@gmx-io/sdk 2.0.0 → 2.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/cjs/src/configs/api.js +1 -1
- package/build/cjs/src/utils/__tests__/numbers.spec.js +51 -0
- package/build/cjs/src/utils/gmxAccountApi/api.js +4 -7
- package/build/cjs/src/utils/http/__tests__/chainPins.spec.js +76 -0
- package/build/cjs/src/utils/http/chainPins.js +81 -0
- package/build/cjs/src/utils/http/http.js +3 -0
- package/build/cjs/src/utils/http/httpFallback.js +9 -1
- package/build/cjs/src/utils/numbers/utils.js +4 -3
- package/build/cjs/src/utils/orderTransactions/api.js +11 -6
- package/build/esm/src/configs/api.js +1 -1
- package/build/esm/src/utils/__tests__/numbers.spec.js +52 -1
- package/build/esm/src/utils/gmxAccountApi/api.js +4 -7
- package/build/esm/src/utils/http/__tests__/chainPins.spec.js +74 -0
- package/build/esm/src/utils/http/chainPins.js +76 -0
- package/build/esm/src/utils/http/http.js +3 -0
- package/build/esm/src/utils/http/httpFallback.js +9 -1
- package/build/esm/src/utils/numbers/utils.js +4 -3
- package/build/esm/src/utils/orderTransactions/api.js +11 -6
- package/build/tsconfig.tsbuildinfo +1 -1
- package/build/types/src/utils/http/__tests__/chainPins.spec.d.ts +1 -0
- package/build/types/src/utils/http/chainPins.d.ts +9 -0
- package/build/types/src/utils/http/http.d.ts +4 -1
- package/build/types/src/utils/http/httpFallback.d.ts +4 -1
- package/build/types/src/utils/http/types.d.ts +7 -0
- package/package.json +1 -1
|
@@ -7,7 +7,7 @@ const API_URLS = {
|
|
|
7
7
|
[chains_1.ARBITRUM]: "https://arbitrum.gmxapi.io",
|
|
8
8
|
[chains_1.AVALANCHE]: "https://avalanche.gmxapi.io",
|
|
9
9
|
[chains_1.AVALANCHE_FUJI]: undefined,
|
|
10
|
-
[chains_1.ARBITRUM_SEPOLIA]: "https://
|
|
10
|
+
[chains_1.ARBITRUM_SEPOLIA]: "https://arbitrum-sepolia-test.gmxapi.ai",
|
|
11
11
|
[chains_1.MEGAETH]: "https://megaeth.gmxapi.io",
|
|
12
12
|
},
|
|
13
13
|
test: {
|
|
@@ -259,7 +259,58 @@ const ONE_USD = 1000000000000000000000000000000n;
|
|
|
259
259
|
(0, vitest_1.expect)((0, numbers_1.formatUsdPrice)(ONE_USD / 10000000000n)).toBe("<\u00a0$\u200a0.000000001");
|
|
260
260
|
});
|
|
261
261
|
});
|
|
262
|
+
(0, vitest_1.describe)("formatNumberHuman", () => {
|
|
263
|
+
vitest_1.it.each([
|
|
264
|
+
[999.94, 1, "999.9"],
|
|
265
|
+
[999.96, 1, "1.0k"],
|
|
266
|
+
[1000, 1, "1.0k"],
|
|
267
|
+
[999940, 1, "999.9k"],
|
|
268
|
+
[999960, 1, "1.0m"],
|
|
269
|
+
[999996, 1, "1.0m"],
|
|
270
|
+
[1000000, 1, "1.0m"],
|
|
271
|
+
[999940000, 1, "999.9m"],
|
|
272
|
+
[999960000, 1, "1.0b"],
|
|
273
|
+
[1000000000, 1, "1.0b"],
|
|
274
|
+
[999.4, 0, "999"],
|
|
275
|
+
[999.6, 0, "1k"],
|
|
276
|
+
[999400, 0, "999k"],
|
|
277
|
+
[999600, 0, "1m"],
|
|
278
|
+
[999400000, 0, "999m"],
|
|
279
|
+
[999600000, 0, "1b"],
|
|
280
|
+
[999.994, 2, "999.99"],
|
|
281
|
+
[999.996, 2, "1.00k"],
|
|
282
|
+
[999994, 2, "999.99k"],
|
|
283
|
+
[999996, 2, "1.00m"],
|
|
284
|
+
[999994000, 2, "999.99m"],
|
|
285
|
+
[999996000, 2, "1.00b"],
|
|
286
|
+
])("formats %s at %s decimal places as %s", (value, displayDecimals, expected) => {
|
|
287
|
+
(0, vitest_1.expect)((0, numbers_1.formatNumberHuman)(value, false, displayDecimals)).toBe(expected);
|
|
288
|
+
(0, vitest_1.expect)((0, numbers_1.formatNumberHuman)(-value, false, displayDecimals)).toBe(`-${expected}`);
|
|
289
|
+
(0, vitest_1.expect)((0, numbers_1.formatNumberHuman)(value, true, displayDecimals)).toBe(`$\u200a${expected}`);
|
|
290
|
+
(0, vitest_1.expect)((0, numbers_1.formatNumberHuman)(-value, true, displayDecimals)).toBe(`-$\u200a${expected}`);
|
|
291
|
+
});
|
|
292
|
+
(0, vitest_1.it)("preserves zero and small values", () => {
|
|
293
|
+
(0, vitest_1.expect)((0, numbers_1.formatNumberHuman)(0)).toBe("0.0");
|
|
294
|
+
(0, vitest_1.expect)((0, numbers_1.formatNumberHuman)(0, true, 2)).toBe("$\u200a0.00");
|
|
295
|
+
(0, vitest_1.expect)((0, numbers_1.formatNumberHuman)(0.04)).toBe("0.0");
|
|
296
|
+
(0, vitest_1.expect)((0, numbers_1.formatNumberHuman)(-0.04)).toBe("-0.0");
|
|
297
|
+
});
|
|
298
|
+
});
|
|
262
299
|
(0, vitest_1.describe)("formatAmountHuman", () => {
|
|
300
|
+
vitest_1.it.each([
|
|
301
|
+
["999.94", "$\u200a999.9"],
|
|
302
|
+
["999.96", "$\u200a1.0k"],
|
|
303
|
+
["999996", "$\u200a1.0m"],
|
|
304
|
+
["999996000", "$\u200a1.0b"],
|
|
305
|
+
])("formats the USD amount %s as %s", (value, expected) => {
|
|
306
|
+
const amount = (0, numbers_1.toBigNumberWithDecimals)(value, factors_1.USD_DECIMALS);
|
|
307
|
+
(0, vitest_1.expect)((0, numbers_1.formatAmountHuman)(amount, factors_1.USD_DECIMALS, true, 1)).toBe(expected);
|
|
308
|
+
(0, vitest_1.expect)((0, numbers_1.formatAmountHuman)(-amount, factors_1.USD_DECIMALS, true, 1)).toBe(`-${expected}`);
|
|
309
|
+
});
|
|
310
|
+
(0, vitest_1.it)("preserves loading and zero values", () => {
|
|
311
|
+
(0, vitest_1.expect)((0, numbers_1.formatAmountHuman)(undefined, factors_1.USD_DECIMALS, true)).toBe("...");
|
|
312
|
+
(0, vitest_1.expect)((0, numbers_1.formatAmountHuman)(0n, factors_1.USD_DECIMALS, true)).toBe("$\u200a0.0");
|
|
313
|
+
});
|
|
263
314
|
(0, vitest_1.it)("positive", () => {
|
|
264
315
|
(0, vitest_1.expect)((0, numbers_1.formatAmountHuman)(ONE_USD, factors_1.USD_DECIMALS)).toBe("1.0");
|
|
265
316
|
(0, vitest_1.expect)((0, numbers_1.formatAmountHuman)(ONE_USD * 1000n, factors_1.USD_DECIMALS)).toBe("1.0k");
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.getCrossChainWithdrawStatus = exports.executeCrossChainWithdraw = exports.signCrossChainWithdrawPrepared = exports.submitCrossChainWithdraw = exports.prepareCrossChainWithdraw = exports.executeCrossChainDeposit = exports.prepareCrossChainDeposit = void 0;
|
|
4
|
+
const chainPins_1 = require("../http/chainPins");
|
|
4
5
|
function parseDepositPrepareResponse(raw) {
|
|
5
6
|
return {
|
|
6
7
|
payloadType: "transaction",
|
|
@@ -57,13 +58,11 @@ async function executeCrossChainDeposit(ctx, signer, request) {
|
|
|
57
58
|
}
|
|
58
59
|
exports.executeCrossChainDeposit = executeCrossChainDeposit;
|
|
59
60
|
async function prepareCrossChainWithdraw(ctx, request) {
|
|
60
|
-
return ctx.api
|
|
61
|
-
transform: parseWithdrawPrepareResponse,
|
|
62
|
-
});
|
|
61
|
+
return (0, chainPins_1.postJsonPinning)(ctx.api, "/v1/gmx-account/withdraw/cross-chain/prepare", request, (prepared) => [prepared.requestId], { transform: parseWithdrawPrepareResponse });
|
|
63
62
|
}
|
|
64
63
|
exports.prepareCrossChainWithdraw = prepareCrossChainWithdraw;
|
|
65
64
|
async function submitCrossChainWithdraw(ctx, request) {
|
|
66
|
-
return ctx.api.
|
|
65
|
+
return (0, chainPins_1.postJsonPinned)(ctx.api, [request.requestId], "/v1/gmx-account/withdraw/cross-chain/submit", request);
|
|
67
66
|
}
|
|
68
67
|
exports.submitCrossChainWithdraw = submitCrossChainWithdraw;
|
|
69
68
|
async function signCrossChainWithdrawPrepared(prepared, signer) {
|
|
@@ -87,8 +86,6 @@ async function executeCrossChainWithdraw(ctx, signer, request) {
|
|
|
87
86
|
}
|
|
88
87
|
exports.executeCrossChainWithdraw = executeCrossChainWithdraw;
|
|
89
88
|
async function getCrossChainWithdrawStatus(ctx, requestId) {
|
|
90
|
-
return ctx.api
|
|
91
|
-
requestId,
|
|
92
|
-
});
|
|
89
|
+
return (0, chainPins_1.postJsonPinned)(ctx.api, [requestId], "/v1/gmx-account/withdraw/cross-chain/status", { requestId });
|
|
93
90
|
}
|
|
94
91
|
exports.getCrossChainWithdrawStatus = getCrossChainWithdrawStatus;
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
const vitest_1 = require("vitest");
|
|
4
|
+
const httpFallback_1 = require("../httpFallback");
|
|
5
|
+
const api_1 = require("../../orderTransactions/api");
|
|
6
|
+
const fetchMock = vitest_1.vi.hoisted(() => vitest_1.vi.fn());
|
|
7
|
+
vitest_1.vi.mock("cross-fetch", () => ({ default: fetchMock }));
|
|
8
|
+
const PREPARE = "/v1/orders/txns/prepare";
|
|
9
|
+
const SUBMIT = "/v1/orders/txns/submit";
|
|
10
|
+
const STATUS = "/v1/orders/txns/status";
|
|
11
|
+
function jsonResponse(status, body) {
|
|
12
|
+
return new Response(JSON.stringify(body), { status, headers: { "Content-Type": "application/json" } });
|
|
13
|
+
}
|
|
14
|
+
(0, vitest_1.describe)("express chain pinning", () => {
|
|
15
|
+
const calls = [];
|
|
16
|
+
const failingOnA = new Set();
|
|
17
|
+
const notFoundOnce = new Set();
|
|
18
|
+
(0, vitest_1.beforeEach)(() => {
|
|
19
|
+
calls.length = 0;
|
|
20
|
+
failingOnA.clear();
|
|
21
|
+
notFoundOnce.clear();
|
|
22
|
+
vitest_1.vi.spyOn(Math, "random").mockReturnValue(0);
|
|
23
|
+
fetchMock.mockImplementation(async (input) => {
|
|
24
|
+
const url = new URL(input);
|
|
25
|
+
calls.push(`${url.origin}${url.pathname}`);
|
|
26
|
+
if (url.origin === "http://a" && failingOnA.has(url.pathname)) {
|
|
27
|
+
return jsonResponse(503, { message: "busy" });
|
|
28
|
+
}
|
|
29
|
+
if (notFoundOnce.delete(url.pathname)) {
|
|
30
|
+
return jsonResponse(404, { message: "not found" });
|
|
31
|
+
}
|
|
32
|
+
if (url.pathname === PREPARE) {
|
|
33
|
+
return jsonResponse(200, { requestId: "req-1", payloadType: "typed-data", mode: "express", payload: {} });
|
|
34
|
+
}
|
|
35
|
+
if (url.pathname === SUBMIT) {
|
|
36
|
+
return jsonResponse(200, { requestId: "req-1", status: "relay_accepted" });
|
|
37
|
+
}
|
|
38
|
+
if (url.pathname === STATUS) {
|
|
39
|
+
return jsonResponse(200, { requestId: "req-1", status: "created" });
|
|
40
|
+
}
|
|
41
|
+
return jsonResponse(404, { message: "not found" });
|
|
42
|
+
});
|
|
43
|
+
});
|
|
44
|
+
(0, vitest_1.afterEach)(() => {
|
|
45
|
+
vitest_1.vi.restoreAllMocks();
|
|
46
|
+
});
|
|
47
|
+
function newCtx() {
|
|
48
|
+
return { api: new httpFallback_1.HttpClientWithFallback(["http://a", "http://b"]) };
|
|
49
|
+
}
|
|
50
|
+
(0, vitest_1.it)("sends submit and status to the origin that served prepare", async () => {
|
|
51
|
+
failingOnA.add(PREPARE);
|
|
52
|
+
const ctx = newCtx();
|
|
53
|
+
const prepared = await (0, api_1.prepareOrder)(ctx, { kind: "increase", orderType: "market", mode: "express", from: "0x1" });
|
|
54
|
+
await (0, api_1.submitOrder)(ctx, { mode: "express", requestId: prepared.requestId });
|
|
55
|
+
await (0, api_1.fetchOrderStatus)(ctx, { requestId: prepared.requestId });
|
|
56
|
+
(0, vitest_1.expect)(calls).toEqual([`http://a${PREPARE}`, `http://b${PREPARE}`, `http://b${SUBMIT}`, `http://b${STATUS}`]);
|
|
57
|
+
});
|
|
58
|
+
(0, vitest_1.it)("pins status to the origin that served an unpinned submit", async () => {
|
|
59
|
+
failingOnA.add(SUBMIT);
|
|
60
|
+
const ctx = newCtx();
|
|
61
|
+
await (0, api_1.submitOrder)(ctx, { mode: "express", requestId: "req-1" });
|
|
62
|
+
await (0, api_1.fetchOrderStatus)(ctx, { requestId: "req-1" });
|
|
63
|
+
(0, vitest_1.expect)(calls).toEqual([`http://a${SUBMIT}`, `http://b${SUBMIT}`, `http://b${STATUS}`]);
|
|
64
|
+
});
|
|
65
|
+
(0, vitest_1.it)("drops the pin when the pinned origin answers 404", async () => {
|
|
66
|
+
failingOnA.add(PREPARE);
|
|
67
|
+
const ctx = newCtx();
|
|
68
|
+
const prepared = await (0, api_1.prepareOrder)(ctx, { kind: "increase", orderType: "market", mode: "express", from: "0x1" });
|
|
69
|
+
notFoundOnce.add(SUBMIT);
|
|
70
|
+
await (0, vitest_1.expect)((0, api_1.submitOrder)(ctx, { mode: "express", requestId: prepared.requestId })).rejects.toMatchObject({
|
|
71
|
+
statusCode: 404,
|
|
72
|
+
});
|
|
73
|
+
await (0, api_1.fetchOrderStatus)(ctx, { requestId: prepared.requestId });
|
|
74
|
+
(0, vitest_1.expect)(calls).toEqual([`http://a${PREPARE}`, `http://b${PREPARE}`, `http://b${SUBMIT}`, `http://a${STATUS}`]);
|
|
75
|
+
});
|
|
76
|
+
});
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.postJsonPinned = exports.postJsonPinning = void 0;
|
|
4
|
+
const http_1 = require("./http");
|
|
5
|
+
const MAX_PINS = 256;
|
|
6
|
+
const pinsByApi = new WeakMap();
|
|
7
|
+
function pinsOf(api) {
|
|
8
|
+
let pins = pinsByApi.get(api);
|
|
9
|
+
if (!pins) {
|
|
10
|
+
pins = new Map();
|
|
11
|
+
pinsByApi.set(api, pins);
|
|
12
|
+
}
|
|
13
|
+
return pins;
|
|
14
|
+
}
|
|
15
|
+
function pinClient(api, keys, client) {
|
|
16
|
+
const pins = pinsOf(api);
|
|
17
|
+
for (const key of keys) {
|
|
18
|
+
if (!key)
|
|
19
|
+
continue;
|
|
20
|
+
pins.delete(key);
|
|
21
|
+
pins.set(key, client);
|
|
22
|
+
}
|
|
23
|
+
while (pins.size > MAX_PINS) {
|
|
24
|
+
const oldest = pins.keys().next().value;
|
|
25
|
+
if (oldest === undefined)
|
|
26
|
+
break;
|
|
27
|
+
pins.delete(oldest);
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
function pinnedClient(api, keys) {
|
|
31
|
+
const pins = pinsByApi.get(api);
|
|
32
|
+
if (!pins)
|
|
33
|
+
return undefined;
|
|
34
|
+
for (const key of keys) {
|
|
35
|
+
if (!key)
|
|
36
|
+
continue;
|
|
37
|
+
const client = pins.get(key);
|
|
38
|
+
if (client) {
|
|
39
|
+
pins.delete(key);
|
|
40
|
+
pins.set(key, client);
|
|
41
|
+
return client;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
return undefined;
|
|
45
|
+
}
|
|
46
|
+
function unpinClient(api, keys) {
|
|
47
|
+
const pins = pinsByApi.get(api);
|
|
48
|
+
if (!pins)
|
|
49
|
+
return;
|
|
50
|
+
for (const key of keys) {
|
|
51
|
+
if (key)
|
|
52
|
+
pins.delete(key);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
async function postJsonPinning(api, path, body, keysOf, opts) {
|
|
56
|
+
if (!api.postJsonWith) {
|
|
57
|
+
return api.postJson(path, body, opts);
|
|
58
|
+
}
|
|
59
|
+
const { result, client } = await api.postJsonWith(path, body, opts);
|
|
60
|
+
pinClient(api, keysOf(result), client);
|
|
61
|
+
return result;
|
|
62
|
+
}
|
|
63
|
+
exports.postJsonPinning = postJsonPinning;
|
|
64
|
+
async function postJsonPinned(api, keys, path, body, opts) {
|
|
65
|
+
const client = pinnedClient(api, keys) ?? api;
|
|
66
|
+
try {
|
|
67
|
+
if (!client.postJsonWith) {
|
|
68
|
+
return await client.postJson(path, body, opts);
|
|
69
|
+
}
|
|
70
|
+
const served = await client.postJsonWith(path, body, opts);
|
|
71
|
+
pinClient(api, keys, served.client);
|
|
72
|
+
return served.result;
|
|
73
|
+
}
|
|
74
|
+
catch (error) {
|
|
75
|
+
if (error instanceof http_1.HttpError && error.statusCode === 404) {
|
|
76
|
+
unpinClient(api, keys);
|
|
77
|
+
}
|
|
78
|
+
throw error;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
exports.postJsonPinned = postJsonPinned;
|
|
@@ -26,7 +26,15 @@ class HttpClientWithFallback {
|
|
|
26
26
|
return this.withFallback((client) => client.fetchJson(path, opts));
|
|
27
27
|
}
|
|
28
28
|
async postJson(path, body, opts) {
|
|
29
|
-
return
|
|
29
|
+
return (await this.postJsonWith(path, body, opts)).result;
|
|
30
|
+
}
|
|
31
|
+
// transform runs after the fallback loop: a deterministic parse error must not re-post to the next origin
|
|
32
|
+
async postJsonWith(path, body, opts) {
|
|
33
|
+
const served = await this.withFallback(async (client) => ({
|
|
34
|
+
result: await client.postJson(path, body),
|
|
35
|
+
client,
|
|
36
|
+
}));
|
|
37
|
+
return { result: opts?.transform ? opts.transform(served.result) : served.result, client: served.client };
|
|
30
38
|
}
|
|
31
39
|
async withFallback(fn) {
|
|
32
40
|
const order = this.getClientOrder();
|
|
@@ -333,13 +333,14 @@ function formatNumberHuman(n, showDollar = false, displayDecimals = 1) {
|
|
|
333
333
|
const isNegative = n < 0;
|
|
334
334
|
const absN = Math.abs(n);
|
|
335
335
|
const sign = showDollar ? "$\u200a" : "";
|
|
336
|
-
|
|
336
|
+
// Promote the suffix when the displayed value rounds to 1000 in the smaller unit.
|
|
337
|
+
if (Number((absN / 1000000).toFixed(displayDecimals)) >= 1000) {
|
|
337
338
|
return `${isNegative ? "-" : ""}${sign}${(absN / 1000000000).toFixed(displayDecimals)}b`;
|
|
338
339
|
}
|
|
339
|
-
if (absN >=
|
|
340
|
+
if (Number((absN / 1000).toFixed(displayDecimals)) >= 1000) {
|
|
340
341
|
return `${isNegative ? "-" : ""}${sign}${(absN / 1000000).toFixed(displayDecimals)}m`;
|
|
341
342
|
}
|
|
342
|
-
if (absN >= 1000) {
|
|
343
|
+
if (Number(absN.toFixed(displayDecimals)) >= 1000) {
|
|
343
344
|
return `${isNegative ? "-" : ""}${sign}${(absN / 1000).toFixed(displayDecimals)}k`;
|
|
344
345
|
}
|
|
345
346
|
return `${isNegative ? "-" : ""}${sign}${absN.toFixed(displayDecimals)}`;
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.executeExpressOrder = exports.signPreparedOrder = exports.fetchOrderStatus = exports.prepareCollateral = exports.prepareCancelOrder = exports.prepareEditOrder = exports.submitOrder = exports.prepareOrder = exports.isPrepareOrderError = exports.parsePrepareOrderError = void 0;
|
|
4
|
+
const chainPins_1 = require("../http/chainPins");
|
|
4
5
|
const http_1 = require("../http/http");
|
|
5
6
|
const api_1 = require("../markets/api");
|
|
6
7
|
const numbers_1 = require("../numbers");
|
|
@@ -177,36 +178,40 @@ function parsePrepareResponse(raw) {
|
|
|
177
178
|
validationWarnings: parseValidationWarnings(raw.validationWarnings),
|
|
178
179
|
};
|
|
179
180
|
}
|
|
181
|
+
// the express chain stays on the origin that served it: prepare and submit pin that origin by request id, submit and status reuse it
|
|
182
|
+
function chainKeys(prepared) {
|
|
183
|
+
return [prepared.requestId, prepared.idempotencyKey];
|
|
184
|
+
}
|
|
180
185
|
async function prepareOrder(ctx, request) {
|
|
181
|
-
return ctx.api
|
|
186
|
+
return (0, chainPins_1.postJsonPinning)(ctx.api, "/v1/orders/txns/prepare", request, chainKeys, {
|
|
182
187
|
transform: parsePrepareResponse,
|
|
183
188
|
});
|
|
184
189
|
}
|
|
185
190
|
exports.prepareOrder = prepareOrder;
|
|
186
191
|
async function submitOrder(ctx, request) {
|
|
187
|
-
return ctx.api.
|
|
192
|
+
return (0, chainPins_1.postJsonPinned)(ctx.api, [request.requestId, request.idempotencyKey], "/v1/orders/txns/submit", request);
|
|
188
193
|
}
|
|
189
194
|
exports.submitOrder = submitOrder;
|
|
190
195
|
async function prepareEditOrder(ctx, request) {
|
|
191
|
-
return ctx.api
|
|
196
|
+
return (0, chainPins_1.postJsonPinning)(ctx.api, "/v1/orders/txns/edit/prepare", request, chainKeys, {
|
|
192
197
|
transform: parsePrepareResponse,
|
|
193
198
|
});
|
|
194
199
|
}
|
|
195
200
|
exports.prepareEditOrder = prepareEditOrder;
|
|
196
201
|
async function prepareCancelOrder(ctx, request) {
|
|
197
|
-
return ctx.api
|
|
202
|
+
return (0, chainPins_1.postJsonPinning)(ctx.api, "/v1/orders/txns/cancel/prepare", request, chainKeys, {
|
|
198
203
|
transform: parsePrepareResponse,
|
|
199
204
|
});
|
|
200
205
|
}
|
|
201
206
|
exports.prepareCancelOrder = prepareCancelOrder;
|
|
202
207
|
async function prepareCollateral(ctx, request) {
|
|
203
|
-
return ctx.api
|
|
208
|
+
return (0, chainPins_1.postJsonPinning)(ctx.api, "/v1/orders/txns/collateral/prepare", request, chainKeys, {
|
|
204
209
|
transform: parsePrepareResponse,
|
|
205
210
|
});
|
|
206
211
|
}
|
|
207
212
|
exports.prepareCollateral = prepareCollateral;
|
|
208
213
|
async function fetchOrderStatus(ctx, request) {
|
|
209
|
-
return ctx.api.
|
|
214
|
+
return (0, chainPins_1.postJsonPinned)(ctx.api, [request.requestId, request.idempotencyKey], "/v1/orders/txns/status", request);
|
|
210
215
|
}
|
|
211
216
|
exports.fetchOrderStatus = fetchOrderStatus;
|
|
212
217
|
async function signPreparedOrder(prepared, signer, chainId, accountAddress) {
|
|
@@ -4,7 +4,7 @@ const API_URLS = {
|
|
|
4
4
|
[ARBITRUM]: "https://arbitrum.gmxapi.io",
|
|
5
5
|
[AVALANCHE]: "https://avalanche.gmxapi.io",
|
|
6
6
|
[AVALANCHE_FUJI]: undefined,
|
|
7
|
-
[ARBITRUM_SEPOLIA]: "https://
|
|
7
|
+
[ARBITRUM_SEPOLIA]: "https://arbitrum-sepolia-test.gmxapi.ai",
|
|
8
8
|
[MEGAETH]: "https://megaeth.gmxapi.io",
|
|
9
9
|
},
|
|
10
10
|
test: {
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { describe, expect, it } from "vitest";
|
|
2
2
|
import { BASIS_POINTS_DIVISOR_BIGINT, USD_DECIMALS } from "../../configs/factors";
|
|
3
|
-
import { applyFactor, basisPointsToFloat, bigintToNumber, BN_NEGATIVE_ONE, BN_ONE, BN_ZERO, expandDecimals, formatAmount, formatAmountHuman, formatBalanceAmount, formatBasisPoints, formatPriceImpactBps, formatFactor, formatPercentage, formatTokenAmount, formatUsdPrice, getBasisPoints, isUint256, MaxUint256, numberToBigint, parseUint256DecimalString, PERCENT_PRECISION_DECIMALS, PRECISION, PRECISION_DECIMALS, parseValue, removeTrailingZeros, trimZeroDecimals, roundWithDecimals, roundUpMagnitudeDivision, roundsToZero, toBigNumberWithDecimals, } from "../numbers";
|
|
3
|
+
import { applyFactor, basisPointsToFloat, bigintToNumber, BN_NEGATIVE_ONE, BN_ONE, BN_ZERO, expandDecimals, formatAmount, formatAmountHuman, formatBalanceAmount, formatBasisPoints, formatPriceImpactBps, formatFactor, formatNumberHuman, formatPercentage, formatTokenAmount, formatUsdPrice, getBasisPoints, isUint256, MaxUint256, numberToBigint, parseUint256DecimalString, PERCENT_PRECISION_DECIMALS, PRECISION, PRECISION_DECIMALS, parseValue, removeTrailingZeros, trimZeroDecimals, roundWithDecimals, roundUpMagnitudeDivision, roundsToZero, toBigNumberWithDecimals, } from "../numbers";
|
|
4
4
|
const ONE_USD = 1000000000000000000000000000000n;
|
|
5
5
|
describe("numbers utils", () => {
|
|
6
6
|
it("constants", () => {
|
|
@@ -257,7 +257,58 @@ describe("formatUsdPrice", () => {
|
|
|
257
257
|
expect(formatUsdPrice(ONE_USD / 10000000000n)).toBe("<\u00a0$\u200a0.000000001");
|
|
258
258
|
});
|
|
259
259
|
});
|
|
260
|
+
describe("formatNumberHuman", () => {
|
|
261
|
+
it.each([
|
|
262
|
+
[999.94, 1, "999.9"],
|
|
263
|
+
[999.96, 1, "1.0k"],
|
|
264
|
+
[1000, 1, "1.0k"],
|
|
265
|
+
[999940, 1, "999.9k"],
|
|
266
|
+
[999960, 1, "1.0m"],
|
|
267
|
+
[999996, 1, "1.0m"],
|
|
268
|
+
[1000000, 1, "1.0m"],
|
|
269
|
+
[999940000, 1, "999.9m"],
|
|
270
|
+
[999960000, 1, "1.0b"],
|
|
271
|
+
[1000000000, 1, "1.0b"],
|
|
272
|
+
[999.4, 0, "999"],
|
|
273
|
+
[999.6, 0, "1k"],
|
|
274
|
+
[999400, 0, "999k"],
|
|
275
|
+
[999600, 0, "1m"],
|
|
276
|
+
[999400000, 0, "999m"],
|
|
277
|
+
[999600000, 0, "1b"],
|
|
278
|
+
[999.994, 2, "999.99"],
|
|
279
|
+
[999.996, 2, "1.00k"],
|
|
280
|
+
[999994, 2, "999.99k"],
|
|
281
|
+
[999996, 2, "1.00m"],
|
|
282
|
+
[999994000, 2, "999.99m"],
|
|
283
|
+
[999996000, 2, "1.00b"],
|
|
284
|
+
])("formats %s at %s decimal places as %s", (value, displayDecimals, expected) => {
|
|
285
|
+
expect(formatNumberHuman(value, false, displayDecimals)).toBe(expected);
|
|
286
|
+
expect(formatNumberHuman(-value, false, displayDecimals)).toBe(`-${expected}`);
|
|
287
|
+
expect(formatNumberHuman(value, true, displayDecimals)).toBe(`$\u200a${expected}`);
|
|
288
|
+
expect(formatNumberHuman(-value, true, displayDecimals)).toBe(`-$\u200a${expected}`);
|
|
289
|
+
});
|
|
290
|
+
it("preserves zero and small values", () => {
|
|
291
|
+
expect(formatNumberHuman(0)).toBe("0.0");
|
|
292
|
+
expect(formatNumberHuman(0, true, 2)).toBe("$\u200a0.00");
|
|
293
|
+
expect(formatNumberHuman(0.04)).toBe("0.0");
|
|
294
|
+
expect(formatNumberHuman(-0.04)).toBe("-0.0");
|
|
295
|
+
});
|
|
296
|
+
});
|
|
260
297
|
describe("formatAmountHuman", () => {
|
|
298
|
+
it.each([
|
|
299
|
+
["999.94", "$\u200a999.9"],
|
|
300
|
+
["999.96", "$\u200a1.0k"],
|
|
301
|
+
["999996", "$\u200a1.0m"],
|
|
302
|
+
["999996000", "$\u200a1.0b"],
|
|
303
|
+
])("formats the USD amount %s as %s", (value, expected) => {
|
|
304
|
+
const amount = toBigNumberWithDecimals(value, USD_DECIMALS);
|
|
305
|
+
expect(formatAmountHuman(amount, USD_DECIMALS, true, 1)).toBe(expected);
|
|
306
|
+
expect(formatAmountHuman(-amount, USD_DECIMALS, true, 1)).toBe(`-${expected}`);
|
|
307
|
+
});
|
|
308
|
+
it("preserves loading and zero values", () => {
|
|
309
|
+
expect(formatAmountHuman(undefined, USD_DECIMALS, true)).toBe("...");
|
|
310
|
+
expect(formatAmountHuman(0n, USD_DECIMALS, true)).toBe("$\u200a0.0");
|
|
311
|
+
});
|
|
261
312
|
it("positive", () => {
|
|
262
313
|
expect(formatAmountHuman(ONE_USD, USD_DECIMALS)).toBe("1.0");
|
|
263
314
|
expect(formatAmountHuman(ONE_USD * 1000n, USD_DECIMALS)).toBe("1.0k");
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { postJsonPinned, postJsonPinning } from "../http/chainPins";
|
|
1
2
|
function parseDepositPrepareResponse(raw) {
|
|
2
3
|
return {
|
|
3
4
|
payloadType: "transaction",
|
|
@@ -52,12 +53,10 @@ export async function executeCrossChainDeposit(ctx, signer, request) {
|
|
|
52
53
|
};
|
|
53
54
|
}
|
|
54
55
|
export async function prepareCrossChainWithdraw(ctx, request) {
|
|
55
|
-
return ctx.api
|
|
56
|
-
transform: parseWithdrawPrepareResponse,
|
|
57
|
-
});
|
|
56
|
+
return postJsonPinning(ctx.api, "/v1/gmx-account/withdraw/cross-chain/prepare", request, (prepared) => [prepared.requestId], { transform: parseWithdrawPrepareResponse });
|
|
58
57
|
}
|
|
59
58
|
export async function submitCrossChainWithdraw(ctx, request) {
|
|
60
|
-
return ctx.api.
|
|
59
|
+
return postJsonPinned(ctx.api, [request.requestId], "/v1/gmx-account/withdraw/cross-chain/submit", request);
|
|
61
60
|
}
|
|
62
61
|
export async function signCrossChainWithdrawPrepared(prepared, signer) {
|
|
63
62
|
const td = prepared.payload.typedData;
|
|
@@ -78,7 +77,5 @@ export async function executeCrossChainWithdraw(ctx, signer, request) {
|
|
|
78
77
|
});
|
|
79
78
|
}
|
|
80
79
|
export async function getCrossChainWithdrawStatus(ctx, requestId) {
|
|
81
|
-
return ctx.api
|
|
82
|
-
requestId,
|
|
83
|
-
});
|
|
80
|
+
return postJsonPinned(ctx.api, [requestId], "/v1/gmx-account/withdraw/cross-chain/status", { requestId });
|
|
84
81
|
}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
|
2
|
+
import { HttpClientWithFallback } from "../httpFallback";
|
|
3
|
+
import { fetchOrderStatus, prepareOrder, submitOrder } from "../../orderTransactions/api";
|
|
4
|
+
const fetchMock = vi.hoisted(() => vi.fn());
|
|
5
|
+
vi.mock("cross-fetch", () => ({ default: fetchMock }));
|
|
6
|
+
const PREPARE = "/v1/orders/txns/prepare";
|
|
7
|
+
const SUBMIT = "/v1/orders/txns/submit";
|
|
8
|
+
const STATUS = "/v1/orders/txns/status";
|
|
9
|
+
function jsonResponse(status, body) {
|
|
10
|
+
return new Response(JSON.stringify(body), { status, headers: { "Content-Type": "application/json" } });
|
|
11
|
+
}
|
|
12
|
+
describe("express chain pinning", () => {
|
|
13
|
+
const calls = [];
|
|
14
|
+
const failingOnA = new Set();
|
|
15
|
+
const notFoundOnce = new Set();
|
|
16
|
+
beforeEach(() => {
|
|
17
|
+
calls.length = 0;
|
|
18
|
+
failingOnA.clear();
|
|
19
|
+
notFoundOnce.clear();
|
|
20
|
+
vi.spyOn(Math, "random").mockReturnValue(0);
|
|
21
|
+
fetchMock.mockImplementation(async (input) => {
|
|
22
|
+
const url = new URL(input);
|
|
23
|
+
calls.push(`${url.origin}${url.pathname}`);
|
|
24
|
+
if (url.origin === "http://a" && failingOnA.has(url.pathname)) {
|
|
25
|
+
return jsonResponse(503, { message: "busy" });
|
|
26
|
+
}
|
|
27
|
+
if (notFoundOnce.delete(url.pathname)) {
|
|
28
|
+
return jsonResponse(404, { message: "not found" });
|
|
29
|
+
}
|
|
30
|
+
if (url.pathname === PREPARE) {
|
|
31
|
+
return jsonResponse(200, { requestId: "req-1", payloadType: "typed-data", mode: "express", payload: {} });
|
|
32
|
+
}
|
|
33
|
+
if (url.pathname === SUBMIT) {
|
|
34
|
+
return jsonResponse(200, { requestId: "req-1", status: "relay_accepted" });
|
|
35
|
+
}
|
|
36
|
+
if (url.pathname === STATUS) {
|
|
37
|
+
return jsonResponse(200, { requestId: "req-1", status: "created" });
|
|
38
|
+
}
|
|
39
|
+
return jsonResponse(404, { message: "not found" });
|
|
40
|
+
});
|
|
41
|
+
});
|
|
42
|
+
afterEach(() => {
|
|
43
|
+
vi.restoreAllMocks();
|
|
44
|
+
});
|
|
45
|
+
function newCtx() {
|
|
46
|
+
return { api: new HttpClientWithFallback(["http://a", "http://b"]) };
|
|
47
|
+
}
|
|
48
|
+
it("sends submit and status to the origin that served prepare", async () => {
|
|
49
|
+
failingOnA.add(PREPARE);
|
|
50
|
+
const ctx = newCtx();
|
|
51
|
+
const prepared = await prepareOrder(ctx, { kind: "increase", orderType: "market", mode: "express", from: "0x1" });
|
|
52
|
+
await submitOrder(ctx, { mode: "express", requestId: prepared.requestId });
|
|
53
|
+
await fetchOrderStatus(ctx, { requestId: prepared.requestId });
|
|
54
|
+
expect(calls).toEqual([`http://a${PREPARE}`, `http://b${PREPARE}`, `http://b${SUBMIT}`, `http://b${STATUS}`]);
|
|
55
|
+
});
|
|
56
|
+
it("pins status to the origin that served an unpinned submit", async () => {
|
|
57
|
+
failingOnA.add(SUBMIT);
|
|
58
|
+
const ctx = newCtx();
|
|
59
|
+
await submitOrder(ctx, { mode: "express", requestId: "req-1" });
|
|
60
|
+
await fetchOrderStatus(ctx, { requestId: "req-1" });
|
|
61
|
+
expect(calls).toEqual([`http://a${SUBMIT}`, `http://b${SUBMIT}`, `http://b${STATUS}`]);
|
|
62
|
+
});
|
|
63
|
+
it("drops the pin when the pinned origin answers 404", async () => {
|
|
64
|
+
failingOnA.add(PREPARE);
|
|
65
|
+
const ctx = newCtx();
|
|
66
|
+
const prepared = await prepareOrder(ctx, { kind: "increase", orderType: "market", mode: "express", from: "0x1" });
|
|
67
|
+
notFoundOnce.add(SUBMIT);
|
|
68
|
+
await expect(submitOrder(ctx, { mode: "express", requestId: prepared.requestId })).rejects.toMatchObject({
|
|
69
|
+
statusCode: 404,
|
|
70
|
+
});
|
|
71
|
+
await fetchOrderStatus(ctx, { requestId: prepared.requestId });
|
|
72
|
+
expect(calls).toEqual([`http://a${PREPARE}`, `http://b${PREPARE}`, `http://b${SUBMIT}`, `http://a${STATUS}`]);
|
|
73
|
+
});
|
|
74
|
+
});
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { HttpError } from "./http";
|
|
2
|
+
const MAX_PINS = 256;
|
|
3
|
+
const pinsByApi = new WeakMap();
|
|
4
|
+
function pinsOf(api) {
|
|
5
|
+
let pins = pinsByApi.get(api);
|
|
6
|
+
if (!pins) {
|
|
7
|
+
pins = new Map();
|
|
8
|
+
pinsByApi.set(api, pins);
|
|
9
|
+
}
|
|
10
|
+
return pins;
|
|
11
|
+
}
|
|
12
|
+
function pinClient(api, keys, client) {
|
|
13
|
+
const pins = pinsOf(api);
|
|
14
|
+
for (const key of keys) {
|
|
15
|
+
if (!key)
|
|
16
|
+
continue;
|
|
17
|
+
pins.delete(key);
|
|
18
|
+
pins.set(key, client);
|
|
19
|
+
}
|
|
20
|
+
while (pins.size > MAX_PINS) {
|
|
21
|
+
const oldest = pins.keys().next().value;
|
|
22
|
+
if (oldest === undefined)
|
|
23
|
+
break;
|
|
24
|
+
pins.delete(oldest);
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
function pinnedClient(api, keys) {
|
|
28
|
+
const pins = pinsByApi.get(api);
|
|
29
|
+
if (!pins)
|
|
30
|
+
return undefined;
|
|
31
|
+
for (const key of keys) {
|
|
32
|
+
if (!key)
|
|
33
|
+
continue;
|
|
34
|
+
const client = pins.get(key);
|
|
35
|
+
if (client) {
|
|
36
|
+
pins.delete(key);
|
|
37
|
+
pins.set(key, client);
|
|
38
|
+
return client;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
return undefined;
|
|
42
|
+
}
|
|
43
|
+
function unpinClient(api, keys) {
|
|
44
|
+
const pins = pinsByApi.get(api);
|
|
45
|
+
if (!pins)
|
|
46
|
+
return;
|
|
47
|
+
for (const key of keys) {
|
|
48
|
+
if (key)
|
|
49
|
+
pins.delete(key);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
export async function postJsonPinning(api, path, body, keysOf, opts) {
|
|
53
|
+
if (!api.postJsonWith) {
|
|
54
|
+
return api.postJson(path, body, opts);
|
|
55
|
+
}
|
|
56
|
+
const { result, client } = await api.postJsonWith(path, body, opts);
|
|
57
|
+
pinClient(api, keysOf(result), client);
|
|
58
|
+
return result;
|
|
59
|
+
}
|
|
60
|
+
export async function postJsonPinned(api, keys, path, body, opts) {
|
|
61
|
+
const client = pinnedClient(api, keys) ?? api;
|
|
62
|
+
try {
|
|
63
|
+
if (!client.postJsonWith) {
|
|
64
|
+
return await client.postJson(path, body, opts);
|
|
65
|
+
}
|
|
66
|
+
const served = await client.postJsonWith(path, body, opts);
|
|
67
|
+
pinClient(api, keys, served.client);
|
|
68
|
+
return served.result;
|
|
69
|
+
}
|
|
70
|
+
catch (error) {
|
|
71
|
+
if (error instanceof HttpError && error.statusCode === 404) {
|
|
72
|
+
unpinClient(api, keys);
|
|
73
|
+
}
|
|
74
|
+
throw error;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
@@ -23,7 +23,15 @@ export class HttpClientWithFallback {
|
|
|
23
23
|
return this.withFallback((client) => client.fetchJson(path, opts));
|
|
24
24
|
}
|
|
25
25
|
async postJson(path, body, opts) {
|
|
26
|
-
return
|
|
26
|
+
return (await this.postJsonWith(path, body, opts)).result;
|
|
27
|
+
}
|
|
28
|
+
// transform runs after the fallback loop: a deterministic parse error must not re-post to the next origin
|
|
29
|
+
async postJsonWith(path, body, opts) {
|
|
30
|
+
const served = await this.withFallback(async (client) => ({
|
|
31
|
+
result: await client.postJson(path, body),
|
|
32
|
+
client,
|
|
33
|
+
}));
|
|
34
|
+
return { result: opts?.transform ? opts.transform(served.result) : served.result, client: served.client };
|
|
27
35
|
}
|
|
28
36
|
async withFallback(fn) {
|
|
29
37
|
const order = this.getClientOrder();
|