@stxapp/stx-typescript 0.10.0 → 0.12.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.
@@ -43,15 +43,46 @@ var STXTermsRequiredException = class extends STXForbiddenException {
43
43
  };
44
44
  var STXIPNotAllowedException = class extends STXForbiddenException {
45
45
  };
46
+ var STXBlockedException = class extends STXForbiddenException {
47
+ reason;
48
+ reference;
49
+ constructor(message, opts = {}) {
50
+ super(message, opts);
51
+ this.reason = opts.reason ?? "blocked";
52
+ this.reference = opts.reference;
53
+ }
54
+ };
55
+ var STXRestrictedJurisdictionException = class extends STXBlockedException {
56
+ };
57
+ var STXUnusualNetworkException = class extends STXBlockedException {
58
+ };
46
59
  var STXNotFoundException = class extends STXAPIException {
47
60
  };
48
61
  var STXRejectedException = class extends STXAPIException {
49
62
  };
63
+ var STXFillModeNotAllowedException = class extends STXRejectedException {
64
+ fillMode;
65
+ constructor(message, opts) {
66
+ super(message, opts);
67
+ this.fillMode = opts.fillMode;
68
+ }
69
+ };
70
+ var STXPostOnlyWouldMatchException = class extends STXRejectedException {
71
+ reason;
72
+ order;
73
+ constructor(message, opts) {
74
+ super(message, opts);
75
+ this.reason = opts.reason;
76
+ this.order = opts.order;
77
+ }
78
+ };
50
79
  var STXRateLimitException = class extends STXAPIException {
51
80
  retryAfter;
81
+ reference;
52
82
  constructor(message, opts = {}) {
53
83
  super(message, opts);
54
84
  this.retryAfter = opts.retryAfter;
85
+ this.reference = opts.reference;
55
86
  }
56
87
  };
57
88
  var STXServerException = class extends STXAPIException {
@@ -92,21 +123,27 @@ var FEATURE_PHRASES = {
92
123
  event_players: "Event players are",
93
124
  leaderboard: "The leaderboard is",
94
125
  loyalty: "The loyalty program is",
95
- combos: "Combos are"
126
+ combos: "Combos are",
127
+ "orders.post_only": "Post-only orders are",
128
+ "orders.fill_or_kill": "Fill-or-kill orders are"
96
129
  };
97
- function notAvailableMessage(feature, host) {
130
+ function notAvailableMessage(feature, host, apiVersion) {
98
131
  const phrase = feature.startsWith("scope:") ? `The ${feature.slice("scope:".length)} scope is` : FEATURE_PHRASES[feature] ?? `${feature} is`;
99
- return `${phrase} not available on ${host} yet.`;
132
+ const where = apiVersion ? `${host} (version ${apiVersion})` : host;
133
+ return `${phrase} not available on ${where} yet.`;
100
134
  }
101
135
  var STXNotAvailableException = class _STXNotAvailableException extends STXAPIException {
102
136
  /** The feature id, e.g. `"combos"`. */
103
137
  feature;
104
138
  /** The exchange host that lacks it, e.g. `"demo.stxapp.ca"`. */
105
139
  host;
140
+ /** The exchange build, e.g. `"3.4.24"`, when known. */
141
+ apiVersion;
106
142
  constructor(feature, host, opts = {}) {
107
- super(opts.message ?? notAvailableMessage(feature, host), opts);
143
+ super(opts.message ?? notAvailableMessage(feature, host, opts.apiVersion), opts);
108
144
  this.feature = feature;
109
145
  this.host = host;
146
+ this.apiVersion = opts.apiVersion ?? void 0;
110
147
  markNotAvailable(this);
111
148
  }
112
149
  // `this` is the class on the right of `instanceof`: a subclass keeps the
@@ -172,6 +209,18 @@ function errorForStatus(statusCode, body, opts) {
172
209
  message = `HTTP ${statusCode}`;
173
210
  }
174
211
  const base = { statusCode, body, method: opts.method, path: opts.path };
212
+ const edge = edgeBlock(statusCode, body, opts.stxError, opts.cfId);
213
+ if (edge) {
214
+ if (statusCode === 429) {
215
+ return new STXRateLimitException(edge.message, {
216
+ ...base,
217
+ retryAfter: parseRetryAfter(opts.retryAfter),
218
+ reference: edge.reference
219
+ });
220
+ }
221
+ const cls = edge.reason === "restricted_jurisdiction" ? STXRestrictedJurisdictionException : edge.reason === "unusual_network" ? STXUnusualNetworkException : STXBlockedException;
222
+ return new cls(edge.message, { ...base, reason: edge.reason, reference: edge.reference });
223
+ }
175
224
  switch (statusCode) {
176
225
  case 400:
177
226
  return new STXValidationException(message, base);
@@ -206,10 +255,36 @@ function errorForStatus(statusCode, body, opts) {
206
255
  return statusCode >= 500 ? new STXServerException(message, base) : new STXAPIException(message, base);
207
256
  }
208
257
  }
258
+ var NO_USER_AGENT_HINT = "Request blocked (HTTP 403) before it reached the exchange. Every request needs a User-Agent header; if you replaced or removed the SDK's, set one that names your application. If it persists, contact STX support.";
259
+ var EDGE_REASONS = {
260
+ 403: ["restricted_jurisdiction", "unusual_network"],
261
+ 429: ["rate_limited"]
262
+ };
263
+ var REFERENCE_PLACEHOLDER = "x-amz-cf-id response header";
264
+ function edgeBlock(status, body, stxError, cfId) {
265
+ const reasons = EDGE_REASONS[status];
266
+ if (!reasons || stxError) return void 0;
267
+ let reference = cfId || void 0;
268
+ if (body && typeof body === "object") {
269
+ const fields = body;
270
+ if (typeof fields.error !== "string" || !reasons.includes(fields.error)) return void 0;
271
+ if (reference === void 0 && typeof fields.reference === "string" && fields.reference) {
272
+ reference = fields.reference === REFERENCE_PLACEHOLDER ? void 0 : fields.reference;
273
+ }
274
+ return {
275
+ reason: fields.error,
276
+ message: typeof fields.message === "string" && fields.message ? fields.message : fields.error,
277
+ reference
278
+ };
279
+ }
280
+ return status === 403 ? { reason: "blocked", message: NO_USER_AGENT_HINT, reference } : void 0;
281
+ }
209
282
  function parseRetryAfter(value) {
210
283
  if (value === null || value === void 0 || value.trim() === "") return void 0;
211
284
  const n = Number(value);
212
- return Number.isFinite(n) ? Math.max(0, n) : void 0;
285
+ if (Number.isFinite(n)) return Math.max(0, n);
286
+ const at = Date.parse(value);
287
+ return Number.isNaN(at) ? void 0 : Math.max(0, (at - Date.now()) / 1e3);
213
288
  }
214
289
  function bearerError(header) {
215
290
  if (!header || !/^\s*Bearer\b/i.test(header)) return void 0;
@@ -326,7 +401,7 @@ async function discoverCapabilities(probes) {
326
401
  swallow(probes.signedGet("/api/v1/portfolio/loyalty?limit=1")),
327
402
  swallow(probes.joinReason(`rfq:${NOBODY}`))
328
403
  ]);
329
- const apiVersion = json(version)?.api_version;
404
+ const apiVersion = version?.status === 200 ? json(version)?.api_version : null;
330
405
  const meta = oauthMetadataFrom(discovery);
331
406
  const scopes = meta ? strings(meta.scopes_supported) : [];
332
407
  const grants = meta ? strings(meta.grant_types_supported) : [];
@@ -481,7 +556,7 @@ var OPERATIONS = {
481
556
  account_market_stats_get: {
482
557
  method: "GET",
483
558
  path: "/api/v1/account/market_stats",
484
- query: ["market_ids", "event_ids", "exclude_zero_settlements", "from_time", "to_time", "sports", "competitions", "limit", "cursor"],
559
+ query: ["market_ids", "event_ids", "exclude_zero_settlements", "unsettled_only", "from_time", "to_time", "sports", "competitions", "limit", "cursor"],
485
560
  pathParams: [],
486
561
  hasBody: false,
487
562
  responseKey: "market_stats",
@@ -917,6 +992,9 @@ var RetryPolicy = class {
917
992
  shouldRetry(exc, attempt, idempotent) {
918
993
  if (attempt >= this.maxAttempts) return false;
919
994
  if (!this.retryableExceptions.some((cls) => exc instanceof cls)) return false;
995
+ if (exc instanceof STXRateLimitException && exc.retryAfter !== void 0 && exc.retryAfter * 1e3 > this.maxBackoffMs) {
996
+ return false;
997
+ }
920
998
  return idempotent || exc instanceof STXRateLimitException;
921
999
  }
922
1000
  /** Milliseconds to wait after attempt `attempt` (1-based) failed. */
@@ -1178,7 +1256,7 @@ function credentialsFromSettings(keyId, privateKey, signer) {
1178
1256
  }
1179
1257
 
1180
1258
  // src/version.ts
1181
- var VERSION = "0.10.0";
1259
+ var VERSION = "0.12.0";
1182
1260
  var USER_AGENT = `stx-typescript/${VERSION}`;
1183
1261
  var ASYNC_DISPOSE = Symbol.asyncDispose ?? /* @__PURE__ */ Symbol.for("Symbol.asyncDispose");
1184
1262
 
@@ -1828,7 +1906,9 @@ function decodeResponse(request, status, text, headers = {}) {
1828
1906
  method: request.method,
1829
1907
  path: request.path,
1830
1908
  retryAfter: headers.retryAfter,
1831
- wwwAuthenticate: headers.wwwAuthenticate
1909
+ wwwAuthenticate: headers.wwwAuthenticate,
1910
+ stxError: headers.stxError,
1911
+ cfId: headers.cfId
1832
1912
  });
1833
1913
  }
1834
1914
  function splitPage(operationId, body) {
@@ -1847,6 +1927,10 @@ function toBatchOrderResult(raw) {
1847
1927
  }
1848
1928
 
1849
1929
  // src/client.ts
1930
+ var FILL_MODES = ["normal", "post_only", "fill_or_kill"];
1931
+ var NOT_ENABLED = /fill_mode (post_only|fill_or_kill) is not enabled|The (post_only|fill_or_kill) fill mode is not enabled/;
1932
+ var NOT_ACCEPTED = /does not accept the (post_only|fill_or_kill) fill mode/;
1933
+ var MATCH_WITH_SELF = "would match with your other order";
1850
1934
  var NEW_ORDER_FIELDS = {
1851
1935
  marketId: "market_id",
1852
1936
  action: "action",
@@ -1857,7 +1941,8 @@ var NEW_ORDER_FIELDS = {
1857
1941
  expiration: "expiration",
1858
1942
  expirationTime: "expiration_time",
1859
1943
  cancelOnDisconnect: "cancel_on_disconnect",
1860
- deviceId: "device_id"
1944
+ deviceId: "device_id",
1945
+ fillMode: "fill_mode"
1861
1946
  };
1862
1947
  function amount(name, value, required) {
1863
1948
  if (value === void 0 || value === null) {
@@ -1872,6 +1957,13 @@ function amount(name, value, required) {
1872
1957
  return value;
1873
1958
  }
1874
1959
  function orderBody(marketId, action, orderType, opts) {
1960
+ const mode = opts.fillMode;
1961
+ if (mode !== void 0 && mode !== null && !FILL_MODES.includes(mode)) {
1962
+ throw new TypeError(`fillMode must be one of ${JSON.stringify(FILL_MODES)}, got ${JSON.stringify(mode)}`);
1963
+ }
1964
+ if ((mode === "post_only" || mode === "fill_or_kill") && orderType !== "limit") {
1965
+ throw new TypeError(`fillMode "${mode}" is for limit orders only`);
1966
+ }
1875
1967
  const body = {
1876
1968
  market_id: marketId,
1877
1969
  action,
@@ -1884,7 +1976,8 @@ function orderBody(marketId, action, orderType, opts) {
1884
1976
  expiration: opts.expiration,
1885
1977
  expiration_time: opts.expirationTime,
1886
1978
  cancel_on_disconnect: opts.cancelOnDisconnect,
1887
- device_id: opts.deviceId
1979
+ device_id: opts.deviceId,
1980
+ fill_mode: mode === "normal" ? void 0 : mode
1888
1981
  };
1889
1982
  for (const [k, v] of Object.entries(optional)) if (v !== void 0 && v !== null) body[k] = v;
1890
1983
  return body;
@@ -1996,7 +2089,7 @@ var STX = class _STX {
1996
2089
  // ------------------------------------------------------------------
1997
2090
  /**
1998
2091
  * Which features this exchange has, from what it publishes: its OAuth
1999
- * discovery document, `/api_version`, a signed GET of the routes that not
2092
+ * discovery document, a signed GET of the routes that not
2000
2093
  * every exchange has yet, and a join of a combos topic nobody owns. Nothing
2001
2094
  * is created or changed. Checked once per client and cached; pass
2002
2095
  * `{ refresh: true }` to check again.
@@ -2038,6 +2131,20 @@ var STX = class _STX {
2038
2131
  clearTimeout(timer);
2039
2132
  }
2040
2133
  }
2134
+ // A typed error for the exchange's refusals of a fill mode, else undefined.
2135
+ #fillModeError(err, mode) {
2136
+ if (!(err instanceof STXValidationException || err instanceof STXRejectedException)) return void 0;
2137
+ const base = { statusCode: err.statusCode, body: err.body, method: err.method, path: err.path, cause: err };
2138
+ const off = NOT_ENABLED.exec(err.message);
2139
+ if (off) return new STXNotAvailableException(`orders.${off[1] ?? off[2]}`, this.host, base);
2140
+ if (!(err instanceof STXRejectedException)) return void 0;
2141
+ const notAccepted = NOT_ACCEPTED.exec(err.message);
2142
+ if (notAccepted) return new STXFillModeNotAllowedException(err.message, { ...base, fillMode: notAccepted[1] });
2143
+ if (mode === "post_only" && err.message.includes(MATCH_WITH_SELF)) {
2144
+ return new STXPostOnlyWouldMatchException(err.message, { ...base, reason: "match_with_self" });
2145
+ }
2146
+ return void 0;
2147
+ }
2041
2148
  async #joinReason(topic) {
2042
2149
  if (!this.auth) return null;
2043
2150
  const ws = this.websocket({ reconnect: false, joinTimeoutMs: 8e3 });
@@ -2129,7 +2236,9 @@ var STX = class _STX {
2129
2236
  this.#report(request, response.status, attempt, started, text);
2130
2237
  return decodeResponse(request, response.status, text, {
2131
2238
  retryAfter: response.headers.get("Retry-After"),
2132
- wwwAuthenticate: response.headers.get("WWW-Authenticate")
2239
+ wwwAuthenticate: response.headers.get("WWW-Authenticate"),
2240
+ stxError: response.headers.get("x-stx-error"),
2241
+ cfId: response.headers.get("x-amz-cf-id")
2133
2242
  });
2134
2243
  }
2135
2244
  async #send(request) {
@@ -2388,6 +2497,18 @@ var STX = class _STX {
2388
2497
  * are decimal strings, e.g. `{ price: "0.58", quantity: "100" }`. Numbers are
2389
2498
  * refused client-side.
2390
2499
  *
2500
+ * `fillMode` (limit orders only) is `"normal"` (the default), `"post_only"`
2501
+ * or `"fill_or_kill"`. A post-only order that would match on arrival is not
2502
+ * placed: this throws `STXPostOnlyWouldMatchException`. A fill-or-kill order
2503
+ * comes back `accepted` (or `delayed` in play); follow it on the `orders`
2504
+ * channel or with `order()` to see it `filled` or `cancelled`.
2505
+ *
2506
+ * The exchange decides whether it takes either mode. Where a mode is not
2507
+ * enabled it rejects the order and this throws `STXNotAvailableException`
2508
+ * (`orders.post_only`, `orders.fill_or_kill`). An exchange on a release from
2509
+ * before fill modes places the order as a normal limit order. A combination
2510
+ * market throws `STXFillModeNotAllowedException`.
2511
+ *
2391
2512
  * The exchange validates the order: a bad price step or a fractional
2392
2513
  * quantity throws `STXValidationException` (400) or `STXRejectedException`
2393
2514
  * (422) with the API's message. An order from outside the region is also
@@ -2398,16 +2519,41 @@ var STX = class _STX {
2398
2519
  */
2399
2520
  async placeOrder(marketId, action, orderType, opts) {
2400
2521
  const body = orderBody(marketId, action, orderType, opts ?? {});
2401
- return this.#one("orders_post", { body });
2522
+ const mode = body.fill_mode;
2523
+ if (mode === void 0) return this.#one("orders_post", { body });
2524
+ let order;
2525
+ try {
2526
+ order = await this.#one("orders_post", { body });
2527
+ } catch (err) {
2528
+ throw this.#fillModeError(err, mode) ?? err;
2529
+ }
2530
+ if (mode === "post_only" && order.status === "cancelled" && order.cancellation_reason === "auto_matching") {
2531
+ throw new STXPostOnlyWouldMatchException(
2532
+ "The post-only order would have matched on arrival, so it was cancelled.",
2533
+ { reason: "auto_matching", order, statusCode: 200, method: "POST", path: OPERATIONS.orders_post.path }
2534
+ );
2535
+ }
2536
+ return order;
2402
2537
  }
2403
2538
  /**
2404
2539
  * `POST /api/v1/orders/batched`: place several orders in one call. Returns
2405
2540
  * one result per order, in order; a rejected order has `errors` instead of
2406
- * `order` and does not stop the others.
2541
+ * `order` and does not stop the others. A post-only order that would have
2542
+ * matched comes back as its order, `cancelled` with `cancellation_reason`
2543
+ * `auto_matching`.
2544
+ *
2545
+ * When the exchange rejects the call because a `fillMode` is not enabled
2546
+ * there, this throws `STXNotAvailableException`, as `placeOrder()` does.
2407
2547
  */
2408
2548
  async placeOrders(orders) {
2409
2549
  const body = { orders: orders.map(normalizeOrder) };
2410
- const raw = await this.#list("orders_batched_post", { body });
2550
+ const modes = body.orders.map((o) => o.fill_mode).filter((m) => typeof m === "string");
2551
+ let raw;
2552
+ try {
2553
+ raw = await this.#list("orders_batched_post", { body });
2554
+ } catch (err) {
2555
+ throw (modes.length ? this.#fillModeError(err, void 0) : void 0) ?? err;
2556
+ }
2411
2557
  return raw.map(toBatchOrderResult);
2412
2558
  }
2413
2559
  /**
@@ -2466,6 +2612,7 @@ var STX = class _STX {
2466
2612
  market_ids: ids(q.marketIds),
2467
2613
  event_ids: ids(q.eventIds),
2468
2614
  exclude_zero_settlements: q.excludeZeroSettlements,
2615
+ unsettled_only: q.unsettledOnly,
2469
2616
  from_time: q.fromTime,
2470
2617
  to_time: q.toTime,
2471
2618
  sports: ids(q.sports),
@@ -3711,8 +3858,13 @@ export {
3711
3858
  STXInsufficientScopeException,
3712
3859
  STXTermsRequiredException,
3713
3860
  STXIPNotAllowedException,
3861
+ STXBlockedException,
3862
+ STXRestrictedJurisdictionException,
3863
+ STXUnusualNetworkException,
3714
3864
  STXNotFoundException,
3715
3865
  STXRejectedException,
3866
+ STXFillModeNotAllowedException,
3867
+ STXPostOnlyWouldMatchException,
3716
3868
  STXRateLimitException,
3717
3869
  STXServerException,
3718
3870
  STXTransportException,
@@ -3773,4 +3925,4 @@ export {
3773
3925
  orderBody,
3774
3926
  STX
3775
3927
  };
3776
- //# sourceMappingURL=chunk-FTZCBXT7.js.map
3928
+ //# sourceMappingURL=chunk-JJRK3Z27.js.map