@polymarket/client 0.1.0-beta.7 → 0.1.0-beta.9

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,12 +1,13 @@
1
- import { aK as RateLimitError, aM as RequestRejectedError, bu as TransportError, bx as UnexpectedResponseError, bn as SigningError, B as BaseClient, h as BaseSecureClient } from '../types-C9xs0MNQ.js';
2
- export { e as ApproveErc1155ForAllError, f as ApproveErc20Error, C as CancelAllError, j as CancelMarketOrdersError, bO as CancelMarketOrdersRequest, k as CancelOrderError, bP as CancelOrderRequest, l as CancelOrdersError, bQ as CancelOrdersRequest, bR as CommentsEventType, bS as CommentsSubscription, bT as CryptoPricesEventType, bU as CryptoPricesSubscription, bV as DeployDepositWalletError, bW as DeprecatedTransactionHandle, s as DownloadAccountingSnapshotError, bX as DownloadAccountingSnapshotRequest, t as DropNotificationsError, bY as DropNotificationsRequest, bZ as EquityPricesEventType, b_ as EquityPricesSubscription, b$ as Erc1155ApprovalForAllWorkflow, c0 as Erc1155ApprovalForAllWorkflowRequest, c1 as Erc20ApprovalWorkflow, c2 as Erc20ApprovalWorkflowRequest, c3 as Erc20TransferWorkflow, c4 as Erc20TransferWorkflowRequest, c5 as EstimateMarketBuyPriceRequest, u as EstimateMarketPriceError, c6 as EstimateMarketPriceRequest, c7 as EstimateMarketSellPriceRequest, c8 as EventForSubscriptionSpec, c9 as EventForSubscriptionSpecs, ca as FetchBalanceAllowanceError, cb as FetchBalanceAllowanceRequest, cc as FetchBuilderFeeRatesError, cd as FetchBuilderFeeRatesRequest, F as FetchClosedOnlyModeError, v as FetchCommentsByIdError, ce as FetchCommentsByIdRequest, w as FetchEventError, x as FetchEventLiveVolumeError, cf as FetchEventLiveVolumeRequest, cg as FetchEventRequest, y as FetchEventTagsError, ch as FetchEventTagsRequest, ci as FetchExecuteParamsError, cj as FetchExecuteParamsRequest, ck as FetchGaslessTransactionRequest, z as FetchLastTradePriceError, cl as FetchLastTradePriceRequest, G as FetchLastTradePricesError, cm as FetchLastTradePricesRequest, H as FetchMarketError, cn as FetchMarketInfoError, co as FetchMarketInfoRequest, cp as FetchMarketRequest, I as FetchMarketTagsError, cq as FetchMarketTagsRequest, J as FetchMidpointError, cr as FetchMidpointRequest, K as FetchMidpointsError, cs as FetchMidpointsRequest, ct as FetchNegRiskError, cu as FetchNegRiskRequest, L as FetchNotificationsError, M as FetchOrderBookError, cv as FetchOrderBookRequest, N as FetchOrderBooksError, cw as FetchOrderBooksRequest, O as FetchOrderError, cx as FetchOrderRequest, P as FetchOrderScoringError, cy as FetchOrderScoringRequest, Q as FetchOrdersScoringError, cz as FetchOrdersScoringRequest, R as FetchPortfolioValueError, cA as FetchPortfolioValueRequest, V as FetchPriceError, W as FetchPriceHistoryError, cB as FetchPriceHistoryRequest, cC as FetchPriceRequest, X as FetchPricesError, cD as FetchPricesRequest, Y as FetchPublicProfileError, cE as FetchPublicProfileRequest, Z as FetchRelatedTagResourcesError, cF as FetchRelatedTagResourcesRequest, _ as FetchRelatedTagsError, cG as FetchRelatedTagsRequest, $ as FetchRewardPercentagesError, a0 as FetchSeriesError, cH as FetchSeriesRequest, a1 as FetchSpreadError, cI as FetchSpreadRequest, a2 as FetchSpreadsError, cJ as FetchSpreadsRequest, a3 as FetchTagError, cK as FetchTagRequest, cL as FetchTickSizeError, cM as FetchTickSizeRequest, a4 as FetchTotalEarningsForUserForDayError, cN as FetchTotalEarningsForUserForDayRequest, a5 as FetchTradedMarketCountError, cO as FetchTradedMarketCountRequest, cP as GaslessTransactionMetadataSchema, cQ as GaslessWorkflow, cR as GaslessWorkflowRequest, cS as IsWalletDeployedError, cT as IsWalletDeployedRequest, a7 as ListAccountTradesError, cU as ListAccountTradesRequest, a8 as ListActivityError, cV as ListActivityRequest, a9 as ListBuilderLeaderboardError, cW as ListBuilderLeaderboardRequest, aa as ListBuilderTradesError, cX as ListBuilderTradesRequest, ab as ListBuilderVolumeError, cY as ListBuilderVolumeRequest, ac as ListClosedPositionsError, cZ as ListClosedPositionsRequest, ad as ListComboMarketsError, c_ as ListComboMarketsRequest, ae as ListComboPositionsError, c$ as ListComboPositionsRequest, af as ListCommentsByUserAddressError, d0 as ListCommentsByUserAddressRequest, ag as ListCommentsError, d1 as ListCommentsRequest, ah as ListCurrentRewardsError, d2 as ListCurrentRewardsRequest, ai as ListEventsError, d3 as ListEventsRequest, aj as ListMarketHoldersError, d4 as ListMarketHoldersRequest, ak as ListMarketPositionsError, d5 as ListMarketPositionsRequest, al as ListMarketRewardsError, d6 as ListMarketRewardsRequest, am as ListMarketsError, d7 as ListMarketsRequest, an as ListOpenInterestError, d8 as ListOpenInterestRequest, ao as ListOpenOrdersError, d9 as ListOpenOrdersRequest, ap as ListPositionsError, da as ListPositionsRequest, aq as ListSeriesError, db as ListSeriesRequest, ar as ListTagsError, dc as ListTagsRequest, as as ListTeamsError, dd as ListTeamsRequest, at as ListTraderLeaderboardError, de as ListTraderLeaderboardRequest, au as ListTradesError, df as ListTradesRequest, av as ListUserEarningsAndMarketsConfigError, dg as ListUserEarningsAndMarketsConfigRequest, aw as ListUserEarningsForDayError, dh as ListUserEarningsForDayRequest, di as MarketEventType, dj as MarketSubscription, dk as MergeComboPositionError, dl as MergeMarketPositionError, ax as MergePositionsError, dm as MergePositionsWorkflow, dn as MergePositionsWorkflowRequest, ay as OpenRfqSessionError, dp as OrderDraft, dq as OrderPostingWorkflow, dr as OrderWorkflow, ds as OrderWorkflowRequest, aC as PostOrderError, aD as PostOrdersError, dt as PostOrdersRequest, du as PrepareErc1155ApprovalForAllError, dv as PrepareErc1155ApprovalForAllRequest, dw as PrepareErc20ApprovalError, dx as PrepareErc20ApprovalRequest, dy as PrepareErc20TransferError, dz as PrepareErc20TransferRequest, dA as PrepareGaslessTransactionError, dB as PrepareGaslessTransactionRequest, dC as PrepareLimitOrderRequest, dD as PrepareMarketBuyOrderRequest, dE as PrepareMarketOrderRequest, dF as PrepareMarketSellOrderRequest, dG as PrepareMergeComboPositionError, dH as PrepareMergeComboPositionRequest, dI as PrepareMergeMarketPositionError, dJ as PrepareMergeMarketPositionRequest, dK as PrepareMergePositionsError, dL as PrepareMergePositionsRequest, dM as PrepareRedeemComboPositionError, dN as PrepareRedeemComboPositionRequest, dO as PrepareRedeemMarketPositionsByConditionIdRequest, dP as PrepareRedeemMarketPositionsByMarketIdRequest, dQ as PrepareRedeemMarketPositionsError, dR as PrepareRedeemMarketPositionsRequest, dS as PrepareRedeemPositionsError, dT as PrepareRedeemPositionsRequest, dU as PrepareSplitComboPositionError, dV as PrepareSplitComboPositionRequest, dW as PrepareSplitMarketPositionError, dX as PrepareSplitMarketPositionRequest, dY as PrepareSplitPositionError, dZ as PrepareSplitPositionRequest, d_ as PrepareTradingApprovalsError, d$ as PublicRealtimeEvent, e0 as PublicRealtimeTopic, e1 as PublicSubscriptionSpec, aL as RedeemPositionsError, e2 as RedeemPositionsWorkflow, e3 as RedeemPositionsWorkflowRequest, e4 as ResolveConditionByTokenError, e5 as ResolveConditionByTokenRequest, aO as RfqCancelQuoteAck, aP as RfqCancelQuoteError, aQ as RfqCancelQuoteRejectedError, aR as RfqCancelQuoteRejectedErrorOptions, aS as RfqConfirmationAck, aT as RfqConfirmationError, aU as RfqConfirmationRejectedError, e6 as RfqConfirmationRejectedErrorOptions, aV as RfqConfirmationRequestEvent, aW as RfqEvent, e7 as RfqExecutionUpdateEvent, aX as RfqQuoteError, aY as RfqQuoteReference, aZ as RfqQuoteRejectedError, a_ as RfqQuoteRejectedErrorOptions, a$ as RfqQuoteRequestEvent, b0 as RfqQuoteResponse, b1 as RfqQuoteSource, b2 as RfqSession, b3 as SearchError, e8 as SearchRequest, e9 as SearchResults, ea as SecureRealtimeEvent, eb as SecureRealtimeTopic, ec as SecureSubscriptionSpec, bl as SetupTradingApprovalsError, ed as SignedOrder, ee as SplitComboPositionError, ef as SplitMarketPositionError, bo as SplitPositionError, eg as SplitPositionWorkflow, eh as SplitPositionWorkflowRequest, ei as SportsEventType, ej as SportsSubscription, ek as SubscribeError, el as SubscriptionHandle, em as TradingApprovalsWorkflow, en as TradingApprovalsWorkflowRequest, bt as TransferErc20Error, eo as UpdateBalanceAllowanceError, ep as UpdateBalanceAllowanceRequest, eq as UserEventType, er as UserSubscription, es as WaitForGaslessTransactionError, et as approveErc1155ForAll, eu as approveErc20, ev as cancelAll, ew as cancelMarketOrders, ex as cancelOrder, ey as cancelOrders, ez as deployDepositWallet, eA as downloadAccountingSnapshot, eB as dropNotifications, eC as estimateMarketPrice, eD as fetchBalanceAllowance, eE as fetchBuilderFeeRates, eF as fetchBuilderVolume, eG as fetchClosedOnlyMode, eH as fetchCommentsById, eI as fetchEvent, eJ as fetchEventLiveVolume, eK as fetchEventTags, eL as fetchExecuteParams, eM as fetchLastTradePrice, eN as fetchLastTradePrices, eO as fetchMarket, eP as fetchMarketInfo, eQ as fetchMarketTags, eR as fetchMidpoint, eS as fetchMidpoints, eT as fetchNegRisk, eU as fetchNotifications, eV as fetchOrder, eW as fetchOrderBook, eX as fetchOrderBooks, eY as fetchOrderScoring, eZ as fetchOrdersScoring, e_ as fetchPortfolioValue, e$ as fetchPrice, f0 as fetchPriceHistory, f1 as fetchPrices, f2 as fetchPublicProfile, f3 as fetchRelatedTagResources, f4 as fetchRelatedTags, f5 as fetchRewardPercentages, f6 as fetchSeries, f7 as fetchSpread, f8 as fetchSpreads, f9 as fetchTag, fa as fetchTickSize, fb as fetchTotalEarningsForUserForDay, fc as fetchTradedMarketCount, fd as fetchTransaction, fe as isWalletDeployed, ff as listAccountTrades, fg as listActivity, fh as listBuilderLeaderboard, fi as listBuilderTrades, fj as listClosedPositions, fk as listComboMarkets, fl as listComboPositions, fm as listComments, fn as listCommentsByUserAddress, fo as listCurrentRewards, fp as listEvents, fq as listMarketHolders, fr as listMarketPositions, fs as listMarketRewards, ft as listMarkets, fu as listOpenInterest, fv as listOpenOrders, fw as listPositions, fx as listSeries, fy as listTags, fz as listTeams, fA as listTraderLeaderboard, fB as listTrades, fC as listUserEarningsAndMarketsConfig, fD as listUserEarningsForDay, fE as mergeComboPosition, fF as mergeMarketPosition, fG as mergePositions, fH as openRfqSession, fI as postOrder, fJ as postOrders, fK as prepareErc1155ApprovalForAll, fL as prepareErc20Approval, fM as prepareErc20Transfer, fN as prepareGaslessTransaction, fO as prepareMergeComboPosition, fP as prepareMergeMarketPosition, fQ as prepareMergePositions, fR as prepareRedeemComboPosition, fS as prepareRedeemMarketPositions, fT as prepareRedeemPositions, fU as prepareSplitComboPosition, fV as prepareSplitMarketPosition, fW as prepareSplitPosition, fX as prepareTradingApprovals, fY as redeemPositions, fZ as resolveConditionByToken, f_ as search, f$ as setupTradingApprovals, g0 as splitComboPosition, g1 as splitMarketPosition, g2 as splitPosition, g3 as subscribe, g4 as transferErc20, g5 as updateBalanceAllowance } from '../types-C9xs0MNQ.js';
1
+ import { aR as RateLimitError, aT as RequestRejectedError, bG as TransportError, bJ as UnexpectedResponseError, bz as SigningError, B as BaseClient, h as BaseSecureClient } from '../types-M1U0um0G.js';
2
+ export { e as ApproveErc1155ForAllError, f as ApproveErc20Error, C as CancelAllError, j as CancelMarketOrdersError, c3 as CancelMarketOrdersRequest, k as CancelOrderError, c4 as CancelOrderRequest, l as CancelOrdersError, c5 as CancelOrdersRequest, c6 as CancelPerpsOrderRequest, c7 as CancelPerpsOrdersRequest, c8 as CommentsEventType, c9 as CommentsSubscription, ca as CreatePerpsSessionRequest, cb as CryptoPricesEventType, cc as CryptoPricesSubscription, cd as DeployDepositWalletError, ce as DepositToPerpsError, cf as DepositToPerpsRequest, cg as DeprecatedTransactionHandle, t as DownloadAccountingSnapshotError, ch as DownloadAccountingSnapshotRequest, u as DropNotificationsError, ci as DropNotificationsRequest, cj as EquityPricesEventType, ck as EquityPricesSubscription, cl as Erc1155ApprovalForAllWorkflow, cm as Erc1155ApprovalForAllWorkflowRequest, cn as Erc20ApprovalWorkflow, co as Erc20ApprovalWorkflowRequest, cp as Erc20TransferWorkflow, cq as Erc20TransferWorkflowRequest, cr as EstimateMarketBuyPriceRequest, x as EstimateMarketPriceError, cs as EstimateMarketPriceRequest, ct as EstimateMarketSellPriceRequest, cu as EventForSubscriptionSpec, cv as EventForSubscriptionSpecs, cw as FetchBalanceAllowanceError, cx as FetchBalanceAllowanceRequest, cy as FetchBuilderFeeRatesError, cz as FetchBuilderFeeRatesRequest, F as FetchClosedOnlyModeError, y as FetchCommentsByIdError, cA as FetchCommentsByIdRequest, z as FetchEventError, G as FetchEventLiveVolumeError, cB as FetchEventLiveVolumeRequest, cC as FetchEventRequest, H as FetchEventTagsError, cD as FetchEventTagsRequest, cE as FetchExecuteParamsError, cF as FetchExecuteParamsRequest, cG as FetchGaslessTransactionRequest, I as FetchLastTradePriceError, cH as FetchLastTradePriceRequest, J as FetchLastTradePricesError, cI as FetchLastTradePricesRequest, K as FetchMarketError, cJ as FetchMarketInfoError, cK as FetchMarketInfoRequest, cL as FetchMarketRequest, L as FetchMarketTagsError, cM as FetchMarketTagsRequest, M as FetchMidpointError, cN as FetchMidpointRequest, N as FetchMidpointsError, cO as FetchMidpointsRequest, cP as FetchNegRiskError, cQ as FetchNegRiskRequest, O as FetchNotificationsError, P as FetchOrderBookError, cR as FetchOrderBookRequest, Q as FetchOrderBooksError, cS as FetchOrderBooksRequest, R as FetchOrderError, cT as FetchOrderRequest, V as FetchOrderScoringError, cU as FetchOrderScoringRequest, W as FetchOrdersScoringError, cV as FetchOrdersScoringRequest, cW as FetchPerpsAccountConfigRequest, cX as FetchPerpsBookError, cY as FetchPerpsBookRequest, cZ as FetchPerpsFeesError, c_ as FetchPerpsInstrumentsError, c$ as FetchPerpsInstrumentsRequest, d0 as FetchPerpsOpenOrdersRequest, d1 as FetchPerpsOrdersRequest, d2 as FetchPerpsTickerError, d3 as FetchPerpsTickerRequest, d4 as FetchPerpsTickersError, d5 as FetchPerpsTickersRequest, X as FetchPortfolioValueError, d6 as FetchPortfolioValueRequest, Y as FetchPriceError, Z as FetchPriceHistoryError, d7 as FetchPriceHistoryRequest, d8 as FetchPriceRequest, _ as FetchPricesError, d9 as FetchPricesRequest, $ as FetchPublicProfileError, da as FetchPublicProfileRequest, a0 as FetchRelatedTagResourcesError, db as FetchRelatedTagResourcesRequest, a1 as FetchRelatedTagsError, dc as FetchRelatedTagsRequest, a2 as FetchRewardPercentagesError, a3 as FetchSeriesError, dd as FetchSeriesRequest, a4 as FetchSpreadError, de as FetchSpreadRequest, a5 as FetchSpreadsError, df as FetchSpreadsRequest, a6 as FetchTagError, dg as FetchTagRequest, dh as FetchTickSizeError, di as FetchTickSizeRequest, a7 as FetchTotalEarningsForUserForDayError, dj as FetchTotalEarningsForUserForDayRequest, a8 as FetchTradedMarketCountError, dk as FetchTradedMarketCountRequest, dl as GaslessTransactionMetadataSchema, dm as GaslessWorkflow, dn as GaslessWorkflowRequest, dp as IsWalletDeployedError, dq as IsWalletDeployedRequest, aa as ListAccountTradesError, dr as ListAccountTradesRequest, ab as ListActivityError, ds as ListActivityRequest, ac as ListBuilderLeaderboardError, dt as ListBuilderLeaderboardRequest, ad as ListBuilderTradesError, du as ListBuilderTradesRequest, ae as ListBuilderVolumeError, dv as ListBuilderVolumeRequest, af as ListClosedPositionsError, dw as ListClosedPositionsRequest, ag as ListComboMarketsError, dx as ListComboMarketsRequest, ah as ListComboPositionsError, dy as ListComboPositionsRequest, ai as ListCommentsByUserAddressError, dz as ListCommentsByUserAddressRequest, aj as ListCommentsError, dA as ListCommentsRequest, ak as ListCurrentRewardsError, dB as ListCurrentRewardsRequest, al as ListEventsError, dC as ListEventsRequest, am as ListMarketHoldersError, dD as ListMarketHoldersRequest, an as ListMarketPositionsError, dE as ListMarketPositionsRequest, ao as ListMarketRewardsError, dF as ListMarketRewardsRequest, ap as ListMarketsError, dG as ListMarketsRequest, aq as ListOpenInterestError, dH as ListOpenInterestRequest, ar as ListOpenOrdersError, dI as ListOpenOrdersRequest, dJ as ListPerpsCandlesError, dK as ListPerpsCandlesRequest, dL as ListPerpsDepositsRequest, dM as ListPerpsEquityHistoryRequest, dN as ListPerpsFillsRequest, dO as ListPerpsFundingHistoryError, dP as ListPerpsFundingHistoryRequest, dQ as ListPerpsFundingPaymentsRequest, dR as ListPerpsPnlHistoryRequest, dS as ListPerpsTradesError, dT as ListPerpsTradesRequest, dU as ListPerpsWithdrawalsRequest, as as ListPositionsError, dV as ListPositionsRequest, at as ListSeriesError, dW as ListSeriesRequest, au as ListTagsError, dX as ListTagsRequest, av as ListTeamsError, dY as ListTeamsRequest, aw as ListTraderLeaderboardError, dZ as ListTraderLeaderboardRequest, ax as ListTradesError, d_ as ListTradesRequest, ay as ListUserEarningsAndMarketsConfigError, d$ as ListUserEarningsAndMarketsConfigRequest, az as ListUserEarningsForDayError, e0 as ListUserEarningsForDayRequest, e1 as MarketEventType, e2 as MarketSubscription, e3 as MergeComboPositionError, e4 as MergeMarketPositionError, aA as MergePositionsError, e5 as MergePositionsWorkflow, e6 as MergePositionsWorkflowRequest, e7 as OpenPerpsSessionError, e8 as OpenPerpsSessionRequest, aB as OpenRfqSessionError, e9 as OrderDraft, ea as OrderPostingWorkflow, eb as OrderWorkflow, ec as OrderWorkflowRequest, ed as PerpsBboSubscription, ee as PerpsBookDepth, ef as PerpsBookSubscription, eg as PerpsCandlesSubscription, eh as PerpsDepositWorkflow, ei as PerpsDepositWorkflowRequest, ej as PerpsMarketDataEventType, ek as PerpsMarketDataSubscription, el as PerpsPlaceFokOrderRequest, em as PerpsPlaceGtcOrderRequest, en as PerpsPlaceIocOrderRequest, aH as PerpsSession, eo as PerpsStatisticsSubscription, ep as PerpsStreamingCandleInterval, eq as PerpsTickersSubscription, er as PerpsTradesSubscription, es as PlacePerpsOrderRequest, aI as PostOrderError, aJ as PostOrdersError, et as PostOrdersRequest, eu as PostPerpsOrdersRequest, ev as PrepareErc1155ApprovalForAllError, ew as PrepareErc1155ApprovalForAllRequest, ex as PrepareErc20ApprovalError, ey as PrepareErc20ApprovalRequest, ez as PrepareErc20TransferError, eA as PrepareErc20TransferRequest, eB as PrepareGaslessTransactionError, eC as PrepareGaslessTransactionRequest, eD as PrepareLimitOrderRequest, eE as PrepareMarketBuyOrderRequest, eF as PrepareMarketOrderRequest, eG as PrepareMarketSellOrderRequest, eH as PrepareMergeComboPositionError, eI as PrepareMergeComboPositionRequest, eJ as PrepareMergeMarketPositionError, eK as PrepareMergeMarketPositionRequest, eL as PrepareMergePositionsError, eM as PrepareMergePositionsRequest, eN as PreparePerpsDepositError, eO as PrepareRedeemComboPositionError, eP as PrepareRedeemComboPositionRequest, eQ as PrepareRedeemMarketPositionsByConditionIdRequest, eR as PrepareRedeemMarketPositionsByMarketIdRequest, eS as PrepareRedeemMarketPositionsError, eT as PrepareRedeemMarketPositionsRequest, eU as PrepareRedeemPositionsError, eV as PrepareRedeemPositionsRequest, eW as PrepareSplitComboPositionError, eX as PrepareSplitComboPositionRequest, eY as PrepareSplitMarketPositionError, eZ as PrepareSplitMarketPositionRequest, e_ as PrepareSplitPositionError, e$ as PrepareSplitPositionRequest, f0 as PrepareTradingApprovalsError, f1 as PublicRealtimeEvent, f2 as PublicRealtimeTopic, f3 as PublicSubscriptionSpec, aS as RedeemPositionsError, f4 as RedeemPositionsWorkflow, f5 as RedeemPositionsWorkflowRequest, f6 as ResolveConditionByTokenError, f7 as ResolveConditionByTokenRequest, f8 as ResumePerpsSessionRequest, f9 as RevokePerpsCredentialsError, fa as RevokePerpsCredentialsRequest, aW as RfqCancelQuoteAck, aX as RfqCancelQuoteError, aY as RfqCancelQuoteRejectedError, aZ as RfqCancelQuoteRejectedErrorOptions, a_ as RfqConfirmationAck, a$ as RfqConfirmationError, b0 as RfqConfirmationRejectedError, fb as RfqConfirmationRejectedErrorOptions, b1 as RfqConfirmationRequestEvent, b3 as RfqEvent, fc as RfqExecutionUpdateEvent, b4 as RfqQuoteError, b5 as RfqQuoteReference, b6 as RfqQuoteRejectedError, b7 as RfqQuoteRejectedErrorOptions, b8 as RfqQuoteRequestEvent, b9 as RfqQuoteResponse, ba as RfqQuoteSource, bb as RfqSession, bc as RfqTradeEvent, bd as SearchError, fd as SearchRequest, fe as SearchResults, be as SearchSort, ff as SecureRealtimeEvent, fg as SecureRealtimeTopic, fh as SecureSubscriptionSpec, bx as SetupTradingApprovalsError, fi as SignedOrder, fj as SplitComboPositionError, fk as SplitMarketPositionError, bA as SplitPositionError, fl as SplitPositionWorkflow, fm as SplitPositionWorkflowRequest, fn as SportsEventType, fo as SportsSubscription, fp as SubscribeError, fq as SubscriptionHandle, fr as TradingApprovalsWorkflow, fs as TradingApprovalsWorkflowRequest, bF as TransferErc20Error, ft as UpdateBalanceAllowanceError, fu as UpdateBalanceAllowanceRequest, bK as UpdatePerpsLeverageError, fv as UpdatePerpsLeverageRequest, bL as UpdatePerpsMarginError, fw as UpdatePerpsMarginRequest, fx as UserEventType, fy as UserSubscription, fz as WaitForGaslessTransactionError, fA as WithdrawFromPerpsError, fB as WithdrawFromPerpsRequest, fC as approveErc1155ForAll, fD as approveErc20, fE as cancelAll, fF as cancelMarketOrders, fG as cancelOrder, fH as cancelOrders, fI as deployDepositWallet, fJ as depositToPerps, fK as downloadAccountingSnapshot, fL as dropNotifications, fM as estimateMarketPrice, fN as fetchBalanceAllowance, fO as fetchBuilderFeeRates, fP as fetchBuilderVolume, fQ as fetchClosedOnlyMode, fR as fetchCommentsById, fS as fetchEvent, fT as fetchEventLiveVolume, fU as fetchEventTags, fV as fetchExecuteParams, fW as fetchLastTradePrice, fX as fetchLastTradePrices, fY as fetchMarket, fZ as fetchMarketInfo, f_ as fetchMarketTags, f$ as fetchMidpoint, g0 as fetchMidpoints, g1 as fetchNegRisk, g2 as fetchNotifications, g3 as fetchOrder, g4 as fetchOrderBook, g5 as fetchOrderBooks, g6 as fetchOrderScoring, g7 as fetchOrdersScoring, g8 as fetchPerpsBook, g9 as fetchPerpsFees, ga as fetchPerpsInstruments, gb as fetchPerpsTicker, gc as fetchPerpsTickers, gd as fetchPortfolioValue, ge as fetchPrice, gf as fetchPriceHistory, gg as fetchPrices, gh as fetchPublicProfile, gi as fetchRelatedTagResources, gj as fetchRelatedTags, gk as fetchRewardPercentages, gl as fetchSeries, gm as fetchSpread, gn as fetchSpreads, go as fetchTag, gp as fetchTickSize, gq as fetchTotalEarningsForUserForDay, gr as fetchTradedMarketCount, gs as fetchTransaction, gt as isWalletDeployed, gu as listAccountTrades, gv as listActivity, gw as listBuilderLeaderboard, gx as listBuilderTrades, gy as listClosedPositions, gz as listComboMarkets, gA as listComboPositions, gB as listComments, gC as listCommentsByUserAddress, gD as listCurrentRewards, gE as listEvents, gF as listMarketHolders, gG as listMarketPositions, gH as listMarketRewards, gI as listMarkets, gJ as listOpenInterest, gK as listOpenOrders, gL as listPerpsCandles, gM as listPerpsFundingHistory, gN as listPerpsTrades, gO as listPositions, gP as listSeries, gQ as listTags, gR as listTeams, gS as listTraderLeaderboard, gT as listTrades, gU as listUserEarningsAndMarketsConfig, gV as listUserEarningsForDay, gW as mergeComboPosition, gX as mergeMarketPosition, gY as mergePositions, gZ as openPerpsSession, g_ as openRfqSession, g$ as postOrder, h0 as postOrders, h1 as prepareErc1155ApprovalForAll, h2 as prepareErc20Approval, h3 as prepareErc20Transfer, h4 as prepareGaslessTransaction, h5 as prepareMergeComboPosition, h6 as prepareMergeMarketPosition, h7 as prepareMergePositions, h8 as preparePerpsDeposit, h9 as prepareRedeemComboPosition, ha as prepareRedeemMarketPositions, hb as prepareRedeemPositions, hc as prepareSplitComboPosition, hd as prepareSplitMarketPosition, he as prepareSplitPosition, hf as prepareTradingApprovals, hg as redeemPositions, hh as resolveConditionByToken, hi as revokePerpsCredentials, hj as search, hk as setupTradingApprovals, hl as splitComboPosition, hm as splitMarketPosition, hn as splitPosition, ho as subscribe, hp as transferErc20, hq as updateBalanceAllowance, hr as withdrawFromPerps } from '../types-M1U0um0G.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-DNQLB2c4.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-BGrBawu_.js';
7
7
  export { ComboPositionStatus } from '@polymarket/bindings/data';
8
- export { CommentsEvent, CryptoPricesBinanceEvent, CryptoPricesChainlinkEvent, CryptoPricesEvent, CustomMarketEvent, EquityPricesEvent, MarketEvent, SportsEvent, StandardMarketEvent, UserEvent } from '@polymarket/bindings/subscriptions';
9
- export { RfqConfirmationDecision, RfqConfirmationRequest, RfqDirection, RfqErrorCode, RfqExecutionStatus, RfqExecutionUpdate, RfqId, RfqQuoteId, RfqQuoteRequest, RfqRequestedSize, RfqRequestedSizeUnit, RfqRequestorPublicId, RfqSide } from '@polymarket/bindings/rfq';
8
+ export { CommentsEvent, CryptoPricesBinanceEvent, CryptoPricesChainlinkEvent, CryptoPricesEvent, CustomMarketEvent, EquityPricesEvent, MarketEvent, PerpsBboEvent, PerpsBookEvent, PerpsCandleEvent, PerpsMarketDataEvent, PerpsSessionEvent, PerpsStatisticEvent, PerpsTickerEvent, PerpsTradeEvent, SportsEvent, StandardMarketEvent, UserEvent } from '@polymarket/bindings/subscriptions';
9
+ export { PerpsCancelOrderResult, PerpsPostOrderAck } from '@polymarket/bindings/perps';
10
+ export { RfqConfirmationDecision, RfqConfirmationRequest, RfqDirection, RfqErrorCode, RfqExecutionStatus, RfqExecutionUpdate, RfqId, RfqQuoteId, RfqQuoteRequest, RfqRequestedSize, RfqRequestedSizeUnit, RfqRequestorPublicId, RfqSide, RfqTrade } from '@polymarket/bindings/rfq';
10
11
  import '@polymarket/bindings/gamma';
11
12
  import '@polymarket/bindings/relayer';
12
13
  import 'zod';
@@ -1,2 +1,2 @@
1
- export{Ya as ApproveErc1155ForAllError,Ua as ApproveErc20Error,yc as CancelAllError,Ac as CancelMarketOrdersError,uc as CancelOrderError,wc as CancelOrdersError,md as ComboPositionStatus,E as CreateApiKeyError,O as CreateBuilderApiKeyError,Yc as CreateLimitOrderError,Uc as CreateMarketOrderError,I as CreateOrDeriveApiKeyError,M as DeleteApiKeyError,ea as DeployDepositWalletError,G as DeriveApiKeyError,kd as DownloadAccountingSnapshotError,ua as DropNotificationsError,Cc as EstimateMarketPriceError,K as FetchApiKeysError,wa as FetchBalanceAllowanceError,Q as FetchBuilderApiKeysError,qb as FetchBuilderFeeRatesError,ka as FetchClosedOnlyModeError,Qb as FetchCommentsByIdError,Wb as FetchEventError,_b as FetchEventLiveVolumeError,Yb as FetchEventTagsError,$ as FetchExecuteParamsError,Eb as FetchLastTradePriceError,Gb as FetchLastTradePricesError,kc as FetchMarketError,ob as FetchMarketInfoError,mc as FetchMarketTagsError,eb as FetchMidpointError,gb as FetchMidpointsError,kb as FetchNegRiskError,sa as FetchNotificationsError,wb as FetchOrderBookError,yb as FetchOrderBooksError,oa as FetchOrderError,Aa as FetchOrderScoringError,Ca as FetchOrdersScoringError,gd as FetchPortfolioValueError,sb as FetchPriceError,Ib as FetchPriceHistoryError,ub as FetchPricesError,Td as FetchPublicProfileError,ye as FetchRelatedTagResourcesError,we as FetchRelatedTagsError,Ka as FetchRewardPercentagesError,le as FetchSeriesError,pe as FetchSportsMarketTypesError,Ab as FetchSpreadError,Cb as FetchSpreadsError,ue as FetchTagError,ib as FetchTickSizeError,Ga as FetchTotalEarningsForUserForDayError,id as FetchTradedMarketCountError,da as GaslessTransactionMetadataSchema,ba as IsWalletDeployedError,qa as ListAccountTradesError,Oa as ListActivityError,ac as ListBuilderLeaderboardError,cb as ListBuilderTradesError,cc as ListBuilderVolumeError,cd as ListClosedPositionsError,ic as ListComboMarketsError,dd as ListComboPositionsError,Sb as ListCommentsByUserAddressError,Ob as ListCommentsError,Kb as ListCurrentRewardsError,Ub as ListEventsError,oc as ListMarketHoldersError,sc as ListMarketPositionsError,Mb as ListMarketRewardsError,gc as ListMarketsError,qc as ListOpenInterestError,ma as ListOpenOrdersError,ad as ListPositionsError,je as ListSeriesError,ne as ListSportsError,se as ListTagsError,Ae as ListTeamsError,ec as ListTraderLeaderboardError,Ma as ListTradesError,Ia as ListUserEarningsAndMarketsConfigError,Ea as ListUserEarningsForDayError,Kd as MergeComboPositionError,Jd as MergeMarketPositionError,Id as MergePositionsError,$d as OpenRfqSessionError,_c as PlaceLimitOrderError,Wc as PlaceMarketOrderError,Fc as PostOrderError,Gc as PostOrdersError,Wa as PrepareErc1155ApprovalForAllError,Sa as PrepareErc20ApprovalError,Ce as PrepareErc20TransferError,ha as PrepareGaslessTransactionError,Oc as PrepareLimitOrderError,Sc as PrepareLimitOrderPostingError,Mc as PrepareMarketOrderError,Qc as PrepareMarketOrderPostingError,sd as PrepareMergeComboPositionError,rd as PrepareMergeMarketPositionError,qd as PrepareMergePositionsError,vd as PrepareRedeemComboPositionError,ud as PrepareRedeemMarketPositionsError,td as PrepareRedeemPositionsError,pd as PrepareSplitComboPositionError,od as PrepareSplitMarketPositionError,nd as PrepareSplitPositionError,_a as PrepareTradingApprovalsError,Rd as RedeemPositionsError,mb as ResolveConditionByTokenError,S as RevokeBuilderApiKeyError,Yd as RfqCancelQuoteError,Xd as RfqCancelQuoteRejectedError,be as RfqConfirmationDecision,_d as RfqConfirmationError,Zd as RfqConfirmationRejectedError,ce as RfqDirection,de as RfqErrorCode,ee as RfqExecutionStatus,Wd as RfqQuoteError,Vd as RfqQuoteRejectedError,fe as RfqRequestedSizeUnit,ge as RfqSide,he as SearchError,ab as SetupTradingApprovalsError,Bd as SplitComboPositionError,Ad as SplitMarketPositionError,zd as SplitPositionError,Ee as TransferErc20Error,ya as UpdateBalanceAllowanceError,ja as WaitForGaslessTransactionError,Za as approveErc1155ForAll,Va as approveErc20,zc as cancelAll,Bc as cancelMarketOrders,vc as cancelOrder,xc as cancelOrders,F as createApiKey,P as createBuilderApiKey,Zc as createLimitOrder,Vc as createMarketOrder,J as createOrDeriveApiKey,N as deleteApiKey,fa as deployDepositWallet,H as deriveApiKey,ld as downloadAccountingSnapshot,va as dropNotifications,Dc as estimateMarketPrice,L as fetchApiKeys,xa as fetchBalanceAllowance,R as fetchBuilderApiKeys,rb as fetchBuilderFeeRates,dc as fetchBuilderVolume,la as fetchClosedOnlyMode,Rb as fetchCommentsById,Xb as fetchEvent,$b as fetchEventLiveVolume,Zb as fetchEventTags,aa as fetchExecuteParams,Fb as fetchLastTradePrice,Hb as fetchLastTradePrices,lc as fetchMarket,pb as fetchMarketInfo,nc as fetchMarketTags,fb as fetchMidpoint,hb as fetchMidpoints,lb as fetchNegRisk,ta as fetchNotifications,pa as fetchOrder,xb as fetchOrderBook,zb as fetchOrderBooks,Ba as fetchOrderScoring,Da as fetchOrdersScoring,hd as fetchPortfolioValue,tb as fetchPrice,Jb as fetchPriceHistory,vb as fetchPrices,Ud as fetchPublicProfile,ze as fetchRelatedTagResources,xe as fetchRelatedTags,La as fetchRewardPercentages,me as fetchSeries,qe as fetchSportsMarketTypes,Bb as fetchSpread,Db as fetchSpreads,ve as fetchTag,jb as fetchTickSize,Ha as fetchTotalEarningsForUserForDay,jd as fetchTradedMarketCount,ga as fetchTransaction,ca as isWalletDeployed,ra as listAccountTrades,Pa as listActivity,bc as listBuilderLeaderboard,db as listBuilderTrades,ed as listClosedPositions,jc as listComboMarkets,fd as listComboPositions,Pb as listComments,Tb as listCommentsByUserAddress,Lb as listCurrentRewards,Vb as listEvents,pc as listMarketHolders,tc as listMarketPositions,Nb as listMarketRewards,hc as listMarkets,rc as listOpenInterest,na as listOpenOrders,bd as listPositions,ke as listSeries,oe as listSports,te as listTags,Be as listTeams,fc as listTraderLeaderboard,Na as listTrades,Ja as listUserEarningsAndMarketsConfig,Fa as listUserEarningsForDay,Md as mergeComboPosition,Ld as mergeMarketPosition,Nd as mergePositions,ae as openRfqSession,$c as placeLimitOrder,Xc as placeMarketOrder,Hc as postOrder,Ic as postOrders,Xa as prepareErc1155ApprovalForAll,Ta as prepareErc20Approval,De as prepareErc20Transfer,ia as prepareGaslessTransaction,Pc as prepareLimitOrder,Tc as prepareLimitOrderPosting,Nc as prepareMarketOrder,Rc as prepareMarketOrderPosting,Gd as prepareMergeComboPosition,Fd as prepareMergeMarketPosition,Hd as prepareMergePositions,Pd as prepareRedeemComboPosition,Od as prepareRedeemMarketPositions,Qd as prepareRedeemPositions,xd as prepareSplitComboPosition,wd as prepareSplitMarketPosition,yd as prepareSplitPosition,$a as prepareTradingApprovals,Sd as redeemPositions,nb as resolveConditionByToken,Ec as resolveEstimatedMarketPrice,T as revokeBuilderApiKey,ie as search,bb as setupTradingApprovals,Lc as signOrder,Dd as splitComboPosition,Cd as splitMarketPosition,Ed as splitPosition,re as subscribe,Fe as transferErc20,za as updateBalanceAllowance}from'../chunk-UBQO5URS.js';import'../chunk-E2CLUN5M.js';//# sourceMappingURL=index.js.map
1
+ export{Ka as ApproveErc1155ForAllError,Ga as ApproveErc20Error,Ac as CancelAllError,Cc as CancelMarketOrdersError,wc as CancelOrderError,yc as CancelOrdersError,Yd as ComboPositionStatus,Qa as CreateApiKeyError,_a as CreateBuilderApiKeyError,_c as CreateLimitOrderError,Wc as CreateMarketOrderError,Ua as CreateOrDeriveApiKeyError,Ya as DeleteApiKeyError,ya as DeployDepositWalletError,Fd as DepositToPerpsError,Sa as DeriveApiKeyError,Wd as DownloadAccountingSnapshotError,V as DropNotificationsError,Ec as EstimateMarketPriceError,Wa as FetchApiKeysError,X as FetchBalanceAllowanceError,ab as FetchBuilderApiKeysError,sb as FetchBuilderFeeRatesError,L as FetchClosedOnlyModeError,Sb as FetchCommentsByIdError,Yb as FetchEventError,ac as FetchEventLiveVolumeError,_b as FetchEventTagsError,ta as FetchExecuteParamsError,Gb as FetchLastTradePriceError,Ib as FetchLastTradePricesError,mc as FetchMarketError,qb as FetchMarketInfoError,oc as FetchMarketTagsError,gb as FetchMidpointError,ib as FetchMidpointsError,mb as FetchNegRiskError,T as FetchNotificationsError,yb as FetchOrderBookError,Ab as FetchOrderBooksError,P as FetchOrderError,$ as FetchOrderScoringError,ba as FetchOrdersScoringError,sd as FetchPerpsBookError,Ad as FetchPerpsFeesError,md as FetchPerpsInstrumentsError,od as FetchPerpsTickerError,qd as FetchPerpsTickersError,Sd as FetchPortfolioValueError,ub as FetchPriceError,Kb as FetchPriceHistoryError,wb as FetchPricesError,De as FetchPublicProfileError,jf as FetchRelatedTagResourcesError,hf as FetchRelatedTagsError,ja as FetchRewardPercentagesError,Ye as FetchSeriesError,af as FetchSportsMarketTypesError,Cb as FetchSpreadError,Eb as FetchSpreadsError,ff as FetchTagError,kb as FetchTickSizeError,fa as FetchTotalEarningsForUserForDayError,Ud as FetchTradedMarketCountError,xa as GaslessTransactionMetadataSchema,va as IsWalletDeployedError,R as ListAccountTradesError,na as ListActivityError,cc as ListBuilderLeaderboardError,eb as ListBuilderTradesError,ec as ListBuilderVolumeError,Od as ListClosedPositionsError,kc as ListComboMarketsError,Pd as ListComboPositionsError,Ub as ListCommentsByUserAddressError,Qb as ListCommentsError,Mb as ListCurrentRewardsError,Wb as ListEventsError,qc as ListMarketHoldersError,uc as ListMarketPositionsError,Ob as ListMarketRewardsError,ic as ListMarketsError,sc as ListOpenInterestError,N as ListOpenOrdersError,ud as ListPerpsCandlesError,wd as ListPerpsFundingHistoryError,yd as ListPerpsTradesError,Md as ListPositionsError,We as ListSeriesError,_e as ListSportsError,df as ListTagsError,lf as ListTeamsError,gc as ListTraderLeaderboardError,la as ListTradesError,ha as ListUserEarningsAndMarketsConfigError,da as ListUserEarningsForDayError,ue as MergeComboPositionError,te as MergeMarketPositionError,se as MergePositionsError,Cd as OpenPerpsSessionError,Le as OpenRfqSessionError,ad as PlaceLimitOrderError,Yc as PlaceMarketOrderError,Hc as PostOrderError,Ic as PostOrdersError,Ia as PrepareErc1155ApprovalForAllError,Ea as PrepareErc20ApprovalError,nf as PrepareErc20TransferError,Ba as PrepareGaslessTransactionError,Qc as PrepareLimitOrderError,Uc as PrepareLimitOrderPostingError,Oc as PrepareMarketOrderError,Sc as PrepareMarketOrderPostingError,ce as PrepareMergeComboPositionError,be as PrepareMergeMarketPositionError,ae as PrepareMergePositionsError,Ed as PreparePerpsDepositError,fe as PrepareRedeemComboPositionError,ee as PrepareRedeemMarketPositionsError,de as PrepareRedeemPositionsError,$d as PrepareSplitComboPositionError,_d as PrepareSplitMarketPositionError,Zd as PrepareSplitPositionError,Ma as PrepareTradingApprovalsError,Be as RedeemPositionsError,ob as ResolveConditionByTokenError,cb as RevokeBuilderApiKeyError,Dd as RevokePerpsCredentialsError,Ie as RfqCancelQuoteError,He as RfqCancelQuoteRejectedError,Ne as RfqConfirmationDecision,Ke as RfqConfirmationError,Je as RfqConfirmationRejectedError,Oe as RfqDirection,Pe as RfqErrorCode,Qe as RfqExecutionStatus,Ge as RfqQuoteError,Fe as RfqQuoteRejectedError,Re as RfqRequestedSizeUnit,Se as RfqSide,Ue as SearchError,Te as SearchSort,Oa as SetupTradingApprovalsError,le as SplitComboPositionError,ke as SplitMarketPositionError,je as SplitPositionError,pf as TransferErc20Error,Z as UpdateBalanceAllowanceError,jd as UpdatePerpsLeverageError,kd as UpdatePerpsMarginError,Da as WaitForGaslessTransactionError,Gd as WithdrawFromPerpsError,La as approveErc1155ForAll,Ha as approveErc20,Bc as cancelAll,Dc as cancelMarketOrders,xc as cancelOrder,zc as cancelOrders,Ra as createApiKey,$a as createBuilderApiKey,$c as createLimitOrder,Xc as createMarketOrder,Va as createOrDeriveApiKey,Za as deleteApiKey,za as deployDepositWallet,Kd as depositToPerps,Ta as deriveApiKey,Xd as downloadAccountingSnapshot,W as dropNotifications,Fc as estimateMarketPrice,Xa as fetchApiKeys,Y as fetchBalanceAllowance,bb as fetchBuilderApiKeys,tb as fetchBuilderFeeRates,fc as fetchBuilderVolume,M as fetchClosedOnlyMode,Tb as fetchCommentsById,Zb as fetchEvent,bc as fetchEventLiveVolume,$b as fetchEventTags,ua as fetchExecuteParams,Hb as fetchLastTradePrice,Jb as fetchLastTradePrices,nc as fetchMarket,rb as fetchMarketInfo,pc as fetchMarketTags,hb as fetchMidpoint,jb as fetchMidpoints,nb as fetchNegRisk,U as fetchNotifications,Q as fetchOrder,zb as fetchOrderBook,Bb as fetchOrderBooks,aa as fetchOrderScoring,ca as fetchOrdersScoring,td as fetchPerpsBook,Bd as fetchPerpsFees,nd as fetchPerpsInstruments,pd as fetchPerpsTicker,rd as fetchPerpsTickers,Td as fetchPortfolioValue,vb as fetchPrice,Lb as fetchPriceHistory,xb as fetchPrices,Ee as fetchPublicProfile,kf as fetchRelatedTagResources,if as fetchRelatedTags,ka as fetchRewardPercentages,Ze as fetchSeries,bf as fetchSportsMarketTypes,Db as fetchSpread,Fb as fetchSpreads,gf as fetchTag,lb as fetchTickSize,ga as fetchTotalEarningsForUserForDay,Vd as fetchTradedMarketCount,Aa as fetchTransaction,wa as isWalletDeployed,S as listAccountTrades,oa as listActivity,dc as listBuilderLeaderboard,fb as listBuilderTrades,Qd as listClosedPositions,lc as listComboMarkets,Rd as listComboPositions,Rb as listComments,Vb as listCommentsByUserAddress,Nb as listCurrentRewards,Xb as listEvents,rc as listMarketHolders,vc as listMarketPositions,Pb as listMarketRewards,jc as listMarkets,tc as listOpenInterest,O as listOpenOrders,vd as listPerpsCandles,xd as listPerpsFundingHistory,zd as listPerpsTrades,Nd as listPositions,Xe as listSeries,$e as listSports,ef as listTags,mf as listTeams,hc as listTraderLeaderboard,ma as listTrades,ia as listUserEarningsAndMarketsConfig,ea as listUserEarningsForDay,we as mergeComboPosition,ve as mergeMarketPosition,xe as mergePositions,Hd as openPerpsSession,Me as openRfqSession,bd as placeLimitOrder,Zc as placeMarketOrder,Jc as postOrder,Kc as postOrders,Ja as prepareErc1155ApprovalForAll,Fa as prepareErc20Approval,of as prepareErc20Transfer,Ca as prepareGaslessTransaction,Rc as prepareLimitOrder,Vc as prepareLimitOrderPosting,Pc as prepareMarketOrder,Tc as prepareMarketOrderPosting,qe as prepareMergeComboPosition,pe as prepareMergeMarketPosition,re as prepareMergePositions,Jd as preparePerpsDeposit,ze as prepareRedeemComboPosition,ye as prepareRedeemMarketPositions,Ae as prepareRedeemPositions,he as prepareSplitComboPosition,ge as prepareSplitMarketPosition,ie as prepareSplitPosition,Na as prepareTradingApprovals,Ce as redeemPositions,pb as resolveConditionByToken,Gc as resolveEstimatedMarketPrice,db as revokeBuilderApiKey,Id as revokePerpsCredentials,Ve as search,Pa as setupTradingApprovals,Nc as signOrder,ne as splitComboPosition,me as splitMarketPosition,oe as splitPosition,cf as subscribe,qf as transferErc20,_ as updateBalanceAllowance,Ld as withdrawFromPerps}from'../chunk-FSNACMPO.js';import'../chunk-E2CLUN5M.js';//# sourceMappingURL=index.js.map
2
2
  //# sourceMappingURL=index.js.map
@@ -0,0 +1,2 @@
1
+ import {k,e,d,j,c,b,a,f,g,h as h$1,i}from'./chunk-E2CLUN5M.js';import {PaginationCursorSchema,TransactionIdSchema,EvmAddressSchema,BuilderCodeSchema,TokenIdSchema,CtfConditionIdSchema,OrderSideSchema,CommentParentEntityTypeSchema,EventIdSchema,CommentIdSchema,IsoDateTimeStringSchema,IsoCalendarDateStringSchema,PositionIdSchema,OrderType,PositiveDecimalNumberSchema,OrderSide,TxHashSchema,ComboConditionIdSchema,MarketIdSchema,toDecimalString,toComboConditionId,toPositionId,toPaginationCursor}from'@polymarket/bindings';import {AssetTypeSchema,PriceHistoryIntervalSchema,SignatureType,AssetType,ClosedOnlyModeSchema,OpenOrdersPageSchema,END_CURSOR,OpenOrderSchema,ClobTradesPageSchema,NotificationsResponseSchema,BalanceAllowanceResponseSchema,OrderScoringResponseSchema,OrdersScoringResponseSchema,UserEarningsPageSchema,TotalUserEarningsResponseSchema,UserRewardsEarningsPageSchema,RewardsPercentagesSchema,ApiKeyCredsSchema,ApiKeysResponseSchema,BuilderApiKeyCredsSchema,BuilderApiKeysResponseSchema,PaginatedBuilderTradesSchema,MidpointSchema,MidpointsSchema,FetchTickSizeResponseSchema,FetchNegRiskResponseSchema,ResolveConditionByTokenResponseSchema,FetchMarketInfoResponseSchema,FetchBuilderFeeRatesResponseSchema,PriceSchema,PricesSchema,FetchOrderBookResponseSchema,OrderBooksSchema,SpreadSchema,SpreadsSchema,LastTradePriceSchema,LastTradePricesSchema,PriceHistorySchema,PaginatedCurrentRewardsSchema,PaginatedMarketRewardsSchema,CancelOrdersResponseSchema,OrderResponseSchema,OrderResponsesSchema}from'@polymarket/bindings/clob';import {isHexString,expectNonEmptyArray,isPrivateKey,expectEvmAddress,PolymarketError,isSameEvmAddress,never,unwrap,invariant,delay,expectEvmSignature,expectHexString,ZERO_ADDRESS,expectErc1271Signature,ResultAsync,setNonBlockingInterval,setNonBlockingTimeout,expectPrivateKey,isPresent,ok as ok$1,err,expectPresent}from'@polymarket/types';import {z}from'zod';import {WalletType,SeriesIdSchema,ListCommentsResponseSchema,ListEventsKeysetResponseSchema,EventSchema,FetchEventTagsResponseSchema,ListMarketsKeysetResponseSchema,FetchMarketTagsResponseSchema,MarketSchema,PublicProfileSchema,PublicSearchResponseSchema,ListSeriesResponseSchema,SeriesSchema,ListSportsMetadataResponseSchema,SportsMarketTypesResponseSchema,ListTagsResponseSchema,TagSchema,ListRelatedTagsResponseSchema,ListRelatedTagResourcesResponseSchema,ListTeamsResponseSchema}from'@polymarket/bindings/gamma';import {AbiFunction,Hash,Bytes,AbiParameters,TypedData,Secp256k1,Address,ContractAddress,Signature}from'ox';import Nt from'ky';import {SideSchema,ActivityTypeSchema,TimePeriodSchema,LeaderboardOrderBySchema,LeaderboardCategorySchema,ComboPositionStatusSchema,ListTradesResponseSchema,ListActivityResponseSchema,FetchEventLiveVolumeResponseSchema,ListBuilderLeaderboardResponseSchema,ListBuilderVolumeResponseSchema,ListTraderLeaderboardResponseSchema,ListMarketHoldersResponseSchema,ListOpenInterestResponseSchema,ListMarketPositionsResponseSchema,ListPositionsResponseSchema,ListClosedPositionsResponseSchema,ListComboPositionsResponseSchema,FetchPortfolioValueResponseSchema,TradedSchema}from'@polymarket/bindings/data';export{ComboPositionStatus as Yd}from'@polymarket/bindings/data';import {RelayerTransactionType,RelayerExecuteRequestSchema,RelayerTransactionState,RelayerExecuteParamsSchema,RelayerDeployedResponseSchema,GaslessTransactionSchema,RelayerExecuteResponseSchema}from'@polymarket/bindings/relayer';import {ListComboMarketsResponseSchema}from'@polymarket/bindings/rfq';export{RfqConfirmationDecision as Ne,RfqDirection as Oe,RfqErrorCode as Pe,RfqExecutionStatus as Qe,RfqRequestedSizeUnit as Re,RfqSide as Se}from'@polymarket/bindings/rfq';import {PerpsPnlIntervalSchema,PerpsWithdrawalStatusSchema,PerpsDepositStatusSchema,PerpsInstrumentIdSchema,PerpsClientOrderIdSchema,PerpsOrderIdSchema,PerpsDecimalInputSchema,PerpsTimeInForce,PerpsCommandAckSchema,PerpsInstrumentCategorySchema,PerpsInstrumentTypeSchema,PerpsKlineIntervalSchema,PerpsTradeIdSchema,PerpsPostOrderAckSchema,PerpsCancelOrderResultSchema,FetchPerpsBalancesResponseSchema,FetchPerpsPortfolioResponseSchema,FetchPerpsAccountConfigResponseSchema,FetchPerpsOpenOrdersResponseSchema,FetchPerpsOrdersResponseSchema,ListPerpsFillsResponseSchema,ListPerpsFundingPaymentsResponseSchema,ListPerpsDepositsResponseSchema,ListPerpsWithdrawalsResponseSchema,ListPerpsEquityHistoryResponseSchema,ListPerpsPnlHistoryResponseSchema,FetchPerpsInstrumentsResponseSchema,FetchPerpsTickersResponseSchema,FetchPerpsStatisticsResponseSchema,PerpsBookSchema,FetchPerpsCandlesResponseSchema,FetchPerpsFundingHistoryResponseSchema,FetchPerpsTradesResponseSchema,FetchPerpsFeesResponseSchema,PerpsDeleteProxyResponseSchema,PerpsWithdrawResponseSchema,PerpsCreateProxyResponseSchema,PerpsCredentialsResponseSchema}from'@polymarket/bindings/perps';import {encode}from'@msgpack/msgpack';import {PerpsSessionUpdateEventSchema}from'@polymarket/bindings/subscriptions';import {pushable}from'it-pushable';import sf from'it-merge';function l(e,r){let t=r.safeParse(e);if(t.success)return t.data;throw a.fromZodError(t.error)}var A=z.number().int().positive(),Ht=z.object({offset:z.number().int().min(0),pageSize:A});function T(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 f=await unwrap(e(a));if(yield f,!f.hasMore)return;a=f.nextCursor;}}}}return n()}function F(e){return toPaginationCursor(btoa(JSON.stringify(Ht.parse(e))))}function U(e,r){if(e===void 0)return {offset:0,pageSize:r};try{return Ht.parse(JSON.parse(atob(e)))}catch(t){throw new a("Invalid pagination cursor",{cause:t})}}function y(e){return function(t){return ResultAsync.fromPromise(t.json(),()=>new b(`Received non-JSON response from ${t.url}`)).andThen(o=>ma(t.url,e,o))}}function _t(e){return ResultAsync.fromPromise(e.blob(),()=>new b(`Received unreadable binary response from ${e.url}`))}function ma(e,r,t){let o=r.safeParse(t);return o.success?ok$1(o.data):err(b.fromZodError(o.error,{endpoint:e}))}var Gt=class{#e;constructor({url:r}){this.#e=r;}async ethCall(r){let t=await this.#n({jsonrpc:"2.0",id:1,method:"eth_call",params:[{to:r.to,data:r.data},"latest"]});if("error"in t)throw new d(`JSON-RPC eth_call failed: ${t.error.message}`,{cause:t.error,status:200});if(typeof t.result!="string")throw new b("Expected JSON-RPC eth_call result to be a hex string");if(!Jt(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#r(r){if(r.length===1)return [await this.ethCall(r[0])];try{return await this.#t(r)}catch(t){if(!(t instanceof d)||t.status<500)throw t;let o=Math.ceil(r.length/2),[n,s]=await Promise.all([this.#r(r.slice(0,o)),this.#r(r.slice(o))]);return [...n,...s]}}async#t(r){let t=await this.#o(r.map((n,s)=>({jsonrpc:"2.0",id:s+1,method:"eth_call",params:[{to:n.to,data:n.data},"latest"]}))),o=new Map;for(let n of t){if("error"in n&&n.id===null)throw new d(`JSON-RPC eth_call failed: ${n.error.message}`,{cause:n.error,status:200});n.id!==null&&o.set(n.id,n);}return r.map((n,s)=>{let a=s+1,f=o.get(a);if(f===void 0)throw new b("Expected JSON-RPC batch response for every request");if("error"in f)throw new d(`JSON-RPC eth_call failed: ${f.error.message}`,{cause:f.error,status:200});return la(f.result)})}async#n(r){let t;try{t=await Nt.post(this.#e,{json:r,throwHttpErrors:!1});}catch(n){throw c.fromError(n)}if(!t.ok)throw new d(`JSON-RPC request to ${this.#e} failed with status ${t.status}`,{status:t.status});let o;try{o=await t.json();}catch(n){throw new b("Expected JSON-RPC response body to be JSON",{cause:n})}if(!Kt(o))throw new b("Unexpected JSON-RPC response shape");return o}async#o(r){let t;try{t=await Nt.post(this.#e,{json:r,throwHttpErrors:!1});}catch(n){throw c.fromError(n)}if(!t.ok)throw new d(`JSON-RPC request to ${this.#e} failed with status ${t.status}`,{status:t.status});let o;try{o=await t.json();}catch(n){throw new b("Expected JSON-RPC response body to be JSON",{cause:n})}if(!Array.isArray(o)||!o.every(n=>Kt(n)))throw new b("Unexpected JSON-RPC response shape");return o}};function $t(e){if(!(e instanceof d)||!Vt(e.cause))return false;let r=[e.cause.message,ya(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 Kt(e){return !Yt(e)||e.jsonrpc!=="2.0"?false:"error"in e?Vt(e.error):"result"in e}function Vt(e){return Yt(e)&&typeof e.code=="number"&&typeof e.message=="string"}function Yt(e){return typeof e=="object"&&e!==null}function Jt(e){return /^0x[a-fA-F0-9]*$/.test(e)}function la(e){if(typeof e!="string"||!Jt(e))throw new b("Expected JSON-RPC eth_call result to be a hex string");return e}function ya(e){if(e===void 0)return "";if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return ""}}function Wf(e,r,t){return {signer:r,wallet:t,walletType:La(e,r,t)}}function pe(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 Zt(e){let r=pe(e.walletType);return {maker:e.wallet,signatureType:r,signer:r===SignatureType.POLY_1271?e.wallet:e.signer}}var ga="3d3d606380380380913d393d73%s5af4602a57600080fd5b602d8060366000396000f3363d3d373d3d3d363d73%s5af43d82803e903d91602b57fd5bf352e831dd00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000000";function Pa(e){let r=ga.replace("%s",e.proxyFactory.slice(2).toLowerCase()).replace("%s",e.proxyImplementation.slice(2).toLowerCase());return expectHexString(Hash.keccak256(`0x${r}`))}function Ea(e,r){return expectEvmAddress(ContractAddress.fromCreate2({bytecodeHash:Pa(r),from:r.proxyFactory,salt:Hash.keccak256(AbiParameters.encodePacked(["address"],[e]))}))}function Ra(e,r){return expectEvmAddress(ContractAddress.fromCreate2({bytecodeHash:r.safeInitCodeHash,from:r.safeFactory,salt:Hash.keccak256(AbiParameters.encode([{name:"address",type:"address"}],[e]))}))}var ha="0xcc3735a920a3ca505d382bbc545af43d6000803e6038573d6000fd5b3d6000f3",Sa="0x5155f3363d3d373d3d363d7f360894a13ba1a3210667c828492db98dca3e2076",Ta=0x61003d3d8160233d3973n;function Qt(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:va(r.depositWalletImplementation,o),from:r.depositWalletFactory,salt:Hash.keccak256(o)}))}var xa="0xb3582b35133d50545afa5036515af43d6000803e604d573d6000fd5b3d6000f3",Ca="0x1b60e01b36527fa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6c",ka="0x60195155f3363d3d373d3d363d602036600436635c60da",ba=0x6100523d8160233d3973n,Ia="0x49493a4d";function Xt(e,r){let t=expectHexString(`0x${e.slice(2).padStart(64,"0")}`),o=AbiParameters.encode([{type:"address"},{type:"bytes32"}],[r.depositWalletFactory,t]);return expectEvmAddress(ContractAddress.fromCreate2({bytecodeHash:qa(r.depositWalletBeacon,o),from:r.depositWalletFactory,salt:Hash.keccak256(o)}))}function va(e,r){let t=BigInt((r.length-2)/2),o=Ta+(t<<56n);return expectHexString(Hash.keccak256(Bytes.concat(Bytes.fromNumber(o,{size:10}),Bytes.fromHex(e),Bytes.fromHex("0x6009"),Bytes.fromHex(Sa),Bytes.fromHex(ha),Bytes.fromHex(r)),{as:"Hex"}))}function qa(e,r){let t=BigInt((r.length-2)/2),o=ba+(t<<56n);return expectHexString(Hash.keccak256(Bytes.concat(Bytes.fromNumber(o,{size:10}),Bytes.fromHex(e),Bytes.fromHex(ka),Bytes.fromHex(Ca),Bytes.fromHex(xa),Bytes.fromHex(r)),{as:"Hex"}))}async function Aa(e,r){try{let t=await e.ethCall({to:r,data:Ia});return wa(t)}catch(t){if($t(t))return ZERO_ADDRESS;throw t}}async function Oa(e,r){let t=await Aa(e,r);return !isSameEvmAddress(t,ZERO_ADDRESS)}async function eo(e,r,t){return await Oa(e,t.depositWalletFactory)?Xt(r,t):Qt(r,t)}function wa(e){return e.length<66?ZERO_ADDRESS:expectEvmAddress(`0x${e.slice(-40)}`)}function La(e,r,t){if(isSameEvmAddress(t,r))return WalletType.EOA;let o=e.walletDerivation;if(isSameEvmAddress(t,Xt(r,o)))return WalletType.DEPOSIT_WALLET;if(isSameEvmAddress(t,Qt(r,o)))return WalletType.DEPOSIT_WALLET;if(isSameEvmAddress(t,Ra(r,o)))return WalletType.GNOSIS_SAFE;if(isSameEvmAddress(t,Ea(r,o)))return WalletType.POLY_PROXY;never(`Wallet ${t} does not match the signer ${r} or any supported deterministic wallet address.`);}function P(e,r){if(Ma(r))return Fa(e,r.exceptions);let t=new URLSearchParams;for(let[o,n]of Object.entries(r)){let s=e[o];if(s!==void 0){if(ro(s)){for(let a of s)t.append(n,Oe(a));continue}t.append(n,Oe(s));}}return t}function h(e={}){return {format:"snake_case",exceptions:e}}function H(e){let r=new URLSearchParams;for(let[t,o]of Object.entries(e))if(o!==void 0){if(Array.isArray(o)){r.append(t,o.map(Oe).join(","));continue}r.append(t,Oe(o));}return r}function Ma(e){return "format"in e}function Fa(e,r){let t=new URLSearchParams;for(let[o,n]of Object.entries(e)){if(n===void 0)continue;let s=r[o]??Ba(o);if(ro(n)){for(let a of n)t.append(s,Oe(a));continue}t.append(s,Oe(n));}return t}function ro(e){return Array.isArray(e)}function Ba(e){return e.replace(/[A-Z]/g,r=>`_${r.toLowerCase()}`)}function Oe(e){return String(e)}var rg=k(e,d,j,c,b);async function tg(e){return (await unwrap(e.secureClob.get("/auth/ban-status/closed-only").andThen(y(ClosedOnlyModeSchema)))).closedOnly}var Ya=z.object({tokenId:z.string().optional(),cursor:PaginationCursorSchema.optional(),id:z.string().optional(),market:z.string().optional()}).default({}),og=k(e,d,j,c,b,a);function ng(e,r){let{cursor:t,...o}=l(r,Ya);return T(n=>e.secureClob.get("/data/orders",{params:P({...o,nextCursor:n},h({tokenId:"asset_id"}))}).andThen(y(OpenOrdersPageSchema)).map(s=>({items:s.data,hasMore:s.nextCursor!==END_CURSOR,nextCursor:s.nextCursor===END_CURSOR?void 0:toPaginationCursor(s.nextCursor),totalCount:s.count})),t)}var Ja=z.object({orderId:z.string()}),sg=k(e,d,j,c,b,a);async function ag(e,r){let t=l(r,Ja);return unwrap(e.secureClob.get(`/data/order/${t.orderId}`).andThen(y(OpenOrderSchema)))}var Za={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()},Qa=z.object(Za).default({}),ig=k(e,d,j,c,b,a);function pg(e,r){let{cursor:t,...o}=l(r,Qa);return T(n=>e.secureClob.get("/data/trades",{params:P({...o,nextCursor:n},h({tokenId:"asset_id"}))}).andThen(y(ClobTradesPageSchema)).map(s=>({items:s.data,hasMore:s.nextCursor!==END_CURSOR,nextCursor:s.nextCursor===END_CURSOR?void 0:toPaginationCursor(s.nextCursor),totalCount:s.count})),t)}var cg=k(e,d,j,c,b),Xa=z.object({ids:z.array(z.string()).min(1)});async function dg(e){let r=pe(e.account.walletType);return unwrap(e.secureClob.get("/notifications",{params:P({signatureType:r},h())}).andThen(y(NotificationsResponseSchema)))}var ug=k(e,d,j,c,b,a);async function mg(e,r){let t=l(r,Xa),o=pe(e.account.walletType),n=P({ids:t.ids.join(","),signatureType:o},h());await unwrap(e.secureClob.del("/notifications",{params:n}));}var ei=z.object({assetType:AssetTypeSchema,tokenId:z.string().optional()}),lg=k(e,d,j,c,b,a);async function Ur(e,r){let t=l(r,ei),o=pe(e.account.walletType);return unwrap(e.secureClob.get("/balance-allowance",{params:P({...t,signatureType:o},h())}).andThen(y(BalanceAllowanceResponseSchema)))}var ri=z.object({assetType:AssetTypeSchema,tokenId:z.string().optional()}),yg=k(e,d,j,c,b,a);async function oo(e,r){let t=l(r,ri),o=pe(e.account.walletType),n=P({...t,signatureType:o},h());return await unwrap(e.secureClob.get("/balance-allowance/update",{params:n})),Ur(e,t)}var ti=z.object({orderId:z.string()}),fg=k(e,d,j,c,b,a);async function gg(e,r){let t=l(r,ti);return (await unwrap(e.secureClob.get("/order-scoring",{params:P(t,h())}).andThen(y(OrderScoringResponseSchema)))).scoring}var oi=z.object({orderIds:z.array(z.string())}),Pg=k(e,d,j,c,b,a);async function Eg(e,r){let o=l(r,oi).orderIds;return unwrap(e.secureClob.post("/orders-scoring",{json:o}).andThen(y(OrdersScoringResponseSchema)))}var no=z.object({cursor:PaginationCursorSchema.optional(),date:z.string()}),Rg=k(e,d,j,c,b,a);function hg(e,r){let{cursor:t,...o}=l(r,no),n=pe(e.account.walletType);return T(s=>e.secureClob.get("/rewards/user",{params:P({...o,nextCursor:s,signatureType:n},h())}).andThen(y(UserEarningsPageSchema)).map(a=>({items:a.data,hasMore:a.nextCursor!==END_CURSOR,nextCursor:a.nextCursor===END_CURSOR?void 0:toPaginationCursor(a.nextCursor),totalCount:a.count})),t)}var Sg=k(e,d,j,c,b,a);async function Tg(e,r){let t=l(r,no),o=pe(e.account.walletType);return unwrap(e.secureClob.get("/rewards/user/total",{params:P({...t,signatureType:o},h())}).andThen(y(TotalUserEarningsResponseSchema)))}var ni=z.object({cursor:PaginationCursorSchema.optional(),date:z.string(),noCompetition:z.boolean().optional(),orderBy:z.string().optional(),pageSize:A.max(500).default(100),position:z.string().optional()}),xg=k(e,d,j,c,b,a);function Cg(e,r){let{cursor:t,...o}=l(r,ni),n=pe(e.account.walletType);return T(s=>e.secureClob.get("/rewards/user/markets",{params:P({...o,nextCursor:s,signatureType:n},h())}).andThen(y(UserRewardsEarningsPageSchema)).map(a=>({items:a.data,hasMore:a.nextCursor!==END_CURSOR,nextCursor:a.nextCursor===END_CURSOR?void 0:toPaginationCursor(a.nextCursor),totalCount:a.count})),t)}var kg=k(e,d,j,c,b);async function bg(e){let r=pe(e.account.walletType);return unwrap(e.secureClob.get("/rewards/user/percentages",{params:P({signatureType:r},h())}).andThen(y(RewardsPercentagesSchema)))}var pi=z.enum(["TIMESTAMP","TOKENS","CASH"]),ci=z.enum(["ASC","DESC"]),di=z.enum(["CASH","TOKENS"]),ui=z.object({cursor:PaginationCursorSchema.optional(),pageSize:A.default(20),takerOnly:z.boolean().optional(),filterType:di.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()}).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"]}),mi=z.object({cursor:PaginationCursorSchema.optional(),pageSize:A.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().optional(),end:z.number().int().optional(),sortBy:pi.optional(),sortDirection:ci.optional(),side:SideSchema.optional()}).refine(e=>!(e.market&&e.eventId),{message:"Provide market or eventId, not both",path:["eventId"]}),Bg=k(e,d,c,b,a);function Ug(e,r={}){let{cursor:t,pageSize:o,...n}=l(r,ui);return T(s=>{let a=U(s,o);return e.data.get("/trades",{params:H({...n,limit:a.pageSize+1,offset:a.offset})}).andThen(y(ListTradesResponseSchema)).map(f=>{let g=f.length>a.pageSize;return {items:f.slice(0,a.pageSize),hasMore:g,nextCursor:g?F({offset:a.offset+a.pageSize,pageSize:a.pageSize}):void 0}})},t)}var Dg=k(e,d,c,b,a);function zg(e,r){let{cursor:t,pageSize:o,...n}=l(r,mi);return T(s=>{let a=U(s,o);return e.data.get("/activity",{params:H({...n,limit:a.pageSize+1,offset:a.offset})}).andThen(y(ListActivityResponseSchema)).map(f=>{let g=f.length>a.pageSize;return {items:f.slice(0,a.pageSize),hasMore:g,nextCursor:g?F({offset:a.offset+a.pageSize,pageSize:a.pageSize}):void 0}})},t)}var yi=64,fi=/^0x[0-9a-fA-F]{62}$/,gi=/^0x[0-9a-fA-F]{64}$/,Dr="0x0000000000000000000000000000000000000000000000000000000000000000",Pi=AbiFunction.from("function approve(address spender, uint256 amount)"),po=AbiFunction.from("function allowance(address owner, address spender) view returns (uint256)"),Ei=AbiFunction.from("function transfer(address recipient, uint256 amount)"),Ri=AbiFunction.from("function deposit(address token, uint256 amount, address to)"),hi=AbiFunction.from("function setApprovalForAll(address operator, bool approved)"),co=AbiFunction.from("function isApprovedForAll(address account, address operator) view returns (bool)"),uo=AbiFunction.from("function balanceOf(address account, uint256 id) view returns (uint256)"),mo=AbiFunction.from("function balanceOfBatch(address[] accounts, uint256[] ids) view returns (uint256[])"),Si=AbiFunction.from("function splitPosition(address collateralToken, bytes32 parentCollectionId, bytes32 conditionId, uint256[] partition, uint256 amount)"),Ti=AbiFunction.from("function mergePositions(address collateralToken, bytes32 parentCollectionId, bytes32 conditionId, uint256[] partition, uint256 amount)"),xi=AbiFunction.from("function redeemPositions(address collateralToken, bytes32 parentCollectionId, bytes32 conditionId, uint256[] indexSets)"),Ci=AbiFunction.from("function split(bytes31 conditionId, uint256 amount)"),ki=AbiFunction.from("function merge(bytes31 conditionId, uint256 amount)"),bi=AbiFunction.from("function redeem(bytes31 conditionId, uint256 outcomeIndex, uint256 amount)"),Ii=AbiFunction.from("function prepareCondition(uint256[] legs) returns (bytes31)"),vi=AbiFunction.from("function multiSend(bytes)"),qi=AbiFunction.from("function proxy((uint8 typeCode, address to, uint256 value, bytes data)[] calls) returns (bytes[])"),lo=[1n,2n],Ai=[1n,2n],Y=(1n<<256n)-1n,Ng=k(a);function dr(e,r,t){if(t<0n)throw new a("Approval amount must be non-negative");if(t>Y)throw new a("Approval amount exceeds uint256 range");return {data:Oi(r,t),to:e}}function yo(e,r,t){return {data:AbiFunction.encodeData(po,[r,t]),to:e}}function fo(e){return AbiFunction.decodeResult(po,e)}function ur(e,r,t){return {data:wi(r,t),to:e}}function go(e,r,t){return {data:AbiFunction.encodeData(co,[r,t]),to:e}}function Po(e){return AbiFunction.decodeResult(co,e)}function Eo(e,r,t){return {data:AbiFunction.encodeData(uo,[r,ge(BigInt(t),"Position ID")]),to:e}}function Ro(e){return AbiFunction.decodeResult(uo,e)}function zr(e,r,t){return {data:AbiFunction.encodeData(mo,[t.map(()=>r),t.map(o=>ge(BigInt(o),"id"))]),to:e}}function jr(e){return AbiFunction.decodeResult(mo,e)}var Gg=k(a);function Hr(e,r,t){if(t<0n)throw new a("Transfer amount must be non-negative");if(t>Y)throw new a("Transfer amount exceeds uint256 range");return {data:Li(r,t),to:e}}var Kg=k(a);function ho(e,r,t,o){if(t<=0n)throw new a("Perps deposit amount must be positive");return {data:AbiFunction.encodeData(Ri,[r,ge(t,"Perps deposit amount"),o]),to:e}}var $g=k(a),Vg=k(a);function So(e,r,t,o){return {data:Mi(r,t,o),to:e}}var Yg=k(a);function To(e,r,t,o){return {data:Fi(r,t,o),to:e}}function xo(e,r,t){return {data:Bi(r,t),to:e}}var Jg=k(a);function Co(e,r,t){return {data:AbiFunction.encodeData(Ci,[_r(r),ge(t,"Split amount")]),to:e}}var Zg=k(a);function ko(e,r,t){return {data:AbiFunction.encodeData(ki,[_r(r),ge(t,"Merge amount")]),to:e}}var Qg=k(a);function bo(e,r,t,o){return {data:AbiFunction.encodeData(bi,[_r(r),BigInt(Ui(t)),ge(o,"Redeem amount")]),to:e}}var Xg=k(a);function Wr(e,r){return {data:AbiFunction.encodeData(Ii,[r.map(t=>ge(t,"Leg position ID"))]),to:e}}function Oi(e,r){return invariant(r>=0n,"Approval amount must be non-negative"),AbiFunction.encodeData(Pi,[e,r])}function wi(e,r){return AbiFunction.encodeData(hi,[e,r])}function Li(e,r){return AbiFunction.encodeData(Ei,[e,r])}function Mi(e,r,t){return AbiFunction.encodeData(Si,[e,Dr,r,lo,ge(t,"Split amount")])}function Fi(e,r,t){return AbiFunction.encodeData(Ti,[e,Dr,r,lo,ge(t,"Merge amount")])}function Bi(e,r){return AbiFunction.encodeData(xi,[e,Dr,r,Ai])}function ge(e,r){if(e<0n)throw new a(`${r} must be non-negative`);if(e>Y)throw new a(`${r} exceeds uint256 range`);return e}function _r(e){if(fi.test(e))return e.toLowerCase();if(gi.test(e)){let r=e.toLowerCase();if(r.endsWith("00")||r.endsWith("01"))return r.slice(0,yi)}throw new a("Protocol v2 condition ID must be bytes31, or bytes32 with a binary outcome byte")}function Ui(e){if(e!==0&&e!==1)throw new a("Protocol v2 outcome index must be 0 or 1");return e}function Io(e){return AbiFunction.encodeData(qi,[e.map(r=>({typeCode:1,to:r.to,value:r.value??0n,data:r.data}))])}function vo(e){let r=e.map(t=>Di(t));return AbiFunction.encodeData(vi,[r.length===0?"0x":AbiParameters.encodePacked(Array.from({length:r.length},()=>"bytes"),r)])}function Di(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 oP=k(e,d,f,g,c,b,a);function _(e,r="Expected a TransactionHandle"){return invariant(typeof e=="object"&&e!==null&&"transactionHash"in e&&"transactionId"in e&&"wait"in e&&typeof e.wait=="function",r),e}k(h$1,j);k(h$1,j);function pP(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 W(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 qo(){return {kind:"requestAddress"}}function N(e,r){return {chainId:e,...r}}var Zi=[{name:"chainId",type:"uint256"},{name:"verifyingContract",type:"address"}],Qi=[{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"}],Xi="DepositWallet",ep="1",rp=600,tp=[{name:"target",type:"address"},{name:"value",type:"uint256"},{name:"data",type:"bytes"}],op=[{name:"wallet",type:"address"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"},{name:"calls",type:"Call[]"}],np=z.object({address:z.string(),type:z.enum(RelayerTransactionType)}),xP=k(e,d,c,b,a);async function $r(e,r){let t=l(r,np);return unwrap(e.relayer.get("/v1/account/transactions/params",{params:P(t,{address:"address",type:"type"})}).andThen(y(RelayerExecuteParamsSchema)))}var sp=z.object({transactionId:TransactionIdSchema}),ap=z.object({wallet:EvmAddressSchema,type:z.enum(WalletType)}),CP=k(e,d,c,b,a);async function kP(e,r){let t=await ip(e,r);return t.type===WalletType.EOA?false:unwrap(e.relayer.get("/deployed",{params:P({address:t.wallet,type:t.type===WalletType.DEPOSIT_WALLET?RelayerTransactionType.WALLET:void 0},{address:"address",type:"type"})}).andThen(y(RelayerDeployedResponseSchema)).map(({deployed:o})=>o))}async function ip(e,r){if(r!==void 0)return l(r,ap);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 eo(e.rpc,e.account.signer,e.environment.walletDerivation),type:WalletType.DEPOSIT_WALLET}}var G=z.string().max(500),Ao=10,bP=k(e,d,c,b,a);async function IP(e){return invariant(e.supportsGasless,"Deposit Wallet deployment requires a Relayer API Key or Builder API Key in the client configuration."),yr(e,{from:e.account.signer,metadata:"Deploy Deposit Wallet",to:e.environment.walletDerivation.depositWalletFactory,type:RelayerTransactionType.WALLET_CREATE})}async function pp(e,r){let t=l(r,sp);return unwrap(e.relayer.get(`/v1/account/transactions/${t.transactionId}`).andThen(y(GaslessTransactionSchema)))}var cp=z.object({data:z.custom(isHexString),to:EvmAddressSchema,value:z.bigint().optional()}),dp=z.object({calls:z.array(cp).min(1).transform(e=>expectNonEmptyArray(e)),metadata:G}),vP=k(e,d,c,b,a);async function J(e,r){let t=l(r,dp);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 qo());invariant(o===e.account.signer,"Wallet client address does not match the authenticated signer");for(let n=0;n<=Ao;n+=1)try{switch(e.account.walletType){case WalletType.POLY_PROXY:return yield*up(e,t);case WalletType.DEPOSIT_WALLET:return yield*mp(e,t);case WalletType.GNOSIS_SAFE:return yield*lp(e,t)}invariant(!1,"Unsupported wallet type for gasless transaction");}catch(s){if(!yp(s)||n===Ao)throw s;await delay(e.environment.relayerPollFrequencyMs);}invariant(false,"Expected gasless transaction retry loop to return");}.call(null)}async function*up(e,r){let t=await $r(e,{address:e.account.signer,type:RelayerTransactionType.PROXY}),o=e.environment.walletDerivation.proxyFactory,n=Io(r.calls),s="0",a="0",f="10000000",g=e.environment.contracts.relayHub,L=ZERO_ADDRESS,I=Sp(e.account.signer,o,n,s,a,f,t.nonce,g,L),$=expectEvmSignature(yield Lo(I));return yr(e,{data:n,from:e.account.signer,metadata:r.metadata,nonce:t.nonce,proxyWallet:e.account.wallet,signature:$,signatureParams:{gasLimit:f,gasPrice:a,relay:L,relayHub:g,relayerFee:s},to:o,type:RelayerTransactionType.PROXY})}async function*mp(e,r){let t=await $r(e,{address:e.account.signer,type:RelayerTransactionType.WALLET}),o=r.calls.map(fp),n=`${Math.floor(Date.now()/1e3)+rp}`,s=expectEvmSignature(yield hp(gp({calls:o,chainId:e.environment.chainId,deadline:n,nonce:t.nonce,wallet:e.account.wallet}))),a={depositWalletParams:{calls:o,deadline:n,depositWallet:e.account.wallet},from:e.account.signer,metadata:r.metadata,nonce:t.nonce,signature:s,to:e.environment.walletDerivation.depositWalletFactory,type:RelayerTransactionType.WALLET};return yr(e,a)}async function*lp(e,r){let t=await $r(e,{address:e.account.signer,type:RelayerTransactionType.SAFE}),o=Pp(r.calls,e.environment.contracts.safeMultisend),n=Rp({chainId:e.environment.chainId,data:o.data,nonce:t.nonce,operation:o.operation,safeAddress:e.account.wallet,to:o.to,value:o.value}),s=expectEvmSignature(yield Lo(expectHexString(TypedData.getSignPayload(n))));return yr(e,{data:o.data,from:e.account.signer,metadata:r.metadata,nonce:t.nonce,proxyWallet:e.account.wallet,signature:Tp(s),signatureParams:Ep(o.operation),to:o.to,type:RelayerTransactionType.SAFE,value:o.value>0n?`${o.value}`:void 0})}async function yr(e,r){let t=l(r,RelayerExecuteRequestSchema),o=await unwrap(e.relayer.post("/submit",{json:t}).andThen(y(RelayerExecuteResponseSchema)));return new Nr(e,o)}function yp(e$1){if(e$1 instanceof e)return true;if(!(e$1 instanceof d)||e$1.status!==400)return false;if(/wallet busy/i.test(e$1.message)&&/active action/i.test(e$1.message)||/wallet has in-flight action/i.test(e$1.message))return true;let r=/batch nonce\s+(\d+)\s+does not match on-chain nonce\s+(\d+)/i.exec(e$1.message);if(r===null)return false;let t=r[1],o=r[2];return t===void 0||o===void 0?false:BigInt(t)<BigInt(o)}function fp(e){return {data:e.data,target:e.to,value:`${e.value??0n}`}}function gp(e){return {domain:{chainId:e.chainId,name:Xi,verifyingContract:e.wallet,version:ep},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:op,Call:tp}}}function Pp(e,r){if(e.length===1){let[t]=e;return {data:t.data,operation:0,to:t.to,value:t.value??0n}}return {data:vo(e),operation:1,to:r,value:0n}}function Ep(e){return {baseGas:"0",gasPrice:"0",gasToken:ZERO_ADDRESS,operation:`${e}`,refundReceiver:ZERO_ADDRESS,safeTxnGas:"0"}}function Rp(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:Zi,SafeTx:Qi}}}function Lo(e){return {kind:"signGaslessMessage",payload:e}}function hp(e){return {kind:"signGaslessTypedData",payload:e}}function Sp(e,r,t,o,n,s,a,f,g){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(f),Bytes.fromHex(g)),{as:"Hex"}))}function Tp(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 qP=k(e,d,c,b,a,f,g),Nr=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 pp(this.#e,{transactionId:this.transactionId});if(t.state===RelayerTransactionState.STATE_MINED||t.state===RelayerTransactionState.STATE_CONFIRMED){let o=t.transactionHash??this.transactionHash;if(o===null)throw new b("Expected submitted transaction to have a transaction hash once settled");return {transactionHash:o,transactionId:t.transactionId}}if(t.state===RelayerTransactionState.STATE_FAILED||t.state===RelayerTransactionState.STATE_INVALID)throw new g(t.errorMsg??`Transaction ${t.transactionId} reached terminal state ${t.state}`);r+=1,await delay(this.#e.environment.relayerPollFrequencyMs);}throw new f(`Timed out waiting for transaction ${this.transactionId} to settle`)}};var xp=z.object({amount:z.union([z.bigint(),z.literal("max")]),metadata:G.optional(),spenderAddress:EvmAddressSchema,tokenAddress:EvmAddressSchema}),jP=k(a);async function Cp(e,r){let t=l(r,xp),o=t.amount==="max"?Y:t.amount;return async function*(){return e.account.walletType===WalletType.EOA?_(yield Bo(N(e.environment.chainId,dr(t.tokenAddress,t.spenderAddress,o)))):yield*await J(e,{calls:[dr(t.tokenAddress,t.spenderAddress,o)],metadata:t.metadata??`Approve ${t.amount} of ${t.tokenAddress} to ${t.spenderAddress}`})}.call(null)}var HP=k(h$1,e,d,j,c,b,a);function Mo(e,r){return Cp(e,r).then(W(e.signer))}var kp=z.object({approved:z.boolean().default(true),metadata:G.optional(),operatorAddress:EvmAddressSchema,tokenAddress:EvmAddressSchema}),WP=k(a);async function bp(e,r){let t=l(r,kp);return async function*(){return e.account.walletType===WalletType.EOA?_(yield Uo(N(e.environment.chainId,ur(t.tokenAddress,t.operatorAddress,t.approved)))):yield*await J(e,{calls:[ur(t.tokenAddress,t.operatorAddress,t.approved)],metadata:t.metadata??`${t.approved?"Approve":"Revoke"} ${t.operatorAddress} on ${t.tokenAddress}`})}.call(null)}var _P=k(h$1,e,d,j,c,b,a);function Fo(e,r){return bp(e,r).then(W(e.signer))}var NP=k(d,c,b,a);async function Ip(e){let r=await qp(e),t=r.erc20.map(n=>dr(n.tokenAddress,n.spenderAddress,n.amount)),o=r.erc1155.map(n=>ur(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 _(yield Bo(N(e.environment.chainId,s))).wait();for(let s of o)await _(yield Uo(N(e.environment.chainId,s))).wait();return}await(yield*await J(e,{calls:[...t,...o],metadata:"Trading setup approvals"})).wait();}.call(null)}var GP=k(h$1,e,d,j,f,g,c,b,a);function KP(e){return Ip(e).then(W(e.signer)).then(vp)}function vp(){return {transactionHash:null,transactionId:null,wait:async()=>{}}}async function qp(e){let r=Ap(e),t=[...r.erc20.map(a=>yo(a.tokenAddress,e.account.wallet,a.spenderAddress)),...r.erc1155.map(a=>go(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,f)=>fo(n[f])<a.amount),erc1155:r.erc1155.filter((a,f)=>!Po(s[f]))}}function Ap(e){let{contracts:r}=e.environment;return {erc20:[{amount:Y,spenderAddress:r.standardExchange,tokenAddress:r.collateralToken},{amount:Y,spenderAddress:r.negRiskExchange,tokenAddress:r.collateralToken},{amount:Y,spenderAddress:r.negRiskAdapter,tokenAddress:r.collateralToken},{amount:Y,spenderAddress:r.collateralAdapter,tokenAddress:r.collateralToken},{amount:Y,spenderAddress:r.negRiskCollateralAdapter,tokenAddress:r.collateralToken},{amount:Y,spenderAddress:r.protocolV2Router,tokenAddress:r.collateralToken},{amount:Y,spenderAddress:r.exchangeV3,tokenAddress:r.collateralToken},{amount:Y,spenderAddress:r.perpsDepositContract,tokenAddress:r.collateralToken}],erc1155:[{operatorAddress:r.standardExchange,tokenAddress:r.conditionalTokens},{operatorAddress:r.negRiskExchange,tokenAddress:r.conditionalTokens},{operatorAddress:r.negRiskAdapter,tokenAddress:r.conditionalTokens},{operatorAddress:r.collateralAdapter,tokenAddress:r.conditionalTokens},{operatorAddress:r.negRiskCollateralAdapter,tokenAddress:r.conditionalTokens},{operatorAddress:r.autoRedeemOperator,tokenAddress:r.conditionalTokens},{operatorAddress:r.protocolV2Router,tokenAddress:r.positionManager},{operatorAddress:r.exchangeV3,tokenAddress:r.positionManager},{operatorAddress:r.autoRedeemOperator,tokenAddress:r.positionManager}]}}function Bo(e){return {kind:"sendErc20ApprovalTransaction",request:e}}function Uo(e){return {kind:"sendErc1155ApprovalForAllTransaction",request:e}}var XP=k(e,d,c,b);async function Mp(e,r){return unwrap(e.clob.post("/auth/api-key",{headers:jo(r)}).andThen(y(ApiKeyCredsSchema)))}var eE=k(e,d,c,b);async function Fp(e,r){return unwrap(e.clob.get("/auth/derive-api-key",{headers:jo(r)}).andThen(y(ApiKeyCredsSchema)))}var rE=k(e,d,c,b);async function tE(e,r){try{return await Mp(e,r)}catch(t){if(!(t instanceof d)||t.status!==400)throw t}return Fp(e,r)}var oE=k(e,d,j,c,b);async function nE(e){return (await unwrap(e.secureClob.get("/auth/api-keys").andThen(y(ApiKeysResponseSchema)))).apiKeys}var sE=k(e,d,j,c,b);async function aE(e){await unwrap(e.secureClob.del("/auth/api-key").andThen(y(z.literal("OK"))));}var iE=k(e,d,j,c,b);async function pE(e){return unwrap(e.secureClob.post("/auth/builder-api-key").andThen(y(BuilderApiKeyCredsSchema)))}var cE=k(e,d,j,c,b);async function dE(e){return unwrap(e.secureClob.get("/auth/builder-api-key").andThen(y(BuilderApiKeysResponseSchema)))}var uE=k(e,d,j,c,b);async function mE(e){await unwrap(e.clob.del("/auth/builder-api-key").andThen(y(z.literal("OK"))));}function jo(e){return {POLY_ADDRESS:e.address,POLY_NONCE:`${e.nonce}`,POLY_SIGNATURE:e.signature,POLY_TIMESTAMP:`${e.timestamp}`}}var jp=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()}),TE=k(e,d,c,b,a);function xE(e,r){let{cursor:t,...o}=l(r,jp);return T(n=>e.clob.get("/builder/trades",{params:P({...o,nextCursor:n},h({builderCode:"builder_code",tokenId:"asset_id"}))}).andThen(y(PaginatedBuilderTradesSchema)).map(s=>({items:s.data,hasMore:s.nextCursor!==END_CURSOR,nextCursor:s.nextCursor===END_CURSOR?void 0:toPaginationCursor(s.nextCursor),totalCount:s.count})),t)}var pc=z.object({tokenId:z.string()}),ME=k(e,d,c,b,a);async function FE(e,r){let t=l(r,pc);return (await unwrap(e.clob.get("/midpoint",{params:P(t,h())}).andThen(y(MidpointSchema)))).mid}var cc=z.array(z.object({tokenId:z.string()})).min(1),BE=k(e,d,c,b,a);async function UE(e,r){let t=l(r,cc);return unwrap(e.clob.post("midpoints",{json:Pr(t)}).andThen(y(MidpointsSchema)))}var dc=z.object({tokenId:z.string()}),DE=k(e,d,c,b,a);async function Fe(e,r){let t=l(r,dc);return (await unwrap(e.clob.get("/tick-size",{params:P(t,h())}).andThen(y(FetchTickSizeResponseSchema)))).minimumTickSize}var uc=z.object({tokenId:z.string()}),zE=k(e,d,c,b,a);async function Be(e,r){let t=l(r,uc);return (await unwrap(e.clob.get("/neg-risk",{params:P(t,h())}).andThen(y(FetchNegRiskResponseSchema)))).negRisk}var mc=z.object({tokenId:TokenIdSchema}),jE=k(e,d,c,b,a);async function Ko(e,r){let t=l(r,mc);return unwrap(e.clob.get(`/markets-by-token/${t.tokenId}`).andThen(y(ResolveConditionByTokenResponseSchema)))}var lc=z.object({conditionId:CtfConditionIdSchema}),HE=k(e,d,c,b,a);async function $o(e,r){let t=l(r,lc);return unwrap(e.clob.get(`/clob-markets/${t.conditionId}`).andThen(y(FetchMarketInfoResponseSchema)))}var yc=z.object({builderCode:BuilderCodeSchema}),WE=k(e,d,c,b,a);async function Vo(e,r){let t=l(r,yc);return unwrap(e.clob.get(`/fees/builder-fees/${t.builderCode}`).andThen(y(FetchBuilderFeeRatesResponseSchema)).mapErr(o=>o instanceof d&&o.status===404?new a(`Unknown builder code: ${t.builderCode}`,{cause:o}):o))}var fc=z.object({tokenId:z.string(),side:OrderSideSchema}),_E=k(e,d,c,b,a);async function NE(e,r){let t=l(r,fc);return (await unwrap(e.clob.get("/price",{params:P(t,h())}).andThen(y(PriceSchema)))).price}var gc=z.array(z.object({tokenId:z.string(),side:OrderSideSchema})).min(1),GE=k(e,d,c,b,a);async function KE(e,r){let t=l(r,gc);return unwrap(e.clob.post("prices",{json:bc(t)}).andThen(y(PricesSchema)))}var Pc=z.object({tokenId:z.string()}),$E=k(e,d,c,b,a);async function Yo(e,r){let t=l(r,Pc);return unwrap(e.clob.get("/book",{params:P(t,h())}).andThen(y(FetchOrderBookResponseSchema)))}var Ec=z.array(z.object({tokenId:z.string()})).min(1),VE=k(e,d,c,b,a);async function YE(e,r){let t=l(r,Ec);return unwrap(e.clob.post("books",{json:Pr(t)}).andThen(y(OrderBooksSchema)))}var Rc=z.object({tokenId:z.string()}),JE=k(e,d,c,b,a);async function ZE(e,r){let t=l(r,Rc);return (await unwrap(e.clob.get("/spread",{params:P(t,h())}).andThen(y(SpreadSchema)))).spread}var hc=z.array(z.object({tokenId:z.string()})).min(1),QE=k(e,d,c,b,a);async function XE(e,r){let t=l(r,hc);return unwrap(e.clob.post("spreads",{json:Pr(t)}).andThen(y(SpreadsSchema)))}var Sc=z.object({tokenId:z.string()}),eR=k(e,d,c,b,a);async function rR(e,r){let t=l(r,Sc);return unwrap(e.clob.get("/last-trade-price",{params:P(t,h())}).andThen(y(LastTradePriceSchema)))}var Tc=z.array(z.object({tokenId:z.string()})).min(1),tR=k(e,d,c,b,a);async function oR(e,r){let t=l(r,Tc);return unwrap(e.clob.post("last-trades-prices",{json:Pr(t)}).andThen(y(LastTradePricesSchema)))}var xc=z.object({tokenId:z.string(),startTs:z.number().int().optional(),endTs:z.number().int().optional(),fidelity:z.number().int().positive().optional(),interval:PriceHistoryIntervalSchema.optional()}),nR=k(e,d,c,b,a);async function sR(e,r){let t=l(r,xc);return (await unwrap(e.clob.get("/prices-history",{params:P(t,{tokenId:"market",startTs:"startTs",endTs:"endTs",fidelity:"fidelity",interval:"interval"})}).andThen(y(PriceHistorySchema)))).history}var Cc=z.object({cursor:PaginationCursorSchema.optional(),sponsored:z.boolean().optional()}).default({}),aR=k(e,d,c,b,a);function iR(e,r={}){let{cursor:t,...o}=l(r,Cc);return T(n=>e.clob.get("/rewards/markets/current",{params:P({...o,nextCursor:n},h())}).andThen(y(PaginatedCurrentRewardsSchema)).map(s=>({items:s.data,hasMore:s.nextCursor!==END_CURSOR,nextCursor:s.nextCursor===END_CURSOR?void 0:toPaginationCursor(s.nextCursor),totalCount:s.count})),t)}var kc=z.object({conditionId:CtfConditionIdSchema,cursor:PaginationCursorSchema.optional(),sponsored:z.boolean().optional()}),pR=k(e,d,c,b,a);function cR(e,r){let{cursor:t,...o}=l(r,kc);return T(n=>e.clob.get(`rewards/markets/${o.conditionId}`,{params:P({nextCursor:n,sponsored:o.sponsored},h())}).andThen(y(PaginatedMarketRewardsSchema)).map(s=>({items:s.data,hasMore:s.nextCursor!==END_CURSOR,nextCursor:s.nextCursor===END_CURSOR?void 0:toPaginationCursor(s.nextCursor),totalCount:s.count})),t)}function Pr(e){return e.map(({tokenId:r})=>({token_id:r}))}function bc(e){return e.map(({tokenId:r,side:t})=>({token_id:r,side:t}))}var wc=z.object({ascending:z.boolean().optional(),cursor:PaginationCursorSchema.optional(),pageSize:A.default(20),getPositions:z.boolean().optional(),holdersOnly:z.boolean().optional(),order:z.string().optional(),parentEntityId:z.union([EventIdSchema,SeriesIdSchema]),parentEntityType:CommentParentEntityTypeSchema}),Lc=z.object({getPositions:z.boolean().optional(),id:CommentIdSchema}),Mc=z.object({address:z.string(),ascending:z.boolean().optional(),cursor:PaginationCursorSchema.optional(),order:z.string().optional(),pageSize:A.default(20)}),hR=k(e,d,c,b,a);function SR(e,r){let{cursor:t,pageSize:o,...n}=l(r,wc);return T(s=>{let a=U(s,o);return e.gamma.get("/comments",{params:P({ascending:n.ascending,getPositions:n.getPositions,holdersOnly:n.holdersOnly,limit:a.pageSize+1,offset:a.offset,order:n.order,parentEntityId:n.parentEntityId,parentEntityType:n.parentEntityType},h())}).andThen(y(ListCommentsResponseSchema)).map(f=>{let g=f.length>a.pageSize;return {items:f.slice(0,a.pageSize),hasMore:g,nextCursor:g?F({offset:a.offset+a.pageSize,pageSize:a.pageSize}):void 0}})},t)}var TR=k(e,d,c,b,a);async function xR(e,r){let t=l(r,Lc);return unwrap(e.gamma.get(`comments/${t.id}`,{params:P({getPositions:t.getPositions},h())}).andThen(y(ListCommentsResponseSchema)))}var CR=k(e,d,c,b,a);function kR(e,r){let{address:t,cursor:o,pageSize:n,...s}=l(r,Mc);return T(a=>{let f=U(a,n);return e.gamma.get(`comments/user_address/${t}`,{params:P({ascending:s.ascending,limit:f.pageSize+1,offset:f.offset,order:s.order},h())}).andThen(y(ListCommentsResponseSchema)).map(g=>{let L=g.length>f.pageSize;return {items:g.slice(0,f.pageSize),hasMore:L,nextCursor:L?F({offset:f.offset+f.pageSize,pageSize:f.pageSize}):void 0}})},o)}function Er(e,r){let t;try{t=new URL(e);}catch(f){throw new a("Expected a valid Polymarket URL.",{cause:f})}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 jc=z.object({ascending:z.boolean().optional(),closed:z.boolean().default(false),cursor:PaginationCursorSchema.optional(),pageSize:A.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()}),Hc=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()})]),Wc=z.object({id:z.string()}),_c=z.object({id:z.string()}),jR=k(e,d,c,b,a);function HR(e,r={}){let t=l(r,jc);return T(o=>e.gamma.get("/events/keyset",{params:Nc({...t,cursor:o??t.cursor})}).andThen(y(ListEventsKeysetResponseSchema)).map(n=>({items:n.items,hasMore:n.nextCursor!==void 0,nextCursor:n.nextCursor})),t.cursor)}var WR=k(e,d,c,b,a);async function _R(e,r){let t=l(r,Hc);if("id"in t)return unwrap(e.gamma.get(`events/${t.id}`,{params:Gc(t)}).andThen(y(EventSchema)));let o="url"in t?Er(t.url,"event"):t.slug;return unwrap(e.gamma.get(`events/slug/${o}`,{params:Kc(t)}).andThen(y(EventSchema)))}var NR=k(e,d,c,b,a);async function GR(e,r){let t=l(r,Wc);return unwrap(e.gamma.get(`events/${t.id}/tags`).andThen(y(FetchEventTagsResponseSchema)))}var KR=k(e,d,c,b,a);async function $R(e,r){let t=l(r,_c);return unwrap(e.data.get("/live-volume",{params:H(t)}).andThen(y(FetchEventLiveVolumeResponseSchema)))}function Nc(e){return P(e,h({cursor:"after_cursor",excludeTagIds:"exclude_tag_id",gameIds:"game_id",ids:"id",pageSize:"limit",seriesIds:"series_id",tagIds:"tag_id"}))}function Gc(e){return P({includeBestLines:e.includeBestLines,includeChat:e.includeChat,includeTemplate:e.includeTemplate,locale:e.locale},h())}function Kc(e){return P({includeBestLines:e.includeBestLines,includeChat:e.includeChat,includeTemplate:e.includeTemplate,locale:e.locale},h())}var Xc=z.object({cursor:PaginationCursorSchema.optional(),pageSize:A.default(20),timePeriod:TimePeriodSchema.optional()}),ed=z.object({timePeriod:TimePeriodSchema.optional()}),rd=z.object({category:LeaderboardCategorySchema.optional(),cursor:PaginationCursorSchema.optional(),pageSize:A.default(20),timePeriod:TimePeriodSchema.optional(),orderBy:LeaderboardOrderBySchema.optional(),user:z.string().optional(),userName:z.string().optional()}),nh=k(e,d,c,b,a);function sh(e,r={}){let{cursor:t,pageSize:o,...n}=l(r,Xc);return T(s=>{let a=U(s,o);return e.data.get("/v1/builders/leaderboard",{params:H({...n,limit:a.pageSize+1,offset:a.offset})}).andThen(y(ListBuilderLeaderboardResponseSchema)).map(f=>{let g=f.length>a.pageSize;return {items:f.slice(0,a.pageSize),hasMore:g,nextCursor:g?F({offset:a.offset+a.pageSize,pageSize:a.pageSize}):void 0}})},t)}var ah=k(e,d,c,b,a);async function ih(e,r={}){let t=l(r,ed);return unwrap(e.data.get("/v1/builders/volume",{params:H(t)}).andThen(y(ListBuilderVolumeResponseSchema)))}var ph=k(e,d,c,b,a);function ch(e,r={}){let{cursor:t,pageSize:o,...n}=l(r,rd);return T(s=>{let a=U(s,o);return e.data.get("/v1/leaderboard",{params:H({...n,limit:a.pageSize+1,offset:a.offset})}).andThen(y(ListTraderLeaderboardResponseSchema)).map(f=>{let g=f.length>a.pageSize;return {items:f.slice(0,a.pageSize),hasMore:g,nextCursor:g?F({offset:a.offset+a.pageSize,pageSize:a.pageSize}):void 0}})},t)}var cd=z.object({ascending:z.boolean().optional(),closed:z.boolean().optional(),clobTokenIds:z.array(z.string()).optional(),cursor:PaginationCursorSchema.optional(),pageSize:A.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()}),dd=z.object({id:z.string(),includeTag:z.boolean().optional(),locale:z.string().optional()}),ud=z.object({slug:z.string(),includeTag:z.boolean().optional(),locale:z.string().optional()}),md=z.object({url:z.string(),includeTag:z.boolean().optional(),locale:z.string().optional()}),ld=z.union([dd,ud,md]),yd=z.object({id:z.string()}),fd=z.object({limit:z.number().int().optional(),market:z.array(z.string()),minBalance:z.number().int().optional()}),gd=z.object({market:z.array(z.string()).optional()}),Pd=z.enum(["OPEN","CLOSED","ALL"]),Ed=z.enum(["TOKENS","CASH_PNL","REALIZED_PNL","TOTAL_PNL"]),Rd=z.enum(["ASC","DESC"]),hd=z.object({cursor:PaginationCursorSchema.optional(),market:z.string(),pageSize:A.default(20),user:z.string().optional(),status:Pd.optional(),sortBy:Ed.optional(),sortDirection:Rd.optional()}),xh=k(e,d,c,b,a);function tn(e,r={}){let t=l(r,cd);return T(o=>e.gamma.get("/markets/keyset",{params:Td({...t,cursor:o??t.cursor})}).andThen(y(ListMarketsKeysetResponseSchema)).map(n=>({items:n.items,hasMore:n.nextCursor!==void 0,nextCursor:n.nextCursor})),t.cursor)}var Sd=z.object({cursor:PaginationCursorSchema.optional(),pageSize:A.max(100).optional(),exclude:z.array(CtfConditionIdSchema).optional()}),Ch=k(e,d,c,b,a);function kh(e,r={}){let t=l(r,Sd);return T(o=>e.rfq.get("/v1/rfq/combo-markets",{params:xd({...t,cursor:o??t.cursor})}).andThen(y(ListComboMarketsResponseSchema)).map(n=>({items:n.markets,hasMore:n.nextCursor!==void 0,nextCursor:n.nextCursor})),t.cursor)}var bh=k(e,d,c,b,a);async function Ih(e,r){let t=l(r,ld);return "id"in t?Cd(e,t):"url"in t?Xo(e,{includeTag:t.includeTag,locale:t.locale,slug:Er(t.url,"market")}):Xo(e,t)}var vh=k(e,d,c,b,a);async function qh(e,r){let t=l(r,yd);return unwrap(e.gamma.get(`markets/${t.id}/tags`).andThen(y(FetchMarketTagsResponseSchema)))}var Ah=k(e,d,c,b,a);async function Oh(e,r){let t=l(r,fd);return unwrap(e.data.get("/holders",{params:H(t)}).andThen(y(ListMarketHoldersResponseSchema)))}var wh=k(e,d,c,b,a);async function Lh(e,r={}){let t=l(r,gd);return unwrap(e.data.get("/oi",{params:H(t)}).andThen(y(ListOpenInterestResponseSchema)))}var Mh=k(e,d,c,b,a);function Fh(e,r){let{cursor:t,pageSize:o,...n}=l(r,hd);return T(s=>{let a=U(s,o);return e.data.get("/v1/market-positions",{params:H({...n,limit:a.pageSize+1,offset:a.offset})}).andThen(y(ListMarketPositionsResponseSchema)).map(f=>{let g=f.length>a.pageSize;return {items:f.slice(0,a.pageSize),hasMore:g,nextCursor:g?F({offset:a.offset+a.pageSize,pageSize:a.pageSize}):void 0}})},t)}function Td(e){return P(e,h({cursor:"after_cursor",ids:"id",marketMakerAddresses:"market_maker_address",pageSize:"limit"}))}function xd(e){return P({cursor:e.cursor,exclude:e.exclude?.join(","),pageSize:e.pageSize},{cursor:"cursor",exclude:"exclude",pageSize:"limit"})}async function Xo(e,r){return unwrap(e.gamma.get(`markets/slug/${r.slug}`,{params:P({includeTag:r.includeTag,locale:r.locale},h())}).andThen(y(MarketSchema)))}async function Cd(e,r){return unwrap(e.gamma.get(`markets/${r.id}`,{params:P({includeTag:r.includeTag,locale:r.locale},h())}).andThen(y(MarketSchema)))}var Id=z.object({orderId:z.string()}),vd=z.object({orderIds:z.array(z.string()).min(1).max(3e3)}),qd=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"]}),_h=k(d,e,j,c,b,a);async function Nh(e,r){let t=l(r,Id);return Sr(e,"/order",{orderID:t.orderId})}var Gh=k(d,e,j,c,b,a);async function Kh(e,r){let t=l(r,vd);return Sr(e,"/orders",t.orderIds)}var $h=k(d,e,j,c,b);async function Vh(e){return Sr(e,"/cancel-all")}var Yh=k(d,e,j,c,b,a);async function Jh(e,r){let t=l(r,qd);return Sr(e,"/cancel-market-orders",{asset_id:t.tokenId,market:t.market})}async function Sr(e,r,t){return unwrap(e.secureClob.del(r,{json:t}).andThen(y(CancelOrdersResponseSchema)))}var nn=z.object({tokenId:z.string(),orderType:z.union([z.literal(OrderType.FAK),z.literal(OrderType.FOK)]).default(OrderType.FOK)}),Od=z.discriminatedUnion("side",[nn.extend({side:z.literal(OrderSide.BUY),amount:PositiveDecimalNumberSchema}),nn.extend({side:z.literal(OrderSide.SELL),shares:PositiveDecimalNumberSchema})]),nS=k(i,e,d,c,b,a);async function sS(e,r){let t=l(r,Od),o=await Fe(e,{tokenId:t.tokenId}),n=t.side===OrderSide.BUY?t.amount:t.shares;return Qr(e,{amount:n,orderType:t.orderType,side:t.side,tickSize:o,tokenId:t.tokenId})}async function Qr(e,r){let t=await Yo(e,{tokenId:r.tokenId}),o=r.side===OrderSide.BUY?Ld(t.asks,r.amount,r.orderType):Md(t.bids,r.amount,r.orderType);return invariant(wd(o,r.tickSize),`Resolved market price fell outside the valid range for tick size ${r.tickSize}.`),o}function wd(e,r){return e>=r&&e<=1-r}function Ld(e,r,t){if(e.length===0)throw new i("No resting liquidity.");let o=0;for(let s=e.length-1;s>=0;s-=1){let a=e[s];if(a!==void 0&&(o+=Number.parseFloat(a.size)*Number.parseFloat(a.price),o>=r))return Number.parseFloat(a.price)}if(t===OrderType.FOK)throw new i("Insufficient liquidity for full fill.");let n=e[0];return Number.parseFloat(n.price)}function Md(e,r,t){if(e.length===0)throw new i("No resting liquidity.");let o=0;for(let s=e.length-1;s>=0;s-=1){let a=e[s];if(a!==void 0&&(o+=Number.parseFloat(a.size),o>=r))return Number.parseFloat(a.price)}if(t===OrderType.FOK)throw new i("Insufficient liquidity for full fill.");let n=e[0];return Number.parseFloat(n.price)}var Dd=z.array(z.custom()).min(1).max(15),yS=k(e,d,j,c,b),fS=k(e,d,j,c,b,a);function xr(e){return async function(t){let o=cn(e,t);return unwrap(e.secureClob.post("/order",{json:o}).andThen(y(OrderResponseSchema)))}}function gS(e){return async function(t){let n=l(t,Dd).map(s=>cn(e,s));return unwrap(e.secureClob.post("/orders",{json:n}).andThen(y(OrderResponsesSchema)))}}function cn(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 De(e){switch(e){case .1:return {amount:3,price:1,size:2};case .01:return {amount:4,price:2,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 ze(e,r){return r?e.environment.contracts.negRiskExchange:e.environment.contracts.standardExchange}function de(e){return BigInt(Math.round(e*10**6))}function ue(e,r){return Z(e)<=r?e:Math.floor(e*10**r)/10**r}function Ce(e,r){return Z(e)<=r?e:Math.ceil(e*10**r)/10**r}function Xr(e,r){return Z(e)<=r?e:Math.round(e*10**r)/10**r}function Z(e){if(typeof e=="number"&&Number.isInteger(e))return 0;let[r="",t]=e.toString().toLowerCase().split("e"),[,o=""]=r.split("."),n=o.length;if(t===void 0)return n;let s=Number.parseInt(t,10);return Math.max(0,n-s)}var mn=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)+60;e.expiration<t&&r.addIssue({code:"custom",message:"Expiration must be at least 60 seconds in the future.",path:["expiration"]});}});async function ln(e,r){let t=await Nd(e,{price:r.price,tokenId:r.tokenId}),o=Gd({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 Nd(e,r){let t=e.account,o=await Fe(e,{tokenId:r.tokenId}),n=await Be(e,{tokenId:r.tokenId});return {exchangeAddress:ze(e,n),funderAddress:t.wallet,negRisk:n,price:Kd(r.price,o),signerAddress:t.signer,tickSize:o}}function Gd(e){let r=De(e.tickSize),t=Xr(e.price,r.price);if(e.side===OrderSide.BUY){let s=ue(e.size,r.size),a=s*t;return Z(a)>r.amount&&(a=Ce(a,r.amount+4),Z(a)>r.amount&&(a=ue(a,r.amount))),{offeredAmount:de(a),requestedAmount:de(s)}}let o=ue(e.size,r.size),n=o*t;return Z(n)>r.amount&&(n=Ce(n,r.amount+4),Z(n)>r.amount&&(n=ue(n,r.amount))),{offeredAmount:de(o),requestedAmount:de(n)}}function Kd(e,r){let t=De(r);if(e<r||e>1-r)throw new a(`Price must be between ${r} and ${1-r} for tick size ${r}.`);if(Z(e)>t.price)throw new a(`Price must conform to tick size ${r} with at most ${t.price} decimal places.`);return Xr(e,t.price)}var yn=z.object({tokenId:TokenIdSchema,builderCode:BuilderCodeSchema.optional(),orderType:z.union([z.literal(OrderType.FAK),z.literal(OrderType.FOK)]).default(OrderType.FAK)}),gn=z.discriminatedUnion("side",[yn.extend({side:z.literal(OrderSide.BUY),amount:PositiveDecimalNumberSchema,maxSpend:PositiveDecimalNumberSchema.optional(),maxPrice:PositiveDecimalNumberSchema.optional()}),yn.extend({side:z.literal(OrderSide.SELL),shares:PositiveDecimalNumberSchema,minPrice:PositiveDecimalNumberSchema.optional()})]);async function Pn(e,r){let t=await Yd(e,r),o=Qd({amount:t.resolvedAmount,price:t.price,protectPrice:Zd(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 Yd(e,r){let t=e.account,o=await Fe(e,{tokenId:r.tokenId}),n=r.side===OrderSide.BUY?r.amount:r.shares,s=await Jd(e,r,n,o),a=await Be(e,{tokenId:r.tokenId}),f=await Xd(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:ze(e,a),funderAddress:t.wallet,negRisk:a,price:s,resolvedAmount:f,signerAddress:t.signer,tickSize:o}}async function Jd(e,r,t,o){return r.side===OrderSide.BUY&&r.maxPrice!==void 0?fn(r.maxPrice,o,"maxPrice"):r.side===OrderSide.SELL&&r.minPrice!==void 0?fn(r.minPrice,o,"minPrice"):Qr(e,{amount:t,orderType:r.orderType,side:r.side,tickSize:o,tokenId:r.tokenId})}function fn(e,r,t){let o=De(r);if(e<r||e>1-r)throw new a(`${t} must be between ${r} and ${1-r} for tick size ${r}.`);if(Z(e)>o.price)throw new a(`${t} must conform to tick size ${r} with at most ${o.price} decimal places.`);return e}function Zd(e){return e.side===OrderSide.BUY&&e.maxPrice!==void 0||e.side===OrderSide.SELL&&e.minPrice!==void 0}function Qd(e){let r=De(e.tickSize),t=ue(e.price,r.price),o=ue(e.amount,r.size);if(e.side===OrderSide.BUY){let s=o/t;return Z(s)>r.amount&&(s=Ce(s,r.amount+4),Z(s)>r.amount&&(s=e.protectPrice?Ce(s,r.amount):ue(s,r.amount))),{offeredAmount:de(o),requestedAmount:de(s)}}let n=o*t;return Z(n)>r.amount&&(n=Ce(n,r.amount+4),Z(n)>r.amount&&(n=e.protectPrice?Ce(n,r.amount):ue(n,r.amount))),{offeredAmount:de(o),requestedAmount:de(n)}}async function Xd(e,r){if(r.side!==OrderSide.BUY||r.maxSpend===void 0)return r.amount;let[t,o]=await Promise.all([eu(e,r.tokenId),ru(e,r.builderCode)]);return tu({amount:r.amount,builderTakerFeeRate:o,platformFeeExponent:t.exponent,platformFeeRate:t.rate,maxSpend:r.maxSpend,price:r.price})}async function eu(e,r){let t=await Ko(e,{tokenId:r});return (await $o(e,{conditionId:t})).feeInfo}async function ru(e,r){return r===void 0?0:(await Vo(e,{builderCode:r})).taker}function tu(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 En="0x0000000000000000000000000000000000000000000000000000000000000000";function tt(e,r){let t=Zt(r);return {builder:e.builderCode??En,chainId:e.chainId,exchangeAddress:e.exchangeAddress,expiration:e.expiration,maker:t.maker,makerAmount:e.offeredAmount.toString(),metadata:En,orderType:e.orderType,salt:ou().toString(),side:e.side,signatureType:t.signatureType,signer:t.signer,takerAmount:e.requestedAmount.toString(),timestamp:Date.now().toString(),tokenId:e.tokenId}}function ot(e,r){let{chainId:t,exchangeAddress:o,...n}=e;return {...n,signature:r}}function ou(){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 Sn="Polymarket CTF Exchange",au="DepositWallet",iu="1",nt="0x0000000000000000000000000000000000000000000000000000000000000000",st="Order(uint256 salt,address maker,address signer,uint256 tokenId,uint256 makerAmount,uint256 takerAmount,uint8 side,uint8 signatureType,uint256 timestamp,bytes32 metadata,bytes32 builder)",pu=Hash.keccak256(Bytes.fromString(st),{as:"Hex"}),cu=Hash.keccak256(Bytes.fromString("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),{as:"Hex"}),du=Hash.keccak256(Bytes.fromString(Sn),{as:"Hex"}),uu=[{name:"name",type:"string"},{name:"version",type:"string"},{name:"chainId",type:"uint256"},{name:"verifyingContract",type:"address"}],Tn=[{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"}],mu=[{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 xn(e){let r=lu(e.domain,e.order);return e.order.signatureType!==SignatureType.POLY_1271?r:{domain:bn(e.domain),message:{chainId:e.domain.chainId,contents:r.message,name:au,salt:nt,verifyingContract:e.order.signer,version:iu},primaryType:"TypedDataSign",types:{Order:Tn,TypedDataSign:mu}}}function Cn(e){if(e.order.signatureType!==SignatureType.POLY_1271)return e.signature;let r=Bytes.toHex(Bytes.fromString(st)),t=st.length.toString(16).padStart(4,"0");return expectErc1271Signature(`0x${e.signature.slice(2)}${yu(e.domain).slice(2)}${fu(e.order).slice(2)}${r.slice(2)}${t}`)}function kn(e){return {builder:e.builder??nt,maker:e.maker,makerAmount:BigInt(e.makerAmount),metadata:e.metadata??nt,salt:BigInt(e.salt),side:Pu(e.side),signatureType:e.signatureType,signer:e.signer,takerAmount:BigInt(e.takerAmount),timestamp:BigInt(e.timestamp),tokenId:BigInt(e.tokenId)}}function lu(e,r){return {domain:bn(e),message:kn(r),primaryType:"Order",types:{EIP712Domain:uu,Order:Tn}}}function bn(e){return {chainId:e.chainId,name:Sn,verifyingContract:e.exchange,version:e.protocolVersion}}function yu(e){return expectHexString(Hash.keccak256(AbiParameters.encode([{type:"bytes32"},{type:"bytes32"},{type:"bytes32"},{type:"uint256"},{type:"address"}],[cu,du,gu(e.protocolVersion),BigInt(e.chainId),e.exchange]),{as:"Hex"}))}function fu(e){let r=kn(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"}],[pu,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 gu(e){return expectHexString(Hash.keccak256(Bytes.fromString(e),{as:"Hex"}))}function Pu(e){return e===0||e===1?e:e===OrderSide.BUY?0:1}function it(e){return xn({domain:In(e),order:e})}function pt(e,r){return Cn({domain:In(e),order:e,signature:r})}function In(e){return {chainId:e.chainId,exchange:e.exchangeAddress,protocolVersion:"2"}}function ct(e){return {kind:"signOrder",payload:e}}var Eu=k(i,e,d,j,c,b,a);async function dt(e,r){let t=l(r,gn);return async function*(){let o=await Pn(e,t),n=tt(o,e.account),s=expectEvmSignature(yield ct(it(n)));return ot(n,pt(n,s))}.call(null)}var Ru=k(e,d,j,c,b,a);async function ut(e,r){let t=l(r,mn);return async function*(){let o=await ln(e,t),n=tt(o,e.account),s=expectEvmSignature(yield ct(it(n))),a=ot(n,pt(n,s));return t.postOnly===true?{...a,postOnly:true}:a}.call(null)}var tT=Eu;async function oT(e,r){return qn(e,dt(e,r))}var nT=Ru;async function sT(e,r){return qn(e,ut(e,r))}async function qn(e,r){let t=await r;return async function*(){let o=yield*t;return xr(e)(o)}.call(null)}async function wn(e,r){let t=r.side===OrderSide.BUY?AssetType.COLLATERAL:AssetType.CONDITIONAL,{allowances:o}=await Ur(e,r.side===OrderSide.BUY?{assetType:t}:{assetType:t,tokenId:r.tokenId});return Su(o,r.spenderAddress)}function Su(e,r){return Object.entries(e).find(([o])=>isSameEvmAddress(o,r))?.[1]??0n}var xT=k(h$1,i,e,d,j,c,b,a);function Tu(e,r){return dt(e,r).then(W(e.signer))}var CT=k(h$1,i,e,d,j,f,g,c,b,a);function kT(e,r){return Tu(e,r).then(t=>Mn(e,t))}var bT=k(h$1,e,d,j,c,b,a);function xu(e,r){return ut(e,r).then(W(e.signer))}var IT=k(h$1,e,d,j,f,g,c,b,a);function vT(e,r){return xu(e,r).then(t=>Mn(e,t))}async function Mn(e,r){let t=xr(e);try{return await t(r)}catch(o){if(!ku(o))throw o;let n=await Cu(e,r,t);if(n===void 0)throw o;return n}}async function Cu(e,r,t){return await bu(e,r)?t(r):void 0}function ku(e){return e instanceof d&&e.status===400&&e.message.includes("allowance is not enough")}async function bu(e,r){let t=await Be(e,{tokenId:r.tokenId}),o=ze(e,t),n=BigInt(r.makerAmount);return await wn(e,{spenderAddress:o,side:r.side,tokenId:r.tokenId})>=n?false:(await(r.side===OrderSide.BUY?await Mo(e,{amount:"max",spenderAddress:o,tokenAddress:e.environment.contracts.collateralToken}):await Fo(e,{operatorAddress:o,tokenAddress:e.environment.contracts.conditionalTokens})).wait(),await oo(e,{assetType:r.side===OrderSide.BUY?AssetType.COLLATERAL:AssetType.CONDITIONAL,tokenId:r.side===OrderSide.SELL?r.tokenId:void 0}),true)}function Fn(e){let r=TypedData.getSignPayload(lt(e));return expectEvmSignature(Signature.toHex(Secp256k1.sign({payload:r,privateKey:e.privateKey})))}function lt(e){return {domain:{chainId:e.chainId,name:"Polymarket",version:"1"},message:{data:Hash.keccak256(encode(Bn(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 Bn(e){return Array.isArray(e)?e.filter(r=>r!==void 0).map(Bn):e}var Cr=class{#e;#r;#t;constructor({root:r,headers:t,resolveHeaders:o}){this.#e=Nt.create({prefixUrl:r,throwHttpErrors:false}),this.#r=t,this.#t=o;}get(r,t={}){return this.#o("GET",r,t)}post(r,t={}){return this.#o("POST",r,t)}patch(r,t={}){return this.#o("PATCH",r,t)}del(r,t={}){return this.#o("DELETE",r,t)}#n(r){return r.startsWith("/")?r.slice(1):r}#o(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.#n(t),{body:n.body,headers:a,method:r,searchParams:n.params})}#i(r,t,o){return {body:"json"in o?this.#s(o.json):void 0,headers:o.headers,json:"json"in o?o.json:void 0,method:r,params:"params"in o?o.params:void 0,path:t}}#s(r){if(r!==void 0)return JSON.stringify(r)}#p(...r){let t=new Headers;for(let o of r)if(o!==void 0)for(let[n,s]of new Headers(o).entries())t.set(n,s);return t}#a(r){return ResultAsync.fromPromise(r.then(async t=>{if(t.ok)return t;if(t.status===429)throw new e(`Request to ${t.url} was rate limited`);let o=await this.#d(t);throw new d(o,{status:t.status})}),t=>t instanceof e||t instanceof d?t:c.fromError(t))}async#d(r){let t=r.headers.get("content-type")?.toLowerCase();if(t?.includes("application/json")){let{error:n}=await r.clone().json().catch(()=>({}));if(n)return `${String(n)} (${r.url})`}if(t?.includes("text/plain")){let n=await r.clone().text().then(s=>s.trim(),()=>"");if(n)return `${n} (${r.url})`}return r.headers.get("server")?.toLowerCase()?.includes("cloudflare")?`Request to ${r.url} was blocked by Cloudflare with status ${r.status}`:t?.includes("text/html")||t?.includes("application/xhtml+xml")?`Request to ${r.url} failed with status ${r.status} and an unexpected HTML response body`:`Request to ${r.url} failed with status ${r.status} and unreadable response body`}};var Fu=1e4,Bu=3e4,Uu=5e3,Du=10*6e4,zu=3e4,ju=25e3,Hu=65e3,Un=class{#e=0;#r;start(r){this.stop(),this.#e=Date.now(),this.#r=setNonBlockingInterval(()=>{r("PING");},Fu);}handleMessage(r){return r!=="PONG"?false:(this.#e=Date.now(),true)}isStale(r){return r-this.#e>Bu}stop(){this.#r!==void 0&&(clearInterval(this.#r),this.#r=void 0);}},Dn=class{#e=0;#r;start(r){this.stop(),this.#e=Date.now(),this.#r=setNonBlockingInterval(()=>{r("PING");},Uu);}handleMessage(){return this.#e=Date.now(),false}isStale(r){return r-this.#e>Du}stop(){this.#r!==void 0&&(clearInterval(this.#r),this.#r=void 0);}},zn=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>zu}},kr=class{#e=0;#r;start(r){this.stop(),this.#e=Date.now(),this.#r=setNonBlockingInterval(()=>{r(JSON.stringify({id:0,req:"post",op:{type:"ping"}}));},ju);}handleMessage(){return this.#e=Date.now(),false}isStale(r){return r-this.#e>Hu}stop(){this.#r!==void 0&&(clearInterval(this.#r),this.#r=void 0);}};var Nu=5e3,Gu=250,Ku=3e4,br=class{#e;#r=0;schedule(r){if(this.#e!==void 0||!r.shouldReconnect())return;let t=Vu(this.#r,{baseMs:Gu,maxMs:Ku});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);}}},Ir=class{#e;#r;#t;#n;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.#o(JSON.stringify(r))}#o(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=$u(r.url,r.headers),a=()=>{s.removeEventListener("error",f),this.#i(s),this.#p(),r.onOpen(t),o(s);},f=g=>{s.removeEventListener("open",a),n(new c(`WebSocket connection failed: ${r.url}`,{cause:g}));};s.addEventListener("open",a,{once:true}),s.addEventListener("error",f,{once:true}),s.addEventListener("message",g=>{if(this.#r!==s)return;let L=String(g.data);if(this.#e?.handleMessage(L))return;let I;try{I=JSON.parse(L);}catch{return}r.onMessage(I);}),s.addEventListener("close",()=>{this.#r===s&&(this.#s(),r.onClose());}),s.addEventListener("error",()=>r.onError());})}#i(r){this.#r=r,this.#t=void 0;}#s(){this.#a(),this.#r=void 0;}#p(){this.#a();let r=this.#e;r!==void 0&&(r.start(t=>this.#o(t)),this.#n=setNonBlockingInterval(()=>{if(!r.isStale(Date.now()))return;let t=this.#r;t?.readyState===WebSocket.OPEN&&t.close();},Nu));}#a(){this.#n!==void 0&&(clearInterval(this.#n),this.#n=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 $u(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 Vu(e,r){let t=Math.min(r.baseMs*2**e,r.maxMs);return Math.random()*t}var er=1440*60*1e3,_n=90*er,le=z.number().int().nonnegative(),vr=z.object({start:le.optional(),end:le.optional()}),Nn=z.object({interval:PerpsPnlIntervalSchema,start:le,end:le.optional()}),cm=z.enum(["perpsFills","perpsFundingPayments","perpsDeposits","perpsWithdrawals"]),dm=z.enum(["perpsEquityHistory","perpsPnlHistory"]),qr=z.object({kind:cm,startTimestamp:le,endTimestamp:le,instrumentId:PerpsInstrumentIdSchema.optional(),depositStatus:PerpsDepositStatusSchema.optional(),withdrawalStatus:PerpsWithdrawalStatusSchema.optional(),hash:TxHashSchema.optional(),seenKeys:z.array(z.string())}),Gn=z.object({kind:dm,startTimestamp:le,endTimestamp:le,interval:PerpsPnlIntervalSchema});async function Kn(e){return await unwrap(e.get("/v1/account/balances").andThen(y(FetchPerpsBalancesResponseSchema)))}async function $n(e){return await unwrap(e.get("/v1/account/portfolio").andThen(y(FetchPerpsPortfolioResponseSchema)))}var um=z.object({instrumentId:PerpsInstrumentIdSchema.optional()}).default({});async function Vn(e,r){let t=l(r,um);return await unwrap(e.get("/v1/account/config",{params:Ee(t)}).andThen(y(FetchPerpsAccountConfigResponseSchema)))}var mm=z.object({instrumentId:PerpsInstrumentIdSchema.optional()}).default({});async function Yn(e,r){let t=l(r,mm);return await unwrap(e.get("/v1/account/open-orders",{params:Ee(t)}).andThen(y(FetchPerpsOpenOrdersResponseSchema)))}var lm=z.object({orderId:PerpsOrderIdSchema.optional(),clientOrderId:PerpsClientOrderIdSchema.optional(),instrumentId:PerpsInstrumentIdSchema.optional(),start:le.optional(),end:le.optional()}).default({}).transform(({end:e,start:r,...t})=>({...t,endTimestamp:e,startTimestamp:r}));async function Jn(e,r){let t=l(r,lm);return await unwrap(e.get("/v1/account/orders",{params:Ee(t)}).andThen(y(FetchPerpsOrdersResponseSchema)))}var ym=z.union([vr.extend({cursor:PaginationCursorSchema.optional()}).transform(({cursor:e,...r})=>({cursor:e,params:Ar(r,er)})),z.object({cursor:PaginationCursorSchema}).transform(({cursor:e})=>({cursor:e,params:void 0}))]);function Zn(e,r={}){let{cursor:t,params:o}=l(r,ym);return T(n=>{let s;n===void 0?(invariant(o!==void 0,"Expected initial Perps fills params."),s={kind:"perpsFills",seenKeys:[],...o}):s=We(n,qr);let{kind:a,seenKeys:f,...g}=s,L=new Set(s.seenKeys);return e.get("/v1/account/fills",{params:Ee(g)}).andThen(y(ListPerpsFillsResponseSchema)).map(I=>{let $=I.data.filter(M=>!L.has(String(M.tradeId)));return Or({getKey:M=>String(M.tradeId),getTimestamp:M=>M.timestamp,items:$,responseData:I.data,responseMore:I.more,state:s})})},t)}var fm=z.union([vr.extend({cursor:PaginationCursorSchema.optional(),instrumentId:PerpsInstrumentIdSchema.optional()}).transform(({cursor:e,...r})=>({cursor:e,params:Ar(r,er)})),z.object({cursor:PaginationCursorSchema}).transform(({cursor:e})=>({cursor:e,params:void 0}))]);function Qn(e,r={}){let{cursor:t,params:o}=l(r,fm);return T(n=>{let s;n===void 0?(invariant(o!==void 0,"Expected initial Perps funding payment params."),s={kind:"perpsFundingPayments",seenKeys:[],...o}):s=We(n,qr);let{kind:a,seenKeys:f,...g}=s,L=new Set(s.seenKeys);return e.get("/v1/account/funding",{params:Ee(g)}).andThen(y(ListPerpsFundingPaymentsResponseSchema)).map(I=>{let $=I.data.filter(M=>!L.has(`${M.instrumentId}:${M.timestamp}:${M.funding}`));return Or({getKey:M=>`${M.instrumentId}:${M.timestamp}:${M.funding}`,getTimestamp:M=>M.timestamp,items:$,responseData:I.data,responseMore:I.more,state:s})})},t)}var gm=z.union([vr.extend({cursor:PaginationCursorSchema.optional(),depositStatus:PerpsDepositStatusSchema.optional(),hash:TxHashSchema.optional()}).transform(({cursor:e,...r})=>({cursor:e,params:Ar(r,_n)})),z.object({cursor:PaginationCursorSchema}).transform(({cursor:e})=>({cursor:e,params:void 0}))]);function Xn(e,r={}){let{cursor:t,params:o}=l(r,gm);return T(n=>{let s;n===void 0?(invariant(o!==void 0,"Expected initial Perps deposit params."),s={kind:"perpsDeposits",seenKeys:[],...o}):s=We(n,qr);let{kind:a,seenKeys:f,...g}=s,L=new Set(s.seenKeys);return e.get("/v1/account/deposits",{params:Ee(g)}).andThen(y(ListPerpsDepositsResponseSchema)).map(I=>{let $=I.data.filter(M=>!L.has(M.hash));return Or({getKey:M=>M.hash,getTimestamp:hm,items:$,responseData:I.data,responseMore:I.more,state:s})})},t)}var Pm=z.union([vr.extend({cursor:PaginationCursorSchema.optional(),withdrawalStatus:PerpsWithdrawalStatusSchema.optional(),hash:TxHashSchema.optional()}).transform(({cursor:e,...r})=>({cursor:e,params:Ar(r,_n)})),z.object({cursor:PaginationCursorSchema}).transform(({cursor:e})=>({cursor:e,params:void 0}))]);function es(e,r={}){let{cursor:t,params:o}=l(r,Pm);return T(n=>{let s;n===void 0?(invariant(o!==void 0,"Expected initial Perps withdrawal params."),s={kind:"perpsWithdrawals",seenKeys:[],...o}):s=We(n,qr);let{kind:a,seenKeys:f,...g}=s,L=new Set(s.seenKeys);return e.get("/v1/account/withdrawals",{params:Ee(g)}).andThen(y(ListPerpsWithdrawalsResponseSchema)).map(I=>{let $=I.data.filter(M=>!L.has(String(M.withdrawalId)));return Or({getKey:M=>String(M.withdrawalId),getTimestamp:Sm,items:$,responseData:I.data,responseMore:I.more,state:s})})},t)}var Em=z.union([Nn.extend({cursor:PaginationCursorSchema.optional()}).transform(({cursor:e,...r})=>({cursor:e,params:os(r)})),z.object({cursor:PaginationCursorSchema}).transform(({cursor:e})=>({cursor:e,params:void 0}))]);function rs(e,r){let{cursor:t,params:o}=l(r,Em);return T(n=>{let s;n===void 0?(invariant(o!==void 0,"Expected initial Perps equity history params."),s={kind:"perpsEquityHistory",...o}):s=We(n,Gn);let{kind:a,...f}=s;return e.get("/v1/account/equity",{params:Ee(f)}).andThen(y(ListPerpsEquityHistoryResponseSchema)).map(g=>{let L=g.data.at(-1),I=g.more&&L!==void 0&&L.timestamp<s.endTimestamp;return {items:g.data,hasMore:I,nextCursor:I?gt({...s,startTimestamp:L.timestamp+ns(s.interval)}):void 0}})},t)}var Rm=z.union([Nn.extend({cursor:PaginationCursorSchema.optional()}).transform(({cursor:e,...r})=>({cursor:e,params:os(r)})),z.object({cursor:PaginationCursorSchema}).transform(({cursor:e})=>({cursor:e,params:void 0}))]);function ts(e,r){let{cursor:t,params:o}=l(r,Rm);return T(n=>{let s;n===void 0?(invariant(o!==void 0,"Expected initial Perps PnL history params."),s={kind:"perpsPnlHistory",...o}):s=We(n,Gn);let{kind:a,...f}=s;return e.get("/v1/account/pnl",{params:Ee(f)}).andThen(y(ListPerpsPnlHistoryResponseSchema)).map(g=>{let L=g.data.at(-1),I=g.more&&L!==void 0&&L.timestamp<s.endTimestamp;return {items:g.data,hasMore:I,nextCursor:I?gt({...s,startTimestamp:L.timestamp+ns(s.interval)}):void 0}})},t)}function Ar(e,r){let t=Date.now(),{end:o,start:n,...s}=e;return {...s,endTimestamp:o??t,startTimestamp:n??t-r}}function os(e){return {endTimestamp:e.end??Date.now(),interval:e.interval,startTimestamp:e.start}}function We(e,r){try{return r.parse(JSON.parse(atob(e)))}catch(t){throw new c("Invalid Perps account pagination cursor",{cause:t})}}function gt(e){return toPaginationCursor(btoa(JSON.stringify(e)))}function Ee(e){return P(e,h())}function hm(e){return e.confirmedTimestamp??e.createdTimestamp}function Sm(e){return e.confirmedTimestamp??e.createdTimestamp}function Or(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 f of e.items)e.getTimestamp(f)===s&&a.add(e.getKey(f));return {items:e.items,hasMore:n,nextCursor:gt({...e.state,endTimestamp:s,seenKeys:Array.from(a)})}}function ns(e){switch(e){case "1h":return 3600*1e3;case "4h":return 14400*1e3;case "1d":return er;case "1w":return 7*er}invariant(false,`Unsupported Perps account history interval: ${String(e)}`);}var St=z.object({instrumentId:PerpsInstrumentIdSchema,side:OrderSideSchema,quantity:PerpsDecimalInputSchema,clientOrderId:PerpsClientOrderIdSchema.optional()}),vm=St.extend({price:PerpsDecimalInputSchema,timeInForce:z.literal(PerpsTimeInForce.GTC),postOnly:z.boolean().default(false)}),qm=St.extend({price:PerpsDecimalInputSchema.optional(),timeInForce:z.literal(PerpsTimeInForce.IOC),postOnly:z.never().optional()}),Am=St.extend({price:PerpsDecimalInputSchema.optional(),timeInForce:z.literal(PerpsTimeInForce.FOK),postOnly:z.never().optional()}),Om=z.discriminatedUnion("timeInForce",[vm,qm,Am]),wm=z.object({orders:z.array(Om).min(1),expiresAt:z.number().int().positive().optional()});async function Tt(e,r){let t=l(r,wm);return await e.sendSignedWsCommand({op:["createOrders",t.orders.map(Um)],responseSchema:z.array(PerpsPostOrderAckSchema),timeoutMessage:"Perps post order acknowledgement timed out.",expiresAt:t.expiresAt})}var Lm=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 is(e,r){let t=l(r,Lm),[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 Mm=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,Mm);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 Fm=z.object({instrumentId:PerpsInstrumentIdSchema,leverage:z.number().int().positive(),crossMargin:z.boolean()}),ps=k(d,j,c,a);async function cs(e,r){let t=l(r,Fm),o=await e.sendSignedWsCommand({op:["updateLeverage",[t.instrumentId,t.leverage,t.crossMargin]],responseSchema:PerpsCommandAckSchema,timeoutMessage:"Perps update leverage acknowledgement timed out."});if(o.status==="err")throw new d(o.error??"Perps update leverage command was rejected.",{status:200})}var Bm=z.object({instrumentId:PerpsInstrumentIdSchema,amount:PerpsDecimalInputSchema}),ds=k(d,j,c,b,a);async function us(e,r){let t=l(r,Bm),o=toDecimalString(t.amount),n=await e.sendSignedHttpCommand("/v1/trade/margin",{op:["updateMargin",[t.instrumentId,o]],bodyOp:{type:"updateMargin",args:{amt:o,iid:t.instrumentId}}});if(n.status==="err")throw new d(n.error??"Perps update margin command was rejected.",{status:200})}function Um(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.clientOrderId]}function ms(e){let[r,t]=e;switch(r){case "createOrders":return {type:r,args:t.map(Dm)};case "cancelOrders":case "cancelOrdersCOID":return {type:r,args:t};case "updateLeverage":{let[o,n,s]=t;return {type:r,args:{cross:s,iid:o,lev:n}}}default:invariant(false,`Unsupported Perps command: ${String(r)}`);}}function Dm(e){let r={iid:e[0],buy:e[1]};return e[2]!==void 0&&(r.p=e[2]),r.qty=e[3],e[4]!==void 0&&(r.tif=e[4]),r.po=e[5],e[6]!==void 0&&(r.c=e[6]),r}var Nm=3e4,ys=3e4,Gm=500,Km=["balances","portfolio","orders","fills","funding","deposits","withdrawals"],$m=z.object({id:z.number().int().positive().optional(),data:z.unknown().optional()}).passthrough(),fs=z.union([PerpsCommandAckSchema,z.array(PerpsCommandAckSchema)]).transform(e=>Array.isArray(e)?e.find(r=>r.status==="err")??e[0]:e),gs=class{credentials;#e;#r;#t;#n;#o;#c=new Ir({heartbeat:new kr});#i=pushable({objectMode:true});#s=new Map;#p=new Set;#a=new br;#d=new Map;#l=1;#u;constructor(r){this.#e=new Cr({headers:r.headers,resolveHeaders:async()=>this.#x(),root:r.restUrl}),this.#r=r.chainId,this.credentials=r.credentials,this.#t=r.headers,this.#n=r.onClose,this.#o=r.wsUrl;}get closed(){return this.#u!==void 0}async connect(){await this.#g(false);}async close(){this.#u===void 0&&(this.#u=this.#b()),await this.#u;}[Symbol.asyncIterator](){return this.#i[Symbol.asyncIterator]()}async fetchBalances(){return await Kn(this.#e)}async fetchPortfolio(){return await $n(this.#e)}async fetchAccountConfig(r){return await Vn(this.#e,r)}async fetchOpenOrders(r){return await Yn(this.#e,r)}async fetchOrders(r){return await Jn(this.#e,r)}listFills(r={}){return Zn(this.#e,r)}listFundingPayments(r={}){return Qn(this.#e,r)}listDeposits(r={}){return Xn(this.#e,r)}listWithdrawals(r={}){return es(this.#e,r)}listEquityHistory(r){return rs(this.#e,r)}listPnlHistory(r){return ts(this.#e,r)}async placeOrder(r){let[t]=await Tt(this.#m(),{orders:[r]}).then(expectNonEmptyArray);if(t.status==="err")throw new d(t.error,{status:200});return (await this.#O(n=>n.type==="order"&&n.payload.id===t.orderId,Gm)).payload}async postOrders(r){return await Tt(this.#m(),r)}async cancelOrder(r){return await is(this.#m(),r)}async cancelOrders(r){return await wr(this.#m(),r)}async updateLeverage(r){return await cs(this.#m(),r)}async updateMargin(r){return await us(this.#m(),r)}async#g(r){await this.#c.connect({onClose:()=>this.#q(),onError:()=>{},onMessage:t=>this.#I(t),onOpen:()=>{},headers:this.#t,url:this.#o}),await this.#S(),await this.#T(),this.#a.resetBackoff(),r&&(this.#d.clear(),this.#i.push({reason:"reconnect",type:"resync"}));}async#S(){await this.#y({id:this.#l++,op:{args:{proxy:this.credentials.proxy,secret:this.credentials.secret},type:"auth"},req:"post"},fs,Nm,"Perps session authentication timed out.");}async#T(){await this.#y({id:this.#l++,req:"sub",chs:Km},fs,ys,"Perps session subscription timed out.");}#x(){return {"POLYMARKET-PROXY":this.credentials.proxy,"POLYMARKET-SECRET":this.credentials.secret}}#m(){return {sendSignedWsCommand:r=>this.#C(r),sendSignedHttpCommand:(r,t)=>this.#k(r,t)}}async#C(r){let t=ms(r.op),o=this.#P(r.op,r.expiresAt);return await this.#y({...o,id:this.#l++,op:t,req:"post"},r.responseSchema,ys,r.timeoutMessage)}async#k(r,t){let o=this.#P(t.op);return await unwrap(this.#e.patch(r,{json:{...o,op:t.bodyOp}}).andThen(y(PerpsCommandAckSchema)))}#P(r,t){let o=Jm(),n=Date.now(),s;try{s=Fn({chainId:this.#r,op:r,privateKey:this.credentials.privateKey,salt:o,timestamp:n});}catch(f){throw j.fromError(f,"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=Vm(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#b(){this.#a.stop(),this.#E(new c("Perps session closed.")),this.#h(new c("Perps session closed.")),this.#i.end(),await this.#c.close(),this.#n(this);}#I(r){if(this.#v(r))return;let t=PerpsSessionUpdateEventSchema.safeParse(r);if(!t.success)return;let o=t.data;this.#A(o),this.#R(o);}#v(r){let t=$m.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=Ps(t.data.data??t.data);return s!==void 0?o.reject(new d(s.error,{status:200})):o.reject(new c("Perps session unexpected response.")),true}return Ym(n.data)?o.reject(new d(n.data.error,{status:200})):o.resolve(n.data),true}#q(){this.#E(new c("Perps session connection closed.")),this.#h(new c("Perps session connection closed.")),this.#u===void 0&&this.#a.schedule({reconnect:()=>this.#g(true),shouldReconnect:()=>this.#u===void 0});}#E(r){for(let t of this.#s.values())t.reject(r);this.#s.clear();}#A(r){let t=this.#d.get(r.channel);this.#d.set(r.channel,r.sequence),!(t===void 0||r.sequence===t+1)&&this.#R({channel:r.channel,previousSequence:t,reason:"sequence_gap",sequence:r.sequence,type:"resync"});}#R(r){this.#L(r),this.#i.push(r);}#O(r,t){return this.#w(r,t).then(o=>o)}#w(r,t){let o,n=new Promise((s,a)=>{o={predicate:r,reject:a,resolve:s,timeout:setNonBlockingTimeout(()=>{this.#f(o),a(new f("Perps event wait timed out."));},t)};});return this.#p.add(o),n}#L(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 Vm(e){let r,t;return {promise:new Promise((n,s)=>{r=n,t=s;}),reject:t,resolve:r,schema:e}}function Ym(e){return Ps(e)!==void 0}function Ps(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 Jm(){let[e]=globalThis.crypto.getRandomValues(new Uint32Array(1));return invariant(e!==void 0,"Expected crypto.getRandomValues to return a salt."),e}var qe=k(e,d,c,b,a),ye=z.number().int().nonnegative(),hs=1440*60*1e3,Pl=z.object({instrumentId:PerpsInstrumentIdSchema.optional(),instrumentType:PerpsInstrumentTypeSchema.optional(),category:PerpsInstrumentCategorySchema.optional()}).default({}),Ux=qe;async function Dx(e,r){let t=l(r,Pl);return unwrap(e.perps.get("/v1/info/instruments",{params:P(t,h())}).andThen(y(FetchPerpsInstrumentsResponseSchema)))}var El=z.object({instrumentId:PerpsInstrumentIdSchema}),zx=qe;async function jx(e,r){let t=l(r,El),[o]=await hl(e,t);if(o===void 0)throw new b(`Perps ticker ${t.instrumentId} was not returned by the API`);return o}var Rl=z.object({instrumentId:PerpsInstrumentIdSchema.optional()}).default({}),Hx=qe;async function hl(e,r){let t=l(r,Rl),o=P(t,h()),[n,s]=await Promise.all([unwrap(e.perps.get("/v1/info/tickers",{params:o}).andThen(y(FetchPerpsTickersResponseSchema))),unwrap(e.perps.get("/v1/info/statistics",{params:o}).andThen(y(FetchPerpsStatisticsResponseSchema)))]),a=new Map(s.map(f=>[f.instrumentId,f]));return n.map(f=>{let g=a.get(f.instrumentId);return {...f,openPrice:g?.openPrice,volume24h:g?.volume}})}var Sl=z.union([z.literal(10),z.literal(100),z.literal(500),z.literal(1e3)]),Tl=z.object({instrumentId:PerpsInstrumentIdSchema,depth:Sl.default(100)}),Wx=qe;async function _x(e,r){let t=l(r,Tl);return unwrap(e.perps.get("/v1/info/book",{params:P(t,h())}).andThen(y(PerpsBookSchema)))}var xl=z.object({instrumentId:PerpsInstrumentIdSchema,interval:PerpsKlineIntervalSchema,start:ye.optional(),end:ye.optional()}),Cl=z.union([xl.extend({cursor:PaginationCursorSchema.optional()}).transform(({cursor:e,...r})=>({cursor:e,params:Al(r)})),z.object({cursor:PaginationCursorSchema}).transform(({cursor:e})=>({cursor:e,params:void 0}))]),Nx=qe;function Gx(e,r){let{cursor:t,params:o}=l(r,Cl);return T(n=>{let s=n===void 0?Ol(o):Ml(n);return e.perps.get("/v1/info/klines",{params:P({endTimestamp:s.endTimestamp,instrumentId:s.instrumentId,interval:s.interval,startTimestamp:s.startTimestamp},h())}).andThen(y(FetchPerpsCandlesResponseSchema)).map(a=>{let f=a.data.at(-1),g=a.more&&f!==void 0;return {items:a.data,hasMore:g,nextCursor:g?It({...s,startTimestamp:f.timestamp+Ul(s.interval)}):void 0}})},t)}var Ss=z.object({instrumentId:PerpsInstrumentIdSchema,start:ye.optional(),end:ye.optional()}),kl=z.union([Ss.extend({cursor:PaginationCursorSchema.optional()}).transform(({cursor:e,...r})=>({cursor:e,params:Ts(r)})),z.object({cursor:PaginationCursorSchema}).transform(({cursor:e})=>({cursor:e,params:void 0}))]),Kx=qe;function $x(e,r){let{cursor:t,params:o}=l(r,kl);return T(n=>{let s=n===void 0?wl(o):Fl(n);return e.perps.get("/v1/info/funding",{params:P({endTimestamp:s.endTimestamp,instrumentId:s.instrumentId,startTimestamp:s.startTimestamp},h())}).andThen(y(FetchPerpsFundingHistoryResponseSchema)).map(a=>{let f=a.data.at(-1),g=a.more&&f!==void 0&&f.timestamp>s.startTimestamp;return {items:a.data,hasMore:g,nextCursor:g?It({...s,endTimestamp:f.timestamp-1}):void 0}})},t)}var bl=z.union([Ss.extend({cursor:PaginationCursorSchema.optional()}).transform(({cursor:e,...r})=>({cursor:e,params:Ts(r)})),z.object({cursor:PaginationCursorSchema}).transform(({cursor:e})=>({cursor:e,params:void 0}))]),Vx=qe;function Yx(e,r){let{cursor:t,params:o}=l(r,bl);return T(n=>{let s=n===void 0?Ll(o):Bl(n),a=new Set(s.seenTradeIds);return e.perps.get("/v1/info/trades",{params:P({endTimestamp:s.endTimestamp,instrumentId:s.instrumentId,startTimestamp:s.startTimestamp},h())}).andThen(y(FetchPerpsTradesResponseSchema)).map(f=>{let g=f.data.filter(pa=>!a.has(pa.tradeId)),L=f.data.at(-1),I=g.at(-1),$=I?.timestamp??L?.timestamp,M=f.more&&$!==void 0&&$>s.startTimestamp;return {items:g,hasMore:M,nextCursor:M?It({...s,endTimestamp:I===void 0?$-1:$,seenTradeIds:I===void 0?[]:Dl(s,g,I)}):void 0}})},t)}var Jx=k(e,d,c,b);async function Zx(e){return (await unwrap(e.perps.get("/v1/info/fees").andThen(y(FetchPerpsFeesResponseSchema)))).feeSchedule}var Il=z.object({kind:z.literal("perpsCandles"),instrumentId:PerpsInstrumentIdSchema,interval:PerpsKlineIntervalSchema,startTimestamp:ye,endTimestamp:ye}),vl=z.object({kind:z.literal("perpsFundingHistory"),instrumentId:PerpsInstrumentIdSchema,startTimestamp:ye,endTimestamp:ye}),ql=z.object({kind:z.literal("perpsTrades"),instrumentId:PerpsInstrumentIdSchema,startTimestamp:ye,endTimestamp:ye,seenTradeIds:z.array(PerpsTradeIdSchema)});function Al(e){let r=Date.now();return {endTimestamp:e.end??r,instrumentId:e.instrumentId,interval:e.interval,startTimestamp:e.start??r-hs}}function Ts(e){let r=Date.now();return {endTimestamp:e.end??r,instrumentId:e.instrumentId,startTimestamp:e.start??r-hs}}function Ol(e){return invariant(e!==void 0,"Expected initial Perps candles params."),{kind:"perpsCandles",...e}}function wl(e){return invariant(e!==void 0,"Expected initial Perps funding params."),{kind:"perpsFundingHistory",...e}}function Ll(e){return invariant(e!==void 0,"Expected initial Perps trades params."),{kind:"perpsTrades",seenTradeIds:[],...e}}function Ml(e){return bt(e,Il)}function Fl(e){return bt(e,vl)}function Bl(e){return bt(e,ql)}function bt(e,r){try{return r.parse(JSON.parse(atob(e)))}catch(t){throw new a("Invalid Perps pagination cursor",{cause:t})}}function It(e){return toPaginationCursor(btoa(JSON.stringify(e)))}function Ul(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 Dl(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 zl=z.custom(e=>isPrivateKey(e),"Expected a hex-encoded 32-byte private key."),jl=z.object({proxy:z.string().transform(e=>expectEvmAddress(e)),privateKey:zl,secret:z.string().min(1),expiresAt:z.number().int().positive()}),Hl=10080*60*1e3,Wl=z.strictObject({expiresIn:z.number().int().positive().default(Hl),label:z.string().min(1).optional()}),_l=z.strictObject({credentials:jl}),Nl=z.union([Wl,_l]),Gl=z.object({proxy:z.string().transform(e=>expectEvmAddress(e))}),xs=z.bigint().positive().max(Y),Kl=z.object({amount:xs,metadata:G.optional()}),$l=z.object({amount:xs}),Qx=k(e,d,j,c,b,a),Xx=k(e,d,j,c,b,a),eC=k(a),rC=k(h$1,e,d,j,c,b,a),tC=k(e,d,j,c,b,a);async function oC(e,r={}){let t=l(r,Nl),o="credentials"in t?await Jl(e,t.credentials):await Yl(e,t);return e.webSockets.perpsSession.connect(o)}async function nC(e,r){let t=l(r,Gl),o={type:"deleteProxy",args:{proxy:t.proxy}},n=["deleteProxy",[t.proxy]],s=vt(),a=Date.now(),f=await Ql(e,{salt:s,signedOp:n,timestamp:a}),g=await unwrap(e.perps.del("/v1/account/proxy",{json:{op:o,salt:s,sig:f,ts:a}}).andThen(y(PerpsDeleteProxyResponseSchema)));if(g.status==="err")throw new d(g.error??"Perps credentials revocation was rejected.",{status:200})}async function Vl(e,r){let t=l(r,Kl),{contracts:o}=e.environment,n=ho(o.perpsDepositContract,o.collateralToken,t.amount,e.account.signer);return async function*(){return e.account.walletType===WalletType.EOA?_(yield sy(N(e.environment.chainId,n))):yield*await J(e,{calls:[n],metadata:t.metadata??`Deposit ${t.amount} of ${o.collateralToken} to Perps`})}.call(null)}function sC(e,r){return Vl(e,r).then(W(e.signer))}async function aC(e,r){let t=l(r,$l),o=Math.floor(Date.now()/1e3),n=vt(),s={type:"withdraw",args:{account:e.account.signer,token:e.environment.contracts.collateralToken,amount:t.amount.toString(),to:e.account.wallet}},a=await Xl(e,{amount:t.amount,salt:n,timestamp:o}),f=await unwrap(e.perps.post("/v1/account/withdraw",{json:{op:s,salt:n,sig:a,ts:o}}).andThen(y(PerpsWithdrawResponseSchema)));if(f.status==="err")throw new d(f.error??"Perps withdrawal was rejected.",{status:200});if(f.withdrawalId===void 0)throw new b("Perps withdrawal response did not include a withdrawal ID.");return f.withdrawalId}async function Yl(e,r){let t=ty(),o=ks(t),n=e.account.signer,s=Date.now()+r.expiresIn,a=Date.now(),f=vt(),g={args:{expiry:s,owner:n,proxy:o},type:"createProxy"},L=await Zl(e,{expiresAt:s,proxy:o,salt:f,timestamp:a}),I={op:g,salt:f,sig:L,ts:a};r.label!==void 0&&(I.label=r.label);let $=await unwrap(e.perps.post("/v1/account/proxy",{json:I}).andThen(y(PerpsCreateProxyResponseSchema))),M={expiresAt:s,privateKey:t,proxy:o,secret:$.secret};return Cs(e,M)}async function Jl(e,r){return oy(r),Cs(e,r)}async function Cs(e,r){let t=await unwrap(e.perps.get("/v1/account/credentials",{headers:ny(r)}).andThen(y(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 Zl(e,r){try{return await e.signer.signTypedData(ry({chainId:e.environment.chainId,...r}))}catch(t){throw j.fromError(t,"Could not sign the Perps proxy credentials request")}}async function Ql(e,r){try{return await e.signer.signTypedData(lt({chainId:e.environment.chainId,op:r.signedOp,salt:r.salt,timestamp:r.timestamp}))}catch(t){throw j.fromError(t,"Could not sign the Perps operation request")}}async function Xl(e,r){try{return await e.signer.signTypedData(ey({account:e.account.signer,chainId:e.environment.chainId,contract:e.environment.contracts.perpsDepositContract,token:e.environment.contracts.collateralToken,to:e.account.wallet,...r}))}catch(t){throw j.fromError(t,"Could not sign the Perps withdrawal request")}}function ey(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 ry(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 ty(){return expectPrivateKey(Secp256k1.randomPrivateKey(),"Generated invalid Perps proxy key.")}function ks(e){return expectEvmAddress(Address.fromPublicKey(Secp256k1.getPublicKey({privateKey:e})))}function oy(e){let r=ks(e.privateKey);if(!isSameEvmAddress(r,e.proxy))throw new a("Perps credentials private key does not match the proxy address.")}function ny(e){return {"POLYMARKET-PROXY":e.proxy,"POLYMARKET-SECRET":e.secret}}function sy(e){return {kind:"sendPerpsDepositTransaction",request:e}}function vt(){let[e]=crypto.getRandomValues(new Uint32Array(1));return invariant(e!==void 0,"Expected crypto.getRandomValues to return a salt."),e}var yy=z.enum(["CURRENT","INITIAL","TOKENS","CASHPNL","PERCENTPNL","TITLE","RESOLVING","PRICE","AVGPRICE"]),bs=z.enum(["ASC","DESC"]),fy=z.enum(["REALIZEDPNL","TITLE","PRICE","AVGPRICE","TIMESTAMP"]),gy=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:A.default(20),sortBy:yy.optional(),sortDirection:bs.optional(),title:z.string().max(100).optional()}).refine(e=>!(e.market&&e.eventId),{message:"Provide market or eventId, not both",path:["eventId"]}),Py=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:A.default(20),sortBy:fy.optional(),sortDirection:bs.optional()}).refine(e=>!(e.market&&e.eventId),{message:"Provide market or eventId, not both",path:["eventId"]}),Ey=z.object({cursor:PaginationCursorSchema.optional(),user:z.string(),pageSize:A.default(20),status:ComboPositionStatusSchema.optional(),conditionId:ComboConditionIdSchema.optional(),positionId:PositionIdSchema.optional()}),Ry=z.object({user:z.string(),market:z.array(z.string()).optional()}),hy=z.object({user:z.string()}),Sy=z.object({user:z.string()}),EC=k(e,d,c,b,a);function RC(e,r){let{cursor:t,pageSize:o,...n}=l(r,gy);return T(s=>{let a=U(s,o);return e.data.get("/positions",{params:H({...n,limit:a.pageSize+1,offset:a.offset})}).andThen(y(ListPositionsResponseSchema)).map(f=>{let g=f.length>a.pageSize;return {items:f.slice(0,a.pageSize),hasMore:g,nextCursor:g?F({offset:a.offset+a.pageSize,pageSize:a.pageSize}):void 0}})},t)}var hC=k(e,d,c,b,a),SC=k(e,d,c,b,a);function TC(e,r){let{cursor:t,pageSize:o,...n}=l(r,Py);return T(s=>{let a=U(s,o);return e.data.get("/closed-positions",{params:H({...n,limit:a.pageSize+1,offset:a.offset})}).andThen(y(ListClosedPositionsResponseSchema)).map(f=>{let g=f.length>a.pageSize;return {items:f.slice(0,a.pageSize),hasMore:g,nextCursor:g?F({offset:a.offset+a.pageSize,pageSize:a.pageSize}):void 0}})},t)}function xC(e,r){let{cursor:t,pageSize:o,...n}=l(r,Ey);return T(s=>{let a=U(s,o);return e.data.get("/v1/positions/combos",{params:P({...n,limit:a.pageSize+1,offset:a.offset},h({conditionId:"combo_condition_id",positionId:"combo_position_id"}))}).andThen(y(ListComboPositionsResponseSchema)).map(f=>{let g=f.combos.length>a.pageSize;return {items:f.combos.slice(0,a.pageSize),hasMore:g,nextCursor:g?F({offset:a.offset+a.pageSize,pageSize:a.pageSize}):void 0}})},t)}var CC=k(e,d,c,b,a);async function kC(e,r){let t=l(r,Ry);return unwrap(e.data.get("/value",{params:H(t)}).andThen(y(FetchPortfolioValueResponseSchema)))}var bC=k(e,d,c,b,a);async function IC(e,r){let t=l(r,hy);return unwrap(e.data.get("/traded",{params:H(t)}).andThen(y(TradedSchema)))}var vC=k(e,d,c,b,a);async function qC(e,r){let t=l(r,Sy);return unwrap(e.data.get("/v1/accounting/snapshot",{params:H(t)}).andThen(_t))}var Os=32,ws=3n,qs=50,xy=(1n<<256n)-1n;function Ot(e){let r=AbiParameters.encode([{name:"legs",type:"uint256[]"}],[e]),t=Hash.keccak256(AbiParameters.encode([{name:"moduleId",type:"uint256"},{name:"data",type:"bytes"}],[ws,r])),o=toComboConditionId(`0x03${t.slice(34)}0000000000000000000000000000`);return {conditionId:o,positionIds:[toPositionId(BigInt(`${o}00`).toString()),toPositionId(BigInt(`${o}01`).toString())]}}function Ls(e){if(e.length===0||e.length>qs)throw new a(`Combo legs must include 1 to ${qs} position IDs`);let r=e.map(t=>{let o=Fs(t),n=o.toString(16).padStart(Os*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 Ms(e){let t=Fs(e).toString(16).padStart(Os*2,"0"),o=BigInt(`0x${t.slice(0,2)}`),n=Number.parseInt(t.slice(-2),16);if(o!==ws)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 Fs(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>xy)throw new a("Position ID must be a uint256 value");return t}var Us=z.object({amount:z.bigint().min(0n),conditionId:CtfConditionIdSchema,metadata:G.optional()}),ky=z.object({amount:z.bigint().positive(),legs:z.array(PositionIdSchema).min(1).max(50),metadata:G.optional()}),Ds=z.array(PositionIdSchema).min(1).max(50).transform(Ls),by=z.object({amount:z.bigint().positive(),legs:Ds,metadata:G.optional()}),Iy=z.union([Us.extend({legs:z.never().optional()}),ky.extend({conditionId:z.never().optional()})]),zs=k(e,d,c,b,a),YC=zs,JC=zs,js=k(e,d,c,b,a),ZC=js,QC=js,Hs=k(e,d,c,b,a),XC=Hs,ek=Hs;async function Ws(e,r){let t=l(r,Us),o=await Ft(e,{conditionId:t.conditionId}),n=So(o.adapterAddress,e.environment.contracts.collateralToken,o.conditionId,t.amount);return async function*(){return e.account.walletType===WalletType.EOA?_(yield wt(N(e.environment.chainId,n))):yield*await J(e,{calls:[n],metadata:t.metadata??`Split ${t.amount} positions for market ${o.marketId} (condition ${o.conditionId})`})}.call(null)}async function _s(e,r){let t=l(r,by),o=Wr(e.environment.contracts.combinatorialModule,t.legs),n=Ot(t.legs),s=Co(e.environment.contracts.protocolV2Router,n.conditionId,t.amount);return async function*(){return e.account.walletType===WalletType.EOA?(await _(yield wt(N(e.environment.chainId,o))).wait(),_(yield wt(N(e.environment.chainId,s)))):yield*await J(e,{calls:[o,s],metadata:t.metadata??`Split ${t.amount} combo positions for condition ${n.conditionId}`})}.call(null)}async function vy(e,r){let t=l(r,Iy);return t.legs!==void 0?_s(e,t):Ws(e,t)}var Ns=k(h$1,e,d,j,f,g,c,b,a),rk=Ns,tk=Ns;function ok(e,r){return Ws(e,r).then(W(e.signer))}function nk(e,r){return _s(e,r).then(W(e.signer))}function sk(e,r){return vy(e,r).then(W(e.signer))}var Gs=z.object({amount:z.union([z.bigint().positive(),z.literal("max")]),conditionId:CtfConditionIdSchema,metadata:G.optional()}),qy=z.object({amount:z.union([z.bigint().positive(),z.literal("max")]),legs:z.array(PositionIdSchema).min(1).max(50),metadata:G.optional()}),Ay=z.object({amount:z.union([z.bigint().positive(),z.literal("max")]),legs:Ds,metadata:G.optional()}),Oy=z.union([Gs.extend({legs:z.never().optional()}),qy.extend({conditionId:z.never().optional()})]);async function Ks(e,r){let t=l(r,Gs),o=await Ft(e,{conditionId:t.conditionId}),n=jr(await e.rpc.ethCall(zr(o.positionErc1155Address,e.account.wallet,o.tokenIds))),s=Xs(o.conditionId,n,t.amount),a=To(o.adapterAddress,e.environment.contracts.collateralToken,o.conditionId,s);return async function*(){return e.account.walletType===WalletType.EOA?_(yield Lt(N(e.environment.chainId,a))):yield*await J(e,{calls:[a],metadata:t.metadata??`Merge ${s} positions for market ${o.marketId} (condition ${o.conditionId})`})}.call(null)}async function $s(e,r){let t=l(r,Ay),o=Wr(e.environment.contracts.combinatorialModule,t.legs),n=Ot(t.legs),s=jr(await e.rpc.ethCall(zr(e.environment.contracts.positionManager,e.account.wallet,n.positionIds))),a=Xs(n.conditionId,s,t.amount),f=ko(e.environment.contracts.protocolV2Router,n.conditionId,a);return async function*(){return e.account.walletType===WalletType.EOA?(await _(yield Lt(N(e.environment.chainId,o))).wait(),_(yield Lt(N(e.environment.chainId,f)))):yield*await J(e,{calls:[o,f],metadata:t.metadata??`Merge ${a} combo positions for condition ${n.conditionId}`})}.call(null)}async function wy(e,r){let t=l(r,Oy);return t.legs!==void 0?$s(e,t):Ks(e,t)}var Vs=k(h$1,e,d,j,f,g,c,b,a),ak=Vs,ik=Vs;function pk(e,r){return Ks(e,r).then(W(e.signer))}function ck(e,r){return $s(e,r).then(W(e.signer))}function dk(e,r){return wy(e,r).then(W(e.signer))}var Ys=z.object({conditionId:CtfConditionIdSchema,marketId:z.never().optional(),amount:z.never().optional(),positionId:z.never().optional(),metadata:G.optional()}),Js=z.object({conditionId:z.never().optional(),marketId:MarketIdSchema,amount:z.never().optional(),positionId:z.never().optional(),metadata:G.optional()}),Ly=z.union([Ys,Js]),Zs=z.object({positionId:PositionIdSchema,conditionId:z.never().optional(),marketId:z.never().optional(),metadata:G.optional()}),My=z.union([Ys,Js,Zs]);async function Fy(e,r){let t=l(r,Ly),o=await Ft(e,t.conditionId!==void 0?{conditionId:t.conditionId}:{marketId:t.marketId}),n=xo(o.adapterAddress,e.environment.contracts.collateralToken,o.conditionId);return async function*(){return e.account.walletType===WalletType.EOA?_(yield Qs(N(e.environment.chainId,n))):yield*await J(e,{calls:[n],metadata:t.metadata??`Redeem positions for market ${o.marketId} (condition ${o.conditionId})`})}.call(null)}async function By(e,r){let t=l(r,Zs),o=Ms(t.positionId),n=Ro(await e.rpc.ethCall(Eo(e.environment.contracts.positionManager,e.account.wallet,t.positionId)));if(n===0n)throw new a("Combo position has no balance to redeem");let s=bo(e.environment.contracts.protocolV2Router,o.conditionId,o.outcomeIndex,n);return async function*(){return e.account.walletType===WalletType.EOA?_(yield Qs(N(e.environment.chainId,s))):yield*await J(e,{calls:[s],metadata:t.metadata??`Redeem combo position ${t.positionId}`})}.call(null)}async function Uy(e,r){let t=l(r,My);return t.positionId!==void 0?By(e,t):Fy(e,t)}var uk=k(h$1,e,d,j,c,b,a);function mk(e,r){return Uy(e,r).then(W(e.signer))}function wt(e){return {kind:"sendSplitPositionTransaction",request:e}}function Lt(e){return {kind:"sendMergePositionsTransaction",request:e}}function Qs(e){return {kind:"sendRedeemPositionsTransaction",request:e}}async function Ft(e,r){let t=r.conditionId!==void 0?`condition ${r.conditionId}`:`market ${r.marketId}`,o=await tn(e,r.conditionId!==void 0?{conditionIds:[r.conditionId],pageSize:1}:{ids:[Dy(r.marketId)],pageSize:1}).firstPage(),[n]=o.items;if(n===void 0)throw new a(`No market found for ${t}`);let s=zy(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 Dy(e){let r=Number(e);if(!Number.isInteger(r))throw new a(`Market ID must be an integer, received ${e}`);return r}function zy(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 Xs(e,r,t){let o=jy(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 jy(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 Gy=z.object({address:z.string()}),Sk=k(e,d,c,b,a);async function Tk(e,r){let t=l(r,Gy);return unwrap(e.gamma.get("/public-profile",{params:P(t,h())}).andThen(y(PublicProfileSchema)).orElse(o=>o instanceof d&&o.status===404?ok$1(null):err(o)))}var Bt=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;}},bk=k(Bt,j,f,c,a),Ut=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;}},Ik=k(Ut,f,c),Dt=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;}},vk=k(Dt,f,c),qk=k(c);async function Ak(e){return e.webSockets.rfqQuoter.connect()}var ra=(f=>(f.Volume="volume",f.Volume24Hr="volume_24hr",f.Liquidity="liquidity",f.Competitive="competitive",f.ClosedTime="closed_time",f.StartDate="start_date",f.EndDate="end_date",f))(ra||{}),Vy=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:A.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(ra).optional()}),$k=k(e,d,c,b,a);function Vk(e,r){let{cursor:t,pageSize:o,...n}=l(r,Vy);return T(s=>{let a=U(s,o);return e.gamma.get("/public-search",{params:P({...n,limitPerType:a.pageSize,page:a.offset},h({excludeTagIds:"exclude_tag_id"}))}).andThen(y(PublicSearchResponseSchema)).map(f=>({items:Yy(f),hasMore:f.pagination?.hasMore??false,totalCount:f.pagination?.totalResults??void 0,nextCursor:f.pagination?.hasMore?F({offset:a.offset+1,pageSize:a.pageSize}):void 0}))},t??F({offset:1,pageSize:o}),{events:[],profiles:[],tags:[]})}function Yy(e){return {events:e.events??[],profiles:e.profiles??[],tags:e.tags??[]}}var ef=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:A.default(20),recurrence:z.enum(["daily","weekly","monthly"]).optional(),slug:z.array(z.string()).optional()}),rf=z.object({id:z.string(),locale:z.string().optional()}),sb=k(e,d,c,b,a);function ab(e,r={}){let{cursor:t,pageSize:o,...n}=l(r,ef);return T(s=>{let a=U(s,o);return e.gamma.get("/series",{params:P({...n,limit:a.pageSize+1,offset:a.offset},h())}).andThen(y(ListSeriesResponseSchema)).map(f=>{let g=f.length>a.pageSize;return {items:f.slice(0,a.pageSize),hasMore:g,nextCursor:g?F({offset:a.offset+a.pageSize,pageSize:a.pageSize}):void 0}})},t)}var ib=k(e,d,c,b,a);async function pb(e,r){let t=l(r,rf);return unwrap(e.gamma.get(`series/${t.id}`,{params:P({locale:t.locale},h())}).andThen(y(SeriesSchema)))}var yb=k(e,d,c,b);async function fb(e){return unwrap(e.gamma.get("/sports").andThen(y(ListSportsMetadataResponseSchema)))}var gb=k(e,d,c,b);async function Pb(e){return unwrap(e.gamma.get("/sports/market-types").andThen(y(SportsMarketTypesResponseSchema)))}async function Sb(e,r){let t=await Promise.all(r.map(o=>af(e,o)));return pf(t)}function af(e,r){switch(r.topic){case "market":return e.webSockets.clobMarket.subscribe(r);case "sports":return e.webSockets.sports.subscribe(r);case "comments":case "prices.crypto.binance":case "prices.crypto.chainlink":case "prices.equity.pyth":return e.webSockets.rtds.subscribe(r);case "perps.trades":case "perps.bbo":case "perps.book":case "perps.candles":case "perps.tickers":case "perps.statistics":return e.webSockets.perpsSubscriptions.subscribe(r);case "user":return invariant(e.isSecureClient(),"A 'user' subscription requires a secure client instance."),e.webSockets.clobUser.subscribe(r)}}function pf(e){let r;async function t(){r===void 0&&(r=Promise.all(e.map(n=>n.close())).then(()=>{})),await r;}let o=sf(...e);return {close:t,[Symbol.asyncIterator](){return o[Symbol.asyncIterator]()}}}var uf=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:A.default(20)}),mf=z.union([z.object({id:z.string(),includeTemplate:z.boolean().optional(),locale:z.string().optional()}),z.object({slug:z.string(),locale:z.string().optional()})]),lf=z.object({id:z.string(),omitEmpty:z.boolean().optional(),status:z.enum(["active","closed","all"]).optional()}),yf=z.object({slug:z.string()}),ff=z.object({id:z.string(),locale:z.string().optional(),omitEmpty:z.boolean().optional(),status:z.enum(["active","closed","all"]).optional()}),gf=z.object({locale:z.string().optional(),slug:z.string(),omitEmpty:z.boolean().optional(),status:z.enum(["active","closed","all"]).optional()}),wb=k(e,d,c,b,a);function Lb(e,r={}){let{cursor:t,pageSize:o,...n}=l(r,uf);return T(s=>{let a=U(s,o);return e.gamma.get("/tags",{params:P({...n,limit:a.pageSize+1,offset:a.offset},h())}).andThen(y(ListTagsResponseSchema)).map(f=>{let g=f.length>a.pageSize;return {items:f.slice(0,a.pageSize),hasMore:g,nextCursor:g?F({offset:a.offset+a.pageSize,pageSize:a.pageSize}):void 0}})},t)}var Mb=k(e,d,c,b,a);async function Fb(e,r){let t=l(r,mf);return "id"in t?unwrap(e.gamma.get(`tags/${t.id}`,{params:P({includeTemplate:t.includeTemplate,locale:t.locale},h())}).andThen(y(TagSchema))):unwrap(e.gamma.get(`tags/slug/${t.slug}`,{params:P({locale:t.locale},h())}).andThen(y(TagSchema)))}var Bb=k(e,d,c,b,a);async function Ub(e,r){if("id"in r){let o=l(r,lf);return unwrap(e.gamma.get(`tags/${o.id}/related-tags`,{params:P({omitEmpty:o.omitEmpty,status:o.status},h())}).andThen(y(ListRelatedTagsResponseSchema)))}let t=l(r,yf);return unwrap(e.gamma.get(`tags/slug/${t.slug}/related-tags`).andThen(y(ListRelatedTagsResponseSchema)))}var Db=k(e,d,c,b,a);async function zb(e,r){if("id"in r){let o=l(r,ff);return unwrap(e.gamma.get(`tags/${o.id}/related-tags/tags`,{params:P({locale:o.locale,omitEmpty:o.omitEmpty,status:o.status},h())}).andThen(y(ListRelatedTagResourcesResponseSchema)))}let t=l(r,gf);return unwrap(e.gamma.get(`tags/slug/${t.slug}/related-tags/tags`,{params:P({locale:t.locale,omitEmpty:t.omitEmpty,status:t.status},h())}).andThen(y(ListRelatedTagResourcesResponseSchema)))}var Rf=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:A.default(20),providerId:z.array(z.number().int()).optional()}),Yb=k(e,d,c,b,a);function Jb(e,r={}){let{cursor:t,pageSize:o,...n}=l(r,Rf);return T(s=>{let a=U(s,o);return e.gamma.get("/teams",{params:P({...n,limit:a.pageSize+1,offset:a.offset},h({providerId:"provider_id"}))}).andThen(y(ListTeamsResponseSchema)).map(f=>{let g=f.length>a.pageSize;return {items:f.slice(0,a.pageSize),hasMore:g,nextCursor:g?F({offset:a.offset+a.pageSize,pageSize:a.pageSize}):void 0}})},t)}var Sf=z.object({amount:z.bigint(),metadata:G.optional(),recipientAddress:EvmAddressSchema,tokenAddress:EvmAddressSchema}),iI=k(a);async function Tf(e,r){let t=l(r,Sf);return async function*(){return e.account.walletType===WalletType.EOA?_(yield xf(N(e.environment.chainId,Hr(t.tokenAddress,t.recipientAddress,t.amount)))):yield*await J(e,{calls:[Hr(t.tokenAddress,t.recipientAddress,t.amount)],metadata:t.metadata??`Transfer ${t.amount} of ${t.tokenAddress} to ${t.recipientAddress}`})}.call(null)}var pI=k(h$1,e,d,j,c,b,a);function cI(e,r){return Tf(e,r).then(W(e.signer))}function xf(e){return {kind:"sendErc20TransferTransaction",request:e}}export{fg as $,pE as $a,GR as $b,xu as $c,JC as $d,fb as $e,Qg as A,pp as Aa,VE as Ab,$h as Ac,Jx as Ad,Uy as Ae,bo as B,vP as Ba,YE as Bb,Vh as Bc,Zx as Bd,uk as Be,Xg as C,J as Ca,JE as Cb,Yh as Cc,Qx as Cd,mk as Ce,Wr as D,qP as Da,ZE as Db,Jh as Dc,Xx as Dd,Sk as De,Io as E,jP as Ea,QE as Eb,nS as Ec,eC as Ed,Tk as Ee,vo as F,Cp as Fa,XE as Fb,sS as Fc,rC as Fd,Bt as Fe,l as G,HP as Ga,eR as Gb,Qr as Gc,tC as Gd,bk as Ge,Gt as H,Mo as Ha,rR as Hb,yS as Hc,oC as Hd,Ut as He,Wf as I,WP as Ia,tR as Ib,fS as Ic,nC as Id,Ik as Ie,Zt as J,bp as Ja,oR as Jb,xr as Jc,Vl as Jd,Dt as Je,eo as K,_P as Ka,nR as Kb,gS as Kc,sC as Kd,vk as Ke,rg as L,Fo as La,sR as Lb,xn as Lc,aC as Ld,qk as Le,tg as M,NP as Ma,aR as Mb,Cn as Mc,EC as Md,Ak as Me,og as N,Ip as Na,iR as Nb,ct as Nc,RC as Nd,ng as O,GP as Oa,pR as Ob,Eu as Oc,hC as Od,sg as P,KP as Pa,cR as Pb,dt as Pc,SC as Pd,ag as Q,XP as Qa,hR as Qb,Ru as Qc,TC as Qd,ig as R,Mp as Ra,SR as Rb,ut as Rc,xC as Rd,pg as S,eE as Sa,TR as Sb,tT as Sc,CC as Sd,cg as T,Fp as Ta,xR as Tb,oT as Tc,kC as Td,ra as Te,dg as U,rE as Ua,CR as Ub,nT as Uc,bC as Ud,$k as Ue,ug as V,tE as Va,kR as Vb,sT as Vc,IC as Vd,Vk as Ve,mg as W,oE as Wa,jR as Wb,xT as Wc,vC as Wd,sb as We,lg as X,nE as Xa,HR as Xb,Tu as Xc,qC as Xd,ab as Xe,Ur as Y,sE as Ya,WR as Yb,CT as Yc,ib as Ye,yg as Z,aE as Za,_R as Zb,kT as Zc,zs as Zd,pb as Ze,oo as _,iE as _a,NR as _b,bT as _c,YC as _d,yb as _e,Y as a,gg as aa,cE as ab,KR as ac,IT as ad,js as ae,gb as af,Ng as b,Pg as ba,dE as bb,$R as bc,vT as bd,ZC as be,Pb as bf,dr as c,Eg as ca,uE as cb,nh as cc,Cr as cd,QC as ce,Sb as cf,yo as d,Rg as da,mE as db,sh as dc,Un as dd,Hs as de,wb as df,fo as e,hg as ea,TE as eb,ah as ec,Dn as ed,XC as ee,Lb as ef,ur as f,Sg as fa,xE as fb,ih as fc,zn as fd,ek as fe,Mb as ff,go as g,Tg as ga,ME as gb,ph as gc,kr as gd,Ws as ge,Fb as gf,Po as h,xg as ha,FE as hb,ch as hc,br as hd,_s as he,Bb as hf,Eo as i,Cg as ia,BE as ib,xh as ic,Ir as id,vy as ie,Ub as if,Ro as j,kg as ja,UE as jb,tn as jc,ps as jd,Ns as je,Db as jf,zr as k,bg as ka,DE as kb,Ch as kc,ds as kd,rk as ke,zb as kf,jr as l,Bg as la,Fe as lb,kh as lc,gs as ld,tk as le,Yb as lf,Gg as m,Ug as ma,zE as mb,bh as mc,Ux as md,ok as me,Jb as mf,Hr as n,Dg as na,Be as nb,Ih as nc,Dx as nd,nk as ne,iI as nf,Kg as o,zg as oa,jE as ob,vh as oc,zx as od,sk as oe,Tf as of,ho as p,oP as pa,Ko as pb,qh as pc,jx as pd,Ks as pe,pI as pf,$g as q,_ as qa,HE as qb,Ah as qc,Hx as qd,$s as qe,cI as qf,Vg as r,pP as ra,$o as rb,Oh as rc,hl as rd,wy as re,So as s,qo as sa,WE as sb,wh as sc,Wx as sd,Vs as se,Yg as t,xP as ta,Vo as tb,Lh as tc,_x as td,ak as te,To as u,$r as ua,_E as ub,Mh as uc,Nx as ud,ik as ue,xo as v,CP as va,NE as vb,Fh as vc,Gx as vd,pk as ve,Jg as w,kP as wa,GE as wb,_h as wc,Kx as wd,ck as we,Co as x,G as xa,KE as xb,Nh as xc,$x as xd,dk as xe,Zg as y,bP as ya,$E as yb,Gh as yc,Vx as yd,Fy as ye,ko as z,IP as za,Yo as zb,Kh as zc,Yx as zd,By as ze};//# sourceMappingURL=chunk-FSNACMPO.js.map
2
+ //# sourceMappingURL=chunk-FSNACMPO.js.map