@polymarket/client 0.1.0-beta.12 → 0.1.0-beta.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,10 +1,10 @@
1
- import { aR as RateLimitError, aT as RequestRejectedError, bG as TransportError, bJ as UnexpectedResponseError, bz as SigningError, B as BaseClient, h as BaseSecureClient } from '../types-BiMOyijM.js';
2
- export { e as ApproveErc1155ForAllError, f as ApproveErc20Error, C as CancelAllError, j as CancelMarketOrdersError, c2 as CancelMarketOrdersRequest, k as CancelOrderError, c3 as CancelOrderRequest, l as CancelOrdersError, c4 as CancelOrdersRequest, c5 as CancelPerpsOrderRequest, c6 as CancelPerpsOrdersRequest, c7 as CommentsEventType, c8 as CommentsSubscription, c9 as CreatePerpsSessionRequest, ca as CryptoPricesEventType, cb as CryptoPricesSubscription, cc as DeployDepositWalletError, cd as DepositToPerpsError, ce as DepositToPerpsRequest, cf as DeprecatedTransactionHandle, t as DownloadAccountingSnapshotError, cg as DownloadAccountingSnapshotRequest, u as DropNotificationsError, ch as DropNotificationsRequest, ci as EquityPricesEventType, cj as EquityPricesSubscription, ck as Erc1155ApprovalForAllWorkflow, cl as Erc1155ApprovalForAllWorkflowRequest, cm as Erc20ApprovalWorkflow, cn as Erc20ApprovalWorkflowRequest, co as Erc20TransferWorkflow, cp as Erc20TransferWorkflowRequest, cq as EstimateMarketBuyPriceRequest, x as EstimateMarketPriceError, cr as EstimateMarketPriceRequest, cs as EstimateMarketSellPriceRequest, ct as EventForSubscriptionSpec, cu as EventForSubscriptionSpecs, cv as FetchBalanceAllowanceError, cw as FetchBalanceAllowanceRequest, cx as FetchBuilderFeeRatesError, cy as FetchBuilderFeeRatesRequest, F as FetchClosedOnlyModeError, y as FetchCommentsByIdError, cz as FetchCommentsByIdRequest, z as FetchEventError, G as FetchEventLiveVolumeError, cA as FetchEventLiveVolumeRequest, cB as FetchEventRequest, H as FetchEventTagsError, cC as FetchEventTagsRequest, cD as FetchExecuteParamsError, cE as FetchExecuteParamsRequest, cF as FetchGaslessTransactionRequest, I as FetchLastTradePriceError, cG as FetchLastTradePriceRequest, J as FetchLastTradePricesError, cH as FetchLastTradePricesRequest, K as FetchMarketError, cI as FetchMarketInfoError, cJ as FetchMarketInfoRequest, cK as FetchMarketRequest, L as FetchMarketTagsError, cL as FetchMarketTagsRequest, M as FetchMidpointError, cM as FetchMidpointRequest, N as FetchMidpointsError, cN as FetchMidpointsRequest, cO as FetchNegRiskError, cP as FetchNegRiskRequest, O as FetchNotificationsError, P as FetchOrderBookError, cQ as FetchOrderBookRequest, Q as FetchOrderBooksError, cR as FetchOrderBooksRequest, R as FetchOrderError, cS as FetchOrderRequest, V as FetchOrderScoringError, cT as FetchOrderScoringRequest, W as FetchOrdersScoringError, cU as FetchOrdersScoringRequest, cV as FetchPerpsAccountConfigRequest, cW as FetchPerpsBookError, cX as FetchPerpsBookRequest, cY as FetchPerpsFeesError, cZ as FetchPerpsInstrumentsError, c_ as FetchPerpsInstrumentsRequest, c$ as FetchPerpsOpenOrdersRequest, d0 as FetchPerpsOrdersRequest, d1 as FetchPerpsTickerError, d2 as FetchPerpsTickerRequest, d3 as FetchPerpsTickersError, d4 as FetchPerpsTickersRequest, X as FetchPortfolioValueError, d5 as FetchPortfolioValueRequest, Y as FetchPriceError, Z as FetchPriceHistoryError, d6 as FetchPriceHistoryRequest, d7 as FetchPriceRequest, _ as FetchPricesError, d8 as FetchPricesRequest, $ as FetchPublicProfileError, d9 as FetchPublicProfileRequest, a0 as FetchRelatedTagResourcesError, da as FetchRelatedTagResourcesRequest, a1 as FetchRelatedTagsError, db as FetchRelatedTagsRequest, a2 as FetchRewardPercentagesError, a3 as FetchSeriesError, dc as FetchSeriesRequest, a4 as FetchSpreadError, dd as FetchSpreadRequest, a5 as FetchSpreadsError, de as FetchSpreadsRequest, a6 as FetchTagError, df as FetchTagRequest, dg as FetchTickSizeError, dh as FetchTickSizeRequest, a7 as FetchTotalEarningsForUserForDayError, di as FetchTotalEarningsForUserForDayRequest, a8 as FetchTradedMarketCountError, dj as FetchTradedMarketCountRequest, dk as GaslessTransactionMetadataSchema, dl as GaslessWorkflow, dm as GaslessWorkflowRequest, dn as IsWalletDeployedError, dp as IsWalletDeployedRequest, aa as ListAccountTradesError, dq as ListAccountTradesRequest, ab as ListActivityError, dr as ListActivityRequest, ac as ListBuilderLeaderboardError, ds as ListBuilderLeaderboardRequest, ad as ListBuilderTradesError, dt as ListBuilderTradesRequest, ae as ListBuilderVolumeError, du as ListBuilderVolumeRequest, af as ListClosedPositionsError, dv as ListClosedPositionsRequest, ag as ListComboMarketsError, dw as ListComboMarketsRequest, ah as ListComboPositionsError, dx as ListComboPositionsRequest, ai as ListCommentsByUserAddressError, dy as ListCommentsByUserAddressRequest, aj as ListCommentsError, dz as ListCommentsRequest, ak as ListCurrentRewardsError, dA as ListCurrentRewardsRequest, al as ListEventsError, dB as ListEventsRequest, am as ListMarketHoldersError, dC as ListMarketHoldersRequest, an as ListMarketPositionsError, dD as ListMarketPositionsRequest, ao as ListMarketRewardsError, dE as ListMarketRewardsRequest, ap as ListMarketsError, dF as ListMarketsRequest, aq as ListOpenInterestError, dG as ListOpenInterestRequest, ar as ListOpenOrdersError, dH as ListOpenOrdersRequest, dI as ListPerpsCandlesError, dJ as ListPerpsCandlesRequest, dK as ListPerpsDepositsRequest, dL as ListPerpsEquityHistoryRequest, dM as ListPerpsFillsRequest, dN as ListPerpsFundingHistoryError, dO as ListPerpsFundingHistoryRequest, dP as ListPerpsFundingPaymentsRequest, dQ as ListPerpsPnlHistoryRequest, dR as ListPerpsTradesError, dS as ListPerpsTradesRequest, dT as ListPerpsWithdrawalsRequest, as as ListPositionsError, dU as ListPositionsRequest, at as ListSeriesError, dV as ListSeriesRequest, au as ListTagsError, dW as ListTagsRequest, av as ListTeamsError, dX as ListTeamsRequest, aw as ListTraderLeaderboardError, dY as ListTraderLeaderboardRequest, ax as ListTradesError, dZ as ListTradesRequest, ay as ListUserEarningsAndMarketsConfigError, d_ as ListUserEarningsAndMarketsConfigRequest, az as ListUserEarningsForDayError, d$ as ListUserEarningsForDayRequest, e0 as MarketEventType, e1 as MarketSubscription, e2 as MergeComboPositionError, e3 as MergeMarketPositionError, aA as MergePositionsError, e4 as MergePositionsWorkflow, e5 as MergePositionsWorkflowRequest, e6 as OpenPerpsSessionError, e7 as OpenPerpsSessionRequest, aB as OpenRfqSessionError, e8 as OrderDraft, e9 as OrderPostingWorkflow, ea as OrderWorkflow, eb as OrderWorkflowRequest, ec as PerpsBboSubscription, ed as PerpsBookDepth, ee as PerpsBookSubscription, ef as PerpsCandlesSubscription, eg as PerpsDepositWorkflow, eh as PerpsDepositWorkflowRequest, ei as PerpsMarketDataEventType, ej as PerpsMarketDataSubscription, ek as PerpsOrderRequest, el as PerpsPlaceFokOrderRequest, em as PerpsPlaceGtcOrderRequest, en as PerpsPlaceIocOrderRequest, eo as PerpsPlacedTpSlOrder, ep as PerpsPlacedTpSlOrders, eq as PerpsPositionTpSlTrigger, aH as PerpsSession, er as PerpsStatisticsSubscription, es as PerpsStreamingCandleInterval, et as PerpsTickersSubscription, eu as PerpsTpSlTrigger, ev as PerpsTradesSubscription, ew as PlacePerpsOrderRequest, ex as PlacePerpsOrderResult, ey as PlacePerpsOrderWithTpSlRequest, ez as PlacePerpsOrderWithTpSlResult, eA as PlacePerpsPositionTpSlRequest, eB as PlacePerpsPositionTpSlResult, aI as PostOrderError, aJ as PostOrdersError, eC as PostOrdersRequest, eD as PostPerpsOrdersRequest, eE as PrepareErc1155ApprovalForAllError, eF as PrepareErc1155ApprovalForAllRequest, eG as PrepareErc20ApprovalError, eH as PrepareErc20ApprovalRequest, eI as PrepareErc20TransferError, eJ as PrepareErc20TransferRequest, eK as PrepareGaslessTransactionError, eL as PrepareGaslessTransactionRequest, eM as PrepareLimitOrderRequest, eN as PrepareMarketBuyOrderRequest, eO as PrepareMarketOrderRequest, eP as PrepareMarketSellOrderRequest, eQ as PrepareMergeComboPositionError, eR as PrepareMergeComboPositionRequest, eS as PrepareMergeMarketPositionError, eT as PrepareMergeMarketPositionRequest, eU as PrepareMergePositionsError, eV as PrepareMergePositionsRequest, eW as PreparePerpsDepositError, eX as PrepareRedeemComboPositionError, eY as PrepareRedeemComboPositionRequest, eZ as PrepareRedeemMarketPositionsByConditionIdRequest, e_ as PrepareRedeemMarketPositionsByMarketIdRequest, e$ as PrepareRedeemMarketPositionsError, f0 as PrepareRedeemMarketPositionsRequest, f1 as PrepareRedeemPositionsError, f2 as PrepareRedeemPositionsRequest, f3 as PrepareSplitComboPositionError, f4 as PrepareSplitComboPositionRequest, f5 as PrepareSplitMarketPositionError, f6 as PrepareSplitMarketPositionRequest, f7 as PrepareSplitPositionError, f8 as PrepareSplitPositionRequest, f9 as PrepareTradingApprovalsError, fa as PublicRealtimeEvent, fb as PublicRealtimeTopic, fc as PublicSubscriptionSpec, aS as RedeemPositionsError, fd as RedeemPositionsWorkflow, fe as RedeemPositionsWorkflowRequest, ff as ResolveConditionByTokenError, fg as ResolveConditionByTokenRequest, fh as ResumePerpsSessionRequest, fi as RevokePerpsCredentialsError, fj as RevokePerpsCredentialsRequest, aW as RfqCancelQuoteAck, aX as RfqCancelQuoteError, aY as RfqCancelQuoteRejectedError, aZ as RfqCancelQuoteRejectedErrorOptions, a_ as RfqConfirmationAck, a$ as RfqConfirmationError, b0 as RfqConfirmationRejectedError, fk as RfqConfirmationRejectedErrorOptions, b1 as RfqConfirmationRequestEvent, b3 as RfqEvent, fl as RfqExecutionUpdateEvent, b4 as RfqQuoteError, b5 as RfqQuoteReference, b6 as RfqQuoteRejectedError, b7 as RfqQuoteRejectedErrorOptions, b8 as RfqQuoteRequestEvent, b9 as RfqQuoteResponse, ba as RfqQuoteSource, bb as RfqSession, bc as RfqTradeEvent, bd as SearchError, fm as SearchRequest, fn as SearchResults, be as SearchSort, fo as SecureRealtimeEvent, fp as SecureRealtimeTopic, fq as SecureSubscriptionSpec, bx as SetupTradingApprovalsError, fr as SignedOrder, fs as SplitComboPositionError, ft as SplitMarketPositionError, bA as SplitPositionError, fu as SplitPositionWorkflow, fv as SplitPositionWorkflowRequest, fw as SportsEventType, fx as SportsSubscription, fy as SubscribeError, fz as SubscriptionHandle, fA as TradingApprovalsWorkflow, fB as TradingApprovalsWorkflowRequest, bF as TransferErc20Error, fC as UpdateBalanceAllowanceError, fD as UpdateBalanceAllowanceRequest, bK as UpdatePerpsLeverageError, fE as UpdatePerpsLeverageRequest, fF as UserEventType, fG as UserSubscription, fH as WaitForGaslessTransactionError, fI as WithdrawFromPerpsError, fJ as WithdrawFromPerpsRequest, fK as approveErc1155ForAll, fL as approveErc20, fM as cancelAll, fN as cancelMarketOrders, fO as cancelOrder, fP as cancelOrders, fQ as deployDepositWallet, fR as depositToPerps, fS as downloadAccountingSnapshot, fT as dropNotifications, fU as estimateMarketPrice, fV as fetchBalanceAllowance, fW as fetchBuilderFeeRates, fX as fetchBuilderVolume, fY as fetchClosedOnlyMode, fZ as fetchCommentsById, f_ as fetchEvent, f$ as fetchEventLiveVolume, g0 as fetchEventTags, g1 as fetchExecuteParams, g2 as fetchLastTradePrice, g3 as fetchLastTradePrices, g4 as fetchMarket, g5 as fetchMarketInfo, g6 as fetchMarketTags, g7 as fetchMidpoint, g8 as fetchMidpoints, g9 as fetchNegRisk, ga as fetchNotifications, gb as fetchOrder, gc as fetchOrderBook, gd as fetchOrderBooks, ge as fetchOrderScoring, gf as fetchOrdersScoring, gg as fetchPerpsBook, gh as fetchPerpsFees, gi as fetchPerpsInstruments, gj as fetchPerpsTicker, gk as fetchPerpsTickers, gl as fetchPortfolioValue, gm as fetchPrice, gn as fetchPriceHistory, go as fetchPrices, gp as fetchPublicProfile, gq as fetchRelatedTagResources, gr as fetchRelatedTags, gs as fetchRewardPercentages, gt as fetchSeries, gu as fetchSpread, gv as fetchSpreads, gw as fetchTag, gx as fetchTickSize, gy as fetchTotalEarningsForUserForDay, gz as fetchTradedMarketCount, gA as fetchTransaction, gB as isWalletDeployed, gC as listAccountTrades, gD as listActivity, gE as listBuilderLeaderboard, gF as listBuilderTrades, gG as listClosedPositions, gH as listComboMarkets, gI as listComboPositions, gJ as listComments, gK as listCommentsByUserAddress, gL as listCurrentRewards, gM as listEvents, gN as listMarketHolders, gO as listMarketPositions, gP as listMarketRewards, gQ as listMarkets, gR as listOpenInterest, gS as listOpenOrders, gT as listPerpsCandles, gU as listPerpsFundingHistory, gV as listPerpsTrades, gW as listPositions, gX as listSeries, gY as listTags, gZ as listTeams, g_ as listTraderLeaderboard, g$ as listTrades, h0 as listUserEarningsAndMarketsConfig, h1 as listUserEarningsForDay, h2 as mergeComboPosition, h3 as mergeMarketPosition, h4 as mergePositions, h5 as openPerpsSession, h6 as openRfqSession, h7 as postOrder, h8 as postOrders, h9 as prepareErc1155ApprovalForAll, ha as prepareErc20Approval, hb as prepareErc20Transfer, hc as prepareGaslessTransaction, hd as prepareMergeComboPosition, he as prepareMergeMarketPosition, hf as prepareMergePositions, hg as preparePerpsDeposit, hh as prepareRedeemComboPosition, hi as prepareRedeemMarketPositions, hj as prepareRedeemPositions, hk as prepareSplitComboPosition, hl as prepareSplitMarketPosition, hm as prepareSplitPosition, hn as prepareTradingApprovals, ho as redeemPositions, hp as resolveConditionByToken, hq as revokePerpsCredentials, hr as search, hs as setupTradingApprovals, ht as splitComboPosition, hu as splitMarketPosition, hv as splitPosition, hw as subscribe, hx as transferErc20, hy as updateBalanceAllowance, hz as withdrawFromPerps } from '../types-BiMOyijM.js';
1
+ import { bG as RateLimitError, bI as RequestRejectedError, cz as TransportError, cC as UnexpectedResponseError, cs as SigningError, B as BaseClient, h as BaseSecureClient } from '../types-B0vr72h4.js';
2
+ export { e as ApproveErc1155ForAllError, f as ApproveErc20Error, C as CancelAllError, j as CancelAllPerpsOrdersRequest, k as CancelMarketOrdersError, c_ as CancelMarketOrdersRequest, l as CancelOrderError, c$ as CancelOrderRequest, m as CancelOrdersError, d0 as CancelOrdersRequest, n as CancelPerpsOrderRequest, o as CancelPerpsOrdersRequest, u as ComboPositionSort, d1 as CommentsEventType, d2 as CommentsSubscription, v as CreatePerpsSessionRequest, d3 as CryptoPricesEventType, d4 as CryptoPricesSubscription, d5 as DeployDepositWalletError, x as DepositToPerpsError, y as DepositToPerpsRequest, d6 as DeprecatedTransactionHandle, E as DownloadAccountingSnapshotError, d7 as DownloadAccountingSnapshotRequest, F as DropNotificationsError, d8 as DropNotificationsRequest, d9 as EquityPricesEventType, da as EquityPricesSubscription, db as Erc1155ApprovalForAllWorkflow, dc as Erc1155ApprovalForAllWorkflowRequest, dd as Erc20ApprovalWorkflow, de as Erc20ApprovalWorkflowRequest, df as Erc20TransferWorkflow, dg as Erc20TransferWorkflowRequest, dh as EstimateMarketBuyPriceRequest, J as EstimateMarketPriceError, di as EstimateMarketPriceRequest, dj as EstimateMarketSellPriceRequest, dk as EventForSubscriptionSpec, dl as EventForSubscriptionSpecs, dm as FetchBalanceAllowanceError, dn as FetchBalanceAllowanceRequest, dp as FetchBuilderFeeRatesError, dq as FetchBuilderFeeRatesRequest, K as FetchClosedOnlyModeError, L as FetchCommentsByIdError, dr as FetchCommentsByIdRequest, M as FetchEventError, N as FetchEventLiveVolumeError, ds as FetchEventLiveVolumeRequest, dt as FetchEventRequest, O as FetchEventTagsError, du as FetchEventTagsRequest, dv as FetchExecuteParamsError, dw as FetchExecuteParamsRequest, dx as FetchGaslessTransactionRequest, P as FetchLastTradePriceError, dy as FetchLastTradePriceRequest, Q as FetchLastTradePricesError, dz as FetchLastTradePricesRequest, R as FetchMarketError, dA as FetchMarketInfoError, dB as FetchMarketInfoRequest, dC as FetchMarketRequest, V as FetchMarketTagsError, dD as FetchMarketTagsRequest, W as FetchMidpointError, dE as FetchMidpointRequest, X as FetchMidpointsError, dF as FetchMidpointsRequest, dG as FetchNegRiskError, dH as FetchNegRiskRequest, Y as FetchNotificationsError, Z as FetchOrderBookError, dI as FetchOrderBookRequest, _ as FetchOrderBooksError, dJ as FetchOrderBooksRequest, $ as FetchOrderError, dK as FetchOrderRequest, a0 as FetchOrderScoringError, dL as FetchOrderScoringRequest, a1 as FetchOrdersScoringError, dM as FetchOrdersScoringRequest, a2 as FetchPerpsAccountConfigRequest, a3 as FetchPerpsBookError, a4 as FetchPerpsBookRequest, a5 as FetchPerpsFeesError, a6 as FetchPerpsInstrumentsError, a7 as FetchPerpsInstrumentsRequest, a8 as FetchPerpsOpenOrdersRequest, a9 as FetchPerpsOrdersRequest, aa as FetchPerpsTickerError, ab as FetchPerpsTickerRequest, ac as FetchPerpsTickersError, ad as FetchPerpsTickersRequest, ae as FetchPortfolioValueError, dN as FetchPortfolioValueRequest, af as FetchPriceError, ag as FetchPriceHistoryError, dO as FetchPriceHistoryRequest, dP as FetchPriceRequest, ah as FetchPricesError, dQ as FetchPricesRequest, ai as FetchPublicProfileError, dR as FetchPublicProfileRequest, aj as FetchRelatedTagResourcesError, dS as FetchRelatedTagResourcesRequest, ak as FetchRelatedTagsError, dT as FetchRelatedTagsRequest, al as FetchRewardPercentagesError, am as FetchSeriesError, dU as FetchSeriesRequest, an as FetchSpreadError, dV as FetchSpreadRequest, ao as FetchSpreadsError, dW as FetchSpreadsRequest, ap as FetchTagError, dX as FetchTagRequest, dY as FetchTickSizeError, dZ as FetchTickSizeRequest, aq as FetchTotalEarningsForUserForDayError, d_ as FetchTotalEarningsForUserForDayRequest, ar as FetchTradedMarketCountError, d$ as FetchTradedMarketCountRequest, e0 as GaslessTransactionMetadataSchema, e1 as GaslessWorkflow, e2 as GaslessWorkflowRequest, e3 as IsWalletDeployedError, e4 as IsWalletDeployedRequest, at as ListAccountTradesError, e5 as ListAccountTradesRequest, au as ListActivityError, e6 as ListActivityRequest, av as ListBuilderLeaderboardError, e7 as ListBuilderLeaderboardRequest, aw as ListBuilderTradesError, e8 as ListBuilderTradesRequest, ax as ListBuilderVolumeError, e9 as ListBuilderVolumeRequest, ay as ListClosedPositionsError, ea as ListClosedPositionsRequest, az as ListComboActivityError, eb as ListComboActivityRequest, aA as ListComboMarketsError, ec as ListComboMarketsRequest, aB as ListComboPositionsError, ed as ListComboPositionsRequest, aC as ListCommentsByUserAddressError, ee as ListCommentsByUserAddressRequest, aD as ListCommentsError, ef as ListCommentsRequest, aE as ListCurrentRewardsError, eg as ListCurrentRewardsRequest, aF as ListEventsError, eh as ListEventsRequest, ei as ListMarketClarificationsError, ej as ListMarketClarificationsRequest, aG as ListMarketHoldersError, ek as ListMarketHoldersRequest, aH as ListMarketPositionsError, el as ListMarketPositionsRequest, aI as ListMarketRewardsError, em as ListMarketRewardsRequest, aJ as ListMarketsError, en as ListMarketsRequest, aK as ListOpenInterestError, eo as ListOpenInterestRequest, aL as ListOpenOrdersError, ep as ListOpenOrdersRequest, aM as ListPerpsCandlesError, aN as ListPerpsCandlesRequest, aO as ListPerpsDepositsRequest, aP as ListPerpsEquityHistoryRequest, aQ as ListPerpsFillsRequest, aR as ListPerpsFundingHistoryError, aS as ListPerpsFundingHistoryRequest, aT as ListPerpsFundingPaymentsRequest, aU as ListPerpsPnlHistoryRequest, aV as ListPerpsTradesError, aW as ListPerpsTradesRequest, aX as ListPerpsWithdrawalsRequest, aY as ListPositionsError, eq as ListPositionsRequest, aZ as ListSeriesError, er as ListSeriesRequest, a_ as ListTagsError, es as ListTagsRequest, a$ as ListTeamsError, et as ListTeamsRequest, b0 as ListTraderLeaderboardError, eu as ListTraderLeaderboardRequest, b1 as ListTradesError, ev as ListTradesRequest, b2 as ListUserEarningsAndMarketsConfigError, ew as ListUserEarningsAndMarketsConfigRequest, b3 as ListUserEarningsForDayError, ex as ListUserEarningsForDayRequest, ey as MarketEventType, ez as MarketSubscription, eA as MergeComboPositionError, eB as MergeMarketPositionError, b4 as MergePositionsError, eC as MergePositionsWorkflow, eD as MergePositionsWorkflowRequest, b5 as OpenPerpsSessionError, b6 as OpenPerpsSessionRequest, b7 as OpenRfqSessionError, eE as OrderDraft, eF as OrderPostingWorkflow, eG as OrderWorkflow, eH as OrderWorkflowRequest, eI as PerpsBboSubscription, bc as PerpsBookDepth, eJ as PerpsBookSubscription, eK as PerpsCandlesSubscription, eL as PerpsDepositWorkflow, eM as PerpsDepositWorkflowRequest, eN as PerpsMarketDataEventType, eO as PerpsMarketDataSubscription, be as PerpsOrderRequest, bf as PerpsPlaceFokOrderRequest, bg as PerpsPlaceGtcOrderRequest, bh as PerpsPlaceIocOrderRequest, bi as PerpsPlacedTpSlOrder, bj as PerpsPlacedTpSlOrders, bk as PerpsPositionTpSlTrigger, bl as PerpsSession, bm as PerpsSessionAccountError, bn as PerpsSessionLifecycleError, bo as PerpsSessionTradingError, eP as PerpsStatisticsSubscription, eQ as PerpsStreamingCandleInterval, eR as PerpsTickersSubscription, bp as PerpsTpSlTrigger, eS as PerpsTradesSubscription, bq as PlacePerpsOrderRequest, br as PlacePerpsOrderResult, bs as PlacePerpsOrderWithTpSlRequest, bt as PlacePerpsOrderWithTpSlResult, bu as PlacePerpsPositionTpSlRequest, bv as PlacePerpsPositionTpSlResult, bw as PostOrderError, bx as PostOrdersError, eT as PostOrdersRequest, by as PostPerpsOrdersRequest, eU as PrepareErc1155ApprovalForAllError, eV as PrepareErc1155ApprovalForAllRequest, eW as PrepareErc20ApprovalError, eX as PrepareErc20ApprovalRequest, eY as PrepareErc20TransferError, eZ as PrepareErc20TransferRequest, e_ as PrepareGaslessTransactionError, e$ as PrepareGaslessTransactionRequest, f0 as PrepareLimitOrderRequest, f1 as PrepareMarketBuyOrderRequest, f2 as PrepareMarketOrderRequest, f3 as PrepareMarketSellOrderRequest, f4 as PrepareMergeComboPositionError, f5 as PrepareMergeComboPositionRequest, f6 as PrepareMergeMarketPositionError, f7 as PrepareMergeMarketPositionRequest, f8 as PrepareMergePositionsError, f9 as PrepareMergePositionsRequest, fa as PreparePerpsDepositError, fb as PrepareRedeemComboPositionError, fc as PrepareRedeemComboPositionRequest, fd as PrepareRedeemMarketPositionsByConditionIdRequest, fe as PrepareRedeemMarketPositionsByMarketIdRequest, ff as PrepareRedeemMarketPositionsError, fg as PrepareRedeemMarketPositionsRequest, fh as PrepareRedeemPositionsError, fi as PrepareRedeemPositionsRequest, fj as PrepareSplitComboPositionError, fk as PrepareSplitComboPositionRequest, fl as PrepareSplitMarketPositionError, fm as PrepareSplitMarketPositionRequest, fn as PrepareSplitPositionError, fo as PrepareSplitPositionRequest, fp as PrepareTradingApprovalsError, fq as PublicRealtimeEvent, fr as PublicRealtimeTopic, fs as PublicSubscriptionSpec, bH as RedeemPositionsError, ft as RedeemPositionsWorkflow, fu as RedeemPositionsWorkflowRequest, fv as ResolveConditionByTokenError, fw as ResolveConditionByTokenRequest, bL as ResumePerpsSessionRequest, bM as RevokePerpsCredentialsError, bN as RevokePerpsCredentialsRequest, bO as RfqCancelQuoteAck, bP as RfqCancelQuoteError, bQ as RfqCancelQuoteRejectedError, bR as RfqCancelQuoteRejectedErrorOptions, bS as RfqConfirmationAck, bT as RfqConfirmationError, bU as RfqConfirmationRejectedError, fx as RfqConfirmationRejectedErrorOptions, bV as RfqConfirmationRequestEvent, bX as RfqEvent, fy as RfqExecutionUpdateEvent, bY as RfqQuoteError, bZ as RfqQuoteReference, b_ as RfqQuoteRejectedError, b$ as RfqQuoteRejectedErrorOptions, c0 as RfqQuoteRequestEvent, c1 as RfqQuoteResponse, c2 as RfqQuoteSource, c3 as RfqSession, c4 as RfqTradeEvent, c5 as SearchError, fz as SearchRequest, fA as SearchResults, c6 as SearchSort, fB as SecureRealtimeEvent, fC as SecureRealtimeTopic, fD as SecureSubscriptionSpec, cq as SetupTradingApprovalsError, fE as SignedOrder, fF as SplitComboPositionError, fG as SplitMarketPositionError, ct as SplitPositionError, fH as SplitPositionWorkflow, fI as SplitPositionWorkflowRequest, fJ as SportsEventType, fK as SportsSubscription, fL as SubscribeError, fM as SubscriptionHandle, fN as TradingApprovalsWorkflow, fO as TradingApprovalsWorkflowRequest, cy as TransferErc20Error, fP as UpdateBalanceAllowanceError, fQ as UpdateBalanceAllowanceRequest, cD as UpdatePerpsLeverageError, cE as UpdatePerpsLeverageRequest, fR as UserEventType, fS as UserSubscription, fT as WaitForGaslessTransactionError, cI as WithdrawFromPerpsError, cJ as WithdrawFromPerpsRequest, fU as approveErc1155ForAll, fV as approveErc20, fW as cancelAll, fX as cancelMarketOrders, fY as cancelOrder, fZ as cancelOrders, f_ as deployDepositWallet, f$ as depositToPerps, g0 as downloadAccountingSnapshot, g1 as dropNotifications, g2 as estimateMarketPrice, g3 as fetchBalanceAllowance, g4 as fetchBuilderFeeRates, g5 as fetchBuilderVolume, g6 as fetchClosedOnlyMode, g7 as fetchCommentsById, g8 as fetchEvent, g9 as fetchEventLiveVolume, ga as fetchEventTags, gb as fetchExecuteParams, gc as fetchLastTradePrice, gd as fetchLastTradePrices, ge as fetchMarket, gf as fetchMarketInfo, gg as fetchMarketTags, gh as fetchMidpoint, gi as fetchMidpoints, gj as fetchNegRisk, gk as fetchNotifications, gl as fetchOrder, gm as fetchOrderBook, gn as fetchOrderBooks, go as fetchOrderScoring, gp as fetchOrdersScoring, gq as fetchPerpsBook, gr as fetchPerpsFees, gs as fetchPerpsInstruments, gt as fetchPerpsTicker, gu as fetchPerpsTickers, gv as fetchPortfolioValue, gw as fetchPrice, gx as fetchPriceHistory, gy as fetchPrices, gz as fetchPublicProfile, gA as fetchRelatedTagResources, gB as fetchRelatedTags, gC as fetchRewardPercentages, gD as fetchSeries, gE as fetchSpread, gF as fetchSpreads, gG as fetchTag, gH as fetchTickSize, gI as fetchTotalEarningsForUserForDay, gJ as fetchTradedMarketCount, gK as fetchTransaction, gL as isWalletDeployed, gM as listAccountTrades, gN as listActivity, gO as listBuilderLeaderboard, gP as listBuilderTrades, gQ as listClosedPositions, gR as listComboActivity, gS as listComboMarkets, gT as listComboPositions, gU as listComments, gV as listCommentsByUserAddress, gW as listCurrentRewards, gX as listEvents, gY as listMarketClarifications, gZ as listMarketHolders, g_ as listMarketPositions, g$ as listMarketRewards, h0 as listMarkets, h1 as listOpenInterest, h2 as listOpenOrders, h3 as listPerpsCandles, h4 as listPerpsFundingHistory, h5 as listPerpsTrades, h6 as listPositions, h7 as listSeries, h8 as listTags, h9 as listTeams, ha as listTraderLeaderboard, hb as listTrades, hc as listUserEarningsAndMarketsConfig, hd as listUserEarningsForDay, he as mergeComboPosition, hf as mergeMarketPosition, hg as mergePositions, hh as openPerpsSession, hi as openRfqSession, hj as postOrder, hk as postOrders, hl as prepareErc1155ApprovalForAll, hm as prepareErc20Approval, hn as prepareErc20Transfer, ho as prepareGaslessTransaction, hp as prepareMergeComboPosition, hq as prepareMergeMarketPosition, hr as prepareMergePositions, hs as preparePerpsDeposit, ht as prepareRedeemComboPosition, hu as prepareRedeemMarketPositions, hv as prepareRedeemPositions, hw as prepareSplitComboPosition, hx as prepareSplitMarketPosition, hy as prepareSplitPosition, hz as prepareTradingApprovals, hA as redeemPositions, hB as resolveConditionByToken, hC as revokePerpsCredentials, hD as search, hE as setupTradingApprovals, hF as splitComboPosition, hG as splitMarketPosition, hH as splitPosition, hI as subscribe, hJ as transferErc20, hK as updateBalanceAllowance, hL as withdrawFromPerps } from '../types-B0vr72h4.js';
3
3
  import { ApiKey } from '@polymarket/bindings';
4
4
  import { ApiKeyCreds, BuilderApiKeyCreds, BuilderApiKey } from '@polymarket/bindings/clob';
5
5
  import { EvmAddress, EvmSignature } from '@polymarket/types';
6
- export { C as CreateLimitOrderError, a as CreateMarketOrderError, F as FetchSportsMarketTypesError, L as ListSportsError, P as PlaceLimitOrderError, b as PlaceMarketOrderError, c as PrepareLimitOrderError, d as PrepareLimitOrderPostingError, e as PrepareMarketOrderError, f as PrepareMarketOrderPostingError, g as createLimitOrder, h as createMarketOrder, i as fetchSportsMarketTypes, l as listSports, p as placeLimitOrder, j as placeMarketOrder, k as prepareLimitOrder, m as prepareLimitOrderPosting, n as prepareMarketOrder, o as prepareMarketOrderPosting } from '../sports-BHPoQjk0.js';
7
- export { ComboPositionStatus } from '@polymarket/bindings/data';
6
+ export { C as CreateLimitOrderError, a as CreateMarketOrderError, F as FetchSportsMarketTypesError, L as ListSportsError, P as PlaceLimitOrderError, b as PlaceMarketOrderError, c as PrepareLimitOrderError, d as PrepareLimitOrderPostingError, e as PrepareMarketOrderError, f as PrepareMarketOrderPostingError, g as createLimitOrder, h as createMarketOrder, i as fetchSportsMarketTypes, l as listSports, p as placeLimitOrder, j as placeMarketOrder, k as prepareLimitOrder, m as prepareLimitOrderPosting, n as prepareMarketOrder, o as prepareMarketOrderPosting } from '../sports-DKIjf_Mf.js';
7
+ export { ComboActivityType, ComboPositionOutcome, ComboPositionStatus } from '@polymarket/bindings/data';
8
8
  export { CommentsEvent, CryptoPricesBinanceEvent, CryptoPricesChainlinkEvent, CryptoPricesEvent, CustomMarketEvent, EquityPricesEvent, MarketEvent, PerpsBboEvent, PerpsBookEvent, PerpsCandleEvent, PerpsMarketDataEvent, PerpsSessionEvent, PerpsStatisticEvent, PerpsTickerEvent, PerpsTradeEvent, SportsEvent, StandardMarketEvent, UserEvent } from '@polymarket/bindings/subscriptions';
9
9
  export { PerpsCancelOrderResult, PerpsPostOrderAck, PerpsUpdateLeverageResult } from '@polymarket/bindings/perps';
10
10
  export { RfqConfirmationDecision, RfqConfirmationRequest, RfqDirection, RfqErrorCode, RfqExecutionStatus, RfqExecutionUpdate, RfqId, RfqQuoteId, RfqQuoteRequest, RfqRequestedSize, RfqRequestedSizeUnit, RfqRequestorPublicId, RfqSide, RfqTrade } from '@polymarket/bindings/rfq';
@@ -21,7 +21,7 @@ type ApiKeyAuthRequest = {
21
21
  };
22
22
  type CreateApiKeyError = RateLimitError | RequestRejectedError | TransportError | UnexpectedResponseError;
23
23
  declare const CreateApiKeyError: {
24
- isError(error: unknown): error is UnexpectedResponseError | TransportError | RequestRejectedError | RateLimitError;
24
+ isError(error: unknown): error is TransportError | UnexpectedResponseError | RequestRejectedError | RateLimitError;
25
25
  };
26
26
  /**
27
27
  * Creates a new API key from a signed L1 auth payload.
@@ -40,7 +40,7 @@ declare const CreateApiKeyError: {
40
40
  declare function createApiKey(client: BaseClient, request: ApiKeyAuthRequest): Promise<ApiKeyCreds>;
41
41
  type DeriveApiKeyError = RateLimitError | RequestRejectedError | TransportError | UnexpectedResponseError;
42
42
  declare const DeriveApiKeyError: {
43
- isError(error: unknown): error is UnexpectedResponseError | TransportError | RequestRejectedError | RateLimitError;
43
+ isError(error: unknown): error is TransportError | UnexpectedResponseError | RequestRejectedError | RateLimitError;
44
44
  };
45
45
  /**
46
46
  * Derives an existing API key from a signed L1 auth payload.
@@ -59,7 +59,7 @@ declare const DeriveApiKeyError: {
59
59
  declare function deriveApiKey(client: BaseClient, request: ApiKeyAuthRequest): Promise<ApiKeyCreds>;
60
60
  type CreateOrDeriveApiKeyError = RateLimitError | RequestRejectedError | TransportError | UnexpectedResponseError;
61
61
  declare const CreateOrDeriveApiKeyError: {
62
- isError(error: unknown): error is UnexpectedResponseError | TransportError | RequestRejectedError | RateLimitError;
62
+ isError(error: unknown): error is TransportError | UnexpectedResponseError | RequestRejectedError | RateLimitError;
63
63
  };
64
64
  /**
65
65
  * Creates an API key and falls back to derivation when it already exists.
@@ -78,7 +78,7 @@ declare const CreateOrDeriveApiKeyError: {
78
78
  declare function createOrDeriveApiKey(client: BaseClient, request: ApiKeyAuthRequest): Promise<ApiKeyCreds>;
79
79
  type FetchApiKeysError = RateLimitError | RequestRejectedError | SigningError | TransportError | UnexpectedResponseError;
80
80
  declare const FetchApiKeysError: {
81
- isError(error: unknown): error is UnexpectedResponseError | TransportError | RequestRejectedError | RateLimitError | SigningError;
81
+ isError(error: unknown): error is SigningError | TransportError | UnexpectedResponseError | RequestRejectedError | RateLimitError;
82
82
  };
83
83
  /**
84
84
  * Fetches all API keys associated with the authenticated client.
@@ -97,7 +97,7 @@ declare const FetchApiKeysError: {
97
97
  declare function fetchApiKeys(client: BaseSecureClient): Promise<ApiKey[]>;
98
98
  type DeleteApiKeyError = RateLimitError | RequestRejectedError | SigningError | TransportError | UnexpectedResponseError;
99
99
  declare const DeleteApiKeyError: {
100
- isError(error: unknown): error is UnexpectedResponseError | TransportError | RequestRejectedError | RateLimitError | SigningError;
100
+ isError(error: unknown): error is SigningError | TransportError | UnexpectedResponseError | RequestRejectedError | RateLimitError;
101
101
  };
102
102
  /**
103
103
  * Deletes the authenticated API key.
@@ -117,7 +117,7 @@ declare const DeleteApiKeyError: {
117
117
  declare function deleteApiKey(client: BaseSecureClient): Promise<void>;
118
118
  type CreateBuilderApiKeyError = RateLimitError | RequestRejectedError | SigningError | TransportError | UnexpectedResponseError;
119
119
  declare const CreateBuilderApiKeyError: {
120
- isError(error: unknown): error is UnexpectedResponseError | TransportError | RequestRejectedError | RateLimitError | SigningError;
120
+ isError(error: unknown): error is SigningError | TransportError | UnexpectedResponseError | RequestRejectedError | RateLimitError;
121
121
  };
122
122
  /**
123
123
  * Creates a new builder API key for the authenticated client.
@@ -137,7 +137,7 @@ declare const CreateBuilderApiKeyError: {
137
137
  declare function createBuilderApiKey(client: BaseSecureClient): Promise<BuilderApiKeyCreds>;
138
138
  type FetchBuilderApiKeysError = RateLimitError | RequestRejectedError | SigningError | TransportError | UnexpectedResponseError;
139
139
  declare const FetchBuilderApiKeysError: {
140
- isError(error: unknown): error is UnexpectedResponseError | TransportError | RequestRejectedError | RateLimitError | SigningError;
140
+ isError(error: unknown): error is SigningError | TransportError | UnexpectedResponseError | RequestRejectedError | RateLimitError;
141
141
  };
142
142
  /**
143
143
  * Fetches builder API keys associated with the authenticated client.
@@ -157,7 +157,7 @@ declare const FetchBuilderApiKeysError: {
157
157
  declare function fetchBuilderApiKeys(client: BaseSecureClient): Promise<BuilderApiKey[]>;
158
158
  type RevokeBuilderApiKeyError = RateLimitError | RequestRejectedError | SigningError | TransportError | UnexpectedResponseError;
159
159
  declare const RevokeBuilderApiKeyError: {
160
- isError(error: unknown): error is UnexpectedResponseError | TransportError | RequestRejectedError | RateLimitError | SigningError;
160
+ isError(error: unknown): error is SigningError | TransportError | UnexpectedResponseError | RequestRejectedError | RateLimitError;
161
161
  };
162
162
  /**
163
163
  * Revokes a builder API key.
@@ -1,2 +1,2 @@
1
- export{La as ApproveErc1155ForAllError,Ha as ApproveErc20Error,Bc as CancelAllError,Dc as CancelMarketOrdersError,xc as CancelOrderError,zc as CancelOrdersError,Yd as ComboPositionStatus,Ra as CreateApiKeyError,$a as CreateBuilderApiKeyError,$c as CreateLimitOrderError,Xc as CreateMarketOrderError,Va as CreateOrDeriveApiKeyError,Za as DeleteApiKeyError,za as DeployDepositWalletError,Fd as DepositToPerpsError,Ta as DeriveApiKeyError,Wd as DownloadAccountingSnapshotError,W as DropNotificationsError,Fc as EstimateMarketPriceError,Xa as FetchApiKeysError,Y as FetchBalanceAllowanceError,bb as FetchBuilderApiKeysError,tb as FetchBuilderFeeRatesError,M as FetchClosedOnlyModeError,Tb as FetchCommentsByIdError,Zb as FetchEventError,bc as FetchEventLiveVolumeError,$b as FetchEventTagsError,ua as FetchExecuteParamsError,Hb as FetchLastTradePriceError,Jb as FetchLastTradePricesError,nc as FetchMarketError,rb as FetchMarketInfoError,pc as FetchMarketTagsError,hb as FetchMidpointError,jb as FetchMidpointsError,nb as FetchNegRiskError,U as FetchNotificationsError,zb as FetchOrderBookError,Bb as FetchOrderBooksError,Q as FetchOrderError,aa as FetchOrderScoringError,ca as FetchOrdersScoringError,sd as FetchPerpsBookError,Ad as FetchPerpsFeesError,md as FetchPerpsInstrumentsError,od as FetchPerpsTickerError,qd as FetchPerpsTickersError,Sd as FetchPortfolioValueError,vb as FetchPriceError,Lb as FetchPriceHistoryError,xb as FetchPricesError,De as FetchPublicProfileError,jf as FetchRelatedTagResourcesError,hf as FetchRelatedTagsError,ka as FetchRewardPercentagesError,Ye as FetchSeriesError,af as FetchSportsMarketTypesError,Db as FetchSpreadError,Fb as FetchSpreadsError,ff as FetchTagError,lb as FetchTickSizeError,ga as FetchTotalEarningsForUserForDayError,Ud as FetchTradedMarketCountError,ya as GaslessTransactionMetadataSchema,wa as IsWalletDeployedError,S as ListAccountTradesError,oa as ListActivityError,dc as ListBuilderLeaderboardError,fb as ListBuilderTradesError,fc as ListBuilderVolumeError,Od as ListClosedPositionsError,lc as ListComboMarketsError,Pd as ListComboPositionsError,Vb as ListCommentsByUserAddressError,Rb as ListCommentsError,Nb as ListCurrentRewardsError,Xb as ListEventsError,rc as ListMarketHoldersError,vc as ListMarketPositionsError,Pb as ListMarketRewardsError,jc as ListMarketsError,tc as ListOpenInterestError,O as ListOpenOrdersError,ud as ListPerpsCandlesError,wd as ListPerpsFundingHistoryError,yd as ListPerpsTradesError,Md as ListPositionsError,We as ListSeriesError,_e as ListSportsError,df as ListTagsError,lf as ListTeamsError,hc as ListTraderLeaderboardError,ma as ListTradesError,ia as ListUserEarningsAndMarketsConfigError,ea as ListUserEarningsForDayError,ue as MergeComboPositionError,te as MergeMarketPositionError,se as MergePositionsError,Cd as OpenPerpsSessionError,Le as OpenRfqSessionError,bd as PlaceLimitOrderError,Zc as PlaceMarketOrderError,Ic as PostOrderError,Jc as PostOrdersError,Ja as PrepareErc1155ApprovalForAllError,Fa as PrepareErc20ApprovalError,nf as PrepareErc20TransferError,Ca as PrepareGaslessTransactionError,Rc as PrepareLimitOrderError,Vc as PrepareLimitOrderPostingError,Pc as PrepareMarketOrderError,Tc as PrepareMarketOrderPostingError,ce as PrepareMergeComboPositionError,be as PrepareMergeMarketPositionError,ae as PrepareMergePositionsError,Ed as PreparePerpsDepositError,fe as PrepareRedeemComboPositionError,ee as PrepareRedeemMarketPositionsError,de as PrepareRedeemPositionsError,$d as PrepareSplitComboPositionError,_d as PrepareSplitMarketPositionError,Zd as PrepareSplitPositionError,Na as PrepareTradingApprovalsError,Be as RedeemPositionsError,pb as ResolveConditionByTokenError,db as RevokeBuilderApiKeyError,Dd as RevokePerpsCredentialsError,Ie as RfqCancelQuoteError,He as RfqCancelQuoteRejectedError,Ne as RfqConfirmationDecision,Ke as RfqConfirmationError,Je as RfqConfirmationRejectedError,Oe as RfqDirection,Pe as RfqErrorCode,Qe as RfqExecutionStatus,Ge as RfqQuoteError,Fe as RfqQuoteRejectedError,Re as RfqRequestedSizeUnit,Se as RfqSide,Ue as SearchError,Te as SearchSort,Pa as SetupTradingApprovalsError,le as SplitComboPositionError,ke as SplitMarketPositionError,je as SplitPositionError,pf as TransferErc20Error,_ as UpdateBalanceAllowanceError,kd as UpdatePerpsLeverageError,Ea as WaitForGaslessTransactionError,Gd as WithdrawFromPerpsError,Ma as approveErc1155ForAll,Ia as approveErc20,Cc as cancelAll,Ec as cancelMarketOrders,yc as cancelOrder,Ac as cancelOrders,Sa as createApiKey,ab as createBuilderApiKey,ad as createLimitOrder,Yc as createMarketOrder,Wa as createOrDeriveApiKey,_a as deleteApiKey,Aa as deployDepositWallet,Kd as depositToPerps,Ua as deriveApiKey,Xd as downloadAccountingSnapshot,X as dropNotifications,Gc as estimateMarketPrice,Ya as fetchApiKeys,Z as fetchBalanceAllowance,cb as fetchBuilderApiKeys,ub as fetchBuilderFeeRates,gc as fetchBuilderVolume,N as fetchClosedOnlyMode,Ub as fetchCommentsById,_b as fetchEvent,cc as fetchEventLiveVolume,ac as fetchEventTags,va as fetchExecuteParams,Ib as fetchLastTradePrice,Kb as fetchLastTradePrices,oc as fetchMarket,sb as fetchMarketInfo,qc as fetchMarketTags,ib as fetchMidpoint,kb as fetchMidpoints,ob as fetchNegRisk,V as fetchNotifications,R as fetchOrder,Ab as fetchOrderBook,Cb as fetchOrderBooks,ba as fetchOrderScoring,da as fetchOrdersScoring,td as fetchPerpsBook,Bd as fetchPerpsFees,nd as fetchPerpsInstruments,pd as fetchPerpsTicker,rd as fetchPerpsTickers,Td as fetchPortfolioValue,wb as fetchPrice,Mb as fetchPriceHistory,yb as fetchPrices,Ee as fetchPublicProfile,kf as fetchRelatedTagResources,if as fetchRelatedTags,la as fetchRewardPercentages,Ze as fetchSeries,bf as fetchSportsMarketTypes,Eb as fetchSpread,Gb as fetchSpreads,gf as fetchTag,mb as fetchTickSize,ha as fetchTotalEarningsForUserForDay,Vd as fetchTradedMarketCount,Ba as fetchTransaction,xa as isWalletDeployed,T as listAccountTrades,pa as listActivity,ec as listBuilderLeaderboard,gb as listBuilderTrades,Qd as listClosedPositions,mc as listComboMarkets,Rd as listComboPositions,Sb as listComments,Wb as listCommentsByUserAddress,Ob as listCurrentRewards,Yb as listEvents,sc as listMarketHolders,wc as listMarketPositions,Qb as listMarketRewards,kc as listMarkets,uc as listOpenInterest,P as listOpenOrders,vd as listPerpsCandles,xd as listPerpsFundingHistory,zd as listPerpsTrades,Nd as listPositions,Xe as listSeries,$e as listSports,ef as listTags,mf as listTeams,ic as listTraderLeaderboard,na as listTrades,ja as listUserEarningsAndMarketsConfig,fa as listUserEarningsForDay,we as mergeComboPosition,ve as mergeMarketPosition,xe as mergePositions,Hd as openPerpsSession,Me as openRfqSession,cd as placeLimitOrder,_c as placeMarketOrder,Kc as postOrder,Lc as postOrders,Ka as prepareErc1155ApprovalForAll,Ga as prepareErc20Approval,of as prepareErc20Transfer,Da as prepareGaslessTransaction,Sc as prepareLimitOrder,Wc as prepareLimitOrderPosting,Qc as prepareMarketOrder,Uc as prepareMarketOrderPosting,qe as prepareMergeComboPosition,pe as prepareMergeMarketPosition,re as prepareMergePositions,Jd as preparePerpsDeposit,ze as prepareRedeemComboPosition,ye as prepareRedeemMarketPositions,Ae as prepareRedeemPositions,he as prepareSplitComboPosition,ge as prepareSplitMarketPosition,ie as prepareSplitPosition,Oa as prepareTradingApprovals,Ce as redeemPositions,qb as resolveConditionByToken,Hc as resolveEstimatedMarketPrice,eb as revokeBuilderApiKey,Id as revokePerpsCredentials,Ve as search,Qa as setupTradingApprovals,Oc as signOrder,ne as splitComboPosition,me as splitMarketPosition,oe as splitPosition,cf as subscribe,qf as transferErc20,$ as updateBalanceAllowance,Ld as withdrawFromPerps}from'../chunk-AYGGMWA6.js';import'../chunk-E2CLUN5M.js';//# sourceMappingURL=index.js.map
1
+ export{Oa as ApproveErc1155ForAllError,Ka as ApproveErc20Error,Gc as CancelAllError,Ic as CancelMarketOrdersError,Cc as CancelOrderError,Ec as CancelOrdersError,sa as ComboActivityType,ce as ComboPositionOutcome,Rd as ComboPositionSort,de as ComboPositionStatus,Ua as CreateApiKeyError,cb as CreateBuilderApiKeyError,ed as CreateLimitOrderError,ad as CreateMarketOrderError,Ya as CreateOrDeriveApiKeyError,ab as DeleteApiKeyError,Ca as DeployDepositWalletError,Kd as DepositToPerpsError,Wa as DeriveApiKeyError,ae as DownloadAccountingSnapshotError,W as DropNotificationsError,Kc as EstimateMarketPriceError,_a as FetchApiKeysError,Y as FetchBalanceAllowanceError,eb as FetchBuilderApiKeysError,wb as FetchBuilderFeeRatesError,M as FetchClosedOnlyModeError,Wb as FetchCommentsByIdError,ac as FetchEventError,ec as FetchEventLiveVolumeError,cc as FetchEventTagsError,xa as FetchExecuteParamsError,Kb as FetchLastTradePriceError,Mb as FetchLastTradePricesError,sc as FetchMarketError,ub as FetchMarketInfoError,uc as FetchMarketTagsError,kb as FetchMidpointError,mb as FetchMidpointsError,qb as FetchNegRiskError,U as FetchNotificationsError,Cb as FetchOrderBookError,Eb as FetchOrderBooksError,Q as FetchOrderError,aa as FetchOrderScoringError,ca as FetchOrdersScoringError,xd as FetchPerpsBookError,Fd as FetchPerpsFeesError,rd as FetchPerpsInstrumentsError,td as FetchPerpsTickerError,vd as FetchPerpsTickersError,Yd as FetchPortfolioValueError,yb as FetchPriceError,Ob as FetchPriceHistoryError,Ab as FetchPricesError,Ke as FetchPublicProfileError,qf as FetchRelatedTagResourcesError,of as FetchRelatedTagsError,ka as FetchRewardPercentagesError,df as FetchSeriesError,hf as FetchSportsMarketTypesError,Gb as FetchSpreadError,Ib as FetchSpreadsError,mf as FetchTagError,ob as FetchTickSizeError,ga as FetchTotalEarningsForUserForDayError,_d as FetchTradedMarketCountError,Ba as GaslessTransactionMetadataSchema,za as IsWalletDeployedError,S as ListAccountTradesError,oa as ListActivityError,gc as ListBuilderLeaderboardError,ib as ListBuilderTradesError,ic as ListBuilderVolumeError,Ud as ListClosedPositionsError,qa as ListComboActivityError,qc as ListComboMarketsError,Wd as ListComboPositionsError,Yb as ListCommentsByUserAddressError,Ub as ListCommentsError,Qb as ListCurrentRewardsError,_b as ListEventsError,mc as ListMarketClarificationsError,wc as ListMarketHoldersError,Ac as ListMarketPositionsError,Sb as ListMarketRewardsError,oc as ListMarketsError,yc as ListOpenInterestError,O as ListOpenOrdersError,zd as ListPerpsCandlesError,Bd as ListPerpsFundingHistoryError,Dd as ListPerpsTradesError,Sd as ListPositionsError,bf as ListSeriesError,ff as ListSportsError,kf as ListTagsError,sf as ListTeamsError,kc as ListTraderLeaderboardError,ma as ListTradesError,ia as ListUserEarningsAndMarketsConfigError,ea as ListUserEarningsForDayError,Be as MergeComboPositionError,Ae as MergeMarketPositionError,ze as MergePositionsError,Hd as OpenPerpsSessionError,Se as OpenRfqSessionError,gd as PlaceLimitOrderError,cd as PlaceMarketOrderError,Nc as PostOrderError,Oc as PostOrdersError,Ma as PrepareErc1155ApprovalForAllError,Ia as PrepareErc20ApprovalError,uf as PrepareErc20TransferError,Fa as PrepareGaslessTransactionError,Wc as PrepareLimitOrderError,_c as PrepareLimitOrderPostingError,Uc as PrepareMarketOrderError,Yc as PrepareMarketOrderPostingError,je as PrepareMergeComboPositionError,ie as PrepareMergeMarketPositionError,he as PrepareMergePositionsError,Jd as PreparePerpsDepositError,me as PrepareRedeemComboPositionError,le as PrepareRedeemMarketPositionsError,ke as PrepareRedeemPositionsError,ge as PrepareSplitComboPositionError,fe as PrepareSplitMarketPositionError,ee as PrepareSplitPositionError,Qa as PrepareTradingApprovalsError,Ie as RedeemPositionsError,sb as ResolveConditionByTokenError,gb as RevokeBuilderApiKeyError,Id as RevokePerpsCredentialsError,Pe as RfqCancelQuoteError,Oe as RfqCancelQuoteRejectedError,Ue as RfqConfirmationDecision,Re as RfqConfirmationError,Qe as RfqConfirmationRejectedError,Ve as RfqDirection,We as RfqErrorCode,Xe as RfqExecutionStatus,Ne as RfqQuoteError,Me as RfqQuoteRejectedError,Ye as RfqRequestedSizeUnit,Ze as RfqSide,$e as SearchError,_e as SearchSort,Sa as SetupTradingApprovalsError,se as SplitComboPositionError,re as SplitMarketPositionError,qe as SplitPositionError,wf as TransferErc20Error,_ as UpdateBalanceAllowanceError,pd as UpdatePerpsLeverageError,Ha as WaitForGaslessTransactionError,Ld as WithdrawFromPerpsError,Pa as approveErc1155ForAll,La as approveErc20,Hc as cancelAll,Jc as cancelMarketOrders,Dc as cancelOrder,Fc as cancelOrders,Va as createApiKey,db as createBuilderApiKey,fd as createLimitOrder,bd as createMarketOrder,Za as createOrDeriveApiKey,bb as deleteApiKey,Da as deployDepositWallet,Pd as depositToPerps,Xa as deriveApiKey,be as downloadAccountingSnapshot,X as dropNotifications,Lc as estimateMarketPrice,$a as fetchApiKeys,Z as fetchBalanceAllowance,fb as fetchBuilderApiKeys,xb as fetchBuilderFeeRates,jc as fetchBuilderVolume,N as fetchClosedOnlyMode,Xb as fetchCommentsById,bc as fetchEvent,fc as fetchEventLiveVolume,dc as fetchEventTags,ya as fetchExecuteParams,Lb as fetchLastTradePrice,Nb as fetchLastTradePrices,tc as fetchMarket,vb as fetchMarketInfo,vc as fetchMarketTags,lb as fetchMidpoint,nb as fetchMidpoints,rb as fetchNegRisk,V as fetchNotifications,R as fetchOrder,Db as fetchOrderBook,Fb as fetchOrderBooks,ba as fetchOrderScoring,da as fetchOrdersScoring,yd as fetchPerpsBook,Gd as fetchPerpsFees,sd as fetchPerpsInstruments,ud as fetchPerpsTicker,wd as fetchPerpsTickers,Zd as fetchPortfolioValue,zb as fetchPrice,Pb as fetchPriceHistory,Bb as fetchPrices,Le as fetchPublicProfile,rf as fetchRelatedTagResources,pf as fetchRelatedTags,la as fetchRewardPercentages,ef as fetchSeries,if as fetchSportsMarketTypes,Hb as fetchSpread,Jb as fetchSpreads,nf as fetchTag,pb as fetchTickSize,ha as fetchTotalEarningsForUserForDay,$d as fetchTradedMarketCount,Ea as fetchTransaction,Aa as isWalletDeployed,T as listAccountTrades,pa as listActivity,hc as listBuilderLeaderboard,jb as listBuilderTrades,Vd as listClosedPositions,ra as listComboActivity,rc as listComboMarkets,Xd as listComboPositions,Vb as listComments,Zb as listCommentsByUserAddress,Rb as listCurrentRewards,$b as listEvents,nc as listMarketClarifications,xc as listMarketHolders,Bc as listMarketPositions,Tb as listMarketRewards,pc as listMarkets,zc as listOpenInterest,P as listOpenOrders,Ad as listPerpsCandles,Cd as listPerpsFundingHistory,Ed as listPerpsTrades,Td as listPositions,cf as listSeries,gf as listSports,lf as listTags,tf as listTeams,lc as listTraderLeaderboard,na as listTrades,ja as listUserEarningsAndMarketsConfig,fa as listUserEarningsForDay,De as mergeComboPosition,Ce as mergeMarketPosition,Ee as mergePositions,Md as openPerpsSession,Te as openRfqSession,hd as placeLimitOrder,dd as placeMarketOrder,Pc as postOrder,Qc as postOrders,Na as prepareErc1155ApprovalForAll,Ja as prepareErc20Approval,vf as prepareErc20Transfer,Ga as prepareGaslessTransaction,Xc as prepareLimitOrder,$c as prepareLimitOrderPosting,Vc as prepareMarketOrder,Zc as prepareMarketOrderPosting,xe as prepareMergeComboPosition,we as prepareMergeMarketPosition,ye as prepareMergePositions,Od as preparePerpsDeposit,Ge as prepareRedeemComboPosition,Fe as prepareRedeemMarketPositions,He as prepareRedeemPositions,oe as prepareSplitComboPosition,ne as prepareSplitMarketPosition,pe as prepareSplitPosition,Ra as prepareTradingApprovals,Je as redeemPositions,tb as resolveConditionByToken,Mc as resolveEstimatedMarketPrice,hb as revokeBuilderApiKey,Nd as revokePerpsCredentials,af as search,Ta as setupTradingApprovals,Tc as signOrder,ue as splitComboPosition,te as splitMarketPosition,ve as splitPosition,jf as subscribe,xf as transferErc20,$ as updateBalanceAllowance,Qd as withdrawFromPerps}from'../chunk-IBUXKB4V.js';import'../chunk-E2CLUN5M.js';//# sourceMappingURL=index.js.map
2
2
  //# sourceMappingURL=index.js.map
@@ -0,0 +1,2 @@
1
+ import {k,e,d,j,c,b,a,f as f$1,g as g$1,h,i}from'./chunk-E2CLUN5M.js';import {PaginationCursorSchema,ComboConditionIdSchema,TransactionIdSchema,EvmAddressSchema,BuilderCodeSchema,TokenIdSchema,CtfConditionIdSchema,OrderSideSchema,CommentParentEntityTypeSchema,EventIdSchema,CommentIdSchema,IsoDateTimeStringSchema,IsoCalendarDateStringSchema,PositionIdSchema,OrderType,PositiveDecimalNumberSchema,OrderSide,TxHashSchema,MarketIdSchema,toDecimalString,toComboConditionId,toPositionId,toPaginationCursor}from'@polymarket/bindings';import {AssetTypeSchema,PriceHistoryIntervalSchema,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,PriceHistorySchema,PaginatedCurrentRewardsSchema,PaginatedMarketRewardsSchema,CancelOrdersResponseSchema,OrderResponseSchema,OrderResponsesSchema}from'@polymarket/bindings/clob';import {isHexString,expectNonEmptyArray,isPrivateKey,expectEvmAddress,PolymarketError,expectHexString,isSameEvmAddress,never,unwrap,invariant,delay,expectEvmSignature,ZERO_ADDRESS,expectErc1271Signature,ResultAsync,setNonBlockingInterval,setNonBlockingTimeout,expectPresent,expectPrivateKey,isPresent,ok,err}from'@polymarket/types';import {z}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 Xt from'ky';import {SideSchema,ActivityTypeSchema,TimePeriodSchema,LeaderboardOrderBySchema,LeaderboardCategorySchema,ComboPositionStatusSchema,ListTradesResponseSchema,ListActivityResponseSchema,ListComboActivityResponseSchema,FetchEventLiveVolumeResponseSchema,ListBuilderLeaderboardResponseSchema,ListBuilderVolumeResponseSchema,ListTraderLeaderboardResponseSchema,ListMarketHoldersResponseSchema,ListOpenInterestResponseSchema,ListMarketPositionsResponseSchema,ListPositionsResponseSchema,ListClosedPositionsResponseSchema,ListComboPositionsResponseSchema,FetchPortfolioValueResponseSchema,TradedSchema}from'@polymarket/bindings/data';export{ComboPositionOutcome as ce,ComboPositionStatus as de,ComboActivityType as sa}from'@polymarket/bindings/data';import {RelayerTransactionType,RelayerExecuteRequestSchema,RelayerTransactionState,RelayerExecuteParamsSchema,RelayerDeployedResponseSchema,GaslessTransactionSchema,RelayerExecuteResponseSchema}from'@polymarket/bindings/relayer';import {ListComboMarketsResponseSchema}from'@polymarket/bindings/rfq';export{RfqConfirmationDecision as Ue,RfqDirection as Ve,RfqErrorCode as We,RfqExecutionStatus as Xe,RfqRequestedSizeUnit as Ye,RfqSide as Ze}from'@polymarket/bindings/rfq';import {PerpsPnlIntervalSchema,PerpsWithdrawalStatusSchema,PerpsDepositStatusSchema,PerpsInstrumentIdSchema,PerpsClientOrderIdSchema,PerpsOrderIdSchema,PerpsDecimalInputSchema,PerpsTimeInForce,PerpsCommandAckSchema,PerpsInstrumentCategorySchema,PerpsKlineIntervalSchema,PerpsTradeIdSchema,PerpsPostOrderAckSchema,PerpsTpSlKind,PerpsTpSlScope,PerpsCancelOrderResultSchema,PerpsUpdateLeverageResultSchema,FetchPerpsBalancesResponseSchema,FetchPerpsPortfolioResponseSchema,FetchPerpsAccountStatsResponseSchema,FetchPerpsAccountConfigResponseSchema,FetchPerpsOpenOrdersResponseSchema,FetchPerpsOrdersResponseSchema,ListPerpsFillsResponseSchema,ListPerpsFundingPaymentsResponseSchema,ListPerpsDepositsResponseSchema,ListPerpsWithdrawalsResponseSchema,ListPerpsEquityHistoryResponseSchema,ListPerpsPnlHistoryResponseSchema,PerpsCancelAllOrdersResponseSchema,FetchPerpsInstrumentsResponseSchema,FetchPerpsTickersResponseSchema,FetchPerpsStatisticsResponseSchema,PerpsBookSchema,FetchPerpsCandlesResponseSchema,FetchPerpsFundingHistoryResponseSchema,FetchPerpsTradesResponseSchema,FetchPerpsFeesResponseSchema,PerpsDeleteProxyResponseSchema,PerpsWithdrawResponseSchema,PerpsCreateProxyResponseSchema,PerpsCredentialsResponseSchema}from'@polymarket/bindings/perps';import {encode}from'@msgpack/msgpack';import {PerpsSessionUpdateEventSchema}from'@polymarket/bindings/subscriptions';import {pushable}from'it-pushable';import aP from'it-merge';function l(e,r){let t=r.safeParse(e);if(t.success)return t.data;throw a.fromZodError(t.error)}var O=z.number().int().positive(),Yt=z.object({offset:z.number().int().min(0),pageSize:O});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 B(e){return toPaginationCursor(btoa(JSON.stringify(Yt.parse(e))))}function U(e,r){if(e===void 0)return {offset:0,pageSize:r};try{return Yt.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=>Ba(t.url,e,o))}}function Qt(e){return ResultAsync.fromPromise(e.blob(),()=>new b(`Received unreadable binary response from ${e.url}`))}function Ba(e,r,t){let o=r.safeParse(t);return o.success?ok(o.data):err(b.fromZodError(o.error,{endpoint:e}))}var eo=class{#e;constructor({url:r}){this.#e=r;}async ethCall(r){let t=await this.#o({jsonrpc:"2.0",id:1,method:"eth_call",params:[{to:r.to,data:r.data},"latest"]});if("error"in t)throw new d(`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(!io(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=oo(r.gasPrice)),r.value!==void 0&&(t.value=oo(r.value));let o=await this.#o({jsonrpc:"2.0",id:1,method:"eth_estimateGas",params:[t]});if("error"in o)throw new d(`JSON-RPC eth_estimateGas failed: ${o.error.message}`,{cause:o.error,status:200});return BigInt(to(o.result,"eth_estimateGas"))}async#r(r){if(r.length===1)return [await this.ethCall(r[0])];try{return await this.#t(r)}catch(t){if(!(t instanceof d)||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#t(r){let t=await this.#n(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 d(`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 d(`JSON-RPC eth_call failed: ${y.error.message}`,{cause:y.error,status:200});return to(y.result)})}async#o(r){let t;try{t=await Xt.post(this.#e,{json:r,throwHttpErrors:!1});}catch(n){throw c.fromError(n)}if(!t.ok)throw new d(`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(!ro(o))throw new b("Unexpected JSON-RPC response shape");return o}async#n(r){let t;try{t=await Xt.post(this.#e,{json:r,throwHttpErrors:!1});}catch(n){throw c.fromError(n)}if(!t.ok)throw new d(`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=>ro(n)))throw new b("Unexpected JSON-RPC response shape");return o}};function no(e){if(!(e instanceof d)||!so(e.cause))return false;let r=[e.cause.message,Ua(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 ro(e){return !ao(e)||e.jsonrpc!=="2.0"?false:"error"in e?so(e.error):"result"in e}function so(e){return ao(e)&&typeof e.code=="number"&&typeof e.message=="string"}function ao(e){return typeof e=="object"&&e!==null}function io(e){return /^0x[a-fA-F0-9]*$/.test(e)}function to(e,r="eth_call"){if(typeof e!="string"||!io(e))throw new b(`Expected JSON-RPC ${r} result to be a hex string`);return e}function oo(e){return `0x${e.toString(16)}`}function Ua(e){if(e===void 0)return "";if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return ""}}function HP(e,r,t){return {signer:r,wallet:t,walletType:ti(e,r,t)}}function ce(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 po(e){let r=ce(e.walletType);return {maker:e.wallet,signatureType:r,signer:r===SignatureType.POLY_1271?e.wallet:e.signer}}var za="3d3d606380380380913d393d73%s5af4602a57600080fd5b602d8060366000396000f3363d3d373d3d3d363d73%s5af43d82803e903d91602b57fd5bf352e831dd00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000000";function ja(e){let r=za.replace("%s",e.proxyFactory.slice(2).toLowerCase()).replace("%s",e.proxyImplementation.slice(2).toLowerCase());return expectHexString(Hash.keccak256(`0x${r}`))}function Wa(e,r){return expectEvmAddress(ContractAddress.fromCreate2({bytecodeHash:ja(r),from:r.proxyFactory,salt:Hash.keccak256(AbiParameters.encodePacked(["address"],[e]))}))}function Ha(e,r){return expectEvmAddress(ContractAddress.fromCreate2({bytecodeHash:r.safeInitCodeHash,from:r.safeFactory,salt:Hash.keccak256(AbiParameters.encode([{name:"address",type:"address"}],[e]))}))}var _a="0xcc3735a920a3ca505d382bbc545af43d6000803e6038573d6000fd5b3d6000f3",Na="0x5155f3363d3d373d3d363d7f360894a13ba1a3210667c828492db98dca3e2076",Ga=0x61003d3d8160233d3973n;function co(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:Ja(r.depositWalletImplementation,o),from:r.depositWalletFactory,salt:Hash.keccak256(o)}))}var Ka="0xb3582b35133d50545afa5036515af43d6000803e604d573d6000fd5b3d6000f3",$a="0x1b60e01b36527fa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6c",Va="0x60195155f3363d3d373d3d363d602036600436635c60da",Za=0x6100523d8160233d3973n,Ya="0x49493a4d";function uo(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:Qa(r.depositWalletBeacon,o),from:r.depositWalletFactory,salt:Hash.keccak256(o)}))}function Ja(e,r){let t=BigInt((r.length-2)/2),o=Ga+(t<<56n);return expectHexString(Hash.keccak256(Bytes.concat(Bytes.fromNumber(o,{size:10}),Bytes.fromHex(e),Bytes.fromHex("0x6009"),Bytes.fromHex(Na),Bytes.fromHex(_a),Bytes.fromHex(r)),{as:"Hex"}))}function Qa(e,r){let t=BigInt((r.length-2)/2),o=Za+(t<<56n);return expectHexString(Hash.keccak256(Bytes.concat(Bytes.fromNumber(o,{size:10}),Bytes.fromHex(e),Bytes.fromHex(Va),Bytes.fromHex($a),Bytes.fromHex(Ka),Bytes.fromHex(r)),{as:"Hex"}))}async function Xa(e,r){try{let t=await e.ethCall({to:r,data:Ya});return ri(t)}catch(t){if(no(t))return ZERO_ADDRESS;throw t}}async function ei(e,r){let t=await Xa(e,r);return !isSameEvmAddress(t,ZERO_ADDRESS)}async function mo(e,r,t){return await ei(e,t.depositWalletFactory)?uo(r,t):co(r,t)}function ri(e){return e.length<66?ZERO_ADDRESS:expectEvmAddress(`0x${e.slice(-40)}`)}function ti(e,r,t){if(isSameEvmAddress(t,r))return WalletType.EOA;let o=e.walletDerivation;if(isSameEvmAddress(t,uo(r,o)))return WalletType.DEPOSIT_WALLET;if(isSameEvmAddress(t,co(r,o)))return WalletType.DEPOSIT_WALLET;if(isSameEvmAddress(t,Ha(r,o)))return WalletType.GNOSIS_SAFE;if(isSameEvmAddress(t,Wa(r,o)))return WalletType.POLY_PROXY;never(`Wallet ${t} does not match the signer ${r} or any supported deterministic wallet address.`);}function g(e,r){if(oi(r))return ni(e,r.exceptions);let t=new URLSearchParams;for(let[o,n]of Object.entries(r)){let s=e[o];if(s!==void 0){if(lo(s)){for(let a of s)t.append(n,Le(a));continue}t.append(n,Le(s));}}return t}function R(e={}){return {format:"snake_case",exceptions:e}}function H(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(Le).join(","));continue}r.append(t,Le(o));}return r}function oi(e){return "format"in e}function ni(e,r){let t=new URLSearchParams;for(let[o,n]of Object.entries(e)){if(n===void 0)continue;let s=r[o]??si(o);if(lo(n)){for(let a of n)t.append(s,Le(a));continue}t.append(s,Le(n));}return t}function lo(e){return Array.isArray(e)}function si(e){return e.replace(/[A-Z]/g,r=>`_${r.toLowerCase()}`)}function Le(e){return String(e)}var rg=k(e,d,j,c,b);async function tg(e){return (await unwrap(e.secureClob.get("/auth/ban-status/closed-only").andThen(f(ClosedOnlyModeSchema)))).closedOnly}var Ri=z.object({tokenId:z.string().optional(),cursor:PaginationCursorSchema.optional(),id:z.string().optional(),market:z.string().optional()}).default({}),og=k(e,d,j,c,b,a);function ng(e,r){let{cursor:t,...o}=l(r,Ri);return x(n=>e.secureClob.get("/data/orders",{params:g({...o,nextCursor:n},R({tokenId:"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),totalCount:s.count})),t)}var Ei=z.object({orderId:z.string()}),sg=k(e,d,j,c,b,a);async function ag(e,r){let t=l(r,Ei);return unwrap(e.secureClob.get(`/data/order/${t.orderId}`).andThen(f(OpenOrderSchema)))}var hi={after:z.string().optional(),tokenId:z.string().optional(),before:z.string().optional(),cursor:PaginationCursorSchema.optional(),id:z.string().optional(),makerAddress:z.string().optional(),market:z.string().optional()},Si=z.object(hi).default({}),ig=k(e,d,j,c,b,a);function pg(e,r){let{cursor:t,...o}=l(r,Si);return x(n=>e.secureClob.get("/data/trades",{params:g({...o,nextCursor:n},R({tokenId:"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),totalCount:s.count})),t)}var cg=k(e,d,j,c,b),Ti=z.object({ids:z.array(z.string()).min(1)});async function dg(e){let r=ce(e.account.walletType);return unwrap(e.secureClob.get("/notifications",{params:g({signatureType:r},R())}).andThen(f(NotificationsResponseSchema)))}var ug=k(e,d,j,c,b,a);async function mg(e,r){let t=l(r,Ti),o=ce(e.account.walletType),n=g({ids:t.ids.join(","),signatureType:o},R());await unwrap(e.secureClob.del("/notifications",{params:n}));}var xi=z.object({assetType:AssetTypeSchema,tokenId:z.string().optional()}),lg=k(e,d,j,c,b,a);async function Gr(e,r){let t=l(r,xi),o=ce(e.account.walletType);return unwrap(e.secureClob.get("/balance-allowance",{params:g({...t,signatureType:o},R())}).andThen(f(BalanceAllowanceResponseSchema)))}var Ci=z.object({assetType:AssetTypeSchema,tokenId:z.string().optional()}),yg=k(e,d,j,c,b,a);async function fo(e,r){let t=l(r,Ci),o=ce(e.account.walletType),n=g({...t,signatureType:o},R());return await unwrap(e.secureClob.get("/balance-allowance/update",{params:n})),Gr(e,t)}var bi=z.object({orderId:z.string()}),fg=k(e,d,j,c,b,a);async function Pg(e,r){let t=l(r,bi);return (await unwrap(e.secureClob.get("/order-scoring",{params:g(t,R())}).andThen(f(OrderScoringResponseSchema)))).scoring}var Ii=z.object({orderIds:z.array(z.string())}),gg=k(e,d,j,c,b,a);async function Rg(e,r){let o=l(r,Ii).orderIds;return unwrap(e.secureClob.post("/orders-scoring",{json:o}).andThen(f(OrdersScoringResponseSchema)))}var Po=z.object({cursor:PaginationCursorSchema.optional(),date:z.string()}),Eg=k(e,d,j,c,b,a);function hg(e,r){let{cursor:t,...o}=l(r,Po),n=ce(e.account.walletType);return x(s=>e.secureClob.get("/rewards/user",{params:g({...o,nextCursor:s,signatureType:n},R())}).andThen(f(UserEarningsPageSchema)).map(a=>({items:a.data,hasMore:a.nextCursor!==END_CURSOR,nextCursor:a.nextCursor===END_CURSOR?void 0:toPaginationCursor(a.nextCursor),totalCount:a.count})),t)}var Sg=k(e,d,j,c,b,a);async function Tg(e,r){let t=l(r,Po),o=ce(e.account.walletType);return unwrap(e.secureClob.get("/rewards/user/total",{params:g({...t,signatureType:o},R())}).andThen(f(TotalUserEarningsResponseSchema)))}var ki=z.object({cursor:PaginationCursorSchema.optional(),date:z.string(),noCompetition:z.boolean().optional(),orderBy:z.string().optional(),pageSize:O.max(500).default(100),position:z.string().optional()}),xg=k(e,d,j,c,b,a);function Cg(e,r){let{cursor:t,...o}=l(r,ki),n=ce(e.account.walletType);return x(s=>e.secureClob.get("/rewards/user/markets",{params:g({...o,nextCursor:s,signatureType:n},R())}).andThen(f(UserRewardsEarningsPageSchema)).map(a=>({items:a.data,hasMore:a.nextCursor!==END_CURSOR,nextCursor:a.nextCursor===END_CURSOR?void 0:toPaginationCursor(a.nextCursor),totalCount:a.count})),t)}var bg=k(e,d,j,c,b);async function Ig(e){let r=ce(e.account.walletType);return unwrap(e.secureClob.get("/rewards/user/percentages",{params:g({signatureType:r},R())}).andThen(f(RewardsPercentagesSchema)))}var wi=z.enum(["CASH","TOKENS"]),Li=z.object({cursor:PaginationCursorSchema.optional(),pageSize:O.default(20),takerOnly:z.boolean().optional(),filterType:wi.optional(),filterAmount:z.number().optional(),market:z.array(z.string()).optional(),eventId:z.array(z.number().int()).optional(),user:z.string().optional(),side:SideSchema.optional(),start:z.number().int().min(0).optional(),end:z.number().int().min(0).optional()}).refine(e=>!(e.market&&e.eventId),{message:"Provide market or eventId, not both",path:["eventId"]}).refine(e=>e.filterType===void 0==(e.filterAmount===void 0),{message:"Provide filterType and filterAmount together",path:["filterAmount"]}),Bg=k(e,d,c,b,a);function Ug(e,r={}){let{cursor:t,pageSize:o,...n}=l(r,Li);return x(s=>{let a=U(s,o);return e.data.get("/trades",{params:H({...n,limit:a.pageSize+1,offset:a.offset})}).andThen(f(ListTradesResponseSchema)).map(y=>{let P=y.length>a.pageSize;return {items:y.slice(0,a.pageSize),hasMore:P,nextCursor:P?B({offset:a.offset+a.pageSize,pageSize:a.pageSize}):void 0}})},t)}var Fi=z.enum(["TIMESTAMP","TOKENS","CASH"]),Mi=z.enum(["ASC","DESC"]),Bi=z.object({cursor:PaginationCursorSchema.optional(),pageSize:O.default(20),user:z.string(),market:z.array(z.string()).optional(),eventId:z.array(z.number().int()).optional(),type:z.array(ActivityTypeSchema).optional(),start:z.number().int().min(0).optional(),end:z.number().int().min(0).optional(),sortBy:Fi.optional(),sortDirection:Mi.optional(),side:SideSchema.optional()}).refine(e=>!(e.market&&e.eventId),{message:"Provide market or eventId, not both",path:["eventId"]}),Dg=k(e,d,c,b,a);function zg(e,r){let{cursor:t,pageSize:o,...n}=l(r,Bi);return x(s=>{let a=U(s,o);return e.data.get("/activity",{params:H({...n,limit:a.pageSize+1,offset:a.offset})}).andThen(f(ListActivityResponseSchema)).map(y=>{let P=y.length>a.pageSize;return {items:y.slice(0,a.pageSize),hasMore:P,nextCursor:P?B({offset:a.offset+a.pageSize,pageSize:a.pageSize}):void 0}})},t)}var Ui=z.union([ComboConditionIdSchema,z.array(ComboConditionIdSchema)]),Di=z.object({cursor:PaginationCursorSchema.optional(),pageSize:O.default(50),user:z.string(),conditionId:Ui.optional()}),jg=k(e,d,c,b,a);function Wg(e,r){let{cursor:t,pageSize:o,conditionId:n,...s}=l(r,Di);return x(a=>{let y=g({...s,limit:o,cursor:a},R());return zi(y,n),e.data.get("/v1/activity/combos",{params:y}).andThen(f(ListComboActivityResponseSchema)).map(P=>{let v=P.pagination.nextCursor??void 0;return {items:P.activity,hasMore:v!==void 0,nextCursor:v}})},t)}function zi(e,r){r!==void 0&&e.append("market_id",Array.isArray(r)?r.join(","):r);}var Wi=64,Hi=/^0x[0-9a-fA-F]{62}$/,_i=/^0x[0-9a-fA-F]{64}$/,$r="0x0000000000000000000000000000000000000000000000000000000000000000",Ni=AbiFunction.from("function approve(address spender, uint256 amount)"),ho=AbiFunction.from("function allowance(address owner, address spender) view returns (uint256)"),Gi=AbiFunction.from("function transfer(address recipient, uint256 amount)"),Ki=AbiFunction.from("function deposit(address token, uint256 amount, address to)"),$i=AbiFunction.from("function setApprovalForAll(address operator, bool approved)"),So=AbiFunction.from("function isApprovedForAll(address account, address operator) view returns (bool)"),To=AbiFunction.from("function balanceOf(address account, uint256 id) view returns (uint256)"),xo=AbiFunction.from("function balanceOfBatch(address[] accounts, uint256[] ids) view returns (uint256[])"),Vi=AbiFunction.from("function splitPosition(address collateralToken, bytes32 parentCollectionId, bytes32 conditionId, uint256[] partition, uint256 amount)"),Zi=AbiFunction.from("function mergePositions(address collateralToken, bytes32 parentCollectionId, bytes32 conditionId, uint256[] partition, uint256 amount)"),Yi=AbiFunction.from("function redeemPositions(address collateralToken, bytes32 parentCollectionId, bytes32 conditionId, uint256[] indexSets)"),Ji=AbiFunction.from("function split(bytes31 conditionId, uint256 amount)"),Qi=AbiFunction.from("function merge(bytes31 conditionId, uint256 amount)"),Xi=AbiFunction.from("function redeem(bytes31 conditionId, uint256 outcomeIndex, uint256 amount)"),ep=AbiFunction.from("function prepareCondition(uint256[] legs) returns (bytes31)"),rp=AbiFunction.from("function multiSend(bytes)"),tp=AbiFunction.from("function proxy((uint8 typeCode, address to, uint256 value, bytes data)[] calls) returns (bytes[])"),Co=[1n,2n],op=[1n,2n],Y=(1n<<256n)-1n,Vg=k(a);function mr(e,r,t){if(t<0n)throw new a("Approval amount must be non-negative");if(t>Y)throw new a("Approval amount exceeds uint256 range");return {data:np(r,t),to:e}}function bo(e,r,t){return {data:AbiFunction.encodeData(ho,[r,t]),to:e}}function Io(e){return AbiFunction.decodeResult(ho,e)}function lr(e,r,t){return {data:sp(r,t),to:e}}function ko(e,r,t){return {data:AbiFunction.encodeData(So,[r,t]),to:e}}function qo(e){return AbiFunction.decodeResult(So,e)}function vo(e,r,t){return {data:AbiFunction.encodeData(To,[r,ge(BigInt(t),"Position ID")]),to:e}}function Ao(e){return AbiFunction.decodeResult(To,e)}function Vr(e,r,t){return {data:AbiFunction.encodeData(xo,[t.map(()=>r),t.map(o=>ge(BigInt(o),"id"))]),to:e}}function Zr(e){return AbiFunction.decodeResult(xo,e)}var Zg=k(a);function Yr(e,r,t){if(t<0n)throw new a("Transfer amount must be non-negative");if(t>Y)throw new a("Transfer amount exceeds uint256 range");return {data:ap(r,t),to:e}}var Yg=k(a);function Oo(e,r,t,o){if(t<=0n)throw new a("Perps deposit amount must be positive");return {data:AbiFunction.encodeData(Ki,[r,ge(t,"Perps deposit amount"),o]),to:e}}var Jg=k(a),Qg=k(a);function wo(e,r,t,o){return {data:ip(r,t,o),to:e}}var Xg=k(a);function Lo(e,r,t,o){return {data:pp(r,t,o),to:e}}function Fo(e,r,t){return {data:cp(r,t),to:e}}var eR=k(a);function Mo(e,r,t){return {data:AbiFunction.encodeData(Ji,[Qr(r),ge(t,"Split amount")]),to:e}}var rR=k(a);function Bo(e,r,t){return {data:AbiFunction.encodeData(Qi,[Qr(r),ge(t,"Merge amount")]),to:e}}var tR=k(a);function Uo(e,r,t,o){return {data:AbiFunction.encodeData(Xi,[Qr(r),BigInt(dp(t)),ge(o,"Redeem amount")]),to:e}}var oR=k(a);function Jr(e,r){return {data:AbiFunction.encodeData(ep,[r.map(t=>ge(t,"Leg position ID"))]),to:e}}function np(e,r){return invariant(r>=0n,"Approval amount must be non-negative"),AbiFunction.encodeData(Ni,[e,r])}function sp(e,r){return AbiFunction.encodeData($i,[e,r])}function ap(e,r){return AbiFunction.encodeData(Gi,[e,r])}function ip(e,r,t){return AbiFunction.encodeData(Vi,[e,$r,r,Co,ge(t,"Split amount")])}function pp(e,r,t){return AbiFunction.encodeData(Zi,[e,$r,r,Co,ge(t,"Merge amount")])}function cp(e,r){return AbiFunction.encodeData(Yi,[e,$r,r,op])}function ge(e,r){if(e<0n)throw new a(`${r} must be non-negative`);if(e>Y)throw new a(`${r} exceeds uint256 range`);return e}function Qr(e){if(Hi.test(e))return e.toLowerCase();if(_i.test(e)){let r=e.toLowerCase();if(r.endsWith("00")||r.endsWith("01"))return r.slice(0,Wi)}throw new a("Protocol v2 condition ID must be bytes31, or bytes32 with a binary outcome byte")}function dp(e){if(e!==0&&e!==1)throw new a("Protocol v2 outcome index must be 0 or 1");return e}function Do(e){return AbiFunction.encodeData(tp,[e.map(r=>({typeCode:1,to:r.to,value:r.value??0n,data:r.data}))])}function zo(e){let r=e.map(t=>up(t));return AbiFunction.encodeData(rp,[r.length===0?"0x":AbiParameters.encodePacked(Array.from({length:r.length},()=>"bytes"),r)])}function up(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 iR=k(e,d,f$1,g$1,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}k(h,j);k(h,j);function mR(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 _(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 jo(){return {kind:"requestAddress"}}function G(e,r){return {chainId:e,...r}}var Cp=[{name:"chainId",type:"uint256"},{name:"verifyingContract",type:"address"}],bp=[{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"}],Ip="DepositWallet",kp="1",qp=600,vp=[{name:"target",type:"address"},{name:"value",type:"uint256"},{name:"data",type:"bytes"}],Ap=[{name:"wallet",type:"address"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"},{name:"calls",type:"Call[]"}],Op=z.object({address:z.string(),type:z.enum(RelayerTransactionType)}),kR=k(e,d,c,b,a);async function ot(e,r){let t=l(r,Op);return unwrap(e.relayer.get("/v1/account/transactions/params",{params:g(t,{address:"address",type:"type"})}).andThen(f(RelayerExecuteParamsSchema)))}var wp=z.object({transactionId:TransactionIdSchema}),Lp=z.object({wallet:EvmAddressSchema,type:z.enum(WalletType)}),qR=k(e,d,c,b,a);async function vR(e,r){let t=await Fp(e,r);return t.type===WalletType.EOA?false:unwrap(e.relayer.get("/deployed",{params:g({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 Fp(e,r){if(r!==void 0)return l(r,Lp);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 mo(e.rpc,e.account.signer,e.environment.walletDerivation),type:WalletType.DEPOSIT_WALLET}}var K=z.string().max(500),Wo=10,AR=k(e,d,c,b,a);async function OR(e){return invariant(e.supportsGasless,"Deposit Wallet deployment requires a Relayer API Key or Builder API Key in the client configuration."),Pr(e,{from:e.account.signer,metadata:"Deploy Deposit Wallet",to:e.environment.walletDerivation.depositWalletFactory,type:RelayerTransactionType.WALLET_CREATE})}async function Mp(e,r){let t=l(r,wp);return unwrap(e.relayer.get(`/v1/account/transactions/${t.transactionId}`).andThen(f(GaslessTransactionSchema)))}var Bp=z.object({data:z.custom(isHexString),to:EvmAddressSchema,value:z.bigint().optional()}),Up=z.object({calls:z.array(Bp).min(1).transform(e=>expectNonEmptyArray(e)),metadata:K}),wR=k(e,d,c,b,a);async function J(e,r){let t=l(r,Up);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 jo());invariant(o===e.account.signer,"Wallet client address does not match the authenticated signer");for(let n=0;n<=Wo;n+=1)try{switch(e.account.walletType){case WalletType.POLY_PROXY:return yield*Dp(e,t);case WalletType.DEPOSIT_WALLET:return yield*zp(e,t);case WalletType.GNOSIS_SAFE:return yield*jp(e,t)}invariant(!1,"Unsupported wallet type for gasless transaction");}catch(s){if(!Wp(s)||n===Wo)throw s;await delay(e.environment.relayerPollFrequencyMs);}invariant(false,"Expected gasless transaction retry loop to return");}.call(null)}async function*Dp(e,r){let t=await ot(e,{address:e.account.signer,type:RelayerTransactionType.PROXY}),o=e.environment.walletDerivation.proxyFactory,n=Do(r.calls),s="0",a="0",y=(await e.rpc.ethEstimateGas({data:n,from:e.account.signer,to:o})).toString(),P=e.environment.contracts.relayHub,v=t.address,A=Vp(e.account.signer,o,n,s,a,y,t.nonce,P,v),V=expectEvmSignature(yield No(A));return Pr(e,{data:n,from:e.account.signer,metadata:r.metadata,nonce:t.nonce,proxyWallet:e.account.wallet,signature:V,signatureParams:{gasLimit:y,gasPrice:a,relay:v,relayHub:P,relayerFee:s},to:o,type:RelayerTransactionType.PROXY})}async function*zp(e,r){let t=await ot(e,{address:e.account.signer,type:RelayerTransactionType.WALLET}),o=r.calls.map(Hp),n=`${Math.floor(Date.now()/1e3)+qp}`,s=expectEvmSignature(yield $p(_p({calls:o,chainId:e.environment.chainId,deadline:n,nonce:t.nonce,wallet:e.account.wallet}))),a={depositWalletParams:{calls:o,deadline:n,depositWallet:e.account.wallet},from:e.account.signer,metadata:r.metadata,nonce:t.nonce,signature:s,to:e.environment.walletDerivation.depositWalletFactory,type:RelayerTransactionType.WALLET};return Pr(e,a)}async function*jp(e,r){let t=await ot(e,{address:e.account.signer,type:RelayerTransactionType.SAFE}),o=Np(r.calls,e.environment.contracts.safeMultisend),n=Kp({chainId:e.environment.chainId,data:o.data,nonce:t.nonce,operation:o.operation,safeAddress:e.account.wallet,to:o.to,value:o.value}),s=expectEvmSignature(yield No(expectHexString(TypedData.getSignPayload(n))));return Pr(e,{data:o.data,from:e.account.signer,metadata:r.metadata,nonce:t.nonce,proxyWallet:e.account.wallet,signature:Zp(s),signatureParams:Gp(o.operation),to:o.to,type:RelayerTransactionType.SAFE,value:o.value>0n?`${o.value}`:void 0})}async function Pr(e,r){let t=l(r,RelayerExecuteRequestSchema),o=await unwrap(e.relayer.post("/submit",{json:t}).andThen(f(RelayerExecuteResponseSchema)));return new et(e,o)}function Wp(e$1){if(e$1 instanceof e)return true;if(!(e$1 instanceof d)||e$1.status!==400)return false;if(/wallet busy/i.test(e$1.message)&&/active action/i.test(e$1.message)||/wallet has in-flight action/i.test(e$1.message))return true;let r=/batch nonce\s+(\d+)\s+does not match on-chain nonce\s+(\d+)/i.exec(e$1.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 Hp(e){return {data:e.data,target:e.to,value:`${e.value??0n}`}}function _p(e){return {domain:{chainId:e.chainId,name:Ip,verifyingContract:e.wallet,version:kp},message:{calls:e.calls.map(r=>({data:r.data,target:r.target,value:BigInt(r.value)})),deadline:BigInt(e.deadline),nonce:BigInt(e.nonce),wallet:e.wallet},primaryType:"Batch",types:{Batch:Ap,Call:vp}}}function Np(e,r){if(e.length===1){let[t]=e;return {data:t.data,operation:0,to:t.to,value:t.value??0n}}return {data:zo(e),operation:1,to:r,value:0n}}function Gp(e){return {baseGas:"0",gasPrice:"0",gasToken:ZERO_ADDRESS,operation:`${e}`,refundReceiver:ZERO_ADDRESS,safeTxnGas:"0"}}function Kp(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:Cp,SafeTx:bp}}}function No(e){return {kind:"signGaslessMessage",payload:e}}function $p(e){return {kind:"signGaslessTypedData",payload:e}}function Vp(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 Zp(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 LR=k(e,d,c,b,a,f$1,g$1),et=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 Mp(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 g$1(t.errorMsg??`Transaction ${t.transactionId} reached terminal state ${t.state}`);r+=1,await delay(this.#e.environment.relayerPollFrequencyMs);}throw new f$1(`Timed out waiting for transaction ${this.transactionId} to settle`)}};var Yp=z.object({amount:z.union([z.bigint(),z.literal("max")]),metadata:K.optional(),spenderAddress:EvmAddressSchema,tokenAddress:EvmAddressSchema}),NR=k(a);async function Jp(e,r){let t=l(r,Yp),o=t.amount==="max"?Y:t.amount;return async function*(){return e.account.walletType===WalletType.EOA?N(yield $o(G(e.environment.chainId,mr(t.tokenAddress,t.spenderAddress,o)))):yield*await J(e,{calls:[mr(t.tokenAddress,t.spenderAddress,o)],metadata:t.metadata??`Approve ${t.amount} of ${t.tokenAddress} to ${t.spenderAddress}`})}.call(null)}var GR=k(h,e,d,j,c,b,a);function Go(e,r){return Jp(e,r).then(_(e.signer))}var Qp=z.object({approved:z.boolean().default(true),metadata:K.optional(),operatorAddress:EvmAddressSchema,tokenAddress:EvmAddressSchema}),KR=k(a);async function Xp(e,r){let t=l(r,Qp);return async function*(){return e.account.walletType===WalletType.EOA?N(yield Vo(G(e.environment.chainId,lr(t.tokenAddress,t.operatorAddress,t.approved)))):yield*await J(e,{calls:[lr(t.tokenAddress,t.operatorAddress,t.approved)],metadata:t.metadata??`${t.approved?"Approve":"Revoke"} ${t.operatorAddress} on ${t.tokenAddress}`})}.call(null)}var $R=k(h,e,d,j,c,b,a);function Ko(e,r){return Xp(e,r).then(_(e.signer))}var VR=k(d,c,b,a);async function ec(e){let r=await tc(e),t=r.erc20.map(n=>mr(n.tokenAddress,n.spenderAddress,n.amount)),o=r.erc1155.map(n=>lr(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 $o(G(e.environment.chainId,s))).wait();for(let s of o)await N(yield Vo(G(e.environment.chainId,s))).wait();return}await(yield*await J(e,{calls:[...t,...o],metadata:"Trading setup approvals"})).wait();}.call(null)}var ZR=k(h,e,d,j,f$1,g$1,c,b,a);function YR(e){return ec(e).then(_(e.signer)).then(rc)}function rc(){return {transactionHash:null,transactionId:null,wait:async()=>{}}}async function tc(e){let r=oc(e),t=[...r.erc20.map(a=>bo(a.tokenAddress,e.account.wallet,a.spenderAddress)),...r.erc1155.map(a=>ko(a.tokenAddress,e.account.wallet,a.operatorAddress))],o=await e.rpc.ethCallBatch(t),n=o.slice(0,r.erc20.length),s=o.slice(r.erc20.length);return {erc20:r.erc20.filter((a,y)=>Io(n[y])<a.amount),erc1155:r.erc1155.filter((a,y)=>!qo(s[y]))}}function oc(e){let{contracts:r}=e.environment;return {erc20:[{amount:Y,spenderAddress:r.standardExchange,tokenAddress:r.collateralToken},{amount:Y,spenderAddress:r.negRiskExchange,tokenAddress:r.collateralToken},{amount:Y,spenderAddress:r.negRiskAdapter,tokenAddress:r.collateralToken},{amount:Y,spenderAddress:r.collateralAdapter,tokenAddress:r.collateralToken},{amount:Y,spenderAddress:r.negRiskCollateralAdapter,tokenAddress:r.collateralToken},{amount:Y,spenderAddress:r.protocolV2Router,tokenAddress:r.collateralToken},{amount:Y,spenderAddress:r.exchangeV3,tokenAddress:r.collateralToken},{amount:Y,spenderAddress:r.perpsDepositContract,tokenAddress:r.collateralToken}],erc1155:[{operatorAddress:r.standardExchange,tokenAddress:r.conditionalTokens},{operatorAddress:r.negRiskExchange,tokenAddress:r.conditionalTokens},{operatorAddress:r.negRiskAdapter,tokenAddress:r.conditionalTokens},{operatorAddress:r.collateralAdapter,tokenAddress:r.conditionalTokens},{operatorAddress:r.negRiskCollateralAdapter,tokenAddress:r.conditionalTokens},{operatorAddress:r.autoRedeemOperator,tokenAddress:r.conditionalTokens},{operatorAddress:r.protocolV2Router,tokenAddress:r.positionManager},{operatorAddress:r.exchangeV3,tokenAddress:r.positionManager},{operatorAddress:r.autoRedeemOperator,tokenAddress:r.positionManager}]}}function $o(e){return {kind:"sendErc20ApprovalTransaction",request:e}}function Vo(e){return {kind:"sendErc1155ApprovalForAllTransaction",request:e}}var oE=k(e,d,c,b);async function ic(e,r){return unwrap(e.clob.post("/auth/api-key",{headers:Jo(r)}).andThen(f(ApiKeyCredsSchema)))}var nE=k(e,d,c,b);async function pc(e,r){return unwrap(e.clob.get("/auth/derive-api-key",{headers:Jo(r)}).andThen(f(ApiKeyCredsSchema)))}var sE=k(e,d,c,b);async function aE(e,r){try{return await ic(e,r)}catch(t){if(!(t instanceof d)||t.status!==400)throw t}return pc(e,r)}var iE=k(e,d,j,c,b);async function pE(e){return (await unwrap(e.secureClob.get("/auth/api-keys").andThen(f(ApiKeysResponseSchema)))).apiKeys}var cE=k(e,d,j,c,b);async function dE(e){await unwrap(e.secureClob.del("/auth/api-key").andThen(f(z.literal("OK"))));}var uE=k(e,d,j,c,b);async function mE(e){return unwrap(e.secureClob.post("/auth/builder-api-key").andThen(f(BuilderApiKeyCredsSchema)))}var lE=k(e,d,j,c,b);async function yE(e){return unwrap(e.secureClob.get("/auth/builder-api-key").andThen(f(BuilderApiKeysResponseSchema)))}var fE=k(e,d,j,c,b);async function PE(e){await unwrap(e.clob.del("/auth/builder-api-key").andThen(f(z.literal("OK"))));}function Jo(e){return {POLY_ADDRESS:e.address,POLY_NONCE:`${e.nonce}`,POLY_SIGNATURE:e.signature,POLY_TIMESTAMP:`${e.timestamp}`}}var lc=z.object({after:z.string().optional(),before:z.string().optional(),builderCode:BuilderCodeSchema,cursor:PaginationCursorSchema.optional(),id:z.string().optional(),market:z.string().optional(),tokenId:z.string().optional()}),IE=k(e,d,c,b,a);function kE(e,r){let{cursor:t,...o}=l(r,lc);return x(n=>e.clob.get("/builder/trades",{params:g({...o,nextCursor:n},R({builderCode:"builder_code",tokenId:"asset_id"}))}).andThen(f(PaginatedBuilderTradesSchema)).map(s=>({items:s.data,hasMore:s.nextCursor!==END_CURSOR,nextCursor:s.nextCursor===END_CURSOR?void 0:toPaginationCursor(s.nextCursor),totalCount:s.count})),t)}var Mc=z.object({tokenId:z.string()}),DE=k(e,d,c,b,a);async function zE(e,r){let t=l(r,Mc);return (await unwrap(e.clob.get("/midpoint",{params:g(t,R())}).andThen(f(MidpointSchema)))).mid}var Bc=z.array(z.object({tokenId:z.string()})).min(1),jE=k(e,d,c,b,a);async function WE(e,r){let t=l(r,Bc);return unwrap(e.clob.post("midpoints",{json:Er(t)}).andThen(f(MidpointsSchema)))}var Uc=z.object({tokenId:z.string()}),HE=k(e,d,c,b,a);async function Ue(e,r){let t=l(r,Uc);return (await unwrap(e.clob.get("/tick-size",{params:g(t,R())}).andThen(f(FetchTickSizeResponseSchema)))).minimumTickSize}var Dc=z.object({tokenId:z.string()}),_E=k(e,d,c,b,a);async function De(e,r){let t=l(r,Dc);return (await unwrap(e.clob.get("/neg-risk",{params:g(t,R())}).andThen(f(FetchNegRiskResponseSchema)))).negRisk}var zc=z.object({tokenId:TokenIdSchema}),NE=k(e,d,c,b,a);async function on(e,r){let t=l(r,zc);return unwrap(e.clob.get(`/markets-by-token/${t.tokenId}`).andThen(f(ResolveConditionByTokenResponseSchema)))}var jc=z.object({conditionId:CtfConditionIdSchema}),GE=k(e,d,c,b,a);async function nn(e,r){let t=l(r,jc);return unwrap(e.clob.get(`/clob-markets/${t.conditionId}`).andThen(f(FetchMarketInfoResponseSchema)))}var Wc=z.object({builderCode:BuilderCodeSchema}),KE=k(e,d,c,b,a);async function sn(e,r){let t=l(r,Wc);return unwrap(e.clob.get(`/fees/builder-fees/${t.builderCode}`).andThen(f(FetchBuilderFeeRatesResponseSchema)).mapErr(o=>o instanceof d&&o.status===404?new a(`Unknown builder code: ${t.builderCode}`,{cause:o}):o))}var Hc=z.object({tokenId:z.string(),side:OrderSideSchema}),$E=k(e,d,c,b,a);async function VE(e,r){let t=l(r,Hc);return (await unwrap(e.clob.get("/price",{params:g(t,R())}).andThen(f(PriceSchema)))).price}var _c=z.array(z.object({tokenId:z.string(),side:OrderSideSchema})).min(1),ZE=k(e,d,c,b,a);async function YE(e,r){let t=l(r,_c);return unwrap(e.clob.post("prices",{json:Xc(t)}).andThen(f(PricesSchema)))}var Nc=z.object({tokenId:z.string()}),JE=k(e,d,c,b,a);async function an(e,r){let t=l(r,Nc);return unwrap(e.clob.get("/book",{params:g(t,R())}).andThen(f(FetchOrderBookResponseSchema)))}var Gc=z.array(z.object({tokenId:z.string()})).min(1),QE=k(e,d,c,b,a);async function XE(e,r){let t=l(r,Gc);return unwrap(e.clob.post("books",{json:Er(t)}).andThen(f(OrderBooksSchema)))}var Kc=z.object({tokenId:z.string()}),eh=k(e,d,c,b,a);async function rh(e,r){let t=l(r,Kc);return (await unwrap(e.clob.get("/spread",{params:g(t,R())}).andThen(f(SpreadSchema)))).spread}var $c=z.array(z.object({tokenId:z.string()})).min(1),th=k(e,d,c,b,a);async function oh(e,r){let t=l(r,$c);return unwrap(e.clob.post("spreads",{json:Er(t)}).andThen(f(SpreadsSchema)))}var Vc=z.object({tokenId:z.string()}),nh=k(e,d,c,b,a);async function sh(e,r){let t=l(r,Vc);return unwrap(e.clob.get("/last-trade-price",{params:g(t,R())}).andThen(f(LastTradePriceSchema)))}var Zc=z.array(z.object({tokenId:z.string()})).min(1),ah=k(e,d,c,b,a);async function ih(e,r){let t=l(r,Zc);return unwrap(e.clob.post("last-trades-prices",{json:Er(t)}).andThen(f(LastTradePricesSchema)))}var Yc=z.object({tokenId:z.string(),startTs:z.number().int().optional(),endTs:z.number().int().optional(),fidelity:z.number().int().positive().optional(),interval:PriceHistoryIntervalSchema.optional()}),ph=k(e,d,c,b,a);async function ch(e,r){let t=l(r,Yc);return (await unwrap(e.clob.get("/prices-history",{params:g(t,{tokenId:"market",startTs:"startTs",endTs:"endTs",fidelity:"fidelity",interval:"interval"})}).andThen(f(PriceHistorySchema)))).history}var Jc=z.object({cursor:PaginationCursorSchema.optional(),sponsored:z.boolean().optional()}).default({}),dh=k(e,d,c,b,a);function uh(e,r={}){let{cursor:t,...o}=l(r,Jc);return x(n=>e.clob.get("/rewards/markets/current",{params:g({...o,nextCursor:n},R())}).andThen(f(PaginatedCurrentRewardsSchema)).map(s=>({items:s.data,hasMore:s.nextCursor!==END_CURSOR,nextCursor:s.nextCursor===END_CURSOR?void 0:toPaginationCursor(s.nextCursor),totalCount:s.count})),t)}var Qc=z.object({conditionId:CtfConditionIdSchema,cursor:PaginationCursorSchema.optional(),sponsored:z.boolean().optional()}),mh=k(e,d,c,b,a);function lh(e,r){let{cursor:t,...o}=l(r,Qc);return x(n=>e.clob.get(`rewards/markets/${o.conditionId}`,{params:g({nextCursor:n,sponsored:o.sponsored},R())}).andThen(f(PaginatedMarketRewardsSchema)).map(s=>({items:s.data,hasMore:s.nextCursor!==END_CURSOR,nextCursor:s.nextCursor===END_CURSOR?void 0:toPaginationCursor(s.nextCursor),totalCount:s.count})),t)}function Er(e){return e.map(({tokenId:r})=>({token_id:r}))}function Xc(e){return e.map(({tokenId:r,side:t})=>({token_id:r,side:t}))}var sd=z.object({ascending:z.boolean().optional(),cursor:PaginationCursorSchema.optional(),pageSize:O.default(20),getPositions:z.boolean().optional(),holdersOnly:z.boolean().optional(),order:z.string().optional(),parentEntityId:z.union([EventIdSchema,SeriesIdSchema]),parentEntityType:CommentParentEntityTypeSchema}),ad=z.object({getPositions:z.boolean().optional(),id:CommentIdSchema}),id=z.object({address:z.string(),ascending:z.boolean().optional(),cursor:PaginationCursorSchema.optional(),order:z.string().optional(),pageSize:O.default(20)}),Ch=k(e,d,c,b,a);function bh(e,r){let{cursor:t,pageSize:o,...n}=l(r,sd);return x(s=>{let a=U(s,o);return e.gamma.get("/comments",{params:g({ascending:n.ascending,getPositions:n.getPositions,holdersOnly:n.holdersOnly,limit:a.pageSize+1,offset:a.offset,order:n.order,parentEntityId:n.parentEntityId,parentEntityType:n.parentEntityType},R())}).andThen(f(ListCommentsResponseSchema)).map(y=>{let P=y.length>a.pageSize;return {items:y.slice(0,a.pageSize),hasMore:P,nextCursor:P?B({offset:a.offset+a.pageSize,pageSize:a.pageSize}):void 0}})},t)}var Ih=k(e,d,c,b,a);async function kh(e,r){let t=l(r,ad);return unwrap(e.gamma.get(`comments/${t.id}`,{params:g({getPositions:t.getPositions},R())}).andThen(f(ListCommentsResponseSchema)))}var qh=k(e,d,c,b,a);function vh(e,r){let{address:t,cursor:o,pageSize:n,...s}=l(r,id);return x(a=>{let y=U(a,n);return e.gamma.get(`comments/user_address/${t}`,{params:g({ascending:s.ascending,limit:y.pageSize+1,offset:y.offset,order:s.order},R())}).andThen(f(ListCommentsResponseSchema)).map(P=>{let v=P.length>y.pageSize;return {items:P.slice(0,y.pageSize),hasMore:v,nextCursor:v?B({offset:y.offset+y.pageSize,pageSize:y.pageSize}):void 0}})},o)}function hr(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 ld=z.object({ascending:z.boolean().optional(),closed:z.boolean().default(false),cursor:PaginationCursorSchema.optional(),pageSize:O.optional(),cyom:z.boolean().optional(),endDateMax:IsoDateTimeStringSchema.optional(),endDateMin:IsoDateTimeStringSchema.optional(),ended:z.boolean().optional(),eventDate:IsoCalendarDateStringSchema.optional(),eventWeek:z.number().int().optional(),excludeTagIds:z.array(z.number().int()).optional(),featured:z.boolean().optional(),featuredOrder:z.boolean().optional(),gameIds:z.array(z.number().int()).optional(),ids:z.array(z.number().int()).optional(),includeBestLines:z.boolean().optional(),includeChat:z.boolean().optional(),includeChildren:z.boolean().optional(),includeTemplate:z.boolean().optional(),liquidityMax:z.number().optional(),liquidityMin:z.number().optional(),live:z.boolean().optional(),locale:z.string().optional(),order:z.string().optional(),parentEventId:z.number().int().optional(),partnerSlug:z.string().optional(),recurrence:z.enum(["daily","weekly","monthly"]).optional(),relatedTags:z.boolean().optional(),seriesIds:z.array(z.number().int()).optional(),slug:z.array(z.string()).optional(),startDateMax:IsoDateTimeStringSchema.optional(),startDateMin:IsoDateTimeStringSchema.optional(),startTimeMax:IsoDateTimeStringSchema.optional(),startTimeMin:IsoDateTimeStringSchema.optional(),tagIds:z.array(z.number().int()).optional(),tagMatch:z.enum(["any","all"]).optional(),tagSlug:z.string().optional(),titleSearch:z.string().optional(),volumeMax:z.number().optional(),volumeMin:z.number().optional()}),yd=z.union([z.object({id:z.string(),includeBestLines:z.boolean().optional(),includeChat:z.boolean().optional(),includeTemplate:z.boolean().optional(),locale:z.string().optional()}),z.object({slug:z.string(),includeBestLines:z.boolean().optional(),includeChat:z.boolean().optional(),includeTemplate:z.boolean().optional(),locale:z.string().optional()}),z.object({url:z.string(),includeBestLines:z.boolean().optional(),includeChat:z.boolean().optional(),includeTemplate:z.boolean().optional(),locale:z.string().optional()})]),fd=z.object({id:z.string()}),Pd=z.object({id:z.string()}),Nh=k(e,d,c,b,a);function Gh(e,r={}){let t=l(r,ld);return x(o=>e.gamma.get("/events/keyset",{params:gd({...t,cursor:o??t.cursor})}).andThen(f(ListEventsKeysetResponseSchema)).map(n=>({items:n.items,hasMore:n.nextCursor!==void 0,nextCursor:n.nextCursor})),t.cursor)}var Kh=k(e,d,c,b,a);async function $h(e,r){let t=l(r,yd);if("id"in t)return unwrap(e.gamma.get(`events/${t.id}`,{params:Rd(t)}).andThen(f(EventSchema)));let o="url"in t?hr(t.url,"event"):t.slug;return unwrap(e.gamma.get(`events/slug/${o}`,{params:Ed(t)}).andThen(f(EventSchema)))}var Vh=k(e,d,c,b,a);async function Zh(e,r){let t=l(r,fd);return unwrap(e.gamma.get(`events/${t.id}/tags`).andThen(f(FetchEventTagsResponseSchema)))}var Yh=k(e,d,c,b,a);async function Jh(e,r){let t=l(r,Pd);return unwrap(e.data.get("/live-volume",{params:H(t)}).andThen(f(FetchEventLiveVolumeResponseSchema)))}function gd(e){return g(e,R({cursor:"after_cursor",excludeTagIds:"exclude_tag_id",gameIds:"game_id",ids:"id",pageSize:"limit",seriesIds:"series_id",tagIds:"tag_id"}))}function Rd(e){return g({includeBestLines:e.includeBestLines,includeChat:e.includeChat,includeTemplate:e.includeTemplate,locale:e.locale},R())}function Ed(e){return g({includeBestLines:e.includeBestLines,includeChat:e.includeChat,includeTemplate:e.includeTemplate,locale:e.locale},R())}var Id=z.object({cursor:PaginationCursorSchema.optional(),pageSize:O.default(20),timePeriod:TimePeriodSchema.optional()}),kd=z.object({timePeriod:TimePeriodSchema.optional()}),qd=z.object({category:LeaderboardCategorySchema.optional(),cursor:PaginationCursorSchema.optional(),pageSize:O.default(20),timePeriod:TimePeriodSchema.optional(),orderBy:LeaderboardOrderBySchema.optional(),user:z.string().optional(),userName:z.string().optional()}),pS=k(e,d,c,b,a);function cS(e,r={}){let{cursor:t,pageSize:o,...n}=l(r,Id);return x(s=>{let a=U(s,o);return e.data.get("/v1/builders/leaderboard",{params:H({...n,limit:a.pageSize+1,offset:a.offset})}).andThen(f(ListBuilderLeaderboardResponseSchema)).map(y=>{let P=y.length>a.pageSize;return {items:y.slice(0,a.pageSize),hasMore:P,nextCursor:P?B({offset:a.offset+a.pageSize,pageSize:a.pageSize}):void 0}})},t)}var dS=k(e,d,c,b,a);async function uS(e,r={}){let t=l(r,kd);return unwrap(e.data.get("/v1/builders/volume",{params:H(t)}).andThen(f(ListBuilderVolumeResponseSchema)))}var mS=k(e,d,c,b,a);function lS(e,r={}){let{cursor:t,pageSize:o,...n}=l(r,qd);return x(s=>{let a=U(s,o);return e.data.get("/v1/leaderboard",{params:H({...n,limit:a.pageSize+1,offset:a.offset})}).andThen(f(ListTraderLeaderboardResponseSchema)).map(y=>{let P=y.length>a.pageSize;return {items:y.slice(0,a.pageSize),hasMore:P,nextCursor:P?B({offset:a.offset+a.pageSize,pageSize:a.pageSize}):void 0}})},t)}var Od=z.object({marketId:z.union([z.string(),z.array(z.string())]).optional(),eventId:z.union([z.string(),z.array(z.string())]).optional(),questionId:z.union([z.string(),z.array(z.string())]).optional(),state:z.union([z.enum(MarketClarificationState),z.array(z.enum(MarketClarificationState))]).optional(),showInFrontend:z.boolean().optional(),txHash:z.string().optional(),order:z.string().optional(),ascending:z.boolean().optional(),cursor:PaginationCursorSchema.optional(),pageSize:O.default(20)}),xS=k(e,d,c,b,a);function CS(e,r={}){let{cursor:t,pageSize:o,...n}=l(r,Od);return x(s=>{let a=U(s,o);return e.gamma.get("/market-clarifications",{params:g({...n,limit:a.pageSize+1,offset:a.offset},R())}).andThen(f(ListMarketClarificationsResponseSchema)).map(y=>{let P=y.length>a.pageSize;return {items:y.slice(0,a.pageSize),hasMore:P,nextCursor:P?B({offset:a.offset+a.pageSize,pageSize:a.pageSize}):void 0}})},t)}var zd=z.object({ascending:z.boolean().optional(),closed:z.boolean().optional(),clobTokenIds:z.array(z.string()).optional(),cursor:PaginationCursorSchema.optional(),pageSize:O.optional(),conditionIds:z.array(CtfConditionIdSchema).optional(),cyom:z.boolean().optional(),decimalized:z.boolean().optional(),endDateMax:IsoDateTimeStringSchema.optional(),endDateMin:IsoDateTimeStringSchema.optional(),gameId:z.string().optional(),ids:z.array(z.number().int()).optional(),includeTag:z.boolean().optional(),liquidityNumMax:z.number().optional(),liquidityNumMin:z.number().optional(),locale:z.string().optional(),marketMakerAddresses:z.array(z.string()).optional(),order:z.string().optional(),positionIds:z.array(PositionIdSchema).optional(),questionIds:z.array(z.string()).optional(),relatedTags:z.boolean().optional(),rfqEnabled:z.boolean().optional(),rewardsMinSize:z.number().optional(),slug:z.array(z.string()).optional(),sportsMarketTypes:z.array(z.string()).optional(),startDateMax:IsoDateTimeStringSchema.optional(),startDateMin:IsoDateTimeStringSchema.optional(),tagId:z.number().int().optional(),tagMatch:z.enum(["any","all"]).optional(),umaResolutionStatus:z.string().optional(),volumeNumMax:z.number().optional(),volumeNumMin:z.number().optional()}),jd=z.object({id:z.string(),includeTag:z.boolean().optional(),locale:z.string().optional()}),Wd=z.object({slug:z.string(),includeTag:z.boolean().optional(),locale:z.string().optional()}),Hd=z.object({url:z.string(),includeTag:z.boolean().optional(),locale:z.string().optional()}),_d=z.union([jd,Wd,Hd]),Nd=z.object({id:z.string()}),Gd=z.object({limit:z.number().int().optional(),market:z.array(z.string()),minBalance:z.number().int().optional()}),Kd=z.object({market:z.array(z.string()).optional()}),$d=z.enum(["OPEN","CLOSED","ALL"]),Vd=z.enum(["TOKENS","CASH_PNL","REALIZED_PNL","TOTAL_PNL"]),Zd=z.enum(["ASC","DESC"]),Yd=z.object({cursor:PaginationCursorSchema.optional(),market:z.string(),pageSize:O.default(20),user:z.string().optional(),status:$d.optional(),sortBy:Vd.optional(),sortDirection:Zd.optional()}),DS=k(e,d,c,b,a);function fn(e,r={}){let t=l(r,zd);return x(o=>e.gamma.get("/markets/keyset",{params:Qd({...t,cursor:o??t.cursor})}).andThen(f(ListMarketsKeysetResponseSchema)).map(n=>({items:n.items,hasMore:n.nextCursor!==void 0,nextCursor:n.nextCursor})),t.cursor)}var Jd=z.object({cursor:PaginationCursorSchema.optional(),pageSize:O.max(100).optional(),exclude:z.array(CtfConditionIdSchema).optional()}),zS=k(e,d,c,b,a);function jS(e,r={}){let t=l(r,Jd);return x(o=>e.rfq.get("/v1/rfq/combo-markets",{params:Xd({...t,cursor:o??t.cursor})}).andThen(f(ListComboMarketsResponseSchema)).map(n=>({items:n.markets,hasMore:n.nextCursor!==void 0,nextCursor:n.nextCursor})),t.cursor)}var WS=k(e,d,c,b,a);async function HS(e,r){let t=l(r,_d);return "id"in t?eu(e,t):"url"in t?mn(e,{includeTag:t.includeTag,locale:t.locale,slug:hr(t.url,"market")}):mn(e,t)}var _S=k(e,d,c,b,a);async function NS(e,r){let t=l(r,Nd);return unwrap(e.gamma.get(`markets/${t.id}/tags`).andThen(f(FetchMarketTagsResponseSchema)))}var GS=k(e,d,c,b,a);async function KS(e,r){let t=l(r,Gd);return unwrap(e.data.get("/holders",{params:H(t)}).andThen(f(ListMarketHoldersResponseSchema)))}var $S=k(e,d,c,b,a);async function VS(e,r={}){let t=l(r,Kd);return unwrap(e.data.get("/oi",{params:H(t)}).andThen(f(ListOpenInterestResponseSchema)))}var ZS=k(e,d,c,b,a);function YS(e,r){let{cursor:t,pageSize:o,...n}=l(r,Yd);return x(s=>{let a=U(s,o);return e.data.get("/v1/market-positions",{params:H({...n,limit:a.pageSize+1,offset:a.offset})}).andThen(f(ListMarketPositionsResponseSchema)).map(y=>{let P=y.length>a.pageSize;return {items:y.slice(0,a.pageSize),hasMore:P,nextCursor:P?B({offset:a.offset+a.pageSize,pageSize:a.pageSize}):void 0}})},t)}function Qd(e){return g(e,R({cursor:"after_cursor",ids:"id",marketMakerAddresses:"market_maker_address",pageSize:"limit"}))}function Xd(e){return g({cursor:e.cursor,exclude:e.exclude?.join(","),pageSize:e.pageSize},{cursor:"cursor",exclude:"exclude",pageSize:"limit"})}async function mn(e,r){return unwrap(e.gamma.get(`markets/slug/${r.slug}`,{params:g({includeTag:r.includeTag,locale:r.locale},R())}).andThen(f(MarketSchema)))}async function eu(e,r){return unwrap(e.gamma.get(`markets/${r.id}`,{params:g({includeTag:r.includeTag,locale:r.locale},R())}).andThen(f(MarketSchema)))}var ou=z.object({orderId:z.string()}),nu=z.object({orderIds:z.array(z.string()).min(1).max(3e3)}),su=z.object({tokenId:z.string().optional(),market:z.string().optional()}).refine(e=>e.market!==void 0||e.tokenId!==void 0,{message:"At least one of market or tokenId is required.",path:["market"]}),nT=k(d,e,j,c,b,a);async function sT(e,r){let t=l(r,ou);return xr(e,"/order",{orderID:t.orderId})}var aT=k(d,e,j,c,b,a);async function iT(e,r){let t=l(r,nu);return xr(e,"/orders",t.orderIds)}var pT=k(d,e,j,c,b);async function cT(e){return xr(e,"/cancel-all")}var dT=k(d,e,j,c,b,a);async function uT(e,r){let t=l(r,su);return xr(e,"/cancel-market-orders",{asset_id:t.tokenId,market:t.market})}async function xr(e,r,t){return unwrap(e.secureClob.del(r,{json:t}).andThen(f(CancelOrdersResponseSchema)))}var gn=z.object({tokenId:z.string(),orderType:z.union([z.literal(OrderType.FAK),z.literal(OrderType.FOK)]).default(OrderType.FOK)}),iu=z.discriminatedUnion("side",[gn.extend({side:z.literal(OrderSide.BUY),amount:PositiveDecimalNumberSchema}),gn.extend({side:z.literal(OrderSide.SELL),shares:PositiveDecimalNumberSchema})]),ET=k(i,e,d,c,b,a);async function hT(e,r){let t=l(r,iu),o=await Ue(e,{tokenId:t.tokenId}),n=t.side===OrderSide.BUY?t.amount:t.shares;return pt(e,{amount:n,orderType:t.orderType,side:t.side,tickSize:o,tokenId:t.tokenId})}async function pt(e,r){let t=await an(e,{tokenId:r.tokenId}),o=r.side===OrderSide.BUY?cu(t.asks,r.amount,r.orderType):du(t.bids,r.amount,r.orderType);return invariant(pu(o,r.tickSize),`Resolved market price fell outside the valid range for tick size ${r.tickSize}.`),o}function pu(e,r){return e>=r&&e<=1-r}function cu(e,r,t){if(e.length===0)throw new i("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 i("Insufficient liquidity for full fill.");let n=e[0];return Number.parseFloat(n.price)}function du(e,r,t){if(e.length===0)throw new i("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 i("Insufficient liquidity for full fill.");let n=e[0];return Number.parseFloat(n.price)}var yu=z.array(z.custom()).min(1).max(15),vT=k(e,d,j,c,b),AT=k(e,d,j,c,b,a);function br(e){return async function(t){let o=Sn(e,t);return unwrap(e.secureClob.post("/order",{json:o}).andThen(f(OrderResponseSchema)))}}function OT(e){return async function(t){let n=l(t,yu).map(s=>Sn(e,s));return unwrap(e.secureClob.post("/orders",{json:n}).andThen(f(OrderResponsesSchema)))}}function Sn(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.parseInt(r.salt,10),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 je(e){switch(e){case .1:return {amount:3,price:1,size:2};case .01:return {amount:4,price:2,size:2};case .005:return {amount:5,price:3,size:2};case .0025:return {amount:6,price:4,size:2};case .001:return {amount:5,price:3,size:2};case 1e-4:return {amount:6,price:4,size:2}}invariant(false,`Unsupported tick size: ${e}`);}function We(e,r){return r?e.environment.contracts.negRiskExchange:e.environment.contracts.standardExchange}function ue(e){return BigInt(Math.round(e*10**6))}function me(e,r){return Q(e)<=r?e:Math.floor(e*10**r)/10**r}function be(e,r){return Q(e)<=r?e:Math.ceil(e*10**r)/10**r}function ct(e,r){return Q(e)<=r?e:Math.round(e*10**r)/10**r}function Q(e){if(typeof e=="number"&&Number.isInteger(e))return 0;let[r="",t]=e.toString().toLowerCase().split("e"),[,o=""]=r.split("."),n=o.length;if(t===void 0)return n;let s=Number.parseInt(t,10);return Math.max(0,n-s)}var hu=180,Cn=z.strictObject({tokenId:TokenIdSchema,price:PositiveDecimalNumberSchema,size:PositiveDecimalNumberSchema,side:OrderSideSchema,builderCode:BuilderCodeSchema.optional(),postOnly:z.boolean().default(false),expiration:z.number().int().nonnegative().optional()}).superRefine((e,r)=>{if(e.expiration!==void 0){let t=Math.floor(Date.now()/1e3)+hu;e.expiration<t&&r.addIssue({code:"custom",message:"Expiration must be at least 3 minutes in the future.",path:["expiration"]});}});async function bn(e,r){let t=await Su(e,{price:r.price,tokenId:r.tokenId}),o=Tu({price:t.price,side:r.side,size:r.size,tickSize:t.tickSize});return {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,tokenId:r.tokenId}}async function Su(e,r){let t=e.account,o=await Ue(e,{tokenId:r.tokenId}),n=await De(e,{tokenId:r.tokenId});return {exchangeAddress:We(e,n),funderAddress:t.wallet,negRisk:n,price:xu(r.price,o),signerAddress:t.signer,tickSize:o}}function Tu(e){let r=je(e.tickSize),t=ct(e.price,r.price);if(e.side===OrderSide.BUY){let s=me(e.size,r.size),a=s*t;return Q(a)>r.amount&&(a=be(a,r.amount+4),Q(a)>r.amount&&(a=me(a,r.amount))),{offeredAmount:ue(a),requestedAmount:ue(s)}}let o=me(e.size,r.size),n=o*t;return Q(n)>r.amount&&(n=be(n,r.amount+4),Q(n)>r.amount&&(n=me(n,r.amount))),{offeredAmount:ue(o),requestedAmount:ue(n)}}function xu(e,r){let t=je(r);if(e<r||e>1-r)throw new a(`Price must be between ${r} and ${1-r} for tick size ${r}.`);if(Q(e)>t.price)throw new a(`Price must conform to tick size ${r} with at most ${t.price} decimal places.`);return ct(e,t.price)}var In=z.object({tokenId:TokenIdSchema,builderCode:BuilderCodeSchema.optional(),orderType:z.union([z.literal(OrderType.FAK),z.literal(OrderType.FOK)]).default(OrderType.FAK)}),qn=z.discriminatedUnion("side",[In.extend({side:z.literal(OrderSide.BUY),amount:PositiveDecimalNumberSchema,maxSpend:PositiveDecimalNumberSchema.optional(),maxPrice:PositiveDecimalNumberSchema.optional()}),In.extend({side:z.literal(OrderSide.SELL),shares:PositiveDecimalNumberSchema,minPrice:PositiveDecimalNumberSchema.optional()})]);async function vn(e,r){let t=await Iu(e,r),o=vu({amount:t.resolvedAmount,price:t.price,protectPrice:qu(r),side:r.side,tickSize:t.tickSize});return {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,tokenId:r.tokenId}}async function Iu(e,r){let t=e.account,o=await Ue(e,{tokenId:r.tokenId}),n=r.side===OrderSide.BUY?r.amount:r.shares,s=await ku(e,r,n,o),a=await De(e,{tokenId:r.tokenId}),y=await Au(e,{amount:n,builderCode:r.builderCode,maxSpend:r.side===OrderSide.BUY?r.maxSpend:void 0,price:s,side:r.side,tokenId:r.tokenId});return {exchangeAddress:We(e,a),funderAddress:t.wallet,negRisk:a,price:s,resolvedAmount:y,signerAddress:t.signer,tickSize:o}}async function ku(e,r,t,o){return r.side===OrderSide.BUY&&r.maxPrice!==void 0?kn(r.maxPrice,o,"maxPrice"):r.side===OrderSide.SELL&&r.minPrice!==void 0?kn(r.minPrice,o,"minPrice"):pt(e,{amount:t,orderType:r.orderType,side:r.side,tickSize:o,tokenId:r.tokenId})}function kn(e,r,t){let o=je(r);if(e<r||e>1-r)throw new a(`${t} must be between ${r} and ${1-r} for tick size ${r}.`);if(Q(e)>o.price)throw new a(`${t} must conform to tick size ${r} with at most ${o.price} decimal places.`);return e}function qu(e){return e.side===OrderSide.BUY&&e.maxPrice!==void 0||e.side===OrderSide.SELL&&e.minPrice!==void 0}function vu(e){let r=je(e.tickSize),t=me(e.price,r.price),o=me(e.amount,r.size);if(e.side===OrderSide.BUY){let s=o/t;return Q(s)>r.amount&&(s=be(s,r.amount+4),Q(s)>r.amount&&(s=e.protectPrice?be(s,r.amount):me(s,r.amount))),{offeredAmount:ue(o),requestedAmount:ue(s)}}let n=o*t;return Q(n)>r.amount&&(n=be(n,r.amount+4),Q(n)>r.amount&&(n=e.protectPrice?be(n,r.amount):me(n,r.amount))),{offeredAmount:ue(o),requestedAmount:ue(n)}}async function Au(e,r){if(r.side!==OrderSide.BUY||r.maxSpend===void 0)return r.amount;let[t,o]=await Promise.all([Ou(e,r.tokenId),wu(e,r.builderCode)]);return Lu({amount:r.amount,builderTakerFeeRate:o,platformFeeExponent:t.exponent,platformFeeRate:t.rate,maxSpend:r.maxSpend,price:r.price})}async function Ou(e,r){let t=await on(e,{tokenId:r});return (await nn(e,{conditionId:t})).feeInfo}async function wu(e,r){return r===void 0?0:(await sn(e,{builderCode:r})).taker}function Lu(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 An="0x0000000000000000000000000000000000000000000000000000000000000000";function mt(e,r){let t=po(r);return {builder:e.builderCode??An,chainId:e.chainId,exchangeAddress:e.exchangeAddress,expiration:e.expiration,maker:t.maker,makerAmount:e.offeredAmount.toString(),metadata:An,orderType:e.orderType,salt:Fu().toString(),side:e.side,signatureType:t.signatureType,signer:t.signer,takerAmount:e.requestedAmount.toString(),timestamp:Date.now().toString(),tokenId:e.tokenId}}function lt(e,r){let{chainId:t,exchangeAddress:o,...n}=e;return {...n,signature:r}}function Fu(){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}var Ln="Polymarket CTF Exchange",Uu="DepositWallet",Du="1",yt="0x0000000000000000000000000000000000000000000000000000000000000000",ft="Order(uint256 salt,address maker,address signer,uint256 tokenId,uint256 makerAmount,uint256 takerAmount,uint8 side,uint8 signatureType,uint256 timestamp,bytes32 metadata,bytes32 builder)",zu=Hash.keccak256(Bytes.fromString(ft),{as:"Hex"}),ju=Hash.keccak256(Bytes.fromString("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),{as:"Hex"}),Wu=Hash.keccak256(Bytes.fromString(Ln),{as:"Hex"}),Hu=[{name:"name",type:"string"},{name:"version",type:"string"},{name:"chainId",type:"uint256"},{name:"verifyingContract",type:"address"}],Fn=[{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"}],_u=[{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 Mn(e){let r=Nu(e.domain,e.order);return e.order.signatureType!==SignatureType.POLY_1271?r:{domain:Dn(e.domain),message:{chainId:e.domain.chainId,contents:r.message,name:Uu,salt:yt,verifyingContract:e.order.signer,version:Du},primaryType:"TypedDataSign",types:{Order:Fn,TypedDataSign:_u}}}function Bn(e){if(e.order.signatureType!==SignatureType.POLY_1271)return e.signature;let r=Bytes.toHex(Bytes.fromString(ft)),t=ft.length.toString(16).padStart(4,"0");return expectErc1271Signature(`0x${e.signature.slice(2)}${Gu(e.domain).slice(2)}${Ku(e.order).slice(2)}${r.slice(2)}${t}`)}function Un(e){return {builder:e.builder??yt,maker:e.maker,makerAmount:BigInt(e.makerAmount),metadata:e.metadata??yt,salt:BigInt(e.salt),side:Vu(e.side),signatureType:e.signatureType,signer:e.signer,takerAmount:BigInt(e.takerAmount),timestamp:BigInt(e.timestamp),tokenId:BigInt(e.tokenId)}}function Nu(e,r){return {domain:Dn(e),message:Un(r),primaryType:"Order",types:{EIP712Domain:Hu,Order:Fn}}}function Dn(e){return {chainId:e.chainId,name:Ln,verifyingContract:e.exchange,version:e.protocolVersion}}function Gu(e){return expectHexString(Hash.keccak256(AbiParameters.encode([{type:"bytes32"},{type:"bytes32"},{type:"bytes32"},{type:"uint256"},{type:"address"}],[ju,Wu,$u(e.protocolVersion),BigInt(e.chainId),e.exchange]),{as:"Hex"}))}function Ku(e){let r=Un(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"}],[zu,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 $u(e){return expectHexString(Hash.keccak256(Bytes.fromString(e),{as:"Hex"}))}function Vu(e){return e===0||e===1?e:e===OrderSide.BUY?0:1}function gt(e){return Mn({domain:zn(e),order:e})}function Rt(e,r){return Bn({domain:zn(e),order:e,signature:r})}function zn(e){return {chainId:e.chainId,exchange:e.exchangeAddress,protocolVersion:"2"}}function Et(e){return {kind:"signOrder",payload:e}}var Zu=k(i,e,d,j,c,b,a);async function ht(e,r){let t=l(r,qn);return async function*(){let o=await vn(e,t),n=mt(o,e.account),s=expectEvmSignature(yield Et(gt(n)));return lt(n,Rt(n,s))}.call(null)}var Yu=k(e,d,j,c,b,a);async function St(e,r){let t=l(r,Cn);return async function*(){let o=await bn(e,t),n=mt(o,e.account),s=expectEvmSignature(yield Et(gt(n))),a=lt(n,Rt(n,s));return t.postOnly===true?{...a,postOnly:true}:a}.call(null)}var gx=Zu;async function Rx(e,r){return Wn(e,ht(e,r))}var Ex=Yu;async function hx(e,r){return Wn(e,St(e,r))}async function Wn(e,r){let t=await r;return async function*(){let o=yield*t;return br(e)(o)}.call(null)}async function Nn(e,r){let t=r.side===OrderSide.BUY?AssetType.COLLATERAL:AssetType.CONDITIONAL,{allowances:o}=await Gr(e,r.side===OrderSide.BUY?{assetType:t}:{assetType:t,tokenId:r.tokenId});return Qu(o,r.spenderAddress)}function Qu(e,r){return Object.entries(e).find(([o])=>isSameEvmAddress(o,r))?.[1]??0n}var Dx=k(h,i,e,d,j,c,b,a);function Xu(e,r){return ht(e,r).then(_(e.signer))}var zx=k(h,i,e,d,j,f$1,g$1,c,b,a);function jx(e,r){return Xu(e,r).then(t=>Kn(e,t))}var Wx=k(h,e,d,j,c,b,a);function em(e,r){return St(e,r).then(_(e.signer))}var Hx=k(h,e,d,j,f$1,g$1,c,b,a);function _x(e,r){return em(e,r).then(t=>Kn(e,t))}async function Kn(e,r){let t=br(e);try{return await t(r)}catch(o){if(!tm(o))throw o;let n=await rm(e,r,t);if(n===void 0)throw o;return n}}async function rm(e,r,t){return await om(e,r)?t(r):void 0}function tm(e){return e instanceof d&&e.status===400&&e.message.includes("allowance is not enough")}async function om(e,r){let t=await De(e,{tokenId:r.tokenId}),o=We(e,t),n=BigInt(r.makerAmount);return await Nn(e,{spenderAddress:o,side:r.side,tokenId:r.tokenId})>=n?false:(await(r.side===OrderSide.BUY?await Go(e,{amount:"max",spenderAddress:o,tokenAddress:e.environment.contracts.collateralToken}):await Ko(e,{operatorAddress:o,tokenAddress:e.environment.contracts.conditionalTokens})).wait(),await fo(e,{assetType:r.side===OrderSide.BUY?AssetType.COLLATERAL:AssetType.CONDITIONAL,tokenId:r.side===OrderSide.SELL?r.tokenId:void 0}),true)}function $n(e){let r=TypedData.getSignPayload(xt(e));return expectEvmSignature(Signature.toHex(Secp256k1.sign({payload:r,privateKey:e.privateKey})))}function xt(e){return {domain:{chainId:e.chainId,name:"Polymarket",version:"1"},message:{data:Hash.keccak256(encode(Vn(e.op)),{as:"Hex"}),salt:BigInt(e.salt),ts:BigInt(e.timestamp)},primaryType:"Op",types:{Op:[{name:"data",type:"bytes32"},{name:"salt",type:"uint64"},{name:"ts",type:"uint64"}]}}}function Vn(e){return Array.isArray(e)?e.filter(r=>r!==void 0).map(Vn):e}var Ir=class{#e;#r;#t;constructor({root:r,headers:t,resolveHeaders:o}){this.#e=Xt.create({prefixUrl:r,throwHttpErrors:false}),this.#r=t,this.#t=o;}get(r,t={}){return this.#n("GET",r,t)}post(r,t={}){return this.#n("POST",r,t)}patch(r,t={}){return this.#n("PATCH",r,t)}del(r,t={}){return this.#n("DELETE",r,t)}#o(r){return r.startsWith("/")?r.slice(1):r}#n(r,t,o){return this.#a(this.#c(r,t,o))}async#c(r,t,o){let n=this.#i(r,t,o),s=await this.#t?.(n),a=this.#p(this.#r,n.headers,s);return n.body!==void 0&&!a.has("content-type")&&a.set("content-type","application/json"),this.#e(this.#o(t),{body:n.body,headers:a,method:r,searchParams:n.params})}#i(r,t,o){return {body:"json"in o?this.#s(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}}#s(r){if(r!==void 0)return JSON.stringify(r)}#p(...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}#a(r){return ResultAsync.fromPromise(r.then(async t=>{if(t.ok)return t;if(t.status===429)throw new e(`Request to ${t.url} was rate limited`);let o=await this.#d(t);throw new d(o,{status:t.status})}),t=>t instanceof e||t instanceof d?t:c.fromError(t))}async#d(r){let t=r.headers.get("content-type")?.toLowerCase();if(t?.includes("application/json")){let{error:n}=await r.clone().json().catch(()=>({}));if(n)return `${String(n)} (${r.url})`}if(t?.includes("text/plain")){let n=await r.clone().text().then(s=>s.trim(),()=>"");if(n)return `${n} (${r.url})`}return r.headers.get("server")?.toLowerCase()?.includes("cloudflare")?`Request to ${r.url} was blocked by Cloudflare with status ${r.status}`:t?.includes("text/html")||t?.includes("application/xhtml+xml")?`Request to ${r.url} failed with status ${r.status} and an unexpected HTML response body`:`Request to ${r.url} failed with status ${r.status} and unreadable response body`}};var mm=1e4,lm=3e4,ym=5e3,fm=10*6e4,Pm=3e4,gm=25e3,Rm=65e3,Zn=class{#e=0;#r;start(r){this.stop(),this.#e=Date.now(),this.#r=setNonBlockingInterval(()=>{r("PING");},mm);}handleMessage(r){return r!=="PONG"?false:(this.#e=Date.now(),true)}isStale(r){return r-this.#e>lm}stop(){this.#r!==void 0&&(clearInterval(this.#r),this.#r=void 0);}},Yn=class{#e=0;#r;start(r){this.stop(),this.#e=Date.now(),this.#r=setNonBlockingInterval(()=>{r("PING");},ym);}handleMessage(){return this.#e=Date.now(),false}isStale(r){return r-this.#e>fm}stop(){this.#r!==void 0&&(clearInterval(this.#r),this.#r=void 0);}},Jn=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>Pm}},kr=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"}}));},gm);}handleMessage(){return this.#e=Date.now(),false}isStale(r){return r-this.#e>Rm}stop(){this.#r!==void 0&&(clearInterval(this.#r),this.#r=void 0);}};var Sm=5e3,Tm=250,xm=3e4,qr=class{#e;#r=0;schedule(r){if(this.#e!==void 0||!r.shouldReconnect())return;let t=bm(this.#r,{baseMs:Tm,maxMs:xm});this.#r+=1,this.#e=setNonBlockingTimeout(()=>{this.#e=void 0,this.#t(r);},t);}stop(){this.#e!==void 0&&(clearTimeout(this.#e),this.#e=void 0);}resetBackoff(){this.#r=0,this.stop();}async#t(r){if(r.shouldReconnect())try{await r.reconnect();}catch{this.schedule(r);}}},vr=class{#e;#r;#t;#o;constructor(r={}){this.#e=r.heartbeat;}connect(r){if(this.#r?.readyState===WebSocket.OPEN)return Promise.resolve({reusedOpenSocket:true});if(this.#s(),this.#t!==void 0)return this.#t;let o=this.#c(r).then(()=>({reusedOpenSocket:false})).catch(n=>{throw this.#t===o&&(this.#t=void 0),n});return this.#t=o,o}send(r){return this.#n(JSON.stringify(r))}#n(r){return this.#r?.readyState!==WebSocket.OPEN?false:(this.#r.send(r),true)}async close(){let r=await this.#d();this.#a(),!(r===void 0||r.readyState===WebSocket.CLOSED)&&await new Promise(t=>{r.addEventListener("close",()=>t(),{once:true}),r.readyState!==WebSocket.CLOSING&&r.close();});}async#c(r){let t=await r.prepare?.();return new Promise((o,n)=>{let s=Cm(r.url,r.headers),a=()=>{s.removeEventListener("error",y),this.#i(s),this.#p(),r.onOpen(t),o(s);},y=P=>{s.removeEventListener("open",a),n(new c(`WebSocket connection failed: ${r.url}`,{cause:P}));};s.addEventListener("open",a,{once:true}),s.addEventListener("error",y,{once:true}),s.addEventListener("message",P=>{if(this.#r!==s)return;let v=String(P.data);if(this.#e?.handleMessage(v))return;let A;try{A=JSON.parse(v);}catch{return}r.onMessage(A);}),s.addEventListener("close",()=>{this.#r===s&&(this.#s(),r.onClose());}),s.addEventListener("error",()=>r.onError());})}#i(r){this.#r=r,this.#t=void 0;}#s(){this.#a(),this.#r=void 0;}#p(){this.#a();let r=this.#e;r!==void 0&&(r.start(t=>this.#n(t)),this.#o=setNonBlockingInterval(()=>{if(!r.isStale(Date.now()))return;let t=this.#r;t?.readyState===WebSocket.OPEN&&t.close();},Sm));}#a(){this.#o!==void 0&&(clearInterval(this.#o),this.#o=void 0),this.#e?.stop();}async#d(){let r=this.#r,t=this.#t;return this.#r=void 0,this.#t=void 0,r!==void 0?r:t?.then(()=>this.#r,()=>{})}};function Cm(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 bm(e,r){let t=Math.min(r.baseMs*2**e,r.maxMs);return Math.random()*t}var or=1440*60*1e3,rs=90*or,ye=z.number().int().nonnegative(),Ar=z.object({start:ye.optional(),end:ye.optional()}),ts=z.object({interval:PerpsPnlIntervalSchema,start:ye,end:ye.optional()}),Wm=z.enum(["perpsFills","perpsFundingPayments","perpsDeposits","perpsWithdrawals"]),Hm=z.enum(["perpsEquityHistory","perpsPnlHistory"]),Or=z.object({kind:Wm,startTimestamp:ye,endTimestamp:ye,instrumentId:PerpsInstrumentIdSchema.optional(),depositStatus:PerpsDepositStatusSchema.optional(),withdrawalStatus:PerpsWithdrawalStatusSchema.optional(),hash:TxHashSchema.optional(),seenKeys:z.array(z.string())}),os=z.object({kind:Hm,startTimestamp:ye,endTimestamp:ye,interval:PerpsPnlIntervalSchema});async function ns(e){return await unwrap(e.get("/v1/account/balances").andThen(f(FetchPerpsBalancesResponseSchema)))}async function ss(e){return await unwrap(e.get("/v1/account/portfolio").andThen(f(FetchPerpsPortfolioResponseSchema)))}async function as(e){return await unwrap(e.get("/v1/account/stats").andThen(f(FetchPerpsAccountStatsResponseSchema)))}var _m=z.object({instrumentId:PerpsInstrumentIdSchema.optional()}).default({});async function is(e,r){let t=l(r,_m);return await unwrap(e.get("/v1/account/config",{params:Ee(t)}).andThen(f(FetchPerpsAccountConfigResponseSchema)))}var Nm=z.object({instrumentId:PerpsInstrumentIdSchema.optional()}).default({});async function ps(e,r){let t=l(r,Nm);return await unwrap(e.get("/v1/account/open-orders",{params:Ee(t)}).andThen(f(FetchPerpsOpenOrdersResponseSchema)))}var Gm=z.object({orderId:PerpsOrderIdSchema.optional(),clientOrderId:PerpsClientOrderIdSchema.optional(),instrumentId:PerpsInstrumentIdSchema.optional(),start:ye.optional(),end:ye.optional()}).default({}),Km=Gm.transform(({end:e,start:r,...t})=>({...t,endTimestamp:e,startTimestamp:r}));async function cs(e,r){let t=l(r,Km);return await unwrap(e.get("/v1/account/orders",{params:Ee(t)}).andThen(f(FetchPerpsOrdersResponseSchema)))}var $m=Ar.extend({cursor:PaginationCursorSchema.optional()}),Vm=z.object({cursor:PaginationCursorSchema}),Zm=z.union([$m.transform(({cursor:e,...r})=>({cursor:e,params:wr(r,or)})),Vm.transform(({cursor:e})=>({cursor:e,params:void 0}))]);function ds(e,r={}){let{cursor:t,params:o}=l(r,Zm);return x(n=>{let s;n===void 0?(invariant(o!==void 0,"Expected initial Perps fills params."),s={kind:"perpsFills",seenKeys:[],...o}):s=Ge(n,Or);let{kind:a,seenKeys:y,...P}=s,v=new Set(s.seenKeys);return e.get("/v1/account/fills",{params:Ee(P)}).andThen(f(ListPerpsFillsResponseSchema)).map(A=>{let V=A.data.filter(F=>!v.has(String(F.tradeId)));return Lr({getKey:F=>String(F.tradeId),getTimestamp:F=>F.timestamp,items:V,responseData:A.data,responseMore:A.more,state:s})})},t)}var Ym=Ar.extend({cursor:PaginationCursorSchema.optional(),instrumentId:PerpsInstrumentIdSchema.optional()}),Jm=z.object({cursor:PaginationCursorSchema}),Qm=z.union([Ym.transform(({cursor:e,...r})=>({cursor:e,params:wr(r,or)})),Jm.transform(({cursor:e})=>({cursor:e,params:void 0}))]);function us(e,r={}){let{cursor:t,params:o}=l(r,Qm);return x(n=>{let s;n===void 0?(invariant(o!==void 0,"Expected initial Perps funding payment params."),s={kind:"perpsFundingPayments",seenKeys:[],...o}):s=Ge(n,Or);let{kind:a,seenKeys:y,...P}=s,v=new Set(s.seenKeys);return e.get("/v1/account/funding",{params:Ee(P)}).andThen(f(ListPerpsFundingPaymentsResponseSchema)).map(A=>{let V=A.data.filter(F=>!v.has(`${F.instrumentId}:${F.timestamp}:${F.funding}`));return Lr({getKey:F=>`${F.instrumentId}:${F.timestamp}:${F.funding}`,getTimestamp:F=>F.timestamp,items:V,responseData:A.data,responseMore:A.more,state:s})})},t)}var Xm=Ar.extend({cursor:PaginationCursorSchema.optional(),depositStatus:PerpsDepositStatusSchema.optional(),hash:TxHashSchema.optional()}),el=z.object({cursor:PaginationCursorSchema}),rl=z.union([Xm.transform(({cursor:e,...r})=>({cursor:e,params:wr(r,rs)})),el.transform(({cursor:e})=>({cursor:e,params:void 0}))]);function ms(e,r={}){let{cursor:t,params:o}=l(r,rl);return x(n=>{let s;n===void 0?(invariant(o!==void 0,"Expected initial Perps deposit params."),s={kind:"perpsDeposits",seenKeys:[],...o}):s=Ge(n,Or);let{kind:a,seenKeys:y,...P}=s,v=new Set(s.seenKeys);return e.get("/v1/account/deposits",{params:Ee(P)}).andThen(f(ListPerpsDepositsResponseSchema)).map(A=>{let V=A.data.filter(F=>!v.has(F.hash));return Lr({getKey:F=>F.hash,getTimestamp:ul,items:V,responseData:A.data,responseMore:A.more,state:s})})},t)}var tl=Ar.extend({cursor:PaginationCursorSchema.optional(),withdrawalStatus:PerpsWithdrawalStatusSchema.optional(),hash:TxHashSchema.optional()}),ol=z.object({cursor:PaginationCursorSchema}),nl=z.union([tl.transform(({cursor:e,...r})=>({cursor:e,params:wr(r,rs)})),ol.transform(({cursor:e})=>({cursor:e,params:void 0}))]);function ls(e,r={}){let{cursor:t,params:o}=l(r,nl);return x(n=>{let s;n===void 0?(invariant(o!==void 0,"Expected initial Perps withdrawal params."),s={kind:"perpsWithdrawals",seenKeys:[],...o}):s=Ge(n,Or);let{kind:a,seenKeys:y,...P}=s,v=new Set(s.seenKeys);return e.get("/v1/account/withdrawals",{params:Ee(P)}).andThen(f(ListPerpsWithdrawalsResponseSchema)).map(A=>{let V=A.data.filter(F=>!v.has(String(F.withdrawalId)));return Lr({getKey:F=>String(F.withdrawalId),getTimestamp:ml,items:V,responseData:A.data,responseMore:A.more,state:s})})},t)}var sl=ts.extend({cursor:PaginationCursorSchema.optional()}),al=z.object({cursor:PaginationCursorSchema}),il=z.union([sl.transform(({cursor:e,...r})=>({cursor:e,params:Ps(r)})),al.transform(({cursor:e})=>({cursor:e,params:void 0}))]);function ys(e,r){let{cursor:t,params:o}=l(r,il);return x(n=>{let s;n===void 0?(invariant(o!==void 0,"Expected initial Perps equity history params."),s={kind:"perpsEquityHistory",...o}):s=Ge(n,os);let{kind:a,...y}=s;return e.get("/v1/account/equity",{params:Ee(y)}).andThen(f(ListPerpsEquityHistoryResponseSchema)).map(P=>{let v=P.data.at(-1),A=P.more&&v!==void 0&&v.timestamp<s.endTimestamp;return {items:P.data,hasMore:A,nextCursor:A?It({...s,startTimestamp:v.timestamp+gs(s.interval)}):void 0}})},t)}var pl=ts.extend({cursor:PaginationCursorSchema.optional()}),cl=z.object({cursor:PaginationCursorSchema}),dl=z.union([pl.transform(({cursor:e,...r})=>({cursor:e,params:Ps(r)})),cl.transform(({cursor:e})=>({cursor:e,params:void 0}))]);function fs(e,r){let{cursor:t,params:o}=l(r,dl);return x(n=>{let s;n===void 0?(invariant(o!==void 0,"Expected initial Perps PnL history params."),s={kind:"perpsPnlHistory",...o}):s=Ge(n,os);let{kind:a,...y}=s;return e.get("/v1/account/pnl",{params:Ee(y)}).andThen(f(ListPerpsPnlHistoryResponseSchema)).map(P=>{let v=P.data.at(-1),A=P.more&&v!==void 0&&v.timestamp<s.endTimestamp;return {items:P.data,hasMore:A,nextCursor:A?It({...s,startTimestamp:v.timestamp+gs(s.interval)}):void 0}})},t)}function wr(e,r){let t=Date.now(),{end:o,start:n,...s}=e;return {...s,endTimestamp:o??t,startTimestamp:n??t-r}}function Ps(e){return {endTimestamp:e.end??Date.now(),interval:e.interval,startTimestamp:e.start}}function Ge(e,r){try{return r.parse(JSON.parse(atob(e)))}catch(t){throw new a("Invalid Perps account pagination cursor",{cause:t})}}function It(e){return toPaginationCursor(btoa(JSON.stringify(e)))}function Ee(e){return g(e,R())}function ul(e){return e.confirmedTimestamp??e.createdTimestamp}function ml(e){return e.confirmedTimestamp??e.createdTimestamp}function Lr(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:It({...e.state,endTimestamp:s,seenKeys:Array.from(a)})}}function gs(e){switch(e){case "1h":return 3600*1e3;case "4h":return 14400*1e3;case "1d":return or;case "1w":return 7*or}invariant(false,`Unsupported Perps account history interval: ${String(e)}`);}var vt=z.object({instrumentId:PerpsInstrumentIdSchema,side:OrderSideSchema,quantity:PerpsDecimalInputSchema,reduceOnly:z.boolean().default(false),clientOrderId:PerpsClientOrderIdSchema.optional()}),El=vt.extend({price:PerpsDecimalInputSchema,timeInForce:z.literal(PerpsTimeInForce.GTC),postOnly:z.boolean().default(false)}),hl=vt.extend({price:PerpsDecimalInputSchema.optional(),timeInForce:z.literal(PerpsTimeInForce.IOC),postOnly:z.never().optional()}),Sl=vt.extend({price:PerpsDecimalInputSchema.optional(),timeInForce:z.literal(PerpsTimeInForce.FOK),postOnly:z.never().optional()}),xs=z.discriminatedUnion("timeInForce",[El,hl,Sl]),Fr=z.object({triggerPrice:PerpsDecimalInputSchema,limitPrice:PerpsDecimalInputSchema.optional()}),Mr=z.object({triggerPrice:PerpsDecimalInputSchema}),Tl=z.union([z.object({takeProfit:Fr,stopLoss:Fr.optional()}),z.object({takeProfit:Fr.optional(),stopLoss:Fr})]),xl=z.object({orders:z.array(xs).min(1),expiresAt:z.number().int().positive().optional()});async function At(e,r){let t=l(r,xl);return await e.sendSignedWsCommand({op:["createOrders",t.orders.map(Os)],responseSchema:z.array(PerpsPostOrderAckSchema),timeoutMessage:"Perps post order acknowledgement timed out.",expiresAt:t.expiresAt})}var Cl=z.intersection(xs,z.intersection(Tl,z.object({expiresAt:z.number().int().positive().optional()})));function Cs(e){return e.takeProfit!==void 0||e.stopLoss!==void 0}async function bs(e,r){let t=l(r,Cl),o=[Os(t)],n=t.side===OrderSide.SELL;return t.takeProfit!==void 0&&o.push(Dr({buy:n,instrumentId:t.instrumentId,kind:PerpsTpSlKind.TakeProfit,quantity:toDecimalString(t.quantity),trigger:t.takeProfit})),t.stopLoss!==void 0&&o.push(Dr({buy:n,instrumentId:t.instrumentId,kind:PerpsTpSlKind.StopLoss,quantity:toDecimalString(t.quantity),trigger:t.stopLoss})),await ws(e,{expiresAt:t.expiresAt,group:PerpsTpSlScope.Order,orders:o})}var bl=z.union([z.object({takeProfit:Mr,stopLoss:Mr.optional()}),z.object({takeProfit:Mr.optional(),stopLoss:Mr})]),Il=z.intersection(bl,z.object({instrumentId:PerpsInstrumentIdSchema,expiresAt:z.number().int().positive().optional()})),kl=z.intersection(Il,z.object({buy:z.boolean()}));async function Is(e,r){let t=l(r,kl),o=[];return t.takeProfit!==void 0&&o.push(Dr({buy:t.buy,instrumentId:t.instrumentId,kind:PerpsTpSlKind.TakeProfit,quantity:"0",trigger:t.takeProfit})),t.stopLoss!==void 0&&o.push(Dr({buy:t.buy,instrumentId:t.instrumentId,kind:PerpsTpSlKind.StopLoss,quantity:"0",trigger:t.stopLoss})),await ws(e,{expiresAt:t.expiresAt,group:PerpsTpSlScope.Position,orders:o})}var ql=z.union([z.object({orderId:PerpsOrderIdSchema,clientOrderId:z.undefined().optional(),expiresAt:z.number().int().positive().optional()}),z.object({clientOrderId:PerpsClientOrderIdSchema,orderId:z.undefined().optional(),expiresAt:z.number().int().positive().optional()})]);async function ks(e,r){let t=l(r,ql),[o]=t.orderId!==void 0?await Ur(e,{orderIds:[t.orderId],expiresAt:t.expiresAt}):await Ur(e,{clientOrderIds:[t.clientOrderId],expiresAt:t.expiresAt});return expectPresent(o,"Expected Perps cancel order result.")}var vl=z.union([z.object({orderIds:z.array(PerpsOrderIdSchema).min(1),clientOrderIds:z.undefined().optional(),expiresAt:z.number().int().positive().optional()}),z.object({clientOrderIds:z.array(PerpsClientOrderIdSchema).min(1),orderIds:z.undefined().optional(),expiresAt:z.number().int().positive().optional()})]);async function Ur(e,r){let t=l(r,vl);return t.orderIds!==void 0?await e.sendSignedWsCommand({op:["cancelOrders",t.orderIds],responseSchema:z.array(PerpsCancelOrderResultSchema),timeoutMessage:"Perps cancel order response timed out.",expiresAt:t.expiresAt}):await e.sendSignedWsCommand({op:["cancelOrdersCOID",t.clientOrderIds],responseSchema:z.array(PerpsCancelOrderResultSchema),timeoutMessage:"Perps cancel order response timed out.",expiresAt:t.expiresAt})}var Al=z.object({instrumentId:PerpsInstrumentIdSchema.optional(),expiresAt:z.number().int().positive().optional()}).default({});async function qs(e,r,t){let o=l(t,Al),n=["cancelAll",o.instrumentId===void 0?[]:[o.instrumentId]],s=r(n,o.expiresAt);await unwrap(e.del("/v1/trade/orders/all",{json:{...s,op:Ot(n)}}).andThen(f(PerpsCancelAllOrdersResponseSchema)));}var Ol=z.object({instrumentId:PerpsInstrumentIdSchema,leverage:z.number().int().positive(),crossMargin:z.boolean()}),vs=k(d,j,c,a);async function As(e,r){let t=l(r,Ol);return await e.sendSignedWsCommand({op:["updateLeverage",[t.instrumentId,t.leverage,t.crossMargin]],responseSchema:PerpsUpdateLeverageResultSchema,timeoutMessage:"Perps update leverage response timed out."})}function Os(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 Dr(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]]}async function ws(e,r){return await e.sendSignedWsCommand({op:["createOrders",r.orders,r.group],responseSchema:z.array(PerpsPostOrderAckSchema),timeoutMessage:"Perps place TP/SL order acknowledgement timed out.",expiresAt:r.expiresAt})}function Ot(e){let[r,t,o]=e;switch(r){case "createOrders":return Fl({args:t.map(wl),type:r},o);case "cancelOrders":case "cancelOrdersCOID":return {type:r,args:t};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}}}default:invariant(false,`Unsupported Perps command: ${String(r)}`);}}function wl(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=Ll(e[8])),r}function Ll(e){let r={tpsl:e[2],trp:e[1]};return e[0]!==void 0&&(r.market=e[0]),r}function Fl(e,r){return r!==void 0&&(e.grp=r),e}var Dl=3e4,Ms=3e4,Bs=2e3,zl=["balances","portfolio","orders","fills","funding","deposits","withdrawals","tpsl"],jl=z.object({id:z.number().int().positive().optional(),data:z.unknown().optional()}).passthrough(),Us=z.union([PerpsCommandAckSchema,z.array(PerpsCommandAckSchema)]).transform(e=>Array.isArray(e)?e.find(r=>r.status==="err")??e[0]:e),Ds=class{credentials;#e;#r;#t;#o;#n;#c=new vr({heartbeat:new kr});#i=pushable({objectMode:true});#s=new Map;#p=new Set;#a=new qr;#d=new Map;#l=1;#m;constructor(r){this.#e=new Ir({headers:r.headers,resolveHeaders:async()=>this.#I(),root:r.restUrl}),this.#r=r.chainId,this.credentials=r.credentials,this.#t=r.headers,this.#o=r.onClose,this.#n=r.wsUrl;}get closed(){return this.#m!==void 0}async connect(){await this.#P(false);}async close(){this.#m===void 0&&(this.#m=this.#q()),await this.#m;}[Symbol.asyncIterator](){return this.#i[Symbol.asyncIterator]()}async fetchBalances(){return await ns(this.#e)}async fetchPortfolio(){return await ss(this.#e)}async fetchStats(){return await as(this.#e)}async fetchAccountConfig(r){return await is(this.#e,r)}async fetchOpenOrders(r){return await ps(this.#e,r)}async fetchOrders(r){return await cs(this.#e,r)}listFills(r={}){return ds(this.#e,r)}listFundingPayments(r={}){return us(this.#e,r)}listDeposits(r={}){return ms(this.#e,r)}listWithdrawals(r={}){return ls(this.#e,r)}listEquityHistory(r){return ys(this.#e,r)}listPnlHistory(r){return fs(this.#e,r)}async placeOrder(r){if(Cs(r))return await this.#T(r);let[t]=await At(this.#u(),{orders:[r],expiresAt:r.expiresAt}).then(expectNonEmptyArray);if(t.status==="err")throw new d(t.error,{status:200});return {order:(await this.#h(n=>n.type==="order"&&n.payload.id===t.orderId,Bs)).payload}}async postOrders(r){return await At(this.#u(),r)}async#T(r){let t=await bs(this.#u(),r).then(expectNonEmptyArray);for(let P of t)if(P.status==="err")throw new d(P.error,{status:200});let[o]=t,n=sr(o),s=await this.#h(P=>P.type==="order"&&P.payload.id===n.orderId,Bs),a=1,y={};return r.takeProfit!==void 0&&(y.takeProfit=sr(expectPresent(t[a++],"Expected Perps take-profit acknowledgement."))),r.stopLoss!==void 0&&(y.stopLoss=sr(expectPresent(t[a],"Expected Perps stop-loss acknowledgement."))),{order:s.payload,tpSl:y}}async placePositionTpSl(r){let t=await Is(this.#u(),{...r,buy:await this.#x(r.instrumentId)}).then(expectNonEmptyArray);for(let s of t)if(s.status==="err")throw new d(s.error,{status:200});let o=0,n={};return r.takeProfit!==void 0&&(n.takeProfit=sr(expectPresent(t[o++],"Expected Perps take-profit acknowledgement."))),r.stopLoss!==void 0&&(n.stopLoss=sr(expectPresent(t[o],"Expected Perps stop-loss acknowledgement."))),{tpSl:n}}async#x(r){let o=(await this.fetchPortfolio()).positions.find(s=>s.instrumentId===r),n=o===void 0?0:_l(o.size);if(n===0)throw new a(`No open Perps position for instrument ${r}.`);return n<0}async cancelOrder(r){return await ks(this.#u(),r)}async cancelOrders(r){return await Ur(this.#u(),r)}async cancelAllOrders(r){await qs(this.#e,(t,o)=>this.#g(t,o),r);}async updateLeverage(r){return await As(this.#u(),r)}async#P(r){await this.#c.connect({onClose:()=>this.#O(),onError:()=>{},onMessage:t=>this.#v(t),onOpen:()=>{},headers:this.#t,url:this.#n}),await this.#C(),await this.#b(),this.#a.resetBackoff(),r&&(this.#d.clear(),this.#i.push({reason:"reconnect",type:"resync"}));}async#C(){await this.#y({id:this.#l++,op:{args:{proxy:this.credentials.proxy,secret:this.credentials.secret},type:"auth"},req:"post"},Us,Dl,"Perps session authentication timed out.");}async#b(){await this.#y({id:this.#l++,req:"sub",chs:zl},Us,Ms,"Perps session subscription timed out.");}#I(){return {"POLYMARKET-PROXY":this.credentials.proxy,"POLYMARKET-SECRET":this.credentials.secret}}#u(){return {sendSignedWsCommand:r=>this.#k(r)}}async#k(r){let t=Ot(r.op),o=this.#g(r.op,r.expiresAt);return await this.#y({...o,id:this.#l++,op:t,req:"post"},r.responseSchema,Ms,r.timeoutMessage)}#g(r,t){let o=Nl(),n=Date.now(),s;try{s=$n({chainId:this.#r,op:r,privateKey:this.credentials.privateKey,salt:o,timestamp:n});}catch(y){throw j.fromError(y,"Could not sign the Perps session command")}let a={salt:o,sig:s,ts:n};return t!==void 0&&(a.exp=t),a}async#y(r,t,o,n){let s=Wl(t);this.#s.set(r.id,s);let a=setNonBlockingTimeout(()=>{s.reject(new c(n));},o);try{if(!this.#c.send(r))throw new c("Perps session transport is not open.");return await s.promise}finally{clearTimeout(a),this.#s.delete(r.id);}}async#q(){this.#a.stop(),this.#R(new c("Perps session closed.")),this.#S(new c("Perps session closed.")),this.#i.end(),await this.#c.close(),this.#o(this);}#v(r){if(this.#A(r))return;let t=PerpsSessionUpdateEventSchema.safeParse(r);if(!t.success)return;let o=t.data;this.#w(o),this.#E(o);}#A(r){let t=jl.safeParse(r);if(!t.success||t.data.id===void 0)return false;let o=this.#s.get(t.data.id);if(o===void 0)return true;let n=o.schema.safeParse(t.data.data);if(!n.success){let s=zs(t.data.data??t.data);return s!==void 0?o.reject(new d(s.error,{status:200})):o.reject(new c("Perps session unexpected response.")),true}return Hl(n.data)?o.reject(new d(n.data.error,{status:200})):o.resolve(n.data),true}#O(){this.#R(new c("Perps session connection closed.")),this.#S(new c("Perps session connection closed.")),this.#m===void 0&&this.#a.schedule({reconnect:()=>this.#P(true),shouldReconnect:()=>this.#m===void 0});}#R(r){for(let t of this.#s.values())t.reject(r);this.#s.clear();}#w(r){let t=this.#d.get(r.channel);this.#d.set(r.channel,r.sequence),!(t===void 0||r.sequence===t+1)&&this.#E({channel:r.channel,previousSequence:t,reason:"sequence_gap",sequence:r.sequence,type:"resync"});}#E(r){this.#F(r),this.#i.push(r);}#h(r,t){return this.#L(r,t).then(o=>o)}#L(r,t){let o,n=new Promise((s,a)=>{o={predicate:r,reject:a,resolve:s,timeout:setNonBlockingTimeout(()=>{this.#f(o),a(new f$1("Perps event wait timed out."));},t)};});return this.#p.add(o),n}#F(r){for(let t of Array.from(this.#p))t.predicate(r)&&(this.#f(t),t.resolve(r));}#f(r){this.#p.delete(r)&&clearTimeout(r.timeout);}#S(r){for(let t of Array.from(this.#p))this.#f(t),t.reject(r);}};function Wl(e){let r,t;return {promise:new Promise((n,s)=>{r=n,t=s;}),reject:t,resolve:r,schema:e}}function Hl(e){return zs(e)!==void 0}function zs(e){if(Array.isArray(e)||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 sr(e){if(e.status==="err")throw new d(e.error,{status:200});return {orderId:e.orderId}}function _l(e){let r=e.trim(),t=r.replace(/^[+-]/,"").replace(".","");return /^0*$/.test(t)?0:r.startsWith("-")?-1:1}function Nl(){let[e]=globalThis.crypto.getRandomValues(new Uint32Array(1));return invariant(e!==void 0,"Expected crypto.getRandomValues to return a salt."),e}var Oe=k(e,d,c,b,a),fe=z.number().int().nonnegative(),Hs=1440*60*1e3,dy=z.object({instrumentId:PerpsInstrumentIdSchema.optional(),category:PerpsInstrumentCategorySchema.optional()}).default({}),QC=Oe;async function XC(e,r){let t=l(r,dy);return unwrap(e.perps.get("/v1/info/instruments",{params:g(t,R())}).andThen(f(FetchPerpsInstrumentsResponseSchema)))}var uy=z.object({instrumentId:PerpsInstrumentIdSchema}),eb=Oe;async function rb(e,r){let t=l(r,uy),[o]=await ly(e,t);if(o===void 0)throw new b(`Perps ticker ${t.instrumentId} was not returned by the API`);return o}var my=z.object({instrumentId:PerpsInstrumentIdSchema.optional()}).default({}),tb=Oe;async function ly(e,r){let t=l(r,my),o=g(t,R()),[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 yy=z.union([z.literal(10),z.literal(100),z.literal(500),z.literal(1e3)]),fy=z.object({instrumentId:PerpsInstrumentIdSchema,depth:yy.default(100)}),ob=Oe;async function nb(e,r){let t=l(r,fy);return unwrap(e.perps.get("/v1/info/book",{params:g(t,R())}).andThen(f(PerpsBookSchema)))}var Py=z.object({instrumentId:PerpsInstrumentIdSchema,interval:PerpsKlineIntervalSchema,start:fe.optional(),end:fe.optional(),cursor:PaginationCursorSchema.optional()}),gy=z.object({cursor:PaginationCursorSchema}),Ry=z.union([Py.transform(({cursor:e,...r})=>({cursor:e,params:qy(r)})),gy.transform(({cursor:e})=>({cursor:e,params:void 0}))]),sb=Oe;function ab(e,r){let{cursor:t,params:o}=l(r,Ry);return x(n=>{let s=n===void 0?vy(o):wy(n);return e.perps.get("/v1/info/klines",{params:g({endTimestamp:s.endTimestamp,instrumentId:s.instrumentId,interval:s.interval,startTimestamp:s.startTimestamp},R())}).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?Bt({...s,startTimestamp:y.timestamp+My(s.interval)}):void 0}})},t)}var _s=z.object({instrumentId:PerpsInstrumentIdSchema,start:fe.optional(),end:fe.optional()}),Ey=_s.extend({cursor:PaginationCursorSchema.optional()}),hy=z.object({cursor:PaginationCursorSchema}),Sy=z.union([Ey.transform(({cursor:e,...r})=>({cursor:e,params:Ns(r)})),hy.transform(({cursor:e})=>({cursor:e,params:void 0}))]),Ty=_s.extend({cursor:PaginationCursorSchema.optional()}),xy=z.object({cursor:PaginationCursorSchema}),ib=Oe;function pb(e,r){let{cursor:t,params:o}=l(r,Sy);return x(n=>{let s=n===void 0?Ay(o):Ly(n);return e.perps.get("/v1/info/funding",{params:g({endTimestamp:s.endTimestamp,instrumentId:s.instrumentId,startTimestamp:s.startTimestamp},R())}).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?Bt({...s,endTimestamp:y.timestamp-1}):void 0}})},t)}var Cy=z.union([Ty.transform(({cursor:e,...r})=>({cursor:e,params:Ns(r)})),xy.transform(({cursor:e})=>({cursor:e,params:void 0}))]),cb=Oe;function db(e,r){let{cursor:t,params:o}=l(r,Cy);return x(n=>{let s=n===void 0?Oy(o):Fy(n),a=new Set(s.seenTradeIds);return e.perps.get("/v1/info/trades",{params:g({endTimestamp:s.endTimestamp,instrumentId:s.instrumentId,startTimestamp:s.startTimestamp},R())}).andThen(f(FetchPerpsTradesResponseSchema)).map(y=>{let P=y.data.filter(wa=>!a.has(wa.tradeId)),v=y.data.at(-1),A=P.at(-1),V=A?.timestamp??v?.timestamp,F=y.more&&V!==void 0&&V>s.startTimestamp;return {items:P,hasMore:F,nextCursor:F?Bt({...s,endTimestamp:A===void 0?V-1:V,seenTradeIds:A===void 0?[]:By(s,P,A)}):void 0}})},t)}var ub=k(e,d,c,b);async function mb(e){return (await unwrap(e.perps.get("/v1/info/fees").andThen(f(FetchPerpsFeesResponseSchema)))).feeSchedule}var by=z.object({kind:z.literal("perpsCandles"),instrumentId:PerpsInstrumentIdSchema,interval:PerpsKlineIntervalSchema,startTimestamp:fe,endTimestamp:fe}),Iy=z.object({kind:z.literal("perpsFundingHistory"),instrumentId:PerpsInstrumentIdSchema,startTimestamp:fe,endTimestamp:fe}),ky=z.object({kind:z.literal("perpsTrades"),instrumentId:PerpsInstrumentIdSchema,startTimestamp:fe,endTimestamp:fe,seenTradeIds:z.array(PerpsTradeIdSchema)});function qy(e){let r=Date.now();return {endTimestamp:e.end??r,instrumentId:e.instrumentId,interval:e.interval,startTimestamp:e.start??r-Hs}}function Ns(e){let r=Date.now();return {endTimestamp:e.end??r,instrumentId:e.instrumentId,startTimestamp:e.start??r-Hs}}function vy(e){return invariant(e!==void 0,"Expected initial Perps candles params."),{kind:"perpsCandles",...e}}function Ay(e){return invariant(e!==void 0,"Expected initial Perps funding params."),{kind:"perpsFundingHistory",...e}}function Oy(e){return invariant(e!==void 0,"Expected initial Perps trades params."),{kind:"perpsTrades",seenTradeIds:[],...e}}function wy(e){return Mt(e,by)}function Ly(e){return Mt(e,Iy)}function Fy(e){return Mt(e,ky)}function Mt(e,r){try{return r.parse(JSON.parse(atob(e)))}catch(t){throw new a("Invalid Perps pagination cursor",{cause:t})}}function Bt(e){return toPaginationCursor(btoa(JSON.stringify(e)))}function My(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 By(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 Uy=z.custom(e=>isPrivateKey(e),"Expected a hex-encoded 32-byte private key."),Dy=z.object({proxy:z.string().transform(e=>expectEvmAddress(e)),privateKey:Uy,secret:z.string().min(1),expiresAt:z.number().int().positive()}),zy=10080*60*1e3,jy=z.strictObject({expiresIn:z.number().int().positive().default(zy),label:z.string().min(1).optional()}),Wy=z.strictObject({credentials:Dy}),Hy=z.union([jy,Wy]),_y=z.object({proxy:z.string()}),Ny=_y.transform(e=>({proxy:expectEvmAddress(e.proxy)})),Gs=z.bigint().positive().max(Y),Gy=z.object({amount:Gs,metadata:K.optional()}),Ky=z.object({amount:Gs}),lb=k(e,d,j,c,b,a),yb=k(e,d,j,c,b,a),fb=k(a),Pb=k(h,e,d,j,c,b,a),gb=k(e,d,j,c,b,a);async function Rb(e,r={}){let t=l(r,Hy),o="credentials"in t?await Zy(e,t.credentials):await Vy(e,t);return e.webSockets.perpsSession.connect(o)}async function Eb(e,r){let t=l(r,Ny),o={type:"deleteProxy",args:{proxy:t.proxy}},n=["deleteProxy",[t.proxy]],s=Ut(),a=Date.now(),y=await Jy(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 d(P.error??"Perps credentials revocation was rejected.",{status:200})}async function $y(e,r){let t=l(r,Gy),{contracts:o}=e.environment,n=Oo(o.perpsDepositContract,o.collateralToken,t.amount,e.account.signer);return async function*(){return e.account.walletType===WalletType.EOA?N(yield nf(G(e.environment.chainId,n))):yield*await J(e,{calls:[n],metadata:t.metadata??`Deposit ${t.amount} of ${o.collateralToken} to Perps`})}.call(null)}function hb(e,r){return $y(e,r).then(_(e.signer))}async function Sb(e,r){let t=l(r,Ky),o=Math.floor(Date.now()/1e3),n=Ut(),s={type:"withdraw",args:{account:e.account.signer,token:e.environment.contracts.collateralToken,amount:t.amount.toString(),to:e.account.wallet}},a=await Qy(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 d(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 Vy(e,r){let t=rf(),o=$s(t),n=e.account.signer,s=Date.now()+r.expiresIn,a=Date.now(),y=Ut(),P={args:{expiry:s,owner:n,proxy:o},type:"createProxy"},v=await Yy(e,{expiresAt:s,proxy:o,salt:y,timestamp:a}),A={op:P,salt:y,sig:v,ts:a};r.label!==void 0&&(A.label=r.label);let V=await unwrap(e.perps.post("/v1/account/proxy",{json:A}).andThen(f(PerpsCreateProxyResponseSchema))),F={expiresAt:s,privateKey:t,proxy:o,secret:V.secret};return Ks(e,F)}async function Zy(e,r){return tf(r),Ks(e,r)}async function Ks(e,r){let t=await unwrap(e.perps.get("/v1/account/credentials",{headers:of(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 Yy(e,r){try{return await e.signer.signTypedData(ef({chainId:e.environment.chainId,...r}))}catch(t){throw j.fromError(t,"Could not sign the Perps proxy credentials request")}}async function Jy(e,r){try{return await e.signer.signTypedData(xt({chainId:e.environment.chainId,op:r.signedOp,salt:r.salt,timestamp:r.timestamp}))}catch(t){throw j.fromError(t,"Could not sign the Perps operation request")}}async function Qy(e,r){try{return await e.signer.signTypedData(Xy({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 j.fromError(t,"Could not sign the Perps withdrawal request")}}function Xy(e){return {domain:{chainId:e.chainId,name:"Polymarket",verifyingContract:e.contract,version:"1"},message:{account:e.account,amount:e.amount,fee:0n,salt:e.salt,token:e.token,to:e.to,ts:e.timestamp},primaryType:"Withdraw",types:{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 ef(e){return {domain:{chainId:e.chainId,name:"Polymarket",version:"1"},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"}]}}}function rf(){return expectPrivateKey(Secp256k1.randomPrivateKey(),"Generated invalid Perps proxy key.")}function $s(e){return expectEvmAddress(Address.fromPublicKey(Secp256k1.getPublicKey({privateKey:e})))}function tf(e){let r=$s(e.privateKey);if(!isSameEvmAddress(r,e.proxy))throw new a("Perps credentials private key does not match the proxy address.")}function of(e){return {"POLYMARKET-PROXY":e.proxy,"POLYMARKET-SECRET":e.secret}}function nf(e){return {kind:"sendPerpsDepositTransaction",request:e}}function Ut(){let[e]=crypto.getRandomValues(new Uint32Array(1));return invariant(e!==void 0,"Expected crypto.getRandomValues to return a salt."),e}var Zs=(s=>(s.CurrentValueDesc="current_value_desc",s.FirstEntryDesc="first_entry_desc",s.EntryCostDesc="entry_cost_desc",s.ResolvedAtDesc="resolved_at_desc",s.UpdatedAsc="updated_asc",s))(Zs||{}),mf=z.enum(["CURRENT","INITIAL","TOKENS","CASHPNL","PERCENTPNL","TITLE","RESOLVING","PRICE","AVGPRICE"]),Ys=z.enum(["ASC","DESC"]),lf=z.object({cursor:PaginationCursorSchema.optional(),user:z.string(),market:z.array(z.string()).optional(),eventId:z.array(z.number().int()).optional(),sizeThreshold:z.number().optional(),redeemable:z.boolean().optional(),mergeable:z.boolean().optional(),pageSize:O.default(20),sortBy:mf.optional(),sortDirection:Ys.optional(),title:z.string().max(100).optional()}).refine(e=>!(e.market&&e.eventId),{message:"Provide market or eventId, not both",path:["eventId"]}),Lb=k(e,d,c,b,a);function Fb(e,r){let{cursor:t,pageSize:o,...n}=l(r,lf);return x(s=>{let a=U(s,o);return e.data.get("/positions",{params:H({...n,limit:a.pageSize+1,offset:a.offset})}).andThen(f(ListPositionsResponseSchema)).map(y=>{let P=y.length>a.pageSize;return {items:y.slice(0,a.pageSize),hasMore:P,nextCursor:P?B({offset:a.offset+a.pageSize,pageSize:a.pageSize}):void 0}})},t)}var yf=z.enum(["REALIZEDPNL","TITLE","PRICE","AVGPRICE","TIMESTAMP"]),ff=z.object({cursor:PaginationCursorSchema.optional(),user:z.string(),market:z.array(z.string()).optional(),title:z.string().max(100).optional(),eventId:z.array(z.number().int()).optional(),pageSize:O.default(20),sortBy:yf.optional(),sortDirection:Ys.optional()}).refine(e=>!(e.market&&e.eventId),{message:"Provide market or eventId, not both",path:["eventId"]}),Mb=k(e,d,c,b,a);function Bb(e,r){let{cursor:t,pageSize:o,...n}=l(r,ff);return x(s=>{let a=U(s,o);return e.data.get("/closed-positions",{params:H({...n,limit:a.pageSize+1,offset:a.offset})}).andThen(f(ListClosedPositionsResponseSchema)).map(y=>{let P=y.length>a.pageSize;return {items:y.slice(0,a.pageSize),hasMore:P,nextCursor:P?B({offset:a.offset+a.pageSize,pageSize:a.pageSize}):void 0}})},t)}var Pf=z.enum(Zs),gf=z.union([ComboConditionIdSchema,z.array(ComboConditionIdSchema)]),Rf=z.object({cursor:PaginationCursorSchema.optional(),user:z.string(),pageSize:O.default(20),status:ComboPositionStatusSchema.optional(),sort:Pf.optional(),conditionId:gf.optional(),updatedAfter:z.number().int().min(0).optional(),updatedBefore:z.number().int().min(0).optional()}),Ub=k(e,d,c,b,a);function Db(e,r){let{cursor:t,pageSize:o,conditionId:n,...s}=l(r,Rf);return x(a=>{let y=g({...s,limit:o,cursor:a},R({updatedAfter:"updatedAfter",updatedBefore:"updatedBefore"}));return Ef(y,n),e.data.get("/v1/positions/combos",{params:y}).andThen(f(ListComboPositionsResponseSchema)).map(P=>{let v=P.pagination.nextCursor??void 0;return {items:P.combos,hasMore:v!==void 0,nextCursor:v}})},t)}function Ef(e,r){r!==void 0&&e.append("market_id",Array.isArray(r)?r.join(","):r);}var hf=z.object({user:z.string(),market:z.array(z.string()).optional()}),zb=k(e,d,c,b,a);async function jb(e,r){let t=l(r,hf);return unwrap(e.data.get("/value",{params:H(t)}).andThen(f(FetchPortfolioValueResponseSchema)))}var Sf=z.object({user:z.string()}),Wb=k(e,d,c,b,a);async function Hb(e,r){let t=l(r,Sf);return unwrap(e.data.get("/traded",{params:H(t)}).andThen(f(TradedSchema)))}var Tf=z.object({user:z.string()}),_b=k(e,d,c,b,a);async function Nb(e,r){let t=l(r,Tf);return unwrap(e.data.get("/v1/accounting/snapshot",{params:H(t)}).andThen(Qt))}var ra=32,ta=3n,Xs=50,Cf=(1n<<256n)-1n;function jt(e){let r=AbiParameters.encode([{name:"legs",type:"uint256[]"}],[e]),t=Hash.keccak256(AbiParameters.encode([{name:"moduleId",type:"uint256"},{name:"data",type:"bytes"}],[ta,r])),o=toComboConditionId(`0x03${t.slice(34)}0000000000000000000000000000`);return {conditionId:o,positionIds:[toPositionId(BigInt(`${o}00`).toString()),toPositionId(BigInt(`${o}01`).toString())]}}function oa(e){if(e.length===0||e.length>Xs)throw new a(`Combo legs must include 1 to ${Xs} position IDs`);let r=e.map(t=>{let o=sa(t),n=o.toString(16).padStart(ra*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 na(e){let t=sa(e).toString(16).padStart(ra*2,"0"),o=BigInt(`0x${t.slice(0,2)}`),n=Number.parseInt(t.slice(-2),16);if(o!==ta)throw new a("Combo position ID must use the combinatorial module");if(n!==0&&n!==1)throw new a("Combo position ID must be a YES/NO position ID");return {conditionId:toComboConditionId(`0x${t.slice(0,-2)}`),outcomeIndex:n}}function sa(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>Cf)throw new a("Position ID must be a uint256 value");return t}var ia=z.object({amount:z.bigint().min(0n),conditionId:CtfConditionIdSchema,metadata:K.optional()}),If=z.object({amount:z.bigint().positive(),legs:z.array(PositionIdSchema).min(1).max(50),metadata:K.optional()}),pa=z.array(PositionIdSchema).min(1).max(50).transform(oa),kf=z.object({amount:z.bigint().positive(),legs:pa,metadata:K.optional()}),qf=z.union([ia.extend({legs:z.never().optional()}),If.extend({conditionId:z.never().optional()})]),ca=k(e,d,c,b,a),uI=ca,mI=ca,da=k(e,d,c,b,a),lI=da,yI=da,ua=k(e,d,c,b,a),fI=ua,PI=ua;async function ma(e,r){let t=l(r,ia),o=await Nt(e,{conditionId:t.conditionId}),n=wo(o.adapterAddress,e.environment.contracts.collateralToken,o.conditionId,t.amount);return async function*(){return e.account.walletType===WalletType.EOA?N(yield Wt(G(e.environment.chainId,n))):yield*await J(e,{calls:[n],metadata:t.metadata??`Split ${t.amount} positions for market ${o.marketId} (condition ${o.conditionId})`})}.call(null)}async function la(e,r){let t=l(r,kf),o=Jr(e.environment.contracts.combinatorialModule,t.legs),n=jt(t.legs),s=Mo(e.environment.contracts.protocolV2Router,n.conditionId,t.amount);return async function*(){return e.account.walletType===WalletType.EOA?(await N(yield Wt(G(e.environment.chainId,o))).wait(),N(yield Wt(G(e.environment.chainId,s)))):yield*await J(e,{calls:[o,s],metadata:t.metadata??`Split ${t.amount} combo positions for condition ${n.conditionId}`})}.call(null)}async function vf(e,r){let t=l(r,qf);return t.legs!==void 0?la(e,t):ma(e,t)}var ya=k(h,e,d,j,f$1,g$1,c,b,a),gI=ya,RI=ya;function EI(e,r){return ma(e,r).then(_(e.signer))}function hI(e,r){return la(e,r).then(_(e.signer))}function SI(e,r){return vf(e,r).then(_(e.signer))}var fa=z.object({amount:z.union([z.bigint().positive(),z.literal("max")]),conditionId:CtfConditionIdSchema,metadata:K.optional()}),Af=z.object({amount:z.union([z.bigint().positive(),z.literal("max")]),legs:z.array(PositionIdSchema).min(1).max(50),metadata:K.optional()}),Of=z.object({amount:z.union([z.bigint().positive(),z.literal("max")]),legs:pa,metadata:K.optional()}),wf=z.union([fa.extend({legs:z.never().optional()}),Af.extend({conditionId:z.never().optional()})]);async function Pa(e,r){let t=l(r,fa),o=await Nt(e,{conditionId:t.conditionId}),n=Zr(await e.rpc.ethCall(Vr(o.positionErc1155Address,e.account.wallet,o.tokenIds))),s=xa(o.conditionId,n,t.amount),a=Lo(o.adapterAddress,e.environment.contracts.collateralToken,o.conditionId,s);return async function*(){return e.account.walletType===WalletType.EOA?N(yield Ht(G(e.environment.chainId,a))):yield*await J(e,{calls:[a],metadata:t.metadata??`Merge ${s} positions for market ${o.marketId} (condition ${o.conditionId})`})}.call(null)}async function ga(e,r){let t=l(r,Of),o=Jr(e.environment.contracts.combinatorialModule,t.legs),n=jt(t.legs),s=Zr(await e.rpc.ethCall(Vr(e.environment.contracts.positionManager,e.account.wallet,n.positionIds))),a=xa(n.conditionId,s,t.amount),y=Bo(e.environment.contracts.protocolV2Router,n.conditionId,a);return async function*(){return e.account.walletType===WalletType.EOA?(await N(yield Ht(G(e.environment.chainId,o))).wait(),N(yield Ht(G(e.environment.chainId,y)))):yield*await J(e,{calls:[o,y],metadata:t.metadata??`Merge ${a} combo positions for condition ${n.conditionId}`})}.call(null)}async function Lf(e,r){let t=l(r,wf);return t.legs!==void 0?ga(e,t):Pa(e,t)}var Ra=k(h,e,d,j,f$1,g$1,c,b,a),TI=Ra,xI=Ra;function CI(e,r){return Pa(e,r).then(_(e.signer))}function bI(e,r){return ga(e,r).then(_(e.signer))}function II(e,r){return Lf(e,r).then(_(e.signer))}var Ea=z.object({conditionId:CtfConditionIdSchema,marketId:z.never().optional(),amount:z.never().optional(),positionId:z.never().optional(),metadata:K.optional()}),ha=z.object({conditionId:z.never().optional(),marketId:MarketIdSchema,amount:z.never().optional(),positionId:z.never().optional(),metadata:K.optional()}),Ff=z.union([Ea,ha]),Sa=z.object({positionId:PositionIdSchema,conditionId:z.never().optional(),marketId:z.never().optional(),metadata:K.optional()}),Mf=z.union([Ea,ha,Sa]);async function Bf(e,r){let t=l(r,Ff),o=await Nt(e,t.conditionId!==void 0?{conditionId:t.conditionId,closed:true}:{marketId:t.marketId,closed:true}),n=Fo(o.adapterAddress,e.environment.contracts.collateralToken,o.conditionId);return async function*(){return e.account.walletType===WalletType.EOA?N(yield Ta(G(e.environment.chainId,n))):yield*await J(e,{calls:[n],metadata:t.metadata??`Redeem positions for market ${o.marketId} (condition ${o.conditionId})`})}.call(null)}async function Uf(e,r){let t=l(r,Sa),o=na(t.positionId),n=Ao(await e.rpc.ethCall(vo(e.environment.contracts.positionManager,e.account.wallet,t.positionId)));if(n===0n)throw new a("Combo position has no balance to redeem");let s=Uo(e.environment.contracts.protocolV2Router,o.conditionId,o.outcomeIndex,n);return async function*(){return e.account.walletType===WalletType.EOA?N(yield Ta(G(e.environment.chainId,s))):yield*await J(e,{calls:[s],metadata:t.metadata??`Redeem combo position ${t.positionId}`})}.call(null)}async function Df(e,r){let t=l(r,Mf);return t.positionId!==void 0?Uf(e,t):Bf(e,t)}var kI=k(h,e,d,j,c,b,a);function qI(e,r){return Df(e,r).then(_(e.signer))}function Wt(e){return {kind:"sendSplitPositionTransaction",request:e}}function Ht(e){return {kind:"sendMergePositionsTransaction",request:e}}function Ta(e){return {kind:"sendRedeemPositionsTransaction",request:e}}async function Nt(e,r){let t=r.conditionId!==void 0?`condition ${r.conditionId}`:`market ${r.marketId}`,o=await fn(e,r.conditionId!==void 0?{conditionIds:[r.conditionId],closed:r.closed,pageSize:1}:{ids:[zf(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=jf(n,t);return {...s,adapterAddress:s.negRisk?e.environment.contracts.negRiskCollateralAdapter:e.environment.contracts.collateralAdapter,positionErc1155Address:s.negRisk?e.environment.contracts.negRiskAdapter:e.environment.contracts.conditionalTokens}}function zf(e){let r=Number(e);if(!Number.isInteger(r))throw new a(`Market ID must be an integer, received ${e}`);return r}function jf(e,r){if(!isPresent(e.conditionId))throw new b(`Missing condition ID for ${r}`);if(!isPresent(e.state.negRisk))throw new b(`Missing negative-risk flag for ${r}`);let t=e.outcomes.yes.tokenId,o=e.outcomes.no.tokenId;if(!isPresent(t)||!isPresent(o))throw new b(`Missing market token IDs for ${r}`);return {marketId:e.id,conditionId:e.conditionId,negRisk:e.state.negRisk,tokenIds:[t,o]}}function xa(e,r,t){let o=Wf(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 Wf(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 Kf=z.object({address:z.string()}),UI=k(e,d,c,b,a);async function DI(e,r){let t=l(r,Kf);return unwrap(e.gamma.get("/public-profile",{params:g(t,R())}).andThen(f(PublicProfileSchema)).orElse(o=>o instanceof d&&o.status===404?ok(null):err(o)))}var Gt=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;}},HI=k(Gt,j,f$1,c,a),Kt=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;}},_I=k(Kt,f$1,c),$t=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;}},NI=k($t,f$1,c),GI=k(c);async function KI(e){return e.webSockets.rfqQuoter.connect()}var ba=(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))(ba||{}),Zf=z.object({q:z.string().trim().min(1),ascending:z.boolean().optional(),cache:z.boolean().optional(),cursor:PaginationCursorSchema.optional(),eventsStatus:z.string().min(1).optional(),eventsTag:z.array(z.string()).optional(),excludeTagIds:z.array(z.number().int()).optional(),keepClosedMarkets:z.number().int().optional(),optimized:z.boolean().optional(),pageSize:O.default(10),presets:z.array(z.string()).optional(),recurrence:z.enum(["daily","weekly","monthly"]).optional(),searchProfiles:z.boolean().optional(),searchTags:z.boolean().optional(),sort:z.enum(ba).optional()}),ck=k(e,d,c,b,a);function dk(e,r){let{cursor:t,pageSize:o,...n}=l(r,Zf);return x(s=>{let a=U(s,o);return e.gamma.get("/public-search",{params:g({...n,limitPerType:a.pageSize,page:a.offset},R({excludeTagIds:"exclude_tag_id"}))}).andThen(f(PublicSearchResponseSchema)).map(y=>({items:Yf(y),hasMore:y.pagination?.hasMore??false,totalCount:y.pagination?.totalResults??void 0,nextCursor:y.pagination?.hasMore?B({offset:a.offset+1,pageSize:a.pageSize}):void 0}))},t??B({offset:1,pageSize:o}),{events:[],profiles:[],tags:[]})}function Yf(e){return {events:e.events??[],profiles:e.profiles??[],tags:e.tags??[]}}var rP=z.object({ascending:z.boolean().optional(),closed:z.boolean().optional(),cursor:PaginationCursorSchema.optional(),excludeEvents:z.boolean().optional(),locale:z.string().optional(),order:z.string().optional(),pageSize:O.default(20),recurrence:z.enum(["daily","weekly","monthly"]).optional(),slug:z.array(z.string()).optional()}),tP=z.object({id:z.string(),locale:z.string().optional()}),Sk=k(e,d,c,b,a);function Tk(e,r={}){let{cursor:t,pageSize:o,...n}=l(r,rP);return x(s=>{let a=U(s,o);return e.gamma.get("/series",{params:g({...n,limit:a.pageSize+1,offset:a.offset},R())}).andThen(f(ListSeriesResponseSchema)).map(y=>{let P=y.length>a.pageSize;return {items:y.slice(0,a.pageSize),hasMore:P,nextCursor:P?B({offset:a.offset+a.pageSize,pageSize:a.pageSize}):void 0}})},t)}var xk=k(e,d,c,b,a);async function Ck(e,r){let t=l(r,tP);return unwrap(e.gamma.get(`series/${t.id}`,{params:g({locale:t.locale},R())}).andThen(f(SeriesSchema)))}var Ak=k(e,d,c,b);async function Ok(e){return unwrap(e.gamma.get("/sports").andThen(f(ListSportsMetadataResponseSchema)))}var wk=k(e,d,c,b);async function Lk(e){return unwrap(e.gamma.get("/sports/market-types").andThen(f(SportsMarketTypesResponseSchema)))}async function Uk(e,r){let t=await Promise.all(r.map(o=>iP(e,o)));return pP(t)}function iP(e,r){switch(r.topic){case "market":return e.webSockets.clobMarket.subscribe(r);case "sports":return e.webSockets.sports.subscribe(r);case "comments":case "prices.crypto.binance":case "prices.crypto.chainlink":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 pP(e){let r;async function t(){r===void 0&&(r=Promise.all(e.map(n=>n.close())).then(()=>{})),await r;}let o=aP(...e);return {close:t,[Symbol.asyncIterator](){return o[Symbol.asyncIterator]()}}}var uP=z.object({ascending:z.boolean().optional(),cursor:PaginationCursorSchema.optional(),includeTemplate:z.boolean().optional(),isCarousel:z.boolean().optional(),locale:z.string().optional(),order:z.string().optional(),pageSize:O.default(20)}),mP=z.union([z.object({id:z.string(),includeTemplate:z.boolean().optional(),locale:z.string().optional()}),z.object({slug:z.string(),locale:z.string().optional()})]),lP=z.object({id:z.string(),omitEmpty:z.boolean().optional(),status:z.enum(["active","closed","all"]).optional()}),yP=z.object({slug:z.string()}),fP=z.object({id:z.string(),locale:z.string().optional(),omitEmpty:z.boolean().optional(),status:z.enum(["active","closed","all"]).optional()}),PP=z.object({locale:z.string().optional(),slug:z.string(),omitEmpty:z.boolean().optional(),status:z.enum(["active","closed","all"]).optional()}),Vk=k(e,d,c,b,a);function Zk(e,r={}){let{cursor:t,pageSize:o,...n}=l(r,uP);return x(s=>{let a=U(s,o);return e.gamma.get("/tags",{params:g({...n,limit:a.pageSize+1,offset:a.offset},R())}).andThen(f(ListTagsResponseSchema)).map(y=>{let P=y.length>a.pageSize;return {items:y.slice(0,a.pageSize),hasMore:P,nextCursor:P?B({offset:a.offset+a.pageSize,pageSize:a.pageSize}):void 0}})},t)}var Yk=k(e,d,c,b,a);async function Jk(e,r){let t=l(r,mP);return "id"in t?unwrap(e.gamma.get(`tags/${t.id}`,{params:g({includeTemplate:t.includeTemplate,locale:t.locale},R())}).andThen(f(TagSchema))):unwrap(e.gamma.get(`tags/slug/${t.slug}`,{params:g({locale:t.locale},R())}).andThen(f(TagSchema)))}var Qk=k(e,d,c,b,a);async function Xk(e,r){if("id"in r){let o=l(r,lP);return unwrap(e.gamma.get(`tags/${o.id}/related-tags`,{params:g({omitEmpty:o.omitEmpty,status:o.status},R())}).andThen(f(ListRelatedTagsResponseSchema)))}let t=l(r,yP);return unwrap(e.gamma.get(`tags/slug/${t.slug}/related-tags`).andThen(f(ListRelatedTagsResponseSchema)))}var eq=k(e,d,c,b,a);async function rq(e,r){if("id"in r){let o=l(r,fP);return unwrap(e.gamma.get(`tags/${o.id}/related-tags/tags`,{params:g({locale:o.locale,omitEmpty:o.omitEmpty,status:o.status},R())}).andThen(f(ListRelatedTagResourcesResponseSchema)))}let t=l(r,PP);return unwrap(e.gamma.get(`tags/slug/${t.slug}/related-tags/tags`,{params:g({locale:t.locale,omitEmpty:t.omitEmpty,status:t.status},R())}).andThen(f(ListRelatedTagResourcesResponseSchema)))}var EP=z.object({abbreviation:z.array(z.string()).optional(),ascending:z.boolean().optional(),cursor:PaginationCursorSchema.optional(),league:z.array(z.string()).optional(),name:z.array(z.string()).optional(),order:z.string().optional(),pageSize:O.default(20),providerId:z.array(z.number().int()).optional()}),uq=k(e,d,c,b,a);function mq(e,r={}){let{cursor:t,pageSize:o,...n}=l(r,EP);return x(s=>{let a=U(s,o);return e.gamma.get("/teams",{params:g({...n,limit:a.pageSize+1,offset:a.offset},R({providerId:"provider_id"}))}).andThen(f(ListTeamsResponseSchema)).map(y=>{let P=y.length>a.pageSize;return {items:y.slice(0,a.pageSize),hasMore:P,nextCursor:P?B({offset:a.offset+a.pageSize,pageSize:a.pageSize}):void 0}})},t)}var SP=z.object({amount:z.bigint(),metadata:K.optional(),recipientAddress:EvmAddressSchema,tokenAddress:EvmAddressSchema}),xq=k(a);async function TP(e,r){let t=l(r,SP);return async function*(){return e.account.walletType===WalletType.EOA?N(yield xP(G(e.environment.chainId,Yr(t.tokenAddress,t.recipientAddress,t.amount)))):yield*await J(e,{calls:[Yr(t.tokenAddress,t.recipientAddress,t.amount)],metadata:t.metadata??`Transfer ${t.amount} of ${t.tokenAddress} to ${t.recipientAddress}`})}.call(null)}var Cq=k(h,e,d,j,c,b,a);function bq(e,r){return TP(e,r).then(_(e.signer))}function xP(e){return {kind:"sendErc20TransferTransaction",request:e}}export{fo as $,pE as $a,Gh as $b,hx as $c,Hb as $d,ck as $e,tR as A,vR as Aa,ZE as Ab,ZS as Ac,ab as Ad,TI as Ae,Uo as B,K as Ba,YE as Bb,YS as Bc,ib as Bd,xI as Be,oR as C,AR as Ca,JE as Cb,nT as Cc,pb as Cd,CI as Ce,Jr as D,OR as Da,an as Db,sT as Dc,cb as Dd,bI as De,Do as E,Mp as Ea,QE as Eb,aT as Ec,db as Ed,II as Ee,zo as F,wR as Fa,XE as Fb,iT as Fc,ub as Fd,Bf as Fe,l as G,J as Ga,eh as Gb,pT as Gc,mb as Gd,Uf as Ge,eo as H,LR as Ha,rh as Hb,cT as Hc,lb as Hd,Df as He,HP as I,NR as Ia,th as Ib,dT as Ic,yb as Id,kI as Ie,po as J,Jp as Ja,oh as Jb,uT as Jc,fb as Jd,qI as Je,co as K,GR as Ka,nh as Kb,ET as Kc,Pb as Kd,UI as Ke,uo as L,Go as La,sh as Lb,hT as Lc,gb as Ld,DI as Le,rg as M,KR as Ma,ah as Mb,pt as Mc,Rb as Md,Gt as Me,tg as N,Xp as Na,ih as Nb,vT as Nc,Eb as Nd,HI as Ne,og as O,$R as Oa,ph as Ob,AT as Oc,$y as Od,Kt as Oe,ng as P,Ko as Pa,ch as Pb,br as Pc,hb as Pd,_I as Pe,sg as Q,VR as Qa,dh as Qb,OT as Qc,Sb as Qd,$t as Qe,ag as R,ec as Ra,uh as Rb,Mn as Rc,Zs as Rd,NI as Re,ig as S,ZR as Sa,mh as Sb,Bn as Sc,Lb as Sd,GI as Se,pg as T,YR as Ta,lh as Tb,Et as Tc,Fb as Td,KI as Te,cg as U,oE as Ua,Ch as Ub,Zu as Uc,Mb as Ud,dg as V,ic as Va,bh as Vb,ht as Vc,Bb as Vd,ug as W,nE as Wa,Ih as Wb,Yu as Wc,Ub as Wd,mg as X,pc as Xa,kh as Xb,St as Xc,Db as Xd,lg as Y,sE as Ya,qh as Yb,gx as Yc,zb as Yd,Gr as Z,aE as Za,vh as Zb,Rx as Zc,jb as Zd,yg as _,iE as _a,Nh as _b,Ex as _c,Wb as _d,ba as _e,Y as a,fg as aa,cE as ab,Kh as ac,Dx as ad,_b as ae,dk as af,Vg as b,Pg as ba,dE as bb,$h as bc,Xu as bd,Nb as be,Sk as bf,mr as c,gg as ca,uE as cb,Vh as cc,zx as cd,Tk as cf,bo as d,Rg as da,mE as db,Zh as dc,jx as dd,xk as df,Io as e,Eg as ea,lE as eb,Yh as ec,Wx as ed,ca as ee,Ck as ef,lr as f,hg as fa,yE as fb,Jh as fc,em as fd,uI as fe,Ak as ff,ko as g,Sg as ga,fE as gb,pS as gc,Hx as gd,mI as ge,Ok as gf,qo as h,Tg as ha,PE as hb,cS as hc,_x as hd,da as he,wk as hf,vo as i,xg as ia,IE as ib,dS as ic,Ir as id,lI as ie,Lk as if,Ao as j,Cg as ja,kE as jb,uS as jc,Zn as jd,yI as je,Uk as jf,Vr as k,bg as ka,DE as kb,mS as kc,Yn as kd,ua as ke,Vk as kf,Zr as l,Ig as la,zE as lb,lS as lc,Jn as ld,fI as le,Zk as lf,Zg as m,Bg as ma,jE as mb,xS as mc,kr as md,PI as me,Yk as mf,Yr as n,Ug as na,WE as nb,CS as nc,qr as nd,ma as ne,Jk as nf,Yg as o,Dg as oa,HE as ob,DS as oc,vr as od,la as oe,Qk as of,Oo as p,zg as pa,Ue as pb,fn as pc,vs as pd,vf as pe,Xk as pf,Jg as q,jg as qa,_E as qb,zS as qc,Ds as qd,ya as qe,eq as qf,Qg as r,Wg as ra,De as rb,jS as rc,QC as rd,gI as re,rq as rf,wo as s,NE as sb,WS as sc,XC as sd,RI as se,uq as sf,Xg as t,iR as ta,on as tb,HS as tc,eb as td,EI as te,mq as tf,Lo as u,N as ua,GE as ub,_S as uc,rb as ud,hI as ue,xq as uf,Fo as v,mR as va,nn as vb,NS as vc,tb as vd,SI as ve,TP as vf,eR as w,jo as wa,KE as wb,GS as wc,ly as wd,Pa as we,Cq as wf,Mo as x,kR as xa,sn as xb,KS as xc,ob as xd,ga as xe,bq as xf,rR as y,ot as ya,$E as yb,$S as yc,nb as yd,Lf as ye,Bo as z,qR as za,VE as zb,VS as zc,sb as zd,Ra as ze};//# sourceMappingURL=chunk-IBUXKB4V.js.map
2
+ //# sourceMappingURL=chunk-IBUXKB4V.js.map