@stxapp/stx-typescript 0.9.0-alpha.1 → 0.10.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 +69 -16
- package/README.md +27 -24
- package/dist/{chunk-33AQCUGM.cjs → chunk-42OCIF3G.cjs} +988 -225
- package/dist/chunk-42OCIF3G.cjs.map +1 -0
- package/dist/{chunk-4CSBA2YV.js → chunk-FTZCBXT7.js} +929 -166
- package/dist/chunk-FTZCBXT7.js.map +1 -0
- package/dist/{client-CNkaTuhG.d.ts → client-DJr0UUvB.d.cts} +671 -148
- package/dist/{client-CNkaTuhG.d.cts → client-DJr0UUvB.d.ts} +671 -148
- package/dist/index.cjs +20 -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 +23 -5
- package/dist/oauth.cjs +244 -107
- package/dist/oauth.cjs.map +1 -1
- package/dist/oauth.d.cts +115 -15
- package/dist/oauth.d.ts +115 -15
- package/dist/oauth.js +206 -69
- package/dist/oauth.js.map +1 -1
- package/package.json +1 -1
- package/dist/chunk-33AQCUGM.cjs.map +0 -1
- package/dist/chunk-4CSBA2YV.js.map +0 -1
|
@@ -1,39 +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;// src/
|
|
2
|
-
var Region = {
|
|
3
|
-
US: "us",
|
|
4
|
-
ONTARIO: "ontario"
|
|
5
|
-
};
|
|
6
|
-
var Environment = {
|
|
7
|
-
PRODUCTION: "production",
|
|
8
|
-
DEMO: "demo"
|
|
9
|
-
};
|
|
10
|
-
|
|
11
|
-
// src/geo.ts
|
|
12
|
-
var IP_NOT_ALLOWED = /from this IP address (\S+?) is disallowed/i;
|
|
13
|
-
function geoRejection(message) {
|
|
14
|
-
const ip = IP_NOT_ALLOWED.exec(message);
|
|
15
|
-
if (ip) return { reason: "ip_not_allowed", ipAddress: ip[1] };
|
|
16
|
-
if (/geo location check was not done by this user|unknown user in geocomply/i.test(message)) {
|
|
17
|
-
return { reason: "packet_other_user" };
|
|
18
|
-
}
|
|
19
|
-
if (/IP address doesn't match geo location/i.test(message)) {
|
|
20
|
-
return { reason: "packet_ip_mismatch" };
|
|
21
|
-
}
|
|
22
|
-
if (/geo ?location package is invalid|geocomply location response|unable to find expected tag/i.test(message)) {
|
|
23
|
-
return { reason: "packet_invalid" };
|
|
24
|
-
}
|
|
25
|
-
if (/invalid geo ?location|geo[- ]?(location|fenc)/i.test(message)) {
|
|
26
|
-
return { reason: "location_not_allowed" };
|
|
27
|
-
}
|
|
28
|
-
return void 0;
|
|
29
|
-
}
|
|
30
|
-
async function resolveGeoLocation(provider) {
|
|
31
|
-
if (provider === void 0 || provider === null) return void 0;
|
|
32
|
-
const value = typeof provider === "function" ? await provider() : provider;
|
|
33
|
-
return value === null || value === void 0 || value === "" ? void 0 : value;
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
// 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(); } } 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/exceptions.ts
|
|
37
2
|
var STXException = class extends Error {
|
|
38
3
|
|
|
39
4
|
|
|
@@ -68,19 +33,20 @@ var STXInvalidTokenException = class extends STXAuthenticationException {
|
|
|
68
33
|
};
|
|
69
34
|
var STXInsufficientScopeException = class extends STXForbiddenException {
|
|
70
35
|
};
|
|
71
|
-
var
|
|
72
|
-
|
|
73
|
-
var STXRejectedException = class extends STXAPIException {
|
|
74
|
-
};
|
|
75
|
-
var STXGeoLocationException = class extends STXRejectedException {
|
|
36
|
+
var STXTermsRequiredException = class extends STXForbiddenException {
|
|
37
|
+
/** The STX page where the member accepts the terms, when the answer names it. */
|
|
76
38
|
|
|
77
|
-
|
|
78
|
-
constructor(message, rejection, opts = {}) {
|
|
39
|
+
constructor(message, opts = {}) {
|
|
79
40
|
super(message, opts);
|
|
80
|
-
this.
|
|
81
|
-
this.ipAddress = rejection.ipAddress;
|
|
41
|
+
this.termsUrl = opts.termsUrl;
|
|
82
42
|
}
|
|
83
43
|
};
|
|
44
|
+
var STXIPNotAllowedException = class extends STXForbiddenException {
|
|
45
|
+
};
|
|
46
|
+
var STXNotFoundException = class extends STXAPIException {
|
|
47
|
+
};
|
|
48
|
+
var STXRejectedException = class extends STXAPIException {
|
|
49
|
+
};
|
|
84
50
|
var STXRateLimitException = class extends STXAPIException {
|
|
85
51
|
|
|
86
52
|
constructor(message, opts = {}) {
|
|
@@ -114,6 +80,88 @@ var STXChannelException = class extends STXException {
|
|
|
114
80
|
};
|
|
115
81
|
var STXTimeoutException = class extends STXChannelException {
|
|
116
82
|
};
|
|
83
|
+
var NOT_AVAILABLE = /* @__PURE__ */ Symbol.for("@stxapp/stx-typescript.notAvailable");
|
|
84
|
+
var FEATURE_PHRASES = {
|
|
85
|
+
oauth: "OAuth is",
|
|
86
|
+
"oauth.member": "Member sign-in with OAuth is",
|
|
87
|
+
"oauth.app": "App tokens are",
|
|
88
|
+
connect: "Sign in with STX is",
|
|
89
|
+
"terms.stx_page": "Accepting terms on an STX page is",
|
|
90
|
+
"markets.create": "Creating markets is",
|
|
91
|
+
market_types: "Market types are",
|
|
92
|
+
event_players: "Event players are",
|
|
93
|
+
leaderboard: "The leaderboard is",
|
|
94
|
+
loyalty: "The loyalty program is",
|
|
95
|
+
combos: "Combos are"
|
|
96
|
+
};
|
|
97
|
+
function notAvailableMessage(feature, host) {
|
|
98
|
+
const phrase = feature.startsWith("scope:") ? `The ${feature.slice("scope:".length)} scope is` : _nullishCoalesce(FEATURE_PHRASES[feature], () => ( `${feature} is`));
|
|
99
|
+
return `${phrase} not available on ${host} yet.`;
|
|
100
|
+
}
|
|
101
|
+
var STXNotAvailableException = class _STXNotAvailableException extends STXAPIException {
|
|
102
|
+
/** The feature id, e.g. `"combos"`. */
|
|
103
|
+
|
|
104
|
+
/** The exchange host that lacks it, e.g. `"demo.stxapp.ca"`. */
|
|
105
|
+
|
|
106
|
+
constructor(feature, host, opts = {}) {
|
|
107
|
+
super(_nullishCoalesce(opts.message, () => ( notAvailableMessage(feature, host))), opts);
|
|
108
|
+
this.feature = feature;
|
|
109
|
+
this.host = host;
|
|
110
|
+
markNotAvailable(this);
|
|
111
|
+
}
|
|
112
|
+
// `this` is the class on the right of `instanceof`: a subclass keeps the
|
|
113
|
+
// ordinary check, only the base class also accepts marked exceptions.
|
|
114
|
+
static [Symbol.hasInstance](value) {
|
|
115
|
+
const cls = this;
|
|
116
|
+
if (Function.prototype[Symbol.hasInstance].call(cls, value)) return true;
|
|
117
|
+
return cls === _STXNotAvailableException && typeof value === "object" && value !== null && value[NOT_AVAILABLE] === true;
|
|
118
|
+
}
|
|
119
|
+
};
|
|
120
|
+
function markNotAvailable(err) {
|
|
121
|
+
Object.defineProperty(err, NOT_AVAILABLE, { value: true, enumerable: false });
|
|
122
|
+
}
|
|
123
|
+
var STXCombosUnavailableException = (_class = class extends STXChannelException {
|
|
124
|
+
__init() {this.feature = "combos"}
|
|
125
|
+
/** The exchange host that lacks combos. */
|
|
126
|
+
|
|
127
|
+
constructor(message, opts = {}) {
|
|
128
|
+
super(message, opts);_class.prototype.__init.call(this);;
|
|
129
|
+
this.host = _nullishCoalesce(opts.host, () => ( ""));
|
|
130
|
+
markNotAvailable(this);
|
|
131
|
+
}
|
|
132
|
+
}, _class);
|
|
133
|
+
function isMissingRoute(err) {
|
|
134
|
+
if (!(err instanceof STXNotFoundException)) return false;
|
|
135
|
+
const body = err.body;
|
|
136
|
+
return !!body && typeof body === "object" && body.error === "not_found" && Object.keys(body).length === 1;
|
|
137
|
+
}
|
|
138
|
+
function isEdgeBlock(status, text) {
|
|
139
|
+
if (status !== 403) return false;
|
|
140
|
+
try {
|
|
141
|
+
JSON.parse(text);
|
|
142
|
+
return false;
|
|
143
|
+
} catch (e2) {
|
|
144
|
+
return true;
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
var STXComboRefusedException = class extends STXChannelException {
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
constructor(message, opts) {
|
|
152
|
+
super(message, opts);
|
|
153
|
+
this.command = opts.command;
|
|
154
|
+
this.code = opts.code;
|
|
155
|
+
this.detail = opts.detail;
|
|
156
|
+
}
|
|
157
|
+
};
|
|
158
|
+
var STXComboPriceMovedException = class extends STXComboRefusedException {
|
|
159
|
+
|
|
160
|
+
constructor(message, opts) {
|
|
161
|
+
super(message, opts);
|
|
162
|
+
this.best = opts.best;
|
|
163
|
+
}
|
|
164
|
+
};
|
|
117
165
|
function errorForStatus(statusCode, body, opts) {
|
|
118
166
|
let message;
|
|
119
167
|
if (body && typeof body === "object" && typeof body.error === "string") {
|
|
@@ -130,6 +178,16 @@ function errorForStatus(statusCode, body, opts) {
|
|
|
130
178
|
case 401:
|
|
131
179
|
return bearerError(opts.wwwAuthenticate) === "invalid_token" ? new STXInvalidTokenException(message, base) : new STXAuthenticationException(message, base);
|
|
132
180
|
case 403: {
|
|
181
|
+
const fields = body && typeof body === "object" ? body : {};
|
|
182
|
+
if (fields.error === "ip_not_allowed") {
|
|
183
|
+
const description = typeof fields.error_description === "string" ? fields.error_description : message;
|
|
184
|
+
return new STXIPNotAllowedException(description, base);
|
|
185
|
+
}
|
|
186
|
+
if (fields.error === "terms_required") {
|
|
187
|
+
const description = typeof fields.error_description === "string" ? fields.error_description : message;
|
|
188
|
+
const termsUrl = typeof fields.terms_url === "string" ? fields.terms_url : void 0;
|
|
189
|
+
return new STXTermsRequiredException(description, { ...base, termsUrl });
|
|
190
|
+
}
|
|
133
191
|
if (bearerError(opts.wwwAuthenticate) === "insufficient_scope" || /insufficient scope/i.test(message)) {
|
|
134
192
|
return new STXInsufficientScopeException(message, {
|
|
135
193
|
...base,
|
|
@@ -140,10 +198,8 @@ function errorForStatus(statusCode, body, opts) {
|
|
|
140
198
|
}
|
|
141
199
|
case 404:
|
|
142
200
|
return new STXNotFoundException(message, base);
|
|
143
|
-
case 422:
|
|
144
|
-
|
|
145
|
-
return geo ? new STXGeoLocationException(message, geo, base) : new STXRejectedException(message, base);
|
|
146
|
-
}
|
|
201
|
+
case 422:
|
|
202
|
+
return new STXRejectedException(message, base);
|
|
147
203
|
case 429:
|
|
148
204
|
return new STXRateLimitException(message, { ...base, retryAfter: parseRetryAfter(opts.retryAfter) });
|
|
149
205
|
default:
|
|
@@ -168,6 +224,151 @@ function insufficientScopes(header, body) {
|
|
|
168
224
|
return raw ? raw.split(/\s+/).filter(Boolean) : [];
|
|
169
225
|
}
|
|
170
226
|
|
|
227
|
+
// src/capabilities.ts
|
|
228
|
+
var FEATURES = [
|
|
229
|
+
"oauth",
|
|
230
|
+
"oauth.member",
|
|
231
|
+
"oauth.app",
|
|
232
|
+
"connect",
|
|
233
|
+
"terms.stx_page",
|
|
234
|
+
"markets.create",
|
|
235
|
+
"market_types",
|
|
236
|
+
"event_players",
|
|
237
|
+
"leaderboard",
|
|
238
|
+
"loyalty",
|
|
239
|
+
"combos"
|
|
240
|
+
];
|
|
241
|
+
var MEMBER_SCOPES = [
|
|
242
|
+
"profile.read",
|
|
243
|
+
"balance.read",
|
|
244
|
+
"portfolio.read",
|
|
245
|
+
"orders.read",
|
|
246
|
+
"transfers.read",
|
|
247
|
+
"orders.write"
|
|
248
|
+
];
|
|
249
|
+
var Capabilities = class {
|
|
250
|
+
/** The exchange host, e.g. `"demo.stxapp.io"`. */
|
|
251
|
+
|
|
252
|
+
/** `GET /api_version`, e.g. `"3.3.196-rnd.9"`, or null when it did not answer. */
|
|
253
|
+
|
|
254
|
+
/** When the checks ran. */
|
|
255
|
+
|
|
256
|
+
/** The scopes the exchange's OAuth discovery document lists; empty without OAuth. */
|
|
257
|
+
|
|
258
|
+
/** Every feature and whether the exchange has it. */
|
|
259
|
+
|
|
260
|
+
constructor(init) {
|
|
261
|
+
this.host = init.host;
|
|
262
|
+
this.apiVersion = init.apiVersion;
|
|
263
|
+
this.checkedAt = init.checkedAt;
|
|
264
|
+
this.scopesSupported = init.scopesSupported;
|
|
265
|
+
this.features = init.features;
|
|
266
|
+
}
|
|
267
|
+
/** True only when the exchange is known to have `feature`. */
|
|
268
|
+
has(feature) {
|
|
269
|
+
return this.features[feature] === true;
|
|
270
|
+
}
|
|
271
|
+
/**
|
|
272
|
+
* Throw `STXNotAvailableException` unless the exchange is known to have
|
|
273
|
+
* `feature`. A feature that could not be checked (`null`) does not throw:
|
|
274
|
+
* the call itself will say.
|
|
275
|
+
*/
|
|
276
|
+
require(feature) {
|
|
277
|
+
if (this.features[feature] === false) throw new STXNotAvailableException(feature, this.host);
|
|
278
|
+
}
|
|
279
|
+
toJSON() {
|
|
280
|
+
return {
|
|
281
|
+
host: this.host,
|
|
282
|
+
apiVersion: this.apiVersion,
|
|
283
|
+
checkedAt: this.checkedAt.toISOString(),
|
|
284
|
+
scopesSupported: this.scopesSupported,
|
|
285
|
+
features: this.features
|
|
286
|
+
};
|
|
287
|
+
}
|
|
288
|
+
};
|
|
289
|
+
var NOBODY = "00000000-0000-0000-0000-000000000000";
|
|
290
|
+
function json(answer) {
|
|
291
|
+
if (!answer) return null;
|
|
292
|
+
try {
|
|
293
|
+
const parsed = JSON.parse(answer.text);
|
|
294
|
+
return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : null;
|
|
295
|
+
} catch (e3) {
|
|
296
|
+
return null;
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
function strings(value) {
|
|
300
|
+
return Array.isArray(value) ? value.filter((v) => typeof v === "string") : [];
|
|
301
|
+
}
|
|
302
|
+
function missingRoute(answer) {
|
|
303
|
+
if (!answer || answer.status !== 404) return false;
|
|
304
|
+
const body = json(answer);
|
|
305
|
+
return !!body && body.error === "not_found" && Object.keys(body).length === 1;
|
|
306
|
+
}
|
|
307
|
+
function oauthMetadataFrom(answer) {
|
|
308
|
+
if (!answer) return null;
|
|
309
|
+
const body = json(answer);
|
|
310
|
+
if (answer.status === 404) return false;
|
|
311
|
+
if (answer.status === 403 && !body) return false;
|
|
312
|
+
if (answer.status !== 200 || !body) return null;
|
|
313
|
+
if (typeof body.issuer !== "string" || typeof body.authorization_endpoint !== "string" || typeof body.token_endpoint !== "string") {
|
|
314
|
+
return null;
|
|
315
|
+
}
|
|
316
|
+
return body;
|
|
317
|
+
}
|
|
318
|
+
async function discoverCapabilities(probes) {
|
|
319
|
+
const swallow = (p) => p ? p.catch(() => null) : Promise.resolve(null);
|
|
320
|
+
const [version, discovery, types, players, board, loyalty, combos] = await Promise.all([
|
|
321
|
+
swallow(probes.get("/api_version")),
|
|
322
|
+
swallow(probes.get("/.well-known/oauth-authorization-server")),
|
|
323
|
+
swallow(probes.signedGet("/api/v1/types")),
|
|
324
|
+
swallow(probes.signedGet(`/api/v1/events/${NOBODY}/players`)),
|
|
325
|
+
swallow(probes.signedGet("/api/v1/leaderboard?limit=1")),
|
|
326
|
+
swallow(probes.signedGet("/api/v1/portfolio/loyalty?limit=1")),
|
|
327
|
+
swallow(probes.joinReason(`rfq:${NOBODY}`))
|
|
328
|
+
]);
|
|
329
|
+
const apiVersion = _optionalChain([json, 'call', _5 => _5(version), 'optionalAccess', _6 => _6.api_version]);
|
|
330
|
+
const meta = oauthMetadataFrom(discovery);
|
|
331
|
+
const scopes = meta ? strings(meta.scopes_supported) : [];
|
|
332
|
+
const grants = meta ? strings(meta.grant_types_supported) : [];
|
|
333
|
+
const fromMeta = (decide) => meta === null ? null : meta === false ? false : decide();
|
|
334
|
+
const oauth = fromMeta(() => true);
|
|
335
|
+
const member = fromMeta(() => grants.includes("authorization_code") && scopes.some((s) => MEMBER_SCOPES.includes(s)));
|
|
336
|
+
const app = fromMeta(() => grants.includes("client_credentials"));
|
|
337
|
+
const features = {
|
|
338
|
+
oauth,
|
|
339
|
+
"oauth.member": member,
|
|
340
|
+
"oauth.app": app,
|
|
341
|
+
connect: fromMeta(() => scopes.includes("openid")),
|
|
342
|
+
"terms.stx_page": fromMeta(() => member === true && !scopes.includes("terms.write")),
|
|
343
|
+
"markets.create": fromMeta(() => app === true && scopes.includes("markets.write")),
|
|
344
|
+
market_types: types === null ? null : types.status >= 200 && types.status < 300 ? true : missingRoute(types) ? false : null,
|
|
345
|
+
// A 404 about the event (not about the route) means the route is there.
|
|
346
|
+
event_players: players === null ? null : missingRoute(players) ? false : players.status === 404 || players.status < 300 ? true : null,
|
|
347
|
+
// Switched off answers 404 too ("Leaderboard is not enabled").
|
|
348
|
+
leaderboard: board === null ? null : board.status >= 200 && board.status < 300 ? true : board.status === 404 ? false : null,
|
|
349
|
+
// Switched off answers 404 ("Loyalty program is not enabled").
|
|
350
|
+
loyalty: loyalty === null ? null : loyalty.status >= 200 && loyalty.status < 300 ? true : loyalty.status === 404 ? false : null,
|
|
351
|
+
combos: combos === null ? null : combos !== "unmatched topic"
|
|
352
|
+
};
|
|
353
|
+
return new Capabilities({
|
|
354
|
+
host: probes.host,
|
|
355
|
+
apiVersion: typeof apiVersion === "string" ? apiVersion : null,
|
|
356
|
+
checkedAt: /* @__PURE__ */ new Date(),
|
|
357
|
+
scopesSupported: scopes,
|
|
358
|
+
features
|
|
359
|
+
});
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
// src/enums.ts
|
|
363
|
+
var Region = {
|
|
364
|
+
US: "us",
|
|
365
|
+
ONTARIO: "ontario"
|
|
366
|
+
};
|
|
367
|
+
var Environment = {
|
|
368
|
+
PRODUCTION: "production",
|
|
369
|
+
DEMO: "demo"
|
|
370
|
+
};
|
|
371
|
+
|
|
171
372
|
// src/config.ts
|
|
172
373
|
var Environments = {
|
|
173
374
|
/** United States demo. Shared by every integrator. No real money. */
|
|
@@ -249,7 +450,7 @@ function baseUrlFor(region, env, host) {
|
|
|
249
450
|
let parsed;
|
|
250
451
|
try {
|
|
251
452
|
parsed = new URL(h);
|
|
252
|
-
} catch (
|
|
453
|
+
} catch (e4) {
|
|
253
454
|
throw new STXConfigException(`Cannot parse host ${JSON.stringify(h)}.`);
|
|
254
455
|
}
|
|
255
456
|
return `${parsed.protocol}//${parsed.host}`;
|
|
@@ -641,16 +842,24 @@ function isValidLine(line) {
|
|
|
641
842
|
return typeof line === "number" && Number.isFinite(line) && line > 0 && line * 2 % 2 === 1;
|
|
642
843
|
}
|
|
643
844
|
function marketEntry(m) {
|
|
644
|
-
return
|
|
845
|
+
return { rule: _nullishCoalesce(m.rule, () => ( "player_stat_line")), player_id: m.playerId, stat: m.stat, line: m.line };
|
|
645
846
|
}
|
|
646
|
-
function toCreateMarketResult(raw, index) {
|
|
647
|
-
|
|
847
|
+
function toCreateMarketResult(raw, m, index) {
|
|
848
|
+
const market = marketEntry(m);
|
|
849
|
+
switch (raw.status) {
|
|
850
|
+
case "created":
|
|
851
|
+
case "exists":
|
|
852
|
+
return { index, status: raw.status, market_id: String(raw.market_id), reason: null, market };
|
|
853
|
+
case "valid":
|
|
854
|
+
return { index, status: "valid", market_id: null, reason: null, market };
|
|
855
|
+
default:
|
|
856
|
+
return rejected(m, index, _nullishCoalesce(raw.reason, () => ( "not_created")));
|
|
857
|
+
}
|
|
648
858
|
}
|
|
649
|
-
function rejected(index, reason) {
|
|
650
|
-
return { index, status: "rejected", market_id: null, reason };
|
|
859
|
+
function rejected(m, index, reason) {
|
|
860
|
+
return { index, status: "rejected", market_id: null, reason, market: marketEntry(m) };
|
|
651
861
|
}
|
|
652
862
|
function checkMarket(m, players) {
|
|
653
|
-
if (m.rule !== "player_stat_line") return { market: m };
|
|
654
863
|
if (!isValidLine(m.line)) return { reason: "invalid_line" };
|
|
655
864
|
const stat = players.stats.find((s) => String(s.stat).toUpperCase() === String(m.stat).toUpperCase());
|
|
656
865
|
if (!stat) return { reason: "unsupported_stat" };
|
|
@@ -775,7 +984,7 @@ function parseIni(text) {
|
|
|
775
984
|
function readProfile(profileName, path) {
|
|
776
985
|
try {
|
|
777
986
|
if (!_fs.statSync.call(void 0, path).isFile()) return [{}, false];
|
|
778
|
-
} catch (
|
|
987
|
+
} catch (e5) {
|
|
779
988
|
return [{}, false];
|
|
780
989
|
}
|
|
781
990
|
let sections;
|
|
@@ -795,7 +1004,7 @@ function readProfile(profileName, path) {
|
|
|
795
1004
|
}
|
|
796
1005
|
function processEnv() {
|
|
797
1006
|
const p = globalThis.process;
|
|
798
|
-
return _nullishCoalesce(_optionalChain([p, 'optionalAccess',
|
|
1007
|
+
return _nullishCoalesce(_optionalChain([p, 'optionalAccess', _7 => _7.env]), () => ( {}));
|
|
799
1008
|
}
|
|
800
1009
|
function resolveSettings(input = {}) {
|
|
801
1010
|
const environ = _nullishCoalesce(input.environ, () => ( processEnv()));
|
|
@@ -869,7 +1078,7 @@ function loadPrivateKey(value) {
|
|
|
869
1078
|
let isFile = false;
|
|
870
1079
|
try {
|
|
871
1080
|
isFile = _fs.statSync.call(void 0, path).isFile();
|
|
872
|
-
} catch (
|
|
1081
|
+
} catch (e6) {
|
|
873
1082
|
isFile = false;
|
|
874
1083
|
}
|
|
875
1084
|
if (!isFile) {
|
|
@@ -887,7 +1096,7 @@ function loadPrivateKey(value) {
|
|
|
887
1096
|
let key;
|
|
888
1097
|
try {
|
|
889
1098
|
key = _crypto.createPrivateKey.call(void 0, { key: Buffer.from(pem), format: "pem" });
|
|
890
|
-
} catch (
|
|
1099
|
+
} catch (e7) {
|
|
891
1100
|
throw new STXConfigException(
|
|
892
1101
|
"Private key is not valid PEM. Expected a PKCS#8 block beginning '-----BEGIN PRIVATE KEY-----'."
|
|
893
1102
|
);
|
|
@@ -904,11 +1113,11 @@ function signerFromPrivateKey(value) {
|
|
|
904
1113
|
const key = loadPrivateKey(value);
|
|
905
1114
|
return (message) => new Uint8Array(_crypto.sign.call(void 0, null, message, key));
|
|
906
1115
|
}
|
|
907
|
-
var ApiKeyCredentials = (
|
|
908
|
-
|
|
1116
|
+
var ApiKeyCredentials = (_class2 = class {
|
|
1117
|
+
__init2() {this.kind = "api_key"}
|
|
909
1118
|
|
|
910
1119
|
#sign;
|
|
911
|
-
constructor(keyId, privateKey, opts = {}) {;
|
|
1120
|
+
constructor(keyId, privateKey, opts = {}) {;_class2.prototype.__init2.call(this);
|
|
912
1121
|
if (!keyId || !String(keyId).trim()) throw new STXConfigException("API key id is required.");
|
|
913
1122
|
const signer = opts.signer;
|
|
914
1123
|
if (!signer && (privateKey === void 0 || privateKey === null)) {
|
|
@@ -951,7 +1160,7 @@ var ApiKeyCredentials = (_class = class {
|
|
|
951
1160
|
[/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")]() {
|
|
952
1161
|
return this.toString();
|
|
953
1162
|
}
|
|
954
|
-
},
|
|
1163
|
+
}, _class2);
|
|
955
1164
|
function credentialsFromSettings(keyId, privateKey, signer) {
|
|
956
1165
|
const hasMaterial = privateKey !== void 0 && privateKey !== null || signer !== void 0;
|
|
957
1166
|
if (!keyId && !hasMaterial) return void 0;
|
|
@@ -969,7 +1178,7 @@ function credentialsFromSettings(keyId, privateKey, signer) {
|
|
|
969
1178
|
}
|
|
970
1179
|
|
|
971
1180
|
// src/version.ts
|
|
972
|
-
var VERSION = "0.
|
|
1181
|
+
var VERSION = "0.10.0";
|
|
973
1182
|
var USER_AGENT = `stx-typescript/${VERSION}`;
|
|
974
1183
|
var ASYNC_DISPOSE = _nullishCoalesce(Symbol.asyncDispose, () => ( /* @__PURE__ */ Symbol.for("Symbol.asyncDispose")));
|
|
975
1184
|
|
|
@@ -988,13 +1197,13 @@ function stamp(item) {
|
|
|
988
1197
|
const t = Date.parse(String(_nullishCoalesce(_nullishCoalesce(item.time, () => ( item.inserted_at)), () => ( ""))));
|
|
989
1198
|
return Number.isNaN(t) ? 0 : t * 1e3;
|
|
990
1199
|
}
|
|
991
|
-
var AccountView = (
|
|
1200
|
+
var AccountView = (_class3 = class {
|
|
992
1201
|
|
|
993
1202
|
|
|
994
1203
|
/** The joined channels, by name. */
|
|
995
|
-
|
|
1204
|
+
__init3() {this.channels = {}}
|
|
996
1205
|
/** Join snapshots applied so far, per channel: 1 after the first seed, more after reconnects. */
|
|
997
|
-
|
|
1206
|
+
__init4() {this.seeds = { balances: 0, orders: 0, fills: 0, positions: 0 }}
|
|
998
1207
|
#balance = null;
|
|
999
1208
|
#orders = /* @__PURE__ */ new Map();
|
|
1000
1209
|
#fills = /* @__PURE__ */ new Map();
|
|
@@ -1003,7 +1212,7 @@ var AccountView = (_class2 = class {
|
|
|
1003
1212
|
#maxFills;
|
|
1004
1213
|
#closed = false;
|
|
1005
1214
|
/** @internal Use `ws.accountView()`. */
|
|
1006
|
-
constructor(ws, opts = {}) {;
|
|
1215
|
+
constructor(ws, opts = {}) {;_class3.prototype.__init3.call(this);_class3.prototype.__init4.call(this);
|
|
1007
1216
|
this.ws = ws;
|
|
1008
1217
|
this.onChange = opts.onChange;
|
|
1009
1218
|
this.#keepFlat = _nullishCoalesce(opts.keepFlatPositions, () => ( false));
|
|
@@ -1101,7 +1310,7 @@ var AccountView = (_class2 = class {
|
|
|
1101
1310
|
case "all_orders":
|
|
1102
1311
|
this.seeds.orders = (_nullishCoalesce(this.seeds.orders, () => ( 0))) + 1;
|
|
1103
1312
|
this.#orders.clear();
|
|
1104
|
-
for (const o of _nullishCoalesce(_optionalChain([payload, 'optionalAccess',
|
|
1313
|
+
for (const o of _nullishCoalesce(_optionalChain([payload, 'optionalAccess', _8 => _8.orders]), () => ( []))) this.#upsertOrder(o);
|
|
1105
1314
|
return change("orders", true);
|
|
1106
1315
|
case "new_open_order":
|
|
1107
1316
|
this.#upsertOrder(payload);
|
|
@@ -1109,7 +1318,7 @@ var AccountView = (_class2 = class {
|
|
|
1109
1318
|
case "all_trades":
|
|
1110
1319
|
this.seeds.fills = (_nullishCoalesce(this.seeds.fills, () => ( 0))) + 1;
|
|
1111
1320
|
this.#fills.clear();
|
|
1112
|
-
for (const t of _nullishCoalesce(_optionalChain([payload, 'optionalAccess',
|
|
1321
|
+
for (const t of _nullishCoalesce(_optionalChain([payload, 'optionalAccess', _9 => _9.trades]), () => ( []))) this.#upsertFill(t);
|
|
1113
1322
|
return change("fills", true);
|
|
1114
1323
|
case "trade":
|
|
1115
1324
|
this.#upsertFill(payload);
|
|
@@ -1117,22 +1326,22 @@ var AccountView = (_class2 = class {
|
|
|
1117
1326
|
case "all_positions":
|
|
1118
1327
|
this.seeds.positions = (_nullishCoalesce(this.seeds.positions, () => ( 0))) + 1;
|
|
1119
1328
|
this.#positions.clear();
|
|
1120
|
-
for (const p of _nullishCoalesce(_optionalChain([payload, 'optionalAccess',
|
|
1329
|
+
for (const p of _nullishCoalesce(_optionalChain([payload, 'optionalAccess', _10 => _10.positions]), () => ( []))) this.#upsertPosition(p);
|
|
1121
1330
|
return change("positions", true);
|
|
1122
1331
|
case "updated_positions":
|
|
1123
|
-
for (const p of _nullishCoalesce(_optionalChain([payload, 'optionalAccess',
|
|
1332
|
+
for (const p of _nullishCoalesce(_optionalChain([payload, 'optionalAccess', _11 => _11.positions]), () => ( []))) this.#upsertPosition(p);
|
|
1124
1333
|
return change("positions", false);
|
|
1125
1334
|
default:
|
|
1126
1335
|
return void 0;
|
|
1127
1336
|
}
|
|
1128
1337
|
}
|
|
1129
1338
|
#upsertOrder(order) {
|
|
1130
|
-
if (!_optionalChain([order, 'optionalAccess',
|
|
1339
|
+
if (!_optionalChain([order, 'optionalAccess', _12 => _12.id])) return;
|
|
1131
1340
|
if (TERMINAL_ORDER_STATUSES.has(String(order.status))) this.#orders.delete(order.id);
|
|
1132
1341
|
else this.#orders.set(order.id, order);
|
|
1133
1342
|
}
|
|
1134
1343
|
#upsertFill(fill) {
|
|
1135
|
-
if (!_optionalChain([fill, 'optionalAccess',
|
|
1344
|
+
if (!_optionalChain([fill, 'optionalAccess', _13 => _13.id])) return;
|
|
1136
1345
|
this.#fills.delete(fill.id);
|
|
1137
1346
|
this.#fills.set(fill.id, fill);
|
|
1138
1347
|
if (this.#fills.size > this.#maxFills) {
|
|
@@ -1141,7 +1350,7 @@ var AccountView = (_class2 = class {
|
|
|
1141
1350
|
}
|
|
1142
1351
|
}
|
|
1143
1352
|
#upsertPosition(position) {
|
|
1144
|
-
const key = _nullishCoalesce(_optionalChain([position, 'optionalAccess',
|
|
1353
|
+
const key = _nullishCoalesce(_optionalChain([position, 'optionalAccess', _14 => _14.market_id]), () => ( _optionalChain([position, 'optionalAccess', _15 => _15.id])));
|
|
1145
1354
|
if (!key) return;
|
|
1146
1355
|
if (!this.#keepFlat && isZero(position.position)) this.#positions.delete(key);
|
|
1147
1356
|
else this.#positions.set(key, position);
|
|
@@ -1154,7 +1363,296 @@ var AccountView = (_class2 = class {
|
|
|
1154
1363
|
CHANNELS.map((name) => this.channels[name]).filter((c) => c !== void 0 && !c.closed).map((c) => c.leave())
|
|
1155
1364
|
);
|
|
1156
1365
|
}
|
|
1157
|
-
},
|
|
1366
|
+
}, _class3);
|
|
1367
|
+
|
|
1368
|
+
// src/combos.ts
|
|
1369
|
+
var COMBO_PLAYER_CHANNEL = "rfq";
|
|
1370
|
+
var COMBO_MAKER_CHANNEL = "combo_quote";
|
|
1371
|
+
var UNAVAILABLE_REASON = "unmatched topic";
|
|
1372
|
+
var ACCEPT_TIMEOUT_MS = 35e3;
|
|
1373
|
+
var HISTORY_SIZE = 1e3;
|
|
1374
|
+
var PLAYER_EVENTS = /* @__PURE__ */ new Set(["best_quote", "placed", "negotiation_closed"]);
|
|
1375
|
+
var MAKER_EVENTS = /* @__PURE__ */ new Set([
|
|
1376
|
+
"rfq_opened",
|
|
1377
|
+
"rfq_closed",
|
|
1378
|
+
"quote_accepted",
|
|
1379
|
+
"placed",
|
|
1380
|
+
"negotiation_closed"
|
|
1381
|
+
]);
|
|
1382
|
+
function comboRefusal(command, topic, response, host = "") {
|
|
1383
|
+
const reply = response && typeof response === "object" ? response : {};
|
|
1384
|
+
const reason = typeof reply.reason === "string" ? reply.reason : void 0;
|
|
1385
|
+
if (reason === UNAVAILABLE_REASON) {
|
|
1386
|
+
return new STXCombosUnavailableException(notAvailableMessage("combos", host || "this exchange"), {
|
|
1387
|
+
topic,
|
|
1388
|
+
reply: response,
|
|
1389
|
+
host
|
|
1390
|
+
});
|
|
1391
|
+
}
|
|
1392
|
+
if (reason === void 0) {
|
|
1393
|
+
return new STXComboRefusedException(`${command} on ${topic} failed: ${JSON.stringify(response)}`, {
|
|
1394
|
+
topic,
|
|
1395
|
+
reply: response,
|
|
1396
|
+
command,
|
|
1397
|
+
code: ""
|
|
1398
|
+
});
|
|
1399
|
+
}
|
|
1400
|
+
let code = reason;
|
|
1401
|
+
let detail;
|
|
1402
|
+
if (reason.startsWith("player_refused:")) {
|
|
1403
|
+
code = "player_refused";
|
|
1404
|
+
detail = reason.slice("player_refused:".length);
|
|
1405
|
+
}
|
|
1406
|
+
const message = `${command} on ${topic} refused: ${reason}`;
|
|
1407
|
+
if (code === "price_moved") {
|
|
1408
|
+
return new STXComboPriceMovedException(message, {
|
|
1409
|
+
topic,
|
|
1410
|
+
reply: response,
|
|
1411
|
+
command,
|
|
1412
|
+
code,
|
|
1413
|
+
best: {
|
|
1414
|
+
quote_id: _nullishCoalesce(reply.quote_id, () => ( null)),
|
|
1415
|
+
amount: _nullishCoalesce(reply.amount, () => ( null)),
|
|
1416
|
+
expires_at: _nullishCoalesce(reply.expires_at, () => ( null))
|
|
1417
|
+
}
|
|
1418
|
+
});
|
|
1419
|
+
}
|
|
1420
|
+
return new STXComboRefusedException(message, { topic, reply: response, command, code, detail });
|
|
1421
|
+
}
|
|
1422
|
+
function comboJoinError(err, host = "") {
|
|
1423
|
+
if (err instanceof STXChannelException && !(err instanceof STXCombosUnavailableException) && err.reply !== void 0) {
|
|
1424
|
+
if (err.constructor !== STXChannelException) return err;
|
|
1425
|
+
return comboRefusal("phx_join", err.topic, err.reply, host);
|
|
1426
|
+
}
|
|
1427
|
+
return err;
|
|
1428
|
+
}
|
|
1429
|
+
function money(name, value) {
|
|
1430
|
+
if (typeof value !== "string") {
|
|
1431
|
+
throw new TypeError(`${name} must be a decimal string such as "250.00", got ${typeof value}`);
|
|
1432
|
+
}
|
|
1433
|
+
return value;
|
|
1434
|
+
}
|
|
1435
|
+
var ComboSession = class {
|
|
1436
|
+
/** The underlying channel. Its `reply` is the latest join reply. */
|
|
1437
|
+
|
|
1438
|
+
#onEvent;
|
|
1439
|
+
#history = [];
|
|
1440
|
+
#waiters = [];
|
|
1441
|
+
#events;
|
|
1442
|
+
/** @internal */
|
|
1443
|
+
constructor(channel, events, onEvent) {
|
|
1444
|
+
this.channel = channel;
|
|
1445
|
+
this.#events = events;
|
|
1446
|
+
this.#onEvent = onEvent;
|
|
1447
|
+
}
|
|
1448
|
+
/** Your account's pseudonym for counterparties, from the join reply. */
|
|
1449
|
+
get externalId() {
|
|
1450
|
+
return _nullishCoalesce(this.channel.reply.external_id, () => ( ""));
|
|
1451
|
+
}
|
|
1452
|
+
/** @internal */
|
|
1453
|
+
_typed(msg) {
|
|
1454
|
+
if (!this.#events.has(msg.event) || !msg.payload || typeof msg.payload !== "object") return void 0;
|
|
1455
|
+
return { event: msg.event, payload: msg.payload };
|
|
1456
|
+
}
|
|
1457
|
+
/** @internal Called for every message on the channel, before it is queued. */
|
|
1458
|
+
async _receive(msg) {
|
|
1459
|
+
const event = this._typed(msg);
|
|
1460
|
+
if (!event) return;
|
|
1461
|
+
this.#history.push(event);
|
|
1462
|
+
if (this.#history.length > HISTORY_SIZE) this.#history.shift();
|
|
1463
|
+
for (const w of [...this.#waiters]) {
|
|
1464
|
+
if (w.match(event)) {
|
|
1465
|
+
this.#waiters = this.#waiters.filter((x) => x !== w);
|
|
1466
|
+
w.resolve(event);
|
|
1467
|
+
}
|
|
1468
|
+
}
|
|
1469
|
+
if (this.#onEvent) await this.#onEvent(event);
|
|
1470
|
+
}
|
|
1471
|
+
/** The events received so far (the latest 1000), oldest first. */
|
|
1472
|
+
get events() {
|
|
1473
|
+
return [...this.#history];
|
|
1474
|
+
}
|
|
1475
|
+
/**
|
|
1476
|
+
* The next event, in arrival order. Rejects with `STXTimeoutException` when
|
|
1477
|
+
* none arrives within `timeoutMs`, and with `STXChannelException` once the
|
|
1478
|
+
* channel is closed. Use either this or `for await`, not both.
|
|
1479
|
+
*/
|
|
1480
|
+
async next(timeoutMs) {
|
|
1481
|
+
for (; ; ) {
|
|
1482
|
+
const event = this._typed(await this.channel.next(timeoutMs));
|
|
1483
|
+
if (event) return event;
|
|
1484
|
+
}
|
|
1485
|
+
}
|
|
1486
|
+
async *[Symbol.asyncIterator]() {
|
|
1487
|
+
for await (const msg of this.channel) {
|
|
1488
|
+
const event = this._typed(msg);
|
|
1489
|
+
if (event) yield event;
|
|
1490
|
+
}
|
|
1491
|
+
}
|
|
1492
|
+
/**
|
|
1493
|
+
* Resolve with the first event named `event` (or one of several) for
|
|
1494
|
+
* `rfqId`, looking first at events already received. Unlike `next()`, it
|
|
1495
|
+
* takes nothing from the queue. Rejects with `STXTimeoutException` after
|
|
1496
|
+
* `timeoutMs` (default 10000).
|
|
1497
|
+
*
|
|
1498
|
+
* @param event An event name, or several.
|
|
1499
|
+
* @param opts.rfqId Only events for this request.
|
|
1500
|
+
* @param opts.quoteId Only events for this quote (maker events).
|
|
1501
|
+
* @param opts.timeoutMs Milliseconds to wait. Default 10000.
|
|
1502
|
+
*/
|
|
1503
|
+
waitFor(event, opts = {}) {
|
|
1504
|
+
const names = typeof event === "string" ? [event] : event;
|
|
1505
|
+
const match = (e) => names.includes(e.event) && (opts.rfqId === void 0 || e.payload.rfq_id === opts.rfqId) && (opts.quoteId === void 0 || e.payload.quote_id === opts.quoteId);
|
|
1506
|
+
const seen = this.#history.find(match);
|
|
1507
|
+
if (seen) return Promise.resolve(seen);
|
|
1508
|
+
const timeoutMs = _nullishCoalesce(opts.timeoutMs, () => ( 1e4));
|
|
1509
|
+
return new Promise((resolve, reject) => {
|
|
1510
|
+
const waiter = {
|
|
1511
|
+
match,
|
|
1512
|
+
resolve: (e) => {
|
|
1513
|
+
clearTimeout(timer);
|
|
1514
|
+
resolve(e);
|
|
1515
|
+
}
|
|
1516
|
+
};
|
|
1517
|
+
const timer = setTimeout(() => {
|
|
1518
|
+
this.#waiters = this.#waiters.filter((w) => w !== waiter);
|
|
1519
|
+
reject(
|
|
1520
|
+
new STXTimeoutException(`No ${names.join(" or ")} on ${this.channel.topic} within ${timeoutMs} ms`, {
|
|
1521
|
+
topic: this.channel.topic
|
|
1522
|
+
})
|
|
1523
|
+
);
|
|
1524
|
+
}, timeoutMs);
|
|
1525
|
+
this.#waiters.push(waiter);
|
|
1526
|
+
});
|
|
1527
|
+
}
|
|
1528
|
+
/**
|
|
1529
|
+
* Leave the topic. Requests opened and quotes placed on this channel end
|
|
1530
|
+
* (`cancelled`), as on any close, and delivery on this channel stops when
|
|
1531
|
+
* `leave()` resolves: the exchange's `negotiation_closed` for those requests
|
|
1532
|
+
* arrives after the channel has closed and is not passed to `onEvent` or to
|
|
1533
|
+
* an iterator. Treat every request still open here as cancelled once
|
|
1534
|
+
* `leave()` resolves. To see each request's own close first, `cancel()` it
|
|
1535
|
+
* and wait for its `negotiation_closed` before leaving. Other connections of
|
|
1536
|
+
* the same member still receive the close.
|
|
1537
|
+
*/
|
|
1538
|
+
leave() {
|
|
1539
|
+
return this.channel.leave();
|
|
1540
|
+
}
|
|
1541
|
+
/** @internal Send a command and map a refusal to the combo exceptions. */
|
|
1542
|
+
async _command(command, payload, timeoutMs) {
|
|
1543
|
+
try {
|
|
1544
|
+
return await this.channel.push(command, payload, timeoutMs);
|
|
1545
|
+
} catch (err) {
|
|
1546
|
+
if (err instanceof STXChannelException && err.constructor === STXChannelException && err.reply !== void 0) {
|
|
1547
|
+
throw comboRefusal(command, this.channel.topic, err.reply);
|
|
1548
|
+
}
|
|
1549
|
+
throw err;
|
|
1550
|
+
}
|
|
1551
|
+
}
|
|
1552
|
+
};
|
|
1553
|
+
var ComboPlayer = class extends ComboSession {
|
|
1554
|
+
/** @internal */
|
|
1555
|
+
constructor(channel, onEvent) {
|
|
1556
|
+
super(channel, PLAYER_EVENTS, onEvent);
|
|
1557
|
+
}
|
|
1558
|
+
/**
|
|
1559
|
+
* `request_quote`: ask makers to quote on these legs for a stake. `amount`
|
|
1560
|
+
* is the stake as a decimal string in whole cents, e.g. `"250.00"`. Makers
|
|
1561
|
+
* quote what you win; quotes arrive as `best_quote` events.
|
|
1562
|
+
*
|
|
1563
|
+
* @param legs Two or more `open` markets and the outcome the combination needs of each.
|
|
1564
|
+
* @param amount The stake in dollars, e.g. `"250.00"`.
|
|
1565
|
+
*/
|
|
1566
|
+
requestQuote(legs, amount2) {
|
|
1567
|
+
return this._command("request_quote", {
|
|
1568
|
+
legs: legs.map((leg) => ({ market_id: leg.marketId, outcome: leg.outcome })),
|
|
1569
|
+
amount: money("amount", amount2)
|
|
1570
|
+
});
|
|
1571
|
+
}
|
|
1572
|
+
/**
|
|
1573
|
+
* `cash_out`: ask makers to quote for what you hold of a combination, by the
|
|
1574
|
+
* `market_id` from `placed`. The exchange sets the size.
|
|
1575
|
+
*
|
|
1576
|
+
* @param marketId The combination's market id.
|
|
1577
|
+
*/
|
|
1578
|
+
cashOut(marketId) {
|
|
1579
|
+
return this._command("cash_out", { market_id: marketId });
|
|
1580
|
+
}
|
|
1581
|
+
/**
|
|
1582
|
+
* `accept`: bind the request at `amount` or more, normally the amount
|
|
1583
|
+
* `best_quote` showed. The best live quote binds whoever made it, so the
|
|
1584
|
+
* placement can be better than `amount`. Waits up to 35 s.
|
|
1585
|
+
*
|
|
1586
|
+
* Throws `STXComboPriceMovedException` (with the live `best`) when nothing
|
|
1587
|
+
* at least as good is live; the request stays open and you can accept again.
|
|
1588
|
+
* The reply says what was placed; fills arrive on `fills`.
|
|
1589
|
+
*
|
|
1590
|
+
* @param rfqId The request.
|
|
1591
|
+
* @param quoteId The quote you saw, normally from `best_quote`.
|
|
1592
|
+
* @param amount The least amount you take, e.g. `"1750.00"`.
|
|
1593
|
+
*/
|
|
1594
|
+
accept(rfqId, quoteId, amount2) {
|
|
1595
|
+
return this._command(
|
|
1596
|
+
"accept",
|
|
1597
|
+
{ rfq_id: rfqId, quote_id: quoteId, amount: money("amount", amount2) },
|
|
1598
|
+
ACCEPT_TIMEOUT_MS
|
|
1599
|
+
);
|
|
1600
|
+
}
|
|
1601
|
+
/**
|
|
1602
|
+
* `cancel`: end the request and drop every quote on it.
|
|
1603
|
+
*
|
|
1604
|
+
* @param rfqId The request.
|
|
1605
|
+
*/
|
|
1606
|
+
cancel(rfqId) {
|
|
1607
|
+
return this._command("cancel", { rfq_id: rfqId });
|
|
1608
|
+
}
|
|
1609
|
+
/**
|
|
1610
|
+
* `snapshot`: the request now, with the live best quote. Not delayed like `best_quote` events.
|
|
1611
|
+
*
|
|
1612
|
+
* @param rfqId The request.
|
|
1613
|
+
*/
|
|
1614
|
+
snapshot(rfqId) {
|
|
1615
|
+
return this._command("snapshot", { rfq_id: rfqId });
|
|
1616
|
+
}
|
|
1617
|
+
};
|
|
1618
|
+
var ComboMaker = class extends ComboSession {
|
|
1619
|
+
/** @internal */
|
|
1620
|
+
constructor(channel, onEvent) {
|
|
1621
|
+
super(channel, MAKER_EVENTS, onEvent);
|
|
1622
|
+
}
|
|
1623
|
+
/**
|
|
1624
|
+
* `quote`: offer `amount` on a request. On a buy it is what the player wins;
|
|
1625
|
+
* on a cash out, what you pay for the whole size. Price it against the
|
|
1626
|
+
* request's `max_price` and `tick_size`. `expiresInMs` (a positive integer)
|
|
1627
|
+
* counts from receipt; the quote ends no later than its request.
|
|
1628
|
+
* `clientOrderId` (at most 255 bytes) is copied onto your order if it binds.
|
|
1629
|
+
*
|
|
1630
|
+
* @param rfqId The request, from `rfq_opened`.
|
|
1631
|
+
* @param amount In dollars, e.g. `"1750.00"`.
|
|
1632
|
+
* @param expiresInMs How long the quote stands, in milliseconds.
|
|
1633
|
+
* @param opts.clientOrderId Copied onto your order if the quote binds.
|
|
1634
|
+
*/
|
|
1635
|
+
quote(rfqId, amount2, expiresInMs, opts = {}) {
|
|
1636
|
+
const payload = {
|
|
1637
|
+
rfq_id: rfqId,
|
|
1638
|
+
amount: money("amount", amount2),
|
|
1639
|
+
expires_in_ms: expiresInMs
|
|
1640
|
+
};
|
|
1641
|
+
if (opts.clientOrderId !== void 0) payload.client_order_id = opts.clientOrderId;
|
|
1642
|
+
return this._command("quote", payload);
|
|
1643
|
+
}
|
|
1644
|
+
/**
|
|
1645
|
+
* `withdraw_quote`: remove one of your quotes.
|
|
1646
|
+
*
|
|
1647
|
+
* @param rfqId The request.
|
|
1648
|
+
* @param quoteId Your quote, from the `quote()` reply.
|
|
1649
|
+
*/
|
|
1650
|
+
withdrawQuote(rfqId, quoteId) {
|
|
1651
|
+
return this._command("withdraw_quote", { rfq_id: rfqId, quote_id: quoteId });
|
|
1652
|
+
}
|
|
1653
|
+
};
|
|
1654
|
+
var COMBO_CHANNELS = /* @__PURE__ */ new Set([COMBO_PLAYER_CHANNEL, COMBO_MAKER_CHANNEL]);
|
|
1655
|
+
var COMBOS_UNAVAILABLE_REASON = UNAVAILABLE_REASON;
|
|
1158
1656
|
|
|
1159
1657
|
// src/money.ts
|
|
1160
1658
|
var PRICE_FIELDS = ["price", "last_traded_price", "max_price"];
|
|
@@ -1291,7 +1789,7 @@ function buildRequest(operationId, args = {}) {
|
|
|
1291
1789
|
const op = OPERATIONS[operationId];
|
|
1292
1790
|
let path = op.path;
|
|
1293
1791
|
for (const name of op.pathParams) {
|
|
1294
|
-
const value = _optionalChain([args, 'access',
|
|
1792
|
+
const value = _optionalChain([args, 'access', _16 => _16.pathParams, 'optionalAccess', _17 => _17[name]]);
|
|
1295
1793
|
if (!value) throw new TypeError(`${name} is required`);
|
|
1296
1794
|
path = path.replace(`{${name}}`, quote(String(value)));
|
|
1297
1795
|
}
|
|
@@ -1314,7 +1812,7 @@ function decodeResponse(request, status, text, headers = {}) {
|
|
|
1314
1812
|
let body;
|
|
1315
1813
|
try {
|
|
1316
1814
|
body = text ? JSON.parse(text) : null;
|
|
1317
|
-
} catch (
|
|
1815
|
+
} catch (e8) {
|
|
1318
1816
|
body = text;
|
|
1319
1817
|
}
|
|
1320
1818
|
if (status >= 200 && status < 300) {
|
|
@@ -1345,7 +1843,7 @@ function toBatchOrderResult(raw) {
|
|
|
1345
1843
|
const obj = raw && typeof raw === "object" ? raw : {};
|
|
1346
1844
|
const order = _nullishCoalesce(obj.order, () => ( null));
|
|
1347
1845
|
const errors = Array.isArray(obj.errors) ? obj.errors : null;
|
|
1348
|
-
return { ...obj, order, errors, ok: order !== null && !_optionalChain([errors, 'optionalAccess',
|
|
1846
|
+
return { ...obj, order, errors, ok: order !== null && !_optionalChain([errors, 'optionalAccess', _18 => _18.length]) };
|
|
1349
1847
|
}
|
|
1350
1848
|
|
|
1351
1849
|
// src/client.ts
|
|
@@ -1409,7 +1907,20 @@ function ids(value) {
|
|
|
1409
1907
|
return typeof value === "string" ? [value] : [...value];
|
|
1410
1908
|
}
|
|
1411
1909
|
var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
1412
|
-
var
|
|
1910
|
+
var GATED_OPERATIONS = {
|
|
1911
|
+
types_get: "market_types",
|
|
1912
|
+
events__id_players_get: "event_players",
|
|
1913
|
+
markets_post: "markets.create",
|
|
1914
|
+
leaderboard_get: "leaderboard",
|
|
1915
|
+
leaderboard_me_get: "leaderboard",
|
|
1916
|
+
me_profile_patch: "leaderboard",
|
|
1917
|
+
portfolio_loyalty_get: "loyalty"
|
|
1918
|
+
};
|
|
1919
|
+
var SWITCHED_OFF = {
|
|
1920
|
+
leaderboard: "Leaderboard is not enabled",
|
|
1921
|
+
loyalty: "Loyalty program is not enabled"
|
|
1922
|
+
};
|
|
1923
|
+
var STX = (_class4 = class _STX {
|
|
1413
1924
|
|
|
1414
1925
|
|
|
1415
1926
|
|
|
@@ -1421,12 +1932,12 @@ var STX = (_class3 = class _STX {
|
|
|
1421
1932
|
|
|
1422
1933
|
|
|
1423
1934
|
|
|
1424
|
-
|
|
1425
1935
|
#fetch;
|
|
1426
1936
|
#me;
|
|
1937
|
+
#capabilities;
|
|
1427
1938
|
/** Test hook: how retries wait. */
|
|
1428
|
-
|
|
1429
|
-
constructor(opts = {}) {;
|
|
1939
|
+
__init5() {this._sleep = sleep}
|
|
1940
|
+
constructor(opts = {}) {;_class4.prototype.__init5.call(this);
|
|
1430
1941
|
if (opts.auth && (opts.keyId || opts.privateKey || opts.signer)) {
|
|
1431
1942
|
throw new STXConfigException("Pass `auth` or an API key (keyId with privateKey or signer), not both.");
|
|
1432
1943
|
}
|
|
@@ -1461,7 +1972,6 @@ var STX = (_class3 = class _STX {
|
|
|
1461
1972
|
this.verifyTls = settings.verifyTls;
|
|
1462
1973
|
this.retry = _nullishCoalesce(opts.retry, () => ( new RetryPolicy()));
|
|
1463
1974
|
this.timeoutMs = _nullishCoalesce(opts.timeoutMs, () => ( 3e4));
|
|
1464
|
-
this.geoLocation = opts.geoLocation;
|
|
1465
1975
|
this.onResponse = opts.onResponse;
|
|
1466
1976
|
const fetchImpl = _nullishCoalesce(opts.fetch, () => ( globalThis.fetch));
|
|
1467
1977
|
if (typeof fetchImpl !== "function") {
|
|
@@ -1475,7 +1985,75 @@ var STX = (_class3 = class _STX {
|
|
|
1475
1985
|
this.#fetch = fetchImpl;
|
|
1476
1986
|
}
|
|
1477
1987
|
toString() {
|
|
1478
|
-
return `STX(baseUrl=${JSON.stringify(this.baseUrl)}, keyId=${JSON.stringify(_nullishCoalesce(_optionalChain([this, 'access',
|
|
1988
|
+
return `STX(baseUrl=${JSON.stringify(this.baseUrl)}, keyId=${JSON.stringify(_nullishCoalesce(_optionalChain([this, 'access', _19 => _19.credentials, 'optionalAccess', _20 => _20.keyId]), () => ( null)))})`;
|
|
1989
|
+
}
|
|
1990
|
+
/** The exchange host, e.g. `"demo.stxapp.io"`: the name `STXNotAvailableException` and `capabilities()` report. */
|
|
1991
|
+
get host() {
|
|
1992
|
+
return new URL(this.baseUrl).host;
|
|
1993
|
+
}
|
|
1994
|
+
// ------------------------------------------------------------------
|
|
1995
|
+
// Capabilities
|
|
1996
|
+
// ------------------------------------------------------------------
|
|
1997
|
+
/**
|
|
1998
|
+
* Which features this exchange has, from what it publishes: its OAuth
|
|
1999
|
+
* discovery document, `/api_version`, a signed GET of the routes that not
|
|
2000
|
+
* every exchange has yet, and a join of a combos topic nobody owns. Nothing
|
|
2001
|
+
* is created or changed. Checked once per client and cached; pass
|
|
2002
|
+
* `{ refresh: true }` to check again.
|
|
2003
|
+
*
|
|
2004
|
+
* const caps = await stx.capabilities();
|
|
2005
|
+
* caps.features.combos; // false on demo.stxapp.ca
|
|
2006
|
+
* caps.require("combos"); // throws STXNotAvailableException there
|
|
2007
|
+
*
|
|
2008
|
+
* Each feature is `true`, `false`, or `null` when it could not be checked
|
|
2009
|
+
* (no credentials for a signed check, or no answer). A missing feature never
|
|
2010
|
+
* throws here; the call that needs it throws `STXNotAvailableException`.
|
|
2011
|
+
*/
|
|
2012
|
+
capabilities(opts = {}) {
|
|
2013
|
+
if (opts.refresh || !this.#capabilities) {
|
|
2014
|
+
const run = discoverCapabilities({
|
|
2015
|
+
host: this.host,
|
|
2016
|
+
get: (path) => this.#rawGet(path, false),
|
|
2017
|
+
signedGet: (path) => this.auth ? this.#rawGet(path, true) : null,
|
|
2018
|
+
joinReason: (topic) => this.#joinReason(topic)
|
|
2019
|
+
});
|
|
2020
|
+
this.#capabilities = run;
|
|
2021
|
+
run.catch(() => {
|
|
2022
|
+
if (this.#capabilities === run) this.#capabilities = void 0;
|
|
2023
|
+
});
|
|
2024
|
+
}
|
|
2025
|
+
return this.#capabilities;
|
|
2026
|
+
}
|
|
2027
|
+
async #rawGet(path, signed) {
|
|
2028
|
+
const headers = { "User-Agent": USER_AGENT, Accept: "application/json" };
|
|
2029
|
+
if (signed && this.auth) Object.assign(headers, await this.auth.authHeaders({ method: "GET", path }));
|
|
2030
|
+
const controller = new AbortController();
|
|
2031
|
+
const timer = setTimeout(() => controller.abort(), Math.min(this.timeoutMs, 15e3));
|
|
2032
|
+
try {
|
|
2033
|
+
const res = await this.#fetch(this.baseUrl + path, { method: "GET", headers, signal: controller.signal });
|
|
2034
|
+
return { status: res.status, text: await res.text() };
|
|
2035
|
+
} catch (e9) {
|
|
2036
|
+
return null;
|
|
2037
|
+
} finally {
|
|
2038
|
+
clearTimeout(timer);
|
|
2039
|
+
}
|
|
2040
|
+
}
|
|
2041
|
+
async #joinReason(topic) {
|
|
2042
|
+
if (!this.auth) return null;
|
|
2043
|
+
const ws = this.websocket({ reconnect: false, joinTimeoutMs: 8e3 });
|
|
2044
|
+
try {
|
|
2045
|
+
const channel = await ws.join(topic);
|
|
2046
|
+
await channel.leave().catch(() => {
|
|
2047
|
+
});
|
|
2048
|
+
return "ok";
|
|
2049
|
+
} catch (err) {
|
|
2050
|
+
if (err instanceof STXTimeoutException) return null;
|
|
2051
|
+
if (err instanceof STXChannelException) return _nullishCoalesce(err.reason, () => ( null));
|
|
2052
|
+
return null;
|
|
2053
|
+
} finally {
|
|
2054
|
+
await ws.close().catch(() => {
|
|
2055
|
+
});
|
|
2056
|
+
}
|
|
1479
2057
|
}
|
|
1480
2058
|
/** Nothing to release (fetch pools connections itself); present so `await using` and explicit cleanup work. */
|
|
1481
2059
|
async close() {
|
|
@@ -1510,11 +2088,11 @@ var STX = (_class3 = class _STX {
|
|
|
1510
2088
|
status,
|
|
1511
2089
|
attempt,
|
|
1512
2090
|
durationMs: Date.now() - started,
|
|
1513
|
-
authKind: _optionalChain([this, 'access',
|
|
2091
|
+
authKind: _optionalChain([this, 'access', _21 => _21.auth, 'optionalAccess', _22 => _22.kind]),
|
|
1514
2092
|
requestBody: request.body,
|
|
1515
2093
|
responseBody
|
|
1516
2094
|
});
|
|
1517
|
-
} catch (
|
|
2095
|
+
} catch (e10) {
|
|
1518
2096
|
}
|
|
1519
2097
|
}
|
|
1520
2098
|
async #sendOnce(request, attempt = 1) {
|
|
@@ -1542,7 +2120,7 @@ var STX = (_class3 = class _STX {
|
|
|
1542
2120
|
});
|
|
1543
2121
|
}
|
|
1544
2122
|
throw new STXTransportException(
|
|
1545
|
-
`${request.method} ${request.path} failed: ${_nullishCoalesce(_optionalChain([err, 'optionalAccess',
|
|
2123
|
+
`${request.method} ${request.path} failed: ${_nullishCoalesce(_optionalChain([err, 'optionalAccess', _23 => _23.message]), () => ( String(err)))}`,
|
|
1546
2124
|
{ method: request.method, path: request.path, cause: err }
|
|
1547
2125
|
);
|
|
1548
2126
|
} finally {
|
|
@@ -1564,7 +2142,7 @@ var STX = (_class3 = class _STX {
|
|
|
1564
2142
|
return await this.#sendOnce(request, sent);
|
|
1565
2143
|
} catch (err) {
|
|
1566
2144
|
if (!(err instanceof STXException)) throw err;
|
|
1567
|
-
if (err.statusCode === 401 && !reauthenticated && _optionalChain([this, 'access',
|
|
2145
|
+
if (err.statusCode === 401 && !reauthenticated && _optionalChain([this, 'access', _24 => _24.auth, 'optionalAccess', _25 => _25.onUnauthorized])) {
|
|
1568
2146
|
reauthenticated = true;
|
|
1569
2147
|
if (await this.auth.onUnauthorized()) continue;
|
|
1570
2148
|
}
|
|
@@ -1575,7 +2153,22 @@ var STX = (_class3 = class _STX {
|
|
|
1575
2153
|
}
|
|
1576
2154
|
}
|
|
1577
2155
|
async #call(operationId, args = {}) {
|
|
1578
|
-
|
|
2156
|
+
try {
|
|
2157
|
+
return await this.#send(buildRequest(operationId, args));
|
|
2158
|
+
} catch (err) {
|
|
2159
|
+
const feature = GATED_OPERATIONS[operationId];
|
|
2160
|
+
const off = feature !== void 0 && err instanceof STXNotFoundException && SWITCHED_OFF[feature] !== void 0 && _optionalChain([err, 'access', _26 => _26.body, 'optionalAccess', _27 => _27.error]) === SWITCHED_OFF[feature];
|
|
2161
|
+
if (feature && (isMissingRoute(err) || off)) {
|
|
2162
|
+
throw new STXNotAvailableException(feature, this.host, {
|
|
2163
|
+
statusCode: err.statusCode,
|
|
2164
|
+
body: err.body,
|
|
2165
|
+
method: err.method,
|
|
2166
|
+
path: err.path,
|
|
2167
|
+
cause: err
|
|
2168
|
+
});
|
|
2169
|
+
}
|
|
2170
|
+
throw err;
|
|
2171
|
+
}
|
|
1579
2172
|
}
|
|
1580
2173
|
async #one(operationId, args = {}) {
|
|
1581
2174
|
const body = await this.#call(operationId, args);
|
|
@@ -1599,10 +2192,6 @@ var STX = (_class3 = class _STX {
|
|
|
1599
2192
|
q.cursor = page.cursor;
|
|
1600
2193
|
}
|
|
1601
2194
|
}
|
|
1602
|
-
async #geoBody(body, opts) {
|
|
1603
|
-
const packet = _optionalChain([opts, 'optionalAccess', _24 => _24.geoLocation]) !== void 0 ? _nullishCoalesce(opts.geoLocation, () => ( void 0)) : await resolveGeoLocation(this.geoLocation);
|
|
1604
|
-
return packet === void 0 ? body : { ...body, geo_location: packet };
|
|
1605
|
-
}
|
|
1606
2195
|
// ------------------------------------------------------------------
|
|
1607
2196
|
// Identity
|
|
1608
2197
|
// ------------------------------------------------------------------
|
|
@@ -1621,7 +2210,7 @@ var STX = (_class3 = class _STX {
|
|
|
1621
2210
|
* `user_id`.
|
|
1622
2211
|
*/
|
|
1623
2212
|
async userId() {
|
|
1624
|
-
if (_optionalChain([this, 'access',
|
|
2213
|
+
if (_optionalChain([this, 'access', _28 => _28.#me, 'optionalAccess', _29 => _29.user_id])) return this.#me.user_id;
|
|
1625
2214
|
try {
|
|
1626
2215
|
await this.me();
|
|
1627
2216
|
} catch (err) {
|
|
@@ -1632,7 +2221,7 @@ var STX = (_class3 = class _STX {
|
|
|
1632
2221
|
if (!balance.user_id) throw err;
|
|
1633
2222
|
this.#me = { ..._nullishCoalesce(this.#me, () => ( {})), user_id: balance.user_id };
|
|
1634
2223
|
}
|
|
1635
|
-
if (!_optionalChain([this, 'access',
|
|
2224
|
+
if (!_optionalChain([this, 'access', _30 => _30.#me, 'optionalAccess', _31 => _31.user_id])) throw new STXException("GET /api/v1/me returned no user_id");
|
|
1636
2225
|
return this.#me.user_id;
|
|
1637
2226
|
}
|
|
1638
2227
|
// ------------------------------------------------------------------
|
|
@@ -1727,16 +2316,18 @@ var STX = (_class3 = class _STX {
|
|
|
1727
2316
|
* which STX grants, from an address on the client's IP allow-list (it
|
|
1728
2317
|
* applies to every call that client makes).
|
|
1729
2318
|
*
|
|
1730
|
-
* Returns one result per market, in
|
|
1731
|
-
* `
|
|
1732
|
-
*
|
|
1733
|
-
*
|
|
1734
|
-
*
|
|
1735
|
-
*
|
|
2319
|
+
* Returns one result per market, in order: `created` or `exists` (both with
|
|
2320
|
+
* `market_id`), `valid` with `dryRun`, or `rejected` with a `reason`. Each
|
|
2321
|
+
* result's `index` is its position in `markets`, and `market` is that market
|
|
2322
|
+
* as requested. A rejected market is a
|
|
2323
|
+
* result, not an error, and resending is safe: a market that is already
|
|
2324
|
+
* listed comes back `exists`. A refused request throws (`403` without
|
|
2325
|
+
* `markets.write`, `404` unknown event, `422` event not open).
|
|
1736
2326
|
*
|
|
1737
|
-
* `
|
|
1738
|
-
* `MAX_MARKETS_PER_REQUEST` markets throws `TypeError` before any
|
|
1739
|
-
* `
|
|
2327
|
+
* Each `line` must be a positive number ending in `.5`, e.g. `18.5`. More
|
|
2328
|
+
* than `MAX_MARKETS_PER_REQUEST` markets throws `TypeError` before any
|
|
2329
|
+
* request. `dryRun` runs every check and creates nothing. `validate` also
|
|
2330
|
+
* needs the `events` scope.
|
|
1740
2331
|
*/
|
|
1741
2332
|
async createMarkets(eventId, markets, opts = {}) {
|
|
1742
2333
|
if (markets.length < 1 || markets.length > MAX_MARKETS_PER_REQUEST) {
|
|
@@ -1749,24 +2340,20 @@ var STX = (_class3 = class _STX {
|
|
|
1749
2340
|
send = send.flatMap(({ m, i }) => {
|
|
1750
2341
|
const checked = checkMarket(m, players);
|
|
1751
2342
|
if ("market" in checked) return [{ m: checked.market, i }];
|
|
1752
|
-
results[i] = rejected(i, checked.reason);
|
|
2343
|
+
results[i] = rejected(m, i, checked.reason);
|
|
1753
2344
|
return [];
|
|
1754
2345
|
});
|
|
1755
2346
|
}
|
|
1756
2347
|
if (send.length) {
|
|
1757
|
-
const body = {
|
|
1758
|
-
|
|
1759
|
-
...opts.dryRun ? { dry_run: true } : {},
|
|
1760
|
-
markets: send.map(({ m }) => marketEntry(m))
|
|
1761
|
-
};
|
|
2348
|
+
const body = { event_id: eventId, markets: send.map(({ m }) => marketEntry(m)) };
|
|
2349
|
+
if (opts.dryRun) body.dry_run = true;
|
|
1762
2350
|
const raw = await this.#one("markets_post", { body });
|
|
1763
2351
|
(_nullishCoalesce(raw.markets, () => ( []))).forEach((r, k) => {
|
|
1764
|
-
const
|
|
1765
|
-
|
|
1766
|
-
if (slot) results[slot.i] = toCreateMarketResult(r, slot.i);
|
|
2352
|
+
const slot = send[typeof r.index === "number" ? r.index : k];
|
|
2353
|
+
if (slot) results[slot.i] = toCreateMarketResult(r, slot.m, slot.i);
|
|
1767
2354
|
});
|
|
1768
2355
|
}
|
|
1769
|
-
return
|
|
2356
|
+
return results.map((r, i) => _nullishCoalesce(r, () => ( rejected(markets[i], i, "not_created"))));
|
|
1770
2357
|
}
|
|
1771
2358
|
// ------------------------------------------------------------------
|
|
1772
2359
|
// Orders
|
|
@@ -1798,88 +2385,46 @@ var STX = (_class3 = class _STX {
|
|
|
1798
2385
|
*
|
|
1799
2386
|
* `action` is `"buy"` or `"sell"`; `orderType` is `"limit"` or `"market"`.
|
|
1800
2387
|
* `price` (dollars, required for a limit order) and `quantity` (contracts)
|
|
1801
|
-
* are decimal strings, e.g. `{ price: "0.
|
|
2388
|
+
* are decimal strings, e.g. `{ price: "0.58", quantity: "100" }`. Numbers are
|
|
1802
2389
|
* refused client-side.
|
|
1803
2390
|
*
|
|
1804
2391
|
* The exchange validates the order: a bad price step or a fractional
|
|
1805
2392
|
* quantity throws `STXValidationException` (400) or `STXRejectedException`
|
|
1806
|
-
* (422) with the API's message
|
|
1807
|
-
* `
|
|
2393
|
+
* (422) with the API's message. An order from outside the region is also
|
|
2394
|
+
* an `STXRejectedException`.
|
|
1808
2395
|
*
|
|
1809
2396
|
* A POST is never retried after a 5xx or a dropped connection; pass
|
|
1810
2397
|
* `clientOrderId` so you can look the order up if that happens.
|
|
1811
2398
|
*/
|
|
1812
2399
|
async placeOrder(marketId, action, orderType, opts) {
|
|
1813
|
-
const
|
|
1814
|
-
|
|
1815
|
-
return this.#one("orders_post", { body: await this.#geoBody(body, { geoLocation }) });
|
|
2400
|
+
const body = orderBody(marketId, action, orderType, _nullishCoalesce(opts, () => ( {})));
|
|
2401
|
+
return this.#one("orders_post", { body });
|
|
1816
2402
|
}
|
|
1817
2403
|
/**
|
|
1818
|
-
* `POST /api/v1/orders/batched`: place several orders in one call.
|
|
1819
|
-
*
|
|
1820
|
-
*
|
|
1821
|
-
* others.
|
|
2404
|
+
* `POST /api/v1/orders/batched`: place several orders in one call. Returns
|
|
2405
|
+
* one result per order, in order; a rejected order has `errors` instead of
|
|
2406
|
+
* `order` and does not stop the others.
|
|
1822
2407
|
*/
|
|
1823
|
-
async placeOrders(orders
|
|
2408
|
+
async placeOrders(orders) {
|
|
1824
2409
|
const body = { orders: orders.map(normalizeOrder) };
|
|
1825
|
-
const raw = await this.#list("orders_batched_post", { body
|
|
2410
|
+
const raw = await this.#list("orders_batched_post", { body });
|
|
1826
2411
|
return raw.map(toBatchOrderResult);
|
|
1827
2412
|
}
|
|
1828
2413
|
/**
|
|
1829
2414
|
* `DELETE /api/v1/orders/{order_id}`: request a cancel. A cancel is a
|
|
1830
2415
|
* request: a fill already in flight can still land.
|
|
1831
2416
|
*/
|
|
1832
|
-
async cancelOrder(orderId
|
|
1833
|
-
|
|
1834
|
-
return this.#one("orders__order_id_delete", {
|
|
1835
|
-
pathParams: { order_id: orderId },
|
|
1836
|
-
body: "geo_location" in geo ? geo : void 0
|
|
1837
|
-
});
|
|
2417
|
+
async cancelOrder(orderId) {
|
|
2418
|
+
return this.#one("orders__order_id_delete", { pathParams: { order_id: orderId } });
|
|
1838
2419
|
}
|
|
1839
2420
|
/** `DELETE /api/v1/orders/batched`: cancel the named orders. */
|
|
1840
|
-
async cancelOrders(orderIds
|
|
2421
|
+
async cancelOrders(orderIds) {
|
|
1841
2422
|
const body = { orders: orderIds.map((id) => ({ order_id: id })) };
|
|
1842
|
-
return this.#list("orders_batched_delete", { body
|
|
2423
|
+
return this.#list("orders_batched_delete", { body });
|
|
1843
2424
|
}
|
|
1844
2425
|
/** `DELETE /api/v1/orders/all`: cancel everything resting on the account. */
|
|
1845
|
-
async cancelAllOrders(
|
|
1846
|
-
|
|
1847
|
-
return this.#list("orders_all_delete", { body: "geo_location" in geo ? geo : void 0 });
|
|
1848
|
-
}
|
|
1849
|
-
// ------------------------------------------------------------------
|
|
1850
|
-
// Geo-fencing
|
|
1851
|
-
// ------------------------------------------------------------------
|
|
1852
|
-
/**
|
|
1853
|
-
* Ask the exchange whether this machine may trade right now, without
|
|
1854
|
-
* placing or cancelling anything.
|
|
1855
|
-
*
|
|
1856
|
-
* Sends `DELETE /api/v1/orders/00000000-0000-0000-0000-000000000000` (an
|
|
1857
|
-
* order id that cannot exist) with the geolocation packet, if one is
|
|
1858
|
-
* configured. The exchange runs its geo check before it looks the order
|
|
1859
|
-
* up, so a 404 means the check passed, and a geo 422 means it did not. On
|
|
1860
|
-
* an exchange without geo-fencing it always passes.
|
|
1861
|
-
*
|
|
1862
|
-
* Needs a `read_write` key (the probe is a write route). The exchange
|
|
1863
|
-
* records a failed check in its geolocation log exactly as it would a real
|
|
1864
|
-
* order from the same place, and may raise a compliance alert, so call it
|
|
1865
|
-
* once at start-up, not in a loop.
|
|
1866
|
-
*/
|
|
1867
|
-
async geoCheck(opts) {
|
|
1868
|
-
const geo = await this.#geoBody({}, opts);
|
|
1869
|
-
const sentPacket = "geo_location" in geo;
|
|
1870
|
-
try {
|
|
1871
|
-
await this.#one("orders__order_id_delete", {
|
|
1872
|
-
pathParams: { order_id: "00000000-0000-0000-0000-000000000000" },
|
|
1873
|
-
body: sentPacket ? geo : void 0
|
|
1874
|
-
});
|
|
1875
|
-
return { allowed: true, sentPacket };
|
|
1876
|
-
} catch (err) {
|
|
1877
|
-
if (err instanceof STXNotFoundException) return { allowed: true, sentPacket };
|
|
1878
|
-
if (err instanceof STXGeoLocationException) {
|
|
1879
|
-
return { allowed: false, reason: err.reason, message: err.message, ipAddress: err.ipAddress, sentPacket };
|
|
1880
|
-
}
|
|
1881
|
-
throw err;
|
|
1882
|
-
}
|
|
2426
|
+
async cancelAllOrders() {
|
|
2427
|
+
return this.#list("orders_all_delete");
|
|
1883
2428
|
}
|
|
1884
2429
|
// ------------------------------------------------------------------
|
|
1885
2430
|
// Fills, positions, balance
|
|
@@ -1985,18 +2530,54 @@ var STX = (_class3 = class _STX {
|
|
|
1985
2530
|
iterFees(query = {}) {
|
|
1986
2531
|
return this.#iterate("portfolio_fees_get", { limit: query.limit });
|
|
1987
2532
|
}
|
|
1988
|
-
/**
|
|
2533
|
+
/**
|
|
2534
|
+
* `GET /api/v1/portfolio/loyalty`: loyalty entries. Throws
|
|
2535
|
+
* `STXNotAvailableException` (feature `loyalty`) where the exchange has the
|
|
2536
|
+
* loyalty program switched off.
|
|
2537
|
+
*/
|
|
1989
2538
|
loyalty(query = {}) {
|
|
1990
2539
|
return this.#page("portfolio_loyalty_get", { limit: query.limit, cursor: query.cursor });
|
|
1991
2540
|
}
|
|
1992
|
-
/** Every loyalty entry, following the cursor. */
|
|
2541
|
+
/** Every loyalty entry, following the cursor. Throws like `loyalty()`. */
|
|
1993
2542
|
iterLoyalty(query = {}) {
|
|
1994
2543
|
return this.#iterate("portfolio_loyalty_get", { limit: query.limit });
|
|
1995
2544
|
}
|
|
1996
2545
|
// ------------------------------------------------------------------
|
|
2546
|
+
// Leaderboard and public profile
|
|
2547
|
+
// ------------------------------------------------------------------
|
|
2548
|
+
/**
|
|
2549
|
+
* `GET /api/v1/leaderboard`: ranked members for a period, sport and metric.
|
|
2550
|
+
* Rows carry a public handle and avatar, never an account id. Throws
|
|
2551
|
+
* `STXNotAvailableException` (feature `leaderboard`) where the exchange does
|
|
2552
|
+
* not have the leaderboard.
|
|
2553
|
+
*/
|
|
2554
|
+
leaderboard(query = {}) {
|
|
2555
|
+
const { period, category, metric, limit } = query;
|
|
2556
|
+
return this.#one("leaderboard_get", { query: { period, category, metric, limit } });
|
|
2557
|
+
}
|
|
2558
|
+
/** `GET /api/v1/leaderboard/me`: your own standing, including your rank outside the list. */
|
|
2559
|
+
leaderboardMe(query = {}) {
|
|
2560
|
+
return this.#one("leaderboard_me_get", { query: { period: query.period, category: query.category } });
|
|
2561
|
+
}
|
|
2562
|
+
/**
|
|
2563
|
+
* `PATCH /api/v1/me/profile`: change your public handle, avatar or
|
|
2564
|
+
* leaderboard opt-in. Resolves to the updated `me`.
|
|
2565
|
+
*/
|
|
2566
|
+
async updateProfile(update) {
|
|
2567
|
+
this.#me = await this.#one("me_profile_patch", { body: update });
|
|
2568
|
+
return this.#me;
|
|
2569
|
+
}
|
|
2570
|
+
// ------------------------------------------------------------------
|
|
1997
2571
|
// Terms
|
|
1998
2572
|
// ------------------------------------------------------------------
|
|
1999
|
-
/**
|
|
2573
|
+
/**
|
|
2574
|
+
* `POST /api/v1/tnc/accept`: accept the current terms for your own account,
|
|
2575
|
+
* with your own API key. Resolves to the server's message.
|
|
2576
|
+
*
|
|
2577
|
+
* An app cannot accept the terms for a member: called with a member's OAuth
|
|
2578
|
+
* access token, the exchange answers 403 `terms_not_delegable`
|
|
2579
|
+
* (`STXForbiddenException`). The member accepts on an STX page instead.
|
|
2580
|
+
*/
|
|
2000
2581
|
async acceptTerms(deviceId, opts = {}) {
|
|
2001
2582
|
const body = {
|
|
2002
2583
|
device_id: deviceId,
|
|
@@ -2017,7 +2598,7 @@ var STX = (_class3 = class _STX {
|
|
|
2017
2598
|
websocket(opts = {}) {
|
|
2018
2599
|
return new STXWebSocket({ ...opts, rest: this });
|
|
2019
2600
|
}
|
|
2020
|
-
},
|
|
2601
|
+
}, _class4);
|
|
2021
2602
|
|
|
2022
2603
|
// src/ws.ts
|
|
2023
2604
|
var PHOENIX_TOPIC = "phoenix";
|
|
@@ -2092,6 +2673,12 @@ var MessageQueue = class {
|
|
|
2092
2673
|
this.#items.push(msg);
|
|
2093
2674
|
return dropped;
|
|
2094
2675
|
}
|
|
2676
|
+
/** Queue the end marker behind everything already queued, dropping nothing. */
|
|
2677
|
+
end() {
|
|
2678
|
+
const waiter = this.#waiters.shift();
|
|
2679
|
+
if (waiter) waiter(null);
|
|
2680
|
+
else this.#items.push(null);
|
|
2681
|
+
}
|
|
2095
2682
|
get(timeoutMs) {
|
|
2096
2683
|
if (this.#items.length) return Promise.resolve(this.#items.shift());
|
|
2097
2684
|
return new Promise((resolve, reject) => {
|
|
@@ -2110,7 +2697,8 @@ var MessageQueue = class {
|
|
|
2110
2697
|
});
|
|
2111
2698
|
}
|
|
2112
2699
|
};
|
|
2113
|
-
var
|
|
2700
|
+
var UNPINGED_CHANNELS = /* @__PURE__ */ new Set(["market", "rfq", "combo_quote"]);
|
|
2701
|
+
var Channel = (_class5 = class {
|
|
2114
2702
|
/** The wire topic, e.g. `orders:<user_id>`. */
|
|
2115
2703
|
|
|
2116
2704
|
/** The topic without the user id, e.g. `orders`. */
|
|
@@ -2120,19 +2708,32 @@ var Channel = (_class4 = class {
|
|
|
2120
2708
|
|
|
2121
2709
|
|
|
2122
2710
|
/** The `response` object from the latest join reply, e.g. `{selected_market_ids: null}`. */
|
|
2123
|
-
|
|
2711
|
+
__init6() {this.reply = {}}
|
|
2124
2712
|
/** The latest snapshot payload per snapshot event name. */
|
|
2125
|
-
|
|
2713
|
+
__init7() {this.snapshots = {}}
|
|
2126
2714
|
/** Market ids watched on `market_updates`; re-sent after a reconnect. */
|
|
2127
|
-
|
|
2128
|
-
|
|
2129
|
-
|
|
2130
|
-
|
|
2715
|
+
__init8() {this.watches = []}
|
|
2716
|
+
__init9() {this.joinRef = null}
|
|
2717
|
+
__init10() {this.joined = false}
|
|
2718
|
+
__init11() {this.closed = false}
|
|
2131
2719
|
#ws;
|
|
2132
2720
|
#queue;
|
|
2133
2721
|
#snapshotWaiters = [];
|
|
2134
2722
|
#pingTimer;
|
|
2135
|
-
|
|
2723
|
+
/** @internal Milliseconds between pings while joined; null when none are sent. */
|
|
2724
|
+
__init12() {this._pingEveryMs = null}
|
|
2725
|
+
// One phx_join per topic per connection (Phoenix answers a second join of a
|
|
2726
|
+
// joined topic by closing the first): joins run one after another, and a
|
|
2727
|
+
// join already made on the current connection is not repeated.
|
|
2728
|
+
/** @internal */
|
|
2729
|
+
__init13() {this._joinTail = Promise.resolve()}
|
|
2730
|
+
/** @internal */
|
|
2731
|
+
__init14() {this._joinedConnection = 0}
|
|
2732
|
+
/** @internal The connection whose join also restored watches and the pinger. */
|
|
2733
|
+
__init15() {this._restoredConnection = 0}
|
|
2734
|
+
/** @internal A phx_close/phx_error for the join in flight. */
|
|
2735
|
+
__init16() {this._endedJoin = null}
|
|
2736
|
+
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);
|
|
2136
2737
|
this.#ws = ws;
|
|
2137
2738
|
this.topic = topic;
|
|
2138
2739
|
this.name = topic.split(":", 1)[0];
|
|
@@ -2297,11 +2898,12 @@ var Channel = (_class4 = class {
|
|
|
2297
2898
|
_startPinger() {
|
|
2298
2899
|
this._stopPinger();
|
|
2299
2900
|
let interval = this.pingIntervalMs;
|
|
2300
|
-
const granted = _optionalChain([this, 'access',
|
|
2901
|
+
const granted = _optionalChain([this, 'access', _32 => _32.reply, 'optionalAccess', _33 => _33.ping_timeout]);
|
|
2301
2902
|
if (typeof granted === "number" && this.joinPayload.cancel_on_disconnect) {
|
|
2302
|
-
const cod = granted
|
|
2903
|
+
const cod = granted / 3;
|
|
2303
2904
|
interval = interval === null ? cod : Math.min(interval, cod);
|
|
2304
2905
|
}
|
|
2906
|
+
this._pingEveryMs = interval || null;
|
|
2305
2907
|
if (interval) {
|
|
2306
2908
|
const every = interval;
|
|
2307
2909
|
this.#pingTimer = setInterval(() => {
|
|
@@ -2310,7 +2912,7 @@ var Channel = (_class4 = class {
|
|
|
2310
2912
|
(err) => this.#ws.logger.warn(`${this.topic} ping failed: ${err.message}`)
|
|
2311
2913
|
);
|
|
2312
2914
|
}, every);
|
|
2313
|
-
_optionalChain([this, 'access',
|
|
2915
|
+
_optionalChain([this, 'access', _34 => _34.#pingTimer, 'access', _35 => _35.unref, 'optionalCall', _36 => _36()]);
|
|
2314
2916
|
}
|
|
2315
2917
|
}
|
|
2316
2918
|
/** @internal */
|
|
@@ -2321,9 +2923,17 @@ var Channel = (_class4 = class {
|
|
|
2321
2923
|
/** @internal */
|
|
2322
2924
|
_resetForRejoin() {
|
|
2323
2925
|
this.joined = false;
|
|
2926
|
+
this._restoredConnection = 0;
|
|
2324
2927
|
this.snapshots = {};
|
|
2325
2928
|
this._stopPinger();
|
|
2326
2929
|
}
|
|
2930
|
+
/** @internal End the channel after every queued message is read. */
|
|
2931
|
+
_finish() {
|
|
2932
|
+
this.closed = true;
|
|
2933
|
+
this.joined = false;
|
|
2934
|
+
this._stopPinger();
|
|
2935
|
+
this.#queue.end();
|
|
2936
|
+
}
|
|
2327
2937
|
/** @internal */
|
|
2328
2938
|
_close() {
|
|
2329
2939
|
this.closed = true;
|
|
@@ -2331,7 +2941,7 @@ var Channel = (_class4 = class {
|
|
|
2331
2941
|
this._stopPinger();
|
|
2332
2942
|
this.#queue.put(null);
|
|
2333
2943
|
}
|
|
2334
|
-
},
|
|
2944
|
+
}, _class5);
|
|
2335
2945
|
var DEFAULT_LOGGER = {
|
|
2336
2946
|
debug: () => {
|
|
2337
2947
|
},
|
|
@@ -2340,7 +2950,7 @@ var DEFAULT_LOGGER = {
|
|
|
2340
2950
|
warn: (...a) => console.warn("[stx.ws]", ...a),
|
|
2341
2951
|
error: (...a) => console.error("[stx.ws]", ...a)
|
|
2342
2952
|
};
|
|
2343
|
-
var STXWebSocket = (
|
|
2953
|
+
var STXWebSocket = (_class6 = class {
|
|
2344
2954
|
|
|
2345
2955
|
|
|
2346
2956
|
|
|
@@ -2354,23 +2964,27 @@ var STXWebSocket = (_class5 = class {
|
|
|
2354
2964
|
|
|
2355
2965
|
|
|
2356
2966
|
|
|
2357
|
-
|
|
2967
|
+
__init17() {this.channels = /* @__PURE__ */ new Map()}
|
|
2358
2968
|
/** Successful reconnects so far. */
|
|
2359
|
-
|
|
2969
|
+
__init18() {this.reconnects = 0}
|
|
2970
|
+
/** Channels rejoined after the server closed or errored them while the socket stayed up. */
|
|
2971
|
+
__init19() {this.channelRejoins = 0}
|
|
2360
2972
|
#userId;
|
|
2361
2973
|
#conn;
|
|
2362
2974
|
#ref = 0;
|
|
2975
|
+
#connection = 0;
|
|
2363
2976
|
#pending = /* @__PURE__ */ new Map();
|
|
2364
2977
|
#heartbeat;
|
|
2365
2978
|
#pendingHeartbeat = null;
|
|
2366
2979
|
#closed = false;
|
|
2367
2980
|
#connecting;
|
|
2368
2981
|
#reconnecting = false;
|
|
2982
|
+
#reconnectDone = Promise.resolve();
|
|
2369
2983
|
#closedWaiters = [];
|
|
2370
2984
|
// Frames are handled one at a time, in arrival order: each waits for the
|
|
2371
2985
|
// previous one's handler to finish.
|
|
2372
2986
|
#inbox = Promise.resolve();
|
|
2373
|
-
constructor(opts = {}) {;
|
|
2987
|
+
constructor(opts = {}) {;_class6.prototype.__init17.call(this);_class6.prototype.__init18.call(this);_class6.prototype.__init19.call(this);
|
|
2374
2988
|
if (opts.rest) {
|
|
2375
2989
|
this.rest = opts.rest;
|
|
2376
2990
|
} else {
|
|
@@ -2415,6 +3029,11 @@ var STXWebSocket = (_class5 = class {
|
|
|
2415
3029
|
async connect() {
|
|
2416
3030
|
if (this.#closed) throw new STXTransportException("This STXWebSocket is closed; create a new one.");
|
|
2417
3031
|
if (this.connected) return this;
|
|
3032
|
+
while (this.#reconnecting) {
|
|
3033
|
+
await this.#reconnectDone;
|
|
3034
|
+
if (this.#closed) throw new STXTransportException("This STXWebSocket is closed; create a new one.");
|
|
3035
|
+
if (this.connected) return this;
|
|
3036
|
+
}
|
|
2418
3037
|
if (!this.#connecting) {
|
|
2419
3038
|
this.#connecting = this.#openAuthenticated().finally(() => {
|
|
2420
3039
|
this.#connecting = void 0;
|
|
@@ -2505,7 +3124,7 @@ var STXWebSocket = (_class5 = class {
|
|
|
2505
3124
|
*/
|
|
2506
3125
|
async marketUpdates(opts = {}) {
|
|
2507
3126
|
const channel = await this.join("market_updates", {}, opts.onMessage);
|
|
2508
|
-
if (_optionalChain([opts, 'access',
|
|
3127
|
+
if (_optionalChain([opts, 'access', _37 => _37.watch, 'optionalAccess', _38 => _38.length])) await channel.watch(opts.watch);
|
|
2509
3128
|
return channel;
|
|
2510
3129
|
}
|
|
2511
3130
|
/**
|
|
@@ -2534,7 +3153,7 @@ var STXWebSocket = (_class5 = class {
|
|
|
2534
3153
|
* `cancelOnDisconnect: true` arms cancel-on-disconnect for orders placed
|
|
2535
3154
|
* with `cancelOnDisconnect: true`. `pingTimeout` is in milliseconds,
|
|
2536
3155
|
* clamped by the server to 5000 to 20000; the granted value is in
|
|
2537
|
-
* `channel.reply.ping_timeout` and the SDK pings at
|
|
3156
|
+
* `channel.reply.ping_timeout` and the SDK pings at a third of it for as long
|
|
2538
3157
|
* as the channel is joined.
|
|
2539
3158
|
*/
|
|
2540
3159
|
orders(opts = {}) {
|
|
@@ -2583,6 +3202,53 @@ var STXWebSocket = (_class5 = class {
|
|
|
2583
3202
|
return this.#joinAccount("user_info", {}, opts.onMessage);
|
|
2584
3203
|
}
|
|
2585
3204
|
// ------------------------------------------------------------------
|
|
3205
|
+
// Combos
|
|
3206
|
+
// ------------------------------------------------------------------
|
|
3207
|
+
/**
|
|
3208
|
+
* Join `rfq:{user_id}` and return a `ComboPlayer`: request quotes on a
|
|
3209
|
+
* combination, cash one out, accept, cancel and read a request.
|
|
3210
|
+
*
|
|
3211
|
+
* Where combos are not available, rejects with
|
|
3212
|
+
* `STXCombosUnavailableException`. Other join refusals (a read-only key, an
|
|
3213
|
+
* account that may not trade) reject with `STXComboRefusedException`.
|
|
3214
|
+
*/
|
|
3215
|
+
async comboPlayer(opts = {}) {
|
|
3216
|
+
let player;
|
|
3217
|
+
const early = [];
|
|
3218
|
+
const channel = await this.#joinCombo(COMBO_PLAYER_CHANNEL, opts, async (msg) => {
|
|
3219
|
+
if (player) await player._receive(msg);
|
|
3220
|
+
else early.push(msg);
|
|
3221
|
+
});
|
|
3222
|
+
player = new ComboPlayer(channel, opts.onEvent);
|
|
3223
|
+
for (const msg of early) await player._receive(msg);
|
|
3224
|
+
return player;
|
|
3225
|
+
}
|
|
3226
|
+
/**
|
|
3227
|
+
* Join `combo_quote:{user_id}` and return a `ComboMaker`: receive every
|
|
3228
|
+
* request opened from now on (`rfq_opened`), quote and withdraw quotes.
|
|
3229
|
+
*
|
|
3230
|
+
* Where combos are not available, rejects with
|
|
3231
|
+
* `STXCombosUnavailableException`.
|
|
3232
|
+
*/
|
|
3233
|
+
async comboMaker(opts = {}) {
|
|
3234
|
+
let maker;
|
|
3235
|
+
const early = [];
|
|
3236
|
+
const channel = await this.#joinCombo(COMBO_MAKER_CHANNEL, opts, async (msg) => {
|
|
3237
|
+
if (maker) await maker._receive(msg);
|
|
3238
|
+
else early.push(msg);
|
|
3239
|
+
});
|
|
3240
|
+
maker = new ComboMaker(channel, opts.onEvent);
|
|
3241
|
+
for (const msg of early) await maker._receive(msg);
|
|
3242
|
+
return maker;
|
|
3243
|
+
}
|
|
3244
|
+
async #joinCombo(name, opts, onMessage) {
|
|
3245
|
+
try {
|
|
3246
|
+
return await this.#joinAccount(name, {}, onMessage);
|
|
3247
|
+
} catch (err) {
|
|
3248
|
+
throw comboJoinError(err, new URL(this.rest.baseUrl).host);
|
|
3249
|
+
}
|
|
3250
|
+
}
|
|
3251
|
+
// ------------------------------------------------------------------
|
|
2586
3252
|
// Generic join
|
|
2587
3253
|
// ------------------------------------------------------------------
|
|
2588
3254
|
/**
|
|
@@ -2591,11 +3257,16 @@ var STXWebSocket = (_class5 = class {
|
|
|
2591
3257
|
* `market_ids_required` or `unauthorized`) if the join is refused.
|
|
2592
3258
|
*/
|
|
2593
3259
|
async join(topic, payload = {}, onMessage, opts = {}) {
|
|
2594
|
-
const
|
|
2595
|
-
|
|
3260
|
+
const already = () => {
|
|
3261
|
+
const existing = this.channels.get(topic);
|
|
3262
|
+
if (existing && !existing.closed) throw new STXChannelException(`Already joined ${topic}`, { topic });
|
|
3263
|
+
};
|
|
3264
|
+
already();
|
|
2596
3265
|
await this.connect();
|
|
3266
|
+
already();
|
|
3267
|
+
const name = topic.split(":", 1)[0];
|
|
2597
3268
|
const channel = new Channel(this, topic, payload, onMessage, {
|
|
2598
|
-
pingIntervalMs: opts.pingIntervalMs
|
|
3269
|
+
pingIntervalMs: opts.pingIntervalMs !== void 0 ? opts.pingIntervalMs : UNPINGED_CHANNELS.has(name) ? null : this.channelPingIntervalMs,
|
|
2599
3270
|
queueSize: this.queueSize
|
|
2600
3271
|
});
|
|
2601
3272
|
this.channels.set(topic, channel);
|
|
@@ -2616,16 +3287,56 @@ var STXWebSocket = (_class5 = class {
|
|
|
2616
3287
|
}
|
|
2617
3288
|
return this.join(`${name}:${await this.userId()}`, payload, onMessage);
|
|
2618
3289
|
}
|
|
2619
|
-
|
|
3290
|
+
/**
|
|
3291
|
+
* Join `channel` on the current connection unless it already is, then
|
|
3292
|
+
* restore its watches and pinger; resolves to whether anything was done.
|
|
3293
|
+
*/
|
|
3294
|
+
#join(channel) {
|
|
3295
|
+
const run = channel._joinTail.then(async () => {
|
|
3296
|
+
const connection = this.#connection;
|
|
3297
|
+
if (channel.closed) return false;
|
|
3298
|
+
if (channel.joined && channel._joinedConnection === connection) {
|
|
3299
|
+
if (channel._restoredConnection === connection) return false;
|
|
3300
|
+
await this.#restore(channel, connection);
|
|
3301
|
+
return true;
|
|
3302
|
+
}
|
|
3303
|
+
await this.#joinNow(channel, connection);
|
|
3304
|
+
await this.#restore(channel, connection);
|
|
3305
|
+
return true;
|
|
3306
|
+
});
|
|
3307
|
+
channel._joinTail = run.catch(() => {
|
|
3308
|
+
});
|
|
3309
|
+
return run;
|
|
3310
|
+
}
|
|
3311
|
+
async #joinNow(channel, connection) {
|
|
2620
3312
|
const ref = this.#nextRef();
|
|
2621
3313
|
channel.joinRef = ref;
|
|
2622
3314
|
channel._resetForRejoin();
|
|
3315
|
+
channel._endedJoin = null;
|
|
2623
3316
|
const reply = await this._request(channel.topic, "phx_join", channel.joinPayload, ref, void 0, ref);
|
|
3317
|
+
const ended = channel._endedJoin;
|
|
3318
|
+
if (ended && ended.joinRef === ref) {
|
|
3319
|
+
channel._endedJoin = null;
|
|
3320
|
+
throw joinInterrupted(channel, ended.event);
|
|
3321
|
+
}
|
|
2624
3322
|
channel.reply = reply && typeof reply === "object" && !Array.isArray(reply) ? reply : { response: reply };
|
|
2625
3323
|
if (channel.name === "market") channel.reply = convertMarketChannelPayload(channel.reply);
|
|
3324
|
+
channel._joinedConnection = connection;
|
|
2626
3325
|
channel.joined = true;
|
|
2627
|
-
|
|
3326
|
+
}
|
|
3327
|
+
async #restore(channel, connection) {
|
|
3328
|
+
if (channel.watches.length) {
|
|
3329
|
+
await channel.push("watch", [...channel.watches]);
|
|
3330
|
+
if (channel.closed || !channel.joined || channel._joinedConnection !== connection) {
|
|
3331
|
+
throw joinInterrupted(channel, "phx_close");
|
|
3332
|
+
}
|
|
3333
|
+
}
|
|
2628
3334
|
channel._startPinger();
|
|
3335
|
+
channel._restoredConnection = connection;
|
|
3336
|
+
}
|
|
3337
|
+
#finishMarket(channel) {
|
|
3338
|
+
channel._finish();
|
|
3339
|
+
if (this.channels.get(channel.topic) === channel) this.channels.delete(channel.topic);
|
|
2629
3340
|
}
|
|
2630
3341
|
/** @internal */
|
|
2631
3342
|
async _leave(channel) {
|
|
@@ -2662,12 +3373,12 @@ var STXWebSocket = (_class5 = class {
|
|
|
2662
3373
|
if (!(err instanceof STXTransportException)) return false;
|
|
2663
3374
|
if (err.statusCode !== 401 && err.statusCode !== 403) return false;
|
|
2664
3375
|
const auth = this.rest.auth;
|
|
2665
|
-
if (!_optionalChain([auth, 'optionalAccess',
|
|
3376
|
+
if (!_optionalChain([auth, 'optionalAccess', _39 => _39.onUnauthorized])) return false;
|
|
2666
3377
|
return auth.onUnauthorized();
|
|
2667
3378
|
}
|
|
2668
3379
|
async #open(reconnect = false) {
|
|
2669
3380
|
const headers = { "User-Agent": USER_AGENT };
|
|
2670
|
-
if (_optionalChain([this, 'access',
|
|
3381
|
+
if (_optionalChain([this, 'access', _40 => _40.rest, 'access', _41 => _41.auth, 'optionalAccess', _42 => _42.websocketHeaders])) Object.assign(headers, await this.rest.auth.websocketHeaders({ reconnect }));
|
|
2671
3382
|
const conn = new (0, _ws2.default)(this.url, {
|
|
2672
3383
|
headers,
|
|
2673
3384
|
rejectUnauthorized: this.rest.verifyTls,
|
|
@@ -2680,8 +3391,10 @@ var STXWebSocket = (_class5 = class {
|
|
|
2680
3391
|
};
|
|
2681
3392
|
const onUnexpected = (_req, res) => {
|
|
2682
3393
|
cleanup();
|
|
3394
|
+
conn.on("error", () => {
|
|
3395
|
+
});
|
|
2683
3396
|
conn.terminate();
|
|
2684
|
-
const reason = _optionalChain([res, 'access',
|
|
3397
|
+
const reason = _optionalChain([res, 'access', _43 => _43.headers, 'optionalAccess', _44 => _44["x-stx-error"]]);
|
|
2685
3398
|
reject(
|
|
2686
3399
|
new STXTransportException(
|
|
2687
3400
|
`Could not open ${this.url}: HTTP ${res.statusCode}${reason ? ` (${String(reason)})` : ""}`,
|
|
@@ -2706,6 +3419,7 @@ var STXWebSocket = (_class5 = class {
|
|
|
2706
3419
|
conn.on("message", (data) => this.#onFrame(data.toString()));
|
|
2707
3420
|
conn.on("close", () => this.#onConnClose(conn));
|
|
2708
3421
|
this.#conn = conn;
|
|
3422
|
+
this.#connection += 1;
|
|
2709
3423
|
this.#pendingHeartbeat = null;
|
|
2710
3424
|
this.#startHeartbeat();
|
|
2711
3425
|
this.logger.debug(`connected to ${this.url}`);
|
|
@@ -2716,7 +3430,7 @@ var STXWebSocket = (_class5 = class {
|
|
|
2716
3430
|
if (conn) {
|
|
2717
3431
|
try {
|
|
2718
3432
|
conn.terminate();
|
|
2719
|
-
} catch (
|
|
3433
|
+
} catch (e11) {
|
|
2720
3434
|
}
|
|
2721
3435
|
}
|
|
2722
3436
|
}
|
|
@@ -2755,7 +3469,7 @@ var STXWebSocket = (_class5 = class {
|
|
|
2755
3469
|
let frame;
|
|
2756
3470
|
try {
|
|
2757
3471
|
frame = JSON.parse(raw);
|
|
2758
|
-
} catch (
|
|
3472
|
+
} catch (e12) {
|
|
2759
3473
|
this.logger.warn(`unparseable frame: ${raw.slice(0, 200)}`);
|
|
2760
3474
|
return;
|
|
2761
3475
|
}
|
|
@@ -2789,15 +3503,29 @@ var STXWebSocket = (_class5 = class {
|
|
|
2789
3503
|
}
|
|
2790
3504
|
const channel = this.channels.get(topic);
|
|
2791
3505
|
if (!channel) return;
|
|
2792
|
-
if (joinRef !== null && joinRef !== void 0 && channel.joinRef !== null && String(joinRef) !== channel.joinRef) {
|
|
2793
|
-
return;
|
|
2794
|
-
}
|
|
2795
3506
|
if (event === "phx_error" || event === "phx_close") {
|
|
2796
|
-
if (
|
|
2797
|
-
|
|
2798
|
-
|
|
2799
|
-
|
|
3507
|
+
if (joinRef === null || joinRef === void 0 || String(joinRef) !== channel.joinRef) return;
|
|
3508
|
+
if (channel.closed || this.#closed) return;
|
|
3509
|
+
if (!channel.joined) {
|
|
3510
|
+
channel._endedJoin = { joinRef: String(joinRef), event };
|
|
3511
|
+
const pending = this.#pending.get(String(joinRef));
|
|
3512
|
+
if (_optionalChain([pending, 'optionalAccess', _45 => _45.event]) === "phx_join") pending.reject(joinInterrupted(channel, event));
|
|
3513
|
+
if (event === "phx_close" && channel.name === "market") this.#finishMarket(channel);
|
|
3514
|
+
return;
|
|
2800
3515
|
}
|
|
3516
|
+
for (const pending of [...this.#pending.values()]) {
|
|
3517
|
+
if (pending.topic === channel.topic) pending.reject(joinInterrupted(channel, event));
|
|
3518
|
+
}
|
|
3519
|
+
if (event === "phx_close" && channel.name === "market") {
|
|
3520
|
+
this.#finishMarket(channel);
|
|
3521
|
+
return;
|
|
3522
|
+
}
|
|
3523
|
+
this.logger.warn(`${topic}: server sent ${event}; rejoining`);
|
|
3524
|
+
channel._resetForRejoin();
|
|
3525
|
+
void this.#rejoinLater(channel, true);
|
|
3526
|
+
return;
|
|
3527
|
+
}
|
|
3528
|
+
if (joinRef !== null && joinRef !== void 0 && channel.joinRef !== null && String(joinRef) !== channel.joinRef) {
|
|
2801
3529
|
return;
|
|
2802
3530
|
}
|
|
2803
3531
|
if (channel.name === "markets") payload = convertMarketsFrame(payload);
|
|
@@ -2815,18 +3543,26 @@ var STXWebSocket = (_class5 = class {
|
|
|
2815
3543
|
)
|
|
2816
3544
|
);
|
|
2817
3545
|
}
|
|
2818
|
-
|
|
3546
|
+
/**
|
|
3547
|
+
* Rejoin `channel` with backoff. `serverClosed`: the server closed or
|
|
3548
|
+
* errored it while the socket stayed up (counted in `channelRejoins`);
|
|
3549
|
+
* otherwise a rejoin refused during a socket reconnect is being retried.
|
|
3550
|
+
*/
|
|
3551
|
+
async #rejoinLater(channel, serverClosed) {
|
|
2819
3552
|
let attempt = 1;
|
|
2820
3553
|
while (!channel.closed && !this.#closed) {
|
|
2821
3554
|
await sleep2(this.reconnectPolicy.delayMs(attempt));
|
|
2822
3555
|
if (!this.connected) return;
|
|
2823
3556
|
try {
|
|
2824
|
-
await this.#join(channel)
|
|
3557
|
+
if (await this.#join(channel) && channel.joined && !channel.closed) {
|
|
3558
|
+
if (serverClosed) this.channelRejoins += 1;
|
|
3559
|
+
await this.#raiseReconnect();
|
|
3560
|
+
}
|
|
2825
3561
|
return;
|
|
2826
3562
|
} catch (err) {
|
|
2827
3563
|
this.logger.error(`rejoin ${channel.topic} failed: ${err.message}`);
|
|
2828
3564
|
const reply = err instanceof STXChannelException ? err.reply : void 0;
|
|
2829
|
-
if (_optionalChain([reply, 'optionalAccess',
|
|
3565
|
+
if (_optionalChain([reply, 'optionalAccess', _46 => _46.reason]) === "unauthorized" || _optionalChain([reply, 'optionalAccess', _47 => _47.reason]) === COMBOS_UNAVAILABLE_REASON && COMBO_CHANNELS.has(channel.name)) {
|
|
2830
3566
|
channel._close();
|
|
2831
3567
|
return;
|
|
2832
3568
|
}
|
|
@@ -2840,15 +3576,15 @@ var STXWebSocket = (_class5 = class {
|
|
|
2840
3576
|
if (!this.connected) return;
|
|
2841
3577
|
if (this.#pendingHeartbeat !== null) {
|
|
2842
3578
|
this.logger.warn("heartbeat unanswered; reconnecting");
|
|
2843
|
-
_optionalChain([this, 'access',
|
|
3579
|
+
_optionalChain([this, 'access', _48 => _48.#conn, 'optionalAccess', _49 => _49.terminate, 'call', _50 => _50()]);
|
|
2844
3580
|
return;
|
|
2845
3581
|
}
|
|
2846
3582
|
const ref = this.#nextRef();
|
|
2847
3583
|
this.#pendingHeartbeat = ref;
|
|
2848
3584
|
try {
|
|
2849
3585
|
this.#send([null, ref, PHOENIX_TOPIC, "heartbeat", {}]);
|
|
2850
|
-
} catch (
|
|
2851
|
-
_optionalChain([this, 'access',
|
|
3586
|
+
} catch (e13) {
|
|
3587
|
+
_optionalChain([this, 'access', _51 => _51.#conn, 'optionalAccess', _52 => _52.terminate, 'call', _53 => _53()]);
|
|
2852
3588
|
}
|
|
2853
3589
|
}, this.heartbeatIntervalMs);
|
|
2854
3590
|
}
|
|
@@ -2871,6 +3607,8 @@ var STXWebSocket = (_class5 = class {
|
|
|
2871
3607
|
}
|
|
2872
3608
|
async #reconnectLoop() {
|
|
2873
3609
|
this.#reconnecting = true;
|
|
3610
|
+
let finished;
|
|
3611
|
+
this.#reconnectDone = new Promise((r) => finished = r);
|
|
2874
3612
|
let ok = false;
|
|
2875
3613
|
try {
|
|
2876
3614
|
let attempt = 1;
|
|
@@ -2892,13 +3630,13 @@ var STXWebSocket = (_class5 = class {
|
|
|
2892
3630
|
} catch (err) {
|
|
2893
3631
|
if (!(err instanceof STXChannelException)) throw err;
|
|
2894
3632
|
this.logger.error(`rejoin ${channel.topic} failed: ${err.message}; retrying`);
|
|
2895
|
-
void this.#rejoinLater(channel);
|
|
3633
|
+
void this.#rejoinLater(channel, false);
|
|
2896
3634
|
}
|
|
2897
3635
|
}
|
|
2898
3636
|
this.reconnects += 1;
|
|
2899
3637
|
this.logger.info(`reconnected (${this.reconnects})`);
|
|
2900
3638
|
ok = true;
|
|
2901
|
-
|
|
3639
|
+
void this.#raiseReconnect();
|
|
2902
3640
|
return;
|
|
2903
3641
|
} catch (err) {
|
|
2904
3642
|
this.#closeConn();
|
|
@@ -2914,17 +3652,26 @@ var STXWebSocket = (_class5 = class {
|
|
|
2914
3652
|
}
|
|
2915
3653
|
} finally {
|
|
2916
3654
|
this.#reconnecting = false;
|
|
3655
|
+
finished();
|
|
2917
3656
|
if (ok && !this.#closed && !this.connected) {
|
|
2918
3657
|
for (const channel of this.channels.values()) channel._resetForRejoin();
|
|
2919
3658
|
void this.#reconnectLoop();
|
|
2920
3659
|
}
|
|
2921
3660
|
}
|
|
2922
3661
|
}
|
|
3662
|
+
async #raiseReconnect() {
|
|
3663
|
+
if (!this.onReconnect) return;
|
|
3664
|
+
try {
|
|
3665
|
+
await this.onReconnect();
|
|
3666
|
+
} catch (err) {
|
|
3667
|
+
this.logger.error("onReconnect threw", err);
|
|
3668
|
+
}
|
|
3669
|
+
}
|
|
2923
3670
|
#failAuth(err) {
|
|
2924
3671
|
this.error = err;
|
|
2925
3672
|
this.#shutdownAfterDrop();
|
|
2926
3673
|
try {
|
|
2927
|
-
_optionalChain([this, 'access',
|
|
3674
|
+
_optionalChain([this, 'access', _54 => _54.onAuthError, 'optionalCall', _55 => _55(err)]);
|
|
2928
3675
|
} catch (hookErr) {
|
|
2929
3676
|
this.logger.error("onAuthError threw", hookErr);
|
|
2930
3677
|
}
|
|
@@ -2940,7 +3687,13 @@ var STXWebSocket = (_class5 = class {
|
|
|
2940
3687
|
this.#closedWaiters = [];
|
|
2941
3688
|
for (const w of waiters) w();
|
|
2942
3689
|
}
|
|
2943
|
-
},
|
|
3690
|
+
}, _class6);
|
|
3691
|
+
function joinInterrupted(channel, event) {
|
|
3692
|
+
return new STXChannelException(`${event} on ${channel.topic} while joining`, {
|
|
3693
|
+
topic: channel.topic,
|
|
3694
|
+
reply: { reason: event }
|
|
3695
|
+
});
|
|
3696
|
+
}
|
|
2944
3697
|
function dropUndefined(payload) {
|
|
2945
3698
|
return Object.fromEntries(
|
|
2946
3699
|
Object.entries(payload).filter(([, v]) => v !== void 0).map(([k, v]) => [k, Array.isArray(v) ? [...v] : v])
|
|
@@ -3009,5 +3762,15 @@ function dropUndefined(payload) {
|
|
|
3009
3762
|
|
|
3010
3763
|
|
|
3011
3764
|
|
|
3012
|
-
|
|
3013
|
-
|
|
3765
|
+
|
|
3766
|
+
|
|
3767
|
+
|
|
3768
|
+
|
|
3769
|
+
|
|
3770
|
+
|
|
3771
|
+
|
|
3772
|
+
|
|
3773
|
+
|
|
3774
|
+
|
|
3775
|
+
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.STXNotFoundException = STXNotFoundException; exports.STXRejectedException = STXRejectedException; 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;
|
|
3776
|
+
//# sourceMappingURL=chunk-42OCIF3G.cjs.map
|