@gmx-io/sdk 2.2.0 → 2.3.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.
Files changed (64) hide show
  1. package/build/cjs/src/abis/TransitStation.js +2222 -0
  2. package/build/cjs/src/abis/index.js +2 -0
  3. package/build/cjs/src/clients/v2/index.js +54 -27
  4. package/build/cjs/src/codegen/prebuilt/hashedKinkModelMarketRatesKeys.json +32 -0
  5. package/build/cjs/src/codegen/prebuilt/hashedMarketConfigKeys.json +272 -0
  6. package/build/cjs/src/codegen/prebuilt/hashedMarketValuesKeys.json +60 -0
  7. package/build/cjs/src/configs/markets.js +28 -0
  8. package/build/cjs/src/configs/tokens.js +9 -0
  9. package/build/cjs/src/test/mock.js +32 -4
  10. package/build/cjs/src/utils/markets/utils.js +45 -1
  11. package/build/cjs/src/utils/paxos/__tests__/api.spec.js +128 -0
  12. package/build/cjs/src/utils/paxos/api.js +129 -0
  13. package/build/cjs/src/utils/paxos/types.js +2 -0
  14. package/build/cjs/src/utils/trade/__tests__/increaseMarginCheck.spec.js +14 -35
  15. package/build/cjs/src/utils/trade/__tests__/twapIncreaseMarginCheck.spec.js +368 -0
  16. package/build/cjs/src/utils/trade/increaseMarginCheck.js +27 -13
  17. package/build/cjs/src/utils/trade/twapIncreaseMarginCheck.js +180 -0
  18. package/build/cjs/src/utils/twap/index.js +13 -4
  19. package/build/cjs/src/utils/usdgBoostApr/api.js +7 -0
  20. package/build/cjs/src/utils/usdgBoostApr/types.js +2 -0
  21. package/build/cjs/src/utils/whitelists/api.js +9 -0
  22. package/build/cjs/src/utils/whitelists/types.js +2 -0
  23. package/build/esm/src/abis/TransitStation.js +2220 -0
  24. package/build/esm/src/abis/index.js +2 -0
  25. package/build/esm/src/clients/v2/index.js +27 -0
  26. package/build/esm/src/codegen/prebuilt/hashedKinkModelMarketRatesKeys.json +32 -0
  27. package/build/esm/src/codegen/prebuilt/hashedMarketConfigKeys.json +272 -0
  28. package/build/esm/src/codegen/prebuilt/hashedMarketValuesKeys.json +60 -0
  29. package/build/esm/src/configs/markets.js +28 -0
  30. package/build/esm/src/configs/tokens.js +9 -0
  31. package/build/esm/src/test/mock.js +27 -0
  32. package/build/esm/src/utils/markets/utils.js +44 -1
  33. package/build/esm/src/utils/paxos/__tests__/api.spec.js +126 -0
  34. package/build/esm/src/utils/paxos/api.js +120 -0
  35. package/build/esm/src/utils/paxos/types.js +1 -0
  36. package/build/esm/src/utils/trade/__tests__/increaseMarginCheck.spec.js +15 -36
  37. package/build/esm/src/utils/trade/__tests__/twapIncreaseMarginCheck.spec.js +366 -0
  38. package/build/esm/src/utils/trade/increaseMarginCheck.js +24 -11
  39. package/build/esm/src/utils/trade/twapIncreaseMarginCheck.js +172 -0
  40. package/build/esm/src/utils/twap/index.js +10 -3
  41. package/build/esm/src/utils/usdgBoostApr/api.js +3 -0
  42. package/build/esm/src/utils/usdgBoostApr/types.js +1 -0
  43. package/build/esm/src/utils/whitelists/api.js +5 -0
  44. package/build/esm/src/utils/whitelists/types.js +1 -0
  45. package/build/tsconfig.tsbuildinfo +1 -1
  46. package/build/types/src/abis/TransitStation.d.ts +1710 -0
  47. package/build/types/src/abis/index.d.ts +1709 -0
  48. package/build/types/src/clients/v2/index.d.ts +20 -0
  49. package/build/types/src/codegen/prebuilt/index.d.ts +364 -0
  50. package/build/types/src/test/mock.d.ts +5 -0
  51. package/build/types/src/utils/markets/utils.d.ts +3 -0
  52. package/build/types/src/utils/paxos/__tests__/api.spec.d.ts +1 -0
  53. package/build/types/src/utils/paxos/api.d.ts +24 -0
  54. package/build/types/src/utils/paxos/types.d.ts +139 -0
  55. package/build/types/src/utils/trade/__tests__/twapIncreaseMarginCheck.spec.d.ts +1 -0
  56. package/build/types/src/utils/trade/increaseMarginCheck.d.ts +15 -7
  57. package/build/types/src/utils/trade/twapIncreaseMarginCheck.d.ts +50 -0
  58. package/build/types/src/utils/trade/types.d.ts +2 -0
  59. package/build/types/src/utils/twap/index.d.ts +2 -0
  60. package/build/types/src/utils/usdgBoostApr/api.d.ts +5 -0
  61. package/build/types/src/utils/usdgBoostApr/types.d.ts +19 -0
  62. package/build/types/src/utils/whitelists/api.d.ts +7 -0
  63. package/build/types/src/utils/whitelists/types.d.ts +6 -0
  64. package/package.json +10 -1
@@ -3,7 +3,7 @@ import { BASIS_POINTS_DIVISOR, BASIS_POINTS_DIVISOR_BIGINT } from "../../configs
3
3
  import { UI_MAX_LEVERAGE_BY_MARKET } from "../../configs/markets";
4
4
  import { convertTokenAddress, getTokenVisualMultiplier, NATIVE_TOKEN_ADDRESS } from "../../configs/tokens";
5
5
  import { bigMath } from "../bigmath";
6
- import { getBorrowingFactorPerPeriod, getFundingFactorPerPeriod } from "../fees";
6
+ import { applySwapImpactWithCap, getBorrowingFactorPerPeriod, getFundingFactorPerPeriod } from "../fees";
7
7
  import { applyFactor, expandDecimals, PRECISION } from "../numbers";
8
8
  import { getByKey } from "../objects";
9
9
  import { periodToSeconds } from "../time";
@@ -309,6 +309,49 @@ export function getMarketInfoWithOpenInterestDelta({ marketInfo, collateralToken
309
309
  }
310
310
  return next;
311
311
  }
312
+ /** The market a swap step leaves: the pools and the swap impact pools move as in `SwapUtils._swap`. */
313
+ export function getMarketInfoWithSwapDelta(marketInfo, swapStep) {
314
+ const isLongTokenIn = getTokenPoolType(marketInfo, swapStep.tokenInAddress) === "long";
315
+ const tokenIn = isLongTokenIn ? marketInfo.longToken : marketInfo.shortToken;
316
+ const tokenOut = isLongTokenIn ? marketInfo.shortToken : marketInfo.longToken;
317
+ let poolAmountIn = swapStep.amountInAfterFees;
318
+ let poolAmountOut = swapStep.amountOut;
319
+ let impactPoolDeltaIn = 0n;
320
+ let impactPoolDeltaOut = 0n;
321
+ if (swapStep.priceImpactDeltaUsd > 0n) {
322
+ const { impactDeltaAmount, cappedDiffUsd } = applySwapImpactWithCap(marketInfo, tokenOut, swapStep.priceImpactDeltaUsd);
323
+ poolAmountOut -= impactDeltaAmount;
324
+ impactPoolDeltaOut = -impactDeltaAmount;
325
+ if (cappedDiffUsd > 0n) {
326
+ const tokenInImpactAmount = applySwapImpactWithCap(marketInfo, tokenIn, cappedDiffUsd).impactDeltaAmount;
327
+ poolAmountIn += tokenInImpactAmount;
328
+ impactPoolDeltaIn = -tokenInImpactAmount;
329
+ }
330
+ }
331
+ else if (swapStep.priceImpactDeltaUsd < 0n) {
332
+ const { impactDeltaAmount } = applySwapImpactWithCap(marketInfo, tokenIn, swapStep.priceImpactDeltaUsd);
333
+ poolAmountIn += impactDeltaAmount;
334
+ impactPoolDeltaIn = -impactDeltaAmount;
335
+ }
336
+ const [longDelta, shortDelta] = isLongTokenIn ? [poolAmountIn, -poolAmountOut] : [-poolAmountOut, poolAmountIn];
337
+ const [longImpactDelta, shortImpactDelta] = isLongTokenIn
338
+ ? [impactPoolDeltaIn, impactPoolDeltaOut]
339
+ : [impactPoolDeltaOut, impactPoolDeltaIn];
340
+ const next = {
341
+ ...marketInfo,
342
+ longPoolAmount: marketInfo.longPoolAmount + longDelta,
343
+ shortPoolAmount: marketInfo.shortPoolAmount + shortDelta,
344
+ swapImpactPoolAmountLong: marketInfo.swapImpactPoolAmountLong + longImpactDelta,
345
+ swapImpactPoolAmountShort: marketInfo.swapImpactPoolAmountShort + shortImpactDelta,
346
+ };
347
+ if (marketInfo.virtualPoolAmountForLongToken > 0n) {
348
+ next.virtualPoolAmountForLongToken = marketInfo.virtualPoolAmountForLongToken + longDelta;
349
+ }
350
+ if (marketInfo.virtualPoolAmountForShortToken > 0n) {
351
+ next.virtualPoolAmountForShortToken = marketInfo.virtualPoolAmountForShortToken + shortDelta;
352
+ }
353
+ return next;
354
+ }
312
355
  export function getOpenInterestForBalance(marketInfo, isLong) {
313
356
  if (marketInfo.useOpenInterestInTokensForBalance) {
314
357
  const interestInTokens = isLong ? marketInfo.longInterestInTokens : marketInfo.shortInterestInTokens;
@@ -0,0 +1,126 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { fetchApiTransitFeeTier, fetchApiTransitOrder, fetchApiTransitOrders, fetchApiTransitQuote, fetchApiTransitRoutes, } from "../api";
3
+ const API_URL = "https://example.test";
4
+ const USER = "0x1111111111111111111111111111111111111111";
5
+ const USDC = "0xaf88d065e77c8cC2239327C5EDb3A432268e5831";
6
+ const USDG = "0x004B506865409877C9fA29bfb1ebA929984B9bbC";
7
+ const ORDER_ID = "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef";
8
+ function createApi(calls, response = {}) {
9
+ return {
10
+ url: API_URL,
11
+ fetchJson: async (path, opts) => {
12
+ calls.push({ path, query: opts?.query });
13
+ return response;
14
+ },
15
+ postJson: async () => {
16
+ throw new Error("Unexpected POST request");
17
+ },
18
+ };
19
+ }
20
+ const RAW_ORDER = {
21
+ id: ORDER_ID,
22
+ offerAsset: USDC,
23
+ wantAsset: USDG,
24
+ amountDue: "50000000",
25
+ remainingAmountDue: "0",
26
+ offerAmount: "50000000",
27
+ receiver: USER,
28
+ distributorCode: "0x",
29
+ destinationChainId: 42161,
30
+ sourceChainId: 42161,
31
+ receiveTime: 1234567890,
32
+ status: "PROCESSED",
33
+ user: USER,
34
+ createdAt: "2026-01-01T00:00:00Z",
35
+ updatedAt: "2026-01-01T00:05:00Z",
36
+ orderExecuteds: [
37
+ { id: "0xab", amount: "50000000", remaining: "0", timestamp: 1234567890, txHash: "0xcd", chainId: 42161 },
38
+ ],
39
+ };
40
+ describe("paxos transit api", () => {
41
+ it("parses routes", async () => {
42
+ const calls = [];
43
+ const api = createApi(calls, {
44
+ routes: [
45
+ {
46
+ sourceChainId: 42161,
47
+ destinationChainId: 42161,
48
+ destinationChainEID: 30110,
49
+ offerAsset: USDC,
50
+ wantAsset: USDG,
51
+ minOrderSize: "10000000",
52
+ },
53
+ ],
54
+ });
55
+ const routes = await fetchApiTransitRoutes({ api });
56
+ expect(calls).toEqual([{ path: "/v1/paxos/transit/routes", query: { filter: undefined } }]);
57
+ expect(routes).toEqual([
58
+ {
59
+ sourceChainId: 42161,
60
+ destinationChainId: 42161,
61
+ destinationChainEID: 30110,
62
+ offerAsset: USDC,
63
+ wantAsset: USDG,
64
+ minOrderSize: 10000000n,
65
+ tokenMetadataMap: {},
66
+ },
67
+ ]);
68
+ });
69
+ it("asks for the routes of a fee tier", async () => {
70
+ const calls = [];
71
+ const api = createApi(calls, { routes: [] });
72
+ await fetchApiTransitRoutes({ api }, { feeTier: "zeroFee" });
73
+ expect(calls).toEqual([{ path: "/v1/paxos/transit/routes", query: { filter: undefined, feeTier: "zeroFee" } }]);
74
+ });
75
+ it("parses fee tier capacity as bigint", async () => {
76
+ const calls = [];
77
+ const api = createApi(calls, { feeTier: "zeroFee", zeroFeeCapacity: "250000000000" });
78
+ const result = await fetchApiTransitFeeTier({ api }, { userAddress: USER });
79
+ expect(calls).toEqual([{ path: "/v1/paxos/transit/fee-tier", query: { userAddress: USER } }]);
80
+ expect(result).toEqual({ feeTier: "zeroFee", zeroFeeCapacity: 250000000000n });
81
+ });
82
+ it("sends quote amounts as strings and parses fees", async () => {
83
+ const calls = [];
84
+ const api = createApi(calls, {
85
+ transaction: { to: "0x22", data: "0x33", value: "1500", functionName: "submitOrder" },
86
+ amountOut: "49990000",
87
+ protocolFee: "10000",
88
+ fillCostFee: "5000",
89
+ conversionRateFee: "5000",
90
+ conversionRateHundredthsBps: 100,
91
+ integratorFee: "0",
92
+ totalFees: "10000",
93
+ });
94
+ const quote = await fetchApiTransitQuote({ api }, {
95
+ userAddress: USER,
96
+ offerAsset: USDC,
97
+ wantAsset: USDG,
98
+ offerAmount: 50000000n,
99
+ sourceChainId: 42161,
100
+ destinationChainId: 42161,
101
+ feeTier: "standardFee",
102
+ });
103
+ expect(calls[0].path).toBe("/v1/paxos/transit/orders/quote");
104
+ expect(calls[0].query).toMatchObject({ offerAmount: "50000000", feeTier: "standardFee" });
105
+ expect(quote.transaction.value).toBe(1500n);
106
+ expect(quote.amountOut).toBe(49990000n);
107
+ expect(quote.totalFees).toBe(10000n);
108
+ expect(quote.estimatedLatencyMs).toBeUndefined();
109
+ });
110
+ it("parses a single order", async () => {
111
+ const calls = [];
112
+ const api = createApi(calls, { order: RAW_ORDER });
113
+ const order = await fetchApiTransitOrder({ api }, { orderId: ORDER_ID });
114
+ expect(calls).toEqual([{ path: `/v1/paxos/transit/orders/${ORDER_ID}`, query: undefined }]);
115
+ expect(order.status).toBe("PROCESSED");
116
+ expect(order.offerAmount).toBe(50000000n);
117
+ expect(order.tokenMetadata).toEqual({});
118
+ expect(order.orderExecuteds[0].amount).toBe(50000000n);
119
+ });
120
+ it("drops an empty next page token", async () => {
121
+ const api = createApi([], { orders: [RAW_ORDER], nextPageToken: "" });
122
+ const result = await fetchApiTransitOrders({ api }, { userAddress: USER });
123
+ expect(result.orders).toHaveLength(1);
124
+ expect(result.nextPageToken).toBeUndefined();
125
+ });
126
+ });
@@ -0,0 +1,120 @@
1
+ export async function fetchApiTransitRoutes(ctx, params) {
2
+ const raw = await ctx.api.fetchJson("/v1/paxos/transit/routes", {
3
+ query: { filter: params?.filter, feeTier: params?.feeTier },
4
+ });
5
+ return (raw.routes ?? []).map(parseRoute);
6
+ }
7
+ export async function fetchApiTransitFeeTier(ctx, params) {
8
+ const raw = await ctx.api.fetchJson("/v1/paxos/transit/fee-tier", {
9
+ query: { userAddress: params.userAddress },
10
+ });
11
+ return {
12
+ feeTier: raw.feeTier,
13
+ zeroFeeCapacity: BigInt(raw.zeroFeeCapacity),
14
+ };
15
+ }
16
+ export async function fetchApiTransitAuthorization(ctx, params) {
17
+ return ctx.api.fetchJson("/v1/paxos/transit/authorization", {
18
+ query: {
19
+ userAddress: params.userAddress,
20
+ tokenAddress: params.tokenAddress,
21
+ spenderAddress: params.spenderAddress,
22
+ amount: params.amount.toString(),
23
+ chainId: params.chainId,
24
+ },
25
+ });
26
+ }
27
+ export async function fetchApiTransitQuote(ctx, params) {
28
+ const raw = await ctx.api.fetchJson("/v1/paxos/transit/orders/quote", {
29
+ query: {
30
+ userAddress: params.userAddress,
31
+ offerAsset: params.offerAsset,
32
+ wantAsset: params.wantAsset,
33
+ offerAmount: params.offerAmount.toString(),
34
+ sourceChainId: params.sourceChainId,
35
+ destinationChainId: params.destinationChainId,
36
+ permitSignature: params.permitSignature,
37
+ permitDeadline: params.permitDeadline,
38
+ responseFormat: params.responseFormat,
39
+ feeTier: params.feeTier,
40
+ },
41
+ });
42
+ return parseQuote(raw);
43
+ }
44
+ export async function fetchApiTransitOrder(ctx, params) {
45
+ const raw = await ctx.api.fetchJson(`/v1/paxos/transit/orders/${encodeURIComponent(params.orderId)}`);
46
+ return parseOrder(raw.order);
47
+ }
48
+ export async function fetchApiTransitOrders(ctx, params) {
49
+ const raw = await ctx.api.fetchJson("/v1/paxos/transit/orders", {
50
+ query: {
51
+ userAddress: params.userAddress,
52
+ pageSize: params.pageSize,
53
+ pageToken: params.pageToken,
54
+ filter: params.filter,
55
+ },
56
+ });
57
+ return {
58
+ orders: (raw.orders ?? []).map(parseOrder),
59
+ nextPageToken: raw.nextPageToken || undefined,
60
+ };
61
+ }
62
+ function parseRoute(raw) {
63
+ return {
64
+ sourceChainId: Number(raw.sourceChainId),
65
+ destinationChainId: Number(raw.destinationChainId),
66
+ destinationChainEID: Number(raw.destinationChainEID),
67
+ offerAsset: raw.offerAsset,
68
+ wantAsset: raw.wantAsset,
69
+ minOrderSize: BigInt(raw.minOrderSize),
70
+ tokenMetadataMap: raw.tokenMetadataMap ?? {},
71
+ };
72
+ }
73
+ function parseQuote(raw) {
74
+ return {
75
+ transaction: {
76
+ to: raw.transaction.to,
77
+ data: raw.transaction.data,
78
+ value: BigInt(raw.transaction.value ?? 0),
79
+ abi: raw.transaction.abi,
80
+ functionName: raw.transaction.functionName,
81
+ args: raw.transaction.args,
82
+ },
83
+ amountOut: BigInt(raw.amountOut),
84
+ protocolFee: BigInt(raw.protocolFee),
85
+ fillCostFee: BigInt(raw.fillCostFee),
86
+ conversionRateFee: BigInt(raw.conversionRateFee),
87
+ conversionRateHundredthsBps: Number(raw.conversionRateHundredthsBps),
88
+ integratorFee: BigInt(raw.integratorFee ?? 0),
89
+ totalFees: BigInt(raw.totalFees),
90
+ estimatedLatencyMs: raw.estimatedLatencyMs === undefined ? undefined : Number(raw.estimatedLatencyMs),
91
+ };
92
+ }
93
+ function parseOrder(raw) {
94
+ return {
95
+ id: raw.id,
96
+ offerAsset: raw.offerAsset,
97
+ wantAsset: raw.wantAsset,
98
+ amountDue: BigInt(raw.amountDue),
99
+ remainingAmountDue: BigInt(raw.remainingAmountDue),
100
+ offerAmount: BigInt(raw.offerAmount),
101
+ receiver: raw.receiver,
102
+ distributorCode: raw.distributorCode,
103
+ destinationChainId: Number(raw.destinationChainId),
104
+ sourceChainId: Number(raw.sourceChainId),
105
+ receiveTime: Number(raw.receiveTime),
106
+ status: raw.status,
107
+ user: raw.user,
108
+ createdAt: raw.createdAt,
109
+ updatedAt: raw.updatedAt,
110
+ tokenMetadata: raw.tokenMetadata ?? {},
111
+ orderExecuteds: (raw.orderExecuteds ?? []).map((execution) => ({
112
+ id: execution.id,
113
+ amount: BigInt(execution.amount),
114
+ remaining: BigInt(execution.remaining),
115
+ timestamp: Number(execution.timestamp),
116
+ txHash: execution.txHash,
117
+ chainId: Number(execution.chainId),
118
+ })),
119
+ };
120
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -1,34 +1,11 @@
1
1
  import { describe, expect, it } from "vitest";
2
- import { mockMarketsInfoData, mockTokensData } from "../../../test/mock";
2
+ import { mockMarginCheckMarketInfo, mockMarketsInfoData, mockTokensData } from "../../../test/mock";
3
3
  import { getMarketInfoWithOpenInterestDelta } from "../../markets";
4
4
  import { USD_DECIMALS, expandDecimals } from "../../numbers";
5
5
  import { convertToTokenAmount, convertToTokenAmountForIncrease, convertToUsd } from "../../tokens";
6
6
  import { PositionMarginFailureReason, getIncreaseResultingPositionMarginState, getIsMaxLeverageMarginReason, getResultingPositionMarginState, } from "../increaseMarginCheck";
7
7
  const BTC_PRICE = expandDecimals(20000, 30);
8
8
  const tokensData = mockTokensData();
9
- /** 1% min collateral factor → 100x, 0.5% for liquidation. Fees and impact off unless a test needs them. */
10
- function buildMarket(overrides = {}) {
11
- return mockMarketsInfoData(tokensData, ["BTC-BTC-USDC"], {
12
- "BTC-BTC-USDC": {
13
- minCollateralFactor: expandDecimals(1, 28),
14
- minCollateralFactorForLiquidation: expandDecimals(5, 27),
15
- minCollateralFactorForOpenInterestLong: 0n,
16
- minCollateralFactorForOpenInterestShort: 0n,
17
- positionFeeFactorForBalanceWasImproved: 0n,
18
- positionFeeFactorForBalanceWasNotImproved: 0n,
19
- positionImpactFactorPositive: 0n,
20
- positionImpactFactorNegative: 0n,
21
- maxPositionImpactFactorPositive: 0n,
22
- maxPositionImpactFactorNegative: 0n,
23
- maxPositionImpactFactorForLiquidations: 0n,
24
- longInterestUsd: 0n,
25
- shortInterestUsd: 0n,
26
- longInterestInTokens: 0n,
27
- shortInterestInTokens: 0n,
28
- ...overrides,
29
- },
30
- })["BTC-BTC-USDC"];
31
- }
32
9
  const usdc = tokensData.USDC;
33
10
  function usdcAmount(usd) {
34
11
  return convertToTokenAmount(usd10(usd), usdc.decimals, usdc.prices.minPrice);
@@ -42,7 +19,7 @@ function btcAmount(usd) {
42
19
  }
43
20
  function baseParams(overrides = {}) {
44
21
  return {
45
- marketInfo: buildMarket(),
22
+ marketInfo: mockMarginCheckMarketInfo(tokensData),
46
23
  collateralToken: usdc,
47
24
  // 10 000 USD of size bought exactly at the oracle price → zero pnl
48
25
  sizeInUsd: expandDecimals(10000, USD_DECIMALS),
@@ -110,7 +87,7 @@ describe("getResultingPositionMarginState", () => {
110
87
  it("deducts the full-close position fee once", () => {
111
88
  // 0.5% closing fee on 10 000 = 50
112
89
  const state = getResultingPositionMarginState(baseParams({
113
- marketInfo: buildMarket({
90
+ marketInfo: mockMarginCheckMarketInfo(tokensData, {
114
91
  positionFeeFactorForBalanceWasImproved: expandDecimals(5, 27),
115
92
  positionFeeFactorForBalanceWasNotImproved: expandDecimals(5, 27),
116
93
  }),
@@ -122,7 +99,7 @@ describe("getResultingPositionMarginState", () => {
122
99
  // 0.5% closing fee on 10 000 = 50; a 50% pro discount returns 25 of it
123
100
  const state = getResultingPositionMarginState({
124
101
  ...baseParams({
125
- marketInfo: buildMarket({
102
+ marketInfo: mockMarginCheckMarketInfo(tokensData, {
126
103
  positionFeeFactorForBalanceWasImproved: expandDecimals(5, 27),
127
104
  positionFeeFactorForBalanceWasNotImproved: expandDecimals(5, 27),
128
105
  }),
@@ -133,7 +110,7 @@ describe("getResultingPositionMarginState", () => {
133
110
  });
134
111
  it("takes the larger of the pro and referral discounts, not their sum", () => {
135
112
  const params = baseParams({
136
- marketInfo: buildMarket({
113
+ marketInfo: mockMarginCheckMarketInfo(tokensData, {
137
114
  positionFeeFactorForBalanceWasImproved: expandDecimals(5, 27),
138
115
  positionFeeFactorForBalanceWasNotImproved: expandDecimals(5, 27),
139
116
  }),
@@ -160,9 +137,11 @@ describe("getResultingPositionMarginState", () => {
160
137
  });
161
138
  });
162
139
  describe("getIncreaseResultingPositionMarginState", () => {
163
- const marketInfo = buildMarket();
140
+ const marketInfo = mockMarginCheckMarketInfo(tokensData);
164
141
  // the contract clamps negative impact at maxPositionImpactFactorForLiquidations — 1% of size here
165
- const marketWithImpactCap = buildMarket({ maxPositionImpactFactorForLiquidations: expandDecimals(1, 28) });
142
+ const marketWithImpactCap = mockMarginCheckMarketInfo(tokensData, {
143
+ maxPositionImpactFactorForLiquidations: expandDecimals(1, 28),
144
+ });
166
145
  it("returns undefined when there is no size to validate", () => {
167
146
  expect(getIncreaseResultingPositionMarginState({
168
147
  marketInfo,
@@ -235,7 +214,7 @@ describe("getIncreaseResultingPositionMarginState", () => {
235
214
  // shorts dominate, so increasing a long is a same-side rebalance towards balance for the
236
215
  // close leg (positive close impact, clamped away) while the increase leg pays negative
237
216
  // impact that is stored as pending impact on the position
238
- const imbalancedMarket = buildMarket({
217
+ const imbalancedMarket = mockMarginCheckMarketInfo(tokensData, {
239
218
  maxPositionImpactFactorForLiquidations: expandDecimals(1, 28),
240
219
  positionImpactFactorNegative: expandDecimals(1, 22),
241
220
  positionImpactExponentFactorPositive: expandDecimals(2, 30),
@@ -332,7 +311,7 @@ describe("getIncreaseResultingPositionMarginState — open interest projection",
332
311
  // linear impact (exponent 1) keeps every leg a round number:
333
312
  // a crossover pays factorNegative on the side it lands on and earns factorPositive on the side it leaves
334
313
  function impactMarket(useOpenInterestInTokensForBalance) {
335
- return buildMarket({
314
+ return mockMarginCheckMarketInfo(tokensData, {
336
315
  positionImpactFactorPositive: expandDecimals(1, 27), // 0.1%
337
316
  positionImpactFactorNegative: expandDecimals(3, 27), // 0.3%
338
317
  positionImpactExponentFactorPositive: expandDecimals(1, 30),
@@ -492,7 +471,7 @@ describe("getIncreaseResultingPositionMarginState — open-interest min collater
492
471
  const OI_MULTIPLIER = expandDecimals(2, 22);
493
472
  function gateArgs(collateralUsd, marketOverrides = {}) {
494
473
  return {
495
- marketInfo: buildMarket({
474
+ marketInfo: mockMarginCheckMarketInfo(tokensData, {
496
475
  minCollateralFactorForOpenInterestLong: OI_MULTIPLIER,
497
476
  longInterestUsd: expandDecimals(990000, USD_DECIMALS),
498
477
  ...marketOverrides,
@@ -534,7 +513,7 @@ describe("getIncreaseResultingPositionMarginState — open-interest min collater
534
513
  });
535
514
  });
536
515
  describe("getIncreaseResultingPositionMarginState — evaluation at the trigger price", () => {
537
- const marketInfo = buildMarket();
516
+ const marketInfo = mockMarginCheckMarketInfo(tokensData);
538
517
  const minCollateralUsd = expandDecimals(1, USD_DECIMALS);
539
518
  // existing long opened at the current price (20 000): flat pnl at current prices
540
519
  const existingPosition = {
@@ -764,7 +743,7 @@ describe("pool pnl cap — profitable position while the cap binds, min < max",
764
743
  });
765
744
  });
766
745
  describe("getIncreaseResultingPositionMarginState — collateral delta and impact clamp", () => {
767
- const marketInfo = buildMarket();
746
+ const marketInfo = mockMarginCheckMarketInfo(tokensData);
768
747
  const minCollateralUsd = expandDecimals(1, USD_DECIMALS);
769
748
  // 10 000 of size opened at the oracle price with 1 000 USDC
770
749
  const existingPosition = {
@@ -803,7 +782,7 @@ describe("getIncreaseResultingPositionMarginState — collateral delta and impac
803
782
  it("the summed negative impact is clamped by maxPositionImpactFactorForLiquidations after the pending impact is added", () => {
804
783
  // linear impact, shorts 30 000 vs longs 10 000: closing the 10 000 long widens the gap by 10 000
805
784
  // → exit impact −2% × 10 000 = −200
806
- const impactMarket = (maxPositionImpactFactorForLiquidations) => buildMarket({
785
+ const impactMarket = (maxPositionImpactFactorForLiquidations) => mockMarginCheckMarketInfo(tokensData, {
807
786
  positionImpactFactorNegative: expandDecimals(2, 28),
808
787
  positionImpactExponentFactorPositive: expandDecimals(1, 30),
809
788
  positionImpactExponentFactorNegative: expandDecimals(1, 30),