felix-mcp 2.0.108 → 2.0.110

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.
Files changed (46) hide show
  1. package/README.md +2 -2
  2. package/THIRD_PARTY_NOTICES.md +28 -0
  3. package/dist/getting-started-guide.js +1 -1
  4. package/dist/index.js +1 -1
  5. package/dist/polymarket.js +1 -1
  6. package/dist/vendor/polymarket-clob-v2/client.js +985 -0
  7. package/dist/vendor/polymarket-clob-v2/config.js +33 -0
  8. package/dist/vendor/polymarket-clob-v2/constants.js +9 -0
  9. package/dist/vendor/polymarket-clob-v2/endpoints.js +64 -0
  10. package/dist/vendor/polymarket-clob-v2/errors.js +16 -0
  11. package/dist/vendor/polymarket-clob-v2/fees/index.js +20 -0
  12. package/dist/vendor/polymarket-clob-v2/headers/index.js +34 -0
  13. package/dist/vendor/polymarket-clob-v2/http-helpers/index.js +112 -0
  14. package/dist/vendor/polymarket-clob-v2/index.js +14 -0
  15. package/dist/vendor/polymarket-clob-v2/order-builder/helpers/buildMarketOrderCreationArgs.js +40 -0
  16. package/dist/vendor/polymarket-clob-v2/order-builder/helpers/buildOrder.js +32 -0
  17. package/dist/vendor/polymarket-clob-v2/order-builder/helpers/buildOrderCreationArgs.js +42 -0
  18. package/dist/vendor/polymarket-clob-v2/order-builder/helpers/calculateBuyMarketPrice.js +25 -0
  19. package/dist/vendor/polymarket-clob-v2/order-builder/helpers/calculateSellMarketPrice.js +25 -0
  20. package/dist/vendor/polymarket-clob-v2/order-builder/helpers/createExchangeV3OrderFromAmounts.js +30 -0
  21. package/dist/vendor/polymarket-clob-v2/order-builder/helpers/createMarketOrder.js +33 -0
  22. package/dist/vendor/polymarket-clob-v2/order-builder/helpers/createOrder.js +33 -0
  23. package/dist/vendor/polymarket-clob-v2/order-builder/helpers/getMarketOrderRawAmounts.js +37 -0
  24. package/dist/vendor/polymarket-clob-v2/order-builder/helpers/getOrderRawAmounts.js +37 -0
  25. package/dist/vendor/polymarket-clob-v2/order-builder/helpers/roundingConfig.js +36 -0
  26. package/dist/vendor/polymarket-clob-v2/order-builder/orderBuilder.js +57 -0
  27. package/dist/vendor/polymarket-clob-v2/order-utils/exchangeOrderBuilderV1.js +135 -0
  28. package/dist/vendor/polymarket-clob-v2/order-utils/exchangeOrderBuilderV2.js +195 -0
  29. package/dist/vendor/polymarket-clob-v2/order-utils/model/ctfExchangeV1TypedData.js +56 -0
  30. package/dist/vendor/polymarket-clob-v2/order-utils/model/ctfExchangeV2TypedData.js +53 -0
  31. package/dist/vendor/polymarket-clob-v2/order-utils/model/eip712.js +22 -0
  32. package/dist/vendor/polymarket-clob-v2/order-utils/model/side.js +9 -0
  33. package/dist/vendor/polymarket-clob-v2/order-utils/model/signatureTypeV1.js +19 -0
  34. package/dist/vendor/polymarket-clob-v2/order-utils/model/signatureTypeV2.js +23 -0
  35. package/dist/vendor/polymarket-clob-v2/order-utils/utils.js +7 -0
  36. package/dist/vendor/polymarket-clob-v2/signing/constants.js +5 -0
  37. package/dist/vendor/polymarket-clob-v2/signing/eip712.js +49 -0
  38. package/dist/vendor/polymarket-clob-v2/signing/hmac.js +43 -0
  39. package/dist/vendor/polymarket-clob-v2/signing/signer.js +44 -0
  40. package/dist/vendor/polymarket-clob-v2/types/clob.js +30 -0
  41. package/dist/vendor/polymarket-clob-v2/types/ordersV1.js +27 -0
  42. package/dist/vendor/polymarket-clob-v2/types/ordersV2.js +28 -0
  43. package/dist/vendor/polymarket-clob-v2/types/unifiedOrder.js +9 -0
  44. package/dist/vendor/polymarket-clob-v2/utilities.js +48 -0
  45. package/package.json +6 -3
  46. package/server.json +2 -2
@@ -0,0 +1,985 @@
1
+ import { BUILDER_FEES_BPS, END_CURSOR, INITIAL_CURSOR, ORDER_VERSION_MISMATCH_ERROR, bytes32Zero } from "./constants.js";
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";
4
+ import { adjustBuyAmountForFees, validateFeeSlippage } from "./fees/index.js";
5
+ import { createL1Headers, createL2Headers } from "./headers/index.js";
6
+ import { DELETE, GET, POST, del, get, parseDropNotificationParams, post } from "./http-helpers/index.js";
7
+ import { SignatureTypeV2 } from "./order-utils/model/signatureTypeV2.js";
8
+ import { Side } from "./order-utils/model/side.js";
9
+ import { OrderType } from "./types/clob.js";
10
+ import { orderToJsonV1 } from "./types/ordersV1.js";
11
+ import { orderToJsonV2 } from "./types/ordersV2.js";
12
+ import { isV2Order } from "./types/unifiedOrder.js";
13
+ import { generateOrderBookSummaryHash, isTickSizeSmaller, priceValid, roundNormal } from "./utilities.js";
14
+ import { calculateBuyMarketPrice } from "./order-builder/helpers/calculateBuyMarketPrice.js";
15
+ import { calculateSellMarketPrice } from "./order-builder/helpers/calculateSellMarketPrice.js";
16
+ import { ROUNDING_CONFIG } from "./order-builder/helpers/roundingConfig.js";
17
+ import { OrderBuilder } from "./order-builder/orderBuilder.js";
18
+ //#region src/client.ts
19
+ const RESOLVE_TRADES_TIMEOUT_MS = 3e4;
20
+ const RESOLVE_TRADES_POLL_INTERVAL_MS = 250;
21
+ const FAILED_TRADE_STATUS = "FAILED";
22
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
23
+ const isTradeResolved = (trade) => trade.status.toUpperCase() === FAILED_TRADE_STATUS || Boolean(trade.transaction_hash && trade.transaction_hash.length > 0);
24
+ var ClobClient = class {
25
+ host;
26
+ chainId;
27
+ signer;
28
+ creds;
29
+ orderBuilder;
30
+ tickSizes;
31
+ negRisk;
32
+ feeInfos;
33
+ feeRates;
34
+ builderFeeRates;
35
+ tokenConditionMap;
36
+ useServerTime;
37
+ builderConfig;
38
+ signatureType;
39
+ funderAddress;
40
+ cachedVersion;
41
+ retryOnError;
42
+ throwOnError;
43
+ feeSlippage;
44
+ constructor({ host, chain, signer, creds, signatureType, funderAddress, useServerTime, builderConfig, getSigner, retryOnError, throwOnError, feeSlippage }) {
45
+ this.host = host.endsWith("/") ? host.slice(0, -1) : host;
46
+ this.chainId = chain;
47
+ if (signer !== void 0)
48
+ this.signer = signer;
49
+ if (creds !== void 0)
50
+ this.creds = creds;
51
+ this.orderBuilder = new OrderBuilder(signer, chain, signatureType, funderAddress, getSigner);
52
+ this.signatureType = signatureType ?? SignatureTypeV2.EOA;
53
+ this.funderAddress = funderAddress;
54
+ this.tickSizes = {};
55
+ this.negRisk = {};
56
+ this.feeRates = {};
57
+ this.feeInfos = {};
58
+ this.builderFeeRates = {};
59
+ this.tokenConditionMap = {};
60
+ this.retryOnError = retryOnError;
61
+ this.throwOnError = throwOnError;
62
+ this.feeSlippage = feeSlippage ?? 0;
63
+ validateFeeSlippage(this.feeSlippage);
64
+ this.useServerTime = useServerTime;
65
+ if (builderConfig !== void 0)
66
+ this.builderConfig = builderConfig;
67
+ }
68
+ async getOk() {
69
+ return this.get(`${this.host}${OK}`);
70
+ }
71
+ async postHeartbeat(heartbeatId = "") {
72
+ this.canL2Auth();
73
+ const body = JSON.stringify({ heartbeat_id: heartbeatId });
74
+ const headers = await createL2Headers(this.signer, this.creds, {
75
+ method: POST,
76
+ requestPath: HEARTBEAT,
77
+ body
78
+ }, this.useServerTime ? await this.getServerTime() : void 0);
79
+ return this.post(`${this.host}${HEARTBEAT}`, {
80
+ headers,
81
+ data: { heartbeat_id: heartbeatId }
82
+ });
83
+ }
84
+ async getVersion() {
85
+ return (await this.get(`${this.host}/version`))?.version ?? 2;
86
+ }
87
+ async getServerTime() {
88
+ return this.get(`${this.host}${TIME}`);
89
+ }
90
+ async getSamplingSimplifiedMarkets(next_cursor = INITIAL_CURSOR) {
91
+ return this.get(`${this.host}${GET_SAMPLING_SIMPLIFIED_MARKETS}`, { params: { next_cursor } });
92
+ }
93
+ async getSamplingMarkets(next_cursor = INITIAL_CURSOR) {
94
+ return this.get(`${this.host}${GET_SAMPLING_MARKETS}`, { params: { next_cursor } });
95
+ }
96
+ async getSimplifiedMarkets(next_cursor = INITIAL_CURSOR) {
97
+ return this.get(`${this.host}${GET_SIMPLIFIED_MARKETS}`, { params: { next_cursor } });
98
+ }
99
+ async getMarkets(next_cursor = INITIAL_CURSOR) {
100
+ return this.get(`${this.host}${GET_MARKETS}`, { params: { next_cursor } });
101
+ }
102
+ async getMarket(conditionID) {
103
+ return this.get(`${this.host}${GET_MARKET}${conditionID}`);
104
+ }
105
+ async getClobMarketInfo(conditionID) {
106
+ const result = await this.get(`${this.host}${GET_CLOB_MARKET}${conditionID}`);
107
+ if (!result?.t)
108
+ throw new Error(`failed to fetch market info for condition id ${conditionID}`);
109
+ for (const token of result.t) {
110
+ if (!token)
111
+ continue;
112
+ const tokenId = token.t;
113
+ this.tokenConditionMap[tokenId] = conditionID;
114
+ this.tickSizes[tokenId] = result.mts.toString();
115
+ this.negRisk[tokenId] = result.nr ?? false;
116
+ this.feeInfos[tokenId] = {
117
+ rate: result.fd?.r ?? 0,
118
+ exponent: result.fd?.e ?? 0
119
+ };
120
+ }
121
+ return result;
122
+ }
123
+ async getOrderBook(tokenID) {
124
+ return this.get(`${this.host}${GET_ORDER_BOOK}`, { params: { token_id: tokenID } });
125
+ }
126
+ async getOrderBooks(params) {
127
+ return this.post(`${this.host}${GET_ORDER_BOOKS}`, { data: params });
128
+ }
129
+ async getTickSize(tokenID) {
130
+ if (tokenID in this.tickSizes)
131
+ return this.tickSizes[tokenID];
132
+ if (tokenID in this.tokenConditionMap) {
133
+ await this.getClobMarketInfo(this.tokenConditionMap[tokenID]);
134
+ return this.tickSizes[tokenID];
135
+ }
136
+ const result = await this.get(`${this.host}${GET_TICK_SIZE}`, { params: { token_id: tokenID } });
137
+ this.tickSizes[tokenID] = result.minimum_tick_size.toString();
138
+ return this.tickSizes[tokenID];
139
+ }
140
+ async getNegRisk(tokenID) {
141
+ if (tokenID in this.negRisk)
142
+ return this.negRisk[tokenID];
143
+ if (tokenID in this.tokenConditionMap) {
144
+ await this.getClobMarketInfo(this.tokenConditionMap[tokenID]);
145
+ return this.negRisk[tokenID];
146
+ }
147
+ const result = await this.get(`${this.host}${GET_NEG_RISK}`, { params: { token_id: tokenID } });
148
+ this.negRisk[tokenID] = result.neg_risk;
149
+ return this.negRisk[tokenID];
150
+ }
151
+ async getFeeRateBps(tokenID) {
152
+ if (tokenID in this.feeRates)
153
+ return this.feeRates[tokenID];
154
+ const result = await this.get(`${this.host}${GET_FEE_RATE}`, { params: { token_id: tokenID } });
155
+ this.feeRates[tokenID] = result.base_fee;
156
+ return this.feeRates[tokenID];
157
+ }
158
+ async getFeeExponent(tokenID) {
159
+ if (tokenID in this.feeInfos)
160
+ return this.feeInfos[tokenID].exponent;
161
+ await this._ensureMarketInfoCached(tokenID);
162
+ return this.feeInfos[tokenID].exponent;
163
+ }
164
+ /**
165
+ * Calculates the hash for the given orderbook
166
+ * @param orderbook
167
+ * @returns
168
+ */
169
+ async getOrderBookHash(orderbook) {
170
+ return generateOrderBookSummaryHash(orderbook);
171
+ }
172
+ async getMidpoint(tokenID) {
173
+ return this.get(`${this.host}${GET_MIDPOINT}`, { params: { token_id: tokenID } });
174
+ }
175
+ async getMidpoints(params) {
176
+ return this.post(`${this.host}${GET_MIDPOINTS}`, { data: params });
177
+ }
178
+ async getPrice(tokenID, side) {
179
+ return this.get(`${this.host}${GET_PRICE}`, { params: {
180
+ token_id: tokenID,
181
+ side
182
+ } });
183
+ }
184
+ async getPrices(params) {
185
+ return this.post(`${this.host}${GET_PRICES}`, { data: params });
186
+ }
187
+ async getSpread(tokenID) {
188
+ return this.get(`${this.host}${GET_SPREAD}`, { params: { token_id: tokenID } });
189
+ }
190
+ async getSpreads(params) {
191
+ return this.post(`${this.host}${GET_SPREADS}`, { data: params });
192
+ }
193
+ async getLastTradePrice(tokenID) {
194
+ return this.get(`${this.host}${GET_LAST_TRADE_PRICE}`, { params: { token_id: tokenID } });
195
+ }
196
+ async getLastTradesPrices(params) {
197
+ return this.post(`${this.host}${GET_LAST_TRADES_PRICES}`, { data: params });
198
+ }
199
+ async getPricesHistory(params) {
200
+ if (!params.interval && (params.startTs === void 0 || params.endTs === void 0))
201
+ throw new Error("getPricesHistory requires either interval or both startTs and endTs");
202
+ return this.get(`${this.host}${GET_PRICES_HISTORY}`, { params });
203
+ }
204
+ /**
205
+ * Creates a new API key for a user
206
+ * @param nonce
207
+ * @returns ApiKeyCreds
208
+ */
209
+ async createApiKey(nonce) {
210
+ this.canL1Auth();
211
+ const endpoint = `${this.host}${CREATE_API_KEY}`;
212
+ const headers = await createL1Headers(this.signer, this.chainId, nonce, this.useServerTime ? await this.getServerTime() : void 0);
213
+ return await this.post(endpoint, { headers }).then((apiKeyRaw) => {
214
+ return {
215
+ key: apiKeyRaw.apiKey,
216
+ secret: apiKeyRaw.secret,
217
+ passphrase: apiKeyRaw.passphrase
218
+ };
219
+ });
220
+ }
221
+ /**
222
+ * Derives an existing API key for a user
223
+ * @param nonce
224
+ * @returns ApiKeyCreds
225
+ */
226
+ async deriveApiKey(nonce) {
227
+ this.canL1Auth();
228
+ const endpoint = `${this.host}${DERIVE_API_KEY}`;
229
+ const headers = await createL1Headers(this.signer, this.chainId, nonce, this.useServerTime ? await this.getServerTime() : void 0);
230
+ return await this.get(endpoint, { headers }).then((apiKeyRaw) => {
231
+ return {
232
+ key: apiKeyRaw.apiKey,
233
+ secret: apiKeyRaw.secret,
234
+ passphrase: apiKeyRaw.passphrase
235
+ };
236
+ });
237
+ }
238
+ async createOrDeriveApiKey(nonce) {
239
+ return this.createApiKey(nonce).then((response) => {
240
+ if (!response.key)
241
+ return this.deriveApiKey(nonce);
242
+ return response;
243
+ });
244
+ }
245
+ async getApiKeys() {
246
+ this.canL2Auth();
247
+ const endpoint = GET_API_KEYS;
248
+ const headerArgs = {
249
+ method: GET,
250
+ requestPath: endpoint
251
+ };
252
+ const headers = await createL2Headers(this.signer, this.creds, headerArgs, this.useServerTime ? await this.getServerTime() : void 0);
253
+ return this.get(`${this.host}${endpoint}`, { headers });
254
+ }
255
+ async getClosedOnlyMode() {
256
+ this.canL2Auth();
257
+ const endpoint = CLOSED_ONLY;
258
+ const headerArgs = {
259
+ method: GET,
260
+ requestPath: endpoint
261
+ };
262
+ const headers = await createL2Headers(this.signer, this.creds, headerArgs, this.useServerTime ? await this.getServerTime() : void 0);
263
+ return this.get(`${this.host}${endpoint}`, { headers });
264
+ }
265
+ async deleteApiKey() {
266
+ this.canL2Auth();
267
+ const endpoint = DELETE_API_KEY;
268
+ const headerArgs = {
269
+ method: DELETE,
270
+ requestPath: endpoint
271
+ };
272
+ const headers = await createL2Headers(this.signer, this.creds, headerArgs, this.useServerTime ? await this.getServerTime() : void 0);
273
+ return this.del(`${this.host}${endpoint}`, { headers });
274
+ }
275
+ async createReadonlyApiKey() {
276
+ this.canL2Auth();
277
+ const endpoint = CREATE_READONLY_API_KEY;
278
+ const headerArgs = {
279
+ method: POST,
280
+ requestPath: endpoint
281
+ };
282
+ const headers = await createL2Headers(this.signer, this.creds, headerArgs, this.useServerTime ? await this.getServerTime() : void 0);
283
+ return this.post(`${this.host}${endpoint}`, { headers });
284
+ }
285
+ async getReadonlyApiKeys() {
286
+ this.canL2Auth();
287
+ const endpoint = GET_READONLY_API_KEYS;
288
+ const headerArgs = {
289
+ method: GET,
290
+ requestPath: endpoint
291
+ };
292
+ const headers = await createL2Headers(this.signer, this.creds, headerArgs, this.useServerTime ? await this.getServerTime() : void 0);
293
+ return this.get(`${this.host}${endpoint}`, { headers });
294
+ }
295
+ async deleteReadonlyApiKey(key) {
296
+ this.canL2Auth();
297
+ const endpoint = DELETE_READONLY_API_KEY;
298
+ const payload = { key };
299
+ const headerArgs = {
300
+ method: DELETE,
301
+ requestPath: endpoint,
302
+ body: JSON.stringify(payload)
303
+ };
304
+ const headers = await createL2Headers(this.signer, this.creds, headerArgs, this.useServerTime ? await this.getServerTime() : void 0);
305
+ return this.del(`${this.host}${endpoint}`, {
306
+ headers,
307
+ data: payload
308
+ });
309
+ }
310
+ async getOrder(orderID) {
311
+ this.canL2Auth();
312
+ const endpoint = `${GET_ORDER}${orderID}`;
313
+ const headerArgs = {
314
+ method: GET,
315
+ requestPath: endpoint
316
+ };
317
+ const headers = await createL2Headers(this.signer, this.creds, headerArgs, this.useServerTime ? await this.getServerTime() : void 0);
318
+ return this.get(`${this.host}${endpoint}`, { headers });
319
+ }
320
+ async getTrades(params, only_first_page = false, next_cursor) {
321
+ this.canL2Auth();
322
+ const endpoint = GET_TRADES;
323
+ const headerArgs = {
324
+ method: GET,
325
+ requestPath: endpoint
326
+ };
327
+ const headers = await createL2Headers(this.signer, this.creds, headerArgs, this.useServerTime ? await this.getServerTime() : void 0);
328
+ let results = [];
329
+ next_cursor = next_cursor || INITIAL_CURSOR;
330
+ while (next_cursor !== END_CURSOR && (next_cursor === INITIAL_CURSOR || !only_first_page)) {
331
+ const _params = {
332
+ ...params,
333
+ next_cursor
334
+ };
335
+ const response = await this.get(`${this.host}${endpoint}`, {
336
+ headers,
337
+ params: _params
338
+ });
339
+ next_cursor = response.next_cursor;
340
+ results = [...results, ...response.data];
341
+ }
342
+ return results;
343
+ }
344
+ async getTradesPaginated(params, next_cursor) {
345
+ this.canL2Auth();
346
+ const endpoint = GET_TRADES;
347
+ const headerArgs = {
348
+ method: GET,
349
+ requestPath: endpoint
350
+ };
351
+ const headers = await createL2Headers(this.signer, this.creds, headerArgs, this.useServerTime ? await this.getServerTime() : void 0);
352
+ next_cursor = next_cursor || INITIAL_CURSOR;
353
+ const _params = {
354
+ ...params,
355
+ next_cursor
356
+ };
357
+ const { data, ...rest } = await this.get(`${this.host}${endpoint}`, {
358
+ headers,
359
+ params: _params
360
+ });
361
+ return {
362
+ trades: Array.isArray(data) ? [...data] : [],
363
+ ...rest
364
+ };
365
+ }
366
+ async getBuilderTrades(params, next_cursor) {
367
+ if (!params.builder_code || params.builder_code === bytes32Zero)
368
+ throw new Error("builderCode is required and cannot be zero");
369
+ const _params = {
370
+ ...params,
371
+ next_cursor: next_cursor || INITIAL_CURSOR
372
+ };
373
+ const { data, ...rest } = await this.get(`${this.host}${GET_BUILDER_TRADES}`, { params: _params });
374
+ return {
375
+ trades: Array.isArray(data) ? [...data] : [],
376
+ ...rest
377
+ };
378
+ }
379
+ async getNotifications() {
380
+ this.canL2Auth();
381
+ const endpoint = GET_NOTIFICATIONS;
382
+ const headerArgs = {
383
+ method: GET,
384
+ requestPath: endpoint
385
+ };
386
+ const headers = await createL2Headers(this.signer, this.creds, headerArgs, this.useServerTime ? await this.getServerTime() : void 0);
387
+ return this.get(`${this.host}${endpoint}`, {
388
+ headers,
389
+ params: { signature_type: this.orderBuilder.signatureType }
390
+ });
391
+ }
392
+ async dropNotifications(params) {
393
+ this.canL2Auth();
394
+ const endpoint = DROP_NOTIFICATIONS;
395
+ const l2HeaderArgs = {
396
+ method: DELETE,
397
+ requestPath: endpoint
398
+ };
399
+ const headers = await createL2Headers(this.signer, this.creds, l2HeaderArgs, this.useServerTime ? await this.getServerTime() : void 0);
400
+ return this.del(`${this.host}${endpoint}`, {
401
+ headers,
402
+ params: parseDropNotificationParams(params)
403
+ });
404
+ }
405
+ async getBalanceAllowance(params) {
406
+ this.canL2Auth();
407
+ const endpoint = GET_BALANCE_ALLOWANCE;
408
+ const headerArgs = {
409
+ method: GET,
410
+ requestPath: endpoint
411
+ };
412
+ const headers = await createL2Headers(this.signer, this.creds, headerArgs, this.useServerTime ? await this.getServerTime() : void 0);
413
+ const _params = {
414
+ ...params,
415
+ signature_type: this.orderBuilder.signatureType
416
+ };
417
+ return this.get(`${this.host}${endpoint}`, {
418
+ headers,
419
+ params: _params
420
+ });
421
+ }
422
+ async updateBalanceAllowance(params) {
423
+ this.canL2Auth();
424
+ const endpoint = UPDATE_BALANCE_ALLOWANCE;
425
+ const headerArgs = {
426
+ method: GET,
427
+ requestPath: endpoint
428
+ };
429
+ const headers = await createL2Headers(this.signer, this.creds, headerArgs, this.useServerTime ? await this.getServerTime() : void 0);
430
+ const _params = {
431
+ ...params,
432
+ signature_type: this.orderBuilder.signatureType
433
+ };
434
+ return this.get(`${this.host}${endpoint}`, {
435
+ headers,
436
+ params: _params
437
+ });
438
+ }
439
+ async createOrder(userOrder, options) {
440
+ this.canL1Auth();
441
+ const orderToSign = { ...userOrder };
442
+ if (this.builderConfig?.builderCode && !orderToSign.builderCode)
443
+ orderToSign.builderCode = this.builderConfig.builderCode;
444
+ const { tokenID } = orderToSign;
445
+ const tickSize = await this._resolveTickSize(tokenID, options?.tickSize);
446
+ if (!priceValid(orderToSign.price, tickSize))
447
+ throw new Error(`invalid price (${orderToSign.price}), min: ${parseFloat(tickSize)} - max: ${1 - parseFloat(tickSize)}`);
448
+ orderToSign.price = roundNormal(orderToSign.price, ROUNDING_CONFIG[tickSize].price);
449
+ const version = options?.version ?? await this.resolveVersion();
450
+ if (version !== 1 && orderToSign.side === Side.BUY && "userUSDCBalance" in orderToSign && orderToSign.userUSDCBalance !== void 0)
451
+ orderToSign.size = await this.adjustBuyAmountForBalance(tokenID, orderToSign.size * orderToSign.price, orderToSign.price, orderToSign.userUSDCBalance, orderToSign.builderCode) / orderToSign.price;
452
+ const negRisk = options?.negRisk ?? await this.getNegRisk(tokenID);
453
+ if (version === 1) {
454
+ const userFeeRateBps = "feeRateBps" in orderToSign ? orderToSign.feeRateBps : void 0;
455
+ orderToSign.feeRateBps = await this._resolveFeeRateBps(tokenID, userFeeRateBps);
456
+ }
457
+ return this.orderBuilder.buildOrder(orderToSign, {
458
+ tickSize,
459
+ negRisk
460
+ }, version);
461
+ }
462
+ async createMarketOrder(userMarketOrder, options) {
463
+ this.canL1Auth();
464
+ const { tokenID } = userMarketOrder;
465
+ await this._ensureMarketInfoCached(tokenID);
466
+ const tickSize = await this._resolveTickSize(tokenID, options?.tickSize);
467
+ if (!userMarketOrder.price)
468
+ userMarketOrder.price = await this.calculateMarketPrice(tokenID, userMarketOrder.side, userMarketOrder.amount, userMarketOrder.orderType);
469
+ if (!priceValid(userMarketOrder.price, tickSize))
470
+ throw new Error(`invalid price (${userMarketOrder.price}), min: ${parseFloat(tickSize)} - max: ${1 - parseFloat(tickSize)}`);
471
+ const orderToSign = { ...userMarketOrder };
472
+ if (this.builderConfig?.builderCode && !orderToSign.builderCode)
473
+ orderToSign.builderCode = this.builderConfig.builderCode;
474
+ await this.ensureBuilderFeeRateCached(orderToSign.builderCode);
475
+ if (orderToSign.side === Side.BUY && "userUSDCBalance" in orderToSign && orderToSign.userUSDCBalance !== void 0) {
476
+ const price = orderToSign.price;
477
+ orderToSign.amount = await this.adjustBuyAmountForBalance(tokenID, orderToSign.amount, price, orderToSign.userUSDCBalance, orderToSign.builderCode);
478
+ }
479
+ const negRisk = options?.negRisk ?? await this.getNegRisk(tokenID);
480
+ const version = options?.version ?? await this.resolveVersion();
481
+ if (version === 1) {
482
+ const userFeeRateBps = "feeRateBps" in orderToSign ? orderToSign.feeRateBps : void 0;
483
+ orderToSign.feeRateBps = await this._resolveFeeRateBps(tokenID, userFeeRateBps);
484
+ }
485
+ return this.orderBuilder.buildMarketOrder(orderToSign, {
486
+ tickSize,
487
+ negRisk
488
+ }, version);
489
+ }
490
+ async createExchangeV3OrderFromAmounts(userOrder) {
491
+ this.canL1Auth();
492
+ const orderToSign = { ...userOrder };
493
+ if (this.builderConfig?.builderCode && !orderToSign.builderCode)
494
+ orderToSign.builderCode = this.builderConfig.builderCode;
495
+ return this.orderBuilder.buildExchangeV3OrderFromAmounts(orderToSign);
496
+ }
497
+ async createAndPostOrder(userOrder, options, orderType = OrderType.GTC, postOnly = false, deferExec = false) {
498
+ let postOrderResponse;
499
+ await this._retryOnVersionUpdate(async () => {
500
+ const order = await this.createOrder(userOrder, options);
501
+ postOrderResponse = await this.postOrder(order, orderType, postOnly, deferExec);
502
+ });
503
+ return postOrderResponse;
504
+ }
505
+ async createAndPostMarketOrder(userMarketOrder, options, orderType = OrderType.FOK, deferExec = false) {
506
+ let postOrderMarketResponse;
507
+ await this._retryOnVersionUpdate(async () => {
508
+ const order = await this.createMarketOrder(userMarketOrder, options);
509
+ postOrderMarketResponse = await this.postOrder(order, orderType, false, deferExec);
510
+ });
511
+ return postOrderMarketResponse;
512
+ }
513
+ async getOpenOrders(params, only_first_page = false, next_cursor) {
514
+ this.canL2Auth();
515
+ const endpoint = GET_OPEN_ORDERS;
516
+ const l2HeaderArgs = {
517
+ method: GET,
518
+ requestPath: endpoint
519
+ };
520
+ const headers = await createL2Headers(this.signer, this.creds, l2HeaderArgs, this.useServerTime ? await this.getServerTime() : void 0);
521
+ let results = [];
522
+ next_cursor = next_cursor || INITIAL_CURSOR;
523
+ while (next_cursor !== END_CURSOR && (next_cursor === INITIAL_CURSOR || !only_first_page)) {
524
+ const _params = {
525
+ ...params,
526
+ next_cursor
527
+ };
528
+ const response = await this.get(`${this.host}${endpoint}`, {
529
+ headers,
530
+ params: _params
531
+ });
532
+ next_cursor = response.next_cursor;
533
+ results = [...results, ...response.data];
534
+ }
535
+ return results;
536
+ }
537
+ async getPreMigrationOrders(only_first_page = false, next_cursor) {
538
+ this.canL2Auth();
539
+ const endpoint = GET_PRE_MIGRATION_ORDERS;
540
+ const l2HeaderArgs = {
541
+ method: GET,
542
+ requestPath: endpoint
543
+ };
544
+ const headers = await createL2Headers(this.signer, this.creds, l2HeaderArgs, this.useServerTime ? await this.getServerTime() : void 0);
545
+ let results = [];
546
+ next_cursor = next_cursor || INITIAL_CURSOR;
547
+ while (next_cursor !== END_CURSOR && (next_cursor === INITIAL_CURSOR || !only_first_page)) {
548
+ const _params = { next_cursor };
549
+ const response = await this.get(`${this.host}${endpoint}`, {
550
+ headers,
551
+ params: _params
552
+ });
553
+ next_cursor = response.next_cursor;
554
+ results = [...results, ...response.data];
555
+ }
556
+ return results;
557
+ }
558
+ /**
559
+ * Posts an order to the CLOB.
560
+ *
561
+ * When the order matches, the response carries the settlement transaction
562
+ * hashes of its fills in `transactionsHashes`, resolved on a best-effort
563
+ * basis. If a hash is not available yet, the fill's trade can be followed
564
+ * via `tradeIDs`.
565
+ */
566
+ async postOrder(order, orderType = OrderType.GTC, postOnly = false, deferExec = false) {
567
+ this.canL2Auth();
568
+ if (postOnly && (orderType === OrderType.FOK || orderType === OrderType.FAK))
569
+ throw new Error("postOnly is not supported for FOK/FAK orders");
570
+ const endpoint = POST_ORDER;
571
+ const orderPayload = isV2Order(order) ? orderToJsonV2(order, this.creds?.key || "", orderType, postOnly, deferExec) : orderToJsonV1(order, this.creds?.key || "", orderType, postOnly, deferExec);
572
+ const l2HeaderArgs = {
573
+ method: POST,
574
+ requestPath: endpoint,
575
+ body: JSON.stringify(orderPayload)
576
+ };
577
+ const headers = await createL2Headers(this.signer, this.creds, l2HeaderArgs, this.useServerTime ? await this.getServerTime() : void 0);
578
+ const res = await this.post(`${this.host}${endpoint}`, {
579
+ headers,
580
+ data: orderPayload
581
+ }, true);
582
+ if (this._isOrderVersionMismatch(res))
583
+ await this.resolveVersion(true);
584
+ const response = this.throwIfError(res);
585
+ if (deferExec)
586
+ return response;
587
+ return this.resolveTransactionsHashes(response);
588
+ }
589
+ async postOrders(args, postOnly = false, deferExec = false) {
590
+ this.canL2Auth();
591
+ if (postOnly && args.some(({ orderType }) => orderType === OrderType.FOK || orderType === OrderType.FAK))
592
+ throw new Error("postOnly is not supported for FOK/FAK orders");
593
+ const endpoint = POST_ORDERS;
594
+ const ordersPayload = [];
595
+ for (const arg of args) {
596
+ const { order, orderType } = arg;
597
+ const orderPayload = isV2Order(order) ? orderToJsonV2(order, this.creds?.key || "", orderType, postOnly, deferExec) : orderToJsonV1(order, this.creds?.key || "", orderType, postOnly, deferExec);
598
+ ordersPayload.push(orderPayload);
599
+ }
600
+ const l2HeaderArgs = {
601
+ method: POST,
602
+ requestPath: endpoint,
603
+ body: JSON.stringify(ordersPayload)
604
+ };
605
+ const headers = await createL2Headers(this.signer, this.creds, l2HeaderArgs, this.useServerTime ? await this.getServerTime() : void 0);
606
+ const res = await this.post(`${this.host}${endpoint}`, {
607
+ headers,
608
+ data: ordersPayload
609
+ }, true);
610
+ if (this._isOrderVersionMismatch(res))
611
+ await this.resolveVersion(true);
612
+ const responses = this.throwIfError(res);
613
+ if (deferExec || !Array.isArray(responses))
614
+ return responses;
615
+ return Promise.all(responses.map((response) => this.resolveTransactionsHashes(response)));
616
+ }
617
+ async waitForResolvedTrades(tradeIDs) {
618
+ const ids = [...new Set(tradeIDs.filter((id) => id.length > 0))];
619
+ if (ids.length === 0)
620
+ return [];
621
+ const resolved = /* @__PURE__ */ new Map();
622
+ const requestedIDs = new Set(ids);
623
+ const deadline = Date.now() + RESOLVE_TRADES_TIMEOUT_MS;
624
+ for (;;) {
625
+ const pending = ids.filter((id) => !resolved.has(id));
626
+ const pages = await Promise.all(pending.map((id) => this.getTrades({ id }, true).catch(() => [])));
627
+ for (const trades of pages)
628
+ for (const trade of trades)
629
+ if (isTradeResolved(trade) && requestedIDs.has(trade.id))
630
+ resolved.set(trade.id, trade);
631
+ if (ids.every((id) => resolved.has(id)) || Date.now() >= deadline)
632
+ return ids.map((id) => resolved.get(id)).filter((trade) => trade !== void 0);
633
+ await sleep(RESOLVE_TRADES_POLL_INTERVAL_MS);
634
+ }
635
+ }
636
+ async resolveTransactionsHashes(response) {
637
+ if (response.transactionsHashes && response.transactionsHashes.length > 0)
638
+ return response;
639
+ const tradeIDs = response.tradeIDs ?? [];
640
+ if (tradeIDs.length === 0)
641
+ return response;
642
+ const transactionsHashes = (await this.waitForResolvedTrades(tradeIDs)).filter((trade) => trade.status.toUpperCase() !== FAILED_TRADE_STATUS).map((trade) => trade.transaction_hash).filter((hash) => Boolean(hash));
643
+ if (transactionsHashes.length === 0)
644
+ return response;
645
+ return {
646
+ ...response,
647
+ transactionsHashes
648
+ };
649
+ }
650
+ async cancelOrder(payload) {
651
+ this.canL2Auth();
652
+ const endpoint = CANCEL_ORDER;
653
+ const l2HeaderArgs = {
654
+ method: DELETE,
655
+ requestPath: endpoint,
656
+ body: JSON.stringify(payload)
657
+ };
658
+ const headers = await createL2Headers(this.signer, this.creds, l2HeaderArgs, this.useServerTime ? await this.getServerTime() : void 0);
659
+ return this.del(`${this.host}${endpoint}`, {
660
+ headers,
661
+ data: payload
662
+ });
663
+ }
664
+ async cancelOrders(ordersHashes) {
665
+ this.canL2Auth();
666
+ const endpoint = CANCEL_ORDERS;
667
+ const l2HeaderArgs = {
668
+ method: DELETE,
669
+ requestPath: endpoint,
670
+ body: JSON.stringify(ordersHashes)
671
+ };
672
+ const headers = await createL2Headers(this.signer, this.creds, l2HeaderArgs, this.useServerTime ? await this.getServerTime() : void 0);
673
+ return this.del(`${this.host}${endpoint}`, {
674
+ headers,
675
+ data: ordersHashes
676
+ });
677
+ }
678
+ async cancelAll() {
679
+ this.canL2Auth();
680
+ const endpoint = CANCEL_ALL;
681
+ const l2HeaderArgs = {
682
+ method: DELETE,
683
+ requestPath: endpoint
684
+ };
685
+ const headers = await createL2Headers(this.signer, this.creds, l2HeaderArgs, this.useServerTime ? await this.getServerTime() : void 0);
686
+ return this.del(`${this.host}${endpoint}`, { headers });
687
+ }
688
+ async cancelMarketOrders(payload) {
689
+ this.canL2Auth();
690
+ const endpoint = CANCEL_MARKET_ORDERS;
691
+ const l2HeaderArgs = {
692
+ method: DELETE,
693
+ requestPath: endpoint,
694
+ body: JSON.stringify(payload)
695
+ };
696
+ const headers = await createL2Headers(this.signer, this.creds, l2HeaderArgs, this.useServerTime ? await this.getServerTime() : void 0);
697
+ return this.del(`${this.host}${endpoint}`, {
698
+ headers,
699
+ data: payload
700
+ });
701
+ }
702
+ async isOrderScoring(params) {
703
+ this.canL2Auth();
704
+ const endpoint = IS_ORDER_SCORING;
705
+ const headerArgs = {
706
+ method: GET,
707
+ requestPath: endpoint
708
+ };
709
+ const headers = await createL2Headers(this.signer, this.creds, headerArgs, this.useServerTime ? await this.getServerTime() : void 0);
710
+ return this.get(`${this.host}${endpoint}`, {
711
+ headers,
712
+ params
713
+ });
714
+ }
715
+ async areOrdersScoring(params) {
716
+ this.canL2Auth();
717
+ const endpoint = ARE_ORDERS_SCORING;
718
+ const payload = JSON.stringify(params?.orderIds);
719
+ const headerArgs = {
720
+ method: POST,
721
+ requestPath: endpoint,
722
+ body: payload
723
+ };
724
+ const headers = await createL2Headers(this.signer, this.creds, headerArgs, this.useServerTime ? await this.getServerTime() : void 0);
725
+ return this.post(`${this.host}${endpoint}`, {
726
+ headers,
727
+ data: payload
728
+ });
729
+ }
730
+ async getEarningsForUserForDay(date) {
731
+ this.canL2Auth();
732
+ const endpoint = GET_EARNINGS_FOR_USER_FOR_DAY;
733
+ const headerArgs = {
734
+ method: GET,
735
+ requestPath: endpoint
736
+ };
737
+ const headers = await createL2Headers(this.signer, this.creds, headerArgs, this.useServerTime ? await this.getServerTime() : void 0);
738
+ let results = [];
739
+ let next_cursor = INITIAL_CURSOR;
740
+ while (next_cursor !== END_CURSOR) {
741
+ const params = {
742
+ date,
743
+ signature_type: this.orderBuilder.signatureType,
744
+ next_cursor
745
+ };
746
+ const response = await this.get(`${this.host}${endpoint}`, {
747
+ headers,
748
+ params
749
+ });
750
+ next_cursor = response.next_cursor;
751
+ results = [...results, ...response.data];
752
+ }
753
+ return results;
754
+ }
755
+ async getTotalEarningsForUserForDay(date) {
756
+ this.canL2Auth();
757
+ const endpoint = GET_TOTAL_EARNINGS_FOR_USER_FOR_DAY;
758
+ const headerArgs = {
759
+ method: GET,
760
+ requestPath: endpoint
761
+ };
762
+ const headers = await createL2Headers(this.signer, this.creds, headerArgs, this.useServerTime ? await this.getServerTime() : void 0);
763
+ const params = {
764
+ date,
765
+ signature_type: this.orderBuilder.signatureType
766
+ };
767
+ return await this.get(`${this.host}${endpoint}`, {
768
+ headers,
769
+ params
770
+ });
771
+ }
772
+ async getUserEarningsAndMarketsConfig(date, order_by = "", position = "", no_competition = false) {
773
+ this.canL2Auth();
774
+ const endpoint = GET_REWARDS_EARNINGS_PERCENTAGES;
775
+ const headerArgs = {
776
+ method: GET,
777
+ requestPath: endpoint
778
+ };
779
+ const headers = await createL2Headers(this.signer, this.creds, headerArgs, this.useServerTime ? await this.getServerTime() : void 0);
780
+ let results = [];
781
+ let next_cursor = INITIAL_CURSOR;
782
+ while (next_cursor !== END_CURSOR) {
783
+ const params = {
784
+ date,
785
+ signature_type: this.orderBuilder.signatureType,
786
+ next_cursor,
787
+ order_by,
788
+ position,
789
+ no_competition
790
+ };
791
+ const response = await this.get(`${this.host}${endpoint}`, {
792
+ headers,
793
+ params
794
+ });
795
+ next_cursor = response.next_cursor;
796
+ results = [...results, ...response.data];
797
+ }
798
+ return results;
799
+ }
800
+ async getRewardPercentages() {
801
+ this.canL2Auth();
802
+ const endpoint = GET_LIQUIDITY_REWARD_PERCENTAGES;
803
+ const headerArgs = {
804
+ method: GET,
805
+ requestPath: endpoint
806
+ };
807
+ const headers = await createL2Headers(this.signer, this.creds, headerArgs, this.useServerTime ? await this.getServerTime() : void 0);
808
+ const _params = { signature_type: this.orderBuilder.signatureType };
809
+ return this.get(`${this.host}${endpoint}`, {
810
+ headers,
811
+ params: _params
812
+ });
813
+ }
814
+ async getCurrentRewards() {
815
+ let results = [];
816
+ let next_cursor = INITIAL_CURSOR;
817
+ while (next_cursor !== END_CURSOR) {
818
+ const response = await this.get(`${this.host}${GET_REWARDS_MARKETS_CURRENT}`, { params: { next_cursor } });
819
+ next_cursor = response.next_cursor;
820
+ results = [...results, ...response.data];
821
+ }
822
+ return results;
823
+ }
824
+ async getRawRewardsForMarket(conditionId) {
825
+ let results = [];
826
+ let next_cursor = INITIAL_CURSOR;
827
+ while (next_cursor !== END_CURSOR) {
828
+ const response = await this.get(`${this.host}${GET_REWARDS_MARKETS}${conditionId}`, { params: { next_cursor } });
829
+ next_cursor = response.next_cursor;
830
+ results = [...results, ...response.data];
831
+ }
832
+ return results;
833
+ }
834
+ async calculateMarketPrice(tokenID, side, amount, orderType = OrderType.FOK) {
835
+ const book = await this.getOrderBook(tokenID);
836
+ if (!book)
837
+ throw new Error("no orderbook");
838
+ if (side === Side.BUY) {
839
+ if (!book.asks)
840
+ throw new Error("no match");
841
+ return calculateBuyMarketPrice(book.asks, amount, orderType);
842
+ }
843
+ else {
844
+ if (!book.bids)
845
+ throw new Error("no match");
846
+ return calculateSellMarketPrice(book.bids, amount, orderType);
847
+ }
848
+ }
849
+ async createBuilderApiKey() {
850
+ this.canL2Auth();
851
+ const endpoint = CREATE_BUILDER_API_KEY;
852
+ const headerArgs = {
853
+ method: POST,
854
+ requestPath: endpoint
855
+ };
856
+ const headers = await createL2Headers(this.signer, this.creds, headerArgs, this.useServerTime ? await this.getServerTime() : void 0);
857
+ return this.post(`${this.host}${endpoint}`, { headers });
858
+ }
859
+ async getBuilderApiKeys() {
860
+ this.canL2Auth();
861
+ const endpoint = GET_BUILDER_API_KEYS;
862
+ const headerArgs = {
863
+ method: GET,
864
+ requestPath: endpoint
865
+ };
866
+ const headers = await createL2Headers(this.signer, this.creds, headerArgs, this.useServerTime ? await this.getServerTime() : void 0);
867
+ return this.get(`${this.host}${endpoint}`, { headers });
868
+ }
869
+ async revokeBuilderApiKey() {
870
+ this.canL2Auth();
871
+ const endpoint = REVOKE_BUILDER_API_KEY;
872
+ const headerArgs = {
873
+ method: DELETE,
874
+ requestPath: endpoint
875
+ };
876
+ const headers = await createL2Headers(this.signer, this.creds, headerArgs, this.useServerTime ? await this.getServerTime() : void 0);
877
+ return this.del(`${this.host}${endpoint}`, { headers });
878
+ }
879
+ async getMarketTradesEvents(conditionID) {
880
+ return this.get(`${this.host}${GET_MARKET_TRADES_EVENTS}${conditionID}`);
881
+ }
882
+ canL1Auth() {
883
+ if (this.signer === void 0)
884
+ throw L1_AUTH_UNAVAILABLE_ERROR;
885
+ }
886
+ canL2Auth() {
887
+ if (this.signer === void 0)
888
+ throw L1_AUTH_UNAVAILABLE_ERROR;
889
+ if (this.creds === void 0)
890
+ throw L2_AUTH_NOT_AVAILABLE;
891
+ }
892
+ isBuilderOrder(builderCode) {
893
+ return builderCode !== void 0 && builderCode !== bytes32Zero;
894
+ }
895
+ async getBuilderTakerFeeRate(builderCode) {
896
+ if (!this.isBuilderOrder(builderCode))
897
+ return 0;
898
+ await this.ensureBuilderFeeRateCached(builderCode);
899
+ return this.builderFeeRates[builderCode ?? ""]?.taker ?? 0;
900
+ }
901
+ async adjustBuyAmountForBalance(tokenID, amount, price, userUSDCBalance, builderCode) {
902
+ await this._ensureMarketInfoCached(tokenID);
903
+ const builderTakerFeeRate = await this.getBuilderTakerFeeRate(builderCode);
904
+ return adjustBuyAmountForFees(amount, price, userUSDCBalance, this.feeInfos[tokenID].rate, this.feeInfos[tokenID].exponent, builderTakerFeeRate, this.feeSlippage);
905
+ }
906
+ async _ensureMarketInfoCached(tokenID) {
907
+ if (tokenID in this.feeInfos)
908
+ return;
909
+ if (!(tokenID in this.tokenConditionMap)) {
910
+ const result = await this.get(`${this.host}${GET_MARKET_BY_TOKEN}${tokenID}`);
911
+ if (!result?.condition_id)
912
+ throw new Error(`failed to resolve condition id for token ${tokenID}`);
913
+ this.tokenConditionMap[tokenID] = result.condition_id;
914
+ }
915
+ await this.getClobMarketInfo(this.tokenConditionMap[tokenID]);
916
+ }
917
+ async ensureBuilderFeeRateCached(builderCode) {
918
+ if (!builderCode || builderCode === bytes32Zero)
919
+ return;
920
+ if (builderCode in this.builderFeeRates)
921
+ return;
922
+ const result = await this.get(`${this.host}${GET_BUILDER_FEES}${builderCode}`);
923
+ this.builderFeeRates[builderCode] = {
924
+ maker: result.builder_maker_fee_rate_bps / BUILDER_FEES_BPS,
925
+ taker: result.builder_taker_fee_rate_bps / BUILDER_FEES_BPS
926
+ };
927
+ }
928
+ async _resolveTickSize(tokenID, tickSize) {
929
+ const minTickSize = await this.getTickSize(tokenID);
930
+ if (tickSize) {
931
+ if (isTickSizeSmaller(tickSize, minTickSize))
932
+ throw new Error(`invalid tick size (${tickSize}), minimum for the market is ${minTickSize}`);
933
+ }
934
+ else
935
+ tickSize = minTickSize;
936
+ return tickSize;
937
+ }
938
+ async _resolveFeeRateBps(tokenID, userFeeRateBps) {
939
+ const marketFeeRateBps = await this.getFeeRateBps(tokenID);
940
+ if (marketFeeRateBps > 0 && userFeeRateBps !== void 0 && userFeeRateBps !== marketFeeRateBps)
941
+ throw new Error(`invalid user provided fee rate: ${userFeeRateBps}, fee rate for the market must be ${marketFeeRateBps}`);
942
+ return marketFeeRateBps;
943
+ }
944
+ async resolveVersion(forceUpdate = false) {
945
+ if (!forceUpdate && this.cachedVersion !== void 0)
946
+ return this.cachedVersion;
947
+ const apiVersion = await this.getVersion();
948
+ this.cachedVersion = apiVersion;
949
+ return apiVersion;
950
+ }
951
+ async _retryOnVersionUpdate(retryFunc) {
952
+ const version = await this.resolveVersion();
953
+ for (let attempt = 0; attempt < 2; attempt++) {
954
+ await retryFunc();
955
+ if (version === await this.resolveVersion())
956
+ break;
957
+ }
958
+ }
959
+ _isOrderVersionMismatch(resp) {
960
+ const error = resp?.error;
961
+ if (!error)
962
+ return false;
963
+ return (typeof error === "string" ? error : JSON.stringify(error)).includes(ORDER_VERSION_MISMATCH_ERROR);
964
+ }
965
+ throwIfError(result) {
966
+ if (this.throwOnError && result && typeof result === "object" && "error" in result)
967
+ throw new ApiError(typeof result.error === "string" ? result.error : JSON.stringify(result.error), result.status, result);
968
+ return result;
969
+ }
970
+ async get(endpoint, options, skipThrow = false) {
971
+ const result = await get(endpoint, options);
972
+ return skipThrow ? result : this.throwIfError(result);
973
+ }
974
+ async post(endpoint, options, skipThrow = false) {
975
+ const result = await post(endpoint, options, this.retryOnError);
976
+ return skipThrow ? result : this.throwIfError(result);
977
+ }
978
+ async del(endpoint, options, skipThrow = false) {
979
+ const result = await del(endpoint, options);
980
+ return skipThrow ? result : this.throwIfError(result);
981
+ }
982
+ };
983
+ //#endregion
984
+ export { ClobClient };
985
+ //# sourceMappingURL=client.js.map