@gmx-io/sdk 1.8.0 → 1.9.1
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/README.md +1 -1
- package/build/cjs/scripts/subsquid-codegen.js +1 -1
- package/build/cjs/src/abis/ArbSys.js +11 -0
- package/build/cjs/src/abis/index.js +2 -0
- package/build/cjs/src/clients/v1/testUtil.js +1 -1
- package/build/cjs/src/clients/v2/index.js +8 -1
- package/build/cjs/src/codegen/prebuilt/hashedKinkModelMarketRatesKeys.json +16 -88
- package/build/cjs/src/codegen/prebuilt/hashedMarketConfigKeys.json +136 -748
- package/build/cjs/src/codegen/prebuilt/hashedMarketValuesKeys.json +30 -165
- package/build/cjs/src/configs/__tests__/markets.spec.js +1 -16
- package/build/cjs/src/configs/api.js +10 -1
- package/build/cjs/src/configs/contracts.js +2 -0
- package/build/cjs/src/configs/dataStore.js +13 -3
- package/build/cjs/src/configs/express.js +1 -0
- package/build/cjs/src/configs/markets.js +14 -77
- package/build/cjs/src/configs/tokens.js +22 -90
- package/build/cjs/src/test/fixtures/arbitrumMarkets.json +0 -72
- package/build/cjs/src/test/mock.js +12 -1
- package/build/cjs/src/utils/__tests__/fees.spec.js +36 -0
- package/build/cjs/src/utils/__tests__/markets.spec.js +233 -0
- package/build/cjs/src/utils/__tests__/positionPnlCap.spec.js +30 -3
- package/build/cjs/src/utils/__tests__/positions.spec.js +5 -5
- package/build/cjs/src/utils/__tests__/prices.spec.js +97 -0
- package/build/cjs/src/utils/express/utils/gelatoRelayUtils.js +2 -0
- package/build/cjs/src/utils/express/utils/gmxRelayUtils.js +145 -0
- package/build/cjs/src/utils/express/utils/gmxRelayUtils.spec.js +163 -0
- package/build/cjs/src/utils/express/utils/index.js +1 -0
- package/build/cjs/src/utils/fees/index.js +8 -5
- package/build/cjs/src/utils/fees/priceImpact.js +4 -9
- package/build/cjs/src/utils/markets/utils.js +57 -1
- package/build/cjs/src/utils/numbers/index.js +1 -0
- package/build/cjs/src/utils/numbers/prbMath.js +154 -0
- package/build/cjs/src/utils/positions/utils.js +66 -43
- package/build/cjs/src/utils/prices/utils.js +28 -1
- package/build/cjs/src/utils/stats/__tests__/api.spec.js +100 -0
- package/build/cjs/src/utils/stats/api.js +32 -0
- package/build/cjs/src/utils/stats/types.js +4 -0
- package/build/cjs/src/utils/trade/__tests__/increase.spec.js +580 -0
- package/build/cjs/src/utils/trade/__tests__/increaseInvariants.spec.js +258 -0
- package/build/cjs/src/utils/trade/__tests__/increaseMarginCheck.spec.js +837 -0
- package/build/cjs/src/utils/trade/increase.js +255 -32
- package/build/cjs/src/utils/trade/increaseMarginCheck.js +179 -0
- package/build/cjs/src/utils/trade/index.js +1 -0
- package/build/cjs/src/utils/trade/trade.js +11 -1
- package/build/cjs/src/utils/tradeHistory/utils.js +3 -0
- package/build/cjs/src/utils/yield/api.js +9 -1
- package/build/esm/scripts/subsquid-codegen.js +1 -1
- package/build/esm/src/abis/ArbSys.js +9 -0
- package/build/esm/src/abis/index.js +2 -0
- package/build/esm/src/clients/v1/testUtil.js +1 -1
- package/build/esm/src/clients/v2/index.js +5 -1
- package/build/esm/src/codegen/prebuilt/hashedKinkModelMarketRatesKeys.json +16 -88
- package/build/esm/src/codegen/prebuilt/hashedMarketConfigKeys.json +136 -748
- package/build/esm/src/codegen/prebuilt/hashedMarketValuesKeys.json +30 -165
- package/build/esm/src/configs/__tests__/markets.spec.js +2 -17
- package/build/esm/src/configs/api.js +8 -0
- package/build/esm/src/configs/contracts.js +2 -0
- package/build/esm/src/configs/dataStore.js +8 -0
- package/build/esm/src/configs/express.js +1 -0
- package/build/esm/src/configs/markets.js +14 -77
- package/build/esm/src/configs/tokens.js +22 -90
- package/build/esm/src/test/fixtures/arbitrumMarkets.json +0 -72
- package/build/esm/src/test/mock.js +10 -0
- package/build/esm/src/utils/__tests__/fees.spec.js +37 -1
- package/build/esm/src/utils/__tests__/markets.spec.js +234 -1
- package/build/esm/src/utils/__tests__/positionPnlCap.spec.js +30 -3
- package/build/esm/src/utils/__tests__/positions.spec.js +5 -5
- package/build/esm/src/utils/__tests__/prices.spec.js +98 -1
- package/build/esm/src/utils/express/utils/gelatoRelayUtils.js +2 -0
- package/build/esm/src/utils/express/utils/gmxRelayUtils.js +137 -0
- package/build/esm/src/utils/express/utils/gmxRelayUtils.spec.js +161 -0
- package/build/esm/src/utils/express/utils/index.js +1 -0
- package/build/esm/src/utils/fees/index.js +8 -5
- package/build/esm/src/utils/fees/priceImpact.js +5 -10
- package/build/esm/src/utils/markets/utils.js +57 -2
- package/build/esm/src/utils/numbers/index.js +1 -0
- package/build/esm/src/utils/numbers/prbMath.js +149 -0
- package/build/esm/src/utils/positions/utils.js +63 -42
- package/build/esm/src/utils/prices/utils.js +25 -0
- package/build/esm/src/utils/stats/__tests__/api.spec.js +98 -0
- package/build/esm/src/utils/stats/api.js +26 -0
- package/build/esm/src/utils/stats/types.js +1 -0
- package/build/esm/src/utils/trade/__tests__/increase.spec.js +578 -0
- package/build/esm/src/utils/trade/__tests__/increaseInvariants.spec.js +256 -0
- package/build/esm/src/utils/trade/__tests__/increaseMarginCheck.spec.js +835 -0
- package/build/esm/src/utils/trade/increase.js +243 -20
- package/build/esm/src/utils/trade/increaseMarginCheck.js +173 -0
- package/build/esm/src/utils/trade/index.js +1 -0
- package/build/esm/src/utils/trade/trade.js +10 -1
- package/build/esm/src/utils/tradeHistory/utils.js +3 -0
- package/build/esm/src/utils/yield/api.js +7 -0
- package/build/tsconfig.tsbuildinfo +1 -1
- package/build/types/src/abis/ArbSys.d.ts +12 -0
- package/build/types/src/abis/index.d.ts +11 -0
- package/build/types/src/clients/v2/index.d.ts +6 -3
- package/build/types/src/codegen/prebuilt/index.d.ts +170 -989
- package/build/types/src/configs/api.d.ts +1 -0
- package/build/types/src/configs/contracts.d.ts +2 -0
- package/build/types/src/configs/dataStore.d.ts +4 -0
- package/build/types/src/configs/express.d.ts +1 -0
- package/build/types/src/test/mock.d.ts +2 -0
- package/build/types/src/utils/buildUrl/utils.d.ts +1 -1
- package/build/types/src/utils/buyback/types.d.ts +7 -0
- package/build/types/src/utils/express/utils/gelatoRelayUtils.d.ts +2 -0
- package/build/types/src/utils/express/utils/gmxRelayUtils.d.ts +61 -0
- package/build/types/src/utils/express/utils/gmxRelayUtils.spec.d.ts +1 -0
- package/build/types/src/utils/express/utils/index.d.ts +1 -0
- package/build/types/src/utils/fees/index.d.ts +1 -1
- package/build/types/src/utils/markets/utils.d.ts +7 -0
- package/build/types/src/utils/numbers/index.d.ts +1 -0
- package/build/types/src/utils/numbers/prbMath.d.ts +7 -0
- package/build/types/src/utils/positions/utils.d.ts +9 -0
- package/build/types/src/utils/prices/utils.d.ts +10 -0
- package/build/types/src/utils/stats/__tests__/api.spec.d.ts +1 -0
- package/build/types/src/utils/stats/api.d.ts +11 -0
- package/build/types/src/utils/stats/types.d.ts +106 -0
- package/build/types/src/utils/trade/__tests__/increase.spec.d.ts +1 -0
- package/build/types/src/utils/trade/__tests__/increaseInvariants.spec.d.ts +1 -0
- package/build/types/src/utils/trade/__tests__/increaseMarginCheck.spec.d.ts +1 -0
- package/build/types/src/utils/trade/increase.d.ts +3 -0
- package/build/types/src/utils/trade/increaseMarginCheck.d.ts +61 -0
- package/build/types/src/utils/trade/index.d.ts +1 -0
- package/build/types/src/utils/trade/trade.d.ts +2 -0
- package/build/types/src/utils/tradeHistory/types.d.ts +2 -1
- package/build/types/src/utils/yield/api.d.ts +4 -1
- package/build/types/src/utils/yield/types.d.ts +18 -0
- package/package.json +3 -3
|
@@ -5,14 +5,14 @@ import { getCappedPoolPnl, getPoolUsdWithoutPnl, getPositiveMarketPnl } from "..
|
|
|
5
5
|
import { expandDecimals, USD_DECIMALS } from "../numbers";
|
|
6
6
|
import { getEntryPrice, getLeverage, getLiquidationPrice, getMinCollateralUsdForLiquidationPrice, getPositionKey, getPositionNetValue, getPositionNetValueAfterAllFees, getPositionPendingFeesUsd, getPositionPnlAfterAllFees, getPositionPnlAfterFees, getPositionPnlUsd, getPositionValueUsd, parsePositionKey, } from "../positions";
|
|
7
7
|
import { convertToUsd, getIsEquivalentTokens } from "../tokens";
|
|
8
|
-
vi.mock("../markets", () => ({
|
|
9
|
-
...vi.importActual("../markets"),
|
|
8
|
+
vi.mock("../markets", async () => ({
|
|
9
|
+
...(await vi.importActual("../markets")),
|
|
10
10
|
getPositiveMarketPnl: vi.fn(),
|
|
11
11
|
getPoolUsdWithoutPnl: vi.fn(),
|
|
12
12
|
getCappedPoolPnl: vi.fn(),
|
|
13
13
|
}));
|
|
14
|
-
vi.mock("../tokens", () => ({
|
|
15
|
-
...vi.importActual("../tokens"),
|
|
14
|
+
vi.mock("../tokens", async () => ({
|
|
15
|
+
...(await vi.importActual("../tokens")),
|
|
16
16
|
convertToUsd: vi.fn(),
|
|
17
17
|
getIsEquivalentTokens: vi.fn(),
|
|
18
18
|
}));
|
|
@@ -83,7 +83,7 @@ describe("getPositionPnlUsd", () => {
|
|
|
83
83
|
markPrice: 10n,
|
|
84
84
|
isLong: true,
|
|
85
85
|
});
|
|
86
|
-
expect(getPositiveMarketPnl).toHaveBeenCalledWith(marketInfo, true,
|
|
86
|
+
expect(getPositiveMarketPnl).toHaveBeenCalledWith(marketInfo, true, false);
|
|
87
87
|
expect(result).toBe(expandDecimals(800, USD_DECIMALS));
|
|
88
88
|
});
|
|
89
89
|
});
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { describe, expect, it } from "vitest";
|
|
2
2
|
import { OrderType } from "../orders/types";
|
|
3
|
-
import { getMarkPrice, getOrderThresholdType, getShouldUseMaxPrice } from "../prices";
|
|
3
|
+
import { getIncreaseEvaluationIndexPrice, getIsIncreaseOrderExecutableNow, getMarkPrice, getOrderThresholdType, getShouldUseMaxPrice, } from "../prices";
|
|
4
4
|
import { TriggerThresholdType } from "../trade/types";
|
|
5
5
|
describe("getMarkPrice", () => {
|
|
6
6
|
it("returns maxPrice if getShouldUseMaxPrice => true", () => {
|
|
@@ -66,3 +66,100 @@ describe("getTriggerThresholdType", () => {
|
|
|
66
66
|
expect(result).toBeUndefined();
|
|
67
67
|
});
|
|
68
68
|
});
|
|
69
|
+
describe("getIsIncreaseOrderExecutableNow", () => {
|
|
70
|
+
const prices = { minPrice: 1000n, maxPrice: 1100n };
|
|
71
|
+
it("is always true for a market increase, regardless of the trigger price", () => {
|
|
72
|
+
expect(getIsIncreaseOrderExecutableNow({
|
|
73
|
+
orderType: OrderType.MarketIncrease,
|
|
74
|
+
isLong: true,
|
|
75
|
+
triggerPrice: undefined,
|
|
76
|
+
indexTokenPrices: prices,
|
|
77
|
+
})).toBe(true);
|
|
78
|
+
});
|
|
79
|
+
it("is false without a usable trigger price", () => {
|
|
80
|
+
for (const triggerPrice of [undefined, 0n, -1n]) {
|
|
81
|
+
expect(getIsIncreaseOrderExecutableNow({
|
|
82
|
+
orderType: OrderType.LimitIncrease,
|
|
83
|
+
isLong: true,
|
|
84
|
+
triggerPrice,
|
|
85
|
+
indexTokenPrices: prices,
|
|
86
|
+
})).toBe(false);
|
|
87
|
+
}
|
|
88
|
+
});
|
|
89
|
+
it("is false for order types that are not increases", () => {
|
|
90
|
+
expect(getIsIncreaseOrderExecutableNow({
|
|
91
|
+
orderType: OrderType.LimitDecrease,
|
|
92
|
+
isLong: true,
|
|
93
|
+
triggerPrice: 5000n,
|
|
94
|
+
indexTokenPrices: prices,
|
|
95
|
+
})).toBe(false);
|
|
96
|
+
expect(getIsIncreaseOrderExecutableNow({
|
|
97
|
+
orderType: undefined,
|
|
98
|
+
isLong: true,
|
|
99
|
+
triggerPrice: 5000n,
|
|
100
|
+
indexTokenPrices: prices,
|
|
101
|
+
})).toBe(false);
|
|
102
|
+
});
|
|
103
|
+
// a long limit increase buys at maxPrice, so it triggers once the max price falls to the trigger
|
|
104
|
+
it.each([
|
|
105
|
+
["long, max above the trigger", true, 1099n, false],
|
|
106
|
+
["long, max exactly at the trigger", true, 1100n, true],
|
|
107
|
+
["long, max below the trigger", true, 1101n, true],
|
|
108
|
+
// a short limit increase sells at minPrice, so it triggers once the min price rises to the trigger
|
|
109
|
+
["short, min below the trigger", false, 1001n, false],
|
|
110
|
+
["short, min exactly at the trigger", false, 1000n, true],
|
|
111
|
+
["short, min above the trigger", false, 999n, true],
|
|
112
|
+
])("LimitIncrease — %s", (_name, isLong, triggerPrice, expected) => {
|
|
113
|
+
expect(getIsIncreaseOrderExecutableNow({
|
|
114
|
+
orderType: OrderType.LimitIncrease,
|
|
115
|
+
isLong,
|
|
116
|
+
triggerPrice,
|
|
117
|
+
indexTokenPrices: prices,
|
|
118
|
+
})).toBe(expected);
|
|
119
|
+
});
|
|
120
|
+
it.each([
|
|
121
|
+
["long, max below the trigger", true, 1101n, false],
|
|
122
|
+
["long, max exactly at the trigger", true, 1100n, true],
|
|
123
|
+
["long, max above the trigger", true, 1099n, true],
|
|
124
|
+
["short, min above the trigger", false, 999n, false],
|
|
125
|
+
["short, min exactly at the trigger", false, 1000n, true],
|
|
126
|
+
["short, min below the trigger", false, 1001n, true],
|
|
127
|
+
])("StopIncrease — %s", (_name, isLong, triggerPrice, expected) => {
|
|
128
|
+
expect(getIsIncreaseOrderExecutableNow({
|
|
129
|
+
orderType: OrderType.StopIncrease,
|
|
130
|
+
isLong,
|
|
131
|
+
triggerPrice,
|
|
132
|
+
indexTokenPrices: prices,
|
|
133
|
+
})).toBe(expected);
|
|
134
|
+
});
|
|
135
|
+
});
|
|
136
|
+
describe("getIncreaseEvaluationIndexPrice", () => {
|
|
137
|
+
it("keeps current prices for a market increase", () => {
|
|
138
|
+
expect(getIncreaseEvaluationIndexPrice({
|
|
139
|
+
orderType: OrderType.MarketIncrease,
|
|
140
|
+
triggerPrice: undefined,
|
|
141
|
+
})).toBeUndefined();
|
|
142
|
+
expect(getIncreaseEvaluationIndexPrice({
|
|
143
|
+
orderType: OrderType.MarketIncrease,
|
|
144
|
+
triggerPrice: 1000n,
|
|
145
|
+
})).toBeUndefined();
|
|
146
|
+
});
|
|
147
|
+
it("keeps current prices without a usable trigger price", () => {
|
|
148
|
+
for (const triggerPrice of [undefined, 0n, -1n]) {
|
|
149
|
+
expect(getIncreaseEvaluationIndexPrice({
|
|
150
|
+
orderType: OrderType.LimitIncrease,
|
|
151
|
+
triggerPrice,
|
|
152
|
+
})).toBeUndefined();
|
|
153
|
+
}
|
|
154
|
+
});
|
|
155
|
+
it.each([
|
|
156
|
+
// amounts are always sized at the trigger price, so the evaluation stays there as well —
|
|
157
|
+
// including the window where the order is already executable (prices 1000 / 1100)
|
|
158
|
+
[OrderType.LimitIncrease, 900n, 900n],
|
|
159
|
+
[OrderType.LimitIncrease, 1200n, 1200n],
|
|
160
|
+
[OrderType.StopIncrease, 1200n, 1200n],
|
|
161
|
+
[OrderType.StopIncrease, 900n, 900n],
|
|
162
|
+
])("orderType=%s trigger=%s → %s", (orderType, triggerPrice, expected) => {
|
|
163
|
+
expect(getIncreaseEvaluationIndexPrice({ orderType, triggerPrice })).toBe(expected);
|
|
164
|
+
});
|
|
165
|
+
});
|
|
@@ -9,6 +9,7 @@ export class GelatoRelayError extends Error {
|
|
|
9
9
|
this.name = "GelatoRelayError";
|
|
10
10
|
}
|
|
11
11
|
}
|
|
12
|
+
/** @deprecated Gelato shuts its relay services down on 2026-09-01; use `sendToGmxRelay`. */
|
|
12
13
|
export async function sendToGelatoRelay({ chainId, txnData, }) {
|
|
13
14
|
const data = encodePacked(["bytes", "address", "address", "uint256"], [txnData.callData, txnData.to, txnData.feeToken, txnData.feeAmount]);
|
|
14
15
|
const apiKey = GELATO_API_KEYS[chainId];
|
|
@@ -32,6 +33,7 @@ export async function sendToGelatoRelay({ chainId, txnData, }) {
|
|
|
32
33
|
}
|
|
33
34
|
return { taskId, relayerClient };
|
|
34
35
|
}
|
|
36
|
+
/** @deprecated Gelato shuts its relay services down on 2026-09-01; use `waitForGmxRelayTask`. */
|
|
35
37
|
export async function waitForGelatoTask(relayerClient, taskId, options) {
|
|
36
38
|
try {
|
|
37
39
|
const receipt = await relayerClient.waitForReceipt({
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
import { getApiUrl } from "../../../configs/api";
|
|
2
|
+
import { buildUrl } from "../../buildUrl";
|
|
3
|
+
import { sleep } from "../../common";
|
|
4
|
+
import { HttpError } from "../../http/http";
|
|
5
|
+
const SUBMIT_TIMEOUT_MS = 15000;
|
|
6
|
+
const STATUS_TIMEOUT_MS = 10000;
|
|
7
|
+
const WAIT_TIMEOUT_MS = 120000;
|
|
8
|
+
const POLLING_INTERVAL_MS = 1000;
|
|
9
|
+
export class GmxRelayError extends HttpError {
|
|
10
|
+
constructor(message, httpStatus, cause) {
|
|
11
|
+
// statusCode 0 marks a transport failure that never got an HTTP answer
|
|
12
|
+
super(httpStatus ?? 0, message);
|
|
13
|
+
this.cause = cause;
|
|
14
|
+
this.name = "GmxRelayError";
|
|
15
|
+
}
|
|
16
|
+
get isPermanent() {
|
|
17
|
+
return this.statusCode >= 400 && this.statusCode < 500 && this.statusCode !== 429;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
export function isPermanentRelayError(error) {
|
|
21
|
+
return error instanceof GmxRelayError && error.isPermanent;
|
|
22
|
+
}
|
|
23
|
+
export async function sendToGmxRelay({ chainId, txnData, apiUrl, }) {
|
|
24
|
+
// bare relay-router calldata: the fee is computed on-chain, so no Gelato fee suffix is appended
|
|
25
|
+
const result = await post(resolveApiUrl(chainId, apiUrl), "/v1/relay/submit", { to: txnData.to, data: txnData.callData }, SUBMIT_TIMEOUT_MS);
|
|
26
|
+
if (!result.taskId) {
|
|
27
|
+
throw new GmxRelayError("GMX Relay returned no taskId");
|
|
28
|
+
}
|
|
29
|
+
return result;
|
|
30
|
+
}
|
|
31
|
+
export function getGmxRelayTaskStatus({ chainId, taskId, apiUrl, }) {
|
|
32
|
+
return post(resolveApiUrl(chainId, apiUrl), "/v1/relay/status", { taskId }, STATUS_TIMEOUT_MS);
|
|
33
|
+
}
|
|
34
|
+
export async function waitForGmxRelayTask({ chainId, taskId, apiUrl, timeout = WAIT_TIMEOUT_MS, pollingInterval = POLLING_INTERVAL_MS, }) {
|
|
35
|
+
const deadline = Date.now() + timeout;
|
|
36
|
+
// eslint-disable-next-line no-constant-condition
|
|
37
|
+
while (true) {
|
|
38
|
+
let view;
|
|
39
|
+
try {
|
|
40
|
+
view = await getGmxRelayTaskStatus({ chainId, taskId, apiUrl });
|
|
41
|
+
}
|
|
42
|
+
catch (e) {
|
|
43
|
+
// a 404 is transient here: the task can be accepted a moment before its status becomes readable
|
|
44
|
+
const error = e instanceof GmxRelayError ? e : new GmxRelayError(String(e));
|
|
45
|
+
if (error.isPermanent && error.statusCode !== 404) {
|
|
46
|
+
throw error;
|
|
47
|
+
}
|
|
48
|
+
if (Date.now() + pollingInterval >= deadline) {
|
|
49
|
+
return {
|
|
50
|
+
transactionHash: undefined,
|
|
51
|
+
status: "pending",
|
|
52
|
+
relayStatus: "unknown",
|
|
53
|
+
message: `Could not read the relay operation's status: ${error.message}`,
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
await sleep(pollingInterval);
|
|
57
|
+
continue;
|
|
58
|
+
}
|
|
59
|
+
if (view.status !== "pending") {
|
|
60
|
+
return {
|
|
61
|
+
transactionHash: view.txHash,
|
|
62
|
+
// relay `unknown` means it could not determine the outcome, so it must not map to failure
|
|
63
|
+
status: view.status === "executed" ? "success" : view.status === "unknown" ? "pending" : "failed",
|
|
64
|
+
relayStatus: view.status,
|
|
65
|
+
message: view.reason,
|
|
66
|
+
revertData: view.revertData,
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
if (Date.now() + pollingInterval >= deadline) {
|
|
70
|
+
return {
|
|
71
|
+
transactionHash: view.txHash,
|
|
72
|
+
status: "pending",
|
|
73
|
+
relayStatus: view.status,
|
|
74
|
+
message: "Timed out waiting for the relay operation to land",
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
await sleep(pollingInterval);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
function resolveApiUrl(chainId, apiUrl) {
|
|
81
|
+
const url = apiUrl ?? getApiUrl(chainId);
|
|
82
|
+
if (!url) {
|
|
83
|
+
throw new GmxRelayError(`GMX API url is not configured for chain ${chainId}`);
|
|
84
|
+
}
|
|
85
|
+
return url;
|
|
86
|
+
}
|
|
87
|
+
async function post(baseUrl, path, body, timeout) {
|
|
88
|
+
const controller = new AbortController();
|
|
89
|
+
const timer = setTimeout(() => controller.abort(), timeout);
|
|
90
|
+
// bespoke fetch rather than postJson: the trace id arrives in a response header on refusals,
|
|
91
|
+
// and the shared client only surfaces parsed bodies
|
|
92
|
+
// the timer must also cover the body read: a response that stalls after its headers would hang forever
|
|
93
|
+
try {
|
|
94
|
+
const response = await fetch(buildUrl(baseUrl, path), {
|
|
95
|
+
method: "POST",
|
|
96
|
+
headers: { "Content-Type": "application/json" },
|
|
97
|
+
body: JSON.stringify(body),
|
|
98
|
+
signal: controller.signal,
|
|
99
|
+
});
|
|
100
|
+
if (!response.ok) {
|
|
101
|
+
const text = await response.text().catch(() => "");
|
|
102
|
+
const error = new GmxRelayError(`GMX Relay ${path} failed: ${extractMessage(text) ?? response.statusText}`, response.status);
|
|
103
|
+
// a request refused before it was relayed never gets a taskId; the trace id is the only handle left
|
|
104
|
+
const traceId = response.headers.get("X-Trace-Id");
|
|
105
|
+
if (traceId) {
|
|
106
|
+
error.traceId = traceId;
|
|
107
|
+
error.data = { traceId };
|
|
108
|
+
}
|
|
109
|
+
throw error;
|
|
110
|
+
}
|
|
111
|
+
try {
|
|
112
|
+
return (await response.json());
|
|
113
|
+
}
|
|
114
|
+
catch (e) {
|
|
115
|
+
throw new GmxRelayError(`GMX Relay ${path} returned an unreadable body`, response.status, e);
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
catch (e) {
|
|
119
|
+
if (e instanceof GmxRelayError) {
|
|
120
|
+
throw e;
|
|
121
|
+
}
|
|
122
|
+
throw new GmxRelayError(`GMX Relay request failed: ${e?.message ?? String(e)}`, undefined, e);
|
|
123
|
+
}
|
|
124
|
+
finally {
|
|
125
|
+
clearTimeout(timer);
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
function extractMessage(text) {
|
|
129
|
+
try {
|
|
130
|
+
const parsed = JSON.parse(text);
|
|
131
|
+
return parsed?.message ?? parsed?.error;
|
|
132
|
+
}
|
|
133
|
+
catch {
|
|
134
|
+
// a non-JSON body is an edge's HTML error page, not a message to surface to a user
|
|
135
|
+
return undefined;
|
|
136
|
+
}
|
|
137
|
+
}
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
import { afterEach, describe, expect, it, vi } from "vitest";
|
|
2
|
+
import { ARBITRUM } from "../../../configs/chains";
|
|
3
|
+
import { GmxRelayError, getGmxRelayTaskStatus, isPermanentRelayError, sendToGmxRelay, waitForGmxRelayTask, } from "./gmxRelayUtils";
|
|
4
|
+
const TASK_ID = `0x${"ab".repeat(32)}`;
|
|
5
|
+
const TXN_DATA = {
|
|
6
|
+
callData: "0xdeadbeef",
|
|
7
|
+
to: "0x0000000000000000000000000000000000000001",
|
|
8
|
+
feeToken: "0x0000000000000000000000000000000000000002",
|
|
9
|
+
feeAmount: 123n,
|
|
10
|
+
};
|
|
11
|
+
function jsonResponse(body, status = 200) {
|
|
12
|
+
return new Response(JSON.stringify(body), { status, headers: { "Content-Type": "application/json" } });
|
|
13
|
+
}
|
|
14
|
+
describe("sendToGmxRelay", () => {
|
|
15
|
+
afterEach(() => {
|
|
16
|
+
vi.unstubAllGlobals();
|
|
17
|
+
});
|
|
18
|
+
it("carries the API's trace id on a refusal", async () => {
|
|
19
|
+
vi.stubGlobal("fetch", vi.fn(async () => new Response(JSON.stringify({ message: "nope" }), {
|
|
20
|
+
status: 400,
|
|
21
|
+
headers: { "Content-Type": "application/json", "X-Trace-Id": "tr-1" },
|
|
22
|
+
})));
|
|
23
|
+
const error = await sendToGmxRelay({ chainId: ARBITRUM, txnData: TXN_DATA }).catch((e) => e);
|
|
24
|
+
expect(error).toBeInstanceOf(GmxRelayError);
|
|
25
|
+
expect(error.data).toEqual({ traceId: "tr-1" });
|
|
26
|
+
});
|
|
27
|
+
it("posts bare calldata without the Gelato fee suffix", async () => {
|
|
28
|
+
const fetchMock = vi.fn(async () => jsonResponse({ taskId: TASK_ID, status: "pending" }));
|
|
29
|
+
vi.stubGlobal("fetch", fetchMock);
|
|
30
|
+
const result = await sendToGmxRelay({ chainId: ARBITRUM, txnData: TXN_DATA });
|
|
31
|
+
expect(result).toEqual({ taskId: TASK_ID, status: "pending" });
|
|
32
|
+
const [url, init] = fetchMock.mock.calls[0];
|
|
33
|
+
expect(url).toContain("/v1/relay/submit");
|
|
34
|
+
expect(JSON.parse(String(init.body))).toEqual({ to: TXN_DATA.to, data: TXN_DATA.callData });
|
|
35
|
+
});
|
|
36
|
+
it("honours an explicit api url", async () => {
|
|
37
|
+
const fetchMock = vi.fn(async () => jsonResponse({ taskId: TASK_ID, status: "pending" }));
|
|
38
|
+
vi.stubGlobal("fetch", fetchMock);
|
|
39
|
+
await sendToGmxRelay({ chainId: ARBITRUM, txnData: TXN_DATA, apiUrl: "https://api.example.com/" });
|
|
40
|
+
const [url] = fetchMock.mock.calls[0];
|
|
41
|
+
expect(url).toBe("https://api.example.com/v1/relay/submit");
|
|
42
|
+
});
|
|
43
|
+
it("raises a permanent error when the api rejects the operation", async () => {
|
|
44
|
+
vi.stubGlobal("fetch", vi.fn(async () => jsonResponse({ message: "to is not an allowlisted relay router" }, 400)));
|
|
45
|
+
const error = await sendToGmxRelay({ chainId: ARBITRUM, txnData: TXN_DATA }).catch((e) => e);
|
|
46
|
+
expect(error).toBeInstanceOf(GmxRelayError);
|
|
47
|
+
expect(error.message).toContain("allowlisted relay router");
|
|
48
|
+
expect(isPermanentRelayError(error)).toBe(true);
|
|
49
|
+
});
|
|
50
|
+
it("treats a rate-limited response as retryable rather than permanent", async () => {
|
|
51
|
+
vi.stubGlobal("fetch", vi.fn(async () => jsonResponse({ message: "slow down" }, 429)));
|
|
52
|
+
const error = await sendToGmxRelay({ chainId: ARBITRUM, txnData: TXN_DATA }).catch((e) => e);
|
|
53
|
+
expect(isPermanentRelayError(error)).toBe(false);
|
|
54
|
+
});
|
|
55
|
+
it("keeps a transport failure retryable", async () => {
|
|
56
|
+
vi.stubGlobal("fetch", vi.fn(async () => {
|
|
57
|
+
throw new Error("network down");
|
|
58
|
+
}));
|
|
59
|
+
const error = await sendToGmxRelay({ chainId: ARBITRUM, txnData: TXN_DATA }).catch((e) => e);
|
|
60
|
+
expect(error).toBeInstanceOf(GmxRelayError);
|
|
61
|
+
expect(isPermanentRelayError(error)).toBe(false);
|
|
62
|
+
});
|
|
63
|
+
});
|
|
64
|
+
describe("getGmxRelayTaskStatus", () => {
|
|
65
|
+
afterEach(() => {
|
|
66
|
+
vi.unstubAllGlobals();
|
|
67
|
+
});
|
|
68
|
+
it("posts the taskId and returns the status view", async () => {
|
|
69
|
+
const fetchMock = vi.fn(async () => jsonResponse({ taskId: TASK_ID, status: "executed", txHash: "0xhash" }));
|
|
70
|
+
vi.stubGlobal("fetch", fetchMock);
|
|
71
|
+
const view = await getGmxRelayTaskStatus({ chainId: ARBITRUM, taskId: TASK_ID });
|
|
72
|
+
expect(view.status).toBe("executed");
|
|
73
|
+
const [url, init] = fetchMock.mock.calls[0];
|
|
74
|
+
expect(url).toContain("/v1/relay/status");
|
|
75
|
+
expect(JSON.parse(String(init.body))).toEqual({ taskId: TASK_ID });
|
|
76
|
+
});
|
|
77
|
+
});
|
|
78
|
+
describe("waitForGmxRelayTask", () => {
|
|
79
|
+
afterEach(() => {
|
|
80
|
+
vi.unstubAllGlobals();
|
|
81
|
+
});
|
|
82
|
+
it("polls until the operation leaves the pending state", async () => {
|
|
83
|
+
let call = 0;
|
|
84
|
+
vi.stubGlobal("fetch", vi.fn(async () => {
|
|
85
|
+
call++;
|
|
86
|
+
return call < 3
|
|
87
|
+
? jsonResponse({ taskId: TASK_ID, status: "pending" })
|
|
88
|
+
: jsonResponse({ taskId: TASK_ID, status: "executed", txHash: "0xhash" });
|
|
89
|
+
}));
|
|
90
|
+
const result = await waitForGmxRelayTask({ chainId: ARBITRUM, taskId: TASK_ID, pollingInterval: 1 });
|
|
91
|
+
expect(result.status).toBe("success");
|
|
92
|
+
expect(result.transactionHash).toBe("0xhash");
|
|
93
|
+
expect(call).toBe(3);
|
|
94
|
+
});
|
|
95
|
+
it("keeps polling through a transient status failure", async () => {
|
|
96
|
+
let call = 0;
|
|
97
|
+
vi.stubGlobal("fetch", vi.fn(async () => {
|
|
98
|
+
call++;
|
|
99
|
+
if (call === 1)
|
|
100
|
+
throw new Error("network blip");
|
|
101
|
+
if (call === 2)
|
|
102
|
+
return jsonResponse({ message: "upstream" }, 503);
|
|
103
|
+
if (call === 3)
|
|
104
|
+
return jsonResponse({ message: "no relay operation" }, 404);
|
|
105
|
+
return jsonResponse({ taskId: TASK_ID, status: "executed", txHash: "0xhash" });
|
|
106
|
+
}));
|
|
107
|
+
const result = await waitForGmxRelayTask({ chainId: ARBITRUM, taskId: TASK_ID, pollingInterval: 1 });
|
|
108
|
+
expect(result.status).toBe("success");
|
|
109
|
+
expect(result.transactionHash).toBe("0xhash");
|
|
110
|
+
expect(call).toBe(4);
|
|
111
|
+
});
|
|
112
|
+
it("gives up immediately when the status request itself is rejected", async () => {
|
|
113
|
+
const fetchMock = vi.fn(async () => jsonResponse({ message: "taskId must be a 32-byte hex string" }, 400));
|
|
114
|
+
vi.stubGlobal("fetch", fetchMock);
|
|
115
|
+
const error = await waitForGmxRelayTask({ chainId: ARBITRUM, taskId: TASK_ID, pollingInterval: 1 }).catch((e) => e);
|
|
116
|
+
expect(error).toBeInstanceOf(GmxRelayError);
|
|
117
|
+
expect(fetchMock).toHaveBeenCalledTimes(1);
|
|
118
|
+
});
|
|
119
|
+
it("reports an unresolved status rather than a failure when the window closes on errors", async () => {
|
|
120
|
+
vi.stubGlobal("fetch", vi.fn(async () => jsonResponse({ message: "upstream" }, 503)));
|
|
121
|
+
const result = await waitForGmxRelayTask({
|
|
122
|
+
chainId: ARBITRUM,
|
|
123
|
+
taskId: TASK_ID,
|
|
124
|
+
pollingInterval: 1,
|
|
125
|
+
timeout: 5,
|
|
126
|
+
});
|
|
127
|
+
expect(result.status).toBe("pending");
|
|
128
|
+
expect(result.message).toContain("Could not read");
|
|
129
|
+
});
|
|
130
|
+
it("reports a revert as a failure carrying the reason and the raw revert bytes", async () => {
|
|
131
|
+
vi.stubGlobal("fetch", vi.fn(async () => jsonResponse({
|
|
132
|
+
taskId: TASK_ID,
|
|
133
|
+
status: "reverted",
|
|
134
|
+
txHash: "0xhash",
|
|
135
|
+
reason: "InsufficientRelayFee",
|
|
136
|
+
revertData: "0x08c379a0deadbeef",
|
|
137
|
+
})));
|
|
138
|
+
const result = await waitForGmxRelayTask({ chainId: ARBITRUM, taskId: TASK_ID, pollingInterval: 1 });
|
|
139
|
+
expect(result.status).toBe("failed");
|
|
140
|
+
expect(result.relayStatus).toBe("reverted");
|
|
141
|
+
expect(result.message).toBe("InsufficientRelayFee");
|
|
142
|
+
expect(result.revertData).toBe("0x08c379a0deadbeef");
|
|
143
|
+
});
|
|
144
|
+
it("never resolves an undetermined outcome as success or failure", async () => {
|
|
145
|
+
vi.stubGlobal("fetch", vi.fn(async () => jsonResponse({ taskId: TASK_ID, status: "unknown", txHash: "0xhash" })));
|
|
146
|
+
const result = await waitForGmxRelayTask({ chainId: ARBITRUM, taskId: TASK_ID, pollingInterval: 1 });
|
|
147
|
+
expect(result.status).toBe("pending");
|
|
148
|
+
expect(result.relayStatus).toBe("unknown");
|
|
149
|
+
});
|
|
150
|
+
it("gives up as pending once the wait window elapses", async () => {
|
|
151
|
+
vi.stubGlobal("fetch", vi.fn(async () => jsonResponse({ taskId: TASK_ID, status: "pending" })));
|
|
152
|
+
const result = await waitForGmxRelayTask({
|
|
153
|
+
chainId: ARBITRUM,
|
|
154
|
+
taskId: TASK_ID,
|
|
155
|
+
timeout: 5,
|
|
156
|
+
pollingInterval: 10,
|
|
157
|
+
});
|
|
158
|
+
expect(result.status).toBe("pending");
|
|
159
|
+
expect(result.message).toMatch(/Timed out/);
|
|
160
|
+
});
|
|
161
|
+
});
|
|
@@ -3,6 +3,7 @@ export * from "./oracleParamsUtils";
|
|
|
3
3
|
export * from "./relayParamsUtils";
|
|
4
4
|
export * from "./batchOrderUtils";
|
|
5
5
|
export * from "./gelatoRelayUtils";
|
|
6
|
+
export * from "./gmxRelayUtils";
|
|
6
7
|
export * from "./globalExpressParams";
|
|
7
8
|
export * from "./expressParamsUtils";
|
|
8
9
|
export * from "./estimateExpressParams";
|
|
@@ -25,17 +25,20 @@ export function getSwapFee(marketInfo, swapAmount, balanceWasImproved, swapPrici
|
|
|
25
25
|
}
|
|
26
26
|
return applyFactor(swapAmount, factor);
|
|
27
27
|
}
|
|
28
|
-
export function getPositionFee(marketInfo, sizeDeltaUsd, balanceWasImproved, referralInfo, uiFeeFactor) {
|
|
28
|
+
export function getPositionFee(marketInfo, sizeDeltaUsd, balanceWasImproved, referralInfo, uiFeeFactor, proDiscountFactor) {
|
|
29
29
|
const factor = balanceWasImproved
|
|
30
30
|
? marketInfo.positionFeeFactorForBalanceWasImproved
|
|
31
31
|
: marketInfo.positionFeeFactorForBalanceWasNotImproved;
|
|
32
32
|
let positionFeeUsd = applyFactor(sizeDeltaUsd, factor);
|
|
33
33
|
const uiFeeUsd = applyFactor(sizeDeltaUsd, uiFeeFactor ?? 0n);
|
|
34
|
-
|
|
35
|
-
|
|
34
|
+
const totalRebateUsd = referralInfo ? applyFactor(positionFeeUsd, referralInfo.totalRebateFactor) : 0n;
|
|
35
|
+
let discountUsd = referralInfo ? applyFactor(totalRebateUsd, referralInfo.discountFactor) : 0n;
|
|
36
|
+
if (proDiscountFactor !== undefined && proDiscountFactor > 0n) {
|
|
37
|
+
const proDiscountUsd = applyFactor(positionFeeUsd, proDiscountFactor);
|
|
38
|
+
if (proDiscountUsd > discountUsd) {
|
|
39
|
+
discountUsd = proDiscountUsd;
|
|
40
|
+
}
|
|
36
41
|
}
|
|
37
|
-
const totalRebateUsd = applyFactor(positionFeeUsd, referralInfo.totalRebateFactor);
|
|
38
|
-
const discountUsd = applyFactor(totalRebateUsd, referralInfo.discountFactor);
|
|
39
42
|
positionFeeUsd = positionFeeUsd - discountUsd;
|
|
40
43
|
return {
|
|
41
44
|
positionFeeUsd,
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { zeroHash } from "viem";
|
|
2
2
|
import { bigMath } from "../bigmath";
|
|
3
3
|
import { getOpenInterestForBalance, getTokenPoolType } from "../markets";
|
|
4
|
-
import { applyFactor, BASIS_POINTS_DECIMALS, expandDecimals, getBasisPoints, PRECISION_DECIMALS, roundUpMagnitudeDivision, } from "../numbers";
|
|
4
|
+
import { applyExponentFactor, applyFactor, BASIS_POINTS_DECIMALS, expandDecimals, getBasisPoints, PRECISION_DECIMALS, roundUpMagnitudeDivision, } from "../numbers";
|
|
5
5
|
import { convertToTokenAmount, convertToTokenAmountForIncrease, convertToUsd, getMidPrice } from "../tokens/utils";
|
|
6
6
|
export function getPriceImpactByAcceptablePrice(p) {
|
|
7
7
|
const { sizeDeltaUsd, acceptablePrice, indexPrice: markPrice, isLong, isIncrease } = p;
|
|
@@ -378,17 +378,12 @@ export function calculateImpactForCrossoverRebalance(p) {
|
|
|
378
378
|
return positiveImpact > negativeImpactUsd ? deltaDiffUsd : -deltaDiffUsd;
|
|
379
379
|
}
|
|
380
380
|
export function applyImpactFactor(diff, factor, exponent) {
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
const powered = _diff ** _exponent * 10 ** 30;
|
|
386
|
-
if (!isFinite(powered) || isNaN(powered)) {
|
|
381
|
+
try {
|
|
382
|
+
return applyFactor(applyExponentFactor(diff, exponent), factor);
|
|
383
|
+
}
|
|
384
|
+
catch {
|
|
387
385
|
return 0n;
|
|
388
386
|
}
|
|
389
|
-
let result = BigInt(Math.round(powered));
|
|
390
|
-
result = (result * factor) / expandDecimals(1, 30);
|
|
391
|
-
return result;
|
|
392
387
|
}
|
|
393
388
|
export function getCappedPriceImpactPercentageFromFees({ fees, isSwap, }) {
|
|
394
389
|
if (isSwap) {
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { zeroAddress } from "viem";
|
|
1
|
+
import { zeroAddress, zeroHash } from "viem";
|
|
2
2
|
import { BASIS_POINTS_DIVISOR, BASIS_POINTS_DIVISOR_BIGINT } from "../../configs/factors";
|
|
3
3
|
import { UI_MAX_LEVERAGE_BY_MARKET } from "../../configs/markets";
|
|
4
4
|
import { convertTokenAddress, getTokenVisualMultiplier, NATIVE_TOKEN_ADDRESS } from "../../configs/tokens";
|
|
@@ -7,7 +7,7 @@ import { getBorrowingFactorPerPeriod, getFundingFactorPerPeriod } from "../fees"
|
|
|
7
7
|
import { applyFactor, expandDecimals, PRECISION } from "../numbers";
|
|
8
8
|
import { getByKey } from "../objects";
|
|
9
9
|
import { periodToSeconds } from "../time";
|
|
10
|
-
import { convertToContractTokenPrices, convertToUsd, getMidPrice } from "../tokens";
|
|
10
|
+
import { convertToContractTokenPrices, convertToUsd, getIsEquivalentTokens, getMidPrice } from "../tokens";
|
|
11
11
|
export function getMarketFullName(p) {
|
|
12
12
|
const { indexToken, longToken, shortToken, isSpotOnly } = p;
|
|
13
13
|
return `${getMarketIndexName({ indexToken, isSpotOnly })} [${getMarketPoolName({ longToken, shortToken })}]`;
|
|
@@ -254,6 +254,61 @@ export function getOpenInterestUsd(marketInfo, isLong) {
|
|
|
254
254
|
export function getOpenInterestInTokens(marketInfo, isLong) {
|
|
255
255
|
return isLong ? marketInfo.longInterestInTokens : marketInfo.shortInterestInTokens;
|
|
256
256
|
}
|
|
257
|
+
export function getMarketInfoWithOpenInterestDelta({ marketInfo, collateralToken, isLong, sizeDeltaUsd, sizeDeltaInTokens, }) {
|
|
258
|
+
if (sizeDeltaUsd === 0n && sizeDeltaInTokens === 0n) {
|
|
259
|
+
return marketInfo;
|
|
260
|
+
}
|
|
261
|
+
const next = isLong
|
|
262
|
+
? {
|
|
263
|
+
...marketInfo,
|
|
264
|
+
longInterestUsd: marketInfo.longInterestUsd + sizeDeltaUsd,
|
|
265
|
+
longInterestInTokens: marketInfo.longInterestInTokens + sizeDeltaInTokens,
|
|
266
|
+
}
|
|
267
|
+
: {
|
|
268
|
+
...marketInfo,
|
|
269
|
+
shortInterestUsd: marketInfo.shortInterestUsd + sizeDeltaUsd,
|
|
270
|
+
shortInterestInTokens: marketInfo.shortInterestInTokens + sizeDeltaInTokens,
|
|
271
|
+
};
|
|
272
|
+
const isLongTokenCollateral = getIsEquivalentTokens(collateralToken, marketInfo.longToken);
|
|
273
|
+
const usdByCollateralKey = isLong
|
|
274
|
+
? isLongTokenCollateral
|
|
275
|
+
? "longInterestUsdUsingLongToken"
|
|
276
|
+
: "longInterestUsdUsingShortToken"
|
|
277
|
+
: isLongTokenCollateral
|
|
278
|
+
? "shortInterestUsdUsingLongToken"
|
|
279
|
+
: "shortInterestUsdUsingShortToken";
|
|
280
|
+
const tokensByCollateralKey = isLong
|
|
281
|
+
? isLongTokenCollateral
|
|
282
|
+
? "longInterestInTokensUsingLongToken"
|
|
283
|
+
: "longInterestInTokensUsingShortToken"
|
|
284
|
+
: isLongTokenCollateral
|
|
285
|
+
? "shortInterestInTokensUsingLongToken"
|
|
286
|
+
: "shortInterestInTokensUsingShortToken";
|
|
287
|
+
const usdByCollateral = marketInfo[usdByCollateralKey];
|
|
288
|
+
const tokensByCollateral = marketInfo[tokensByCollateralKey];
|
|
289
|
+
if (usdByCollateral !== undefined) {
|
|
290
|
+
next[usdByCollateralKey] = usdByCollateral + sizeDeltaUsd;
|
|
291
|
+
}
|
|
292
|
+
if (tokensByCollateral !== undefined) {
|
|
293
|
+
next[tokensByCollateralKey] = tokensByCollateral + sizeDeltaInTokens;
|
|
294
|
+
}
|
|
295
|
+
const hasVirtualInventory = typeof marketInfo.virtualIndexTokenId === "string"
|
|
296
|
+
? marketInfo.virtualIndexTokenId !== zeroHash
|
|
297
|
+
: marketInfo.useOpenInterestInTokensForBalance
|
|
298
|
+
? marketInfo.virtualInventoryForPositionsInTokens !== 0n
|
|
299
|
+
: marketInfo.virtualInventoryForPositions !== 0n;
|
|
300
|
+
if (hasVirtualInventory) {
|
|
301
|
+
if (marketInfo.useOpenInterestInTokensForBalance) {
|
|
302
|
+
next.virtualInventoryForPositionsInTokens =
|
|
303
|
+
marketInfo.virtualInventoryForPositionsInTokens + (isLong ? -sizeDeltaInTokens : sizeDeltaInTokens);
|
|
304
|
+
}
|
|
305
|
+
else {
|
|
306
|
+
next.virtualInventoryForPositions =
|
|
307
|
+
marketInfo.virtualInventoryForPositions + (isLong ? -sizeDeltaUsd : sizeDeltaUsd);
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
return next;
|
|
311
|
+
}
|
|
257
312
|
export function getOpenInterestForBalance(marketInfo, isLong) {
|
|
258
313
|
if (marketInfo.useOpenInterestInTokensForBalance) {
|
|
259
314
|
const interestInTokens = isLong ? marketInfo.longInterestInTokens : marketInfo.shortInterestInTokens;
|