@polymarket/clob-client-v2 1.2.1 → 1.3.1

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/client.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { BUILDER_FEES_BPS, END_CURSOR, INITIAL_CURSOR, ORDER_VERSION_MISMATCH_ERROR, bytes32Zero } from "./constants.js";
2
2
  import { ARE_ORDERS_SCORING, CANCEL_ALL, CANCEL_MARKET_ORDERS, CANCEL_ORDER, CANCEL_ORDERS, CLOSED_ONLY, CREATE_API_KEY, CREATE_BUILDER_API_KEY, CREATE_READONLY_API_KEY, DELETE_API_KEY, DELETE_READONLY_API_KEY, DERIVE_API_KEY, DROP_NOTIFICATIONS, GET_API_KEYS, GET_BALANCE_ALLOWANCE, GET_BUILDER_API_KEYS, GET_BUILDER_FEES, GET_BUILDER_TRADES, GET_CLOB_MARKET, GET_EARNINGS_FOR_USER_FOR_DAY, GET_FEE_RATE, GET_LAST_TRADES_PRICES, GET_LAST_TRADE_PRICE, GET_LIQUIDITY_REWARD_PERCENTAGES, GET_MARKET, GET_MARKETS, GET_MARKET_BY_TOKEN, GET_MARKET_TRADES_EVENTS, GET_MIDPOINT, GET_MIDPOINTS, GET_NEG_RISK, GET_NOTIFICATIONS, GET_OPEN_ORDERS, GET_ORDER, GET_ORDER_BOOK, GET_ORDER_BOOKS, GET_PRE_MIGRATION_ORDERS, GET_PRICE, GET_PRICES, GET_PRICES_HISTORY, GET_READONLY_API_KEYS, GET_REWARDS_EARNINGS_PERCENTAGES, GET_REWARDS_MARKETS, GET_REWARDS_MARKETS_CURRENT, GET_SAMPLING_MARKETS, GET_SAMPLING_SIMPLIFIED_MARKETS, GET_SIMPLIFIED_MARKETS, GET_SPREAD, GET_SPREADS, GET_TICK_SIZE, GET_TOTAL_EARNINGS_FOR_USER_FOR_DAY, GET_TRADES, HEARTBEAT, IS_ORDER_SCORING, OK, POST_ORDER, POST_ORDERS, REVOKE_BUILDER_API_KEY, TIME, UPDATE_BALANCE_ALLOWANCE } from "./endpoints.js";
3
- import { ApiError, L1_AUTH_UNAVAILABLE_ERROR, L2_AUTH_NOT_AVAILABLE } from "./errors.js";
3
+ import { ApiError, L1_AUTH_UNAVAILABLE_ERROR, L2_AUTH_NOT_AVAILABLE, isApiErrorResponse } from "./errors.js";
4
4
  import { adjustBuyAmountForFees, validateFeeSlippage } from "./fees/index.js";
5
5
  import { createL1Headers, createL2Headers } from "./headers/index.js";
6
6
  import { DELETE, GET, POST, del, get, parseDropNotificationParams, post } from "./http-helpers/index.js";
@@ -23,6 +23,20 @@ const RESOLVE_TRADES_POLL_INTERVAL_MS = 250;
23
23
  const FAILED_TRADE_STATUS = "FAILED";
24
24
  const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
25
25
  const isTradeResolved = (trade) => trade.status.toUpperCase() === FAILED_TRADE_STATUS || Boolean(trade.transaction_hash && trade.transaction_hash.length > 0);
26
+ const toApiError = (result) => {
27
+ return new ApiError(typeof result.error === "string" ? result.error : JSON.stringify(result.error), result.status, result);
28
+ };
29
+ const pageItems = (page, endpoint) => {
30
+ if (Array.isArray(page?.data)) return page.data;
31
+ if (isApiErrorResponse(page)) throw toApiError(page);
32
+ throw new ApiError(`unexpected response from ${endpoint}: expected a page with a data array`, void 0, page);
33
+ };
34
+ const requireFields = (result, endpoint, ...fields) => {
35
+ if (isApiErrorResponse(result)) throw toApiError(result);
36
+ const missing = fields.filter((field) => result?.[field] === void 0 || result[field] === null);
37
+ if (missing.length > 0) throw new ApiError(`unexpected response from ${endpoint}: missing ${missing.join(", ")}`, void 0, result);
38
+ return result;
39
+ };
26
40
  var ClobClient = class {
27
41
  host;
28
42
  chainId;
@@ -139,7 +153,8 @@ var ClobClient = class {
139
153
  }
140
154
  async fetchClobMarketInfo(conditionID) {
141
155
  const result = await this.get(`${this.host}${GET_CLOB_MARKET}${conditionID}`);
142
- if (!result?.t) throw new Error(`failed to fetch market info for condition id ${conditionID}`);
156
+ if (isApiErrorResponse(result)) throw toApiError(result);
157
+ if (!result?.t) throw new ApiError(`failed to fetch market info for condition id ${conditionID}`, void 0, result);
143
158
  for (const token of result.t) {
144
159
  if (!token) continue;
145
160
  const tokenId = token.t;
@@ -165,7 +180,7 @@ var ClobClient = class {
165
180
  await this.getClobMarketInfo(this.tokenConditionMap[tokenID]);
166
181
  return this.tickSizes[tokenID];
167
182
  }
168
- const result = await this.get(`${this.host}${GET_TICK_SIZE}`, { params: { token_id: tokenID } });
183
+ const result = requireFields(await this.get(`${this.host}${GET_TICK_SIZE}`, { params: { token_id: tokenID } }), GET_TICK_SIZE, "minimum_tick_size");
169
184
  this.tickSizes[tokenID] = result.minimum_tick_size.toString();
170
185
  return this.tickSizes[tokenID];
171
186
  }
@@ -175,13 +190,13 @@ var ClobClient = class {
175
190
  await this.getClobMarketInfo(this.tokenConditionMap[tokenID]);
176
191
  return this.negRisk[tokenID];
177
192
  }
178
- const result = await this.get(`${this.host}${GET_NEG_RISK}`, { params: { token_id: tokenID } });
193
+ const result = requireFields(await this.get(`${this.host}${GET_NEG_RISK}`, { params: { token_id: tokenID } }), GET_NEG_RISK, "neg_risk");
179
194
  this.negRisk[tokenID] = result.neg_risk;
180
195
  return this.negRisk[tokenID];
181
196
  }
182
197
  async getFeeRateBps(tokenID) {
183
198
  if (tokenID in this.feeRates) return this.feeRates[tokenID];
184
- const result = await this.get(`${this.host}${GET_FEE_RATE}`, { params: { token_id: tokenID } });
199
+ const result = requireFields(await this.get(`${this.host}${GET_FEE_RATE}`, { params: { token_id: tokenID } }), GET_FEE_RATE, "base_fee");
185
200
  this.feeRates[tokenID] = result.base_fee;
186
201
  return this.feeRates[tokenID];
187
202
  }
@@ -352,21 +367,10 @@ var ClobClient = class {
352
367
  requestPath: endpoint
353
368
  };
354
369
  const headers = await createL2Headers(this.signer, this.creds, headerArgs, this.useServerTime ? await this.getServerTime() : void 0);
355
- let results = [];
356
- next_cursor = next_cursor || INITIAL_CURSOR;
357
- while (next_cursor !== END_CURSOR && (next_cursor === INITIAL_CURSOR || !only_first_page)) {
358
- const _params = {
359
- ...params,
360
- next_cursor
361
- };
362
- const response = await this.get(`${this.host}${endpoint}`, {
363
- headers,
364
- params: _params
365
- });
366
- next_cursor = response.next_cursor;
367
- results = [...results, ...response.data];
368
- }
369
- return results;
370
+ return this.getAllPages(endpoint, {
371
+ headers,
372
+ params
373
+ }, next_cursor, only_first_page);
370
374
  }
371
375
  async getTradesPaginated(params, next_cursor) {
372
376
  this.canL2Auth();
@@ -535,21 +539,10 @@ var ClobClient = class {
535
539
  requestPath: endpoint
536
540
  };
537
541
  const headers = await createL2Headers(this.signer, this.creds, l2HeaderArgs, this.useServerTime ? await this.getServerTime() : void 0);
538
- let results = [];
539
- next_cursor = next_cursor || INITIAL_CURSOR;
540
- while (next_cursor !== END_CURSOR && (next_cursor === INITIAL_CURSOR || !only_first_page)) {
541
- const _params = {
542
- ...params,
543
- next_cursor
544
- };
545
- const response = await this.get(`${this.host}${endpoint}`, {
546
- headers,
547
- params: _params
548
- });
549
- next_cursor = response.next_cursor;
550
- results = [...results, ...response.data];
551
- }
552
- return results;
542
+ return this.getAllPages(endpoint, {
543
+ headers,
544
+ params
545
+ }, next_cursor, only_first_page);
553
546
  }
554
547
  async getPreMigrationOrders(only_first_page = false, next_cursor) {
555
548
  this.canL2Auth();
@@ -559,18 +552,7 @@ var ClobClient = class {
559
552
  requestPath: endpoint
560
553
  };
561
554
  const headers = await createL2Headers(this.signer, this.creds, l2HeaderArgs, this.useServerTime ? await this.getServerTime() : void 0);
562
- let results = [];
563
- next_cursor = next_cursor || INITIAL_CURSOR;
564
- while (next_cursor !== END_CURSOR && (next_cursor === INITIAL_CURSOR || !only_first_page)) {
565
- const _params = { next_cursor };
566
- const response = await this.get(`${this.host}${endpoint}`, {
567
- headers,
568
- params: _params
569
- });
570
- next_cursor = response.next_cursor;
571
- results = [...results, ...response.data];
572
- }
573
- return results;
555
+ return this.getAllPages(endpoint, { headers }, next_cursor, only_first_page);
574
556
  }
575
557
  /**
576
558
  * Posts an order to the CLOB.
@@ -738,22 +720,13 @@ var ClobClient = class {
738
720
  requestPath: endpoint
739
721
  };
740
722
  const headers = await createL2Headers(this.signer, this.creds, headerArgs, this.useServerTime ? await this.getServerTime() : void 0);
741
- let results = [];
742
- let next_cursor = INITIAL_CURSOR;
743
- while (next_cursor !== END_CURSOR) {
744
- const params = {
723
+ return this.getAllPages(endpoint, {
724
+ headers,
725
+ params: {
745
726
  date,
746
- signature_type: this.orderBuilder.signatureType,
747
- next_cursor
748
- };
749
- const response = await this.get(`${this.host}${endpoint}`, {
750
- headers,
751
- params
752
- });
753
- next_cursor = response.next_cursor;
754
- results = [...results, ...response.data];
755
- }
756
- return results;
727
+ signature_type: this.orderBuilder.signatureType
728
+ }
729
+ });
757
730
  }
758
731
  async getTotalEarningsForUserForDay(date) {
759
732
  this.canL2Auth();
@@ -780,25 +753,16 @@ var ClobClient = class {
780
753
  requestPath: endpoint
781
754
  };
782
755
  const headers = await createL2Headers(this.signer, this.creds, headerArgs, this.useServerTime ? await this.getServerTime() : void 0);
783
- let results = [];
784
- let next_cursor = INITIAL_CURSOR;
785
- while (next_cursor !== END_CURSOR) {
786
- const params = {
756
+ return this.getAllPages(endpoint, {
757
+ headers,
758
+ params: {
787
759
  date,
788
760
  signature_type: this.orderBuilder.signatureType,
789
- next_cursor,
790
761
  order_by,
791
762
  position,
792
763
  no_competition
793
- };
794
- const response = await this.get(`${this.host}${endpoint}`, {
795
- headers,
796
- params
797
- });
798
- next_cursor = response.next_cursor;
799
- results = [...results, ...response.data];
800
- }
801
- return results;
764
+ }
765
+ });
802
766
  }
803
767
  async getRewardPercentages() {
804
768
  this.canL2Auth();
@@ -815,27 +779,14 @@ var ClobClient = class {
815
779
  });
816
780
  }
817
781
  async getCurrentRewards() {
818
- let results = [];
819
- let next_cursor = INITIAL_CURSOR;
820
- while (next_cursor !== END_CURSOR) {
821
- const response = await this.get(`${this.host}${GET_REWARDS_MARKETS_CURRENT}`, { params: { next_cursor } });
822
- next_cursor = response.next_cursor;
823
- results = [...results, ...response.data];
824
- }
825
- return results;
782
+ return this.getAllPages(GET_REWARDS_MARKETS_CURRENT);
826
783
  }
827
784
  async getRawRewardsForMarket(conditionId) {
828
- let results = [];
829
- let next_cursor = INITIAL_CURSOR;
830
- while (next_cursor !== END_CURSOR) {
831
- const response = await this.get(`${this.host}${GET_REWARDS_MARKETS}${conditionId}`, { params: { next_cursor } });
832
- next_cursor = response.next_cursor;
833
- results = [...results, ...response.data];
834
- }
835
- return results;
785
+ return this.getAllPages(`${GET_REWARDS_MARKETS}${conditionId}`);
836
786
  }
837
787
  async calculateMarketPrice(tokenID, side, amount, orderType = OrderType.FOK) {
838
788
  const book = await this.getOrderBook(tokenID);
789
+ if (isApiErrorResponse(book)) throw toApiError(book);
839
790
  if (!book) throw new Error("no orderbook");
840
791
  if (side === Side.BUY) {
841
792
  if (!book.asks) throw new Error("no match");
@@ -902,7 +853,8 @@ var ClobClient = class {
902
853
  if (tokenID in this.feeInfos) return;
903
854
  if (!(tokenID in this.tokenConditionMap)) {
904
855
  const result = await this.get(`${this.host}${GET_MARKET_BY_TOKEN}${tokenID}`);
905
- if (!result?.condition_id) throw new Error(`failed to resolve condition id for token ${tokenID}`);
856
+ if (isApiErrorResponse(result)) throw toApiError(result);
857
+ if (!result?.condition_id) throw new ApiError(`failed to resolve condition id for token ${tokenID}`, void 0, result);
906
858
  this.tokenConditionMap[tokenID] = result.condition_id;
907
859
  }
908
860
  if (tokenID in this.feeInfos) return;
@@ -911,14 +863,19 @@ var ClobClient = class {
911
863
  async ensureBuilderFeeRateCached(builderCode) {
912
864
  if (!builderCode || builderCode === bytes32Zero) return;
913
865
  if (builderCode in this.builderFeeRates) return;
914
- const result = await this.get(`${this.host}${GET_BUILDER_FEES}${builderCode}`);
866
+ const endpoint = `${GET_BUILDER_FEES}${builderCode}`;
867
+ const result = requireFields(await this.get(`${this.host}${endpoint}`), endpoint, "builder_maker_fee_rate_bps", "builder_taker_fee_rate_bps");
915
868
  this.builderFeeRates[builderCode] = {
916
869
  maker: result.builder_maker_fee_rate_bps / BUILDER_FEES_BPS,
917
870
  taker: result.builder_taker_fee_rate_bps / BUILDER_FEES_BPS
918
871
  };
919
872
  }
920
873
  async _resolveTickSize(tokenID, tickSize) {
921
- const minTickSize = await this.getTickSize(tokenID);
874
+ let minTickSize = await this.getTickSize(tokenID);
875
+ if (tickSize && isTickSizeSmaller(tickSize, minTickSize)) {
876
+ delete this.tickSizes[tokenID];
877
+ minTickSize = await this.getTickSize(tokenID);
878
+ }
922
879
  if (tickSize) {
923
880
  if (isTickSizeSmaller(tickSize, minTickSize)) throw new Error(`invalid tick size (${tickSize}), minimum for the market is ${minTickSize}`);
924
881
  } else tickSize = minTickSize;
@@ -950,9 +907,33 @@ var ClobClient = class {
950
907
  return (typeof error === "string" ? error : JSON.stringify(error)).includes(ORDER_VERSION_MISMATCH_ERROR);
951
908
  }
952
909
  throwIfError(result) {
953
- if (this.throwOnError && result && typeof result === "object" && "error" in result) throw new ApiError(typeof result.error === "string" ? result.error : JSON.stringify(result.error), result.status, result);
910
+ if (this.throwOnError && isApiErrorResponse(result)) throw toApiError(result);
954
911
  return result;
955
912
  }
913
+ /**
914
+ * Collects the items of a cursor-paginated GET endpoint, starting at `cursor` and
915
+ * following `next_cursor` until the server returns END_CURSOR. With `onlyFirstPage`
916
+ * it fetches the page at `cursor` alone. A failed page rejects with ApiError whatever
917
+ * `throwOnError` is, since a partial list cannot be told apart from a complete one.
918
+ */
919
+ async getAllPages(endpoint, options = {}, cursor, onlyFirstPage = false) {
920
+ const items = [];
921
+ let nextCursor = cursor || INITIAL_CURSOR;
922
+ while (nextCursor !== END_CURSOR) {
923
+ const page = await this.get(`${this.host}${endpoint}`, {
924
+ ...options,
925
+ params: {
926
+ ...options.params,
927
+ next_cursor: nextCursor
928
+ }
929
+ });
930
+ items.push(...pageItems(page, endpoint));
931
+ if (onlyFirstPage) break;
932
+ if (typeof page.next_cursor !== "string" || page.next_cursor.length === 0) throw new ApiError(`unexpected response from ${endpoint}: expected a non-empty next_cursor string`, void 0, page);
933
+ nextCursor = page.next_cursor;
934
+ }
935
+ return items;
936
+ }
956
937
  async get(endpoint, options, skipThrow = false) {
957
938
  const result = await get(endpoint, options);
958
939
  return skipThrow ? result : this.throwIfError(result);