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