@polymarket/client 0.1.0 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/actions/index.d.ts +4 -4
- package/dist/actions/index.js +1 -1
- package/dist/chunk-FA3ZDOJN.js +2 -0
- package/dist/chunk-FA3ZDOJN.js.map +1 -0
- package/dist/ethers-v5.d.ts +2 -2
- package/dist/index.d.ts +5 -5
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/{sports-Dm3yiYAe.d.ts → sports-CYYRGlQj.d.ts} +1 -1
- package/dist/{types-CgIv7KE4.d.ts → types-vvy5wT5V.d.ts} +229 -9
- package/dist/viem.d.ts +2 -2
- package/package.json +2 -2
- package/dist/chunk-Z6CZB4WP.js +0 -2
- package/dist/chunk-Z6CZB4WP.js.map +0 -1
package/dist/ethers-v5.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { ethers } from 'ethers-v5';
|
|
2
|
-
import { T as TypedDataPayload, a as TypedData, S as Signer } from './types-
|
|
2
|
+
import { T as TypedDataPayload, a as TypedData, S as Signer } from './types-vvy5wT5V.js';
|
|
3
3
|
import '@polymarket/bindings';
|
|
4
4
|
import '@polymarket/types';
|
|
5
5
|
import '@polymarket/bindings/gamma';
|
|
@@ -7,7 +7,7 @@ import '@polymarket/bindings/relayer';
|
|
|
7
7
|
import 'zod';
|
|
8
8
|
import '@polymarket/bindings/clob';
|
|
9
9
|
import '@polymarket/bindings/data';
|
|
10
|
-
import '@polymarket/bindings/
|
|
10
|
+
import '@polymarket/bindings/combos';
|
|
11
11
|
import '@polymarket/bindings/perps';
|
|
12
12
|
import '@polymarket/bindings/subscriptions';
|
|
13
13
|
import 'ox';
|
package/dist/index.d.ts
CHANGED
|
@@ -8,14 +8,14 @@ export { ActivityType, ComboActivityType, ComboPositionOutcome, ComboPositionSta
|
|
|
8
8
|
export * from '@polymarket/bindings/gamma';
|
|
9
9
|
export { WalletType } from '@polymarket/bindings/gamma';
|
|
10
10
|
export * from '@polymarket/bindings/perps';
|
|
11
|
-
export { PerpsCancelOrderResult, PerpsDepositStatus, PerpsInstrumentCategory, PerpsInstrumentType, PerpsInternalTransferDirection, PerpsKlineInterval, PerpsOrderStatus, PerpsPostOrderAck, PerpsSide, PerpsTimeInForce, PerpsUpdateLeverageResult
|
|
11
|
+
export { PerpsCancelOrderResult, PerpsDepositStatus, PerpsInstrumentCategory, PerpsInstrumentType, PerpsInternalTransferDirection, PerpsKlineInterval, PerpsKnownWithdrawalStatus, PerpsOrderStatus, PerpsPostOrderAck, PerpsSide, PerpsTimeInForce, PerpsUpdateLeverageResult } 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-
|
|
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 CancelAllPerpsOrdersRequest, k as CancelMarketOrdersError, l as CancelOrderError, m as CancelOrdersError, n as CancelPerpsOrderRequest, o as CancelPerpsOrdersRequest, p as CancelledSigningError, q as Client, r as ClientActions, s as ClientDecorator, t as ClobEndpoints, u as ComboPositionSort, v as
|
|
16
|
-
export { C as CreateLimitOrderError, a as CreateMarketOrderError, F as FetchSportsMarketTypesError, L as ListSportsError, P as PlaceLimitOrderError, b as PlaceMarketOrderError } from './sports-
|
|
14
|
+
import { U as UserInputError, b as TransactionCall, A as ApiKeyAuthorization } from './types-vvy5wT5V.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 CancelAllPerpsOrdersRequest, k as CancelMarketOrdersError, l as CancelOrderError, m as CancelOrdersError, n as CancelPerpsOrderRequest, o as CancelPerpsOrdersRequest, p as CancelledSigningError, q as Client, r as ClientActions, s as ClientDecorator, t as ClobEndpoints, u as ComboPositionSort, v as CombosEndpoints, w as ConnectionLostError, x as ConnectionLostErrorOptions, y as CreatePerpsSessionRequest, z as CreateSecureClientError, D as DataActions, E as DepositToPerpsError, F as DepositToPerpsRequest, G as DiscoveryActions, H as DownloadAccountingSnapshotError, I as DropNotificationsError, J as EnvironmentConfig, K as EnvironmentConfigFork, L as EnvironmentContracts, M as EstimateMarketPriceError, N as ExecuteCollateralReturnPlanError, O as ExecuteCollateralReturnPlanRequest, P as FetchClosedOnlyModeError, Q as FetchCommentsByIdError, R as FetchEventError, V as FetchEventLiveVolumeError, W as FetchEventTagsError, X as FetchLastTradePriceError, Y as FetchLastTradePricesError, Z as FetchMarketError, _ as FetchMarketTagsError, $ as FetchMidpointError, a0 as FetchMidpointsError, a1 as FetchNotificationsError, a2 as FetchOrderBookError, a3 as FetchOrderBooksError, a4 as FetchOrderError, a5 as FetchOrderScoringError, a6 as FetchOrdersScoringError, a7 as FetchPerpsAccountConfigRequest, a8 as FetchPerpsBookError, a9 as FetchPerpsBookRequest, aa as FetchPerpsFeesError, ab as FetchPerpsInstrumentsError, ac as FetchPerpsInstrumentsRequest, ad as FetchPerpsOpenOrdersRequest, ae as FetchPerpsOrdersRequest, af as FetchPerpsTickerError, ag as FetchPerpsTickerRequest, ah as FetchPerpsTickersError, ai as FetchPerpsTickersRequest, aj as FetchPortfolioValueError, ak as FetchPriceError, al as FetchPriceHistoryError, am as FetchPricesError, an as FetchPublicProfileError, ao as FetchRelatedTagResourcesError, ap as FetchRelatedTagsError, aq as FetchRewardPercentagesError, ar as FetchSeriesError, as as FetchSpreadError, at as FetchSpreadsError, au as FetchTagError, av as FetchTotalEarningsForUserForDayError, aw as FetchTradedMarketCountError, ax as InsufficientLiquidityError, ay as ListAccountTradesError, az as ListActivityError, aA as ListBuilderLeaderboardError, aB as ListBuilderTradesError, aC as ListBuilderVolumeError, aD as ListClosedPositionsError, aE as ListComboActivityError, aF as ListComboMarketsError, aG as ListComboPositionsError, aH as ListCommentsByUserAddressError, aI as ListCommentsError, aJ as ListCurrentRewardsError, aK as ListEventsError, aL as ListMarketHoldersError, aM as ListMarketPositionsError, aN as ListMarketRewardsError, aO as ListMarketsError, aP as ListOpenInterestError, aQ as ListOpenOrdersError, aR as ListPerpsCandlesError, aS as ListPerpsCandlesRequest, aT as ListPerpsDepositsRequest, aU as ListPerpsEquityHistoryRequest, aV as ListPerpsFillsRequest, aW as ListPerpsFundingHistoryError, aX as ListPerpsFundingHistoryRequest, aY as ListPerpsFundingPaymentsRequest, aZ as ListPerpsPnlHistoryRequest, a_ as ListPerpsTradesError, a$ as ListPerpsTradesRequest, b0 as ListPerpsWithdrawalsRequest, b1 as ListPositionsError, b2 as ListSeriesError, b3 as ListTagsError, b4 as ListTeamsError, b5 as ListTraderLeaderboardError, b6 as ListTradesError, b7 as ListUserEarningsAndMarketsConfigError, b8 as ListUserEarningsForDayError, b9 as MergePositionsError, ba as OpenPerpsSessionError, bb as OpenPerpsSessionRequest, bc as OpenRfqSessionError, bd as Page, be as PageSizeSchema, bf as Paginated, bg as PerpsActions, bh as PerpsBookDepth, bi as PerpsEndpoints, bj as PerpsOrderRequest, bk as PerpsPlaceFokOrderRequest, bl as PerpsPlaceGtcOrderRequest, bm as PerpsPlaceIocOrderRequest, bn as PerpsPlacedTpSlOrder, bo as PerpsPlacedTpSlOrders, bp as PerpsPositionTpSlTrigger, bq as PerpsSession, br as PerpsSessionAccountError, bs as PerpsSessionLifecycleError, bt as PerpsSessionTradingError, bu as PerpsTpSlTrigger, bv as PlacePerpsOrderRequest, bw as PlacePerpsOrderResult, bx as PlacePerpsOrderWithTpSlRequest, by as PlacePerpsOrderWithTpSlResult, bz as PlacePerpsPositionTpSlRequest, bA as PlacePerpsPositionTpSlResult, bB as PlanCollateralReturnError, bC as PostOrderError, bD as PostOrdersError, bE as PostPerpsOrdersRequest, bF as PublicAccountActions, bG as PublicActions, bH as PublicClient, bI as PublicClientOptions, bJ as PublicPerpsActions, bK as PublicRewardsActions, bL as PublicSubscriptionsActions, bM as RateLimitError, bN as RedeemPositionsError, bO as RequestRejectedError, bP as RequestRejectedErrorOptions, bQ as RestEndpoint, bR as ResumePerpsSessionRequest, bS as RevokePerpsCredentialsError, bT as RevokePerpsCredentialsRequest, bU as RfqCancelQuoteAck, bV as RfqCancelQuoteError, bW as RfqCancelQuoteRejectedError, bX as RfqCancelQuoteRejectedErrorOptions, bY as RfqConfirmationAck, bZ as RfqConfirmationError, b_ as RfqConfirmationRejectedError, b$ as RfqConfirmationRequestEvent, c0 as RfqEvent, c1 as RfqQuoteError, c2 as RfqQuoteReference, c3 as RfqQuoteRejectedError, c4 as RfqQuoteRejectedErrorOptions, c5 as RfqQuoteRequestEvent, c6 as RfqQuoteResponse, c7 as RfqQuoteSource, c8 as RfqSession, c9 as RfqTradeEvent, ca as SearchError, cb as SearchSort, cc as SecureAccountActions, cd as SecureActions, ce as SecureClient, cf as SecureClientOptions, cg as SecureDownloadAccountingSnapshotRequest, ch as SecureFetchPortfolioValueRequest, ci as SecureFetchTradedMarketCountRequest, cj as SecureListActivityRequest, ck as SecureListClosedPositionsRequest, cl as SecureListComboActivityRequest, cm as SecureListComboPositionsRequest, cn as SecureListPositionsRequest, co as SecurePerpsActions, cp as SecureRewardsActions, cq as SecureRfqActions, cr as SecureSubscriptionsActions, cs as SecureTradingActions, ct as SecureWalletActions, cu as SetupGaslessWalletError, cv as SetupTradingApprovalsError, S as Signer, cw as SignerTransactionRequest, cx as SigningError, cy as SplitPositionError, cz as TimeoutError, cA as TransactionFailedError, cB as TransactionHandle, cC as TransactionOutcome, cD as TransferErc20Error, cE as TransportError, a as TypedData, cF as TypedDataDomain, cG as TypedDataField, T as TypedDataPayload, cH as UnexpectedResponseError, cI as UpdatePerpsLeverageError, cJ as UpdatePerpsLeverageRequest, cK as WaitForOrderFillSettlementError, cL as WaitForTransactionError, cM as WalletDerivationConfig, cN as WebSocketCloseCode, cO as WebSocketEndpoint, cP as WebSocketKnownCloseCode, cQ as WithdrawFromPerpsError, cR as WithdrawFromPerpsRequest, cS as accountActions, cT as allActions, cU as analyticsActions, cV as createPublicClient, cW as createSecureClient, cX as dataActions, cY as discoveryActions, cZ as forkEnvironmentConfig, c_ as makeErrorGuard, c$ as perpsActions, d0 as production, d1 as rewardsActions, d2 as rfqActions, d3 as subscriptionsActions, d4 as tradingActions, d5 as walletActions } from './types-vvy5wT5V.js';
|
|
16
|
+
export { C as CreateLimitOrderError, a as CreateMarketOrderError, F as FetchSportsMarketTypesError, L as ListSportsError, P as PlaceLimitOrderError, b as PlaceMarketOrderError } from './sports-CYYRGlQj.js';
|
|
17
17
|
export { PerpsSessionEvent } from '@polymarket/bindings/subscriptions';
|
|
18
|
-
export { RfqConfirmationDecision, RfqConfirmationRequest, RfqDirection, RfqErrorCode, RfqExecutionStatus, RfqExecutionUpdate, RfqId, RfqKnownErrorCode, RfqQuoteId, RfqQuoteRequest, RfqRequestedSize, RfqRequestedSizeUnit, RfqRequestorPublicId, RfqSide, RfqTrade } from '@polymarket/bindings/
|
|
18
|
+
export { CollateralReturnKnownOperationKind, CollateralReturnOperation, CollateralReturnOperationKind, CollateralReturnPlanResponse, CollateralReturnPositionAmount, CollateralReturnPositionSummary, CollateralReturnRouterCall, RfqConfirmationDecision, RfqConfirmationRequest, RfqDirection, RfqErrorCode, RfqExecutionStatus, RfqExecutionUpdate, RfqId, RfqKnownErrorCode, RfqQuoteId, RfqQuoteRequest, RfqRequestedSize, RfqRequestedSizeUnit, RfqRequestorPublicId, RfqSide, RfqTrade } from '@polymarket/bindings/combos';
|
|
19
19
|
import 'zod';
|
|
20
20
|
import 'ox';
|
|
21
21
|
|
package/dist/index.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import {N,X,V,T,ra,pa,be as be$1,$d,Zd,Xd,Vd,Td,lc,jc,hc,jb,na,xc,zc,Lc,Pb,Nb,Lb,Jb,Hb,Fb,Db,Bb,zb,nb,lb,fc,Zb,Xb,Vb,Le,tf,if as _if,gf,af,rf,pf,nf,lf,nc,ef,cf,vc,tc,rc,pc,dc,bc,$b,Qd,Nd,Md,Pd,la,ja,ha,fa,da,ba,Te,jf,R as R$1,P as P$1,Jc,Hc,Fc,Dc,Qc,Pc,hd,fd,dd,bd,Je,Ee,ve as ve$1,xf,Pa,La,Ta,va,Aa,K,L as L$1,Da,Ed,Cd,Ad,wd,ud,sd,Gd,yd,Bc,Tb,Rb,H,id,G,wa,I as I$1,$a,Za,od,md,nd,kd,ld,jd,bb,qd,Me,Oe,Qe,J,Rc,Sc}from'./chunk-Z6CZB4WP.js';export{Oa as ApproveErc1155ForAllError,Ka as ApproveErc20Error,Gc as CancelAllError,Ic as CancelMarketOrdersError,Cc as CancelOrderError,Ec as CancelOrdersError,C as CombinatorialPrepareConditionCallError,sa as ComboActivityType,ce as ComboPositionOutcome,Rd as ComboPositionSort,de as ComboPositionStatus,ed as CreateLimitOrderError,ad as CreateMarketOrderError,q as CtfRedeemPositionsCallError,Kd as DepositToPerpsError,ae as DownloadAccountingSnapshotError,W as DropNotificationsError,b as Erc20ApprovalCallError,m as Erc20TransferCallError,Kc as EstimateMarketPriceError,M as FetchClosedOnlyModeError,Wb as FetchCommentsByIdError,ac as FetchEventError,ec as FetchEventLiveVolumeError,cc as FetchEventTagsError,Kb as FetchLastTradePriceError,Mb as FetchLastTradePricesError,sc as FetchMarketError,uc as FetchMarketTagsError,kb as FetchMidpointError,mb as FetchMidpointsError,U as FetchNotificationsError,Cb as FetchOrderBookError,Eb as FetchOrderBooksError,Q as FetchOrderError,aa as FetchOrderScoringError,ca as FetchOrdersScoringError,xd as FetchPerpsBookError,Fd as FetchPerpsFeesError,rd as FetchPerpsInstrumentsError,td as FetchPerpsTickerError,vd as FetchPerpsTickersError,Yd as FetchPortfolioValueError,yb as FetchPriceError,Ob as FetchPriceHistoryError,Ab as FetchPricesError,Ke as FetchPublicProfileError,qf as FetchRelatedTagResourcesError,of as FetchRelatedTagsError,ka as FetchRewardPercentagesError,df as FetchSeriesError,hf as FetchSportsMarketTypesError,Gb as FetchSpreadError,Ib as FetchSpreadsError,mf as FetchTagError,ga as FetchTotalEarningsForUserForDayError,_d as FetchTradedMarketCountError,S as ListAccountTradesError,oa as ListActivityError,gc as ListBuilderLeaderboardError,ib as ListBuilderTradesError,ic as ListBuilderVolumeError,Ud as ListClosedPositionsError,qa as ListComboActivityError,qc as ListComboMarketsError,Wd as ListComboPositionsError,Yb as ListCommentsByUserAddressError,Ub as ListCommentsError,Qb as ListCurrentRewardsError,_b as ListEventsError,wc as ListMarketHoldersError,Ac as ListMarketPositionsError,Sb as ListMarketRewardsError,oc as ListMarketsError,yc as ListOpenInterestError,O as ListOpenOrdersError,zd as ListPerpsCandlesError,Bd as ListPerpsFundingHistoryError,Dd as ListPerpsTradesError,Sd as ListPositionsError,bf as ListSeriesError,ff as ListSportsError,kf as ListTagsError,sf as ListTeamsError,kc as ListTraderLeaderboardError,ma as ListTradesError,ia as ListUserEarningsAndMarketsConfigError,ea as ListUserEarningsForDayError,a as MAX_UINT256,t as MergePositionsCallError,ze as MergePositionsError,y as MergeV2CallError,Hd as OpenPerpsSessionError,Se as OpenRfqSessionError,o as PerpsDepositCallError,gd as PlaceLimitOrderError,cd as PlaceMarketOrderError,Nc as PostOrderError,Oc as PostOrdersError,Ie as RedeemPositionsError,A as RedeemV2CallError,Id as RevokePerpsCredentialsError,Pe as RfqCancelQuoteError,Oe as RfqCancelQuoteRejectedError,Ue as RfqConfirmationDecision,Re as RfqConfirmationError,Qe as RfqConfirmationRejectedError,Ve as RfqDirection,We as RfqExecutionStatus,Xe as RfqKnownErrorCode,Ne as RfqQuoteError,Me as RfqQuoteRejectedError,Ye as RfqRequestedSizeUnit,Ze as RfqSide,$e as SearchError,_e as SearchSort,Sa as SetupTradingApprovalsError,r as SplitPositionCallError,qe as SplitPositionError,w as SplitV2CallError,wf as TransferErc20Error,pd as UpdatePerpsLeverageError,ta as WaitForTransactionError,Ld as WithdrawFromPerpsError,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,ua as expectTransactionHandle,u as mergePositionsCall,z as mergeV2Call,p as perpsDepositCall,B as redeemV2Call,s as splitPositionCall,x as splitV2Call}from'./chunk-Z6CZB4WP.js';import {a,m as m$1,j,g as g$1,f,l,h as h$1,i,c,b as b$1,e}from'./chunk-TYJAXA3Y.js';export{j as CancelledSigningError,e as ConnectionLostError,k as InsufficientLiquidityError,g as RateLimitError,f as RequestRejectedError,l as SigningError,h as TimeoutError,i as TransactionFailedError,c as TransportError,b as UnexpectedResponseError,a as UserInputError,d as WebSocketKnownCloseCode,m as makeErrorGuard}from'./chunk-TYJAXA3Y.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 {RfqQuoterInboundMessageSchema,RfqConfirmationDecision,RfqRequestedSizeUnit,RfqDirection}from'@polymarket/bindings/rfq';var yi=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 Si(t){return new se(t)}function bi(t){return new ne(t)}var se=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 l.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 yi.parse(await r.json())}},ne=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 Ar(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 Pi(t){return {listPositions:Td.bind(null,t),listClosedPositions:Vd.bind(null,t),listComboPositions:Xd.bind(null,t),fetchPortfolioValue:Zd.bind(null,t),fetchTradedMarketCount:$d.bind(null,t),downloadAccountingSnapshot:be$1.bind(null,t),listMarketPositions:Bc.bind(null,t),listActivity:pa.bind(null,t),listComboActivity:ra.bind(null,t)}}function h(t,e={}){return {...e,user:e.user??t.account.wallet}}function ie(t){let e=Pi(t);return t.isPublicClient()?e:{...e,listPositions:r=>Td(t,h(t,r)),listClosedPositions:r=>Vd(t,h(t,r)),listComboPositions:r=>Xd(t,h(t,r)),fetchPortfolioValue:r=>Zd(t,h(t,r)),fetchTradedMarketCount:r=>$d(t,h(t,r)),downloadAccountingSnapshot:r=>be$1(t,h(t,r)),listActivity:r=>pa(t,h(t,r)),listComboActivity:r=>ra(t,h(t,r)),listAccountTrades:T.bind(null,t),fetchNotifications:V.bind(null,t),dropNotifications:X.bind(null,t),fetchClosedOnlyMode:N.bind(null,t)}}function oe(t){return {listBuilderTrades:jb.bind(null,t),listBuilderLeaderboard:hc.bind(null,t),fetchBuilderVolume:jc.bind(null,t),listTraderLeaderboard:lc.bind(null,t)}}function ae(t){return {fetchEventLiveVolume:fc.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:Lc.bind(null,t),listOpenInterest:zc.bind(null,t),listMarketHolders:xc.bind(null,t),listTrades:na.bind(null,t)}}function ce(t){return {listEvents:$b.bind(null,t),fetchEvent:bc.bind(null,t),fetchEventTags:dc.bind(null,t),listMarkets:pc.bind(null,t),listComboMarkets:rc.bind(null,t),fetchMarket:tc.bind(null,t),fetchMarketTags:vc.bind(null,t),listSeries:cf.bind(null,t),fetchSeries:ef.bind(null,t),listMarketClarifications:nc.bind(null,t),listTags:lf.bind(null,t),fetchTag:nf.bind(null,t),fetchRelatedTags:pf.bind(null,t),fetchRelatedTagResources:rf.bind(null,t),search:af.bind(null,t),listSports:gf.bind(null,t),fetchSportsMarketTypes:_if.bind(null,t),listTeams:tf.bind(null,t),fetchPublicProfile:Le.bind(null,t),listComments:Vb.bind(null,t),fetchCommentsById:Xb.bind(null,t),listCommentsByUserAddress:Zb.bind(null,t)}}function ue(t){let e={fetchPerpsBook:r=>yd(t,r),fetchPerpsFees:()=>Gd(t),fetchPerpsInstruments:r=>sd(t,r),fetchPerpsTicker:r=>ud(t,r),fetchPerpsTickers:r=>wd(t,r),listPerpsCandles:r=>Ad(t,r),listPerpsFundingHistory:r=>Cd(t,r),listPerpsTrades:r=>Ed(t,r)};return t.isSecureClient()?{...e,depositToPerps:r=>Pd(t,r),openPerpsSession:r=>Md(t,r),revokePerpsCredentials:r=>Nd(t,r),withdrawFromPerps:r=>Qd(t,r)}:e}function Ri(t){return {listCurrentRewards:Rb.bind(null,t),listMarketRewards:Tb.bind(null,t)}}function de(t){let e=Ri(t);return t.isPublicClient()?e:{...e,fetchOrderScoring:ba.bind(null,t),fetchOrdersScoring:da.bind(null,t),listUserEarningsForDay:fa.bind(null,t),fetchTotalEarningsForUserForDay:ha.bind(null,t),listUserEarningsAndMarketsConfig:ja.bind(null,t),fetchRewardPercentages:la.bind(null,t)}}function Cr(t){return {openRfqSession(){return Te(t)}}}function pe(t){return t.isSecureClient()?{subscribe(e){return jf(t,e)}}:{subscribe(e){return jf(t,e)}}}function Er(t){return {createMarketOrder:bd.bind(null,t),placeMarketOrder:dd.bind(null,t),createLimitOrder:fd.bind(null,t),placeLimitOrder:hd.bind(null,t),postOrder:Pc(t),postOrders:Qc(t),cancelOrder:Dc.bind(null,t),cancelOrders:Fc.bind(null,t),cancelAll:Hc.bind(null,t),cancelMarketOrders:Jc.bind(null,t),listOpenOrders:P$1.bind(null,t),fetchOrder:R$1.bind(null,t)}}function kr(t){return {setupTradingApprovals:Ta.bind(null,t),approveErc20:La.bind(null,t),approveErc1155ForAll:Pa.bind(null,t),transferErc20:xf.bind(null,t),splitPosition:ve$1.bind(null,t),mergePositions:Ee.bind(null,t),redeemPositions:Je.bind(null,t)}}function Tr(t){return t.isSecureClient()?{...ie(t),...oe(t),...ae(t),...ce(t),...ue(t),...de(t),...Cr(t),...pe(t),...Er(t),...kr(t)}:{...ie(t),...oe(t),...ae(t),...ce(t),...ue(t),...de(t),...pe(t)}}var le={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 gi(t,e=le){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:wr(e.rfq,t.rfq),perps:wr(e.perps,t.perps),rtds:O(e.rtds,t.rtds),sports:O(e.sports,t.sports)}}function I(t,e){return {...t,...e,headers:me(t.headers,e?.headers)}}function O(t,e){return {...t,...e,headers:me(t.headers,e?.headers)}}function wr(t,e){return {...t,...e,headers:me(t.headers,e?.headers)}}function me(t,e){if(!(t===void 0&&e===void 0))return {...t,...e}}var ic=gi({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 xr(t,e,r,s,n){let i=`${e}${r}${s}`;n!==void 0&&(i+=n);let o=await globalThis.crypto.subtle.importKey("raw",qi(t),{name:"HMAC",hash:"SHA-256"},false,["sign"]),A=await globalThis.crypto.subtle.sign("HMAC",o,new TextEncoder().encode(i));return Ai(vi(A))}function qi(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 vi(t){let e=new Uint8Array(t),r="";for(let s of e)r+=String.fromCharCode(s);return btoa(r)}function Ai(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 fe(t,e,r){let s=F(r.assetsIds,e.assetsIds),n=F(e.assetsIds,r.assetsIds);s.length>0&&t(Mr(s,r.customFeatureEnabled));let i=r.assetsIds[0];s.length===0&&e.customFeatureEnabled!==r.customFeatureEnabled&&i!==void 0&&t(Mr([i],r.customFeatureEnabled)),n.length>0&&t(Ei(n));}function he(t,e,r){if(r.includeAllMarkets){!e.includeAllMarkets&&e.markets.length>0&&t(Or(e.markets));return}if(e.includeAllMarkets){r.markets.length>0&&t(Ir(r.markets));return}let s=F(r.markets,e.markets),n=F(e.markets,r.markets);s.length>0&&t(Ir(s)),n.length>0&&t(Or(n));}function Fr(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 Lr(t){let e=false,r=new Set;for(let{subscription:s}of t){if(Qr(s)){e=true;continue}for(let n of s.markets??[])r.add(n);}return {includeAllMarkets:e,markets:e?[]:Array.from(r)}}function Dr(t){return {assets_ids:t.assetsIds,custom_feature_enabled:t.customFeatureEnabled,type:"market"}}function Mr(t,e){return {assets_ids:t,custom_feature_enabled:e,operation:"subscribe"}}function Ei(t){return {assets_ids:t,operation:"unsubscribe"}}function Br(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 Ir(t){return {markets:t,operation:"subscribe"}}function Or(t){return {markets:t,operation:"unsubscribe"}}function Wr(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 Ur(t){if(Qr(t))return ()=>true;let e=new Set((t.markets??[]).map(r=>r.toLowerCase()));return r=>e.has(r.payload.market.toLowerCase())}function Qr(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 od({heartbeat:new jd});#i=new nd;#t=new p({deriveServerState:Fr});constructor(e){this.#e=e.headers,this.#r=e.url;}async subscribe(e){let{change:r,entry:s}=this.#t.add(e,{matches:Wr(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&&fe(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}fe(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({onConnectionLost:()=>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(Dr(this.#t.serverState()));}#m(){this.#i.schedule({reconnect:()=>this.#u(),shouldReconnect:()=>this.#t.hasActiveSubscriptions()});}};var P=class{#e;#r;#s;#o;#i=new od({heartbeat:new jd});#t=new nd;#n=new p({deriveServerState:Lr});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:Ur(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&&he(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}he(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({onConnectionLost:()=>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(Br(this.#n.serverState(),e));}#y(){this.#t.schedule({reconnect:()=>this.#c(),shouldReconnect:()=>this.#n.hasActiveSubscriptions()});}};var R=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 qd({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 od({heartbeat:new md});#t=new nd;#n=new p({deriveServerState:xi});constructor(e){this.#e=e.headers,this.#r=e.url;}async subscribe(e){let{change:r,entry:s}=this.#n.add(e,{matches:Ii(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(Hr(r.before,r.after)),this.#y(_r(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(Hr(r,s)),this.#y(_r(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({onConnectionLost:()=>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 xi(t){let e=new Set,r=new Set,s=new Set,n=false,i=false;for(let{subscription:o}of t)switch(o.topic){case "perps.tickers":o.instrumentId===void 0?n=true:r.add(o.instrumentId);break;case "perps.statistics":o.instrumentId===void 0?i=true:s.add(o.instrumentId);break;default:e.add(Mi(o));}if(n)e.add("tickers::all");else for(let o of r)e.add(`tickers::${o}`);if(i)e.add("statistics::all");else for(let o of s)e.add(`statistics::${o}`);return e}function Hr(t,e){return Array.from(e).filter(r=>!t.has(r))}function _r(t,e){return Array.from(t).filter(r=>!e.has(r))}function Mi(t){switch(t.topic){case "perps.trades":return `trades::${t.instrumentId}`;case "perps.bbo":return `bbo::${t.instrumentId}`;case "perps.book":return `book::${t.instrumentId}`;case "perps.candles":return `klines::${t.instrumentId}::${t.interval}`;case "perps.tickers":return t.instrumentId===void 0?"tickers::all":`tickers::${t.instrumentId}`;case "perps.statistics":return t.instrumentId===void 0?"statistics::all":`statistics::${t.instrumentId}`;default:invariant(false,`Unknown Perps topic: ${String(t)}`);}}function Ii(t){switch(t.topic){case "perps.trades":return e=>e.topic==="perps.trades"&&e.channel===`trades::${t.instrumentId}`;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 jr(t,e){return {...e,quote:r=>t.quote(e,r)}}function zr(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 Nr(t){return {quoteId:t.quoteId,rfqId:t.rfqId}}function Yr(t){return {quoteId:t.quoteId,rfqId:t.rfqId}}function Gr(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 Jr(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 Zr(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 Xr(t,e,r){return {decision:r,quote_id:e,rfq_id:t,type:"RFQ_CONFIRMATION_RESPONSE"}}var L=class{#e=new Map;#r;constructor(e){this.#r=e;}waitFor(e,r){let s=Fi(),n,i=setNonBlockingTimeout(()=>{this.remove(e,n),s.reject(new h$1(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 Fi(){let t,e;return {promise:new Promise((s,n)=>{t=s,e=n;}),reject:e,resolve:t}}var ts="0x0000000000000000000000000000000000000000000000000000000000000000";async function ss(t){let e=J(t.account),r={builder:ts,maker:e.maker,makerAmount:toBaseUnits(Li(t.orderSide,t.orderPrice,t.size)),metadata:ts,salt:Wi().toString(),side:Bi(t.orderSide),signatureType:e.signatureType,signer:e.signer,takerAmount:toBaseUnits(Di(t.orderSide,t.orderPrice,t.size)),timestamp:Math.floor(Date.now()/1e3).toString(),tokenId:t.tokenId},s;try{s=await t.signer.signTypedData(Rc({domain:rs(t),order:r}));}catch(n){throw l.fromError(n,"Could not sign the RFQ quote order.")}return {...r,signature:Sc({domain:rs(t),order:r,signature:s})}}function rs(t){return {chainId:t.chainId,exchange:t.exchange,protocolVersion:"3"}}function Li(t,e,r){return t===OrderSide.SELL?r.toString():((e*r+999999n)/1000000n).toString()}function Di(t,e,r){return t===OrderSide.SELL?(e*r/1000000n).toString():r.toString()}function Bi(t){return t===OrderSide.BUY?0:1}function Wi(){let t=new Uint8Array(8);return globalThis.crypto.getRandomValues(t),BigInt(`0x${Array.from(t,e=>e.toString(16).padStart(2,"0")).join("")}`)}var os=DecimalishSchema.transform(t=>us(t)).refine(t=>t<=BigInt(Number.MAX_SAFE_INTEGER),{message:"Value exceeds the temporary numeric wire limit."}),Hi=z.strictObject({price:os.refine(t=>t<1000000n,{message:"Price must be less than 1."}),size:os.optional(),source:z.enum(["collateral","inventory"]).default("collateral")});function as(t){return G(t,Hi)}async function cs(t){let e=t.response.price,r=t.response.size===void 0?ji(t.request.requestedSize,e):t.response.size,s=await ss({account:t.account,chainId:t.chainId,exchange:t.exchange,orderPrice:Ki(t.request,t.response.source,e),orderSide:Vi(t.response.source),signer:t.signer,size:r,tokenId:_i(t.request,t.response.source)});return {price:e,signedOrder:s,size:r}}function _i(t,e){return t.direction===RfqDirection.Buy?e==="collateral"?t.noPositionId:t.yesPositionId:e==="collateral"?t.yesPositionId:t.noPositionId}function Ki(t,e,r){return t.direction===RfqDirection.Buy&&e==="collateral"||t.direction===RfqDirection.Sell&&e==="inventory"?1000000n-r:r}function Vi(t){return t==="collateral"?OrderSide.BUY:OrderSide.SELL}function ji(t,e){let r=us(t.value);return t.unit===RfqRequestedSizeUnit.Shares?r:r*1000000n/e}function us(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 Yi=3e4,Gi=3e4,g=class{#e;#r;#s;#o;#i;#t;#n;#a;#d;#u;#c=false;constructor(e){this.#e=e.account,this.#r=e.chainId,this.#s=e.credentials,this.#o=e.exchange,this.#i=e.headers,this.#t=e.signer,this.#n=e.url;}async connect(){if(this.#c)throw new c("RFQ quoter manager has been shut down.");if(this.#a!==void 0){if(!this.#a.closed)return this.#a;this.#a=void 0;}if(this.#u!==void 0)return this.#u;let e=new Re({account:this.#e,chainId:this.#r,credentials:this.#s,exchange:this.#o,headers:this.#i,onClose:()=>this.#p(e),signer:this.#t,url:this.#n});this.#d=e;let r;return r=(async()=>{try{if(await e.connect(),this.#c)throw await e.close(),new c("RFQ quoter manager has been shut down.");return this.#a=e,e}catch(s){throw await e.close(),s}finally{this.#u===r&&(this.#u=void 0),this.#d===e&&(this.#d=void 0);}})(),this.#u=r,r}async shutdown(){this.#c=true;let e=this.#a,r=this.#d,s=this.#u;this.#a=void 0,this.#d=void 0,this.#u=void 0,await Promise.allSettled([e?.close(),r?.close(),s?.catch(()=>{})]).then(()=>{});}#p(e){this.#a===e&&(this.#a=void 0),this.#d===e&&(this.#d=void 0);}},Re=class{#e;#r;#s;#o;#i;#t;#n;#a;#d=new od;#u=pushable({objectMode:true});#c=new L(Gi);#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=Ji();this.#l=e;let r=setNonBlockingTimeout(()=>{e.reject(new c("RFQ quoter authentication timed out."));},Yi);try{await this.#d.connect({headers:this.#i,onConnectionLost:s=>this.#g(s),onError:()=>{},onMessage:s=>this.#P(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.");this.#S(e),this.#u.end(),await this.#d.close(),this.#t();}async#m(e){this.#p===void 0&&(this.#p=this.#y(e)),await this.#p;}async#y(e){this.#S(e),this.#u.end(e),await this.#d.close(),this.#t();}#S(e){this.#l?.reject(e),this.#c.rejectAll(e);}#b(){this.#d.send(Gr(this.#e,this.#s));}#P(e){if(this.#p!==void 0)return;let r=RfqQuoterInboundMessageSchema.safeParse(e);if(!r.success)return;let s=r.data;switch(s.type){case "auth":this.#R(s);return;case "quote_request":this.#u.push(jr(this,s));return;case "quote_ack":this.#c.resolve(D(s.rfqId),$r(s));return;case "quote_cancel_ack":this.#c.resolve(be(s.rfqId,s.quoteId),Nr(s));return;case "confirmation_request":this.#u.push(zr(this,s));return;case "confirmation_ack":this.#c.resolve(Pe(s.rfqId,s.quoteId),Yr(s));return;case "execution_update":this.#u.push(s);return;case "trade":this.#u.push(s);return;case "rfq_error":this.#q(s);return}}#R(e){if(e.success===true){this.#l?.resolve(void 0);return}this.#l?.reject(new c(`RFQ quoter authentication failed: ${e.error}`));}#g(e$1){this.#m(new e("RFQ quoter connection lost.",e$1));}#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 Me(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(be(e.rfqId,e.quoteId),new Oe(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(Pe(e.rfqId,e.quoteId),new Qe(e.message,{code:e.code,errorId:e.errorId,quoteId:e.quoteId,rfqId:e.rfqId}));}}async quote(e,r){let s=as(r),n=await cs({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(Jr(e,n)),await i}catch(o){throw this.#c.remove(D(e.rfqId),i),o}}async cancelQuote(e){let r=be(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(Zr(this.#e,e.rfqId,e.quoteId)),await s}catch(n){throw this.#c.remove(r,s),n}}async respondToConfirmation(e,r,s){let n=Pe(e,r),i=this.#c.waitFor(n,`Timed out waiting for RFQ confirmation acknowledgement for ${e}.`);try{return await this.#f(Xr(e,r,s)),await i}catch(o){throw this.#c.remove(n,i),o}}};function D(t){return `ACK_RFQ_QUOTE:${t}`}function be(t,e){return `ACK_RFQ_QUOTE_CANCEL:${t}:${e}`}function Pe(t,e){return `ACK_RFQ_CONFIRMATION_RESPONSE:${t}:${e}`}function Ji(){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 od({heartbeat:new kd});#i=new nd;#t=new p({deriveServerState:to});constructor(e){this.#e=e.headers,this.#r=e.url;}async subscribe(e){let{change:r,entry:s}=this.#t.add(e,{matches:io(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=Xi(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=eo(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({onConnectionLost:()=>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(ro(e));}#y(e){e.length!==0&&this.#o.send(so(e));}#S(){this.#i.schedule({reconnect:()=>this.#u(),shouldReconnect:()=>this.#t.hasActiveSubscriptions()});}};function Xi(t,e){return Array.from(e).flatMap(([r,s])=>t.has(r)?[]:[s])}function eo(t,e){return Array.from(t).flatMap(([r,s])=>e.has(r)?[]:[s])}function to(t){let e=new Map;for(let{subscription:r}of t)for(let s of no(r))e.has(s.key)||e.set(s.key,s);return e}function ro(t){return {action:"subscribe",subscriptions:t.map(({topic:e,type:r})=>({topic:e,type:r}))}}function so(t){return {action:"unsubscribe",subscriptions:t.map(({topic:e,type:r})=>({topic:e,type:r}))}}function no(t){switch(t.topic){case "comments":return (t.types??["comment_created"]).map(e=>B("comments",e));case "prices.crypto.binance":return [B("crypto_prices","update")];case "prices.crypto.chainlink":return [B("crypto_prices_chainlink","update")];case "prices.equity.pyth":return [B("equity_prices","update")];default:invariant(false,`Unknown RTDS topic: ${String(t)}`);}}function B(t,e){return {key:`${t}:${e}`,topic:t,type:e}}function io(t){switch(t.topic){case "comments":return e=>!(e.topic!=="comments"||t.types!==void 0&&t.types.length>0&&!t.types.includes(e.type)||(t.parentEntityId!==void 0||t.parentEntityType!==void 0)&&(!(e.type==="comment_created"||e.type==="comment_removed")||t.parentEntityId!==void 0&&e.payload.parentEntityID!==t.parentEntityId||t.parentEntityType!==void 0&&e.payload.parentEntityType!==t.parentEntityType));case "prices.crypto.binance":return e=>e.topic==="prices.crypto.binance"&&(t.symbols===void 0||t.symbols.length===0||t.symbols.includes(e.payload.symbol));case "prices.crypto.chainlink":return e=>e.topic==="prices.crypto.chainlink"&&(t.symbols===void 0||t.symbols.length===0||t.symbols.includes(e.payload.symbol));case "prices.equity.pyth":return e=>e.topic==="prices.equity.pyth"&&e.payload.symbol.toLowerCase()===t.symbol.toLowerCase()&&(t.types===void 0||t.types.length===0||t.types.includes(e.type));default:invariant(false,`Unknown RTDS topic: ${String(t)}`);}}var v=class{#e;#r;#s;#o=new od({heartbeat:new ld});#i=new nd;#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({onConnectionLost:()=>this.#l(),onError:()=>this.#f(),onMessage:e=>this.#p(e),onOpen:()=>this.#c(),headers:this.#e,url:this.#r})}#c(){this.#i.resetBackoff();}#p(e){let r=SportsResultEventSchema.safeParse(e);r.success&&this.#t.dispatch(r.data);}#l(){this.#t.hasActiveSubscriptions()&&this.#h();}#f(){}#h(){this.#i.schedule({reconnect:()=>this.#u(),shouldReconnect:()=>this.#t.hasActiveSubscriptions()});}};var W=class{#e;#r;get context(){return this.#e}get decorators(){return this.#r}get environment(){return this.context.environment}get clob(){return this.context.clob}get relayer(){return this.context.relayer}get rpc(){return this.context.rpc}get gamma(){return this.context.gamma}get data(){return this.context.data}get rfq(){return this.context.rfq}get perps(){return this.context.perps}get webSockets(){return this.context.webSockets}get supportsGasless(){return this.context.apiKey?.supportGasless??false}constructor(e){this.#e=e,this.#r=[];}async resolveClobHeaders(e){return this.context.apiKey?.isBuilderKey?this.context.apiKey.authorize(e):Promise.resolve({})}async resolveRelayerHeaders(e){return this.context.apiKey?.supportGasless?this.context.apiKey.authorize(e):Promise.resolve({})}rememberDecorator(e){this.#r.push(e);}},mo=z.object({key:ApiKeySchema,passphrase:z.string(),secret:z.string()}),fo=z.object({wallet:EvmAddressSchema,credentials:mo.optional(),nonce:z.number().int().nonnegative().optional()}).superRefine((t,e)=>{t.credentials!==void 0&&t.nonce!==void 0&&e.addIssue({code:"custom",message:"`credentials` and `nonce` are mutually exclusive.",path:["nonce"]});}).transform(t=>t.credentials!==void 0?{wallet:t.wallet,credentials:t.credentials}:t.nonce!==void 0?{wallet:t.wallet,nonce:t.nonce}:{wallet:t.wallet}),U=class extends W{constructor(e){super({apiKey:e.apiKey,environment:e.environment,data:new id({headers:e.environment.data.headers,root:e.environment.data.rest}),gamma:new id({headers:e.environment.gamma.headers,root:e.environment.gamma.rest}),clob:new id({headers:e.environment.clob.headers,root:e.environment.clob.rest,resolveHeaders:r=>this.resolveClobHeaders(r)}),relayer:new id({headers:e.environment.relayer.headers,root:e.environment.relayer.rest,resolveHeaders:r=>this.resolveRelayerHeaders(r)}),rfq:new id({headers:e.environment.rfq.headers,root:e.environment.rfq.rest}),perps:new id({headers:e.environment.perps.headers,root:e.environment.perps.rest}),rpc:new H({url:e.environment.rpc}),webSockets:{clobMarket:new S({headers:e.environment.clob.market.headers,url:e.environment.clob.market.ws}),sports:new v({headers:e.environment.sports.headers,url:e.environment.sports.ws}),rtds:new q({headers:e.environment.rtds.headers,url:e.environment.rtds.ws}),perpsSubscriptions:new b({headers:e.environment.perps.headers,url:e.environment.perps.ws})}});}isSecureClient(){return false}isPublicClient(){return true}async closeSubscriptions(){await Promise.all([this.webSockets.clobMarket.close(),this.webSockets.rtds.close(),this.webSockets.sports.close(),this.webSockets.perpsSubscriptions.close()]).then(()=>{});}extend(e){return this.rememberDecorator(e),Object.assign(this,e(this)),this}beginAuthentication(e,r){let s=G(e,fo);return Promise.resolve(async function*(){let n=Math.floor(Date.now()/1e3),i=s?.nonce??0,o=expectEvmAddress(yield wa()),A=expectEvmAddress(s.wallet),Ae=I$1(this.environment,o,A);if(s.credentials!==void 0){let Ce=this.#e(s.credentials,Ae,r);try{if((await $a(Ce)).includes(s.credentials.key))return Ce}catch(T){if(!(T instanceof f)||T.status!==401)throw T}}let ls=yield {kind:"signAuthMessage",payload:Ar({address:o,chainId:this.environment.chainId,nonce:i,timestamp:n})},ms=await Za(this,{address:o,nonce:i,signature:expectEvmSignature(ls),timestamp:n});return this.#e(ms,Ae,r)}.call(this))}#e(e,r,s){let n=new ve({account:r,apiKey:this.context.apiKey,credentials:e,environment:this.environment,signer:s});for(let i of this.decorators)n.extend(i);return n}},ve=class extends W{#e=false;get context(){return invariant(!this.#e,"This client has ended authentication and can no longer be used."),super.context}endAuthenticationLifecycle(){this.#e=true;}constructor(e){super({account:e.account,credentials:e.credentials,apiKey:e.apiKey,environment:e.environment,signer:e.signer,clob:new id({headers:e.environment.clob.headers,root:e.environment.clob.rest,resolveHeaders:r=>this.resolveClobHeaders(r)}),relayer:new id({headers:e.environment.relayer.headers,root:e.environment.relayer.rest,resolveHeaders:r=>this.resolveRelayerHeaders(r)}),rpc:new H({url:e.environment.rpc}),gamma:new id({headers:e.environment.gamma.headers,root:e.environment.gamma.rest}),data:new id({headers:e.environment.data.headers,root:e.environment.data.rest}),rfq:new id({headers:e.environment.rfq.headers,root:e.environment.rfq.rest}),perps:new id({headers:e.environment.perps.headers,root:e.environment.perps.rest}),secureClob:new id({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 P({credentials:e.credentials,headers:e.environment.clob.user.headers,url:e.environment.clob.user.ws}),rfqQuoter:new g({account:e.account,chainId:e.environment.chainId,credentials:e.credentials,exchange:e.environment.contracts.exchangeV3,headers:e.environment.rfq.headers,signer:e.signer,url:e.environment.rfq.ws}),sports:new v({headers:e.environment.sports.headers,url:e.environment.sports.ws}),rtds:new q({headers:e.environment.rtds.headers,url:e.environment.rtds.ws}),perpsSubscriptions:new b({headers:e.environment.perps.headers,url:e.environment.perps.ws}),perpsSession:new R({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}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 bb(this);}finally{this.endAuthenticationLifecycle(),await Promise.allSettled([e,r,s]).then(()=>{});}let o=new U({apiKey:n,environment:i});for(let A of this.decorators)o.extend(A);return o}async#r(e){try{let r=Math.floor(Date.now()/1e3);return {POLY_ADDRESS:this.account.signer,POLY_API_KEY:this.credentials.key,POLY_PASSPHRASE:this.credentials.passphrase,POLY_SIGNATURE:await xr(this.credentials.secret,r,e.method,e.path,e.body),POLY_TIMESTAMP:`${r}`}}catch(r){throw l.fromError(r,"Could not sign the L2-authenticated request")}}};function ps(t={}){return new U({environment:t.environment??le,apiKey:t.apiKey}).extend(Tr)}var ho=m$1(j,g$1,f,l,h$1,i,c,b$1,a),yo=m$1(a);async function So(t){let e=ps({environment:t.environment,apiKey:t.apiKey}),r=await bo(e,t),s=await e.beginAuthentication({wallet:r,credentials:t.credentials,nonce:t.nonce},t.signer).then(va(t.signer));if(s.account.walletType===WalletType.EOA||await Aa(s,{wallet:s.account.wallet,type:s.account.walletType}))return s;if(s.account.walletType===WalletType.DEPOSIT_WALLET)return await Po(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 bo(t,e){if(e.wallet!==void 0)return e.wallet;let r=expectEvmAddress(await e.signer.getAddress()),s=K(r,t.environment.walletDerivation);return await Aa(t,{wallet:s,type:WalletType.DEPOSIT_WALLET})?s:L$1(r,t.environment.walletDerivation)}async function Po(t){let e=L$1(t.account.signer,t.environment.walletDerivation);if(!isSameEvmAddress(t.account.wallet,e))throw new a(`Wallet ${t.account.wallet} does not match the expected Deposit Wallet ${e} for this signer, nor a deployed wallet address.`);await(await Da(t)).wait();}
|
|
2
|
-
export{
|
|
1
|
+
import {N,X,V,T,ra,pa,pe as pe$1,ne as ne$1,le as le$1,je,he as he$1,fe as fe$1,xc,vc,tc,ob,na,Jc,Lc,Xc,Ub,Sb,Qb,Ob,Mb,Kb,Ib,Gb,Eb,sb,qb,rc,jc,hc,fc,Ze,Hf,wf,uf,of,Ff,Df,Bf,zf,zc,sf,qf,Hc,Fc,Dc,Bc,pc,nc,lc as lc$1,ce as ce$1,$d,_d,be as be$1,la,ja,ha,fa,da,ba,ff,xf,R as R$1,P as P$1,Vc,Tc,Rc,Pc,nd,ad,$c,vd,td,rd,pd,cc,_b,Xe,Se,Je,Lf,Ua,Qa,Ya,va,Aa,K,L as L$1,Da,Sd,Qd,Od,Kd,Id,Gd,Ud,Md,Nc,Yb,Wb,H,wd,G,wa,I,eb,cb,Cd,Ad,Bd,yd,zd,xd,gb,Ed,_e,af,cf,J,bd,cd}from'./chunk-FA3ZDOJN.js';export{Ta as ApproveErc1155ForAllError,Pa as ApproveErc20Error,Sc as CancelAllError,Uc as CancelMarketOrdersError,Oc as CancelOrderError,Qc as CancelOrdersError,dc as CollateralReturnKnownOperationKind,C as CombinatorialPrepareConditionCallError,sa as ComboActivityType,qe as ComboPositionOutcome,de as ComboPositionSort,re as ComboPositionStatus,sd as CreateLimitOrderError,od as CreateMarketOrderError,q as CtfRedeemPositionsCallError,Yd as DepositToPerpsError,oe as DownloadAccountingSnapshotError,W as DropNotificationsError,b as Erc20ApprovalCallError,m as Erc20TransferCallError,Wc as EstimateMarketPriceError,bc as ExecuteCollateralReturnPlanError,M as FetchClosedOnlyModeError,gc as FetchCommentsByIdError,mc as FetchEventError,qc as FetchEventLiveVolumeError,oc as FetchEventTagsError,Pb as FetchLastTradePriceError,Rb as FetchLastTradePricesError,Ec as FetchMarketError,Gc as FetchMarketTagsError,pb as FetchMidpointError,rb as FetchMidpointsError,U as FetchNotificationsError,Hb as FetchOrderBookError,Jb as FetchOrderBooksError,Q as FetchOrderError,aa as FetchOrderScoringError,ca as FetchOrdersScoringError,Ld as FetchPerpsBookError,Td as FetchPerpsFeesError,Fd as FetchPerpsInstrumentsError,Hd as FetchPerpsTickerError,Jd as FetchPerpsTickersError,ke as FetchPortfolioValueError,Db as FetchPriceError,Tb as FetchPriceHistoryError,Fb as FetchPricesError,Ye as FetchPublicProfileError,Ef as FetchRelatedTagResourcesError,Cf as FetchRelatedTagsError,ka as FetchRewardPercentagesError,rf as FetchSeriesError,vf as FetchSportsMarketTypesError,Lb as FetchSpreadError,Nb as FetchSpreadsError,Af as FetchTagError,ga as FetchTotalEarningsForUserForDayError,me as FetchTradedMarketCountError,S as ListAccountTradesError,oa as ListActivityError,sc as ListBuilderLeaderboardError,nb as ListBuilderTradesError,uc as ListBuilderVolumeError,ge as ListClosedPositionsError,qa as ListComboActivityError,Cc as ListComboMarketsError,ie as ListComboPositionsError,ic as ListCommentsByUserAddressError,ec as ListCommentsError,Vb as ListCurrentRewardsError,kc as ListEventsError,Ic as ListMarketHoldersError,Mc as ListMarketPositionsError,Xb as ListMarketRewardsError,Ac as ListMarketsError,Kc as ListOpenInterestError,O as ListOpenOrdersError,Nd as ListPerpsCandlesError,Pd as ListPerpsFundingHistoryError,Rd as ListPerpsTradesError,ee as ListPositionsError,pf as ListSeriesError,tf as ListSportsError,yf as ListTagsError,Gf as ListTeamsError,wc as ListTraderLeaderboardError,ma as ListTradesError,ia as ListUserEarningsAndMarketsConfigError,ea as ListUserEarningsForDayError,a as MAX_UINT256,t as MergePositionsCallError,Ne as MergePositionsError,y as MergeV2CallError,Vd as OpenPerpsSessionError,ef as OpenRfqSessionError,o as PerpsDepositCallError,ud as PlaceLimitOrderError,qd as PlaceMarketOrderError,Zb as PlanCollateralReturnError,Zc as PostOrderError,_c as PostOrdersError,We as RedeemPositionsError,A as RedeemV2CallError,Wd as RevokePerpsCredentialsError,bf as RfqCancelQuoteError,af as RfqCancelQuoteRejectedError,gf as RfqConfirmationDecision,df as RfqConfirmationError,cf as RfqConfirmationRejectedError,hf as RfqDirection,if as RfqExecutionStatus,jf as RfqKnownErrorCode,$e as RfqQuoteError,_e as RfqQuoteRejectedError,kf as RfqRequestedSizeUnit,lf as RfqSide,nf as SearchError,mf as SearchSort,Xa as SetupTradingApprovalsError,r as SplitPositionCallError,Ee as SplitPositionError,w as SplitV2CallError,Kf as TransferErc20Error,Dd as UpdatePerpsLeverageError,md as WaitForOrderFillSettlementError,ta as WaitForTransactionError,Zd as WithdrawFromPerpsError,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,ua as expectTransactionHandle,u as mergePositionsCall,z as mergeV2Call,p as perpsDepositCall,B as redeemV2Call,s as splitPositionCall,x as splitV2Call}from'./chunk-FA3ZDOJN.js';import {a,m as m$1,j,g as g$1,f as f$1,l,h,i,c,b as b$1,e}from'./chunk-TYJAXA3Y.js';export{j as CancelledSigningError,e as ConnectionLostError,k as InsufficientLiquidityError,g as RateLimitError,f as RequestRejectedError,l as SigningError,h as TimeoutError,i as TransactionFailedError,c as TransportError,b as UnexpectedResponseError,a as UserInputError,d as WebSocketKnownCloseCode,m as makeErrorGuard}from'./chunk-TYJAXA3Y.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,PerpsKnownWithdrawalStatus,PerpsOrderStatus,PerpsSide,PerpsTimeInForce}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 {RfqQuoterInboundMessageSchema,RfqConfirmationDecision,RfqRequestedSizeUnit,RfqDirection}from'@polymarket/bindings/combos';var vi=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 Ai(t){return new se(t)}function Ci(t){return new ne(t)}var se=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 l.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 vi.parse(await r.json())}},ne=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 kr(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:fe$1.bind(null,t),listClosedPositions:he$1.bind(null,t),listComboPositions:je.bind(null,t),fetchPortfolioValue:le$1.bind(null,t),fetchTradedMarketCount:ne$1.bind(null,t),downloadAccountingSnapshot:pe$1.bind(null,t),listMarketPositions:Nc.bind(null,t),listActivity:pa.bind(null,t),listComboActivity:ra.bind(null,t)}}function f(t,e={}){return {...e,user:e.user??t.account.wallet}}function ie(t){let e=Ei(t);return t.isPublicClient()?e:{...e,listPositions:r=>fe$1(t,f(t,r)),listClosedPositions:r=>he$1(t,f(t,r)),listComboPositions:r=>je(t,f(t,r)),fetchPortfolioValue:r=>le$1(t,f(t,r)),fetchTradedMarketCount:r=>ne$1(t,f(t,r)),downloadAccountingSnapshot:r=>pe$1(t,f(t,r)),listActivity:r=>pa(t,f(t,r)),listComboActivity:r=>ra(t,f(t,r)),listAccountTrades:T.bind(null,t),fetchNotifications:V.bind(null,t),dropNotifications:X.bind(null,t),fetchClosedOnlyMode:N.bind(null,t)}}function oe(t){return {listBuilderTrades:ob.bind(null,t),listBuilderLeaderboard:tc.bind(null,t),fetchBuilderVolume:vc.bind(null,t),listTraderLeaderboard:xc.bind(null,t)}}function ae(t){return {fetchEventLiveVolume:rc.bind(null,t),fetchMidpoint:qb.bind(null,t),fetchMidpoints:sb.bind(null,t),fetchPrice:Eb.bind(null,t),fetchPrices:Gb.bind(null,t),fetchOrderBook:Ib.bind(null,t),fetchOrderBooks:Kb.bind(null,t),fetchSpread:Mb.bind(null,t),fetchSpreads:Ob.bind(null,t),fetchLastTradePrice:Qb.bind(null,t),fetchLastTradePrices:Sb.bind(null,t),fetchPriceHistory:Ub.bind(null,t),estimateMarketPrice:Xc.bind(null,t),listOpenInterest:Lc.bind(null,t),listMarketHolders:Jc.bind(null,t),listTrades:na.bind(null,t)}}function ce(t){return {listEvents:lc$1.bind(null,t),fetchEvent:nc.bind(null,t),fetchEventTags:pc.bind(null,t),listMarkets:Bc.bind(null,t),listComboMarkets:Dc.bind(null,t),fetchMarket:Fc.bind(null,t),fetchMarketTags:Hc.bind(null,t),listSeries:qf.bind(null,t),fetchSeries:sf.bind(null,t),listMarketClarifications:zc.bind(null,t),listTags:zf.bind(null,t),fetchTag:Bf.bind(null,t),fetchRelatedTags:Df.bind(null,t),fetchRelatedTagResources:Ff.bind(null,t),search:of.bind(null,t),listSports:uf.bind(null,t),fetchSportsMarketTypes:wf.bind(null,t),listTeams:Hf.bind(null,t),fetchPublicProfile:Ze.bind(null,t),listComments:fc.bind(null,t),fetchCommentsById:hc.bind(null,t),listCommentsByUserAddress:jc.bind(null,t)}}function ue(t){let e={fetchPerpsBook:r=>Md(t,r),fetchPerpsFees:()=>Ud(t),fetchPerpsInstruments:r=>Gd(t,r),fetchPerpsTicker:r=>Id(t,r),fetchPerpsTickers:r=>Kd(t,r),listPerpsCandles:r=>Od(t,r),listPerpsFundingHistory:r=>Qd(t,r),listPerpsTrades:r=>Sd(t,r)};return t.isSecureClient()?{...e,depositToPerps:r=>be$1(t,r),openPerpsSession:r=>_d(t,r),revokePerpsCredentials:r=>$d(t,r),withdrawFromPerps:r=>ce$1(t,r)}:e}function ki(t){return {listCurrentRewards:Wb.bind(null,t),listMarketRewards:Yb.bind(null,t)}}function de(t){let e=ki(t);return t.isPublicClient()?e:{...e,fetchOrderScoring:ba.bind(null,t),fetchOrdersScoring:da.bind(null,t),listUserEarningsForDay:fa.bind(null,t),fetchTotalEarningsForUserForDay:ha.bind(null,t),listUserEarningsAndMarketsConfig:ja.bind(null,t),fetchRewardPercentages:la.bind(null,t)}}function Tr(t){return {openRfqSession(){return ff(t)}}}function pe(t){return t.isSecureClient()?{subscribe(e){return xf(t,e)}}:{subscribe(e){return xf(t,e)}}}function wr(t){return {createMarketOrder:pd.bind(null,t),placeMarketOrder:rd.bind(null,t),createLimitOrder:td.bind(null,t),placeLimitOrder:vd.bind(null,t),postOrder:$c(t),postOrders:ad(t),waitForOrderFillSettlement:nd.bind(null,t),cancelOrder:Pc.bind(null,t),cancelOrders:Rc.bind(null,t),cancelAll:Tc.bind(null,t),cancelMarketOrders:Vc.bind(null,t),listOpenOrders:P$1.bind(null,t),fetchOrder:R$1.bind(null,t)}}function xr(t){return {setupTradingApprovals:Ya.bind(null,t),approveErc20:Qa.bind(null,t),approveErc1155ForAll:Ua.bind(null,t),transferErc20:Lf.bind(null,t),splitPosition:Je.bind(null,t),mergePositions:Se.bind(null,t),redeemPositions:Xe.bind(null,t),planCollateralReturn:_b.bind(null,t),executeCollateralReturnPlan:cc.bind(null,t)}}function Mr(t){return t.isSecureClient()?{...ie(t),...oe(t),...ae(t),...ce(t),...ue(t),...de(t),...Tr(t),...pe(t),...wr(t),...xr(t)}:{...ie(t),...oe(t),...ae(t),...ce(t),...ue(t),...de(t),...pe(t)}}var le={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"},combos:{rest:"https://combos-rfq-api.polymarket.com",ws:"wss://combos-rfq-gateway-quoter.polymarket.com/ws/rfq",collateralReturn:{rest:"https://combos-rfq-collateral-return.polymarket.com"}},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 Ti(t,e=le){return {...e,...t,walletDerivation:{...e.walletDerivation,...t.walletDerivation},contracts:{...e.contracts,...t.contracts},clob:{...k(e.clob,t.clob),market:O(e.clob.market,t.clob?.market),user:O(e.clob.user,t.clob?.user)},relayer:k(e.relayer,t.relayer),gamma:k(e.gamma,t.gamma),data:k(e.data,t.data),combos:{...Ir(e.combos,t.combos),collateralReturn:k(e.combos.collateralReturn,t.combos?.collateralReturn)},perps:Ir(e.perps,t.perps),rtds:O(e.rtds,t.rtds),sports:O(e.sports,t.sports)}}function k(t,e){return {...t,...e,headers:me(t.headers,e?.headers)}}function O(t,e){return {...t,...e,headers:me(t.headers,e?.headers)}}function Ir(t,e){return {...t,...e,headers:me(t.headers,e?.headers)}}function me(t,e){if(!(t===void 0&&e===void 0))return {...t,...e}}var lc=Ti({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 Or(t,e,r,s,n){let i=`${e}${r}${s}`;n!==void 0&&(i+=n);let o=await globalThis.crypto.subtle.importKey("raw",wi(t),{name:"HMAC",hash:"SHA-256"},false,["sign"]),A=await globalThis.crypto.subtle.sign("HMAC",o,new TextEncoder().encode(i));return Mi(xi(A))}function wi(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 xi(t){let e=new Uint8Array(t),r="";for(let s of e)r+=String.fromCharCode(s);return btoa(r)}function Mi(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 he(t,e,r){let s=F(r.assetsIds,e.assetsIds),n=F(e.assetsIds,r.assetsIds);s.length>0&&t(Fr(s,r.customFeatureEnabled));let i=r.assetsIds[0];s.length===0&&e.customFeatureEnabled!==r.customFeatureEnabled&&i!==void 0&&t(Fr([i],r.customFeatureEnabled)),n.length>0&&t(Oi(n));}function fe(t,e,r){if(r.includeAllMarkets){!e.includeAllMarkets&&e.markets.length>0&&t(Dr(e.markets));return}if(e.includeAllMarkets){r.markets.length>0&&t(Lr(r.markets));return}let s=F(r.markets,e.markets),n=F(e.markets,r.markets);s.length>0&&t(Lr(s)),n.length>0&&t(Dr(n));}function Br(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 Wr(t){let e=false,r=new Set;for(let{subscription:s}of t){if(Kr(s)){e=true;continue}for(let n of s.markets??[])r.add(n);}return {includeAllMarkets:e,markets:e?[]:Array.from(r)}}function Ur(t){return {assets_ids:t.assetsIds,custom_feature_enabled:t.customFeatureEnabled,type:"market"}}function Fr(t,e){return {assets_ids:t,custom_feature_enabled:e,operation:"subscribe"}}function Oi(t){return {assets_ids:t,operation:"unsubscribe"}}function Qr(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 Lr(t){return {markets:t,operation:"subscribe"}}function Dr(t){return {markets:t,operation:"unsubscribe"}}function Hr(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 _r(t){if(Kr(t))return ()=>true;let e=new Set((t.markets??[]).map(r=>r.toLowerCase()));return r=>e.has(r.payload.market.toLowerCase())}function Kr(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 Cd({heartbeat:new xd});#i=new Bd;#t=new p({deriveServerState:Br});constructor(e){this.#e=e.headers,this.#r=e.url;}async subscribe(e){let{change:r,entry:s}=this.#t.add(e,{matches:Hr(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&&he(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}he(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({onConnectionLost:()=>this.#l(),onError:()=>this.#h(),onMessage:e=>this.#p(e),onOpen:()=>this.#c(),headers:this.#e,url:this.#r})}#c(){this.#i.resetBackoff(),this.#f();}#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();}#h(){}#f(){this.#o.send(Ur(this.#t.serverState()));}#m(){this.#i.schedule({reconnect:()=>this.#u(),shouldReconnect:()=>this.#t.hasActiveSubscriptions()});}};var R=class{#e;#r;#s;#o;#i=new Cd({heartbeat:new xd});#t=new Bd;#n=new p({deriveServerState:Wr});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:_r(e)});return await this.#a(s,r),m(s.subscriber.queue,()=>this.#d(s))}async#a(e,r){let{before:s,after:n}=r;try{(await this.#c()).reusedOpenSocket&&fe(o=>this.#i.send(o),s,n);}catch(i){throw await this.#d(e),i}}async#d(e){let{before:r,after:s}=this.#n.remove(e);if(!this.#n.hasActiveSubscriptions()){await this.close();return}fe(n=>this.#i.send(n),r,s);}async close(){this.#o===void 0&&(this.#o=this.#u().finally(()=>{this.#o=void 0;})),await this.#o;}async#u(){this.#t.stop(),this.#n.endAll(),await this.#i.close();}#c(){return this.#i.connect({onConnectionLost:()=>this.#h(),onError:()=>this.#f(),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);}}#h(){this.#n.hasActiveSubscriptions()&&this.#y();}#f(){}#m(e){this.#i.send(Qr(this.#n.serverState(),e));}#y(){this.#t.schedule({reconnect:()=>this.#c(),shouldReconnect:()=>this.#n.hasActiveSubscriptions()});}};var P=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 Ed({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 Cd({heartbeat:new Ad});#t=new Bd;#n=new p({deriveServerState:Bi});constructor(e){this.#e=e.headers,this.#r=e.url;}async subscribe(e){let{change:r,entry:s}=this.#n.add(e,{matches:Ui(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(Vr(r.before,r.after)),this.#y(jr(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(Vr(r,s)),this.#y(jr(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({onConnectionLost:()=>this.#h(),onError:()=>this.#f(),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);}#h(){this.#n.hasActiveSubscriptions()&&this.#b();}#f(){}#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 Bi(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(Wi(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 Vr(t,e){return Array.from(e).filter(r=>!t.has(r))}function jr(t,e){return Array.from(t).filter(r=>!e.has(r))}function Wi(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 Ui(t){switch(t.topic){case "perps.trades":return e=>e.topic==="perps.trades"&&e.channel===`trades::${t.instrumentId}`;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 Nr(t,e){return {...e,quote:r=>t.quote(e,r)}}function Yr(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 Gr(t){return {quoteId:t.quoteId,rfqId:t.rfqId}}function Jr(t){return {quoteId:t.quoteId,rfqId:t.rfqId}}function Zr(t){return {quoteId:t.quoteId,rfqId:t.rfqId}}function Xr(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 es(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 ts(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 rs(t,e,r){return {decision:r,quote_id:e,rfq_id:t,type:"RFQ_CONFIRMATION_RESPONSE"}}var L=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 h(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 ns="0x0000000000000000000000000000000000000000000000000000000000000000";async function os(t){let e=J(t.account),r={builder:ns,maker:e.maker,makerAmount:toBaseUnits(_i(t.orderSide,t.orderPrice,t.size)),metadata:ns,salt:ji().toString(),side:Vi(t.orderSide),signatureType:e.signatureType,signer:e.signer,takerAmount:toBaseUnits(Ki(t.orderSide,t.orderPrice,t.size)),timestamp:Math.floor(Date.now()/1e3).toString(),tokenId:t.tokenId},s;try{s=await t.signer.signTypedData(bd({domain:is(t),order:r}));}catch(n){throw l.fromError(n,"Could not sign the RFQ quote order.")}return {...r,signature:cd({domain:is(t),order:r,signature:s})}}function is(t){return {chainId:t.chainId,exchange:t.exchange,protocolVersion:"3"}}function _i(t,e,r){return t===OrderSide.SELL?r.toString():((e*r+999999n)/1000000n).toString()}function Ki(t,e,r){return t===OrderSide.SELL?(e*r/1000000n).toString():r.toString()}function Vi(t){return t===OrderSide.BUY?0:1}function ji(){let t=new Uint8Array(8);return globalThis.crypto.getRandomValues(t),BigInt(`0x${Array.from(t,e=>e.toString(16).padStart(2,"0")).join("")}`)}var us=DecimalishSchema.transform(t=>ls(t)).refine(t=>t<=BigInt(Number.MAX_SAFE_INTEGER),{message:"Value exceeds the temporary numeric wire limit."}),Ni=z.strictObject({price:us.refine(t=>t<1000000n,{message:"Price must be less than 1."}),size:us.optional(),source:z.enum(["collateral","inventory"]).default("collateral")});function ds(t){return G(t,Ni)}async function ps(t){let e=t.response.price,r=t.response.size===void 0?Zi(t.request.requestedSize,e):t.response.size,s=await os({account:t.account,chainId:t.chainId,exchange:t.exchange,orderPrice:Gi(t.request,t.response.source,e),orderSide:Ji(t.response.source),signer:t.signer,size:r,tokenId:Yi(t.request,t.response.source)});return {price:e,signedOrder:s,size:r}}function Yi(t,e){return t.direction===RfqDirection.Buy?e==="collateral"?t.noPositionId:t.yesPositionId:e==="collateral"?t.yesPositionId:t.noPositionId}function Gi(t,e,r){return t.direction===RfqDirection.Buy&&e==="collateral"||t.direction===RfqDirection.Sell&&e==="inventory"?1000000n-r:r}function Ji(t){return t==="collateral"?OrderSide.BUY:OrderSide.SELL}function Zi(t,e){let r=ls(t.value);return t.unit===RfqRequestedSizeUnit.Shares?r:r*1000000n/e}function ls(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 ro=3e4,so=3e4,g=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 Pe({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);}},Pe=class{#e;#r;#s;#o;#i;#t;#n;#a;#d=new Cd;#u=pushable({objectMode:true});#c=new L(so);#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=no();this.#l=e;let r=setNonBlockingTimeout(()=>{e.reject(new c("RFQ quoter authentication timed out."));},ro);try{await this.#d.connect({headers:this.#i,onConnectionLost:s=>this.#g(s),onError:()=>{},onMessage:s=>this.#R(s),onOpen:()=>this.#b(),url:this.#a}),await e.promise;}finally{clearTimeout(r),this.#l=void 0;}}async#h(e){if(!this.#d.send(e))throw new c("RFQ quoter websocket is not open.")}async close(){this.#p===void 0&&(this.#p=this.#f()),await this.#p;}[Symbol.asyncIterator](){return this.#u[Symbol.asyncIterator]()}async#f(){let e=new c("RFQ quoter websocket closed.");this.#S(e),this.#u.end(),await this.#d.close(),this.#t();}async#m(e){this.#p===void 0&&(this.#p=this.#y(e)),await this.#p;}async#y(e){this.#S(e),this.#u.end(e),await this.#d.close(),this.#t();}#S(e){this.#l?.reject(e),this.#c.rejectAll(e);}#b(){this.#d.send(Xr(this.#e,this.#s));}#R(e){if(this.#p!==void 0)return;let r=RfqQuoterInboundMessageSchema.safeParse(e);if(!r.success)return;let s=r.data;switch(s.type){case "auth":this.#P(s);return;case "quote_request":this.#u.push(Nr(this,s));return;case "quote_ack":this.#c.resolve(D(s.rfqId),Gr(s));return;case "quote_cancel_ack":this.#c.resolve(be(s.rfqId,s.quoteId),Jr(s));return;case "confirmation_request":this.#u.push(Yr(this,s));return;case "confirmation_ack":this.#c.resolve(Re(s.rfqId,s.quoteId),Zr(s));return;case "execution_update":this.#u.push(s);return;case "trade":this.#u.push(s);return;case "rfq_error":this.#q(s);return}}#P(e){if(e.success===true){this.#l?.resolve(void 0);return}this.#l?.reject(new c(`RFQ quoter authentication failed: ${e.error}`));}#g(e$1){this.#m(new e("RFQ quoter connection lost.",e$1));}#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 _e(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(be(e.rfqId,e.quoteId),new af(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(Re(e.rfqId,e.quoteId),new cf(e.message,{code:e.code,errorId:e.errorId,quoteId:e.quoteId,rfqId:e.rfqId}));}}async quote(e,r){let s=ds(r),n=await ps({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.#h(es(e,n)),await i}catch(o){throw this.#c.remove(D(e.rfqId),i),o}}async cancelQuote(e){let r=be(e.rfqId,e.quoteId),s=this.#c.waitFor(r,`Timed out waiting for RFQ quote cancellation acknowledgement for ${e.rfqId}.`);try{return await this.#h(ts(this.#e,e.rfqId,e.quoteId)),await s}catch(n){throw this.#c.remove(r,s),n}}async respondToConfirmation(e,r,s){let n=Re(e,r),i=this.#c.waitFor(n,`Timed out waiting for RFQ confirmation acknowledgement for ${e}.`);try{return await this.#h(rs(e,r,s)),await i}catch(o){throw this.#c.remove(n,i),o}}};function D(t){return `ACK_RFQ_QUOTE:${t}`}function be(t,e){return `ACK_RFQ_QUOTE_CANCEL:${t}:${e}`}function Re(t,e){return `ACK_RFQ_CONFIRMATION_RESPONSE:${t}:${e}`}function no(){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 Cd({heartbeat:new yd});#i=new Bd;#t=new p({deriveServerState:co});constructor(e){this.#e=e.headers,this.#r=e.url;}async subscribe(e){let{change:r,entry:s}=this.#t.add(e,{matches:mo(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=oo(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=ao(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({onConnectionLost:()=>this.#l(),onError:()=>this.#h(),onMessage:e=>this.#p(e),onOpen:()=>this.#c(),headers:this.#e,url:this.#r})}#c(){this.#i.resetBackoff(),this.#f();}#p(e){let r=RealtimeEventSchema.safeParse(e);r.success&&this.#t.dispatch(r.data);}#l(){this.#t.hasActiveSubscriptions()&&this.#S();}#h(){}#f(){this.#m(Array.from(this.#t.serverState().values()));}#m(e){e.length!==0&&this.#o.send(uo(e));}#y(e){e.length!==0&&this.#o.send(po(e));}#S(){this.#i.schedule({reconnect:()=>this.#u(),shouldReconnect:()=>this.#t.hasActiveSubscriptions()});}};function oo(t,e){return Array.from(e).flatMap(([r,s])=>t.has(r)?[]:[s])}function ao(t,e){return Array.from(t).flatMap(([r,s])=>e.has(r)?[]:[s])}function co(t){let e=new Map;for(let{subscription:r}of t)for(let s of lo(r))e.has(s.key)||e.set(s.key,s);return e}function uo(t){return {action:"subscribe",subscriptions:t.map(({topic:e,type:r})=>({topic:e,type:r}))}}function po(t){return {action:"unsubscribe",subscriptions:t.map(({topic:e,type:r})=>({topic:e,type:r}))}}function lo(t){switch(t.topic){case "comments":return (t.types??["comment_created"]).map(e=>B("comments",e));case "prices.crypto.binance":return [B("crypto_prices","update")];case "prices.crypto.chainlink":return [B("crypto_prices_chainlink","update")];case "prices.equity.pyth":return [B("equity_prices","update")];default:invariant(false,`Unknown RTDS topic: ${String(t)}`);}}function B(t,e){return {key:`${t}:${e}`,topic:t,type:e}}function mo(t){switch(t.topic){case "comments":return e=>!(e.topic!=="comments"||t.types!==void 0&&t.types.length>0&&!t.types.includes(e.type)||(t.parentEntityId!==void 0||t.parentEntityType!==void 0)&&(!(e.type==="comment_created"||e.type==="comment_removed")||t.parentEntityId!==void 0&&e.payload.parentEntityID!==t.parentEntityId||t.parentEntityType!==void 0&&e.payload.parentEntityType!==t.parentEntityType));case "prices.crypto.binance":return e=>e.topic==="prices.crypto.binance"&&(t.symbols===void 0||t.symbols.length===0||t.symbols.includes(e.payload.symbol));case "prices.crypto.chainlink":return e=>e.topic==="prices.crypto.chainlink"&&(t.symbols===void 0||t.symbols.length===0||t.symbols.includes(e.payload.symbol));case "prices.equity.pyth":return e=>e.topic==="prices.equity.pyth"&&e.payload.symbol.toLowerCase()===t.symbol.toLowerCase()&&(t.types===void 0||t.types.length===0||t.types.includes(e.type));default:invariant(false,`Unknown RTDS topic: ${String(t)}`);}}var v=class{#e;#r;#s;#o=new Cd({heartbeat:new zd});#i=new Bd;#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({onConnectionLost:()=>this.#l(),onError:()=>this.#h(),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.#f();}#h(){}#f(){this.#i.schedule({reconnect:()=>this.#u(),shouldReconnect:()=>this.#t.hasActiveSubscriptions()});}};var W=class{#e;#r;get context(){return this.#e}get decorators(){return this.#r}get environment(){return this.context.environment}get clob(){return this.context.clob}get relayer(){return this.context.relayer}get rpc(){return this.context.rpc}get gamma(){return this.context.gamma}get data(){return this.context.data}get rfq(){return this.context.rfq}get perps(){return this.context.perps}get webSockets(){return this.context.webSockets}get supportsGasless(){return this.context.apiKey?.supportGasless??false}constructor(e){this.#e=e,this.#r=[];}async resolveClobHeaders(e){return this.context.apiKey?.isBuilderKey?this.context.apiKey.authorize(e):Promise.resolve({})}async resolveRelayerHeaders(e){return this.context.apiKey?.supportGasless?this.context.apiKey.authorize(e):Promise.resolve({})}rememberDecorator(e){this.#r.push(e);}},Po=z.object({key:ApiKeySchema,passphrase:z.string(),secret:z.string()}),go=z.object({wallet:EvmAddressSchema,credentials:Po.optional(),nonce:z.number().int().nonnegative().optional()}).superRefine((t,e)=>{t.credentials!==void 0&&t.nonce!==void 0&&e.addIssue({code:"custom",message:"`credentials` and `nonce` are mutually exclusive.",path:["nonce"]});}).transform(t=>t.credentials!==void 0?{wallet:t.wallet,credentials:t.credentials}:t.nonce!==void 0?{wallet:t.wallet,nonce:t.nonce}:{wallet:t.wallet}),U=class extends W{constructor(e){super({apiKey:e.apiKey,environment:e.environment,data:new wd({headers:e.environment.data.headers,root:e.environment.data.rest}),gamma:new wd({headers:e.environment.gamma.headers,root:e.environment.gamma.rest}),clob:new wd({headers:e.environment.clob.headers,root:e.environment.clob.rest,resolveHeaders:r=>this.resolveClobHeaders(r)}),relayer:new wd({headers:e.environment.relayer.headers,root:e.environment.relayer.rest,resolveHeaders:r=>this.resolveRelayerHeaders(r)}),rfq:new wd({headers:e.environment.combos.headers,root:e.environment.combos.rest}),perps:new wd({headers:e.environment.perps.headers,root:e.environment.perps.rest}),rpc:new H({url:e.environment.rpc}),webSockets:{clobMarket:new S({headers:e.environment.clob.market.headers,url:e.environment.clob.market.ws}),sports:new v({headers:e.environment.sports.headers,url:e.environment.sports.ws}),rtds:new q({headers:e.environment.rtds.headers,url:e.environment.rtds.ws}),perpsSubscriptions:new b({headers:e.environment.perps.headers,url:e.environment.perps.ws})}});}isSecureClient(){return false}isPublicClient(){return true}async closeSubscriptions(){await Promise.all([this.webSockets.clobMarket.close(),this.webSockets.rtds.close(),this.webSockets.sports.close(),this.webSockets.perpsSubscriptions.close()]).then(()=>{});}extend(e){return this.rememberDecorator(e),Object.assign(this,e(this)),this}beginAuthentication(e,r){let s=G(e,go);return Promise.resolve(async function*(){let n=Math.floor(Date.now()/1e3),i=s?.nonce??0,o=expectEvmAddress(yield wa()),A=expectEvmAddress(s.wallet),Ae=I(this.environment,o,A);if(s.credentials!==void 0){let Ce=this.#e(s.credentials,Ae,r);try{if((await eb(Ce)).includes(s.credentials.key))return Ce}catch(w){if(!(w instanceof f$1)||w.status!==401)throw w}}let fs=yield {kind:"signAuthMessage",payload:kr({address:o,chainId:this.environment.chainId,nonce:i,timestamp:n})},ys=await cb(this,{address:o,nonce:i,signature:expectEvmSignature(fs),timestamp:n});return this.#e(ys,Ae,r)}.call(this))}#e(e,r,s){let n=new ve({account:r,apiKey:this.context.apiKey,credentials:e,environment:this.environment,signer:s});for(let i of this.decorators)n.extend(i);return n}},ve=class extends W{#e=false;get context(){return invariant(!this.#e,"This client has ended authentication and can no longer be used."),super.context}endAuthenticationLifecycle(){this.#e=true;}constructor(e){super({account:e.account,credentials:e.credentials,apiKey:e.apiKey,environment:e.environment,signer:e.signer,clob:new wd({headers:e.environment.clob.headers,root:e.environment.clob.rest,resolveHeaders:r=>this.resolveClobHeaders(r)}),relayer:new wd({headers:e.environment.relayer.headers,root:e.environment.relayer.rest,resolveHeaders:r=>this.resolveRelayerHeaders(r)}),rpc:new H({url:e.environment.rpc}),gamma:new wd({headers:e.environment.gamma.headers,root:e.environment.gamma.rest}),data:new wd({headers:e.environment.data.headers,root:e.environment.data.rest}),rfq:new wd({headers:e.environment.combos.headers,root:e.environment.combos.rest}),perps:new wd({headers:e.environment.perps.headers,root:e.environment.perps.rest}),secureClob:new wd({headers:e.environment.clob.headers,resolveHeaders:async r=>({...await this.resolveClobHeaders(r),...await this.#r(r)}),root:e.environment.clob.rest}),combos:new wd({headers:e.environment.combos.collateralReturn.headers,resolveHeaders:r=>this.resolveRelayerHeaders(r),root:e.environment.combos.collateralReturn.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 g({account:e.account,chainId:e.environment.chainId,credentials:e.credentials,exchange:e.environment.contracts.exchangeV3,headers:e.environment.combos.headers,signer:e.signer,url:e.environment.combos.ws}),sports:new v({headers:e.environment.sports.headers,url:e.environment.sports.ws}),rtds:new q({headers:e.environment.rtds.headers,url:e.environment.rtds.ws}),perpsSubscriptions:new b({headers:e.environment.perps.headers,url:e.environment.perps.ws}),perpsSession:new P({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}get secureClob(){return this.context.secureClob}get combos(){return this.context.combos}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 gb(this);}finally{this.endAuthenticationLifecycle(),await Promise.allSettled([e,r,s]).then(()=>{});}let o=new U({apiKey:n,environment:i});for(let A of this.decorators)o.extend(A);return o}async#r(e){try{let r=Math.floor(Date.now()/1e3);return {POLY_ADDRESS:this.account.signer,POLY_API_KEY:this.credentials.key,POLY_PASSPHRASE:this.credentials.passphrase,POLY_SIGNATURE:await Or(this.credentials.secret,r,e.method,e.path,e.body),POLY_TIMESTAMP:`${r}`}}catch(r){throw l.fromError(r,"Could not sign the L2-authenticated request")}}};function hs(t={}){return new U({environment:t.environment??le,apiKey:t.apiKey}).extend(Mr)}var qo=m$1(j,g$1,f$1,l,h,i,c,b$1,a),vo=m$1(a);async function Ao(t){let e=hs({environment:t.environment,apiKey:t.apiKey}),r=await Co(e,t),s=await e.beginAuthentication({wallet:r,credentials:t.credentials,nonce:t.nonce},t.signer).then(va(t.signer));if(s.account.walletType===WalletType.EOA||await Aa(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 Co(t,e){if(e.wallet!==void 0)return e.wallet;let r=expectEvmAddress(await e.signer.getAddress()),s=K(r,t.environment.walletDerivation);return await Aa(t,{wallet:s,type:WalletType.DEPOSIT_WALLET})?s:L$1(r,t.environment.walletDerivation)}async function Eo(t){let e=L$1(t.account.signer,t.environment.walletDerivation);if(!isSameEvmAddress(t.account.wallet,e))throw new a(`Wallet ${t.account.wallet} does not match the expected Deposit Wallet ${e} for this signer, nor a deployed wallet address.`);await(await Da(t)).wait();}
|
|
2
|
+
export{qo as CreateSecureClientError,vo as SetupGaslessWalletError,ie as accountActions,Mr as allActions,oe as analyticsActions,Or as buildHmacSignature,hs as createPublicClient,Ao as createSecureClient,ae as dataActions,ce as discoveryActions,Ti as forkEnvironmentConfig,ue as perpsActions,lc as preproduction,le as production,Ci as relayerApiKey,Ai as remoteBuilderSigning,de as rewardsActions,Tr as rfqActions,pe as subscriptionsActions,wr as tradingActions,xr as walletActions};//# sourceMappingURL=index.js.map
|
|
3
3
|
//# sourceMappingURL=index.js.map
|