@polymarket/client 0.1.0-beta.0 → 0.1.0-beta.10

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.
@@ -1,5 +1,5 @@
1
1
  import { ethers } from 'ethers-v5';
2
- import { T as TypedDataPayload, a as TypedData, S as Signer } from './types-D7tLX0ye.js';
2
+ import { T as TypedDataPayload, a as TypedData, S as Signer } from './types-M1U0um0G.js';
3
3
  import '@polymarket/bindings';
4
4
  import '@polymarket/types';
5
5
  import '@polymarket/bindings/gamma';
@@ -7,6 +7,8 @@ import '@polymarket/bindings/relayer';
7
7
  import 'zod';
8
8
  import '@polymarket/bindings/clob';
9
9
  import '@polymarket/bindings/data';
10
+ import '@polymarket/bindings/rfq';
11
+ import '@polymarket/bindings/perps';
10
12
  import '@polymarket/bindings/subscriptions';
11
13
  import 'ox';
12
14
 
package/dist/index.d.ts CHANGED
@@ -1,21 +1,29 @@
1
- import { ConditionId } from '@polymarket/bindings';
1
+ import { CtfConditionId, ComboConditionId } from '@polymarket/bindings';
2
2
  export * from '@polymarket/bindings';
3
3
  export { OrderSide, OrderType } from '@polymarket/bindings';
4
4
  export * from '@polymarket/bindings/clob';
5
- export { SignatureType } from '@polymarket/bindings/clob';
5
+ export { PriceHistoryInterval, SignatureType } from '@polymarket/bindings/clob';
6
6
  export * from '@polymarket/bindings/data';
7
- export { ActivityType } from '@polymarket/bindings/data';
7
+ export { ActivityType, ComboPositionStatus } from '@polymarket/bindings/data';
8
8
  export * from '@polymarket/bindings/gamma';
9
9
  export { WalletType } from '@polymarket/bindings/gamma';
10
+ export * from '@polymarket/bindings/perps';
11
+ export { PerpsCancelOrderResult, PerpsDepositStatus, PerpsInstrumentCategory, PerpsInstrumentType, PerpsInternalTransferDirection, PerpsKlineInterval, PerpsOrderStatus, PerpsPostOrderAck, PerpsSide, PerpsTimeInForce, PerpsWithdrawalStatus } from '@polymarket/bindings/perps';
10
12
  export * from '@polymarket/bindings/relayer';
11
13
  import { EvmAddress } from '@polymarket/types';
12
- import { U as UserInputError, b as TransactionCall, A as ApiKeyAuthorization } from './types-D7tLX0ye.js';
13
- export { c as AccountIdentity, d as AnalyticsActions, e as ApproveErc1155ForAllError, f as ApproveErc20Error, B as BaseClient, g as BasePublicClient, h as BaseSecureClient, i as BeginAuthenticationRequest, C as CancelAllError, j as CancelMarketOrdersError, k as CancelOrderError, l as CancelOrdersError, m as CancelledSigningError, n as Client, o as ClientActions, p as ClientDecorator, q as CreateSecureClientError, D as DataActions, r as DiscoveryActions, s as DownloadAccountingSnapshotError, t as DropNotificationsError, E as EnvironmentConfig, u as EstimateMarketPriceError, F as FetchClosedOnlyModeError, v as FetchCommentsByIdError, w as FetchEventError, x as FetchEventLiveVolumeError, y as FetchEventTagsError, z as FetchLastTradePriceError, G as FetchLastTradePricesError, H as FetchMarketError, I as FetchMarketTagsError, J as FetchMidpointError, K as FetchMidpointsError, L as FetchNotificationsError, M as FetchOrderBookError, N as FetchOrderBooksError, O as FetchOrderError, P as FetchOrderScoringError, Q as FetchOrdersScoringError, R as FetchPortfolioValueError, V as FetchPriceError, W as FetchPriceHistoryError, X as FetchPricesError, Y as FetchPublicProfileError, Z as FetchRelatedTagResourcesError, _ as FetchRelatedTagsError, $ as FetchRewardPercentagesError, a0 as FetchSeriesError, a1 as FetchSpreadError, a2 as FetchSpreadsError, a3 as FetchTagError, a4 as FetchTotalEarningsForUserForDayError, a5 as FetchTradedMarketCountError, a6 as InsufficientLiquidityError, a7 as IsGaslessReadyError, a8 as ListAccountTradesError, a9 as ListActivityError, aa as ListBuilderLeaderboardError, ab as ListBuilderTradesError, ac as ListBuilderVolumeError, ad as ListClosedPositionsError, ae as ListCommentsByUserAddressError, af as ListCommentsError, ag as ListCurrentRewardsError, ah as ListEventsError, ai as ListMarketHoldersError, aj as ListMarketPositionsError, ak as ListMarketRewardsError, al as ListMarketsError, am as ListOpenInterestError, an as ListOpenOrdersError, ao as ListPositionsError, ap as ListSeriesError, aq as ListTagsError, ar as ListTeamsError, as as ListTraderLeaderboardError, at as ListTradesError, au as ListUserEarningsAndMarketsConfigError, av as ListUserEarningsForDayError, aw as MergePositionsError, ax as Page, ay as PageSizeSchema, az as Paginated, aA as PostOrderError, aB as PostOrdersError, aC as PublicAccountActions, aD as PublicActions, aE as PublicClient, aF as PublicClientOptions, aG as PublicRewardsActions, aH as PublicSubscriptionsActions, aI as RateLimitError, aJ as RedeemPositionsError, aK as RequestRejectedError, aL as RequestRejectedErrorOptions, aM as SearchError, aN as SecureAccountActions, aO as SecureActions, aP as SecureClient, aQ as SecureClientOptions, aR as SecureDownloadAccountingSnapshotRequest, aS as SecureFetchPortfolioValueRequest, aT as SecureFetchTradedMarketCountRequest, aU as SecureListActivityRequest, aV as SecureListClosedPositionsRequest, aW as SecureListPositionsRequest, aX as SecureRewardsActions, aY as SecureSubscriptionsActions, aZ as SecureTradingActions, a_ as SecureWalletActions, a$ as SetupGaslessWalletError, b0 as SetupTradingApprovalsError, S as Signer, b1 as SignerTransactionRequest, b2 as SigningError, b3 as SplitPositionError, b4 as TimeoutError, b5 as TransactionFailedError, b6 as TransactionHandle, b7 as TransactionOutcome, b8 as TransferErc20Error, b9 as TransportError, a as TypedData, ba as TypedDataDomain, bb as TypedDataField, T as TypedDataPayload, bc as UnexpectedResponseError, bd as WaitForTransactionError, be as WalletDerivationConfig, bf as accountActions, bg as allActions, bh as analyticsActions, bi as createPublicClient, bj as createSecureClient, bk as dataActions, bl as discoveryActions, bm as makeErrorGuard, bn as production, bo as rewardsActions, bp as subscriptionsActions, bq as tradingActions, br as walletActions } from './types-D7tLX0ye.js';
14
- export { C as CreateLimitOrderError, a as CreateMarketOrderError, F as FetchSportsMarketTypesError, L as ListSportsError, P as PlaceLimitOrderError, b as PlaceMarketOrderError } from './sports-BDLhQVTP.js';
14
+ import { U as UserInputError, b as TransactionCall, A as ApiKeyAuthorization } from './types-M1U0um0G.js';
15
+ export { c as AccountIdentity, d as AnalyticsActions, e as ApproveErc1155ForAllError, f as ApproveErc20Error, B as BaseClient, g as BasePublicClient, h as BaseSecureClient, i as BeginAuthenticationRequest, C as CancelAllError, j as CancelMarketOrdersError, k as CancelOrderError, l as CancelOrdersError, m as CancelledSigningError, n as Client, o as ClientActions, p as ClientDecorator, q as ClobEndpoints, r as CreateSecureClientError, D as DataActions, s as DiscoveryActions, t as DownloadAccountingSnapshotError, u as DropNotificationsError, E as EnvironmentConfig, v as EnvironmentConfigFork, w as EnvironmentContracts, x as EstimateMarketPriceError, F as FetchClosedOnlyModeError, y as FetchCommentsByIdError, z as FetchEventError, G as FetchEventLiveVolumeError, H as FetchEventTagsError, I as FetchLastTradePriceError, J as FetchLastTradePricesError, K as FetchMarketError, L as FetchMarketTagsError, M as FetchMidpointError, N as FetchMidpointsError, O as FetchNotificationsError, P as FetchOrderBookError, Q as FetchOrderBooksError, R as FetchOrderError, V as FetchOrderScoringError, W as FetchOrdersScoringError, X as FetchPortfolioValueError, Y as FetchPriceError, Z as FetchPriceHistoryError, _ as FetchPricesError, $ as FetchPublicProfileError, a0 as FetchRelatedTagResourcesError, a1 as FetchRelatedTagsError, a2 as FetchRewardPercentagesError, a3 as FetchSeriesError, a4 as FetchSpreadError, a5 as FetchSpreadsError, a6 as FetchTagError, a7 as FetchTotalEarningsForUserForDayError, a8 as FetchTradedMarketCountError, a9 as InsufficientLiquidityError, aa as ListAccountTradesError, ab as ListActivityError, ac as ListBuilderLeaderboardError, ad as ListBuilderTradesError, ae as ListBuilderVolumeError, af as ListClosedPositionsError, ag as ListComboMarketsError, ah as ListComboPositionsError, ai as ListCommentsByUserAddressError, aj as ListCommentsError, ak as ListCurrentRewardsError, al as ListEventsError, am as ListMarketHoldersError, an as ListMarketPositionsError, ao as ListMarketRewardsError, ap as ListMarketsError, aq as ListOpenInterestError, ar as ListOpenOrdersError, as as ListPositionsError, at as ListSeriesError, au as ListTagsError, av as ListTeamsError, aw as ListTraderLeaderboardError, ax as ListTradesError, ay as ListUserEarningsAndMarketsConfigError, az as ListUserEarningsForDayError, aA as MergePositionsError, aB as OpenRfqSessionError, aC as Page, aD as PageSizeSchema, aE as Paginated, aF as PerpsActions, aG as PerpsEndpoints, aH as PerpsSession, aI as PostOrderError, aJ as PostOrdersError, aK as PublicAccountActions, aL as PublicActions, aM as PublicClient, aN as PublicClientOptions, aO as PublicPerpsActions, aP as PublicRewardsActions, aQ as PublicSubscriptionsActions, aR as RateLimitError, aS as RedeemPositionsError, aT as RequestRejectedError, aU as RequestRejectedErrorOptions, aV as RestEndpoint, aW as RfqCancelQuoteAck, aX as RfqCancelQuoteError, aY as RfqCancelQuoteRejectedError, aZ as RfqCancelQuoteRejectedErrorOptions, a_ as RfqConfirmationAck, a$ as RfqConfirmationError, b0 as RfqConfirmationRejectedError, b1 as RfqConfirmationRequestEvent, b2 as RfqEndpoints, b3 as RfqEvent, b4 as RfqQuoteError, b5 as RfqQuoteReference, b6 as RfqQuoteRejectedError, b7 as RfqQuoteRejectedErrorOptions, b8 as RfqQuoteRequestEvent, b9 as RfqQuoteResponse, ba as RfqQuoteSource, bb as RfqSession, bc as RfqTradeEvent, bd as SearchError, be as SearchSort, bf as SecureAccountActions, bg as SecureActions, bh as SecureClient, bi as SecureClientOptions, bj as SecureDownloadAccountingSnapshotRequest, bk as SecureFetchPortfolioValueRequest, bl as SecureFetchTradedMarketCountRequest, bm as SecureListActivityRequest, bn as SecureListClosedPositionsRequest, bo as SecureListComboPositionsRequest, bp as SecureListPositionsRequest, bq as SecurePerpsActions, br as SecureRewardsActions, bs as SecureRfqActions, bt as SecureSubscriptionsActions, bu as SecureTradingActions, bv as SecureWalletActions, bw as SetupGaslessWalletError, bx as SetupTradingApprovalsError, S as Signer, by as SignerTransactionRequest, bz as SigningError, bA as SplitPositionError, bB as TimeoutError, bC as TransactionFailedError, bD as TransactionHandle, bE as TransactionOutcome, bF as TransferErc20Error, bG as TransportError, a as TypedData, bH as TypedDataDomain, bI as TypedDataField, T as TypedDataPayload, bJ as UnexpectedResponseError, bK as UpdatePerpsLeverageError, bL as UpdatePerpsMarginError, bM as WaitForTransactionError, bN as WalletDerivationConfig, bO as WebSocketEndpoint, bP as accountActions, bQ as allActions, bR as analyticsActions, bS as createPublicClient, bT as createSecureClient, bU as dataActions, bV as discoveryActions, bW as forkEnvironmentConfig, bX as makeErrorGuard, bY as perpsActions, bZ as production, b_ as rewardsActions, b$ as rfqActions, c0 as subscriptionsActions, c1 as tradingActions, c2 as walletActions } from './types-M1U0um0G.js';
16
+ export { C as CreateLimitOrderError, a as CreateMarketOrderError, F as FetchSportsMarketTypesError, L as ListSportsError, P as PlaceLimitOrderError, b as PlaceMarketOrderError } from './sports-BGrBawu_.js';
17
+ export { PerpsSessionEvent } from '@polymarket/bindings/subscriptions';
18
+ export { RfqConfirmationDecision, RfqConfirmationRequest, RfqDirection, RfqErrorCode, RfqExecutionStatus, RfqExecutionUpdate, RfqId, RfqQuoteId, RfqQuoteRequest, RfqRequestedSize, RfqRequestedSizeUnit, RfqRequestorPublicId, RfqSide, RfqTrade } from '@polymarket/bindings/rfq';
15
19
  import 'zod';
16
- import '@polymarket/bindings/subscriptions';
17
20
  import 'ox';
18
21
 
22
+ type Tagged<T, Tag extends string> = T & {
23
+ readonly __tag: Tag;
24
+ };
25
+ type CanonicalComboLegs = Tagged<readonly bigint[], 'CanonicalComboLegs'>;
26
+
19
27
  type Erc20ApprovalCallError = UserInputError;
20
28
  declare const Erc20ApprovalCallError: {
21
29
  isError(error: unknown): error is UserInputError;
@@ -42,6 +50,17 @@ declare const Erc20TransferCallError: {
42
50
  * Thrown when the transfer amount is invalid.
43
51
  */
44
52
  declare function erc20TransferCall(tokenAddress: EvmAddress, recipient: EvmAddress, amount: bigint): TransactionCall;
53
+ type PerpsDepositCallError = UserInputError;
54
+ declare const PerpsDepositCallError: {
55
+ isError(error: unknown): error is UserInputError;
56
+ };
57
+ /**
58
+ * Creates a transaction call for Perps `deposit(address,uint256,address)`.
59
+ *
60
+ * @throws {@link PerpsDepositCallError}
61
+ * Thrown when the deposit amount is invalid.
62
+ */
63
+ declare function perpsDepositCall(depositContractAddress: EvmAddress, tokenAddress: EvmAddress, amount: bigint, to: EvmAddress): TransactionCall;
45
64
  type CtfRedeemPositionsCallError = UserInputError;
46
65
  declare const CtfRedeemPositionsCallError: {
47
66
  isError(error: unknown): error is UserInputError;
@@ -60,7 +79,7 @@ declare const SplitPositionCallError: {
60
79
  * @throws {@link SplitPositionCallError}
61
80
  * Thrown when the amount is invalid.
62
81
  */
63
- declare function splitPositionCall(targetAddress: EvmAddress, collateralTokenAddress: EvmAddress, conditionId: ConditionId, amount: bigint): TransactionCall;
82
+ declare function splitPositionCall(targetAddress: EvmAddress, collateralTokenAddress: EvmAddress, conditionId: CtfConditionId, amount: bigint): TransactionCall;
64
83
  type MergePositionsCallError = UserInputError;
65
84
  declare const MergePositionsCallError: {
66
85
  isError(error: unknown): error is UserInputError;
@@ -75,7 +94,7 @@ declare const MergePositionsCallError: {
75
94
  * @throws {@link MergePositionsCallError}
76
95
  * Thrown when the amount is invalid.
77
96
  */
78
- declare function mergePositionsCall(targetAddress: EvmAddress, collateralTokenAddress: EvmAddress, conditionId: ConditionId, amount: bigint): TransactionCall;
97
+ declare function mergePositionsCall(targetAddress: EvmAddress, collateralTokenAddress: EvmAddress, conditionId: CtfConditionId, amount: bigint): TransactionCall;
79
98
  /**
80
99
  * Creates a transaction call for `redeemPositions(address,bytes32,bytes32,uint256[])`
81
100
  * on Conditional Tokens-compatible contracts, including the collateral adapters.
@@ -86,7 +105,51 @@ declare function mergePositionsCall(targetAddress: EvmAddress, collateralTokenAd
86
105
  * @throws {@link CtfRedeemPositionsCallError}
87
106
  * Thrown when the condition is invalid.
88
107
  */
89
- declare function ctfRedeemPositionsCall(conditionalTokensAddress: EvmAddress, collateralTokenAddress: EvmAddress, conditionId: ConditionId): TransactionCall;
108
+ declare function ctfRedeemPositionsCall(conditionalTokensAddress: EvmAddress, collateralTokenAddress: EvmAddress, conditionId: CtfConditionId): TransactionCall;
109
+ type SplitV2CallError = UserInputError;
110
+ declare const SplitV2CallError: {
111
+ isError(error: unknown): error is UserInputError;
112
+ };
113
+ /**
114
+ * Creates a transaction call for protocol v2 Router `split(bytes31,uint256)`.
115
+ *
116
+ * @throws {@link SplitV2CallError}
117
+ * Thrown when the condition ID or amount is invalid.
118
+ */
119
+ declare function splitV2Call(routerAddress: EvmAddress, conditionId: ComboConditionId, amount: bigint): TransactionCall;
120
+ type MergeV2CallError = UserInputError;
121
+ declare const MergeV2CallError: {
122
+ isError(error: unknown): error is UserInputError;
123
+ };
124
+ /**
125
+ * Creates a transaction call for protocol v2 Router `merge(bytes31,uint256)`.
126
+ *
127
+ * @throws {@link MergeV2CallError}
128
+ * Thrown when the condition ID or amount is invalid.
129
+ */
130
+ declare function mergeV2Call(routerAddress: EvmAddress, conditionId: ComboConditionId, amount: bigint): TransactionCall;
131
+ type RedeemV2CallError = UserInputError;
132
+ declare const RedeemV2CallError: {
133
+ isError(error: unknown): error is UserInputError;
134
+ };
135
+ /**
136
+ * Creates a transaction call for protocol v2 Router `redeem(bytes31,uint256,uint256)`.
137
+ *
138
+ * @throws {@link RedeemV2CallError}
139
+ * Thrown when the condition ID, outcome index, or amount is invalid.
140
+ */
141
+ declare function redeemV2Call(routerAddress: EvmAddress, conditionId: ComboConditionId, outcomeIndex: 0 | 1, amount: bigint): TransactionCall;
142
+ type CombinatorialPrepareConditionCallError = UserInputError;
143
+ declare const CombinatorialPrepareConditionCallError: {
144
+ isError(error: unknown): error is UserInputError;
145
+ };
146
+ /**
147
+ * Creates a transaction call for CombinatorialModule `prepareCondition(uint256[])`.
148
+ *
149
+ * @throws {@link CombinatorialPrepareConditionCallError}
150
+ * Thrown when any leg position ID is invalid.
151
+ */
152
+ declare function combinatorialPrepareConditionCall(combinatorialModuleAddress: EvmAddress, legs: CanonicalComboLegs): TransactionCall;
90
153
 
91
154
  type RelayerApiKeyConfig = {
92
155
  key: string;
@@ -155,4 +218,4 @@ declare function relayerApiKey(config: RelayerApiKeyConfig): ApiKeyAuthorization
155
218
  */
156
219
  declare function buildHmacSignature(secret: string, timestamp: number, method: string, requestPath: string, body?: string): Promise<string>;
157
220
 
158
- export { ApiKeyAuthorization, CtfRedeemPositionsCallError, Erc20ApprovalCallError, Erc20TransferCallError, MergePositionsCallError, type RelayerApiKeyConfig, type RemoteBuilderSigningConfig, SplitPositionCallError, TransactionCall, UserInputError, buildHmacSignature, ctfRedeemPositionsCall, erc1155ApprovalForAllCall, erc20ApprovalCall, erc20TransferCall, mergePositionsCall, relayerApiKey, remoteBuilderSigning, splitPositionCall };
221
+ export { ApiKeyAuthorization, CombinatorialPrepareConditionCallError, CtfRedeemPositionsCallError, Erc20ApprovalCallError, Erc20TransferCallError, MergePositionsCallError, MergeV2CallError, PerpsDepositCallError, RedeemV2CallError, type RelayerApiKeyConfig, type RemoteBuilderSigningConfig, SplitPositionCallError, SplitV2CallError, TransactionCall, UserInputError, buildHmacSignature, combinatorialPrepareConditionCall, ctfRedeemPositionsCall, erc1155ApprovalForAllCall, erc20ApprovalCall, erc20TransferCall, mergePositionsCall, mergeV2Call, perpsDepositCall, redeemV2Call, relayerApiKey, remoteBuilderSigning, splitPositionCall, splitV2Call };
package/dist/index.js CHANGED
@@ -1,3 +1,3 @@
1
- import {W,ea,ca,aa,ya,Qc,Oc,Mc,Kc,Ic,Qb,Ob,Mb,Oa,wa,Yb,_b,kc,sb,qb,ob,mb,kb,ib,gb,eb,cb,Sa,Qa,Kb,Cb,Ab,yb,cd,xd,md,kd,ed,vd,td,rd,pd,id,gd,Wb,Ub,Sb,Ib,Gb,Eb,ua,sa,qa,oa,ma,ka,nd,_,Y as Y$1,ic,gc,ec,cc,pc,oc,Gc,Ec,Cc,Ac,ad,Zc,Wc,Bd,Ia,Ea,Ma,N,I,ac,wb,ub,F as F$1,E,J as J$1,G,v as v$1,t,H,Q as Q$1,x}from'./chunk-VQOVE5SC.js';export{Ha as ApproveErc1155ForAllError,Da as ApproveErc20Error,fc as CancelAllError,hc as CancelMarketOrdersError,bc as CancelOrderError,dc as CancelOrdersError,Dc as CreateLimitOrderError,zc as CreateMarketOrderError,g as CtfRedeemPositionsCallError,Pc as DownloadAccountingSnapshotError,da as DropNotificationsError,b as Erc20ApprovalCallError,e as Erc20TransferCallError,jc as EstimateMarketPriceError,V as FetchClosedOnlyModeError,zb as FetchCommentsByIdError,Fb as FetchEventError,Jb as FetchEventLiveVolumeError,Hb as FetchEventTagsError,nb as FetchLastTradePriceError,pb as FetchLastTradePricesError,Tb as FetchMarketError,Vb as FetchMarketTagsError,Pa as FetchMidpointError,Ra as FetchMidpointsError,ba as FetchNotificationsError,fb as FetchOrderBookError,hb as FetchOrderBooksError,Z as FetchOrderError,ja as FetchOrderScoringError,la as FetchOrdersScoringError,Lc as FetchPortfolioValueError,bb as FetchPriceError,rb as FetchPriceHistoryError,db as FetchPricesError,bd as FetchPublicProfileError,ud as FetchRelatedTagResourcesError,sd as FetchRelatedTagsError,ta as FetchRewardPercentagesError,hd as FetchSeriesError,ld as FetchSportsMarketTypesError,jb as FetchSpreadError,lb as FetchSpreadsError,qd as FetchTagError,pa as FetchTotalEarningsForUserForDayError,Nc as FetchTradedMarketCountError,M as IsGaslessReadyError,$ as ListAccountTradesError,xa as ListActivityError,Lb as ListBuilderLeaderboardError,Na as ListBuilderTradesError,Nb as ListBuilderVolumeError,Jc as ListClosedPositionsError,Bb as ListCommentsByUserAddressError,xb as ListCommentsError,tb as ListCurrentRewardsError,Db as ListEventsError,Xb as ListMarketHoldersError,$b as ListMarketPositionsError,vb as ListMarketRewardsError,Rb as ListMarketsError,Zb as ListOpenInterestError,X as ListOpenOrdersError,Hc as ListPositionsError,fd as ListSeriesError,jd as ListSportsError,od as ListTagsError,wd as ListTeamsError,Pb as ListTraderLeaderboardError,va as ListTradesError,ra as ListUserEarningsAndMarketsConfigError,na as ListUserEarningsForDayError,a as MAX_UINT256,j as MergePositionsCallError,Yc as MergePositionsError,Fc as PlaceLimitOrderError,Bc as PlaceMarketOrderError,mc as PostOrderError,nc as PostOrdersError,$c as RedeemPositionsError,dd as SearchError,La as SetupTradingApprovalsError,h as SplitPositionCallError,Vc as SplitPositionError,Ad as TransferErc20Error,za as WaitForTransactionError,l as ctfRedeemPositionsCall,m as encodeProxyCall,n as encodeSafeMultisendCall,d as erc1155ApprovalForAllCall,c as erc20ApprovalCall,f as erc20TransferCall,Aa as expectTransactionHandle,k as mergePositionsCall,i as splitPositionCall}from'./chunk-VQOVE5SC.js';import {k,h,e,d as d$1,j,c,b as b$1,a as a$1,f,g}from'./chunk-E2CLUN5M.js';export{h as CancelledSigningError,i as InsufficientLiquidityError,e as RateLimitError,d as RequestRejectedError,j as SigningError,f as TimeoutError,g as TransactionFailedError,c as TransportError,b as UnexpectedResponseError,a as UserInputError,k as makeErrorGuard}from'./chunk-E2CLUN5M.js';import {ApiKeySchema,EvmAddressSchema}from'@polymarket/bindings';export{OrderSide,OrderType}from'@polymarket/bindings';export{SignatureType}from'@polymarket/bindings/clob';export{ActivityType}from'@polymarket/bindings/data';import {WalletType}from'@polymarket/bindings/gamma';export{WalletType}from'@polymarket/bindings/gamma';import {z}from'zod';import {expectEvmAddress,expectEvmSignature,ResultAsync,invariant,isSameEvmAddress,setNonBlockingInterval,setNonBlockingTimeout}from'@polymarket/types';import Hs from'ky';import {RealtimeEventSchema,SportsResultEventSchema,MarketEventSchema,UserEventSchema}from'@polymarket/bindings/subscriptions';import {pushable}from'it-pushable';var ws=z.object({POLY_BUILDER_API_KEY:z.string().min(1),POLY_BUILDER_TIMESTAMP:z.string().min(1),POLY_BUILDER_PASSPHRASE:z.string().min(1),POLY_BUILDER_SIGNATURE:z.string().min(1)});function xs(t){return new Y(t)}function Ms(t){return new J(t)}var Y=class{#e;constructor(e){this.#e=e;}get isBuilderKey(){return true}get supportGasless(){return true}async authorize(e){try{return await this.#r(e)}catch(r){throw j.fromError(r,"Could not authorize the builder-authenticated request")}}async#t(){let e=this.#e.headers,r=typeof e=="function"?await e():e,s=new Headers(r);return s.set("content-type","application/json"),s}async#r(e){let r=await fetch(this.#e.url,{body:JSON.stringify({body:e.body,method:e.method,path:e.path}),credentials:this.#e.credentials,headers:await this.#t(),method:"POST",mode:"cors"});if(!r.ok)throw new Error(`Remote signer rejected request with status ${r.status}`);return ws.parse(await r.json())}},J=class{#e;constructor(e){this.#e=e;}get isBuilderKey(){return false}get supportGasless(){return true}authorize(){return Promise.resolve({RELAYER_API_KEY:this.#e.key,RELAYER_API_KEY_ADDRESS:this.#e.address})}};function Ht(t){return {domain:{chainId:t.chainId,name:"ClobAuthDomain",version:"1"},message:{address:t.address,message:"This message attests that I control the given wallet",nonce:t.nonce??0,timestamp:`${t.timestamp}`},primaryType:"ClobAuth",types:{ClobAuth:[{name:"address",type:"address"},{name:"timestamp",type:"string"},{name:"nonce",type:"uint256"},{name:"message",type:"string"}]}}}function Os(t){return {listPositions:Ic.bind(null,t),listClosedPositions:Kc.bind(null,t),fetchPortfolioValue:Mc.bind(null,t),fetchTradedMarketCount:Oc.bind(null,t),downloadAccountingSnapshot:Qc.bind(null,t),listMarketPositions:ac.bind(null,t),listActivity:ya.bind(null,t)}}function A(t,e={}){return {...e,user:e.user??t.account.wallet}}function Z(t){let e=Os(t);return t.isPublicClient()?e:{...e,listPositions:r=>Ic(t,A(t,r)),listClosedPositions:r=>Kc(t,A(t,r)),fetchPortfolioValue:r=>Mc(t,A(t,r)),fetchTradedMarketCount:r=>Oc(t,A(t,r)),downloadAccountingSnapshot:r=>Qc(t,A(t,r)),listActivity:r=>ya(t,A(t,r)),listAccountTrades:aa.bind(null,t),fetchNotifications:ca.bind(null,t),dropNotifications:ea.bind(null,t),fetchClosedOnlyMode:W.bind(null,t)}}function X(t){return {listBuilderTrades:Oa.bind(null,t),listBuilderLeaderboard:Mb.bind(null,t),fetchBuilderVolume:Ob.bind(null,t),listTraderLeaderboard:Qb.bind(null,t)}}function Q(t){return {fetchEventLiveVolume:Kb.bind(null,t),fetchMidpoint:Qa.bind(null,t),fetchMidpoints:Sa.bind(null,t),fetchPrice:cb.bind(null,t),fetchPrices:eb.bind(null,t),fetchOrderBook:gb.bind(null,t),fetchOrderBooks:ib.bind(null,t),fetchSpread:kb.bind(null,t),fetchSpreads:mb.bind(null,t),fetchLastTradePrice:ob.bind(null,t),fetchLastTradePrices:qb.bind(null,t),fetchPriceHistory:sb.bind(null,t),estimateMarketPrice:kc.bind(null,t),listOpenInterest:_b.bind(null,t),listMarketHolders:Yb.bind(null,t),listTrades:wa.bind(null,t)}}function ee(t){return {listEvents:Eb.bind(null,t),fetchEvent:Gb.bind(null,t),fetchEventTags:Ib.bind(null,t),listMarkets:Sb.bind(null,t),fetchMarket:Ub.bind(null,t),fetchMarketTags:Wb.bind(null,t),listSeries:gd.bind(null,t),fetchSeries:id.bind(null,t),listTags:pd.bind(null,t),fetchTag:rd.bind(null,t),fetchRelatedTags:td.bind(null,t),fetchRelatedTagResources:vd.bind(null,t),search:ed.bind(null,t),listSports:kd.bind(null,t),fetchSportsMarketTypes:md.bind(null,t),listTeams:xd.bind(null,t),fetchPublicProfile:cd.bind(null,t),listComments:yb.bind(null,t),fetchCommentsById:Ab.bind(null,t),listCommentsByUserAddress:Cb.bind(null,t)}}function Ls(t){return {listCurrentRewards:ub.bind(null,t),listMarketRewards:wb.bind(null,t)}}function te(t){let e=Ls(t);return t.isPublicClient()?e:{...e,fetchOrderScoring:ka.bind(null,t),fetchOrdersScoring:ma.bind(null,t),listUserEarningsForDay:oa.bind(null,t),fetchTotalEarningsForUserForDay:qa.bind(null,t),listUserEarningsAndMarketsConfig:sa.bind(null,t),fetchRewardPercentages:ua.bind(null,t)}}function re(t){return t.isSecureClient()?{subscribe(e){return nd(t,e)}}:{subscribe(e){return nd(t,e)}}}function It(t){return {createMarketOrder:Ac.bind(null,t),placeMarketOrder:Cc.bind(null,t),createLimitOrder:Ec.bind(null,t),placeLimitOrder:Gc.bind(null,t),postOrder:oc(t),postOrders:pc(t),cancelOrder:cc.bind(null,t),cancelOrders:ec.bind(null,t),cancelAll:gc.bind(null,t),cancelMarketOrders:ic.bind(null,t),listOpenOrders:Y$1.bind(null,t),fetchOrder:_.bind(null,t)}}function Ut(t){return {isGaslessReady:N.bind(null,t),setupTradingApprovals:Ma.bind(null,t),approveErc20:Ea.bind(null,t),approveErc1155ForAll:Ia.bind(null,t),transferErc20:Bd.bind(null,t),splitPosition:Wc.bind(null,t),mergePositions:Zc.bind(null,t),redeemPositions:ad.bind(null,t)}}function Kt(t){return t.isSecureClient()?{...Z(t),...X(t),...Q(t),...ee(t),...te(t),...re(t),...It(t),...Ut(t)}:{...Z(t),...X(t),...Q(t),...ee(t),...te(t),...re(t)}}var _t={name:"production",chainId:137,rpc:"https://polygon.drpc.org",walletDerivation:{depositWalletFactory:expectEvmAddress("0x00000000000Fb5C9ADea0298D729A0CB3823Cc07"),depositWalletBeacon:expectEvmAddress("0x7A18EDfe055488A3128f01F563e5B479D92ffc3a"),depositWalletImplementation:expectEvmAddress("0x58CA52ebe0DadfdF531Cde7062e76746de4Db1eB"),proxyFactory:expectEvmAddress("0xaB45c5A4B0c941a2F231C04C3f49182e1A254052"),proxyImplementation:expectEvmAddress("0x44e999d5c2F66Ef0861317f9A4805AC2e90aEB4f"),safeFactory:expectEvmAddress("0xaacFeEa03eb1561C4e67d661e40682Bd20E3541b"),safeInitCodeHash:"0x2bce2127ff07fb632d16c8347c4ebf501f4841168bed00d9e6ef715ddb6fcecf"},collateralToken:expectEvmAddress("0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB"),conditionalTokens:expectEvmAddress("0x4D97DCd97eC945f40cF65F87097ACe5EA0476045"),negRiskAdapter:expectEvmAddress("0xd91E80cF2E7be2e162c6513ceD06f1dD0dA35296"),collateralAdapter:expectEvmAddress("0xAdA100Db00Ca00073811820692005400218FcE1f"),negRiskCollateralAdapter:expectEvmAddress("0xadA2005600Dec949baf300f4C6120000bDB6eAab"),standardExchange:expectEvmAddress("0xE111180000d2663C0091e4f400237545B87B996B"),negRiskExchange:expectEvmAddress("0xe2222d279d744050d28e00520010520000310F59"),autoRedeemOperator:expectEvmAddress("0xF3cFb6a6eBFeB51876289Eb235719EB1C65252B0"),safeMultisend:expectEvmAddress("0xA238CBeb142c10Ef7Ad8442C6D1f9E89e07e7761"),relayHub:expectEvmAddress("0xD216153c06E857cD7f72665E0aF1d7D82172F494"),clob:"https://clob.polymarket.com",clobMarketWs:"wss://ws-subscriptions-clob.polymarket.com/ws/market",clobUserWs:"wss://ws-subscriptions-clob.polymarket.com/ws/user",relayer:"https://relayer-v2.polymarket.com",gamma:"https://gamma-api.polymarket.com",data:"https://data-api.polymarket.com",rtdsWs:"wss://ws-live-data.polymarket.com",sportsWs:"wss://sports-api.polymarket.com/ws",relayerMaxPolls:100,relayerPollFrequencyMs:2e3};async function Nt(t,e,r,s,i){let n=`${e}${r}${s}`;i!==void 0&&(n+=i);let o=await globalThis.crypto.subtle.importKey("raw",Fs(t),{name:"HMAC",hash:"SHA-256"},false,["sign"]),h=await globalThis.crypto.subtle.sign("HMAC",o,new TextEncoder().encode(n));return Ds(Bs(h))}function Fs(t){let e=t.replace(/-/g,"+").replace(/_/g,"/").replace(/[^A-Za-z0-9+/=]/g,""),r=atob(e),s=new Uint8Array(r.length);for(let i=0;i<r.length;i+=1)s[i]=r.charCodeAt(i);return s.buffer}function Bs(t){let e=new Uint8Array(t),r="";for(let s of e)r+=String.fromCharCode(s);return btoa(r)}function Ds(t){return t.replace(/\+/g,"-").replace(/\//g,"_")}var a=class{#e;#t;constructor({root:e,resolveHeaders:r}){this.#e=Hs.create({prefixUrl:e,throwHttpErrors:false}),this.#t=r;}get(e,r={}){return this.#i("GET",e,r)}post(e,r={}){return this.#i("POST",e,r)}del(e,r={}){return this.#i("DELETE",e,r)}#r(e){return e.startsWith("/")?e.slice(1):e}#i(e,r,s){return this.#c(this.#s(e,r,s))}async#s(e,r,s){let i=this.#n(e,r,s),n=await this.#t?.(i),o=this.#u(i.headers,n);return i.body!==void 0&&!o.has("content-type")&&o.set("content-type","application/json"),this.#e(this.#r(r),{body:i.body,headers:o,method:e,searchParams:i.params})}#n(e,r,s){return {body:"json"in s?this.#o(s.json):void 0,headers:s.headers,json:"json"in s?s.json:void 0,method:e,params:"params"in s?s.params:void 0,path:r}}#o(e){if(e!==void 0)return JSON.stringify(e)}#u(...e){let r=new Headers;for(let s of e)if(s!==void 0)for(let[i,n]of new Headers(s).entries())r.set(i,n);return r}#c(e$1){return ResultAsync.fromPromise(e$1.then(async r=>{if(r.ok)return r;if(r.status===429)throw new e(`Request to ${r.url} was rate limited`);let s=await this.#a(r);throw new d$1(s,{status:r.status})}),r=>r instanceof e||r instanceof d$1?r:c.fromError(r))}async#a(e){let r=e.headers.get("content-type")?.toLowerCase();if(r?.includes("application/json")){let{error:i}=await e.clone().json().catch(()=>({}));if(i)return `${String(i)} (${e.url})`}if(r?.includes("text/plain")){let i=await e.clone().text().then(n=>n.trim(),()=>"");if(i)return `${i} (${e.url})`}return e.headers.get("server")?.toLowerCase()?.includes("cloudflare")?`Request to ${e.url} was blocked by Cloudflare with status ${e.status}`:r?.includes("text/html")||r?.includes("application/xhtml+xml")?`Request to ${e.url} failed with status ${e.status} and an unexpected HTML response body`:`Request to ${e.url} failed with status ${e.status} and unreadable response body`}};function p(t,e){let r;return {close:()=>(r===void 0&&(r=Promise.resolve(t.return()).then(()=>e())),r),[Symbol.asyncIterator](){return t[Symbol.asyncIterator]()}}}var Is=1e4,Us=3e4,Ks=5e3,_s=10*6e4,Ns=3e4,P=class{#e=0;#t;start(e){this.stop(),this.#e=Date.now(),this.#t=setNonBlockingInterval(()=>{e("PING");},Is);}handleMessage(e){return e!=="PONG"?false:(this.#e=Date.now(),true)}isStale(e){return e-this.#e>Us}stop(){this.#t!==void 0&&(clearInterval(this.#t),this.#t=void 0);}},M=class{#e=0;#t;start(e){this.stop(),this.#e=Date.now(),this.#t=setNonBlockingInterval(()=>{e("PING");},Ks);}handleMessage(){return this.#e=Date.now(),false}isStale(e){return e-this.#e>_s}stop(){this.#t!==void 0&&(clearInterval(this.#t),this.#t=void 0);}},O=class{#e=0;#t;start(e){this.#e=Date.now(),this.#t=e;}stop(){this.#t=void 0;}handleMessage(e){return e!=="ping"?false:(this.#e=Date.now(),this.#t?.("pong"),true)}isStale(e){return e-this.#e>Ns}};var js=5e3,zs=250,$s=3e4,u=class{#e;#t=0;schedule(e){if(this.#e!==void 0||!e.shouldReconnect())return;let r=Ys(this.#t,{baseMs:zs,maxMs:$s});this.#t+=1,this.#e=setNonBlockingTimeout(()=>{this.#e=void 0,this.#r(e);},r);}stop(){this.#e!==void 0&&(clearTimeout(this.#e),this.#e=void 0);}resetBackoff(){this.#t=0,this.stop();}async#r(e){if(e.shouldReconnect())try{await e.reconnect();}catch{this.schedule(e);}}},l=class{#e;#t;#r;#i;constructor(e){this.#e=e.heartbeat;}connect(e){if(this.#t?.readyState===WebSocket.OPEN)return Promise.resolve({reusedOpenSocket:true});if(this.#u(),this.#r!==void 0)return this.#r;let s=this.#n(e).then(()=>({reusedOpenSocket:false})).catch(i=>{throw this.#r===s&&(this.#r=void 0),i});return this.#r=s,s}send(e){return this.#s(JSON.stringify(e))}#s(e){return this.#t?.readyState!==WebSocket.OPEN?false:(this.#t.send(e),true)}async close(){let e=await this.#l();this.#a(),!(e===void 0||e.readyState===WebSocket.CLOSED)&&await new Promise(r=>{e.addEventListener("close",()=>r(),{once:true}),e.readyState!==WebSocket.CLOSING&&e.close();});}async#n(e){let r=await e.prepare?.();return new Promise((s,i)=>{let n=new WebSocket(e.url),o=()=>{n.removeEventListener("error",h),this.#o(n),this.#c(),e.onOpen(r),s(n);},h=S=>{n.removeEventListener("open",o),i(new c(`WebSocket connection failed: ${e.url}`,{cause:S}));};n.addEventListener("open",o,{once:true}),n.addEventListener("error",h,{once:true}),n.addEventListener("message",S=>{if(this.#t!==n)return;let k=String(S.data);if(this.#e.handleMessage(k))return;let q;try{q=JSON.parse(k);}catch{return}e.onMessage(q);}),n.addEventListener("close",()=>{this.#t===n&&(this.#u(),e.onClose());}),n.addEventListener("error",()=>e.onError());})}#o(e){this.#t=e,this.#r=void 0;}#u(){this.#a(),this.#t=void 0;}#c(){this.#a(),this.#e.start(e=>this.#s(e)),this.#i=setNonBlockingInterval(()=>{if(!this.#e.isStale(Date.now()))return;let e=this.#t;e?.readyState===WebSocket.OPEN&&e.close();},js);}#a(){this.#i!==void 0&&(clearInterval(this.#i),this.#i=void 0),this.#e.stop();}async#l(){let e=this.#t,r=this.#r;return this.#t=void 0,this.#r=void 0,e!==void 0?e:r?.then(()=>this.#t,()=>{})}};function Ys(t,e){let r=Math.min(e.baseMs*2**t,e.maxMs);return Math.random()*r}var d=class{#e=new Set;#t;constructor(e){this.#t=e?.deriveServerState??(()=>{});}add(e,r={}){let s={queue:pushable({objectMode:true})};r.matches!==void 0&&(s.matches=r.matches);let i={subscription:e,subscriber:s};return {change:this.#r(i),entry:i}}#r(e){let r=this.serverState();return this.#e.add(e),{before:r,after:this.serverState()}}remove(e){let r=this.serverState();return this.#e.delete(e),e.subscriber.queue.end(),{before:r,after:this.serverState()}}dispatch(e){for(let{subscriber:r}of this.#e)(r.matches===void 0||r.matches(e))&&r.queue.push(e);}hasActiveSubscriptions(){return this.#e.size>0}endAll(e){for(let{subscriber:r}of this.#e)r.queue.end(e);this.#e.clear();}serverState(){return this.#t(this.#e)}};function se(t,e,r){let s=L(r.assetsIds,e.assetsIds),i=L(e.assetsIds,r.assetsIds);s.length>0&&t(Gt(s,r.customFeatureEnabled));let n=r.assetsIds[0];s.length===0&&e.customFeatureEnabled!==r.customFeatureEnabled&&n!==void 0&&t(Gt([n],r.customFeatureEnabled)),i.length>0&&t(Zs(i));}function ie(t,e,r){if(r.includeAllMarkets){!e.includeAllMarkets&&e.markets.length>0&&t(zt(e.markets));return}if(e.includeAllMarkets){r.markets.length>0&&t(jt(r.markets));return}let s=L(r.markets,e.markets),i=L(e.markets,r.markets);s.length>0&&t(jt(s)),i.length>0&&t(zt(i));}function $t(t){let e=new Set,r=false;for(let{subscription:s}of t){for(let i of s.tokenIds)e.add(i);r||=s.customFeatureEnabled===true;}return {assetsIds:Array.from(e),customFeatureEnabled:r}}function Yt(t){let e=false,r=new Set;for(let{subscription:s}of t){if(er(s)){e=true;continue}for(let i of s.markets??[])r.add(i);}return {includeAllMarkets:e,markets:e?[]:Array.from(r)}}function Jt(t){return {assets_ids:t.assetsIds,custom_feature_enabled:t.customFeatureEnabled,type:"market"}}function Gt(t,e){return {assets_ids:t,custom_feature_enabled:e,operation:"subscribe"}}function Zs(t){return {assets_ids:t,operation:"unsubscribe"}}function Zt(t,e){return {auth:{apiKey:e.key,passphrase:e.passphrase,secret:e.secret},markets:t.markets,type:"user"}}function jt(t){return {markets:t,operation:"subscribe"}}function zt(t){return {markets:t,operation:"unsubscribe"}}function Xt(t){return e=>{switch(e.type){case "price_change":return e.payload.priceChanges.some(r=>t.tokenIds.includes(r.tokenId));case "new_market":return t.customFeatureEnabled===true;case "market_resolved":return t.customFeatureEnabled===true&&(e.payload.tokenIds??[]).some(r=>t.tokenIds.includes(r));case "best_bid_ask":return t.customFeatureEnabled===true&&t.tokenIds.includes(e.payload.tokenId);default:return t.tokenIds.includes(e.payload.tokenId)}}}function Qt(t){if(er(t))return ()=>true;let e=new Set((t.markets??[]).map(r=>r.toLowerCase()));return r=>e.has(r.payload.market.toLowerCase())}function er(t){return (t.markets?.length??0)===0}function L(t,e){let r=new Set(e);return t.filter(s=>!r.has(s))}var b=class{#e;#t;#r=new l({heartbeat:new P});#i=new u;#s=new d({deriveServerState:$t});constructor(e){this.#e=e.url;}async subscribe(e){let{change:r,entry:s}=this.#s.add(e,{matches:Xt(e)});return await this.#n(s,r),p(s.subscriber.queue,()=>this.#o(s))}async#n(e,r){let{before:s,after:i}=r;try{(await this.#c()).reusedOpenSocket&&se(o=>this.#r.send(o),s,i);}catch(n){throw await this.#o(e),n}}async#o(e){let{before:r,after:s}=this.#s.remove(e);if(!this.#s.hasActiveSubscriptions()){await this.close();return}se(i=>this.#r.send(i),r,s);}async close(){this.#t===void 0&&(this.#t=this.#u().finally(()=>{this.#t=void 0;})),await this.#t;}async#u(){this.#i.stop(),this.#s.endAll(),await this.#r.close();}#c(){return this.#r.connect({onClose:()=>this.#d(),onError:()=>this.#p(),onMessage:e=>this.#l(e),onOpen:()=>this.#a(),url:this.#e})}#a(){this.#i.resetBackoff(),this.#m();}#l(e){let r=Array.isArray(e)?e:[e];for(let s of r){let i=MarketEventSchema.safeParse(s);i.success&&this.#s.dispatch(i.data);}}#d(){this.#s.hasActiveSubscriptions()&&this.#y();}#p(){}#m(){this.#r.send(Jt(this.#s.serverState()));}#y(){this.#i.schedule({reconnect:()=>this.#c(),shouldReconnect:()=>this.#s.hasActiveSubscriptions()});}};var v=class{#e;#t;#r;#i=new l({heartbeat:new P});#s=new u;#n=new d({deriveServerState:Yt});constructor(e){this.#e=e.url,this.#t=e.resolveCredentials;}async subscribe(e){let{change:r,entry:s}=this.#n.add(e,{matches:Qt(e)});return await this.#o(s,r),p(s.subscriber.queue,()=>this.#u(s))}async#o(e,r){let{before:s,after:i}=r;try{(await this.#a()).reusedOpenSocket&&ie(o=>this.#i.send(o),s,i);}catch(n){throw await this.#u(e),n}}async#u(e){let{before:r,after:s}=this.#n.remove(e);if(!this.#n.hasActiveSubscriptions()){await this.close();return}ie(i=>this.#i.send(i),r,s);}async close(){this.#r===void 0&&(this.#r=this.#c().finally(()=>{this.#r=void 0;})),await this.#r;}async#c(){this.#s.stop(),this.#n.endAll(),await this.#i.close();}#a(){return this.#i.connect({onClose:()=>this.#p(),onError:()=>this.#m(),onMessage:e=>this.#d(e),onOpen:e=>this.#l(e),prepare:()=>this.#t(),url:this.#e})}#l(e){this.#s.resetBackoff(),this.#y(e);}#d(e){let r=Array.isArray(e)?e:[e];for(let s of r){let i=UserEventSchema.safeParse(s);i.success&&this.#n.dispatch(i.data);}}#p(){this.#n.hasActiveSubscriptions()&&this.#b();}#m(){}#y(e){this.#i.send(Zt(this.#n.serverState(),e));}#b(){this.#s.schedule({reconnect:()=>this.#a(),shouldReconnect:()=>this.#n.hasActiveSubscriptions()});}};var R=class{#e;#t;#r=new l({heartbeat:new M});#i=new u;#s=new d({deriveServerState:si});constructor(e){this.#e=e;}async subscribe(e){let{change:r,entry:s}=this.#s.add(e,{matches:ci(e)});return await this.#n(s,r),p(s.subscriber.queue,()=>this.#o(s))}async#n(e,r){try{if((await this.#c()).reusedOpenSocket){let{before:i,after:n}=r,o=ti(i,n);this.#y(o);}}catch(s){throw await this.#o(e),s}}async#o(e){let{before:r,after:s}=this.#s.remove(e),i=ri(r,s);this.#b(i),this.#s.hasActiveSubscriptions()||await this.close();}async close(){this.#t===void 0&&(this.#t=this.#u().finally(()=>{this.#t=void 0;})),await this.#t;}async#u(){this.#i.stop(),this.#s.endAll(),await this.#r.close();}#c(){return this.#r.connect({onClose:()=>this.#d(),onError:()=>this.#p(),onMessage:e=>this.#l(e),onOpen:()=>this.#a(),url:this.#e})}#a(){this.#i.resetBackoff(),this.#m();}#l(e){let r=RealtimeEventSchema.safeParse(e);r.success&&this.#s.dispatch(r.data);}#d(){this.#s.hasActiveSubscriptions()&&this.#h();}#p(){}#m(){this.#y(Array.from(this.#s.serverState().values()));}#y(e){e.length!==0&&this.#r.send(ii(e));}#b(e){e.length!==0&&this.#r.send(ni(e));}#h(){this.#i.schedule({reconnect:()=>this.#c(),shouldReconnect:()=>this.#s.hasActiveSubscriptions()});}};function ti(t,e){return Array.from(e).flatMap(([r,s])=>t.has(r)?[]:[s])}function ri(t,e){return Array.from(t).flatMap(([r,s])=>e.has(r)?[]:[s])}function si(t){let e=new Map;for(let{subscription:r}of t)for(let s of oi(r))e.has(s.key)||e.set(s.key,s);return e}function ii(t){return {action:"subscribe",subscriptions:t.map(({topic:e,type:r})=>({topic:e,type:r}))}}function ni(t){return {action:"unsubscribe",subscriptions:t.map(({topic:e,type:r})=>({topic:e,type:r}))}}function oi(t){switch(t.topic){case "comments":return (t.types??["comment_created"]).map(e=>F("comments",e));case "prices.crypto.binance":return [F("crypto_prices","update")];case "prices.crypto.chainlink":return [F("crypto_prices_chainlink","update")];case "prices.equity.pyth":return [F("equity_prices","update")];default:invariant(false,`Unknown RTDS topic: ${String(t)}`);}}function F(t,e){return {key:`${t}:${e}`,topic:t,type:e}}function ci(t){switch(t.topic){case "comments":return e=>!(e.topic!=="comments"||t.types!==void 0&&t.types.length>0&&!t.types.includes(e.type)||(t.parentEntityId!==void 0||t.parentEntityType!==void 0)&&(!(e.type==="comment_created"||e.type==="comment_removed")||t.parentEntityId!==void 0&&e.payload.parentEntityID!==t.parentEntityId||t.parentEntityType!==void 0&&e.payload.parentEntityType!==t.parentEntityType));case "prices.crypto.binance":return e=>e.topic==="prices.crypto.binance"&&(t.symbols===void 0||t.symbols.length===0||t.symbols.includes(e.payload.symbol));case "prices.crypto.chainlink":return e=>e.topic==="prices.crypto.chainlink"&&(t.symbols===void 0||t.symbols.length===0||t.symbols.includes(e.payload.symbol));case "prices.equity.pyth":return e=>e.topic==="prices.equity.pyth"&&e.payload.symbol.toLowerCase()===t.symbol.toLowerCase()&&(t.types===void 0||t.types.length===0||t.types.includes(e.type));default:invariant(false,`Unknown RTDS topic: ${String(t)}`);}}var C=class{#e;#t;#r=new l({heartbeat:new O});#i=new u;#s=new d;constructor(e){this.#e=e.url;}async subscribe(e){let{entry:r}=this.#s.add(e);return await this.#n(r),p(r.subscriber.queue,()=>this.#o(r))}async#n(e){try{await this.#c();}catch(r){throw await this.#o(e),r}}async#o(e){this.#s.remove(e),this.#s.hasActiveSubscriptions()||await this.close();}async close(){this.#t===void 0&&(this.#t=this.#u().finally(()=>{this.#t=void 0;})),await this.#t;}async#u(){this.#i.stop(),this.#s.endAll(),await this.#r.close();}#c(){return this.#r.connect({onClose:()=>this.#d(),onError:()=>this.#p(),onMessage:e=>this.#l(e),onOpen:()=>this.#a(),url:this.#e})}#a(){this.#i.resetBackoff();}#l(e){let r=SportsResultEventSchema.safeParse(e);r.success&&this.#s.dispatch(r.data);}#d(){this.#s.hasActiveSubscriptions()&&this.#m();}#p(){}#m(){this.#i.schedule({reconnect:()=>this.#c(),shouldReconnect:()=>this.#s.hasActiveSubscriptions()});}};var B=class{#e;#t;get context(){return this.#e}get decorators(){return this.#t}get environment(){return this.context.environment}get clob(){return this.context.clob}get relayer(){return this.context.relayer}get rpc(){return this.context.rpc}get gamma(){return this.context.gamma}get data(){return this.context.data}get webSockets(){return this.context.webSockets}get supportsGasless(){return this.context.apiKey?.supportGasless??false}constructor(e){this.#e=e,this.#t=[];}async resolveClobHeaders(e){return this.context.apiKey?.isBuilderKey?this.context.apiKey.authorize(e):Promise.resolve({})}async resolveRelayerHeaders(e){return this.context.apiKey?.supportGasless?this.context.apiKey.authorize(e):Promise.resolve({})}rememberDecorator(e){this.#t.push(e);}},mi=z.object({key:ApiKeySchema,passphrase:z.string(),secret:z.string()}),yi=z.object({wallet:EvmAddressSchema,credentials:mi.optional(),nonce:z.number().int().positive().optional()}).superRefine((t,e)=>{t.credentials!==void 0&&t.nonce!==void 0&&e.addIssue({code:"custom",message:"`credentials` and `nonce` are mutually exclusive.",path:["nonce"]});}).transform(t=>t.credentials!==void 0?{wallet:t.wallet,credentials:t.credentials}:t.nonce!==void 0?{wallet:t.wallet,nonce:t.nonce}:{wallet:t.wallet}),D=class extends B{constructor(e){super({apiKey:e.apiKey,environment:e.environment,data:new a({root:e.environment.data}),gamma:new a({root:e.environment.gamma}),clob:new a({root:e.environment.clob,resolveHeaders:r=>this.resolveClobHeaders(r)}),relayer:new a({root:e.environment.relayer,resolveHeaders:r=>this.resolveRelayerHeaders(r)}),rpc:new F$1({url:e.environment.rpc}),webSockets:{clobMarket:new b({url:e.environment.clobMarketWs}),sports:new C({url:e.environment.sportsWs}),rtds:new R(e.environment.rtdsWs)}});}isSecureClient(){return false}isPublicClient(){return true}async closeSubscriptions(){await Promise.all([this.webSockets.clobMarket.close(),this.webSockets.rtds.close(),this.webSockets.sports.close()]).then(()=>{});}extend(e){return this.rememberDecorator(e),Object.assign(this,e(this)),this}beginAuthentication(e,r){let s=E(e,yi);return Promise.resolve(async function*(){let i=Math.floor(Date.now()/1e3),n=s?.nonce??0,o=expectEvmAddress(yield J$1()),h=expectEvmAddress(s.wallet),S=G(this.environment,o,h);if(s.credentials!==void 0){let ae=this.#e(s.credentials,S,r);try{if((await v$1(ae)).includes(s.credentials.key))return ae}catch(w){if(!(w instanceof d$1)||w.status!==401)throw w}}let k=yield {kind:"signAuthMessage",payload:Ht({address:o,chainId:this.environment.chainId,nonce:n,timestamp:i})},q=await t(this,{address:o,nonce:n,signature:expectEvmSignature(k),timestamp:i});return this.#e(q,S,r)}.call(this))}#e(e,r,s){let i=new ce({account:r,apiKey:this.context.apiKey,credentials:e,environment:this.environment,signer:s});for(let n of this.decorators)i.extend(n);return i}},ce=class t extends B{#e=false;get context(){return invariant(!this.#e,"This client has ended authentication and can no longer be used."),super.context}endAuthenticationLifecycle(){this.#e=true;}constructor(e){super({account:e.account,credentials:e.credentials,apiKey:e.apiKey,environment:e.environment,signer:e.signer,clob:new a({root:e.environment.clob,resolveHeaders:r=>this.resolveClobHeaders(r)}),relayer:new a({root:e.environment.relayer,resolveHeaders:r=>this.resolveRelayerHeaders(r)}),rpc:new F$1({url:e.environment.rpc}),gamma:new a({root:e.environment.gamma}),data:new a({root:e.environment.data}),secureClob:new a({resolveHeaders:async r=>({...await this.resolveClobHeaders(r),...await this.#r(r)}),root:e.environment.clob}),webSockets:{clobMarket:new b({url:e.environment.clobMarketWs}),clobUser:new v({resolveCredentials:()=>this.credentials,url:e.environment.clobUserWs}),sports:new C({url:e.environment.sportsWs}),rtds:new R(e.environment.rtdsWs)}});}get credentials(){return this.context.credentials}get account(){return this.context.account}get signer(){return invariant(this.context.signer!==void 0,"Secure client does not have a signer. Create secure clients with createSecureClient to use wallet-interactive methods."),this.context.signer}async setupGaslessWallet(){let e=expectEvmAddress(await this.signer.getAddress());if(invariant(isSameEvmAddress(e,this.account.signer),"The current signer address does not match the authenticated signer for this client."),this.account.walletType!==WalletType.EOA)return this.#t(this.account.wallet,e);let r=await H(this.rpc,e,this.environment.walletDerivation);return await N(this,{wallet:r,type:WalletType.DEPOSIT_WALLET})?this.#t(r,e):(await(await Q$1(this)).wait(),this.#t(r,e))}#t(e,r){let s=new t({account:G(this.environment,r,e),apiKey:this.context.apiKey,credentials:this.credentials,environment:this.environment,signer:this.context.signer});for(let i of this.decorators)s.extend(i);return s}get secureClob(){return this.context.secureClob}get webSockets(){return this.context.webSockets}async closeSubscriptions(){await Promise.allSettled([this.webSockets.clobMarket.close(),this.webSockets.rtds.close(),this.webSockets.sports.close(),this.webSockets.clobUser.close()]).then(()=>{});}isSecureClient(){return true}isPublicClient(){return false}extend(e){return this.rememberDecorator(e),Object.assign(this,e(this)),this}async endAuthentication(){let e=this.closeSubscriptions(),{apiKey:r,environment:s}=this.context;try{await x(this);}finally{this.endAuthenticationLifecycle(),await e;}let i=new D({apiKey:r,environment:s});for(let n of this.decorators)i.extend(n);return i}async#r(e){try{let r=Math.floor(Date.now()/1e3);return {POLY_ADDRESS:this.account.signer,POLY_API_KEY:this.credentials.key,POLY_PASSPHRASE:this.credentials.passphrase,POLY_SIGNATURE:await Nt(this.credentials.secret,r,e.method,e.path,e.body),POLY_TIMESTAMP:`${r}`}}catch(r){throw j.fromError(r,"Could not sign the L2-authenticated request")}}};function sr(t={}){return new D({environment:t.environment??_t,apiKey:t.apiKey}).extend(Kt)}var bi=k(h,e,d$1,j,c,b$1,a$1),hi=k(e,d$1,j,f,g,c,b$1,a$1);async function Si(t){let e=sr({environment:t.environment,apiKey:t.apiKey}),r=t.wallet??await t.signer.getAddress();return e.beginAuthentication({wallet:r,credentials:t.credentials,nonce:t.nonce},t.signer).then(I(t.signer))}
2
- export{bi as CreateSecureClientError,hi as SetupGaslessWalletError,Z as accountActions,Kt as allActions,X as analyticsActions,Nt as buildHmacSignature,sr as createPublicClient,Si as createSecureClient,Q as dataActions,ee as discoveryActions,_t as production,Ms as relayerApiKey,xs as remoteBuilderSigning,te as rewardsActions,re as subscriptionsActions,It as tradingActions,Ut as walletActions};//# sourceMappingURL=index.js.map
1
+ import {N,X,V,T,pa,Yd,Wd,Ud,Sd,Rd,Od,ic,gc,ec,gb,na,sc,uc,Gc,Mb,Kb,Ib,Gb,Eb,Cb,Ab,yb,wb,kb,ib,cc,Wb,Ub,Sb,Fe,nf,cf,af,We,lf,jf,hf,ff,_e,Ye,qc,oc,mc,kc,ac,_b,Yb,Md,Jd,Id,Ld,la,ja,ha,fa,da,ba,Ne,df,R as R$1,P as P$1,Ec,Cc,Ac,yc,Lc,Kc,cd,ad,_c,Yc,De,ye,pe as pe$1,rf,Ma,Ia,Qa as Qa$1,sa,xa,K,L as L$1,Aa,Ad,yd,wd,sd,qd,od,Cd,ud,wc,Qb,Ob,H,dd,G,ta,I as I$1,Ya,Wa,jd,hd,id,fd,gd,ed,_a,md,Ge,Ie,Ke,J,Mc,Nc}from'./chunk-FMBJ7ZRK.js';export{La as ApproveErc1155ForAllError,Ha as ApproveErc20Error,Bc as CancelAllError,Dc as CancelMarketOrdersError,xc as CancelOrderError,zc as CancelOrdersError,C as CombinatorialPrepareConditionCallError,Zd as ComboPositionStatus,$c as CreateLimitOrderError,Xc as CreateMarketOrderError,q as CtfRedeemPositionsCallError,Xd as DownloadAccountingSnapshotError,W as DropNotificationsError,b as Erc20ApprovalCallError,m as Erc20TransferCallError,Fc as EstimateMarketPriceError,M as FetchClosedOnlyModeError,Tb as FetchCommentsByIdError,Zb as FetchEventError,bc as FetchEventLiveVolumeError,$b as FetchEventTagsError,Hb as FetchLastTradePriceError,Jb as FetchLastTradePricesError,nc as FetchMarketError,pc as FetchMarketTagsError,hb as FetchMidpointError,jb as FetchMidpointsError,U as FetchNotificationsError,zb as FetchOrderBookError,Bb as FetchOrderBooksError,Q as FetchOrderError,aa as FetchOrderScoringError,ca as FetchOrdersScoringError,Td as FetchPortfolioValueError,vb as FetchPriceError,Lb as FetchPriceHistoryError,xb as FetchPricesError,Ee as FetchPublicProfileError,kf as FetchRelatedTagResourcesError,if as FetchRelatedTagsError,ka as FetchRewardPercentagesError,Ze as FetchSeriesError,bf as FetchSportsMarketTypesError,Db as FetchSpreadError,Fb as FetchSpreadsError,gf as FetchTagError,ga as FetchTotalEarningsForUserForDayError,Vd as FetchTradedMarketCountError,S as ListAccountTradesError,oa as ListActivityError,dc as ListBuilderLeaderboardError,fb as ListBuilderTradesError,fc as ListBuilderVolumeError,Pd as ListClosedPositionsError,lc as ListComboMarketsError,Qd as ListComboPositionsError,Vb as ListCommentsByUserAddressError,Rb as ListCommentsError,Nb as ListCurrentRewardsError,Xb as ListEventsError,rc as ListMarketHoldersError,vc as ListMarketPositionsError,Pb as ListMarketRewardsError,jc as ListMarketsError,tc as ListOpenInterestError,O as ListOpenOrdersError,Nd as ListPositionsError,Xe as ListSeriesError,$e as ListSportsError,ef as ListTagsError,mf as ListTeamsError,hc as ListTraderLeaderboardError,ma as ListTradesError,ia as ListUserEarningsAndMarketsConfigError,ea as ListUserEarningsForDayError,a as MAX_UINT256,t as MergePositionsCallError,te as MergePositionsError,y as MergeV2CallError,Me as OpenRfqSessionError,o as PerpsDepositCallError,bd as PlaceLimitOrderError,Zc as PlaceMarketOrderError,Ic as PostOrderError,Jc as PostOrdersError,Ce as RedeemPositionsError,A as RedeemV2CallError,Je as RfqCancelQuoteError,Ie as RfqCancelQuoteRejectedError,Oe as RfqConfirmationDecision,Le as RfqConfirmationError,Ke as RfqConfirmationRejectedError,Pe as RfqDirection,Qe as RfqErrorCode,Re as RfqExecutionStatus,He as RfqQuoteError,Ge as RfqQuoteRejectedError,Se as RfqRequestedSizeUnit,Te as RfqSide,Ve as SearchError,Ue as SearchSort,Pa as SetupTradingApprovalsError,r as SplitPositionCallError,ke as SplitPositionError,w as SplitV2CallError,qf as TransferErc20Error,kd as UpdatePerpsLeverageError,ld as UpdatePerpsMarginError,qa as WaitForTransactionError,D as combinatorialPrepareConditionCall,v as ctfRedeemPositionsCall,l as decodeErc1155BalanceOfBatchResult,j as decodeErc1155BalanceOfResult,h as decodeErc1155IsApprovedForAllResult,e as decodeErc20AllowanceResult,E as encodeProxyCall,F as encodeSafeMultisendCall,f as erc1155ApprovalForAllCall,k as erc1155BalanceOfBatchCall,i as erc1155BalanceOfCall,g as erc1155IsApprovedForAllCall,d as erc20AllowanceCall,c as erc20ApprovalCall,n as erc20TransferCall,ra as expectTransactionHandle,u as mergePositionsCall,z as mergeV2Call,p as perpsDepositCall,B as redeemV2Call,s as splitPositionCall,x as splitV2Call}from'./chunk-FMBJ7ZRK.js';import {a,k,h,e,d,j,f,g as g$1,c,b as b$1}from'./chunk-E2CLUN5M.js';export{h as CancelledSigningError,i as InsufficientLiquidityError,e as RateLimitError,d as RequestRejectedError,j as SigningError,f as TimeoutError,g as TransactionFailedError,c as TransportError,b as UnexpectedResponseError,a as UserInputError,k as makeErrorGuard}from'./chunk-E2CLUN5M.js';import {DecimalishSchema,ApiKeySchema,EvmAddressSchema,toBaseUnits,OrderSide}from'@polymarket/bindings';export{OrderSide,OrderType}from'@polymarket/bindings';export{PriceHistoryInterval,SignatureType}from'@polymarket/bindings/clob';export{ActivityType}from'@polymarket/bindings/data';import {WalletType}from'@polymarket/bindings/gamma';export{WalletType}from'@polymarket/bindings/gamma';export{PerpsDepositStatus,PerpsInstrumentCategory,PerpsInstrumentType,PerpsInternalTransferDirection,PerpsKlineInterval,PerpsOrderStatus,PerpsSide,PerpsTimeInForce,PerpsWithdrawalStatus}from'@polymarket/bindings/perps';import {z}from'zod';import {expectEvmAddress,isSameEvmAddress,expectEvmSignature,invariant,setNonBlockingTimeout}from'@polymarket/types';import {PerpsMarketDataEventSchema,RealtimeEventSchema,SportsResultEventSchema,MarketEventSchema,UserEventSchema}from'@polymarket/bindings/subscriptions';import {pushable}from'it-pushable';import {RfqKnownInboundMessageSchema,RfqQuoterInboundMessageSchema,RfqConfirmationDecision,RfqRequestedSizeUnit,RfqDirection}from'@polymarket/bindings/rfq';var Zn=z.object({POLY_BUILDER_API_KEY:z.string().min(1),POLY_BUILDER_TIMESTAMP:z.string().min(1),POLY_BUILDER_PASSPHRASE:z.string().min(1),POLY_BUILDER_SIGNATURE:z.string().min(1)});function Xn(t){return new re(t)}function ei(t){return new se(t)}var re=class{#e;constructor(e){this.#e=e;}get isBuilderKey(){return true}get supportGasless(){return true}async authorize(e){try{return await this.#s(e)}catch(r){throw j.fromError(r,"Could not authorize the builder-authenticated request")}}async#r(){let e=this.#e.headers,r=typeof e=="function"?await e():e,s=new Headers(r);return s.set("content-type","application/json"),s}async#s(e){let r=await fetch(this.#e.url,{body:JSON.stringify({body:e.body,method:e.method,path:e.path}),credentials:this.#e.credentials,headers:await this.#r(),method:"POST",mode:"cors"});if(!r.ok)throw new Error(`Remote signer rejected request with status ${r.status}`);return Zn.parse(await r.json())}},se=class{#e;constructor(e){this.#e=e;}get isBuilderKey(){return false}get supportGasless(){return true}authorize(){return Promise.resolve({RELAYER_API_KEY:this.#e.key,RELAYER_API_KEY_ADDRESS:this.#e.address})}};function Pr(t){return {domain:{chainId:t.chainId,name:"ClobAuthDomain",version:"1"},message:{address:t.address,message:"This message attests that I control the given wallet",nonce:t.nonce??0,timestamp:`${t.timestamp}`},primaryType:"ClobAuth",types:{ClobAuth:[{name:"address",type:"address"},{name:"timestamp",type:"string"},{name:"nonce",type:"uint256"},{name:"message",type:"string"}]}}}function ti(t){return {listPositions:Od.bind(null,t),listClosedPositions:Rd.bind(null,t),listComboPositions:Sd.bind(null,t),fetchPortfolioValue:Ud.bind(null,t),fetchTradedMarketCount:Wd.bind(null,t),downloadAccountingSnapshot:Yd.bind(null,t),listMarketPositions:wc.bind(null,t),listActivity:pa.bind(null,t)}}function y(t,e={}){return {...e,user:e.user??t.account.wallet}}function ne(t){let e=ti(t);return t.isPublicClient()?e:{...e,listPositions:r=>Od(t,y(t,r)),listClosedPositions:r=>Rd(t,y(t,r)),listComboPositions:r=>Sd(t,y(t,r)),fetchPortfolioValue:r=>Ud(t,y(t,r)),fetchTradedMarketCount:r=>Wd(t,y(t,r)),downloadAccountingSnapshot:r=>Yd(t,y(t,r)),listActivity:r=>pa(t,y(t,r)),listAccountTrades:T.bind(null,t),fetchNotifications:V.bind(null,t),dropNotifications:X.bind(null,t),fetchClosedOnlyMode:N.bind(null,t)}}function ie(t){return {listBuilderTrades:gb.bind(null,t),listBuilderLeaderboard:ec.bind(null,t),fetchBuilderVolume:gc.bind(null,t),listTraderLeaderboard:ic.bind(null,t)}}function oe(t){return {fetchEventLiveVolume:cc.bind(null,t),fetchMidpoint:ib.bind(null,t),fetchMidpoints:kb.bind(null,t),fetchPrice:wb.bind(null,t),fetchPrices:yb.bind(null,t),fetchOrderBook:Ab.bind(null,t),fetchOrderBooks:Cb.bind(null,t),fetchSpread:Eb.bind(null,t),fetchSpreads:Gb.bind(null,t),fetchLastTradePrice:Ib.bind(null,t),fetchLastTradePrices:Kb.bind(null,t),fetchPriceHistory:Mb.bind(null,t),estimateMarketPrice:Gc.bind(null,t),listOpenInterest:uc.bind(null,t),listMarketHolders:sc.bind(null,t),listTrades:na.bind(null,t)}}function ae(t){return {listEvents:Yb.bind(null,t),fetchEvent:_b.bind(null,t),fetchEventTags:ac.bind(null,t),listMarkets:kc.bind(null,t),listComboMarkets:mc.bind(null,t),fetchMarket:oc.bind(null,t),fetchMarketTags:qc.bind(null,t),listSeries:Ye.bind(null,t),fetchSeries:_e.bind(null,t),listTags:ff.bind(null,t),fetchTag:hf.bind(null,t),fetchRelatedTags:jf.bind(null,t),fetchRelatedTagResources:lf.bind(null,t),search:We.bind(null,t),listSports:af.bind(null,t),fetchSportsMarketTypes:cf.bind(null,t),listTeams:nf.bind(null,t),fetchPublicProfile:Fe.bind(null,t),listComments:Sb.bind(null,t),fetchCommentsById:Ub.bind(null,t),listCommentsByUserAddress:Wb.bind(null,t)}}function ce(t){let e={fetchPerpsBook:r=>ud(t,r),fetchPerpsFees:()=>Cd(t),fetchPerpsInstruments:r=>od(t,r),fetchPerpsTicker:r=>qd(t,r),fetchPerpsTickers:r=>sd(t,r),listPerpsCandles:r=>wd(t,r),listPerpsFundingHistory:r=>yd(t,r),listPerpsTrades:r=>Ad(t,r)};return t.isSecureClient()?{...e,depositToPerps:r=>Ld(t,r),openPerpsSession:r=>Id(t,r),revokePerpsCredentials:r=>Jd(t,r),withdrawFromPerps:r=>Md(t,r)}:e}function ri(t){return {listCurrentRewards:Ob.bind(null,t),listMarketRewards:Qb.bind(null,t)}}function ue(t){let e=ri(t);return t.isPublicClient()?e:{...e,fetchOrderScoring:ba.bind(null,t),fetchOrdersScoring:da.bind(null,t),listUserEarningsForDay:fa.bind(null,t),fetchTotalEarningsForUserForDay:ha.bind(null,t),listUserEarningsAndMarketsConfig:ja.bind(null,t),fetchRewardPercentages:la.bind(null,t)}}function qr(t){return {openRfqSession(){return Ne(t)}}}function de(t){return t.isSecureClient()?{subscribe(e){return df(t,e)}}:{subscribe(e){return df(t,e)}}}function vr(t){return {createMarketOrder:Yc.bind(null,t),placeMarketOrder:_c.bind(null,t),createLimitOrder:ad.bind(null,t),placeLimitOrder:cd.bind(null,t),postOrder:Kc(t),postOrders:Lc(t),cancelOrder:yc.bind(null,t),cancelOrders:Ac.bind(null,t),cancelAll:Cc.bind(null,t),cancelMarketOrders:Ec.bind(null,t),listOpenOrders:P$1.bind(null,t),fetchOrder:R$1.bind(null,t)}}function Ar(t){return {isGaslessReady:()=>Promise.resolve(true),setupTradingApprovals:Qa$1.bind(null,t),approveErc20:Ia.bind(null,t),approveErc1155ForAll:Ma.bind(null,t),transferErc20:rf.bind(null,t),splitPosition:pe$1.bind(null,t),mergePositions:ye.bind(null,t),redeemPositions:De.bind(null,t)}}function Cr(t){return t.isSecureClient()?{...ne(t),...ie(t),...oe(t),...ae(t),...ce(t),...ue(t),...qr(t),...de(t),...vr(t),...Ar(t)}:{...ne(t),...ie(t),...oe(t),...ae(t),...ce(t),...ue(t),...de(t)}}var pe={name:"production",chainId:137,rpc:"https://polygon.drpc.org",walletDerivation:{depositWalletFactory:expectEvmAddress("0x00000000000Fb5C9ADea0298D729A0CB3823Cc07"),depositWalletBeacon:expectEvmAddress("0x7A18EDfe055488A3128f01F563e5B479D92ffc3a"),depositWalletImplementation:expectEvmAddress("0x58CA52ebe0DadfdF531Cde7062e76746de4Db1eB"),proxyFactory:expectEvmAddress("0xaB45c5A4B0c941a2F231C04C3f49182e1A254052"),proxyImplementation:expectEvmAddress("0x44e999d5c2F66Ef0861317f9A4805AC2e90aEB4f"),safeFactory:expectEvmAddress("0xaacFeEa03eb1561C4e67d661e40682Bd20E3541b"),safeInitCodeHash:"0x2bce2127ff07fb632d16c8347c4ebf501f4841168bed00d9e6ef715ddb6fcecf"},contracts:{collateralToken:expectEvmAddress("0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB"),conditionalTokens:expectEvmAddress("0x4D97DCd97eC945f40cF65F87097ACe5EA0476045"),negRiskAdapter:expectEvmAddress("0xd91E80cF2E7be2e162c6513ceD06f1dD0dA35296"),collateralAdapter:expectEvmAddress("0xAdA100Db00Ca00073811820692005400218FcE1f"),negRiskCollateralAdapter:expectEvmAddress("0xadA2005600Dec949baf300f4C6120000bDB6eAab"),standardExchange:expectEvmAddress("0xE111180000d2663C0091e4f400237545B87B996B"),negRiskExchange:expectEvmAddress("0xe2222d279d744050d28e00520010520000310F59"),exchangeV3:expectEvmAddress("0xe3333700cA9d93003F00f0F71f8515005F6c00Aa"),protocolV2Router:expectEvmAddress("0x12121212006e4CD160D18e3f00711DA5c3372600"),combinatorialModule:expectEvmAddress("0x30000034706c7d8e12009dab006be20000c031a8"),positionManager:expectEvmAddress("0x006F54F7f9A22e0000CC2AB60031000000ae9fEF"),autoRedeemOperator:expectEvmAddress("0xa1200000d0002264C9a1698e001292D00E1b00af"),safeMultisend:expectEvmAddress("0xA238CBeb142c10Ef7Ad8442C6D1f9E89e07e7761"),relayHub:expectEvmAddress("0xD216153c06E857cD7f72665E0aF1d7D82172F494"),perpsDepositContract:expectEvmAddress("0xDCa4af75705dbB50f62437045afF9921947917d2")},clob:{rest:"https://clob.polymarket.com",market:{ws:"wss://ws-subscriptions-clob.polymarket.com/ws/market"},user:{ws:"wss://ws-subscriptions-clob.polymarket.com/ws/user"}},relayer:{rest:"https://relayer-v2.polymarket.com"},gamma:{rest:"https://gamma-api.polymarket.com"},data:{rest:"https://data-api.polymarket.com"},rfq:{rest:"https://combos-rfq-api.polymarket.com",ws:"wss://combos-rfq-gateway-quoter.polymarket.com/ws/rfq"},perps:{rest:"https://api.perpetuals.polymarket.com",ws:"wss://ws.perpetuals.polymarket.com/v1/ws"},rtds:{ws:"wss://ws-live-data.polymarket.com"},sports:{ws:"wss://sports-api.polymarket.com/ws"},relayerMaxPolls:100,relayerPollFrequencyMs:2e3};function si(t,e=pe){return {...e,...t,walletDerivation:{...e.walletDerivation,...t.walletDerivation},contracts:{...e.contracts,...t.contracts},clob:{...I(e.clob,t.clob),market:O(e.clob.market,t.clob?.market),user:O(e.clob.user,t.clob?.user)},relayer:I(e.relayer,t.relayer),gamma:I(e.gamma,t.gamma),data:I(e.data,t.data),rfq:Er(e.rfq,t.rfq),perps:Er(e.perps,t.perps),rtds:O(e.rtds,t.rtds),sports:O(e.sports,t.sports)}}function I(t,e){return {...t,...e,headers:le(t.headers,e?.headers)}}function O(t,e){return {...t,...e,headers:le(t.headers,e?.headers)}}function Er(t,e){return {...t,...e,headers:le(t.headers,e?.headers)}}function le(t,e){if(!(t===void 0&&e===void 0))return {...t,...e}}var Qa=si({name:"preproduction",clob:{rest:"https://clob-preprod-int-v2.polymarket.com"},data:{rest:"https://data-api-preprod-int.polymarket.com"},gamma:{rest:"https://gamma-api-preprod-int.polymarket.com"},relayer:{rest:"https://relayer-v2-preprod-int.polymarket.com"}});async function kr(t,e,r,s,n){let i=`${e}${r}${s}`;n!==void 0&&(i+=n);let o=await globalThis.crypto.subtle.importKey("raw",ni(t),{name:"HMAC",hash:"SHA-256"},false,["sign"]),A=await globalThis.crypto.subtle.sign("HMAC",o,new TextEncoder().encode(i));return oi(ii(A))}function ni(t){let e=t.replace(/-/g,"+").replace(/_/g,"/").replace(/[^A-Za-z0-9+/=]/g,""),r=atob(e),s=new Uint8Array(r.length);for(let n=0;n<r.length;n+=1)s[n]=r.charCodeAt(n);return s.buffer}function ii(t){let e=new Uint8Array(t),r="";for(let s of e)r+=String.fromCharCode(s);return btoa(r)}function oi(t){return t.replace(/\+/g,"-").replace(/\//g,"_")}function m(t,e){let r;return {close:()=>(r===void 0&&(r=Promise.resolve(t.return()).then(()=>e())),r),[Symbol.asyncIterator](){return t[Symbol.asyncIterator]()}}}var p=class{#e=new Set;#r;constructor(e){this.#r=e?.deriveServerState??(()=>{});}add(e,r={}){let s={queue:pushable({objectMode:true})};r.matches!==void 0&&(s.matches=r.matches);let n={subscription:e,subscriber:s};return {change:this.#s(n),entry:n}}#s(e){let r=this.serverState();return this.#e.add(e),{before:r,after:this.serverState()}}remove(e){let r=this.serverState();return this.#e.delete(e),e.subscriber.queue.end(),{before:r,after:this.serverState()}}dispatch(e){for(let{subscriber:r}of this.#e)(r.matches===void 0||r.matches(e))&&r.queue.push(e);}hasActiveSubscriptions(){return this.#e.size>0}endAll(e){for(let{subscriber:r}of this.#e)r.queue.end(e);this.#e.clear();}serverState(){return this.#r(this.#e)}};function me(t,e,r){let s=F(r.assetsIds,e.assetsIds),n=F(e.assetsIds,r.assetsIds);s.length>0&&t(Tr(s,r.customFeatureEnabled));let i=r.assetsIds[0];s.length===0&&e.customFeatureEnabled!==r.customFeatureEnabled&&i!==void 0&&t(Tr([i],r.customFeatureEnabled)),n.length>0&&t(ci(n));}function fe(t,e,r){if(r.includeAllMarkets){!e.includeAllMarkets&&e.markets.length>0&&t(xr(e.markets));return}if(e.includeAllMarkets){r.markets.length>0&&t(wr(r.markets));return}let s=F(r.markets,e.markets),n=F(e.markets,r.markets);s.length>0&&t(wr(s)),n.length>0&&t(xr(n));}function Mr(t){let e=new Set,r=false;for(let{subscription:s}of t){for(let n of s.tokenIds)e.add(n);r||=s.customFeatureEnabled===true;}return {assetsIds:Array.from(e),customFeatureEnabled:r}}function Ir(t){let e=false,r=new Set;for(let{subscription:s}of t){if(Lr(s)){e=true;continue}for(let n of s.markets??[])r.add(n);}return {includeAllMarkets:e,markets:e?[]:Array.from(r)}}function Or(t){return {assets_ids:t.assetsIds,custom_feature_enabled:t.customFeatureEnabled,type:"market"}}function Tr(t,e){return {assets_ids:t,custom_feature_enabled:e,operation:"subscribe"}}function ci(t){return {assets_ids:t,operation:"unsubscribe"}}function Fr(t,e){let r={auth:{apiKey:e.key,passphrase:e.passphrase,secret:e.secret},type:"user"};return t.includeAllMarkets||(r.markets=t.markets),r}function wr(t){return {markets:t,operation:"subscribe"}}function xr(t){return {markets:t,operation:"unsubscribe"}}function Dr(t){return e=>{switch(e.type){case "price_change":return e.payload.priceChanges.some(r=>t.tokenIds.includes(r.tokenId));case "new_market":return t.customFeatureEnabled===true;case "market_resolved":return t.customFeatureEnabled===true&&(e.payload.tokenIds??[]).some(r=>t.tokenIds.includes(r));case "best_bid_ask":return t.customFeatureEnabled===true&&t.tokenIds.includes(e.payload.tokenId);default:return t.tokenIds.includes(e.payload.tokenId)}}}function Br(t){if(Lr(t))return ()=>true;let e=new Set((t.markets??[]).map(r=>r.toLowerCase()));return r=>e.has(r.payload.market.toLowerCase())}function Lr(t){return (t.markets?.length??0)===0}function F(t,e){let r=new Set(e);return t.filter(s=>!r.has(s))}var S=class{#e;#r;#s;#o=new jd({heartbeat:new ed});#i=new id;#t=new p({deriveServerState:Mr});constructor(e){this.#e=e.headers,this.#r=e.url;}async subscribe(e){let{change:r,entry:s}=this.#t.add(e,{matches:Dr(e)});return await this.#n(s,r),m(s.subscriber.queue,()=>this.#a(s))}async#n(e,r){let{before:s,after:n}=r;try{(await this.#u()).reusedOpenSocket&&me(o=>this.#o.send(o),s,n);}catch(i){throw await this.#a(e),i}}async#a(e){let{before:r,after:s}=this.#t.remove(e);if(!this.#t.hasActiveSubscriptions()){await this.close();return}me(n=>this.#o.send(n),r,s);}async close(){this.#s===void 0&&(this.#s=this.#d().finally(()=>{this.#s=void 0;})),await this.#s;}async#d(){this.#i.stop(),this.#t.endAll(),await this.#o.close();}#u(){return this.#o.connect({onClose:()=>this.#l(),onError:()=>this.#f(),onMessage:e=>this.#p(e),onOpen:()=>this.#c(),headers:this.#e,url:this.#r})}#c(){this.#i.resetBackoff(),this.#h();}#p(e){let r=Array.isArray(e)?e:[e];for(let s of r){let n=MarketEventSchema.safeParse(s);n.success&&this.#t.dispatch(n.data);}}#l(){this.#t.hasActiveSubscriptions()&&this.#m();}#f(){}#h(){this.#o.send(Or(this.#t.serverState()));}#m(){this.#i.schedule({reconnect:()=>this.#u(),shouldReconnect:()=>this.#t.hasActiveSubscriptions()});}};var R=class{#e;#r;#s;#o;#i=new jd({heartbeat:new ed});#t=new id;#n=new p({deriveServerState:Ir});constructor(e){this.#e=e.credentials,this.#r=e.headers,this.#s=e.url;}async subscribe(e){let{change:r,entry:s}=this.#n.add(e,{matches:Br(e)});return await this.#a(s,r),m(s.subscriber.queue,()=>this.#d(s))}async#a(e,r){let{before:s,after:n}=r;try{(await this.#c()).reusedOpenSocket&&fe(o=>this.#i.send(o),s,n);}catch(i){throw await this.#d(e),i}}async#d(e){let{before:r,after:s}=this.#n.remove(e);if(!this.#n.hasActiveSubscriptions()){await this.close();return}fe(n=>this.#i.send(n),r,s);}async close(){this.#o===void 0&&(this.#o=this.#u().finally(()=>{this.#o=void 0;})),await this.#o;}async#u(){this.#t.stop(),this.#n.endAll(),await this.#i.close();}#c(){return this.#i.connect({onClose:()=>this.#f(),onError:()=>this.#h(),onMessage:e=>this.#l(e),onOpen:e=>this.#p(e),prepare:()=>this.#e,headers:this.#r,url:this.#s})}#p(e){this.#t.resetBackoff(),this.#m(e);}#l(e){let r=Array.isArray(e)?e:[e];for(let s of r){let n=UserEventSchema.safeParse(s);n.success&&this.#n.dispatch(n.data);}}#f(){this.#n.hasActiveSubscriptions()&&this.#y();}#h(){}#m(e){this.#i.send(Fr(this.#n.serverState(),e));}#y(){this.#t.schedule({reconnect:()=>this.#c(),shouldReconnect:()=>this.#n.hasActiveSubscriptions()});}};var g=class{#e;#r;#s;#o;#i=new Set;#t=new Set;#n=new Set;#a=false;constructor(e){this.#e=e.chainId,this.#r=e.headers,this.#s=e.restUrl,this.#o=e.wsUrl;}connect(e){if(this.#a)return Promise.reject(new c("Perps session manager has been shut down."));let r=new md({chainId:this.#e,credentials:e,headers:this.#r,onClose:n=>this.#d(n),restUrl:this.#s,wsUrl:this.#o});this.#t.add(r);let s;return s=(async()=>{try{if(await r.connect(),this.#a)throw await r.close(),new c("Perps session manager has been shut down.");return this.#i.add(r),r}catch(n){throw await r.close(),n}finally{this.#n.delete(s),this.#t.delete(r);}})(),this.#n.add(s),s}async shutdown(){this.#a=true;let e=Array.from(this.#i),r=Array.from(this.#t),s=Array.from(this.#n);this.#i.clear(),this.#t.clear(),this.#n.clear(),await Promise.allSettled([...e.map(n=>n.close()),...r.map(n=>n.close()),...s.map(n=>n.catch(()=>{}))]).then(()=>{});}#d(e){this.#i.delete(e),this.#t.delete(e);}};var b=class{#e;#r;#s;#o=1;#i=new jd({heartbeat:new hd});#t=new id;#n=new p({deriveServerState:li});constructor(e){this.#e=e.headers,this.#r=e.url;}async subscribe(e){let{change:r,entry:s}=this.#n.add(e,{matches:fi(e)});return await this.#a(s,r),m(s.subscriber.queue,()=>this.#d(s))}async#a(e,r){try{(await this.#c()).reusedOpenSocket&&(this.#m(Wr(r.before,r.after)),this.#y(Ur(r.before,r.after)));}catch(s){throw await this.#d(e),s}}async#d(e){let{before:r,after:s}=this.#n.remove(e);this.#m(Wr(r,s)),this.#y(Ur(r,s)),this.#n.hasActiveSubscriptions()||await this.close();}async close(){this.#s===void 0&&(this.#s=this.#u().finally(()=>{this.#s=void 0;})),await this.#s;}async#u(){this.#t.stop(),this.#n.endAll(),await this.#i.close();}#c(){return this.#i.connect({onClose:()=>this.#f(),onError:()=>this.#h(),onMessage:e=>this.#l(e),onOpen:()=>this.#p(),headers:this.#e,url:this.#r})}#p(){this.#t.resetBackoff(),this.#m(Array.from(this.#n.serverState()));}#l(e){let r=PerpsMarketDataEventSchema.safeParse(e);r.success&&this.#n.dispatch(r.data);}#f(){this.#n.hasActiveSubscriptions()&&this.#b();}#h(){}#m(e){e.length!==0&&this.#i.send(this.#S("sub",e));}#y(e){e.length!==0&&this.#i.send(this.#S("unsub",e));}#S(e,r){return {id:this.#o++,req:e,chs:r}}#b(){this.#t.schedule({reconnect:()=>this.#c(),shouldReconnect:()=>this.#n.hasActiveSubscriptions()});}};function li(t){let e=new Set,r=new Set,s=new Set,n=false,i=false;for(let{subscription:o}of t)switch(o.topic){case "perps.tickers":o.instrumentId===void 0?n=true:r.add(o.instrumentId);break;case "perps.statistics":o.instrumentId===void 0?i=true:s.add(o.instrumentId);break;default:e.add(mi(o));}if(n)e.add("tickers::all");else for(let o of r)e.add(`tickers::${o}`);if(i)e.add("statistics::all");else for(let o of s)e.add(`statistics::${o}`);return e}function Wr(t,e){return Array.from(e).filter(r=>!t.has(r))}function Ur(t,e){return Array.from(t).filter(r=>!e.has(r))}function mi(t){switch(t.topic){case "perps.trades":return `trades::${t.instrumentId}`;case "perps.bbo":return `bbo::${t.instrumentId}`;case "perps.book":return `book::${t.instrumentId}`;case "perps.candles":return `klines::${t.instrumentId}::${t.interval}`;case "perps.tickers":return t.instrumentId===void 0?"tickers::all":`tickers::${t.instrumentId}`;case "perps.statistics":return t.instrumentId===void 0?"statistics::all":`statistics::${t.instrumentId}`;default:invariant(false,`Unknown Perps topic: ${String(t)}`);}}function fi(t){switch(t.topic){case "perps.trades":case "perps.bbo":case "perps.book":return e=>e.topic===t.topic&&e.payload.instrumentId===t.instrumentId;case "perps.candles":return e=>e.topic==="perps.candles"&&e.payload.instrumentId===t.instrumentId&&e.payload.interval===t.interval;case "perps.tickers":case "perps.statistics":return e=>e.topic===t.topic&&(t.instrumentId===void 0||e.payload.instrumentId===t.instrumentId);default:invariant(false,`Unknown Perps topic: ${String(t)}`);}}function _r(t,e){return {...e,quote:r=>t.quote(e,r)}}function Kr(t,e){let r=e.rfqId,s=e.quoteId;return {...e,confirm:()=>t.respondToConfirmation(r,s,RfqConfirmationDecision.Confirm),decline:()=>t.respondToConfirmation(r,s,RfqConfirmationDecision.Decline)}}function Vr(t){return {quoteId:t.quoteId,rfqId:t.rfqId}}function jr(t){return {quoteId:t.quoteId,rfqId:t.rfqId}}function zr(t){return {quoteId:t.quoteId,rfqId:t.rfqId}}function $r(t,e){let r=J(t);return {auth:{apiKey:e.key,passphrase:e.passphrase,secret:e.secret},identity:{maker_address:r.maker,signature_type:r.signatureType,signer_address:r.signer},type:"auth"}}function Nr(t,e){return {price_e6:e.price.toString(),rfq_id:t.rfqId,signed_order:e.signedOrder,size_e6:e.size.toString(),type:"RFQ_QUOTE"}}function Yr(t,e,r){let s=J(t);return {maker_address:s.maker,quote_id:r,rfq_id:e,signer_address:s.signer,type:"RFQ_QUOTE_CANCEL"}}function Gr(t,e,r){return {decision:r,quote_id:e,rfq_id:t,type:"RFQ_CONFIRMATION_RESPONSE"}}var D=class{#e=new Map;#r;constructor(e){this.#r=e;}waitFor(e,r){let s=yi(),n,i=setNonBlockingTimeout(()=>{this.remove(e,n),s.reject(new f(r));},this.#r);n=s.promise.finally(()=>clearTimeout(i));let o=this.#e.get(e)??[];return o.push({...s,promise:n}),this.#e.set(e,o),n}resolve(e,r){let s=this.#e.get(e),n=s?.shift();n!==void 0&&(s!==void 0&&s.length===0&&this.#e.delete(e),n.resolve(r));}reject(e,r){let s=this.#e.get(e),n=s?.shift();n!==void 0&&(s!==void 0&&s.length===0&&this.#e.delete(e),n.reject(r));}remove(e,r){let s=this.#e.get(e);if(s===void 0)return;let n=s.filter(i=>i.promise!==r);n.length===0?this.#e.delete(e):this.#e.set(e,n);}rejectAll(e){for(let r of this.#e.values())for(let s of r)s.reject(e);this.#e.clear();}};function yi(){let t,e;return {promise:new Promise((s,n)=>{t=s,e=n;}),reject:e,resolve:t}}var Zr="0x0000000000000000000000000000000000000000000000000000000000000000";async function es(t){let e=J(t.account),r={builder:Zr,maker:e.maker,makerAmount:toBaseUnits(Si(t.orderSide,t.orderPrice,t.size)),metadata:Zr,salt:gi().toString(),side:Ri(t.orderSide),signatureType:e.signatureType,signer:e.signer,takerAmount:toBaseUnits(bi(t.orderSide,t.orderPrice,t.size)),timestamp:Math.floor(Date.now()/1e3).toString(),tokenId:t.tokenId},s;try{s=await t.signer.signTypedData(Mc({domain:Xr(t),order:r}));}catch(n){throw j.fromError(n,"Could not sign the RFQ quote order.")}return {...r,signature:Nc({domain:Xr(t),order:r,signature:s})}}function Xr(t){return {chainId:t.chainId,exchange:t.exchange,protocolVersion:"3"}}function Si(t,e,r){return t===OrderSide.SELL?r.toString():((e*r+999999n)/1000000n).toString()}function bi(t,e,r){return t===OrderSide.SELL?(e*r/1000000n).toString():r.toString()}function Ri(t){return t===OrderSide.BUY?0:1}function gi(){let t=new Uint8Array(8);return globalThis.crypto.getRandomValues(t),BigInt(`0x${Array.from(t,e=>e.toString(16).padStart(2,"0")).join("")}`)}var ss=DecimalishSchema.transform(t=>os(t)).refine(t=>t<=BigInt(Number.MAX_SAFE_INTEGER),{message:"Value exceeds the temporary numeric wire limit."}),vi=z.strictObject({price:ss.refine(t=>t<1000000n,{message:"Price must be less than 1."}),size:ss.optional(),source:z.enum(["collateral","inventory"]).default("collateral")});function ns(t){return G(t,vi)}async function is(t){let e=t.response.price,r=t.response.size===void 0?ki(t.request.requestedSize,e):t.response.size,s=await es({account:t.account,chainId:t.chainId,exchange:t.exchange,orderPrice:Ci(t.request,t.response.source,e),orderSide:Ei(t.response.source),signer:t.signer,size:r,tokenId:Ai(t.request,t.response.source)});return {price:e,signedOrder:s,size:r}}function Ai(t,e){return t.direction===RfqDirection.Buy?e==="collateral"?t.noPositionId:t.yesPositionId:e==="collateral"?t.yesPositionId:t.noPositionId}function Ci(t,e,r){return t.direction===RfqDirection.Buy&&e==="collateral"||t.direction===RfqDirection.Sell&&e==="inventory"?1000000n-r:r}function Ei(t){return t==="collateral"?OrderSide.BUY:OrderSide.SELL}function ki(t,e){let r=os(t.value);return t.unit===RfqRequestedSizeUnit.Shares?r:r*1000000n/e}function os(t){let e=/^(\d+)(?:\.(\d*))?$/.exec(t);if(e===null)throw new a("Value must be a valid decimal.");let[,r="",s=""]=e;if(s.length>6)throw new a("Value must have at most 6 decimal places.");let n=BigInt(r)*1000000n+BigInt(s.padEnd(6,"0"));if(n<=0n)throw new a("Value must be greater than 0.");return n}var Ii=3e4,Oi=3e4,P=class{#e;#r;#s;#o;#i;#t;#n;#a;#d;#u;#c=false;constructor(e){this.#e=e.account,this.#r=e.chainId,this.#s=e.credentials,this.#o=e.exchange,this.#i=e.headers,this.#t=e.signer,this.#n=e.url;}async connect(){if(this.#c)throw new c("RFQ quoter manager has been shut down.");if(this.#a!==void 0){if(!this.#a.closed)return this.#a;this.#a=void 0;}if(this.#u!==void 0)return this.#u;let e=new Re({account:this.#e,chainId:this.#r,credentials:this.#s,exchange:this.#o,headers:this.#i,onClose:()=>this.#p(e),signer:this.#t,url:this.#n});this.#d=e;let r;return r=(async()=>{try{if(await e.connect(),this.#c)throw await e.close(),new c("RFQ quoter manager has been shut down.");return this.#a=e,e}catch(s){throw await e.close(),s}finally{this.#u===r&&(this.#u=void 0),this.#d===e&&(this.#d=void 0);}})(),this.#u=r,r}async shutdown(){this.#c=true;let e=this.#a,r=this.#d,s=this.#u;this.#a=void 0,this.#d=void 0,this.#u=void 0,await Promise.allSettled([e?.close(),r?.close(),s?.catch(()=>{})]).then(()=>{});}#p(e){this.#a===e&&(this.#a=void 0),this.#d===e&&(this.#d=void 0);}},Re=class{#e;#r;#s;#o;#i;#t;#n;#a;#d=new jd;#u=pushable({objectMode:true});#c=new D(Oi);#p;#l;constructor(e){this.#e=e.account,this.#r=e.chainId,this.#s=e.credentials,this.#o=e.exchange,this.#i=e.headers,this.#t=e.onClose,this.#n=e.signer,this.#a=e.url;}get closed(){return this.#p!==void 0}async connect(){let e=Fi();this.#l=e;let r=setNonBlockingTimeout(()=>{e.reject(new c("RFQ quoter authentication timed out."));},Ii);try{await this.#d.connect({headers:this.#i,onClose:()=>this.#P(),onError:()=>{},onMessage:s=>this.#R(s),onOpen:()=>this.#b(),url:this.#a}),await e.promise;}finally{clearTimeout(r),this.#l=void 0;}}async#f(e){if(!this.#d.send(e))throw new c("RFQ quoter websocket is not open.")}async close(){this.#p===void 0&&(this.#p=this.#h()),await this.#p;}[Symbol.asyncIterator](){return this.#u[Symbol.asyncIterator]()}async#h(){let e=new c("RFQ quoter websocket closed.");await this.#y(e);}async#m(e){this.#p===void 0&&(this.#p=this.#y(e)),await this.#p;}async#y(e){this.#S(e),this.#u.end(),await this.#d.close(),this.#t();}#S(e){this.#l?.reject(e),this.#c.rejectAll(e);}#b(){this.#d.send($r(this.#e,this.#s));}#R(e){if(this.#p!==void 0||!RfqKnownInboundMessageSchema.safeParse(e).success)return;let r=RfqQuoterInboundMessageSchema.safeParse(e);if(!r.success){let n=new c("Invalid RFQ quoter message.",{cause:r.error});this.#m(n);return}let s=r.data;switch(s.type){case "auth":this.#g(s);return;case "quote_request":this.#u.push(_r(this,s));return;case "quote_ack":this.#c.resolve(B(s.rfqId),Vr(s));return;case "quote_cancel_ack":this.#c.resolve(Se(s.rfqId,s.quoteId),jr(s));return;case "confirmation_request":this.#u.push(Kr(this,s));return;case "confirmation_ack":this.#c.resolve(be(s.rfqId,s.quoteId),zr(s));return;case "execution_update":this.#u.push(s);return;case "trade":this.#u.push(s);return;case "rfq_error":this.#q(s);return}}#g(e){if(e.success===true){this.#l?.resolve(void 0);return}this.#l?.reject(new c(`RFQ quoter authentication failed: ${e.error}`));}#P(){this.#t(),this.close();}#q(e){if(e.requestType==="RFQ_QUOTE"){if(e.rfqId===void 0){this.#m(new c("Uncorrelated RFQ quoter error."));return}this.#c.reject(B(e.rfqId),new Ge(e.message,{code:e.code,errorId:e.errorId,rfqId:e.rfqId}));return}if(e.requestType==="RFQ_QUOTE_CANCEL"){if(e.rfqId===void 0||e.quoteId===void 0){this.#m(new c("Uncorrelated RFQ quoter error."));return}this.#c.reject(Se(e.rfqId,e.quoteId),new Ie(e.message,{code:e.code,errorId:e.errorId,quoteId:e.quoteId,rfqId:e.rfqId}));return}if(e.requestType==="RFQ_CONFIRMATION_RESPONSE"){if(e.rfqId===void 0||e.quoteId===void 0){this.#m(new c("Uncorrelated RFQ quoter error."));return}this.#c.reject(be(e.rfqId,e.quoteId),new Ke(e.message,{code:e.code,errorId:e.errorId,quoteId:e.quoteId,rfqId:e.rfqId}));}}async quote(e,r){let s=ns(r),n=await is({account:this.#e,chainId:this.#r,exchange:this.#o,request:e,response:s,signer:this.#n}),i=this.#c.waitFor(B(e.rfqId),`Timed out waiting for RFQ quote acknowledgement for ${e.rfqId}.`);try{return await this.#f(Nr(e,n)),await i}catch(o){throw this.#c.remove(B(e.rfqId),i),o}}async cancelQuote(e){let r=Se(e.rfqId,e.quoteId),s=this.#c.waitFor(r,`Timed out waiting for RFQ quote cancellation acknowledgement for ${e.rfqId}.`);try{return await this.#f(Yr(this.#e,e.rfqId,e.quoteId)),await s}catch(n){throw this.#c.remove(r,s),n}}async respondToConfirmation(e,r,s){let n=be(e,r),i=this.#c.waitFor(n,`Timed out waiting for RFQ confirmation acknowledgement for ${e}.`);try{return await this.#f(Gr(e,r,s)),await i}catch(o){throw this.#c.remove(n,i),o}}};function B(t){return `ACK_RFQ_QUOTE:${t}`}function Se(t,e){return `ACK_RFQ_QUOTE_CANCEL:${t}:${e}`}function be(t,e){return `ACK_RFQ_CONFIRMATION_RESPONSE:${t}:${e}`}function Fi(){let t,e;return {promise:new Promise((s,n)=>{t=s,e=n;}),reject:e,resolve:t}}var q=class{#e;#r;#s;#o=new jd({heartbeat:new fd});#i=new id;#t=new p({deriveServerState:Wi});constructor(e){this.#e=e.headers,this.#r=e.url;}async subscribe(e){let{change:r,entry:s}=this.#t.add(e,{matches:_i(e)});return await this.#n(s,r),m(s.subscriber.queue,()=>this.#a(s))}async#n(e,r){try{if((await this.#u()).reusedOpenSocket){let{before:n,after:i}=r,o=Bi(n,i);this.#m(o);}}catch(s){throw await this.#a(e),s}}async#a(e){let{before:r,after:s}=this.#t.remove(e),n=Li(r,s);this.#y(n),this.#t.hasActiveSubscriptions()||await this.close();}async close(){this.#s===void 0&&(this.#s=this.#d().finally(()=>{this.#s=void 0;})),await this.#s;}async#d(){this.#i.stop(),this.#t.endAll(),await this.#o.close();}#u(){return this.#o.connect({onClose:()=>this.#l(),onError:()=>this.#f(),onMessage:e=>this.#p(e),onOpen:()=>this.#c(),headers:this.#e,url:this.#r})}#c(){this.#i.resetBackoff(),this.#h();}#p(e){let r=RealtimeEventSchema.safeParse(e);r.success&&this.#t.dispatch(r.data);}#l(){this.#t.hasActiveSubscriptions()&&this.#S();}#f(){}#h(){this.#m(Array.from(this.#t.serverState().values()));}#m(e){e.length!==0&&this.#o.send(Ui(e));}#y(e){e.length!==0&&this.#o.send(Qi(e));}#S(){this.#i.schedule({reconnect:()=>this.#u(),shouldReconnect:()=>this.#t.hasActiveSubscriptions()});}};function Bi(t,e){return Array.from(e).flatMap(([r,s])=>t.has(r)?[]:[s])}function Li(t,e){return Array.from(t).flatMap(([r,s])=>e.has(r)?[]:[s])}function Wi(t){let e=new Map;for(let{subscription:r}of t)for(let s of Hi(r))e.has(s.key)||e.set(s.key,s);return e}function Ui(t){return {action:"subscribe",subscriptions:t.map(({topic:e,type:r})=>({topic:e,type:r}))}}function Qi(t){return {action:"unsubscribe",subscriptions:t.map(({topic:e,type:r})=>({topic:e,type:r}))}}function Hi(t){switch(t.topic){case "comments":return (t.types??["comment_created"]).map(e=>L("comments",e));case "prices.crypto.binance":return [L("crypto_prices","update")];case "prices.crypto.chainlink":return [L("crypto_prices_chainlink","update")];case "prices.equity.pyth":return [L("equity_prices","update")];default:invariant(false,`Unknown RTDS topic: ${String(t)}`);}}function L(t,e){return {key:`${t}:${e}`,topic:t,type:e}}function _i(t){switch(t.topic){case "comments":return e=>!(e.topic!=="comments"||t.types!==void 0&&t.types.length>0&&!t.types.includes(e.type)||(t.parentEntityId!==void 0||t.parentEntityType!==void 0)&&(!(e.type==="comment_created"||e.type==="comment_removed")||t.parentEntityId!==void 0&&e.payload.parentEntityID!==t.parentEntityId||t.parentEntityType!==void 0&&e.payload.parentEntityType!==t.parentEntityType));case "prices.crypto.binance":return e=>e.topic==="prices.crypto.binance"&&(t.symbols===void 0||t.symbols.length===0||t.symbols.includes(e.payload.symbol));case "prices.crypto.chainlink":return e=>e.topic==="prices.crypto.chainlink"&&(t.symbols===void 0||t.symbols.length===0||t.symbols.includes(e.payload.symbol));case "prices.equity.pyth":return e=>e.topic==="prices.equity.pyth"&&e.payload.symbol.toLowerCase()===t.symbol.toLowerCase()&&(t.types===void 0||t.types.length===0||t.types.includes(e.type));default:invariant(false,`Unknown RTDS topic: ${String(t)}`);}}var v=class{#e;#r;#s;#o=new jd({heartbeat:new gd});#i=new id;#t=new p;constructor(e){this.#e=e.headers,this.#r=e.url;}async subscribe(e){let{entry:r}=this.#t.add(e);return await this.#n(r),m(r.subscriber.queue,()=>this.#a(r))}async#n(e){try{await this.#u();}catch(r){throw await this.#a(e),r}}async#a(e){this.#t.remove(e),this.#t.hasActiveSubscriptions()||await this.close();}async close(){this.#s===void 0&&(this.#s=this.#d().finally(()=>{this.#s=void 0;})),await this.#s;}async#d(){this.#i.stop(),this.#t.endAll(),await this.#o.close();}#u(){return this.#o.connect({onClose:()=>this.#l(),onError:()=>this.#f(),onMessage:e=>this.#p(e),onOpen:()=>this.#c(),headers:this.#e,url:this.#r})}#c(){this.#i.resetBackoff();}#p(e){let r=SportsResultEventSchema.safeParse(e);r.success&&this.#t.dispatch(r.data);}#l(){this.#t.hasActiveSubscriptions()&&this.#h();}#f(){}#h(){this.#i.schedule({reconnect:()=>this.#u(),shouldReconnect:()=>this.#t.hasActiveSubscriptions()});}};var W=class{#e;#r;get context(){return this.#e}get decorators(){return this.#r}get environment(){return this.context.environment}get clob(){return this.context.clob}get relayer(){return this.context.relayer}get rpc(){return this.context.rpc}get gamma(){return this.context.gamma}get data(){return this.context.data}get rfq(){return this.context.rfq}get perps(){return this.context.perps}get webSockets(){return this.context.webSockets}get supportsGasless(){return this.context.apiKey?.supportGasless??false}constructor(e){this.#e=e,this.#r=[];}async resolveClobHeaders(e){return this.context.apiKey?.isBuilderKey?this.context.apiKey.authorize(e):Promise.resolve({})}async resolveRelayerHeaders(e){return this.context.apiKey?.supportGasless?this.context.apiKey.authorize(e):Promise.resolve({})}rememberDecorator(e){this.#r.push(e);}},Yi=z.object({key:ApiKeySchema,passphrase:z.string(),secret:z.string()}),Gi=z.object({wallet:EvmAddressSchema,credentials:Yi.optional(),nonce:z.number().int().nonnegative().optional()}).superRefine((t,e)=>{t.credentials!==void 0&&t.nonce!==void 0&&e.addIssue({code:"custom",message:"`credentials` and `nonce` are mutually exclusive.",path:["nonce"]});}).transform(t=>t.credentials!==void 0?{wallet:t.wallet,credentials:t.credentials}:t.nonce!==void 0?{wallet:t.wallet,nonce:t.nonce}:{wallet:t.wallet}),U=class extends W{constructor(e){super({apiKey:e.apiKey,environment:e.environment,data:new dd({headers:e.environment.data.headers,root:e.environment.data.rest}),gamma:new dd({headers:e.environment.gamma.headers,root:e.environment.gamma.rest}),clob:new dd({headers:e.environment.clob.headers,root:e.environment.clob.rest,resolveHeaders:r=>this.resolveClobHeaders(r)}),relayer:new dd({headers:e.environment.relayer.headers,root:e.environment.relayer.rest,resolveHeaders:r=>this.resolveRelayerHeaders(r)}),rfq:new dd({headers:e.environment.rfq.headers,root:e.environment.rfq.rest}),perps:new dd({headers:e.environment.perps.headers,root:e.environment.perps.rest}),rpc:new H({url:e.environment.rpc}),webSockets:{clobMarket:new S({headers:e.environment.clob.market.headers,url:e.environment.clob.market.ws}),sports:new v({headers:e.environment.sports.headers,url:e.environment.sports.ws}),rtds:new q({headers:e.environment.rtds.headers,url:e.environment.rtds.ws}),perpsSubscriptions:new b({headers:e.environment.perps.headers,url:e.environment.perps.ws})}});}isSecureClient(){return false}isPublicClient(){return true}async closeSubscriptions(){await Promise.all([this.webSockets.clobMarket.close(),this.webSockets.rtds.close(),this.webSockets.sports.close(),this.webSockets.perpsSubscriptions.close()]).then(()=>{});}extend(e){return this.rememberDecorator(e),Object.assign(this,e(this)),this}beginAuthentication(e,r){let s=G(e,Gi);return Promise.resolve(async function*(){let n=Math.floor(Date.now()/1e3),i=s?.nonce??0,o=expectEvmAddress(yield ta()),A=expectEvmAddress(s.wallet),ve=I$1(this.environment,o,A);if(s.credentials!==void 0){let Ae=this.#e(s.credentials,ve,r);try{if((await Ya(Ae)).includes(s.credentials.key))return Ae}catch(T){if(!(T instanceof d)||T.status!==401)throw T}}let us=yield {kind:"signAuthMessage",payload:Pr({address:o,chainId:this.environment.chainId,nonce:i,timestamp:n})},ds=await Wa(this,{address:o,nonce:i,signature:expectEvmSignature(us),timestamp:n});return this.#e(ds,ve,r)}.call(this))}#e(e,r,s){let n=new qe({account:r,apiKey:this.context.apiKey,credentials:e,environment:this.environment,signer:s});for(let i of this.decorators)n.extend(i);return n}},qe=class extends W{#e=false;get context(){return invariant(!this.#e,"This client has ended authentication and can no longer be used."),super.context}endAuthenticationLifecycle(){this.#e=true;}constructor(e){super({account:e.account,credentials:e.credentials,apiKey:e.apiKey,environment:e.environment,signer:e.signer,clob:new dd({headers:e.environment.clob.headers,root:e.environment.clob.rest,resolveHeaders:r=>this.resolveClobHeaders(r)}),relayer:new dd({headers:e.environment.relayer.headers,root:e.environment.relayer.rest,resolveHeaders:r=>this.resolveRelayerHeaders(r)}),rpc:new H({url:e.environment.rpc}),gamma:new dd({headers:e.environment.gamma.headers,root:e.environment.gamma.rest}),data:new dd({headers:e.environment.data.headers,root:e.environment.data.rest}),rfq:new dd({headers:e.environment.rfq.headers,root:e.environment.rfq.rest}),perps:new dd({headers:e.environment.perps.headers,root:e.environment.perps.rest}),secureClob:new dd({headers:e.environment.clob.headers,resolveHeaders:async r=>({...await this.resolveClobHeaders(r),...await this.#r(r)}),root:e.environment.clob.rest}),webSockets:{clobMarket:new S({headers:e.environment.clob.market.headers,url:e.environment.clob.market.ws}),clobUser:new R({credentials:e.credentials,headers:e.environment.clob.user.headers,url:e.environment.clob.user.ws}),rfqQuoter:new P({account:e.account,chainId:e.environment.chainId,credentials:e.credentials,exchange:e.environment.contracts.exchangeV3,headers:e.environment.rfq.headers,signer:e.signer,url:e.environment.rfq.ws}),sports:new v({headers:e.environment.sports.headers,url:e.environment.sports.ws}),rtds:new q({headers:e.environment.rtds.headers,url:e.environment.rtds.ws}),perpsSubscriptions:new b({headers:e.environment.perps.headers,url:e.environment.perps.ws}),perpsSession:new g({chainId:e.environment.chainId,headers:e.environment.perps.headers,restUrl:e.environment.perps.rest,wsUrl:e.environment.perps.ws})}});}get credentials(){return this.context.credentials}get account(){return this.context.account}get signer(){return this.context.signer}setupGaslessWallet(){return Promise.resolve(this)}get secureClob(){return this.context.secureClob}get webSockets(){return this.context.webSockets}async closeSubscriptions(){await Promise.allSettled([this.webSockets.clobMarket.close(),this.webSockets.rtds.close(),this.webSockets.sports.close(),this.webSockets.perpsSubscriptions.close(),this.webSockets.clobUser.close()]).then(()=>{});}isSecureClient(){return true}isPublicClient(){return false}extend(e){return this.rememberDecorator(e),Object.assign(this,e(this)),this}async endAuthentication(){let e=this.closeSubscriptions(),r=this.webSockets.perpsSession.shutdown(),s=this.webSockets.rfqQuoter.shutdown(),{apiKey:n,environment:i}=this.context;try{await _a(this);}finally{this.endAuthenticationLifecycle(),await Promise.allSettled([e,r,s]).then(()=>{});}let o=new U({apiKey:n,environment:i});for(let A of this.decorators)o.extend(A);return o}async#r(e){try{let r=Math.floor(Date.now()/1e3);return {POLY_ADDRESS:this.account.signer,POLY_API_KEY:this.credentials.key,POLY_PASSPHRASE:this.credentials.passphrase,POLY_SIGNATURE:await kr(this.credentials.secret,r,e.method,e.path,e.body),POLY_TIMESTAMP:`${r}`}}catch(r){throw j.fromError(r,"Could not sign the L2-authenticated request")}}};function cs(t={}){return new U({environment:t.environment??pe,apiKey:t.apiKey}).extend(Cr)}var Ji=k(h,e,d,j,f,g$1,c,b$1,a),Zi=k(a);async function Xi(t){let e=cs({environment:t.environment,apiKey:t.apiKey}),r=await eo(e,t),s=await e.beginAuthentication({wallet:r,credentials:t.credentials,nonce:t.nonce},t.signer).then(sa(t.signer));if(s.account.walletType===WalletType.EOA||await xa(s,{wallet:s.account.wallet,type:s.account.walletType}))return s;if(s.account.walletType===WalletType.DEPOSIT_WALLET)return await to(s),s;throw new a(`Wallet ${s.account.wallet} does not exist. Provide an existing wallet address, or omit wallet to use the default Deposit Wallet flow.`)}async function eo(t,e){if(e.wallet!==void 0)return e.wallet;let r=expectEvmAddress(await e.signer.getAddress()),s=K(r,t.environment.walletDerivation);return await xa(t,{wallet:s,type:WalletType.DEPOSIT_WALLET})?s:L$1(r,t.environment.walletDerivation)}async function to(t){let e=L$1(t.account.signer,t.environment.walletDerivation);if(!isSameEvmAddress(t.account.wallet,e))throw new a(`Wallet ${t.account.wallet} does not match the expected Deposit Wallet ${e} for this signer, nor a deployed wallet address.`);await(await Aa(t)).wait();}
2
+ export{Ji as CreateSecureClientError,Zi as SetupGaslessWalletError,ne as accountActions,Cr as allActions,ie as analyticsActions,kr as buildHmacSignature,cs as createPublicClient,Xi as createSecureClient,oe as dataActions,ae as discoveryActions,si as forkEnvironmentConfig,ce as perpsActions,Qa as preproduction,pe as production,ei as relayerApiKey,Xn as remoteBuilderSigning,ue as rewardsActions,qr as rfqActions,de as subscriptionsActions,vr as tradingActions,Ar as walletActions};//# sourceMappingURL=index.js.map
3
3
  //# sourceMappingURL=index.js.map