@polymarket/clob-client-v2 0.0.3 → 0.2.0

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