@gmx-io/sdk 1.6.2 → 1.6.3

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.
@@ -1,10 +1,280 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  const vitest_1 = require("vitest");
4
+ const subaccount_1 = require("../../../utils/subaccount");
5
+ const index_1 = require("../index");
4
6
  const testUtil_1 = require("./testUtil");
5
7
  const signer = (0, testUtil_1.getTestSigner)();
6
8
  const hasSigner = !!signer;
9
+ const LIMIT_TRIGGER_PRICE = 1n * 10n ** 30n;
10
+ const EXTERNAL_SUBACCOUNT_ADDRESS = "0x1111111111111111111111111111111111111111";
11
+ function buildTestPrepareRequest(from) {
12
+ return {
13
+ kind: "increase",
14
+ symbol: testUtil_1.TEST_SYMBOL,
15
+ direction: "long",
16
+ orderType: "limit",
17
+ size: testUtil_1.TEST_SIZE_USD,
18
+ triggerPrice: LIMIT_TRIGGER_PRICE,
19
+ collateralToken: "USDC",
20
+ collateralToPay: testUtil_1.TEST_COLLATERAL,
21
+ mode: "express",
22
+ from,
23
+ };
24
+ }
25
+ async function waitForSubaccountNoopApproval(sdk, account) {
26
+ const startedAt = Date.now();
27
+ while (Date.now() - startedAt < 30000) {
28
+ await sdk.refreshSubaccountState(account);
29
+ if (sdk.subaccountApprovalMessage?.signature === "0x") {
30
+ return;
31
+ }
32
+ await new Promise((resolve) => setTimeout(resolve, 2000));
33
+ }
34
+ throw new Error("Timed out waiting for subaccount approval to sync on-chain");
35
+ }
36
+ async function waitForOrderCreatedOrExecuted(sdk, requestId) {
37
+ const startedAt = Date.now();
38
+ while (Date.now() - startedAt < 180000) {
39
+ const status = await sdk.fetchOrderStatus({ requestId });
40
+ if (status.status === "created" ||
41
+ status.status === "executed" ||
42
+ status.status === "cancelled" ||
43
+ status.status === "relay_failed" ||
44
+ status.status === "relay_reverted") {
45
+ return status;
46
+ }
47
+ await new Promise((resolve) => setTimeout(resolve, 2000));
48
+ }
49
+ return sdk.fetchOrderStatus({ requestId });
50
+ }
7
51
  (0, vitest_1.describe)("GmxApiSdk — subaccount (1CT)", () => {
52
+ vitest_1.it.skipIf(!hasSigner)("rejects external subaccount details for SDK-managed signing", async () => {
53
+ const signer = (0, testUtil_1.getTestSigner)();
54
+ const api = new testUtil_1.ScriptedOrderApi((0, testUtil_1.buildPreparedOrderResponse)("request-1"));
55
+ const sdk = new index_1.GmxApiSdk({ chainId: testUtil_1.TEST_CHAIN_ID, api });
56
+ const subaccountAddress = await sdk.generateSubaccount(signer);
57
+ await (0, vitest_1.expect)(sdk.prepareOrder({
58
+ ...buildTestPrepareRequest(signer.address),
59
+ subaccountAddress: EXTERNAL_SUBACCOUNT_ADDRESS,
60
+ subaccountApproval: (0, subaccount_1.getEmptySubaccountApproval)(testUtil_1.TEST_CHAIN_ID, subaccountAddress),
61
+ })).rejects.toThrow("subaccountAddress");
62
+ await (0, vitest_1.expect)(sdk.prepareOrder({
63
+ ...buildTestPrepareRequest(signer.address),
64
+ subaccountApproval: (0, subaccount_1.getEmptySubaccountApproval)(testUtil_1.TEST_CHAIN_ID, EXTERNAL_SUBACCOUNT_ADDRESS),
65
+ })).rejects.toThrow("subaccountApproval.subaccount");
66
+ (0, vitest_1.expect)(api.prepareRequests).toHaveLength(0);
67
+ });
68
+ vitest_1.it.skipIf(!hasSigner)("keeps prepared subaccount approval after failed submit response", async () => {
69
+ const signer = (0, testUtil_1.getTestSigner)();
70
+ const requestId = "retry-request";
71
+ const api = new testUtil_1.ScriptedOrderApi((0, testUtil_1.buildPreparedOrderResponse)(requestId), [
72
+ {
73
+ requestId,
74
+ status: "relay_failed",
75
+ error: { code: "TEST_RELAY_FAILED", message: "relay failed" },
76
+ },
77
+ {
78
+ requestId,
79
+ status: "relay_accepted",
80
+ },
81
+ ], [(0, testUtil_1.buildSubaccountStatusResponse)()]);
82
+ const sdk = new index_1.GmxApiSdk({ chainId: testUtil_1.TEST_CHAIN_ID, api });
83
+ const subaccountAddress = await sdk.generateSubaccount(signer);
84
+ const subaccountApproval = (0, subaccount_1.getEmptySubaccountApproval)(testUtil_1.TEST_CHAIN_ID, subaccountAddress);
85
+ await sdk.prepareOrder({
86
+ ...buildTestPrepareRequest(signer.address),
87
+ subaccountAddress,
88
+ subaccountApproval,
89
+ });
90
+ const submitRequest = {
91
+ mode: "express",
92
+ requestId,
93
+ signature: "0x",
94
+ from: signer.address,
95
+ eip712Data: {
96
+ batchParams: {},
97
+ relayParams: {},
98
+ },
99
+ };
100
+ await sdk.submitOrder(submitRequest);
101
+ await sdk.submitOrder(submitRequest);
102
+ (0, vitest_1.expect)(api.submitRequests[0].eip712Data?.subaccountApproval?.signature).toBe("0x");
103
+ (0, vitest_1.expect)(api.submitRequests[1].eip712Data?.subaccountApproval?.signature).toBe("0x");
104
+ });
105
+ vitest_1.it.skipIf(!hasSigner)("decrements cached subaccount actions only after final order status", async () => {
106
+ const signer = (0, testUtil_1.getTestSigner)();
107
+ const requestId = "accepted-request";
108
+ const api = new testUtil_1.ScriptedOrderApi((0, testUtil_1.buildPreparedOrderResponse)(requestId), [
109
+ {
110
+ requestId,
111
+ status: "executed",
112
+ },
113
+ ], [
114
+ (0, testUtil_1.buildSubaccountStatusResponse)({
115
+ currentActionsCount: "3",
116
+ remainingActions: "2",
117
+ }),
118
+ ]);
119
+ const sdk = new index_1.GmxApiSdk({ chainId: testUtil_1.TEST_CHAIN_ID, api });
120
+ await sdk.generateSubaccount(signer);
121
+ await sdk.refreshSubaccountState(signer.address);
122
+ await sdk.prepareOrder(buildTestPrepareRequest(signer.address));
123
+ await sdk.submitOrder({
124
+ mode: "express",
125
+ requestId,
126
+ signature: "0x",
127
+ from: signer.address,
128
+ eip712Data: {
129
+ batchParams: {},
130
+ relayParams: {},
131
+ },
132
+ });
133
+ (0, vitest_1.expect)(sdk.subaccountStatus?.currentActionsCount).toBe(4n);
134
+ (0, vitest_1.expect)(sdk.subaccountStatus?.remainingActions).toBe(1n);
135
+ });
136
+ vitest_1.it.skipIf(!hasSigner)("does not decrement cached subaccount actions for relay_accepted status", async () => {
137
+ const signer = (0, testUtil_1.getTestSigner)();
138
+ const requestId = "relay-accepted-request";
139
+ const api = new testUtil_1.ScriptedOrderApi((0, testUtil_1.buildPreparedOrderResponse)(requestId), [
140
+ {
141
+ requestId,
142
+ status: "relay_accepted",
143
+ },
144
+ ], [
145
+ (0, testUtil_1.buildSubaccountStatusResponse)({
146
+ currentActionsCount: "3",
147
+ remainingActions: "2",
148
+ }),
149
+ ]);
150
+ const sdk = new index_1.GmxApiSdk({ chainId: testUtil_1.TEST_CHAIN_ID, api });
151
+ await sdk.generateSubaccount(signer);
152
+ await sdk.refreshSubaccountState(signer.address);
153
+ await sdk.prepareOrder(buildTestPrepareRequest(signer.address));
154
+ await sdk.submitOrder({
155
+ mode: "express",
156
+ requestId,
157
+ signature: "0x",
158
+ from: signer.address,
159
+ eip712Data: {
160
+ batchParams: {},
161
+ relayParams: {},
162
+ },
163
+ });
164
+ (0, vitest_1.expect)(sdk.subaccountStatus?.currentActionsCount).toBe(3n);
165
+ (0, vitest_1.expect)(sdk.subaccountStatus?.remainingActions).toBe(2n);
166
+ });
167
+ vitest_1.it.skipIf(!hasSigner)("refreshes subaccount state before noop approval when only one action remains", async () => {
168
+ const signer = (0, testUtil_1.getTestSigner)();
169
+ const api = new testUtil_1.ScriptedOrderApi((0, testUtil_1.buildPreparedOrderResponse)("request-1"), [], [
170
+ (0, testUtil_1.buildSubaccountStatusResponse)({
171
+ currentActionsCount: "9",
172
+ remainingActions: "1",
173
+ }),
174
+ (0, testUtil_1.buildSubaccountStatusResponse)({
175
+ currentActionsCount: "10",
176
+ remainingActions: "0",
177
+ }),
178
+ ]);
179
+ const sdk = new index_1.GmxApiSdk({ chainId: testUtil_1.TEST_CHAIN_ID, api });
180
+ await sdk.generateSubaccount(signer);
181
+ await sdk.refreshSubaccountState(signer.address);
182
+ await (0, vitest_1.expect)(sdk.prepareOrder(buildTestPrepareRequest(signer.address))).rejects.toThrow("Subaccount is not active");
183
+ (0, vitest_1.expect)(api.subaccountStatusRequests).toHaveLength(2);
184
+ (0, vitest_1.expect)(api.prepareRequests).toHaveLength(0);
185
+ });
186
+ vitest_1.it.skipIf(!hasSigner)("validates caller-supplied noop approval against exhausted subaccount quota", async () => {
187
+ const signer = (0, testUtil_1.getTestSigner)();
188
+ const api = new testUtil_1.ScriptedOrderApi((0, testUtil_1.buildPreparedOrderResponse)("request-1"), [], [
189
+ (0, testUtil_1.buildSubaccountStatusResponse)({
190
+ currentActionsCount: "10",
191
+ remainingActions: "0",
192
+ }),
193
+ ]);
194
+ const sdk = new index_1.GmxApiSdk({ chainId: testUtil_1.TEST_CHAIN_ID, api });
195
+ const subaccountAddress = await sdk.generateSubaccount(signer);
196
+ await sdk.refreshSubaccountState(signer.address);
197
+ await (0, vitest_1.expect)(sdk.prepareOrder({
198
+ ...buildTestPrepareRequest(signer.address),
199
+ subaccountAddress,
200
+ subaccountApproval: (0, subaccount_1.getEmptySubaccountApproval)(testUtil_1.TEST_CHAIN_ID, subaccountAddress),
201
+ })).rejects.toThrow("Subaccount is not active");
202
+ (0, vitest_1.expect)(api.prepareRequests).toHaveLength(0);
203
+ });
204
+ vitest_1.it.skipIf(!hasSigner)("e2e applies approval once and uses noop approval for the next order", async () => {
205
+ const signer = (0, testUtil_1.getTestSigner)();
206
+ const account = signer.address;
207
+ const recordingApi = new testUtil_1.RecordingApi((0, testUtil_1.getTestSdk)().ctx.api);
208
+ const sdkSub = new index_1.GmxApiSdk({ chainId: testUtil_1.TEST_CHAIN_ID, api: recordingApi });
209
+ const cleanupSdk = new index_1.GmxApiSdk({ chainId: testUtil_1.TEST_CHAIN_ID, api: recordingApi });
210
+ try {
211
+ const subaccountAddress = await sdkSub.generateSubaccount(signer);
212
+ const statusBefore = await sdkSub.refreshSubaccountState(account);
213
+ await sdkSub.activateSubaccount(signer, {
214
+ expiresInSeconds: 86400,
215
+ maxAllowedCount: (statusBefore?.maxAllowedCount ?? 0n) + 2n,
216
+ });
217
+ const signedApproval = sdkSub.subaccountApprovalMessage;
218
+ (0, vitest_1.expect)(signedApproval).toBeDefined();
219
+ (0, vitest_1.expect)(signedApproval.signature).not.toBe("0x");
220
+ const first = await sdkSub.executeExpressOrder({
221
+ kind: "increase",
222
+ symbol: testUtil_1.TEST_SYMBOL,
223
+ direction: "long",
224
+ orderType: "limit",
225
+ size: testUtil_1.TEST_SIZE_USD,
226
+ triggerPrice: LIMIT_TRIGGER_PRICE,
227
+ collateralToken: "USDC",
228
+ collateralToPay: testUtil_1.TEST_COLLATERAL,
229
+ mode: "express",
230
+ from: account,
231
+ }, signer);
232
+ (0, vitest_1.expect)(first.requestId).toBeDefined();
233
+ const firstStatus = await waitForOrderCreatedOrExecuted(sdkSub, first.requestId);
234
+ (0, vitest_1.expect)(["created", "executed"]).toContain(firstStatus.status);
235
+ (0, vitest_1.expect)(recordingApi.orderPrepareRequests[0].subaccountAddress).toBe(subaccountAddress);
236
+ (0, vitest_1.expect)(recordingApi.orderPrepareRequests[0].subaccountApproval?.signature).toBe(signedApproval.signature);
237
+ (0, vitest_1.expect)(recordingApi.orderSubmitRequests[0].eip712Data?.subaccountApproval?.signature).toBe(signedApproval.signature);
238
+ await waitForSubaccountNoopApproval(sdkSub, account);
239
+ const staleApproval = signedApproval;
240
+ await sdkSub.prepareOrder({
241
+ kind: "increase",
242
+ symbol: testUtil_1.TEST_SYMBOL,
243
+ direction: "long",
244
+ orderType: "limit",
245
+ size: testUtil_1.TEST_SIZE_USD,
246
+ triggerPrice: LIMIT_TRIGGER_PRICE,
247
+ collateralToken: "USDC",
248
+ collateralToPay: testUtil_1.TEST_COLLATERAL,
249
+ mode: "express",
250
+ from: account,
251
+ subaccountAddress,
252
+ subaccountApproval: staleApproval,
253
+ });
254
+ (0, vitest_1.expect)(recordingApi.orderPrepareRequests[1].subaccountApproval?.signature).toBe("0x");
255
+ }
256
+ finally {
257
+ try {
258
+ const prepared = await cleanupSdk.prepareCancelOrder({ all: true, mode: "express", from: account });
259
+ const cancelSignature = await cleanupSdk.signOrder(prepared, signer);
260
+ await cleanupSdk.submitOrder({
261
+ mode: prepared.mode,
262
+ requestId: prepared.requestId,
263
+ signature: cancelSignature,
264
+ from: account,
265
+ idempotencyKey: prepared.idempotencyKey,
266
+ eip712Data: {
267
+ batchParams: prepared.payload.batchParams,
268
+ relayParams: prepared.payload.relayParams,
269
+ },
270
+ });
271
+ }
272
+ catch {
273
+ // cleanup best-effort
274
+ }
275
+ sdkSub.clearSubaccount();
276
+ }
277
+ }, 300000);
8
278
  vitest_1.it.skipIf(!hasSigner)("generateSubaccount derives address deterministically", async () => {
9
279
  const sdk1 = (0, testUtil_1.getTestSdk)();
10
280
  const sdk2 = (0, testUtil_1.getTestSdk)();
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.activateTestSubaccount = exports.waitForPositionUpdate = exports.waitForOrdersUpdate = exports.expressFlow = exports.waitForOrderStatus = exports.hasRpcUrl = exports.requireSigner = exports.getTestSigner = exports.getTestSdk = exports.TEST_COLLATERAL = exports.TEST_SIZE_USD = exports.TEST_SYMBOL = exports.TEST_CHAIN_ID = void 0;
3
+ exports.activateTestSubaccount = exports.waitForPositionUpdate = exports.waitForOrdersUpdate = exports.expressFlow = exports.waitForOrderStatus = exports.hasRpcUrl = exports.requireSigner = exports.getTestSigner = exports.getTestSdk = exports.buildSubaccountStatusResponse = exports.ScriptedOrderApi = exports.buildPreparedOrderResponse = exports.RecordingApi = exports.TEST_COLLATERAL = exports.TEST_SIZE_USD = exports.TEST_SYMBOL = exports.TEST_CHAIN_ID = void 0;
4
4
  const chains_1 = require("../../../configs/chains");
5
5
  const common_1 = require("../../../utils/common");
6
6
  const signer_1 = require("../../../utils/signer");
@@ -10,6 +10,97 @@ exports.TEST_SYMBOL = "ETH/USD [WETH-USDC]";
10
10
  exports.TEST_SIZE_USD = 10n * 10n ** 30n; // $10
11
11
  exports.TEST_COLLATERAL = { amount: 1000000n, token: "USDC" }; // 1 USDC
12
12
  const TERMINAL_STATUSES = new Set(["executed", "cancelled", "relay_failed", "relay_reverted"]);
13
+ const ORDER_PREPARE_PATHS = new Set([
14
+ "/v1/orders/txns/prepare",
15
+ "/v1/orders/txns/edit/prepare",
16
+ "/v1/orders/txns/cancel/prepare",
17
+ "/v1/orders/txns/collateral/prepare",
18
+ ]);
19
+ class RecordingApi {
20
+ constructor(delegate) {
21
+ this.delegate = delegate;
22
+ this.orderPrepareRequests = [];
23
+ this.orderSubmitRequests = [];
24
+ this.url = delegate.url;
25
+ }
26
+ fetchJson(path, opts) {
27
+ return this.delegate.fetchJson(path, opts);
28
+ }
29
+ postJson(path, body, opts) {
30
+ if (ORDER_PREPARE_PATHS.has(path)) {
31
+ this.orderPrepareRequests.push(body);
32
+ }
33
+ else if (path === "/v1/orders/txns/submit") {
34
+ this.orderSubmitRequests.push(body);
35
+ }
36
+ return this.delegate.postJson(path, body, opts);
37
+ }
38
+ }
39
+ exports.RecordingApi = RecordingApi;
40
+ function buildPreparedOrderResponse(requestId) {
41
+ return {
42
+ requestId,
43
+ mode: "express",
44
+ payloadType: "typed-data",
45
+ payload: {
46
+ batchParams: {},
47
+ relayParams: {},
48
+ },
49
+ };
50
+ }
51
+ exports.buildPreparedOrderResponse = buildPreparedOrderResponse;
52
+ class ScriptedOrderApi {
53
+ constructor(prepareResponse, submitResponses = [], subaccountStatusResponses = []) {
54
+ this.prepareResponse = prepareResponse;
55
+ this.submitResponses = submitResponses;
56
+ this.subaccountStatusResponses = subaccountStatusResponses;
57
+ this.url = "http://test";
58
+ this.prepareRequests = [];
59
+ this.submitRequests = [];
60
+ this.subaccountStatusRequests = [];
61
+ }
62
+ fetchJson(path, _opts) {
63
+ return Promise.reject(new Error(`Unexpected fetchJson call ${path}`));
64
+ }
65
+ postJson(path, body, opts) {
66
+ if (path === "/v1/orders/txns/prepare") {
67
+ this.prepareRequests.push(body);
68
+ return Promise.resolve(opts?.transform ? opts.transform(this.prepareResponse) : this.prepareResponse);
69
+ }
70
+ if (path === "/v1/orders/txns/submit") {
71
+ this.submitRequests.push(body);
72
+ const response = this.submitResponses.shift();
73
+ if (!response) {
74
+ return Promise.reject(new Error("Unexpected submit call"));
75
+ }
76
+ return Promise.resolve(response);
77
+ }
78
+ if (path === "/v1/subaccounts/status") {
79
+ this.subaccountStatusRequests.push(body);
80
+ const response = this.subaccountStatusResponses.shift();
81
+ if (!response) {
82
+ return Promise.reject(new Error("Unexpected subaccount status call"));
83
+ }
84
+ return Promise.resolve(response);
85
+ }
86
+ return Promise.reject(new Error(`Unexpected API path ${path}`));
87
+ }
88
+ }
89
+ exports.ScriptedOrderApi = ScriptedOrderApi;
90
+ function buildSubaccountStatusResponse(overrides = {}) {
91
+ return {
92
+ active: true,
93
+ maxAllowedCount: "10",
94
+ currentActionsCount: "0",
95
+ remainingActions: "10",
96
+ expiresAt: String(Math.floor(Date.now() / 1000) + 86400),
97
+ approvalNonce: "0",
98
+ multichainApprovalNonce: "0",
99
+ integrationId: null,
100
+ ...overrides,
101
+ };
102
+ }
103
+ exports.buildSubaccountStatusResponse = buildSubaccountStatusResponse;
13
104
  function getTestSdk() {
14
105
  // eslint-disable-next-line no-restricted-globals
15
106
  const apiUrl = process.env.GMX_TEST_API_URL;
@@ -2,7 +2,6 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.GmxApiSdk = exports.getGasPaymentTokens = exports.HttpClientWithFallback = exports.HttpError = exports.PrivateKeySigner = void 0;
4
4
  const api_1 = require("../../configs/api");
5
- const express_1 = require("../../configs/express");
6
5
  const multichain_1 = require("../../configs/multichain");
7
6
  const api_2 = require("../../utils/apy/api");
8
7
  const api_3 = require("../../utils/balances/api");
@@ -22,8 +21,7 @@ const api_12 = require("../../utils/prices/api");
22
21
  const api_13 = require("../../utils/rates/api");
23
22
  const api_14 = require("../../utils/staking/api");
24
23
  const api_15 = require("../../utils/subaccount/api");
25
- const generateSubaccount_1 = require("../../utils/subaccount/generateSubaccount");
26
- const time_1 = require("../../utils/time");
24
+ const sdkClient_1 = require("../../utils/subaccount/sdkClient");
27
25
  const api_16 = require("../../utils/tokens/api");
28
26
  const api_17 = require("../../utils/trades/api");
29
27
  var signer_1 = require("../../utils/signer");
@@ -32,11 +30,11 @@ var http_2 = require("../../utils/http/http");
32
30
  Object.defineProperty(exports, "HttpError", { enumerable: true, get: function () { return http_2.HttpError; } });
33
31
  var httpFallback_2 = require("../../utils/http/httpFallback");
34
32
  Object.defineProperty(exports, "HttpClientWithFallback", { enumerable: true, get: function () { return httpFallback_2.HttpClientWithFallback; } });
35
- var express_2 = require("../../configs/express");
36
- Object.defineProperty(exports, "getGasPaymentTokens", { enumerable: true, get: function () { return express_2.getGasPaymentTokens; } });
37
- const subaccountSigners = new WeakMap();
33
+ var express_1 = require("../../configs/express");
34
+ Object.defineProperty(exports, "getGasPaymentTokens", { enumerable: true, get: function () { return express_1.getGasPaymentTokens; } });
38
35
  class GmxApiSdk {
39
36
  constructor({ chainId, apiUrl, api }) {
37
+ this.preparedSubaccountApprovals = new Map();
40
38
  if (api) {
41
39
  this.ctx = { chainId, api };
42
40
  return;
@@ -52,14 +50,28 @@ class GmxApiSdk {
52
50
  api: allUrls.length > 1 ? new httpFallback_1.HttpClientWithFallback(allUrls) : new http_1.HttpClient(resolvedApiUrl),
53
51
  };
54
52
  }
53
+ get subaccountClient() {
54
+ return {
55
+ ctx: this.ctx,
56
+ owner: this,
57
+ preparedSubaccountApprovals: this.preparedSubaccountApprovals,
58
+ getSubaccount: () => this._subaccount,
59
+ setSubaccount: (subaccount) => {
60
+ this._subaccount = subaccount;
61
+ },
62
+ };
63
+ }
55
64
  get subaccountAddress() {
56
65
  return this._subaccount?.address;
57
66
  }
67
+ get subaccountStatus() {
68
+ return this._subaccount?.onchainData;
69
+ }
58
70
  get hasActiveSubaccount() {
59
- return this._subaccount?.approval !== undefined;
71
+ return (0, sdkClient_1.hasActiveSdkSubaccount)(this.subaccountClient);
60
72
  }
61
73
  get subaccountApprovalMessage() {
62
- return this._subaccount?.approval?.message;
74
+ return (0, sdkClient_1.getSdkSubaccountApprovalMessage)(this.subaccountClient);
63
75
  }
64
76
  fetchMarketsInfo() {
65
77
  return (0, api_6.fetchApiMarketsInfo)(this.ctx);
@@ -178,44 +190,35 @@ class GmxApiSdk {
178
190
  return (0, gmxAccountApi_1.getCrossChainWithdrawStatus)(this.ctx, requestId);
179
191
  }
180
192
  prepareOrder(request) {
181
- return (0, api_8.prepareOrder)(this.ctx, request);
193
+ return (0, sdkClient_1.prepareWithSubaccount)(this.subaccountClient, request, api_8.prepareOrder);
182
194
  }
183
195
  signOrder(prepared, signer) {
184
- const subSigner = this._subaccount?.approval ? subaccountSigners.get(this) : undefined;
185
- const effectiveSigner = subSigner ?? signer;
186
- const accountAddress = subSigner ? signer.address : undefined;
187
- return (0, api_8.signPreparedOrder)(prepared, effectiveSigner, this.ctx.chainId, accountAddress);
196
+ return (0, sdkClient_1.signOrderWithSubaccount)(this.subaccountClient, prepared, signer);
188
197
  }
189
- submitOrder(request) {
190
- return (0, api_8.submitOrder)(this.ctx, request);
198
+ async submitOrder(request) {
199
+ return (0, sdkClient_1.submitOrderWithSubaccount)(this.subaccountClient, request);
191
200
  }
192
201
  async executeExpressOrder(request, signer) {
193
- const subSigner = subaccountSigners.get(this);
194
- if (subSigner && this._subaccount?.approval) {
195
- const enrichedRequest = {
196
- ...request,
197
- subaccountAddress: this._subaccount.address,
198
- subaccountApproval: this._subaccount.approval.message,
199
- };
200
- return (0, api_8.executeExpressOrder)(this.ctx, enrichedRequest, subSigner, request.from);
201
- }
202
- return (0, api_8.executeExpressOrder)(this.ctx, request, signer);
202
+ return (0, sdkClient_1.executeExpressOrderWithSubaccount)(this.subaccountClient, request, signer);
203
203
  }
204
204
  fetchOrderStatus(request) {
205
205
  return (0, api_8.fetchOrderStatus)(this.ctx, request);
206
206
  }
207
207
  prepareEditOrder(request) {
208
- return (0, api_8.prepareEditOrder)(this.ctx, request);
208
+ return (0, sdkClient_1.prepareWithSubaccount)(this.subaccountClient, request, api_8.prepareEditOrder);
209
209
  }
210
210
  prepareCancelOrder(request) {
211
- return (0, api_8.prepareCancelOrder)(this.ctx, request);
211
+ return (0, sdkClient_1.prepareWithSubaccount)(this.subaccountClient, request, api_8.prepareCancelOrder);
212
212
  }
213
213
  prepareCollateral(request) {
214
- return (0, api_8.prepareCollateral)(this.ctx, request);
214
+ return (0, sdkClient_1.prepareWithSubaccount)(this.subaccountClient, request, api_8.prepareCollateral);
215
215
  }
216
216
  fetchSubaccountStatus(request) {
217
217
  return (0, api_15.fetchSubaccountStatus)(this.ctx, request);
218
218
  }
219
+ async refreshSubaccountState(account) {
220
+ return (0, sdkClient_1.refreshSdkSubaccountState)(this.subaccountClient, account);
221
+ }
219
222
  prepareSubaccountApproval(request) {
220
223
  return (0, api_15.prepareSubaccountApproval)(this.ctx, request);
221
224
  }
@@ -234,12 +237,7 @@ class GmxApiSdk {
234
237
  * approval and start using it for orders.
235
238
  */
236
239
  async generateSubaccount(mainSigner) {
237
- const result = await (0, generateSubaccount_1.generateSubaccount)(mainSigner);
238
- subaccountSigners.set(this, result.signer);
239
- this._subaccount = {
240
- address: result.address,
241
- };
242
- return result.address;
240
+ return (0, sdkClient_1.generateSdkSubaccount)(this.subaccountClient, mainSigner);
243
241
  }
244
242
  /**
245
243
  * Generate (if needed) and activate the subaccount:
@@ -248,31 +246,10 @@ class GmxApiSdk {
248
246
  * 3. Stores the approval so subsequent orders use 1CT mode automatically
249
247
  */
250
248
  async activateSubaccount(mainSigner, options) {
251
- if (!this._subaccount) {
252
- await this.generateSubaccount(mainSigner);
253
- }
254
- const expiresAt = String((0, time_1.nowInSeconds)() + (options?.expiresInSeconds ?? express_1.DEFAULT_SUBACCOUNT_EXPIRY_DURATION));
255
- const maxAllowedCount = String(options?.maxAllowedCount ?? express_1.DEFAULT_SUBACCOUNT_MAX_ALLOWED_COUNT);
256
- const prepared = await this.prepareSubaccountApproval({
257
- account: mainSigner.address,
258
- subaccountAddress: this._subaccount.address,
259
- shouldAdd: true,
260
- expiresAt,
261
- maxAllowedCount,
262
- });
263
- const signature = await (0, api_15.signSubaccountApproval)(prepared, mainSigner, {
264
- chainId: this.ctx.chainId,
265
- expectedSubaccountAddress: this._subaccount.address,
266
- });
267
- this._subaccount.approval = {
268
- message: { ...prepared.message, signature },
269
- signature,
270
- };
271
- return this._subaccount.address;
249
+ return (0, sdkClient_1.activateSdkSubaccount)(this.subaccountClient, mainSigner, options);
272
250
  }
273
251
  clearSubaccount() {
274
- subaccountSigners.delete(this);
275
- this._subaccount = undefined;
252
+ (0, sdkClient_1.clearSdkSubaccount)(this.subaccountClient);
276
253
  }
277
254
  }
278
255
  exports.GmxApiSdk = GmxApiSdk;
@@ -14,7 +14,7 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
- exports.signSubaccountApproval = exports.prepareSubaccountApproval = exports.fetchSubaccountStatus = exports.getSubaccountApprovalTypedData = exports.getEmptySubaccountApproval = exports.hashSubaccountApproval = exports.createSubaccountSignerFromConfig = exports.decryptSubaccountPrivateKey = exports.generateSubaccount = void 0;
17
+ exports.signSubaccountApproval = exports.prepareSubaccountApproval = exports.fetchSubaccountStatus = exports.toSignedSubaccountApproval = exports.shouldRefreshExplicitSubaccountApproval = exports.parseSubaccountStatus = exports.isSubaccountStatusUsable = exports.isSubaccountApprovalSynced = exports.isSubaccountApprovalNonceExpired = exports.isSubaccountApprovalExpired = exports.isSameSubaccountApproval = exports.isEmptySubaccountApproval = exports.getSubaccountApprovalTypedData = exports.getEmptySubaccountApproval = exports.hashSubaccountApproval = exports.createSubaccountSignerFromConfig = exports.decryptSubaccountPrivateKey = exports.generateSubaccount = void 0;
18
18
  __exportStar(require("./types"), exports);
19
19
  var generateSubaccount_1 = require("./generateSubaccount");
20
20
  Object.defineProperty(exports, "generateSubaccount", { enumerable: true, get: function () { return generateSubaccount_1.generateSubaccount; } });
@@ -26,6 +26,16 @@ var getEmptySubaccountApproval_1 = require("./getEmptySubaccountApproval");
26
26
  Object.defineProperty(exports, "getEmptySubaccountApproval", { enumerable: true, get: function () { return getEmptySubaccountApproval_1.getEmptySubaccountApproval; } });
27
27
  var getSubaccountApprovalTypedData_1 = require("./getSubaccountApprovalTypedData");
28
28
  Object.defineProperty(exports, "getSubaccountApprovalTypedData", { enumerable: true, get: function () { return getSubaccountApprovalTypedData_1.getSubaccountApprovalTypedData; } });
29
+ var state_1 = require("./state");
30
+ Object.defineProperty(exports, "isEmptySubaccountApproval", { enumerable: true, get: function () { return state_1.isEmptySubaccountApproval; } });
31
+ Object.defineProperty(exports, "isSameSubaccountApproval", { enumerable: true, get: function () { return state_1.isSameSubaccountApproval; } });
32
+ Object.defineProperty(exports, "isSubaccountApprovalExpired", { enumerable: true, get: function () { return state_1.isSubaccountApprovalExpired; } });
33
+ Object.defineProperty(exports, "isSubaccountApprovalNonceExpired", { enumerable: true, get: function () { return state_1.isSubaccountApprovalNonceExpired; } });
34
+ Object.defineProperty(exports, "isSubaccountApprovalSynced", { enumerable: true, get: function () { return state_1.isSubaccountApprovalSynced; } });
35
+ Object.defineProperty(exports, "isSubaccountStatusUsable", { enumerable: true, get: function () { return state_1.isSubaccountStatusUsable; } });
36
+ Object.defineProperty(exports, "parseSubaccountStatus", { enumerable: true, get: function () { return state_1.parseSubaccountStatus; } });
37
+ Object.defineProperty(exports, "shouldRefreshExplicitSubaccountApproval", { enumerable: true, get: function () { return state_1.shouldRefreshExplicitSubaccountApproval; } });
38
+ Object.defineProperty(exports, "toSignedSubaccountApproval", { enumerable: true, get: function () { return state_1.toSignedSubaccountApproval; } });
29
39
  var api_1 = require("./api");
30
40
  Object.defineProperty(exports, "fetchSubaccountStatus", { enumerable: true, get: function () { return api_1.fetchSubaccountStatus; } });
31
41
  Object.defineProperty(exports, "prepareSubaccountApproval", { enumerable: true, get: function () { return api_1.prepareSubaccountApproval; } });