@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.
Files changed (90) hide show
  1. package/README.md +48 -0
  2. package/build/cjs/scripts/subsquid-codegen.js +1 -1
  3. package/build/cjs/src/clients/v1/testUtil.js +1 -1
  4. package/build/cjs/src/clients/v2/__tests__/data.spec.js +5 -5
  5. package/build/cjs/src/clients/v2/__tests__/decrease.spec.js +6 -6
  6. package/build/cjs/src/clients/v2/__tests__/editCancel.spec.js +12 -12
  7. package/build/cjs/src/clients/v2/__tests__/errors.spec.js +1 -47
  8. package/build/cjs/src/clients/v2/__tests__/errorsLifecycle.spec.js +53 -0
  9. package/build/cjs/src/clients/v2/__tests__/globalCleanup.js +80 -0
  10. package/build/cjs/src/clients/v2/__tests__/increase.spec.js +14 -14
  11. package/build/cjs/src/clients/v2/__tests__/multichain.spec.js +5 -6
  12. package/build/cjs/src/clients/v2/__tests__/prepareErrors.spec.js +167 -0
  13. package/build/cjs/src/clients/v2/__tests__/setupAllowance.js +32 -0
  14. package/build/cjs/src/clients/v2/__tests__/subaccount.spec.js +16 -123
  15. package/build/cjs/src/clients/v2/__tests__/subaccountLifecycle.spec.js +108 -0
  16. package/build/cjs/src/clients/v2/__tests__/testUtil.js +38 -5
  17. package/build/cjs/src/clients/v2/__tests__/tradingCapacity.spec.js +371 -0
  18. package/build/cjs/src/clients/v2/index.js +10 -1
  19. package/build/cjs/src/codegen/subsquid.js +284 -20
  20. package/build/cjs/src/configs/__tests__/markets.spec.js +8 -0
  21. package/build/cjs/src/utils/__tests__/markets.spec.js +60 -0
  22. package/build/cjs/src/utils/__tests__/numbers.spec.js +39 -0
  23. package/build/cjs/src/utils/__tests__/positionPnlCap.spec.js +78 -0
  24. package/build/cjs/src/utils/__tests__/positions.spec.js +16 -4
  25. package/build/cjs/src/utils/markets/api.js +90 -2
  26. package/build/cjs/src/utils/markets/multicall.js +4 -6
  27. package/build/cjs/src/utils/markets/types.js +8 -0
  28. package/build/cjs/src/utils/markets/utils.js +67 -9
  29. package/build/cjs/src/utils/numbers/utils.js +28 -9
  30. package/build/cjs/src/utils/orderTransactions/api.js +160 -2
  31. package/build/cjs/src/utils/positions/utils.js +1 -1
  32. package/build/cjs/src/utils/tradeHistory/__tests__/utils.spec.js +64 -0
  33. package/build/cjs/src/utils/tradeHistory/utils.js +2 -0
  34. package/build/cjs/src/utils/yield/api.js +13 -0
  35. package/build/cjs/src/utils/yield/types.js +2 -0
  36. package/build/esm/scripts/subsquid-codegen.js +1 -1
  37. package/build/esm/src/clients/v1/testUtil.js +1 -1
  38. package/build/esm/src/clients/v2/__tests__/data.spec.js +6 -6
  39. package/build/esm/src/clients/v2/__tests__/decrease.spec.js +7 -7
  40. package/build/esm/src/clients/v2/__tests__/editCancel.spec.js +13 -13
  41. package/build/esm/src/clients/v2/__tests__/errors.spec.js +2 -48
  42. package/build/esm/src/clients/v2/__tests__/errorsLifecycle.spec.js +51 -0
  43. package/build/esm/src/clients/v2/__tests__/globalCleanup.js +77 -0
  44. package/build/esm/src/clients/v2/__tests__/increase.spec.js +15 -15
  45. package/build/esm/src/clients/v2/__tests__/multichain.spec.js +6 -7
  46. package/build/esm/src/clients/v2/__tests__/prepareErrors.spec.js +165 -0
  47. package/build/esm/src/clients/v2/__tests__/setupAllowance.js +30 -0
  48. package/build/esm/src/clients/v2/__tests__/subaccount.spec.js +17 -124
  49. package/build/esm/src/clients/v2/__tests__/subaccountLifecycle.spec.js +106 -0
  50. package/build/esm/src/clients/v2/__tests__/testUtil.js +33 -4
  51. package/build/esm/src/clients/v2/__tests__/tradingCapacity.spec.js +369 -0
  52. package/build/esm/src/clients/v2/index.js +10 -2
  53. package/build/esm/src/codegen/subsquid.js +282 -18
  54. package/build/esm/src/configs/__tests__/markets.spec.js +9 -1
  55. package/build/esm/src/utils/__tests__/markets.spec.js +61 -1
  56. package/build/esm/src/utils/__tests__/numbers.spec.js +40 -1
  57. package/build/esm/src/utils/__tests__/positionPnlCap.spec.js +76 -0
  58. package/build/esm/src/utils/__tests__/positions.spec.js +17 -5
  59. package/build/esm/src/utils/markets/api.js +88 -2
  60. package/build/esm/src/utils/markets/multicall.js +4 -6
  61. package/build/esm/src/utils/markets/types.js +8 -0
  62. package/build/esm/src/utils/markets/utils.js +65 -8
  63. package/build/esm/src/utils/numbers/utils.js +24 -7
  64. package/build/esm/src/utils/orderTransactions/api.js +157 -1
  65. package/build/esm/src/utils/positions/utils.js +2 -2
  66. package/build/esm/src/utils/tradeHistory/__tests__/utils.spec.js +62 -0
  67. package/build/esm/src/utils/tradeHistory/utils.js +2 -0
  68. package/build/esm/src/utils/yield/api.js +9 -0
  69. package/build/esm/src/utils/yield/types.js +1 -0
  70. package/build/tsconfig.tsbuildinfo +1 -1
  71. package/build/types/src/clients/v2/__tests__/errorsLifecycle.spec.d.ts +1 -0
  72. package/build/types/src/clients/v2/__tests__/globalCleanup.d.ts +1 -0
  73. package/build/types/src/clients/v2/__tests__/prepareErrors.spec.d.ts +1 -0
  74. package/build/types/src/clients/v2/__tests__/setupAllowance.d.ts +1 -0
  75. package/build/types/src/clients/v2/__tests__/subaccountLifecycle.spec.d.ts +1 -0
  76. package/build/types/src/clients/v2/__tests__/testUtil.d.ts +7 -1
  77. package/build/types/src/clients/v2/__tests__/tradingCapacity.spec.d.ts +1 -0
  78. package/build/types/src/clients/v2/index.d.ts +11 -5
  79. package/build/types/src/codegen/subsquid.d.ts +1141 -51
  80. package/build/types/src/utils/__tests__/positionPnlCap.spec.d.ts +1 -0
  81. package/build/types/src/utils/markets/api.d.ts +6 -2
  82. package/build/types/src/utils/markets/types.d.ts +28 -1
  83. package/build/types/src/utils/markets/utils.d.ts +7 -8
  84. package/build/types/src/utils/numbers/utils.d.ts +2 -0
  85. package/build/types/src/utils/orderTransactions/api.d.ts +50 -0
  86. package/build/types/src/utils/tradeHistory/__tests__/utils.spec.d.ts +1 -0
  87. package/build/types/src/utils/tradeHistory/types.d.ts +2 -0
  88. package/build/types/src/utils/yield/api.d.ts +5 -0
  89. package/build/types/src/utils/yield/types.d.ts +29 -0
  90. package/package.json +2 -1
@@ -0,0 +1,78 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const vitest_1 = require("vitest");
4
+ const factors_1 = require("../../configs/factors");
5
+ const mock_1 = require("../../test/mock");
6
+ const markets_1 = require("../markets");
7
+ const numbers_1 = require("../numbers");
8
+ const positions_1 = require("../positions");
9
+ const MARKET_KEY = "ETH-ETH-USDC";
10
+ function usd(amount) {
11
+ return (0, numbers_1.expandDecimals)(amount, factors_1.USD_DECIMALS);
12
+ }
13
+ function eth(amount) {
14
+ return (0, numbers_1.expandDecimals)(amount, 18);
15
+ }
16
+ const ETH_PRICE = usd(2000);
17
+ /**
18
+ * Long side splits into an eth collateral bucket worth +$1,000,000 and a usdc collateral bucket worth
19
+ * -$500,000, so net pnl is $500,000 and positive-only pnl is $1,000,000. The long pool is $1,000,000
20
+ * with a 90% trader pnl factor, so the cap binds on the positive-only figure only.
21
+ */
22
+ function createMarketInfo(overrides = {}) {
23
+ const tokensData = (0, mock_1.mockTokensData)({ ETH: { prices: { minPrice: ETH_PRICE, maxPrice: ETH_PRICE } } });
24
+ return (0, mock_1.mockMarketsInfoData)(tokensData, [MARKET_KEY], {
25
+ [MARKET_KEY]: {
26
+ longPoolAmount: eth(500),
27
+ maxPnlFactorForTradersLong: (0, numbers_1.expandDecimals)(9, 29),
28
+ longInterestUsd: usd(2000000),
29
+ longInterestInTokens: eth(1250),
30
+ longInterestUsdUsingLongToken: usd(1000000),
31
+ longInterestInTokensUsingLongToken: eth(1000),
32
+ longInterestUsdUsingShortToken: usd(1000000),
33
+ longInterestInTokensUsingShortToken: eth(250),
34
+ ...overrides,
35
+ },
36
+ })[MARKET_KEY];
37
+ }
38
+ function getLongPositionPnl(marketInfo) {
39
+ return (0, positions_1.getPositionPnlUsd)({
40
+ marketInfo,
41
+ sizeInUsd: usd(100000),
42
+ sizeInTokens: eth(100),
43
+ markPrice: ETH_PRICE,
44
+ isLong: true,
45
+ });
46
+ }
47
+ (0, vitest_1.describe)("per-position pnl cap (v2.2c parity)", () => {
48
+ (0, vitest_1.it)("caps against the positive-only pool pnl", () => {
49
+ const marketInfo = createMarketInfo();
50
+ (0, vitest_1.expect)((0, markets_1.getPositiveMarketPnl)(marketInfo, true, true)).toBe(usd(1000000));
51
+ (0, vitest_1.expect)(getLongPositionPnl(marketInfo)).toBe(usd(90000));
52
+ });
53
+ (0, vitest_1.it)("leaves the net pool pnl used by gm pool value untouched", () => {
54
+ const marketInfo = createMarketInfo();
55
+ (0, vitest_1.expect)((0, markets_1.getMarketPnl)(marketInfo, true, true)).toBe(usd(500000));
56
+ });
57
+ (0, vitest_1.it)("keeps the net behaviour when the data source has no per-collateral open interest", () => {
58
+ const marketInfo = createMarketInfo({
59
+ longInterestUsdUsingLongToken: undefined,
60
+ longInterestInTokensUsingLongToken: undefined,
61
+ longInterestUsdUsingShortToken: undefined,
62
+ longInterestInTokensUsingShortToken: undefined,
63
+ });
64
+ (0, vitest_1.expect)((0, markets_1.getPositiveMarketPnl)(marketInfo, true, true)).toBe(usd(500000));
65
+ (0, vitest_1.expect)(getLongPositionPnl(marketInfo)).toBe(usd(100000));
66
+ });
67
+ (0, vitest_1.it)("matches the net pool pnl when both collateral buckets are winning", () => {
68
+ const marketInfo = createMarketInfo({
69
+ longInterestUsdUsingShortToken: usd(1000000),
70
+ longInterestInTokensUsingShortToken: eth(600),
71
+ longInterestUsd: usd(2000000),
72
+ longInterestInTokens: eth(1600),
73
+ });
74
+ (0, vitest_1.expect)((0, markets_1.getPositiveMarketPnl)(marketInfo, true, true)).toBe(usd(1200000));
75
+ (0, vitest_1.expect)((0, markets_1.getMarketPnl)(marketInfo, true, true)).toBe(usd(1200000));
76
+ (0, vitest_1.expect)(getLongPositionPnl(marketInfo)).toBe(usd(75000));
77
+ });
78
+ });
@@ -9,7 +9,7 @@ const positions_1 = require("../positions");
9
9
  const tokens_1 = require("../tokens");
10
10
  vitest_1.vi.mock("../markets", () => ({
11
11
  ...vitest_1.vi.importActual("../markets"),
12
- getMarketPnl: vitest_1.vi.fn(),
12
+ getPositiveMarketPnl: vitest_1.vi.fn(),
13
13
  getPoolUsdWithoutPnl: vitest_1.vi.fn(),
14
14
  getCappedPoolPnl: vitest_1.vi.fn(),
15
15
  }));
@@ -61,9 +61,9 @@ vitest_1.vi.mock("../fees", () => ({
61
61
  (0, vitest_1.describe)("getPositionPnlUsd", () => {
62
62
  const marketInfo = { indexToken: {}, maxPositionImpactFactorForLiquidations: 2n };
63
63
  (0, vitest_1.beforeEach)(() => {
64
- markets_1.getMarketPnl.mockReturnValue(1000n);
65
- markets_1.getPoolUsdWithoutPnl.mockReturnValue(5000n);
66
- markets_1.getCappedPoolPnl.mockReturnValue(800n);
64
+ markets_1.getPositiveMarketPnl.mockReturnValue((0, numbers_1.expandDecimals)(1000, numbers_1.USD_DECIMALS));
65
+ markets_1.getPoolUsdWithoutPnl.mockReturnValue((0, numbers_1.expandDecimals)(5000, numbers_1.USD_DECIMALS));
66
+ markets_1.getCappedPoolPnl.mockReturnValue((0, numbers_1.expandDecimals)(800, numbers_1.USD_DECIMALS));
67
67
  });
68
68
  (0, vitest_1.it)("returns negative PnL if positionValueUsd < sizeInUsd for a long", () => {
69
69
  tokens_1.convertToUsd.mockReturnValueOnce(900n); // positionValueUsd
@@ -76,6 +76,18 @@ vitest_1.vi.mock("../fees", () => ({
76
76
  });
77
77
  (0, vitest_1.expect)(result).toBe(900n - 1000n); // -100n
78
78
  });
79
+ (0, vitest_1.it)("scales a winning position by the positive-only pool pnl", () => {
80
+ tokens_1.convertToUsd.mockReturnValueOnce((0, numbers_1.expandDecimals)(2000, numbers_1.USD_DECIMALS)); // positionValueUsd
81
+ const result = (0, positions_1.getPositionPnlUsd)({
82
+ marketInfo,
83
+ sizeInUsd: (0, numbers_1.expandDecimals)(1000, numbers_1.USD_DECIMALS),
84
+ sizeInTokens: 100n,
85
+ markPrice: 10n,
86
+ isLong: true,
87
+ });
88
+ (0, vitest_1.expect)(markets_1.getPositiveMarketPnl).toHaveBeenCalledWith(marketInfo, true, true);
89
+ (0, vitest_1.expect)(result).toBe((0, numbers_1.expandDecimals)(800, numbers_1.USD_DECIMALS));
90
+ });
79
91
  });
80
92
  (0, vitest_1.describe)("getPositionPendingFeesUsd", () => {
81
93
  (0, vitest_1.it)("sums up funding and borrowing fees", () => {
@@ -1,8 +1,9 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.fetchApiMarketsTickers = exports.fetchApiMarkets = exports.fetchApiTokensData = exports.fetchApiMarketsValues = exports.fetchApiMarketsConfig = exports.fetchApiMarketsInfo = void 0;
3
+ exports.fetchApiTradingCapacity = exports.parseTradingCapacity = exports.fetchApiMarketsTickers = exports.fetchApiMarkets = exports.fetchApiTokensData = exports.fetchApiMarketsValues = exports.fetchApiMarketsConfig = exports.fetchApiMarketsInfo = void 0;
4
4
  const validation_1 = require("../http/validation");
5
5
  const numbers_1 = require("../numbers");
6
+ const objects_1 = require("../objects");
6
7
  const MARKET_CONFIG_V22C_FIELDS = [
7
8
  { name: "marketTokenAddress", type: "string" },
8
9
  { name: "useOpenInterestInTokensForBalance", type: "boolean" },
@@ -66,6 +67,93 @@ async function fetchApiMarketsTickers(ctx, params) {
66
67
  symbols: params?.symbols,
67
68
  },
68
69
  });
69
- return tickers.map((t) => (0, numbers_1.deserializeBigIntsInObject)(t, { handleInts: true }));
70
+ return tickers.map((rawTicker) => {
71
+ const { capacityLong: rawCapacityLong, capacityShort: rawCapacityShort, ...rawMarketTicker } = rawTicker;
72
+ const marketTicker = (0, numbers_1.deserializeBigIntsInObject)(rawMarketTicker, { handleInts: true });
73
+ const capacityLong = parseTradingCapacity(rawCapacityLong);
74
+ const capacityShort = parseTradingCapacity(rawCapacityShort);
75
+ return {
76
+ ...marketTicker,
77
+ ...(capacityLong ? { capacityLong } : {}),
78
+ ...(capacityShort ? { capacityShort } : {}),
79
+ };
80
+ });
70
81
  }
71
82
  exports.fetchApiMarketsTickers = fetchApiMarketsTickers;
83
+ function parseTradingCapacityAmount(value) {
84
+ if (typeof value === "string") {
85
+ return (0, numbers_1.parseUint256DecimalString)(value);
86
+ }
87
+ if (typeof value === "bigint") {
88
+ return (0, numbers_1.isUint256)(value) ? value : undefined;
89
+ }
90
+ if (typeof value === "number" && Number.isSafeInteger(value) && value >= 0) {
91
+ return BigInt(value);
92
+ }
93
+ return undefined;
94
+ }
95
+ function parseTradingCapacityLimitingFactor(value) {
96
+ const factor = (0, objects_1.getString)(value);
97
+ if (factor === "reserve" || factor === "openInterest" || factor === "both" || factor === "notApplicable") {
98
+ return factor;
99
+ }
100
+ return undefined;
101
+ }
102
+ function parseJitDataStatus(value) {
103
+ const status = (0, objects_1.getString)(value);
104
+ if (status === "available" || status === "stale" || status === "unavailable") {
105
+ return status;
106
+ }
107
+ return undefined;
108
+ }
109
+ function parseMarketDataStatus(value) {
110
+ const status = (0, objects_1.getString)(value);
111
+ if (status === "fresh" || status === "stale") {
112
+ return status;
113
+ }
114
+ return undefined;
115
+ }
116
+ function parseTradingCapacity(raw) {
117
+ if (!(0, objects_1.isRecord)(raw)) {
118
+ return undefined;
119
+ }
120
+ const availableLiquidity = parseTradingCapacityAmount(raw.availableLiquidity);
121
+ const baseAvailableLiquidity = parseTradingCapacityAmount(raw.baseAvailableLiquidity);
122
+ const jitAvailableLiquidity = parseTradingCapacityAmount(raw.jitAvailableLiquidity);
123
+ const limitingFactor = parseTradingCapacityLimitingFactor(raw.limitingFactor);
124
+ const jitDataStatus = parseJitDataStatus(raw.jitDataStatus);
125
+ const marketDataStatus = parseMarketDataStatus(raw.marketDataStatus);
126
+ if (availableLiquidity === undefined ||
127
+ baseAvailableLiquidity === undefined ||
128
+ jitAvailableLiquidity === undefined ||
129
+ limitingFactor === undefined ||
130
+ jitDataStatus === undefined ||
131
+ marketDataStatus === undefined) {
132
+ return undefined;
133
+ }
134
+ return {
135
+ availableLiquidity,
136
+ baseAvailableLiquidity,
137
+ jitAvailableLiquidity,
138
+ limitingFactor,
139
+ jitDataStatus,
140
+ marketDataStatus,
141
+ };
142
+ }
143
+ exports.parseTradingCapacity = parseTradingCapacity;
144
+ async function fetchApiTradingCapacity(ctx, params) {
145
+ return ctx.api.fetchJson("/v1/markets/trading-capacity", {
146
+ query: {
147
+ symbol: params.symbol,
148
+ direction: params.direction,
149
+ },
150
+ transform: (raw) => {
151
+ const capacity = parseTradingCapacity(raw);
152
+ if (!capacity) {
153
+ throw new Error("Invalid trading capacity response");
154
+ }
155
+ return capacity;
156
+ },
157
+ });
158
+ }
159
+ exports.fetchApiTradingCapacity = fetchApiTradingCapacity;
@@ -234,13 +234,13 @@ function parseMarketsValuesResponse(res, marketsAddresses, marketsData, getMarke
234
234
  return acc;
235
235
  }
236
236
  const marketDivisor = getMarketDivisor(market);
237
- const { longInterestUsd, shortInterestUsd } = (0, markets_1.getOiUsdFromRawValues)({
237
+ const oiUsd = (0, markets_1.getOiUsdFromRawValues)({
238
238
  longInterestUsingLongToken: BigInt(dataStoreValues.longInterestUsingLongToken.returnValues[0]),
239
239
  longInterestUsingShortToken: BigInt(dataStoreValues.longInterestUsingShortToken.returnValues[0]),
240
240
  shortInterestUsingLongToken: BigInt(dataStoreValues.shortInterestUsingLongToken.returnValues[0]),
241
241
  shortInterestUsingShortToken: BigInt(dataStoreValues.shortInterestUsingShortToken.returnValues[0]),
242
242
  }, marketDivisor);
243
- const { longInterestInTokens, shortInterestInTokens } = (0, markets_1.getOiInTokensFromRawValues)({
243
+ const oiInTokens = (0, markets_1.getOiInTokensFromRawValues)({
244
244
  longInterestInTokensUsingLongToken: BigInt(dataStoreValues.longInterestInTokensUsingLongToken.returnValues[0]),
245
245
  longInterestInTokensUsingShortToken: BigInt(dataStoreValues.longInterestInTokensUsingShortToken.returnValues[0]),
246
246
  shortInterestInTokensUsingLongToken: BigInt(dataStoreValues.shortInterestInTokensUsingLongToken.returnValues[0]),
@@ -250,10 +250,8 @@ function parseMarketsValuesResponse(res, marketsAddresses, marketsData, getMarke
250
250
  const [, poolValueInfoMin] = readerValues.marketTokenPriceMin.returnValues;
251
251
  const [, poolValueInfoMax] = readerValues.marketTokenPriceMax.returnValues;
252
252
  acc[marketAddress] = {
253
- longInterestUsd,
254
- shortInterestUsd,
255
- longInterestInTokens,
256
- shortInterestInTokens,
253
+ ...oiUsd,
254
+ ...oiInTokens,
257
255
  longPoolAmount: dataStoreValues.longPoolAmount.returnValues[0] / marketDivisor,
258
256
  shortPoolAmount: dataStoreValues.shortPoolAmount.returnValues[0] / marketDivisor,
259
257
  poolValueMin: poolValueInfoMin.poolValue,
@@ -6,6 +6,14 @@ exports.MARKET_VALUES_KEYS = [
6
6
  "shortInterestUsd",
7
7
  "longInterestInTokens",
8
8
  "shortInterestInTokens",
9
+ "longInterestUsdUsingLongToken",
10
+ "longInterestUsdUsingShortToken",
11
+ "shortInterestUsdUsingLongToken",
12
+ "shortInterestUsdUsingShortToken",
13
+ "longInterestInTokensUsingLongToken",
14
+ "longInterestInTokensUsingShortToken",
15
+ "shortInterestInTokensUsingLongToken",
16
+ "shortInterestInTokensUsingShortToken",
9
17
  "longPoolAmount",
10
18
  "shortPoolAmount",
11
19
  "poolValueMin",
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getMarketAddressByName = exports.getMarketWithTiers = exports.composeFullMarketsInfoData = exports.hydrateMarketInfo = exports.mergeMarketsConfigValues = exports.composeRawMarketsInfoData = exports.composeRawMarketInfo = exports.getMarketTicker = exports.getMarket24Stats = exports.getIsMarketDeprecated = exports.getIsMarketAvailableForExpressSwaps = exports.getPriceForPnl = exports.getOpenInterestForBalance = exports.getOpenInterestInTokens = exports.getOpenInterestUsd = exports.getMarketPnl = exports.getOiInTokensFromRawValues = exports.getOiUsdFromRawValues = exports.getMarketDivisor = exports.getReservedUsd = exports.getAvailableUsdLiquidityForCollateral = exports.getOppositeCollateralFromConfig = exports.getOppositeCollateral = exports.getMaxAllowedLeverage = exports.getMaxLeverageByMinCollateralFactor = exports.getCappedPoolPnl = exports.getPoolUsdWithoutPnl = exports.getTokenPoolType = exports.getContractMarketPrices = exports.getMarketPoolName = exports.getMarketBaseName = exports.getMarketIndexName = exports.getMarketFullName = void 0;
3
+ exports.getMarketAddressByName = exports.getMarketWithTiers = exports.composeFullMarketsInfoData = exports.hydrateMarketInfo = exports.mergeMarketsConfigValues = exports.composeRawMarketsInfoData = exports.composeRawMarketInfo = exports.getMarketTicker = exports.getMarket24Stats = exports.getIsMarketDeprecated = exports.getIsMarketAvailableForExpressSwaps = exports.getPriceForPnl = exports.getOpenInterestForBalance = exports.getOpenInterestInTokens = exports.getOpenInterestUsd = exports.getPositiveMarketPnl = exports.getMarketPnl = exports.getOiInTokensFromRawValues = exports.getOiUsdFromRawValues = exports.getMarketDivisor = exports.getReservedUsd = exports.getAvailableUsdLiquidityForCollateral = exports.getOppositeCollateralFromConfig = exports.getOppositeCollateral = exports.getMaxAllowedLeverage = exports.getMaxLeverageByMinCollateralFactor = exports.getCappedPoolPnl = exports.getPoolUsdWithoutPnl = exports.getTokenPoolType = exports.getContractMarketPrices = exports.getMarketPoolName = exports.getMarketBaseName = exports.getMarketIndexName = exports.getMarketFullName = void 0;
4
4
  const viem_1 = require("viem");
5
5
  const factors_1 = require("../../configs/factors");
6
6
  const markets_1 = require("../../configs/markets");
@@ -180,13 +180,20 @@ function getMarketDivisor({ longTokenAddress, shortTokenAddress, }) {
180
180
  }
181
181
  exports.getMarketDivisor = getMarketDivisor;
182
182
  function getOiUsdFromRawValues(rawValues, marketDivisor) {
183
- const longInterestUsingLongToken = rawValues.longInterestUsingLongToken / marketDivisor;
184
- const longInterestUsingShortToken = rawValues.longInterestUsingShortToken / marketDivisor;
185
- const shortInterestUsingLongToken = rawValues.shortInterestUsingLongToken / marketDivisor;
186
- const shortInterestUsingShortToken = rawValues.shortInterestUsingShortToken / marketDivisor;
187
- const longInterestUsd = longInterestUsingLongToken + longInterestUsingShortToken;
188
- const shortInterestUsd = shortInterestUsingLongToken + shortInterestUsingShortToken;
189
- return { longInterestUsd, shortInterestUsd };
183
+ const longInterestUsdUsingLongToken = rawValues.longInterestUsingLongToken / marketDivisor;
184
+ const longInterestUsdUsingShortToken = rawValues.longInterestUsingShortToken / marketDivisor;
185
+ const shortInterestUsdUsingLongToken = rawValues.shortInterestUsingLongToken / marketDivisor;
186
+ const shortInterestUsdUsingShortToken = rawValues.shortInterestUsingShortToken / marketDivisor;
187
+ const longInterestUsd = longInterestUsdUsingLongToken + longInterestUsdUsingShortToken;
188
+ const shortInterestUsd = shortInterestUsdUsingLongToken + shortInterestUsdUsingShortToken;
189
+ return {
190
+ longInterestUsd,
191
+ shortInterestUsd,
192
+ longInterestUsdUsingLongToken,
193
+ longInterestUsdUsingShortToken,
194
+ shortInterestUsdUsingLongToken,
195
+ shortInterestUsdUsingShortToken,
196
+ };
190
197
  }
191
198
  exports.getOiUsdFromRawValues = getOiUsdFromRawValues;
192
199
  function getOiInTokensFromRawValues(rawValues, marketDivisor) {
@@ -196,7 +203,14 @@ function getOiInTokensFromRawValues(rawValues, marketDivisor) {
196
203
  const shortInterestInTokensUsingShortToken = rawValues.shortInterestInTokensUsingShortToken / marketDivisor;
197
204
  const longInterestInTokens = longInterestInTokensUsingLongToken + longInterestInTokensUsingShortToken;
198
205
  const shortInterestInTokens = shortInterestInTokensUsingLongToken + shortInterestInTokensUsingShortToken;
199
- return { longInterestInTokens, shortInterestInTokens };
206
+ return {
207
+ longInterestInTokens,
208
+ shortInterestInTokens,
209
+ longInterestInTokensUsingLongToken,
210
+ longInterestInTokensUsingShortToken,
211
+ shortInterestInTokensUsingLongToken,
212
+ shortInterestInTokensUsingShortToken,
213
+ };
200
214
  }
201
215
  exports.getOiInTokensFromRawValues = getOiInTokensFromRawValues;
202
216
  function getMarketPnl(marketInfo, isLong, forMaxPoolValue) {
@@ -212,6 +226,50 @@ function getMarketPnl(marketInfo, isLong, forMaxPoolValue) {
212
226
  return pnl;
213
227
  }
214
228
  exports.getMarketPnl = getMarketPnl;
229
+ function getMarketPnlByCollateralToken(marketInfo, isLong, isLongCollateral, forMaxPoolValue) {
230
+ const maximize = !forMaxPoolValue;
231
+ let openInterestUsd;
232
+ let openInterestInTokens;
233
+ if (isLong) {
234
+ openInterestUsd = isLongCollateral
235
+ ? marketInfo.longInterestUsdUsingLongToken
236
+ : marketInfo.longInterestUsdUsingShortToken;
237
+ openInterestInTokens = isLongCollateral
238
+ ? marketInfo.longInterestInTokensUsingLongToken
239
+ : marketInfo.longInterestInTokensUsingShortToken;
240
+ }
241
+ else {
242
+ openInterestUsd = isLongCollateral
243
+ ? marketInfo.shortInterestUsdUsingLongToken
244
+ : marketInfo.shortInterestUsdUsingShortToken;
245
+ openInterestInTokens = isLongCollateral
246
+ ? marketInfo.shortInterestInTokensUsingLongToken
247
+ : marketInfo.shortInterestInTokensUsingShortToken;
248
+ }
249
+ if (openInterestUsd === undefined || openInterestInTokens === undefined) {
250
+ return undefined;
251
+ }
252
+ if (openInterestUsd === 0n || openInterestInTokens === 0n) {
253
+ return 0n;
254
+ }
255
+ const price = getPriceForPnl(marketInfo.indexToken.prices, isLong, maximize);
256
+ const openInterestValue = (0, tokens_2.convertToUsd)(openInterestInTokens, marketInfo.indexToken.decimals, price);
257
+ return isLong ? openInterestValue - openInterestUsd : openInterestUsd - openInterestValue;
258
+ }
259
+ /**
260
+ * Mirrors MarketUtils.getPositivePnl, the denominator of the per-position pnl cap since v2.2c.
261
+ * Pool value keeps using the net {@link getMarketPnl}. Falls back to it without the collateral split.
262
+ */
263
+ function getPositiveMarketPnl(marketInfo, isLong, forMaxPoolValue) {
264
+ const pnlUsingLongTokenAsCollateral = getMarketPnlByCollateralToken(marketInfo, isLong, true, forMaxPoolValue);
265
+ const pnlUsingShortTokenAsCollateral = getMarketPnlByCollateralToken(marketInfo, isLong, false, forMaxPoolValue);
266
+ if (pnlUsingLongTokenAsCollateral === undefined || pnlUsingShortTokenAsCollateral === undefined) {
267
+ return getMarketPnl(marketInfo, isLong, forMaxPoolValue);
268
+ }
269
+ return ((pnlUsingLongTokenAsCollateral > 0 ? pnlUsingLongTokenAsCollateral : 0n) +
270
+ (pnlUsingShortTokenAsCollateral > 0 ? pnlUsingShortTokenAsCollateral : 0n));
271
+ }
272
+ exports.getPositiveMarketPnl = getPositiveMarketPnl;
215
273
  function getOpenInterestUsd(marketInfo, isLong) {
216
274
  return isLong ? marketInfo.longInterestUsd : marketInfo.shortInterestUsd;
217
275
  }
@@ -1,7 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getLimitedDisplay = exports.formatAmountFree = exports.formatArrayAmount = exports.formatKeyAmount = exports.formatAmount = exports.numberWithCommas = exports.formatFactor = exports.formatBalanceAmount = exports.formatAmountHuman = exports.formatNumberHuman = exports.formatPercentageDisplay = exports.formatUsdPrice = exports.formatRatePercentage = exports.formatTokenAmountWithUsd = exports.formatTokenAmount = exports.formatPercentage = exports.formatDeltaUsd = exports.formatBigUsd = exports.formatUsd = exports.adjustForDecimals = exports.bigintToNumber = exports.trimZeroDecimals = exports.numberToBigint = exports.applyFactor = exports.roundsToZero = exports.roundUpMagnitudeDivision = exports.formatPriceImpactBps = exports.formatBasisPoints = exports.getBasisPoints = exports.basisPointsToFloat = exports.toBigInt = exports.expandDecimals = exports.safeDivide = exports.isNonZero = exports.TRIGGER_PREFIX_BELOW = exports.TRIGGER_PREFIX_ABOVE = exports.PERCENT_PRECISION_DECIMALS = exports.MaxInt256 = exports.MaxUint256 = exports.BN_NEGATIVE_ONE = exports.BN_ONE = exports.BN_ZERO = exports.FLOAT_PRECISION_SQRT = exports.FLOAT_PRECISION_SQRT_DECIMALS = exports.PRECISION = exports.PRECISION_DECIMALS = exports.BASIS_POINTS_DECIMALS = exports.BASIS_POINTS_DIVISOR_BIGINT = exports.BASIS_POINTS_DIVISOR = exports.USD_DECIMALS = void 0;
4
- exports.absDiffBps = exports.clamp = exports.calculateDisplayDecimals = exports.deserializeBigIntsInObject = exports.serializeBigIntsInObject = exports.removeTrailingZeros = exports.maxbigint = exports.minBigNumber = exports.roundBigIntToDecimals = exports.roundToOrder = exports.roundToTwoDecimals = exports.roundUpDivision = exports.parseValue = exports.toBigNumberWithDecimals = exports.roundWithDecimals = exports.getPlusOrMinusSymbol = exports.padDecimals = exports.limitDecimals = void 0;
3
+ exports.formatArrayAmount = exports.formatKeyAmount = exports.formatAmount = exports.numberWithCommas = exports.formatFactor = exports.formatBalanceAmount = exports.formatAmountHuman = exports.formatNumberHuman = exports.formatPercentageDisplay = exports.formatUsdPrice = exports.formatRatePercentage = exports.formatTokenAmountWithUsd = exports.formatTokenAmount = exports.formatPercentage = exports.formatDeltaUsd = exports.formatBigUsd = exports.formatUsd = exports.adjustForDecimals = exports.bigintToNumber = exports.trimZeroDecimals = exports.numberToBigint = exports.applyFactor = exports.roundsToZero = exports.roundUpMagnitudeDivision = exports.formatPriceImpactBps = exports.formatBasisPoints = exports.getBasisPoints = exports.basisPointsToFloat = exports.toBigInt = exports.expandDecimals = exports.safeDivide = exports.isNonZero = exports.TRIGGER_PREFIX_BELOW = exports.TRIGGER_PREFIX_ABOVE = exports.PERCENT_PRECISION_DECIMALS = exports.isUint256 = exports.parseUint256DecimalString = exports.MaxInt256 = exports.MaxUint256 = exports.BN_NEGATIVE_ONE = exports.BN_ONE = exports.BN_ZERO = exports.FLOAT_PRECISION_SQRT = exports.FLOAT_PRECISION_SQRT_DECIMALS = exports.PRECISION = exports.PRECISION_DECIMALS = exports.BASIS_POINTS_DECIMALS = exports.BASIS_POINTS_DIVISOR_BIGINT = exports.BASIS_POINTS_DIVISOR = exports.USD_DECIMALS = void 0;
4
+ exports.absDiffBps = exports.clamp = exports.calculateDisplayDecimals = exports.deserializeBigIntsInObject = exports.serializeBigIntsInObject = exports.removeTrailingZeros = exports.maxbigint = exports.minBigNumber = exports.roundBigIntToDecimals = exports.roundToOrder = exports.roundToTwoDecimals = exports.roundUpDivision = exports.parseValue = exports.toBigNumberWithDecimals = exports.roundWithDecimals = exports.getPlusOrMinusSymbol = exports.padDecimals = exports.limitDecimals = exports.getLimitedDisplay = exports.formatAmountFree = void 0;
5
5
  const viem_1 = require("viem");
6
6
  const bigmath_1 = require("../bigmath");
7
7
  exports.USD_DECIMALS = 30;
@@ -17,6 +17,19 @@ exports.BN_ONE = 1n;
17
17
  exports.BN_NEGATIVE_ONE = -1n;
18
18
  exports.MaxUint256 = BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
19
19
  exports.MaxInt256 = BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
20
+ const UINT_DECIMAL_STRING_REGEX = /^(0|[1-9]\d*)$/;
21
+ function parseUint256DecimalString(value) {
22
+ if (typeof value !== "string" || !UINT_DECIMAL_STRING_REGEX.test(value)) {
23
+ return undefined;
24
+ }
25
+ const parsed = BigInt(value);
26
+ return parsed <= exports.MaxUint256 ? parsed : undefined;
27
+ }
28
+ exports.parseUint256DecimalString = parseUint256DecimalString;
29
+ function isUint256(value) {
30
+ return typeof value === "bigint" && value >= 0n && value <= exports.MaxUint256;
31
+ }
32
+ exports.isUint256 = isUint256;
20
33
  exports.PERCENT_PRECISION_DECIMALS = exports.PRECISION_DECIMALS - 2;
21
34
  const MAX_EXCEEDING_THRESHOLD = "1000000000";
22
35
  const MIN_EXCEEDING_THRESHOLD = "0.01";
@@ -392,8 +405,8 @@ function formatFactor(factor) {
392
405
  .abs(factor)
393
406
  .toString()
394
407
  .match(/^(.+?)(?<zeroes>0*)$/)?.groups?.zeroes?.length || 0;
395
- const factorDecimals = 30 - trailingZeroes;
396
- return (0, exports.formatAmount)(factor, 30, factorDecimals);
408
+ const factorDecimals = Math.max(exports.PRECISION_DECIMALS - trailingZeroes, 0);
409
+ return (0, exports.formatAmount)(factor, exports.PRECISION_DECIMALS, factorDecimals);
397
410
  }
398
411
  exports.formatFactor = formatFactor;
399
412
  function numberWithCommas(x, { showDollar = false } = {}) {
@@ -573,8 +586,14 @@ const parseValue = (value, tokenDecimals) => {
573
586
  if (isNaN(pValue) || !isFinite(pValue)) {
574
587
  return undefined;
575
588
  }
576
- value = (0, exports.limitDecimals)(value, tokenDecimals);
577
- const amount = (0, viem_1.parseUnits)(value, tokenDecimals);
589
+ let amount;
590
+ try {
591
+ value = (0, exports.limitDecimals)(value, tokenDecimals);
592
+ amount = (0, viem_1.parseUnits)(value, tokenDecimals);
593
+ }
594
+ catch {
595
+ return undefined;
596
+ }
578
597
  // Cap at a safe maximum to prevent downstream BigInt overflow errors
579
598
  const MAX_ALLOWED = expandDecimals(1, 62);
580
599
  if (amount > MAX_ALLOWED || amount < -MAX_ALLOWED) {
@@ -618,10 +637,10 @@ function maxbigint(...args) {
618
637
  }
619
638
  exports.maxbigint = maxbigint;
620
639
  function removeTrailingZeros(amount) {
621
- const amountWithoutZeros = Number(amount);
622
- if (!amountWithoutZeros)
640
+ if (typeof amount === "number" || !amount.includes(".") || amount.includes(",") || /^[-+]?0*\.0*$/.test(amount)) {
623
641
  return amount;
624
- return amountWithoutZeros;
642
+ }
643
+ return amount.replace(/0+$/, "").replace(/\.$/, "");
625
644
  }
626
645
  exports.removeTrailingZeros = removeTrailingZeros;
627
646
  const NUMERIC_STRING_REGEX = /^-?\d+$/;
@@ -1,10 +1,113 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.executeExpressOrder = exports.signPreparedOrder = exports.fetchOrderStatus = exports.prepareCollateral = exports.prepareCancelOrder = exports.prepareEditOrder = exports.submitOrder = exports.prepareOrder = void 0;
3
+ exports.executeExpressOrder = exports.signPreparedOrder = exports.fetchOrderStatus = exports.prepareCollateral = exports.prepareCancelOrder = exports.prepareEditOrder = exports.submitOrder = exports.prepareOrder = exports.isPrepareOrderError = exports.parsePrepareOrderError = void 0;
4
+ const http_1 = require("../http/http");
5
+ const api_1 = require("../markets/api");
6
+ const numbers_1 = require("../numbers");
7
+ const objects_1 = require("../objects");
4
8
  const validateTypedData_1 = require("./validateTypedData");
9
+ const PREPARE_ORDER_ERROR_CODES = [
10
+ "INVALID_PARAMS",
11
+ "MARKET_NOT_FOUND",
12
+ "TOKEN_NOT_FOUND",
13
+ "NO_SWAP_PATH",
14
+ "POSITION_NOT_FOUND",
15
+ ];
16
+ function isDeserializedTradingCapacity(value) {
17
+ const raw = (0, objects_1.getRecord)(value);
18
+ if (!raw) {
19
+ return false;
20
+ }
21
+ const parsed = (0, api_1.parseTradingCapacity)(raw);
22
+ return parsed !== undefined && Object.entries(parsed).every(([key, parsedValue]) => raw[key] === parsedValue);
23
+ }
24
+ function isPrepareOrderFieldValidationErrors(value) {
25
+ if (!(0, objects_1.isRecord)(value)) {
26
+ return false;
27
+ }
28
+ return Object.values(value).every((fieldError) => (0, objects_1.isRecord)(fieldError) && typeof fieldError.message === "string");
29
+ }
30
+ function parsePrepareOrderErrorBody(value) {
31
+ if (!(0, objects_1.isRecord)(value)) {
32
+ return undefined;
33
+ }
34
+ const body = value;
35
+ if (body.code === "INSUFFICIENT_LIQUIDITY") {
36
+ const details = (0, objects_1.getRecord)(body.details);
37
+ const capacity = (0, api_1.parseTradingCapacity)(details);
38
+ const requestedSizeUsd = (0, numbers_1.parseUint256DecimalString)(details?.requestedSizeUsd);
39
+ if (!capacity || requestedSizeUsd === undefined || typeof body.message !== "string") {
40
+ return undefined;
41
+ }
42
+ return {
43
+ code: body.code,
44
+ message: body.message,
45
+ details: {
46
+ ...capacity,
47
+ requestedSizeUsd,
48
+ },
49
+ };
50
+ }
51
+ if (PREPARE_ORDER_ERROR_CODES.includes(body.code) && typeof body.message === "string") {
52
+ return {
53
+ code: body.code,
54
+ message: body.message,
55
+ };
56
+ }
57
+ if (typeof body.code === "string" && body.code.length > 0 && typeof body.message === "string") {
58
+ return {
59
+ code: "UNKNOWN_PREPARE_ORDER_ERROR",
60
+ originalCode: body.code,
61
+ message: body.message,
62
+ ...(typeof body.traceId === "string" ? { traceId: body.traceId } : {}),
63
+ };
64
+ }
65
+ if (body.code !== undefined) {
66
+ return undefined;
67
+ }
68
+ if (typeof body.message === "string") {
69
+ return { message: body.message };
70
+ }
71
+ if (isPrepareOrderFieldValidationErrors(body.message)) {
72
+ return { message: body.message };
73
+ }
74
+ return undefined;
75
+ }
76
+ function parsePrepareOrderError(error) {
77
+ if (!(error instanceof http_1.HttpError) || error.statusCode !== 400) {
78
+ return undefined;
79
+ }
80
+ return parsePrepareOrderErrorBody(error.body);
81
+ }
82
+ exports.parsePrepareOrderError = parsePrepareOrderError;
83
+ /** Validates an already deserialized prepare error. Use parsePrepareOrderError for a caught HttpError. */
84
+ function isPrepareOrderError(value) {
85
+ if (!(0, objects_1.isRecord)(value)) {
86
+ return false;
87
+ }
88
+ const error = value;
89
+ if (error.code === "INSUFFICIENT_LIQUIDITY") {
90
+ const details = (0, objects_1.getRecord)(error.details);
91
+ const requestedSizeUsd = details?.requestedSizeUsd;
92
+ return Boolean(isDeserializedTradingCapacity(details) && (0, numbers_1.isUint256)(requestedSizeUsd) && typeof error.message === "string");
93
+ }
94
+ if (PREPARE_ORDER_ERROR_CODES.includes(error.code)) {
95
+ return typeof error.message === "string";
96
+ }
97
+ if (error.code === "UNKNOWN_PREPARE_ORDER_ERROR") {
98
+ return (typeof error.originalCode === "string" &&
99
+ error.originalCode.length > 0 &&
100
+ typeof error.message === "string" &&
101
+ (error.traceId === undefined || typeof error.traceId === "string"));
102
+ }
103
+ return (error.code === undefined &&
104
+ (typeof error.message === "string" || isPrepareOrderFieldValidationErrors(error.message)));
105
+ }
106
+ exports.isPrepareOrderError = isPrepareOrderError;
5
107
  function parseEstimates(raw) {
6
108
  if (!raw)
7
109
  return undefined;
110
+ const tradingCapacity = raw.tradingCapacity === undefined ? undefined : (0, api_1.parseTradingCapacity)(raw.tradingCapacity);
8
111
  return {
9
112
  positionPriceImpactDeltaUsd: BigInt(raw.positionPriceImpactDeltaUsd ?? "0"),
10
113
  swapPriceImpactDeltaUsd: BigInt(raw.swapPriceImpactDeltaUsd ?? "0"),
@@ -14,10 +117,65 @@ function parseEstimates(raw) {
14
117
  positionFeeUsd: BigInt(raw.positionFeeUsd ?? "0"),
15
118
  borrowingFeeUsd: BigInt(raw.borrowingFeeUsd ?? "0"),
16
119
  fundingFeeUsd: BigInt(raw.fundingFeeUsd ?? "0"),
120
+ tradingCapacity,
121
+ };
122
+ }
123
+ function parseValidationWarning(raw) {
124
+ const warning = (0, objects_1.getRecord)(raw);
125
+ const code = (0, objects_1.getString)(warning?.code);
126
+ const message = (0, objects_1.getString)(warning?.message);
127
+ if (!warning || !code || !message) {
128
+ return undefined;
129
+ }
130
+ const details = (0, objects_1.getRecord)(warning.details);
131
+ if (code === "INSUFFICIENT_LIQUIDITY") {
132
+ const capacity = (0, api_1.parseTradingCapacity)(details);
133
+ const requestedSizeUsd = (0, numbers_1.parseUint256DecimalString)(details?.requestedSizeUsd);
134
+ if (capacity && requestedSizeUsd !== undefined) {
135
+ return {
136
+ code,
137
+ message,
138
+ details: {
139
+ ...capacity,
140
+ requestedSizeUsd,
141
+ },
142
+ };
143
+ }
144
+ }
145
+ const reason = (0, objects_1.getString)(details?.reason);
146
+ if (code === "TRADING_CAPACITY_UNAVAILABLE" &&
147
+ (reason === "STALE_MARKET_DATA" ||
148
+ reason === "JIT_DATA_UNAVAILABLE" ||
149
+ reason === "JIT_ACCOUNT_ELIGIBILITY_UNKNOWN" ||
150
+ reason === "COLLATERAL_SWAP")) {
151
+ return {
152
+ code,
153
+ message,
154
+ details: { reason },
155
+ };
156
+ }
157
+ return {
158
+ code: "UNKNOWN_VALIDATION_WARNING",
159
+ originalCode: code,
160
+ message,
161
+ ...(warning.details === undefined ? {} : { details: warning.details }),
17
162
  };
18
163
  }
164
+ function parseValidationWarnings(raw) {
165
+ if (raw === undefined) {
166
+ return undefined;
167
+ }
168
+ if (!Array.isArray(raw)) {
169
+ return undefined;
170
+ }
171
+ return raw.map(parseValidationWarning).filter((warning) => warning !== undefined);
172
+ }
19
173
  function parsePrepareResponse(raw) {
20
- return { ...raw, estimates: parseEstimates(raw.estimates) };
174
+ return {
175
+ ...raw,
176
+ estimates: parseEstimates(raw.estimates),
177
+ validationWarnings: parseValidationWarnings(raw.validationWarnings),
178
+ };
21
179
  }
22
180
  async function prepareOrder(ctx, request) {
23
181
  return ctx.api.postJson("/v1/orders/txns/prepare", request, {
@@ -32,7 +32,7 @@ function getPositionPnlUsd(p) {
32
32
  if (totalPnl <= 0) {
33
33
  return totalPnl;
34
34
  }
35
- const poolPnl = (0, markets_1.getMarketPnl)(marketInfo, isLong, true);
35
+ const poolPnl = (0, markets_1.getPositiveMarketPnl)(marketInfo, isLong, true);
36
36
  const poolUsd = (0, markets_1.getPoolUsdWithoutPnl)(marketInfo, isLong, "minPrice");
37
37
  const cappedPnl = (0, markets_1.getCappedPoolPnl)({
38
38
  marketInfo,