@polymarket/client 0.1.0-beta.8 → 0.1.0-beta.9

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-5uGoLhNm.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';
package/dist/index.d.ts CHANGED
@@ -2,18 +2,18 @@ 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
7
  export { ActivityType, ComboPositionStatus } from '@polymarket/bindings/data';
8
8
  export * from '@polymarket/bindings/gamma';
9
9
  export { WalletType } from '@polymarket/bindings/gamma';
10
10
  export * from '@polymarket/bindings/perps';
11
- export { PerpsDepositStatus, PerpsInstrumentCategory, PerpsInstrumentType, PerpsInternalTransferDirection, PerpsKlineInterval, PerpsSide, PerpsTimeInForce, PerpsWithdrawalStatus } from '@polymarket/bindings/perps';
11
+ export { PerpsCancelOrderResult, PerpsDepositStatus, PerpsInstrumentCategory, PerpsInstrumentType, PerpsInternalTransferDirection, PerpsKlineInterval, PerpsOrderStatus, PerpsPostOrderAck, PerpsSide, PerpsTimeInForce, PerpsWithdrawalStatus } from '@polymarket/bindings/perps';
12
12
  export * from '@polymarket/bindings/relayer';
13
13
  import { EvmAddress } from '@polymarket/types';
14
- import { U as UserInputError, b as TransactionCall, A as ApiKeyAuthorization } from './types-5uGoLhNm.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 SecureAccountActions, bf as SecureActions, bg as SecureClient, bh as SecureClientOptions, bi as SecureDownloadAccountingSnapshotRequest, bj as SecureFetchPortfolioValueRequest, bk as SecureFetchTradedMarketCountRequest, bl as SecureListActivityRequest, bm as SecureListClosedPositionsRequest, bn as SecureListComboPositionsRequest, bo as SecureListPositionsRequest, bp as SecurePerpsActions, bq as SecureRewardsActions, br as SecureRfqActions, bs as SecureSubscriptionsActions, bt as SecureTradingActions, bu as SecureWalletActions, bv as SetupGaslessWalletError, bw as SetupTradingApprovalsError, S as Signer, bx as SignerTransactionRequest, by as SigningError, bz as SplitPositionError, bA as TimeoutError, bB as TransactionFailedError, bC as TransactionHandle, bD as TransactionOutcome, bE as TransferErc20Error, bF as TransportError, a as TypedData, bG as TypedDataDomain, bH as TypedDataField, T as TypedDataPayload, bI as UnexpectedResponseError, bJ as WaitForTransactionError, bK as WalletDerivationConfig, bL as WebSocketEndpoint, bM as accountActions, bN as allActions, bO as analyticsActions, bP as createPublicClient, bQ as createSecureClient, bR as dataActions, bS as discoveryActions, bT as forkEnvironmentConfig, bU as makeErrorGuard, bV as perpsActions, bW as production, bX as rewardsActions, bY as rfqActions, bZ as subscriptionsActions, b_ as tradingActions, b$ as walletActions } from './types-5uGoLhNm.js';
16
- export { C as CreateLimitOrderError, a as CreateMarketOrderError, F as FetchSportsMarketTypesError, L as ListSportsError, P as PlaceLimitOrderError, b as PlaceMarketOrderError } from './sports-_kLx9-gD.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
17
  export { PerpsSessionEvent } from '@polymarket/bindings/subscriptions';
18
18
  export { RfqConfirmationDecision, RfqConfirmationRequest, RfqDirection, RfqErrorCode, RfqExecutionStatus, RfqExecutionUpdate, RfqId, RfqQuoteId, RfqQuoteRequest, RfqRequestedSize, RfqRequestedSizeUnit, RfqRequestorPublicId, RfqSide, RfqTrade } from '@polymarket/bindings/rfq';
19
19
  import 'zod';
package/dist/index.js CHANGED
@@ -1,3 +1,3 @@
1
- import {ra as ra$1,Ba as Ba$1,za,xa as xa$1,Va,Sd,Qd,Od,Md,Ld,Id,lc as lc$1,jc,hc as hc$1,jb,Ta,vc,xc,Jc,Pb,Nb,Lb,Jb,Hb,Fb,Db,Bb,zb,nb,lb,fc as fc$1,Zb,Xb,Vb,ze,gf,Xe as Xe$1,Ve,Pe,ef,cf,af,_e as _e$1,Te,Re,tc as tc$1,rc as rc$1,pc,nc as nc$1,dc,bc,$b,Gd,Dd,Cd,Fd,Ra,Pa,Na,La as La$1,Ja as Ja$1,Ha,He as He$1,Ye,va as va$1,ta as ta$1,Hc,Fc,Dc,Bc,Oc,Nc,fd,dd,bd,$c,xe as xe$1,se as se$1,je as je$1,kf,db,$a,hb,aa as aa$1,ha as ha$1,$,ka as ka$1,ud,sd,qd,md,kd,id,wd,od,zc,Tb,Rb,Y,X as X$1,ba,Z as Z$1,O as O$1,M as M$1,Q as Q$1,G,gd,Ae,Ce,Ee,pa as pa$1,_ as _$1,ca,da,Pc as Pc$1,Qc}from'./chunk-GZWA532J.js';export{cb as ApproveErc1155ForAllError,_a as ApproveErc20Error,Ec as CancelAllError,Gc as CancelMarketOrdersError,Ac as CancelOrderError,Cc as CancelOrdersError,C as CombinatorialPrepareConditionCallError,Td as ComboPositionStatus,cd as CreateLimitOrderError,_c as CreateMarketOrderError,q as CtfRedeemPositionsCallError,Rd as DownloadAccountingSnapshotError,Aa as DropNotificationsError,b as Erc20ApprovalCallError,m as Erc20TransferCallError,Ic as EstimateMarketPriceError,qa as FetchClosedOnlyModeError,Wb as FetchCommentsByIdError,ac as FetchEventError,ec as FetchEventLiveVolumeError,cc as FetchEventTagsError,Kb as FetchLastTradePriceError,Mb as FetchLastTradePricesError,qc as FetchMarketError,sc as FetchMarketTagsError,kb as FetchMidpointError,mb as FetchMidpointsError,ya as FetchNotificationsError,Cb as FetchOrderBookError,Eb as FetchOrderBooksError,ua as FetchOrderError,Ga as FetchOrderScoringError,Ia as FetchOrdersScoringError,Nd as FetchPortfolioValueError,yb as FetchPriceError,Ob as FetchPriceHistoryError,Ab as FetchPricesError,ye as FetchPublicProfileError,df as FetchRelatedTagResourcesError,bf as FetchRelatedTagsError,Qa as FetchRewardPercentagesError,Se as FetchSeriesError,We as FetchSportsMarketTypesError,Gb as FetchSpreadError,Ib as FetchSpreadsError,$e as FetchTagError,Ma as FetchTotalEarningsForUserForDayError,Pd as FetchTradedMarketCountError,wa as ListAccountTradesError,Ua as ListActivityError,gc as ListBuilderLeaderboardError,ib as ListBuilderTradesError,ic as ListBuilderVolumeError,Jd as ListClosedPositionsError,oc as ListComboMarketsError,Kd as ListComboPositionsError,Yb as ListCommentsByUserAddressError,Ub as ListCommentsError,Qb as ListCurrentRewardsError,_b as ListEventsError,uc as ListMarketHoldersError,yc as ListMarketPositionsError,Sb as ListMarketRewardsError,mc as ListMarketsError,wc as ListOpenInterestError,sa as ListOpenOrdersError,Hd as ListPositionsError,Qe as ListSeriesError,Ue as ListSportsError,Ze as ListTagsError,ff as ListTeamsError,kc as ListTraderLeaderboardError,Sa as ListTradesError,Oa as ListUserEarningsAndMarketsConfigError,Ka as ListUserEarningsForDayError,a as MAX_UINT256,t as MergePositionsCallError,ne as MergePositionsError,y as MergeV2CallError,Ge as OpenRfqSessionError,o as PerpsDepositCallError,ed as PlaceLimitOrderError,ad as PlaceMarketOrderError,Lc as PostOrderError,Mc as PostOrdersError,we as RedeemPositionsError,A as RedeemV2CallError,De as RfqCancelQuoteError,Ce as RfqCancelQuoteRejectedError,Ie as RfqConfirmationDecision,Fe as RfqConfirmationError,Ee as RfqConfirmationRejectedError,Je as RfqDirection,Ke as RfqErrorCode,Le as RfqExecutionStatus,Be as RfqQuoteError,Ae as RfqQuoteRejectedError,Me as RfqRequestedSizeUnit,Ne as RfqSide,Oe as SearchError,gb as SetupTradingApprovalsError,r as SplitPositionCallError,ee as SplitPositionError,w as SplitV2CallError,jf as TransferErc20Error,Wa 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,Xa as expectTransactionHandle,u as mergePositionsCall,z as mergeV2Call,p as perpsDepositCall,B as redeemV2Call,s as splitPositionCall,x as splitV2Call}from'./chunk-GZWA532J.js';import {a,k,h,e,d,j,f,g as g$1,c,b}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 {TxHashSchema,PaginationCursorSchema,DecimalishSchema,ApiKeySchema,EvmAddressSchema,toDecimalString,toPaginationCursor,toBaseUnits,OrderSide}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 {PerpsPnlIntervalSchema,PerpsWithdrawalStatusSchema,PerpsDepositStatusSchema,PerpsInstrumentIdSchema,PerpsClientOrderIdSchema,PerpsOrderIdSchema,PerpsTimeInForceSchema,PerpsDecimalInputSchema,PerpsCommandAckSchema,FetchPerpsBalancesResponseSchema,FetchPerpsPortfolioResponseSchema,FetchPerpsAccountConfigResponseSchema,FetchPerpsOpenOrdersResponseSchema,FetchPerpsOrdersResponseSchema,ListPerpsFillsResponseSchema,ListPerpsFundingPaymentsResponseSchema,ListPerpsDepositsResponseSchema,ListPerpsWithdrawalsResponseSchema,ListPerpsEquityHistoryResponseSchema,ListPerpsPnlHistoryResponseSchema,RawPerpsOrderCommandAckSchema}from'@polymarket/bindings/perps';export{PerpsDepositStatus,PerpsInstrumentCategory,PerpsInstrumentType,PerpsInternalTransferDirection,PerpsKlineInterval,PerpsSide,PerpsTimeInForce,PerpsWithdrawalStatus}from'@polymarket/bindings/perps';import {z}from'zod';import {expectEvmAddress,isSameEvmAddress,expectEvmSignature,ResultAsync,invariant,setNonBlockingInterval,setNonBlockingTimeout,unwrap,expectPresent}from'@polymarket/types';import yo from'ky';import {PerpsMarketDataEventSchema,RealtimeEventSchema,SportsResultEventSchema,MarketEventSchema,UserEventSchema,PerpsSessionUpdateEventSchema}from'@polymarket/bindings/subscriptions';import {pushable}from'it-pushable';import {RfqKnownInboundMessageSchema,RfqQuoterInboundMessageSchema,RfqConfirmationDecision,RfqRequestedSizeUnit,RfqDirection}from'@polymarket/bindings/rfq';var io=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 oo(t){return new we(t)}function ao(t){return new xe(t)}var we=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#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#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.#t(),method:"POST",mode:"cors"});if(!r.ok)throw new Error(`Remote signer rejected request with status ${r.status}`);return io.parse(await r.json())}},xe=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 rs(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 co(t){return {listPositions:Id.bind(null,t),listClosedPositions:Ld.bind(null,t),listComboPositions:Md.bind(null,t),fetchPortfolioValue:Od.bind(null,t),fetchTradedMarketCount:Qd.bind(null,t),downloadAccountingSnapshot:Sd.bind(null,t),listMarketPositions:zc.bind(null,t),listActivity:Va.bind(null,t)}}function x(t,e={}){return {...e,user:e.user??t.account.wallet}}function Oe(t){let e=co(t);return t.isPublicClient()?e:{...e,listPositions:r=>Id(t,x(t,r)),listClosedPositions:r=>Ld(t,x(t,r)),listComboPositions:r=>Md(t,x(t,r)),fetchPortfolioValue:r=>Od(t,x(t,r)),fetchTradedMarketCount:r=>Qd(t,x(t,r)),downloadAccountingSnapshot:r=>Sd(t,x(t,r)),listActivity:r=>Va(t,x(t,r)),listAccountTrades:xa$1.bind(null,t),fetchNotifications:za.bind(null,t),dropNotifications:Ba$1.bind(null,t),fetchClosedOnlyMode:ra$1.bind(null,t)}}function Ie(t){return {listBuilderTrades:jb.bind(null,t),listBuilderLeaderboard:hc$1.bind(null,t),fetchBuilderVolume:jc.bind(null,t),listTraderLeaderboard:lc$1.bind(null,t)}}function Me(t){return {fetchEventLiveVolume:fc$1.bind(null,t),fetchMidpoint:lb.bind(null,t),fetchMidpoints:nb.bind(null,t),fetchPrice:zb.bind(null,t),fetchPrices:Bb.bind(null,t),fetchOrderBook:Db.bind(null,t),fetchOrderBooks:Fb.bind(null,t),fetchSpread:Hb.bind(null,t),fetchSpreads:Jb.bind(null,t),fetchLastTradePrice:Lb.bind(null,t),fetchLastTradePrices:Nb.bind(null,t),fetchPriceHistory:Pb.bind(null,t),estimateMarketPrice:Jc.bind(null,t),listOpenInterest:xc.bind(null,t),listMarketHolders:vc.bind(null,t),listTrades:Ta.bind(null,t)}}function Fe(t){return {listEvents:$b.bind(null,t),fetchEvent:bc.bind(null,t),fetchEventTags:dc.bind(null,t),listMarkets:nc$1.bind(null,t),listComboMarkets:pc.bind(null,t),fetchMarket:rc$1.bind(null,t),fetchMarketTags:tc$1.bind(null,t),listSeries:Re.bind(null,t),fetchSeries:Te.bind(null,t),listTags:_e$1.bind(null,t),fetchTag:af.bind(null,t),fetchRelatedTags:cf.bind(null,t),fetchRelatedTagResources:ef.bind(null,t),search:Pe.bind(null,t),listSports:Ve.bind(null,t),fetchSportsMarketTypes:Xe$1.bind(null,t),listTeams:gf.bind(null,t),fetchPublicProfile:ze.bind(null,t),listComments:Vb.bind(null,t),fetchCommentsById:Xb.bind(null,t),listCommentsByUserAddress:Zb.bind(null,t)}}function Le(t){let e={fetchPerpsBook:r=>od(t,r),fetchPerpsFees:()=>wd(t),fetchPerpsInstruments:r=>id(t,r),fetchPerpsTicker:r=>kd(t,r),fetchPerpsTickers:r=>md(t,r),listPerpsCandles:r=>qd(t,r),listPerpsFundingHistory:r=>sd(t,r),listPerpsTrades:r=>ud(t,r)};return t.isSecureClient()?{...e,depositToPerps:r=>Fd(t,r),openPerpsSession:r=>Cd(t,r),revokePerpsCredentials:r=>Dd(t,r),withdrawFromPerps:r=>Gd(t,r)}:e}function uo(t){return {listCurrentRewards:Rb.bind(null,t),listMarketRewards:Tb.bind(null,t)}}function De(t){let e=uo(t);return t.isPublicClient()?e:{...e,fetchOrderScoring:Ha.bind(null,t),fetchOrdersScoring:Ja$1.bind(null,t),listUserEarningsForDay:La$1.bind(null,t),fetchTotalEarningsForUserForDay:Na.bind(null,t),listUserEarningsAndMarketsConfig:Pa.bind(null,t),fetchRewardPercentages:Ra.bind(null,t)}}function ss(t){return {openRfqSession(){return He$1(t)}}}function Be(t){return t.isSecureClient()?{subscribe(e){return Ye(t,e)}}:{subscribe(e){return Ye(t,e)}}}function ns(t){return {createMarketOrder:$c.bind(null,t),placeMarketOrder:bd.bind(null,t),createLimitOrder:dd.bind(null,t),placeLimitOrder:fd.bind(null,t),postOrder:Nc(t),postOrders:Oc(t),cancelOrder:Bc.bind(null,t),cancelOrders:Dc.bind(null,t),cancelAll:Fc.bind(null,t),cancelMarketOrders:Hc.bind(null,t),listOpenOrders:ta$1.bind(null,t),fetchOrder:va$1.bind(null,t)}}function is(t){return {isGaslessReady:()=>Promise.resolve(true),setupTradingApprovals:hb.bind(null,t),approveErc20:$a.bind(null,t),approveErc1155ForAll:db.bind(null,t),transferErc20:kf.bind(null,t),splitPosition:je$1.bind(null,t),mergePositions:se$1.bind(null,t),redeemPositions:xe$1.bind(null,t)}}function os(t){return t.isSecureClient()?{...Oe(t),...Ie(t),...Me(t),...Fe(t),...Le(t),...De(t),...ss(t),...Be(t),...ns(t),...is(t)}:{...Oe(t),...Ie(t),...Me(t),...Fe(t),...Le(t),...De(t),...Be(t)}}var We={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 po(t,e=We){return {...e,...t,walletDerivation:{...e.walletDerivation,...t.walletDerivation},contracts:{...e.contracts,...t.contracts},clob:{...Z(e.clob,t.clob),market:X(e.clob.market,t.clob?.market),user:X(e.clob.user,t.clob?.user)},relayer:Z(e.relayer,t.relayer),gamma:Z(e.gamma,t.gamma),data:Z(e.data,t.data),rfq:as(e.rfq,t.rfq),perps:as(e.perps,t.perps),rtds:X(e.rtds,t.rtds),sports:X(e.sports,t.sports)}}function Z(t,e){return {...t,...e,headers:He(t.headers,e?.headers)}}function X(t,e){return {...t,...e,headers:He(t.headers,e?.headers)}}function as(t,e){return {...t,...e,headers:He(t.headers,e?.headers)}}function He(t,e){if(!(t===void 0&&e===void 0))return {...t,...e}}var tu=po({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 cs(t,e,r,s,n){let i=`${e}${r}${s}`;n!==void 0&&(i+=n);let o=await globalThis.crypto.subtle.importKey("raw",lo(t),{name:"HMAC",hash:"SHA-256"},false,["sign"]),h=await globalThis.crypto.subtle.sign("HMAC",o,new TextEncoder().encode(i));return ho(mo(h))}function lo(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 mo(t){let e=new Uint8Array(t),r="";for(let s of e)r+=String.fromCharCode(s);return btoa(r)}function ho(t){return t.replace(/\+/g,"-").replace(/\//g,"_")}var P=class{#e;#t;#s;constructor({root:e,headers:r,resolveHeaders:s}){this.#e=yo.create({prefixUrl:e,throwHttpErrors:false}),this.#t=r,this.#s=s;}get(e,r={}){return this.#n("GET",e,r)}post(e,r={}){return this.#n("POST",e,r)}patch(e,r={}){return this.#n("PATCH",e,r)}del(e,r={}){return this.#n("DELETE",e,r)}#a(e){return e.startsWith("/")?e.slice(1):e}#n(e,r,s){return this.#c(this.#r(e,r,s))}async#r(e,r,s){let n=this.#i(e,r,s),i=await this.#s?.(n),o=this.#u(this.#t,n.headers,i);return n.body!==void 0&&!o.has("content-type")&&o.set("content-type","application/json"),this.#e(this.#a(r),{body:n.body,headers:o,method:e,searchParams:n.params})}#i(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[n,i]of new Headers(s).entries())r.set(n,i);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.#d(r);throw new d(s,{status:r.status})}),r=>r instanceof e||r instanceof d?r:c.fromError(r))}async#d(e){let r=e.headers.get("content-type")?.toLowerCase();if(r?.includes("application/json")){let{error:n}=await e.clone().json().catch(()=>({}));if(n)return `${String(n)} (${e.url})`}if(r?.includes("text/plain")){let n=await e.clone().text().then(i=>i.trim(),()=>"");if(n)return `${n} (${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 A(t,e){let r;return {close:()=>(r===void 0&&(r=Promise.resolve(t.return()).then(()=>e())),r),[Symbol.asyncIterator](){return t[Symbol.asyncIterator]()}}}var Po=1e4,So=3e4,bo=5e3,go=10*6e4,Ro=3e4,vo=25e3,qo=65e3,L=class{#e=0;#t;start(e){this.stop(),this.#e=Date.now(),this.#t=setNonBlockingInterval(()=>{e("PING");},Po);}handleMessage(e){return e!=="PONG"?false:(this.#e=Date.now(),true)}isStale(e){return e-this.#e>So}stop(){this.#t!==void 0&&(clearInterval(this.#t),this.#t=void 0);}},ee=class{#e=0;#t;start(e){this.stop(),this.#e=Date.now(),this.#t=setNonBlockingInterval(()=>{e("PING");},bo);}handleMessage(){return this.#e=Date.now(),false}isStale(e){return e-this.#e>go}stop(){this.#t!==void 0&&(clearInterval(this.#t),this.#t=void 0);}},te=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>Ro}},D=class{#e=0;#t;start(e){this.stop(),this.#e=Date.now(),this.#t=setNonBlockingInterval(()=>{e(JSON.stringify({id:0,req:"post",op:{type:"ping"}}));},vo);}handleMessage(){return this.#e=Date.now(),false}isStale(e){return e-this.#e>qo}stop(){this.#t!==void 0&&(clearInterval(this.#t),this.#t=void 0);}};var Eo=5e3,ko=250,To=3e4,g=class{#e;#t=0;schedule(e){if(this.#e!==void 0||!e.shouldReconnect())return;let r=xo(this.#t,{baseMs:ko,maxMs:To});this.#t+=1,this.#e=setNonBlockingTimeout(()=>{this.#e=void 0,this.#s(e);},r);}stop(){this.#e!==void 0&&(clearTimeout(this.#e),this.#e=void 0);}resetBackoff(){this.#t=0,this.stop();}async#s(e){if(e.shouldReconnect())try{await e.reconnect();}catch{this.schedule(e);}}},S=class{#e;#t;#s;#a;constructor(e={}){this.#e=e.heartbeat;}connect(e){if(this.#t?.readyState===WebSocket.OPEN)return Promise.resolve({reusedOpenSocket:true});if(this.#o(),this.#s!==void 0)return this.#s;let s=this.#r(e).then(()=>({reusedOpenSocket:false})).catch(n=>{throw this.#s===s&&(this.#s=void 0),n});return this.#s=s,s}send(e){return this.#n(JSON.stringify(e))}#n(e){return this.#t?.readyState!==WebSocket.OPEN?false:(this.#t.send(e),true)}async close(){let e=await this.#d();this.#c(),!(e===void 0||e.readyState===WebSocket.CLOSED)&&await new Promise(r=>{e.addEventListener("close",()=>r(),{once:true}),e.readyState!==WebSocket.CLOSING&&e.close();});}async#r(e){let r=await e.prepare?.();return new Promise((s,n)=>{let i=wo(e.url,e.headers),o=()=>{i.removeEventListener("error",h),this.#i(i),this.#u(),e.onOpen(r),s(i);},h=l=>{i.removeEventListener("open",o),n(new c(`WebSocket connection failed: ${e.url}`,{cause:l}));};i.addEventListener("open",o,{once:true}),i.addEventListener("error",h,{once:true}),i.addEventListener("message",l=>{if(this.#t!==i)return;let y=String(l.data);if(this.#e?.handleMessage(y))return;let u;try{u=JSON.parse(y);}catch{return}e.onMessage(u);}),i.addEventListener("close",()=>{this.#t===i&&(this.#o(),e.onClose());}),i.addEventListener("error",()=>e.onError());})}#i(e){this.#t=e,this.#s=void 0;}#o(){this.#c(),this.#t=void 0;}#u(){this.#c();let e=this.#e;e!==void 0&&(e.start(r=>this.#n(r)),this.#a=setNonBlockingInterval(()=>{if(!e.isStale(Date.now()))return;let r=this.#t;r?.readyState===WebSocket.OPEN&&r.close();},Eo));}#c(){this.#a!==void 0&&(clearInterval(this.#a),this.#a=void 0),this.#e?.stop();}async#d(){let e=this.#t,r=this.#s;return this.#t=void 0,this.#s=void 0,e!==void 0?e:r?.then(()=>this.#t,()=>{})}};function wo(t,e){if(e===void 0)return new WebSocket(t);try{let r=Reflect.construct(WebSocket,[t,{headers:e}]);if(r instanceof WebSocket)return r}catch(r){throw new c("WebSocket headers require a header-capable WebSocket implementation.",{cause:r})}throw new c("WebSocket headers require a header-capable WebSocket implementation.")}function xo(t,e){let r=Math.min(e.baseMs*2**t,e.maxMs);return Math.random()*r}var R=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 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.#t(this.#e)}};function _e(t,e,r){let s=re(r.assetsIds,e.assetsIds),n=re(e.assetsIds,r.assetsIds);s.length>0&&t(ds(s,r.customFeatureEnabled));let i=r.assetsIds[0];s.length===0&&e.customFeatureEnabled!==r.customFeatureEnabled&&i!==void 0&&t(ds([i],r.customFeatureEnabled)),n.length>0&&t(Io(n));}function Qe(t,e,r){if(r.includeAllMarkets){!e.includeAllMarkets&&e.markets.length>0&&t(ps(e.markets));return}if(e.includeAllMarkets){r.markets.length>0&&t(us(r.markets));return}let s=re(r.markets,e.markets),n=re(e.markets,r.markets);s.length>0&&t(us(s)),n.length>0&&t(ps(n));}function ls(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 ms(t){let e=false,r=new Set;for(let{subscription:s}of t){if(Ss(s)){e=true;continue}for(let n of s.markets??[])r.add(n);}return {includeAllMarkets:e,markets:e?[]:Array.from(r)}}function hs(t){return {assets_ids:t.assetsIds,custom_feature_enabled:t.customFeatureEnabled,type:"market"}}function ds(t,e){return {assets_ids:t,custom_feature_enabled:e,operation:"subscribe"}}function Io(t){return {assets_ids:t,operation:"unsubscribe"}}function fs(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 us(t){return {markets:t,operation:"subscribe"}}function ps(t){return {markets:t,operation:"unsubscribe"}}function ys(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 Ps(t){if(Ss(t))return ()=>true;let e=new Set((t.markets??[]).map(r=>r.toLowerCase()));return r=>e.has(r.payload.market.toLowerCase())}function Ss(t){return (t.markets?.length??0)===0}function re(t,e){let r=new Set(e);return t.filter(s=>!r.has(s))}var O=class{#e;#t;#s;#a=new S({heartbeat:new L});#n=new g;#r=new R({deriveServerState:ls});constructor(e){this.#e=e.headers,this.#t=e.url;}async subscribe(e){let{change:r,entry:s}=this.#r.add(e,{matches:ys(e)});return await this.#i(s,r),A(s.subscriber.queue,()=>this.#o(s))}async#i(e,r){let{before:s,after:n}=r;try{(await this.#c()).reusedOpenSocket&&_e(o=>this.#a.send(o),s,n);}catch(i){throw await this.#o(e),i}}async#o(e){let{before:r,after:s}=this.#r.remove(e);if(!this.#r.hasActiveSubscriptions()){await this.close();return}_e(n=>this.#a.send(n),r,s);}async close(){this.#s===void 0&&(this.#s=this.#u().finally(()=>{this.#s=void 0;})),await this.#s;}async#u(){this.#n.stop(),this.#r.endAll(),await this.#a.close();}#c(){return this.#a.connect({onClose:()=>this.#l(),onError:()=>this.#h(),onMessage:e=>this.#p(e),onOpen:()=>this.#d(),headers:this.#e,url:this.#t})}#d(){this.#n.resetBackoff(),this.#y();}#p(e){let r=Array.isArray(e)?e:[e];for(let s of r){let n=MarketEventSchema.safeParse(s);n.success&&this.#r.dispatch(n.data);}}#l(){this.#r.hasActiveSubscriptions()&&this.#m();}#h(){}#y(){this.#a.send(hs(this.#r.serverState()));}#m(){this.#n.schedule({reconnect:()=>this.#c(),shouldReconnect:()=>this.#r.hasActiveSubscriptions()});}};var B=class{#e;#t;#s;#a;#n=new S({heartbeat:new L});#r=new g;#i=new R({deriveServerState:ms});constructor(e){this.#e=e.credentials,this.#t=e.headers,this.#s=e.url;}async subscribe(e){let{change:r,entry:s}=this.#i.add(e,{matches:Ps(e)});return await this.#o(s,r),A(s.subscriber.queue,()=>this.#u(s))}async#o(e,r){let{before:s,after:n}=r;try{(await this.#d()).reusedOpenSocket&&Qe(o=>this.#n.send(o),s,n);}catch(i){throw await this.#u(e),i}}async#u(e){let{before:r,after:s}=this.#i.remove(e);if(!this.#i.hasActiveSubscriptions()){await this.close();return}Qe(n=>this.#n.send(n),r,s);}async close(){this.#a===void 0&&(this.#a=this.#c().finally(()=>{this.#a=void 0;})),await this.#a;}async#c(){this.#r.stop(),this.#i.endAll(),await this.#n.close();}#d(){return this.#n.connect({onClose:()=>this.#h(),onError:()=>this.#y(),onMessage:e=>this.#l(e),onOpen:e=>this.#p(e),prepare:()=>this.#e,headers:this.#t,url:this.#s})}#p(e){this.#r.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.#i.dispatch(n.data);}}#h(){this.#i.hasActiveSubscriptions()&&this.#P();}#y(){}#m(e){this.#n.send(fs(this.#i.serverState(),e));}#P(){this.#r.schedule({reconnect:()=>this.#d(),shouldReconnect:()=>this.#i.hasActiveSubscriptions()});}};var N=1440*60*1e3,vs=90*N,C=z.number().int().nonnegative(),se=z.object({start:C.optional(),end:C.optional()}),qs=z.object({interval:PerpsPnlIntervalSchema,start:C,end:C.optional()}),Go=z.enum(["perpsFills","perpsFundingPayments","perpsDeposits","perpsWithdrawals"]),Yo=z.enum(["perpsEquityHistory","perpsPnlHistory"]),ne=z.object({kind:Go,startTimestamp:C,endTimestamp:C,instrumentId:PerpsInstrumentIdSchema.optional(),depositStatus:PerpsDepositStatusSchema.optional(),withdrawalStatus:PerpsWithdrawalStatusSchema.optional(),hash:TxHashSchema.optional(),seenKeys:z.array(z.string())}),As=z.object({kind:Yo,startTimestamp:C,endTimestamp:C,interval:PerpsPnlIntervalSchema});async function Cs(t){return await unwrap(t.get("/v1/account/balances").andThen(G(FetchPerpsBalancesResponseSchema)))}async function Es(t){return await unwrap(t.get("/v1/account/portfolio").andThen(G(FetchPerpsPortfolioResponseSchema)))}var Jo=z.object({instrumentId:PerpsInstrumentIdSchema.optional()}).default({});async function ks(t,e){let r=X$1(e,Jo);return await unwrap(t.get("/v1/account/config",{params:T(r)}).andThen(G(FetchPerpsAccountConfigResponseSchema)))}var Zo=z.object({instrumentId:PerpsInstrumentIdSchema.optional()}).default({});async function Ts(t,e){let r=X$1(e,Zo);return await unwrap(t.get("/v1/account/open-orders",{params:T(r)}).andThen(G(FetchPerpsOpenOrdersResponseSchema)))}var Xo=z.object({orderId:PerpsOrderIdSchema.optional(),clientOrderId:PerpsClientOrderIdSchema.optional(),instrumentId:PerpsInstrumentIdSchema.optional(),start:C.optional(),end:C.optional()}).default({}).transform(({end:t,start:e,...r})=>({...r,endTimestamp:t,startTimestamp:e}));async function ws(t,e){let r=X$1(e,Xo);return await unwrap(t.get("/v1/account/orders",{params:T(r)}).andThen(G(FetchPerpsOrdersResponseSchema)))}var ea=z.union([se.extend({cursor:PaginationCursorSchema.optional()}).transform(({cursor:t,...e})=>({cursor:t,params:ie(e,N)})),z.object({cursor:PaginationCursorSchema}).transform(({cursor:t})=>({cursor:t,params:void 0}))]);function xs(t,e={}){let{cursor:r,params:s}=X$1(e,ea);return pa$1(n=>{let i;n===void 0?(invariant(s!==void 0,"Expected initial Perps fills params."),i={kind:"perpsFills",seenKeys:[],...s}):i=W(n,ne);let{kind:o,seenKeys:h,...l}=i,y=new Set(i.seenKeys);return t.get("/v1/account/fills",{params:T(l)}).andThen(G(ListPerpsFillsResponseSchema)).map(u=>{let q=u.data.filter(d=>!y.has(String(d.tradeId)));return oe({getKey:d=>String(d.tradeId),getTimestamp:d=>d.timestamp,items:q,responseData:u.data,responseMore:u.more,state:i})})},r)}var ta=z.union([se.extend({cursor:PaginationCursorSchema.optional(),instrumentId:PerpsInstrumentIdSchema.optional()}).transform(({cursor:t,...e})=>({cursor:t,params:ie(e,N)})),z.object({cursor:PaginationCursorSchema}).transform(({cursor:t})=>({cursor:t,params:void 0}))]);function Os(t,e={}){let{cursor:r,params:s}=X$1(e,ta);return pa$1(n=>{let i;n===void 0?(invariant(s!==void 0,"Expected initial Perps funding payment params."),i={kind:"perpsFundingPayments",seenKeys:[],...s}):i=W(n,ne);let{kind:o,seenKeys:h,...l}=i,y=new Set(i.seenKeys);return t.get("/v1/account/funding",{params:T(l)}).andThen(G(ListPerpsFundingPaymentsResponseSchema)).map(u=>{let q=u.data.filter(d=>!y.has(`${d.instrumentId}:${d.timestamp}:${d.funding}`));return oe({getKey:d=>`${d.instrumentId}:${d.timestamp}:${d.funding}`,getTimestamp:d=>d.timestamp,items:q,responseData:u.data,responseMore:u.more,state:i})})},r)}var ra=z.union([se.extend({cursor:PaginationCursorSchema.optional(),depositStatus:PerpsDepositStatusSchema.optional(),hash:TxHashSchema.optional()}).transform(({cursor:t,...e})=>({cursor:t,params:ie(e,vs)})),z.object({cursor:PaginationCursorSchema}).transform(({cursor:t})=>({cursor:t,params:void 0}))]);function Is(t,e={}){let{cursor:r,params:s}=X$1(e,ra);return pa$1(n=>{let i;n===void 0?(invariant(s!==void 0,"Expected initial Perps deposit params."),i={kind:"perpsDeposits",seenKeys:[],...s}):i=W(n,ne);let{kind:o,seenKeys:h,...l}=i,y=new Set(i.seenKeys);return t.get("/v1/account/deposits",{params:T(l)}).andThen(G(ListPerpsDepositsResponseSchema)).map(u=>{let q=u.data.filter(d=>!y.has(d.hash));return oe({getKey:d=>d.hash,getTimestamp:oa,items:q,responseData:u.data,responseMore:u.more,state:i})})},r)}var sa=z.union([se.extend({cursor:PaginationCursorSchema.optional(),withdrawalStatus:PerpsWithdrawalStatusSchema.optional(),hash:TxHashSchema.optional()}).transform(({cursor:t,...e})=>({cursor:t,params:ie(e,vs)})),z.object({cursor:PaginationCursorSchema}).transform(({cursor:t})=>({cursor:t,params:void 0}))]);function Ms(t,e={}){let{cursor:r,params:s}=X$1(e,sa);return pa$1(n=>{let i;n===void 0?(invariant(s!==void 0,"Expected initial Perps withdrawal params."),i={kind:"perpsWithdrawals",seenKeys:[],...s}):i=W(n,ne);let{kind:o,seenKeys:h,...l}=i,y=new Set(i.seenKeys);return t.get("/v1/account/withdrawals",{params:T(l)}).andThen(G(ListPerpsWithdrawalsResponseSchema)).map(u=>{let q=u.data.filter(d=>!y.has(String(d.withdrawalId)));return oe({getKey:d=>String(d.withdrawalId),getTimestamp:aa,items:q,responseData:u.data,responseMore:u.more,state:i})})},r)}var na=z.union([qs.extend({cursor:PaginationCursorSchema.optional()}).transform(({cursor:t,...e})=>({cursor:t,params:Ds(e)})),z.object({cursor:PaginationCursorSchema}).transform(({cursor:t})=>({cursor:t,params:void 0}))]);function Fs(t,e){let{cursor:r,params:s}=X$1(e,na);return pa$1(n=>{let i;n===void 0?(invariant(s!==void 0,"Expected initial Perps equity history params."),i={kind:"perpsEquityHistory",...s}):i=W(n,As);let{kind:o,...h}=i;return t.get("/v1/account/equity",{params:T(h)}).andThen(G(ListPerpsEquityHistoryResponseSchema)).map(l=>{let y=l.data.at(-1),u=l.more&&y!==void 0&&y.timestamp<i.endTimestamp;return {items:l.data,hasMore:u,nextCursor:u?je({...i,startTimestamp:y.timestamp+Bs(i.interval)}):void 0}})},r)}var ia=z.union([qs.extend({cursor:PaginationCursorSchema.optional()}).transform(({cursor:t,...e})=>({cursor:t,params:Ds(e)})),z.object({cursor:PaginationCursorSchema}).transform(({cursor:t})=>({cursor:t,params:void 0}))]);function Ls(t,e){let{cursor:r,params:s}=X$1(e,ia);return pa$1(n=>{let i;n===void 0?(invariant(s!==void 0,"Expected initial Perps PnL history params."),i={kind:"perpsPnlHistory",...s}):i=W(n,As);let{kind:o,...h}=i;return t.get("/v1/account/pnl",{params:T(h)}).andThen(G(ListPerpsPnlHistoryResponseSchema)).map(l=>{let y=l.data.at(-1),u=l.more&&y!==void 0&&y.timestamp<i.endTimestamp;return {items:l.data,hasMore:u,nextCursor:u?je({...i,startTimestamp:y.timestamp+Bs(i.interval)}):void 0}})},r)}function ie(t,e){let r=Date.now(),{end:s,start:n,...i}=t;return {...i,endTimestamp:s??r,startTimestamp:n??r-e}}function Ds(t){return {endTimestamp:t.end??Date.now(),interval:t.interval,startTimestamp:t.start}}function W(t,e){try{return e.parse(JSON.parse(atob(t)))}catch(r){throw new c("Invalid Perps account pagination cursor",{cause:r})}}function je(t){return toPaginationCursor(btoa(JSON.stringify(t)))}function T(t){return ca(t,da())}function oa(t){return t.confirmedTimestamp??t.createdTimestamp}function aa(t){return t.confirmedTimestamp??t.createdTimestamp}function oe(t){let e=t.responseData.at(-1),r=t.items.at(-1),s=(r===void 0?void 0:t.getTimestamp(r))??(e===void 0?void 0:t.getTimestamp(e)),n=t.responseMore&&s!==void 0&&s>t.state.startTimestamp;if(!n)return {items:t.items,hasMore:n};let i=r===void 0?s-1:s,o=new Set(t.state.endTimestamp===i?t.state.seenKeys:[]);for(let h of t.items)t.getTimestamp(h)===i&&o.add(t.getKey(h));return {items:t.items,hasMore:n,nextCursor:je({...t.state,endTimestamp:i,seenKeys:Array.from(o)})}}function Bs(t){switch(t){case "1h":return 3600*1e3;case "4h":return 14400*1e3;case "1d":return N;case "1w":return 7*N}invariant(false,`Unsupported Perps account history interval: ${String(t)}`);}var Je=z.object({instrumentId:PerpsInstrumentIdSchema,buy:z.boolean(),price:PerpsDecimalInputSchema.optional(),quantity:PerpsDecimalInputSchema,timeInForce:PerpsTimeInForceSchema,postOnly:z.boolean().optional(),clientOrderId:PerpsClientOrderIdSchema.optional()});async function Us(t,e){let[r]=await Ze(t,{orders:[e]});return expectPresent(r,"Expected Perps place order acknowledgement.")}var ua=z.object({orders:z.array(Je).min(1),expiresAt:z.number().int().positive().optional()});async function Ze(t,e){let r=X$1(e,ua);return await t.sendSignedWsCommand({op:["createOrders",r.orders.map(zs)],responseSchema:z.array(RawPerpsOrderCommandAckSchema),timeoutMessage:"Perps place order acknowledgement timed out.",expiresAt:r.expiresAt})}var pa=z.object({orderId:PerpsOrderIdSchema,order:Je,expiresAt:z.number().int().positive().optional()});async function _s(t,e){let r=X$1(e,pa),[s]=await Xe(t,{orders:[{orderId:r.orderId,order:r.order}],expiresAt:r.expiresAt});return expectPresent(s,"Expected Perps modify order acknowledgement.")}var la=z.object({orders:z.array(z.object({orderId:PerpsOrderIdSchema,order:Je})).min(1),expiresAt:z.number().int().positive().optional()});async function Xe(t,e){let r=X$1(e,la);return await t.sendSignedWsCommand({op:["modifyOrders",r.orders.map(s=>[s.orderId,zs(s.order)])],responseSchema:z.array(RawPerpsOrderCommandAckSchema),timeoutMessage:"Perps modify order acknowledgement timed out.",expiresAt:r.expiresAt})}var ma=z.union([z.object({orderId:PerpsOrderIdSchema,clientOrderId:z.undefined().optional(),expiresAt:z.number().int().positive().optional()}),z.object({clientOrderId:PerpsClientOrderIdSchema,orderId:z.undefined().optional(),expiresAt:z.number().int().positive().optional()})]);async function Qs(t,e){let r=X$1(e,ma),[s]=r.orderId!==void 0?await ae(t,{orderIds:[r.orderId],expiresAt:r.expiresAt}):await ae(t,{clientOrderIds:[r.clientOrderId],expiresAt:r.expiresAt});return expectPresent(s,"Expected Perps cancel order acknowledgement.")}var ha=z.union([z.object({orderIds:z.array(PerpsOrderIdSchema).min(1),clientOrderIds:z.undefined().optional(),expiresAt:z.number().int().positive().optional()}),z.object({clientOrderIds:z.array(PerpsClientOrderIdSchema).min(1),orderIds:z.undefined().optional(),expiresAt:z.number().int().positive().optional()})]);async function ae(t,e){let r=X$1(e,ha);return r.orderIds!==void 0?await t.sendSignedWsCommand({op:["cancelOrders",r.orderIds],responseSchema:z.array(PerpsCommandAckSchema),timeoutMessage:"Perps cancel order acknowledgement timed out.",expiresAt:r.expiresAt}):await t.sendSignedWsCommand({op:["cancelOrdersCOID",r.clientOrderIds],responseSchema:z.array(PerpsCommandAckSchema),timeoutMessage:"Perps cancel order acknowledgement timed out.",expiresAt:r.expiresAt})}var fa=z.object({instrumentId:PerpsInstrumentIdSchema,leverage:z.number().int().positive(),crossMargin:z.boolean()});async function Ks(t,e){let r=X$1(e,fa);return await t.sendSignedWsCommand({op:["updateLeverage",[r.instrumentId,r.leverage,r.crossMargin]],responseSchema:PerpsCommandAckSchema,timeoutMessage:"Perps update leverage acknowledgement timed out."})}var ya=z.object({instrumentId:PerpsInstrumentIdSchema,amount:PerpsDecimalInputSchema});async function js(t,e){let r=X$1(e,ya),s=toDecimalString(r.amount);return await t.sendSignedHttpCommand("/v1/trade/margin",{op:["updateMargin",[r.instrumentId,s]],bodyOp:{args:{amt:s,iid:r.instrumentId},type:"updateMargin"}})}function zs(t){return [t.instrumentId,t.buy,t.price===void 0?void 0:toDecimalString(t.price),toDecimalString(t.quantity),t.timeInForce,t.postOnly??false,t.clientOrderId]}function Ns(t){let[e,r]=t;switch(e){case "createOrders":return {args:r.map(Ws),type:e};case "modifyOrders":return {args:r.map(([s,n])=>({oid:s,order:Ws(n)})),type:e};case "cancelOrders":case "cancelOrdersCOID":return {args:r,type:e};case "updateLeverage":{let[s,n,i]=r;return {args:{cross:i,iid:s,lev:n},type:e}}default:invariant(false,`Unsupported Perps command: ${String(e)}`);}}function Ws(t){let e={buy:t[1],iid:t[0],po:t[5],qty:t[3],tif:t[4]};return t[2]!==void 0&&(e.p=t[2]),t[6]!==void 0&&(e.c=t[6]),e}var va=3e4,$s=3e4,qa=["balances","portfolio","orders","fills","funding","deposits","withdrawals"],Aa=z.object({id:z.number().int().positive().optional(),data:z.unknown()}),Vs=z.union([PerpsCommandAckSchema,z.array(PerpsCommandAckSchema)]).transform(t=>Array.isArray(t)?t.find(e=>e.status==="err")??t[0]:t),de=class{credentials;#e;#t;#s;#a;#n;#r=new S({heartbeat:new D});#i=pushable({objectMode:true});#o=new Map;#u=new g;#c=new Map;#d=new Map;#p=1;#l;constructor(e){this.#e=new P({headers:e.headers,resolveHeaders:async()=>this.#P(),root:e.restUrl}),this.#t=e.chainId,this.credentials=e.credentials,this.#s=e.headers,this.#a=e.onClose,this.#n=e.wsUrl;}get closed(){return this.#l!==void 0}async connect(){await this.#h(false);}async close(){this.#l===void 0&&(this.#l=this.#v()),await this.#l;}[Symbol.asyncIterator](){return this.#i[Symbol.asyncIterator]()}async fetchBalances(){return await Cs(this.#e)}async fetchPortfolio(){return await Es(this.#e)}async fetchAccountConfig(e){return await ks(this.#e,e)}async fetchOpenOrders(e){return await Ts(this.#e,e)}async fetchOrders(e){return await ws(this.#e,e)}listFills(e={}){return xs(this.#e,e)}listFundingPayments(e={}){return Os(this.#e,e)}listDeposits(e={}){return Is(this.#e,e)}listWithdrawals(e={}){return Ms(this.#e,e)}listEquityHistory(e){return Fs(this.#e,e)}listPnlHistory(e){return Ls(this.#e,e)}async placeOrder(e){return await Us(this.#f(),e)}async placeOrders(e){return await Ze(this.#f(),e)}async modifyOrder(e){return await _s(this.#f(),e)}async modifyOrders(e){return await Xe(this.#f(),e)}async cancelOrder(e){return await Qs(this.#f(),e)}async cancelOrders(e){return await ae(this.#f(),e)}async updateLeverage(e){return await Ks(this.#f(),e)}async updateMargin(e){return await js(this.#f(),e)}async#h(e){await this.#r.connect({onClose:()=>this.#E(),onError:()=>{},onMessage:r=>this.#A(r),onOpen:()=>{},headers:this.#s,url:this.#n}),await this.#y(),await this.#m(),this.#u.resetBackoff(),e&&(this.#c.clear(),this.#d.clear(),this.#i.push({reason:"reconnect",type:"resync"}));}async#y(){await this.#b({id:this.#p++,op:{args:{proxy:this.credentials.proxy,secret:this.credentials.secret},type:"auth"},req:"post"},Vs,va,"Perps session authentication timed out.");}async#m(){await this.#b({id:this.#p++,req:"sub",chs:qa},Vs,$s,"Perps session subscription timed out.");}#P(){return {"POLYMARKET-PROXY":this.credentials.proxy,"POLYMARKET-SECRET":this.credentials.secret}}#f(){return {sendSignedWsCommand:e=>this.#S(e),sendSignedHttpCommand:(e,r)=>this.#R(e,r)}}async#S(e){let r=this.#g(e.op,e.expiresAt);return await this.#b({...r,id:this.#p++,op:Ns(e.op),req:"post"},e.responseSchema,$s,e.timeoutMessage)}async#R(e,r){let s=this.#g(r.op);return await unwrap(this.#e.patch(e,{json:{...s,op:r.bodyOp}}).andThen(G(PerpsCommandAckSchema)))}#g(e,r){let s=ka(),n=Date.now(),i;try{i=gd({chainId:this.#t,op:e,privateKey:this.credentials.privateKey,salt:s,timestamp:n});}catch(h){throw j.fromError(h,"Could not sign the Perps session command")}let o={salt:s,sig:i,ts:n};return r!==void 0&&(o.exp=r),o}async#b(e,r,s,n){let i=Ca(r);this.#o.set(e.id,i);let o=setNonBlockingTimeout(()=>{i.reject(new c(n));},s);try{if(!this.#r.send(e))throw new c("Perps session transport is not open.");return await i.promise}finally{clearTimeout(o),this.#o.delete(e.id);}}async#v(){this.#u.stop(),this.#q(new c("Perps session closed.")),this.#i.end(),await this.#r.close(),this.#a(this);}#A(e){if(this.#C(e))return;let r=PerpsSessionUpdateEventSchema.safeParse(e);if(!r.success)return;let s=r.data,n=this.#k(s);this.#T(s),!n&&this.#i.push(s);}#C(e){let r=Aa.safeParse(e);if(!r.success||r.data.id===void 0)return false;let s=this.#o.get(r.data.id);if(s===void 0)return true;let n=s.schema.safeParse(r.data.data);return n.success?(Ea(n.data)?s.reject(new c(n.data.error??"Perps session request rejected.")):s.resolve(n.data),true):(s.reject(new c("Perps session empty response.")),true)}#E(){this.#q(new c("Perps session connection closed.")),this.#l===void 0&&this.#u.schedule({reconnect:()=>this.#h(true),shouldReconnect:()=>this.#l===void 0});}#q(e){for(let r of this.#o.values())r.reject(e);this.#o.clear();}#k(e){if(e.channel!=="balances"&&e.channel!=="portfolio")return false;let r=JSON.stringify(e.payload),s=this.#d.get(e.channel);return this.#d.set(e.channel,r),r===s}#T(e){let r=this.#c.get(e.channel);this.#c.set(e.channel,e.sequence),!(r===void 0||e.sequence===r+1)&&this.#i.push({channel:e.channel,previousSequence:r,reason:"sequence_gap",sequence:e.sequence,type:"resync"});}};function Ca(t){let e,r;return {promise:new Promise((n,i)=>{e=n,r=i;}),reject:r,resolve:e,schema:t}}function Ea(t){return !Array.isArray(t)&&typeof t=="object"&&t!==null&&"status"in t&&t.status==="err"}function ka(){let[t]=globalThis.crypto.getRandomValues(new Uint32Array(1));return invariant(t!==void 0,"Expected crypto.getRandomValues to return a salt."),t}var H=class{#e;#t;#s;#a;#n=new Set;#r=new Set;#i=new Set;#o=false;constructor(e){this.#e=e.chainId,this.#t=e.headers,this.#s=e.restUrl,this.#a=e.wsUrl;}connect(e){if(this.#o)return Promise.reject(new c("Perps session manager has been shut down."));let r=new de({chainId:this.#e,credentials:e,headers:this.#t,onClose:n=>this.#u(n),restUrl:this.#s,wsUrl:this.#a});this.#r.add(r);let s;return s=(async()=>{try{if(await r.connect(),this.#o)throw await r.close(),new c("Perps session manager has been shut down.");return this.#n.add(r),r}catch(n){throw await r.close(),n}finally{this.#i.delete(s),this.#r.delete(r);}})(),this.#i.add(s),s}async shutdown(){this.#o=true;let e=Array.from(this.#n),r=Array.from(this.#r),s=Array.from(this.#i);this.#n.clear(),this.#r.clear(),this.#i.clear(),await Promise.allSettled([...e.map(n=>n.close()),...r.map(n=>n.close()),...s.map(n=>n.catch(()=>{}))]).then(()=>{});}#u(e){this.#n.delete(e),this.#r.delete(e);}};var M=class{#e;#t;#s;#a=1;#n=new S({heartbeat:new D});#r=new g;#i=new R({deriveServerState:wa});constructor(e){this.#e=e.headers,this.#t=e.url;}async subscribe(e){let{change:r,entry:s}=this.#i.add(e,{matches:Oa(e)});return await this.#o(s,r),A(s.subscriber.queue,()=>this.#u(s))}async#o(e,r){try{(await this.#d()).reusedOpenSocket&&(this.#m(Gs(r.before,r.after)),this.#P(Ys(r.before,r.after)));}catch(s){throw await this.#u(e),s}}async#u(e){let{before:r,after:s}=this.#i.remove(e);this.#m(Gs(r,s)),this.#P(Ys(r,s)),this.#i.hasActiveSubscriptions()||await this.close();}async close(){this.#s===void 0&&(this.#s=this.#c().finally(()=>{this.#s=void 0;})),await this.#s;}async#c(){this.#r.stop(),this.#i.endAll(),await this.#n.close();}#d(){return this.#n.connect({onClose:()=>this.#h(),onError:()=>this.#y(),onMessage:e=>this.#l(e),onOpen:()=>this.#p(),headers:this.#e,url:this.#t})}#p(){this.#r.resetBackoff(),this.#m(Array.from(this.#i.serverState()));}#l(e){let r=PerpsMarketDataEventSchema.safeParse(e);r.success&&this.#i.dispatch(r.data);}#h(){this.#i.hasActiveSubscriptions()&&this.#S();}#y(){}#m(e){e.length!==0&&this.#n.send(this.#f("sub",e));}#P(e){e.length!==0&&this.#n.send(this.#f("unsub",e));}#f(e,r){return {id:this.#a++,req:e,chs:r}}#S(){this.#r.schedule({reconnect:()=>this.#d(),shouldReconnect:()=>this.#i.hasActiveSubscriptions()});}};function wa(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(xa(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 Gs(t,e){return Array.from(e).filter(r=>!t.has(r))}function Ys(t,e){return Array.from(t).filter(r=>!e.has(r))}function xa(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 Oa(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 Xs(t,e){return {...e,quote:r=>t.quote(e,r)}}function en(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 tn(t){return {quoteId:t.quoteId,rfqId:t.rfqId}}function rn(t){return {quoteId:t.quoteId,rfqId:t.rfqId}}function sn(t){return {quoteId:t.quoteId,rfqId:t.rfqId}}function nn(t,e){let r=_$1(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 on(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 an(t,e,r){let s=_$1(t);return {maker_address:s.maker,quote_id:r,rfq_id:e,signer_address:s.signer,type:"RFQ_QUOTE_CANCEL"}}function cn(t,e,r){return {decision:r,quote_id:e,rfq_id:t,type:"RFQ_CONFIRMATION_RESPONSE"}}var ue=class{#e=new Map;#t;constructor(e){this.#t=e;}waitFor(e,r){let s=Ma(),n,i=setNonBlockingTimeout(()=>{this.remove(e,n),s.reject(new f(r));},this.#t);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 Ma(){let t,e;return {promise:new Promise((s,n)=>{t=s,e=n;}),reject:e,resolve:t}}var un="0x0000000000000000000000000000000000000000000000000000000000000000";async function ln(t){let e=_$1(t.account),r={builder:un,maker:e.maker,makerAmount:toBaseUnits(Fa(t.orderSide,t.orderPrice,t.size)),metadata:un,salt:Ba().toString(),side:Da(t.orderSide),signatureType:e.signatureType,signer:e.signer,takerAmount:toBaseUnits(La(t.orderSide,t.orderPrice,t.size)),timestamp:Math.floor(Date.now()/1e3).toString(),tokenId:t.tokenId},s;try{s=await t.signer.signTypedData(Pc$1({domain:pn(t),order:r}));}catch(n){throw j.fromError(n,"Could not sign the RFQ quote order.")}return {...r,signature:Qc({domain:pn(t),order:r,signature:s})}}function pn(t){return {chainId:t.chainId,exchange:t.exchange,protocolVersion:"3"}}function Fa(t,e,r){return t===OrderSide.SELL?r.toString():((e*r+999999n)/1000000n).toString()}function La(t,e,r){return t===OrderSide.SELL?(e*r/1000000n).toString():r.toString()}function Da(t){return t===OrderSide.BUY?0:1}function Ba(){let t=new Uint8Array(8);return globalThis.crypto.getRandomValues(t),BigInt(`0x${Array.from(t,e=>e.toString(16).padStart(2,"0")).join("")}`)}var fn=DecimalishSchema.transform(t=>Sn(t)).refine(t=>t<=BigInt(Number.MAX_SAFE_INTEGER),{message:"Value exceeds the temporary numeric wire limit."}),Ua=z.strictObject({price:fn.refine(t=>t<1000000n,{message:"Price must be less than 1."}),size:fn.optional(),source:z.enum(["collateral","inventory"]).default("collateral")});function yn(t){return X$1(t,Ua)}async function Pn(t){let e=t.response.price,r=t.response.size===void 0?ja(t.request.requestedSize,e):t.response.size,s=await ln({account:t.account,chainId:t.chainId,exchange:t.exchange,orderPrice:Qa(t.request,t.response.source,e),orderSide:Ka(t.response.source),signer:t.signer,size:r,tokenId:_a(t.request,t.response.source)});return {price:e,signedOrder:s,size:r}}function _a(t,e){return t.direction===RfqDirection.Buy?e==="collateral"?t.noPositionId:t.yesPositionId:e==="collateral"?t.yesPositionId:t.noPositionId}function Qa(t,e,r){return t.direction===RfqDirection.Buy&&e==="collateral"||t.direction===RfqDirection.Sell&&e==="inventory"?1000000n-r:r}function Ka(t){return t==="collateral"?OrderSide.BUY:OrderSide.SELL}function ja(t,e){let r=Sn(t.value);return t.unit===RfqRequestedSizeUnit.Shares?r:r*1000000n/e}function Sn(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 Ga=3e4,Ya=3e4,U=class{#e;#t;#s;#a;#n;#r;#i;#o;#u;#c;#d=false;constructor(e){this.#e=e.account,this.#t=e.chainId,this.#s=e.credentials,this.#a=e.exchange,this.#n=e.headers,this.#r=e.signer,this.#i=e.url;}async connect(){if(this.#d)throw new c("RFQ quoter manager has been shut down.");if(this.#o!==void 0){if(!this.#o.closed)return this.#o;this.#o=void 0;}if(this.#c!==void 0)return this.#c;let e=new it({account:this.#e,chainId:this.#t,credentials:this.#s,exchange:this.#a,headers:this.#n,onClose:()=>this.#p(e),signer:this.#r,url:this.#i});this.#u=e;let r;return r=(async()=>{try{if(await e.connect(),this.#d)throw await e.close(),new c("RFQ quoter manager has been shut down.");return this.#o=e,e}catch(s){throw await e.close(),s}finally{this.#c===r&&(this.#c=void 0),this.#u===e&&(this.#u=void 0);}})(),this.#c=r,r}async shutdown(){this.#d=true;let e=this.#o,r=this.#u,s=this.#c;this.#o=void 0,this.#u=void 0,this.#c=void 0,await Promise.allSettled([e?.close(),r?.close(),s?.catch(()=>{})]).then(()=>{});}#p(e){this.#o===e&&(this.#o=void 0),this.#u===e&&(this.#u=void 0);}},it=class{#e;#t;#s;#a;#n;#r;#i;#o;#u=new S;#c=pushable({objectMode:true});#d=new ue(Ya);#p;#l;constructor(e){this.#e=e.account,this.#t=e.chainId,this.#s=e.credentials,this.#a=e.exchange,this.#n=e.headers,this.#r=e.onClose,this.#i=e.signer,this.#o=e.url;}get closed(){return this.#p!==void 0}async connect(){let e=Ja();this.#l=e;let r=setNonBlockingTimeout(()=>{e.reject(new c("RFQ quoter authentication timed out."));},Ga);try{await this.#u.connect({headers:this.#n,onClose:()=>this.#b(),onError:()=>{},onMessage:s=>this.#R(s),onOpen:()=>this.#S(),url:this.#o}),await e.promise;}finally{clearTimeout(r),this.#l=void 0;}}async#h(e){if(!this.#u.send(e))throw new c("RFQ quoter websocket is not open.")}async close(){this.#p===void 0&&(this.#p=this.#y()),await this.#p;}[Symbol.asyncIterator](){return this.#c[Symbol.asyncIterator]()}async#y(){let e=new c("RFQ quoter websocket closed.");await this.#P(e);}async#m(e){this.#p===void 0&&(this.#p=this.#P(e)),await this.#p;}async#P(e){this.#f(e),this.#c.end(),await this.#u.close(),this.#r();}#f(e){this.#l?.reject(e),this.#d.rejectAll(e);}#S(){this.#u.send(nn(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.#c.push(Xs(this,s));return;case "quote_ack":this.#d.resolve(pe(s.rfqId),tn(s));return;case "quote_cancel_ack":this.#d.resolve(st(s.rfqId,s.quoteId),rn(s));return;case "confirmation_request":this.#c.push(en(this,s));return;case "confirmation_ack":this.#d.resolve(nt(s.rfqId,s.quoteId),sn(s));return;case "execution_update":this.#c.push(s);return;case "trade":this.#c.push(s);return;case "rfq_error":this.#v(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}`));}#b(){this.#r(),this.close();}#v(e){if(e.requestType==="RFQ_QUOTE"){if(e.rfqId===void 0){this.#m(new c("Uncorrelated RFQ quoter error."));return}this.#d.reject(pe(e.rfqId),new Ae(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.#d.reject(st(e.rfqId,e.quoteId),new Ce(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.#d.reject(nt(e.rfqId,e.quoteId),new Ee(e.message,{code:e.code,errorId:e.errorId,quoteId:e.quoteId,rfqId:e.rfqId}));}}async quote(e,r){let s=yn(r),n=await Pn({account:this.#e,chainId:this.#t,exchange:this.#a,request:e,response:s,signer:this.#i}),i=this.#d.waitFor(pe(e.rfqId),`Timed out waiting for RFQ quote acknowledgement for ${e.rfqId}.`);try{return await this.#h(on(e,n)),await i}catch(o){throw this.#d.remove(pe(e.rfqId),i),o}}async cancelQuote(e){let r=st(e.rfqId,e.quoteId),s=this.#d.waitFor(r,`Timed out waiting for RFQ quote cancellation acknowledgement for ${e.rfqId}.`);try{return await this.#h(an(this.#e,e.rfqId,e.quoteId)),await s}catch(n){throw this.#d.remove(r,s),n}}async respondToConfirmation(e,r,s){let n=nt(e,r),i=this.#d.waitFor(n,`Timed out waiting for RFQ confirmation acknowledgement for ${e}.`);try{return await this.#h(cn(e,r,s)),await i}catch(o){throw this.#d.remove(n,i),o}}};function pe(t){return `ACK_RFQ_QUOTE:${t}`}function st(t,e){return `ACK_RFQ_QUOTE_CANCEL:${t}:${e}`}function nt(t,e){return `ACK_RFQ_CONFIRMATION_RESPONSE:${t}:${e}`}function Ja(){let t,e;return {promise:new Promise((s,n)=>{t=s,e=n;}),reject:e,resolve:t}}var _=class{#e;#t;#s;#a=new S({heartbeat:new ee});#n=new g;#r=new R({deriveServerState:tc});constructor(e){this.#e=e.headers,this.#t=e.url;}async subscribe(e){let{change:r,entry:s}=this.#r.add(e,{matches:ic(e)});return await this.#i(s,r),A(s.subscriber.queue,()=>this.#o(s))}async#i(e,r){try{if((await this.#c()).reusedOpenSocket){let{before:n,after:i}=r,o=Xa(n,i);this.#m(o);}}catch(s){throw await this.#o(e),s}}async#o(e){let{before:r,after:s}=this.#r.remove(e),n=ec(r,s);this.#P(n),this.#r.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.#n.stop(),this.#r.endAll(),await this.#a.close();}#c(){return this.#a.connect({onClose:()=>this.#l(),onError:()=>this.#h(),onMessage:e=>this.#p(e),onOpen:()=>this.#d(),headers:this.#e,url:this.#t})}#d(){this.#n.resetBackoff(),this.#y();}#p(e){let r=RealtimeEventSchema.safeParse(e);r.success&&this.#r.dispatch(r.data);}#l(){this.#r.hasActiveSubscriptions()&&this.#f();}#h(){}#y(){this.#m(Array.from(this.#r.serverState().values()));}#m(e){e.length!==0&&this.#a.send(rc(e));}#P(e){e.length!==0&&this.#a.send(sc(e));}#f(){this.#n.schedule({reconnect:()=>this.#c(),shouldReconnect:()=>this.#r.hasActiveSubscriptions()});}};function Xa(t,e){return Array.from(e).flatMap(([r,s])=>t.has(r)?[]:[s])}function ec(t,e){return Array.from(t).flatMap(([r,s])=>e.has(r)?[]:[s])}function tc(t){let e=new Map;for(let{subscription:r}of t)for(let s of nc(r))e.has(s.key)||e.set(s.key,s);return e}function rc(t){return {action:"subscribe",subscriptions:t.map(({topic:e,type:r})=>({topic:e,type:r}))}}function sc(t){return {action:"unsubscribe",subscriptions:t.map(({topic:e,type:r})=>({topic:e,type:r}))}}function nc(t){switch(t.topic){case "comments":return (t.types??["comment_created"]).map(e=>le("comments",e));case "prices.crypto.binance":return [le("crypto_prices","update")];case "prices.crypto.chainlink":return [le("crypto_prices_chainlink","update")];case "prices.equity.pyth":return [le("equity_prices","update")];default:invariant(false,`Unknown RTDS topic: ${String(t)}`);}}function le(t,e){return {key:`${t}:${e}`,topic:t,type:e}}function ic(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 Q=class{#e;#t;#s;#a=new S({heartbeat:new te});#n=new g;#r=new R;constructor(e){this.#e=e.headers,this.#t=e.url;}async subscribe(e){let{entry:r}=this.#r.add(e);return await this.#i(r),A(r.subscriber.queue,()=>this.#o(r))}async#i(e){try{await this.#c();}catch(r){throw await this.#o(e),r}}async#o(e){this.#r.remove(e),this.#r.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.#n.stop(),this.#r.endAll(),await this.#a.close();}#c(){return this.#a.connect({onClose:()=>this.#l(),onError:()=>this.#h(),onMessage:e=>this.#p(e),onOpen:()=>this.#d(),headers:this.#e,url:this.#t})}#d(){this.#n.resetBackoff();}#p(e){let r=SportsResultEventSchema.safeParse(e);r.success&&this.#r.dispatch(r.data);}#l(){this.#r.hasActiveSubscriptions()&&this.#y();}#h(){}#y(){this.#n.schedule({reconnect:()=>this.#c(),shouldReconnect:()=>this.#r.hasActiveSubscriptions()});}};var me=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 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.#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);}},lc=z.object({key:ApiKeySchema,passphrase:z.string(),secret:z.string()}),mc=z.object({wallet:EvmAddressSchema,credentials:lc.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}),he=class extends me{constructor(e){super({apiKey:e.apiKey,environment:e.environment,data:new P({headers:e.environment.data.headers,root:e.environment.data.rest}),gamma:new P({headers:e.environment.gamma.headers,root:e.environment.gamma.rest}),clob:new P({headers:e.environment.clob.headers,root:e.environment.clob.rest,resolveHeaders:r=>this.resolveClobHeaders(r)}),relayer:new P({headers:e.environment.relayer.headers,root:e.environment.relayer.rest,resolveHeaders:r=>this.resolveRelayerHeaders(r)}),rfq:new P({headers:e.environment.rfq.headers,root:e.environment.rfq.rest}),perps:new P({headers:e.environment.perps.headers,root:e.environment.perps.rest}),rpc:new Y({url:e.environment.rpc}),webSockets:{clobMarket:new O({headers:e.environment.clob.market.headers,url:e.environment.clob.market.ws}),sports:new Q({headers:e.environment.sports.headers,url:e.environment.sports.ws}),rtds:new _({headers:e.environment.rtds.headers,url:e.environment.rtds.ws}),perpsSubscriptions:new M({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=X$1(e,mc);return Promise.resolve(async function*(){let n=Math.floor(Date.now()/1e3),i=s?.nonce??0,o=expectEvmAddress(yield ba()),h=expectEvmAddress(s.wallet),l=Z$1(this.environment,o,h);if(s.credentials!==void 0){let q=this.#e(s.credentials,l,r);try{if((await O$1(q)).includes(s.credentials.key))return q}catch(d$1){if(!(d$1 instanceof d)||d$1.status!==401)throw d$1}}let y=yield {kind:"signAuthMessage",payload:rs({address:o,chainId:this.environment.chainId,nonce:i,timestamp:n})},u=await M$1(this,{address:o,nonce:i,signature:expectEvmSignature(y),timestamp:n});return this.#e(u,l,r)}.call(this))}#e(e,r,s){let n=new at({account:r,apiKey:this.context.apiKey,credentials:e,environment:this.environment,signer:s});for(let i of this.decorators)n.extend(i);return n}},at=class extends me{#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 P({headers:e.environment.clob.headers,root:e.environment.clob.rest,resolveHeaders:r=>this.resolveClobHeaders(r)}),relayer:new P({headers:e.environment.relayer.headers,root:e.environment.relayer.rest,resolveHeaders:r=>this.resolveRelayerHeaders(r)}),rpc:new Y({url:e.environment.rpc}),gamma:new P({headers:e.environment.gamma.headers,root:e.environment.gamma.rest}),data:new P({headers:e.environment.data.headers,root:e.environment.data.rest}),rfq:new P({headers:e.environment.rfq.headers,root:e.environment.rfq.rest}),perps:new P({headers:e.environment.perps.headers,root:e.environment.perps.rest}),secureClob:new P({headers:e.environment.clob.headers,resolveHeaders:async r=>({...await this.resolveClobHeaders(r),...await this.#t(r)}),root:e.environment.clob.rest}),webSockets:{clobMarket:new O({headers:e.environment.clob.market.headers,url:e.environment.clob.market.ws}),clobUser:new B({credentials:e.credentials,headers:e.environment.clob.user.headers,url:e.environment.clob.user.ws}),rfqQuoter:new U({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 Q({headers:e.environment.sports.headers,url:e.environment.sports.ws}),rtds:new _({headers:e.environment.rtds.headers,url:e.environment.rtds.ws}),perpsSubscriptions:new M({headers:e.environment.perps.headers,url:e.environment.perps.ws}),perpsSession:new H({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 Q$1(this);}finally{this.endAuthenticationLifecycle(),await Promise.allSettled([e,r,s]).then(()=>{});}let o=new he({apiKey:n,environment:i});for(let h of this.decorators)o.extend(h);return o}async#t(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 cs(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 Rn(t={}){return new he({environment:t.environment??We,apiKey:t.apiKey}).extend(os)}var hc=k(h,e,d,j,f,g$1,c,b,a),fc=k(a);async function yc(t){let e=Rn({environment:t.environment,apiKey:t.apiKey}),r=await Pc(e,t),s=await e.beginAuthentication({wallet:r,credentials:t.credentials,nonce:t.nonce},t.signer).then(aa$1(t.signer));if(s.account.walletType===WalletType.EOA||await ha$1(s,{wallet:s.account.wallet,type:s.account.walletType}))return s;if(s.account.walletType===WalletType.DEPOSIT_WALLET)return await Sc(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 Pc(t,e){if(e.wallet!==void 0)return e.wallet;let r=expectEvmAddress(await e.signer.getAddress());return $(t.rpc,r,t.environment.walletDerivation)}async function Sc(t){let e=await $(t.rpc,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 ka$1(t)).wait();}
2
- export{hc as CreateSecureClientError,fc as SetupGaslessWalletError,Oe as accountActions,os as allActions,Ie as analyticsActions,cs as buildHmacSignature,Rn as createPublicClient,yc as createSecureClient,Me as dataActions,Fe as discoveryActions,po as forkEnvironmentConfig,Le as perpsActions,tu as preproduction,We as production,ao as relayerApiKey,oo as remoteBuilderSigning,De as rewardsActions,ss as rfqActions,Be as subscriptionsActions,ns as tradingActions,is as walletActions};//# sourceMappingURL=index.js.map
1
+ import {M,W as W$1,U as U$1,S as S$1,oa,Xd,Vd,Td,Rd,Qd,Nd,hc,fc,dc,fb,ma,rc,tc,Fc,Lb,Jb,Hb,Fb,Db,Bb,zb,xb,vb,jb,hb,bc,Vb,Tb,Rb,Ee,mf,bf,$e,Ve,kf,if as _if,gf,ef,Ze,Xe,pc,nc,lc,jc,$b,Zb,Xb,Ld,Id,Hd,Kd,ka,ia,ga,ea,ca,aa,Me,cf,Q,O as O$1,Dc,Bc,zc,xc,Kc,Jc,bd,$c,Zc,Xc,Ce,xe,oe as oe$1,qf,La,Ha,Pa,ra,wa,K,za,zd,xd,vd,rd,pd,nd,Bd,td,vc,Pb,Nb,H,cd,G,sa,I as I$1,Xa,Va,id,gd,hd,ed,fd,dd,Za,ld,Fe,He,Je,J,Lc,Mc}from'./chunk-FSNACMPO.js';export{Ka as ApproveErc1155ForAllError,Ga as ApproveErc20Error,Ac as CancelAllError,Cc as CancelMarketOrdersError,wc as CancelOrderError,yc as CancelOrdersError,C as CombinatorialPrepareConditionCallError,Yd as ComboPositionStatus,_c as CreateLimitOrderError,Wc as CreateMarketOrderError,q as CtfRedeemPositionsCallError,Wd as DownloadAccountingSnapshotError,V as DropNotificationsError,b as Erc20ApprovalCallError,m as Erc20TransferCallError,Ec as EstimateMarketPriceError,L as FetchClosedOnlyModeError,Sb as FetchCommentsByIdError,Yb as FetchEventError,ac as FetchEventLiveVolumeError,_b as FetchEventTagsError,Gb as FetchLastTradePriceError,Ib as FetchLastTradePricesError,mc as FetchMarketError,oc as FetchMarketTagsError,gb as FetchMidpointError,ib as FetchMidpointsError,T as FetchNotificationsError,yb as FetchOrderBookError,Ab as FetchOrderBooksError,P as FetchOrderError,$ as FetchOrderScoringError,ba as FetchOrdersScoringError,Sd as FetchPortfolioValueError,ub as FetchPriceError,Kb as FetchPriceHistoryError,wb as FetchPricesError,De as FetchPublicProfileError,jf as FetchRelatedTagResourcesError,hf as FetchRelatedTagsError,ja as FetchRewardPercentagesError,Ye as FetchSeriesError,af as FetchSportsMarketTypesError,Cb as FetchSpreadError,Eb as FetchSpreadsError,ff as FetchTagError,fa as FetchTotalEarningsForUserForDayError,Ud as FetchTradedMarketCountError,R as ListAccountTradesError,na as ListActivityError,cc as ListBuilderLeaderboardError,eb as ListBuilderTradesError,ec as ListBuilderVolumeError,Od as ListClosedPositionsError,kc as ListComboMarketsError,Pd as ListComboPositionsError,Ub as ListCommentsByUserAddressError,Qb as ListCommentsError,Mb as ListCurrentRewardsError,Wb as ListEventsError,qc as ListMarketHoldersError,uc as ListMarketPositionsError,Ob as ListMarketRewardsError,ic as ListMarketsError,sc as ListOpenInterestError,N as ListOpenOrdersError,Md as ListPositionsError,We as ListSeriesError,_e as ListSportsError,df as ListTagsError,lf as ListTeamsError,gc as ListTraderLeaderboardError,la as ListTradesError,ha as ListUserEarningsAndMarketsConfigError,da as ListUserEarningsForDayError,a as MAX_UINT256,t as MergePositionsCallError,se as MergePositionsError,y as MergeV2CallError,Le as OpenRfqSessionError,o as PerpsDepositCallError,ad as PlaceLimitOrderError,Yc as PlaceMarketOrderError,Hc as PostOrderError,Ic as PostOrdersError,Be as RedeemPositionsError,A as RedeemV2CallError,Ie as RfqCancelQuoteError,He as RfqCancelQuoteRejectedError,Ne as RfqConfirmationDecision,Ke as RfqConfirmationError,Je as RfqConfirmationRejectedError,Oe as RfqDirection,Pe as RfqErrorCode,Qe as RfqExecutionStatus,Ge as RfqQuoteError,Fe as RfqQuoteRejectedError,Re as RfqRequestedSizeUnit,Se as RfqSide,Ue as SearchError,Te as SearchSort,Oa as SetupTradingApprovalsError,r as SplitPositionCallError,je as SplitPositionError,w as SplitV2CallError,pf as TransferErc20Error,jd as UpdatePerpsLeverageError,kd as UpdatePerpsMarginError,pa 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,qa as expectTransactionHandle,u as mergePositionsCall,z as mergeV2Call,p as perpsDepositCall,B as redeemV2Call,s as splitPositionCall,x as splitV2Call}from'./chunk-FSNACMPO.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 Jn=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 Zn(t){return new te(t)}function Xn(t){return new re(t)}var te=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 Jn.parse(await r.json())}},re=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 Rr(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 ei(t){return {listPositions:Nd.bind(null,t),listClosedPositions:Qd.bind(null,t),listComboPositions:Rd.bind(null,t),fetchPortfolioValue:Td.bind(null,t),fetchTradedMarketCount:Vd.bind(null,t),downloadAccountingSnapshot:Xd.bind(null,t),listMarketPositions:vc.bind(null,t),listActivity:oa.bind(null,t)}}function y(t,e={}){return {...e,user:e.user??t.account.wallet}}function se(t){let e=ei(t);return t.isPublicClient()?e:{...e,listPositions:r=>Nd(t,y(t,r)),listClosedPositions:r=>Qd(t,y(t,r)),listComboPositions:r=>Rd(t,y(t,r)),fetchPortfolioValue:r=>Td(t,y(t,r)),fetchTradedMarketCount:r=>Vd(t,y(t,r)),downloadAccountingSnapshot:r=>Xd(t,y(t,r)),listActivity:r=>oa(t,y(t,r)),listAccountTrades:S$1.bind(null,t),fetchNotifications:U$1.bind(null,t),dropNotifications:W$1.bind(null,t),fetchClosedOnlyMode:M.bind(null,t)}}function ne(t){return {listBuilderTrades:fb.bind(null,t),listBuilderLeaderboard:dc.bind(null,t),fetchBuilderVolume:fc.bind(null,t),listTraderLeaderboard:hc.bind(null,t)}}function ie(t){return {fetchEventLiveVolume:bc.bind(null,t),fetchMidpoint:hb.bind(null,t),fetchMidpoints:jb.bind(null,t),fetchPrice:vb.bind(null,t),fetchPrices:xb.bind(null,t),fetchOrderBook:zb.bind(null,t),fetchOrderBooks:Bb.bind(null,t),fetchSpread:Db.bind(null,t),fetchSpreads:Fb.bind(null,t),fetchLastTradePrice:Hb.bind(null,t),fetchLastTradePrices:Jb.bind(null,t),fetchPriceHistory:Lb.bind(null,t),estimateMarketPrice:Fc.bind(null,t),listOpenInterest:tc.bind(null,t),listMarketHolders:rc.bind(null,t),listTrades:ma.bind(null,t)}}function oe(t){return {listEvents:Xb.bind(null,t),fetchEvent:Zb.bind(null,t),fetchEventTags:$b.bind(null,t),listMarkets:jc.bind(null,t),listComboMarkets:lc.bind(null,t),fetchMarket:nc.bind(null,t),fetchMarketTags:pc.bind(null,t),listSeries:Xe.bind(null,t),fetchSeries:Ze.bind(null,t),listTags:ef.bind(null,t),fetchTag:gf.bind(null,t),fetchRelatedTags:_if.bind(null,t),fetchRelatedTagResources:kf.bind(null,t),search:Ve.bind(null,t),listSports:$e.bind(null,t),fetchSportsMarketTypes:bf.bind(null,t),listTeams:mf.bind(null,t),fetchPublicProfile:Ee.bind(null,t),listComments:Rb.bind(null,t),fetchCommentsById:Tb.bind(null,t),listCommentsByUserAddress:Vb.bind(null,t)}}function ae(t){let e={fetchPerpsBook:r=>td(t,r),fetchPerpsFees:()=>Bd(t),fetchPerpsInstruments:r=>nd(t,r),fetchPerpsTicker:r=>pd(t,r),fetchPerpsTickers:r=>rd(t,r),listPerpsCandles:r=>vd(t,r),listPerpsFundingHistory:r=>xd(t,r),listPerpsTrades:r=>zd(t,r)};return t.isSecureClient()?{...e,depositToPerps:r=>Kd(t,r),openPerpsSession:r=>Hd(t,r),revokePerpsCredentials:r=>Id(t,r),withdrawFromPerps:r=>Ld(t,r)}:e}function ti(t){return {listCurrentRewards:Nb.bind(null,t),listMarketRewards:Pb.bind(null,t)}}function ce(t){let e=ti(t);return t.isPublicClient()?e:{...e,fetchOrderScoring:aa.bind(null,t),fetchOrdersScoring:ca.bind(null,t),listUserEarningsForDay:ea.bind(null,t),fetchTotalEarningsForUserForDay:ga.bind(null,t),listUserEarningsAndMarketsConfig:ia.bind(null,t),fetchRewardPercentages:ka.bind(null,t)}}function gr(t){return {openRfqSession(){return Me(t)}}}function ue(t){return t.isSecureClient()?{subscribe(e){return cf(t,e)}}:{subscribe(e){return cf(t,e)}}}function Pr(t){return {createMarketOrder:Xc.bind(null,t),placeMarketOrder:Zc.bind(null,t),createLimitOrder:$c.bind(null,t),placeLimitOrder:bd.bind(null,t),postOrder:Jc(t),postOrders:Kc(t),cancelOrder:xc.bind(null,t),cancelOrders:zc.bind(null,t),cancelAll:Bc.bind(null,t),cancelMarketOrders:Dc.bind(null,t),listOpenOrders:O$1.bind(null,t),fetchOrder:Q.bind(null,t)}}function qr(t){return {isGaslessReady:()=>Promise.resolve(true),setupTradingApprovals:Pa.bind(null,t),approveErc20:Ha.bind(null,t),approveErc1155ForAll:La.bind(null,t),transferErc20:qf.bind(null,t),splitPosition:oe$1.bind(null,t),mergePositions:xe.bind(null,t),redeemPositions:Ce.bind(null,t)}}function Ar(t){return t.isSecureClient()?{...se(t),...ne(t),...ie(t),...oe(t),...ae(t),...ce(t),...gr(t),...ue(t),...Pr(t),...qr(t)}:{...se(t),...ne(t),...ie(t),...oe(t),...ae(t),...ce(t),...ue(t)}}var de={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 ri(t,e=de){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:vr(e.rfq,t.rfq),perps:vr(e.perps,t.perps),rtds:O(e.rtds,t.rtds),sports:O(e.sports,t.sports)}}function I(t,e){return {...t,...e,headers:pe(t.headers,e?.headers)}}function O(t,e){return {...t,...e,headers:pe(t.headers,e?.headers)}}function vr(t,e){return {...t,...e,headers:pe(t.headers,e?.headers)}}function pe(t,e){if(!(t===void 0&&e===void 0))return {...t,...e}}var Wa=ri({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 Cr(t,e,r,s,n){let i=`${e}${r}${s}`;n!==void 0&&(i+=n);let o=await globalThis.crypto.subtle.importKey("raw",si(t),{name:"HMAC",hash:"SHA-256"},false,["sign"]),v=await globalThis.crypto.subtle.sign("HMAC",o,new TextEncoder().encode(i));return ii(ni(v))}function si(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 ni(t){let e=new Uint8Array(t),r="";for(let s of e)r+=String.fromCharCode(s);return btoa(r)}function ii(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 le(t,e,r){let s=F(r.assetsIds,e.assetsIds),n=F(e.assetsIds,r.assetsIds);s.length>0&&t(Er(s,r.customFeatureEnabled));let i=r.assetsIds[0];s.length===0&&e.customFeatureEnabled!==r.customFeatureEnabled&&i!==void 0&&t(Er([i],r.customFeatureEnabled)),n.length>0&&t(ai(n));}function me(t,e,r){if(r.includeAllMarkets){!e.includeAllMarkets&&e.markets.length>0&&t(Tr(e.markets));return}if(e.includeAllMarkets){r.markets.length>0&&t(kr(r.markets));return}let s=F(r.markets,e.markets),n=F(e.markets,r.markets);s.length>0&&t(kr(s)),n.length>0&&t(Tr(n));}function wr(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 xr(t){let e=false,r=new Set;for(let{subscription:s}of t){if(Br(s)){e=true;continue}for(let n of s.markets??[])r.add(n);}return {includeAllMarkets:e,markets:e?[]:Array.from(r)}}function Mr(t){return {assets_ids:t.assetsIds,custom_feature_enabled:t.customFeatureEnabled,type:"market"}}function Er(t,e){return {assets_ids:t,custom_feature_enabled:e,operation:"subscribe"}}function ai(t){return {assets_ids:t,operation:"unsubscribe"}}function Ir(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 kr(t){return {markets:t,operation:"subscribe"}}function Tr(t){return {markets:t,operation:"unsubscribe"}}function Or(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 Fr(t){if(Br(t))return ()=>true;let e=new Set((t.markets??[]).map(r=>r.toLowerCase()));return r=>e.has(r.payload.market.toLowerCase())}function Br(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 id({heartbeat:new dd});#i=new hd;#t=new p({deriveServerState:wr});constructor(e){this.#e=e.headers,this.#r=e.url;}async subscribe(e){let{change:r,entry:s}=this.#t.add(e,{matches:Or(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&&le(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}le(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(Mr(this.#t.serverState()));}#m(){this.#i.schedule({reconnect:()=>this.#u(),shouldReconnect:()=>this.#t.hasActiveSubscriptions()});}};var R=class{#e;#r;#s;#o;#i=new id({heartbeat:new dd});#t=new hd;#n=new p({deriveServerState:xr});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:Fr(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&&me(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}me(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(Ir(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 ld({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 id({heartbeat:new gd});#t=new hd;#n=new p({deriveServerState:pi});constructor(e){this.#e=e.headers,this.#r=e.url;}async subscribe(e){let{change:r,entry:s}=this.#n.add(e,{matches:mi(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(Dr(r.before,r.after)),this.#y(Lr(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(Dr(r,s)),this.#y(Lr(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 pi(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(li(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 Dr(t,e){return Array.from(e).filter(r=>!t.has(r))}function Lr(t,e){return Array.from(t).filter(r=>!e.has(r))}function li(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 mi(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 Qr(t,e){return {...e,quote:r=>t.quote(e,r)}}function Hr(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 _r(t){return {quoteId:t.quoteId,rfqId:t.rfqId}}function Kr(t){return {quoteId:t.quoteId,rfqId:t.rfqId}}function Vr(t){return {quoteId:t.quoteId,rfqId:t.rfqId}}function jr(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 zr(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 $r(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 Nr(t,e,r){return {decision:r,quote_id:e,rfq_id:t,type:"RFQ_CONFIRMATION_RESPONSE"}}var B=class{#e=new Map;#r;constructor(e){this.#r=e;}waitFor(e,r){let s=hi(),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 hi(){let t,e;return {promise:new Promise((s,n)=>{t=s,e=n;}),reject:e,resolve:t}}var Gr="0x0000000000000000000000000000000000000000000000000000000000000000";async function Zr(t){let e=J(t.account),r={builder:Gr,maker:e.maker,makerAmount:toBaseUnits(yi(t.orderSide,t.orderPrice,t.size)),metadata:Gr,salt:Ri().toString(),side:bi(t.orderSide),signatureType:e.signatureType,signer:e.signer,takerAmount:toBaseUnits(Si(t.orderSide,t.orderPrice,t.size)),timestamp:Math.floor(Date.now()/1e3).toString(),tokenId:t.tokenId},s;try{s=await t.signer.signTypedData(Lc({domain:Jr(t),order:r}));}catch(n){throw j.fromError(n,"Could not sign the RFQ quote order.")}return {...r,signature:Mc({domain:Jr(t),order:r,signature:s})}}function Jr(t){return {chainId:t.chainId,exchange:t.exchange,protocolVersion:"3"}}function yi(t,e,r){return t===OrderSide.SELL?r.toString():((e*r+999999n)/1000000n).toString()}function Si(t,e,r){return t===OrderSide.SELL?(e*r/1000000n).toString():r.toString()}function bi(t){return t===OrderSide.BUY?0:1}function Ri(){let t=new Uint8Array(8);return globalThis.crypto.getRandomValues(t),BigInt(`0x${Array.from(t,e=>e.toString(16).padStart(2,"0")).join("")}`)}var ts=DecimalishSchema.transform(t=>ns(t)).refine(t=>t<=BigInt(Number.MAX_SAFE_INTEGER),{message:"Value exceeds the temporary numeric wire limit."}),qi=z.strictObject({price:ts.refine(t=>t<1000000n,{message:"Price must be less than 1."}),size:ts.optional(),source:z.enum(["collateral","inventory"]).default("collateral")});function rs(t){return G(t,qi)}async function ss(t){let e=t.response.price,r=t.response.size===void 0?Ei(t.request.requestedSize,e):t.response.size,s=await Zr({account:t.account,chainId:t.chainId,exchange:t.exchange,orderPrice:vi(t.request,t.response.source,e),orderSide:Ci(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 vi(t,e,r){return t.direction===RfqDirection.Buy&&e==="collateral"||t.direction===RfqDirection.Sell&&e==="inventory"?1000000n-r:r}function Ci(t){return t==="collateral"?OrderSide.BUY:OrderSide.SELL}function Ei(t,e){let r=ns(t.value);return t.unit===RfqRequestedSizeUnit.Shares?r:r*1000000n/e}function ns(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 Mi=3e4,Ii=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 be({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);}},be=class{#e;#r;#s;#o;#i;#t;#n;#a;#d=new id;#u=pushable({objectMode:true});#c=new B(Ii);#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=Oi();this.#l=e;let r=setNonBlockingTimeout(()=>{e.reject(new c("RFQ quoter authentication timed out."));},Mi);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(jr(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(Qr(this,s));return;case "quote_ack":this.#c.resolve(D(s.rfqId),_r(s));return;case "quote_cancel_ack":this.#c.resolve(ye(s.rfqId,s.quoteId),Kr(s));return;case "confirmation_request":this.#u.push(Hr(this,s));return;case "confirmation_ack":this.#c.resolve(Se(s.rfqId,s.quoteId),Vr(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(D(e.rfqId),new Fe(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(ye(e.rfqId,e.quoteId),new He(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(Se(e.rfqId,e.quoteId),new Je(e.message,{code:e.code,errorId:e.errorId,quoteId:e.quoteId,rfqId:e.rfqId}));}}async quote(e,r){let s=rs(r),n=await ss({account:this.#e,chainId:this.#r,exchange:this.#o,request:e,response:s,signer:this.#n}),i=this.#c.waitFor(D(e.rfqId),`Timed out waiting for RFQ quote acknowledgement for ${e.rfqId}.`);try{return await this.#f(zr(e,n)),await i}catch(o){throw this.#c.remove(D(e.rfqId),i),o}}async cancelQuote(e){let r=ye(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($r(this.#e,e.rfqId,e.quoteId)),await s}catch(n){throw this.#c.remove(r,s),n}}async respondToConfirmation(e,r,s){let n=Se(e,r),i=this.#c.waitFor(n,`Timed out waiting for RFQ confirmation acknowledgement for ${e}.`);try{return await this.#f(Nr(e,r,s)),await i}catch(o){throw this.#c.remove(n,i),o}}};function D(t){return `ACK_RFQ_QUOTE:${t}`}function ye(t,e){return `ACK_RFQ_QUOTE_CANCEL:${t}:${e}`}function Se(t,e){return `ACK_RFQ_CONFIRMATION_RESPONSE:${t}:${e}`}function Oi(){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 id({heartbeat:new ed});#i=new hd;#t=new p({deriveServerState:Li});constructor(e){this.#e=e.headers,this.#r=e.url;}async subscribe(e){let{change:r,entry:s}=this.#t.add(e,{matches:Hi(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=Di(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(Wi(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 Di(t,e){return Array.from(t).flatMap(([r,s])=>e.has(r)?[]:[s])}function Li(t){let e=new Map;for(let{subscription:r}of t)for(let s of Qi(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 Wi(t){return {action:"unsubscribe",subscriptions:t.map(({topic:e,type:r})=>({topic:e,type:r}))}}function Qi(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 Hi(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 A=class{#e;#r;#s;#o=new id({heartbeat:new fd});#i=new hd;#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 U=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);}},Ni=z.object({key:ApiKeySchema,passphrase:z.string(),secret:z.string()}),Yi=z.object({wallet:EvmAddressSchema,credentials:Ni.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}),W=class extends U{constructor(e){super({apiKey:e.apiKey,environment:e.environment,data:new cd({headers:e.environment.data.headers,root:e.environment.data.rest}),gamma:new cd({headers:e.environment.gamma.headers,root:e.environment.gamma.rest}),clob:new cd({headers:e.environment.clob.headers,root:e.environment.clob.rest,resolveHeaders:r=>this.resolveClobHeaders(r)}),relayer:new cd({headers:e.environment.relayer.headers,root:e.environment.relayer.rest,resolveHeaders:r=>this.resolveRelayerHeaders(r)}),rfq:new cd({headers:e.environment.rfq.headers,root:e.environment.rfq.rest}),perps:new cd({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 A({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,Yi);return Promise.resolve(async function*(){let n=Math.floor(Date.now()/1e3),i=s?.nonce??0,o=expectEvmAddress(yield sa()),v=expectEvmAddress(s.wallet),Pe=I$1(this.environment,o,v);if(s.credentials!==void 0){let qe=this.#e(s.credentials,Pe,r);try{if((await Xa(qe)).includes(s.credentials.key))return qe}catch(T){if(!(T instanceof d)||T.status!==401)throw T}}let cs=yield {kind:"signAuthMessage",payload:Rr({address:o,chainId:this.environment.chainId,nonce:i,timestamp:n})},us=await Va(this,{address:o,nonce:i,signature:expectEvmSignature(cs),timestamp:n});return this.#e(us,Pe,r)}.call(this))}#e(e,r,s){let n=new ge({account:r,apiKey:this.context.apiKey,credentials:e,environment:this.environment,signer:s});for(let i of this.decorators)n.extend(i);return n}},ge=class extends U{#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 cd({headers:e.environment.clob.headers,root:e.environment.clob.rest,resolveHeaders:r=>this.resolveClobHeaders(r)}),relayer:new cd({headers:e.environment.relayer.headers,root:e.environment.relayer.rest,resolveHeaders:r=>this.resolveRelayerHeaders(r)}),rpc:new H({url:e.environment.rpc}),gamma:new cd({headers:e.environment.gamma.headers,root:e.environment.gamma.rest}),data:new cd({headers:e.environment.data.headers,root:e.environment.data.rest}),rfq:new cd({headers:e.environment.rfq.headers,root:e.environment.rfq.rest}),perps:new cd({headers:e.environment.perps.headers,root:e.environment.perps.rest}),secureClob:new cd({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 A({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 Za(this);}finally{this.endAuthenticationLifecycle(),await Promise.allSettled([e,r,s]).then(()=>{});}let o=new W({apiKey:n,environment:i});for(let v of this.decorators)o.extend(v);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 Cr(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 as(t={}){return new W({environment:t.environment??de,apiKey:t.apiKey}).extend(Ar)}var Gi=k(h,e,d,j,f,g$1,c,b$1,a),Ji=k(a);async function Zi(t){let e=as({environment:t.environment,apiKey:t.apiKey}),r=await Xi(e,t),s=await e.beginAuthentication({wallet:r,credentials:t.credentials,nonce:t.nonce},t.signer).then(ra(t.signer));if(s.account.walletType===WalletType.EOA||await wa(s,{wallet:s.account.wallet,type:s.account.walletType}))return s;if(s.account.walletType===WalletType.DEPOSIT_WALLET)return await eo(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 Xi(t,e){if(e.wallet!==void 0)return e.wallet;let r=expectEvmAddress(await e.signer.getAddress());return K(t.rpc,r,t.environment.walletDerivation)}async function eo(t){let e=await K(t.rpc,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 za(t)).wait();}
2
+ export{Gi as CreateSecureClientError,Ji as SetupGaslessWalletError,se as accountActions,Ar as allActions,ne as analyticsActions,Cr as buildHmacSignature,as as createPublicClient,Zi as createSecureClient,ie as dataActions,oe as discoveryActions,ri as forkEnvironmentConfig,ae as perpsActions,Wa as preproduction,de as production,Xn as relayerApiKey,Zn as remoteBuilderSigning,ce as rewardsActions,gr as rfqActions,ue as subscriptionsActions,Pr as tradingActions,qr as walletActions};//# sourceMappingURL=index.js.map
3
3
  //# sourceMappingURL=index.js.map