@polymarket/client 0.12.0 → 0.13.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/actions/index.d.ts +6 -6
- package/dist/actions/index.js +1 -1
- package/dist/chunk-MY66WYAN.js +3 -0
- package/dist/chunk-MY66WYAN.js.map +1 -0
- package/dist/ethers-v5.d.ts +1 -1
- package/dist/index.d.ts +6 -6
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/{sports-CERQxAjR.d.ts → sports-DxgyI41A.d.ts} +1 -1
- package/dist/{types-B9F4CyS-.d.ts → types-BGxCI8uu.d.ts} +515 -25
- package/dist/viem.d.ts +1 -1
- package/package.json +2 -2
- package/dist/chunk-5JHFOBBZ.js +0 -3
- package/dist/chunk-5JHFOBBZ.js.map +0 -1
package/dist/ethers-v5.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { ethers } from 'ethers-v5';
|
|
2
|
-
import { T as TypedDataPayload, a as TypedData, S as Signer } from './types-
|
|
2
|
+
import { T as TypedDataPayload, a as TypedData, S as Signer } from './types-BGxCI8uu.js';
|
|
3
3
|
import '@polymarket/bindings';
|
|
4
4
|
import '@polymarket/types';
|
|
5
5
|
import '@polymarket/bindings/gamma';
|
package/dist/index.d.ts
CHANGED
|
@@ -4,18 +4,18 @@ export { CommentParentEntityType, OrderSide, OrderType, SessionSignerKnownScope
|
|
|
4
4
|
export * from '@polymarket/bindings/clob';
|
|
5
5
|
export { AssetType, NotificationType, OrderPostStatus, OrderResponseErrorCode, SignatureType } from '@polymarket/bindings/clob';
|
|
6
6
|
export * from '@polymarket/bindings/data';
|
|
7
|
-
export { ActivityType, BiggestWinnerKind, BuilderVolumeInterval, ComboActivityType, ComboPositionSortBy, ComboPositionStatus, LeaderboardWindow, PositionFilterType, PositionSortBy, PositionStatus, PriceHistoryInterval, ResolutionMarketType, ResolutionReporter, ResolutionSource, ResolutionStatus, SortDirection, TipSide, TradeFilterType, TraderLeaderboardSort, UserPnlFidelity, UserPnlInterval } from '@polymarket/bindings/data';
|
|
7
|
+
export { ActivityType, BiggestWinnerKind, BuilderVolumeInterval, ComboActivityType, ComboPositionSortBy, ComboPositionStatus, LeaderboardWindow, PositionFilterType, PositionSortBy, PositionStatus, PriceHistoryInterval, ResolutionMarketType, ResolutionReporter, ResolutionSettlementTimeBasis, ResolutionSource, ResolutionStatus, SortDirection, TipSide, TradeFilterType, TraderLeaderboardSort, UserPnlFidelity, UserPnlInterval } from '@polymarket/bindings/data';
|
|
8
8
|
export * from '@polymarket/bindings/gamma';
|
|
9
9
|
export { ComboKnownStatus, ProtocolVersion, TeamOrdering, WalletType } from '@polymarket/bindings/gamma';
|
|
10
10
|
export * from '@polymarket/bindings/perps';
|
|
11
|
-
export { PerpsAutoCancelStatus, PerpsCancelOrderResult, PerpsDepositStatus, PerpsInstrumentCategory, PerpsInstrumentType, PerpsInternalTransferDirection, PerpsKlineInterval, PerpsKnownCancelOrderErrorCode, PerpsKnownInternalTransferType, PerpsKnownWithdrawalStatus, PerpsLiquidityRole, PerpsMarginType, PerpsNotificationOrderType, PerpsNotificationType, PerpsOrderStatus, PerpsPostOrderAck, PerpsSide, PerpsSortDirection, PerpsTimeInForce, PerpsUpdateLeverageResult } from '@polymarket/bindings/perps';
|
|
11
|
+
export { PerpsAutoCancelStatus, PerpsCancelOrderResult, PerpsChase, PerpsChaseAccepted, PerpsChaseId, PerpsDepositStatus, PerpsInstrumentCategory, PerpsInstrumentType, PerpsInternalTransferDirection, PerpsKlineInterval, PerpsKnownCancelOrderErrorCode, PerpsKnownInternalTransferType, PerpsKnownWithdrawalStatus, PerpsLiquidityRole, PerpsMarginType, PerpsNotificationOrderType, PerpsNotificationType, PerpsOrderStatus, PerpsPositionSnapshotMarkerKind, PerpsPositionSnapshotStatus, PerpsPostOrderAck, PerpsSide, PerpsSortDirection, PerpsTimeInForce, PerpsTwap, PerpsTwapAccepted, PerpsTwapId, PerpsTwapStatus, PerpsUpdateLeverageBatchResult, PerpsUpdateLeverageRejection, PerpsUpdateLeverageResult } from '@polymarket/bindings/perps';
|
|
12
12
|
export * from '@polymarket/bindings/relayer';
|
|
13
13
|
import { Tagged, EvmAddress } from '@polymarket/types';
|
|
14
|
-
import { U as UserInputError, b as TransactionCall, A as ApiKeyAuthorization } from './types-
|
|
15
|
-
export { c as AcceptComboQuoteError, d as AcceptComboQuoteParams, e as AcceptComboQuoteResult, f as AccountIdentity, g as AnalyticsActions, h as ApproveErc1155ForAllError, i as ApproveErc20Error, j as ApprovePerpsBuilderFeeError, k as ApprovePerpsBuilderFeeRequest, l as ArmPerpsAutoCancelError, m as ArmPerpsAutoCancelRequest, n as AuthorizeSessionKeyError, o as AuthorizeSessionKeyRequest, p as AuthorizeSessionKeyResult, q as AutoCancelDailyLimitError, B as BaseClient, r as BasePublicClient, s as BaseSecureClient, t as BeginAuthenticationRequest, C as CancelAllError, u as CancelAllPerpsOrdersRequest, v as CancelMarketOrdersError, w as CancelOrderError, x as CancelOrdersError, y as CancelPerpsOrderRequest, z as CancelPerpsOrdersRequest, D as CancelledSigningError, E as Client, F as ClientActions, G as ClientDecorator, H as ClobEndpoints, I as ComboPositionStatusFilter, J as ComboQuote, K as CombosEndpoints, L as CommentsSubscription, M as ConnectionLostError, N as ConnectionLostErrorOptions, O as CreatePerpsSessionRequest, P as CreateSecureClientError, Q as CryptoPriceSubscription, R as CryptoPricesChainlinkTwapSubscription, V as CryptoPricesSubscription, W as CryptoTwapPriceSubscription, X as DataActions, Y as DepositToPerpsError, Z as DepositToPerpsRequest, _ as DisarmPerpsAutoCancelRequest, $ as DiscoveryActions, a0 as DownloadAccountingSnapshotError, a1 as DropNotificationsError, a2 as EnvironmentConfig, a3 as EnvironmentConfigFork, a4 as EnvironmentContracts, a5 as EquityPriceSubscription, a6 as EquityPricesSubscription, a7 as Erc1155TradingApproval, a8 as Erc20TradingApproval, a9 as EstimateMarketPriceError, aa as ExecuteCollateralReturnPlanError, ab as ExecuteCollateralReturnPlanRequest, ac as FetchBuilderVolumeError, ad as FetchClosedOnlyModeError, ae as FetchCommentsByIdError, af as FetchEventError, ag as FetchEventLiveVolumeError, ah as FetchEventTagsError, ai as FetchLastTradePriceError, aj as FetchLastTradePricesError, ak as FetchMarketError, al as FetchMarketTagsError, am as FetchMidpointError, an as FetchMidpointsError, ao as FetchNotificationsError, ap as FetchOpenInterestError, aq as FetchOrderBookError, ar as FetchOrderBooksError, as as FetchOrderError, at as FetchOrderScoringError, au as FetchOrdersScoringError, av as FetchPerpsAccountConfigRequest, aw as FetchPerpsBookError, ax as FetchPerpsBookRequest, ay as FetchPerpsBuilderApprovalsError, az as FetchPerpsBuilderApprovalsRequest, aA as FetchPerpsBuilderEarningsSummaryError, aB as FetchPerpsBuilderEarningsSummaryRequest, aC as FetchPerpsBuilderStatusError, aD as FetchPerpsBuilderStatusRequest, aE as FetchPerpsFeesError, aF as FetchPerpsInstrumentsError, aG as FetchPerpsInstrumentsRequest, aH as FetchPerpsOpenOrdersRequest, aI as FetchPerpsOrdersRequest, aJ as FetchPerpsTickerError, aK as FetchPerpsTickerRequest, aL as FetchPerpsTickersError, aM as FetchPerpsTickersRequest, aN as FetchPortfolioValueError, aO as FetchPriceError, aP as FetchPricesError, aQ as FetchPublicProfileError, aR as FetchRelatedTagResourcesError, aS as FetchRelatedTagsError, aT as FetchResolutionsError, aU as FetchRewardPercentagesError, aV as FetchRfqStatusError, aW as FetchRfqStatusParams, aX as FetchSeriesError, aY as FetchSessionKeysError, aZ as FetchSpreadError, a_ as FetchSpreadsError, a$ as FetchTagError, b0 as FetchTotalEarningsForUserForDayError, b1 as FetchTraderLeaderboardStandingError, b2 as FetchTradingApprovalsStateError, b3 as FetchTradingApprovalsStateRequest, b4 as FetchUserPnlError, b5 as FetchUserStatsError, b6 as FetchUserVolumeError, b7 as InsufficientLiquidityError, b8 as ListAccountTradesError, b9 as ListActivityError, ba as ListBiggestWinnersError, bb as ListBuilderLeaderboardError, bc as ListBuilderTradesError, bd as ListComboActivityError, be as ListComboMarketsError, bf as ListComboPositionsError, bg as ListCommentsByUserAddressError, bh as ListCommentsError, bi as ListCurrentRewardsError, bj as ListEventsError, bk as ListMarketHoldersError, bl as ListMarketRewardsError, bm as ListMarketsError, bn as ListOpenOrdersError, bo as ListPerpsBuilderEarningsError, bp as ListPerpsBuilderEarningsRequest, bq as ListPerpsCandlesError, br as ListPerpsCandlesRequest, bs as ListPerpsDepositsRequest, bt as ListPerpsEquityHistoryRequest, bu as ListPerpsFillsRequest, bv as ListPerpsFundingHistoryError, bw as ListPerpsFundingHistoryRequest, bx as ListPerpsFundingPaymentsRequest, by as ListPerpsInternalTransfersRequest, bz as ListPerpsNotificationsRequest, bA as ListPerpsPnlHistoryRequest, bB as ListPerpsTradesError, bC as ListPerpsTradesRequest, bD as ListPerpsWithdrawalsRequest, bE as ListPositionsError, bF as ListPriceHistoryError, bG as ListSeriesError, bH as ListTagsError, bI as ListTeamsError, bJ as ListTraderLeaderboardError, bK as ListTradesError, bL as ListUserEarningsAndMarketsConfigError, bM as ListUserEarningsForDayError, bN as MarkPerpsNotificationsReadRequest, bO as MergePositionsError, bP as OpenPerpsSessionError, bQ as OpenPerpsSessionRequest, bR as OpenRfqSessionError, bS as OperationAbortedError, bT as OrderSignature, bU as Page, bV as PageSizeSchema, bW as Paginated, bX as PaginationLimitError, bY as PerpsActions, bZ as PerpsBookDepth, b_ as PerpsBuilderTermsInput, b$ as PerpsCancelOptions, c0 as PerpsCancelRetryError, c1 as PerpsCancelRetryErrorOptions, c2 as PerpsCancelRetryOptions, c3 as PerpsEndpoints, c4 as PerpsOrderRequest, c5 as PerpsPlaceFokOrderRequest, c6 as PerpsPlaceGtcOrderRequest, c7 as PerpsPlaceIocOrderRequest, c8 as PerpsPlacedTpSlOrder, c9 as PerpsPlacedTpSlOrders, ca as PerpsPositionTpSlTrigger, cb as PerpsSession, cc as PerpsSessionAccountError, cd as PerpsSessionLifecycleError, ce as PerpsSessionTradingError, cf as PerpsTpSlTrigger, cg as PlacePerpsOrderRequest, ch as PlacePerpsOrderResult, ci as PlacePerpsOrderWithTpSlRequest, cj as PlacePerpsOrderWithTpSlResult, ck as PlacePerpsPositionTpSlRequest, cl as PlacePerpsPositionTpSlResult, cm as PlanCollateralReturnError, cn as PostOrderError, co as PostOrdersError, cp as PostPerpsOrdersRequest, cq as PriceSubscription, cr as PublicAccountActions, cs as PublicActions, ct as PublicClient, cu as PublicClientOptions, cv as PublicPerpsActions, cw as PublicRewardsActions, cx as PublicSubscriptionsActions, cy as PublicWalletActions, cz as RateLimitBucket, cA as RateLimitError, cB as RateLimitErrorOptions, cC as RateLimitUpdate, cD as RateLimitUpdateListener, cE as RedeemPositionsError, cF as RequestComboQuoteError, cG as RequestComboQuoteParams, cH as RequestComboQuoteResult, cI as RequestRejectedError, cJ as RequestRejectedErrorOptions, cK as RestEndpoint, cL as ResumePerpsSessionRequest, cM as RevokePerpsBuilderFeeError, cN as RevokePerpsCredentialsError, cO as RevokePerpsCredentialsRequest, cP as RevokeSessionKeyError, cQ as RevokeSessionKeyRequest, cR as RfqCancelQuoteAck, cS as RfqCancelQuoteError, cT as RfqCancelQuoteRejectedError, cU as RfqCancelQuoteRejectedErrorOptions, cV as RfqConfirmationAck, cW as RfqConfirmationError, cX as RfqConfirmationRejectedError, cY as RfqConfirmationRequestEvent, cZ as RfqEvent, c_ as RfqQuoteError, c$ as RfqQuoteReference, d0 as RfqQuoteRejectedError, d1 as RfqQuoteRejectedErrorOptions, d2 as RfqQuoteRequestEvent, d3 as RfqQuoteResponse, d4 as RfqQuoteSource, d5 as RfqRequestRejectedError, d6 as RfqRequestRejectedErrorOptions, d7 as RfqSession, d8 as RfqStatusResult, d9 as RfqTradeEvent, da as SearchError, db as SearchSort, dc as SecureAccountActions, dd as SecureActions, de as SecureClient, df as SecureClientOptions, dg as SecureDownloadAccountingSnapshotRequest, dh as SecureFetchPortfolioValueRequest, di as SecureFetchTraderLeaderboardStandingRequest, dj as SecureFetchUserPnlRequest, dk as SecureFetchUserStatsRequest, dl as SecureFetchUserVolumeRequest, dm as SecureListActivityRequest, dn as SecureListComboActivityRequest, dp as SecureListComboPositionsRequest, dq as SecureListPositionsRequest, dr as SecurePerpsActions, ds as SecureRewardsActions, dt as SecureRfqActions, du as SecureSubscriptionsActions, dv as SecureTradingActions, dw as SecureWalletActions, dx as SessionKey, dy as SessionKeyActions, dz as SetupGaslessWalletError, dA as SetupTradingApprovalsError, dB as SignedOrder, S as Signer, dC as SignerTransactionRequest, dD as SignerType, dE as SigningError, dF as SplitPositionError, dG as SubscribeError, dH as SubscriptionHandle, dI as TimeoutError, dJ as TradingApprovalRequirements, dK as TradingApprovalsState, dL as TradingRestriction, dM as TransactionFailedError, dN as TransactionHandle, dO as TransactionOutcome, dP as TransferErc20Error, dQ as TransferPerpsCollateralError, dR as TransferPerpsCollateralRequest, dS as TransportError, a as TypedData, dT as TypedDataDomain, dU as TypedDataField, T as TypedDataPayload, dV as UnexpectedResponseError, dW as UpdatePerpsLeverageError, dX as UpdatePerpsLeverageRequest, dY as UpdatePerpsMarginError, dZ as UpdatePerpsMarginRequest, d_ as WaitForComboFillError, d$ as WaitForComboFillParams, e0 as WaitForComboFillResult, e1 as WaitForOrderFillSettlementError, e2 as WaitForTransactionError, e3 as WalletDerivationConfig, e4 as WebSocketCloseCode, e5 as WebSocketEndpoint, e6 as WebSocketKnownCloseCode, e7 as WithdrawFromPerpsError, e8 as WithdrawFromPerpsRequest, e9 as accountActions, ea as allActions, eb as analyticsActions, ec as createPublicClient, ed as createSecureClient, ee as dataActions, ef as discoveryActions, eg as forkEnvironmentConfig, eh as makeErrorGuard, ei as perpsActions, ej as production, ek as rewardsActions, el as rfqActions, em as sessionKeyActions, en as subscriptionsActions, eo as tradingActions, ep as walletActions } from './types-B9F4CyS-.js';
|
|
16
|
-
export { C as CreateLimitOrderError, a as CreateMarketOrderError, F as FetchSportsMarketTypesError, L as ListSportsError, P as PlaceLimitOrderError, b as PlaceMarketOrderError } from './sports-
|
|
14
|
+
import { U as UserInputError, b as TransactionCall, A as ApiKeyAuthorization } from './types-BGxCI8uu.js';
|
|
15
|
+
export { c as AcceptComboQuoteError, d as AcceptComboQuoteParams, e as AcceptComboQuoteResult, f as AccountIdentity, g as AnalyticsActions, h as ApproveErc1155ForAllError, i as ApproveErc20Error, j as ApprovePerpsBuilderFeeError, k as ApprovePerpsBuilderFeeRequest, l as ArmPerpsAutoCancelError, m as ArmPerpsAutoCancelRequest, n as AuthorizeSessionKeyError, o as AuthorizeSessionKeyRequest, p as AuthorizeSessionKeyResult, q as AutoCancelDailyLimitError, B as BaseClient, r as BasePublicClient, s as BaseSecureClient, t as BeginAuthenticationRequest, C as CancelAllError, u as CancelAllPerpsOrdersRequest, v as CancelMarketOrdersError, w as CancelOrderError, x as CancelOrdersError, y as CancelPerpsChaseError, z as CancelPerpsChaseRequest, D as CancelPerpsOrderRequest, E as CancelPerpsOrdersRequest, F as CancelPerpsTwapError, G as CancelPerpsTwapRequest, H as CancelledSigningError, I as Client, J as ClientActions, K as ClientDecorator, L as ClobEndpoints, M as ComboPositionStatusFilter, N as ComboQuote, O as CombosEndpoints, P as CommentsSubscription, Q as ConnectionLostError, R as ConnectionLostErrorOptions, V as CreatePerpsChaseError, W as CreatePerpsChaseRequest, X as CreatePerpsSessionRequest, Y as CreatePerpsTwapError, Z as CreatePerpsTwapRequest, _ as CreateSecureClientError, $ as CryptoPriceSubscription, a0 as CryptoPricesChainlinkTwapSubscription, a1 as CryptoPricesSubscription, a2 as CryptoTwapPriceSubscription, a3 as DataActions, a4 as DepositToPerpsError, a5 as DepositToPerpsRequest, a6 as DisarmPerpsAutoCancelRequest, a7 as DiscoveryActions, a8 as DownloadAccountingSnapshotError, a9 as DropNotificationsError, aa as EnvironmentConfig, ab as EnvironmentConfigFork, ac as EnvironmentContracts, ad as EquityPriceSubscription, ae as EquityPricesSubscription, af as EquityTwapPriceSubscription, ag as Erc1155TradingApproval, ah as Erc20TradingApproval, ai as EstimateMarketPriceError, aj as ExecuteCollateralReturnPlanError, ak as ExecuteCollateralReturnPlanRequest, al as FetchBuilderVolumeError, am as FetchClosedOnlyModeError, an as FetchCommentsByIdError, ao as FetchEventError, ap as FetchEventLiveVolumeError, aq as FetchEventTagsError, ar as FetchLastTradePriceError, as as FetchLastTradePricesError, at as FetchMarketError, au as FetchMarketTagsError, av as FetchMidpointError, aw as FetchMidpointsError, ax as FetchNotificationsError, ay as FetchOpenInterestError, az as FetchOrderBookError, aA as FetchOrderBooksError, aB as FetchOrderError, aC as FetchOrderScoringError, aD as FetchOrdersScoringError, aE as FetchPerpsAccountConfigRequest, aF as FetchPerpsBookError, aG as FetchPerpsBookRequest, aH as FetchPerpsBuilderApprovalsError, aI as FetchPerpsBuilderApprovalsRequest, aJ as FetchPerpsBuilderEarningsSummaryError, aK as FetchPerpsBuilderEarningsSummaryRequest, aL as FetchPerpsBuilderStatusError, aM as FetchPerpsBuilderStatusRequest, aN as FetchPerpsChasesError, aO as FetchPerpsFeesError, aP as FetchPerpsInstrumentsError, aQ as FetchPerpsInstrumentsRequest, aR as FetchPerpsOpenOrdersRequest, aS as FetchPerpsOrdersRequest, aT as FetchPerpsPositionSnapshotsError, aU as FetchPerpsPositionSnapshotsRequest, aV as FetchPerpsRegistrationError, aW as FetchPerpsRegistrationRequest, aX as FetchPerpsTickerError, aY as FetchPerpsTickerRequest, aZ as FetchPerpsTickersError, a_ as FetchPerpsTickersRequest, a$ as FetchPerpsTwapsError, b0 as FetchPortfolioValueError, b1 as FetchPriceError, b2 as FetchPricesError, b3 as FetchPublicProfileError, b4 as FetchRelatedTagResourcesError, b5 as FetchRelatedTagsError, b6 as FetchResolutionsError, b7 as FetchRewardPercentagesError, b8 as FetchRfqStatusError, b9 as FetchRfqStatusParams, ba as FetchSeriesError, bb as FetchSessionKeysError, bc as FetchSpreadError, bd as FetchSpreadsError, be as FetchTagError, bf as FetchTotalEarningsForUserForDayError, bg as FetchTraderLeaderboardStandingError, bh as FetchTradingApprovalsStateError, bi as FetchTradingApprovalsStateRequest, bj as FetchUserPnlError, bk as FetchUserStatsError, bl as FetchUserVolumeError, bm as InsufficientLiquidityError, bn as ListAccountTradesError, bo as ListActivityError, bp as ListBiggestWinnersError, bq as ListBuilderLeaderboardError, br as ListBuilderTradesError, bs as ListComboActivityError, bt as ListComboMarketsError, bu as ListComboPositionsError, bv as ListCommentsByUserAddressError, bw as ListCommentsError, bx as ListCurrentRewardsError, by as ListEventsError, bz as ListMarketHoldersError, bA as ListMarketRewardsError, bB as ListMarketsError, bC as ListOpenOrdersError, bD as ListPerpsBuilderEarningsError, bE as ListPerpsBuilderEarningsRequest, bF as ListPerpsCandlesError, bG as ListPerpsCandlesRequest, bH as ListPerpsDepositsRequest, bI as ListPerpsEquityHistoryRequest, bJ as ListPerpsFillsRequest, bK as ListPerpsFundingHistoryError, bL as ListPerpsFundingHistoryRequest, bM as ListPerpsFundingPaymentsRequest, bN as ListPerpsInternalTransfersRequest, bO as ListPerpsNotificationsRequest, bP as ListPerpsPnlHistoryRequest, bQ as ListPerpsTradesError, bR as ListPerpsTradesRequest, bS as ListPerpsWithdrawalsRequest, bT as ListPositionsError, bU as ListPriceHistoryError, bV as ListSeriesError, bW as ListTagsError, bX as ListTeamsError, bY as ListTraderLeaderboardError, bZ as ListTradesError, b_ as ListUserEarningsAndMarketsConfigError, b$ as ListUserEarningsForDayError, c0 as MarkPerpsNotificationsReadRequest, c1 as MergePositionsError, c2 as OpenPerpsSessionError, c3 as OpenPerpsSessionRequest, c4 as OpenRfqSessionError, c5 as OperationAbortedError, c6 as OrderSignature, c7 as Page, c8 as PageSizeSchema, c9 as Paginated, ca as PaginationLimitError, cb as PausePerpsTwapError, cc as PausePerpsTwapRequest, cd as PerpsActions, ce as PerpsBookDepth, cf as PerpsBuilderTermsInput, cg as PerpsCancelOptions, ch as PerpsCancelRetryError, ci as PerpsCancelRetryErrorOptions, cj as PerpsCancelRetryOptions, ck as PerpsEndpoints, cl as PerpsOrderRequest, cm as PerpsPlaceFokOrderRequest, cn as PerpsPlaceGtcOrderRequest, co as PerpsPlaceGtdOrderRequest, cp as PerpsPlaceIocOrderRequest, cq as PerpsPlacedTpSlOrder, cr as PerpsPlacedTpSlOrders, cs as PerpsPositionSnapshotFill, ct as PerpsPositionSnapshotSelection, cu as PerpsPositionTpSlTrigger, cv as PerpsPositionTrailingStop, cw as PerpsSession, cx as PerpsSessionAccountError, cy as PerpsSessionLifecycleError, cz as PerpsSessionTradingError, cA as PerpsTpSlTrigger, cB as PerpsTrailingStop, cC as PlacePerpsOrderRequest, cD as PlacePerpsOrderResult, cE as PlacePerpsOrderWithTpSlRequest, cF as PlacePerpsOrderWithTpSlResult, cG as PlacePerpsPositionTpSlRequest, cH as PlacePerpsPositionTpSlResult, cI as PlanCollateralReturnError, cJ as PostOrderError, cK as PostOrdersError, cL as PostPerpsOrdersRequest, cM as PriceSubscription, cN as PriceSubscriptionConfirmation, cO as PublicAccountActions, cP as PublicActions, cQ as PublicClient, cR as PublicClientOptions, cS as PublicPerpsActions, cT as PublicRewardsActions, cU as PublicSubscriptionsActions, cV as PublicWalletActions, cW as RateLimitBucket, cX as RateLimitError, cY as RateLimitErrorOptions, cZ as RateLimitUpdate, c_ as RateLimitUpdateListener, c$ as RedeemPositionsError, d0 as RequestComboQuoteError, d1 as RequestComboQuoteParams, d2 as RequestComboQuoteResult, d3 as RequestRejectedError, d4 as RequestRejectedErrorOptions, d5 as RestEndpoint, d6 as ResumePerpsSessionRequest, d7 as ResumePerpsTwapError, d8 as ResumePerpsTwapRequest, d9 as RevokePerpsBuilderFeeError, da as RevokePerpsCredentialsError, db as RevokePerpsCredentialsRequest, dc as RevokeSessionKeyError, dd as RevokeSessionKeyRequest, de as RfqCancelQuoteAck, df as RfqCancelQuoteError, dg as RfqCancelQuoteRejectedError, dh as RfqCancelQuoteRejectedErrorOptions, di as RfqConfirmationAck, dj as RfqConfirmationError, dk as RfqConfirmationRejectedError, dl as RfqConfirmationRequestEvent, dm as RfqEvent, dn as RfqQuoteError, dp as RfqQuoteReference, dq as RfqQuoteRejectedError, dr as RfqQuoteRejectedErrorOptions, ds as RfqQuoteRequestEvent, dt as RfqQuoteResponse, du as RfqQuoteSource, dv as RfqRequestRejectedError, dw as RfqRequestRejectedErrorOptions, dx as RfqSession, dy as RfqStatusResult, dz as RfqTradeEvent, dA as SearchError, dB as SearchSort, dC as SecureAccountActions, dD as SecureActions, dE as SecureClient, dF as SecureClientOptions, dG as SecureDownloadAccountingSnapshotRequest, dH as SecureFetchPortfolioValueRequest, dI as SecureFetchTraderLeaderboardStandingRequest, dJ as SecureFetchUserPnlRequest, dK as SecureFetchUserStatsRequest, dL as SecureFetchUserVolumeRequest, dM as SecureListActivityRequest, dN as SecureListComboActivityRequest, dO as SecureListComboPositionsRequest, dP as SecureListPositionsRequest, dQ as SecurePerpsActions, dR as SecureRewardsActions, dS as SecureRfqActions, dT as SecureSubscriptionsActions, dU as SecureTradingActions, dV as SecureWalletActions, dW as SessionKey, dX as SessionKeyActions, dY as SetupGaslessWalletError, dZ as SetupTradingApprovalsError, d_ as SignedOrder, S as Signer, d$ as SignerTransactionRequest, e0 as SignerType, e1 as SigningError, e2 as SplitPositionError, e3 as SubscribeError, e4 as SubscriptionHandle, e5 as TimeoutError, e6 as TradingApprovalRequirements, e7 as TradingApprovalsState, e8 as TradingRestriction, e9 as TransactionFailedError, ea as TransactionHandle, eb as TransactionOutcome, ec as TransferErc20Error, ed as TransferPerpsCollateralError, ee as TransferPerpsCollateralRequest, ef as TransportError, a as TypedData, eg as TypedDataDomain, eh as TypedDataField, T as TypedDataPayload, ei as UnexpectedResponseError, ej as UpdatePerpsLeverageError, ek as UpdatePerpsLeverageRequest, el as UpdatePerpsLeveragesError, em as UpdatePerpsLeveragesRequest, en as UpdatePerpsMarginError, eo as UpdatePerpsMarginRequest, ep as WaitForComboFillError, eq as WaitForComboFillParams, er as WaitForComboFillResult, es as WaitForOrderFillSettlementError, et as WaitForTransactionError, eu as WalletDerivationConfig, ev as WebSocketCloseCode, ew as WebSocketEndpoint, ex as WebSocketKnownCloseCode, ey as WithdrawFromPerpsError, ez as WithdrawFromPerpsRequest, eA as accountActions, eB as allActions, eC as analyticsActions, eD as createPublicClient, eE as createSecureClient, eF as dataActions, eG as discoveryActions, eH as forkEnvironmentConfig, eI as makeErrorGuard, eJ as perpsActions, eK as production, eL as rewardsActions, eM as rfqActions, eN as sessionKeyActions, eO as subscriptionsActions, eP as tradingActions, eQ as walletActions } from './types-BGxCI8uu.js';
|
|
16
|
+
export { C as CreateLimitOrderError, a as CreateMarketOrderError, F as FetchSportsMarketTypesError, L as ListSportsError, P as PlaceLimitOrderError, b as PlaceMarketOrderError } from './sports-DxgyI41A.js';
|
|
17
17
|
export { BuilderRfqError, CollateralReturnKnownOperationKind, CollateralReturnOperation, CollateralReturnOperationKind, CollateralReturnPlanResponse, CollateralReturnPositionAmount, CollateralReturnPositionSummary, CollateralReturnRouterCall, ComboAcceptFailureReason, ComboQuoteUnavailableReason, RfqConfirmationDecision, RfqConfirmationRequest, RfqDirection, RfqErrorCode, RfqExecutionStatus, RfqExecutionUpdate, RfqId, RfqKnownErrorCode, RfqQuoteId, RfqQuoteRequest, RfqRejectionCode, RfqRequestedSize, RfqRequestedSizeUnit, RfqRequestorPublicId, RfqSide, RfqStatus, RfqTrade } from '@polymarket/bindings/combos';
|
|
18
|
-
export { CommentsEvent, CryptoPriceEvent, CryptoPriceSnapshotEvent, CryptoPricesBinanceEvent, CryptoPricesChainlinkEvent, CryptoPricesChainlinkTwapEvent, CryptoPricesChainlinkTwapSixtyEvent, CryptoPricesChainlinkTwapThirtyEvent, CryptoPricesChainlinkTwapWindowSeconds, CryptoPricesEvent, CryptoTwapPriceEvent, CryptoTwapPriceSnapshotEvent, EquityPriceEvent, EquityPricesEvent, PerpsBuilderFillUpdateEvent, PerpsSessionEvent, RealtimeErrorCode, RealtimeKnownErrorCode } from '@polymarket/bindings/subscriptions';
|
|
18
|
+
export { CommentsEvent, CryptoPriceEvent, CryptoPriceSnapshotEvent, CryptoPricesBinanceEvent, CryptoPricesChainlinkEvent, CryptoPricesChainlinkTwapEvent, CryptoPricesChainlinkTwapSixtyEvent, CryptoPricesChainlinkTwapThirtyEvent, CryptoPricesChainlinkTwapWindowSeconds, CryptoPricesEvent, CryptoTwapPriceEvent, CryptoTwapPriceSnapshotEvent, EquityPriceEvent, EquityPricesEvent, EquityTwapPriceEvent, EquityTwapPriceSnapshotEvent, KnownPriceSource, PerpsBuilderFillUpdateEvent, PerpsSessionEvent, PriceProvider, PriceSource, RealtimeErrorCode, RealtimeKnownErrorCode } from '@polymarket/bindings/subscriptions';
|
|
19
19
|
import 'zod';
|
|
20
20
|
import 'ox';
|
|
21
21
|
|
package/dist/index.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import {Q,_,Y as Y$1,W,ua,sa as sa$1,cf,af,_e,Ye,Nc,We,Ue,Se as Se$1,Pc,Lc,Jc,Hc,yb,qa as qa$1,ed,id,sd,gd,ac,_b,Yb,Wb,Ub,Sb,Qb,Ob,Cb,Ab,zc,Bc,rc,pc,nc,Sf,Vg,Jg,Hg,ug,Tg,Rg,Pg,Ng,Vc,yg,wg,cd,ad,_c,Yc,xc,vc,tc,Zd,Pe as Pe$1,Qe as Qe$1,Me,Le as Le$1,Oe,oa,ma,ka as ka$1,ia as ia$1,ga as ga$1,ea,fg,dg,bg,_f,Fg,Bg,Dg,Lg,U as U$1,S,qd,od,md,kd,Pd,yd,xd,Xd,Vd,Td,Rd,kc,gc,Qf,Hf,vf,Zg,ab,Ya as Ya$1,gb,db,Ba as Ba$1,Ga as Ga$1,N as N$1,O,Ja as Ja$1,Ce as Ce$1,Ae as Ae$1,ye,ue,se,qe as qe$1,Ee as Ee$1,we as we$1,ec,cc,J as J$1,$d,I,Ca,L as L$1,ob,mb,ge as ge$1,de,fe,be,ce,ae,qb,oe,Tf,Vf,Xf,ee,M as M$1,Bd,Dd,Ed,Cd,zd,Ad}from'./chunk-5JHFOBBZ.js';export{cg as AcceptComboQuoteError,$a as ApproveErc1155ForAllError,Xa as ApproveErc20Error,_d as ApprovePerpsBuilderFeeError,ke as ArmPerpsAutoCancelError,Cg as AuthorizeSessionKeyError,Qc as BiggestWinnerKind,Rc as BuilderVolumeInterval,nd as CancelAllError,pd as CancelMarketOrdersError,jd as CancelOrderError,ld as CancelOrdersError,lc as CollateralReturnKnownOperationKind,E as CombinatorialPrepareConditionCallError,ig as ComboAcceptFailureReason,va as ComboActivityType,df as ComboPositionSortBy,ef as ComboPositionStatus,jg as ComboQuoteUnavailableReason,Ud as CreateLimitOrderError,Qd as CreateMarketOrderError,u as CtfMergePositionsCallError,w as CtfRedeemPositionsCallError,s as CtfSplitPositionCallError,Ie as DepositToPerpsError,bf as DownloadAccountingSnapshotError,Z as DropNotificationsError,b as Erc20ApprovalCallError,m as Erc20TransferCallError,rd as EstimateMarketPriceError,jc as ExecuteCollateralReturnPlanError,Ic as FetchBuilderVolumeError,P as FetchClosedOnlyModeError,oc as FetchCommentsByIdError,uc as FetchEventError,Ac as FetchEventLiveVolumeError,wc as FetchEventTagsError,Zb as FetchLastTradePriceError,$b as FetchLastTradePricesError,$c as FetchMarketError,bd as FetchMarketTagsError,zb as FetchMidpointError,Bb as FetchMidpointsError,X as FetchNotificationsError,hd as FetchOpenInterestError,Rb as FetchOrderBookError,Tb as FetchOrderBooksError,T as FetchOrderError,da as FetchOrderScoringError,fa as FetchOrdersScoringError,ve as FetchPerpsBookError,he as FetchPerpsBuilderApprovalsError,je as FetchPerpsBuilderEarningsSummaryError,Yd as FetchPerpsBuilderStatusError,De as FetchPerpsFeesError,pe as FetchPerpsInstrumentsError,re as FetchPerpsTickerError,te as FetchPerpsTickersError,Ve as FetchPortfolioValueError,Nb as FetchPriceError,Pb as FetchPricesError,Rf as FetchPublicProfileError,Sg as FetchRelatedTagResourcesError,Qg as FetchRelatedTagsError,yc as FetchResolutionsError,na as FetchRewardPercentagesError,gg as FetchRfqStatusError,xg as FetchSeriesError,Ag as FetchSessionKeysError,Ig as FetchSportsMarketTypesError,Vb as FetchSpreadError,Xb as FetchSpreadsError,Og as FetchTagError,ja as FetchTotalEarningsForUserForDayError,Mc as FetchTraderLeaderboardStandingError,cb as FetchTradingApprovalsStateError,Ze as FetchUserPnlError,Xe as FetchUserStatsError,$e as FetchUserVolumeError,Sc as LeaderboardWindow,V as ListAccountTradesError,ra as ListActivityError,Oc as ListBiggestWinnersError,Gc as ListBuilderLeaderboardError,xb as ListBuilderTradesError,ta as ListComboActivityError,Zc as ListComboMarketsError,Te as ListComboPositionsError,qc as ListCommentsByUserAddressError,mc as ListCommentsError,bc as ListCurrentRewardsError,sc as ListEventsError,dd as ListMarketHoldersError,dc as ListMarketRewardsError,Xc as ListMarketsError,R as ListOpenOrdersError,ie as ListPerpsBuilderEarningsError,xe as ListPerpsCandlesError,ze as ListPerpsFundingHistoryError,Be as ListPerpsTradesError,Re as ListPositionsError,fd as ListPriceHistoryError,vg as ListSeriesError,Gg as ListSportsError,Mg as ListTagsError,Ug as ListTeamsError,Kc as ListTraderLeaderboardError,pa as ListTradesError,la as ListUserEarningsAndMarketsConfigError,ha as ListUserEarningsForDayError,a as MAX_UINT256,Cf as MergePositionsError,Fe as OpenPerpsSessionError,Zf as OpenRfqSessionError,q as PerpsDepositCallError,Wd as PlaceLimitOrderError,Sd as PlaceMarketOrderError,fc as PlanCollateralReturnError,ff as PositionFilterType,gf as PositionSortBy,hf as PositionStatus,vd as PostOrderError,wd as PostOrdersError,Wc as PriceHistoryInterval,Pf as RedeemPositionsError,ag as RequestComboQuoteError,Cc as ResolutionMarketType,Dc as ResolutionReporter,Ec as ResolutionSource,Fc as ResolutionStatus,ne as RevokePerpsBuilderFeeError,Ge as RevokePerpsCredentialsError,Eg as RevokeSessionKeyError,Wf as RfqCancelQuoteError,Vf as RfqCancelQuoteRejectedError,kg as RfqConfirmationDecision,Yf as RfqConfirmationError,Xf as RfqConfirmationRejectedError,lg as RfqDirection,mg as RfqExecutionStatus,ng as RfqKnownErrorCode,Uf as RfqQuoteError,Tf as RfqQuoteRejectedError,og as RfqRejectionCode,$f as RfqRequestRejectedError,pg as RfqRequestedSizeUnit,qg as RfqSide,rg as RfqStatus,A as RouterMergeCallError,C as RouterRedeemCallError,y as RouterSplitCallError,tg as SearchError,sg as SearchSort,zg as SessionKeyKnownScope,fb as SetupTradingApprovalsError,K as SignerType,wa as SortDirection,qf as SplitPositionError,Kg as SubscribeError,xa as TipSide,ya as TradeFilterType,Tc as TraderLeaderboardSort,Yg as TransferErc20Error,Ke as TransferPerpsCollateralError,le as UpdatePerpsLeverageError,me as UpdatePerpsMarginError,if as UserPnlFidelity,jf as UserPnlInterval,eg as WaitForComboFillError,Od as WaitForOrderFillSettlementError,za as WaitForTransactionError,Je as WithdrawFromPerpsError,o as authorizeSessionSignerCall,F as combinatorialPrepareConditionCall,v as ctfMergePositionsCall,x as ctfRedeemPositionsCall,t as ctfSplitPositionCall,l as decodeErc1155BalanceOfBatchResult,j as decodeErc1155BalanceOfResult,h as decodeErc1155IsApprovedForAllResult,e as decodeErc20AllowanceResult,G as encodeProxyCall,H as encodeSafeMultisendCall,f as erc1155ApprovalForAllCall,k as erc1155BalanceOfBatchCall,i as erc1155BalanceOfCall,g as erc1155IsApprovedForAllCall,d as erc20AllowanceCall,c as erc20ApprovalCall,n as erc20TransferCall,Aa as expectTransactionHandle,r as perpsDepositCall,p as revokeSessionSignerCall,B as routerMergeCall,D as routerRedeemCall,z as routerSplitCall}from'./chunk-5JHFOBBZ.js';import {a,r,m,i,h,q,j as j$1,l,d,c,f}from'./chunk-VLNLVY4C.js';export{o as AutoCancelDailyLimitError,m as CancelledSigningError,f as ConnectionLostError,n as InsufficientLiquidityError,k as OperationAbortedError,b as PaginationLimitError,p as PerpsCancelRetryError,i as RateLimitError,s as RealtimeKnownErrorCode,h as RequestRejectedError,q as SigningError,j as TimeoutError,g as TradingRestriction,l as TransactionFailedError,d as TransportError,c as UnexpectedResponseError,a as UserInputError,e as WebSocketKnownCloseCode,r as makeErrorGuard}from'./chunk-VLNLVY4C.js';import {DecimalishSchema,ApiKeySchema,EvmAddressSchema,toBaseUnits,OrderSide}from'@polymarket/bindings';export{CommentParentEntityType,OrderSide,OrderType}from'@polymarket/bindings';export{AssetType,NotificationType,OrderPostStatus,OrderResponseErrorCode,SignatureType}from'@polymarket/bindings/clob';export{ActivityType}from'@polymarket/bindings/data';import {WalletType}from'@polymarket/bindings/gamma';export{ComboKnownStatus,ProtocolVersion,TeamOrdering,WalletType}from'@polymarket/bindings/gamma';export{PerpsDepositStatus,PerpsInstrumentCategory,PerpsInstrumentType,PerpsInternalTransferDirection,PerpsKlineInterval,PerpsKnownCancelOrderErrorCode,PerpsKnownInternalTransferType,PerpsKnownWithdrawalStatus,PerpsLiquidityRole,PerpsMarginType,PerpsNotificationOrderType,PerpsNotificationType,PerpsOrderStatus,PerpsSide,PerpsSortDirection,PerpsTimeInForce}from'@polymarket/bindings/perps';import {z}from'zod';import {expectEvmAddress,isSameEvmAddress,expectEvmSignature,invariant,setNonBlockingTimeout}from'@polymarket/types';import {TypedData}from'ox';import {PerpsMarketDataEventSchema,RealtimeEventSchema,SportsResultEventSchema,MarketEventSchema,UserEventSchema,RealtimeKnownErrorCode,PolyboltAckOp,PolyboltAckSchema,PolyboltEnvelopeSchema,parsePolyboltEvent,PolyboltChannel}from'@polymarket/bindings/subscriptions';import {pushable}from'it-pushable';import {RfqQuoterInboundMessageSchema,RfqConfirmationDecision,RfqRequestedSizeUnit,RfqDirection}from'@polymarket/bindings/combos';var Ko=z.object({POLY_BUILDER_API_KEY:z.string().min(1),POLY_BUILDER_TIMESTAMP:z.string().min(1),POLY_BUILDER_PASSPHRASE:z.string().min(1),POLY_BUILDER_SIGNATURE:z.string().min(1)});function Ho(t){return new Se(t)}function _o(t){return new Pe(t)}var Se=class{#e;constructor(e){this.#e=e;}get isBuilderKey(){return true}get supportGasless(){return true}async authorize(e){try{return await this.#t(e)}catch(r){throw q.fromError(r,"Could not authorize the builder-authenticated request")}}async#s(){let e=this.#e.headers,r=typeof e=="function"?await e():e,s=new Headers(r);return s.set("content-type","application/json"),s}async#t(e){let r=await fetch(this.#e.url,{body:JSON.stringify({body:e.body,method:e.method,path:e.path}),credentials:this.#e.credentials,headers:await this.#s(),method:"POST",mode:"cors"});if(!r.ok)throw new Error(`Remote signer rejected request with status ${r.status}`);return Ko.parse(await r.json())}},Pe=class{#e;constructor(e){this.#e=e;}get isBuilderKey(){return false}get supportGasless(){return true}authorize(){return Promise.resolve({RELAYER_API_KEY:this.#e.key,RELAYER_API_KEY_ADDRESS:this.#e.address})}};function ts(t){let e={chainId:t.chainId,name:"ClobAuthDomain",version:"1"};return {domain:e,message:{address:t.address,message:"This message attests that I control the given wallet",nonce:t.nonce??0,timestamp:`${t.timestamp}`},primaryType:"ClobAuth",types:{EIP712Domain:TypedData.extractEip712DomainTypes(e),ClobAuth:[{name:"address",type:"address"},{name:"timestamp",type:"string"},{name:"nonce",type:"uint256"},{name:"message",type:"string"}]}}}function zo(t){return {listPositions:Se$1.bind(null,t),listComboPositions:Ue.bind(null,t),fetchPortfolioValue:We.bind(null,t),fetchTraderLeaderboardStanding:Nc.bind(null,t),fetchUserStats:Ye.bind(null,t),fetchUserPnl:_e.bind(null,t),fetchUserVolume:af.bind(null,t),downloadAccountingSnapshot:cf.bind(null,t),listActivity:sa$1.bind(null,t),listComboActivity:ua.bind(null,t)}}function P(t,e={}){return e===null||typeof e!="object"||Array.isArray(e)?e:{...e,user:e.user===void 0?t.account.wallet:e.user}}function Re(t){let e=zo(t);return t.isPublicClient()?e:{...e,listPositions:r=>Se$1(t,P(t,r)),listComboPositions:r=>Ue(t,P(t,r)),fetchPortfolioValue:r=>We(t,P(t,r)),fetchTraderLeaderboardStanding:r=>Nc(t,P(t,r)),fetchUserStats:r=>Ye(t,P(t,r)),fetchUserPnl:r=>_e(t,P(t,r)),fetchUserVolume:r=>af(t,P(t,r)),downloadAccountingSnapshot:r=>cf(t,P(t,r)),listActivity:r=>sa$1(t,P(t,r)),listComboActivity:r=>ua(t,P(t,r)),listAccountTrades:W.bind(null,t),fetchNotifications:Y$1.bind(null,t),dropNotifications:_.bind(null,t),fetchClosedOnlyMode:Q.bind(null,t)}}function ge(t){return {listBuilderTrades:yb.bind(null,t),listBuilderLeaderboard:Hc.bind(null,t),fetchBuilderVolume:Jc.bind(null,t),listTraderLeaderboard:Lc.bind(null,t),listBiggestWinners:Pc.bind(null,t)}}function ve(t){return {fetchEventLiveVolume:Bc.bind(null,t),fetchResolutions:zc.bind(null,t),fetchMidpoint:Ab.bind(null,t),fetchMidpoints:Cb.bind(null,t),fetchPrice:Ob.bind(null,t),fetchPrices:Qb.bind(null,t),fetchOrderBook:Sb.bind(null,t),fetchOrderBooks:Ub.bind(null,t),fetchSpread:Wb.bind(null,t),fetchSpreads:Yb.bind(null,t),fetchLastTradePrice:_b.bind(null,t),fetchLastTradePrices:ac.bind(null,t),listPriceHistory:gd.bind(null,t),estimateMarketPrice:sd.bind(null,t),fetchOpenInterest:id.bind(null,t),listMarketHolders:ed.bind(null,t),listTrades:qa$1.bind(null,t)}}function qe(t){return {listEvents:tc.bind(null,t),fetchEvent:vc.bind(null,t),fetchEventTags:xc.bind(null,t),listMarkets:Yc.bind(null,t),listComboMarkets:_c.bind(null,t),fetchMarket:ad.bind(null,t),fetchMarketTags:cd.bind(null,t),listSeries:wg.bind(null,t),fetchSeries:yg.bind(null,t),listMarketClarifications:Vc.bind(null,t),listTags:Ng.bind(null,t),fetchTag:Pg.bind(null,t),fetchRelatedTags:Rg.bind(null,t),fetchRelatedTagResources:Tg.bind(null,t),search:ug.bind(null,t),listSports:Hg.bind(null,t),fetchSportsMarketTypes:Jg.bind(null,t),listTeams:Vg.bind(null,t),fetchPublicProfile:Sf.bind(null,t),listComments:nc.bind(null,t),fetchCommentsById:pc.bind(null,t),listCommentsByUserAddress:rc.bind(null,t)}}function Ae(t){let e={fetchPerpsBuilderStatus:Zd.bind(null,t),fetchPerpsBook:r=>we$1(t,r),fetchPerpsFees:()=>Ee$1(t),fetchPerpsInstruments:r=>qe$1(t,r),fetchPerpsTicker:r=>se(t,r),fetchPerpsTickers:r=>ue(t,r),listPerpsCandles:r=>ye(t,r),listPerpsFundingHistory:r=>Ae$1(t,r),listPerpsTrades:r=>Ce$1(t,r)};return t.isSecureClient()?{...e,depositToPerps:r=>Oe(t,r),openPerpsSession:r=>Le$1(t,r),revokePerpsCredentials:r=>Me(t,r),transferPerpsCollateral:Qe$1.bind(null,t),withdrawFromPerps:r=>Pe$1(t,r)}:e}function Vo(t){return {listCurrentRewards:cc.bind(null,t),listMarketRewards:ec.bind(null,t)}}function Ce(t){let e=Vo(t);return t.isPublicClient()?e:{...e,fetchOrderScoring:ea.bind(null,t),fetchOrdersScoring:ga$1.bind(null,t),listUserEarningsForDay:ia$1.bind(null,t),fetchTotalEarningsForUserForDay:ka$1.bind(null,t),listUserEarningsAndMarketsConfig:ma.bind(null,t),fetchRewardPercentages:oa.bind(null,t)}}function rs(t){return {openRfqSession(){return _f(t)},requestComboQuote(e){return bg(t,e)},acceptComboQuote(e){return dg(t,e)},waitForComboFill(e){return fg(t,e)}}}function ss(t){return {authorizeSessionKey:Dg.bind(null,t),fetchSessionKeys:Bg.bind(null,t),revokeSessionKey:Fg.bind(null,t)}}function Ee(t){return t.isSecureClient()?{subscribe(e){return Lg(t,e)}}:{subscribe(e){return Lg(t,e)}}}function is(t){return {createMarketOrder:Rd.bind(null,t),placeMarketOrder:Td.bind(null,t),createLimitOrder:Vd.bind(null,t),placeLimitOrder:Xd.bind(null,t),postOrder:xd(t),postOrders:yd(t),waitForOrderFillSettlement:Pd.bind(null,t),cancelOrder:kd.bind(null,t),cancelOrders:md.bind(null,t),cancelAll:od.bind(null,t),cancelMarketOrders:qd.bind(null,t),listOpenOrders:S.bind(null,t),fetchOrder:U$1.bind(null,t)}}function No(t){return {fetchTradingApprovalsState:db.bind(null,t)}}function ke(t){let e=No(t);return t.isPublicClient()?e:{...e,fetchTradingApprovalsState:()=>db(t,{user:t.account.wallet}),setupTradingApprovals:gb.bind(null,t),approveErc20:Ya$1.bind(null,t),approveErc1155ForAll:ab.bind(null,t),transferErc20:Zg.bind(null,t),splitPosition:vf.bind(null,t),mergePositions:Hf.bind(null,t),redeemPositions:Qf.bind(null,t),planCollateralReturn:gc.bind(null,t),executeCollateralReturnPlan:kc.bind(null,t)}}function ns(t){return t.isSecureClient()?{...Re(t),...ge(t),...ve(t),...qe(t),...Ae(t),...Ce(t),...rs(t),...ss(t),...Ee(t),...is(t),...ke(t)}:{...Re(t),...ge(t),...ve(t),...qe(t),...Ae(t),...Ce(t),...Ee(t),...ke(t)}}var we={name:"production",chainId:137,rpc:"https://polygon.drpc.org",walletDerivation:{depositWalletFactory:expectEvmAddress("0x00000000000Fb5C9ADea0298D729A0CB3823Cc07"),depositWalletBeacon:expectEvmAddress("0x7A18EDfe055488A3128f01F563e5B479D92ffc3a"),depositWalletImplementation:expectEvmAddress("0x58CA52ebe0DadfdF531Cde7062e76746de4Db1eB"),proxyFactory:expectEvmAddress("0xaB45c5A4B0c941a2F231C04C3f49182e1A254052"),proxyImplementation:expectEvmAddress("0x44e999d5c2F66Ef0861317f9A4805AC2e90aEB4f"),safeFactory:expectEvmAddress("0xaacFeEa03eb1561C4e67d661e40682Bd20E3541b"),safeInitCodeHash:"0x2bce2127ff07fb632d16c8347c4ebf501f4841168bed00d9e6ef715ddb6fcecf"},contracts:{collateralToken:expectEvmAddress("0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB"),conditionalTokens:expectEvmAddress("0x4D97DCd97eC945f40cF65F87097ACe5EA0476045"),negRiskAdapter:expectEvmAddress("0xd91E80cF2E7be2e162c6513ceD06f1dD0dA35296"),collateralAdapter:expectEvmAddress("0xAdA100Db00Ca00073811820692005400218FcE1f"),negRiskCollateralAdapter:expectEvmAddress("0xadA2005600Dec949baf300f4C6120000bDB6eAab"),standardExchange:expectEvmAddress("0xE111180000d2663C0091e4f400237545B87B996B"),negRiskExchange:expectEvmAddress("0xe2222d279d744050d28e00520010520000310F59"),exchangeV3:expectEvmAddress("0xe3333700cA9d93003F00f0F71f8515005F6c00Aa"),protocolV2Router:expectEvmAddress("0x12121212006e4CD160D18e3f00711DA5c3372600"),binaryModule:expectEvmAddress("0x1000008dD9001B968442c1000017eaE6E0dA00Ba"),negRiskModule:expectEvmAddress("0x200000900045e3B6259600682756002200028933"),combinatorialModule:expectEvmAddress("0x30000034706c7d8e12009dab006be20000c031a8"),positionManager:expectEvmAddress("0x006F54F7f9A22e0000CC2AB60031000000ae9fEF"),autoRedeemOperator:expectEvmAddress("0xa1200000d0002264C9a1698e001292D00E1b00af"),safeMultisend:expectEvmAddress("0xA238CBeb142c10Ef7Ad8442C6D1f9E89e07e7761"),relayHub:expectEvmAddress("0xD216153c06E857cD7f72665E0aF1d7D82172F494"),perpsDepositContract:expectEvmAddress("0xDCa4af75705dbB50f62437045afF9921947917d2")},clob:{rest:"https://clob.polymarket.com",market:{ws:"wss://ws-subscriptions-clob.polymarket.com/ws/market"},user:{ws:"wss://ws-subscriptions-clob.polymarket.com/ws/user"}},relayer:{rest:"https://relayer-v2.polymarket.com"},gamma:{rest:"https://gamma-api.polymarket.com"},data:{rest:"https://data-api.polymarket.com"},combos:{rest:"https://combos-rfq-api.polymarket.com",ws:"wss://combos-rfq-gateway-quoter.polymarket.com/ws/rfq",builderGateway:{rest:"https://combos-rfq-gateway-builder.polymarket.com"},collateralReturn:{rest:"https://combos-rfq-collateral-return.polymarket.com"}},perps:{rest:"https://api.perpetuals.polymarket.com",ws:"wss://ws.perpetuals.polymarket.com/v1/ws"},realtime:{ws:"wss://ws-live-v2.polymarket.com/ws"},rtds:{ws:"wss://ws-live-data.polymarket.com"},sports:{ws:"wss://sports-api.polymarket.com/ws"},relayerMaxPolls:100,relayerPollFrequencyMs:2e3};function $o(t,e=we){return {...e,...t,walletDerivation:{...e.walletDerivation,...t.walletDerivation},contracts:{...e.contracts,...t.contracts},clob:{...k(e.clob,t.clob),market:L(e.clob.market,t.clob?.market),user:L(e.clob.user,t.clob?.user)},relayer:k(e.relayer,t.relayer),gamma:k(e.gamma,t.gamma),data:k(e.data,t.data),combos:{...os(e.combos,t.combos),builderGateway:k(e.combos.builderGateway,t.combos?.builderGateway),collateralReturn:k(e.combos.collateralReturn,t.combos?.collateralReturn)},perps:os(e.perps,t.perps),realtime:L(e.realtime,t.realtime),rtds:L(e.rtds,t.rtds),sports:L(e.sports,t.sports)}}function k(t,e){return {...t,...e,headers:Te(t.headers,e?.headers)}}function L(t,e){return {...t,...e,headers:Te(t.headers,e?.headers)}}function os(t,e){return {...t,...e,headers:Te(t.headers,e?.headers)}}function Te(t,e){if(!(t===void 0&&e===void 0))return {...t,...e}}var td=$o({name:"preproduction",clob:{rest:"https://clob-preprod-int-v2.polymarket.com"},data:{rest:"https://data-api-preprod-int.polymarket.com"},gamma:{rest:"https://gamma-api-preprod-int.polymarket.com"},relayer:{rest:"https://relayer-v2-preprod-int.polymarket.com"}});async function as(t,e,r,s,i){let n=`${e}${r}${s}`;i!==void 0&&(n+=i);let o=await globalThis.crypto.subtle.importKey("raw",Go(t),{name:"HMAC",hash:"SHA-256"},false,["sign"]),a=await globalThis.crypto.subtle.sign("HMAC",o,new TextEncoder().encode(n));return Jo(Yo(a))}function Go(t){let e=t.replace(/-/g,"+").replace(/_/g,"/").replace(/[^A-Za-z0-9+/=]/g,""),r=atob(e),s=new Uint8Array(r.length);for(let i=0;i<r.length;i+=1)s[i]=r.charCodeAt(i);return s.buffer}function Yo(t){let e=new Uint8Array(t),r="";for(let s of e)r+=String.fromCharCode(s);return btoa(r)}function Jo(t){return t.replace(/\+/g,"-").replace(/\//g,"_")}function R(t,e){let r;return {close:()=>(r===void 0&&(r=Promise.resolve(t.return()).then(()=>e())),r),[Symbol.asyncIterator](){return t[Symbol.asyncIterator]()}}}var b=class{#e=new Set;#s;constructor(e){this.#s=e?.deriveServerState??(()=>{});}add(e,r={}){let s={queue:pushable({objectMode:true})};r.matches!==void 0&&(s.matches=r.matches);let i={subscription:e,subscriber:s};return {change:this.#t(i),entry:i}}#t(e){let r=this.serverState();return this.#e.add(e),{before:r,after:this.serverState()}}remove(e){let r=this.serverState();return this.#e.delete(e),e.subscriber.queue.end(),{before:r,after:this.serverState()}}dispatch(e){for(let{subscriber:r}of this.#e)(r.matches===void 0||r.matches(e))&&r.queue.push(e);}hasActiveSubscriptions(){return this.#e.size>0}endAll(e){for(let{subscriber:r}of this.#e)r.queue.end(e);this.#e.clear();}serverState(){return this.#s(this.#e)}};function xe(t,e,r){let s=H(r.assetsIds,e.assetsIds),i=H(e.assetsIds,r.assetsIds);s.length>0&&t(cs(s,r.customFeatureEnabled));let n=r.assetsIds[0];s.length===0&&e.customFeatureEnabled!==r.customFeatureEnabled&&n!==void 0&&t(cs([n],r.customFeatureEnabled)),i.length>0&&t(Xo(i));}function Fe(t,e,r){if(r.includeAllMarkets){!e.includeAllMarkets&&e.markets.length>0&&t(ds(e.markets));return}if(e.includeAllMarkets){r.markets.length>0&&t(us(r.markets));return}let s=H(r.markets,e.markets),i=H(e.markets,r.markets);s.length>0&&t(us(s)),i.length>0&&t(ds(i));}function ps(t){let e=new Set,r=false;for(let{subscription:s}of t){for(let i of s.assetIds??s.tokenIds)e.add(i);r||=s.customFeatureEnabled===true;}return {assetsIds:Array.from(e),customFeatureEnabled:r}}function ls(t){let e=false,r=new Set;for(let{subscription:s}of t){if(bs(s)){e=true;continue}for(let i of s.markets??[])r.add(i);}return {includeAllMarkets:e,markets:e?[]:Array.from(r)}}function ms(t){return {assets_ids:t.assetsIds,custom_feature_enabled:t.customFeatureEnabled,type:"market"}}function cs(t,e){return {assets_ids:t,custom_feature_enabled:e,operation:"subscribe"}}function Xo(t){return {assets_ids:t,operation:"unsubscribe"}}function hs(t,e){let r={auth:{apiKey:e.key,passphrase:e.passphrase,secret:e.secret},type:"user"};return t.includeAllMarkets||(r.markets=t.markets),r}function us(t){return {markets:t,operation:"subscribe"}}function ds(t){return {markets:t,operation:"unsubscribe"}}function ys(t){let e=t.assetIds??t.tokenIds;return r=>{switch(r.type){case "price_change":return r.payload.priceChanges.some(s=>e.includes(s.assetId));case "new_market":return t.customFeatureEnabled===true;case "market_resolved":return t.customFeatureEnabled===true&&(r.payload.assetIds??[]).some(s=>e.includes(s));case "best_bid_ask":return t.customFeatureEnabled===true&&e.includes(r.payload.assetId);default:return e.includes(r.payload.assetId)}}}function fs(t){if(bs(t))return ()=>true;let e=new Set((t.markets??[]).map(r=>r.toLowerCase()));return r=>e.has(r.payload.market.toLowerCase())}function bs(t){return (t.markets?.length??0)===0}function H(t,e){let r=new Set(e);return t.filter(s=>!r.has(s))}var A=class{#e;#s;#t;#a=new ge$1({heartbeat:new ae});#o=new fe;#r=new b({deriveServerState:ps});constructor(e){this.#e=e.headers,this.#s=e.url;}async subscribe(e){let{change:r,entry:s}=this.#r.add(e,{matches:ys(e)});return await this.#i(s,r),R(s.subscriber.queue,()=>this.#n(s))}async#i(e,r){let{before:s,after:i}=r;try{(await this.#c()).reusedOpenSocket&&xe(o=>this.#a.send(o),s,i);}catch(n){throw await this.#n(e),n}}async#n(e){let{before:r,after:s}=this.#r.remove(e);if(!this.#r.hasActiveSubscriptions()){await this.close();return}xe(i=>this.#a.send(i),r,s);}async close(){this.#t===void 0&&(this.#t=this.#d().finally(()=>{this.#t=void 0;})),await this.#t;}async#d(){this.#o.stop(),this.#r.endAll(),await this.#a.close();}#c(){return this.#a.connect({onConnectionLost:()=>this.#l(),onError:()=>this.#m(),onMessage:e=>this.#p(e),onOpen:()=>this.#u(),headers:this.#e,url:this.#s})}#u(){this.#o.resetBackoff(),this.#y();}#p(e){let r=Array.isArray(e)?e:[e];for(let s of r){let i=MarketEventSchema.safeParse(s);i.success&&this.#r.dispatch(i.data);}}#l(){this.#r.hasActiveSubscriptions()&&this.#h();}#m(){}#y(){this.#a.send(ms(this.#r.serverState()));}#h(){this.#o.schedule({reconnect:()=>this.#c(),shouldReconnect:()=>this.#r.hasActiveSubscriptions()});}};var w=class{#e;#s;#t;#a;#o=new ge$1({heartbeat:new ae});#r=new fe;#i=new b({deriveServerState:ls});constructor(e){this.#e=e.credentials,this.#s=e.headers,this.#t=e.url;}async subscribe(e){let{change:r,entry:s}=this.#i.add(e,{matches:fs(e)});return await this.#n(s,r),R(s.subscriber.queue,()=>this.#d(s))}async#n(e,r){let{before:s,after:i}=r;try{(await this.#u()).reusedOpenSocket&&Fe(o=>this.#o.send(o),s,i);}catch(n){throw await this.#d(e),n}}async#d(e){let{before:r,after:s}=this.#i.remove(e);if(!this.#i.hasActiveSubscriptions()){await this.close();return}Fe(i=>this.#o.send(i),r,s);}async close(){this.#a===void 0&&(this.#a=this.#c().finally(()=>{this.#a=void 0;})),await this.#a;}async#c(){this.#r.stop(),this.#i.endAll(),await this.#o.close();}#u(){return this.#o.connect({onConnectionLost:()=>this.#m(),onError:()=>this.#y(),onMessage:e=>this.#l(e),onOpen:e=>this.#p(e),prepare:()=>this.#e,headers:this.#s,url:this.#t})}#p(e){this.#r.resetBackoff(),this.#h(e);}#l(e){let r=Array.isArray(e)?e:[e];for(let s of r){let i=UserEventSchema.safeParse(s);i.success&&this.#i.dispatch(i.data);}}#m(){this.#i.hasActiveSubscriptions()&&this.#f();}#y(){}#h(e){this.#o.send(hs(this.#i.serverState(),e));}#f(){this.#r.schedule({reconnect:()=>this.#u(),shouldReconnect:()=>this.#i.hasActiveSubscriptions()});}};var T=class{#e;#s;#t;#a;#o=new Set;#r=new Set;#i=new Set;#n=false;constructor(e){this.#e=e.chainId,this.#s=e.headers,this.#t=e.restUrl,this.#a=e.wsUrl;}connect(e,r,s,i){if(this.#n)return Promise.reject(new d("Perps session manager has been shut down."));let n=new oe({builderAttribution:r,approveBuilderFee:s,includeBuilderFills:i,chainId:this.#e,credentials:e,headers:this.#s,onClose:a=>this.#d(a),restUrl:this.#t,wsUrl:this.#a});this.#r.add(n);let o;return o=(async()=>{try{if(await n.connect(),this.#n)throw await n.close(),new d("Perps session manager has been shut down.");return this.#o.add(n),n}catch(a){throw await n.close(),a}finally{this.#i.delete(o),this.#r.delete(n);}})(),this.#i.add(o),o}async shutdown(){this.#n=true;let e=Array.from(this.#o),r=Array.from(this.#r),s=Array.from(this.#i);this.#o.clear(),this.#r.clear(),this.#i.clear(),await Promise.allSettled([...e.map(i=>i.close()),...r.map(i=>i.close()),...s.map(i=>i.catch(()=>{}))]).then(()=>{});}#d(e){this.#o.delete(e),this.#r.delete(e);}};var C=class{#e;#s;#t;#a=1;#o=new ge$1({heartbeat:new de});#r=new fe;#i=new b({deriveServerState:sa});constructor(e){this.#e=e.headers,this.#s=e.url;}async subscribe(e){let{change:r,entry:s}=this.#i.add(e,{matches:na(e)});return await this.#n(s,r),R(s.subscriber.queue,()=>this.#d(s))}async#n(e,r){try{(await this.#u()).reusedOpenSocket&&(this.#h(Ss(r.before,r.after)),this.#f(Ps(r.before,r.after)));}catch(s){throw await this.#d(e),s}}async#d(e){let{before:r,after:s}=this.#i.remove(e);this.#h(Ss(r,s)),this.#f(Ps(r,s)),this.#i.hasActiveSubscriptions()||await this.close();}async close(){this.#t===void 0&&(this.#t=this.#c().finally(()=>{this.#t=void 0;})),await this.#t;}async#c(){this.#r.stop(),this.#i.endAll(),await this.#o.close();}#u(){return this.#o.connect({onConnectionLost:()=>this.#m(),onError:()=>this.#y(),onMessage:e=>this.#l(e),onOpen:()=>this.#p(),headers:this.#e,url:this.#s})}#p(){this.#r.resetBackoff(),this.#h(Array.from(this.#i.serverState()));}#l(e){let r=PerpsMarketDataEventSchema.safeParse(e);r.success&&this.#i.dispatch(r.data);}#m(){this.#i.hasActiveSubscriptions()&&this.#S();}#y(){}#h(e){e.length!==0&&this.#o.send(this.#b("sub",e));}#f(e){e.length!==0&&this.#o.send(this.#b("unsub",e));}#b(e,r){return {id:this.#a++,req:e,chs:r}}#S(){this.#r.schedule({reconnect:()=>this.#u(),shouldReconnect:()=>this.#i.hasActiveSubscriptions()});}};function sa(t){let e=new Set,r=new Set,s=new Set,i=false,n=false;for(let{subscription:o}of t)switch(o.topic){case "perps.tickers":o.instrumentId===void 0?i=true:r.add(o.instrumentId);break;case "perps.statistics":o.instrumentId===void 0?n=true:s.add(o.instrumentId);break;default:e.add(ia(o));}if(i)e.add("tickers::all");else for(let o of r)e.add(`tickers::${o}`);if(n)e.add("statistics::all");else for(let o of s)e.add(`statistics::${o}`);return e}function Ss(t,e){return Array.from(e).filter(r=>!t.has(r))}function Ps(t,e){return Array.from(t).filter(r=>!e.has(r))}function ia(t){switch(t.topic){case "perps.trades":return `trades::${t.instrumentId}`;case "perps.bbo":return `bbo::${t.instrumentId}`;case "perps.book":return `book::${t.instrumentId}`;case "perps.candles":return `klines::${t.instrumentId}::${t.interval}`;case "perps.tickers":return t.instrumentId===void 0?"tickers::all":`tickers::${t.instrumentId}`;case "perps.statistics":return t.instrumentId===void 0?"statistics::all":`statistics::${t.instrumentId}`;default:invariant(false,`Unknown Perps topic: ${String(t)}`);}}function na(t){switch(t.topic){case "perps.trades":return e=>e.topic==="perps.trades"&&e.channel===`trades::${t.instrumentId}`;case "perps.bbo":case "perps.book":return e=>e.topic===t.topic&&e.payload.instrumentId===t.instrumentId;case "perps.candles":return e=>e.topic==="perps.candles"&&e.payload.instrumentId===t.instrumentId&&e.payload.interval===t.interval;case "perps.tickers":case "perps.statistics":return e=>e.topic===t.topic&&(t.instrumentId===void 0||e.payload.instrumentId===t.instrumentId);default:invariant(false,`Unknown Perps topic: ${String(t)}`);}}function gs(t){if(t.topic==="prices.equity"){let e=t.symbol.toLowerCase();return [{key:JSON.stringify([t.topic,e]),topic:t.topic,symbol:e}]}return t.symbols.map(e=>t.topic==="prices.crypto.twap"?{key:JSON.stringify([t.topic,e,60]),topic:t.topic,symbol:e,windowSeconds:60}:{key:JSON.stringify([t.topic,e]),topic:t.topic,symbol:e})}function vs(t,e){return Math.random()*(t===4003?1e4:Math.min(1e3*2**e,3e4))}var j=class{#e;#s=new fe;#t=new Map;#a=[];#o;#r;#i=false;#n=false;#d=false;#c=false;#u;#p=0;#l=64;#m=Number.NEGATIVE_INFINITY;constructor(e){this.#e=e;}get size(){return this.#t.size}has(e){return this.#t.has(e)}get closed(){return this.#n}get keyTarget(){return Date.now()-this.#m>=6e4?64:this.#l}add(e,r){clearTimeout(this.#r);let s=this.#t.get(e.key);if(s===void 0){let{promise:i,resolve:n,reject:o}=Promise.withResolvers();i.catch(()=>{}),s={subscription:e,listeners:new Set,ready:i,resolve:n,reject:o,subscribed:false,accepted:false},this.#t.set(e.key,s),this.#i&&this.#f("subscribe",[s]);}return s.listeners.add(r),s.snapshot!==void 0&&r.event(s.snapshot),!this.#i&&!this.#c&&this.#u===void 0&&!this.#s.isScheduled&&this.#y(),aa(s.ready)}remove(e,r){let s=this.#t.get(e);s!==void 0&&(s.listeners.delete(r),!(s.listeners.size>0)&&(this.#t.delete(e),s.reject(new d("Realtime subscription closed.")),this.#i&&this.#f("unsubscribe",[s]),this.#t.size===0&&(this.#r=setNonBlockingTimeout(()=>{this.close();},1e3))));}#y(){if(this.#n||this.#c)return Promise.resolve();if(this.#u!==void 0)return this.#u;let e=this.#h().catch(r=>{this.#A([...this.#t.values()].filter(s=>!s.accepted),d.fromError(r));}).finally(()=>{this.#u===e&&(this.#u=void 0),this.#i||this.#q(1006);});return this.#u=e,e}async#h(){let e=this.#p;if(await this.#e.open({event:r=>this.#R(r),dropped:()=>this.#g(),disconnected:r=>this.#v(r)}),!(this.#n||e!==this.#p))try{if(await this.#e.authorize(),this.#n||e!==this.#p)return;this.#i=!0,this.#f("subscribe",[...this.#t.values()]);}catch(r){if(this.#n||e!==this.#p)return;r instanceof h&&r.code!==RealtimeKnownErrorCode.AuthUnavailable?this.#E(r):await this.#C(1006);}}#f(e,r){if(r.length===0)return;let s=this.#a.at(-1);s?.op===e?s.keys.push(...r):this.#a.push({op:e,keys:r}),this.#b();}#b(){this.#o!==void 0||this.#d||!this.#i||this.#n||(this.#o=setNonBlockingTimeout(()=>{this.#o=void 0,this.#S();},10));}async#S(){if(!this.#i||this.#n)return;let e=this.#a.shift();if(e===void 0)return;let r=[...new Set(e.keys)].filter(i=>e.op==="unsubscribe"||this.#t.get(i.subscription.key)===i);if(r.length===0){this.#b();return}let s=this.#p;this.#d=true;try{let i=await this.#e.change(e.op,r.map(({subscription:n})=>n));if(s!==this.#p||this.#n)return;if(e.op==="unsubscribe"&&i.length>0){let n=i[0];if(n!==void 0)throw n.error}if(e.op==="subscribe"){this.#s.resetBackoff();let n=new Set(i.map(o=>o.key));for(let o of r)n.has(o.subscription.key)||(o.subscribed=!0,o.accepted=!0,o.resolve());for(let{key:o,error:a}of i){let c=r.find(u=>u.subscription.key===o);c!==void 0&&this.#A([c],a,!1);}}}catch(i){if(s!==this.#p||this.#n)return;i instanceof h&&e.op==="subscribe"?this.#A(r,i):await this.#C(1006);}finally{this.#d=false,this.#b();}}#R(e){for(let r of this.#t.values()){let s=r.subscription;if(s.topic!==e.topic)continue;let i=e.payload;if(i.symbol.toLowerCase()===s.symbol&&!(s.topic==="prices.crypto.twap"&&(!("windowSeconds"in i)||i.windowSeconds!==s.windowSeconds))){r.snapshot=ca(r.snapshot,e);for(let n of r.listeners)n.event(e);}}}#g(){let e=Date.now();e-this.#m<5e3||(this.#l=Math.max(1,Math.floor(this.keyTarget/2)),this.#m=e);}#P(){this.#p++,this.#i=false,this.#a=[],clearTimeout(this.#o),this.#o=void 0;for(let e of this.#t.values()){if(e.snapshot=void 0,!e.subscribed)continue;let{promise:r,resolve:s,reject:i}=Promise.withResolvers();r.catch(()=>{}),e.ready=r,e.resolve=s,e.reject=i,e.subscribed=false;}}#v(e){let r=new f("Realtime connection closed.",e);this.#P(),e.code===4001||e.code===4008?this.#E(r):this.#q(e.code);}async#C(e){this.#c=true,this.#P();try{await this.#e.close();}finally{this.#c=false,this.#q(e);}}#q(e){this.#s.schedule({delayPolicy:r=>vs(e,r),shouldReconnect:()=>!this.#n&&this.#t.size>0,reconnect:()=>this.#y()});}#E(e){let r=[...this.#t.values()],s=new Set(r.flatMap(i=>[...i.listeners]));for(let i of r)i.reject(e);for(let i of s)i.end(e);this.close();}#A(e,r,s=true){let i=e.filter(o=>this.#t.get(o.subscription.key)===o),n=new Set(i.flatMap(o=>[...o.listeners]));for(let o of i)this.#t.delete(o.subscription.key),o.reject(r);s&&this.#i&&this.#f("unsubscribe",i);for(let o of n)o.end(r);this.#t.size===0&&(this.#r=setNonBlockingTimeout(()=>{this.close();},1e3));}async close(){if(this.#n)return;this.#n=true,this.#s.stop(),clearTimeout(this.#r);let e=new d("Realtime connection closed.");this.#P();for(let r of this.#t.values())r.reject(e);this.#t.clear(),await this.#e.close();}};function aa(t){return new Promise((e,r)=>{let s=setNonBlockingTimeout(()=>{r(new d("Realtime subscription was not accepted within 30 seconds."));},3e4);t.then(()=>{clearTimeout(s),e();},i=>{clearTimeout(s),r(i);});})}function ca(t,e){if(e.type==="subscribe")return e;let r=t?.type==="subscribe"?t.payload.data:[],{symbol:s,timestamp:i,value:n}=e.payload;if((r.at(-1)?.timestamp??0)>i)return t;let o=[...r.filter(a=>a.timestamp>i-12e4&&a.timestamp<i),{timestamp:i,value:n}];return e.topic==="prices.crypto.twap"?{...e,type:"subscribe",payload:{symbol:s,data:o,windowSeconds:e.payload.windowSeconds}}:{...e,type:"subscribe",payload:{symbol:s,data:o}}}var V=class{#e;#s=new ge$1({heartbeat:new ee,connectTimeoutMs:1e4,closeTimeoutMs:1e3});#t=new Map;#a;#o=0;#r=0;#i=0;constructor(e){this.#e=e;}async open(e){this.#a=e;let r=this.#i;await this.#s.connect({url:this.#e.url,headers:this.#e.headers,onOpen:()=>{},onError:()=>{},onConnectionLost:s=>{r===this.#i&&(this.#c(new f("Realtime connection closed.",s)),e.disconnected(s));},onMessage:s=>{r===this.#i&&this.#d(s);}});}async authorize(){let{key:e,secret:r,passphrase:s}=this.#e.credentials;await this.#n({op:"auth",auth:{apiKey:e,secret:r,passphrase:s}},PolyboltAckOp.Authed,[]);}async change(e,r){let s=[],i=0;for(;i<r.length;){let n=[];for(;i+n.length<r.length;){let a=r[i+n.length];if(a===void 0)break;let c=la(a),u={op:e,subscriptions:[...n,c],rid:String(this.#o+1)};if(n.length>0&&new TextEncoder().encode(JSON.stringify(u)).length>6e4)break;n.push(c);}let o=await this.#n({op:e,subscriptions:n},e==="subscribe"?PolyboltAckOp.Subscribed:PolyboltAckOp.Unsubscribed,n.map(({channel:a})=>a));for(let{index:a,error:c}of o){let u=r[i+a];u!==void 0&&s.push({key:u.key,error:c});}i+=n.length;}return s}#n(e,r,s){let i=String(++this.#o);return new Promise((n,o)=>{let a={op:r,channels:[...s],rejections:[],resolve:n,reject:o};this.#t.set(i,a),a.sendTimer=setNonBlockingTimeout(()=>{a.timer=setNonBlockingTimeout(()=>{this.#t.delete(i),o(new d("Realtime acknowledgement timed out after 10 seconds."));},1e4),this.#r=Date.now();try{if(!this.#s.send({...e,rid:i}))throw new d("Realtime connection is not open.")}catch(c){clearTimeout(a.timer),this.#t.delete(i),o(d.fromError(c));}},Math.max(0,110-(Date.now()-this.#r)));})}#d(e){let r=PolyboltAckSchema.safeParse(e);if(r.success){let{op:n,rid:o,code:a,channel:c}=r.data,u=o===void 0?void 0:this.#t.get(o);if(u===void 0)return;if(n===PolyboltAckOp.Error&&a!==void 0){let S=new h(`Realtime subscription rejected: ${a}`,{status:200,code:a}),l=u.channels.flatMap((y,Z)=>y===c?[Z]:[]);if(c===void 0||l.length!==1)u.reject(S);else {let y=l[0];if(y===void 0||(u.channels[y]=void 0,u.rejections.push({index:y,error:S}),u.channels.some(Z=>Z!==void 0)))return;u.resolve(u.rejections);}}else if(n===u.op){if(u.channels.length>0){let S=u.channels.indexOf(c??"");if(S<0||(u.channels[S]=void 0,u.channels.some(l=>l!==void 0)))return}u.resolve(u.rejections);}else return;clearTimeout(u.timer),o!==void 0&&this.#t.delete(o);return}let s=PolyboltEnvelopeSchema.safeParse(e);if(!s.success)return;let i=parsePolyboltEvent(s.data);i!==void 0&&this.#a?.event(i),(s.data.dropped??0)>0&&this.#a?.dropped();}#c(e){for(let r of this.#t.values())clearTimeout(r.sendTimer),clearTimeout(r.timer),r.reject(e);this.#t.clear();}async close(){this.#i++,this.#a=void 0,this.#c(new d("Realtime connection closed.")),await this.#s.close();}};function la(t){switch(t.topic){case "prices.crypto":return {channel:PolyboltChannel.Crypto,filter:{symbol:t.symbol}};case "prices.crypto.twap":return {channel:PolyboltChannel.Twap,filter:{symbol:t.symbol,window_seconds:t.windowSeconds}};case "prices.equity":return {channel:PolyboltChannel.Equity,filter:{symbol:t.symbol}}}}var N=class{#e;#s=new Set;#t=new Set;constructor(e){this.#e=e;}async subscribe(e){let r=[...new Map(gs(e).map(c=>[c.key,c])).values()],s=pushable({objectMode:true}),i=[],n=false,o,a=async()=>{if(!n){n=true;for(let c of i)c();o===void 0?await s.return():s.end(o),this.#t.delete(a);}};this.#t.add(a);try{await Promise.all(r.map(c=>{let u=this.#a(c.key),S={event(l){if(n||"types"in e&&e.types!==void 0&&e.types.length>0&&!e.types.includes(l.type))return;let y="symbol"in l.payload?{...l.payload,symbol:"symbol"in c?c.symbol:l.payload.symbol}:l.payload;s.push({...l,payload:y});},end(l){o=l,s.end(l),a();}};return i.push(()=>u.remove(c.key,S)),u.add(c,S)}));}catch(c){throw await a(),c}return {close:a,async*[Symbol.asyncIterator](){try{yield*s;}finally{await a();}}}}#a(e){for(let s of this.#s)if(s.closed)this.#s.delete(s);else if(s.has(e))return s;for(let s of this.#s)if(s.size<s.keyTarget)return s;let r=new j(new V(this.#e));return this.#s.add(r),r}async close(){await Promise.all([...this.#t].map(r=>r()));let e=[...this.#s];this.#s.clear(),await Promise.all(e.map(r=>r.close()));}};var B=class{#e;constructor(e){this.#e=new N(e);}async subscribe(e){return this.#e.subscribe(e)}async close(){await this.#e.close();}};function Cs(t,e){return {...e,quote:r=>t.quote(e,r)}}function Es(t,e){let r=e.rfqId,s=e.quoteId;return {...e,confirm:()=>t.respondToConfirmation(r,s,RfqConfirmationDecision.Confirm),decline:()=>t.respondToConfirmation(r,s,RfqConfirmationDecision.Decline)}}function ks(t){return {quoteId:t.quoteId,rfqId:t.rfqId}}function ws(t){return {quoteId:t.quoteId,rfqId:t.rfqId}}function Ts(t){return {quoteId:t.quoteId,rfqId:t.rfqId}}function xs(t,e){let r=M$1(t);return {auth:{apiKey:e.key,passphrase:e.passphrase,secret:e.secret},identity:{maker_address:r.maker,signature_type:r.signatureType,signer_address:r.signer},type:"auth"}}function Fs(t,e){return {price_e6:e.price.toString(),rfq_id:t.rfqId,signed_order:e.signedOrder,size_e6:e.size.toString(),type:"RFQ_QUOTE"}}function Ms(t,e,r){let s=M$1(t);return {maker_address:s.maker,quote_id:r,rfq_id:e,signer_address:s.signer,type:"RFQ_QUOTE_CANCEL"}}function Os(t,e,r){return {decision:r,quote_id:e,rfq_id:t,type:"RFQ_CONFIRMATION_RESPONSE"}}var $=class{#e=new Map;#s;constructor(e){this.#s=e;}waitFor(e,r){let s=ya(),i,n=setNonBlockingTimeout(()=>{this.remove(e,i),s.reject(new j$1(r));},this.#s);i=s.promise.finally(()=>clearTimeout(n));let o=this.#e.get(e)??[];return o.push({...s,promise:i}),this.#e.set(e,o),i}resolve(e,r){let s=this.#e.get(e),i=s?.shift();i!==void 0&&(s!==void 0&&s.length===0&&this.#e.delete(e),i.resolve(r));}reject(e,r){let s=this.#e.get(e),i=s?.shift();i!==void 0&&(s!==void 0&&s.length===0&&this.#e.delete(e),i.reject(r));}remove(e,r){let s=this.#e.get(e);if(s===void 0)return;let i=s.filter(n=>n.promise!==r);i.length===0?this.#e.delete(e):this.#e.set(e,i);}rejectAll(e){for(let r of this.#e.values())for(let s of r)s.reject(e);this.#e.clear();}};function ya(){let t,e;return {promise:new Promise((s,i)=>{t=s,e=i;}),reject:e,resolve:t}}var Ls="0x0000000000000000000000000000000000000000000000000000000000000000";async function Bs(t){let e=M$1(t.account),r=Bd({chainId:t.chainId,exchange:t.exchange}),s={builder:Ls,maker:e.maker,makerAmount:toBaseUnits(Cd(t.orderSide,t.orderPrice,t.size)),metadata:Ls,salt:fa().toString(),side:Ed(t.orderSide),signatureType:e.signatureType,signer:e.signer,takerAmount:toBaseUnits(Dd(t.orderSide,t.orderPrice,t.size)),timestamp:Math.floor(Date.now()/1e3).toString(),tokenId:t.tokenId},i;try{i=await t.signer.signTypedData(zd({domain:r,order:s}));}catch(n){throw q.fromError(n,"Could not sign the RFQ quote order.")}return {...s,signature:Ad({domain:r,order:s,signature:i})}}function fa(){let t=new Uint8Array(8);return globalThis.crypto.getRandomValues(t),BigInt(`0x${Array.from(t,e=>e.toString(16).padStart(2,"0")).join("")}`)}var Ws=DecimalishSchema.transform(t=>Hs(t)).refine(t=>t<=BigInt(Number.MAX_SAFE_INTEGER),{message:"Value exceeds the temporary numeric wire limit."}),Pa=z.strictObject({price:Ws.refine(t=>t<1000000n,{message:"Price must be less than 1."}),size:Ws.optional(),source:z.enum(["collateral","inventory"]).default("collateral")});function Qs(t){return I(t,Pa)}async function Ks(t){let e=t.response.price,r=t.response.size===void 0?qa(t.request.requestedSize,e):t.response.size,s=await Bs({account:t.account,chainId:t.chainId,exchange:t.exchange,orderPrice:ga(t.request,t.response.source,e),orderSide:va(t.response.source),signer:t.signer,size:r,tokenId:Ra(t.request,t.response.source)});return {price:e,signedOrder:s,size:r}}function Ra(t,e){return t.direction===RfqDirection.Buy?e==="collateral"?t.noPositionId:t.yesPositionId:e==="collateral"?t.yesPositionId:t.noPositionId}function ga(t,e,r){return t.direction===RfqDirection.Buy&&e==="collateral"||t.direction===RfqDirection.Sell&&e==="inventory"?1000000n-r:r}function va(t){return t==="collateral"?OrderSide.BUY:OrderSide.SELL}function qa(t,e){let r=Hs(t.value);return t.unit===RfqRequestedSizeUnit.Shares?r:r*1000000n/e}function Hs(t){let e=/^(\d+)(?:\.(\d*))?$/.exec(t);if(e===null)throw new a("Value must be a valid decimal.");let[,r="",s=""]=e;if(s.length>6)throw new a("Value must have at most 6 decimal places.");let i=BigInt(r)*1000000n+BigInt(s.padEnd(6,"0"));if(i<=0n)throw new a("Value must be greater than 0.");return i}var ka=3e4,wa=3e4,x=class{#e;#s;#t;#a;#o;#r;#i;#n;#d;#c;#u=false;constructor(e){this.#e=e.account,this.#s=e.chainId,this.#t=e.credentials,this.#a=e.exchange,this.#o=e.headers,this.#r=e.signer,this.#i=e.url;}async connect(){if(this.#u)throw new d("RFQ quoter manager has been shut down.");if(this.#n!==void 0){if(!this.#n.closed)return this.#n;this.#n=void 0;}if(this.#c!==void 0)return this.#c;let e=new Be({account:this.#e,chainId:this.#s,credentials:this.#t,exchange:this.#a,headers:this.#o,onClose:()=>this.#p(e),signer:this.#r,url:this.#i});this.#d=e;let r;return r=(async()=>{try{if(await e.connect(),this.#u)throw await e.close(),new d("RFQ quoter manager has been shut down.");return this.#n=e,e}catch(s){throw await e.close(),s}finally{this.#c===r&&(this.#c=void 0),this.#d===e&&(this.#d=void 0);}})(),this.#c=r,r}async shutdown(){this.#u=true;let e=this.#n,r=this.#d,s=this.#c;this.#n=void 0,this.#d=void 0,this.#c=void 0,await Promise.allSettled([e?.close(),r?.close(),s?.catch(()=>{})]).then(()=>{});}#p(e){this.#n===e&&(this.#n=void 0),this.#d===e&&(this.#d=void 0);}},Be=class{#e;#s;#t;#a;#o;#r;#i;#n;#d=new ge$1;#c=pushable({objectMode:true});#u=new $(wa);#p;#l;constructor(e){this.#e=e.account,this.#s=e.chainId,this.#t=e.credentials,this.#a=e.exchange,this.#o=e.headers,this.#r=e.onClose,this.#i=e.signer,this.#n=e.url;}get closed(){return this.#p!==void 0}async connect(){let e=Ta();this.#l=e;let r=setNonBlockingTimeout(()=>{e.reject(new d("RFQ quoter authentication timed out."));},ka);try{await this.#d.connect({headers:this.#o,onConnectionLost:s=>this.#P(s),onError:()=>{},onMessage:s=>this.#R(s),onOpen:()=>this.#S(),url:this.#n}),await e.promise;}finally{clearTimeout(r),this.#l=void 0;}}async#m(e){if(!this.#d.send(e))throw new d("RFQ quoter websocket is not open.")}async close(){this.#p===void 0&&(this.#p=this.#y()),await this.#p;}[Symbol.asyncIterator](){return this.#c[Symbol.asyncIterator]()}async#y(){let e=new d("RFQ quoter websocket closed.");this.#b(e),this.#c.end(),await this.#d.close(),this.#r();}async#h(e){this.#p===void 0&&(this.#p=this.#f(e)),await this.#p;}async#f(e){this.#b(e),this.#c.end(e),await this.#d.close(),this.#r();}#b(e){this.#l?.reject(e),this.#u.rejectAll(e);}#S(){this.#d.send(xs(this.#e,this.#t));}#R(e){if(this.#p!==void 0)return;let r=RfqQuoterInboundMessageSchema.safeParse(e);if(!r.success)return;let s=r.data;switch(s.type){case "auth":this.#g(s);return;case "quote_request":this.#c.push(Cs(this,s));return;case "quote_ack":this.#u.resolve(G(s.rfqId),ks(s));return;case "quote_cancel_ack":this.#u.resolve(Ie(s.rfqId,s.quoteId),ws(s));return;case "confirmation_request":this.#c.push(Es(this,s));return;case "confirmation_ack":this.#u.resolve(Le(s.rfqId,s.quoteId),Ts(s));return;case "execution_update":this.#c.push(s);return;case "trade":this.#c.push(s);return;case "rfq_error":this.#v(s);return}}#g(e){if(e.success===true){this.#l?.resolve(void 0);return}this.#l?.reject(new d(`RFQ quoter authentication failed: ${e.error}`));}#P(e){this.#h(new f("RFQ quoter connection lost.",e));}#v(e){if(e.requestType==="RFQ_QUOTE"){if(e.rfqId===void 0){this.#h(new d("Uncorrelated RFQ quoter error."));return}this.#u.reject(G(e.rfqId),new Tf(e.message,{code:e.code,errorId:e.errorId,rfqId:e.rfqId}));return}if(e.requestType==="RFQ_QUOTE_CANCEL"){if(e.rfqId===void 0||e.quoteId===void 0){this.#h(new d("Uncorrelated RFQ quoter error."));return}this.#u.reject(Ie(e.rfqId,e.quoteId),new Vf(e.message,{code:e.code,errorId:e.errorId,quoteId:e.quoteId,rfqId:e.rfqId}));return}if(e.requestType==="RFQ_CONFIRMATION_RESPONSE"){if(e.rfqId===void 0||e.quoteId===void 0){this.#h(new d("Uncorrelated RFQ quoter error."));return}this.#u.reject(Le(e.rfqId,e.quoteId),new Xf(e.message,{code:e.code,errorId:e.errorId,quoteId:e.quoteId,rfqId:e.rfqId}));}}async quote(e,r){let s=Qs(r),i=await Ks({account:this.#e,chainId:this.#s,exchange:this.#a,request:e,response:s,signer:this.#i}),n=this.#u.waitFor(G(e.rfqId),`Timed out waiting for RFQ quote acknowledgement for ${e.rfqId}.`);try{return await this.#m(Fs(e,i)),await n}catch(o){throw this.#u.remove(G(e.rfqId),n),o}}async cancelQuote(e){let r=Ie(e.rfqId,e.quoteId),s=this.#u.waitFor(r,`Timed out waiting for RFQ quote cancellation acknowledgement for ${e.rfqId}.`);try{return await this.#m(Ms(this.#e,e.rfqId,e.quoteId)),await s}catch(i){throw this.#u.remove(r,s),i}}async respondToConfirmation(e,r,s){let i=Le(e,r),n=this.#u.waitFor(i,`Timed out waiting for RFQ confirmation acknowledgement for ${e}.`);try{return await this.#m(Os(e,r,s)),await n}catch(o){throw this.#u.remove(i,n),o}}};function G(t){return `ACK_RFQ_QUOTE:${t}`}function Ie(t,e){return `ACK_RFQ_QUOTE_CANCEL:${t}:${e}`}function Le(t,e){return `ACK_RFQ_CONFIRMATION_RESPONSE:${t}:${e}`}function Ta(){let t,e;return {promise:new Promise((s,i)=>{t=s,e=i;}),reject:e,resolve:t}}var F=class{#e;#s;#t;#a=new ge$1({heartbeat:new be});#o=new fe;#r=new b({deriveServerState:Oa});constructor(e){this.#e=e.headers,this.#s=e.url;}async subscribe(e){let{change:r,entry:s}=this.#r.add(e,{matches:Da(e)});return await this.#i(s,r),R(s.subscriber.queue,()=>this.#n(s))}async#i(e,r){try{if((await this.#c()).reusedOpenSocket){let{before:i,after:n}=r,o=Fa(i,n);this.#h(o);}}catch(s){throw await this.#n(e),s}}async#n(e){let{before:r,after:s}=this.#r.remove(e),i=Ma(r,s);this.#f(i),this.#r.hasActiveSubscriptions()||await this.close();}async close(){this.#t===void 0&&(this.#t=this.#d().finally(()=>{this.#t=void 0;})),await this.#t;}async#d(){this.#o.stop(),this.#r.endAll(),await this.#a.close();}#c(){return this.#a.connect({onConnectionLost:()=>this.#l(),onError:()=>this.#m(),onMessage:e=>this.#p(e),onOpen:()=>this.#u(),headers:this.#e,url:this.#s})}#u(){this.#o.resetBackoff(),this.#y();}#p(e){let r=RealtimeEventSchema.safeParse(e);r.success&&this.#r.dispatch(r.data);}#l(){this.#r.hasActiveSubscriptions()&&this.#b();}#m(){}#y(){this.#h(Array.from(this.#r.serverState().values()));}#h(e){e.length!==0&&this.#a.send(Ia(e));}#f(e){e.length!==0&&this.#a.send(La(e));}#b(){this.#o.schedule({reconnect:()=>this.#c(),shouldReconnect:()=>this.#r.hasActiveSubscriptions()});}};function Fa(t,e){return Array.from(e).flatMap(([r,s])=>t.has(r)?[]:[s])}function Ma(t,e){return Array.from(t).flatMap(([r,s])=>e.has(r)?[]:[s])}function Oa(t){let e=new Map;for(let{subscription:r}of t)for(let s of Ba(r))e.has(s.key)||e.set(s.key,s);return e}function Ia(t){return {action:"subscribe",subscriptions:t.map(({topic:e,type:r})=>({topic:e,type:r}))}}function La(t){return {action:"unsubscribe",subscriptions:t.map(({topic:e,type:r})=>({topic:e,type:r}))}}function Ba(t){switch(t.topic){case "comments":return (t.types??["comment_created"]).map(e=>U("comments",e));case "prices.crypto.binance":return [U("crypto_prices","update")];case "prices.crypto.chainlink":return [U("crypto_prices_chainlink","update")];case "prices.crypto.chainlink.twap":return [U(Ua(t.windowSeconds),"update")];case "prices.equity.pyth":return [U("equity_prices","update")];default:invariant(false,`Unknown RTDS topic: ${String(t)}`);}}function Ua(t){switch(t){case 30:return "crypto_prices_twap_thirty";case 60:return "crypto_prices_twap_sixty";default:invariant(false,`Unknown TWAP window: ${String(t)}`);}}function U(t,e){return {key:`${t}:${e}`,topic:t,type:e}}function Da(t){switch(t.topic){case "comments":return e=>!(e.topic!=="comments"||t.types!==void 0&&t.types.length>0&&!t.types.includes(e.type)||(t.parentEntityId!==void 0||t.parentEntityType!==void 0)&&(!(e.type==="comment_created"||e.type==="comment_removed")||t.parentEntityId!==void 0&&e.payload.parentEntityID!==t.parentEntityId||t.parentEntityType!==void 0&&e.payload.parentEntityType!==t.parentEntityType));case "prices.crypto.binance":return e=>e.topic==="prices.crypto.binance"&&(t.symbols===void 0||t.symbols.length===0||t.symbols.includes(e.payload.symbol));case "prices.crypto.chainlink":return e=>e.topic==="prices.crypto.chainlink"&&(t.symbols===void 0||t.symbols.length===0||t.symbols.includes(e.payload.symbol));case "prices.crypto.chainlink.twap":return e=>e.topic==="prices.crypto.chainlink.twap"&&e.payload.windowSeconds===t.windowSeconds&&(t.symbols===void 0||t.symbols.length===0||t.symbols.includes(e.payload.symbol));case "prices.equity.pyth":return e=>e.topic==="prices.equity.pyth"&&e.payload.symbol.toLowerCase()===t.symbol.toLowerCase()&&(t.types===void 0||t.types.length===0||t.types.includes(e.type));default:invariant(false,`Unknown RTDS topic: ${String(t)}`);}}var M=class{#e;#s;#t;#a=new ge$1({heartbeat:new ce});#o=new fe;#r=new b;constructor(e){this.#e=e.headers,this.#s=e.url;}async subscribe(e){let{entry:r}=this.#r.add(e);return await this.#i(r),R(r.subscriber.queue,()=>this.#n(r))}async#i(e){try{await this.#c();}catch(r){throw await this.#n(e),r}}async#n(e){this.#r.remove(e),this.#r.hasActiveSubscriptions()||await this.close();}async close(){this.#t===void 0&&(this.#t=this.#d().finally(()=>{this.#t=void 0;})),await this.#t;}async#d(){this.#o.stop(),this.#r.endAll(),await this.#a.close();}#c(){return this.#a.connect({onConnectionLost:()=>this.#l(),onError:()=>this.#m(),onMessage:e=>this.#p(e),onOpen:()=>this.#u(),headers:this.#e,url:this.#s})}#u(){this.#o.resetBackoff();}#p(e){let r=SportsResultEventSchema.safeParse(e);r.success&&this.#r.dispatch(r.data);}#l(){this.#r.hasActiveSubscriptions()&&this.#y();}#m(){}#y(){this.#o.schedule({reconnect:()=>this.#c(),shouldReconnect:()=>this.#r.hasActiveSubscriptions()});}};var Y=class{#e;#s;get context(){return this.#e}get decorators(){return this.#s}get environment(){return this.context.environment}get clob(){return this.context.clob}get relayer(){return this.context.relayer}get rpc(){return this.context.rpc}get gamma(){return this.context.gamma}get data(){return this.context.data}get rfq(){return this.context.rfq}get perps(){return this.context.perps}get webSockets(){return this.context.webSockets}get supportsGasless(){return this.context.apiKey?.supportGasless??false}get hasBuilderApiKey(){return this.context.apiKey?.isBuilderKey??false}constructor(e){this.#e=e,this.#s=[];}async resolveClobHeaders(e){return this.context.apiKey?.isBuilderKey?this.context.apiKey.authorize(e):Promise.resolve({})}async resolveRelayerHeaders(e){return this.context.apiKey?.supportGasless?this.context.apiKey.authorize(e):Promise.resolve({})}rememberDecorator(e){this.#s.push(e);}},za=z.object({key:ApiKeySchema,passphrase:z.string(),secret:z.string()}),Va=z.object({wallet:EvmAddressSchema,credentials:za.optional(),nonce:z.number().int().nonnegative().optional()}).superRefine((t,e)=>{t.credentials!==void 0&&t.nonce!==void 0&&e.addIssue({code:"custom",message:"`credentials` and `nonce` are mutually exclusive.",path:["nonce"]});}).transform(t=>t.credentials!==void 0?{wallet:t.wallet,credentials:t.credentials}:t.nonce!==void 0?{wallet:t.wallet,nonce:t.nonce}:{wallet:t.wallet}),J=class extends Y{constructor(e){super({apiKey:e.apiKey,environment:e.environment,onRateLimitUpdate:e.onRateLimitUpdate,data:new $d({headers:e.environment.data.headers,root:e.environment.data.rest}),gamma:new $d({headers:e.environment.gamma.headers,root:e.environment.gamma.rest}),clob:new $d({headers:e.environment.clob.headers,onRateLimitUpdate:e.onRateLimitUpdate,root:e.environment.clob.rest,resolveHeaders:r=>this.resolveClobHeaders(r)}),relayer:new $d({headers:e.environment.relayer.headers,root:e.environment.relayer.rest,resolveHeaders:r=>this.resolveRelayerHeaders(r)}),rfq:new $d({headers:e.environment.combos.headers,root:e.environment.combos.rest}),perps:new $d({headers:e.environment.perps.headers,root:e.environment.perps.rest}),rpc:new J$1({url:e.environment.rpc}),webSockets:{clobMarket:new A({headers:e.environment.clob.market.headers,url:e.environment.clob.market.ws}),sports:new M({headers:e.environment.sports.headers,url:e.environment.sports.ws}),rtds:new F({headers:e.environment.rtds.headers,url:e.environment.rtds.ws}),perpsSubscriptions:new C({headers:e.environment.perps.headers,url:e.environment.perps.ws})}});}isSecureClient(){return false}isPublicClient(){return true}async closeSubscriptions(){await Promise.all([this.webSockets.clobMarket.close(),this.webSockets.rtds.close(),this.webSockets.sports.close(),this.webSockets.perpsSubscriptions.close()]).then(()=>{});}extend(e){return this.rememberDecorator(e),Object.assign(this,e(this)),this}beginAuthentication(e,r){let s=I(e,Va);return Promise.resolve(async function*(){let i=Math.floor(Date.now()/1e3),n=s?.nonce??0,o=expectEvmAddress(yield Ca()),a=expectEvmAddress(s.wallet),c=L$1(this.environment,o,a);if(s.credentials!==void 0){let l=this.#e(s.credentials,c,r);try{if((await ob(l)).includes(s.credentials.key))return l}catch(y){if(!(y instanceof h)||y.status!==401)throw y}}let u=yield {kind:"signAuthMessage",payload:ts({address:o,chainId:this.environment.chainId,nonce:n,timestamp:i})},S=await mb(this,{address:o,nonce:n,signature:expectEvmSignature(u),timestamp:i});return this.#e(S,c,r)}.call(this))}#e(e,r,s){let i=new Qe({account:r,apiKey:this.context.apiKey,credentials:e,environment:this.environment,onRateLimitUpdate:this.context.onRateLimitUpdate,signer:s});for(let n of this.decorators)i.extend(n);return i}},Qe=class extends Y{#e=false;get context(){return invariant(!this.#e,"This client has ended authentication and can no longer be used."),super.context}endAuthenticationLifecycle(){this.#e=true;}constructor(e){let r=new B({url:e.environment.realtime.ws,headers:e.environment.realtime.headers,credentials:e.credentials});super({account:e.account,credentials:e.credentials,apiKey:e.apiKey,environment:e.environment,onRateLimitUpdate:e.onRateLimitUpdate,signer:e.signer,clob:new $d({headers:e.environment.clob.headers,onRateLimitUpdate:e.onRateLimitUpdate,root:e.environment.clob.rest,resolveHeaders:s=>this.resolveClobHeaders(s)}),relayer:new $d({headers:e.environment.relayer.headers,root:e.environment.relayer.rest,resolveHeaders:s=>this.resolveRelayerHeaders(s)}),rpc:new J$1({url:e.environment.rpc}),gamma:new $d({headers:e.environment.gamma.headers,root:e.environment.gamma.rest}),data:new $d({headers:e.environment.data.headers,root:e.environment.data.rest}),rfq:new $d({headers:e.environment.combos.headers,root:e.environment.combos.rest}),perps:new $d({headers:e.environment.perps.headers,root:e.environment.perps.rest}),secureClob:new $d({headers:e.environment.clob.headers,onRateLimitUpdate:e.onRateLimitUpdate,resolveHeaders:async s=>({...await this.resolveClobHeaders(s),...await this.#t(s)}),root:e.environment.clob.rest}),combos:new $d({headers:e.environment.combos.collateralReturn.headers,resolveHeaders:s=>this.resolveRelayerHeaders(s),root:e.environment.combos.collateralReturn.rest}),builderGateway:new $d({headers:e.environment.combos.builderGateway.headers,resolveHeaders:async s=>({...await this.#s(s),...await this.#t(s)}),root:e.environment.combos.builderGateway.rest}),webSockets:{clobMarket:new A({headers:e.environment.clob.market.headers,url:e.environment.clob.market.ws}),clobUser:new w({credentials:e.credentials,headers:e.environment.clob.user.headers,url:e.environment.clob.user.ws}),rfqQuoter:new x({account:e.account,chainId:e.environment.chainId,credentials:e.credentials,exchange:e.environment.contracts.exchangeV3,headers:e.environment.combos.headers,signer:e.signer,url:e.environment.combos.ws}),sports:new M({headers:e.environment.sports.headers,url:e.environment.sports.ws}),realtime:r,rtds:new F({headers:e.environment.rtds.headers,url:e.environment.rtds.ws}),perpsSubscriptions:new C({headers:e.environment.perps.headers,url:e.environment.perps.ws}),perpsSession:new T({chainId:e.environment.chainId,headers:e.environment.perps.headers,restUrl:e.environment.perps.rest,wsUrl:e.environment.perps.ws})}});}get credentials(){return this.context.credentials}get account(){return this.context.account}get signer(){return this.context.signer}get secureClob(){return this.context.secureClob}get combos(){return this.context.combos}get builderGateway(){return this.context.builderGateway}get webSockets(){return this.context.webSockets}async closeSubscriptions(){await Promise.allSettled([this.webSockets.clobMarket.close(),this.webSockets.realtime.close(),this.webSockets.rtds.close(),this.webSockets.sports.close(),this.webSockets.perpsSubscriptions.close(),this.webSockets.clobUser.close()]).then(()=>{});}isSecureClient(){return true}isPublicClient(){return false}extend(e){return this.rememberDecorator(e),Object.assign(this,e(this)),this}async endAuthentication(){let e=this.closeSubscriptions(),r=this.webSockets.perpsSession.shutdown(),s=this.webSockets.rfqQuoter.shutdown(),{apiKey:i,environment:n,onRateLimitUpdate:o}=this.context;try{await qb(this);}finally{this.endAuthenticationLifecycle(),await Promise.allSettled([e,r,s]).then(()=>{});}let a=new J({apiKey:i,environment:n,onRateLimitUpdate:o});for(let c of this.decorators)a.extend(c);return a}async#s(e){return e.method!=="GET"&&this.context.apiKey?.isBuilderKey?this.context.apiKey.authorize(e):{}}async#t(e){try{let r=Math.floor(Date.now()/1e3);return {POLY_ADDRESS:this.account.signer,POLY_API_KEY:this.credentials.key,POLY_PASSPHRASE:this.credentials.passphrase,POLY_SIGNATURE:await as(this.credentials.secret,r,e.method,e.path,e.body),POLY_TIMESTAMP:`${r}`}}catch(r){throw q.fromError(r,"Could not sign the L2-authenticated request")}}};function _s(t={}){return new J({environment:t.environment??we,apiKey:t.apiKey,onRateLimitUpdate:t.onRateLimitUpdate}).extend(ns)}var Na=r(m,i,h,q,j$1,l,d,c,a),$a=r(a);async function Ga(t){let e=_s({environment:t.environment,apiKey:t.apiKey,onRateLimitUpdate:t.onRateLimitUpdate}),r=await Ya(e,t),s=await e.beginAuthentication({wallet:r,credentials:t.credentials,nonce:t.nonce},t.signer).then(Ba$1(t.signer));if(s.account.walletType===WalletType.EOA||await Ga$1(s,{wallet:s.account.wallet,type:s.account.walletType}))return s;if(s.account.walletType===WalletType.DEPOSIT_WALLET)return await Ja(s),s;throw new a(`Wallet ${s.account.wallet} does not exist. Provide an existing wallet address, or omit wallet to use the default Deposit Wallet flow.`)}async function Ya(t,e){if(e.wallet!==void 0)return e.wallet;let r=expectEvmAddress(await e.signer.getAddress()),s=N$1(r,t.environment.walletDerivation);return await Ga$1(t,{wallet:s,type:WalletType.DEPOSIT_WALLET})?s:O(r,t.environment.walletDerivation)}async function Ja(t){let e=O(t.account.signer,t.environment.walletDerivation);if(!isSameEvmAddress(t.account.wallet,e))throw new a(`Wallet ${t.account.wallet} does not match the expected Deposit Wallet ${e} for this signer, nor a deployed wallet address.`);await(await Ja$1(t)).wait();}
|
|
2
|
-
export{
|
|
1
|
+
import {Q,_,Y as Y$1,W as W$1,ua as ua$1,sa,rf,pf,nf,lf,Oc,jf,hf,ff,Qc,Mc,Kc,Ic,yb,qa,fd,jd,td,hd,ac,_b,Yb,Wb,Ub,Sb,Qb,Ob,Cb,Ab,zc,Bc,rc,pc as pc$1,nc,fg,kh,Yg,Wg,Jg,ih,gh,eh,ch,Wc,Ng,Lg,dd,bd,$c,Zc,xc,vc,tc as tc$1,_d,df,$e,af,Ye,Xe,_e,oa as oa$1,ma as ma$1,ka as ka$1,ia as ia$1,ga as ga$1,ea,ug,sg,qg,ng,Ug,Qg,Sg,_g,U as U$1,S,rd,pd,nd,ld,Qd,zd,yd,Yd,Wd,Ud,Sd,kc,gc,dg,Wf,Kf,oh,ab,Ya as Ya$1,gb,db,Ba as Ba$1,Ga as Ga$1,N as N$1,O as O$1,Ja as Ja$1,Oe as Oe$1,Me as Me$1,Ke,Ge,Ee as Ee$1,Ce as Ce$1,Qe as Qe$1,Ie,be,ec as ec$1,cc as cc$1,J as J$1,ce,I as I$1,Ca as Ca$1,L,ob,mb,je,ge as ge$1,ie,ee as ee$1,fe,de,qb,Ae as Ae$1,gg,ig,kg,he,M as M$1,Cd,Ed as Ed$1,Fd,Dd,Ad,Bd}from'./chunk-MY66WYAN.js';export{rg as AcceptComboQuoteError,$a as ApproveErc1155ForAllError,Xa as ApproveErc20Error,$d as ApprovePerpsBuilderFeeError,qe as ArmPerpsAutoCancelError,Rg as AuthorizeSessionKeyError,Rc as BiggestWinnerKind,Sc as BuilderVolumeInterval,od as CancelAllError,qd as CancelMarketOrdersError,kd as CancelOrderError,md as CancelOrdersError,pe as CancelPerpsChaseError,ye as CancelPerpsTwapError,lc as CollateralReturnKnownOperationKind,E as CombinatorialPrepareConditionCallError,xg as ComboAcceptFailureReason,va as ComboActivityType,sf as ComboPositionSortBy,tf as ComboPositionStatus,yg as ComboQuoteUnavailableReason,Vd as CreateLimitOrderError,Rd as CreateMarketOrderError,ne as CreatePerpsChaseError,ue as CreatePerpsTwapError,u as CtfMergePositionsCallError,w as CtfRedeemPositionsCallError,s as CtfSplitPositionCallError,Ue as DepositToPerpsError,qf as DownloadAccountingSnapshotError,Z as DropNotificationsError,b as Erc20ApprovalCallError,m as Erc20TransferCallError,sd as EstimateMarketPriceError,jc as ExecuteCollateralReturnPlanError,Jc as FetchBuilderVolumeError,P as FetchClosedOnlyModeError,oc as FetchCommentsByIdError,uc as FetchEventError,Ac as FetchEventLiveVolumeError,wc as FetchEventTagsError,Zb as FetchLastTradePriceError,$b as FetchLastTradePricesError,ad as FetchMarketError,cd as FetchMarketTagsError,zb as FetchMidpointError,Bb as FetchMidpointsError,X as FetchNotificationsError,id as FetchOpenInterestError,Rb as FetchOrderBookError,Tb as FetchOrderBooksError,T as FetchOrderError,da as FetchOrderScoringError,fa as FetchOrdersScoringError,He as FetchPerpsBookError,ke as FetchPerpsBuilderApprovalsError,me as FetchPerpsBuilderEarningsSummaryError,Zd as FetchPerpsBuilderStatusError,oe as FetchPerpsChasesError,Pe as FetchPerpsFeesError,Be as FetchPerpsInstrumentsError,ae as FetchPerpsPositionSnapshotsError,cf as FetchPerpsRegistrationError,De as FetchPerpsTickerError,Fe as FetchPerpsTickersError,ve as FetchPerpsTwapsError,if as FetchPortfolioValueError,Nb as FetchPriceError,Pb as FetchPricesError,eg as FetchPublicProfileError,hh as FetchRelatedTagResourcesError,fh as FetchRelatedTagsError,yc as FetchResolutionsError,na as FetchRewardPercentagesError,vg as FetchRfqStatusError,Mg as FetchSeriesError,Pg as FetchSessionKeysError,Xg as FetchSportsMarketTypesError,Vb as FetchSpreadError,Xb as FetchSpreadsError,dh as FetchTagError,ja as FetchTotalEarningsForUserForDayError,Nc as FetchTraderLeaderboardStandingError,cb as FetchTradingApprovalsStateError,mf as FetchUserPnlError,kf as FetchUserStatsError,of as FetchUserVolumeError,$g as KnownPriceSource,Tc as LeaderboardWindow,V as ListAccountTradesError,ra as ListActivityError,Pc as ListBiggestWinnersError,Hc as ListBuilderLeaderboardError,xb as ListBuilderTradesError,ta as ListComboActivityError,_c as ListComboMarketsError,gf as ListComboPositionsError,qc as ListCommentsByUserAddressError,mc as ListCommentsError,bc as ListCurrentRewardsError,sc as ListEventsError,ed as ListMarketHoldersError,dc as ListMarketRewardsError,Yc as ListMarketsError,R as ListOpenOrdersError,le as ListPerpsBuilderEarningsError,Je as ListPerpsCandlesError,Le as ListPerpsFundingHistoryError,Ne as ListPerpsTradesError,ef as ListPositionsError,gd as ListPriceHistoryError,Kg as ListSeriesError,Vg as ListSportsError,bh as ListTagsError,jh as ListTeamsError,Lc as ListTraderLeaderboardError,pa as ListTradesError,la as ListUserEarningsAndMarketsConfigError,ha as ListUserEarningsForDayError,a as MAX_UINT256,Rf as MergePositionsError,Re as OpenPerpsSessionError,mg as OpenRfqSessionError,we as PausePerpsTwapError,q as PerpsDepositCallError,Xd as PlaceLimitOrderError,Td as PlaceMarketOrderError,fc as PlanCollateralReturnError,uf as PositionFilterType,vf as PositionSortBy,wf as PositionStatus,wd as PostOrderError,xd as PostOrdersError,Xc as PriceHistoryInterval,ah as PriceProvider,cg as RedeemPositionsError,pg as RequestComboQuoteError,Cc as ResolutionMarketType,Dc as ResolutionReporter,Ec as ResolutionSettlementTimeBasis,Fc as ResolutionSource,Gc as ResolutionStatus,xe as ResumePerpsTwapError,ze as RevokePerpsBuilderFeeError,Se as RevokePerpsCredentialsError,Tg as RevokeSessionKeyError,jg as RfqCancelQuoteError,ig as RfqCancelQuoteRejectedError,zg as RfqConfirmationDecision,lg as RfqConfirmationError,kg as RfqConfirmationRejectedError,Ag as RfqDirection,Bg as RfqExecutionStatus,Cg as RfqKnownErrorCode,hg as RfqQuoteError,gg as RfqQuoteRejectedError,Dg as RfqRejectionCode,og as RfqRequestRejectedError,Eg as RfqRequestedSizeUnit,Fg as RfqSide,Gg as RfqStatus,A as RouterMergeCallError,C as RouterRedeemCallError,y as RouterSplitCallError,Ig as SearchError,Hg as SearchSort,Og as SessionKeyKnownScope,fb as SetupTradingApprovalsError,K as SignerType,wa as SortDirection,Ff as SplitPositionError,Zg as SubscribeError,xa as TipSide,ya as TradeFilterType,Uc as TraderLeaderboardSort,nh as TransferErc20Error,We as TransferPerpsCollateralError,re as UpdatePerpsLeverageError,se as UpdatePerpsLeveragesError,te as UpdatePerpsMarginError,xf as UserPnlFidelity,yf as UserPnlInterval,tg as WaitForComboFillError,Pd as WaitForOrderFillSettlementError,za as WaitForTransactionError,Ve as WithdrawFromPerpsError,o as authorizeSessionSignerCall,F as combinatorialPrepareConditionCall,v as ctfMergePositionsCall,x as ctfRedeemPositionsCall,t as ctfSplitPositionCall,l as decodeErc1155BalanceOfBatchResult,j as decodeErc1155BalanceOfResult,h as decodeErc1155IsApprovedForAllResult,e as decodeErc20AllowanceResult,G as encodeProxyCall,H as encodeSafeMultisendCall,f as erc1155ApprovalForAllCall,k as erc1155BalanceOfBatchCall,i as erc1155BalanceOfCall,g as erc1155IsApprovedForAllCall,d as erc20AllowanceCall,c as erc20ApprovalCall,n as erc20TransferCall,Aa as expectTransactionHandle,r as perpsDepositCall,p as revokeSessionSignerCall,B as routerMergeCall,D as routerRedeemCall,z as routerSplitCall}from'./chunk-MY66WYAN.js';import {a,r,m,i,h,q,j,l,d,c,f}from'./chunk-VLNLVY4C.js';export{o as AutoCancelDailyLimitError,m as CancelledSigningError,f as ConnectionLostError,n as InsufficientLiquidityError,k as OperationAbortedError,b as PaginationLimitError,p as PerpsCancelRetryError,i as RateLimitError,s as RealtimeKnownErrorCode,h as RequestRejectedError,q as SigningError,j as TimeoutError,g as TradingRestriction,l as TransactionFailedError,d as TransportError,c as UnexpectedResponseError,a as UserInputError,e as WebSocketKnownCloseCode,r as makeErrorGuard}from'./chunk-VLNLVY4C.js';import {DecimalishSchema,ApiKeySchema,EvmAddressSchema,toBaseUnits,OrderSide}from'@polymarket/bindings';export{CommentParentEntityType,OrderSide,OrderType}from'@polymarket/bindings';export{AssetType,NotificationType,OrderPostStatus,OrderResponseErrorCode,SignatureType}from'@polymarket/bindings/clob';export{ActivityType}from'@polymarket/bindings/data';import {WalletType}from'@polymarket/bindings/gamma';export{ComboKnownStatus,ProtocolVersion,TeamOrdering,WalletType}from'@polymarket/bindings/gamma';export{PerpsDepositStatus,PerpsInstrumentCategory,PerpsInstrumentType,PerpsInternalTransferDirection,PerpsKlineInterval,PerpsKnownCancelOrderErrorCode,PerpsKnownInternalTransferType,PerpsKnownWithdrawalStatus,PerpsLiquidityRole,PerpsMarginType,PerpsNotificationOrderType,PerpsNotificationType,PerpsOrderStatus,PerpsPositionSnapshotMarkerKind,PerpsPositionSnapshotStatus,PerpsSide,PerpsSortDirection,PerpsTimeInForce,PerpsTwapStatus}from'@polymarket/bindings/perps';import {z as z$1}from'zod';import {expectEvmAddress,isSameEvmAddress,expectEvmSignature,invariant,setNonBlockingTimeout}from'@polymarket/types';import {TypedData}from'ox';import {PerpsMarketDataEventSchema,RealtimeEventSchema,SportsResultEventSchema,MarketEventSchema,UserEventSchema,RealtimeKnownErrorCode,PolyboltAckOp,PolyboltAckSchema,PolyboltEnvelopeSchema,parsePolyboltEvent,PolyboltChannel}from'@polymarket/bindings/subscriptions';import {pushable}from'it-pushable';import {RfqQuoterInboundMessageSchema,RfqConfirmationDecision,RfqRequestedSizeUnit,RfqDirection}from'@polymarket/bindings/combos';var ia=z$1.object({POLY_BUILDER_API_KEY:z$1.string().min(1),POLY_BUILDER_TIMESTAMP:z$1.string().min(1),POLY_BUILDER_PASSPHRASE:z$1.string().min(1),POLY_BUILDER_SIGNATURE:z$1.string().min(1)});function oa(t){return new Re(t)}function na(t){return new ge(t)}var Re=class{#e;constructor(e){this.#e=e;}get isBuilderKey(){return true}get supportGasless(){return true}async authorize(e){try{return await this.#t(e)}catch(r){throw q.fromError(r,"Could not authorize the builder-authenticated request")}}async#s(){let e=this.#e.headers,r=typeof e=="function"?await e():e,s=new Headers(r);return s.set("content-type","application/json"),s}async#t(e){let r=await fetch(this.#e.url,{body:JSON.stringify({body:e.body,method:e.method,path:e.path}),credentials:this.#e.credentials,headers:await this.#s(),method:"POST",mode:"cors"});if(!r.ok)throw new Error(`Remote signer rejected request with status ${r.status}`);return ia.parse(await r.json())}},ge=class{#e;constructor(e){this.#e=e;}get isBuilderKey(){return false}get supportGasless(){return true}authorize(){return Promise.resolve({RELAYER_API_KEY:this.#e.key,RELAYER_API_KEY_ADDRESS:this.#e.address})}};function is(t){let e={chainId:t.chainId,name:"ClobAuthDomain",version:"1"};return {domain:e,message:{address:t.address,message:"This message attests that I control the given wallet",nonce:t.nonce??0,timestamp:`${t.timestamp}`},primaryType:"ClobAuth",types:{EIP712Domain:TypedData.extractEip712DomainTypes(e),ClobAuth:[{name:"address",type:"address"},{name:"timestamp",type:"string"},{name:"nonce",type:"uint256"},{name:"message",type:"string"}]}}}function ca(t){return {listPositions:ff.bind(null,t),listComboPositions:hf.bind(null,t),fetchPortfolioValue:jf.bind(null,t),fetchTraderLeaderboardStanding:Oc.bind(null,t),fetchUserStats:lf.bind(null,t),fetchUserPnl:nf.bind(null,t),fetchUserVolume:pf.bind(null,t),downloadAccountingSnapshot:rf.bind(null,t),listActivity:sa.bind(null,t),listComboActivity:ua$1.bind(null,t)}}function R(t,e={}){return e===null||typeof e!="object"||Array.isArray(e)?e:{...e,user:e.user===void 0?t.account.wallet:e.user}}function ve(t){let e=ca(t);return t.isPublicClient()?e:{...e,listPositions:r=>ff(t,R(t,r)),listComboPositions:r=>hf(t,R(t,r)),fetchPortfolioValue:r=>jf(t,R(t,r)),fetchTraderLeaderboardStanding:r=>Oc(t,R(t,r)),fetchUserStats:r=>lf(t,R(t,r)),fetchUserPnl:r=>nf(t,R(t,r)),fetchUserVolume:r=>pf(t,R(t,r)),downloadAccountingSnapshot:r=>rf(t,R(t,r)),listActivity:r=>sa(t,R(t,r)),listComboActivity:r=>ua$1(t,R(t,r)),listAccountTrades:W$1.bind(null,t),fetchNotifications:Y$1.bind(null,t),dropNotifications:_.bind(null,t),fetchClosedOnlyMode:Q.bind(null,t)}}function qe(t){return {listBuilderTrades:yb.bind(null,t),listBuilderLeaderboard:Ic.bind(null,t),fetchBuilderVolume:Kc.bind(null,t),listTraderLeaderboard:Mc.bind(null,t),listBiggestWinners:Qc.bind(null,t)}}function Ce(t){return {fetchEventLiveVolume:Bc.bind(null,t),fetchResolutions:zc.bind(null,t),fetchMidpoint:Ab.bind(null,t),fetchMidpoints:Cb.bind(null,t),fetchPrice:Ob.bind(null,t),fetchPrices:Qb.bind(null,t),fetchOrderBook:Sb.bind(null,t),fetchOrderBooks:Ub.bind(null,t),fetchSpread:Wb.bind(null,t),fetchSpreads:Yb.bind(null,t),fetchLastTradePrice:_b.bind(null,t),fetchLastTradePrices:ac.bind(null,t),listPriceHistory:hd.bind(null,t),estimateMarketPrice:td.bind(null,t),fetchOpenInterest:jd.bind(null,t),listMarketHolders:fd.bind(null,t),listTrades:qa.bind(null,t)}}function Ae(t){return {listEvents:tc$1.bind(null,t),fetchEvent:vc.bind(null,t),fetchEventTags:xc.bind(null,t),listMarkets:Zc.bind(null,t),listComboMarkets:$c.bind(null,t),fetchMarket:bd.bind(null,t),fetchMarketTags:dd.bind(null,t),listSeries:Lg.bind(null,t),fetchSeries:Ng.bind(null,t),listMarketClarifications:Wc.bind(null,t),listTags:ch.bind(null,t),fetchTag:eh.bind(null,t),fetchRelatedTags:gh.bind(null,t),fetchRelatedTagResources:ih.bind(null,t),search:Jg.bind(null,t),listSports:Wg.bind(null,t),fetchSportsMarketTypes:Yg.bind(null,t),listTeams:kh.bind(null,t),fetchPublicProfile:fg.bind(null,t),listComments:nc.bind(null,t),fetchCommentsById:pc$1.bind(null,t),listCommentsByUserAddress:rc.bind(null,t)}}function Ee(t){let e={fetchPerpsPositionSnapshots:r=>be(t,r),fetchPerpsRegistration:df.bind(null,t),fetchPerpsBuilderStatus:_d.bind(null,t),fetchPerpsBook:r=>Ie(t,r),fetchPerpsFees:()=>Qe$1(t),fetchPerpsInstruments:r=>Ce$1(t,r),fetchPerpsTicker:r=>Ee$1(t,r),fetchPerpsTickers:r=>Ge(t,r),listPerpsCandles:r=>Ke(t,r),listPerpsFundingHistory:r=>Me$1(t,r),listPerpsTrades:r=>Oe$1(t,r)};return t.isSecureClient()?{...e,depositToPerps:r=>_e(t,r),openPerpsSession:r=>Xe(t,r),revokePerpsCredentials:r=>Ye(t,r),transferPerpsCollateral:af.bind(null,t),withdrawFromPerps:r=>$e(t,r)}:e}function ua(t){return {listCurrentRewards:cc$1.bind(null,t),listMarketRewards:ec$1.bind(null,t)}}function we(t){let e=ua(t);return t.isPublicClient()?e:{...e,fetchOrderScoring:ea.bind(null,t),fetchOrdersScoring:ga$1.bind(null,t),listUserEarningsForDay:ia$1.bind(null,t),fetchTotalEarningsForUserForDay:ka$1.bind(null,t),listUserEarningsAndMarketsConfig:ma$1.bind(null,t),fetchRewardPercentages:oa$1.bind(null,t)}}function os(t){return {openRfqSession(){return ng(t)},requestComboQuote(e){return qg(t,e)},acceptComboQuote(e){return sg(t,e)},waitForComboFill(e){return ug(t,e)}}}function ns(t){return {authorizeSessionKey:Sg.bind(null,t),fetchSessionKeys:Qg.bind(null,t),revokeSessionKey:Ug.bind(null,t)}}function Te(t){return t.isSecureClient()?{subscribe(e){return _g(t,e)}}:{subscribe(e){return _g(t,e)}}}function as(t){return {createMarketOrder:Sd.bind(null,t),placeMarketOrder:Ud.bind(null,t),createLimitOrder:Wd.bind(null,t),placeLimitOrder:Yd.bind(null,t),postOrder:yd(t),postOrders:zd(t),waitForOrderFillSettlement:Qd.bind(null,t),cancelOrder:ld.bind(null,t),cancelOrders:nd.bind(null,t),cancelAll:pd.bind(null,t),cancelMarketOrders:rd.bind(null,t),listOpenOrders:S.bind(null,t),fetchOrder:U$1.bind(null,t)}}function da(t){return {fetchTradingApprovalsState:db.bind(null,t)}}function ke(t){let e=da(t);return t.isPublicClient()?e:{...e,fetchTradingApprovalsState:()=>db(t,{user:t.account.wallet}),setupTradingApprovals:gb.bind(null,t),approveErc20:Ya$1.bind(null,t),approveErc1155ForAll:ab.bind(null,t),transferErc20:oh.bind(null,t),splitPosition:Kf.bind(null,t),mergePositions:Wf.bind(null,t),redeemPositions:dg.bind(null,t),planCollateralReturn:gc.bind(null,t),executeCollateralReturnPlan:kc.bind(null,t)}}function cs(t){return t.isSecureClient()?{...ve(t),...qe(t),...Ce(t),...Ae(t),...Ee(t),...we(t),...os(t),...ns(t),...Te(t),...as(t),...ke(t)}:{...ve(t),...qe(t),...Ce(t),...Ae(t),...Ee(t),...we(t),...Te(t),...ke(t)}}var xe={name:"production",chainId:137,rpc:"https://polygon.drpc.org",walletDerivation:{depositWalletFactory:expectEvmAddress("0x00000000000Fb5C9ADea0298D729A0CB3823Cc07"),depositWalletBeacon:expectEvmAddress("0x7A18EDfe055488A3128f01F563e5B479D92ffc3a"),depositWalletImplementation:expectEvmAddress("0x58CA52ebe0DadfdF531Cde7062e76746de4Db1eB"),proxyFactory:expectEvmAddress("0xaB45c5A4B0c941a2F231C04C3f49182e1A254052"),proxyImplementation:expectEvmAddress("0x44e999d5c2F66Ef0861317f9A4805AC2e90aEB4f"),safeFactory:expectEvmAddress("0xaacFeEa03eb1561C4e67d661e40682Bd20E3541b"),safeInitCodeHash:"0x2bce2127ff07fb632d16c8347c4ebf501f4841168bed00d9e6ef715ddb6fcecf"},contracts:{collateralToken:expectEvmAddress("0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB"),conditionalTokens:expectEvmAddress("0x4D97DCd97eC945f40cF65F87097ACe5EA0476045"),negRiskAdapter:expectEvmAddress("0xd91E80cF2E7be2e162c6513ceD06f1dD0dA35296"),collateralAdapter:expectEvmAddress("0xAdA100Db00Ca00073811820692005400218FcE1f"),negRiskCollateralAdapter:expectEvmAddress("0xadA2005600Dec949baf300f4C6120000bDB6eAab"),standardExchange:expectEvmAddress("0xE111180000d2663C0091e4f400237545B87B996B"),negRiskExchange:expectEvmAddress("0xe2222d279d744050d28e00520010520000310F59"),exchangeV3:expectEvmAddress("0xe3333700cA9d93003F00f0F71f8515005F6c00Aa"),protocolV2Router:expectEvmAddress("0x12121212006e4CD160D18e3f00711DA5c3372600"),binaryModule:expectEvmAddress("0x1000008dD9001B968442c1000017eaE6E0dA00Ba"),negRiskModule:expectEvmAddress("0x200000900045e3B6259600682756002200028933"),combinatorialModule:expectEvmAddress("0x30000034706c7d8e12009dab006be20000c031a8"),positionManager:expectEvmAddress("0x006F54F7f9A22e0000CC2AB60031000000ae9fEF"),autoRedeemOperator:expectEvmAddress("0xa1200000d0002264C9a1698e001292D00E1b00af"),safeMultisend:expectEvmAddress("0xA238CBeb142c10Ef7Ad8442C6D1f9E89e07e7761"),relayHub:expectEvmAddress("0xD216153c06E857cD7f72665E0aF1d7D82172F494"),perpsDepositContract:expectEvmAddress("0xDCa4af75705dbB50f62437045afF9921947917d2")},clob:{rest:"https://clob.polymarket.com",market:{ws:"wss://ws-subscriptions-clob.polymarket.com/ws/market"},user:{ws:"wss://ws-subscriptions-clob.polymarket.com/ws/user"}},relayer:{rest:"https://relayer-v2.polymarket.com"},gamma:{rest:"https://gamma-api.polymarket.com"},data:{rest:"https://data-api.polymarket.com"},combos:{rest:"https://combos-rfq-api.polymarket.com",ws:"wss://combos-rfq-gateway-quoter.polymarket.com/ws/rfq",builderGateway:{rest:"https://combos-rfq-gateway-builder.polymarket.com"},collateralReturn:{rest:"https://combos-rfq-collateral-return.polymarket.com"}},perps:{rest:"https://api.perpetuals.polymarket.com",ws:"wss://ws.perpetuals.polymarket.com/v1/ws"},realtime:{ws:"wss://ws-live-v2.polymarket.com/ws"},rtds:{ws:"wss://ws-live-data.polymarket.com"},sports:{ws:"wss://sports-api.polymarket.com/ws"},relayerMaxPolls:100,relayerPollFrequencyMs:2e3};function pa(t,e=xe){return {...e,...t,walletDerivation:{...e.walletDerivation,...t.walletDerivation},contracts:{...e.contracts,...t.contracts},clob:{...k(e.clob,t.clob),market:U(e.clob.market,t.clob?.market),user:U(e.clob.user,t.clob?.user)},relayer:k(e.relayer,t.relayer),gamma:k(e.gamma,t.gamma),data:k(e.data,t.data),combos:{...us(e.combos,t.combos),builderGateway:k(e.combos.builderGateway,t.combos?.builderGateway),collateralReturn:k(e.combos.collateralReturn,t.combos?.collateralReturn)},perps:us(e.perps,t.perps),realtime:U(e.realtime,t.realtime),rtds:U(e.rtds,t.rtds),sports:U(e.sports,t.sports)}}function k(t,e){return {...t,...e,headers:Fe(t.headers,e?.headers)}}function U(t,e){return {...t,...e,headers:Fe(t.headers,e?.headers)}}function us(t,e){return {...t,...e,headers:Fe(t.headers,e?.headers)}}function Fe(t,e){if(!(t===void 0&&e===void 0))return {...t,...e}}var Ed=pa({name:"preproduction",clob:{rest:"https://clob-preprod-int-v2.polymarket.com"},data:{rest:"https://data-api-preprod-int.polymarket.com"},gamma:{rest:"https://gamma-api-preprod-int.polymarket.com"},relayer:{rest:"https://relayer-v2-preprod-int.polymarket.com"}});async function ds(t,e,r,s,i){let o=`${e}${r}${s}`;i!==void 0&&(o+=i);let n=await globalThis.crypto.subtle.importKey("raw",la(t),{name:"HMAC",hash:"SHA-256"},false,["sign"]),a=await globalThis.crypto.subtle.sign("HMAC",n,new TextEncoder().encode(o));return ha(ma(a))}function la(t){let e=t.replace(/-/g,"+").replace(/_/g,"/").replace(/[^A-Za-z0-9+/=]/g,""),r=atob(e),s=new Uint8Array(r.length);for(let i=0;i<r.length;i+=1)s[i]=r.charCodeAt(i);return s.buffer}function ma(t){let e=new Uint8Array(t),r="";for(let s of e)r+=String.fromCharCode(s);return btoa(r)}function ha(t){return t.replace(/\+/g,"-").replace(/\//g,"_")}function g(t,e){let r;return {close:()=>(r===void 0&&(r=Promise.resolve(t.return()).then(()=>e())),r),[Symbol.asyncIterator](){return t[Symbol.asyncIterator]()}}}var P=class{#e=new Set;#s;constructor(e){this.#s=e?.deriveServerState??(()=>{});}add(e,r={}){let s={queue:pushable({objectMode:true})};r.matches!==void 0&&(s.matches=r.matches);let i={subscription:e,subscriber:s};return {change:this.#t(i),entry:i}}#t(e){let r=this.serverState();return this.#e.add(e),{before:r,after:this.serverState()}}remove(e){let r=this.serverState();return this.#e.delete(e),e.subscriber.queue.end(),{before:r,after:this.serverState()}}dispatch(e){for(let{subscriber:r}of this.#e)(r.matches===void 0||r.matches(e))&&r.queue.push(e);}hasActiveSubscriptions(){return this.#e.size>0}endAll(e){for(let{subscriber:r}of this.#e)r.queue.end(e);this.#e.clear();}serverState(){return this.#s(this.#e)}};function Me(t,e,r){let s=z(r.assetsIds,e.assetsIds),i=z(e.assetsIds,r.assetsIds);s.length>0&&t(ps(s,r.customFeatureEnabled));let o=r.assetsIds[0];s.length===0&&e.customFeatureEnabled!==r.customFeatureEnabled&&o!==void 0&&t(ps([o],r.customFeatureEnabled)),i.length>0&&t(fa(i));}function Oe(t,e,r){if(r.includeAllMarkets){!e.includeAllMarkets&&e.markets.length>0&&t(ms(e.markets));return}if(e.includeAllMarkets){r.markets.length>0&&t(ls(r.markets));return}let s=z(r.markets,e.markets),i=z(e.markets,r.markets);s.length>0&&t(ls(s)),i.length>0&&t(ms(i));}function hs(t){let e=new Set,r=false;for(let{subscription:s}of t){for(let i of s.assetIds??s.tokenIds)e.add(i);r||=s.customFeatureEnabled===true;}return {assetsIds:Array.from(e),customFeatureEnabled:r}}function ys(t){let e=false,r=new Set;for(let{subscription:s}of t){if(Rs(s)){e=true;continue}for(let i of s.markets??[])r.add(i);}return {includeAllMarkets:e,markets:e?[]:Array.from(r)}}function fs(t){return {assets_ids:t.assetsIds,custom_feature_enabled:t.customFeatureEnabled,type:"market"}}function ps(t,e){return {assets_ids:t,custom_feature_enabled:e,operation:"subscribe"}}function fa(t){return {assets_ids:t,operation:"unsubscribe"}}function bs(t,e){let r={auth:{apiKey:e.key,passphrase:e.passphrase,secret:e.secret},type:"user"};return t.includeAllMarkets||(r.markets=t.markets),r}function ls(t){return {markets:t,operation:"subscribe"}}function ms(t){return {markets:t,operation:"unsubscribe"}}function Ss(t){let e=t.assetIds??t.tokenIds;return r=>{switch(r.type){case "price_change":return r.payload.priceChanges.some(s=>e.includes(s.assetId));case "new_market":return t.customFeatureEnabled===true;case "market_resolved":return t.customFeatureEnabled===true&&(r.payload.assetIds??[]).some(s=>e.includes(s));case "best_bid_ask":return t.customFeatureEnabled===true&&e.includes(r.payload.assetId);default:return e.includes(r.payload.assetId)}}}function Ps(t){if(Rs(t))return ()=>true;let e=new Set((t.markets??[]).map(r=>r.toLowerCase()));return r=>e.has(r.payload.market.toLowerCase())}function Rs(t){return (t.markets?.length??0)===0}function z(t,e){let r=new Set(e);return t.filter(s=>!r.has(s))}var E=class{#e;#s;#t;#n=new je({heartbeat:new de});#a=new ie;#r=new P({deriveServerState:hs});constructor(e){this.#e=e.headers,this.#s=e.url;}async subscribe(e){let{change:r,entry:s}=this.#r.add(e,{matches:Ss(e)});return await this.#i(s,r),g(s.subscriber.queue,()=>this.#o(s))}async#i(e,r){let{before:s,after:i}=r;try{(await this.#c()).reusedOpenSocket&&Me(n=>this.#n.send(n),s,i);}catch(o){throw await this.#o(e),o}}async#o(e){let{before:r,after:s}=this.#r.remove(e);if(!this.#r.hasActiveSubscriptions()){await this.close();return}Me(i=>this.#n.send(i),r,s);}async close(){this.#t===void 0&&(this.#t=this.#d().finally(()=>{this.#t=void 0;})),await this.#t;}async#d(){this.#a.stop(),this.#r.endAll(),await this.#n.close();}#c(){return this.#n.connect({onConnectionLost:()=>this.#l(),onError:()=>this.#m(),onMessage:e=>this.#p(e),onOpen:()=>this.#u(),headers:this.#e,url:this.#s})}#u(){this.#a.resetBackoff(),this.#y();}#p(e){let r=Array.isArray(e)?e:[e];for(let s of r){let i=MarketEventSchema.safeParse(s);i.success&&this.#r.dispatch(i.data);}}#l(){this.#r.hasActiveSubscriptions()&&this.#h();}#m(){}#y(){this.#n.send(fs(this.#r.serverState()));}#h(){this.#a.schedule({reconnect:()=>this.#c(),shouldReconnect:()=>this.#r.hasActiveSubscriptions()});}};var x=class{#e;#s;#t;#n;#a=new je({heartbeat:new de});#r=new ie;#i=new P({deriveServerState:ys});constructor(e){this.#e=e.credentials,this.#s=e.headers,this.#t=e.url;}async subscribe(e){let{change:r,entry:s}=this.#i.add(e,{matches:Ps(e)});return await this.#o(s,r),g(s.subscriber.queue,()=>this.#d(s))}async#o(e,r){let{before:s,after:i}=r;try{(await this.#u()).reusedOpenSocket&&Oe(n=>this.#a.send(n),s,i);}catch(o){throw await this.#d(e),o}}async#d(e){let{before:r,after:s}=this.#i.remove(e);if(!this.#i.hasActiveSubscriptions()){await this.close();return}Oe(i=>this.#a.send(i),r,s);}async close(){this.#n===void 0&&(this.#n=this.#c().finally(()=>{this.#n=void 0;})),await this.#n;}async#c(){this.#r.stop(),this.#i.endAll(),await this.#a.close();}#u(){return this.#a.connect({onConnectionLost:()=>this.#m(),onError:()=>this.#y(),onMessage:e=>this.#l(e),onOpen:e=>this.#p(e),prepare:()=>this.#e,headers:this.#s,url:this.#t})}#p(e){this.#r.resetBackoff(),this.#h(e);}#l(e){let r=Array.isArray(e)?e:[e];for(let s of r){let i=UserEventSchema.safeParse(s);i.success&&this.#i.dispatch(i.data);}}#m(){this.#i.hasActiveSubscriptions()&&this.#f();}#y(){}#h(e){this.#a.send(bs(this.#i.serverState(),e));}#f(){this.#r.schedule({reconnect:()=>this.#u(),shouldReconnect:()=>this.#i.hasActiveSubscriptions()});}};var F=class{#e;#s;#t;#n;#a=new Set;#r=new Set;#i=new Set;#o=false;constructor(e){this.#e=e.chainId,this.#s=e.headers,this.#t=e.restUrl,this.#n=e.wsUrl;}connect(e,r,s,i){if(this.#o)return Promise.reject(new d("Perps session manager has been shut down."));let o=new Ae$1({builderAttribution:r,approveBuilderFee:s,includeBuilderFills:i,chainId:this.#e,credentials:e,headers:this.#s,onClose:a=>this.#d(a),restUrl:this.#t,wsUrl:this.#n});this.#r.add(o);let n;return n=(async()=>{try{if(await o.connect(),this.#o)throw await o.close(),new d("Perps session manager has been shut down.");return this.#a.add(o),o}catch(a){throw await o.close(),a}finally{this.#i.delete(n),this.#r.delete(o);}})(),this.#i.add(n),n}async shutdown(){this.#o=true;let e=Array.from(this.#a),r=Array.from(this.#r),s=Array.from(this.#i);this.#a.clear(),this.#r.clear(),this.#i.clear(),await Promise.allSettled([...e.map(i=>i.close()),...r.map(i=>i.close()),...s.map(i=>i.catch(()=>{}))]).then(()=>{});}#d(e){this.#a.delete(e),this.#r.delete(e);}};var w=class{#e;#s;#t;#n=1;#a=new je({heartbeat:new ge$1});#r=new ie;#i=new P({deriveServerState:Ra});constructor(e){this.#e=e.headers,this.#s=e.url;}async subscribe(e){let{change:r,entry:s}=this.#i.add(e,{matches:va(e)});return await this.#o(s,r),g(s.subscriber.queue,()=>this.#d(s))}async#o(e,r){try{(await this.#u()).reusedOpenSocket&&(this.#h(gs(r.before,r.after)),this.#f(vs(r.before,r.after)));}catch(s){throw await this.#d(e),s}}async#d(e){let{before:r,after:s}=this.#i.remove(e);this.#h(gs(r,s)),this.#f(vs(r,s)),this.#i.hasActiveSubscriptions()||await this.close();}async close(){this.#t===void 0&&(this.#t=this.#c().finally(()=>{this.#t=void 0;})),await this.#t;}async#c(){this.#r.stop(),this.#i.endAll(),await this.#a.close();}#u(){return this.#a.connect({onConnectionLost:()=>this.#m(),onError:()=>this.#y(),onMessage:e=>this.#l(e),onOpen:()=>this.#p(),headers:this.#e,url:this.#s})}#p(){this.#r.resetBackoff(),this.#h(Array.from(this.#i.serverState()));}#l(e){let r=PerpsMarketDataEventSchema.safeParse(e);r.success&&this.#i.dispatch(r.data);}#m(){this.#i.hasActiveSubscriptions()&&this.#S();}#y(){}#h(e){e.length!==0&&this.#a.send(this.#b("sub",e));}#f(e){e.length!==0&&this.#a.send(this.#b("unsub",e));}#b(e,r){return {id:this.#n++,req:e,chs:r}}#S(){this.#r.schedule({reconnect:()=>this.#u(),shouldReconnect:()=>this.#i.hasActiveSubscriptions()});}};function Ra(t){let e=new Set,r=new Set,s=new Set,i=false,o=false;for(let{subscription:n}of t)switch(n.topic){case "perps.tickers":n.instrumentId===void 0?i=true:r.add(n.instrumentId);break;case "perps.statistics":n.instrumentId===void 0?o=true:s.add(n.instrumentId);break;default:e.add(ga(n));}if(i)e.add("tickers::all");else for(let n of r)e.add(`tickers::${n}`);if(o)e.add("statistics::all");else for(let n of s)e.add(`statistics::${n}`);return e}function gs(t,e){return Array.from(e).filter(r=>!t.has(r))}function vs(t,e){return Array.from(t).filter(r=>!e.has(r))}function ga(t){switch(t.topic){case "perps.trades":return `trades::${t.instrumentId}`;case "perps.bbo":return `bbo::${t.instrumentId}`;case "perps.book":return `book::${t.instrumentId}`;case "perps.candles":return `klines::${t.instrumentId}::${t.interval}`;case "perps.tickers":return t.instrumentId===void 0?"tickers::all":`tickers::${t.instrumentId}`;case "perps.statistics":return t.instrumentId===void 0?"statistics::all":`statistics::${t.instrumentId}`;default:invariant(false,`Unknown Perps topic: ${String(t)}`);}}function va(t){switch(t.topic){case "perps.trades":return e=>e.topic==="perps.trades"&&e.channel===`trades::${t.instrumentId}`;case "perps.bbo":case "perps.book":return e=>e.topic===t.topic&&e.payload.instrumentId===t.instrumentId;case "perps.candles":return e=>e.topic==="perps.candles"&&e.payload.instrumentId===t.instrumentId&&e.payload.interval===t.interval;case "perps.tickers":case "perps.statistics":return e=>e.topic===t.topic&&(t.instrumentId===void 0||e.payload.instrumentId===t.instrumentId);default:invariant(false,`Unknown Perps topic: ${String(t)}`);}}function Cs(t){let e="symbol"in t?[t.symbol.toLowerCase()]:t.symbols,{provider:r}=t;return e.map(s=>t.topic==="prices.crypto.twap"||t.topic==="prices.equity.twap"?{key:JSON.stringify([t.topic,s,60,r]),topic:t.topic,symbol:s,windowSeconds:60,provider:r}:{key:JSON.stringify([t.topic,s,r]),topic:t.topic,symbol:s,provider:r})}function As(t,e){return Math.random()*(t===4003?1e4:Math.min(1e3*2**e,3e4))}var N=class{#e;#s=new ie;#t=new Map;#n=[];#a;#r;#i=false;#o=false;#d=false;#c=false;#u;#p=0;#l=64;#m=Number.NEGATIVE_INFINITY;constructor(e){this.#e=e;}get size(){return this.#t.size}has(e){return this.#t.has(e)}get closed(){return this.#o}get keyTarget(){return Date.now()-this.#m>=6e4?64:this.#l}add(e,r){clearTimeout(this.#r);let s=this.#t.get(e.key);if(s===void 0){let{promise:i,resolve:o,reject:n}=Promise.withResolvers();i.catch(()=>{}),s={subscription:e,listeners:new Set,ready:i,resolve:o,reject:n,subscribed:false,accepted:false},this.#t.set(e.key,s),this.#i&&this.#f("subscribe",[s]);}return s.listeners.add(r),s.confirmation!==void 0&&r.subscribed?.({...s.confirmation}),s.snapshot!==void 0&&r.event(s.snapshot),!this.#i&&!this.#c&&this.#u===void 0&&!this.#s.isScheduled&&this.#y(),Ca(s.ready)}remove(e,r){let s=this.#t.get(e);s!==void 0&&(s.listeners.delete(r),!(s.listeners.size>0)&&(this.#t.delete(e),s.reject(new d("Realtime subscription closed.")),this.#i&&this.#f("unsubscribe",[s]),this.#t.size===0&&(this.#r=setNonBlockingTimeout(()=>{this.close();},1e3))));}#y(){if(this.#o||this.#c)return Promise.resolve();if(this.#u!==void 0)return this.#u;let e=this.#h().catch(r=>{this.#C([...this.#t.values()].filter(s=>!s.accepted),d.fromError(r));}).finally(()=>{this.#u===e&&(this.#u=void 0),this.#i||this.#q(1006);});return this.#u=e,e}async#h(){let e=this.#p;if(await this.#e.open({subscribed:(r,s)=>this.#R(r,s),event:r=>this.#g(r),dropped:()=>this.#v(),disconnected:r=>this.#w(r)}),!(this.#o||e!==this.#p))try{if(await this.#e.authorize(),this.#o||e!==this.#p)return;this.#i=!0,this.#f("subscribe",[...this.#t.values()]);}catch(r){if(this.#o||e!==this.#p)return;r instanceof h&&r.code!==RealtimeKnownErrorCode.AuthUnavailable?this.#E(r):await this.#A(1006);}}#f(e,r){if(r.length===0)return;let s=this.#n.at(-1);s?.op===e?s.keys.push(...r):this.#n.push({op:e,keys:r}),this.#b();}#b(){this.#a!==void 0||this.#d||!this.#i||this.#o||(this.#a=setNonBlockingTimeout(()=>{this.#a=void 0,this.#S();},10));}async#S(){if(!this.#i||this.#o)return;let e=this.#n.shift();if(e===void 0)return;let r=[...new Set(e.keys)].filter(i=>e.op==="unsubscribe"||this.#t.get(i.subscription.key)===i);if(r.length===0){this.#b();return}let s=this.#p;this.#d=true;try{let i=await this.#e.change(e.op,r.map(({subscription:o})=>o));if(s!==this.#p||this.#o)return;if(e.op==="unsubscribe"&&i.length>0){let o=i[0];if(o!==void 0)throw o.error}if(e.op==="subscribe"){this.#s.resetBackoff();let o=new Set(i.map(n=>n.key));for(let n of r)o.has(n.subscription.key)||(n.subscribed=!0,n.accepted=!0,n.resolve());for(let{key:n,error:a}of i){let u=r.find(p=>p.subscription.key===n);u!==void 0&&this.#C([u],a,!1);}}}catch(i){if(s!==this.#p||this.#o)return;i instanceof h&&e.op==="subscribe"?this.#C(r,i):await this.#A(1006);}finally{this.#d=false,this.#b();}}#R(e,r){let s=this.#t.get(e.key);if(s?.subscription===e){s.confirmation={...r};for(let i of [...s.listeners])i.subscribed?.({...r});}}#g(e){for(let r of this.#t.values()){let s=r.subscription;if(s.topic!==e.topic)continue;let i=e.payload;if(i.symbol.toLowerCase()===s.symbol&&!((s.topic==="prices.crypto.twap"||s.topic==="prices.equity.twap")&&(!("windowSeconds"in i)||i.windowSeconds!==s.windowSeconds))){r.snapshot=Aa(r.snapshot,e);for(let o of r.listeners)o.event(e);}}}#v(){let e=Date.now();e-this.#m<5e3||(this.#l=Math.max(1,Math.floor(this.keyTarget/2)),this.#m=e);}#P(){this.#p++,this.#i=false,this.#n=[],clearTimeout(this.#a),this.#a=void 0;for(let e of this.#t.values()){if(e.snapshot=void 0,e.confirmation=void 0,!e.subscribed)continue;let{promise:r,resolve:s,reject:i}=Promise.withResolvers();r.catch(()=>{}),e.ready=r,e.resolve=s,e.reject=i,e.subscribed=false;}}#w(e){let r=new f("Realtime connection closed.",e);this.#P(),e.code===4001||e.code===4008?this.#E(r):this.#q(e.code);}async#A(e){this.#c=true,this.#P();try{await this.#e.close();}finally{this.#c=false,this.#q(e);}}#q(e){this.#s.schedule({delayPolicy:r=>As(e,r),shouldReconnect:()=>!this.#o&&this.#t.size>0,reconnect:()=>this.#y()});}#E(e){let r=[...this.#t.values()],s=new Set(r.flatMap(i=>[...i.listeners]));for(let i of r)i.reject(e);for(let i of s)i.end(e);this.close();}#C(e,r,s=true){let i=e.filter(n=>this.#t.get(n.subscription.key)===n),o=new Set(i.flatMap(n=>[...n.listeners]));for(let n of i)this.#t.delete(n.subscription.key),n.reject(r);s&&this.#i&&this.#f("unsubscribe",i);for(let n of o)n.end(r);this.#t.size===0&&(this.#r=setNonBlockingTimeout(()=>{this.close();},1e3));}async close(){if(this.#o)return;this.#o=true,this.#s.stop(),clearTimeout(this.#r);let e=new d("Realtime connection closed.");this.#P();for(let r of this.#t.values())r.reject(e);this.#t.clear(),await this.#e.close();}};function Ca(t){return new Promise((e,r)=>{let s=setNonBlockingTimeout(()=>{r(new d("Realtime subscription was not accepted within 30 seconds."));},3e4);t.then(()=>{clearTimeout(s),e();},i=>{clearTimeout(s),r(i);});})}function Aa(t,e){if(e.type==="subscribe")return e;let{symbol:r,source:s,timestamp:i,value:o}=e.payload,n=t?.type==="subscribe"&&t.payload.source===s?t.payload.data:[];if((n.at(-1)?.timestamp??0)>i)return t;let a=[...n.filter(u=>u.timestamp>i-12e4&&u.timestamp<i),{timestamp:i,value:o}];return e.topic==="prices.crypto.twap"||e.topic==="prices.equity.twap"?{...e,type:"subscribe",payload:{symbol:r,source:s,data:a,windowSeconds:e.payload.windowSeconds}}:{...e,type:"subscribe",payload:{symbol:r,source:s,data:a}}}var G=class{#e;#s=new je({heartbeat:new he,connectTimeoutMs:1e4,closeTimeoutMs:1e3});#t=new Map;#n;#a=0;#r=0;#i=0;constructor(e){this.#e=e;}async open(e){this.#n=e;let r=this.#i;await this.#s.connect({url:this.#e.url,headers:this.#e.headers,onOpen:()=>{},onError:()=>{},onConnectionLost:s=>{r===this.#i&&(this.#c(new f("Realtime connection closed.",s)),e.disconnected(s));},onMessage:s=>{r===this.#i&&this.#d(s);}});}async authorize(){let{key:e,secret:r,passphrase:s}=this.#e.credentials;await this.#o({op:"auth",auth:{apiKey:e,secret:r,passphrase:s}},PolyboltAckOp.Authed,[]);}async change(e,r){let s=[],i=0;for(;i<r.length;){let o=[];for(;i+o.length<r.length;){let a=r[i+o.length];if(a===void 0)break;let u=ka(a),p={op:e,subscriptions:[...o,u],rid:String(this.#a+1)};if(o.length>0&&new TextEncoder().encode(JSON.stringify(p)).length>6e4)break;o.push(u);}let n=await this.#o({op:e,subscriptions:o},e==="subscribe"?PolyboltAckOp.Subscribed:PolyboltAckOp.Unsubscribed,o.map(({channel:a})=>a),r.slice(i,i+o.length));for(let{index:a,error:u}of n){let p=r[i+a];p!==void 0&&s.push({key:p.key,error:u});}i+=o.length;}return s}#o(e,r,s,i=[]){let o=String(++this.#a);return new Promise((n,a)=>{let u={op:r,channels:[...s],subscriptions:i,rejections:[],resolve:n,reject:a};this.#t.set(o,u),u.sendTimer=setNonBlockingTimeout(()=>{u.timer=setNonBlockingTimeout(()=>{this.#t.delete(o),a(new d("Realtime acknowledgement timed out after 10 seconds."));},1e4),this.#r=Date.now();try{if(!this.#s.send({...e,rid:o}))throw new d("Realtime connection is not open.")}catch(p){clearTimeout(u.timer),this.#t.delete(o),a(d.fromError(p));}},Math.max(0,110-(Date.now()-this.#r)));})}#d(e){let r=PolyboltAckSchema.safeParse(e);if(r.success){let{op:o,rid:n,code:a,channel:u,provider:p}=r.data,c=n===void 0?void 0:this.#t.get(n);if(c===void 0)return;if(o===PolyboltAckOp.Error&&a!==void 0){let b=new h(`Realtime subscription rejected: ${a}`,{status:200,code:a}),y=c.channels.flatMap((m,C)=>m===u?[C]:[]);if(u===void 0||y.length!==1)c.reject(b);else {let m=y[0];if(m===void 0||(c.channels[m]=void 0,c.rejections.push({index:m,error:b}),c.channels.some(C=>C!==void 0)))return;c.resolve(c.rejections);}}else if(o===c.op){if(c.channels.length>0){let b=c.channels.findIndex(m=>m!==void 0);if(b<0||c.channels[b]!==u)return;c.channels[b]=void 0;let y=c.subscriptions[b];if(o===PolyboltAckOp.Subscribed&&y!==void 0&&this.#n?.subscribed(y,{symbol:y.symbol,provider:p}),c.channels.some(m=>m!==void 0))return}c.resolve(c.rejections);}else return;clearTimeout(c.timer),n!==void 0&&this.#t.delete(n);return}let s=PolyboltEnvelopeSchema.safeParse(e);if(!s.success)return;let i=parsePolyboltEvent(s.data);i!==void 0&&this.#n?.event(i),(s.data.dropped??0)>0&&this.#n?.dropped();}#c(e){for(let r of this.#t.values())clearTimeout(r.sendTimer),clearTimeout(r.timer),r.reject(e);this.#t.clear();}async close(){this.#i++,this.#n=void 0,this.#c(new d("Realtime connection closed.")),await this.#s.close();}};function ka(t){switch(t.topic){case "prices.crypto":return {channel:PolyboltChannel.Crypto,filter:{symbol:t.symbol,provider:t.provider}};case "prices.crypto.twap":return {channel:PolyboltChannel.Twap,filter:{symbol:t.symbol,window_seconds:t.windowSeconds,provider:t.provider}};case "prices.equity":return {channel:PolyboltChannel.Equity,filter:{symbol:t.symbol,provider:t.provider}};case "prices.equity.twap":return {channel:PolyboltChannel.EquityTwap,filter:{symbol:t.symbol,window_seconds:t.windowSeconds,provider:t.provider}}}}var Y=class{#e;#s=new Map;#t=new Set;constructor(e){this.#e=e;}async subscribe(e){let r=[...new Map(Cs(e).map(p=>[p.key,p])).values()],s=pushable({objectMode:true}),i=[],o=false,n,a=async()=>{if(!o){o=true;for(let p of i)p();n===void 0?await s.return():s.end(n),this.#t.delete(a);}};this.#t.add(a);let u=p=>{o||(n=d.fromError(p),s.end(n),a());};try{let p=r.map(c=>{if(o)return Promise.resolve();let b=this.#n(c.key,c.provider),y={subscribed(m){if(!(o||!("onSubscribed"in e)))try{Promise.resolve(e.onSubscribed?.(m)).catch(u);}catch(C){u(C);}},event(m){if(o||"types"in e&&e.types!==void 0&&e.types.length>0&&!e.types.includes(m.type))return;let C="symbol"in m.payload?{...m.payload,symbol:"symbol"in c?c.symbol:m.payload.symbol}:m.payload;s.push({...m,payload:C});},end(m){n=m,s.end(m),a();}};return i.push(()=>b.remove(c.key,y)),b.add(c,y)});for(let c of p)c.catch(()=>{});if(await Promise.all(p),n!==void 0)throw n}catch(p){throw await a(),n??p}return {close:a,async*[Symbol.asyncIterator](){try{yield*s;}finally{await a();}}}}#n(e,r){for(let i of this.#s.keys())if(i.closed)this.#s.delete(i);else if(i.has(e))return i;for(let[i,o]of this.#s)if(o===r&&i.size<i.keyTarget)return i;let s=new N(new G(this.#e));return this.#s.set(s,r),s}async close(){await Promise.all([...this.#t].map(r=>r()));let e=[...this.#s.keys()];this.#s.clear(),await Promise.all(e.map(r=>r.close()));}};var W=class{#e;constructor(e){this.#e=new Y(e);}async subscribe(e){return this.#e.subscribe(e)}async close(){await this.#e.close();}};function Ts(t,e){return {...e,quote:r=>t.quote(e,r)}}function ks(t,e){let r=e.rfqId,s=e.quoteId;return {...e,confirm:()=>t.respondToConfirmation(r,s,RfqConfirmationDecision.Confirm),decline:()=>t.respondToConfirmation(r,s,RfqConfirmationDecision.Decline)}}function xs(t){return {quoteId:t.quoteId,rfqId:t.rfqId}}function Fs(t){return {quoteId:t.quoteId,rfqId:t.rfqId}}function Ms(t){return {quoteId:t.quoteId,rfqId:t.rfqId}}function Os(t,e){let r=M$1(t);return {auth:{apiKey:e.key,passphrase:e.passphrase,secret:e.secret},identity:{maker_address:r.maker,signature_type:r.signatureType,signer_address:r.signer},type:"auth"}}function Is(t,e){return {price_e6:e.price.toString(),rfq_id:t.rfqId,signed_order:e.signedOrder,size_e6:e.size.toString(),type:"RFQ_QUOTE"}}function Ls(t,e,r){let s=M$1(t);return {maker_address:s.maker,quote_id:r,rfq_id:e,signer_address:s.signer,type:"RFQ_QUOTE_CANCEL"}}function Bs(t,e,r){return {decision:r,quote_id:e,rfq_id:t,type:"RFQ_CONFIRMATION_RESPONSE"}}var J=class{#e=new Map;#s;constructor(e){this.#s=e;}waitFor(e,r){let s=Ma(),i,o=setNonBlockingTimeout(()=>{this.remove(e,i),s.reject(new j(r));},this.#s);i=s.promise.finally(()=>clearTimeout(o));let n=this.#e.get(e)??[];return n.push({...s,promise:i}),this.#e.set(e,n),i}resolve(e,r){let s=this.#e.get(e),i=s?.shift();i!==void 0&&(s!==void 0&&s.length===0&&this.#e.delete(e),i.resolve(r));}reject(e,r){let s=this.#e.get(e),i=s?.shift();i!==void 0&&(s!==void 0&&s.length===0&&this.#e.delete(e),i.reject(r));}remove(e,r){let s=this.#e.get(e);if(s===void 0)return;let i=s.filter(o=>o.promise!==r);i.length===0?this.#e.delete(e):this.#e.set(e,i);}rejectAll(e){for(let r of this.#e.values())for(let s of r)s.reject(e);this.#e.clear();}};function Ma(){let t,e;return {promise:new Promise((s,i)=>{t=s,e=i;}),reject:e,resolve:t}}var Ds="0x0000000000000000000000000000000000000000000000000000000000000000";async function Ws(t){let e=M$1(t.account),r=Cd({chainId:t.chainId,exchange:t.exchange}),s={builder:Ds,maker:e.maker,makerAmount:toBaseUnits(Dd(t.orderSide,t.orderPrice,t.size)),metadata:Ds,salt:Oa().toString(),side:Fd(t.orderSide),signatureType:e.signatureType,signer:e.signer,takerAmount:toBaseUnits(Ed$1(t.orderSide,t.orderPrice,t.size)),timestamp:Math.floor(Date.now()/1e3).toString(),tokenId:t.tokenId},i;try{i=await t.signer.signTypedData(Ad({domain:r,order:s}));}catch(o){throw q.fromError(o,"Could not sign the RFQ quote order.")}return {...s,signature:Bd({domain:r,order:s,signature:i})}}function Oa(){let t=new Uint8Array(8);return globalThis.crypto.getRandomValues(t),BigInt(`0x${Array.from(t,e=>e.toString(16).padStart(2,"0")).join("")}`)}var Hs=DecimalishSchema.transform(t=>zs(t)).refine(t=>t<=BigInt(Number.MAX_SAFE_INTEGER),{message:"Value exceeds the temporary numeric wire limit."}),Ba=z$1.strictObject({price:Hs.refine(t=>t<1000000n,{message:"Price must be less than 1."}),size:Hs.optional(),source:z$1.enum(["collateral","inventory"]).default("collateral")});function _s(t){return I$1(t,Ba)}async function js(t){let e=t.response.price,r=t.response.size===void 0?Ka(t.request.requestedSize,e):t.response.size,s=await Ws({account:t.account,chainId:t.chainId,exchange:t.exchange,orderPrice:Da(t.request,t.response.source,e),orderSide:Wa(t.response.source),signer:t.signer,size:r,tokenId:Ua(t.request,t.response.source)});return {price:e,signedOrder:s,size:r}}function Ua(t,e){return t.direction===RfqDirection.Buy?e==="collateral"?t.noPositionId:t.yesPositionId:e==="collateral"?t.yesPositionId:t.noPositionId}function Da(t,e,r){return t.direction===RfqDirection.Buy&&e==="collateral"||t.direction===RfqDirection.Sell&&e==="inventory"?1000000n-r:r}function Wa(t){return t==="collateral"?OrderSide.BUY:OrderSide.SELL}function Ka(t,e){let r=zs(t.value);return t.unit===RfqRequestedSizeUnit.Shares?r:r*1000000n/e}function zs(t){let e=/^(\d+)(?:\.(\d*))?$/.exec(t);if(e===null)throw new a("Value must be a valid decimal.");let[,r="",s=""]=e;if(s.length>6)throw new a("Value must have at most 6 decimal places.");let i=BigInt(r)*1000000n+BigInt(s.padEnd(6,"0"));if(i<=0n)throw new a("Value must be greater than 0.");return i}var ja=3e4,za=3e4,M=class{#e;#s;#t;#n;#a;#r;#i;#o;#d;#c;#u=false;constructor(e){this.#e=e.account,this.#s=e.chainId,this.#t=e.credentials,this.#n=e.exchange,this.#a=e.headers,this.#r=e.signer,this.#i=e.url;}async connect(){if(this.#u)throw new d("RFQ quoter manager has been shut down.");if(this.#o!==void 0){if(!this.#o.closed)return this.#o;this.#o=void 0;}if(this.#c!==void 0)return this.#c;let e=new Ue({account:this.#e,chainId:this.#s,credentials:this.#t,exchange:this.#n,headers:this.#a,onClose:()=>this.#p(e),signer:this.#r,url:this.#i});this.#d=e;let r;return r=(async()=>{try{if(await e.connect(),this.#u)throw await e.close(),new d("RFQ quoter manager has been shut down.");return this.#o=e,e}catch(s){throw await e.close(),s}finally{this.#c===r&&(this.#c=void 0),this.#d===e&&(this.#d=void 0);}})(),this.#c=r,r}async shutdown(){this.#u=true;let e=this.#o,r=this.#d,s=this.#c;this.#o=void 0,this.#d=void 0,this.#c=void 0,await Promise.allSettled([e?.close(),r?.close(),s?.catch(()=>{})]).then(()=>{});}#p(e){this.#o===e&&(this.#o=void 0),this.#d===e&&(this.#d=void 0);}},Ue=class{#e;#s;#t;#n;#a;#r;#i;#o;#d=new je;#c=pushable({objectMode:true});#u=new J(za);#p;#l;constructor(e){this.#e=e.account,this.#s=e.chainId,this.#t=e.credentials,this.#n=e.exchange,this.#a=e.headers,this.#r=e.onClose,this.#i=e.signer,this.#o=e.url;}get closed(){return this.#p!==void 0}async connect(){let e=Va();this.#l=e;let r=setNonBlockingTimeout(()=>{e.reject(new d("RFQ quoter authentication timed out."));},ja);try{await this.#d.connect({headers:this.#a,onConnectionLost:s=>this.#v(s),onError:()=>{},onMessage:s=>this.#R(s),onOpen:()=>this.#S(),url:this.#o}),await e.promise;}finally{clearTimeout(r),this.#l=void 0;}}async#m(e){if(!this.#d.send(e))throw new d("RFQ quoter websocket is not open.")}async close(){this.#p===void 0&&(this.#p=this.#y()),await this.#p;}[Symbol.asyncIterator](){return this.#c[Symbol.asyncIterator]()}async#y(){let e=new d("RFQ quoter websocket closed.");this.#b(e),this.#c.end(),await this.#d.close(),this.#r();}async#h(e){this.#p===void 0&&(this.#p=this.#f(e)),await this.#p;}async#f(e){this.#b(e),this.#c.end(e),await this.#d.close(),this.#r();}#b(e){this.#l?.reject(e),this.#u.rejectAll(e);}#S(){this.#d.send(Os(this.#e,this.#t));}#R(e){if(this.#p!==void 0)return;let r=RfqQuoterInboundMessageSchema.safeParse(e);if(!r.success)return;let s=r.data;switch(s.type){case "auth":this.#g(s);return;case "quote_request":this.#c.push(Ts(this,s));return;case "quote_ack":this.#u.resolve(Z(s.rfqId),xs(s));return;case "quote_cancel_ack":this.#u.resolve(Le(s.rfqId,s.quoteId),Fs(s));return;case "confirmation_request":this.#c.push(ks(this,s));return;case "confirmation_ack":this.#u.resolve(Be(s.rfqId,s.quoteId),Ms(s));return;case "execution_update":this.#c.push(s);return;case "trade":this.#c.push(s);return;case "rfq_error":this.#P(s);return}}#g(e){if(e.success===true){this.#l?.resolve(void 0);return}this.#l?.reject(new d(`RFQ quoter authentication failed: ${e.error}`));}#v(e){this.#h(new f("RFQ quoter connection lost.",e));}#P(e){if(e.requestType==="RFQ_QUOTE"){if(e.rfqId===void 0){this.#h(new d("Uncorrelated RFQ quoter error."));return}this.#u.reject(Z(e.rfqId),new gg(e.message,{code:e.code,errorId:e.errorId,rfqId:e.rfqId}));return}if(e.requestType==="RFQ_QUOTE_CANCEL"){if(e.rfqId===void 0||e.quoteId===void 0){this.#h(new d("Uncorrelated RFQ quoter error."));return}this.#u.reject(Le(e.rfqId,e.quoteId),new ig(e.message,{code:e.code,errorId:e.errorId,quoteId:e.quoteId,rfqId:e.rfqId}));return}if(e.requestType==="RFQ_CONFIRMATION_RESPONSE"){if(e.rfqId===void 0||e.quoteId===void 0){this.#h(new d("Uncorrelated RFQ quoter error."));return}this.#u.reject(Be(e.rfqId,e.quoteId),new kg(e.message,{code:e.code,errorId:e.errorId,quoteId:e.quoteId,rfqId:e.rfqId}));}}async quote(e,r){let s=_s(r),i=await js({account:this.#e,chainId:this.#s,exchange:this.#n,request:e,response:s,signer:this.#i}),o=this.#u.waitFor(Z(e.rfqId),`Timed out waiting for RFQ quote acknowledgement for ${e.rfqId}.`);try{return await this.#m(Is(e,i)),await o}catch(n){throw this.#u.remove(Z(e.rfqId),o),n}}async cancelQuote(e){let r=Le(e.rfqId,e.quoteId),s=this.#u.waitFor(r,`Timed out waiting for RFQ quote cancellation acknowledgement for ${e.rfqId}.`);try{return await this.#m(Ls(this.#e,e.rfqId,e.quoteId)),await s}catch(i){throw this.#u.remove(r,s),i}}async respondToConfirmation(e,r,s){let i=Be(e,r),o=this.#u.waitFor(i,`Timed out waiting for RFQ confirmation acknowledgement for ${e}.`);try{return await this.#m(Bs(e,r,s)),await o}catch(n){throw this.#u.remove(i,o),n}}};function Z(t){return `ACK_RFQ_QUOTE:${t}`}function Le(t,e){return `ACK_RFQ_QUOTE_CANCEL:${t}:${e}`}function Be(t,e){return `ACK_RFQ_CONFIRMATION_RESPONSE:${t}:${e}`}function Va(){let t,e;return {promise:new Promise((s,i)=>{t=s,e=i;}),reject:e,resolve:t}}var O=class{#e;#s;#t;#n=new je({heartbeat:new ee$1});#a=new ie;#r=new P({deriveServerState:Ya});constructor(e){this.#e=e.headers,this.#s=e.url;}async subscribe(e){let{change:r,entry:s}=this.#r.add(e,{matches:tc(e)});return await this.#i(s,r),g(s.subscriber.queue,()=>this.#o(s))}async#i(e,r){try{if((await this.#c()).reusedOpenSocket){let{before:i,after:o}=r,n=$a(i,o);this.#h(n);}}catch(s){throw await this.#o(e),s}}async#o(e){let{before:r,after:s}=this.#r.remove(e),i=Ga(r,s);this.#f(i),this.#r.hasActiveSubscriptions()||await this.close();}async close(){this.#t===void 0&&(this.#t=this.#d().finally(()=>{this.#t=void 0;})),await this.#t;}async#d(){this.#a.stop(),this.#r.endAll(),await this.#n.close();}#c(){return this.#n.connect({onConnectionLost:()=>this.#l(),onError:()=>this.#m(),onMessage:e=>this.#p(e),onOpen:()=>this.#u(),headers:this.#e,url:this.#s})}#u(){this.#a.resetBackoff(),this.#y();}#p(e){let r=RealtimeEventSchema.safeParse(e);r.success&&this.#r.dispatch(r.data);}#l(){this.#r.hasActiveSubscriptions()&&this.#b();}#m(){}#y(){this.#h(Array.from(this.#r.serverState().values()));}#h(e){e.length!==0&&this.#n.send(Ja(e));}#f(e){e.length!==0&&this.#n.send(Za(e));}#b(){this.#a.schedule({reconnect:()=>this.#c(),shouldReconnect:()=>this.#r.hasActiveSubscriptions()});}};function $a(t,e){return Array.from(e).flatMap(([r,s])=>t.has(r)?[]:[s])}function Ga(t,e){return Array.from(t).flatMap(([r,s])=>e.has(r)?[]:[s])}function Ya(t){let e=new Map;for(let{subscription:r}of t)for(let s of Xa(r))e.has(s.key)||e.set(s.key,s);return e}function Ja(t){return {action:"subscribe",subscriptions:t.map(({topic:e,type:r})=>({topic:e,type:r}))}}function Za(t){return {action:"unsubscribe",subscriptions:t.map(({topic:e,type:r})=>({topic:e,type:r}))}}function Xa(t){switch(t.topic){case "comments":return (t.types??["comment_created"]).map(e=>K("comments",e));case "prices.crypto.binance":return [K("crypto_prices","update")];case "prices.crypto.chainlink":return [K("crypto_prices_chainlink","update")];case "prices.crypto.chainlink.twap":return [K(ec(t.windowSeconds),"update")];case "prices.equity.pyth":return [K("equity_prices","update")];default:invariant(false,`Unknown RTDS topic: ${String(t)}`);}}function ec(t){switch(t){case 30:return "crypto_prices_twap_thirty";case 60:return "crypto_prices_twap_sixty";default:invariant(false,`Unknown TWAP window: ${String(t)}`);}}function K(t,e){return {key:`${t}:${e}`,topic:t,type:e}}function tc(t){switch(t.topic){case "comments":return e=>!(e.topic!=="comments"||t.types!==void 0&&t.types.length>0&&!t.types.includes(e.type)||(t.parentEntityId!==void 0||t.parentEntityType!==void 0)&&(!(e.type==="comment_created"||e.type==="comment_removed")||t.parentEntityId!==void 0&&e.payload.parentEntityID!==t.parentEntityId||t.parentEntityType!==void 0&&e.payload.parentEntityType!==t.parentEntityType));case "prices.crypto.binance":return e=>e.topic==="prices.crypto.binance"&&(t.symbols===void 0||t.symbols.length===0||t.symbols.includes(e.payload.symbol));case "prices.crypto.chainlink":return e=>e.topic==="prices.crypto.chainlink"&&(t.symbols===void 0||t.symbols.length===0||t.symbols.includes(e.payload.symbol));case "prices.crypto.chainlink.twap":return e=>e.topic==="prices.crypto.chainlink.twap"&&e.payload.windowSeconds===t.windowSeconds&&(t.symbols===void 0||t.symbols.length===0||t.symbols.includes(e.payload.symbol));case "prices.equity.pyth":return e=>e.topic==="prices.equity.pyth"&&e.payload.symbol.toLowerCase()===t.symbol.toLowerCase()&&(t.types===void 0||t.types.length===0||t.types.includes(e.type));default:invariant(false,`Unknown RTDS topic: ${String(t)}`);}}var I=class{#e;#s;#t;#n=new je({heartbeat:new fe});#a=new ie;#r=new P;constructor(e){this.#e=e.headers,this.#s=e.url;}async subscribe(e){let{entry:r}=this.#r.add(e);return await this.#i(r),g(r.subscriber.queue,()=>this.#o(r))}async#i(e){try{await this.#c();}catch(r){throw await this.#o(e),r}}async#o(e){this.#r.remove(e),this.#r.hasActiveSubscriptions()||await this.close();}async close(){this.#t===void 0&&(this.#t=this.#d().finally(()=>{this.#t=void 0;})),await this.#t;}async#d(){this.#a.stop(),this.#r.endAll(),await this.#n.close();}#c(){return this.#n.connect({onConnectionLost:()=>this.#l(),onError:()=>this.#m(),onMessage:e=>this.#p(e),onOpen:()=>this.#u(),headers:this.#e,url:this.#s})}#u(){this.#a.resetBackoff();}#p(e){let r=SportsResultEventSchema.safeParse(e);r.success&&this.#r.dispatch(r.data);}#l(){this.#r.hasActiveSubscriptions()&&this.#y();}#m(){}#y(){this.#a.schedule({reconnect:()=>this.#c(),shouldReconnect:()=>this.#r.hasActiveSubscriptions()});}};var X=class{#e;#s;get context(){return this.#e}get decorators(){return this.#s}get environment(){return this.context.environment}get clob(){return this.context.clob}get relayer(){return this.context.relayer}get rpc(){return this.context.rpc}get gamma(){return this.context.gamma}get data(){return this.context.data}get rfq(){return this.context.rfq}get perps(){return this.context.perps}get webSockets(){return this.context.webSockets}get supportsGasless(){return this.context.apiKey?.supportGasless??false}get hasBuilderApiKey(){return this.context.apiKey?.isBuilderKey??false}constructor(e){this.#e=e,this.#s=[];}async resolveClobHeaders(e){return this.context.apiKey?.isBuilderKey?this.context.apiKey.authorize(e):Promise.resolve({})}async resolveRelayerHeaders(e){return this.context.apiKey?.supportGasless?this.context.apiKey.authorize(e):Promise.resolve({})}rememberDecorator(e){this.#s.push(e);}},cc=z$1.object({key:ApiKeySchema,passphrase:z$1.string(),secret:z$1.string()}),uc=z$1.object({wallet:EvmAddressSchema,credentials:cc.optional(),nonce:z$1.number().int().nonnegative().optional()}).superRefine((t,e)=>{t.credentials!==void 0&&t.nonce!==void 0&&e.addIssue({code:"custom",message:"`credentials` and `nonce` are mutually exclusive.",path:["nonce"]});}).transform(t=>t.credentials!==void 0?{wallet:t.wallet,credentials:t.credentials}:t.nonce!==void 0?{wallet:t.wallet,nonce:t.nonce}:{wallet:t.wallet}),ee=class extends X{constructor(e){super({apiKey:e.apiKey,environment:e.environment,onRateLimitUpdate:e.onRateLimitUpdate,data:new ce({headers:e.environment.data.headers,root:e.environment.data.rest}),gamma:new ce({headers:e.environment.gamma.headers,root:e.environment.gamma.rest}),clob:new ce({headers:e.environment.clob.headers,onRateLimitUpdate:e.onRateLimitUpdate,root:e.environment.clob.rest,resolveHeaders:r=>this.resolveClobHeaders(r)}),relayer:new ce({headers:e.environment.relayer.headers,root:e.environment.relayer.rest,resolveHeaders:r=>this.resolveRelayerHeaders(r)}),rfq:new ce({headers:e.environment.combos.headers,root:e.environment.combos.rest}),perps:new ce({headers:e.environment.perps.headers,root:e.environment.perps.rest}),rpc:new J$1({url:e.environment.rpc}),webSockets:{clobMarket:new E({headers:e.environment.clob.market.headers,url:e.environment.clob.market.ws}),sports:new I({headers:e.environment.sports.headers,url:e.environment.sports.ws}),rtds:new O({headers:e.environment.rtds.headers,url:e.environment.rtds.ws}),perpsSubscriptions:new w({headers:e.environment.perps.headers,url:e.environment.perps.ws})}});}isSecureClient(){return false}isPublicClient(){return true}async closeSubscriptions(){await Promise.all([this.webSockets.clobMarket.close(),this.webSockets.rtds.close(),this.webSockets.sports.close(),this.webSockets.perpsSubscriptions.close()]).then(()=>{});}extend(e){return this.rememberDecorator(e),Object.assign(this,e(this)),this}beginAuthentication(e,r){let s=I$1(e,uc);return Promise.resolve(async function*(){let i=Math.floor(Date.now()/1e3),o=s?.nonce??0,n=expectEvmAddress(yield Ca$1()),a=expectEvmAddress(s.wallet),u=L(this.environment,n,a);if(s.credentials!==void 0){let b=this.#e(s.credentials,u,r);try{if((await ob(b)).includes(s.credentials.key))return b}catch(y){if(!(y instanceof h)||y.status!==401)throw y}}let p=yield {kind:"signAuthMessage",payload:is({address:n,chainId:this.environment.chainId,nonce:o,timestamp:i})},c=await mb(this,{address:n,nonce:o,signature:expectEvmSignature(p),timestamp:i});return this.#e(c,u,r)}.call(this))}#e(e,r,s){let i=new Qe({account:r,apiKey:this.context.apiKey,credentials:e,environment:this.environment,onRateLimitUpdate:this.context.onRateLimitUpdate,signer:s});for(let o of this.decorators)i.extend(o);return i}},Qe=class extends X{#e=false;get context(){return invariant(!this.#e,"This client has ended authentication and can no longer be used."),super.context}endAuthenticationLifecycle(){this.#e=true;}constructor(e){let r=new W({url:e.environment.realtime.ws,headers:e.environment.realtime.headers,credentials:e.credentials});super({account:e.account,credentials:e.credentials,apiKey:e.apiKey,environment:e.environment,onRateLimitUpdate:e.onRateLimitUpdate,signer:e.signer,clob:new ce({headers:e.environment.clob.headers,onRateLimitUpdate:e.onRateLimitUpdate,root:e.environment.clob.rest,resolveHeaders:s=>this.resolveClobHeaders(s)}),relayer:new ce({headers:e.environment.relayer.headers,root:e.environment.relayer.rest,resolveHeaders:s=>this.resolveRelayerHeaders(s)}),rpc:new J$1({url:e.environment.rpc}),gamma:new ce({headers:e.environment.gamma.headers,root:e.environment.gamma.rest}),data:new ce({headers:e.environment.data.headers,root:e.environment.data.rest}),rfq:new ce({headers:e.environment.combos.headers,root:e.environment.combos.rest}),perps:new ce({headers:e.environment.perps.headers,root:e.environment.perps.rest}),secureClob:new ce({headers:e.environment.clob.headers,onRateLimitUpdate:e.onRateLimitUpdate,resolveHeaders:async s=>({...await this.resolveClobHeaders(s),...await this.#t(s)}),root:e.environment.clob.rest}),combos:new ce({headers:e.environment.combos.collateralReturn.headers,resolveHeaders:s=>this.resolveRelayerHeaders(s),root:e.environment.combos.collateralReturn.rest}),builderGateway:new ce({headers:e.environment.combos.builderGateway.headers,resolveHeaders:async s=>({...await this.#s(s),...await this.#t(s)}),root:e.environment.combos.builderGateway.rest}),webSockets:{clobMarket:new E({headers:e.environment.clob.market.headers,url:e.environment.clob.market.ws}),clobUser:new x({credentials:e.credentials,headers:e.environment.clob.user.headers,url:e.environment.clob.user.ws}),rfqQuoter:new M({account:e.account,chainId:e.environment.chainId,credentials:e.credentials,exchange:e.environment.contracts.exchangeV3,headers:e.environment.combos.headers,signer:e.signer,url:e.environment.combos.ws}),sports:new I({headers:e.environment.sports.headers,url:e.environment.sports.ws}),realtime:r,rtds:new O({headers:e.environment.rtds.headers,url:e.environment.rtds.ws}),perpsSubscriptions:new w({headers:e.environment.perps.headers,url:e.environment.perps.ws}),perpsSession:new F({chainId:e.environment.chainId,headers:e.environment.perps.headers,restUrl:e.environment.perps.rest,wsUrl:e.environment.perps.ws})}});}get credentials(){return this.context.credentials}get account(){return this.context.account}get signer(){return this.context.signer}get secureClob(){return this.context.secureClob}get combos(){return this.context.combos}get builderGateway(){return this.context.builderGateway}get webSockets(){return this.context.webSockets}async closeSubscriptions(){await Promise.allSettled([this.webSockets.clobMarket.close(),this.webSockets.realtime.close(),this.webSockets.rtds.close(),this.webSockets.sports.close(),this.webSockets.perpsSubscriptions.close(),this.webSockets.clobUser.close()]).then(()=>{});}isSecureClient(){return true}isPublicClient(){return false}extend(e){return this.rememberDecorator(e),Object.assign(this,e(this)),this}async endAuthentication(){let e=this.closeSubscriptions(),r=this.webSockets.perpsSession.shutdown(),s=this.webSockets.rfqQuoter.shutdown(),{apiKey:i,environment:o,onRateLimitUpdate:n}=this.context;try{await qb(this);}finally{this.endAuthenticationLifecycle(),await Promise.allSettled([e,r,s]).then(()=>{});}let a=new ee({apiKey:i,environment:o,onRateLimitUpdate:n});for(let u of this.decorators)a.extend(u);return a}async#s(e){return e.method!=="GET"&&this.context.apiKey?.isBuilderKey?this.context.apiKey.authorize(e):{}}async#t(e){try{let r=Math.floor(Date.now()/1e3);return {POLY_ADDRESS:this.account.signer,POLY_API_KEY:this.credentials.key,POLY_PASSPHRASE:this.credentials.passphrase,POLY_SIGNATURE:await ds(this.credentials.secret,r,e.method,e.path,e.body),POLY_TIMESTAMP:`${r}`}}catch(r){throw q.fromError(r,"Could not sign the L2-authenticated request")}}};function Vs(t={}){return new ee({environment:t.environment??xe,apiKey:t.apiKey,onRateLimitUpdate:t.onRateLimitUpdate}).extend(cs)}var dc=r(m,i,h,q,j,l,d,c,a),pc=r(a);async function lc(t){let e=Vs({environment:t.environment,apiKey:t.apiKey,onRateLimitUpdate:t.onRateLimitUpdate}),r=await mc(e,t),s=await e.beginAuthentication({wallet:r,credentials:t.credentials,nonce:t.nonce},t.signer).then(Ba$1(t.signer));if(s.account.walletType===WalletType.EOA||await Ga$1(s,{wallet:s.account.wallet,type:s.account.walletType}))return s;if(s.account.walletType===WalletType.DEPOSIT_WALLET)return await hc(s),s;throw new a(`Wallet ${s.account.wallet} does not exist. Provide an existing wallet address, or omit wallet to use the default Deposit Wallet flow.`)}async function mc(t,e){if(e.wallet!==void 0)return e.wallet;let r=expectEvmAddress(await e.signer.getAddress()),s=N$1(r,t.environment.walletDerivation);return await Ga$1(t,{wallet:s,type:WalletType.DEPOSIT_WALLET})?s:O$1(r,t.environment.walletDerivation)}async function hc(t){let e=O$1(t.account.signer,t.environment.walletDerivation);if(!isSameEvmAddress(t.account.wallet,e))throw new a(`Wallet ${t.account.wallet} does not match the expected Deposit Wallet ${e} for this signer, nor a deployed wallet address.`);await(await Ja$1(t)).wait();}
|
|
2
|
+
export{dc as CreateSecureClientError,pc as SetupGaslessWalletError,ve as accountActions,cs as allActions,qe as analyticsActions,ds as buildHmacSignature,Vs as createPublicClient,lc as createSecureClient,Ce as dataActions,Ae as discoveryActions,pa as forkEnvironmentConfig,Ee as perpsActions,Ed as preproduction,xe as production,na as relayerApiKey,oa as remoteBuilderSigning,we as rewardsActions,os as rfqActions,ns as sessionKeyActions,Te as subscriptionsActions,as as tradingActions,ke as walletActions};//# sourceMappingURL=index.js.map
|
|
3
3
|
//# sourceMappingURL=index.js.map
|