@polymarket/client 0.1.0-beta.5 → 0.1.0-beta.6
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 +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import {la,va,ta,ra,Pa,ld,jd,hd,fd,ed,bd,fc,dc,bc,db,Na,pc,rc,Dc,Jb,Hb,Fb,Db,Bb,zb,xb,vb,tb,hb,fb,$b,Tb,Rb,Pb,Ud,Be,qe,oe as oe$1,ie as ie$1,ze,xe,ve,te,me,ke,nc,lc,jc,hc as hc$1,Zb,Xb,Vb,La,Ja,Ha,Fa,Da,Ba,ae as ae$1,re,pa,na,Bc,zc,xc,vc,Ic,Hc,$c,Zc,Xc,Vc,Sd,Nd,Ed,Fe,Za,Va,bb,Z,ca,Y,fa,tc,Nb,Lb,V,U as U$1,_ as _$1,W as W$1,L,J,N,Vd,Xd,Zd,X,Jc,Kc}from'./chunk-2ZZDFOKL.js';export{Ya as ApproveErc1155ForAllError,Ua as ApproveErc20Error,yc as CancelAllError,Ac as CancelMarketOrdersError,uc as CancelOrderError,wc as CancelOrdersError,A as CombinatorialPrepareConditionCallError,md as ComboPositionStatus,Yc as CreateLimitOrderError,Uc as CreateMarketOrderError,o as CtfRedeemPositionsCallError,kd as DownloadAccountingSnapshotError,ua as DropNotificationsError,b as Erc20ApprovalCallError,m as Erc20TransferCallError,Cc as EstimateMarketPriceError,ka as FetchClosedOnlyModeError,Qb as FetchCommentsByIdError,Wb as FetchEventError,_b as FetchEventLiveVolumeError,Yb as FetchEventTagsError,Eb as FetchLastTradePriceError,Gb as FetchLastTradePricesError,kc as FetchMarketError,mc as FetchMarketTagsError,eb as FetchMidpointError,gb as FetchMidpointsError,sa as FetchNotificationsError,wb as FetchOrderBookError,yb as FetchOrderBooksError,oa as FetchOrderError,Aa as FetchOrderScoringError,Ca as FetchOrdersScoringError,gd as FetchPortfolioValueError,sb as FetchPriceError,Ib as FetchPriceHistoryError,ub as FetchPricesError,Td as FetchPublicProfileError,ye as FetchRelatedTagResourcesError,we as FetchRelatedTagsError,Ka as FetchRewardPercentagesError,le as FetchSeriesError,pe as FetchSportsMarketTypesError,Ab as FetchSpreadError,Cb as FetchSpreadsError,ue as FetchTagError,Ga as FetchTotalEarningsForUserForDayError,id as FetchTradedMarketCountError,qa as ListAccountTradesError,Oa as ListActivityError,ac as ListBuilderLeaderboardError,cb as ListBuilderTradesError,cc as ListBuilderVolumeError,cd as ListClosedPositionsError,ic as ListComboMarketsError,dd as ListComboPositionsError,Sb as ListCommentsByUserAddressError,Ob as ListCommentsError,Kb as ListCurrentRewardsError,Ub as ListEventsError,oc as ListMarketHoldersError,sc as ListMarketPositionsError,Mb as ListMarketRewardsError,gc as ListMarketsError,qc as ListOpenInterestError,ma as ListOpenOrdersError,ad as ListPositionsError,je as ListSeriesError,ne as ListSportsError,se as ListTagsError,Ae as ListTeamsError,ec as ListTraderLeaderboardError,Ma as ListTradesError,Ia as ListUserEarningsAndMarketsConfigError,Ea as ListUserEarningsForDayError,a as MAX_UINT256,r as MergePositionsCallError,Id as MergePositionsError,w as MergeV2CallError,$d as OpenRfqSessionError,_c as PlaceLimitOrderError,Wc as PlaceMarketOrderError,Fc as PostOrderError,Gc as PostOrdersError,Rd as RedeemPositionsError,y as RedeemV2CallError,Yd as RfqCancelQuoteError,Xd as RfqCancelQuoteRejectedError,be as RfqConfirmationDecision,_d as RfqConfirmationError,Zd as RfqConfirmationRejectedError,ce as RfqDirection,de as RfqErrorCode,ee as RfqExecutionStatus,Wd as RfqQuoteError,Vd as RfqQuoteRejectedError,fe as RfqRequestedSizeUnit,ge as RfqSide,he as SearchError,ab as SetupTradingApprovalsError,p as SplitPositionCallError,zd as SplitPositionError,u as SplitV2CallError,Ee as TransferErc20Error,Qa as WaitForTransactionError,B as combinatorialPrepareConditionCall,t as ctfRedeemPositionsCall,l as decodeErc1155BalanceOfBatchResult,j as decodeErc1155BalanceOfResult,h as decodeErc1155IsApprovedForAllResult,e as decodeErc20AllowanceResult,C as encodeProxyCall,D as encodeSafeMultisendCall,f as erc1155ApprovalForAllCall,k as erc1155BalanceOfBatchCall,i as erc1155BalanceOfCall,g as erc1155IsApprovedForAllCall,d as erc20AllowanceCall,c as erc20ApprovalCall,n as erc20TransferCall,Ra as expectTransactionHandle,s as mergePositionsCall,x as mergeV2Call,z as redeemV2Call,q as splitPositionCall,v as splitV2Call}from'./chunk-2ZZDFOKL.js';import {a,k,h,e,d as d$1,j,f,g,c,b}from'./chunk-E2CLUN5M.js';export{h as CancelledSigningError,i as InsufficientLiquidityError,e as RateLimitError,d as RequestRejectedError,j as SigningError,f as TimeoutError,g as TransactionFailedError,c as TransportError,b as UnexpectedResponseError,a as UserInputError,k as makeErrorGuard}from'./chunk-E2CLUN5M.js';import {DecimalishSchema,ApiKeySchema,EvmAddressSchema,toBaseUnits,OrderSide}from'@polymarket/bindings';export{OrderSide,OrderType}from'@polymarket/bindings';export{SignatureType}from'@polymarket/bindings/clob';export{ActivityType}from'@polymarket/bindings/data';import {WalletType}from'@polymarket/bindings/gamma';export{WalletType}from'@polymarket/bindings/gamma';import {z}from'zod';import {expectEvmAddress,isSameEvmAddress,expectEvmSignature,ResultAsync,invariant,setNonBlockingInterval,setNonBlockingTimeout}from'@polymarket/types';import Ls from'ky';import {RealtimeEventSchema,SportsResultEventSchema,MarketEventSchema,UserEventSchema}from'@polymarket/bindings/subscriptions';import {pushable}from'it-pushable';import {RfqKnownInboundMessageSchema,RfqQuoterInboundMessageSchema,RfqConfirmationDecision,RfqRequestedSizeUnit,RfqDirection}from'@polymarket/bindings/rfq';var Cs=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 Es(t){return new ne(t)}function ks(t){return new se(t)}var ne=class{#e;constructor(e){this.#e=e;}get isBuilderKey(){return true}get supportGasless(){return true}async authorize(e){try{return await this.#r(e)}catch(r){throw j.fromError(r,"Could not authorize the builder-authenticated request")}}async#t(){let e=this.#e.headers,r=typeof e=="function"?await e():e,n=new Headers(r);return n.set("content-type","application/json"),n}async#r(e){let r=await fetch(this.#e.url,{body:JSON.stringify({body:e.body,method:e.method,path:e.path}),credentials:this.#e.credentials,headers:await this.#t(),method:"POST",mode:"cors"});if(!r.ok)throw new Error(`Remote signer rejected request with status ${r.status}`);return Cs.parse(await r.json())}},se=class{#e;constructor(e){this.#e=e;}get isBuilderKey(){return false}get supportGasless(){return true}authorize(){return Promise.resolve({RELAYER_API_KEY:this.#e.key,RELAYER_API_KEY_ADDRESS:this.#e.address})}};function tr(t){return {domain:{chainId:t.chainId,name:"ClobAuthDomain",version:"1"},message:{address:t.address,message:"This message attests that I control the given wallet",nonce:t.nonce??0,timestamp:`${t.timestamp}`},primaryType:"ClobAuth",types:{ClobAuth:[{name:"address",type:"address"},{name:"timestamp",type:"string"},{name:"nonce",type:"uint256"},{name:"message",type:"string"}]}}}function Ts(t){return {listPositions:bd.bind(null,t),listClosedPositions:ed.bind(null,t),listComboPositions:fd.bind(null,t),fetchPortfolioValue:hd.bind(null,t),fetchTradedMarketCount:jd.bind(null,t),downloadAccountingSnapshot:ld.bind(null,t),listMarketPositions:tc.bind(null,t),listActivity:Pa.bind(null,t)}}function y(t,e={}){return {...e,user:e.user??t.account.wallet}}function ie(t){let e=Ts(t);return t.isPublicClient()?e:{...e,listPositions:r=>bd(t,y(t,r)),listClosedPositions:r=>ed(t,y(t,r)),listComboPositions:r=>fd(t,y(t,r)),fetchPortfolioValue:r=>hd(t,y(t,r)),fetchTradedMarketCount:r=>jd(t,y(t,r)),downloadAccountingSnapshot:r=>ld(t,y(t,r)),listActivity:r=>Pa(t,y(t,r)),listAccountTrades:ra.bind(null,t),fetchNotifications:ta.bind(null,t),dropNotifications:va.bind(null,t),fetchClosedOnlyMode:la.bind(null,t)}}function oe(t){return {listBuilderTrades:db.bind(null,t),listBuilderLeaderboard:bc.bind(null,t),fetchBuilderVolume:dc.bind(null,t),listTraderLeaderboard:fc.bind(null,t)}}function ce(t){return {fetchEventLiveVolume:$b.bind(null,t),fetchMidpoint:fb.bind(null,t),fetchMidpoints:hb.bind(null,t),fetchPrice:tb.bind(null,t),fetchPrices:vb.bind(null,t),fetchOrderBook:xb.bind(null,t),fetchOrderBooks:zb.bind(null,t),fetchSpread:Bb.bind(null,t),fetchSpreads:Db.bind(null,t),fetchLastTradePrice:Fb.bind(null,t),fetchLastTradePrices:Hb.bind(null,t),fetchPriceHistory:Jb.bind(null,t),estimateMarketPrice:Dc.bind(null,t),listOpenInterest:rc.bind(null,t),listMarketHolders:pc.bind(null,t),listTrades:Na.bind(null,t)}}function ae(t){return {listEvents:Vb.bind(null,t),fetchEvent:Xb.bind(null,t),fetchEventTags:Zb.bind(null,t),listMarkets:hc$1.bind(null,t),listComboMarkets:jc.bind(null,t),fetchMarket:lc.bind(null,t),fetchMarketTags:nc.bind(null,t),listSeries:ke.bind(null,t),fetchSeries:me.bind(null,t),listTags:te.bind(null,t),fetchTag:ve.bind(null,t),fetchRelatedTags:xe.bind(null,t),fetchRelatedTagResources:ze.bind(null,t),search:ie$1.bind(null,t),listSports:oe$1.bind(null,t),fetchSportsMarketTypes:qe.bind(null,t),listTeams:Be.bind(null,t),fetchPublicProfile:Ud.bind(null,t),listComments:Pb.bind(null,t),fetchCommentsById:Rb.bind(null,t),listCommentsByUserAddress:Tb.bind(null,t)}}function ws(t){return {listCurrentRewards:Lb.bind(null,t),listMarketRewards:Nb.bind(null,t)}}function ue(t){let e=ws(t);return t.isPublicClient()?e:{...e,fetchOrderScoring:Ba.bind(null,t),fetchOrdersScoring:Da.bind(null,t),listUserEarningsForDay:Fa.bind(null,t),fetchTotalEarningsForUserForDay:Ha.bind(null,t),listUserEarningsAndMarketsConfig:Ja.bind(null,t),fetchRewardPercentages:La.bind(null,t)}}function rr(t){return {openRfqSession(){return ae$1(t)}}}function de(t){return t.isSecureClient()?{subscribe(e){return re(t,e)}}:{subscribe(e){return re(t,e)}}}function nr(t){return {createMarketOrder:Vc.bind(null,t),placeMarketOrder:Xc.bind(null,t),createLimitOrder:Zc.bind(null,t),placeLimitOrder:$c.bind(null,t),postOrder:Hc(t),postOrders:Ic(t),cancelOrder:vc.bind(null,t),cancelOrders:xc.bind(null,t),cancelAll:zc.bind(null,t),cancelMarketOrders:Bc.bind(null,t),listOpenOrders:na.bind(null,t),fetchOrder:pa.bind(null,t)}}function sr(t){return {isGaslessReady:()=>Promise.resolve(true),setupTradingApprovals:bb.bind(null,t),approveErc20:Va.bind(null,t),approveErc1155ForAll:Za.bind(null,t),transferErc20:Fe.bind(null,t),splitPosition:Ed.bind(null,t),mergePositions:Nd.bind(null,t),redeemPositions:Sd.bind(null,t)}}function ir(t){return t.isSecureClient()?{...ie(t),...oe(t),...ce(t),...ae(t),...ue(t),...rr(t),...de(t),...nr(t),...sr(t)}:{...ie(t),...oe(t),...ce(t),...ae(t),...ue(t),...de(t)}}var le={name:"production",chainId:137,rpc:"https://polygon.drpc.org",walletDerivation:{depositWalletFactory:expectEvmAddress("0x00000000000Fb5C9ADea0298D729A0CB3823Cc07"),depositWalletBeacon:expectEvmAddress("0x7A18EDfe055488A3128f01F563e5B479D92ffc3a"),depositWalletImplementation:expectEvmAddress("0x58CA52ebe0DadfdF531Cde7062e76746de4Db1eB"),proxyFactory:expectEvmAddress("0xaB45c5A4B0c941a2F231C04C3f49182e1A254052"),proxyImplementation:expectEvmAddress("0x44e999d5c2F66Ef0861317f9A4805AC2e90aEB4f"),safeFactory:expectEvmAddress("0xaacFeEa03eb1561C4e67d661e40682Bd20E3541b"),safeInitCodeHash:"0x2bce2127ff07fb632d16c8347c4ebf501f4841168bed00d9e6ef715ddb6fcecf"},collateralToken:expectEvmAddress("0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB"),conditionalTokens:expectEvmAddress("0x4D97DCd97eC945f40cF65F87097ACe5EA0476045"),negRiskAdapter:expectEvmAddress("0xd91E80cF2E7be2e162c6513ceD06f1dD0dA35296"),collateralAdapter:expectEvmAddress("0xAdA100Db00Ca00073811820692005400218FcE1f"),negRiskCollateralAdapter:expectEvmAddress("0xadA2005600Dec949baf300f4C6120000bDB6eAab"),standardExchange:expectEvmAddress("0xE111180000d2663C0091e4f400237545B87B996B"),negRiskExchange:expectEvmAddress("0xe2222d279d744050d28e00520010520000310F59"),exchangeV3:expectEvmAddress("0xe3333700cA9d93003F00f0F71f8515005F6c00Aa"),protocolV2Router:expectEvmAddress("0x12121212006e4CD160D18e3f00711DA5c3372600"),combinatorialModule:expectEvmAddress("0x30000034706c7d8e12009dab006be20000c031a8"),positionManager:expectEvmAddress("0x006F54F7f9A22e0000CC2AB60031000000ae9fEF"),autoRedeemOperator:expectEvmAddress("0xa1200000d0002264C9a1698e001292D00E1b00af"),safeMultisend:expectEvmAddress("0xA238CBeb142c10Ef7Ad8442C6D1f9E89e07e7761"),relayHub:expectEvmAddress("0xD216153c06E857cD7f72665E0aF1d7D82172F494"),clob:"https://clob.polymarket.com",clobMarketWs:"wss://ws-subscriptions-clob.polymarket.com/ws/market",clobUserWs:"wss://ws-subscriptions-clob.polymarket.com/ws/user",relayer:"https://relayer-v2.polymarket.com",gamma:"https://gamma-api.polymarket.com",data:"https://data-api.polymarket.com",rfq:"https://combos-rfq-api.polymarket.sh",rtdsWs:"wss://ws-live-data.polymarket.com",rfqQuoterWs:"wss://combos-rfq-gateway-quoter.polymarket.sh/ws/rfq",sportsWs:"wss://sports-api.polymarket.com/ws",relayerMaxPolls:100,relayerPollFrequencyMs:2e3},hc={...le,name:"preproduction",clob:"https://clob-preprod-int-v2.polymarket.com",data:"https://data-api-preprod-int.polymarket.com",gamma:"https://gamma-api-preprod-int.polymarket.com",relayer:"https://relayer-v2-preprod-int.polymarket.com"};async function or(t,e,r,n,s){let i=`${e}${r}${n}`;s!==void 0&&(i+=s);let o=await globalThis.crypto.subtle.importKey("raw",xs(t),{name:"HMAC",hash:"SHA-256"},false,["sign"]),b=await globalThis.crypto.subtle.sign("HMAC",o,new TextEncoder().encode(i));return Os(Ms(b))}function xs(t){let e=t.replace(/-/g,"+").replace(/_/g,"/").replace(/[^A-Za-z0-9+/=]/g,""),r=atob(e),n=new Uint8Array(r.length);for(let s=0;s<r.length;s+=1)n[s]=r.charCodeAt(s);return n.buffer}function Ms(t){let e=new Uint8Array(t),r="";for(let n of e)r+=String.fromCharCode(n);return btoa(r)}function Os(t){return t.replace(/\+/g,"-").replace(/\//g,"_")}var u=class{#e;#t;constructor({root:e,resolveHeaders:r}){this.#e=Ls.create({prefixUrl:e,throwHttpErrors:false}),this.#t=r;}get(e,r={}){return this.#s("GET",e,r)}post(e,r={}){return this.#s("POST",e,r)}del(e,r={}){return this.#s("DELETE",e,r)}#r(e){return e.startsWith("/")?e.slice(1):e}#s(e,r,n){return this.#o(this.#n(e,r,n))}async#n(e,r,n){let s=this.#a(e,r,n),i=await this.#t?.(s),o=this.#c(s.headers,i);return s.body!==void 0&&!o.has("content-type")&&o.set("content-type","application/json"),this.#e(this.#r(r),{body:s.body,headers:o,method:e,searchParams:s.params})}#a(e,r,n){return {body:"json"in n?this.#d(n.json):void 0,headers:n.headers,json:"json"in n?n.json:void 0,method:e,params:"params"in n?n.params:void 0,path:r}}#d(e){if(e!==void 0)return JSON.stringify(e)}#c(...e){let r=new Headers;for(let n of e)if(n!==void 0)for(let[s,i]of new Headers(n).entries())r.set(s,i);return r}#o(e$1){return ResultAsync.fromPromise(e$1.then(async r=>{if(r.ok)return r;if(r.status===429)throw new e(`Request to ${r.url} was rate limited`);let n=await this.#i(r);throw new d$1(n,{status:r.status})}),r=>r instanceof e||r instanceof d$1?r:c.fromError(r))}async#i(e){let r=e.headers.get("content-type")?.toLowerCase();if(r?.includes("application/json")){let{error:s}=await e.clone().json().catch(()=>({}));if(s)return `${String(s)} (${e.url})`}if(r?.includes("text/plain")){let s=await e.clone().text().then(i=>i.trim(),()=>"");if(s)return `${s} (${e.url})`}return e.headers.get("server")?.toLowerCase()?.includes("cloudflare")?`Request to ${e.url} was blocked by Cloudflare with status ${e.status}`:r?.includes("text/html")||r?.includes("application/xhtml+xml")?`Request to ${e.url} failed with status ${e.status} and an unexpected HTML response body`:`Request to ${e.url} failed with status ${e.status} and unreadable response body`}};function m(t,e){let r;return {close:()=>(r===void 0&&(r=Promise.resolve(t.return()).then(()=>e())),r),[Symbol.asyncIterator](){return t[Symbol.asyncIterator]()}}}var Fs=1e4,Bs=3e4,Ds=5e3,Ws=10*6e4,Qs=3e4,A=class{#e=0;#t;start(e){this.stop(),this.#e=Date.now(),this.#t=setNonBlockingInterval(()=>{e("PING");},Fs);}handleMessage(e){return e!=="PONG"?false:(this.#e=Date.now(),true)}isStale(e){return e-this.#e>Bs}stop(){this.#t!==void 0&&(clearInterval(this.#t),this.#t=void 0);}},F=class{#e=0;#t;start(e){this.stop(),this.#e=Date.now(),this.#t=setNonBlockingInterval(()=>{e("PING");},Ds);}handleMessage(){return this.#e=Date.now(),false}isStale(e){return e-this.#e>Ws}stop(){this.#t!==void 0&&(clearInterval(this.#t),this.#t=void 0);}},B=class{#e=0;#t;start(e){this.#e=Date.now(),this.#t=e;}stop(){this.#t=void 0;}handleMessage(e){return e!=="ping"?false:(this.#e=Date.now(),this.#t?.("pong"),true)}isStale(e){return e-this.#e>Qs}};var Hs=5e3,Ks=250,js=3e4,l=class{#e;#t=0;schedule(e){if(this.#e!==void 0||!e.shouldReconnect())return;let r=Vs(this.#t,{baseMs:Ks,maxMs:js});this.#t+=1,this.#e=setNonBlockingTimeout(()=>{this.#e=void 0,this.#r(e);},r);}stop(){this.#e!==void 0&&(clearTimeout(this.#e),this.#e=void 0);}resetBackoff(){this.#t=0,this.stop();}async#r(e){if(e.shouldReconnect())try{await e.reconnect();}catch{this.schedule(e);}}},d=class{#e;#t;#r;#s;constructor(e={}){this.#e=e.heartbeat;}connect(e){if(this.#t?.readyState===WebSocket.OPEN)return Promise.resolve({reusedOpenSocket:true});if(this.#c(),this.#r!==void 0)return this.#r;let n=this.#a(e).then(()=>({reusedOpenSocket:false})).catch(s=>{throw this.#r===n&&(this.#r=void 0),s});return this.#r=n,n}send(e){return this.#n(JSON.stringify(e))}#n(e){return this.#t?.readyState!==WebSocket.OPEN?false:(this.#t.send(e),true)}async close(){let e=await this.#u();this.#i(),!(e===void 0||e.readyState===WebSocket.CLOSED)&&await new Promise(r=>{e.addEventListener("close",()=>r(),{once:true}),e.readyState!==WebSocket.CLOSING&&e.close();});}async#a(e){let r=await e.prepare?.();return new Promise((n,s)=>{let i=Ns(e.url,e.headers),o=()=>{i.removeEventListener("error",b),this.#d(i),this.#o(),e.onOpen(r),n(i);},b=R=>{i.removeEventListener("open",o),s(new c(`WebSocket connection failed: ${e.url}`,{cause:R}));};i.addEventListener("open",o,{once:true}),i.addEventListener("error",b,{once:true}),i.addEventListener("message",R=>{if(this.#t!==i)return;let x=String(R.data);if(this.#e?.handleMessage(x))return;let M;try{M=JSON.parse(x);}catch{return}e.onMessage(M);}),i.addEventListener("close",()=>{this.#t===i&&(this.#c(),e.onClose());}),i.addEventListener("error",()=>e.onError());})}#d(e){this.#t=e,this.#r=void 0;}#c(){this.#i(),this.#t=void 0;}#o(){this.#i();let e=this.#e;e!==void 0&&(e.start(r=>this.#n(r)),this.#s=setNonBlockingInterval(()=>{if(!e.isStale(Date.now()))return;let r=this.#t;r?.readyState===WebSocket.OPEN&&r.close();},Hs));}#i(){this.#s!==void 0&&(clearInterval(this.#s),this.#s=void 0),this.#e?.stop();}async#u(){let e=this.#t,r=this.#r;return this.#t=void 0,this.#r=void 0,e!==void 0?e:r?.then(()=>this.#t,()=>{})}};function Ns(t,e){if(e===void 0)return new WebSocket(t);try{let r=Reflect.construct(WebSocket,[t,{headers:e}]);if(r instanceof WebSocket)return r}catch(r){throw new c("WebSocket headers require a header-capable WebSocket implementation.",{cause:r})}throw new c("WebSocket headers require a header-capable WebSocket implementation.")}function Vs(t,e){let r=Math.min(e.baseMs*2**t,e.maxMs);return Math.random()*r}var p=class{#e=new Set;#t;constructor(e){this.#t=e?.deriveServerState??(()=>{});}add(e,r={}){let n={queue:pushable({objectMode:true})};r.matches!==void 0&&(n.matches=r.matches);let s={subscription:e,subscriber:n};return {change:this.#r(s),entry:s}}#r(e){let r=this.serverState();return this.#e.add(e),{before:r,after:this.serverState()}}remove(e){let r=this.serverState();return this.#e.delete(e),e.subscriber.queue.end(),{before:r,after:this.serverState()}}dispatch(e){for(let{subscriber:r}of this.#e)(r.matches===void 0||r.matches(e))&&r.queue.push(e);}hasActiveSubscriptions(){return this.#e.size>0}endAll(e){for(let{subscriber:r}of this.#e)r.queue.end(e);this.#e.clear();}serverState(){return this.#t(this.#e)}};function pe(t,e,r){let n=D(r.assetsIds,e.assetsIds),s=D(e.assetsIds,r.assetsIds);n.length>0&&t(ar(n,r.customFeatureEnabled));let i=r.assetsIds[0];n.length===0&&e.customFeatureEnabled!==r.customFeatureEnabled&&i!==void 0&&t(ar([i],r.customFeatureEnabled)),s.length>0&&t($s(s));}function fe(t,e,r){if(r.includeAllMarkets){!e.includeAllMarkets&&e.markets.length>0&&t(dr(e.markets));return}if(e.includeAllMarkets){r.markets.length>0&&t(ur(r.markets));return}let n=D(r.markets,e.markets),s=D(e.markets,r.markets);n.length>0&&t(ur(n)),s.length>0&&t(dr(s));}function lr(t){let e=new Set,r=false;for(let{subscription:n}of t){for(let s of n.tokenIds)e.add(s);r||=n.customFeatureEnabled===true;}return {assetsIds:Array.from(e),customFeatureEnabled:r}}function pr(t){let e=false,r=new Set;for(let{subscription:n}of t){if(Sr(n)){e=true;continue}for(let s of n.markets??[])r.add(s);}return {includeAllMarkets:e,markets:e?[]:Array.from(r)}}function fr(t){return {assets_ids:t.assetsIds,custom_feature_enabled:t.customFeatureEnabled,type:"market"}}function ar(t,e){return {assets_ids:t,custom_feature_enabled:e,operation:"subscribe"}}function $s(t){return {assets_ids:t,operation:"unsubscribe"}}function mr(t,e){return {auth:{apiKey:e.key,passphrase:e.passphrase,secret:e.secret},markets:t.markets,type:"user"}}function ur(t){return {markets:t,operation:"subscribe"}}function dr(t){return {markets:t,operation:"unsubscribe"}}function hr(t){return e=>{switch(e.type){case "price_change":return e.payload.priceChanges.some(r=>t.tokenIds.includes(r.tokenId));case "new_market":return t.customFeatureEnabled===true;case "market_resolved":return t.customFeatureEnabled===true&&(e.payload.tokenIds??[]).some(r=>t.tokenIds.includes(r));case "best_bid_ask":return t.customFeatureEnabled===true&&t.tokenIds.includes(e.payload.tokenId);default:return t.tokenIds.includes(e.payload.tokenId)}}}function yr(t){if(Sr(t))return ()=>true;let e=new Set((t.markets??[]).map(r=>r.toLowerCase()));return r=>e.has(r.payload.market.toLowerCase())}function Sr(t){return (t.markets?.length??0)===0}function D(t,e){let r=new Set(e);return t.filter(n=>!r.has(n))}var S=class{#e;#t;#r=new d({heartbeat:new A});#s=new l;#n=new p({deriveServerState:lr});constructor(e){this.#e=e.url;}async subscribe(e){let{change:r,entry:n}=this.#n.add(e,{matches:hr(e)});return await this.#a(n,r),m(n.subscriber.queue,()=>this.#d(n))}async#a(e,r){let{before:n,after:s}=r;try{(await this.#o()).reusedOpenSocket&&pe(o=>this.#r.send(o),n,s);}catch(i){throw await this.#d(e),i}}async#d(e){let{before:r,after:n}=this.#n.remove(e);if(!this.#n.hasActiveSubscriptions()){await this.close();return}pe(s=>this.#r.send(s),r,n);}async close(){this.#t===void 0&&(this.#t=this.#c().finally(()=>{this.#t=void 0;})),await this.#t;}async#c(){this.#s.stop(),this.#n.endAll(),await this.#r.close();}#o(){return this.#r.connect({onClose:()=>this.#l(),onError:()=>this.#p(),onMessage:e=>this.#u(e),onOpen:()=>this.#i(),url:this.#e})}#i(){this.#s.resetBackoff(),this.#f();}#u(e){let r=Array.isArray(e)?e:[e];for(let n of r){let s=MarketEventSchema.safeParse(n);s.success&&this.#n.dispatch(s.data);}}#l(){this.#n.hasActiveSubscriptions()&&this.#m();}#p(){}#f(){this.#r.send(fr(this.#n.serverState()));}#m(){this.#s.schedule({reconnect:()=>this.#o(),shouldReconnect:()=>this.#n.hasActiveSubscriptions()});}};var q=class{#e;#t;#r;#s=new d({heartbeat:new A});#n=new l;#a=new p({deriveServerState:pr});constructor(e){this.#e=e.url,this.#t=e.credentials;}async subscribe(e){let{change:r,entry:n}=this.#a.add(e,{matches:yr(e)});return await this.#d(n,r),m(n.subscriber.queue,()=>this.#c(n))}async#d(e,r){let{before:n,after:s}=r;try{(await this.#i()).reusedOpenSocket&&fe(o=>this.#s.send(o),n,s);}catch(i){throw await this.#c(e),i}}async#c(e){let{before:r,after:n}=this.#a.remove(e);if(!this.#a.hasActiveSubscriptions()){await this.close();return}fe(s=>this.#s.send(s),r,n);}async close(){this.#r===void 0&&(this.#r=this.#o().finally(()=>{this.#r=void 0;})),await this.#r;}async#o(){this.#n.stop(),this.#a.endAll(),await this.#s.close();}#i(){return this.#s.connect({onClose:()=>this.#p(),onError:()=>this.#f(),onMessage:e=>this.#l(e),onOpen:e=>this.#u(e),prepare:()=>this.#t,url:this.#e})}#u(e){this.#n.resetBackoff(),this.#m(e);}#l(e){let r=Array.isArray(e)?e:[e];for(let n of r){let s=UserEventSchema.safeParse(n);s.success&&this.#a.dispatch(s.data);}}#p(){this.#a.hasActiveSubscriptions()&&this.#h();}#f(){}#m(e){this.#s.send(mr(this.#a.serverState(),e));}#h(){this.#n.schedule({reconnect:()=>this.#i(),shouldReconnect:()=>this.#a.hasActiveSubscriptions()});}};function Rr(t,e){return {...e,quote:r=>t.quote(e,r)}}function gr(t,e){let r=e.rfqId,n=e.quoteId;return {...e,confirm:()=>t.respondToConfirmation(r,n,RfqConfirmationDecision.Confirm),decline:()=>t.respondToConfirmation(r,n,RfqConfirmationDecision.Decline)}}function Ar(t){return {quoteId:t.quoteId,rfqId:t.rfqId}}function qr(t){return {quoteId:t.quoteId,rfqId:t.rfqId}}function vr(t){return {quoteId:t.quoteId,rfqId:t.rfqId}}function Pr(t,e){let r=X(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 Cr(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 Er(t,e,r){let n=X(t);return {maker_address:n.maker,quote_id:r,rfq_id:e,signer_address:n.signer,type:"RFQ_QUOTE_CANCEL"}}function kr(t,e,r){return {decision:r,quote_id:e,rfq_id:t,type:"RFQ_CONFIRMATION_RESPONSE"}}var W=class{#e=new Map;#t;constructor(e){this.#t=e;}waitFor(e,r){let n=Zs(),s,i=setNonBlockingTimeout(()=>{this.remove(e,s),n.reject(new f(r));},this.#t);s=n.promise.finally(()=>clearTimeout(i));let o=this.#e.get(e)??[];return o.push({...n,promise:s}),this.#e.set(e,o),s}resolve(e,r){let n=this.#e.get(e),s=n?.shift();s!==void 0&&(n!==void 0&&n.length===0&&this.#e.delete(e),s.resolve(r));}reject(e,r){let n=this.#e.get(e),s=n?.shift();s!==void 0&&(n!==void 0&&n.length===0&&this.#e.delete(e),s.reject(r));}remove(e,r){let n=this.#e.get(e);if(n===void 0)return;let s=n.filter(i=>i.promise!==r);s.length===0?this.#e.delete(e):this.#e.set(e,s);}rejectAll(e){for(let r of this.#e.values())for(let n of r)n.reject(e);this.#e.clear();}};function Zs(){let t,e;return {promise:new Promise((n,s)=>{t=n,e=s;}),reject:e,resolve:t}}var wr="0x0000000000000000000000000000000000000000000000000000000000000000";async function Mr(t){let e=X(t.account),r={builder:wr,maker:e.maker,makerAmount:toBaseUnits(Xs(t.orderSide,t.orderPrice,t.size)),metadata:wr,salt:ri().toString(),side:ti(t.orderSide),signatureType:e.signatureType,signer:e.signer,takerAmount:toBaseUnits(ei(t.orderSide,t.orderPrice,t.size)),timestamp:Math.floor(Date.now()/1e3).toString(),tokenId:t.tokenId},n;try{n=await t.signer.signTypedData(Jc({domain:xr(t),order:r}));}catch(s){throw j.fromError(s,"Could not sign the RFQ quote order.")}return {...r,signature:Kc({domain:xr(t),order:r,signature:n})}}function xr(t){return {chainId:t.chainId,exchange:t.exchange,protocolVersion:"3"}}function Xs(t,e,r){return t===OrderSide.SELL?r.toString():((e*r+999999n)/1000000n).toString()}function ei(t,e,r){return t===OrderSide.SELL?(e*r/1000000n).toString():r.toString()}function ti(t){return t===OrderSide.BUY?0:1}function ri(){let t=new Uint8Array(8);return globalThis.crypto.getRandomValues(t),BigInt(`0x${Array.from(t,e=>e.toString(16).padStart(2,"0")).join("")}`)}var Lr=DecimalishSchema.transform(t=>Dr(t)).refine(t=>t<=BigInt(Number.MAX_SAFE_INTEGER),{message:"Value exceeds the temporary numeric wire limit."}),ii=z.strictObject({price:Lr.refine(t=>t<1000000n,{message:"Price must be less than 1."}),size:Lr.optional(),source:z.enum(["collateral","inventory"]).default("collateral")});function Fr(t){return U$1(t,ii)}async function Br(t){let e=t.response.price,r=t.response.size===void 0?ui(t.request.requestedSize,e):t.response.size,n=await Mr({account:t.account,chainId:t.chainId,exchange:t.exchange,orderPrice:ci(t.request,t.response.source,e),orderSide:ai(t.response.source),signer:t.signer,size:r,tokenId:oi(t.request,t.response.source)});return {price:e,signedOrder:n,size:r}}function oi(t,e){return t.direction===RfqDirection.Buy?e==="collateral"?t.noPositionId:t.yesPositionId:e==="collateral"?t.yesPositionId:t.noPositionId}function ci(t,e,r){return t.direction===RfqDirection.Buy&&e==="collateral"||t.direction===RfqDirection.Sell&&e==="inventory"?1000000n-r:r}function ai(t){return t==="collateral"?OrderSide.BUY:OrderSide.SELL}function ui(t,e){let r=Dr(t.value);return t.unit===RfqRequestedSizeUnit.Shares?r:r*1000000n/e}function Dr(t){let e=/^(\d+)(?:\.(\d*))?$/.exec(t);if(e===null)throw new a("Value must be a valid decimal.");let[,r="",n=""]=e;if(n.length>6)throw new a("Value must have at most 6 decimal places.");let s=BigInt(r)*1000000n+BigInt(n.padEnd(6,"0"));if(s<=0n)throw new a("Value must be greater than 0.");return s}var mi=3e4,hi=3e4,v=class{#e;#t;#r;#s;#n;#a;#d;#c;#o;#i;constructor(e){this.#e=e.account,this.#t=e.chainId,this.#r=e.credentials,this.#s=e.exchange,this.#n=e.headers,this.#a=e.signer,this.#d=e.url;}async connect(){if(this.#c!==void 0){if(!this.#c.closed)return this.#c;this.#c=void 0;}if(this.#i!==void 0)return this.#i;let e=new be({account:this.#e,chainId:this.#t,credentials:this.#r,exchange:this.#s,headers:this.#n,onClose:()=>this.#u(e),signer:this.#a,url:this.#d});this.#o=e;let r;return r=(async()=>{try{return await e.connect(),this.#c=e,e}catch(n){throw await e.close(),n}finally{this.#i===r&&(this.#i=void 0),this.#o===e&&(this.#o=void 0);}})(),this.#i=r,r}async close(){let e=this.#c,r=this.#o,n=this.#i;this.#c=void 0,this.#o=void 0,this.#i=void 0,await Promise.allSettled([e?.close(),r?.close(),n?.catch(()=>{})]).then(()=>{});}#u(e){this.#c===e&&(this.#c=void 0),this.#o===e&&(this.#o=void 0);}},be=class{#e;#t;#r;#s;#n;#a;#d;#c;#o=new d;#i=pushable({objectMode:true});#u=new W(hi);#l;#p;constructor(e){this.#e=e.account,this.#t=e.chainId,this.#r=e.credentials,this.#s=e.exchange,this.#n=e.headers,this.#a=e.onClose,this.#d=e.signer,this.#c=e.url;}get closed(){return this.#l!==void 0}async connect(){let e=yi();this.#p=e;let r=setNonBlockingTimeout(()=>{e.reject(new c("RFQ quoter authentication timed out."));},mi);try{await this.#o.connect({headers:this.#n,onClose:()=>this.#A(),onError:()=>{},onMessage:n=>this.#R(n),onOpen:()=>this.#b(),url:this.#c}),await e.promise;}finally{clearTimeout(r),this.#p=void 0;}}async#f(e){if(!this.#o.send(e))throw new c("RFQ quoter websocket is not open.")}async close(){this.#l===void 0&&(this.#l=this.#m()),await this.#l;}[Symbol.asyncIterator](){return this.#i[Symbol.asyncIterator]()}async#m(){let e=new c("RFQ quoter websocket closed.");await this.#y(e);}async#h(e){this.#l===void 0&&(this.#l=this.#y(e)),await this.#l;}async#y(e){this.#S(e),this.#i.end(),await this.#o.close(),this.#a();}#S(e){this.#p?.reject(e),this.#u.rejectAll(e);}#b(){this.#o.send(Pr(this.#e,this.#r));}#R(e){if(this.#l!==void 0||!RfqKnownInboundMessageSchema.safeParse(e).success)return;let r=RfqQuoterInboundMessageSchema.safeParse(e);if(!r.success){let s=new c("Invalid RFQ quoter message.",{cause:r.error});this.#h(s);return}let n=r.data;switch(n.type){case "auth":this.#g(n);return;case "quote_request":this.#i.push(Rr(this,n));return;case "quote_ack":this.#u.resolve(Q(n.rfqId),Ar(n));return;case "quote_cancel_ack":this.#u.resolve(ye(n.rfqId,n.quoteId),qr(n));return;case "confirmation_request":this.#i.push(gr(this,n));return;case "confirmation_ack":this.#u.resolve(Se(n.rfqId,n.quoteId),vr(n));return;case "execution_update":this.#i.push(n);return;case "rfq_error":this.#q(n);return}}#g(e){if(e.success===true){this.#p?.resolve(void 0);return}this.#p?.reject(new c(`RFQ quoter authentication failed: ${e.error}`));}#A(){this.#a(),this.close();}#q(e){if(e.requestType==="RFQ_QUOTE"){if(e.rfqId===void 0){this.#h(new c("Uncorrelated RFQ quoter error."));return}this.#u.reject(Q(e.rfqId),new Vd(e.message,{code:e.code,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(ye(e.rfqId,e.quoteId),new Xd(e.message,{code:e.code,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(Se(e.rfqId,e.quoteId),new Zd(e.message,{code:e.code,quoteId:e.quoteId,rfqId:e.rfqId}));}}async quote(e,r){let n=Fr(r),s=await Br({account:this.#e,chainId:this.#t,exchange:this.#s,request:e,response:n,signer:this.#d}),i=this.#u.waitFor(Q(e.rfqId),`Timed out waiting for RFQ quote acknowledgement for ${e.rfqId}.`);try{return await this.#f(Cr(e,s)),await i}catch(o){throw this.#u.remove(Q(e.rfqId),i),o}}async cancelQuote(e){let r=ye(e.rfqId,e.quoteId),n=this.#u.waitFor(r,`Timed out waiting for RFQ quote cancellation acknowledgement for ${e.rfqId}.`);try{return await this.#f(Er(this.#e,e.rfqId,e.quoteId)),await n}catch(s){throw this.#u.remove(r,n),s}}async respondToConfirmation(e,r,n){let s=Se(e,r),i=this.#u.waitFor(s,`Timed out waiting for RFQ confirmation acknowledgement for ${e}.`);try{return await this.#f(kr(e,r,n)),await i}catch(o){throw this.#u.remove(s,i),o}}};function Q(t){return `ACK_RFQ_QUOTE:${t}`}function ye(t,e){return `ACK_RFQ_QUOTE_CANCEL:${t}:${e}`}function Se(t,e){return `ACK_RFQ_CONFIRMATION_RESPONSE:${t}:${e}`}function yi(){let t,e;return {promise:new Promise((n,s)=>{t=n,e=s;}),reject:e,resolve:t}}var P=class{#e;#t;#r=new d({heartbeat:new F});#s=new l;#n=new p({deriveServerState:gi});constructor(e){this.#e=e;}async subscribe(e){let{change:r,entry:n}=this.#n.add(e,{matches:Pi(e)});return await this.#a(n,r),m(n.subscriber.queue,()=>this.#d(n))}async#a(e,r){try{if((await this.#o()).reusedOpenSocket){let{before:s,after:i}=r,o=bi(s,i);this.#m(o);}}catch(n){throw await this.#d(e),n}}async#d(e){let{before:r,after:n}=this.#n.remove(e),s=Ri(r,n);this.#h(s),this.#n.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.#s.stop(),this.#n.endAll(),await this.#r.close();}#o(){return this.#r.connect({onClose:()=>this.#l(),onError:()=>this.#p(),onMessage:e=>this.#u(e),onOpen:()=>this.#i(),url:this.#e})}#i(){this.#s.resetBackoff(),this.#f();}#u(e){let r=RealtimeEventSchema.safeParse(e);r.success&&this.#n.dispatch(r.data);}#l(){this.#n.hasActiveSubscriptions()&&this.#y();}#p(){}#f(){this.#m(Array.from(this.#n.serverState().values()));}#m(e){e.length!==0&&this.#r.send(Ai(e));}#h(e){e.length!==0&&this.#r.send(qi(e));}#y(){this.#s.schedule({reconnect:()=>this.#o(),shouldReconnect:()=>this.#n.hasActiveSubscriptions()});}};function bi(t,e){return Array.from(e).flatMap(([r,n])=>t.has(r)?[]:[n])}function Ri(t,e){return Array.from(t).flatMap(([r,n])=>e.has(r)?[]:[n])}function gi(t){let e=new Map;for(let{subscription:r}of t)for(let n of vi(r))e.has(n.key)||e.set(n.key,n);return e}function Ai(t){return {action:"subscribe",subscriptions:t.map(({topic:e,type:r})=>({topic:e,type:r}))}}function qi(t){return {action:"unsubscribe",subscriptions:t.map(({topic:e,type:r})=>({topic:e,type:r}))}}function vi(t){switch(t.topic){case "comments":return (t.types??["comment_created"]).map(e=>_("comments",e));case "prices.crypto.binance":return [_("crypto_prices","update")];case "prices.crypto.chainlink":return [_("crypto_prices_chainlink","update")];case "prices.equity.pyth":return [_("equity_prices","update")];default:invariant(false,`Unknown RTDS topic: ${String(t)}`);}}function _(t,e){return {key:`${t}:${e}`,topic:t,type:e}}function Pi(t){switch(t.topic){case "comments":return e=>!(e.topic!=="comments"||t.types!==void 0&&t.types.length>0&&!t.types.includes(e.type)||(t.parentEntityId!==void 0||t.parentEntityType!==void 0)&&(!(e.type==="comment_created"||e.type==="comment_removed")||t.parentEntityId!==void 0&&e.payload.parentEntityID!==t.parentEntityId||t.parentEntityType!==void 0&&e.payload.parentEntityType!==t.parentEntityType));case "prices.crypto.binance":return e=>e.topic==="prices.crypto.binance"&&(t.symbols===void 0||t.symbols.length===0||t.symbols.includes(e.payload.symbol));case "prices.crypto.chainlink":return e=>e.topic==="prices.crypto.chainlink"&&(t.symbols===void 0||t.symbols.length===0||t.symbols.includes(e.payload.symbol));case "prices.equity.pyth":return e=>e.topic==="prices.equity.pyth"&&e.payload.symbol.toLowerCase()===t.symbol.toLowerCase()&&(t.types===void 0||t.types.length===0||t.types.includes(e.type));default:invariant(false,`Unknown RTDS topic: ${String(t)}`);}}var C=class{#e;#t;#r=new d({heartbeat:new B});#s=new l;#n=new p;constructor(e){this.#e=e.url;}async subscribe(e){let{entry:r}=this.#n.add(e);return await this.#a(r),m(r.subscriber.queue,()=>this.#d(r))}async#a(e){try{await this.#o();}catch(r){throw await this.#d(e),r}}async#d(e){this.#n.remove(e),this.#n.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.#s.stop(),this.#n.endAll(),await this.#r.close();}#o(){return this.#r.connect({onClose:()=>this.#l(),onError:()=>this.#p(),onMessage:e=>this.#u(e),onOpen:()=>this.#i(),url:this.#e})}#i(){this.#s.resetBackoff();}#u(e){let r=SportsResultEventSchema.safeParse(e);r.success&&this.#n.dispatch(r.data);}#l(){this.#n.hasActiveSubscriptions()&&this.#f();}#p(){}#f(){this.#s.schedule({reconnect:()=>this.#o(),shouldReconnect:()=>this.#n.hasActiveSubscriptions()});}};var U=class{#e;#t;get context(){return this.#e}get decorators(){return this.#t}get environment(){return this.context.environment}get clob(){return this.context.clob}get relayer(){return this.context.relayer}get rpc(){return this.context.rpc}get gamma(){return this.context.gamma}get data(){return this.context.data}get rfq(){return this.context.rfq}get webSockets(){return this.context.webSockets}get supportsGasless(){return this.context.apiKey?.supportGasless??false}constructor(e){this.#e=e,this.#t=[];}async resolveClobHeaders(e){return this.context.apiKey?.isBuilderKey?this.context.apiKey.authorize(e):Promise.resolve({})}async resolveRelayerHeaders(e){return this.context.apiKey?.supportGasless?this.context.apiKey.authorize(e):Promise.resolve({})}rememberDecorator(e){this.#t.push(e);}},Mi=z.object({key:ApiKeySchema,passphrase:z.string(),secret:z.string()}),Oi=z.object({wallet:EvmAddressSchema,credentials:Mi.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}),H=class extends U{constructor(e){super({apiKey:e.apiKey,environment:e.environment,data:new u({root:e.environment.data}),gamma:new u({root:e.environment.gamma}),clob:new u({root:e.environment.clob,resolveHeaders:r=>this.resolveClobHeaders(r)}),relayer:new u({root:e.environment.relayer,resolveHeaders:r=>this.resolveRelayerHeaders(r)}),rfq:new u({root:e.environment.rfq}),rpc:new V({url:e.environment.rpc}),webSockets:{clobMarket:new S({url:e.environment.clobMarketWs}),sports:new C({url:e.environment.sportsWs}),rtds:new P(e.environment.rtdsWs)}});}isSecureClient(){return false}isPublicClient(){return true}async closeSubscriptions(){await Promise.all([this.webSockets.clobMarket.close(),this.webSockets.rtds.close(),this.webSockets.sports.close()]).then(()=>{});}extend(e){return this.rememberDecorator(e),Object.assign(this,e(this)),this}beginAuthentication(e,r){let n=U$1(e,Oi);return Promise.resolve(async function*(){let s=Math.floor(Date.now()/1e3),i=n?.nonce??0,o=expectEvmAddress(yield _$1()),b=expectEvmAddress(n.wallet),R=W$1(this.environment,o,b);if(n.credentials!==void 0){let Ae=this.#e(n.credentials,R,r);try{if((await L(Ae)).includes(n.credentials.key))return Ae}catch(O){if(!(O instanceof d$1)||O.status!==401)throw O}}let x=yield {kind:"signAuthMessage",payload:tr({address:o,chainId:this.environment.chainId,nonce:i,timestamp:s})},M=await J(this,{address:o,nonce:i,signature:expectEvmSignature(x),timestamp:s});return this.#e(M,R,r)}.call(this))}#e(e,r,n){let s=new ge({account:r,apiKey:this.context.apiKey,credentials:e,environment:this.environment,signer:n});for(let i of this.decorators)s.extend(i);return s}},ge=class extends U{#e=false;get context(){return invariant(!this.#e,"This client has ended authentication and can no longer be used."),super.context}endAuthenticationLifecycle(){this.#e=true;}constructor(e){super({account:e.account,credentials:e.credentials,apiKey:e.apiKey,environment:e.environment,signer:e.signer,clob:new u({root:e.environment.clob,resolveHeaders:r=>this.resolveClobHeaders(r)}),relayer:new u({root:e.environment.relayer,resolveHeaders:r=>this.resolveRelayerHeaders(r)}),rpc:new V({url:e.environment.rpc}),gamma:new u({root:e.environment.gamma}),data:new u({root:e.environment.data}),rfq:new u({root:e.environment.rfq}),secureClob:new u({resolveHeaders:async r=>({...await this.resolveClobHeaders(r),...await this.#t(r)}),root:e.environment.clob}),webSockets:{clobMarket:new S({url:e.environment.clobMarketWs}),clobUser:new q({credentials:e.credentials,url:e.environment.clobUserWs}),rfqQuoter:new v({account:e.account,chainId:e.environment.chainId,credentials:e.credentials,exchange:e.environment.exchangeV3,headers:e.environment.rfqQuoterWsHeaders,signer:e.signer,url:e.environment.rfqQuoterWs}),sports:new C({url:e.environment.sportsWs}),rtds:new P(e.environment.rtdsWs)}});}get credentials(){return this.context.credentials}get account(){return this.context.account}get signer(){return this.context.signer}setupGaslessWallet(){return Promise.resolve(this)}get secureClob(){return this.context.secureClob}get webSockets(){return this.context.webSockets}async closeSubscriptions(){await Promise.allSettled([this.webSockets.clobMarket.close(),this.webSockets.rtds.close(),this.webSockets.sports.close(),this.webSockets.clobUser.close(),this.webSockets.rfqQuoter.close()]).then(()=>{});}isSecureClient(){return true}isPublicClient(){return false}extend(e){return this.rememberDecorator(e),Object.assign(this,e(this)),this}async endAuthentication(){let e=this.closeSubscriptions(),{apiKey:r,environment:n}=this.context;try{await N(this);}finally{this.endAuthenticationLifecycle(),await e;}let s=new H({apiKey:r,environment:n});for(let i of this.decorators)s.extend(i);return s}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 or(this.credentials.secret,r,e.method,e.path,e.body),POLY_TIMESTAMP:`${r}`}}catch(r){throw j.fromError(r,"Could not sign the L2-authenticated request")}}};function _r(t={}){return new H({environment:t.environment??le,apiKey:t.apiKey}).extend(ir)}var Ii=k(h,e,d$1,j,f,g,c,b,a),Li=k(a);async function Fi(t){let e=_r({environment:t.environment,apiKey:t.apiKey}),r=await Bi(e,t),n=await e.beginAuthentication({wallet:r,credentials:t.credentials,nonce:t.nonce},t.signer).then(Z(t.signer));if(n.account.walletType===WalletType.EOA||await ca(n,{wallet:n.account.wallet,type:n.account.walletType}))return n;if(n.account.walletType===WalletType.DEPOSIT_WALLET)return await Di(n),n;throw new a(`Wallet ${n.account.wallet} does not exist. Provide an existing wallet address, or omit wallet to use the default Deposit Wallet flow.`)}async function Bi(t,e){if(e.wallet!==void 0)return e.wallet;let r=expectEvmAddress(await e.signer.getAddress());return Y(t.rpc,r,t.environment.walletDerivation)}async function Di(t){let e=await Y(t.rpc,t.account.signer,t.environment.walletDerivation);if(!isSameEvmAddress(t.account.wallet,e))throw new a(`Wallet ${t.account.wallet} does not match the expected Deposit Wallet ${e} for this signer, nor a deployed wallet address.`);await(await fa(t)).wait();}
|
|
1
|
+
import {la,va,ta,ra,Pa,ld,jd,hd,fd,ed,bd,fc,dc,bc,db,Na,pc,rc,Dc,Jb,Hb,Fb,Db,Bb,zb,xb,vb,tb,hb,fb,$b,Tb,Rb,Pb,Ud,Be,qe,oe as oe$1,ie as ie$1,ze,xe,ve,te,me,ke,nc,lc,jc,hc as hc$1,Zb,Xb,Vb,La,Ja,Ha,Fa,Da,Ba,ae as ae$1,re,pa,na,Bc,zc,xc,vc,Ic,Hc,$c,Zc,Xc,Vc,Sd,Nd,Ed,Fe,Za,Va,bb,Z,ca,Y,fa,tc,Nb,Lb,V,U as U$1,_ as _$1,W as W$1,L,J,N,Vd,Xd,Zd,X,Jc,Kc}from'./chunk-2ZZDFOKL.js';export{Ya as ApproveErc1155ForAllError,Ua as ApproveErc20Error,yc as CancelAllError,Ac as CancelMarketOrdersError,uc as CancelOrderError,wc as CancelOrdersError,A as CombinatorialPrepareConditionCallError,md as ComboPositionStatus,Yc as CreateLimitOrderError,Uc as CreateMarketOrderError,o as CtfRedeemPositionsCallError,kd as DownloadAccountingSnapshotError,ua as DropNotificationsError,b as Erc20ApprovalCallError,m as Erc20TransferCallError,Cc as EstimateMarketPriceError,ka as FetchClosedOnlyModeError,Qb as FetchCommentsByIdError,Wb as FetchEventError,_b as FetchEventLiveVolumeError,Yb as FetchEventTagsError,Eb as FetchLastTradePriceError,Gb as FetchLastTradePricesError,kc as FetchMarketError,mc as FetchMarketTagsError,eb as FetchMidpointError,gb as FetchMidpointsError,sa as FetchNotificationsError,wb as FetchOrderBookError,yb as FetchOrderBooksError,oa as FetchOrderError,Aa as FetchOrderScoringError,Ca as FetchOrdersScoringError,gd as FetchPortfolioValueError,sb as FetchPriceError,Ib as FetchPriceHistoryError,ub as FetchPricesError,Td as FetchPublicProfileError,ye as FetchRelatedTagResourcesError,we as FetchRelatedTagsError,Ka as FetchRewardPercentagesError,le as FetchSeriesError,pe as FetchSportsMarketTypesError,Ab as FetchSpreadError,Cb as FetchSpreadsError,ue as FetchTagError,Ga as FetchTotalEarningsForUserForDayError,id as FetchTradedMarketCountError,qa as ListAccountTradesError,Oa as ListActivityError,ac as ListBuilderLeaderboardError,cb as ListBuilderTradesError,cc as ListBuilderVolumeError,cd as ListClosedPositionsError,ic as ListComboMarketsError,dd as ListComboPositionsError,Sb as ListCommentsByUserAddressError,Ob as ListCommentsError,Kb as ListCurrentRewardsError,Ub as ListEventsError,oc as ListMarketHoldersError,sc as ListMarketPositionsError,Mb as ListMarketRewardsError,gc as ListMarketsError,qc as ListOpenInterestError,ma as ListOpenOrdersError,ad as ListPositionsError,je as ListSeriesError,ne as ListSportsError,se as ListTagsError,Ae as ListTeamsError,ec as ListTraderLeaderboardError,Ma as ListTradesError,Ia as ListUserEarningsAndMarketsConfigError,Ea as ListUserEarningsForDayError,a as MAX_UINT256,r as MergePositionsCallError,Id as MergePositionsError,w as MergeV2CallError,$d as OpenRfqSessionError,_c as PlaceLimitOrderError,Wc as PlaceMarketOrderError,Fc as PostOrderError,Gc as PostOrdersError,Rd as RedeemPositionsError,y as RedeemV2CallError,Yd as RfqCancelQuoteError,Xd as RfqCancelQuoteRejectedError,be as RfqConfirmationDecision,_d as RfqConfirmationError,Zd as RfqConfirmationRejectedError,ce as RfqDirection,de as RfqErrorCode,ee as RfqExecutionStatus,Wd as RfqQuoteError,Vd as RfqQuoteRejectedError,fe as RfqRequestedSizeUnit,ge as RfqSide,he as SearchError,ab as SetupTradingApprovalsError,p as SplitPositionCallError,zd as SplitPositionError,u as SplitV2CallError,Ee as TransferErc20Error,Qa as WaitForTransactionError,B as combinatorialPrepareConditionCall,t as ctfRedeemPositionsCall,l as decodeErc1155BalanceOfBatchResult,j as decodeErc1155BalanceOfResult,h as decodeErc1155IsApprovedForAllResult,e as decodeErc20AllowanceResult,C as encodeProxyCall,D as encodeSafeMultisendCall,f as erc1155ApprovalForAllCall,k as erc1155BalanceOfBatchCall,i as erc1155BalanceOfCall,g as erc1155IsApprovedForAllCall,d as erc20AllowanceCall,c as erc20ApprovalCall,n as erc20TransferCall,Ra as expectTransactionHandle,s as mergePositionsCall,x as mergeV2Call,z as redeemV2Call,q as splitPositionCall,v as splitV2Call}from'./chunk-2ZZDFOKL.js';import {a,k,h,e,d as d$1,j,f,g,c,b}from'./chunk-E2CLUN5M.js';export{h as CancelledSigningError,i as InsufficientLiquidityError,e as RateLimitError,d as RequestRejectedError,j as SigningError,f as TimeoutError,g as TransactionFailedError,c as TransportError,b as UnexpectedResponseError,a as UserInputError,k as makeErrorGuard}from'./chunk-E2CLUN5M.js';import {DecimalishSchema,ApiKeySchema,EvmAddressSchema,toBaseUnits,OrderSide}from'@polymarket/bindings';export{OrderSide,OrderType}from'@polymarket/bindings';export{SignatureType}from'@polymarket/bindings/clob';export{ActivityType}from'@polymarket/bindings/data';import {WalletType}from'@polymarket/bindings/gamma';export{WalletType}from'@polymarket/bindings/gamma';import {z}from'zod';import {expectEvmAddress,isSameEvmAddress,expectEvmSignature,ResultAsync,invariant,setNonBlockingInterval,setNonBlockingTimeout}from'@polymarket/types';import Ls from'ky';import {RealtimeEventSchema,SportsResultEventSchema,MarketEventSchema,UserEventSchema}from'@polymarket/bindings/subscriptions';import {pushable}from'it-pushable';import {RfqKnownInboundMessageSchema,RfqQuoterInboundMessageSchema,RfqConfirmationDecision,RfqRequestedSizeUnit,RfqDirection}from'@polymarket/bindings/rfq';var Cs=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 Es(t){return new ne(t)}function ks(t){return new se(t)}var ne=class{#e;constructor(e){this.#e=e;}get isBuilderKey(){return true}get supportGasless(){return true}async authorize(e){try{return await this.#r(e)}catch(r){throw j.fromError(r,"Could not authorize the builder-authenticated request")}}async#t(){let e=this.#e.headers,r=typeof e=="function"?await e():e,n=new Headers(r);return n.set("content-type","application/json"),n}async#r(e){let r=await fetch(this.#e.url,{body:JSON.stringify({body:e.body,method:e.method,path:e.path}),credentials:this.#e.credentials,headers:await this.#t(),method:"POST",mode:"cors"});if(!r.ok)throw new Error(`Remote signer rejected request with status ${r.status}`);return Cs.parse(await r.json())}},se=class{#e;constructor(e){this.#e=e;}get isBuilderKey(){return false}get supportGasless(){return true}authorize(){return Promise.resolve({RELAYER_API_KEY:this.#e.key,RELAYER_API_KEY_ADDRESS:this.#e.address})}};function tr(t){return {domain:{chainId:t.chainId,name:"ClobAuthDomain",version:"1"},message:{address:t.address,message:"This message attests that I control the given wallet",nonce:t.nonce??0,timestamp:`${t.timestamp}`},primaryType:"ClobAuth",types:{ClobAuth:[{name:"address",type:"address"},{name:"timestamp",type:"string"},{name:"nonce",type:"uint256"},{name:"message",type:"string"}]}}}function Ts(t){return {listPositions:bd.bind(null,t),listClosedPositions:ed.bind(null,t),listComboPositions:fd.bind(null,t),fetchPortfolioValue:hd.bind(null,t),fetchTradedMarketCount:jd.bind(null,t),downloadAccountingSnapshot:ld.bind(null,t),listMarketPositions:tc.bind(null,t),listActivity:Pa.bind(null,t)}}function y(t,e={}){return {...e,user:e.user??t.account.wallet}}function ie(t){let e=Ts(t);return t.isPublicClient()?e:{...e,listPositions:r=>bd(t,y(t,r)),listClosedPositions:r=>ed(t,y(t,r)),listComboPositions:r=>fd(t,y(t,r)),fetchPortfolioValue:r=>hd(t,y(t,r)),fetchTradedMarketCount:r=>jd(t,y(t,r)),downloadAccountingSnapshot:r=>ld(t,y(t,r)),listActivity:r=>Pa(t,y(t,r)),listAccountTrades:ra.bind(null,t),fetchNotifications:ta.bind(null,t),dropNotifications:va.bind(null,t),fetchClosedOnlyMode:la.bind(null,t)}}function oe(t){return {listBuilderTrades:db.bind(null,t),listBuilderLeaderboard:bc.bind(null,t),fetchBuilderVolume:dc.bind(null,t),listTraderLeaderboard:fc.bind(null,t)}}function ce(t){return {fetchEventLiveVolume:$b.bind(null,t),fetchMidpoint:fb.bind(null,t),fetchMidpoints:hb.bind(null,t),fetchPrice:tb.bind(null,t),fetchPrices:vb.bind(null,t),fetchOrderBook:xb.bind(null,t),fetchOrderBooks:zb.bind(null,t),fetchSpread:Bb.bind(null,t),fetchSpreads:Db.bind(null,t),fetchLastTradePrice:Fb.bind(null,t),fetchLastTradePrices:Hb.bind(null,t),fetchPriceHistory:Jb.bind(null,t),estimateMarketPrice:Dc.bind(null,t),listOpenInterest:rc.bind(null,t),listMarketHolders:pc.bind(null,t),listTrades:Na.bind(null,t)}}function ae(t){return {listEvents:Vb.bind(null,t),fetchEvent:Xb.bind(null,t),fetchEventTags:Zb.bind(null,t),listMarkets:hc$1.bind(null,t),listComboMarkets:jc.bind(null,t),fetchMarket:lc.bind(null,t),fetchMarketTags:nc.bind(null,t),listSeries:ke.bind(null,t),fetchSeries:me.bind(null,t),listTags:te.bind(null,t),fetchTag:ve.bind(null,t),fetchRelatedTags:xe.bind(null,t),fetchRelatedTagResources:ze.bind(null,t),search:ie$1.bind(null,t),listSports:oe$1.bind(null,t),fetchSportsMarketTypes:qe.bind(null,t),listTeams:Be.bind(null,t),fetchPublicProfile:Ud.bind(null,t),listComments:Pb.bind(null,t),fetchCommentsById:Rb.bind(null,t),listCommentsByUserAddress:Tb.bind(null,t)}}function ws(t){return {listCurrentRewards:Lb.bind(null,t),listMarketRewards:Nb.bind(null,t)}}function ue(t){let e=ws(t);return t.isPublicClient()?e:{...e,fetchOrderScoring:Ba.bind(null,t),fetchOrdersScoring:Da.bind(null,t),listUserEarningsForDay:Fa.bind(null,t),fetchTotalEarningsForUserForDay:Ha.bind(null,t),listUserEarningsAndMarketsConfig:Ja.bind(null,t),fetchRewardPercentages:La.bind(null,t)}}function rr(t){return {openRfqSession(){return ae$1(t)}}}function de(t){return t.isSecureClient()?{subscribe(e){return re(t,e)}}:{subscribe(e){return re(t,e)}}}function nr(t){return {createMarketOrder:Vc.bind(null,t),placeMarketOrder:Xc.bind(null,t),createLimitOrder:Zc.bind(null,t),placeLimitOrder:$c.bind(null,t),postOrder:Hc(t),postOrders:Ic(t),cancelOrder:vc.bind(null,t),cancelOrders:xc.bind(null,t),cancelAll:zc.bind(null,t),cancelMarketOrders:Bc.bind(null,t),listOpenOrders:na.bind(null,t),fetchOrder:pa.bind(null,t)}}function sr(t){return {isGaslessReady:()=>Promise.resolve(true),setupTradingApprovals:bb.bind(null,t),approveErc20:Va.bind(null,t),approveErc1155ForAll:Za.bind(null,t),transferErc20:Fe.bind(null,t),splitPosition:Ed.bind(null,t),mergePositions:Nd.bind(null,t),redeemPositions:Sd.bind(null,t)}}function ir(t){return t.isSecureClient()?{...ie(t),...oe(t),...ce(t),...ae(t),...ue(t),...rr(t),...de(t),...nr(t),...sr(t)}:{...ie(t),...oe(t),...ce(t),...ae(t),...ue(t),...de(t)}}var le={name:"production",chainId:137,rpc:"https://polygon.drpc.org",walletDerivation:{depositWalletFactory:expectEvmAddress("0x00000000000Fb5C9ADea0298D729A0CB3823Cc07"),depositWalletBeacon:expectEvmAddress("0x7A18EDfe055488A3128f01F563e5B479D92ffc3a"),depositWalletImplementation:expectEvmAddress("0x58CA52ebe0DadfdF531Cde7062e76746de4Db1eB"),proxyFactory:expectEvmAddress("0xaB45c5A4B0c941a2F231C04C3f49182e1A254052"),proxyImplementation:expectEvmAddress("0x44e999d5c2F66Ef0861317f9A4805AC2e90aEB4f"),safeFactory:expectEvmAddress("0xaacFeEa03eb1561C4e67d661e40682Bd20E3541b"),safeInitCodeHash:"0x2bce2127ff07fb632d16c8347c4ebf501f4841168bed00d9e6ef715ddb6fcecf"},collateralToken:expectEvmAddress("0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB"),conditionalTokens:expectEvmAddress("0x4D97DCd97eC945f40cF65F87097ACe5EA0476045"),negRiskAdapter:expectEvmAddress("0xd91E80cF2E7be2e162c6513ceD06f1dD0dA35296"),collateralAdapter:expectEvmAddress("0xAdA100Db00Ca00073811820692005400218FcE1f"),negRiskCollateralAdapter:expectEvmAddress("0xadA2005600Dec949baf300f4C6120000bDB6eAab"),standardExchange:expectEvmAddress("0xE111180000d2663C0091e4f400237545B87B996B"),negRiskExchange:expectEvmAddress("0xe2222d279d744050d28e00520010520000310F59"),exchangeV3:expectEvmAddress("0xe3333700cA9d93003F00f0F71f8515005F6c00Aa"),protocolV2Router:expectEvmAddress("0x12121212006e4CD160D18e3f00711DA5c3372600"),combinatorialModule:expectEvmAddress("0x30000034706c7d8e12009dab006be20000c031a8"),positionManager:expectEvmAddress("0x006F54F7f9A22e0000CC2AB60031000000ae9fEF"),autoRedeemOperator:expectEvmAddress("0xa1200000d0002264C9a1698e001292D00E1b00af"),safeMultisend:expectEvmAddress("0xA238CBeb142c10Ef7Ad8442C6D1f9E89e07e7761"),relayHub:expectEvmAddress("0xD216153c06E857cD7f72665E0aF1d7D82172F494"),clob:"https://clob.polymarket.com",clobMarketWs:"wss://ws-subscriptions-clob.polymarket.com/ws/market",clobUserWs:"wss://ws-subscriptions-clob.polymarket.com/ws/user",relayer:"https://relayer-v2.polymarket.com",gamma:"https://gamma-api.polymarket.com",data:"https://data-api.polymarket.com",rfq:"https://combos-rfq-api.polymarket.com",rtdsWs:"wss://ws-live-data.polymarket.com",rfqQuoterWs:"wss://combos-rfq-gateway-quoter.polymarket.com/ws/rfq",sportsWs:"wss://sports-api.polymarket.com/ws",relayerMaxPolls:100,relayerPollFrequencyMs:2e3},hc={...le,name:"preproduction",clob:"https://clob-preprod-int-v2.polymarket.com",data:"https://data-api-preprod-int.polymarket.com",gamma:"https://gamma-api-preprod-int.polymarket.com",relayer:"https://relayer-v2-preprod-int.polymarket.com"};async function or(t,e,r,n,s){let i=`${e}${r}${n}`;s!==void 0&&(i+=s);let o=await globalThis.crypto.subtle.importKey("raw",xs(t),{name:"HMAC",hash:"SHA-256"},false,["sign"]),b=await globalThis.crypto.subtle.sign("HMAC",o,new TextEncoder().encode(i));return Os(Ms(b))}function xs(t){let e=t.replace(/-/g,"+").replace(/_/g,"/").replace(/[^A-Za-z0-9+/=]/g,""),r=atob(e),n=new Uint8Array(r.length);for(let s=0;s<r.length;s+=1)n[s]=r.charCodeAt(s);return n.buffer}function Ms(t){let e=new Uint8Array(t),r="";for(let n of e)r+=String.fromCharCode(n);return btoa(r)}function Os(t){return t.replace(/\+/g,"-").replace(/\//g,"_")}var u=class{#e;#t;constructor({root:e,resolveHeaders:r}){this.#e=Ls.create({prefixUrl:e,throwHttpErrors:false}),this.#t=r;}get(e,r={}){return this.#s("GET",e,r)}post(e,r={}){return this.#s("POST",e,r)}del(e,r={}){return this.#s("DELETE",e,r)}#r(e){return e.startsWith("/")?e.slice(1):e}#s(e,r,n){return this.#o(this.#n(e,r,n))}async#n(e,r,n){let s=this.#a(e,r,n),i=await this.#t?.(s),o=this.#c(s.headers,i);return s.body!==void 0&&!o.has("content-type")&&o.set("content-type","application/json"),this.#e(this.#r(r),{body:s.body,headers:o,method:e,searchParams:s.params})}#a(e,r,n){return {body:"json"in n?this.#d(n.json):void 0,headers:n.headers,json:"json"in n?n.json:void 0,method:e,params:"params"in n?n.params:void 0,path:r}}#d(e){if(e!==void 0)return JSON.stringify(e)}#c(...e){let r=new Headers;for(let n of e)if(n!==void 0)for(let[s,i]of new Headers(n).entries())r.set(s,i);return r}#o(e$1){return ResultAsync.fromPromise(e$1.then(async r=>{if(r.ok)return r;if(r.status===429)throw new e(`Request to ${r.url} was rate limited`);let n=await this.#i(r);throw new d$1(n,{status:r.status})}),r=>r instanceof e||r instanceof d$1?r:c.fromError(r))}async#i(e){let r=e.headers.get("content-type")?.toLowerCase();if(r?.includes("application/json")){let{error:s}=await e.clone().json().catch(()=>({}));if(s)return `${String(s)} (${e.url})`}if(r?.includes("text/plain")){let s=await e.clone().text().then(i=>i.trim(),()=>"");if(s)return `${s} (${e.url})`}return e.headers.get("server")?.toLowerCase()?.includes("cloudflare")?`Request to ${e.url} was blocked by Cloudflare with status ${e.status}`:r?.includes("text/html")||r?.includes("application/xhtml+xml")?`Request to ${e.url} failed with status ${e.status} and an unexpected HTML response body`:`Request to ${e.url} failed with status ${e.status} and unreadable response body`}};function m(t,e){let r;return {close:()=>(r===void 0&&(r=Promise.resolve(t.return()).then(()=>e())),r),[Symbol.asyncIterator](){return t[Symbol.asyncIterator]()}}}var Fs=1e4,Bs=3e4,Ds=5e3,Ws=10*6e4,Qs=3e4,A=class{#e=0;#t;start(e){this.stop(),this.#e=Date.now(),this.#t=setNonBlockingInterval(()=>{e("PING");},Fs);}handleMessage(e){return e!=="PONG"?false:(this.#e=Date.now(),true)}isStale(e){return e-this.#e>Bs}stop(){this.#t!==void 0&&(clearInterval(this.#t),this.#t=void 0);}},F=class{#e=0;#t;start(e){this.stop(),this.#e=Date.now(),this.#t=setNonBlockingInterval(()=>{e("PING");},Ds);}handleMessage(){return this.#e=Date.now(),false}isStale(e){return e-this.#e>Ws}stop(){this.#t!==void 0&&(clearInterval(this.#t),this.#t=void 0);}},B=class{#e=0;#t;start(e){this.#e=Date.now(),this.#t=e;}stop(){this.#t=void 0;}handleMessage(e){return e!=="ping"?false:(this.#e=Date.now(),this.#t?.("pong"),true)}isStale(e){return e-this.#e>Qs}};var Hs=5e3,Ks=250,js=3e4,l=class{#e;#t=0;schedule(e){if(this.#e!==void 0||!e.shouldReconnect())return;let r=Vs(this.#t,{baseMs:Ks,maxMs:js});this.#t+=1,this.#e=setNonBlockingTimeout(()=>{this.#e=void 0,this.#r(e);},r);}stop(){this.#e!==void 0&&(clearTimeout(this.#e),this.#e=void 0);}resetBackoff(){this.#t=0,this.stop();}async#r(e){if(e.shouldReconnect())try{await e.reconnect();}catch{this.schedule(e);}}},d=class{#e;#t;#r;#s;constructor(e={}){this.#e=e.heartbeat;}connect(e){if(this.#t?.readyState===WebSocket.OPEN)return Promise.resolve({reusedOpenSocket:true});if(this.#c(),this.#r!==void 0)return this.#r;let n=this.#a(e).then(()=>({reusedOpenSocket:false})).catch(s=>{throw this.#r===n&&(this.#r=void 0),s});return this.#r=n,n}send(e){return this.#n(JSON.stringify(e))}#n(e){return this.#t?.readyState!==WebSocket.OPEN?false:(this.#t.send(e),true)}async close(){let e=await this.#u();this.#i(),!(e===void 0||e.readyState===WebSocket.CLOSED)&&await new Promise(r=>{e.addEventListener("close",()=>r(),{once:true}),e.readyState!==WebSocket.CLOSING&&e.close();});}async#a(e){let r=await e.prepare?.();return new Promise((n,s)=>{let i=Ns(e.url,e.headers),o=()=>{i.removeEventListener("error",b),this.#d(i),this.#o(),e.onOpen(r),n(i);},b=R=>{i.removeEventListener("open",o),s(new c(`WebSocket connection failed: ${e.url}`,{cause:R}));};i.addEventListener("open",o,{once:true}),i.addEventListener("error",b,{once:true}),i.addEventListener("message",R=>{if(this.#t!==i)return;let x=String(R.data);if(this.#e?.handleMessage(x))return;let M;try{M=JSON.parse(x);}catch{return}e.onMessage(M);}),i.addEventListener("close",()=>{this.#t===i&&(this.#c(),e.onClose());}),i.addEventListener("error",()=>e.onError());})}#d(e){this.#t=e,this.#r=void 0;}#c(){this.#i(),this.#t=void 0;}#o(){this.#i();let e=this.#e;e!==void 0&&(e.start(r=>this.#n(r)),this.#s=setNonBlockingInterval(()=>{if(!e.isStale(Date.now()))return;let r=this.#t;r?.readyState===WebSocket.OPEN&&r.close();},Hs));}#i(){this.#s!==void 0&&(clearInterval(this.#s),this.#s=void 0),this.#e?.stop();}async#u(){let e=this.#t,r=this.#r;return this.#t=void 0,this.#r=void 0,e!==void 0?e:r?.then(()=>this.#t,()=>{})}};function Ns(t,e){if(e===void 0)return new WebSocket(t);try{let r=Reflect.construct(WebSocket,[t,{headers:e}]);if(r instanceof WebSocket)return r}catch(r){throw new c("WebSocket headers require a header-capable WebSocket implementation.",{cause:r})}throw new c("WebSocket headers require a header-capable WebSocket implementation.")}function Vs(t,e){let r=Math.min(e.baseMs*2**t,e.maxMs);return Math.random()*r}var p=class{#e=new Set;#t;constructor(e){this.#t=e?.deriveServerState??(()=>{});}add(e,r={}){let n={queue:pushable({objectMode:true})};r.matches!==void 0&&(n.matches=r.matches);let s={subscription:e,subscriber:n};return {change:this.#r(s),entry:s}}#r(e){let r=this.serverState();return this.#e.add(e),{before:r,after:this.serverState()}}remove(e){let r=this.serverState();return this.#e.delete(e),e.subscriber.queue.end(),{before:r,after:this.serverState()}}dispatch(e){for(let{subscriber:r}of this.#e)(r.matches===void 0||r.matches(e))&&r.queue.push(e);}hasActiveSubscriptions(){return this.#e.size>0}endAll(e){for(let{subscriber:r}of this.#e)r.queue.end(e);this.#e.clear();}serverState(){return this.#t(this.#e)}};function pe(t,e,r){let n=D(r.assetsIds,e.assetsIds),s=D(e.assetsIds,r.assetsIds);n.length>0&&t(ar(n,r.customFeatureEnabled));let i=r.assetsIds[0];n.length===0&&e.customFeatureEnabled!==r.customFeatureEnabled&&i!==void 0&&t(ar([i],r.customFeatureEnabled)),s.length>0&&t($s(s));}function fe(t,e,r){if(r.includeAllMarkets){!e.includeAllMarkets&&e.markets.length>0&&t(dr(e.markets));return}if(e.includeAllMarkets){r.markets.length>0&&t(ur(r.markets));return}let n=D(r.markets,e.markets),s=D(e.markets,r.markets);n.length>0&&t(ur(n)),s.length>0&&t(dr(s));}function lr(t){let e=new Set,r=false;for(let{subscription:n}of t){for(let s of n.tokenIds)e.add(s);r||=n.customFeatureEnabled===true;}return {assetsIds:Array.from(e),customFeatureEnabled:r}}function pr(t){let e=false,r=new Set;for(let{subscription:n}of t){if(Sr(n)){e=true;continue}for(let s of n.markets??[])r.add(s);}return {includeAllMarkets:e,markets:e?[]:Array.from(r)}}function fr(t){return {assets_ids:t.assetsIds,custom_feature_enabled:t.customFeatureEnabled,type:"market"}}function ar(t,e){return {assets_ids:t,custom_feature_enabled:e,operation:"subscribe"}}function $s(t){return {assets_ids:t,operation:"unsubscribe"}}function mr(t,e){return {auth:{apiKey:e.key,passphrase:e.passphrase,secret:e.secret},markets:t.markets,type:"user"}}function ur(t){return {markets:t,operation:"subscribe"}}function dr(t){return {markets:t,operation:"unsubscribe"}}function hr(t){return e=>{switch(e.type){case "price_change":return e.payload.priceChanges.some(r=>t.tokenIds.includes(r.tokenId));case "new_market":return t.customFeatureEnabled===true;case "market_resolved":return t.customFeatureEnabled===true&&(e.payload.tokenIds??[]).some(r=>t.tokenIds.includes(r));case "best_bid_ask":return t.customFeatureEnabled===true&&t.tokenIds.includes(e.payload.tokenId);default:return t.tokenIds.includes(e.payload.tokenId)}}}function yr(t){if(Sr(t))return ()=>true;let e=new Set((t.markets??[]).map(r=>r.toLowerCase()));return r=>e.has(r.payload.market.toLowerCase())}function Sr(t){return (t.markets?.length??0)===0}function D(t,e){let r=new Set(e);return t.filter(n=>!r.has(n))}var S=class{#e;#t;#r=new d({heartbeat:new A});#s=new l;#n=new p({deriveServerState:lr});constructor(e){this.#e=e.url;}async subscribe(e){let{change:r,entry:n}=this.#n.add(e,{matches:hr(e)});return await this.#a(n,r),m(n.subscriber.queue,()=>this.#d(n))}async#a(e,r){let{before:n,after:s}=r;try{(await this.#o()).reusedOpenSocket&&pe(o=>this.#r.send(o),n,s);}catch(i){throw await this.#d(e),i}}async#d(e){let{before:r,after:n}=this.#n.remove(e);if(!this.#n.hasActiveSubscriptions()){await this.close();return}pe(s=>this.#r.send(s),r,n);}async close(){this.#t===void 0&&(this.#t=this.#c().finally(()=>{this.#t=void 0;})),await this.#t;}async#c(){this.#s.stop(),this.#n.endAll(),await this.#r.close();}#o(){return this.#r.connect({onClose:()=>this.#l(),onError:()=>this.#p(),onMessage:e=>this.#u(e),onOpen:()=>this.#i(),url:this.#e})}#i(){this.#s.resetBackoff(),this.#f();}#u(e){let r=Array.isArray(e)?e:[e];for(let n of r){let s=MarketEventSchema.safeParse(n);s.success&&this.#n.dispatch(s.data);}}#l(){this.#n.hasActiveSubscriptions()&&this.#m();}#p(){}#f(){this.#r.send(fr(this.#n.serverState()));}#m(){this.#s.schedule({reconnect:()=>this.#o(),shouldReconnect:()=>this.#n.hasActiveSubscriptions()});}};var q=class{#e;#t;#r;#s=new d({heartbeat:new A});#n=new l;#a=new p({deriveServerState:pr});constructor(e){this.#e=e.url,this.#t=e.credentials;}async subscribe(e){let{change:r,entry:n}=this.#a.add(e,{matches:yr(e)});return await this.#d(n,r),m(n.subscriber.queue,()=>this.#c(n))}async#d(e,r){let{before:n,after:s}=r;try{(await this.#i()).reusedOpenSocket&&fe(o=>this.#s.send(o),n,s);}catch(i){throw await this.#c(e),i}}async#c(e){let{before:r,after:n}=this.#a.remove(e);if(!this.#a.hasActiveSubscriptions()){await this.close();return}fe(s=>this.#s.send(s),r,n);}async close(){this.#r===void 0&&(this.#r=this.#o().finally(()=>{this.#r=void 0;})),await this.#r;}async#o(){this.#n.stop(),this.#a.endAll(),await this.#s.close();}#i(){return this.#s.connect({onClose:()=>this.#p(),onError:()=>this.#f(),onMessage:e=>this.#l(e),onOpen:e=>this.#u(e),prepare:()=>this.#t,url:this.#e})}#u(e){this.#n.resetBackoff(),this.#m(e);}#l(e){let r=Array.isArray(e)?e:[e];for(let n of r){let s=UserEventSchema.safeParse(n);s.success&&this.#a.dispatch(s.data);}}#p(){this.#a.hasActiveSubscriptions()&&this.#h();}#f(){}#m(e){this.#s.send(mr(this.#a.serverState(),e));}#h(){this.#n.schedule({reconnect:()=>this.#i(),shouldReconnect:()=>this.#a.hasActiveSubscriptions()});}};function Rr(t,e){return {...e,quote:r=>t.quote(e,r)}}function gr(t,e){let r=e.rfqId,n=e.quoteId;return {...e,confirm:()=>t.respondToConfirmation(r,n,RfqConfirmationDecision.Confirm),decline:()=>t.respondToConfirmation(r,n,RfqConfirmationDecision.Decline)}}function Ar(t){return {quoteId:t.quoteId,rfqId:t.rfqId}}function qr(t){return {quoteId:t.quoteId,rfqId:t.rfqId}}function vr(t){return {quoteId:t.quoteId,rfqId:t.rfqId}}function Pr(t,e){let r=X(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 Cr(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 Er(t,e,r){let n=X(t);return {maker_address:n.maker,quote_id:r,rfq_id:e,signer_address:n.signer,type:"RFQ_QUOTE_CANCEL"}}function kr(t,e,r){return {decision:r,quote_id:e,rfq_id:t,type:"RFQ_CONFIRMATION_RESPONSE"}}var W=class{#e=new Map;#t;constructor(e){this.#t=e;}waitFor(e,r){let n=Zs(),s,i=setNonBlockingTimeout(()=>{this.remove(e,s),n.reject(new f(r));},this.#t);s=n.promise.finally(()=>clearTimeout(i));let o=this.#e.get(e)??[];return o.push({...n,promise:s}),this.#e.set(e,o),s}resolve(e,r){let n=this.#e.get(e),s=n?.shift();s!==void 0&&(n!==void 0&&n.length===0&&this.#e.delete(e),s.resolve(r));}reject(e,r){let n=this.#e.get(e),s=n?.shift();s!==void 0&&(n!==void 0&&n.length===0&&this.#e.delete(e),s.reject(r));}remove(e,r){let n=this.#e.get(e);if(n===void 0)return;let s=n.filter(i=>i.promise!==r);s.length===0?this.#e.delete(e):this.#e.set(e,s);}rejectAll(e){for(let r of this.#e.values())for(let n of r)n.reject(e);this.#e.clear();}};function Zs(){let t,e;return {promise:new Promise((n,s)=>{t=n,e=s;}),reject:e,resolve:t}}var wr="0x0000000000000000000000000000000000000000000000000000000000000000";async function Mr(t){let e=X(t.account),r={builder:wr,maker:e.maker,makerAmount:toBaseUnits(Xs(t.orderSide,t.orderPrice,t.size)),metadata:wr,salt:ri().toString(),side:ti(t.orderSide),signatureType:e.signatureType,signer:e.signer,takerAmount:toBaseUnits(ei(t.orderSide,t.orderPrice,t.size)),timestamp:Math.floor(Date.now()/1e3).toString(),tokenId:t.tokenId},n;try{n=await t.signer.signTypedData(Jc({domain:xr(t),order:r}));}catch(s){throw j.fromError(s,"Could not sign the RFQ quote order.")}return {...r,signature:Kc({domain:xr(t),order:r,signature:n})}}function xr(t){return {chainId:t.chainId,exchange:t.exchange,protocolVersion:"3"}}function Xs(t,e,r){return t===OrderSide.SELL?r.toString():((e*r+999999n)/1000000n).toString()}function ei(t,e,r){return t===OrderSide.SELL?(e*r/1000000n).toString():r.toString()}function ti(t){return t===OrderSide.BUY?0:1}function ri(){let t=new Uint8Array(8);return globalThis.crypto.getRandomValues(t),BigInt(`0x${Array.from(t,e=>e.toString(16).padStart(2,"0")).join("")}`)}var Lr=DecimalishSchema.transform(t=>Dr(t)).refine(t=>t<=BigInt(Number.MAX_SAFE_INTEGER),{message:"Value exceeds the temporary numeric wire limit."}),ii=z.strictObject({price:Lr.refine(t=>t<1000000n,{message:"Price must be less than 1."}),size:Lr.optional(),source:z.enum(["collateral","inventory"]).default("collateral")});function Fr(t){return U$1(t,ii)}async function Br(t){let e=t.response.price,r=t.response.size===void 0?ui(t.request.requestedSize,e):t.response.size,n=await Mr({account:t.account,chainId:t.chainId,exchange:t.exchange,orderPrice:ci(t.request,t.response.source,e),orderSide:ai(t.response.source),signer:t.signer,size:r,tokenId:oi(t.request,t.response.source)});return {price:e,signedOrder:n,size:r}}function oi(t,e){return t.direction===RfqDirection.Buy?e==="collateral"?t.noPositionId:t.yesPositionId:e==="collateral"?t.yesPositionId:t.noPositionId}function ci(t,e,r){return t.direction===RfqDirection.Buy&&e==="collateral"||t.direction===RfqDirection.Sell&&e==="inventory"?1000000n-r:r}function ai(t){return t==="collateral"?OrderSide.BUY:OrderSide.SELL}function ui(t,e){let r=Dr(t.value);return t.unit===RfqRequestedSizeUnit.Shares?r:r*1000000n/e}function Dr(t){let e=/^(\d+)(?:\.(\d*))?$/.exec(t);if(e===null)throw new a("Value must be a valid decimal.");let[,r="",n=""]=e;if(n.length>6)throw new a("Value must have at most 6 decimal places.");let s=BigInt(r)*1000000n+BigInt(n.padEnd(6,"0"));if(s<=0n)throw new a("Value must be greater than 0.");return s}var mi=3e4,hi=3e4,v=class{#e;#t;#r;#s;#n;#a;#d;#c;#o;#i;constructor(e){this.#e=e.account,this.#t=e.chainId,this.#r=e.credentials,this.#s=e.exchange,this.#n=e.headers,this.#a=e.signer,this.#d=e.url;}async connect(){if(this.#c!==void 0){if(!this.#c.closed)return this.#c;this.#c=void 0;}if(this.#i!==void 0)return this.#i;let e=new be({account:this.#e,chainId:this.#t,credentials:this.#r,exchange:this.#s,headers:this.#n,onClose:()=>this.#u(e),signer:this.#a,url:this.#d});this.#o=e;let r;return r=(async()=>{try{return await e.connect(),this.#c=e,e}catch(n){throw await e.close(),n}finally{this.#i===r&&(this.#i=void 0),this.#o===e&&(this.#o=void 0);}})(),this.#i=r,r}async close(){let e=this.#c,r=this.#o,n=this.#i;this.#c=void 0,this.#o=void 0,this.#i=void 0,await Promise.allSettled([e?.close(),r?.close(),n?.catch(()=>{})]).then(()=>{});}#u(e){this.#c===e&&(this.#c=void 0),this.#o===e&&(this.#o=void 0);}},be=class{#e;#t;#r;#s;#n;#a;#d;#c;#o=new d;#i=pushable({objectMode:true});#u=new W(hi);#l;#p;constructor(e){this.#e=e.account,this.#t=e.chainId,this.#r=e.credentials,this.#s=e.exchange,this.#n=e.headers,this.#a=e.onClose,this.#d=e.signer,this.#c=e.url;}get closed(){return this.#l!==void 0}async connect(){let e=yi();this.#p=e;let r=setNonBlockingTimeout(()=>{e.reject(new c("RFQ quoter authentication timed out."));},mi);try{await this.#o.connect({headers:this.#n,onClose:()=>this.#A(),onError:()=>{},onMessage:n=>this.#R(n),onOpen:()=>this.#b(),url:this.#c}),await e.promise;}finally{clearTimeout(r),this.#p=void 0;}}async#f(e){if(!this.#o.send(e))throw new c("RFQ quoter websocket is not open.")}async close(){this.#l===void 0&&(this.#l=this.#m()),await this.#l;}[Symbol.asyncIterator](){return this.#i[Symbol.asyncIterator]()}async#m(){let e=new c("RFQ quoter websocket closed.");await this.#y(e);}async#h(e){this.#l===void 0&&(this.#l=this.#y(e)),await this.#l;}async#y(e){this.#S(e),this.#i.end(),await this.#o.close(),this.#a();}#S(e){this.#p?.reject(e),this.#u.rejectAll(e);}#b(){this.#o.send(Pr(this.#e,this.#r));}#R(e){if(this.#l!==void 0||!RfqKnownInboundMessageSchema.safeParse(e).success)return;let r=RfqQuoterInboundMessageSchema.safeParse(e);if(!r.success){let s=new c("Invalid RFQ quoter message.",{cause:r.error});this.#h(s);return}let n=r.data;switch(n.type){case "auth":this.#g(n);return;case "quote_request":this.#i.push(Rr(this,n));return;case "quote_ack":this.#u.resolve(Q(n.rfqId),Ar(n));return;case "quote_cancel_ack":this.#u.resolve(ye(n.rfqId,n.quoteId),qr(n));return;case "confirmation_request":this.#i.push(gr(this,n));return;case "confirmation_ack":this.#u.resolve(Se(n.rfqId,n.quoteId),vr(n));return;case "execution_update":this.#i.push(n);return;case "rfq_error":this.#q(n);return}}#g(e){if(e.success===true){this.#p?.resolve(void 0);return}this.#p?.reject(new c(`RFQ quoter authentication failed: ${e.error}`));}#A(){this.#a(),this.close();}#q(e){if(e.requestType==="RFQ_QUOTE"){if(e.rfqId===void 0){this.#h(new c("Uncorrelated RFQ quoter error."));return}this.#u.reject(Q(e.rfqId),new Vd(e.message,{code:e.code,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(ye(e.rfqId,e.quoteId),new Xd(e.message,{code:e.code,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(Se(e.rfqId,e.quoteId),new Zd(e.message,{code:e.code,quoteId:e.quoteId,rfqId:e.rfqId}));}}async quote(e,r){let n=Fr(r),s=await Br({account:this.#e,chainId:this.#t,exchange:this.#s,request:e,response:n,signer:this.#d}),i=this.#u.waitFor(Q(e.rfqId),`Timed out waiting for RFQ quote acknowledgement for ${e.rfqId}.`);try{return await this.#f(Cr(e,s)),await i}catch(o){throw this.#u.remove(Q(e.rfqId),i),o}}async cancelQuote(e){let r=ye(e.rfqId,e.quoteId),n=this.#u.waitFor(r,`Timed out waiting for RFQ quote cancellation acknowledgement for ${e.rfqId}.`);try{return await this.#f(Er(this.#e,e.rfqId,e.quoteId)),await n}catch(s){throw this.#u.remove(r,n),s}}async respondToConfirmation(e,r,n){let s=Se(e,r),i=this.#u.waitFor(s,`Timed out waiting for RFQ confirmation acknowledgement for ${e}.`);try{return await this.#f(kr(e,r,n)),await i}catch(o){throw this.#u.remove(s,i),o}}};function Q(t){return `ACK_RFQ_QUOTE:${t}`}function ye(t,e){return `ACK_RFQ_QUOTE_CANCEL:${t}:${e}`}function Se(t,e){return `ACK_RFQ_CONFIRMATION_RESPONSE:${t}:${e}`}function yi(){let t,e;return {promise:new Promise((n,s)=>{t=n,e=s;}),reject:e,resolve:t}}var P=class{#e;#t;#r=new d({heartbeat:new F});#s=new l;#n=new p({deriveServerState:gi});constructor(e){this.#e=e;}async subscribe(e){let{change:r,entry:n}=this.#n.add(e,{matches:Pi(e)});return await this.#a(n,r),m(n.subscriber.queue,()=>this.#d(n))}async#a(e,r){try{if((await this.#o()).reusedOpenSocket){let{before:s,after:i}=r,o=bi(s,i);this.#m(o);}}catch(n){throw await this.#d(e),n}}async#d(e){let{before:r,after:n}=this.#n.remove(e),s=Ri(r,n);this.#h(s),this.#n.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.#s.stop(),this.#n.endAll(),await this.#r.close();}#o(){return this.#r.connect({onClose:()=>this.#l(),onError:()=>this.#p(),onMessage:e=>this.#u(e),onOpen:()=>this.#i(),url:this.#e})}#i(){this.#s.resetBackoff(),this.#f();}#u(e){let r=RealtimeEventSchema.safeParse(e);r.success&&this.#n.dispatch(r.data);}#l(){this.#n.hasActiveSubscriptions()&&this.#y();}#p(){}#f(){this.#m(Array.from(this.#n.serverState().values()));}#m(e){e.length!==0&&this.#r.send(Ai(e));}#h(e){e.length!==0&&this.#r.send(qi(e));}#y(){this.#s.schedule({reconnect:()=>this.#o(),shouldReconnect:()=>this.#n.hasActiveSubscriptions()});}};function bi(t,e){return Array.from(e).flatMap(([r,n])=>t.has(r)?[]:[n])}function Ri(t,e){return Array.from(t).flatMap(([r,n])=>e.has(r)?[]:[n])}function gi(t){let e=new Map;for(let{subscription:r}of t)for(let n of vi(r))e.has(n.key)||e.set(n.key,n);return e}function Ai(t){return {action:"subscribe",subscriptions:t.map(({topic:e,type:r})=>({topic:e,type:r}))}}function qi(t){return {action:"unsubscribe",subscriptions:t.map(({topic:e,type:r})=>({topic:e,type:r}))}}function vi(t){switch(t.topic){case "comments":return (t.types??["comment_created"]).map(e=>_("comments",e));case "prices.crypto.binance":return [_("crypto_prices","update")];case "prices.crypto.chainlink":return [_("crypto_prices_chainlink","update")];case "prices.equity.pyth":return [_("equity_prices","update")];default:invariant(false,`Unknown RTDS topic: ${String(t)}`);}}function _(t,e){return {key:`${t}:${e}`,topic:t,type:e}}function Pi(t){switch(t.topic){case "comments":return e=>!(e.topic!=="comments"||t.types!==void 0&&t.types.length>0&&!t.types.includes(e.type)||(t.parentEntityId!==void 0||t.parentEntityType!==void 0)&&(!(e.type==="comment_created"||e.type==="comment_removed")||t.parentEntityId!==void 0&&e.payload.parentEntityID!==t.parentEntityId||t.parentEntityType!==void 0&&e.payload.parentEntityType!==t.parentEntityType));case "prices.crypto.binance":return e=>e.topic==="prices.crypto.binance"&&(t.symbols===void 0||t.symbols.length===0||t.symbols.includes(e.payload.symbol));case "prices.crypto.chainlink":return e=>e.topic==="prices.crypto.chainlink"&&(t.symbols===void 0||t.symbols.length===0||t.symbols.includes(e.payload.symbol));case "prices.equity.pyth":return e=>e.topic==="prices.equity.pyth"&&e.payload.symbol.toLowerCase()===t.symbol.toLowerCase()&&(t.types===void 0||t.types.length===0||t.types.includes(e.type));default:invariant(false,`Unknown RTDS topic: ${String(t)}`);}}var C=class{#e;#t;#r=new d({heartbeat:new B});#s=new l;#n=new p;constructor(e){this.#e=e.url;}async subscribe(e){let{entry:r}=this.#n.add(e);return await this.#a(r),m(r.subscriber.queue,()=>this.#d(r))}async#a(e){try{await this.#o();}catch(r){throw await this.#d(e),r}}async#d(e){this.#n.remove(e),this.#n.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.#s.stop(),this.#n.endAll(),await this.#r.close();}#o(){return this.#r.connect({onClose:()=>this.#l(),onError:()=>this.#p(),onMessage:e=>this.#u(e),onOpen:()=>this.#i(),url:this.#e})}#i(){this.#s.resetBackoff();}#u(e){let r=SportsResultEventSchema.safeParse(e);r.success&&this.#n.dispatch(r.data);}#l(){this.#n.hasActiveSubscriptions()&&this.#f();}#p(){}#f(){this.#s.schedule({reconnect:()=>this.#o(),shouldReconnect:()=>this.#n.hasActiveSubscriptions()});}};var U=class{#e;#t;get context(){return this.#e}get decorators(){return this.#t}get environment(){return this.context.environment}get clob(){return this.context.clob}get relayer(){return this.context.relayer}get rpc(){return this.context.rpc}get gamma(){return this.context.gamma}get data(){return this.context.data}get rfq(){return this.context.rfq}get webSockets(){return this.context.webSockets}get supportsGasless(){return this.context.apiKey?.supportGasless??false}constructor(e){this.#e=e,this.#t=[];}async resolveClobHeaders(e){return this.context.apiKey?.isBuilderKey?this.context.apiKey.authorize(e):Promise.resolve({})}async resolveRelayerHeaders(e){return this.context.apiKey?.supportGasless?this.context.apiKey.authorize(e):Promise.resolve({})}rememberDecorator(e){this.#t.push(e);}},Mi=z.object({key:ApiKeySchema,passphrase:z.string(),secret:z.string()}),Oi=z.object({wallet:EvmAddressSchema,credentials:Mi.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}),H=class extends U{constructor(e){super({apiKey:e.apiKey,environment:e.environment,data:new u({root:e.environment.data}),gamma:new u({root:e.environment.gamma}),clob:new u({root:e.environment.clob,resolveHeaders:r=>this.resolveClobHeaders(r)}),relayer:new u({root:e.environment.relayer,resolveHeaders:r=>this.resolveRelayerHeaders(r)}),rfq:new u({root:e.environment.rfq}),rpc:new V({url:e.environment.rpc}),webSockets:{clobMarket:new S({url:e.environment.clobMarketWs}),sports:new C({url:e.environment.sportsWs}),rtds:new P(e.environment.rtdsWs)}});}isSecureClient(){return false}isPublicClient(){return true}async closeSubscriptions(){await Promise.all([this.webSockets.clobMarket.close(),this.webSockets.rtds.close(),this.webSockets.sports.close()]).then(()=>{});}extend(e){return this.rememberDecorator(e),Object.assign(this,e(this)),this}beginAuthentication(e,r){let n=U$1(e,Oi);return Promise.resolve(async function*(){let s=Math.floor(Date.now()/1e3),i=n?.nonce??0,o=expectEvmAddress(yield _$1()),b=expectEvmAddress(n.wallet),R=W$1(this.environment,o,b);if(n.credentials!==void 0){let Ae=this.#e(n.credentials,R,r);try{if((await L(Ae)).includes(n.credentials.key))return Ae}catch(O){if(!(O instanceof d$1)||O.status!==401)throw O}}let x=yield {kind:"signAuthMessage",payload:tr({address:o,chainId:this.environment.chainId,nonce:i,timestamp:s})},M=await J(this,{address:o,nonce:i,signature:expectEvmSignature(x),timestamp:s});return this.#e(M,R,r)}.call(this))}#e(e,r,n){let s=new ge({account:r,apiKey:this.context.apiKey,credentials:e,environment:this.environment,signer:n});for(let i of this.decorators)s.extend(i);return s}},ge=class extends U{#e=false;get context(){return invariant(!this.#e,"This client has ended authentication and can no longer be used."),super.context}endAuthenticationLifecycle(){this.#e=true;}constructor(e){super({account:e.account,credentials:e.credentials,apiKey:e.apiKey,environment:e.environment,signer:e.signer,clob:new u({root:e.environment.clob,resolveHeaders:r=>this.resolveClobHeaders(r)}),relayer:new u({root:e.environment.relayer,resolveHeaders:r=>this.resolveRelayerHeaders(r)}),rpc:new V({url:e.environment.rpc}),gamma:new u({root:e.environment.gamma}),data:new u({root:e.environment.data}),rfq:new u({root:e.environment.rfq}),secureClob:new u({resolveHeaders:async r=>({...await this.resolveClobHeaders(r),...await this.#t(r)}),root:e.environment.clob}),webSockets:{clobMarket:new S({url:e.environment.clobMarketWs}),clobUser:new q({credentials:e.credentials,url:e.environment.clobUserWs}),rfqQuoter:new v({account:e.account,chainId:e.environment.chainId,credentials:e.credentials,exchange:e.environment.exchangeV3,headers:e.environment.rfqQuoterWsHeaders,signer:e.signer,url:e.environment.rfqQuoterWs}),sports:new C({url:e.environment.sportsWs}),rtds:new P(e.environment.rtdsWs)}});}get credentials(){return this.context.credentials}get account(){return this.context.account}get signer(){return this.context.signer}setupGaslessWallet(){return Promise.resolve(this)}get secureClob(){return this.context.secureClob}get webSockets(){return this.context.webSockets}async closeSubscriptions(){await Promise.allSettled([this.webSockets.clobMarket.close(),this.webSockets.rtds.close(),this.webSockets.sports.close(),this.webSockets.clobUser.close(),this.webSockets.rfqQuoter.close()]).then(()=>{});}isSecureClient(){return true}isPublicClient(){return false}extend(e){return this.rememberDecorator(e),Object.assign(this,e(this)),this}async endAuthentication(){let e=this.closeSubscriptions(),{apiKey:r,environment:n}=this.context;try{await N(this);}finally{this.endAuthenticationLifecycle(),await e;}let s=new H({apiKey:r,environment:n});for(let i of this.decorators)s.extend(i);return s}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 or(this.credentials.secret,r,e.method,e.path,e.body),POLY_TIMESTAMP:`${r}`}}catch(r){throw j.fromError(r,"Could not sign the L2-authenticated request")}}};function _r(t={}){return new H({environment:t.environment??le,apiKey:t.apiKey}).extend(ir)}var Ii=k(h,e,d$1,j,f,g,c,b,a),Li=k(a);async function Fi(t){let e=_r({environment:t.environment,apiKey:t.apiKey}),r=await Bi(e,t),n=await e.beginAuthentication({wallet:r,credentials:t.credentials,nonce:t.nonce},t.signer).then(Z(t.signer));if(n.account.walletType===WalletType.EOA||await ca(n,{wallet:n.account.wallet,type:n.account.walletType}))return n;if(n.account.walletType===WalletType.DEPOSIT_WALLET)return await Di(n),n;throw new a(`Wallet ${n.account.wallet} does not exist. Provide an existing wallet address, or omit wallet to use the default Deposit Wallet flow.`)}async function Bi(t,e){if(e.wallet!==void 0)return e.wallet;let r=expectEvmAddress(await e.signer.getAddress());return Y(t.rpc,r,t.environment.walletDerivation)}async function Di(t){let e=await Y(t.rpc,t.account.signer,t.environment.walletDerivation);if(!isSameEvmAddress(t.account.wallet,e))throw new a(`Wallet ${t.account.wallet} does not match the expected Deposit Wallet ${e} for this signer, nor a deployed wallet address.`);await(await fa(t)).wait();}
|
|
2
2
|
export{Ii as CreateSecureClientError,Li as SetupGaslessWalletError,ie as accountActions,ir as allActions,oe as analyticsActions,or as buildHmacSignature,_r as createPublicClient,Fi as createSecureClient,ce as dataActions,ae as discoveryActions,hc as preproduction,le as production,ks as relayerApiKey,Es as remoteBuilderSigning,ue as rewardsActions,rr as rfqActions,de as subscriptionsActions,nr as tradingActions,sr as walletActions};//# sourceMappingURL=index.js.map
|
|
3
3
|
//# sourceMappingURL=index.js.map
|