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