@stxapp/stx-typescript 0.9.0-alpha.1 → 0.9.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 +46 -16
- package/README.md +27 -24
- package/dist/{chunk-4CSBA2YV.js → chunk-46XK6VDD.js} +778 -44
- package/dist/chunk-46XK6VDD.js.map +1 -0
- package/dist/{chunk-33AQCUGM.cjs → chunk-R77AZ5UH.cjs} +840 -106
- package/dist/chunk-R77AZ5UH.cjs.map +1 -0
- package/dist/{client-CNkaTuhG.d.ts → client-B-MMKiRt.d.cts} +645 -43
- package/dist/{client-CNkaTuhG.d.cts → client-B-MMKiRt.d.ts} +645 -43
- package/dist/index.cjs +24 -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 -1
- 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,14 +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
|
|
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/geo.ts
|
|
12
2
|
var IP_NOT_ALLOWED = /from this IP address (\S+?) is disallowed/i;
|
|
13
3
|
function geoRejection(message) {
|
|
14
4
|
const ip = IP_NOT_ALLOWED.exec(message);
|
|
@@ -68,6 +58,16 @@ var STXInvalidTokenException = class extends STXAuthenticationException {
|
|
|
68
58
|
};
|
|
69
59
|
var STXInsufficientScopeException = class extends STXForbiddenException {
|
|
70
60
|
};
|
|
61
|
+
var STXTermsRequiredException = class extends STXForbiddenException {
|
|
62
|
+
/** The STX page where the member accepts the terms, when the answer names it. */
|
|
63
|
+
|
|
64
|
+
constructor(message, opts = {}) {
|
|
65
|
+
super(message, opts);
|
|
66
|
+
this.termsUrl = opts.termsUrl;
|
|
67
|
+
}
|
|
68
|
+
};
|
|
69
|
+
var STXIPNotAllowedException = class extends STXForbiddenException {
|
|
70
|
+
};
|
|
71
71
|
var STXNotFoundException = class extends STXAPIException {
|
|
72
72
|
};
|
|
73
73
|
var STXRejectedException = class extends STXAPIException {
|
|
@@ -114,6 +114,87 @@ var STXChannelException = class extends STXException {
|
|
|
114
114
|
};
|
|
115
115
|
var STXTimeoutException = class extends STXChannelException {
|
|
116
116
|
};
|
|
117
|
+
var NOT_AVAILABLE = /* @__PURE__ */ Symbol.for("@stxapp/stx-typescript.notAvailable");
|
|
118
|
+
var FEATURE_PHRASES = {
|
|
119
|
+
oauth: "OAuth is",
|
|
120
|
+
"oauth.member": "Member sign-in with OAuth is",
|
|
121
|
+
"oauth.app": "App tokens are",
|
|
122
|
+
connect: "Sign in with STX is",
|
|
123
|
+
"terms.stx_page": "Accepting terms on an STX page is",
|
|
124
|
+
"markets.create": "Creating markets is",
|
|
125
|
+
market_types: "Market types are",
|
|
126
|
+
event_players: "Event players are",
|
|
127
|
+
leaderboard: "The leaderboard is",
|
|
128
|
+
combos: "Combos are"
|
|
129
|
+
};
|
|
130
|
+
function notAvailableMessage(feature, host) {
|
|
131
|
+
const phrase = feature.startsWith("scope:") ? `The ${feature.slice("scope:".length)} scope is` : _nullishCoalesce(FEATURE_PHRASES[feature], () => ( `${feature} is`));
|
|
132
|
+
return `${phrase} not available on ${host} yet.`;
|
|
133
|
+
}
|
|
134
|
+
var STXNotAvailableException = class _STXNotAvailableException extends STXAPIException {
|
|
135
|
+
/** The feature id, e.g. `"combos"`. */
|
|
136
|
+
|
|
137
|
+
/** The exchange host that lacks it, e.g. `"demo.stxapp.ca"`. */
|
|
138
|
+
|
|
139
|
+
constructor(feature, host, opts = {}) {
|
|
140
|
+
super(_nullishCoalesce(opts.message, () => ( notAvailableMessage(feature, host))), opts);
|
|
141
|
+
this.feature = feature;
|
|
142
|
+
this.host = host;
|
|
143
|
+
markNotAvailable(this);
|
|
144
|
+
}
|
|
145
|
+
// `this` is the class on the right of `instanceof`: a subclass keeps the
|
|
146
|
+
// ordinary check, only the base class also accepts marked exceptions.
|
|
147
|
+
static [Symbol.hasInstance](value) {
|
|
148
|
+
const cls = this;
|
|
149
|
+
if (Function.prototype[Symbol.hasInstance].call(cls, value)) return true;
|
|
150
|
+
return cls === _STXNotAvailableException && typeof value === "object" && value !== null && value[NOT_AVAILABLE] === true;
|
|
151
|
+
}
|
|
152
|
+
};
|
|
153
|
+
function markNotAvailable(err) {
|
|
154
|
+
Object.defineProperty(err, NOT_AVAILABLE, { value: true, enumerable: false });
|
|
155
|
+
}
|
|
156
|
+
var STXCombosUnavailableException = (_class = class extends STXChannelException {
|
|
157
|
+
__init() {this.feature = "combos"}
|
|
158
|
+
/** The exchange host that lacks combos. */
|
|
159
|
+
|
|
160
|
+
constructor(message, opts = {}) {
|
|
161
|
+
super(message, opts);_class.prototype.__init.call(this);;
|
|
162
|
+
this.host = _nullishCoalesce(opts.host, () => ( ""));
|
|
163
|
+
markNotAvailable(this);
|
|
164
|
+
}
|
|
165
|
+
}, _class);
|
|
166
|
+
function isMissingRoute(err) {
|
|
167
|
+
if (!(err instanceof STXNotFoundException)) return false;
|
|
168
|
+
const body = err.body;
|
|
169
|
+
return !!body && typeof body === "object" && body.error === "not_found" && Object.keys(body).length === 1;
|
|
170
|
+
}
|
|
171
|
+
function isEdgeBlock(status, text) {
|
|
172
|
+
if (status !== 403) return false;
|
|
173
|
+
try {
|
|
174
|
+
JSON.parse(text);
|
|
175
|
+
return false;
|
|
176
|
+
} catch (e2) {
|
|
177
|
+
return true;
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
var STXComboRefusedException = class extends STXChannelException {
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
constructor(message, opts) {
|
|
185
|
+
super(message, opts);
|
|
186
|
+
this.command = opts.command;
|
|
187
|
+
this.code = opts.code;
|
|
188
|
+
this.detail = opts.detail;
|
|
189
|
+
}
|
|
190
|
+
};
|
|
191
|
+
var STXComboPriceMovedException = class extends STXComboRefusedException {
|
|
192
|
+
|
|
193
|
+
constructor(message, opts) {
|
|
194
|
+
super(message, opts);
|
|
195
|
+
this.best = opts.best;
|
|
196
|
+
}
|
|
197
|
+
};
|
|
117
198
|
function errorForStatus(statusCode, body, opts) {
|
|
118
199
|
let message;
|
|
119
200
|
if (body && typeof body === "object" && typeof body.error === "string") {
|
|
@@ -130,6 +211,16 @@ function errorForStatus(statusCode, body, opts) {
|
|
|
130
211
|
case 401:
|
|
131
212
|
return bearerError(opts.wwwAuthenticate) === "invalid_token" ? new STXInvalidTokenException(message, base) : new STXAuthenticationException(message, base);
|
|
132
213
|
case 403: {
|
|
214
|
+
const fields = body && typeof body === "object" ? body : {};
|
|
215
|
+
if (fields.error === "ip_not_allowed") {
|
|
216
|
+
const description = typeof fields.error_description === "string" ? fields.error_description : message;
|
|
217
|
+
return new STXIPNotAllowedException(description, base);
|
|
218
|
+
}
|
|
219
|
+
if (fields.error === "terms_required") {
|
|
220
|
+
const description = typeof fields.error_description === "string" ? fields.error_description : message;
|
|
221
|
+
const termsUrl = typeof fields.terms_url === "string" ? fields.terms_url : void 0;
|
|
222
|
+
return new STXTermsRequiredException(description, { ...base, termsUrl });
|
|
223
|
+
}
|
|
133
224
|
if (bearerError(opts.wwwAuthenticate) === "insufficient_scope" || /insufficient scope/i.test(message)) {
|
|
134
225
|
return new STXInsufficientScopeException(message, {
|
|
135
226
|
...base,
|
|
@@ -168,6 +259,147 @@ function insufficientScopes(header, body) {
|
|
|
168
259
|
return raw ? raw.split(/\s+/).filter(Boolean) : [];
|
|
169
260
|
}
|
|
170
261
|
|
|
262
|
+
// src/capabilities.ts
|
|
263
|
+
var FEATURES = [
|
|
264
|
+
"oauth",
|
|
265
|
+
"oauth.member",
|
|
266
|
+
"oauth.app",
|
|
267
|
+
"connect",
|
|
268
|
+
"terms.stx_page",
|
|
269
|
+
"markets.create",
|
|
270
|
+
"market_types",
|
|
271
|
+
"event_players",
|
|
272
|
+
"leaderboard",
|
|
273
|
+
"combos"
|
|
274
|
+
];
|
|
275
|
+
var MEMBER_SCOPES = [
|
|
276
|
+
"profile.read",
|
|
277
|
+
"balance.read",
|
|
278
|
+
"portfolio.read",
|
|
279
|
+
"orders.read",
|
|
280
|
+
"transfers.read",
|
|
281
|
+
"orders.write"
|
|
282
|
+
];
|
|
283
|
+
var Capabilities = class {
|
|
284
|
+
/** The exchange host, e.g. `"demo.stxapp.io"`. */
|
|
285
|
+
|
|
286
|
+
/** `GET /api_version`, e.g. `"3.3.196-rnd.9"`, or null when it did not answer. */
|
|
287
|
+
|
|
288
|
+
/** When the checks ran. */
|
|
289
|
+
|
|
290
|
+
/** The scopes the exchange's OAuth discovery document lists; empty without OAuth. */
|
|
291
|
+
|
|
292
|
+
/** Every feature and whether the exchange has it. */
|
|
293
|
+
|
|
294
|
+
constructor(init) {
|
|
295
|
+
this.host = init.host;
|
|
296
|
+
this.apiVersion = init.apiVersion;
|
|
297
|
+
this.checkedAt = init.checkedAt;
|
|
298
|
+
this.scopesSupported = init.scopesSupported;
|
|
299
|
+
this.features = init.features;
|
|
300
|
+
}
|
|
301
|
+
/** True only when the exchange is known to have `feature`. */
|
|
302
|
+
has(feature) {
|
|
303
|
+
return this.features[feature] === true;
|
|
304
|
+
}
|
|
305
|
+
/**
|
|
306
|
+
* Throw `STXNotAvailableException` unless the exchange is known to have
|
|
307
|
+
* `feature`. A feature that could not be checked (`null`) does not throw:
|
|
308
|
+
* the call itself will say.
|
|
309
|
+
*/
|
|
310
|
+
require(feature) {
|
|
311
|
+
if (this.features[feature] === false) throw new STXNotAvailableException(feature, this.host);
|
|
312
|
+
}
|
|
313
|
+
toJSON() {
|
|
314
|
+
return {
|
|
315
|
+
host: this.host,
|
|
316
|
+
apiVersion: this.apiVersion,
|
|
317
|
+
checkedAt: this.checkedAt.toISOString(),
|
|
318
|
+
scopesSupported: this.scopesSupported,
|
|
319
|
+
features: this.features
|
|
320
|
+
};
|
|
321
|
+
}
|
|
322
|
+
};
|
|
323
|
+
var NOBODY = "00000000-0000-0000-0000-000000000000";
|
|
324
|
+
function json(answer) {
|
|
325
|
+
if (!answer) return null;
|
|
326
|
+
try {
|
|
327
|
+
const parsed = JSON.parse(answer.text);
|
|
328
|
+
return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : null;
|
|
329
|
+
} catch (e3) {
|
|
330
|
+
return null;
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
function strings(value) {
|
|
334
|
+
return Array.isArray(value) ? value.filter((v) => typeof v === "string") : [];
|
|
335
|
+
}
|
|
336
|
+
function missingRoute(answer) {
|
|
337
|
+
if (!answer || answer.status !== 404) return false;
|
|
338
|
+
const body = json(answer);
|
|
339
|
+
return !!body && body.error === "not_found" && Object.keys(body).length === 1;
|
|
340
|
+
}
|
|
341
|
+
function oauthMetadataFrom(answer) {
|
|
342
|
+
if (!answer) return null;
|
|
343
|
+
const body = json(answer);
|
|
344
|
+
if (answer.status === 404) return false;
|
|
345
|
+
if (answer.status === 403 && !body) return false;
|
|
346
|
+
if (answer.status !== 200 || !body) return null;
|
|
347
|
+
if (typeof body.issuer !== "string" || typeof body.authorization_endpoint !== "string" || typeof body.token_endpoint !== "string") {
|
|
348
|
+
return null;
|
|
349
|
+
}
|
|
350
|
+
return body;
|
|
351
|
+
}
|
|
352
|
+
async function discoverCapabilities(probes) {
|
|
353
|
+
const swallow = (p) => p ? p.catch(() => null) : Promise.resolve(null);
|
|
354
|
+
const [version, discovery, types, players, board, combos] = await Promise.all([
|
|
355
|
+
swallow(probes.get("/api_version")),
|
|
356
|
+
swallow(probes.get("/.well-known/oauth-authorization-server")),
|
|
357
|
+
swallow(probes.signedGet("/api/v1/types")),
|
|
358
|
+
swallow(probes.signedGet(`/api/v1/events/${NOBODY}/players`)),
|
|
359
|
+
swallow(probes.signedGet("/api/v1/leaderboard?limit=1")),
|
|
360
|
+
swallow(probes.joinReason(`rfq:${NOBODY}`))
|
|
361
|
+
]);
|
|
362
|
+
const apiVersion = _optionalChain([json, 'call', _5 => _5(version), 'optionalAccess', _6 => _6.api_version]);
|
|
363
|
+
const meta = oauthMetadataFrom(discovery);
|
|
364
|
+
const scopes = meta ? strings(meta.scopes_supported) : [];
|
|
365
|
+
const grants = meta ? strings(meta.grant_types_supported) : [];
|
|
366
|
+
const fromMeta = (decide) => meta === null ? null : meta === false ? false : decide();
|
|
367
|
+
const oauth = fromMeta(() => true);
|
|
368
|
+
const member = fromMeta(() => grants.includes("authorization_code") && scopes.some((s) => MEMBER_SCOPES.includes(s)));
|
|
369
|
+
const app = fromMeta(() => grants.includes("client_credentials"));
|
|
370
|
+
const features = {
|
|
371
|
+
oauth,
|
|
372
|
+
"oauth.member": member,
|
|
373
|
+
"oauth.app": app,
|
|
374
|
+
connect: fromMeta(() => scopes.includes("openid")),
|
|
375
|
+
"terms.stx_page": fromMeta(() => member === true && !scopes.includes("terms.write")),
|
|
376
|
+
"markets.create": fromMeta(() => app === true && scopes.includes("markets.write")),
|
|
377
|
+
market_types: types === null ? null : types.status >= 200 && types.status < 300 ? true : missingRoute(types) ? false : null,
|
|
378
|
+
// A 404 about the event (not about the route) means the route is there.
|
|
379
|
+
event_players: players === null ? null : missingRoute(players) ? false : players.status === 404 || players.status < 300 ? true : null,
|
|
380
|
+
// Switched off answers 404 too ("Leaderboard is not enabled").
|
|
381
|
+
leaderboard: board === null ? null : board.status >= 200 && board.status < 300 ? true : board.status === 404 ? false : null,
|
|
382
|
+
combos: combos === null ? null : combos !== "unmatched topic"
|
|
383
|
+
};
|
|
384
|
+
return new Capabilities({
|
|
385
|
+
host: probes.host,
|
|
386
|
+
apiVersion: typeof apiVersion === "string" ? apiVersion : null,
|
|
387
|
+
checkedAt: /* @__PURE__ */ new Date(),
|
|
388
|
+
scopesSupported: scopes,
|
|
389
|
+
features
|
|
390
|
+
});
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
// src/enums.ts
|
|
394
|
+
var Region = {
|
|
395
|
+
US: "us",
|
|
396
|
+
ONTARIO: "ontario"
|
|
397
|
+
};
|
|
398
|
+
var Environment = {
|
|
399
|
+
PRODUCTION: "production",
|
|
400
|
+
DEMO: "demo"
|
|
401
|
+
};
|
|
402
|
+
|
|
171
403
|
// src/config.ts
|
|
172
404
|
var Environments = {
|
|
173
405
|
/** United States demo. Shared by every integrator. No real money. */
|
|
@@ -249,7 +481,7 @@ function baseUrlFor(region, env, host) {
|
|
|
249
481
|
let parsed;
|
|
250
482
|
try {
|
|
251
483
|
parsed = new URL(h);
|
|
252
|
-
} catch (
|
|
484
|
+
} catch (e4) {
|
|
253
485
|
throw new STXConfigException(`Cannot parse host ${JSON.stringify(h)}.`);
|
|
254
486
|
}
|
|
255
487
|
return `${parsed.protocol}//${parsed.host}`;
|
|
@@ -641,16 +873,24 @@ function isValidLine(line) {
|
|
|
641
873
|
return typeof line === "number" && Number.isFinite(line) && line > 0 && line * 2 % 2 === 1;
|
|
642
874
|
}
|
|
643
875
|
function marketEntry(m) {
|
|
644
|
-
return
|
|
876
|
+
return { rule: _nullishCoalesce(m.rule, () => ( "player_stat_line")), player_id: m.playerId, stat: m.stat, line: m.line };
|
|
645
877
|
}
|
|
646
|
-
function toCreateMarketResult(raw, index) {
|
|
647
|
-
|
|
878
|
+
function toCreateMarketResult(raw, m, index) {
|
|
879
|
+
const market = marketEntry(m);
|
|
880
|
+
switch (raw.status) {
|
|
881
|
+
case "created":
|
|
882
|
+
case "exists":
|
|
883
|
+
return { index, status: raw.status, market_id: String(raw.market_id), reason: null, market };
|
|
884
|
+
case "valid":
|
|
885
|
+
return { index, status: "valid", market_id: null, reason: null, market };
|
|
886
|
+
default:
|
|
887
|
+
return rejected(m, index, _nullishCoalesce(raw.reason, () => ( "not_created")));
|
|
888
|
+
}
|
|
648
889
|
}
|
|
649
|
-
function rejected(index, reason) {
|
|
650
|
-
return { index, status: "rejected", market_id: null, reason };
|
|
890
|
+
function rejected(m, index, reason) {
|
|
891
|
+
return { index, status: "rejected", market_id: null, reason, market: marketEntry(m) };
|
|
651
892
|
}
|
|
652
893
|
function checkMarket(m, players) {
|
|
653
|
-
if (m.rule !== "player_stat_line") return { market: m };
|
|
654
894
|
if (!isValidLine(m.line)) return { reason: "invalid_line" };
|
|
655
895
|
const stat = players.stats.find((s) => String(s.stat).toUpperCase() === String(m.stat).toUpperCase());
|
|
656
896
|
if (!stat) return { reason: "unsupported_stat" };
|
|
@@ -775,7 +1015,7 @@ function parseIni(text) {
|
|
|
775
1015
|
function readProfile(profileName, path) {
|
|
776
1016
|
try {
|
|
777
1017
|
if (!_fs.statSync.call(void 0, path).isFile()) return [{}, false];
|
|
778
|
-
} catch (
|
|
1018
|
+
} catch (e5) {
|
|
779
1019
|
return [{}, false];
|
|
780
1020
|
}
|
|
781
1021
|
let sections;
|
|
@@ -795,7 +1035,7 @@ function readProfile(profileName, path) {
|
|
|
795
1035
|
}
|
|
796
1036
|
function processEnv() {
|
|
797
1037
|
const p = globalThis.process;
|
|
798
|
-
return _nullishCoalesce(_optionalChain([p, 'optionalAccess',
|
|
1038
|
+
return _nullishCoalesce(_optionalChain([p, 'optionalAccess', _7 => _7.env]), () => ( {}));
|
|
799
1039
|
}
|
|
800
1040
|
function resolveSettings(input = {}) {
|
|
801
1041
|
const environ = _nullishCoalesce(input.environ, () => ( processEnv()));
|
|
@@ -869,7 +1109,7 @@ function loadPrivateKey(value) {
|
|
|
869
1109
|
let isFile = false;
|
|
870
1110
|
try {
|
|
871
1111
|
isFile = _fs.statSync.call(void 0, path).isFile();
|
|
872
|
-
} catch (
|
|
1112
|
+
} catch (e6) {
|
|
873
1113
|
isFile = false;
|
|
874
1114
|
}
|
|
875
1115
|
if (!isFile) {
|
|
@@ -887,7 +1127,7 @@ function loadPrivateKey(value) {
|
|
|
887
1127
|
let key;
|
|
888
1128
|
try {
|
|
889
1129
|
key = _crypto.createPrivateKey.call(void 0, { key: Buffer.from(pem), format: "pem" });
|
|
890
|
-
} catch (
|
|
1130
|
+
} catch (e7) {
|
|
891
1131
|
throw new STXConfigException(
|
|
892
1132
|
"Private key is not valid PEM. Expected a PKCS#8 block beginning '-----BEGIN PRIVATE KEY-----'."
|
|
893
1133
|
);
|
|
@@ -904,11 +1144,11 @@ function signerFromPrivateKey(value) {
|
|
|
904
1144
|
const key = loadPrivateKey(value);
|
|
905
1145
|
return (message) => new Uint8Array(_crypto.sign.call(void 0, null, message, key));
|
|
906
1146
|
}
|
|
907
|
-
var ApiKeyCredentials = (
|
|
908
|
-
|
|
1147
|
+
var ApiKeyCredentials = (_class2 = class {
|
|
1148
|
+
__init2() {this.kind = "api_key"}
|
|
909
1149
|
|
|
910
1150
|
#sign;
|
|
911
|
-
constructor(keyId, privateKey, opts = {}) {;
|
|
1151
|
+
constructor(keyId, privateKey, opts = {}) {;_class2.prototype.__init2.call(this);
|
|
912
1152
|
if (!keyId || !String(keyId).trim()) throw new STXConfigException("API key id is required.");
|
|
913
1153
|
const signer = opts.signer;
|
|
914
1154
|
if (!signer && (privateKey === void 0 || privateKey === null)) {
|
|
@@ -951,7 +1191,7 @@ var ApiKeyCredentials = (_class = class {
|
|
|
951
1191
|
[/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")]() {
|
|
952
1192
|
return this.toString();
|
|
953
1193
|
}
|
|
954
|
-
},
|
|
1194
|
+
}, _class2);
|
|
955
1195
|
function credentialsFromSettings(keyId, privateKey, signer) {
|
|
956
1196
|
const hasMaterial = privateKey !== void 0 && privateKey !== null || signer !== void 0;
|
|
957
1197
|
if (!keyId && !hasMaterial) return void 0;
|
|
@@ -969,7 +1209,7 @@ function credentialsFromSettings(keyId, privateKey, signer) {
|
|
|
969
1209
|
}
|
|
970
1210
|
|
|
971
1211
|
// src/version.ts
|
|
972
|
-
var VERSION = "0.9.0
|
|
1212
|
+
var VERSION = "0.9.0";
|
|
973
1213
|
var USER_AGENT = `stx-typescript/${VERSION}`;
|
|
974
1214
|
var ASYNC_DISPOSE = _nullishCoalesce(Symbol.asyncDispose, () => ( /* @__PURE__ */ Symbol.for("Symbol.asyncDispose")));
|
|
975
1215
|
|
|
@@ -988,13 +1228,13 @@ function stamp(item) {
|
|
|
988
1228
|
const t = Date.parse(String(_nullishCoalesce(_nullishCoalesce(item.time, () => ( item.inserted_at)), () => ( ""))));
|
|
989
1229
|
return Number.isNaN(t) ? 0 : t * 1e3;
|
|
990
1230
|
}
|
|
991
|
-
var AccountView = (
|
|
1231
|
+
var AccountView = (_class3 = class {
|
|
992
1232
|
|
|
993
1233
|
|
|
994
1234
|
/** The joined channels, by name. */
|
|
995
|
-
|
|
1235
|
+
__init3() {this.channels = {}}
|
|
996
1236
|
/** Join snapshots applied so far, per channel: 1 after the first seed, more after reconnects. */
|
|
997
|
-
|
|
1237
|
+
__init4() {this.seeds = { balances: 0, orders: 0, fills: 0, positions: 0 }}
|
|
998
1238
|
#balance = null;
|
|
999
1239
|
#orders = /* @__PURE__ */ new Map();
|
|
1000
1240
|
#fills = /* @__PURE__ */ new Map();
|
|
@@ -1003,7 +1243,7 @@ var AccountView = (_class2 = class {
|
|
|
1003
1243
|
#maxFills;
|
|
1004
1244
|
#closed = false;
|
|
1005
1245
|
/** @internal Use `ws.accountView()`. */
|
|
1006
|
-
constructor(ws, opts = {}) {;
|
|
1246
|
+
constructor(ws, opts = {}) {;_class3.prototype.__init3.call(this);_class3.prototype.__init4.call(this);
|
|
1007
1247
|
this.ws = ws;
|
|
1008
1248
|
this.onChange = opts.onChange;
|
|
1009
1249
|
this.#keepFlat = _nullishCoalesce(opts.keepFlatPositions, () => ( false));
|
|
@@ -1101,7 +1341,7 @@ var AccountView = (_class2 = class {
|
|
|
1101
1341
|
case "all_orders":
|
|
1102
1342
|
this.seeds.orders = (_nullishCoalesce(this.seeds.orders, () => ( 0))) + 1;
|
|
1103
1343
|
this.#orders.clear();
|
|
1104
|
-
for (const o of _nullishCoalesce(_optionalChain([payload, 'optionalAccess',
|
|
1344
|
+
for (const o of _nullishCoalesce(_optionalChain([payload, 'optionalAccess', _8 => _8.orders]), () => ( []))) this.#upsertOrder(o);
|
|
1105
1345
|
return change("orders", true);
|
|
1106
1346
|
case "new_open_order":
|
|
1107
1347
|
this.#upsertOrder(payload);
|
|
@@ -1109,7 +1349,7 @@ var AccountView = (_class2 = class {
|
|
|
1109
1349
|
case "all_trades":
|
|
1110
1350
|
this.seeds.fills = (_nullishCoalesce(this.seeds.fills, () => ( 0))) + 1;
|
|
1111
1351
|
this.#fills.clear();
|
|
1112
|
-
for (const t of _nullishCoalesce(_optionalChain([payload, 'optionalAccess',
|
|
1352
|
+
for (const t of _nullishCoalesce(_optionalChain([payload, 'optionalAccess', _9 => _9.trades]), () => ( []))) this.#upsertFill(t);
|
|
1113
1353
|
return change("fills", true);
|
|
1114
1354
|
case "trade":
|
|
1115
1355
|
this.#upsertFill(payload);
|
|
@@ -1117,22 +1357,22 @@ var AccountView = (_class2 = class {
|
|
|
1117
1357
|
case "all_positions":
|
|
1118
1358
|
this.seeds.positions = (_nullishCoalesce(this.seeds.positions, () => ( 0))) + 1;
|
|
1119
1359
|
this.#positions.clear();
|
|
1120
|
-
for (const p of _nullishCoalesce(_optionalChain([payload, 'optionalAccess',
|
|
1360
|
+
for (const p of _nullishCoalesce(_optionalChain([payload, 'optionalAccess', _10 => _10.positions]), () => ( []))) this.#upsertPosition(p);
|
|
1121
1361
|
return change("positions", true);
|
|
1122
1362
|
case "updated_positions":
|
|
1123
|
-
for (const p of _nullishCoalesce(_optionalChain([payload, 'optionalAccess',
|
|
1363
|
+
for (const p of _nullishCoalesce(_optionalChain([payload, 'optionalAccess', _11 => _11.positions]), () => ( []))) this.#upsertPosition(p);
|
|
1124
1364
|
return change("positions", false);
|
|
1125
1365
|
default:
|
|
1126
1366
|
return void 0;
|
|
1127
1367
|
}
|
|
1128
1368
|
}
|
|
1129
1369
|
#upsertOrder(order) {
|
|
1130
|
-
if (!_optionalChain([order, 'optionalAccess',
|
|
1370
|
+
if (!_optionalChain([order, 'optionalAccess', _12 => _12.id])) return;
|
|
1131
1371
|
if (TERMINAL_ORDER_STATUSES.has(String(order.status))) this.#orders.delete(order.id);
|
|
1132
1372
|
else this.#orders.set(order.id, order);
|
|
1133
1373
|
}
|
|
1134
1374
|
#upsertFill(fill) {
|
|
1135
|
-
if (!_optionalChain([fill, 'optionalAccess',
|
|
1375
|
+
if (!_optionalChain([fill, 'optionalAccess', _13 => _13.id])) return;
|
|
1136
1376
|
this.#fills.delete(fill.id);
|
|
1137
1377
|
this.#fills.set(fill.id, fill);
|
|
1138
1378
|
if (this.#fills.size > this.#maxFills) {
|
|
@@ -1141,7 +1381,7 @@ var AccountView = (_class2 = class {
|
|
|
1141
1381
|
}
|
|
1142
1382
|
}
|
|
1143
1383
|
#upsertPosition(position) {
|
|
1144
|
-
const key = _nullishCoalesce(_optionalChain([position, 'optionalAccess',
|
|
1384
|
+
const key = _nullishCoalesce(_optionalChain([position, 'optionalAccess', _14 => _14.market_id]), () => ( _optionalChain([position, 'optionalAccess', _15 => _15.id])));
|
|
1145
1385
|
if (!key) return;
|
|
1146
1386
|
if (!this.#keepFlat && isZero(position.position)) this.#positions.delete(key);
|
|
1147
1387
|
else this.#positions.set(key, position);
|
|
@@ -1154,7 +1394,304 @@ var AccountView = (_class2 = class {
|
|
|
1154
1394
|
CHANNELS.map((name) => this.channels[name]).filter((c) => c !== void 0 && !c.closed).map((c) => c.leave())
|
|
1155
1395
|
);
|
|
1156
1396
|
}
|
|
1157
|
-
},
|
|
1397
|
+
}, _class3);
|
|
1398
|
+
|
|
1399
|
+
// src/combos.ts
|
|
1400
|
+
var COMBO_PLAYER_CHANNEL = "rfq";
|
|
1401
|
+
var COMBO_MAKER_CHANNEL = "combo_quote";
|
|
1402
|
+
var UNAVAILABLE_REASON = "unmatched topic";
|
|
1403
|
+
var ACCEPT_TIMEOUT_MS = 35e3;
|
|
1404
|
+
var HISTORY_SIZE = 1e3;
|
|
1405
|
+
var PLAYER_EVENTS = /* @__PURE__ */ new Set(["best_quote", "placed", "negotiation_closed"]);
|
|
1406
|
+
var MAKER_EVENTS = /* @__PURE__ */ new Set([
|
|
1407
|
+
"rfq_opened",
|
|
1408
|
+
"rfq_closed",
|
|
1409
|
+
"quote_accepted",
|
|
1410
|
+
"placed",
|
|
1411
|
+
"negotiation_closed"
|
|
1412
|
+
]);
|
|
1413
|
+
function comboRefusal(command, topic, response, host = "") {
|
|
1414
|
+
const reply = response && typeof response === "object" ? response : {};
|
|
1415
|
+
const reason = typeof reply.reason === "string" ? reply.reason : void 0;
|
|
1416
|
+
if (reason === UNAVAILABLE_REASON) {
|
|
1417
|
+
return new STXCombosUnavailableException(notAvailableMessage("combos", host || "this exchange"), {
|
|
1418
|
+
topic,
|
|
1419
|
+
reply: response,
|
|
1420
|
+
host
|
|
1421
|
+
});
|
|
1422
|
+
}
|
|
1423
|
+
if (reason === void 0) {
|
|
1424
|
+
return new STXComboRefusedException(`${command} on ${topic} failed: ${JSON.stringify(response)}`, {
|
|
1425
|
+
topic,
|
|
1426
|
+
reply: response,
|
|
1427
|
+
command,
|
|
1428
|
+
code: ""
|
|
1429
|
+
});
|
|
1430
|
+
}
|
|
1431
|
+
let code = reason;
|
|
1432
|
+
let detail;
|
|
1433
|
+
if (reason.startsWith("player_refused:")) {
|
|
1434
|
+
code = "player_refused";
|
|
1435
|
+
detail = reason.slice("player_refused:".length);
|
|
1436
|
+
}
|
|
1437
|
+
const message = `${command} on ${topic} refused: ${reason}`;
|
|
1438
|
+
if (code === "price_moved") {
|
|
1439
|
+
return new STXComboPriceMovedException(message, {
|
|
1440
|
+
topic,
|
|
1441
|
+
reply: response,
|
|
1442
|
+
command,
|
|
1443
|
+
code,
|
|
1444
|
+
best: {
|
|
1445
|
+
quote_id: _nullishCoalesce(reply.quote_id, () => ( null)),
|
|
1446
|
+
amount: _nullishCoalesce(reply.amount, () => ( null)),
|
|
1447
|
+
expires_at: _nullishCoalesce(reply.expires_at, () => ( null))
|
|
1448
|
+
}
|
|
1449
|
+
});
|
|
1450
|
+
}
|
|
1451
|
+
return new STXComboRefusedException(message, { topic, reply: response, command, code, detail });
|
|
1452
|
+
}
|
|
1453
|
+
function comboJoinError(err, host = "") {
|
|
1454
|
+
if (err instanceof STXChannelException && !(err instanceof STXCombosUnavailableException) && err.reply !== void 0) {
|
|
1455
|
+
if (err.constructor !== STXChannelException) return err;
|
|
1456
|
+
return comboRefusal("phx_join", err.topic, err.reply, host);
|
|
1457
|
+
}
|
|
1458
|
+
return err;
|
|
1459
|
+
}
|
|
1460
|
+
async function comboJoinPayload(geo) {
|
|
1461
|
+
const packet = await resolveGeoLocation(geo);
|
|
1462
|
+
return packet === void 0 ? {} : { geo_location: packet };
|
|
1463
|
+
}
|
|
1464
|
+
function money(name, value) {
|
|
1465
|
+
if (typeof value !== "string") {
|
|
1466
|
+
throw new TypeError(`${name} must be a decimal string such as "250.00", got ${typeof value}`);
|
|
1467
|
+
}
|
|
1468
|
+
return value;
|
|
1469
|
+
}
|
|
1470
|
+
var ComboSession = class {
|
|
1471
|
+
/** The underlying channel. Its `reply` is the latest join reply. */
|
|
1472
|
+
|
|
1473
|
+
#onEvent;
|
|
1474
|
+
#history = [];
|
|
1475
|
+
#waiters = [];
|
|
1476
|
+
#events;
|
|
1477
|
+
/** @internal */
|
|
1478
|
+
constructor(channel, events, onEvent) {
|
|
1479
|
+
this.channel = channel;
|
|
1480
|
+
this.#events = events;
|
|
1481
|
+
this.#onEvent = onEvent;
|
|
1482
|
+
}
|
|
1483
|
+
/** Your account's pseudonym for counterparties, from the join reply. */
|
|
1484
|
+
get externalId() {
|
|
1485
|
+
return _nullishCoalesce(this.channel.reply.external_id, () => ( ""));
|
|
1486
|
+
}
|
|
1487
|
+
/** When the geolocation packet this join used expires (ISO 8601), or null. Rejoin before it. */
|
|
1488
|
+
get nextGeolocationAt() {
|
|
1489
|
+
return _nullishCoalesce(this.channel.reply.next_geolocation_at, () => ( null));
|
|
1490
|
+
}
|
|
1491
|
+
/** @internal */
|
|
1492
|
+
_typed(msg) {
|
|
1493
|
+
if (!this.#events.has(msg.event) || !msg.payload || typeof msg.payload !== "object") return void 0;
|
|
1494
|
+
return { event: msg.event, payload: msg.payload };
|
|
1495
|
+
}
|
|
1496
|
+
/** @internal Called for every message on the channel, before it is queued. */
|
|
1497
|
+
async _receive(msg) {
|
|
1498
|
+
const event = this._typed(msg);
|
|
1499
|
+
if (!event) return;
|
|
1500
|
+
this.#history.push(event);
|
|
1501
|
+
if (this.#history.length > HISTORY_SIZE) this.#history.shift();
|
|
1502
|
+
for (const w of [...this.#waiters]) {
|
|
1503
|
+
if (w.match(event)) {
|
|
1504
|
+
this.#waiters = this.#waiters.filter((x) => x !== w);
|
|
1505
|
+
w.resolve(event);
|
|
1506
|
+
}
|
|
1507
|
+
}
|
|
1508
|
+
if (this.#onEvent) await this.#onEvent(event);
|
|
1509
|
+
}
|
|
1510
|
+
/** The events received so far (the latest 1000), oldest first. */
|
|
1511
|
+
get events() {
|
|
1512
|
+
return [...this.#history];
|
|
1513
|
+
}
|
|
1514
|
+
/**
|
|
1515
|
+
* The next event, in arrival order. Rejects with `STXTimeoutException` when
|
|
1516
|
+
* none arrives within `timeoutMs`, and with `STXChannelException` once the
|
|
1517
|
+
* channel is closed. Use either this or `for await`, not both.
|
|
1518
|
+
*/
|
|
1519
|
+
async next(timeoutMs) {
|
|
1520
|
+
for (; ; ) {
|
|
1521
|
+
const event = this._typed(await this.channel.next(timeoutMs));
|
|
1522
|
+
if (event) return event;
|
|
1523
|
+
}
|
|
1524
|
+
}
|
|
1525
|
+
async *[Symbol.asyncIterator]() {
|
|
1526
|
+
for await (const msg of this.channel) {
|
|
1527
|
+
const event = this._typed(msg);
|
|
1528
|
+
if (event) yield event;
|
|
1529
|
+
}
|
|
1530
|
+
}
|
|
1531
|
+
/**
|
|
1532
|
+
* Resolve with the first event named `event` (or one of several) for
|
|
1533
|
+
* `rfqId`, looking first at events already received. Unlike `next()`, it
|
|
1534
|
+
* takes nothing from the queue. Rejects with `STXTimeoutException` after
|
|
1535
|
+
* `timeoutMs` (default 10000).
|
|
1536
|
+
*
|
|
1537
|
+
* @param event An event name, or several.
|
|
1538
|
+
* @param opts.rfqId Only events for this request.
|
|
1539
|
+
* @param opts.quoteId Only events for this quote (maker events).
|
|
1540
|
+
* @param opts.timeoutMs Milliseconds to wait. Default 10000.
|
|
1541
|
+
*/
|
|
1542
|
+
waitFor(event, opts = {}) {
|
|
1543
|
+
const names = typeof event === "string" ? [event] : event;
|
|
1544
|
+
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);
|
|
1545
|
+
const seen = this.#history.find(match);
|
|
1546
|
+
if (seen) return Promise.resolve(seen);
|
|
1547
|
+
const timeoutMs = _nullishCoalesce(opts.timeoutMs, () => ( 1e4));
|
|
1548
|
+
return new Promise((resolve, reject) => {
|
|
1549
|
+
const waiter = {
|
|
1550
|
+
match,
|
|
1551
|
+
resolve: (e) => {
|
|
1552
|
+
clearTimeout(timer);
|
|
1553
|
+
resolve(e);
|
|
1554
|
+
}
|
|
1555
|
+
};
|
|
1556
|
+
const timer = setTimeout(() => {
|
|
1557
|
+
this.#waiters = this.#waiters.filter((w) => w !== waiter);
|
|
1558
|
+
reject(
|
|
1559
|
+
new STXTimeoutException(`No ${names.join(" or ")} on ${this.channel.topic} within ${timeoutMs} ms`, {
|
|
1560
|
+
topic: this.channel.topic
|
|
1561
|
+
})
|
|
1562
|
+
);
|
|
1563
|
+
}, timeoutMs);
|
|
1564
|
+
this.#waiters.push(waiter);
|
|
1565
|
+
});
|
|
1566
|
+
}
|
|
1567
|
+
/**
|
|
1568
|
+
* Leave the topic. Requests opened and quotes placed on this channel end
|
|
1569
|
+
* (`cancelled`), as on any close, and delivery on this channel stops when
|
|
1570
|
+
* `leave()` resolves: the exchange's `negotiation_closed` for those requests
|
|
1571
|
+
* arrives after the channel has closed and is not passed to `onEvent` or to
|
|
1572
|
+
* an iterator. Treat every request still open here as cancelled once
|
|
1573
|
+
* `leave()` resolves. To see each request's own close first, `cancel()` it
|
|
1574
|
+
* and wait for its `negotiation_closed` before leaving. Other connections of
|
|
1575
|
+
* the same member still receive the close.
|
|
1576
|
+
*/
|
|
1577
|
+
leave() {
|
|
1578
|
+
return this.channel.leave();
|
|
1579
|
+
}
|
|
1580
|
+
/** @internal Send a command and map a refusal to the combo exceptions. */
|
|
1581
|
+
async _command(command, payload, timeoutMs) {
|
|
1582
|
+
try {
|
|
1583
|
+
return await this.channel.push(command, payload, timeoutMs);
|
|
1584
|
+
} catch (err) {
|
|
1585
|
+
if (err instanceof STXChannelException && err.constructor === STXChannelException && err.reply !== void 0) {
|
|
1586
|
+
throw comboRefusal(command, this.channel.topic, err.reply);
|
|
1587
|
+
}
|
|
1588
|
+
throw err;
|
|
1589
|
+
}
|
|
1590
|
+
}
|
|
1591
|
+
};
|
|
1592
|
+
var ComboPlayer = class extends ComboSession {
|
|
1593
|
+
/** @internal */
|
|
1594
|
+
constructor(channel, onEvent) {
|
|
1595
|
+
super(channel, PLAYER_EVENTS, onEvent);
|
|
1596
|
+
}
|
|
1597
|
+
/**
|
|
1598
|
+
* `request_quote`: ask makers to quote on these legs for a stake. `amount`
|
|
1599
|
+
* is the stake as a decimal string in whole cents, e.g. `"250.00"`. Makers
|
|
1600
|
+
* quote what you win; quotes arrive as `best_quote` events.
|
|
1601
|
+
*
|
|
1602
|
+
* @param legs Two or more `open` markets and the outcome the combination needs of each.
|
|
1603
|
+
* @param amount The stake in dollars, e.g. `"250.00"`.
|
|
1604
|
+
*/
|
|
1605
|
+
requestQuote(legs, amount2) {
|
|
1606
|
+
return this._command("request_quote", {
|
|
1607
|
+
legs: legs.map((leg) => ({ market_id: leg.marketId, outcome: leg.outcome })),
|
|
1608
|
+
amount: money("amount", amount2)
|
|
1609
|
+
});
|
|
1610
|
+
}
|
|
1611
|
+
/**
|
|
1612
|
+
* `cash_out`: ask makers to quote for what you hold of a combination, by the
|
|
1613
|
+
* `market_id` from `placed`. The exchange sets the size.
|
|
1614
|
+
*
|
|
1615
|
+
* @param marketId The combination's market id.
|
|
1616
|
+
*/
|
|
1617
|
+
cashOut(marketId) {
|
|
1618
|
+
return this._command("cash_out", { market_id: marketId });
|
|
1619
|
+
}
|
|
1620
|
+
/**
|
|
1621
|
+
* `accept`: bind the request at `amount` or more, normally the amount
|
|
1622
|
+
* `best_quote` showed. The best live quote binds whoever made it, so the
|
|
1623
|
+
* placement can be better than `amount`. Waits up to 35 s.
|
|
1624
|
+
*
|
|
1625
|
+
* Throws `STXComboPriceMovedException` (with the live `best`) when nothing
|
|
1626
|
+
* at least as good is live; the request stays open and you can accept again.
|
|
1627
|
+
* The reply says what was placed; fills arrive on `fills`.
|
|
1628
|
+
*
|
|
1629
|
+
* @param rfqId The request.
|
|
1630
|
+
* @param quoteId The quote you saw, normally from `best_quote`.
|
|
1631
|
+
* @param amount The least amount you take, e.g. `"1750.00"`.
|
|
1632
|
+
*/
|
|
1633
|
+
accept(rfqId, quoteId, amount2) {
|
|
1634
|
+
return this._command(
|
|
1635
|
+
"accept",
|
|
1636
|
+
{ rfq_id: rfqId, quote_id: quoteId, amount: money("amount", amount2) },
|
|
1637
|
+
ACCEPT_TIMEOUT_MS
|
|
1638
|
+
);
|
|
1639
|
+
}
|
|
1640
|
+
/**
|
|
1641
|
+
* `cancel`: end the request and drop every quote on it.
|
|
1642
|
+
*
|
|
1643
|
+
* @param rfqId The request.
|
|
1644
|
+
*/
|
|
1645
|
+
cancel(rfqId) {
|
|
1646
|
+
return this._command("cancel", { rfq_id: rfqId });
|
|
1647
|
+
}
|
|
1648
|
+
/**
|
|
1649
|
+
* `snapshot`: the request now, with the live best quote. Not delayed like `best_quote` events.
|
|
1650
|
+
*
|
|
1651
|
+
* @param rfqId The request.
|
|
1652
|
+
*/
|
|
1653
|
+
snapshot(rfqId) {
|
|
1654
|
+
return this._command("snapshot", { rfq_id: rfqId });
|
|
1655
|
+
}
|
|
1656
|
+
};
|
|
1657
|
+
var ComboMaker = class extends ComboSession {
|
|
1658
|
+
/** @internal */
|
|
1659
|
+
constructor(channel, onEvent) {
|
|
1660
|
+
super(channel, MAKER_EVENTS, onEvent);
|
|
1661
|
+
}
|
|
1662
|
+
/**
|
|
1663
|
+
* `quote`: offer `amount` on a request. On a buy it is what the player wins;
|
|
1664
|
+
* on a cash out, what you pay for the whole size. Price it against the
|
|
1665
|
+
* request's `max_price` and `tick_size`. `expiresInMs` (a positive integer)
|
|
1666
|
+
* counts from receipt; the quote ends no later than its request.
|
|
1667
|
+
* `clientOrderId` (at most 255 bytes) is copied onto your order if it binds.
|
|
1668
|
+
*
|
|
1669
|
+
* @param rfqId The request, from `rfq_opened`.
|
|
1670
|
+
* @param amount In dollars, e.g. `"1750.00"`.
|
|
1671
|
+
* @param expiresInMs How long the quote stands, in milliseconds.
|
|
1672
|
+
* @param opts.clientOrderId Copied onto your order if the quote binds.
|
|
1673
|
+
*/
|
|
1674
|
+
quote(rfqId, amount2, expiresInMs, opts = {}) {
|
|
1675
|
+
const payload = {
|
|
1676
|
+
rfq_id: rfqId,
|
|
1677
|
+
amount: money("amount", amount2),
|
|
1678
|
+
expires_in_ms: expiresInMs
|
|
1679
|
+
};
|
|
1680
|
+
if (opts.clientOrderId !== void 0) payload.client_order_id = opts.clientOrderId;
|
|
1681
|
+
return this._command("quote", payload);
|
|
1682
|
+
}
|
|
1683
|
+
/**
|
|
1684
|
+
* `withdraw_quote`: remove one of your quotes.
|
|
1685
|
+
*
|
|
1686
|
+
* @param rfqId The request.
|
|
1687
|
+
* @param quoteId Your quote, from the `quote()` reply.
|
|
1688
|
+
*/
|
|
1689
|
+
withdrawQuote(rfqId, quoteId) {
|
|
1690
|
+
return this._command("withdraw_quote", { rfq_id: rfqId, quote_id: quoteId });
|
|
1691
|
+
}
|
|
1692
|
+
};
|
|
1693
|
+
var COMBO_CHANNELS = /* @__PURE__ */ new Set([COMBO_PLAYER_CHANNEL, COMBO_MAKER_CHANNEL]);
|
|
1694
|
+
var COMBOS_UNAVAILABLE_REASON = UNAVAILABLE_REASON;
|
|
1158
1695
|
|
|
1159
1696
|
// src/money.ts
|
|
1160
1697
|
var PRICE_FIELDS = ["price", "last_traded_price", "max_price"];
|
|
@@ -1291,7 +1828,7 @@ function buildRequest(operationId, args = {}) {
|
|
|
1291
1828
|
const op = OPERATIONS[operationId];
|
|
1292
1829
|
let path = op.path;
|
|
1293
1830
|
for (const name of op.pathParams) {
|
|
1294
|
-
const value = _optionalChain([args, 'access',
|
|
1831
|
+
const value = _optionalChain([args, 'access', _16 => _16.pathParams, 'optionalAccess', _17 => _17[name]]);
|
|
1295
1832
|
if (!value) throw new TypeError(`${name} is required`);
|
|
1296
1833
|
path = path.replace(`{${name}}`, quote(String(value)));
|
|
1297
1834
|
}
|
|
@@ -1314,7 +1851,7 @@ function decodeResponse(request, status, text, headers = {}) {
|
|
|
1314
1851
|
let body;
|
|
1315
1852
|
try {
|
|
1316
1853
|
body = text ? JSON.parse(text) : null;
|
|
1317
|
-
} catch (
|
|
1854
|
+
} catch (e8) {
|
|
1318
1855
|
body = text;
|
|
1319
1856
|
}
|
|
1320
1857
|
if (status >= 200 && status < 300) {
|
|
@@ -1345,7 +1882,7 @@ function toBatchOrderResult(raw) {
|
|
|
1345
1882
|
const obj = raw && typeof raw === "object" ? raw : {};
|
|
1346
1883
|
const order = _nullishCoalesce(obj.order, () => ( null));
|
|
1347
1884
|
const errors = Array.isArray(obj.errors) ? obj.errors : null;
|
|
1348
|
-
return { ...obj, order, errors, ok: order !== null && !_optionalChain([errors, 'optionalAccess',
|
|
1885
|
+
return { ...obj, order, errors, ok: order !== null && !_optionalChain([errors, 'optionalAccess', _18 => _18.length]) };
|
|
1349
1886
|
}
|
|
1350
1887
|
|
|
1351
1888
|
// src/client.ts
|
|
@@ -1409,7 +1946,16 @@ function ids(value) {
|
|
|
1409
1946
|
return typeof value === "string" ? [value] : [...value];
|
|
1410
1947
|
}
|
|
1411
1948
|
var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
1412
|
-
var
|
|
1949
|
+
var GATED_OPERATIONS = {
|
|
1950
|
+
types_get: "market_types",
|
|
1951
|
+
events__id_players_get: "event_players",
|
|
1952
|
+
markets_post: "markets.create",
|
|
1953
|
+
leaderboard_get: "leaderboard",
|
|
1954
|
+
leaderboard_me_get: "leaderboard",
|
|
1955
|
+
me_profile_patch: "leaderboard"
|
|
1956
|
+
};
|
|
1957
|
+
var LEADERBOARD_OFF = "Leaderboard is not enabled";
|
|
1958
|
+
var STX = (_class4 = class _STX {
|
|
1413
1959
|
|
|
1414
1960
|
|
|
1415
1961
|
|
|
@@ -1424,9 +1970,10 @@ var STX = (_class3 = class _STX {
|
|
|
1424
1970
|
|
|
1425
1971
|
#fetch;
|
|
1426
1972
|
#me;
|
|
1973
|
+
#capabilities;
|
|
1427
1974
|
/** Test hook: how retries wait. */
|
|
1428
|
-
|
|
1429
|
-
constructor(opts = {}) {;
|
|
1975
|
+
__init5() {this._sleep = sleep}
|
|
1976
|
+
constructor(opts = {}) {;_class4.prototype.__init5.call(this);
|
|
1430
1977
|
if (opts.auth && (opts.keyId || opts.privateKey || opts.signer)) {
|
|
1431
1978
|
throw new STXConfigException("Pass `auth` or an API key (keyId with privateKey or signer), not both.");
|
|
1432
1979
|
}
|
|
@@ -1475,7 +2022,75 @@ var STX = (_class3 = class _STX {
|
|
|
1475
2022
|
this.#fetch = fetchImpl;
|
|
1476
2023
|
}
|
|
1477
2024
|
toString() {
|
|
1478
|
-
return `STX(baseUrl=${JSON.stringify(this.baseUrl)}, keyId=${JSON.stringify(_nullishCoalesce(_optionalChain([this, 'access',
|
|
2025
|
+
return `STX(baseUrl=${JSON.stringify(this.baseUrl)}, keyId=${JSON.stringify(_nullishCoalesce(_optionalChain([this, 'access', _19 => _19.credentials, 'optionalAccess', _20 => _20.keyId]), () => ( null)))})`;
|
|
2026
|
+
}
|
|
2027
|
+
/** The exchange host, e.g. `"demo.stxapp.io"`: the name `STXNotAvailableException` and `capabilities()` report. */
|
|
2028
|
+
get host() {
|
|
2029
|
+
return new URL(this.baseUrl).host;
|
|
2030
|
+
}
|
|
2031
|
+
// ------------------------------------------------------------------
|
|
2032
|
+
// Capabilities
|
|
2033
|
+
// ------------------------------------------------------------------
|
|
2034
|
+
/**
|
|
2035
|
+
* Which features this exchange has, from what it publishes: its OAuth
|
|
2036
|
+
* discovery document, `/api_version`, a signed GET of the routes that not
|
|
2037
|
+
* every exchange has yet, and a join of a combos topic nobody owns. Nothing
|
|
2038
|
+
* is created or changed. Checked once per client and cached; pass
|
|
2039
|
+
* `{ refresh: true }` to check again.
|
|
2040
|
+
*
|
|
2041
|
+
* const caps = await stx.capabilities();
|
|
2042
|
+
* caps.features.combos; // false on demo.stxapp.ca
|
|
2043
|
+
* caps.require("combos"); // throws STXNotAvailableException there
|
|
2044
|
+
*
|
|
2045
|
+
* Each feature is `true`, `false`, or `null` when it could not be checked
|
|
2046
|
+
* (no credentials for a signed check, or no answer). A missing feature never
|
|
2047
|
+
* throws here; the call that needs it throws `STXNotAvailableException`.
|
|
2048
|
+
*/
|
|
2049
|
+
capabilities(opts = {}) {
|
|
2050
|
+
if (opts.refresh || !this.#capabilities) {
|
|
2051
|
+
const run = discoverCapabilities({
|
|
2052
|
+
host: this.host,
|
|
2053
|
+
get: (path) => this.#rawGet(path, false),
|
|
2054
|
+
signedGet: (path) => this.auth ? this.#rawGet(path, true) : null,
|
|
2055
|
+
joinReason: (topic) => this.#joinReason(topic)
|
|
2056
|
+
});
|
|
2057
|
+
this.#capabilities = run;
|
|
2058
|
+
run.catch(() => {
|
|
2059
|
+
if (this.#capabilities === run) this.#capabilities = void 0;
|
|
2060
|
+
});
|
|
2061
|
+
}
|
|
2062
|
+
return this.#capabilities;
|
|
2063
|
+
}
|
|
2064
|
+
async #rawGet(path, signed) {
|
|
2065
|
+
const headers = { "User-Agent": USER_AGENT, Accept: "application/json" };
|
|
2066
|
+
if (signed && this.auth) Object.assign(headers, await this.auth.authHeaders({ method: "GET", path }));
|
|
2067
|
+
const controller = new AbortController();
|
|
2068
|
+
const timer = setTimeout(() => controller.abort(), Math.min(this.timeoutMs, 15e3));
|
|
2069
|
+
try {
|
|
2070
|
+
const res = await this.#fetch(this.baseUrl + path, { method: "GET", headers, signal: controller.signal });
|
|
2071
|
+
return { status: res.status, text: await res.text() };
|
|
2072
|
+
} catch (e9) {
|
|
2073
|
+
return null;
|
|
2074
|
+
} finally {
|
|
2075
|
+
clearTimeout(timer);
|
|
2076
|
+
}
|
|
2077
|
+
}
|
|
2078
|
+
async #joinReason(topic) {
|
|
2079
|
+
if (!this.auth) return null;
|
|
2080
|
+
const ws = this.websocket({ reconnect: false, joinTimeoutMs: 8e3 });
|
|
2081
|
+
try {
|
|
2082
|
+
const channel = await ws.join(topic);
|
|
2083
|
+
await channel.leave().catch(() => {
|
|
2084
|
+
});
|
|
2085
|
+
return "ok";
|
|
2086
|
+
} catch (err) {
|
|
2087
|
+
if (err instanceof STXTimeoutException) return null;
|
|
2088
|
+
if (err instanceof STXChannelException) return _nullishCoalesce(err.reason, () => ( null));
|
|
2089
|
+
return null;
|
|
2090
|
+
} finally {
|
|
2091
|
+
await ws.close().catch(() => {
|
|
2092
|
+
});
|
|
2093
|
+
}
|
|
1479
2094
|
}
|
|
1480
2095
|
/** Nothing to release (fetch pools connections itself); present so `await using` and explicit cleanup work. */
|
|
1481
2096
|
async close() {
|
|
@@ -1510,11 +2125,11 @@ var STX = (_class3 = class _STX {
|
|
|
1510
2125
|
status,
|
|
1511
2126
|
attempt,
|
|
1512
2127
|
durationMs: Date.now() - started,
|
|
1513
|
-
authKind: _optionalChain([this, 'access',
|
|
2128
|
+
authKind: _optionalChain([this, 'access', _21 => _21.auth, 'optionalAccess', _22 => _22.kind]),
|
|
1514
2129
|
requestBody: request.body,
|
|
1515
2130
|
responseBody
|
|
1516
2131
|
});
|
|
1517
|
-
} catch (
|
|
2132
|
+
} catch (e10) {
|
|
1518
2133
|
}
|
|
1519
2134
|
}
|
|
1520
2135
|
async #sendOnce(request, attempt = 1) {
|
|
@@ -1542,7 +2157,7 @@ var STX = (_class3 = class _STX {
|
|
|
1542
2157
|
});
|
|
1543
2158
|
}
|
|
1544
2159
|
throw new STXTransportException(
|
|
1545
|
-
`${request.method} ${request.path} failed: ${_nullishCoalesce(_optionalChain([err, 'optionalAccess',
|
|
2160
|
+
`${request.method} ${request.path} failed: ${_nullishCoalesce(_optionalChain([err, 'optionalAccess', _23 => _23.message]), () => ( String(err)))}`,
|
|
1546
2161
|
{ method: request.method, path: request.path, cause: err }
|
|
1547
2162
|
);
|
|
1548
2163
|
} finally {
|
|
@@ -1564,7 +2179,7 @@ var STX = (_class3 = class _STX {
|
|
|
1564
2179
|
return await this.#sendOnce(request, sent);
|
|
1565
2180
|
} catch (err) {
|
|
1566
2181
|
if (!(err instanceof STXException)) throw err;
|
|
1567
|
-
if (err.statusCode === 401 && !reauthenticated && _optionalChain([this, 'access',
|
|
2182
|
+
if (err.statusCode === 401 && !reauthenticated && _optionalChain([this, 'access', _24 => _24.auth, 'optionalAccess', _25 => _25.onUnauthorized])) {
|
|
1568
2183
|
reauthenticated = true;
|
|
1569
2184
|
if (await this.auth.onUnauthorized()) continue;
|
|
1570
2185
|
}
|
|
@@ -1575,7 +2190,22 @@ var STX = (_class3 = class _STX {
|
|
|
1575
2190
|
}
|
|
1576
2191
|
}
|
|
1577
2192
|
async #call(operationId, args = {}) {
|
|
1578
|
-
|
|
2193
|
+
try {
|
|
2194
|
+
return await this.#send(buildRequest(operationId, args));
|
|
2195
|
+
} catch (err) {
|
|
2196
|
+
const feature = GATED_OPERATIONS[operationId];
|
|
2197
|
+
const off = feature === "leaderboard" && err instanceof STXNotFoundException && _optionalChain([err, 'access', _26 => _26.body, 'optionalAccess', _27 => _27.error]) === LEADERBOARD_OFF;
|
|
2198
|
+
if (feature && (isMissingRoute(err) || off)) {
|
|
2199
|
+
throw new STXNotAvailableException(feature, this.host, {
|
|
2200
|
+
statusCode: err.statusCode,
|
|
2201
|
+
body: err.body,
|
|
2202
|
+
method: err.method,
|
|
2203
|
+
path: err.path,
|
|
2204
|
+
cause: err
|
|
2205
|
+
});
|
|
2206
|
+
}
|
|
2207
|
+
throw err;
|
|
2208
|
+
}
|
|
1579
2209
|
}
|
|
1580
2210
|
async #one(operationId, args = {}) {
|
|
1581
2211
|
const body = await this.#call(operationId, args);
|
|
@@ -1600,7 +2230,7 @@ var STX = (_class3 = class _STX {
|
|
|
1600
2230
|
}
|
|
1601
2231
|
}
|
|
1602
2232
|
async #geoBody(body, opts) {
|
|
1603
|
-
const packet = _optionalChain([opts, 'optionalAccess',
|
|
2233
|
+
const packet = _optionalChain([opts, 'optionalAccess', _28 => _28.geoLocation]) !== void 0 ? _nullishCoalesce(opts.geoLocation, () => ( void 0)) : await resolveGeoLocation(this.geoLocation);
|
|
1604
2234
|
return packet === void 0 ? body : { ...body, geo_location: packet };
|
|
1605
2235
|
}
|
|
1606
2236
|
// ------------------------------------------------------------------
|
|
@@ -1621,7 +2251,7 @@ var STX = (_class3 = class _STX {
|
|
|
1621
2251
|
* `user_id`.
|
|
1622
2252
|
*/
|
|
1623
2253
|
async userId() {
|
|
1624
|
-
if (_optionalChain([this, 'access',
|
|
2254
|
+
if (_optionalChain([this, 'access', _29 => _29.#me, 'optionalAccess', _30 => _30.user_id])) return this.#me.user_id;
|
|
1625
2255
|
try {
|
|
1626
2256
|
await this.me();
|
|
1627
2257
|
} catch (err) {
|
|
@@ -1632,7 +2262,7 @@ var STX = (_class3 = class _STX {
|
|
|
1632
2262
|
if (!balance.user_id) throw err;
|
|
1633
2263
|
this.#me = { ..._nullishCoalesce(this.#me, () => ( {})), user_id: balance.user_id };
|
|
1634
2264
|
}
|
|
1635
|
-
if (!_optionalChain([this, 'access',
|
|
2265
|
+
if (!_optionalChain([this, 'access', _31 => _31.#me, 'optionalAccess', _32 => _32.user_id])) throw new STXException("GET /api/v1/me returned no user_id");
|
|
1636
2266
|
return this.#me.user_id;
|
|
1637
2267
|
}
|
|
1638
2268
|
// ------------------------------------------------------------------
|
|
@@ -1727,16 +2357,18 @@ var STX = (_class3 = class _STX {
|
|
|
1727
2357
|
* which STX grants, from an address on the client's IP allow-list (it
|
|
1728
2358
|
* applies to every call that client makes).
|
|
1729
2359
|
*
|
|
1730
|
-
* Returns one result per market, in
|
|
1731
|
-
* `
|
|
1732
|
-
*
|
|
1733
|
-
*
|
|
1734
|
-
*
|
|
1735
|
-
*
|
|
2360
|
+
* Returns one result per market, in order: `created` or `exists` (both with
|
|
2361
|
+
* `market_id`), `valid` with `dryRun`, or `rejected` with a `reason`. Each
|
|
2362
|
+
* result's `index` is its position in `markets`, and `market` is that market
|
|
2363
|
+
* as requested. A rejected market is a
|
|
2364
|
+
* result, not an error, and resending is safe: a market that is already
|
|
2365
|
+
* listed comes back `exists`. A refused request throws (`403` without
|
|
2366
|
+
* `markets.write`, `404` unknown event, `422` event not open).
|
|
1736
2367
|
*
|
|
1737
|
-
* `
|
|
1738
|
-
* `MAX_MARKETS_PER_REQUEST` markets throws `TypeError` before any
|
|
1739
|
-
* `
|
|
2368
|
+
* Each `line` must be a positive number ending in `.5`, e.g. `18.5`. More
|
|
2369
|
+
* than `MAX_MARKETS_PER_REQUEST` markets throws `TypeError` before any
|
|
2370
|
+
* request. `dryRun` runs every check and creates nothing. `validate` also
|
|
2371
|
+
* needs the `events` scope.
|
|
1740
2372
|
*/
|
|
1741
2373
|
async createMarkets(eventId, markets, opts = {}) {
|
|
1742
2374
|
if (markets.length < 1 || markets.length > MAX_MARKETS_PER_REQUEST) {
|
|
@@ -1749,24 +2381,20 @@ var STX = (_class3 = class _STX {
|
|
|
1749
2381
|
send = send.flatMap(({ m, i }) => {
|
|
1750
2382
|
const checked = checkMarket(m, players);
|
|
1751
2383
|
if ("market" in checked) return [{ m: checked.market, i }];
|
|
1752
|
-
results[i] = rejected(i, checked.reason);
|
|
2384
|
+
results[i] = rejected(m, i, checked.reason);
|
|
1753
2385
|
return [];
|
|
1754
2386
|
});
|
|
1755
2387
|
}
|
|
1756
2388
|
if (send.length) {
|
|
1757
|
-
const body = {
|
|
1758
|
-
|
|
1759
|
-
...opts.dryRun ? { dry_run: true } : {},
|
|
1760
|
-
markets: send.map(({ m }) => marketEntry(m))
|
|
1761
|
-
};
|
|
2389
|
+
const body = { event_id: eventId, markets: send.map(({ m }) => marketEntry(m)) };
|
|
2390
|
+
if (opts.dryRun) body.dry_run = true;
|
|
1762
2391
|
const raw = await this.#one("markets_post", { body });
|
|
1763
2392
|
(_nullishCoalesce(raw.markets, () => ( []))).forEach((r, k) => {
|
|
1764
|
-
const
|
|
1765
|
-
|
|
1766
|
-
if (slot) results[slot.i] = toCreateMarketResult(r, slot.i);
|
|
2393
|
+
const slot = send[typeof r.index === "number" ? r.index : k];
|
|
2394
|
+
if (slot) results[slot.i] = toCreateMarketResult(r, slot.m, slot.i);
|
|
1767
2395
|
});
|
|
1768
2396
|
}
|
|
1769
|
-
return
|
|
2397
|
+
return results.map((r, i) => _nullishCoalesce(r, () => ( rejected(markets[i], i, "not_created"))));
|
|
1770
2398
|
}
|
|
1771
2399
|
// ------------------------------------------------------------------
|
|
1772
2400
|
// Orders
|
|
@@ -1798,7 +2426,7 @@ var STX = (_class3 = class _STX {
|
|
|
1798
2426
|
*
|
|
1799
2427
|
* `action` is `"buy"` or `"sell"`; `orderType` is `"limit"` or `"market"`.
|
|
1800
2428
|
* `price` (dollars, required for a limit order) and `quantity` (contracts)
|
|
1801
|
-
* are decimal strings, e.g. `{ price: "0.
|
|
2429
|
+
* are decimal strings, e.g. `{ price: "0.58", quantity: "100" }`. Numbers are
|
|
1802
2430
|
* refused client-side.
|
|
1803
2431
|
*
|
|
1804
2432
|
* The exchange validates the order: a bad price step or a fractional
|
|
@@ -1994,9 +2622,41 @@ var STX = (_class3 = class _STX {
|
|
|
1994
2622
|
return this.#iterate("portfolio_loyalty_get", { limit: query.limit });
|
|
1995
2623
|
}
|
|
1996
2624
|
// ------------------------------------------------------------------
|
|
2625
|
+
// Leaderboard and public profile
|
|
2626
|
+
// ------------------------------------------------------------------
|
|
2627
|
+
/**
|
|
2628
|
+
* `GET /api/v1/leaderboard`: ranked members for a period, sport and metric.
|
|
2629
|
+
* Rows carry a public handle and avatar, never an account id. Throws
|
|
2630
|
+
* `STXNotAvailableException` (feature `leaderboard`) where the exchange does
|
|
2631
|
+
* not have the leaderboard.
|
|
2632
|
+
*/
|
|
2633
|
+
leaderboard(query = {}) {
|
|
2634
|
+
const { period, category, metric, limit } = query;
|
|
2635
|
+
return this.#one("leaderboard_get", { query: { period, category, metric, limit } });
|
|
2636
|
+
}
|
|
2637
|
+
/** `GET /api/v1/leaderboard/me`: your own standing, including your rank outside the list. */
|
|
2638
|
+
leaderboardMe(query = {}) {
|
|
2639
|
+
return this.#one("leaderboard_me_get", { query: { period: query.period, category: query.category } });
|
|
2640
|
+
}
|
|
2641
|
+
/**
|
|
2642
|
+
* `PATCH /api/v1/me/profile`: change your public handle, avatar or
|
|
2643
|
+
* leaderboard opt-in. Resolves to the updated `me`.
|
|
2644
|
+
*/
|
|
2645
|
+
async updateProfile(update) {
|
|
2646
|
+
this.#me = await this.#one("me_profile_patch", { body: update });
|
|
2647
|
+
return this.#me;
|
|
2648
|
+
}
|
|
2649
|
+
// ------------------------------------------------------------------
|
|
1997
2650
|
// Terms
|
|
1998
2651
|
// ------------------------------------------------------------------
|
|
1999
|
-
/**
|
|
2652
|
+
/**
|
|
2653
|
+
* `POST /api/v1/tnc/accept`: accept the current terms for your own account,
|
|
2654
|
+
* with your own API key. Resolves to the server's message.
|
|
2655
|
+
*
|
|
2656
|
+
* An app cannot accept the terms for a member: called with a member's OAuth
|
|
2657
|
+
* access token, the exchange answers 403 `terms_not_delegable`
|
|
2658
|
+
* (`STXForbiddenException`). The member accepts on an STX page instead.
|
|
2659
|
+
*/
|
|
2000
2660
|
async acceptTerms(deviceId, opts = {}) {
|
|
2001
2661
|
const body = {
|
|
2002
2662
|
device_id: deviceId,
|
|
@@ -2017,7 +2677,7 @@ var STX = (_class3 = class _STX {
|
|
|
2017
2677
|
websocket(opts = {}) {
|
|
2018
2678
|
return new STXWebSocket({ ...opts, rest: this });
|
|
2019
2679
|
}
|
|
2020
|
-
},
|
|
2680
|
+
}, _class4);
|
|
2021
2681
|
|
|
2022
2682
|
// src/ws.ts
|
|
2023
2683
|
var PHOENIX_TOPIC = "phoenix";
|
|
@@ -2110,7 +2770,8 @@ var MessageQueue = class {
|
|
|
2110
2770
|
});
|
|
2111
2771
|
}
|
|
2112
2772
|
};
|
|
2113
|
-
var
|
|
2773
|
+
var UNPINGED_CHANNELS = /* @__PURE__ */ new Set(["market", "rfq", "combo_quote"]);
|
|
2774
|
+
var Channel = (_class5 = class {
|
|
2114
2775
|
/** The wire topic, e.g. `orders:<user_id>`. */
|
|
2115
2776
|
|
|
2116
2777
|
/** The topic without the user id, e.g. `orders`. */
|
|
@@ -2120,19 +2781,21 @@ var Channel = (_class4 = class {
|
|
|
2120
2781
|
|
|
2121
2782
|
|
|
2122
2783
|
/** The `response` object from the latest join reply, e.g. `{selected_market_ids: null}`. */
|
|
2123
|
-
|
|
2784
|
+
__init6() {this.reply = {}}
|
|
2124
2785
|
/** The latest snapshot payload per snapshot event name. */
|
|
2125
|
-
|
|
2786
|
+
__init7() {this.snapshots = {}}
|
|
2126
2787
|
/** Market ids watched on `market_updates`; re-sent after a reconnect. */
|
|
2127
|
-
|
|
2128
|
-
|
|
2129
|
-
|
|
2130
|
-
|
|
2788
|
+
__init8() {this.watches = []}
|
|
2789
|
+
__init9() {this.joinRef = null}
|
|
2790
|
+
__init10() {this.joined = false}
|
|
2791
|
+
__init11() {this.closed = false}
|
|
2792
|
+
/** @internal Runs before every (re)join, e.g. to refresh a geolocation packet in `joinPayload`. */
|
|
2793
|
+
|
|
2131
2794
|
#ws;
|
|
2132
2795
|
#queue;
|
|
2133
2796
|
#snapshotWaiters = [];
|
|
2134
2797
|
#pingTimer;
|
|
2135
|
-
constructor(ws, topic, joinPayload, onMessage, opts) {;
|
|
2798
|
+
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);
|
|
2136
2799
|
this.#ws = ws;
|
|
2137
2800
|
this.topic = topic;
|
|
2138
2801
|
this.name = topic.split(":", 1)[0];
|
|
@@ -2297,7 +2960,7 @@ var Channel = (_class4 = class {
|
|
|
2297
2960
|
_startPinger() {
|
|
2298
2961
|
this._stopPinger();
|
|
2299
2962
|
let interval = this.pingIntervalMs;
|
|
2300
|
-
const granted = _optionalChain([this, 'access',
|
|
2963
|
+
const granted = _optionalChain([this, 'access', _33 => _33.reply, 'optionalAccess', _34 => _34.ping_timeout]);
|
|
2301
2964
|
if (typeof granted === "number" && this.joinPayload.cancel_on_disconnect) {
|
|
2302
2965
|
const cod = granted * 0.6;
|
|
2303
2966
|
interval = interval === null ? cod : Math.min(interval, cod);
|
|
@@ -2310,7 +2973,7 @@ var Channel = (_class4 = class {
|
|
|
2310
2973
|
(err) => this.#ws.logger.warn(`${this.topic} ping failed: ${err.message}`)
|
|
2311
2974
|
);
|
|
2312
2975
|
}, every);
|
|
2313
|
-
_optionalChain([this, 'access',
|
|
2976
|
+
_optionalChain([this, 'access', _35 => _35.#pingTimer, 'access', _36 => _36.unref, 'optionalCall', _37 => _37()]);
|
|
2314
2977
|
}
|
|
2315
2978
|
}
|
|
2316
2979
|
/** @internal */
|
|
@@ -2331,7 +2994,7 @@ var Channel = (_class4 = class {
|
|
|
2331
2994
|
this._stopPinger();
|
|
2332
2995
|
this.#queue.put(null);
|
|
2333
2996
|
}
|
|
2334
|
-
},
|
|
2997
|
+
}, _class5);
|
|
2335
2998
|
var DEFAULT_LOGGER = {
|
|
2336
2999
|
debug: () => {
|
|
2337
3000
|
},
|
|
@@ -2340,7 +3003,7 @@ var DEFAULT_LOGGER = {
|
|
|
2340
3003
|
warn: (...a) => console.warn("[stx.ws]", ...a),
|
|
2341
3004
|
error: (...a) => console.error("[stx.ws]", ...a)
|
|
2342
3005
|
};
|
|
2343
|
-
var STXWebSocket = (
|
|
3006
|
+
var STXWebSocket = (_class6 = class {
|
|
2344
3007
|
|
|
2345
3008
|
|
|
2346
3009
|
|
|
@@ -2354,9 +3017,9 @@ var STXWebSocket = (_class5 = class {
|
|
|
2354
3017
|
|
|
2355
3018
|
|
|
2356
3019
|
|
|
2357
|
-
|
|
3020
|
+
__init12() {this.channels = /* @__PURE__ */ new Map()}
|
|
2358
3021
|
/** Successful reconnects so far. */
|
|
2359
|
-
|
|
3022
|
+
__init13() {this.reconnects = 0}
|
|
2360
3023
|
#userId;
|
|
2361
3024
|
#conn;
|
|
2362
3025
|
#ref = 0;
|
|
@@ -2370,7 +3033,7 @@ var STXWebSocket = (_class5 = class {
|
|
|
2370
3033
|
// Frames are handled one at a time, in arrival order: each waits for the
|
|
2371
3034
|
// previous one's handler to finish.
|
|
2372
3035
|
#inbox = Promise.resolve();
|
|
2373
|
-
constructor(opts = {}) {;
|
|
3036
|
+
constructor(opts = {}) {;_class6.prototype.__init12.call(this);_class6.prototype.__init13.call(this);
|
|
2374
3037
|
if (opts.rest) {
|
|
2375
3038
|
this.rest = opts.rest;
|
|
2376
3039
|
} else {
|
|
@@ -2505,7 +3168,7 @@ var STXWebSocket = (_class5 = class {
|
|
|
2505
3168
|
*/
|
|
2506
3169
|
async marketUpdates(opts = {}) {
|
|
2507
3170
|
const channel = await this.join("market_updates", {}, opts.onMessage);
|
|
2508
|
-
if (_optionalChain([opts, 'access',
|
|
3171
|
+
if (_optionalChain([opts, 'access', _38 => _38.watch, 'optionalAccess', _39 => _39.length])) await channel.watch(opts.watch);
|
|
2509
3172
|
return channel;
|
|
2510
3173
|
}
|
|
2511
3174
|
/**
|
|
@@ -2583,6 +3246,63 @@ var STXWebSocket = (_class5 = class {
|
|
|
2583
3246
|
return this.#joinAccount("user_info", {}, opts.onMessage);
|
|
2584
3247
|
}
|
|
2585
3248
|
// ------------------------------------------------------------------
|
|
3249
|
+
// Combos
|
|
3250
|
+
// ------------------------------------------------------------------
|
|
3251
|
+
/**
|
|
3252
|
+
* Join `rfq:{user_id}` and return a `ComboPlayer`: request quotes on a
|
|
3253
|
+
* combination, cash one out, accept, cancel and read a request.
|
|
3254
|
+
*
|
|
3255
|
+
* Available on US demo.
|
|
3256
|
+
* Where combos are not available, rejects with
|
|
3257
|
+
* `STXCombosUnavailableException`. Other join refusals (a read-only key, an
|
|
3258
|
+
* account that may not trade) reject with `STXComboRefusedException`.
|
|
3259
|
+
*/
|
|
3260
|
+
async comboPlayer(opts = {}) {
|
|
3261
|
+
let player;
|
|
3262
|
+
const early = [];
|
|
3263
|
+
const channel = await this.#joinCombo(COMBO_PLAYER_CHANNEL, opts, async (msg) => {
|
|
3264
|
+
if (player) await player._receive(msg);
|
|
3265
|
+
else early.push(msg);
|
|
3266
|
+
});
|
|
3267
|
+
player = new ComboPlayer(channel, opts.onEvent);
|
|
3268
|
+
for (const msg of early) await player._receive(msg);
|
|
3269
|
+
return player;
|
|
3270
|
+
}
|
|
3271
|
+
/**
|
|
3272
|
+
* Join `combo_quote:{user_id}` and return a `ComboMaker`: receive every
|
|
3273
|
+
* request opened from now on (`rfq_opened`), quote and withdraw quotes.
|
|
3274
|
+
*
|
|
3275
|
+
* Available on US demo.
|
|
3276
|
+
* Where combos are not available, rejects with
|
|
3277
|
+
* `STXCombosUnavailableException`.
|
|
3278
|
+
*/
|
|
3279
|
+
async comboMaker(opts = {}) {
|
|
3280
|
+
let maker;
|
|
3281
|
+
const early = [];
|
|
3282
|
+
const channel = await this.#joinCombo(COMBO_MAKER_CHANNEL, opts, async (msg) => {
|
|
3283
|
+
if (maker) await maker._receive(msg);
|
|
3284
|
+
else early.push(msg);
|
|
3285
|
+
});
|
|
3286
|
+
maker = new ComboMaker(channel, opts.onEvent);
|
|
3287
|
+
for (const msg of early) await maker._receive(msg);
|
|
3288
|
+
return maker;
|
|
3289
|
+
}
|
|
3290
|
+
async #joinCombo(name, opts, onMessage) {
|
|
3291
|
+
let channel;
|
|
3292
|
+
try {
|
|
3293
|
+
channel = await this.#joinAccount(name, await comboJoinPayload(opts.geoLocation), onMessage);
|
|
3294
|
+
} catch (err) {
|
|
3295
|
+
throw comboJoinError(err, new URL(this.rest.baseUrl).host);
|
|
3296
|
+
}
|
|
3297
|
+
if (typeof opts.geoLocation === "function") {
|
|
3298
|
+
const geo = opts.geoLocation;
|
|
3299
|
+
channel._beforeJoin = async () => {
|
|
3300
|
+
channel.joinPayload = await comboJoinPayload(geo);
|
|
3301
|
+
};
|
|
3302
|
+
}
|
|
3303
|
+
return channel;
|
|
3304
|
+
}
|
|
3305
|
+
// ------------------------------------------------------------------
|
|
2586
3306
|
// Generic join
|
|
2587
3307
|
// ------------------------------------------------------------------
|
|
2588
3308
|
/**
|
|
@@ -2594,8 +3314,9 @@ var STXWebSocket = (_class5 = class {
|
|
|
2594
3314
|
const existing = this.channels.get(topic);
|
|
2595
3315
|
if (existing && !existing.closed) throw new STXChannelException(`Already joined ${topic}`, { topic });
|
|
2596
3316
|
await this.connect();
|
|
3317
|
+
const name = topic.split(":", 1)[0];
|
|
2597
3318
|
const channel = new Channel(this, topic, payload, onMessage, {
|
|
2598
|
-
pingIntervalMs: opts.pingIntervalMs
|
|
3319
|
+
pingIntervalMs: opts.pingIntervalMs !== void 0 ? opts.pingIntervalMs : UNPINGED_CHANNELS.has(name) ? null : this.channelPingIntervalMs,
|
|
2599
3320
|
queueSize: this.queueSize
|
|
2600
3321
|
});
|
|
2601
3322
|
this.channels.set(topic, channel);
|
|
@@ -2620,6 +3341,7 @@ var STXWebSocket = (_class5 = class {
|
|
|
2620
3341
|
const ref = this.#nextRef();
|
|
2621
3342
|
channel.joinRef = ref;
|
|
2622
3343
|
channel._resetForRejoin();
|
|
3344
|
+
if (channel._beforeJoin) await channel._beforeJoin();
|
|
2623
3345
|
const reply = await this._request(channel.topic, "phx_join", channel.joinPayload, ref, void 0, ref);
|
|
2624
3346
|
channel.reply = reply && typeof reply === "object" && !Array.isArray(reply) ? reply : { response: reply };
|
|
2625
3347
|
if (channel.name === "market") channel.reply = convertMarketChannelPayload(channel.reply);
|
|
@@ -2662,12 +3384,12 @@ var STXWebSocket = (_class5 = class {
|
|
|
2662
3384
|
if (!(err instanceof STXTransportException)) return false;
|
|
2663
3385
|
if (err.statusCode !== 401 && err.statusCode !== 403) return false;
|
|
2664
3386
|
const auth = this.rest.auth;
|
|
2665
|
-
if (!_optionalChain([auth, 'optionalAccess',
|
|
3387
|
+
if (!_optionalChain([auth, 'optionalAccess', _40 => _40.onUnauthorized])) return false;
|
|
2666
3388
|
return auth.onUnauthorized();
|
|
2667
3389
|
}
|
|
2668
3390
|
async #open(reconnect = false) {
|
|
2669
3391
|
const headers = { "User-Agent": USER_AGENT };
|
|
2670
|
-
if (_optionalChain([this, 'access',
|
|
3392
|
+
if (_optionalChain([this, 'access', _41 => _41.rest, 'access', _42 => _42.auth, 'optionalAccess', _43 => _43.websocketHeaders])) Object.assign(headers, await this.rest.auth.websocketHeaders({ reconnect }));
|
|
2671
3393
|
const conn = new (0, _ws2.default)(this.url, {
|
|
2672
3394
|
headers,
|
|
2673
3395
|
rejectUnauthorized: this.rest.verifyTls,
|
|
@@ -2681,7 +3403,7 @@ var STXWebSocket = (_class5 = class {
|
|
|
2681
3403
|
const onUnexpected = (_req, res) => {
|
|
2682
3404
|
cleanup();
|
|
2683
3405
|
conn.terminate();
|
|
2684
|
-
const reason = _optionalChain([res, 'access',
|
|
3406
|
+
const reason = _optionalChain([res, 'access', _44 => _44.headers, 'optionalAccess', _45 => _45["x-stx-error"]]);
|
|
2685
3407
|
reject(
|
|
2686
3408
|
new STXTransportException(
|
|
2687
3409
|
`Could not open ${this.url}: HTTP ${res.statusCode}${reason ? ` (${String(reason)})` : ""}`,
|
|
@@ -2716,7 +3438,7 @@ var STXWebSocket = (_class5 = class {
|
|
|
2716
3438
|
if (conn) {
|
|
2717
3439
|
try {
|
|
2718
3440
|
conn.terminate();
|
|
2719
|
-
} catch (
|
|
3441
|
+
} catch (e11) {
|
|
2720
3442
|
}
|
|
2721
3443
|
}
|
|
2722
3444
|
}
|
|
@@ -2755,7 +3477,7 @@ var STXWebSocket = (_class5 = class {
|
|
|
2755
3477
|
let frame;
|
|
2756
3478
|
try {
|
|
2757
3479
|
frame = JSON.parse(raw);
|
|
2758
|
-
} catch (
|
|
3480
|
+
} catch (e12) {
|
|
2759
3481
|
this.logger.warn(`unparseable frame: ${raw.slice(0, 200)}`);
|
|
2760
3482
|
return;
|
|
2761
3483
|
}
|
|
@@ -2826,7 +3548,7 @@ var STXWebSocket = (_class5 = class {
|
|
|
2826
3548
|
} catch (err) {
|
|
2827
3549
|
this.logger.error(`rejoin ${channel.topic} failed: ${err.message}`);
|
|
2828
3550
|
const reply = err instanceof STXChannelException ? err.reply : void 0;
|
|
2829
|
-
if (_optionalChain([reply, 'optionalAccess',
|
|
3551
|
+
if (_optionalChain([reply, 'optionalAccess', _46 => _46.reason]) === "unauthorized" || _optionalChain([reply, 'optionalAccess', _47 => _47.reason]) === COMBOS_UNAVAILABLE_REASON && COMBO_CHANNELS.has(channel.name)) {
|
|
2830
3552
|
channel._close();
|
|
2831
3553
|
return;
|
|
2832
3554
|
}
|
|
@@ -2840,15 +3562,15 @@ var STXWebSocket = (_class5 = class {
|
|
|
2840
3562
|
if (!this.connected) return;
|
|
2841
3563
|
if (this.#pendingHeartbeat !== null) {
|
|
2842
3564
|
this.logger.warn("heartbeat unanswered; reconnecting");
|
|
2843
|
-
_optionalChain([this, 'access',
|
|
3565
|
+
_optionalChain([this, 'access', _48 => _48.#conn, 'optionalAccess', _49 => _49.terminate, 'call', _50 => _50()]);
|
|
2844
3566
|
return;
|
|
2845
3567
|
}
|
|
2846
3568
|
const ref = this.#nextRef();
|
|
2847
3569
|
this.#pendingHeartbeat = ref;
|
|
2848
3570
|
try {
|
|
2849
3571
|
this.#send([null, ref, PHOENIX_TOPIC, "heartbeat", {}]);
|
|
2850
|
-
} catch (
|
|
2851
|
-
_optionalChain([this, 'access',
|
|
3572
|
+
} catch (e13) {
|
|
3573
|
+
_optionalChain([this, 'access', _51 => _51.#conn, 'optionalAccess', _52 => _52.terminate, 'call', _53 => _53()]);
|
|
2852
3574
|
}
|
|
2853
3575
|
}, this.heartbeatIntervalMs);
|
|
2854
3576
|
}
|
|
@@ -2924,7 +3646,7 @@ var STXWebSocket = (_class5 = class {
|
|
|
2924
3646
|
this.error = err;
|
|
2925
3647
|
this.#shutdownAfterDrop();
|
|
2926
3648
|
try {
|
|
2927
|
-
_optionalChain([this, 'access',
|
|
3649
|
+
_optionalChain([this, 'access', _54 => _54.onAuthError, 'optionalCall', _55 => _55(err)]);
|
|
2928
3650
|
} catch (hookErr) {
|
|
2929
3651
|
this.logger.error("onAuthError threw", hookErr);
|
|
2930
3652
|
}
|
|
@@ -2940,7 +3662,7 @@ var STXWebSocket = (_class5 = class {
|
|
|
2940
3662
|
this.#closedWaiters = [];
|
|
2941
3663
|
for (const w of waiters) w();
|
|
2942
3664
|
}
|
|
2943
|
-
},
|
|
3665
|
+
}, _class6);
|
|
2944
3666
|
function dropUndefined(payload) {
|
|
2945
3667
|
return Object.fromEntries(
|
|
2946
3668
|
Object.entries(payload).filter(([, v]) => v !== void 0).map(([k, v]) => [k, Array.isArray(v) ? [...v] : v])
|
|
@@ -3009,5 +3731,17 @@ function dropUndefined(payload) {
|
|
|
3009
3731
|
|
|
3010
3732
|
|
|
3011
3733
|
|
|
3012
|
-
|
|
3013
|
-
|
|
3734
|
+
|
|
3735
|
+
|
|
3736
|
+
|
|
3737
|
+
|
|
3738
|
+
|
|
3739
|
+
|
|
3740
|
+
|
|
3741
|
+
|
|
3742
|
+
|
|
3743
|
+
|
|
3744
|
+
|
|
3745
|
+
|
|
3746
|
+
exports.geoRejection = geoRejection; 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.STXGeoLocationException = STXGeoLocationException; 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;
|
|
3747
|
+
//# sourceMappingURL=chunk-R77AZ5UH.cjs.map
|