@polymarket/client 0.3.0-beta.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,9 +1,9 @@
1
- import { bP as RateLimitError, bS as RequestRejectedError, cJ as TransportError, cM as UnexpectedResponseError, cB as SigningError, B as BaseClient, h as BaseSecureClient } from '../types-BXOHrumK.js';
2
- export { e as ApproveErc1155ForAllError, f as ApproveErc20Error, C as CancelAllError, j as CancelAllPerpsOrdersRequest, k as CancelMarketOrdersError, db as CancelMarketOrdersRequest, l as CancelOrderError, dc as CancelOrderRequest, m as CancelOrdersError, dd as CancelOrdersRequest, n as CancelPerpsOrderRequest, o as CancelPerpsOrdersRequest, de as CollateralReturnExecutionWorkflow, u as ComboPositionSort, df as CommentsEventType, dg as CommentsSubscription, y as CreatePerpsSessionRequest, D as CryptoPricesChainlinkTwapSubscription, dh as CryptoPricesEventType, di as CryptoPricesSubscription, dj as DeployDepositWalletError, F as DepositToPerpsError, G as DepositToPerpsRequest, I as DownloadAccountingSnapshotError, dk as DownloadAccountingSnapshotRequest, J as DropNotificationsError, dl as DropNotificationsRequest, dm as EquityPricesEventType, dn as EquityPricesSubscription, dp as Erc1155ApprovalForAllWorkflow, dq as Erc1155ApprovalForAllWorkflowRequest, dr as Erc20ApprovalWorkflow, ds as Erc20ApprovalWorkflowRequest, dt as Erc20TransferWorkflow, du as Erc20TransferWorkflowRequest, dv as EstimateMarketBuyPriceRequest, N as EstimateMarketPriceError, dw as EstimateMarketPriceRequest, dx as EstimateMarketSellPriceRequest, dy as EventForSubscriptionSpec, dz as EventForSubscriptionSpecs, O as ExecuteCollateralReturnPlanError, P as ExecuteCollateralReturnPlanRequest, dA as FetchBalanceAllowanceError, dB as FetchBalanceAllowanceRequest, dC as FetchBuilderFeeRatesError, dD as FetchBuilderFeeRatesRequest, Q as FetchClosedOnlyModeError, R as FetchCommentsByIdError, dE as FetchCommentsByIdRequest, V as FetchEventError, W as FetchEventLiveVolumeError, dF as FetchEventLiveVolumeRequest, dG as FetchEventRequest, X as FetchEventTagsError, dH as FetchEventTagsRequest, dI as FetchExecuteParamsError, dJ as FetchExecuteParamsRequest, dK as FetchGaslessTransactionRequest, Y as FetchLastTradePriceError, dL as FetchLastTradePriceRequest, Z as FetchLastTradePricesError, dM as FetchLastTradePricesRequest, _ as FetchMarketError, dN as FetchMarketInfoError, dO as FetchMarketInfoRequest, dP as FetchMarketRequest, $ as FetchMarketTagsError, dQ as FetchMarketTagsRequest, a0 as FetchMidpointError, dR as FetchMidpointRequest, a1 as FetchMidpointsError, dS as FetchMidpointsRequest, dT as FetchNegRiskError, dU as FetchNegRiskRequest, a2 as FetchNotificationsError, a3 as FetchOrderBookError, dV as FetchOrderBookRequest, a4 as FetchOrderBooksError, dW as FetchOrderBooksRequest, a5 as FetchOrderError, dX as FetchOrderRequest, a6 as FetchOrderScoringError, dY as FetchOrderScoringRequest, a7 as FetchOrdersScoringError, dZ as FetchOrdersScoringRequest, a8 as FetchPerpsAccountConfigRequest, a9 as FetchPerpsBookError, aa as FetchPerpsBookRequest, ab as FetchPerpsFeesError, ac as FetchPerpsInstrumentsError, ad as FetchPerpsInstrumentsRequest, ae as FetchPerpsOpenOrdersRequest, af as FetchPerpsOrdersRequest, ag as FetchPerpsTickerError, ah as FetchPerpsTickerRequest, ai as FetchPerpsTickersError, aj as FetchPerpsTickersRequest, ak as FetchPortfolioValueError, d_ as FetchPortfolioValueRequest, al as FetchPriceError, am as FetchPriceHistoryError, d$ as FetchPriceHistoryRequest, e0 as FetchPriceRequest, an as FetchPricesError, e1 as FetchPricesRequest, ao as FetchPublicProfileError, e2 as FetchPublicProfileRequest, ap as FetchRelatedTagResourcesError, e3 as FetchRelatedTagResourcesRequest, aq as FetchRelatedTagsError, e4 as FetchRelatedTagsRequest, ar as FetchRewardPercentagesError, as as FetchSeriesError, e5 as FetchSeriesRequest, at as FetchSpreadError, e6 as FetchSpreadRequest, au as FetchSpreadsError, e7 as FetchSpreadsRequest, av as FetchTagError, e8 as FetchTagRequest, e9 as FetchTickSizeError, ea as FetchTickSizeRequest, aw as FetchTotalEarningsForUserForDayError, eb as FetchTotalEarningsForUserForDayRequest, ax as FetchTradedMarketCountError, ec as FetchTradedMarketCountRequest, ed as GaslessTransactionMetadataSchema, ee as GaslessWorkflow, ef as GaslessWorkflowRequest, eg as IsWalletDeployedError, eh as IsWalletDeployedRequest, az as ListAccountTradesError, ei as ListAccountTradesRequest, aA as ListActivityError, ej as ListActivityRequest, aB as ListBuilderLeaderboardError, ek as ListBuilderLeaderboardRequest, aC as ListBuilderTradesError, el as ListBuilderTradesRequest, aD as ListBuilderVolumeError, em as ListBuilderVolumeRequest, aE as ListClosedPositionsError, en as ListClosedPositionsRequest, aF as ListComboActivityError, eo as ListComboActivityRequest, aG as ListComboMarketsError, ep as ListComboMarketsRequest, aH as ListComboPositionsError, eq as ListComboPositionsRequest, aI as ListCommentsByUserAddressError, er as ListCommentsByUserAddressRequest, aJ as ListCommentsError, es as ListCommentsRequest, aK as ListCurrentRewardsError, et as ListCurrentRewardsRequest, aL as ListEventsError, eu as ListEventsRequest, ev as ListMarketClarificationsError, ew as ListMarketClarificationsRequest, aM as ListMarketHoldersError, ex as ListMarketHoldersRequest, aN as ListMarketPositionsError, ey as ListMarketPositionsRequest, aO as ListMarketRewardsError, ez as ListMarketRewardsRequest, aP as ListMarketsError, eA as ListMarketsRequest, aQ as ListOpenInterestError, eB as ListOpenInterestRequest, aR as ListOpenOrdersError, eC as ListOpenOrdersRequest, aS as ListPerpsCandlesError, aT as ListPerpsCandlesRequest, aU as ListPerpsDepositsRequest, aV as ListPerpsEquityHistoryRequest, aW as ListPerpsFillsRequest, aX as ListPerpsFundingHistoryError, aY as ListPerpsFundingHistoryRequest, aZ as ListPerpsFundingPaymentsRequest, a_ as ListPerpsNotificationsRequest, a$ as ListPerpsPnlHistoryRequest, b0 as ListPerpsTradesError, b1 as ListPerpsTradesRequest, b2 as ListPerpsWithdrawalsRequest, b3 as ListPositionsError, eD as ListPositionsRequest, b4 as ListSeriesError, eE as ListSeriesRequest, b5 as ListTagsError, eF as ListTagsRequest, b6 as ListTeamsError, eG as ListTeamsRequest, b7 as ListTraderLeaderboardError, eH as ListTraderLeaderboardRequest, b8 as ListTradesError, eI as ListTradesRequest, b9 as ListUserEarningsAndMarketsConfigError, eJ as ListUserEarningsAndMarketsConfigRequest, ba as ListUserEarningsForDayError, eK as ListUserEarningsForDayRequest, bb as MarkPerpsNotificationsReadRequest, eL as MarketEventType, eM as MarketSubscription, eN as MergeComboPositionError, eO as MergeMarketPositionError, bc as MergePositionsError, eP as MergePositionsWorkflow, eQ as MergePositionsWorkflowRequest, bd as OpenPerpsSessionError, be as OpenPerpsSessionRequest, bf as OpenRfqSessionError, eR as OrderDraft, eS as OrderPostingWorkflow, eT as OrderWorkflow, eU as OrderWorkflowRequest, eV as PerpsBboSubscription, bk as PerpsBookDepth, eW as PerpsBookSubscription, eX as PerpsCandlesSubscription, eY as PerpsDepositWorkflow, eZ as PerpsDepositWorkflowRequest, e_ as PerpsMarketDataEventType, e$ as PerpsMarketDataSubscription, bm as PerpsOrderRequest, bn as PerpsPlaceFokOrderRequest, bo as PerpsPlaceGtcOrderRequest, bp as PerpsPlaceIocOrderRequest, bq as PerpsPlacedTpSlOrder, br as PerpsPlacedTpSlOrders, bs as PerpsPositionTpSlTrigger, bt as PerpsSession, bu as PerpsSessionAccountError, bv as PerpsSessionLifecycleError, bw as PerpsSessionTradingError, f0 as PerpsStatisticsSubscription, f1 as PerpsStreamingCandleInterval, f2 as PerpsTickersSubscription, bx as PerpsTpSlTrigger, f3 as PerpsTradesSubscription, by as PlacePerpsOrderRequest, bz as PlacePerpsOrderResult, bA as PlacePerpsOrderWithTpSlRequest, bB as PlacePerpsOrderWithTpSlResult, bC as PlacePerpsPositionTpSlRequest, bD as PlacePerpsPositionTpSlResult, bE as PlanCollateralReturnError, bF as PostOrderError, bG as PostOrdersError, f4 as PostOrdersRequest, bH as PostPerpsOrdersRequest, f5 as PrepareCollateralReturnExecutionError, f6 as PrepareErc1155ApprovalForAllError, f7 as PrepareErc1155ApprovalForAllRequest, f8 as PrepareErc20ApprovalError, f9 as PrepareErc20ApprovalRequest, fa as PrepareErc20TransferError, fb as PrepareErc20TransferRequest, fc as PrepareGaslessTransactionError, fd as PrepareGaslessTransactionRequest, fe as PrepareLimitOrderRequest, ff as PrepareMarketBuyOrderRequest, fg as PrepareMarketOrderRequest, fh as PrepareMarketSellOrderRequest, fi as PrepareMergeComboPositionError, fj as PrepareMergeComboPositionRequest, fk as PrepareMergeMarketPositionError, fl as PrepareMergeMarketPositionRequest, fm as PrepareMergePositionsError, fn as PrepareMergePositionsRequest, fo as PreparePerpsDepositError, fp as PrepareRedeemComboPositionError, fq as PrepareRedeemComboPositionRequest, fr as PrepareRedeemMarketPositionsByConditionIdRequest, fs as PrepareRedeemMarketPositionsByMarketIdRequest, ft as PrepareRedeemMarketPositionsError, fu as PrepareRedeemMarketPositionsRequest, fv as PrepareRedeemPositionsError, fw as PrepareRedeemPositionsRequest, fx as PrepareSplitComboPositionError, fy as PrepareSplitComboPositionRequest, fz as PrepareSplitMarketPositionError, fA as PrepareSplitMarketPositionRequest, fB as PrepareSplitPositionError, fC as PrepareSplitPositionRequest, fD as PrepareTradingApprovalsError, fE as PublicRealtimeEvent, fF as PublicRealtimeTopic, fG as PublicSubscriptionSpec, bR as RedeemPositionsError, fH as RedeemPositionsWorkflow, fI as RedeemPositionsWorkflowRequest, fJ as ResolveConditionByTokenError, fK as ResolveConditionByTokenRequest, bV as ResumePerpsSessionRequest, bW as RevokePerpsCredentialsError, bX as RevokePerpsCredentialsRequest, bY as RfqCancelQuoteAck, bZ as RfqCancelQuoteError, b_ as RfqCancelQuoteRejectedError, b$ as RfqCancelQuoteRejectedErrorOptions, c0 as RfqConfirmationAck, c1 as RfqConfirmationError, c2 as RfqConfirmationRejectedError, fL as RfqConfirmationRejectedErrorOptions, c3 as RfqConfirmationRequestEvent, c4 as RfqEvent, fM as RfqExecutionUpdateEvent, c5 as RfqQuoteError, c6 as RfqQuoteReference, c7 as RfqQuoteRejectedError, c8 as RfqQuoteRejectedErrorOptions, c9 as RfqQuoteRequestEvent, ca as RfqQuoteResponse, cb as RfqQuoteSource, cc as RfqSession, cd as RfqTradeEvent, ce as SearchError, fN as SearchRequest, fO as SearchResults, cf as SearchSort, fP as SecureRealtimeEvent, fQ as SecureRealtimeTopic, fR as SecureSubscriptionSpec, cz as SetupTradingApprovalsError, fS as SignedOrder, fT as SplitComboPositionError, fU as SplitMarketPositionError, cC as SplitPositionError, fV as SplitPositionWorkflow, fW as SplitPositionWorkflowRequest, fX as SportsEventType, fY as SportsSubscription, cD as SubscribeError, fZ as SubscriptionHandle, f_ as TradingApprovalsWorkflow, f$ as TradingApprovalsWorkflowRequest, cI as TransferErc20Error, g0 as UpdateBalanceAllowanceError, g1 as UpdateBalanceAllowanceRequest, cN as UpdatePerpsLeverageError, cO as UpdatePerpsLeverageRequest, g2 as UserEventType, g3 as UserSubscription, g4 as WaitForGaslessTransactionError, cP as WaitForOrderFillSettlementError, g5 as WaitForOrderFillSettlementRequest, cV as WithdrawFromPerpsError, cW as WithdrawFromPerpsRequest, g6 as approveErc1155ForAll, g7 as approveErc20, g8 as cancelAll, g9 as cancelMarketOrders, ga as cancelOrder, gb as cancelOrders, gc as deployDepositWallet, gd as depositToPerps, ge as downloadAccountingSnapshot, gf as dropNotifications, gg as estimateMarketPrice, gh as executeCollateralReturnPlan, gi as fetchBalanceAllowance, gj as fetchBuilderFeeRates, gk as fetchBuilderVolume, gl as fetchClosedOnlyMode, gm as fetchCommentsById, gn as fetchEvent, go as fetchEventLiveVolume, gp as fetchEventTags, gq as fetchExecuteParams, gr as fetchLastTradePrice, gs as fetchLastTradePrices, gt as fetchMarket, gu as fetchMarketInfo, gv as fetchMarketTags, gw as fetchMidpoint, gx as fetchMidpoints, gy as fetchNegRisk, gz as fetchNotifications, gA as fetchOrder, gB as fetchOrderBook, gC as fetchOrderBooks, gD as fetchOrderScoring, gE as fetchOrdersScoring, gF as fetchPerpsBook, gG as fetchPerpsFees, gH as fetchPerpsInstruments, gI as fetchPerpsTicker, gJ as fetchPerpsTickers, gK as fetchPortfolioValue, gL as fetchPrice, gM as fetchPriceHistory, gN as fetchPrices, gO as fetchPublicProfile, gP as fetchRelatedTagResources, gQ as fetchRelatedTags, gR as fetchRewardPercentages, gS as fetchSeries, gT as fetchSpread, gU as fetchSpreads, gV as fetchTag, gW as fetchTickSize, gX as fetchTotalEarningsForUserForDay, gY as fetchTradedMarketCount, gZ as fetchTransaction, g_ as isWalletDeployed, g$ as listAccountTrades, h0 as listActivity, h1 as listBuilderLeaderboard, h2 as listBuilderTrades, h3 as listClosedPositions, h4 as listComboActivity, h5 as listComboMarkets, h6 as listComboPositions, h7 as listComments, h8 as listCommentsByUserAddress, h9 as listCurrentRewards, ha as listEvents, hb as listMarketClarifications, hc as listMarketHolders, hd as listMarketPositions, he as listMarketRewards, hf as listMarkets, hg as listOpenInterest, hh as listOpenOrders, hi as listPerpsCandles, hj as listPerpsFundingHistory, hk as listPerpsTrades, hl as listPositions, hm as listSeries, hn as listTags, ho as listTeams, hp as listTraderLeaderboard, hq as listTrades, hr as listUserEarningsAndMarketsConfig, hs as listUserEarningsForDay, ht as mergeComboPosition, hu as mergeMarketPosition, hv as mergePositions, hw as openPerpsSession, hx as openRfqSession, hy as planCollateralReturn, hz as postOrder, hA as postOrders, hB as prepareCollateralReturnExecution, hC as prepareErc1155ApprovalForAll, hD as prepareErc20Approval, hE as prepareErc20Transfer, hF as prepareGaslessTransaction, hG as prepareMergeComboPosition, hH as prepareMergeMarketPosition, hI as prepareMergePositions, hJ as preparePerpsDeposit, hK as prepareRedeemComboPosition, hL as prepareRedeemMarketPositions, hM as prepareRedeemPositions, hN as prepareSplitComboPosition, hO as prepareSplitMarketPosition, hP as prepareSplitPosition, hQ as prepareTradingApprovals, hR as redeemPositions, hS as resolveConditionByToken, hT as revokePerpsCredentials, hU as search, hV as setupTradingApprovals, hW as splitComboPosition, hX as splitMarketPosition, hY as splitPosition, hZ as subscribe, h_ as transferErc20, h$ as updateBalanceAllowance, i0 as waitForOrderFillSettlement, i1 as withdrawFromPerps } from '../types-BXOHrumK.js';
1
+ import { bP as RateLimitError, bS as RequestRejectedError, cJ as TransportError, cM as UnexpectedResponseError, cB as SigningError, B as BaseClient, h as BaseSecureClient } from '../types-BzzqPJTs.js';
2
+ export { e as ApproveErc1155ForAllError, f as ApproveErc20Error, C as CancelAllError, j as CancelAllPerpsOrdersRequest, k as CancelMarketOrdersError, db as CancelMarketOrdersRequest, l as CancelOrderError, dc as CancelOrderRequest, m as CancelOrdersError, dd as CancelOrdersRequest, n as CancelPerpsOrderRequest, o as CancelPerpsOrdersRequest, de as CollateralReturnExecutionWorkflow, u as ComboPositionSort, df as CommentsEventType, dg as CommentsSubscription, y as CreatePerpsSessionRequest, D as CryptoPricesChainlinkTwapSubscription, dh as CryptoPricesEventType, di as CryptoPricesSubscription, dj as DeployDepositWalletError, F as DepositToPerpsError, G as DepositToPerpsRequest, I as DownloadAccountingSnapshotError, dk as DownloadAccountingSnapshotRequest, J as DropNotificationsError, dl as DropNotificationsRequest, dm as EquityPricesEventType, dn as EquityPricesSubscription, dp as Erc1155ApprovalForAllWorkflow, dq as Erc1155ApprovalForAllWorkflowRequest, dr as Erc20ApprovalWorkflow, ds as Erc20ApprovalWorkflowRequest, dt as Erc20TransferWorkflow, du as Erc20TransferWorkflowRequest, dv as EstimateMarketBuyPriceRequest, N as EstimateMarketPriceError, dw as EstimateMarketPriceRequest, dx as EstimateMarketSellPriceRequest, dy as EventForSubscriptionSpec, dz as EventForSubscriptionSpecs, O as ExecuteCollateralReturnPlanError, P as ExecuteCollateralReturnPlanRequest, dA as FetchBalanceAllowanceError, dB as FetchBalanceAllowanceRequest, dC as FetchBuilderFeeRatesError, dD as FetchBuilderFeeRatesRequest, Q as FetchClosedOnlyModeError, R as FetchCommentsByIdError, dE as FetchCommentsByIdRequest, V as FetchEventError, W as FetchEventLiveVolumeError, dF as FetchEventLiveVolumeRequest, dG as FetchEventRequest, X as FetchEventTagsError, dH as FetchEventTagsRequest, dI as FetchExecuteParamsError, dJ as FetchExecuteParamsRequest, dK as FetchGaslessTransactionRequest, Y as FetchLastTradePriceError, dL as FetchLastTradePriceRequest, Z as FetchLastTradePricesError, dM as FetchLastTradePricesRequest, _ as FetchMarketError, dN as FetchMarketInfoError, dO as FetchMarketInfoRequest, dP as FetchMarketRequest, $ as FetchMarketTagsError, dQ as FetchMarketTagsRequest, a0 as FetchMidpointError, dR as FetchMidpointRequest, a1 as FetchMidpointsError, dS as FetchMidpointsRequest, dT as FetchNegRiskError, dU as FetchNegRiskRequest, a2 as FetchNotificationsError, a3 as FetchOrderBookError, dV as FetchOrderBookRequest, a4 as FetchOrderBooksError, dW as FetchOrderBooksRequest, a5 as FetchOrderError, dX as FetchOrderRequest, a6 as FetchOrderScoringError, dY as FetchOrderScoringRequest, a7 as FetchOrdersScoringError, dZ as FetchOrdersScoringRequest, a8 as FetchPerpsAccountConfigRequest, a9 as FetchPerpsBookError, aa as FetchPerpsBookRequest, ab as FetchPerpsFeesError, ac as FetchPerpsInstrumentsError, ad as FetchPerpsInstrumentsRequest, ae as FetchPerpsOpenOrdersRequest, af as FetchPerpsOrdersRequest, ag as FetchPerpsTickerError, ah as FetchPerpsTickerRequest, ai as FetchPerpsTickersError, aj as FetchPerpsTickersRequest, ak as FetchPortfolioValueError, d_ as FetchPortfolioValueRequest, al as FetchPriceError, am as FetchPriceHistoryError, d$ as FetchPriceHistoryRequest, e0 as FetchPriceRequest, an as FetchPricesError, e1 as FetchPricesRequest, ao as FetchPublicProfileError, e2 as FetchPublicProfileRequest, ap as FetchRelatedTagResourcesError, e3 as FetchRelatedTagResourcesRequest, aq as FetchRelatedTagsError, e4 as FetchRelatedTagsRequest, ar as FetchRewardPercentagesError, as as FetchSeriesError, e5 as FetchSeriesRequest, at as FetchSpreadError, e6 as FetchSpreadRequest, au as FetchSpreadsError, e7 as FetchSpreadsRequest, av as FetchTagError, e8 as FetchTagRequest, e9 as FetchTickSizeError, ea as FetchTickSizeRequest, aw as FetchTotalEarningsForUserForDayError, eb as FetchTotalEarningsForUserForDayRequest, ax as FetchTradedMarketCountError, ec as FetchTradedMarketCountRequest, ed as GaslessTransactionMetadataSchema, ee as GaslessWorkflow, ef as GaslessWorkflowRequest, eg as IsWalletDeployedError, eh as IsWalletDeployedRequest, az as ListAccountTradesError, ei as ListAccountTradesRequest, aA as ListActivityError, ej as ListActivityRequest, aB as ListBuilderLeaderboardError, ek as ListBuilderLeaderboardRequest, aC as ListBuilderTradesError, el as ListBuilderTradesRequest, aD as ListBuilderVolumeError, em as ListBuilderVolumeRequest, aE as ListClosedPositionsError, en as ListClosedPositionsRequest, aF as ListComboActivityError, eo as ListComboActivityRequest, aG as ListComboMarketsError, ep as ListComboMarketsRequest, aH as ListComboPositionsError, eq as ListComboPositionsRequest, aI as ListCommentsByUserAddressError, er as ListCommentsByUserAddressRequest, aJ as ListCommentsError, es as ListCommentsRequest, aK as ListCurrentRewardsError, et as ListCurrentRewardsRequest, aL as ListEventsError, eu as ListEventsRequest, ev as ListMarketClarificationsError, ew as ListMarketClarificationsRequest, aM as ListMarketHoldersError, ex as ListMarketHoldersRequest, aN as ListMarketPositionsError, ey as ListMarketPositionsRequest, aO as ListMarketRewardsError, ez as ListMarketRewardsRequest, aP as ListMarketsError, eA as ListMarketsRequest, aQ as ListOpenInterestError, eB as ListOpenInterestRequest, aR as ListOpenOrdersError, eC as ListOpenOrdersRequest, aS as ListPerpsCandlesError, aT as ListPerpsCandlesRequest, aU as ListPerpsDepositsRequest, aV as ListPerpsEquityHistoryRequest, aW as ListPerpsFillsRequest, aX as ListPerpsFundingHistoryError, aY as ListPerpsFundingHistoryRequest, aZ as ListPerpsFundingPaymentsRequest, a_ as ListPerpsNotificationsRequest, a$ as ListPerpsPnlHistoryRequest, b0 as ListPerpsTradesError, b1 as ListPerpsTradesRequest, b2 as ListPerpsWithdrawalsRequest, b3 as ListPositionsError, eD as ListPositionsRequest, b4 as ListSeriesError, eE as ListSeriesRequest, b5 as ListTagsError, eF as ListTagsRequest, b6 as ListTeamsError, eG as ListTeamsRequest, b7 as ListTraderLeaderboardError, eH as ListTraderLeaderboardRequest, b8 as ListTradesError, eI as ListTradesRequest, b9 as ListUserEarningsAndMarketsConfigError, eJ as ListUserEarningsAndMarketsConfigRequest, ba as ListUserEarningsForDayError, eK as ListUserEarningsForDayRequest, bb as MarkPerpsNotificationsReadRequest, eL as MarketEventType, eM as MarketSubscription, eN as MergeComboPositionError, eO as MergeMarketPositionError, bc as MergePositionsError, eP as MergePositionsWorkflow, eQ as MergePositionsWorkflowRequest, bd as OpenPerpsSessionError, be as OpenPerpsSessionRequest, bf as OpenRfqSessionError, eR as OrderDraft, eS as OrderPostingWorkflow, eT as OrderWorkflow, eU as OrderWorkflowRequest, eV as PerpsBboSubscription, bk as PerpsBookDepth, eW as PerpsBookSubscription, eX as PerpsCandlesSubscription, eY as PerpsDepositWorkflow, eZ as PerpsDepositWorkflowRequest, e_ as PerpsMarketDataEventType, e$ as PerpsMarketDataSubscription, bm as PerpsOrderRequest, bn as PerpsPlaceFokOrderRequest, bo as PerpsPlaceGtcOrderRequest, bp as PerpsPlaceIocOrderRequest, bq as PerpsPlacedTpSlOrder, br as PerpsPlacedTpSlOrders, bs as PerpsPositionTpSlTrigger, bt as PerpsSession, bu as PerpsSessionAccountError, bv as PerpsSessionLifecycleError, bw as PerpsSessionTradingError, f0 as PerpsStatisticsSubscription, f1 as PerpsStreamingCandleInterval, f2 as PerpsTickersSubscription, bx as PerpsTpSlTrigger, f3 as PerpsTradesSubscription, by as PlacePerpsOrderRequest, bz as PlacePerpsOrderResult, bA as PlacePerpsOrderWithTpSlRequest, bB as PlacePerpsOrderWithTpSlResult, bC as PlacePerpsPositionTpSlRequest, bD as PlacePerpsPositionTpSlResult, bE as PlanCollateralReturnError, bF as PostOrderError, bG as PostOrdersError, f4 as PostOrdersRequest, bH as PostPerpsOrdersRequest, f5 as PrepareCollateralReturnExecutionError, f6 as PrepareErc1155ApprovalForAllError, f7 as PrepareErc1155ApprovalForAllRequest, f8 as PrepareErc20ApprovalError, f9 as PrepareErc20ApprovalRequest, fa as PrepareErc20TransferError, fb as PrepareErc20TransferRequest, fc as PrepareGaslessTransactionError, fd as PrepareGaslessTransactionRequest, fe as PrepareLimitOrderRequest, ff as PrepareMarketBuyOrderRequest, fg as PrepareMarketOrderRequest, fh as PrepareMarketSellOrderRequest, fi as PrepareMergeComboPositionError, fj as PrepareMergeComboPositionRequest, fk as PrepareMergeMarketPositionError, fl as PrepareMergeMarketPositionRequest, fm as PrepareMergePositionsError, fn as PrepareMergePositionsRequest, fo as PreparePerpsDepositError, fp as PrepareRedeemComboPositionError, fq as PrepareRedeemComboPositionRequest, fr as PrepareRedeemMarketPositionsByConditionIdRequest, fs as PrepareRedeemMarketPositionsByMarketIdRequest, ft as PrepareRedeemMarketPositionsError, fu as PrepareRedeemMarketPositionsRequest, fv as PrepareRedeemPositionsError, fw as PrepareRedeemPositionsRequest, fx as PrepareSplitComboPositionError, fy as PrepareSplitComboPositionRequest, fz as PrepareSplitMarketPositionError, fA as PrepareSplitMarketPositionRequest, fB as PrepareSplitPositionError, fC as PrepareSplitPositionRequest, fD as PrepareTradingApprovalsError, fE as PublicRealtimeEvent, fF as PublicRealtimeTopic, fG as PublicSubscriptionSpec, bR as RedeemPositionsError, fH as RedeemPositionsWorkflow, fI as RedeemPositionsWorkflowRequest, fJ as ResolveConditionByTokenError, fK as ResolveConditionByTokenRequest, bV as ResumePerpsSessionRequest, bW as RevokePerpsCredentialsError, bX as RevokePerpsCredentialsRequest, bY as RfqCancelQuoteAck, bZ as RfqCancelQuoteError, b_ as RfqCancelQuoteRejectedError, b$ as RfqCancelQuoteRejectedErrorOptions, c0 as RfqConfirmationAck, c1 as RfqConfirmationError, c2 as RfqConfirmationRejectedError, fL as RfqConfirmationRejectedErrorOptions, c3 as RfqConfirmationRequestEvent, c4 as RfqEvent, fM as RfqExecutionUpdateEvent, c5 as RfqQuoteError, c6 as RfqQuoteReference, c7 as RfqQuoteRejectedError, c8 as RfqQuoteRejectedErrorOptions, c9 as RfqQuoteRequestEvent, ca as RfqQuoteResponse, cb as RfqQuoteSource, cc as RfqSession, cd as RfqTradeEvent, ce as SearchError, fN as SearchRequest, fO as SearchResults, cf as SearchSort, fP as SecureRealtimeEvent, fQ as SecureRealtimeTopic, fR as SecureSubscriptionSpec, cz as SetupTradingApprovalsError, fS as SignedOrder, fT as SplitComboPositionError, fU as SplitMarketPositionError, cC as SplitPositionError, fV as SplitPositionWorkflow, fW as SplitPositionWorkflowRequest, fX as SportsEventType, fY as SportsSubscription, cD as SubscribeError, fZ as SubscriptionHandle, f_ as TradingApprovalsWorkflow, f$ as TradingApprovalsWorkflowRequest, cI as TransferErc20Error, g0 as UpdateBalanceAllowanceError, g1 as UpdateBalanceAllowanceRequest, cN as UpdatePerpsLeverageError, cO as UpdatePerpsLeverageRequest, g2 as UserEventType, g3 as UserSubscription, g4 as WaitForGaslessTransactionError, cP as WaitForOrderFillSettlementError, g5 as WaitForOrderFillSettlementRequest, cV as WithdrawFromPerpsError, cW as WithdrawFromPerpsRequest, g6 as approveErc1155ForAll, g7 as approveErc20, g8 as cancelAll, g9 as cancelMarketOrders, ga as cancelOrder, gb as cancelOrders, gc as deployDepositWallet, gd as depositToPerps, ge as downloadAccountingSnapshot, gf as dropNotifications, gg as estimateMarketPrice, gh as executeCollateralReturnPlan, gi as fetchBalanceAllowance, gj as fetchBuilderFeeRates, gk as fetchBuilderVolume, gl as fetchClosedOnlyMode, gm as fetchCommentsById, gn as fetchEvent, go as fetchEventLiveVolume, gp as fetchEventTags, gq as fetchExecuteParams, gr as fetchLastTradePrice, gs as fetchLastTradePrices, gt as fetchMarket, gu as fetchMarketInfo, gv as fetchMarketTags, gw as fetchMidpoint, gx as fetchMidpoints, gy as fetchNegRisk, gz as fetchNotifications, gA as fetchOrder, gB as fetchOrderBook, gC as fetchOrderBooks, gD as fetchOrderScoring, gE as fetchOrdersScoring, gF as fetchPerpsBook, gG as fetchPerpsFees, gH as fetchPerpsInstruments, gI as fetchPerpsTicker, gJ as fetchPerpsTickers, gK as fetchPortfolioValue, gL as fetchPrice, gM as fetchPriceHistory, gN as fetchPrices, gO as fetchPublicProfile, gP as fetchRelatedTagResources, gQ as fetchRelatedTags, gR as fetchRewardPercentages, gS as fetchSeries, gT as fetchSpread, gU as fetchSpreads, gV as fetchTag, gW as fetchTickSize, gX as fetchTotalEarningsForUserForDay, gY as fetchTradedMarketCount, gZ as fetchTransaction, g_ as isWalletDeployed, g$ as listAccountTrades, h0 as listActivity, h1 as listBuilderLeaderboard, h2 as listBuilderTrades, h3 as listClosedPositions, h4 as listComboActivity, h5 as listComboMarkets, h6 as listComboPositions, h7 as listComments, h8 as listCommentsByUserAddress, h9 as listCurrentRewards, ha as listEvents, hb as listMarketClarifications, hc as listMarketHolders, hd as listMarketPositions, he as listMarketRewards, hf as listMarkets, hg as listOpenInterest, hh as listOpenOrders, hi as listPerpsCandles, hj as listPerpsFundingHistory, hk as listPerpsTrades, hl as listPositions, hm as listSeries, hn as listTags, ho as listTeams, hp as listTraderLeaderboard, hq as listTrades, hr as listUserEarningsAndMarketsConfig, hs as listUserEarningsForDay, ht as mergeComboPosition, hu as mergeMarketPosition, hv as mergePositions, hw as openPerpsSession, hx as openRfqSession, hy as planCollateralReturn, hz as postOrder, hA as postOrders, hB as prepareCollateralReturnExecution, hC as prepareErc1155ApprovalForAll, hD as prepareErc20Approval, hE as prepareErc20Transfer, hF as prepareGaslessTransaction, hG as prepareMergeComboPosition, hH as prepareMergeMarketPosition, hI as prepareMergePositions, hJ as preparePerpsDeposit, hK as prepareRedeemComboPosition, hL as prepareRedeemMarketPositions, hM as prepareRedeemPositions, hN as prepareSplitComboPosition, hO as prepareSplitMarketPosition, hP as prepareSplitPosition, hQ as prepareTradingApprovals, hR as redeemPositions, hS as resolveConditionByToken, hT as revokePerpsCredentials, hU as search, hV as setupTradingApprovals, hW as splitComboPosition, hX as splitMarketPosition, hY as splitPosition, hZ as subscribe, h_ as transferErc20, h$ as updateBalanceAllowance, i0 as waitForOrderFillSettlement, i1 as withdrawFromPerps } from '../types-BzzqPJTs.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-BrD6Dal5.js';
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-x4Y_Y4yb.js';
7
7
  export { CollateralReturnKnownOperationKind, CollateralReturnOperation, CollateralReturnOperationKind, CollateralReturnPlanResponse, CollateralReturnPositionAmount, CollateralReturnPositionSummary, CollateralReturnRouterCall, RfqConfirmationDecision, RfqConfirmationRequest, RfqDirection, RfqErrorCode, RfqExecutionStatus, RfqExecutionUpdate, RfqId, RfqKnownErrorCode, RfqQuoteId, RfqQuoteRequest, RfqRequestedSize, RfqRequestedSizeUnit, RfqRequestorPublicId, RfqSide, RfqTrade } from '@polymarket/bindings/combos';
8
8
  export { ComboActivityType, ComboPositionOutcome, ComboPositionStatus } from '@polymarket/bindings/data';
9
9
  export { CommentsEvent, CryptoPricesBinanceEvent, CryptoPricesChainlinkEvent, CryptoPricesChainlinkTwapEvent, CryptoPricesChainlinkTwapSixtyEvent, CryptoPricesChainlinkTwapThirtyEvent, CryptoPricesChainlinkTwapWindowSeconds, CryptoPricesEvent, CustomMarketEvent, EquityPricesEvent, MarketEvent, PerpsBboEvent, PerpsBookEvent, PerpsCandleEvent, PerpsMarketDataEvent, PerpsSessionEvent, PerpsStatisticEvent, PerpsTickerEvent, PerpsTradeEvent, SportsEvent, StandardMarketEvent, UserEvent } from '@polymarket/bindings/subscriptions';
@@ -1,2 +1,2 @@
1
- export{Va as ApproveErc1155ForAllError,Ra as ApproveErc20Error,Uc as CancelAllError,Wc as CancelMarketOrdersError,Qc as CancelOrderError,Sc as CancelOrdersError,fc as CollateralReturnKnownOperationKind,sa as ComboActivityType,se as ComboPositionOutcome,fe as ComboPositionSort,te as ComboPositionStatus,$a as CreateApiKeyError,jb as CreateBuilderApiKeyError,ud as CreateLimitOrderError,qd as CreateMarketOrderError,db as CreateOrDeriveApiKeyError,hb as DeleteApiKeyError,Ca as DeployDepositWalletError,_d as DepositToPerpsError,bb as DeriveApiKeyError,qe as DownloadAccountingSnapshotError,W as DropNotificationsError,Yc as EstimateMarketPriceError,dc as ExecuteCollateralReturnPlanError,fb as FetchApiKeysError,Y as FetchBalanceAllowanceError,lb as FetchBuilderApiKeysError,Db as FetchBuilderFeeRatesError,M as FetchClosedOnlyModeError,ic as FetchCommentsByIdError,oc as FetchEventError,sc as FetchEventLiveVolumeError,qc as FetchEventTagsError,xa as FetchExecuteParamsError,Rb as FetchLastTradePriceError,Tb as FetchLastTradePricesError,Gc as FetchMarketError,Bb as FetchMarketInfoError,Ic as FetchMarketTagsError,rb as FetchMidpointError,tb as FetchMidpointsError,xb as FetchNegRiskError,U as FetchNotificationsError,Jb as FetchOrderBookError,Lb as FetchOrderBooksError,Q as FetchOrderError,aa as FetchOrderScoringError,ca as FetchOrdersScoringError,Nd as FetchPerpsBookError,Vd as FetchPerpsFeesError,Hd as FetchPerpsInstrumentsError,Jd as FetchPerpsTickerError,Ld as FetchPerpsTickersError,me as FetchPortfolioValueError,Fb as FetchPriceError,Vb as FetchPriceHistoryError,Hb as FetchPricesError,_e as FetchPublicProfileError,If as FetchRelatedTagResourcesError,Gf as FetchRelatedTagsError,ka as FetchRewardPercentagesError,tf as FetchSeriesError,xf as FetchSportsMarketTypesError,Nb as FetchSpreadError,Pb as FetchSpreadsError,Ef as FetchTagError,vb as FetchTickSizeError,ga as FetchTotalEarningsForUserForDayError,oe as FetchTradedMarketCountError,Oa as GaslessTransactionHandle,Ba as GaslessTransactionMetadataSchema,za as IsWalletDeployedError,S as ListAccountTradesError,oa as ListActivityError,uc as ListBuilderLeaderboardError,pb as ListBuilderTradesError,wc as ListBuilderVolumeError,ie as ListClosedPositionsError,qa as ListComboActivityError,Ec as ListComboMarketsError,ke as ListComboPositionsError,kc as ListCommentsByUserAddressError,gc as ListCommentsError,Xb as ListCurrentRewardsError,mc as ListEventsError,Ac as ListMarketClarificationsError,Kc as ListMarketHoldersError,Oc as ListMarketPositionsError,Zb as ListMarketRewardsError,Cc as ListMarketsError,Mc as ListOpenInterestError,O as ListOpenOrdersError,Pd as ListPerpsCandlesError,Rd as ListPerpsFundingHistoryError,Td as ListPerpsTradesError,ge as ListPositionsError,rf as ListSeriesError,vf as ListSportsError,Cf as ListTagsError,Kf as ListTeamsError,yc as ListTraderLeaderboardError,ma as ListTradesError,ia as ListUserEarningsAndMarketsConfigError,ea as ListUserEarningsForDayError,Re as MergeComboPositionError,Qe as MergeMarketPositionError,Pe as MergePositionsError,Xd as OpenPerpsSessionError,gf as OpenRfqSessionError,wd as PlaceLimitOrderError,sd as PlaceMarketOrderError,$b as PlanCollateralReturnError,$c as PostOrderError,ad as PostOrdersError,bc as PrepareCollateralReturnExecutionError,Ta as PrepareErc1155ApprovalForAllError,Pa as PrepareErc20ApprovalError,Mf as PrepareErc20TransferError,Fa as PrepareGaslessTransactionError,id as PrepareLimitOrderError,md as PrepareLimitOrderPostingError,gd as PrepareMarketOrderError,kd as PrepareMarketOrderPostingError,ze as PrepareMergeComboPositionError,ye as PrepareMergeMarketPositionError,xe as PrepareMergePositionsError,Zd as PreparePerpsDepositError,Ce as PrepareRedeemComboPositionError,Be as PrepareRedeemMarketPositionsError,Ae as PrepareRedeemPositionsError,we as PrepareSplitComboPositionError,ve as PrepareSplitMarketPositionError,ue as PrepareSplitPositionError,Xa as PrepareTradingApprovalsError,Ye as RedeemPositionsError,zb as ResolveConditionByTokenError,nb as RevokeBuilderApiKeyError,Yd as RevokePerpsCredentialsError,df as RfqCancelQuoteError,cf as RfqCancelQuoteRejectedError,if as RfqConfirmationDecision,ff as RfqConfirmationError,ef as RfqConfirmationRejectedError,jf as RfqDirection,kf as RfqExecutionStatus,lf as RfqKnownErrorCode,bf as RfqQuoteError,af as RfqQuoteRejectedError,mf as RfqRequestedSizeUnit,nf as RfqSide,pf as SearchError,of as SearchSort,Za as SetupTradingApprovalsError,Ie as SplitComboPositionError,He as SplitMarketPositionError,Ge as SplitPositionError,Af as SubscribeError,Of as TransferErc20Error,_ as UpdateBalanceAllowanceError,Fd as UpdatePerpsLeverageError,Na as WaitForGaslessTransactionError,od as WaitForOrderFillSettlementError,$d as WithdrawFromPerpsError,Wa as approveErc1155ForAll,Sa as approveErc20,Ja as buildDepositWalletExecuteRequest,Ha as buildProxyWalletExecuteRequest,La as buildSafeWalletExecuteRequest,Vc as cancelAll,Xc as cancelMarketOrders,Rc as cancelOrder,Tc as cancelOrders,ab as createApiKey,kb as createBuilderApiKey,vd as createLimitOrder,rd as createMarketOrder,eb as createOrDeriveApiKey,ib as deleteApiKey,Da as deployDepositWallet,de as depositToPerps,cb as deriveApiKey,re as downloadAccountingSnapshot,X as dropNotifications,Zc as estimateMarketPrice,ec as executeCollateralReturnPlan,Ia as extractOnChainNonceFromSubmitError,gb as fetchApiKeys,Z as fetchBalanceAllowance,mb as fetchBuilderApiKeys,Eb as fetchBuilderFeeRates,xc as fetchBuilderVolume,N as fetchClosedOnlyMode,jc as fetchCommentsById,pc as fetchEvent,tc as fetchEventLiveVolume,rc as fetchEventTags,ya as fetchExecuteParams,Sb as fetchLastTradePrice,Ub as fetchLastTradePrices,Hc as fetchMarket,Cb as fetchMarketInfo,Jc as fetchMarketTags,sb as fetchMidpoint,ub as fetchMidpoints,yb as fetchNegRisk,V as fetchNotifications,R as fetchOrder,Kb as fetchOrderBook,Mb as fetchOrderBooks,ba as fetchOrderScoring,da as fetchOrdersScoring,Od as fetchPerpsBook,Wd as fetchPerpsFees,Id as fetchPerpsInstruments,Kd as fetchPerpsTicker,Md as fetchPerpsTickers,ne as fetchPortfolioValue,Gb as fetchPrice,Wb as fetchPriceHistory,Ib as fetchPrices,$e as fetchPublicProfile,Jf as fetchRelatedTagResources,Hf as fetchRelatedTags,la as fetchRewardPercentages,uf as fetchSeries,yf as fetchSportsMarketTypes,Ob as fetchSpread,Qb as fetchSpreads,Ff as fetchTag,wb as fetchTickSize,ha as fetchTotalEarningsForUserForDay,pe as fetchTradedMarketCount,Ea as fetchTransaction,Ma as isRetryableGaslessSubmitError,Aa as isWalletDeployed,T as listAccountTrades,pa as listActivity,vc as listBuilderLeaderboard,qb as listBuilderTrades,je as listClosedPositions,ra as listComboActivity,Fc as listComboMarkets,le as listComboPositions,hc as listComments,lc as listCommentsByUserAddress,Yb as listCurrentRewards,nc as listEvents,Bc as listMarketClarifications,Lc as listMarketHolders,Pc as listMarketPositions,_b as listMarketRewards,Dc as listMarkets,Nc as listOpenInterest,P as listOpenOrders,Qd as listPerpsCandles,Sd as listPerpsFundingHistory,Ud as listPerpsTrades,he as listPositions,sf as listSeries,wf as listSports,Df as listTags,Lf as listTeams,zc as listTraderLeaderboard,na as listTrades,ja as listUserEarningsAndMarketsConfig,fa as listUserEarningsForDay,Te as mergeComboPosition,Se as mergeMarketPosition,Ue as mergePositions,ae as openPerpsSession,hf as openRfqSession,xd as placeLimitOrder,td as placeMarketOrder,ac as planCollateralReturn,bd as postOrder,cd as postOrders,cc as prepareCollateralReturnExecution,Ua as prepareErc1155ApprovalForAll,Qa as prepareErc20Approval,Nf as prepareErc20Transfer,Ga as prepareGaslessTransaction,jd as prepareLimitOrder,nd as prepareLimitOrderPosting,hd as prepareMarketOrder,ld as prepareMarketOrderPosting,Ne as prepareMergeComboPosition,Me as prepareMergeMarketPosition,Oe as prepareMergePositions,ce as preparePerpsDeposit,We as prepareRedeemComboPosition,Ve as prepareRedeemMarketPositions,Xe as prepareRedeemPositions,Ee as prepareSplitComboPosition,De as prepareSplitMarketPosition,Fe as prepareSplitPosition,Ya as prepareTradingApprovals,Ze as redeemPositions,Ka as resignDepositWalletExecuteRequest,Ab as resolveConditionByToken,_c as resolveEstimatedMarketPrice,ob as revokeBuilderApiKey,be as revokePerpsCredentials,qf as search,_a as setupTradingApprovals,fd as signOrder,Ke as splitComboPosition,Je as splitMarketPosition,Le as splitPosition,Bf as subscribe,Pf as transferErc20,$ as updateBalanceAllowance,pd as waitForOrderFillSettlement,ee as withdrawFromPerps}from'../chunk-NJ2FDU52.js';import'../chunk-4LDMO37Q.js';//# sourceMappingURL=index.js.map
1
+ export{Va as ApproveErc1155ForAllError,Ra as ApproveErc20Error,Uc as CancelAllError,Wc as CancelMarketOrdersError,Qc as CancelOrderError,Sc as CancelOrdersError,fc as CollateralReturnKnownOperationKind,sa as ComboActivityType,se as ComboPositionOutcome,fe as ComboPositionSort,te as ComboPositionStatus,$a as CreateApiKeyError,jb as CreateBuilderApiKeyError,ud as CreateLimitOrderError,qd as CreateMarketOrderError,db as CreateOrDeriveApiKeyError,hb as DeleteApiKeyError,Ca as DeployDepositWalletError,_d as DepositToPerpsError,bb as DeriveApiKeyError,qe as DownloadAccountingSnapshotError,W as DropNotificationsError,Yc as EstimateMarketPriceError,dc as ExecuteCollateralReturnPlanError,fb as FetchApiKeysError,Y as FetchBalanceAllowanceError,lb as FetchBuilderApiKeysError,Db as FetchBuilderFeeRatesError,M as FetchClosedOnlyModeError,ic as FetchCommentsByIdError,oc as FetchEventError,sc as FetchEventLiveVolumeError,qc as FetchEventTagsError,xa as FetchExecuteParamsError,Rb as FetchLastTradePriceError,Tb as FetchLastTradePricesError,Gc as FetchMarketError,Bb as FetchMarketInfoError,Ic as FetchMarketTagsError,rb as FetchMidpointError,tb as FetchMidpointsError,xb as FetchNegRiskError,U as FetchNotificationsError,Jb as FetchOrderBookError,Lb as FetchOrderBooksError,Q as FetchOrderError,aa as FetchOrderScoringError,ca as FetchOrdersScoringError,Nd as FetchPerpsBookError,Vd as FetchPerpsFeesError,Hd as FetchPerpsInstrumentsError,Jd as FetchPerpsTickerError,Ld as FetchPerpsTickersError,me as FetchPortfolioValueError,Fb as FetchPriceError,Vb as FetchPriceHistoryError,Hb as FetchPricesError,_e as FetchPublicProfileError,Hf as FetchRelatedTagResourcesError,Ff as FetchRelatedTagsError,ka as FetchRewardPercentagesError,tf as FetchSeriesError,xf as FetchSportsMarketTypesError,Nb as FetchSpreadError,Pb as FetchSpreadsError,Df as FetchTagError,vb as FetchTickSizeError,ga as FetchTotalEarningsForUserForDayError,oe as FetchTradedMarketCountError,Oa as GaslessTransactionHandle,Ba as GaslessTransactionMetadataSchema,za as IsWalletDeployedError,S as ListAccountTradesError,oa as ListActivityError,uc as ListBuilderLeaderboardError,pb as ListBuilderTradesError,wc as ListBuilderVolumeError,ie as ListClosedPositionsError,qa as ListComboActivityError,Ec as ListComboMarketsError,ke as ListComboPositionsError,kc as ListCommentsByUserAddressError,gc as ListCommentsError,Xb as ListCurrentRewardsError,mc as ListEventsError,Ac as ListMarketClarificationsError,Kc as ListMarketHoldersError,Oc as ListMarketPositionsError,Zb as ListMarketRewardsError,Cc as ListMarketsError,Mc as ListOpenInterestError,O as ListOpenOrdersError,Pd as ListPerpsCandlesError,Rd as ListPerpsFundingHistoryError,Td as ListPerpsTradesError,ge as ListPositionsError,rf as ListSeriesError,vf as ListSportsError,Bf as ListTagsError,Jf as ListTeamsError,yc as ListTraderLeaderboardError,ma as ListTradesError,ia as ListUserEarningsAndMarketsConfigError,ea as ListUserEarningsForDayError,Re as MergeComboPositionError,Qe as MergeMarketPositionError,Pe as MergePositionsError,Xd as OpenPerpsSessionError,gf as OpenRfqSessionError,wd as PlaceLimitOrderError,sd as PlaceMarketOrderError,$b as PlanCollateralReturnError,$c as PostOrderError,ad as PostOrdersError,bc as PrepareCollateralReturnExecutionError,Ta as PrepareErc1155ApprovalForAllError,Pa as PrepareErc20ApprovalError,Lf as PrepareErc20TransferError,Fa as PrepareGaslessTransactionError,id as PrepareLimitOrderError,md as PrepareLimitOrderPostingError,gd as PrepareMarketOrderError,kd as PrepareMarketOrderPostingError,ze as PrepareMergeComboPositionError,ye as PrepareMergeMarketPositionError,xe as PrepareMergePositionsError,Zd as PreparePerpsDepositError,Ce as PrepareRedeemComboPositionError,Be as PrepareRedeemMarketPositionsError,Ae as PrepareRedeemPositionsError,we as PrepareSplitComboPositionError,ve as PrepareSplitMarketPositionError,ue as PrepareSplitPositionError,Xa as PrepareTradingApprovalsError,Ye as RedeemPositionsError,zb as ResolveConditionByTokenError,nb as RevokeBuilderApiKeyError,Yd as RevokePerpsCredentialsError,df as RfqCancelQuoteError,cf as RfqCancelQuoteRejectedError,if as RfqConfirmationDecision,ff as RfqConfirmationError,ef as RfqConfirmationRejectedError,jf as RfqDirection,kf as RfqExecutionStatus,lf as RfqKnownErrorCode,bf as RfqQuoteError,af as RfqQuoteRejectedError,mf as RfqRequestedSizeUnit,nf as RfqSide,pf as SearchError,of as SearchSort,Za as SetupTradingApprovalsError,Ie as SplitComboPositionError,He as SplitMarketPositionError,Ge as SplitPositionError,zf as SubscribeError,Nf as TransferErc20Error,_ as UpdateBalanceAllowanceError,Fd as UpdatePerpsLeverageError,Na as WaitForGaslessTransactionError,od as WaitForOrderFillSettlementError,$d as WithdrawFromPerpsError,Wa as approveErc1155ForAll,Sa as approveErc20,Ja as buildDepositWalletExecuteRequest,Ha as buildProxyWalletExecuteRequest,La as buildSafeWalletExecuteRequest,Vc as cancelAll,Xc as cancelMarketOrders,Rc as cancelOrder,Tc as cancelOrders,ab as createApiKey,kb as createBuilderApiKey,vd as createLimitOrder,rd as createMarketOrder,eb as createOrDeriveApiKey,ib as deleteApiKey,Da as deployDepositWallet,de as depositToPerps,cb as deriveApiKey,re as downloadAccountingSnapshot,X as dropNotifications,Zc as estimateMarketPrice,ec as executeCollateralReturnPlan,Ia as extractOnChainNonceFromSubmitError,gb as fetchApiKeys,Z as fetchBalanceAllowance,mb as fetchBuilderApiKeys,Eb as fetchBuilderFeeRates,xc as fetchBuilderVolume,N as fetchClosedOnlyMode,jc as fetchCommentsById,pc as fetchEvent,tc as fetchEventLiveVolume,rc as fetchEventTags,ya as fetchExecuteParams,Sb as fetchLastTradePrice,Ub as fetchLastTradePrices,Hc as fetchMarket,Cb as fetchMarketInfo,Jc as fetchMarketTags,sb as fetchMidpoint,ub as fetchMidpoints,yb as fetchNegRisk,V as fetchNotifications,R as fetchOrder,Kb as fetchOrderBook,Mb as fetchOrderBooks,ba as fetchOrderScoring,da as fetchOrdersScoring,Od as fetchPerpsBook,Wd as fetchPerpsFees,Id as fetchPerpsInstruments,Kd as fetchPerpsTicker,Md as fetchPerpsTickers,ne as fetchPortfolioValue,Gb as fetchPrice,Wb as fetchPriceHistory,Ib as fetchPrices,$e as fetchPublicProfile,If as fetchRelatedTagResources,Gf as fetchRelatedTags,la as fetchRewardPercentages,uf as fetchSeries,yf as fetchSportsMarketTypes,Ob as fetchSpread,Qb as fetchSpreads,Ef as fetchTag,wb as fetchTickSize,ha as fetchTotalEarningsForUserForDay,pe as fetchTradedMarketCount,Ea as fetchTransaction,Ma as isRetryableGaslessSubmitError,Aa as isWalletDeployed,T as listAccountTrades,pa as listActivity,vc as listBuilderLeaderboard,qb as listBuilderTrades,je as listClosedPositions,ra as listComboActivity,Fc as listComboMarkets,le as listComboPositions,hc as listComments,lc as listCommentsByUserAddress,Yb as listCurrentRewards,nc as listEvents,Bc as listMarketClarifications,Lc as listMarketHolders,Pc as listMarketPositions,_b as listMarketRewards,Dc as listMarkets,Nc as listOpenInterest,P as listOpenOrders,Qd as listPerpsCandles,Sd as listPerpsFundingHistory,Ud as listPerpsTrades,he as listPositions,sf as listSeries,wf as listSports,Cf as listTags,Kf as listTeams,zc as listTraderLeaderboard,na as listTrades,ja as listUserEarningsAndMarketsConfig,fa as listUserEarningsForDay,Te as mergeComboPosition,Se as mergeMarketPosition,Ue as mergePositions,ae as openPerpsSession,hf as openRfqSession,xd as placeLimitOrder,td as placeMarketOrder,ac as planCollateralReturn,bd as postOrder,cd as postOrders,cc as prepareCollateralReturnExecution,Ua as prepareErc1155ApprovalForAll,Qa as prepareErc20Approval,Mf as prepareErc20Transfer,Ga as prepareGaslessTransaction,jd as prepareLimitOrder,nd as prepareLimitOrderPosting,hd as prepareMarketOrder,ld as prepareMarketOrderPosting,Ne as prepareMergeComboPosition,Me as prepareMergeMarketPosition,Oe as prepareMergePositions,ce as preparePerpsDeposit,We as prepareRedeemComboPosition,Ve as prepareRedeemMarketPositions,Xe as prepareRedeemPositions,Ee as prepareSplitComboPosition,De as prepareSplitMarketPosition,Fe as prepareSplitPosition,Ya as prepareTradingApprovals,Ze as redeemPositions,Ka as resignDepositWalletExecuteRequest,Ab as resolveConditionByToken,_c as resolveEstimatedMarketPrice,ob as revokeBuilderApiKey,be as revokePerpsCredentials,qf as search,_a as setupTradingApprovals,fd as signOrder,Ke as splitComboPosition,Je as splitMarketPosition,Le as splitPosition,Af as subscribe,Of as transferErc20,$ as updateBalanceAllowance,pd as waitForOrderFillSettlement,ee as withdrawFromPerps}from'../chunk-EC3TWEID.js';import'../chunk-4LDMO37Q.js';//# sourceMappingURL=index.js.map
2
2
  //# sourceMappingURL=index.js.map
@@ -0,0 +1,3 @@
1
+ import {m,g as g$1,f as f$1,l as l$1,c,b,a,h,i,j,k,e}from'./chunk-4LDMO37Q.js';import {PaginationCursorSchema,ComboConditionIdSchema,TransactionIdSchema,EvmAddressSchema,BuilderCodeSchema,TokenIdSchema,CtfConditionIdSchema,OrderSideSchema,CommentParentEntityTypeSchema,EventIdSchema,CommentIdSchema,IsoDateTimeStringSchema,IsoCalendarDateStringSchema,PositionIdSchema,OrderType,PositiveDecimalNumberSchema,OrderSide,TxHashSchema,MarketIdSchema,TradeStatus,toPaginationCursor,toDecimalString,toComboConditionId,toPositionId}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 lo 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{ComboActivityType as sa,ComboPositionOutcome as se,ComboPositionStatus as te}from'@polymarket/bindings/data';import {RelayerTransactionType,RelayerExecuteRequestSchema,RelayerTransactionState,RelayerExecuteParamsSchema,RelayerDeployedResponseSchema,GaslessTransactionSchema,RelayerExecuteResponseSchema}from'@polymarket/bindings/relayer';import {CollateralReturnPlanSchema,CollateralReturnPlanResponseSchema,ListComboMarketsResponseSchema}from'@polymarket/bindings/combos';export{CollateralReturnKnownOperationKind as fc,RfqConfirmationDecision as if,RfqDirection as jf,RfqExecutionStatus as kf,RfqKnownErrorCode as lf,RfqRequestedSizeUnit as mf,RfqSide as nf}from'@polymarket/bindings/combos';import {PerpsPnlIntervalSchema,PerpsWithdrawalStatusSchema,PerpsDepositStatusSchema,PerpsInstrumentIdSchema,PerpsClientOrderIdSchema,PerpsOrderIdSchema,PerpsSortDirectionSchema,PerpsDecimalInputSchema,PerpsTimeInForce,PerpsCommandAckSchema,PerpsInstrumentCategorySchema,PerpsKlineIntervalSchema,PerpsTradeIdSchema,PerpsPostOrderAckSchema,PerpsTpSlKind,PerpsTpSlScope,PerpsCancelOrderResultSchema,PerpsUpdateLeverageResultSchema,FetchPerpsBalancesResponseSchema,FetchPerpsPortfolioResponseSchema,FetchPerpsAccountStatsResponseSchema,FetchPerpsAccountConfigResponseSchema,FetchPerpsOpenOrdersResponseSchema,FetchPerpsOrdersResponseSchema,ListPerpsFillsResponseSchema,ListPerpsFundingPaymentsResponseSchema,ListPerpsDepositsResponseSchema,ListPerpsWithdrawalsResponseSchema,ListPerpsEquityHistoryResponseSchema,ListPerpsPnlHistoryResponseSchema,ListPerpsNotificationsResponseSchema,FetchPerpsUnreadNotificationsCountResponseSchema,MarkPerpsNotificationsReadResponseSchema,PerpsCancelAllOrdersResponseSchema,FetchPerpsInstrumentsResponseSchema,FetchPerpsTickersResponseSchema,FetchPerpsStatisticsResponseSchema,PerpsBookSchema,FetchPerpsCandlesResponseSchema,FetchPerpsFundingHistoryResponseSchema,FetchPerpsTradesResponseSchema,FetchPerpsFeesResponseSchema,PerpsDeleteProxyResponseSchema,PerpsWithdrawResponseSchema,PerpsCreateProxyResponseSchema,PerpsCredentialsResponseSchema}from'@polymarket/bindings/perps';import {encode}from'@msgpack/msgpack';import {PerpsNotificationsResyncFrameSchema,PerpsSessionUpdateEventSchema}from'@polymarket/bindings/subscriptions';import {pushable}from'it-pushable';import tg from'it-merge';function l(e,r){let t=r.safeParse(e);if(t.success)return t.data;throw a.fromZodError(t.error)}var w=z.number().int().positive(),po=z.object({offset:z.number().int().min(0),pageSize:w});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(po.parse(e))))}function D(e,r){if(e===void 0)return {offset:0,pageSize:r};try{return po.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=>di(t.url,e,o))}}function uo(e){return ResultAsync.fromPromise(e.blob(),()=>new b(`Received unreadable binary response from ${e.url}`))}function di(e,r,t){let o=r.safeParse(t);return o.success?ok(o.data):err(b.fromZodError(o.error,{endpoint:e}))}var mo=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 f$1(`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(!So(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=Po(r.gasPrice)),r.value!==void 0&&(t.value=Po(r.value));let o=await this.#o({jsonrpc:"2.0",id:1,method:"eth_estimateGas",params:[t]});if("error"in o)throw new f$1(`JSON-RPC eth_estimateGas failed: ${o.error.message}`,{cause:o.error,status:200});return BigInt(fo(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 f$1)||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 f$1(`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 f$1(`JSON-RPC eth_call failed: ${y.error.message}`,{cause:y.error,status:200});return fo(y.result)})}async#o(r){let t;try{t=await lo.post(this.#e,{json:r,throwHttpErrors:!1});}catch(n){throw c.fromError(n)}if(!t.ok)throw new f$1(`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(!yo(o))throw new b("Unexpected JSON-RPC response shape");return o}async#n(r){let t;try{t=await lo.post(this.#e,{json:r,throwHttpErrors:!1});}catch(n){throw c.fromError(n)}if(!t.ok)throw new f$1(`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=>yo(n)))throw new b("Unexpected JSON-RPC response shape");return o}};function go(e){if(!(e instanceof f$1)||!Ro(e.cause))return false;let r=[e.cause.message,ui(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 yo(e){return !Eo(e)||e.jsonrpc!=="2.0"?false:"error"in e?Ro(e.error):"result"in e}function Ro(e){return Eo(e)&&typeof e.code=="number"&&typeof e.message=="string"}function Eo(e){return typeof e=="object"&&e!==null}function So(e){return /^0x[a-fA-F0-9]*$/.test(e)}function fo(e,r="eth_call"){if(typeof e!="string"||!So(e))throw new b(`Expected JSON-RPC ${r} result to be a hex string`);return e}function Po(e){return `0x${e.toString(16)}`}function ui(e){if(e===void 0)return "";if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return ""}}function zg(e,r,t){return {signer:r,wallet:t,walletType:Ai(e,r,t)}}function ue(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 ho(e){let r=ue(e.walletType);return {maker:e.wallet,signatureType:r,signer:r===SignatureType.POLY_1271?e.wallet:e.signer}}var mi="3d3d606380380380913d393d73%s5af4602a57600080fd5b602d8060366000396000f3363d3d373d3d3d363d73%s5af43d82803e903d91602b57fd5bf352e831dd00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000000";function yi(e){let r=mi.replace("%s",e.proxyFactory.slice(2).toLowerCase()).replace("%s",e.proxyImplementation.slice(2).toLowerCase());return expectHexString(Hash.keccak256(`0x${r}`))}function fi(e,r){return expectEvmAddress(ContractAddress.fromCreate2({bytecodeHash:yi(r),from:r.proxyFactory,salt:Hash.keccak256(AbiParameters.encodePacked(["address"],[e]))}))}function Pi(e,r){return expectEvmAddress(ContractAddress.fromCreate2({bytecodeHash:r.safeInitCodeHash,from:r.safeFactory,salt:Hash.keccak256(AbiParameters.encode([{name:"address",type:"address"}],[e]))}))}var gi="0xcc3735a920a3ca505d382bbc545af43d6000803e6038573d6000fd5b3d6000f3",Ri="0x5155f3363d3d373d3d363d7f360894a13ba1a3210667c828492db98dca3e2076",Ei=0x61003d3d8160233d3973n;function To(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:bi(r.depositWalletImplementation,o),from:r.depositWalletFactory,salt:Hash.keccak256(o)}))}var Si="0xb3582b35133d50545afa5036515af43d6000803e604d573d6000fd5b3d6000f3",hi="0x1b60e01b36527fa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6c",Ti="0x60195155f3363d3d373d3d363d602036600436635c60da",xi=0x6100523d8160233d3973n,Ci="0x49493a4d";function xo(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:ki(r.depositWalletBeacon,o),from:r.depositWalletFactory,salt:Hash.keccak256(o)}))}function bi(e,r){let t=BigInt((r.length-2)/2),o=Ei+(t<<56n);return expectHexString(Hash.keccak256(Bytes.concat(Bytes.fromNumber(o,{size:10}),Bytes.fromHex(e),Bytes.fromHex("0x6009"),Bytes.fromHex(Ri),Bytes.fromHex(gi),Bytes.fromHex(r)),{as:"Hex"}))}function ki(e,r){let t=BigInt((r.length-2)/2),o=xi+(t<<56n);return expectHexString(Hash.keccak256(Bytes.concat(Bytes.fromNumber(o,{size:10}),Bytes.fromHex(e),Bytes.fromHex(Ti),Bytes.fromHex(hi),Bytes.fromHex(Si),Bytes.fromHex(r)),{as:"Hex"}))}async function Ii(e,r){try{let t=await e.ethCall({to:r,data:Ci});return vi(t)}catch(t){if(go(t))return ZERO_ADDRESS;throw t}}async function qi(e,r){let t=await Ii(e,r);return !isSameEvmAddress(t,ZERO_ADDRESS)}async function Co(e,r,t){return await qi(e,t.depositWalletFactory)?xo(r,t):To(r,t)}function vi(e){return e.length<66?ZERO_ADDRESS:expectEvmAddress(`0x${e.slice(-40)}`)}function Ai(e,r,t){if(isSameEvmAddress(t,r))return WalletType.EOA;let o=e.walletDerivation;if(isSameEvmAddress(t,xo(r,o)))return WalletType.DEPOSIT_WALLET;if(isSameEvmAddress(t,To(r,o)))return WalletType.DEPOSIT_WALLET;if(isSameEvmAddress(t,Pi(r,o)))return WalletType.GNOSIS_SAFE;if(isSameEvmAddress(t,fi(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 wi(e,r.exceptions);let t=new URLSearchParams;for(let[o,n]of Object.entries(r)){let s=e[o];if(s!==void 0){if(bo(s)){for(let a of s)t.append(n,Fe(a));continue}t.append(n,Fe(s));}}return t}function E(e={}){return {format:"snake_case",exceptions:e}}function N(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(Fe).join(","));continue}r.append(t,Fe(o));}return r}function Oi(e){return "format"in e}function wi(e,r){let t=new URLSearchParams;for(let[o,n]of Object.entries(e)){if(n===void 0)continue;let s=r[o]??Li(o);if(bo(n)){for(let a of n)t.append(s,Fe(a));continue}t.append(s,Fe(n));}return t}function bo(e){return Array.isArray(e)}function Li(e){return e.replace(/[A-Z]/g,r=>`_${r.toLowerCase()}`)}function Fe(e){return String(e)}var Qg=m(g$1,f$1,l$1,c,b);async function Xg(e){return (await unwrap(e.secureClob.get("/auth/ban-status/closed-only").andThen(f(ClosedOnlyModeSchema)))).closedOnly}var Ki=z.object({tokenId:z.string().optional(),cursor:PaginationCursorSchema.optional(),id:z.string().optional(),market:z.string().optional()}).default({}),eR=m(g$1,f$1,l$1,c,b,a);function rR(e,r){let{cursor:t,...o}=l(r,Ki);return x(n=>e.secureClob.get("/data/orders",{params:g({...o,nextCursor:n},E({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)})),t)}var $i=z.object({orderId:z.string()}),tR=m(g$1,f$1,l$1,c,b,a);async function oR(e,r){let t=l(r,$i);return unwrap(e.secureClob.get(`/data/order/${t.orderId}`).andThen(f(OpenOrderSchema)))}var Vi={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()},Zi=z.object(Vi).default({}),nR=m(g$1,f$1,l$1,c,b,a);function Io(e,r){let{cursor:t,...o}=l(r,Zi);return x(n=>e.secureClob.get("/data/trades",{params:g({...o,nextCursor:n},E({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)})),t)}var sR=m(g$1,f$1,l$1,c,b),Yi=z.object({ids:z.array(z.string()).min(1)});async function aR(e){let r=ue(e.account.walletType);return unwrap(e.secureClob.get("/notifications",{params:g({signatureType:r},E())}).andThen(f(NotificationsResponseSchema)))}var iR=m(g$1,f$1,l$1,c,b,a);async function pR(e,r){let t=l(r,Yi),o=ue(e.account.walletType),n=g({ids:t.ids.join(","),signatureType:o},E());await unwrap(e.secureClob.del("/notifications",{params:n}));}var Ji=z.object({assetType:AssetTypeSchema,tokenId:z.string().optional()}),cR=m(g$1,f$1,l$1,c,b,a);async function Vr(e,r){let t=l(r,Ji),o=ue(e.account.walletType);return unwrap(e.secureClob.get("/balance-allowance",{params:g({...t,signatureType:o},E())}).andThen(f(BalanceAllowanceResponseSchema)))}var Qi=z.object({assetType:AssetTypeSchema,tokenId:z.string().optional()}),dR=m(g$1,f$1,l$1,c,b,a);async function qo(e,r){let t=l(r,Qi),o=ue(e.account.walletType),n=g({...t,signatureType:o},E());return await unwrap(e.secureClob.get("/balance-allowance/update",{params:n})),Vr(e,t)}var Xi=z.object({orderId:z.string()}),uR=m(g$1,f$1,l$1,c,b,a);async function lR(e,r){let t=l(r,Xi);return (await unwrap(e.secureClob.get("/order-scoring",{params:g(t,E())}).andThen(f(OrderScoringResponseSchema)))).scoring}var ep=z.object({orderIds:z.array(z.string())}),mR=m(g$1,f$1,l$1,c,b,a);async function yR(e,r){let o=l(r,ep).orderIds;return unwrap(e.secureClob.post("/orders-scoring",{json:o}).andThen(f(OrdersScoringResponseSchema)))}var vo=z.object({cursor:PaginationCursorSchema.optional(),date:z.string()}),fR=m(g$1,f$1,l$1,c,b,a);function PR(e,r){let{cursor:t,...o}=l(r,vo),n=ue(e.account.walletType);return x(s=>e.secureClob.get("/rewards/user",{params:g({...o,nextCursor:s,signatureType:n},E())}).andThen(f(UserEarningsPageSchema)).map(a=>({items:a.data,hasMore:a.nextCursor!==END_CURSOR,nextCursor:a.nextCursor===END_CURSOR?void 0:toPaginationCursor(a.nextCursor)})),t)}var gR=m(g$1,f$1,l$1,c,b,a);async function RR(e,r){let t=l(r,vo),o=ue(e.account.walletType);return unwrap(e.secureClob.get("/rewards/user/total",{params:g({...t,signatureType:o},E())}).andThen(f(TotalUserEarningsResponseSchema)))}var rp=z.object({cursor:PaginationCursorSchema.optional(),date:z.string(),noCompetition:z.boolean().optional(),orderBy:z.string().optional(),pageSize:w.max(500).default(100),position:z.string().optional()}),ER=m(g$1,f$1,l$1,c,b,a);function SR(e,r){let{cursor:t,...o}=l(r,rp),n=ue(e.account.walletType);return x(s=>e.secureClob.get("/rewards/user/markets",{params:g({...o,nextCursor:s,signatureType:n},E())}).andThen(f(UserRewardsEarningsPageSchema)).map(a=>({items:a.data,hasMore:a.nextCursor!==END_CURSOR,nextCursor:a.nextCursor===END_CURSOR?void 0:toPaginationCursor(a.nextCursor)})),t)}var hR=m(g$1,f$1,l$1,c,b);async function TR(e){let r=ue(e.account.walletType);return unwrap(e.secureClob.get("/rewards/user/percentages",{params:g({signatureType:r},E())}).andThen(f(RewardsPercentagesSchema)))}var ap=z.enum(["CASH","TOKENS"]),ip=z.object({cursor:PaginationCursorSchema.optional(),pageSize:w.max(1e4).default(20),takerOnly:z.boolean().optional(),filterType:ap.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"]}),wR=m(g$1,f$1,c,b,a);function LR(e,r={}){let{cursor:t,pageSize:o,...n}=l(r,ip);return x(s=>{let a=D(s,o);return e.data.get("/trades",{params:N({...n,limit:a.pageSize,offset:a.offset})}).andThen(f(ListTradesResponseSchema)).map(y=>{let P=y.length>=a.pageSize;return {items:y,hasMore:P,nextCursor:P?B({offset:a.offset+a.pageSize,pageSize:a.pageSize}):void 0}})},t)}var pp=z.enum(["TIMESTAMP","TOKENS","CASH"]),cp=z.enum(["ASC","DESC"]),dp=z.object({cursor:PaginationCursorSchema.optional(),pageSize:w.max(500).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:pp.optional(),sortDirection:cp.optional(),side:SideSchema.optional()}).refine(e=>!(e.market&&e.eventId),{message:"Provide market or eventId, not both",path:["eventId"]}),MR=m(g$1,f$1,c,b,a);function FR(e,r){let{cursor:t,pageSize:o,...n}=l(r,dp);return x(s=>{let a=D(s,o);return e.data.get("/activity",{params:N({...n,excludeDepositsWithdrawals:false,limit:a.pageSize,offset:a.offset})}).andThen(f(ListActivityResponseSchema)).map(y=>{let P=y.length>=a.pageSize;return {items:y,hasMore:P,nextCursor:P?B({offset:a.offset+a.pageSize,pageSize:a.pageSize}):void 0}})},t)}var up=z.union([ComboConditionIdSchema,z.array(ComboConditionIdSchema)]),lp=z.object({cursor:PaginationCursorSchema.optional(),pageSize:w.default(50),user:z.string(),conditionId:up.optional()}),BR=m(g$1,f$1,c,b,a);function UR(e,r){let{cursor:t,pageSize:o,conditionId:n,...s}=l(r,lp);return x(a=>{let y=g({...s,limit:o,cursor:a},E());return mp(y,n),e.data.get("/v1/activity/combos",{params:y}).andThen(f(ListComboActivityResponseSchema)).map(P=>{let A=P.pagination.nextCursor??void 0;return {items:P.activity,hasMore:A!==void 0,nextCursor:A}})},t)}function mp(e,r){r!==void 0&&e.append("market_id",Array.isArray(r)?r.join(","):r);}var fp=64,Pp=/^0x[0-9a-fA-F]{62}$/,gp=/^0x[0-9a-fA-F]{64}$/,Yr="0x0000000000000000000000000000000000000000000000000000000000000000",Rp=AbiFunction.from("function approve(address spender, uint256 amount)"),Lo=AbiFunction.from("function allowance(address owner, address spender) view returns (uint256)"),Ep=AbiFunction.from("function transfer(address recipient, uint256 amount)"),Sp=AbiFunction.from("function deposit(address token, uint256 amount, address to)"),hp=AbiFunction.from("function setApprovalForAll(address operator, bool approved)"),Mo=AbiFunction.from("function isApprovedForAll(address account, address operator) view returns (bool)"),Fo=AbiFunction.from("function balanceOf(address account, uint256 id) view returns (uint256)"),Bo=AbiFunction.from("function balanceOfBatch(address[] accounts, uint256[] ids) view returns (uint256[])"),Tp=AbiFunction.from("function splitPosition(address collateralToken, bytes32 parentCollectionId, bytes32 conditionId, uint256[] partition, uint256 amount)"),xp=AbiFunction.from("function mergePositions(address collateralToken, bytes32 parentCollectionId, bytes32 conditionId, uint256[] partition, uint256 amount)"),Cp=AbiFunction.from("function redeemPositions(address collateralToken, bytes32 parentCollectionId, bytes32 conditionId, uint256[] indexSets)"),bp=AbiFunction.from("function split(bytes31 conditionId, uint256 amount)"),kp=AbiFunction.from("function merge(bytes31 conditionId, uint256 amount)"),Ip=AbiFunction.from("function redeem(bytes31 conditionId, uint256 outcomeIndex, uint256 amount)"),qp=AbiFunction.from("function prepareCondition(uint256[] legs) returns (bytes31)"),vp=AbiFunction.from("function multiSend(bytes)"),Ap=AbiFunction.from("function proxy((uint8 typeCode, address to, uint256 value, bytes data)[] calls) returns (bytes[])"),Uo=[1n,2n],Op=[1n,2n],ee=(1n<<256n)-1n,NR=m(a);function Pr(e,r,t){if(t<0n)throw new a("Approval amount must be non-negative");if(t>ee)throw new a("Approval amount exceeds uint256 range");return {data:wp(r,t),to:e}}function Do(e,r,t){return {data:AbiFunction.encodeData(Lo,[r,t]),to:e}}function zo(e){return AbiFunction.decodeResult(Lo,e)}function gr(e,r,t){return {data:Lp(r,t),to:e}}function Wo(e,r,t){return {data:AbiFunction.encodeData(Mo,[r,t]),to:e}}function jo(e){return AbiFunction.decodeResult(Mo,e)}function Ho(e,r,t){return {data:AbiFunction.encodeData(Fo,[r,Re(BigInt(t),"Position ID")]),to:e}}function _o(e){return AbiFunction.decodeResult(Fo,e)}function Jr(e,r,t){return {data:AbiFunction.encodeData(Bo,[t.map(()=>r),t.map(o=>Re(BigInt(o),"id"))]),to:e}}function Qr(e){return AbiFunction.decodeResult(Bo,e)}var GR=m(a);function Xr(e,r,t){if(t<0n)throw new a("Transfer amount must be non-negative");if(t>ee)throw new a("Transfer amount exceeds uint256 range");return {data:Mp(r,t),to:e}}var KR=m(a);function No(e,r,t,o){if(t<=0n)throw new a("Perps deposit amount must be positive");return {data:AbiFunction.encodeData(Sp,[r,Re(t,"Perps deposit amount"),o]),to:e}}var $R=m(a),VR=m(a);function Go(e,r,t,o){return {data:Fp(r,t,o),to:e}}var ZR=m(a);function Ko(e,r,t,o){return {data:Bp(r,t,o),to:e}}function $o(e,r,t){return {data:Up(r,t),to:e}}var YR=m(a);function Vo(e,r,t){return {data:AbiFunction.encodeData(bp,[rt(r),Re(t,"Split amount")]),to:e}}var JR=m(a);function Zo(e,r,t){return {data:AbiFunction.encodeData(kp,[rt(r),Re(t,"Merge amount")]),to:e}}var QR=m(a);function Yo(e,r,t,o){return {data:AbiFunction.encodeData(Ip,[rt(r),BigInt(Dp(t)),Re(o,"Redeem amount")]),to:e}}var XR=m(a);function et(e,r){return {data:AbiFunction.encodeData(qp,[r.map(t=>Re(t,"Leg position ID"))]),to:e}}function wp(e,r){return invariant(r>=0n,"Approval amount must be non-negative"),AbiFunction.encodeData(Rp,[e,r])}function Lp(e,r){return AbiFunction.encodeData(hp,[e,r])}function Mp(e,r){return AbiFunction.encodeData(Ep,[e,r])}function Fp(e,r,t){return AbiFunction.encodeData(Tp,[e,Yr,r,Uo,Re(t,"Split amount")])}function Bp(e,r,t){return AbiFunction.encodeData(xp,[e,Yr,r,Uo,Re(t,"Merge amount")])}function Up(e,r){return AbiFunction.encodeData(Cp,[e,Yr,r,Op])}function Re(e,r){if(e<0n)throw new a(`${r} must be non-negative`);if(e>ee)throw new a(`${r} exceeds uint256 range`);return e}function rt(e){if(Pp.test(e))return e.toLowerCase();if(gp.test(e)){let r=e.toLowerCase();if(r.endsWith("00")||r.endsWith("01"))return r.slice(0,fp)}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 Jo(e){return AbiFunction.encodeData(Ap,[e.map(r=>({typeCode:1,to:r.to,value:r.value??0n,data:r.data}))])}function Qo(e){let r=e.map(t=>zp(t));return AbiFunction.encodeData(vp,[r.length===0?"0x":AbiParameters.encodePacked(Array.from({length:r.length},()=>"bytes"),r)])}function zp(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 oE=m(g$1,f$1,h,i,c,b,a);function G(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}m(j,l$1);m(j,l$1);function pE(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 H(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 Xo(){return {kind:"requestAddress"}}function K(e,r){return {chainId:e,...r}}var Qp=[{name:"chainId",type:"uint256"},{name:"verifyingContract",type:"address"}],Xp=[{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"}],ec="DepositWallet",rc="1",tc=600,oc=[{name:"target",type:"address"},{name:"value",type:"uint256"},{name:"data",type:"bytes"}],nc=[{name:"wallet",type:"address"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"},{name:"calls",type:"Call[]"}],sc=z.object({address:z.string(),type:z.enum(RelayerTransactionType)}),xE=m(g$1,f$1,c,b,a);async function nt(e,r){let t=l(r,sc);return unwrap(e.relayer.get("/v1/account/transactions/params",{params:g(t,{address:"address",type:"type"})}).andThen(f(RelayerExecuteParamsSchema)))}var ac=z.object({transactionId:TransactionIdSchema}),ic=z.object({wallet:EvmAddressSchema,type:z.enum(WalletType)}),CE=m(g$1,f$1,c,b,a);async function bE(e,r){let t=await pc(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 pc(e,r){if(r!==void 0)return l(r,ic);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 Co(e.rpc,e.account.signer,e.environment.walletDerivation),type:WalletType.DEPOSIT_WALLET}}var $=z.string().max(500),en=10,kE=m(g$1,f$1,c,b,a);async function IE(e){return invariant(e.supportsGasless,"Deposit Wallet deployment requires a Relayer API Key or Builder API Key in the client configuration."),er(e,{from:e.account.signer,metadata:"Deploy Deposit Wallet",to:e.environment.walletDerivation.depositWalletFactory,type:RelayerTransactionType.WALLET_CREATE})}async function cc(e,r){let t=l(r,ac);return unwrap(e.relayer.get(`/v1/account/transactions/${t.transactionId}`).andThen(f(GaslessTransactionSchema)))}var dc=z.object({data:z.custom(isHexString),to:EvmAddressSchema,value:z.bigint().optional()}),uc=z.object({calls:z.array(dc).min(1).transform(e=>expectNonEmptyArray(e)),metadata:$}),qE=m(g$1,f$1,c,b,a);async function Q(e,r){let t=l(r,uc);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 Xo());invariant(o===e.account.signer,"Wallet client address does not match the authenticated signer");for(let n=0;n<=en;n+=1)try{switch(e.account.walletType){case WalletType.POLY_PROXY:return yield*lc(e,t);case WalletType.DEPOSIT_WALLET:return yield*mc(e,t);case WalletType.GNOSIS_SAFE:return yield*yc(e,t)}invariant(!1,"Unsupported wallet type for gasless transaction");}catch(s){if(!dt(s)||n===en)throw s;await delay(e.environment.relayerPollFrequencyMs);}invariant(false,"Expected gasless transaction retry loop to return");}.call(null)}async function*lc(e,r){let t=yield*st(e,r.calls,r.metadata);return er(e,t)}async function*st(e,r,t){let o=await nt(e,{address:e.account.signer,type:RelayerTransactionType.PROXY}),n=e.environment.walletDerivation.proxyFactory,s=Jo(r),a="0",y="0",P=(await e.rpc.ethEstimateGas({data:s,from:e.account.signer,to:n})).toString(),A=e.environment.contracts.relayHub,q=o.address,j=Rc(e.account.signer,n,s,a,y,P,o.nonce,A,q),U=expectEvmSignature(yield sn(j));return {data:s,from:e.account.signer,...t!==void 0&&{metadata:t},nonce:o.nonce,proxyWallet:e.account.wallet,signature:U,signatureParams:{gasLimit:P,gasPrice:y,relay:q,relayHub:A,relayerFee:a},to:n,type:RelayerTransactionType.PROXY}}function at(e){return !(e instanceof f$1)||e.status!==400?void 0:/batch nonce\s+\d+\s+does not match on-chain nonce\s+(\d+)/i.exec(e.message)?.[1]}async function*mc(e,r){let t=yield*it(e,r.calls,r.metadata);try{return await er(e,t)}catch(o){let n=at(o);if(n===void 0)throw o;let s=yield*pt(e,t,r.calls,n);return er(e,s)}}async function*it(e,r,t){let o=await nt(e,{address:e.account.signer,type:RelayerTransactionType.WALLET}),n=r.map(on),s=`${Math.floor(Date.now()/1e3)+tc}`,a=expectEvmSignature(yield an(nn({calls:n,chainId:e.environment.chainId,deadline:s,nonce:o.nonce,wallet:e.account.wallet})));return {depositWalletParams:{calls:n,deadline:s,depositWallet:e.account.wallet},from:e.account.signer,...t!==void 0&&{metadata:t},nonce:o.nonce,signature:a,to:e.environment.walletDerivation.depositWalletFactory,type:RelayerTransactionType.WALLET}}async function*pt(e,r,t,o){let n=expectEvmSignature(yield an(nn({calls:t.map(on),chainId:e.environment.chainId,deadline:r.depositWalletParams.deadline,nonce:o,wallet:e.account.wallet})));return {...r,nonce:o,signature:n}}async function*yc(e,r){let t=yield*ct(e,r.calls,r.metadata);return er(e,t)}async function*ct(e,r,t){let o=await nt(e,{address:e.account.signer,type:RelayerTransactionType.SAFE}),n=fc(r,e.environment.contracts.safeMultisend),s=gc({chainId:e.environment.chainId,data:n.data,nonce:o.nonce,operation:n.operation,safeAddress:e.account.wallet,to:n.to,value:n.value}),a=expectEvmSignature(yield sn(expectHexString(TypedData.getSignPayload(s))));return {data:n.data,from:e.account.signer,...t!==void 0&&{metadata:t},nonce:o.nonce,proxyWallet:e.account.wallet,signature:Ec(a),signatureParams:Pc(n.operation),to:n.to,type:RelayerTransactionType.SAFE,value:n.value>0n?`${n.value}`:void 0}}async function er(e,r){let t=l(r,RelayerExecuteRequestSchema),o=await unwrap(e.relayer.post("/submit",{json:t}).andThen(f(RelayerExecuteResponseSchema)));return new rr(e,o)}function dt(e){if(e instanceof g$1)return true;if(!(e instanceof f$1)||e.status!==400)return false;if(/wallet busy/i.test(e.message)&&/active action/i.test(e.message)||/wallet has in-flight action/i.test(e.message))return true;let r=/batch nonce\s+(\d+)\s+does not match on-chain nonce\s+(\d+)/i.exec(e.message);if(r===null)return false;let t=r[1],o=r[2];return t===void 0||o===void 0?false:BigInt(t)<BigInt(o)}function on(e){return {data:e.data,target:e.to,value:`${e.value??0n}`}}function nn(e){return {domain:{chainId:e.chainId,name:ec,verifyingContract:e.wallet,version:rc},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:nc,Call:oc}}}function fc(e,r){if(e.length===1){let[t]=e;return {data:t.data,operation:0,to:t.to,value:t.value??0n}}return {data:Qo(e),operation:1,to:r,value:0n}}function Pc(e){return {baseGas:"0",gasPrice:"0",gasToken:ZERO_ADDRESS,operation:`${e}`,refundReceiver:ZERO_ADDRESS,safeTxnGas:"0"}}function gc(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:Qp,SafeTx:Xp}}}function sn(e){return {kind:"signGaslessMessage",payload:e}}function an(e){return {kind:"signGaslessTypedData",payload:e}}function Rc(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 Ec(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 vE=m(g$1,f$1,c,b,a,h,i),rr=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 cc(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 i(t.errorMsg??`Transaction ${t.transactionId} reached terminal state ${t.state}`);r+=1,await delay(this.#e.environment.relayerPollFrequencyMs);}throw new h(`Timed out waiting for transaction ${this.transactionId} to settle`)}};var Sc=z.object({amount:z.union([z.bigint(),z.literal("max")]),metadata:$.optional(),spenderAddress:EvmAddressSchema,tokenAddress:EvmAddressSchema}),WE=m(a);async function hc(e,r){let t=l(r,Sc),o=t.amount==="max"?ee:t.amount;return async function*(){return e.account.walletType===WalletType.EOA?G(yield dn(K(e.environment.chainId,Pr(t.tokenAddress,t.spenderAddress,o)))):yield*await Q(e,{calls:[Pr(t.tokenAddress,t.spenderAddress,o)],metadata:t.metadata??`Approve ${t.amount} of ${t.tokenAddress} to ${t.spenderAddress}`})}.call(null)}var jE=m(j,g$1,f$1,l$1,c,b,a);function pn(e,r){return hc(e,r).then(H(e.signer))}var Tc=z.object({approved:z.boolean().default(true),metadata:$.optional(),operatorAddress:EvmAddressSchema,tokenAddress:EvmAddressSchema}),HE=m(a);async function xc(e,r){let t=l(r,Tc);return async function*(){return e.account.walletType===WalletType.EOA?G(yield un(K(e.environment.chainId,gr(t.tokenAddress,t.operatorAddress,t.approved)))):yield*await Q(e,{calls:[gr(t.tokenAddress,t.operatorAddress,t.approved)],metadata:t.metadata??`${t.approved?"Approve":"Revoke"} ${t.operatorAddress} on ${t.tokenAddress}`})}.call(null)}var _E=m(j,g$1,f$1,l$1,c,b,a);function cn(e,r){return xc(e,r).then(H(e.signer))}var NE=m(f$1,c,b,a);async function Cc(e){let r=await bc(e),t=r.erc20.map(n=>Pr(n.tokenAddress,n.spenderAddress,n.amount)),o=r.erc1155.map(n=>gr(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 G(yield dn(K(e.environment.chainId,s))).wait();for(let s of o)await G(yield un(K(e.environment.chainId,s))).wait();return}await(yield*await Q(e,{calls:[...t,...o],metadata:"Trading setup approvals"})).wait();}.call(null)}var GE=m(j,g$1,f$1,l$1,h,i,c,b,a);function KE(e){return Cc(e).then(H(e.signer)).then(()=>{})}async function bc(e){let r=kc(e),t=[...r.erc20.map(a=>Do(a.tokenAddress,e.account.wallet,a.spenderAddress)),...r.erc1155.map(a=>Wo(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)=>zo(n[y])<a.amount),erc1155:r.erc1155.filter((a,y)=>!jo(s[y]))}}function kc(e){let{contracts:r}=e.environment;return {erc20:[{amount:ee,spenderAddress:r.standardExchange,tokenAddress:r.collateralToken},{amount:ee,spenderAddress:r.negRiskExchange,tokenAddress:r.collateralToken},{amount:ee,spenderAddress:r.collateralAdapter,tokenAddress:r.collateralToken},{amount:ee,spenderAddress:r.negRiskCollateralAdapter,tokenAddress:r.collateralToken},{amount:ee,spenderAddress:r.protocolV2Router,tokenAddress:r.collateralToken},{amount:ee,spenderAddress:r.exchangeV3,tokenAddress:r.collateralToken},{amount:ee,spenderAddress:r.perpsDepositContract,tokenAddress:r.collateralToken}],erc1155:[{operatorAddress:r.standardExchange,tokenAddress:r.conditionalTokens},{operatorAddress:r.negRiskExchange,tokenAddress:r.conditionalTokens},{operatorAddress:r.collateralAdapter,tokenAddress:r.conditionalTokens},{operatorAddress:r.negRiskCollateralAdapter,tokenAddress:r.conditionalTokens},{operatorAddress:r.autoRedeemOperator,tokenAddress:r.conditionalTokens},{operatorAddress:r.protocolV2Router,tokenAddress:r.positionManager},{operatorAddress:r.exchangeV3,tokenAddress:r.positionManager},{operatorAddress:r.autoRedeemOperator,tokenAddress:r.positionManager}]}}function dn(e){return {kind:"sendErc20ApprovalTransaction",request:e}}function un(e){return {kind:"sendErc1155ApprovalForAllTransaction",request:e}}var XE=m(g$1,f$1,c,b);async function Ac(e,r){return unwrap(e.clob.post("/auth/api-key",{headers:yn(r)}).andThen(f(ApiKeyCredsSchema)))}var eS=m(g$1,f$1,c,b);async function Oc(e,r){return unwrap(e.clob.get("/auth/derive-api-key",{headers:yn(r)}).andThen(f(ApiKeyCredsSchema)))}var rS=m(g$1,f$1,c,b);async function tS(e,r){try{return await Ac(e,r)}catch(t){if(!(t instanceof f$1)||t.status!==400)throw t}return Oc(e,r)}var oS=m(g$1,f$1,l$1,c,b);async function nS(e){return (await unwrap(e.secureClob.get("/auth/api-keys").andThen(f(ApiKeysResponseSchema)))).apiKeys}var sS=m(g$1,f$1,l$1,c,b);async function aS(e){await unwrap(e.secureClob.del("/auth/api-key").andThen(f(z.literal("OK"))));}var iS=m(g$1,f$1,l$1,c,b);async function pS(e){return unwrap(e.secureClob.post("/auth/builder-api-key").andThen(f(BuilderApiKeyCredsSchema)))}var cS=m(g$1,f$1,l$1,c,b);async function dS(e){return unwrap(e.secureClob.get("/auth/builder-api-key").andThen(f(BuilderApiKeysResponseSchema)))}var uS=m(g$1,f$1,l$1,c,b);async function lS(e){await unwrap(e.clob.del("/auth/builder-api-key").andThen(f(z.literal("OK"))));}function yn(e){return {POLY_ADDRESS:e.address,POLY_NONCE:`${e.nonce}`,POLY_SIGNATURE:e.signature,POLY_TIMESTAMP:`${e.timestamp}`}}var Bc=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()}),TS=m(g$1,f$1,c,b,a);function xS(e,r){let{cursor:t,...o}=l(r,Bc);return x(n=>e.clob.get("/builder/trades",{params:g({...o,nextCursor:n},E({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)})),t)}var nd=z.object({tokenId:z.string()}),MS=m(g$1,f$1,c,b,a);async function FS(e,r){let t=l(r,nd);return (await unwrap(e.clob.get("/midpoint",{params:g(t,E())}).andThen(f(MidpointSchema)))).mid}var sd=z.array(z.object({tokenId:z.string()})).min(1),BS=m(g$1,f$1,c,b,a);async function US(e,r){let t=l(r,sd);return unwrap(e.clob.post("midpoints",{json:xr(t)}).andThen(f(MidpointsSchema)))}var ad=z.object({tokenId:z.string()}),DS=m(g$1,f$1,c,b,a);async function ze(e,r){let t=l(r,ad);return (await unwrap(e.clob.get("/tick-size",{params:g(t,E())}).andThen(f(FetchTickSizeResponseSchema)))).minimumTickSize}var id=z.object({tokenId:z.string()}),zS=m(g$1,f$1,c,b,a);async function We(e,r){let t=l(r,id);return (await unwrap(e.clob.get("/neg-risk",{params:g(t,E())}).andThen(f(FetchNegRiskResponseSchema)))).negRisk}var pd=z.object({tokenId:TokenIdSchema}),WS=m(g$1,f$1,c,b,a);async function Sn(e,r){let t=l(r,pd);return unwrap(e.clob.get(`/markets-by-token/${t.tokenId}`).andThen(f(ResolveConditionByTokenResponseSchema)))}var cd=z.object({conditionId:CtfConditionIdSchema}),jS=m(g$1,f$1,c,b,a);async function hn(e,r){let t=l(r,cd);return unwrap(e.clob.get(`/clob-markets/${t.conditionId}`).andThen(f(FetchMarketInfoResponseSchema)))}var dd=z.object({builderCode:BuilderCodeSchema}),HS=m(g$1,f$1,c,b,a);async function Tn(e,r){let t=l(r,dd);return unwrap(e.clob.get(`/fees/builder-fees/${t.builderCode}`).andThen(f(FetchBuilderFeeRatesResponseSchema)).mapErr(o=>o instanceof f$1&&o.status===404?new a(`Unknown builder code: ${t.builderCode}`,{cause:o}):o))}var ud=z.object({tokenId:z.string(),side:OrderSideSchema}),_S=m(g$1,f$1,c,b,a);async function NS(e,r){let t=l(r,ud);return (await unwrap(e.clob.get("/price",{params:g(t,E())}).andThen(f(PriceSchema)))).price}var ld=z.array(z.object({tokenId:z.string(),side:OrderSideSchema})).min(1),GS=m(g$1,f$1,c,b,a);async function KS(e,r){let t=l(r,ld);return unwrap(e.clob.post("prices",{json:Td(t)}).andThen(f(PricesSchema)))}var md=z.object({tokenId:z.string()}),$S=m(g$1,f$1,c,b,a);async function xn(e,r){let t=l(r,md);return unwrap(e.clob.get("/book",{params:g(t,E())}).andThen(f(FetchOrderBookResponseSchema)))}var yd=z.array(z.object({tokenId:z.string()})).min(1),VS=m(g$1,f$1,c,b,a);async function ZS(e,r){let t=l(r,yd);return unwrap(e.clob.post("books",{json:xr(t)}).andThen(f(OrderBooksSchema)))}var fd=z.object({tokenId:z.string()}),YS=m(g$1,f$1,c,b,a);async function JS(e,r){let t=l(r,fd);return (await unwrap(e.clob.get("/spread",{params:g(t,E())}).andThen(f(SpreadSchema)))).spread}var Pd=z.array(z.object({tokenId:z.string()})).min(1),QS=m(g$1,f$1,c,b,a);async function XS(e,r){let t=l(r,Pd);return unwrap(e.clob.post("spreads",{json:xr(t)}).andThen(f(SpreadsSchema)))}var gd=z.object({tokenId:z.string()}),eh=m(g$1,f$1,c,b,a);async function rh(e,r){let t=l(r,gd);return unwrap(e.clob.get("/last-trade-price",{params:g(t,E())}).andThen(f(LastTradePriceSchema)))}var Rd=z.array(z.object({tokenId:z.string()})).min(1),th=m(g$1,f$1,c,b,a);async function oh(e,r){let t=l(r,Rd);return unwrap(e.clob.post("last-trades-prices",{json:xr(t)}).andThen(f(LastTradePricesSchema)))}var Ed=z.object({tokenId:z.string(),startTs:z.number().int().optional(),endTs:z.number().int().optional(),fidelity:z.number().int().positive().optional(),interval:PriceHistoryIntervalSchema.optional()}),nh=m(g$1,f$1,c,b,a);async function sh(e,r){let t=l(r,Ed);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 Sd=z.object({cursor:PaginationCursorSchema.optional(),sponsored:z.boolean().optional()}).default({}),ah=m(g$1,f$1,c,b,a);function ih(e,r={}){let{cursor:t,...o}=l(r,Sd);return x(n=>e.clob.get("/rewards/markets/current",{params:g({...o,nextCursor:n},E())}).andThen(f(PaginatedCurrentRewardsSchema)).map(s=>({items:s.data,hasMore:s.nextCursor!==END_CURSOR,nextCursor:s.nextCursor===END_CURSOR?void 0:toPaginationCursor(s.nextCursor)})),t)}var hd=z.object({conditionId:CtfConditionIdSchema,cursor:PaginationCursorSchema.optional(),sponsored:z.boolean().optional()}),ph=m(g$1,f$1,c,b,a);function ch(e,r){let{cursor:t,...o}=l(r,hd);return x(n=>e.clob.get(`rewards/markets/${o.conditionId}`,{params:g({nextCursor:n,sponsored:o.sponsored},E())}).andThen(f(PaginatedMarketRewardsSchema)).map(s=>({items:s.data,hasMore:s.nextCursor!==END_CURSOR,nextCursor:s.nextCursor===END_CURSOR?void 0:toPaginationCursor(s.nextCursor)})),t)}function xr(e){return e.map(({tokenId:r})=>({token_id:r}))}function Td(e){return e.map(({tokenId:r,side:t})=>({token_id:r,side:t}))}var In=2*6e4,hh=m(g$1,f$1,c,b);async function Th(e){return qn(e),unwrap(e.combos.post("/v1/collateral-return/plan",{json:{wallet:e.account.wallet},timeout:In}).andThen(f(CollateralReturnPlanResponseSchema)))}var Ad=z.object({plan:CollateralReturnPlanSchema}),Cn=10,lt="Collateral return",xh=m(f$1,c,b,a);async function Od(e,r){let{plan:t}=l(r,Ad);if(invariant(e.supportsGasless,"Collateral return execution requires a Relayer API Key or Builder API Key in the client configuration."),qn(e),!isSameEvmAddress(t.wallet,e.account.wallet))throw new a("The collateral return plan was created for a different wallet than the authenticated account.");if(t.chainId!==e.environment.chainId)throw new a(`The collateral return plan was created for chain ${t.chainId}, but the client is configured for chain ${e.environment.chainId}.`);return async function*(){let o=[{data:t.routerCall.data,to:t.routerCall.to,value:0n}];for(let n=0;n<=Cn;n+=1)try{let s=yield*wd(e,o);try{return await bn(e,t.planHash,s)}catch(a){let y=at(a);if(y===void 0||s.type!==RelayerTransactionType.WALLET)throw a;let P=yield*pt(e,s,o,y);return await bn(e,t.planHash,P)}}catch(s){if(!dt(s)||n===Cn)throw s;await delay(e.environment.relayerPollFrequencyMs);}invariant(false,"Expected collateral return submit retry loop to return");}.call(null)}var Ch=m(j,g$1,f$1,l$1,c,b,a);function bh(e,r){return Od(e,r).then(H(e.signer))}function qn(e){invariant(e.account.walletType===WalletType.DEPOSIT_WALLET||e.account.walletType===WalletType.GNOSIS_SAFE||e.account.walletType===WalletType.POLY_PROXY,"Collateral return supports Deposit Wallet, Safe Wallet, and Proxy Wallet accounts");}function wd(e,r){switch(e.account.walletType){case WalletType.GNOSIS_SAFE:return ct(e,r,lt);case WalletType.POLY_PROXY:return st(e,r,lt);default:return it(e,r,lt)}}async function bn(e,r,t){let o=await unwrap(e.combos.post("/v1/collateral-return/submit",{json:{envelope:t,plan_hash:r},timeout:In}).andThen(f(RelayerExecuteResponseSchema)));return new rr(e,o)}var Dd=z.object({ascending:z.boolean().optional(),cursor:PaginationCursorSchema.optional(),pageSize:w.max(100).default(20),getPositions:z.boolean().optional(),holdersOnly:z.boolean().optional(),order:z.string().optional(),parentEntityId:z.union([EventIdSchema,SeriesIdSchema]),parentEntityType:CommentParentEntityTypeSchema}),zd=z.object({getPositions:z.boolean().optional(),id:CommentIdSchema}),Wd=z.object({address:z.string(),ascending:z.boolean().optional(),cursor:PaginationCursorSchema.optional(),order:z.string().optional(),pageSize:w.max(100).default(20)}),Dh=m(g$1,f$1,c,b,a);function zh(e,r){let{cursor:t,pageSize:o,...n}=l(r,Dd);return x(s=>{let a=D(s,o);return e.gamma.get("/comments",{params:g({ascending:n.ascending,getPositions:n.getPositions,holdersOnly:n.holdersOnly,limit:a.pageSize,offset:a.offset,order:n.order,parentEntityId:n.parentEntityId,parentEntityType:n.parentEntityType},E())}).andThen(f(ListCommentsResponseSchema)).map(y=>{let P=y.length>=a.pageSize;return {items:y,hasMore:P,nextCursor:P?B({offset:a.offset+a.pageSize,pageSize:a.pageSize}):void 0}})},t)}var Wh=m(g$1,f$1,c,b,a);async function jh(e,r){let t=l(r,zd);return unwrap(e.gamma.get(`comments/${t.id}`,{params:g({getPositions:t.getPositions},E())}).andThen(f(ListCommentsResponseSchema)))}var Hh=m(g$1,f$1,c,b,a);function _h(e,r){let{address:t,cursor:o,pageSize:n,...s}=l(r,Wd);return x(a=>{let y=D(a,n);return e.gamma.get(`comments/user_address/${t}`,{params:g({ascending:s.ascending,limit:y.pageSize,offset:y.offset,order:s.order},E())}).andThen(f(ListCommentsResponseSchema)).map(P=>{let A=P.length>=y.pageSize;return {items:P,hasMore:A,nextCursor:A?B({offset:y.offset+y.pageSize,pageSize:y.pageSize}):void 0}})},o)}function Cr(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 Kd=z.object({ascending:z.boolean().optional(),closed:z.boolean().default(false),cursor:PaginationCursorSchema.optional(),pageSize:w.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()}),$d=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()})]),Vd=z.object({id:z.string()}),Zd=z.object({id:z.string()}),nT=m(g$1,f$1,c,b,a);function sT(e,r={}){let t=l(r,Kd);return x(o=>e.gamma.get("/events/keyset",{params:Yd({...t,cursor:o??t.cursor})}).andThen(f(ListEventsKeysetResponseSchema)).map(n=>({items:n.items,hasMore:n.nextCursor!==void 0,nextCursor:n.nextCursor})),t.cursor)}var aT=m(g$1,f$1,c,b,a);async function iT(e,r){let t=l(r,$d);if("id"in t)return unwrap(e.gamma.get(`events/${t.id}`,{params:Jd(t)}).andThen(f(EventSchema)));let o="url"in t?Cr(t.url,"event"):t.slug;return unwrap(e.gamma.get(`events/slug/${o}`,{params:Qd(t)}).andThen(f(EventSchema)))}var pT=m(g$1,f$1,c,b,a);async function cT(e,r){let t=l(r,Vd);return unwrap(e.gamma.get(`events/${t.id}/tags`).andThen(f(FetchEventTagsResponseSchema)))}var dT=m(g$1,f$1,c,b,a);async function uT(e,r){let t=l(r,Zd);return unwrap(e.data.get("/live-volume",{params:N(t)}).andThen(f(FetchEventLiveVolumeResponseSchema)))}function Yd(e){return g(e,E({cursor:"after_cursor",excludeTagIds:"exclude_tag_id",gameIds:"game_id",ids:"id",pageSize:"limit",seriesIds:"series_id",tagIds:"tag_id"}))}function Jd(e){return g({includeBestLines:e.includeBestLines,includeChat:e.includeChat,includeTemplate:e.includeTemplate,locale:e.locale},E())}function Qd(e){return g({includeBestLines:e.includeBestLines,includeChat:e.includeChat,includeTemplate:e.includeTemplate,locale:e.locale},E())}var su=z.object({cursor:PaginationCursorSchema.optional(),pageSize:w.max(50).default(20),timePeriod:TimePeriodSchema.optional()}),au=z.object({timePeriod:TimePeriodSchema.optional()}),iu=z.object({category:LeaderboardCategorySchema.optional(),cursor:PaginationCursorSchema.optional(),pageSize:w.max(50).default(20),timePeriod:TimePeriodSchema.optional(),orderBy:LeaderboardOrderBySchema.optional(),user:z.string().optional(),userName:z.string().optional()}),TT=m(g$1,f$1,c,b,a);function xT(e,r={}){let{cursor:t,pageSize:o,...n}=l(r,su);return x(s=>{let a=D(s,o);return e.data.get("/v1/builders/leaderboard",{params:N({...n,limit:a.pageSize,offset:a.offset})}).andThen(f(ListBuilderLeaderboardResponseSchema)).map(y=>{let P=y.length>=a.pageSize;return {items:y,hasMore:P,nextCursor:P?B({offset:a.offset+a.pageSize,pageSize:a.pageSize}):void 0}})},t)}var CT=m(g$1,f$1,c,b,a);async function bT(e,r={}){let t=l(r,au);return unwrap(e.data.get("/v1/builders/volume",{params:N(t)}).andThen(f(ListBuilderVolumeResponseSchema)))}var kT=m(g$1,f$1,c,b,a);function IT(e,r={}){let{cursor:t,pageSize:o,...n}=l(r,iu);return x(s=>{let a=D(s,o);return e.data.get("/v1/leaderboard",{params:N({...n,limit:a.pageSize,offset:a.offset})}).andThen(f(ListTraderLeaderboardResponseSchema)).map(y=>{let P=y.length>=a.pageSize;return {items:y,hasMore:P,nextCursor:P?B({offset:a.offset+a.pageSize,pageSize:a.pageSize}):void 0}})},t)}var du=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:w.max(100).default(20)}),UT=m(g$1,f$1,c,b,a);function DT(e,r={}){let{cursor:t,pageSize:o,...n}=l(r,du);return x(s=>{let a=D(s,o);return e.gamma.get("/market-clarifications",{params:g({...n,limit:a.pageSize,offset:a.offset},E())}).andThen(f(ListMarketClarificationsResponseSchema)).map(y=>{let P=y.length>=a.pageSize;return {items:y,hasMore:P,nextCursor:P?B({offset:a.offset+a.pageSize,pageSize:a.pageSize}):void 0}})},t)}var Ru=z.object({ascending:z.boolean().optional(),closed:z.boolean().optional(),clobTokenIds:z.array(z.string()).optional(),cursor:PaginationCursorSchema.optional(),pageSize:w.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()}),Eu=z.object({id:z.string(),includeTag:z.boolean().optional(),locale:z.string().optional()}),Su=z.object({slug:z.string(),includeTag:z.boolean().optional(),locale:z.string().optional()}),hu=z.object({url:z.string(),includeTag:z.boolean().optional(),locale:z.string().optional()}),Tu=z.union([Eu,Su,hu]),xu=z.object({id:z.string()}),Cu=z.object({limit:z.number().int().optional(),market:z.array(z.string()),minBalance:z.number().int().optional()}),bu=z.object({market:z.array(z.string()).optional()}),ku=z.enum(["OPEN","CLOSED","ALL"]),Iu=z.enum(["TOKENS","CASH_PNL","REALIZED_PNL","TOTAL_PNL"]),qu=z.enum(["ASC","DESC"]),vu=z.object({cursor:PaginationCursorSchema.optional(),market:z.string(),pageSize:w.max(500).default(20),user:z.string().optional(),status:ku.optional(),sortBy:Iu.optional(),sortDirection:qu.optional()}),QT=m(g$1,f$1,c,b,a);function Bn(e,r={}){let t=l(r,Ru);return x(o=>e.gamma.get("/markets/keyset",{params:Ou({...t,cursor:o??t.cursor})}).andThen(f(ListMarketsKeysetResponseSchema)).map(n=>({items:n.items,hasMore:n.nextCursor!==void 0,nextCursor:n.nextCursor})),t.cursor)}var Au=z.object({cursor:PaginationCursorSchema.optional(),pageSize:w.max(100).optional(),exclude:z.array(CtfConditionIdSchema).optional()}),XT=m(g$1,f$1,c,b,a);function ex(e,r={}){let t=l(r,Au);return x(o=>e.rfq.get("/v1/rfq/combo-markets",{params:wu({...t,cursor:o??t.cursor})}).andThen(f(ListComboMarketsResponseSchema)).map(n=>({items:n.markets,hasMore:n.nextCursor!==void 0,nextCursor:n.nextCursor})),t.cursor)}var rx=m(g$1,f$1,c,b,a);async function tx(e,r){let t=l(r,Tu);return "id"in t?Lu(e,t):"url"in t?Ln(e,{includeTag:t.includeTag,locale:t.locale,slug:Cr(t.url,"market")}):Ln(e,t)}var ox=m(g$1,f$1,c,b,a);async function nx(e,r){let t=l(r,xu);return unwrap(e.gamma.get(`markets/${t.id}/tags`).andThen(f(FetchMarketTagsResponseSchema)))}var sx=m(g$1,f$1,c,b,a);async function ax(e,r){let t=l(r,Cu);return unwrap(e.data.get("/holders",{params:N(t)}).andThen(f(ListMarketHoldersResponseSchema)))}var ix=m(g$1,f$1,c,b,a);async function px(e,r={}){let t=l(r,bu);return unwrap(e.data.get("/oi",{params:N(t)}).andThen(f(ListOpenInterestResponseSchema)))}var cx=m(g$1,f$1,c,b,a);function dx(e,r){let{cursor:t,pageSize:o,...n}=l(r,vu);return x(s=>{let a=D(s,o);return e.data.get("/v1/market-positions",{params:N({...n,limit:a.pageSize,offset:a.offset})}).andThen(f(ListMarketPositionsResponseSchema)).map(y=>{let P=y.length>=a.pageSize;return {items:y,hasMore:P,nextCursor:P?B({offset:a.offset+a.pageSize,pageSize:a.pageSize}):void 0}})},t)}function Ou(e){return g(e,E({cursor:"after_cursor",ids:"id",marketMakerAddresses:"market_maker_address",pageSize:"limit"}))}function wu(e){return g({cursor:e.cursor,exclude:e.exclude?.join(","),pageSize:e.pageSize},{cursor:"cursor",exclude:"exclude",pageSize:"limit"})}async function Ln(e,r){return unwrap(e.gamma.get(`markets/slug/${r.slug}`,{params:g({includeTag:r.includeTag,locale:r.locale},E())}).andThen(f(MarketSchema)))}async function Lu(e,r){return unwrap(e.gamma.get(`markets/${r.id}`,{params:g({includeTag:r.includeTag,locale:r.locale},E())}).andThen(f(MarketSchema)))}var Bu=z.object({orderId:z.string()}),Uu=z.object({orderIds:z.array(z.string()).min(1).max(3e3)}),Du=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"]}),Rx=m(f$1,g$1,l$1,c,b,a);async function Ex(e,r){let t=l(r,Bu);return Ir(e,"/order",{orderID:t.orderId})}var Sx=m(f$1,g$1,l$1,c,b,a);async function hx(e,r){let t=l(r,Uu);return Ir(e,"/orders",t.orderIds)}var Tx=m(f$1,g$1,l$1,c,b);async function xx(e){return Ir(e,"/cancel-all")}var Cx=m(f$1,g$1,l$1,c,b,a);async function bx(e,r){let t=l(r,Du);return Ir(e,"/cancel-market-orders",{asset_id:t.tokenId,market:t.market})}async function Ir(e,r,t){return unwrap(e.secureClob.del(r,{json:t}).andThen(f(CancelOrdersResponseSchema)))}var Dn=z.object({tokenId:z.string(),orderType:z.union([z.literal(OrderType.FAK),z.literal(OrderType.FOK)]).default(OrderType.FOK)}),Wu=z.discriminatedUnion("side",[Dn.extend({side:z.literal(OrderSide.BUY),amount:PositiveDecimalNumberSchema}),Dn.extend({side:z.literal(OrderSide.SELL),shares:PositiveDecimalNumberSchema})]),Lx=m(k,g$1,f$1,c,b,a);async function Mx(e,r){let t=l(r,Wu),o=await ze(e,{tokenId:t.tokenId}),n=t.side===OrderSide.BUY?t.amount:t.shares;return gt(e,{amount:n,orderType:t.orderType,side:t.side,tickSize:o,tokenId:t.tokenId})}async function gt(e,r){let t=await xn(e,{tokenId:r.tokenId}),o=r.side===OrderSide.BUY?Hu(t.asks,r.amount,r.orderType):_u(t.bids,r.amount,r.orderType);return invariant(ju(o,r.tickSize),`Resolved market price fell outside the valid range for tick size ${r.tickSize}.`),o}function ju(e,r){return e>=r&&e<=1-r}function Hu(e,r,t){if(e.length===0)throw new k("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 k("Insufficient liquidity for full fill.");let n=e[0];return Number.parseFloat(n.price)}function _u(e,r,t){if(e.length===0)throw new k("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 k("Insufficient liquidity for full fill.");let n=e[0];return Number.parseFloat(n.price)}var $u=z.array(z.custom()).min(1).max(15),_x=m(g$1,f$1,l$1,c,b),Nx=m(g$1,f$1,l$1,c,b,a);function vr(e){return async function(t){let o=Hn(e,t);return unwrap(e.secureClob.post("/order",{json:o}).andThen(f(OrderResponseSchema)))}}function Gx(e){return async function(t){let n=l(t,$u).map(s=>Hn(e,s));return unwrap(e.secureClob.post("/orders",{json:n}).andThen(f(OrderResponsesSchema)))}}function Hn(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 me(e){return BigInt(Math.round(e*10**6))}function ye(e,r){return V(e)<=r?e:Math.floor(e*10**r)/10**r}function be(e,r){return V(e)<=r?e:Math.ceil(e*10**r)/10**r}function _n(e,r){return V(e)<=r?e:Math.round(e*10**r)/10**r}function Nn(e,r){let t=V(r);if(V(e)>t)return false;let o=10**t;return Math.round(e*o)%Math.round(r*o)===0}function V(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)}function Ar(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 ar(e,r,t){let o=V(r);if(e<r||e>1-r)throw new a(`${t} must be between ${r} and ${1-r} for tick size ${r}.`);if(V(e)>o)throw new a(`${t} must conform to tick size ${r} with at most ${o} decimal places.`);if(!Nn(e,r))throw new a(`${t} ${e} must be a multiple of tick size ${r}.`);return e}function He(e,r){return r?e.environment.contracts.negRiskExchange:e.environment.contracts.standardExchange}var Xu=180,$n=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)+Xu;e.expiration<t&&r.addIssue({code:"custom",message:"Expiration must be at least 3 minutes in the future.",path:["expiration"]});}});async function Vn(e,r){let t=await el(e,{price:r.price,tokenId:r.tokenId}),o=rl({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 el(e,r){let t=e.account,o=await ze(e,{tokenId:r.tokenId}),n=await We(e,{tokenId:r.tokenId});return {exchangeAddress:He(e,n),funderAddress:t.wallet,negRisk:n,price:ar(r.price,o,"Price"),signerAddress:t.signer,tickSize:o}}function rl(e){let r=Ar(e.tickSize),t=_n(e.price,r.price);if(e.side===OrderSide.BUY){let s=ye(e.size,r.size),a=s*t;return V(a)>r.amount&&(a=be(a,r.amount+4),V(a)>r.amount&&(a=ye(a,r.amount))),{offeredAmount:me(a),requestedAmount:me(s)}}let o=ye(e.size,r.size),n=o*t;return V(n)>r.amount&&(n=be(n,r.amount+4),V(n)>r.amount&&(n=ye(n,r.amount))),{offeredAmount:me(o),requestedAmount:me(n)}}var Zn=z.object({tokenId:TokenIdSchema,builderCode:BuilderCodeSchema.optional(),orderType:z.union([z.literal(OrderType.FAK),z.literal(OrderType.FOK)]).default(OrderType.FAK)}),Yn=z.discriminatedUnion("side",[Zn.extend({side:z.literal(OrderSide.BUY),amount:PositiveDecimalNumberSchema,maxSpend:PositiveDecimalNumberSchema.optional(),maxPrice:PositiveDecimalNumberSchema.optional()}),Zn.extend({side:z.literal(OrderSide.SELL),shares:PositiveDecimalNumberSchema,minPrice:PositiveDecimalNumberSchema.optional()})]);async function Jn(e,r){let t=await nl(e,r),o=il({amount:t.resolvedAmount,price:t.price,protectPrice:al(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 nl(e,r){let t=e.account,o=await ze(e,{tokenId:r.tokenId}),n=r.side===OrderSide.BUY?r.amount:r.shares,s=await sl(e,r,n,o),a=await We(e,{tokenId:r.tokenId}),y=await pl(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:He(e,a),funderAddress:t.wallet,negRisk:a,price:s,resolvedAmount:y,signerAddress:t.signer,tickSize:o}}async function sl(e,r,t,o){return r.side===OrderSide.BUY&&r.maxPrice!==void 0?ar(r.maxPrice,o,"maxPrice"):r.side===OrderSide.SELL&&r.minPrice!==void 0?ar(r.minPrice,o,"minPrice"):gt(e,{amount:t,orderType:r.orderType,side:r.side,tickSize:o,tokenId:r.tokenId})}function al(e){return e.side===OrderSide.BUY&&e.maxPrice!==void 0||e.side===OrderSide.SELL&&e.minPrice!==void 0}function il(e){let r=Ar(e.tickSize),t=ye(e.price,r.price),o=ye(e.amount,r.size);if(e.side===OrderSide.BUY){let s=o/t;return V(s)>r.amount&&(s=be(s,r.amount+4),V(s)>r.amount&&(s=e.protectPrice?be(s,r.amount):ye(s,r.amount))),{offeredAmount:me(o),requestedAmount:me(s)}}let n=o*t;return V(n)>r.amount&&(n=be(n,r.amount+4),V(n)>r.amount&&(n=e.protectPrice?be(n,r.amount):ye(n,r.amount))),{offeredAmount:me(o),requestedAmount:me(n)}}async function pl(e,r){if(r.side!==OrderSide.BUY||r.maxSpend===void 0)return r.amount;let[t,o]=await Promise.all([cl(e,r.tokenId),dl(e,r.builderCode)]);return ul({amount:r.amount,builderTakerFeeRate:o,platformFeeExponent:t.exponent,platformFeeRate:t.rate,maxSpend:r.maxSpend,price:r.price})}async function cl(e,r){let t=await Sn(e,{tokenId:r});return (await hn(e,{conditionId:t})).feeInfo}async function dl(e,r){return r===void 0?0:(await Tn(e,{builderCode:r})).taker}function ul(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 Qn="0x0000000000000000000000000000000000000000000000000000000000000000";function St(e,r){let t=ho(r);return {builder:e.builderCode??Qn,chainId:e.chainId,exchangeAddress:e.exchangeAddress,expiration:e.expiration,maker:t.maker,makerAmount:e.offeredAmount.toString(),metadata:Qn,orderType:e.orderType,salt:ll().toString(),side:e.side,signatureType:t.signatureType,signer:t.signer,takerAmount:e.requestedAmount.toString(),timestamp:Date.now().toString(),tokenId:e.tokenId}}function ht(e,r){let{chainId:t,exchangeAddress:o,...n}=e;return {...n,signature:r}}function ll(){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 rs="Polymarket CTF Exchange",fl="DepositWallet",Pl="1",Tt="0x0000000000000000000000000000000000000000000000000000000000000000",xt="Order(uint256 salt,address maker,address signer,uint256 tokenId,uint256 makerAmount,uint256 takerAmount,uint8 side,uint8 signatureType,uint256 timestamp,bytes32 metadata,bytes32 builder)",gl=Hash.keccak256(Bytes.fromString(xt),{as:"Hex"}),Rl=Hash.keccak256(Bytes.fromString("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),{as:"Hex"}),El=Hash.keccak256(Bytes.fromString(rs),{as:"Hex"}),Sl=[{name:"name",type:"string"},{name:"version",type:"string"},{name:"chainId",type:"uint256"},{name:"verifyingContract",type:"address"}],ts=[{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"}],hl=[{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 os(e){let r=Tl(e.domain,e.order);return e.order.signatureType!==SignatureType.POLY_1271?r:{domain:as(e.domain),message:{chainId:e.domain.chainId,contents:r.message,name:fl,salt:Tt,verifyingContract:e.order.signer,version:Pl},primaryType:"TypedDataSign",types:{Order:ts,TypedDataSign:hl}}}function ns(e){if(e.order.signatureType!==SignatureType.POLY_1271)return e.signature;let r=Bytes.toHex(Bytes.fromString(xt)),t=xt.length.toString(16).padStart(4,"0");return expectErc1271Signature(`0x${e.signature.slice(2)}${xl(e.domain).slice(2)}${Cl(e.order).slice(2)}${r.slice(2)}${t}`)}function ss(e){return {builder:e.builder??Tt,maker:e.maker,makerAmount:BigInt(e.makerAmount),metadata:e.metadata??Tt,salt:BigInt(e.salt),side:kl(e.side),signatureType:e.signatureType,signer:e.signer,takerAmount:BigInt(e.takerAmount),timestamp:BigInt(e.timestamp),tokenId:BigInt(e.tokenId)}}function Tl(e,r){return {domain:as(e),message:ss(r),primaryType:"Order",types:{EIP712Domain:Sl,Order:ts}}}function as(e){return {chainId:e.chainId,name:rs,verifyingContract:e.exchange,version:e.protocolVersion}}function xl(e){return expectHexString(Hash.keccak256(AbiParameters.encode([{type:"bytes32"},{type:"bytes32"},{type:"bytes32"},{type:"uint256"},{type:"address"}],[Rl,El,bl(e.protocolVersion),BigInt(e.chainId),e.exchange]),{as:"Hex"}))}function Cl(e){let r=ss(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"}],[gl,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 bl(e){return expectHexString(Hash.keccak256(Bytes.fromString(e),{as:"Hex"}))}function kl(e){return e===0||e===1?e:e===OrderSide.BUY?0:1}function bt(e){return os({domain:is(e),order:e})}function kt(e,r){return ns({domain:is(e),order:e,signature:r})}function is(e){return {chainId:e.chainId,exchange:e.exchangeAddress,protocolVersion:"2"}}function It(e){return {kind:"signOrder",payload:e}}var Il=m(k,g$1,f$1,l$1,c,b,a);async function qt(e,r){let t=l(r,Yn);return async function*(){let o=await Jn(e,t),n=St(o,e.account),s=expectEvmSignature(yield It(bt(n)));return ht(n,kt(n,s))}.call(null)}var ql=m(g$1,f$1,l$1,c,b,a);async function vt(e,r){let t=l(r,$n);return async function*(){let o=await Vn(e,t),n=St(o,e.account),s=expectEvmSignature(yield It(bt(n))),a=ht(n,kt(n,s));return t.postOnly===true?{...a,postOnly:true}:a}.call(null)}var OC=Il;async function wC(e,r){return cs(e,qt(e,r))}var LC=ql;async function MC(e,r){return cs(e,vt(e,r))}async function cs(e,r){let t=await r;return async function*(){let o=yield*t;return vr(e)(o)}.call(null)}var Ol=250,wl=3e4,Ll={timeoutMs:z.number().int().positive().optional()},Ml=z.object(Ll).default({}),HC=m(g$1,f$1,l$1,h,i,c,b,a);function Fl(e){return e.status===TradeStatus.Confirmed||e.status===TradeStatus.Failed}function ds(e){return e.status===TradeStatus.Failed}async function _C(e,r,t){let{timeoutMs:o=wl}=l(t,Ml),n=[...new Set(r.tradeIds)];if(n.length===0)return [...r.transactionsHashes];let s=new Map,a=Date.now()+o;for(;s.size<n.length;){let P=n.filter(q=>!s.has(q)),A=await Promise.all(P.map(q=>Io(e,{id:q}).firstPage()));for(let q of A)for(let j of q.items)n.includes(j.id)&&Fl(j)&&s.set(j.id,j);if(s.size===n.length)break;if(Date.now()>=a){let q=n.filter(j=>!s.has(j));throw new h(`Timed out waiting for trades to settle: ${q.join(", ")}`)}await delay(Ol);}let y=[...s.values()];if(y.every(ds))throw new i(`Every fill of order ${r.orderId} failed execution: ${n.join(", ")}`);return [...new Set(y.filter(P=>!ds(P)).map(P=>P.transactionHash))].map(P=>TxHashSchema.parse(P))}async function ys(e,r){let t=r.side===OrderSide.BUY?AssetType.COLLATERAL:AssetType.CONDITIONAL,{allowances:o}=await Vr(e,r.side===OrderSide.BUY?{assetType:t}:{assetType:t,tokenId:r.tokenId});return Ul(o,r.spenderAddress)}function Ul(e,r){return Object.entries(e).find(([o])=>isSameEvmAddress(o,r))?.[1]??0n}var ib=m(j,k,g$1,f$1,l$1,c,b,a);function Dl(e,r){return qt(e,r).then(H(e.signer))}var pb=m(j,k,g$1,f$1,l$1,h,i,c,b,a);function cb(e,r){return Dl(e,r).then(t=>Ps(e,t))}var db=m(j,g$1,f$1,l$1,c,b,a);function zl(e,r){return vt(e,r).then(H(e.signer))}var ub=m(j,g$1,f$1,l$1,h,i,c,b,a);function lb(e,r){return zl(e,r).then(t=>Ps(e,t))}async function Ps(e,r){let t=vr(e);try{return await t(r)}catch(o){if(!jl(o))throw o;let n=await Wl(e,r,t);if(n===void 0)throw o;return n}}async function Wl(e,r,t){return await Hl(e,r)?t(r):void 0}function jl(e){return e instanceof f$1&&e.status===400&&e.message.includes("allowance is not enough")}async function Hl(e,r){let t=await We(e,{tokenId:r.tokenId}),o=He(e,t),n=BigInt(r.makerAmount);return await ys(e,{spenderAddress:o,side:r.side,tokenId:r.tokenId})>=n?false:(await(r.side===OrderSide.BUY?await pn(e,{amount:"max",spenderAddress:o,tokenAddress:e.environment.contracts.collateralToken}):await cn(e,{operatorAddress:o,tokenAddress:e.environment.contracts.conditionalTokens})).wait(),await qo(e,{assetType:r.side===OrderSide.BUY?AssetType.COLLATERAL:AssetType.CONDITIONAL,tokenId:r.side===OrderSide.SELL?r.tokenId:void 0}),true)}function gs(e){let r=TypedData.getSignPayload(wt(e));return expectEvmSignature(Signature.toHex(Secp256k1.sign({payload:r,privateKey:e.privateKey})))}function wt(e){return {domain:{chainId:e.chainId,name:"Polymarket",version:"1"},message:{data:Hash.keccak256(encode(Rs(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 Rs(e){return Array.isArray(e)?e.filter(r=>r!==void 0).map(Rs):e}var Or=class{#e;#r;#t;constructor({root:r,headers:t,resolveHeaders:o}){this.#e=lo.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,...o.timeout!==void 0&&{timeout:o.timeout}})}#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;let o=this.#d(t);if(t.status===429)throw new g$1(`Request to ${t.url} was rate limited`,{retryAfter:o});let n=await this.#m(t);throw new f$1(n,{retryAfter:o,status:t.status})}),t=>t instanceof g$1||t instanceof f$1?t:c.fromError(t))}#d(r){let t=r.headers.get("retry-after");if(!(t===null||!/^\d+$/.test(t)))return Number(t)}async#m(r){let t=r.headers.get("content-type")?.toLowerCase();if(t?.includes("application/json")){let{error:n}=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 Jl=1e4,Ql=3e4,Xl=5e3,em=10*6e4,rm=3e4,tm=25e3,om=65e3,Es=class{#e=0;#r;start(r){this.stop(),this.#e=Date.now(),this.#r=setNonBlockingInterval(()=>{r("PING");},Jl);}handleMessage(r){return r!=="PONG"?false:(this.#e=Date.now(),true)}isStale(r){return r-this.#e>Ql}stop(){this.#r!==void 0&&(clearInterval(this.#r),this.#r=void 0);}},Ss=class{#e=0;#r;start(r){this.stop(),this.#e=Date.now(),this.#r=setNonBlockingInterval(()=>{r("PING");},Xl);}handleMessage(){return this.#e=Date.now(),false}isStale(r){return r-this.#e>em}stop(){this.#r!==void 0&&(clearInterval(this.#r),this.#r=void 0);}},hs=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>rm}},wr=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"}}));},tm);}handleMessage(){return this.#e=Date.now(),false}isStale(r){return r-this.#e>om}stop(){this.#r!==void 0&&(clearInterval(this.#r),this.#r=void 0);}};var am=5e3,im=250,pm=3e4,Lr=class{#e;#r=0;schedule(r){if(this.#e!==void 0||!r.shouldReconnect())return;let t=dm(this.#r,{baseMs:im,maxMs:pm});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);}}},Mr=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 A=String(P.data);if(this.#e?.handleMessage(A))return;let q;try{q=JSON.parse(A);}catch{return}r.onMessage(q);}),s.addEventListener("close",P=>{this.#r===s&&(this.#s(),r.onConnectionLost({code:P.code||1005,reason:P.reason??""}));}),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();},am));}#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 dm(e,r){let t=Math.min(r.baseMs*2**e,r.maxMs);return Math.random()*t}var Fr=1440*60*1e3,ks=90*Fr,ne=z.number().int().nonnegative(),Ft=z.object({start:ne.optional(),end:ne.optional()}),Is=z.object({interval:PerpsPnlIntervalSchema,start:ne,end:ne.optional()}),vm=z.enum(["perpsFundingPayments","perpsDeposits","perpsWithdrawals"]),Am=z.enum(["perpsEquityHistory","perpsPnlHistory"]),Bt=z.object({kind:vm,startTimestamp:ne,endTimestamp:ne,instrumentId:PerpsInstrumentIdSchema.optional(),depositStatus:PerpsDepositStatusSchema.optional(),withdrawalStatus:PerpsWithdrawalStatusSchema.optional(),hash:TxHashSchema.optional(),seenKeys:z.array(z.string())}),qs=z.object({kind:Am,startTimestamp:ne,endTimestamp:ne,interval:PerpsPnlIntervalSchema});async function vs(e){return await unwrap(e.get("/v1/account/balances").andThen(f(FetchPerpsBalancesResponseSchema)))}async function As(e){return await unwrap(e.get("/v1/account/portfolio").andThen(f(FetchPerpsPortfolioResponseSchema)))}async function Os(e){return await unwrap(e.get("/v1/account/stats").andThen(f(FetchPerpsAccountStatsResponseSchema)))}var Om=z.object({instrumentId:PerpsInstrumentIdSchema.optional()}).default({});async function ws(e,r){let t=l(r,Om);return await unwrap(e.get("/v1/account/config",{params:ce(t)}).andThen(f(FetchPerpsAccountConfigResponseSchema)))}var wm=z.object({instrumentId:PerpsInstrumentIdSchema.optional()}).default({});async function Ls(e,r){let t=l(r,wm);return await unwrap(e.get("/v1/account/open-orders",{params:ce(t)}).andThen(f(FetchPerpsOpenOrdersResponseSchema)))}var Lm=z.object({orderId:PerpsOrderIdSchema.optional(),clientOrderId:PerpsClientOrderIdSchema.optional(),instrumentId:PerpsInstrumentIdSchema.optional(),start:ne.optional(),end:ne.optional()}).default({}),Mm=Lm.transform(({end:e,start:r,...t})=>({...t,endTimestamp:e,startTimestamp:r}));async function Ms(e,r){let t=l(r,Mm);return await unwrap(e.get("/v1/account/orders",{params:ce(t)}).andThen(f(FetchPerpsOrdersResponseSchema)))}var Fm=z.object({start:ne.optional(),end:ne.optional(),sort:PerpsSortDirectionSchema.optional(),cursor:PaginationCursorSchema.optional()});function Fs(e,r={}){let t=l(r,Fm);return x(o=>e.get("/v1/account/fills",{params:ce({startTimestamp:t.start,endTimestamp:t.end,sort:t.sort,cursor:o??t.cursor})}).andThen(f(ListPerpsFillsResponseSchema)).map(n=>{let s=n.data.at(-1);return !n.more||s===void 0?{items:n.data,hasMore:false}:{items:n.data,hasMore:true,nextCursor:toPaginationCursor(String(s.tradeId))}}),t.cursor)}var Bm=Ft.extend({cursor:PaginationCursorSchema.optional(),instrumentId:PerpsInstrumentIdSchema.optional()}),Um=z.object({cursor:PaginationCursorSchema}),Dm=z.union([Bm.transform(({cursor:e,...r})=>({cursor:e,params:Ut(r,Fr)})),Um.transform(({cursor:e})=>({cursor:e,params:void 0}))]);function Bs(e,r={}){let{cursor:t,params:o}=l(r,Dm);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,Bt);let{kind:a,seenKeys:y,...P}=s,A=new Set(s.seenKeys);return e.get("/v1/account/funding",{params:ce(P)}).andThen(f(ListPerpsFundingPaymentsResponseSchema)).map(q=>{let j=q.data.filter(U=>!A.has(`${U.instrumentId}:${U.timestamp}:${U.funding}`));return Dt({getKey:U=>`${U.instrumentId}:${U.timestamp}:${U.funding}`,getTimestamp:U=>U.timestamp,items:j,responseData:q.data,responseMore:q.more,state:s})})},t)}var zm=Ft.extend({cursor:PaginationCursorSchema.optional(),depositStatus:PerpsDepositStatusSchema.optional(),hash:TxHashSchema.optional()}),Wm=z.object({cursor:PaginationCursorSchema}),jm=z.union([zm.transform(({cursor:e,...r})=>({cursor:e,params:Ut(r,ks)})),Wm.transform(({cursor:e})=>({cursor:e,params:void 0}))]);function Us(e,r={}){let{cursor:t,params:o}=l(r,jm);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,Bt);let{kind:a,seenKeys:y,...P}=s,A=new Set(s.seenKeys);return e.get("/v1/account/deposits",{params:ce(P)}).andThen(f(ListPerpsDepositsResponseSchema)).map(q=>{let j=q.data.filter(U=>!A.has(U.hash));return Dt({getKey:U=>U.hash,getTimestamp:sy,items:j,responseData:q.data,responseMore:q.more,state:s})})},t)}var Hm=Ft.extend({cursor:PaginationCursorSchema.optional(),withdrawalStatus:PerpsWithdrawalStatusSchema.optional(),hash:TxHashSchema.optional()}),_m=z.object({cursor:PaginationCursorSchema}),Nm=z.union([Hm.transform(({cursor:e,...r})=>({cursor:e,params:Ut(r,ks)})),_m.transform(({cursor:e})=>({cursor:e,params:void 0}))]);function Ds(e,r={}){let{cursor:t,params:o}=l(r,Nm);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,Bt);let{kind:a,seenKeys:y,...P}=s,A=new Set(s.seenKeys);return e.get("/v1/account/withdrawals",{params:ce(P)}).andThen(f(ListPerpsWithdrawalsResponseSchema)).map(q=>{let j=q.data.filter(U=>!A.has(String(U.withdrawalId)));return Dt({getKey:U=>String(U.withdrawalId),getTimestamp:ay,items:j,responseData:q.data,responseMore:q.more,state:s})})},t)}var Gm=Is.extend({cursor:PaginationCursorSchema.optional()}),Km=z.object({cursor:PaginationCursorSchema}),$m=z.union([Gm.transform(({cursor:e,...r})=>({cursor:e,params:Ns(r)})),Km.transform(({cursor:e})=>({cursor:e,params:void 0}))]);function zs(e,r){let{cursor:t,params:o}=l(r,$m);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,qs);let{kind:a,...y}=s;return e.get("/v1/account/equity",{params:ce(y)}).andThen(f(ListPerpsEquityHistoryResponseSchema)).map(P=>{let A=P.data.at(-1),q=P.more&&A!==void 0&&A.timestamp<s.endTimestamp;return {items:P.data,hasMore:q,nextCursor:q?Br({...s,startTimestamp:A.timestamp+Gs(s.interval)}):void 0}})},t)}var Vm=Is.extend({cursor:PaginationCursorSchema.optional()}),Zm=z.object({cursor:PaginationCursorSchema}),Ym=z.union([Vm.transform(({cursor:e,...r})=>({cursor:e,params:Ns(r)})),Zm.transform(({cursor:e})=>({cursor:e,params:void 0}))]);function Ws(e,r){let{cursor:t,params:o}=l(r,Ym);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,qs);let{kind:a,...y}=s;return e.get("/v1/account/pnl",{params:ce(y)}).andThen(f(ListPerpsPnlHistoryResponseSchema)).map(P=>{let A=P.data.at(-1),q=P.more&&A!==void 0&&A.timestamp<s.endTimestamp;return {items:P.data,hasMore:q,nextCursor:q?Br({...s,startTimestamp:A.timestamp+Gs(s.interval)}):void 0}})},t)}var Jm=z.object({kind:z.literal("perpsNotifications"),cursor:z.string().min(1),sinceSeq:z.number().int().nonnegative().optional(),limit:z.number().int().positive().optional()}),Qm=z.object({sinceSeq:z.number().int().nonnegative().optional(),limit:z.number().int().positive().optional(),cursor:PaginationCursorSchema.optional()}),Xm=z.object({cursor:PaginationCursorSchema}),ey=z.union([Qm.transform(({cursor:e,...r})=>({cursor:e,params:r})),Xm.transform(({cursor:e})=>({cursor:e,params:void 0}))]);function js(e,r={}){let{cursor:t,params:o}=l(r,ey);return x(n=>{let s;n===void 0?invariant(o!==void 0,"Expected initial Perps notifications params."):s=Ge(n,Jm);let a=s===void 0?o?.sinceSeq:s.sinceSeq,y=s===void 0?o?.limit:s.limit;return e.get("/v1/account/notifications",{params:ce({cursor:s?.cursor,limit:y,sinceSeq:a})}).andThen(f(ListPerpsNotificationsResponseSchema)).map(P=>{let A=P.has_more&&P.next_cursor!==null;return {items:P.items,hasMore:A,nextCursor:A&&P.next_cursor!==null?Br({kind:"perpsNotifications",cursor:P.next_cursor,limit:y,sinceSeq:a}):void 0}})},t)}async function Hs(e){return (await unwrap(e.get("/v1/account/notifications",{params:ce({limit:1})}).andThen(f(FetchPerpsUnreadNotificationsCountResponseSchema)))).unread}var ry=z.object({ids:z.array(z.string().min(1)).min(1)}),ty=z.object({upTo:z.object({id:z.string().min(1),timestamp:z.number().int().nonnegative()})}),oy=z.union([ry.transform(({ids:e})=>({ids:e})),ty.transform(({upTo:e})=>({before:ny(e)}))]);async function _s(e,r){let t=l(r,oy),o=await unwrap(e.post("/v1/account/notifications/read",{json:t}).andThen(f(MarkPerpsNotificationsReadResponseSchema)));if(o.status==="err")throw new f$1(o.error??"Perps notifications read request was rejected.",{status:200})}function ny(e){return btoa(JSON.stringify({ts:e.timestamp,id:e.id})).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function Ut(e,r){let t=Date.now(),{end:o,start:n,...s}=e;return {...s,endTimestamp:o??t,startTimestamp:n??t-r}}function Ns(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 Br(e){return toPaginationCursor(btoa(JSON.stringify(e)))}function ce(e){return g(e,E())}function sy(e){return e.confirmedTimestamp??e.createdTimestamp}function ay(e){return e.confirmedTimestamp??e.createdTimestamp}function Dt(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:Br({...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 Fr;case "1w":return 7*Fr}invariant(false,`Unsupported Perps account history interval: ${String(e)}`);}var jt=z.object({instrumentId:PerpsInstrumentIdSchema,side:OrderSideSchema,quantity:PerpsDecimalInputSchema,reduceOnly:z.boolean().default(false),clientOrderId:PerpsClientOrderIdSchema.optional()}),my=jt.extend({price:PerpsDecimalInputSchema,timeInForce:z.literal(PerpsTimeInForce.GTC),postOnly:z.boolean().default(false)}),yy=jt.extend({price:PerpsDecimalInputSchema.optional(),timeInForce:z.literal(PerpsTimeInForce.IOC),postOnly:z.never().optional()}),fy=jt.extend({price:PerpsDecimalInputSchema.optional(),timeInForce:z.literal(PerpsTimeInForce.FOK),postOnly:z.never().optional()}),Js=z.discriminatedUnion("timeInForce",[my,yy,fy]),Ur=z.object({triggerPrice:PerpsDecimalInputSchema,limitPrice:PerpsDecimalInputSchema.optional()}),Dr=z.object({triggerPrice:PerpsDecimalInputSchema}),Py=z.union([z.object({takeProfit:Ur,stopLoss:Ur.optional()}),z.object({takeProfit:Ur.optional(),stopLoss:Ur})]),gy=z.object({orders:z.array(Js).min(1),expiresAt:z.number().int().positive().optional()});async function Ht(e,r){let t=l(r,gy);return await e.sendSignedWsCommand({op:["createOrders",t.orders.map(sa)],responseSchema:z.array(PerpsPostOrderAckSchema),timeoutMessage:"Perps post order acknowledgement timed out.",expiresAt:t.expiresAt})}var Ry=z.intersection(Js,z.intersection(Py,z.object({expiresAt:z.number().int().positive().optional()})));function Qs(e){return e.takeProfit!==void 0||e.stopLoss!==void 0}async function Xs(e,r){let t=l(r,Ry),o=[sa(t)],n=t.side===OrderSide.SELL;return t.takeProfit!==void 0&&o.push(jr({buy:n,instrumentId:t.instrumentId,kind:PerpsTpSlKind.TakeProfit,quantity:toDecimalString(t.quantity),trigger:t.takeProfit})),t.stopLoss!==void 0&&o.push(jr({buy:n,instrumentId:t.instrumentId,kind:PerpsTpSlKind.StopLoss,quantity:toDecimalString(t.quantity),trigger:t.stopLoss})),await aa(e,{expiresAt:t.expiresAt,group:PerpsTpSlScope.Order,orders:o})}var Ey=z.union([z.object({takeProfit:Dr,stopLoss:Dr.optional()}),z.object({takeProfit:Dr.optional(),stopLoss:Dr})]),Sy=z.intersection(Ey,z.object({instrumentId:PerpsInstrumentIdSchema,expiresAt:z.number().int().positive().optional()})),hy=z.intersection(Sy,z.object({buy:z.boolean()}));async function ea(e,r){let t=l(r,hy),o=[];return t.takeProfit!==void 0&&o.push(jr({buy:t.buy,instrumentId:t.instrumentId,kind:PerpsTpSlKind.TakeProfit,quantity:"0",trigger:t.takeProfit})),t.stopLoss!==void 0&&o.push(jr({buy:t.buy,instrumentId:t.instrumentId,kind:PerpsTpSlKind.StopLoss,quantity:"0",trigger:t.stopLoss})),await aa(e,{expiresAt:t.expiresAt,group:PerpsTpSlScope.Position,orders:o})}var Ty=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 ra(e,r){let t=l(r,Ty),[o]=t.orderId!==void 0?await Wr(e,{orderIds:[t.orderId],expiresAt:t.expiresAt}):await Wr(e,{clientOrderIds:[t.clientOrderId],expiresAt:t.expiresAt});return expectPresent(o,"Expected Perps cancel order result.")}var xy=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 Wr(e,r){let t=l(r,xy);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 Cy=z.object({instrumentId:PerpsInstrumentIdSchema.optional(),expiresAt:z.number().int().positive().optional()}).default({});async function ta(e,r,t){let o=l(t,Cy),n=["cancelAll",o.instrumentId===void 0?[]:[o.instrumentId]],s=r(n,o.expiresAt);await unwrap(e.del("/v1/trade/orders/all",{json:{...s,op:_t(n)}}).andThen(f(PerpsCancelAllOrdersResponseSchema)));}var by=z.object({instrumentId:PerpsInstrumentIdSchema,leverage:z.number().int().positive(),crossMargin:z.boolean()}),oa=m(f$1,l$1,c,a);async function na(e,r){let t=l(r,by);return await e.sendSignedWsCommand({op:["updateLeverage",[t.instrumentId,t.leverage,t.crossMargin]],responseSchema:PerpsUpdateLeverageResultSchema,timeoutMessage:"Perps update leverage response timed out."})}function sa(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 jr(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 aa(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 _t(e){let[r,t,o]=e;switch(r){case "createOrders":return qy({args:t.map(ky),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 ky(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=Iy(e[8])),r}function Iy(e){let r={tpsl:e[2],trp:e[1]};return e[0]!==void 0&&(r.market=e[0]),r}function qy(e,r){return r!==void 0&&(e.grp=r),e}var Ly=3e4,ca=3e4,da=2e3,My=["balances","portfolio","orders","fills","funding","deposits","withdrawals","notifications","tpsl"],Fy=new Set(["notifications"]),By=z.object({id:z.number().int().positive().optional(),data:z.unknown().optional()}).passthrough(),ua=z.union([PerpsCommandAckSchema,z.array(PerpsCommandAckSchema)]).transform(e=>Array.isArray(e)?e.find(r=>r.status==="err")??e[0]:e),la=class{credentials;#e;#r;#t;#o;#n;#c=new Mr({heartbeat:new wr});#i=pushable({objectMode:true});#s=new Map;#p=new Set;#a=new Lr;#d=new Map;#m=1;#l;constructor(r){this.#e=new Or({headers:r.headers,resolveHeaders:async()=>this.#k(),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.#l!==void 0}async connect(){await this.#P(false);}async close(){this.#l===void 0&&(this.#l=this.#q()),await this.#l;}[Symbol.asyncIterator](){return this.#i[Symbol.asyncIterator]()}async fetchBalances(){return await vs(this.#e)}async fetchPortfolio(){return await As(this.#e)}async fetchStats(){return await Os(this.#e)}async fetchAccountConfig(r){return await ws(this.#e,r)}async fetchOpenOrders(r){return await Ls(this.#e,r)}async fetchOrders(r){return await Ms(this.#e,r)}listFills(r={}){return Fs(this.#e,r)}listFundingPayments(r={}){return Bs(this.#e,r)}listDeposits(r={}){return Us(this.#e,r)}listWithdrawals(r={}){return Ds(this.#e,r)}listEquityHistory(r){return zs(this.#e,r)}listPnlHistory(r){return Ws(this.#e,r)}listNotifications(r={}){return js(this.#e,r)}async fetchUnreadNotificationsCount(){return await Hs(this.#e)}async markNotificationsRead(r){await _s(this.#e,r);}async placeOrder(r){if(Qs(r))return await this.#T(r);let[t]=await Ht(this.#u(),{orders:[r],expiresAt:r.expiresAt}).then(expectNonEmptyArray);if(t.status==="err")throw new f$1(t.error,{status:200});return {order:(await this.#S(n=>n.type==="order"&&n.payload.id===t.orderId,da)).payload}}async postOrders(r){return await Ht(this.#u(),r)}async#T(r){let t=await Xs(this.#u(),r).then(expectNonEmptyArray);for(let P of t)if(P.status==="err")throw new f$1(P.error,{status:200});let[o]=t,n=cr(o),s=await this.#S(P=>P.type==="order"&&P.payload.id===n.orderId,da),a=1,y={};return r.takeProfit!==void 0&&(y.takeProfit=cr(expectPresent(t[a++],"Expected Perps take-profit acknowledgement."))),r.stopLoss!==void 0&&(y.stopLoss=cr(expectPresent(t[a],"Expected Perps stop-loss acknowledgement."))),{order:s.payload,tpSl:y}}async placePositionTpSl(r){let t=await ea(this.#u(),{...r,buy:await this.#x(r.instrumentId)}).then(expectNonEmptyArray);for(let s of t)if(s.status==="err")throw new f$1(s.error,{status:200});let o=0,n={};return r.takeProfit!==void 0&&(n.takeProfit=cr(expectPresent(t[o++],"Expected Perps take-profit acknowledgement."))),r.stopLoss!==void 0&&(n.stopLoss=cr(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:zy(o.size);if(n===0)throw new a(`No open Perps position for instrument ${r}.`);return n<0}async cancelOrder(r){return await ra(this.#u(),r)}async cancelOrders(r){return await Wr(this.#u(),r)}async cancelAllOrders(r){await ta(this.#e,(t,o)=>this.#g(t,o),r);}async updateLeverage(r){return await na(this.#u(),r)}async#P(r){await this.#c.connect({onConnectionLost:()=>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.#m++,op:{args:{proxy:this.credentials.proxy,secret:this.credentials.secret},type:"auth"},req:"post"},ua,Ly,"Perps session authentication timed out.");}async#b(){await this.#y({id:this.#m++,req:"sub",chs:My},ua,ca,"Perps session subscription timed out.");}#k(){return {"POLYMARKET-PROXY":this.credentials.proxy,"POLYMARKET-SECRET":this.credentials.secret}}#u(){return {sendSignedWsCommand:r=>this.#I(r)}}async#I(r){let t=_t(r.op),o=this.#g(r.op,r.expiresAt);return await this.#y({...o,id:this.#m++,op:t,req:"post"},r.responseSchema,ca,r.timeoutMessage)}#g(r,t){let o=Wy(),n=Date.now(),s;try{s=gs({chainId:this.#r,op:r,privateKey:this.credentials.privateKey,salt:o,timestamp:n});}catch(y){throw l$1.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=Uy(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.#h(new c("Perps session closed.")),this.#i.end(),await this.#c.close(),this.#o(this);}#v(r){if(this.#A(r)||PerpsNotificationsResyncFrameSchema.safeParse(r).success)return;let t=PerpsSessionUpdateEventSchema.safeParse(r);if(!t.success)return;let o=t.data;this.#w(o),this.#E(o);}#A(r){let t=By.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=ma(t.data.data??t.data);return s!==void 0?o.reject(new f$1(s.error,{status:200})):o.reject(new c("Perps session unexpected response.")),true}return Dy(n.data)?o.reject(new f$1(n.data.error,{status:200})):o.resolve(n.data),true}#O(){this.#R(new c("Perps session connection closed.")),this.#h(new c("Perps session connection closed.")),this.#l===void 0&&this.#a.schedule({reconnect:()=>this.#P(true),shouldReconnect:()=>this.#l===void 0});}#R(r){for(let t of this.#s.values())t.reject(r);this.#s.clear();}#w(r){if(Fy.has(r.channel))return;let t=this.#d.get(r.channel);this.#d.set(r.channel,r.sequence),!(t===void 0||r.sequence===t+1)&&this.#E({channel:r.channel,previousSequence:t,reason:"sequence_gap",sequence:r.sequence,type:"resync"});}#E(r){this.#M(r),this.#i.push(r);}#S(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 h("Perps event wait timed out."));},t)};});return this.#p.add(o),n}#M(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);}#h(r){for(let t of Array.from(this.#p))this.#f(t),t.reject(r);}};function Uy(e){let r,t;return {promise:new Promise((n,s)=>{r=n,t=s;}),reject:t,resolve:r,schema:e}}function Dy(e){return ma(e)!==void 0}function ma(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 cr(e){if(e.status==="err")throw new f$1(e.error,{status:200});return {orderId:e.orderId}}function zy(e){let r=e.trim(),t=r.replace(/^[+-]/,"").replace(".","");return /^0*$/.test(t)?0:r.startsWith("-")?-1:1}function Wy(){let[e]=globalThis.crypto.getRandomValues(new Uint32Array(1));return invariant(e!==void 0,"Expected crypto.getRandomValues to return a salt."),e}var we=m(g$1,f$1,c,b,a),Pe=z.number().int().nonnegative(),Pa=1440*60*1e3,af=z.object({instrumentId:PerpsInstrumentIdSchema.optional(),category:PerpsInstrumentCategorySchema.optional()}).default({}),Tk=we;async function xk(e,r){let t=l(r,af);return unwrap(e.perps.get("/v1/info/instruments",{params:g(t,E())}).andThen(f(FetchPerpsInstrumentsResponseSchema)))}var pf=z.object({instrumentId:PerpsInstrumentIdSchema}),Ck=we;async function bk(e,r){let t=l(r,pf),[o]=await df(e,t);if(o===void 0)throw new b(`Perps ticker ${t.instrumentId} was not returned by the API`);return o}var cf=z.object({instrumentId:PerpsInstrumentIdSchema.optional()}).default({}),kk=we;async function df(e,r){let t=l(r,cf),o=g(t,E()),[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 uf=z.union([z.literal(10),z.literal(100),z.literal(500),z.literal(1e3)]),lf=z.object({instrumentId:PerpsInstrumentIdSchema,depth:uf.default(100)}),Ik=we;async function qk(e,r){let t=l(r,lf);return unwrap(e.perps.get("/v1/info/book",{params:g(t,E())}).andThen(f(PerpsBookSchema)))}var mf=z.object({instrumentId:PerpsInstrumentIdSchema,interval:PerpsKlineIntervalSchema,start:Pe.optional(),end:Pe.optional(),cursor:PaginationCursorSchema.optional()}),yf=z.object({cursor:PaginationCursorSchema}),ff=z.union([mf.transform(({cursor:e,...r})=>({cursor:e,params:bf(r)})),yf.transform(({cursor:e})=>({cursor:e,params:void 0}))]),vk=we;function Ak(e,r){let{cursor:t,params:o}=l(r,ff);return x(n=>{let s=n===void 0?kf(o):vf(n);return e.perps.get("/v1/info/klines",{params:g({endTimestamp:s.endTimestamp,instrumentId:s.instrumentId,interval:s.interval,startTimestamp:s.startTimestamp},E())}).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?Vt({...s,startTimestamp:y.timestamp+wf(s.interval)}):void 0}})},t)}var ga=z.object({instrumentId:PerpsInstrumentIdSchema,start:Pe.optional(),end:Pe.optional()}),Pf=ga.extend({cursor:PaginationCursorSchema.optional()}),gf=z.object({cursor:PaginationCursorSchema}),Rf=z.union([Pf.transform(({cursor:e,...r})=>({cursor:e,params:Ra(r)})),gf.transform(({cursor:e})=>({cursor:e,params:void 0}))]),Ef=ga.extend({cursor:PaginationCursorSchema.optional()}),Sf=z.object({cursor:PaginationCursorSchema}),Ok=we;function wk(e,r){let{cursor:t,params:o}=l(r,Rf);return x(n=>{let s=n===void 0?If(o):Af(n);return e.perps.get("/v1/info/funding",{params:g({endTimestamp:s.endTimestamp,instrumentId:s.instrumentId,startTimestamp:s.startTimestamp},E())}).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?Vt({...s,endTimestamp:y.timestamp-1}):void 0}})},t)}var hf=z.union([Ef.transform(({cursor:e,...r})=>({cursor:e,params:Ra(r)})),Sf.transform(({cursor:e})=>({cursor:e,params:void 0}))]),Lk=we;function Mk(e,r){let{cursor:t,params:o}=l(r,hf);return x(n=>{let s=n===void 0?qf(o):Of(n),a=new Set(s.seenTradeIds);return e.perps.get("/v1/info/trades",{params:g({endTimestamp:s.endTimestamp,instrumentId:s.instrumentId,startTimestamp:s.startTimestamp},E())}).andThen(f(FetchPerpsTradesResponseSchema)).map(y=>{let P=y.data.filter(ai=>!a.has(ai.tradeId)),A=y.data.at(-1),q=P.at(-1),j=q?.timestamp??A?.timestamp,U=y.more&&j!==void 0&&j>s.startTimestamp;return {items:P,hasMore:U,nextCursor:U?Vt({...s,endTimestamp:q===void 0?j-1:j,seenTradeIds:q===void 0?[]:Lf(s,P,q)}):void 0}})},t)}var Fk=m(g$1,f$1,c,b);async function Bk(e){return (await unwrap(e.perps.get("/v1/info/fees").andThen(f(FetchPerpsFeesResponseSchema)))).feeSchedule}var Tf=z.object({kind:z.literal("perpsCandles"),instrumentId:PerpsInstrumentIdSchema,interval:PerpsKlineIntervalSchema,startTimestamp:Pe,endTimestamp:Pe}),xf=z.object({kind:z.literal("perpsFundingHistory"),instrumentId:PerpsInstrumentIdSchema,startTimestamp:Pe,endTimestamp:Pe}),Cf=z.object({kind:z.literal("perpsTrades"),instrumentId:PerpsInstrumentIdSchema,startTimestamp:Pe,endTimestamp:Pe,seenTradeIds:z.array(PerpsTradeIdSchema)});function bf(e){let r=Date.now();return {endTimestamp:e.end??r,instrumentId:e.instrumentId,interval:e.interval,startTimestamp:e.start??r-Pa}}function Ra(e){let r=Date.now();return {endTimestamp:e.end??r,instrumentId:e.instrumentId,startTimestamp:e.start??r-Pa}}function kf(e){return invariant(e!==void 0,"Expected initial Perps candles params."),{kind:"perpsCandles",...e}}function If(e){return invariant(e!==void 0,"Expected initial Perps funding params."),{kind:"perpsFundingHistory",...e}}function qf(e){return invariant(e!==void 0,"Expected initial Perps trades params."),{kind:"perpsTrades",seenTradeIds:[],...e}}function vf(e){return $t(e,Tf)}function Af(e){return $t(e,xf)}function Of(e){return $t(e,Cf)}function $t(e,r){try{return r.parse(JSON.parse(atob(e)))}catch(t){throw new a("Invalid Perps pagination cursor",{cause:t})}}function Vt(e){return toPaginationCursor(btoa(JSON.stringify(e)))}function wf(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 Lf(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 Mf=z.custom(e=>isPrivateKey(e),"Expected a hex-encoded 32-byte private key."),Ff=z.object({proxy:z.string().transform(e=>expectEvmAddress(e)),privateKey:Mf,secret:z.string().min(1),expiresAt:z.number().int().positive()}),Bf=10080*60*1e3,Uf=z.strictObject({expiresIn:z.number().int().positive().default(Bf),label:z.string().min(1).optional()}),Df=z.strictObject({credentials:Ff}),zf=z.union([Uf,Df]),Wf=z.object({proxy:z.string()}),jf=Wf.transform(e=>({proxy:expectEvmAddress(e.proxy)})),Ea=z.bigint().positive().max(ee),Hf=z.object({amount:Ea,metadata:$.optional()}),_f=z.object({amount:Ea}),Uk=m(g$1,f$1,l$1,c,b,a),Dk=m(g$1,f$1,l$1,c,b,a),zk=m(a),Wk=m(j,g$1,f$1,l$1,c,b,a),jk=m(g$1,f$1,l$1,c,b,a);async function Hk(e,r={}){let t=l(r,zf),o="credentials"in t?await Kf(e,t.credentials):await Gf(e,t);return e.webSockets.perpsSession.connect(o)}async function _k(e,r){let t=l(r,jf),o={type:"deleteProxy",args:{proxy:t.proxy}},n=["deleteProxy",[t.proxy]],s=Zt(),a=Date.now(),y=await Vf(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 f$1(P.error??"Perps credentials revocation was rejected.",{status:200})}async function Nf(e,r){let t=l(r,Hf),{contracts:o}=e.environment,n=No(o.perpsDepositContract,o.collateralToken,t.amount,e.account.signer);return async function*(){return e.account.walletType===WalletType.EOA?G(yield rP(K(e.environment.chainId,n))):yield*await Q(e,{calls:[n],metadata:t.metadata??`Deposit ${t.amount} of ${o.collateralToken} to Perps`})}.call(null)}function Nk(e,r){return Nf(e,r).then(H(e.signer))}async function Gk(e,r){let t=l(r,_f),o=Math.floor(Date.now()/1e3),n=Zt(),s={type:"withdraw",args:{account:e.account.signer,token:e.environment.contracts.collateralToken,amount:t.amount.toString(),to:e.account.wallet}},a=await Zf(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 f$1(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 Gf(e,r){let t=Qf(),o=ha(t),n=e.account.signer,s=Date.now()+r.expiresIn,a=Date.now(),y=Zt(),P={args:{expiry:s,owner:n,proxy:o},type:"createProxy"},A=await $f(e,{expiresAt:s,proxy:o,salt:y,timestamp:a}),q={op:P,salt:y,sig:A,ts:a};r.label!==void 0&&(q.label=r.label);let j=await unwrap(e.perps.post("/v1/account/proxy",{json:q}).andThen(f(PerpsCreateProxyResponseSchema))),U={expiresAt:s,privateKey:t,proxy:o,secret:j.secret};return Sa(e,U)}async function Kf(e,r){return Xf(r),Sa(e,r)}async function Sa(e,r){let t=await unwrap(e.perps.get("/v1/account/credentials",{headers:eP(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 $f(e,r){try{return await e.signer.signTypedData(Jf({chainId:e.environment.chainId,...r}))}catch(t){throw l$1.fromError(t,"Could not sign the Perps proxy credentials request")}}async function Vf(e,r){try{return await e.signer.signTypedData(wt({chainId:e.environment.chainId,op:r.signedOp,salt:r.salt,timestamp:r.timestamp}))}catch(t){throw l$1.fromError(t,"Could not sign the Perps operation request")}}async function Zf(e,r){try{return await e.signer.signTypedData(Yf({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 l$1.fromError(t,"Could not sign the Perps withdrawal request")}}function Yf(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 Jf(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 Qf(){return expectPrivateKey(Secp256k1.randomPrivateKey(),"Generated invalid Perps proxy key.")}function ha(e){return expectEvmAddress(Address.fromPublicKey(Secp256k1.getPublicKey({privateKey:e})))}function Xf(e){let r=ha(e.privateKey);if(!isSameEvmAddress(r,e.proxy))throw new a("Perps credentials private key does not match the proxy address.")}function eP(e){return {"POLYMARKET-PROXY":e.proxy,"POLYMARKET-SECRET":e.secret}}function rP(e){return {kind:"sendPerpsDepositTransaction",request:e}}function Zt(){let[e]=crypto.getRandomValues(new Uint32Array(1));return invariant(e!==void 0,"Expected crypto.getRandomValues to return a salt."),e}var xa=(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))(xa||{}),pP=z.enum(["CURRENT","INITIAL","TOKENS","CASHPNL","PERCENTPNL","TITLE","RESOLVING","PRICE","AVGPRICE"]),Ca=z.enum(["ASC","DESC"]),cP=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:w.max(500).default(20),sortBy:pP.optional(),sortDirection:Ca.optional(),title:z.string().max(100).optional()}).refine(e=>!(e.market&&e.eventId),{message:"Provide market or eventId, not both",path:["eventId"]}),oI=m(g$1,f$1,c,b,a);function nI(e,r){let{cursor:t,pageSize:o,...n}=l(r,cP);return x(s=>{let a=D(s,o);return e.data.get("/positions",{params:N({...n,limit:a.pageSize,offset:a.offset})}).andThen(f(ListPositionsResponseSchema)).map(y=>{let P=y.length>=a.pageSize;return {items:y,hasMore:P,nextCursor:P?B({offset:a.offset+a.pageSize,pageSize:a.pageSize}):void 0}})},t)}var dP=z.enum(["REALIZEDPNL","TITLE","PRICE","AVGPRICE","TIMESTAMP"]),uP=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:w.max(50).default(20),sortBy:dP.optional(),sortDirection:Ca.optional()}).refine(e=>!(e.market&&e.eventId),{message:"Provide market or eventId, not both",path:["eventId"]}),sI=m(g$1,f$1,c,b,a);function aI(e,r){let{cursor:t,pageSize:o,...n}=l(r,uP);return x(s=>{let a=D(s,o);return e.data.get("/closed-positions",{params:N({...n,limit:a.pageSize,offset:a.offset})}).andThen(f(ListClosedPositionsResponseSchema)).map(y=>{let P=y.length>=a.pageSize;return {items:y,hasMore:P,nextCursor:P?B({offset:a.offset+a.pageSize,pageSize:a.pageSize}):void 0}})},t)}var lP=z.enum(xa),mP=z.union([ComboConditionIdSchema,z.array(ComboConditionIdSchema)]),yP=z.object({cursor:PaginationCursorSchema.optional(),user:z.string(),pageSize:w.default(20),status:ComboPositionStatusSchema.optional(),sort:lP.optional(),conditionId:mP.optional(),updatedAfter:z.number().int().min(0).optional(),updatedBefore:z.number().int().min(0).optional()}),iI=m(g$1,f$1,c,b,a);function pI(e,r){let{cursor:t,pageSize:o,conditionId:n,...s}=l(r,yP);return x(a=>{let y=g({...s,limit:o,cursor:a},E({updatedAfter:"updatedAfter",updatedBefore:"updatedBefore"}));return fP(y,n),e.data.get("/v1/positions/combos",{params:y}).andThen(f(ListComboPositionsResponseSchema)).map(P=>{let A=P.pagination.nextCursor??void 0;return {items:P.combos,hasMore:A!==void 0,nextCursor:A}})},t)}function fP(e,r){r!==void 0&&e.append("market_id",Array.isArray(r)?r.join(","):r);}var PP=z.object({user:z.string(),market:z.array(z.string()).optional()}),cI=m(g$1,f$1,c,b,a);async function dI(e,r){let t=l(r,PP);return unwrap(e.data.get("/value",{params:N(t)}).andThen(f(FetchPortfolioValueResponseSchema)))}var gP=z.object({user:z.string()}),uI=m(g$1,f$1,c,b,a);async function lI(e,r){let t=l(r,gP);return unwrap(e.data.get("/traded",{params:N(t)}).andThen(f(TradedSchema)))}var RP=z.object({user:z.string()}),mI=m(g$1,f$1,c,b,a);async function yI(e,r){let t=l(r,RP);return unwrap(e.data.get("/v1/accounting/snapshot",{params:N(t)}).andThen(uo))}var va=32,Aa=3n,Ia=50,SP=(1n<<256n)-1n;function Qt(e){let r=AbiParameters.encode([{name:"legs",type:"uint256[]"}],[e]),t=Hash.keccak256(AbiParameters.encode([{name:"moduleId",type:"uint256"},{name:"data",type:"bytes"}],[Aa,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>Ia)throw new a(`Combo legs must include 1 to ${Ia} position IDs`);let r=e.map(t=>{let o=La(t),n=o.toString(16).padStart(va*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 wa(e){let t=La(e).toString(16).padStart(va*2,"0"),o=BigInt(`0x${t.slice(0,2)}`),n=Number.parseInt(t.slice(-2),16);if(o!==Aa)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 La(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>SP)throw new a("Position ID must be a uint256 value");return t}var Fa=z.object({amount:z.bigint().min(0n),conditionId:CtfConditionIdSchema,metadata:$.optional()}),TP=z.object({amount:z.bigint().positive(),legs:z.array(PositionIdSchema).min(1).max(50),metadata:$.optional()}),Ba=z.array(PositionIdSchema).min(1).max(50).transform(Oa),xP=z.object({amount:z.bigint().positive(),legs:Ba,metadata:$.optional()}),CP=z.union([Fa.extend({legs:z.never().optional()}),TP.extend({conditionId:z.never().optional()})]),Ua=m(g$1,f$1,c,b,a),FI=Ua,BI=Ua,Da=m(g$1,f$1,c,b,a),UI=Da,DI=Da,za=m(g$1,f$1,c,b,a),zI=za,WI=za;async function Wa(e,r){let t=l(r,Fa),o=await to(e,{conditionId:t.conditionId}),n=Go(o.adapterAddress,e.environment.contracts.collateralToken,o.conditionId,t.amount);return async function*(){return e.account.walletType===WalletType.EOA?G(yield Xt(K(e.environment.chainId,n))):yield*await Q(e,{calls:[n],metadata:t.metadata??`Split ${t.amount} positions for market ${o.marketId} (condition ${o.conditionId})`})}.call(null)}async function ja(e,r){let t=l(r,xP),o=et(e.environment.contracts.combinatorialModule,t.legs),n=Qt(t.legs),s=Vo(e.environment.contracts.protocolV2Router,n.conditionId,t.amount);return async function*(){return e.account.walletType===WalletType.EOA?(await G(yield Xt(K(e.environment.chainId,o))).wait(),G(yield Xt(K(e.environment.chainId,s)))):yield*await Q(e,{calls:[o,s],metadata:t.metadata??`Split ${t.amount} combo positions for condition ${n.conditionId}`})}.call(null)}async function bP(e,r){let t=l(r,CP);return t.legs!==void 0?ja(e,t):Wa(e,t)}var Ha=m(j,g$1,f$1,l$1,h,i,c,b,a),jI=Ha,HI=Ha;function _I(e,r){return Wa(e,r).then(H(e.signer))}function NI(e,r){return ja(e,r).then(H(e.signer))}function GI(e,r){return bP(e,r).then(H(e.signer))}var _a=z.object({amount:z.union([z.bigint().positive(),z.literal("max")]),conditionId:CtfConditionIdSchema,metadata:$.optional()}),kP=z.object({amount:z.union([z.bigint().positive(),z.literal("max")]),legs:z.array(PositionIdSchema).min(1).max(50),metadata:$.optional()}),IP=z.object({amount:z.union([z.bigint().positive(),z.literal("max")]),legs:Ba,metadata:$.optional()}),qP=z.union([_a.extend({legs:z.never().optional()}),kP.extend({conditionId:z.never().optional()})]);async function Na(e,r){let t=l(r,_a),o=await to(e,{conditionId:t.conditionId}),n=Qr(await e.rpc.ethCall(Jr(o.positionErc1155Address,e.account.wallet,o.tokenIds))),s=Ja(o.conditionId,n,t.amount),a=Ko(o.adapterAddress,e.environment.contracts.collateralToken,o.conditionId,s);return async function*(){return e.account.walletType===WalletType.EOA?G(yield eo(K(e.environment.chainId,a))):yield*await Q(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,IP),o=et(e.environment.contracts.combinatorialModule,t.legs),n=Qt(t.legs),s=Qr(await e.rpc.ethCall(Jr(e.environment.contracts.positionManager,e.account.wallet,n.positionIds))),a=Ja(n.conditionId,s,t.amount),y=Zo(e.environment.contracts.protocolV2Router,n.conditionId,a);return async function*(){return e.account.walletType===WalletType.EOA?(await G(yield eo(K(e.environment.chainId,o))).wait(),G(yield eo(K(e.environment.chainId,y)))):yield*await Q(e,{calls:[o,y],metadata:t.metadata??`Merge ${a} combo positions for condition ${n.conditionId}`})}.call(null)}async function vP(e,r){let t=l(r,qP);return t.legs!==void 0?Ga(e,t):Na(e,t)}var Ka=m(j,g$1,f$1,l$1,h,i,c,b,a),KI=Ka,$I=Ka;function VI(e,r){return Na(e,r).then(H(e.signer))}function ZI(e,r){return Ga(e,r).then(H(e.signer))}function YI(e,r){return vP(e,r).then(H(e.signer))}var $a=z.object({conditionId:CtfConditionIdSchema,marketId:z.never().optional(),amount:z.never().optional(),positionId:z.never().optional(),metadata:$.optional()}),Va=z.object({conditionId:z.never().optional(),marketId:MarketIdSchema,amount:z.never().optional(),positionId:z.never().optional(),metadata:$.optional()}),AP=z.union([$a,Va]),Za=z.object({positionId:PositionIdSchema,conditionId:z.never().optional(),marketId:z.never().optional(),metadata:$.optional()}),OP=z.union([$a,Va,Za]);async function wP(e,r){let t=l(r,AP),o=await to(e,t.conditionId!==void 0?{conditionId:t.conditionId,closed:true}:{marketId:t.marketId,closed:true}),n=$o(o.adapterAddress,e.environment.contracts.collateralToken,o.conditionId);return async function*(){return e.account.walletType===WalletType.EOA?G(yield Ya(K(e.environment.chainId,n))):yield*await Q(e,{calls:[n],metadata:t.metadata??`Redeem positions for market ${o.marketId} (condition ${o.conditionId})`})}.call(null)}async function LP(e,r){let t=l(r,Za),o=wa(t.positionId),n=_o(await e.rpc.ethCall(Ho(e.environment.contracts.positionManager,e.account.wallet,t.positionId)));if(n===0n)throw new a("Combo position has no balance to redeem");let s=Yo(e.environment.contracts.protocolV2Router,o.conditionId,o.outcomeIndex,n);return async function*(){return e.account.walletType===WalletType.EOA?G(yield Ya(K(e.environment.chainId,s))):yield*await Q(e,{calls:[s],metadata:t.metadata??`Redeem combo position ${t.positionId}`})}.call(null)}async function MP(e,r){let t=l(r,OP);return t.positionId!==void 0?LP(e,t):wP(e,t)}var JI=m(j,g$1,f$1,l$1,c,b,a);function QI(e,r){return MP(e,r).then(H(e.signer))}function Xt(e){return {kind:"sendSplitPositionTransaction",request:e}}function eo(e){return {kind:"sendMergePositionsTransaction",request:e}}function Ya(e){return {kind:"sendRedeemPositionsTransaction",request:e}}async function to(e,r){let t=r.conditionId!==void 0?`condition ${r.conditionId}`:`market ${r.marketId}`,o=await Bn(e,r.conditionId!==void 0?{conditionIds:[r.conditionId],closed:r.closed,pageSize:1}:{ids:[FP(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=BP(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 FP(e){let r=Number(e);if(!Number.isInteger(r))throw new a(`Market ID must be an integer, received ${e}`);return r}function BP(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 Ja(e,r,t){let o=UP(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 UP(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 HP=z.object({address:z.string()}),iq=m(g$1,f$1,c,b,a);async function pq(e,r){let t=l(r,HP);return unwrap(e.gamma.get("/public-profile",{params:g(t,E())}).andThen(f(PublicProfileSchema)).orElse(o=>o instanceof f$1&&o.status===404?ok(null):err(o)))}var oo=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;}},lq=m(e,oo,l$1,h,c,a),no=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;}},mq=m(e,no,h,c),so=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;}},yq=m(e,so,h,c),fq=m(e,c);async function Pq(e){return e.webSockets.rfqQuoter.connect()}var Xa=(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))(Xa||{}),GP=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:w.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(Xa).optional()}),Lq=m(g$1,f$1,c,b,a);function Mq(e,r){let{cursor:t,pageSize:o,...n}=l(r,GP);return x(s=>{let a=D(s,o);return e.gamma.get("/public-search",{params:g({...n,limitPerType:a.pageSize,page:a.offset},E({excludeTagIds:"exclude_tag_id"}))}).andThen(f(PublicSearchResponseSchema)).map(y=>({items:KP(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 KP(e){return {events:e.events??[],profiles:e.profiles??[],tags:e.tags??[]}}var JP=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:w.max(50).default(20),recurrence:z.enum(["daily","weekly","monthly"]).optional(),slug:z.array(z.string()).optional()}),QP=z.object({id:z.string(),locale:z.string().optional()}),Gq=m(g$1,f$1,c,b,a);function Kq(e,r={}){let{cursor:t,pageSize:o,...n}=l(r,JP);return x(s=>{let a=D(s,o);return e.gamma.get("/series",{params:g({...n,limit:a.pageSize,offset:a.offset},E())}).andThen(f(ListSeriesResponseSchema)).map(y=>{let P=y.length>=a.pageSize;return {items:y,hasMore:P,nextCursor:P?B({offset:a.offset+a.pageSize,pageSize:a.pageSize}):void 0}})},t)}var $q=m(g$1,f$1,c,b,a);async function Vq(e,r){let t=l(r,QP);return unwrap(e.gamma.get(`series/${t.id}`,{params:g({locale:t.locale},E())}).andThen(f(SeriesSchema)))}var ev=m(g$1,f$1,c,b);async function rv(e){return unwrap(e.gamma.get("/sports").andThen(f(ListSportsMetadataResponseSchema)))}var tv=m(g$1,f$1,c,b);async function ov(e){return unwrap(e.gamma.get("/sports/market-types").andThen(f(SportsMarketTypesResponseSchema)))}var dv=m(c,a),og=z.object({topic:z.literal("prices.crypto.chainlink.twap"),windowSeconds:z.union([z.literal(30),z.literal(60)]),symbols:z.array(z.string()).optional()});async function uv(e,r){for(let o of r)o.topic==="prices.crypto.chainlink.twap"&&l(o,og);let t=await Promise.all(r.map(o=>ng(e,o)));return sg(t)}function ng(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.crypto.chainlink.twap":case "prices.equity.pyth":return e.webSockets.rtds.subscribe(r);case "perps.trades":case "perps.bbo":case "perps.book":case "perps.candles":case "perps.tickers":case "perps.statistics":return e.webSockets.perpsSubscriptions.subscribe(r);case "user":return invariant(e.isSecureClient(),"A 'user' subscription requires a secure client instance."),e.webSockets.clobUser.subscribe(r)}}function sg(e){let r;async function t(){r===void 0&&(r=Promise.all(e.map(n=>n.close())).then(()=>{})),await r;}let o=tg(...e);return {close:t,[Symbol.asyncIterator](){return o[Symbol.asyncIterator]()}}}var pg=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:w.max(100).default(20)}),cg=z.union([z.object({id:z.string(),includeTemplate:z.boolean().optional(),locale:z.string().optional()}),z.object({slug:z.string(),locale:z.string().optional()})]),dg=z.object({id:z.string(),omitEmpty:z.boolean().optional(),status:z.enum(["active","closed","all"]).optional()}),ug=z.object({slug:z.string()}),lg=z.object({id:z.string(),locale:z.string().optional(),omitEmpty:z.boolean().optional(),status:z.enum(["active","closed","all"]).optional()}),mg=z.object({locale:z.string().optional(),slug:z.string(),omitEmpty:z.boolean().optional(),status:z.enum(["active","closed","all"]).optional()}),Tv=m(g$1,f$1,c,b,a);function xv(e,r={}){let{cursor:t,pageSize:o,...n}=l(r,pg);return x(s=>{let a=D(s,o);return e.gamma.get("/tags",{params:g({...n,limit:a.pageSize,offset:a.offset},E())}).andThen(f(ListTagsResponseSchema)).map(y=>{let P=y.length>=a.pageSize;return {items:y,hasMore:P,nextCursor:P?B({offset:a.offset+a.pageSize,pageSize:a.pageSize}):void 0}})},t)}var Cv=m(g$1,f$1,c,b,a);async function bv(e,r){let t=l(r,cg);return "id"in t?unwrap(e.gamma.get(`tags/${t.id}`,{params:g({includeTemplate:t.includeTemplate,locale:t.locale},E())}).andThen(f(TagSchema))):unwrap(e.gamma.get(`tags/slug/${t.slug}`,{params:g({locale:t.locale},E())}).andThen(f(TagSchema)))}var kv=m(g$1,f$1,c,b,a);async function Iv(e,r){if("id"in r){let o=l(r,dg);return unwrap(e.gamma.get(`tags/${o.id}/related-tags`,{params:g({omitEmpty:o.omitEmpty,status:o.status},E())}).andThen(f(ListRelatedTagsResponseSchema)))}let t=l(r,ug);return unwrap(e.gamma.get(`tags/slug/${t.slug}/related-tags`).andThen(f(ListRelatedTagsResponseSchema)))}var qv=m(g$1,f$1,c,b,a);async function vv(e,r){if("id"in r){let o=l(r,lg);return unwrap(e.gamma.get(`tags/${o.id}/related-tags/tags`,{params:g({locale:o.locale,omitEmpty:o.omitEmpty,status:o.status},E())}).andThen(f(ListRelatedTagResourcesResponseSchema)))}let t=l(r,mg);return unwrap(e.gamma.get(`tags/slug/${t.slug}/related-tags/tags`,{params:g({locale:t.locale,omitEmpty:t.omitEmpty,status:t.status},E())}).andThen(f(ListRelatedTagResourcesResponseSchema)))}var Pg=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:w.max(100).default(20),providerId:z.array(z.number().int()).optional()}),zv=m(g$1,f$1,c,b,a);function Wv(e,r={}){let{cursor:t,pageSize:o,...n}=l(r,Pg);return x(s=>{let a=D(s,o);return e.gamma.get("/teams",{params:g({...n,limit:a.pageSize,offset:a.offset},E({providerId:"provider_id"}))}).andThen(f(ListTeamsResponseSchema)).map(y=>{let P=y.length>=a.pageSize;return {items:y,hasMore:P,nextCursor:P?B({offset:a.offset+a.pageSize,pageSize:a.pageSize}):void 0}})},t)}var Rg=z.object({amount:z.bigint(),metadata:$.optional(),recipientAddress:EvmAddressSchema,tokenAddress:EvmAddressSchema}),Jv=m(a);async function Eg(e,r){let t=l(r,Rg);return async function*(){return e.account.walletType===WalletType.EOA?G(yield Sg(K(e.environment.chainId,Xr(t.tokenAddress,t.recipientAddress,t.amount)))):yield*await Q(e,{calls:[Xr(t.tokenAddress,t.recipientAddress,t.amount)],metadata:t.metadata??`Transfer ${t.amount} of ${t.tokenAddress} to ${t.recipientAddress}`})}.call(null)}var Qv=m(j,g$1,f$1,l$1,c,b,a);function Xv(e,r){return Eg(e,r).then(H(e.signer))}function Sg(e){return {kind:"sendErc20TransferTransaction",request:e}}
2
+ export{qo as $,XE as $a,hh as $b,_x as $c,jk as $d,pq as $e,QR as A,bE as Aa,Sn as Ab,UT as Ac,Ss as Ad,za as Ae,uv as Af,Yo as B,$ as Ba,jS as Bb,DT as Bc,hs as Bd,zI as Be,Tv as Bf,XR as C,kE as Ca,hn as Cb,QT as Cc,wr as Cd,WI as Ce,xv as Cf,et as D,IE as Da,HS as Db,Bn as Dc,Lr as Dd,Wa as De,Cv as Df,Jo as E,cc as Ea,Tn as Eb,XT as Ec,Mr as Ed,ja as Ee,bv as Ef,Qo as F,qE as Fa,_S as Fb,ex as Fc,oa as Fd,bP as Fe,kv as Ff,l as G,Q as Ga,NS as Gb,rx as Gc,la as Gd,Ha as Ge,Iv as Gf,mo as H,st as Ha,GS as Hb,tx as Hc,Tk as Hd,jI as He,qv as Hf,zg as I,at as Ia,KS as Ib,ox as Ic,xk as Id,HI as Ie,vv as If,ho as J,it as Ja,$S as Jb,nx as Jc,Ck as Jd,_I as Je,zv as Jf,To as K,pt as Ka,xn as Kb,sx as Kc,bk as Kd,NI as Ke,Wv as Kf,xo as L,ct as La,VS as Lb,ax as Lc,kk as Ld,GI as Le,Jv as Lf,Qg as M,dt as Ma,ZS as Mb,ix as Mc,df as Md,Na as Me,Eg as Mf,Xg as N,vE as Na,YS as Nb,px as Nc,Ik as Nd,Ga as Ne,Qv as Nf,eR as O,rr as Oa,JS as Ob,cx as Oc,qk as Od,vP as Oe,Xv as Of,rR as P,WE as Pa,QS as Pb,dx as Pc,vk as Pd,Ka as Pe,tR as Q,hc as Qa,XS as Qb,Rx as Qc,Ak as Qd,KI as Qe,oR as R,jE as Ra,eh as Rb,Ex as Rc,Ok as Rd,$I as Re,nR as S,pn as Sa,rh as Sb,Sx as Sc,wk as Sd,VI as Se,Io as T,HE as Ta,th as Tb,hx as Tc,Lk as Td,ZI as Te,sR as U,xc as Ua,oh as Ub,Tx as Uc,Mk as Ud,YI as Ue,aR as V,_E as Va,nh as Vb,xx as Vc,Fk as Vd,wP as Ve,iR as W,cn as Wa,sh as Wb,Cx as Wc,Bk as Wd,LP as We,pR as X,NE as Xa,ah as Xb,bx as Xc,Uk as Xd,MP as Xe,cR as Y,Cc as Ya,ih as Yb,Lx as Yc,Dk as Yd,JI as Ye,Vr as Z,GE as Za,ph as Zb,Mx as Zc,zk as Zd,QI as Ze,dR as _,KE as _a,ch as _b,gt as _c,Wk as _d,iq as _e,ee as a,uR as aa,Ac as ab,Th as ac,Nx as ad,Hk as ae,oo as af,NR as b,lR as ba,eS as bb,xh as bc,vr as bd,_k as be,lq as bf,Pr as c,mR as ca,Oc as cb,Od as cc,Gx as cd,Nf as ce,no as cf,Do as d,yR as da,rS as db,Ch as dc,os as dd,Nk as de,mq as df,zo as e,fR as ea,tS as eb,bh as ec,ns as ed,Gk as ee,so as ef,gr as f,PR as fa,oS as fb,It as fd,xa as fe,yq as ff,Wo as g,gR as ga,nS as gb,Dh as gc,Il as gd,oI as ge,fq as gf,jo as h,RR as ha,sS as hb,zh as hc,qt as hd,nI as he,Pq as hf,Ho as i,ER as ia,aS as ib,Wh as ic,ql as id,sI as ie,_o as j,SR as ja,iS as jb,jh as jc,vt as jd,aI as je,Jr as k,hR as ka,pS as kb,Hh as kc,OC as kd,iI as ke,Qr as l,TR as la,cS as lb,_h as lc,wC as ld,pI as le,GR as m,wR as ma,dS as mb,nT as mc,LC as md,cI as me,Xr as n,LR as na,uS as nb,sT as nc,MC as nd,dI as ne,KR as o,MR as oa,lS as ob,aT as oc,HC as od,uI as oe,Xa as of,No as p,FR as pa,TS as pb,iT as pc,_C as pd,lI as pe,Lq as pf,$R as q,BR as qa,xS as qb,pT as qc,ib as qd,mI as qe,Mq as qf,VR as r,UR as ra,MS as rb,cT as rc,Dl as rd,yI as re,Gq as rf,Go as s,FS as sb,dT as sc,pb as sd,Kq as sf,ZR as t,oE as ta,BS as tb,uT as tc,cb as td,$q as tf,Ko as u,G as ua,US as ub,TT as uc,db as ud,Ua as ue,Vq as uf,$o as v,pE as va,DS as vb,xT as vc,zl as vd,FI as ve,ev as vf,YR as w,Xo as wa,ze as wb,CT as wc,ub as wd,BI as we,rv as wf,Vo as x,xE as xa,zS as xb,bT as xc,lb as xd,Da as xe,tv as xf,JR as y,nt as ya,We as yb,kT as yc,Or as yd,UI as ye,ov as yf,Zo as z,CE as za,WS as zb,IT as zc,Es as zd,DI as ze,dv as zf};//# sourceMappingURL=chunk-EC3TWEID.js.map
3
+ //# sourceMappingURL=chunk-EC3TWEID.js.map