@stxapp/stx-typescript 0.9.0 → 0.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +37 -0
- package/README.md +2 -0
- package/dist/{chunk-46XK6VDD.js → chunk-2PYJI3JS.js} +430 -159
- package/dist/chunk-2PYJI3JS.js.map +1 -0
- package/dist/{chunk-R77AZ5UH.cjs → chunk-BSX65XEA.cjs} +459 -188
- package/dist/chunk-BSX65XEA.cjs.map +1 -0
- package/dist/{client-B-MMKiRt.d.ts → client-DxY8eJ58.d.cts} +252 -156
- package/dist/{client-B-MMKiRt.d.cts → client-DxY8eJ58.d.ts} +252 -156
- package/dist/index.cjs +8 -2
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +11 -5
- package/dist/oauth.cjs +30 -30
- package/dist/oauth.d.cts +2 -2
- package/dist/oauth.d.ts +2 -2
- package/dist/oauth.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-46XK6VDD.js.map +0 -1
- package/dist/chunk-R77AZ5UH.cjs.map +0 -1
|
@@ -1,29 +1,4 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } var _class; var _class2; var _class3; var _class4; var _class5; var _class6;// src/
|
|
2
|
-
var IP_NOT_ALLOWED = /from this IP address (\S+?) is disallowed/i;
|
|
3
|
-
function geoRejection(message) {
|
|
4
|
-
const ip = IP_NOT_ALLOWED.exec(message);
|
|
5
|
-
if (ip) return { reason: "ip_not_allowed", ipAddress: ip[1] };
|
|
6
|
-
if (/geo location check was not done by this user|unknown user in geocomply/i.test(message)) {
|
|
7
|
-
return { reason: "packet_other_user" };
|
|
8
|
-
}
|
|
9
|
-
if (/IP address doesn't match geo location/i.test(message)) {
|
|
10
|
-
return { reason: "packet_ip_mismatch" };
|
|
11
|
-
}
|
|
12
|
-
if (/geo ?location package is invalid|geocomply location response|unable to find expected tag/i.test(message)) {
|
|
13
|
-
return { reason: "packet_invalid" };
|
|
14
|
-
}
|
|
15
|
-
if (/invalid geo ?location|geo[- ]?(location|fenc)/i.test(message)) {
|
|
16
|
-
return { reason: "location_not_allowed" };
|
|
17
|
-
}
|
|
18
|
-
return void 0;
|
|
19
|
-
}
|
|
20
|
-
async function resolveGeoLocation(provider) {
|
|
21
|
-
if (provider === void 0 || provider === null) return void 0;
|
|
22
|
-
const value = typeof provider === "function" ? await provider() : provider;
|
|
23
|
-
return value === null || value === void 0 || value === "" ? void 0 : value;
|
|
24
|
-
}
|
|
25
|
-
|
|
26
|
-
// src/exceptions.ts
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } async function _asyncNullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return await rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } async function _asyncOptionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = await fn(value); } else if (op === 'call' || op === 'optionalCall') { value = await fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } var _class; var _class2; var _class3; var _class4; var _class5; var _class6;// src/exceptions.ts
|
|
27
2
|
var STXException = class extends Error {
|
|
28
3
|
|
|
29
4
|
|
|
@@ -68,24 +43,46 @@ var STXTermsRequiredException = class extends STXForbiddenException {
|
|
|
68
43
|
};
|
|
69
44
|
var STXIPNotAllowedException = class extends STXForbiddenException {
|
|
70
45
|
};
|
|
46
|
+
var STXBlockedException = class extends STXForbiddenException {
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
constructor(message, opts = {}) {
|
|
50
|
+
super(message, opts);
|
|
51
|
+
this.reason = _nullishCoalesce(opts.reason, () => ( "blocked"));
|
|
52
|
+
this.reference = opts.reference;
|
|
53
|
+
}
|
|
54
|
+
};
|
|
55
|
+
var STXRestrictedJurisdictionException = class extends STXBlockedException {
|
|
56
|
+
};
|
|
57
|
+
var STXUnusualNetworkException = class extends STXBlockedException {
|
|
58
|
+
};
|
|
71
59
|
var STXNotFoundException = class extends STXAPIException {
|
|
72
60
|
};
|
|
73
61
|
var STXRejectedException = class extends STXAPIException {
|
|
74
62
|
};
|
|
75
|
-
var
|
|
63
|
+
var STXFillModeNotAllowedException = class extends STXRejectedException {
|
|
76
64
|
|
|
65
|
+
constructor(message, opts) {
|
|
66
|
+
super(message, opts);
|
|
67
|
+
this.fillMode = opts.fillMode;
|
|
68
|
+
}
|
|
69
|
+
};
|
|
70
|
+
var STXPostOnlyWouldMatchException = class extends STXRejectedException {
|
|
77
71
|
|
|
78
|
-
|
|
72
|
+
|
|
73
|
+
constructor(message, opts) {
|
|
79
74
|
super(message, opts);
|
|
80
|
-
this.reason =
|
|
81
|
-
this.
|
|
75
|
+
this.reason = opts.reason;
|
|
76
|
+
this.order = opts.order;
|
|
82
77
|
}
|
|
83
78
|
};
|
|
84
79
|
var STXRateLimitException = class extends STXAPIException {
|
|
85
80
|
|
|
81
|
+
|
|
86
82
|
constructor(message, opts = {}) {
|
|
87
83
|
super(message, opts);
|
|
88
84
|
this.retryAfter = opts.retryAfter;
|
|
85
|
+
this.reference = opts.reference;
|
|
89
86
|
}
|
|
90
87
|
};
|
|
91
88
|
var STXServerException = class extends STXAPIException {
|
|
@@ -125,21 +122,28 @@ var FEATURE_PHRASES = {
|
|
|
125
122
|
market_types: "Market types are",
|
|
126
123
|
event_players: "Event players are",
|
|
127
124
|
leaderboard: "The leaderboard is",
|
|
128
|
-
|
|
125
|
+
loyalty: "The loyalty program is",
|
|
126
|
+
combos: "Combos are",
|
|
127
|
+
"orders.post_only": "Post-only orders are",
|
|
128
|
+
"orders.fill_or_kill": "Fill-or-kill orders are"
|
|
129
129
|
};
|
|
130
|
-
function notAvailableMessage(feature, host) {
|
|
130
|
+
function notAvailableMessage(feature, host, apiVersion) {
|
|
131
131
|
const phrase = feature.startsWith("scope:") ? `The ${feature.slice("scope:".length)} scope is` : _nullishCoalesce(FEATURE_PHRASES[feature], () => ( `${feature} is`));
|
|
132
|
-
|
|
132
|
+
const where = apiVersion ? `${host} (version ${apiVersion})` : host;
|
|
133
|
+
return `${phrase} not available on ${where} yet.`;
|
|
133
134
|
}
|
|
134
135
|
var STXNotAvailableException = class _STXNotAvailableException extends STXAPIException {
|
|
135
136
|
/** The feature id, e.g. `"combos"`. */
|
|
136
137
|
|
|
137
138
|
/** The exchange host that lacks it, e.g. `"demo.stxapp.ca"`. */
|
|
138
139
|
|
|
140
|
+
/** The exchange build, e.g. `"3.4.24"`, when known. */
|
|
141
|
+
|
|
139
142
|
constructor(feature, host, opts = {}) {
|
|
140
|
-
super(_nullishCoalesce(opts.message, () => ( notAvailableMessage(feature, host))), opts);
|
|
143
|
+
super(_nullishCoalesce(opts.message, () => ( notAvailableMessage(feature, host, opts.apiVersion))), opts);
|
|
141
144
|
this.feature = feature;
|
|
142
145
|
this.host = host;
|
|
146
|
+
this.apiVersion = _nullishCoalesce(opts.apiVersion, () => ( void 0));
|
|
143
147
|
markNotAvailable(this);
|
|
144
148
|
}
|
|
145
149
|
// `this` is the class on the right of `instanceof`: a subclass keeps the
|
|
@@ -205,6 +209,18 @@ function errorForStatus(statusCode, body, opts) {
|
|
|
205
209
|
message = `HTTP ${statusCode}`;
|
|
206
210
|
}
|
|
207
211
|
const base = { statusCode, body, method: opts.method, path: opts.path };
|
|
212
|
+
const edge = edgeBlock(statusCode, body, opts.stxError, opts.cfId);
|
|
213
|
+
if (edge) {
|
|
214
|
+
if (statusCode === 429) {
|
|
215
|
+
return new STXRateLimitException(edge.message, {
|
|
216
|
+
...base,
|
|
217
|
+
retryAfter: parseRetryAfter(opts.retryAfter),
|
|
218
|
+
reference: edge.reference
|
|
219
|
+
});
|
|
220
|
+
}
|
|
221
|
+
const cls = edge.reason === "restricted_jurisdiction" ? STXRestrictedJurisdictionException : edge.reason === "unusual_network" ? STXUnusualNetworkException : STXBlockedException;
|
|
222
|
+
return new cls(edge.message, { ...base, reason: edge.reason, reference: edge.reference });
|
|
223
|
+
}
|
|
208
224
|
switch (statusCode) {
|
|
209
225
|
case 400:
|
|
210
226
|
return new STXValidationException(message, base);
|
|
@@ -231,20 +247,44 @@ function errorForStatus(statusCode, body, opts) {
|
|
|
231
247
|
}
|
|
232
248
|
case 404:
|
|
233
249
|
return new STXNotFoundException(message, base);
|
|
234
|
-
case 422:
|
|
235
|
-
|
|
236
|
-
return geo ? new STXGeoLocationException(message, geo, base) : new STXRejectedException(message, base);
|
|
237
|
-
}
|
|
250
|
+
case 422:
|
|
251
|
+
return new STXRejectedException(message, base);
|
|
238
252
|
case 429:
|
|
239
253
|
return new STXRateLimitException(message, { ...base, retryAfter: parseRetryAfter(opts.retryAfter) });
|
|
240
254
|
default:
|
|
241
255
|
return statusCode >= 500 ? new STXServerException(message, base) : new STXAPIException(message, base);
|
|
242
256
|
}
|
|
243
257
|
}
|
|
258
|
+
var NO_USER_AGENT_HINT = "Request blocked (HTTP 403) before it reached the exchange. Every request needs a User-Agent header; if you replaced or removed the SDK's, set one that names your application. If it persists, contact STX support.";
|
|
259
|
+
var EDGE_REASONS = {
|
|
260
|
+
403: ["restricted_jurisdiction", "unusual_network"],
|
|
261
|
+
429: ["rate_limited"]
|
|
262
|
+
};
|
|
263
|
+
var REFERENCE_PLACEHOLDER = "x-amz-cf-id response header";
|
|
264
|
+
function edgeBlock(status, body, stxError, cfId) {
|
|
265
|
+
const reasons = EDGE_REASONS[status];
|
|
266
|
+
if (!reasons || stxError) return void 0;
|
|
267
|
+
let reference = cfId || void 0;
|
|
268
|
+
if (body && typeof body === "object") {
|
|
269
|
+
const fields = body;
|
|
270
|
+
if (typeof fields.error !== "string" || !reasons.includes(fields.error)) return void 0;
|
|
271
|
+
if (reference === void 0 && typeof fields.reference === "string" && fields.reference) {
|
|
272
|
+
reference = fields.reference === REFERENCE_PLACEHOLDER ? void 0 : fields.reference;
|
|
273
|
+
}
|
|
274
|
+
return {
|
|
275
|
+
reason: fields.error,
|
|
276
|
+
message: typeof fields.message === "string" && fields.message ? fields.message : fields.error,
|
|
277
|
+
reference
|
|
278
|
+
};
|
|
279
|
+
}
|
|
280
|
+
return status === 403 ? { reason: "blocked", message: NO_USER_AGENT_HINT, reference } : void 0;
|
|
281
|
+
}
|
|
244
282
|
function parseRetryAfter(value) {
|
|
245
283
|
if (value === null || value === void 0 || value.trim() === "") return void 0;
|
|
246
284
|
const n = Number(value);
|
|
247
|
-
|
|
285
|
+
if (Number.isFinite(n)) return Math.max(0, n);
|
|
286
|
+
const at = Date.parse(value);
|
|
287
|
+
return Number.isNaN(at) ? void 0 : Math.max(0, (at - Date.now()) / 1e3);
|
|
248
288
|
}
|
|
249
289
|
function bearerError(header) {
|
|
250
290
|
if (!header || !/^\s*Bearer\b/i.test(header)) return void 0;
|
|
@@ -270,8 +310,23 @@ var FEATURES = [
|
|
|
270
310
|
"market_types",
|
|
271
311
|
"event_players",
|
|
272
312
|
"leaderboard",
|
|
273
|
-
"
|
|
313
|
+
"loyalty",
|
|
314
|
+
"combos",
|
|
315
|
+
"orders.post_only",
|
|
316
|
+
"orders.fill_or_kill"
|
|
274
317
|
];
|
|
318
|
+
var API_FEATURES = {
|
|
319
|
+
"orders.post_only": "order_post_only",
|
|
320
|
+
"orders.fill_or_kill": "order_fill_or_kill"
|
|
321
|
+
};
|
|
322
|
+
function apiVersionFrom(body) {
|
|
323
|
+
const version = _optionalChain([body, 'optionalAccess', _5 => _5.api_version]);
|
|
324
|
+
const features = _optionalChain([body, 'optionalAccess', _6 => _6.features]);
|
|
325
|
+
return {
|
|
326
|
+
apiVersion: typeof version === "string" ? version : null,
|
|
327
|
+
features: Array.isArray(features) ? features.filter((f) => typeof f === "string") : null
|
|
328
|
+
};
|
|
329
|
+
}
|
|
275
330
|
var MEMBER_SCOPES = [
|
|
276
331
|
"profile.read",
|
|
277
332
|
"balance.read",
|
|
@@ -351,15 +406,18 @@ function oauthMetadataFrom(answer) {
|
|
|
351
406
|
}
|
|
352
407
|
async function discoverCapabilities(probes) {
|
|
353
408
|
const swallow = (p) => p ? p.catch(() => null) : Promise.resolve(null);
|
|
354
|
-
const [version, discovery, types, players, board, combos] = await Promise.all([
|
|
409
|
+
const [version, discovery, types, players, board, loyalty, combos] = await Promise.all([
|
|
355
410
|
swallow(probes.get("/api_version")),
|
|
356
411
|
swallow(probes.get("/.well-known/oauth-authorization-server")),
|
|
357
412
|
swallow(probes.signedGet("/api/v1/types")),
|
|
358
413
|
swallow(probes.signedGet(`/api/v1/events/${NOBODY}/players`)),
|
|
359
414
|
swallow(probes.signedGet("/api/v1/leaderboard?limit=1")),
|
|
415
|
+
swallow(probes.signedGet("/api/v1/portfolio/loyalty?limit=1")),
|
|
360
416
|
swallow(probes.joinReason(`rfq:${NOBODY}`))
|
|
361
417
|
]);
|
|
362
|
-
const
|
|
418
|
+
const info = version ? apiVersionFrom(version.status === 200 ? json(version) : null) : null;
|
|
419
|
+
const apiVersion = _optionalChain([info, 'optionalAccess', _7 => _7.apiVersion]);
|
|
420
|
+
const listed = (name) => version === null ? null : version.status === 200 || version.status === 404 || version.status === 403 && json(version) === null ? !!_optionalChain([info, 'optionalAccess', _8 => _8.features, 'optionalAccess', _9 => _9.includes, 'call', _10 => _10(name)]) : null;
|
|
363
421
|
const meta = oauthMetadataFrom(discovery);
|
|
364
422
|
const scopes = meta ? strings(meta.scopes_supported) : [];
|
|
365
423
|
const grants = meta ? strings(meta.grant_types_supported) : [];
|
|
@@ -379,7 +437,11 @@ async function discoverCapabilities(probes) {
|
|
|
379
437
|
event_players: players === null ? null : missingRoute(players) ? false : players.status === 404 || players.status < 300 ? true : null,
|
|
380
438
|
// Switched off answers 404 too ("Leaderboard is not enabled").
|
|
381
439
|
leaderboard: board === null ? null : board.status >= 200 && board.status < 300 ? true : board.status === 404 ? false : null,
|
|
382
|
-
|
|
440
|
+
// Switched off answers 404 ("Loyalty program is not enabled").
|
|
441
|
+
loyalty: loyalty === null ? null : loyalty.status >= 200 && loyalty.status < 300 ? true : loyalty.status === 404 ? false : null,
|
|
442
|
+
combos: combos === null ? null : combos !== "unmatched topic",
|
|
443
|
+
"orders.post_only": listed(API_FEATURES["orders.post_only"]),
|
|
444
|
+
"orders.fill_or_kill": listed(API_FEATURES["orders.fill_or_kill"])
|
|
383
445
|
};
|
|
384
446
|
return new Capabilities({
|
|
385
447
|
host: probes.host,
|
|
@@ -512,7 +574,7 @@ var OPERATIONS = {
|
|
|
512
574
|
account_market_stats_get: {
|
|
513
575
|
method: "GET",
|
|
514
576
|
path: "/api/v1/account/market_stats",
|
|
515
|
-
query: ["market_ids", "event_ids", "exclude_zero_settlements", "from_time", "to_time", "sports", "competitions", "limit", "cursor"],
|
|
577
|
+
query: ["market_ids", "event_ids", "exclude_zero_settlements", "unsettled_only", "from_time", "to_time", "sports", "competitions", "limit", "cursor"],
|
|
516
578
|
pathParams: [],
|
|
517
579
|
hasBody: false,
|
|
518
580
|
responseKey: "market_stats",
|
|
@@ -948,6 +1010,9 @@ var RetryPolicy = class {
|
|
|
948
1010
|
shouldRetry(exc, attempt, idempotent) {
|
|
949
1011
|
if (attempt >= this.maxAttempts) return false;
|
|
950
1012
|
if (!this.retryableExceptions.some((cls) => exc instanceof cls)) return false;
|
|
1013
|
+
if (exc instanceof STXRateLimitException && exc.retryAfter !== void 0 && exc.retryAfter * 1e3 > this.maxBackoffMs) {
|
|
1014
|
+
return false;
|
|
1015
|
+
}
|
|
951
1016
|
return idempotent || exc instanceof STXRateLimitException;
|
|
952
1017
|
}
|
|
953
1018
|
/** Milliseconds to wait after attempt `attempt` (1-based) failed. */
|
|
@@ -1035,7 +1100,7 @@ function readProfile(profileName, path) {
|
|
|
1035
1100
|
}
|
|
1036
1101
|
function processEnv() {
|
|
1037
1102
|
const p = globalThis.process;
|
|
1038
|
-
return _nullishCoalesce(_optionalChain([p, 'optionalAccess',
|
|
1103
|
+
return _nullishCoalesce(_optionalChain([p, 'optionalAccess', _11 => _11.env]), () => ( {}));
|
|
1039
1104
|
}
|
|
1040
1105
|
function resolveSettings(input = {}) {
|
|
1041
1106
|
const environ = _nullishCoalesce(input.environ, () => ( processEnv()));
|
|
@@ -1209,7 +1274,7 @@ function credentialsFromSettings(keyId, privateKey, signer) {
|
|
|
1209
1274
|
}
|
|
1210
1275
|
|
|
1211
1276
|
// src/version.ts
|
|
1212
|
-
var VERSION = "0.
|
|
1277
|
+
var VERSION = "0.11.0";
|
|
1213
1278
|
var USER_AGENT = `stx-typescript/${VERSION}`;
|
|
1214
1279
|
var ASYNC_DISPOSE = _nullishCoalesce(Symbol.asyncDispose, () => ( /* @__PURE__ */ Symbol.for("Symbol.asyncDispose")));
|
|
1215
1280
|
|
|
@@ -1341,7 +1406,7 @@ var AccountView = (_class3 = class {
|
|
|
1341
1406
|
case "all_orders":
|
|
1342
1407
|
this.seeds.orders = (_nullishCoalesce(this.seeds.orders, () => ( 0))) + 1;
|
|
1343
1408
|
this.#orders.clear();
|
|
1344
|
-
for (const o of _nullishCoalesce(_optionalChain([payload, 'optionalAccess',
|
|
1409
|
+
for (const o of _nullishCoalesce(_optionalChain([payload, 'optionalAccess', _12 => _12.orders]), () => ( []))) this.#upsertOrder(o);
|
|
1345
1410
|
return change("orders", true);
|
|
1346
1411
|
case "new_open_order":
|
|
1347
1412
|
this.#upsertOrder(payload);
|
|
@@ -1349,7 +1414,7 @@ var AccountView = (_class3 = class {
|
|
|
1349
1414
|
case "all_trades":
|
|
1350
1415
|
this.seeds.fills = (_nullishCoalesce(this.seeds.fills, () => ( 0))) + 1;
|
|
1351
1416
|
this.#fills.clear();
|
|
1352
|
-
for (const t of _nullishCoalesce(_optionalChain([payload, 'optionalAccess',
|
|
1417
|
+
for (const t of _nullishCoalesce(_optionalChain([payload, 'optionalAccess', _13 => _13.trades]), () => ( []))) this.#upsertFill(t);
|
|
1353
1418
|
return change("fills", true);
|
|
1354
1419
|
case "trade":
|
|
1355
1420
|
this.#upsertFill(payload);
|
|
@@ -1357,22 +1422,22 @@ var AccountView = (_class3 = class {
|
|
|
1357
1422
|
case "all_positions":
|
|
1358
1423
|
this.seeds.positions = (_nullishCoalesce(this.seeds.positions, () => ( 0))) + 1;
|
|
1359
1424
|
this.#positions.clear();
|
|
1360
|
-
for (const p of _nullishCoalesce(_optionalChain([payload, 'optionalAccess',
|
|
1425
|
+
for (const p of _nullishCoalesce(_optionalChain([payload, 'optionalAccess', _14 => _14.positions]), () => ( []))) this.#upsertPosition(p);
|
|
1361
1426
|
return change("positions", true);
|
|
1362
1427
|
case "updated_positions":
|
|
1363
|
-
for (const p of _nullishCoalesce(_optionalChain([payload, 'optionalAccess',
|
|
1428
|
+
for (const p of _nullishCoalesce(_optionalChain([payload, 'optionalAccess', _15 => _15.positions]), () => ( []))) this.#upsertPosition(p);
|
|
1364
1429
|
return change("positions", false);
|
|
1365
1430
|
default:
|
|
1366
1431
|
return void 0;
|
|
1367
1432
|
}
|
|
1368
1433
|
}
|
|
1369
1434
|
#upsertOrder(order) {
|
|
1370
|
-
if (!_optionalChain([order, 'optionalAccess',
|
|
1435
|
+
if (!_optionalChain([order, 'optionalAccess', _16 => _16.id])) return;
|
|
1371
1436
|
if (TERMINAL_ORDER_STATUSES.has(String(order.status))) this.#orders.delete(order.id);
|
|
1372
1437
|
else this.#orders.set(order.id, order);
|
|
1373
1438
|
}
|
|
1374
1439
|
#upsertFill(fill) {
|
|
1375
|
-
if (!_optionalChain([fill, 'optionalAccess',
|
|
1440
|
+
if (!_optionalChain([fill, 'optionalAccess', _17 => _17.id])) return;
|
|
1376
1441
|
this.#fills.delete(fill.id);
|
|
1377
1442
|
this.#fills.set(fill.id, fill);
|
|
1378
1443
|
if (this.#fills.size > this.#maxFills) {
|
|
@@ -1381,7 +1446,7 @@ var AccountView = (_class3 = class {
|
|
|
1381
1446
|
}
|
|
1382
1447
|
}
|
|
1383
1448
|
#upsertPosition(position) {
|
|
1384
|
-
const key = _nullishCoalesce(_optionalChain([position, 'optionalAccess',
|
|
1449
|
+
const key = _nullishCoalesce(_optionalChain([position, 'optionalAccess', _18 => _18.market_id]), () => ( _optionalChain([position, 'optionalAccess', _19 => _19.id])));
|
|
1385
1450
|
if (!key) return;
|
|
1386
1451
|
if (!this.#keepFlat && isZero(position.position)) this.#positions.delete(key);
|
|
1387
1452
|
else this.#positions.set(key, position);
|
|
@@ -1457,10 +1522,6 @@ function comboJoinError(err, host = "") {
|
|
|
1457
1522
|
}
|
|
1458
1523
|
return err;
|
|
1459
1524
|
}
|
|
1460
|
-
async function comboJoinPayload(geo) {
|
|
1461
|
-
const packet = await resolveGeoLocation(geo);
|
|
1462
|
-
return packet === void 0 ? {} : { geo_location: packet };
|
|
1463
|
-
}
|
|
1464
1525
|
function money(name, value) {
|
|
1465
1526
|
if (typeof value !== "string") {
|
|
1466
1527
|
throw new TypeError(`${name} must be a decimal string such as "250.00", got ${typeof value}`);
|
|
@@ -1484,10 +1545,6 @@ var ComboSession = class {
|
|
|
1484
1545
|
get externalId() {
|
|
1485
1546
|
return _nullishCoalesce(this.channel.reply.external_id, () => ( ""));
|
|
1486
1547
|
}
|
|
1487
|
-
/** When the geolocation packet this join used expires (ISO 8601), or null. Rejoin before it. */
|
|
1488
|
-
get nextGeolocationAt() {
|
|
1489
|
-
return _nullishCoalesce(this.channel.reply.next_geolocation_at, () => ( null));
|
|
1490
|
-
}
|
|
1491
1548
|
/** @internal */
|
|
1492
1549
|
_typed(msg) {
|
|
1493
1550
|
if (!this.#events.has(msg.event) || !msg.payload || typeof msg.payload !== "object") return void 0;
|
|
@@ -1828,7 +1885,7 @@ function buildRequest(operationId, args = {}) {
|
|
|
1828
1885
|
const op = OPERATIONS[operationId];
|
|
1829
1886
|
let path = op.path;
|
|
1830
1887
|
for (const name of op.pathParams) {
|
|
1831
|
-
const value = _optionalChain([args, 'access',
|
|
1888
|
+
const value = _optionalChain([args, 'access', _20 => _20.pathParams, 'optionalAccess', _21 => _21[name]]);
|
|
1832
1889
|
if (!value) throw new TypeError(`${name} is required`);
|
|
1833
1890
|
path = path.replace(`{${name}}`, quote(String(value)));
|
|
1834
1891
|
}
|
|
@@ -1867,7 +1924,9 @@ function decodeResponse(request, status, text, headers = {}) {
|
|
|
1867
1924
|
method: request.method,
|
|
1868
1925
|
path: request.path,
|
|
1869
1926
|
retryAfter: headers.retryAfter,
|
|
1870
|
-
wwwAuthenticate: headers.wwwAuthenticate
|
|
1927
|
+
wwwAuthenticate: headers.wwwAuthenticate,
|
|
1928
|
+
stxError: headers.stxError,
|
|
1929
|
+
cfId: headers.cfId
|
|
1871
1930
|
});
|
|
1872
1931
|
}
|
|
1873
1932
|
function splitPage(operationId, body) {
|
|
@@ -1882,10 +1941,14 @@ function toBatchOrderResult(raw) {
|
|
|
1882
1941
|
const obj = raw && typeof raw === "object" ? raw : {};
|
|
1883
1942
|
const order = _nullishCoalesce(obj.order, () => ( null));
|
|
1884
1943
|
const errors = Array.isArray(obj.errors) ? obj.errors : null;
|
|
1885
|
-
return { ...obj, order, errors, ok: order !== null && !_optionalChain([errors, 'optionalAccess',
|
|
1944
|
+
return { ...obj, order, errors, ok: order !== null && !_optionalChain([errors, 'optionalAccess', _22 => _22.length]) };
|
|
1886
1945
|
}
|
|
1887
1946
|
|
|
1888
1947
|
// src/client.ts
|
|
1948
|
+
var FILL_MODES = ["normal", "post_only", "fill_or_kill"];
|
|
1949
|
+
var NOT_ENABLED = /fill_mode (post_only|fill_or_kill) is not enabled|The (post_only|fill_or_kill) fill mode is not enabled/;
|
|
1950
|
+
var NOT_ACCEPTED = /does not accept the (post_only|fill_or_kill) fill mode/;
|
|
1951
|
+
var MATCH_WITH_SELF = "would match with your other order";
|
|
1889
1952
|
var NEW_ORDER_FIELDS = {
|
|
1890
1953
|
marketId: "market_id",
|
|
1891
1954
|
action: "action",
|
|
@@ -1896,7 +1959,8 @@ var NEW_ORDER_FIELDS = {
|
|
|
1896
1959
|
expiration: "expiration",
|
|
1897
1960
|
expirationTime: "expiration_time",
|
|
1898
1961
|
cancelOnDisconnect: "cancel_on_disconnect",
|
|
1899
|
-
deviceId: "device_id"
|
|
1962
|
+
deviceId: "device_id",
|
|
1963
|
+
fillMode: "fill_mode"
|
|
1900
1964
|
};
|
|
1901
1965
|
function amount(name, value, required) {
|
|
1902
1966
|
if (value === void 0 || value === null) {
|
|
@@ -1911,6 +1975,13 @@ function amount(name, value, required) {
|
|
|
1911
1975
|
return value;
|
|
1912
1976
|
}
|
|
1913
1977
|
function orderBody(marketId, action, orderType, opts) {
|
|
1978
|
+
const mode = opts.fillMode;
|
|
1979
|
+
if (mode !== void 0 && mode !== null && !FILL_MODES.includes(mode)) {
|
|
1980
|
+
throw new TypeError(`fillMode must be one of ${JSON.stringify(FILL_MODES)}, got ${JSON.stringify(mode)}`);
|
|
1981
|
+
}
|
|
1982
|
+
if ((mode === "post_only" || mode === "fill_or_kill") && orderType !== "limit") {
|
|
1983
|
+
throw new TypeError(`fillMode "${mode}" is for limit orders only`);
|
|
1984
|
+
}
|
|
1914
1985
|
const body = {
|
|
1915
1986
|
market_id: marketId,
|
|
1916
1987
|
action,
|
|
@@ -1923,7 +1994,8 @@ function orderBody(marketId, action, orderType, opts) {
|
|
|
1923
1994
|
expiration: opts.expiration,
|
|
1924
1995
|
expiration_time: opts.expirationTime,
|
|
1925
1996
|
cancel_on_disconnect: opts.cancelOnDisconnect,
|
|
1926
|
-
device_id: opts.deviceId
|
|
1997
|
+
device_id: opts.deviceId,
|
|
1998
|
+
fill_mode: mode === "normal" ? void 0 : mode
|
|
1927
1999
|
};
|
|
1928
2000
|
for (const [k, v] of Object.entries(optional)) if (v !== void 0 && v !== null) body[k] = v;
|
|
1929
2001
|
return body;
|
|
@@ -1952,9 +2024,13 @@ var GATED_OPERATIONS = {
|
|
|
1952
2024
|
markets_post: "markets.create",
|
|
1953
2025
|
leaderboard_get: "leaderboard",
|
|
1954
2026
|
leaderboard_me_get: "leaderboard",
|
|
1955
|
-
me_profile_patch: "leaderboard"
|
|
2027
|
+
me_profile_patch: "leaderboard",
|
|
2028
|
+
portfolio_loyalty_get: "loyalty"
|
|
2029
|
+
};
|
|
2030
|
+
var SWITCHED_OFF = {
|
|
2031
|
+
leaderboard: "Leaderboard is not enabled",
|
|
2032
|
+
loyalty: "Loyalty program is not enabled"
|
|
1956
2033
|
};
|
|
1957
|
-
var LEADERBOARD_OFF = "Leaderboard is not enabled";
|
|
1958
2034
|
var STX = (_class4 = class _STX {
|
|
1959
2035
|
|
|
1960
2036
|
|
|
@@ -1967,10 +2043,10 @@ var STX = (_class4 = class _STX {
|
|
|
1967
2043
|
|
|
1968
2044
|
|
|
1969
2045
|
|
|
1970
|
-
|
|
1971
2046
|
#fetch;
|
|
1972
2047
|
#me;
|
|
1973
2048
|
#capabilities;
|
|
2049
|
+
#apiVersion;
|
|
1974
2050
|
/** Test hook: how retries wait. */
|
|
1975
2051
|
__init5() {this._sleep = sleep}
|
|
1976
2052
|
constructor(opts = {}) {;_class4.prototype.__init5.call(this);
|
|
@@ -2008,7 +2084,6 @@ var STX = (_class4 = class _STX {
|
|
|
2008
2084
|
this.verifyTls = settings.verifyTls;
|
|
2009
2085
|
this.retry = _nullishCoalesce(opts.retry, () => ( new RetryPolicy()));
|
|
2010
2086
|
this.timeoutMs = _nullishCoalesce(opts.timeoutMs, () => ( 3e4));
|
|
2011
|
-
this.geoLocation = opts.geoLocation;
|
|
2012
2087
|
this.onResponse = opts.onResponse;
|
|
2013
2088
|
const fetchImpl = _nullishCoalesce(opts.fetch, () => ( globalThis.fetch));
|
|
2014
2089
|
if (typeof fetchImpl !== "function") {
|
|
@@ -2022,7 +2097,7 @@ var STX = (_class4 = class _STX {
|
|
|
2022
2097
|
this.#fetch = fetchImpl;
|
|
2023
2098
|
}
|
|
2024
2099
|
toString() {
|
|
2025
|
-
return `STX(baseUrl=${JSON.stringify(this.baseUrl)}, keyId=${JSON.stringify(_nullishCoalesce(_optionalChain([this, 'access',
|
|
2100
|
+
return `STX(baseUrl=${JSON.stringify(this.baseUrl)}, keyId=${JSON.stringify(_nullishCoalesce(_optionalChain([this, 'access', _23 => _23.credentials, 'optionalAccess', _24 => _24.keyId]), () => ( null)))})`;
|
|
2026
2101
|
}
|
|
2027
2102
|
/** The exchange host, e.g. `"demo.stxapp.io"`: the name `STXNotAvailableException` and `capabilities()` report. */
|
|
2028
2103
|
get host() {
|
|
@@ -2075,6 +2150,89 @@ var STX = (_class4 = class _STX {
|
|
|
2075
2150
|
clearTimeout(timer);
|
|
2076
2151
|
}
|
|
2077
2152
|
}
|
|
2153
|
+
// GET /api_version, cached on the client. A 404 is an answer (no feature
|
|
2154
|
+
// list), and so is a bare 403 from the edge (not JSON, no x-stx-error), which
|
|
2155
|
+
// some exchanges send for this path while serving the API. Any other failure
|
|
2156
|
+
// throws, so an outage or a block with a reason is never read as "absent".
|
|
2157
|
+
#apiVersionInfo() {
|
|
2158
|
+
if (!this.#apiVersion) {
|
|
2159
|
+
const run = this.#fetchApiVersion();
|
|
2160
|
+
this.#apiVersion = run;
|
|
2161
|
+
run.catch(() => {
|
|
2162
|
+
if (this.#apiVersion === run) this.#apiVersion = void 0;
|
|
2163
|
+
});
|
|
2164
|
+
}
|
|
2165
|
+
return this.#apiVersion;
|
|
2166
|
+
}
|
|
2167
|
+
async #fetchApiVersion() {
|
|
2168
|
+
const request = {
|
|
2169
|
+
operationId: "api_version",
|
|
2170
|
+
method: "GET",
|
|
2171
|
+
path: "/api_version",
|
|
2172
|
+
body: void 0,
|
|
2173
|
+
idempotent: true
|
|
2174
|
+
};
|
|
2175
|
+
const controller = new AbortController();
|
|
2176
|
+
const timer = setTimeout(() => controller.abort(), this.timeoutMs);
|
|
2177
|
+
let res;
|
|
2178
|
+
let text;
|
|
2179
|
+
try {
|
|
2180
|
+
res = await this.#fetch(this.baseUrl + request.path, {
|
|
2181
|
+
method: "GET",
|
|
2182
|
+
headers: { "User-Agent": USER_AGENT, Accept: "application/json" },
|
|
2183
|
+
signal: controller.signal
|
|
2184
|
+
});
|
|
2185
|
+
text = await res.text();
|
|
2186
|
+
} catch (err) {
|
|
2187
|
+
throw new STXTransportException(`GET /api_version failed: ${_nullishCoalesce(_optionalChain([err, 'optionalAccess', _25 => _25.message]), () => ( String(err)))}`, {
|
|
2188
|
+
method: "GET",
|
|
2189
|
+
path: request.path,
|
|
2190
|
+
cause: err
|
|
2191
|
+
});
|
|
2192
|
+
} finally {
|
|
2193
|
+
clearTimeout(timer);
|
|
2194
|
+
}
|
|
2195
|
+
if (res.status === 404 || res.status === 403 && !res.headers.get("x-stx-error") && isEdgeBlock(403, text)) {
|
|
2196
|
+
return { apiVersion: null, features: null };
|
|
2197
|
+
}
|
|
2198
|
+
return apiVersionFrom(
|
|
2199
|
+
decodeResponse(request, res.status, text, {
|
|
2200
|
+
retryAfter: res.headers.get("Retry-After"),
|
|
2201
|
+
stxError: res.headers.get("x-stx-error"),
|
|
2202
|
+
cfId: res.headers.get("x-amz-cf-id")
|
|
2203
|
+
})
|
|
2204
|
+
);
|
|
2205
|
+
}
|
|
2206
|
+
// Older builds ignore a fill_mode they do not know and would place a normal
|
|
2207
|
+
// order, so nothing is sent unless the exchange lists the mode.
|
|
2208
|
+
async #requireFillModes(modes) {
|
|
2209
|
+
for (const mode of [...new Set(modes)].sort()) {
|
|
2210
|
+
const feature = `orders.${mode}`;
|
|
2211
|
+
const info = await this.#apiVersionInfo();
|
|
2212
|
+
if (!_optionalChain([info, 'access', _26 => _26.features, 'optionalAccess', _27 => _27.includes, 'call', _28 => _28(API_FEATURES[feature])])) {
|
|
2213
|
+
throw new STXNotAvailableException(feature, this.host, { apiVersion: info.apiVersion });
|
|
2214
|
+
}
|
|
2215
|
+
}
|
|
2216
|
+
}
|
|
2217
|
+
// A typed error for the exchange's refusals of a fill mode, else undefined.
|
|
2218
|
+
async #fillModeError(err, mode) {
|
|
2219
|
+
if (!(err instanceof STXValidationException || err instanceof STXRejectedException)) return void 0;
|
|
2220
|
+
const base = { statusCode: err.statusCode, body: err.body, method: err.method, path: err.path, cause: err };
|
|
2221
|
+
const off = NOT_ENABLED.exec(err.message);
|
|
2222
|
+
if (off) {
|
|
2223
|
+
const cached = this.#apiVersion;
|
|
2224
|
+
this.#apiVersion = void 0;
|
|
2225
|
+
const apiVersion = cached ? await _asyncOptionalChain([(await cached.catch(() => null)), 'optionalAccess', async _29 => _29.apiVersion]) : void 0;
|
|
2226
|
+
return new STXNotAvailableException(`orders.${_nullishCoalesce(off[1], () => ( off[2]))}`, this.host, { ...base, apiVersion });
|
|
2227
|
+
}
|
|
2228
|
+
if (!(err instanceof STXRejectedException)) return void 0;
|
|
2229
|
+
const notAccepted = NOT_ACCEPTED.exec(err.message);
|
|
2230
|
+
if (notAccepted) return new STXFillModeNotAllowedException(err.message, { ...base, fillMode: notAccepted[1] });
|
|
2231
|
+
if (mode === "post_only" && err.message.includes(MATCH_WITH_SELF)) {
|
|
2232
|
+
return new STXPostOnlyWouldMatchException(err.message, { ...base, reason: "match_with_self" });
|
|
2233
|
+
}
|
|
2234
|
+
return void 0;
|
|
2235
|
+
}
|
|
2078
2236
|
async #joinReason(topic) {
|
|
2079
2237
|
if (!this.auth) return null;
|
|
2080
2238
|
const ws = this.websocket({ reconnect: false, joinTimeoutMs: 8e3 });
|
|
@@ -2125,7 +2283,7 @@ var STX = (_class4 = class _STX {
|
|
|
2125
2283
|
status,
|
|
2126
2284
|
attempt,
|
|
2127
2285
|
durationMs: Date.now() - started,
|
|
2128
|
-
authKind: _optionalChain([this, 'access',
|
|
2286
|
+
authKind: _optionalChain([this, 'access', _30 => _30.auth, 'optionalAccess', _31 => _31.kind]),
|
|
2129
2287
|
requestBody: request.body,
|
|
2130
2288
|
responseBody
|
|
2131
2289
|
});
|
|
@@ -2157,7 +2315,7 @@ var STX = (_class4 = class _STX {
|
|
|
2157
2315
|
});
|
|
2158
2316
|
}
|
|
2159
2317
|
throw new STXTransportException(
|
|
2160
|
-
`${request.method} ${request.path} failed: ${_nullishCoalesce(_optionalChain([err, 'optionalAccess',
|
|
2318
|
+
`${request.method} ${request.path} failed: ${_nullishCoalesce(_optionalChain([err, 'optionalAccess', _32 => _32.message]), () => ( String(err)))}`,
|
|
2161
2319
|
{ method: request.method, path: request.path, cause: err }
|
|
2162
2320
|
);
|
|
2163
2321
|
} finally {
|
|
@@ -2166,7 +2324,9 @@ var STX = (_class4 = class _STX {
|
|
|
2166
2324
|
this.#report(request, response.status, attempt, started, text);
|
|
2167
2325
|
return decodeResponse(request, response.status, text, {
|
|
2168
2326
|
retryAfter: response.headers.get("Retry-After"),
|
|
2169
|
-
wwwAuthenticate: response.headers.get("WWW-Authenticate")
|
|
2327
|
+
wwwAuthenticate: response.headers.get("WWW-Authenticate"),
|
|
2328
|
+
stxError: response.headers.get("x-stx-error"),
|
|
2329
|
+
cfId: response.headers.get("x-amz-cf-id")
|
|
2170
2330
|
});
|
|
2171
2331
|
}
|
|
2172
2332
|
async #send(request) {
|
|
@@ -2179,7 +2339,7 @@ var STX = (_class4 = class _STX {
|
|
|
2179
2339
|
return await this.#sendOnce(request, sent);
|
|
2180
2340
|
} catch (err) {
|
|
2181
2341
|
if (!(err instanceof STXException)) throw err;
|
|
2182
|
-
if (err.statusCode === 401 && !reauthenticated && _optionalChain([this, 'access',
|
|
2342
|
+
if (err.statusCode === 401 && !reauthenticated && _optionalChain([this, 'access', _33 => _33.auth, 'optionalAccess', _34 => _34.onUnauthorized])) {
|
|
2183
2343
|
reauthenticated = true;
|
|
2184
2344
|
if (await this.auth.onUnauthorized()) continue;
|
|
2185
2345
|
}
|
|
@@ -2194,7 +2354,7 @@ var STX = (_class4 = class _STX {
|
|
|
2194
2354
|
return await this.#send(buildRequest(operationId, args));
|
|
2195
2355
|
} catch (err) {
|
|
2196
2356
|
const feature = GATED_OPERATIONS[operationId];
|
|
2197
|
-
const off = feature
|
|
2357
|
+
const off = feature !== void 0 && err instanceof STXNotFoundException && SWITCHED_OFF[feature] !== void 0 && _optionalChain([err, 'access', _35 => _35.body, 'optionalAccess', _36 => _36.error]) === SWITCHED_OFF[feature];
|
|
2198
2358
|
if (feature && (isMissingRoute(err) || off)) {
|
|
2199
2359
|
throw new STXNotAvailableException(feature, this.host, {
|
|
2200
2360
|
statusCode: err.statusCode,
|
|
@@ -2229,10 +2389,6 @@ var STX = (_class4 = class _STX {
|
|
|
2229
2389
|
q.cursor = page.cursor;
|
|
2230
2390
|
}
|
|
2231
2391
|
}
|
|
2232
|
-
async #geoBody(body, opts) {
|
|
2233
|
-
const packet = _optionalChain([opts, 'optionalAccess', _28 => _28.geoLocation]) !== void 0 ? _nullishCoalesce(opts.geoLocation, () => ( void 0)) : await resolveGeoLocation(this.geoLocation);
|
|
2234
|
-
return packet === void 0 ? body : { ...body, geo_location: packet };
|
|
2235
|
-
}
|
|
2236
2392
|
// ------------------------------------------------------------------
|
|
2237
2393
|
// Identity
|
|
2238
2394
|
// ------------------------------------------------------------------
|
|
@@ -2251,7 +2407,7 @@ var STX = (_class4 = class _STX {
|
|
|
2251
2407
|
* `user_id`.
|
|
2252
2408
|
*/
|
|
2253
2409
|
async userId() {
|
|
2254
|
-
if (_optionalChain([this, 'access',
|
|
2410
|
+
if (_optionalChain([this, 'access', _37 => _37.#me, 'optionalAccess', _38 => _38.user_id])) return this.#me.user_id;
|
|
2255
2411
|
try {
|
|
2256
2412
|
await this.me();
|
|
2257
2413
|
} catch (err) {
|
|
@@ -2262,7 +2418,7 @@ var STX = (_class4 = class _STX {
|
|
|
2262
2418
|
if (!balance.user_id) throw err;
|
|
2263
2419
|
this.#me = { ..._nullishCoalesce(this.#me, () => ( {})), user_id: balance.user_id };
|
|
2264
2420
|
}
|
|
2265
|
-
if (!_optionalChain([this, 'access',
|
|
2421
|
+
if (!_optionalChain([this, 'access', _39 => _39.#me, 'optionalAccess', _40 => _40.user_id])) throw new STXException("GET /api/v1/me returned no user_id");
|
|
2266
2422
|
return this.#me.user_id;
|
|
2267
2423
|
}
|
|
2268
2424
|
// ------------------------------------------------------------------
|
|
@@ -2429,85 +2585,82 @@ var STX = (_class4 = class _STX {
|
|
|
2429
2585
|
* are decimal strings, e.g. `{ price: "0.58", quantity: "100" }`. Numbers are
|
|
2430
2586
|
* refused client-side.
|
|
2431
2587
|
*
|
|
2588
|
+
* `fillMode` (limit orders only) is `"normal"` (the default), `"post_only"`
|
|
2589
|
+
* or `"fill_or_kill"`. A post-only order that would match on arrival is not
|
|
2590
|
+
* placed: this throws `STXPostOnlyWouldMatchException`. A fill-or-kill order
|
|
2591
|
+
* comes back `accepted` (or `delayed` in play); follow it on the `orders`
|
|
2592
|
+
* channel or with `order()` to see it `filled` or `cancelled`.
|
|
2593
|
+
*
|
|
2594
|
+
* Before sending either mode, the client checks once that the exchange offers
|
|
2595
|
+
* it (`GET /api_version`, cached) and throws `STXNotAvailableException`
|
|
2596
|
+
* (`orders.post_only`, `orders.fill_or_kill`) without sending the order when
|
|
2597
|
+
* it does not. A combination market throws `STXFillModeNotAllowedException`.
|
|
2598
|
+
*
|
|
2432
2599
|
* The exchange validates the order: a bad price step or a fractional
|
|
2433
2600
|
* quantity throws `STXValidationException` (400) or `STXRejectedException`
|
|
2434
|
-
* (422) with the API's message
|
|
2435
|
-
* `
|
|
2601
|
+
* (422) with the API's message. An order from outside the region is also
|
|
2602
|
+
* an `STXRejectedException`.
|
|
2436
2603
|
*
|
|
2437
2604
|
* A POST is never retried after a 5xx or a dropped connection; pass
|
|
2438
2605
|
* `clientOrderId` so you can look the order up if that happens.
|
|
2439
2606
|
*/
|
|
2440
2607
|
async placeOrder(marketId, action, orderType, opts) {
|
|
2441
|
-
const
|
|
2442
|
-
const
|
|
2443
|
-
return this.#one("orders_post", { body
|
|
2608
|
+
const body = orderBody(marketId, action, orderType, _nullishCoalesce(opts, () => ( {})));
|
|
2609
|
+
const mode = body.fill_mode;
|
|
2610
|
+
if (mode === void 0) return this.#one("orders_post", { body });
|
|
2611
|
+
await this.#requireFillModes([mode]);
|
|
2612
|
+
let order;
|
|
2613
|
+
try {
|
|
2614
|
+
order = await this.#one("orders_post", { body });
|
|
2615
|
+
} catch (err) {
|
|
2616
|
+
throw await _asyncNullishCoalesce(await this.#fillModeError(err, mode), async () => ( err));
|
|
2617
|
+
}
|
|
2618
|
+
if (mode === "post_only" && order.status === "cancelled" && order.cancellation_reason === "auto_matching") {
|
|
2619
|
+
throw new STXPostOnlyWouldMatchException(
|
|
2620
|
+
"The post-only order would have matched on arrival, so it was cancelled.",
|
|
2621
|
+
{ reason: "auto_matching", order, statusCode: 200, method: "POST", path: OPERATIONS.orders_post.path }
|
|
2622
|
+
);
|
|
2623
|
+
}
|
|
2624
|
+
return order;
|
|
2444
2625
|
}
|
|
2445
2626
|
/**
|
|
2446
|
-
* `POST /api/v1/orders/batched`: place several orders in one call.
|
|
2447
|
-
*
|
|
2448
|
-
*
|
|
2449
|
-
*
|
|
2627
|
+
* `POST /api/v1/orders/batched`: place several orders in one call. Returns
|
|
2628
|
+
* one result per order, in order; a rejected order has `errors` instead of
|
|
2629
|
+
* `order` and does not stop the others. A post-only order that would have
|
|
2630
|
+
* matched comes back as its order, `cancelled` with `cancellation_reason`
|
|
2631
|
+
* `auto_matching`.
|
|
2632
|
+
*
|
|
2633
|
+
* When any order has a `fillMode` other than `"normal"`, the exchange is
|
|
2634
|
+
* checked first as in `placeOrder()`, and `STXNotAvailableException` is
|
|
2635
|
+
* thrown with nothing sent.
|
|
2450
2636
|
*/
|
|
2451
|
-
async placeOrders(orders
|
|
2637
|
+
async placeOrders(orders) {
|
|
2452
2638
|
const body = { orders: orders.map(normalizeOrder) };
|
|
2453
|
-
const
|
|
2639
|
+
const modes = body.orders.map((o) => o.fill_mode).filter((m) => typeof m === "string");
|
|
2640
|
+
if (modes.length) await this.#requireFillModes(modes);
|
|
2641
|
+
let raw;
|
|
2642
|
+
try {
|
|
2643
|
+
raw = await this.#list("orders_batched_post", { body });
|
|
2644
|
+
} catch (err) {
|
|
2645
|
+
throw await _asyncNullishCoalesce((modes.length ? await this.#fillModeError(err, void 0) : void 0), async () => ( err));
|
|
2646
|
+
}
|
|
2454
2647
|
return raw.map(toBatchOrderResult);
|
|
2455
2648
|
}
|
|
2456
2649
|
/**
|
|
2457
2650
|
* `DELETE /api/v1/orders/{order_id}`: request a cancel. A cancel is a
|
|
2458
2651
|
* request: a fill already in flight can still land.
|
|
2459
2652
|
*/
|
|
2460
|
-
async cancelOrder(orderId
|
|
2461
|
-
|
|
2462
|
-
return this.#one("orders__order_id_delete", {
|
|
2463
|
-
pathParams: { order_id: orderId },
|
|
2464
|
-
body: "geo_location" in geo ? geo : void 0
|
|
2465
|
-
});
|
|
2653
|
+
async cancelOrder(orderId) {
|
|
2654
|
+
return this.#one("orders__order_id_delete", { pathParams: { order_id: orderId } });
|
|
2466
2655
|
}
|
|
2467
2656
|
/** `DELETE /api/v1/orders/batched`: cancel the named orders. */
|
|
2468
|
-
async cancelOrders(orderIds
|
|
2657
|
+
async cancelOrders(orderIds) {
|
|
2469
2658
|
const body = { orders: orderIds.map((id) => ({ order_id: id })) };
|
|
2470
|
-
return this.#list("orders_batched_delete", { body
|
|
2659
|
+
return this.#list("orders_batched_delete", { body });
|
|
2471
2660
|
}
|
|
2472
2661
|
/** `DELETE /api/v1/orders/all`: cancel everything resting on the account. */
|
|
2473
|
-
async cancelAllOrders(
|
|
2474
|
-
|
|
2475
|
-
return this.#list("orders_all_delete", { body: "geo_location" in geo ? geo : void 0 });
|
|
2476
|
-
}
|
|
2477
|
-
// ------------------------------------------------------------------
|
|
2478
|
-
// Geo-fencing
|
|
2479
|
-
// ------------------------------------------------------------------
|
|
2480
|
-
/**
|
|
2481
|
-
* Ask the exchange whether this machine may trade right now, without
|
|
2482
|
-
* placing or cancelling anything.
|
|
2483
|
-
*
|
|
2484
|
-
* Sends `DELETE /api/v1/orders/00000000-0000-0000-0000-000000000000` (an
|
|
2485
|
-
* order id that cannot exist) with the geolocation packet, if one is
|
|
2486
|
-
* configured. The exchange runs its geo check before it looks the order
|
|
2487
|
-
* up, so a 404 means the check passed, and a geo 422 means it did not. On
|
|
2488
|
-
* an exchange without geo-fencing it always passes.
|
|
2489
|
-
*
|
|
2490
|
-
* Needs a `read_write` key (the probe is a write route). The exchange
|
|
2491
|
-
* records a failed check in its geolocation log exactly as it would a real
|
|
2492
|
-
* order from the same place, and may raise a compliance alert, so call it
|
|
2493
|
-
* once at start-up, not in a loop.
|
|
2494
|
-
*/
|
|
2495
|
-
async geoCheck(opts) {
|
|
2496
|
-
const geo = await this.#geoBody({}, opts);
|
|
2497
|
-
const sentPacket = "geo_location" in geo;
|
|
2498
|
-
try {
|
|
2499
|
-
await this.#one("orders__order_id_delete", {
|
|
2500
|
-
pathParams: { order_id: "00000000-0000-0000-0000-000000000000" },
|
|
2501
|
-
body: sentPacket ? geo : void 0
|
|
2502
|
-
});
|
|
2503
|
-
return { allowed: true, sentPacket };
|
|
2504
|
-
} catch (err) {
|
|
2505
|
-
if (err instanceof STXNotFoundException) return { allowed: true, sentPacket };
|
|
2506
|
-
if (err instanceof STXGeoLocationException) {
|
|
2507
|
-
return { allowed: false, reason: err.reason, message: err.message, ipAddress: err.ipAddress, sentPacket };
|
|
2508
|
-
}
|
|
2509
|
-
throw err;
|
|
2510
|
-
}
|
|
2662
|
+
async cancelAllOrders() {
|
|
2663
|
+
return this.#list("orders_all_delete");
|
|
2511
2664
|
}
|
|
2512
2665
|
// ------------------------------------------------------------------
|
|
2513
2666
|
// Fills, positions, balance
|
|
@@ -2549,6 +2702,7 @@ var STX = (_class4 = class _STX {
|
|
|
2549
2702
|
market_ids: ids(q.marketIds),
|
|
2550
2703
|
event_ids: ids(q.eventIds),
|
|
2551
2704
|
exclude_zero_settlements: q.excludeZeroSettlements,
|
|
2705
|
+
unsettled_only: q.unsettledOnly,
|
|
2552
2706
|
from_time: q.fromTime,
|
|
2553
2707
|
to_time: q.toTime,
|
|
2554
2708
|
sports: ids(q.sports),
|
|
@@ -2613,11 +2767,15 @@ var STX = (_class4 = class _STX {
|
|
|
2613
2767
|
iterFees(query = {}) {
|
|
2614
2768
|
return this.#iterate("portfolio_fees_get", { limit: query.limit });
|
|
2615
2769
|
}
|
|
2616
|
-
/**
|
|
2770
|
+
/**
|
|
2771
|
+
* `GET /api/v1/portfolio/loyalty`: loyalty entries. Throws
|
|
2772
|
+
* `STXNotAvailableException` (feature `loyalty`) where the exchange has the
|
|
2773
|
+
* loyalty program switched off.
|
|
2774
|
+
*/
|
|
2617
2775
|
loyalty(query = {}) {
|
|
2618
2776
|
return this.#page("portfolio_loyalty_get", { limit: query.limit, cursor: query.cursor });
|
|
2619
2777
|
}
|
|
2620
|
-
/** Every loyalty entry, following the cursor. */
|
|
2778
|
+
/** Every loyalty entry, following the cursor. Throws like `loyalty()`. */
|
|
2621
2779
|
iterLoyalty(query = {}) {
|
|
2622
2780
|
return this.#iterate("portfolio_loyalty_get", { limit: query.limit });
|
|
2623
2781
|
}
|
|
@@ -2752,6 +2910,12 @@ var MessageQueue = class {
|
|
|
2752
2910
|
this.#items.push(msg);
|
|
2753
2911
|
return dropped;
|
|
2754
2912
|
}
|
|
2913
|
+
/** Queue the end marker behind everything already queued, dropping nothing. */
|
|
2914
|
+
end() {
|
|
2915
|
+
const waiter = this.#waiters.shift();
|
|
2916
|
+
if (waiter) waiter(null);
|
|
2917
|
+
else this.#items.push(null);
|
|
2918
|
+
}
|
|
2755
2919
|
get(timeoutMs) {
|
|
2756
2920
|
if (this.#items.length) return Promise.resolve(this.#items.shift());
|
|
2757
2921
|
return new Promise((resolve, reject) => {
|
|
@@ -2789,13 +2953,24 @@ var Channel = (_class5 = class {
|
|
|
2789
2953
|
__init9() {this.joinRef = null}
|
|
2790
2954
|
__init10() {this.joined = false}
|
|
2791
2955
|
__init11() {this.closed = false}
|
|
2792
|
-
/** @internal Runs before every (re)join, e.g. to refresh a geolocation packet in `joinPayload`. */
|
|
2793
|
-
|
|
2794
2956
|
#ws;
|
|
2795
2957
|
#queue;
|
|
2796
2958
|
#snapshotWaiters = [];
|
|
2797
2959
|
#pingTimer;
|
|
2798
|
-
|
|
2960
|
+
/** @internal Milliseconds between pings while joined; null when none are sent. */
|
|
2961
|
+
__init12() {this._pingEveryMs = null}
|
|
2962
|
+
// One phx_join per topic per connection (Phoenix answers a second join of a
|
|
2963
|
+
// joined topic by closing the first): joins run one after another, and a
|
|
2964
|
+
// join already made on the current connection is not repeated.
|
|
2965
|
+
/** @internal */
|
|
2966
|
+
__init13() {this._joinTail = Promise.resolve()}
|
|
2967
|
+
/** @internal */
|
|
2968
|
+
__init14() {this._joinedConnection = 0}
|
|
2969
|
+
/** @internal The connection whose join also restored watches and the pinger. */
|
|
2970
|
+
__init15() {this._restoredConnection = 0}
|
|
2971
|
+
/** @internal A phx_close/phx_error for the join in flight. */
|
|
2972
|
+
__init16() {this._endedJoin = null}
|
|
2973
|
+
constructor(ws, topic, joinPayload, onMessage, opts) {;_class5.prototype.__init6.call(this);_class5.prototype.__init7.call(this);_class5.prototype.__init8.call(this);_class5.prototype.__init9.call(this);_class5.prototype.__init10.call(this);_class5.prototype.__init11.call(this);_class5.prototype.__init12.call(this);_class5.prototype.__init13.call(this);_class5.prototype.__init14.call(this);_class5.prototype.__init15.call(this);_class5.prototype.__init16.call(this);
|
|
2799
2974
|
this.#ws = ws;
|
|
2800
2975
|
this.topic = topic;
|
|
2801
2976
|
this.name = topic.split(":", 1)[0];
|
|
@@ -2960,11 +3135,12 @@ var Channel = (_class5 = class {
|
|
|
2960
3135
|
_startPinger() {
|
|
2961
3136
|
this._stopPinger();
|
|
2962
3137
|
let interval = this.pingIntervalMs;
|
|
2963
|
-
const granted = _optionalChain([this, 'access',
|
|
3138
|
+
const granted = _optionalChain([this, 'access', _41 => _41.reply, 'optionalAccess', _42 => _42.ping_timeout]);
|
|
2964
3139
|
if (typeof granted === "number" && this.joinPayload.cancel_on_disconnect) {
|
|
2965
|
-
const cod = granted
|
|
3140
|
+
const cod = granted / 3;
|
|
2966
3141
|
interval = interval === null ? cod : Math.min(interval, cod);
|
|
2967
3142
|
}
|
|
3143
|
+
this._pingEveryMs = interval || null;
|
|
2968
3144
|
if (interval) {
|
|
2969
3145
|
const every = interval;
|
|
2970
3146
|
this.#pingTimer = setInterval(() => {
|
|
@@ -2973,7 +3149,7 @@ var Channel = (_class5 = class {
|
|
|
2973
3149
|
(err) => this.#ws.logger.warn(`${this.topic} ping failed: ${err.message}`)
|
|
2974
3150
|
);
|
|
2975
3151
|
}, every);
|
|
2976
|
-
_optionalChain([this, 'access',
|
|
3152
|
+
_optionalChain([this, 'access', _43 => _43.#pingTimer, 'access', _44 => _44.unref, 'optionalCall', _45 => _45()]);
|
|
2977
3153
|
}
|
|
2978
3154
|
}
|
|
2979
3155
|
/** @internal */
|
|
@@ -2984,9 +3160,17 @@ var Channel = (_class5 = class {
|
|
|
2984
3160
|
/** @internal */
|
|
2985
3161
|
_resetForRejoin() {
|
|
2986
3162
|
this.joined = false;
|
|
3163
|
+
this._restoredConnection = 0;
|
|
2987
3164
|
this.snapshots = {};
|
|
2988
3165
|
this._stopPinger();
|
|
2989
3166
|
}
|
|
3167
|
+
/** @internal End the channel after every queued message is read. */
|
|
3168
|
+
_finish() {
|
|
3169
|
+
this.closed = true;
|
|
3170
|
+
this.joined = false;
|
|
3171
|
+
this._stopPinger();
|
|
3172
|
+
this.#queue.end();
|
|
3173
|
+
}
|
|
2990
3174
|
/** @internal */
|
|
2991
3175
|
_close() {
|
|
2992
3176
|
this.closed = true;
|
|
@@ -3017,23 +3201,27 @@ var STXWebSocket = (_class6 = class {
|
|
|
3017
3201
|
|
|
3018
3202
|
|
|
3019
3203
|
|
|
3020
|
-
|
|
3204
|
+
__init17() {this.channels = /* @__PURE__ */ new Map()}
|
|
3021
3205
|
/** Successful reconnects so far. */
|
|
3022
|
-
|
|
3206
|
+
__init18() {this.reconnects = 0}
|
|
3207
|
+
/** Channels rejoined after the server closed or errored them while the socket stayed up. */
|
|
3208
|
+
__init19() {this.channelRejoins = 0}
|
|
3023
3209
|
#userId;
|
|
3024
3210
|
#conn;
|
|
3025
3211
|
#ref = 0;
|
|
3212
|
+
#connection = 0;
|
|
3026
3213
|
#pending = /* @__PURE__ */ new Map();
|
|
3027
3214
|
#heartbeat;
|
|
3028
3215
|
#pendingHeartbeat = null;
|
|
3029
3216
|
#closed = false;
|
|
3030
3217
|
#connecting;
|
|
3031
3218
|
#reconnecting = false;
|
|
3219
|
+
#reconnectDone = Promise.resolve();
|
|
3032
3220
|
#closedWaiters = [];
|
|
3033
3221
|
// Frames are handled one at a time, in arrival order: each waits for the
|
|
3034
3222
|
// previous one's handler to finish.
|
|
3035
3223
|
#inbox = Promise.resolve();
|
|
3036
|
-
constructor(opts = {}) {;_class6.prototype.
|
|
3224
|
+
constructor(opts = {}) {;_class6.prototype.__init17.call(this);_class6.prototype.__init18.call(this);_class6.prototype.__init19.call(this);
|
|
3037
3225
|
if (opts.rest) {
|
|
3038
3226
|
this.rest = opts.rest;
|
|
3039
3227
|
} else {
|
|
@@ -3078,6 +3266,11 @@ var STXWebSocket = (_class6 = class {
|
|
|
3078
3266
|
async connect() {
|
|
3079
3267
|
if (this.#closed) throw new STXTransportException("This STXWebSocket is closed; create a new one.");
|
|
3080
3268
|
if (this.connected) return this;
|
|
3269
|
+
while (this.#reconnecting) {
|
|
3270
|
+
await this.#reconnectDone;
|
|
3271
|
+
if (this.#closed) throw new STXTransportException("This STXWebSocket is closed; create a new one.");
|
|
3272
|
+
if (this.connected) return this;
|
|
3273
|
+
}
|
|
3081
3274
|
if (!this.#connecting) {
|
|
3082
3275
|
this.#connecting = this.#openAuthenticated().finally(() => {
|
|
3083
3276
|
this.#connecting = void 0;
|
|
@@ -3168,7 +3361,7 @@ var STXWebSocket = (_class6 = class {
|
|
|
3168
3361
|
*/
|
|
3169
3362
|
async marketUpdates(opts = {}) {
|
|
3170
3363
|
const channel = await this.join("market_updates", {}, opts.onMessage);
|
|
3171
|
-
if (_optionalChain([opts, 'access',
|
|
3364
|
+
if (_optionalChain([opts, 'access', _46 => _46.watch, 'optionalAccess', _47 => _47.length])) await channel.watch(opts.watch);
|
|
3172
3365
|
return channel;
|
|
3173
3366
|
}
|
|
3174
3367
|
/**
|
|
@@ -3197,7 +3390,7 @@ var STXWebSocket = (_class6 = class {
|
|
|
3197
3390
|
* `cancelOnDisconnect: true` arms cancel-on-disconnect for orders placed
|
|
3198
3391
|
* with `cancelOnDisconnect: true`. `pingTimeout` is in milliseconds,
|
|
3199
3392
|
* clamped by the server to 5000 to 20000; the granted value is in
|
|
3200
|
-
* `channel.reply.ping_timeout` and the SDK pings at
|
|
3393
|
+
* `channel.reply.ping_timeout` and the SDK pings at a third of it for as long
|
|
3201
3394
|
* as the channel is joined.
|
|
3202
3395
|
*/
|
|
3203
3396
|
orders(opts = {}) {
|
|
@@ -3252,7 +3445,6 @@ var STXWebSocket = (_class6 = class {
|
|
|
3252
3445
|
* Join `rfq:{user_id}` and return a `ComboPlayer`: request quotes on a
|
|
3253
3446
|
* combination, cash one out, accept, cancel and read a request.
|
|
3254
3447
|
*
|
|
3255
|
-
* Available on US demo.
|
|
3256
3448
|
* Where combos are not available, rejects with
|
|
3257
3449
|
* `STXCombosUnavailableException`. Other join refusals (a read-only key, an
|
|
3258
3450
|
* account that may not trade) reject with `STXComboRefusedException`.
|
|
@@ -3272,7 +3464,6 @@ var STXWebSocket = (_class6 = class {
|
|
|
3272
3464
|
* Join `combo_quote:{user_id}` and return a `ComboMaker`: receive every
|
|
3273
3465
|
* request opened from now on (`rfq_opened`), quote and withdraw quotes.
|
|
3274
3466
|
*
|
|
3275
|
-
* Available on US demo.
|
|
3276
3467
|
* Where combos are not available, rejects with
|
|
3277
3468
|
* `STXCombosUnavailableException`.
|
|
3278
3469
|
*/
|
|
@@ -3288,19 +3479,11 @@ var STXWebSocket = (_class6 = class {
|
|
|
3288
3479
|
return maker;
|
|
3289
3480
|
}
|
|
3290
3481
|
async #joinCombo(name, opts, onMessage) {
|
|
3291
|
-
let channel;
|
|
3292
3482
|
try {
|
|
3293
|
-
|
|
3483
|
+
return await this.#joinAccount(name, {}, onMessage);
|
|
3294
3484
|
} catch (err) {
|
|
3295
3485
|
throw comboJoinError(err, new URL(this.rest.baseUrl).host);
|
|
3296
3486
|
}
|
|
3297
|
-
if (typeof opts.geoLocation === "function") {
|
|
3298
|
-
const geo = opts.geoLocation;
|
|
3299
|
-
channel._beforeJoin = async () => {
|
|
3300
|
-
channel.joinPayload = await comboJoinPayload(geo);
|
|
3301
|
-
};
|
|
3302
|
-
}
|
|
3303
|
-
return channel;
|
|
3304
3487
|
}
|
|
3305
3488
|
// ------------------------------------------------------------------
|
|
3306
3489
|
// Generic join
|
|
@@ -3311,9 +3494,13 @@ var STXWebSocket = (_class6 = class {
|
|
|
3311
3494
|
* `market_ids_required` or `unauthorized`) if the join is refused.
|
|
3312
3495
|
*/
|
|
3313
3496
|
async join(topic, payload = {}, onMessage, opts = {}) {
|
|
3314
|
-
const
|
|
3315
|
-
|
|
3497
|
+
const already = () => {
|
|
3498
|
+
const existing = this.channels.get(topic);
|
|
3499
|
+
if (existing && !existing.closed) throw new STXChannelException(`Already joined ${topic}`, { topic });
|
|
3500
|
+
};
|
|
3501
|
+
already();
|
|
3316
3502
|
await this.connect();
|
|
3503
|
+
already();
|
|
3317
3504
|
const name = topic.split(":", 1)[0];
|
|
3318
3505
|
const channel = new Channel(this, topic, payload, onMessage, {
|
|
3319
3506
|
pingIntervalMs: opts.pingIntervalMs !== void 0 ? opts.pingIntervalMs : UNPINGED_CHANNELS.has(name) ? null : this.channelPingIntervalMs,
|
|
@@ -3337,17 +3524,56 @@ var STXWebSocket = (_class6 = class {
|
|
|
3337
3524
|
}
|
|
3338
3525
|
return this.join(`${name}:${await this.userId()}`, payload, onMessage);
|
|
3339
3526
|
}
|
|
3340
|
-
|
|
3527
|
+
/**
|
|
3528
|
+
* Join `channel` on the current connection unless it already is, then
|
|
3529
|
+
* restore its watches and pinger; resolves to whether anything was done.
|
|
3530
|
+
*/
|
|
3531
|
+
#join(channel) {
|
|
3532
|
+
const run = channel._joinTail.then(async () => {
|
|
3533
|
+
const connection = this.#connection;
|
|
3534
|
+
if (channel.closed) return false;
|
|
3535
|
+
if (channel.joined && channel._joinedConnection === connection) {
|
|
3536
|
+
if (channel._restoredConnection === connection) return false;
|
|
3537
|
+
await this.#restore(channel, connection);
|
|
3538
|
+
return true;
|
|
3539
|
+
}
|
|
3540
|
+
await this.#joinNow(channel, connection);
|
|
3541
|
+
await this.#restore(channel, connection);
|
|
3542
|
+
return true;
|
|
3543
|
+
});
|
|
3544
|
+
channel._joinTail = run.catch(() => {
|
|
3545
|
+
});
|
|
3546
|
+
return run;
|
|
3547
|
+
}
|
|
3548
|
+
async #joinNow(channel, connection) {
|
|
3341
3549
|
const ref = this.#nextRef();
|
|
3342
3550
|
channel.joinRef = ref;
|
|
3343
3551
|
channel._resetForRejoin();
|
|
3344
|
-
|
|
3552
|
+
channel._endedJoin = null;
|
|
3345
3553
|
const reply = await this._request(channel.topic, "phx_join", channel.joinPayload, ref, void 0, ref);
|
|
3554
|
+
const ended = channel._endedJoin;
|
|
3555
|
+
if (ended && ended.joinRef === ref) {
|
|
3556
|
+
channel._endedJoin = null;
|
|
3557
|
+
throw joinInterrupted(channel, ended.event);
|
|
3558
|
+
}
|
|
3346
3559
|
channel.reply = reply && typeof reply === "object" && !Array.isArray(reply) ? reply : { response: reply };
|
|
3347
3560
|
if (channel.name === "market") channel.reply = convertMarketChannelPayload(channel.reply);
|
|
3561
|
+
channel._joinedConnection = connection;
|
|
3348
3562
|
channel.joined = true;
|
|
3349
|
-
|
|
3563
|
+
}
|
|
3564
|
+
async #restore(channel, connection) {
|
|
3565
|
+
if (channel.watches.length) {
|
|
3566
|
+
await channel.push("watch", [...channel.watches]);
|
|
3567
|
+
if (channel.closed || !channel.joined || channel._joinedConnection !== connection) {
|
|
3568
|
+
throw joinInterrupted(channel, "phx_close");
|
|
3569
|
+
}
|
|
3570
|
+
}
|
|
3350
3571
|
channel._startPinger();
|
|
3572
|
+
channel._restoredConnection = connection;
|
|
3573
|
+
}
|
|
3574
|
+
#finishMarket(channel) {
|
|
3575
|
+
channel._finish();
|
|
3576
|
+
if (this.channels.get(channel.topic) === channel) this.channels.delete(channel.topic);
|
|
3351
3577
|
}
|
|
3352
3578
|
/** @internal */
|
|
3353
3579
|
async _leave(channel) {
|
|
@@ -3384,12 +3610,12 @@ var STXWebSocket = (_class6 = class {
|
|
|
3384
3610
|
if (!(err instanceof STXTransportException)) return false;
|
|
3385
3611
|
if (err.statusCode !== 401 && err.statusCode !== 403) return false;
|
|
3386
3612
|
const auth = this.rest.auth;
|
|
3387
|
-
if (!_optionalChain([auth, 'optionalAccess',
|
|
3613
|
+
if (!_optionalChain([auth, 'optionalAccess', _48 => _48.onUnauthorized])) return false;
|
|
3388
3614
|
return auth.onUnauthorized();
|
|
3389
3615
|
}
|
|
3390
3616
|
async #open(reconnect = false) {
|
|
3391
3617
|
const headers = { "User-Agent": USER_AGENT };
|
|
3392
|
-
if (_optionalChain([this, 'access',
|
|
3618
|
+
if (_optionalChain([this, 'access', _49 => _49.rest, 'access', _50 => _50.auth, 'optionalAccess', _51 => _51.websocketHeaders])) Object.assign(headers, await this.rest.auth.websocketHeaders({ reconnect }));
|
|
3393
3619
|
const conn = new (0, _ws2.default)(this.url, {
|
|
3394
3620
|
headers,
|
|
3395
3621
|
rejectUnauthorized: this.rest.verifyTls,
|
|
@@ -3402,8 +3628,10 @@ var STXWebSocket = (_class6 = class {
|
|
|
3402
3628
|
};
|
|
3403
3629
|
const onUnexpected = (_req, res) => {
|
|
3404
3630
|
cleanup();
|
|
3631
|
+
conn.on("error", () => {
|
|
3632
|
+
});
|
|
3405
3633
|
conn.terminate();
|
|
3406
|
-
const reason = _optionalChain([res, 'access',
|
|
3634
|
+
const reason = _optionalChain([res, 'access', _52 => _52.headers, 'optionalAccess', _53 => _53["x-stx-error"]]);
|
|
3407
3635
|
reject(
|
|
3408
3636
|
new STXTransportException(
|
|
3409
3637
|
`Could not open ${this.url}: HTTP ${res.statusCode}${reason ? ` (${String(reason)})` : ""}`,
|
|
@@ -3428,6 +3656,7 @@ var STXWebSocket = (_class6 = class {
|
|
|
3428
3656
|
conn.on("message", (data) => this.#onFrame(data.toString()));
|
|
3429
3657
|
conn.on("close", () => this.#onConnClose(conn));
|
|
3430
3658
|
this.#conn = conn;
|
|
3659
|
+
this.#connection += 1;
|
|
3431
3660
|
this.#pendingHeartbeat = null;
|
|
3432
3661
|
this.#startHeartbeat();
|
|
3433
3662
|
this.logger.debug(`connected to ${this.url}`);
|
|
@@ -3511,15 +3740,29 @@ var STXWebSocket = (_class6 = class {
|
|
|
3511
3740
|
}
|
|
3512
3741
|
const channel = this.channels.get(topic);
|
|
3513
3742
|
if (!channel) return;
|
|
3514
|
-
if (joinRef !== null && joinRef !== void 0 && channel.joinRef !== null && String(joinRef) !== channel.joinRef) {
|
|
3515
|
-
return;
|
|
3516
|
-
}
|
|
3517
3743
|
if (event === "phx_error" || event === "phx_close") {
|
|
3518
|
-
if (
|
|
3519
|
-
|
|
3520
|
-
|
|
3521
|
-
|
|
3744
|
+
if (joinRef === null || joinRef === void 0 || String(joinRef) !== channel.joinRef) return;
|
|
3745
|
+
if (channel.closed || this.#closed) return;
|
|
3746
|
+
if (!channel.joined) {
|
|
3747
|
+
channel._endedJoin = { joinRef: String(joinRef), event };
|
|
3748
|
+
const pending = this.#pending.get(String(joinRef));
|
|
3749
|
+
if (_optionalChain([pending, 'optionalAccess', _54 => _54.event]) === "phx_join") pending.reject(joinInterrupted(channel, event));
|
|
3750
|
+
if (event === "phx_close" && channel.name === "market") this.#finishMarket(channel);
|
|
3751
|
+
return;
|
|
3522
3752
|
}
|
|
3753
|
+
for (const pending of [...this.#pending.values()]) {
|
|
3754
|
+
if (pending.topic === channel.topic) pending.reject(joinInterrupted(channel, event));
|
|
3755
|
+
}
|
|
3756
|
+
if (event === "phx_close" && channel.name === "market") {
|
|
3757
|
+
this.#finishMarket(channel);
|
|
3758
|
+
return;
|
|
3759
|
+
}
|
|
3760
|
+
this.logger.warn(`${topic}: server sent ${event}; rejoining`);
|
|
3761
|
+
channel._resetForRejoin();
|
|
3762
|
+
void this.#rejoinLater(channel, true);
|
|
3763
|
+
return;
|
|
3764
|
+
}
|
|
3765
|
+
if (joinRef !== null && joinRef !== void 0 && channel.joinRef !== null && String(joinRef) !== channel.joinRef) {
|
|
3523
3766
|
return;
|
|
3524
3767
|
}
|
|
3525
3768
|
if (channel.name === "markets") payload = convertMarketsFrame(payload);
|
|
@@ -3537,18 +3780,26 @@ var STXWebSocket = (_class6 = class {
|
|
|
3537
3780
|
)
|
|
3538
3781
|
);
|
|
3539
3782
|
}
|
|
3540
|
-
|
|
3783
|
+
/**
|
|
3784
|
+
* Rejoin `channel` with backoff. `serverClosed`: the server closed or
|
|
3785
|
+
* errored it while the socket stayed up (counted in `channelRejoins`);
|
|
3786
|
+
* otherwise a rejoin refused during a socket reconnect is being retried.
|
|
3787
|
+
*/
|
|
3788
|
+
async #rejoinLater(channel, serverClosed) {
|
|
3541
3789
|
let attempt = 1;
|
|
3542
3790
|
while (!channel.closed && !this.#closed) {
|
|
3543
3791
|
await sleep2(this.reconnectPolicy.delayMs(attempt));
|
|
3544
3792
|
if (!this.connected) return;
|
|
3545
3793
|
try {
|
|
3546
|
-
await this.#join(channel)
|
|
3794
|
+
if (await this.#join(channel) && channel.joined && !channel.closed) {
|
|
3795
|
+
if (serverClosed) this.channelRejoins += 1;
|
|
3796
|
+
await this.#raiseReconnect();
|
|
3797
|
+
}
|
|
3547
3798
|
return;
|
|
3548
3799
|
} catch (err) {
|
|
3549
3800
|
this.logger.error(`rejoin ${channel.topic} failed: ${err.message}`);
|
|
3550
3801
|
const reply = err instanceof STXChannelException ? err.reply : void 0;
|
|
3551
|
-
if (_optionalChain([reply, 'optionalAccess',
|
|
3802
|
+
if (_optionalChain([reply, 'optionalAccess', _55 => _55.reason]) === "unauthorized" || _optionalChain([reply, 'optionalAccess', _56 => _56.reason]) === COMBOS_UNAVAILABLE_REASON && COMBO_CHANNELS.has(channel.name)) {
|
|
3552
3803
|
channel._close();
|
|
3553
3804
|
return;
|
|
3554
3805
|
}
|
|
@@ -3562,7 +3813,7 @@ var STXWebSocket = (_class6 = class {
|
|
|
3562
3813
|
if (!this.connected) return;
|
|
3563
3814
|
if (this.#pendingHeartbeat !== null) {
|
|
3564
3815
|
this.logger.warn("heartbeat unanswered; reconnecting");
|
|
3565
|
-
_optionalChain([this, 'access',
|
|
3816
|
+
_optionalChain([this, 'access', _57 => _57.#conn, 'optionalAccess', _58 => _58.terminate, 'call', _59 => _59()]);
|
|
3566
3817
|
return;
|
|
3567
3818
|
}
|
|
3568
3819
|
const ref = this.#nextRef();
|
|
@@ -3570,7 +3821,7 @@ var STXWebSocket = (_class6 = class {
|
|
|
3570
3821
|
try {
|
|
3571
3822
|
this.#send([null, ref, PHOENIX_TOPIC, "heartbeat", {}]);
|
|
3572
3823
|
} catch (e13) {
|
|
3573
|
-
_optionalChain([this, 'access',
|
|
3824
|
+
_optionalChain([this, 'access', _60 => _60.#conn, 'optionalAccess', _61 => _61.terminate, 'call', _62 => _62()]);
|
|
3574
3825
|
}
|
|
3575
3826
|
}, this.heartbeatIntervalMs);
|
|
3576
3827
|
}
|
|
@@ -3593,6 +3844,8 @@ var STXWebSocket = (_class6 = class {
|
|
|
3593
3844
|
}
|
|
3594
3845
|
async #reconnectLoop() {
|
|
3595
3846
|
this.#reconnecting = true;
|
|
3847
|
+
let finished;
|
|
3848
|
+
this.#reconnectDone = new Promise((r) => finished = r);
|
|
3596
3849
|
let ok = false;
|
|
3597
3850
|
try {
|
|
3598
3851
|
let attempt = 1;
|
|
@@ -3614,13 +3867,13 @@ var STXWebSocket = (_class6 = class {
|
|
|
3614
3867
|
} catch (err) {
|
|
3615
3868
|
if (!(err instanceof STXChannelException)) throw err;
|
|
3616
3869
|
this.logger.error(`rejoin ${channel.topic} failed: ${err.message}; retrying`);
|
|
3617
|
-
void this.#rejoinLater(channel);
|
|
3870
|
+
void this.#rejoinLater(channel, false);
|
|
3618
3871
|
}
|
|
3619
3872
|
}
|
|
3620
3873
|
this.reconnects += 1;
|
|
3621
3874
|
this.logger.info(`reconnected (${this.reconnects})`);
|
|
3622
3875
|
ok = true;
|
|
3623
|
-
|
|
3876
|
+
void this.#raiseReconnect();
|
|
3624
3877
|
return;
|
|
3625
3878
|
} catch (err) {
|
|
3626
3879
|
this.#closeConn();
|
|
@@ -3636,17 +3889,26 @@ var STXWebSocket = (_class6 = class {
|
|
|
3636
3889
|
}
|
|
3637
3890
|
} finally {
|
|
3638
3891
|
this.#reconnecting = false;
|
|
3892
|
+
finished();
|
|
3639
3893
|
if (ok && !this.#closed && !this.connected) {
|
|
3640
3894
|
for (const channel of this.channels.values()) channel._resetForRejoin();
|
|
3641
3895
|
void this.#reconnectLoop();
|
|
3642
3896
|
}
|
|
3643
3897
|
}
|
|
3644
3898
|
}
|
|
3899
|
+
async #raiseReconnect() {
|
|
3900
|
+
if (!this.onReconnect) return;
|
|
3901
|
+
try {
|
|
3902
|
+
await this.onReconnect();
|
|
3903
|
+
} catch (err) {
|
|
3904
|
+
this.logger.error("onReconnect threw", err);
|
|
3905
|
+
}
|
|
3906
|
+
}
|
|
3645
3907
|
#failAuth(err) {
|
|
3646
3908
|
this.error = err;
|
|
3647
3909
|
this.#shutdownAfterDrop();
|
|
3648
3910
|
try {
|
|
3649
|
-
_optionalChain([this, 'access',
|
|
3911
|
+
_optionalChain([this, 'access', _63 => _63.onAuthError, 'optionalCall', _64 => _64(err)]);
|
|
3650
3912
|
} catch (hookErr) {
|
|
3651
3913
|
this.logger.error("onAuthError threw", hookErr);
|
|
3652
3914
|
}
|
|
@@ -3663,6 +3925,12 @@ var STXWebSocket = (_class6 = class {
|
|
|
3663
3925
|
for (const w of waiters) w();
|
|
3664
3926
|
}
|
|
3665
3927
|
}, _class6);
|
|
3928
|
+
function joinInterrupted(channel, event) {
|
|
3929
|
+
return new STXChannelException(`${event} on ${channel.topic} while joining`, {
|
|
3930
|
+
topic: channel.topic,
|
|
3931
|
+
reply: { reason: event }
|
|
3932
|
+
});
|
|
3933
|
+
}
|
|
3666
3934
|
function dropUndefined(payload) {
|
|
3667
3935
|
return Object.fromEntries(
|
|
3668
3936
|
Object.entries(payload).filter(([, v]) => v !== void 0).map(([k, v]) => [k, Array.isArray(v) ? [...v] : v])
|
|
@@ -3743,5 +4011,8 @@ function dropUndefined(payload) {
|
|
|
3743
4011
|
|
|
3744
4012
|
|
|
3745
4013
|
|
|
3746
|
-
|
|
3747
|
-
|
|
4014
|
+
|
|
4015
|
+
|
|
4016
|
+
|
|
4017
|
+
exports.STXException = STXException; exports.STXConfigException = STXConfigException; exports.STXAPIException = STXAPIException; exports.STXValidationException = STXValidationException; exports.STXAuthenticationException = STXAuthenticationException; exports.STXForbiddenException = STXForbiddenException; exports.STXInvalidTokenException = STXInvalidTokenException; exports.STXInsufficientScopeException = STXInsufficientScopeException; exports.STXTermsRequiredException = STXTermsRequiredException; exports.STXIPNotAllowedException = STXIPNotAllowedException; exports.STXBlockedException = STXBlockedException; exports.STXRestrictedJurisdictionException = STXRestrictedJurisdictionException; exports.STXUnusualNetworkException = STXUnusualNetworkException; exports.STXNotFoundException = STXNotFoundException; exports.STXRejectedException = STXRejectedException; exports.STXFillModeNotAllowedException = STXFillModeNotAllowedException; exports.STXPostOnlyWouldMatchException = STXPostOnlyWouldMatchException; exports.STXRateLimitException = STXRateLimitException; exports.STXServerException = STXServerException; exports.STXTransportException = STXTransportException; exports.STXChannelException = STXChannelException; exports.STXTimeoutException = STXTimeoutException; exports.notAvailableMessage = notAvailableMessage; exports.STXNotAvailableException = STXNotAvailableException; exports.STXCombosUnavailableException = STXCombosUnavailableException; exports.isEdgeBlock = isEdgeBlock; exports.STXComboRefusedException = STXComboRefusedException; exports.STXComboPriceMovedException = STXComboPriceMovedException; exports.errorForStatus = errorForStatus; exports.FEATURES = FEATURES; exports.Capabilities = Capabilities; exports.Region = Region; exports.Environment = Environment; exports.Environments = Environments; exports.HOSTS = HOSTS; exports.environmentNamed = environmentNamed; exports.resolveHost = resolveHost; exports.baseUrlFor = baseUrlFor; exports.socketUrlFor = socketUrlFor; exports.OPERATIONS = OPERATIONS; exports.Stats = Stats; exports.MAX_MARKETS_PER_REQUEST = MAX_MARKETS_PER_REQUEST; exports.isValidLine = isValidLine; exports.Page = Page; exports.RetryPolicy = RetryPolicy; exports.NO_RETRY = NO_RETRY; exports.resolveSettings = resolveSettings; exports.KEY_HEADER = KEY_HEADER; exports.TIMESTAMP_HEADER = TIMESTAMP_HEADER; exports.SIGNATURE_HEADER = SIGNATURE_HEADER; exports.buildMessage = buildMessage; exports.requestPath = requestPath; exports.handshakePath = handshakePath; exports.loadPrivateKey = loadPrivateKey; exports.signerFromPrivateKey = signerFromPrivateKey; exports.ApiKeyCredentials = ApiKeyCredentials; exports.VERSION = VERSION; exports.USER_AGENT = USER_AGENT; exports.TERMINAL_ORDER_STATUSES = TERMINAL_ORDER_STATUSES; exports.AccountView = AccountView; exports.ComboPlayer = ComboPlayer; exports.ComboMaker = ComboMaker; exports.centsToDollars = centsToDollars; exports.toDollarString = toDollarString; exports.toQuantity = toQuantity; exports.convertMarketPayload = convertMarketPayload; exports.convertMarketsFrame = convertMarketsFrame; exports.convertBook = convertBook; exports.convertMarketChannelPayload = convertMarketChannelPayload; exports.SNAPSHOT_EVENTS = SNAPSHOT_EVENTS; exports.ChannelMessage = ChannelMessage; exports.ReconnectPolicy = ReconnectPolicy; exports.Channel = Channel; exports.STXWebSocket = STXWebSocket; exports.orderBody = orderBody; exports.STX = STX;
|
|
4018
|
+
//# sourceMappingURL=chunk-BSX65XEA.cjs.map
|