@gmx-io/sdk 1.6.4 → 1.8.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/README.md +48 -0
- package/build/cjs/scripts/subsquid-codegen.js +1 -1
- package/build/cjs/src/clients/v1/testUtil.js +1 -1
- package/build/cjs/src/clients/v2/__tests__/data.spec.js +5 -5
- package/build/cjs/src/clients/v2/__tests__/decrease.spec.js +6 -6
- package/build/cjs/src/clients/v2/__tests__/editCancel.spec.js +12 -12
- package/build/cjs/src/clients/v2/__tests__/errors.spec.js +1 -47
- package/build/cjs/src/clients/v2/__tests__/errorsLifecycle.spec.js +53 -0
- package/build/cjs/src/clients/v2/__tests__/globalCleanup.js +80 -0
- package/build/cjs/src/clients/v2/__tests__/increase.spec.js +14 -14
- package/build/cjs/src/clients/v2/__tests__/multichain.spec.js +5 -6
- package/build/cjs/src/clients/v2/__tests__/prepareErrors.spec.js +167 -0
- package/build/cjs/src/clients/v2/__tests__/setupAllowance.js +32 -0
- package/build/cjs/src/clients/v2/__tests__/subaccount.spec.js +16 -123
- package/build/cjs/src/clients/v2/__tests__/subaccountLifecycle.spec.js +108 -0
- package/build/cjs/src/clients/v2/__tests__/testUtil.js +38 -5
- package/build/cjs/src/clients/v2/__tests__/tradingCapacity.spec.js +371 -0
- package/build/cjs/src/clients/v2/index.js +10 -1
- package/build/cjs/src/codegen/subsquid.js +284 -20
- package/build/cjs/src/configs/__tests__/markets.spec.js +8 -0
- package/build/cjs/src/utils/__tests__/markets.spec.js +60 -0
- package/build/cjs/src/utils/__tests__/numbers.spec.js +39 -0
- package/build/cjs/src/utils/__tests__/positionPnlCap.spec.js +78 -0
- package/build/cjs/src/utils/__tests__/positions.spec.js +16 -4
- package/build/cjs/src/utils/markets/api.js +90 -2
- package/build/cjs/src/utils/markets/multicall.js +4 -6
- package/build/cjs/src/utils/markets/types.js +8 -0
- package/build/cjs/src/utils/markets/utils.js +67 -9
- package/build/cjs/src/utils/numbers/utils.js +28 -9
- package/build/cjs/src/utils/orderTransactions/api.js +160 -2
- package/build/cjs/src/utils/positions/utils.js +1 -1
- package/build/cjs/src/utils/tradeHistory/__tests__/utils.spec.js +64 -0
- package/build/cjs/src/utils/tradeHistory/utils.js +2 -0
- package/build/cjs/src/utils/yield/api.js +13 -0
- package/build/cjs/src/utils/yield/types.js +2 -0
- package/build/esm/scripts/subsquid-codegen.js +1 -1
- package/build/esm/src/clients/v1/testUtil.js +1 -1
- package/build/esm/src/clients/v2/__tests__/data.spec.js +6 -6
- package/build/esm/src/clients/v2/__tests__/decrease.spec.js +7 -7
- package/build/esm/src/clients/v2/__tests__/editCancel.spec.js +13 -13
- package/build/esm/src/clients/v2/__tests__/errors.spec.js +2 -48
- package/build/esm/src/clients/v2/__tests__/errorsLifecycle.spec.js +51 -0
- package/build/esm/src/clients/v2/__tests__/globalCleanup.js +77 -0
- package/build/esm/src/clients/v2/__tests__/increase.spec.js +15 -15
- package/build/esm/src/clients/v2/__tests__/multichain.spec.js +6 -7
- package/build/esm/src/clients/v2/__tests__/prepareErrors.spec.js +165 -0
- package/build/esm/src/clients/v2/__tests__/setupAllowance.js +30 -0
- package/build/esm/src/clients/v2/__tests__/subaccount.spec.js +17 -124
- package/build/esm/src/clients/v2/__tests__/subaccountLifecycle.spec.js +106 -0
- package/build/esm/src/clients/v2/__tests__/testUtil.js +33 -4
- package/build/esm/src/clients/v2/__tests__/tradingCapacity.spec.js +369 -0
- package/build/esm/src/clients/v2/index.js +10 -2
- package/build/esm/src/codegen/subsquid.js +282 -18
- package/build/esm/src/configs/__tests__/markets.spec.js +9 -1
- package/build/esm/src/utils/__tests__/markets.spec.js +61 -1
- package/build/esm/src/utils/__tests__/numbers.spec.js +40 -1
- package/build/esm/src/utils/__tests__/positionPnlCap.spec.js +76 -0
- package/build/esm/src/utils/__tests__/positions.spec.js +17 -5
- package/build/esm/src/utils/markets/api.js +88 -2
- package/build/esm/src/utils/markets/multicall.js +4 -6
- package/build/esm/src/utils/markets/types.js +8 -0
- package/build/esm/src/utils/markets/utils.js +65 -8
- package/build/esm/src/utils/numbers/utils.js +24 -7
- package/build/esm/src/utils/orderTransactions/api.js +157 -1
- package/build/esm/src/utils/positions/utils.js +2 -2
- package/build/esm/src/utils/tradeHistory/__tests__/utils.spec.js +62 -0
- package/build/esm/src/utils/tradeHistory/utils.js +2 -0
- package/build/esm/src/utils/yield/api.js +9 -0
- package/build/esm/src/utils/yield/types.js +1 -0
- package/build/tsconfig.tsbuildinfo +1 -1
- package/build/types/src/clients/v2/__tests__/errorsLifecycle.spec.d.ts +1 -0
- package/build/types/src/clients/v2/__tests__/globalCleanup.d.ts +1 -0
- package/build/types/src/clients/v2/__tests__/prepareErrors.spec.d.ts +1 -0
- package/build/types/src/clients/v2/__tests__/setupAllowance.d.ts +1 -0
- package/build/types/src/clients/v2/__tests__/subaccountLifecycle.spec.d.ts +1 -0
- package/build/types/src/clients/v2/__tests__/testUtil.d.ts +7 -1
- package/build/types/src/clients/v2/__tests__/tradingCapacity.spec.d.ts +1 -0
- package/build/types/src/clients/v2/index.d.ts +11 -5
- package/build/types/src/codegen/subsquid.d.ts +1141 -51
- package/build/types/src/utils/__tests__/positionPnlCap.spec.d.ts +1 -0
- package/build/types/src/utils/markets/api.d.ts +6 -2
- package/build/types/src/utils/markets/types.d.ts +28 -1
- package/build/types/src/utils/markets/utils.d.ts +7 -8
- package/build/types/src/utils/numbers/utils.d.ts +2 -0
- package/build/types/src/utils/orderTransactions/api.d.ts +50 -0
- package/build/types/src/utils/tradeHistory/__tests__/utils.spec.d.ts +1 -0
- package/build/types/src/utils/tradeHistory/types.d.ts +2 -0
- package/build/types/src/utils/yield/api.d.ts +5 -0
- package/build/types/src/utils/yield/types.d.ts +29 -0
- package/package.json +2 -1
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { describe, expect, it } from "vitest";
|
|
2
|
+
import { USD_DECIMALS } from "../../configs/factors";
|
|
3
|
+
import { mockMarketsInfoData, mockTokensData } from "../../test/mock";
|
|
4
|
+
import { getMarketPnl, getPositiveMarketPnl } from "../markets";
|
|
5
|
+
import { expandDecimals } from "../numbers";
|
|
6
|
+
import { getPositionPnlUsd } from "../positions";
|
|
7
|
+
const MARKET_KEY = "ETH-ETH-USDC";
|
|
8
|
+
function usd(amount) {
|
|
9
|
+
return expandDecimals(amount, USD_DECIMALS);
|
|
10
|
+
}
|
|
11
|
+
function eth(amount) {
|
|
12
|
+
return expandDecimals(amount, 18);
|
|
13
|
+
}
|
|
14
|
+
const ETH_PRICE = usd(2000);
|
|
15
|
+
/**
|
|
16
|
+
* Long side splits into an eth collateral bucket worth +$1,000,000 and a usdc collateral bucket worth
|
|
17
|
+
* -$500,000, so net pnl is $500,000 and positive-only pnl is $1,000,000. The long pool is $1,000,000
|
|
18
|
+
* with a 90% trader pnl factor, so the cap binds on the positive-only figure only.
|
|
19
|
+
*/
|
|
20
|
+
function createMarketInfo(overrides = {}) {
|
|
21
|
+
const tokensData = mockTokensData({ ETH: { prices: { minPrice: ETH_PRICE, maxPrice: ETH_PRICE } } });
|
|
22
|
+
return mockMarketsInfoData(tokensData, [MARKET_KEY], {
|
|
23
|
+
[MARKET_KEY]: {
|
|
24
|
+
longPoolAmount: eth(500),
|
|
25
|
+
maxPnlFactorForTradersLong: expandDecimals(9, 29),
|
|
26
|
+
longInterestUsd: usd(2000000),
|
|
27
|
+
longInterestInTokens: eth(1250),
|
|
28
|
+
longInterestUsdUsingLongToken: usd(1000000),
|
|
29
|
+
longInterestInTokensUsingLongToken: eth(1000),
|
|
30
|
+
longInterestUsdUsingShortToken: usd(1000000),
|
|
31
|
+
longInterestInTokensUsingShortToken: eth(250),
|
|
32
|
+
...overrides,
|
|
33
|
+
},
|
|
34
|
+
})[MARKET_KEY];
|
|
35
|
+
}
|
|
36
|
+
function getLongPositionPnl(marketInfo) {
|
|
37
|
+
return getPositionPnlUsd({
|
|
38
|
+
marketInfo,
|
|
39
|
+
sizeInUsd: usd(100000),
|
|
40
|
+
sizeInTokens: eth(100),
|
|
41
|
+
markPrice: ETH_PRICE,
|
|
42
|
+
isLong: true,
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
describe("per-position pnl cap (v2.2c parity)", () => {
|
|
46
|
+
it("caps against the positive-only pool pnl", () => {
|
|
47
|
+
const marketInfo = createMarketInfo();
|
|
48
|
+
expect(getPositiveMarketPnl(marketInfo, true, true)).toBe(usd(1000000));
|
|
49
|
+
expect(getLongPositionPnl(marketInfo)).toBe(usd(90000));
|
|
50
|
+
});
|
|
51
|
+
it("leaves the net pool pnl used by gm pool value untouched", () => {
|
|
52
|
+
const marketInfo = createMarketInfo();
|
|
53
|
+
expect(getMarketPnl(marketInfo, true, true)).toBe(usd(500000));
|
|
54
|
+
});
|
|
55
|
+
it("keeps the net behaviour when the data source has no per-collateral open interest", () => {
|
|
56
|
+
const marketInfo = createMarketInfo({
|
|
57
|
+
longInterestUsdUsingLongToken: undefined,
|
|
58
|
+
longInterestInTokensUsingLongToken: undefined,
|
|
59
|
+
longInterestUsdUsingShortToken: undefined,
|
|
60
|
+
longInterestInTokensUsingShortToken: undefined,
|
|
61
|
+
});
|
|
62
|
+
expect(getPositiveMarketPnl(marketInfo, true, true)).toBe(usd(500000));
|
|
63
|
+
expect(getLongPositionPnl(marketInfo)).toBe(usd(100000));
|
|
64
|
+
});
|
|
65
|
+
it("matches the net pool pnl when both collateral buckets are winning", () => {
|
|
66
|
+
const marketInfo = createMarketInfo({
|
|
67
|
+
longInterestUsdUsingShortToken: usd(1000000),
|
|
68
|
+
longInterestInTokensUsingShortToken: eth(600),
|
|
69
|
+
longInterestUsd: usd(2000000),
|
|
70
|
+
longInterestInTokens: eth(1600),
|
|
71
|
+
});
|
|
72
|
+
expect(getPositiveMarketPnl(marketInfo, true, true)).toBe(usd(1200000));
|
|
73
|
+
expect(getMarketPnl(marketInfo, true, true)).toBe(usd(1200000));
|
|
74
|
+
expect(getLongPositionPnl(marketInfo)).toBe(usd(75000));
|
|
75
|
+
});
|
|
76
|
+
});
|
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
import { describe, expect, it, vi, beforeEach } from "vitest";
|
|
2
2
|
import { bigMath } from "../bigmath";
|
|
3
3
|
import { getPositionFee, getPriceImpactForPosition } from "../fees";
|
|
4
|
-
import { getCappedPoolPnl,
|
|
4
|
+
import { getCappedPoolPnl, getPoolUsdWithoutPnl, getPositiveMarketPnl } from "../markets";
|
|
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
8
|
vi.mock("../markets", () => ({
|
|
9
9
|
...vi.importActual("../markets"),
|
|
10
|
-
|
|
10
|
+
getPositiveMarketPnl: vi.fn(),
|
|
11
11
|
getPoolUsdWithoutPnl: vi.fn(),
|
|
12
12
|
getCappedPoolPnl: vi.fn(),
|
|
13
13
|
}));
|
|
@@ -59,9 +59,9 @@ describe("getPositionValueUsd", () => {
|
|
|
59
59
|
describe("getPositionPnlUsd", () => {
|
|
60
60
|
const marketInfo = { indexToken: {}, maxPositionImpactFactorForLiquidations: 2n };
|
|
61
61
|
beforeEach(() => {
|
|
62
|
-
|
|
63
|
-
getPoolUsdWithoutPnl.mockReturnValue(
|
|
64
|
-
getCappedPoolPnl.mockReturnValue(
|
|
62
|
+
getPositiveMarketPnl.mockReturnValue(expandDecimals(1000, USD_DECIMALS));
|
|
63
|
+
getPoolUsdWithoutPnl.mockReturnValue(expandDecimals(5000, USD_DECIMALS));
|
|
64
|
+
getCappedPoolPnl.mockReturnValue(expandDecimals(800, USD_DECIMALS));
|
|
65
65
|
});
|
|
66
66
|
it("returns negative PnL if positionValueUsd < sizeInUsd for a long", () => {
|
|
67
67
|
convertToUsd.mockReturnValueOnce(900n); // positionValueUsd
|
|
@@ -74,6 +74,18 @@ describe("getPositionPnlUsd", () => {
|
|
|
74
74
|
});
|
|
75
75
|
expect(result).toBe(900n - 1000n); // -100n
|
|
76
76
|
});
|
|
77
|
+
it("scales a winning position by the positive-only pool pnl", () => {
|
|
78
|
+
convertToUsd.mockReturnValueOnce(expandDecimals(2000, USD_DECIMALS)); // positionValueUsd
|
|
79
|
+
const result = getPositionPnlUsd({
|
|
80
|
+
marketInfo,
|
|
81
|
+
sizeInUsd: expandDecimals(1000, USD_DECIMALS),
|
|
82
|
+
sizeInTokens: 100n,
|
|
83
|
+
markPrice: 10n,
|
|
84
|
+
isLong: true,
|
|
85
|
+
});
|
|
86
|
+
expect(getPositiveMarketPnl).toHaveBeenCalledWith(marketInfo, true, true);
|
|
87
|
+
expect(result).toBe(expandDecimals(800, USD_DECIMALS));
|
|
88
|
+
});
|
|
77
89
|
});
|
|
78
90
|
describe("getPositionPendingFeesUsd", () => {
|
|
79
91
|
it("sums up funding and borrowing fees", () => {
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { assertApiFields, assertApiRecords } from "../http/validation";
|
|
2
|
-
import { deserializeBigIntsInObject } from "../numbers";
|
|
2
|
+
import { deserializeBigIntsInObject, isUint256, parseUint256DecimalString } from "../numbers";
|
|
3
|
+
import { getString, isRecord } from "../objects";
|
|
3
4
|
const MARKET_CONFIG_V22C_FIELDS = [
|
|
4
5
|
{ name: "marketTokenAddress", type: "string" },
|
|
5
6
|
{ name: "useOpenInterestInTokensForBalance", type: "boolean" },
|
|
@@ -58,5 +59,90 @@ export async function fetchApiMarketsTickers(ctx, params) {
|
|
|
58
59
|
symbols: params?.symbols,
|
|
59
60
|
},
|
|
60
61
|
});
|
|
61
|
-
return tickers.map((
|
|
62
|
+
return tickers.map((rawTicker) => {
|
|
63
|
+
const { capacityLong: rawCapacityLong, capacityShort: rawCapacityShort, ...rawMarketTicker } = rawTicker;
|
|
64
|
+
const marketTicker = deserializeBigIntsInObject(rawMarketTicker, { handleInts: true });
|
|
65
|
+
const capacityLong = parseTradingCapacity(rawCapacityLong);
|
|
66
|
+
const capacityShort = parseTradingCapacity(rawCapacityShort);
|
|
67
|
+
return {
|
|
68
|
+
...marketTicker,
|
|
69
|
+
...(capacityLong ? { capacityLong } : {}),
|
|
70
|
+
...(capacityShort ? { capacityShort } : {}),
|
|
71
|
+
};
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
function parseTradingCapacityAmount(value) {
|
|
75
|
+
if (typeof value === "string") {
|
|
76
|
+
return parseUint256DecimalString(value);
|
|
77
|
+
}
|
|
78
|
+
if (typeof value === "bigint") {
|
|
79
|
+
return isUint256(value) ? value : undefined;
|
|
80
|
+
}
|
|
81
|
+
if (typeof value === "number" && Number.isSafeInteger(value) && value >= 0) {
|
|
82
|
+
return BigInt(value);
|
|
83
|
+
}
|
|
84
|
+
return undefined;
|
|
85
|
+
}
|
|
86
|
+
function parseTradingCapacityLimitingFactor(value) {
|
|
87
|
+
const factor = getString(value);
|
|
88
|
+
if (factor === "reserve" || factor === "openInterest" || factor === "both" || factor === "notApplicable") {
|
|
89
|
+
return factor;
|
|
90
|
+
}
|
|
91
|
+
return undefined;
|
|
92
|
+
}
|
|
93
|
+
function parseJitDataStatus(value) {
|
|
94
|
+
const status = getString(value);
|
|
95
|
+
if (status === "available" || status === "stale" || status === "unavailable") {
|
|
96
|
+
return status;
|
|
97
|
+
}
|
|
98
|
+
return undefined;
|
|
99
|
+
}
|
|
100
|
+
function parseMarketDataStatus(value) {
|
|
101
|
+
const status = getString(value);
|
|
102
|
+
if (status === "fresh" || status === "stale") {
|
|
103
|
+
return status;
|
|
104
|
+
}
|
|
105
|
+
return undefined;
|
|
106
|
+
}
|
|
107
|
+
export function parseTradingCapacity(raw) {
|
|
108
|
+
if (!isRecord(raw)) {
|
|
109
|
+
return undefined;
|
|
110
|
+
}
|
|
111
|
+
const availableLiquidity = parseTradingCapacityAmount(raw.availableLiquidity);
|
|
112
|
+
const baseAvailableLiquidity = parseTradingCapacityAmount(raw.baseAvailableLiquidity);
|
|
113
|
+
const jitAvailableLiquidity = parseTradingCapacityAmount(raw.jitAvailableLiquidity);
|
|
114
|
+
const limitingFactor = parseTradingCapacityLimitingFactor(raw.limitingFactor);
|
|
115
|
+
const jitDataStatus = parseJitDataStatus(raw.jitDataStatus);
|
|
116
|
+
const marketDataStatus = parseMarketDataStatus(raw.marketDataStatus);
|
|
117
|
+
if (availableLiquidity === undefined ||
|
|
118
|
+
baseAvailableLiquidity === undefined ||
|
|
119
|
+
jitAvailableLiquidity === undefined ||
|
|
120
|
+
limitingFactor === undefined ||
|
|
121
|
+
jitDataStatus === undefined ||
|
|
122
|
+
marketDataStatus === undefined) {
|
|
123
|
+
return undefined;
|
|
124
|
+
}
|
|
125
|
+
return {
|
|
126
|
+
availableLiquidity,
|
|
127
|
+
baseAvailableLiquidity,
|
|
128
|
+
jitAvailableLiquidity,
|
|
129
|
+
limitingFactor,
|
|
130
|
+
jitDataStatus,
|
|
131
|
+
marketDataStatus,
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
export async function fetchApiTradingCapacity(ctx, params) {
|
|
135
|
+
return ctx.api.fetchJson("/v1/markets/trading-capacity", {
|
|
136
|
+
query: {
|
|
137
|
+
symbol: params.symbol,
|
|
138
|
+
direction: params.direction,
|
|
139
|
+
},
|
|
140
|
+
transform: (raw) => {
|
|
141
|
+
const capacity = parseTradingCapacity(raw);
|
|
142
|
+
if (!capacity) {
|
|
143
|
+
throw new Error("Invalid trading capacity response");
|
|
144
|
+
}
|
|
145
|
+
return capacity;
|
|
146
|
+
},
|
|
147
|
+
});
|
|
62
148
|
}
|
|
@@ -227,13 +227,13 @@ export function parseMarketsValuesResponse(res, marketsAddresses, marketsData, g
|
|
|
227
227
|
return acc;
|
|
228
228
|
}
|
|
229
229
|
const marketDivisor = getMarketDivisor(market);
|
|
230
|
-
const
|
|
230
|
+
const oiUsd = getOiUsdFromRawValues({
|
|
231
231
|
longInterestUsingLongToken: BigInt(dataStoreValues.longInterestUsingLongToken.returnValues[0]),
|
|
232
232
|
longInterestUsingShortToken: BigInt(dataStoreValues.longInterestUsingShortToken.returnValues[0]),
|
|
233
233
|
shortInterestUsingLongToken: BigInt(dataStoreValues.shortInterestUsingLongToken.returnValues[0]),
|
|
234
234
|
shortInterestUsingShortToken: BigInt(dataStoreValues.shortInterestUsingShortToken.returnValues[0]),
|
|
235
235
|
}, marketDivisor);
|
|
236
|
-
const
|
|
236
|
+
const oiInTokens = getOiInTokensFromRawValues({
|
|
237
237
|
longInterestInTokensUsingLongToken: BigInt(dataStoreValues.longInterestInTokensUsingLongToken.returnValues[0]),
|
|
238
238
|
longInterestInTokensUsingShortToken: BigInt(dataStoreValues.longInterestInTokensUsingShortToken.returnValues[0]),
|
|
239
239
|
shortInterestInTokensUsingLongToken: BigInt(dataStoreValues.shortInterestInTokensUsingLongToken.returnValues[0]),
|
|
@@ -243,10 +243,8 @@ export function parseMarketsValuesResponse(res, marketsAddresses, marketsData, g
|
|
|
243
243
|
const [, poolValueInfoMin] = readerValues.marketTokenPriceMin.returnValues;
|
|
244
244
|
const [, poolValueInfoMax] = readerValues.marketTokenPriceMax.returnValues;
|
|
245
245
|
acc[marketAddress] = {
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
longInterestInTokens,
|
|
249
|
-
shortInterestInTokens,
|
|
246
|
+
...oiUsd,
|
|
247
|
+
...oiInTokens,
|
|
250
248
|
longPoolAmount: dataStoreValues.longPoolAmount.returnValues[0] / marketDivisor,
|
|
251
249
|
shortPoolAmount: dataStoreValues.shortPoolAmount.returnValues[0] / marketDivisor,
|
|
252
250
|
poolValueMin: poolValueInfoMin.poolValue,
|
|
@@ -3,6 +3,14 @@ export const MARKET_VALUES_KEYS = [
|
|
|
3
3
|
"shortInterestUsd",
|
|
4
4
|
"longInterestInTokens",
|
|
5
5
|
"shortInterestInTokens",
|
|
6
|
+
"longInterestUsdUsingLongToken",
|
|
7
|
+
"longInterestUsdUsingShortToken",
|
|
8
|
+
"shortInterestUsdUsingLongToken",
|
|
9
|
+
"shortInterestUsdUsingShortToken",
|
|
10
|
+
"longInterestInTokensUsingLongToken",
|
|
11
|
+
"longInterestInTokensUsingShortToken",
|
|
12
|
+
"shortInterestInTokensUsingLongToken",
|
|
13
|
+
"shortInterestInTokensUsingShortToken",
|
|
6
14
|
"longPoolAmount",
|
|
7
15
|
"shortPoolAmount",
|
|
8
16
|
"poolValueMin",
|
|
@@ -162,13 +162,20 @@ export function getMarketDivisor({ longTokenAddress, shortTokenAddress, }) {
|
|
|
162
162
|
return longTokenAddress === shortTokenAddress ? 2n : 1n;
|
|
163
163
|
}
|
|
164
164
|
export function getOiUsdFromRawValues(rawValues, marketDivisor) {
|
|
165
|
-
const
|
|
166
|
-
const
|
|
167
|
-
const
|
|
168
|
-
const
|
|
169
|
-
const longInterestUsd =
|
|
170
|
-
const shortInterestUsd =
|
|
171
|
-
return {
|
|
165
|
+
const longInterestUsdUsingLongToken = rawValues.longInterestUsingLongToken / marketDivisor;
|
|
166
|
+
const longInterestUsdUsingShortToken = rawValues.longInterestUsingShortToken / marketDivisor;
|
|
167
|
+
const shortInterestUsdUsingLongToken = rawValues.shortInterestUsingLongToken / marketDivisor;
|
|
168
|
+
const shortInterestUsdUsingShortToken = rawValues.shortInterestUsingShortToken / marketDivisor;
|
|
169
|
+
const longInterestUsd = longInterestUsdUsingLongToken + longInterestUsdUsingShortToken;
|
|
170
|
+
const shortInterestUsd = shortInterestUsdUsingLongToken + shortInterestUsdUsingShortToken;
|
|
171
|
+
return {
|
|
172
|
+
longInterestUsd,
|
|
173
|
+
shortInterestUsd,
|
|
174
|
+
longInterestUsdUsingLongToken,
|
|
175
|
+
longInterestUsdUsingShortToken,
|
|
176
|
+
shortInterestUsdUsingLongToken,
|
|
177
|
+
shortInterestUsdUsingShortToken,
|
|
178
|
+
};
|
|
172
179
|
}
|
|
173
180
|
export function getOiInTokensFromRawValues(rawValues, marketDivisor) {
|
|
174
181
|
const longInterestInTokensUsingLongToken = rawValues.longInterestInTokensUsingLongToken / marketDivisor;
|
|
@@ -177,7 +184,14 @@ export function getOiInTokensFromRawValues(rawValues, marketDivisor) {
|
|
|
177
184
|
const shortInterestInTokensUsingShortToken = rawValues.shortInterestInTokensUsingShortToken / marketDivisor;
|
|
178
185
|
const longInterestInTokens = longInterestInTokensUsingLongToken + longInterestInTokensUsingShortToken;
|
|
179
186
|
const shortInterestInTokens = shortInterestInTokensUsingLongToken + shortInterestInTokensUsingShortToken;
|
|
180
|
-
return {
|
|
187
|
+
return {
|
|
188
|
+
longInterestInTokens,
|
|
189
|
+
shortInterestInTokens,
|
|
190
|
+
longInterestInTokensUsingLongToken,
|
|
191
|
+
longInterestInTokensUsingShortToken,
|
|
192
|
+
shortInterestInTokensUsingLongToken,
|
|
193
|
+
shortInterestInTokensUsingShortToken,
|
|
194
|
+
};
|
|
181
195
|
}
|
|
182
196
|
export function getMarketPnl(marketInfo, isLong, forMaxPoolValue) {
|
|
183
197
|
const maximize = !forMaxPoolValue;
|
|
@@ -191,6 +205,49 @@ export function getMarketPnl(marketInfo, isLong, forMaxPoolValue) {
|
|
|
191
205
|
const pnl = isLong ? openInterestValue - openInterestUsd : openInterestUsd - openInterestValue;
|
|
192
206
|
return pnl;
|
|
193
207
|
}
|
|
208
|
+
function getMarketPnlByCollateralToken(marketInfo, isLong, isLongCollateral, forMaxPoolValue) {
|
|
209
|
+
const maximize = !forMaxPoolValue;
|
|
210
|
+
let openInterestUsd;
|
|
211
|
+
let openInterestInTokens;
|
|
212
|
+
if (isLong) {
|
|
213
|
+
openInterestUsd = isLongCollateral
|
|
214
|
+
? marketInfo.longInterestUsdUsingLongToken
|
|
215
|
+
: marketInfo.longInterestUsdUsingShortToken;
|
|
216
|
+
openInterestInTokens = isLongCollateral
|
|
217
|
+
? marketInfo.longInterestInTokensUsingLongToken
|
|
218
|
+
: marketInfo.longInterestInTokensUsingShortToken;
|
|
219
|
+
}
|
|
220
|
+
else {
|
|
221
|
+
openInterestUsd = isLongCollateral
|
|
222
|
+
? marketInfo.shortInterestUsdUsingLongToken
|
|
223
|
+
: marketInfo.shortInterestUsdUsingShortToken;
|
|
224
|
+
openInterestInTokens = isLongCollateral
|
|
225
|
+
? marketInfo.shortInterestInTokensUsingLongToken
|
|
226
|
+
: marketInfo.shortInterestInTokensUsingShortToken;
|
|
227
|
+
}
|
|
228
|
+
if (openInterestUsd === undefined || openInterestInTokens === undefined) {
|
|
229
|
+
return undefined;
|
|
230
|
+
}
|
|
231
|
+
if (openInterestUsd === 0n || openInterestInTokens === 0n) {
|
|
232
|
+
return 0n;
|
|
233
|
+
}
|
|
234
|
+
const price = getPriceForPnl(marketInfo.indexToken.prices, isLong, maximize);
|
|
235
|
+
const openInterestValue = convertToUsd(openInterestInTokens, marketInfo.indexToken.decimals, price);
|
|
236
|
+
return isLong ? openInterestValue - openInterestUsd : openInterestUsd - openInterestValue;
|
|
237
|
+
}
|
|
238
|
+
/**
|
|
239
|
+
* Mirrors MarketUtils.getPositivePnl, the denominator of the per-position pnl cap since v2.2c.
|
|
240
|
+
* Pool value keeps using the net {@link getMarketPnl}. Falls back to it without the collateral split.
|
|
241
|
+
*/
|
|
242
|
+
export function getPositiveMarketPnl(marketInfo, isLong, forMaxPoolValue) {
|
|
243
|
+
const pnlUsingLongTokenAsCollateral = getMarketPnlByCollateralToken(marketInfo, isLong, true, forMaxPoolValue);
|
|
244
|
+
const pnlUsingShortTokenAsCollateral = getMarketPnlByCollateralToken(marketInfo, isLong, false, forMaxPoolValue);
|
|
245
|
+
if (pnlUsingLongTokenAsCollateral === undefined || pnlUsingShortTokenAsCollateral === undefined) {
|
|
246
|
+
return getMarketPnl(marketInfo, isLong, forMaxPoolValue);
|
|
247
|
+
}
|
|
248
|
+
return ((pnlUsingLongTokenAsCollateral > 0 ? pnlUsingLongTokenAsCollateral : 0n) +
|
|
249
|
+
(pnlUsingShortTokenAsCollateral > 0 ? pnlUsingShortTokenAsCollateral : 0n));
|
|
250
|
+
}
|
|
194
251
|
export function getOpenInterestUsd(marketInfo, isLong) {
|
|
195
252
|
return isLong ? marketInfo.longInterestUsd : marketInfo.shortInterestUsd;
|
|
196
253
|
}
|
|
@@ -13,6 +13,17 @@ export const BN_ONE = 1n;
|
|
|
13
13
|
export const BN_NEGATIVE_ONE = -1n;
|
|
14
14
|
export const MaxUint256 = BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
|
|
15
15
|
export const MaxInt256 = BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
|
|
16
|
+
const UINT_DECIMAL_STRING_REGEX = /^(0|[1-9]\d*)$/;
|
|
17
|
+
export function parseUint256DecimalString(value) {
|
|
18
|
+
if (typeof value !== "string" || !UINT_DECIMAL_STRING_REGEX.test(value)) {
|
|
19
|
+
return undefined;
|
|
20
|
+
}
|
|
21
|
+
const parsed = BigInt(value);
|
|
22
|
+
return parsed <= MaxUint256 ? parsed : undefined;
|
|
23
|
+
}
|
|
24
|
+
export function isUint256(value) {
|
|
25
|
+
return typeof value === "bigint" && value >= 0n && value <= MaxUint256;
|
|
26
|
+
}
|
|
16
27
|
export const PERCENT_PRECISION_DECIMALS = PRECISION_DECIMALS - 2;
|
|
17
28
|
const MAX_EXCEEDING_THRESHOLD = "1000000000";
|
|
18
29
|
const MIN_EXCEEDING_THRESHOLD = "0.01";
|
|
@@ -361,8 +372,8 @@ export function formatFactor(factor) {
|
|
|
361
372
|
.abs(factor)
|
|
362
373
|
.toString()
|
|
363
374
|
.match(/^(.+?)(?<zeroes>0*)$/)?.groups?.zeroes?.length || 0;
|
|
364
|
-
const factorDecimals =
|
|
365
|
-
return formatAmount(factor,
|
|
375
|
+
const factorDecimals = Math.max(PRECISION_DECIMALS - trailingZeroes, 0);
|
|
376
|
+
return formatAmount(factor, PRECISION_DECIMALS, factorDecimals);
|
|
366
377
|
}
|
|
367
378
|
export function numberWithCommas(x, { showDollar = false } = {}) {
|
|
368
379
|
if (x === undefined || x === null) {
|
|
@@ -530,8 +541,14 @@ export const parseValue = (value, tokenDecimals) => {
|
|
|
530
541
|
if (isNaN(pValue) || !isFinite(pValue)) {
|
|
531
542
|
return undefined;
|
|
532
543
|
}
|
|
533
|
-
|
|
534
|
-
|
|
544
|
+
let amount;
|
|
545
|
+
try {
|
|
546
|
+
value = limitDecimals(value, tokenDecimals);
|
|
547
|
+
amount = parseUnits(value, tokenDecimals);
|
|
548
|
+
}
|
|
549
|
+
catch {
|
|
550
|
+
return undefined;
|
|
551
|
+
}
|
|
535
552
|
// Cap at a safe maximum to prevent downstream BigInt overflow errors
|
|
536
553
|
const MAX_ALLOWED = expandDecimals(1, 62);
|
|
537
554
|
if (amount > MAX_ALLOWED || amount < -MAX_ALLOWED) {
|
|
@@ -568,10 +585,10 @@ export function maxbigint(...args) {
|
|
|
568
585
|
return args.reduce((acc, num) => (num > acc ? num : acc), args[0]);
|
|
569
586
|
}
|
|
570
587
|
export function removeTrailingZeros(amount) {
|
|
571
|
-
|
|
572
|
-
if (!amountWithoutZeros)
|
|
588
|
+
if (typeof amount === "number" || !amount.includes(".") || amount.includes(",") || /^[-+]?0*\.0*$/.test(amount)) {
|
|
573
589
|
return amount;
|
|
574
|
-
|
|
590
|
+
}
|
|
591
|
+
return amount.replace(/0+$/, "").replace(/\.$/, "");
|
|
575
592
|
}
|
|
576
593
|
const NUMERIC_STRING_REGEX = /^-?\d+$/;
|
|
577
594
|
export function serializeBigIntsInObject(obj) {
|
|
@@ -1,7 +1,108 @@
|
|
|
1
|
+
import { HttpError } from "../http/http";
|
|
2
|
+
import { parseTradingCapacity } from "../markets/api";
|
|
3
|
+
import { isUint256, parseUint256DecimalString } from "../numbers";
|
|
4
|
+
import { getRecord, getString, isRecord } from "../objects";
|
|
1
5
|
import { validateOrderTypedData } from "./validateTypedData";
|
|
6
|
+
const PREPARE_ORDER_ERROR_CODES = [
|
|
7
|
+
"INVALID_PARAMS",
|
|
8
|
+
"MARKET_NOT_FOUND",
|
|
9
|
+
"TOKEN_NOT_FOUND",
|
|
10
|
+
"NO_SWAP_PATH",
|
|
11
|
+
"POSITION_NOT_FOUND",
|
|
12
|
+
];
|
|
13
|
+
function isDeserializedTradingCapacity(value) {
|
|
14
|
+
const raw = getRecord(value);
|
|
15
|
+
if (!raw) {
|
|
16
|
+
return false;
|
|
17
|
+
}
|
|
18
|
+
const parsed = parseTradingCapacity(raw);
|
|
19
|
+
return parsed !== undefined && Object.entries(parsed).every(([key, parsedValue]) => raw[key] === parsedValue);
|
|
20
|
+
}
|
|
21
|
+
function isPrepareOrderFieldValidationErrors(value) {
|
|
22
|
+
if (!isRecord(value)) {
|
|
23
|
+
return false;
|
|
24
|
+
}
|
|
25
|
+
return Object.values(value).every((fieldError) => isRecord(fieldError) && typeof fieldError.message === "string");
|
|
26
|
+
}
|
|
27
|
+
function parsePrepareOrderErrorBody(value) {
|
|
28
|
+
if (!isRecord(value)) {
|
|
29
|
+
return undefined;
|
|
30
|
+
}
|
|
31
|
+
const body = value;
|
|
32
|
+
if (body.code === "INSUFFICIENT_LIQUIDITY") {
|
|
33
|
+
const details = getRecord(body.details);
|
|
34
|
+
const capacity = parseTradingCapacity(details);
|
|
35
|
+
const requestedSizeUsd = parseUint256DecimalString(details?.requestedSizeUsd);
|
|
36
|
+
if (!capacity || requestedSizeUsd === undefined || typeof body.message !== "string") {
|
|
37
|
+
return undefined;
|
|
38
|
+
}
|
|
39
|
+
return {
|
|
40
|
+
code: body.code,
|
|
41
|
+
message: body.message,
|
|
42
|
+
details: {
|
|
43
|
+
...capacity,
|
|
44
|
+
requestedSizeUsd,
|
|
45
|
+
},
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
if (PREPARE_ORDER_ERROR_CODES.includes(body.code) && typeof body.message === "string") {
|
|
49
|
+
return {
|
|
50
|
+
code: body.code,
|
|
51
|
+
message: body.message,
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
if (typeof body.code === "string" && body.code.length > 0 && typeof body.message === "string") {
|
|
55
|
+
return {
|
|
56
|
+
code: "UNKNOWN_PREPARE_ORDER_ERROR",
|
|
57
|
+
originalCode: body.code,
|
|
58
|
+
message: body.message,
|
|
59
|
+
...(typeof body.traceId === "string" ? { traceId: body.traceId } : {}),
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
if (body.code !== undefined) {
|
|
63
|
+
return undefined;
|
|
64
|
+
}
|
|
65
|
+
if (typeof body.message === "string") {
|
|
66
|
+
return { message: body.message };
|
|
67
|
+
}
|
|
68
|
+
if (isPrepareOrderFieldValidationErrors(body.message)) {
|
|
69
|
+
return { message: body.message };
|
|
70
|
+
}
|
|
71
|
+
return undefined;
|
|
72
|
+
}
|
|
73
|
+
export function parsePrepareOrderError(error) {
|
|
74
|
+
if (!(error instanceof HttpError) || error.statusCode !== 400) {
|
|
75
|
+
return undefined;
|
|
76
|
+
}
|
|
77
|
+
return parsePrepareOrderErrorBody(error.body);
|
|
78
|
+
}
|
|
79
|
+
/** Validates an already deserialized prepare error. Use parsePrepareOrderError for a caught HttpError. */
|
|
80
|
+
export function isPrepareOrderError(value) {
|
|
81
|
+
if (!isRecord(value)) {
|
|
82
|
+
return false;
|
|
83
|
+
}
|
|
84
|
+
const error = value;
|
|
85
|
+
if (error.code === "INSUFFICIENT_LIQUIDITY") {
|
|
86
|
+
const details = getRecord(error.details);
|
|
87
|
+
const requestedSizeUsd = details?.requestedSizeUsd;
|
|
88
|
+
return Boolean(isDeserializedTradingCapacity(details) && isUint256(requestedSizeUsd) && typeof error.message === "string");
|
|
89
|
+
}
|
|
90
|
+
if (PREPARE_ORDER_ERROR_CODES.includes(error.code)) {
|
|
91
|
+
return typeof error.message === "string";
|
|
92
|
+
}
|
|
93
|
+
if (error.code === "UNKNOWN_PREPARE_ORDER_ERROR") {
|
|
94
|
+
return (typeof error.originalCode === "string" &&
|
|
95
|
+
error.originalCode.length > 0 &&
|
|
96
|
+
typeof error.message === "string" &&
|
|
97
|
+
(error.traceId === undefined || typeof error.traceId === "string"));
|
|
98
|
+
}
|
|
99
|
+
return (error.code === undefined &&
|
|
100
|
+
(typeof error.message === "string" || isPrepareOrderFieldValidationErrors(error.message)));
|
|
101
|
+
}
|
|
2
102
|
function parseEstimates(raw) {
|
|
3
103
|
if (!raw)
|
|
4
104
|
return undefined;
|
|
105
|
+
const tradingCapacity = raw.tradingCapacity === undefined ? undefined : parseTradingCapacity(raw.tradingCapacity);
|
|
5
106
|
return {
|
|
6
107
|
positionPriceImpactDeltaUsd: BigInt(raw.positionPriceImpactDeltaUsd ?? "0"),
|
|
7
108
|
swapPriceImpactDeltaUsd: BigInt(raw.swapPriceImpactDeltaUsd ?? "0"),
|
|
@@ -11,10 +112,65 @@ function parseEstimates(raw) {
|
|
|
11
112
|
positionFeeUsd: BigInt(raw.positionFeeUsd ?? "0"),
|
|
12
113
|
borrowingFeeUsd: BigInt(raw.borrowingFeeUsd ?? "0"),
|
|
13
114
|
fundingFeeUsd: BigInt(raw.fundingFeeUsd ?? "0"),
|
|
115
|
+
tradingCapacity,
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
function parseValidationWarning(raw) {
|
|
119
|
+
const warning = getRecord(raw);
|
|
120
|
+
const code = getString(warning?.code);
|
|
121
|
+
const message = getString(warning?.message);
|
|
122
|
+
if (!warning || !code || !message) {
|
|
123
|
+
return undefined;
|
|
124
|
+
}
|
|
125
|
+
const details = getRecord(warning.details);
|
|
126
|
+
if (code === "INSUFFICIENT_LIQUIDITY") {
|
|
127
|
+
const capacity = parseTradingCapacity(details);
|
|
128
|
+
const requestedSizeUsd = parseUint256DecimalString(details?.requestedSizeUsd);
|
|
129
|
+
if (capacity && requestedSizeUsd !== undefined) {
|
|
130
|
+
return {
|
|
131
|
+
code,
|
|
132
|
+
message,
|
|
133
|
+
details: {
|
|
134
|
+
...capacity,
|
|
135
|
+
requestedSizeUsd,
|
|
136
|
+
},
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
const reason = getString(details?.reason);
|
|
141
|
+
if (code === "TRADING_CAPACITY_UNAVAILABLE" &&
|
|
142
|
+
(reason === "STALE_MARKET_DATA" ||
|
|
143
|
+
reason === "JIT_DATA_UNAVAILABLE" ||
|
|
144
|
+
reason === "JIT_ACCOUNT_ELIGIBILITY_UNKNOWN" ||
|
|
145
|
+
reason === "COLLATERAL_SWAP")) {
|
|
146
|
+
return {
|
|
147
|
+
code,
|
|
148
|
+
message,
|
|
149
|
+
details: { reason },
|
|
150
|
+
};
|
|
151
|
+
}
|
|
152
|
+
return {
|
|
153
|
+
code: "UNKNOWN_VALIDATION_WARNING",
|
|
154
|
+
originalCode: code,
|
|
155
|
+
message,
|
|
156
|
+
...(warning.details === undefined ? {} : { details: warning.details }),
|
|
14
157
|
};
|
|
15
158
|
}
|
|
159
|
+
function parseValidationWarnings(raw) {
|
|
160
|
+
if (raw === undefined) {
|
|
161
|
+
return undefined;
|
|
162
|
+
}
|
|
163
|
+
if (!Array.isArray(raw)) {
|
|
164
|
+
return undefined;
|
|
165
|
+
}
|
|
166
|
+
return raw.map(parseValidationWarning).filter((warning) => warning !== undefined);
|
|
167
|
+
}
|
|
16
168
|
function parsePrepareResponse(raw) {
|
|
17
|
-
return {
|
|
169
|
+
return {
|
|
170
|
+
...raw,
|
|
171
|
+
estimates: parseEstimates(raw.estimates),
|
|
172
|
+
validationWarnings: parseValidationWarnings(raw.validationWarnings),
|
|
173
|
+
};
|
|
18
174
|
}
|
|
19
175
|
export async function prepareOrder(ctx, request) {
|
|
20
176
|
return ctx.api.postJson("/v1/orders/txns/prepare", request, {
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { BASIS_POINTS_DIVISOR_BIGINT } from "../../configs/factors";
|
|
2
2
|
import { bigMath } from "../bigmath";
|
|
3
3
|
import { capPositionImpactUsdByMaxImpactPool, capPositionImpactUsdByMaxPriceImpactFactor, getMaxPositionImpactFactors, getPositionFee, getPriceImpactForPosition, getProportionalPendingImpactValues, } from "../fees";
|
|
4
|
-
import { getCappedPoolPnl, getMarketIndexName,
|
|
4
|
+
import { getCappedPoolPnl, getMarketIndexName, getMarketPoolName, getMaxAllowedLeverage, getOpenInterestUsd, getPoolUsdWithoutPnl, getPositiveMarketPnl, } from "../markets";
|
|
5
5
|
import { applyFactor, expandDecimals, FLOAT_PRECISION_SQRT, getBasisPoints, PRECISION } from "../numbers";
|
|
6
6
|
import { getAcceptablePriceInfo, getMarkPrice } from "../prices";
|
|
7
7
|
import { convertToTokenAmount, convertToUsd, getIsEquivalentTokens } from "../tokens";
|
|
@@ -26,7 +26,7 @@ export function getPositionPnlUsd(p) {
|
|
|
26
26
|
if (totalPnl <= 0) {
|
|
27
27
|
return totalPnl;
|
|
28
28
|
}
|
|
29
|
-
const poolPnl =
|
|
29
|
+
const poolPnl = getPositiveMarketPnl(marketInfo, isLong, true);
|
|
30
30
|
const poolUsd = getPoolUsdWithoutPnl(marketInfo, isLong, "minPrice");
|
|
31
31
|
const cappedPnl = getCappedPoolPnl({
|
|
32
32
|
marketInfo,
|