@gmx-io/sdk 1.6.4 → 1.7.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 (84) 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 +6 -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/esm/scripts/subsquid-codegen.js +1 -1
  35. package/build/esm/src/clients/v1/testUtil.js +1 -1
  36. package/build/esm/src/clients/v2/__tests__/data.spec.js +6 -6
  37. package/build/esm/src/clients/v2/__tests__/decrease.spec.js +7 -7
  38. package/build/esm/src/clients/v2/__tests__/editCancel.spec.js +13 -13
  39. package/build/esm/src/clients/v2/__tests__/errors.spec.js +2 -48
  40. package/build/esm/src/clients/v2/__tests__/errorsLifecycle.spec.js +51 -0
  41. package/build/esm/src/clients/v2/__tests__/globalCleanup.js +77 -0
  42. package/build/esm/src/clients/v2/__tests__/increase.spec.js +15 -15
  43. package/build/esm/src/clients/v2/__tests__/multichain.spec.js +6 -7
  44. package/build/esm/src/clients/v2/__tests__/prepareErrors.spec.js +165 -0
  45. package/build/esm/src/clients/v2/__tests__/setupAllowance.js +30 -0
  46. package/build/esm/src/clients/v2/__tests__/subaccount.spec.js +17 -124
  47. package/build/esm/src/clients/v2/__tests__/subaccountLifecycle.spec.js +106 -0
  48. package/build/esm/src/clients/v2/__tests__/testUtil.js +33 -4
  49. package/build/esm/src/clients/v2/__tests__/tradingCapacity.spec.js +369 -0
  50. package/build/esm/src/clients/v2/index.js +6 -2
  51. package/build/esm/src/codegen/subsquid.js +282 -18
  52. package/build/esm/src/configs/__tests__/markets.spec.js +9 -1
  53. package/build/esm/src/utils/__tests__/markets.spec.js +61 -1
  54. package/build/esm/src/utils/__tests__/numbers.spec.js +40 -1
  55. package/build/esm/src/utils/__tests__/positionPnlCap.spec.js +76 -0
  56. package/build/esm/src/utils/__tests__/positions.spec.js +17 -5
  57. package/build/esm/src/utils/markets/api.js +88 -2
  58. package/build/esm/src/utils/markets/multicall.js +4 -6
  59. package/build/esm/src/utils/markets/types.js +8 -0
  60. package/build/esm/src/utils/markets/utils.js +65 -8
  61. package/build/esm/src/utils/numbers/utils.js +24 -7
  62. package/build/esm/src/utils/orderTransactions/api.js +157 -1
  63. package/build/esm/src/utils/positions/utils.js +2 -2
  64. package/build/esm/src/utils/tradeHistory/__tests__/utils.spec.js +62 -0
  65. package/build/esm/src/utils/tradeHistory/utils.js +2 -0
  66. package/build/tsconfig.tsbuildinfo +1 -1
  67. package/build/types/src/clients/v2/__tests__/errorsLifecycle.spec.d.ts +1 -0
  68. package/build/types/src/clients/v2/__tests__/globalCleanup.d.ts +1 -0
  69. package/build/types/src/clients/v2/__tests__/prepareErrors.spec.d.ts +1 -0
  70. package/build/types/src/clients/v2/__tests__/setupAllowance.d.ts +1 -0
  71. package/build/types/src/clients/v2/__tests__/subaccountLifecycle.spec.d.ts +1 -0
  72. package/build/types/src/clients/v2/__tests__/testUtil.d.ts +7 -1
  73. package/build/types/src/clients/v2/__tests__/tradingCapacity.spec.d.ts +1 -0
  74. package/build/types/src/clients/v2/index.d.ts +8 -5
  75. package/build/types/src/codegen/subsquid.d.ts +1141 -51
  76. package/build/types/src/utils/__tests__/positionPnlCap.spec.d.ts +1 -0
  77. package/build/types/src/utils/markets/api.d.ts +6 -2
  78. package/build/types/src/utils/markets/types.d.ts +28 -1
  79. package/build/types/src/utils/markets/utils.d.ts +7 -8
  80. package/build/types/src/utils/numbers/utils.d.ts +2 -0
  81. package/build/types/src/utils/orderTransactions/api.d.ts +50 -0
  82. package/build/types/src/utils/tradeHistory/__tests__/utils.spec.d.ts +1 -0
  83. package/build/types/src/utils/tradeHistory/types.d.ts +2 -0
  84. package/package.json +2 -1
@@ -0,0 +1,64 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const vitest_1 = require("vitest");
4
+ const types_1 = require("../../orders/types");
5
+ const utils_1 = require("../utils");
6
+ const USDC_ADDRESS = "0xaf88d065e77c8cC2239327C5EDb3A432268e5831";
7
+ const WETH_ADDRESS = "0x82aF49447D8a07e3bd95BD0d56f35241523fBab1";
8
+ const usdc = {
9
+ name: "USD Coin",
10
+ symbol: "USDC",
11
+ decimals: 6,
12
+ address: USDC_ADDRESS,
13
+ isStable: true,
14
+ prices: { minPrice: 10n ** 24n, maxPrice: 10n ** 24n },
15
+ };
16
+ const weth = {
17
+ name: "Wrapped Ether",
18
+ symbol: "WETH",
19
+ decimals: 18,
20
+ address: WETH_ADDRESS,
21
+ isWrapped: true,
22
+ prices: { minPrice: 2000n * 10n ** 12n, maxPrice: 2000n * 10n ** 12n },
23
+ };
24
+ const tokensData = { [USDC_ADDRESS]: usdc, [WETH_ADDRESS]: weth };
25
+ const rawSwapAction = {
26
+ id: "0xdeadbeef:1",
27
+ eventName: "OrderExecuted",
28
+ account: "0x90c5814240Ae5Cf09730536e76C117FA00Eb7d8e",
29
+ orderType: types_1.OrderType.MarketSwap,
30
+ orderKey: "0xorderkey",
31
+ swapPath: [],
32
+ initialCollateralTokenAddress: USDC_ADDRESS,
33
+ initialCollateralDeltaAmount: "1000000",
34
+ minOutputAmount: "500000000000000",
35
+ executionAmountOut: "522169429885209",
36
+ shouldUnwrapNativeToken: false,
37
+ timestamp: 1786095479,
38
+ transactionHash: "0xdeadbeef",
39
+ };
40
+ const transform = (0, utils_1.createRawTradeActionTransformer)({}, weth, tokensData);
41
+ const transformSwap = (overrides) => transform({ ...rawSwapAction, ...overrides }, 0, []);
42
+ (0, vitest_1.describe)("createRawTradeActionTransformer", () => {
43
+ (0, vitest_1.it)("exposes the settled swap fee and swap price impact of a pure swap", () => {
44
+ const tradeAction = transformSwap({
45
+ swapFeeUsd: "499878460269198975000000000",
46
+ swapImpactUsd: "-933922965518581505565621250",
47
+ });
48
+ (0, vitest_1.expect)(tradeAction).toMatchObject({
49
+ type: "swap",
50
+ executionAmountOut: 522169429885209n,
51
+ swapFeeUsd: 499878460269198975000000000n,
52
+ swapImpactUsd: -933922965518581505565621250n,
53
+ });
54
+ });
55
+ (0, vitest_1.it)("keeps a genuine zero apart from missing source data", () => {
56
+ (0, vitest_1.expect)(transformSwap({ swapFeeUsd: "0", swapImpactUsd: "0" })).toMatchObject({
57
+ swapFeeUsd: 0n,
58
+ swapImpactUsd: 0n,
59
+ });
60
+ const withoutEconomics = transformSwap({ swapFeeUsd: null, swapImpactUsd: null });
61
+ (0, vitest_1.expect)(withoutEconomics).toHaveProperty("swapFeeUsd", undefined);
62
+ (0, vitest_1.expect)(withoutEconomics).toHaveProperty("swapImpactUsd", undefined);
63
+ });
64
+ });
@@ -39,6 +39,8 @@ function createRawTradeActionTransformer(marketsInfoData, wrappedToken, tokensDa
39
39
  initialCollateralDeltaAmount: (0, numbers_1.toBigInt)(rawAction.initialCollateralDeltaAmount),
40
40
  minOutputAmount: (0, numbers_1.toBigInt)(rawAction.minOutputAmount),
41
41
  executionAmountOut: rawAction.executionAmountOut ? (0, numbers_1.toBigInt)(rawAction.executionAmountOut) : undefined,
42
+ swapFeeUsd: (0, numbers_1.toBigInt)(rawAction.swapFeeUsd),
43
+ swapImpactUsd: (0, numbers_1.toBigInt)(rawAction.swapImpactUsd),
42
44
  shouldUnwrapNativeToken: rawAction.shouldUnwrapNativeToken,
43
45
  targetCollateralToken,
44
46
  initialCollateralToken,
@@ -1,5 +1,5 @@
1
1
  const config = {
2
- schema: "https://gmx.squids.live/gmx-synthetics-arbitrum@bac941/api/graphql",
2
+ schema: "https://gmx.squids.live/gmx-synthetics-arbitrum@c9407b/api/graphql",
3
3
  overwrite: true,
4
4
  debug: true,
5
5
  generates: {
@@ -14,6 +14,6 @@ export const arbitrumSdkConfig = {
14
14
  oracleUrl: "https://arbitrum-api.gmxinfra.io",
15
15
  rpcUrl: "https://arb1.arbitrum.io/rpc",
16
16
  walletClient: client,
17
- subsquidUrl: "https://gmx.squids.live/gmx-synthetics-arbitrum@bac941/api/graphql",
17
+ subsquidUrl: "https://gmx.squids.live/gmx-synthetics-arbitrum@c9407b/api/graphql",
18
18
  };
19
19
  export const arbitrumSdk = new GmxSdk(arbitrumSdkConfig);
@@ -1,7 +1,7 @@
1
1
  import { describe, expect, it } from "vitest";
2
- import { getTestSdk, getTestSigner } from "./testUtil";
2
+ import { getOrCreateTestSigner, getTestSdk } from "./testUtil";
3
3
  const sdk = getTestSdk();
4
- const signer = getTestSigner();
4
+ const signer = getOrCreateTestSigner();
5
5
  describe("GmxApiSdk — data fetching", () => {
6
6
  it("fetchMarketsInfo", async () => {
7
7
  const result = await sdk.fetchMarketsInfo();
@@ -51,8 +51,8 @@ describe("GmxApiSdk — data fetching", () => {
51
51
  });
52
52
  });
53
53
  describe("positions & orders", () => {
54
- const account = signer?.address;
55
- it.skipIf(!signer)("fetchPositionsInfo returns positions for account", async () => {
54
+ const account = signer.address;
55
+ it("fetchPositionsInfo returns positions for account", async () => {
56
56
  const positions = await sdk.fetchPositionsInfo({ address: account });
57
57
  expect(Array.isArray(positions)).toBe(true);
58
58
  if (positions.length > 0) {
@@ -61,7 +61,7 @@ describe("positions & orders", () => {
61
61
  expect(positions[0].sizeInUsd).toBeDefined();
62
62
  }
63
63
  });
64
- it.skipIf(!signer)("fetchPositionsInfo with includeRelatedOrders", async () => {
64
+ it("fetchPositionsInfo with includeRelatedOrders", async () => {
65
65
  const [without, withOrders] = await Promise.all([
66
66
  sdk.fetchPositionsInfo({ address: account }),
67
67
  sdk.fetchPositionsInfo({ address: account, includeRelatedOrders: true }),
@@ -69,7 +69,7 @@ describe("positions & orders", () => {
69
69
  expect(Array.isArray(withOrders)).toBe(true);
70
70
  expect(withOrders.length).toBeGreaterThanOrEqual(without.length);
71
71
  });
72
- it.skipIf(!signer)("fetchOrders returns orders array", async () => {
72
+ it("fetchOrders returns orders array", async () => {
73
73
  const orders = await sdk.fetchOrders({ address: account });
74
74
  expect(Array.isArray(orders)).toBe(true);
75
75
  });
@@ -1,5 +1,5 @@
1
1
  import { describe, expect, it, beforeAll, afterAll } from "vitest";
2
- import { getTestSdk, requireSigner, expressFlow, waitForOrderStatus, waitForOrdersUpdate, waitForPositionUpdate, activateTestSubaccount, hasRpcUrl, TEST_SYMBOL, TEST_SIZE_USD, } from "./testUtil";
2
+ import { getTestSdk, requireSigner, expressFlow, waitForOrderStatus, waitForOrderPlaced, PLACED_OK_STATUSES, waitForOrdersUpdate, waitForPositionUpdate, activateTestSubaccount, hasRpcUrl, shouldRunTwap, withinOneBp, TEST_SYMBOL, TEST_SIZE_USD, } from "./testUtil";
3
3
  const sdk = getTestSdk();
4
4
  const signer = requireSigner();
5
5
  const account = signer.address;
@@ -189,7 +189,7 @@ describe("decrease orders", () => {
189
189
  expect(prepared.estimates).toBeDefined();
190
190
  });
191
191
  });
192
- describe("TWAP decrease", () => {
192
+ describe.skipIf(!shouldRunTwap())("TWAP decrease", () => {
193
193
  afterAll(async () => {
194
194
  try {
195
195
  const prepared = await sdk.prepareCancelOrder({ all: true, mode: "express", from: account });
@@ -278,7 +278,7 @@ describe("decrease orders", () => {
278
278
  expect(prepared300.estimates.acceptablePrice).toBeGreaterThan(0n);
279
279
  // Size and fees unchanged between slippage variants
280
280
  expect(prepared30.estimates.sizeDeltaUsd).toBe(prepared300.estimates.sizeDeltaUsd);
281
- expect(prepared30.estimates.positionFeeUsd).toBe(prepared300.estimates.positionFeeUsd);
281
+ expect(withinOneBp(prepared30.estimates.positionFeeUsd, prepared300.estimates.positionFeeUsd)).toBe(true);
282
282
  });
283
283
  });
284
284
  describe("express conditional decrease", () => {
@@ -322,8 +322,8 @@ describe("decrease orders", () => {
322
322
  expect(prepared.estimates.executionFeeAmount).toBeGreaterThan(0n);
323
323
  expect(prepared.estimates.acceptablePrice).toBeLessThan(triggerPrice);
324
324
  expect(submitted.status).toBeDefined();
325
- const status = await waitForOrderStatus(sdk, submitted.requestId);
326
- expect(status.status).toBe("executed");
325
+ const status = await waitForOrderPlaced(sdk, submitted.requestId);
326
+ expect(PLACED_OK_STATUSES).toContain(status.status);
327
327
  const orders = await waitForOrdersUpdate(sdk, account, (o) => o.length > 0, 30000);
328
328
  expect(orders.length).toBeGreaterThan(0);
329
329
  });
@@ -346,8 +346,8 @@ describe("decrease orders", () => {
346
346
  expect(prepared.estimates.sizeDeltaUsd).toBe(TEST_SIZE_USD);
347
347
  expect(prepared.estimates.acceptablePrice).toBeGreaterThan(0n);
348
348
  expect(submitted.status).toBeDefined();
349
- const status = await waitForOrderStatus(sdk, submitted.requestId);
350
- expect(status.status).toBe("executed");
349
+ const status = await waitForOrderPlaced(sdk, submitted.requestId);
350
+ expect(PLACED_OK_STATUSES).toContain(status.status);
351
351
  const orders = await waitForOrdersUpdate(sdk, account, (o) => o.length > 0, 30000);
352
352
  expect(orders.length).toBeGreaterThan(0);
353
353
  });
@@ -1,5 +1,5 @@
1
1
  import { describe, expect, it, afterAll } from "vitest";
2
- import { getTestSdk, requireSigner, waitForOrderStatus, waitForOrdersUpdate, activateTestSubaccount, TEST_SYMBOL, TEST_SIZE_USD, TEST_COLLATERAL, } from "./testUtil";
2
+ import { getTestSdk, requireSigner, waitForOrderPlaced, PLACED_OK_STATUSES, waitForOrdersUpdate, activateTestSubaccount, TEST_SYMBOL, TEST_SIZE_USD, TEST_COLLATERAL, } from "./testUtil";
3
3
  const sdk = getTestSdk();
4
4
  const signer = requireSigner();
5
5
  const account = signer.address;
@@ -32,8 +32,8 @@ async function createLimitOrder(sdkInstance, triggerPrice = LIMIT_TRIGGER_PRICE)
32
32
  mode: "express",
33
33
  from: account,
34
34
  }, signer);
35
- const status = await waitForOrderStatus(sdkInstance, result.requestId);
36
- expect(status.status).toBe("executed");
35
+ const status = await waitForOrderPlaced(sdkInstance, result.requestId);
36
+ expect(PLACED_OK_STATUSES).toContain(status.status);
37
37
  return result;
38
38
  }
39
39
  describe("edit & cancel orders", () => {
@@ -79,8 +79,8 @@ describe("edit & cancel orders", () => {
79
79
  expect(prepared.payloadType).toBe("typed-data");
80
80
  const submitted = await signAndSubmit(sdk, prepared);
81
81
  expect(submitted.status).toBeDefined();
82
- const status = await waitForOrderStatus(sdk, submitted.requestId);
83
- expect(status.status).toBe("executed");
82
+ const status = await waitForOrderPlaced(sdk, submitted.requestId);
83
+ expect(PLACED_OK_STATUSES).toContain(status.status);
84
84
  const ordersAfter = await waitForOrdersUpdate(sdk, account, (ords) => {
85
85
  const edited = ords.find((o) => o.key === orderId);
86
86
  return edited ? BigInt(edited.triggerPrice) !== triggerBefore : false;
@@ -101,8 +101,8 @@ describe("edit & cancel orders", () => {
101
101
  expect(prepared.payloadType).toBe("typed-data");
102
102
  const submitted = await signAndSubmit(sdk, prepared);
103
103
  expect(submitted.status).toBeDefined();
104
- const status = await waitForOrderStatus(sdk, submitted.requestId);
105
- expect(status.status).toBe("executed");
104
+ const status = await waitForOrderPlaced(sdk, submitted.requestId);
105
+ expect(PLACED_OK_STATUSES).toContain(status.status);
106
106
  const ordersAfter = await waitForOrdersUpdate(sdk, account, (ords) => {
107
107
  return !ords.find((o) => o.key === orderId);
108
108
  }, 30000);
@@ -127,8 +127,8 @@ describe("edit & cancel orders", () => {
127
127
  expect(prepared.payloadType).toBe("typed-data");
128
128
  const submitted = await signAndSubmit(sdk, prepared);
129
129
  expect(submitted.status).toBeDefined();
130
- const status = await waitForOrderStatus(sdk, submitted.requestId);
131
- expect(status.status).toBe("executed");
130
+ const status = await waitForOrderPlaced(sdk, submitted.requestId);
131
+ expect(PLACED_OK_STATUSES).toContain(status.status);
132
132
  });
133
133
  });
134
134
  describe("1CT edit + cancel", () => {
@@ -176,8 +176,8 @@ describe("edit & cancel orders", () => {
176
176
  },
177
177
  });
178
178
  expect(submitted.requestId).toBeDefined();
179
- const status = await waitForOrderStatus(sdk, submitted.requestId);
180
- expect(status.status).toBe("executed");
179
+ const status = await waitForOrderPlaced(sdk, submitted.requestId);
180
+ expect(PLACED_OK_STATUSES).toContain(status.status);
181
181
  const updatedOrders = await waitForOrdersUpdate(sdk, account, (ords) => {
182
182
  const edited = ords.find((o) => o.key === orderId);
183
183
  return edited ? BigInt(edited.triggerPrice) !== triggerBefore : false;
@@ -217,8 +217,8 @@ describe("edit & cancel orders", () => {
217
217
  },
218
218
  });
219
219
  expect(submitted.requestId).toBeDefined();
220
- const status = await waitForOrderStatus(sdk, submitted.requestId);
221
- expect(status.status).toBe("executed");
220
+ const status = await waitForOrderPlaced(sdk, submitted.requestId);
221
+ expect(PLACED_OK_STATUSES).toContain(status.status);
222
222
  const updatedOrders = await waitForOrdersUpdate(sdk, account, (ords) => {
223
223
  return !ords.find((o) => o.key === orderId);
224
224
  }, 30000);
@@ -1,7 +1,7 @@
1
1
  import { describe, expect, it } from "vitest";
2
- import { getTestSdk, requireSigner, expressFlow, waitForOrderStatus, TEST_SYMBOL, TEST_SIZE_USD, TEST_COLLATERAL, } from "./testUtil";
2
+ import { getOrCreateTestSigner, getTestSdk, TEST_SYMBOL, TEST_SIZE_USD, TEST_COLLATERAL } from "./testUtil";
3
3
  const sdk = getTestSdk();
4
- const signer = requireSigner();
4
+ const signer = getOrCreateTestSigner();
5
5
  const account = signer.address;
6
6
  describe("validation errors", () => {
7
7
  describe("prepare validation", () => {
@@ -212,50 +212,4 @@ describe("validation errors", () => {
212
212
  })).rejects.toThrow();
213
213
  });
214
214
  });
215
- describe("order lifecycle tracking", () => {
216
- it("status transitions from initial to executed", async () => {
217
- const { submitted } = await expressFlow(sdk, signer, {
218
- kind: "increase",
219
- symbol: TEST_SYMBOL,
220
- direction: "long",
221
- orderType: "market",
222
- size: TEST_SIZE_USD,
223
- collateralToken: "USDC",
224
- collateralToPay: TEST_COLLATERAL,
225
- mode: "express",
226
- from: account,
227
- });
228
- const initial = await sdk.fetchOrderStatus({ requestId: submitted.requestId });
229
- expect(["relay_accepted", "relay_pending", "relay_submitted", "created", "executed"]).toContain(initial.status);
230
- expect(initial.requestId).toBe(submitted.requestId);
231
- const terminal = await waitForOrderStatus(sdk, submitted.requestId);
232
- expect(terminal.status).toBe("executed");
233
- expect(terminal.requestId).toBe(submitted.requestId);
234
- });
235
- it("terminal status has populated fields", async () => {
236
- const { submitted } = await expressFlow(sdk, signer, {
237
- kind: "increase",
238
- symbol: TEST_SYMBOL,
239
- direction: "long",
240
- orderType: "market",
241
- size: TEST_SIZE_USD,
242
- collateralToken: "USDC",
243
- collateralToPay: TEST_COLLATERAL,
244
- mode: "express",
245
- from: account,
246
- });
247
- const status = await waitForOrderStatus(sdk, submitted.requestId);
248
- expect(status.status).toBe("executed");
249
- expect(status.requestId).toBeDefined();
250
- // createdTxnHash may not be populated immediately for all executed orders
251
- if (status.createdTxnHash)
252
- expect(status.createdTxnHash.startsWith("0x")).toBe(true);
253
- if (status.executionTxnHash)
254
- expect(status.executionTxnHash.startsWith("0x")).toBe(true);
255
- if (status.createdAt)
256
- expect(typeof status.createdAt).toBe("string");
257
- if (status.updatedAt)
258
- expect(typeof status.updatedAt).toBe("string");
259
- });
260
- });
261
215
  });
@@ -0,0 +1,51 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { getTestSdk, requireSigner, expressFlow, waitForOrderStatus, TEST_SYMBOL, TEST_SIZE_USD, TEST_COLLATERAL, } from "./testUtil";
3
+ const sdk = getTestSdk();
4
+ const signer = requireSigner();
5
+ const account = signer.address;
6
+ describe("order lifecycle tracking", () => {
7
+ it("status transitions from initial to executed", async () => {
8
+ const { submitted } = await expressFlow(sdk, signer, {
9
+ kind: "increase",
10
+ symbol: TEST_SYMBOL,
11
+ direction: "long",
12
+ orderType: "market",
13
+ size: TEST_SIZE_USD,
14
+ collateralToken: "USDC",
15
+ collateralToPay: TEST_COLLATERAL,
16
+ mode: "express",
17
+ from: account,
18
+ });
19
+ const initial = await sdk.fetchOrderStatus({ requestId: submitted.requestId });
20
+ expect(["relay_accepted", "relay_pending", "relay_submitted", "created", "executed"]).toContain(initial.status);
21
+ expect(initial.requestId).toBe(submitted.requestId);
22
+ const terminal = await waitForOrderStatus(sdk, submitted.requestId);
23
+ expect(terminal.status).toBe("executed");
24
+ expect(terminal.requestId).toBe(submitted.requestId);
25
+ });
26
+ it("terminal status has populated fields", async () => {
27
+ const { submitted } = await expressFlow(sdk, signer, {
28
+ kind: "increase",
29
+ symbol: TEST_SYMBOL,
30
+ direction: "long",
31
+ orderType: "market",
32
+ size: TEST_SIZE_USD,
33
+ collateralToken: "USDC",
34
+ collateralToPay: TEST_COLLATERAL,
35
+ mode: "express",
36
+ from: account,
37
+ });
38
+ const status = await waitForOrderStatus(sdk, submitted.requestId);
39
+ expect(status.status).toBe("executed");
40
+ expect(status.requestId).toBeDefined();
41
+ // createdTxnHash may not be populated immediately for all executed orders
42
+ if (status.createdTxnHash)
43
+ expect(status.createdTxnHash.startsWith("0x")).toBe(true);
44
+ if (status.executionTxnHash)
45
+ expect(status.executionTxnHash.startsWith("0x")).toBe(true);
46
+ if (status.createdAt)
47
+ expect(typeof status.createdAt).toBe("string");
48
+ if (status.updatedAt)
49
+ expect(typeof status.updatedAt).toBe("string");
50
+ });
51
+ });
@@ -0,0 +1,77 @@
1
+ import { expressFlow, getTestSdk, getTestSigner, waitForOrderStatus } from "./testUtil";
2
+ // The wallet is shared between runs, so anything left behind keeps holding collateral.
3
+ async function sweep(label) {
4
+ const signer = getTestSigner();
5
+ if (!signer)
6
+ return;
7
+ const sdk = getTestSdk();
8
+ const account = signer.address;
9
+ try {
10
+ const orders = await sdk.fetchOrders({ address: account });
11
+ if (orders.length > 0) {
12
+ const prepared = await sdk.prepareCancelOrder({ all: true, mode: "express", from: account });
13
+ const signature = await sdk.signOrder(prepared, signer);
14
+ await sdk.submitOrder({
15
+ mode: prepared.mode,
16
+ requestId: prepared.requestId,
17
+ signature,
18
+ from: account,
19
+ idempotencyKey: prepared.idempotencyKey,
20
+ eip712Data: {
21
+ batchParams: prepared.payload.batchParams,
22
+ relayParams: prepared.payload.relayParams,
23
+ },
24
+ });
25
+ // eslint-disable-next-line no-console
26
+ console.log(`[cleanup:${label}] cancelled ${orders.length} resting order(s)`);
27
+ }
28
+ }
29
+ catch (error) {
30
+ // eslint-disable-next-line no-console
31
+ console.warn(`[cleanup:${label}] cancel-all failed:`, error.message);
32
+ }
33
+ // A close can settle after the snapshot, so re-read instead of trusting one pass.
34
+ for (let attempt = 0; attempt < 4; attempt++) {
35
+ let positions;
36
+ try {
37
+ positions = await sdk.fetchPositionsInfo({ address: account });
38
+ }
39
+ catch (error) {
40
+ // eslint-disable-next-line no-console
41
+ console.warn(`[cleanup:${label}] fetchPositions failed:`, error.message);
42
+ return;
43
+ }
44
+ const open = positions.filter((p) => BigInt(p.sizeInUsd) > 0n);
45
+ if (open.length === 0)
46
+ return;
47
+ for (const position of open) {
48
+ try {
49
+ const { submitted } = await expressFlow(sdk, signer, {
50
+ kind: "decrease",
51
+ symbol: position.marketAddress,
52
+ direction: position.isLong ? "long" : "short",
53
+ orderType: "market",
54
+ size: BigInt(position.sizeInUsd),
55
+ collateralToken: position.collateralTokenAddress,
56
+ // Settle into USDC, or the wallet drifts into the index token.
57
+ receiveToken: "USDC",
58
+ mode: "express",
59
+ from: account,
60
+ });
61
+ await waitForOrderStatus(sdk, submitted.requestId);
62
+ // eslint-disable-next-line no-console
63
+ console.log(`[cleanup:${label}] closed position on ${position.marketAddress}`);
64
+ }
65
+ catch (error) {
66
+ // eslint-disable-next-line no-console
67
+ console.warn(`[cleanup:${label}] close failed for ${position.marketAddress}:`, error.message);
68
+ }
69
+ }
70
+ }
71
+ }
72
+ export default async function setup() {
73
+ await sweep("before");
74
+ return async () => {
75
+ await sweep("after");
76
+ };
77
+ }
@@ -1,5 +1,5 @@
1
1
  import { describe, expect, it, beforeAll, afterAll } from "vitest";
2
- import { getTestSdk, requireSigner, expressFlow, waitForOrderStatus, waitForOrdersUpdate, waitForPositionUpdate, activateTestSubaccount, hasRpcUrl, TEST_SYMBOL, TEST_SIZE_USD, TEST_COLLATERAL, } from "./testUtil";
2
+ import { getTestSdk, requireSigner, expressFlow, waitForOrderStatus, waitForOrderPlaced, PLACED_OK_STATUSES, waitForOrdersUpdate, waitForPositionUpdate, activateTestSubaccount, hasRpcUrl, shouldRunTwap, withinOneBp, TEST_SYMBOL, TEST_SIZE_USD, TEST_COLLATERAL, } from "./testUtil";
3
3
  const sdk = getTestSdk();
4
4
  const signer = requireSigner();
5
5
  const account = signer.address;
@@ -85,7 +85,7 @@ describe("increase orders", () => {
85
85
  expect(status.requestId).toBe(submitted.requestId);
86
86
  });
87
87
  it("larger collateral: position fee scales with size not collateral", async () => {
88
- const collateral = { amount: 2000000n, token: "USDC" }; // 2 USDC vs 1 USDC in TEST_COLLATERAL
88
+ const collateral = { amount: TEST_COLLATERAL.amount * 2n, token: "USDC" };
89
89
  const [small, large] = await Promise.all([
90
90
  sdk.prepareOrder({
91
91
  kind: "increase",
@@ -109,7 +109,7 @@ describe("increase orders", () => {
109
109
  }),
110
110
  ]);
111
111
  // Same size → same position fee regardless of collateral amount
112
- expect(small.estimates.positionFeeUsd).toBe(large.estimates.positionFeeUsd);
112
+ expect(withinOneBp(small.estimates.positionFeeUsd, large.estimates.positionFeeUsd)).toBe(true);
113
113
  expect(small.estimates.sizeDeltaUsd).toBe(large.estimates.sizeDeltaUsd);
114
114
  });
115
115
  });
@@ -122,7 +122,7 @@ describe("increase orders", () => {
122
122
  orderType: "market",
123
123
  size: TEST_SIZE_USD,
124
124
  collateralToken: "USDC",
125
- collateralToPay: { amount: 1000000n, token: "USDC" },
125
+ collateralToPay: TEST_COLLATERAL,
126
126
  mode: "express",
127
127
  from: account,
128
128
  });
@@ -142,7 +142,7 @@ describe("increase orders", () => {
142
142
  direction: "long",
143
143
  orderType: "market",
144
144
  size: TEST_SIZE_USD,
145
- collateralToPay: { amount: 1000000n, token: "USDC" },
145
+ collateralToPay: TEST_COLLATERAL,
146
146
  mode: "express",
147
147
  from: account,
148
148
  });
@@ -160,7 +160,7 @@ describe("increase orders", () => {
160
160
  orderType: "market",
161
161
  size: TEST_SIZE_USD,
162
162
  collateralToken: "USDC",
163
- collateralToPay: { amount: 1000000n, token: "USDC" },
163
+ collateralToPay: TEST_COLLATERAL,
164
164
  mode: "express",
165
165
  from: account,
166
166
  }),
@@ -170,7 +170,7 @@ describe("increase orders", () => {
170
170
  direction: "long",
171
171
  orderType: "market",
172
172
  size: TEST_SIZE_USD,
173
- collateralToPay: { amount: 1000000n, token: "USDC" },
173
+ collateralToPay: TEST_COLLATERAL,
174
174
  mode: "express",
175
175
  from: account,
176
176
  }),
@@ -192,7 +192,7 @@ describe("increase orders", () => {
192
192
  direction: "long",
193
193
  orderType: "market",
194
194
  size: TEST_SIZE_USD,
195
- collateralToPay: { amount: 1000000n, token: "USDC" },
195
+ collateralToPay: TEST_COLLATERAL,
196
196
  mode: "express",
197
197
  from: account,
198
198
  }),
@@ -202,7 +202,7 @@ describe("increase orders", () => {
202
202
  direction: "long",
203
203
  orderType: "market",
204
204
  size: TEST_SIZE_USD,
205
- collateralToPay: { amount: 1000000n, token: "USDC" },
205
+ collateralToPay: TEST_COLLATERAL,
206
206
  manualSwapPath: [ETH_USD_MARKET_ADDRESS],
207
207
  mode: "express",
208
208
  from: account,
@@ -384,7 +384,7 @@ describe("increase orders", () => {
384
384
  })).rejects.toThrow();
385
385
  });
386
386
  });
387
- describe("TWAP increase", () => {
387
+ describe.skipIf(!shouldRunTwap())("TWAP increase", () => {
388
388
  afterAll(cancelAllOrders);
389
389
  it("TWAP market increase — creates sub-orders", async () => {
390
390
  const twapSize = 20n * 10n ** 30n; // $20
@@ -482,9 +482,9 @@ describe("increase orders", () => {
482
482
  expect(prepared.estimates.positionFeeUsd).toBeGreaterThan(0n);
483
483
  expect(prepared.estimates.acceptablePrice).toBeGreaterThan(triggerPrice);
484
484
  expect(submitted.status).toBeDefined();
485
- const status = await waitForOrderStatus(sdk, submitted.requestId);
485
+ const status = await waitForOrderPlaced(sdk, submitted.requestId);
486
486
  expect(status.requestId).toBe(submitted.requestId);
487
- expect(status.status).toBe("executed");
487
+ expect(PLACED_OK_STATUSES).toContain(status.status);
488
488
  const orders = await waitForOrdersUpdate(sdk, account, (o) => o.length > 0, 30000);
489
489
  expect(orders.length).toBeGreaterThan(0);
490
490
  const order = orders.find((o) => o.isLong && BigInt(o.sizeDeltaUsd) > 0n);
@@ -523,7 +523,7 @@ describe("increase orders", () => {
523
523
  sdk.prepareOrder({ ...baseRequest, slippage: 300 }),
524
524
  ]);
525
525
  expect(prepared30.estimates.sizeDeltaUsd).toBe(prepared300.estimates.sizeDeltaUsd);
526
- expect(prepared30.estimates.positionFeeUsd).toBe(prepared300.estimates.positionFeeUsd);
526
+ expect(withinOneBp(prepared30.estimates.positionFeeUsd, prepared300.estimates.positionFeeUsd)).toBe(true);
527
527
  });
528
528
  });
529
529
  describe("executionFeeBufferBps", () => {
@@ -550,8 +550,8 @@ describe("increase orders", () => {
550
550
  sdk.prepareOrder({ ...baseRequest, executionFeeBufferBps: 5000 }),
551
551
  ]);
552
552
  expect(prepared0.estimates.sizeDeltaUsd).toBe(prepared5000.estimates.sizeDeltaUsd);
553
- expect(prepared0.estimates.positionFeeUsd).toBe(prepared5000.estimates.positionFeeUsd);
554
- expect(prepared0.estimates.acceptablePrice).toBe(prepared5000.estimates.acceptablePrice);
553
+ expect(withinOneBp(prepared0.estimates.positionFeeUsd, prepared5000.estimates.positionFeeUsd)).toBe(true);
554
+ expect(withinOneBp(prepared0.estimates.acceptablePrice, prepared5000.estimates.acceptablePrice)).toBe(true);
555
555
  });
556
556
  });
557
557
  describe("express convenience method", () => {
@@ -1,17 +1,16 @@
1
1
  import { isAddress } from "viem";
2
2
  import { beforeAll, describe, expect, it } from "vitest";
3
3
  import { ensureSourceErc20Allowance, expectArbitrumSettlement, getSourceSigner, shouldSendOnChain, STARGATE_USDC_ARBITRUM, STARGATE_USDC_BASE, TEST_SOURCE_CHAIN_ID, USDC_ARBITRUM, USDC_BASE, waitForWithdrawStatus, } from "./multichainTestUtil";
4
- import { getTestSdk, getTestSigner } from "./testUtil";
4
+ import { getOrCreateTestSigner, getTestSdk } from "./testUtil";
5
5
  beforeAll(() => {
6
6
  expectArbitrumSettlement();
7
7
  });
8
8
  const sdk = getTestSdk();
9
- const signer = getTestSigner();
10
- const account = signer?.address ?? "";
11
- const hasSigner = signer !== undefined;
9
+ const signer = getOrCreateTestSigner();
10
+ const account = signer.address;
12
11
  const DEPOSIT_AMOUNT = 1000000n; // 1 USDC
13
12
  const WITHDRAW_AMOUNT = 500000n; // 0.5 USDC
14
- describe.skipIf(!hasSigner)("multichain same-chain (build only)", () => {
13
+ describe("multichain same-chain (build only)", () => {
15
14
  it("deposit: multicall(sendTokens + bridgeIn)", () => {
16
15
  const built = sdk.buildSameChainDepositTxn({
17
16
  tokenAddress: USDC_ARBITRUM,
@@ -33,7 +32,7 @@ describe.skipIf(!hasSigner)("multichain same-chain (build only)", () => {
33
32
  expect(built.value).toBe(0n);
34
33
  });
35
34
  });
36
- describe.skipIf(!hasSigner)("multichain cross-chain deposit (Base → Arbitrum, API-driven)", () => {
35
+ describe("multichain cross-chain deposit (Base → Arbitrum, API-driven)", () => {
37
36
  it("prepare: server resolves pools + quotes nativeFee + composeGas (tokenSymbol)", async () => {
38
37
  const prepared = await sdk.prepareCrossChainDeposit({
39
38
  srcChainId: TEST_SOURCE_CHAIN_ID,
@@ -77,7 +76,7 @@ describe.skipIf(!hasSigner)("multichain cross-chain deposit (Base → Arbitrum,
77
76
  expect(result.nativeFee).toBeGreaterThan(0n);
78
77
  });
79
78
  });
80
- describe.skipIf(!hasSigner)("multichain cross-chain withdraw (Arbitrum → Base, via Gelato)", () => {
79
+ describe("multichain cross-chain withdraw (Arbitrum → Base, via Gelato)", () => {
81
80
  it("prepare: returns typed-data + gasPaymentParams", async () => {
82
81
  const bridgeOutParams = sdk.buildCrossChainWithdrawBridgeOutParams({
83
82
  tokenAddress: USDC_ARBITRUM,