@stxapp/stx-typescript 0.6.0 → 0.6.2

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.
@@ -809,7 +809,7 @@ function credentialsFromSettings(keyId, privateKey, signer) {
809
809
  }
810
810
 
811
811
  // src/version.ts
812
- var VERSION = "0.6.0";
812
+ var VERSION = "0.6.2";
813
813
  var USER_AGENT = `stx-typescript/${VERSION}`;
814
814
  var ASYNC_DISPOSE = Symbol.asyncDispose ?? /* @__PURE__ */ Symbol.for("Symbol.asyncDispose");
815
815
 
@@ -1187,6 +1187,105 @@ function toBatchOrderResult(raw) {
1187
1187
  return { ...obj, order, errors, ok: order !== null && !errors?.length };
1188
1188
  }
1189
1189
 
1190
+ // src/legacy-routes.ts
1191
+ function isRouteMissing(err) {
1192
+ return err instanceof STXNotFoundException && err.statusCode === 404 && typeof err.body === "string";
1193
+ }
1194
+ var QUIET = { debug() {
1195
+ }, info() {
1196
+ }, warn() {
1197
+ }, error() {
1198
+ } };
1199
+ var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
1200
+ async function channelSnapshot(client, join3, event) {
1201
+ const me = await client._identity();
1202
+ const ws = client.websocket({
1203
+ userId: me.user_id,
1204
+ reconnect: false,
1205
+ channelPingIntervalMs: null,
1206
+ joinTimeoutMs: client.timeoutMs,
1207
+ logger: QUIET
1208
+ });
1209
+ try {
1210
+ const channel = await join3(ws, me);
1211
+ const snapshot = await channel.waitSnapshot(client.timeoutMs);
1212
+ return snapshot[event];
1213
+ } finally {
1214
+ await ws.close();
1215
+ }
1216
+ }
1217
+ async function balanceFromChannel(client) {
1218
+ const payload = await channelSnapshot(
1219
+ client,
1220
+ (ws, me) => ws.balances(me.account_id ? { accountId: me.account_id } : {}),
1221
+ "balances"
1222
+ );
1223
+ if (!payload || typeof payload !== "object") {
1224
+ throw new STXException("The balances channel sent no balance", { path: "/api/v1/account/balance" });
1225
+ }
1226
+ return payload;
1227
+ }
1228
+ function positionsFilter(marketIds) {
1229
+ if (marketIds === void 0 || marketIds === null) return null;
1230
+ const list = typeof marketIds === "string" ? [marketIds] : [...marketIds];
1231
+ if (list.length === 0) return null;
1232
+ const joined = list.join(",");
1233
+ if (joined === "") return null;
1234
+ const ids2 = joined.split(",").map((s) => s.trim());
1235
+ for (const id of ids2) {
1236
+ if (!UUID.test(id)) {
1237
+ throw new STXValidationException(`${id} is not a valid UUID`, {
1238
+ statusCode: 400,
1239
+ body: { error: `${id} is not a valid UUID` },
1240
+ method: "GET",
1241
+ path: "/api/v1/positions"
1242
+ });
1243
+ }
1244
+ }
1245
+ return new Set(ids2.map((id) => id.toLowerCase()));
1246
+ }
1247
+ async function positionsFromChannel(client, query = {}) {
1248
+ const filter = positionsFilter(query.marketIds);
1249
+ const payload = await channelSnapshot(client, (ws) => ws.positions(), "all_positions");
1250
+ const rows = payload && Array.isArray(payload.positions) ? payload.positions : null;
1251
+ if (!rows) throw new STXException("The positions channel sent no positions", { path: "/api/v1/positions" });
1252
+ return filter ? rows.filter((p) => filter.has(String(p.market_id).toLowerCase())) : rows;
1253
+ }
1254
+ async function placeOrdersOneByOne(client, orders, opts) {
1255
+ if (orders.length === 0) {
1256
+ throw new STXValidationException("orders must not be empty", {
1257
+ statusCode: 400,
1258
+ body: { error: "orders must not be empty" },
1259
+ method: "POST",
1260
+ path: "/api/v1/orders/batched"
1261
+ });
1262
+ }
1263
+ const packet = opts?.geoLocation !== void 0 ? opts.geoLocation : await resolveGeoLocation(client.geoLocation) ?? null;
1264
+ const results = [];
1265
+ let placed = 0;
1266
+ for (let i = 0; i < orders.length; i++) {
1267
+ const { marketId, action, orderType, ...fields } = orders[i];
1268
+ try {
1269
+ const order = await client.placeOrder(marketId, action, orderType, { ...fields, geoLocation: packet });
1270
+ results.push(toBatchOrderResult({ order }));
1271
+ placed += 1;
1272
+ } catch (err) {
1273
+ if (!(err instanceof STXException)) throw err;
1274
+ if (err instanceof STXRejectedException && !(err instanceof STXGeoLocationException)) {
1275
+ results.push(toBatchOrderResult({ errors: [err.message] }));
1276
+ continue;
1277
+ }
1278
+ if (err instanceof STXServerException || err instanceof STXTransportException) throw err;
1279
+ if (placed === 0) throw err;
1280
+ results.push(toBatchOrderResult({ errors: [err.message] }));
1281
+ if (err instanceof STXValidationException) continue;
1282
+ for (let j = i + 1; j < orders.length; j++) results.push(toBatchOrderResult({ errors: [err.message] }));
1283
+ break;
1284
+ }
1285
+ }
1286
+ return results;
1287
+ }
1288
+
1190
1289
  // src/client.ts
1191
1290
  var NEW_ORDER_FIELDS = {
1192
1291
  marketId: "market_id",
@@ -1263,6 +1362,8 @@ var STX = class _STX {
1263
1362
  onResponse;
1264
1363
  #fetch;
1265
1364
  #me;
1365
+ // Exchanges older than v3.3.172: the routes this exchange turned out not to serve.
1366
+ #missingRoutes = /* @__PURE__ */ new Set();
1266
1367
  /** Test hook: how retries wait. */
1267
1368
  _sleep = sleep;
1268
1369
  constructor(opts = {}) {
@@ -1328,7 +1429,7 @@ var STX = class _STX {
1328
1429
  async #headers(request) {
1329
1430
  if (!this.auth) {
1330
1431
  throw new STXConfigException(
1331
- "No API key configured. Pass keyId and privateKey (or set STX_KEY_ID and STX_PRIVATE_KEY, or use a profile in ~/.stx/credentials). Every REST route is signed."
1432
+ "No API key configured. Pass keyId and privateKey (or set STX_KEY_ID and STX_PRIVATE_KEY, or use a profile in ~/.stx/credentials). Every request is signed."
1332
1433
  );
1333
1434
  }
1334
1435
  const headers = {
@@ -1455,9 +1556,17 @@ var STX = class _STX {
1455
1556
  return this.#me;
1456
1557
  }
1457
1558
  /**
1458
- * The user id from `me()`, fetched once and cached. An OAuth token granted
1459
- * without `profile.read` cannot call `me()`; the id then comes from
1460
- * `balance()` (`balance.read`), which carries the same `user_id`.
1559
+ * @internal The cached `me()` when it has both ids, else a fresh `me()`.
1560
+ * Never falls back to `balance()`, so the channel fallbacks can use it.
1561
+ */
1562
+ async _identity() {
1563
+ if (this.#me?.user_id && this.#me.account_id) return this.#me;
1564
+ return this.me();
1565
+ }
1566
+ /**
1567
+ * The user id from `me()`, fetched once and cached. If `me()` is not
1568
+ * permitted, the id comes from `balance()`, which carries the same
1569
+ * `user_id`.
1461
1570
  */
1462
1571
  async userId() {
1463
1572
  if (this.#me?.user_id) return this.#me.user_id;
@@ -1586,7 +1695,15 @@ var STX = class _STX {
1586
1695
  */
1587
1696
  async placeOrders(orders, opts) {
1588
1697
  const body = { orders: orders.map(normalizeOrder) };
1589
- const raw = await this.#list("orders_batched_post", { body: await this.#geoBody(body, opts) });
1698
+ if (this.#missingRoutes.has("batch")) return placeOrdersOneByOne(this, orders, opts);
1699
+ let raw;
1700
+ try {
1701
+ raw = await this.#list("orders_batched_post", { body: await this.#geoBody(body, opts) });
1702
+ } catch (err) {
1703
+ if (!isRouteMissing(err)) throw err;
1704
+ this.#missingRoutes.add("batch");
1705
+ return placeOrdersOneByOne(this, orders, opts);
1706
+ }
1590
1707
  return raw.map(toBatchOrderResult);
1591
1708
  }
1592
1709
  /**
@@ -1670,15 +1787,29 @@ var STX = class _STX {
1670
1787
  * `positions` channel sends on join. `position` is positive when long,
1671
1788
  * negative when short.
1672
1789
  */
1673
- positions(query = {}) {
1674
- return this.#list("positions_get", { query: { market_ids: ids(query.marketIds) } });
1790
+ async positions(query = {}) {
1791
+ if (this.#missingRoutes.has("positions")) return positionsFromChannel(this, query);
1792
+ try {
1793
+ return await this.#list("positions_get", { query: { market_ids: ids(query.marketIds) } });
1794
+ } catch (err) {
1795
+ if (!isRouteMissing(err)) throw err;
1796
+ this.#missingRoutes.add("positions");
1797
+ return positionsFromChannel(this, query);
1798
+ }
1675
1799
  }
1676
1800
  /**
1677
1801
  * `GET /api/v1/account/balance`: balance, liabilities and fee schedule.
1678
1802
  * The same object the `balances` channel pushes.
1679
1803
  */
1680
- balance() {
1681
- return this.#one("account_balance_get");
1804
+ async balance() {
1805
+ if (this.#missingRoutes.has("balance")) return balanceFromChannel(this);
1806
+ try {
1807
+ return await this.#one("account_balance_get");
1808
+ } catch (err) {
1809
+ if (!isRouteMissing(err)) throw err;
1810
+ this.#missingRoutes.add("balance");
1811
+ return balanceFromChannel(this);
1812
+ }
1682
1813
  }
1683
1814
  static #marketStatsQuery(q) {
1684
1815
  return {
@@ -2771,4 +2902,4 @@ export {
2771
2902
  orderBody,
2772
2903
  STX
2773
2904
  };
2774
- //# sourceMappingURL=chunk-U3KT3I43.js.map
2905
+ //# sourceMappingURL=chunk-X7B7WXJ3.js.map