@polymarket/clob-client-v2 1.0.3-canary.0 → 1.0.4

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.
package/dist/index.d.cts CHANGED
@@ -69,7 +69,8 @@ interface OrderResponse {
69
69
  success: boolean;
70
70
  errorMsg: string;
71
71
  orderID: string;
72
- transactionsHashes: string[];
72
+ transactionsHashes?: string[];
73
+ tradeIDs?: string[];
73
74
  status: string;
74
75
  takingAmount: string;
75
76
  makingAmount: string;
@@ -103,7 +104,9 @@ interface MakerOrder {
103
104
  fee_rate_bps: string;
104
105
  asset_id: string;
105
106
  outcome: string;
106
- side: Side;
107
+ side?: Side;
108
+ builder_fee?: string;
109
+ builder_code?: string;
107
110
  }
108
111
  interface Trade {
109
112
  id: string;
@@ -116,13 +119,15 @@ interface Trade {
116
119
  price: string;
117
120
  status: string;
118
121
  match_time: string;
122
+ match_time_nano?: string;
119
123
  last_update: string;
120
124
  outcome: string;
121
125
  bucket_index: number;
122
126
  owner: string;
123
127
  maker_address: string;
124
128
  maker_orders: MakerOrder[];
125
- transaction_hash: string;
129
+ transaction_hash?: string;
130
+ err_msg?: string | null;
126
131
  trader_side: "TAKER" | "MAKER";
127
132
  }
128
133
  interface ApiKeysResponse {
@@ -207,7 +212,7 @@ interface BalanceAllowanceParams {
207
212
  }
208
213
  interface BalanceAllowanceResponse {
209
214
  balance: string;
210
- allowance: string;
215
+ allowances: Record<string, string>;
211
216
  }
212
217
  interface OrderScoringParams {
213
218
  order_id: string;
@@ -257,7 +262,14 @@ type TokenConditionMap = Record<string, string>;
257
262
  interface FeeDetails {
258
263
  r?: number;
259
264
  e?: number;
260
- to: boolean;
265
+ to?: boolean;
266
+ }
267
+ interface ClobRewards {
268
+ mi?: number;
269
+ ma?: number;
270
+ e?: boolean;
271
+ smoa?: boolean;
272
+ moas?: number;
261
273
  }
262
274
  interface ClobToken {
263
275
  t: string;
@@ -265,12 +277,22 @@ interface ClobToken {
265
277
  }
266
278
  interface MarketDetails {
267
279
  c: string;
268
- t: [ClobToken | null, ClobToken | null];
280
+ t: [ClobToken, ClobToken];
269
281
  mts: number;
270
- nr: boolean;
282
+ nr?: boolean;
271
283
  fd?: FeeDetails;
272
284
  mbf?: number;
273
285
  tbf?: number;
286
+ r: ClobRewards | null;
287
+ ao?: boolean;
288
+ mos?: number;
289
+ sd?: number;
290
+ gst?: string;
291
+ cbos?: boolean;
292
+ aot?: string;
293
+ rfqe?: boolean;
294
+ itode?: boolean;
295
+ ibce?: boolean;
274
296
  }
275
297
  interface PaginationPayload {
276
298
  readonly limit: number;
@@ -364,6 +386,8 @@ interface BuilderTrade {
364
386
  bucketIndex: number;
365
387
  fee: string;
366
388
  feeUsdc: string;
389
+ builderFee: string;
390
+ builderCode: string;
367
391
  err_msg?: string | null;
368
392
  createdAt: string | null;
369
393
  updatedAt: string | null;
@@ -585,6 +609,13 @@ interface UserOrderV2 {
585
609
  * Expiration timestamp (unix seconds). Defaults to 0 (no expiration).
586
610
  */
587
611
  expiration?: number;
612
+ /**
613
+ * User's USDC balance. If provided and sufficient to cover amount + fees, the order
614
+ * size is used as-is. Otherwise fees are deducted from the order notional and size is reduced.
615
+ * If this field is left empty, the default flow is to use the order size as-is.
616
+ * This is used for marketable limit orders
617
+ */
618
+ userUSDCBalance?: number;
588
619
  }
589
620
  interface UserMarketOrderV2 {
590
621
  /**
@@ -840,7 +871,8 @@ declare class OrderBuilder {
840
871
  private resolveSigner;
841
872
  }
842
873
 
843
- declare function adjustBuyAmountForFees(amount: number, price: number, userUSDCBalance: number, feeRate: number, feeExponent: number, builderTakerFeeRate: number): number;
874
+ declare function adjustBuyAmountForFees(amount: number, price: number, userUSDCBalance: number, feeRate: number, feeExponent: number, builderTakerFeeRate: number, feeSlippage?: number): number;
875
+
844
876
  interface ClobClientOptions {
845
877
  host: string;
846
878
  chain: Chain;
@@ -853,6 +885,7 @@ interface ClobClientOptions {
853
885
  getSigner?: () => Promise<ClobSigner> | ClobSigner;
854
886
  retryOnError?: boolean;
855
887
  throwOnError?: boolean;
888
+ feeSlippage?: number;
856
889
  }
857
890
  declare class ClobClient {
858
891
  readonly host: string;
@@ -873,7 +906,8 @@ declare class ClobClient {
873
906
  private cachedVersion?;
874
907
  readonly retryOnError?: boolean;
875
908
  readonly throwOnError?: boolean;
876
- constructor({ host, chain, signer, creds, signatureType, funderAddress, useServerTime, builderConfig, getSigner, retryOnError, throwOnError, }: ClobClientOptions);
909
+ readonly feeSlippage: number;
910
+ constructor({ host, chain, signer, creds, signatureType, funderAddress, useServerTime, builderConfig, getSigner, retryOnError, throwOnError, feeSlippage, }: ClobClientOptions);
877
911
  getOk(): Promise<any>;
878
912
  postHeartbeat(heartbeatId?: string): Promise<{
879
913
  heartbeat_id: string;
@@ -898,7 +932,7 @@ declare class ClobClient {
898
932
  * @param orderbook
899
933
  * @returns
900
934
  */
901
- getOrderBookHash(orderbook: OrderBookSummary): string;
935
+ getOrderBookHash(orderbook: OrderBookSummary): Promise<string>;
902
936
  getMidpoint(tokenID: string): Promise<any>;
903
937
  getMidpoints(params: BookParams[]): Promise<any>;
904
938
  getPrice(tokenID: string, side: string): Promise<any>;
@@ -963,6 +997,8 @@ declare class ClobClient {
963
997
  private canL1Auth;
964
998
  private canL2Auth;
965
999
  private isBuilderOrder;
1000
+ private getBuilderTakerFeeRate;
1001
+ private adjustBuyAmountForBalance;
966
1002
  private _ensureMarketInfoCached;
967
1003
  private ensureBuilderFeeRateCached;
968
1004
  private _resolveTickSize;
@@ -1000,4 +1036,4 @@ declare class ApiError extends Error {
1000
1036
  declare const createL1Headers: (signer: ClobSigner, chainId: Chain, nonce?: number, timestamp?: number, address?: string) => Promise<L1PolyHeader>;
1001
1037
  declare const createL2Headers: (signer: ClobSigner, creds: ApiKeyCreds, l2HeaderArgs: L2HeaderArgs, timestamp?: number) => Promise<L2PolyHeader>;
1002
1038
 
1003
- export { ApiError, type ApiKeyCreds, type ApiKeyRaw, type ApiKeysResponse, AssetType, type BalanceAllowanceParams, type BalanceAllowanceResponse, type BanStatus, type BookParams, type BuilderApiKey, type BuilderApiKeyResponse, type BuilderConfig, type BuilderFeeRates, type BuilderTrade, type BuilderTradeParams, type BuilderTradesResponse, COLLATERAL_TOKEN_DECIMALS, CONDITIONAL_TOKEN_DECIMALS, Chain, ClobClient, type ClobClientOptions, type ClobErrorResponseBody, type ClobToken, type ContractConfig, type CreateOrderOptions, type DropNotificationParams, type Earning, type FeeDetails, type FeeInfo, type FeeInfos, type FeeRates, type L1PolyHeader, L1_AUTH_UNAVAILABLE_ERROR, type L2HeaderArgs, type L2PolyHeader, L2_AUTH_NOT_AVAILABLE, type MakerOrder, type MarketDetails, type MarketPrice, type MarketReward, type MarketTradeEvent, type NegRisk, type NewOrderV1, type NewOrderV2, type Notification, type OpenOrder, type OpenOrderParams, type OpenOrdersResponse, type OrderBookSummary, OrderBuilder, type OrderMarketCancelParams, type OrderPayload, type OrderResponse, type OrderScoring, type OrderScoringParams, type OrderSummary, OrderType, type OrdersScoring, type OrdersScoringParams, type PaginationPayload, type PostOrdersArgs, type PostOrdersV1Args, type PostOrdersV2Args, type PreMigrationOrder, type PreMigrationOrdersResponse, type PriceHistoryFilterParams, PriceHistoryInterval, type ReadonlyApiKeyResponse, type RewardsConfig, type RewardsPercentages, type RoundConfig, Side, SignatureTypeV1, SignatureTypeV2, type SignedOrder, type SimpleHeaders, type TickSize, type TickSizes, type Token, type TokenConditionMap, type TotalUserEarning, type Trade, type TradeParams, type TradesPaginatedResponse, type UserEarning, type UserMarketOrderV1, type UserMarketOrderV2, type UserOrderV1, type UserOrderV2, type UserRewardsEarning, type VersionedPostOrdersArgs, type VersionedSignedOrder, type VersionedUserMarketOrder, type VersionedUserOrder, adjustBuyAmountForFees, createL1Headers, createL2Headers, getContractConfig, isV2Order, orderToJsonV1, orderToJsonV2 };
1039
+ export { ApiError, type ApiKeyCreds, type ApiKeyRaw, type ApiKeysResponse, AssetType, type BalanceAllowanceParams, type BalanceAllowanceResponse, type BanStatus, type BookParams, type BuilderApiKey, type BuilderApiKeyResponse, type BuilderConfig, type BuilderFeeRates, type BuilderTrade, type BuilderTradeParams, type BuilderTradesResponse, COLLATERAL_TOKEN_DECIMALS, CONDITIONAL_TOKEN_DECIMALS, Chain, ClobClient, type ClobClientOptions, type ClobErrorResponseBody, type ClobRewards, type ClobToken, type ContractConfig, type CreateOrderOptions, type DropNotificationParams, type Earning, type FeeDetails, type FeeInfo, type FeeInfos, type FeeRates, type L1PolyHeader, L1_AUTH_UNAVAILABLE_ERROR, type L2HeaderArgs, type L2PolyHeader, L2_AUTH_NOT_AVAILABLE, type MakerOrder, type MarketDetails, type MarketPrice, type MarketReward, type MarketTradeEvent, type NegRisk, type NewOrderV1, type NewOrderV2, type Notification, type OpenOrder, type OpenOrderParams, type OpenOrdersResponse, type OrderBookSummary, OrderBuilder, type OrderMarketCancelParams, type OrderPayload, type OrderResponse, type OrderScoring, type OrderScoringParams, type OrderSummary, OrderType, type OrdersScoring, type OrdersScoringParams, type PaginationPayload, type PostOrdersArgs, type PostOrdersV1Args, type PostOrdersV2Args, type PreMigrationOrder, type PreMigrationOrdersResponse, type PriceHistoryFilterParams, PriceHistoryInterval, type ReadonlyApiKeyResponse, type RewardsConfig, type RewardsPercentages, type RoundConfig, Side, SignatureTypeV1, SignatureTypeV2, type SignedOrder, type SimpleHeaders, type TickSize, type TickSizes, type Token, type TokenConditionMap, type TotalUserEarning, type Trade, type TradeParams, type TradesPaginatedResponse, type UserEarning, type UserMarketOrderV1, type UserMarketOrderV2, type UserOrderV1, type UserOrderV2, type UserRewardsEarning, type VersionedPostOrdersArgs, type VersionedSignedOrder, type VersionedUserMarketOrder, type VersionedUserOrder, adjustBuyAmountForFees, createL1Headers, createL2Headers, getContractConfig, isV2Order, orderToJsonV1, orderToJsonV2 };
package/dist/index.d.ts CHANGED
@@ -69,7 +69,8 @@ interface OrderResponse {
69
69
  success: boolean;
70
70
  errorMsg: string;
71
71
  orderID: string;
72
- transactionsHashes: string[];
72
+ transactionsHashes?: string[];
73
+ tradeIDs?: string[];
73
74
  status: string;
74
75
  takingAmount: string;
75
76
  makingAmount: string;
@@ -103,7 +104,9 @@ interface MakerOrder {
103
104
  fee_rate_bps: string;
104
105
  asset_id: string;
105
106
  outcome: string;
106
- side: Side;
107
+ side?: Side;
108
+ builder_fee?: string;
109
+ builder_code?: string;
107
110
  }
108
111
  interface Trade {
109
112
  id: string;
@@ -116,13 +119,15 @@ interface Trade {
116
119
  price: string;
117
120
  status: string;
118
121
  match_time: string;
122
+ match_time_nano?: string;
119
123
  last_update: string;
120
124
  outcome: string;
121
125
  bucket_index: number;
122
126
  owner: string;
123
127
  maker_address: string;
124
128
  maker_orders: MakerOrder[];
125
- transaction_hash: string;
129
+ transaction_hash?: string;
130
+ err_msg?: string | null;
126
131
  trader_side: "TAKER" | "MAKER";
127
132
  }
128
133
  interface ApiKeysResponse {
@@ -207,7 +212,7 @@ interface BalanceAllowanceParams {
207
212
  }
208
213
  interface BalanceAllowanceResponse {
209
214
  balance: string;
210
- allowance: string;
215
+ allowances: Record<string, string>;
211
216
  }
212
217
  interface OrderScoringParams {
213
218
  order_id: string;
@@ -257,7 +262,14 @@ type TokenConditionMap = Record<string, string>;
257
262
  interface FeeDetails {
258
263
  r?: number;
259
264
  e?: number;
260
- to: boolean;
265
+ to?: boolean;
266
+ }
267
+ interface ClobRewards {
268
+ mi?: number;
269
+ ma?: number;
270
+ e?: boolean;
271
+ smoa?: boolean;
272
+ moas?: number;
261
273
  }
262
274
  interface ClobToken {
263
275
  t: string;
@@ -265,12 +277,22 @@ interface ClobToken {
265
277
  }
266
278
  interface MarketDetails {
267
279
  c: string;
268
- t: [ClobToken | null, ClobToken | null];
280
+ t: [ClobToken, ClobToken];
269
281
  mts: number;
270
- nr: boolean;
282
+ nr?: boolean;
271
283
  fd?: FeeDetails;
272
284
  mbf?: number;
273
285
  tbf?: number;
286
+ r: ClobRewards | null;
287
+ ao?: boolean;
288
+ mos?: number;
289
+ sd?: number;
290
+ gst?: string;
291
+ cbos?: boolean;
292
+ aot?: string;
293
+ rfqe?: boolean;
294
+ itode?: boolean;
295
+ ibce?: boolean;
274
296
  }
275
297
  interface PaginationPayload {
276
298
  readonly limit: number;
@@ -364,6 +386,8 @@ interface BuilderTrade {
364
386
  bucketIndex: number;
365
387
  fee: string;
366
388
  feeUsdc: string;
389
+ builderFee: string;
390
+ builderCode: string;
367
391
  err_msg?: string | null;
368
392
  createdAt: string | null;
369
393
  updatedAt: string | null;
@@ -585,6 +609,13 @@ interface UserOrderV2 {
585
609
  * Expiration timestamp (unix seconds). Defaults to 0 (no expiration).
586
610
  */
587
611
  expiration?: number;
612
+ /**
613
+ * User's USDC balance. If provided and sufficient to cover amount + fees, the order
614
+ * size is used as-is. Otherwise fees are deducted from the order notional and size is reduced.
615
+ * If this field is left empty, the default flow is to use the order size as-is.
616
+ * This is used for marketable limit orders
617
+ */
618
+ userUSDCBalance?: number;
588
619
  }
589
620
  interface UserMarketOrderV2 {
590
621
  /**
@@ -840,7 +871,8 @@ declare class OrderBuilder {
840
871
  private resolveSigner;
841
872
  }
842
873
 
843
- declare function adjustBuyAmountForFees(amount: number, price: number, userUSDCBalance: number, feeRate: number, feeExponent: number, builderTakerFeeRate: number): number;
874
+ declare function adjustBuyAmountForFees(amount: number, price: number, userUSDCBalance: number, feeRate: number, feeExponent: number, builderTakerFeeRate: number, feeSlippage?: number): number;
875
+
844
876
  interface ClobClientOptions {
845
877
  host: string;
846
878
  chain: Chain;
@@ -853,6 +885,7 @@ interface ClobClientOptions {
853
885
  getSigner?: () => Promise<ClobSigner> | ClobSigner;
854
886
  retryOnError?: boolean;
855
887
  throwOnError?: boolean;
888
+ feeSlippage?: number;
856
889
  }
857
890
  declare class ClobClient {
858
891
  readonly host: string;
@@ -873,7 +906,8 @@ declare class ClobClient {
873
906
  private cachedVersion?;
874
907
  readonly retryOnError?: boolean;
875
908
  readonly throwOnError?: boolean;
876
- constructor({ host, chain, signer, creds, signatureType, funderAddress, useServerTime, builderConfig, getSigner, retryOnError, throwOnError, }: ClobClientOptions);
909
+ readonly feeSlippage: number;
910
+ constructor({ host, chain, signer, creds, signatureType, funderAddress, useServerTime, builderConfig, getSigner, retryOnError, throwOnError, feeSlippage, }: ClobClientOptions);
877
911
  getOk(): Promise<any>;
878
912
  postHeartbeat(heartbeatId?: string): Promise<{
879
913
  heartbeat_id: string;
@@ -898,7 +932,7 @@ declare class ClobClient {
898
932
  * @param orderbook
899
933
  * @returns
900
934
  */
901
- getOrderBookHash(orderbook: OrderBookSummary): string;
935
+ getOrderBookHash(orderbook: OrderBookSummary): Promise<string>;
902
936
  getMidpoint(tokenID: string): Promise<any>;
903
937
  getMidpoints(params: BookParams[]): Promise<any>;
904
938
  getPrice(tokenID: string, side: string): Promise<any>;
@@ -963,6 +997,8 @@ declare class ClobClient {
963
997
  private canL1Auth;
964
998
  private canL2Auth;
965
999
  private isBuilderOrder;
1000
+ private getBuilderTakerFeeRate;
1001
+ private adjustBuyAmountForBalance;
966
1002
  private _ensureMarketInfoCached;
967
1003
  private ensureBuilderFeeRateCached;
968
1004
  private _resolveTickSize;
@@ -1000,4 +1036,4 @@ declare class ApiError extends Error {
1000
1036
  declare const createL1Headers: (signer: ClobSigner, chainId: Chain, nonce?: number, timestamp?: number, address?: string) => Promise<L1PolyHeader>;
1001
1037
  declare const createL2Headers: (signer: ClobSigner, creds: ApiKeyCreds, l2HeaderArgs: L2HeaderArgs, timestamp?: number) => Promise<L2PolyHeader>;
1002
1038
 
1003
- export { ApiError, type ApiKeyCreds, type ApiKeyRaw, type ApiKeysResponse, AssetType, type BalanceAllowanceParams, type BalanceAllowanceResponse, type BanStatus, type BookParams, type BuilderApiKey, type BuilderApiKeyResponse, type BuilderConfig, type BuilderFeeRates, type BuilderTrade, type BuilderTradeParams, type BuilderTradesResponse, COLLATERAL_TOKEN_DECIMALS, CONDITIONAL_TOKEN_DECIMALS, Chain, ClobClient, type ClobClientOptions, type ClobErrorResponseBody, type ClobToken, type ContractConfig, type CreateOrderOptions, type DropNotificationParams, type Earning, type FeeDetails, type FeeInfo, type FeeInfos, type FeeRates, type L1PolyHeader, L1_AUTH_UNAVAILABLE_ERROR, type L2HeaderArgs, type L2PolyHeader, L2_AUTH_NOT_AVAILABLE, type MakerOrder, type MarketDetails, type MarketPrice, type MarketReward, type MarketTradeEvent, type NegRisk, type NewOrderV1, type NewOrderV2, type Notification, type OpenOrder, type OpenOrderParams, type OpenOrdersResponse, type OrderBookSummary, OrderBuilder, type OrderMarketCancelParams, type OrderPayload, type OrderResponse, type OrderScoring, type OrderScoringParams, type OrderSummary, OrderType, type OrdersScoring, type OrdersScoringParams, type PaginationPayload, type PostOrdersArgs, type PostOrdersV1Args, type PostOrdersV2Args, type PreMigrationOrder, type PreMigrationOrdersResponse, type PriceHistoryFilterParams, PriceHistoryInterval, type ReadonlyApiKeyResponse, type RewardsConfig, type RewardsPercentages, type RoundConfig, Side, SignatureTypeV1, SignatureTypeV2, type SignedOrder, type SimpleHeaders, type TickSize, type TickSizes, type Token, type TokenConditionMap, type TotalUserEarning, type Trade, type TradeParams, type TradesPaginatedResponse, type UserEarning, type UserMarketOrderV1, type UserMarketOrderV2, type UserOrderV1, type UserOrderV2, type UserRewardsEarning, type VersionedPostOrdersArgs, type VersionedSignedOrder, type VersionedUserMarketOrder, type VersionedUserOrder, adjustBuyAmountForFees, createL1Headers, createL2Headers, getContractConfig, isV2Order, orderToJsonV1, orderToJsonV2 };
1039
+ export { ApiError, type ApiKeyCreds, type ApiKeyRaw, type ApiKeysResponse, AssetType, type BalanceAllowanceParams, type BalanceAllowanceResponse, type BanStatus, type BookParams, type BuilderApiKey, type BuilderApiKeyResponse, type BuilderConfig, type BuilderFeeRates, type BuilderTrade, type BuilderTradeParams, type BuilderTradesResponse, COLLATERAL_TOKEN_DECIMALS, CONDITIONAL_TOKEN_DECIMALS, Chain, ClobClient, type ClobClientOptions, type ClobErrorResponseBody, type ClobRewards, type ClobToken, type ContractConfig, type CreateOrderOptions, type DropNotificationParams, type Earning, type FeeDetails, type FeeInfo, type FeeInfos, type FeeRates, type L1PolyHeader, L1_AUTH_UNAVAILABLE_ERROR, type L2HeaderArgs, type L2PolyHeader, L2_AUTH_NOT_AVAILABLE, type MakerOrder, type MarketDetails, type MarketPrice, type MarketReward, type MarketTradeEvent, type NegRisk, type NewOrderV1, type NewOrderV2, type Notification, type OpenOrder, type OpenOrderParams, type OpenOrdersResponse, type OrderBookSummary, OrderBuilder, type OrderMarketCancelParams, type OrderPayload, type OrderResponse, type OrderScoring, type OrderScoringParams, type OrderSummary, OrderType, type OrdersScoring, type OrdersScoringParams, type PaginationPayload, type PostOrdersArgs, type PostOrdersV1Args, type PostOrdersV2Args, type PreMigrationOrder, type PreMigrationOrdersResponse, type PriceHistoryFilterParams, PriceHistoryInterval, type ReadonlyApiKeyResponse, type RewardsConfig, type RewardsPercentages, type RoundConfig, Side, SignatureTypeV1, SignatureTypeV2, type SignedOrder, type SimpleHeaders, type TickSize, type TickSizes, type Token, type TokenConditionMap, type TotalUserEarning, type Trade, type TradeParams, type TradesPaginatedResponse, type UserEarning, type UserMarketOrderV1, type UserMarketOrderV2, type UserOrderV1, type UserOrderV2, type UserRewardsEarning, type VersionedPostOrdersArgs, type VersionedSignedOrder, type VersionedUserMarketOrder, type VersionedUserOrder, adjustBuyAmountForFees, createL1Headers, createL2Headers, getContractConfig, isV2Order, orderToJsonV1, orderToJsonV2 };
package/dist/index.js CHANGED
@@ -85,6 +85,28 @@ var ApiError = class extends Error {
85
85
  }
86
86
  };
87
87
 
88
+ // src/fees/index.ts
89
+ var MIN_FEE_SLIPPAGE_PERCENTAGE = 1;
90
+ var MAX_FEE_SLIPPAGE_PERCENTAGE = 100;
91
+ function validateFeeSlippage(feeSlippage) {
92
+ if (!Number.isFinite(feeSlippage) || feeSlippage < 0 || feeSlippage > MAX_FEE_SLIPPAGE_PERCENTAGE || feeSlippage > 0 && feeSlippage < MIN_FEE_SLIPPAGE_PERCENTAGE) {
93
+ throw new Error("feeSlippage must be 0 or a percentage between 1 and 100");
94
+ }
95
+ }
96
+ function adjustBuyAmountForFees(amount, price, userUSDCBalance, feeRate, feeExponent, builderTakerFeeRate, feeSlippage = 0) {
97
+ validateFeeSlippage(feeSlippage);
98
+ const platformFeeRate = feeRate * (price * (1 - price)) ** feeExponent;
99
+ const effectivePlatformFeeRate = platformFeeRate * (1 + feeSlippage / 100);
100
+ const feeBaseAmount = Math.min(amount, userUSDCBalance);
101
+ const platformFee = feeBaseAmount / price * effectivePlatformFeeRate;
102
+ const builderFee = feeBaseAmount * builderTakerFeeRate;
103
+ const totalCost = amount + platformFee + builderFee;
104
+ if (userUSDCBalance <= totalCost) {
105
+ return Math.max(userUSDCBalance - platformFee - builderFee, 0);
106
+ }
107
+ return amount;
108
+ }
109
+
88
110
  // src/signing/constants.ts
89
111
  var MSG_TO_SIGN = "This message attests that I control the given wallet";
90
112
 
@@ -179,20 +201,34 @@ var buildClobEip712Signature = async (signer, chainId, timestamp, nonce, address
179
201
  };
180
202
 
181
203
  // 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) => {
204
+ var buildPolyHmacSignature = async (secret, timestamp, method, requestPath, body) => {
187
205
  let message = timestamp + method + requestPath;
188
206
  if (body !== void 0) {
189
207
  message += body;
190
208
  }
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;
209
+ const binarySecret = atob(secret);
210
+ const keyBytes = new Uint8Array(binarySecret.length);
211
+ for (let i = 0; i < binarySecret.length; i++) {
212
+ keyBytes[i] = binarySecret.charCodeAt(i);
213
+ }
214
+ const key = await globalThis.crypto.subtle.importKey(
215
+ "raw",
216
+ keyBytes,
217
+ { name: "HMAC", hash: "SHA-256" },
218
+ false,
219
+ ["sign"]
220
+ );
221
+ const sigBuffer = await globalThis.crypto.subtle.sign(
222
+ "HMAC",
223
+ key,
224
+ new TextEncoder().encode(message)
225
+ );
226
+ const sigBytes = new Uint8Array(sigBuffer);
227
+ let binary = "";
228
+ for (let i = 0; i < sigBytes.length; i++) {
229
+ binary += String.fromCharCode(sigBytes[i]);
230
+ }
231
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_");
196
232
  };
197
233
 
198
234
  // src/headers/index.ts
@@ -221,7 +257,7 @@ var createL2Headers = async (signer, creds, l2HeaderArgs, timestamp) => {
221
257
  ts = timestamp;
222
258
  }
223
259
  const address = await getSignerAddress(signer);
224
- const sig = buildPolyHmacSignature(
260
+ const sig = await buildPolyHmacSignature(
225
261
  creds.secret,
226
262
  ts,
227
263
  l2HeaderArgs.method,
@@ -273,7 +309,6 @@ var post = async (endpoint, options, retryOnError = false) => {
273
309
  return resp.data;
274
310
  } catch (err) {
275
311
  if (retryOnError && isTransientAxiosError(err)) {
276
- console.log("[CLOB Client-v2] transient error, retrying once after 30 ms");
277
312
  await sleep(30);
278
313
  try {
279
314
  const resp = await request(
@@ -316,15 +351,6 @@ var del = async (endpoint, options) => {
316
351
  var errorHandling = (err) => {
317
352
  if (axios.isAxiosError(err)) {
318
353
  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
354
  if (err.response?.data) {
329
355
  if (typeof err.response?.data === "string" || err.response?.data instanceof String) {
330
356
  return { error: err.response?.data, status: err.response?.status };
@@ -336,16 +362,9 @@ var errorHandling = (err) => {
336
362
  }
337
363
  }
338
364
  if (err.message) {
339
- console.error(
340
- "[CLOB Client] request error",
341
- JSON.stringify({
342
- error: err.message
343
- })
344
- );
345
365
  return { error: err.message };
346
366
  }
347
367
  }
348
- console.error("[CLOB Client] request error", err);
349
368
  return { error: err };
350
369
  };
351
370
  var isTransientAxiosError = (err) => {
@@ -974,7 +993,6 @@ function isV2Order(order) {
974
993
  }
975
994
 
976
995
  // src/utilities.ts
977
- import { createHash } from "crypto";
978
996
  var roundNormal = (num, decimals) => {
979
997
  if (decimalPlaces(num) <= decimals) {
980
998
  return num;
@@ -1003,9 +1021,12 @@ var decimalPlaces = (num) => {
1003
1021
  }
1004
1022
  return arr[1].length;
1005
1023
  };
1006
- var generateOrderBookSummaryHash = (orderbook) => {
1024
+ var generateOrderBookSummaryHash = async (orderbook) => {
1007
1025
  orderbook.hash = "";
1008
- const hash = createHash("sha1").update(JSON.stringify(orderbook)).digest("hex");
1026
+ const data = new TextEncoder().encode(JSON.stringify(orderbook));
1027
+ const hashBuffer = await globalThis.crypto.subtle.digest("SHA-1", data);
1028
+ const hashArray = Array.from(new Uint8Array(hashBuffer));
1029
+ const hash = hashArray.map((b) => b.toString(16).padStart(2, "0")).join("");
1009
1030
  orderbook.hash = hash;
1010
1031
  return hash;
1011
1032
  };
@@ -1316,15 +1337,6 @@ var OrderBuilder = class {
1316
1337
  };
1317
1338
 
1318
1339
  // src/client.ts
1319
- function adjustBuyAmountForFees(amount, price, userUSDCBalance, feeRate, feeExponent, builderTakerFeeRate) {
1320
- const platformFeeRate = feeRate * (price * (1 - price)) ** feeExponent;
1321
- const platformFee = amount / price * platformFeeRate;
1322
- const totalCost = amount + platformFee + amount * builderTakerFeeRate;
1323
- if (userUSDCBalance <= totalCost) {
1324
- return userUSDCBalance / (1 + platformFeeRate / price + builderTakerFeeRate);
1325
- }
1326
- return amount;
1327
- }
1328
1340
  var ClobClient = class {
1329
1341
  host;
1330
1342
  chainId;
@@ -1347,6 +1359,7 @@ var ClobClient = class {
1347
1359
  cachedVersion;
1348
1360
  retryOnError;
1349
1361
  throwOnError;
1362
+ feeSlippage;
1350
1363
  constructor({
1351
1364
  host,
1352
1365
  chain,
@@ -1358,7 +1371,8 @@ var ClobClient = class {
1358
1371
  builderConfig,
1359
1372
  getSigner,
1360
1373
  retryOnError,
1361
- throwOnError
1374
+ throwOnError,
1375
+ feeSlippage
1362
1376
  }) {
1363
1377
  this.host = host.endsWith("/") ? host.slice(0, -1) : host;
1364
1378
  this.chainId = chain;
@@ -1385,6 +1399,8 @@ var ClobClient = class {
1385
1399
  this.tokenConditionMap = {};
1386
1400
  this.retryOnError = retryOnError;
1387
1401
  this.throwOnError = throwOnError;
1402
+ this.feeSlippage = feeSlippage ?? 0;
1403
+ validateFeeSlippage(this.feeSlippage);
1388
1404
  this.useServerTime = useServerTime;
1389
1405
  if (builderConfig !== void 0) {
1390
1406
  this.builderConfig = builderConfig;
@@ -1518,7 +1534,7 @@ var ClobClient = class {
1518
1534
  * @param orderbook
1519
1535
  * @returns
1520
1536
  */
1521
- getOrderBookHash(orderbook) {
1537
+ async getOrderBookHash(orderbook) {
1522
1538
  return generateOrderBookSummaryHash(orderbook);
1523
1539
  }
1524
1540
  async getMidpoint(tokenID) {
@@ -1882,8 +1898,19 @@ var ClobClient = class {
1882
1898
  `invalid price (${orderToSign.price}), min: ${parseFloat(tickSize)} - max: ${1 - parseFloat(tickSize)}`
1883
1899
  );
1884
1900
  }
1885
- const negRisk = options?.negRisk ?? await this.getNegRisk(tokenID);
1901
+ orderToSign.price = roundNormal(orderToSign.price, ROUNDING_CONFIG[tickSize].price);
1886
1902
  const version = await this.resolveVersion();
1903
+ if (version === 2 && orderToSign.side === "BUY" /* BUY */ && "userUSDCBalance" in orderToSign && orderToSign.userUSDCBalance !== void 0) {
1904
+ const adjustedAmount = await this.adjustBuyAmountForBalance(
1905
+ tokenID,
1906
+ orderToSign.size * orderToSign.price,
1907
+ orderToSign.price,
1908
+ orderToSign.userUSDCBalance,
1909
+ orderToSign.builderCode
1910
+ );
1911
+ orderToSign.size = adjustedAmount / orderToSign.price;
1912
+ }
1913
+ const negRisk = options?.negRisk ?? await this.getNegRisk(tokenID);
1887
1914
  if (version === 1) {
1888
1915
  const userFeeRateBps = "feeRateBps" in orderToSign ? orderToSign.feeRateBps : void 0;
1889
1916
  const feeRateBps = await this._resolveFeeRateBps(tokenID, userFeeRateBps);
@@ -1923,15 +1950,12 @@ var ClobClient = class {
1923
1950
  await this.ensureBuilderFeeRateCached(orderToSign.builderCode);
1924
1951
  if (orderToSign.side === "BUY" /* BUY */ && "userUSDCBalance" in orderToSign && orderToSign.userUSDCBalance !== void 0) {
1925
1952
  const price = orderToSign.price;
1926
- const { userUSDCBalance } = orderToSign;
1927
- const builderTakerFeeRate = this.isBuilderOrder(orderToSign.builderCode) ? this.builderFeeRates[orderToSign.builderCode ?? ""]?.taker ?? 0 : 0;
1928
- orderToSign.amount = adjustBuyAmountForFees(
1953
+ orderToSign.amount = await this.adjustBuyAmountForBalance(
1954
+ tokenID,
1929
1955
  orderToSign.amount,
1930
1956
  price,
1931
- userUSDCBalance,
1932
- this.feeInfos[tokenID].rate,
1933
- this.feeInfos[tokenID].exponent,
1934
- builderTakerFeeRate
1957
+ orderToSign.userUSDCBalance,
1958
+ orderToSign.builderCode
1935
1959
  );
1936
1960
  }
1937
1961
  const negRisk = options?.negRisk ?? await this.getNegRisk(tokenID);
@@ -2391,6 +2415,24 @@ var ClobClient = class {
2391
2415
  isBuilderOrder(builderCode) {
2392
2416
  return builderCode !== void 0 && builderCode !== bytes32Zero;
2393
2417
  }
2418
+ async getBuilderTakerFeeRate(builderCode) {
2419
+ if (!this.isBuilderOrder(builderCode)) return 0;
2420
+ await this.ensureBuilderFeeRateCached(builderCode);
2421
+ return this.builderFeeRates[builderCode ?? ""]?.taker ?? 0;
2422
+ }
2423
+ async adjustBuyAmountForBalance(tokenID, amount, price, userUSDCBalance, builderCode) {
2424
+ await this._ensureMarketInfoCached(tokenID);
2425
+ const builderTakerFeeRate = await this.getBuilderTakerFeeRate(builderCode);
2426
+ return adjustBuyAmountForFees(
2427
+ amount,
2428
+ price,
2429
+ userUSDCBalance,
2430
+ this.feeInfos[tokenID].rate,
2431
+ this.feeInfos[tokenID].exponent,
2432
+ builderTakerFeeRate,
2433
+ this.feeSlippage
2434
+ );
2435
+ }
2394
2436
  async _ensureMarketInfoCached(tokenID) {
2395
2437
  if (tokenID in this.feeInfos) return;
2396
2438
  if (!(tokenID in this.tokenConditionMap)) {