@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,165 @@
1
+ import { describe, expect, expectTypeOf, it } from "vitest";
2
+ import { prepareOrder } from "../../../utils/orderTransactions/api";
3
+ import { HttpError, isPrepareOrderError, parsePrepareOrderError } from "../index";
4
+ const MAX_UINT256 = 2n ** 256n - 1n;
5
+ class PrepareApi {
6
+ constructor(response) {
7
+ this.response = response;
8
+ this.url = "http://test";
9
+ }
10
+ fetchJson() {
11
+ return Promise.reject(new Error("Unexpected fetchJson call"));
12
+ }
13
+ postJson(_path, _body, opts) {
14
+ const result = this.response;
15
+ return Promise.resolve(opts?.transform ? opts.transform(result) : result);
16
+ }
17
+ }
18
+ function buildCapacity() {
19
+ return {
20
+ availableLiquidity: "100",
21
+ baseAvailableLiquidity: "80",
22
+ jitAvailableLiquidity: "20",
23
+ limitingFactor: "reserve",
24
+ jitDataStatus: "available",
25
+ marketDataStatus: "fresh",
26
+ };
27
+ }
28
+ function buildInsufficientLiquidityBody(requestedSizeUsd) {
29
+ return {
30
+ code: "INSUFFICIENT_LIQUIDITY",
31
+ message: "Insufficient liquidity",
32
+ details: { ...buildCapacity(), requestedSizeUsd },
33
+ };
34
+ }
35
+ function buildPrepareResponse(requestedSizeUsd) {
36
+ return {
37
+ requestId: "request-1",
38
+ payloadType: "transaction",
39
+ mode: "classic",
40
+ payload: {},
41
+ validationWarnings: [buildInsufficientLiquidityBody(requestedSizeUsd)],
42
+ };
43
+ }
44
+ const prepareRequest = {
45
+ kind: "increase",
46
+ symbol: "ETH/USD [WETH-USDC]",
47
+ direction: "long",
48
+ orderType: "limit",
49
+ size: 1n,
50
+ mode: "classic",
51
+ from: "0x1111111111111111111111111111111111111111",
52
+ };
53
+ describe("prepare order errors", () => {
54
+ it("parses and deserializes an insufficient-liquidity HttpError", () => {
55
+ const error = new HttpError(400, "Bad Request", buildInsufficientLiquidityBody(MAX_UINT256.toString()));
56
+ const parsed = parsePrepareOrderError(error);
57
+ expect(parsed).toEqual({
58
+ code: "INSUFFICIENT_LIQUIDITY",
59
+ message: "Insufficient liquidity",
60
+ details: {
61
+ availableLiquidity: 100n,
62
+ baseAvailableLiquidity: 80n,
63
+ jitAvailableLiquidity: 20n,
64
+ limitingFactor: "reserve",
65
+ jitDataStatus: "available",
66
+ marketDataStatus: "fresh",
67
+ requestedSizeUsd: MAX_UINT256,
68
+ },
69
+ });
70
+ expect(isPrepareOrderError(parsed)).toBe(true);
71
+ expect(isPrepareOrderError(buildInsufficientLiquidityBody(MAX_UINT256.toString()))).toBe(false);
72
+ if (parsed?.code !== "INSUFFICIENT_LIQUIDITY") {
73
+ throw new Error("Expected insufficient-liquidity error");
74
+ }
75
+ expectTypeOf(parsed.details.requestedSizeUsd).toEqualTypeOf();
76
+ });
77
+ it.each([
78
+ "INVALID_PARAMS",
79
+ "MARKET_NOT_FOUND",
80
+ "TOKEN_NOT_FOUND",
81
+ "NO_SWAP_PATH",
82
+ "POSITION_NOT_FOUND",
83
+ ])("parses the documented %s error", (code) => {
84
+ const parsed = parsePrepareOrderError(new HttpError(400, "Bad Request", { code, message: "Prepare failed" }));
85
+ expect(parsed).toEqual({ code, message: "Prepare failed" });
86
+ expect(isPrepareOrderError(parsed)).toBe(true);
87
+ });
88
+ it("preserves an unknown error code and diagnostics", () => {
89
+ const parsed = parsePrepareOrderError(new HttpError(400, "Bad Request", {
90
+ code: "FUTURE_ERROR",
91
+ message: "Prepare failed",
92
+ traceId: "trace-1",
93
+ }));
94
+ expect(parsed).toEqual({
95
+ code: "UNKNOWN_PREPARE_ORDER_ERROR",
96
+ originalCode: "FUTURE_ERROR",
97
+ message: "Prepare failed",
98
+ traceId: "trace-1",
99
+ });
100
+ expect(isPrepareOrderError(parsed)).toBe(true);
101
+ });
102
+ it("parses a documented code-less bad request", () => {
103
+ const parsed = parsePrepareOrderError(new HttpError(400, "Bad Request", { message: "Invalid request" }));
104
+ expect(parsed).toEqual({ message: "Invalid request" });
105
+ expect(isPrepareOrderError(parsed)).toBe(true);
106
+ });
107
+ it("parses documented field validation errors", () => {
108
+ const parsed = parsePrepareOrderError(new HttpError(400, "Bad Request", {
109
+ message: {
110
+ size: { message: "size must be a positive integer", value: "invalid" },
111
+ symbol: { message: "symbol is required" },
112
+ },
113
+ }));
114
+ expect(parsed).toEqual({
115
+ message: {
116
+ size: { message: "size must be a positive integer", value: "invalid" },
117
+ symbol: { message: "symbol is required" },
118
+ },
119
+ });
120
+ expect(isPrepareOrderError(parsed)).toBe(true);
121
+ });
122
+ it.each([
123
+ ["a non-HTTP error", new Error("Prepare failed")],
124
+ ["a non-400 response", new HttpError(500, "Internal Server Error", buildInsufficientLiquidityBody("101"))],
125
+ ["a raw response body", buildInsufficientLiquidityBody("101")],
126
+ ["an empty error code", new HttpError(400, "Bad Request", { code: "", message: "Prepare failed" })],
127
+ [
128
+ "malformed field validation errors",
129
+ new HttpError(400, "Bad Request", { message: { size: { value: "invalid" } } }),
130
+ ],
131
+ [
132
+ "malformed capacity details",
133
+ new HttpError(400, "Bad Request", {
134
+ ...buildInsufficientLiquidityBody("101"),
135
+ details: { requestedSizeUsd: "101" },
136
+ }),
137
+ ],
138
+ ])("does not classify %s as a prepare error", (_description, error) => {
139
+ expect(parsePrepareOrderError(error)).toBeUndefined();
140
+ });
141
+ it.each([true, 1, 1.5, null, undefined, "", "-1", "+1", "01", "1.0", "0x1", (MAX_UINT256 + 1n).toString()])("rejects non-canonical requestedSizeUsd %p in error details", (requestedSizeUsd) => {
142
+ const error = new HttpError(400, "Bad Request", buildInsufficientLiquidityBody(requestedSizeUsd));
143
+ expect(parsePrepareOrderError(error)).toBeUndefined();
144
+ });
145
+ });
146
+ describe("prepare order warning amount parsing", () => {
147
+ it.each([true, 1, 1.5, null, undefined, "", "-1", "+1", "01", "1.0", "0x1", (MAX_UINT256 + 1n).toString()])("degrades non-canonical requestedSizeUsd %p to an unknown warning", async (requestedSizeUsd) => {
148
+ const prepared = await prepareOrder({ api: new PrepareApi(buildPrepareResponse(requestedSizeUsd)) }, prepareRequest);
149
+ expect(prepared.validationWarnings).toEqual([
150
+ {
151
+ code: "UNKNOWN_VALIDATION_WARNING",
152
+ originalCode: "INSUFFICIENT_LIQUIDITY",
153
+ message: "Insufficient liquidity",
154
+ details: { ...buildCapacity(), requestedSizeUsd },
155
+ },
156
+ ]);
157
+ });
158
+ it("accepts the canonical zero amount", async () => {
159
+ const prepared = await prepareOrder({ api: new PrepareApi(buildPrepareResponse("0")) }, prepareRequest);
160
+ expect(prepared.validationWarnings?.[0]).toMatchObject({
161
+ code: "INSUFFICIENT_LIQUIDITY",
162
+ details: { requestedSizeUsd: 0n },
163
+ });
164
+ });
165
+ });
@@ -0,0 +1,30 @@
1
+ import { createPublicClient, erc20Abi, http } from "viem";
2
+ import { beforeAll } from "vitest";
3
+ import { getViemChain } from "../../../configs/chains";
4
+ import { getContract } from "../../../configs/contracts";
5
+ import { getTestSdk, getTestSigner, TEST_CHAIN_ID } from "./testUtil";
6
+ const USDC_ARBITRUM = "0xaf88d065e77c8cC2239327C5EDb3A432268e5831";
7
+ // Collateral is pulled through SyntheticsRouter; without an allowance every submit reverts.
8
+ beforeAll(async () => {
9
+ const signer = getTestSigner();
10
+ // eslint-disable-next-line no-restricted-globals
11
+ const rpcUrl = process.env.GMX_TEST_RPC_URL;
12
+ if (!signer || !rpcUrl)
13
+ return;
14
+ const spender = getContract(TEST_CHAIN_ID, "SyntheticsRouter");
15
+ const owner = signer.address;
16
+ const client = createPublicClient({ chain: getViemChain(TEST_CHAIN_ID), transport: http(rpcUrl) });
17
+ const current = (await client.readContract({
18
+ address: USDC_ARBITRUM,
19
+ abi: erc20Abi,
20
+ functionName: "allowance",
21
+ args: [owner, spender],
22
+ }));
23
+ if (current > 0n)
24
+ return;
25
+ const txHash = await getTestSdk().executeErc20Approve(signer, {
26
+ tokenAddress: USDC_ARBITRUM,
27
+ spender,
28
+ });
29
+ await client.waitForTransactionReceipt({ hash: txHash });
30
+ }, 120000);
@@ -1,9 +1,8 @@
1
1
  import { describe, expect, it } from "vitest";
2
2
  import { getEmptySubaccountApproval } from "../../../utils/subaccount";
3
3
  import { GmxApiSdk } from "../index";
4
- import { buildPreparedOrderResponse, buildSubaccountStatusResponse, getTestSdk, getTestSigner, RecordingApi, ScriptedOrderApi, TEST_CHAIN_ID, TEST_COLLATERAL, TEST_SIZE_USD, TEST_SYMBOL, } from "./testUtil";
5
- const signer = getTestSigner();
6
- const hasSigner = !!signer;
4
+ import { buildPreparedOrderResponse, buildSubaccountStatusResponse, getOrCreateTestSigner, getTestSdk, ScriptedOrderApi, TEST_CHAIN_ID, TEST_COLLATERAL, TEST_SIZE_USD, TEST_SYMBOL, } from "./testUtil";
5
+ const signer = getOrCreateTestSigner();
7
6
  const LIMIT_TRIGGER_PRICE = 1n * 10n ** 30n;
8
7
  const EXTERNAL_SUBACCOUNT_ADDRESS = "0x1111111111111111111111111111111111111111";
9
8
  function buildTestPrepareRequest(from) {
@@ -20,35 +19,8 @@ function buildTestPrepareRequest(from) {
20
19
  from,
21
20
  };
22
21
  }
23
- async function waitForSubaccountNoopApproval(sdk, account) {
24
- const startedAt = Date.now();
25
- while (Date.now() - startedAt < 30000) {
26
- await sdk.refreshSubaccountState(account);
27
- if (sdk.subaccountApprovalMessage?.signature === "0x") {
28
- return;
29
- }
30
- await new Promise((resolve) => setTimeout(resolve, 2000));
31
- }
32
- throw new Error("Timed out waiting for subaccount approval to sync on-chain");
33
- }
34
- async function waitForOrderCreatedOrExecuted(sdk, requestId) {
35
- const startedAt = Date.now();
36
- while (Date.now() - startedAt < 180000) {
37
- const status = await sdk.fetchOrderStatus({ requestId });
38
- if (status.status === "created" ||
39
- status.status === "executed" ||
40
- status.status === "cancelled" ||
41
- status.status === "relay_failed" ||
42
- status.status === "relay_reverted") {
43
- return status;
44
- }
45
- await new Promise((resolve) => setTimeout(resolve, 2000));
46
- }
47
- return sdk.fetchOrderStatus({ requestId });
48
- }
49
22
  describe("GmxApiSdk — subaccount (1CT)", () => {
50
- it.skipIf(!hasSigner)("rejects external subaccount details for SDK-managed signing", async () => {
51
- const signer = getTestSigner();
23
+ it("rejects external subaccount details for SDK-managed signing", async () => {
52
24
  const api = new ScriptedOrderApi(buildPreparedOrderResponse("request-1"));
53
25
  const sdk = new GmxApiSdk({ chainId: TEST_CHAIN_ID, api });
54
26
  const subaccountAddress = await sdk.generateSubaccount(signer);
@@ -63,8 +35,7 @@ describe("GmxApiSdk — subaccount (1CT)", () => {
63
35
  })).rejects.toThrow("subaccountApproval.subaccount");
64
36
  expect(api.prepareRequests).toHaveLength(0);
65
37
  });
66
- it.skipIf(!hasSigner)("keeps prepared subaccount approval after failed submit response", async () => {
67
- const signer = getTestSigner();
38
+ it("keeps prepared subaccount approval after failed submit response", async () => {
68
39
  const requestId = "retry-request";
69
40
  const api = new ScriptedOrderApi(buildPreparedOrderResponse(requestId), [
70
41
  {
@@ -100,8 +71,7 @@ describe("GmxApiSdk — subaccount (1CT)", () => {
100
71
  expect(api.submitRequests[0].eip712Data?.subaccountApproval?.signature).toBe("0x");
101
72
  expect(api.submitRequests[1].eip712Data?.subaccountApproval?.signature).toBe("0x");
102
73
  });
103
- it.skipIf(!hasSigner)("decrements cached subaccount actions only after final order status", async () => {
104
- const signer = getTestSigner();
74
+ it("decrements cached subaccount actions only after final order status", async () => {
105
75
  const requestId = "accepted-request";
106
76
  const api = new ScriptedOrderApi(buildPreparedOrderResponse(requestId), [
107
77
  {
@@ -131,8 +101,7 @@ describe("GmxApiSdk — subaccount (1CT)", () => {
131
101
  expect(sdk.subaccountStatus?.currentActionsCount).toBe(4n);
132
102
  expect(sdk.subaccountStatus?.remainingActions).toBe(1n);
133
103
  });
134
- it.skipIf(!hasSigner)("does not decrement cached subaccount actions for relay_accepted status", async () => {
135
- const signer = getTestSigner();
104
+ it("does not decrement cached subaccount actions for relay_accepted status", async () => {
136
105
  const requestId = "relay-accepted-request";
137
106
  const api = new ScriptedOrderApi(buildPreparedOrderResponse(requestId), [
138
107
  {
@@ -162,8 +131,7 @@ describe("GmxApiSdk — subaccount (1CT)", () => {
162
131
  expect(sdk.subaccountStatus?.currentActionsCount).toBe(3n);
163
132
  expect(sdk.subaccountStatus?.remainingActions).toBe(2n);
164
133
  });
165
- it.skipIf(!hasSigner)("refreshes subaccount state before noop approval when only one action remains", async () => {
166
- const signer = getTestSigner();
134
+ it("refreshes subaccount state before noop approval when only one action remains", async () => {
167
135
  const api = new ScriptedOrderApi(buildPreparedOrderResponse("request-1"), [], [
168
136
  buildSubaccountStatusResponse({
169
137
  currentActionsCount: "9",
@@ -181,8 +149,7 @@ describe("GmxApiSdk — subaccount (1CT)", () => {
181
149
  expect(api.subaccountStatusRequests).toHaveLength(2);
182
150
  expect(api.prepareRequests).toHaveLength(0);
183
151
  });
184
- it.skipIf(!hasSigner)("validates caller-supplied noop approval against exhausted subaccount quota", async () => {
185
- const signer = getTestSigner();
152
+ it("validates caller-supplied noop approval against exhausted subaccount quota", async () => {
186
153
  const api = new ScriptedOrderApi(buildPreparedOrderResponse("request-1"), [], [
187
154
  buildSubaccountStatusResponse({
188
155
  currentActionsCount: "10",
@@ -199,81 +166,7 @@ describe("GmxApiSdk — subaccount (1CT)", () => {
199
166
  })).rejects.toThrow("Subaccount is not active");
200
167
  expect(api.prepareRequests).toHaveLength(0);
201
168
  });
202
- it.skipIf(!hasSigner)("e2e applies approval once and uses noop approval for the next order", async () => {
203
- const signer = getTestSigner();
204
- const account = signer.address;
205
- const recordingApi = new RecordingApi(getTestSdk().ctx.api);
206
- const sdkSub = new GmxApiSdk({ chainId: TEST_CHAIN_ID, api: recordingApi });
207
- const cleanupSdk = new GmxApiSdk({ chainId: TEST_CHAIN_ID, api: recordingApi });
208
- try {
209
- const subaccountAddress = await sdkSub.generateSubaccount(signer);
210
- const statusBefore = await sdkSub.refreshSubaccountState(account);
211
- await sdkSub.activateSubaccount(signer, {
212
- expiresInSeconds: 86400,
213
- maxAllowedCount: (statusBefore?.maxAllowedCount ?? 0n) + 2n,
214
- });
215
- const signedApproval = sdkSub.subaccountApprovalMessage;
216
- expect(signedApproval).toBeDefined();
217
- expect(signedApproval.signature).not.toBe("0x");
218
- const first = await sdkSub.executeExpressOrder({
219
- kind: "increase",
220
- symbol: TEST_SYMBOL,
221
- direction: "long",
222
- orderType: "limit",
223
- size: TEST_SIZE_USD,
224
- triggerPrice: LIMIT_TRIGGER_PRICE,
225
- collateralToken: "USDC",
226
- collateralToPay: TEST_COLLATERAL,
227
- mode: "express",
228
- from: account,
229
- }, signer);
230
- expect(first.requestId).toBeDefined();
231
- const firstStatus = await waitForOrderCreatedOrExecuted(sdkSub, first.requestId);
232
- expect(["created", "executed"]).toContain(firstStatus.status);
233
- expect(recordingApi.orderPrepareRequests[0].subaccountAddress).toBe(subaccountAddress);
234
- expect(recordingApi.orderPrepareRequests[0].subaccountApproval?.signature).toBe(signedApproval.signature);
235
- expect(recordingApi.orderSubmitRequests[0].eip712Data?.subaccountApproval?.signature).toBe(signedApproval.signature);
236
- await waitForSubaccountNoopApproval(sdkSub, account);
237
- const staleApproval = signedApproval;
238
- await sdkSub.prepareOrder({
239
- kind: "increase",
240
- symbol: TEST_SYMBOL,
241
- direction: "long",
242
- orderType: "limit",
243
- size: TEST_SIZE_USD,
244
- triggerPrice: LIMIT_TRIGGER_PRICE,
245
- collateralToken: "USDC",
246
- collateralToPay: TEST_COLLATERAL,
247
- mode: "express",
248
- from: account,
249
- subaccountAddress,
250
- subaccountApproval: staleApproval,
251
- });
252
- expect(recordingApi.orderPrepareRequests[1].subaccountApproval?.signature).toBe("0x");
253
- }
254
- finally {
255
- try {
256
- const prepared = await cleanupSdk.prepareCancelOrder({ all: true, mode: "express", from: account });
257
- const cancelSignature = await cleanupSdk.signOrder(prepared, signer);
258
- await cleanupSdk.submitOrder({
259
- mode: prepared.mode,
260
- requestId: prepared.requestId,
261
- signature: cancelSignature,
262
- from: account,
263
- idempotencyKey: prepared.idempotencyKey,
264
- eip712Data: {
265
- batchParams: prepared.payload.batchParams,
266
- relayParams: prepared.payload.relayParams,
267
- },
268
- });
269
- }
270
- catch {
271
- // cleanup best-effort
272
- }
273
- sdkSub.clearSubaccount();
274
- }
275
- }, 300000);
276
- it.skipIf(!hasSigner)("generateSubaccount derives address deterministically", async () => {
169
+ it("generateSubaccount derives address deterministically", async () => {
277
170
  const sdk1 = getTestSdk();
278
171
  const sdk2 = getTestSdk();
279
172
  const addr1 = await sdk1.generateSubaccount(signer);
@@ -282,14 +175,14 @@ describe("GmxApiSdk — subaccount (1CT)", () => {
282
175
  expect(addr1.startsWith("0x")).toBe(true);
283
176
  expect(addr1).toBe(addr2);
284
177
  });
285
- it.skipIf(!hasSigner)("subaccountAddress getter works after generate", async () => {
178
+ it("subaccountAddress getter works after generate", async () => {
286
179
  const sdk = getTestSdk();
287
180
  expect(sdk.subaccountAddress).toBeUndefined();
288
181
  await sdk.generateSubaccount(signer);
289
182
  expect(sdk.subaccountAddress).toBeDefined();
290
183
  expect(sdk.hasActiveSubaccount).toBe(false);
291
184
  });
292
- it.skipIf(!hasSigner)("clearSubaccount resets state", async () => {
185
+ it("clearSubaccount resets state", async () => {
293
186
  const sdk = getTestSdk();
294
187
  await sdk.generateSubaccount(signer);
295
188
  expect(sdk.subaccountAddress).toBeDefined();
@@ -297,7 +190,7 @@ describe("GmxApiSdk — subaccount (1CT)", () => {
297
190
  expect(sdk.subaccountAddress).toBeUndefined();
298
191
  expect(sdk.hasActiveSubaccount).toBe(false);
299
192
  });
300
- it.skipIf(!hasSigner)("activateSubaccount prepares and signs approval", async () => {
193
+ it("activateSubaccount prepares and signs approval", async () => {
301
194
  const sdk = getTestSdk();
302
195
  const address = await sdk.activateSubaccount(signer, {
303
196
  expiresInSeconds: 86400,
@@ -307,7 +200,7 @@ describe("GmxApiSdk — subaccount (1CT)", () => {
307
200
  expect(sdk.subaccountAddress).toBe(address);
308
201
  expect(sdk.hasActiveSubaccount).toBe(true);
309
202
  });
310
- it.skipIf(!hasSigner)("fetchSubaccountStatus returns data", async () => {
203
+ it("fetchSubaccountStatus returns data", async () => {
311
204
  const sdk = getTestSdk();
312
205
  const subAddr = await sdk.generateSubaccount(signer);
313
206
  const status = await sdk.fetchSubaccountStatus({
@@ -318,7 +211,7 @@ describe("GmxApiSdk — subaccount (1CT)", () => {
318
211
  expect(typeof status.active).toBe("boolean");
319
212
  expect(status.approvalNonce).toBeDefined();
320
213
  });
321
- it.skipIf(!hasSigner)("signOrder uses subaccount signer when active", async () => {
214
+ it("signOrder uses subaccount signer when active", async () => {
322
215
  const sdk = getTestSdk();
323
216
  await sdk.activateSubaccount(signer, {
324
217
  expiresInSeconds: 86400,
@@ -326,11 +219,11 @@ describe("GmxApiSdk — subaccount (1CT)", () => {
326
219
  });
327
220
  const prepared = await sdk.prepareOrder({
328
221
  kind: "increase",
329
- symbol: "ETH/USD [WETH-USDC]",
222
+ symbol: TEST_SYMBOL,
330
223
  direction: "long",
331
224
  orderType: "market",
332
- size: 100n * 10n ** 30n,
333
- collateralToPay: { amount: 1000000n, token: "USDC" },
225
+ size: TEST_SIZE_USD,
226
+ collateralToPay: TEST_COLLATERAL,
334
227
  mode: "express",
335
228
  from: signer.address,
336
229
  subaccountAddress: sdk.subaccountAddress,
@@ -0,0 +1,106 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { GmxApiSdk } from "../index";
3
+ import { getTestSdk, RecordingApi, requireSigner, TEST_CHAIN_ID, TEST_COLLATERAL, TEST_SIZE_USD, TEST_SYMBOL, } from "./testUtil";
4
+ const signer = requireSigner();
5
+ const LIMIT_TRIGGER_PRICE = 1n * 10n ** 30n;
6
+ async function waitForSubaccountNoopApproval(sdk, account) {
7
+ const startedAt = Date.now();
8
+ while (Date.now() - startedAt < 30000) {
9
+ await sdk.refreshSubaccountState(account);
10
+ if (sdk.subaccountApprovalMessage?.signature === "0x") {
11
+ return;
12
+ }
13
+ await new Promise((resolve) => setTimeout(resolve, 2000));
14
+ }
15
+ throw new Error("Timed out waiting for subaccount approval to sync on-chain");
16
+ }
17
+ async function waitForOrderCreatedOrExecuted(sdk, requestId) {
18
+ const startedAt = Date.now();
19
+ while (Date.now() - startedAt < 180000) {
20
+ const status = await sdk.fetchOrderStatus({ requestId });
21
+ if (status.status === "created" ||
22
+ status.status === "executed" ||
23
+ status.status === "cancelled" ||
24
+ status.status === "relay_failed" ||
25
+ status.status === "relay_reverted") {
26
+ return status;
27
+ }
28
+ await new Promise((resolve) => setTimeout(resolve, 2000));
29
+ }
30
+ return sdk.fetchOrderStatus({ requestId });
31
+ }
32
+ describe("GmxApiSdk — subaccount (1CT) live flow", () => {
33
+ it("e2e applies approval once and uses noop approval for the next order", async () => {
34
+ const account = signer.address;
35
+ const recordingApi = new RecordingApi(getTestSdk().ctx.api);
36
+ const sdkSub = new GmxApiSdk({ chainId: TEST_CHAIN_ID, api: recordingApi });
37
+ const cleanupSdk = new GmxApiSdk({ chainId: TEST_CHAIN_ID, api: recordingApi });
38
+ try {
39
+ const subaccountAddress = await sdkSub.generateSubaccount(signer);
40
+ const statusBefore = await sdkSub.refreshSubaccountState(account);
41
+ await sdkSub.activateSubaccount(signer, {
42
+ expiresInSeconds: 86400,
43
+ maxAllowedCount: (statusBefore?.maxAllowedCount ?? 0n) + 2n,
44
+ });
45
+ const signedApproval = sdkSub.subaccountApprovalMessage;
46
+ expect(signedApproval).toBeDefined();
47
+ expect(signedApproval.signature).not.toBe("0x");
48
+ const first = await sdkSub.executeExpressOrder({
49
+ kind: "increase",
50
+ symbol: TEST_SYMBOL,
51
+ direction: "long",
52
+ orderType: "limit",
53
+ size: TEST_SIZE_USD,
54
+ triggerPrice: LIMIT_TRIGGER_PRICE,
55
+ collateralToken: "USDC",
56
+ collateralToPay: TEST_COLLATERAL,
57
+ mode: "express",
58
+ from: account,
59
+ }, signer);
60
+ expect(first.requestId).toBeDefined();
61
+ const firstStatus = await waitForOrderCreatedOrExecuted(sdkSub, first.requestId);
62
+ expect(["created", "executed"]).toContain(firstStatus.status);
63
+ expect(recordingApi.orderPrepareRequests[0].subaccountAddress).toBe(subaccountAddress);
64
+ expect(recordingApi.orderPrepareRequests[0].subaccountApproval?.signature).toBe(signedApproval.signature);
65
+ expect(recordingApi.orderSubmitRequests[0].eip712Data?.subaccountApproval?.signature).toBe(signedApproval.signature);
66
+ await waitForSubaccountNoopApproval(sdkSub, account);
67
+ const staleApproval = signedApproval;
68
+ await sdkSub.prepareOrder({
69
+ kind: "increase",
70
+ symbol: TEST_SYMBOL,
71
+ direction: "long",
72
+ orderType: "limit",
73
+ size: TEST_SIZE_USD,
74
+ triggerPrice: LIMIT_TRIGGER_PRICE,
75
+ collateralToken: "USDC",
76
+ collateralToPay: TEST_COLLATERAL,
77
+ mode: "express",
78
+ from: account,
79
+ subaccountAddress,
80
+ subaccountApproval: staleApproval,
81
+ });
82
+ expect(recordingApi.orderPrepareRequests[1].subaccountApproval?.signature).toBe("0x");
83
+ }
84
+ finally {
85
+ try {
86
+ const prepared = await cleanupSdk.prepareCancelOrder({ all: true, mode: "express", from: account });
87
+ const cancelSignature = await cleanupSdk.signOrder(prepared, signer);
88
+ await cleanupSdk.submitOrder({
89
+ mode: prepared.mode,
90
+ requestId: prepared.requestId,
91
+ signature: cancelSignature,
92
+ from: account,
93
+ idempotencyKey: prepared.idempotencyKey,
94
+ eip712Data: {
95
+ batchParams: prepared.payload.batchParams,
96
+ relayParams: prepared.payload.relayParams,
97
+ },
98
+ });
99
+ }
100
+ catch {
101
+ // cleanup best-effort
102
+ }
103
+ sdkSub.clearSubaccount();
104
+ }
105
+ }, 300000);
106
+ });
@@ -1,3 +1,4 @@
1
+ import { generatePrivateKey } from "viem/accounts";
1
2
  import { ARBITRUM, getViemChain } from "../../../configs/chains";
2
3
  import { sleep } from "../../../utils/common";
3
4
  import { PrivateKeySigner } from "../../../utils/signer";
@@ -5,8 +6,12 @@ import { GmxApiSdk } from "../index";
5
6
  export const TEST_CHAIN_ID = ARBITRUM;
6
7
  export const TEST_SYMBOL = "ETH/USD [WETH-USDC]";
7
8
  export const TEST_SIZE_USD = 10n * 10n ** 30n; // $10
8
- export const TEST_COLLATERAL = { amount: 1000000n, token: "USDC" }; // 1 USDC
9
+ // Must clear MIN_COLLATERAL_USD ($1 on Arbitrum) after fees, or the keeper cancels the order.
10
+ export const TEST_COLLATERAL = { amount: 3000000n, token: "USDC" }; // 3 USDC
9
11
  const TERMINAL_STATUSES = new Set(["executed", "cancelled", "relay_failed", "relay_reverted"]);
12
+ // A limit or conditional order rests at "created" until its trigger is hit.
13
+ const PLACED_STATUSES = new Set([...TERMINAL_STATUSES, "created"]);
14
+ export const PLACED_OK_STATUSES = ["created", "executed"];
10
15
  const ORDER_PREPARE_PATHS = new Set([
11
16
  "/v1/orders/txns/prepare",
12
17
  "/v1/orders/txns/edit/prepare",
@@ -115,16 +120,40 @@ export function requireSigner() {
115
120
  }
116
121
  return signer;
117
122
  }
123
+ let ephemeralSigner;
124
+ export function getOrCreateTestSigner() {
125
+ const signer = getTestSigner();
126
+ if (signer)
127
+ return signer;
128
+ if (!ephemeralSigner) {
129
+ ephemeralSigner = new PrivateKeySigner(generatePrivateKey());
130
+ }
131
+ return ephemeralSigner;
132
+ }
133
+ // TWAP fans out into one paid sub-order per part, so the live flows are opt-in.
134
+ export function shouldRunTwap() {
135
+ // eslint-disable-next-line no-restricted-globals
136
+ return process.env.GMX_TEST_TWAP === "1";
137
+ }
138
+ // Concurrent prepares are priced moments apart, so oracle-derived values drift in the last digits.
139
+ export function withinOneBp(a, b) {
140
+ const diff = a > b ? a - b : b - a;
141
+ return diff * 10000n <= a;
142
+ }
118
143
  export function hasRpcUrl() {
119
144
  // eslint-disable-next-line no-restricted-globals
120
145
  return !!process.env.GMX_TEST_RPC_URL;
121
146
  }
122
- export async function waitForOrderStatus(sdk, requestId, timeoutMs = 60000) {
147
+ /** For limit and conditional orders: resolves as soon as the order is on the book. */
148
+ export function waitForOrderPlaced(sdk, requestId, timeoutMs = 60000) {
149
+ return waitForOrderStatus(sdk, requestId, timeoutMs, PLACED_STATUSES);
150
+ }
151
+ export async function waitForOrderStatus(sdk, requestId, timeoutMs = 60000, stopStatuses = TERMINAL_STATUSES) {
123
152
  const start = Date.now();
124
153
  while (Date.now() - start < timeoutMs) {
125
154
  const status = await sdk.fetchOrderStatus({ requestId });
126
- if (TERMINAL_STATUSES.has(status.status)) {
127
- if (status.status !== "executed") {
155
+ if (stopStatuses.has(status.status)) {
156
+ if (!PLACED_OK_STATUSES.includes(status.status)) {
128
157
  logOrderFailure(status);
129
158
  }
130
159
  return status;