@gainsnetwork/sdk 1.0.6-rc4 → 1.1.0
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.
- package/lib/backend/globalTrades/index.js +10 -10
- package/lib/backend/tradingVariables/converter.js +57 -57
- package/lib/backend/tradingVariables/index.js +7 -6
- package/lib/contracts/addresses.js +1 -4
- package/lib/contracts/index.d.ts +1 -1
- package/lib/contracts/index.js +3 -3
- package/lib/contracts/types/generated/GNSMultiCollatDiamond.d.ts +20 -7
- package/lib/contracts/types/generated/factories/GNSMultiCollatDiamond__factory.js +16 -7
- package/lib/contracts/types/generated/factories/GToken__factory.d.ts +0 -7
- package/lib/contracts/types/generated/factories/GToken__factory.js +0 -4
- package/lib/contracts/utils/borrowingFees.js +20 -9
- package/lib/contracts/utils/openTrades.js +20 -11
- package/lib/contracts/utils/pairs.js +21 -12
- package/lib/markets/forex.js +1 -1
- package/lib/markets/leverage/builder.js +2 -2
- package/lib/markets/price/index.d.ts +0 -1
- package/lib/markets/price/index.js +0 -1
- package/lib/markets/price/types.d.ts +0 -27
- package/lib/trade/fees/borrowing/builder.js +3 -2
- package/lib/trade/fees/borrowing/converter.js +1 -5
- package/lib/trade/fees/borrowing/index.js +5 -5
- package/lib/trade/fees/borrowingV2/builder.js +4 -3
- package/lib/trade/fees/borrowingV2/converter.js +1 -1
- package/lib/trade/fees/borrowingV2/fetcher.js +32 -26
- package/lib/trade/fees/borrowingV2/index.js +3 -3
- package/lib/trade/fees/converter.js +22 -22
- package/lib/trade/fees/fundingFees/builder.js +7 -6
- package/lib/trade/fees/fundingFees/converter.js +1 -1
- package/lib/trade/fees/fundingFees/fetcher.js +25 -16
- package/lib/trade/fees/fundingFees/index.js +3 -2
- package/lib/trade/fees/tiers/index.js +2 -1
- package/lib/trade/fees/trading/builder.d.ts +2 -1
- package/lib/trade/fees/trading/builder.js +2 -1
- package/lib/trade/fees/trading/index.js +3 -5
- package/lib/trade/fees/trading/types.d.ts +1 -3
- package/lib/trade/liquidation/builder.js +3 -6
- package/lib/trade/liquidation/index.js +6 -4
- package/lib/trade/liquidation/types.d.ts +2 -7
- package/lib/trade/oiWindows.js +2 -1
- package/lib/trade/pnl/builder.js +2 -1
- package/lib/trade/pnl/converter.js +1 -1
- package/lib/trade/pnl/index.js +9 -4
- package/lib/trade/priceImpact/close/builder.js +2 -1
- package/lib/trade/priceImpact/close/index.js +1 -4
- package/lib/trade/priceImpact/cumulVol/builder.js +10 -18
- package/lib/trade/priceImpact/cumulVol/index.js +16 -21
- package/lib/trade/priceImpact/open/builder.js +2 -1
- package/lib/trade/priceImpact/open/index.js +1 -4
- package/lib/trade/priceImpact/skew/builder.js +3 -2
- package/lib/trade/priceImpact/skew/converter.js +1 -1
- package/lib/trade/priceImpact/skew/fetcher.js +33 -24
- package/package.json +2 -2
- package/lib/contracts/types/generated/GNSBorrowingFeesV6_3_2.d.ts +0 -979
- package/lib/contracts/types/generated/GNSBorrowingFeesV6_3_2.js +0 -2
- package/lib/contracts/types/generated/GNSBorrowingFeesV6_4.d.ts +0 -1058
- package/lib/contracts/types/generated/GNSBorrowingFeesV6_4.js +0 -2
- package/lib/contracts/types/generated/GNSPairInfosV6_1.d.ts +0 -911
- package/lib/contracts/types/generated/GNSPairInfosV6_1.js +0 -2
- package/lib/contracts/types/generated/GNSPairsStorageV6.d.ts +0 -660
- package/lib/contracts/types/generated/GNSPairsStorageV6.js +0 -2
- package/lib/contracts/types/generated/GNSTradingCallbacksV6_3_2.d.ts +0 -806
- package/lib/contracts/types/generated/GNSTradingCallbacksV6_3_2.js +0 -2
- package/lib/contracts/types/generated/GNSTradingCallbacksV6_4.d.ts +0 -821
- package/lib/contracts/types/generated/GNSTradingCallbacksV6_4.js +0 -2
- package/lib/contracts/types/generated/factories/GNSBorrowingFeesV6_3_2__factory.d.ts +0 -88
- package/lib/contracts/types/generated/factories/GNSBorrowingFeesV6_3_2__factory.js +0 -1654
- package/lib/contracts/types/generated/factories/GNSBorrowingFeesV6_4__factory.d.ts +0 -113
- package/lib/contracts/types/generated/factories/GNSBorrowingFeesV6_4__factory.js +0 -1742
- package/lib/contracts/types/generated/factories/GNSPairInfosV6_1__factory.d.ts +0 -98
- package/lib/contracts/types/generated/factories/GNSPairInfosV6_1__factory.js +0 -1485
- package/lib/contracts/types/generated/factories/GNSPairsStorageV6__factory.d.ts +0 -117
- package/lib/contracts/types/generated/factories/GNSPairsStorageV6__factory.js +0 -1265
- package/lib/contracts/types/generated/factories/GNSTradingCallbacksV6_3_2__factory.d.ts +0 -82
- package/lib/contracts/types/generated/factories/GNSTradingCallbacksV6_3_2__factory.js +0 -1273
- package/lib/contracts/types/generated/factories/GNSTradingCallbacksV6_4__factory.d.ts +0 -82
- package/lib/contracts/types/generated/factories/GNSTradingCallbacksV6_4__factory.js +0 -1326
- package/lib/markets/oi/fetcher.d.ts +0 -58
- package/lib/markets/oi/fetcher.js +0 -181
- package/lib/markets/oi/validation.d.ts +0 -80
- package/lib/markets/oi/validation.js +0 -172
- package/lib/markets/price/signedPrices.d.ts +0 -36
- package/lib/markets/price/signedPrices.js +0 -181
- package/lib/trade/effectiveLeverage/builder.d.ts +0 -23
- package/lib/trade/effectiveLeverage/builder.js +0 -30
- package/lib/trade/fees/holdingFees/index.d.ts +0 -46
- package/lib/trade/fees/holdingFees/index.js +0 -105
- package/lib/trade/fees/holdingFees/types.d.ts +0 -23
- package/lib/trade/fees/holdingFees/types.js +0 -5
- package/lib/trade/fees/trading/holdingFees.d.ts +0 -28
- package/lib/trade/fees/trading/holdingFees.js +0 -66
- package/lib/trade/fees/trading/holdingFeesStructured.d.ts +0 -28
- package/lib/trade/fees/trading/holdingFeesStructured.js +0 -66
|
@@ -1,181 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.isValidSignedPricesOrderType = exports.isValidSignedPricesChain = exports.validateSignedPricesPairs = exports.fetchSignedLookbackPricesWithRetry = exports.fetchSignedPricesWithRetry = exports.fetchSignedLookbackPrices = exports.fetchSignedPrices = void 0;
|
|
4
|
-
/* eslint-disable @typescript-eslint/no-unsafe-member-access */
|
|
5
|
-
const types_1 = require("../../contracts/types");
|
|
6
|
-
const trade_1 = require("../../trade");
|
|
7
|
-
const fetchSignedPrices = async (input) => {
|
|
8
|
-
const { minAnswers, timeoutMs, oracles, chain } = {
|
|
9
|
-
minAnswers: input.chain === types_1.ChainId.ARBITRUM_SEPOLIA ? 2 : 3,
|
|
10
|
-
timeoutMs: 1000,
|
|
11
|
-
...input,
|
|
12
|
-
};
|
|
13
|
-
if (!(0, exports.isValidSignedPricesChain)(chain))
|
|
14
|
-
throw new Error(`Invalid chain ${chain}`);
|
|
15
|
-
const { valid, pairs } = (0, exports.validateSignedPricesPairs)(input.pairs);
|
|
16
|
-
if (!valid)
|
|
17
|
-
throw new Error(`Invalid pairs array`);
|
|
18
|
-
return await initiateSignedPricesRequest(oracles, "signPrices", JSON.stringify({ pairs, chain }), minAnswers, timeoutMs);
|
|
19
|
-
};
|
|
20
|
-
exports.fetchSignedPrices = fetchSignedPrices;
|
|
21
|
-
const fetchSignedLookbackPrices = async (input) => {
|
|
22
|
-
const { minAnswers, timeoutMs, oracles, trader, tradeIndex, pair, orderType, currentBlock, fromBlock, chain, } = {
|
|
23
|
-
minAnswers: input.chain === types_1.ChainId.ARBITRUM_SEPOLIA ? 2 : 3,
|
|
24
|
-
timeoutMs: 6000,
|
|
25
|
-
...input,
|
|
26
|
-
};
|
|
27
|
-
if (!(0, exports.isValidSignedPricesChain)(chain))
|
|
28
|
-
throw new Error(`Invalid chain ${chain}`);
|
|
29
|
-
if (!(0, exports.isValidSignedPricesOrderType)(orderType))
|
|
30
|
-
throw new Error(`Invalid orderType ${orderType}`);
|
|
31
|
-
if (isNaN(pair))
|
|
32
|
-
throw new Error(`Invalid pair ${pair}`);
|
|
33
|
-
if (isNaN(tradeIndex) || tradeIndex < 0)
|
|
34
|
-
throw new Error(`Invalid tradeIndex ${tradeIndex}`);
|
|
35
|
-
if (!currentBlock || !fromBlock)
|
|
36
|
-
throw new Error(`Invalid block numbers`);
|
|
37
|
-
return await initiateSignedPricesRequest(oracles, "signLookbackPrices", JSON.stringify({
|
|
38
|
-
trader,
|
|
39
|
-
tradeIndex,
|
|
40
|
-
pair,
|
|
41
|
-
orderType,
|
|
42
|
-
currentBlock,
|
|
43
|
-
fromBlock,
|
|
44
|
-
chain,
|
|
45
|
-
}), minAnswers, timeoutMs);
|
|
46
|
-
};
|
|
47
|
-
exports.fetchSignedLookbackPrices = fetchSignedLookbackPrices;
|
|
48
|
-
// Helper to determine if an error is likely transient
|
|
49
|
-
const isTransientError = (error) => {
|
|
50
|
-
const message = (error instanceof Error ? error.message : String(error))?.toLowerCase() ||
|
|
51
|
-
"";
|
|
52
|
-
return (message.includes("timeout") ||
|
|
53
|
-
message.includes("aborted") ||
|
|
54
|
-
message.includes("not enough valid signed prices") ||
|
|
55
|
-
message.includes("network") ||
|
|
56
|
-
message.includes("fetch failed"));
|
|
57
|
-
};
|
|
58
|
-
// Fetch signed prices with retry logic for transient failures
|
|
59
|
-
const fetchSignedPricesWithRetry = async (input, retryOptions) => {
|
|
60
|
-
const { maxRetries = 2, retryDelayMs = 500, backoffMultiplier = 1.5, } = retryOptions || {};
|
|
61
|
-
let lastError;
|
|
62
|
-
for (let attempt = 0; attempt <= maxRetries; attempt++) {
|
|
63
|
-
try {
|
|
64
|
-
return await (0, exports.fetchSignedPrices)(input);
|
|
65
|
-
}
|
|
66
|
-
catch (error) {
|
|
67
|
-
lastError = error;
|
|
68
|
-
// Don't retry non-transient errors or if we're out of retries
|
|
69
|
-
if (attempt === maxRetries || !isTransientError(error)) {
|
|
70
|
-
throw error;
|
|
71
|
-
}
|
|
72
|
-
// Wait with exponential backoff before retry
|
|
73
|
-
const delay = Math.floor(retryDelayMs * Math.pow(backoffMultiplier, attempt));
|
|
74
|
-
await new Promise(resolve => setTimeout(resolve, delay));
|
|
75
|
-
}
|
|
76
|
-
}
|
|
77
|
-
throw lastError;
|
|
78
|
-
};
|
|
79
|
-
exports.fetchSignedPricesWithRetry = fetchSignedPricesWithRetry;
|
|
80
|
-
// Fetch lookback prices with retry logic
|
|
81
|
-
const fetchSignedLookbackPricesWithRetry = async (input, retryOptions) => {
|
|
82
|
-
const { maxRetries = 2, retryDelayMs = 1000, backoffMultiplier = 2, } = retryOptions || {};
|
|
83
|
-
let lastError;
|
|
84
|
-
for (let attempt = 0; attempt <= maxRetries; attempt++) {
|
|
85
|
-
try {
|
|
86
|
-
return await (0, exports.fetchSignedLookbackPrices)(input);
|
|
87
|
-
}
|
|
88
|
-
catch (error) {
|
|
89
|
-
lastError = error;
|
|
90
|
-
// Don't retry non-transient errors or if we're out of retries
|
|
91
|
-
if (attempt === maxRetries || !isTransientError(error)) {
|
|
92
|
-
throw error;
|
|
93
|
-
}
|
|
94
|
-
// Wait with exponential backoff before retry
|
|
95
|
-
const delay = Math.floor(retryDelayMs * Math.pow(backoffMultiplier, attempt));
|
|
96
|
-
await new Promise(resolve => setTimeout(resolve, delay));
|
|
97
|
-
}
|
|
98
|
-
}
|
|
99
|
-
throw lastError;
|
|
100
|
-
};
|
|
101
|
-
exports.fetchSignedLookbackPricesWithRetry = fetchSignedLookbackPricesWithRetry;
|
|
102
|
-
// @todo optional filtering to minAnswers best responses
|
|
103
|
-
const initiateSignedPricesRequest = async (oracles, request, requestBody, minAnswers, timeoutMs) => {
|
|
104
|
-
try {
|
|
105
|
-
// Fetch signed prices from all oracles in parallel
|
|
106
|
-
const signedPrices = await Promise.allSettled(oracles.map(oracle => _getSignedPricesFromSigner(`${oracle.url}/${request}`, requestBody, oracle?.key, timeoutMs)));
|
|
107
|
-
// Filter out failed requests and null responses, then sort by signerId
|
|
108
|
-
const successfulResponses = signedPrices.filter(res => res.status === "fulfilled" && res.value !== null // Filter out failed or null responses
|
|
109
|
-
)
|
|
110
|
-
// Extract `value`
|
|
111
|
-
.map((res) => res.value)
|
|
112
|
-
// Sort by signerId, contracts expect signerId ascending
|
|
113
|
-
.sort((a, b) => a.signedData.signerId - b.signedData.signerId);
|
|
114
|
-
// Ensure we have at least `minAnswers` valid responses
|
|
115
|
-
if (successfulResponses.length < minAnswers) {
|
|
116
|
-
throw new Error(`Not enough valid signed prices. Wanted ${minAnswers} but got ${successfulResponses.length}`);
|
|
117
|
-
}
|
|
118
|
-
return successfulResponses;
|
|
119
|
-
}
|
|
120
|
-
catch (e) {
|
|
121
|
-
console.error("Error processing signed prices", e);
|
|
122
|
-
throw e;
|
|
123
|
-
}
|
|
124
|
-
};
|
|
125
|
-
const _getSignedPricesFromSigner = async (url, requestBody, authKey, timeoutMs) => {
|
|
126
|
-
try {
|
|
127
|
-
const controller = new AbortController();
|
|
128
|
-
const timeout = setTimeout(() => {
|
|
129
|
-
controller.abort();
|
|
130
|
-
}, timeoutMs || 2000);
|
|
131
|
-
const response = await fetch(`${url}`, {
|
|
132
|
-
method: "POST",
|
|
133
|
-
headers: {
|
|
134
|
-
"Content-Type": "application/json",
|
|
135
|
-
"x-api-key": authKey || "",
|
|
136
|
-
},
|
|
137
|
-
body: requestBody,
|
|
138
|
-
signal: controller.signal,
|
|
139
|
-
});
|
|
140
|
-
clearTimeout(timeout);
|
|
141
|
-
if (!response.ok) {
|
|
142
|
-
throw new Error(`Failed to fetch signed prices from ${url}: ${response.statusText}`);
|
|
143
|
-
}
|
|
144
|
-
return (await response.json());
|
|
145
|
-
}
|
|
146
|
-
catch (error) {
|
|
147
|
-
console.error(`Error fetching signed prices from ${url}:`, {
|
|
148
|
-
error: error?.message,
|
|
149
|
-
});
|
|
150
|
-
return null;
|
|
151
|
-
}
|
|
152
|
-
};
|
|
153
|
-
const validateSignedPricesPairs = (pairs) => {
|
|
154
|
-
if (!Array.isArray(pairs) || pairs?.length === 0 || pairs.some(p => isNaN(p)))
|
|
155
|
-
return { valid: false, pairs: [] };
|
|
156
|
-
// Pairs must always be in ascending order
|
|
157
|
-
return { valid: true, pairs: [...new Set(pairs)].sort((a, b) => a - b) };
|
|
158
|
-
};
|
|
159
|
-
exports.validateSignedPricesPairs = validateSignedPricesPairs;
|
|
160
|
-
const isValidSignedPricesChain = (chainId) => {
|
|
161
|
-
return (!isNaN(chainId) &&
|
|
162
|
-
[
|
|
163
|
-
types_1.ChainId.POLYGON,
|
|
164
|
-
types_1.ChainId.BASE,
|
|
165
|
-
types_1.ChainId.ARBITRUM,
|
|
166
|
-
types_1.ChainId.ARBITRUM_SEPOLIA,
|
|
167
|
-
types_1.ChainId.APECHAIN,
|
|
168
|
-
].includes(chainId));
|
|
169
|
-
};
|
|
170
|
-
exports.isValidSignedPricesChain = isValidSignedPricesChain;
|
|
171
|
-
const isValidSignedPricesOrderType = (orderType) => {
|
|
172
|
-
return (!isNaN(orderType) &&
|
|
173
|
-
[
|
|
174
|
-
trade_1.PendingOrderType.LIMIT_OPEN,
|
|
175
|
-
trade_1.PendingOrderType.STOP_OPEN,
|
|
176
|
-
trade_1.PendingOrderType.TP_CLOSE,
|
|
177
|
-
trade_1.PendingOrderType.SL_CLOSE,
|
|
178
|
-
trade_1.PendingOrderType.LIQ_CLOSE,
|
|
179
|
-
].includes(orderType));
|
|
180
|
-
};
|
|
181
|
-
exports.isValidSignedPricesOrderType = isValidSignedPricesOrderType;
|
|
@@ -1,23 +0,0 @@
|
|
|
1
|
-
import { GlobalTradingVariablesType } from "../../backend/tradingVariables/types";
|
|
2
|
-
import { TradeInfo } from "..";
|
|
3
|
-
import { TradeEffectiveLeverageContext } from "./types";
|
|
4
|
-
/**
|
|
5
|
-
* @dev Builds a complete context for effective leverage calculations
|
|
6
|
-
* @dev Uses the closing price impact context builder as a sub-context
|
|
7
|
-
* @param globalTradingVariables The transformed global trading variables from backend
|
|
8
|
-
* @param collateralIndex The collateral index (1-based)
|
|
9
|
-
* @param pairIndex The pair index
|
|
10
|
-
* @param tradeInfo Trade information including createdBlock
|
|
11
|
-
* @param additionalParams Additional parameters for price impact calculations
|
|
12
|
-
* @returns Complete context ready for getTradeNewEffectiveLeverage
|
|
13
|
-
*/
|
|
14
|
-
export declare const buildTradeEffectiveLeverageContext: (globalTradingVariables: GlobalTradingVariablesType, collateralIndex: number, pairIndex: number, tradeInfo: TradeInfo, additionalParams: {
|
|
15
|
-
currentBlock: number;
|
|
16
|
-
contractsVersion?: number;
|
|
17
|
-
isPnlPositive?: boolean;
|
|
18
|
-
userPriceImpact?: {
|
|
19
|
-
cumulVolPriceImpactMultiplier: number;
|
|
20
|
-
fixedSpreadP: number;
|
|
21
|
-
};
|
|
22
|
-
protectionCloseFactorWhitelist?: boolean;
|
|
23
|
-
}) => TradeEffectiveLeverageContext | undefined;
|
|
@@ -1,30 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.buildTradeEffectiveLeverageContext = void 0;
|
|
4
|
-
const __1 = require("..");
|
|
5
|
-
/**
|
|
6
|
-
* @dev Builds a complete context for effective leverage calculations
|
|
7
|
-
* @dev Uses the closing price impact context builder as a sub-context
|
|
8
|
-
* @param globalTradingVariables The transformed global trading variables from backend
|
|
9
|
-
* @param collateralIndex The collateral index (1-based)
|
|
10
|
-
* @param pairIndex The pair index
|
|
11
|
-
* @param tradeInfo Trade information including createdBlock
|
|
12
|
-
* @param additionalParams Additional parameters for price impact calculations
|
|
13
|
-
* @returns Complete context ready for getTradeNewEffectiveLeverage
|
|
14
|
-
*/
|
|
15
|
-
const buildTradeEffectiveLeverageContext = (globalTradingVariables, collateralIndex, pairIndex, tradeInfo, additionalParams) => {
|
|
16
|
-
var _a;
|
|
17
|
-
// Build the closing price impact context which we'll use for PnL calculations
|
|
18
|
-
const closingPriceImpactContext = (0, __1.buildTradeClosingPriceImpactContext)(globalTradingVariables, collateralIndex, pairIndex, tradeInfo, additionalParams);
|
|
19
|
-
if (!closingPriceImpactContext) {
|
|
20
|
-
return undefined;
|
|
21
|
-
}
|
|
22
|
-
// Extract base spread from pairs data
|
|
23
|
-
const pairs = globalTradingVariables.pairs;
|
|
24
|
-
const baseSpreadP = ((_a = pairs === null || pairs === void 0 ? void 0 : pairs[pairIndex]) === null || _a === void 0 ? void 0 : _a.spreadP) || 0;
|
|
25
|
-
return {
|
|
26
|
-
closingPriceImpactContext,
|
|
27
|
-
baseSpreadP,
|
|
28
|
-
};
|
|
29
|
-
};
|
|
30
|
-
exports.buildTradeEffectiveLeverageContext = buildTradeEffectiveLeverageContext;
|
|
@@ -1,46 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* @dev Holding fees calculation utilities for v10+ markets
|
|
3
|
-
* @dev Combines funding fees and borrowing v2 fees
|
|
4
|
-
*/
|
|
5
|
-
import { FundingFeeParams, PairFundingFeeData, PairOiAfterV10 } from "../fundingFees/types";
|
|
6
|
-
import { BorrowingFeeParams, PairBorrowingFeeData } from "../borrowingV2/types";
|
|
7
|
-
export type HoldingFeeRates = {
|
|
8
|
-
longHourlyRate: number;
|
|
9
|
-
shortHourlyRate: number;
|
|
10
|
-
fundingFeeLongHourlyRate: number;
|
|
11
|
-
fundingFeeShortHourlyRate: number;
|
|
12
|
-
borrowingFeeHourlyRate: number;
|
|
13
|
-
currentFundingRatePerSecondP: number;
|
|
14
|
-
currentBorrowingRatePerSecondP: number;
|
|
15
|
-
};
|
|
16
|
-
export type GetPairHoldingFeeRatesInput = {
|
|
17
|
-
fundingParams: FundingFeeParams;
|
|
18
|
-
fundingData: PairFundingFeeData;
|
|
19
|
-
pairOiToken: PairOiAfterV10;
|
|
20
|
-
netExposureToken: number;
|
|
21
|
-
netExposureUsd: number;
|
|
22
|
-
borrowingParams: BorrowingFeeParams | null;
|
|
23
|
-
borrowingData: PairBorrowingFeeData | null;
|
|
24
|
-
currentPairPrice: number;
|
|
25
|
-
currentTimestamp: number;
|
|
26
|
-
};
|
|
27
|
-
/**
|
|
28
|
-
* @dev Calculates current holding fee rates per hour for display
|
|
29
|
-
* @param input Input parameters for calculation
|
|
30
|
-
* @returns Holding fee rates per hour with breakdown
|
|
31
|
-
*/
|
|
32
|
-
export declare const getPairHoldingFeeRates: (input: GetPairHoldingFeeRatesInput) => HoldingFeeRates;
|
|
33
|
-
/**
|
|
34
|
-
* @dev Converts a per-second rate to annual percentage rate (APR)
|
|
35
|
-
* @param ratePerSecond Rate per second
|
|
36
|
-
* @returns Annual percentage rate
|
|
37
|
-
*/
|
|
38
|
-
export declare const convertRatePerSecondToAPR: (ratePerSecond: number) => number;
|
|
39
|
-
/**
|
|
40
|
-
* @dev Formats a holding fee rate for display
|
|
41
|
-
* @param rate Hourly rate (can be negative)
|
|
42
|
-
* @param decimals Number of decimal places
|
|
43
|
-
* @returns Formatted string with sign
|
|
44
|
-
*/
|
|
45
|
-
export declare const formatHoldingFeeRate: (rate: number, decimals?: number) => string;
|
|
46
|
-
export * as HoldingFees from "./types";
|
|
@@ -1,105 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
/**
|
|
3
|
-
* @dev Holding fees calculation utilities for v10+ markets
|
|
4
|
-
* @dev Combines funding fees and borrowing v2 fees
|
|
5
|
-
*/
|
|
6
|
-
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
7
|
-
if (k2 === undefined) k2 = k;
|
|
8
|
-
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
9
|
-
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
10
|
-
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
11
|
-
}
|
|
12
|
-
Object.defineProperty(o, k2, desc);
|
|
13
|
-
}) : (function(o, m, k, k2) {
|
|
14
|
-
if (k2 === undefined) k2 = k;
|
|
15
|
-
o[k2] = m[k];
|
|
16
|
-
}));
|
|
17
|
-
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
18
|
-
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
19
|
-
}) : function(o, v) {
|
|
20
|
-
o["default"] = v;
|
|
21
|
-
});
|
|
22
|
-
var __importStar = (this && this.__importStar) || function (mod) {
|
|
23
|
-
if (mod && mod.__esModule) return mod;
|
|
24
|
-
var result = {};
|
|
25
|
-
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
|
|
26
|
-
__setModuleDefault(result, mod);
|
|
27
|
-
return result;
|
|
28
|
-
};
|
|
29
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
30
|
-
exports.HoldingFees = exports.formatHoldingFeeRate = exports.convertRatePerSecondToAPR = exports.getPairHoldingFeeRates = void 0;
|
|
31
|
-
const fundingFees_1 = require("../fundingFees");
|
|
32
|
-
const SECONDS_PER_HOUR = 3600;
|
|
33
|
-
const SECONDS_PER_YEAR = 365 * 24 * 60 * 60;
|
|
34
|
-
const PERCENTAGE_PRECISION = 100;
|
|
35
|
-
/**
|
|
36
|
-
* @dev Calculates current holding fee rates per hour for display
|
|
37
|
-
* @param input Input parameters for calculation
|
|
38
|
-
* @returns Holding fee rates per hour with breakdown
|
|
39
|
-
*/
|
|
40
|
-
const getPairHoldingFeeRates = (input) => {
|
|
41
|
-
const { fundingParams, fundingData, pairOiToken, netExposureToken, netExposureUsd, borrowingParams, borrowingData, currentPairPrice, currentTimestamp, } = input;
|
|
42
|
-
// Calculate funding fee rates
|
|
43
|
-
let fundingFeeLongHourlyRate = 0;
|
|
44
|
-
let fundingFeeShortHourlyRate = 0;
|
|
45
|
-
let currentFundingRatePerSecondP = 0;
|
|
46
|
-
if (fundingParams.fundingFeesEnabled) {
|
|
47
|
-
// Get current funding rate
|
|
48
|
-
const pendingFunding = (0, fundingFees_1.getPairPendingAccFundingFees)(fundingParams, fundingData, currentPairPrice, pairOiToken, netExposureToken, netExposureUsd, currentTimestamp);
|
|
49
|
-
currentFundingRatePerSecondP = pendingFunding.currentFundingRatePerSecondP;
|
|
50
|
-
// Get APR multipliers
|
|
51
|
-
const { longAprMultiplier, shortAprMultiplier } = (0, fundingFees_1.getLongShortAprMultiplier)(currentFundingRatePerSecondP, pairOiToken.oiLongToken, pairOiToken.oiShortToken, fundingParams.aprMultiplierEnabled);
|
|
52
|
-
// Calculate hourly rates
|
|
53
|
-
// Funding rate * seconds per hour * current price * APR multiplier / 100
|
|
54
|
-
const baseHourlyRate = (currentFundingRatePerSecondP * SECONDS_PER_HOUR * currentPairPrice) /
|
|
55
|
-
PERCENTAGE_PRECISION;
|
|
56
|
-
// Long side pays when rate is positive, earns when negative
|
|
57
|
-
fundingFeeLongHourlyRate = baseHourlyRate * longAprMultiplier;
|
|
58
|
-
// Short side is opposite
|
|
59
|
-
fundingFeeShortHourlyRate = -baseHourlyRate * shortAprMultiplier;
|
|
60
|
-
}
|
|
61
|
-
// Calculate borrowing v2 rates
|
|
62
|
-
let borrowingFeeHourlyRate = 0;
|
|
63
|
-
let currentBorrowingRatePerSecondP = 0;
|
|
64
|
-
if (borrowingParams && borrowingData) {
|
|
65
|
-
currentBorrowingRatePerSecondP = borrowingParams.borrowingRatePerSecondP;
|
|
66
|
-
// Borrowing rate * seconds per hour * current price / 100
|
|
67
|
-
borrowingFeeHourlyRate =
|
|
68
|
-
(currentBorrowingRatePerSecondP * SECONDS_PER_HOUR * currentPairPrice) /
|
|
69
|
-
PERCENTAGE_PRECISION;
|
|
70
|
-
}
|
|
71
|
-
// Total holding fees (funding can be negative/positive, borrowing always positive cost)
|
|
72
|
-
const longHourlyRate = fundingFeeLongHourlyRate + borrowingFeeHourlyRate;
|
|
73
|
-
const shortHourlyRate = fundingFeeShortHourlyRate + borrowingFeeHourlyRate;
|
|
74
|
-
return {
|
|
75
|
-
longHourlyRate,
|
|
76
|
-
shortHourlyRate,
|
|
77
|
-
fundingFeeLongHourlyRate,
|
|
78
|
-
fundingFeeShortHourlyRate,
|
|
79
|
-
borrowingFeeHourlyRate,
|
|
80
|
-
currentFundingRatePerSecondP,
|
|
81
|
-
currentBorrowingRatePerSecondP,
|
|
82
|
-
};
|
|
83
|
-
};
|
|
84
|
-
exports.getPairHoldingFeeRates = getPairHoldingFeeRates;
|
|
85
|
-
/**
|
|
86
|
-
* @dev Converts a per-second rate to annual percentage rate (APR)
|
|
87
|
-
* @param ratePerSecond Rate per second
|
|
88
|
-
* @returns Annual percentage rate
|
|
89
|
-
*/
|
|
90
|
-
const convertRatePerSecondToAPR = (ratePerSecond) => {
|
|
91
|
-
return ratePerSecond * SECONDS_PER_YEAR * PERCENTAGE_PRECISION;
|
|
92
|
-
};
|
|
93
|
-
exports.convertRatePerSecondToAPR = convertRatePerSecondToAPR;
|
|
94
|
-
/**
|
|
95
|
-
* @dev Formats a holding fee rate for display
|
|
96
|
-
* @param rate Hourly rate (can be negative)
|
|
97
|
-
* @param decimals Number of decimal places
|
|
98
|
-
* @returns Formatted string with sign
|
|
99
|
-
*/
|
|
100
|
-
const formatHoldingFeeRate = (rate, decimals = 4) => {
|
|
101
|
-
const sign = rate > 0 ? "+" : "";
|
|
102
|
-
return `${sign}${rate.toFixed(decimals)}%`;
|
|
103
|
-
};
|
|
104
|
-
exports.formatHoldingFeeRate = formatHoldingFeeRate;
|
|
105
|
-
exports.HoldingFees = __importStar(require("./types"));
|
|
@@ -1,23 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* @dev Type definitions for holding fees (funding + borrowing v2)
|
|
3
|
-
*/
|
|
4
|
-
export interface HoldingFeeRates {
|
|
5
|
-
longHourlyRate: number;
|
|
6
|
-
shortHourlyRate: number;
|
|
7
|
-
fundingFeeLongHourlyRate: number;
|
|
8
|
-
fundingFeeShortHourlyRate: number;
|
|
9
|
-
borrowingFeeHourlyRate: number;
|
|
10
|
-
currentFundingRatePerSecondP: number;
|
|
11
|
-
currentBorrowingRatePerSecondP: number;
|
|
12
|
-
}
|
|
13
|
-
export interface GetPairHoldingFeeRatesInput {
|
|
14
|
-
fundingParams: import("../fundingFees/types").FundingFeeParams;
|
|
15
|
-
fundingData: import("../fundingFees/types").PairFundingFeeData;
|
|
16
|
-
pairOiToken: import("../fundingFees/types").PairOiAfterV10;
|
|
17
|
-
netExposureToken: number;
|
|
18
|
-
netExposureUsd: number;
|
|
19
|
-
borrowingParams: import("../borrowingV2/types").BorrowingFeeParams | null;
|
|
20
|
-
borrowingData: import("../borrowingV2/types").PairBorrowingFeeData | null;
|
|
21
|
-
currentPairPrice: number;
|
|
22
|
-
currentTimestamp: number;
|
|
23
|
-
}
|
|
@@ -1,28 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* @dev Holding fees calculation for structured contexts
|
|
3
|
-
*/
|
|
4
|
-
import { Trade, TradeInfo, TradeFeesData } from "../../types";
|
|
5
|
-
import { TradeHoldingFees } from "./types";
|
|
6
|
-
import { ContractsVersion } from "../../../contracts/types";
|
|
7
|
-
import type { BorrowingV1SubContext, BorrowingV2SubContext, FundingFeesSubContext } from "../../pnl";
|
|
8
|
-
/**
|
|
9
|
-
* @dev Context for holding fees calculation with structured sub-contexts
|
|
10
|
-
*/
|
|
11
|
-
export type GetStructuredHoldingFeesContext = {
|
|
12
|
-
contractsVersion: ContractsVersion;
|
|
13
|
-
currentTimestamp: number;
|
|
14
|
-
collateralPriceUsd: number;
|
|
15
|
-
borrowingV1?: BorrowingV1SubContext;
|
|
16
|
-
borrowingV2?: BorrowingV2SubContext;
|
|
17
|
-
funding?: FundingFeesSubContext;
|
|
18
|
-
};
|
|
19
|
-
/**
|
|
20
|
-
* @dev Calculates total holding fees using structured context
|
|
21
|
-
* @param trade The trade to calculate fees for
|
|
22
|
-
* @param tradeInfo Trade info containing contracts version
|
|
23
|
-
* @param tradeFeesData Trade fees data containing initial acc fees
|
|
24
|
-
* @param currentPairPrice Current pair price
|
|
25
|
-
* @param context Structured context with sub-contexts for each fee type
|
|
26
|
-
* @returns Object containing all holding fee components
|
|
27
|
-
*/
|
|
28
|
-
export declare const getTradePendingHoldingFeesCollateralStructured: (trade: Trade, tradeInfo: TradeInfo, tradeFeesData: TradeFeesData, currentPairPrice: number, context: GetStructuredHoldingFeesContext) => TradeHoldingFees;
|
|
@@ -1,66 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
/**
|
|
3
|
-
* @dev Holding fees calculation for structured contexts
|
|
4
|
-
*/
|
|
5
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
-
exports.getTradePendingHoldingFeesCollateralStructured = void 0;
|
|
7
|
-
const types_1 = require("../../../contracts/types");
|
|
8
|
-
const borrowing_1 = require("../borrowing");
|
|
9
|
-
const borrowingV2_1 = require("../borrowingV2");
|
|
10
|
-
const pairContext_1 = require("../fundingFees/pairContext");
|
|
11
|
-
/**
|
|
12
|
-
* @dev Calculates total holding fees using structured context
|
|
13
|
-
* @param trade The trade to calculate fees for
|
|
14
|
-
* @param tradeInfo Trade info containing contracts version
|
|
15
|
-
* @param tradeFeesData Trade fees data containing initial acc fees
|
|
16
|
-
* @param currentPairPrice Current pair price
|
|
17
|
-
* @param context Structured context with sub-contexts for each fee type
|
|
18
|
-
* @returns Object containing all holding fee components
|
|
19
|
-
*/
|
|
20
|
-
const getTradePendingHoldingFeesCollateralStructured = (trade, tradeInfo, tradeFeesData, currentPairPrice, context) => {
|
|
21
|
-
const positionSizeCollateral = trade.collateralAmount * trade.leverage;
|
|
22
|
-
// Calculate funding fees (v10+ only)
|
|
23
|
-
let fundingFeeCollateral = 0;
|
|
24
|
-
if (context.contractsVersion >= types_1.ContractsVersion.V10 &&
|
|
25
|
-
context.funding &&
|
|
26
|
-
tradeFeesData.initialAccFundingFeeP !== undefined) {
|
|
27
|
-
fundingFeeCollateral = (0, pairContext_1.getPairTradeFundingFeesCollateral)({
|
|
28
|
-
positionSizeCollateral,
|
|
29
|
-
openPrice: trade.openPrice,
|
|
30
|
-
long: trade.long,
|
|
31
|
-
currentPairPrice,
|
|
32
|
-
initialAccFundingFeeP: tradeFeesData.initialAccFundingFeeP,
|
|
33
|
-
}, context.funding // TODO: Fix types once funding types are properly imported
|
|
34
|
-
);
|
|
35
|
-
}
|
|
36
|
-
// Calculate borrowing fees v2
|
|
37
|
-
let borrowingFeeCollateral = 0;
|
|
38
|
-
if (context.borrowingV2 && tradeFeesData.initialAccBorrowingFeeP !== undefined) {
|
|
39
|
-
borrowingFeeCollateral = (0, borrowingV2_1.getPairTradeBorrowingFeesCollateral)({
|
|
40
|
-
positionSizeCollateral,
|
|
41
|
-
openPrice: trade.openPrice,
|
|
42
|
-
currentPairPrice,
|
|
43
|
-
initialAccBorrowingFeeP: tradeFeesData.initialAccBorrowingFeeP,
|
|
44
|
-
currentTimestamp: context.currentTimestamp,
|
|
45
|
-
}, context.borrowingV2);
|
|
46
|
-
}
|
|
47
|
-
// Calculate v1 borrowing fees (some markets use v1 indefinitely)
|
|
48
|
-
let borrowingFeeCollateral_old = 0;
|
|
49
|
-
if (context.borrowingV1) {
|
|
50
|
-
borrowingFeeCollateral_old = (0, borrowing_1.getPairBorrowingFee)(positionSizeCollateral, trade.long, context.borrowingV1.initialAccFees || { accPairFee: 0, accGroupFee: 0, block: 0 }, {
|
|
51
|
-
currentBlock: context.borrowingV1.currentBlock,
|
|
52
|
-
group: context.borrowingV1.group,
|
|
53
|
-
pair: context.borrowingV1.pair,
|
|
54
|
-
collateralPriceUsd: context.collateralPriceUsd,
|
|
55
|
-
});
|
|
56
|
-
}
|
|
57
|
-
return {
|
|
58
|
-
fundingFeeCollateral,
|
|
59
|
-
borrowingFeeCollateral,
|
|
60
|
-
borrowingFeeCollateral_old,
|
|
61
|
-
totalFeeCollateral: fundingFeeCollateral +
|
|
62
|
-
borrowingFeeCollateral +
|
|
63
|
-
borrowingFeeCollateral_old,
|
|
64
|
-
};
|
|
65
|
-
};
|
|
66
|
-
exports.getTradePendingHoldingFeesCollateralStructured = getTradePendingHoldingFeesCollateralStructured;
|
|
@@ -1,28 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* @dev Holding fees calculation for structured contexts
|
|
3
|
-
*/
|
|
4
|
-
import { Trade, TradeInfo, TradeFeesData } from "../../types";
|
|
5
|
-
import { TradeHoldingFees } from "./types";
|
|
6
|
-
import { ContractsVersion } from "../../../contracts/types";
|
|
7
|
-
import type { BorrowingV1SubContext, BorrowingV2SubContext, FundingFeesSubContext } from "../../pnl";
|
|
8
|
-
/**
|
|
9
|
-
* @dev Context for holding fees calculation with structured sub-contexts
|
|
10
|
-
*/
|
|
11
|
-
export type GetStructuredHoldingFeesContext = {
|
|
12
|
-
contractsVersion: ContractsVersion;
|
|
13
|
-
currentTimestamp: number;
|
|
14
|
-
collateralPriceUsd: number;
|
|
15
|
-
borrowingV1?: BorrowingV1SubContext;
|
|
16
|
-
borrowingV2?: BorrowingV2SubContext;
|
|
17
|
-
funding?: FundingFeesSubContext;
|
|
18
|
-
};
|
|
19
|
-
/**
|
|
20
|
-
* @dev Calculates total holding fees using structured context
|
|
21
|
-
* @param trade The trade to calculate fees for
|
|
22
|
-
* @param tradeInfo Trade info containing contracts version
|
|
23
|
-
* @param tradeFeesData Trade fees data containing initial acc fees
|
|
24
|
-
* @param currentPairPrice Current pair price
|
|
25
|
-
* @param context Structured context with sub-contexts for each fee type
|
|
26
|
-
* @returns Object containing all holding fee components
|
|
27
|
-
*/
|
|
28
|
-
export declare const getTradePendingHoldingFeesCollateralStructured: (trade: Trade, tradeInfo: TradeInfo, tradeFeesData: TradeFeesData, currentPairPrice: number, context: GetStructuredHoldingFeesContext) => TradeHoldingFees;
|
|
@@ -1,66 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
/**
|
|
3
|
-
* @dev Holding fees calculation for structured contexts
|
|
4
|
-
*/
|
|
5
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
-
exports.getTradePendingHoldingFeesCollateralStructured = void 0;
|
|
7
|
-
const types_1 = require("../../../contracts/types");
|
|
8
|
-
const borrowing_1 = require("../borrowing");
|
|
9
|
-
const borrowingV2_1 = require("../borrowingV2");
|
|
10
|
-
const fundingFees_1 = require("../fundingFees");
|
|
11
|
-
/**
|
|
12
|
-
* @dev Calculates total holding fees using structured context
|
|
13
|
-
* @param trade The trade to calculate fees for
|
|
14
|
-
* @param tradeInfo Trade info containing contracts version
|
|
15
|
-
* @param tradeFeesData Trade fees data containing initial acc fees
|
|
16
|
-
* @param currentPairPrice Current pair price
|
|
17
|
-
* @param context Structured context with sub-contexts for each fee type
|
|
18
|
-
* @returns Object containing all holding fee components
|
|
19
|
-
*/
|
|
20
|
-
const getTradePendingHoldingFeesCollateralStructured = (trade, tradeInfo, tradeFeesData, currentPairPrice, context) => {
|
|
21
|
-
const positionSizeCollateral = trade.collateralAmount * trade.leverage;
|
|
22
|
-
// Calculate funding fees (v10+ only)
|
|
23
|
-
let fundingFeeCollateral = 0;
|
|
24
|
-
if (context.contractsVersion >= types_1.ContractsVersion.V10 &&
|
|
25
|
-
context.funding &&
|
|
26
|
-
tradeFeesData.initialAccFundingFeeP !== undefined) {
|
|
27
|
-
fundingFeeCollateral = (0, fundingFees_1.getTradeFundingFeesCollateral)(trade, tradeInfo, tradeFeesData, currentPairPrice, Object.assign(Object.assign({}, context.funding), { currentTimestamp: context.currentTimestamp }) // TODO: Fix types once funding types are properly imported
|
|
28
|
-
);
|
|
29
|
-
}
|
|
30
|
-
// Calculate borrowing fees v2
|
|
31
|
-
let borrowingFeeCollateral = 0;
|
|
32
|
-
if (context.borrowingV2 &&
|
|
33
|
-
tradeFeesData.initialAccBorrowingFeeP !== undefined) {
|
|
34
|
-
borrowingFeeCollateral = (0, borrowingV2_1.getTradeBorrowingFeesCollateral)({
|
|
35
|
-
positionSizeCollateral,
|
|
36
|
-
openPrice: trade.openPrice,
|
|
37
|
-
currentPairPrice,
|
|
38
|
-
initialAccBorrowingFeeP: tradeFeesData.initialAccBorrowingFeeP,
|
|
39
|
-
currentTimestamp: context.currentTimestamp,
|
|
40
|
-
}, context.borrowingV2);
|
|
41
|
-
}
|
|
42
|
-
// Calculate v1 borrowing fees (some markets use v1 indefinitely)
|
|
43
|
-
let borrowingFeeCollateral_old = 0;
|
|
44
|
-
if (context.borrowingV1) {
|
|
45
|
-
borrowingFeeCollateral_old = (0, borrowing_1.getBorrowingFee)(positionSizeCollateral, undefined, // pairIndex not needed for pair-specific context
|
|
46
|
-
trade.long, context.borrowingV1.initialAccFees || {
|
|
47
|
-
accPairFee: 0,
|
|
48
|
-
accGroupFee: 0,
|
|
49
|
-
block: 0,
|
|
50
|
-
}, {
|
|
51
|
-
currentBlock: context.borrowingV1.currentBlock,
|
|
52
|
-
group: context.borrowingV1.group,
|
|
53
|
-
pair: context.borrowingV1.pair,
|
|
54
|
-
collateralPriceUsd: context.collateralPriceUsd,
|
|
55
|
-
});
|
|
56
|
-
}
|
|
57
|
-
return {
|
|
58
|
-
fundingFeeCollateral,
|
|
59
|
-
borrowingFeeCollateral,
|
|
60
|
-
borrowingFeeCollateral_old,
|
|
61
|
-
totalFeeCollateral: fundingFeeCollateral +
|
|
62
|
-
borrowingFeeCollateral +
|
|
63
|
-
borrowingFeeCollateral_old,
|
|
64
|
-
};
|
|
65
|
-
};
|
|
66
|
-
exports.getTradePendingHoldingFeesCollateralStructured = getTradePendingHoldingFeesCollateralStructured;
|