@agg-build/sdk 4.24.0 → 4.26.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/dist/index.js CHANGED
@@ -87,6 +87,7 @@ __export(index_exports, {
87
87
  MarketStatus: () => MarketStatus,
88
88
  MatchStatus: () => MatchStatus,
89
89
  MatchType: () => MatchType,
90
+ OPTIONAL_SIGNATURE_TIMEOUT_MS: () => OPTIONAL_SIGNATURE_TIMEOUT_MS,
90
91
  OrderStatus: () => OrderStatus,
91
92
  OrderType: () => OrderType,
92
93
  RECURRENCE_CADENCES: () => RECURRENCE_CADENCES,
@@ -1101,6 +1102,7 @@ function toChecksumAddress(address) {
1101
1102
  // src/types.ts
1102
1103
  var SELF_CUSTODY_FILL_TIMEOUT_MS = 5 * 6e4;
1103
1104
  var SELF_CUSTODY_POLL_INTERVAL_MS = 2e3;
1105
+ var OPTIONAL_SIGNATURE_TIMEOUT_MS = 15e3;
1104
1106
  var TERMINAL_EXECUTION_STATES = /* @__PURE__ */ new Set(["filled", "partially_filled", "failed", "cancelled", "expired"]);
1105
1107
  var RECURRENCE_CADENCES = [
1106
1108
  "PT5M",
@@ -1543,6 +1545,10 @@ var RECONNECT_BASE_MS = 1e3;
1543
1545
  var RECONNECT_MAX_MS = 3e4;
1544
1546
  var STALE_TIMEOUT_MS = 45e3;
1545
1547
  var ORDERBOOK_DEBUG_TOP_LEVELS = 5;
1548
+ var WATCHDOG_SILENCE_MS = 5 * 6e4;
1549
+ var WATCHDOG_CHECK_INTERVAL_MS = 6e4;
1550
+ var WATCHDOG_BATCH_MAX = 100;
1551
+ var WATCHDOG_REQUEST_TIMEOUT_MS = 15e3;
1546
1552
  var AggWebSocket = class {
1547
1553
  constructor(options) {
1548
1554
  this.ws = null;
@@ -1568,6 +1574,18 @@ var AggWebSocket = class {
1568
1574
  this.books = /* @__PURE__ */ new Map();
1569
1575
  /** Markets currently resyncing (awaiting snapshot after seq gap / checksum mismatch). */
1570
1576
  this.resyncing = /* @__PURE__ */ new Set();
1577
+ /**
1578
+ * Per subscribed orderbook outcome: last time it made progress (subscribe,
1579
+ * snapshot, applied delta) or was checked against REST (ms). Tracked from
1580
+ * subscribe, not from the first snapshot, so a book that never arrives or
1581
+ * is stuck resyncing is still found by the watchdog.
1582
+ */
1583
+ this.bookCheckedAt = /* @__PURE__ */ new Map();
1584
+ /** Outcomes the watchdog already resnapshotted; a repeat mismatch resubscribes. */
1585
+ this.watchdogResnapshotted = /* @__PURE__ */ new Set();
1586
+ this.watchdogTimer = null;
1587
+ this.watchdogAbort = null;
1588
+ this.watchdogPausedUntil = 0;
1571
1589
  // ── Connection state ──
1572
1590
  this.connecting = false;
1573
1591
  this._connected = false;
@@ -1583,6 +1601,7 @@ var AggWebSocket = class {
1583
1601
  this.callbacks = (_b = options.callbacks) != null ? _b : {};
1584
1602
  this.initialToken = options.initialToken;
1585
1603
  this.enableLogs = (_c = options.enableLogs) != null ? _c : false;
1604
+ this.bookWatchdog = options.bookWatchdog;
1586
1605
  }
1587
1606
  // ── Public API ──
1588
1607
  get connected() {
@@ -1728,6 +1747,7 @@ var AggWebSocket = class {
1728
1747
  this.subs.set(outcomeId, sub);
1729
1748
  }
1730
1749
  if (sub.refCount === 0) {
1750
+ this.bookCheckedAt.set(outcomeId, Date.now());
1731
1751
  this.pendingSubs.add(outcomeId);
1732
1752
  this.ensureConnected();
1733
1753
  if (this._connected) {
@@ -1752,6 +1772,8 @@ var AggWebSocket = class {
1752
1772
  this.books.delete(outcomeId);
1753
1773
  }
1754
1774
  this.resyncing.delete(outcomeId);
1775
+ this.bookCheckedAt.delete(outcomeId);
1776
+ this.watchdogResnapshotted.delete(outcomeId);
1755
1777
  if (this._connected) {
1756
1778
  if (this.pendingFlushSubs.has(outcomeId)) {
1757
1779
  this.pendingFlushSubs.delete(outcomeId);
@@ -1819,6 +1841,7 @@ var AggWebSocket = class {
1819
1841
  }
1820
1842
  /** Send a JWT to authenticate (or re-authenticate) the connection. */
1821
1843
  authenticate(token) {
1844
+ this.initialToken = token;
1822
1845
  if (this._connected) {
1823
1846
  this.send({ action: "authenticate", token });
1824
1847
  }
@@ -1850,6 +1873,7 @@ var AggWebSocket = class {
1850
1873
  }
1851
1874
  /** Permanently destroy. Cannot reconnect after this. */
1852
1875
  destroy() {
1876
+ var _a;
1853
1877
  this.destroyed = true;
1854
1878
  for (const controller of this.historyControllers)
1855
1879
  controller.abort(new Error("Market-data client disposed"));
@@ -1860,6 +1884,12 @@ var AggWebSocket = class {
1860
1884
  this.subs.clear();
1861
1885
  this.books.clear();
1862
1886
  this.resyncing.clear();
1887
+ if (this.watchdogTimer) clearInterval(this.watchdogTimer);
1888
+ this.watchdogTimer = null;
1889
+ (_a = this.watchdogAbort) == null ? void 0 : _a.abort();
1890
+ this.watchdogAbort = null;
1891
+ this.bookCheckedAt.clear();
1892
+ this.watchdogResnapshotted.clear();
1863
1893
  this.pendingSubs.clear();
1864
1894
  this.pendingTradeSubs.clear();
1865
1895
  this.pendingResnapshots.clear();
@@ -2043,11 +2073,21 @@ var AggWebSocket = class {
2043
2073
  * ready to accept subscriptions. Now flush all pending subs.
2044
2074
  */
2045
2075
  handleConnected(msg) {
2046
- var _a, _b, _c, _d;
2076
+ var _a, _b, _c, _d, _e;
2047
2077
  this._connected = true;
2048
- (_b = (_a = this.callbacks).onConnectionStateChange) == null ? void 0 : _b.call(_a, true);
2049
- (_d = (_c = this.callbacks).onConnected) == null ? void 0 : _d.call(_c, msg);
2078
+ if (this.bookWatchdog && !this.watchdogTimer && !this.destroyed) {
2079
+ this.watchdogTimer = setInterval(
2080
+ () => void this.checkSilentBooks(),
2081
+ (_a = this.bookWatchdog.checkIntervalMs) != null ? _a : WATCHDOG_CHECK_INTERVAL_MS
2082
+ );
2083
+ }
2084
+ (_c = (_b = this.callbacks).onConnectionStateChange) == null ? void 0 : _c.call(_b, true);
2085
+ (_e = (_d = this.callbacks).onConnected) == null ? void 0 : _e.call(_d, msg);
2050
2086
  const orderbookSet = new Set(this.activeOrderbookMarkets());
2087
+ const reconnectedAt = Date.now();
2088
+ for (const id of orderbookSet) {
2089
+ if (this.bookCheckedAt.has(id)) this.bookCheckedAt.set(id, reconnectedAt);
2090
+ }
2051
2091
  this.pendingSubs.forEach((id) => orderbookSet.add(id));
2052
2092
  this.pendingFlushSubs.forEach((id) => orderbookSet.add(id));
2053
2093
  const orderbookIds = Array.from(orderbookSet);
@@ -2090,6 +2130,7 @@ var AggWebSocket = class {
2090
2130
  const msg = __spreadProps(__spreadValues({}, raw), { timestamp: raw.timestamp / 1e3 });
2091
2131
  const book = snapshotToOrderbook(msg);
2092
2132
  this.books.set(msg.outcomeId, new IndexedOrderbook(book));
2133
+ this.bookCheckedAt.set(msg.outcomeId, Date.now());
2093
2134
  this.resyncing.delete(msg.outcomeId);
2094
2135
  this.pendingResnapshots.delete(msg.outcomeId);
2095
2136
  this.debugOrderbook("snapshot_applied", {
@@ -2159,6 +2200,8 @@ var AggWebSocket = class {
2159
2200
  this.requestResnapshot(outcomeId);
2160
2201
  return;
2161
2202
  }
2203
+ this.bookCheckedAt.set(outcomeId, Date.now());
2204
+ this.watchdogResnapshotted.delete(outcomeId);
2162
2205
  (_b = (_a = this.callbacks).onBookTick) == null ? void 0 : _b.call(_a, outcomeId, {
2163
2206
  midpoint: msg.midpoint,
2164
2207
  timestamp: msg.timestamp,
@@ -2181,6 +2224,8 @@ var AggWebSocket = class {
2181
2224
  var _a, _b;
2182
2225
  const msg = __spreadProps(__spreadValues({}, raw), { timestamp: raw.timestamp / 1e3 });
2183
2226
  this.books.delete(msg.outcomeId);
2227
+ this.bookCheckedAt.delete(msg.outcomeId);
2228
+ this.watchdogResnapshotted.delete(msg.outcomeId);
2184
2229
  this.pendingResnapshots.delete(msg.outcomeId);
2185
2230
  this.resyncing.delete(msg.outcomeId);
2186
2231
  (_b = (_a = this.callbacks).onMarketResolved) == null ? void 0 : _b.call(_a, msg);
@@ -2200,6 +2245,89 @@ var AggWebSocket = class {
2200
2245
  const msg = __spreadProps(__spreadValues({}, raw), { timestamp: raw.timestamp / 1e3 });
2201
2246
  (_b = (_a = this.callbacks).onRedeemEvent) == null ? void 0 : _b.call(_a, msg);
2202
2247
  }
2248
+ // ── Book watchdog ──
2249
+ /**
2250
+ * Heartbeats prove the socket, not each stream. Every subscribed outcome
2251
+ * with no progress for `silenceMs` is checked against the REST `seq`:
2252
+ *
2253
+ * - book present, not resyncing, same `seq` → the market is just quiet;
2254
+ * - different `seq`, no book (snapshot never arrived, or a resubscribe's
2255
+ * snapshot was lost), or stuck resyncing (any recovery whose snapshot
2256
+ * was lost) → resnapshot, then resubscribe on the next overdue check;
2257
+ * - REST can't serve it (`null`) → counted as an attempt, so the next
2258
+ * batch moves on to other outcomes instead of retrying the same 100.
2259
+ */
2260
+ checkSilentBooks() {
2261
+ return __async(this, null, function* () {
2262
+ var _a;
2263
+ const opts = this.bookWatchdog;
2264
+ if (!opts || !this._connected || this.watchdogAbort) return;
2265
+ const now = Date.now();
2266
+ if (now < this.watchdogPausedUntil) return;
2267
+ const silenceMs = (_a = opts.silenceMs) != null ? _a : WATCHDOG_SILENCE_MS;
2268
+ const silent = this.activeOrderbookMarkets().filter((id) => this.bookCheckedAt.has(id)).filter((id) => now - this.bookCheckedAt.get(id) >= silenceMs).sort((a, b) => this.bookCheckedAt.get(a) - this.bookCheckedAt.get(b)).slice(0, WATCHDOG_BATCH_MAX);
2269
+ if (silent.length === 0) return;
2270
+ const checkedAt = new Map(silent.map((id) => [id, this.bookCheckedAt.get(id)]));
2271
+ const abort = new AbortController();
2272
+ this.watchdogAbort = abort;
2273
+ const timeout = setTimeout(() => abort.abort(), WATCHDOG_REQUEST_TIMEOUT_MS);
2274
+ try {
2275
+ const url = new URL(`${opts.baseUrl.replace(/\/$/, "")}/orderbooks/outcomes`);
2276
+ url.searchParams.set("venueMarketOutcomeIds", silent.join(","));
2277
+ url.searchParams.set("depth", "1");
2278
+ const response = yield fetch(url, { headers: opts.headers, signal: abort.signal });
2279
+ if (!response.ok) {
2280
+ const retryAfterS = Number(response.headers.get("retry-after"));
2281
+ if (response.status === 429 && retryAfterS > 0) {
2282
+ this.watchdogPausedUntil = Date.now() + retryAfterS * 1e3;
2283
+ }
2284
+ this.emitDiagnostic({ type: "book_watchdog_error", status: response.status });
2285
+ return;
2286
+ }
2287
+ const body = yield response.json();
2288
+ if (this.destroyed) return;
2289
+ silent.forEach((outcomeId, i) => {
2290
+ var _a2, _b;
2291
+ if (this.bookCheckedAt.get(outcomeId) !== checkedAt.get(outcomeId)) return;
2292
+ const server = (_a2 = body.data) == null ? void 0 : _a2[i];
2293
+ if (!server) {
2294
+ this.bookCheckedAt.set(outcomeId, Date.now());
2295
+ return;
2296
+ }
2297
+ const book = this.books.get(outcomeId);
2298
+ if (book && !this.resyncing.has(outcomeId) && server.seq === book.seq) {
2299
+ this.bookCheckedAt.set(outcomeId, Date.now());
2300
+ this.watchdogResnapshotted.delete(outcomeId);
2301
+ return;
2302
+ }
2303
+ const action = this.watchdogResnapshotted.has(outcomeId) ? "resubscribe" : "resnapshot";
2304
+ this.emitDiagnostic({
2305
+ type: "book_watchdog_resync",
2306
+ outcomeId,
2307
+ localSeq: (_b = book == null ? void 0 : book.seq) != null ? _b : null,
2308
+ serverSeq: server.seq,
2309
+ action
2310
+ });
2311
+ this.bookCheckedAt.set(outcomeId, Date.now());
2312
+ if (action === "resubscribe") {
2313
+ this.watchdogResnapshotted.delete(outcomeId);
2314
+ this.books.delete(outcomeId);
2315
+ this.resyncing.add(outcomeId);
2316
+ this.send({ action: "unsubscribe", channel: "orderbook", outcomeIds: [outcomeId] });
2317
+ this.sendSubscribe([outcomeId]);
2318
+ } else {
2319
+ this.watchdogResnapshotted.add(outcomeId);
2320
+ this.requestResnapshot(outcomeId, true);
2321
+ }
2322
+ });
2323
+ } catch (e) {
2324
+ if (!this.destroyed) this.emitDiagnostic({ type: "book_watchdog_error", status: null });
2325
+ } finally {
2326
+ clearTimeout(timeout);
2327
+ if (this.watchdogAbort === abort) this.watchdogAbort = null;
2328
+ }
2329
+ });
2330
+ }
2203
2331
  // ── Resnapshot ──
2204
2332
  requestResnapshot(outcomeId, force = false) {
2205
2333
  if (this.resyncing.has(outcomeId) && !force) return;
@@ -2424,6 +2552,21 @@ var AUTH_PATHS = /* @__PURE__ */ new Set([
2424
2552
  "/auth/token/exchange",
2425
2553
  "/auth/sign-out"
2426
2554
  ]);
2555
+ function withTimeout(p, ms) {
2556
+ return new Promise((resolve, reject) => {
2557
+ const timer = setTimeout(() => reject(new Error(`timed out after ${ms}ms`)), ms);
2558
+ p.then(
2559
+ (v) => {
2560
+ clearTimeout(timer);
2561
+ resolve(v);
2562
+ },
2563
+ (e) => {
2564
+ clearTimeout(timer);
2565
+ reject(e);
2566
+ }
2567
+ );
2568
+ });
2569
+ }
2427
2570
  var AggClient = class {
2428
2571
  constructor(options) {
2429
2572
  this.listeners = /* @__PURE__ */ new Set();
@@ -3141,23 +3284,38 @@ Issued At: ${issuedAt}`;
3141
3284
  getLeaderboard() {
3142
3285
  return __async(this, arguments, function* (params = {}) {
3143
3286
  const query = {};
3144
- if (params.from) query.from = params.from;
3145
- if (params.to) query.to = params.to;
3146
- if (params.metric) query.metric = params.metric;
3287
+ for (const key of [
3288
+ "from",
3289
+ "to",
3290
+ "metric",
3291
+ "cursor",
3292
+ "userId",
3293
+ "externalId",
3294
+ "username",
3295
+ "walletAddress"
3296
+ ]) {
3297
+ const value = params[key];
3298
+ if (value) query[key] = value;
3299
+ }
3147
3300
  if (params.limit != null) query.limit = String(params.limit);
3148
- if (params.cursor) query.cursor = params.cursor;
3301
+ for (const key of ["categoryIds", "venueEventIds", "userIds"]) {
3302
+ const value = params[key];
3303
+ if (value == null ? void 0 : value.length) query[key] = value;
3304
+ }
3149
3305
  return this.request("/leaderboard", {
3150
3306
  query: Object.keys(query).length ? query : void 0
3151
3307
  });
3152
3308
  });
3153
3309
  }
3154
3310
  /**
3155
- * One user's leaderboard stats per UTC day (default the last 30 days, at
3156
- * most 366) with a running cumulative realized P&L. Gross of fees;
3311
+ * One user's (or, with no user, the whole app's) leaderboard stats per UTC
3312
+ * day (default the last 30 days, at most 366) with a running cumulative
3313
+ * realized P&L, optionally for a single category. Gross of fees;
3157
3314
  * unrealized P&L is not included.
3158
3315
  */
3159
3316
  getLeaderboardSeries(params) {
3160
3317
  return __async(this, null, function* () {
3318
+ var _a;
3161
3319
  const query = {};
3162
3320
  for (const key of [
3163
3321
  "from",
@@ -3170,17 +3328,21 @@ Issued At: ${issuedAt}`;
3170
3328
  const value = params[key];
3171
3329
  if (value) query[key] = value;
3172
3330
  }
3331
+ if ((_a = params.categoryIds) == null ? void 0 : _a.length) query.categoryIds = params.categoryIds;
3173
3332
  return this.request("/leaderboard/series", { query });
3174
3333
  });
3175
3334
  }
3176
3335
  /** List execution positions for the authenticated user (cursor pagination). */
3177
3336
  getExecutionPositions() {
3178
3337
  return __async(this, arguments, function* (params = {}) {
3338
+ var _a;
3179
3339
  const query = {};
3180
3340
  if (params.cursor) query.cursor = params.cursor;
3181
3341
  if (params.limit != null) query.limit = String(params.limit);
3182
3342
  if (params.status) query.status = params.status;
3183
3343
  if (params.mode) query.mode = params.mode;
3344
+ if ((_a = params.categoryIds) == null ? void 0 : _a.length) query.categoryIds = params.categoryIds;
3345
+ if (params.sort) query.sort = params.sort;
3184
3346
  return this.request("/execution/positions", {
3185
3347
  query: Object.keys(query).length ? query : void 0
3186
3348
  });
@@ -3943,6 +4105,9 @@ Issued At: ${issuedAt}`;
3943
4105
  }
3944
4106
  if (params.referralPayer) query.referralPayer = params.referralPayer;
3945
4107
  if (params.referralPayerAddress) query.referralPayerAddress = params.referralPayerAddress;
4108
+ if (params.referralActivationSponsorAddress) {
4109
+ query.referralActivationSponsorAddress = params.referralActivationSponsorAddress;
4110
+ }
3946
4111
  const response = yield this.request(
3947
4112
  `/orderbook/${encodeURIComponent(venueMarketOutcomeId)}/route`,
3948
4113
  { query, signal: options == null ? void 0 : options.signal }
@@ -3973,11 +4138,15 @@ Issued At: ${issuedAt}`;
3973
4138
  const url = new URL(this.wsUrl);
3974
4139
  if (this._appId) url.searchParams.set("appId", this._appId);
3975
4140
  const createSocket = (_a = this.webSocketFactory) != null ? _a : ((socketOptions) => new AggWebSocket(socketOptions));
4141
+ const watchdogHeaders = {};
4142
+ if (this._appId) watchdogHeaders["x-app-id"] = this._appId;
4143
+ if (this.apiKey) watchdogHeaders["x-app-api-key"] = this.apiKey;
3976
4144
  return createSocket({
3977
4145
  url: url.toString(),
3978
4146
  callbacks,
3979
4147
  initialToken: this.accessToken,
3980
- enableLogs: (_b = options == null ? void 0 : options.enableLogs) != null ? _b : false
4148
+ enableLogs: (_b = options == null ? void 0 : options.enableLogs) != null ? _b : false,
4149
+ bookWatchdog: (options == null ? void 0 : options.bookWatchdog) === false ? void 0 : __spreadValues({ baseUrl: this.baseUrl, headers: watchdogHeaders }, options == null ? void 0 : options.bookWatchdog)
3981
4150
  });
3982
4151
  }
3983
4152
  /** Execute a previously quoted managed trade. Returns pending order IDs. */
@@ -4012,7 +4181,7 @@ Issued At: ${issuedAt}`;
4012
4181
  */
4013
4182
  fillSelfCustody(params) {
4014
4183
  return __async(this, null, function* () {
4015
- var _a, _b, _c;
4184
+ var _a, _b, _c, _d;
4016
4185
  if (this.signer && !params.signingAddress) {
4017
4186
  throw new Error(
4018
4187
  "fillSelfCustody requires `signingAddress` \u2014 the wallet that will sign this fill."
@@ -4061,7 +4230,11 @@ Issued At: ${issuedAt}`;
4061
4230
  }
4062
4231
  lastKey = key;
4063
4232
  const signatures = [];
4064
- for (const req of pending) {
4233
+ const ordered = [...pending].sort((a, b) => Number(!!a.optional) - Number(!!b.optional));
4234
+ const userSigners = new Set(
4235
+ [params.signingAddress, ...pending.filter((p) => !p.optional).map((p) => p.signerAddress)].filter((a) => !!a).map((a) => a.toLowerCase())
4236
+ );
4237
+ for (const req of ordered) {
4065
4238
  if (Date.now() > new Date(req.expiresAt).getTime()) {
4066
4239
  if (req.optional) {
4067
4240
  declinedOptional.add(req.stepId);
@@ -4073,7 +4246,7 @@ Issued At: ${issuedAt}`;
4073
4246
  }
4074
4247
  let signed;
4075
4248
  try {
4076
- signed = yield signer(req);
4249
+ signed = req.optional && !userSigners.has((_c = req.signerAddress) == null ? void 0 : _c.toLowerCase()) ? yield withTimeout(signer(req), OPTIONAL_SIGNATURE_TIMEOUT_MS) : yield signer(req);
4077
4250
  } catch (err) {
4078
4251
  if (!req.optional) throw err;
4079
4252
  declinedOptional.add(req.stepId);
@@ -4088,7 +4261,7 @@ Issued At: ${issuedAt}`;
4088
4261
  continue;
4089
4262
  }
4090
4263
  const next = yield this.submitFillSignatures(quoteId, signatures);
4091
- pending = (_c = next.pendingSignatures) != null ? _c : [];
4264
+ pending = (_d = next.pendingSignatures) != null ? _d : [];
4092
4265
  }
4093
4266
  });
4094
4267
  }
@@ -4241,11 +4414,14 @@ Issued At: ${issuedAt}`;
4241
4414
  /** Get open positions grouped by matched market with per-venue breakdown. */
4242
4415
  getPositions(params) {
4243
4416
  return __async(this, null, function* () {
4417
+ var _a;
4244
4418
  const query = {};
4245
4419
  if (params == null ? void 0 : params.cursor) query.cursor = params.cursor;
4246
4420
  if ((params == null ? void 0 : params.limit) != null) query.limit = String(params.limit);
4247
4421
  if (params == null ? void 0 : params.status) query.status = params.status;
4248
4422
  if (params == null ? void 0 : params.mode) query.mode = params.mode;
4423
+ if ((_a = params == null ? void 0 : params.categoryIds) == null ? void 0 : _a.length) query.categoryIds = params.categoryIds;
4424
+ if (params == null ? void 0 : params.sort) query.sort = params.sort;
4249
4425
  return this.request("/execution/positions", {
4250
4426
  query: Object.keys(query).length > 0 ? query : void 0
4251
4427
  });
@@ -4683,6 +4859,7 @@ function createAggClient(options) {
4683
4859
  MarketStatus,
4684
4860
  MatchStatus,
4685
4861
  MatchType,
4862
+ OPTIONAL_SIGNATURE_TIMEOUT_MS,
4686
4863
  OrderStatus,
4687
4864
  OrderType,
4688
4865
  RECURRENCE_CADENCES,
package/dist/index.mjs CHANGED
@@ -59,7 +59,7 @@ import {
59
59
  safeParse,
60
60
  snapshotToOrderbook,
61
61
  sortVenues
62
- } from "./chunk-QXBVA5TW.mjs";
62
+ } from "./chunk-CPMSVNBO.mjs";
63
63
  import {
64
64
  __async,
65
65
  __objRest,
@@ -244,6 +244,7 @@ function toChecksumAddress(address) {
244
244
  // src/types.ts
245
245
  var SELF_CUSTODY_FILL_TIMEOUT_MS = 5 * 6e4;
246
246
  var SELF_CUSTODY_POLL_INTERVAL_MS = 2e3;
247
+ var OPTIONAL_SIGNATURE_TIMEOUT_MS = 15e3;
247
248
  var TERMINAL_EXECUTION_STATES = /* @__PURE__ */ new Set(["filled", "partially_filled", "failed", "cancelled", "expired"]);
248
249
  var RECURRENCE_CADENCES = [
249
250
  "PT5M",
@@ -341,6 +342,21 @@ var AUTH_PATHS = /* @__PURE__ */ new Set([
341
342
  "/auth/token/exchange",
342
343
  "/auth/sign-out"
343
344
  ]);
345
+ function withTimeout(p, ms) {
346
+ return new Promise((resolve, reject) => {
347
+ const timer = setTimeout(() => reject(new Error(`timed out after ${ms}ms`)), ms);
348
+ p.then(
349
+ (v) => {
350
+ clearTimeout(timer);
351
+ resolve(v);
352
+ },
353
+ (e) => {
354
+ clearTimeout(timer);
355
+ reject(e);
356
+ }
357
+ );
358
+ });
359
+ }
344
360
  var AggClient = class {
345
361
  constructor(options) {
346
362
  this.listeners = /* @__PURE__ */ new Set();
@@ -1058,23 +1074,38 @@ Issued At: ${issuedAt}`;
1058
1074
  getLeaderboard() {
1059
1075
  return __async(this, arguments, function* (params = {}) {
1060
1076
  const query = {};
1061
- if (params.from) query.from = params.from;
1062
- if (params.to) query.to = params.to;
1063
- if (params.metric) query.metric = params.metric;
1077
+ for (const key of [
1078
+ "from",
1079
+ "to",
1080
+ "metric",
1081
+ "cursor",
1082
+ "userId",
1083
+ "externalId",
1084
+ "username",
1085
+ "walletAddress"
1086
+ ]) {
1087
+ const value = params[key];
1088
+ if (value) query[key] = value;
1089
+ }
1064
1090
  if (params.limit != null) query.limit = String(params.limit);
1065
- if (params.cursor) query.cursor = params.cursor;
1091
+ for (const key of ["categoryIds", "venueEventIds", "userIds"]) {
1092
+ const value = params[key];
1093
+ if (value == null ? void 0 : value.length) query[key] = value;
1094
+ }
1066
1095
  return this.request("/leaderboard", {
1067
1096
  query: Object.keys(query).length ? query : void 0
1068
1097
  });
1069
1098
  });
1070
1099
  }
1071
1100
  /**
1072
- * One user's leaderboard stats per UTC day (default the last 30 days, at
1073
- * most 366) with a running cumulative realized P&L. Gross of fees;
1101
+ * One user's (or, with no user, the whole app's) leaderboard stats per UTC
1102
+ * day (default the last 30 days, at most 366) with a running cumulative
1103
+ * realized P&L, optionally for a single category. Gross of fees;
1074
1104
  * unrealized P&L is not included.
1075
1105
  */
1076
1106
  getLeaderboardSeries(params) {
1077
1107
  return __async(this, null, function* () {
1108
+ var _a;
1078
1109
  const query = {};
1079
1110
  for (const key of [
1080
1111
  "from",
@@ -1087,17 +1118,21 @@ Issued At: ${issuedAt}`;
1087
1118
  const value = params[key];
1088
1119
  if (value) query[key] = value;
1089
1120
  }
1121
+ if ((_a = params.categoryIds) == null ? void 0 : _a.length) query.categoryIds = params.categoryIds;
1090
1122
  return this.request("/leaderboard/series", { query });
1091
1123
  });
1092
1124
  }
1093
1125
  /** List execution positions for the authenticated user (cursor pagination). */
1094
1126
  getExecutionPositions() {
1095
1127
  return __async(this, arguments, function* (params = {}) {
1128
+ var _a;
1096
1129
  const query = {};
1097
1130
  if (params.cursor) query.cursor = params.cursor;
1098
1131
  if (params.limit != null) query.limit = String(params.limit);
1099
1132
  if (params.status) query.status = params.status;
1100
1133
  if (params.mode) query.mode = params.mode;
1134
+ if ((_a = params.categoryIds) == null ? void 0 : _a.length) query.categoryIds = params.categoryIds;
1135
+ if (params.sort) query.sort = params.sort;
1101
1136
  return this.request("/execution/positions", {
1102
1137
  query: Object.keys(query).length ? query : void 0
1103
1138
  });
@@ -1860,6 +1895,9 @@ Issued At: ${issuedAt}`;
1860
1895
  }
1861
1896
  if (params.referralPayer) query.referralPayer = params.referralPayer;
1862
1897
  if (params.referralPayerAddress) query.referralPayerAddress = params.referralPayerAddress;
1898
+ if (params.referralActivationSponsorAddress) {
1899
+ query.referralActivationSponsorAddress = params.referralActivationSponsorAddress;
1900
+ }
1863
1901
  const response = yield this.request(
1864
1902
  `/orderbook/${encodeURIComponent(venueMarketOutcomeId)}/route`,
1865
1903
  { query, signal: options == null ? void 0 : options.signal }
@@ -1890,11 +1928,15 @@ Issued At: ${issuedAt}`;
1890
1928
  const url = new URL(this.wsUrl);
1891
1929
  if (this._appId) url.searchParams.set("appId", this._appId);
1892
1930
  const createSocket = (_a = this.webSocketFactory) != null ? _a : ((socketOptions) => new AggWebSocket(socketOptions));
1931
+ const watchdogHeaders = {};
1932
+ if (this._appId) watchdogHeaders["x-app-id"] = this._appId;
1933
+ if (this.apiKey) watchdogHeaders["x-app-api-key"] = this.apiKey;
1893
1934
  return createSocket({
1894
1935
  url: url.toString(),
1895
1936
  callbacks,
1896
1937
  initialToken: this.accessToken,
1897
- enableLogs: (_b = options == null ? void 0 : options.enableLogs) != null ? _b : false
1938
+ enableLogs: (_b = options == null ? void 0 : options.enableLogs) != null ? _b : false,
1939
+ bookWatchdog: (options == null ? void 0 : options.bookWatchdog) === false ? void 0 : __spreadValues({ baseUrl: this.baseUrl, headers: watchdogHeaders }, options == null ? void 0 : options.bookWatchdog)
1898
1940
  });
1899
1941
  }
1900
1942
  /** Execute a previously quoted managed trade. Returns pending order IDs. */
@@ -1929,7 +1971,7 @@ Issued At: ${issuedAt}`;
1929
1971
  */
1930
1972
  fillSelfCustody(params) {
1931
1973
  return __async(this, null, function* () {
1932
- var _a, _b, _c;
1974
+ var _a, _b, _c, _d;
1933
1975
  if (this.signer && !params.signingAddress) {
1934
1976
  throw new Error(
1935
1977
  "fillSelfCustody requires `signingAddress` \u2014 the wallet that will sign this fill."
@@ -1978,7 +2020,11 @@ Issued At: ${issuedAt}`;
1978
2020
  }
1979
2021
  lastKey = key;
1980
2022
  const signatures = [];
1981
- for (const req of pending) {
2023
+ const ordered = [...pending].sort((a, b) => Number(!!a.optional) - Number(!!b.optional));
2024
+ const userSigners = new Set(
2025
+ [params.signingAddress, ...pending.filter((p) => !p.optional).map((p) => p.signerAddress)].filter((a) => !!a).map((a) => a.toLowerCase())
2026
+ );
2027
+ for (const req of ordered) {
1982
2028
  if (Date.now() > new Date(req.expiresAt).getTime()) {
1983
2029
  if (req.optional) {
1984
2030
  declinedOptional.add(req.stepId);
@@ -1990,7 +2036,7 @@ Issued At: ${issuedAt}`;
1990
2036
  }
1991
2037
  let signed;
1992
2038
  try {
1993
- signed = yield signer(req);
2039
+ signed = req.optional && !userSigners.has((_c = req.signerAddress) == null ? void 0 : _c.toLowerCase()) ? yield withTimeout(signer(req), OPTIONAL_SIGNATURE_TIMEOUT_MS) : yield signer(req);
1994
2040
  } catch (err) {
1995
2041
  if (!req.optional) throw err;
1996
2042
  declinedOptional.add(req.stepId);
@@ -2005,7 +2051,7 @@ Issued At: ${issuedAt}`;
2005
2051
  continue;
2006
2052
  }
2007
2053
  const next = yield this.submitFillSignatures(quoteId, signatures);
2008
- pending = (_c = next.pendingSignatures) != null ? _c : [];
2054
+ pending = (_d = next.pendingSignatures) != null ? _d : [];
2009
2055
  }
2010
2056
  });
2011
2057
  }
@@ -2158,11 +2204,14 @@ Issued At: ${issuedAt}`;
2158
2204
  /** Get open positions grouped by matched market with per-venue breakdown. */
2159
2205
  getPositions(params) {
2160
2206
  return __async(this, null, function* () {
2207
+ var _a;
2161
2208
  const query = {};
2162
2209
  if (params == null ? void 0 : params.cursor) query.cursor = params.cursor;
2163
2210
  if ((params == null ? void 0 : params.limit) != null) query.limit = String(params.limit);
2164
2211
  if (params == null ? void 0 : params.status) query.status = params.status;
2165
2212
  if (params == null ? void 0 : params.mode) query.mode = params.mode;
2213
+ if ((_a = params == null ? void 0 : params.categoryIds) == null ? void 0 : _a.length) query.categoryIds = params.categoryIds;
2214
+ if (params == null ? void 0 : params.sort) query.sort = params.sort;
2166
2215
  return this.request("/execution/positions", {
2167
2216
  query: Object.keys(query).length > 0 ? query : void 0
2168
2217
  });
@@ -2449,6 +2498,7 @@ export {
2449
2498
  MarketStatus,
2450
2499
  MatchStatus,
2451
2500
  MatchType,
2501
+ OPTIONAL_SIGNATURE_TIMEOUT_MS,
2452
2502
  OrderStatus,
2453
2503
  OrderType,
2454
2504
  RECURRENCE_CADENCES,
@@ -1,5 +1,5 @@
1
- import { C as ChartBarsResponse } from './agg-websocket-Cm_8f8hA.mjs';
2
- export { bD as CandleTail, ci as HistoryRangeRequest, M as MarketDataEngine, cp as MarketView, cq as MarketViewBatch } from './agg-websocket-Cm_8f8hA.mjs';
1
+ import { C as ChartBarsResponse } from './agg-websocket-x_U4-orL.mjs';
2
+ export { bE as CandleTail, cj as HistoryRangeRequest, M as MarketDataEngine, cr as MarketView, cs as MarketViewBatch } from './agg-websocket-x_U4-orL.mjs';
3
3
 
4
4
  /** Decode bounded dynamic history where processing lives; retain milliseconds and optional mean. */
5
5
  declare function decodeChartHistory(payload: string): ChartBarsResponse;
@@ -1,5 +1,5 @@
1
- import { C as ChartBarsResponse } from './agg-websocket-Cm_8f8hA.js';
2
- export { bD as CandleTail, ci as HistoryRangeRequest, M as MarketDataEngine, cp as MarketView, cq as MarketViewBatch } from './agg-websocket-Cm_8f8hA.js';
1
+ import { C as ChartBarsResponse } from './agg-websocket-x_U4-orL.js';
2
+ export { bE as CandleTail, cj as HistoryRangeRequest, M as MarketDataEngine, cr as MarketView, cs as MarketViewBatch } from './agg-websocket-x_U4-orL.js';
3
3
 
4
4
  /** Decode bounded dynamic history where processing lives; retain milliseconds and optional mean. */
5
5
  declare function decodeChartHistory(payload: string): ChartBarsResponse;