@polymarket/client 0.11.0 → 0.12.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/index.js CHANGED
@@ -1,3 +1,3 @@
1
- import {Q,_,Y as Y$1,W,ua,sa as sa$1,Ve,Te as Te$1,Re as Re$1,Pe as Pe$1,Nc,Ne,Le as Le$1,Je,Pc,Lc,Jc,Hc,yb,qa as qa$1,ed,id,sd,gd,ac,_b,Yb,Wb,Ub,Sb,Qb,Ob,Cb,Ab,zc,Bc,rc,pc,nc,Jf,Mg,Ag,yg,lg,Kg,Ig,Gg,Eg,Vc,pg,ng,cd,ad,_c,Yc,xc,vc,tc,He,Ee as Ee$1,De,Ge,oa as oa$1,ma as ma$1,ka as ka$1,ia,ga,ea,Yf,Wf,Uf,Rf,wg,sg,ug,Cg,U as U$1,S,qd,od,md,kd,Pd,yd,xd,Xd,Vd,Td,Rd,kc,gc,Hf,yf,mf,Qg,ab,Ya,gb,db,Ba as Ba$1,Ga,N as N$1,O,Ja,ve as ve$1,te,re,ne,le,je,xe as xe$1,pe,ec,cc,J as J$1,Yd,I,Ca as Ca$1,L as L$1,ob,mb,de,ae,ce,_d,$d,Zd,qb,he,Kf,Mf,Of,be,M as M$1,Bd,Dd,Ed,Cd,zd,Ad}from'./chunk-WZQAMVAC.js';export{Vf as AcceptComboQuoteError,$a as ApproveErc1155ForAllError,Xa as ApproveErc20Error,ee as ArmPerpsAutoCancelError,tg as AuthorizeSessionKeyError,Qc as BiggestWinnerKind,Rc as BuilderVolumeInterval,nd as CancelAllError,pd as CancelMarketOrdersError,jd as CancelOrderError,ld as CancelOrdersError,lc as CollateralReturnKnownOperationKind,E as CombinatorialPrepareConditionCallError,$f as ComboAcceptFailureReason,va as ComboActivityType,We as ComboPositionSortBy,Xe as ComboPositionStatus,ag as ComboQuoteUnavailableReason,Ud as CreateLimitOrderError,Qd as CreateMarketOrderError,u as CtfMergePositionsCallError,w as CtfRedeemPositionsCallError,s as CtfSplitPositionCallError,Be as DepositToPerpsError,Ue as DownloadAccountingSnapshotError,Z as DropNotificationsError,b as Erc20ApprovalCallError,m as Erc20TransferCallError,rd as EstimateMarketPriceError,jc as ExecuteCollateralReturnPlanError,Ic as FetchBuilderVolumeError,P as FetchClosedOnlyModeError,oc as FetchCommentsByIdError,uc as FetchEventError,Ac as FetchEventLiveVolumeError,wc as FetchEventTagsError,Zb as FetchLastTradePriceError,$b as FetchLastTradePricesError,$c as FetchMarketError,bd as FetchMarketTagsError,zb as FetchMidpointError,Bb as FetchMidpointsError,X as FetchNotificationsError,hd as FetchOpenInterestError,Rb as FetchOrderBookError,Tb as FetchOrderBooksError,T as FetchOrderError,da as FetchOrderScoringError,fa as FetchOrdersScoringError,oe as FetchPerpsBookError,we as FetchPerpsFeesError,ie as FetchPerpsInstrumentsError,ke as FetchPerpsTickerError,me as FetchPerpsTickersError,Me as FetchPortfolioValueError,Nb as FetchPriceError,Pb as FetchPricesError,If as FetchPublicProfileError,Jg as FetchRelatedTagResourcesError,Hg as FetchRelatedTagsError,yc as FetchResolutionsError,na as FetchRewardPercentagesError,Zf as FetchRfqStatusError,og as FetchSeriesError,rg as FetchSessionKeysError,zg as FetchSportsMarketTypesError,Vb as FetchSpreadError,Xb as FetchSpreadsError,Fg as FetchTagError,ja as FetchTotalEarningsForUserForDayError,Mc as FetchTraderLeaderboardStandingError,cb as FetchTradingApprovalsStateError,Qe as FetchUserPnlError,Oe as FetchUserStatsError,Se as FetchUserVolumeError,Sc as LeaderboardWindow,V as ListAccountTradesError,ra as ListActivityError,Oc as ListBiggestWinnersError,Gc as ListBuilderLeaderboardError,xb as ListBuilderTradesError,ta as ListComboActivityError,Zc as ListComboMarketsError,Ke as ListComboPositionsError,qc as ListCommentsByUserAddressError,mc as ListCommentsError,bc as ListCurrentRewardsError,sc as ListEventsError,dd as ListMarketHoldersError,dc as ListMarketRewardsError,Xc as ListMarketsError,R as ListOpenOrdersError,qe as ListPerpsCandlesError,se as ListPerpsFundingHistoryError,ue as ListPerpsTradesError,Ie as ListPositionsError,fd as ListPriceHistoryError,mg as ListSeriesError,xg as ListSportsError,Dg as ListTagsError,Lg as ListTeamsError,Kc as ListTraderLeaderboardError,pa as ListTradesError,la as ListUserEarningsAndMarketsConfigError,ha as ListUserEarningsForDayError,a as MAX_UINT256,tf as MergePositionsError,ye as OpenPerpsSessionError,Qf as OpenRfqSessionError,q as PerpsDepositCallError,Wd as PlaceLimitOrderError,Sd as PlaceMarketOrderError,fc as PlanCollateralReturnError,Ye as PositionFilterType,Ze as PositionSortBy,_e as PositionStatus,vd as PostOrderError,wd as PostOrdersError,Wc as PriceHistoryInterval,Gf as RedeemPositionsError,Tf as RequestComboQuoteError,Cc as ResolutionMarketType,Dc as ResolutionReporter,Ec as ResolutionSource,Fc as ResolutionStatus,ze as RevokePerpsCredentialsError,vg as RevokeSessionKeyError,Nf as RfqCancelQuoteError,Mf as RfqCancelQuoteRejectedError,bg as RfqConfirmationDecision,Pf as RfqConfirmationError,Of as RfqConfirmationRejectedError,cg as RfqDirection,dg as RfqExecutionStatus,eg as RfqKnownErrorCode,Lf as RfqQuoteError,Kf as RfqQuoteRejectedError,fg as RfqRejectionCode,Sf as RfqRequestRejectedError,gg as RfqRequestedSizeUnit,hg as RfqSide,ig as RfqStatus,A as RouterMergeCallError,C as RouterRedeemCallError,y as RouterSplitCallError,kg as SearchError,jg as SearchSort,qg as SessionKeyKnownScope,fb as SetupTradingApprovalsError,K as SignerType,wa as SortDirection,hf as SplitPositionError,Bg as SubscribeError,xa as TipSide,ya as TradeFilterType,Tc as TraderLeaderboardSort,Pg as TransferErc20Error,fe as UpdatePerpsLeverageError,ge as UpdatePerpsMarginError,$e as UserPnlFidelity,af as UserPnlInterval,Xf as WaitForComboFillError,Od as WaitForOrderFillSettlementError,za as WaitForTransactionError,Ce as WithdrawFromPerpsError,o as authorizeSessionSignerCall,F as combinatorialPrepareConditionCall,v as ctfMergePositionsCall,x as ctfRedeemPositionsCall,t as ctfSplitPositionCall,l as decodeErc1155BalanceOfBatchResult,j as decodeErc1155BalanceOfResult,h as decodeErc1155IsApprovedForAllResult,e as decodeErc20AllowanceResult,G as encodeProxyCall,H as encodeSafeMultisendCall,f as erc1155ApprovalForAllCall,k as erc1155BalanceOfBatchCall,i as erc1155BalanceOfCall,g as erc1155IsApprovedForAllCall,d as erc20AllowanceCall,c as erc20ApprovalCall,n as erc20TransferCall,Aa as expectTransactionHandle,r as perpsDepositCall,p as revokeSessionSignerCall,B as routerMergeCall,D as routerRedeemCall,z as routerSplitCall}from'./chunk-WZQAMVAC.js';import {a,o,k as k$1,h,g,n,i,j as j$1,c,b as b$1,e}from'./chunk-IPPWXOOG.js';export{m as AutoCancelDailyLimitError,k as CancelledSigningError,e as ConnectionLostError,l as InsufficientLiquidityError,h as RateLimitError,p as RealtimeKnownErrorCode,g as RequestRejectedError,n as SigningError,i as TimeoutError,f as TradingRestriction,j as TransactionFailedError,c as TransportError,b as UnexpectedResponseError,a as UserInputError,d as WebSocketKnownCloseCode,o as makeErrorGuard}from'./chunk-IPPWXOOG.js';import {DecimalishSchema,ApiKeySchema,EvmAddressSchema,toBaseUnits,OrderSide}from'@polymarket/bindings';export{CommentParentEntityType,OrderSide,OrderType}from'@polymarket/bindings';export{NotificationType,OrderPostStatus,OrderResponseErrorCode,SignatureType}from'@polymarket/bindings/clob';export{ActivityType}from'@polymarket/bindings/data';import {WalletType}from'@polymarket/bindings/gamma';export{ComboKnownStatus,ProtocolVersion,TeamOrdering,WalletType}from'@polymarket/bindings/gamma';export{PerpsDepositStatus,PerpsInstrumentCategory,PerpsInstrumentType,PerpsInternalTransferDirection,PerpsKlineInterval,PerpsKnownWithdrawalStatus,PerpsMarginType,PerpsNotificationOrderType,PerpsNotificationType,PerpsOrderStatus,PerpsSide,PerpsSortDirection,PerpsTimeInForce}from'@polymarket/bindings/perps';import {z}from'zod';import {expectEvmAddress,isSameEvmAddress,expectEvmSignature,invariant,setNonBlockingTimeout}from'@polymarket/types';import {TypedData}from'ox';import {PerpsMarketDataEventSchema,RealtimeEventSchema,SportsResultEventSchema,MarketEventSchema,UserEventSchema,RealtimeKnownErrorCode,PolyboltAckOp,PolyboltAckSchema,PolyboltEnvelopeSchema,parsePolyboltEvent,PolyboltChannel}from'@polymarket/bindings/subscriptions';import {pushable}from'it-pushable';import {RfqQuoterInboundMessageSchema,RfqConfirmationDecision,RfqRequestedSizeUnit,RfqDirection}from'@polymarket/bindings/combos';var Mo=z.object({POLY_BUILDER_API_KEY:z.string().min(1),POLY_BUILDER_TIMESTAMP:z.string().min(1),POLY_BUILDER_PASSPHRASE:z.string().min(1),POLY_BUILDER_SIGNATURE:z.string().min(1)});function Oo(t){return new Se(t)}function Io(t){return new Pe(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.#t(e)}catch(r){throw n.fromError(r,"Could not authorize the builder-authenticated request")}}async#s(){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#t(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.#s(),method:"POST",mode:"cors"});if(!r.ok)throw new Error(`Remote signer rejected request with status ${r.status}`);return Mo.parse(await r.json())}},Pe=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 Xr(t){let e={chainId:t.chainId,name:"ClobAuthDomain",version:"1"};return {domain:e,message:{address:t.address,message:"This message attests that I control the given wallet",nonce:t.nonce??0,timestamp:`${t.timestamp}`},primaryType:"ClobAuth",types:{EIP712Domain:TypedData.extractEip712DomainTypes(e),ClobAuth:[{name:"address",type:"address"},{name:"timestamp",type:"string"},{name:"nonce",type:"uint256"},{name:"message",type:"string"}]}}}function Bo(t){return {listPositions:Je.bind(null,t),listComboPositions:Le$1.bind(null,t),fetchPortfolioValue:Ne.bind(null,t),fetchTraderLeaderboardStanding:Nc.bind(null,t),fetchUserStats:Pe$1.bind(null,t),fetchUserPnl:Re$1.bind(null,t),fetchUserVolume:Te$1.bind(null,t),downloadAccountingSnapshot:Ve.bind(null,t),listActivity:sa$1.bind(null,t),listComboActivity:ua.bind(null,t)}}function P(t,e={}){return e===null||typeof e!="object"||Array.isArray(e)?e:{...e,user:e.user===void 0?t.account.wallet:e.user}}function Re(t){let e=Bo(t);return t.isPublicClient()?e:{...e,listPositions:r=>Je(t,P(t,r)),listComboPositions:r=>Le$1(t,P(t,r)),fetchPortfolioValue:r=>Ne(t,P(t,r)),fetchTraderLeaderboardStanding:r=>Nc(t,P(t,r)),fetchUserStats:r=>Pe$1(t,P(t,r)),fetchUserPnl:r=>Re$1(t,P(t,r)),fetchUserVolume:r=>Te$1(t,P(t,r)),downloadAccountingSnapshot:r=>Ve(t,P(t,r)),listActivity:r=>sa$1(t,P(t,r)),listComboActivity:r=>ua(t,P(t,r)),listAccountTrades:W.bind(null,t),fetchNotifications:Y$1.bind(null,t),dropNotifications:_.bind(null,t),fetchClosedOnlyMode:Q.bind(null,t)}}function ge(t){return {listBuilderTrades:yb.bind(null,t),listBuilderLeaderboard:Hc.bind(null,t),fetchBuilderVolume:Jc.bind(null,t),listTraderLeaderboard:Lc.bind(null,t),listBiggestWinners:Pc.bind(null,t)}}function ve(t){return {fetchEventLiveVolume:Bc.bind(null,t),fetchResolutions:zc.bind(null,t),fetchMidpoint:Ab.bind(null,t),fetchMidpoints:Cb.bind(null,t),fetchPrice:Ob.bind(null,t),fetchPrices:Qb.bind(null,t),fetchOrderBook:Sb.bind(null,t),fetchOrderBooks:Ub.bind(null,t),fetchSpread:Wb.bind(null,t),fetchSpreads:Yb.bind(null,t),fetchLastTradePrice:_b.bind(null,t),fetchLastTradePrices:ac.bind(null,t),listPriceHistory:gd.bind(null,t),estimateMarketPrice:sd.bind(null,t),fetchOpenInterest:id.bind(null,t),listMarketHolders:ed.bind(null,t),listTrades:qa$1.bind(null,t)}}function qe(t){return {listEvents:tc.bind(null,t),fetchEvent:vc.bind(null,t),fetchEventTags:xc.bind(null,t),listMarkets:Yc.bind(null,t),listComboMarkets:_c.bind(null,t),fetchMarket:ad.bind(null,t),fetchMarketTags:cd.bind(null,t),listSeries:ng.bind(null,t),fetchSeries:pg.bind(null,t),listMarketClarifications:Vc.bind(null,t),listTags:Eg.bind(null,t),fetchTag:Gg.bind(null,t),fetchRelatedTags:Ig.bind(null,t),fetchRelatedTagResources:Kg.bind(null,t),search:lg.bind(null,t),listSports:yg.bind(null,t),fetchSportsMarketTypes:Ag.bind(null,t),listTeams:Mg.bind(null,t),fetchPublicProfile:Jf.bind(null,t),listComments:nc.bind(null,t),fetchCommentsById:pc.bind(null,t),listCommentsByUserAddress:rc.bind(null,t)}}function Ae(t){let e={fetchPerpsBook:r=>pe(t,r),fetchPerpsFees:()=>xe$1(t),fetchPerpsInstruments:r=>je(t,r),fetchPerpsTicker:r=>le(t,r),fetchPerpsTickers:r=>ne(t,r),listPerpsCandles:r=>re(t,r),listPerpsFundingHistory:r=>te(t,r),listPerpsTrades:r=>ve$1(t,r)};return t.isSecureClient()?{...e,depositToPerps:r=>Ge(t,r),openPerpsSession:r=>De(t,r),revokePerpsCredentials:r=>Ee$1(t,r),withdrawFromPerps:r=>He(t,r)}:e}function Uo(t){return {listCurrentRewards:cc.bind(null,t),listMarketRewards:ec.bind(null,t)}}function Ce(t){let e=Uo(t);return t.isPublicClient()?e:{...e,fetchOrderScoring:ea.bind(null,t),fetchOrdersScoring:ga.bind(null,t),listUserEarningsForDay:ia.bind(null,t),fetchTotalEarningsForUserForDay:ka$1.bind(null,t),listUserEarningsAndMarketsConfig:ma$1.bind(null,t),fetchRewardPercentages:oa$1.bind(null,t)}}function es(t){return {openRfqSession(){return Rf(t)},requestComboQuote(e){return Uf(t,e)},acceptComboQuote(e){return Wf(t,e)},waitForComboFill(e){return Yf(t,e)}}}function ts(t){return {authorizeSessionKey:ug.bind(null,t),fetchSessionKeys:sg.bind(null,t),revokeSessionKey:wg.bind(null,t)}}function Ee(t){return t.isSecureClient()?{subscribe(e){return Cg(t,e)}}:{subscribe(e){return Cg(t,e)}}}function rs(t){return {createMarketOrder:Rd.bind(null,t),placeMarketOrder:Td.bind(null,t),createLimitOrder:Vd.bind(null,t),placeLimitOrder:Xd.bind(null,t),postOrder:xd(t),postOrders:yd(t),waitForOrderFillSettlement:Pd.bind(null,t),cancelOrder:kd.bind(null,t),cancelOrders:md.bind(null,t),cancelAll:od.bind(null,t),cancelMarketOrders:qd.bind(null,t),listOpenOrders:S.bind(null,t),fetchOrder:U$1.bind(null,t)}}function Do(t){return {fetchTradingApprovalsState:db.bind(null,t)}}function ke(t){let e=Do(t);return t.isPublicClient()?e:{...e,fetchTradingApprovalsState:()=>db(t,{user:t.account.wallet}),setupTradingApprovals:gb.bind(null,t),approveErc20:Ya.bind(null,t),approveErc1155ForAll:ab.bind(null,t),transferErc20:Qg.bind(null,t),splitPosition:mf.bind(null,t),mergePositions:yf.bind(null,t),redeemPositions:Hf.bind(null,t),planCollateralReturn:gc.bind(null,t),executeCollateralReturnPlan:kc.bind(null,t)}}function ss(t){return t.isSecureClient()?{...Re(t),...ge(t),...ve(t),...qe(t),...Ae(t),...Ce(t),...es(t),...ts(t),...Ee(t),...rs(t),...ke(t)}:{...Re(t),...ge(t),...ve(t),...qe(t),...Ae(t),...Ce(t),...Ee(t),...ke(t)}}var we={name:"production",chainId:137,rpc:"https://polygon.drpc.org",walletDerivation:{depositWalletFactory:expectEvmAddress("0x00000000000Fb5C9ADea0298D729A0CB3823Cc07"),depositWalletBeacon:expectEvmAddress("0x7A18EDfe055488A3128f01F563e5B479D92ffc3a"),depositWalletImplementation:expectEvmAddress("0x58CA52ebe0DadfdF531Cde7062e76746de4Db1eB"),proxyFactory:expectEvmAddress("0xaB45c5A4B0c941a2F231C04C3f49182e1A254052"),proxyImplementation:expectEvmAddress("0x44e999d5c2F66Ef0861317f9A4805AC2e90aEB4f"),safeFactory:expectEvmAddress("0xaacFeEa03eb1561C4e67d661e40682Bd20E3541b"),safeInitCodeHash:"0x2bce2127ff07fb632d16c8347c4ebf501f4841168bed00d9e6ef715ddb6fcecf"},contracts:{collateralToken:expectEvmAddress("0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB"),conditionalTokens:expectEvmAddress("0x4D97DCd97eC945f40cF65F87097ACe5EA0476045"),negRiskAdapter:expectEvmAddress("0xd91E80cF2E7be2e162c6513ceD06f1dD0dA35296"),collateralAdapter:expectEvmAddress("0xAdA100Db00Ca00073811820692005400218FcE1f"),negRiskCollateralAdapter:expectEvmAddress("0xadA2005600Dec949baf300f4C6120000bDB6eAab"),standardExchange:expectEvmAddress("0xE111180000d2663C0091e4f400237545B87B996B"),negRiskExchange:expectEvmAddress("0xe2222d279d744050d28e00520010520000310F59"),exchangeV3:expectEvmAddress("0xe3333700cA9d93003F00f0F71f8515005F6c00Aa"),protocolV2Router:expectEvmAddress("0x12121212006e4CD160D18e3f00711DA5c3372600"),binaryModule:expectEvmAddress("0x1000008dD9001B968442c1000017eaE6E0dA00Ba"),negRiskModule:expectEvmAddress("0x200000900045e3B6259600682756002200028933"),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",builderGateway:{rest:"https://combos-rfq-gateway-builder.polymarket.com"},collateralReturn:{rest:"https://combos-rfq-collateral-return.polymarket.com"}},perps:{rest:"https://api.perpetuals.polymarket.com",ws:"wss://ws.perpetuals.polymarket.com/v1/ws"},realtime:{ws:"wss://ws-live-v2.polymarket.com/ws"},rtds:{ws:"wss://ws-live-data.polymarket.com"},sports:{ws:"wss://sports-api.polymarket.com/ws"},relayerMaxPolls:100,relayerPollFrequencyMs:2e3};function Wo(t,e=we){return {...e,...t,walletDerivation:{...e.walletDerivation,...t.walletDerivation},contracts:{...e.contracts,...t.contracts},clob:{...k(e.clob,t.clob),market:L(e.clob.market,t.clob?.market),user:L(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:{...is(e.combos,t.combos),builderGateway:k(e.combos.builderGateway,t.combos?.builderGateway),collateralReturn:k(e.combos.collateralReturn,t.combos?.collateralReturn)},perps:is(e.perps,t.perps),realtime:L(e.realtime,t.realtime),rtds:L(e.rtds,t.rtds),sports:L(e.sports,t.sports)}}function k(t,e){return {...t,...e,headers:Te(t.headers,e?.headers)}}function L(t,e){return {...t,...e,headers:Te(t.headers,e?.headers)}}function is(t,e){return {...t,...e,headers:Te(t.headers,e?.headers)}}function Te(t,e){if(!(t===void 0&&e===void 0))return {...t,...e}}var Qu=Wo({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 ns(t,e,r,s,i){let o=`${e}${r}${s}`;i!==void 0&&(o+=i);let n=await globalThis.crypto.subtle.importKey("raw",Qo(t),{name:"HMAC",hash:"SHA-256"},false,["sign"]),a=await globalThis.crypto.subtle.sign("HMAC",n,new TextEncoder().encode(o));return Ho(Ko(a))}function Qo(t){let e=t.replace(/-/g,"+").replace(/_/g,"/").replace(/[^A-Za-z0-9+/=]/g,""),r=atob(e),s=new Uint8Array(r.length);for(let i=0;i<r.length;i+=1)s[i]=r.charCodeAt(i);return s.buffer}function Ko(t){let e=new Uint8Array(t),r="";for(let s of e)r+=String.fromCharCode(s);return btoa(r)}function Ho(t){return t.replace(/\+/g,"-").replace(/\//g,"_")}function R(t,e){let r;return {close:()=>(r===void 0&&(r=Promise.resolve(t.return()).then(()=>e())),r),[Symbol.asyncIterator](){return t[Symbol.asyncIterator]()}}}var b=class{#e=new Set;#s;constructor(e){this.#s=e?.deriveServerState??(()=>{});}add(e,r={}){let s={queue:pushable({objectMode:true})};r.matches!==void 0&&(s.matches=r.matches);let i={subscription:e,subscriber:s};return {change:this.#t(i),entry:i}}#t(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.#s(this.#e)}};function xe(t,e,r){let s=H(r.assetsIds,e.assetsIds),i=H(e.assetsIds,r.assetsIds);s.length>0&&t(os(s,r.customFeatureEnabled));let o=r.assetsIds[0];s.length===0&&e.customFeatureEnabled!==r.customFeatureEnabled&&o!==void 0&&t(os([o],r.customFeatureEnabled)),i.length>0&&t(jo(i));}function Fe(t,e,r){if(r.includeAllMarkets){!e.includeAllMarkets&&e.markets.length>0&&t(cs(e.markets));return}if(e.includeAllMarkets){r.markets.length>0&&t(as(r.markets));return}let s=H(r.markets,e.markets),i=H(e.markets,r.markets);s.length>0&&t(as(s)),i.length>0&&t(cs(i));}function us(t){let e=new Set,r=false;for(let{subscription:s}of t){for(let i of s.assetIds??s.tokenIds)e.add(i);r||=s.customFeatureEnabled===true;}return {assetsIds:Array.from(e),customFeatureEnabled:r}}function ds(t){let e=false,r=new Set;for(let{subscription:s}of t){if(ys(s)){e=true;continue}for(let i of s.markets??[])r.add(i);}return {includeAllMarkets:e,markets:e?[]:Array.from(r)}}function ps(t){return {assets_ids:t.assetsIds,custom_feature_enabled:t.customFeatureEnabled,type:"market"}}function os(t,e){return {assets_ids:t,custom_feature_enabled:e,operation:"subscribe"}}function jo(t){return {assets_ids:t,operation:"unsubscribe"}}function ls(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 as(t){return {markets:t,operation:"subscribe"}}function cs(t){return {markets:t,operation:"unsubscribe"}}function ms(t){let e=t.assetIds??t.tokenIds;return r=>{switch(r.type){case "price_change":return r.payload.priceChanges.some(s=>e.includes(s.assetId));case "new_market":return t.customFeatureEnabled===true;case "market_resolved":return t.customFeatureEnabled===true&&(r.payload.assetIds??[]).some(s=>e.includes(s));case "best_bid_ask":return t.customFeatureEnabled===true&&e.includes(r.payload.assetId);default:return e.includes(r.payload.assetId)}}}function hs(t){if(ys(t))return ()=>true;let e=new Set((t.markets??[]).map(r=>r.toLowerCase()));return r=>e.has(r.payload.market.toLowerCase())}function ys(t){return (t.markets?.length??0)===0}function H(t,e){let r=new Set(e);return t.filter(s=>!r.has(s))}var A=class{#e;#s;#t;#a=new de({heartbeat:new Zd});#o=new ce;#r=new b({deriveServerState:us});constructor(e){this.#e=e.headers,this.#s=e.url;}async subscribe(e){let{change:r,entry:s}=this.#r.add(e,{matches:ms(e)});return await this.#i(s,r),R(s.subscriber.queue,()=>this.#n(s))}async#i(e,r){let{before:s,after:i}=r;try{(await this.#c()).reusedOpenSocket&&xe(n=>this.#a.send(n),s,i);}catch(o){throw await this.#n(e),o}}async#n(e){let{before:r,after:s}=this.#r.remove(e);if(!this.#r.hasActiveSubscriptions()){await this.close();return}xe(i=>this.#a.send(i),r,s);}async close(){this.#t===void 0&&(this.#t=this.#d().finally(()=>{this.#t=void 0;})),await this.#t;}async#d(){this.#o.stop(),this.#r.endAll(),await this.#a.close();}#c(){return this.#a.connect({onConnectionLost:()=>this.#l(),onError:()=>this.#m(),onMessage:e=>this.#p(e),onOpen:()=>this.#u(),headers:this.#e,url:this.#s})}#u(){this.#o.resetBackoff(),this.#y();}#p(e){let r=Array.isArray(e)?e:[e];for(let s of r){let i=MarketEventSchema.safeParse(s);i.success&&this.#r.dispatch(i.data);}}#l(){this.#r.hasActiveSubscriptions()&&this.#h();}#m(){}#y(){this.#a.send(ps(this.#r.serverState()));}#h(){this.#o.schedule({reconnect:()=>this.#c(),shouldReconnect:()=>this.#r.hasActiveSubscriptions()});}};var w=class{#e;#s;#t;#a;#o=new de({heartbeat:new Zd});#r=new ce;#i=new b({deriveServerState:ds});constructor(e){this.#e=e.credentials,this.#s=e.headers,this.#t=e.url;}async subscribe(e){let{change:r,entry:s}=this.#i.add(e,{matches:hs(e)});return await this.#n(s,r),R(s.subscriber.queue,()=>this.#d(s))}async#n(e,r){let{before:s,after:i}=r;try{(await this.#u()).reusedOpenSocket&&Fe(n=>this.#o.send(n),s,i);}catch(o){throw await this.#d(e),o}}async#d(e){let{before:r,after:s}=this.#i.remove(e);if(!this.#i.hasActiveSubscriptions()){await this.close();return}Fe(i=>this.#o.send(i),r,s);}async close(){this.#a===void 0&&(this.#a=this.#c().finally(()=>{this.#a=void 0;})),await this.#a;}async#c(){this.#r.stop(),this.#i.endAll(),await this.#o.close();}#u(){return this.#o.connect({onConnectionLost:()=>this.#m(),onError:()=>this.#y(),onMessage:e=>this.#l(e),onOpen:e=>this.#p(e),prepare:()=>this.#e,headers:this.#s,url:this.#t})}#p(e){this.#r.resetBackoff(),this.#h(e);}#l(e){let r=Array.isArray(e)?e:[e];for(let s of r){let i=UserEventSchema.safeParse(s);i.success&&this.#i.dispatch(i.data);}}#m(){this.#i.hasActiveSubscriptions()&&this.#f();}#y(){}#h(e){this.#o.send(ls(this.#i.serverState(),e));}#f(){this.#r.schedule({reconnect:()=>this.#u(),shouldReconnect:()=>this.#i.hasActiveSubscriptions()});}};var T=class{#e;#s;#t;#a;#o=new Set;#r=new Set;#i=new Set;#n=false;constructor(e){this.#e=e.chainId,this.#s=e.headers,this.#t=e.restUrl,this.#a=e.wsUrl;}connect(e){if(this.#n)return Promise.reject(new c("Perps session manager has been shut down."));let r=new he({chainId:this.#e,credentials:e,headers:this.#s,onClose:i=>this.#d(i),restUrl:this.#t,wsUrl:this.#a});this.#r.add(r);let s;return s=(async()=>{try{if(await r.connect(),this.#n)throw await r.close(),new c("Perps session manager has been shut down.");return this.#o.add(r),r}catch(i){throw await r.close(),i}finally{this.#i.delete(s),this.#r.delete(r);}})(),this.#i.add(s),s}async shutdown(){this.#n=true;let e=Array.from(this.#o),r=Array.from(this.#r),s=Array.from(this.#i);this.#o.clear(),this.#r.clear(),this.#i.clear(),await Promise.allSettled([...e.map(i=>i.close()),...r.map(i=>i.close()),...s.map(i=>i.catch(()=>{}))]).then(()=>{});}#d(e){this.#o.delete(e),this.#r.delete(e);}};var C=class{#e;#s;#t;#a=1;#o=new de({heartbeat:new ae});#r=new ce;#i=new b({deriveServerState:$o});constructor(e){this.#e=e.headers,this.#s=e.url;}async subscribe(e){let{change:r,entry:s}=this.#i.add(e,{matches:Yo(e)});return await this.#n(s,r),R(s.subscriber.queue,()=>this.#d(s))}async#n(e,r){try{(await this.#u()).reusedOpenSocket&&(this.#h(fs(r.before,r.after)),this.#f(bs(r.before,r.after)));}catch(s){throw await this.#d(e),s}}async#d(e){let{before:r,after:s}=this.#i.remove(e);this.#h(fs(r,s)),this.#f(bs(r,s)),this.#i.hasActiveSubscriptions()||await this.close();}async close(){this.#t===void 0&&(this.#t=this.#c().finally(()=>{this.#t=void 0;})),await this.#t;}async#c(){this.#r.stop(),this.#i.endAll(),await this.#o.close();}#u(){return this.#o.connect({onConnectionLost:()=>this.#m(),onError:()=>this.#y(),onMessage:e=>this.#l(e),onOpen:()=>this.#p(),headers:this.#e,url:this.#s})}#p(){this.#r.resetBackoff(),this.#h(Array.from(this.#i.serverState()));}#l(e){let r=PerpsMarketDataEventSchema.safeParse(e);r.success&&this.#i.dispatch(r.data);}#m(){this.#i.hasActiveSubscriptions()&&this.#S();}#y(){}#h(e){e.length!==0&&this.#o.send(this.#b("sub",e));}#f(e){e.length!==0&&this.#o.send(this.#b("unsub",e));}#b(e,r){return {id:this.#a++,req:e,chs:r}}#S(){this.#r.schedule({reconnect:()=>this.#u(),shouldReconnect:()=>this.#i.hasActiveSubscriptions()});}};function $o(t){let e=new Set,r=new Set,s=new Set,i=false,o=false;for(let{subscription:n}of t)switch(n.topic){case "perps.tickers":n.instrumentId===void 0?i=true:r.add(n.instrumentId);break;case "perps.statistics":n.instrumentId===void 0?o=true:s.add(n.instrumentId);break;default:e.add(Go(n));}if(i)e.add("tickers::all");else for(let n of r)e.add(`tickers::${n}`);if(o)e.add("statistics::all");else for(let n of s)e.add(`statistics::${n}`);return e}function fs(t,e){return Array.from(e).filter(r=>!t.has(r))}function bs(t,e){return Array.from(t).filter(r=>!e.has(r))}function Go(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 Yo(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 Ps(t){if(t.topic==="prices.equity"){let e=t.symbol.toLowerCase();return [{key:JSON.stringify([t.topic,e]),topic:t.topic,symbol:e}]}return t.symbols.map(e=>t.topic==="prices.crypto.twap"?{key:JSON.stringify([t.topic,e,60]),topic:t.topic,symbol:e,windowSeconds:60}:{key:JSON.stringify([t.topic,e]),topic:t.topic,symbol:e})}function Rs(t,e){return Math.random()*(t===4003?1e4:Math.min(1e3*2**e,3e4))}var j=class{#e;#s=new ce;#t=new Map;#a=[];#o;#r;#i=false;#n=false;#d=false;#c=false;#u;#p=0;#l=64;#m=Number.NEGATIVE_INFINITY;constructor(e){this.#e=e;}get size(){return this.#t.size}has(e){return this.#t.has(e)}get closed(){return this.#n}get keyTarget(){return Date.now()-this.#m>=6e4?64:this.#l}add(e,r){clearTimeout(this.#r);let s=this.#t.get(e.key);if(s===void 0){let{promise:i,resolve:o,reject:n}=Promise.withResolvers();i.catch(()=>{}),s={subscription:e,listeners:new Set,ready:i,resolve:o,reject:n,subscribed:false,accepted:false},this.#t.set(e.key,s),this.#i&&this.#f("subscribe",[s]);}return s.listeners.add(r),s.snapshot!==void 0&&r.event(s.snapshot),!this.#i&&!this.#c&&this.#u===void 0&&!this.#s.isScheduled&&this.#y(),Zo(s.ready)}remove(e,r){let s=this.#t.get(e);s!==void 0&&(s.listeners.delete(r),!(s.listeners.size>0)&&(this.#t.delete(e),s.reject(new c("Realtime subscription closed.")),this.#i&&this.#f("unsubscribe",[s]),this.#t.size===0&&(this.#r=setNonBlockingTimeout(()=>{this.close();},1e3))));}#y(){if(this.#n||this.#c)return Promise.resolve();if(this.#u!==void 0)return this.#u;let e=this.#h().catch(r=>{this.#A([...this.#t.values()].filter(s=>!s.accepted),c.fromError(r));}).finally(()=>{this.#u===e&&(this.#u=void 0),this.#i||this.#q(1006);});return this.#u=e,e}async#h(){let e=this.#p;if(await this.#e.open({event:r=>this.#R(r),dropped:()=>this.#g(),disconnected:r=>this.#v(r)}),!(this.#n||e!==this.#p))try{if(await this.#e.authorize(),this.#n||e!==this.#p)return;this.#i=!0,this.#f("subscribe",[...this.#t.values()]);}catch(r){if(this.#n||e!==this.#p)return;r instanceof g&&r.code!==RealtimeKnownErrorCode.AuthUnavailable?this.#E(r):await this.#C(1006);}}#f(e,r){if(r.length===0)return;let s=this.#a.at(-1);s?.op===e?s.keys.push(...r):this.#a.push({op:e,keys:r}),this.#b();}#b(){this.#o!==void 0||this.#d||!this.#i||this.#n||(this.#o=setNonBlockingTimeout(()=>{this.#o=void 0,this.#S();},10));}async#S(){if(!this.#i||this.#n)return;let e=this.#a.shift();if(e===void 0)return;let r=[...new Set(e.keys)].filter(i=>e.op==="unsubscribe"||this.#t.get(i.subscription.key)===i);if(r.length===0){this.#b();return}let s=this.#p;this.#d=true;try{let i=await this.#e.change(e.op,r.map(({subscription:o})=>o));if(s!==this.#p||this.#n)return;if(e.op==="unsubscribe"&&i.length>0){let o=i[0];if(o!==void 0)throw o.error}if(e.op==="subscribe"){this.#s.resetBackoff();let o=new Set(i.map(n=>n.key));for(let n of r)o.has(n.subscription.key)||(n.subscribed=!0,n.accepted=!0,n.resolve());for(let{key:n,error:a}of i){let c=r.find(u=>u.subscription.key===n);c!==void 0&&this.#A([c],a,!1);}}}catch(i){if(s!==this.#p||this.#n)return;i instanceof g&&e.op==="subscribe"?this.#A(r,i):await this.#C(1006);}finally{this.#d=false,this.#b();}}#R(e){for(let r of this.#t.values()){let s=r.subscription;if(s.topic!==e.topic)continue;let i=e.payload;if(i.symbol.toLowerCase()===s.symbol&&!(s.topic==="prices.crypto.twap"&&(!("windowSeconds"in i)||i.windowSeconds!==s.windowSeconds))){r.snapshot=Xo(r.snapshot,e);for(let o of r.listeners)o.event(e);}}}#g(){let e=Date.now();e-this.#m<5e3||(this.#l=Math.max(1,Math.floor(this.keyTarget/2)),this.#m=e);}#P(){this.#p++,this.#i=false,this.#a=[],clearTimeout(this.#o),this.#o=void 0;for(let e of this.#t.values()){if(e.snapshot=void 0,!e.subscribed)continue;let{promise:r,resolve:s,reject:i}=Promise.withResolvers();r.catch(()=>{}),e.ready=r,e.resolve=s,e.reject=i,e.subscribed=false;}}#v(e$1){let r=new e("Realtime connection closed.",e$1);this.#P(),e$1.code===4001||e$1.code===4008?this.#E(r):this.#q(e$1.code);}async#C(e){this.#c=true,this.#P();try{await this.#e.close();}finally{this.#c=false,this.#q(e);}}#q(e){this.#s.schedule({delayPolicy:r=>Rs(e,r),shouldReconnect:()=>!this.#n&&this.#t.size>0,reconnect:()=>this.#y()});}#E(e){let r=[...this.#t.values()],s=new Set(r.flatMap(i=>[...i.listeners]));for(let i of r)i.reject(e);for(let i of s)i.end(e);this.close();}#A(e,r,s=true){let i=e.filter(n=>this.#t.get(n.subscription.key)===n),o=new Set(i.flatMap(n=>[...n.listeners]));for(let n of i)this.#t.delete(n.subscription.key),n.reject(r);s&&this.#i&&this.#f("unsubscribe",i);for(let n of o)n.end(r);this.#t.size===0&&(this.#r=setNonBlockingTimeout(()=>{this.close();},1e3));}async close(){if(this.#n)return;this.#n=true,this.#s.stop(),clearTimeout(this.#r);let e=new c("Realtime connection closed.");this.#P();for(let r of this.#t.values())r.reject(e);this.#t.clear(),await this.#e.close();}};function Zo(t){return new Promise((e,r)=>{let s=setNonBlockingTimeout(()=>{r(new c("Realtime subscription was not accepted within 30 seconds."));},3e4);t.then(()=>{clearTimeout(s),e();},i=>{clearTimeout(s),r(i);});})}function Xo(t,e){if(e.type==="subscribe")return e;let r=t?.type==="subscribe"?t.payload.data:[],{symbol:s,timestamp:i,value:o}=e.payload;if((r.at(-1)?.timestamp??0)>i)return t;let n=[...r.filter(a=>a.timestamp>i-12e4&&a.timestamp<i),{timestamp:i,value:o}];return e.topic==="prices.crypto.twap"?{...e,type:"subscribe",payload:{symbol:s,data:n,windowSeconds:e.payload.windowSeconds}}:{...e,type:"subscribe",payload:{symbol:s,data:n}}}var V=class{#e;#s=new de({heartbeat:new be,connectTimeoutMs:1e4,closeTimeoutMs:1e3});#t=new Map;#a;#o=0;#r=0;#i=0;constructor(e){this.#e=e;}async open(e$1){this.#a=e$1;let r=this.#i;await this.#s.connect({url:this.#e.url,headers:this.#e.headers,onOpen:()=>{},onError:()=>{},onConnectionLost:s=>{r===this.#i&&(this.#c(new e("Realtime connection closed.",s)),e$1.disconnected(s));},onMessage:s=>{r===this.#i&&this.#d(s);}});}async authorize(){let{key:e,secret:r,passphrase:s}=this.#e.credentials;await this.#n({op:"auth",auth:{apiKey:e,secret:r,passphrase:s}},PolyboltAckOp.Authed,[]);}async change(e,r){let s=[],i=0;for(;i<r.length;){let o=[];for(;i+o.length<r.length;){let a=r[i+o.length];if(a===void 0)break;let c=sa(a),u={op:e,subscriptions:[...o,c],rid:String(this.#o+1)};if(o.length>0&&new TextEncoder().encode(JSON.stringify(u)).length>6e4)break;o.push(c);}let n=await this.#n({op:e,subscriptions:o},e==="subscribe"?PolyboltAckOp.Subscribed:PolyboltAckOp.Unsubscribed,o.map(({channel:a})=>a));for(let{index:a,error:c}of n){let u=r[i+a];u!==void 0&&s.push({key:u.key,error:c});}i+=o.length;}return s}#n(e,r,s){let i=String(++this.#o);return new Promise((o,n)=>{let a={op:r,channels:[...s],rejections:[],resolve:o,reject:n};this.#t.set(i,a),a.sendTimer=setNonBlockingTimeout(()=>{a.timer=setNonBlockingTimeout(()=>{this.#t.delete(i),n(new c("Realtime acknowledgement timed out after 10 seconds."));},1e4),this.#r=Date.now();try{if(!this.#s.send({...e,rid:i}))throw new c("Realtime connection is not open.")}catch(c$1){clearTimeout(a.timer),this.#t.delete(i),n(c.fromError(c$1));}},Math.max(0,110-(Date.now()-this.#r)));})}#d(e){let r=PolyboltAckSchema.safeParse(e);if(r.success){let{op:o,rid:n,code:a,channel:c}=r.data,u=n===void 0?void 0:this.#t.get(n);if(u===void 0)return;if(o===PolyboltAckOp.Error&&a!==void 0){let S=new g(`Realtime subscription rejected: ${a}`,{status:200,code:a}),l=u.channels.flatMap((y,Z)=>y===c?[Z]:[]);if(c===void 0||l.length!==1)u.reject(S);else {let y=l[0];if(y===void 0||(u.channels[y]=void 0,u.rejections.push({index:y,error:S}),u.channels.some(Z=>Z!==void 0)))return;u.resolve(u.rejections);}}else if(o===u.op){if(u.channels.length>0){let S=u.channels.indexOf(c??"");if(S<0||(u.channels[S]=void 0,u.channels.some(l=>l!==void 0)))return}u.resolve(u.rejections);}else return;clearTimeout(u.timer),n!==void 0&&this.#t.delete(n);return}let s=PolyboltEnvelopeSchema.safeParse(e);if(!s.success)return;let i=parsePolyboltEvent(s.data);i!==void 0&&this.#a?.event(i),(s.data.dropped??0)>0&&this.#a?.dropped();}#c(e){for(let r of this.#t.values())clearTimeout(r.sendTimer),clearTimeout(r.timer),r.reject(e);this.#t.clear();}async close(){this.#i++,this.#a=void 0,this.#c(new c("Realtime connection closed.")),await this.#s.close();}};function sa(t){switch(t.topic){case "prices.crypto":return {channel:PolyboltChannel.Crypto,filter:{symbol:t.symbol}};case "prices.crypto.twap":return {channel:PolyboltChannel.Twap,filter:{symbol:t.symbol,window_seconds:t.windowSeconds}};case "prices.equity":return {channel:PolyboltChannel.Equity,filter:{symbol:t.symbol}}}}var N=class{#e;#s=new Set;#t=new Set;constructor(e){this.#e=e;}async subscribe(e){let r=[...new Map(Ps(e).map(c=>[c.key,c])).values()],s=pushable({objectMode:true}),i=[],o=false,n,a=async()=>{if(!o){o=true;for(let c of i)c();n===void 0?await s.return():s.end(n),this.#t.delete(a);}};this.#t.add(a);try{await Promise.all(r.map(c=>{let u=this.#a(c.key),S={event(l){if(o||"types"in e&&e.types!==void 0&&e.types.length>0&&!e.types.includes(l.type))return;let y="symbol"in l.payload?{...l.payload,symbol:"symbol"in c?c.symbol:l.payload.symbol}:l.payload;s.push({...l,payload:y});},end(l){n=l,s.end(l),a();}};return i.push(()=>u.remove(c.key,S)),u.add(c,S)}));}catch(c){throw await a(),c}return {close:a,async*[Symbol.asyncIterator](){try{yield*s;}finally{await a();}}}}#a(e){for(let s of this.#s)if(s.closed)this.#s.delete(s);else if(s.has(e))return s;for(let s of this.#s)if(s.size<s.keyTarget)return s;let r=new j(new V(this.#e));return this.#s.add(r),r}async close(){await Promise.all([...this.#t].map(r=>r()));let e=[...this.#s];this.#s.clear(),await Promise.all(e.map(r=>r.close()));}};var B=class{#e;constructor(e){this.#e=new N(e);}async subscribe(e){return this.#e.subscribe(e)}async close(){await this.#e.close();}};function qs(t,e){return {...e,quote:r=>t.quote(e,r)}}function As(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 Cs(t){return {quoteId:t.quoteId,rfqId:t.rfqId}}function Es(t){return {quoteId:t.quoteId,rfqId:t.rfqId}}function ks(t){return {quoteId:t.quoteId,rfqId:t.rfqId}}function ws(t,e){let r=M$1(t);return {auth:{apiKey:e.key,passphrase:e.passphrase,secret:e.secret},identity:{maker_address:r.maker,signature_type:r.signatureType,signer_address:r.signer},type:"auth"}}function Ts(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 xs(t,e,r){let s=M$1(t);return {maker_address:s.maker,quote_id:r,rfq_id:e,signer_address:s.signer,type:"RFQ_QUOTE_CANCEL"}}function Fs(t,e,r){return {decision:r,quote_id:e,rfq_id:t,type:"RFQ_CONFIRMATION_RESPONSE"}}var $=class{#e=new Map;#s;constructor(e){this.#s=e;}waitFor(e,r){let s=oa(),i$1,o=setNonBlockingTimeout(()=>{this.remove(e,i$1),s.reject(new i(r));},this.#s);i$1=s.promise.finally(()=>clearTimeout(o));let n=this.#e.get(e)??[];return n.push({...s,promise:i$1}),this.#e.set(e,n),i$1}resolve(e,r){let s=this.#e.get(e),i=s?.shift();i!==void 0&&(s!==void 0&&s.length===0&&this.#e.delete(e),i.resolve(r));}reject(e,r){let s=this.#e.get(e),i=s?.shift();i!==void 0&&(s!==void 0&&s.length===0&&this.#e.delete(e),i.reject(r));}remove(e,r){let s=this.#e.get(e);if(s===void 0)return;let i=s.filter(o=>o.promise!==r);i.length===0?this.#e.delete(e):this.#e.set(e,i);}rejectAll(e){for(let r of this.#e.values())for(let s of r)s.reject(e);this.#e.clear();}};function oa(){let t,e;return {promise:new Promise((s,i)=>{t=s,e=i;}),reject:e,resolve:t}}var Os="0x0000000000000000000000000000000000000000000000000000000000000000";async function Is(t){let e=M$1(t.account),r=Bd({chainId:t.chainId,exchange:t.exchange}),s={builder:Os,maker:e.maker,makerAmount:toBaseUnits(Cd(t.orderSide,t.orderPrice,t.size)),metadata:Os,salt:aa().toString(),side:Ed(t.orderSide),signatureType:e.signatureType,signer:e.signer,takerAmount:toBaseUnits(Dd(t.orderSide,t.orderPrice,t.size)),timestamp:Math.floor(Date.now()/1e3).toString(),tokenId:t.tokenId},i;try{i=await t.signer.signTypedData(zd({domain:r,order:s}));}catch(o){throw n.fromError(o,"Could not sign the RFQ quote order.")}return {...s,signature:Ad({domain:r,order:s,signature:i})}}function aa(){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=>Qs(t)).refine(t=>t<=BigInt(Number.MAX_SAFE_INTEGER),{message:"Value exceeds the temporary numeric wire limit."}),da=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 I(t,da)}async function Ws(t){let e=t.response.price,r=t.response.size===void 0?ha(t.request.requestedSize,e):t.response.size,s=await Is({account:t.account,chainId:t.chainId,exchange:t.exchange,orderPrice:la(t.request,t.response.source,e),orderSide:ma(t.response.source),signer:t.signer,size:r,tokenId:pa(t.request,t.response.source)});return {price:e,signedOrder:s,size:r}}function pa(t,e){return t.direction===RfqDirection.Buy?e==="collateral"?t.noPositionId:t.yesPositionId:e==="collateral"?t.yesPositionId:t.noPositionId}function la(t,e,r){return t.direction===RfqDirection.Buy&&e==="collateral"||t.direction===RfqDirection.Sell&&e==="inventory"?1000000n-r:r}function ma(t){return t==="collateral"?OrderSide.BUY:OrderSide.SELL}function ha(t,e){let r=Qs(t.value);return t.unit===RfqRequestedSizeUnit.Shares?r:r*1000000n/e}function Qs(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 i=BigInt(r)*1000000n+BigInt(s.padEnd(6,"0"));if(i<=0n)throw new a("Value must be greater than 0.");return i}var Sa=3e4,Pa=3e4,x=class{#e;#s;#t;#a;#o;#r;#i;#n;#d;#c;#u=false;constructor(e){this.#e=e.account,this.#s=e.chainId,this.#t=e.credentials,this.#a=e.exchange,this.#o=e.headers,this.#r=e.signer,this.#i=e.url;}async connect(){if(this.#u)throw new c("RFQ quoter manager has been shut down.");if(this.#n!==void 0){if(!this.#n.closed)return this.#n;this.#n=void 0;}if(this.#c!==void 0)return this.#c;let e=new Be({account:this.#e,chainId:this.#s,credentials:this.#t,exchange:this.#a,headers:this.#o,onClose:()=>this.#p(e),signer:this.#r,url:this.#i});this.#d=e;let r;return r=(async()=>{try{if(await e.connect(),this.#u)throw await e.close(),new c("RFQ quoter manager has been shut down.");return this.#n=e,e}catch(s){throw await e.close(),s}finally{this.#c===r&&(this.#c=void 0),this.#d===e&&(this.#d=void 0);}})(),this.#c=r,r}async shutdown(){this.#u=true;let e=this.#n,r=this.#d,s=this.#c;this.#n=void 0,this.#d=void 0,this.#c=void 0,await Promise.allSettled([e?.close(),r?.close(),s?.catch(()=>{})]).then(()=>{});}#p(e){this.#n===e&&(this.#n=void 0),this.#d===e&&(this.#d=void 0);}},Be=class{#e;#s;#t;#a;#o;#r;#i;#n;#d=new de;#c=pushable({objectMode:true});#u=new $(Pa);#p;#l;constructor(e){this.#e=e.account,this.#s=e.chainId,this.#t=e.credentials,this.#a=e.exchange,this.#o=e.headers,this.#r=e.onClose,this.#i=e.signer,this.#n=e.url;}get closed(){return this.#p!==void 0}async connect(){let e=Ra();this.#l=e;let r=setNonBlockingTimeout(()=>{e.reject(new c("RFQ quoter authentication timed out."));},Sa);try{await this.#d.connect({headers:this.#o,onConnectionLost:s=>this.#P(s),onError:()=>{},onMessage:s=>this.#R(s),onOpen:()=>this.#S(),url:this.#n}),await e.promise;}finally{clearTimeout(r),this.#l=void 0;}}async#m(e){if(!this.#d.send(e))throw new c("RFQ quoter websocket is not open.")}async close(){this.#p===void 0&&(this.#p=this.#y()),await this.#p;}[Symbol.asyncIterator](){return this.#c[Symbol.asyncIterator]()}async#y(){let e=new c("RFQ quoter websocket closed.");this.#b(e),this.#c.end(),await this.#d.close(),this.#r();}async#h(e){this.#p===void 0&&(this.#p=this.#f(e)),await this.#p;}async#f(e){this.#b(e),this.#c.end(e),await this.#d.close(),this.#r();}#b(e){this.#l?.reject(e),this.#u.rejectAll(e);}#S(){this.#d.send(ws(this.#e,this.#t));}#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.#g(s);return;case "quote_request":this.#c.push(qs(this,s));return;case "quote_ack":this.#u.resolve(G(s.rfqId),Cs(s));return;case "quote_cancel_ack":this.#u.resolve(Ie(s.rfqId,s.quoteId),Es(s));return;case "confirmation_request":this.#c.push(As(this,s));return;case "confirmation_ack":this.#u.resolve(Le(s.rfqId,s.quoteId),ks(s));return;case "execution_update":this.#c.push(s);return;case "trade":this.#c.push(s);return;case "rfq_error":this.#v(s);return}}#g(e){if(e.success===true){this.#l?.resolve(void 0);return}this.#l?.reject(new c(`RFQ quoter authentication failed: ${e.error}`));}#P(e$1){this.#h(new e("RFQ quoter connection lost.",e$1));}#v(e){if(e.requestType==="RFQ_QUOTE"){if(e.rfqId===void 0){this.#h(new c("Uncorrelated RFQ quoter error."));return}this.#u.reject(G(e.rfqId),new Kf(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.#h(new c("Uncorrelated RFQ quoter error."));return}this.#u.reject(Ie(e.rfqId,e.quoteId),new Mf(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.#h(new c("Uncorrelated RFQ quoter error."));return}this.#u.reject(Le(e.rfqId,e.quoteId),new Of(e.message,{code:e.code,errorId:e.errorId,quoteId:e.quoteId,rfqId:e.rfqId}));}}async quote(e,r){let s=Ds(r),i=await Ws({account:this.#e,chainId:this.#s,exchange:this.#a,request:e,response:s,signer:this.#i}),o=this.#u.waitFor(G(e.rfqId),`Timed out waiting for RFQ quote acknowledgement for ${e.rfqId}.`);try{return await this.#m(Ts(e,i)),await o}catch(n){throw this.#u.remove(G(e.rfqId),o),n}}async cancelQuote(e){let r=Ie(e.rfqId,e.quoteId),s=this.#u.waitFor(r,`Timed out waiting for RFQ quote cancellation acknowledgement for ${e.rfqId}.`);try{return await this.#m(xs(this.#e,e.rfqId,e.quoteId)),await s}catch(i){throw this.#u.remove(r,s),i}}async respondToConfirmation(e,r,s){let i=Le(e,r),o=this.#u.waitFor(i,`Timed out waiting for RFQ confirmation acknowledgement for ${e}.`);try{return await this.#m(Fs(e,r,s)),await o}catch(n){throw this.#u.remove(i,o),n}}};function G(t){return `ACK_RFQ_QUOTE:${t}`}function Ie(t,e){return `ACK_RFQ_QUOTE_CANCEL:${t}:${e}`}function Le(t,e){return `ACK_RFQ_CONFIRMATION_RESPONSE:${t}:${e}`}function Ra(){let t,e;return {promise:new Promise((s,i)=>{t=s,e=i;}),reject:e,resolve:t}}var F=class{#e;#s;#t;#a=new de({heartbeat:new _d});#o=new ce;#r=new b({deriveServerState:Aa});constructor(e){this.#e=e.headers,this.#s=e.url;}async subscribe(e){let{change:r,entry:s}=this.#r.add(e,{matches:Ta(e)});return await this.#i(s,r),R(s.subscriber.queue,()=>this.#n(s))}async#i(e,r){try{if((await this.#c()).reusedOpenSocket){let{before:i,after:o}=r,n=va(i,o);this.#h(n);}}catch(s){throw await this.#n(e),s}}async#n(e){let{before:r,after:s}=this.#r.remove(e),i=qa(r,s);this.#f(i),this.#r.hasActiveSubscriptions()||await this.close();}async close(){this.#t===void 0&&(this.#t=this.#d().finally(()=>{this.#t=void 0;})),await this.#t;}async#d(){this.#o.stop(),this.#r.endAll(),await this.#a.close();}#c(){return this.#a.connect({onConnectionLost:()=>this.#l(),onError:()=>this.#m(),onMessage:e=>this.#p(e),onOpen:()=>this.#u(),headers:this.#e,url:this.#s})}#u(){this.#o.resetBackoff(),this.#y();}#p(e){let r=RealtimeEventSchema.safeParse(e);r.success&&this.#r.dispatch(r.data);}#l(){this.#r.hasActiveSubscriptions()&&this.#b();}#m(){}#y(){this.#h(Array.from(this.#r.serverState().values()));}#h(e){e.length!==0&&this.#a.send(Ca(e));}#f(e){e.length!==0&&this.#a.send(Ea(e));}#b(){this.#o.schedule({reconnect:()=>this.#c(),shouldReconnect:()=>this.#r.hasActiveSubscriptions()});}};function va(t,e){return Array.from(e).flatMap(([r,s])=>t.has(r)?[]:[s])}function qa(t,e){return Array.from(t).flatMap(([r,s])=>e.has(r)?[]:[s])}function Aa(t){let e=new Map;for(let{subscription:r}of t)for(let s of ka(r))e.has(s.key)||e.set(s.key,s);return e}function Ca(t){return {action:"subscribe",subscriptions:t.map(({topic:e,type:r})=>({topic:e,type:r}))}}function Ea(t){return {action:"unsubscribe",subscriptions:t.map(({topic:e,type:r})=>({topic:e,type:r}))}}function ka(t){switch(t.topic){case "comments":return (t.types??["comment_created"]).map(e=>U("comments",e));case "prices.crypto.binance":return [U("crypto_prices","update")];case "prices.crypto.chainlink":return [U("crypto_prices_chainlink","update")];case "prices.crypto.chainlink.twap":return [U(wa(t.windowSeconds),"update")];case "prices.equity.pyth":return [U("equity_prices","update")];default:invariant(false,`Unknown RTDS topic: ${String(t)}`);}}function wa(t){switch(t){case 30:return "crypto_prices_twap_thirty";case 60:return "crypto_prices_twap_sixty";default:invariant(false,`Unknown TWAP window: ${String(t)}`);}}function U(t,e){return {key:`${t}:${e}`,topic:t,type:e}}function Ta(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.crypto.chainlink.twap":return e=>e.topic==="prices.crypto.chainlink.twap"&&e.payload.windowSeconds===t.windowSeconds&&(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 M=class{#e;#s;#t;#a=new de({heartbeat:new $d});#o=new ce;#r=new b;constructor(e){this.#e=e.headers,this.#s=e.url;}async subscribe(e){let{entry:r}=this.#r.add(e);return await this.#i(r),R(r.subscriber.queue,()=>this.#n(r))}async#i(e){try{await this.#c();}catch(r){throw await this.#n(e),r}}async#n(e){this.#r.remove(e),this.#r.hasActiveSubscriptions()||await this.close();}async close(){this.#t===void 0&&(this.#t=this.#d().finally(()=>{this.#t=void 0;})),await this.#t;}async#d(){this.#o.stop(),this.#r.endAll(),await this.#a.close();}#c(){return this.#a.connect({onConnectionLost:()=>this.#l(),onError:()=>this.#m(),onMessage:e=>this.#p(e),onOpen:()=>this.#u(),headers:this.#e,url:this.#s})}#u(){this.#o.resetBackoff();}#p(e){let r=SportsResultEventSchema.safeParse(e);r.success&&this.#r.dispatch(r.data);}#l(){this.#r.hasActiveSubscriptions()&&this.#y();}#m(){}#y(){this.#o.schedule({reconnect:()=>this.#c(),shouldReconnect:()=>this.#r.hasActiveSubscriptions()});}};var Y=class{#e;#s;get context(){return this.#e}get decorators(){return this.#s}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}get hasBuilderApiKey(){return this.context.apiKey?.isBuilderKey??false}constructor(e){this.#e=e,this.#s=[];}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.#s.push(e);}},Ba=z.object({key:ApiKeySchema,passphrase:z.string(),secret:z.string()}),Ua=z.object({wallet:EvmAddressSchema,credentials:Ba.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}),J=class extends Y{constructor(e){super({apiKey:e.apiKey,environment:e.environment,onRateLimitUpdate:e.onRateLimitUpdate,data:new Yd({headers:e.environment.data.headers,root:e.environment.data.rest}),gamma:new Yd({headers:e.environment.gamma.headers,root:e.environment.gamma.rest}),clob:new Yd({headers:e.environment.clob.headers,onRateLimitUpdate:e.onRateLimitUpdate,root:e.environment.clob.rest,resolveHeaders:r=>this.resolveClobHeaders(r)}),relayer:new Yd({headers:e.environment.relayer.headers,root:e.environment.relayer.rest,resolveHeaders:r=>this.resolveRelayerHeaders(r)}),rfq:new Yd({headers:e.environment.combos.headers,root:e.environment.combos.rest}),perps:new Yd({headers:e.environment.perps.headers,root:e.environment.perps.rest}),rpc:new J$1({url:e.environment.rpc}),webSockets:{clobMarket:new A({headers:e.environment.clob.market.headers,url:e.environment.clob.market.ws}),sports:new M({headers:e.environment.sports.headers,url:e.environment.sports.ws}),rtds:new F({headers:e.environment.rtds.headers,url:e.environment.rtds.ws}),perpsSubscriptions:new C({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=I(e,Ua);return Promise.resolve(async function*(){let i=Math.floor(Date.now()/1e3),o=s?.nonce??0,n=expectEvmAddress(yield Ca$1()),a=expectEvmAddress(s.wallet),c=L$1(this.environment,n,a);if(s.credentials!==void 0){let l=this.#e(s.credentials,c,r);try{if((await ob(l)).includes(s.credentials.key))return l}catch(y){if(!(y instanceof g)||y.status!==401)throw y}}let u=yield {kind:"signAuthMessage",payload:Xr({address:n,chainId:this.environment.chainId,nonce:o,timestamp:i})},S=await mb(this,{address:n,nonce:o,signature:expectEvmSignature(u),timestamp:i});return this.#e(S,c,r)}.call(this))}#e(e,r,s){let i=new Qe({account:r,apiKey:this.context.apiKey,credentials:e,environment:this.environment,onRateLimitUpdate:this.context.onRateLimitUpdate,signer:s});for(let o of this.decorators)i.extend(o);return i}},Qe=class extends Y{#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){let r=new B({url:e.environment.realtime.ws,headers:e.environment.realtime.headers,credentials:e.credentials});super({account:e.account,credentials:e.credentials,apiKey:e.apiKey,environment:e.environment,onRateLimitUpdate:e.onRateLimitUpdate,signer:e.signer,clob:new Yd({headers:e.environment.clob.headers,onRateLimitUpdate:e.onRateLimitUpdate,root:e.environment.clob.rest,resolveHeaders:s=>this.resolveClobHeaders(s)}),relayer:new Yd({headers:e.environment.relayer.headers,root:e.environment.relayer.rest,resolveHeaders:s=>this.resolveRelayerHeaders(s)}),rpc:new J$1({url:e.environment.rpc}),gamma:new Yd({headers:e.environment.gamma.headers,root:e.environment.gamma.rest}),data:new Yd({headers:e.environment.data.headers,root:e.environment.data.rest}),rfq:new Yd({headers:e.environment.combos.headers,root:e.environment.combos.rest}),perps:new Yd({headers:e.environment.perps.headers,root:e.environment.perps.rest}),secureClob:new Yd({headers:e.environment.clob.headers,onRateLimitUpdate:e.onRateLimitUpdate,resolveHeaders:async s=>({...await this.resolveClobHeaders(s),...await this.#t(s)}),root:e.environment.clob.rest}),combos:new Yd({headers:e.environment.combos.collateralReturn.headers,resolveHeaders:s=>this.resolveRelayerHeaders(s),root:e.environment.combos.collateralReturn.rest}),builderGateway:new Yd({headers:e.environment.combos.builderGateway.headers,resolveHeaders:async s=>({...await this.#s(s),...await this.#t(s)}),root:e.environment.combos.builderGateway.rest}),webSockets:{clobMarket:new A({headers:e.environment.clob.market.headers,url:e.environment.clob.market.ws}),clobUser:new w({credentials:e.credentials,headers:e.environment.clob.user.headers,url:e.environment.clob.user.ws}),rfqQuoter:new x({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 M({headers:e.environment.sports.headers,url:e.environment.sports.ws}),realtime:r,rtds:new F({headers:e.environment.rtds.headers,url:e.environment.rtds.ws}),perpsSubscriptions:new C({headers:e.environment.perps.headers,url:e.environment.perps.ws}),perpsSession:new T({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 builderGateway(){return this.context.builderGateway}get webSockets(){return this.context.webSockets}async closeSubscriptions(){await Promise.allSettled([this.webSockets.clobMarket.close(),this.webSockets.realtime.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:i,environment:o,onRateLimitUpdate:n}=this.context;try{await qb(this);}finally{this.endAuthenticationLifecycle(),await Promise.allSettled([e,r,s]).then(()=>{});}let a=new J({apiKey:i,environment:o,onRateLimitUpdate:n});for(let c of this.decorators)a.extend(c);return a}async#s(e){return e.method!=="GET"&&this.context.apiKey?.isBuilderKey?this.context.apiKey.authorize(e):{}}async#t(e){try{let r=Math.floor(Date.now()/1e3);return {POLY_ADDRESS:this.account.signer,POLY_API_KEY:this.credentials.key,POLY_PASSPHRASE:this.credentials.passphrase,POLY_SIGNATURE:await ns(this.credentials.secret,r,e.method,e.path,e.body),POLY_TIMESTAMP:`${r}`}}catch(r){throw n.fromError(r,"Could not sign the L2-authenticated request")}}};function Ks(t={}){return new J({environment:t.environment??we,apiKey:t.apiKey,onRateLimitUpdate:t.onRateLimitUpdate}).extend(ss)}var Da=o(k$1,h,g,n,i,j$1,c,b$1,a),Wa=o(a);async function Qa(t){let e=Ks({environment:t.environment,apiKey:t.apiKey,onRateLimitUpdate:t.onRateLimitUpdate}),r=await Ka(e,t),s=await e.beginAuthentication({wallet:r,credentials:t.credentials,nonce:t.nonce},t.signer).then(Ba$1(t.signer));if(s.account.walletType===WalletType.EOA||await Ga(s,{wallet:s.account.wallet,type:s.account.walletType}))return s;if(s.account.walletType===WalletType.DEPOSIT_WALLET)return await Ha(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 Ka(t,e){if(e.wallet!==void 0)return e.wallet;let r=expectEvmAddress(await e.signer.getAddress()),s=N$1(r,t.environment.walletDerivation);return await Ga(t,{wallet:s,type:WalletType.DEPOSIT_WALLET})?s:O(r,t.environment.walletDerivation)}async function Ha(t){let e=O(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 Ja(t)).wait();}
2
- export{Da as CreateSecureClientError,Wa as SetupGaslessWalletError,Re as accountActions,ss as allActions,ge as analyticsActions,ns as buildHmacSignature,Ks as createPublicClient,Qa as createSecureClient,ve as dataActions,qe as discoveryActions,Wo as forkEnvironmentConfig,Ae as perpsActions,Qu as preproduction,we as production,Io as relayerApiKey,Oo as remoteBuilderSigning,Ce as rewardsActions,es as rfqActions,ts as sessionKeyActions,Ee as subscriptionsActions,rs as tradingActions,ke as walletActions};//# sourceMappingURL=index.js.map
1
+ import {Q,_,Y as Y$1,W,ua,sa as sa$1,cf,af,_e,Ye,Nc,We,Ue,Se as Se$1,Pc,Lc,Jc,Hc,yb,qa as qa$1,ed,id,sd,gd,ac,_b,Yb,Wb,Ub,Sb,Qb,Ob,Cb,Ab,zc,Bc,rc,pc,nc,Sf,Vg,Jg,Hg,ug,Tg,Rg,Pg,Ng,Vc,yg,wg,cd,ad,_c,Yc,xc,vc,tc,Zd,Pe as Pe$1,Qe as Qe$1,Me,Le as Le$1,Oe,oa,ma,ka as ka$1,ia as ia$1,ga as ga$1,ea,fg,dg,bg,_f,Fg,Bg,Dg,Lg,U as U$1,S,qd,od,md,kd,Pd,yd,xd,Xd,Vd,Td,Rd,kc,gc,Qf,Hf,vf,Zg,ab,Ya as Ya$1,gb,db,Ba as Ba$1,Ga as Ga$1,N as N$1,O,Ja as Ja$1,Ce as Ce$1,Ae as Ae$1,ye,ue,se,qe as qe$1,Ee as Ee$1,we as we$1,ec,cc,J as J$1,$d,I,Ca,L as L$1,ob,mb,ge as ge$1,de,fe,be,ce,ae,qb,oe,Tf,Vf,Xf,ee,M as M$1,Bd,Dd,Ed,Cd,zd,Ad}from'./chunk-5JHFOBBZ.js';export{cg as AcceptComboQuoteError,$a as ApproveErc1155ForAllError,Xa as ApproveErc20Error,_d as ApprovePerpsBuilderFeeError,ke as ArmPerpsAutoCancelError,Cg as AuthorizeSessionKeyError,Qc as BiggestWinnerKind,Rc as BuilderVolumeInterval,nd as CancelAllError,pd as CancelMarketOrdersError,jd as CancelOrderError,ld as CancelOrdersError,lc as CollateralReturnKnownOperationKind,E as CombinatorialPrepareConditionCallError,ig as ComboAcceptFailureReason,va as ComboActivityType,df as ComboPositionSortBy,ef as ComboPositionStatus,jg as ComboQuoteUnavailableReason,Ud as CreateLimitOrderError,Qd as CreateMarketOrderError,u as CtfMergePositionsCallError,w as CtfRedeemPositionsCallError,s as CtfSplitPositionCallError,Ie as DepositToPerpsError,bf as DownloadAccountingSnapshotError,Z as DropNotificationsError,b as Erc20ApprovalCallError,m as Erc20TransferCallError,rd as EstimateMarketPriceError,jc as ExecuteCollateralReturnPlanError,Ic as FetchBuilderVolumeError,P as FetchClosedOnlyModeError,oc as FetchCommentsByIdError,uc as FetchEventError,Ac as FetchEventLiveVolumeError,wc as FetchEventTagsError,Zb as FetchLastTradePriceError,$b as FetchLastTradePricesError,$c as FetchMarketError,bd as FetchMarketTagsError,zb as FetchMidpointError,Bb as FetchMidpointsError,X as FetchNotificationsError,hd as FetchOpenInterestError,Rb as FetchOrderBookError,Tb as FetchOrderBooksError,T as FetchOrderError,da as FetchOrderScoringError,fa as FetchOrdersScoringError,ve as FetchPerpsBookError,he as FetchPerpsBuilderApprovalsError,je as FetchPerpsBuilderEarningsSummaryError,Yd as FetchPerpsBuilderStatusError,De as FetchPerpsFeesError,pe as FetchPerpsInstrumentsError,re as FetchPerpsTickerError,te as FetchPerpsTickersError,Ve as FetchPortfolioValueError,Nb as FetchPriceError,Pb as FetchPricesError,Rf as FetchPublicProfileError,Sg as FetchRelatedTagResourcesError,Qg as FetchRelatedTagsError,yc as FetchResolutionsError,na as FetchRewardPercentagesError,gg as FetchRfqStatusError,xg as FetchSeriesError,Ag as FetchSessionKeysError,Ig as FetchSportsMarketTypesError,Vb as FetchSpreadError,Xb as FetchSpreadsError,Og as FetchTagError,ja as FetchTotalEarningsForUserForDayError,Mc as FetchTraderLeaderboardStandingError,cb as FetchTradingApprovalsStateError,Ze as FetchUserPnlError,Xe as FetchUserStatsError,$e as FetchUserVolumeError,Sc as LeaderboardWindow,V as ListAccountTradesError,ra as ListActivityError,Oc as ListBiggestWinnersError,Gc as ListBuilderLeaderboardError,xb as ListBuilderTradesError,ta as ListComboActivityError,Zc as ListComboMarketsError,Te as ListComboPositionsError,qc as ListCommentsByUserAddressError,mc as ListCommentsError,bc as ListCurrentRewardsError,sc as ListEventsError,dd as ListMarketHoldersError,dc as ListMarketRewardsError,Xc as ListMarketsError,R as ListOpenOrdersError,ie as ListPerpsBuilderEarningsError,xe as ListPerpsCandlesError,ze as ListPerpsFundingHistoryError,Be as ListPerpsTradesError,Re as ListPositionsError,fd as ListPriceHistoryError,vg as ListSeriesError,Gg as ListSportsError,Mg as ListTagsError,Ug as ListTeamsError,Kc as ListTraderLeaderboardError,pa as ListTradesError,la as ListUserEarningsAndMarketsConfigError,ha as ListUserEarningsForDayError,a as MAX_UINT256,Cf as MergePositionsError,Fe as OpenPerpsSessionError,Zf as OpenRfqSessionError,q as PerpsDepositCallError,Wd as PlaceLimitOrderError,Sd as PlaceMarketOrderError,fc as PlanCollateralReturnError,ff as PositionFilterType,gf as PositionSortBy,hf as PositionStatus,vd as PostOrderError,wd as PostOrdersError,Wc as PriceHistoryInterval,Pf as RedeemPositionsError,ag as RequestComboQuoteError,Cc as ResolutionMarketType,Dc as ResolutionReporter,Ec as ResolutionSource,Fc as ResolutionStatus,ne as RevokePerpsBuilderFeeError,Ge as RevokePerpsCredentialsError,Eg as RevokeSessionKeyError,Wf as RfqCancelQuoteError,Vf as RfqCancelQuoteRejectedError,kg as RfqConfirmationDecision,Yf as RfqConfirmationError,Xf as RfqConfirmationRejectedError,lg as RfqDirection,mg as RfqExecutionStatus,ng as RfqKnownErrorCode,Uf as RfqQuoteError,Tf as RfqQuoteRejectedError,og as RfqRejectionCode,$f as RfqRequestRejectedError,pg as RfqRequestedSizeUnit,qg as RfqSide,rg as RfqStatus,A as RouterMergeCallError,C as RouterRedeemCallError,y as RouterSplitCallError,tg as SearchError,sg as SearchSort,zg as SessionKeyKnownScope,fb as SetupTradingApprovalsError,K as SignerType,wa as SortDirection,qf as SplitPositionError,Kg as SubscribeError,xa as TipSide,ya as TradeFilterType,Tc as TraderLeaderboardSort,Yg as TransferErc20Error,Ke as TransferPerpsCollateralError,le as UpdatePerpsLeverageError,me as UpdatePerpsMarginError,if as UserPnlFidelity,jf as UserPnlInterval,eg as WaitForComboFillError,Od as WaitForOrderFillSettlementError,za as WaitForTransactionError,Je as WithdrawFromPerpsError,o as authorizeSessionSignerCall,F as combinatorialPrepareConditionCall,v as ctfMergePositionsCall,x as ctfRedeemPositionsCall,t as ctfSplitPositionCall,l as decodeErc1155BalanceOfBatchResult,j as decodeErc1155BalanceOfResult,h as decodeErc1155IsApprovedForAllResult,e as decodeErc20AllowanceResult,G as encodeProxyCall,H as encodeSafeMultisendCall,f as erc1155ApprovalForAllCall,k as erc1155BalanceOfBatchCall,i as erc1155BalanceOfCall,g as erc1155IsApprovedForAllCall,d as erc20AllowanceCall,c as erc20ApprovalCall,n as erc20TransferCall,Aa as expectTransactionHandle,r as perpsDepositCall,p as revokeSessionSignerCall,B as routerMergeCall,D as routerRedeemCall,z as routerSplitCall}from'./chunk-5JHFOBBZ.js';import {a,r,m,i,h,q,j as j$1,l,d,c,f}from'./chunk-VLNLVY4C.js';export{o as AutoCancelDailyLimitError,m as CancelledSigningError,f as ConnectionLostError,n as InsufficientLiquidityError,k as OperationAbortedError,b as PaginationLimitError,p as PerpsCancelRetryError,i as RateLimitError,s as RealtimeKnownErrorCode,h as RequestRejectedError,q as SigningError,j as TimeoutError,g as TradingRestriction,l as TransactionFailedError,d as TransportError,c as UnexpectedResponseError,a as UserInputError,e as WebSocketKnownCloseCode,r as makeErrorGuard}from'./chunk-VLNLVY4C.js';import {DecimalishSchema,ApiKeySchema,EvmAddressSchema,toBaseUnits,OrderSide}from'@polymarket/bindings';export{CommentParentEntityType,OrderSide,OrderType}from'@polymarket/bindings';export{AssetType,NotificationType,OrderPostStatus,OrderResponseErrorCode,SignatureType}from'@polymarket/bindings/clob';export{ActivityType}from'@polymarket/bindings/data';import {WalletType}from'@polymarket/bindings/gamma';export{ComboKnownStatus,ProtocolVersion,TeamOrdering,WalletType}from'@polymarket/bindings/gamma';export{PerpsDepositStatus,PerpsInstrumentCategory,PerpsInstrumentType,PerpsInternalTransferDirection,PerpsKlineInterval,PerpsKnownCancelOrderErrorCode,PerpsKnownInternalTransferType,PerpsKnownWithdrawalStatus,PerpsLiquidityRole,PerpsMarginType,PerpsNotificationOrderType,PerpsNotificationType,PerpsOrderStatus,PerpsSide,PerpsSortDirection,PerpsTimeInForce}from'@polymarket/bindings/perps';import {z}from'zod';import {expectEvmAddress,isSameEvmAddress,expectEvmSignature,invariant,setNonBlockingTimeout}from'@polymarket/types';import {TypedData}from'ox';import {PerpsMarketDataEventSchema,RealtimeEventSchema,SportsResultEventSchema,MarketEventSchema,UserEventSchema,RealtimeKnownErrorCode,PolyboltAckOp,PolyboltAckSchema,PolyboltEnvelopeSchema,parsePolyboltEvent,PolyboltChannel}from'@polymarket/bindings/subscriptions';import {pushable}from'it-pushable';import {RfqQuoterInboundMessageSchema,RfqConfirmationDecision,RfqRequestedSizeUnit,RfqDirection}from'@polymarket/bindings/combos';var Ko=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 Ho(t){return new Se(t)}function _o(t){return new Pe(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.#t(e)}catch(r){throw q.fromError(r,"Could not authorize the builder-authenticated request")}}async#s(){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#t(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.#s(),method:"POST",mode:"cors"});if(!r.ok)throw new Error(`Remote signer rejected request with status ${r.status}`);return Ko.parse(await r.json())}},Pe=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 ts(t){let e={chainId:t.chainId,name:"ClobAuthDomain",version:"1"};return {domain:e,message:{address:t.address,message:"This message attests that I control the given wallet",nonce:t.nonce??0,timestamp:`${t.timestamp}`},primaryType:"ClobAuth",types:{EIP712Domain:TypedData.extractEip712DomainTypes(e),ClobAuth:[{name:"address",type:"address"},{name:"timestamp",type:"string"},{name:"nonce",type:"uint256"},{name:"message",type:"string"}]}}}function zo(t){return {listPositions:Se$1.bind(null,t),listComboPositions:Ue.bind(null,t),fetchPortfolioValue:We.bind(null,t),fetchTraderLeaderboardStanding:Nc.bind(null,t),fetchUserStats:Ye.bind(null,t),fetchUserPnl:_e.bind(null,t),fetchUserVolume:af.bind(null,t),downloadAccountingSnapshot:cf.bind(null,t),listActivity:sa$1.bind(null,t),listComboActivity:ua.bind(null,t)}}function P(t,e={}){return e===null||typeof e!="object"||Array.isArray(e)?e:{...e,user:e.user===void 0?t.account.wallet:e.user}}function Re(t){let e=zo(t);return t.isPublicClient()?e:{...e,listPositions:r=>Se$1(t,P(t,r)),listComboPositions:r=>Ue(t,P(t,r)),fetchPortfolioValue:r=>We(t,P(t,r)),fetchTraderLeaderboardStanding:r=>Nc(t,P(t,r)),fetchUserStats:r=>Ye(t,P(t,r)),fetchUserPnl:r=>_e(t,P(t,r)),fetchUserVolume:r=>af(t,P(t,r)),downloadAccountingSnapshot:r=>cf(t,P(t,r)),listActivity:r=>sa$1(t,P(t,r)),listComboActivity:r=>ua(t,P(t,r)),listAccountTrades:W.bind(null,t),fetchNotifications:Y$1.bind(null,t),dropNotifications:_.bind(null,t),fetchClosedOnlyMode:Q.bind(null,t)}}function ge(t){return {listBuilderTrades:yb.bind(null,t),listBuilderLeaderboard:Hc.bind(null,t),fetchBuilderVolume:Jc.bind(null,t),listTraderLeaderboard:Lc.bind(null,t),listBiggestWinners:Pc.bind(null,t)}}function ve(t){return {fetchEventLiveVolume:Bc.bind(null,t),fetchResolutions:zc.bind(null,t),fetchMidpoint:Ab.bind(null,t),fetchMidpoints:Cb.bind(null,t),fetchPrice:Ob.bind(null,t),fetchPrices:Qb.bind(null,t),fetchOrderBook:Sb.bind(null,t),fetchOrderBooks:Ub.bind(null,t),fetchSpread:Wb.bind(null,t),fetchSpreads:Yb.bind(null,t),fetchLastTradePrice:_b.bind(null,t),fetchLastTradePrices:ac.bind(null,t),listPriceHistory:gd.bind(null,t),estimateMarketPrice:sd.bind(null,t),fetchOpenInterest:id.bind(null,t),listMarketHolders:ed.bind(null,t),listTrades:qa$1.bind(null,t)}}function qe(t){return {listEvents:tc.bind(null,t),fetchEvent:vc.bind(null,t),fetchEventTags:xc.bind(null,t),listMarkets:Yc.bind(null,t),listComboMarkets:_c.bind(null,t),fetchMarket:ad.bind(null,t),fetchMarketTags:cd.bind(null,t),listSeries:wg.bind(null,t),fetchSeries:yg.bind(null,t),listMarketClarifications:Vc.bind(null,t),listTags:Ng.bind(null,t),fetchTag:Pg.bind(null,t),fetchRelatedTags:Rg.bind(null,t),fetchRelatedTagResources:Tg.bind(null,t),search:ug.bind(null,t),listSports:Hg.bind(null,t),fetchSportsMarketTypes:Jg.bind(null,t),listTeams:Vg.bind(null,t),fetchPublicProfile:Sf.bind(null,t),listComments:nc.bind(null,t),fetchCommentsById:pc.bind(null,t),listCommentsByUserAddress:rc.bind(null,t)}}function Ae(t){let e={fetchPerpsBuilderStatus:Zd.bind(null,t),fetchPerpsBook:r=>we$1(t,r),fetchPerpsFees:()=>Ee$1(t),fetchPerpsInstruments:r=>qe$1(t,r),fetchPerpsTicker:r=>se(t,r),fetchPerpsTickers:r=>ue(t,r),listPerpsCandles:r=>ye(t,r),listPerpsFundingHistory:r=>Ae$1(t,r),listPerpsTrades:r=>Ce$1(t,r)};return t.isSecureClient()?{...e,depositToPerps:r=>Oe(t,r),openPerpsSession:r=>Le$1(t,r),revokePerpsCredentials:r=>Me(t,r),transferPerpsCollateral:Qe$1.bind(null,t),withdrawFromPerps:r=>Pe$1(t,r)}:e}function Vo(t){return {listCurrentRewards:cc.bind(null,t),listMarketRewards:ec.bind(null,t)}}function Ce(t){let e=Vo(t);return t.isPublicClient()?e:{...e,fetchOrderScoring:ea.bind(null,t),fetchOrdersScoring:ga$1.bind(null,t),listUserEarningsForDay:ia$1.bind(null,t),fetchTotalEarningsForUserForDay:ka$1.bind(null,t),listUserEarningsAndMarketsConfig:ma.bind(null,t),fetchRewardPercentages:oa.bind(null,t)}}function rs(t){return {openRfqSession(){return _f(t)},requestComboQuote(e){return bg(t,e)},acceptComboQuote(e){return dg(t,e)},waitForComboFill(e){return fg(t,e)}}}function ss(t){return {authorizeSessionKey:Dg.bind(null,t),fetchSessionKeys:Bg.bind(null,t),revokeSessionKey:Fg.bind(null,t)}}function Ee(t){return t.isSecureClient()?{subscribe(e){return Lg(t,e)}}:{subscribe(e){return Lg(t,e)}}}function is(t){return {createMarketOrder:Rd.bind(null,t),placeMarketOrder:Td.bind(null,t),createLimitOrder:Vd.bind(null,t),placeLimitOrder:Xd.bind(null,t),postOrder:xd(t),postOrders:yd(t),waitForOrderFillSettlement:Pd.bind(null,t),cancelOrder:kd.bind(null,t),cancelOrders:md.bind(null,t),cancelAll:od.bind(null,t),cancelMarketOrders:qd.bind(null,t),listOpenOrders:S.bind(null,t),fetchOrder:U$1.bind(null,t)}}function No(t){return {fetchTradingApprovalsState:db.bind(null,t)}}function ke(t){let e=No(t);return t.isPublicClient()?e:{...e,fetchTradingApprovalsState:()=>db(t,{user:t.account.wallet}),setupTradingApprovals:gb.bind(null,t),approveErc20:Ya$1.bind(null,t),approveErc1155ForAll:ab.bind(null,t),transferErc20:Zg.bind(null,t),splitPosition:vf.bind(null,t),mergePositions:Hf.bind(null,t),redeemPositions:Qf.bind(null,t),planCollateralReturn:gc.bind(null,t),executeCollateralReturnPlan:kc.bind(null,t)}}function ns(t){return t.isSecureClient()?{...Re(t),...ge(t),...ve(t),...qe(t),...Ae(t),...Ce(t),...rs(t),...ss(t),...Ee(t),...is(t),...ke(t)}:{...Re(t),...ge(t),...ve(t),...qe(t),...Ae(t),...Ce(t),...Ee(t),...ke(t)}}var we={name:"production",chainId:137,rpc:"https://polygon.drpc.org",walletDerivation:{depositWalletFactory:expectEvmAddress("0x00000000000Fb5C9ADea0298D729A0CB3823Cc07"),depositWalletBeacon:expectEvmAddress("0x7A18EDfe055488A3128f01F563e5B479D92ffc3a"),depositWalletImplementation:expectEvmAddress("0x58CA52ebe0DadfdF531Cde7062e76746de4Db1eB"),proxyFactory:expectEvmAddress("0xaB45c5A4B0c941a2F231C04C3f49182e1A254052"),proxyImplementation:expectEvmAddress("0x44e999d5c2F66Ef0861317f9A4805AC2e90aEB4f"),safeFactory:expectEvmAddress("0xaacFeEa03eb1561C4e67d661e40682Bd20E3541b"),safeInitCodeHash:"0x2bce2127ff07fb632d16c8347c4ebf501f4841168bed00d9e6ef715ddb6fcecf"},contracts:{collateralToken:expectEvmAddress("0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB"),conditionalTokens:expectEvmAddress("0x4D97DCd97eC945f40cF65F87097ACe5EA0476045"),negRiskAdapter:expectEvmAddress("0xd91E80cF2E7be2e162c6513ceD06f1dD0dA35296"),collateralAdapter:expectEvmAddress("0xAdA100Db00Ca00073811820692005400218FcE1f"),negRiskCollateralAdapter:expectEvmAddress("0xadA2005600Dec949baf300f4C6120000bDB6eAab"),standardExchange:expectEvmAddress("0xE111180000d2663C0091e4f400237545B87B996B"),negRiskExchange:expectEvmAddress("0xe2222d279d744050d28e00520010520000310F59"),exchangeV3:expectEvmAddress("0xe3333700cA9d93003F00f0F71f8515005F6c00Aa"),protocolV2Router:expectEvmAddress("0x12121212006e4CD160D18e3f00711DA5c3372600"),binaryModule:expectEvmAddress("0x1000008dD9001B968442c1000017eaE6E0dA00Ba"),negRiskModule:expectEvmAddress("0x200000900045e3B6259600682756002200028933"),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",builderGateway:{rest:"https://combos-rfq-gateway-builder.polymarket.com"},collateralReturn:{rest:"https://combos-rfq-collateral-return.polymarket.com"}},perps:{rest:"https://api.perpetuals.polymarket.com",ws:"wss://ws.perpetuals.polymarket.com/v1/ws"},realtime:{ws:"wss://ws-live-v2.polymarket.com/ws"},rtds:{ws:"wss://ws-live-data.polymarket.com"},sports:{ws:"wss://sports-api.polymarket.com/ws"},relayerMaxPolls:100,relayerPollFrequencyMs:2e3};function $o(t,e=we){return {...e,...t,walletDerivation:{...e.walletDerivation,...t.walletDerivation},contracts:{...e.contracts,...t.contracts},clob:{...k(e.clob,t.clob),market:L(e.clob.market,t.clob?.market),user:L(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:{...os(e.combos,t.combos),builderGateway:k(e.combos.builderGateway,t.combos?.builderGateway),collateralReturn:k(e.combos.collateralReturn,t.combos?.collateralReturn)},perps:os(e.perps,t.perps),realtime:L(e.realtime,t.realtime),rtds:L(e.rtds,t.rtds),sports:L(e.sports,t.sports)}}function k(t,e){return {...t,...e,headers:Te(t.headers,e?.headers)}}function L(t,e){return {...t,...e,headers:Te(t.headers,e?.headers)}}function os(t,e){return {...t,...e,headers:Te(t.headers,e?.headers)}}function Te(t,e){if(!(t===void 0&&e===void 0))return {...t,...e}}var td=$o({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 as(t,e,r,s,i){let n=`${e}${r}${s}`;i!==void 0&&(n+=i);let o=await globalThis.crypto.subtle.importKey("raw",Go(t),{name:"HMAC",hash:"SHA-256"},false,["sign"]),a=await globalThis.crypto.subtle.sign("HMAC",o,new TextEncoder().encode(n));return Jo(Yo(a))}function Go(t){let e=t.replace(/-/g,"+").replace(/_/g,"/").replace(/[^A-Za-z0-9+/=]/g,""),r=atob(e),s=new Uint8Array(r.length);for(let i=0;i<r.length;i+=1)s[i]=r.charCodeAt(i);return s.buffer}function Yo(t){let e=new Uint8Array(t),r="";for(let s of e)r+=String.fromCharCode(s);return btoa(r)}function Jo(t){return t.replace(/\+/g,"-").replace(/\//g,"_")}function R(t,e){let r;return {close:()=>(r===void 0&&(r=Promise.resolve(t.return()).then(()=>e())),r),[Symbol.asyncIterator](){return t[Symbol.asyncIterator]()}}}var b=class{#e=new Set;#s;constructor(e){this.#s=e?.deriveServerState??(()=>{});}add(e,r={}){let s={queue:pushable({objectMode:true})};r.matches!==void 0&&(s.matches=r.matches);let i={subscription:e,subscriber:s};return {change:this.#t(i),entry:i}}#t(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.#s(this.#e)}};function xe(t,e,r){let s=H(r.assetsIds,e.assetsIds),i=H(e.assetsIds,r.assetsIds);s.length>0&&t(cs(s,r.customFeatureEnabled));let n=r.assetsIds[0];s.length===0&&e.customFeatureEnabled!==r.customFeatureEnabled&&n!==void 0&&t(cs([n],r.customFeatureEnabled)),i.length>0&&t(Xo(i));}function Fe(t,e,r){if(r.includeAllMarkets){!e.includeAllMarkets&&e.markets.length>0&&t(ds(e.markets));return}if(e.includeAllMarkets){r.markets.length>0&&t(us(r.markets));return}let s=H(r.markets,e.markets),i=H(e.markets,r.markets);s.length>0&&t(us(s)),i.length>0&&t(ds(i));}function ps(t){let e=new Set,r=false;for(let{subscription:s}of t){for(let i of s.assetIds??s.tokenIds)e.add(i);r||=s.customFeatureEnabled===true;}return {assetsIds:Array.from(e),customFeatureEnabled:r}}function ls(t){let e=false,r=new Set;for(let{subscription:s}of t){if(bs(s)){e=true;continue}for(let i of s.markets??[])r.add(i);}return {includeAllMarkets:e,markets:e?[]:Array.from(r)}}function ms(t){return {assets_ids:t.assetsIds,custom_feature_enabled:t.customFeatureEnabled,type:"market"}}function cs(t,e){return {assets_ids:t,custom_feature_enabled:e,operation:"subscribe"}}function Xo(t){return {assets_ids:t,operation:"unsubscribe"}}function hs(t,e){let r={auth:{apiKey:e.key,passphrase:e.passphrase,secret:e.secret},type:"user"};return t.includeAllMarkets||(r.markets=t.markets),r}function us(t){return {markets:t,operation:"subscribe"}}function ds(t){return {markets:t,operation:"unsubscribe"}}function ys(t){let e=t.assetIds??t.tokenIds;return r=>{switch(r.type){case "price_change":return r.payload.priceChanges.some(s=>e.includes(s.assetId));case "new_market":return t.customFeatureEnabled===true;case "market_resolved":return t.customFeatureEnabled===true&&(r.payload.assetIds??[]).some(s=>e.includes(s));case "best_bid_ask":return t.customFeatureEnabled===true&&e.includes(r.payload.assetId);default:return e.includes(r.payload.assetId)}}}function fs(t){if(bs(t))return ()=>true;let e=new Set((t.markets??[]).map(r=>r.toLowerCase()));return r=>e.has(r.payload.market.toLowerCase())}function bs(t){return (t.markets?.length??0)===0}function H(t,e){let r=new Set(e);return t.filter(s=>!r.has(s))}var A=class{#e;#s;#t;#a=new ge$1({heartbeat:new ae});#o=new fe;#r=new b({deriveServerState:ps});constructor(e){this.#e=e.headers,this.#s=e.url;}async subscribe(e){let{change:r,entry:s}=this.#r.add(e,{matches:ys(e)});return await this.#i(s,r),R(s.subscriber.queue,()=>this.#n(s))}async#i(e,r){let{before:s,after:i}=r;try{(await this.#c()).reusedOpenSocket&&xe(o=>this.#a.send(o),s,i);}catch(n){throw await this.#n(e),n}}async#n(e){let{before:r,after:s}=this.#r.remove(e);if(!this.#r.hasActiveSubscriptions()){await this.close();return}xe(i=>this.#a.send(i),r,s);}async close(){this.#t===void 0&&(this.#t=this.#d().finally(()=>{this.#t=void 0;})),await this.#t;}async#d(){this.#o.stop(),this.#r.endAll(),await this.#a.close();}#c(){return this.#a.connect({onConnectionLost:()=>this.#l(),onError:()=>this.#m(),onMessage:e=>this.#p(e),onOpen:()=>this.#u(),headers:this.#e,url:this.#s})}#u(){this.#o.resetBackoff(),this.#y();}#p(e){let r=Array.isArray(e)?e:[e];for(let s of r){let i=MarketEventSchema.safeParse(s);i.success&&this.#r.dispatch(i.data);}}#l(){this.#r.hasActiveSubscriptions()&&this.#h();}#m(){}#y(){this.#a.send(ms(this.#r.serverState()));}#h(){this.#o.schedule({reconnect:()=>this.#c(),shouldReconnect:()=>this.#r.hasActiveSubscriptions()});}};var w=class{#e;#s;#t;#a;#o=new ge$1({heartbeat:new ae});#r=new fe;#i=new b({deriveServerState:ls});constructor(e){this.#e=e.credentials,this.#s=e.headers,this.#t=e.url;}async subscribe(e){let{change:r,entry:s}=this.#i.add(e,{matches:fs(e)});return await this.#n(s,r),R(s.subscriber.queue,()=>this.#d(s))}async#n(e,r){let{before:s,after:i}=r;try{(await this.#u()).reusedOpenSocket&&Fe(o=>this.#o.send(o),s,i);}catch(n){throw await this.#d(e),n}}async#d(e){let{before:r,after:s}=this.#i.remove(e);if(!this.#i.hasActiveSubscriptions()){await this.close();return}Fe(i=>this.#o.send(i),r,s);}async close(){this.#a===void 0&&(this.#a=this.#c().finally(()=>{this.#a=void 0;})),await this.#a;}async#c(){this.#r.stop(),this.#i.endAll(),await this.#o.close();}#u(){return this.#o.connect({onConnectionLost:()=>this.#m(),onError:()=>this.#y(),onMessage:e=>this.#l(e),onOpen:e=>this.#p(e),prepare:()=>this.#e,headers:this.#s,url:this.#t})}#p(e){this.#r.resetBackoff(),this.#h(e);}#l(e){let r=Array.isArray(e)?e:[e];for(let s of r){let i=UserEventSchema.safeParse(s);i.success&&this.#i.dispatch(i.data);}}#m(){this.#i.hasActiveSubscriptions()&&this.#f();}#y(){}#h(e){this.#o.send(hs(this.#i.serverState(),e));}#f(){this.#r.schedule({reconnect:()=>this.#u(),shouldReconnect:()=>this.#i.hasActiveSubscriptions()});}};var T=class{#e;#s;#t;#a;#o=new Set;#r=new Set;#i=new Set;#n=false;constructor(e){this.#e=e.chainId,this.#s=e.headers,this.#t=e.restUrl,this.#a=e.wsUrl;}connect(e,r,s,i){if(this.#n)return Promise.reject(new d("Perps session manager has been shut down."));let n=new oe({builderAttribution:r,approveBuilderFee:s,includeBuilderFills:i,chainId:this.#e,credentials:e,headers:this.#s,onClose:a=>this.#d(a),restUrl:this.#t,wsUrl:this.#a});this.#r.add(n);let o;return o=(async()=>{try{if(await n.connect(),this.#n)throw await n.close(),new d("Perps session manager has been shut down.");return this.#o.add(n),n}catch(a){throw await n.close(),a}finally{this.#i.delete(o),this.#r.delete(n);}})(),this.#i.add(o),o}async shutdown(){this.#n=true;let e=Array.from(this.#o),r=Array.from(this.#r),s=Array.from(this.#i);this.#o.clear(),this.#r.clear(),this.#i.clear(),await Promise.allSettled([...e.map(i=>i.close()),...r.map(i=>i.close()),...s.map(i=>i.catch(()=>{}))]).then(()=>{});}#d(e){this.#o.delete(e),this.#r.delete(e);}};var C=class{#e;#s;#t;#a=1;#o=new ge$1({heartbeat:new de});#r=new fe;#i=new b({deriveServerState:sa});constructor(e){this.#e=e.headers,this.#s=e.url;}async subscribe(e){let{change:r,entry:s}=this.#i.add(e,{matches:na(e)});return await this.#n(s,r),R(s.subscriber.queue,()=>this.#d(s))}async#n(e,r){try{(await this.#u()).reusedOpenSocket&&(this.#h(Ss(r.before,r.after)),this.#f(Ps(r.before,r.after)));}catch(s){throw await this.#d(e),s}}async#d(e){let{before:r,after:s}=this.#i.remove(e);this.#h(Ss(r,s)),this.#f(Ps(r,s)),this.#i.hasActiveSubscriptions()||await this.close();}async close(){this.#t===void 0&&(this.#t=this.#c().finally(()=>{this.#t=void 0;})),await this.#t;}async#c(){this.#r.stop(),this.#i.endAll(),await this.#o.close();}#u(){return this.#o.connect({onConnectionLost:()=>this.#m(),onError:()=>this.#y(),onMessage:e=>this.#l(e),onOpen:()=>this.#p(),headers:this.#e,url:this.#s})}#p(){this.#r.resetBackoff(),this.#h(Array.from(this.#i.serverState()));}#l(e){let r=PerpsMarketDataEventSchema.safeParse(e);r.success&&this.#i.dispatch(r.data);}#m(){this.#i.hasActiveSubscriptions()&&this.#S();}#y(){}#h(e){e.length!==0&&this.#o.send(this.#b("sub",e));}#f(e){e.length!==0&&this.#o.send(this.#b("unsub",e));}#b(e,r){return {id:this.#a++,req:e,chs:r}}#S(){this.#r.schedule({reconnect:()=>this.#u(),shouldReconnect:()=>this.#i.hasActiveSubscriptions()});}};function sa(t){let e=new Set,r=new Set,s=new Set,i=false,n=false;for(let{subscription:o}of t)switch(o.topic){case "perps.tickers":o.instrumentId===void 0?i=true:r.add(o.instrumentId);break;case "perps.statistics":o.instrumentId===void 0?n=true:s.add(o.instrumentId);break;default:e.add(ia(o));}if(i)e.add("tickers::all");else for(let o of r)e.add(`tickers::${o}`);if(n)e.add("statistics::all");else for(let o of s)e.add(`statistics::${o}`);return e}function Ss(t,e){return Array.from(e).filter(r=>!t.has(r))}function Ps(t,e){return Array.from(t).filter(r=>!e.has(r))}function ia(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 na(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 gs(t){if(t.topic==="prices.equity"){let e=t.symbol.toLowerCase();return [{key:JSON.stringify([t.topic,e]),topic:t.topic,symbol:e}]}return t.symbols.map(e=>t.topic==="prices.crypto.twap"?{key:JSON.stringify([t.topic,e,60]),topic:t.topic,symbol:e,windowSeconds:60}:{key:JSON.stringify([t.topic,e]),topic:t.topic,symbol:e})}function vs(t,e){return Math.random()*(t===4003?1e4:Math.min(1e3*2**e,3e4))}var j=class{#e;#s=new fe;#t=new Map;#a=[];#o;#r;#i=false;#n=false;#d=false;#c=false;#u;#p=0;#l=64;#m=Number.NEGATIVE_INFINITY;constructor(e){this.#e=e;}get size(){return this.#t.size}has(e){return this.#t.has(e)}get closed(){return this.#n}get keyTarget(){return Date.now()-this.#m>=6e4?64:this.#l}add(e,r){clearTimeout(this.#r);let s=this.#t.get(e.key);if(s===void 0){let{promise:i,resolve:n,reject:o}=Promise.withResolvers();i.catch(()=>{}),s={subscription:e,listeners:new Set,ready:i,resolve:n,reject:o,subscribed:false,accepted:false},this.#t.set(e.key,s),this.#i&&this.#f("subscribe",[s]);}return s.listeners.add(r),s.snapshot!==void 0&&r.event(s.snapshot),!this.#i&&!this.#c&&this.#u===void 0&&!this.#s.isScheduled&&this.#y(),aa(s.ready)}remove(e,r){let s=this.#t.get(e);s!==void 0&&(s.listeners.delete(r),!(s.listeners.size>0)&&(this.#t.delete(e),s.reject(new d("Realtime subscription closed.")),this.#i&&this.#f("unsubscribe",[s]),this.#t.size===0&&(this.#r=setNonBlockingTimeout(()=>{this.close();},1e3))));}#y(){if(this.#n||this.#c)return Promise.resolve();if(this.#u!==void 0)return this.#u;let e=this.#h().catch(r=>{this.#A([...this.#t.values()].filter(s=>!s.accepted),d.fromError(r));}).finally(()=>{this.#u===e&&(this.#u=void 0),this.#i||this.#q(1006);});return this.#u=e,e}async#h(){let e=this.#p;if(await this.#e.open({event:r=>this.#R(r),dropped:()=>this.#g(),disconnected:r=>this.#v(r)}),!(this.#n||e!==this.#p))try{if(await this.#e.authorize(),this.#n||e!==this.#p)return;this.#i=!0,this.#f("subscribe",[...this.#t.values()]);}catch(r){if(this.#n||e!==this.#p)return;r instanceof h&&r.code!==RealtimeKnownErrorCode.AuthUnavailable?this.#E(r):await this.#C(1006);}}#f(e,r){if(r.length===0)return;let s=this.#a.at(-1);s?.op===e?s.keys.push(...r):this.#a.push({op:e,keys:r}),this.#b();}#b(){this.#o!==void 0||this.#d||!this.#i||this.#n||(this.#o=setNonBlockingTimeout(()=>{this.#o=void 0,this.#S();},10));}async#S(){if(!this.#i||this.#n)return;let e=this.#a.shift();if(e===void 0)return;let r=[...new Set(e.keys)].filter(i=>e.op==="unsubscribe"||this.#t.get(i.subscription.key)===i);if(r.length===0){this.#b();return}let s=this.#p;this.#d=true;try{let i=await this.#e.change(e.op,r.map(({subscription:n})=>n));if(s!==this.#p||this.#n)return;if(e.op==="unsubscribe"&&i.length>0){let n=i[0];if(n!==void 0)throw n.error}if(e.op==="subscribe"){this.#s.resetBackoff();let n=new Set(i.map(o=>o.key));for(let o of r)n.has(o.subscription.key)||(o.subscribed=!0,o.accepted=!0,o.resolve());for(let{key:o,error:a}of i){let c=r.find(u=>u.subscription.key===o);c!==void 0&&this.#A([c],a,!1);}}}catch(i){if(s!==this.#p||this.#n)return;i instanceof h&&e.op==="subscribe"?this.#A(r,i):await this.#C(1006);}finally{this.#d=false,this.#b();}}#R(e){for(let r of this.#t.values()){let s=r.subscription;if(s.topic!==e.topic)continue;let i=e.payload;if(i.symbol.toLowerCase()===s.symbol&&!(s.topic==="prices.crypto.twap"&&(!("windowSeconds"in i)||i.windowSeconds!==s.windowSeconds))){r.snapshot=ca(r.snapshot,e);for(let n of r.listeners)n.event(e);}}}#g(){let e=Date.now();e-this.#m<5e3||(this.#l=Math.max(1,Math.floor(this.keyTarget/2)),this.#m=e);}#P(){this.#p++,this.#i=false,this.#a=[],clearTimeout(this.#o),this.#o=void 0;for(let e of this.#t.values()){if(e.snapshot=void 0,!e.subscribed)continue;let{promise:r,resolve:s,reject:i}=Promise.withResolvers();r.catch(()=>{}),e.ready=r,e.resolve=s,e.reject=i,e.subscribed=false;}}#v(e){let r=new f("Realtime connection closed.",e);this.#P(),e.code===4001||e.code===4008?this.#E(r):this.#q(e.code);}async#C(e){this.#c=true,this.#P();try{await this.#e.close();}finally{this.#c=false,this.#q(e);}}#q(e){this.#s.schedule({delayPolicy:r=>vs(e,r),shouldReconnect:()=>!this.#n&&this.#t.size>0,reconnect:()=>this.#y()});}#E(e){let r=[...this.#t.values()],s=new Set(r.flatMap(i=>[...i.listeners]));for(let i of r)i.reject(e);for(let i of s)i.end(e);this.close();}#A(e,r,s=true){let i=e.filter(o=>this.#t.get(o.subscription.key)===o),n=new Set(i.flatMap(o=>[...o.listeners]));for(let o of i)this.#t.delete(o.subscription.key),o.reject(r);s&&this.#i&&this.#f("unsubscribe",i);for(let o of n)o.end(r);this.#t.size===0&&(this.#r=setNonBlockingTimeout(()=>{this.close();},1e3));}async close(){if(this.#n)return;this.#n=true,this.#s.stop(),clearTimeout(this.#r);let e=new d("Realtime connection closed.");this.#P();for(let r of this.#t.values())r.reject(e);this.#t.clear(),await this.#e.close();}};function aa(t){return new Promise((e,r)=>{let s=setNonBlockingTimeout(()=>{r(new d("Realtime subscription was not accepted within 30 seconds."));},3e4);t.then(()=>{clearTimeout(s),e();},i=>{clearTimeout(s),r(i);});})}function ca(t,e){if(e.type==="subscribe")return e;let r=t?.type==="subscribe"?t.payload.data:[],{symbol:s,timestamp:i,value:n}=e.payload;if((r.at(-1)?.timestamp??0)>i)return t;let o=[...r.filter(a=>a.timestamp>i-12e4&&a.timestamp<i),{timestamp:i,value:n}];return e.topic==="prices.crypto.twap"?{...e,type:"subscribe",payload:{symbol:s,data:o,windowSeconds:e.payload.windowSeconds}}:{...e,type:"subscribe",payload:{symbol:s,data:o}}}var V=class{#e;#s=new ge$1({heartbeat:new ee,connectTimeoutMs:1e4,closeTimeoutMs:1e3});#t=new Map;#a;#o=0;#r=0;#i=0;constructor(e){this.#e=e;}async open(e){this.#a=e;let r=this.#i;await this.#s.connect({url:this.#e.url,headers:this.#e.headers,onOpen:()=>{},onError:()=>{},onConnectionLost:s=>{r===this.#i&&(this.#c(new f("Realtime connection closed.",s)),e.disconnected(s));},onMessage:s=>{r===this.#i&&this.#d(s);}});}async authorize(){let{key:e,secret:r,passphrase:s}=this.#e.credentials;await this.#n({op:"auth",auth:{apiKey:e,secret:r,passphrase:s}},PolyboltAckOp.Authed,[]);}async change(e,r){let s=[],i=0;for(;i<r.length;){let n=[];for(;i+n.length<r.length;){let a=r[i+n.length];if(a===void 0)break;let c=la(a),u={op:e,subscriptions:[...n,c],rid:String(this.#o+1)};if(n.length>0&&new TextEncoder().encode(JSON.stringify(u)).length>6e4)break;n.push(c);}let o=await this.#n({op:e,subscriptions:n},e==="subscribe"?PolyboltAckOp.Subscribed:PolyboltAckOp.Unsubscribed,n.map(({channel:a})=>a));for(let{index:a,error:c}of o){let u=r[i+a];u!==void 0&&s.push({key:u.key,error:c});}i+=n.length;}return s}#n(e,r,s){let i=String(++this.#o);return new Promise((n,o)=>{let a={op:r,channels:[...s],rejections:[],resolve:n,reject:o};this.#t.set(i,a),a.sendTimer=setNonBlockingTimeout(()=>{a.timer=setNonBlockingTimeout(()=>{this.#t.delete(i),o(new d("Realtime acknowledgement timed out after 10 seconds."));},1e4),this.#r=Date.now();try{if(!this.#s.send({...e,rid:i}))throw new d("Realtime connection is not open.")}catch(c){clearTimeout(a.timer),this.#t.delete(i),o(d.fromError(c));}},Math.max(0,110-(Date.now()-this.#r)));})}#d(e){let r=PolyboltAckSchema.safeParse(e);if(r.success){let{op:n,rid:o,code:a,channel:c}=r.data,u=o===void 0?void 0:this.#t.get(o);if(u===void 0)return;if(n===PolyboltAckOp.Error&&a!==void 0){let S=new h(`Realtime subscription rejected: ${a}`,{status:200,code:a}),l=u.channels.flatMap((y,Z)=>y===c?[Z]:[]);if(c===void 0||l.length!==1)u.reject(S);else {let y=l[0];if(y===void 0||(u.channels[y]=void 0,u.rejections.push({index:y,error:S}),u.channels.some(Z=>Z!==void 0)))return;u.resolve(u.rejections);}}else if(n===u.op){if(u.channels.length>0){let S=u.channels.indexOf(c??"");if(S<0||(u.channels[S]=void 0,u.channels.some(l=>l!==void 0)))return}u.resolve(u.rejections);}else return;clearTimeout(u.timer),o!==void 0&&this.#t.delete(o);return}let s=PolyboltEnvelopeSchema.safeParse(e);if(!s.success)return;let i=parsePolyboltEvent(s.data);i!==void 0&&this.#a?.event(i),(s.data.dropped??0)>0&&this.#a?.dropped();}#c(e){for(let r of this.#t.values())clearTimeout(r.sendTimer),clearTimeout(r.timer),r.reject(e);this.#t.clear();}async close(){this.#i++,this.#a=void 0,this.#c(new d("Realtime connection closed.")),await this.#s.close();}};function la(t){switch(t.topic){case "prices.crypto":return {channel:PolyboltChannel.Crypto,filter:{symbol:t.symbol}};case "prices.crypto.twap":return {channel:PolyboltChannel.Twap,filter:{symbol:t.symbol,window_seconds:t.windowSeconds}};case "prices.equity":return {channel:PolyboltChannel.Equity,filter:{symbol:t.symbol}}}}var N=class{#e;#s=new Set;#t=new Set;constructor(e){this.#e=e;}async subscribe(e){let r=[...new Map(gs(e).map(c=>[c.key,c])).values()],s=pushable({objectMode:true}),i=[],n=false,o,a=async()=>{if(!n){n=true;for(let c of i)c();o===void 0?await s.return():s.end(o),this.#t.delete(a);}};this.#t.add(a);try{await Promise.all(r.map(c=>{let u=this.#a(c.key),S={event(l){if(n||"types"in e&&e.types!==void 0&&e.types.length>0&&!e.types.includes(l.type))return;let y="symbol"in l.payload?{...l.payload,symbol:"symbol"in c?c.symbol:l.payload.symbol}:l.payload;s.push({...l,payload:y});},end(l){o=l,s.end(l),a();}};return i.push(()=>u.remove(c.key,S)),u.add(c,S)}));}catch(c){throw await a(),c}return {close:a,async*[Symbol.asyncIterator](){try{yield*s;}finally{await a();}}}}#a(e){for(let s of this.#s)if(s.closed)this.#s.delete(s);else if(s.has(e))return s;for(let s of this.#s)if(s.size<s.keyTarget)return s;let r=new j(new V(this.#e));return this.#s.add(r),r}async close(){await Promise.all([...this.#t].map(r=>r()));let e=[...this.#s];this.#s.clear(),await Promise.all(e.map(r=>r.close()));}};var B=class{#e;constructor(e){this.#e=new N(e);}async subscribe(e){return this.#e.subscribe(e)}async close(){await this.#e.close();}};function Cs(t,e){return {...e,quote:r=>t.quote(e,r)}}function Es(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 ks(t){return {quoteId:t.quoteId,rfqId:t.rfqId}}function ws(t){return {quoteId:t.quoteId,rfqId:t.rfqId}}function Ts(t){return {quoteId:t.quoteId,rfqId:t.rfqId}}function xs(t,e){let r=M$1(t);return {auth:{apiKey:e.key,passphrase:e.passphrase,secret:e.secret},identity:{maker_address:r.maker,signature_type:r.signatureType,signer_address:r.signer},type:"auth"}}function Fs(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 Ms(t,e,r){let s=M$1(t);return {maker_address:s.maker,quote_id:r,rfq_id:e,signer_address:s.signer,type:"RFQ_QUOTE_CANCEL"}}function Os(t,e,r){return {decision:r,quote_id:e,rfq_id:t,type:"RFQ_CONFIRMATION_RESPONSE"}}var $=class{#e=new Map;#s;constructor(e){this.#s=e;}waitFor(e,r){let s=ya(),i,n=setNonBlockingTimeout(()=>{this.remove(e,i),s.reject(new j$1(r));},this.#s);i=s.promise.finally(()=>clearTimeout(n));let o=this.#e.get(e)??[];return o.push({...s,promise:i}),this.#e.set(e,o),i}resolve(e,r){let s=this.#e.get(e),i=s?.shift();i!==void 0&&(s!==void 0&&s.length===0&&this.#e.delete(e),i.resolve(r));}reject(e,r){let s=this.#e.get(e),i=s?.shift();i!==void 0&&(s!==void 0&&s.length===0&&this.#e.delete(e),i.reject(r));}remove(e,r){let s=this.#e.get(e);if(s===void 0)return;let i=s.filter(n=>n.promise!==r);i.length===0?this.#e.delete(e):this.#e.set(e,i);}rejectAll(e){for(let r of this.#e.values())for(let s of r)s.reject(e);this.#e.clear();}};function ya(){let t,e;return {promise:new Promise((s,i)=>{t=s,e=i;}),reject:e,resolve:t}}var Ls="0x0000000000000000000000000000000000000000000000000000000000000000";async function Bs(t){let e=M$1(t.account),r=Bd({chainId:t.chainId,exchange:t.exchange}),s={builder:Ls,maker:e.maker,makerAmount:toBaseUnits(Cd(t.orderSide,t.orderPrice,t.size)),metadata:Ls,salt:fa().toString(),side:Ed(t.orderSide),signatureType:e.signatureType,signer:e.signer,takerAmount:toBaseUnits(Dd(t.orderSide,t.orderPrice,t.size)),timestamp:Math.floor(Date.now()/1e3).toString(),tokenId:t.tokenId},i;try{i=await t.signer.signTypedData(zd({domain:r,order:s}));}catch(n){throw q.fromError(n,"Could not sign the RFQ quote order.")}return {...s,signature:Ad({domain:r,order:s,signature:i})}}function fa(){let t=new Uint8Array(8);return globalThis.crypto.getRandomValues(t),BigInt(`0x${Array.from(t,e=>e.toString(16).padStart(2,"0")).join("")}`)}var Ws=DecimalishSchema.transform(t=>Hs(t)).refine(t=>t<=BigInt(Number.MAX_SAFE_INTEGER),{message:"Value exceeds the temporary numeric wire limit."}),Pa=z.strictObject({price:Ws.refine(t=>t<1000000n,{message:"Price must be less than 1."}),size:Ws.optional(),source:z.enum(["collateral","inventory"]).default("collateral")});function Qs(t){return I(t,Pa)}async function Ks(t){let e=t.response.price,r=t.response.size===void 0?qa(t.request.requestedSize,e):t.response.size,s=await Bs({account:t.account,chainId:t.chainId,exchange:t.exchange,orderPrice:ga(t.request,t.response.source,e),orderSide:va(t.response.source),signer:t.signer,size:r,tokenId:Ra(t.request,t.response.source)});return {price:e,signedOrder:s,size:r}}function Ra(t,e){return t.direction===RfqDirection.Buy?e==="collateral"?t.noPositionId:t.yesPositionId:e==="collateral"?t.yesPositionId:t.noPositionId}function ga(t,e,r){return t.direction===RfqDirection.Buy&&e==="collateral"||t.direction===RfqDirection.Sell&&e==="inventory"?1000000n-r:r}function va(t){return t==="collateral"?OrderSide.BUY:OrderSide.SELL}function qa(t,e){let r=Hs(t.value);return t.unit===RfqRequestedSizeUnit.Shares?r:r*1000000n/e}function Hs(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 i=BigInt(r)*1000000n+BigInt(s.padEnd(6,"0"));if(i<=0n)throw new a("Value must be greater than 0.");return i}var ka=3e4,wa=3e4,x=class{#e;#s;#t;#a;#o;#r;#i;#n;#d;#c;#u=false;constructor(e){this.#e=e.account,this.#s=e.chainId,this.#t=e.credentials,this.#a=e.exchange,this.#o=e.headers,this.#r=e.signer,this.#i=e.url;}async connect(){if(this.#u)throw new d("RFQ quoter manager has been shut down.");if(this.#n!==void 0){if(!this.#n.closed)return this.#n;this.#n=void 0;}if(this.#c!==void 0)return this.#c;let e=new Be({account:this.#e,chainId:this.#s,credentials:this.#t,exchange:this.#a,headers:this.#o,onClose:()=>this.#p(e),signer:this.#r,url:this.#i});this.#d=e;let r;return r=(async()=>{try{if(await e.connect(),this.#u)throw await e.close(),new d("RFQ quoter manager has been shut down.");return this.#n=e,e}catch(s){throw await e.close(),s}finally{this.#c===r&&(this.#c=void 0),this.#d===e&&(this.#d=void 0);}})(),this.#c=r,r}async shutdown(){this.#u=true;let e=this.#n,r=this.#d,s=this.#c;this.#n=void 0,this.#d=void 0,this.#c=void 0,await Promise.allSettled([e?.close(),r?.close(),s?.catch(()=>{})]).then(()=>{});}#p(e){this.#n===e&&(this.#n=void 0),this.#d===e&&(this.#d=void 0);}},Be=class{#e;#s;#t;#a;#o;#r;#i;#n;#d=new ge$1;#c=pushable({objectMode:true});#u=new $(wa);#p;#l;constructor(e){this.#e=e.account,this.#s=e.chainId,this.#t=e.credentials,this.#a=e.exchange,this.#o=e.headers,this.#r=e.onClose,this.#i=e.signer,this.#n=e.url;}get closed(){return this.#p!==void 0}async connect(){let e=Ta();this.#l=e;let r=setNonBlockingTimeout(()=>{e.reject(new d("RFQ quoter authentication timed out."));},ka);try{await this.#d.connect({headers:this.#o,onConnectionLost:s=>this.#P(s),onError:()=>{},onMessage:s=>this.#R(s),onOpen:()=>this.#S(),url:this.#n}),await e.promise;}finally{clearTimeout(r),this.#l=void 0;}}async#m(e){if(!this.#d.send(e))throw new d("RFQ quoter websocket is not open.")}async close(){this.#p===void 0&&(this.#p=this.#y()),await this.#p;}[Symbol.asyncIterator](){return this.#c[Symbol.asyncIterator]()}async#y(){let e=new d("RFQ quoter websocket closed.");this.#b(e),this.#c.end(),await this.#d.close(),this.#r();}async#h(e){this.#p===void 0&&(this.#p=this.#f(e)),await this.#p;}async#f(e){this.#b(e),this.#c.end(e),await this.#d.close(),this.#r();}#b(e){this.#l?.reject(e),this.#u.rejectAll(e);}#S(){this.#d.send(xs(this.#e,this.#t));}#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.#g(s);return;case "quote_request":this.#c.push(Cs(this,s));return;case "quote_ack":this.#u.resolve(G(s.rfqId),ks(s));return;case "quote_cancel_ack":this.#u.resolve(Ie(s.rfqId,s.quoteId),ws(s));return;case "confirmation_request":this.#c.push(Es(this,s));return;case "confirmation_ack":this.#u.resolve(Le(s.rfqId,s.quoteId),Ts(s));return;case "execution_update":this.#c.push(s);return;case "trade":this.#c.push(s);return;case "rfq_error":this.#v(s);return}}#g(e){if(e.success===true){this.#l?.resolve(void 0);return}this.#l?.reject(new d(`RFQ quoter authentication failed: ${e.error}`));}#P(e){this.#h(new f("RFQ quoter connection lost.",e));}#v(e){if(e.requestType==="RFQ_QUOTE"){if(e.rfqId===void 0){this.#h(new d("Uncorrelated RFQ quoter error."));return}this.#u.reject(G(e.rfqId),new Tf(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.#h(new d("Uncorrelated RFQ quoter error."));return}this.#u.reject(Ie(e.rfqId,e.quoteId),new Vf(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.#h(new d("Uncorrelated RFQ quoter error."));return}this.#u.reject(Le(e.rfqId,e.quoteId),new Xf(e.message,{code:e.code,errorId:e.errorId,quoteId:e.quoteId,rfqId:e.rfqId}));}}async quote(e,r){let s=Qs(r),i=await Ks({account:this.#e,chainId:this.#s,exchange:this.#a,request:e,response:s,signer:this.#i}),n=this.#u.waitFor(G(e.rfqId),`Timed out waiting for RFQ quote acknowledgement for ${e.rfqId}.`);try{return await this.#m(Fs(e,i)),await n}catch(o){throw this.#u.remove(G(e.rfqId),n),o}}async cancelQuote(e){let r=Ie(e.rfqId,e.quoteId),s=this.#u.waitFor(r,`Timed out waiting for RFQ quote cancellation acknowledgement for ${e.rfqId}.`);try{return await this.#m(Ms(this.#e,e.rfqId,e.quoteId)),await s}catch(i){throw this.#u.remove(r,s),i}}async respondToConfirmation(e,r,s){let i=Le(e,r),n=this.#u.waitFor(i,`Timed out waiting for RFQ confirmation acknowledgement for ${e}.`);try{return await this.#m(Os(e,r,s)),await n}catch(o){throw this.#u.remove(i,n),o}}};function G(t){return `ACK_RFQ_QUOTE:${t}`}function Ie(t,e){return `ACK_RFQ_QUOTE_CANCEL:${t}:${e}`}function Le(t,e){return `ACK_RFQ_CONFIRMATION_RESPONSE:${t}:${e}`}function Ta(){let t,e;return {promise:new Promise((s,i)=>{t=s,e=i;}),reject:e,resolve:t}}var F=class{#e;#s;#t;#a=new ge$1({heartbeat:new be});#o=new fe;#r=new b({deriveServerState:Oa});constructor(e){this.#e=e.headers,this.#s=e.url;}async subscribe(e){let{change:r,entry:s}=this.#r.add(e,{matches:Da(e)});return await this.#i(s,r),R(s.subscriber.queue,()=>this.#n(s))}async#i(e,r){try{if((await this.#c()).reusedOpenSocket){let{before:i,after:n}=r,o=Fa(i,n);this.#h(o);}}catch(s){throw await this.#n(e),s}}async#n(e){let{before:r,after:s}=this.#r.remove(e),i=Ma(r,s);this.#f(i),this.#r.hasActiveSubscriptions()||await this.close();}async close(){this.#t===void 0&&(this.#t=this.#d().finally(()=>{this.#t=void 0;})),await this.#t;}async#d(){this.#o.stop(),this.#r.endAll(),await this.#a.close();}#c(){return this.#a.connect({onConnectionLost:()=>this.#l(),onError:()=>this.#m(),onMessage:e=>this.#p(e),onOpen:()=>this.#u(),headers:this.#e,url:this.#s})}#u(){this.#o.resetBackoff(),this.#y();}#p(e){let r=RealtimeEventSchema.safeParse(e);r.success&&this.#r.dispatch(r.data);}#l(){this.#r.hasActiveSubscriptions()&&this.#b();}#m(){}#y(){this.#h(Array.from(this.#r.serverState().values()));}#h(e){e.length!==0&&this.#a.send(Ia(e));}#f(e){e.length!==0&&this.#a.send(La(e));}#b(){this.#o.schedule({reconnect:()=>this.#c(),shouldReconnect:()=>this.#r.hasActiveSubscriptions()});}};function Fa(t,e){return Array.from(e).flatMap(([r,s])=>t.has(r)?[]:[s])}function Ma(t,e){return Array.from(t).flatMap(([r,s])=>e.has(r)?[]:[s])}function Oa(t){let e=new Map;for(let{subscription:r}of t)for(let s of Ba(r))e.has(s.key)||e.set(s.key,s);return e}function Ia(t){return {action:"subscribe",subscriptions:t.map(({topic:e,type:r})=>({topic:e,type:r}))}}function La(t){return {action:"unsubscribe",subscriptions:t.map(({topic:e,type:r})=>({topic:e,type:r}))}}function Ba(t){switch(t.topic){case "comments":return (t.types??["comment_created"]).map(e=>U("comments",e));case "prices.crypto.binance":return [U("crypto_prices","update")];case "prices.crypto.chainlink":return [U("crypto_prices_chainlink","update")];case "prices.crypto.chainlink.twap":return [U(Ua(t.windowSeconds),"update")];case "prices.equity.pyth":return [U("equity_prices","update")];default:invariant(false,`Unknown RTDS topic: ${String(t)}`);}}function Ua(t){switch(t){case 30:return "crypto_prices_twap_thirty";case 60:return "crypto_prices_twap_sixty";default:invariant(false,`Unknown TWAP window: ${String(t)}`);}}function U(t,e){return {key:`${t}:${e}`,topic:t,type:e}}function Da(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.crypto.chainlink.twap":return e=>e.topic==="prices.crypto.chainlink.twap"&&e.payload.windowSeconds===t.windowSeconds&&(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 M=class{#e;#s;#t;#a=new ge$1({heartbeat:new ce});#o=new fe;#r=new b;constructor(e){this.#e=e.headers,this.#s=e.url;}async subscribe(e){let{entry:r}=this.#r.add(e);return await this.#i(r),R(r.subscriber.queue,()=>this.#n(r))}async#i(e){try{await this.#c();}catch(r){throw await this.#n(e),r}}async#n(e){this.#r.remove(e),this.#r.hasActiveSubscriptions()||await this.close();}async close(){this.#t===void 0&&(this.#t=this.#d().finally(()=>{this.#t=void 0;})),await this.#t;}async#d(){this.#o.stop(),this.#r.endAll(),await this.#a.close();}#c(){return this.#a.connect({onConnectionLost:()=>this.#l(),onError:()=>this.#m(),onMessage:e=>this.#p(e),onOpen:()=>this.#u(),headers:this.#e,url:this.#s})}#u(){this.#o.resetBackoff();}#p(e){let r=SportsResultEventSchema.safeParse(e);r.success&&this.#r.dispatch(r.data);}#l(){this.#r.hasActiveSubscriptions()&&this.#y();}#m(){}#y(){this.#o.schedule({reconnect:()=>this.#c(),shouldReconnect:()=>this.#r.hasActiveSubscriptions()});}};var Y=class{#e;#s;get context(){return this.#e}get decorators(){return this.#s}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}get hasBuilderApiKey(){return this.context.apiKey?.isBuilderKey??false}constructor(e){this.#e=e,this.#s=[];}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.#s.push(e);}},za=z.object({key:ApiKeySchema,passphrase:z.string(),secret:z.string()}),Va=z.object({wallet:EvmAddressSchema,credentials:za.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}),J=class extends Y{constructor(e){super({apiKey:e.apiKey,environment:e.environment,onRateLimitUpdate:e.onRateLimitUpdate,data:new $d({headers:e.environment.data.headers,root:e.environment.data.rest}),gamma:new $d({headers:e.environment.gamma.headers,root:e.environment.gamma.rest}),clob:new $d({headers:e.environment.clob.headers,onRateLimitUpdate:e.onRateLimitUpdate,root:e.environment.clob.rest,resolveHeaders:r=>this.resolveClobHeaders(r)}),relayer:new $d({headers:e.environment.relayer.headers,root:e.environment.relayer.rest,resolveHeaders:r=>this.resolveRelayerHeaders(r)}),rfq:new $d({headers:e.environment.combos.headers,root:e.environment.combos.rest}),perps:new $d({headers:e.environment.perps.headers,root:e.environment.perps.rest}),rpc:new J$1({url:e.environment.rpc}),webSockets:{clobMarket:new A({headers:e.environment.clob.market.headers,url:e.environment.clob.market.ws}),sports:new M({headers:e.environment.sports.headers,url:e.environment.sports.ws}),rtds:new F({headers:e.environment.rtds.headers,url:e.environment.rtds.ws}),perpsSubscriptions:new C({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=I(e,Va);return Promise.resolve(async function*(){let i=Math.floor(Date.now()/1e3),n=s?.nonce??0,o=expectEvmAddress(yield Ca()),a=expectEvmAddress(s.wallet),c=L$1(this.environment,o,a);if(s.credentials!==void 0){let l=this.#e(s.credentials,c,r);try{if((await ob(l)).includes(s.credentials.key))return l}catch(y){if(!(y instanceof h)||y.status!==401)throw y}}let u=yield {kind:"signAuthMessage",payload:ts({address:o,chainId:this.environment.chainId,nonce:n,timestamp:i})},S=await mb(this,{address:o,nonce:n,signature:expectEvmSignature(u),timestamp:i});return this.#e(S,c,r)}.call(this))}#e(e,r,s){let i=new Qe({account:r,apiKey:this.context.apiKey,credentials:e,environment:this.environment,onRateLimitUpdate:this.context.onRateLimitUpdate,signer:s});for(let n of this.decorators)i.extend(n);return i}},Qe=class extends Y{#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){let r=new B({url:e.environment.realtime.ws,headers:e.environment.realtime.headers,credentials:e.credentials});super({account:e.account,credentials:e.credentials,apiKey:e.apiKey,environment:e.environment,onRateLimitUpdate:e.onRateLimitUpdate,signer:e.signer,clob:new $d({headers:e.environment.clob.headers,onRateLimitUpdate:e.onRateLimitUpdate,root:e.environment.clob.rest,resolveHeaders:s=>this.resolveClobHeaders(s)}),relayer:new $d({headers:e.environment.relayer.headers,root:e.environment.relayer.rest,resolveHeaders:s=>this.resolveRelayerHeaders(s)}),rpc:new J$1({url:e.environment.rpc}),gamma:new $d({headers:e.environment.gamma.headers,root:e.environment.gamma.rest}),data:new $d({headers:e.environment.data.headers,root:e.environment.data.rest}),rfq:new $d({headers:e.environment.combos.headers,root:e.environment.combos.rest}),perps:new $d({headers:e.environment.perps.headers,root:e.environment.perps.rest}),secureClob:new $d({headers:e.environment.clob.headers,onRateLimitUpdate:e.onRateLimitUpdate,resolveHeaders:async s=>({...await this.resolveClobHeaders(s),...await this.#t(s)}),root:e.environment.clob.rest}),combos:new $d({headers:e.environment.combos.collateralReturn.headers,resolveHeaders:s=>this.resolveRelayerHeaders(s),root:e.environment.combos.collateralReturn.rest}),builderGateway:new $d({headers:e.environment.combos.builderGateway.headers,resolveHeaders:async s=>({...await this.#s(s),...await this.#t(s)}),root:e.environment.combos.builderGateway.rest}),webSockets:{clobMarket:new A({headers:e.environment.clob.market.headers,url:e.environment.clob.market.ws}),clobUser:new w({credentials:e.credentials,headers:e.environment.clob.user.headers,url:e.environment.clob.user.ws}),rfqQuoter:new x({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 M({headers:e.environment.sports.headers,url:e.environment.sports.ws}),realtime:r,rtds:new F({headers:e.environment.rtds.headers,url:e.environment.rtds.ws}),perpsSubscriptions:new C({headers:e.environment.perps.headers,url:e.environment.perps.ws}),perpsSession:new T({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 builderGateway(){return this.context.builderGateway}get webSockets(){return this.context.webSockets}async closeSubscriptions(){await Promise.allSettled([this.webSockets.clobMarket.close(),this.webSockets.realtime.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:i,environment:n,onRateLimitUpdate:o}=this.context;try{await qb(this);}finally{this.endAuthenticationLifecycle(),await Promise.allSettled([e,r,s]).then(()=>{});}let a=new J({apiKey:i,environment:n,onRateLimitUpdate:o});for(let c of this.decorators)a.extend(c);return a}async#s(e){return e.method!=="GET"&&this.context.apiKey?.isBuilderKey?this.context.apiKey.authorize(e):{}}async#t(e){try{let r=Math.floor(Date.now()/1e3);return {POLY_ADDRESS:this.account.signer,POLY_API_KEY:this.credentials.key,POLY_PASSPHRASE:this.credentials.passphrase,POLY_SIGNATURE:await as(this.credentials.secret,r,e.method,e.path,e.body),POLY_TIMESTAMP:`${r}`}}catch(r){throw q.fromError(r,"Could not sign the L2-authenticated request")}}};function _s(t={}){return new J({environment:t.environment??we,apiKey:t.apiKey,onRateLimitUpdate:t.onRateLimitUpdate}).extend(ns)}var Na=r(m,i,h,q,j$1,l,d,c,a),$a=r(a);async function Ga(t){let e=_s({environment:t.environment,apiKey:t.apiKey,onRateLimitUpdate:t.onRateLimitUpdate}),r=await Ya(e,t),s=await e.beginAuthentication({wallet:r,credentials:t.credentials,nonce:t.nonce},t.signer).then(Ba$1(t.signer));if(s.account.walletType===WalletType.EOA||await Ga$1(s,{wallet:s.account.wallet,type:s.account.walletType}))return s;if(s.account.walletType===WalletType.DEPOSIT_WALLET)return await Ja(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 Ya(t,e){if(e.wallet!==void 0)return e.wallet;let r=expectEvmAddress(await e.signer.getAddress()),s=N$1(r,t.environment.walletDerivation);return await Ga$1(t,{wallet:s,type:WalletType.DEPOSIT_WALLET})?s:O(r,t.environment.walletDerivation)}async function Ja(t){let e=O(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 Ja$1(t)).wait();}
2
+ export{Na as CreateSecureClientError,$a as SetupGaslessWalletError,Re as accountActions,ns as allActions,ge as analyticsActions,as as buildHmacSignature,_s as createPublicClient,Ga as createSecureClient,ve as dataActions,qe as discoveryActions,$o as forkEnvironmentConfig,Ae as perpsActions,td as preproduction,we as production,_o as relayerApiKey,Ho as remoteBuilderSigning,Ce as rewardsActions,rs as rfqActions,ss as sessionKeyActions,Ee as subscriptionsActions,is as tradingActions,ke as walletActions};//# sourceMappingURL=index.js.map
3
3
  //# sourceMappingURL=index.js.map