@polymarket/client 0.10.0 → 0.11.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.
@@ -0,0 +1,3 @@
1
+ import {o,h as h$1,g,n,c,b,a,i,j,k as k$1,l as l$1,m,e}from'./chunk-IPPWXOOG.js';import {EventIdSchema,PaginationCursorSchema,OrderSideSchema,ConditionIdSchema,EvmAddressSchema,ComboConditionIdSchema,TransactionIdSchema,BuilderCodeSchema,CommentParentEntityTypeSchema,CommentIdSchema,IsoDateTimeStringSchema,IsoCalendarDateStringSchema,QuestionIdSchema,PositionIdSchema,ClobAssetIdSchema,OrderType,PositiveDecimalNumberSchema,OrderSide,TxHashSchema,MarketIdSchema,toPositionId,toBaseUnits,toRfqId,toRfqQuoteId,toBuilderCode,SessionSignerKnownScope,SessionSignerScopeSchema,TradeStatus,toPaginationCursor,toDecimalString,toComboConditionId,toConditionId}from'@polymarket/bindings';export{SessionSignerKnownScope as qg}from'@polymarket/bindings';import {AssetTypeSchema,SignatureType,AssetType,ClosedOnlyModeSchema,OpenOrdersPageSchema,END_CURSOR,OpenOrderSchema,ClobTradesPageSchema,NotificationsResponseSchema,BalanceAllowanceResponseSchema,OrderScoringResponseSchema,OrdersScoringResponseSchema,UserEarningsPageSchema,TotalUserEarningsResponseSchema,UserRewardsEarningsPageSchema,RewardsPercentagesSchema,ApiKeyCredsSchema,ApiKeysResponseSchema,BuilderApiKeyCredsSchema,BuilderApiKeysResponseSchema,PaginatedBuilderTradesSchema,MidpointSchema,MidpointsSchema,FetchTickSizeResponseSchema,FetchNegRiskResponseSchema,ResolveConditionByTokenResponseSchema,FetchMarketInfoResponseSchema,FetchBuilderFeeRatesResponseSchema,PriceSchema,PricesSchema,FetchOrderBookResponseSchema,OrderBooksSchema,SpreadSchema,SpreadsSchema,LastTradePriceSchema,LastTradePricesSchema,PaginatedCurrentRewardsSchema,PaginatedMarketRewardsSchema,CancelOrdersResponseSchema,OrderResponseSchema,OrderResponsesSchema,ActiveSessionSignersResponseSchema}from'@polymarket/bindings/clob';import {isHexString,expectNonEmptyArray,isPrivateKey,expectEvmAddress,isSameEvmAddress,ZERO_ADDRESS,PolymarketError,expectHexString,unwrap,invariant,delay,expectEvmSignature,expectErc1271Signature,ResultAsync,setNonBlockingInterval,setNonBlockingTimeout,expectPrivateKey,isPresent,ok,err,expectPresent,expectSessionSignerSignature,errAsync}from'@polymarket/types';import {z as z$1}from'zod';import {WalletType,SeriesIdSchema,MarketClarificationState,ListCommentsResponseSchema,ListEventsKeysetResponseSchema,EventSchema,FetchEventTagsResponseSchema,ListMarketClarificationsResponseSchema,ListMarketsKeysetResponseSchema,FetchMarketTagsResponseSchema,MarketSchema,PublicProfileSchema,PublicSearchResponseSchema,ListSeriesResponseSchema,SeriesSchema,ListSportsMetadataResponseSchema,SportsMarketTypesResponseSchema,ListTagsResponseSchema,TagSchema,ListRelatedTagsResponseSchema,ListRelatedTagResourcesResponseSchema,ListTeamsResponseSchema}from'@polymarket/bindings/gamma';import {AbiFunction,Hash,Bytes,AbiParameters,ContractAddress,TypedData,Secp256k1,Address,Signature}from'ox';import Bn from'ky';import {TradeFilterTypeSchema,SortDirectionSchema,ActivityTypeSchema,CanonicalMarketConditionIdSchema,LeaderboardWindowSchema,BuilderVolumeIntervalSchema,TraderLeaderboardSortSchema,PriceHistoryIntervalSchema,PriceHistoryInterval,PositionSortBySchema,PositionFilterTypeSchema,PositionStatusSchema,ComboPositionStatusSchema,ComboPositionStatus,ComboPositionSortBySchema,UserPnlFidelitySchema,UserPnlIntervalSchema,ListTradesResponseSchema,ListActivityResponseSchema,ListComboActivityResponseSchema,FetchResolutionsResponseSchema,FetchEventLiveVolumeResponseSchema,ListBuilderLeaderboardResponseSchema,FetchBuilderVolumeResponseSchema,ListTraderLeaderboardResponseSchema,FetchTraderLeaderboardStandingResponseSchema,ListBiggestWinnersResponseSchema,ListMarketHoldersResponseSchema,ListPriceHistoryResponseSchema,FetchOpenInterestResponseSchema,ListPositionsResponseSchema,ListComboPositionsResponseSchema,FetchPortfolioValueResponseSchema,FetchUserStatsResponseSchema,FetchUserPnlResponseSchema,FetchUserVolumeResponseSchema}from'@polymarket/bindings/data';export{UserPnlFidelity as $e,ResolutionMarketType as Cc,ResolutionReporter as Dc,ResolutionSource as Ec,ResolutionStatus as Fc,BiggestWinnerKind as Qc,BuilderVolumeInterval as Rc,LeaderboardWindow as Sc,TraderLeaderboardSort as Tc,PriceHistoryInterval as Wc,ComboPositionSortBy as We,ComboPositionStatus as Xe,PositionFilterType as Ye,PositionSortBy as Ze,PositionStatus as _e,UserPnlInterval as af,ComboActivityType as va,SortDirection as wa,TipSide as xa,TradeFilterType as ya}from'@polymarket/bindings/data';import {RelayerTransactionType,RelayerExecuteRequestSchema,RelayerTransactionState,RelayerAuthorizeSessionSignerStatus,RelayerRevokeSessionSignerStatus,RelayerExecuteParamsSchema,RelayerDeployedResponseSchema,GaslessTransactionSchema,RelayerExecuteResponseSchema,RelayerAuthorizeSessionSignerResponseSchema,RelayerRevokeSessionSignerResponseSchema}from'@polymarket/bindings/relayer';import {CollateralReturnPlanSchema,RfqRejectionCode,RfqSide,RfqRequestedSizeUnit,RfqDirection,RfqKnownErrorCode,ComboQuoteUnavailableReason,RfqStatus,ComboAcceptFailureReason,RfqExecutionStatus,CollateralReturnPlanResponseSchema,ListComboMarketsResponseSchema,BuilderRfqCreateResponseSchema,BuilderRfqStatusResponseSchema}from'@polymarket/bindings/combos';export{ComboAcceptFailureReason as $f,ComboQuoteUnavailableReason as ag,RfqConfirmationDecision as bg,RfqDirection as cg,RfqExecutionStatus as dg,RfqKnownErrorCode as eg,RfqRejectionCode as fg,RfqRequestedSizeUnit as gg,RfqSide as hg,RfqStatus as ig,CollateralReturnKnownOperationKind as lc}from'@polymarket/bindings/combos';import {PerpsPnlIntervalSchema,PerpsWithdrawalStatusSchema,PerpsDepositStatusSchema,PerpsInstrumentIdSchema,PerpsClientOrderIdSchema,PerpsOrderIdSchema,PerpsSortDirectionSchema,PerpsDecimalInputSchema,PerpsTimeInForce,PerpsPostOrderAckSchema,PerpsCommandAckSchema,PerpsInstrumentCategorySchema,PerpsKlineIntervalSchema,PerpsTradeIdSchema,PerpsTpSlKind,PerpsTpSlScope,PerpsCancelOrderResultSchema,PerpsCancelAllOrdersResponseSchema,PerpsUpdateLeverageResultSchema,FetchPerpsBalancesResponseSchema,FetchPerpsPortfolioResponseSchema,FetchPerpsAccountStatsResponseSchema,FetchPerpsAutoCancelStatusResponseSchema,FetchPerpsAccountConfigResponseSchema,FetchPerpsOpenOrdersResponseSchema,FetchPerpsOrdersResponseSchema,ListPerpsFillsResponseSchema,ListPerpsFundingPaymentsResponseSchema,ListPerpsDepositsResponseSchema,ListPerpsWithdrawalsResponseSchema,ListPerpsEquityHistoryResponseSchema,ListPerpsPnlHistoryResponseSchema,ListPerpsNotificationsResponseSchema,FetchPerpsUnreadNotificationsCountResponseSchema,MarkPerpsNotificationsReadResponseSchema,PerpsAutoCancelResponseSchema,FetchPerpsInstrumentsResponseSchema,FetchPerpsTickersResponseSchema,FetchPerpsStatisticsResponseSchema,PerpsBookSchema,FetchPerpsCandlesResponseSchema,FetchPerpsFundingHistoryResponseSchema,FetchPerpsTradesResponseSchema,FetchPerpsFeesResponseSchema,PerpsDeleteProxyResponseSchema,PerpsWithdrawResponseSchema,PerpsCreateProxyResponseSchema,PerpsCredentialsResponseSchema}from'@polymarket/bindings/perps';import {encode}from'@msgpack/msgpack';import {PerpsNotificationsResyncFrameSchema,PerpsSessionUpdateEventSchema}from'@polymarket/bindings/subscriptions';import {pushable}from'it-pushable';import KS from'it-merge';function l(e,r){let t=r.safeParse(e);if(t.success)return t.data;throw a.fromZodError(t.error)}var k=z$1.number().int().positive(),Ln=z$1.object({offset:z$1.number().int().min(0),pageSize:k});function x(e,r,t=[]){function o(){return {async firstPage(){return {items:t,hasMore:false}},from(){return o()},async*[Symbol.asyncIterator](){}}}function n(s=r){return {firstPage(){return unwrap(e(s))},from(a){return a===void 0?o():n(a)},async*[Symbol.asyncIterator](){let a=s;for(;;){let y=await unwrap(e(a));if(yield y,!y.hasMore)return;a=y.nextCursor;}}}}return n()}function J(e){return toPaginationCursor(btoa(JSON.stringify(Ln.parse(e))))}function te(e,r){if(e===void 0)return {offset:0,pageSize:r};try{return Ln.parse(JSON.parse(atob(e)))}catch(t){throw new a("Invalid pagination cursor",{cause:t})}}function f(e){return function(t){return ResultAsync.fromPromise(t.json(),()=>new b(`Received non-JSON response from ${t.url}`)).andThen(o=>Lc(t.url,e,o))}}function Mn(e){return ResultAsync.fromPromise(e.blob(),()=>new b(`Received unreadable binary response from ${e.url}`))}function Lc(e,r,t){let o=r.safeParse(t);return o.success?ok(o.data):err(b.fromZodError(o.error,{endpoint:e}))}var Un=class{#e;constructor({url:r}){this.#e=r;}async ethCall(r){let t=await this.#s({jsonrpc:"2.0",id:1,method:"eth_call",params:[{to:r.to,data:r.data},"latest"]});if("error"in t)throw new g(`JSON-RPC eth_call failed: ${t.error.message}`,{cause:t.error,status:200});if(typeof t.result!="string")throw new b("Expected JSON-RPC eth_call result to be a hex string");if(!Nn(t.result))throw new b("Expected JSON-RPC eth_call result to be a hex string");return t.result}async ethCallBatch(r){return r.length===0?[]:this.#r(r)}async ethEstimateGas(r){let t={to:r.to};r.data!==void 0&&(t.data=r.data),r.from!==void 0&&(t.from=r.from),r.gasPrice!==void 0&&(t.gasPrice=zn(r.gasPrice)),r.value!==void 0&&(t.value=zn(r.value));let o=await this.#s({jsonrpc:"2.0",id:1,method:"eth_estimateGas",params:[t]});if("error"in o)throw new g(`JSON-RPC eth_estimateGas failed: ${o.error.message}`,{cause:o.error,status:200});return BigInt(_n(o.result,"eth_estimateGas"))}async#r(r){if(r.length===1)return [await this.ethCall(r[0])];try{return await this.#n(r)}catch(t){if(!(t instanceof g)||t.status<500)throw t;let o=Math.ceil(r.length/2),[n,s]=await Promise.all([this.#r(r.slice(0,o)),this.#r(r.slice(o))]);return [...n,...s]}}async#n(r){let t=await this.#t(r.map((n,s)=>({jsonrpc:"2.0",id:s+1,method:"eth_call",params:[{to:n.to,data:n.data},"latest"]}))),o=new Map;for(let n of t){if("error"in n&&n.id===null)throw new g(`JSON-RPC eth_call failed: ${n.error.message}`,{cause:n.error,status:200});n.id!==null&&o.set(n.id,n);}return r.map((n,s)=>{let a=s+1,y=o.get(a);if(y===void 0)throw new b("Expected JSON-RPC batch response for every request");if("error"in y)throw new g(`JSON-RPC eth_call failed: ${y.error.message}`,{cause:y.error,status:200});return _n(y.result)})}async#s(r){let t;try{t=await Bn.post(this.#e,{json:r,throwHttpErrors:!1});}catch(n){throw c.fromError(n)}if(!t.ok)throw new g(`JSON-RPC request to ${this.#e} failed with status ${t.status}`,{status:t.status});let o;try{o=await t.json();}catch(n){throw new b("Expected JSON-RPC response body to be JSON",{cause:n})}if(!Dn(o))throw new b("Unexpected JSON-RPC response shape");return o}async#t(r){let t;try{t=await Bn.post(this.#e,{json:r,throwHttpErrors:!1});}catch(n){throw c.fromError(n)}if(!t.ok)throw new g(`JSON-RPC request to ${this.#e} failed with status ${t.status}`,{status:t.status});let o;try{o=await t.json();}catch(n){throw new b("Expected JSON-RPC response body to be JSON",{cause:n})}if(!Array.isArray(o)||!o.every(n=>Dn(n)))throw new b("Unexpected JSON-RPC response shape");return o}};function Wn(e){if(!(e instanceof g)||!jn(e.cause))return false;let r=[e.cause.message,Fc(e.cause.data)].join(" ").toLowerCase();return (e.cause.code===3||e.cause.code===-32e3||e.cause.code===-32003||e.cause.code===-32015||e.cause.code===-32603)&&(r.includes("execution reverted")||r.includes("revert")||r.includes("invalid opcode"))}function Dn(e){return !Hn(e)||e.jsonrpc!=="2.0"?false:"error"in e?jn(e.error):"result"in e}function jn(e){return Hn(e)&&typeof e.code=="number"&&typeof e.message=="string"}function Hn(e){return typeof e=="object"&&e!==null}function Nn(e){return /^0x[a-fA-F0-9]*$/.test(e)}function _n(e,r="eth_call"){if(typeof e!="string"||!Nn(e))throw new b(`Expected JSON-RPC ${r} result to be a hex string`);return e}function zn(e){return `0x${e.toString(16)}`}function Fc(e){if(e===void 0)return "";if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return ""}}var Kn=(t=>(t.OWNER="OWNER",t.SESSION_KEY="SESSION_KEY",t))(Kn||{}),Bc="0x0000000000000000000000000000000000000000000000000000000000000000",Uc="0x6492649264926492649264926492649264926492649264926492649264926492";function Ah(e,r,t){let o=td(e,r,t);return {signer:r,wallet:t,...o}}function Ee(e){switch(e){case WalletType.EOA:return SignatureType.EOA;case WalletType.POLY_PROXY:return SignatureType.POLY_PROXY;case WalletType.GNOSIS_SAFE:return SignatureType.POLY_GNOSIS_SAFE;case WalletType.DEPOSIT_WALLET:return SignatureType.POLY_1271}}function Tr(e){let r=Ee(e.walletType);return {maker:e.wallet,signatureType:r,signer:r===SignatureType.POLY_1271?e.wallet:e.signer}}function nr(e,r){return e.signerType==="OWNER"?r:Dc(e.signer,r)}function Dc(e,r){let t=expectHexString(`0x${e.slice(2).padStart(64,"0")}`),o=AbiParameters.encode([{type:"bytes32"},{type:"bytes32"},{type:"bytes"}],[t,Bc,r]);return expectSessionSignerSignature(`${o}${Uc.slice(2)}`)}var _c="3d3d606380380380913d393d73%s5af4602a57600080fd5b602d8060366000396000f3363d3d373d3d3d363d73%s5af43d82803e903d91602b57fd5bf352e831dd00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000000";function zc(e){let r=_c.replace("%s",e.proxyFactory.slice(2).toLowerCase()).replace("%s",e.proxyImplementation.slice(2).toLowerCase());return expectHexString(Hash.keccak256(`0x${r}`))}function Wc(e,r){return expectEvmAddress(ContractAddress.fromCreate2({bytecodeHash:zc(r),from:r.proxyFactory,salt:Hash.keccak256(AbiParameters.encodePacked(["address"],[e]))}))}function jc(e,r){return expectEvmAddress(ContractAddress.fromCreate2({bytecodeHash:r.safeInitCodeHash,from:r.safeFactory,salt:Hash.keccak256(AbiParameters.encode([{name:"address",type:"address"}],[e]))}))}var Hc="0xcc3735a920a3ca505d382bbc545af43d6000803e6038573d6000fd5b3d6000f3",Nc="0x5155f3363d3d373d3d363d7f360894a13ba1a3210667c828492db98dca3e2076",Kc=0x61003d3d8160233d3973n;function Gn(e,r){let t=expectHexString(`0x${e.slice(2).padStart(64,"0")}`),o=AbiParameters.encode([{type:"address"},{type:"bytes32"}],[r.depositWalletFactory,t]);return expectEvmAddress(ContractAddress.fromCreate2({bytecodeHash:Zc(r.depositWalletImplementation,o),from:r.depositWalletFactory,salt:Hash.keccak256(o)}))}var Gc="0xb3582b35133d50545afa5036515af43d6000803e604d573d6000fd5b3d6000f3",$c="0x1b60e01b36527fa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6c",Vc="0x60195155f3363d3d373d3d363d602036600436635c60da",Yc=0x6100523d8160233d3973n,Qc="0x49493a4d";function $n(e,r){let t=expectHexString(`0x${e.slice(2).padStart(64,"0")}`),o=AbiParameters.encode([{type:"address"},{type:"bytes32"}],[r.depositWalletFactory,t]);return expectEvmAddress(ContractAddress.fromCreate2({bytecodeHash:Jc(r.depositWalletBeacon,o),from:r.depositWalletFactory,salt:Hash.keccak256(o)}))}function Zc(e,r){let t=BigInt((r.length-2)/2),o=Kc+(t<<56n);return expectHexString(Hash.keccak256(Bytes.concat(Bytes.fromNumber(o,{size:10}),Bytes.fromHex(e),Bytes.fromHex("0x6009"),Bytes.fromHex(Nc),Bytes.fromHex(Hc),Bytes.fromHex(r)),{as:"Hex"}))}function Jc(e,r){let t=BigInt((r.length-2)/2),o=Yc+(t<<56n);return expectHexString(Hash.keccak256(Bytes.concat(Bytes.fromNumber(o,{size:10}),Bytes.fromHex(e),Bytes.fromHex(Vc),Bytes.fromHex($c),Bytes.fromHex(Gc),Bytes.fromHex(r)),{as:"Hex"}))}async function Xc(e,r){try{let t=await e.ethCall({to:r,data:Qc});return rd(t)}catch(t){if(Wn(t))return ZERO_ADDRESS;throw t}}async function ed(e,r){let t=await Xc(e,r);return !isSameEvmAddress(t,ZERO_ADDRESS)}async function Vn(e,r,t){return await ed(e,t.depositWalletFactory)?$n(r,t):Gn(r,t)}function rd(e){return e.length<66?ZERO_ADDRESS:expectEvmAddress(`0x${e.slice(-40)}`)}function td(e,r,t){if(isSameEvmAddress(t,r))return {signerType:"OWNER",walletType:WalletType.EOA};let o=e.walletDerivation;return isSameEvmAddress(t,$n(r,o))?{signerType:"OWNER",walletType:WalletType.DEPOSIT_WALLET}:isSameEvmAddress(t,Gn(r,o))?{signerType:"OWNER",walletType:WalletType.DEPOSIT_WALLET}:isSameEvmAddress(t,jc(r,o))?{signerType:"OWNER",walletType:WalletType.GNOSIS_SAFE}:isSameEvmAddress(t,Wc(r,o))?{signerType:"OWNER",walletType:WalletType.POLY_PROXY}:{signerType:"SESSION_KEY",walletType:WalletType.DEPOSIT_WALLET}}var Yn=z$1.string().transform(e=>e);function ee(e){return z$1.union([z$1.object({...e,assetId:Yn,tokenId:z$1.never().optional()}),z$1.object({...e,assetId:z$1.never().optional(),tokenId:z$1.string()})])}function be(e){return z$1.union([z$1.object({...e,assetId:Yn.optional(),tokenId:z$1.never().optional()}),z$1.object({...e,assetId:z$1.never().optional(),tokenId:z$1.string().optional()})])}function h(e,r){if(nd(r))return sd(e,r.exceptions);let t=new URLSearchParams;for(let[o,n]of Object.entries(r)){let s=e[o];if(s!==void 0){if(jt(s)){for(let a of s)t.append(n,we(a));continue}t.append(n,we(s));}}return t}function T(e={}){return {format:"snake_case",exceptions:e}}function Qn(e){let r=new URLSearchParams;for(let[t,o]of Object.entries(e))if(o!==void 0){if(Array.isArray(o)){r.append(t,o.map(we).join(","));continue}r.append(t,we(o));}return r}var je=z$1.union([z$1.number().int().min(0),z$1.date()]).transform(e=>e instanceof Date?Math.floor(e.getTime()/1e3):e),sr=z$1.union([z$1.literal("full"),z$1.object({start:je.optional(),end:je.optional()}).refine(e=>!e.end||e.end>=(e.start??0),"end must not precede start")]).transform(e=>e==="full"?{start:1}:e),Wt=EventIdSchema.refine(e=>/^[1-9]\d*$/.test(e)&&BigInt(e)<=2147483647n,"Expected a positive 32-bit event ID");function ue(e,r){return z$1.array(e).min(1).transform(t=>[...new Map(t.map(o=>[o.toLowerCase(),o])).values()]).refine(t=>t.length<=r,`At most ${r} distinct ids`)}function D(e){let r=new URLSearchParams;for(let[t,o]of Object.entries(e)){if(o===void 0)continue;let n=Zn(t);if(jt(o)){r.append(n,o.map(we).join(","));continue}r.append(n,we(o));}return r}function nd(e){return "format"in e}function sd(e,r){let t=new URLSearchParams;for(let[o,n]of Object.entries(e)){if(n===void 0)continue;let s=r[o]??Zn(o);if(jt(n)){for(let a of n)t.append(s,we(a));continue}t.append(s,we(n));}return t}function jt(e){return Array.isArray(e)}function Zn(e){return e.replace(/[A-Z]/g,r=>`_${r.toLowerCase()}`)}function we(e){return String(e)}var Vh=o(h$1,g,n,c,b);async function Yh(e){return (await unwrap(e.secureClob.get("/auth/ban-status/closed-only").andThen(f(ClosedOnlyModeSchema)))).closedOnly}var Ed=z$1.object({cursor:PaginationCursorSchema.optional(),id:z$1.string().optional(),market:z$1.string().optional()}),Sd=be(Ed.shape).default({}),Qh=o(h$1,g,n,c,b,a);function Zh(e,r){let t=l(r,Sd),{cursor:o}=t;return x(n=>e.secureClob.get("/data/orders",{params:h({assetId:t.assetId??t.tokenId,id:t.id,market:t.market,nextCursor:n},T({assetId:"asset_id"}))}).andThen(f(OpenOrdersPageSchema)).map(s=>({items:s.data,hasMore:s.nextCursor!==END_CURSOR,nextCursor:s.nextCursor===END_CURSOR?void 0:toPaginationCursor(s.nextCursor)})),o)}var hd=z$1.object({orderId:z$1.string()}),Jh=o(h$1,g,n,c,b,a);async function Xh(e,r){let t=l(r,hd);return unwrap(e.secureClob.get(`/data/order/${t.orderId}`).andThen(f(OpenOrderSchema)))}var Td={after:z$1.string().optional(),before:z$1.string().optional(),cursor:PaginationCursorSchema.optional(),id:z$1.string().optional(),makerAddress:z$1.string().optional(),market:z$1.string().optional()},xd=be(Td).default({}),eT=o(h$1,g,n,c,b,a);function Jn(e,r){let t=l(r,xd),{cursor:o}=t;return x(n=>e.secureClob.get("/data/trades",{params:h({after:t.after,assetId:t.assetId??t.tokenId,before:t.before,id:t.id,makerAddress:t.makerAddress,market:t.market,nextCursor:n},T({assetId:"asset_id"}))}).andThen(f(ClobTradesPageSchema)).map(s=>({items:s.data,hasMore:s.nextCursor!==END_CURSOR,nextCursor:s.nextCursor===END_CURSOR?void 0:toPaginationCursor(s.nextCursor)})),o)}var rT=o(h$1,g,n,c,b),Cd=z$1.object({ids:z$1.array(z$1.string()).min(1)});async function tT(e){let r=Ee(e.account.walletType);return unwrap(e.secureClob.get("/notifications",{params:h({signatureType:r},T())}).andThen(f(NotificationsResponseSchema)))}var oT=o(h$1,g,n,c,b,a);async function nT(e,r){let t=l(r,Cd),o=Ee(e.account.walletType),n=h({ids:t.ids.join(","),signatureType:o},T());await unwrap(e.secureClob.del("/notifications",{params:n}));}var Xn=z$1.object({assetType:AssetTypeSchema}),Id=be(Xn.shape),sT=o(h$1,g,n,c,b,a);async function Ht(e,r){let t=l(r,Id),o=Ee(e.account.walletType);return unwrap(e.secureClob.get("/balance-allowance",{params:h({assetType:t.assetType,tokenId:t.assetId??t.tokenId,signatureType:o},T())}).andThen(f(BalanceAllowanceResponseSchema)))}var bd=be(Xn.shape),aT=o(h$1,g,n,c,b,a);async function es(e,r){let t=l(r,bd),o=Ee(e.account.walletType),n=h({assetType:t.assetType,tokenId:t.assetId??t.tokenId,signatureType:o},T());return await unwrap(e.secureClob.get("/balance-allowance/update",{params:n})),Ht(e,t)}var vd=z$1.object({orderId:z$1.string()}),iT=o(h$1,g,n,c,b,a);async function pT(e,r){let t=l(r,vd);return (await unwrap(e.secureClob.get("/order-scoring",{params:h(t,T())}).andThen(f(OrderScoringResponseSchema)))).scoring}var qd=z$1.object({orderIds:z$1.array(z$1.string())}),cT=o(h$1,g,n,c,b,a);async function dT(e,r){let o=l(r,qd).orderIds;return unwrap(e.secureClob.post("/orders-scoring",{json:o}).andThen(f(OrdersScoringResponseSchema)))}var rs=z$1.object({cursor:PaginationCursorSchema.optional(),date:z$1.string()}),uT=o(h$1,g,n,c,b,a);function lT(e,r){let{cursor:t,...o}=l(r,rs),n=Ee(e.account.walletType);return x(s=>e.secureClob.get("/rewards/user",{params:h({...o,nextCursor:s,signatureType:n},T())}).andThen(f(UserEarningsPageSchema)).map(a=>({items:a.data,hasMore:a.nextCursor!==END_CURSOR,nextCursor:a.nextCursor===END_CURSOR?void 0:toPaginationCursor(a.nextCursor)})),t)}var mT=o(h$1,g,n,c,b,a);async function yT(e,r){let t=l(r,rs),o=Ee(e.account.walletType);return unwrap(e.secureClob.get("/rewards/user/total",{params:h({...t,signatureType:o},T())}).andThen(f(TotalUserEarningsResponseSchema)))}var kd=z$1.object({cursor:PaginationCursorSchema.optional(),date:z$1.string(),noCompetition:z$1.boolean().optional(),orderBy:z$1.string().optional(),pageSize:k.max(500).default(100),position:z$1.string().optional()}),fT=o(h$1,g,n,c,b,a);function PT(e,r){let{cursor:t,...o}=l(r,kd),n=Ee(e.account.walletType);return x(s=>e.secureClob.get("/rewards/user/markets",{params:h({...o,nextCursor:s,signatureType:n},T())}).andThen(f(UserRewardsEarningsPageSchema)).map(a=>({items:a.data,hasMore:a.nextCursor!==END_CURSOR,nextCursor:a.nextCursor===END_CURSOR?void 0:toPaginationCursor(a.nextCursor)})),t)}var gT=o(h$1,g,n,c,b);async function RT(e){let r=Ee(e.account.walletType);return unwrap(e.secureClob.get("/rewards/user/percentages",{params:h({signatureType:r},T())}).andThen(f(RewardsPercentagesSchema)))}function _(e,r={}){let{retries:t=2,maxDelaySeconds:o=5,sleep:n=delay}=r;function s(a){return e().orElse(y=>{if(!(y instanceof h$1)||a<=0)return errAsync(y);let P=y.retryAfter??1;return P>o?errAsync(y):ResultAsync.fromSafePromise(n(P*1e3).catch(()=>{})).andThen(()=>s(a-1))})}return s(t)}var Dd=z$1.object({cursor:PaginationCursorSchema.optional(),pageSize:k.max(1e3).default(100),user:EvmAddressSchema.optional(),takerOnly:z$1.boolean().optional(),filterType:TradeFilterTypeSchema.optional(),filterAmount:z$1.number().min(0).optional(),conditionId:z$1.union([ConditionIdSchema,ue(ConditionIdSchema,20)]).optional(),eventId:z$1.array(EventIdSchema).min(1).optional(),side:OrderSideSchema.optional(),window:sr.optional()}).refine(e=>!(e.conditionId&&e.eventId),{message:"Provide conditionId or eventId, not both",path:["eventId"]}),wT=o(h$1,g,c,b,a);function LT(e,r={}){let{cursor:t,pageSize:o,window:n,...s}=l(r,Dd);return x(a=>_(()=>e.data.get("/v2/trades",{params:D({...s,...n,limit:o,cursor:a})})).andThen(f(ListTradesResponseSchema)),t)}var _d=z$1.object({cursor:PaginationCursorSchema.optional(),pageSize:k.max(1e3).default(100),user:EvmAddressSchema,conditionId:z$1.union([ConditionIdSchema,ue(ConditionIdSchema,20)]).optional(),eventId:z$1.array(EventIdSchema).min(1).optional(),type:z$1.array(ActivityTypeSchema).min(1).optional(),side:OrderSideSchema.optional(),sortDirection:SortDirectionSchema.optional(),window:sr.optional()}).refine(e=>!(e.conditionId&&e.eventId),{message:"Provide conditionId or eventId, not both",path:["eventId"]}),FT=o(h$1,g,c,b,a);function MT(e,r){let{cursor:t,pageSize:o,window:n,...s}=l(r,_d);return x(a=>_(()=>e.data.get("/v2/activity",{params:D({...s,...n,excludeDepositsWithdrawals:false,limit:o,cursor:a})})).andThen(f(ListActivityResponseSchema)),t)}var zd=z$1.object({cursor:PaginationCursorSchema.optional(),pageSize:k.max(1e3).default(100),user:EvmAddressSchema,conditionId:z$1.union([ComboConditionIdSchema,ue(ComboConditionIdSchema,20)]).optional()}),BT=o(h$1,g,c,b,a);function UT(e,r){let{cursor:t,pageSize:o,...n}=l(r,zd);return x(s=>_(()=>e.data.get("/v2/activity/combos",{params:D({...n,limit:o,cursor:s})})).andThen(f(ListComboActivityResponseSchema)),t)}var jd=64,Hd=/^0x[0-9a-fA-F]{62}$/,Nd=/^0x[0-9a-fA-F]{64}$/,Gt="0x0000000000000000000000000000000000000000000000000000000000000000",Kd=AbiFunction.from("function approve(address spender, uint256 amount)"),is=AbiFunction.from("function allowance(address owner, address spender) view returns (uint256)"),Gd=AbiFunction.from("function transfer(address recipient, uint256 amount)"),$d=AbiFunction.from("function authorizeSessionSigner(address sessionSigner, uint256 validUntil)"),Vd=AbiFunction.from("function revokeSessionSigner(address sessionSigner)"),Yd=AbiFunction.from("function deposit(address token, uint256 amount, address to)"),Qd=AbiFunction.from("function setApprovalForAll(address operator, bool approved)"),ps=AbiFunction.from("function isApprovedForAll(address account, address operator) view returns (bool)"),cs=AbiFunction.from("function balanceOf(address account, uint256 id) view returns (uint256)"),ds=AbiFunction.from("function balanceOfBatch(address[] accounts, uint256[] ids) view returns (uint256[])"),Zd=AbiFunction.from("function splitPosition(address collateralToken, bytes32 parentCollectionId, bytes32 conditionId, uint256[] partition, uint256 amount)"),Jd=AbiFunction.from("function mergePositions(address collateralToken, bytes32 parentCollectionId, bytes32 conditionId, uint256[] partition, uint256 amount)"),Xd=AbiFunction.from("function redeemPositions(address collateralToken, bytes32 parentCollectionId, bytes32 conditionId, uint256[] indexSets)"),eu=AbiFunction.from("function split(bytes31 conditionId, uint256 amount)"),ru=AbiFunction.from("function merge(bytes31 conditionId, uint256 amount)"),tu=AbiFunction.from("function redeem(bytes31 conditionId, uint256 outcomeIndex, uint256 amount)"),ou=AbiFunction.from("function prepareCondition(uint256[] legs) returns (bytes31)"),nu=AbiFunction.from("function multiSend(bytes)"),su=AbiFunction.from("function proxy((uint8 typeCode, address to, uint256 value, bytes data)[] calls) returns (bytes[])"),us=[1n,2n],au=[1n,2n],re=(1n<<256n)-1n,$T=o(a);function Vr(e,r,t){if(t<0n)throw new a("Approval amount must be non-negative");if(t>re)throw new a("Approval amount exceeds uint256 range");return {data:iu(r,t),to:e}}function ls(e,r,t){return {data:AbiFunction.encodeData(is,[r,t]),to:e}}function ms(e){return AbiFunction.decodeResult(is,e)}function Yr(e,r,t){return {data:pu(r,t),to:e}}function ys(e,r,t){return {data:AbiFunction.encodeData(ps,[r,t]),to:e}}function fs(e){return AbiFunction.decodeResult(ps,e)}function Ps(e,r,t){return {data:AbiFunction.encodeData(cs,[r,he(BigInt(t),"Position ID")]),to:e}}function gs(e){return AbiFunction.decodeResult(cs,e)}function Qr(e,r,t){return {data:AbiFunction.encodeData(ds,[t.map(()=>r),t.map(o=>he(BigInt(o),"id"))]),to:e}}function Zr(e){return AbiFunction.decodeResult(ds,e)}var VT=o(a);function $t(e,r,t){if(t<0n)throw new a("Transfer amount must be non-negative");if(t>re)throw new a("Transfer amount exceeds uint256 range");return {data:cu(r,t),to:e}}function Rs(e,r,t){return {data:AbiFunction.encodeData($d,[r,he(t,"Session key expiry")]),to:e}}function Es(e,r){return {data:AbiFunction.encodeData(Vd,[r]),to:e}}var YT=o(a);function Ss(e,r,t,o){if(t<=0n)throw new a("Perps deposit amount must be positive");return {data:AbiFunction.encodeData(Yd,[r,he(t,"Perps deposit amount"),o]),to:e}}var QT=o(a);function hs(e,r,t,o){return {data:du(r,t,o),to:e}}var ZT=o(a);function Ts(e,r,t,o){return {data:uu(r,t,o),to:e}}var JT=o(a);function xs(e,r,t){return {data:lu(r,t),to:e}}var XT=o(a);function Vt(e,r,t){return {data:AbiFunction.encodeData(eu,[Zt(r),he(t,"Split amount")]),to:e}}var ex=o(a);function Yt(e,r,t){return {data:AbiFunction.encodeData(ru,[Zt(r),he(t,"Merge amount")]),to:e}}var rx=o(a);function Jr(e,r,t,o){return {data:AbiFunction.encodeData(tu,[Zt(r),BigInt(mu(t)),he(o,"Redeem amount")]),to:e}}var tx=o(a);function Qt(e,r){return {data:AbiFunction.encodeData(ou,[r.map(t=>he(t,"Leg position ID"))]),to:e}}function iu(e,r){return invariant(r>=0n,"Approval amount must be non-negative"),AbiFunction.encodeData(Kd,[e,r])}function pu(e,r){return AbiFunction.encodeData(Qd,[e,r])}function cu(e,r){return AbiFunction.encodeData(Gd,[e,r])}function du(e,r,t){return AbiFunction.encodeData(Zd,[e,Gt,r,us,he(t,"Split amount")])}function uu(e,r,t){return AbiFunction.encodeData(Jd,[e,Gt,r,us,he(t,"Merge amount")])}function lu(e,r){return AbiFunction.encodeData(Xd,[e,Gt,r,au])}function he(e,r){if(e<0n)throw new a(`${r} must be non-negative`);if(e>re)throw new a(`${r} exceeds uint256 range`);return e}function Zt(e){if(Hd.test(e))return e.toLowerCase();if(Nd.test(e)){let r=e.toLowerCase();if(r.endsWith("00")||r.endsWith("01"))return r.slice(0,jd)}throw new a("Protocol v2 condition ID must be bytes31, or bytes32 with a binary outcome byte")}function mu(e){if(e!==0&&e!==1)throw new a("Protocol v2 outcome index must be 0 or 1");return e}function Cs(e){return AbiFunction.encodeData(su,[e.map(r=>({typeCode:1,to:r.to,value:r.value??0n,data:r.data}))])}function Is(e){let r=e.map(t=>yu(t));return AbiFunction.encodeData(nu,[r.length===0?"0x":AbiParameters.encodePacked(Array.from({length:r.length},()=>"bytes"),r)])}function yu(e){let r=e.value??0n;return AbiParameters.encodePacked(["uint8","address","uint256","uint256","bytes"],[0,e.to,r,BigInt((e.data.length-2)/2),e.data])}var ax=o(h$1,g,i,j,c,b,a);function N(e,r="Expected a TransactionHandle"){return invariant(typeof e=="object"&&e!==null&&"transactionHash"in e&&"transactionId"in e&&"wait"in e&&typeof e.wait=="function",r),e}o(k$1,n);o(k$1,n);function ux(e){return async function(t){let o=await t.next();for(;!o.done;)try{switch(o.value.kind){case "requestAddress":o=await t.next(await e.getAddress());break;case "signAuthMessage":o=await t.next(await e.signTypedData(o.value.payload));break}}catch(n){o=await t.throw(n);}return o.value}}function z(e){return async function(t){let o=await t.next();for(;!o.done;)try{switch(o.value.kind){case "requestAddress":o=await t.next(await e.getAddress());break;case "signGaslessTypedData":case "signOrder":o=await t.next(await e.signTypedData(o.value.payload));break;case "signGaslessMessage":o=await t.next(await e.signMessage(o.value.payload));break;case "sendErc20ApprovalTransaction":case "sendErc1155ApprovalForAllTransaction":case "sendErc20TransferTransaction":case "sendPerpsDepositTransaction":case "sendMergePositionsTransaction":case "sendRedeemPositionsTransaction":case "sendSplitPositionTransaction":o=await t.next(await e.sendTransaction(o.value.request));break}}catch(n){o=await t.throw(n);}return o.value}}function bs(){return {kind:"requestAddress"}}function K(e,r){return {chainId:e,...r}}var bu=[{name:"chainId",type:"uint256"},{name:"verifyingContract",type:"address"}],vu=[{name:"to",type:"address"},{name:"value",type:"uint256"},{name:"data",type:"bytes"},{name:"operation",type:"uint8"},{name:"safeTxGas",type:"uint256"},{name:"baseGas",type:"uint256"},{name:"gasPrice",type:"uint256"},{name:"gasToken",type:"address"},{name:"refundReceiver",type:"address"},{name:"nonce",type:"uint256"}],qu="DepositWallet",ku="1",Au=600,Ou=[{name:"target",type:"address"},{name:"value",type:"uint256"},{name:"data",type:"bytes"}],wu=[{name:"wallet",type:"address"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"},{name:"calls",type:"Call[]"}],Lu=z$1.object({address:z$1.string(),type:z$1.enum(RelayerTransactionType)}),bx=o(h$1,g,c,b,a);async function eo(e,r){let t=l(r,Lu);return unwrap(e.relayer.get("/v1/account/transactions/params",{params:h(t,{address:"address",type:"type"})}).andThen(f(RelayerExecuteParamsSchema)))}var Fu=z$1.object({transactionId:TransactionIdSchema}),Mu=z$1.object({wallet:EvmAddressSchema,type:z$1.enum(WalletType)}),vx=o(h$1,g,c,b,a);async function qx(e,r){let t=await Bu(e,r);return t.type===WalletType.EOA?false:unwrap(e.relayer.get("/deployed",{params:h({address:t.wallet,type:t.type===WalletType.DEPOSIT_WALLET?RelayerTransactionType.WALLET:void 0},{address:"address",type:"type"})}).andThen(f(RelayerDeployedResponseSchema)).map(({deployed:o})=>o))}async function Bu(e,r){if(r!==void 0)return l(r,Mu);if(!e.isSecureClient())throw new a("Gasless readiness inference requires a secure client. Pass a wallet and type when using a public client.");return e.account.walletType!==WalletType.EOA?{wallet:e.account.wallet,type:e.account.walletType}:{wallet:await Vn(e.rpc,e.account.signer,e.environment.walletDerivation),type:WalletType.DEPOSIT_WALLET}}var V=z$1.string().max(500),vs=10,kx=o(h$1,g,c,b,a);async function Ax(e){return invariant(e.supportsGasless,"Deposit Wallet deployment requires a Relayer API Key or Builder API Key in the client configuration."),xr(e,{from:e.account.signer,metadata:"Deploy Deposit Wallet",to:e.environment.walletDerivation.depositWalletFactory,type:RelayerTransactionType.WALLET_CREATE})}async function Uu(e,r){let t=l(r,Fu);return unwrap(e.relayer.get(`/v1/account/transactions/${t.transactionId}`).andThen(f(GaslessTransactionSchema)))}var Du=z$1.object({data:z$1.custom(isHexString),to:EvmAddressSchema,value:z$1.bigint().optional()}),_u=z$1.object({calls:z$1.array(Du).min(1).transform(e=>expectNonEmptyArray(e)),metadata:V}),Ox=o(h$1,g,c,b,a);async function Y(e,r){let t=l(r,_u);return invariant(e.supportsGasless,"Gasless transactions require a Relayer API Key or Builder API Key in the client configuration."),invariant(e.account.walletType===WalletType.GNOSIS_SAFE||e.account.walletType===WalletType.POLY_PROXY||e.account.walletType===WalletType.DEPOSIT_WALLET,"Gasless transaction preparation supports Deposit Wallet, Safe-backed, and proxy-backed accounts"),async function*(){let o=expectEvmAddress(yield bs());invariant(o===e.account.signer,"Wallet client address does not match the authenticated signer");for(let n=0;n<=vs;n+=1)try{switch(e.account.walletType){case WalletType.POLY_PROXY:return yield*zu(e,t);case WalletType.DEPOSIT_WALLET:return yield*Wu(e,t);case WalletType.GNOSIS_SAFE:return yield*ju(e,t)}invariant(!1,"Unsupported wallet type for gasless transaction");}catch(s){if(!so(s)||n===vs)throw s;await delay(e.environment.relayerPollFrequencyMs);}invariant(false,"Expected gasless transaction retry loop to return");}.call(null)}async function*zu(e,r){let t=yield*ro(e,r.calls,r.metadata);return xr(e,t)}async function*ro(e,r,t){let o=await eo(e,{address:e.account.signer,type:RelayerTransactionType.PROXY}),n=e.environment.walletDerivation.proxyFactory,s=Cs(r),a="0",y="0",P=(await e.rpc.ethEstimateGas({data:s,from:e.account.signer,to:n})).toString(),C=e.environment.contracts.relayHub,I=o.address,B=Gu(e.account.signer,n,s,a,y,P,o.nonce,C,I),w=expectEvmSignature(yield Ls(B));return {data:s,from:e.account.signer,...t!==void 0&&{metadata:t},nonce:o.nonce,proxyWallet:e.account.wallet,signature:w,signatureParams:{gasLimit:P,gasPrice:y,relay:I,relayHub:C,relayerFee:a},to:n,type:RelayerTransactionType.PROXY}}function to(e){return !(e instanceof g)||e.status!==400?void 0:/batch nonce\s+\d+\s+does not match on-chain nonce\s+(\d+)/i.exec(e.message)?.[1]}async function*Wu(e,r){let t=yield*ir(e,r.calls,r.metadata);try{return await xr(e,t)}catch(o){let n=to(o);if(n===void 0)throw o;let s=yield*oo(e,t,r.calls,n);return xr(e,s)}}async function*ir(e,r,t){let o=await eo(e,{address:e.account.signer,type:RelayerTransactionType.WALLET}),n=r.map(Os),s=`${Math.floor(Date.now()/1e3)+Au}`,a=nr(e.account,expectEvmSignature(yield Fs(ws({calls:n,chainId:e.environment.chainId,deadline:s,nonce:o.nonce,wallet:e.account.wallet}))));return {depositWalletParams:{calls:n,deadline:s,depositWallet:e.account.wallet},from:e.account.signer,...t!==void 0&&{metadata:t},nonce:o.nonce,signature:a,to:e.environment.walletDerivation.depositWalletFactory,type:RelayerTransactionType.WALLET}}async function*oo(e,r,t,o){let n=nr(e.account,expectEvmSignature(yield Fs(ws({calls:t.map(Os),chainId:e.environment.chainId,deadline:r.depositWalletParams.deadline,nonce:o,wallet:e.account.wallet}))));return {...r,nonce:o,signature:n}}async function*ju(e,r){let t=yield*no(e,r.calls,r.metadata);return xr(e,t)}async function*no(e,r,t){let o=await eo(e,{address:e.account.signer,type:RelayerTransactionType.SAFE}),n=Hu(r,e.environment.contracts.safeMultisend),s=Ku({chainId:e.environment.chainId,data:n.data,nonce:o.nonce,operation:n.operation,safeAddress:e.account.wallet,to:n.to,value:n.value}),a=expectEvmSignature(yield Ls(expectHexString(TypedData.getSignPayload(s))));return {data:n.data,from:e.account.signer,...t!==void 0&&{metadata:t},nonce:o.nonce,proxyWallet:e.account.wallet,signature:$u(a),signatureParams:Nu(n.operation),to:n.to,type:RelayerTransactionType.SAFE,value:n.value>0n?`${n.value}`:void 0}}async function xr(e,r){let t=l(r,RelayerExecuteRequestSchema),o=await unwrap(e.relayer.post("/submit",{json:t}).andThen(f(RelayerExecuteResponseSchema)));return new He(e,o)}function so(e){if(e instanceof h$1)return true;if(!(e instanceof g)||e.status!==400)return false;if(/wallet busy/i.test(e.message)&&/active action/i.test(e.message)||/wallet has in-flight action/i.test(e.message))return true;let r=/batch nonce\s+(\d+)\s+does not match on-chain nonce\s+(\d+)/i.exec(e.message);if(r===null)return false;let t=r[1],o=r[2];return t===void 0||o===void 0?false:BigInt(t)<BigInt(o)}function Os(e){return {data:e.data,target:e.to,value:`${e.value??0n}`}}function ws(e){let r={chainId:e.chainId,name:qu,verifyingContract:e.wallet,version:ku};return {domain:r,message:{calls:e.calls.map(t=>({data:t.data,target:t.target,value:BigInt(t.value)})),deadline:BigInt(e.deadline),nonce:BigInt(e.nonce),wallet:e.wallet},primaryType:"Batch",types:{Batch:wu,Call:Ou,EIP712Domain:TypedData.extractEip712DomainTypes(r)}}}function Hu(e,r){if(e.length===1){let[t]=e;return {data:t.data,operation:0,to:t.to,value:t.value??0n}}return {data:Is(e),operation:1,to:r,value:0n}}function Nu(e){return {baseGas:"0",gasPrice:"0",gasToken:ZERO_ADDRESS,operation:`${e}`,refundReceiver:ZERO_ADDRESS,safeTxnGas:"0"}}function Ku(e){return {domain:{chainId:e.chainId,verifyingContract:e.safeAddress},message:{baseGas:0n,data:e.data,gasPrice:0n,gasToken:ZERO_ADDRESS,nonce:BigInt(e.nonce),operation:e.operation,refundReceiver:ZERO_ADDRESS,safeTxGas:0n,to:e.to,value:e.value},primaryType:"SafeTx",types:{EIP712Domain:bu,SafeTx:vu}}}function Ls(e){return {kind:"signGaslessMessage",payload:e}}function Fs(e){return {kind:"signGaslessTypedData",payload:e}}function Gu(e,r,t,o,n,s,a,y,P){return expectHexString(Hash.keccak256(Bytes.concat(Bytes.fromString("rlx:"),Bytes.fromHex(e),Bytes.fromHex(r),Bytes.fromHex(t),Bytes.fromNumber(BigInt(o),{size:32}),Bytes.fromNumber(BigInt(n),{size:32}),Bytes.fromNumber(BigInt(s),{size:32}),Bytes.fromNumber(BigInt(a),{size:32}),Bytes.fromHex(y),Bytes.fromHex(P)),{as:"Hex"}))}function $u(e){let r=e.slice(2),t=Number.parseInt(r.slice(128,130),16),o=t===0||t===1?t+31:t===27||t===28?t+4:t;return expectHexString(`0x${r.slice(0,128)}${o.toString(16).padStart(2,"0")}`)}var wx=o(h$1,g,c,b,a,i,j),He=class{#e;transactionHash;transactionId;constructor(r,t){this.#e=r,this.transactionHash=t.transactionHash,this.transactionId=t.transactionId;}async wait(){let r=0;for(;r<this.#e.environment.relayerMaxPolls;){let t=await Uu(this.#e,{transactionId:this.transactionId});if(t.state===RelayerTransactionState.STATE_CONFIRMED){let o=t.transactionHash??this.transactionHash;if(o===null)throw new b("Expected submitted transaction to have a transaction hash once settled");return {transactionHash:o,transactionId:t.transactionId}}if(t.state===RelayerTransactionState.STATE_FAILED||t.state===RelayerTransactionState.STATE_INVALID)throw new j(t.errorMsg??`Transaction ${t.transactionId} reached terminal state ${t.state}`);r+=1,await delay(this.#e.environment.relayerPollFrequencyMs);}throw new i(`Timed out waiting for transaction ${this.transactionId} to settle`)}};var Vu=z$1.object({amount:z$1.union([z$1.bigint(),z$1.literal("max")]),metadata:V.optional(),spenderAddress:EvmAddressSchema,tokenAddress:EvmAddressSchema}),Hx=o(a);async function Yu(e,r){let t=l(r,Vu),o=t.amount==="max"?re:t.amount;return async function*(){return e.account.walletType===WalletType.EOA?N(yield Ds(K(e.environment.chainId,Vr(t.tokenAddress,t.spenderAddress,o)))):yield*await Y(e,{calls:[Vr(t.tokenAddress,t.spenderAddress,o)],metadata:t.metadata??`Approve ${t.amount} of ${t.tokenAddress} to ${t.spenderAddress}`})}.call(null)}var Nx=o(k$1,h$1,g,n,c,b,a);function Ms(e,r){return Yu(e,r).then(z(e.signer))}var Qu=z$1.object({approved:z$1.boolean().default(true),metadata:V.optional(),operatorAddress:EvmAddressSchema,tokenAddress:EvmAddressSchema}),Kx=o(a);async function Zu(e,r){let t=l(r,Qu);return async function*(){return e.account.walletType===WalletType.EOA?N(yield _s(K(e.environment.chainId,Yr(t.tokenAddress,t.operatorAddress,t.approved)))):yield*await Y(e,{calls:[Yr(t.tokenAddress,t.operatorAddress,t.approved)],metadata:t.metadata??`${t.approved?"Approve":"Revoke"} ${t.operatorAddress} on ${t.tokenAddress}`})}.call(null)}var Gx=o(k$1,h$1,g,n,c,b,a);function Bs(e,r){return Zu(e,r).then(z(e.signer))}var $x=o(g,c,b,a),Ju=z$1.object({user:EvmAddressSchema}),Vx=o(g,c,b,a);async function Yx(e,r){let{user:t}=l(r,Ju),o=await Us(e,t);return {isFullyApproved:o.erc20.length===0&&o.erc1155.length===0,missing:o}}async function Xu(e){let r=await Us(e,e.account.wallet),t=r.erc20.map(n=>Vr(n.tokenAddress,n.spenderAddress,n.amount)),o=r.erc1155.map(n=>Yr(n.tokenAddress,n.operatorAddress,true));return async function*(){if(t.length===0&&o.length===0)return;if(e.account.walletType===WalletType.EOA){for(let s of t)await N(yield Ds(K(e.environment.chainId,s))).wait();for(let s of o)await N(yield _s(K(e.environment.chainId,s))).wait();return}await(yield*await Y(e,{calls:[...t,...o],metadata:"Trading setup approvals"})).wait();}.call(null)}var Qx=o(k$1,h$1,g,n,i,j,c,b,a);function Zx(e){return Xu(e).then(z(e.signer)).then(()=>{})}async function Us(e,r){let t=el(e),o=[...t.erc20.map(y=>ls(y.tokenAddress,r,y.spenderAddress)),...t.erc1155.map(y=>ys(y.tokenAddress,r,y.operatorAddress))],n=await e.rpc.ethCallBatch(o),s=n.slice(0,t.erc20.length),a=n.slice(t.erc20.length);try{return {erc20:t.erc20.filter((y,P)=>ms(s[P])<y.amount),erc1155:t.erc1155.filter((y,P)=>!fs(a[P]))}}catch(y){throw new b("Expected JSON-RPC approval checks to return ABI-encoded values",{cause:y})}}function el(e){let{contracts:r}=e.environment;return {erc20:[{amount:re,spenderAddress:r.standardExchange,tokenAddress:r.collateralToken},{amount:re,spenderAddress:r.negRiskExchange,tokenAddress:r.collateralToken},{amount:re,spenderAddress:r.collateralAdapter,tokenAddress:r.collateralToken},{amount:re,spenderAddress:r.negRiskCollateralAdapter,tokenAddress:r.collateralToken},{amount:re,spenderAddress:r.protocolV2Router,tokenAddress:r.collateralToken},{amount:re,spenderAddress:r.exchangeV3,tokenAddress:r.collateralToken},{amount:re,spenderAddress:r.perpsDepositContract,tokenAddress:r.collateralToken}],erc1155:[{operatorAddress:r.standardExchange,tokenAddress:r.conditionalTokens},{operatorAddress:r.negRiskExchange,tokenAddress:r.conditionalTokens},{operatorAddress:r.collateralAdapter,tokenAddress:r.conditionalTokens},{operatorAddress:r.negRiskCollateralAdapter,tokenAddress:r.conditionalTokens},{operatorAddress:r.autoRedeemOperator,tokenAddress:r.conditionalTokens},{operatorAddress:r.binaryModule,tokenAddress:r.conditionalTokens},{operatorAddress:r.negRiskModule,tokenAddress:r.conditionalTokens},{operatorAddress:r.protocolV2Router,tokenAddress:r.positionManager},{operatorAddress:r.exchangeV3,tokenAddress:r.positionManager},{operatorAddress:r.autoRedeemOperator,tokenAddress:r.positionManager}]}}function Ds(e){return {kind:"sendErc20ApprovalTransaction",request:e}}function _s(e){return {kind:"sendErc1155ApprovalForAllTransaction",request:e}}var nC=o(h$1,g,c,b);async function nl(e,r){return unwrap(e.clob.post("/auth/api-key",{headers:js(r)}).andThen(f(ApiKeyCredsSchema)))}var sC=o(h$1,g,c,b);async function sl(e,r){return unwrap(e.clob.get("/auth/derive-api-key",{headers:js(r)}).andThen(f(ApiKeyCredsSchema)))}var aC=o(h$1,g,c,b);async function iC(e,r){try{return await nl(e,r)}catch(t){if(!(t instanceof g)||t.status!==400)throw t}return sl(e,r)}var pC=o(h$1,g,n,c,b);async function cC(e){return (await unwrap(e.secureClob.get("/auth/api-keys").andThen(f(ApiKeysResponseSchema)))).apiKeys}var dC=o(h$1,g,n,c,b);async function uC(e){await unwrap(e.secureClob.del("/auth/api-key").andThen(f(z$1.literal("OK"))));}var lC=o(h$1,g,n,c,b);async function mC(e){return unwrap(e.secureClob.post("/auth/builder-api-key").andThen(f(BuilderApiKeyCredsSchema)))}var yC=o(h$1,g,n,c,b);async function fC(e){return unwrap(e.secureClob.get("/auth/builder-api-key").andThen(f(BuilderApiKeysResponseSchema)))}var PC=o(h$1,g,n,c,b);async function gC(e){await unwrap(e.clob.del("/auth/builder-api-key").andThen(f(z$1.literal("OK"))));}function js(e){return {POLY_ADDRESS:e.address,POLY_NONCE:`${e.nonce}`,POLY_SIGNATURE:e.signature,POLY_TIMESTAMP:`${e.timestamp}`}}var dl=z$1.object({after:z$1.string().optional(),before:z$1.string().optional(),builderCode:BuilderCodeSchema,cursor:PaginationCursorSchema.optional(),id:z$1.string().optional(),market:z$1.string().optional()}),ul=be(dl.shape),qC=o(h$1,g,c,b,a);function kC(e,r){let t=l(r,ul),{cursor:o}=t;return x(n=>e.clob.get("/builder/trades",{params:h({after:t.after,assetId:t.assetId??t.tokenId,before:t.before,builderCode:t.builderCode,id:t.id,market:t.market,nextCursor:n},T({assetId:"asset_id",builderCode:"builder_code"}))}).andThen(f(PaginatedBuilderTradesSchema)).map(s=>({items:s.data,hasMore:s.nextCursor!==END_CURSOR,nextCursor:s.nextCursor===END_CURSOR?void 0:toPaginationCursor(s.nextCursor)})),o)}var Al=ee({}),WC=o(h$1,g,c,b,a);async function jC(e,r){let t=l(r,Al);return (await unwrap(e.clob.get("/midpoint",{params:Ge(t)}).andThen(f(MidpointSchema)))).mid}var Ol=z$1.array(ee({})).min(1),HC=o(h$1,g,c,b,a);async function NC(e,r){let t=l(r,Ol);return unwrap(e.clob.post("midpoints",{json:nt(t)}).andThen(f(MidpointsSchema)))}var wl=ee({}),KC=o(h$1,g,c,b,a);async function GC(e,r){let t=l(r,wl);return (await unwrap(e.clob.get("/tick-size",{params:Ge(t)}).andThen(f(FetchTickSizeResponseSchema)))).minimumTickSize}var Ll=ee({}),$C=o(h$1,g,c,b,a);async function VC(e,r){let t=l(r,Ll);return (await unwrap(e.clob.get("/neg-risk",{params:Ge(t)}).andThen(f(FetchNegRiskResponseSchema)))).negRisk}var Fl=ee({}),YC=o(h$1,g,c,b,a);async function Vs(e,r){let t=l(r,Fl);return unwrap(e.clob.get(`/markets-by-token/${t.assetId??t.tokenId}`).andThen(f(ResolveConditionByTokenResponseSchema)))}var Ml=z$1.object({conditionId:ConditionIdSchema}),QC=o(h$1,g,c,b,a);async function Ys(e,r){let t=l(r,Ml);return unwrap(e.clob.get(`/clob-markets/${t.conditionId}`).andThen(f(FetchMarketInfoResponseSchema)))}var Bl=z$1.object({builderCode:BuilderCodeSchema}),ZC=o(h$1,g,c,b,a);async function Qs(e,r){let t=l(r,Bl);return unwrap(e.clob.get(`/fees/builder-fees/${t.builderCode}`).andThen(f(FetchBuilderFeeRatesResponseSchema)).mapErr(o=>o instanceof g&&o.status===404?new a(`Unknown builder code: ${t.builderCode}`,{cause:o}):o))}var Ul=ee({side:OrderSideSchema}),JC=o(h$1,g,c,b,a);async function XC(e,r){let t=l(r,Ul);return (await unwrap(e.clob.get("/price",{params:Ge(t)}).andThen(f(PriceSchema)))).price}var Dl=z$1.array(ee({side:OrderSideSchema})).min(1),eI=o(h$1,g,c,b,a);async function rI(e,r){let t=l(r,Dl);return unwrap(e.clob.post("prices",{json:$l(t)}).andThen(f(PricesSchema)))}var _l=ee({}),tI=o(h$1,g,c,b,a);async function ot(e,r){let t=l(r,_l);return unwrap(e.clob.get("/book",{params:Ge(t)}).andThen(f(FetchOrderBookResponseSchema)))}var zl=z$1.array(ee({})).min(1),oI=o(h$1,g,c,b,a);async function nI(e,r){let t=l(r,zl);return unwrap(e.clob.post("books",{json:nt(t)}).andThen(f(OrderBooksSchema)))}var Wl=ee({}),sI=o(h$1,g,c,b,a);async function aI(e,r){let t=l(r,Wl);return (await unwrap(e.clob.get("/spread",{params:Ge(t)}).andThen(f(SpreadSchema)))).spread}var jl=z$1.array(ee({})).min(1),iI=o(h$1,g,c,b,a);async function pI(e,r){let t=l(r,jl);return unwrap(e.clob.post("spreads",{json:nt(t)}).andThen(f(SpreadsSchema)))}var Hl=ee({}),cI=o(h$1,g,c,b,a);async function dI(e,r){let t=l(r,Hl);return unwrap(e.clob.get("/last-trade-price",{params:Ge(t)}).andThen(f(LastTradePriceSchema)))}var Nl=z$1.array(ee({})).min(1),uI=o(h$1,g,c,b,a);async function lI(e,r){let t=l(r,Nl);return unwrap(e.clob.post("last-trades-prices",{json:nt(t)}).andThen(f(LastTradePricesSchema)))}var Kl=z$1.object({cursor:PaginationCursorSchema.optional(),sponsored:z$1.boolean().optional()}).default({}),mI=o(h$1,g,c,b,a);function yI(e,r={}){let{cursor:t,...o}=l(r,Kl);return x(n=>e.clob.get("/rewards/markets/current",{params:h({...o,nextCursor:n},T())}).andThen(f(PaginatedCurrentRewardsSchema)).map(s=>({items:s.data,hasMore:s.nextCursor!==END_CURSOR,nextCursor:s.nextCursor===END_CURSOR?void 0:toPaginationCursor(s.nextCursor)})),t)}var Gl=z$1.object({conditionId:ConditionIdSchema,cursor:PaginationCursorSchema.optional(),sponsored:z$1.boolean().optional()}),fI=o(h$1,g,c,b,a);function PI(e,r){let{cursor:t,...o}=l(r,Gl);return x(n=>e.clob.get(`rewards/markets/${o.conditionId}`,{params:h({nextCursor:n,sponsored:o.sponsored},T())}).andThen(f(PaginatedMarketRewardsSchema)).map(s=>({items:s.data,hasMore:s.nextCursor!==END_CURSOR,nextCursor:s.nextCursor===END_CURSOR?void 0:toPaginationCursor(s.nextCursor)})),t)}function nt(e){return e.map(r=>({token_id:r.assetId??r.tokenId}))}function $l(e){return e.map(r=>({token_id:r.assetId??r.tokenId,side:r.side}))}function Ge(e){let{assetId:r,tokenId:t,...o}=e;return h({...o,tokenId:e.assetId??e.tokenId},T())}var ea=2*6e4,qI=o(h$1,g,c,b);async function kI(e){return ra(e),unwrap(e.combos.post("/v1/collateral-return/plan",{json:{wallet:e.account.wallet},timeout:ea}).andThen(f(CollateralReturnPlanResponseSchema)))}var rm=z$1.object({plan:CollateralReturnPlanSchema}),Zs=10,io="Collateral return",AI=o(g,c,b,a);async function tm(e,r){let{plan:t}=l(r,rm);if(invariant(e.supportsGasless,"Collateral return execution requires a Relayer API Key or Builder API Key in the client configuration."),ra(e),!isSameEvmAddress(t.wallet,e.account.wallet))throw new a("The collateral return plan was created for a different wallet than the authenticated account.");if(t.chainId!==e.environment.chainId)throw new a(`The collateral return plan was created for chain ${t.chainId}, but the client is configured for chain ${e.environment.chainId}.`);return async function*(){let o=[{data:t.routerCall.data,to:t.routerCall.to,value:0n}];for(let n=0;n<=Zs;n+=1)try{let s=yield*om(e,o);try{return await Js(e,t.planHash,s)}catch(a){let y=to(a);if(y===void 0||s.type!==RelayerTransactionType.WALLET)throw a;let P=yield*oo(e,s,o,y);return await Js(e,t.planHash,P)}}catch(s){if(!so(s)||n===Zs)throw s;await delay(e.environment.relayerPollFrequencyMs);}invariant(false,"Expected collateral return submit retry loop to return");}.call(null)}var OI=o(k$1,h$1,g,n,c,b,a);function wI(e,r){return tm(e,r).then(z(e.signer))}function ra(e){invariant(e.account.walletType===WalletType.DEPOSIT_WALLET||e.account.walletType===WalletType.GNOSIS_SAFE||e.account.walletType===WalletType.POLY_PROXY,"Collateral return supports Deposit Wallet, Safe Wallet, and Proxy Wallet accounts");}function om(e,r){switch(e.account.walletType){case WalletType.GNOSIS_SAFE:return no(e,r,io);case WalletType.POLY_PROXY:return ro(e,r,io);default:return ir(e,r,io)}}async function Js(e,r,t){let o=await unwrap(e.combos.post("/v1/collateral-return/submit",{json:{envelope:t,plan_hash:r},timeout:ea}).andThen(f(RelayerExecuteResponseSchema)));return new He(e,o)}var cm=z$1.object({ascending:z$1.boolean().optional(),cursor:PaginationCursorSchema.optional(),pageSize:k.max(100).default(20),getPositions:z$1.boolean().optional(),holdersOnly:z$1.boolean().optional(),order:z$1.string().optional(),parentEntityId:z$1.union([EventIdSchema,SeriesIdSchema]),parentEntityType:CommentParentEntityTypeSchema}),dm=z$1.object({getPositions:z$1.boolean().optional(),id:CommentIdSchema}),um=z$1.object({address:z$1.string(),ascending:z$1.boolean().optional(),cursor:PaginationCursorSchema.optional(),order:z$1.string().optional(),pageSize:k.max(100).default(20)}),KI=o(h$1,g,c,b,a);function GI(e,r){let{cursor:t,pageSize:o,...n}=l(r,cm);return x(s=>{let a=te(s,o);return e.gamma.get("/comments",{params:h({ascending:n.ascending,getPositions:n.getPositions,holdersOnly:n.holdersOnly,limit:a.pageSize,offset:a.offset,order:n.order,parentEntityId:n.parentEntityId,parentEntityType:n.parentEntityType},T())}).andThen(f(ListCommentsResponseSchema)).map(y=>{let P=y.length>=a.pageSize;return {items:y,hasMore:P,nextCursor:P?J({offset:a.offset+a.pageSize,pageSize:a.pageSize}):void 0}})},t)}var $I=o(h$1,g,c,b,a);async function VI(e,r){let t=l(r,dm);return unwrap(e.gamma.get(`comments/${t.id}`,{params:h({getPositions:t.getPositions},T())}).andThen(f(ListCommentsResponseSchema)))}var YI=o(h$1,g,c,b,a);function QI(e,r){let{address:t,cursor:o,pageSize:n,...s}=l(r,um);return x(a=>{let y=te(a,n);return e.gamma.get(`comments/user_address/${t}`,{params:h({ascending:s.ascending,limit:y.pageSize,offset:y.offset,order:s.order},T())}).andThen(f(ListCommentsResponseSchema)).map(P=>{let C=P.length>=y.pageSize;return {items:P,hasMore:C,nextCursor:C?J({offset:y.offset+y.pageSize,pageSize:y.pageSize}):void 0}})},o)}function st(e,r){let t;try{t=new URL(e);}catch(y){throw new a("Expected a valid Polymarket URL.",{cause:y})}if(t.protocol!=="https:"||t.hostname!=="polymarket.com"&&t.hostname!=="www.polymarket.com")throw new a("Expected a valid Polymarket URL.");let[o,n,...s]=t.pathname.split("/").filter(Boolean),a$1=s[0];if(r==="market"&&o==="event"&&n!==void 0&&s.length<=1)return a$1??n;if(o!==r||n===void 0||s.length>0)throw new a(`Expected a Polymarket ${r} URL.`);return n}var Sm=z$1.object({ascending:z$1.boolean().optional(),closed:z$1.boolean().default(false),cursor:PaginationCursorSchema.optional(),pageSize:k.optional(),cyom:z$1.boolean().optional(),endDateMax:IsoDateTimeStringSchema.optional(),endDateMin:IsoDateTimeStringSchema.optional(),ended:z$1.boolean().optional(),eventDate:IsoCalendarDateStringSchema.optional(),eventWeek:z$1.number().int().optional(),excludeTagIds:z$1.array(z$1.number().int()).optional(),featured:z$1.boolean().optional(),featuredOrder:z$1.boolean().optional(),gameIds:z$1.array(z$1.number().int()).optional(),ids:z$1.array(z$1.number().int()).optional(),includeBestLines:z$1.boolean().optional(),includeChat:z$1.boolean().optional(),includeChildren:z$1.boolean().optional(),includeTemplate:z$1.boolean().optional(),liquidityMax:z$1.number().optional(),liquidityMin:z$1.number().optional(),live:z$1.boolean().optional(),locale:z$1.string().optional(),order:z$1.string().optional(),parentEventId:z$1.number().int().optional(),partnerSlug:z$1.string().optional(),recurrence:z$1.enum(["daily","weekly","monthly"]).optional(),relatedTags:z$1.boolean().optional(),seriesIds:z$1.array(z$1.number().int()).optional(),slug:z$1.array(z$1.string()).optional(),startDateMax:IsoDateTimeStringSchema.optional(),startDateMin:IsoDateTimeStringSchema.optional(),startTimeMax:IsoDateTimeStringSchema.optional(),startTimeMin:IsoDateTimeStringSchema.optional(),tagIds:z$1.array(z$1.number().int()).optional(),tagMatch:z$1.enum(["any","all"]).optional(),tagSlug:z$1.string().optional(),titleSearch:z$1.string().optional(),volumeMax:z$1.number().optional(),volumeMin:z$1.number().optional()}),hm=z$1.union([z$1.object({id:z$1.string(),includeBestLines:z$1.boolean().optional(),includeChat:z$1.boolean().optional(),includeTemplate:z$1.boolean().optional(),locale:z$1.string().optional()}),z$1.object({slug:z$1.string(),includeBestLines:z$1.boolean().optional(),includeChat:z$1.boolean().optional(),includeTemplate:z$1.boolean().optional(),locale:z$1.string().optional()}),z$1.object({url:z$1.string(),includeBestLines:z$1.boolean().optional(),includeChat:z$1.boolean().optional(),includeTemplate:z$1.boolean().optional(),locale:z$1.string().optional()})]),Tm=z$1.object({id:z$1.string()}),lb=o(h$1,g,c,b,a);function mb(e,r={}){let t=l(r,Sm);return x(o=>e.gamma.get("/events/keyset",{params:vm({...t,cursor:o??t.cursor})}).andThen(f(ListEventsKeysetResponseSchema)).map(n=>({items:n.items,hasMore:n.nextCursor!==void 0,nextCursor:n.nextCursor})),t.cursor)}var yb=o(h$1,g,c,b,a);async function fb(e,r){let t=l(r,hm);if("id"in t)return unwrap(e.gamma.get(`events/${t.id}`,{params:qm(t)}).andThen(f(EventSchema)));let o="url"in t?st(t.url,"event"):t.slug;return unwrap(e.gamma.get(`events/slug/${o}`,{params:km(t)}).andThen(f(EventSchema)))}var Pb=o(h$1,g,c,b,a);async function gb(e,r){let t=l(r,Tm);return unwrap(e.gamma.get(`events/${t.id}/tags`).andThen(f(FetchEventTagsResponseSchema)))}var xm=z$1.array(CanonicalMarketConditionIdSchema).min(1).transform(e=>[...new Set(e)]).refine(e=>e.length<=20,"At most 20 distinct condition ids"),Cm=z$1.array(Wt).min(1).transform(e=>[...new Set(e)]).refine(e=>e.length<=20,"At most 20 distinct event ids"),Im=z$1.union([z$1.object({questionId:QuestionIdSchema,conditionIds:z$1.never().optional(),eventIds:z$1.never().optional()}),z$1.object({questionId:z$1.never().optional(),conditionIds:xm,eventIds:z$1.never().optional()}),z$1.object({questionId:z$1.never().optional(),conditionIds:z$1.never().optional(),eventIds:Cm})]),Rb=o(h$1,g,c,b,a);async function Eb(e,r){let{conditionIds:t,eventIds:o,questionId:n}=l(r,Im);return unwrap(_(()=>e.data.get("/v2/resolutions",{params:D({questionId:n,condition:t,eventId:o})})).andThen(f(FetchResolutionsResponseSchema)))}var bm=z$1.object({eventIds:z$1.array(Wt).min(1).transform(e=>[...new Set(e)])}),Sb=o(h$1,g,c,b,a);async function hb(e,r){let{eventIds:t}=l(r,bm);return unwrap(_(()=>e.data.get("/v2/live-volume",{params:D({eventId:t})})).andThen(f(FetchEventLiveVolumeResponseSchema)))}function vm(e){return h(e,T({cursor:"after_cursor",excludeTagIds:"exclude_tag_id",gameIds:"game_id",ids:"id",pageSize:"limit",seriesIds:"series_id",tagIds:"tag_id"}))}function qm(e){return h({includeBestLines:e.includeBestLines,includeChat:e.includeChat,includeTemplate:e.includeTemplate,locale:e.locale},T())}function km(e){return h({includeBestLines:e.includeBestLines,includeChat:e.includeChat,includeTemplate:e.includeTemplate,locale:e.locale},T())}var Dm=z$1.object({cursor:PaginationCursorSchema.optional(),pageSize:k.max(1e3).default(100),window:LeaderboardWindowSchema.optional()}),Db=o(h$1,g,c,b,a);function _b(e,r={}){let{cursor:t,pageSize:o,window:n}=l(r,Dm);return x(s=>_(()=>e.data.get("/v2/builders/leaderboard",{params:D({timePeriod:n,limit:o,cursor:s})})).andThen(f(ListBuilderLeaderboardResponseSchema)),t)}var _m=z$1.object({interval:BuilderVolumeIntervalSchema.optional(),bucketLimit:z$1.number().int().positive().max(90).optional()}),zb=o(h$1,g,c,b,a);async function Wb(e,r={}){let{interval:t,bucketLimit:o}=l(r,_m);return unwrap(_(()=>e.data.get("/v2/builders/volume",{params:D({interval:t,limit:o})})).andThen(f(FetchBuilderVolumeResponseSchema)))}var lo=z$1.string().min(1),zm=z$1.object({category:lo.optional(),cursor:PaginationCursorSchema.optional(),pageSize:k.max(1e3).default(100),sortBy:TraderLeaderboardSortSchema.optional(),window:LeaderboardWindowSchema.optional()}),jb=o(h$1,g,c,b,a);function Hb(e,r={}){let{category:t,cursor:o,pageSize:n,sortBy:s,window:a}=l(r,zm);return x(y=>_(()=>e.data.get("/v2/leaderboard",{params:D({category:t,cursor:y,limit:n,sortBy:s,timePeriod:a})})).andThen(f(ListTraderLeaderboardResponseSchema)),o)}var Wm=z$1.object({category:lo.optional(),user:EvmAddressSchema,window:LeaderboardWindowSchema.optional()}),Nb=o(h$1,g,c,b,a);async function Kb(e,r){let{category:t,user:o,window:n}=l(r,Wm);return unwrap(_(()=>e.data.get("/v2/leaderboard",{params:D({category:t,timePeriod:n,user:o})})).andThen(f(FetchTraderLeaderboardStandingResponseSchema)))}var jm=z$1.object({category:lo.optional(),cursor:PaginationCursorSchema.optional(),pageSize:k.max(1e3).default(100),window:LeaderboardWindowSchema.optional()}),Gb=o(h$1,g,c,b,a);function $b(e,r={}){let{category:t,cursor:o,pageSize:n,window:s}=l(r,jm);return x(a=>_(()=>e.data.get("/v2/biggest-winners",{params:D({category:t,cursor:a,limit:n,timePeriod:s})})).andThen(f(ListBiggestWinnersResponseSchema)),o)}var Km=z$1.object({marketId:z$1.union([z$1.string(),z$1.array(z$1.string())]).optional(),eventId:z$1.union([z$1.string(),z$1.array(z$1.string())]).optional(),questionId:z$1.union([z$1.string(),z$1.array(z$1.string())]).optional(),state:z$1.union([z$1.enum(MarketClarificationState),z$1.array(z$1.enum(MarketClarificationState))]).optional(),showInFrontend:z$1.boolean().optional(),txHash:z$1.string().optional(),order:z$1.string().optional(),ascending:z$1.boolean().optional(),cursor:PaginationCursorSchema.optional(),pageSize:k.max(100).default(20)}),pv=o(h$1,g,c,b,a);function cv(e,r={}){let{cursor:t,pageSize:o,...n}=l(r,Km);return x(s=>{let a=te(s,o);return e.gamma.get("/market-clarifications",{params:h({...n,limit:a.pageSize,offset:a.offset},T())}).andThen(f(ListMarketClarificationsResponseSchema)).map(y=>{let P=y.length>=a.pageSize;return {items:y,hasMore:P,nextCursor:P?J({offset:a.offset+a.pageSize,pageSize:a.pageSize}):void 0}})},t)}var ry=z$1.object({ascending:z$1.boolean().optional(),closed:z$1.boolean().optional(),clobTokenIds:z$1.array(z$1.string()).optional(),cursor:PaginationCursorSchema.optional(),pageSize:k.optional(),conditionIds:z$1.array(ConditionIdSchema).optional(),cyom:z$1.boolean().optional(),decimalized:z$1.boolean().optional(),endDateMax:IsoDateTimeStringSchema.optional(),endDateMin:IsoDateTimeStringSchema.optional(),gameId:z$1.string().optional(),ids:z$1.array(z$1.number().int()).optional(),includeTag:z$1.boolean().optional(),liquidityNumMax:z$1.number().optional(),liquidityNumMin:z$1.number().optional(),locale:z$1.string().optional(),order:z$1.string().optional(),positionIds:z$1.array(PositionIdSchema).optional(),questionIds:z$1.array(z$1.string()).optional(),relatedTags:z$1.boolean().optional(),rfqEnabled:z$1.boolean().optional(),rewardsMinSize:z$1.number().optional(),slug:z$1.array(z$1.string()).optional(),sportsMarketTypes:z$1.array(z$1.string()).optional(),startDateMax:IsoDateTimeStringSchema.optional(),startDateMin:IsoDateTimeStringSchema.optional(),tagId:z$1.number().int().optional(),tagMatch:z$1.enum(["any","all"]).optional(),umaResolutionStatus:z$1.string().optional(),volumeNumMax:z$1.number().optional(),volumeNumMin:z$1.number().optional()}),ty=z$1.object({id:z$1.string(),includeTag:z$1.boolean().optional(),locale:z$1.string().optional()}),oy=z$1.object({slug:z$1.string(),includeTag:z$1.boolean().optional(),locale:z$1.string().optional()}),ny=z$1.object({url:z$1.string(),includeTag:z$1.boolean().optional(),locale:z$1.string().optional()}),sy=z$1.union([ty,oy,ny]),ay=z$1.object({id:z$1.string()}),Cv=o(h$1,g,c,b,a);function da(e,r={}){let t=l(r,ry);return x(o=>e.gamma.get("/markets/keyset",{params:Py({...t,cursor:o??t.cursor})}).andThen(f(ListMarketsKeysetResponseSchema)).map(n=>({items:n.items,hasMore:n.nextCursor!==void 0,nextCursor:n.nextCursor})),t.cursor)}var iy=z$1.object({cursor:PaginationCursorSchema.optional(),pageSize:k.max(100).optional(),exclude:z$1.array(ConditionIdSchema).optional()}),Iv=o(h$1,g,c,b,a);function bv(e,r={}){let t=l(r,iy);return x(o=>e.rfq.get("/v1/rfq/combo-markets",{params:gy({...t,cursor:o??t.cursor})}).andThen(f(ListComboMarketsResponseSchema)).map(n=>({items:n.markets,hasMore:n.nextCursor!==void 0,nextCursor:n.nextCursor})),t.cursor)}var vv=o(h$1,g,c,b,a);async function qv(e,r){let t=l(r,sy);return "id"in t?Ry(e,t):"url"in t?aa(e,{includeTag:t.includeTag,locale:t.locale,slug:st(t.url,"market")}):aa(e,t)}var kv=o(h$1,g,c,b,a);async function Av(e,r){let t=l(r,ay);return unwrap(e.gamma.get(`markets/${t.id}/tags`).andThen(f(FetchMarketTagsResponseSchema)))}var py=z$1.object({conditionIds:ue(CanonicalMarketConditionIdSchema,20),cursor:PaginationCursorSchema.optional(),includePnl:z$1.boolean().optional(),minBalance:z$1.number().nonnegative().optional(),pageSize:k.max(1e3).default(100)}).superRefine(({conditionIds:e,includePnl:r,pageSize:t},o)=>{r&&(e.length!==1&&o.addIssue({code:"custom",message:"includePnl requires exactly one conditionId",path:["conditionIds"]}),t>100&&o.addIssue({code:"custom",message:"includePnl supports pageSize at most 100",path:["pageSize"]}));}),Ov=o(h$1,g,c,b,a);function wv(e,r){let{conditionIds:t,cursor:o,includePnl:n,minBalance:s,pageSize:a}=l(r,py);return x(y=>_(()=>e.data.get("/v2/holders",{params:D({condition:t,limit:a,cursor:y,includePnl:n,minBalance:s})})).andThen(f(ListMarketHoldersResponseSchema)),o)}var cy=360*60*60,dy=253402300799,yo=je.pipe(z$1.number().int().positive().max(dy)),ua=z$1.string().min(1).pipe(ClobAssetIdSchema),la={assetId:ua,bucketSeconds:z$1.number().int().min(60).max(86400).optional(),cursor:PaginationCursorSchema.optional(),pageSize:k.max(1e4).default(1e4)},uy=z$1.object({...la,interval:PriceHistoryIntervalSchema,start:z$1.never().optional(),end:z$1.never().optional(),asOf:z$1.never().optional()}).superRefine(({bucketSeconds:e,interval:r},t)=>{let o=r===PriceHistoryInterval.Max||r===PriceHistoryInterval.OneMonth?600:r===PriceHistoryInterval.OneWeek?300:60;e!==void 0&&e<o&&t.addIssue({code:"custom",message:`bucketSeconds must be at least ${o} for this interval`,path:["bucketSeconds"]});}),ly=z$1.object({...la,start:yo,end:yo.optional(),interval:z$1.never().optional(),asOf:z$1.never().optional()}).superRefine(({end:e,start:r},t)=>{if(e!==void 0&&e<r){t.addIssue({code:"custom",message:"end must not precede start",path:["end"]});return}(e??Math.floor(Date.now()/1e3))-r>cy&&t.addIssue({code:"custom",message:"start to end must span at most 15 days",path:["end"]});}),my=z$1.object({assetId:ua,asOf:yo,interval:z$1.never().optional(),start:z$1.never().optional(),end:z$1.never().optional(),bucketSeconds:z$1.never().optional(),cursor:z$1.never().optional(),pageSize:z$1.never().optional()}),yy=z$1.union([uy,ly,my]),Lv=o(h$1,g,c,b,a);function Fv(e,r){let{assetId:t,cursor:o,pageSize:n,...s}=l(r,yy);return x(a=>_(()=>e.data.get("/v2/prices-history",{params:D({...s,tokenId:t,limit:n,cursor:a})})).andThen(f(ListPriceHistoryResponseSchema)),o)}var fy=z$1.object({conditionIds:ue(CanonicalMarketConditionIdSchema,20).optional()}),Mv=o(h$1,g,c,b,a);async function Bv(e,r={}){let{conditionIds:t}=l(r,fy);return unwrap(_(()=>e.data.get("/v2/oi",{params:D({condition:t})})).andThen(f(FetchOpenInterestResponseSchema)))}function Py(e){return h(e,T({cursor:"after_cursor",ids:"id",pageSize:"limit"}))}function gy(e){return h({cursor:e.cursor,exclude:e.exclude?.join(","),pageSize:e.pageSize},{cursor:"cursor",exclude:"exclude",pageSize:"limit"})}async function aa(e,r){return unwrap(e.gamma.get(`markets/slug/${r.slug}`,{params:h({includeTag:r.includeTag,locale:r.locale},T())}).andThen(f(MarketSchema)))}async function Ry(e,r){return unwrap(e.gamma.get(`markets/${r.id}`,{params:h({includeTag:r.includeTag,locale:r.locale},T())}).andThen(f(MarketSchema)))}function qr(e){if(!(e instanceof g))return e;let r=Ey(e);return r===void 0?e:new g(e.message,{cause:e,...e.code!==void 0?{code:e.code}:{},restriction:r,...e.retryAfter!==void 0?{retryAfter:e.retryAfter}:{},status:e.status})}function Ey(e){if(e.status===425)return "restarting";if(e.status===503&&e.code==="post_only_mode")return "post_only"}var Ty=z$1.object({orderId:z$1.string()}),xy=z$1.object({orderIds:z$1.array(z$1.string()).min(1).max(3e3)}),Cy=z$1.object({market:z$1.string().optional()}),Iy=be(Cy.shape).refine(e=>e.market!==void 0||e.assetId!==void 0||e.tokenId!==void 0,{message:"At least one of market or assetId is required.",path:["market"]}),Yv=o(g,h$1,n,c,b,a);async function Qv(e,r){let t=l(r,Ty);return dt(e,"/order",{orderID:t.orderId})}var Zv=o(g,h$1,n,c,b,a);async function Jv(e,r){let t=l(r,xy);return dt(e,"/orders",t.orderIds)}var Xv=o(g,h$1,n,c,b);async function eq(e){return dt(e,"/cancel-all")}var rq=o(g,h$1,n,c,b,a);async function tq(e,r){let t=l(r,Iy);return dt(e,"/cancel-market-orders",{asset_id:t.assetId??t.tokenId,market:t.market})}async function dt(e,r,t){return unwrap(e.secureClob.del(r,{json:t,rateLimitBucket:"cancel"}).mapErr(qr).andThen(f(CancelOrdersResponseSchema)))}var Fe=z$1.object({assetId:ClobAssetIdSchema,tokenId:z$1.never().optional()}),Me=z$1.object({assetId:z$1.never().optional(),tokenId:ClobAssetIdSchema});var ga=z$1.object({orderType:z$1.union([z$1.literal(OrderType.FAK),z$1.literal(OrderType.FOK)]).default(OrderType.FOK)}),ya=ga.extend({side:z$1.literal(OrderSide.BUY),amount:PositiveDecimalNumberSchema}),fa=ga.extend({side:z$1.literal(OrderSide.SELL),shares:PositiveDecimalNumberSchema}),vy=z$1.union([ya.extend(Fe.shape),ya.extend(Me.shape),fa.extend(Fe.shape),fa.extend(Me.shape)]).transform(({assetId:e,tokenId:r,...t})=>({...t,assetId:e??r})),yq=o(l$1,h$1,g,c,b,a);async function fq(e,r){let t=l(r,vy),o=t.side===OrderSide.BUY?t.amount:t.shares;return qy(e,{amount:o,assetId:t.assetId,orderType:t.orderType,side:t.side})}async function qy(e,r){let t=await ot(e,{assetId:r.assetId});return fo({amount:r.amount,orderBook:t,orderType:r.orderType,side:r.side})}function fo(e){let{orderBook:r}=e,t=e.side===OrderSide.BUY?Ay(r.asks,e.amount,e.orderType):Oy(r.bids,e.amount,e.orderType);return invariant(ky(t,r.tickSize),`Resolved market price fell outside the valid range for tick size ${r.tickSize}.`),t}function ky(e,r){return e>=r&&e<=1-r}function Ay(e,r,t){if(e.length===0)throw new l$1("No resting liquidity.");let o=0;for(let s=e.length-1;s>=0;s-=1){let a=e[s];if(a!==void 0&&(o+=Number.parseFloat(a.size)*Number.parseFloat(a.price),o>=r))return Number.parseFloat(a.price)}if(t===OrderType.FOK)throw new l$1("Insufficient liquidity for full fill.");let n=e[0];return Number.parseFloat(n.price)}function Oy(e,r,t){if(e.length===0)throw new l$1("No resting liquidity.");let o=0;for(let s=e.length-1;s>=0;s-=1){let a=e[s];if(a!==void 0&&(o+=Number.parseFloat(a.size),o>=r))return Number.parseFloat(a.price)}if(t===OrderType.FOK)throw new l$1("Insufficient liquidity for full fill.");let n=e[0];return Number.parseFloat(n.price)}var My=BigInt(Number.MAX_SAFE_INTEGER),By=z$1.string().refine(Dy,{message:"Order salt must be a non-negative JavaScript-safe integer."}),Sa=z$1.looseObject({salt:By}),Uy=z$1.array(Sa).min(1).max(15),Iq=o(h$1,g,n,c,b,a),bq=o(h$1,g,n,c,b,a);function mt(e){return async function(t){l(t,Sa);let o=ha(e,t);return unwrap(e.secureClob.post("/order",{json:o,rateLimitBucket:"order"}).mapErr(qr).andThen(f(OrderResponseSchema)))}}function vq(e){return async function(t){l(t,Uy);let o=t.map(n=>ha(e,n));return unwrap(e.secureClob.post("/orders",{json:o,rateLimitBucket:"order"}).mapErr(qr).andThen(f(OrderResponsesSchema)))}}function ha(e,r){return invariant(r.postOnly!==true||r.orderType===OrderType.GTC||r.orderType===OrderType.GTD,"Post-only orders are only supported for GTC and GTD order types."),{deferExec:false,order:{builder:r.builder,expiration:`${r.expiration}`,maker:r.maker,makerAmount:r.makerAmount,metadata:r.metadata,salt:Number(BigInt(r.salt)),side:r.side,signature:r.signature,signatureType:r.signatureType,signer:r.signer,takerAmount:r.takerAmount,timestamp:r.timestamp,tokenId:r.tokenId},orderType:r.orderType,owner:e.credentials.key,...r.postOnly===true?{postOnly:true}:{}}}function Dy(e){try{let r=BigInt(e);return r>=0n&&r<=My}catch{return false}}var Ia=32,jy=1n,Hy=2n,ba=3n,Ca=50,Ny=(1n<<256n)-1n,Ky=(1n<<64n)-1n<<40n;function go(e){let r=AbiParameters.encode([{name:"legs",type:"uint256[]"}],[e]),t=Hash.keccak256(AbiParameters.encode([{name:"moduleId",type:"uint256"},{name:"data",type:"bytes"}],[ba,r])),o=toComboConditionId(`0x03${t.slice(34)}0000000000000000000000000000`);return {conditionId:o,positionIds:[toPositionId(BigInt(`${o}00`).toString()),toPositionId(BigInt(`${o}01`).toString())]}}function Ro(e){if(e.length===0||e.length>Ca)throw new a(`Combo legs must include 1 to ${Ca} position IDs`);let r=e.map(t=>{let o=Eo(t),n=o.toString(16).padStart(Ia*2,"0"),s=Number.parseInt(n.slice(0,2),16),a$1=Number.parseInt(n.slice(-2),16);if(s!==1&&s!==2||a$1>1)throw new a("Combo legs must be binary or neg-risk YES/NO position IDs");return {value:o,conditionId:n.slice(0,-2)}});r.sort((t,o)=>t.value<o.value?-1:t.value>o.value?1:0);for(let t=1;t<r.length;t+=1){let o=r[t-1],n=r[t];if(o===void 0||n===void 0)throw new a("Invalid combo leg set");if(o.value===n.value)throw new a("Combo legs must not contain duplicate position IDs");if(o.conditionId===n.conditionId)throw new a("Combo legs must not contain both outcomes for the same condition")}return r.map(t=>t.value)}function cr(e){try{return (Eo(e)&Ky)===0n}catch{return false}}function va(e){let t=Eo(e).toString(16).padStart(Ia*2,"0"),o=BigInt(`0x${t.slice(0,2)}`),n=Number.parseInt(t.slice(-2),16);if(o!==jy&&o!==Hy&&o!==ba)throw new a("Position ID must use a supported protocol v2 module");if(n!==0&&n!==1)throw new a("Protocol v2 position ID must be a YES/NO position ID");return {conditionId:toConditionId(`0x${t.slice(0,-2)}`),outcomeIndex:n}}function Eo(e){let r=e.trim(),t;if(r.length===0)throw new a("Position ID must be a uint256 value");try{t=BigInt(r);}catch{throw new a("Position ID must be a uint256 value")}if(t<0n||t>Ny)throw new a("Position ID must be a uint256 value");return t}var qe=1000000n,Gy=8*Number.EPSILON,So=6,$y=8*Number.EPSILON;function ho(e){let r=e*Number(qe),t=Math.round(r),o=$y*Math.max(1,Math.abs(r)),n=Math.abs(r-t)<=o?t:Math.trunc(r);return BigInt(n)}function Ar(e){let r=Math.round(e*Number(qe)),t=r/Number(qe);if(!Number.isSafeInteger(r)||Math.abs(e-t)>Gy)throw new a("has unsupported precision.");return BigInt(r)}function To(e){return Number(e)/Number(qe)}function ft(e){return invariant(Number.isInteger(e)&&e>=0&&e<=So,`Decimal places must be an integer between 0 and ${So}.`),10n**BigInt(So-e)}function Pt(e,r,t,o){invariant(e>=0n,"Value must be non-negative."),invariant(r>=0n,"Multiplier must be non-negative."),invariant(t>0n,"Denominator must be positive.");let n=e*r,s=n/t;return o==="up"&&n%t!==0n?s+1n:s}function xo(e,r,t){let o=ft(r);return Pt(e,1n,o,t)*o}function Co(e){switch(e){case .1:return {amount:3,size:2};case .01:return {amount:4,size:2};case .005:return {amount:5,size:2};case .0025:return {amount:6,size:2};case .001:return {amount:5,size:2};case 1e-4:return {amount:6,size:2}}invariant(false,`Unsupported tick size: ${e}`);}function gt(e,r){let t=Ar(e),o=Ar(r);if(t<o||t>qe-o)throw new a(`must be between ${r} and ${1-r} for tick size ${r}.`);if(t%o!==0n)throw new a(`${e} must be a multiple of tick size ${r}.`);return t}function Yy(e,r){return r?e.environment.contracts.negRiskExchange:e.environment.contracts.standardExchange}function Be(e,r,t){return cr(r)?e.environment.contracts.exchangeV3:Yy(e,t)}function Io(e,r,t,o){let n=ft(t);return Pt(e,r,qe*n,o)*n}function Qy(e,r,t,o){let n=ft(t);return Pt(e,qe,r*n,o)*n}function ka(e){let r=Co(e.tickSize),t=xo(ho(e.size),r.size,"down");return e.side===OrderSide.BUY?{offeredAmount:Io(t,e.price,r.amount,"down"),requestedAmount:t}:{offeredAmount:t,requestedAmount:Io(t,e.price,r.amount,"down")}}function Aa(e){let r=Co(e.tickSize),t=xo(ho(e.amount),r.size,"down"),o=e.protectPrice?"up":"down";return e.side===OrderSide.BUY?{offeredAmount:t,requestedAmount:Qy(t,e.price,r.amount,o)}:{offeredAmount:t,requestedAmount:Io(t,e.price,r.amount,o)}}var bo=600*1e3,vo=Number.POSITIVE_INFINITY,qo=class{#e;#r=new Map;#n=new Map;#s=new Map;constructor(r){this.#e=r;}async resolveMarket(r){let t=await this.#t(r);return {feeInfo:t.feeInfo,negRisk:t.negRisk,tickSize:t.tickSize}}async resolveBuilderTakerFeeRate(r){return r===void 0?0:Rt(this.#r,r,bo,()=>this.#e.fetchBuilderTakerFeeRate(r))}async fetchCurrentMarket(r){let t=await Rt(this.#n,r,vo,()=>this.#e.resolveCondition(r)),o=await this.#a(t);return this.#o(r,t,o),this.#s.set(t,Oa(o,bo)),{feeInfo:o.feeInfo,negRisk:o.negRisk,tickSize:o.tickSize}}async#t(r){let t=await Rt(this.#n,r,vo,()=>this.#e.resolveCondition(r)),o=await Rt(this.#s,t,bo,()=>this.#a(t));return this.#o(r,t,o),o}#o(r,t,o){if(!o.assetIds.has(r))throw this.#n.delete(r),this.#s.delete(t),new b(`Market ${t} does not include asset ${r}.`)}async#a(r){let t=await this.#e.fetchMarket(r),o=new Set(t.tokens.map(({assetId:n})=>n));for(let n of o)this.#n.set(n,Oa(r));return {feeInfo:t.feeInfo,negRisk:t.negRisk,tickSize:t.tickSize,assetIds:o}}};function Rt(e,r,t,o){let n=e.get(r);if(n!==void 0&&(n.expiresAt===void 0||n.expiresAt>Date.now()))return n.promise;let s={promise:o()};return s.promise.then(()=>{s.expiresAt=Date.now()+t;},()=>{e.get(r)===s&&e.delete(r);}),e.set(r,s),s.promise}function Oa(e,r=vo){return {expiresAt:Date.now()+r,promise:Promise.resolve(e)}}var wa=new WeakMap;function Qe(e,r){return ko(e).resolveMarket(r)}function Or(e,r){return ko(e).fetchCurrentMarket(r)}function La(e,r){return ko(e).resolveBuilderTakerFeeRate(r)}function ko(e){let r=wa.get(e);if(r!==void 0)return r;let t=new qo({fetchBuilderTakerFeeRate:async o=>(await Qs(e,{builderCode:o})).taker,fetchMarket:o=>Ys(e,{conditionId:o}),resolveCondition:o=>Vs(e,{assetId:o})});return wa.set(e,t),t}var Xy=180,Ba=z$1.strictObject({price:PositiveDecimalNumberSchema,size:PositiveDecimalNumberSchema,side:OrderSideSchema,builderCode:BuilderCodeSchema.optional(),postOnly:z$1.boolean().default(false),expiration:z$1.number().int().nonnegative().optional()}),Da=z$1.union([Ba.extend(Fe.shape),Ba.extend(Me.shape)]).superRefine((e,r)=>{if(e.expiration!==void 0){let t=Math.floor(Date.now()/1e3)+Xy;e.expiration<t&&r.addIssue({code:"custom",message:"Expiration must be at least 3 minutes in the future.",path:["expiration"]});}}).transform(({assetId:e,tokenId:r,...t})=>({...t,assetId:e??r}));async function _a(e,r){let t=await ef(e,{assetId:r.assetId,price:r.price}),o=ka({price:t.price,side:r.side,size:r.size,tickSize:t.tickSize});return {assetId:r.assetId,builderCode:r.builderCode,chainId:e.environment.chainId,exchangeAddress:t.exchangeAddress,expiration:r.expiration??0,funderAddress:t.funderAddress,offeredAmount:o.offeredAmount,orderType:r.expiration===void 0?OrderType.GTC:OrderType.GTD,side:r.side,signer:t.signerAddress,requestedAmount:o.requestedAmount}}async function ef(e,r){let t=await Qe(e,r.assetId);try{return Ua(e,r,t)}catch(o){if(!(o instanceof a))throw o;let n=await Or(e,r.assetId);return Ua(e,r,n)}}function Ua(e,r,t){let o=rf(r.price,t.tickSize);return {exchangeAddress:Be(e,r.assetId,t.negRisk),funderAddress:e.account.wallet,price:o,signerAddress:e.account.signer,tickSize:t.tickSize}}function rf(e,r){try{return gt(e,r)}catch(t){throw t instanceof a?new a(`Price ${t.message}`,{cause:t}):t}}var Ga=z$1.object({builderCode:BuilderCodeSchema.optional(),orderType:z$1.union([z$1.literal(OrderType.FAK),z$1.literal(OrderType.FOK)]).default(OrderType.FAK)}),Wa=Ga.extend({side:z$1.literal(OrderSide.BUY),amount:PositiveDecimalNumberSchema,maxSpend:PositiveDecimalNumberSchema.optional(),maxPrice:PositiveDecimalNumberSchema.optional()}),ja=Ga.extend({side:z$1.literal(OrderSide.SELL),shares:PositiveDecimalNumberSchema,minPrice:PositiveDecimalNumberSchema.optional()}),$a=z$1.union([Wa.extend(Fe.shape),Wa.extend(Me.shape),ja.extend(Fe.shape),ja.extend(Me.shape)]).transform(({assetId:e,tokenId:r,...t})=>({...t,assetId:e??r}));async function Va(e,r){let t=await of(e,r,r.assetId),o=Aa({amount:t.resolvedAmount,price:t.price,protectPrice:Qa(r),side:r.side,tickSize:t.tickSize});return {assetId:r.assetId,builderCode:r.builderCode,chainId:e.environment.chainId,exchangeAddress:t.exchangeAddress,expiration:0,funderAddress:t.funderAddress,offeredAmount:o.offeredAmount,orderType:r.orderType,side:r.side,signer:t.signerAddress,requestedAmount:o.requestedAmount}}async function of(e,r,t){return Qa(r)?nf(e,r,t):sf(e,r,t)}async function nf(e,r,t){let o=r.side===OrderSide.BUY?r.amount:r.shares;if(r.side===OrderSide.BUY&&r.maxSpend!==void 0){let{builderTakerFeeRate:s,market:a$1}=await Za(e,t,r.builderCode);try{return Ha(e,r,t,o,s,r.maxSpend,a$1)}catch(y){if(!(y instanceof a))throw y;let P=await Or(e,t);return Ha(e,r,t,o,s,r.maxSpend,P)}}let n=await Qe(e,t);try{return Na(e,r,t,o,n)}catch(s){if(!(s instanceof a))throw s;let a$1=await Or(e,t);return Na(e,r,t,o,a$1)}}function Ha(e,r,t,o,n,s,a){let y=Ya(r,a.tickSize),P=To(y);return {exchangeAddress:Be(e,t,a.negRisk),funderAddress:e.account.wallet,price:y,resolvedAmount:Ja({amount:o,builderTakerFeeRate:n,maxSpend:s,platformFeeExponent:a.feeInfo.exponent,platformFeeRate:a.feeInfo.rate,price:P}),signerAddress:e.account.signer,tickSize:a.tickSize}}function Na(e,r,t,o,n){let s=Ya(r,n.tickSize);return {exchangeAddress:Be(e,t,n.negRisk),funderAddress:e.account.wallet,price:s,resolvedAmount:o,signerAddress:e.account.signer,tickSize:n.tickSize}}async function sf(e,r,t){let o=r.side===OrderSide.BUY?r.amount:r.shares,n=r.side===OrderSide.BUY&&r.maxSpend!==void 0?Za(e,t,r.builderCode):void 0,[s,a]=await Promise.all([ot(e,{assetId:t}),n]);if(s.assetId!==t)throw new b(`Order book returned asset ${s.assetId} for requested asset ${t}.`);let y=Ar(fo({amount:o,orderBook:s,orderType:r.orderType,side:r.side}));return {exchangeAddress:Be(e,t,s.negRisk),funderAddress:e.account.wallet,price:y,resolvedAmount:af(r,o,To(y),a),signerAddress:e.account.signer,tickSize:s.tickSize}}function af(e,r,t,o){return e.side!==OrderSide.BUY||e.maxSpend===void 0||o===void 0?r:Ja({amount:r,builderTakerFeeRate:o.builderTakerFeeRate,maxSpend:e.maxSpend,platformFeeExponent:o.market.feeInfo.exponent,platformFeeRate:o.market.feeInfo.rate,price:t})}function Ya(e,r){return e.side===OrderSide.BUY?(invariant(e.maxPrice!==void 0,"Protected BUY market order requires maxPrice."),Ka("maxPrice",e.maxPrice,r)):(invariant(e.minPrice!==void 0,"Protected SELL market order requires minPrice."),Ka("minPrice",e.minPrice,r))}function Ka(e,r,t){try{return gt(r,t)}catch(o){throw o instanceof a?new a(`${e} ${o.message}`,{cause:o}):o}}function Qa(e){return e.side===OrderSide.BUY&&e.maxPrice!==void 0||e.side===OrderSide.SELL&&e.minPrice!==void 0}async function Za(e,r,t){let[o,n]=await Promise.all([Qe(e,r),La(e,t)]);return {builderTakerFeeRate:n,market:o}}function Ja(e){let r=e.platformFeeRate*(e.price*(1-e.price))**e.platformFeeExponent,t=e.amount/e.price*r,o=e.amount+t+e.amount*e.builderTakerFeeRate;return e.maxSpend<=o?e.maxSpend/(1+r/e.price+e.builderTakerFeeRate):e.amount}var ri="Polymarket CTF Exchange",cf="DepositWallet",df="1",Oo="0x0000000000000000000000000000000000000000000000000000000000000000",wo="Order(uint256 salt,address maker,address signer,uint256 tokenId,uint256 makerAmount,uint256 takerAmount,uint8 side,uint8 signatureType,uint256 timestamp,bytes32 metadata,bytes32 builder)",uf=Hash.keccak256(Bytes.fromString(wo),{as:"Hex"}),lf=Hash.keccak256(Bytes.fromString("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),{as:"Hex"}),mf=Hash.keccak256(Bytes.fromString(ri),{as:"Hex"}),ti=[{name:"name",type:"string"},{name:"version",type:"string"},{name:"chainId",type:"uint256"},{name:"verifyingContract",type:"address"}],oi=[{name:"salt",type:"uint256"},{name:"maker",type:"address"},{name:"signer",type:"address"},{name:"tokenId",type:"uint256"},{name:"makerAmount",type:"uint256"},{name:"takerAmount",type:"uint256"},{name:"side",type:"uint8"},{name:"signatureType",type:"uint8"},{name:"timestamp",type:"uint256"},{name:"metadata",type:"bytes32"},{name:"builder",type:"bytes32"}],yf=[{name:"contents",type:"Order"},{name:"name",type:"string"},{name:"version",type:"string"},{name:"chainId",type:"uint256"},{name:"verifyingContract",type:"address"},{name:"salt",type:"bytes32"}];function St(e){let r=ff(e.domain,e.order);return e.order.signatureType!==SignatureType.POLY_1271?r:{domain:ai(e.domain),message:{chainId:e.domain.chainId,contents:r.message,name:cf,salt:Oo,verifyingContract:e.order.signer,version:df},primaryType:"TypedDataSign",types:{EIP712Domain:ti,Order:oi,TypedDataSign:yf}}}function ht(e){if(e.order.signatureType!==SignatureType.POLY_1271)return e.signature;let r=Bytes.toHex(Bytes.fromString(wo)),t=wo.length.toString(16).padStart(4,"0");return expectErc1271Signature(`0x${e.signature.slice(2)}${Pf(e.domain).slice(2)}${gf(e.order).slice(2)}${r.slice(2)}${t}`)}function ni(e){return {chainId:e.chainId,exchange:e.exchange,protocolVersion:"3"}}function Ek(e,r,t){return e===OrderSide.SELL?t.toString():((r*t+999999n)/1000000n).toString()}function Sk(e,r,t){return e===OrderSide.SELL?(r*t/1000000n).toString():t.toString()}function si(e){return {builder:e.builder??Oo,maker:e.maker,makerAmount:BigInt(e.makerAmount),metadata:e.metadata??Oo,salt:BigInt(e.salt),side:Mo(e.side),signatureType:e.signatureType,signer:e.signer,takerAmount:BigInt(e.takerAmount),timestamp:BigInt(e.timestamp),tokenId:BigInt(e.tokenId)}}function ff(e,r){return {domain:ai(e),message:si(r),primaryType:"Order",types:{EIP712Domain:ti,Order:oi}}}function ai(e){return {chainId:e.chainId,name:ri,verifyingContract:e.exchange,version:e.protocolVersion}}function Pf(e){return expectHexString(Hash.keccak256(AbiParameters.encode([{type:"bytes32"},{type:"bytes32"},{type:"bytes32"},{type:"uint256"},{type:"address"}],[lf,mf,Rf(e.protocolVersion),BigInt(e.chainId),e.exchange]),{as:"Hex"}))}function gf(e){let r=si(e);return expectHexString(Hash.keccak256(AbiParameters.encode([{type:"bytes32"},{type:"uint256"},{type:"address"},{type:"address"},{type:"uint256"},{type:"uint256"},{type:"uint256"},{type:"uint8"},{type:"uint8"},{type:"uint256"},{type:"bytes32"},{type:"bytes32"}],[uf,r.salt,r.maker,r.signer,r.tokenId,r.makerAmount,r.takerAmount,r.side,r.signatureType,r.timestamp,r.metadata,r.builder]),{as:"Hex"}))}function Rf(e){return expectHexString(Hash.keccak256(Bytes.fromString(e),{as:"Hex"}))}function Mo(e){return e===0||e===1?e:e===OrderSide.BUY?0:1}var ii="0x0000000000000000000000000000000000000000000000000000000000000000";function Bo(e,r){let t=Tr(r);return {builder:e.builderCode??ii,chainId:e.chainId,exchangeAddress:e.exchangeAddress,expiration:e.expiration,maker:t.maker,makerAmount:e.offeredAmount.toString(),metadata:ii,orderType:e.orderType,protocolVersion:cr(e.assetId)?"3":"2",salt:Ef().toString(),side:e.side,signatureType:t.signatureType,signer:t.signer,takerAmount:e.requestedAmount.toString(),timestamp:Date.now().toString(),tokenId:e.assetId}}function Uo(e,r){let{chainId:t,exchangeAddress:o,protocolVersion:n,...s}=e;return {...s,signature:r}}function Ef(){let e=new Uint8Array(8);return globalThis.crypto.getRandomValues(e),BigInt(`0x${Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}`)&(1n<<53n)-1n}function Do(e){return St({domain:pi(e),order:e})}function _o(e,r){return ht({domain:pi(e),order:e,signature:r})}function pi(e){return {chainId:e.chainId,exchange:e.exchangeAddress,protocolVersion:e.protocolVersion}}function zo(e){return {kind:"signOrder",payload:e}}var Sf=o(l$1,h$1,g,n,c,b,a);async function Wo(e,r){let t=l(r,$a);return async function*(){let o=await Va(e,t),n=Bo(o,e.account),s=expectEvmSignature(yield zo(Do(n)));return Uo(n,nr(e.account,_o(n,s)))}.call(null)}var hf=o(h$1,g,n,c,b,a);async function jo(e,r){let t=l(r,Da);return async function*(){let o=await _a(e,t),n=Bo(o,e.account),s=expectEvmSignature(yield zo(Do(n))),a=Uo(n,nr(e.account,_o(n,s)));return t.postOnly===true?{...a,postOnly:true}:a}.call(null)}var Dk=Sf;async function _k(e,r){return di(e,Wo(e,r))}var zk=hf;async function Wk(e,r){return di(e,jo(e,r))}async function di(e,r){let t=await r;return async function*(){let o=yield*t;return mt(e)(o)}.call(null)}var Cf=250,If=3e4,bf={timeoutMs:z$1.number().int().positive().optional()},vf=z$1.object(bf).default({}),Yk=o(h$1,g,n,i,j,c,b,a);function qf(e){return e.status===TradeStatus.Confirmed||e.status===TradeStatus.Failed}function ui(e){return e.status===TradeStatus.Failed}async function Qk(e,r,t){let{timeoutMs:o=If}=l(t,vf),n=[...new Set(r.tradeIds)];if(n.length===0)return [...r.transactionsHashes];let s=new Map,a=Date.now()+o;for(;s.size<n.length;){let P=n.filter(I=>!s.has(I)),C=await Promise.all(P.map(I=>Jn(e,{id:I}).firstPage()));for(let I of C)for(let B of I.items)n.includes(B.id)&&qf(B)&&s.set(B.id,B);if(s.size===n.length)break;if(Date.now()>=a){let I=n.filter(B=>!s.has(B));throw new i(`Timed out waiting for trades to settle: ${I.join(", ")}`)}await delay(Cf);}let y=[...s.values()];if(y.every(ui))throw new j(`Every fill of order ${r.orderId} failed execution: ${n.join(", ")}`);return [...new Set(y.filter(P=>!ui(P)).map(P=>P.transactionHash))].map(P=>TxHashSchema.parse(P))}async function fi(e,r){let t=r.side===OrderSide.BUY?AssetType.COLLATERAL:AssetType.CONDITIONAL,{allowances:o}=await Ht(e,r.side===OrderSide.BUY?{assetType:t}:{assetType:t,assetId:r.assetId});return Af(o,r.spenderAddress)}function Af(e,r){return Object.entries(e).find(([o])=>isSameEvmAddress(o,r))?.[1]??0n}var fA=o(k$1,l$1,h$1,g,n,c,b,a);function Of(e,r){return Wo(e,r).then(z(e.signer))}var PA=o(k$1,l$1,h$1,g,n,i,j,c,b,a);function gA(e,r){return Of(e,r).then(t=>gi(e,t))}var RA=o(k$1,h$1,g,n,c,b,a);function wf(e,r){return jo(e,r).then(z(e.signer))}var EA=o(k$1,h$1,g,n,i,j,c,b,a);function SA(e,r){return wf(e,r).then(t=>gi(e,t))}async function gi(e,r){let t=mt(e);try{return await t(r)}catch(o){if(!Ff(o))throw o;let n=await Lf(e,r,t);if(n===void 0)throw o;return n}}async function Lf(e,r,t){return await Mf(e,r)?t(r):void 0}function Ff(e){return e instanceof g&&e.status===400&&e.message.includes("allowance is not enough")}async function Mf(e,r){let t=r.tokenId,o=await Qe(e,t),n=Be(e,t,o.negRisk),s=BigInt(r.makerAmount);return await fi(e,{assetId:t,spenderAddress:n,side:r.side})>=s?false:(await(r.side===OrderSide.BUY?await Ms(e,{amount:"max",spenderAddress:n,tokenAddress:e.environment.contracts.collateralToken}):await Bs(e,{operatorAddress:n,tokenAddress:cr(t)?e.environment.contracts.positionManager:e.environment.contracts.conditionalTokens})).wait(),await es(e,{assetType:r.side===OrderSide.BUY?AssetType.COLLATERAL:AssetType.CONDITIONAL,tokenId:r.side===OrderSide.SELL?t:void 0}),true)}function Ei(e){let r=TypedData.getSignPayload(Ko(e));return expectEvmSignature(Signature.toHex(Secp256k1.sign({payload:r,privateKey:e.privateKey})))}function Ko(e){let r={chainId:e.chainId,name:"Polymarket",version:"1"};return {domain:r,message:{data:Hash.keccak256(encode(Si(e.op)),{as:"Hex"}),salt:BigInt(e.salt),ts:BigInt(e.timestamp)},primaryType:"Op",types:{EIP712Domain:TypedData.extractEip712DomainTypes(r),Op:[{name:"data",type:"bytes32"},{name:"salt",type:"uint64"},{name:"ts",type:"uint64"}]}}}function Si(e){return Array.isArray(e)?e.filter(r=>r!==void 0).map(Si):e}function Ti(e,r){let t=hi(e.get("Poly-RateLimit-Remaining"),/^-?\d+$/),o=hi(e.get("Poly-RateLimit-Reset"),/^\d+$/),n=Wf(e.get("Poly-RateLimit-Tier")),s=e.get("Poly-RateLimit-Warning")?.trim().toLowerCase()==="true";if(!(t===void 0&&o===void 0&&n===void 0&&!s))return {...r===void 0?{}:{bucket:r},remaining:t,reset:o,tier:n,warning:s}}function hi(e,r){let t=e?.trim();if(t===void 0||!r.test(t))return;let o=Number(t);return Number.isSafeInteger(o)?o:void 0}function Wf(e){if(!(e===null||e.trim()===""))return e}var Tt=class{#e;#r;#n;#s;constructor({root:r,headers:t,resolveHeaders:o,onRateLimitUpdate:n}){this.#e=Bn.create({prefixUrl:r,throwHttpErrors:false}),this.#r=t,this.#n=o,this.#s=n;}get(r,t={}){return this.#o("GET",r,t)}post(r,t={}){return this.#o("POST",r,t)}patch(r,t={}){return this.#o("PATCH",r,t)}del(r,t={}){return this.#o("DELETE",r,t)}#t(r){return r.startsWith("/")?r.slice(1):r}#o(r,t,o){return this.#d(this.#a(r,t,o),o.rateLimitBucket)}async#a(r,t,o){let n=this.#p(r,t,o),s=await this.#n?.(n),a=this.#u(this.#r,n.headers,s);return n.body!==void 0&&!a.has("content-type")&&a.set("content-type","application/json"),this.#e(this.#t(t),{body:n.body,headers:a,method:r,searchParams:n.params,...o.timeout!==void 0&&{timeout:o.timeout}})}#p(r,t,o){return {body:"json"in o?this.#c(o.json):void 0,headers:o.headers,json:"json"in o?o.json:void 0,method:r,params:"params"in o?o.params:void 0,path:t}}#c(r){if(r!==void 0)return JSON.stringify(r)}#u(...r){let t=new Headers;for(let o of r)if(o!==void 0)for(let[n,s]of new Headers(o).entries())t.set(n,s);return t}#d(r,t){return ResultAsync.fromPromise(r.then(async o=>{let n=Ti(o.headers,t);if(n!==void 0&&this.#l(n),o.ok)return o;let s=this.#i(o);if(o.status===429)throw new h$1(`Request to ${o.url} was rate limited`,{rateLimit:n,retryAfter:s});let{code:a,message:y,retryAfter:P}=await this.#m(o);throw new g(y,{code:a,retryAfter:s??P,status:o.status})}),o=>o instanceof h$1||o instanceof g?o:c.fromError(o))}#l(r){try{Promise.resolve(this.#s?.(r)).catch(()=>{});}catch{}}#i(r){let t=r.headers.get("retry-after");if(!(t===null||!/^\d+$/.test(t)))return Number(t)}async#m(r){let t=r.headers.get("content-type")?.toLowerCase();if(t?.includes("application/json")){let{error:n,code:s,retry_after_seconds:a}=await r.clone().json().catch(()=>({}));if(n)return {message:`${String(n)} (${r.url})`,...typeof s=="string"&&s!==""?{code:s}:{},...typeof a=="number"&&Number.isFinite(a)&&a>=0?{retryAfter:a}:{}}}if(t?.includes("text/plain")){let n=await r.clone().text().then(s=>s.trim(),()=>"");if(n)return {message:`${n} (${r.url})`}}return r.headers.get("server")?.toLowerCase()?.includes("cloudflare")?{message:`Request to ${r.url} was blocked by Cloudflare with status ${r.status}`}:t?.includes("text/html")||t?.includes("application/xhtml+xml")?{message:`Request to ${r.url} failed with status ${r.status} and an unexpected HTML response body`}:{message:`Request to ${r.url} failed with status ${r.status} and unreadable response body`}}};var Nf=1e4,Kf=3e4,Gf=5e3,$f=10*6e4,Vf=3e4,Yf=25e3,Qf=65e3,xi=class{#e=0;#r;start(r){this.stop(),this.#e=Date.now(),this.#r=setNonBlockingInterval(()=>{r("PING");},Nf);}handleMessage(r){return r!=="PONG"?false:(this.#e=Date.now(),true)}isStale(r){return r-this.#e>Kf}stop(){this.#r!==void 0&&(clearInterval(this.#r),this.#r=void 0);}},Ci=class{#e=0;#r;start(r){this.stop(),this.#e=Date.now(),this.#r=setNonBlockingInterval(()=>{r("PING");},Gf);}handleMessage(){return this.#e=Date.now(),false}isStale(r){return r-this.#e>$f}stop(){this.#r!==void 0&&(clearInterval(this.#r),this.#r=void 0);}},Ii=class{#e=0;#r;start(r){this.#e=Date.now(),this.#r=r;}stop(){this.#r=void 0;}handleMessage(r){return r!=="ping"?false:(this.#e=Date.now(),this.#r?.("pong"),true)}isStale(r){return r-this.#e>Vf}},xt=class{#e=0;#r;start(r){this.stop(),this.#e=Date.now(),this.#r=setNonBlockingInterval(()=>{r(JSON.stringify({id:0,req:"post",op:{type:"ping"}}));},Yf);}handleMessage(){return this.#e=Date.now(),false}isStale(r){return r-this.#e>Qf}stop(){this.#r!==void 0&&(clearInterval(this.#r),this.#r=void 0);}},bi=class{#e=0;#r;start(r){this.stop(),this.#e=Date.now(),this.#r=setNonBlockingInterval(()=>r('{"op":"ping"}'),3e4);}handleMessage(r){return this.#e=Date.now(),false}isStale(r){return r-this.#e>=9e4}stop(){clearInterval(this.#r),this.#r=void 0;}};var Jf=5e3,Xf=250,eP=3e4,It=class{#e;#r=0;get isScheduled(){return this.#e!==void 0}schedule(r){if(this.#e!==void 0||!r.shouldReconnect())return;let t=r.delayPolicy?.(this.#r)??tP(this.#r,{baseMs:Xf,maxMs:eP});this.#r+=1,this.#e=setNonBlockingTimeout(()=>{this.#e=void 0,this.#n(r);},t);}stop(){this.#e!==void 0&&(clearTimeout(this.#e),this.#e=void 0);}resetBackoff(){this.#r=0,this.stop();}async#n(r){if(r.shouldReconnect())try{await r.reconnect();}catch{this.schedule(r);}}},bt=class{#e;#r;#n;#s;#t;#o;#a;constructor(r={}){this.#e=r.heartbeat,this.#r=r.connectTimeoutMs,this.#n=r.closeTimeoutMs;}connect(r){if(this.#t?.readyState===WebSocket.OPEN)return Promise.resolve({reusedOpenSocket:true});if(this.#d(),this.#o!==void 0)return this.#o;let o=this.#c(r).then(()=>({reusedOpenSocket:false})).catch(n=>{throw this.#o===o&&(this.#o=void 0),n});return this.#o=o,o}send(r){return this.#p(JSON.stringify(r))}#p(r){return this.#t?.readyState!==WebSocket.OPEN?false:(this.#t.send(r),true)}async close(){this.#s?.();let r=await this.#m();this.#i(),!(r===void 0||r.readyState===WebSocket.CLOSED)&&await new Promise(t=>{let o=this.#n===void 0?void 0:setNonBlockingTimeout(t,this.#n);r.addEventListener("close",()=>{clearTimeout(o),t();},{once:true}),r.readyState!==WebSocket.CLOSING&&r.close();});}async#c(r){let t=await r.prepare?.();return new Promise((o,n)=>{let s=rP(r.url,r.headers),a,y=()=>{s.removeEventListener("open",P),clearTimeout(a),this.#s=void 0,n(new c("WebSocket connection did not open.")),s.close();},P=()=>{clearTimeout(a),this.#s=void 0,s.removeEventListener("error",C),this.#u(s),this.#l(),r.onOpen(t),o(s);},C=I=>{clearTimeout(a),this.#s=void 0,s.removeEventListener("open",P),n(new c(`WebSocket connection failed: ${r.url}`,{cause:I}));};s.addEventListener("open",P,{once:true}),this.#r!==void 0&&(this.#s=y,a=setNonBlockingTimeout(y,this.#r)),s.addEventListener("error",C,{once:true}),s.addEventListener("message",I=>{if(this.#t!==s)return;let B=String(I.data);if(this.#e?.handleMessage(B))return;let w;try{w=JSON.parse(B);}catch{return}r.onMessage(w);}),s.addEventListener("close",I=>{this.#t===s&&(this.#d(),r.onConnectionLost({code:I.code||1005,reason:I.reason??""}));}),s.addEventListener("error",()=>r.onError());})}#u(r){this.#t=r,this.#o=void 0;}#d(){this.#i(),this.#t=void 0;}#l(){this.#i();let r=this.#e;r!==void 0&&(r.start(t=>this.#p(t)),this.#a=setNonBlockingInterval(()=>{if(!r.isStale(Date.now()))return;let t=this.#t;t?.readyState===WebSocket.OPEN&&t.close();},Jf));}#i(){this.#a!==void 0&&(clearInterval(this.#a),this.#a=void 0),this.#e?.stop();}async#m(){let r=this.#t,t=this.#o;return this.#t=void 0,this.#o=void 0,r!==void 0?r:t?.then(()=>this.#t,()=>{})}};function rP(e,r){if(r===void 0)return new WebSocket(e);try{let t=Reflect.construct(WebSocket,[e,{headers:r}]);if(t instanceof WebSocket)return t}catch(t){throw new c("WebSocket headers require a header-capable WebSocket implementation.",{cause:t})}throw new c("WebSocket headers require a header-capable WebSocket implementation.")}function tP(e,r){let t=Math.min(r.baseMs*2**e,r.maxMs);return Math.random()*t}var vt=1440*60*1e3,Oi=90*vt,pe=z$1.number().int().nonnegative(),Vo=z$1.object({start:pe.optional(),end:pe.optional()}),wi=z$1.object({interval:PerpsPnlIntervalSchema,start:pe,end:pe.optional()}),TP=z$1.enum(["perpsFundingPayments","perpsDeposits","perpsWithdrawals"]),xP=z$1.enum(["perpsEquityHistory","perpsPnlHistory"]),Yo=z$1.object({kind:TP,startTimestamp:pe,endTimestamp:pe,instrumentId:PerpsInstrumentIdSchema.optional(),depositStatus:PerpsDepositStatusSchema.optional(),withdrawalStatus:PerpsWithdrawalStatusSchema.optional(),hash:TxHashSchema.optional(),seenKeys:z$1.array(z$1.string())}),Li=z$1.object({kind:xP,startTimestamp:pe,endTimestamp:pe,interval:PerpsPnlIntervalSchema});async function Fi(e){return await unwrap(e.get("/v1/account/balances").andThen(f(FetchPerpsBalancesResponseSchema)))}async function Mi(e){return await unwrap(e.get("/v1/account/portfolio").andThen(f(FetchPerpsPortfolioResponseSchema)))}async function Bi(e){return await unwrap(e.get("/v1/account/stats").andThen(f(FetchPerpsAccountStatsResponseSchema)))}async function Ui(e){return await unwrap(e.get("/v1/account/auto-cancel").andThen(f(FetchPerpsAutoCancelStatusResponseSchema)))}var CP=z$1.object({instrumentId:PerpsInstrumentIdSchema.optional()}).default({});async function Di(e,r){let t=l(r,CP);return await unwrap(e.get("/v1/account/config",{params:Pe(t)}).andThen(f(FetchPerpsAccountConfigResponseSchema)))}var IP=z$1.object({instrumentId:PerpsInstrumentIdSchema.optional()}).default({});async function _i(e,r){let t=l(r,IP);return await unwrap(e.get("/v1/account/open-orders",{params:Pe(t)}).andThen(f(FetchPerpsOpenOrdersResponseSchema)))}var bP=z$1.object({orderId:PerpsOrderIdSchema.optional(),clientOrderId:PerpsClientOrderIdSchema.optional(),instrumentId:PerpsInstrumentIdSchema.optional(),start:pe.optional(),end:pe.optional()}).default({}),vP=bP.transform(({end:e,start:r,...t})=>({...t,endTimestamp:e,startTimestamp:r}));async function zi(e,r){let t=l(r,vP);return await unwrap(e.get("/v1/account/orders",{params:Pe(t)}).andThen(f(FetchPerpsOrdersResponseSchema)))}var qP=z$1.object({start:pe.optional(),end:pe.optional(),sort:PerpsSortDirectionSchema.optional(),cursor:PaginationCursorSchema.optional()});function Wi(e,r={}){let t=l(r,qP);return x(o=>e.get("/v1/account/fills",{params:Pe({startTimestamp:t.start,endTimestamp:t.end,sort:t.sort,cursor:o??t.cursor})}).andThen(f(ListPerpsFillsResponseSchema)).map(n=>{let s=n.data.at(-1);return !n.more||s===void 0?{items:n.data,hasMore:false}:{items:n.data,hasMore:true,nextCursor:toPaginationCursor(String(s.tradeId))}}),t.cursor)}var kP=Vo.extend({cursor:PaginationCursorSchema.optional(),instrumentId:PerpsInstrumentIdSchema.optional()}),AP=z$1.object({cursor:PaginationCursorSchema}),OP=z$1.union([kP.transform(({cursor:e,...r})=>({cursor:e,params:Qo(r,vt)})),AP.transform(({cursor:e})=>({cursor:e,params:void 0}))]);function ji(e,r={}){let{cursor:t,params:o}=l(r,OP);return x(n=>{let s;n===void 0?(invariant(o!==void 0,"Expected initial Perps funding payment params."),s={kind:"perpsFundingPayments",seenKeys:[],...o}):s=lr(n,Yo);let{kind:a,seenKeys:y,...P}=s,C=new Set(s.seenKeys);return e.get("/v1/account/funding",{params:Pe(P)}).andThen(f(ListPerpsFundingPaymentsResponseSchema)).map(I=>{let B=I.data.filter(w=>!C.has(`${w.instrumentId}:${w.timestamp}:${w.funding}`));return Zo({getKey:w=>`${w.instrumentId}:${w.timestamp}:${w.funding}`,getTimestamp:w=>w.timestamp,items:B,responseData:I.data,responseMore:I.more,state:s})})},t)}var wP=Vo.extend({cursor:PaginationCursorSchema.optional(),depositStatus:PerpsDepositStatusSchema.optional(),hash:TxHashSchema.optional()}),LP=z$1.object({cursor:PaginationCursorSchema}),FP=z$1.union([wP.transform(({cursor:e,...r})=>({cursor:e,params:Qo(r,Oi)})),LP.transform(({cursor:e})=>({cursor:e,params:void 0}))]);function Hi(e,r={}){let{cursor:t,params:o}=l(r,FP);return x(n=>{let s;n===void 0?(invariant(o!==void 0,"Expected initial Perps deposit params."),s={kind:"perpsDeposits",seenKeys:[],...o}):s=lr(n,Yo);let{kind:a,seenKeys:y,...P}=s,C=new Set(s.seenKeys);return e.get("/v1/account/deposits",{params:Pe(P)}).andThen(f(ListPerpsDepositsResponseSchema)).map(I=>{let B=I.data.filter(w=>!C.has(w.hash));return Zo({getKey:w=>w.hash,getTimestamp:JP,items:B,responseData:I.data,responseMore:I.more,state:s})})},t)}var MP=Vo.extend({cursor:PaginationCursorSchema.optional(),withdrawalStatus:PerpsWithdrawalStatusSchema.optional(),hash:TxHashSchema.optional()}),BP=z$1.object({cursor:PaginationCursorSchema}),UP=z$1.union([MP.transform(({cursor:e,...r})=>({cursor:e,params:Qo(r,Oi)})),BP.transform(({cursor:e})=>({cursor:e,params:void 0}))]);function Ni(e,r={}){let{cursor:t,params:o}=l(r,UP);return x(n=>{let s;n===void 0?(invariant(o!==void 0,"Expected initial Perps withdrawal params."),s={kind:"perpsWithdrawals",seenKeys:[],...o}):s=lr(n,Yo);let{kind:a,seenKeys:y,...P}=s,C=new Set(s.seenKeys);return e.get("/v1/account/withdrawals",{params:Pe(P)}).andThen(f(ListPerpsWithdrawalsResponseSchema)).map(I=>{let B=I.data.filter(w=>!C.has(String(w.withdrawalId)));return Zo({getKey:w=>String(w.withdrawalId),getTimestamp:XP,items:B,responseData:I.data,responseMore:I.more,state:s})})},t)}var DP=wi.extend({cursor:PaginationCursorSchema.optional()}),_P=z$1.object({cursor:PaginationCursorSchema}),zP=z$1.union([DP.transform(({cursor:e,...r})=>({cursor:e,params:Qi(r)})),_P.transform(({cursor:e})=>({cursor:e,params:void 0}))]);function Ki(e,r){let{cursor:t,params:o}=l(r,zP);return x(n=>{let s;n===void 0?(invariant(o!==void 0,"Expected initial Perps equity history params."),s={kind:"perpsEquityHistory",...o}):s=lr(n,Li);let{kind:a,...y}=s;return e.get("/v1/account/equity",{params:Pe(y)}).andThen(f(ListPerpsEquityHistoryResponseSchema)).map(P=>{let C=P.data.at(-1),I=P.more&&C!==void 0&&C.timestamp<s.endTimestamp;return {items:P.data,hasMore:I,nextCursor:I?qt({...s,startTimestamp:C.timestamp+Zi(s.interval)}):void 0}})},t)}var WP=wi.extend({cursor:PaginationCursorSchema.optional()}),jP=z$1.object({cursor:PaginationCursorSchema}),HP=z$1.union([WP.transform(({cursor:e,...r})=>({cursor:e,params:Qi(r)})),jP.transform(({cursor:e})=>({cursor:e,params:void 0}))]);function Gi(e,r){let{cursor:t,params:o}=l(r,HP);return x(n=>{let s;n===void 0?(invariant(o!==void 0,"Expected initial Perps PnL history params."),s={kind:"perpsPnlHistory",...o}):s=lr(n,Li);let{kind:a,...y}=s;return e.get("/v1/account/pnl",{params:Pe(y)}).andThen(f(ListPerpsPnlHistoryResponseSchema)).map(P=>{let C=P.data.at(-1),I=P.more&&C!==void 0&&C.timestamp<s.endTimestamp;return {items:P.data,hasMore:I,nextCursor:I?qt({...s,startTimestamp:C.timestamp+Zi(s.interval)}):void 0}})},t)}var NP=z$1.object({kind:z$1.literal("perpsNotifications"),cursor:z$1.string().min(1),sinceSeq:z$1.number().int().nonnegative().optional(),limit:z$1.number().int().positive().optional()}),KP=z$1.object({sinceSeq:z$1.number().int().nonnegative().optional(),limit:z$1.number().int().positive().optional(),cursor:PaginationCursorSchema.optional()}),GP=z$1.object({cursor:PaginationCursorSchema}),$P=z$1.union([KP.transform(({cursor:e,...r})=>({cursor:e,params:r})),GP.transform(({cursor:e})=>({cursor:e,params:void 0}))]);function $i(e,r={}){let{cursor:t,params:o}=l(r,$P);return x(n=>{let s;n===void 0?invariant(o!==void 0,"Expected initial Perps notifications params."):s=lr(n,NP);let a=s===void 0?o?.sinceSeq:s.sinceSeq,y=s===void 0?o?.limit:s.limit;return e.get("/v1/account/notifications",{params:Pe({cursor:s?.cursor,limit:y,sinceSeq:a})}).andThen(f(ListPerpsNotificationsResponseSchema)).map(P=>{let C=P.has_more&&P.next_cursor!==null;return {items:P.items,hasMore:C,nextCursor:C&&P.next_cursor!==null?qt({kind:"perpsNotifications",cursor:P.next_cursor,limit:y,sinceSeq:a}):void 0}})},t)}async function Vi(e){return (await unwrap(e.get("/v1/account/notifications",{params:Pe({limit:1})}).andThen(f(FetchPerpsUnreadNotificationsCountResponseSchema)))).unread}var VP=z$1.object({ids:z$1.array(z$1.string().min(1)).min(1)}),YP=z$1.object({upTo:z$1.object({id:z$1.string().min(1),timestamp:z$1.number().int().nonnegative()})}),QP=z$1.union([VP.transform(({ids:e})=>({ids:e})),YP.transform(({upTo:e})=>({before:ZP(e)}))]);async function Yi(e,r){let t=l(r,QP),o=await unwrap(e.post("/v1/account/notifications/read",{json:t}).andThen(f(MarkPerpsNotificationsReadResponseSchema)));if(o.status==="err")throw new g(o.error??"Perps notifications read request was rejected.",{status:200})}function ZP(e){return btoa(JSON.stringify({ts:e.timestamp,id:e.id})).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function Qo(e,r){let t=Date.now(),{end:o,start:n,...s}=e;return {...s,endTimestamp:o??t,startTimestamp:n??t-r}}function Qi(e){return {endTimestamp:e.end??Date.now(),interval:e.interval,startTimestamp:e.start}}function lr(e,r){try{return r.parse(JSON.parse(atob(e)))}catch(t){throw new a("Invalid Perps account pagination cursor",{cause:t})}}function qt(e){return toPaginationCursor(btoa(JSON.stringify(e)))}function Pe(e){return h(e,T())}function JP(e){return e.confirmedTimestamp??e.createdTimestamp}function XP(e){return e.confirmedTimestamp??e.createdTimestamp}function Zo(e){let r=e.responseData.at(-1),t=e.items.at(-1),o=(t===void 0?void 0:e.getTimestamp(t))??(r===void 0?void 0:e.getTimestamp(r)),n=e.responseMore&&o!==void 0&&o>e.state.startTimestamp;if(!n)return {items:e.items,hasMore:n};let s=t===void 0?o-1:o,a=new Set(e.state.endTimestamp===s?e.state.seenKeys:[]);for(let y of e.items)e.getTimestamp(y)===s&&a.add(e.getKey(y));return {items:e.items,hasMore:n,nextCursor:qt({...e.state,endTimestamp:s,seenKeys:Array.from(a)})}}function Zi(e){switch(e){case "1h":return 3600*1e3;case "4h":return 14400*1e3;case "1d":return vt;case "1w":return 7*vt}invariant(false,`Unsupported Perps account history interval: ${String(e)}`);}var en=z$1.object({instrumentId:PerpsInstrumentIdSchema,side:OrderSideSchema,quantity:PerpsDecimalInputSchema,reduceOnly:z$1.boolean().default(false),clientOrderId:PerpsClientOrderIdSchema.optional()}),sg=en.extend({price:PerpsDecimalInputSchema,timeInForce:z$1.literal(PerpsTimeInForce.GTC),postOnly:z$1.boolean().default(false)}),ag=en.extend({price:PerpsDecimalInputSchema.optional(),timeInForce:z$1.literal(PerpsTimeInForce.IOC),postOnly:z$1.never().optional()}),ig=en.extend({price:PerpsDecimalInputSchema.optional(),timeInForce:z$1.literal(PerpsTimeInForce.FOK),postOnly:z$1.never().optional()}),rn=z$1.discriminatedUnion("timeInForce",[sg,ag,ig]),kt=z$1.object({triggerPrice:PerpsDecimalInputSchema,limitPrice:PerpsDecimalInputSchema.optional()}),At=z$1.object({triggerPrice:PerpsDecimalInputSchema}),pg=z$1.union([z$1.object({takeProfit:kt,stopLoss:kt.optional()}),z$1.object({takeProfit:kt.optional(),stopLoss:kt})]),cg=z$1.object({orders:z$1.array(rn).min(1),expiresAt:z$1.number().int().positive().optional()});async function np(e,r){let t=l(r,cg);return await e.executeCommand({op:["createOrders",t.orders.map(tn)],expiresAt:t.expiresAt},z$1.array(PerpsPostOrderAckSchema))}var dg=z$1.intersection(rn,z$1.intersection(pg,z$1.object({clientOrderId:PerpsClientOrderIdSchema.default(gp),expiresAt:z$1.number().int().positive().optional()}))),ug=z$1.intersection(rn,z$1.object({clientOrderId:PerpsClientOrderIdSchema.default(gp),expiresAt:z$1.number().int().positive().optional(),takeProfit:z$1.never().optional(),stopLoss:z$1.never().optional()})),sp=z$1.array(PerpsPostOrderAckSchema).min(1).refine(e=>e.every(r=>r.status==="ok"),"Expected successful Perps order acknowledgements.");function lg(e){return e.takeProfit!==void 0||e.stopLoss!==void 0}async function ap(e,r){if(lg(r))return await mg(e,r);let t=l(r,ug),[,o]=await e.executeCommandWithEvent({op:["createOrders",[tn(t)]],expiresAt:t.expiresAt},sp,Rp(t.clientOrderId));return {order:o.payload}}async function mg(e,r){let t=l(r,dg),o=[tn(t)],n=t.side===OrderSide.SELL;t.takeProfit!==void 0&&o.push(Ft({buy:n,instrumentId:t.instrumentId,kind:PerpsTpSlKind.TakeProfit,quantity:toDecimalString(t.quantity),trigger:t.takeProfit})),t.stopLoss!==void 0&&o.push(Ft({buy:n,instrumentId:t.instrumentId,kind:PerpsTpSlKind.StopLoss,quantity:toDecimalString(t.quantity),trigger:t.stopLoss}));let[s,a]=await e.executeCommandWithEvent({op:["createOrders",o,PerpsTpSlScope.Order],expiresAt:t.expiresAt},sp,Rp(t.clientOrderId)),y=1,P={};return t.takeProfit!==void 0&&(P.takeProfit=Lt(expectPresent(s[y++],"Expected Perps take-profit acknowledgement."))),t.stopLoss!==void 0&&(P.stopLoss=Lt(expectPresent(s[y],"Expected Perps stop-loss acknowledgement."))),{order:a.payload,tpSl:P}}var yg=z$1.union([z$1.object({takeProfit:At,stopLoss:At.optional()}),z$1.object({takeProfit:At.optional(),stopLoss:At})]),fg=z$1.intersection(yg,z$1.object({instrumentId:PerpsInstrumentIdSchema,expiresAt:z$1.number().int().positive().optional()}));async function ip(e,r){let t=l(r,fg),o=Ig(await e.fetchPortfolio(),t.instrumentId),n=[];t.takeProfit!==void 0&&n.push(Ft({buy:o,instrumentId:t.instrumentId,kind:PerpsTpSlKind.TakeProfit,quantity:"0",trigger:t.takeProfit})),t.stopLoss!==void 0&&n.push(Ft({buy:o,instrumentId:t.instrumentId,kind:PerpsTpSlKind.StopLoss,quantity:"0",trigger:t.stopLoss}));let s=await e.executeCommand({op:["createOrders",n,PerpsTpSlScope.Position],expiresAt:t.expiresAt},z$1.array(PerpsPostOrderAckSchema));for(let P of s)if(P.status==="err")throw new g(P.error,{status:200});let a=0,y={};return t.takeProfit!==void 0&&(y.takeProfit=Lt(expectPresent(s[a++],"Expected Perps take-profit acknowledgement."))),t.stopLoss!==void 0&&(y.stopLoss=Lt(expectPresent(s[a],"Expected Perps stop-loss acknowledgement."))),{tpSl:y}}var Pg=z$1.union([z$1.object({orderId:PerpsOrderIdSchema,clientOrderId:z$1.undefined().optional(),expiresAt:z$1.number().int().positive().optional()}),z$1.object({clientOrderId:PerpsClientOrderIdSchema,orderId:z$1.undefined().optional(),expiresAt:z$1.number().int().positive().optional()})]);async function pp(e,r){let t=l(r,Pg),[o]=t.orderId!==void 0?await wt(e,{orderIds:[t.orderId],expiresAt:t.expiresAt}):await wt(e,{clientOrderIds:[t.clientOrderId],expiresAt:t.expiresAt});return expectPresent(o,"Expected Perps cancel order result.")}var gg=z$1.union([z$1.object({orderIds:z$1.array(PerpsOrderIdSchema).min(1),clientOrderIds:z$1.undefined().optional(),expiresAt:z$1.number().int().positive().optional()}),z$1.object({clientOrderIds:z$1.array(PerpsClientOrderIdSchema).min(1),orderIds:z$1.undefined().optional(),expiresAt:z$1.number().int().positive().optional()})]);async function wt(e,r){let t=l(r,gg);return t.orderIds!==void 0?await e.executeCommand({op:["cancelOrders",t.orderIds],expiresAt:t.expiresAt},z$1.array(PerpsCancelOrderResultSchema)):await e.executeCommand({op:["cancelOrdersCOID",t.clientOrderIds],expiresAt:t.expiresAt},z$1.array(PerpsCancelOrderResultSchema))}var Rg=z$1.object({instrumentId:PerpsInstrumentIdSchema.optional(),expiresAt:z$1.number().int().positive().optional()}).default({});async function cp(e,r){let t=l(r,Rg),o=["cancelAll",t.instrumentId===void 0?[]:[t.instrumentId]];await e.executeDeleteCommand({path:"/v1/trade/orders/all",op:o,responseSchema:PerpsCancelAllOrdersResponseSchema,expiresAt:t.expiresAt});}var Eg=5e3,Sg=z$1.object({cancelAt:z$1.number().int().positive(),expiresAt:z$1.number().int().positive().optional()}).superRefine((e,r)=>{let t=Date.now()+Eg;e.cancelAt<t&&r.addIssue({code:"custom",message:"cancelAt must be at least 5 seconds in the future.",path:["cancelAt"]});}),dp=o(m,h$1,g,n,c,b,a),hg="auto_cancel_daily_limit_reached";async function up(e,r,t){let o=l(t,Sg),n=["autoCancel",[o.cancelAt]],s=r(n,o.expiresAt);await unwrap(e.patch("/v1/trade/auto-cancel",{json:{...s,op:Br(n)}}).andThen(f(PerpsAutoCancelResponseSchema)).mapErr(a=>a instanceof g&&a.message.startsWith(`${hg} (`)?new m("Auto-cancel daily trigger limit reached.",{cause:a}):a));}var Tg=z$1.object({expiresAt:z$1.number().int().positive().optional()}).default({});async function lp(e,r,t){let o=l(t,Tg),n=["autoCancel",[0]],s=r(n,o.expiresAt);await unwrap(e.patch("/v1/trade/auto-cancel",{json:{...s,op:Br(n)}}).andThen(f(PerpsAutoCancelResponseSchema)));}var xg=z$1.object({instrumentId:PerpsInstrumentIdSchema,leverage:z$1.number().int().positive(),crossMargin:z$1.boolean()}),mp=o(g,n,c,a);async function yp(e,r){let t=l(r,xg);return await e.executeCommand({op:["updateLeverage",[t.instrumentId,t.leverage,t.crossMargin]]},PerpsUpdateLeverageResultSchema)}var Cg=z$1.object({instrumentId:PerpsInstrumentIdSchema,amount:PerpsDecimalInputSchema}),fp=o(g,n,c,a);async function Pp(e,r){let t=l(r,Cg),o=toDecimalString(t.amount),n=await e.executeCommand({op:["updateMargin",[t.instrumentId,o]]},PerpsCommandAckSchema);if(n.status==="err")throw new g(n.error,{status:200})}function gp(){let e=globalThis.crypto.getRandomValues(new Uint8Array(16));return PerpsClientOrderIdSchema.parse(Array.from(e,r=>r.toString(16).padStart(2,"0")).join(""))}function Rp(e){return r=>r.type==="order"&&r.payload.clientOrderId===e}function Lt(e){if(e.status==="err")throw new g(e.error,{status:200});return {orderId:e.orderId}}function Ig(e,r){let t=e.positions.find(n=>n.instrumentId===r),o=t===void 0?0:bg(t.size);if(o===0)throw new a(`No open Perps position for instrument ${r}.`);return o<0}function bg(e){let r=e.trim(),t=r.replace(/^[+-]/,"").replace(".","");return /^0*$/.test(t)?0:r.startsWith("-")?-1:1}function tn(e){return [e.instrumentId,e.side===OrderSide.BUY,e.price===void 0?void 0:toDecimalString(e.price),toDecimalString(e.quantity),e.timeInForce,e.postOnly??false,e.reduceOnly===true?true:void 0,e.clientOrderId,void 0]}function Ft(e){return [e.instrumentId,e.buy,e.trigger.limitPrice===void 0?void 0:toDecimalString(e.trigger.limitPrice),e.quantity,void 0,false,true,void 0,[e.trigger.limitPrice===void 0?true:void 0,toDecimalString(e.trigger.triggerPrice),e.kind]]}function Br(e){let[r,t,o]=e;switch(r){case "createOrders":return kg({args:t.map(vg),type:r},o);case "cancelOrders":case "cancelOrdersCOID":return {type:r,args:t};case "autoCancel":{let[n]=t;return {type:r,args:{time:n}}}case "cancelAll":{let[n]=t;return {type:r,args:n===void 0?{}:{iid:n}}}case "updateLeverage":{let[n,s,a]=t;return {type:r,args:{cross:a,iid:n,lev:s}}}case "updateMargin":{let[n,s]=t;return {type:r,args:{amt:s,iid:n}}}default:invariant(false,`Unsupported Perps command: ${String(r)}`);}}function vg(e){let r={iid:e[0],buy:e[1],po:e[5],qty:e[3]};return e[4]!==void 0&&(r.tif=e[4]),e[6]&&(r.ro=e[6]),e[2]!==void 0&&(r.p=e[2]),e[7]!==void 0&&(r.c=e[7]),e[8]!==void 0&&(r.tr=qg(e[8])),r}function qg(e){let r={tpsl:e[2],trp:e[1]};return e[0]!==void 0&&(r.market=e[0]),r}function kg(e,r){return r!==void 0&&(e.grp=r),e}var Mg=3e4,hp=3e4,Bg=2e3,Ug=["balances","portfolio","orders","fills","funding","deposits","withdrawals","notifications","tpsl"],Dg=new Set(["notifications"]),_g=z$1.object({id:z$1.number().int().positive().optional(),data:z$1.unknown().optional()}).passthrough(),Tp=z$1.union([PerpsCommandAckSchema,z$1.array(PerpsCommandAckSchema)]).transform(e=>Array.isArray(e)?e.find(r=>r.status==="err")??e[0]:e),xp=class{credentials;#e;#r;#n;#s;#t;#o=new bt({heartbeat:new xt});#a=pushable({objectMode:true});#p=new Map;#c=new Set;#u=new It;#d=new Map;#l=1;#i;constructor(r){this.#e=new Tt({headers:r.headers,resolveHeaders:async()=>this.#T(),root:r.restUrl}),this.#r=r.chainId,this.credentials=r.credentials,this.#n=r.headers,this.#s=r.onClose,this.#t=r.wsUrl;}get closed(){return this.#i!==void 0}async connect(){await this.#m(false);}async close(){this.#i===void 0&&(this.#i=this.#x()),await this.#i;}[Symbol.asyncIterator](){return this.#a[Symbol.asyncIterator]()}async fetchBalances(){return await Fi(this.#e)}async fetchPortfolio(){return await Mi(this.#e)}async fetchStats(){return await Bi(this.#e)}async fetchAccountConfig(r){return await Di(this.#e,r)}async fetchAutoCancelStatus(){return await Ui(this.#e)}async fetchOpenOrders(r){return await _i(this.#e,r)}async fetchOrders(r){return await zi(this.#e,r)}listFills(r={}){return Wi(this.#e,r)}listFundingPayments(r={}){return ji(this.#e,r)}listDeposits(r={}){return Hi(this.#e,r)}listWithdrawals(r={}){return Ni(this.#e,r)}listEquityHistory(r){return Ki(this.#e,r)}listPnlHistory(r){return Gi(this.#e,r)}listNotifications(r={}){return $i(this.#e,r)}async fetchUnreadNotificationsCount(){return await Vi(this.#e)}async markNotificationsRead(r){await Yi(this.#e,r);}async placeOrder(r){return await ap(this,r)}async postOrders(r){return await np(this,r)}async placePositionTpSl(r){return await ip(this,r)}async cancelOrder(r){return await pp(this,r)}async cancelOrders(r){return await wt(this,r)}async cancelAllOrders(r){await cp(this,r);}async armAutoCancel(r){await up(this.#e,(t,o)=>this.#y(t,o),r);}async disarmAutoCancel(r){await lp(this.#e,(t,o)=>this.#y(t,o),r);}async updateLeverage(r){return await yp(this,r)}async updateMargin(r){await Pp(this,r);}async#m(r){await this.#o.connect({onConnectionLost:()=>this.#b(),onError:()=>{},onMessage:t=>this.#C(t),onOpen:()=>{},headers:this.#n,url:this.#t}),await this.#S(),await this.#h(),this.#u.resetBackoff(),r&&(this.#d.clear(),this.#a.push({reason:"reconnect",type:"resync"}));}async#S(){await this.#P({id:this.#l++,op:{args:{proxy:this.credentials.proxy,secret:this.credentials.secret},type:"auth"},req:"post"},Tp,Mg,"Perps session authentication timed out.");}async#h(){await this.#P({id:this.#l++,req:"sub",chs:Ug},Tp,hp,"Perps session subscription timed out.");}#T(){return {"POLYMARKET-PROXY":this.credentials.proxy,"POLYMARKET-SECRET":this.credentials.secret}}async executeCommand(r,t){let o=Br(r.op),n=this.#y(r.op,r.expiresAt);return await this.#P({...n,id:this.#l++,op:o,req:"post"},t,hp,"Perps command response timed out.")}async executeCommandWithEvent(r,t,o){let n=this.#q(o),s=this.executeCommand(r,t);s.then(()=>this.#k(n,Bg),()=>{});try{let[a,y]=await Promise.all([s,n.promise]);return [a,y]}finally{this.#f(n);}}async executeDeleteCommand(r){let t=this.#y(r.op,r.expiresAt);return await unwrap(this.#e.del(r.path,{json:{...t,op:Br(r.op)}}).andThen(f(r.responseSchema)))}#y(r,t){let o=jg(),n$1=Date.now(),s;try{s=Ei({chainId:this.#r,op:r,privateKey:this.credentials.privateKey,salt:o,timestamp:n$1});}catch(y){throw n.fromError(y,"Could not sign the Perps session command")}let a={salt:o,sig:s,ts:n$1};return t!==void 0&&(a.exp=t),a}async#P(r,t,o,n){let s=zg(t);this.#p.set(r.id,s);let a=setNonBlockingTimeout(()=>{s.reject(new c(n));},o);try{if(!this.#o.send(r))throw new c("Perps session transport is not open.");return await s.promise}finally{clearTimeout(a),this.#p.delete(r.id);}}async#x(){this.#u.stop(),this.#g(new c("Perps session closed.")),this.#E(new c("Perps session closed.")),this.#a.end(),await this.#o.close(),this.#s(this);}#C(r){if(this.#I(r)||PerpsNotificationsResyncFrameSchema.safeParse(r).success)return;let t=PerpsSessionUpdateEventSchema.safeParse(r);if(!t.success)return;let o=t.data;this.#v(o),this.#R(o);}#I(r){let t=_g.safeParse(r);if(!t.success||t.data.id===void 0)return false;let o=this.#p.get(t.data.id);if(o===void 0)return true;let n=o.schema.safeParse(t.data.data);if(!n.success){let s=on(t.data.data??t.data);return s!==void 0?o.reject(new g(s.error,{status:200})):o.reject(new c("Perps session unexpected response.")),true}return Wg(n.data)?o.reject(new g(n.data.error,{status:200})):o.resolve(n.data),true}#b(){this.#g(new c("Perps session connection closed.")),this.#E(new c("Perps session connection closed.")),this.#i===void 0&&this.#u.schedule({reconnect:()=>this.#m(true),shouldReconnect:()=>this.#i===void 0});}#g(r){for(let t of this.#p.values())t.reject(r);this.#p.clear();}#v(r){if(Dg.has(r.channel))return;let t=this.#d.get(r.channel);this.#d.set(r.channel,r.sequence),!(t===void 0||r.sequence===t+1)&&this.#R({channel:r.channel,previousSequence:t,reason:"sequence_gap",sequence:r.sequence,type:"resync"});}#R(r){this.#A(r),this.#a.push(r);}#q(r){let t,o,s={promise:new Promise((a,y)=>{t=a,o=y;}),predicate:r,reject:o,resolve:t};return this.#c.add(s),s}#k(r,t){this.#c.has(r)&&(r.timeout=setNonBlockingTimeout(()=>{this.#f(r),r.reject(new i("Perps event wait timed out."));},t));}#A(r){for(let t of Array.from(this.#c))t.predicate(r)&&(this.#f(t),t.resolve(r));}#f(r){this.#c.delete(r)&&r.timeout!==void 0&&clearTimeout(r.timeout);}#E(r){for(let t of Array.from(this.#c))this.#f(t),t.reject(r);}};function zg(e){let r,t;return {promise:new Promise((n,s)=>{r=n,t=s;}),reject:t,resolve:r,schema:e}}function Wg(e){return Array.isArray(e)?false:on(e)!==void 0}function on(e){if(Array.isArray(e)){for(let t of e){let o=on(t);if(o!==void 0)return o}return}if(typeof e!="object"||e===null)return;let r=e;if(r.status==="err")return {error:typeof r.error=="string"?r.error:"Perps command failed."}}function jg(){let[e]=globalThis.crypto.getRandomValues(new Uint32Array(1));return invariant(e!==void 0,"Expected crypto.getRandomValues to return a salt."),e}var er=o(h$1,g,c,b,a),xe=z$1.number().int().nonnegative(),vp=1440*60*1e3,pR=z$1.object({instrumentId:PerpsInstrumentIdSchema.optional(),category:PerpsInstrumentCategorySchema.optional()}).default({}),LO=er;async function FO(e,r){let t=l(r,pR);return unwrap(e.perps.get("/v1/info/instruments",{params:h(t,T())}).andThen(f(FetchPerpsInstrumentsResponseSchema)))}var cR=z$1.object({instrumentId:PerpsInstrumentIdSchema}),MO=er;async function BO(e,r){let t=l(r,cR),[o]=await uR(e,t);if(o===void 0)throw new b(`Perps ticker ${t.instrumentId} was not returned by the API`);return o}var dR=z$1.object({instrumentId:PerpsInstrumentIdSchema.optional()}).default({}),UO=er;async function uR(e,r){let t=l(r,dR),o=h(t,T()),[n,s]=await Promise.all([unwrap(e.perps.get("/v1/info/tickers",{params:o}).andThen(f(FetchPerpsTickersResponseSchema))),unwrap(e.perps.get("/v1/info/statistics",{params:o}).andThen(f(FetchPerpsStatisticsResponseSchema)))]),a=new Map(s.map(y=>[y.instrumentId,y]));return n.map(y=>{let P=a.get(y.instrumentId);return {...y,openPrice:P?.openPrice,volume24h:P?.volume}})}var lR=z$1.union([z$1.literal(10),z$1.literal(100),z$1.literal(500),z$1.literal(1e3)]),mR=z$1.object({instrumentId:PerpsInstrumentIdSchema,depth:lR.default(100)}),DO=er;async function _O(e,r){let t=l(r,mR);return unwrap(e.perps.get("/v1/info/book",{params:h(t,T())}).andThen(f(PerpsBookSchema)))}var yR=z$1.object({instrumentId:PerpsInstrumentIdSchema,interval:PerpsKlineIntervalSchema,start:xe.optional(),end:xe.optional(),cursor:PaginationCursorSchema.optional()}),fR=z$1.object({cursor:PaginationCursorSchema}),PR=z$1.union([yR.transform(({cursor:e,...r})=>({cursor:e,params:bR(r)})),fR.transform(({cursor:e})=>({cursor:e,params:void 0}))]),zO=er;function WO(e,r){let{cursor:t,params:o}=l(r,PR);return x(n=>{let s=n===void 0?vR(o):AR(n);return e.perps.get("/v1/info/klines",{params:h({endTimestamp:s.endTimestamp,instrumentId:s.instrumentId,interval:s.interval,startTimestamp:s.startTimestamp},T())}).andThen(f(FetchPerpsCandlesResponseSchema)).map(a=>{let y=a.data.at(-1),P=a.more&&y!==void 0;return {items:a.data,hasMore:P,nextCursor:P?pn({...s,startTimestamp:y.timestamp+LR(s.interval)}):void 0}})},t)}var qp=z$1.object({instrumentId:PerpsInstrumentIdSchema,start:xe.optional(),end:xe.optional()}),gR=qp.extend({cursor:PaginationCursorSchema.optional()}),RR=z$1.object({cursor:PaginationCursorSchema}),ER=z$1.union([gR.transform(({cursor:e,...r})=>({cursor:e,params:kp(r)})),RR.transform(({cursor:e})=>({cursor:e,params:void 0}))]),SR=qp.extend({cursor:PaginationCursorSchema.optional()}),hR=z$1.object({cursor:PaginationCursorSchema}),jO=er;function HO(e,r){let{cursor:t,params:o}=l(r,ER);return x(n=>{let s=n===void 0?qR(o):OR(n);return e.perps.get("/v1/info/funding",{params:h({endTimestamp:s.endTimestamp,instrumentId:s.instrumentId,startTimestamp:s.startTimestamp},T())}).andThen(f(FetchPerpsFundingHistoryResponseSchema)).map(a=>{let y=a.data.at(-1),P=a.more&&y!==void 0&&y.timestamp>s.startTimestamp;return {items:a.data,hasMore:P,nextCursor:P?pn({...s,endTimestamp:y.timestamp-1}):void 0}})},t)}var TR=z$1.union([SR.transform(({cursor:e,...r})=>({cursor:e,params:kp(r)})),hR.transform(({cursor:e})=>({cursor:e,params:void 0}))]),NO=er;function KO(e,r){let{cursor:t,params:o}=l(r,TR);return x(n=>{let s=n===void 0?kR(o):wR(n),a=new Set(s.seenTradeIds);return e.perps.get("/v1/info/trades",{params:h({endTimestamp:s.endTimestamp,instrumentId:s.instrumentId,startTimestamp:s.startTimestamp},T())}).andThen(f(FetchPerpsTradesResponseSchema)).map(y=>{let P=y.data.filter(kc=>!a.has(kc.tradeId)),C=y.data.at(-1),I=P.at(-1),B=I?.timestamp??C?.timestamp,w=y.more&&B!==void 0&&B>s.startTimestamp;return {items:P,hasMore:w,nextCursor:w?pn({...s,endTimestamp:I===void 0?B-1:B,seenTradeIds:I===void 0?[]:FR(s,P,I)}):void 0}})},t)}var GO=o(h$1,g,c,b);async function $O(e){return (await unwrap(e.perps.get("/v1/info/fees").andThen(f(FetchPerpsFeesResponseSchema)))).feeSchedule}var xR=z$1.object({kind:z$1.literal("perpsCandles"),instrumentId:PerpsInstrumentIdSchema,interval:PerpsKlineIntervalSchema,startTimestamp:xe,endTimestamp:xe}),CR=z$1.object({kind:z$1.literal("perpsFundingHistory"),instrumentId:PerpsInstrumentIdSchema,startTimestamp:xe,endTimestamp:xe}),IR=z$1.object({kind:z$1.literal("perpsTrades"),instrumentId:PerpsInstrumentIdSchema,startTimestamp:xe,endTimestamp:xe,seenTradeIds:z$1.array(PerpsTradeIdSchema)});function bR(e){let r=Date.now();return {endTimestamp:e.end??r,instrumentId:e.instrumentId,interval:e.interval,startTimestamp:e.start??r-vp}}function kp(e){let r=Date.now();return {endTimestamp:e.end??r,instrumentId:e.instrumentId,startTimestamp:e.start??r-vp}}function vR(e){return invariant(e!==void 0,"Expected initial Perps candles params."),{kind:"perpsCandles",...e}}function qR(e){return invariant(e!==void 0,"Expected initial Perps funding params."),{kind:"perpsFundingHistory",...e}}function kR(e){return invariant(e!==void 0,"Expected initial Perps trades params."),{kind:"perpsTrades",seenTradeIds:[],...e}}function AR(e){return an(e,xR)}function OR(e){return an(e,CR)}function wR(e){return an(e,IR)}function an(e,r){try{return r.parse(JSON.parse(atob(e)))}catch(t){throw new a("Invalid Perps pagination cursor",{cause:t})}}function pn(e){return toPaginationCursor(btoa(JSON.stringify(e)))}function LR(e){switch(e){case "1s":return 1e3;case "1m":return 60*1e3;case "5m":return 300*1e3;case "15m":return 900*1e3;case "1h":return 3600*1e3;case "4h":return 14400*1e3;case "1d":return 1440*60*1e3;case "1w":return 10080*60*1e3}invariant(false,`Unsupported Perps kline interval: ${String(e)}`);}function FR(e,r,t){let o=new Set(e.endTimestamp===t.timestamp?e.seenTradeIds:[]);for(let n of r)n.timestamp===t.timestamp&&o.add(n.tradeId);return Array.from(o)}var MR=z$1.custom(e=>isPrivateKey(e),"Expected a hex-encoded 32-byte private key."),BR=z$1.object({proxy:z$1.string().transform(e=>expectEvmAddress(e)),privateKey:MR,secret:z$1.string().min(1),expiresAt:z$1.number().int().positive()}),UR=10080*60*1e3,DR=z$1.strictObject({expiresIn:z$1.number().int().positive().default(UR),label:z$1.string().min(1).optional()}),_R=z$1.strictObject({credentials:BR}),zR=z$1.union([DR,_R]),WR=z$1.object({proxy:z$1.string()}),jR=WR.transform(e=>({proxy:expectEvmAddress(e.proxy)})),Ap=z$1.bigint().positive().max(re),HR=z$1.object({amount:Ap,metadata:V.optional()}),NR=z$1.object({amount:Ap}),VO=o(h$1,g,n,c,b,a),YO=o(h$1,g,n,c,b,a),QO=o(a),ZO=o(k$1,h$1,g,n,c,b,a),JO=o(h$1,g,n,c,b,a);async function XO(e,r={}){let t=l(r,zR),o="credentials"in t?await $R(e,t.credentials):await GR(e,t);return e.webSockets.perpsSession.connect(o)}async function ew(e,r){let t=l(r,jR),o={type:"deleteProxy",args:{proxy:t.proxy}},n=["deleteProxy",[t.proxy]],s=cn(),a=Date.now(),y=await YR(e,{salt:s,signedOp:n,timestamp:a}),P=await unwrap(e.perps.del("/v1/account/proxy",{json:{op:o,salt:s,sig:y,ts:a}}).andThen(f(PerpsDeleteProxyResponseSchema)));if(P.status==="err")throw new g(P.error??"Perps credentials revocation was rejected.",{status:200})}async function KR(e,r){let t=l(r,HR),{contracts:o}=e.environment,n=Ss(o.perpsDepositContract,o.collateralToken,t.amount,e.account.signer);return async function*(){return e.account.walletType===WalletType.EOA?N(yield tE(K(e.environment.chainId,n))):yield*await Y(e,{calls:[n],metadata:t.metadata??`Deposit ${t.amount} of ${o.collateralToken} to Perps`})}.call(null)}function rw(e,r){return KR(e,r).then(z(e.signer))}async function tw(e,r){let t=l(r,NR),o=Math.floor(Date.now()/1e3),n=cn(),s={type:"withdraw",args:{account:e.account.signer,token:e.environment.contracts.collateralToken,amount:t.amount.toString(),to:e.account.wallet}},a=await QR(e,{amount:t.amount,salt:n,timestamp:o}),y=await unwrap(e.perps.post("/v1/account/withdraw",{json:{op:s,salt:n,sig:a,ts:o}}).andThen(f(PerpsWithdrawResponseSchema)));if(y.status==="err")throw new g(y.error??"Perps withdrawal was rejected.",{status:200});if(y.withdrawalId===void 0)throw new b("Perps withdrawal response did not include a withdrawal ID.");return y.withdrawalId}async function GR(e,r){let t=XR(),o=wp(t),n=e.account.signer,s=Date.now()+r.expiresIn,a=Date.now(),y=cn(),P={args:{expiry:s,owner:n,proxy:o},type:"createProxy"},C=await VR(e,{expiresAt:s,proxy:o,salt:y,timestamp:a}),I={op:P,salt:y,sig:C,ts:a};r.label!==void 0&&(I.label=r.label);let B=await unwrap(e.perps.post("/v1/account/proxy",{json:I}).andThen(f(PerpsCreateProxyResponseSchema))),w={expiresAt:s,privateKey:t,proxy:o,secret:B.secret};return Op(e,w)}async function $R(e,r){return eE(r),Op(e,r)}async function Op(e,r){let t=await unwrap(e.perps.get("/v1/account/credentials",{headers:rE(r)}).andThen(f(PerpsCredentialsResponseSchema)));if(!isSameEvmAddress(t.address,e.account.signer))throw new b("Perps credentials belong to a different signer account.");let o=t.keys.find(n=>isSameEvmAddress(n.proxy,r.proxy));if(o===void 0)throw new b("Perps credentials were not returned by the API.");if(o.expiresAt<=Date.now())throw new b("Perps credentials are expired.");return {...r,expiresAt:o.expiresAt}}async function VR(e,r){try{return await e.signer.signTypedData(JR({chainId:e.environment.chainId,...r}))}catch(t){throw n.fromError(t,"Could not sign the Perps proxy credentials request")}}async function YR(e,r){try{return await e.signer.signTypedData(Ko({chainId:e.environment.chainId,op:r.signedOp,salt:r.salt,timestamp:r.timestamp}))}catch(t){throw n.fromError(t,"Could not sign the Perps operation request")}}async function QR(e,r){try{return await e.signer.signTypedData(ZR({account:e.account.signer,chainId:e.environment.chainId,contract:e.environment.contracts.perpsDepositContract,token:e.environment.contracts.collateralToken,to:e.account.wallet,...r}))}catch(t){throw n.fromError(t,"Could not sign the Perps withdrawal request")}}function ZR(e){let r={chainId:e.chainId,name:"Polymarket",verifyingContract:e.contract,version:"1"};return {domain:r,message:{account:e.account,amount:e.amount,fee:0n,salt:e.salt,token:e.token,to:e.to,ts:e.timestamp},primaryType:"Withdraw",types:{EIP712Domain:TypedData.extractEip712DomainTypes(r),Withdraw:[{name:"account",type:"address"},{name:"token",type:"address"},{name:"amount",type:"uint256"},{name:"fee",type:"uint256"},{name:"to",type:"address"},{name:"salt",type:"uint64"},{name:"ts",type:"uint64"}]}}}function JR(e){let r={chainId:e.chainId,name:"Polymarket",version:"1"};return {domain:r,message:{addr:e.proxy,exp:e.expiresAt,salt:e.salt,ts:e.timestamp},primaryType:"CreateProxy",types:{CreateProxy:[{name:"addr",type:"address"},{name:"exp",type:"uint64"},{name:"salt",type:"uint64"},{name:"ts",type:"uint64"}],EIP712Domain:TypedData.extractEip712DomainTypes(r)}}}function XR(){return expectPrivateKey(Secp256k1.randomPrivateKey(),"Generated invalid Perps proxy key.")}function wp(e){return expectEvmAddress(Address.fromPublicKey(Secp256k1.getPublicKey({privateKey:e})))}function eE(e){let r=wp(e.privateKey);if(!isSameEvmAddress(r,e.proxy))throw new a("Perps credentials private key does not match the proxy address.")}function rE(e){return {"POLYMARKET-PROXY":e.proxy,"POLYMARKET-SECRET":e.secret}}function tE(e){return {kind:"sendPerpsDepositTransaction",request:e}}function cn(){let[e]=crypto.getRandomValues(new Uint32Array(1));return invariant(e!==void 0,"Expected crypto.getRandomValues to return a salt."),e}var gE=z$1.object({cursor:PaginationCursorSchema.optional(),pageSize:k.max(1e3).default(100),user:EvmAddressSchema.optional(),conditionId:z$1.union([CanonicalMarketConditionIdSchema,ue(CanonicalMarketConditionIdSchema,20)]).optional(),status:PositionStatusSchema.optional(),eventId:z$1.array(EventIdSchema).min(1).optional(),filterType:PositionFilterTypeSchema.optional(),filterAmount:z$1.number().min(0).optional(),includeArchived:z$1.boolean().optional(),sortBy:PositionSortBySchema.optional(),sortDirection:SortDirectionSchema.optional(),window:sr.optional()}).refine(e=>e.user!==void 0||e.conditionId,{message:"Provide user or conditionId",path:["user"]}).refine(e=>e.user!==void 0||!Array.isArray(e.conditionId)||e.conditionId.length===1,{message:"Without user, provide exactly one conditionId",path:["conditionId"]}).refine(e=>!(e.conditionId&&e.eventId),{message:"Provide conditionId or eventId, not both",path:["eventId"]}).refine(e=>e.user!==void 0||e.eventId===void 0,{message:"eventId requires user",path:["eventId"]}).refine(e=>!(e.includeArchived&&e.status==="CLOSED"),{message:"includeArchived does not apply to CLOSED positions",path:["includeArchived"]}),fw=o(h$1,g,c,b,a);function Pw(e,r){let{cursor:t,pageSize:o,window:n,...s}=l(r,gE);return x(a=>_(()=>e.data.get("/v2/positions",{params:D({...s,...n,limit:o,cursor:a})})).andThen(f(ListPositionsResponseSchema)),t)}var RE=z$1.union([ComboPositionStatusSchema,z$1.tuple([ComboPositionStatusSchema],ComboPositionStatusSchema).refine(e=>e.length===1||!e.includes(ComboPositionStatus.Redeemable),{message:"REDEEMABLE must be the sole status value"})]),EE=z$1.object({cursor:PaginationCursorSchema.optional(),pageSize:k.max(1e3).default(100),user:EvmAddressSchema,conditionId:z$1.union([ComboConditionIdSchema,ue(ComboConditionIdSchema,20)]).optional(),status:RE.optional(),sortBy:ComboPositionSortBySchema.optional(),sortDirection:SortDirectionSchema.optional(),updatedAfter:je.optional(),updatedBefore:je.optional()}),SE=EE.refine(e=>e.updatedBefore===void 0||e.updatedAfter===void 0||e.updatedBefore>=e.updatedAfter,{message:"updatedBefore must not precede updatedAfter",path:["updatedBefore"]}),gw=o(h$1,g,c,b,a);function Rw(e,r){let{cursor:t,pageSize:o,...n}=l(r,SE);return x(s=>_(()=>e.data.get("/v2/positions/combos",{params:D({...n,limit:o,cursor:s})})).andThen(f(ListComboPositionsResponseSchema)),t)}var hE=z$1.object({user:EvmAddressSchema,conditionIds:ue(CanonicalMarketConditionIdSchema,20).optional()}),Ew=o(h$1,g,c,b,a);async function Sw(e,r){let{conditionIds:t,...o}=l(r,hE);return unwrap(_(()=>e.data.get("/v2/value",{params:D({...o,condition:t})})).andThen(f(FetchPortfolioValueResponseSchema)))}var TE=z$1.object({user:EvmAddressSchema}),hw=o(h$1,g,c,b,a);async function Tw(e,r){let t=l(r,TE);return unwrap(_(()=>e.data.get("/v2/user-stats",{params:D(t)})).andThen(f(FetchUserStatsResponseSchema)))}var xE=z$1.object({user:EvmAddressSchema,interval:UserPnlIntervalSchema.optional(),fidelity:UserPnlFidelitySchema.optional()}),xw=o(h$1,g,c,b,a);async function Cw(e,r){let t=l(r,xE);return unwrap(_(()=>e.data.get("/v2/user-pnl",{params:D(t)})).andThen(f(FetchUserPnlResponseSchema)))}var CE=z$1.object({user:EvmAddressSchema,window:sr.optional()}),Iw=o(h$1,g,c,b,a);async function bw(e,r){let{window:t,...o}=l(r,CE);return unwrap(_(()=>e.data.get("/v2/user-volume",{params:D({...o,...t})})).andThen(f(FetchUserVolumeResponseSchema)))}var IE=z$1.object({user:z$1.string()}),vw=o(h$1,g,c,b,a);async function qw(e,r){let t=l(r,IE);return unwrap(e.data.get("/v1/accounting/snapshot",{params:Qn(t)}).andThen(Mn))}var Bp=o(h$1,g,c,b,a),Up=z$1.object({amount:z$1.bigint().min(0n),conditionId:ConditionIdSchema,metadata:V.optional()}),Qw=Bp;async function Dp(e,r){let t=l(r,Up),o=await gn(e,{conditionId:t.conditionId}),n=o.protocol==="ctf"?hs(o.adapterAddress,e.environment.contracts.collateralToken,o.conditionId,t.amount):Vt(e.environment.contracts.protocolV2Router,o.conditionId,t.amount);return async function*(){return e.account.walletType===WalletType.EOA?N(yield ln(K(e.environment.chainId,n))):yield*await Y(e,{calls:[n],metadata:t.metadata??`Split ${t.amount} positions for market ${o.marketId} (condition ${o.conditionId})`})}.call(null)}var _p=z$1.object({amount:z$1.bigint().positive(),legs:z$1.array(PositionIdSchema).min(1).max(50),metadata:V.optional()}),Zw=Bp;async function zp(e,r){let t=l(r,_p),o=Ro(t.legs),n=Qt(e.environment.contracts.combinatorialModule,o),s=go(o),a=Vt(e.environment.contracts.protocolV2Router,s.conditionId,t.amount);return async function*(){return e.account.walletType===WalletType.EOA?(await N(yield ln(K(e.environment.chainId,n))).wait(),N(yield ln(K(e.environment.chainId,a)))):yield*await Y(e,{calls:[n,a],metadata:t.metadata??`Split ${t.amount} combo positions for condition ${s.conditionId}`})}.call(null)}var vE=z$1.union([Up.extend({legs:z$1.never().optional()}),_p.extend({conditionId:z$1.never().optional()})]);async function qE(e,r){let t=l(r,vE);return t.legs!==void 0?zp(e,t):Dp(e,t)}var Wp=o(k$1,h$1,g,n,i,j,c,b,a),Jw=Wp;function Xw(e,r){return Dp(e,r).then(z(e.signer))}var e0=Wp;function r0(e,r){return zp(e,r).then(z(e.signer))}function t0(e,r){return qE(e,r).then(z(e.signer))}var jp=o(h$1,g,c,b,a),Hp=z$1.object({amount:z$1.union([z$1.bigint().positive(),z$1.literal("max")]),conditionId:ConditionIdSchema,metadata:V.optional()}),o0=jp;async function Np(e,r){let t=l(r,Hp),o=await gn(e,{conditionId:t.conditionId}),n=Zr(await e.rpc.ethCall(Qr(o.positionErc1155Address,e.account.wallet,o.outcomeIds))),s=Xp(o.conditionId,n,t.amount),a=o.protocol==="ctf"?Ts(o.adapterAddress,e.environment.contracts.collateralToken,o.conditionId,s):Yt(e.environment.contracts.protocolV2Router,o.conditionId,s);return async function*(){return e.account.walletType===WalletType.EOA?N(yield mn(K(e.environment.chainId,a))):yield*await Y(e,{calls:[a],metadata:t.metadata??`Merge ${s} positions for market ${o.marketId} (condition ${o.conditionId})`})}.call(null)}var Kp=z$1.object({amount:z$1.union([z$1.bigint().positive(),z$1.literal("max")]),legs:z$1.array(PositionIdSchema).min(1).max(50),metadata:V.optional()}),n0=jp;async function Gp(e,r){let t=l(r,Kp),o=Ro(t.legs),n=Qt(e.environment.contracts.combinatorialModule,o),s=go(o),a=Zr(await e.rpc.ethCall(Qr(e.environment.contracts.positionManager,e.account.wallet,s.positionIds))),y=Xp(s.conditionId,a,t.amount),P=Yt(e.environment.contracts.protocolV2Router,s.conditionId,y);return async function*(){return e.account.walletType===WalletType.EOA?(await N(yield mn(K(e.environment.chainId,n))).wait(),N(yield mn(K(e.environment.chainId,P)))):yield*await Y(e,{calls:[n,P],metadata:t.metadata??`Merge ${y} combo positions for condition ${s.conditionId}`})}.call(null)}var kE=z$1.union([Hp.extend({legs:z$1.never().optional()}),Kp.extend({conditionId:z$1.never().optional()})]);async function AE(e,r){let t=l(r,kE);return t.legs!==void 0?Gp(e,t):Np(e,t)}var $p=o(k$1,h$1,g,n,i,j,c,b,a),s0=$p;function a0(e,r){return Np(e,r).then(z(e.signer))}var i0=$p;function p0(e,r){return Gp(e,r).then(z(e.signer))}function c0(e,r){return AE(e,r).then(z(e.signer))}var Vp=o(h$1,g,c,b,a),Yp=z$1.object({conditionId:ConditionIdSchema,marketId:z$1.never().optional(),amount:z$1.never().optional(),positionId:z$1.never().optional(),metadata:V.optional()}),Qp=z$1.object({conditionId:z$1.never().optional(),marketId:MarketIdSchema,amount:z$1.never().optional(),positionId:z$1.never().optional(),metadata:V.optional()}),OE=z$1.union([Yp,Qp]),d0=Vp;async function wE(e,r){let t=l(r,OE),o=await gn(e,t.conditionId!==void 0?{conditionId:t.conditionId,closed:true}:{marketId:t.marketId,closed:true}),n=await DE(e,o);return async function*(){return e.account.walletType===WalletType.EOA?yield*ME(e,n):yield*await Y(e,{calls:n,metadata:t.metadata??`Redeem positions for market ${o.marketId} (condition ${o.conditionId})`})}.call(null)}var Zp=z$1.object({positionId:PositionIdSchema,conditionId:z$1.never().optional(),marketId:z$1.never().optional(),metadata:V.optional()});async function Jp(e,r){let t=l(r,Zp),o=va(t.positionId),n=gs(await e.rpc.ethCall(Ps(e.environment.contracts.positionManager,e.account.wallet,t.positionId)));if(n===0n)throw new a("Position has no balance to redeem");let s=Jr(e.environment.contracts.protocolV2Router,o.conditionId,o.outcomeIndex,n);return async function*(){return e.account.walletType===WalletType.EOA?N(yield yn(K(e.environment.chainId,s))):yield*await Y(e,{calls:[s],metadata:t.metadata??`Redeem position ${t.positionId}`})}.call(null)}var u0=Vp;function l0(e,r){return Jp(e,r)}var LE=z$1.union([Yp,Qp,Zp]);async function FE(e,r){let t=l(r,LE);return t.positionId!==void 0?Jp(e,t):wE(e,t)}var m0=o(k$1,h$1,g,n,i,j,c,b,a);function y0(e,r){return FE(e,r).then(z(e.signer))}function ln(e){return {kind:"sendSplitPositionTransaction",request:e}}function mn(e){return {kind:"sendMergePositionsTransaction",request:e}}function yn(e){return {kind:"sendRedeemPositionsTransaction",request:e}}async function*ME(e,r){let[t,...o]=r;invariant(t!==void 0,"Expected at least one redemption call");let n=t;for(let s of o)await N(yield yn(K(e.environment.chainId,n))).wait(),n=s;return N(yield yn(K(e.environment.chainId,n)))}async function gn(e,r){let t=r.conditionId!==void 0?`condition ${r.conditionId}`:`market ${r.marketId}`,o=await da(e,r.conditionId!==void 0?{conditionIds:[r.conditionId],closed:r.closed,pageSize:1}:{ids:[BE(r.marketId)],closed:r.closed,pageSize:1}).firstPage(),[n]=o.items;if(n===void 0)throw new a(`No market found for ${t}`);let s=UE(n,t);return s.protocol==="v2"?{...s,positionErc1155Address:e.environment.contracts.positionManager}:{...s,adapterAddress:s.negRisk?e.environment.contracts.negRiskCollateralAdapter:e.environment.contracts.collateralAdapter,positionErc1155Address:s.negRisk?e.environment.contracts.negRiskAdapter:e.environment.contracts.conditionalTokens}}function BE(e){let r=Number(e);if(!Number.isInteger(r))throw new a(`Market ID must be an integer, received ${e}`);return r}function UE(e,r){if(!isPresent(e.conditionId))throw new b(`Missing condition ID for ${r}`);let t=e.outcomes.yes.tokenId,o=e.outcomes.no.tokenId,n=e.outcomes.yes.positionId,s=e.outcomes.no.positionId;if(isPresent(t)!==isPresent(o))throw new b(`Incomplete market token IDs for ${r}`);if(isPresent(t)&&isPresent(o)){if(!isPresent(e.state.negRisk))throw new b(`Missing negative-risk flag for ${r}`);return {marketId:e.id,conditionId:e.conditionId,protocol:"ctf",negRisk:e.state.negRisk,outcomeIds:[t,o]}}if(isPresent(n)!==isPresent(s))throw new b(`Incomplete market position IDs for ${r}`);if(isPresent(n)&&isPresent(s))return {marketId:e.id,conditionId:e.conditionId,protocol:"v2",outcomeIds:[n,s]};throw new b(`Missing tradeable outcome IDs for ${r}`)}async function DE(e,r){if(r.protocol==="ctf")return [xs(r.adapterAddress,e.environment.contracts.collateralToken,r.conditionId)];let t=Zr(await e.rpc.ethCall(Qr(r.positionErc1155Address,e.account.wallet,r.outcomeIds)));if(t.length!==2)throw new b("Expected two position balances");let[o,n]=t;invariant(o!==void 0,"Expected YES position balance"),invariant(n!==void 0,"Expected NO position balance");let s=[];if(o>0n&&s.push(Jr(e.environment.contracts.protocolV2Router,r.conditionId,0,o)),n>0n&&s.push(Jr(e.environment.contracts.protocolV2Router,r.conditionId,1,n)),s.length===0)throw new a(`Market positions have no balance to redeem for condition ${r.conditionId}`);return s}function Xp(e,r,t){let o=_E(r);if(o===0n)throw new a(`You have no complementary positions to merge for condition ${e}`);if(t==="max")return o;if(t>o)throw new a(`Requested merge amount ${t} exceeds the maximum mergeable amount ${o} for condition ${e}`);return t}function _E(e){if(e.length!==2)throw new b("Expected two position balances");let[r,t]=e;return invariant(r!==void 0,"Expected YES position balance"),invariant(t!==void 0,"Expected NO position balance"),r<t?r:t}var NE=z$1.object({address:z$1.string()}),x0=o(h$1,g,c,b,a);async function C0(e,r){let t=l(r,NE);return unwrap(e.gamma.get("/public-profile",{params:h(t,T())}).andThen(f(PublicProfileSchema)).orElse(o=>o instanceof g&&o.status===404?ok(null):err(o)))}var Sn=class extends PolymarketError{name="RfqQuoteRejectedError";code;errorId;rfqId;constructor(r,t){super(r,t),this.code=t.code,this.errorId=t.errorId,this.rfqId=t.rfqId;}},M0=o(e,Sn,n,i,c,a),hn=class extends PolymarketError{name="RfqCancelQuoteRejectedError";code;errorId;rfqId;quoteId;constructor(r,t){super(r,t),this.code=t.code,this.errorId=t.errorId,this.rfqId=t.rfqId,this.quoteId=t.quoteId;}},B0=o(e,hn,i,c),Tn=class extends PolymarketError{name="RfqConfirmationRejectedError";code;errorId;rfqId;quoteId;constructor(r,t){super(r,t),this.code=t.code,this.errorId=t.errorId,this.rfqId=t.rfqId,this.quoteId=t.quoteId;}},U0=o(e,Tn,i,c),D0=o(e,c,a);async function _0(e){return Wr(e),e.webSockets.rfqQuoter.connect()}var Cn="/v1/builder/rfq/requests",QE=3e4,ZE=3e4,JE=3e4,XE=500,eS=3e4,rS=1e3,tS="0x0000000000000000000000000000000000000000000000000000000000000000",De=class extends PolymarketError{name="RfqRequestRejectedError";status;code;constructor(r,t){super(r,t),this.status=t.status,this.code=t.code;}};function In(e){return e instanceof g?new De(e.message,{cause:e,code:dc(e.code),status:e.status}):e}var oS=new Set(Object.values(RfqRejectionCode));function dc(e){return e!==void 0&&oS.has(e)?e:RfqRejectionCode.RequestFailed}function uc(e){if(!e.hasBuilderApiKey)throw new a("Combo RFQ requests require a Builder API Key in the client configuration, via builderApiKey(...) or remoteBuilderSigning(...).")}var nc=z$1.array(z$1.string().regex(/^\d+$/,"Leg position IDs must be numeric strings.").transform(e=>toPositionId(BigInt(e).toString()))).min(2,"Combo requests require at least 2 legs.").max(50,"Combo requests allow at most 50 legs.").refine(e=>new Set(e).size===e.length,"Leg position IDs must not contain duplicates.").transform(e=>[...e].sort((r,t)=>{let o=BigInt(r),n=BigInt(t);return o<n?-1:o>n?1:0})),Bt=z$1.union([z$1.number(),z$1.string()]).transform((e,r)=>{let t=/^(\d+)(?:\.(\d*))?$/.exec(String(e));if(t===null)return r.addIssue({code:"custom",message:"Value must be a valid decimal."}),z$1.NEVER;let[,o="",n=""]=t;if(n.length>6)return r.addIssue({code:"custom",message:"Value must have at most 6 decimal places."}),z$1.NEVER;let s=nS(o,n);return s<=0n?(r.addIssue({code:"custom",message:"Value must be greater than 0."}),z$1.NEVER):s.toString()});function nS(e,r){return BigInt(e)*1000000n+BigInt(r.padEnd(6,"0"))}var sS=z$1.discriminatedUnion("direction",[z$1.object({amount:Bt,direction:z$1.literal(OrderSide.BUY),legPositionIds:nc,side:z$1.literal(RfqSide.Yes).optional()}),z$1.object({direction:z$1.literal(OrderSide.SELL),legPositionIds:nc,side:z$1.literal(RfqSide.Yes).optional(),size:Bt})]),z0=o(h$1,De,c,b,a);async function W0(e,r){Wr(e);let t=l(r,sS);uc(e);let o=Tr(e.account),n={direction:t.direction===OrderSide.BUY?RfqDirection.Buy:RfqDirection.Sell,leg_position_ids:t.legPositionIds,maker_address:o.maker,requested_size:t.direction===OrderSide.BUY?{unit:RfqRequestedSizeUnit.Notional,value_e6:t.amount}:{unit:RfqRequestedSizeUnit.Shares,value_e6:t.size},side:RfqSide.Yes,signature_type:o.signatureType,signer_address:o.signer},s=await unwrap(e.builderGateway.post(Cn,{json:n,timeout:QE}).andThen(f(BuilderRfqCreateResponseSchema)).mapErr(In));if("quote"in s){aS(s,n);let a=s.request.direction===RfqDirection.Buy?OrderSide.BUY:OrderSide.SELL,y={blendedPrice:s.quote.blendedPrice,builderCode:s.builderCode,expiresAt:s.expiresAt,makerAmount:s.quote.makerAmount,positionId:s.request.yesPositionId,quoteId:s.quote.quoteId,rfqId:s.rfqId,takerAmount:s.quote.takerAmount,totalRequired:s.quote.totalRequired};if(a===OrderSide.SELL){if(s.quote.netReceive===void 0)throw new b(`SELL quote for RFQ ${s.rfqId} omitted net sell proceeds.`);return {quote:{...y,direction:a,netReceive:s.quote.netReceive},rfqId:s.rfqId}}return {quote:{...y,direction:a},rfqId:s.rfqId}}return iS(s)}function aS(e,r){let t=e.request,o=[];if(t.rfqId!==e.rfqId&&o.push("rfq_id"),t.direction!==r.direction&&o.push("direction"),t.side!==r.side&&o.push("side"),(t.legPositionIds.length!==r.leg_position_ids.length||t.legPositionIds.some((n,s)=>n!==r.leg_position_ids[s]))&&o.push("leg_position_ids"),(t.requestedSize.unit!==r.requested_size.unit||t.requestedSize.valueE6!==r.requested_size.value_e6)&&o.push("requested_size"),o.length>0)throw new b(`Builder RFQ response did not echo the submitted ${o.join(", ")}.`)}function iS(e){switch(e.error?.code){case RfqKnownErrorCode.NoQuotes:return {quote:null,reason:ComboQuoteUnavailableReason.NoQuotes,rfqId:e.rfqId};case RfqKnownErrorCode.SizeTooLarge:return {quote:null,reason:ComboQuoteUnavailableReason.SizeTooLarge,rfqId:e.rfqId};default:throw new De(e.error?.message??"The combo quote request failed.",{code:dc(e.error?.code),status:200,...e.error===void 0?{}:{cause:e.error}})}}var pS=OrderSideSchema,cS=z$1.object({blendedPrice:z$1.string(),builderCode:z$1.string().regex(/^0x[0-9a-fA-F]{64}$/,"builderCode must be a 32-byte hex string.").transform(toBuilderCode),direction:pS,expiresAt:z$1.number().int().nonnegative(),makerAmount:Bt.transform(toBaseUnits),netReceive:z$1.string().optional(),positionId:z$1.string().regex(/^\d+$/,"positionId must be a numeric string.").transform(toPositionId),quoteId:z$1.string().min(1).transform(toRfqQuoteId),rfqId:z$1.string().min(1).transform(toRfqId),takerAmount:Bt.transform(toBaseUnits),totalRequired:z$1.string()}),j0=o(k$1,h$1,De,n,i,c,b,a);async function H0(e,r){Wr(e);let t=l(r,cS);uc(e);let o=ni({chainId:e.environment.chainId,exchange:e.environment.contracts.exchangeV3}),n=lS(e,t),s=await yS(e,o,n),a={quote_id:t.quoteId,signed_order:s};function y(){return e.builderGateway.post(`${Cn}/${encodeURIComponent(t.rfqId)}/accept`,{json:a,timeout:ZE}).andThen(f(BuilderRfqStatusResponseSchema))}let P=await y();if(P.isErr()&&(P.error instanceof c||P.error instanceof b)&&(P=await y()),P.isErr()){let w=dS(t.rfqId,P.error);if(w!==void 0)return w;throw In(P.error)}let C=P.value,I=P.value.takerOrderHash,B=Date.now()+JE;for(;C.status===RfqStatus.AwaitingMakerConfirmation;){if(Date.now()>=B)throw new i(`Timed out waiting for the acceptance outcome of RFQ ${t.rfqId}.`);await delay(XE),C=await lc(e,{rfqId:t.rfqId});}return C.status===RfqStatus.Failed||C.status===RfqStatus.Expired||C.status===RfqStatus.Canceled?{reason:uS(C.status,C.error?.code),rfqId:C.rfqId,status:"failed",...C.error===void 0?{}:{error:C.error}}:{rfqId:C.rfqId,status:"executing",...I===void 0?{}:{takerOrderHash:I}}}function dS(e,r){if(r instanceof g&&r.code===RfqKnownErrorCode.ExpiredRfq)return {error:{code:RfqKnownErrorCode.ExpiredRfq,message:r.message},reason:ComboAcceptFailureReason.AcceptanceWindowExpired,rfqId:e,status:"failed"}}function uS(e,r){return e===RfqStatus.Expired||r===RfqKnownErrorCode.ExpiredRfq?ComboAcceptFailureReason.AcceptanceWindowExpired:r===RfqKnownErrorCode.MakerDeclined?ComboAcceptFailureReason.MakerDeclined:ComboAcceptFailureReason.ExecutionFailed}function lS(e,r){let t=Tr(e.account);return {builder:r.builderCode,maker:t.maker,makerAmount:r.makerAmount,metadata:tS,salt:mS().toString(),side:Mo(r.direction),signatureType:t.signatureType,signer:t.signer,takerAmount:r.takerAmount,timestamp:Math.floor(Date.now()/1e3).toString(),tokenId:r.positionId}}function mS(){let e=new Uint8Array(8);return globalThis.crypto.getRandomValues(e),BigInt(`0x${Array.from(e,r=>r.toString(16).padStart(2,"0")).join("")}`)}async function yS(e,r,t){let o;try{o=await e.signer.signTypedData(St({domain:r,order:t}));}catch(n$1){throw n$1 instanceof k$1?n$1:n.fromError(n$1,"Could not sign the combo quote acceptance order.")}return {...t,signature:ht({domain:r,order:t,signature:o})}}var fS=z$1.object({pollingIntervalMs:z$1.number().int().positive().optional(),rfqId:z$1.string().min(1).transform(toRfqId),timeoutMs:z$1.number().int().positive().optional()}),N0=o(h$1,De,i,c,b,a);async function K0(e,r){Wr(e);let t=l(r,fS),o=t.timeoutMs??eS,n=t.pollingIntervalMs??rS,s=Date.now()+o;for(;;){let a=await lc(e,{rfqId:t.rfqId});if(a.status===RfqStatus.Filled||a.status===RfqExecutionStatus.Confirmed){if(a.txHash===void 0)throw new b(`RFQ ${a.rfqId} reached ${a.status} without a transaction hash.`);return {rfqId:a.rfqId,status:RfqStatus.Filled,txHash:a.txHash}}if(a.status===RfqStatus.Failed||a.status===RfqStatus.Expired||a.status===RfqStatus.Canceled)return {rfqId:a.rfqId,status:a.status,...a.error===void 0?{}:{error:a.error}};if(Date.now()>=s)throw new i(`Timed out after ${o}ms waiting for RFQ ${t.rfqId} to reach a terminal state.`);await delay(n);}}var PS=z$1.object({rfqId:z$1.string().min(1).transform(toRfqId)}),G0=o(h$1,De,c,b,a);function lc(e,r){Wr(e);let t=l(r,PS);return unwrap(e.builderGateway.get(`${Cn}/${encodeURIComponent(t.rfqId)}`).andThen(f(BuilderRfqStatusResponseSchema)).mapErr(In))}function Wr(e){if(e.account.signerType==="SESSION_KEY")throw new a("Combos is not supported with Session Keys")}var mc=(y=>(y.Volume="volume",y.Volume24Hr="volume_24hr",y.Liquidity="liquidity",y.Competitive="competitive",y.ClosedTime="closed_time",y.StartDate="start_date",y.EndDate="end_date",y))(mc||{}),ES=z$1.object({q:z$1.string().trim().min(1),ascending:z$1.boolean().optional(),cache:z$1.boolean().optional(),cursor:PaginationCursorSchema.optional(),eventsStatus:z$1.string().min(1).optional(),eventsTag:z$1.array(z$1.string()).optional(),excludeTagIds:z$1.array(z$1.number().int()).optional(),keepClosedMarkets:z$1.number().int().optional(),optimized:z$1.boolean().optional(),pageSize:k.default(10),presets:z$1.array(z$1.string()).optional(),recurrence:z$1.enum(["daily","weekly","monthly"]).optional(),searchProfiles:z$1.boolean().optional(),searchTags:z$1.boolean().optional(),sort:z$1.enum(mc).optional()}),mL=o(h$1,g,c,b,a);function yL(e,r){let{cursor:t,pageSize:o,...n}=l(r,ES);return x(s=>{let a=te(s,o);return e.gamma.get("/public-search",{params:h({...n,limitPerType:a.pageSize,page:a.offset},T({excludeTagIds:"exclude_tag_id"}))}).andThen(f(PublicSearchResponseSchema)).map(y=>({items:SS(y),hasMore:y.pagination?.hasMore??false,totalCount:y.pagination?.totalResults??void 0,nextCursor:y.pagination?.hasMore?J({offset:a.offset+1,pageSize:a.pageSize}):void 0}))},t??J({offset:1,pageSize:o}),{events:[],profiles:[],tags:[]})}function SS(e){return {events:e.events??[],profiles:e.profiles??[],tags:e.tags??[]}}var IS=z$1.object({ascending:z$1.boolean().optional(),closed:z$1.boolean().optional(),cursor:PaginationCursorSchema.optional(),excludeEvents:z$1.boolean().optional(),locale:z$1.string().optional(),order:z$1.string().optional(),pageSize:k.max(50).default(20),recurrence:z$1.enum(["daily","weekly","monthly"]).optional(),slug:z$1.array(z$1.string()).optional()}),bS=z$1.object({id:z$1.string(),locale:z$1.string().optional()}),IL=o(h$1,g,c,b,a);function bL(e,r={}){let{cursor:t,pageSize:o,...n}=l(r,IS);return x(s=>{let a=te(s,o);return e.gamma.get("/series",{params:h({...n,limit:a.pageSize,offset:a.offset},T())}).andThen(f(ListSeriesResponseSchema)).map(y=>{let P=y.length>=a.pageSize;return {items:y,hasMore:P,nextCursor:P?J({offset:a.offset+a.pageSize,pageSize:a.pageSize}):void 0}})},t)}var vL=o(h$1,g,c,b,a);async function qL(e,r){let t=l(r,bS);return unwrap(e.gamma.get(`series/${t.id}`,{params:h({locale:t.locale},T())}).andThen(f(SeriesSchema)))}function vn(e){if(e.kind==="authorization"?e.status===RelayerAuthorizeSessionSignerStatus.FAILED||e.status===RelayerAuthorizeSessionSignerStatus.SUPERSEDED||e.status===RelayerAuthorizeSessionSignerStatus.REPAIR_REQUIRED:e.status===RelayerRevokeSessionSignerStatus.FAILED)throw new j(`Session-key ${e.kind} reached terminal status ${e.status}`)}var GL=o(h$1,g,n,c,b,a);async function gc(e){On(e);let r=await unwrap(e.secureClob.get("/v1/user/session-signers").andThen(f(ActiveSessionSignersResponseSchema)));if(!isSameEvmAddress(r.wallet,e.account.wallet))throw new b(`Session-key response wallet ${r.wallet} does not match authenticated wallet ${e.account.wallet}`);return r.signers.map(t=>({address:expectEvmAddress(t.address.toLowerCase()),scopes:t.scopes,validUntil:t.validUntil}))}var LS=[SessionSignerKnownScope.ALL],FS=4315*60*60,Rc=300*1e3,MS=z$1.object({address:EvmAddressSchema,idempotencyKey:z$1.string().trim().min(1).optional(),scopes:z$1.array(SessionSignerScopeSchema).min(1).default(LS)}).superRefine((e,r)=>{isSameEvmAddress(e.address,ZERO_ADDRESS)&&r.addIssue({code:"custom",message:"Session key address must not be the zero address.",path:["address"]}),e.scopes.includes(SessionSignerKnownScope.ALL)&&e.scopes.some(t=>t!==SessionSignerKnownScope.ALL)&&r.addIssue({code:"custom",message:"Session key scope ALL cannot be combined with another scope.",path:["scopes"]});}).transform(e=>({...e,address:expectEvmAddress(e.address.toLowerCase())})),$L=o(k$1,h$1,g,n,i,j,c,b,a);async function VL(e,r){if(On(e),!e.hasBuilderApiKey)throw new a("Session-key authorization requires builder API-key authentication.");let t=l(r,MS),o=Math.floor(Date.now()/1e3)+FS,n=await z(e.signer)(ir(e,[Rs(e.account.wallet,t.address,BigInt(o))])),s={deadline:n.depositWalletParams.deadline,nonce:n.nonce,scopes:t.scopes,sessionSignerAddress:t.address,signature:n.signature,validUntil:`${o}`,walletAddress:e.account.wallet},a$1=await unwrap(e.relayer.post("/v1/session-signers/authorizations",{headers:{"Idempotency-Key":t.idempotencyKey??globalThis.crypto.randomUUID()},json:s,timeout:Rc}).andThen(f(RelayerAuthorizeSessionSignerResponseSchema)));vn({kind:"authorization",status:a$1.status});let y=await new He(e,a$1).wait();return {sessionKey:await DS(e,{address:t.address,scopes:t.scopes,validUntil:o}),transaction:y}}var BS=z$1.object({address:EvmAddressSchema,idempotencyKey:z$1.string().trim().min(1).optional()}).superRefine((e,r)=>{isSameEvmAddress(e.address,ZERO_ADDRESS)&&r.addIssue({code:"custom",message:"Session key address must not be the zero address.",path:["address"]});}).transform(e=>({...e,address:expectEvmAddress(e.address.toLowerCase())})),YL=o(k$1,h$1,g,n,i,j,c,b,a);async function QL(e,r){if(On(e),!e.supportsGasless)throw new a("Session-key revocation requires API-key authentication that supports gasless transactions.");let t=l(r,BS),o=await z(e.signer)(ir(e,[Es(e.account.wallet,t.address)])),n={deadline:o.depositWalletParams.deadline,nonce:o.nonce,sessionSignerAddress:t.address,signature:o.signature,walletAddress:e.account.wallet},s=await unwrap(e.relayer.post("/v1/session-signers/revocations",{headers:{"Idempotency-Key":t.idempotencyKey??globalThis.crypto.randomUUID()},json:n,timeout:Rc}).andThen(f(RelayerRevokeSessionSignerResponseSchema)));vn({kind:"revocation",status:s.status}),await US(e,t.address);}async function US(e,r){for(let t=0;t<e.environment.relayerMaxPolls;t+=1){if(!(await gc(e)).some(n=>isSameEvmAddress(n.address,r)))return;await delay(e.environment.relayerPollFrequencyMs);}throw new i(`Timed out waiting for session key ${r} to be revoked`)}async function DS(e,r){for(let t=0;t<e.environment.relayerMaxPolls;t+=1){let o=(await gc(e)).find(n=>isSameEvmAddress(n.address,r.address)&&n.validUntil===r.validUntil&&_S(n.scopes,r.scopes));if(o!==void 0)return o;await delay(e.environment.relayerPollFrequencyMs);}throw new i(`Timed out waiting for session key ${r.address} to become active`)}function _S(e,r){let t=new Set(r);return new Set(e).size===t.size&&e.every(o=>t.has(o))}function On(e){if(e.account.walletType!==WalletType.DEPOSIT_WALLET)throw new a("Session keys can only be managed for a Deposit Wallet.");if(e.account.signerType!=="OWNER")throw new a("Session keys can only be managed by the Deposit Wallet owner.")}var tF=o(h$1,g,c,b);async function oF(e){return unwrap(e.gamma.get("/sports").andThen(f(ListSportsMetadataResponseSchema)))}var nF=o(h$1,g,c,b);async function sF(e){return unwrap(e.gamma.get("/sports/market-types").andThen(f(SportsMarketTypesResponseSchema)))}var jS=z$1.string().trim().min(1).max(64).regex(/^[a-zA-Z0-9._:/-]+$/),Sc=z$1.string().max(64).regex(/^[a-z0-9]+usd$/,{error:"Use a canonical lowercase USD pair such as btcusd. Slash-separated symbols and USDT pairs are not supported."}),hc=(t=>(t.Update="update",t.Subscribe="subscribe",t))(hc||{}),HS=z$1.discriminatedUnion("topic",[z$1.strictObject({topic:z$1.literal("prices.crypto"),symbols:z$1.array(Sc).min(1)}),z$1.strictObject({topic:z$1.literal("prices.crypto.twap"),symbols:z$1.array(Sc).min(1)}),z$1.strictObject({topic:z$1.literal("prices.equity"),symbol:jS,types:z$1.array(z$1.enum(hc)).optional()})]);function Tc(e){return l(e,HS)}var PF=o(c,a,g,e),xc=(G=>(G.Market="market",G.User="user",G.Sports="sports",G.Crypto="prices.crypto",G.Twap="prices.crypto.twap",G.Equity="prices.equity",G.Comments="comments",G.LegacyBinance="prices.crypto.binance",G.LegacyChainlink="prices.crypto.chainlink",G.LegacyTwap="prices.crypto.chainlink.twap",G.LegacyEquity="prices.equity.pyth",G.PerpsTrades="perps.trades",G.PerpsBbo="perps.bbo",G.PerpsBook="perps.book",G.PerpsCandles="perps.candles",G.PerpsTickers="perps.tickers",G.PerpsStatistics="perps.statistics",G))(xc||{}),GS=z$1.object({topic:z$1.enum(xc)}),$S=z$1.object({topic:z$1.literal("prices.crypto.chainlink.twap"),windowSeconds:z$1.union([z$1.literal(30),z$1.literal(60)]),symbols:z$1.array(z$1.string()).optional()}),VS=z$1.union([z$1.object({topic:z$1.literal("market"),assetIds:z$1.array(z$1.string()),tokenIds:z$1.never().optional(),customFeatureEnabled:z$1.boolean().optional()}),z$1.object({topic:z$1.literal("market"),assetIds:z$1.never().optional(),tokenIds:z$1.array(z$1.string()),customFeatureEnabled:z$1.boolean().optional()})]);async function gF(e,r){let t=r.map(a$1=>{switch(l(a$1,GS),a$1.topic){case "prices.crypto":case "prices.crypto.twap":case "prices.equity":if(!e.isSecureClient())throw new a("This subscription requires a secure client.");return Tc(a$1);case "prices.crypto.chainlink.twap":l(a$1,$S);break;case "market":l(a$1,VS);break}return a$1}),o=await Promise.allSettled(t.map(async a=>YS(e,a))),n=o.flatMap(a=>a.status==="fulfilled"?[a.value]:[]),s=o.find(a=>a.status==="rejected");if(s?.status==="rejected")throw await Promise.allSettled(n.map(a=>a.close())),s.reason;return QS(n)}function YS(e,r){switch(r.topic){case "market":return e.webSockets.clobMarket.subscribe(r);case "sports":return e.webSockets.sports.subscribe(r);case "prices.crypto":case "prices.crypto.twap":case "prices.equity":if(!e.isSecureClient())throw new a("This subscription requires a secure client.");return e.webSockets.realtime.subscribe(r);case "comments":case "prices.crypto.binance":case "prices.crypto.chainlink":case "prices.crypto.chainlink.twap":case "prices.equity.pyth":return e.webSockets.rtds.subscribe(r);case "perps.trades":case "perps.bbo":case "perps.book":case "perps.candles":case "perps.tickers":case "perps.statistics":return e.webSockets.perpsSubscriptions.subscribe(r);case "user":return invariant(e.isSecureClient(),"A 'user' subscription requires a secure client instance."),e.webSockets.clobUser.subscribe(r)}}function QS(e){let r;async function t(){r===void 0&&(r=Promise.all(e.map(n=>n.close())).then(()=>{})),await r;}let o=KS(...e);return {close:t,[Symbol.asyncIterator](){return o[Symbol.asyncIterator]()}}}var XS=z$1.object({ascending:z$1.boolean().optional(),cursor:PaginationCursorSchema.optional(),includeTemplate:z$1.boolean().optional(),isCarousel:z$1.boolean().optional(),locale:z$1.string().optional(),order:z$1.string().optional(),pageSize:k.max(100).default(20)}),eh=z$1.union([z$1.object({id:z$1.string(),includeTemplate:z$1.boolean().optional(),locale:z$1.string().optional()}),z$1.object({slug:z$1.string(),locale:z$1.string().optional()})]),rh=z$1.object({id:z$1.string(),omitEmpty:z$1.boolean().optional(),status:z$1.enum(["active","closed","all"]).optional()}),th=z$1.object({slug:z$1.string()}),oh=z$1.object({id:z$1.string(),locale:z$1.string().optional(),omitEmpty:z$1.boolean().optional(),status:z$1.enum(["active","closed","all"]).optional()}),nh=z$1.object({locale:z$1.string().optional(),slug:z$1.string(),omitEmpty:z$1.boolean().optional(),status:z$1.enum(["active","closed","all"]).optional()}),qF=o(h$1,g,c,b,a);function kF(e,r={}){let{cursor:t,pageSize:o,...n}=l(r,XS);return x(s=>{let a=te(s,o);return e.gamma.get("/tags",{params:h({...n,limit:a.pageSize,offset:a.offset},T())}).andThen(f(ListTagsResponseSchema)).map(y=>{let P=y.length>=a.pageSize;return {items:y,hasMore:P,nextCursor:P?J({offset:a.offset+a.pageSize,pageSize:a.pageSize}):void 0}})},t)}var AF=o(h$1,g,c,b,a);async function OF(e,r){let t=l(r,eh);return "id"in t?unwrap(e.gamma.get(`tags/${t.id}`,{params:h({includeTemplate:t.includeTemplate,locale:t.locale},T())}).andThen(f(TagSchema))):unwrap(e.gamma.get(`tags/slug/${t.slug}`,{params:h({locale:t.locale},T())}).andThen(f(TagSchema)))}var wF=o(h$1,g,c,b,a);async function LF(e,r){if("id"in r){let o=l(r,rh);return unwrap(e.gamma.get(`tags/${o.id}/related-tags`,{params:h({omitEmpty:o.omitEmpty,status:o.status},T())}).andThen(f(ListRelatedTagsResponseSchema)))}let t=l(r,th);return unwrap(e.gamma.get(`tags/slug/${t.slug}/related-tags`).andThen(f(ListRelatedTagsResponseSchema)))}var FF=o(h$1,g,c,b,a);async function MF(e,r){if("id"in r){let o=l(r,oh);return unwrap(e.gamma.get(`tags/${o.id}/related-tags/tags`,{params:h({locale:o.locale,omitEmpty:o.omitEmpty,status:o.status},T())}).andThen(f(ListRelatedTagResourcesResponseSchema)))}let t=l(r,nh);return unwrap(e.gamma.get(`tags/slug/${t.slug}/related-tags/tags`,{params:h({locale:t.locale,omitEmpty:t.omitEmpty,status:t.status},T())}).andThen(f(ListRelatedTagResourcesResponseSchema)))}var ih=z$1.object({abbreviation:z$1.array(z$1.string()).optional(),ascending:z$1.boolean().optional(),cursor:PaginationCursorSchema.optional(),league:z$1.array(z$1.string()).optional(),name:z$1.array(z$1.string()).optional(),order:z$1.string().optional(),pageSize:k.max(100).default(20),providerId:z$1.array(z$1.number().int()).optional()}),KF=o(h$1,g,c,b,a);function GF(e,r={}){let{cursor:t,pageSize:o,...n}=l(r,ih);return x(s=>{let a=te(s,o);return e.gamma.get("/teams",{params:h({...n,limit:a.pageSize,offset:a.offset},T({providerId:"provider_id"}))}).andThen(f(ListTeamsResponseSchema)).map(y=>{let P=y.length>=a.pageSize;return {items:y,hasMore:P,nextCursor:P?J({offset:a.offset+a.pageSize,pageSize:a.pageSize}):void 0}})},t)}var ch=z$1.object({amount:z$1.bigint(),metadata:V.optional(),recipientAddress:EvmAddressSchema,tokenAddress:EvmAddressSchema}),oM=o(a);async function dh(e,r){let t=l(r,ch);return async function*(){return e.account.walletType===WalletType.EOA?N(yield uh(K(e.environment.chainId,$t(t.tokenAddress,t.recipientAddress,t.amount)))):yield*await Y(e,{calls:[$t(t.tokenAddress,t.recipientAddress,t.amount)],metadata:t.metadata??`Transfer ${t.amount} of ${t.tokenAddress} to ${t.recipientAddress}`})}.call(null)}var nM=o(k$1,h$1,g,n,c,b,a);function sM(e,r){return dh(e,r).then(z(e.signer))}function uh(e){return {kind:"sendErc20TransferTransaction",request:e}}
2
+ export{sT as $,Gx as $a,uI as $b,vv as $c,Ii as $d,ex as A,N as Aa,jC as Ab,Sb as Ac,ht as Ad,QO as Ae,d0 as Af,sF as Ag,Yt as B,ux as Ba,HC as Bb,hb as Bc,ni as Bd,ZO as Be,wE as Bf,PF as Bg,rx as C,bs as Ca,NC as Cb,Ek as Cd,JO as Ce,Jp as Cf,gF as Cg,Jr as D,bx as Da,KC as Db,Sk as Dd,XO as De,u0 as Df,qF as Dg,tx as E,eo as Ea,GC as Eb,Mo as Ed,ew as Ee,l0 as Ef,kF as Eg,Qt as F,vx as Fa,$C as Fb,zo as Fd,KR as Fe,FE as Ff,AF as Fg,Cs as G,qx as Ga,VC as Gb,Db as Gc,Sf as Gd,rw as Ge,m0 as Gf,OF as Gg,Is as H,V as Ha,YC as Hb,_b as Hc,Wo as Hd,tw as He,y0 as Hf,wF as Hg,l as I,kx as Ia,Vs as Ib,zb as Ic,hf as Id,fw as Ie,x0 as If,LF as Ig,Un as J,Ax as Ja,QC as Jb,Wb as Jc,jo as Jd,Pw as Je,C0 as Jf,FF as Jg,Kn as K,Uu as Ka,Ys as Kb,jb as Kc,Dk as Kd,gw as Ke,Sn as Kf,MF as Kg,Ah as L,Ox as La,ZC as Lb,Hb as Lc,_k as Ld,Rw as Le,M0 as Lf,KF as Lg,Tr as M,Y as Ma,Qs as Mb,Nb as Mc,zk as Md,Ew as Me,hn as Mf,GF as Mg,Gn as N,ro as Na,JC as Nb,Kb as Nc,Wk as Nd,Sw as Ne,B0 as Nf,oM as Ng,$n as O,to as Oa,XC as Ob,Gb as Oc,Yk as Od,hw as Oe,Tn as Of,dh as Og,Vh as P,ir as Pa,eI as Pb,$b as Pc,Qk as Pd,Tw as Pe,U0 as Pf,nM as Pg,Yh as Q,oo as Qa,rI as Qb,fA as Qd,xw as Qe,D0 as Qf,sM as Qg,Qh as R,no as Ra,tI as Rb,Of as Rd,Cw as Re,_0 as Rf,Zh as S,so as Sa,ot as Sb,PA as Sd,Iw as Se,De as Sf,Jh as T,wx as Ta,oI as Tb,gA as Td,bw as Te,z0 as Tf,Xh as U,He as Ua,nI as Ub,pv as Uc,RA as Ud,vw as Ue,W0 as Uf,eT as V,Hx as Va,sI as Vb,cv as Vc,wf as Vd,qw as Ve,j0 as Vf,Jn as W,Yu as Wa,aI as Wb,EA as Wd,H0 as Wf,rT as X,Nx as Xa,iI as Xb,Cv as Xc,SA as Xd,N0 as Xf,tT as Y,Ms as Ya,pI as Yb,da as Yc,Tt as Yd,K0 as Yf,oT as Z,Kx as Za,cI as Zb,Iv as Zc,xi as Zd,G0 as Zf,nT as _,Zu as _a,dI as _b,bv as _c,Ci as _d,lc as _f,re as a,Ht as aa,Bs as ab,lI as ac,qv as ad,xt as ae,$T as b,aT as ba,$x as bb,mI as bc,kv as bd,bi as be,Bp as bf,Vr as c,es as ca,Vx as cb,yI as cc,Av as cd,It as ce,Qw as cf,ls as d,iT as da,Yx as db,fI as dc,Ov as dd,bt as de,Dp as df,ms as e,pT as ea,Xu as eb,PI as ec,wv as ed,dp as ee,Zw as ef,Yr as f,cT as fa,Qx as fb,qI as fc,Lv as fd,mp as fe,zp as ff,ys as g,dT as ga,Zx as gb,kI as gc,Fv as gd,fp as ge,qE as gf,fs as h,uT as ha,nC as hb,AI as hc,Mv as hd,xp as he,Wp as hf,Ps as i,lT as ia,nl as ib,tm as ic,Bv as id,LO as ie,Jw as if,gs as j,mT as ja,sC as jb,OI as jc,Yv as jd,FO as je,Xw as jf,mc as jg,Qr as k,yT as ka,sl as kb,wI as kc,Qv as kd,MO as ke,e0 as kf,mL as kg,Zr as l,fT as la,aC as lb,Zv as ld,BO as le,r0 as lf,yL as lg,VT as m,PT as ma,iC as mb,KI as mc,Jv as md,UO as me,t0 as mf,IL as mg,$t as n,gT as na,pC as nb,GI as nc,Xv as nd,uR as ne,jp as nf,bL as ng,Rs as o,RT as oa,cC as ob,$I as oc,eq as od,DO as oe,o0 as of,vL as og,Es as p,wT as pa,dC as pb,VI as pc,rq as pd,_O as pe,Np as pf,qL as pg,YT as q,LT as qa,uC as qb,YI as qc,tq as qd,zO as qe,n0 as qf,Ss as r,FT as ra,lC as rb,QI as rc,yq as rd,WO as re,Gp as rf,GL as rg,QT as s,MT as sa,mC as sb,lb as sc,fq as sd,jO as se,AE as sf,gc as sg,hs as t,BT as ta,yC as tb,mb as tc,qy as td,HO as te,$p as tf,$L as tg,ZT as u,UT as ua,fC as ub,yb as uc,fo as ud,NO as ue,s0 as uf,VL as ug,Ts as v,PC as vb,fb as vc,Iq as vd,KO as ve,a0 as vf,YL as vg,JT as w,gC as wb,Pb as wc,bq as wd,GO as we,i0 as wf,QL as wg,xs as x,qC as xb,gb as xc,mt as xd,$O as xe,p0 as xf,tF as xg,XT as y,kC as yb,Rb as yc,vq as yd,VO as ye,c0 as yf,oF as yg,Vt as z,ax as za,WC as zb,Eb as zc,St as zd,YO as ze,Vp as zf,nF as zg};//# sourceMappingURL=chunk-WZQAMVAC.js.map
3
+ //# sourceMappingURL=chunk-WZQAMVAC.js.map