@gmx-io/sdk 1.6.1 → 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.
- package/build/cjs/src/clients/v2/__tests__/subaccount.spec.js +270 -0
- package/build/cjs/src/clients/v2/__tests__/testUtil.js +92 -1
- package/build/cjs/src/clients/v2/index.js +34 -57
- package/build/cjs/src/codegen/prebuilt/hashedKinkModelMarketRatesKeys.json +8 -0
- package/build/cjs/src/codegen/prebuilt/hashedMarketConfigKeys.json +61 -0
- package/build/cjs/src/codegen/prebuilt/hashedMarketValuesKeys.json +15 -0
- package/build/cjs/src/configs/markets.js +11 -1
- package/build/cjs/src/configs/tokens.js +11 -0
- package/build/cjs/src/utils/__tests__/markets.spec.js +30 -0
- package/build/cjs/src/utils/markets/utils.js +16 -12
- package/build/cjs/src/utils/positions/utils.js +1 -0
- package/build/cjs/src/utils/subaccount/index.js +11 -1
- package/build/cjs/src/utils/subaccount/sdkClient.js +367 -0
- package/build/cjs/src/utils/subaccount/state.js +76 -0
- package/build/esm/src/clients/v2/__tests__/subaccount.spec.js +271 -1
- package/build/esm/src/clients/v2/__tests__/testUtil.js +87 -0
- package/build/esm/src/clients/v2/index.js +33 -56
- package/build/esm/src/codegen/prebuilt/hashedKinkModelMarketRatesKeys.json +8 -0
- package/build/esm/src/codegen/prebuilt/hashedMarketConfigKeys.json +61 -0
- package/build/esm/src/codegen/prebuilt/hashedMarketValuesKeys.json +15 -0
- package/build/esm/src/configs/markets.js +10 -0
- package/build/esm/src/configs/tokens.js +11 -0
- package/build/esm/src/utils/__tests__/markets.spec.js +30 -0
- package/build/esm/src/utils/markets/utils.js +16 -12
- package/build/esm/src/utils/positions/utils.js +1 -0
- package/build/esm/src/utils/subaccount/index.js +1 -0
- package/build/esm/src/utils/subaccount/sdkClient.js +352 -0
- package/build/esm/src/utils/subaccount/state.js +64 -0
- package/build/tsconfig.tsbuildinfo +1 -1
- package/build/types/src/clients/v2/__tests__/testUtil.d.ts +37 -1
- package/build/types/src/clients/v2/index.d.ts +8 -2
- package/build/types/src/codegen/prebuilt/index.d.ts +84 -0
- package/build/types/src/configs/markets.d.ts +1 -0
- package/build/types/src/utils/markets/utils.d.ts +4 -3
- package/build/types/src/utils/subaccount/index.d.ts +1 -0
- package/build/types/src/utils/subaccount/sdkClient.d.ts +36 -0
- package/build/types/src/utils/subaccount/state.d.ts +11 -0
- package/build/types/src/utils/subaccount/types.d.ts +18 -0
- package/build/types/src/utils/tokens/types.d.ts +1 -1
- package/package.json +1 -1
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.toSignedSubaccountApproval = exports.isSubaccountApprovalExpired = exports.isSubaccountApprovalSynced = exports.isSubaccountApprovalNonceExpired = exports.shouldRefreshExplicitSubaccountApproval = exports.isSameSubaccountApproval = exports.isEmptySubaccountApproval = exports.isSubaccountStatusUsable = exports.parseSubaccountStatus = void 0;
|
|
4
|
+
const numbers_1 = require("../numbers");
|
|
5
|
+
const time_1 = require("../time");
|
|
6
|
+
function parseSubaccountStatus(status) {
|
|
7
|
+
return {
|
|
8
|
+
active: status.active,
|
|
9
|
+
maxAllowedCount: (0, numbers_1.toBigInt)(status.maxAllowedCount) ?? 0n,
|
|
10
|
+
currentActionsCount: (0, numbers_1.toBigInt)(status.currentActionsCount) ?? 0n,
|
|
11
|
+
remainingActions: (0, numbers_1.toBigInt)(status.remainingActions) ?? 0n,
|
|
12
|
+
expiresAt: (0, numbers_1.toBigInt)(status.expiresAt) ?? 0n,
|
|
13
|
+
approvalNonce: (0, numbers_1.toBigInt)(status.approvalNonce) ?? 0n,
|
|
14
|
+
multichainApprovalNonce: (0, numbers_1.toBigInt)(status.multichainApprovalNonce) ?? 0n,
|
|
15
|
+
integrationId: status.integrationId ?? undefined,
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
exports.parseSubaccountStatus = parseSubaccountStatus;
|
|
19
|
+
function isSubaccountStatusUsable(status) {
|
|
20
|
+
return (status !== undefined && status.active && status.remainingActions > 0n && status.expiresAt > BigInt((0, time_1.nowInSeconds)()));
|
|
21
|
+
}
|
|
22
|
+
exports.isSubaccountStatusUsable = isSubaccountStatusUsable;
|
|
23
|
+
function isEmptySubaccountApproval(approval) {
|
|
24
|
+
return approval.signature === "0x";
|
|
25
|
+
}
|
|
26
|
+
exports.isEmptySubaccountApproval = isEmptySubaccountApproval;
|
|
27
|
+
function isSameSubaccountApproval(a, b) {
|
|
28
|
+
return a.signature === b.signature && (0, numbers_1.toBigInt)(a.nonce) === (0, numbers_1.toBigInt)(b.nonce);
|
|
29
|
+
}
|
|
30
|
+
exports.isSameSubaccountApproval = isSameSubaccountApproval;
|
|
31
|
+
function shouldRefreshExplicitSubaccountApproval(approval, status, pendingApproval) {
|
|
32
|
+
if (isEmptySubaccountApproval(approval)) {
|
|
33
|
+
return false;
|
|
34
|
+
}
|
|
35
|
+
if (pendingApproval?.submittedRequestId && isSameSubaccountApproval(approval, pendingApproval.message)) {
|
|
36
|
+
return true;
|
|
37
|
+
}
|
|
38
|
+
return (status !== undefined &&
|
|
39
|
+
(isSubaccountApprovalSynced(approval, status) ||
|
|
40
|
+
isSubaccountApprovalNonceExpired(approval, status) ||
|
|
41
|
+
isSubaccountApprovalExpired(approval)));
|
|
42
|
+
}
|
|
43
|
+
exports.shouldRefreshExplicitSubaccountApproval = shouldRefreshExplicitSubaccountApproval;
|
|
44
|
+
function isSubaccountApprovalNonceExpired(approval, status) {
|
|
45
|
+
return (0, numbers_1.toBigInt)(approval.nonce) !== status.approvalNonce;
|
|
46
|
+
}
|
|
47
|
+
exports.isSubaccountApprovalNonceExpired = isSubaccountApprovalNonceExpired;
|
|
48
|
+
function isSubaccountApprovalSynced(approval, status) {
|
|
49
|
+
return (status.active &&
|
|
50
|
+
status.maxAllowedCount === (0, numbers_1.toBigInt)(approval.maxAllowedCount) &&
|
|
51
|
+
status.expiresAt === (0, numbers_1.toBigInt)(approval.expiresAt));
|
|
52
|
+
}
|
|
53
|
+
exports.isSubaccountApprovalSynced = isSubaccountApprovalSynced;
|
|
54
|
+
function isSubaccountApprovalExpired(approval) {
|
|
55
|
+
const now = BigInt((0, time_1.nowInSeconds)());
|
|
56
|
+
return ((0, numbers_1.toBigInt)(approval.expiresAt) ?? 0n) <= now || ((0, numbers_1.toBigInt)(approval.deadline) ?? 0n) <= now;
|
|
57
|
+
}
|
|
58
|
+
exports.isSubaccountApprovalExpired = isSubaccountApprovalExpired;
|
|
59
|
+
function toSignedSubaccountApproval(prepared, signature) {
|
|
60
|
+
return {
|
|
61
|
+
subaccount: prepared.message.subaccount,
|
|
62
|
+
shouldAdd: Boolean(prepared.message.shouldAdd),
|
|
63
|
+
expiresAt: (0, numbers_1.toBigInt)(prepared.message.expiresAt) ?? 0n,
|
|
64
|
+
maxAllowedCount: (0, numbers_1.toBigInt)(prepared.message.maxAllowedCount) ?? 0n,
|
|
65
|
+
actionType: prepared.message.actionType,
|
|
66
|
+
nonce: (0, numbers_1.toBigInt)(prepared.message.nonce ?? prepared.nonce) ?? 0n,
|
|
67
|
+
desChainId: (0, numbers_1.toBigInt)(prepared.message.desChainId) ?? 0n,
|
|
68
|
+
deadline: (0, numbers_1.toBigInt)(prepared.message.deadline) ?? 0n,
|
|
69
|
+
integrationId: prepared.message.integrationId,
|
|
70
|
+
signature,
|
|
71
|
+
signedAt: Date.now(),
|
|
72
|
+
signatureChainId: prepared.domain.chainId,
|
|
73
|
+
subaccountRouterAddress: prepared.relayRouterAddress,
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
exports.toSignedSubaccountApproval = toSignedSubaccountApproval;
|
|
@@ -1,8 +1,278 @@
|
|
|
1
1
|
import { describe, expect, it } from "vitest";
|
|
2
|
-
import {
|
|
2
|
+
import { getEmptySubaccountApproval } from "../../../utils/subaccount";
|
|
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";
|
|
3
5
|
const signer = getTestSigner();
|
|
4
6
|
const hasSigner = !!signer;
|
|
7
|
+
const LIMIT_TRIGGER_PRICE = 1n * 10n ** 30n;
|
|
8
|
+
const EXTERNAL_SUBACCOUNT_ADDRESS = "0x1111111111111111111111111111111111111111";
|
|
9
|
+
function buildTestPrepareRequest(from) {
|
|
10
|
+
return {
|
|
11
|
+
kind: "increase",
|
|
12
|
+
symbol: TEST_SYMBOL,
|
|
13
|
+
direction: "long",
|
|
14
|
+
orderType: "limit",
|
|
15
|
+
size: TEST_SIZE_USD,
|
|
16
|
+
triggerPrice: LIMIT_TRIGGER_PRICE,
|
|
17
|
+
collateralToken: "USDC",
|
|
18
|
+
collateralToPay: TEST_COLLATERAL,
|
|
19
|
+
mode: "express",
|
|
20
|
+
from,
|
|
21
|
+
};
|
|
22
|
+
}
|
|
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
|
+
}
|
|
5
49
|
describe("GmxApiSdk — subaccount (1CT)", () => {
|
|
50
|
+
it.skipIf(!hasSigner)("rejects external subaccount details for SDK-managed signing", async () => {
|
|
51
|
+
const signer = getTestSigner();
|
|
52
|
+
const api = new ScriptedOrderApi(buildPreparedOrderResponse("request-1"));
|
|
53
|
+
const sdk = new GmxApiSdk({ chainId: TEST_CHAIN_ID, api });
|
|
54
|
+
const subaccountAddress = await sdk.generateSubaccount(signer);
|
|
55
|
+
await expect(sdk.prepareOrder({
|
|
56
|
+
...buildTestPrepareRequest(signer.address),
|
|
57
|
+
subaccountAddress: EXTERNAL_SUBACCOUNT_ADDRESS,
|
|
58
|
+
subaccountApproval: getEmptySubaccountApproval(TEST_CHAIN_ID, subaccountAddress),
|
|
59
|
+
})).rejects.toThrow("subaccountAddress");
|
|
60
|
+
await expect(sdk.prepareOrder({
|
|
61
|
+
...buildTestPrepareRequest(signer.address),
|
|
62
|
+
subaccountApproval: getEmptySubaccountApproval(TEST_CHAIN_ID, EXTERNAL_SUBACCOUNT_ADDRESS),
|
|
63
|
+
})).rejects.toThrow("subaccountApproval.subaccount");
|
|
64
|
+
expect(api.prepareRequests).toHaveLength(0);
|
|
65
|
+
});
|
|
66
|
+
it.skipIf(!hasSigner)("keeps prepared subaccount approval after failed submit response", async () => {
|
|
67
|
+
const signer = getTestSigner();
|
|
68
|
+
const requestId = "retry-request";
|
|
69
|
+
const api = new ScriptedOrderApi(buildPreparedOrderResponse(requestId), [
|
|
70
|
+
{
|
|
71
|
+
requestId,
|
|
72
|
+
status: "relay_failed",
|
|
73
|
+
error: { code: "TEST_RELAY_FAILED", message: "relay failed" },
|
|
74
|
+
},
|
|
75
|
+
{
|
|
76
|
+
requestId,
|
|
77
|
+
status: "relay_accepted",
|
|
78
|
+
},
|
|
79
|
+
], [buildSubaccountStatusResponse()]);
|
|
80
|
+
const sdk = new GmxApiSdk({ chainId: TEST_CHAIN_ID, api });
|
|
81
|
+
const subaccountAddress = await sdk.generateSubaccount(signer);
|
|
82
|
+
const subaccountApproval = getEmptySubaccountApproval(TEST_CHAIN_ID, subaccountAddress);
|
|
83
|
+
await sdk.prepareOrder({
|
|
84
|
+
...buildTestPrepareRequest(signer.address),
|
|
85
|
+
subaccountAddress,
|
|
86
|
+
subaccountApproval,
|
|
87
|
+
});
|
|
88
|
+
const submitRequest = {
|
|
89
|
+
mode: "express",
|
|
90
|
+
requestId,
|
|
91
|
+
signature: "0x",
|
|
92
|
+
from: signer.address,
|
|
93
|
+
eip712Data: {
|
|
94
|
+
batchParams: {},
|
|
95
|
+
relayParams: {},
|
|
96
|
+
},
|
|
97
|
+
};
|
|
98
|
+
await sdk.submitOrder(submitRequest);
|
|
99
|
+
await sdk.submitOrder(submitRequest);
|
|
100
|
+
expect(api.submitRequests[0].eip712Data?.subaccountApproval?.signature).toBe("0x");
|
|
101
|
+
expect(api.submitRequests[1].eip712Data?.subaccountApproval?.signature).toBe("0x");
|
|
102
|
+
});
|
|
103
|
+
it.skipIf(!hasSigner)("decrements cached subaccount actions only after final order status", async () => {
|
|
104
|
+
const signer = getTestSigner();
|
|
105
|
+
const requestId = "accepted-request";
|
|
106
|
+
const api = new ScriptedOrderApi(buildPreparedOrderResponse(requestId), [
|
|
107
|
+
{
|
|
108
|
+
requestId,
|
|
109
|
+
status: "executed",
|
|
110
|
+
},
|
|
111
|
+
], [
|
|
112
|
+
buildSubaccountStatusResponse({
|
|
113
|
+
currentActionsCount: "3",
|
|
114
|
+
remainingActions: "2",
|
|
115
|
+
}),
|
|
116
|
+
]);
|
|
117
|
+
const sdk = new GmxApiSdk({ chainId: TEST_CHAIN_ID, api });
|
|
118
|
+
await sdk.generateSubaccount(signer);
|
|
119
|
+
await sdk.refreshSubaccountState(signer.address);
|
|
120
|
+
await sdk.prepareOrder(buildTestPrepareRequest(signer.address));
|
|
121
|
+
await sdk.submitOrder({
|
|
122
|
+
mode: "express",
|
|
123
|
+
requestId,
|
|
124
|
+
signature: "0x",
|
|
125
|
+
from: signer.address,
|
|
126
|
+
eip712Data: {
|
|
127
|
+
batchParams: {},
|
|
128
|
+
relayParams: {},
|
|
129
|
+
},
|
|
130
|
+
});
|
|
131
|
+
expect(sdk.subaccountStatus?.currentActionsCount).toBe(4n);
|
|
132
|
+
expect(sdk.subaccountStatus?.remainingActions).toBe(1n);
|
|
133
|
+
});
|
|
134
|
+
it.skipIf(!hasSigner)("does not decrement cached subaccount actions for relay_accepted status", async () => {
|
|
135
|
+
const signer = getTestSigner();
|
|
136
|
+
const requestId = "relay-accepted-request";
|
|
137
|
+
const api = new ScriptedOrderApi(buildPreparedOrderResponse(requestId), [
|
|
138
|
+
{
|
|
139
|
+
requestId,
|
|
140
|
+
status: "relay_accepted",
|
|
141
|
+
},
|
|
142
|
+
], [
|
|
143
|
+
buildSubaccountStatusResponse({
|
|
144
|
+
currentActionsCount: "3",
|
|
145
|
+
remainingActions: "2",
|
|
146
|
+
}),
|
|
147
|
+
]);
|
|
148
|
+
const sdk = new GmxApiSdk({ chainId: TEST_CHAIN_ID, api });
|
|
149
|
+
await sdk.generateSubaccount(signer);
|
|
150
|
+
await sdk.refreshSubaccountState(signer.address);
|
|
151
|
+
await sdk.prepareOrder(buildTestPrepareRequest(signer.address));
|
|
152
|
+
await sdk.submitOrder({
|
|
153
|
+
mode: "express",
|
|
154
|
+
requestId,
|
|
155
|
+
signature: "0x",
|
|
156
|
+
from: signer.address,
|
|
157
|
+
eip712Data: {
|
|
158
|
+
batchParams: {},
|
|
159
|
+
relayParams: {},
|
|
160
|
+
},
|
|
161
|
+
});
|
|
162
|
+
expect(sdk.subaccountStatus?.currentActionsCount).toBe(3n);
|
|
163
|
+
expect(sdk.subaccountStatus?.remainingActions).toBe(2n);
|
|
164
|
+
});
|
|
165
|
+
it.skipIf(!hasSigner)("refreshes subaccount state before noop approval when only one action remains", async () => {
|
|
166
|
+
const signer = getTestSigner();
|
|
167
|
+
const api = new ScriptedOrderApi(buildPreparedOrderResponse("request-1"), [], [
|
|
168
|
+
buildSubaccountStatusResponse({
|
|
169
|
+
currentActionsCount: "9",
|
|
170
|
+
remainingActions: "1",
|
|
171
|
+
}),
|
|
172
|
+
buildSubaccountStatusResponse({
|
|
173
|
+
currentActionsCount: "10",
|
|
174
|
+
remainingActions: "0",
|
|
175
|
+
}),
|
|
176
|
+
]);
|
|
177
|
+
const sdk = new GmxApiSdk({ chainId: TEST_CHAIN_ID, api });
|
|
178
|
+
await sdk.generateSubaccount(signer);
|
|
179
|
+
await sdk.refreshSubaccountState(signer.address);
|
|
180
|
+
await expect(sdk.prepareOrder(buildTestPrepareRequest(signer.address))).rejects.toThrow("Subaccount is not active");
|
|
181
|
+
expect(api.subaccountStatusRequests).toHaveLength(2);
|
|
182
|
+
expect(api.prepareRequests).toHaveLength(0);
|
|
183
|
+
});
|
|
184
|
+
it.skipIf(!hasSigner)("validates caller-supplied noop approval against exhausted subaccount quota", async () => {
|
|
185
|
+
const signer = getTestSigner();
|
|
186
|
+
const api = new ScriptedOrderApi(buildPreparedOrderResponse("request-1"), [], [
|
|
187
|
+
buildSubaccountStatusResponse({
|
|
188
|
+
currentActionsCount: "10",
|
|
189
|
+
remainingActions: "0",
|
|
190
|
+
}),
|
|
191
|
+
]);
|
|
192
|
+
const sdk = new GmxApiSdk({ chainId: TEST_CHAIN_ID, api });
|
|
193
|
+
const subaccountAddress = await sdk.generateSubaccount(signer);
|
|
194
|
+
await sdk.refreshSubaccountState(signer.address);
|
|
195
|
+
await expect(sdk.prepareOrder({
|
|
196
|
+
...buildTestPrepareRequest(signer.address),
|
|
197
|
+
subaccountAddress,
|
|
198
|
+
subaccountApproval: getEmptySubaccountApproval(TEST_CHAIN_ID, subaccountAddress),
|
|
199
|
+
})).rejects.toThrow("Subaccount is not active");
|
|
200
|
+
expect(api.prepareRequests).toHaveLength(0);
|
|
201
|
+
});
|
|
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);
|
|
6
276
|
it.skipIf(!hasSigner)("generateSubaccount derives address deterministically", async () => {
|
|
7
277
|
const sdk1 = getTestSdk();
|
|
8
278
|
const sdk2 = getTestSdk();
|
|
@@ -7,6 +7,93 @@ export const TEST_SYMBOL = "ETH/USD [WETH-USDC]";
|
|
|
7
7
|
export const TEST_SIZE_USD = 10n * 10n ** 30n; // $10
|
|
8
8
|
export const TEST_COLLATERAL = { amount: 1000000n, token: "USDC" }; // 1 USDC
|
|
9
9
|
const TERMINAL_STATUSES = new Set(["executed", "cancelled", "relay_failed", "relay_reverted"]);
|
|
10
|
+
const ORDER_PREPARE_PATHS = new Set([
|
|
11
|
+
"/v1/orders/txns/prepare",
|
|
12
|
+
"/v1/orders/txns/edit/prepare",
|
|
13
|
+
"/v1/orders/txns/cancel/prepare",
|
|
14
|
+
"/v1/orders/txns/collateral/prepare",
|
|
15
|
+
]);
|
|
16
|
+
export class RecordingApi {
|
|
17
|
+
constructor(delegate) {
|
|
18
|
+
this.delegate = delegate;
|
|
19
|
+
this.orderPrepareRequests = [];
|
|
20
|
+
this.orderSubmitRequests = [];
|
|
21
|
+
this.url = delegate.url;
|
|
22
|
+
}
|
|
23
|
+
fetchJson(path, opts) {
|
|
24
|
+
return this.delegate.fetchJson(path, opts);
|
|
25
|
+
}
|
|
26
|
+
postJson(path, body, opts) {
|
|
27
|
+
if (ORDER_PREPARE_PATHS.has(path)) {
|
|
28
|
+
this.orderPrepareRequests.push(body);
|
|
29
|
+
}
|
|
30
|
+
else if (path === "/v1/orders/txns/submit") {
|
|
31
|
+
this.orderSubmitRequests.push(body);
|
|
32
|
+
}
|
|
33
|
+
return this.delegate.postJson(path, body, opts);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
export function buildPreparedOrderResponse(requestId) {
|
|
37
|
+
return {
|
|
38
|
+
requestId,
|
|
39
|
+
mode: "express",
|
|
40
|
+
payloadType: "typed-data",
|
|
41
|
+
payload: {
|
|
42
|
+
batchParams: {},
|
|
43
|
+
relayParams: {},
|
|
44
|
+
},
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
export class ScriptedOrderApi {
|
|
48
|
+
constructor(prepareResponse, submitResponses = [], subaccountStatusResponses = []) {
|
|
49
|
+
this.prepareResponse = prepareResponse;
|
|
50
|
+
this.submitResponses = submitResponses;
|
|
51
|
+
this.subaccountStatusResponses = subaccountStatusResponses;
|
|
52
|
+
this.url = "http://test";
|
|
53
|
+
this.prepareRequests = [];
|
|
54
|
+
this.submitRequests = [];
|
|
55
|
+
this.subaccountStatusRequests = [];
|
|
56
|
+
}
|
|
57
|
+
fetchJson(path, _opts) {
|
|
58
|
+
return Promise.reject(new Error(`Unexpected fetchJson call ${path}`));
|
|
59
|
+
}
|
|
60
|
+
postJson(path, body, opts) {
|
|
61
|
+
if (path === "/v1/orders/txns/prepare") {
|
|
62
|
+
this.prepareRequests.push(body);
|
|
63
|
+
return Promise.resolve(opts?.transform ? opts.transform(this.prepareResponse) : this.prepareResponse);
|
|
64
|
+
}
|
|
65
|
+
if (path === "/v1/orders/txns/submit") {
|
|
66
|
+
this.submitRequests.push(body);
|
|
67
|
+
const response = this.submitResponses.shift();
|
|
68
|
+
if (!response) {
|
|
69
|
+
return Promise.reject(new Error("Unexpected submit call"));
|
|
70
|
+
}
|
|
71
|
+
return Promise.resolve(response);
|
|
72
|
+
}
|
|
73
|
+
if (path === "/v1/subaccounts/status") {
|
|
74
|
+
this.subaccountStatusRequests.push(body);
|
|
75
|
+
const response = this.subaccountStatusResponses.shift();
|
|
76
|
+
if (!response) {
|
|
77
|
+
return Promise.reject(new Error("Unexpected subaccount status call"));
|
|
78
|
+
}
|
|
79
|
+
return Promise.resolve(response);
|
|
80
|
+
}
|
|
81
|
+
return Promise.reject(new Error(`Unexpected API path ${path}`));
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
export function buildSubaccountStatusResponse(overrides = {}) {
|
|
85
|
+
return {
|
|
86
|
+
active: true,
|
|
87
|
+
maxAllowedCount: "10",
|
|
88
|
+
currentActionsCount: "0",
|
|
89
|
+
remainingActions: "10",
|
|
90
|
+
expiresAt: String(Math.floor(Date.now() / 1000) + 86400),
|
|
91
|
+
approvalNonce: "0",
|
|
92
|
+
multichainApprovalNonce: "0",
|
|
93
|
+
integrationId: null,
|
|
94
|
+
...overrides,
|
|
95
|
+
};
|
|
96
|
+
}
|
|
10
97
|
export function getTestSdk() {
|
|
11
98
|
// eslint-disable-next-line no-restricted-globals
|
|
12
99
|
const apiUrl = process.env.GMX_TEST_API_URL;
|
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import { getApiUrl, getApiFallbackUrls } from "../../configs/api";
|
|
2
|
-
import { DEFAULT_SUBACCOUNT_EXPIRY_DURATION, DEFAULT_SUBACCOUNT_MAX_ALLOWED_COUNT } from "../../configs/express";
|
|
3
2
|
import { isSettlementChain } from "../../configs/multichain";
|
|
4
3
|
import { fetchApiApy } from "../../utils/apy/api";
|
|
5
4
|
import { fetchWalletBalances as fetchWalletBalancesRaw, fetchAllowances as fetchAllowancesRaw, buildApproveTransaction, buildErc20ApproveTxn, executeErc20Approve, } from "../../utils/balances/api";
|
|
@@ -11,7 +10,7 @@ import { fetchApiJitLiquidityInfo } from "../../utils/jitLiquidity/api";
|
|
|
11
10
|
import { fetchApiMarkets, fetchApiMarketsInfo, fetchApiMarketsTickers, fetchApiTokensData } from "../../utils/markets/api";
|
|
12
11
|
import { buildCrossChainWithdrawBridgeOutParams, buildSameChainDepositTxn, buildSameChainWithdrawBridgeOutParams, buildSameChainWithdrawTxn, executeSameChainDeposit, executeSameChainWithdraw, } from "../../utils/multichain";
|
|
13
12
|
import { fetchApiOrders } from "../../utils/orders/api";
|
|
14
|
-
import { prepareOrder,
|
|
13
|
+
import { prepareOrder, prepareEditOrder, prepareCancelOrder, prepareCollateral, fetchOrderStatus as fetchOrderStatusRaw, } from "../../utils/orderTransactions/api";
|
|
15
14
|
import { fetchApiPairs } from "../../utils/pairs/api";
|
|
16
15
|
import { fetchApiPerformanceAnnualized, fetchApiPerformanceSnapshots } from "../../utils/performance/api";
|
|
17
16
|
import { fetchApiPositionsInfo } from "../../utils/positions/api";
|
|
@@ -19,17 +18,16 @@ import { fetchApiOhlcv } from "../../utils/prices/api";
|
|
|
19
18
|
import { fetchApiRates } from "../../utils/rates/api";
|
|
20
19
|
import { fetchApiStakingPower } from "../../utils/staking/api";
|
|
21
20
|
import { fetchSubaccountStatus, prepareSubaccountApproval, signSubaccountApproval } from "../../utils/subaccount/api";
|
|
22
|
-
import {
|
|
23
|
-
import { nowInSeconds } from "../../utils/time";
|
|
21
|
+
import { activateSdkSubaccount, clearSdkSubaccount, executeExpressOrderWithSubaccount, generateSdkSubaccount, getSdkSubaccountApprovalMessage, hasActiveSdkSubaccount, prepareWithSubaccount, refreshSdkSubaccountState, signOrderWithSubaccount, submitOrderWithSubaccount, } from "../../utils/subaccount/sdkClient";
|
|
24
22
|
import { fetchApiTokens } from "../../utils/tokens/api";
|
|
25
23
|
import { fetchApiTrades, searchApiTrades } from "../../utils/trades/api";
|
|
26
24
|
export { PrivateKeySigner } from "../../utils/signer";
|
|
27
25
|
export { HttpError } from "../../utils/http/http";
|
|
28
26
|
export { HttpClientWithFallback } from "../../utils/http/httpFallback";
|
|
29
27
|
export { getGasPaymentTokens } from "../../configs/express";
|
|
30
|
-
const subaccountSigners = new WeakMap();
|
|
31
28
|
export class GmxApiSdk {
|
|
32
29
|
constructor({ chainId, apiUrl, api }) {
|
|
30
|
+
this.preparedSubaccountApprovals = new Map();
|
|
33
31
|
if (api) {
|
|
34
32
|
this.ctx = { chainId, api };
|
|
35
33
|
return;
|
|
@@ -45,14 +43,28 @@ export class GmxApiSdk {
|
|
|
45
43
|
api: allUrls.length > 1 ? new HttpClientWithFallback(allUrls) : new HttpClient(resolvedApiUrl),
|
|
46
44
|
};
|
|
47
45
|
}
|
|
46
|
+
get subaccountClient() {
|
|
47
|
+
return {
|
|
48
|
+
ctx: this.ctx,
|
|
49
|
+
owner: this,
|
|
50
|
+
preparedSubaccountApprovals: this.preparedSubaccountApprovals,
|
|
51
|
+
getSubaccount: () => this._subaccount,
|
|
52
|
+
setSubaccount: (subaccount) => {
|
|
53
|
+
this._subaccount = subaccount;
|
|
54
|
+
},
|
|
55
|
+
};
|
|
56
|
+
}
|
|
48
57
|
get subaccountAddress() {
|
|
49
58
|
return this._subaccount?.address;
|
|
50
59
|
}
|
|
60
|
+
get subaccountStatus() {
|
|
61
|
+
return this._subaccount?.onchainData;
|
|
62
|
+
}
|
|
51
63
|
get hasActiveSubaccount() {
|
|
52
|
-
return this.
|
|
64
|
+
return hasActiveSdkSubaccount(this.subaccountClient);
|
|
53
65
|
}
|
|
54
66
|
get subaccountApprovalMessage() {
|
|
55
|
-
return this.
|
|
67
|
+
return getSdkSubaccountApprovalMessage(this.subaccountClient);
|
|
56
68
|
}
|
|
57
69
|
fetchMarketsInfo() {
|
|
58
70
|
return fetchApiMarketsInfo(this.ctx);
|
|
@@ -171,44 +183,35 @@ export class GmxApiSdk {
|
|
|
171
183
|
return getCrossChainWithdrawStatus(this.ctx, requestId);
|
|
172
184
|
}
|
|
173
185
|
prepareOrder(request) {
|
|
174
|
-
return
|
|
186
|
+
return prepareWithSubaccount(this.subaccountClient, request, prepareOrder);
|
|
175
187
|
}
|
|
176
188
|
signOrder(prepared, signer) {
|
|
177
|
-
|
|
178
|
-
const effectiveSigner = subSigner ?? signer;
|
|
179
|
-
const accountAddress = subSigner ? signer.address : undefined;
|
|
180
|
-
return signPreparedOrder(prepared, effectiveSigner, this.ctx.chainId, accountAddress);
|
|
189
|
+
return signOrderWithSubaccount(this.subaccountClient, prepared, signer);
|
|
181
190
|
}
|
|
182
|
-
submitOrder(request) {
|
|
183
|
-
return
|
|
191
|
+
async submitOrder(request) {
|
|
192
|
+
return submitOrderWithSubaccount(this.subaccountClient, request);
|
|
184
193
|
}
|
|
185
194
|
async executeExpressOrder(request, signer) {
|
|
186
|
-
|
|
187
|
-
if (subSigner && this._subaccount?.approval) {
|
|
188
|
-
const enrichedRequest = {
|
|
189
|
-
...request,
|
|
190
|
-
subaccountAddress: this._subaccount.address,
|
|
191
|
-
subaccountApproval: this._subaccount.approval.message,
|
|
192
|
-
};
|
|
193
|
-
return executeExpressOrderRaw(this.ctx, enrichedRequest, subSigner, request.from);
|
|
194
|
-
}
|
|
195
|
-
return executeExpressOrderRaw(this.ctx, request, signer);
|
|
195
|
+
return executeExpressOrderWithSubaccount(this.subaccountClient, request, signer);
|
|
196
196
|
}
|
|
197
197
|
fetchOrderStatus(request) {
|
|
198
198
|
return fetchOrderStatusRaw(this.ctx, request);
|
|
199
199
|
}
|
|
200
200
|
prepareEditOrder(request) {
|
|
201
|
-
return
|
|
201
|
+
return prepareWithSubaccount(this.subaccountClient, request, prepareEditOrder);
|
|
202
202
|
}
|
|
203
203
|
prepareCancelOrder(request) {
|
|
204
|
-
return
|
|
204
|
+
return prepareWithSubaccount(this.subaccountClient, request, prepareCancelOrder);
|
|
205
205
|
}
|
|
206
206
|
prepareCollateral(request) {
|
|
207
|
-
return
|
|
207
|
+
return prepareWithSubaccount(this.subaccountClient, request, prepareCollateral);
|
|
208
208
|
}
|
|
209
209
|
fetchSubaccountStatus(request) {
|
|
210
210
|
return fetchSubaccountStatus(this.ctx, request);
|
|
211
211
|
}
|
|
212
|
+
async refreshSubaccountState(account) {
|
|
213
|
+
return refreshSdkSubaccountState(this.subaccountClient, account);
|
|
214
|
+
}
|
|
212
215
|
prepareSubaccountApproval(request) {
|
|
213
216
|
return prepareSubaccountApproval(this.ctx, request);
|
|
214
217
|
}
|
|
@@ -227,12 +230,7 @@ export class GmxApiSdk {
|
|
|
227
230
|
* approval and start using it for orders.
|
|
228
231
|
*/
|
|
229
232
|
async generateSubaccount(mainSigner) {
|
|
230
|
-
|
|
231
|
-
subaccountSigners.set(this, result.signer);
|
|
232
|
-
this._subaccount = {
|
|
233
|
-
address: result.address,
|
|
234
|
-
};
|
|
235
|
-
return result.address;
|
|
233
|
+
return generateSdkSubaccount(this.subaccountClient, mainSigner);
|
|
236
234
|
}
|
|
237
235
|
/**
|
|
238
236
|
* Generate (if needed) and activate the subaccount:
|
|
@@ -241,30 +239,9 @@ export class GmxApiSdk {
|
|
|
241
239
|
* 3. Stores the approval so subsequent orders use 1CT mode automatically
|
|
242
240
|
*/
|
|
243
241
|
async activateSubaccount(mainSigner, options) {
|
|
244
|
-
|
|
245
|
-
await this.generateSubaccount(mainSigner);
|
|
246
|
-
}
|
|
247
|
-
const expiresAt = String(nowInSeconds() + (options?.expiresInSeconds ?? DEFAULT_SUBACCOUNT_EXPIRY_DURATION));
|
|
248
|
-
const maxAllowedCount = String(options?.maxAllowedCount ?? DEFAULT_SUBACCOUNT_MAX_ALLOWED_COUNT);
|
|
249
|
-
const prepared = await this.prepareSubaccountApproval({
|
|
250
|
-
account: mainSigner.address,
|
|
251
|
-
subaccountAddress: this._subaccount.address,
|
|
252
|
-
shouldAdd: true,
|
|
253
|
-
expiresAt,
|
|
254
|
-
maxAllowedCount,
|
|
255
|
-
});
|
|
256
|
-
const signature = await signSubaccountApproval(prepared, mainSigner, {
|
|
257
|
-
chainId: this.ctx.chainId,
|
|
258
|
-
expectedSubaccountAddress: this._subaccount.address,
|
|
259
|
-
});
|
|
260
|
-
this._subaccount.approval = {
|
|
261
|
-
message: { ...prepared.message, signature },
|
|
262
|
-
signature,
|
|
263
|
-
};
|
|
264
|
-
return this._subaccount.address;
|
|
242
|
+
return activateSdkSubaccount(this.subaccountClient, mainSigner, options);
|
|
265
243
|
}
|
|
266
244
|
clearSubaccount() {
|
|
267
|
-
|
|
268
|
-
this._subaccount = undefined;
|
|
245
|
+
clearSdkSubaccount(this.subaccountClient);
|
|
269
246
|
}
|
|
270
247
|
}
|
|
@@ -1124,6 +1124,14 @@
|
|
|
1124
1124
|
"aboveOptimalUsageBorrowingFactorLong": "0xfdc145dc5c86925a834513f0c78ef57f8da0f095253e561506b6367106d5caac",
|
|
1125
1125
|
"aboveOptimalUsageBorrowingFactorShort": "0xc961a42b4a07b7f63f14fbd2a3c14c41643eb80dd5a8fdcde32ad1365bcb51a7"
|
|
1126
1126
|
},
|
|
1127
|
+
"0x470128853D74dab7423904a20eA5AA230e9e561B": {
|
|
1128
|
+
"optimalUsageFactorLong": "0xea04ac5384e4e3d5ba65acf6c8e6d030d7363b1a23b8c11bb58ae3ac16f4d6ef",
|
|
1129
|
+
"optimalUsageFactorShort": "0xf5ee87e53fffcadf24faa470f02b3bb0330cd9831045be7607787069de177b1b",
|
|
1130
|
+
"baseBorrowingFactorLong": "0xc288943efb3c238de85008769939b3b7def08f466702f497bc733c8b1c85ef3a",
|
|
1131
|
+
"baseBorrowingFactorShort": "0x92d89abb98ad384bea84894361789e7c950c1298246e71c24fc0883e953a1ede",
|
|
1132
|
+
"aboveOptimalUsageBorrowingFactorLong": "0x7e034f066736dca0c85aaf2dfb4c64048d34fce3c932085d783794ba2024df9d",
|
|
1133
|
+
"aboveOptimalUsageBorrowingFactorShort": "0xbc8b7b4174c18250b8cbe2bc9b23b678695089afbe2cf61ed4b90643cefc050e"
|
|
1134
|
+
},
|
|
1127
1135
|
"0xE26E7b91143f367445f1c0a5dCf4f4aC8EaDcDb1": {
|
|
1128
1136
|
"optimalUsageFactorLong": "0x7dd92ed8d2f972a0bedc134931f1ce1257fdc1ba4ebc043c270e81880efee700",
|
|
1129
1137
|
"optimalUsageFactorShort": "0xec58abc0c1c902e8df7ed4f6968dbfd88228e741bfd63bf3efc635e0d7c9bb9d",
|