@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/index.js CHANGED
@@ -1,8 +1,2438 @@
1
- export * from "./client.js";
2
- export * from "./config.js";
3
- export * from "./headers/index.js";
4
- export * from "./order-builder/index.js";
5
- export * from "./order-utils/model/signatureTypeV1.js";
6
- export * from "./order-utils/model/signatureTypeV2.js";
7
- export * from "./types/index.js";
1
+ // src/constants.ts
2
+ var INITIAL_CURSOR = "MA==";
3
+ var END_CURSOR = "LTE=";
4
+ var bytes32Zero = "0x0000000000000000000000000000000000000000000000000000000000000000";
5
+ var ORDER_VERSION_MISMATCH_ERROR = "order_version_mismatch";
6
+ var BUILDER_FEES_BPS = 1e4;
7
+
8
+ // src/endpoints.ts
9
+ var OK = "/ok";
10
+ var HEARTBEAT = "/v1/heartbeats";
11
+ var TIME = "/time";
12
+ var CREATE_API_KEY = "/auth/api-key";
13
+ var GET_API_KEYS = "/auth/api-keys";
14
+ var DELETE_API_KEY = "/auth/api-key";
15
+ var DERIVE_API_KEY = "/auth/derive-api-key";
16
+ var CLOSED_ONLY = "/auth/ban-status/closed-only";
17
+ var GET_SAMPLING_SIMPLIFIED_MARKETS = "/sampling-simplified-markets";
18
+ var GET_SAMPLING_MARKETS = "/sampling-markets";
19
+ var GET_SIMPLIFIED_MARKETS = "/simplified-markets";
20
+ var GET_MARKETS = "/markets";
21
+ var GET_MARKET = "/markets/";
22
+ var GET_MARKET_BY_TOKEN = "/markets-by-token/";
23
+ var GET_CLOB_MARKET = "/clob-markets/";
24
+ var GET_ORDER_BOOK = "/book";
25
+ var GET_ORDER_BOOKS = "/books";
26
+ var GET_MIDPOINT = "/midpoint";
27
+ var GET_MIDPOINTS = "/midpoints";
28
+ var GET_PRICE = "/price";
29
+ var GET_PRICES = "/prices";
30
+ var GET_SPREAD = "/spread";
31
+ var GET_SPREADS = "/spreads";
32
+ var GET_LAST_TRADE_PRICE = "/last-trade-price";
33
+ var GET_LAST_TRADES_PRICES = "/last-trades-prices";
34
+ var GET_TICK_SIZE = "/tick-size";
35
+ var GET_NEG_RISK = "/neg-risk";
36
+ var GET_FEE_RATE = "/fee-rate";
37
+ var POST_ORDER = "/order";
38
+ var POST_ORDERS = "/orders";
39
+ var CANCEL_ORDER = "/order";
40
+ var CANCEL_ORDERS = "/orders";
41
+ var GET_ORDER = "/data/order/";
42
+ var CANCEL_ALL = "/cancel-all";
43
+ var CANCEL_MARKET_ORDERS = "/cancel-market-orders";
44
+ var GET_OPEN_ORDERS = "/data/orders";
45
+ var GET_PRE_MIGRATION_ORDERS = "/data/pre-migration-orders";
46
+ var GET_TRADES = "/data/trades";
47
+ var IS_ORDER_SCORING = "/order-scoring";
48
+ var ARE_ORDERS_SCORING = "/orders-scoring";
49
+ var GET_PRICES_HISTORY = "/prices-history";
50
+ var GET_NOTIFICATIONS = "/notifications";
51
+ var DROP_NOTIFICATIONS = "/notifications";
52
+ var GET_BALANCE_ALLOWANCE = "/balance-allowance";
53
+ var UPDATE_BALANCE_ALLOWANCE = "/balance-allowance/update";
54
+ var GET_EARNINGS_FOR_USER_FOR_DAY = "/rewards/user";
55
+ var GET_TOTAL_EARNINGS_FOR_USER_FOR_DAY = "/rewards/user/total";
56
+ var GET_LIQUIDITY_REWARD_PERCENTAGES = "/rewards/user/percentages";
57
+ var GET_REWARDS_MARKETS_CURRENT = "/rewards/markets/current";
58
+ var GET_REWARDS_MARKETS = "/rewards/markets/";
59
+ var GET_REWARDS_EARNINGS_PERCENTAGES = "/rewards/user/markets";
60
+ var CREATE_READONLY_API_KEY = "/auth/readonly-api-key";
61
+ var GET_READONLY_API_KEYS = "/auth/readonly-api-keys";
62
+ var DELETE_READONLY_API_KEY = "/auth/readonly-api-key";
63
+ var CREATE_BUILDER_API_KEY = "/auth/builder-api-key";
64
+ var GET_BUILDER_API_KEYS = "/auth/builder-api-key";
65
+ var REVOKE_BUILDER_API_KEY = "/auth/builder-api-key";
66
+ var GET_MARKET_TRADES_EVENTS = "/markets/live-activity/";
67
+ var GET_BUILDER_TRADES = "/builder/trades";
68
+ var GET_BUILDER_FEES = "/fees/builder-fees/";
69
+
70
+ // src/errors.ts
71
+ var L1_AUTH_UNAVAILABLE_ERROR = new Error(
72
+ "Signer is needed to interact with this endpoint!"
73
+ );
74
+ var L2_AUTH_NOT_AVAILABLE = new Error(
75
+ "API Credentials are needed to interact with this endpoint!"
76
+ );
77
+ var ApiError = class extends Error {
78
+ status;
79
+ data;
80
+ constructor(message, status, data) {
81
+ super(message);
82
+ this.name = "ApiError";
83
+ this.status = status;
84
+ this.data = data;
85
+ }
86
+ };
87
+
88
+ // src/signing/constants.ts
89
+ var MSG_TO_SIGN = "This message attests that I control the given wallet";
90
+
91
+ // src/signing/signer.ts
92
+ var isEthersTypedDataSigner = (signer) => (
93
+ // eslint-disable-next-line no-underscore-dangle
94
+ typeof signer._signTypedData === "function"
95
+ );
96
+ var isWalletClientSigner = (signer) => typeof signer.signTypedData === "function";
97
+ var getWalletClientAddress = async (walletClient) => {
98
+ const accountAddress = walletClient.account?.address;
99
+ if (typeof accountAddress === "string" && accountAddress.length > 0) {
100
+ return accountAddress;
101
+ }
102
+ if (typeof walletClient.requestAddresses === "function") {
103
+ const [address] = await walletClient.requestAddresses();
104
+ if (typeof address === "string" && address.length > 0) {
105
+ return address;
106
+ }
107
+ }
108
+ if (typeof walletClient.getAddresses === "function") {
109
+ const [address] = await walletClient.getAddresses();
110
+ if (typeof address === "string" && address.length > 0) {
111
+ return address;
112
+ }
113
+ }
114
+ throw new Error("wallet client is missing account address");
115
+ };
116
+ var getSignerAddress = async (signer) => {
117
+ if (isEthersTypedDataSigner(signer)) {
118
+ return signer.getAddress();
119
+ }
120
+ if (isWalletClientSigner(signer)) {
121
+ return getWalletClientAddress(signer);
122
+ }
123
+ throw new Error("unsupported signer type");
124
+ };
125
+ var signTypedDataWithSigner = async ({
126
+ signer,
127
+ domain,
128
+ types,
129
+ value,
130
+ primaryType
131
+ }) => {
132
+ if (isEthersTypedDataSigner(signer)) {
133
+ return signer._signTypedData(domain, types, value);
134
+ }
135
+ if (isWalletClientSigner(signer)) {
136
+ const account = signer.account ?? await getWalletClientAddress(signer);
137
+ return signer.signTypedData({
138
+ account,
139
+ domain,
140
+ types,
141
+ primaryType,
142
+ message: value
143
+ });
144
+ }
145
+ throw new Error("unsupported signer type");
146
+ };
147
+
148
+ // src/signing/eip712.ts
149
+ var buildClobEip712Signature = async (signer, chainId, timestamp, nonce) => {
150
+ const address = await getSignerAddress(signer);
151
+ const ts = timestamp.toString();
152
+ const domain = {
153
+ name: "ClobAuthDomain",
154
+ version: "1",
155
+ chainId
156
+ };
157
+ const types = {
158
+ ClobAuth: [
159
+ { name: "address", type: "address" },
160
+ { name: "timestamp", type: "string" },
161
+ { name: "nonce", type: "uint256" },
162
+ { name: "message", type: "string" }
163
+ ]
164
+ };
165
+ const value = {
166
+ address,
167
+ timestamp: ts,
168
+ nonce,
169
+ message: MSG_TO_SIGN
170
+ };
171
+ const sig = await signTypedDataWithSigner({
172
+ signer,
173
+ domain,
174
+ types,
175
+ value,
176
+ primaryType: "ClobAuth"
177
+ });
178
+ return sig;
179
+ };
180
+
181
+ // src/signing/hmac.ts
182
+ import crypto from "crypto";
183
+ function replaceAll(s, search, replace) {
184
+ return s.split(search).join(replace);
185
+ }
186
+ var buildPolyHmacSignature = (secret, timestamp, method, requestPath, body) => {
187
+ let message = timestamp + method + requestPath;
188
+ if (body !== void 0) {
189
+ message += body;
190
+ }
191
+ const base64Secret = Buffer.from(secret, "base64");
192
+ const hmac = crypto.createHmac("sha256", base64Secret);
193
+ const sig = hmac.update(message).digest("base64");
194
+ const sigUrlSafe = replaceAll(replaceAll(sig, "+", "-"), "/", "_");
195
+ return sigUrlSafe;
196
+ };
197
+
198
+ // src/headers/index.ts
199
+ var createL1Headers = async (signer, chainId, nonce, timestamp) => {
200
+ let ts = Math.floor(Date.now() / 1e3);
201
+ if (timestamp !== void 0) {
202
+ ts = timestamp;
203
+ }
204
+ let n = 0;
205
+ if (nonce !== void 0) {
206
+ n = nonce;
207
+ }
208
+ const sig = await buildClobEip712Signature(signer, chainId, ts, n);
209
+ const address = await getSignerAddress(signer);
210
+ const headers = {
211
+ POLY_ADDRESS: address,
212
+ POLY_SIGNATURE: sig,
213
+ POLY_TIMESTAMP: `${ts}`,
214
+ POLY_NONCE: `${n}`
215
+ };
216
+ return headers;
217
+ };
218
+ var createL2Headers = async (signer, creds, l2HeaderArgs, timestamp) => {
219
+ let ts = Math.floor(Date.now() / 1e3);
220
+ if (timestamp !== void 0) {
221
+ ts = timestamp;
222
+ }
223
+ const address = await getSignerAddress(signer);
224
+ const sig = buildPolyHmacSignature(
225
+ creds.secret,
226
+ ts,
227
+ l2HeaderArgs.method,
228
+ l2HeaderArgs.requestPath,
229
+ l2HeaderArgs.body
230
+ );
231
+ const headers = {
232
+ POLY_ADDRESS: address,
233
+ POLY_SIGNATURE: sig,
234
+ POLY_TIMESTAMP: `${ts}`,
235
+ POLY_API_KEY: creds.key,
236
+ POLY_PASSPHRASE: creds.passphrase
237
+ };
238
+ return headers;
239
+ };
240
+
241
+ // src/http-helpers/index.ts
242
+ import axios from "axios";
243
+ import { isBrowser } from "browser-or-node";
244
+ var GET = "GET";
245
+ var POST = "POST";
246
+ var DELETE = "DELETE";
247
+ var overloadHeaders = (method, headers = {}) => {
248
+ if (isBrowser) {
249
+ return;
250
+ }
251
+ headers["User-Agent"] = `@polymarket/clob-client`;
252
+ headers.Accept = "*/*";
253
+ headers.Connection = "keep-alive";
254
+ headers["Content-Type"] = "application/json";
255
+ if (method === GET) {
256
+ headers["Accept-Encoding"] = "gzip";
257
+ }
258
+ };
259
+ var request = async (endpoint, method, headers, data, params) => {
260
+ overloadHeaders(method, headers);
261
+ return await axios({ method, url: endpoint, headers, data, params });
262
+ };
263
+ var sleep = (ms) => new Promise((res) => setTimeout(res, ms));
264
+ var post = async (endpoint, options, retryOnError = false) => {
265
+ try {
266
+ const resp = await request(
267
+ endpoint,
268
+ POST,
269
+ options?.headers,
270
+ options?.data,
271
+ options?.params
272
+ );
273
+ return resp.data;
274
+ } catch (err) {
275
+ if (retryOnError && isTransientAxiosError(err)) {
276
+ console.log("[CLOB Client-v2] transient error, retrying once after 30 ms");
277
+ await sleep(30);
278
+ try {
279
+ const resp = await request(
280
+ endpoint,
281
+ POST,
282
+ options?.headers,
283
+ options?.data,
284
+ options?.params
285
+ );
286
+ return resp.data;
287
+ } catch (retryErr) {
288
+ return errorHandling(retryErr);
289
+ }
290
+ }
291
+ return errorHandling(err);
292
+ }
293
+ };
294
+ var get = async (endpoint, options) => {
295
+ try {
296
+ const resp = await request(endpoint, GET, options?.headers, options?.data, options?.params);
297
+ return resp.data;
298
+ } catch (err) {
299
+ return errorHandling(err);
300
+ }
301
+ };
302
+ var del = async (endpoint, options) => {
303
+ try {
304
+ const resp = await request(
305
+ endpoint,
306
+ DELETE,
307
+ options?.headers,
308
+ options?.data,
309
+ options?.params
310
+ );
311
+ return resp.data;
312
+ } catch (err) {
313
+ return errorHandling(err);
314
+ }
315
+ };
316
+ var errorHandling = (err) => {
317
+ if (axios.isAxiosError(err)) {
318
+ if (err.response) {
319
+ console.error(
320
+ "[CLOB Client] request error",
321
+ JSON.stringify({
322
+ status: err.response?.status,
323
+ statusText: err.response?.statusText,
324
+ data: err.response?.data,
325
+ config: err.response?.config
326
+ })
327
+ );
328
+ if (err.response?.data) {
329
+ if (typeof err.response?.data === "string" || err.response?.data instanceof String) {
330
+ return { error: err.response?.data, status: err.response?.status };
331
+ }
332
+ if (!Object.prototype.hasOwnProperty.call(err.response?.data, "error")) {
333
+ return { error: err.response?.data, status: err.response?.status };
334
+ }
335
+ return { ...err.response?.data, status: err.response?.status };
336
+ }
337
+ }
338
+ if (err.message) {
339
+ console.error(
340
+ "[CLOB Client] request error",
341
+ JSON.stringify({
342
+ error: err.message
343
+ })
344
+ );
345
+ return { error: err.message };
346
+ }
347
+ }
348
+ console.error("[CLOB Client] request error", err);
349
+ return { error: err };
350
+ };
351
+ var isTransientAxiosError = (err) => {
352
+ if (!axios.isAxiosError(err)) return false;
353
+ if (!err.response) return true;
354
+ const status = err.response.status ?? 0;
355
+ if (status >= 500 && status < 600) return true;
356
+ const code = (err.code ?? "").toString();
357
+ return ["ECONNABORTED", "ENETUNREACH", "EAI_AGAIN", "ETIMEDOUT"].includes(code);
358
+ };
359
+ var parseDropNotificationParams = (dropNotificationParams) => {
360
+ const params = {};
361
+ if (dropNotificationParams !== void 0) {
362
+ if (dropNotificationParams.ids !== void 0) {
363
+ params.ids = dropNotificationParams?.ids.join(",");
364
+ }
365
+ }
366
+ return params;
367
+ };
368
+
369
+ // src/order-builder/helpers/buildMarketOrderCreationArgs.ts
370
+ import { parseUnits, zeroAddress } from "viem";
371
+
372
+ // src/config.ts
373
+ var AMOY_CONTRACTS = {
374
+ exchange: "0xdFE02Eb6733538f8Ea35D585af8DE5958AD99E40",
375
+ negRiskAdapter: "0xd91E80cF2E7be2e162c6513ceD06f1dD0dA35296",
376
+ negRiskExchange: "0xC5d563A36AE78145C45a50134d48A1215220f80a",
377
+ collateral: "0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB",
378
+ conditionalTokens: "0x69308FB512518e39F9b16112fA8d994F4e2Bf8bB",
379
+ exchangeV2: "0xE111180000d2663C0091e4f400237545B87B996B",
380
+ negRiskExchangeV2: "0xe2222d279d744050d28e00520010520000310F59"
381
+ };
382
+ var MATIC_CONTRACTS = {
383
+ exchange: "0x4bFb41d5B3570DeFd03C39a9A4D8dE6Bd8B8982E",
384
+ negRiskAdapter: "0xd91E80cF2E7be2e162c6513ceD06f1dD0dA35296",
385
+ negRiskExchange: "0xC5d563A36AE78145C45a50134d48A1215220f80a",
386
+ collateral: "0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB",
387
+ conditionalTokens: "0x4D97DCd97eC945f40cF65F87097ACe5EA0476045",
388
+ exchangeV2: "0xE111180000d2663C0091e4f400237545B87B996B",
389
+ negRiskExchangeV2: "0xe2222d279d744050d28e00520010520000310F59"
390
+ };
391
+ var COLLATERAL_TOKEN_DECIMALS = 6;
392
+ var CONDITIONAL_TOKEN_DECIMALS = 6;
393
+ var getContractConfig = (chainID) => {
394
+ switch (chainID) {
395
+ case 137:
396
+ return MATIC_CONTRACTS;
397
+ case 80002:
398
+ return AMOY_CONTRACTS;
399
+ default:
400
+ throw new Error("Invalid network");
401
+ }
402
+ };
403
+
404
+ // src/order-builder/helpers/buildMarketOrderCreationArgs.ts
405
+ async function buildMarketOrderCreationArgs(signer, maker, signatureType, userMarketOrder, roundConfig, version = 2) {
406
+ const { side, rawMakerAmt, rawTakerAmt } = getMarketOrderRawAmounts(
407
+ userMarketOrder.side,
408
+ userMarketOrder.amount,
409
+ userMarketOrder.price || 1,
410
+ roundConfig
411
+ );
412
+ const makerAmount = parseUnits(rawMakerAmt.toString(), COLLATERAL_TOKEN_DECIMALS).toString();
413
+ const takerAmount = parseUnits(rawTakerAmt.toString(), COLLATERAL_TOKEN_DECIMALS).toString();
414
+ if (version === 1) {
415
+ const v1Order = userMarketOrder;
416
+ return {
417
+ maker,
418
+ taker: v1Order.taker ?? zeroAddress,
419
+ tokenId: userMarketOrder.tokenID,
420
+ makerAmount,
421
+ takerAmount,
422
+ side,
423
+ signer,
424
+ signatureType,
425
+ feeRateBps: v1Order.feeRateBps?.toString() ?? "0",
426
+ nonce: v1Order.nonce?.toString() ?? "0"
427
+ };
428
+ }
429
+ return {
430
+ maker,
431
+ tokenId: userMarketOrder.tokenID,
432
+ makerAmount,
433
+ takerAmount,
434
+ side,
435
+ signer,
436
+ signatureType,
437
+ timestamp: Date.now().toString(),
438
+ metadata: "metadata" in userMarketOrder ? userMarketOrder.metadata ?? bytes32Zero : bytes32Zero,
439
+ builder: userMarketOrder.builderCode ?? bytes32Zero
440
+ };
441
+ }
442
+
443
+ // src/order-utils/exchangeOrderBuilderV1.ts
444
+ import { hashTypedData } from "viem";
445
+
446
+ // src/order-utils/model/ctfExchangeV1TypedData.ts
447
+ var CTF_EXCHANGE_V1_DOMAIN_NAME = "Polymarket CTF Exchange";
448
+ var CTF_EXCHANGE_V1_DOMAIN_VERSION = "1";
449
+ var CTF_EXCHANGE_V1_ORDER_STRUCT = [
450
+ { name: "salt", type: "uint256" },
451
+ { name: "maker", type: "address" },
452
+ { name: "signer", type: "address" },
453
+ { name: "taker", type: "address" },
454
+ { name: "tokenId", type: "uint256" },
455
+ { name: "makerAmount", type: "uint256" },
456
+ { name: "takerAmount", type: "uint256" },
457
+ { name: "expiration", type: "uint256" },
458
+ { name: "nonce", type: "uint256" },
459
+ { name: "feeRateBps", type: "uint256" },
460
+ { name: "side", type: "uint8" },
461
+ { name: "signatureType", type: "uint8" }
462
+ ];
463
+
464
+ // src/order-utils/model/eip712.ts
465
+ var EIP712_DOMAIN = [
466
+ { name: "name", type: "string" },
467
+ { name: "version", type: "string" },
468
+ { name: "chainId", type: "uint256" },
469
+ { name: "verifyingContract", type: "address" }
470
+ ];
471
+
472
+ // src/order-utils/model/signatureTypeV1.ts
473
+ var SignatureTypeV1 = /* @__PURE__ */ ((SignatureTypeV12) => {
474
+ SignatureTypeV12[SignatureTypeV12["EOA"] = 0] = "EOA";
475
+ SignatureTypeV12[SignatureTypeV12["POLY_PROXY"] = 1] = "POLY_PROXY";
476
+ SignatureTypeV12[SignatureTypeV12["POLY_GNOSIS_SAFE"] = 2] = "POLY_GNOSIS_SAFE";
477
+ return SignatureTypeV12;
478
+ })(SignatureTypeV1 || {});
479
+
480
+ // src/order-utils/utils.ts
481
+ function generateOrderSalt() {
482
+ return `${Math.round(Math.random() * Date.now())}`;
483
+ }
484
+
485
+ // src/order-utils/exchangeOrderBuilderV1.ts
486
+ var ZERO_ADDRESS = "0x0000000000000000000000000000000000000000";
487
+ var ExchangeOrderBuilderV1 = class {
488
+ constructor(contractAddress, chainId, signer, generateSalt = generateOrderSalt) {
489
+ this.contractAddress = contractAddress;
490
+ this.chainId = chainId;
491
+ this.signer = signer;
492
+ this.generateSalt = generateSalt;
493
+ }
494
+ contractAddress;
495
+ chainId;
496
+ signer;
497
+ generateSalt;
498
+ /**
499
+ * build an order object including the signature.
500
+ * @param orderData
501
+ * @returns a SignedOrder object (order + signature)
502
+ */
503
+ async buildSignedOrder(orderData) {
504
+ const order = await this.buildOrder(orderData);
505
+ const orderTypedData = this.buildOrderTypedData(order);
506
+ const orderSignature = await this.buildOrderSignature(orderTypedData);
507
+ return {
508
+ ...order,
509
+ signature: orderSignature
510
+ };
511
+ }
512
+ /**
513
+ * Creates an Order object from order data.
514
+ * @param OrderData
515
+ * @returns a Order object (not signed)
516
+ */
517
+ async buildOrder({
518
+ maker,
519
+ taker,
520
+ tokenId,
521
+ makerAmount,
522
+ takerAmount,
523
+ side,
524
+ feeRateBps,
525
+ nonce,
526
+ signer,
527
+ expiration,
528
+ signatureType
529
+ }) {
530
+ if (!signer) {
531
+ signer = maker;
532
+ }
533
+ const signerAddress = await getSignerAddress(this.signer);
534
+ if (signer !== signerAddress) {
535
+ throw new Error("signer does not match");
536
+ }
537
+ if (!expiration) {
538
+ expiration = "0";
539
+ }
540
+ if (!signatureType) {
541
+ signatureType = 0 /* EOA */;
542
+ }
543
+ let takerAddress;
544
+ if (typeof taker !== "undefined" && taker) {
545
+ takerAddress = taker;
546
+ } else {
547
+ takerAddress = ZERO_ADDRESS;
548
+ }
549
+ let feeRateBpsResolved;
550
+ if (typeof feeRateBps !== "undefined" && feeRateBps) {
551
+ feeRateBpsResolved = feeRateBps.toString();
552
+ } else {
553
+ feeRateBpsResolved = "0";
554
+ }
555
+ let nonceResolved;
556
+ if (typeof nonce !== "undefined" && nonce) {
557
+ nonceResolved = nonce.toString();
558
+ } else {
559
+ nonceResolved = "0";
560
+ }
561
+ return {
562
+ salt: this.generateSalt(),
563
+ maker,
564
+ signer,
565
+ taker: takerAddress,
566
+ tokenId,
567
+ makerAmount,
568
+ takerAmount,
569
+ expiration,
570
+ nonce: nonceResolved,
571
+ feeRateBps: feeRateBpsResolved,
572
+ side,
573
+ signatureType
574
+ };
575
+ }
576
+ /**
577
+ * Parses an Order object to EIP712 typed data
578
+ * @param order
579
+ * @returns a EIP712TypedData object
580
+ */
581
+ buildOrderTypedData(order) {
582
+ return {
583
+ primaryType: "Order",
584
+ types: {
585
+ EIP712Domain: EIP712_DOMAIN,
586
+ Order: CTF_EXCHANGE_V1_ORDER_STRUCT
587
+ },
588
+ domain: {
589
+ name: CTF_EXCHANGE_V1_DOMAIN_NAME,
590
+ version: CTF_EXCHANGE_V1_DOMAIN_VERSION,
591
+ chainId: this.chainId,
592
+ verifyingContract: this.contractAddress
593
+ },
594
+ message: {
595
+ salt: order.salt,
596
+ maker: order.maker,
597
+ signer: order.signer,
598
+ taker: order.taker,
599
+ tokenId: order.tokenId,
600
+ makerAmount: order.makerAmount,
601
+ takerAmount: order.takerAmount,
602
+ expiration: order.expiration,
603
+ nonce: order.nonce,
604
+ feeRateBps: order.feeRateBps,
605
+ side: order.side === "BUY" ? 0 : 1,
606
+ signatureType: order.signatureType
607
+ }
608
+ };
609
+ }
610
+ /**
611
+ * Generates order's signature from a EIP712TypedData object + the signer address
612
+ * @param typedData
613
+ * @returns a OrderSignature that is an string
614
+ */
615
+ buildOrderSignature(typedData) {
616
+ delete typedData.types.EIP712Domain;
617
+ return signTypedDataWithSigner({
618
+ signer: this.signer,
619
+ domain: typedData.domain,
620
+ types: typedData.types,
621
+ value: typedData.message,
622
+ primaryType: typedData.primaryType
623
+ });
624
+ }
625
+ /**
626
+ * Generates the hash of the order from a EIP712TypedData object.
627
+ * @param orderTypedData
628
+ * @returns a OrderHash that is an string
629
+ */
630
+ buildOrderHash(orderTypedData) {
631
+ const digest = hashTypedData(orderTypedData);
632
+ return digest;
633
+ }
634
+ };
635
+
636
+ // src/order-utils/exchangeOrderBuilderV2.ts
637
+ import { hashTypedData as hashTypedData2 } from "viem";
638
+
639
+ // src/order-utils/model/ctfExchangeV2TypedData.ts
640
+ var CTF_EXCHANGE_V2_DOMAIN_NAME = "Polymarket CTF Exchange";
641
+ var CTF_EXCHANGE_V2_DOMAIN_VERSION = "2";
642
+ var CTF_EXCHANGE_V2_ORDER_STRUCT = [
643
+ { name: "salt", type: "uint256" },
644
+ { name: "maker", type: "address" },
645
+ { name: "signer", type: "address" },
646
+ { name: "tokenId", type: "uint256" },
647
+ { name: "makerAmount", type: "uint256" },
648
+ { name: "takerAmount", type: "uint256" },
649
+ { name: "side", type: "uint8" },
650
+ { name: "signatureType", type: "uint8" },
651
+ { name: "timestamp", type: "uint256" },
652
+ { name: "metadata", type: "bytes32" },
653
+ { name: "builder", type: "bytes32" }
654
+ ];
655
+
656
+ // src/order-utils/model/signatureTypeV2.ts
657
+ var SignatureTypeV2 = /* @__PURE__ */ ((SignatureTypeV22) => {
658
+ SignatureTypeV22[SignatureTypeV22["EOA"] = 0] = "EOA";
659
+ SignatureTypeV22[SignatureTypeV22["POLY_PROXY"] = 1] = "POLY_PROXY";
660
+ SignatureTypeV22[SignatureTypeV22["POLY_GNOSIS_SAFE"] = 2] = "POLY_GNOSIS_SAFE";
661
+ SignatureTypeV22[SignatureTypeV22["POLY_1271"] = 3] = "POLY_1271";
662
+ return SignatureTypeV22;
663
+ })(SignatureTypeV2 || {});
664
+
665
+ // src/order-utils/exchangeOrderBuilderV2.ts
666
+ var ExchangeOrderBuilderV2 = class {
667
+ constructor(contractAddress, chainId, signer, generateSalt = generateOrderSalt) {
668
+ this.contractAddress = contractAddress;
669
+ this.chainId = chainId;
670
+ this.signer = signer;
671
+ this.generateSalt = generateSalt;
672
+ }
673
+ contractAddress;
674
+ chainId;
675
+ signer;
676
+ generateSalt;
677
+ /**
678
+ * build an order object including the signature.
679
+ * @param orderData
680
+ * @returns a SignedOrder object (order + signature)
681
+ */
682
+ async buildSignedOrder(orderData) {
683
+ const order = await this.buildOrder(orderData);
684
+ const orderTypedData = this.buildOrderTypedData(order);
685
+ const orderSignature = await this.buildOrderSignature(orderTypedData);
686
+ return {
687
+ ...order,
688
+ signature: orderSignature
689
+ };
690
+ }
691
+ /**
692
+ * Creates an Order object from order data.
693
+ * @param OrderData
694
+ * @returns a Order object (not signed)
695
+ */
696
+ async buildOrder({
697
+ maker,
698
+ tokenId,
699
+ makerAmount,
700
+ takerAmount,
701
+ side,
702
+ signer,
703
+ signatureType,
704
+ timestamp,
705
+ metadata,
706
+ builder,
707
+ expiration
708
+ }) {
709
+ if (!signer) {
710
+ signer = maker;
711
+ }
712
+ const signerAddress = await getSignerAddress(this.signer);
713
+ if (signer !== signerAddress) {
714
+ throw new Error("signer does not match");
715
+ }
716
+ return {
717
+ salt: this.generateSalt(),
718
+ maker,
719
+ signer,
720
+ tokenId,
721
+ makerAmount,
722
+ takerAmount,
723
+ side,
724
+ signatureType: signatureType ?? 0 /* EOA */,
725
+ metadata: metadata ?? bytes32Zero,
726
+ builder: builder ?? bytes32Zero,
727
+ timestamp: timestamp ?? Date.now().toString(),
728
+ expiration: expiration ?? "0"
729
+ };
730
+ }
731
+ /**
732
+ * Parses an Order object to EIP712 typed data
733
+ * @param order
734
+ * @returns a EIP712TypedData object
735
+ */
736
+ buildOrderTypedData(order) {
737
+ return {
738
+ primaryType: "Order",
739
+ types: {
740
+ EIP712Domain: EIP712_DOMAIN,
741
+ Order: CTF_EXCHANGE_V2_ORDER_STRUCT
742
+ },
743
+ domain: {
744
+ name: CTF_EXCHANGE_V2_DOMAIN_NAME,
745
+ version: CTF_EXCHANGE_V2_DOMAIN_VERSION,
746
+ chainId: this.chainId,
747
+ verifyingContract: this.contractAddress
748
+ },
749
+ message: {
750
+ salt: order.salt,
751
+ maker: order.maker,
752
+ signer: order.signer,
753
+ tokenId: order.tokenId,
754
+ makerAmount: order.makerAmount,
755
+ takerAmount: order.takerAmount,
756
+ timestamp: order.timestamp,
757
+ side: order.side === "BUY" ? 0 : 1,
758
+ signatureType: order.signatureType,
759
+ metadata: order.metadata,
760
+ builder: order.builder
761
+ }
762
+ };
763
+ }
764
+ /**
765
+ * Generates order's signature from a EIP712TypedData object + the signer address
766
+ * @param typedData
767
+ * @returns a OrderSignature that is an string
768
+ */
769
+ buildOrderSignature(typedData) {
770
+ delete typedData.types.EIP712Domain;
771
+ return signTypedDataWithSigner({
772
+ signer: this.signer,
773
+ domain: typedData.domain,
774
+ types: typedData.types,
775
+ value: typedData.message,
776
+ primaryType: typedData.primaryType
777
+ });
778
+ }
779
+ /**
780
+ * Generates the hash of the order from a EIP712TypedData object.
781
+ * @param orderTypedData
782
+ * @returns a OrderHash that is an string
783
+ */
784
+ buildOrderHash(orderTypedData) {
785
+ const digest = hashTypedData2(orderTypedData);
786
+ return digest;
787
+ }
788
+ };
789
+
790
+ // src/order-builder/helpers/buildOrder.ts
791
+ var buildOrder = async (signer, exchangeAddress, chainId, orderData, version = 2) => {
792
+ switch (version) {
793
+ case 1:
794
+ return buildOrderV1(signer, exchangeAddress, chainId, orderData);
795
+ case 2:
796
+ return buildOrderV2(signer, exchangeAddress, chainId, orderData);
797
+ default:
798
+ throw new Error(`unsupported order version ${version}`);
799
+ }
800
+ };
801
+ var buildOrderV1 = async (signer, exchangeAddress, chainId, orderData) => {
802
+ const ctfExchangeOrderBuilder = new ExchangeOrderBuilderV1(exchangeAddress, chainId, signer);
803
+ return ctfExchangeOrderBuilder.buildSignedOrder(orderData);
804
+ };
805
+ var buildOrderV2 = async (signer, exchangeAddress, chainId, orderData) => {
806
+ const ctfExchangeOrderBuilder = new ExchangeOrderBuilderV2(exchangeAddress, chainId, signer);
807
+ return ctfExchangeOrderBuilder.buildSignedOrder(orderData);
808
+ };
809
+
810
+ // src/order-builder/helpers/buildOrderCreationArgs.ts
811
+ import { parseUnits as parseUnits2, zeroAddress as zeroAddress2 } from "viem";
812
+
813
+ // src/order-utils/model/side.ts
814
+ var Side = /* @__PURE__ */ ((Side2) => {
815
+ Side2["BUY"] = "BUY";
816
+ Side2["SELL"] = "SELL";
817
+ return Side2;
818
+ })(Side || {});
819
+
820
+ // src/types/clob.ts
821
+ var OrderType = /* @__PURE__ */ ((OrderType2) => {
822
+ OrderType2["GTC"] = "GTC";
823
+ OrderType2["FOK"] = "FOK";
824
+ OrderType2["GTD"] = "GTD";
825
+ OrderType2["FAK"] = "FAK";
826
+ return OrderType2;
827
+ })(OrderType || {});
828
+ var Chain = /* @__PURE__ */ ((Chain2) => {
829
+ Chain2[Chain2["POLYGON"] = 137] = "POLYGON";
830
+ Chain2[Chain2["AMOY"] = 80002] = "AMOY";
831
+ return Chain2;
832
+ })(Chain || {});
833
+ var PriceHistoryInterval = /* @__PURE__ */ ((PriceHistoryInterval2) => {
834
+ PriceHistoryInterval2["MAX"] = "max";
835
+ PriceHistoryInterval2["ONE_WEEK"] = "1w";
836
+ PriceHistoryInterval2["ONE_DAY"] = "1d";
837
+ PriceHistoryInterval2["SIX_HOURS"] = "6h";
838
+ PriceHistoryInterval2["ONE_HOUR"] = "1h";
839
+ return PriceHistoryInterval2;
840
+ })(PriceHistoryInterval || {});
841
+ var AssetType = /* @__PURE__ */ ((AssetType2) => {
842
+ AssetType2["COLLATERAL"] = "COLLATERAL";
843
+ AssetType2["CONDITIONAL"] = "CONDITIONAL";
844
+ return AssetType2;
845
+ })(AssetType || {});
846
+
847
+ // src/types/ordersV1.ts
848
+ function orderToJsonV1(order, owner, orderType, postOnly = false, deferExec = false) {
849
+ return {
850
+ deferExec,
851
+ postOnly,
852
+ order: {
853
+ salt: parseInt(order.salt, 10),
854
+ maker: order.maker,
855
+ signer: order.signer,
856
+ taker: order.taker,
857
+ tokenId: order.tokenId,
858
+ makerAmount: order.makerAmount,
859
+ takerAmount: order.takerAmount,
860
+ side: order.side,
861
+ expiration: order.expiration,
862
+ nonce: order.nonce,
863
+ feeRateBps: order.feeRateBps,
864
+ signatureType: order.signatureType,
865
+ signature: order.signature
866
+ },
867
+ owner,
868
+ orderType
869
+ };
870
+ }
871
+
872
+ // src/types/ordersV2.ts
873
+ function orderToJsonV2(order, owner, orderType, postOnly = false, deferExec = false) {
874
+ return {
875
+ deferExec,
876
+ postOnly,
877
+ order: {
878
+ salt: parseInt(order.salt, 10),
879
+ maker: order.maker,
880
+ signer: order.signer,
881
+ taker: order.taker,
882
+ tokenId: order.tokenId,
883
+ makerAmount: order.makerAmount,
884
+ takerAmount: order.takerAmount,
885
+ side: order.side,
886
+ signatureType: order.signatureType,
887
+ timestamp: order.timestamp,
888
+ expiration: order.expiration,
889
+ metadata: order.metadata,
890
+ builder: order.builder,
891
+ signature: order.signature
892
+ },
893
+ owner,
894
+ orderType
895
+ };
896
+ }
897
+
898
+ // src/types/unifiedOrder.ts
899
+ function isV2Order(order) {
900
+ if ("version" in order && "order" in order) {
901
+ return order.version === 2;
902
+ }
903
+ return "timestamp" in order && "metadata" in order && "builder" in order;
904
+ }
905
+
906
+ // src/utilities.ts
907
+ import { createHash } from "crypto";
908
+ var roundNormal = (num, decimals) => {
909
+ if (decimalPlaces(num) <= decimals) {
910
+ return num;
911
+ }
912
+ return Math.round((num + Number.EPSILON) * 10 ** decimals) / 10 ** decimals;
913
+ };
914
+ var roundDown = (num, decimals) => {
915
+ if (decimalPlaces(num) <= decimals) {
916
+ return num;
917
+ }
918
+ return Math.floor(num * 10 ** decimals) / 10 ** decimals;
919
+ };
920
+ var roundUp = (num, decimals) => {
921
+ if (decimalPlaces(num) <= decimals) {
922
+ return num;
923
+ }
924
+ return Math.ceil(num * 10 ** decimals) / 10 ** decimals;
925
+ };
926
+ var decimalPlaces = (num) => {
927
+ if (Number.isInteger(num)) {
928
+ return 0;
929
+ }
930
+ const arr = num.toString().split(".");
931
+ if (arr.length <= 1) {
932
+ return 0;
933
+ }
934
+ return arr[1].length;
935
+ };
936
+ var generateOrderBookSummaryHash = (orderbook) => {
937
+ orderbook.hash = "";
938
+ const hash = createHash("sha1").update(JSON.stringify(orderbook)).digest("hex");
939
+ orderbook.hash = hash;
940
+ return hash;
941
+ };
942
+ var isTickSizeSmaller = (a, b) => {
943
+ return parseFloat(a) < parseFloat(b);
944
+ };
945
+ var priceValid = (price, tickSize) => {
946
+ return price >= parseFloat(tickSize) && price <= 1 - parseFloat(tickSize);
947
+ };
948
+
949
+ // src/order-builder/helpers/getOrderRawAmounts.ts
950
+ var getOrderRawAmounts = (side, size, price, roundConfig) => {
951
+ const rawPrice = roundNormal(price, roundConfig.price);
952
+ if (side === "BUY" /* BUY */) {
953
+ const rawTakerAmt = roundDown(size, roundConfig.size);
954
+ let rawMakerAmt = rawTakerAmt * rawPrice;
955
+ if (decimalPlaces(rawMakerAmt) > roundConfig.amount) {
956
+ rawMakerAmt = roundUp(rawMakerAmt, roundConfig.amount + 4);
957
+ if (decimalPlaces(rawMakerAmt) > roundConfig.amount) {
958
+ rawMakerAmt = roundDown(rawMakerAmt, roundConfig.amount);
959
+ }
960
+ }
961
+ return {
962
+ side: "BUY" /* BUY */,
963
+ rawMakerAmt,
964
+ rawTakerAmt
965
+ };
966
+ } else {
967
+ const rawMakerAmt = roundDown(size, roundConfig.size);
968
+ let rawTakerAmt = rawMakerAmt * rawPrice;
969
+ if (decimalPlaces(rawTakerAmt) > roundConfig.amount) {
970
+ rawTakerAmt = roundUp(rawTakerAmt, roundConfig.amount + 4);
971
+ if (decimalPlaces(rawTakerAmt) > roundConfig.amount) {
972
+ rawTakerAmt = roundDown(rawTakerAmt, roundConfig.amount);
973
+ }
974
+ }
975
+ return {
976
+ side: "SELL" /* SELL */,
977
+ rawMakerAmt,
978
+ rawTakerAmt
979
+ };
980
+ }
981
+ };
982
+
983
+ // src/order-builder/helpers/buildOrderCreationArgs.ts
984
+ async function buildOrderCreationArgs(signer, maker, signatureType, userOrder, roundConfig, version = 2) {
985
+ const { side, rawMakerAmt, rawTakerAmt } = getOrderRawAmounts(
986
+ userOrder.side,
987
+ userOrder.size,
988
+ userOrder.price,
989
+ roundConfig
990
+ );
991
+ const makerAmount = parseUnits2(rawMakerAmt.toString(), COLLATERAL_TOKEN_DECIMALS).toString();
992
+ const takerAmount = parseUnits2(rawTakerAmt.toString(), COLLATERAL_TOKEN_DECIMALS).toString();
993
+ if (version === 1) {
994
+ const v1Order = userOrder;
995
+ return {
996
+ maker,
997
+ taker: v1Order.taker ?? zeroAddress2,
998
+ tokenId: userOrder.tokenID,
999
+ makerAmount,
1000
+ takerAmount,
1001
+ side,
1002
+ signer,
1003
+ signatureType,
1004
+ feeRateBps: v1Order.feeRateBps?.toString() ?? "0",
1005
+ nonce: v1Order.nonce?.toString() ?? "0",
1006
+ expiration: userOrder.expiration !== void 0 ? userOrder.expiration.toString() : "0"
1007
+ };
1008
+ }
1009
+ return {
1010
+ maker,
1011
+ tokenId: userOrder.tokenID,
1012
+ makerAmount,
1013
+ takerAmount,
1014
+ side,
1015
+ signer,
1016
+ signatureType,
1017
+ timestamp: Date.now().toString(),
1018
+ metadata: "metadata" in userOrder ? userOrder.metadata ?? bytes32Zero : bytes32Zero,
1019
+ builder: userOrder.builderCode ?? bytes32Zero,
1020
+ expiration: userOrder.expiration !== void 0 ? userOrder.expiration.toString() : "0"
1021
+ };
1022
+ }
1023
+
1024
+ // src/order-builder/helpers/calculateBuyMarketPrice.ts
1025
+ var calculateBuyMarketPrice = (positions, amountToMatch, orderType) => {
1026
+ if (!positions.length) {
1027
+ throw new Error("no match");
1028
+ }
1029
+ let sum = 0;
1030
+ for (let i = positions.length - 1; i >= 0; i--) {
1031
+ const p = positions[i];
1032
+ sum += parseFloat(p.size) * parseFloat(p.price);
1033
+ if (sum >= amountToMatch) {
1034
+ return parseFloat(p.price);
1035
+ }
1036
+ }
1037
+ if (orderType === "FOK" /* FOK */) {
1038
+ throw new Error("no match");
1039
+ }
1040
+ return parseFloat(positions[0].price);
1041
+ };
1042
+
1043
+ // src/order-builder/helpers/calculateSellMarketPrice.ts
1044
+ var calculateSellMarketPrice = (positions, amountToMatch, orderType) => {
1045
+ if (!positions.length) {
1046
+ throw new Error("no match");
1047
+ }
1048
+ let sum = 0;
1049
+ for (let i = positions.length - 1; i >= 0; i--) {
1050
+ const p = positions[i];
1051
+ sum += parseFloat(p.size);
1052
+ if (sum >= amountToMatch) {
1053
+ return parseFloat(p.price);
1054
+ }
1055
+ }
1056
+ if (orderType === "FOK" /* FOK */) {
1057
+ throw new Error("no match");
1058
+ }
1059
+ return parseFloat(positions[0].price);
1060
+ };
1061
+
1062
+ // src/order-builder/helpers/roundingConfig.ts
1063
+ var ROUNDING_CONFIG = {
1064
+ "0.1": {
1065
+ price: 1,
1066
+ size: 2,
1067
+ amount: 3
1068
+ },
1069
+ "0.01": {
1070
+ price: 2,
1071
+ size: 2,
1072
+ amount: 4
1073
+ },
1074
+ "0.001": {
1075
+ price: 3,
1076
+ size: 2,
1077
+ amount: 5
1078
+ },
1079
+ "0.0001": {
1080
+ price: 4,
1081
+ size: 2,
1082
+ amount: 6
1083
+ }
1084
+ };
1085
+
1086
+ // src/order-builder/helpers/createMarketOrder.ts
1087
+ var createMarketOrder = async (eoaSigner, chainId, signatureType, funderAddress, userMarketOrder, options, version) => {
1088
+ const eoaSignerAddress = await getSignerAddress(eoaSigner);
1089
+ const maker = funderAddress === void 0 ? eoaSignerAddress : funderAddress;
1090
+ const contractConfig = getContractConfig(chainId);
1091
+ const orderData = await buildMarketOrderCreationArgs(
1092
+ eoaSignerAddress,
1093
+ maker,
1094
+ signatureType,
1095
+ userMarketOrder,
1096
+ ROUNDING_CONFIG[options.tickSize],
1097
+ version
1098
+ );
1099
+ let exchangeContract;
1100
+ switch (version) {
1101
+ case 1:
1102
+ if (signatureType === 3 /* POLY_1271 */) {
1103
+ throw new Error(`signature type POLY_1271 is not supported for v1 orders`);
1104
+ }
1105
+ exchangeContract = options.negRisk ? contractConfig.negRiskExchange : contractConfig.exchange;
1106
+ break;
1107
+ case 2:
1108
+ exchangeContract = options.negRisk ? contractConfig.negRiskExchangeV2 : contractConfig.exchangeV2;
1109
+ break;
1110
+ default:
1111
+ throw new Error(`unsupported order version ${version}`);
1112
+ }
1113
+ return buildOrder(eoaSigner, exchangeContract, chainId, orderData, version);
1114
+ };
1115
+
1116
+ // src/order-builder/helpers/createOrder.ts
1117
+ var createOrder = async (eoaSigner, chainId, signatureType, funderAddress, userOrder, options, version) => {
1118
+ const eoaSignerAddress = await getSignerAddress(eoaSigner);
1119
+ const maker = funderAddress === void 0 ? eoaSignerAddress : funderAddress;
1120
+ const contractConfig = getContractConfig(chainId);
1121
+ const orderData = await buildOrderCreationArgs(
1122
+ eoaSignerAddress,
1123
+ maker,
1124
+ signatureType,
1125
+ userOrder,
1126
+ ROUNDING_CONFIG[options.tickSize],
1127
+ version
1128
+ );
1129
+ let exchangeContract;
1130
+ switch (version) {
1131
+ case 1:
1132
+ if (signatureType === 3 /* POLY_1271 */) {
1133
+ throw new Error(`signature type POLY_1271 is not supported for v1 orders`);
1134
+ }
1135
+ exchangeContract = options.negRisk ? contractConfig.negRiskExchange : contractConfig.exchange;
1136
+ break;
1137
+ case 2:
1138
+ exchangeContract = options.negRisk ? contractConfig.negRiskExchangeV2 : contractConfig.exchangeV2;
1139
+ break;
1140
+ default:
1141
+ throw new Error(`unsupported order version ${version}`);
1142
+ }
1143
+ return buildOrder(eoaSigner, exchangeContract, chainId, orderData, version);
1144
+ };
1145
+
1146
+ // src/order-builder/helpers/getMarketOrderRawAmounts.ts
1147
+ var getMarketOrderRawAmounts = (side, amount, price, roundConfig) => {
1148
+ const rawPrice = roundDown(price, roundConfig.price);
1149
+ if (side === "BUY" /* BUY */) {
1150
+ const rawMakerAmt = roundDown(amount, roundConfig.size);
1151
+ let rawTakerAmt = rawMakerAmt / rawPrice;
1152
+ if (decimalPlaces(rawTakerAmt) > roundConfig.amount) {
1153
+ rawTakerAmt = roundUp(rawTakerAmt, roundConfig.amount + 4);
1154
+ if (decimalPlaces(rawTakerAmt) > roundConfig.amount) {
1155
+ rawTakerAmt = roundDown(rawTakerAmt, roundConfig.amount);
1156
+ }
1157
+ }
1158
+ return {
1159
+ side: "BUY" /* BUY */,
1160
+ rawMakerAmt,
1161
+ rawTakerAmt
1162
+ };
1163
+ } else {
1164
+ const rawMakerAmt = roundDown(amount, roundConfig.size);
1165
+ let rawTakerAmt = rawMakerAmt * rawPrice;
1166
+ if (decimalPlaces(rawTakerAmt) > roundConfig.amount) {
1167
+ rawTakerAmt = roundUp(rawTakerAmt, roundConfig.amount + 4);
1168
+ if (decimalPlaces(rawTakerAmt) > roundConfig.amount) {
1169
+ rawTakerAmt = roundDown(rawTakerAmt, roundConfig.amount);
1170
+ }
1171
+ }
1172
+ return {
1173
+ side: "SELL" /* SELL */,
1174
+ rawMakerAmt,
1175
+ rawTakerAmt
1176
+ };
1177
+ }
1178
+ };
1179
+
1180
+ // src/order-builder/orderBuilder.ts
1181
+ var OrderBuilder = class {
1182
+ signer;
1183
+ chainId;
1184
+ // Signature type used sign orders, defaults to EOA type
1185
+ signatureType;
1186
+ // Address which holds funds to be used.
1187
+ // Used for Polymarket proxy wallets and other smart contract wallets
1188
+ // If not provided, funderAddress is the signer address
1189
+ funderAddress;
1190
+ /**
1191
+ * Optional function to dynamically resolve the signer.
1192
+ * If provided, this function will be called to obtain a fresh signer instance
1193
+ * (e.g., for smart contract wallets or when the signer may change).
1194
+ * Should return a Wallet or JsonRpcSigner, or a Promise resolving to one.
1195
+ * If not provided, the static `signer` property is used.
1196
+ */
1197
+ getSigner;
1198
+ constructor(signer, chainId, signatureType, funderAddress, getSigner) {
1199
+ this.signer = signer;
1200
+ this.chainId = chainId;
1201
+ this.signatureType = signatureType === void 0 ? 0 /* EOA */ : signatureType;
1202
+ this.funderAddress = funderAddress;
1203
+ this.getSigner = getSigner;
1204
+ }
1205
+ /**
1206
+ * Generate and sign a order
1207
+ */
1208
+ async buildOrder(userOrder, options, version) {
1209
+ const signer = await this.resolveSigner();
1210
+ return createOrder(
1211
+ signer,
1212
+ this.chainId,
1213
+ this.signatureType,
1214
+ this.funderAddress,
1215
+ userOrder,
1216
+ options,
1217
+ version
1218
+ );
1219
+ }
1220
+ /**
1221
+ * Generate and sign a market order
1222
+ */
1223
+ async buildMarketOrder(userMarketOrder, options, version) {
1224
+ const signer = await this.resolveSigner();
1225
+ return createMarketOrder(
1226
+ signer,
1227
+ this.chainId,
1228
+ this.signatureType,
1229
+ this.funderAddress,
1230
+ userMarketOrder,
1231
+ options,
1232
+ version
1233
+ );
1234
+ }
1235
+ /** Unified getter: use fresh signer if available */
1236
+ async resolveSigner() {
1237
+ if (this.getSigner) {
1238
+ const s = await this.getSigner();
1239
+ if (!s) throw new Error("getSigner() function returned undefined or null");
1240
+ return s;
1241
+ }
1242
+ return this.signer;
1243
+ }
1244
+ };
1245
+
1246
+ // src/client.ts
1247
+ function adjustBuyAmountForFees(amount, price, userUSDCBalance, feeRate, feeExponent, builderTakerFeeRate) {
1248
+ const platformFeeRate = feeRate * (price * (1 - price)) ** feeExponent;
1249
+ const platformFee = amount / price * platformFeeRate;
1250
+ const totalCost = amount + platformFee + amount * builderTakerFeeRate;
1251
+ if (userUSDCBalance <= totalCost) {
1252
+ return userUSDCBalance / (1 + platformFeeRate / price + builderTakerFeeRate);
1253
+ }
1254
+ return amount;
1255
+ }
1256
+ var ClobClient = class {
1257
+ host;
1258
+ chainId;
1259
+ // Used to perform Level 1 authentication and sign orders
1260
+ signer;
1261
+ // Used to perform Level 2 authentication
1262
+ creds;
1263
+ orderBuilder;
1264
+ tickSizes;
1265
+ negRisk;
1266
+ feeInfos;
1267
+ // Fee rate bps data for CLOB V1
1268
+ feeRates;
1269
+ builderFeeRates;
1270
+ tokenConditionMap;
1271
+ useServerTime;
1272
+ builderConfig;
1273
+ cachedVersion;
1274
+ retryOnError;
1275
+ throwOnError;
1276
+ constructor({
1277
+ host,
1278
+ chain,
1279
+ signer,
1280
+ creds,
1281
+ signatureType,
1282
+ funderAddress,
1283
+ useServerTime,
1284
+ builderConfig,
1285
+ getSigner,
1286
+ retryOnError,
1287
+ throwOnError
1288
+ }) {
1289
+ this.host = host.endsWith("/") ? host.slice(0, -1) : host;
1290
+ this.chainId = chain;
1291
+ if (signer !== void 0) {
1292
+ this.signer = signer;
1293
+ }
1294
+ if (creds !== void 0) {
1295
+ this.creds = creds;
1296
+ }
1297
+ this.orderBuilder = new OrderBuilder(
1298
+ signer,
1299
+ chain,
1300
+ signatureType,
1301
+ funderAddress,
1302
+ getSigner
1303
+ );
1304
+ this.tickSizes = {};
1305
+ this.negRisk = {};
1306
+ this.feeRates = {};
1307
+ this.feeInfos = {};
1308
+ this.builderFeeRates = {};
1309
+ this.tokenConditionMap = {};
1310
+ this.retryOnError = retryOnError;
1311
+ this.throwOnError = throwOnError;
1312
+ this.useServerTime = useServerTime;
1313
+ if (builderConfig !== void 0) {
1314
+ this.builderConfig = builderConfig;
1315
+ }
1316
+ }
1317
+ // Public endpoints
1318
+ async getOk() {
1319
+ return this.get(`${this.host}${OK}`);
1320
+ }
1321
+ async postHeartbeat(heartbeatId = "") {
1322
+ this.canL2Auth();
1323
+ const body = JSON.stringify({ heartbeat_id: heartbeatId });
1324
+ const headers = await createL2Headers(
1325
+ this.signer,
1326
+ this.creds,
1327
+ { method: POST, requestPath: HEARTBEAT, body },
1328
+ this.useServerTime ? await this.getServerTime() : void 0
1329
+ );
1330
+ return this.post(`${this.host}${HEARTBEAT}`, {
1331
+ headers,
1332
+ data: { heartbeat_id: heartbeatId }
1333
+ });
1334
+ }
1335
+ async getVersion() {
1336
+ const response = await this.get(`${this.host}/version`);
1337
+ return response?.version ?? 2;
1338
+ }
1339
+ async getServerTime() {
1340
+ return this.get(`${this.host}${TIME}`);
1341
+ }
1342
+ async getSamplingSimplifiedMarkets(next_cursor = INITIAL_CURSOR) {
1343
+ return this.get(`${this.host}${GET_SAMPLING_SIMPLIFIED_MARKETS}`, {
1344
+ params: { next_cursor }
1345
+ });
1346
+ }
1347
+ async getSamplingMarkets(next_cursor = INITIAL_CURSOR) {
1348
+ return this.get(`${this.host}${GET_SAMPLING_MARKETS}`, {
1349
+ params: { next_cursor }
1350
+ });
1351
+ }
1352
+ async getSimplifiedMarkets(next_cursor = INITIAL_CURSOR) {
1353
+ return this.get(`${this.host}${GET_SIMPLIFIED_MARKETS}`, {
1354
+ params: { next_cursor }
1355
+ });
1356
+ }
1357
+ async getMarkets(next_cursor = INITIAL_CURSOR) {
1358
+ return this.get(`${this.host}${GET_MARKETS}`, {
1359
+ params: { next_cursor }
1360
+ });
1361
+ }
1362
+ async getMarket(conditionID) {
1363
+ return this.get(`${this.host}${GET_MARKET}${conditionID}`);
1364
+ }
1365
+ async getClobMarketInfo(conditionID) {
1366
+ const result = await this.get(
1367
+ `${this.host}${GET_CLOB_MARKET}${conditionID}`
1368
+ );
1369
+ if (!result?.t) {
1370
+ throw new Error(`failed to fetch market info for condition id ${conditionID}`);
1371
+ }
1372
+ for (const token of result.t) {
1373
+ if (!token) continue;
1374
+ const tokenId = token.t;
1375
+ this.tokenConditionMap[tokenId] = conditionID;
1376
+ this.tickSizes[tokenId] = result.mts.toString();
1377
+ this.negRisk[tokenId] = result.nr ?? false;
1378
+ this.feeInfos[tokenId] = {
1379
+ rate: result.fd?.r ?? 0,
1380
+ exponent: result.fd?.e ?? 0
1381
+ };
1382
+ }
1383
+ return result;
1384
+ }
1385
+ async getOrderBook(tokenID) {
1386
+ return this.get(`${this.host}${GET_ORDER_BOOK}`, {
1387
+ params: { token_id: tokenID }
1388
+ });
1389
+ }
1390
+ async getOrderBooks(params) {
1391
+ return this.post(`${this.host}${GET_ORDER_BOOKS}`, {
1392
+ data: params
1393
+ });
1394
+ }
1395
+ async getTickSize(tokenID) {
1396
+ if (tokenID in this.tickSizes) {
1397
+ return this.tickSizes[tokenID];
1398
+ }
1399
+ if (tokenID in this.tokenConditionMap) {
1400
+ await this.getClobMarketInfo(this.tokenConditionMap[tokenID]);
1401
+ return this.tickSizes[tokenID];
1402
+ }
1403
+ const result = await this.get(`${this.host}${GET_TICK_SIZE}`, {
1404
+ params: { token_id: tokenID }
1405
+ });
1406
+ this.tickSizes[tokenID] = result.minimum_tick_size.toString();
1407
+ return this.tickSizes[tokenID];
1408
+ }
1409
+ async getNegRisk(tokenID) {
1410
+ if (tokenID in this.negRisk) {
1411
+ return this.negRisk[tokenID];
1412
+ }
1413
+ if (tokenID in this.tokenConditionMap) {
1414
+ await this.getClobMarketInfo(this.tokenConditionMap[tokenID]);
1415
+ return this.negRisk[tokenID];
1416
+ }
1417
+ const result = await this.get(`${this.host}${GET_NEG_RISK}`, {
1418
+ params: { token_id: tokenID }
1419
+ });
1420
+ this.negRisk[tokenID] = result.neg_risk;
1421
+ return this.negRisk[tokenID];
1422
+ }
1423
+ async getFeeRateBps(tokenID) {
1424
+ if (tokenID in this.feeRates) {
1425
+ return this.feeRates[tokenID];
1426
+ }
1427
+ const result = await this.get(`${this.host}${GET_FEE_RATE}`, {
1428
+ params: { token_id: tokenID }
1429
+ });
1430
+ this.feeRates[tokenID] = result.base_fee;
1431
+ return this.feeRates[tokenID];
1432
+ }
1433
+ async getFeeExponent(tokenID) {
1434
+ if (tokenID in this.feeInfos) {
1435
+ return this.feeInfos[tokenID].exponent;
1436
+ }
1437
+ await this._ensureMarketInfoCached(tokenID);
1438
+ return this.feeInfos[tokenID].exponent;
1439
+ }
1440
+ /**
1441
+ * Calculates the hash for the given orderbook
1442
+ * @param orderbook
1443
+ * @returns
1444
+ */
1445
+ getOrderBookHash(orderbook) {
1446
+ return generateOrderBookSummaryHash(orderbook);
1447
+ }
1448
+ async getMidpoint(tokenID) {
1449
+ return this.get(`${this.host}${GET_MIDPOINT}`, {
1450
+ params: { token_id: tokenID }
1451
+ });
1452
+ }
1453
+ async getMidpoints(params) {
1454
+ return this.post(`${this.host}${GET_MIDPOINTS}`, {
1455
+ data: params
1456
+ });
1457
+ }
1458
+ async getPrice(tokenID, side) {
1459
+ return this.get(`${this.host}${GET_PRICE}`, {
1460
+ params: { token_id: tokenID, side }
1461
+ });
1462
+ }
1463
+ async getPrices(params) {
1464
+ return this.post(`${this.host}${GET_PRICES}`, {
1465
+ data: params
1466
+ });
1467
+ }
1468
+ async getSpread(tokenID) {
1469
+ return this.get(`${this.host}${GET_SPREAD}`, {
1470
+ params: { token_id: tokenID }
1471
+ });
1472
+ }
1473
+ async getSpreads(params) {
1474
+ return this.post(`${this.host}${GET_SPREADS}`, {
1475
+ data: params
1476
+ });
1477
+ }
1478
+ async getLastTradePrice(tokenID) {
1479
+ return this.get(`${this.host}${GET_LAST_TRADE_PRICE}`, {
1480
+ params: { token_id: tokenID }
1481
+ });
1482
+ }
1483
+ async getLastTradesPrices(params) {
1484
+ return this.post(`${this.host}${GET_LAST_TRADES_PRICES}`, {
1485
+ data: params
1486
+ });
1487
+ }
1488
+ async getPricesHistory(params) {
1489
+ if (!params.interval && (params.startTs === void 0 || params.endTs === void 0)) {
1490
+ throw new Error("getPricesHistory requires either interval or both startTs and endTs");
1491
+ }
1492
+ return this.get(`${this.host}${GET_PRICES_HISTORY}`, {
1493
+ params
1494
+ });
1495
+ }
1496
+ // L1 Authed
1497
+ /**
1498
+ * Creates a new API key for a user
1499
+ * @param nonce
1500
+ * @returns ApiKeyCreds
1501
+ */
1502
+ async createApiKey(nonce) {
1503
+ this.canL1Auth();
1504
+ const endpoint = `${this.host}${CREATE_API_KEY}`;
1505
+ const headers = await createL1Headers(
1506
+ this.signer,
1507
+ this.chainId,
1508
+ nonce,
1509
+ this.useServerTime ? await this.getServerTime() : void 0
1510
+ );
1511
+ return await this.post(endpoint, { headers }).then((apiKeyRaw) => {
1512
+ const apiKey = {
1513
+ key: apiKeyRaw.apiKey,
1514
+ secret: apiKeyRaw.secret,
1515
+ passphrase: apiKeyRaw.passphrase
1516
+ };
1517
+ return apiKey;
1518
+ });
1519
+ }
1520
+ /**
1521
+ * Derives an existing API key for a user
1522
+ * @param nonce
1523
+ * @returns ApiKeyCreds
1524
+ */
1525
+ async deriveApiKey(nonce) {
1526
+ this.canL1Auth();
1527
+ const endpoint = `${this.host}${DERIVE_API_KEY}`;
1528
+ const headers = await createL1Headers(
1529
+ this.signer,
1530
+ this.chainId,
1531
+ nonce,
1532
+ this.useServerTime ? await this.getServerTime() : void 0
1533
+ );
1534
+ return await this.get(endpoint, { headers }).then((apiKeyRaw) => {
1535
+ const apiKey = {
1536
+ key: apiKeyRaw.apiKey,
1537
+ secret: apiKeyRaw.secret,
1538
+ passphrase: apiKeyRaw.passphrase
1539
+ };
1540
+ return apiKey;
1541
+ });
1542
+ }
1543
+ async createOrDeriveApiKey(nonce) {
1544
+ return this.createApiKey(nonce).then((response) => {
1545
+ if (!response.key) {
1546
+ return this.deriveApiKey(nonce);
1547
+ }
1548
+ return response;
1549
+ });
1550
+ }
1551
+ async getApiKeys() {
1552
+ this.canL2Auth();
1553
+ const endpoint = GET_API_KEYS;
1554
+ const headerArgs = {
1555
+ method: GET,
1556
+ requestPath: endpoint
1557
+ };
1558
+ const headers = await createL2Headers(
1559
+ this.signer,
1560
+ this.creds,
1561
+ headerArgs,
1562
+ this.useServerTime ? await this.getServerTime() : void 0
1563
+ );
1564
+ return this.get(`${this.host}${endpoint}`, { headers });
1565
+ }
1566
+ async getClosedOnlyMode() {
1567
+ this.canL2Auth();
1568
+ const endpoint = CLOSED_ONLY;
1569
+ const headerArgs = {
1570
+ method: GET,
1571
+ requestPath: endpoint
1572
+ };
1573
+ const headers = await createL2Headers(
1574
+ this.signer,
1575
+ this.creds,
1576
+ headerArgs,
1577
+ this.useServerTime ? await this.getServerTime() : void 0
1578
+ );
1579
+ return this.get(`${this.host}${endpoint}`, { headers });
1580
+ }
1581
+ async deleteApiKey() {
1582
+ this.canL2Auth();
1583
+ const endpoint = DELETE_API_KEY;
1584
+ const headerArgs = {
1585
+ method: DELETE,
1586
+ requestPath: endpoint
1587
+ };
1588
+ const headers = await createL2Headers(
1589
+ this.signer,
1590
+ this.creds,
1591
+ headerArgs,
1592
+ this.useServerTime ? await this.getServerTime() : void 0
1593
+ );
1594
+ return this.del(`${this.host}${endpoint}`, { headers });
1595
+ }
1596
+ async createReadonlyApiKey() {
1597
+ this.canL2Auth();
1598
+ const endpoint = CREATE_READONLY_API_KEY;
1599
+ const headerArgs = {
1600
+ method: POST,
1601
+ requestPath: endpoint
1602
+ };
1603
+ const headers = await createL2Headers(
1604
+ this.signer,
1605
+ this.creds,
1606
+ headerArgs,
1607
+ this.useServerTime ? await this.getServerTime() : void 0
1608
+ );
1609
+ return this.post(`${this.host}${endpoint}`, { headers });
1610
+ }
1611
+ async getReadonlyApiKeys() {
1612
+ this.canL2Auth();
1613
+ const endpoint = GET_READONLY_API_KEYS;
1614
+ const headerArgs = {
1615
+ method: GET,
1616
+ requestPath: endpoint
1617
+ };
1618
+ const headers = await createL2Headers(
1619
+ this.signer,
1620
+ this.creds,
1621
+ headerArgs,
1622
+ this.useServerTime ? await this.getServerTime() : void 0
1623
+ );
1624
+ return this.get(`${this.host}${endpoint}`, { headers });
1625
+ }
1626
+ async deleteReadonlyApiKey(key) {
1627
+ this.canL2Auth();
1628
+ const endpoint = DELETE_READONLY_API_KEY;
1629
+ const payload = { key };
1630
+ const headerArgs = {
1631
+ method: DELETE,
1632
+ requestPath: endpoint,
1633
+ body: JSON.stringify(payload)
1634
+ };
1635
+ const headers = await createL2Headers(
1636
+ this.signer,
1637
+ this.creds,
1638
+ headerArgs,
1639
+ this.useServerTime ? await this.getServerTime() : void 0
1640
+ );
1641
+ return this.del(`${this.host}${endpoint}`, { headers, data: payload });
1642
+ }
1643
+ async getOrder(orderID) {
1644
+ this.canL2Auth();
1645
+ const endpoint = `${GET_ORDER}${orderID}`;
1646
+ const headerArgs = {
1647
+ method: GET,
1648
+ requestPath: endpoint
1649
+ };
1650
+ const headers = await createL2Headers(
1651
+ this.signer,
1652
+ this.creds,
1653
+ headerArgs,
1654
+ this.useServerTime ? await this.getServerTime() : void 0
1655
+ );
1656
+ return this.get(`${this.host}${endpoint}`, { headers });
1657
+ }
1658
+ async getTrades(params, only_first_page = false, next_cursor) {
1659
+ this.canL2Auth();
1660
+ const endpoint = GET_TRADES;
1661
+ const headerArgs = {
1662
+ method: GET,
1663
+ requestPath: endpoint
1664
+ };
1665
+ const headers = await createL2Headers(
1666
+ this.signer,
1667
+ this.creds,
1668
+ headerArgs,
1669
+ this.useServerTime ? await this.getServerTime() : void 0
1670
+ );
1671
+ let results = [];
1672
+ next_cursor = next_cursor || INITIAL_CURSOR;
1673
+ while (next_cursor !== END_CURSOR && (next_cursor === INITIAL_CURSOR || !only_first_page)) {
1674
+ const _params = {
1675
+ ...params,
1676
+ next_cursor
1677
+ };
1678
+ const response = await this.get(`${this.host}${endpoint}`, {
1679
+ headers,
1680
+ params: _params
1681
+ });
1682
+ next_cursor = response.next_cursor;
1683
+ results = [...results, ...response.data];
1684
+ }
1685
+ return results;
1686
+ }
1687
+ async getTradesPaginated(params, next_cursor) {
1688
+ this.canL2Auth();
1689
+ const endpoint = GET_TRADES;
1690
+ const headerArgs = {
1691
+ method: GET,
1692
+ requestPath: endpoint
1693
+ };
1694
+ const headers = await createL2Headers(
1695
+ this.signer,
1696
+ this.creds,
1697
+ headerArgs,
1698
+ this.useServerTime ? await this.getServerTime() : void 0
1699
+ );
1700
+ next_cursor = next_cursor || INITIAL_CURSOR;
1701
+ const _params = { ...params, next_cursor };
1702
+ const {
1703
+ data,
1704
+ ...rest
1705
+ } = await this.get(
1706
+ `${this.host}${endpoint}`,
1707
+ { headers, params: _params }
1708
+ );
1709
+ return { trades: Array.isArray(data) ? [...data] : [], ...rest };
1710
+ }
1711
+ async getBuilderTrades(params, next_cursor) {
1712
+ if (!params.builder_code || params.builder_code === bytes32Zero) {
1713
+ throw new Error("builderCode is required and cannot be zero");
1714
+ }
1715
+ this.canL2Auth();
1716
+ const endpoint = GET_BUILDER_TRADES;
1717
+ const headerArgs = {
1718
+ method: GET,
1719
+ requestPath: endpoint
1720
+ };
1721
+ const headers = await createL2Headers(
1722
+ this.signer,
1723
+ this.creds,
1724
+ headerArgs,
1725
+ this.useServerTime ? await this.getServerTime() : void 0
1726
+ );
1727
+ next_cursor = next_cursor || INITIAL_CURSOR;
1728
+ const _params = { ...params, next_cursor };
1729
+ const {
1730
+ data,
1731
+ ...rest
1732
+ } = await this.get(`${this.host}${endpoint}`, { headers, params: _params });
1733
+ return { trades: Array.isArray(data) ? [...data] : [], ...rest };
1734
+ }
1735
+ async getNotifications() {
1736
+ this.canL2Auth();
1737
+ const endpoint = GET_NOTIFICATIONS;
1738
+ const headerArgs = {
1739
+ method: GET,
1740
+ requestPath: endpoint
1741
+ };
1742
+ const headers = await createL2Headers(
1743
+ this.signer,
1744
+ this.creds,
1745
+ headerArgs,
1746
+ this.useServerTime ? await this.getServerTime() : void 0
1747
+ );
1748
+ return this.get(`${this.host}${endpoint}`, {
1749
+ headers,
1750
+ params: { signature_type: this.orderBuilder.signatureType }
1751
+ });
1752
+ }
1753
+ async dropNotifications(params) {
1754
+ this.canL2Auth();
1755
+ const endpoint = DROP_NOTIFICATIONS;
1756
+ const l2HeaderArgs = {
1757
+ method: DELETE,
1758
+ requestPath: endpoint
1759
+ };
1760
+ const headers = await createL2Headers(
1761
+ this.signer,
1762
+ this.creds,
1763
+ l2HeaderArgs,
1764
+ this.useServerTime ? await this.getServerTime() : void 0
1765
+ );
1766
+ return this.del(`${this.host}${endpoint}`, {
1767
+ headers,
1768
+ params: parseDropNotificationParams(params)
1769
+ });
1770
+ }
1771
+ async getBalanceAllowance(params) {
1772
+ this.canL2Auth();
1773
+ const endpoint = GET_BALANCE_ALLOWANCE;
1774
+ const headerArgs = {
1775
+ method: GET,
1776
+ requestPath: endpoint
1777
+ };
1778
+ const headers = await createL2Headers(
1779
+ this.signer,
1780
+ this.creds,
1781
+ headerArgs,
1782
+ this.useServerTime ? await this.getServerTime() : void 0
1783
+ );
1784
+ const _params = {
1785
+ ...params,
1786
+ signature_type: this.orderBuilder.signatureType
1787
+ };
1788
+ return this.get(`${this.host}${endpoint}`, { headers, params: _params });
1789
+ }
1790
+ async updateBalanceAllowance(params) {
1791
+ this.canL2Auth();
1792
+ const endpoint = UPDATE_BALANCE_ALLOWANCE;
1793
+ const headerArgs = {
1794
+ method: GET,
1795
+ requestPath: endpoint
1796
+ };
1797
+ const headers = await createL2Headers(
1798
+ this.signer,
1799
+ this.creds,
1800
+ headerArgs,
1801
+ this.useServerTime ? await this.getServerTime() : void 0
1802
+ );
1803
+ const _params = {
1804
+ ...params,
1805
+ signature_type: this.orderBuilder.signatureType
1806
+ };
1807
+ return this.get(`${this.host}${endpoint}`, { headers, params: _params });
1808
+ }
1809
+ async createOrder(userOrder, options) {
1810
+ this.canL1Auth();
1811
+ const orderToSign = { ...userOrder };
1812
+ if (this.builderConfig?.builderCode && !orderToSign.builderCode) {
1813
+ orderToSign.builderCode = this.builderConfig.builderCode;
1814
+ }
1815
+ const { tokenID } = orderToSign;
1816
+ const tickSize = await this._resolveTickSize(tokenID, options?.tickSize);
1817
+ if (!priceValid(orderToSign.price, tickSize)) {
1818
+ throw new Error(
1819
+ `invalid price (${orderToSign.price}), min: ${parseFloat(tickSize)} - max: ${1 - parseFloat(tickSize)}`
1820
+ );
1821
+ }
1822
+ const negRisk = options?.negRisk ?? await this.getNegRisk(tokenID);
1823
+ const version = await this.resolveVersion();
1824
+ if (version === 1) {
1825
+ const userFeeRateBps = "feeRateBps" in orderToSign ? orderToSign.feeRateBps : void 0;
1826
+ const feeRateBps = await this._resolveFeeRateBps(tokenID, userFeeRateBps);
1827
+ orderToSign.feeRateBps = feeRateBps;
1828
+ }
1829
+ return this.orderBuilder.buildOrder(
1830
+ orderToSign,
1831
+ {
1832
+ tickSize,
1833
+ negRisk
1834
+ },
1835
+ version
1836
+ );
1837
+ }
1838
+ async createMarketOrder(userMarketOrder, options) {
1839
+ this.canL1Auth();
1840
+ const { tokenID } = userMarketOrder;
1841
+ await this._ensureMarketInfoCached(tokenID);
1842
+ const tickSize = await this._resolveTickSize(tokenID, options?.tickSize);
1843
+ if (!userMarketOrder.price) {
1844
+ userMarketOrder.price = await this.calculateMarketPrice(
1845
+ tokenID,
1846
+ userMarketOrder.side,
1847
+ userMarketOrder.amount,
1848
+ userMarketOrder.orderType
1849
+ );
1850
+ }
1851
+ if (!priceValid(userMarketOrder.price, tickSize)) {
1852
+ throw new Error(
1853
+ `invalid price (${userMarketOrder.price}), min: ${parseFloat(tickSize)} - max: ${1 - parseFloat(tickSize)}`
1854
+ );
1855
+ }
1856
+ const orderToSign = { ...userMarketOrder };
1857
+ if (this.builderConfig?.builderCode && !orderToSign.builderCode) {
1858
+ orderToSign.builderCode = this.builderConfig.builderCode;
1859
+ }
1860
+ await this.ensureBuilderFeeRateCached(orderToSign.builderCode);
1861
+ if (orderToSign.side === "BUY" /* BUY */ && "userUSDCBalance" in orderToSign && orderToSign.userUSDCBalance !== void 0) {
1862
+ const price = orderToSign.price;
1863
+ const { userUSDCBalance } = orderToSign;
1864
+ const builderTakerFeeRate = this.isBuilderOrder(orderToSign.builderCode) ? this.builderFeeRates[orderToSign.builderCode ?? ""]?.taker ?? 0 : 0;
1865
+ orderToSign.amount = adjustBuyAmountForFees(
1866
+ orderToSign.amount,
1867
+ price,
1868
+ userUSDCBalance,
1869
+ this.feeInfos[tokenID].rate,
1870
+ this.feeInfos[tokenID].exponent,
1871
+ builderTakerFeeRate
1872
+ );
1873
+ }
1874
+ const negRisk = options?.negRisk ?? await this.getNegRisk(tokenID);
1875
+ const version = await this.resolveVersion();
1876
+ if (version === 1) {
1877
+ const userFeeRateBps = "feeRateBps" in orderToSign ? orderToSign.feeRateBps : void 0;
1878
+ const feeRateBps = await this._resolveFeeRateBps(tokenID, userFeeRateBps);
1879
+ orderToSign.feeRateBps = feeRateBps;
1880
+ }
1881
+ return this.orderBuilder.buildMarketOrder(
1882
+ orderToSign,
1883
+ {
1884
+ tickSize,
1885
+ negRisk
1886
+ },
1887
+ version
1888
+ );
1889
+ }
1890
+ async createAndPostOrder(userOrder, options, orderType = "GTC" /* GTC */, postOnly = false, deferExec = false) {
1891
+ let postOrderResponse;
1892
+ await this._retryOnVersionUpdate(async () => {
1893
+ const order = await this.createOrder(userOrder, options);
1894
+ postOrderResponse = await this.postOrder(order, orderType, postOnly, deferExec);
1895
+ });
1896
+ return postOrderResponse;
1897
+ }
1898
+ async createAndPostMarketOrder(userMarketOrder, options, orderType = "FOK" /* FOK */, deferExec = false) {
1899
+ let postOrderMarketResponse;
1900
+ await this._retryOnVersionUpdate(async () => {
1901
+ const order = await this.createMarketOrder(userMarketOrder, options);
1902
+ postOrderMarketResponse = await this.postOrder(order, orderType, false, deferExec);
1903
+ });
1904
+ return postOrderMarketResponse;
1905
+ }
1906
+ async getOpenOrders(params, only_first_page = false, next_cursor) {
1907
+ this.canL2Auth();
1908
+ const endpoint = GET_OPEN_ORDERS;
1909
+ const l2HeaderArgs = {
1910
+ method: GET,
1911
+ requestPath: endpoint
1912
+ };
1913
+ const headers = await createL2Headers(
1914
+ this.signer,
1915
+ this.creds,
1916
+ l2HeaderArgs,
1917
+ this.useServerTime ? await this.getServerTime() : void 0
1918
+ );
1919
+ let results = [];
1920
+ next_cursor = next_cursor || INITIAL_CURSOR;
1921
+ while (next_cursor !== END_CURSOR && (next_cursor === INITIAL_CURSOR || !only_first_page)) {
1922
+ const _params = {
1923
+ ...params,
1924
+ next_cursor
1925
+ };
1926
+ const response = await this.get(`${this.host}${endpoint}`, {
1927
+ headers,
1928
+ params: _params
1929
+ });
1930
+ next_cursor = response.next_cursor;
1931
+ results = [...results, ...response.data];
1932
+ }
1933
+ return results;
1934
+ }
1935
+ async getPreMigrationOrders(only_first_page = false, next_cursor) {
1936
+ this.canL2Auth();
1937
+ const endpoint = GET_PRE_MIGRATION_ORDERS;
1938
+ const l2HeaderArgs = {
1939
+ method: GET,
1940
+ requestPath: endpoint
1941
+ };
1942
+ const headers = await createL2Headers(
1943
+ this.signer,
1944
+ this.creds,
1945
+ l2HeaderArgs,
1946
+ this.useServerTime ? await this.getServerTime() : void 0
1947
+ );
1948
+ let results = [];
1949
+ next_cursor = next_cursor || INITIAL_CURSOR;
1950
+ while (next_cursor !== END_CURSOR && (next_cursor === INITIAL_CURSOR || !only_first_page)) {
1951
+ const _params = { next_cursor };
1952
+ const response = await this.get(`${this.host}${endpoint}`, {
1953
+ headers,
1954
+ params: _params
1955
+ });
1956
+ next_cursor = response.next_cursor;
1957
+ results = [...results, ...response.data];
1958
+ }
1959
+ return results;
1960
+ }
1961
+ async postOrder(order, orderType = "GTC" /* GTC */, postOnly = false, deferExec = false) {
1962
+ this.canL2Auth();
1963
+ if (postOnly && (orderType === "FOK" /* FOK */ || orderType === "FAK" /* FAK */)) {
1964
+ throw new Error("postOnly is not supported for FOK/FAK orders");
1965
+ }
1966
+ const endpoint = POST_ORDER;
1967
+ const orderPayload = isV2Order(order) ? orderToJsonV2(order, this.creds?.key || "", orderType, postOnly, deferExec) : orderToJsonV1(order, this.creds?.key || "", orderType, postOnly, deferExec);
1968
+ const l2HeaderArgs = {
1969
+ method: POST,
1970
+ requestPath: endpoint,
1971
+ body: JSON.stringify(orderPayload)
1972
+ };
1973
+ const headers = await createL2Headers(
1974
+ this.signer,
1975
+ this.creds,
1976
+ l2HeaderArgs,
1977
+ this.useServerTime ? await this.getServerTime() : void 0
1978
+ );
1979
+ const res = await this.post(
1980
+ `${this.host}${endpoint}`,
1981
+ {
1982
+ headers,
1983
+ data: orderPayload
1984
+ },
1985
+ true
1986
+ );
1987
+ if (this._isOrderVersionMismatch(res)) await this.resolveVersion(true);
1988
+ return this.throwIfError(res);
1989
+ }
1990
+ async postOrders(args, postOnly = false, deferExec = false) {
1991
+ this.canL2Auth();
1992
+ if (postOnly && args.some(({ orderType }) => orderType === "FOK" /* FOK */ || orderType === "FAK" /* FAK */)) {
1993
+ throw new Error("postOnly is not supported for FOK/FAK orders");
1994
+ }
1995
+ const endpoint = POST_ORDERS;
1996
+ const ordersPayload = [];
1997
+ for (const arg of args) {
1998
+ const { order, orderType } = arg;
1999
+ const orderPayload = isV2Order(order) ? orderToJsonV2(order, this.creds?.key || "", orderType, postOnly, deferExec) : orderToJsonV1(order, this.creds?.key || "", orderType, postOnly, deferExec);
2000
+ ordersPayload.push(orderPayload);
2001
+ }
2002
+ const l2HeaderArgs = {
2003
+ method: POST,
2004
+ requestPath: endpoint,
2005
+ body: JSON.stringify(ordersPayload)
2006
+ };
2007
+ const headers = await createL2Headers(
2008
+ this.signer,
2009
+ this.creds,
2010
+ l2HeaderArgs,
2011
+ this.useServerTime ? await this.getServerTime() : void 0
2012
+ );
2013
+ const res = await this.post(
2014
+ `${this.host}${endpoint}`,
2015
+ {
2016
+ headers,
2017
+ data: ordersPayload
2018
+ },
2019
+ true
2020
+ );
2021
+ if (this._isOrderVersionMismatch(res)) await this.resolveVersion(true);
2022
+ return this.throwIfError(res);
2023
+ }
2024
+ async cancelOrder(payload) {
2025
+ this.canL2Auth();
2026
+ const endpoint = CANCEL_ORDER;
2027
+ const l2HeaderArgs = {
2028
+ method: DELETE,
2029
+ requestPath: endpoint,
2030
+ body: JSON.stringify(payload)
2031
+ };
2032
+ const headers = await createL2Headers(
2033
+ this.signer,
2034
+ this.creds,
2035
+ l2HeaderArgs,
2036
+ this.useServerTime ? await this.getServerTime() : void 0
2037
+ );
2038
+ return this.del(`${this.host}${endpoint}`, { headers, data: payload });
2039
+ }
2040
+ async cancelOrders(ordersHashes) {
2041
+ this.canL2Auth();
2042
+ const endpoint = CANCEL_ORDERS;
2043
+ const l2HeaderArgs = {
2044
+ method: DELETE,
2045
+ requestPath: endpoint,
2046
+ body: JSON.stringify(ordersHashes)
2047
+ };
2048
+ const headers = await createL2Headers(
2049
+ this.signer,
2050
+ this.creds,
2051
+ l2HeaderArgs,
2052
+ this.useServerTime ? await this.getServerTime() : void 0
2053
+ );
2054
+ return this.del(`${this.host}${endpoint}`, { headers, data: ordersHashes });
2055
+ }
2056
+ async cancelAll() {
2057
+ this.canL2Auth();
2058
+ const endpoint = CANCEL_ALL;
2059
+ const l2HeaderArgs = {
2060
+ method: DELETE,
2061
+ requestPath: endpoint
2062
+ };
2063
+ const headers = await createL2Headers(
2064
+ this.signer,
2065
+ this.creds,
2066
+ l2HeaderArgs,
2067
+ this.useServerTime ? await this.getServerTime() : void 0
2068
+ );
2069
+ return this.del(`${this.host}${endpoint}`, { headers });
2070
+ }
2071
+ async cancelMarketOrders(payload) {
2072
+ this.canL2Auth();
2073
+ const endpoint = CANCEL_MARKET_ORDERS;
2074
+ const l2HeaderArgs = {
2075
+ method: DELETE,
2076
+ requestPath: endpoint,
2077
+ body: JSON.stringify(payload)
2078
+ };
2079
+ const headers = await createL2Headers(
2080
+ this.signer,
2081
+ this.creds,
2082
+ l2HeaderArgs,
2083
+ this.useServerTime ? await this.getServerTime() : void 0
2084
+ );
2085
+ return this.del(`${this.host}${endpoint}`, { headers, data: payload });
2086
+ }
2087
+ async isOrderScoring(params) {
2088
+ this.canL2Auth();
2089
+ const endpoint = IS_ORDER_SCORING;
2090
+ const headerArgs = {
2091
+ method: GET,
2092
+ requestPath: endpoint
2093
+ };
2094
+ const headers = await createL2Headers(
2095
+ this.signer,
2096
+ this.creds,
2097
+ headerArgs,
2098
+ this.useServerTime ? await this.getServerTime() : void 0
2099
+ );
2100
+ return this.get(`${this.host}${endpoint}`, { headers, params });
2101
+ }
2102
+ async areOrdersScoring(params) {
2103
+ this.canL2Auth();
2104
+ const endpoint = ARE_ORDERS_SCORING;
2105
+ const payload = JSON.stringify(params?.orderIds);
2106
+ const headerArgs = {
2107
+ method: POST,
2108
+ requestPath: endpoint,
2109
+ body: payload
2110
+ };
2111
+ const headers = await createL2Headers(
2112
+ this.signer,
2113
+ this.creds,
2114
+ headerArgs,
2115
+ this.useServerTime ? await this.getServerTime() : void 0
2116
+ );
2117
+ return this.post(`${this.host}${endpoint}`, {
2118
+ headers,
2119
+ data: payload
2120
+ });
2121
+ }
2122
+ // Rewards
2123
+ async getEarningsForUserForDay(date) {
2124
+ this.canL2Auth();
2125
+ const endpoint = GET_EARNINGS_FOR_USER_FOR_DAY;
2126
+ const headerArgs = {
2127
+ method: GET,
2128
+ requestPath: endpoint
2129
+ };
2130
+ const headers = await createL2Headers(
2131
+ this.signer,
2132
+ this.creds,
2133
+ headerArgs,
2134
+ this.useServerTime ? await this.getServerTime() : void 0
2135
+ );
2136
+ let results = [];
2137
+ let next_cursor = INITIAL_CURSOR;
2138
+ while (next_cursor !== END_CURSOR) {
2139
+ const params = {
2140
+ date,
2141
+ signature_type: this.orderBuilder.signatureType,
2142
+ next_cursor
2143
+ };
2144
+ const response = await this.get(`${this.host}${endpoint}`, {
2145
+ headers,
2146
+ params
2147
+ });
2148
+ next_cursor = response.next_cursor;
2149
+ results = [...results, ...response.data];
2150
+ }
2151
+ return results;
2152
+ }
2153
+ async getTotalEarningsForUserForDay(date) {
2154
+ this.canL2Auth();
2155
+ const endpoint = GET_TOTAL_EARNINGS_FOR_USER_FOR_DAY;
2156
+ const headerArgs = {
2157
+ method: GET,
2158
+ requestPath: endpoint
2159
+ };
2160
+ const headers = await createL2Headers(
2161
+ this.signer,
2162
+ this.creds,
2163
+ headerArgs,
2164
+ this.useServerTime ? await this.getServerTime() : void 0
2165
+ );
2166
+ const params = {
2167
+ date,
2168
+ signature_type: this.orderBuilder.signatureType
2169
+ };
2170
+ return await this.get(`${this.host}${endpoint}`, {
2171
+ headers,
2172
+ params
2173
+ });
2174
+ }
2175
+ async getUserEarningsAndMarketsConfig(date, order_by = "", position = "", no_competition = false) {
2176
+ this.canL2Auth();
2177
+ const endpoint = GET_REWARDS_EARNINGS_PERCENTAGES;
2178
+ const headerArgs = {
2179
+ method: GET,
2180
+ requestPath: endpoint
2181
+ };
2182
+ const headers = await createL2Headers(
2183
+ this.signer,
2184
+ this.creds,
2185
+ headerArgs,
2186
+ this.useServerTime ? await this.getServerTime() : void 0
2187
+ );
2188
+ let results = [];
2189
+ let next_cursor = INITIAL_CURSOR;
2190
+ while (next_cursor !== END_CURSOR) {
2191
+ const params = {
2192
+ date,
2193
+ signature_type: this.orderBuilder.signatureType,
2194
+ next_cursor,
2195
+ order_by,
2196
+ position,
2197
+ no_competition
2198
+ };
2199
+ const response = await this.get(`${this.host}${endpoint}`, {
2200
+ headers,
2201
+ params
2202
+ });
2203
+ next_cursor = response.next_cursor;
2204
+ results = [...results, ...response.data];
2205
+ }
2206
+ return results;
2207
+ }
2208
+ async getRewardPercentages() {
2209
+ this.canL2Auth();
2210
+ const endpoint = GET_LIQUIDITY_REWARD_PERCENTAGES;
2211
+ const headerArgs = {
2212
+ method: GET,
2213
+ requestPath: endpoint
2214
+ };
2215
+ const headers = await createL2Headers(
2216
+ this.signer,
2217
+ this.creds,
2218
+ headerArgs,
2219
+ this.useServerTime ? await this.getServerTime() : void 0
2220
+ );
2221
+ const _params = {
2222
+ signature_type: this.orderBuilder.signatureType
2223
+ };
2224
+ return this.get(`${this.host}${endpoint}`, { headers, params: _params });
2225
+ }
2226
+ async getCurrentRewards() {
2227
+ let results = [];
2228
+ let next_cursor = INITIAL_CURSOR;
2229
+ while (next_cursor !== END_CURSOR) {
2230
+ const response = await this.get(`${this.host}${GET_REWARDS_MARKETS_CURRENT}`, {
2231
+ params: { next_cursor }
2232
+ });
2233
+ next_cursor = response.next_cursor;
2234
+ results = [...results, ...response.data];
2235
+ }
2236
+ return results;
2237
+ }
2238
+ async getRawRewardsForMarket(conditionId) {
2239
+ let results = [];
2240
+ let next_cursor = INITIAL_CURSOR;
2241
+ while (next_cursor !== END_CURSOR) {
2242
+ const response = await this.get(`${this.host}${GET_REWARDS_MARKETS}${conditionId}`, {
2243
+ params: { next_cursor }
2244
+ });
2245
+ next_cursor = response.next_cursor;
2246
+ results = [...results, ...response.data];
2247
+ }
2248
+ return results;
2249
+ }
2250
+ async calculateMarketPrice(tokenID, side, amount, orderType = "FOK" /* FOK */) {
2251
+ const book = await this.getOrderBook(tokenID);
2252
+ if (!book) {
2253
+ throw new Error("no orderbook");
2254
+ }
2255
+ if (side === "BUY" /* BUY */) {
2256
+ if (!book.asks) {
2257
+ throw new Error("no match");
2258
+ }
2259
+ return calculateBuyMarketPrice(book.asks, amount, orderType);
2260
+ } else {
2261
+ if (!book.bids) {
2262
+ throw new Error("no match");
2263
+ }
2264
+ return calculateSellMarketPrice(book.bids, amount, orderType);
2265
+ }
2266
+ }
2267
+ async createBuilderApiKey() {
2268
+ this.canL2Auth();
2269
+ const endpoint = CREATE_BUILDER_API_KEY;
2270
+ const headerArgs = {
2271
+ method: POST,
2272
+ requestPath: endpoint
2273
+ };
2274
+ const headers = await createL2Headers(
2275
+ this.signer,
2276
+ this.creds,
2277
+ headerArgs,
2278
+ this.useServerTime ? await this.getServerTime() : void 0
2279
+ );
2280
+ return this.post(`${this.host}${endpoint}`, { headers });
2281
+ }
2282
+ async getBuilderApiKeys() {
2283
+ this.canL2Auth();
2284
+ const endpoint = GET_BUILDER_API_KEYS;
2285
+ const headerArgs = {
2286
+ method: GET,
2287
+ requestPath: endpoint
2288
+ };
2289
+ const headers = await createL2Headers(
2290
+ this.signer,
2291
+ this.creds,
2292
+ headerArgs,
2293
+ this.useServerTime ? await this.getServerTime() : void 0
2294
+ );
2295
+ return this.get(`${this.host}${endpoint}`, { headers });
2296
+ }
2297
+ async revokeBuilderApiKey() {
2298
+ this.canL2Auth();
2299
+ const endpoint = REVOKE_BUILDER_API_KEY;
2300
+ const headerArgs = {
2301
+ method: DELETE,
2302
+ requestPath: endpoint
2303
+ };
2304
+ const headers = await createL2Headers(
2305
+ this.signer,
2306
+ this.creds,
2307
+ headerArgs,
2308
+ this.useServerTime ? await this.getServerTime() : void 0
2309
+ );
2310
+ return this.del(`${this.host}${endpoint}`, { headers });
2311
+ }
2312
+ async getMarketTradesEvents(conditionID) {
2313
+ return this.get(`${this.host}${GET_MARKET_TRADES_EVENTS}${conditionID}`);
2314
+ }
2315
+ canL1Auth() {
2316
+ if (this.signer === void 0) {
2317
+ throw L1_AUTH_UNAVAILABLE_ERROR;
2318
+ }
2319
+ }
2320
+ canL2Auth() {
2321
+ if (this.signer === void 0) {
2322
+ throw L1_AUTH_UNAVAILABLE_ERROR;
2323
+ }
2324
+ if (this.creds === void 0) {
2325
+ throw L2_AUTH_NOT_AVAILABLE;
2326
+ }
2327
+ }
2328
+ isBuilderOrder(builderCode) {
2329
+ return builderCode !== void 0 && builderCode !== bytes32Zero;
2330
+ }
2331
+ async _ensureMarketInfoCached(tokenID) {
2332
+ if (tokenID in this.feeInfos) return;
2333
+ if (!(tokenID in this.tokenConditionMap)) {
2334
+ const result = await this.get(`${this.host}${GET_MARKET_BY_TOKEN}${tokenID}`);
2335
+ if (!result?.condition_id) {
2336
+ throw new Error(`failed to resolve condition id for token ${tokenID}`);
2337
+ }
2338
+ this.tokenConditionMap[tokenID] = result.condition_id;
2339
+ }
2340
+ await this.getClobMarketInfo(this.tokenConditionMap[tokenID]);
2341
+ }
2342
+ async ensureBuilderFeeRateCached(builderCode) {
2343
+ if (!builderCode || builderCode === bytes32Zero) return;
2344
+ if (builderCode in this.builderFeeRates) return;
2345
+ const result = await this.get(`${this.host}${GET_BUILDER_FEES}${builderCode}`);
2346
+ this.builderFeeRates[builderCode] = {
2347
+ maker: result.builder_maker_fee_rate_bps / BUILDER_FEES_BPS,
2348
+ taker: result.builder_taker_fee_rate_bps / BUILDER_FEES_BPS
2349
+ };
2350
+ }
2351
+ async _resolveTickSize(tokenID, tickSize) {
2352
+ const minTickSize = await this.getTickSize(tokenID);
2353
+ if (tickSize) {
2354
+ if (isTickSizeSmaller(tickSize, minTickSize)) {
2355
+ throw new Error(
2356
+ `invalid tick size (${tickSize}), minimum for the market is ${minTickSize}`
2357
+ );
2358
+ }
2359
+ } else {
2360
+ tickSize = minTickSize;
2361
+ }
2362
+ return tickSize;
2363
+ }
2364
+ async _resolveFeeRateBps(tokenID, userFeeRateBps) {
2365
+ const marketFeeRateBps = await this.getFeeRateBps(tokenID);
2366
+ if (marketFeeRateBps > 0 && userFeeRateBps !== void 0 && userFeeRateBps !== marketFeeRateBps) {
2367
+ throw new Error(
2368
+ `invalid user provided fee rate: ${userFeeRateBps}, fee rate for the market must be ${marketFeeRateBps}`
2369
+ );
2370
+ }
2371
+ return marketFeeRateBps;
2372
+ }
2373
+ async resolveVersion(forceUpdate = false) {
2374
+ if (!forceUpdate && this.cachedVersion !== void 0) {
2375
+ return this.cachedVersion;
2376
+ }
2377
+ const apiVersion = await this.getVersion();
2378
+ this.cachedVersion = apiVersion;
2379
+ return apiVersion;
2380
+ }
2381
+ async _retryOnVersionUpdate(retryFunc) {
2382
+ const version = await this.resolveVersion();
2383
+ for (let attempt = 0; attempt < 2; attempt++) {
2384
+ await retryFunc();
2385
+ if (version === await this.resolveVersion()) break;
2386
+ }
2387
+ }
2388
+ _isOrderVersionMismatch(resp) {
2389
+ const error = resp?.error;
2390
+ if (!error) return false;
2391
+ const message = typeof error === "string" ? error : JSON.stringify(error);
2392
+ return message.includes(ORDER_VERSION_MISMATCH_ERROR);
2393
+ }
2394
+ throwIfError(result) {
2395
+ if (this.throwOnError && result && typeof result === "object" && "error" in result) {
2396
+ const msg = typeof result.error === "string" ? result.error : JSON.stringify(result.error);
2397
+ throw new ApiError(msg, result.status, result);
2398
+ }
2399
+ return result;
2400
+ }
2401
+ // http methods
2402
+ async get(endpoint, options, skipThrow = false) {
2403
+ const result = await get(endpoint, options);
2404
+ return skipThrow ? result : this.throwIfError(result);
2405
+ }
2406
+ async post(endpoint, options, skipThrow = false) {
2407
+ const result = await post(endpoint, options, this.retryOnError);
2408
+ return skipThrow ? result : this.throwIfError(result);
2409
+ }
2410
+ async del(endpoint, options, skipThrow = false) {
2411
+ const result = await del(endpoint, options);
2412
+ return skipThrow ? result : this.throwIfError(result);
2413
+ }
2414
+ };
2415
+ export {
2416
+ ApiError,
2417
+ AssetType,
2418
+ COLLATERAL_TOKEN_DECIMALS,
2419
+ CONDITIONAL_TOKEN_DECIMALS,
2420
+ Chain,
2421
+ ClobClient,
2422
+ L1_AUTH_UNAVAILABLE_ERROR,
2423
+ L2_AUTH_NOT_AVAILABLE,
2424
+ OrderBuilder,
2425
+ OrderType,
2426
+ PriceHistoryInterval,
2427
+ Side,
2428
+ SignatureTypeV1,
2429
+ SignatureTypeV2,
2430
+ adjustBuyAmountForFees,
2431
+ createL1Headers,
2432
+ createL2Headers,
2433
+ getContractConfig,
2434
+ isV2Order,
2435
+ orderToJsonV1,
2436
+ orderToJsonV2
2437
+ };
8
2438
  //# sourceMappingURL=index.js.map