@polymarket/client 0.9.0 → 0.10.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/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/authorization.ts","../src/authentication.ts","../src/decorators/account.ts","../src/decorators/analytics.ts","../src/decorators/data.ts","../src/decorators/discovery.ts","../src/decorators/perps.ts","../src/decorators/rewards.ts","../src/decorators/rfq.ts","../src/decorators/session-keys.ts","../src/decorators/subscriptions.ts","../src/decorators/trading.ts","../src/decorators/wallet.ts","../src/decorators/index.ts","../src/environments.ts","../src/hmac.ts","../src/websockets/handle.ts","../src/websockets/registry.ts","../src/websockets/clob/protocol.ts","../src/websockets/clob/market.ts","../src/websockets/clob/user.ts","../src/websockets/perps/manager.ts","../src/websockets/perps/subscription.ts","../src/websockets/rfq/events.ts","../src/websockets/rfq/messages.ts","../src/websockets/rfq/pending.ts","../src/websockets/rfq/signing.ts","../src/websockets/rfq/quote.ts","../src/websockets/rfq/quoter.ts","../src/websockets/rtds.ts","../src/websockets/sports.ts","../src/clients.ts"],"names":["RemoteBuilderSigningResponseSchema","z","remoteBuilderSigning","config","RemoteBuilderAuthorization","relayerApiKey","RelayerApiKeyAuthorization","#config","request","#fetchBuilderKeyHeaders","error","SigningError","#resolveHeaders","headers","resolvedHeaders","requestHeaders","response","createApiKeyAuthTypedDataPayload","publicAccountActions","client","listPositions","listClosedPositions","listComboPositions","fetchPortfolioValue","fetchTradedMarketCount","downloadAccountingSnapshot","listMarketPositions","listActivity","listComboActivity","withAccountWallet","accountActions","actions","listAccountTrades","fetchNotifications","dropNotifications","fetchClosedOnlyMode","analyticsActions","listBuilderTrades","listBuilderLeaderboard","fetchBuilderVolume","listTraderLeaderboard","dataActions","fetchEventLiveVolume","fetchMidpoint","fetchMidpoints","fetchPrice","fetchPrices","fetchOrderBook","fetchOrderBooks","fetchSpread","fetchSpreads","fetchLastTradePrice","fetchLastTradePrices","fetchPriceHistory","estimateMarketPrice","listOpenInterest","listMarketHolders","listTrades","discoveryActions","listEvents","fetchEvent","fetchEventTags","listMarkets","listComboMarkets","fetchMarket","fetchMarketTags","listSeries","fetchSeries","listMarketClarifications","listTags","fetchTag","fetchRelatedTags","fetchRelatedTagResources","search","listSports","fetchSportsMarketTypes","listTeams","fetchPublicProfile","listComments","fetchCommentsById","listCommentsByUserAddress","perpsActions","fetchPerpsBook","fetchPerpsFees","fetchPerpsInstruments","fetchPerpsTicker","fetchPerpsTickers","listPerpsCandles","listPerpsFundingHistory","listPerpsTrades","depositToPerps","openPerpsSession","revokePerpsCredentials","withdrawFromPerps","publicRewardsActions","listCurrentRewards","listMarketRewards","rewardsActions","fetchOrderScoring","fetchOrdersScoring","listUserEarningsForDay","fetchTotalEarningsForUserForDay","listUserEarningsAndMarketsConfig","fetchRewardPercentages","rfqActions","openRfqSession","params","requestComboQuote","acceptComboQuote","waitForComboFill","sessionKeyActions","authorizeSessionKey","fetchSessionKeys","revokeSessionKey","subscriptionsActions","subscriptions","subscribe","tradingActions","createMarketOrder","placeMarketOrder","createLimitOrder","placeLimitOrder","postOrder","postOrders","waitForOrderFillSettlement","cancelOrder","cancelOrders","cancelAll","cancelMarketOrders","listOpenOrders","fetchOrder","publicWalletActions","fetchTradingApprovalsState","walletActions","setupTradingApprovals","approveErc20","approveErc1155ForAll","transferErc20","splitPosition","mergePositions","redeemPositions","planCollateralReturn","executeCollateralReturnPlan","allActions","production","expectEvmAddress","forkEnvironmentConfig","fork","base","forkRestEndpoint","forkWebSocketEndpoint","forkRestWebSocketEndpoint","forkHeaders","preproduction","buildHmacSignature","secret","timestamp","method","requestPath","body","message","cryptoKey","base64ToArrayBuffer","signature","toUrlSafeBase64","arrayBufferToBase64","base64","sanitizedBase64","binaryString","bytes","index","buffer","binary","byte","value","createSubscriptionHandle","queue","closeSubscription","closing","SubscriptionRegistry","#entries","#deriveServerState","options","subscription","subscriber","pushable","entry","#addEntry","before","event","syncMarketSubscription","send","after","addedAssets","difference","removedAssets","buildMarketSubscribeUpdate","firstActiveAsset","buildMarketUnsubscribeUpdate","syncUserSubscription","buildUserUnsubscribeUpdate","buildUserSubscribeUpdate","addedMarkets","removedMarkets","deriveMarketServerSubscription","entries","assets","customFeatureEnabled","assetId","deriveUserServerSubscription","includeAllMarkets","markets","isAllMarketsUserSubscription","market","buildMarketSubscribeMessage","assetsIds","buildUserSubscribeMessage","credentials","marketMatcherFor","assetIds","change","userMatcherFor","left","right","rightSet","ClobMarketWebSocketManager","#headers","#url","#closing","#connection","WebSocketConnection","ClobWebSocketHeartbeat","#reconnectScheduler","ReconnectScheduler","#subscriptions","#registerSubscriber","#closeSubscriber","#connect","#shutdown","#onConnectionLost","#onConnectionError","#onConnectionMessage","#onConnectionOpen","#sendInitialSubscription","events","eventData","parsed","MarketEventSchema","#scheduleReconnect","ClobUserWebSocketManager","#credentials","UserEventSchema","PerpsSessionManager","#chainId","#restUrl","#wsUrl","#sessions","#connectingSessions","#connecting","#hasShutdown","TransportError","session","PerpsSession","closedSession","#clearSession","connecting","sessions","connectingSessions","promise","PerpsSubscriptionManager","#nextRequestId","PerpsWebSocketHeartbeat","derivePerpsSubscriptionServerState","matcherFor","#sendSubscribeFrame","channelsAdded","#sendUnsubscribeFrame","channelsRemoved","PerpsMarketDataEventSchema","channels","#buildChannelFrame","req","tickerInstrumentIds","statisticInstrumentIds","subscribeAllTickers","subscribeAllStatistics","channelFor","instrumentId","channel","invariant","toQuoteRequestEvent","controller","toConfirmationRequestEvent","rfqId","quoteId","RfqConfirmationDecision","toQuoteAck","toQuoteCancelAck","toConfirmationAck","createAuthMessage","account","identity","resolveOrderIdentity","createQuoteMessage","quote","createQuoteCancelMessage","createConfirmationResponseMessage","decision","PendingResponses","#pending","#timeoutMs","timeoutMs","key","timeoutMessage","pending","createPending","timeout","setNonBlockingTimeout","TimeoutError","remaining","resolve","reject","resolvePromise","rejectPromise","BYTES32_ZERO","signRfqQuoteOrder","domain","createExchangeV3OrderDomain","order","toBaseUnits","calculateExchangeOrderMakerAmount","generateRfqOrderSalt","encodeExchangeOrderSide","calculateExchangeOrderTakerAmount","createExchangeOrderTypedDataPayload","createExchangeOrderSignature","DecimalishToBigIntSchema","DecimalishSchema","decimalToScaledInteger","RfqQuoteResponseSchema","price","parseRfqQuoteResponse","parseUserInput","createRfqQuote","size","defaultQuoteSize","signedOrder","quoteOrderPrice","quoteOrderSide","quoteOrderTokenId","source","RfqDirection","OrderSide","requestedSize","RfqRequestedSizeUnit","match","UserInputError","whole","fraction","scaledValue","AUTH_TIMEOUT_MS","ACK_TIMEOUT_MS","RfqQuoterWebSocketManager","#account","#exchange","#signer","#session","#connectingSession","RfqWebSocketSession","connectingSession","#onClose","#queue","#auth","auth","authTimeout","info","#handleConnectionLost","#handleMessage","#sendAuthMessage","#send","#failPending","#fail","#shutdownWithError","rawMessage","RfqQuoterInboundMessageSchema","#handleAuthMessage","quoteAckKey","quoteCancelAckKey","confirmationAckKey","#handleRfqError","ConnectionLostError","RfqQuoteRejectedError","RfqCancelQuoteRejectedError","RfqConfirmationRejectedError","parsedResponse","reference","RtdsWebSocketManager","RtdsWebSocketHeartbeat","deriveRtdsServerState","subscriptionsToOpen","serverSubscriptionsAdded","subscriptionsToClose","serverSubscriptionsRemoved","#resubscribeActiveServerEntries","RealtimeEventSchema","buildSubscribeMessage","buildUnsubscribeMessage","activeByKey","serverSubscription","serverSubscriptionsFor","topic","type","twapServerTopic","windowSeconds","SportsWebSocketManager","SportsWebSocketHeartbeat","SportsResultEventSchema","AbstractClient","#context","#decorators","context","decorator","BeginAuthenticationCredentialsSchema","ApiKeySchema","BeginAuthenticationRequestSchema","EvmAddressSchema","BasePublicClient","ServiceClient","JsonRpcClient","signer","nonce","signerAddress","requestAddress","wallet","resolveAccountIdentity","#createSecureClient","fetchApiKeys","RequestRejectedError","createOrDeriveApiKey","expectEvmSignature","BaseSecureClient","#hasEndedAuthentication","#createL2Headers","#resolveBuilderGatewayHeaders","closingSubscriptions","shuttingDownPerpsSessions","shuttingDownRfqQuoter","apiKey","environment","onRateLimitUpdate","deleteApiKey","createPublicClient","CreateSecureClientError","makeErrorGuard","CancelledSigningError","RateLimitError","TransactionFailedError","UnexpectedResponseError","SetupGaslessWalletError","createSecureClient","resolveRequestedWallet","secureClient","authenticateWith","WalletType","isWalletDeployed","deployDefaultDepositWallet","legacyDepositWallet","deriveUupsDepositWalletAddress","deriveBeaconDepositWalletAddress","currentDepositWallet","isSameEvmAddress","deployDepositWallet"],"mappings":"o2NAiCA,IAAMA,EAAAA,CAAqCC,CAAAA,CAAE,OAAO,CAClD,oBAAA,CAAsBA,CAAAA,CAAE,MAAA,EAAO,CAAE,GAAA,CAAI,CAAC,CAAA,CACtC,sBAAA,CAAwBA,CAAAA,CAAE,MAAA,EAAO,CAAE,GAAA,CAAI,CAAC,CAAA,CACxC,uBAAA,CAAyBA,EAAE,MAAA,EAAO,CAAE,GAAA,CAAI,CAAC,CAAA,CACzC,sBAAA,CAAwBA,CAAAA,CAAE,MAAA,EAAO,CAAE,GAAA,CAAI,CAAC,CAC1C,CAAC,CAAA,CAEM,SAASC,EAAAA,CACdC,EACqB,CACrB,OAAO,IAAIC,EAAAA,CAA2BD,CAAM,CAC9C,CAEO,SAASE,EAAAA,CACdF,CAAAA,CACqB,CACrB,OAAO,IAAIG,EAAAA,CAA2BH,CAAM,CAC9C,CAEA,IAAMC,EAAAA,CAAN,KAAgE,CACrDG,EAAAA,CAET,WAAA,CAAYJ,CAAAA,CAAoC,CAC9C,KAAKI,EAAAA,CAAUJ,EACjB,CAEA,IAAI,YAAA,EAAwB,CAC1B,OAAO,KACT,CAEA,IAAI,cAAA,EAA0B,CAC5B,OAAO,KACT,CAEA,MAAM,SAAA,CAAUK,CAAAA,CAA2D,CACzE,GAAI,CACF,OAAO,MAAM,IAAA,CAAKC,EAAAA,CAAwBD,CAAO,CACnD,CAAA,MAASE,CAAAA,CAAO,CACd,MAAMC,CAAAA,CAAa,SAAA,CACjBD,CA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,CAAoB,CAAA,gDAAA,CAC1G,CAAA,CAIF,KAAA,CADe,MAAME,EAAAA,CAAoBV,CAAY,CAAA,EACxC,OACf","file":"index.js","sourcesContent":["import { z } from 'zod';\nimport { SigningError } from './errors';\nimport type { ApiKeyAuthorization, ApiKeyAuthorizationRequest } from './types';\n\nexport type RelayerApiKeyConfig = {\n key: string;\n address: string;\n};\n\nexport type RemoteBuilderSigningConfig = {\n /**\n * URL for the application's remote builder-signing endpoint.\n *\n * This may be an absolute `http` or `https` URL, or a root-relative path\n * such as `/api/builder/sign` in browser environments.\n */\n url: string;\n /**\n * Fetch credential mode for requests to the remote signer.\n *\n * Set this when the signer relies on cookie-backed authentication, especially\n * for cross-origin requests that require `include`.\n */\n credentials?: RequestCredentials;\n /**\n * Additional headers to send to the remote signer.\n *\n * Use this for application-specific authorization such as bearer tokens,\n * tenant headers, or CSRF headers. The SDK always sends JSON.\n */\n headers?: HeadersInit | (() => HeadersInit | Promise<HeadersInit>);\n};\n\nconst RemoteBuilderSigningResponseSchema = z.object({\n POLY_BUILDER_API_KEY: z.string().min(1),\n POLY_BUILDER_TIMESTAMP: z.string().min(1),\n POLY_BUILDER_PASSPHRASE: z.string().min(1),\n POLY_BUILDER_SIGNATURE: z.string().min(1),\n});\n\nexport function remoteBuilderSigning(\n config: RemoteBuilderSigningConfig,\n): ApiKeyAuthorization {\n return new RemoteBuilderAuthorization(config);\n}\n\nexport function relayerApiKey(\n config: RelayerApiKeyConfig,\n): ApiKeyAuthorization {\n return new RelayerApiKeyAuthorization(config);\n}\n\nclass RemoteBuilderAuthorization implements ApiKeyAuthorization {\n readonly #config: RemoteBuilderSigningConfig;\n\n constructor(config: RemoteBuilderSigningConfig) {\n this.#config = config;\n }\n\n get isBuilderKey(): boolean {\n return true;\n }\n\n get supportGasless(): boolean {\n return true;\n }\n\n async authorize(request: ApiKeyAuthorizationRequest): Promise<HeadersInit> {\n try {\n return await this.#fetchBuilderKeyHeaders(request);\n } catch (error) {\n throw SigningError.fromError(\n error,\n 'Could not authorize the builder-authenticated request',\n );\n }\n }\n\n async #resolveHeaders(): Promise<Headers> {\n const headers = this.#config.headers;\n const resolvedHeaders =\n typeof headers === 'function' ? await headers() : headers;\n const requestHeaders = new Headers(resolvedHeaders);\n\n requestHeaders.set('content-type', 'application/json');\n\n return requestHeaders;\n }\n\n async #fetchBuilderKeyHeaders(\n request: ApiKeyAuthorizationRequest,\n ): Promise<HeadersInit> {\n const response = await fetch(this.#config.url, {\n body: JSON.stringify({\n body: request.body,\n method: request.method,\n path: request.path,\n }),\n credentials: this.#config.credentials,\n headers: await this.#resolveHeaders(),\n method: 'POST',\n mode: 'cors',\n });\n\n if (!response.ok) {\n throw new Error(\n `Remote signer rejected request with status ${response.status}`,\n );\n }\n\n return RemoteBuilderSigningResponseSchema.parse(await response.json());\n }\n}\n\nclass RelayerApiKeyAuthorization implements ApiKeyAuthorization {\n readonly #config: RelayerApiKeyConfig;\n\n constructor(config: RelayerApiKeyConfig) {\n this.#config = config;\n }\n\n get isBuilderKey(): boolean {\n return false;\n }\n\n get supportGasless(): boolean {\n return true;\n }\n\n authorize(): Promise<HeadersInit> {\n return Promise.resolve({\n RELAYER_API_KEY: this.#config.key,\n RELAYER_API_KEY_ADDRESS: this.#config.address,\n });\n }\n}\n","import type { EvmAddress } from '@polymarket/types';\nimport type { TypedDataPayload } from './types';\n\n/** @internal */\nexport type CreateApiKeyAuthTypedDataPayloadRequest = {\n address: EvmAddress;\n chainId: number;\n nonce?: number;\n timestamp: number;\n};\n\n/** @internal */\nexport function createApiKeyAuthTypedDataPayload(\n request: CreateApiKeyAuthTypedDataPayloadRequest,\n): TypedDataPayload {\n return {\n domain: {\n chainId: request.chainId,\n name: 'ClobAuthDomain',\n version: '1',\n },\n message: {\n address: request.address,\n message: 'This message attests that I control the given wallet',\n nonce: request.nonce ?? 0,\n timestamp: `${request.timestamp}`,\n },\n primaryType: 'ClobAuth',\n types: {\n ClobAuth: [\n { name: 'address', type: 'address' },\n { name: 'timestamp', type: 'string' },\n { name: 'nonce', type: 'uint256' },\n { name: 'message', type: 'string' },\n ],\n },\n };\n}\n","import type {\n ClobTrade,\n NotificationsResponse,\n} from '@polymarket/bindings/clob';\nimport type {\n Activity,\n ClosedPosition,\n ComboActivity,\n ComboPosition,\n MetaMarketPosition,\n Position,\n Traded,\n Value,\n} from '@polymarket/bindings/data';\nimport type { Prettify } from '@polymarket/types';\nimport {\n type DownloadAccountingSnapshotRequest,\n type DropNotificationsRequest,\n downloadAccountingSnapshot,\n dropNotifications,\n type FetchPortfolioValueRequest,\n type FetchTradedMarketCountRequest,\n fetchClosedOnlyMode,\n fetchNotifications,\n fetchPortfolioValue,\n fetchTradedMarketCount,\n type ListAccountTradesRequest,\n type ListActivityRequest,\n type ListClosedPositionsRequest,\n type ListComboActivityRequest,\n type ListComboPositionsRequest,\n type ListMarketPositionsRequest,\n type ListPositionsRequest,\n listAccountTrades,\n listActivity,\n listClosedPositions,\n listComboActivity,\n listComboPositions,\n listMarketPositions,\n listPositions,\n} from '../actions';\nimport type {\n BaseClient,\n BasePublicClient,\n BaseSecureClient,\n} from '../clients';\nimport type { Paginated } from '../pagination';\n\ntype DefaultAccountWallet<TRequest extends { user: string }> = Prettify<\n Omit<TRequest, 'user'> & {\n /**\n * Wallet address to use.\n *\n * @defaultValue `client.account.wallet`\n */\n user?: string;\n }\n>;\n\nexport type SecureListPositionsRequest =\n DefaultAccountWallet<ListPositionsRequest>;\nexport type SecureListClosedPositionsRequest =\n DefaultAccountWallet<ListClosedPositionsRequest>;\nexport type SecureListComboPositionsRequest =\n DefaultAccountWallet<ListComboPositionsRequest>;\nexport type SecureFetchPortfolioValueRequest =\n DefaultAccountWallet<FetchPortfolioValueRequest>;\nexport type SecureFetchTradedMarketCountRequest =\n DefaultAccountWallet<FetchTradedMarketCountRequest>;\nexport type SecureDownloadAccountingSnapshotRequest =\n DefaultAccountWallet<DownloadAccountingSnapshotRequest>;\nexport type SecureListActivityRequest =\n DefaultAccountWallet<ListActivityRequest>;\nexport type SecureListComboActivityRequest =\n DefaultAccountWallet<ListComboActivityRequest>;\n\ntype CommonAccountActions = {\n /**\n * Lists positions for a market.\n *\n * @throws {@link ListMarketPositionsError}\n * Thrown on failure.\n *\n * @example\n * Fetch the first page of results:\n * ```ts\n * const paginator = client.listMarketPositions({\n * market: '0xe546672750517f62c45a5a00067481981e62b9c20fa8220203232c9dc8fd2093',\n * pageSize: 10,\n * });\n *\n * const firstPage = await paginator.firstPage();\n *\n * // Optionally, fetch additional pages:\n * for await (const page of paginator.from(firstPage.nextCursor)) {\n * // page.items: MetaMarketPosition[]\n * }\n * ```\n *\n * @example\n * Loop through all pages with `for await`:\n * ```ts\n * const paginator = client.listMarketPositions({\n * market: '0xe546672750517f62c45a5a00067481981e62b9c20fa8220203232c9dc8fd2093',\n * pageSize: 10,\n * });\n *\n * for await (const page of paginator) {\n * // page.items: MetaMarketPosition[]\n * }\n * ```\n */\n listMarketPositions(\n request: ListMarketPositionsRequest,\n ): Paginated<MetaMarketPosition[]>;\n};\n\nexport type PublicAccountActions = Prettify<\n CommonAccountActions & {\n /**\n * Lists current positions for a wallet.\n *\n * @throws {@link ListPositionsError}\n * Thrown on failure.\n *\n * @example\n * Fetch the first page of results:\n * ```ts\n * const paginator = client.listPositions({\n * user: '0x7c3db723f1d4d8cb9c550095203b686cb11e5c6b',\n * pageSize: 10,\n * });\n *\n * const firstPage = await paginator.firstPage();\n *\n * // Optionally, fetch additional pages:\n * for await (const page of paginator.from(firstPage.nextCursor)) {\n * // page.items: Position[]\n * }\n * ```\n *\n * @example\n * Loop through all pages with `for await`:\n * ```ts\n * const paginator = client.listPositions({\n * user: '0x7c3db723f1d4d8cb9c550095203b686cb11e5c6b',\n * pageSize: 10,\n * });\n *\n * for await (const page of paginator) {\n * // page.items: Position[]\n * }\n * ```\n */\n listPositions(request: ListPositionsRequest): Paginated<Position[]>;\n /**\n * Lists closed positions for a wallet.\n *\n * @throws {@link ListClosedPositionsError}\n * Thrown on failure.\n *\n * @example\n * Fetch the first page of results:\n * ```ts\n * const paginator = client.listClosedPositions({\n * user: '0x7c3db723f1d4d8cb9c550095203b686cb11e5c6b',\n * pageSize: 10,\n * });\n *\n * const firstPage = await paginator.firstPage();\n *\n * // Optionally, fetch additional pages:\n * for await (const page of paginator.from(firstPage.nextCursor)) {\n * // page.items: ClosedPosition[]\n * }\n * ```\n *\n * @example\n * Loop through all pages with `for await`:\n * ```ts\n * const paginator = client.listClosedPositions({\n * user: '0x7c3db723f1d4d8cb9c550095203b686cb11e5c6b',\n * pageSize: 10,\n * });\n *\n * for await (const page of paginator) {\n * // page.items: ClosedPosition[]\n * }\n * ```\n */\n listClosedPositions(\n request: ListClosedPositionsRequest,\n ): Paginated<ClosedPosition[]>;\n /**\n * Lists combo positions for a wallet.\n *\n * @throws {@link ListComboPositionsError}\n * Thrown on failure.\n *\n * @example\n * Fetch the first page of results:\n * ```ts\n * const paginator = client.listComboPositions({\n * user: '0x7c3db723f1d4d8cb9c550095203b686cb11e5c6b',\n * pageSize: 10,\n * });\n *\n * const firstPage = await paginator.firstPage();\n * ```\n *\n * @example\n * Filter to any of several resolved statuses:\n * ```ts\n * const paginator = client.listComboPositions({\n * user: '0x7c3db723f1d4d8cb9c550095203b686cb11e5c6b',\n * status: [\n * ComboPositionStatus.ResolvedWin,\n * ComboPositionStatus.ResolvedPartial,\n * ComboPositionStatus.ResolvedLoss,\n * ],\n * });\n * ```\n */\n listComboPositions(\n request: ListComboPositionsRequest,\n ): Paginated<ComboPosition[]>;\n /**\n * Fetches the total value for a wallet's positions.\n *\n * @throws {@link FetchPortfolioValueError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const value = await client.fetchPortfolioValue({\n * user: '0x7c3db723f1d4d8cb9c550095203b686cb11e5c6b',\n * });\n * ```\n */\n fetchPortfolioValue(request: FetchPortfolioValueRequest): Promise<Value[]>;\n /**\n * Fetches the total number of markets a wallet has traded.\n *\n * @throws {@link FetchTradedMarketCountError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const traded = await client.fetchTradedMarketCount({\n * user: '0x7c3db723f1d4d8cb9c550095203b686cb11e5c6b',\n * });\n * ```\n */\n fetchTradedMarketCount(\n request: FetchTradedMarketCountRequest,\n ): Promise<Traded>;\n /**\n * Downloads an accounting snapshot archive for a wallet.\n *\n * @throws {@link DownloadAccountingSnapshotError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const snapshot = await client.downloadAccountingSnapshot({\n * user: '0x7c3db723f1d4d8cb9c550095203b686cb11e5c6b',\n * });\n * ```\n */\n downloadAccountingSnapshot(\n request: DownloadAccountingSnapshotRequest,\n ): Promise<Blob>;\n /**\n * Lists wallet activity.\n *\n * All activity types are returned by default, including deposits and withdrawals; use the `type` filter to narrow results.\n *\n * @throws {@link ListActivityError}\n * Thrown on failure.\n *\n * @example\n * Fetch the first page of results:\n * ```ts\n * const paginator = client.listActivity({\n * user: '0x7c3db723f1d4d8cb9c550095203b686cb11e5c6b',\n * pageSize: 10,\n * });\n *\n * const firstPage = await paginator.firstPage();\n *\n * // Optionally, fetch additional pages:\n * for await (const page of paginator.from(firstPage.nextCursor)) {\n * // page.items: Activity[]\n * }\n * ```\n *\n * @example\n * Loop through all pages with `for await`:\n * ```ts\n * const paginator = client.listActivity({\n * user: '0x7c3db723f1d4d8cb9c550095203b686cb11e5c6b',\n * pageSize: 10,\n * });\n *\n * for await (const page of paginator) {\n * // page.items: Activity[]\n * }\n * ```\n */\n listActivity(request: ListActivityRequest): Paginated<Activity[]>;\n /**\n * Lists combo lifecycle activity for a wallet.\n *\n * @throws {@link ListComboActivityError}\n * Thrown on failure.\n *\n * @example\n * Fetch the first page of results:\n * ```ts\n * const paginator = client.listComboActivity({\n * user: '0x7c3db723f1d4d8cb9c550095203b686cb11e5c6b',\n * pageSize: 10,\n * });\n *\n * const firstPage = await paginator.firstPage();\n * ```\n */\n listComboActivity(\n request: ListComboActivityRequest,\n ): Paginated<ComboActivity[]>;\n }\n>;\n\nexport type SecureAccountActions = Prettify<\n CommonAccountActions & {\n /**\n * Lists current positions for a wallet.\n *\n * Defaults to the authenticated account's wallet when `user` is omitted.\n *\n * @throws {@link ListPositionsError}\n * Thrown on failure.\n *\n * @example\n * Fetch the first page of results for the authenticated account:\n * ```ts\n * const paginator = client.listPositions({\n * pageSize: 10,\n * });\n *\n * const firstPage = await paginator.firstPage();\n * ```\n */\n listPositions(request?: SecureListPositionsRequest): Paginated<Position[]>;\n /**\n * Lists closed positions for a wallet.\n *\n * Defaults to the authenticated account's wallet when `user` is omitted.\n *\n * @throws {@link ListClosedPositionsError}\n * Thrown on failure.\n */\n listClosedPositions(\n request?: SecureListClosedPositionsRequest,\n ): Paginated<ClosedPosition[]>;\n /**\n * Lists combo positions for a wallet.\n *\n * Defaults to the authenticated account's wallet when `user` is omitted.\n *\n * @throws {@link ListComboPositionsError}\n * Thrown on failure.\n *\n * @example\n * Filter the authenticated account's positions to multiple statuses:\n * ```ts\n * const paginator = client.listComboPositions({\n * status: [\n * ComboPositionStatus.ResolvedWin,\n * ComboPositionStatus.ResolvedPartial,\n * ],\n * });\n * ```\n */\n listComboPositions(\n request?: SecureListComboPositionsRequest,\n ): Paginated<ComboPosition[]>;\n /**\n * Fetches the total value for a wallet's positions.\n *\n * Defaults to the authenticated account's wallet when `user` is omitted.\n *\n * @throws {@link FetchPortfolioValueError}\n * Thrown on failure.\n */\n fetchPortfolioValue(\n request?: SecureFetchPortfolioValueRequest,\n ): Promise<Value[]>;\n /**\n * Fetches the total number of markets a wallet has traded.\n *\n * Defaults to the authenticated account's wallet when `user` is omitted.\n *\n * @throws {@link FetchTradedMarketCountError}\n * Thrown on failure.\n */\n fetchTradedMarketCount(\n request?: SecureFetchTradedMarketCountRequest,\n ): Promise<Traded>;\n /**\n * Downloads an accounting snapshot archive for a wallet.\n *\n * Defaults to the authenticated account's wallet when `user` is omitted.\n *\n * @throws {@link DownloadAccountingSnapshotError}\n * Thrown on failure.\n */\n downloadAccountingSnapshot(\n request?: SecureDownloadAccountingSnapshotRequest,\n ): Promise<Blob>;\n /**\n * Lists wallet activity.\n *\n * Defaults to the authenticated account's wallet when `user` is omitted.\n *\n * All activity types are returned by default, including deposits and withdrawals; use the `type` filter to narrow results.\n *\n * @throws {@link ListActivityError}\n * Thrown on failure.\n */\n listActivity(request?: SecureListActivityRequest): Paginated<Activity[]>;\n /**\n * Lists combo lifecycle activity for a wallet.\n *\n * Defaults to the authenticated account's wallet when `user` is omitted.\n *\n * @throws {@link ListComboActivityError}\n * Thrown on failure.\n */\n listComboActivity(\n request?: SecureListComboActivityRequest,\n ): Paginated<ComboActivity[]>;\n /**\n * Lists trades for the authenticated account across all pages.\n *\n * @throws {@link ListAccountTradesError}\n * Thrown on failure.\n *\n * @example\n * Fetch the first page of results:\n * ```ts\n * const paginator = client.listAccountTrades({\n * market: '0x0000000000000000000000000000000000000000000000000000000000000001',\n * });\n *\n * const firstPage = await paginator.firstPage();\n *\n * // Optionally, fetch additional pages:\n * for await (const page of paginator.from(firstPage.nextCursor)) {\n * // page.items: ClobTrade[]\n * }\n * ```\n *\n * @example\n * Loop through all pages with `for await`:\n * ```ts\n * const paginator = client.listAccountTrades({\n * market: '0x0000000000000000000000000000000000000000000000000000000000000001',\n * });\n *\n * for await (const page of paginator) {\n * // page.items: ClobTrade[]\n * }\n * ```\n */\n listAccountTrades(\n request?: ListAccountTradesRequest,\n ): Paginated<ClobTrade[]>;\n /**\n * Fetches notifications for the authenticated account.\n * Notifications of a kind this SDK version does not recognize are omitted.\n *\n * @throws {@link FetchNotificationsError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const notifications = await client.fetchNotifications();\n * ```\n */\n fetchNotifications(): Promise<NotificationsResponse>;\n /**\n * Drops notifications for the authenticated account.\n *\n * @throws {@link DropNotificationsError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * await client.dropNotifications({\n * ids: ['1', '2'],\n * });\n * ```\n */\n dropNotifications(request: DropNotificationsRequest): Promise<void>;\n /**\n * Fetches whether the account is restricted to closed-only trading.\n *\n * @throws {@link FetchClosedOnlyModeError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const closedOnly = await client.fetchClosedOnlyMode();\n * ```\n */\n fetchClosedOnlyMode(): Promise<boolean>;\n }\n>;\n\nfunction publicAccountActions(client: BaseClient): PublicAccountActions {\n return {\n listPositions: listPositions.bind(null, client),\n listClosedPositions: listClosedPositions.bind(null, client),\n listComboPositions: listComboPositions.bind(null, client),\n fetchPortfolioValue: fetchPortfolioValue.bind(null, client),\n fetchTradedMarketCount: fetchTradedMarketCount.bind(null, client),\n downloadAccountingSnapshot: downloadAccountingSnapshot.bind(null, client),\n listMarketPositions: listMarketPositions.bind(null, client),\n listActivity: listActivity.bind(null, client),\n listComboActivity: listComboActivity.bind(null, client),\n };\n}\n\ntype WithAccountWallet<TRequest> = Omit<TRequest, 'user'> & { user: string };\n\nfunction withAccountWallet<TRequest extends { user?: string }>(\n client: BaseSecureClient,\n request: TRequest = {} as TRequest,\n): WithAccountWallet<TRequest> {\n if (\n request === null ||\n typeof request !== 'object' ||\n Array.isArray(request)\n ) {\n return request as WithAccountWallet<TRequest>;\n }\n\n return {\n ...request,\n user: request.user === undefined ? client.account.wallet : request.user,\n };\n}\n\nexport function accountActions(client: BasePublicClient): PublicAccountActions;\nexport function accountActions(client: BaseSecureClient): SecureAccountActions;\nexport function accountActions(\n client: BaseClient,\n): PublicAccountActions | SecureAccountActions {\n const actions = publicAccountActions(client);\n\n if (client.isPublicClient()) {\n return actions;\n }\n\n return {\n ...actions,\n listPositions: (request?: SecureListPositionsRequest) =>\n listPositions(client, withAccountWallet(client, request)),\n listClosedPositions: (request?: SecureListClosedPositionsRequest) =>\n listClosedPositions(client, withAccountWallet(client, request)),\n listComboPositions: (request?: SecureListComboPositionsRequest) =>\n listComboPositions(client, withAccountWallet(client, request)),\n fetchPortfolioValue: (request?: SecureFetchPortfolioValueRequest) =>\n fetchPortfolioValue(client, withAccountWallet(client, request)),\n fetchTradedMarketCount: (request?: SecureFetchTradedMarketCountRequest) =>\n fetchTradedMarketCount(client, withAccountWallet(client, request)),\n downloadAccountingSnapshot: (\n request?: SecureDownloadAccountingSnapshotRequest,\n ) => downloadAccountingSnapshot(client, withAccountWallet(client, request)),\n listActivity: (request?: SecureListActivityRequest) =>\n listActivity(client, withAccountWallet(client, request)),\n listComboActivity: (request?: SecureListComboActivityRequest) =>\n listComboActivity(client, withAccountWallet(client, request)),\n listAccountTrades: listAccountTrades.bind(null, client),\n fetchNotifications: fetchNotifications.bind(null, client),\n dropNotifications: dropNotifications.bind(null, client),\n fetchClosedOnlyMode: fetchClosedOnlyMode.bind(null, client),\n };\n}\n\n// Error unions and runtime `isError` guards for every action bound above.\n// Surfaced at the root entry point through `export * from './decorators'`.\n// Keep this list in sync with the methods on PublicAccountActions / SecureAccountActions.\nexport {\n DownloadAccountingSnapshotError,\n DropNotificationsError,\n FetchClosedOnlyModeError,\n FetchNotificationsError,\n FetchPortfolioValueError,\n FetchTradedMarketCountError,\n ListAccountTradesError,\n ListActivityError,\n ListClosedPositionsError,\n ListComboActivityError,\n ListComboPositionsError,\n ListMarketPositionsError,\n ListPositionsError,\n} from '../actions';\nexport { ComboActivityType } from '../actions/activity';\nexport type { ComboPositionStatusFilter } from '../actions/portfolio';\nexport {\n ComboPositionOutcome,\n ComboPositionSort,\n ComboPositionStatus,\n} from '../actions/portfolio';\n","import type { BuilderTrade } from '@polymarket/bindings/clob';\nimport type {\n BuilderVolumeEntry,\n LeaderboardEntry,\n TraderLeaderboardEntry,\n} from '@polymarket/bindings/data';\nimport {\n fetchBuilderVolume,\n type ListBuilderLeaderboardRequest,\n type ListBuilderTradesRequest,\n type ListBuilderVolumeRequest,\n type ListTraderLeaderboardRequest,\n listBuilderLeaderboard,\n listBuilderTrades,\n listTraderLeaderboard,\n} from '../actions';\nimport type {\n BaseClient,\n BasePublicClient,\n BaseSecureClient,\n} from '../clients';\nimport type { Paginated } from '../pagination';\n\nexport type AnalyticsActions = {\n /**\n * Lists builder-attributed trades.\n *\n * @throws {@link ListBuilderTradesError}\n * Thrown on failure.\n *\n * @example\n * Fetch the first page of results:\n * ```ts\n * const paginator = client.listBuilderTrades({\n * builderCode: '0x...',\n * });\n *\n * const firstPage = await paginator.firstPage();\n *\n * // Optionally, fetch additional pages:\n * for await (const page of paginator.from(firstPage.nextCursor)) {\n * // page.items: BuilderTrade[]\n * }\n * ```\n *\n * @example\n * Loop through all pages with `for await`:\n * ```ts\n * const paginator = client.listBuilderTrades({\n * builderCode: '0x...',\n * });\n *\n * for await (const page of paginator) {\n * // page.items: BuilderTrade[]\n * }\n * ```\n */\n listBuilderTrades(\n request: ListBuilderTradesRequest,\n ): Paginated<BuilderTrade[]>;\n\n /**\n * Lists builder leaderboard rankings.\n *\n * @throws {@link ListBuilderLeaderboardError}\n * Thrown on failure.\n *\n * @example\n * Fetch the first page of results:\n * ```ts\n * const paginator = client.listBuilderLeaderboard({\n * pageSize: 10,\n * timePeriod: 'DAY',\n * });\n *\n * const firstPage = await paginator.firstPage();\n *\n * // Optionally, fetch additional pages:\n * for await (const page of paginator.from(firstPage.nextCursor)) {\n * // page.items: LeaderboardEntry[]\n * }\n * ```\n *\n * @example\n * Loop through all pages with `for await`:\n * ```ts\n * const paginator = client.listBuilderLeaderboard({\n * pageSize: 10,\n * timePeriod: 'DAY',\n * });\n *\n * for await (const page of paginator) {\n * // page.items: LeaderboardEntry[]\n * }\n * ```\n */\n listBuilderLeaderboard(\n request?: ListBuilderLeaderboardRequest,\n ): Paginated<LeaderboardEntry[]>;\n\n /**\n * Lists daily builder volume entries.\n *\n * @throws {@link ListBuilderVolumeError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const volume = await client.fetchBuilderVolume({\n * timePeriod: 'DAY',\n * });\n * ```\n */\n fetchBuilderVolume(\n request?: ListBuilderVolumeRequest,\n ): Promise<BuilderVolumeEntry[]>;\n\n /**\n * Lists trader leaderboard rankings.\n *\n * @throws {@link ListTraderLeaderboardError}\n * Thrown on failure.\n *\n * @example\n * Fetch the first page of results:\n * ```ts\n * const paginator = client.listTraderLeaderboard({\n * orderBy: 'PNL',\n * pageSize: 10,\n * timePeriod: 'DAY',\n * });\n *\n * const firstPage = await paginator.firstPage();\n *\n * // Optionally, fetch additional pages:\n * for await (const page of paginator.from(firstPage.nextCursor)) {\n * // page.items: TraderLeaderboardEntry[]\n * }\n * ```\n *\n * @example\n * Loop through all pages with `for await`:\n * ```ts\n * const paginator = client.listTraderLeaderboard({\n * orderBy: 'PNL',\n * pageSize: 10,\n * timePeriod: 'DAY',\n * });\n *\n * for await (const page of paginator) {\n * // page.items: TraderLeaderboardEntry[]\n * }\n * ```\n */\n listTraderLeaderboard(\n request?: ListTraderLeaderboardRequest,\n ): Paginated<TraderLeaderboardEntry[]>;\n};\n\nexport function analyticsActions(client: BasePublicClient): AnalyticsActions;\nexport function analyticsActions(client: BaseSecureClient): AnalyticsActions;\nexport function analyticsActions(client: BaseClient): AnalyticsActions {\n return {\n listBuilderTrades: listBuilderTrades.bind(null, client),\n listBuilderLeaderboard: listBuilderLeaderboard.bind(null, client),\n fetchBuilderVolume: fetchBuilderVolume.bind(null, client),\n listTraderLeaderboard: listTraderLeaderboard.bind(null, client),\n };\n}\n\n// Error unions and runtime `isError` guards for every action bound above.\n// Surfaced at the root entry point through `export * from './decorators'`.\n// Keep this list in sync with the methods on AnalyticsActions.\nexport {\n ListBuilderLeaderboardError,\n ListBuilderTradesError,\n ListBuilderVolumeError,\n ListTraderLeaderboardError,\n} from '../actions';\n","import type { DecimalString } from '@polymarket/bindings';\nimport type {\n LastTradePrice,\n LastTradePriceForAsset,\n Midpoints,\n OrderBook,\n PriceHistoryPoint,\n Prices,\n Spreads,\n} from '@polymarket/bindings/clob';\nimport type {\n LiveVolume,\n MetaHolder,\n OpenInterest,\n Trade,\n} from '@polymarket/bindings/data';\nimport {\n type EstimateMarketPriceRequest,\n estimateMarketPrice,\n type FetchEventLiveVolumeRequest,\n type FetchLastTradePriceRequest,\n type FetchLastTradePricesRequest,\n type FetchMidpointRequest,\n type FetchMidpointsRequest,\n type FetchOrderBookRequest,\n type FetchOrderBooksRequest,\n type FetchPriceHistoryRequest,\n type FetchPriceRequest,\n type FetchPricesRequest,\n type FetchSpreadRequest,\n type FetchSpreadsRequest,\n fetchEventLiveVolume,\n fetchLastTradePrice,\n fetchLastTradePrices,\n fetchMidpoint,\n fetchMidpoints,\n fetchOrderBook,\n fetchOrderBooks,\n fetchPrice,\n fetchPriceHistory,\n fetchPrices,\n fetchSpread,\n fetchSpreads,\n type ListMarketHoldersRequest,\n type ListOpenInterestRequest,\n type ListTradesRequest,\n listMarketHolders,\n listOpenInterest,\n listTrades,\n} from '../actions';\nimport type {\n BaseClient,\n BasePublicClient,\n BaseSecureClient,\n} from '../clients';\nimport type { Paginated } from '../pagination';\n\nexport type DataActions = {\n /**\n * Fetches live volume for an event.\n *\n * @throws {@link FetchEventLiveVolumeError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const volume = await client.fetchEventLiveVolume({ id: '123' });\n * ```\n */\n fetchEventLiveVolume(\n request: FetchEventLiveVolumeRequest,\n ): Promise<LiveVolume[]>;\n /**\n * Fetches the midpoint price for an exchange asset as a decimal string.\n *\n * @throws {@link FetchMidpointError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const midpoint = await client.fetchMidpoint({ assetId: '0x0122…0000' });\n * ```\n */\n fetchMidpoint(request: FetchMidpointRequest): Promise<DecimalString>;\n /**\n * Fetches midpoint prices for multiple exchange assets as an asset ID keyed lookup.\n *\n * @throws {@link FetchMidpointsError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const midpoints = await client.fetchMidpoints([{ assetId: '0x0122…0000' }]);\n * ```\n */\n fetchMidpoints(request: FetchMidpointsRequest): Promise<Midpoints>;\n /**\n * Fetches the current quoted price for an exchange asset and side as a decimal string.\n *\n * @throws {@link FetchPriceError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const price = await client.fetchPrice({ assetId: '0x0122…0000', side: OrderSide.BUY });\n * ```\n */\n fetchPrice(request: FetchPriceRequest): Promise<DecimalString>;\n /**\n * Fetches quoted prices for multiple exchange assets as an asset ID keyed lookup.\n *\n * @throws {@link FetchPricesError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const prices = await client.fetchPrices([{ assetId: '0x0122…0000', side: OrderSide.BUY }]);\n * ```\n */\n fetchPrices(request: FetchPricesRequest): Promise<Prices>;\n /**\n * Fetches the current order book for an exchange asset.\n *\n * @throws {@link FetchOrderBookError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const book = await client.fetchOrderBook({ assetId: '0x0122…0000' });\n * ```\n */\n fetchOrderBook(request: FetchOrderBookRequest): Promise<OrderBook>;\n /**\n * Fetches order books for multiple exchange assets.\n *\n * @throws {@link FetchOrderBooksError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const books = await client.fetchOrderBooks([{ assetId: '0x0122…0000' }]);\n * ```\n */\n fetchOrderBooks(request: FetchOrderBooksRequest): Promise<OrderBook[]>;\n /**\n * Fetches the spread for an exchange asset as a decimal string.\n *\n * @throws {@link FetchSpreadError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const spread = await client.fetchSpread({ assetId: '0x0122…0000' });\n * ```\n */\n fetchSpread(request: FetchSpreadRequest): Promise<DecimalString>;\n /**\n * Fetches spreads for multiple exchange assets as an asset ID keyed lookup.\n *\n * @throws {@link FetchSpreadsError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const spreads = await client.fetchSpreads([{ assetId: '0x0122…0000' }]);\n * ```\n */\n fetchSpreads(request: FetchSpreadsRequest): Promise<Spreads>;\n /**\n * Fetches the last traded price for an exchange asset.\n *\n * Returns `null` when the asset has not traded.\n *\n * @throws {@link FetchLastTradePriceError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const trade = await client.fetchLastTradePrice({ assetId: '0x0122…0000' });\n *\n * // trade === LastTradePrice | null\n * ```\n */\n fetchLastTradePrice(\n request: FetchLastTradePriceRequest,\n ): Promise<LastTradePrice | null>;\n /**\n * Fetches last traded prices for multiple exchange assets.\n *\n * Assets without trades are omitted from the response. Match returned rows by\n * `assetId`; the array is not positionally aligned with the request.\n *\n * @throws {@link FetchLastTradePricesError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const trades = await client.fetchLastTradePrices([{ assetId: '0x0122…0000' }]);\n * const trade = trades.find((candidate) => candidate.assetId === '0x0122…0000');\n * ```\n */\n fetchLastTradePrices(\n request: FetchLastTradePricesRequest,\n ): Promise<LastTradePriceForAsset[]>;\n /**\n * Fetches historical price points for an exchange asset.\n *\n * @throws {@link FetchPriceHistoryError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const history = await client.fetchPriceHistory({ assetId: '0x0122…0000', interval: '1d' });\n * ```\n */\n fetchPriceHistory(\n request: FetchPriceHistoryRequest,\n ): Promise<PriceHistoryPoint[]>;\n /**\n * Estimates the price level a market order would cross at current book depth.\n *\n * For BUY orders, `amount` is the amount of collateral to spend. For SELL\n * orders, `shares` is the number of shares to sell.\n *\n * @throws {@link EstimateMarketPriceError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const price = await client.estimateMarketPrice({\n * assetId: '0x0122…0000',\n * side: OrderSide.BUY,\n * amount: 10,\n * });\n * ```\n */\n estimateMarketPrice(request: EstimateMarketPriceRequest): Promise<number>;\n /**\n * Lists open interest for one or more markets.\n *\n * @throws {@link ListOpenInterestError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const openInterest = await client.listOpenInterest({\n * market: ['0xe546672750517f62c45a5a00067481981e62b9c20fa8220203232c9dc8fd2093'],\n * });\n * ```\n */\n listOpenInterest(request?: ListOpenInterestRequest): Promise<OpenInterest[]>;\n /**\n * Lists the top holders for one or more markets.\n *\n * @throws {@link ListMarketHoldersError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const holders = await client.listMarketHolders({\n * market: ['0xe546672750517f62c45a5a00067481981e62b9c20fa8220203232c9dc8fd2093'],\n * limit: 5,\n * });\n * ```\n */\n listMarketHolders(request: ListMarketHoldersRequest): Promise<MetaHolder[]>;\n /**\n * Lists trades for a wallet, market, or event.\n *\n * @throws {@link ListTradesError}\n * Thrown on failure.\n *\n * @example\n * Fetch the first page of results:\n * ```ts\n * const paginator = client.listTrades({\n * user: '0x7c3db723f1d4d8cb9c550095203b686cb11e5c6b',\n * pageSize: 10,\n * });\n *\n * const firstPage = await paginator.firstPage();\n *\n * // Optionally, fetch additional pages:\n * for await (const page of paginator.from(firstPage.nextCursor)) {\n * // page.items: Trade[]\n * }\n * ```\n *\n * @example\n * Loop through all pages with `for await`:\n * ```ts\n * const paginator = client.listTrades({\n * user: '0x7c3db723f1d4d8cb9c550095203b686cb11e5c6b',\n * pageSize: 10,\n * });\n *\n * for await (const page of paginator) {\n * // page.items: Trade[]\n * }\n * ```\n */\n listTrades(request?: ListTradesRequest): Paginated<Trade[]>;\n};\n\nexport function dataActions(client: BasePublicClient): DataActions;\nexport function dataActions(client: BaseSecureClient): DataActions;\nexport function dataActions(client: BaseClient): DataActions {\n return {\n fetchEventLiveVolume: fetchEventLiveVolume.bind(null, client),\n fetchMidpoint: fetchMidpoint.bind(null, client),\n fetchMidpoints: fetchMidpoints.bind(null, client),\n fetchPrice: fetchPrice.bind(null, client),\n fetchPrices: fetchPrices.bind(null, client),\n fetchOrderBook: fetchOrderBook.bind(null, client),\n fetchOrderBooks: fetchOrderBooks.bind(null, client),\n fetchSpread: fetchSpread.bind(null, client),\n fetchSpreads: fetchSpreads.bind(null, client),\n fetchLastTradePrice: fetchLastTradePrice.bind(null, client),\n fetchLastTradePrices: fetchLastTradePrices.bind(null, client),\n fetchPriceHistory: fetchPriceHistory.bind(null, client),\n estimateMarketPrice: estimateMarketPrice.bind(null, client),\n listOpenInterest: listOpenInterest.bind(null, client),\n listMarketHolders: listMarketHolders.bind(null, client),\n listTrades: listTrades.bind(null, client),\n };\n}\n\n// Error unions and runtime `isError` guards for every action bound above.\n// Surfaced at the root entry point through `export * from './decorators'`.\n// Keep this list in sync with the methods on DataActions.\nexport {\n EstimateMarketPriceError,\n FetchEventLiveVolumeError,\n FetchLastTradePriceError,\n FetchLastTradePricesError,\n FetchMidpointError,\n FetchMidpointsError,\n FetchOrderBookError,\n FetchOrderBooksError,\n FetchPriceError,\n FetchPriceHistoryError,\n FetchPricesError,\n FetchSpreadError,\n FetchSpreadsError,\n ListMarketHoldersError,\n ListOpenInterestError,\n ListTradesError,\n} from '../actions';\n","import type { ComboMarket } from '@polymarket/bindings/combos';\nimport type {\n Comment,\n Event,\n Market,\n MarketClarification,\n PublicProfile,\n RelatedTag,\n Series,\n SportsMarketTypesResponse,\n SportsMetadata,\n Tag,\n TagReference,\n Team,\n} from '@polymarket/bindings/gamma';\nimport {\n type FetchCommentsByIdRequest,\n type FetchEventRequest,\n type FetchEventTagsRequest,\n type FetchMarketRequest,\n type FetchMarketTagsRequest,\n type FetchPublicProfileRequest,\n type FetchRelatedTagResourcesRequest,\n type FetchRelatedTagsRequest,\n type FetchSeriesRequest,\n type FetchTagRequest,\n fetchCommentsById,\n fetchEvent,\n fetchEventTags,\n fetchMarket,\n fetchMarketTags,\n fetchPublicProfile,\n fetchRelatedTagResources,\n fetchRelatedTags,\n fetchSeries,\n fetchSportsMarketTypes,\n fetchTag,\n type ListComboMarketsRequest,\n type ListCommentsByUserAddressRequest,\n type ListCommentsRequest,\n type ListEventsRequest,\n type ListMarketClarificationsRequest,\n type ListMarketsRequest,\n type ListSeriesRequest,\n type ListTagsRequest,\n type ListTeamsRequest,\n listComboMarkets,\n listComments,\n listCommentsByUserAddress,\n listEvents,\n listMarketClarifications,\n listMarkets,\n listSeries,\n listSports,\n listTags,\n listTeams,\n type SearchRequest,\n type SearchResults,\n search,\n} from '../actions';\nimport type {\n BaseClient,\n BasePublicClient,\n BaseSecureClient,\n} from '../clients';\nimport type { Paginated } from '../pagination';\n\nexport type DiscoveryActions = {\n /**\n * Lists events.\n *\n * Defaults to open events. Pass `closed: true` to list settled events.\n *\n * @throws {@link ListEventsError}\n * Thrown on failure.\n *\n * @example\n * Fetch the first page of results:\n * ```ts\n * const paginator = client.listEvents({\n * pageSize: 10,\n * });\n *\n * const firstPage = await paginator.firstPage();\n *\n * // Optionally, fetch additional pages:\n * for await (const page of paginator.from(firstPage.nextCursor)) {\n * // page.items: Event[]\n * }\n * ```\n *\n * @example\n * Loop through all pages with `for await`:\n * ```ts\n * const paginator = client.listEvents({\n * pageSize: 10,\n * });\n *\n * for await (const page of paginator) {\n * // page.items: Event[]\n * }\n * ```\n */\n listEvents(request?: ListEventsRequest): Paginated<Event[]>;\n\n /**\n * Fetches an event.\n *\n * @throws {@link FetchEventError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const event = await client.fetchEvent({\n * id: '123',\n * });\n *\n * const eventBySlug = await client.fetchEvent({\n * slug: 'presidential-election-2028',\n * });\n *\n * const eventByUrl = await client.fetchEvent({\n * url: 'https://polymarket.com/event/presidential-election-2028',\n * });\n * ```\n */\n fetchEvent(request: FetchEventRequest): Promise<Event>;\n\n /**\n * Fetches an event's tags.\n *\n * @throws {@link FetchEventTagsError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const tags = await client.fetchEventTags({\n * id: '123',\n * });\n * ```\n */\n fetchEventTags(request: FetchEventTagsRequest): Promise<TagReference[]>;\n\n /**\n * Lists markets.\n *\n * @remarks\n * Legacy multi-outcome markets cannot be represented by the binary\n * {@link Market} model and are omitted from results.\n *\n * @throws {@link ListMarketsError}\n * Thrown on failure.\n *\n * @example\n * Fetch the first page of results:\n * ```ts\n * const paginator = client.listMarkets({\n * closed: false,\n * pageSize: 10,\n * });\n *\n * const firstPage = await paginator.firstPage();\n *\n * // Optionally, fetch additional pages:\n * for await (const page of paginator.from(firstPage.nextCursor)) {\n * // page.items: Market[]\n * }\n * ```\n *\n * @example\n * Loop through all pages with `for await`:\n * ```ts\n * const paginator = client.listMarkets({\n * closed: false,\n * pageSize: 10,\n * });\n *\n * for await (const page of paginator) {\n * // page.items: Market[]\n * }\n * ```\n */\n listMarkets(request?: ListMarketsRequest): Paginated<Market[]>;\n\n /**\n * Lists markets available for Combos.\n *\n * @throws {@link ListComboMarketsError}\n * Thrown on failure.\n *\n * @example\n * Fetch the first page of results:\n * ```ts\n * const paginator = client.listComboMarkets({\n * pageSize: 10,\n * });\n *\n * const firstPage = await paginator.firstPage();\n *\n * // Optionally, fetch additional pages:\n * for await (const page of paginator.from(firstPage.nextCursor)) {\n * // page.items: ComboMarket[]\n * }\n * ```\n *\n * @example\n * Loop through all pages with `for await`:\n * ```ts\n * const paginator = client.listComboMarkets({\n * pageSize: 10,\n * });\n *\n * for await (const page of paginator) {\n * // page.items: ComboMarket[]\n * }\n * ```\n *\n * @example\n * Omit markets the caller has already displayed:\n * ```ts\n * const paginator = client.listComboMarkets({\n * exclude: ['0x4cd77d456c83e7d8c569a8fb8f6396c3f40154f657e6d970733e2b1b6a7110ff'],\n * pageSize: 10,\n * });\n * ```\n */\n listComboMarkets(request?: ListComboMarketsRequest): Paginated<ComboMarket[]>;\n\n /**\n * Fetches a market.\n *\n * @remarks\n * Legacy multi-outcome markets cannot be represented by the binary\n * {@link Market} model, so fetching one fails with an\n * `UnexpectedResponseError`.\n *\n * @throws {@link FetchMarketError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const market = await client.fetchMarket({\n * id: '12345',\n * });\n *\n * const marketBySlug = await client.fetchMarket({\n * slug: 'some-market-slug',\n * });\n *\n * const marketByUrl = await client.fetchMarket({\n * url: 'https://polymarket.com/event/some-market-slug',\n * });\n * ```\n */\n fetchMarket(request: FetchMarketRequest): Promise<Market>;\n\n /**\n * Fetches a market's tags.\n *\n * @throws {@link FetchMarketTagsError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const tags = await client.fetchMarketTags({\n * id: '12345',\n * });\n * ```\n */\n fetchMarketTags(request: FetchMarketTagsRequest): Promise<TagReference[]>;\n\n /**\n * Lists series.\n *\n * @throws {@link ListSeriesError}\n * Thrown on failure.\n *\n * @example\n * Fetch the first page of results:\n * ```ts\n * const paginator = client.listSeries({\n * pageSize: 10,\n * });\n *\n * const firstPage = await paginator.firstPage();\n *\n * // Optionally, fetch additional pages:\n * for await (const page of paginator.from(firstPage.nextCursor)) {\n * // page.items: Series[]\n * }\n * ```\n *\n * @example\n * Loop through all pages with `for await`:\n * ```ts\n * const paginator = client.listSeries({\n * pageSize: 10,\n * });\n *\n * for await (const page of paginator) {\n * // page.items: Series[]\n * }\n * ```\n */\n listSeries(request?: ListSeriesRequest): Paginated<Series[]>;\n\n /**\n * Fetches a series.\n *\n * @throws {@link FetchSeriesError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const series = await client.fetchSeries({\n * id: '123',\n * });\n * ```\n */\n fetchSeries(request: FetchSeriesRequest): Promise<Series>;\n\n /**\n * Lists market clarifications — notes that resolve ambiguity in how a market\n * settles.\n *\n * @throws {@link ListMarketClarificationsError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const paginator = client.listMarketClarifications({\n * marketId: '512038',\n * });\n *\n * for await (const page of paginator) {\n * // page.items: MarketClarification[]\n * }\n * ```\n */\n listMarketClarifications(\n request?: ListMarketClarificationsRequest,\n ): Paginated<MarketClarification[]>;\n\n /**\n * Lists tags.\n *\n * @throws {@link ListTagsError}\n * Thrown on failure.\n *\n * @example\n * Fetch the first page of results:\n * ```ts\n * const paginator = client.listTags({\n * pageSize: 10,\n * });\n *\n * const firstPage = await paginator.firstPage();\n *\n * // Optionally, fetch additional pages:\n * for await (const page of paginator.from(firstPage.nextCursor)) {\n * // page.items: Tag[]\n * }\n * ```\n *\n * @example\n * Loop through all pages with `for await`:\n * ```ts\n * const paginator = client.listTags({\n * pageSize: 10,\n * });\n *\n * for await (const page of paginator) {\n * // page.items: Tag[]\n * }\n * ```\n */\n listTags(request?: ListTagsRequest): Paginated<Tag[]>;\n\n /**\n * Fetches a tag by id or slug.\n *\n * @throws {@link FetchTagError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const tag = await client.fetchTag({\n * slug: 'politics',\n * });\n * ```\n */\n fetchTag(request: FetchTagRequest): Promise<Tag>;\n\n /**\n * Fetches related tag relationships by id or slug.\n *\n * @throws {@link FetchRelatedTagsError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const related = await client.fetchRelatedTags({\n * slug: 'politics',\n * });\n * ```\n */\n fetchRelatedTags(request: FetchRelatedTagsRequest): Promise<RelatedTag[]>;\n\n /**\n * Fetches resources linked from related tag relationships by id or slug.\n *\n * @throws {@link FetchRelatedTagResourcesError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const resources = await client.fetchRelatedTagResources({\n * slug: 'politics',\n * });\n * ```\n */\n fetchRelatedTagResources(\n request: FetchRelatedTagResourcesRequest,\n ): Promise<Tag[]>;\n\n /**\n * Runs a public full-text search.\n *\n * `keepClosedMarkets` is an hour window for including recently closed markets\n * when searching active events.\n *\n * @throws {@link SearchError}\n * Thrown on failure.\n *\n * @example\n * Fetch the first page of results:\n * ```ts\n * const paginator = client.search({\n * q: 'election',\n * pageSize: 10,\n * });\n *\n * const firstPage = await paginator.firstPage();\n *\n * // Optionally, fetch additional pages:\n * for await (const page of paginator.from(firstPage.nextCursor)) {\n * // page.items.events: Event[]\n * // page.items.tags: SearchTag[]\n * // page.items.profiles: Profile[]\n * }\n * ```\n */\n search(request: SearchRequest): Paginated<SearchResults>;\n\n /**\n * Lists available sports metadata.\n *\n * @throws {@link ListSportsError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const sports = await client.listSports();\n * ```\n */\n listSports(): Promise<SportsMetadata[]>;\n\n /**\n * Fetches the available market types grouped by sport.\n *\n * @throws {@link FetchSportsMarketTypesError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const marketTypes = await client.fetchSportsMarketTypes();\n * ```\n */\n fetchSportsMarketTypes(): Promise<SportsMarketTypesResponse>;\n\n /**\n * Lists teams.\n *\n * @throws {@link ListTeamsError}\n * Thrown on failure.\n *\n * @example\n * Fetch the first page of results:\n * ```ts\n * const paginator = client.listTeams({\n * pageSize: 10,\n * });\n *\n * const firstPage = await paginator.firstPage();\n *\n * // Optionally, fetch additional pages:\n * for await (const page of paginator.from(firstPage.nextCursor)) {\n * // page.items: Team[]\n * }\n * ```\n *\n * @example\n * Loop through all pages with `for await`:\n * ```ts\n * const paginator = client.listTeams({\n * pageSize: 10,\n * });\n *\n * for await (const page of paginator) {\n * // page.items: Team[]\n * }\n * ```\n */\n listTeams(request?: ListTeamsRequest): Paginated<Team[]>;\n\n /**\n * Fetches a public profile by wallet address.\n *\n * @throws {@link FetchPublicProfileError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const profile = await client.fetchPublicProfile({\n * address: '0x1234...',\n * });\n * ```\n */\n fetchPublicProfile(\n request: FetchPublicProfileRequest,\n ): Promise<PublicProfile | null>;\n\n /**\n * Lists comments for an event or series.\n *\n * @throws {@link ListCommentsError}\n * Thrown on failure.\n *\n * @example\n * Fetch the first page of results:\n * ```ts\n * const paginator = client.listComments({\n * parentEntityId: '123',\n * parentEntityType: CommentParentEntityType.Event,\n * pageSize: 20,\n * });\n *\n * const firstPage = await paginator.firstPage();\n *\n * // Optionally, fetch additional pages:\n * for await (const page of paginator.from(firstPage.nextCursor)) {\n * // page.items: Comment[]\n * }\n * ```\n *\n * @example\n * Loop through all pages with `for await`:\n * ```ts\n * const paginator = client.listComments({\n * parentEntityId: '123',\n * parentEntityType: CommentParentEntityType.Event,\n * pageSize: 20,\n * });\n *\n * for await (const page of paginator) {\n * // page.items: Comment[]\n * }\n * ```\n */\n listComments(request: ListCommentsRequest): Paginated<Comment[]>;\n\n /**\n * Fetches a comment thread by comment id.\n *\n * @throws {@link FetchCommentsByIdError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const thread = await client.fetchCommentsById({\n * id: '456',\n * getPositions: true,\n * });\n * ```\n */\n fetchCommentsById(request: FetchCommentsByIdRequest): Promise<Comment[]>;\n\n /**\n * Lists comments written by a wallet address.\n *\n * @throws {@link ListCommentsByUserAddressError}\n * Thrown on failure.\n *\n * @example\n * Fetch the first page of results:\n * ```ts\n * const paginator = client.listCommentsByUserAddress({\n * address: '0x1234...',\n * pageSize: 10,\n * order: 'DESC',\n * });\n *\n * const firstPage = await paginator.firstPage();\n *\n * // Optionally, fetch additional pages:\n * for await (const page of paginator.from(firstPage.nextCursor)) {\n * // page.items: Comment[]\n * }\n * ```\n *\n * @example\n * Loop through all pages with `for await`:\n * ```ts\n * const paginator = client.listCommentsByUserAddress({\n * address: '0x1234...',\n * pageSize: 10,\n * order: 'DESC',\n * });\n *\n * for await (const page of paginator) {\n * // page.items: Comment[]\n * }\n * ```\n */\n listCommentsByUserAddress(\n request: ListCommentsByUserAddressRequest,\n ): Paginated<Comment[]>;\n};\n\nexport function discoveryActions(client: BasePublicClient): DiscoveryActions;\nexport function discoveryActions(client: BaseSecureClient): DiscoveryActions;\nexport function discoveryActions(client: BaseClient): DiscoveryActions {\n return {\n listEvents: listEvents.bind(null, client),\n fetchEvent: fetchEvent.bind(null, client),\n fetchEventTags: fetchEventTags.bind(null, client),\n listMarkets: listMarkets.bind(null, client),\n listComboMarkets: listComboMarkets.bind(null, client),\n fetchMarket: fetchMarket.bind(null, client),\n fetchMarketTags: fetchMarketTags.bind(null, client),\n listSeries: listSeries.bind(null, client),\n fetchSeries: fetchSeries.bind(null, client),\n listMarketClarifications: listMarketClarifications.bind(null, client),\n listTags: listTags.bind(null, client),\n fetchTag: fetchTag.bind(null, client),\n fetchRelatedTags: fetchRelatedTags.bind(null, client),\n fetchRelatedTagResources: fetchRelatedTagResources.bind(null, client),\n search: search.bind(null, client),\n listSports: listSports.bind(null, client),\n fetchSportsMarketTypes: fetchSportsMarketTypes.bind(null, client),\n listTeams: listTeams.bind(null, client),\n fetchPublicProfile: fetchPublicProfile.bind(null, client),\n listComments: listComments.bind(null, client),\n fetchCommentsById: fetchCommentsById.bind(null, client),\n listCommentsByUserAddress: listCommentsByUserAddress.bind(null, client),\n };\n}\n\n// Error unions and runtime `isError` guards for every action bound above.\n// Surfaced at the root entry point through `export * from './decorators'`.\n// Keep this list in sync with the methods on DiscoveryActions.\nexport {\n FetchCommentsByIdError,\n FetchEventError,\n FetchEventTagsError,\n FetchMarketError,\n FetchMarketTagsError,\n FetchPublicProfileError,\n FetchRelatedTagResourcesError,\n FetchRelatedTagsError,\n FetchSeriesError,\n FetchSportsMarketTypesError,\n FetchTagError,\n ListComboMarketsError,\n ListCommentsByUserAddressError,\n ListCommentsError,\n ListEventsError,\n ListMarketsError,\n ListSeriesError,\n ListSportsError,\n ListTagsError,\n ListTeamsError,\n SearchError,\n} from '../actions';\n","import type {\n PerpsBook,\n PerpsCandle,\n PerpsFeeScheduleEntry,\n PerpsFundingRate,\n PerpsInstrument,\n PerpsPublicTrade,\n PerpsTicker,\n PerpsWithdrawalId,\n} from '@polymarket/bindings/perps';\nimport {\n type DepositToPerpsRequest,\n depositToPerps,\n type FetchPerpsBookRequest,\n type FetchPerpsInstrumentsRequest,\n type FetchPerpsTickerRequest,\n type FetchPerpsTickersRequest,\n fetchPerpsBook,\n fetchPerpsFees,\n fetchPerpsInstruments,\n fetchPerpsTicker,\n fetchPerpsTickers,\n type ListPerpsCandlesRequest,\n type ListPerpsFundingHistoryRequest,\n type ListPerpsTradesRequest,\n listPerpsCandles,\n listPerpsFundingHistory,\n listPerpsTrades,\n type OpenPerpsSessionRequest,\n openPerpsSession,\n type PerpsSession,\n type RevokePerpsCredentialsRequest,\n revokePerpsCredentials,\n type WithdrawFromPerpsRequest,\n withdrawFromPerps,\n} from '../actions';\nimport type {\n BaseClient,\n BasePublicClient,\n BaseSecureClient,\n} from '../clients';\nimport type { Paginated } from '../pagination';\nimport type { TransactionHandle } from '../types';\n\nexport type {\n ArmPerpsAutoCancelRequest,\n CancelAllPerpsOrdersRequest,\n CancelPerpsOrderRequest,\n CancelPerpsOrdersRequest,\n CreatePerpsSessionRequest,\n DepositToPerpsRequest,\n DisarmPerpsAutoCancelRequest,\n FetchPerpsAccountConfigRequest,\n FetchPerpsBookRequest,\n FetchPerpsInstrumentsRequest,\n FetchPerpsOpenOrdersRequest,\n FetchPerpsOrdersRequest,\n FetchPerpsTickerRequest,\n FetchPerpsTickersRequest,\n ListPerpsCandlesRequest,\n ListPerpsDepositsRequest,\n ListPerpsEquityHistoryRequest,\n ListPerpsFillsRequest,\n ListPerpsFundingHistoryRequest,\n ListPerpsFundingPaymentsRequest,\n ListPerpsNotificationsRequest,\n ListPerpsPnlHistoryRequest,\n ListPerpsTradesRequest,\n ListPerpsWithdrawalsRequest,\n MarkPerpsNotificationsReadRequest,\n OpenPerpsSessionRequest,\n PerpsAutoCancelStatus,\n PerpsBookDepth,\n PerpsCancelOrderResult,\n PerpsOrderRequest,\n PerpsPlacedTpSlOrder,\n PerpsPlacedTpSlOrders,\n PerpsPlaceFokOrderRequest,\n PerpsPlaceGtcOrderRequest,\n PerpsPlaceIocOrderRequest,\n PerpsPositionTpSlTrigger,\n PerpsPostOrderAck,\n PerpsSession,\n PerpsSessionAccountError,\n PerpsSessionEvent,\n PerpsSessionLifecycleError,\n PerpsSessionTradingError,\n PerpsTpSlTrigger,\n PerpsUpdateLeverageResult,\n PlacePerpsOrderRequest,\n PlacePerpsOrderResult,\n PlacePerpsOrderWithTpSlRequest,\n PlacePerpsOrderWithTpSlResult,\n PlacePerpsPositionTpSlRequest,\n PlacePerpsPositionTpSlResult,\n PostPerpsOrdersRequest,\n ResumePerpsSessionRequest,\n RevokePerpsCredentialsRequest,\n UpdatePerpsLeverageRequest,\n UpdatePerpsMarginRequest,\n WithdrawFromPerpsRequest,\n} from '../actions';\nexport {\n ArmPerpsAutoCancelError,\n DepositToPerpsError,\n FetchPerpsBookError,\n FetchPerpsFeesError,\n FetchPerpsInstrumentsError,\n FetchPerpsTickerError,\n FetchPerpsTickersError,\n ListPerpsCandlesError,\n ListPerpsFundingHistoryError,\n ListPerpsTradesError,\n OpenPerpsSessionError,\n RevokePerpsCredentialsError,\n UpdatePerpsLeverageError,\n UpdatePerpsMarginError,\n WithdrawFromPerpsError,\n} from '../actions';\n\n/**\n * @experimental This API may change in a breaking way in any release, including patch releases.\n */\nexport type PublicPerpsActions = {\n /**\n * Fetches Perps instruments.\n *\n * @example\n * ```ts\n * const instruments = await client.fetchPerpsInstruments();\n * ```\n *\n * @throws {@link FetchPerpsInstrumentsError}\n * Thrown on failure.\n *\n * @experimental This API may change in a breaking way in any release, including patch releases.\n */\n fetchPerpsInstruments(\n request?: FetchPerpsInstrumentsRequest,\n ): Promise<PerpsInstrument[]>;\n\n /**\n * Fetches the current Perps ticker for an instrument.\n *\n * @example\n * ```ts\n * const ticker = await client.fetchPerpsTicker({ instrumentId: 1 });\n * ```\n *\n * @throws {@link FetchPerpsTickerError}\n * Thrown on failure.\n *\n * @experimental This API may change in a breaking way in any release, including patch releases.\n */\n fetchPerpsTicker(request: FetchPerpsTickerRequest): Promise<PerpsTicker>;\n\n /**\n * Fetches current Perps tickers.\n *\n * @example\n * ```ts\n * const tickers = await client.fetchPerpsTickers();\n * ```\n *\n * @throws {@link FetchPerpsTickersError}\n * Thrown on failure.\n *\n * @experimental This API may change in a breaking way in any release, including patch releases.\n */\n fetchPerpsTickers(request?: FetchPerpsTickersRequest): Promise<PerpsTicker[]>;\n\n /**\n * Fetches a Perps order book.\n *\n * @example\n * ```ts\n * const book = await client.fetchPerpsBook({ instrumentId: 1, depth: 100 });\n * ```\n *\n * @throws {@link FetchPerpsBookError}\n * Thrown on failure.\n *\n * @experimental This API may change in a breaking way in any release, including patch releases.\n */\n fetchPerpsBook(request: FetchPerpsBookRequest): Promise<PerpsBook>;\n\n /**\n * Lists Perps candles for an instrument with SDK-owned pagination.\n *\n * @example\n * ```ts\n * for await (const candles of client.listPerpsCandles({\n * instrumentId: 1,\n * interval: PerpsKlineInterval.OneMinute,\n * })) {\n * console.log(candles);\n * }\n * ```\n *\n * @throws {@link ListPerpsCandlesError}\n * Thrown on failure.\n *\n * @experimental This API may change in a breaking way in any release, including patch releases.\n */\n listPerpsCandles(request: ListPerpsCandlesRequest): Paginated<PerpsCandle[]>;\n\n /**\n * Lists Perps funding-rate history for an instrument with SDK-owned pagination.\n *\n * @example\n * ```ts\n * for await (const rates of client.listPerpsFundingHistory({\n * instrumentId: 1,\n * })) {\n * console.log(rates);\n * }\n * ```\n *\n * @throws {@link ListPerpsFundingHistoryError}\n * Thrown on failure.\n *\n * @experimental This API may change in a breaking way in any release, including patch releases.\n */\n listPerpsFundingHistory(\n request: ListPerpsFundingHistoryRequest,\n ): Paginated<PerpsFundingRate[]>;\n\n /**\n * Lists recent Perps trades for an instrument with SDK-owned pagination.\n *\n * @example\n * ```ts\n * for await (const trades of client.listPerpsTrades({ instrumentId: 1 })) {\n * console.log(trades);\n * }\n * ```\n *\n * @throws {@link ListPerpsTradesError}\n * Thrown on failure.\n *\n * @experimental This API may change in a breaking way in any release, including patch releases.\n */\n listPerpsTrades(\n request: ListPerpsTradesRequest,\n ): Paginated<PerpsPublicTrade[]>;\n\n /**\n * Fetches the Perps fee schedule.\n *\n * @example\n * ```ts\n * const fees = await client.fetchPerpsFees();\n * ```\n *\n * @throws {@link FetchPerpsFeesError}\n * Thrown on failure.\n *\n * @experimental This API may change in a breaking way in any release, including patch releases.\n */\n fetchPerpsFees(): Promise<PerpsFeeScheduleEntry[]>;\n};\n\n/**\n * @experimental This API may change in a breaking way in any release, including patch releases.\n */\nexport type SecurePerpsActions = PublicPerpsActions & {\n /**\n * Deposits collateral into Perps for the authenticated signer account.\n *\n * @example\n * ```ts\n * const transaction = await client.depositToPerps({ amount: 100_000_000n });\n * ```\n *\n * @throws {@link DepositToPerpsError}\n * Thrown on failure.\n *\n * @experimental This API may change in a breaking way in any release, including patch releases.\n */\n depositToPerps(request: DepositToPerpsRequest): Promise<TransactionHandle>;\n\n /**\n * Opens a Perps account session.\n *\n * @remarks\n * Omit `expiresIn` to create new delegated Perps credentials that expire after\n * one week. Pass `expiresIn` as a duration in milliseconds to use a shorter or\n * longer credential lifetime, or pass existing credentials to validate and\n * resume a previous session.\n *\n * @example\n * ```ts\n * const session = await client.openPerpsSession();\n * ```\n *\n * @throws {@link OpenPerpsSessionError}\n * Thrown on failure.\n *\n * @experimental This API may change in a breaking way in any release, including patch releases.\n */\n openPerpsSession(request?: OpenPerpsSessionRequest): Promise<PerpsSession>;\n\n /**\n * Revokes delegated Perps credentials by proxy address.\n *\n * @remarks\n * This can revoke credentials outside the currently open Perps session.\n *\n * @example\n * ```ts\n * await client.revokePerpsCredentials({ proxy: session.credentials.proxy });\n * ```\n *\n * @throws {@link RevokePerpsCredentialsError}\n * Thrown on failure.\n *\n * @experimental This API may change in a breaking way in any release, including patch releases.\n */\n revokePerpsCredentials(request: RevokePerpsCredentialsRequest): Promise<void>;\n\n /**\n * Requests a Perps withdrawal to the authenticated wallet.\n *\n * @example\n * ```ts\n * const withdrawalId = await client.withdrawFromPerps({ amount: 100_000_000n });\n * ```\n *\n * @throws {@link WithdrawFromPerpsError}\n * Thrown on failure.\n *\n * @experimental This API may change in a breaking way in any release, including patch releases.\n */\n withdrawFromPerps(\n request: WithdrawFromPerpsRequest,\n ): Promise<PerpsWithdrawalId>;\n};\n\n/**\n * @experimental This API may change in a breaking way in any release, including patch releases.\n */\nexport type PerpsActions = PublicPerpsActions;\n\n/**\n * @experimental This API may change in a breaking way in any release, including patch releases.\n */\nexport function perpsActions(client: BasePublicClient): PublicPerpsActions;\n/**\n * @experimental This API may change in a breaking way in any release, including patch releases.\n */\nexport function perpsActions(client: BaseSecureClient): SecurePerpsActions;\n/**\n * @experimental This API may change in a breaking way in any release, including patch releases.\n */\nexport function perpsActions(\n client: BaseClient,\n): PublicPerpsActions | SecurePerpsActions {\n const actions: PublicPerpsActions = {\n fetchPerpsBook: (request) => fetchPerpsBook(client, request),\n fetchPerpsFees: () => fetchPerpsFees(client),\n fetchPerpsInstruments: (request) => fetchPerpsInstruments(client, request),\n fetchPerpsTicker: (request) => fetchPerpsTicker(client, request),\n fetchPerpsTickers: (request) => fetchPerpsTickers(client, request),\n listPerpsCandles: (request) => listPerpsCandles(client, request),\n listPerpsFundingHistory: (request) =>\n listPerpsFundingHistory(client, request),\n listPerpsTrades: (request) => listPerpsTrades(client, request),\n };\n\n if (!client.isSecureClient()) return actions;\n\n return {\n ...actions,\n depositToPerps: (request) => depositToPerps(client, request),\n openPerpsSession: (request) => openPerpsSession(client, request),\n revokePerpsCredentials: (request) =>\n revokePerpsCredentials(client, request),\n withdrawFromPerps: (request) => withdrawFromPerps(client, request),\n };\n}\n","import type {\n CurrentReward,\n MarketReward,\n OrdersScoringResponse,\n RewardsPercentages,\n TotalUserEarning,\n UserEarning,\n UserRewardsEarning,\n} from '@polymarket/bindings/clob';\nimport type { Prettify } from '@polymarket/types';\nimport {\n type FetchOrderScoringRequest,\n type FetchOrdersScoringRequest,\n type FetchTotalEarningsForUserForDayRequest,\n fetchOrderScoring,\n fetchOrdersScoring,\n fetchRewardPercentages,\n fetchTotalEarningsForUserForDay,\n type ListCurrentRewardsRequest,\n type ListMarketRewardsRequest,\n type ListUserEarningsAndMarketsConfigRequest,\n type ListUserEarningsForDayRequest,\n listCurrentRewards,\n listMarketRewards,\n listUserEarningsAndMarketsConfig,\n listUserEarningsForDay,\n} from '../actions';\nimport type {\n BaseClient,\n BasePublicClient,\n BaseSecureClient,\n} from '../clients';\nimport type { Paginated } from '../pagination';\n\nexport type PublicRewardsActions = {\n /**\n * Lists current active market rewards.\n *\n * @throws {@link ListCurrentRewardsError}\n * Thrown on failure.\n *\n * @example\n * Fetch the first page of results:\n * ```ts\n * const paginator = client.listCurrentRewards();\n *\n * const firstPage = await paginator.firstPage();\n *\n * // Optionally, fetch additional pages:\n * for await (const page of paginator.from(firstPage.nextCursor)) {\n * // page.items: CurrentReward[]\n * }\n * ```\n *\n * @example\n * Loop through all pages with `for await`:\n * ```ts\n * const paginator = client.listCurrentRewards();\n *\n * for await (const page of paginator) {\n * // page.items: CurrentReward[]\n * }\n * ```\n */\n listCurrentRewards(\n request?: ListCurrentRewardsRequest,\n ): Paginated<CurrentReward[]>;\n /**\n * Lists reward configurations for a market.\n *\n * @throws {@link ListMarketRewardsError}\n * Thrown on failure.\n *\n * @example\n * Fetch the first page of results:\n * ```ts\n * const paginator = client.listMarketRewards({\n * conditionId:\n * '0xbd31dc8a20211944f6b70f31557f1001557b59905b7738480ca09bd4532f84af',\n * });\n *\n * const firstPage = await paginator.firstPage();\n *\n * // Optionally, fetch additional pages:\n * for await (const page of paginator.from(firstPage.nextCursor)) {\n * // page.items: MarketReward[]\n * }\n * ```\n *\n * @example\n * Loop through all pages with `for await`:\n * ```ts\n * const paginator = client.listMarketRewards({\n * conditionId:\n * '0xbd31dc8a20211944f6b70f31557f1001557b59905b7738480ca09bd4532f84af',\n * });\n *\n * for await (const page of paginator) {\n * // page.items: MarketReward[]\n * }\n * ```\n */\n listMarketRewards(\n request: ListMarketRewardsRequest,\n ): Paginated<MarketReward[]>;\n};\n\nexport type SecureRewardsActions = Prettify<\n PublicRewardsActions & {\n /**\n * Fetches whether a single order is currently scoring.\n *\n * @throws {@link FetchOrderScoringError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const scoring = await client.fetchOrderScoring({\n * orderId: '123',\n * });\n * ```\n */\n fetchOrderScoring(request: FetchOrderScoringRequest): Promise<boolean>;\n /**\n * Fetches scoring state for multiple orders.\n *\n * @throws {@link FetchOrdersScoringError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const scoring = await client.fetchOrdersScoring({\n * orderIds: ['1', '2'],\n * });\n * ```\n */\n fetchOrdersScoring(\n request: FetchOrdersScoringRequest,\n ): Promise<OrdersScoringResponse>;\n /**\n * Lists per-market earnings for the authenticated account on a given day.\n *\n * @throws {@link ListUserEarningsForDayError}\n * Thrown on failure.\n *\n * @example\n * Fetch the first page of results:\n * ```ts\n * const paginator = client.listUserEarningsForDay({\n * date: '2026-04-16',\n * });\n *\n * const firstPage = await paginator.firstPage();\n *\n * // Optionally, fetch additional pages:\n * for await (const page of paginator.from(firstPage.nextCursor)) {\n * // page.items: UserEarning[]\n * }\n * ```\n *\n * @example\n * Loop through all pages with `for await`:\n * ```ts\n * const paginator = client.listUserEarningsForDay({\n * date: '2026-04-16',\n * });\n *\n * for await (const page of paginator) {\n * // page.items: UserEarning[]\n * }\n * ```\n */\n listUserEarningsForDay(\n request: ListUserEarningsForDayRequest,\n ): Paginated<UserEarning[]>;\n /**\n * Fetches total earnings for the authenticated account on a given day.\n *\n * @throws {@link FetchTotalEarningsForUserForDayError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const earnings = await client.fetchTotalEarningsForUserForDay({\n * date: '2026-04-16',\n * });\n * ```\n */\n fetchTotalEarningsForUserForDay(\n request: FetchTotalEarningsForUserForDayRequest,\n ): Promise<TotalUserEarning[]>;\n /**\n * Lists market reward configuration and earnings for the authenticated account on a given day.\n *\n * @throws {@link ListUserEarningsAndMarketsConfigError}\n * Thrown on failure.\n *\n * @example\n * Fetch the first page of results:\n * ```ts\n * const paginator = client.listUserEarningsAndMarketsConfig({\n * date: '2026-04-16',\n * });\n *\n * const firstPage = await paginator.firstPage();\n *\n * // Optionally, fetch additional pages:\n * for await (const page of paginator.from(firstPage.nextCursor)) {\n * // page.items: UserRewardsEarning[]\n * }\n * ```\n *\n * @example\n * Loop through all pages with `for await`:\n * ```ts\n * const paginator = client.listUserEarningsAndMarketsConfig({\n * date: '2026-04-16',\n * });\n *\n * for await (const page of paginator) {\n * // page.items: UserRewardsEarning[]\n * }\n * ```\n */\n listUserEarningsAndMarketsConfig(\n request: ListUserEarningsAndMarketsConfigRequest,\n ): Paginated<UserRewardsEarning[]>;\n /**\n * Fetches reward percentages for the authenticated account.\n *\n * @throws {@link FetchRewardPercentagesError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const percentages = await client.fetchRewardPercentages();\n * ```\n */\n fetchRewardPercentages(): Promise<RewardsPercentages>;\n }\n>;\n\nfunction publicRewardsActions(client: BaseClient): PublicRewardsActions {\n return {\n listCurrentRewards: listCurrentRewards.bind(null, client),\n listMarketRewards: listMarketRewards.bind(null, client),\n };\n}\n\nexport function rewardsActions(client: BasePublicClient): PublicRewardsActions;\nexport function rewardsActions(client: BaseSecureClient): SecureRewardsActions;\nexport function rewardsActions(\n client: BaseClient,\n): PublicRewardsActions | SecureRewardsActions {\n const actions = publicRewardsActions(client);\n\n if (client.isPublicClient()) {\n return actions;\n }\n\n return {\n ...actions,\n fetchOrderScoring: fetchOrderScoring.bind(null, client),\n fetchOrdersScoring: fetchOrdersScoring.bind(null, client),\n listUserEarningsForDay: listUserEarningsForDay.bind(null, client),\n fetchTotalEarningsForUserForDay: fetchTotalEarningsForUserForDay.bind(\n null,\n client,\n ),\n listUserEarningsAndMarketsConfig: listUserEarningsAndMarketsConfig.bind(\n null,\n client,\n ),\n fetchRewardPercentages: fetchRewardPercentages.bind(null, client),\n };\n}\n\n// Error unions and runtime `isError` guards for every action bound above.\n// Surfaced at the root entry point through `export * from './decorators'`.\n// Keep this list in sync with the methods on PublicRewardsActions / SecureRewardsActions.\nexport {\n FetchOrderScoringError,\n FetchOrdersScoringError,\n FetchRewardPercentagesError,\n FetchTotalEarningsForUserForDayError,\n ListCurrentRewardsError,\n ListMarketRewardsError,\n ListUserEarningsAndMarketsConfigError,\n ListUserEarningsForDayError,\n} from '../actions';\n","import type {\n AcceptComboQuoteParams,\n AcceptComboQuoteResult,\n RequestComboQuoteParams,\n RequestComboQuoteResult,\n RfqSession,\n WaitForComboFillParams,\n WaitForComboFillResult,\n} from '../actions';\nimport {\n acceptComboQuote,\n openRfqSession,\n requestComboQuote,\n waitForComboFill,\n} from '../actions';\nimport type { BaseSecureClient } from '../clients';\n\nexport type {\n BuilderRfqError,\n ComboQuote,\n FetchRfqStatusParams,\n RfqCancelQuoteAck,\n RfqCancelQuoteRejectedErrorOptions,\n RfqConfirmationAck,\n RfqConfirmationRequest,\n RfqConfirmationRequestEvent,\n RfqErrorCode,\n RfqEvent,\n RfqExecutionUpdate,\n RfqId,\n RfqQuoteId,\n RfqQuoteReference,\n RfqQuoteRejectedErrorOptions,\n RfqQuoteRequest,\n RfqQuoteRequestEvent,\n RfqQuoteResponse,\n RfqQuoteSource,\n RfqRequestedSize,\n RfqRequestorPublicId,\n RfqRequestRejectedErrorOptions,\n RfqSession,\n RfqStatusResult,\n RfqTrade,\n RfqTradeEvent,\n} from '../actions/rfq';\nexport {\n AcceptComboQuoteError,\n ComboAcceptFailureReason,\n ComboQuoteUnavailableReason,\n FetchRfqStatusError,\n OpenRfqSessionError,\n RequestComboQuoteError,\n RfqCancelQuoteError,\n RfqCancelQuoteRejectedError,\n RfqConfirmationDecision,\n RfqConfirmationError,\n RfqConfirmationRejectedError,\n RfqDirection,\n RfqExecutionStatus,\n RfqKnownErrorCode,\n RfqQuoteError,\n RfqQuoteRejectedError,\n RfqRejectionCode,\n RfqRequestedSizeUnit,\n RfqRequestRejectedError,\n RfqSide,\n RfqStatus,\n WaitForComboFillError,\n} from '../actions/rfq';\nexport type {\n AcceptComboQuoteParams,\n AcceptComboQuoteResult,\n RequestComboQuoteParams,\n RequestComboQuoteResult,\n WaitForComboFillParams,\n WaitForComboFillResult,\n};\n\nexport type SecureRfqActions = {\n /**\n * Opens an RFQ event session.\n *\n * @remarks\n * The returned async iterator is a stream, not a worker queue. Await inside the\n * loop to process RFQ events sequentially, or dispatch handlers without awaiting\n * them to fan out handling when quote windows are tight.\n *\n * @example\n * Quote the full requested size:\n * ```ts\n * const session = await client.openRfqSession();\n *\n * for await (const event of session) {\n * switch (event.type) {\n * case 'quote_request':\n * await event.quote({ price: 0.45 });\n * break;\n *\n * case 'execution_update':\n * // event.rfqId: RfqId\n * // event.status: RfqExecutionStatus\n * // event.txHash: TxHash | undefined\n * break;\n * }\n * }\n * ```\n *\n * @example\n * Quote a specific outcome-token size. `0.5` means half of one share, not\n * half of one 6-decimal base unit:\n * ```ts\n * const session = await client.openRfqSession();\n *\n * for await (const event of session) {\n * switch (event.type) {\n * case 'quote_request':\n * await event.quote({ price: 0.45, size: 0.5 });\n * break;\n *\n * // …\n * }\n * }\n * ```\n *\n * @example\n * Cancel a submitted quote using the live session:\n * ```ts\n * const session = await client.openRfqSession();\n *\n * for await (const event of session) {\n * switch (event.type) {\n * case 'quote_request': {\n * const ref = await event.quote({ price: 0.45 });\n *\n * if (shouldCancel(ref)) {\n * await session.cancelQuote(ref);\n * }\n * break;\n * }\n *\n * // …\n * }\n * }\n * ```\n * The cancellation ack means the backend processed the request; it does not\n * guarantee the quote was withdrawn from an already-selected RFQ.\n *\n * @example\n * Handle Last Look confirmation requests:\n * ```ts\n * const session = await client.openRfqSession();\n *\n * for await (const event of session) {\n * switch (event.type) {\n * case 'quote_request':\n * await event.quote({ price: 0.45 });\n * break;\n *\n * case 'confirmation_request':\n * await event.confirm();\n * break;\n *\n * // …\n * }\n * }\n * ```\n * Any maker can quote permissionlessly. Last Look confirmation requests are\n * only sent to makers with Last Look enabled.\n *\n * @example\n * Choose collateral or inventory per request:\n * ```ts\n * const session = await client.openRfqSession();\n *\n * for await (const event of session) {\n * switch (event.type) {\n * case 'quote_request': {\n * switch (event.direction) {\n * case RfqDirection.Buy:\n * await event.quote({\n * price: 0.45,\n * source: chooseSource(event.yesPositionId, event.requestedSize),\n * });\n * break;\n *\n * case RfqDirection.Sell:\n * await event.quote({\n * price: 0.45,\n * source: chooseSource(event.noPositionId, event.requestedSize),\n * });\n * break;\n * }\n * break;\n * }\n *\n * case 'confirmation_request':\n * await event.confirm();\n * break;\n *\n * // …\n * }\n * }\n *\n * function chooseSource(positionId: PositionId, requestedSize: RfqRequestedSize): RfqQuoteSource {\n * return hasInventory(positionId, requestedSize) ? 'inventory' : 'collateral';\n * }\n * ```\n *\n * @throws {@link OpenRfqSessionError}\n * Thrown on failure.\n */\n openRfqSession(): Promise<RfqSession>;\n\n /**\n * Requests a quote for a combo of positions.\n *\n * @remarks\n * Resolves when the quote competition window closes. A request that\n * attracts no usable quotes is a normal outcome, returned as `quote: null`\n * with a reason rather than thrown.\n *\n * A winning quote is self-contained JSON data and may be persisted or\n * routed to another process before acceptance.\n *\n * Requires a Builder API Key in the client configuration, via\n * `builderApiKey(...)` or `remoteBuilderSigning(...)`.\n *\n * @throws {@link RequestComboQuoteError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const result = await client.requestComboQuote({\n * legPositionIds: ['123', '456'],\n * direction: OrderSide.BUY,\n * amount: 100,\n * });\n *\n * if (result.quote !== null) {\n * // result.quote.blendedPrice: DecimalString\n * // result.quote.totalRequired: DecimalString\n * // SELL quotes also carry result.quote.netReceive after fees.\n * // result.quote.expiresAt: EpochMilliseconds\n * }\n * ```\n */\n requestComboQuote(\n params: RequestComboQuoteParams,\n ): Promise<RequestComboQuoteResult>;\n\n /**\n * Accepts a self-contained combo quote, signing the acceptance order for\n * the authenticated account.\n *\n * @remarks\n * Resolves at the maker last-look outcome. A maker declining or the\n * acceptance window expiring is a normal outcome, returned as\n * `status: 'failed'`. `status: 'executing'` means the trade was handed off\n * for onchain execution; follow it with `waitForComboFill`.\n *\n * A transport failure or unrecognized acceptance response is retried once\n * automatically; this is safe because an already-accepted RFQ reports its\n * current status instead of executing twice. After such a retry\n * `takerOrderHash` is absent because the retried order was not the one\n * recorded.\n *\n * The quote is JSON-serializable and may cross process boundaries before\n * acceptance. The accepting client must represent the same account and\n * builder identity used to request it.\n * Treat the quote as signing-sensitive data: preserve its integrity across\n * process boundaries and do not accept fields modified by an untrusted client.\n *\n * @throws {@link AcceptComboQuoteError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const result = await client.requestComboQuote({\n * legPositionIds: ['123', '456'],\n * direction: OrderSide.BUY,\n * amount: 100,\n * });\n *\n * if (result.quote !== null) {\n * const acceptance = await client.acceptComboQuote(result.quote);\n * }\n * ```\n */\n acceptComboQuote(\n params: AcceptComboQuoteParams,\n ): Promise<AcceptComboQuoteResult>;\n\n /**\n * Waits for an accepted RFQ to reach a terminal state.\n *\n * @remarks\n * Polls the RFQ status until it is filled (or confirmed onchain),\n * `FAILED`, `EXPIRED`, or `CANCELED`. Terminal failure is a normal outcome\n * and is returned, not thrown. A `TimeoutError` does not mean the trade\n * failed; resume with the `fetchRfqStatus` action from\n * `@polymarket/client/actions`.\n *\n * @throws {@link WaitForComboFillError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const fill = await client.waitForComboFill({ rfqId });\n *\n * if (fill.status === RfqStatus.Filled) {\n * // fill.txHash: TxHash\n * }\n * ```\n */\n waitForComboFill(\n params: WaitForComboFillParams,\n ): Promise<WaitForComboFillResult>;\n};\n\nexport function rfqActions(client: BaseSecureClient): SecureRfqActions {\n return {\n openRfqSession() {\n return openRfqSession(client);\n },\n requestComboQuote(params: RequestComboQuoteParams) {\n return requestComboQuote(client, params);\n },\n acceptComboQuote(params: AcceptComboQuoteParams) {\n return acceptComboQuote(client, params);\n },\n waitForComboFill(params: WaitForComboFillParams) {\n return waitForComboFill(client, params);\n },\n };\n}\n","import {\n type AuthorizeSessionKeyRequest,\n type AuthorizeSessionKeyResult,\n authorizeSessionKey,\n fetchSessionKeys,\n type RevokeSessionKeyRequest,\n revokeSessionKey,\n type SessionKey,\n} from '../actions';\nimport type { BaseSecureClient } from '../clients';\n\nexport type SessionKeyActions = {\n /**\n * Authorizes an externally managed signer for selected venues.\n *\n * The SDK receives only the public address. The application remains\n * responsible for generating, storing, and protecting the private key.\n * When scopes are omitted, authorization defaults to `ALL`.\n * The authorization expires 180 days after it is created.\n * Requires builder API-key authentication.\n *\n * @remarks\n * Resolves after the submitted transaction is confirmed and the session key\n * appears in the active session-key list.\n *\n * @example\n * ```ts\n * const authorization = await client.authorizeSessionKey({\n * address: sessionAddress,\n * });\n * ```\n *\n * @throws {@link AuthorizeSessionKeyError}\n * Thrown on failure.\n */\n authorizeSessionKey(\n request: AuthorizeSessionKeyRequest,\n ): Promise<AuthorizeSessionKeyResult>;\n\n /**\n * Fetches the active session keys authorized for the Deposit Wallet.\n *\n * @example\n * ```ts\n * const sessionKeys = await client.fetchSessionKeys();\n * ```\n *\n * @throws {@link FetchSessionKeysError}\n * Thrown on failure.\n */\n fetchSessionKeys(): Promise<SessionKey[]>;\n\n /**\n * Revokes a session key authorized for the Deposit Wallet.\n *\n * Returns once the session key is removed from the active-key registry and can\n * no longer be used. The on-chain transaction may still be pending.\n * Requires API-key authentication that supports gasless transactions.\n *\n * @example\n * ```ts\n * await client.revokeSessionKey({\n * address: sessionAddress,\n * });\n * ```\n *\n * @throws {@link RevokeSessionKeyError}\n * Thrown on failure.\n */\n revokeSessionKey(request: RevokeSessionKeyRequest): Promise<void>;\n};\n\nexport function sessionKeyActions(client: BaseSecureClient): SessionKeyActions {\n return {\n authorizeSessionKey: authorizeSessionKey.bind(null, client),\n fetchSessionKeys: fetchSessionKeys.bind(null, client),\n revokeSessionKey: revokeSessionKey.bind(null, client),\n };\n}\n\nexport type {\n AuthorizeSessionKeyRequest,\n AuthorizeSessionKeyResult,\n RevokeSessionKeyRequest,\n SessionKey,\n SessionKeyScope,\n} from '../actions';\nexport {\n AuthorizeSessionKeyError,\n FetchSessionKeysError,\n RevokeSessionKeyError,\n SessionKeyKnownScope,\n} from '../actions';\n","import {\n type EventForSubscriptionSpecs,\n type PublicSubscriptionSpec,\n type SecureSubscriptionSpec,\n type SubscriptionHandle,\n subscribe,\n} from '../actions';\nimport type {\n BaseClient,\n BasePublicClient,\n BaseSecureClient,\n} from '../clients';\n\nexport type {\n CryptoPricesChainlinkTwapEvent,\n CryptoPricesChainlinkTwapSixtyEvent,\n CryptoPricesChainlinkTwapSubscription,\n CryptoPricesChainlinkTwapThirtyEvent,\n CryptoPricesChainlinkTwapWindowSeconds,\n} from '../actions';\nexport { SubscribeError } from '../actions';\n\nexport type PublicSubscriptionsActions = {\n /**\n * Starts one or more realtime subscriptions on this client.\n *\n * @throws {@link SubscribeError}\n * Thrown when subscription input is invalid or a realtime subscription fails.\n *\n * @example\n * ```ts\n * const handle = await client.subscribe([\n * { topic: 'market', assetIds: ['123'] },\n * ]);\n *\n * for await (const event of handle) {\n * // event: StandardMarketEvent\n * }\n * ```\n */\n subscribe<const TSubscriptions extends readonly PublicSubscriptionSpec[]>(\n subscriptions: TSubscriptions,\n ): Promise<SubscriptionHandle<EventForSubscriptionSpecs<TSubscriptions>>>;\n};\n\nexport type SecureSubscriptionsActions = {\n /**\n * Starts one or more realtime subscriptions on this client.\n *\n * @throws {@link SubscribeError}\n * Thrown when subscription input is invalid or a realtime subscription fails.\n *\n * @example\n * ```ts\n * const handle = await client.subscribe([\n * { topic: 'user' },\n * { topic: 'market', assetIds: ['123'] },\n * ]);\n *\n * for await (const event of handle) {\n * // event: StandardMarketEvent | UserEvent\n * }\n * ```\n */\n subscribe<const TSubscriptions extends readonly SecureSubscriptionSpec[]>(\n subscriptions: TSubscriptions,\n ): Promise<SubscriptionHandle<EventForSubscriptionSpecs<TSubscriptions>>>;\n};\n\nexport function subscriptionsActions(\n client: BasePublicClient,\n): PublicSubscriptionsActions;\nexport function subscriptionsActions(\n client: BaseSecureClient,\n): SecureSubscriptionsActions;\nexport function subscriptionsActions(\n client: BaseClient,\n): PublicSubscriptionsActions | SecureSubscriptionsActions {\n // Wrap instead of `bind` so the method preserves its generic type parameter\n // and can narrow the resolved event type per call site.\n if (client.isSecureClient()) {\n return {\n subscribe<const TSubscriptions extends readonly SecureSubscriptionSpec[]>(\n subscriptions: TSubscriptions,\n ): Promise<\n SubscriptionHandle<EventForSubscriptionSpecs<TSubscriptions>>\n > {\n return subscribe(client, subscriptions);\n },\n };\n }\n\n return {\n subscribe<const TSubscriptions extends readonly PublicSubscriptionSpec[]>(\n subscriptions: TSubscriptions,\n ): Promise<SubscriptionHandle<EventForSubscriptionSpecs<TSubscriptions>>> {\n return subscribe(client, subscriptions);\n },\n };\n}\n","import type {\n AcceptedOrderResponse,\n CancelOrdersResponse,\n OpenOrder,\n OrderResponse,\n OrderResponses,\n} from '@polymarket/bindings/clob';\nimport type { TxHash } from '@polymarket/types';\nimport {\n type CancelMarketOrdersRequest,\n type CancelOrderRequest,\n type CancelOrdersRequest,\n cancelAll,\n cancelMarketOrders,\n cancelOrder,\n cancelOrders,\n createLimitOrder,\n createMarketOrder,\n type FetchOrderRequest,\n fetchOrder,\n type ListOpenOrdersRequest,\n listOpenOrders,\n type PostOrdersRequest,\n type PrepareLimitOrderRequest,\n type PrepareMarketOrderRequest,\n placeLimitOrder,\n placeMarketOrder,\n postOrder,\n postOrders,\n type WaitForOrderFillSettlementRequest,\n waitForOrderFillSettlement,\n} from '../actions';\nimport type { SignedOrder } from '../actions/orders';\nimport type { BaseSecureClient } from '../clients';\nimport type { Paginated } from '../pagination';\n\nexport type { OrderSignature, SignedOrder } from '../actions';\n\nexport type SecureTradingActions = {\n /**\n * Creates a signed market order for the authenticated account.\n *\n * @throws {@link CreateMarketOrderError}\n * Thrown on failure.\n *\n * @example Basic market buy\n * ```ts\n * const order = await client.createMarketOrder({\n * assetId: '0x0122…0000',\n * amount: 10,\n * side: OrderSide.BUY,\n * });\n * ```\n *\n * @example Protected market buy\n * ```ts\n * const order = await client.createMarketOrder({\n * assetId: '0x0122…0000',\n * amount: 10,\n * maxPrice: '0.55',\n * side: OrderSide.BUY,\n * });\n * ```\n *\n * @example Polymarket V2 market buy\n * ```ts\n * const order = await client.createMarketOrder({\n * assetId: '0x0122…0000',\n * amount: 10,\n * side: OrderSide.BUY,\n * });\n * ```\n */\n createMarketOrder(request: PrepareMarketOrderRequest): Promise<SignedOrder>;\n /**\n * Creates and posts a market order for the authenticated account.\n *\n * @remarks\n * Settlement happens asynchronously, so a matched response is not\n * guaranteed to carry settlement transaction hashes. Use\n * `waitForOrderFillSettlement` to obtain them reliably.\n *\n * @throws {@link PlaceMarketOrderError}\n * Thrown on failure.\n *\n * @example Basic market buy\n * ```ts\n * const response = await client.placeMarketOrder({\n * assetId: '0x0122…0000',\n * amount: 10,\n * side: OrderSide.BUY,\n * });\n *\n * // response: OrderResponse\n * ```\n *\n * @example Protected market sell\n * ```ts\n * const response = await client.placeMarketOrder({\n * assetId: '0x0122…0000',\n * minPrice: '0.54',\n * shares: 10,\n * side: OrderSide.SELL,\n * });\n *\n * // response: OrderResponse\n * ```\n *\n * @example Market buy followed to settlement\n * ```ts\n * const response = await client.placeMarketOrder({\n * assetId: '0x0122…0000',\n * amount: 10,\n * side: OrderSide.BUY,\n * });\n *\n * if (response.ok) {\n * const hashes = await client.waitForOrderFillSettlement(response);\n * // hashes: TxHash[]\n * }\n * ```\n */\n placeMarketOrder(request: PrepareMarketOrderRequest): Promise<OrderResponse>;\n /**\n * Creates a signed limit order for the authenticated account.\n *\n * @remarks\n * GTD expirations must be at least 3 minutes in the future. Add your own\n * buffer for network latency and clock skew when deriving an expiration from\n * the current time.\n *\n * @throws {@link CreateLimitOrderError}\n * Thrown on failure.\n *\n * @example CTF limit order\n * ```ts\n * const order = await client.createLimitOrder({\n * assetId: '0x0122…0000',\n * postOnly: true,\n * price: 0.52,\n * side: OrderSide.BUY,\n * size: 10,\n * });\n * ```\n *\n * @example Polymarket V2 limit order\n * ```ts\n * const order = await client.createLimitOrder({\n * assetId: '0x0122…0000',\n * postOnly: true,\n * price: 0.52,\n * side: OrderSide.BUY,\n * size: 10,\n * });\n * ```\n */\n createLimitOrder(request: PrepareLimitOrderRequest): Promise<SignedOrder>;\n /**\n * Creates and posts a limit order for the authenticated account.\n *\n * @remarks\n * GTD expirations must be at least 3 minutes in the future. Add your own\n * buffer for network latency and clock skew when deriving an expiration from\n * the current time.\n *\n * @throws {@link PlaceLimitOrderError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const response = await client.placeLimitOrder({\n * assetId: '0x0122…0000',\n * postOnly: true,\n * price: 0.52,\n * side: OrderSide.BUY,\n * size: 10,\n * });\n *\n * // response: OrderResponse\n * ```\n */\n placeLimitOrder(request: PrepareLimitOrderRequest): Promise<OrderResponse>;\n /**\n * Posts a signed order for the authenticated account.\n *\n * @throws {@link PostOrderError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const response = await client.postOrder(signedOrder);\n * ```\n */\n postOrder(order: SignedOrder): Promise<OrderResponse>;\n /**\n * Posts multiple signed orders for the authenticated account.\n *\n * @remarks\n * Accepts between 1 and 15 orders, matching the current service limit.\n *\n * @throws {@link PostOrdersError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const responses = await client.postOrders([firstSignedOrder, secondSignedOrder]);\n * ```\n */\n postOrders(orders: PostOrdersRequest): Promise<OrderResponses>;\n /**\n * Waits until every fill listed in an order response reaches a terminal\n * settlement outcome and returns the settlement transaction hashes.\n *\n * @remarks\n * Settlement covers the fills listed in this order response. These are the\n * fills that happened immediately when the order was accepted. It does not\n * wait for later fills of any remaining quantity resting on the book;\n * subscribe to the `user` channel to follow those.\n *\n * @throws {@link WaitForOrderFillSettlementError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const response = await client.placeMarketOrder({\n * assetId: '0x0122…0000',\n * amount: 10,\n * side: OrderSide.BUY,\n * });\n *\n * if (response.ok) {\n * const hashes = await client.waitForOrderFillSettlement(response);\n * // hashes: TxHash[]\n * }\n * ```\n */\n waitForOrderFillSettlement(\n order: AcceptedOrderResponse,\n request?: WaitForOrderFillSettlementRequest,\n ): Promise<TxHash[]>;\n /**\n * Cancels a single open order for the authenticated account.\n *\n * @throws {@link CancelOrderError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const response = await client.cancelOrder({ orderId: '123' });\n *\n * // response.canceled: OrderId[]\n * ```\n */\n cancelOrder(request: CancelOrderRequest): Promise<CancelOrdersResponse>;\n /**\n * Cancels multiple open orders for the authenticated account.\n *\n * @throws {@link CancelOrdersError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const response = await client.cancelOrders({ orderIds: ['1', '2'] });\n *\n * // response.canceled: OrderId[]\n * ```\n */\n cancelOrders(request: CancelOrdersRequest): Promise<CancelOrdersResponse>;\n /**\n * Cancels all open orders for the authenticated account.\n *\n * @throws {@link CancelAllError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const response = await client.cancelAll();\n *\n * // response.canceled: OrderId[]\n * ```\n */\n cancelAll(): Promise<CancelOrdersResponse>;\n /**\n * Cancels all open orders for the authenticated account that match the market or asset filter.\n *\n * @throws {@link CancelMarketOrdersError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const response = await client.cancelMarketOrders({\n * market: '0x0000000000000000000000000000000000000000000000000000000000000001',\n * });\n *\n * // response.canceled: OrderId[]\n * ```\n */\n cancelMarketOrders(\n request: CancelMarketOrdersRequest,\n ): Promise<CancelOrdersResponse>;\n /**\n * Lists open orders for the authenticated account across all pages.\n *\n * @throws {@link ListOpenOrdersError}\n * Thrown on failure.\n *\n * @example\n * Fetch the first page of results:\n * ```ts\n * const paginator = client.listOpenOrders({\n * market: '0x0000000000000000000000000000000000000000000000000000000000000001',\n * });\n *\n * const firstPage = await paginator.firstPage();\n *\n * // Optionally, fetch additional pages:\n * for await (const page of paginator.from(firstPage.nextCursor)) {\n * // page.items: OpenOrder[]\n * }\n * ```\n *\n * @example\n * Loop through all pages with `for await`:\n * ```ts\n * const paginator = client.listOpenOrders({\n * market: '0x0000000000000000000000000000000000000000000000000000000000000001',\n * });\n *\n * for await (const page of paginator) {\n * // page.items: OpenOrder[]\n * }\n * ```\n */\n listOpenOrders(request?: ListOpenOrdersRequest): Paginated<OpenOrder[]>;\n /**\n * Fetches a single order for the authenticated account.\n *\n * @throws {@link FetchOrderError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const order = await client.fetchOrder({ orderId: '123' });\n * ```\n */\n fetchOrder(request: FetchOrderRequest): Promise<OpenOrder>;\n};\n\nexport function tradingActions(client: BaseSecureClient): SecureTradingActions;\nexport function tradingActions(client: BaseSecureClient): SecureTradingActions {\n return {\n createMarketOrder: createMarketOrder.bind(null, client),\n placeMarketOrder: placeMarketOrder.bind(null, client),\n createLimitOrder: createLimitOrder.bind(null, client),\n placeLimitOrder: placeLimitOrder.bind(null, client),\n postOrder: postOrder(client),\n postOrders: postOrders(client),\n waitForOrderFillSettlement: waitForOrderFillSettlement.bind(null, client),\n cancelOrder: cancelOrder.bind(null, client),\n cancelOrders: cancelOrders.bind(null, client),\n cancelAll: cancelAll.bind(null, client),\n cancelMarketOrders: cancelMarketOrders.bind(null, client),\n listOpenOrders: listOpenOrders.bind(null, client),\n fetchOrder: fetchOrder.bind(null, client),\n };\n}\n\n// Error unions and runtime `isError` guards for every action bound above.\n// Surfaced at the root entry point through `export * from './decorators'`.\n// Keep this list in sync with the methods on SecureTradingActions.\nexport {\n CancelAllError,\n CancelMarketOrdersError,\n CancelOrderError,\n CancelOrdersError,\n CreateLimitOrderError,\n CreateMarketOrderError,\n FetchOrderError,\n ListOpenOrdersError,\n PlaceLimitOrderError,\n PlaceMarketOrderError,\n PostOrderError,\n PostOrdersError,\n WaitForOrderFillSettlementError,\n} from '../actions';\n","import {\n approveErc20,\n approveErc1155ForAll,\n type CollateralReturnPlanResponse,\n type ExecuteCollateralReturnPlanRequest,\n executeCollateralReturnPlan,\n type FetchTradingApprovalsStateRequest,\n fetchTradingApprovalsState,\n mergePositions,\n type PrepareErc20ApprovalRequest,\n type PrepareErc20TransferRequest,\n type PrepareErc1155ApprovalForAllRequest,\n type PrepareMergePositionsRequest,\n type PrepareRedeemPositionsRequest,\n type PrepareSplitPositionRequest,\n planCollateralReturn,\n redeemPositions,\n setupTradingApprovals,\n splitPosition,\n type TradingApprovalsState,\n transferErc20,\n} from '../actions';\nimport type {\n BaseClient,\n BasePublicClient,\n BaseSecureClient,\n} from '../clients';\nimport type { TransactionHandle } from '../types';\n\nexport type PublicWalletActions = {\n /**\n * Reads the approvals a wallet is missing for supported trading workflows.\n *\n * This method only reads on-chain state. It does not require a signer or\n * submit transactions.\n *\n * @throws {@link FetchTradingApprovalsStateError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const state = await client.fetchTradingApprovalsState({\n * user: '0x1234…',\n * });\n * ```\n */\n fetchTradingApprovalsState(\n request: FetchTradingApprovalsStateRequest,\n ): Promise<TradingApprovalsState>;\n};\n\nexport type SecureWalletActions = {\n /**\n * Reads the approvals a wallet is missing for supported trading workflows.\n *\n * This method reads the authenticated account's wallet state. It only reads\n * on-chain state and does not submit transactions.\n *\n * @throws {@link FetchTradingApprovalsStateError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const state = await client.fetchTradingApprovalsState();\n * ```\n */\n fetchTradingApprovalsState(): Promise<TradingApprovalsState>;\n /**\n * Sets up the approvals required for trading and supported position lifecycle workflows.\n *\n * @throws {@link SetupTradingApprovalsError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * await client.setupTradingApprovals();\n * ```\n */\n setupTradingApprovals(): Promise<void>;\n /**\n * Approves ERC-20 token spending for the authenticated account.\n *\n * @throws {@link ApproveErc20Error}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const handle = await client.approveErc20({\n * amount: 'max',\n * spenderAddress: '0x1234…',\n * tokenAddress: '0x5678…',\n * });\n *\n * const outcome = await handle.wait();\n *\n * // outcome.transactionHash: TxHash\n * ```\n */\n approveErc20(\n request: PrepareErc20ApprovalRequest,\n ): Promise<TransactionHandle>;\n /**\n * Approves or revokes ERC-1155 operator access for the authenticated account.\n *\n * @throws {@link ApproveErc1155ForAllError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const handle = await client.approveErc1155ForAll({\n * operatorAddress: '0x1234…',\n * tokenAddress: '0x5678…',\n * });\n *\n * const outcome = await handle.wait();\n *\n * // outcome.transactionHash: TxHash\n * ```\n */\n approveErc1155ForAll(\n request: PrepareErc1155ApprovalForAllRequest,\n ): Promise<TransactionHandle>;\n /**\n * Transfers ERC-20 tokens from the authenticated account.\n *\n * @throws {@link TransferErc20Error}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const handle = await client.transferErc20({\n * amount: 1n,\n * recipientAddress: client.account.signer,\n * tokenAddress: client.environment.contracts.collateralToken,\n * });\n *\n * const outcome = await handle.wait();\n *\n * // outcome.transactionHash: TxHash\n * ```\n */\n transferErc20(\n request: PrepareErc20TransferRequest,\n ): Promise<TransactionHandle>;\n /**\n * Splits collateral into positions.\n *\n * @throws {@link SplitPositionError}\n * Thrown on failure.\n *\n * @example Split a market by condition ID.\n * ```ts\n * const handle = await client.splitPosition({\n * amount: 1n,\n * conditionId: '0x123…',\n * });\n *\n * const outcome = await handle.wait();\n *\n * // outcome.transactionHash: TxHash\n * ```\n *\n * @example Split a combo by legs.\n * ```ts\n * const handle = await client.splitPosition({\n * amount: 1n,\n * legs: ['123', '456'],\n * });\n *\n * const outcome = await handle.wait();\n *\n * // outcome.transactionHash: TxHash\n * ```\n */\n splitPosition(\n request: PrepareSplitPositionRequest,\n ): Promise<TransactionHandle>;\n /**\n * Merges complementary positions back into collateral.\n *\n * @throws {@link MergePositionsError}\n * Thrown on failure.\n *\n * @example Merge a market by condition ID.\n * ```ts\n * const handle = await client.mergePositions({\n * amount: 'max',\n * conditionId: '0x123…',\n * });\n *\n * const outcome = await handle.wait();\n *\n * // outcome.transactionHash: TxHash\n * ```\n *\n * @example Merge a combo by legs.\n * ```ts\n * const handle = await client.mergePositions({\n * amount: 'max',\n * legs: ['123', '456'],\n * });\n *\n * const outcome = await handle.wait();\n *\n * // outcome.transactionHash: TxHash\n * ```\n */\n mergePositions(\n request: PrepareMergePositionsRequest,\n ): Promise<TransactionHandle>;\n /**\n * Redeems held positions for a market or a specific position by ID.\n *\n * @throws {@link RedeemPositionsError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * // Redeem a market by condition ID.\n * const handle = await client.redeemPositions({\n * conditionId: '0x123…',\n * });\n *\n * const outcome = await handle.wait();\n *\n * // outcome.transactionHash: TxHash\n * ```\n *\n * @example Redeem a market by market ID.\n * ```ts\n * const handle = await client.redeemPositions({\n * marketId: '12345',\n * });\n *\n * const outcome = await handle.wait();\n *\n * // outcome.transactionHash: TxHash\n * ```\n *\n * @example Redeem a Polymarket V2 position by position ID.\n * ```ts\n * const handle = await client.redeemPositions({\n * positionId: '123',\n * });\n *\n * const outcome = await handle.wait();\n *\n * // outcome.transactionHash: TxHash\n * ```\n */\n redeemPositions(\n request: PrepareRedeemPositionsRequest,\n ): Promise<TransactionHandle>;\n /**\n * Plans a collateral return for the authenticated account.\n *\n * The returned plan is an inspectable artifact: review the collateral it\n * releases, the inputs it consumes, and the residual-position impact, and\n * apply any application-specific limits before executing it with\n * {@link SecureWalletActions.executeCollateralReturnPlan | executeCollateralReturnPlan}.\n * A truncated plan is one executable chunk of a larger return; execute and\n * confirm it before requesting the next plan.\n *\n * @throws {@link PlanCollateralReturnError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * let plan: CollateralReturnPlanResponse;\n *\n * do {\n * plan = await client.planCollateralReturn();\n *\n * // Inspect the return and residual-position impact, and apply any\n * // application-specific limits before signing.\n * const handle = await client.executeCollateralReturnPlan({ plan });\n * await handle.wait();\n * } while (plan.truncated);\n * ```\n */\n planCollateralReturn(): Promise<CollateralReturnPlanResponse>;\n /**\n * Executes a collateral return plan for the authenticated account.\n *\n * Execution signs and submits the exact call carried by the plan; nothing is\n * recomputed on the client, and no approval transactions are run implicitly.\n * Confirmation stays explicit through the returned handle's `wait()`.\n *\n * If wallet state changed since the plan was created, the service rejects\n * the submission; request a fresh plan and execute that instead.\n *\n * @throws {@link ExecuteCollateralReturnPlanError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const plan = await client.planCollateralReturn();\n *\n * const handle = await client.executeCollateralReturnPlan({ plan });\n * const outcome = await handle.wait();\n *\n * // outcome.transactionHash: TxHash\n * ```\n */\n executeCollateralReturnPlan(\n request: ExecuteCollateralReturnPlanRequest,\n ): Promise<TransactionHandle>;\n};\n\nfunction publicWalletActions(client: BaseClient): PublicWalletActions {\n return {\n fetchTradingApprovalsState: fetchTradingApprovalsState.bind(null, client),\n };\n}\n\nexport function walletActions(client: BasePublicClient): PublicWalletActions;\nexport function walletActions(client: BaseSecureClient): SecureWalletActions;\nexport function walletActions(\n client: BaseClient,\n): PublicWalletActions | SecureWalletActions {\n const actions = publicWalletActions(client);\n\n if (client.isPublicClient()) {\n return actions;\n }\n\n return {\n ...actions,\n fetchTradingApprovalsState: () =>\n fetchTradingApprovalsState(client, { user: client.account.wallet }),\n setupTradingApprovals: setupTradingApprovals.bind(null, client),\n approveErc20: approveErc20.bind(null, client),\n approveErc1155ForAll: approveErc1155ForAll.bind(null, client),\n transferErc20: transferErc20.bind(null, client),\n splitPosition: splitPosition.bind(null, client),\n mergePositions: mergePositions.bind(null, client),\n redeemPositions: redeemPositions.bind(null, client),\n planCollateralReturn: planCollateralReturn.bind(null, client),\n executeCollateralReturnPlan: executeCollateralReturnPlan.bind(null, client),\n };\n}\n\n// Public collateral-return model types surfaced alongside the bound methods.\nexport type {\n CollateralReturnOperation,\n CollateralReturnOperationKind,\n CollateralReturnPlanResponse,\n CollateralReturnPositionAmount,\n CollateralReturnPositionSummary,\n CollateralReturnRouterCall,\n Erc20TradingApproval,\n Erc1155TradingApproval,\n ExecuteCollateralReturnPlanRequest,\n FetchTradingApprovalsStateRequest,\n TradingApprovalRequirements,\n TradingApprovalsState,\n} from '../actions';\n// Error unions and runtime `isError` guards for every action bound above.\n// Surfaced at the root entry point through `export * from './decorators'`.\n// Keep this list in sync with the methods on SecureWalletActions.\nexport {\n ApproveErc20Error,\n ApproveErc1155ForAllError,\n CollateralReturnKnownOperationKind,\n ExecuteCollateralReturnPlanError,\n FetchTradingApprovalsStateError,\n MergePositionsError,\n PlanCollateralReturnError,\n RedeemPositionsError,\n SetupTradingApprovalsError,\n SplitPositionError,\n TransferErc20Error,\n} from '../actions';\n","import type { Prettify } from '@polymarket/types';\nimport type {\n BaseClient,\n BasePublicClient,\n BaseSecureClient,\n} from '../clients';\nimport {\n accountActions,\n type PublicAccountActions,\n type SecureAccountActions,\n} from './account';\nimport { type AnalyticsActions, analyticsActions } from './analytics';\nimport { type DataActions, dataActions } from './data';\nimport { type DiscoveryActions, discoveryActions } from './discovery';\nimport {\n type PublicPerpsActions,\n perpsActions,\n type SecurePerpsActions,\n} from './perps';\nimport {\n type PublicRewardsActions,\n rewardsActions,\n type SecureRewardsActions,\n} from './rewards';\nimport { rfqActions, type SecureRfqActions } from './rfq';\nimport { type SessionKeyActions, sessionKeyActions } from './session-keys';\nimport {\n type PublicSubscriptionsActions,\n type SecureSubscriptionsActions,\n subscriptionsActions,\n} from './subscriptions';\nimport { type SecureTradingActions, tradingActions } from './trading';\nimport {\n type PublicWalletActions,\n type SecureWalletActions,\n walletActions,\n} from './wallet';\n\nexport type PublicActions = Prettify<\n DiscoveryActions &\n DataActions &\n AnalyticsActions &\n PublicPerpsActions &\n PublicAccountActions &\n PublicRewardsActions &\n PublicSubscriptionsActions &\n PublicWalletActions\n>;\n\nexport type SecureActions = Prettify<\n DiscoveryActions &\n DataActions &\n AnalyticsActions &\n SecurePerpsActions &\n SecureAccountActions &\n SecureRewardsActions &\n SecureRfqActions &\n SessionKeyActions &\n SecureSubscriptionsActions &\n SecureWalletActions &\n SecureTradingActions\n>;\n\nexport function allActions(client: BasePublicClient): PublicActions;\nexport function allActions(client: BaseSecureClient): SecureActions;\nexport function allActions(client: BaseClient): PublicActions | SecureActions {\n if (client.isSecureClient()) {\n return {\n ...accountActions(client),\n ...analyticsActions(client),\n ...dataActions(client),\n ...discoveryActions(client),\n ...perpsActions(client),\n ...rewardsActions(client),\n ...rfqActions(client),\n ...sessionKeyActions(client),\n ...subscriptionsActions(client),\n ...tradingActions(client),\n ...walletActions(client),\n };\n }\n\n return {\n ...accountActions(client),\n ...analyticsActions(client),\n ...dataActions(client),\n ...discoveryActions(client),\n ...perpsActions(client),\n ...rewardsActions(client),\n ...subscriptionsActions(client),\n ...walletActions(client),\n };\n}\n\nexport * from './account';\nexport * from './analytics';\nexport * from './data';\nexport * from './discovery';\nexport * from './perps';\nexport * from './rewards';\nexport * from './rfq';\nexport * from './session-keys';\nexport * from './subscriptions';\nexport * from './trading';\nexport * from './wallet';\n","import { type EvmAddress, expectEvmAddress } from '@polymarket/types';\nimport type { Hex } from 'ox';\n\nexport type WalletDerivationConfig = {\n depositWalletFactory: EvmAddress;\n depositWalletBeacon: EvmAddress;\n depositWalletImplementation: EvmAddress;\n proxyFactory: EvmAddress;\n proxyImplementation: EvmAddress;\n safeFactory: EvmAddress;\n safeInitCodeHash: Hex.Hex;\n};\n\nexport type RestEndpoint = {\n rest: string;\n headers?: Record<string, string>;\n};\n\nexport type WebSocketEndpoint = {\n ws: string;\n headers?: Record<string, string>;\n};\n\nexport type ClobEndpoints = RestEndpoint & {\n market: WebSocketEndpoint;\n user: WebSocketEndpoint;\n};\n\nexport type CombosEndpoints = RestEndpoint &\n WebSocketEndpoint & {\n builderGateway: RestEndpoint;\n collateralReturn: RestEndpoint;\n };\n\n/**\n * @experimental This API may change in a breaking way in any release, including patch releases.\n */\nexport type PerpsEndpoints = RestEndpoint & WebSocketEndpoint;\n\nexport type EnvironmentContracts = {\n collateralToken: EvmAddress;\n conditionalTokens: EvmAddress;\n negRiskAdapter: EvmAddress;\n collateralAdapter: EvmAddress;\n negRiskCollateralAdapter: EvmAddress;\n standardExchange: EvmAddress;\n negRiskExchange: EvmAddress;\n exchangeV3: EvmAddress;\n protocolV2Router: EvmAddress;\n binaryModule: EvmAddress;\n negRiskModule: EvmAddress;\n combinatorialModule: EvmAddress;\n positionManager: EvmAddress;\n autoRedeemOperator: EvmAddress;\n safeMultisend: EvmAddress;\n relayHub: EvmAddress;\n perpsDepositContract: EvmAddress;\n};\n\nexport type EnvironmentConfig = {\n name: string;\n chainId: number;\n /** @internal */\n rpc: string;\n /** @internal */\n walletDerivation: WalletDerivationConfig;\n /** @internal */\n contracts: EnvironmentContracts;\n /** @internal */\n clob: ClobEndpoints;\n /** @internal */\n relayer: RestEndpoint;\n /** @internal */\n gamma: RestEndpoint;\n /** @internal */\n data: RestEndpoint;\n /** @internal */\n combos: CombosEndpoints;\n /** @internal */\n perps: PerpsEndpoints;\n /** @internal */\n rtds: WebSocketEndpoint;\n /** @internal */\n sports: WebSocketEndpoint;\n /** @internal */\n relayerMaxPolls: number;\n /** @internal */\n relayerPollFrequencyMs: number;\n};\n\ntype EnvironmentConfigForkEndpoint = Partial<RestEndpoint & WebSocketEndpoint>;\n\nexport type EnvironmentConfigFork = {\n name: string;\n chainId?: number;\n rpc?: string;\n walletDerivation?: Partial<WalletDerivationConfig>;\n contracts?: Partial<EnvironmentContracts>;\n clob?: Partial<RestEndpoint> & {\n market?: Partial<WebSocketEndpoint>;\n user?: Partial<WebSocketEndpoint>;\n };\n relayer?: Partial<RestEndpoint>;\n gamma?: Partial<RestEndpoint>;\n data?: Partial<RestEndpoint>;\n combos?: EnvironmentConfigForkEndpoint & {\n builderGateway?: Partial<RestEndpoint>;\n collateralReturn?: Partial<RestEndpoint>;\n };\n perps?: EnvironmentConfigForkEndpoint;\n rtds?: Partial<WebSocketEndpoint>;\n sports?: Partial<WebSocketEndpoint>;\n relayerMaxPolls?: number;\n relayerPollFrequencyMs?: number;\n};\n\n/**\n * The production environment configuration.\n */\nexport const production: EnvironmentConfig = {\n name: 'production',\n chainId: 137,\n rpc: 'https://polygon.drpc.org',\n walletDerivation: {\n depositWalletFactory: expectEvmAddress(\n '0x00000000000Fb5C9ADea0298D729A0CB3823Cc07',\n ),\n depositWalletBeacon: expectEvmAddress(\n '0x7A18EDfe055488A3128f01F563e5B479D92ffc3a',\n ),\n depositWalletImplementation: expectEvmAddress(\n '0x58CA52ebe0DadfdF531Cde7062e76746de4Db1eB',\n ),\n proxyFactory: expectEvmAddress(\n '0xaB45c5A4B0c941a2F231C04C3f49182e1A254052',\n ),\n proxyImplementation: expectEvmAddress(\n '0x44e999d5c2F66Ef0861317f9A4805AC2e90aEB4f',\n ),\n safeFactory: expectEvmAddress('0xaacFeEa03eb1561C4e67d661e40682Bd20E3541b'),\n safeInitCodeHash:\n '0x2bce2127ff07fb632d16c8347c4ebf501f4841168bed00d9e6ef715ddb6fcecf',\n },\n contracts: {\n collateralToken: expectEvmAddress(\n '0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB',\n ),\n conditionalTokens: expectEvmAddress(\n '0x4D97DCd97eC945f40cF65F87097ACe5EA0476045',\n ),\n negRiskAdapter: expectEvmAddress(\n '0xd91E80cF2E7be2e162c6513ceD06f1dD0dA35296',\n ),\n collateralAdapter: expectEvmAddress(\n '0xAdA100Db00Ca00073811820692005400218FcE1f',\n ),\n negRiskCollateralAdapter: expectEvmAddress(\n '0xadA2005600Dec949baf300f4C6120000bDB6eAab',\n ),\n standardExchange: expectEvmAddress(\n '0xE111180000d2663C0091e4f400237545B87B996B',\n ),\n negRiskExchange: expectEvmAddress(\n '0xe2222d279d744050d28e00520010520000310F59',\n ),\n exchangeV3: expectEvmAddress('0xe3333700cA9d93003F00f0F71f8515005F6c00Aa'),\n protocolV2Router: expectEvmAddress(\n '0x12121212006e4CD160D18e3f00711DA5c3372600',\n ),\n binaryModule: expectEvmAddress(\n '0x1000008dD9001B968442c1000017eaE6E0dA00Ba',\n ),\n negRiskModule: expectEvmAddress(\n '0x200000900045e3B6259600682756002200028933',\n ),\n combinatorialModule: expectEvmAddress(\n '0x30000034706c7d8e12009dab006be20000c031a8',\n ),\n positionManager: expectEvmAddress(\n '0x006F54F7f9A22e0000CC2AB60031000000ae9fEF',\n ),\n autoRedeemOperator: expectEvmAddress(\n '0xa1200000d0002264C9a1698e001292D00E1b00af',\n ),\n safeMultisend: expectEvmAddress(\n '0xA238CBeb142c10Ef7Ad8442C6D1f9E89e07e7761',\n ),\n relayHub: expectEvmAddress('0xD216153c06E857cD7f72665E0aF1d7D82172F494'),\n perpsDepositContract: expectEvmAddress(\n '0xDCa4af75705dbB50f62437045afF9921947917d2',\n ),\n },\n clob: {\n rest: 'https://clob.polymarket.com',\n market: { ws: 'wss://ws-subscriptions-clob.polymarket.com/ws/market' },\n user: { ws: 'wss://ws-subscriptions-clob.polymarket.com/ws/user' },\n },\n relayer: { rest: 'https://relayer-v2.polymarket.com' },\n gamma: { rest: 'https://gamma-api.polymarket.com' },\n data: { rest: 'https://data-api.polymarket.com' },\n combos: {\n rest: 'https://combos-rfq-api.polymarket.com',\n ws: 'wss://combos-rfq-gateway-quoter.polymarket.com/ws/rfq',\n builderGateway: {\n rest: 'https://combos-rfq-gateway-builder.polymarket.com',\n },\n collateralReturn: {\n rest: 'https://combos-rfq-collateral-return.polymarket.com',\n },\n },\n perps: {\n rest: 'https://api.perpetuals.polymarket.com',\n ws: 'wss://ws.perpetuals.polymarket.com/v1/ws',\n },\n rtds: { ws: 'wss://ws-live-data.polymarket.com' },\n sports: { ws: 'wss://sports-api.polymarket.com/ws' },\n relayerMaxPolls: 100,\n relayerPollFrequencyMs: 2000,\n};\n\n/**\n * Forks an environment config from production unless a different base is passed.\n *\n * @experimental This helper is intended for advanced custom environment use,\n * not general SDK usage. Its signature may change without notice.\n */\nexport function forkEnvironmentConfig(\n fork: EnvironmentConfigFork,\n base: EnvironmentConfig = production,\n): EnvironmentConfig {\n return {\n ...base,\n ...fork,\n walletDerivation: {\n ...base.walletDerivation,\n ...fork.walletDerivation,\n },\n contracts: {\n ...base.contracts,\n ...fork.contracts,\n },\n clob: {\n ...forkRestEndpoint(base.clob, fork.clob),\n market: forkWebSocketEndpoint(base.clob.market, fork.clob?.market),\n user: forkWebSocketEndpoint(base.clob.user, fork.clob?.user),\n },\n relayer: forkRestEndpoint(base.relayer, fork.relayer),\n gamma: forkRestEndpoint(base.gamma, fork.gamma),\n data: forkRestEndpoint(base.data, fork.data),\n combos: {\n ...forkRestWebSocketEndpoint(base.combos, fork.combos),\n builderGateway: forkRestEndpoint(\n base.combos.builderGateway,\n fork.combos?.builderGateway,\n ),\n collateralReturn: forkRestEndpoint(\n base.combos.collateralReturn,\n fork.combos?.collateralReturn,\n ),\n },\n perps: forkRestWebSocketEndpoint(base.perps, fork.perps),\n rtds: forkWebSocketEndpoint(base.rtds, fork.rtds),\n sports: forkWebSocketEndpoint(base.sports, fork.sports),\n };\n}\n\nfunction forkRestEndpoint(\n base: RestEndpoint,\n fork: Partial<RestEndpoint> | undefined,\n): RestEndpoint {\n return {\n ...base,\n ...fork,\n headers: forkHeaders(base.headers, fork?.headers),\n };\n}\n\nfunction forkWebSocketEndpoint(\n base: WebSocketEndpoint,\n fork: Partial<WebSocketEndpoint> | undefined,\n): WebSocketEndpoint {\n return {\n ...base,\n ...fork,\n headers: forkHeaders(base.headers, fork?.headers),\n };\n}\n\nfunction forkRestWebSocketEndpoint<\n TEndpoint extends RestEndpoint & WebSocketEndpoint,\n>(base: TEndpoint, fork: EnvironmentConfigForkEndpoint | undefined): TEndpoint {\n return {\n ...base,\n ...fork,\n headers: forkHeaders(base.headers, fork?.headers),\n };\n}\n\nfunction forkHeaders(\n base: Record<string, string> | undefined,\n fork: Record<string, string> | undefined,\n): Record<string, string> | undefined {\n if (base === undefined && fork === undefined) return undefined;\n return { ...base, ...fork };\n}\n\n/** @internal */\nexport const preproduction = forkEnvironmentConfig({\n name: 'preproduction',\n clob: { rest: 'https://clob-preprod-int-v2.polymarket.com' },\n data: { rest: 'https://data-api-preprod-int.polymarket.com' },\n gamma: { rest: 'https://gamma-api-preprod-int.polymarket.com' },\n relayer: { rest: 'https://relayer-v2-preprod-int.polymarket.com' },\n});\n","/**\n * Builds the canonical HMAC signature for authenticated requests.\n *\n * The signed payload is the raw string concatenation of `timestamp`, `method`,\n * `requestPath`, and, when present, the serialized request `body`, matching the\n * remote signing contract.\n *\n * The `secret` is expected to be base64-encoded and is decoded before signing.\n * The returned signature is base64url-encoded with padding preserved.\n *\n * @example\n * Server-side signing example for builder-authenticated requests:\n *\n * ```ts\n * async function handleSignRequest(request: Request): Promise<Response> {\n * const { body, method, path } = await request.json();\n *\n * const timestamp = Math.floor(Date.now() / 1000);\n * const signature = await buildHmacSignature(\n * process.env.POLY_BUILDER_SECRET!,\n * timestamp,\n * method,\n * path,\n * body,\n * );\n *\n * return Response.json({\n * POLY_BUILDER_API_KEY: process.env.POLY_BUILDER_API_KEY!,\n * POLY_BUILDER_PASSPHRASE: process.env.POLY_BUILDER_PASSPHRASE!,\n * POLY_BUILDER_SIGNATURE: signature,\n * POLY_BUILDER_TIMESTAMP: `${timestamp}`,\n * });\n * }\n * ```\n */\nexport async function buildHmacSignature(\n secret: string,\n timestamp: number,\n method: string,\n requestPath: string,\n body?: string,\n): Promise<string> {\n let message = `${timestamp}${method}${requestPath}`;\n\n if (body !== undefined) {\n message += body;\n }\n\n const cryptoKey = await globalThis.crypto.subtle.importKey(\n 'raw',\n base64ToArrayBuffer(secret),\n { name: 'HMAC', hash: 'SHA-256' },\n false,\n ['sign'],\n );\n const signature = await globalThis.crypto.subtle.sign(\n 'HMAC',\n cryptoKey,\n new TextEncoder().encode(message),\n );\n\n return toUrlSafeBase64(arrayBufferToBase64(signature));\n}\n\nfunction base64ToArrayBuffer(base64: string): ArrayBuffer {\n const sanitizedBase64 = base64\n .replace(/-/g, '+')\n .replace(/_/g, '/')\n .replace(/[^A-Za-z0-9+/=]/g, '');\n const binaryString = atob(sanitizedBase64);\n const bytes = new Uint8Array(binaryString.length);\n\n for (let index = 0; index < binaryString.length; index += 1) {\n bytes[index] = binaryString.charCodeAt(index);\n }\n\n return bytes.buffer;\n}\n\nfunction arrayBufferToBase64(buffer: ArrayBuffer): string {\n const bytes = new Uint8Array(buffer);\n let binary = '';\n\n for (const byte of bytes) {\n binary += String.fromCharCode(byte);\n }\n\n return btoa(binary);\n}\n\nfunction toUrlSafeBase64(value: string): string {\n return value.replace(/\\+/g, '-').replace(/\\//g, '_');\n}\n","import type { Pushable } from 'it-pushable';\nimport type { SubscriptionHandle } from '../actions/subscriptions';\n\nexport function createSubscriptionHandle<TEvent>(\n queue: Pushable<TEvent>,\n closeSubscription: () => Promise<void>,\n): SubscriptionHandle<TEvent> {\n let closing: Promise<void> | undefined;\n\n return {\n close: () => {\n if (closing === undefined) {\n closing = Promise.resolve(queue.return()).then(() =>\n closeSubscription(),\n );\n }\n return closing;\n },\n [Symbol.asyncIterator]() {\n return queue[Symbol.asyncIterator]();\n },\n };\n}\n","import { type Pushable, pushable } from 'it-pushable';\n\nexport type SubscriptionRegistrySubscriber<TEvent> = {\n matches?: (event: TEvent) => boolean;\n queue: Pushable<TEvent>;\n};\n\nexport type SubscriptionRegistryEntry<TSubscription, TEvent> = {\n subscription: TSubscription;\n subscriber: SubscriptionRegistrySubscriber<TEvent>;\n};\n\nexport type SubscriptionRegistryChange<TState> = {\n before: TState;\n after: TState;\n};\n\nexport type SubscriptionRegistryAddOptions<TEvent> = {\n matches?: (event: TEvent) => boolean;\n};\n\nexport type SubscriptionRegistryAddResult<TSubscription, TEvent, TState> = {\n change: SubscriptionRegistryChange<TState>;\n entry: SubscriptionRegistryEntry<TSubscription, TEvent>;\n};\n\ntype DeriveServerState<TSubscription, TEvent, TState> = (\n entries: Iterable<SubscriptionRegistryEntry<TSubscription, TEvent>>,\n) => TState;\n\nexport type SubscriptionRegistryOptions<TSubscription, TEvent, TState> = {\n deriveServerState: DeriveServerState<TSubscription, TEvent, TState>;\n};\n\nexport class SubscriptionRegistry<\n TSubscription,\n TEvent,\n TServerState = undefined,\n> {\n readonly #entries = new Set<\n SubscriptionRegistryEntry<TSubscription, TEvent>\n >();\n readonly #deriveServerState: DeriveServerState<\n TSubscription,\n TEvent,\n TServerState\n >;\n\n constructor(\n options?: SubscriptionRegistryOptions<TSubscription, TEvent, TServerState>,\n ) {\n this.#deriveServerState =\n options?.deriveServerState ?? (() => undefined as TServerState);\n }\n\n add(\n subscription: TSubscription,\n options: SubscriptionRegistryAddOptions<TEvent> = {},\n ): SubscriptionRegistryAddResult<TSubscription, TEvent, TServerState> {\n const subscriber: SubscriptionRegistrySubscriber<TEvent> = {\n queue: pushable<TEvent>({ objectMode: true }),\n };\n if (options.matches !== undefined) {\n subscriber.matches = options.matches;\n }\n const entry: SubscriptionRegistryEntry<TSubscription, TEvent> = {\n subscription,\n subscriber,\n };\n return { change: this.#addEntry(entry), entry };\n }\n\n #addEntry(\n entry: SubscriptionRegistryEntry<TSubscription, TEvent>,\n ): SubscriptionRegistryChange<TServerState> {\n const before = this.serverState();\n this.#entries.add(entry);\n return { before, after: this.serverState() };\n }\n\n remove(\n entry: SubscriptionRegistryEntry<TSubscription, TEvent>,\n ): SubscriptionRegistryChange<TServerState> {\n const before = this.serverState();\n this.#entries.delete(entry);\n entry.subscriber.queue.end();\n return { before, after: this.serverState() };\n }\n\n dispatch(event: TEvent): void {\n for (const { subscriber } of this.#entries) {\n if (subscriber.matches === undefined || subscriber.matches(event)) {\n subscriber.queue.push(event);\n }\n }\n }\n\n hasActiveSubscriptions(): boolean {\n return this.#entries.size > 0;\n }\n\n endAll(error?: Error): void {\n for (const { subscriber } of this.#entries) {\n subscriber.queue.end(error);\n }\n this.#entries.clear();\n }\n\n serverState(): TServerState {\n return this.#deriveServerState(this.#entries);\n }\n}\n","import type { ApiKeyCreds } from '@polymarket/bindings/clob';\nimport type {\n MarketEvent,\n UserEvent,\n} from '@polymarket/bindings/subscriptions';\nimport type {\n MarketSubscription,\n UserSubscription,\n} from '../../actions/subscriptions';\nimport type { SubscriptionRegistryEntry } from '../registry';\n\nexport type SendWebSocketMessage = (message: unknown) => void;\n\nexport type MarketSubscriptionEntry = SubscriptionRegistryEntry<\n MarketSubscription,\n MarketEvent\n>;\n\nexport type MarketServerSubscription = {\n assetsIds: string[];\n customFeatureEnabled: boolean;\n};\n\nexport type UserSubscriptionEntry = SubscriptionRegistryEntry<\n UserSubscription,\n UserEvent\n>;\n\nexport type UserServerSubscription = {\n includeAllMarkets: boolean;\n markets: string[];\n};\n\nexport function syncMarketSubscription(\n send: SendWebSocketMessage,\n before: MarketServerSubscription,\n after: MarketServerSubscription,\n): void {\n const addedAssets = difference(after.assetsIds, before.assetsIds);\n const removedAssets = difference(before.assetsIds, after.assetsIds);\n\n if (addedAssets.length > 0) {\n send(buildMarketSubscribeUpdate(addedAssets, after.customFeatureEnabled));\n }\n const firstActiveAsset = after.assetsIds[0];\n if (\n addedAssets.length === 0 &&\n before.customFeatureEnabled !== after.customFeatureEnabled &&\n firstActiveAsset !== undefined\n ) {\n // CLOB applies `custom_feature_enabled` before rejecting duplicate assets as\n // \"NO NEW ASSETS\", so this toggles connection-level custom events in place.\n send(\n buildMarketSubscribeUpdate(\n [firstActiveAsset],\n after.customFeatureEnabled,\n ),\n );\n }\n if (removedAssets.length > 0) {\n send(buildMarketUnsubscribeUpdate(removedAssets));\n }\n}\n\nexport function syncUserSubscription(\n send: SendWebSocketMessage,\n before: UserServerSubscription,\n after: UserServerSubscription,\n): void {\n if (after.includeAllMarkets) {\n if (!before.includeAllMarkets && before.markets.length > 0) {\n send(buildUserUnsubscribeUpdate(before.markets));\n }\n return;\n }\n\n if (before.includeAllMarkets) {\n if (after.markets.length > 0) {\n send(buildUserSubscribeUpdate(after.markets));\n }\n return;\n }\n\n const addedMarkets = difference(after.markets, before.markets);\n const removedMarkets = difference(before.markets, after.markets);\n\n if (addedMarkets.length > 0) {\n send(buildUserSubscribeUpdate(addedMarkets));\n }\n if (removedMarkets.length > 0) {\n send(buildUserUnsubscribeUpdate(removedMarkets));\n }\n}\n\nexport function deriveMarketServerSubscription(\n entries: Iterable<MarketSubscriptionEntry>,\n): MarketServerSubscription {\n const assets = new Set<string>();\n let customFeatureEnabled = false;\n for (const { subscription } of entries) {\n for (const assetId of subscription.assetIds ?? subscription.tokenIds) {\n assets.add(assetId);\n }\n customFeatureEnabled ||= subscription.customFeatureEnabled === true;\n }\n return { assetsIds: Array.from(assets), customFeatureEnabled };\n}\n\nexport function deriveUserServerSubscription(\n entries: Iterable<UserSubscriptionEntry>,\n): UserServerSubscription {\n let includeAllMarkets = false;\n const markets = new Set<string>();\n for (const { subscription } of entries) {\n if (isAllMarketsUserSubscription(subscription)) {\n includeAllMarkets = true;\n continue;\n }\n for (const market of subscription.markets ?? []) markets.add(market);\n }\n return {\n includeAllMarkets,\n markets: includeAllMarkets ? [] : Array.from(markets),\n };\n}\n\nexport function buildMarketSubscribeMessage(\n subscription: MarketServerSubscription,\n): unknown {\n return {\n assets_ids: subscription.assetsIds,\n custom_feature_enabled: subscription.customFeatureEnabled,\n type: 'market',\n };\n}\n\nfunction buildMarketSubscribeUpdate(\n assetsIds: readonly string[],\n customFeatureEnabled: boolean,\n): unknown {\n return {\n assets_ids: assetsIds,\n custom_feature_enabled: customFeatureEnabled,\n operation: 'subscribe',\n };\n}\n\nfunction buildMarketUnsubscribeUpdate(assetsIds: readonly string[]): unknown {\n return {\n assets_ids: assetsIds,\n operation: 'unsubscribe',\n };\n}\n\nexport function buildUserSubscribeMessage(\n subscription: UserServerSubscription,\n credentials: ApiKeyCreds,\n): unknown {\n const message: {\n auth: { apiKey: string; passphrase: string; secret: string };\n markets?: string[];\n type: 'user';\n } = {\n auth: {\n apiKey: credentials.key,\n passphrase: credentials.passphrase,\n secret: credentials.secret,\n },\n type: 'user',\n };\n if (!subscription.includeAllMarkets) {\n message.markets = subscription.markets;\n }\n return message;\n}\n\nfunction buildUserSubscribeUpdate(markets: readonly string[]): unknown {\n return {\n markets,\n operation: 'subscribe',\n };\n}\n\nfunction buildUserUnsubscribeUpdate(markets: readonly string[]): unknown {\n return {\n markets,\n operation: 'unsubscribe',\n };\n}\n\nexport function marketMatcherFor(\n subscription: MarketSubscription,\n): (event: MarketEvent) => boolean {\n const assetIds = subscription.assetIds ?? subscription.tokenIds;\n return (event) => {\n switch (event.type) {\n case 'price_change':\n return event.payload.priceChanges.some((change) =>\n assetIds.includes(change.assetId),\n );\n case 'new_market':\n return subscription.customFeatureEnabled === true;\n case 'market_resolved':\n return (\n subscription.customFeatureEnabled === true &&\n (event.payload.assetIds ?? []).some((assetId) =>\n assetIds.includes(assetId),\n )\n );\n case 'best_bid_ask':\n return (\n subscription.customFeatureEnabled === true &&\n assetIds.includes(event.payload.assetId)\n );\n default:\n return assetIds.includes(event.payload.assetId);\n }\n };\n}\n\nexport function userMatcherFor(\n subscription: UserSubscription,\n): (event: UserEvent) => boolean {\n if (isAllMarketsUserSubscription(subscription)) {\n return () => true;\n }\n\n const markets = new Set(\n (subscription.markets ?? []).map((market) => market.toLowerCase()),\n );\n return (event) => markets.has(event.payload.market.toLowerCase());\n}\n\nfunction isAllMarketsUserSubscription(subscription: UserSubscription): boolean {\n return (subscription.markets?.length ?? 0) === 0;\n}\n\nfunction difference(\n left: readonly string[],\n right: readonly string[],\n): string[] {\n const rightSet = new Set(right);\n return left.filter((value) => !rightSet.has(value));\n}\n","import {\n type MarketEvent,\n MarketEventSchema,\n} from '@polymarket/bindings/subscriptions';\nimport type {\n MarketSubscription,\n SubscriptionHandle,\n} from '../../actions/subscriptions';\nimport { createSubscriptionHandle } from '../handle';\nimport { ClobWebSocketHeartbeat } from '../heartbeat';\nimport {\n ReconnectScheduler,\n WebSocketConnection,\n type WebSocketConnectionResult,\n} from '../lifecycle';\nimport {\n SubscriptionRegistry,\n type SubscriptionRegistryChange,\n} from '../registry';\nimport type { WebSocketSubscriptionManager } from '../types';\nimport {\n buildMarketSubscribeMessage,\n deriveMarketServerSubscription,\n type MarketServerSubscription,\n type MarketSubscriptionEntry,\n marketMatcherFor,\n syncMarketSubscription,\n} from './protocol';\n\nexport type ClobMarketWebSocketManagerOptions = {\n headers?: Record<string, string>;\n url: string;\n};\n\n/**\n * CLOB market WebSocket manager.\n *\n * The CLOB server tracks market subscriptions by asset id on the connection.\n * Incremental subscribe/unsubscribe frames mutate that server-side asset set.\n */\nexport class ClobMarketWebSocketManager\n implements WebSocketSubscriptionManager<MarketSubscription, MarketEvent>\n{\n readonly #headers: Record<string, string> | undefined;\n readonly #url: string;\n #closing: Promise<void> | undefined;\n readonly #connection = new WebSocketConnection({\n heartbeat: new ClobWebSocketHeartbeat(),\n });\n readonly #reconnectScheduler = new ReconnectScheduler();\n readonly #subscriptions = new SubscriptionRegistry<\n MarketSubscription,\n MarketEvent,\n MarketServerSubscription\n >({ deriveServerState: deriveMarketServerSubscription });\n\n constructor(options: ClobMarketWebSocketManagerOptions) {\n this.#headers = options.headers;\n this.#url = options.url;\n }\n\n async subscribe(\n subscription: MarketSubscription,\n ): Promise<SubscriptionHandle<MarketEvent>> {\n const { change, entry } = this.#subscriptions.add(subscription, {\n matches: marketMatcherFor(subscription),\n });\n\n await this.#registerSubscriber(entry, change);\n return createSubscriptionHandle(entry.subscriber.queue, () =>\n this.#closeSubscriber(entry),\n );\n }\n\n async #registerSubscriber(\n entry: MarketSubscriptionEntry,\n change: SubscriptionRegistryChange<MarketServerSubscription>,\n ): Promise<void> {\n const { before, after } = change;\n\n try {\n const connection = await this.#connect();\n if (connection.reusedOpenSocket) {\n syncMarketSubscription(\n (message) => this.#connection.send(message),\n before,\n after,\n );\n }\n } catch (error) {\n await this.#closeSubscriber(entry);\n throw error;\n }\n }\n\n async #closeSubscriber(entry: MarketSubscriptionEntry): Promise<void> {\n const { before, after } = this.#subscriptions.remove(entry);\n\n if (!this.#subscriptions.hasActiveSubscriptions()) {\n await this.close();\n return;\n }\n\n syncMarketSubscription(\n (message) => this.#connection.send(message),\n before,\n after,\n );\n }\n\n async close(): Promise<void> {\n if (this.#closing === undefined) {\n this.#closing = this.#shutdown().finally(() => {\n this.#closing = undefined;\n });\n }\n await this.#closing;\n }\n\n async #shutdown(): Promise<void> {\n this.#reconnectScheduler.stop();\n this.#subscriptions.endAll();\n\n await this.#connection.close();\n }\n\n #connect(): Promise<WebSocketConnectionResult> {\n return this.#connection.connect({\n onConnectionLost: () => this.#onConnectionLost(),\n onError: () => this.#onConnectionError(),\n onMessage: (message) => this.#onConnectionMessage(message),\n onOpen: () => this.#onConnectionOpen(),\n headers: this.#headers,\n url: this.#url,\n });\n }\n\n #onConnectionOpen(): void {\n this.#reconnectScheduler.resetBackoff();\n this.#sendInitialSubscription();\n }\n\n #onConnectionMessage(message: unknown): void {\n const events = Array.isArray(message) ? message : [message];\n for (const eventData of events) {\n const parsed = MarketEventSchema.safeParse(eventData);\n if (!parsed.success) continue;\n this.#subscriptions.dispatch(parsed.data);\n }\n }\n\n #onConnectionLost(): void {\n if (this.#subscriptions.hasActiveSubscriptions()) {\n this.#scheduleReconnect();\n }\n }\n\n #onConnectionError(): void {\n // Browser WebSockets report most failures as an error followed by close.\n // Keep iterators alive here so the close path can reconnect active handles.\n }\n\n #sendInitialSubscription(): void {\n this.#connection.send(\n buildMarketSubscribeMessage(this.#subscriptions.serverState()),\n );\n }\n\n #scheduleReconnect(): void {\n this.#reconnectScheduler.schedule({\n reconnect: () => this.#connect(),\n shouldReconnect: () => this.#subscriptions.hasActiveSubscriptions(),\n });\n }\n}\n","import type { ApiKeyCreds } from '@polymarket/bindings/clob';\nimport {\n type UserEvent,\n UserEventSchema,\n} from '@polymarket/bindings/subscriptions';\nimport type {\n SubscriptionHandle,\n UserSubscription,\n} from '../../actions/subscriptions';\nimport { createSubscriptionHandle } from '../handle';\nimport { ClobWebSocketHeartbeat } from '../heartbeat';\nimport {\n ReconnectScheduler,\n WebSocketConnection,\n type WebSocketConnectionResult,\n} from '../lifecycle';\nimport {\n SubscriptionRegistry,\n type SubscriptionRegistryChange,\n} from '../registry';\nimport type { WebSocketSubscriptionManager } from '../types';\nimport {\n buildUserSubscribeMessage,\n deriveUserServerSubscription,\n syncUserSubscription,\n type UserServerSubscription,\n type UserSubscriptionEntry,\n userMatcherFor,\n} from './protocol';\n\nexport type ClobUserWebSocketManagerOptions = {\n credentials: ApiKeyCreds;\n headers?: Record<string, string>;\n url: string;\n};\n\nexport class ClobUserWebSocketManager\n implements WebSocketSubscriptionManager<UserSubscription, UserEvent>\n{\n readonly #credentials: ApiKeyCreds;\n readonly #headers: Record<string, string> | undefined;\n readonly #url: string;\n #closing: Promise<void> | undefined;\n readonly #connection = new WebSocketConnection({\n heartbeat: new ClobWebSocketHeartbeat(),\n });\n readonly #reconnectScheduler = new ReconnectScheduler();\n readonly #subscriptions = new SubscriptionRegistry<\n UserSubscription,\n UserEvent,\n UserServerSubscription\n >({ deriveServerState: deriveUserServerSubscription });\n\n constructor(options: ClobUserWebSocketManagerOptions) {\n this.#credentials = options.credentials;\n this.#headers = options.headers;\n this.#url = options.url;\n }\n\n async subscribe(\n subscription: UserSubscription,\n ): Promise<SubscriptionHandle<UserEvent>> {\n const { change, entry } = this.#subscriptions.add(subscription, {\n matches: userMatcherFor(subscription),\n });\n\n await this.#registerSubscriber(entry, change);\n return createSubscriptionHandle(entry.subscriber.queue, () =>\n this.#closeSubscriber(entry),\n );\n }\n\n async #registerSubscriber(\n entry: UserSubscriptionEntry,\n change: SubscriptionRegistryChange<UserServerSubscription>,\n ): Promise<void> {\n const { before, after } = change;\n\n try {\n const connection = await this.#connect();\n if (connection.reusedOpenSocket) {\n syncUserSubscription(\n (message) => this.#connection.send(message),\n before,\n after,\n );\n }\n } catch (error) {\n await this.#closeSubscriber(entry);\n throw error;\n }\n }\n\n async #closeSubscriber(entry: UserSubscriptionEntry): Promise<void> {\n const { before, after } = this.#subscriptions.remove(entry);\n\n if (!this.#subscriptions.hasActiveSubscriptions()) {\n await this.close();\n return;\n }\n\n syncUserSubscription(\n (message) => this.#connection.send(message),\n before,\n after,\n );\n }\n\n async close(): Promise<void> {\n if (this.#closing === undefined) {\n this.#closing = this.#shutdown().finally(() => {\n this.#closing = undefined;\n });\n }\n await this.#closing;\n }\n\n async #shutdown(): Promise<void> {\n this.#reconnectScheduler.stop();\n this.#subscriptions.endAll();\n\n await this.#connection.close();\n }\n\n #connect(): Promise<WebSocketConnectionResult> {\n return this.#connection.connect({\n onConnectionLost: () => this.#onConnectionLost(),\n onError: () => this.#onConnectionError(),\n onMessage: (message) => this.#onConnectionMessage(message),\n onOpen: (credentials) => this.#onConnectionOpen(credentials),\n prepare: () => this.#credentials,\n headers: this.#headers,\n url: this.#url,\n });\n }\n\n #onConnectionOpen(credentials: ApiKeyCreds): void {\n this.#reconnectScheduler.resetBackoff();\n this.#sendInitialSubscription(credentials);\n }\n\n #onConnectionMessage(message: unknown): void {\n const events = Array.isArray(message) ? message : [message];\n for (const eventData of events) {\n const parsed = UserEventSchema.safeParse(eventData);\n if (!parsed.success) continue;\n this.#subscriptions.dispatch(parsed.data);\n }\n }\n\n #onConnectionLost(): void {\n if (this.#subscriptions.hasActiveSubscriptions()) {\n this.#scheduleReconnect();\n }\n }\n\n #onConnectionError(): void {\n // Browser WebSockets report most failures as an error followed by close.\n // Keep iterators alive here so the close path can reconnect active handles.\n }\n\n #sendInitialSubscription(credentials: ApiKeyCreds): void {\n this.#connection.send(\n buildUserSubscribeMessage(this.#subscriptions.serverState(), credentials),\n );\n }\n\n #scheduleReconnect(): void {\n this.#reconnectScheduler.schedule({\n reconnect: () => this.#connect(),\n shouldReconnect: () => this.#subscriptions.hasActiveSubscriptions(),\n });\n }\n}\n","import type { PerpsCredentials } from '@polymarket/bindings/perps';\nimport { TransportError } from '../../errors';\nimport { PerpsSession } from './session';\n\n/**\n * @experimental This API may change in a breaking way in any release, including patch releases.\n */\nexport type PerpsSessionManagerOptions = {\n chainId: number;\n headers?: Record<string, string>;\n restUrl: string;\n wsUrl: string;\n};\n\n/**\n * @experimental This API may change in a breaking way in any release, including patch releases.\n */\nexport class PerpsSessionManager {\n readonly #chainId: number;\n readonly #headers: Record<string, string> | undefined;\n readonly #restUrl: string;\n readonly #wsUrl: string;\n readonly #sessions = new Set<PerpsSession>();\n readonly #connectingSessions = new Set<PerpsSession>();\n readonly #connecting = new Set<Promise<PerpsSession>>();\n #hasShutdown = false;\n\n /**\n * @experimental This API may change in a breaking way in any release, including patch releases.\n */\n constructor(options: PerpsSessionManagerOptions) {\n this.#chainId = options.chainId;\n this.#headers = options.headers;\n this.#restUrl = options.restUrl;\n this.#wsUrl = options.wsUrl;\n }\n\n /**\n * @experimental This API may change in a breaking way in any release, including patch releases.\n */\n connect(credentials: PerpsCredentials): Promise<PerpsSession> {\n if (this.#hasShutdown) {\n return Promise.reject(\n new TransportError('Perps session manager has been shut down.'),\n );\n }\n\n const session = new PerpsSession({\n chainId: this.#chainId,\n credentials,\n headers: this.#headers,\n onClose: (closedSession) => this.#clearSession(closedSession),\n restUrl: this.#restUrl,\n wsUrl: this.#wsUrl,\n });\n this.#connectingSessions.add(session);\n\n let connecting!: Promise<PerpsSession>;\n connecting = (async () => {\n try {\n await session.connect();\n if (this.#hasShutdown) {\n await session.close();\n throw new TransportError('Perps session manager has been shut down.');\n }\n this.#sessions.add(session);\n return session;\n } catch (error) {\n await session.close();\n throw error;\n } finally {\n this.#connecting.delete(connecting);\n this.#connectingSessions.delete(session);\n }\n })();\n\n this.#connecting.add(connecting);\n return connecting;\n }\n\n /**\n * @experimental This API may change in a breaking way in any release, including patch releases.\n */\n async shutdown(): Promise<void> {\n this.#hasShutdown = true;\n const sessions = Array.from(this.#sessions);\n const connectingSessions = Array.from(this.#connectingSessions);\n const connecting = Array.from(this.#connecting);\n\n this.#sessions.clear();\n this.#connectingSessions.clear();\n this.#connecting.clear();\n\n await Promise.allSettled([\n ...sessions.map((session) => session.close()),\n ...connectingSessions.map((session) => session.close()),\n ...connecting.map((promise) => promise.catch(() => undefined)),\n ]).then(() => undefined);\n }\n\n #clearSession(session: PerpsSession): void {\n this.#sessions.delete(session);\n this.#connectingSessions.delete(session);\n }\n}\n","import {\n type PerpsMarketDataEvent,\n PerpsMarketDataEventSchema,\n} from '@polymarket/bindings/subscriptions';\nimport { invariant } from '@polymarket/types';\nimport type {\n PerpsMarketDataSubscription,\n SubscriptionHandle,\n} from '../../actions/subscriptions';\nimport { createSubscriptionHandle } from '../handle';\nimport { PerpsWebSocketHeartbeat } from '../heartbeat';\nimport {\n ReconnectScheduler,\n WebSocketConnection,\n type WebSocketConnectionResult,\n} from '../lifecycle';\nimport {\n SubscriptionRegistry,\n type SubscriptionRegistryChange,\n type SubscriptionRegistryEntry,\n} from '../registry';\nimport type { WebSocketSubscriptionManager } from '../types';\n\ntype PerpsSubscriptionEntry = SubscriptionRegistryEntry<\n PerpsMarketDataSubscription,\n PerpsMarketDataEvent\n>;\n\ntype PerpsSubscriptionServerState = Set<string>;\n\n/**\n * @experimental This API may change in a breaking way in any release, including patch releases.\n */\nexport type PerpsSubscriptionManagerOptions = {\n headers?: Record<string, string>;\n url: string;\n};\n\n/**\n * Perps public subscription WebSocket manager.\n *\n * The Perps server tracks subscriptions by channel string. This manager keeps\n * SDK-level topic specs separate from upstream channel names and resubscribes\n * active channels after reconnects.\n *\n * @experimental This API may change in a breaking way in any release, including patch releases.\n */\nexport class PerpsSubscriptionManager\n implements\n WebSocketSubscriptionManager<\n PerpsMarketDataSubscription,\n PerpsMarketDataEvent\n >\n{\n readonly #headers: Record<string, string> | undefined;\n readonly #url: string;\n #closing: Promise<void> | undefined;\n #nextRequestId = 1;\n readonly #connection = new WebSocketConnection({\n heartbeat: new PerpsWebSocketHeartbeat(),\n });\n readonly #reconnectScheduler = new ReconnectScheduler();\n readonly #subscriptions = new SubscriptionRegistry<\n PerpsMarketDataSubscription,\n PerpsMarketDataEvent,\n PerpsSubscriptionServerState\n >({ deriveServerState: derivePerpsSubscriptionServerState });\n\n /**\n * @experimental This API may change in a breaking way in any release, including patch releases.\n */\n constructor(options: PerpsSubscriptionManagerOptions) {\n this.#headers = options.headers;\n this.#url = options.url;\n }\n\n /**\n * @experimental This API may change in a breaking way in any release, including patch releases.\n */\n async subscribe(\n subscription: PerpsMarketDataSubscription,\n ): Promise<SubscriptionHandle<PerpsMarketDataEvent>> {\n const { change, entry } = this.#subscriptions.add(subscription, {\n matches: matcherFor(subscription),\n });\n await this.#registerSubscriber(entry, change);\n return createSubscriptionHandle(entry.subscriber.queue, () =>\n this.#closeSubscriber(entry),\n );\n }\n\n async #registerSubscriber(\n entry: PerpsSubscriptionEntry,\n change: SubscriptionRegistryChange<PerpsSubscriptionServerState>,\n ): Promise<void> {\n try {\n const connection = await this.#connect();\n if (connection.reusedOpenSocket) {\n this.#sendSubscribeFrame(channelsAdded(change.before, change.after));\n this.#sendUnsubscribeFrame(\n channelsRemoved(change.before, change.after),\n );\n }\n } catch (error) {\n await this.#closeSubscriber(entry);\n throw error;\n }\n }\n\n async #closeSubscriber(entry: PerpsSubscriptionEntry): Promise<void> {\n const { before, after } = this.#subscriptions.remove(entry);\n this.#sendSubscribeFrame(channelsAdded(before, after));\n this.#sendUnsubscribeFrame(channelsRemoved(before, after));\n if (!this.#subscriptions.hasActiveSubscriptions()) {\n await this.close();\n }\n }\n\n /**\n * @experimental This API may change in a breaking way in any release, including patch releases.\n */\n async close(): Promise<void> {\n if (this.#closing === undefined) {\n this.#closing = this.#shutdown().finally(() => {\n this.#closing = undefined;\n });\n }\n await this.#closing;\n }\n\n async #shutdown(): Promise<void> {\n this.#reconnectScheduler.stop();\n this.#subscriptions.endAll();\n\n await this.#connection.close();\n }\n\n #connect(): Promise<WebSocketConnectionResult> {\n return this.#connection.connect({\n onConnectionLost: () => this.#onConnectionLost(),\n onError: () => this.#onConnectionError(),\n onMessage: (message) => this.#onConnectionMessage(message),\n onOpen: () => this.#onConnectionOpen(),\n headers: this.#headers,\n url: this.#url,\n });\n }\n\n #onConnectionOpen(): void {\n this.#reconnectScheduler.resetBackoff();\n this.#sendSubscribeFrame(Array.from(this.#subscriptions.serverState()));\n }\n\n #onConnectionMessage(message: unknown): void {\n const parsed = PerpsMarketDataEventSchema.safeParse(message);\n if (!parsed.success) return;\n this.#subscriptions.dispatch(parsed.data);\n }\n\n #onConnectionLost(): void {\n if (this.#subscriptions.hasActiveSubscriptions()) {\n this.#scheduleReconnect();\n }\n }\n\n #onConnectionError(): void {\n // Browser WebSockets report most failures as an error followed by close.\n // Keep iterators alive here so the close path can reconnect active handles.\n }\n\n #sendSubscribeFrame(channels: readonly string[]): void {\n if (channels.length === 0) return;\n this.#connection.send(this.#buildChannelFrame('sub', channels));\n }\n\n #sendUnsubscribeFrame(channels: readonly string[]): void {\n if (channels.length === 0) return;\n this.#connection.send(this.#buildChannelFrame('unsub', channels));\n }\n\n #buildChannelFrame(req: 'sub' | 'unsub', channels: readonly string[]) {\n return {\n id: this.#nextRequestId++,\n req,\n chs: channels,\n };\n }\n\n #scheduleReconnect(): void {\n this.#reconnectScheduler.schedule({\n reconnect: () => this.#connect(),\n shouldReconnect: () => this.#subscriptions.hasActiveSubscriptions(),\n });\n }\n}\n\nfunction derivePerpsSubscriptionServerState(\n entries: Iterable<PerpsSubscriptionEntry>,\n): PerpsSubscriptionServerState {\n const channels = new Set<string>();\n const tickerInstrumentIds = new Set<number>();\n const statisticInstrumentIds = new Set<number>();\n let subscribeAllTickers = false;\n let subscribeAllStatistics = false;\n\n for (const { subscription } of entries) {\n switch (subscription.topic) {\n case 'perps.tickers':\n if (subscription.instrumentId === undefined) {\n subscribeAllTickers = true;\n } else {\n tickerInstrumentIds.add(subscription.instrumentId);\n }\n break;\n case 'perps.statistics':\n if (subscription.instrumentId === undefined) {\n subscribeAllStatistics = true;\n } else {\n statisticInstrumentIds.add(subscription.instrumentId);\n }\n break;\n default:\n channels.add(channelFor(subscription));\n }\n }\n\n if (subscribeAllTickers) {\n channels.add('tickers::all');\n } else {\n for (const instrumentId of tickerInstrumentIds) {\n channels.add(`tickers::${instrumentId}`);\n }\n }\n\n if (subscribeAllStatistics) {\n channels.add('statistics::all');\n } else {\n for (const instrumentId of statisticInstrumentIds) {\n channels.add(`statistics::${instrumentId}`);\n }\n }\n\n return channels;\n}\n\nfunction channelsAdded(\n before: ReadonlySet<string>,\n after: ReadonlySet<string>,\n): string[] {\n return Array.from(after).filter((channel) => !before.has(channel));\n}\n\nfunction channelsRemoved(\n before: ReadonlySet<string>,\n after: ReadonlySet<string>,\n): string[] {\n return Array.from(before).filter((channel) => !after.has(channel));\n}\n\nfunction channelFor(subscription: PerpsMarketDataSubscription): string {\n switch (subscription.topic) {\n case 'perps.trades':\n return `trades::${subscription.instrumentId}`;\n case 'perps.bbo':\n return `bbo::${subscription.instrumentId}`;\n case 'perps.book':\n return `book::${subscription.instrumentId}`;\n case 'perps.candles':\n return `klines::${subscription.instrumentId}::${subscription.interval}`;\n case 'perps.tickers':\n return subscription.instrumentId === undefined\n ? 'tickers::all'\n : `tickers::${subscription.instrumentId}`;\n case 'perps.statistics':\n return subscription.instrumentId === undefined\n ? 'statistics::all'\n : `statistics::${subscription.instrumentId}`;\n default: {\n const neverSpec: never = subscription;\n invariant(false, `Unknown Perps topic: ${String(neverSpec)}`);\n }\n }\n}\n\nfunction matcherFor(\n subscription: PerpsMarketDataSubscription,\n): (event: PerpsMarketDataEvent) => boolean {\n switch (subscription.topic) {\n case 'perps.trades':\n return (event) =>\n event.topic === 'perps.trades' &&\n event.channel === `trades::${subscription.instrumentId}`;\n case 'perps.bbo':\n case 'perps.book':\n return (event) =>\n event.topic === subscription.topic &&\n event.payload.instrumentId === subscription.instrumentId;\n case 'perps.candles':\n return (event) =>\n event.topic === 'perps.candles' &&\n event.payload.instrumentId === subscription.instrumentId &&\n event.payload.interval === subscription.interval;\n case 'perps.tickers':\n case 'perps.statistics':\n return (event) =>\n event.topic === subscription.topic &&\n (subscription.instrumentId === undefined ||\n event.payload.instrumentId === subscription.instrumentId);\n default: {\n const neverSpec: never = subscription;\n invariant(false, `Unknown Perps topic: ${String(neverSpec)}`);\n }\n }\n}\n","import {\n type RfqConfirmationAck as BindingRfqConfirmationAck,\n type RfqQuoteAck as BindingRfqQuoteAck,\n type RfqQuoteCancelAck as BindingRfqQuoteCancelAck,\n RfqConfirmationDecision,\n type RfqConfirmationRequest,\n type RfqExecutionUpdate,\n type RfqId,\n type RfqQuoteId,\n type RfqQuoteRequest,\n type RfqTrade,\n} from '@polymarket/bindings/combos';\nimport type {\n RfqCancelQuoteAck,\n RfqConfirmationAck,\n RfqConfirmationRequestEvent,\n RfqExecutionUpdateEvent,\n RfqQuoteReference,\n RfqQuoteRequestEvent,\n RfqQuoteResponse,\n RfqTradeEvent,\n} from '../../actions/rfq';\n\nexport interface RfqEventController {\n quote(\n request: RfqQuoteRequest,\n response: RfqQuoteResponse,\n ): Promise<RfqQuoteReference>;\n respondToConfirmation(\n rfqId: RfqId,\n quoteId: RfqQuoteId,\n decision: RfqConfirmationDecision,\n ): Promise<RfqConfirmationAck>;\n}\n\nexport function toQuoteRequestEvent(\n controller: RfqEventController,\n message: RfqQuoteRequest,\n): RfqQuoteRequestEvent {\n return {\n ...message,\n quote: (request) => controller.quote(message, request),\n };\n}\n\nexport function toConfirmationRequestEvent(\n controller: RfqEventController,\n message: RfqConfirmationRequest,\n): RfqConfirmationRequestEvent {\n const rfqId = message.rfqId;\n const quoteId = message.quoteId;\n return {\n ...message,\n confirm: () =>\n controller.respondToConfirmation(\n rfqId,\n quoteId,\n RfqConfirmationDecision.Confirm,\n ),\n decline: () =>\n controller.respondToConfirmation(\n rfqId,\n quoteId,\n RfqConfirmationDecision.Decline,\n ),\n };\n}\n\nexport function toExecutionUpdateEvent(\n message: RfqExecutionUpdate,\n): RfqExecutionUpdateEvent {\n return message;\n}\n\nexport function toTradeEvent(message: RfqTrade): RfqTradeEvent {\n return message;\n}\n\nexport function toQuoteAck(message: BindingRfqQuoteAck): RfqQuoteReference {\n return {\n quoteId: message.quoteId,\n rfqId: message.rfqId,\n };\n}\n\nexport function toQuoteCancelAck(\n message: BindingRfqQuoteCancelAck,\n): RfqCancelQuoteAck {\n return {\n quoteId: message.quoteId,\n rfqId: message.rfqId,\n };\n}\n\nexport function toConfirmationAck(\n message: BindingRfqConfirmationAck,\n): RfqConfirmationAck {\n return {\n quoteId: message.quoteId,\n rfqId: message.rfqId,\n };\n}\n","import type { ApiKeyCreds } from '@polymarket/bindings/clob';\nimport type {\n RfqAuthMessage,\n RfqConfirmationDecision,\n RfqConfirmationResponseMessage,\n RfqId,\n RfqQuoteCancelMessage,\n RfqQuoteId,\n RfqQuoteMessage,\n RfqQuoteRequest,\n} from '@polymarket/bindings/combos';\nimport type { AccountIdentity } from '../../wallet';\nimport { resolveOrderIdentity } from '../../wallet';\nimport type { RfqQuote } from './quote';\n\nexport function createAuthMessage(\n account: AccountIdentity,\n credentials: ApiKeyCreds,\n): RfqAuthMessage {\n const identity = resolveOrderIdentity(account);\n\n return {\n auth: {\n apiKey: credentials.key,\n passphrase: credentials.passphrase,\n secret: credentials.secret,\n },\n identity: {\n maker_address: identity.maker,\n signature_type: identity.signatureType,\n signer_address: identity.signer,\n },\n type: 'auth',\n };\n}\n\nexport function createQuoteMessage(\n request: RfqQuoteRequest,\n quote: RfqQuote,\n): RfqQuoteMessage {\n return {\n price_e6: quote.price.toString(),\n rfq_id: request.rfqId,\n signed_order: quote.signedOrder,\n size_e6: quote.size.toString(),\n type: 'RFQ_QUOTE',\n };\n}\n\nexport function createQuoteCancelMessage(\n account: AccountIdentity,\n rfqId: RfqId,\n quoteId: RfqQuoteId,\n): RfqQuoteCancelMessage {\n const identity = resolveOrderIdentity(account);\n\n return {\n maker_address: identity.maker,\n quote_id: quoteId,\n rfq_id: rfqId,\n signer_address: identity.signer,\n type: 'RFQ_QUOTE_CANCEL',\n };\n}\n\nexport function createConfirmationResponseMessage(\n rfqId: RfqId,\n quoteId: RfqQuoteId,\n decision: RfqConfirmationDecision,\n): RfqConfirmationResponseMessage {\n return {\n decision,\n quote_id: quoteId,\n rfq_id: rfqId,\n type: 'RFQ_CONFIRMATION_RESPONSE',\n };\n}\n","import { setNonBlockingTimeout } from '@polymarket/types';\nimport { TimeoutError } from '../../errors';\n\ntype PendingResponse<T> = {\n promise: Promise<T>;\n reject(error: Error): void;\n resolve(value: T): void;\n};\n\nexport class PendingResponses {\n readonly #pending = new Map<string, PendingResponse<unknown>[]>();\n readonly #timeoutMs: number;\n\n constructor(timeoutMs: number) {\n this.#timeoutMs = timeoutMs;\n }\n\n waitFor<T>(key: string, timeoutMessage: string): Promise<T> {\n const pending = createPending<T>();\n let promise!: Promise<T>;\n const timeout = setNonBlockingTimeout(() => {\n this.remove(key, promise);\n pending.reject(new TimeoutError(timeoutMessage));\n }, this.#timeoutMs);\n promise = pending.promise.finally(() => clearTimeout(timeout));\n const entries = this.#pending.get(key) ?? [];\n entries.push({ ...pending, promise } as PendingResponse<unknown>);\n this.#pending.set(key, entries);\n return promise;\n }\n\n resolve<T>(key: string, value: T): void {\n const entries = this.#pending.get(key);\n const pending = entries?.shift();\n if (pending === undefined) return;\n if (entries !== undefined && entries.length === 0) {\n this.#pending.delete(key);\n }\n pending.resolve(value);\n }\n\n reject(key: string, error: Error): void {\n const entries = this.#pending.get(key);\n const pending = entries?.shift();\n if (pending === undefined) return;\n if (entries !== undefined && entries.length === 0) {\n this.#pending.delete(key);\n }\n pending.reject(error);\n }\n\n remove<T>(key: string, promise: Promise<T>): void {\n const entries = this.#pending.get(key);\n if (entries === undefined) return;\n const remaining = entries.filter((entry) => entry.promise !== promise);\n if (remaining.length === 0) {\n this.#pending.delete(key);\n } else {\n this.#pending.set(key, remaining);\n }\n }\n\n rejectAll(error: Error): void {\n for (const entries of this.#pending.values()) {\n for (const pending of entries) {\n pending.reject(error);\n }\n }\n this.#pending.clear();\n }\n}\n\nfunction createPending<T>(): PendingResponse<T> {\n let resolve!: (value: T) => void;\n let reject!: (error: Error) => void;\n const promise = new Promise<T>((resolvePromise, rejectPromise) => {\n resolve = resolvePromise;\n reject = rejectPromise;\n });\n return { promise, reject, resolve };\n}\n","import {\n type OrderSide,\n type PositionId,\n toBaseUnits,\n} from '@polymarket/bindings';\nimport type { RfqSignedOrder } from '@polymarket/bindings/combos';\nimport type { EvmAddress, EvmSignature, HexString } from '@polymarket/types';\nimport { SigningError } from '../../errors';\nimport {\n calculateExchangeOrderMakerAmount,\n calculateExchangeOrderTakerAmount,\n createExchangeOrderSignature,\n createExchangeOrderTypedDataPayload,\n createExchangeV3OrderDomain,\n encodeExchangeOrderSide,\n} from '../../exchange';\nimport type { Signer } from '../../types';\nimport type { AccountIdentity } from '../../wallet';\nimport { resolveOrderIdentity } from '../../wallet';\n\nconst BYTES32_ZERO =\n '0x0000000000000000000000000000000000000000000000000000000000000000' satisfies HexString;\n\nexport type SignRfqQuoteOrderParams = {\n account: AccountIdentity;\n chainId: number;\n exchange: EvmAddress;\n orderPrice: bigint;\n orderSide: OrderSide;\n signer: Signer;\n size: bigint;\n tokenId: PositionId;\n};\n\nexport async function signRfqQuoteOrder(\n params: SignRfqQuoteOrderParams,\n): Promise<RfqSignedOrder> {\n const identity = resolveOrderIdentity(params.account);\n const domain = createExchangeV3OrderDomain({\n chainId: params.chainId,\n exchange: params.exchange,\n });\n const order: Omit<RfqSignedOrder, 'signature'> = {\n builder: BYTES32_ZERO,\n maker: identity.maker,\n makerAmount: toBaseUnits(\n calculateExchangeOrderMakerAmount(\n params.orderSide,\n params.orderPrice,\n params.size,\n ),\n ),\n metadata: BYTES32_ZERO,\n salt: generateRfqOrderSalt().toString(),\n side: encodeExchangeOrderSide(params.orderSide),\n signatureType: identity.signatureType,\n signer: identity.signer,\n takerAmount: toBaseUnits(\n calculateExchangeOrderTakerAmount(\n params.orderSide,\n params.orderPrice,\n params.size,\n ),\n ),\n timestamp: Math.floor(Date.now() / 1000).toString(),\n tokenId: params.tokenId,\n };\n\n let signature: EvmSignature;\n try {\n signature = await params.signer.signTypedData(\n createExchangeOrderTypedDataPayload({ domain, order }),\n );\n } catch (error) {\n throw SigningError.fromError(error, 'Could not sign the RFQ quote order.');\n }\n\n return {\n ...order,\n signature: createExchangeOrderSignature({ domain, order, signature }),\n };\n}\n\nfunction generateRfqOrderSalt(): bigint {\n const bytes = new Uint8Array(8);\n globalThis.crypto.getRandomValues(bytes);\n\n // RFQ salts stay strings on the wire, so the full 64-bit value is lossless.\n return BigInt(\n `0x${Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('')}`,\n );\n}\n","import {\n DecimalishSchema,\n type DecimalString,\n OrderSide,\n type PositionId,\n} from '@polymarket/bindings';\nimport {\n RfqDirection,\n type RfqQuoteRequest,\n type RfqRequestedSize,\n RfqRequestedSizeUnit,\n type RfqSignedOrder,\n} from '@polymarket/bindings/combos';\nimport type { EvmAddress } from '@polymarket/types';\nimport { z } from 'zod';\nimport type { RfqQuoteResponse, RfqQuoteSource } from '../../actions/rfq';\nimport { UserInputError } from '../../errors';\nimport { parseUserInput } from '../../input';\nimport type { Signer } from '../../types';\nimport type { AccountIdentity } from '../../wallet';\nimport { signRfqQuoteOrder } from './signing';\n\nconst DecimalishToBigIntSchema = DecimalishSchema.transform((value) =>\n decimalToScaledInteger(value),\n).refine((value) => value <= BigInt(Number.MAX_SAFE_INTEGER), {\n message: 'Value exceeds the temporary numeric wire limit.',\n});\n\nconst RfqQuoteResponseSchema = z.strictObject({\n price: DecimalishToBigIntSchema.refine((price) => price < 1_000_000n, {\n message: 'Price must be less than 1.',\n }),\n size: DecimalishToBigIntSchema.optional(),\n source: z.enum(['collateral', 'inventory']).default('collateral'),\n});\n\nexport type ParsedRfqQuoteResponse = {\n price: bigint;\n size?: bigint;\n source: RfqQuoteSource;\n};\n\nexport type CreateRfqQuoteParams = {\n account: AccountIdentity;\n chainId: number;\n exchange: EvmAddress;\n request: RfqQuoteRequest;\n response: ParsedRfqQuoteResponse;\n signer: Signer;\n};\n\nexport type RfqQuote = {\n price: bigint;\n signedOrder: RfqSignedOrder;\n size: bigint;\n};\n\nexport function parseRfqQuoteResponse(\n response: RfqQuoteResponse,\n): ParsedRfqQuoteResponse {\n return parseUserInput(response, RfqQuoteResponseSchema);\n}\n\nexport async function createRfqQuote(\n params: CreateRfqQuoteParams,\n): Promise<RfqQuote> {\n const price = params.response.price;\n const size =\n params.response.size === undefined\n ? defaultQuoteSize(params.request.requestedSize, price)\n : params.response.size;\n const signedOrder = await signRfqQuoteOrder({\n account: params.account,\n chainId: params.chainId,\n exchange: params.exchange,\n orderPrice: quoteOrderPrice(params.request, params.response.source, price),\n orderSide: quoteOrderSide(params.response.source),\n signer: params.signer,\n size,\n tokenId: quoteOrderTokenId(params.request, params.response.source),\n });\n\n return { price, signedOrder, size };\n}\n\nfunction quoteOrderTokenId(\n request: RfqQuoteRequest,\n source: RfqQuoteSource,\n): PositionId {\n if (request.direction === RfqDirection.Buy) {\n return source === 'collateral'\n ? request.noPositionId\n : request.yesPositionId;\n }\n\n return source === 'collateral' ? request.yesPositionId : request.noPositionId;\n}\n\nfunction quoteOrderPrice(\n request: RfqQuoteRequest,\n source: RfqQuoteSource,\n price: bigint,\n): bigint {\n const usesComplementPrice =\n (request.direction === RfqDirection.Buy && source === 'collateral') ||\n (request.direction === RfqDirection.Sell && source === 'inventory');\n\n return usesComplementPrice ? 1_000_000n - price : price;\n}\n\nfunction quoteOrderSide(source: RfqQuoteSource): OrderSide {\n return source === 'collateral' ? OrderSide.BUY : OrderSide.SELL;\n}\n\nfunction defaultQuoteSize(\n requestedSize: RfqRequestedSize,\n price: bigint,\n): bigint {\n const value = decimalToScaledInteger(requestedSize.value);\n\n if (requestedSize.unit === RfqRequestedSizeUnit.Shares) {\n return value;\n }\n\n return (value * 1_000_000n) / price;\n}\n\nfunction decimalToScaledInteger(value: DecimalString): bigint {\n const match = /^(\\d+)(?:\\.(\\d*))?$/.exec(value);\n if (match === null) {\n throw new UserInputError('Value must be a valid decimal.');\n }\n\n const [, whole = '', fraction = ''] = match;\n\n if (fraction.length > 6) {\n throw new UserInputError('Value must have at most 6 decimal places.');\n }\n\n const scaledValue =\n BigInt(whole) * 1_000_000n + BigInt(fraction.padEnd(6, '0'));\n\n if (scaledValue <= 0n) {\n throw new UserInputError('Value must be greater than 0.');\n }\n\n return scaledValue;\n}\n","import type { ApiKeyCreds } from '@polymarket/bindings/clob';\nimport {\n type RfqConfirmationDecision,\n type RfqErrorMessage,\n type RfqId,\n type RfqQuoteId,\n type RfqQuoteRequest,\n RfqQuoterInboundMessageSchema,\n type RfqQuoterOutboundMessage,\n} from '@polymarket/bindings/combos';\nimport { type EvmAddress, setNonBlockingTimeout } from '@polymarket/types';\nimport { type Pushable, pushable } from 'it-pushable';\nimport type {\n RfqCancelQuoteAck,\n RfqConfirmationAck,\n RfqEvent,\n RfqQuoteReference,\n RfqQuoteResponse,\n RfqSession,\n} from '../../actions/rfq';\nimport {\n RfqCancelQuoteRejectedError,\n RfqConfirmationRejectedError,\n RfqQuoteRejectedError,\n} from '../../actions/rfq';\nimport { ConnectionLostError, TransportError } from '../../errors';\nimport type { Signer } from '../../types';\nimport type { AccountIdentity } from '../../wallet';\nimport { type WebSocketCloseInfo, WebSocketConnection } from '../lifecycle';\nimport {\n type RfqEventController,\n toConfirmationAck,\n toConfirmationRequestEvent,\n toExecutionUpdateEvent,\n toQuoteAck,\n toQuoteCancelAck,\n toQuoteRequestEvent,\n toTradeEvent,\n} from './events';\nimport {\n createAuthMessage,\n createConfirmationResponseMessage,\n createQuoteCancelMessage,\n createQuoteMessage,\n} from './messages';\nimport { PendingResponses } from './pending';\nimport { createRfqQuote, parseRfqQuoteResponse } from './quote';\n\nconst AUTH_TIMEOUT_MS = 30_000;\nconst ACK_TIMEOUT_MS = 30_000;\n\nexport type RfqQuoterWebSocketManagerOptions = {\n account: AccountIdentity;\n chainId: number;\n credentials: ApiKeyCreds;\n exchange: EvmAddress;\n headers?: Record<string, string>;\n signer: Signer;\n url: string;\n};\n\nexport class RfqQuoterWebSocketManager {\n readonly #account: AccountIdentity;\n readonly #chainId: number;\n readonly #credentials: ApiKeyCreds;\n readonly #exchange: EvmAddress;\n readonly #headers: Record<string, string> | undefined;\n readonly #signer: Signer;\n readonly #url: string;\n #session: RfqWebSocketSession | undefined;\n #connectingSession: RfqWebSocketSession | undefined;\n #connecting: Promise<RfqSession> | undefined;\n #hasShutdown = false;\n\n constructor(options: RfqQuoterWebSocketManagerOptions) {\n this.#account = options.account;\n this.#chainId = options.chainId;\n this.#credentials = options.credentials;\n this.#exchange = options.exchange;\n this.#headers = options.headers;\n this.#signer = options.signer;\n this.#url = options.url;\n }\n\n async connect(): Promise<RfqSession> {\n if (this.#hasShutdown) {\n throw new TransportError('RFQ quoter manager has been shut down.');\n }\n\n if (this.#session !== undefined) {\n if (!this.#session.closed) return this.#session;\n this.#session = undefined;\n }\n if (this.#connecting !== undefined) return this.#connecting;\n\n const session = new RfqWebSocketSession({\n account: this.#account,\n chainId: this.#chainId,\n credentials: this.#credentials,\n exchange: this.#exchange,\n headers: this.#headers,\n onClose: () => this.#clearSession(session),\n signer: this.#signer,\n url: this.#url,\n });\n this.#connectingSession = session;\n\n let connecting!: Promise<RfqSession>;\n connecting = (async () => {\n try {\n await session.connect();\n if (this.#hasShutdown) {\n await session.close();\n throw new TransportError('RFQ quoter manager has been shut down.');\n }\n this.#session = session;\n return session;\n } catch (error) {\n await session.close();\n throw error;\n } finally {\n if (this.#connecting === connecting) {\n this.#connecting = undefined;\n }\n if (this.#connectingSession === session) {\n this.#connectingSession = undefined;\n }\n }\n })();\n\n this.#connecting = connecting;\n return connecting;\n }\n\n async shutdown(): Promise<void> {\n this.#hasShutdown = true;\n const session = this.#session;\n const connectingSession = this.#connectingSession;\n const connecting = this.#connecting;\n\n this.#session = undefined;\n this.#connectingSession = undefined;\n this.#connecting = undefined;\n\n await Promise.allSettled([\n session?.close(),\n connectingSession?.close(),\n connecting?.catch(() => undefined),\n ]).then(() => undefined);\n }\n\n #clearSession(session: RfqWebSocketSession): void {\n if (this.#session === session) {\n this.#session = undefined;\n }\n if (this.#connectingSession === session) {\n this.#connectingSession = undefined;\n }\n }\n}\n\ntype RfqWebSocketSessionConfig = {\n account: AccountIdentity;\n chainId: number;\n credentials: ApiKeyCreds;\n exchange: EvmAddress;\n headers?: Record<string, string>;\n onClose: () => void;\n signer: Signer;\n url: string;\n};\n\nclass RfqWebSocketSession implements RfqSession, RfqEventController {\n readonly #account: AccountIdentity;\n readonly #chainId: number;\n readonly #credentials: ApiKeyCreds;\n readonly #exchange: EvmAddress;\n readonly #headers: Record<string, string> | undefined;\n readonly #onClose: () => void;\n readonly #signer: Signer;\n readonly #url: string;\n readonly #connection = new WebSocketConnection();\n readonly #queue: Pushable<RfqEvent> = pushable({ objectMode: true });\n readonly #pending = new PendingResponses(ACK_TIMEOUT_MS);\n #closing: Promise<void> | undefined;\n #auth: PendingResponse<void> | undefined;\n\n constructor(options: RfqWebSocketSessionConfig) {\n this.#account = options.account;\n this.#chainId = options.chainId;\n this.#credentials = options.credentials;\n this.#exchange = options.exchange;\n this.#headers = options.headers;\n this.#onClose = options.onClose;\n this.#signer = options.signer;\n this.#url = options.url;\n }\n\n get closed(): boolean {\n return this.#closing !== undefined;\n }\n\n async connect(): Promise<void> {\n const auth = createPending<void>();\n this.#auth = auth;\n const authTimeout = setNonBlockingTimeout(() => {\n auth.reject(new TransportError('RFQ quoter authentication timed out.'));\n }, AUTH_TIMEOUT_MS);\n\n try {\n await this.#connection.connect({\n headers: this.#headers,\n onConnectionLost: (info) => this.#handleConnectionLost(info),\n onError: () => undefined,\n onMessage: (message) => this.#handleMessage(message),\n onOpen: () => this.#sendAuthMessage(),\n url: this.#url,\n });\n await auth.promise;\n } finally {\n clearTimeout(authTimeout);\n this.#auth = undefined;\n }\n }\n\n async #send(message: RfqQuoterOutboundMessage): Promise<void> {\n if (!this.#connection.send(message)) {\n throw new TransportError('RFQ quoter websocket is not open.');\n }\n }\n\n async close(): Promise<void> {\n if (this.#closing === undefined) {\n this.#closing = this.#shutdown();\n }\n await this.#closing;\n }\n\n [Symbol.asyncIterator](): AsyncIterator<RfqEvent> {\n return this.#queue[Symbol.asyncIterator]();\n }\n\n async #shutdown(): Promise<void> {\n const error = new TransportError('RFQ quoter websocket closed.');\n this.#failPending(error);\n this.#queue.end();\n await this.#connection.close();\n this.#onClose();\n }\n\n async #fail(error: Error): Promise<void> {\n if (this.#closing === undefined) {\n this.#closing = this.#shutdownWithError(error);\n }\n await this.#closing;\n }\n\n async #shutdownWithError(error: Error): Promise<void> {\n this.#failPending(error);\n this.#queue.end(error);\n await this.#connection.close();\n this.#onClose();\n }\n\n #failPending(error: Error): void {\n this.#auth?.reject(error);\n this.#pending.rejectAll(error);\n }\n\n #sendAuthMessage(): void {\n this.#connection.send(createAuthMessage(this.#account, this.#credentials));\n }\n\n #handleMessage(rawMessage: unknown): void {\n if (this.#closing !== undefined) return;\n\n const parsed = RfqQuoterInboundMessageSchema.safeParse(rawMessage);\n if (!parsed.success) return;\n\n const message = parsed.data;\n switch (message.type) {\n case 'auth':\n this.#handleAuthMessage(message);\n return;\n case 'quote_request':\n this.#queue.push(toQuoteRequestEvent(this, message));\n return;\n case 'quote_ack':\n this.#pending.resolve(quoteAckKey(message.rfqId), toQuoteAck(message));\n return;\n case 'quote_cancel_ack':\n this.#pending.resolve(\n quoteCancelAckKey(message.rfqId, message.quoteId),\n toQuoteCancelAck(message),\n );\n return;\n case 'confirmation_request':\n this.#queue.push(toConfirmationRequestEvent(this, message));\n return;\n case 'confirmation_ack':\n this.#pending.resolve(\n confirmationAckKey(message.rfqId, message.quoteId),\n toConfirmationAck(message),\n );\n return;\n case 'execution_update':\n this.#queue.push(toExecutionUpdateEvent(message));\n return;\n case 'trade':\n this.#queue.push(toTradeEvent(message));\n return;\n case 'rfq_error':\n this.#handleRfqError(message);\n return;\n }\n }\n\n #handleAuthMessage(message: { error?: string; success: boolean }): void {\n if (message.success === true) {\n this.#auth?.resolve(undefined);\n return;\n }\n this.#auth?.reject(\n new TransportError(`RFQ quoter authentication failed: ${message.error}`),\n );\n }\n\n #handleConnectionLost(info: WebSocketCloseInfo): void {\n void this.#fail(\n new ConnectionLostError('RFQ quoter connection lost.', info),\n );\n }\n\n // Unsupported RFQ_ERROR request types are ignored for forward compatibility.\n // Known outbound request errors without enough IDs are protocol failures.\n #handleRfqError(message: RfqErrorMessage): void {\n if (message.requestType === 'RFQ_QUOTE') {\n if (message.rfqId === undefined) {\n void this.#fail(new TransportError('Uncorrelated RFQ quoter error.'));\n return;\n }\n\n this.#pending.reject(\n quoteAckKey(message.rfqId),\n new RfqQuoteRejectedError(message.message, {\n code: message.code,\n errorId: message.errorId,\n rfqId: message.rfqId,\n }),\n );\n return;\n }\n\n if (message.requestType === 'RFQ_QUOTE_CANCEL') {\n if (message.rfqId === undefined || message.quoteId === undefined) {\n void this.#fail(new TransportError('Uncorrelated RFQ quoter error.'));\n return;\n }\n\n this.#pending.reject(\n quoteCancelAckKey(message.rfqId, message.quoteId),\n new RfqCancelQuoteRejectedError(message.message, {\n code: message.code,\n errorId: message.errorId,\n quoteId: message.quoteId,\n rfqId: message.rfqId,\n }),\n );\n return;\n }\n\n if (message.requestType === 'RFQ_CONFIRMATION_RESPONSE') {\n if (message.rfqId === undefined || message.quoteId === undefined) {\n void this.#fail(new TransportError('Uncorrelated RFQ quoter error.'));\n return;\n }\n\n this.#pending.reject(\n confirmationAckKey(message.rfqId, message.quoteId),\n new RfqConfirmationRejectedError(message.message, {\n code: message.code,\n errorId: message.errorId,\n quoteId: message.quoteId,\n rfqId: message.rfqId,\n }),\n );\n }\n }\n\n async quote(\n request: RfqQuoteRequest,\n response: RfqQuoteResponse,\n ): Promise<RfqQuoteReference> {\n const parsedResponse = parseRfqQuoteResponse(response);\n const quote = await createRfqQuote({\n account: this.#account,\n chainId: this.#chainId,\n exchange: this.#exchange,\n request,\n response: parsedResponse,\n signer: this.#signer,\n });\n const pending = this.#pending.waitFor<RfqQuoteReference>(\n quoteAckKey(request.rfqId),\n `Timed out waiting for RFQ quote acknowledgement for ${request.rfqId}.`,\n );\n try {\n await this.#send(createQuoteMessage(request, quote));\n return await pending;\n } catch (error) {\n this.#pending.remove(quoteAckKey(request.rfqId), pending);\n throw error;\n }\n }\n\n async cancelQuote(reference: RfqQuoteReference): Promise<RfqCancelQuoteAck> {\n const key = quoteCancelAckKey(reference.rfqId, reference.quoteId);\n const pending = this.#pending.waitFor<RfqCancelQuoteAck>(\n key,\n `Timed out waiting for RFQ quote cancellation acknowledgement for ${reference.rfqId}.`,\n );\n try {\n await this.#send(\n createQuoteCancelMessage(\n this.#account,\n reference.rfqId,\n reference.quoteId,\n ),\n );\n return await pending;\n } catch (error) {\n this.#pending.remove(key, pending);\n throw error;\n }\n }\n\n async respondToConfirmation(\n rfqId: RfqId,\n quoteId: RfqQuoteId,\n decision: RfqConfirmationDecision,\n ): Promise<RfqConfirmationAck> {\n const key = confirmationAckKey(rfqId, quoteId);\n const pending = this.#pending.waitFor<RfqConfirmationAck>(\n key,\n `Timed out waiting for RFQ confirmation acknowledgement for ${rfqId}.`,\n );\n try {\n await this.#send(\n createConfirmationResponseMessage(rfqId, quoteId, decision),\n );\n return await pending;\n } catch (error) {\n this.#pending.remove(key, pending);\n throw error;\n }\n }\n}\n\nfunction quoteAckKey(rfqId: RfqId): string {\n return `ACK_RFQ_QUOTE:${rfqId}`;\n}\n\nfunction quoteCancelAckKey(rfqId: RfqId, quoteId: RfqQuoteId): string {\n return `ACK_RFQ_QUOTE_CANCEL:${rfqId}:${quoteId}`;\n}\n\nfunction confirmationAckKey(rfqId: RfqId, quoteId: RfqQuoteId): string {\n return `ACK_RFQ_CONFIRMATION_RESPONSE:${rfqId}:${quoteId}`;\n}\n\ntype PendingResponse<T> = {\n promise: Promise<T>;\n reject(error: Error): void;\n resolve(value: T): void;\n};\n\nfunction createPending<T>(): PendingResponse<T> {\n let resolve!: (value: T) => void;\n let reject!: (error: Error) => void;\n const promise = new Promise<T>((resolvePromise, rejectPromise) => {\n resolve = resolvePromise;\n reject = rejectPromise;\n });\n return { promise, reject, resolve };\n}\n","import {\n type CommentsEvent,\n type CryptoPricesChainlinkTwapWindowSeconds,\n type CryptoPricesEvent,\n type EquityPricesEvent,\n RealtimeEventSchema,\n} from '@polymarket/bindings/subscriptions';\nimport { invariant } from '@polymarket/types';\nimport type {\n CommentsSubscription,\n CryptoPricesChainlinkTwapSubscription,\n CryptoPricesSubscription,\n EquityPricesSubscription,\n SubscriptionHandle,\n} from '../actions/subscriptions';\nimport { createSubscriptionHandle } from './handle';\nimport { RtdsWebSocketHeartbeat } from './heartbeat';\nimport {\n ReconnectScheduler,\n WebSocketConnection,\n type WebSocketConnectionResult,\n} from './lifecycle';\nimport {\n SubscriptionRegistry,\n type SubscriptionRegistryChange,\n type SubscriptionRegistryEntry,\n} from './registry';\nimport type { WebSocketSubscriptionManager } from './types';\n\ntype RtdsSpec =\n | CommentsSubscription\n | CryptoPricesSubscription\n | CryptoPricesChainlinkTwapSubscription\n | EquityPricesSubscription;\n\ntype RtdsEvent = CommentsEvent | CryptoPricesEvent | EquityPricesEvent;\n\ntype RtdsSubscriptionEntry = SubscriptionRegistryEntry<RtdsSpec, RtdsEvent>;\n\ntype RtdsServerSubscription = {\n key: string;\n topic: string;\n type: string;\n};\n\ntype RtdsServerState = Map<string, RtdsServerSubscription>;\n\nexport type RtdsWebSocketManagerOptions = {\n headers?: Record<string, string>;\n url: string;\n};\n\n/**\n * Realtime Data Service (RTDS) WebSocket manager.\n *\n * Implements {@link WebSocketSubscriptionManager} for the comments, crypto prices, and\n * equity prices topics multiplexed over a single shared upstream socket\n * opened lazily on the first subscribe.\n */\nexport class RtdsWebSocketManager\n implements WebSocketSubscriptionManager<RtdsSpec, RtdsEvent>\n{\n readonly #headers: Record<string, string> | undefined;\n readonly #url: string;\n #closing: Promise<void> | undefined;\n readonly #connection = new WebSocketConnection({\n heartbeat: new RtdsWebSocketHeartbeat(),\n });\n readonly #reconnectScheduler = new ReconnectScheduler();\n readonly #subscriptions = new SubscriptionRegistry<\n RtdsSpec,\n RtdsEvent,\n RtdsServerState\n >({ deriveServerState: deriveRtdsServerState });\n\n constructor(options: RtdsWebSocketManagerOptions) {\n this.#headers = options.headers;\n this.#url = options.url;\n }\n\n async subscribe(\n subscription: RtdsSpec,\n ): Promise<SubscriptionHandle<RtdsEvent>> {\n const { change, entry } = this.#subscriptions.add(subscription, {\n matches: matcherFor(subscription),\n });\n await this.#registerSubscriber(entry, change);\n return createSubscriptionHandle(entry.subscriber.queue, () =>\n this.#closeSubscriber(entry),\n );\n }\n\n // Subscription handle lifecycle.\n\n async #registerSubscriber(\n entry: RtdsSubscriptionEntry,\n change: SubscriptionRegistryChange<RtdsServerState>,\n ): Promise<void> {\n try {\n const connection = await this.#connect();\n if (connection.reusedOpenSocket) {\n const { before, after } = change;\n const subscriptionsToOpen = serverSubscriptionsAdded(before, after);\n this.#sendSubscribeFrame(subscriptionsToOpen);\n }\n } catch (error) {\n await this.#closeSubscriber(entry);\n throw error;\n }\n }\n\n async #closeSubscriber(entry: RtdsSubscriptionEntry): Promise<void> {\n const { before, after } = this.#subscriptions.remove(entry);\n const subscriptionsToClose = serverSubscriptionsRemoved(before, after);\n this.#sendUnsubscribeFrame(subscriptionsToClose);\n if (!this.#subscriptions.hasActiveSubscriptions()) {\n await this.close();\n }\n }\n\n // Socket lifecycle.\n\n async close(): Promise<void> {\n if (this.#closing === undefined) {\n this.#closing = this.#shutdown().finally(() => {\n this.#closing = undefined;\n });\n }\n await this.#closing;\n }\n\n async #shutdown(): Promise<void> {\n this.#reconnectScheduler.stop();\n this.#subscriptions.endAll();\n\n await this.#connection.close();\n }\n\n #connect(): Promise<WebSocketConnectionResult> {\n return this.#connection.connect({\n onConnectionLost: () => this.#onConnectionLost(),\n onError: () => this.#onConnectionError(),\n onMessage: (message) => this.#onConnectionMessage(message),\n onOpen: () => this.#onConnectionOpen(),\n headers: this.#headers,\n url: this.#url,\n });\n }\n\n #onConnectionOpen(): void {\n this.#reconnectScheduler.resetBackoff();\n this.#resubscribeActiveServerEntries();\n }\n\n #onConnectionMessage(message: unknown): void {\n const parsed = RealtimeEventSchema.safeParse(message);\n if (!parsed.success) return;\n this.#subscriptions.dispatch(parsed.data);\n }\n\n #onConnectionLost(): void {\n if (this.#subscriptions.hasActiveSubscriptions()) {\n this.#scheduleReconnect();\n }\n }\n\n #onConnectionError(): void {\n // Browser WebSockets report most failures as an error followed by close.\n // Keep iterators alive here so the close path can reconnect active handles.\n }\n\n // RTDS subscribe/unsubscribe frames.\n\n #resubscribeActiveServerEntries(): void {\n this.#sendSubscribeFrame(\n Array.from(this.#subscriptions.serverState().values()),\n );\n }\n\n #sendSubscribeFrame(subscriptions: readonly RtdsServerSubscription[]): void {\n if (subscriptions.length === 0) return;\n this.#connection.send(buildSubscribeMessage(subscriptions));\n }\n\n #sendUnsubscribeFrame(\n subscriptions: readonly RtdsServerSubscription[],\n ): void {\n if (subscriptions.length === 0) return;\n this.#connection.send(buildUnsubscribeMessage(subscriptions));\n }\n\n #scheduleReconnect(): void {\n this.#reconnectScheduler.schedule({\n reconnect: () => this.#connect(),\n shouldReconnect: () => this.#subscriptions.hasActiveSubscriptions(),\n });\n }\n}\n\nfunction serverSubscriptionsAdded(\n before: ReadonlyMap<string, RtdsServerSubscription>,\n after: ReadonlyMap<string, RtdsServerSubscription>,\n): RtdsServerSubscription[] {\n return Array.from(after).flatMap(([key, subscription]) =>\n before.has(key) ? [] : [subscription],\n );\n}\n\nfunction serverSubscriptionsRemoved(\n before: ReadonlyMap<string, RtdsServerSubscription>,\n after: ReadonlyMap<string, RtdsServerSubscription>,\n): RtdsServerSubscription[] {\n return Array.from(before).flatMap(([key, subscription]) =>\n after.has(key) ? [] : [subscription],\n );\n}\n\nfunction deriveRtdsServerState(\n entries: Iterable<RtdsSubscriptionEntry>,\n): RtdsServerState {\n const activeByKey = new Map<string, RtdsServerSubscription>();\n for (const { subscription } of entries) {\n for (const serverSubscription of serverSubscriptionsFor(subscription)) {\n if (!activeByKey.has(serverSubscription.key)) {\n activeByKey.set(serverSubscription.key, serverSubscription);\n }\n }\n }\n return activeByKey;\n}\n\nfunction buildSubscribeMessage(\n subscriptions: readonly RtdsServerSubscription[],\n): unknown {\n return {\n action: 'subscribe',\n subscriptions: subscriptions.map(({ topic, type }) => ({ topic, type })),\n };\n}\n\nfunction buildUnsubscribeMessage(\n subscriptions: readonly RtdsServerSubscription[],\n): unknown {\n return {\n action: 'unsubscribe',\n subscriptions: subscriptions.map(({ topic, type }) => ({ topic, type })),\n };\n}\n\nfunction serverSubscriptionsFor(\n subscription: RtdsSpec,\n): RtdsServerSubscription[] {\n switch (subscription.topic) {\n case 'comments':\n // RTDS tracks subscription state per (topic, type): different comment\n // event types coexist independently on the same socket, so one entry\n // per requested type. No server-side filters — any narrowing by\n // parentEntityID/parentEntityType happens client-side via matcherFor.\n return (subscription.types ?? ['comment_created']).map((type) =>\n serverSubscription('comments', type),\n );\n case 'prices.crypto.binance':\n // Subscribe broadly and filter client-side. Sending a second subscribe\n // frame with a different `filters` value on the same socket causes the\n // server to replace the prior subscription rather than add one, so\n // multiple subscribers on the same manager cannot share a socket while\n // using server-side filters. See docs/api-boundary-notes.md.\n return [serverSubscription('crypto_prices', 'update')];\n case 'prices.crypto.chainlink':\n // RTDS tracks one filter per topic per connection, so a second subscribe\n // with a different filter replaces the first. Subscribe broadly and\n // filter client-side — see docs/api-boundary-notes.md.\n return [serverSubscription('crypto_prices_chainlink', 'update')];\n case 'prices.crypto.chainlink.twap':\n // Each TWAP window is a distinct RTDS topic. Subscribe broadly within\n // the requested window and narrow symbols client-side so subscribers for\n // the same window can safely share a socket.\n return [\n serverSubscription(\n twapServerTopic(subscription.windowSeconds),\n 'update',\n ),\n ];\n case 'prices.equity.pyth':\n // Same per-topic replace-on-resubscribe constraint as crypto_prices. A\n // single unfiltered subscribe covers every active equity symbol; the\n // client-side matcher narrows to the caller's requested symbol.\n return [serverSubscription('equity_prices', 'update')];\n default: {\n const neverSpec: never = subscription;\n invariant(false, `Unknown RTDS topic: ${String(neverSpec)}`);\n }\n }\n}\n\nfunction twapServerTopic(\n windowSeconds: CryptoPricesChainlinkTwapWindowSeconds,\n): string {\n switch (windowSeconds) {\n case 30:\n return 'crypto_prices_twap_thirty';\n case 60:\n return 'crypto_prices_twap_sixty';\n default: {\n const neverWindow: never = windowSeconds;\n invariant(false, `Unknown TWAP window: ${String(neverWindow)}`);\n }\n }\n}\n\nfunction serverSubscription(\n topic: string,\n type: string,\n): RtdsServerSubscription {\n return {\n key: `${topic}:${type}`,\n topic,\n type,\n };\n}\n\nfunction matcherFor(subscription: RtdsSpec): (event: RtdsEvent) => boolean {\n switch (subscription.topic) {\n case 'comments':\n // All `comments` narrowing happens client-side because the RTDS server\n // uses opaque substring matching on `filters` rather than structured\n // fields. When the caller sets `parentEntityId` or `parentEntityType`,\n // reaction events are dropped: their payloads carry only `commentID`,\n // not the parent context, so we can't verify the filter on them. Rule:\n // if a filter can't be verified on an event, the event doesn't match.\n // See docs/api-boundary-notes.md.\n return (event) => {\n if (event.topic !== 'comments') return false;\n if (\n subscription.types !== undefined &&\n subscription.types.length > 0 &&\n !subscription.types.includes(event.type)\n ) {\n return false;\n }\n const hasParentFilter =\n subscription.parentEntityId !== undefined ||\n subscription.parentEntityType !== undefined;\n if (hasParentFilter) {\n const carriesParentContext =\n event.type === 'comment_created' ||\n event.type === 'comment_removed';\n if (!carriesParentContext) return false;\n if (\n subscription.parentEntityId !== undefined &&\n event.payload.parentEntityID !== subscription.parentEntityId\n ) {\n return false;\n }\n if (\n subscription.parentEntityType !== undefined &&\n event.payload.parentEntityType !== subscription.parentEntityType\n ) {\n return false;\n }\n }\n return true;\n };\n case 'prices.crypto.binance':\n return (event) =>\n event.topic === 'prices.crypto.binance' &&\n (subscription.symbols === undefined ||\n subscription.symbols.length === 0 ||\n subscription.symbols.includes(event.payload.symbol));\n case 'prices.crypto.chainlink':\n return (event) =>\n event.topic === 'prices.crypto.chainlink' &&\n (subscription.symbols === undefined ||\n subscription.symbols.length === 0 ||\n subscription.symbols.includes(event.payload.symbol));\n case 'prices.crypto.chainlink.twap':\n return (event) =>\n event.topic === 'prices.crypto.chainlink.twap' &&\n event.payload.windowSeconds === subscription.windowSeconds &&\n (subscription.symbols === undefined ||\n subscription.symbols.length === 0 ||\n subscription.symbols.includes(event.payload.symbol));\n case 'prices.equity.pyth':\n // RTDS emits every event kind for a topic regardless of the `type` value\n // in the subscribe frame, so the caller's `types` filter must be\n // enforced client-side here.\n return (event) =>\n event.topic === 'prices.equity.pyth' &&\n event.payload.symbol.toLowerCase() ===\n subscription.symbol.toLowerCase() &&\n (subscription.types === undefined ||\n subscription.types.length === 0 ||\n subscription.types.includes(event.type));\n default: {\n const neverSpec: never = subscription;\n invariant(false, `Unknown RTDS topic: ${String(neverSpec)}`);\n }\n }\n}\n","import {\n type SportsEvent,\n SportsResultEventSchema,\n} from '@polymarket/bindings/subscriptions';\nimport type {\n SportsSubscription,\n SubscriptionHandle,\n} from '../actions/subscriptions';\nimport { createSubscriptionHandle } from './handle';\nimport { SportsWebSocketHeartbeat } from './heartbeat';\nimport {\n ReconnectScheduler,\n WebSocketConnection,\n type WebSocketConnectionResult,\n} from './lifecycle';\nimport {\n SubscriptionRegistry,\n type SubscriptionRegistryEntry,\n} from './registry';\nimport type { WebSocketSubscriptionManager } from './types';\n\ntype SportsSubscriptionEntry = SubscriptionRegistryEntry<\n SportsSubscription,\n SportsEvent\n>;\n\nexport type SportsWebSocketManagerOptions = {\n headers?: Record<string, string>;\n url: string;\n};\n\n/**\n * Sports WebSocket manager.\n *\n * The sports stream starts sending events immediately after connection and does\n * not require a subscribe frame. The server sends `ping`; clients must reply\n * with `pong` to keep the socket alive.\n */\nexport class SportsWebSocketManager\n implements WebSocketSubscriptionManager<SportsSubscription, SportsEvent>\n{\n readonly #headers: Record<string, string> | undefined;\n readonly #url: string;\n #closing: Promise<void> | undefined;\n readonly #connection = new WebSocketConnection({\n heartbeat: new SportsWebSocketHeartbeat(),\n });\n readonly #reconnectScheduler = new ReconnectScheduler();\n readonly #subscriptions = new SubscriptionRegistry<\n SportsSubscription,\n SportsEvent\n >();\n\n constructor(options: SportsWebSocketManagerOptions) {\n this.#headers = options.headers;\n this.#url = options.url;\n }\n\n async subscribe(\n subscription: SportsSubscription,\n ): Promise<SubscriptionHandle<SportsEvent>> {\n const { entry } = this.#subscriptions.add(subscription);\n\n await this.#registerSubscriber(entry);\n return createSubscriptionHandle(entry.subscriber.queue, () =>\n this.#closeSubscriber(entry),\n );\n }\n\n // Subscription handle lifecycle.\n\n async #registerSubscriber(entry: SportsSubscriptionEntry): Promise<void> {\n try {\n await this.#connect();\n } catch (error) {\n await this.#closeSubscriber(entry);\n throw error;\n }\n }\n\n async #closeSubscriber(entry: SportsSubscriptionEntry): Promise<void> {\n this.#subscriptions.remove(entry);\n\n if (!this.#subscriptions.hasActiveSubscriptions()) {\n await this.close();\n }\n }\n\n // Socket lifecycle.\n\n async close(): Promise<void> {\n if (this.#closing === undefined) {\n this.#closing = this.#shutdown().finally(() => {\n this.#closing = undefined;\n });\n }\n await this.#closing;\n }\n\n async #shutdown(): Promise<void> {\n this.#reconnectScheduler.stop();\n this.#subscriptions.endAll();\n\n await this.#connection.close();\n }\n\n #connect(): Promise<WebSocketConnectionResult> {\n return this.#connection.connect({\n onConnectionLost: () => this.#onConnectionLost(),\n onError: () => this.#onConnectionError(),\n onMessage: (message) => this.#onConnectionMessage(message),\n onOpen: () => this.#onConnectionOpen(),\n headers: this.#headers,\n url: this.#url,\n });\n }\n\n #onConnectionOpen(): void {\n this.#reconnectScheduler.resetBackoff();\n }\n\n #onConnectionMessage(message: unknown): void {\n const parsed = SportsResultEventSchema.safeParse(message);\n if (!parsed.success) return;\n this.#subscriptions.dispatch(parsed.data);\n }\n\n #onConnectionLost(): void {\n if (this.#subscriptions.hasActiveSubscriptions()) {\n this.#scheduleReconnect();\n }\n }\n\n #onConnectionError(): void {\n // Browser WebSockets report most failures as an error followed by close.\n // Keep iterators alive here so the close path can reconnect active handles.\n }\n\n #scheduleReconnect(): void {\n this.#reconnectScheduler.schedule({\n reconnect: () => this.#connect(),\n shouldReconnect: () => this.#subscriptions.hasActiveSubscriptions(),\n });\n }\n}\n","import { ApiKeySchema, EvmAddressSchema } from '@polymarket/bindings';\nimport type { ApiKeyCreds } from '@polymarket/bindings/clob';\nimport { WalletType } from '@polymarket/bindings/gamma';\nimport {\n expectEvmAddress,\n expectEvmSignature,\n invariant,\n isSameEvmAddress,\n type Prettify,\n} from '@polymarket/types';\nimport { z } from 'zod';\nimport {\n createOrDeriveApiKey,\n deleteApiKey,\n fetchApiKeys,\n} from './actions/auth';\nimport {\n type DeployDepositWalletError,\n deployDepositWallet,\n type IsWalletDeployedError,\n isWalletDeployed,\n type WaitForGaslessTransactionError,\n} from './actions/gasless';\nimport { createApiKeyAuthTypedDataPayload } from './authentication';\nimport {\n allActions,\n type PublicActions,\n type SecureActions,\n} from './decorators';\nimport { type EnvironmentConfig, production } from './environments';\nimport {\n CancelledSigningError,\n makeErrorGuard,\n RateLimitError,\n RequestRejectedError,\n SigningError,\n TimeoutError,\n TransactionFailedError,\n TransportError,\n UnexpectedResponseError,\n UserInputError,\n} from './errors';\nimport { buildHmacSignature } from './hmac';\nimport { parseUserInput } from './input';\nimport type { RateLimitUpdateListener } from './rate-limit';\nimport { JsonRpcClient } from './rpc';\nimport type { ServiceRequest } from './ServiceClient';\nimport { ServiceClient } from './ServiceClient';\nimport type { ApiKeyAuthorization, Signer } from './types';\nimport type { AccountIdentity } from './wallet';\nimport {\n deriveBeaconDepositWalletAddress,\n deriveUupsDepositWalletAddress,\n resolveAccountIdentity,\n} from './wallet';\nimport {\n ClobMarketWebSocketManager,\n ClobUserWebSocketManager,\n PerpsSessionManager,\n PerpsSubscriptionManager,\n type PublicWebSocketManagers,\n RfqQuoterWebSocketManager,\n RtdsWebSocketManager,\n type SecureWebSocketManagers,\n SportsWebSocketManager,\n} from './websockets';\nimport {\n type AuthenticationWorkflow,\n authenticateWith,\n requestAddress,\n} from './workflow';\n\ntype PublicContext = {\n /** @internal */\n apiKey?: ApiKeyAuthorization;\n /** @internal */\n environment: EnvironmentConfig;\n /** @internal */\n onRateLimitUpdate?: RateLimitUpdateListener;\n /** @internal */\n clob: ServiceClient;\n /** @internal */\n relayer: ServiceClient;\n /** @internal */\n rpc: JsonRpcClient;\n /** @internal */\n gamma: ServiceClient;\n /** @internal */\n data: ServiceClient;\n /** @internal */\n rfq: ServiceClient;\n /** @internal */\n perps: ServiceClient;\n /** @internal */\n webSockets: PublicWebSocketManagers;\n};\n\n// biome-ignore lint/complexity/noBannedTypes: intentional\nexport type ClientActions = {};\n\nexport type ClientDecorator<\n TPublicActions extends ClientActions = ClientActions,\n TSecureActions extends ClientActions = TPublicActions,\n> = {\n (client: BasePublicClient<ClientActions, ClientActions>): TPublicActions;\n (client: BaseSecureClient<ClientActions, ClientActions>): TSecureActions;\n};\n\ntype DecoratorPublicActions<TDecorator extends ClientDecorator> =\n TDecorator extends ClientDecorator<\n infer TPublicActions,\n infer _TSecureActions\n >\n ? TPublicActions\n : never;\n\ntype DecoratorSecureActions<TDecorator extends ClientDecorator> =\n TDecorator extends ClientDecorator<\n infer _TPublicActions,\n infer TSecureActions\n >\n ? TSecureActions\n : never;\n\nabstract class AbstractClient<TContext extends PublicContext> {\n // Keep the backing context off the public object shape so accidental\n // client logs do not print secure credentials.\n readonly #context: TContext;\n readonly #decorators: ClientDecorator[];\n\n protected get context(): TContext {\n return this.#context;\n }\n\n protected get decorators(): readonly ClientDecorator[] {\n return this.#decorators;\n }\n\n /** @internal */\n get environment(): EnvironmentConfig {\n return this.context.environment;\n }\n\n /** @internal */\n get clob(): ServiceClient {\n return this.context.clob;\n }\n\n /** @internal */\n get relayer(): ServiceClient {\n return this.context.relayer;\n }\n\n /** @internal */\n get rpc(): JsonRpcClient {\n return this.context.rpc;\n }\n\n /** @internal */\n get gamma(): ServiceClient {\n return this.context.gamma;\n }\n\n /** @internal */\n get data(): ServiceClient {\n return this.context.data;\n }\n\n /** @internal */\n get rfq(): ServiceClient {\n return this.context.rfq;\n }\n\n /** @internal */\n get perps(): ServiceClient {\n return this.context.perps;\n }\n\n /** @internal */\n get webSockets(): PublicWebSocketManagers {\n return this.context.webSockets;\n }\n\n /** @internal */\n get supportsGasless(): boolean {\n return this.context.apiKey?.supportGasless ?? false;\n }\n\n /** @internal */\n get hasBuilderApiKey(): boolean {\n return this.context.apiKey?.isBuilderKey ?? false;\n }\n\n constructor(context: TContext) {\n this.#context = context;\n this.#decorators = [];\n }\n\n protected async resolveClobHeaders(\n request: ServiceRequest,\n ): Promise<HeadersInit> {\n if (this.context.apiKey?.isBuilderKey) {\n return this.context.apiKey.authorize(request);\n }\n return Promise.resolve({});\n }\n\n protected async resolveRelayerHeaders(\n request: ServiceRequest,\n ): Promise<HeadersInit> {\n if (this.context.apiKey?.supportGasless) {\n return this.context.apiKey.authorize(request);\n }\n return Promise.resolve({});\n }\n\n protected rememberDecorator(decorator: ClientDecorator): void {\n this.#decorators.push(decorator);\n }\n}\n\nconst BeginAuthenticationCredentialsSchema = z.object({\n key: ApiKeySchema,\n passphrase: z.string(),\n secret: z.string(),\n});\n\nexport type BeginAuthenticationRequest = {\n /**\n * Wallet address to authenticate as.\n *\n * Pass the signer address itself to authenticate as an EOA account.\n */\n wallet: string;\n\n /**\n * Nonce used when creating or deriving fresh credentials.\n *\n * Mutually exclusive with `credentials`.\n *\n * @defaultValue 0\n */\n nonce?: number;\n\n /**\n * Existing API credentials to reuse when they remain valid.\n *\n * If these credentials are revoked or invalid, authentication falls back to\n * fresh authentication and the signer may be asked to sign again.\n */\n credentials?: ApiKeyCreds;\n};\n\nconst BeginAuthenticationRequestSchema: z.ZodType<BeginAuthenticationRequest> =\n z\n .object({\n wallet: EvmAddressSchema,\n credentials: BeginAuthenticationCredentialsSchema.optional(),\n nonce: z.number().int().nonnegative().optional(),\n })\n .superRefine((value, context) => {\n if (value.credentials !== undefined && value.nonce !== undefined) {\n context.addIssue({\n code: 'custom',\n message: '`credentials` and `nonce` are mutually exclusive.',\n path: ['nonce'],\n });\n }\n })\n .transform((value): BeginAuthenticationRequest => {\n if (value.credentials !== undefined) {\n return {\n wallet: value.wallet,\n credentials: value.credentials,\n };\n }\n\n if (value.nonce !== undefined) {\n return {\n wallet: value.wallet,\n nonce: value.nonce,\n };\n }\n\n return {\n wallet: value.wallet,\n };\n });\n\ntype PublicClientConfig = {\n environment: EnvironmentConfig;\n apiKey?: ApiKeyAuthorization;\n onRateLimitUpdate?: RateLimitUpdateListener;\n};\n\nclass BasePublicClient<\n TPublicActions extends ClientActions = ClientActions,\n TSecureActions extends ClientActions = TPublicActions,\n> extends AbstractClient<PublicContext> {\n constructor(config: PublicClientConfig) {\n super({\n apiKey: config.apiKey,\n environment: config.environment,\n onRateLimitUpdate: config.onRateLimitUpdate,\n data: new ServiceClient({\n headers: config.environment.data.headers,\n root: config.environment.data.rest,\n }),\n gamma: new ServiceClient({\n headers: config.environment.gamma.headers,\n root: config.environment.gamma.rest,\n }),\n clob: new ServiceClient({\n headers: config.environment.clob.headers,\n onRateLimitUpdate: config.onRateLimitUpdate,\n root: config.environment.clob.rest,\n resolveHeaders: (request) => this.resolveClobHeaders(request),\n }),\n relayer: new ServiceClient({\n headers: config.environment.relayer.headers,\n root: config.environment.relayer.rest,\n resolveHeaders: (request) => this.resolveRelayerHeaders(request),\n }),\n rfq: new ServiceClient({\n headers: config.environment.combos.headers,\n root: config.environment.combos.rest,\n }),\n perps: new ServiceClient({\n headers: config.environment.perps.headers,\n root: config.environment.perps.rest,\n }),\n rpc: new JsonRpcClient({ url: config.environment.rpc }),\n webSockets: {\n clobMarket: new ClobMarketWebSocketManager({\n headers: config.environment.clob.market.headers,\n url: config.environment.clob.market.ws,\n }),\n sports: new SportsWebSocketManager({\n headers: config.environment.sports.headers,\n url: config.environment.sports.ws,\n }),\n rtds: new RtdsWebSocketManager({\n headers: config.environment.rtds.headers,\n url: config.environment.rtds.ws,\n }),\n perpsSubscriptions: new PerpsSubscriptionManager({\n headers: config.environment.perps.headers,\n url: config.environment.perps.ws,\n }),\n },\n });\n }\n\n /**\n * Use this to narrow a {@link Client} union to {@link SecureClient}.\n *\n * @example\n * ```ts\n * if (client.isSecureClient()) {\n * client.credentials; // SecureClient\n * }\n * ```\n */\n isSecureClient(): this is BaseSecureClient<TPublicActions, TSecureActions> {\n return false;\n }\n\n /**\n * Use this to narrow a {@link Client} union to {@link PublicClient}.\n *\n * @example\n * ```ts\n * if (client.isPublicClient()) {\n * client.closeSubscriptions(); // PublicClient\n * }\n * ```\n */\n isPublicClient(): this is BasePublicClient<TPublicActions, TSecureActions> {\n return true;\n }\n\n /**\n * Closes all active realtime subscriptions owned by this client.\n *\n * @remarks\n * This ends active subscription iterators and closes shared websocket\n * connections. It does not affect authentication or other client state.\n *\n * @example\n * ```ts\n * await client.closeSubscriptions();\n * ```\n */\n async closeSubscriptions(): Promise<void> {\n await Promise.all([\n this.webSockets.clobMarket.close(),\n this.webSockets.rtds.close(),\n this.webSockets.sports.close(),\n this.webSockets.perpsSubscriptions.close(),\n ]).then(() => undefined);\n }\n\n /**\n * Returns a client typed with the methods contributed by the decorator.\n */\n extend<TDecorator extends ClientDecorator>(\n decorator: TDecorator,\n ): PublicClient<\n Prettify<TPublicActions & DecoratorPublicActions<TDecorator>>,\n Prettify<TSecureActions & DecoratorSecureActions<TDecorator>>\n > {\n this.rememberDecorator(decorator);\n Object.assign(this, decorator(this));\n return this as unknown as PublicClient<\n Prettify<TPublicActions & DecoratorPublicActions<TDecorator>>,\n Prettify<TSecureActions & DecoratorSecureActions<TDecorator>>\n >;\n }\n\n /**\n * Begins an authentication workflow that produces a {@link SecureClient}.\n *\n * @remarks\n * This is a low-level method for building wallet-interactive workflows. Most\n * applications should use {@link createSecureClient} instead.\n *\n * @internal\n */\n beginAuthentication(\n request: BeginAuthenticationRequest,\n signer: Signer,\n ): Promise<\n AuthenticationWorkflow<SecureClient<TPublicActions, TSecureActions>>\n > {\n const params = parseUserInput(request, BeginAuthenticationRequestSchema);\n\n return Promise.resolve(\n async function* (\n this: PublicClient<TPublicActions, TSecureActions>,\n ): AuthenticationWorkflow<SecureClient<TPublicActions, TSecureActions>> {\n const timestamp = Math.floor(Date.now() / 1000);\n const nonce = params?.nonce ?? 0;\n const signerAddress = expectEvmAddress(yield requestAddress());\n const wallet = expectEvmAddress(params.wallet);\n const identity = resolveAccountIdentity(\n this.environment,\n signerAddress,\n wallet,\n );\n\n if (params.credentials !== undefined) {\n const client = this.#createSecureClient(\n params.credentials,\n identity,\n signer,\n );\n\n try {\n const apiKeys = await fetchApiKeys(client);\n if (apiKeys.includes(params.credentials.key)) {\n return client;\n }\n } catch (error) {\n if (\n !(error instanceof RequestRejectedError) ||\n error.status !== 401\n ) {\n throw error;\n }\n }\n }\n\n const signature = yield {\n kind: 'signAuthMessage',\n payload: createApiKeyAuthTypedDataPayload({\n address: signerAddress,\n chainId: this.environment.chainId,\n nonce,\n timestamp,\n }),\n };\n const credentials = await createOrDeriveApiKey(this, {\n address: signerAddress,\n nonce,\n signature: expectEvmSignature(signature),\n timestamp,\n });\n\n return this.#createSecureClient(credentials, identity, signer);\n }.call(this as unknown as PublicClient<TPublicActions, TSecureActions>),\n );\n }\n\n #createSecureClient(\n credentials: ApiKeyCreds,\n account: AccountIdentity,\n signer: Signer,\n ): SecureClient<TPublicActions, TSecureActions> {\n const client = new BaseSecureClient({\n account: account,\n apiKey: this.context.apiKey,\n credentials,\n environment: this.environment,\n onRateLimitUpdate: this.context.onRateLimitUpdate,\n signer,\n });\n\n for (const decorator of this.decorators) {\n client.extend(decorator);\n }\n\n return client as SecureClient<TPublicActions, TSecureActions>;\n }\n}\n\nclass BaseSecureClient<\n TPublicActions extends ClientActions = ClientActions,\n TSecureActions extends ClientActions = TPublicActions,\n> extends AbstractClient<SecureContext> {\n #hasEndedAuthentication = false;\n\n /**\n * @remarks This is the choking point for all requests, so we can ensure that once\n * `endAuthentication` is called, no further authenticated requests can be made with this client instance.\n */\n protected override get context(): SecureContext {\n invariant(\n !this.#hasEndedAuthentication,\n 'This client has ended authentication and can no longer be used.',\n );\n\n return super.context;\n }\n\n protected endAuthenticationLifecycle(): void {\n this.#hasEndedAuthentication = true;\n }\n\n constructor(config: SecureClientConfig) {\n super({\n account: config.account,\n credentials: config.credentials,\n apiKey: config.apiKey,\n environment: config.environment,\n onRateLimitUpdate: config.onRateLimitUpdate,\n signer: config.signer,\n clob: new ServiceClient({\n headers: config.environment.clob.headers,\n onRateLimitUpdate: config.onRateLimitUpdate,\n root: config.environment.clob.rest,\n resolveHeaders: (request) => this.resolveClobHeaders(request),\n }),\n relayer: new ServiceClient({\n headers: config.environment.relayer.headers,\n root: config.environment.relayer.rest,\n resolveHeaders: (request) => this.resolveRelayerHeaders(request),\n }),\n rpc: new JsonRpcClient({ url: config.environment.rpc }),\n gamma: new ServiceClient({\n headers: config.environment.gamma.headers,\n root: config.environment.gamma.rest,\n }),\n data: new ServiceClient({\n headers: config.environment.data.headers,\n root: config.environment.data.rest,\n }),\n rfq: new ServiceClient({\n headers: config.environment.combos.headers,\n root: config.environment.combos.rest,\n }),\n perps: new ServiceClient({\n headers: config.environment.perps.headers,\n root: config.environment.perps.rest,\n }),\n secureClob: new ServiceClient({\n headers: config.environment.clob.headers,\n onRateLimitUpdate: config.onRateLimitUpdate,\n resolveHeaders: async (request) => ({\n ...(await this.resolveClobHeaders(request)),\n ...(await this.#createL2Headers(request)),\n }),\n root: config.environment.clob.rest,\n }),\n combos: new ServiceClient({\n headers: config.environment.combos.collateralReturn.headers,\n resolveHeaders: (request) => this.resolveRelayerHeaders(request),\n root: config.environment.combos.collateralReturn.rest,\n }),\n builderGateway: new ServiceClient({\n headers: config.environment.combos.builderGateway.headers,\n resolveHeaders: async (request) => ({\n ...(await this.#resolveBuilderGatewayHeaders(request)),\n ...(await this.#createL2Headers(request)),\n }),\n root: config.environment.combos.builderGateway.rest,\n }),\n webSockets: {\n clobMarket: new ClobMarketWebSocketManager({\n headers: config.environment.clob.market.headers,\n url: config.environment.clob.market.ws,\n }),\n clobUser: new ClobUserWebSocketManager({\n credentials: config.credentials,\n headers: config.environment.clob.user.headers,\n url: config.environment.clob.user.ws,\n }),\n rfqQuoter: new RfqQuoterWebSocketManager({\n account: config.account,\n chainId: config.environment.chainId,\n credentials: config.credentials,\n exchange: config.environment.contracts.exchangeV3,\n headers: config.environment.combos.headers,\n signer: config.signer,\n url: config.environment.combos.ws,\n }),\n sports: new SportsWebSocketManager({\n headers: config.environment.sports.headers,\n url: config.environment.sports.ws,\n }),\n rtds: new RtdsWebSocketManager({\n headers: config.environment.rtds.headers,\n url: config.environment.rtds.ws,\n }),\n perpsSubscriptions: new PerpsSubscriptionManager({\n headers: config.environment.perps.headers,\n url: config.environment.perps.ws,\n }),\n perpsSession: new PerpsSessionManager({\n chainId: config.environment.chainId,\n headers: config.environment.perps.headers,\n restUrl: config.environment.perps.rest,\n wsUrl: config.environment.perps.ws,\n }),\n },\n });\n }\n\n /**\n * API credentials for the authenticated session.\n *\n * @remarks\n * These credentials are sensitive. Store them securely if you want to create\n * another secure client later without requiring a new authentication signature\n * while the credentials remain valid.\n */\n get credentials(): ApiKeyCreds {\n return this.context.credentials;\n }\n\n /**\n * The authenticated account identity associated with this client, including the signer and wallet addresses and wallet type.\n */\n get account(): AccountIdentity {\n return this.context.account;\n }\n\n /** @internal */\n get signer(): Signer {\n return this.context.signer;\n }\n\n /** @internal */\n get secureClob(): ServiceClient {\n return this.context.secureClob;\n }\n\n /** @internal */\n get combos(): ServiceClient {\n return this.context.combos;\n }\n\n /** @internal */\n get builderGateway(): ServiceClient {\n return this.context.builderGateway;\n }\n\n /** @internal */\n override get webSockets(): SecureWebSocketManagers {\n return this.context.webSockets;\n }\n\n /**\n * Closes all active realtime subscriptions owned by this client.\n *\n * @remarks\n * Secure clients also close authenticated user-stream subscriptions. This\n * ends active subscription iterators and closes shared websocket connections.\n * It does not affect authentication or other client state.\n *\n * @example\n * ```ts\n * await client.closeSubscriptions();\n * ```\n */\n async closeSubscriptions(): Promise<void> {\n await Promise.allSettled([\n this.webSockets.clobMarket.close(),\n this.webSockets.rtds.close(),\n this.webSockets.sports.close(),\n this.webSockets.perpsSubscriptions.close(),\n this.webSockets.clobUser.close(),\n ]).then(() => undefined);\n }\n\n /**\n * Use this to narrow a {@link Client} union to {@link SecureClient}.\n *\n * @example\n * ```ts\n * if (client.isSecureClient()) {\n * client.credentials; // SecureClient\n * }\n * ```\n */\n isSecureClient(): this is BaseSecureClient<TPublicActions, TSecureActions> {\n return true;\n }\n\n /**\n * Use this to narrow a {@link Client} union to {@link PublicClient}.\n *\n * @example\n * ```ts\n * if (client.isPublicClient()) {\n * client.closeSubscriptions(); // PublicClient\n * }\n * ```\n */\n isPublicClient(): this is BasePublicClient<TPublicActions, TSecureActions> {\n return false;\n }\n\n /**\n * Returns a secure client typed with the methods contributed by the decorator.\n */\n extend<TDecorator extends ClientDecorator>(\n decorator: TDecorator,\n ): SecureClient<\n TPublicActions,\n Prettify<TSecureActions & DecoratorSecureActions<TDecorator>>\n > {\n this.rememberDecorator(decorator);\n Object.assign(this, decorator(this));\n\n return this as unknown as SecureClient<\n TPublicActions,\n Prettify<TSecureActions & DecoratorSecureActions<TDecorator>>\n >;\n }\n\n /**\n * Ends authentication for this client and returns a public client.\n *\n * @remarks\n * This revokes the current authenticated credential and invalidates the\n * current `SecureClient` instance.\n *\n * @example\n * ```ts\n * const publicClient = await secureClient.endAuthentication();\n * ```\n */\n async endAuthentication(): Promise<\n PublicClient<TPublicActions, TSecureActions>\n > {\n // Server-side revocation must not depend on local WebSocket cleanup.\n const closingSubscriptions = this.closeSubscriptions();\n const shuttingDownPerpsSessions = this.webSockets.perpsSession.shutdown();\n const shuttingDownRfqQuoter = this.webSockets.rfqQuoter.shutdown();\n const { apiKey, environment, onRateLimitUpdate } = this.context;\n\n try {\n await deleteApiKey(this);\n } finally {\n this.endAuthenticationLifecycle();\n await Promise.allSettled([\n closingSubscriptions,\n shuttingDownPerpsSessions,\n shuttingDownRfqQuoter,\n ]).then(() => undefined);\n }\n\n const client = new BasePublicClient({\n apiKey,\n environment,\n onRateLimitUpdate,\n });\n\n for (const decorator of this.decorators) {\n client.extend(decorator);\n }\n\n return client as PublicClient<TPublicActions, TSecureActions>;\n }\n\n // Builder gateway status reads authenticate with account headers only;\n // builder headers are required on the mutating requests.\n async #resolveBuilderGatewayHeaders(\n request: ServiceRequest,\n ): Promise<HeadersInit> {\n if (request.method !== 'GET' && this.context.apiKey?.isBuilderKey) {\n return this.context.apiKey.authorize(request);\n }\n return {};\n }\n\n async #createL2Headers(request: ServiceRequest): Promise<HeadersInit> {\n try {\n const timestamp = Math.floor(Date.now() / 1000);\n\n return {\n POLY_ADDRESS: this.account.signer,\n POLY_API_KEY: this.credentials.key,\n POLY_PASSPHRASE: this.credentials.passphrase,\n POLY_SIGNATURE: await buildHmacSignature(\n this.credentials.secret,\n timestamp,\n request.method,\n request.path,\n request.body,\n ),\n POLY_TIMESTAMP: `${timestamp}`,\n };\n } catch (error) {\n throw SigningError.fromError(\n error,\n 'Could not sign the L2-authenticated request',\n );\n }\n }\n}\n\ntype SecureContext = PublicContext & {\n /** @internal */\n account: AccountIdentity;\n /** @internal */\n credentials: ApiKeyCreds;\n /** @internal */\n signer: Signer;\n /** @internal */\n secureClob: ServiceClient;\n /** @internal */\n combos: ServiceClient;\n /** @internal */\n builderGateway: ServiceClient;\n /** @internal */\n webSockets: SecureWebSocketManagers;\n};\n\ntype SecureClientConfig = PublicClientConfig & {\n account: AccountIdentity;\n credentials: ApiKeyCreds;\n signer: Signer;\n};\n\nexport type PublicClient<\n TPublicActions extends ClientActions = PublicActions,\n TSecureActions extends ClientActions = SecureActions,\n> = BasePublicClient<TPublicActions, TSecureActions> & TPublicActions;\n\nexport type SecureClient<\n TPublicActions extends ClientActions = PublicActions,\n TSecureActions extends ClientActions = SecureActions,\n> = BaseSecureClient<TPublicActions, TSecureActions> & TSecureActions;\n\nexport { BasePublicClient, BaseSecureClient };\n\nexport type BaseClient<\n TPublicActions extends ClientActions = ClientActions,\n TSecureActions extends ClientActions = TPublicActions,\n> =\n | BasePublicClient<TPublicActions, TSecureActions>\n | BaseSecureClient<TPublicActions, TSecureActions>;\n\nexport type Client<\n TPublicActions extends ClientActions = ClientActions,\n TSecureActions extends ClientActions = TPublicActions,\n> =\n | PublicClient<TPublicActions, TSecureActions>\n | SecureClient<TPublicActions, TSecureActions>;\n\nexport type PublicClientOptions = {\n /**\n * The environment configuration used by the client.\n *\n * @defaultValue `production`\n */\n environment?: EnvironmentConfig;\n\n /**\n * Optional request authorization applied by the client when needed.\n */\n apiKey?: ApiKeyAuthorization;\n\n /**\n * Listener invoked whenever a response reports per-signer rate-limit state,\n * as order and cancellation responses do.\n *\n * @remarks\n * Use this to monitor remaining rate-limit capacity and warning-mode\n * signals, and adjust request patterns before requests are rejected.\n * Errors thrown by the listener and rejections from promises it returns are\n * ignored.\n */\n onRateLimitUpdate?: RateLimitUpdateListener;\n};\n\nexport type SecureClientOptions = PublicClientOptions & {\n /**\n * Wallet address to use as the account wallet.\n *\n * If omitted, the client uses the signer's deterministic Deposit Wallet as\n * the account wallet. Pass the signer address itself to explicitly trade as\n * an EOA account, or pass a supported Poly Deposit Wallet, Poly Safe, or Poly\n * Proxy wallet address to use that wallet as the account/funder.\n */\n wallet?: string;\n\n /**\n * Wallet-library adapter used to authenticate and complete wallet operations.\n */\n signer: Signer;\n} & (\n | {\n /**\n * Existing API credentials to reuse when they remain valid.\n */\n credentials?: ApiKeyCreds;\n nonce?: never;\n }\n | {\n credentials?: never;\n /**\n * Nonce used when creating or deriving fresh credentials.\n *\n * @defaultValue 0\n */\n nonce?: number;\n }\n );\n\n/**\n * Creates a new `PublicClient` instance.\n *\n * @example\n * ```ts\n * const client = createPublicClient();\n * ```\n */\nexport function createPublicClient(\n options: PublicClientOptions = {},\n): PublicClient<PublicActions, SecureActions> {\n return new BasePublicClient({\n environment: options.environment ?? production,\n apiKey: options.apiKey,\n onRateLimitUpdate: options.onRateLimitUpdate,\n }).extend(allActions);\n}\n\nexport type CreateSecureClientError =\n | CancelledSigningError\n | DeployDepositWalletError\n | IsWalletDeployedError\n | RateLimitError\n | RequestRejectedError\n | SigningError\n | TimeoutError\n | TransactionFailedError\n | TransportError\n | UnexpectedResponseError\n | UserInputError\n | WaitForGaslessTransactionError;\nexport const CreateSecureClientError = makeErrorGuard(\n CancelledSigningError,\n RateLimitError,\n RequestRejectedError,\n SigningError,\n TimeoutError,\n TransactionFailedError,\n TransportError,\n UnexpectedResponseError,\n UserInputError,\n);\n\nexport type SetupGaslessWalletError = UserInputError;\nexport const SetupGaslessWalletError = makeErrorGuard(UserInputError);\n\n/**\n * Creates a new authenticated `SecureClient` instance.\n *\n * @example\n * ```ts\n * const secureClient = await createSecureClient({\n * signer,\n * });\n * ```\n *\n * @throws {@link CreateSecureClientError}\n * Thrown on failure.\n */\nexport async function createSecureClient(\n options: SecureClientOptions,\n): Promise<SecureClient<PublicActions, SecureActions>> {\n const client = createPublicClient({\n environment: options.environment,\n apiKey: options.apiKey,\n onRateLimitUpdate: options.onRateLimitUpdate,\n });\n const wallet = await resolveRequestedWallet(client, options);\n\n const secureClient = await client\n .beginAuthentication(\n {\n wallet,\n credentials: options.credentials,\n nonce: options.nonce,\n },\n options.signer,\n )\n .then(authenticateWith(options.signer));\n\n if (secureClient.account.walletType === WalletType.EOA) {\n return secureClient;\n }\n\n const deployed = await isWalletDeployed(secureClient, {\n wallet: secureClient.account.wallet,\n type: secureClient.account.walletType,\n });\n\n if (deployed) {\n return secureClient;\n }\n\n if (secureClient.account.walletType === WalletType.DEPOSIT_WALLET) {\n await deployDefaultDepositWallet(secureClient);\n return secureClient;\n }\n\n throw new UserInputError(\n `Wallet ${secureClient.account.wallet} does not exist. Provide an existing wallet address, or omit wallet to use the default Deposit Wallet flow.`,\n );\n}\n\n/** Resolves the wallet address to authenticate as. */\nasync function resolveRequestedWallet(\n client: BasePublicClient,\n options: SecureClientOptions,\n): Promise<string> {\n if (options.wallet !== undefined) {\n return options.wallet;\n }\n\n const signerAddress = expectEvmAddress(await options.signer.getAddress());\n const legacyDepositWallet = deriveUupsDepositWalletAddress(\n signerAddress,\n client.environment.walletDerivation,\n );\n\n if (\n await isWalletDeployed(client, {\n wallet: legacyDepositWallet,\n type: WalletType.DEPOSIT_WALLET,\n })\n ) {\n return legacyDepositWallet;\n }\n\n return deriveBeaconDepositWalletAddress(\n signerAddress,\n client.environment.walletDerivation,\n );\n}\n\n/**\n * Deploys the signer's beacon Deposit Wallet for the secure client. The current\n * factory only deploys beacon wallets, so legacy UUPS wallets must already be\n * deployed and cannot be created through this path.\n */\nasync function deployDefaultDepositWallet(\n secureClient: SecureClient<PublicActions, SecureActions>,\n): Promise<void> {\n const currentDepositWallet = deriveBeaconDepositWalletAddress(\n secureClient.account.signer,\n secureClient.environment.walletDerivation,\n );\n\n if (!isSameEvmAddress(secureClient.account.wallet, currentDepositWallet)) {\n throw new UserInputError(\n `Wallet ${secureClient.account.wallet} does not match the expected Deposit Wallet ${currentDepositWallet} for this signer, nor a deployed wallet address.`,\n );\n }\n\n const handle = await deployDepositWallet(secureClient);\n await handle.wait();\n}\n"]}
1
+ {"version":3,"sources":["../src/authorization.ts","../src/authentication.ts","../src/decorators/account.ts","../src/decorators/analytics.ts","../src/decorators/data.ts","../src/decorators/discovery.ts","../src/decorators/perps.ts","../src/decorators/rewards.ts","../src/decorators/rfq.ts","../src/decorators/session-keys.ts","../src/decorators/subscriptions.ts","../src/decorators/trading.ts","../src/decorators/wallet.ts","../src/decorators/index.ts","../src/environments.ts","../src/hmac.ts","../src/websockets/handle.ts","../src/websockets/registry.ts","../src/websockets/clob/protocol.ts","../src/websockets/clob/market.ts","../src/websockets/clob/user.ts","../src/websockets/perps/manager.ts","../src/websockets/perps/subscription.ts","../src/websockets/rfq/events.ts","../src/websockets/rfq/messages.ts","../src/websockets/rfq/pending.ts","../src/websockets/rfq/signing.ts","../src/websockets/rfq/quote.ts","../src/websockets/rfq/quoter.ts","../src/websockets/rtds.ts","../src/websockets/sports.ts","../src/clients.ts"],"names":["RemoteBuilderSigningResponseSchema","z","remoteBuilderSigning","config","RemoteBuilderAuthorization","relayerApiKey","RelayerApiKeyAuthorization","#config","request","#fetchBuilderKeyHeaders","error","SigningError","#resolveHeaders","headers","resolvedHeaders","requestHeaders","response","createApiKeyAuthTypedDataPayload","publicAccountActions","client","listPositions","listComboPositions","fetchPortfolioValue","fetchTraderLeaderboardStanding","fetchUserStats","fetchUserPnl","fetchUserVolume","downloadAccountingSnapshot","listActivity","listComboActivity","withAccountWallet","accountActions","actions","listAccountTrades","fetchNotifications","dropNotifications","fetchClosedOnlyMode","analyticsActions","listBuilderTrades","listBuilderLeaderboard","fetchBuilderVolume","listTraderLeaderboard","listBiggestWinners","dataActions","fetchEventLiveVolume","fetchResolutions","fetchMidpoint","fetchMidpoints","fetchPrice","fetchPrices","fetchOrderBook","fetchOrderBooks","fetchSpread","fetchSpreads","fetchLastTradePrice","fetchLastTradePrices","listPriceHistory","estimateMarketPrice","fetchOpenInterest","listMarketHolders","listTrades","discoveryActions","listEvents","fetchEvent","fetchEventTags","listMarkets","listComboMarkets","fetchMarket","fetchMarketTags","listSeries","fetchSeries","listMarketClarifications","listTags","fetchTag","fetchRelatedTags","fetchRelatedTagResources","search","listSports","fetchSportsMarketTypes","listTeams","fetchPublicProfile","listComments","fetchCommentsById","listCommentsByUserAddress","perpsActions","fetchPerpsBook","fetchPerpsFees","fetchPerpsInstruments","fetchPerpsTicker","fetchPerpsTickers","listPerpsCandles","listPerpsFundingHistory","listPerpsTrades","depositToPerps","openPerpsSession","revokePerpsCredentials","withdrawFromPerps","publicRewardsActions","listCurrentRewards","listMarketRewards","rewardsActions","fetchOrderScoring","fetchOrdersScoring","listUserEarningsForDay","fetchTotalEarningsForUserForDay","listUserEarningsAndMarketsConfig","fetchRewardPercentages","rfqActions","openRfqSession","params","requestComboQuote","acceptComboQuote","waitForComboFill","sessionKeyActions","authorizeSessionKey","fetchSessionKeys","revokeSessionKey","subscriptionsActions","subscriptions","subscribe","tradingActions","createMarketOrder","placeMarketOrder","createLimitOrder","placeLimitOrder","postOrder","postOrders","waitForOrderFillSettlement","cancelOrder","cancelOrders","cancelAll","cancelMarketOrders","listOpenOrders","fetchOrder","publicWalletActions","fetchTradingApprovalsState","walletActions","setupTradingApprovals","approveErc20","approveErc1155ForAll","transferErc20","splitPosition","mergePositions","redeemPositions","planCollateralReturn","executeCollateralReturnPlan","allActions","production","expectEvmAddress","forkEnvironmentConfig","fork","base","forkRestEndpoint","forkWebSocketEndpoint","forkRestWebSocketEndpoint","forkHeaders","preproduction","buildHmacSignature","secret","timestamp","method","requestPath","body","message","cryptoKey","base64ToArrayBuffer","signature","toUrlSafeBase64","arrayBufferToBase64","base64","sanitizedBase64","binaryString","bytes","index","buffer","binary","byte","value","createSubscriptionHandle","queue","closeSubscription","closing","SubscriptionRegistry","#entries","#deriveServerState","options","subscription","subscriber","pushable","entry","#addEntry","before","event","syncMarketSubscription","send","after","addedAssets","difference","removedAssets","buildMarketSubscribeUpdate","firstActiveAsset","buildMarketUnsubscribeUpdate","syncUserSubscription","buildUserUnsubscribeUpdate","buildUserSubscribeUpdate","addedMarkets","removedMarkets","deriveMarketServerSubscription","entries","assets","customFeatureEnabled","assetId","deriveUserServerSubscription","includeAllMarkets","markets","isAllMarketsUserSubscription","market","buildMarketSubscribeMessage","assetsIds","buildUserSubscribeMessage","credentials","marketMatcherFor","assetIds","change","userMatcherFor","left","right","rightSet","ClobMarketWebSocketManager","#headers","#url","#closing","#connection","WebSocketConnection","ClobWebSocketHeartbeat","#reconnectScheduler","ReconnectScheduler","#subscriptions","#registerSubscriber","#closeSubscriber","#connect","#shutdown","#onConnectionLost","#onConnectionError","#onConnectionMessage","#onConnectionOpen","#sendInitialSubscription","events","eventData","parsed","MarketEventSchema","#scheduleReconnect","ClobUserWebSocketManager","#credentials","UserEventSchema","PerpsSessionManager","#chainId","#restUrl","#wsUrl","#sessions","#connectingSessions","#connecting","#hasShutdown","TransportError","session","PerpsSession","closedSession","#clearSession","connecting","sessions","connectingSessions","promise","PerpsSubscriptionManager","#nextRequestId","PerpsWebSocketHeartbeat","derivePerpsSubscriptionServerState","matcherFor","#sendSubscribeFrame","channelsAdded","#sendUnsubscribeFrame","channelsRemoved","PerpsMarketDataEventSchema","channels","#buildChannelFrame","req","tickerInstrumentIds","statisticInstrumentIds","subscribeAllTickers","subscribeAllStatistics","channelFor","instrumentId","channel","invariant","toQuoteRequestEvent","controller","toConfirmationRequestEvent","rfqId","quoteId","RfqConfirmationDecision","toQuoteAck","toQuoteCancelAck","toConfirmationAck","createAuthMessage","account","identity","resolveOrderIdentity","createQuoteMessage","quote","createQuoteCancelMessage","createConfirmationResponseMessage","decision","PendingResponses","#pending","#timeoutMs","timeoutMs","key","timeoutMessage","pending","createPending","timeout","setNonBlockingTimeout","TimeoutError","remaining","resolve","reject","resolvePromise","rejectPromise","BYTES32_ZERO","signRfqQuoteOrder","domain","createExchangeV3OrderDomain","order","toBaseUnits","calculateExchangeOrderMakerAmount","generateRfqOrderSalt","encodeExchangeOrderSide","calculateExchangeOrderTakerAmount","createExchangeOrderTypedDataPayload","createExchangeOrderSignature","DecimalishToBigIntSchema","DecimalishSchema","decimalToScaledInteger","RfqQuoteResponseSchema","price","parseRfqQuoteResponse","parseUserInput","createRfqQuote","size","defaultQuoteSize","signedOrder","quoteOrderPrice","quoteOrderSide","quoteOrderTokenId","source","RfqDirection","OrderSide","requestedSize","RfqRequestedSizeUnit","match","UserInputError","whole","fraction","scaledValue","AUTH_TIMEOUT_MS","ACK_TIMEOUT_MS","RfqQuoterWebSocketManager","#account","#exchange","#signer","#session","#connectingSession","RfqWebSocketSession","connectingSession","#onClose","#queue","#auth","auth","authTimeout","info","#handleConnectionLost","#handleMessage","#sendAuthMessage","#send","#failPending","#fail","#shutdownWithError","rawMessage","RfqQuoterInboundMessageSchema","#handleAuthMessage","quoteAckKey","quoteCancelAckKey","confirmationAckKey","#handleRfqError","ConnectionLostError","RfqQuoteRejectedError","RfqCancelQuoteRejectedError","RfqConfirmationRejectedError","parsedResponse","reference","RtdsWebSocketManager","RtdsWebSocketHeartbeat","deriveRtdsServerState","subscriptionsToOpen","serverSubscriptionsAdded","subscriptionsToClose","serverSubscriptionsRemoved","#resubscribeActiveServerEntries","RealtimeEventSchema","buildSubscribeMessage","buildUnsubscribeMessage","activeByKey","serverSubscription","serverSubscriptionsFor","topic","type","twapServerTopic","windowSeconds","SportsWebSocketManager","SportsWebSocketHeartbeat","SportsResultEventSchema","AbstractClient","#context","#decorators","context","decorator","BeginAuthenticationCredentialsSchema","ApiKeySchema","BeginAuthenticationRequestSchema","EvmAddressSchema","BasePublicClient","ServiceClient","JsonRpcClient","signer","nonce","signerAddress","requestAddress","wallet","resolveAccountIdentity","#createSecureClient","fetchApiKeys","RequestRejectedError","createOrDeriveApiKey","expectEvmSignature","BaseSecureClient","#hasEndedAuthentication","#createL2Headers","#resolveBuilderGatewayHeaders","closingSubscriptions","shuttingDownPerpsSessions","shuttingDownRfqQuoter","apiKey","environment","onRateLimitUpdate","deleteApiKey","createPublicClient","CreateSecureClientError","makeErrorGuard","CancelledSigningError","RateLimitError","TransactionFailedError","UnexpectedResponseError","SetupGaslessWalletError","createSecureClient","resolveRequestedWallet","secureClient","authenticateWith","WalletType","isWalletDeployed","deployDefaultDepositWallet","legacyDepositWallet","deriveUupsDepositWalletAddress","deriveBeaconDepositWalletAddress","currentDepositWallet","isSameEvmAddress","deployDepositWallet"],"mappings":"o0OAiCA,IAAMA,EAAAA,CAAqCC,CAAAA,CAAE,MAAA,CAAO,CAClD,qBAAsBA,CAAAA,CAAE,MAAA,EAAO,CAAE,GAAA,CAAI,CAAC,CAAA,CACtC,sBAAA,CAAwBA,CAAAA,CAAE,MAAA,EAAO,CAAE,GAAA,CAAI,CAAC,CAAA,CACxC,uBAAA,CAAyBA,CAAAA,CAAE,MAAA,GAAS,GAAA,CAAI,CAAC,CAAA,CACzC,sBAAA,CAAwBA,CAAAA,CAAE,MAAA,EAAO,CAAE,GAAA,CAAI,CAAC,CAC1C,CAAC,CAAA,CAEM,SAASC,EAAAA,CACdC,CAAAA,CACqB,CACrB,OAAO,IAAIC,EAAAA,CAA2BD,CAAM,CAC9C,CAEO,SAASE,EAAAA,CACdF,CAAAA,CACqB,CACrB,OAAO,IAAIG,EAAAA,CAA2BH,CAAM,CAC9C,CAEA,IAAMC,EAAAA,CAAN,KAAgE,CACrDG,EAAAA,CAET,WAAA,CAAYJ,CAAAA,CAAoC,CAC9C,IAAA,CAAKI,EAAAA,CAAUJ,EACjB,CAEA,IAAI,YAAA,EAAwB,CAC1B,OAAO,KACT,CAEA,IAAI,cAAA,EAA0B,CAC5B,OAAO,KACT,CAEA,MAAM,SAAA,CAAUK,CAAAA,CAA2D,CACzE,GAAI,CACF,OAAO,MAAM,IAAA,CAAKC,EAAAA,CAAwBD,CAAO,CACnD,CAAA,MAASE,EAAO,CACd,MAAMC,CAAAA,CAAa,SAAA,CACjBD,CAAAA,CACA,uDACF,CACF,CACF,CAEA,KAAME,EAAAA,EAAoC,CACxC,IAAMC,CAAAA,CAAU,IAAA,CAAKN,EAAAA,CAAQ,QACvBO,CAAAA,CACJ,OAAOD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A,CAAAA,CAAa,WAAA,CAAY,gBAC3B,CAAA,CAEA,GAAI,CAACS,gBAAAA,CAAiBT,CAAAA,CAAa,OAAA,CAAQ,MAAA,CAAQQ,CAAoB,CAAA,CACrE,MAAM,IAAIjH,CAAAA,CACR,CAAA,OAAA,EAAUyG,CAAAA,CAAa,OAAA,CAAQ,MAAM,+CAA+CQ,CAAoB,CAAA,gDAAA,CAC1G,CAAA,CAIF,KAAA,CADe,MAAME,EAAAA,CAAoBV,CAAY,CAAA,EACxC,OACf","file":"index.js","sourcesContent":["import { z } from 'zod';\nimport { SigningError } from './errors';\nimport type { ApiKeyAuthorization, ApiKeyAuthorizationRequest } from './types';\n\nexport type RelayerApiKeyConfig = {\n key: string;\n address: string;\n};\n\nexport type RemoteBuilderSigningConfig = {\n /**\n * URL for the application's remote builder-signing endpoint.\n *\n * This may be an absolute `http` or `https` URL, or a root-relative path\n * such as `/api/builder/sign` in browser environments.\n */\n url: string;\n /**\n * Fetch credential mode for requests to the remote signer.\n *\n * Set this when the signer relies on cookie-backed authentication, especially\n * for cross-origin requests that require `include`.\n */\n credentials?: RequestCredentials;\n /**\n * Additional headers to send to the remote signer.\n *\n * Use this for application-specific authorization such as bearer tokens,\n * tenant headers, or CSRF headers. The SDK always sends JSON.\n */\n headers?: HeadersInit | (() => HeadersInit | Promise<HeadersInit>);\n};\n\nconst RemoteBuilderSigningResponseSchema = z.object({\n POLY_BUILDER_API_KEY: z.string().min(1),\n POLY_BUILDER_TIMESTAMP: z.string().min(1),\n POLY_BUILDER_PASSPHRASE: z.string().min(1),\n POLY_BUILDER_SIGNATURE: z.string().min(1),\n});\n\nexport function remoteBuilderSigning(\n config: RemoteBuilderSigningConfig,\n): ApiKeyAuthorization {\n return new RemoteBuilderAuthorization(config);\n}\n\nexport function relayerApiKey(\n config: RelayerApiKeyConfig,\n): ApiKeyAuthorization {\n return new RelayerApiKeyAuthorization(config);\n}\n\nclass RemoteBuilderAuthorization implements ApiKeyAuthorization {\n readonly #config: RemoteBuilderSigningConfig;\n\n constructor(config: RemoteBuilderSigningConfig) {\n this.#config = config;\n }\n\n get isBuilderKey(): boolean {\n return true;\n }\n\n get supportGasless(): boolean {\n return true;\n }\n\n async authorize(request: ApiKeyAuthorizationRequest): Promise<HeadersInit> {\n try {\n return await this.#fetchBuilderKeyHeaders(request);\n } catch (error) {\n throw SigningError.fromError(\n error,\n 'Could not authorize the builder-authenticated request',\n );\n }\n }\n\n async #resolveHeaders(): Promise<Headers> {\n const headers = this.#config.headers;\n const resolvedHeaders =\n typeof headers === 'function' ? await headers() : headers;\n const requestHeaders = new Headers(resolvedHeaders);\n\n requestHeaders.set('content-type', 'application/json');\n\n return requestHeaders;\n }\n\n async #fetchBuilderKeyHeaders(\n request: ApiKeyAuthorizationRequest,\n ): Promise<HeadersInit> {\n const response = await fetch(this.#config.url, {\n body: JSON.stringify({\n body: request.body,\n method: request.method,\n path: request.path,\n }),\n credentials: this.#config.credentials,\n headers: await this.#resolveHeaders(),\n method: 'POST',\n mode: 'cors',\n });\n\n if (!response.ok) {\n throw new Error(\n `Remote signer rejected request with status ${response.status}`,\n );\n }\n\n return RemoteBuilderSigningResponseSchema.parse(await response.json());\n }\n}\n\nclass RelayerApiKeyAuthorization implements ApiKeyAuthorization {\n readonly #config: RelayerApiKeyConfig;\n\n constructor(config: RelayerApiKeyConfig) {\n this.#config = config;\n }\n\n get isBuilderKey(): boolean {\n return false;\n }\n\n get supportGasless(): boolean {\n return true;\n }\n\n authorize(): Promise<HeadersInit> {\n return Promise.resolve({\n RELAYER_API_KEY: this.#config.key,\n RELAYER_API_KEY_ADDRESS: this.#config.address,\n });\n }\n}\n","import type { EvmAddress } from '@polymarket/types';\nimport type { TypedDataPayload } from './types';\n\n/** @internal */\nexport type CreateApiKeyAuthTypedDataPayloadRequest = {\n address: EvmAddress;\n chainId: number;\n nonce?: number;\n timestamp: number;\n};\n\n/** @internal */\nexport function createApiKeyAuthTypedDataPayload(\n request: CreateApiKeyAuthTypedDataPayloadRequest,\n): TypedDataPayload {\n return {\n domain: {\n chainId: request.chainId,\n name: 'ClobAuthDomain',\n version: '1',\n },\n message: {\n address: request.address,\n message: 'This message attests that I control the given wallet',\n nonce: request.nonce ?? 0,\n timestamp: `${request.timestamp}`,\n },\n primaryType: 'ClobAuth',\n types: {\n ClobAuth: [\n { name: 'address', type: 'address' },\n { name: 'timestamp', type: 'string' },\n { name: 'nonce', type: 'uint256' },\n { name: 'message', type: 'string' },\n ],\n },\n };\n}\n","import type {\n ClobTrade,\n NotificationsResponse,\n} from '@polymarket/bindings/clob';\nimport type {\n Activity,\n ComboActivity,\n ComboPosition,\n PortfolioValue,\n Position,\n TraderLeaderboardStanding,\n UserPnlSeries,\n UserStats,\n UserVolume,\n} from '@polymarket/bindings/data';\nimport type { Prettify } from '@polymarket/types';\nimport {\n type DownloadAccountingSnapshotRequest,\n type DropNotificationsRequest,\n downloadAccountingSnapshot,\n dropNotifications,\n type FetchPortfolioValueRequest,\n type FetchTraderLeaderboardStandingRequest,\n type FetchUserPnlRequest,\n type FetchUserStatsRequest,\n type FetchUserVolumeRequest,\n fetchClosedOnlyMode,\n fetchNotifications,\n fetchPortfolioValue,\n fetchTraderLeaderboardStanding,\n fetchUserPnl,\n fetchUserStats,\n fetchUserVolume,\n type ListAccountTradesRequest,\n type ListActivityRequest,\n type ListComboActivityRequest,\n type ListComboPositionsRequest,\n type ListPositionsRequest,\n listAccountTrades,\n listActivity,\n listComboActivity,\n listComboPositions,\n listPositions,\n} from '../actions';\nimport type {\n BaseClient,\n BasePublicClient,\n BaseSecureClient,\n} from '../clients';\nimport type { Paginated } from '../pagination';\n\ntype DefaultAccountWallet<TRequest extends { user?: string }> = Prettify<\n Omit<TRequest, 'user'> & {\n /**\n * Wallet address to use.\n *\n * @defaultValue `client.account.wallet`\n */\n user?: string;\n }\n>;\n\nexport type SecureListPositionsRequest =\n DefaultAccountWallet<ListPositionsRequest>;\nexport type SecureListComboPositionsRequest =\n DefaultAccountWallet<ListComboPositionsRequest>;\nexport type SecureFetchPortfolioValueRequest =\n DefaultAccountWallet<FetchPortfolioValueRequest>;\nexport type SecureFetchTraderLeaderboardStandingRequest =\n DefaultAccountWallet<FetchTraderLeaderboardStandingRequest>;\nexport type SecureFetchUserPnlRequest =\n DefaultAccountWallet<FetchUserPnlRequest>;\nexport type SecureFetchUserStatsRequest =\n DefaultAccountWallet<FetchUserStatsRequest>;\nexport type SecureFetchUserVolumeRequest =\n DefaultAccountWallet<FetchUserVolumeRequest>;\nexport type SecureDownloadAccountingSnapshotRequest =\n DefaultAccountWallet<DownloadAccountingSnapshotRequest>;\nexport type SecureListActivityRequest =\n DefaultAccountWallet<ListActivityRequest>;\nexport type SecureListComboActivityRequest =\n DefaultAccountWallet<ListComboActivityRequest>;\n\nexport type PublicAccountActions = Prettify<{\n /**\n * Lists current positions for a wallet.\n *\n * @throws {@link ListPositionsError}\n * Thrown on failure.\n *\n * @example\n * Fetch the first page of results:\n * ```ts\n * const paginator = client.listPositions({\n * user: '0x7c3db723f1d4d8cb9c550095203b686cb11e5c6b',\n * pageSize: 10,\n * });\n *\n * const firstPage = await paginator.firstPage();\n *\n * // Optionally, fetch additional pages:\n * for await (const page of paginator.from(firstPage.nextCursor)) {\n * // page.items: Position[]\n * }\n * ```\n *\n * @example\n * Loop through all pages with `for await`:\n * ```ts\n * const paginator = client.listPositions({\n * user: '0x7c3db723f1d4d8cb9c550095203b686cb11e5c6b',\n * pageSize: 10,\n * });\n *\n * for await (const page of paginator) {\n * // page.items: Position[]\n * }\n * ```\n */\n listPositions(request: ListPositionsRequest): Paginated<Position[]>;\n /**\n * Lists combo positions for a wallet.\n *\n * @throws {@link ListComboPositionsError}\n * Thrown on failure.\n *\n * @example\n * Fetch the first page of results:\n * ```ts\n * const paginator = client.listComboPositions({\n * user: '0x7c3db723f1d4d8cb9c550095203b686cb11e5c6b',\n * pageSize: 10,\n * });\n *\n * const firstPage = await paginator.firstPage();\n * ```\n *\n * @example\n * Filter to any of several resolved statuses:\n * ```ts\n * const paginator = client.listComboPositions({\n * user: '0x7c3db723f1d4d8cb9c550095203b686cb11e5c6b',\n * status: [\n * ComboPositionStatus.ResolvedWin,\n * ComboPositionStatus.ResolvedPartial,\n * ComboPositionStatus.ResolvedLoss,\n * ],\n * });\n * ```\n */\n listComboPositions(\n request: ListComboPositionsRequest,\n ): Paginated<ComboPosition[]>;\n /**\n * Fetches the total value for a wallet's positions.\n *\n * When `conditionIds` is present, only those single-market positions are\n * included; portfolio-level combo positions are excluded. Accepts at most\n * 20 distinct condition IDs.\n *\n * @throws {@link FetchPortfolioValueError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const value = await client.fetchPortfolioValue({\n * user: '0x7c3db723f1d4d8cb9c550095203b686cb11e5c6b',\n * conditionIds: ['0xe546672750517f62c45a5a00067481981e62b9c20fa8220203232c9dc8fd2093'],\n * });\n * ```\n */\n fetchPortfolioValue(\n request: FetchPortfolioValueRequest,\n ): Promise<PortfolioValue>;\n /**\n * Fetches one trader's standing on both the PnL and volume boards.\n *\n * `window` defaults to one day and `category` to overall. A `null` rank means\n * the trader is unranked on that board. Returns `null` for an unknown wallet.\n *\n * @throws {@link FetchTraderLeaderboardStandingError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const standing = await client.fetchTraderLeaderboardStanding({\n * user: '0xa71093cafc0c099b4ccab24c3cb8018d817923c4',\n * window: LeaderboardWindow.All,\n * });\n * ```\n */\n fetchTraderLeaderboardStanding(\n request: FetchTraderLeaderboardStandingRequest,\n ): Promise<TraderLeaderboardStanding | null>;\n /**\n * Fetches profile and lifetime trading statistics for a wallet.\n *\n * `tradedMarketCount` is the exact number of distinct markets traded.\n *\n * Returns `null` when the wallet is not a known user.\n *\n * @throws {@link FetchUserStatsError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const stats = await client.fetchUserStats({\n * user: '0x7c3db723f1d4d8cb9c550095203b686cb11e5c6b',\n * });\n * ```\n */\n fetchUserStats(request: FetchUserStatsRequest): Promise<UserStats | null>;\n /**\n * Fetches a wallet's cumulative PnL series.\n *\n * `interval` defaults to one day and `fidelity` defaults to one hour. Each\n * point is cumulative through its timestamp; nullable amounts mean the\n * source was unavailable and are never coerced to zero.\n *\n * @throws {@link FetchUserPnlError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const pnl = await client.fetchUserPnl({\n * user: '0x7c3db723f1d4d8cb9c550095203b686cb11e5c6b',\n * interval: UserPnlInterval.OneWeek,\n * fidelity: UserPnlFidelity.ThreeHours,\n * });\n * ```\n */\n fetchUserPnl(request: FetchUserPnlRequest): Promise<UserPnlSeries>;\n /**\n * Fetches a wallet's trading volume for a time window.\n *\n * Volume is returned in shares and USD. Window bounds accept epoch seconds\n * or `Date` values and are widened to whole UTC days.\n *\n * @throws {@link FetchUserVolumeError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const volume = await client.fetchUserVolume({\n * user: '0x7c3db723f1d4d8cb9c550095203b686cb11e5c6b',\n * window: { start: new Date('2026-08-01T00:00:00Z') },\n * });\n * ```\n */\n fetchUserVolume(request: FetchUserVolumeRequest): Promise<UserVolume>;\n /**\n * Downloads an accounting snapshot archive for a wallet.\n *\n * @throws {@link DownloadAccountingSnapshotError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const snapshot = await client.downloadAccountingSnapshot({\n * user: '0x7c3db723f1d4d8cb9c550095203b686cb11e5c6b',\n * });\n * ```\n */\n downloadAccountingSnapshot(\n request: DownloadAccountingSnapshotRequest,\n ): Promise<Blob>;\n /**\n * Lists wallet activity.\n *\n * Every activity type is included by default, including deposits and\n * withdrawals; use the `type` filter to narrow results. An omitted `window`\n * serves the most recent three years; `window: 'full'` requests the complete\n * history. Window bounds accept Unix epoch seconds or `Date` values. Results\n * are newest-first by default. `pageSize` defaults to 100 (max 1000), and\n * transient rate limits are retried automatically.\n *\n * @throws {@link ListActivityError}\n * Thrown on failure.\n *\n * @example\n * Fetch the first page of results:\n * ```ts\n * const paginator = client.listActivity({\n * user: '0x7c3db723f1d4d8cb9c550095203b686cb11e5c6b',\n * pageSize: 10,\n * });\n *\n * const firstPage = await paginator.firstPage();\n *\n * // Optionally, fetch additional pages:\n * for await (const page of paginator.from(firstPage.nextCursor)) {\n * // page.items: Activity[]\n * }\n * ```\n *\n * @example\n * Loop through all pages with `for await`:\n * ```ts\n * const paginator = client.listActivity({\n * user: '0x7c3db723f1d4d8cb9c550095203b686cb11e5c6b',\n * pageSize: 10,\n * });\n *\n * for await (const page of paginator) {\n * // page.items: Activity[]\n * }\n * ```\n */\n listActivity(request: ListActivityRequest): Paginated<Activity[]>;\n /**\n * Lists combo lifecycle activity for a wallet.\n *\n * @throws {@link ListComboActivityError}\n * Thrown on failure.\n *\n * @example\n * Fetch the first page of results:\n * ```ts\n * const paginator = client.listComboActivity({\n * user: '0x7c3db723f1d4d8cb9c550095203b686cb11e5c6b',\n * pageSize: 10,\n * });\n *\n * const firstPage = await paginator.firstPage();\n * ```\n */\n listComboActivity(\n request: ListComboActivityRequest,\n ): Paginated<ComboActivity[]>;\n}>;\n\nexport type SecureAccountActions = Prettify<{\n /**\n * Lists current positions for a wallet.\n *\n * Defaults to the authenticated account's wallet when `user` is omitted.\n * To list a market's holders (a `conditionId` anchor with no wallet), use\n * a public client's `listPositions` instead.\n *\n * @throws {@link ListPositionsError}\n * Thrown on failure.\n *\n * @example\n * Fetch the first page of results for the authenticated account:\n * ```ts\n * const paginator = client.listPositions({\n * pageSize: 10,\n * });\n *\n * const firstPage = await paginator.firstPage();\n * ```\n */\n listPositions(request?: SecureListPositionsRequest): Paginated<Position[]>;\n /**\n * Lists combo positions for a wallet.\n *\n * Defaults to the authenticated account's wallet when `user` is omitted.\n *\n * @throws {@link ListComboPositionsError}\n * Thrown on failure.\n *\n * @example\n * Filter the authenticated account's positions to multiple statuses:\n * ```ts\n * const paginator = client.listComboPositions({\n * status: [\n * ComboPositionStatus.ResolvedWin,\n * ComboPositionStatus.ResolvedPartial,\n * ],\n * });\n * ```\n */\n listComboPositions(\n request?: SecureListComboPositionsRequest,\n ): Paginated<ComboPosition[]>;\n /**\n * Fetches the total value for a wallet's positions.\n *\n * When `conditionIds` is present, only those single-market positions are\n * included; portfolio-level combo positions are excluded. Accepts at most\n * 20 distinct condition IDs.\n *\n * Defaults to the authenticated account's wallet when `user` is omitted.\n *\n * @throws {@link FetchPortfolioValueError}\n * Thrown on failure.\n */\n fetchPortfolioValue(\n request?: SecureFetchPortfolioValueRequest,\n ): Promise<PortfolioValue>;\n /**\n * Fetches one trader's standing on both the PnL and volume boards.\n *\n * Defaults to the authenticated account's wallet when `user` is omitted.\n * `window` defaults to one day and `category` to overall. A `null` rank means\n * the trader is unranked on that board. Returns `null` for an unknown wallet.\n *\n * @throws {@link FetchTraderLeaderboardStandingError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const standing = await client.fetchTraderLeaderboardStanding({\n * window: LeaderboardWindow.All,\n * });\n * ```\n */\n fetchTraderLeaderboardStanding(\n request?: SecureFetchTraderLeaderboardStandingRequest,\n ): Promise<TraderLeaderboardStanding | null>;\n /**\n * Fetches profile and lifetime trading statistics for a wallet.\n *\n * `tradedMarketCount` is the exact number of distinct markets traded.\n *\n * Defaults to the authenticated account's wallet when `user` is omitted.\n * Returns `null` when the wallet is not a known user.\n *\n * @throws {@link FetchUserStatsError}\n * Thrown on failure.\n */\n fetchUserStats(\n request?: SecureFetchUserStatsRequest,\n ): Promise<UserStats | null>;\n /**\n * Fetches the cumulative PnL series for a wallet.\n *\n * Defaults to the authenticated account's wallet when `user` is omitted.\n * `interval` defaults to one day and `fidelity` defaults to one hour.\n *\n * @throws {@link FetchUserPnlError}\n * Thrown on failure.\n */\n fetchUserPnl(request?: SecureFetchUserPnlRequest): Promise<UserPnlSeries>;\n /**\n * Fetches trading volume for a wallet over a time window.\n *\n * Defaults to the authenticated account's wallet when `user` is omitted.\n * Window bounds accept epoch seconds or `Date` values and are widened to\n * whole UTC days.\n *\n * @throws {@link FetchUserVolumeError}\n * Thrown on failure.\n */\n fetchUserVolume(request?: SecureFetchUserVolumeRequest): Promise<UserVolume>;\n /**\n * Downloads an accounting snapshot archive for a wallet.\n *\n * Defaults to the authenticated account's wallet when `user` is omitted.\n *\n * @throws {@link DownloadAccountingSnapshotError}\n * Thrown on failure.\n */\n downloadAccountingSnapshot(\n request?: SecureDownloadAccountingSnapshotRequest,\n ): Promise<Blob>;\n /**\n * Lists wallet activity.\n *\n * Defaults to the authenticated account's wallet when `user` is omitted.\n *\n * Every activity type is included by default, including deposits and\n * withdrawals; use the `type` filter to narrow results. An omitted `window`\n * serves the most recent three years; `window: 'full'` requests the complete\n * history. Window bounds accept Unix epoch seconds or `Date` values. Results\n * are newest-first by default. `pageSize` defaults to 100 (max 1000), and\n * transient rate limits are retried automatically.\n *\n * @throws {@link ListActivityError}\n * Thrown on failure.\n */\n listActivity(request?: SecureListActivityRequest): Paginated<Activity[]>;\n /**\n * Lists combo lifecycle activity for a wallet.\n *\n * Defaults to the authenticated account's wallet when `user` is omitted.\n *\n * @throws {@link ListComboActivityError}\n * Thrown on failure.\n */\n listComboActivity(\n request?: SecureListComboActivityRequest,\n ): Paginated<ComboActivity[]>;\n /**\n * Lists trades for the authenticated account across all pages.\n *\n * @throws {@link ListAccountTradesError}\n * Thrown on failure.\n *\n * @example\n * Fetch the first page of results:\n * ```ts\n * const paginator = client.listAccountTrades({\n * market: '0x0000000000000000000000000000000000000000000000000000000000000001',\n * });\n *\n * const firstPage = await paginator.firstPage();\n *\n * // Optionally, fetch additional pages:\n * for await (const page of paginator.from(firstPage.nextCursor)) {\n * // page.items: ClobTrade[]\n * }\n * ```\n *\n * @example\n * Loop through all pages with `for await`:\n * ```ts\n * const paginator = client.listAccountTrades({\n * market: '0x0000000000000000000000000000000000000000000000000000000000000001',\n * });\n *\n * for await (const page of paginator) {\n * // page.items: ClobTrade[]\n * }\n * ```\n */\n listAccountTrades(request?: ListAccountTradesRequest): Paginated<ClobTrade[]>;\n /**\n * Fetches notifications for the authenticated account.\n * Notifications of a kind this SDK version does not recognize are omitted.\n *\n * @throws {@link FetchNotificationsError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const notifications = await client.fetchNotifications();\n * ```\n */\n fetchNotifications(): Promise<NotificationsResponse>;\n /**\n * Drops notifications for the authenticated account.\n *\n * @throws {@link DropNotificationsError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * await client.dropNotifications({\n * ids: ['1', '2'],\n * });\n * ```\n */\n dropNotifications(request: DropNotificationsRequest): Promise<void>;\n /**\n * Fetches whether the account is restricted to closed-only trading.\n *\n * @throws {@link FetchClosedOnlyModeError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const closedOnly = await client.fetchClosedOnlyMode();\n * ```\n */\n fetchClosedOnlyMode(): Promise<boolean>;\n}>;\n\nfunction publicAccountActions(client: BaseClient): PublicAccountActions {\n return {\n listPositions: listPositions.bind(null, client),\n listComboPositions: listComboPositions.bind(null, client),\n fetchPortfolioValue: fetchPortfolioValue.bind(null, client),\n fetchTraderLeaderboardStanding: fetchTraderLeaderboardStanding.bind(\n null,\n client,\n ),\n fetchUserStats: fetchUserStats.bind(null, client),\n fetchUserPnl: fetchUserPnl.bind(null, client),\n fetchUserVolume: fetchUserVolume.bind(null, client),\n downloadAccountingSnapshot: downloadAccountingSnapshot.bind(null, client),\n listActivity: listActivity.bind(null, client),\n listComboActivity: listComboActivity.bind(null, client),\n };\n}\n\ntype WithAccountWallet<TRequest> = Omit<TRequest, 'user'> & { user: string };\n\nfunction withAccountWallet<TRequest extends { user?: string }>(\n client: BaseSecureClient,\n request: TRequest = {} as TRequest,\n): WithAccountWallet<TRequest> {\n if (\n request === null ||\n typeof request !== 'object' ||\n Array.isArray(request)\n ) {\n return request as WithAccountWallet<TRequest>;\n }\n\n return {\n ...request,\n user: request.user === undefined ? client.account.wallet : request.user,\n };\n}\n\nexport function accountActions(client: BasePublicClient): PublicAccountActions;\nexport function accountActions(client: BaseSecureClient): SecureAccountActions;\nexport function accountActions(\n client: BaseClient,\n): PublicAccountActions | SecureAccountActions {\n const actions = publicAccountActions(client);\n\n if (client.isPublicClient()) {\n return actions;\n }\n\n return {\n ...actions,\n listPositions: (request?: SecureListPositionsRequest) =>\n listPositions(client, withAccountWallet(client, request)),\n listComboPositions: (request?: SecureListComboPositionsRequest) =>\n listComboPositions(client, withAccountWallet(client, request)),\n fetchPortfolioValue: (request?: SecureFetchPortfolioValueRequest) =>\n fetchPortfolioValue(client, withAccountWallet(client, request)),\n fetchTraderLeaderboardStanding: (\n request?: SecureFetchTraderLeaderboardStandingRequest,\n ) =>\n fetchTraderLeaderboardStanding(\n client,\n withAccountWallet(client, request),\n ),\n fetchUserStats: (request?: SecureFetchUserStatsRequest) =>\n fetchUserStats(client, withAccountWallet(client, request)),\n fetchUserPnl: (request?: SecureFetchUserPnlRequest) =>\n fetchUserPnl(client, withAccountWallet(client, request)),\n fetchUserVolume: (request?: SecureFetchUserVolumeRequest) =>\n fetchUserVolume(client, withAccountWallet(client, request)),\n downloadAccountingSnapshot: (\n request?: SecureDownloadAccountingSnapshotRequest,\n ) => downloadAccountingSnapshot(client, withAccountWallet(client, request)),\n listActivity: (request?: SecureListActivityRequest) =>\n listActivity(client, withAccountWallet(client, request)),\n listComboActivity: (request?: SecureListComboActivityRequest) =>\n listComboActivity(client, withAccountWallet(client, request)),\n listAccountTrades: listAccountTrades.bind(null, client),\n fetchNotifications: fetchNotifications.bind(null, client),\n dropNotifications: dropNotifications.bind(null, client),\n fetchClosedOnlyMode: fetchClosedOnlyMode.bind(null, client),\n };\n}\n\n// Error unions and runtime `isError` guards for every action bound above.\n// Surfaced at the root entry point through `export * from './decorators'`.\n// Keep this list in sync with the methods on PublicAccountActions / SecureAccountActions.\nexport {\n DownloadAccountingSnapshotError,\n DropNotificationsError,\n FetchClosedOnlyModeError,\n FetchNotificationsError,\n FetchPortfolioValueError,\n FetchTraderLeaderboardStandingError,\n FetchUserPnlError,\n FetchUserStatsError,\n FetchUserVolumeError,\n ListAccountTradesError,\n ListActivityError,\n ListComboActivityError,\n ListComboPositionsError,\n ListPositionsError,\n} from '../actions';\nexport {\n ComboActivityType,\n SortDirection,\n TipSide,\n TradeFilterType,\n} from '../actions/activity';\nexport type { ComboPositionStatusFilter } from '../actions/portfolio';\nexport {\n ComboPositionSortBy,\n ComboPositionStatus,\n PositionFilterType,\n PositionSortBy,\n PositionStatus,\n UserPnlFidelity,\n UserPnlInterval,\n} from '../actions/portfolio';\n","import type { BuilderTrade } from '@polymarket/bindings/clob';\nimport type {\n BiggestWinner,\n BuilderStanding,\n BuilderVolumePoint,\n TraderLeaderboardEntry,\n} from '@polymarket/bindings/data';\nimport {\n type FetchBuilderVolumeRequest,\n fetchBuilderVolume,\n type ListBiggestWinnersRequest,\n type ListBuilderLeaderboardRequest,\n type ListBuilderTradesRequest,\n type ListTraderLeaderboardRequest,\n listBiggestWinners,\n listBuilderLeaderboard,\n listBuilderTrades,\n listTraderLeaderboard,\n} from '../actions';\nimport type {\n BaseClient,\n BasePublicClient,\n BaseSecureClient,\n} from '../clients';\nimport type { Paginated } from '../pagination';\n\nexport type AnalyticsActions = {\n /**\n * Lists builder-attributed trades.\n *\n * @throws {@link ListBuilderTradesError}\n * Thrown on failure.\n *\n * @example\n * Fetch the first page of results:\n * ```ts\n * const paginator = client.listBuilderTrades({\n * builderCode: '0x...',\n * });\n *\n * const firstPage = await paginator.firstPage();\n *\n * // Optionally, fetch additional pages:\n * for await (const page of paginator.from(firstPage.nextCursor)) {\n * // page.items: BuilderTrade[]\n * }\n * ```\n *\n * @example\n * Loop through all pages with `for await`:\n * ```ts\n * const paginator = client.listBuilderTrades({\n * builderCode: '0x...',\n * });\n *\n * for await (const page of paginator) {\n * // page.items: BuilderTrade[]\n * }\n * ```\n */\n listBuilderTrades(\n request: ListBuilderTradesRequest,\n ): Paginated<BuilderTrade[]>;\n\n /**\n * Lists builder leaderboard rankings.\n *\n * Builders are ranked by attributed share volume within `window`, which\n * defaults to one day. `builderCode` is the stable identifier; names and\n * profile images are display metadata. `pageSize` defaults to 100 (max 1000).\n * Transient rate limits are retried automatically.\n *\n * @throws {@link ListBuilderLeaderboardError}\n * Thrown on failure.\n *\n * @example\n * Fetch the first page of results:\n * ```ts\n * const paginator = client.listBuilderLeaderboard({\n * pageSize: 10,\n * window: LeaderboardWindow.Day,\n * });\n *\n * const firstPage = await paginator.firstPage();\n *\n * // Optionally, fetch additional pages:\n * for await (const page of paginator.from(firstPage.nextCursor)) {\n * // page.items: BuilderStanding[]\n * }\n * ```\n *\n * @example\n * Loop through all pages with `for await`:\n * ```ts\n * const paginator = client.listBuilderLeaderboard({\n * pageSize: 10,\n * window: LeaderboardWindow.Day,\n * });\n *\n * for await (const page of paginator) {\n * // page.items: BuilderStanding[]\n * }\n * ```\n */\n listBuilderLeaderboard(\n request?: ListBuilderLeaderboardRequest,\n ): Paginated<BuilderStanding[]>;\n\n /**\n * Fetches the per-builder volume time series.\n *\n * `interval` controls bucket width and defaults to daily; use\n * {@link BuilderVolumeInterval.Year} for one bucket per calendar year.\n * `bucketLimit` returns that many complete recent buckets (default 30, max 90),\n * not that many builder rows. Results are newest bucket first, and volume is\n * measured in shares. Transient rate limits are retried automatically.\n *\n * @throws {@link FetchBuilderVolumeError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const volume = await client.fetchBuilderVolume({\n * interval: BuilderVolumeInterval.Day,\n * bucketLimit: 7,\n * });\n * ```\n */\n fetchBuilderVolume(\n request?: FetchBuilderVolumeRequest,\n ): Promise<BuilderVolumePoint[]>;\n\n /**\n * Lists trader leaderboard rankings.\n *\n * `window` defaults to one day, `category` to overall, and `sortBy` to PnL.\n * Finite-window PnL is marked equity change net of flows, while all-time PnL\n * is realized only. Volume is measured in shares. Tied traders share a rank\n * and the next rank skips. `pageSize` defaults to 100 (max 1000).\n *\n * @throws {@link ListTraderLeaderboardError}\n * Thrown on failure.\n *\n * @example\n * Fetch the first page of results:\n * ```ts\n * const paginator = client.listTraderLeaderboard({\n * pageSize: 10,\n * sortBy: TraderLeaderboardSort.Pnl,\n * window: LeaderboardWindow.Week,\n * });\n *\n * const firstPage = await paginator.firstPage();\n *\n * // Optionally, fetch additional pages:\n * for await (const page of paginator.from(firstPage.nextCursor)) {\n * // page.items: TraderLeaderboardEntry[]\n * }\n * ```\n *\n * @example\n * Loop through all pages with `for await`:\n * ```ts\n * const paginator = client.listTraderLeaderboard({\n * pageSize: 10,\n * sortBy: TraderLeaderboardSort.Pnl,\n * window: LeaderboardWindow.Week,\n * });\n *\n * for await (const page of paginator) {\n * // page.items: TraderLeaderboardEntry[]\n * }\n * ```\n */\n listTraderLeaderboard(\n request?: ListTraderLeaderboardRequest,\n ): Paginated<TraderLeaderboardEntry[]>;\n\n /**\n * Lists the largest individual winning positions.\n *\n * The board has one row per position, ranked by its resolution profit.\n * `window` applies to resolution time and defaults to one day; `category`\n * defaults to overall. Equal profits retain distinct row ordinals. Combo rows\n * have no parent event, so branch on `kind` before using event metadata.\n * `pageSize` defaults to 100 (max 1000).\n *\n * @throws {@link ListBiggestWinnersError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const paginator = client.listBiggestWinners({\n * category: 'sports',\n * pageSize: 10,\n * window: LeaderboardWindow.Week,\n * });\n *\n * for await (const page of paginator) {\n * // page.items: BiggestWinner[]\n * }\n * ```\n */\n listBiggestWinners(\n request?: ListBiggestWinnersRequest,\n ): Paginated<BiggestWinner[]>;\n};\n\nexport function analyticsActions(client: BasePublicClient): AnalyticsActions;\nexport function analyticsActions(client: BaseSecureClient): AnalyticsActions;\nexport function analyticsActions(client: BaseClient): AnalyticsActions {\n return {\n listBuilderTrades: listBuilderTrades.bind(null, client),\n listBuilderLeaderboard: listBuilderLeaderboard.bind(null, client),\n fetchBuilderVolume: fetchBuilderVolume.bind(null, client),\n listTraderLeaderboard: listTraderLeaderboard.bind(null, client),\n listBiggestWinners: listBiggestWinners.bind(null, client),\n };\n}\n\n// Error unions and runtime `isError` guards for every action bound above.\n// Surfaced at the root entry point through `export * from './decorators'`.\n// Keep this list in sync with the methods on AnalyticsActions.\nexport {\n BiggestWinnerKind,\n BuilderVolumeInterval,\n FetchBuilderVolumeError,\n LeaderboardWindow,\n ListBiggestWinnersError,\n ListBuilderLeaderboardError,\n ListBuilderTradesError,\n ListTraderLeaderboardError,\n TraderLeaderboardSort,\n} from '../actions';\n","import type { DecimalString } from '@polymarket/bindings';\nimport type {\n LastTradePrice,\n LastTradePriceForAsset,\n Midpoints,\n OrderBook,\n Prices,\n Spreads,\n} from '@polymarket/bindings/clob';\nimport type {\n LiveVolume,\n MetaHolder,\n OpenInterest,\n PriceHistoryPoint,\n Resolution,\n Trade,\n} from '@polymarket/bindings/data';\nimport {\n type EstimateMarketPriceRequest,\n estimateMarketPrice,\n type FetchEventLiveVolumeRequest,\n type FetchLastTradePriceRequest,\n type FetchLastTradePricesRequest,\n type FetchMidpointRequest,\n type FetchMidpointsRequest,\n type FetchOpenInterestRequest,\n type FetchOrderBookRequest,\n type FetchOrderBooksRequest,\n type FetchPriceRequest,\n type FetchPricesRequest,\n type FetchResolutionsRequest,\n type FetchSpreadRequest,\n type FetchSpreadsRequest,\n fetchEventLiveVolume,\n fetchLastTradePrice,\n fetchLastTradePrices,\n fetchMidpoint,\n fetchMidpoints,\n fetchOpenInterest,\n fetchOrderBook,\n fetchOrderBooks,\n fetchPrice,\n fetchPrices,\n fetchResolutions,\n fetchSpread,\n fetchSpreads,\n type ListMarketHoldersRequest,\n type ListPriceHistoryRequest,\n type ListTradesRequest,\n listMarketHolders,\n listPriceHistory,\n listTrades,\n} from '../actions';\nimport type {\n BaseClient,\n BasePublicClient,\n BaseSecureClient,\n} from '../clients';\nimport type { Paginated } from '../pagination';\n\nexport type DataActions = {\n /**\n * Fetches cumulative taker volume for one or more events.\n *\n * Results contain one row per market, ordered by taker volume descending, and\n * a total across all returned markets. Volume is measured in shares. Event\n * IDs must be positive 32-bit integers. Transient rate limits are retried\n * automatically.\n *\n * @throws {@link FetchEventLiveVolumeError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const volume = await client.fetchEventLiveVolume({\n * eventIds: ['160707'],\n * });\n * ```\n */\n fetchEventLiveVolume(\n request: FetchEventLiveVolumeRequest,\n ): Promise<LiveVolume>;\n /**\n * Fetches resolution lifecycle rows by question, condition, or event.\n *\n * Provide exactly one selector. Condition and event lookups accept at most\n * 20 distinct IDs and return one row per matching condition. Missing\n * resolutions return an empty array. A 31-byte protocol v2 market condition\n * ID is right-padded to its canonical 32-byte form. A 31-byte combo condition\n * ID is rejected.\n *\n * @throws {@link FetchResolutionsError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const resolutions = await client.fetchResolutions({\n * eventIds: ['903193'],\n * });\n * ```\n */\n fetchResolutions(request: FetchResolutionsRequest): Promise<Resolution[]>;\n /**\n * Fetches the midpoint price for an exchange asset as a decimal string.\n *\n * @throws {@link FetchMidpointError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const midpoint = await client.fetchMidpoint({ assetId: '0x0122…0000' });\n * ```\n */\n fetchMidpoint(request: FetchMidpointRequest): Promise<DecimalString>;\n /**\n * Fetches midpoint prices for multiple exchange assets as an asset ID keyed lookup.\n *\n * @throws {@link FetchMidpointsError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const midpoints = await client.fetchMidpoints([{ assetId: '0x0122…0000' }]);\n * ```\n */\n fetchMidpoints(request: FetchMidpointsRequest): Promise<Midpoints>;\n /**\n * Fetches the current quoted price for an exchange asset and side as a decimal string.\n *\n * @throws {@link FetchPriceError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const price = await client.fetchPrice({ assetId: '0x0122…0000', side: OrderSide.BUY });\n * ```\n */\n fetchPrice(request: FetchPriceRequest): Promise<DecimalString>;\n /**\n * Fetches quoted prices for multiple exchange assets as an asset ID keyed lookup.\n *\n * @throws {@link FetchPricesError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const prices = await client.fetchPrices([{ assetId: '0x0122…0000', side: OrderSide.BUY }]);\n * ```\n */\n fetchPrices(request: FetchPricesRequest): Promise<Prices>;\n /**\n * Fetches the current order book for an exchange asset.\n *\n * @throws {@link FetchOrderBookError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const book = await client.fetchOrderBook({ assetId: '0x0122…0000' });\n * ```\n */\n fetchOrderBook(request: FetchOrderBookRequest): Promise<OrderBook>;\n /**\n * Fetches order books for multiple exchange assets.\n *\n * @throws {@link FetchOrderBooksError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const books = await client.fetchOrderBooks([{ assetId: '0x0122…0000' }]);\n * ```\n */\n fetchOrderBooks(request: FetchOrderBooksRequest): Promise<OrderBook[]>;\n /**\n * Fetches the spread for an exchange asset as a decimal string.\n *\n * @throws {@link FetchSpreadError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const spread = await client.fetchSpread({ assetId: '0x0122…0000' });\n * ```\n */\n fetchSpread(request: FetchSpreadRequest): Promise<DecimalString>;\n /**\n * Fetches spreads for multiple exchange assets as an asset ID keyed lookup.\n *\n * @throws {@link FetchSpreadsError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const spreads = await client.fetchSpreads([{ assetId: '0x0122…0000' }]);\n * ```\n */\n fetchSpreads(request: FetchSpreadsRequest): Promise<Spreads>;\n /**\n * Fetches the last traded price for an exchange asset.\n *\n * Returns `null` when the asset has not traded.\n *\n * @throws {@link FetchLastTradePriceError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const trade = await client.fetchLastTradePrice({ assetId: '0x0122…0000' });\n *\n * // trade === LastTradePrice | null\n * ```\n */\n fetchLastTradePrice(\n request: FetchLastTradePriceRequest,\n ): Promise<LastTradePrice | null>;\n /**\n * Fetches last traded prices for multiple exchange assets.\n *\n * Assets without trades are omitted from the response. Match returned rows by\n * `assetId`; the array is not positionally aligned with the request.\n *\n * @throws {@link FetchLastTradePricesError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const trades = await client.fetchLastTradePrices([{ assetId: '0x0122…0000' }]);\n * const trade = trades.find((candidate) => candidate.assetId === '0x0122…0000');\n * ```\n */\n fetchLastTradePrices(\n request: FetchLastTradePricesRequest,\n ): Promise<LastTradePriceForAsset[]>;\n /**\n * Lists historical price observations for an exchange asset.\n *\n * Select exactly one time form: a relative `interval`, an explicit `start`\n * with optional `end`, or the latest observation at or before an `asOf`\n * instant. Time inputs accept Unix epoch seconds or `Date` values. When\n * `bucketSeconds` is omitted, resolution is selected automatically for the\n * requested window and reported on each point as `resolutionSeconds`. An\n * explicit bucket is used exactly as requested and may produce an empty series\n * when that resolution is unavailable for the window. Prices are decimal\n * strings and returned timestamps are Unix epoch milliseconds. Series pages\n * are ordered oldest first; an `asOf` request returns at most one item. Series\n * page sizes default to and are capped at 10,000 points. Transient rate limits\n * are retried automatically.\n *\n * @throws {@link ListPriceHistoryError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const history = client.listPriceHistory({\n * assetId: '17023124228269928849020611259015948850061676830917875073785033885105715180702',\n * interval: PriceHistoryInterval.OneDay,\n * bucketSeconds: 3600,\n * });\n *\n * for await (const page of history) {\n * // page.items: PriceHistoryPoint[]\n * }\n * ```\n */\n listPriceHistory(\n request: ListPriceHistoryRequest,\n ): Paginated<PriceHistoryPoint[]>;\n /**\n * Estimates the price level a market order would cross at current book depth.\n *\n * For BUY orders, `amount` is the amount of collateral to spend. For SELL\n * orders, `shares` is the number of shares to sell.\n *\n * @throws {@link EstimateMarketPriceError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const price = await client.estimateMarketPrice({\n * assetId: '0x0122…0000',\n * side: OrderSide.BUY,\n * amount: 10,\n * });\n * ```\n */\n estimateMarketPrice(request: EstimateMarketPriceRequest): Promise<number>;\n /**\n * Fetches priced gross open interest for selected markets or globally.\n *\n * `conditionIds` accepts up to 20 distinct market condition IDs. Omit it for\n * the global aggregate, whose `conditionId` is `null`. A requested servable\n * market with no holdings has a zero value; an absent row means the market\n * is not servable. Values are in USDC. Transient rate limits are retried\n * automatically.\n *\n * @throws {@link FetchOpenInterestError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const openInterest = await client.fetchOpenInterest({\n * conditionIds: ['0xe546672750517f62c45a5a00067481981e62b9c20fa8220203232c9dc8fd2093'],\n * });\n * ```\n */\n fetchOpenInterest(\n request?: FetchOpenInterestRequest,\n ): Promise<OpenInterest[]>;\n /**\n * Lists top holders grouped by outcome for one or more markets.\n *\n * `conditionIds` accepts up to 20 distinct market condition IDs. `pageSize`\n * defaults to 100 (max 1000) and applies separately to each outcome. Merge\n * matching `assetId` groups across pages rather than relying on array position.\n * `minBalance` uses display shares and defaults to `0`; `1` means one share,\n * equivalent to 1,000,000 base units.\n * Amounts are net holdings by default. `includePnl` switches to per-outcome\n * gross holdings and adds position economics; it requires one condition ID and\n * a page size of at most 100. Transient rate limits are retried automatically.\n *\n * @throws {@link ListMarketHoldersError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const result = client.listMarketHolders({\n * conditionIds: ['0xe546672750517f62c45a5a00067481981e62b9c20fa8220203232c9dc8fd2093'],\n * pageSize: 5,\n * });\n *\n * for await (const page of result) {\n * // page.items: MetaHolder[]\n * }\n * ```\n */\n listMarketHolders(request: ListMarketHoldersRequest): Paginated<MetaHolder[]>;\n /**\n * Lists trades for a wallet, market, or event — or the global recent-trades\n * feed when no filter is given.\n *\n * Only the taker side of each match is returned by default\n * (`takerOnly: false` includes maker rows), and a dust filter of 0.01\n * shares applies unless `filterType`/`filterAmount` say otherwise (either\n * may be sent alone). `conditionId` accepts at most 20 distinct ids. `pageSize`\n * defaults to 100 (max 1000). `window: 'full'` requests the complete\n * history; an omitted window serves the recent feed. Window bounds accept\n * Unix epoch seconds or `Date` values. Transient rate limits are retried\n * automatically.\n *\n * @throws {@link ListTradesError}\n * Thrown on failure.\n *\n * @example\n * Fetch the first page of results:\n * ```ts\n * const paginator = client.listTrades({\n * user: '0x7c3db723f1d4d8cb9c550095203b686cb11e5c6b',\n * pageSize: 10,\n * });\n *\n * const firstPage = await paginator.firstPage();\n *\n * // Optionally, fetch additional pages:\n * for await (const page of paginator.from(firstPage.nextCursor)) {\n * // page.items: Trade[]\n * }\n * ```\n *\n * @example\n * Loop through all pages with `for await`:\n * ```ts\n * const paginator = client.listTrades({\n * user: '0x7c3db723f1d4d8cb9c550095203b686cb11e5c6b',\n * pageSize: 10,\n * });\n *\n * for await (const page of paginator) {\n * // page.items: Trade[]\n * }\n * ```\n */\n listTrades(request?: ListTradesRequest): Paginated<Trade[]>;\n};\n\nexport function dataActions(client: BasePublicClient): DataActions;\nexport function dataActions(client: BaseSecureClient): DataActions;\nexport function dataActions(client: BaseClient): DataActions {\n return {\n fetchEventLiveVolume: fetchEventLiveVolume.bind(null, client),\n fetchResolutions: fetchResolutions.bind(null, client),\n fetchMidpoint: fetchMidpoint.bind(null, client),\n fetchMidpoints: fetchMidpoints.bind(null, client),\n fetchPrice: fetchPrice.bind(null, client),\n fetchPrices: fetchPrices.bind(null, client),\n fetchOrderBook: fetchOrderBook.bind(null, client),\n fetchOrderBooks: fetchOrderBooks.bind(null, client),\n fetchSpread: fetchSpread.bind(null, client),\n fetchSpreads: fetchSpreads.bind(null, client),\n fetchLastTradePrice: fetchLastTradePrice.bind(null, client),\n fetchLastTradePrices: fetchLastTradePrices.bind(null, client),\n listPriceHistory: listPriceHistory.bind(null, client),\n estimateMarketPrice: estimateMarketPrice.bind(null, client),\n fetchOpenInterest: fetchOpenInterest.bind(null, client),\n listMarketHolders: listMarketHolders.bind(null, client),\n listTrades: listTrades.bind(null, client),\n };\n}\n\n// Error unions and runtime `isError` guards for every action bound above.\n// Surfaced at the root entry point through `export * from './decorators'`.\n// Keep this list in sync with the methods on DataActions.\nexport {\n EstimateMarketPriceError,\n FetchEventLiveVolumeError,\n FetchLastTradePriceError,\n FetchLastTradePricesError,\n FetchMidpointError,\n FetchMidpointsError,\n FetchOpenInterestError,\n FetchOrderBookError,\n FetchOrderBooksError,\n FetchPriceError,\n FetchPricesError,\n FetchResolutionsError,\n FetchSpreadError,\n FetchSpreadsError,\n ListMarketHoldersError,\n ListPriceHistoryError,\n ListTradesError,\n PriceHistoryInterval,\n ResolutionMarketType,\n ResolutionReporter,\n ResolutionSource,\n ResolutionStatus,\n} from '../actions';\n","import type { ComboMarket } from '@polymarket/bindings/combos';\nimport type {\n Comment,\n Event,\n Market,\n MarketClarification,\n PublicProfile,\n RelatedTag,\n Series,\n SportsMarketTypesResponse,\n SportsMetadata,\n Tag,\n TagReference,\n Team,\n} from '@polymarket/bindings/gamma';\nimport {\n type FetchCommentsByIdRequest,\n type FetchEventRequest,\n type FetchEventTagsRequest,\n type FetchMarketRequest,\n type FetchMarketTagsRequest,\n type FetchPublicProfileRequest,\n type FetchRelatedTagResourcesRequest,\n type FetchRelatedTagsRequest,\n type FetchSeriesRequest,\n type FetchTagRequest,\n fetchCommentsById,\n fetchEvent,\n fetchEventTags,\n fetchMarket,\n fetchMarketTags,\n fetchPublicProfile,\n fetchRelatedTagResources,\n fetchRelatedTags,\n fetchSeries,\n fetchSportsMarketTypes,\n fetchTag,\n type ListComboMarketsRequest,\n type ListCommentsByUserAddressRequest,\n type ListCommentsRequest,\n type ListEventsRequest,\n type ListMarketClarificationsRequest,\n type ListMarketsRequest,\n type ListSeriesRequest,\n type ListTagsRequest,\n type ListTeamsRequest,\n listComboMarkets,\n listComments,\n listCommentsByUserAddress,\n listEvents,\n listMarketClarifications,\n listMarkets,\n listSeries,\n listSports,\n listTags,\n listTeams,\n type SearchRequest,\n type SearchResults,\n search,\n} from '../actions';\nimport type {\n BaseClient,\n BasePublicClient,\n BaseSecureClient,\n} from '../clients';\nimport type { Paginated } from '../pagination';\n\nexport type DiscoveryActions = {\n /**\n * Lists events.\n *\n * Defaults to open events. Pass `closed: true` to list settled events.\n *\n * @throws {@link ListEventsError}\n * Thrown on failure.\n *\n * @example\n * Fetch the first page of results:\n * ```ts\n * const paginator = client.listEvents({\n * pageSize: 10,\n * });\n *\n * const firstPage = await paginator.firstPage();\n *\n * // Optionally, fetch additional pages:\n * for await (const page of paginator.from(firstPage.nextCursor)) {\n * // page.items: Event[]\n * }\n * ```\n *\n * @example\n * Loop through all pages with `for await`:\n * ```ts\n * const paginator = client.listEvents({\n * pageSize: 10,\n * });\n *\n * for await (const page of paginator) {\n * // page.items: Event[]\n * }\n * ```\n */\n listEvents(request?: ListEventsRequest): Paginated<Event[]>;\n\n /**\n * Fetches an event.\n *\n * @throws {@link FetchEventError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const event = await client.fetchEvent({\n * id: '123',\n * });\n *\n * const eventBySlug = await client.fetchEvent({\n * slug: 'presidential-election-2028',\n * });\n *\n * const eventByUrl = await client.fetchEvent({\n * url: 'https://polymarket.com/event/presidential-election-2028',\n * });\n * ```\n */\n fetchEvent(request: FetchEventRequest): Promise<Event>;\n\n /**\n * Fetches an event's tags.\n *\n * @throws {@link FetchEventTagsError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const tags = await client.fetchEventTags({\n * id: '123',\n * });\n * ```\n */\n fetchEventTags(request: FetchEventTagsRequest): Promise<TagReference[]>;\n\n /**\n * Lists markets.\n *\n * @remarks\n * Legacy multi-outcome markets cannot be represented by the binary\n * {@link Market} model and are omitted from results.\n *\n * @throws {@link ListMarketsError}\n * Thrown on failure.\n *\n * @example\n * Fetch the first page of results:\n * ```ts\n * const paginator = client.listMarkets({\n * closed: false,\n * pageSize: 10,\n * });\n *\n * const firstPage = await paginator.firstPage();\n *\n * // Optionally, fetch additional pages:\n * for await (const page of paginator.from(firstPage.nextCursor)) {\n * // page.items: Market[]\n * }\n * ```\n *\n * @example\n * Loop through all pages with `for await`:\n * ```ts\n * const paginator = client.listMarkets({\n * closed: false,\n * pageSize: 10,\n * });\n *\n * for await (const page of paginator) {\n * // page.items: Market[]\n * }\n * ```\n */\n listMarkets(request?: ListMarketsRequest): Paginated<Market[]>;\n\n /**\n * Lists markets available for Combos.\n *\n * @throws {@link ListComboMarketsError}\n * Thrown on failure.\n *\n * @example\n * Fetch the first page of results:\n * ```ts\n * const paginator = client.listComboMarkets({\n * pageSize: 10,\n * });\n *\n * const firstPage = await paginator.firstPage();\n *\n * // Optionally, fetch additional pages:\n * for await (const page of paginator.from(firstPage.nextCursor)) {\n * // page.items: ComboMarket[]\n * }\n * ```\n *\n * @example\n * Loop through all pages with `for await`:\n * ```ts\n * const paginator = client.listComboMarkets({\n * pageSize: 10,\n * });\n *\n * for await (const page of paginator) {\n * // page.items: ComboMarket[]\n * }\n * ```\n *\n * @example\n * Omit markets the caller has already displayed:\n * ```ts\n * const paginator = client.listComboMarkets({\n * exclude: ['0x4cd77d456c83e7d8c569a8fb8f6396c3f40154f657e6d970733e2b1b6a7110ff'],\n * pageSize: 10,\n * });\n * ```\n */\n listComboMarkets(request?: ListComboMarketsRequest): Paginated<ComboMarket[]>;\n\n /**\n * Fetches a market.\n *\n * @remarks\n * Legacy multi-outcome markets cannot be represented by the binary\n * {@link Market} model, so fetching one fails with an\n * `UnexpectedResponseError`.\n *\n * @throws {@link FetchMarketError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const market = await client.fetchMarket({\n * id: '12345',\n * });\n *\n * const marketBySlug = await client.fetchMarket({\n * slug: 'some-market-slug',\n * });\n *\n * const marketByUrl = await client.fetchMarket({\n * url: 'https://polymarket.com/event/some-market-slug',\n * });\n * ```\n */\n fetchMarket(request: FetchMarketRequest): Promise<Market>;\n\n /**\n * Fetches a market's tags.\n *\n * @throws {@link FetchMarketTagsError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const tags = await client.fetchMarketTags({\n * id: '12345',\n * });\n * ```\n */\n fetchMarketTags(request: FetchMarketTagsRequest): Promise<TagReference[]>;\n\n /**\n * Lists series.\n *\n * @throws {@link ListSeriesError}\n * Thrown on failure.\n *\n * @example\n * Fetch the first page of results:\n * ```ts\n * const paginator = client.listSeries({\n * pageSize: 10,\n * });\n *\n * const firstPage = await paginator.firstPage();\n *\n * // Optionally, fetch additional pages:\n * for await (const page of paginator.from(firstPage.nextCursor)) {\n * // page.items: Series[]\n * }\n * ```\n *\n * @example\n * Loop through all pages with `for await`:\n * ```ts\n * const paginator = client.listSeries({\n * pageSize: 10,\n * });\n *\n * for await (const page of paginator) {\n * // page.items: Series[]\n * }\n * ```\n */\n listSeries(request?: ListSeriesRequest): Paginated<Series[]>;\n\n /**\n * Fetches a series.\n *\n * @throws {@link FetchSeriesError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const series = await client.fetchSeries({\n * id: '123',\n * });\n * ```\n */\n fetchSeries(request: FetchSeriesRequest): Promise<Series>;\n\n /**\n * Lists market clarifications — notes that resolve ambiguity in how a market\n * settles.\n *\n * @throws {@link ListMarketClarificationsError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const paginator = client.listMarketClarifications({\n * marketId: '512038',\n * });\n *\n * for await (const page of paginator) {\n * // page.items: MarketClarification[]\n * }\n * ```\n */\n listMarketClarifications(\n request?: ListMarketClarificationsRequest,\n ): Paginated<MarketClarification[]>;\n\n /**\n * Lists tags.\n *\n * @throws {@link ListTagsError}\n * Thrown on failure.\n *\n * @example\n * Fetch the first page of results:\n * ```ts\n * const paginator = client.listTags({\n * pageSize: 10,\n * });\n *\n * const firstPage = await paginator.firstPage();\n *\n * // Optionally, fetch additional pages:\n * for await (const page of paginator.from(firstPage.nextCursor)) {\n * // page.items: Tag[]\n * }\n * ```\n *\n * @example\n * Loop through all pages with `for await`:\n * ```ts\n * const paginator = client.listTags({\n * pageSize: 10,\n * });\n *\n * for await (const page of paginator) {\n * // page.items: Tag[]\n * }\n * ```\n */\n listTags(request?: ListTagsRequest): Paginated<Tag[]>;\n\n /**\n * Fetches a tag by id or slug.\n *\n * @throws {@link FetchTagError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const tag = await client.fetchTag({\n * slug: 'politics',\n * });\n * ```\n */\n fetchTag(request: FetchTagRequest): Promise<Tag>;\n\n /**\n * Fetches related tag relationships by id or slug.\n *\n * @throws {@link FetchRelatedTagsError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const related = await client.fetchRelatedTags({\n * slug: 'politics',\n * });\n * ```\n */\n fetchRelatedTags(request: FetchRelatedTagsRequest): Promise<RelatedTag[]>;\n\n /**\n * Fetches resources linked from related tag relationships by id or slug.\n *\n * @throws {@link FetchRelatedTagResourcesError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const resources = await client.fetchRelatedTagResources({\n * slug: 'politics',\n * });\n * ```\n */\n fetchRelatedTagResources(\n request: FetchRelatedTagResourcesRequest,\n ): Promise<Tag[]>;\n\n /**\n * Runs a public full-text search.\n *\n * `keepClosedMarkets` is an hour window for including recently closed markets\n * when searching active events.\n *\n * @throws {@link SearchError}\n * Thrown on failure.\n *\n * @example\n * Fetch the first page of results:\n * ```ts\n * const paginator = client.search({\n * q: 'election',\n * pageSize: 10,\n * });\n *\n * const firstPage = await paginator.firstPage();\n *\n * // Optionally, fetch additional pages:\n * for await (const page of paginator.from(firstPage.nextCursor)) {\n * // page.items.events: Event[]\n * // page.items.tags: SearchTag[]\n * // page.items.profiles: Profile[]\n * }\n * ```\n */\n search(request: SearchRequest): Paginated<SearchResults>;\n\n /**\n * Lists available sports metadata.\n *\n * @throws {@link ListSportsError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const sports = await client.listSports();\n * ```\n */\n listSports(): Promise<SportsMetadata[]>;\n\n /**\n * Fetches the available market types grouped by sport.\n *\n * @throws {@link FetchSportsMarketTypesError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const marketTypes = await client.fetchSportsMarketTypes();\n * ```\n */\n fetchSportsMarketTypes(): Promise<SportsMarketTypesResponse>;\n\n /**\n * Lists teams.\n *\n * @throws {@link ListTeamsError}\n * Thrown on failure.\n *\n * @example\n * Fetch the first page of results:\n * ```ts\n * const paginator = client.listTeams({\n * pageSize: 10,\n * });\n *\n * const firstPage = await paginator.firstPage();\n *\n * // Optionally, fetch additional pages:\n * for await (const page of paginator.from(firstPage.nextCursor)) {\n * // page.items: Team[]\n * }\n * ```\n *\n * @example\n * Loop through all pages with `for await`:\n * ```ts\n * const paginator = client.listTeams({\n * pageSize: 10,\n * });\n *\n * for await (const page of paginator) {\n * // page.items: Team[]\n * }\n * ```\n */\n listTeams(request?: ListTeamsRequest): Paginated<Team[]>;\n\n /**\n * Fetches a public profile by wallet address.\n *\n * @throws {@link FetchPublicProfileError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const profile = await client.fetchPublicProfile({\n * address: '0x1234...',\n * });\n * ```\n */\n fetchPublicProfile(\n request: FetchPublicProfileRequest,\n ): Promise<PublicProfile | null>;\n\n /**\n * Lists comments for an event or series.\n *\n * @throws {@link ListCommentsError}\n * Thrown on failure.\n *\n * @example\n * Fetch the first page of results:\n * ```ts\n * const paginator = client.listComments({\n * parentEntityId: '123',\n * parentEntityType: CommentParentEntityType.Event,\n * pageSize: 20,\n * });\n *\n * const firstPage = await paginator.firstPage();\n *\n * // Optionally, fetch additional pages:\n * for await (const page of paginator.from(firstPage.nextCursor)) {\n * // page.items: Comment[]\n * }\n * ```\n *\n * @example\n * Loop through all pages with `for await`:\n * ```ts\n * const paginator = client.listComments({\n * parentEntityId: '123',\n * parentEntityType: CommentParentEntityType.Event,\n * pageSize: 20,\n * });\n *\n * for await (const page of paginator) {\n * // page.items: Comment[]\n * }\n * ```\n */\n listComments(request: ListCommentsRequest): Paginated<Comment[]>;\n\n /**\n * Fetches a comment thread by comment id.\n *\n * @throws {@link FetchCommentsByIdError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const thread = await client.fetchCommentsById({\n * id: '456',\n * getPositions: true,\n * });\n * ```\n */\n fetchCommentsById(request: FetchCommentsByIdRequest): Promise<Comment[]>;\n\n /**\n * Lists comments written by a wallet address.\n *\n * @throws {@link ListCommentsByUserAddressError}\n * Thrown on failure.\n *\n * @example\n * Fetch the first page of results:\n * ```ts\n * const paginator = client.listCommentsByUserAddress({\n * address: '0x1234...',\n * pageSize: 10,\n * order: 'DESC',\n * });\n *\n * const firstPage = await paginator.firstPage();\n *\n * // Optionally, fetch additional pages:\n * for await (const page of paginator.from(firstPage.nextCursor)) {\n * // page.items: Comment[]\n * }\n * ```\n *\n * @example\n * Loop through all pages with `for await`:\n * ```ts\n * const paginator = client.listCommentsByUserAddress({\n * address: '0x1234...',\n * pageSize: 10,\n * order: 'DESC',\n * });\n *\n * for await (const page of paginator) {\n * // page.items: Comment[]\n * }\n * ```\n */\n listCommentsByUserAddress(\n request: ListCommentsByUserAddressRequest,\n ): Paginated<Comment[]>;\n};\n\nexport function discoveryActions(client: BasePublicClient): DiscoveryActions;\nexport function discoveryActions(client: BaseSecureClient): DiscoveryActions;\nexport function discoveryActions(client: BaseClient): DiscoveryActions {\n return {\n listEvents: listEvents.bind(null, client),\n fetchEvent: fetchEvent.bind(null, client),\n fetchEventTags: fetchEventTags.bind(null, client),\n listMarkets: listMarkets.bind(null, client),\n listComboMarkets: listComboMarkets.bind(null, client),\n fetchMarket: fetchMarket.bind(null, client),\n fetchMarketTags: fetchMarketTags.bind(null, client),\n listSeries: listSeries.bind(null, client),\n fetchSeries: fetchSeries.bind(null, client),\n listMarketClarifications: listMarketClarifications.bind(null, client),\n listTags: listTags.bind(null, client),\n fetchTag: fetchTag.bind(null, client),\n fetchRelatedTags: fetchRelatedTags.bind(null, client),\n fetchRelatedTagResources: fetchRelatedTagResources.bind(null, client),\n search: search.bind(null, client),\n listSports: listSports.bind(null, client),\n fetchSportsMarketTypes: fetchSportsMarketTypes.bind(null, client),\n listTeams: listTeams.bind(null, client),\n fetchPublicProfile: fetchPublicProfile.bind(null, client),\n listComments: listComments.bind(null, client),\n fetchCommentsById: fetchCommentsById.bind(null, client),\n listCommentsByUserAddress: listCommentsByUserAddress.bind(null, client),\n };\n}\n\n// Error unions and runtime `isError` guards for every action bound above.\n// Surfaced at the root entry point through `export * from './decorators'`.\n// Keep this list in sync with the methods on DiscoveryActions.\nexport {\n FetchCommentsByIdError,\n FetchEventError,\n FetchEventTagsError,\n FetchMarketError,\n FetchMarketTagsError,\n FetchPublicProfileError,\n FetchRelatedTagResourcesError,\n FetchRelatedTagsError,\n FetchSeriesError,\n FetchSportsMarketTypesError,\n FetchTagError,\n ListComboMarketsError,\n ListCommentsByUserAddressError,\n ListCommentsError,\n ListEventsError,\n ListMarketsError,\n ListSeriesError,\n ListSportsError,\n ListTagsError,\n ListTeamsError,\n SearchError,\n} from '../actions';\n","import type {\n PerpsBook,\n PerpsCandle,\n PerpsFeeScheduleEntry,\n PerpsFundingRate,\n PerpsInstrument,\n PerpsPublicTrade,\n PerpsTicker,\n PerpsWithdrawalId,\n} from '@polymarket/bindings/perps';\nimport {\n type DepositToPerpsRequest,\n depositToPerps,\n type FetchPerpsBookRequest,\n type FetchPerpsInstrumentsRequest,\n type FetchPerpsTickerRequest,\n type FetchPerpsTickersRequest,\n fetchPerpsBook,\n fetchPerpsFees,\n fetchPerpsInstruments,\n fetchPerpsTicker,\n fetchPerpsTickers,\n type ListPerpsCandlesRequest,\n type ListPerpsFundingHistoryRequest,\n type ListPerpsTradesRequest,\n listPerpsCandles,\n listPerpsFundingHistory,\n listPerpsTrades,\n type OpenPerpsSessionRequest,\n openPerpsSession,\n type PerpsSession,\n type RevokePerpsCredentialsRequest,\n revokePerpsCredentials,\n type WithdrawFromPerpsRequest,\n withdrawFromPerps,\n} from '../actions';\nimport type {\n BaseClient,\n BasePublicClient,\n BaseSecureClient,\n} from '../clients';\nimport type { Paginated } from '../pagination';\nimport type { TransactionHandle } from '../types';\n\nexport type {\n ArmPerpsAutoCancelRequest,\n CancelAllPerpsOrdersRequest,\n CancelPerpsOrderRequest,\n CancelPerpsOrdersRequest,\n CreatePerpsSessionRequest,\n DepositToPerpsRequest,\n DisarmPerpsAutoCancelRequest,\n FetchPerpsAccountConfigRequest,\n FetchPerpsBookRequest,\n FetchPerpsInstrumentsRequest,\n FetchPerpsOpenOrdersRequest,\n FetchPerpsOrdersRequest,\n FetchPerpsTickerRequest,\n FetchPerpsTickersRequest,\n ListPerpsCandlesRequest,\n ListPerpsDepositsRequest,\n ListPerpsEquityHistoryRequest,\n ListPerpsFillsRequest,\n ListPerpsFundingHistoryRequest,\n ListPerpsFundingPaymentsRequest,\n ListPerpsNotificationsRequest,\n ListPerpsPnlHistoryRequest,\n ListPerpsTradesRequest,\n ListPerpsWithdrawalsRequest,\n MarkPerpsNotificationsReadRequest,\n OpenPerpsSessionRequest,\n PerpsAutoCancelStatus,\n PerpsBookDepth,\n PerpsCancelOrderResult,\n PerpsOrderRequest,\n PerpsPlacedTpSlOrder,\n PerpsPlacedTpSlOrders,\n PerpsPlaceFokOrderRequest,\n PerpsPlaceGtcOrderRequest,\n PerpsPlaceIocOrderRequest,\n PerpsPositionTpSlTrigger,\n PerpsPostOrderAck,\n PerpsSession,\n PerpsSessionAccountError,\n PerpsSessionEvent,\n PerpsSessionLifecycleError,\n PerpsSessionTradingError,\n PerpsTpSlTrigger,\n PerpsUpdateLeverageResult,\n PlacePerpsOrderRequest,\n PlacePerpsOrderResult,\n PlacePerpsOrderWithTpSlRequest,\n PlacePerpsOrderWithTpSlResult,\n PlacePerpsPositionTpSlRequest,\n PlacePerpsPositionTpSlResult,\n PostPerpsOrdersRequest,\n ResumePerpsSessionRequest,\n RevokePerpsCredentialsRequest,\n UpdatePerpsLeverageRequest,\n UpdatePerpsMarginRequest,\n WithdrawFromPerpsRequest,\n} from '../actions';\nexport {\n ArmPerpsAutoCancelError,\n DepositToPerpsError,\n FetchPerpsBookError,\n FetchPerpsFeesError,\n FetchPerpsInstrumentsError,\n FetchPerpsTickerError,\n FetchPerpsTickersError,\n ListPerpsCandlesError,\n ListPerpsFundingHistoryError,\n ListPerpsTradesError,\n OpenPerpsSessionError,\n RevokePerpsCredentialsError,\n UpdatePerpsLeverageError,\n UpdatePerpsMarginError,\n WithdrawFromPerpsError,\n} from '../actions';\n\n/**\n * @experimental This API may change in a breaking way in any release, including patch releases.\n */\nexport type PublicPerpsActions = {\n /**\n * Fetches Perps instruments.\n *\n * @example\n * ```ts\n * const instruments = await client.fetchPerpsInstruments();\n * ```\n *\n * @throws {@link FetchPerpsInstrumentsError}\n * Thrown on failure.\n *\n * @experimental This API may change in a breaking way in any release, including patch releases.\n */\n fetchPerpsInstruments(\n request?: FetchPerpsInstrumentsRequest,\n ): Promise<PerpsInstrument[]>;\n\n /**\n * Fetches the current Perps ticker for an instrument.\n *\n * @example\n * ```ts\n * const ticker = await client.fetchPerpsTicker({ instrumentId: 1 });\n * ```\n *\n * @throws {@link FetchPerpsTickerError}\n * Thrown on failure.\n *\n * @experimental This API may change in a breaking way in any release, including patch releases.\n */\n fetchPerpsTicker(request: FetchPerpsTickerRequest): Promise<PerpsTicker>;\n\n /**\n * Fetches current Perps tickers.\n *\n * @example\n * ```ts\n * const tickers = await client.fetchPerpsTickers();\n * ```\n *\n * @throws {@link FetchPerpsTickersError}\n * Thrown on failure.\n *\n * @experimental This API may change in a breaking way in any release, including patch releases.\n */\n fetchPerpsTickers(request?: FetchPerpsTickersRequest): Promise<PerpsTicker[]>;\n\n /**\n * Fetches a Perps order book.\n *\n * @example\n * ```ts\n * const book = await client.fetchPerpsBook({ instrumentId: 1, depth: 100 });\n * ```\n *\n * @throws {@link FetchPerpsBookError}\n * Thrown on failure.\n *\n * @experimental This API may change in a breaking way in any release, including patch releases.\n */\n fetchPerpsBook(request: FetchPerpsBookRequest): Promise<PerpsBook>;\n\n /**\n * Lists Perps candles for an instrument with SDK-owned pagination.\n *\n * @example\n * ```ts\n * for await (const candles of client.listPerpsCandles({\n * instrumentId: 1,\n * interval: PerpsKlineInterval.OneMinute,\n * })) {\n * console.log(candles);\n * }\n * ```\n *\n * @throws {@link ListPerpsCandlesError}\n * Thrown on failure.\n *\n * @experimental This API may change in a breaking way in any release, including patch releases.\n */\n listPerpsCandles(request: ListPerpsCandlesRequest): Paginated<PerpsCandle[]>;\n\n /**\n * Lists Perps funding-rate history for an instrument with SDK-owned pagination.\n *\n * @example\n * ```ts\n * for await (const rates of client.listPerpsFundingHistory({\n * instrumentId: 1,\n * })) {\n * console.log(rates);\n * }\n * ```\n *\n * @throws {@link ListPerpsFundingHistoryError}\n * Thrown on failure.\n *\n * @experimental This API may change in a breaking way in any release, including patch releases.\n */\n listPerpsFundingHistory(\n request: ListPerpsFundingHistoryRequest,\n ): Paginated<PerpsFundingRate[]>;\n\n /**\n * Lists recent Perps trades for an instrument with SDK-owned pagination.\n *\n * @example\n * ```ts\n * for await (const trades of client.listPerpsTrades({ instrumentId: 1 })) {\n * console.log(trades);\n * }\n * ```\n *\n * @throws {@link ListPerpsTradesError}\n * Thrown on failure.\n *\n * @experimental This API may change in a breaking way in any release, including patch releases.\n */\n listPerpsTrades(\n request: ListPerpsTradesRequest,\n ): Paginated<PerpsPublicTrade[]>;\n\n /**\n * Fetches the Perps fee schedule.\n *\n * @example\n * ```ts\n * const fees = await client.fetchPerpsFees();\n * ```\n *\n * @throws {@link FetchPerpsFeesError}\n * Thrown on failure.\n *\n * @experimental This API may change in a breaking way in any release, including patch releases.\n */\n fetchPerpsFees(): Promise<PerpsFeeScheduleEntry[]>;\n};\n\n/**\n * @experimental This API may change in a breaking way in any release, including patch releases.\n */\nexport type SecurePerpsActions = PublicPerpsActions & {\n /**\n * Deposits collateral into Perps for the authenticated signer account.\n *\n * @example\n * ```ts\n * const transaction = await client.depositToPerps({ amount: 100_000_000n });\n * ```\n *\n * @throws {@link DepositToPerpsError}\n * Thrown on failure.\n *\n * @experimental This API may change in a breaking way in any release, including patch releases.\n */\n depositToPerps(request: DepositToPerpsRequest): Promise<TransactionHandle>;\n\n /**\n * Opens a Perps account session.\n *\n * @remarks\n * Omit `expiresIn` to create new delegated Perps credentials that expire after\n * one week. Pass `expiresIn` as a duration in milliseconds to use a shorter or\n * longer credential lifetime, or pass existing credentials to validate and\n * resume a previous session.\n *\n * @example\n * ```ts\n * const session = await client.openPerpsSession();\n * ```\n *\n * @throws {@link OpenPerpsSessionError}\n * Thrown on failure.\n *\n * @experimental This API may change in a breaking way in any release, including patch releases.\n */\n openPerpsSession(request?: OpenPerpsSessionRequest): Promise<PerpsSession>;\n\n /**\n * Revokes delegated Perps credentials by proxy address.\n *\n * @remarks\n * This can revoke credentials outside the currently open Perps session.\n *\n * @example\n * ```ts\n * await client.revokePerpsCredentials({ proxy: session.credentials.proxy });\n * ```\n *\n * @throws {@link RevokePerpsCredentialsError}\n * Thrown on failure.\n *\n * @experimental This API may change in a breaking way in any release, including patch releases.\n */\n revokePerpsCredentials(request: RevokePerpsCredentialsRequest): Promise<void>;\n\n /**\n * Requests a Perps withdrawal to the authenticated wallet.\n *\n * @example\n * ```ts\n * const withdrawalId = await client.withdrawFromPerps({ amount: 100_000_000n });\n * ```\n *\n * @throws {@link WithdrawFromPerpsError}\n * Thrown on failure.\n *\n * @experimental This API may change in a breaking way in any release, including patch releases.\n */\n withdrawFromPerps(\n request: WithdrawFromPerpsRequest,\n ): Promise<PerpsWithdrawalId>;\n};\n\n/**\n * @experimental This API may change in a breaking way in any release, including patch releases.\n */\nexport type PerpsActions = PublicPerpsActions;\n\n/**\n * @experimental This API may change in a breaking way in any release, including patch releases.\n */\nexport function perpsActions(client: BasePublicClient): PublicPerpsActions;\n/**\n * @experimental This API may change in a breaking way in any release, including patch releases.\n */\nexport function perpsActions(client: BaseSecureClient): SecurePerpsActions;\n/**\n * @experimental This API may change in a breaking way in any release, including patch releases.\n */\nexport function perpsActions(\n client: BaseClient,\n): PublicPerpsActions | SecurePerpsActions {\n const actions: PublicPerpsActions = {\n fetchPerpsBook: (request) => fetchPerpsBook(client, request),\n fetchPerpsFees: () => fetchPerpsFees(client),\n fetchPerpsInstruments: (request) => fetchPerpsInstruments(client, request),\n fetchPerpsTicker: (request) => fetchPerpsTicker(client, request),\n fetchPerpsTickers: (request) => fetchPerpsTickers(client, request),\n listPerpsCandles: (request) => listPerpsCandles(client, request),\n listPerpsFundingHistory: (request) =>\n listPerpsFundingHistory(client, request),\n listPerpsTrades: (request) => listPerpsTrades(client, request),\n };\n\n if (!client.isSecureClient()) return actions;\n\n return {\n ...actions,\n depositToPerps: (request) => depositToPerps(client, request),\n openPerpsSession: (request) => openPerpsSession(client, request),\n revokePerpsCredentials: (request) =>\n revokePerpsCredentials(client, request),\n withdrawFromPerps: (request) => withdrawFromPerps(client, request),\n };\n}\n","import type {\n CurrentReward,\n MarketReward,\n OrdersScoringResponse,\n RewardsPercentages,\n TotalUserEarning,\n UserEarning,\n UserRewardsEarning,\n} from '@polymarket/bindings/clob';\nimport type { Prettify } from '@polymarket/types';\nimport {\n type FetchOrderScoringRequest,\n type FetchOrdersScoringRequest,\n type FetchTotalEarningsForUserForDayRequest,\n fetchOrderScoring,\n fetchOrdersScoring,\n fetchRewardPercentages,\n fetchTotalEarningsForUserForDay,\n type ListCurrentRewardsRequest,\n type ListMarketRewardsRequest,\n type ListUserEarningsAndMarketsConfigRequest,\n type ListUserEarningsForDayRequest,\n listCurrentRewards,\n listMarketRewards,\n listUserEarningsAndMarketsConfig,\n listUserEarningsForDay,\n} from '../actions';\nimport type {\n BaseClient,\n BasePublicClient,\n BaseSecureClient,\n} from '../clients';\nimport type { Paginated } from '../pagination';\n\nexport type PublicRewardsActions = {\n /**\n * Lists current active market rewards.\n *\n * @throws {@link ListCurrentRewardsError}\n * Thrown on failure.\n *\n * @example\n * Fetch the first page of results:\n * ```ts\n * const paginator = client.listCurrentRewards();\n *\n * const firstPage = await paginator.firstPage();\n *\n * // Optionally, fetch additional pages:\n * for await (const page of paginator.from(firstPage.nextCursor)) {\n * // page.items: CurrentReward[]\n * }\n * ```\n *\n * @example\n * Loop through all pages with `for await`:\n * ```ts\n * const paginator = client.listCurrentRewards();\n *\n * for await (const page of paginator) {\n * // page.items: CurrentReward[]\n * }\n * ```\n */\n listCurrentRewards(\n request?: ListCurrentRewardsRequest,\n ): Paginated<CurrentReward[]>;\n /**\n * Lists reward configurations for a market.\n *\n * @throws {@link ListMarketRewardsError}\n * Thrown on failure.\n *\n * @example\n * Fetch the first page of results:\n * ```ts\n * const paginator = client.listMarketRewards({\n * conditionId:\n * '0xbd31dc8a20211944f6b70f31557f1001557b59905b7738480ca09bd4532f84af',\n * });\n *\n * const firstPage = await paginator.firstPage();\n *\n * // Optionally, fetch additional pages:\n * for await (const page of paginator.from(firstPage.nextCursor)) {\n * // page.items: MarketReward[]\n * }\n * ```\n *\n * @example\n * Loop through all pages with `for await`:\n * ```ts\n * const paginator = client.listMarketRewards({\n * conditionId:\n * '0xbd31dc8a20211944f6b70f31557f1001557b59905b7738480ca09bd4532f84af',\n * });\n *\n * for await (const page of paginator) {\n * // page.items: MarketReward[]\n * }\n * ```\n */\n listMarketRewards(\n request: ListMarketRewardsRequest,\n ): Paginated<MarketReward[]>;\n};\n\nexport type SecureRewardsActions = Prettify<\n PublicRewardsActions & {\n /**\n * Fetches whether a single order is currently scoring.\n *\n * @throws {@link FetchOrderScoringError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const scoring = await client.fetchOrderScoring({\n * orderId: '123',\n * });\n * ```\n */\n fetchOrderScoring(request: FetchOrderScoringRequest): Promise<boolean>;\n /**\n * Fetches scoring state for multiple orders.\n *\n * @throws {@link FetchOrdersScoringError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const scoring = await client.fetchOrdersScoring({\n * orderIds: ['1', '2'],\n * });\n * ```\n */\n fetchOrdersScoring(\n request: FetchOrdersScoringRequest,\n ): Promise<OrdersScoringResponse>;\n /**\n * Lists per-market earnings for the authenticated account on a given day.\n *\n * @throws {@link ListUserEarningsForDayError}\n * Thrown on failure.\n *\n * @example\n * Fetch the first page of results:\n * ```ts\n * const paginator = client.listUserEarningsForDay({\n * date: '2026-04-16',\n * });\n *\n * const firstPage = await paginator.firstPage();\n *\n * // Optionally, fetch additional pages:\n * for await (const page of paginator.from(firstPage.nextCursor)) {\n * // page.items: UserEarning[]\n * }\n * ```\n *\n * @example\n * Loop through all pages with `for await`:\n * ```ts\n * const paginator = client.listUserEarningsForDay({\n * date: '2026-04-16',\n * });\n *\n * for await (const page of paginator) {\n * // page.items: UserEarning[]\n * }\n * ```\n */\n listUserEarningsForDay(\n request: ListUserEarningsForDayRequest,\n ): Paginated<UserEarning[]>;\n /**\n * Fetches total earnings for the authenticated account on a given day.\n *\n * @throws {@link FetchTotalEarningsForUserForDayError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const earnings = await client.fetchTotalEarningsForUserForDay({\n * date: '2026-04-16',\n * });\n * ```\n */\n fetchTotalEarningsForUserForDay(\n request: FetchTotalEarningsForUserForDayRequest,\n ): Promise<TotalUserEarning[]>;\n /**\n * Lists market reward configuration and earnings for the authenticated account on a given day.\n *\n * @throws {@link ListUserEarningsAndMarketsConfigError}\n * Thrown on failure.\n *\n * @example\n * Fetch the first page of results:\n * ```ts\n * const paginator = client.listUserEarningsAndMarketsConfig({\n * date: '2026-04-16',\n * });\n *\n * const firstPage = await paginator.firstPage();\n *\n * // Optionally, fetch additional pages:\n * for await (const page of paginator.from(firstPage.nextCursor)) {\n * // page.items: UserRewardsEarning[]\n * }\n * ```\n *\n * @example\n * Loop through all pages with `for await`:\n * ```ts\n * const paginator = client.listUserEarningsAndMarketsConfig({\n * date: '2026-04-16',\n * });\n *\n * for await (const page of paginator) {\n * // page.items: UserRewardsEarning[]\n * }\n * ```\n */\n listUserEarningsAndMarketsConfig(\n request: ListUserEarningsAndMarketsConfigRequest,\n ): Paginated<UserRewardsEarning[]>;\n /**\n * Fetches reward percentages for the authenticated account.\n *\n * @throws {@link FetchRewardPercentagesError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const percentages = await client.fetchRewardPercentages();\n * ```\n */\n fetchRewardPercentages(): Promise<RewardsPercentages>;\n }\n>;\n\nfunction publicRewardsActions(client: BaseClient): PublicRewardsActions {\n return {\n listCurrentRewards: listCurrentRewards.bind(null, client),\n listMarketRewards: listMarketRewards.bind(null, client),\n };\n}\n\nexport function rewardsActions(client: BasePublicClient): PublicRewardsActions;\nexport function rewardsActions(client: BaseSecureClient): SecureRewardsActions;\nexport function rewardsActions(\n client: BaseClient,\n): PublicRewardsActions | SecureRewardsActions {\n const actions = publicRewardsActions(client);\n\n if (client.isPublicClient()) {\n return actions;\n }\n\n return {\n ...actions,\n fetchOrderScoring: fetchOrderScoring.bind(null, client),\n fetchOrdersScoring: fetchOrdersScoring.bind(null, client),\n listUserEarningsForDay: listUserEarningsForDay.bind(null, client),\n fetchTotalEarningsForUserForDay: fetchTotalEarningsForUserForDay.bind(\n null,\n client,\n ),\n listUserEarningsAndMarketsConfig: listUserEarningsAndMarketsConfig.bind(\n null,\n client,\n ),\n fetchRewardPercentages: fetchRewardPercentages.bind(null, client),\n };\n}\n\n// Error unions and runtime `isError` guards for every action bound above.\n// Surfaced at the root entry point through `export * from './decorators'`.\n// Keep this list in sync with the methods on PublicRewardsActions / SecureRewardsActions.\nexport {\n FetchOrderScoringError,\n FetchOrdersScoringError,\n FetchRewardPercentagesError,\n FetchTotalEarningsForUserForDayError,\n ListCurrentRewardsError,\n ListMarketRewardsError,\n ListUserEarningsAndMarketsConfigError,\n ListUserEarningsForDayError,\n} from '../actions';\n","import type {\n AcceptComboQuoteParams,\n AcceptComboQuoteResult,\n RequestComboQuoteParams,\n RequestComboQuoteResult,\n RfqSession,\n WaitForComboFillParams,\n WaitForComboFillResult,\n} from '../actions';\nimport {\n acceptComboQuote,\n openRfqSession,\n requestComboQuote,\n waitForComboFill,\n} from '../actions';\nimport type { BaseSecureClient } from '../clients';\n\nexport type {\n BuilderRfqError,\n ComboQuote,\n FetchRfqStatusParams,\n RfqCancelQuoteAck,\n RfqCancelQuoteRejectedErrorOptions,\n RfqConfirmationAck,\n RfqConfirmationRequest,\n RfqConfirmationRequestEvent,\n RfqErrorCode,\n RfqEvent,\n RfqExecutionUpdate,\n RfqId,\n RfqQuoteId,\n RfqQuoteReference,\n RfqQuoteRejectedErrorOptions,\n RfqQuoteRequest,\n RfqQuoteRequestEvent,\n RfqQuoteResponse,\n RfqQuoteSource,\n RfqRequestedSize,\n RfqRequestorPublicId,\n RfqRequestRejectedErrorOptions,\n RfqSession,\n RfqStatusResult,\n RfqTrade,\n RfqTradeEvent,\n} from '../actions/rfq';\nexport {\n AcceptComboQuoteError,\n ComboAcceptFailureReason,\n ComboQuoteUnavailableReason,\n FetchRfqStatusError,\n OpenRfqSessionError,\n RequestComboQuoteError,\n RfqCancelQuoteError,\n RfqCancelQuoteRejectedError,\n RfqConfirmationDecision,\n RfqConfirmationError,\n RfqConfirmationRejectedError,\n RfqDirection,\n RfqExecutionStatus,\n RfqKnownErrorCode,\n RfqQuoteError,\n RfqQuoteRejectedError,\n RfqRejectionCode,\n RfqRequestedSizeUnit,\n RfqRequestRejectedError,\n RfqSide,\n RfqStatus,\n WaitForComboFillError,\n} from '../actions/rfq';\nexport type {\n AcceptComboQuoteParams,\n AcceptComboQuoteResult,\n RequestComboQuoteParams,\n RequestComboQuoteResult,\n WaitForComboFillParams,\n WaitForComboFillResult,\n};\n\nexport type SecureRfqActions = {\n /**\n * Opens an RFQ event session.\n *\n * @remarks\n * The returned async iterator is a stream, not a worker queue. Await inside the\n * loop to process RFQ events sequentially, or dispatch handlers without awaiting\n * them to fan out handling when quote windows are tight.\n *\n * @example\n * Quote the full requested size:\n * ```ts\n * const session = await client.openRfqSession();\n *\n * for await (const event of session) {\n * switch (event.type) {\n * case 'quote_request':\n * await event.quote({ price: 0.45 });\n * break;\n *\n * case 'execution_update':\n * // event.rfqId: RfqId\n * // event.status: RfqExecutionStatus\n * // event.txHash: TxHash | undefined\n * break;\n * }\n * }\n * ```\n *\n * @example\n * Quote a specific outcome-token size. `0.5` means half of one share, not\n * half of one 6-decimal base unit:\n * ```ts\n * const session = await client.openRfqSession();\n *\n * for await (const event of session) {\n * switch (event.type) {\n * case 'quote_request':\n * await event.quote({ price: 0.45, size: 0.5 });\n * break;\n *\n * // …\n * }\n * }\n * ```\n *\n * @example\n * Cancel a submitted quote using the live session:\n * ```ts\n * const session = await client.openRfqSession();\n *\n * for await (const event of session) {\n * switch (event.type) {\n * case 'quote_request': {\n * const ref = await event.quote({ price: 0.45 });\n *\n * if (shouldCancel(ref)) {\n * await session.cancelQuote(ref);\n * }\n * break;\n * }\n *\n * // …\n * }\n * }\n * ```\n * The cancellation ack means the backend processed the request; it does not\n * guarantee the quote was withdrawn from an already-selected RFQ.\n *\n * @example\n * Handle Last Look confirmation requests:\n * ```ts\n * const session = await client.openRfqSession();\n *\n * for await (const event of session) {\n * switch (event.type) {\n * case 'quote_request':\n * await event.quote({ price: 0.45 });\n * break;\n *\n * case 'confirmation_request':\n * await event.confirm();\n * break;\n *\n * // …\n * }\n * }\n * ```\n * Any maker can quote permissionlessly. Last Look confirmation requests are\n * only sent to makers with Last Look enabled.\n *\n * @example\n * Choose collateral or inventory per request:\n * ```ts\n * const session = await client.openRfqSession();\n *\n * for await (const event of session) {\n * switch (event.type) {\n * case 'quote_request': {\n * switch (event.direction) {\n * case RfqDirection.Buy:\n * await event.quote({\n * price: 0.45,\n * source: chooseSource(event.yesPositionId, event.requestedSize),\n * });\n * break;\n *\n * case RfqDirection.Sell:\n * await event.quote({\n * price: 0.45,\n * source: chooseSource(event.noPositionId, event.requestedSize),\n * });\n * break;\n * }\n * break;\n * }\n *\n * case 'confirmation_request':\n * await event.confirm();\n * break;\n *\n * // …\n * }\n * }\n *\n * function chooseSource(positionId: PositionId, requestedSize: RfqRequestedSize): RfqQuoteSource {\n * return hasInventory(positionId, requestedSize) ? 'inventory' : 'collateral';\n * }\n * ```\n *\n * @throws {@link OpenRfqSessionError}\n * Thrown on failure.\n */\n openRfqSession(): Promise<RfqSession>;\n\n /**\n * Requests a quote for a combo of positions.\n *\n * @remarks\n * Resolves when the quote competition window closes. A request that\n * attracts no usable quotes is a normal outcome, returned as `quote: null`\n * with a reason rather than thrown.\n *\n * A winning quote is self-contained JSON data and may be persisted or\n * routed to another process before acceptance.\n *\n * Requires a Builder API Key in the client configuration, via\n * `builderApiKey(...)` or `remoteBuilderSigning(...)`.\n *\n * @throws {@link RequestComboQuoteError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const result = await client.requestComboQuote({\n * legPositionIds: ['123', '456'],\n * direction: OrderSide.BUY,\n * amount: 100,\n * });\n *\n * if (result.quote !== null) {\n * // result.quote.blendedPrice: DecimalString\n * // result.quote.totalRequired: DecimalString\n * // SELL quotes also carry result.quote.netReceive after fees.\n * // result.quote.expiresAt: EpochMilliseconds\n * }\n * ```\n */\n requestComboQuote(\n params: RequestComboQuoteParams,\n ): Promise<RequestComboQuoteResult>;\n\n /**\n * Accepts a self-contained combo quote, signing the acceptance order for\n * the authenticated account.\n *\n * @remarks\n * Resolves at the maker last-look outcome. A maker declining or the\n * acceptance window expiring is a normal outcome, returned as\n * `status: 'failed'`. `status: 'executing'` means the trade was handed off\n * for onchain execution; follow it with `waitForComboFill`.\n *\n * A transport failure or unrecognized acceptance response is retried once\n * automatically; this is safe because an already-accepted RFQ reports its\n * current status instead of executing twice. After such a retry\n * `takerOrderHash` is absent because the retried order was not the one\n * recorded.\n *\n * The quote is JSON-serializable and may cross process boundaries before\n * acceptance. The accepting client must represent the same account and\n * builder identity used to request it.\n * Treat the quote as signing-sensitive data: preserve its integrity across\n * process boundaries and do not accept fields modified by an untrusted client.\n *\n * @throws {@link AcceptComboQuoteError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const result = await client.requestComboQuote({\n * legPositionIds: ['123', '456'],\n * direction: OrderSide.BUY,\n * amount: 100,\n * });\n *\n * if (result.quote !== null) {\n * const acceptance = await client.acceptComboQuote(result.quote);\n * }\n * ```\n */\n acceptComboQuote(\n params: AcceptComboQuoteParams,\n ): Promise<AcceptComboQuoteResult>;\n\n /**\n * Waits for an accepted RFQ to reach a terminal state.\n *\n * @remarks\n * Polls the RFQ status until it is filled (or confirmed onchain),\n * `FAILED`, `EXPIRED`, or `CANCELED`. Terminal failure is a normal outcome\n * and is returned, not thrown. A `TimeoutError` does not mean the trade\n * failed; resume with the `fetchRfqStatus` action from\n * `@polymarket/client/actions`.\n *\n * @throws {@link WaitForComboFillError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const fill = await client.waitForComboFill({ rfqId });\n *\n * if (fill.status === RfqStatus.Filled) {\n * // fill.txHash: TxHash\n * }\n * ```\n */\n waitForComboFill(\n params: WaitForComboFillParams,\n ): Promise<WaitForComboFillResult>;\n};\n\nexport function rfqActions(client: BaseSecureClient): SecureRfqActions {\n return {\n openRfqSession() {\n return openRfqSession(client);\n },\n requestComboQuote(params: RequestComboQuoteParams) {\n return requestComboQuote(client, params);\n },\n acceptComboQuote(params: AcceptComboQuoteParams) {\n return acceptComboQuote(client, params);\n },\n waitForComboFill(params: WaitForComboFillParams) {\n return waitForComboFill(client, params);\n },\n };\n}\n","import {\n type AuthorizeSessionKeyRequest,\n type AuthorizeSessionKeyResult,\n authorizeSessionKey,\n fetchSessionKeys,\n type RevokeSessionKeyRequest,\n revokeSessionKey,\n type SessionKey,\n} from '../actions';\nimport type { BaseSecureClient } from '../clients';\n\nexport type SessionKeyActions = {\n /**\n * Authorizes an externally managed signer for selected venues.\n *\n * The SDK receives only the public address. The application remains\n * responsible for generating, storing, and protecting the private key.\n * When scopes are omitted, authorization defaults to `ALL`.\n * The authorization expires 180 days after it is created.\n * Requires builder API-key authentication.\n *\n * @remarks\n * Resolves after the submitted transaction is confirmed and the session key\n * appears in the active session-key list.\n *\n * @example\n * ```ts\n * const authorization = await client.authorizeSessionKey({\n * address: sessionAddress,\n * });\n * ```\n *\n * @throws {@link AuthorizeSessionKeyError}\n * Thrown on failure.\n */\n authorizeSessionKey(\n request: AuthorizeSessionKeyRequest,\n ): Promise<AuthorizeSessionKeyResult>;\n\n /**\n * Fetches the active session keys authorized for the Deposit Wallet.\n *\n * @example\n * ```ts\n * const sessionKeys = await client.fetchSessionKeys();\n * ```\n *\n * @throws {@link FetchSessionKeysError}\n * Thrown on failure.\n */\n fetchSessionKeys(): Promise<SessionKey[]>;\n\n /**\n * Revokes a session key authorized for the Deposit Wallet.\n *\n * Returns once the session key is removed from the active-key registry and can\n * no longer be used. The on-chain transaction may still be pending.\n * Requires API-key authentication that supports gasless transactions.\n *\n * @example\n * ```ts\n * await client.revokeSessionKey({\n * address: sessionAddress,\n * });\n * ```\n *\n * @throws {@link RevokeSessionKeyError}\n * Thrown on failure.\n */\n revokeSessionKey(request: RevokeSessionKeyRequest): Promise<void>;\n};\n\nexport function sessionKeyActions(client: BaseSecureClient): SessionKeyActions {\n return {\n authorizeSessionKey: authorizeSessionKey.bind(null, client),\n fetchSessionKeys: fetchSessionKeys.bind(null, client),\n revokeSessionKey: revokeSessionKey.bind(null, client),\n };\n}\n\nexport type {\n AuthorizeSessionKeyRequest,\n AuthorizeSessionKeyResult,\n RevokeSessionKeyRequest,\n SessionKey,\n SessionKeyScope,\n} from '../actions';\nexport {\n AuthorizeSessionKeyError,\n FetchSessionKeysError,\n RevokeSessionKeyError,\n SessionKeyKnownScope,\n} from '../actions';\n","import {\n type EventForSubscriptionSpecs,\n type PublicSubscriptionSpec,\n type SecureSubscriptionSpec,\n type SubscriptionHandle,\n subscribe,\n} from '../actions';\nimport type {\n BaseClient,\n BasePublicClient,\n BaseSecureClient,\n} from '../clients';\n\nexport type {\n CryptoPricesChainlinkTwapEvent,\n CryptoPricesChainlinkTwapSixtyEvent,\n CryptoPricesChainlinkTwapSubscription,\n CryptoPricesChainlinkTwapThirtyEvent,\n CryptoPricesChainlinkTwapWindowSeconds,\n} from '../actions';\nexport { SubscribeError } from '../actions';\n\nexport type PublicSubscriptionsActions = {\n /**\n * Starts one or more realtime subscriptions on this client.\n *\n * @throws {@link SubscribeError}\n * Thrown when subscription input is invalid or a realtime subscription fails.\n *\n * @example\n * ```ts\n * const handle = await client.subscribe([\n * { topic: 'market', assetIds: ['123'] },\n * ]);\n *\n * for await (const event of handle) {\n * // event: StandardMarketEvent\n * }\n * ```\n */\n subscribe<const TSubscriptions extends readonly PublicSubscriptionSpec[]>(\n subscriptions: TSubscriptions,\n ): Promise<SubscriptionHandle<EventForSubscriptionSpecs<TSubscriptions>>>;\n};\n\nexport type SecureSubscriptionsActions = {\n /**\n * Starts one or more realtime subscriptions on this client.\n *\n * @throws {@link SubscribeError}\n * Thrown when subscription input is invalid or a realtime subscription fails.\n *\n * @example\n * ```ts\n * const handle = await client.subscribe([\n * { topic: 'user' },\n * { topic: 'market', assetIds: ['123'] },\n * ]);\n *\n * for await (const event of handle) {\n * // event: StandardMarketEvent | UserEvent\n * }\n * ```\n */\n subscribe<const TSubscriptions extends readonly SecureSubscriptionSpec[]>(\n subscriptions: TSubscriptions,\n ): Promise<SubscriptionHandle<EventForSubscriptionSpecs<TSubscriptions>>>;\n};\n\nexport function subscriptionsActions(\n client: BasePublicClient,\n): PublicSubscriptionsActions;\nexport function subscriptionsActions(\n client: BaseSecureClient,\n): SecureSubscriptionsActions;\nexport function subscriptionsActions(\n client: BaseClient,\n): PublicSubscriptionsActions | SecureSubscriptionsActions {\n // Wrap instead of `bind` so the method preserves its generic type parameter\n // and can narrow the resolved event type per call site.\n if (client.isSecureClient()) {\n return {\n subscribe<const TSubscriptions extends readonly SecureSubscriptionSpec[]>(\n subscriptions: TSubscriptions,\n ): Promise<\n SubscriptionHandle<EventForSubscriptionSpecs<TSubscriptions>>\n > {\n return subscribe(client, subscriptions);\n },\n };\n }\n\n return {\n subscribe<const TSubscriptions extends readonly PublicSubscriptionSpec[]>(\n subscriptions: TSubscriptions,\n ): Promise<SubscriptionHandle<EventForSubscriptionSpecs<TSubscriptions>>> {\n return subscribe(client, subscriptions);\n },\n };\n}\n","import type {\n AcceptedOrderResponse,\n CancelOrdersResponse,\n OpenOrder,\n OrderResponse,\n OrderResponses,\n} from '@polymarket/bindings/clob';\nimport type { TxHash } from '@polymarket/types';\nimport {\n type CancelMarketOrdersRequest,\n type CancelOrderRequest,\n type CancelOrdersRequest,\n cancelAll,\n cancelMarketOrders,\n cancelOrder,\n cancelOrders,\n createLimitOrder,\n createMarketOrder,\n type FetchOrderRequest,\n fetchOrder,\n type ListOpenOrdersRequest,\n listOpenOrders,\n type PostOrdersRequest,\n type PrepareLimitOrderRequest,\n type PrepareMarketOrderRequest,\n placeLimitOrder,\n placeMarketOrder,\n postOrder,\n postOrders,\n type WaitForOrderFillSettlementRequest,\n waitForOrderFillSettlement,\n} from '../actions';\nimport type { SignedOrder } from '../actions/orders';\nimport type { BaseSecureClient } from '../clients';\nimport type { Paginated } from '../pagination';\n\nexport type { OrderSignature, SignedOrder } from '../actions';\n\nexport type SecureTradingActions = {\n /**\n * Creates a signed market order for the authenticated account.\n *\n * @throws {@link CreateMarketOrderError}\n * Thrown on failure.\n *\n * @example Basic market buy\n * ```ts\n * const order = await client.createMarketOrder({\n * assetId: '0x0122…0000',\n * amount: 10,\n * side: OrderSide.BUY,\n * });\n * ```\n *\n * @example Protected market buy\n * ```ts\n * const order = await client.createMarketOrder({\n * assetId: '0x0122…0000',\n * amount: 10,\n * maxPrice: '0.55',\n * side: OrderSide.BUY,\n * });\n * ```\n *\n * @example Polymarket V2 market buy\n * ```ts\n * const order = await client.createMarketOrder({\n * assetId: '0x0122…0000',\n * amount: 10,\n * side: OrderSide.BUY,\n * });\n * ```\n */\n createMarketOrder(request: PrepareMarketOrderRequest): Promise<SignedOrder>;\n /**\n * Creates and posts a market order for the authenticated account.\n *\n * @remarks\n * Settlement happens asynchronously, so a matched response is not\n * guaranteed to carry settlement transaction hashes. Use\n * `waitForOrderFillSettlement` to obtain them reliably.\n *\n * @throws {@link PlaceMarketOrderError}\n * Thrown on failure.\n *\n * @example Basic market buy\n * ```ts\n * const response = await client.placeMarketOrder({\n * assetId: '0x0122…0000',\n * amount: 10,\n * side: OrderSide.BUY,\n * });\n *\n * // response: OrderResponse\n * ```\n *\n * @example Protected market sell\n * ```ts\n * const response = await client.placeMarketOrder({\n * assetId: '0x0122…0000',\n * minPrice: '0.54',\n * shares: 10,\n * side: OrderSide.SELL,\n * });\n *\n * // response: OrderResponse\n * ```\n *\n * @example Market buy followed to settlement\n * ```ts\n * const response = await client.placeMarketOrder({\n * assetId: '0x0122…0000',\n * amount: 10,\n * side: OrderSide.BUY,\n * });\n *\n * if (response.ok) {\n * const hashes = await client.waitForOrderFillSettlement(response);\n * // hashes: TxHash[]\n * }\n * ```\n */\n placeMarketOrder(request: PrepareMarketOrderRequest): Promise<OrderResponse>;\n /**\n * Creates a signed limit order for the authenticated account.\n *\n * @remarks\n * GTD expirations must be at least 3 minutes in the future. Add your own\n * buffer for network latency and clock skew when deriving an expiration from\n * the current time.\n *\n * @throws {@link CreateLimitOrderError}\n * Thrown on failure.\n *\n * @example CTF limit order\n * ```ts\n * const order = await client.createLimitOrder({\n * assetId: '0x0122…0000',\n * postOnly: true,\n * price: 0.52,\n * side: OrderSide.BUY,\n * size: 10,\n * });\n * ```\n *\n * @example Polymarket V2 limit order\n * ```ts\n * const order = await client.createLimitOrder({\n * assetId: '0x0122…0000',\n * postOnly: true,\n * price: 0.52,\n * side: OrderSide.BUY,\n * size: 10,\n * });\n * ```\n */\n createLimitOrder(request: PrepareLimitOrderRequest): Promise<SignedOrder>;\n /**\n * Creates and posts a limit order for the authenticated account.\n *\n * @remarks\n * GTD expirations must be at least 3 minutes in the future. Add your own\n * buffer for network latency and clock skew when deriving an expiration from\n * the current time.\n *\n * @throws {@link PlaceLimitOrderError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const response = await client.placeLimitOrder({\n * assetId: '0x0122…0000',\n * postOnly: true,\n * price: 0.52,\n * side: OrderSide.BUY,\n * size: 10,\n * });\n *\n * // response: OrderResponse\n * ```\n */\n placeLimitOrder(request: PrepareLimitOrderRequest): Promise<OrderResponse>;\n /**\n * Posts a signed order for the authenticated account.\n *\n * @throws {@link PostOrderError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const response = await client.postOrder(signedOrder);\n * ```\n */\n postOrder(order: SignedOrder): Promise<OrderResponse>;\n /**\n * Posts multiple signed orders for the authenticated account.\n *\n * @remarks\n * Accepts between 1 and 15 orders, matching the current service limit.\n *\n * @throws {@link PostOrdersError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const responses = await client.postOrders([firstSignedOrder, secondSignedOrder]);\n * ```\n */\n postOrders(orders: PostOrdersRequest): Promise<OrderResponses>;\n /**\n * Waits until every fill listed in an order response reaches a terminal\n * settlement outcome and returns the settlement transaction hashes.\n *\n * @remarks\n * Settlement covers the fills listed in this order response. These are the\n * fills that happened immediately when the order was accepted. It does not\n * wait for later fills of any remaining quantity resting on the book;\n * subscribe to the `user` channel to follow those.\n *\n * @throws {@link WaitForOrderFillSettlementError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const response = await client.placeMarketOrder({\n * assetId: '0x0122…0000',\n * amount: 10,\n * side: OrderSide.BUY,\n * });\n *\n * if (response.ok) {\n * const hashes = await client.waitForOrderFillSettlement(response);\n * // hashes: TxHash[]\n * }\n * ```\n */\n waitForOrderFillSettlement(\n order: AcceptedOrderResponse,\n request?: WaitForOrderFillSettlementRequest,\n ): Promise<TxHash[]>;\n /**\n * Cancels a single open order for the authenticated account.\n *\n * @throws {@link CancelOrderError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const response = await client.cancelOrder({ orderId: '123' });\n *\n * // response.canceled: OrderId[]\n * ```\n */\n cancelOrder(request: CancelOrderRequest): Promise<CancelOrdersResponse>;\n /**\n * Cancels multiple open orders for the authenticated account.\n *\n * @throws {@link CancelOrdersError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const response = await client.cancelOrders({ orderIds: ['1', '2'] });\n *\n * // response.canceled: OrderId[]\n * ```\n */\n cancelOrders(request: CancelOrdersRequest): Promise<CancelOrdersResponse>;\n /**\n * Cancels all open orders for the authenticated account.\n *\n * @throws {@link CancelAllError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const response = await client.cancelAll();\n *\n * // response.canceled: OrderId[]\n * ```\n */\n cancelAll(): Promise<CancelOrdersResponse>;\n /**\n * Cancels all open orders for the authenticated account that match the market or asset filter.\n *\n * @throws {@link CancelMarketOrdersError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const response = await client.cancelMarketOrders({\n * market: '0x0000000000000000000000000000000000000000000000000000000000000001',\n * });\n *\n * // response.canceled: OrderId[]\n * ```\n */\n cancelMarketOrders(\n request: CancelMarketOrdersRequest,\n ): Promise<CancelOrdersResponse>;\n /**\n * Lists open orders for the authenticated account across all pages.\n *\n * @throws {@link ListOpenOrdersError}\n * Thrown on failure.\n *\n * @example\n * Fetch the first page of results:\n * ```ts\n * const paginator = client.listOpenOrders({\n * market: '0x0000000000000000000000000000000000000000000000000000000000000001',\n * });\n *\n * const firstPage = await paginator.firstPage();\n *\n * // Optionally, fetch additional pages:\n * for await (const page of paginator.from(firstPage.nextCursor)) {\n * // page.items: OpenOrder[]\n * }\n * ```\n *\n * @example\n * Loop through all pages with `for await`:\n * ```ts\n * const paginator = client.listOpenOrders({\n * market: '0x0000000000000000000000000000000000000000000000000000000000000001',\n * });\n *\n * for await (const page of paginator) {\n * // page.items: OpenOrder[]\n * }\n * ```\n */\n listOpenOrders(request?: ListOpenOrdersRequest): Paginated<OpenOrder[]>;\n /**\n * Fetches a single order for the authenticated account.\n *\n * @throws {@link FetchOrderError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const order = await client.fetchOrder({ orderId: '123' });\n * ```\n */\n fetchOrder(request: FetchOrderRequest): Promise<OpenOrder>;\n};\n\nexport function tradingActions(client: BaseSecureClient): SecureTradingActions;\nexport function tradingActions(client: BaseSecureClient): SecureTradingActions {\n return {\n createMarketOrder: createMarketOrder.bind(null, client),\n placeMarketOrder: placeMarketOrder.bind(null, client),\n createLimitOrder: createLimitOrder.bind(null, client),\n placeLimitOrder: placeLimitOrder.bind(null, client),\n postOrder: postOrder(client),\n postOrders: postOrders(client),\n waitForOrderFillSettlement: waitForOrderFillSettlement.bind(null, client),\n cancelOrder: cancelOrder.bind(null, client),\n cancelOrders: cancelOrders.bind(null, client),\n cancelAll: cancelAll.bind(null, client),\n cancelMarketOrders: cancelMarketOrders.bind(null, client),\n listOpenOrders: listOpenOrders.bind(null, client),\n fetchOrder: fetchOrder.bind(null, client),\n };\n}\n\n// Error unions and runtime `isError` guards for every action bound above.\n// Surfaced at the root entry point through `export * from './decorators'`.\n// Keep this list in sync with the methods on SecureTradingActions.\nexport {\n CancelAllError,\n CancelMarketOrdersError,\n CancelOrderError,\n CancelOrdersError,\n CreateLimitOrderError,\n CreateMarketOrderError,\n FetchOrderError,\n ListOpenOrdersError,\n PlaceLimitOrderError,\n PlaceMarketOrderError,\n PostOrderError,\n PostOrdersError,\n WaitForOrderFillSettlementError,\n} from '../actions';\n","import {\n approveErc20,\n approveErc1155ForAll,\n type CollateralReturnPlanResponse,\n type ExecuteCollateralReturnPlanRequest,\n executeCollateralReturnPlan,\n type FetchTradingApprovalsStateRequest,\n fetchTradingApprovalsState,\n mergePositions,\n type PrepareErc20ApprovalRequest,\n type PrepareErc20TransferRequest,\n type PrepareErc1155ApprovalForAllRequest,\n type PrepareMergePositionsRequest,\n type PrepareRedeemPositionsRequest,\n type PrepareSplitPositionRequest,\n planCollateralReturn,\n redeemPositions,\n setupTradingApprovals,\n splitPosition,\n type TradingApprovalsState,\n transferErc20,\n} from '../actions';\nimport type {\n BaseClient,\n BasePublicClient,\n BaseSecureClient,\n} from '../clients';\nimport type { TransactionHandle } from '../types';\n\nexport type PublicWalletActions = {\n /**\n * Reads the approvals a wallet is missing for supported trading workflows.\n *\n * This method only reads on-chain state. It does not require a signer or\n * submit transactions.\n *\n * @throws {@link FetchTradingApprovalsStateError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const state = await client.fetchTradingApprovalsState({\n * user: '0x1234…',\n * });\n * ```\n */\n fetchTradingApprovalsState(\n request: FetchTradingApprovalsStateRequest,\n ): Promise<TradingApprovalsState>;\n};\n\nexport type SecureWalletActions = {\n /**\n * Reads the approvals a wallet is missing for supported trading workflows.\n *\n * This method reads the authenticated account's wallet state. It only reads\n * on-chain state and does not submit transactions.\n *\n * @throws {@link FetchTradingApprovalsStateError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const state = await client.fetchTradingApprovalsState();\n * ```\n */\n fetchTradingApprovalsState(): Promise<TradingApprovalsState>;\n /**\n * Sets up the approvals required for trading and supported position lifecycle workflows.\n *\n * @throws {@link SetupTradingApprovalsError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * await client.setupTradingApprovals();\n * ```\n */\n setupTradingApprovals(): Promise<void>;\n /**\n * Approves ERC-20 token spending for the authenticated account.\n *\n * @throws {@link ApproveErc20Error}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const handle = await client.approveErc20({\n * amount: 'max',\n * spenderAddress: '0x1234…',\n * tokenAddress: '0x5678…',\n * });\n *\n * const outcome = await handle.wait();\n *\n * // outcome.transactionHash: TxHash\n * ```\n */\n approveErc20(\n request: PrepareErc20ApprovalRequest,\n ): Promise<TransactionHandle>;\n /**\n * Approves or revokes ERC-1155 operator access for the authenticated account.\n *\n * @throws {@link ApproveErc1155ForAllError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const handle = await client.approveErc1155ForAll({\n * operatorAddress: '0x1234…',\n * tokenAddress: '0x5678…',\n * });\n *\n * const outcome = await handle.wait();\n *\n * // outcome.transactionHash: TxHash\n * ```\n */\n approveErc1155ForAll(\n request: PrepareErc1155ApprovalForAllRequest,\n ): Promise<TransactionHandle>;\n /**\n * Transfers ERC-20 tokens from the authenticated account.\n *\n * @throws {@link TransferErc20Error}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const handle = await client.transferErc20({\n * amount: 1n,\n * recipientAddress: client.account.signer,\n * tokenAddress: client.environment.contracts.collateralToken,\n * });\n *\n * const outcome = await handle.wait();\n *\n * // outcome.transactionHash: TxHash\n * ```\n */\n transferErc20(\n request: PrepareErc20TransferRequest,\n ): Promise<TransactionHandle>;\n /**\n * Splits collateral into positions.\n *\n * @throws {@link SplitPositionError}\n * Thrown on failure.\n *\n * @example Split a market by condition ID.\n * ```ts\n * const handle = await client.splitPosition({\n * amount: 1n,\n * conditionId: '0x123…',\n * });\n *\n * const outcome = await handle.wait();\n *\n * // outcome.transactionHash: TxHash\n * ```\n *\n * @example Split a combo by legs.\n * ```ts\n * const handle = await client.splitPosition({\n * amount: 1n,\n * legs: ['123', '456'],\n * });\n *\n * const outcome = await handle.wait();\n *\n * // outcome.transactionHash: TxHash\n * ```\n */\n splitPosition(\n request: PrepareSplitPositionRequest,\n ): Promise<TransactionHandle>;\n /**\n * Merges complementary positions back into collateral.\n *\n * @throws {@link MergePositionsError}\n * Thrown on failure.\n *\n * @example Merge a market by condition ID.\n * ```ts\n * const handle = await client.mergePositions({\n * amount: 'max',\n * conditionId: '0x123…',\n * });\n *\n * const outcome = await handle.wait();\n *\n * // outcome.transactionHash: TxHash\n * ```\n *\n * @example Merge a combo by legs.\n * ```ts\n * const handle = await client.mergePositions({\n * amount: 'max',\n * legs: ['123', '456'],\n * });\n *\n * const outcome = await handle.wait();\n *\n * // outcome.transactionHash: TxHash\n * ```\n */\n mergePositions(\n request: PrepareMergePositionsRequest,\n ): Promise<TransactionHandle>;\n /**\n * Redeems held positions for a market or a specific position by ID.\n *\n * @throws {@link RedeemPositionsError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * // Redeem a market by condition ID.\n * const handle = await client.redeemPositions({\n * conditionId: '0x123…',\n * });\n *\n * const outcome = await handle.wait();\n *\n * // outcome.transactionHash: TxHash\n * ```\n *\n * @example Redeem a market by market ID.\n * ```ts\n * const handle = await client.redeemPositions({\n * marketId: '12345',\n * });\n *\n * const outcome = await handle.wait();\n *\n * // outcome.transactionHash: TxHash\n * ```\n *\n * @example Redeem a Polymarket V2 position by position ID.\n * ```ts\n * const handle = await client.redeemPositions({\n * positionId: '123',\n * });\n *\n * const outcome = await handle.wait();\n *\n * // outcome.transactionHash: TxHash\n * ```\n */\n redeemPositions(\n request: PrepareRedeemPositionsRequest,\n ): Promise<TransactionHandle>;\n /**\n * Plans a collateral return for the authenticated account.\n *\n * The returned plan is an inspectable artifact: review the collateral it\n * releases, the inputs it consumes, and the residual-position impact, and\n * apply any application-specific limits before executing it with\n * {@link SecureWalletActions.executeCollateralReturnPlan | executeCollateralReturnPlan}.\n * A truncated plan is one executable chunk of a larger return; execute and\n * confirm it before requesting the next plan.\n *\n * @throws {@link PlanCollateralReturnError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * let plan: CollateralReturnPlanResponse;\n *\n * do {\n * plan = await client.planCollateralReturn();\n *\n * // Inspect the return and residual-position impact, and apply any\n * // application-specific limits before signing.\n * const handle = await client.executeCollateralReturnPlan({ plan });\n * await handle.wait();\n * } while (plan.truncated);\n * ```\n */\n planCollateralReturn(): Promise<CollateralReturnPlanResponse>;\n /**\n * Executes a collateral return plan for the authenticated account.\n *\n * Execution signs and submits the exact call carried by the plan; nothing is\n * recomputed on the client, and no approval transactions are run implicitly.\n * Confirmation stays explicit through the returned handle's `wait()`.\n *\n * If wallet state changed since the plan was created, the service rejects\n * the submission; request a fresh plan and execute that instead.\n *\n * @throws {@link ExecuteCollateralReturnPlanError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const plan = await client.planCollateralReturn();\n *\n * const handle = await client.executeCollateralReturnPlan({ plan });\n * const outcome = await handle.wait();\n *\n * // outcome.transactionHash: TxHash\n * ```\n */\n executeCollateralReturnPlan(\n request: ExecuteCollateralReturnPlanRequest,\n ): Promise<TransactionHandle>;\n};\n\nfunction publicWalletActions(client: BaseClient): PublicWalletActions {\n return {\n fetchTradingApprovalsState: fetchTradingApprovalsState.bind(null, client),\n };\n}\n\nexport function walletActions(client: BasePublicClient): PublicWalletActions;\nexport function walletActions(client: BaseSecureClient): SecureWalletActions;\nexport function walletActions(\n client: BaseClient,\n): PublicWalletActions | SecureWalletActions {\n const actions = publicWalletActions(client);\n\n if (client.isPublicClient()) {\n return actions;\n }\n\n return {\n ...actions,\n fetchTradingApprovalsState: () =>\n fetchTradingApprovalsState(client, { user: client.account.wallet }),\n setupTradingApprovals: setupTradingApprovals.bind(null, client),\n approveErc20: approveErc20.bind(null, client),\n approveErc1155ForAll: approveErc1155ForAll.bind(null, client),\n transferErc20: transferErc20.bind(null, client),\n splitPosition: splitPosition.bind(null, client),\n mergePositions: mergePositions.bind(null, client),\n redeemPositions: redeemPositions.bind(null, client),\n planCollateralReturn: planCollateralReturn.bind(null, client),\n executeCollateralReturnPlan: executeCollateralReturnPlan.bind(null, client),\n };\n}\n\n// Public collateral-return model types surfaced alongside the bound methods.\nexport type {\n CollateralReturnOperation,\n CollateralReturnOperationKind,\n CollateralReturnPlanResponse,\n CollateralReturnPositionAmount,\n CollateralReturnPositionSummary,\n CollateralReturnRouterCall,\n Erc20TradingApproval,\n Erc1155TradingApproval,\n ExecuteCollateralReturnPlanRequest,\n FetchTradingApprovalsStateRequest,\n TradingApprovalRequirements,\n TradingApprovalsState,\n} from '../actions';\n// Error unions and runtime `isError` guards for every action bound above.\n// Surfaced at the root entry point through `export * from './decorators'`.\n// Keep this list in sync with the methods on SecureWalletActions.\nexport {\n ApproveErc20Error,\n ApproveErc1155ForAllError,\n CollateralReturnKnownOperationKind,\n ExecuteCollateralReturnPlanError,\n FetchTradingApprovalsStateError,\n MergePositionsError,\n PlanCollateralReturnError,\n RedeemPositionsError,\n SetupTradingApprovalsError,\n SplitPositionError,\n TransferErc20Error,\n} from '../actions';\n","import type { Prettify } from '@polymarket/types';\nimport type {\n BaseClient,\n BasePublicClient,\n BaseSecureClient,\n} from '../clients';\nimport {\n accountActions,\n type PublicAccountActions,\n type SecureAccountActions,\n} from './account';\nimport { type AnalyticsActions, analyticsActions } from './analytics';\nimport { type DataActions, dataActions } from './data';\nimport { type DiscoveryActions, discoveryActions } from './discovery';\nimport {\n type PublicPerpsActions,\n perpsActions,\n type SecurePerpsActions,\n} from './perps';\nimport {\n type PublicRewardsActions,\n rewardsActions,\n type SecureRewardsActions,\n} from './rewards';\nimport { rfqActions, type SecureRfqActions } from './rfq';\nimport { type SessionKeyActions, sessionKeyActions } from './session-keys';\nimport {\n type PublicSubscriptionsActions,\n type SecureSubscriptionsActions,\n subscriptionsActions,\n} from './subscriptions';\nimport { type SecureTradingActions, tradingActions } from './trading';\nimport {\n type PublicWalletActions,\n type SecureWalletActions,\n walletActions,\n} from './wallet';\n\nexport type PublicActions = Prettify<\n DiscoveryActions &\n DataActions &\n AnalyticsActions &\n PublicPerpsActions &\n PublicAccountActions &\n PublicRewardsActions &\n PublicSubscriptionsActions &\n PublicWalletActions\n>;\n\nexport type SecureActions = Prettify<\n DiscoveryActions &\n DataActions &\n AnalyticsActions &\n SecurePerpsActions &\n SecureAccountActions &\n SecureRewardsActions &\n SecureRfqActions &\n SessionKeyActions &\n SecureSubscriptionsActions &\n SecureWalletActions &\n SecureTradingActions\n>;\n\nexport function allActions(client: BasePublicClient): PublicActions;\nexport function allActions(client: BaseSecureClient): SecureActions;\nexport function allActions(client: BaseClient): PublicActions | SecureActions {\n if (client.isSecureClient()) {\n return {\n ...accountActions(client),\n ...analyticsActions(client),\n ...dataActions(client),\n ...discoveryActions(client),\n ...perpsActions(client),\n ...rewardsActions(client),\n ...rfqActions(client),\n ...sessionKeyActions(client),\n ...subscriptionsActions(client),\n ...tradingActions(client),\n ...walletActions(client),\n };\n }\n\n return {\n ...accountActions(client),\n ...analyticsActions(client),\n ...dataActions(client),\n ...discoveryActions(client),\n ...perpsActions(client),\n ...rewardsActions(client),\n ...subscriptionsActions(client),\n ...walletActions(client),\n };\n}\n\nexport * from './account';\nexport * from './analytics';\nexport * from './data';\nexport * from './discovery';\nexport * from './perps';\nexport * from './rewards';\nexport * from './rfq';\nexport * from './session-keys';\nexport * from './subscriptions';\nexport * from './trading';\nexport * from './wallet';\n","import { type EvmAddress, expectEvmAddress } from '@polymarket/types';\nimport type { Hex } from 'ox';\n\nexport type WalletDerivationConfig = {\n depositWalletFactory: EvmAddress;\n depositWalletBeacon: EvmAddress;\n depositWalletImplementation: EvmAddress;\n proxyFactory: EvmAddress;\n proxyImplementation: EvmAddress;\n safeFactory: EvmAddress;\n safeInitCodeHash: Hex.Hex;\n};\n\nexport type RestEndpoint = {\n rest: string;\n headers?: Record<string, string>;\n};\n\nexport type WebSocketEndpoint = {\n ws: string;\n headers?: Record<string, string>;\n};\n\nexport type ClobEndpoints = RestEndpoint & {\n market: WebSocketEndpoint;\n user: WebSocketEndpoint;\n};\n\nexport type CombosEndpoints = RestEndpoint &\n WebSocketEndpoint & {\n builderGateway: RestEndpoint;\n collateralReturn: RestEndpoint;\n };\n\n/**\n * @experimental This API may change in a breaking way in any release, including patch releases.\n */\nexport type PerpsEndpoints = RestEndpoint & WebSocketEndpoint;\n\nexport type EnvironmentContracts = {\n collateralToken: EvmAddress;\n conditionalTokens: EvmAddress;\n negRiskAdapter: EvmAddress;\n collateralAdapter: EvmAddress;\n negRiskCollateralAdapter: EvmAddress;\n standardExchange: EvmAddress;\n negRiskExchange: EvmAddress;\n exchangeV3: EvmAddress;\n protocolV2Router: EvmAddress;\n binaryModule: EvmAddress;\n negRiskModule: EvmAddress;\n combinatorialModule: EvmAddress;\n positionManager: EvmAddress;\n autoRedeemOperator: EvmAddress;\n safeMultisend: EvmAddress;\n relayHub: EvmAddress;\n perpsDepositContract: EvmAddress;\n};\n\nexport type EnvironmentConfig = {\n name: string;\n chainId: number;\n /** @internal */\n rpc: string;\n /** @internal */\n walletDerivation: WalletDerivationConfig;\n /** @internal */\n contracts: EnvironmentContracts;\n /** @internal */\n clob: ClobEndpoints;\n /** @internal */\n relayer: RestEndpoint;\n /** @internal */\n gamma: RestEndpoint;\n /** @internal */\n data: RestEndpoint;\n /** @internal */\n combos: CombosEndpoints;\n /** @internal */\n perps: PerpsEndpoints;\n /** @internal */\n rtds: WebSocketEndpoint;\n /** @internal */\n sports: WebSocketEndpoint;\n /** @internal */\n relayerMaxPolls: number;\n /** @internal */\n relayerPollFrequencyMs: number;\n};\n\ntype EnvironmentConfigForkEndpoint = Partial<RestEndpoint & WebSocketEndpoint>;\n\nexport type EnvironmentConfigFork = {\n name: string;\n chainId?: number;\n rpc?: string;\n walletDerivation?: Partial<WalletDerivationConfig>;\n contracts?: Partial<EnvironmentContracts>;\n clob?: Partial<RestEndpoint> & {\n market?: Partial<WebSocketEndpoint>;\n user?: Partial<WebSocketEndpoint>;\n };\n relayer?: Partial<RestEndpoint>;\n gamma?: Partial<RestEndpoint>;\n data?: Partial<RestEndpoint>;\n combos?: EnvironmentConfigForkEndpoint & {\n builderGateway?: Partial<RestEndpoint>;\n collateralReturn?: Partial<RestEndpoint>;\n };\n perps?: EnvironmentConfigForkEndpoint;\n rtds?: Partial<WebSocketEndpoint>;\n sports?: Partial<WebSocketEndpoint>;\n relayerMaxPolls?: number;\n relayerPollFrequencyMs?: number;\n};\n\n/**\n * The production environment configuration.\n */\nexport const production: EnvironmentConfig = {\n name: 'production',\n chainId: 137,\n rpc: 'https://polygon.drpc.org',\n walletDerivation: {\n depositWalletFactory: expectEvmAddress(\n '0x00000000000Fb5C9ADea0298D729A0CB3823Cc07',\n ),\n depositWalletBeacon: expectEvmAddress(\n '0x7A18EDfe055488A3128f01F563e5B479D92ffc3a',\n ),\n depositWalletImplementation: expectEvmAddress(\n '0x58CA52ebe0DadfdF531Cde7062e76746de4Db1eB',\n ),\n proxyFactory: expectEvmAddress(\n '0xaB45c5A4B0c941a2F231C04C3f49182e1A254052',\n ),\n proxyImplementation: expectEvmAddress(\n '0x44e999d5c2F66Ef0861317f9A4805AC2e90aEB4f',\n ),\n safeFactory: expectEvmAddress('0xaacFeEa03eb1561C4e67d661e40682Bd20E3541b'),\n safeInitCodeHash:\n '0x2bce2127ff07fb632d16c8347c4ebf501f4841168bed00d9e6ef715ddb6fcecf',\n },\n contracts: {\n collateralToken: expectEvmAddress(\n '0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB',\n ),\n conditionalTokens: expectEvmAddress(\n '0x4D97DCd97eC945f40cF65F87097ACe5EA0476045',\n ),\n negRiskAdapter: expectEvmAddress(\n '0xd91E80cF2E7be2e162c6513ceD06f1dD0dA35296',\n ),\n collateralAdapter: expectEvmAddress(\n '0xAdA100Db00Ca00073811820692005400218FcE1f',\n ),\n negRiskCollateralAdapter: expectEvmAddress(\n '0xadA2005600Dec949baf300f4C6120000bDB6eAab',\n ),\n standardExchange: expectEvmAddress(\n '0xE111180000d2663C0091e4f400237545B87B996B',\n ),\n negRiskExchange: expectEvmAddress(\n '0xe2222d279d744050d28e00520010520000310F59',\n ),\n exchangeV3: expectEvmAddress('0xe3333700cA9d93003F00f0F71f8515005F6c00Aa'),\n protocolV2Router: expectEvmAddress(\n '0x12121212006e4CD160D18e3f00711DA5c3372600',\n ),\n binaryModule: expectEvmAddress(\n '0x1000008dD9001B968442c1000017eaE6E0dA00Ba',\n ),\n negRiskModule: expectEvmAddress(\n '0x200000900045e3B6259600682756002200028933',\n ),\n combinatorialModule: expectEvmAddress(\n '0x30000034706c7d8e12009dab006be20000c031a8',\n ),\n positionManager: expectEvmAddress(\n '0x006F54F7f9A22e0000CC2AB60031000000ae9fEF',\n ),\n autoRedeemOperator: expectEvmAddress(\n '0xa1200000d0002264C9a1698e001292D00E1b00af',\n ),\n safeMultisend: expectEvmAddress(\n '0xA238CBeb142c10Ef7Ad8442C6D1f9E89e07e7761',\n ),\n relayHub: expectEvmAddress('0xD216153c06E857cD7f72665E0aF1d7D82172F494'),\n perpsDepositContract: expectEvmAddress(\n '0xDCa4af75705dbB50f62437045afF9921947917d2',\n ),\n },\n clob: {\n rest: 'https://clob.polymarket.com',\n market: { ws: 'wss://ws-subscriptions-clob.polymarket.com/ws/market' },\n user: { ws: 'wss://ws-subscriptions-clob.polymarket.com/ws/user' },\n },\n relayer: { rest: 'https://relayer-v2.polymarket.com' },\n gamma: { rest: 'https://gamma-api.polymarket.com' },\n data: { rest: 'https://data-api.polymarket.com' },\n combos: {\n rest: 'https://combos-rfq-api.polymarket.com',\n ws: 'wss://combos-rfq-gateway-quoter.polymarket.com/ws/rfq',\n builderGateway: {\n rest: 'https://combos-rfq-gateway-builder.polymarket.com',\n },\n collateralReturn: {\n rest: 'https://combos-rfq-collateral-return.polymarket.com',\n },\n },\n perps: {\n rest: 'https://api.perpetuals.polymarket.com',\n ws: 'wss://ws.perpetuals.polymarket.com/v1/ws',\n },\n rtds: { ws: 'wss://ws-live-data.polymarket.com' },\n sports: { ws: 'wss://sports-api.polymarket.com/ws' },\n relayerMaxPolls: 100,\n relayerPollFrequencyMs: 2000,\n};\n\n/**\n * Forks an environment config from production unless a different base is passed.\n *\n * @experimental This helper is intended for advanced custom environment use,\n * not general SDK usage. Its signature may change without notice.\n */\nexport function forkEnvironmentConfig(\n fork: EnvironmentConfigFork,\n base: EnvironmentConfig = production,\n): EnvironmentConfig {\n return {\n ...base,\n ...fork,\n walletDerivation: {\n ...base.walletDerivation,\n ...fork.walletDerivation,\n },\n contracts: {\n ...base.contracts,\n ...fork.contracts,\n },\n clob: {\n ...forkRestEndpoint(base.clob, fork.clob),\n market: forkWebSocketEndpoint(base.clob.market, fork.clob?.market),\n user: forkWebSocketEndpoint(base.clob.user, fork.clob?.user),\n },\n relayer: forkRestEndpoint(base.relayer, fork.relayer),\n gamma: forkRestEndpoint(base.gamma, fork.gamma),\n data: forkRestEndpoint(base.data, fork.data),\n combos: {\n ...forkRestWebSocketEndpoint(base.combos, fork.combos),\n builderGateway: forkRestEndpoint(\n base.combos.builderGateway,\n fork.combos?.builderGateway,\n ),\n collateralReturn: forkRestEndpoint(\n base.combos.collateralReturn,\n fork.combos?.collateralReturn,\n ),\n },\n perps: forkRestWebSocketEndpoint(base.perps, fork.perps),\n rtds: forkWebSocketEndpoint(base.rtds, fork.rtds),\n sports: forkWebSocketEndpoint(base.sports, fork.sports),\n };\n}\n\nfunction forkRestEndpoint(\n base: RestEndpoint,\n fork: Partial<RestEndpoint> | undefined,\n): RestEndpoint {\n return {\n ...base,\n ...fork,\n headers: forkHeaders(base.headers, fork?.headers),\n };\n}\n\nfunction forkWebSocketEndpoint(\n base: WebSocketEndpoint,\n fork: Partial<WebSocketEndpoint> | undefined,\n): WebSocketEndpoint {\n return {\n ...base,\n ...fork,\n headers: forkHeaders(base.headers, fork?.headers),\n };\n}\n\nfunction forkRestWebSocketEndpoint<\n TEndpoint extends RestEndpoint & WebSocketEndpoint,\n>(base: TEndpoint, fork: EnvironmentConfigForkEndpoint | undefined): TEndpoint {\n return {\n ...base,\n ...fork,\n headers: forkHeaders(base.headers, fork?.headers),\n };\n}\n\nfunction forkHeaders(\n base: Record<string, string> | undefined,\n fork: Record<string, string> | undefined,\n): Record<string, string> | undefined {\n if (base === undefined && fork === undefined) return undefined;\n return { ...base, ...fork };\n}\n\n/** @internal */\nexport const preproduction = forkEnvironmentConfig({\n name: 'preproduction',\n clob: { rest: 'https://clob-preprod-int-v2.polymarket.com' },\n data: { rest: 'https://data-api-preprod-int.polymarket.com' },\n gamma: { rest: 'https://gamma-api-preprod-int.polymarket.com' },\n relayer: { rest: 'https://relayer-v2-preprod-int.polymarket.com' },\n});\n","/**\n * Builds the canonical HMAC signature for authenticated requests.\n *\n * The signed payload is the raw string concatenation of `timestamp`, `method`,\n * `requestPath`, and, when present, the serialized request `body`, matching the\n * remote signing contract.\n *\n * The `secret` is expected to be base64-encoded and is decoded before signing.\n * The returned signature is base64url-encoded with padding preserved.\n *\n * @example\n * Server-side signing example for builder-authenticated requests:\n *\n * ```ts\n * async function handleSignRequest(request: Request): Promise<Response> {\n * const { body, method, path } = await request.json();\n *\n * const timestamp = Math.floor(Date.now() / 1000);\n * const signature = await buildHmacSignature(\n * process.env.POLY_BUILDER_SECRET!,\n * timestamp,\n * method,\n * path,\n * body,\n * );\n *\n * return Response.json({\n * POLY_BUILDER_API_KEY: process.env.POLY_BUILDER_API_KEY!,\n * POLY_BUILDER_PASSPHRASE: process.env.POLY_BUILDER_PASSPHRASE!,\n * POLY_BUILDER_SIGNATURE: signature,\n * POLY_BUILDER_TIMESTAMP: `${timestamp}`,\n * });\n * }\n * ```\n */\nexport async function buildHmacSignature(\n secret: string,\n timestamp: number,\n method: string,\n requestPath: string,\n body?: string,\n): Promise<string> {\n let message = `${timestamp}${method}${requestPath}`;\n\n if (body !== undefined) {\n message += body;\n }\n\n const cryptoKey = await globalThis.crypto.subtle.importKey(\n 'raw',\n base64ToArrayBuffer(secret),\n { name: 'HMAC', hash: 'SHA-256' },\n false,\n ['sign'],\n );\n const signature = await globalThis.crypto.subtle.sign(\n 'HMAC',\n cryptoKey,\n new TextEncoder().encode(message),\n );\n\n return toUrlSafeBase64(arrayBufferToBase64(signature));\n}\n\nfunction base64ToArrayBuffer(base64: string): ArrayBuffer {\n const sanitizedBase64 = base64\n .replace(/-/g, '+')\n .replace(/_/g, '/')\n .replace(/[^A-Za-z0-9+/=]/g, '');\n const binaryString = atob(sanitizedBase64);\n const bytes = new Uint8Array(binaryString.length);\n\n for (let index = 0; index < binaryString.length; index += 1) {\n bytes[index] = binaryString.charCodeAt(index);\n }\n\n return bytes.buffer;\n}\n\nfunction arrayBufferToBase64(buffer: ArrayBuffer): string {\n const bytes = new Uint8Array(buffer);\n let binary = '';\n\n for (const byte of bytes) {\n binary += String.fromCharCode(byte);\n }\n\n return btoa(binary);\n}\n\nfunction toUrlSafeBase64(value: string): string {\n return value.replace(/\\+/g, '-').replace(/\\//g, '_');\n}\n","import type { Pushable } from 'it-pushable';\nimport type { SubscriptionHandle } from '../actions/subscriptions';\n\nexport function createSubscriptionHandle<TEvent>(\n queue: Pushable<TEvent>,\n closeSubscription: () => Promise<void>,\n): SubscriptionHandle<TEvent> {\n let closing: Promise<void> | undefined;\n\n return {\n close: () => {\n if (closing === undefined) {\n closing = Promise.resolve(queue.return()).then(() =>\n closeSubscription(),\n );\n }\n return closing;\n },\n [Symbol.asyncIterator]() {\n return queue[Symbol.asyncIterator]();\n },\n };\n}\n","import { type Pushable, pushable } from 'it-pushable';\n\nexport type SubscriptionRegistrySubscriber<TEvent> = {\n matches?: (event: TEvent) => boolean;\n queue: Pushable<TEvent>;\n};\n\nexport type SubscriptionRegistryEntry<TSubscription, TEvent> = {\n subscription: TSubscription;\n subscriber: SubscriptionRegistrySubscriber<TEvent>;\n};\n\nexport type SubscriptionRegistryChange<TState> = {\n before: TState;\n after: TState;\n};\n\nexport type SubscriptionRegistryAddOptions<TEvent> = {\n matches?: (event: TEvent) => boolean;\n};\n\nexport type SubscriptionRegistryAddResult<TSubscription, TEvent, TState> = {\n change: SubscriptionRegistryChange<TState>;\n entry: SubscriptionRegistryEntry<TSubscription, TEvent>;\n};\n\ntype DeriveServerState<TSubscription, TEvent, TState> = (\n entries: Iterable<SubscriptionRegistryEntry<TSubscription, TEvent>>,\n) => TState;\n\nexport type SubscriptionRegistryOptions<TSubscription, TEvent, TState> = {\n deriveServerState: DeriveServerState<TSubscription, TEvent, TState>;\n};\n\nexport class SubscriptionRegistry<\n TSubscription,\n TEvent,\n TServerState = undefined,\n> {\n readonly #entries = new Set<\n SubscriptionRegistryEntry<TSubscription, TEvent>\n >();\n readonly #deriveServerState: DeriveServerState<\n TSubscription,\n TEvent,\n TServerState\n >;\n\n constructor(\n options?: SubscriptionRegistryOptions<TSubscription, TEvent, TServerState>,\n ) {\n this.#deriveServerState =\n options?.deriveServerState ?? (() => undefined as TServerState);\n }\n\n add(\n subscription: TSubscription,\n options: SubscriptionRegistryAddOptions<TEvent> = {},\n ): SubscriptionRegistryAddResult<TSubscription, TEvent, TServerState> {\n const subscriber: SubscriptionRegistrySubscriber<TEvent> = {\n queue: pushable<TEvent>({ objectMode: true }),\n };\n if (options.matches !== undefined) {\n subscriber.matches = options.matches;\n }\n const entry: SubscriptionRegistryEntry<TSubscription, TEvent> = {\n subscription,\n subscriber,\n };\n return { change: this.#addEntry(entry), entry };\n }\n\n #addEntry(\n entry: SubscriptionRegistryEntry<TSubscription, TEvent>,\n ): SubscriptionRegistryChange<TServerState> {\n const before = this.serverState();\n this.#entries.add(entry);\n return { before, after: this.serverState() };\n }\n\n remove(\n entry: SubscriptionRegistryEntry<TSubscription, TEvent>,\n ): SubscriptionRegistryChange<TServerState> {\n const before = this.serverState();\n this.#entries.delete(entry);\n entry.subscriber.queue.end();\n return { before, after: this.serverState() };\n }\n\n dispatch(event: TEvent): void {\n for (const { subscriber } of this.#entries) {\n if (subscriber.matches === undefined || subscriber.matches(event)) {\n subscriber.queue.push(event);\n }\n }\n }\n\n hasActiveSubscriptions(): boolean {\n return this.#entries.size > 0;\n }\n\n endAll(error?: Error): void {\n for (const { subscriber } of this.#entries) {\n subscriber.queue.end(error);\n }\n this.#entries.clear();\n }\n\n serverState(): TServerState {\n return this.#deriveServerState(this.#entries);\n }\n}\n","import type { ApiKeyCreds } from '@polymarket/bindings/clob';\nimport type {\n MarketEvent,\n UserEvent,\n} from '@polymarket/bindings/subscriptions';\nimport type {\n MarketSubscription,\n UserSubscription,\n} from '../../actions/subscriptions';\nimport type { SubscriptionRegistryEntry } from '../registry';\n\nexport type SendWebSocketMessage = (message: unknown) => void;\n\nexport type MarketSubscriptionEntry = SubscriptionRegistryEntry<\n MarketSubscription,\n MarketEvent\n>;\n\nexport type MarketServerSubscription = {\n assetsIds: string[];\n customFeatureEnabled: boolean;\n};\n\nexport type UserSubscriptionEntry = SubscriptionRegistryEntry<\n UserSubscription,\n UserEvent\n>;\n\nexport type UserServerSubscription = {\n includeAllMarkets: boolean;\n markets: string[];\n};\n\nexport function syncMarketSubscription(\n send: SendWebSocketMessage,\n before: MarketServerSubscription,\n after: MarketServerSubscription,\n): void {\n const addedAssets = difference(after.assetsIds, before.assetsIds);\n const removedAssets = difference(before.assetsIds, after.assetsIds);\n\n if (addedAssets.length > 0) {\n send(buildMarketSubscribeUpdate(addedAssets, after.customFeatureEnabled));\n }\n const firstActiveAsset = after.assetsIds[0];\n if (\n addedAssets.length === 0 &&\n before.customFeatureEnabled !== after.customFeatureEnabled &&\n firstActiveAsset !== undefined\n ) {\n // CLOB applies `custom_feature_enabled` before rejecting duplicate assets as\n // \"NO NEW ASSETS\", so this toggles connection-level custom events in place.\n send(\n buildMarketSubscribeUpdate(\n [firstActiveAsset],\n after.customFeatureEnabled,\n ),\n );\n }\n if (removedAssets.length > 0) {\n send(buildMarketUnsubscribeUpdate(removedAssets));\n }\n}\n\nexport function syncUserSubscription(\n send: SendWebSocketMessage,\n before: UserServerSubscription,\n after: UserServerSubscription,\n): void {\n if (after.includeAllMarkets) {\n if (!before.includeAllMarkets && before.markets.length > 0) {\n send(buildUserUnsubscribeUpdate(before.markets));\n }\n return;\n }\n\n if (before.includeAllMarkets) {\n if (after.markets.length > 0) {\n send(buildUserSubscribeUpdate(after.markets));\n }\n return;\n }\n\n const addedMarkets = difference(after.markets, before.markets);\n const removedMarkets = difference(before.markets, after.markets);\n\n if (addedMarkets.length > 0) {\n send(buildUserSubscribeUpdate(addedMarkets));\n }\n if (removedMarkets.length > 0) {\n send(buildUserUnsubscribeUpdate(removedMarkets));\n }\n}\n\nexport function deriveMarketServerSubscription(\n entries: Iterable<MarketSubscriptionEntry>,\n): MarketServerSubscription {\n const assets = new Set<string>();\n let customFeatureEnabled = false;\n for (const { subscription } of entries) {\n for (const assetId of subscription.assetIds ?? subscription.tokenIds) {\n assets.add(assetId);\n }\n customFeatureEnabled ||= subscription.customFeatureEnabled === true;\n }\n return { assetsIds: Array.from(assets), customFeatureEnabled };\n}\n\nexport function deriveUserServerSubscription(\n entries: Iterable<UserSubscriptionEntry>,\n): UserServerSubscription {\n let includeAllMarkets = false;\n const markets = new Set<string>();\n for (const { subscription } of entries) {\n if (isAllMarketsUserSubscription(subscription)) {\n includeAllMarkets = true;\n continue;\n }\n for (const market of subscription.markets ?? []) markets.add(market);\n }\n return {\n includeAllMarkets,\n markets: includeAllMarkets ? [] : Array.from(markets),\n };\n}\n\nexport function buildMarketSubscribeMessage(\n subscription: MarketServerSubscription,\n): unknown {\n return {\n assets_ids: subscription.assetsIds,\n custom_feature_enabled: subscription.customFeatureEnabled,\n type: 'market',\n };\n}\n\nfunction buildMarketSubscribeUpdate(\n assetsIds: readonly string[],\n customFeatureEnabled: boolean,\n): unknown {\n return {\n assets_ids: assetsIds,\n custom_feature_enabled: customFeatureEnabled,\n operation: 'subscribe',\n };\n}\n\nfunction buildMarketUnsubscribeUpdate(assetsIds: readonly string[]): unknown {\n return {\n assets_ids: assetsIds,\n operation: 'unsubscribe',\n };\n}\n\nexport function buildUserSubscribeMessage(\n subscription: UserServerSubscription,\n credentials: ApiKeyCreds,\n): unknown {\n const message: {\n auth: { apiKey: string; passphrase: string; secret: string };\n markets?: string[];\n type: 'user';\n } = {\n auth: {\n apiKey: credentials.key,\n passphrase: credentials.passphrase,\n secret: credentials.secret,\n },\n type: 'user',\n };\n if (!subscription.includeAllMarkets) {\n message.markets = subscription.markets;\n }\n return message;\n}\n\nfunction buildUserSubscribeUpdate(markets: readonly string[]): unknown {\n return {\n markets,\n operation: 'subscribe',\n };\n}\n\nfunction buildUserUnsubscribeUpdate(markets: readonly string[]): unknown {\n return {\n markets,\n operation: 'unsubscribe',\n };\n}\n\nexport function marketMatcherFor(\n subscription: MarketSubscription,\n): (event: MarketEvent) => boolean {\n const assetIds = subscription.assetIds ?? subscription.tokenIds;\n return (event) => {\n switch (event.type) {\n case 'price_change':\n return event.payload.priceChanges.some((change) =>\n assetIds.includes(change.assetId),\n );\n case 'new_market':\n return subscription.customFeatureEnabled === true;\n case 'market_resolved':\n return (\n subscription.customFeatureEnabled === true &&\n (event.payload.assetIds ?? []).some((assetId) =>\n assetIds.includes(assetId),\n )\n );\n case 'best_bid_ask':\n return (\n subscription.customFeatureEnabled === true &&\n assetIds.includes(event.payload.assetId)\n );\n default:\n return assetIds.includes(event.payload.assetId);\n }\n };\n}\n\nexport function userMatcherFor(\n subscription: UserSubscription,\n): (event: UserEvent) => boolean {\n if (isAllMarketsUserSubscription(subscription)) {\n return () => true;\n }\n\n const markets = new Set(\n (subscription.markets ?? []).map((market) => market.toLowerCase()),\n );\n return (event) => markets.has(event.payload.market.toLowerCase());\n}\n\nfunction isAllMarketsUserSubscription(subscription: UserSubscription): boolean {\n return (subscription.markets?.length ?? 0) === 0;\n}\n\nfunction difference(\n left: readonly string[],\n right: readonly string[],\n): string[] {\n const rightSet = new Set(right);\n return left.filter((value) => !rightSet.has(value));\n}\n","import {\n type MarketEvent,\n MarketEventSchema,\n} from '@polymarket/bindings/subscriptions';\nimport type {\n MarketSubscription,\n SubscriptionHandle,\n} from '../../actions/subscriptions';\nimport { createSubscriptionHandle } from '../handle';\nimport { ClobWebSocketHeartbeat } from '../heartbeat';\nimport {\n ReconnectScheduler,\n WebSocketConnection,\n type WebSocketConnectionResult,\n} from '../lifecycle';\nimport {\n SubscriptionRegistry,\n type SubscriptionRegistryChange,\n} from '../registry';\nimport type { WebSocketSubscriptionManager } from '../types';\nimport {\n buildMarketSubscribeMessage,\n deriveMarketServerSubscription,\n type MarketServerSubscription,\n type MarketSubscriptionEntry,\n marketMatcherFor,\n syncMarketSubscription,\n} from './protocol';\n\nexport type ClobMarketWebSocketManagerOptions = {\n headers?: Record<string, string>;\n url: string;\n};\n\n/**\n * CLOB market WebSocket manager.\n *\n * The CLOB server tracks market subscriptions by asset id on the connection.\n * Incremental subscribe/unsubscribe frames mutate that server-side asset set.\n */\nexport class ClobMarketWebSocketManager\n implements WebSocketSubscriptionManager<MarketSubscription, MarketEvent>\n{\n readonly #headers: Record<string, string> | undefined;\n readonly #url: string;\n #closing: Promise<void> | undefined;\n readonly #connection = new WebSocketConnection({\n heartbeat: new ClobWebSocketHeartbeat(),\n });\n readonly #reconnectScheduler = new ReconnectScheduler();\n readonly #subscriptions = new SubscriptionRegistry<\n MarketSubscription,\n MarketEvent,\n MarketServerSubscription\n >({ deriveServerState: deriveMarketServerSubscription });\n\n constructor(options: ClobMarketWebSocketManagerOptions) {\n this.#headers = options.headers;\n this.#url = options.url;\n }\n\n async subscribe(\n subscription: MarketSubscription,\n ): Promise<SubscriptionHandle<MarketEvent>> {\n const { change, entry } = this.#subscriptions.add(subscription, {\n matches: marketMatcherFor(subscription),\n });\n\n await this.#registerSubscriber(entry, change);\n return createSubscriptionHandle(entry.subscriber.queue, () =>\n this.#closeSubscriber(entry),\n );\n }\n\n async #registerSubscriber(\n entry: MarketSubscriptionEntry,\n change: SubscriptionRegistryChange<MarketServerSubscription>,\n ): Promise<void> {\n const { before, after } = change;\n\n try {\n const connection = await this.#connect();\n if (connection.reusedOpenSocket) {\n syncMarketSubscription(\n (message) => this.#connection.send(message),\n before,\n after,\n );\n }\n } catch (error) {\n await this.#closeSubscriber(entry);\n throw error;\n }\n }\n\n async #closeSubscriber(entry: MarketSubscriptionEntry): Promise<void> {\n const { before, after } = this.#subscriptions.remove(entry);\n\n if (!this.#subscriptions.hasActiveSubscriptions()) {\n await this.close();\n return;\n }\n\n syncMarketSubscription(\n (message) => this.#connection.send(message),\n before,\n after,\n );\n }\n\n async close(): Promise<void> {\n if (this.#closing === undefined) {\n this.#closing = this.#shutdown().finally(() => {\n this.#closing = undefined;\n });\n }\n await this.#closing;\n }\n\n async #shutdown(): Promise<void> {\n this.#reconnectScheduler.stop();\n this.#subscriptions.endAll();\n\n await this.#connection.close();\n }\n\n #connect(): Promise<WebSocketConnectionResult> {\n return this.#connection.connect({\n onConnectionLost: () => this.#onConnectionLost(),\n onError: () => this.#onConnectionError(),\n onMessage: (message) => this.#onConnectionMessage(message),\n onOpen: () => this.#onConnectionOpen(),\n headers: this.#headers,\n url: this.#url,\n });\n }\n\n #onConnectionOpen(): void {\n this.#reconnectScheduler.resetBackoff();\n this.#sendInitialSubscription();\n }\n\n #onConnectionMessage(message: unknown): void {\n const events = Array.isArray(message) ? message : [message];\n for (const eventData of events) {\n const parsed = MarketEventSchema.safeParse(eventData);\n if (!parsed.success) continue;\n this.#subscriptions.dispatch(parsed.data);\n }\n }\n\n #onConnectionLost(): void {\n if (this.#subscriptions.hasActiveSubscriptions()) {\n this.#scheduleReconnect();\n }\n }\n\n #onConnectionError(): void {\n // Browser WebSockets report most failures as an error followed by close.\n // Keep iterators alive here so the close path can reconnect active handles.\n }\n\n #sendInitialSubscription(): void {\n this.#connection.send(\n buildMarketSubscribeMessage(this.#subscriptions.serverState()),\n );\n }\n\n #scheduleReconnect(): void {\n this.#reconnectScheduler.schedule({\n reconnect: () => this.#connect(),\n shouldReconnect: () => this.#subscriptions.hasActiveSubscriptions(),\n });\n }\n}\n","import type { ApiKeyCreds } from '@polymarket/bindings/clob';\nimport {\n type UserEvent,\n UserEventSchema,\n} from '@polymarket/bindings/subscriptions';\nimport type {\n SubscriptionHandle,\n UserSubscription,\n} from '../../actions/subscriptions';\nimport { createSubscriptionHandle } from '../handle';\nimport { ClobWebSocketHeartbeat } from '../heartbeat';\nimport {\n ReconnectScheduler,\n WebSocketConnection,\n type WebSocketConnectionResult,\n} from '../lifecycle';\nimport {\n SubscriptionRegistry,\n type SubscriptionRegistryChange,\n} from '../registry';\nimport type { WebSocketSubscriptionManager } from '../types';\nimport {\n buildUserSubscribeMessage,\n deriveUserServerSubscription,\n syncUserSubscription,\n type UserServerSubscription,\n type UserSubscriptionEntry,\n userMatcherFor,\n} from './protocol';\n\nexport type ClobUserWebSocketManagerOptions = {\n credentials: ApiKeyCreds;\n headers?: Record<string, string>;\n url: string;\n};\n\nexport class ClobUserWebSocketManager\n implements WebSocketSubscriptionManager<UserSubscription, UserEvent>\n{\n readonly #credentials: ApiKeyCreds;\n readonly #headers: Record<string, string> | undefined;\n readonly #url: string;\n #closing: Promise<void> | undefined;\n readonly #connection = new WebSocketConnection({\n heartbeat: new ClobWebSocketHeartbeat(),\n });\n readonly #reconnectScheduler = new ReconnectScheduler();\n readonly #subscriptions = new SubscriptionRegistry<\n UserSubscription,\n UserEvent,\n UserServerSubscription\n >({ deriveServerState: deriveUserServerSubscription });\n\n constructor(options: ClobUserWebSocketManagerOptions) {\n this.#credentials = options.credentials;\n this.#headers = options.headers;\n this.#url = options.url;\n }\n\n async subscribe(\n subscription: UserSubscription,\n ): Promise<SubscriptionHandle<UserEvent>> {\n const { change, entry } = this.#subscriptions.add(subscription, {\n matches: userMatcherFor(subscription),\n });\n\n await this.#registerSubscriber(entry, change);\n return createSubscriptionHandle(entry.subscriber.queue, () =>\n this.#closeSubscriber(entry),\n );\n }\n\n async #registerSubscriber(\n entry: UserSubscriptionEntry,\n change: SubscriptionRegistryChange<UserServerSubscription>,\n ): Promise<void> {\n const { before, after } = change;\n\n try {\n const connection = await this.#connect();\n if (connection.reusedOpenSocket) {\n syncUserSubscription(\n (message) => this.#connection.send(message),\n before,\n after,\n );\n }\n } catch (error) {\n await this.#closeSubscriber(entry);\n throw error;\n }\n }\n\n async #closeSubscriber(entry: UserSubscriptionEntry): Promise<void> {\n const { before, after } = this.#subscriptions.remove(entry);\n\n if (!this.#subscriptions.hasActiveSubscriptions()) {\n await this.close();\n return;\n }\n\n syncUserSubscription(\n (message) => this.#connection.send(message),\n before,\n after,\n );\n }\n\n async close(): Promise<void> {\n if (this.#closing === undefined) {\n this.#closing = this.#shutdown().finally(() => {\n this.#closing = undefined;\n });\n }\n await this.#closing;\n }\n\n async #shutdown(): Promise<void> {\n this.#reconnectScheduler.stop();\n this.#subscriptions.endAll();\n\n await this.#connection.close();\n }\n\n #connect(): Promise<WebSocketConnectionResult> {\n return this.#connection.connect({\n onConnectionLost: () => this.#onConnectionLost(),\n onError: () => this.#onConnectionError(),\n onMessage: (message) => this.#onConnectionMessage(message),\n onOpen: (credentials) => this.#onConnectionOpen(credentials),\n prepare: () => this.#credentials,\n headers: this.#headers,\n url: this.#url,\n });\n }\n\n #onConnectionOpen(credentials: ApiKeyCreds): void {\n this.#reconnectScheduler.resetBackoff();\n this.#sendInitialSubscription(credentials);\n }\n\n #onConnectionMessage(message: unknown): void {\n const events = Array.isArray(message) ? message : [message];\n for (const eventData of events) {\n const parsed = UserEventSchema.safeParse(eventData);\n if (!parsed.success) continue;\n this.#subscriptions.dispatch(parsed.data);\n }\n }\n\n #onConnectionLost(): void {\n if (this.#subscriptions.hasActiveSubscriptions()) {\n this.#scheduleReconnect();\n }\n }\n\n #onConnectionError(): void {\n // Browser WebSockets report most failures as an error followed by close.\n // Keep iterators alive here so the close path can reconnect active handles.\n }\n\n #sendInitialSubscription(credentials: ApiKeyCreds): void {\n this.#connection.send(\n buildUserSubscribeMessage(this.#subscriptions.serverState(), credentials),\n );\n }\n\n #scheduleReconnect(): void {\n this.#reconnectScheduler.schedule({\n reconnect: () => this.#connect(),\n shouldReconnect: () => this.#subscriptions.hasActiveSubscriptions(),\n });\n }\n}\n","import type { PerpsCredentials } from '@polymarket/bindings/perps';\nimport { TransportError } from '../../errors';\nimport { PerpsSession } from './session';\n\n/**\n * @experimental This API may change in a breaking way in any release, including patch releases.\n */\nexport type PerpsSessionManagerOptions = {\n chainId: number;\n headers?: Record<string, string>;\n restUrl: string;\n wsUrl: string;\n};\n\n/**\n * @experimental This API may change in a breaking way in any release, including patch releases.\n */\nexport class PerpsSessionManager {\n readonly #chainId: number;\n readonly #headers: Record<string, string> | undefined;\n readonly #restUrl: string;\n readonly #wsUrl: string;\n readonly #sessions = new Set<PerpsSession>();\n readonly #connectingSessions = new Set<PerpsSession>();\n readonly #connecting = new Set<Promise<PerpsSession>>();\n #hasShutdown = false;\n\n /**\n * @experimental This API may change in a breaking way in any release, including patch releases.\n */\n constructor(options: PerpsSessionManagerOptions) {\n this.#chainId = options.chainId;\n this.#headers = options.headers;\n this.#restUrl = options.restUrl;\n this.#wsUrl = options.wsUrl;\n }\n\n /**\n * @experimental This API may change in a breaking way in any release, including patch releases.\n */\n connect(credentials: PerpsCredentials): Promise<PerpsSession> {\n if (this.#hasShutdown) {\n return Promise.reject(\n new TransportError('Perps session manager has been shut down.'),\n );\n }\n\n const session = new PerpsSession({\n chainId: this.#chainId,\n credentials,\n headers: this.#headers,\n onClose: (closedSession) => this.#clearSession(closedSession),\n restUrl: this.#restUrl,\n wsUrl: this.#wsUrl,\n });\n this.#connectingSessions.add(session);\n\n let connecting!: Promise<PerpsSession>;\n connecting = (async () => {\n try {\n await session.connect();\n if (this.#hasShutdown) {\n await session.close();\n throw new TransportError('Perps session manager has been shut down.');\n }\n this.#sessions.add(session);\n return session;\n } catch (error) {\n await session.close();\n throw error;\n } finally {\n this.#connecting.delete(connecting);\n this.#connectingSessions.delete(session);\n }\n })();\n\n this.#connecting.add(connecting);\n return connecting;\n }\n\n /**\n * @experimental This API may change in a breaking way in any release, including patch releases.\n */\n async shutdown(): Promise<void> {\n this.#hasShutdown = true;\n const sessions = Array.from(this.#sessions);\n const connectingSessions = Array.from(this.#connectingSessions);\n const connecting = Array.from(this.#connecting);\n\n this.#sessions.clear();\n this.#connectingSessions.clear();\n this.#connecting.clear();\n\n await Promise.allSettled([\n ...sessions.map((session) => session.close()),\n ...connectingSessions.map((session) => session.close()),\n ...connecting.map((promise) => promise.catch(() => undefined)),\n ]).then(() => undefined);\n }\n\n #clearSession(session: PerpsSession): void {\n this.#sessions.delete(session);\n this.#connectingSessions.delete(session);\n }\n}\n","import {\n type PerpsMarketDataEvent,\n PerpsMarketDataEventSchema,\n} from '@polymarket/bindings/subscriptions';\nimport { invariant } from '@polymarket/types';\nimport type {\n PerpsMarketDataSubscription,\n SubscriptionHandle,\n} from '../../actions/subscriptions';\nimport { createSubscriptionHandle } from '../handle';\nimport { PerpsWebSocketHeartbeat } from '../heartbeat';\nimport {\n ReconnectScheduler,\n WebSocketConnection,\n type WebSocketConnectionResult,\n} from '../lifecycle';\nimport {\n SubscriptionRegistry,\n type SubscriptionRegistryChange,\n type SubscriptionRegistryEntry,\n} from '../registry';\nimport type { WebSocketSubscriptionManager } from '../types';\n\ntype PerpsSubscriptionEntry = SubscriptionRegistryEntry<\n PerpsMarketDataSubscription,\n PerpsMarketDataEvent\n>;\n\ntype PerpsSubscriptionServerState = Set<string>;\n\n/**\n * @experimental This API may change in a breaking way in any release, including patch releases.\n */\nexport type PerpsSubscriptionManagerOptions = {\n headers?: Record<string, string>;\n url: string;\n};\n\n/**\n * Perps public subscription WebSocket manager.\n *\n * The Perps server tracks subscriptions by channel string. This manager keeps\n * SDK-level topic specs separate from upstream channel names and resubscribes\n * active channels after reconnects.\n *\n * @experimental This API may change in a breaking way in any release, including patch releases.\n */\nexport class PerpsSubscriptionManager\n implements\n WebSocketSubscriptionManager<\n PerpsMarketDataSubscription,\n PerpsMarketDataEvent\n >\n{\n readonly #headers: Record<string, string> | undefined;\n readonly #url: string;\n #closing: Promise<void> | undefined;\n #nextRequestId = 1;\n readonly #connection = new WebSocketConnection({\n heartbeat: new PerpsWebSocketHeartbeat(),\n });\n readonly #reconnectScheduler = new ReconnectScheduler();\n readonly #subscriptions = new SubscriptionRegistry<\n PerpsMarketDataSubscription,\n PerpsMarketDataEvent,\n PerpsSubscriptionServerState\n >({ deriveServerState: derivePerpsSubscriptionServerState });\n\n /**\n * @experimental This API may change in a breaking way in any release, including patch releases.\n */\n constructor(options: PerpsSubscriptionManagerOptions) {\n this.#headers = options.headers;\n this.#url = options.url;\n }\n\n /**\n * @experimental This API may change in a breaking way in any release, including patch releases.\n */\n async subscribe(\n subscription: PerpsMarketDataSubscription,\n ): Promise<SubscriptionHandle<PerpsMarketDataEvent>> {\n const { change, entry } = this.#subscriptions.add(subscription, {\n matches: matcherFor(subscription),\n });\n await this.#registerSubscriber(entry, change);\n return createSubscriptionHandle(entry.subscriber.queue, () =>\n this.#closeSubscriber(entry),\n );\n }\n\n async #registerSubscriber(\n entry: PerpsSubscriptionEntry,\n change: SubscriptionRegistryChange<PerpsSubscriptionServerState>,\n ): Promise<void> {\n try {\n const connection = await this.#connect();\n if (connection.reusedOpenSocket) {\n this.#sendSubscribeFrame(channelsAdded(change.before, change.after));\n this.#sendUnsubscribeFrame(\n channelsRemoved(change.before, change.after),\n );\n }\n } catch (error) {\n await this.#closeSubscriber(entry);\n throw error;\n }\n }\n\n async #closeSubscriber(entry: PerpsSubscriptionEntry): Promise<void> {\n const { before, after } = this.#subscriptions.remove(entry);\n this.#sendSubscribeFrame(channelsAdded(before, after));\n this.#sendUnsubscribeFrame(channelsRemoved(before, after));\n if (!this.#subscriptions.hasActiveSubscriptions()) {\n await this.close();\n }\n }\n\n /**\n * @experimental This API may change in a breaking way in any release, including patch releases.\n */\n async close(): Promise<void> {\n if (this.#closing === undefined) {\n this.#closing = this.#shutdown().finally(() => {\n this.#closing = undefined;\n });\n }\n await this.#closing;\n }\n\n async #shutdown(): Promise<void> {\n this.#reconnectScheduler.stop();\n this.#subscriptions.endAll();\n\n await this.#connection.close();\n }\n\n #connect(): Promise<WebSocketConnectionResult> {\n return this.#connection.connect({\n onConnectionLost: () => this.#onConnectionLost(),\n onError: () => this.#onConnectionError(),\n onMessage: (message) => this.#onConnectionMessage(message),\n onOpen: () => this.#onConnectionOpen(),\n headers: this.#headers,\n url: this.#url,\n });\n }\n\n #onConnectionOpen(): void {\n this.#reconnectScheduler.resetBackoff();\n this.#sendSubscribeFrame(Array.from(this.#subscriptions.serverState()));\n }\n\n #onConnectionMessage(message: unknown): void {\n const parsed = PerpsMarketDataEventSchema.safeParse(message);\n if (!parsed.success) return;\n this.#subscriptions.dispatch(parsed.data);\n }\n\n #onConnectionLost(): void {\n if (this.#subscriptions.hasActiveSubscriptions()) {\n this.#scheduleReconnect();\n }\n }\n\n #onConnectionError(): void {\n // Browser WebSockets report most failures as an error followed by close.\n // Keep iterators alive here so the close path can reconnect active handles.\n }\n\n #sendSubscribeFrame(channels: readonly string[]): void {\n if (channels.length === 0) return;\n this.#connection.send(this.#buildChannelFrame('sub', channels));\n }\n\n #sendUnsubscribeFrame(channels: readonly string[]): void {\n if (channels.length === 0) return;\n this.#connection.send(this.#buildChannelFrame('unsub', channels));\n }\n\n #buildChannelFrame(req: 'sub' | 'unsub', channels: readonly string[]) {\n return {\n id: this.#nextRequestId++,\n req,\n chs: channels,\n };\n }\n\n #scheduleReconnect(): void {\n this.#reconnectScheduler.schedule({\n reconnect: () => this.#connect(),\n shouldReconnect: () => this.#subscriptions.hasActiveSubscriptions(),\n });\n }\n}\n\nfunction derivePerpsSubscriptionServerState(\n entries: Iterable<PerpsSubscriptionEntry>,\n): PerpsSubscriptionServerState {\n const channels = new Set<string>();\n const tickerInstrumentIds = new Set<number>();\n const statisticInstrumentIds = new Set<number>();\n let subscribeAllTickers = false;\n let subscribeAllStatistics = false;\n\n for (const { subscription } of entries) {\n switch (subscription.topic) {\n case 'perps.tickers':\n if (subscription.instrumentId === undefined) {\n subscribeAllTickers = true;\n } else {\n tickerInstrumentIds.add(subscription.instrumentId);\n }\n break;\n case 'perps.statistics':\n if (subscription.instrumentId === undefined) {\n subscribeAllStatistics = true;\n } else {\n statisticInstrumentIds.add(subscription.instrumentId);\n }\n break;\n default:\n channels.add(channelFor(subscription));\n }\n }\n\n if (subscribeAllTickers) {\n channels.add('tickers::all');\n } else {\n for (const instrumentId of tickerInstrumentIds) {\n channels.add(`tickers::${instrumentId}`);\n }\n }\n\n if (subscribeAllStatistics) {\n channels.add('statistics::all');\n } else {\n for (const instrumentId of statisticInstrumentIds) {\n channels.add(`statistics::${instrumentId}`);\n }\n }\n\n return channels;\n}\n\nfunction channelsAdded(\n before: ReadonlySet<string>,\n after: ReadonlySet<string>,\n): string[] {\n return Array.from(after).filter((channel) => !before.has(channel));\n}\n\nfunction channelsRemoved(\n before: ReadonlySet<string>,\n after: ReadonlySet<string>,\n): string[] {\n return Array.from(before).filter((channel) => !after.has(channel));\n}\n\nfunction channelFor(subscription: PerpsMarketDataSubscription): string {\n switch (subscription.topic) {\n case 'perps.trades':\n return `trades::${subscription.instrumentId}`;\n case 'perps.bbo':\n return `bbo::${subscription.instrumentId}`;\n case 'perps.book':\n return `book::${subscription.instrumentId}`;\n case 'perps.candles':\n return `klines::${subscription.instrumentId}::${subscription.interval}`;\n case 'perps.tickers':\n return subscription.instrumentId === undefined\n ? 'tickers::all'\n : `tickers::${subscription.instrumentId}`;\n case 'perps.statistics':\n return subscription.instrumentId === undefined\n ? 'statistics::all'\n : `statistics::${subscription.instrumentId}`;\n default: {\n const neverSpec: never = subscription;\n invariant(false, `Unknown Perps topic: ${String(neverSpec)}`);\n }\n }\n}\n\nfunction matcherFor(\n subscription: PerpsMarketDataSubscription,\n): (event: PerpsMarketDataEvent) => boolean {\n switch (subscription.topic) {\n case 'perps.trades':\n return (event) =>\n event.topic === 'perps.trades' &&\n event.channel === `trades::${subscription.instrumentId}`;\n case 'perps.bbo':\n case 'perps.book':\n return (event) =>\n event.topic === subscription.topic &&\n event.payload.instrumentId === subscription.instrumentId;\n case 'perps.candles':\n return (event) =>\n event.topic === 'perps.candles' &&\n event.payload.instrumentId === subscription.instrumentId &&\n event.payload.interval === subscription.interval;\n case 'perps.tickers':\n case 'perps.statistics':\n return (event) =>\n event.topic === subscription.topic &&\n (subscription.instrumentId === undefined ||\n event.payload.instrumentId === subscription.instrumentId);\n default: {\n const neverSpec: never = subscription;\n invariant(false, `Unknown Perps topic: ${String(neverSpec)}`);\n }\n }\n}\n","import {\n type RfqConfirmationAck as BindingRfqConfirmationAck,\n type RfqQuoteAck as BindingRfqQuoteAck,\n type RfqQuoteCancelAck as BindingRfqQuoteCancelAck,\n RfqConfirmationDecision,\n type RfqConfirmationRequest,\n type RfqExecutionUpdate,\n type RfqId,\n type RfqQuoteId,\n type RfqQuoteRequest,\n type RfqTrade,\n} from '@polymarket/bindings/combos';\nimport type {\n RfqCancelQuoteAck,\n RfqConfirmationAck,\n RfqConfirmationRequestEvent,\n RfqExecutionUpdateEvent,\n RfqQuoteReference,\n RfqQuoteRequestEvent,\n RfqQuoteResponse,\n RfqTradeEvent,\n} from '../../actions/rfq';\n\nexport interface RfqEventController {\n quote(\n request: RfqQuoteRequest,\n response: RfqQuoteResponse,\n ): Promise<RfqQuoteReference>;\n respondToConfirmation(\n rfqId: RfqId,\n quoteId: RfqQuoteId,\n decision: RfqConfirmationDecision,\n ): Promise<RfqConfirmationAck>;\n}\n\nexport function toQuoteRequestEvent(\n controller: RfqEventController,\n message: RfqQuoteRequest,\n): RfqQuoteRequestEvent {\n return {\n ...message,\n quote: (request) => controller.quote(message, request),\n };\n}\n\nexport function toConfirmationRequestEvent(\n controller: RfqEventController,\n message: RfqConfirmationRequest,\n): RfqConfirmationRequestEvent {\n const rfqId = message.rfqId;\n const quoteId = message.quoteId;\n return {\n ...message,\n confirm: () =>\n controller.respondToConfirmation(\n rfqId,\n quoteId,\n RfqConfirmationDecision.Confirm,\n ),\n decline: () =>\n controller.respondToConfirmation(\n rfqId,\n quoteId,\n RfqConfirmationDecision.Decline,\n ),\n };\n}\n\nexport function toExecutionUpdateEvent(\n message: RfqExecutionUpdate,\n): RfqExecutionUpdateEvent {\n return message;\n}\n\nexport function toTradeEvent(message: RfqTrade): RfqTradeEvent {\n return message;\n}\n\nexport function toQuoteAck(message: BindingRfqQuoteAck): RfqQuoteReference {\n return {\n quoteId: message.quoteId,\n rfqId: message.rfqId,\n };\n}\n\nexport function toQuoteCancelAck(\n message: BindingRfqQuoteCancelAck,\n): RfqCancelQuoteAck {\n return {\n quoteId: message.quoteId,\n rfqId: message.rfqId,\n };\n}\n\nexport function toConfirmationAck(\n message: BindingRfqConfirmationAck,\n): RfqConfirmationAck {\n return {\n quoteId: message.quoteId,\n rfqId: message.rfqId,\n };\n}\n","import type { ApiKeyCreds } from '@polymarket/bindings/clob';\nimport type {\n RfqAuthMessage,\n RfqConfirmationDecision,\n RfqConfirmationResponseMessage,\n RfqId,\n RfqQuoteCancelMessage,\n RfqQuoteId,\n RfqQuoteMessage,\n RfqQuoteRequest,\n} from '@polymarket/bindings/combos';\nimport type { AccountIdentity } from '../../wallet';\nimport { resolveOrderIdentity } from '../../wallet';\nimport type { RfqQuote } from './quote';\n\nexport function createAuthMessage(\n account: AccountIdentity,\n credentials: ApiKeyCreds,\n): RfqAuthMessage {\n const identity = resolveOrderIdentity(account);\n\n return {\n auth: {\n apiKey: credentials.key,\n passphrase: credentials.passphrase,\n secret: credentials.secret,\n },\n identity: {\n maker_address: identity.maker,\n signature_type: identity.signatureType,\n signer_address: identity.signer,\n },\n type: 'auth',\n };\n}\n\nexport function createQuoteMessage(\n request: RfqQuoteRequest,\n quote: RfqQuote,\n): RfqQuoteMessage {\n return {\n price_e6: quote.price.toString(),\n rfq_id: request.rfqId,\n signed_order: quote.signedOrder,\n size_e6: quote.size.toString(),\n type: 'RFQ_QUOTE',\n };\n}\n\nexport function createQuoteCancelMessage(\n account: AccountIdentity,\n rfqId: RfqId,\n quoteId: RfqQuoteId,\n): RfqQuoteCancelMessage {\n const identity = resolveOrderIdentity(account);\n\n return {\n maker_address: identity.maker,\n quote_id: quoteId,\n rfq_id: rfqId,\n signer_address: identity.signer,\n type: 'RFQ_QUOTE_CANCEL',\n };\n}\n\nexport function createConfirmationResponseMessage(\n rfqId: RfqId,\n quoteId: RfqQuoteId,\n decision: RfqConfirmationDecision,\n): RfqConfirmationResponseMessage {\n return {\n decision,\n quote_id: quoteId,\n rfq_id: rfqId,\n type: 'RFQ_CONFIRMATION_RESPONSE',\n };\n}\n","import { setNonBlockingTimeout } from '@polymarket/types';\nimport { TimeoutError } from '../../errors';\n\ntype PendingResponse<T> = {\n promise: Promise<T>;\n reject(error: Error): void;\n resolve(value: T): void;\n};\n\nexport class PendingResponses {\n readonly #pending = new Map<string, PendingResponse<unknown>[]>();\n readonly #timeoutMs: number;\n\n constructor(timeoutMs: number) {\n this.#timeoutMs = timeoutMs;\n }\n\n waitFor<T>(key: string, timeoutMessage: string): Promise<T> {\n const pending = createPending<T>();\n let promise!: Promise<T>;\n const timeout = setNonBlockingTimeout(() => {\n this.remove(key, promise);\n pending.reject(new TimeoutError(timeoutMessage));\n }, this.#timeoutMs);\n promise = pending.promise.finally(() => clearTimeout(timeout));\n const entries = this.#pending.get(key) ?? [];\n entries.push({ ...pending, promise } as PendingResponse<unknown>);\n this.#pending.set(key, entries);\n return promise;\n }\n\n resolve<T>(key: string, value: T): void {\n const entries = this.#pending.get(key);\n const pending = entries?.shift();\n if (pending === undefined) return;\n if (entries !== undefined && entries.length === 0) {\n this.#pending.delete(key);\n }\n pending.resolve(value);\n }\n\n reject(key: string, error: Error): void {\n const entries = this.#pending.get(key);\n const pending = entries?.shift();\n if (pending === undefined) return;\n if (entries !== undefined && entries.length === 0) {\n this.#pending.delete(key);\n }\n pending.reject(error);\n }\n\n remove<T>(key: string, promise: Promise<T>): void {\n const entries = this.#pending.get(key);\n if (entries === undefined) return;\n const remaining = entries.filter((entry) => entry.promise !== promise);\n if (remaining.length === 0) {\n this.#pending.delete(key);\n } else {\n this.#pending.set(key, remaining);\n }\n }\n\n rejectAll(error: Error): void {\n for (const entries of this.#pending.values()) {\n for (const pending of entries) {\n pending.reject(error);\n }\n }\n this.#pending.clear();\n }\n}\n\nfunction createPending<T>(): PendingResponse<T> {\n let resolve!: (value: T) => void;\n let reject!: (error: Error) => void;\n const promise = new Promise<T>((resolvePromise, rejectPromise) => {\n resolve = resolvePromise;\n reject = rejectPromise;\n });\n return { promise, reject, resolve };\n}\n","import {\n type OrderSide,\n type PositionId,\n toBaseUnits,\n} from '@polymarket/bindings';\nimport type { RfqSignedOrder } from '@polymarket/bindings/combos';\nimport type { EvmAddress, EvmSignature, HexString } from '@polymarket/types';\nimport { SigningError } from '../../errors';\nimport {\n calculateExchangeOrderMakerAmount,\n calculateExchangeOrderTakerAmount,\n createExchangeOrderSignature,\n createExchangeOrderTypedDataPayload,\n createExchangeV3OrderDomain,\n encodeExchangeOrderSide,\n} from '../../exchange';\nimport type { Signer } from '../../types';\nimport type { AccountIdentity } from '../../wallet';\nimport { resolveOrderIdentity } from '../../wallet';\n\nconst BYTES32_ZERO =\n '0x0000000000000000000000000000000000000000000000000000000000000000' satisfies HexString;\n\nexport type SignRfqQuoteOrderParams = {\n account: AccountIdentity;\n chainId: number;\n exchange: EvmAddress;\n orderPrice: bigint;\n orderSide: OrderSide;\n signer: Signer;\n size: bigint;\n tokenId: PositionId;\n};\n\nexport async function signRfqQuoteOrder(\n params: SignRfqQuoteOrderParams,\n): Promise<RfqSignedOrder> {\n const identity = resolveOrderIdentity(params.account);\n const domain = createExchangeV3OrderDomain({\n chainId: params.chainId,\n exchange: params.exchange,\n });\n const order: Omit<RfqSignedOrder, 'signature'> = {\n builder: BYTES32_ZERO,\n maker: identity.maker,\n makerAmount: toBaseUnits(\n calculateExchangeOrderMakerAmount(\n params.orderSide,\n params.orderPrice,\n params.size,\n ),\n ),\n metadata: BYTES32_ZERO,\n salt: generateRfqOrderSalt().toString(),\n side: encodeExchangeOrderSide(params.orderSide),\n signatureType: identity.signatureType,\n signer: identity.signer,\n takerAmount: toBaseUnits(\n calculateExchangeOrderTakerAmount(\n params.orderSide,\n params.orderPrice,\n params.size,\n ),\n ),\n timestamp: Math.floor(Date.now() / 1000).toString(),\n tokenId: params.tokenId,\n };\n\n let signature: EvmSignature;\n try {\n signature = await params.signer.signTypedData(\n createExchangeOrderTypedDataPayload({ domain, order }),\n );\n } catch (error) {\n throw SigningError.fromError(error, 'Could not sign the RFQ quote order.');\n }\n\n return {\n ...order,\n signature: createExchangeOrderSignature({ domain, order, signature }),\n };\n}\n\nfunction generateRfqOrderSalt(): bigint {\n const bytes = new Uint8Array(8);\n globalThis.crypto.getRandomValues(bytes);\n\n // RFQ salts stay strings on the wire, so the full 64-bit value is lossless.\n return BigInt(\n `0x${Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('')}`,\n );\n}\n","import {\n DecimalishSchema,\n type DecimalString,\n OrderSide,\n type PositionId,\n} from '@polymarket/bindings';\nimport {\n RfqDirection,\n type RfqQuoteRequest,\n type RfqRequestedSize,\n RfqRequestedSizeUnit,\n type RfqSignedOrder,\n} from '@polymarket/bindings/combos';\nimport type { EvmAddress } from '@polymarket/types';\nimport { z } from 'zod';\nimport type { RfqQuoteResponse, RfqQuoteSource } from '../../actions/rfq';\nimport { UserInputError } from '../../errors';\nimport { parseUserInput } from '../../input';\nimport type { Signer } from '../../types';\nimport type { AccountIdentity } from '../../wallet';\nimport { signRfqQuoteOrder } from './signing';\n\nconst DecimalishToBigIntSchema = DecimalishSchema.transform((value) =>\n decimalToScaledInteger(value),\n).refine((value) => value <= BigInt(Number.MAX_SAFE_INTEGER), {\n message: 'Value exceeds the temporary numeric wire limit.',\n});\n\nconst RfqQuoteResponseSchema = z.strictObject({\n price: DecimalishToBigIntSchema.refine((price) => price < 1_000_000n, {\n message: 'Price must be less than 1.',\n }),\n size: DecimalishToBigIntSchema.optional(),\n source: z.enum(['collateral', 'inventory']).default('collateral'),\n});\n\nexport type ParsedRfqQuoteResponse = {\n price: bigint;\n size?: bigint;\n source: RfqQuoteSource;\n};\n\nexport type CreateRfqQuoteParams = {\n account: AccountIdentity;\n chainId: number;\n exchange: EvmAddress;\n request: RfqQuoteRequest;\n response: ParsedRfqQuoteResponse;\n signer: Signer;\n};\n\nexport type RfqQuote = {\n price: bigint;\n signedOrder: RfqSignedOrder;\n size: bigint;\n};\n\nexport function parseRfqQuoteResponse(\n response: RfqQuoteResponse,\n): ParsedRfqQuoteResponse {\n return parseUserInput(response, RfqQuoteResponseSchema);\n}\n\nexport async function createRfqQuote(\n params: CreateRfqQuoteParams,\n): Promise<RfqQuote> {\n const price = params.response.price;\n const size =\n params.response.size === undefined\n ? defaultQuoteSize(params.request.requestedSize, price)\n : params.response.size;\n const signedOrder = await signRfqQuoteOrder({\n account: params.account,\n chainId: params.chainId,\n exchange: params.exchange,\n orderPrice: quoteOrderPrice(params.request, params.response.source, price),\n orderSide: quoteOrderSide(params.response.source),\n signer: params.signer,\n size,\n tokenId: quoteOrderTokenId(params.request, params.response.source),\n });\n\n return { price, signedOrder, size };\n}\n\nfunction quoteOrderTokenId(\n request: RfqQuoteRequest,\n source: RfqQuoteSource,\n): PositionId {\n if (request.direction === RfqDirection.Buy) {\n return source === 'collateral'\n ? request.noPositionId\n : request.yesPositionId;\n }\n\n return source === 'collateral' ? request.yesPositionId : request.noPositionId;\n}\n\nfunction quoteOrderPrice(\n request: RfqQuoteRequest,\n source: RfqQuoteSource,\n price: bigint,\n): bigint {\n const usesComplementPrice =\n (request.direction === RfqDirection.Buy && source === 'collateral') ||\n (request.direction === RfqDirection.Sell && source === 'inventory');\n\n return usesComplementPrice ? 1_000_000n - price : price;\n}\n\nfunction quoteOrderSide(source: RfqQuoteSource): OrderSide {\n return source === 'collateral' ? OrderSide.BUY : OrderSide.SELL;\n}\n\nfunction defaultQuoteSize(\n requestedSize: RfqRequestedSize,\n price: bigint,\n): bigint {\n const value = decimalToScaledInteger(requestedSize.value);\n\n if (requestedSize.unit === RfqRequestedSizeUnit.Shares) {\n return value;\n }\n\n return (value * 1_000_000n) / price;\n}\n\nfunction decimalToScaledInteger(value: DecimalString): bigint {\n const match = /^(\\d+)(?:\\.(\\d*))?$/.exec(value);\n if (match === null) {\n throw new UserInputError('Value must be a valid decimal.');\n }\n\n const [, whole = '', fraction = ''] = match;\n\n if (fraction.length > 6) {\n throw new UserInputError('Value must have at most 6 decimal places.');\n }\n\n const scaledValue =\n BigInt(whole) * 1_000_000n + BigInt(fraction.padEnd(6, '0'));\n\n if (scaledValue <= 0n) {\n throw new UserInputError('Value must be greater than 0.');\n }\n\n return scaledValue;\n}\n","import type { ApiKeyCreds } from '@polymarket/bindings/clob';\nimport {\n type RfqConfirmationDecision,\n type RfqErrorMessage,\n type RfqId,\n type RfqQuoteId,\n type RfqQuoteRequest,\n RfqQuoterInboundMessageSchema,\n type RfqQuoterOutboundMessage,\n} from '@polymarket/bindings/combos';\nimport { type EvmAddress, setNonBlockingTimeout } from '@polymarket/types';\nimport { type Pushable, pushable } from 'it-pushable';\nimport type {\n RfqCancelQuoteAck,\n RfqConfirmationAck,\n RfqEvent,\n RfqQuoteReference,\n RfqQuoteResponse,\n RfqSession,\n} from '../../actions/rfq';\nimport {\n RfqCancelQuoteRejectedError,\n RfqConfirmationRejectedError,\n RfqQuoteRejectedError,\n} from '../../actions/rfq';\nimport { ConnectionLostError, TransportError } from '../../errors';\nimport type { Signer } from '../../types';\nimport type { AccountIdentity } from '../../wallet';\nimport { type WebSocketCloseInfo, WebSocketConnection } from '../lifecycle';\nimport {\n type RfqEventController,\n toConfirmationAck,\n toConfirmationRequestEvent,\n toExecutionUpdateEvent,\n toQuoteAck,\n toQuoteCancelAck,\n toQuoteRequestEvent,\n toTradeEvent,\n} from './events';\nimport {\n createAuthMessage,\n createConfirmationResponseMessage,\n createQuoteCancelMessage,\n createQuoteMessage,\n} from './messages';\nimport { PendingResponses } from './pending';\nimport { createRfqQuote, parseRfqQuoteResponse } from './quote';\n\nconst AUTH_TIMEOUT_MS = 30_000;\nconst ACK_TIMEOUT_MS = 30_000;\n\nexport type RfqQuoterWebSocketManagerOptions = {\n account: AccountIdentity;\n chainId: number;\n credentials: ApiKeyCreds;\n exchange: EvmAddress;\n headers?: Record<string, string>;\n signer: Signer;\n url: string;\n};\n\nexport class RfqQuoterWebSocketManager {\n readonly #account: AccountIdentity;\n readonly #chainId: number;\n readonly #credentials: ApiKeyCreds;\n readonly #exchange: EvmAddress;\n readonly #headers: Record<string, string> | undefined;\n readonly #signer: Signer;\n readonly #url: string;\n #session: RfqWebSocketSession | undefined;\n #connectingSession: RfqWebSocketSession | undefined;\n #connecting: Promise<RfqSession> | undefined;\n #hasShutdown = false;\n\n constructor(options: RfqQuoterWebSocketManagerOptions) {\n this.#account = options.account;\n this.#chainId = options.chainId;\n this.#credentials = options.credentials;\n this.#exchange = options.exchange;\n this.#headers = options.headers;\n this.#signer = options.signer;\n this.#url = options.url;\n }\n\n async connect(): Promise<RfqSession> {\n if (this.#hasShutdown) {\n throw new TransportError('RFQ quoter manager has been shut down.');\n }\n\n if (this.#session !== undefined) {\n if (!this.#session.closed) return this.#session;\n this.#session = undefined;\n }\n if (this.#connecting !== undefined) return this.#connecting;\n\n const session = new RfqWebSocketSession({\n account: this.#account,\n chainId: this.#chainId,\n credentials: this.#credentials,\n exchange: this.#exchange,\n headers: this.#headers,\n onClose: () => this.#clearSession(session),\n signer: this.#signer,\n url: this.#url,\n });\n this.#connectingSession = session;\n\n let connecting!: Promise<RfqSession>;\n connecting = (async () => {\n try {\n await session.connect();\n if (this.#hasShutdown) {\n await session.close();\n throw new TransportError('RFQ quoter manager has been shut down.');\n }\n this.#session = session;\n return session;\n } catch (error) {\n await session.close();\n throw error;\n } finally {\n if (this.#connecting === connecting) {\n this.#connecting = undefined;\n }\n if (this.#connectingSession === session) {\n this.#connectingSession = undefined;\n }\n }\n })();\n\n this.#connecting = connecting;\n return connecting;\n }\n\n async shutdown(): Promise<void> {\n this.#hasShutdown = true;\n const session = this.#session;\n const connectingSession = this.#connectingSession;\n const connecting = this.#connecting;\n\n this.#session = undefined;\n this.#connectingSession = undefined;\n this.#connecting = undefined;\n\n await Promise.allSettled([\n session?.close(),\n connectingSession?.close(),\n connecting?.catch(() => undefined),\n ]).then(() => undefined);\n }\n\n #clearSession(session: RfqWebSocketSession): void {\n if (this.#session === session) {\n this.#session = undefined;\n }\n if (this.#connectingSession === session) {\n this.#connectingSession = undefined;\n }\n }\n}\n\ntype RfqWebSocketSessionConfig = {\n account: AccountIdentity;\n chainId: number;\n credentials: ApiKeyCreds;\n exchange: EvmAddress;\n headers?: Record<string, string>;\n onClose: () => void;\n signer: Signer;\n url: string;\n};\n\nclass RfqWebSocketSession implements RfqSession, RfqEventController {\n readonly #account: AccountIdentity;\n readonly #chainId: number;\n readonly #credentials: ApiKeyCreds;\n readonly #exchange: EvmAddress;\n readonly #headers: Record<string, string> | undefined;\n readonly #onClose: () => void;\n readonly #signer: Signer;\n readonly #url: string;\n readonly #connection = new WebSocketConnection();\n readonly #queue: Pushable<RfqEvent> = pushable({ objectMode: true });\n readonly #pending = new PendingResponses(ACK_TIMEOUT_MS);\n #closing: Promise<void> | undefined;\n #auth: PendingResponse<void> | undefined;\n\n constructor(options: RfqWebSocketSessionConfig) {\n this.#account = options.account;\n this.#chainId = options.chainId;\n this.#credentials = options.credentials;\n this.#exchange = options.exchange;\n this.#headers = options.headers;\n this.#onClose = options.onClose;\n this.#signer = options.signer;\n this.#url = options.url;\n }\n\n get closed(): boolean {\n return this.#closing !== undefined;\n }\n\n async connect(): Promise<void> {\n const auth = createPending<void>();\n this.#auth = auth;\n const authTimeout = setNonBlockingTimeout(() => {\n auth.reject(new TransportError('RFQ quoter authentication timed out.'));\n }, AUTH_TIMEOUT_MS);\n\n try {\n await this.#connection.connect({\n headers: this.#headers,\n onConnectionLost: (info) => this.#handleConnectionLost(info),\n onError: () => undefined,\n onMessage: (message) => this.#handleMessage(message),\n onOpen: () => this.#sendAuthMessage(),\n url: this.#url,\n });\n await auth.promise;\n } finally {\n clearTimeout(authTimeout);\n this.#auth = undefined;\n }\n }\n\n async #send(message: RfqQuoterOutboundMessage): Promise<void> {\n if (!this.#connection.send(message)) {\n throw new TransportError('RFQ quoter websocket is not open.');\n }\n }\n\n async close(): Promise<void> {\n if (this.#closing === undefined) {\n this.#closing = this.#shutdown();\n }\n await this.#closing;\n }\n\n [Symbol.asyncIterator](): AsyncIterator<RfqEvent> {\n return this.#queue[Symbol.asyncIterator]();\n }\n\n async #shutdown(): Promise<void> {\n const error = new TransportError('RFQ quoter websocket closed.');\n this.#failPending(error);\n this.#queue.end();\n await this.#connection.close();\n this.#onClose();\n }\n\n async #fail(error: Error): Promise<void> {\n if (this.#closing === undefined) {\n this.#closing = this.#shutdownWithError(error);\n }\n await this.#closing;\n }\n\n async #shutdownWithError(error: Error): Promise<void> {\n this.#failPending(error);\n this.#queue.end(error);\n await this.#connection.close();\n this.#onClose();\n }\n\n #failPending(error: Error): void {\n this.#auth?.reject(error);\n this.#pending.rejectAll(error);\n }\n\n #sendAuthMessage(): void {\n this.#connection.send(createAuthMessage(this.#account, this.#credentials));\n }\n\n #handleMessage(rawMessage: unknown): void {\n if (this.#closing !== undefined) return;\n\n const parsed = RfqQuoterInboundMessageSchema.safeParse(rawMessage);\n if (!parsed.success) return;\n\n const message = parsed.data;\n switch (message.type) {\n case 'auth':\n this.#handleAuthMessage(message);\n return;\n case 'quote_request':\n this.#queue.push(toQuoteRequestEvent(this, message));\n return;\n case 'quote_ack':\n this.#pending.resolve(quoteAckKey(message.rfqId), toQuoteAck(message));\n return;\n case 'quote_cancel_ack':\n this.#pending.resolve(\n quoteCancelAckKey(message.rfqId, message.quoteId),\n toQuoteCancelAck(message),\n );\n return;\n case 'confirmation_request':\n this.#queue.push(toConfirmationRequestEvent(this, message));\n return;\n case 'confirmation_ack':\n this.#pending.resolve(\n confirmationAckKey(message.rfqId, message.quoteId),\n toConfirmationAck(message),\n );\n return;\n case 'execution_update':\n this.#queue.push(toExecutionUpdateEvent(message));\n return;\n case 'trade':\n this.#queue.push(toTradeEvent(message));\n return;\n case 'rfq_error':\n this.#handleRfqError(message);\n return;\n }\n }\n\n #handleAuthMessage(message: { error?: string; success: boolean }): void {\n if (message.success === true) {\n this.#auth?.resolve(undefined);\n return;\n }\n this.#auth?.reject(\n new TransportError(`RFQ quoter authentication failed: ${message.error}`),\n );\n }\n\n #handleConnectionLost(info: WebSocketCloseInfo): void {\n void this.#fail(\n new ConnectionLostError('RFQ quoter connection lost.', info),\n );\n }\n\n // Unsupported RFQ_ERROR request types are ignored for forward compatibility.\n // Known outbound request errors without enough IDs are protocol failures.\n #handleRfqError(message: RfqErrorMessage): void {\n if (message.requestType === 'RFQ_QUOTE') {\n if (message.rfqId === undefined) {\n void this.#fail(new TransportError('Uncorrelated RFQ quoter error.'));\n return;\n }\n\n this.#pending.reject(\n quoteAckKey(message.rfqId),\n new RfqQuoteRejectedError(message.message, {\n code: message.code,\n errorId: message.errorId,\n rfqId: message.rfqId,\n }),\n );\n return;\n }\n\n if (message.requestType === 'RFQ_QUOTE_CANCEL') {\n if (message.rfqId === undefined || message.quoteId === undefined) {\n void this.#fail(new TransportError('Uncorrelated RFQ quoter error.'));\n return;\n }\n\n this.#pending.reject(\n quoteCancelAckKey(message.rfqId, message.quoteId),\n new RfqCancelQuoteRejectedError(message.message, {\n code: message.code,\n errorId: message.errorId,\n quoteId: message.quoteId,\n rfqId: message.rfqId,\n }),\n );\n return;\n }\n\n if (message.requestType === 'RFQ_CONFIRMATION_RESPONSE') {\n if (message.rfqId === undefined || message.quoteId === undefined) {\n void this.#fail(new TransportError('Uncorrelated RFQ quoter error.'));\n return;\n }\n\n this.#pending.reject(\n confirmationAckKey(message.rfqId, message.quoteId),\n new RfqConfirmationRejectedError(message.message, {\n code: message.code,\n errorId: message.errorId,\n quoteId: message.quoteId,\n rfqId: message.rfqId,\n }),\n );\n }\n }\n\n async quote(\n request: RfqQuoteRequest,\n response: RfqQuoteResponse,\n ): Promise<RfqQuoteReference> {\n const parsedResponse = parseRfqQuoteResponse(response);\n const quote = await createRfqQuote({\n account: this.#account,\n chainId: this.#chainId,\n exchange: this.#exchange,\n request,\n response: parsedResponse,\n signer: this.#signer,\n });\n const pending = this.#pending.waitFor<RfqQuoteReference>(\n quoteAckKey(request.rfqId),\n `Timed out waiting for RFQ quote acknowledgement for ${request.rfqId}.`,\n );\n try {\n await this.#send(createQuoteMessage(request, quote));\n return await pending;\n } catch (error) {\n this.#pending.remove(quoteAckKey(request.rfqId), pending);\n throw error;\n }\n }\n\n async cancelQuote(reference: RfqQuoteReference): Promise<RfqCancelQuoteAck> {\n const key = quoteCancelAckKey(reference.rfqId, reference.quoteId);\n const pending = this.#pending.waitFor<RfqCancelQuoteAck>(\n key,\n `Timed out waiting for RFQ quote cancellation acknowledgement for ${reference.rfqId}.`,\n );\n try {\n await this.#send(\n createQuoteCancelMessage(\n this.#account,\n reference.rfqId,\n reference.quoteId,\n ),\n );\n return await pending;\n } catch (error) {\n this.#pending.remove(key, pending);\n throw error;\n }\n }\n\n async respondToConfirmation(\n rfqId: RfqId,\n quoteId: RfqQuoteId,\n decision: RfqConfirmationDecision,\n ): Promise<RfqConfirmationAck> {\n const key = confirmationAckKey(rfqId, quoteId);\n const pending = this.#pending.waitFor<RfqConfirmationAck>(\n key,\n `Timed out waiting for RFQ confirmation acknowledgement for ${rfqId}.`,\n );\n try {\n await this.#send(\n createConfirmationResponseMessage(rfqId, quoteId, decision),\n );\n return await pending;\n } catch (error) {\n this.#pending.remove(key, pending);\n throw error;\n }\n }\n}\n\nfunction quoteAckKey(rfqId: RfqId): string {\n return `ACK_RFQ_QUOTE:${rfqId}`;\n}\n\nfunction quoteCancelAckKey(rfqId: RfqId, quoteId: RfqQuoteId): string {\n return `ACK_RFQ_QUOTE_CANCEL:${rfqId}:${quoteId}`;\n}\n\nfunction confirmationAckKey(rfqId: RfqId, quoteId: RfqQuoteId): string {\n return `ACK_RFQ_CONFIRMATION_RESPONSE:${rfqId}:${quoteId}`;\n}\n\ntype PendingResponse<T> = {\n promise: Promise<T>;\n reject(error: Error): void;\n resolve(value: T): void;\n};\n\nfunction createPending<T>(): PendingResponse<T> {\n let resolve!: (value: T) => void;\n let reject!: (error: Error) => void;\n const promise = new Promise<T>((resolvePromise, rejectPromise) => {\n resolve = resolvePromise;\n reject = rejectPromise;\n });\n return { promise, reject, resolve };\n}\n","import {\n type CommentsEvent,\n type CryptoPricesChainlinkTwapWindowSeconds,\n type CryptoPricesEvent,\n type EquityPricesEvent,\n RealtimeEventSchema,\n} from '@polymarket/bindings/subscriptions';\nimport { invariant } from '@polymarket/types';\nimport type {\n CommentsSubscription,\n CryptoPricesChainlinkTwapSubscription,\n CryptoPricesSubscription,\n EquityPricesSubscription,\n SubscriptionHandle,\n} from '../actions/subscriptions';\nimport { createSubscriptionHandle } from './handle';\nimport { RtdsWebSocketHeartbeat } from './heartbeat';\nimport {\n ReconnectScheduler,\n WebSocketConnection,\n type WebSocketConnectionResult,\n} from './lifecycle';\nimport {\n SubscriptionRegistry,\n type SubscriptionRegistryChange,\n type SubscriptionRegistryEntry,\n} from './registry';\nimport type { WebSocketSubscriptionManager } from './types';\n\ntype RtdsSpec =\n | CommentsSubscription\n | CryptoPricesSubscription\n | CryptoPricesChainlinkTwapSubscription\n | EquityPricesSubscription;\n\ntype RtdsEvent = CommentsEvent | CryptoPricesEvent | EquityPricesEvent;\n\ntype RtdsSubscriptionEntry = SubscriptionRegistryEntry<RtdsSpec, RtdsEvent>;\n\ntype RtdsServerSubscription = {\n key: string;\n topic: string;\n type: string;\n};\n\ntype RtdsServerState = Map<string, RtdsServerSubscription>;\n\nexport type RtdsWebSocketManagerOptions = {\n headers?: Record<string, string>;\n url: string;\n};\n\n/**\n * Realtime Data Service (RTDS) WebSocket manager.\n *\n * Implements {@link WebSocketSubscriptionManager} for the comments, crypto prices, and\n * equity prices topics multiplexed over a single shared upstream socket\n * opened lazily on the first subscribe.\n */\nexport class RtdsWebSocketManager\n implements WebSocketSubscriptionManager<RtdsSpec, RtdsEvent>\n{\n readonly #headers: Record<string, string> | undefined;\n readonly #url: string;\n #closing: Promise<void> | undefined;\n readonly #connection = new WebSocketConnection({\n heartbeat: new RtdsWebSocketHeartbeat(),\n });\n readonly #reconnectScheduler = new ReconnectScheduler();\n readonly #subscriptions = new SubscriptionRegistry<\n RtdsSpec,\n RtdsEvent,\n RtdsServerState\n >({ deriveServerState: deriveRtdsServerState });\n\n constructor(options: RtdsWebSocketManagerOptions) {\n this.#headers = options.headers;\n this.#url = options.url;\n }\n\n async subscribe(\n subscription: RtdsSpec,\n ): Promise<SubscriptionHandle<RtdsEvent>> {\n const { change, entry } = this.#subscriptions.add(subscription, {\n matches: matcherFor(subscription),\n });\n await this.#registerSubscriber(entry, change);\n return createSubscriptionHandle(entry.subscriber.queue, () =>\n this.#closeSubscriber(entry),\n );\n }\n\n // Subscription handle lifecycle.\n\n async #registerSubscriber(\n entry: RtdsSubscriptionEntry,\n change: SubscriptionRegistryChange<RtdsServerState>,\n ): Promise<void> {\n try {\n const connection = await this.#connect();\n if (connection.reusedOpenSocket) {\n const { before, after } = change;\n const subscriptionsToOpen = serverSubscriptionsAdded(before, after);\n this.#sendSubscribeFrame(subscriptionsToOpen);\n }\n } catch (error) {\n await this.#closeSubscriber(entry);\n throw error;\n }\n }\n\n async #closeSubscriber(entry: RtdsSubscriptionEntry): Promise<void> {\n const { before, after } = this.#subscriptions.remove(entry);\n const subscriptionsToClose = serverSubscriptionsRemoved(before, after);\n this.#sendUnsubscribeFrame(subscriptionsToClose);\n if (!this.#subscriptions.hasActiveSubscriptions()) {\n await this.close();\n }\n }\n\n // Socket lifecycle.\n\n async close(): Promise<void> {\n if (this.#closing === undefined) {\n this.#closing = this.#shutdown().finally(() => {\n this.#closing = undefined;\n });\n }\n await this.#closing;\n }\n\n async #shutdown(): Promise<void> {\n this.#reconnectScheduler.stop();\n this.#subscriptions.endAll();\n\n await this.#connection.close();\n }\n\n #connect(): Promise<WebSocketConnectionResult> {\n return this.#connection.connect({\n onConnectionLost: () => this.#onConnectionLost(),\n onError: () => this.#onConnectionError(),\n onMessage: (message) => this.#onConnectionMessage(message),\n onOpen: () => this.#onConnectionOpen(),\n headers: this.#headers,\n url: this.#url,\n });\n }\n\n #onConnectionOpen(): void {\n this.#reconnectScheduler.resetBackoff();\n this.#resubscribeActiveServerEntries();\n }\n\n #onConnectionMessage(message: unknown): void {\n const parsed = RealtimeEventSchema.safeParse(message);\n if (!parsed.success) return;\n this.#subscriptions.dispatch(parsed.data);\n }\n\n #onConnectionLost(): void {\n if (this.#subscriptions.hasActiveSubscriptions()) {\n this.#scheduleReconnect();\n }\n }\n\n #onConnectionError(): void {\n // Browser WebSockets report most failures as an error followed by close.\n // Keep iterators alive here so the close path can reconnect active handles.\n }\n\n // RTDS subscribe/unsubscribe frames.\n\n #resubscribeActiveServerEntries(): void {\n this.#sendSubscribeFrame(\n Array.from(this.#subscriptions.serverState().values()),\n );\n }\n\n #sendSubscribeFrame(subscriptions: readonly RtdsServerSubscription[]): void {\n if (subscriptions.length === 0) return;\n this.#connection.send(buildSubscribeMessage(subscriptions));\n }\n\n #sendUnsubscribeFrame(\n subscriptions: readonly RtdsServerSubscription[],\n ): void {\n if (subscriptions.length === 0) return;\n this.#connection.send(buildUnsubscribeMessage(subscriptions));\n }\n\n #scheduleReconnect(): void {\n this.#reconnectScheduler.schedule({\n reconnect: () => this.#connect(),\n shouldReconnect: () => this.#subscriptions.hasActiveSubscriptions(),\n });\n }\n}\n\nfunction serverSubscriptionsAdded(\n before: ReadonlyMap<string, RtdsServerSubscription>,\n after: ReadonlyMap<string, RtdsServerSubscription>,\n): RtdsServerSubscription[] {\n return Array.from(after).flatMap(([key, subscription]) =>\n before.has(key) ? [] : [subscription],\n );\n}\n\nfunction serverSubscriptionsRemoved(\n before: ReadonlyMap<string, RtdsServerSubscription>,\n after: ReadonlyMap<string, RtdsServerSubscription>,\n): RtdsServerSubscription[] {\n return Array.from(before).flatMap(([key, subscription]) =>\n after.has(key) ? [] : [subscription],\n );\n}\n\nfunction deriveRtdsServerState(\n entries: Iterable<RtdsSubscriptionEntry>,\n): RtdsServerState {\n const activeByKey = new Map<string, RtdsServerSubscription>();\n for (const { subscription } of entries) {\n for (const serverSubscription of serverSubscriptionsFor(subscription)) {\n if (!activeByKey.has(serverSubscription.key)) {\n activeByKey.set(serverSubscription.key, serverSubscription);\n }\n }\n }\n return activeByKey;\n}\n\nfunction buildSubscribeMessage(\n subscriptions: readonly RtdsServerSubscription[],\n): unknown {\n return {\n action: 'subscribe',\n subscriptions: subscriptions.map(({ topic, type }) => ({ topic, type })),\n };\n}\n\nfunction buildUnsubscribeMessage(\n subscriptions: readonly RtdsServerSubscription[],\n): unknown {\n return {\n action: 'unsubscribe',\n subscriptions: subscriptions.map(({ topic, type }) => ({ topic, type })),\n };\n}\n\nfunction serverSubscriptionsFor(\n subscription: RtdsSpec,\n): RtdsServerSubscription[] {\n switch (subscription.topic) {\n case 'comments':\n // RTDS tracks subscription state per (topic, type): different comment\n // event types coexist independently on the same socket, so one entry\n // per requested type. No server-side filters — any narrowing by\n // parentEntityID/parentEntityType happens client-side via matcherFor.\n return (subscription.types ?? ['comment_created']).map((type) =>\n serverSubscription('comments', type),\n );\n case 'prices.crypto.binance':\n // Subscribe broadly and filter client-side. Sending a second subscribe\n // frame with a different `filters` value on the same socket causes the\n // server to replace the prior subscription rather than add one, so\n // multiple subscribers on the same manager cannot share a socket while\n // using server-side filters. See docs/api-boundary-notes.md.\n return [serverSubscription('crypto_prices', 'update')];\n case 'prices.crypto.chainlink':\n // RTDS tracks one filter per topic per connection, so a second subscribe\n // with a different filter replaces the first. Subscribe broadly and\n // filter client-side — see docs/api-boundary-notes.md.\n return [serverSubscription('crypto_prices_chainlink', 'update')];\n case 'prices.crypto.chainlink.twap':\n // Each TWAP window is a distinct RTDS topic. Subscribe broadly within\n // the requested window and narrow symbols client-side so subscribers for\n // the same window can safely share a socket.\n return [\n serverSubscription(\n twapServerTopic(subscription.windowSeconds),\n 'update',\n ),\n ];\n case 'prices.equity.pyth':\n // Same per-topic replace-on-resubscribe constraint as crypto_prices. A\n // single unfiltered subscribe covers every active equity symbol; the\n // client-side matcher narrows to the caller's requested symbol.\n return [serverSubscription('equity_prices', 'update')];\n default: {\n const neverSpec: never = subscription;\n invariant(false, `Unknown RTDS topic: ${String(neverSpec)}`);\n }\n }\n}\n\nfunction twapServerTopic(\n windowSeconds: CryptoPricesChainlinkTwapWindowSeconds,\n): string {\n switch (windowSeconds) {\n case 30:\n return 'crypto_prices_twap_thirty';\n case 60:\n return 'crypto_prices_twap_sixty';\n default: {\n const neverWindow: never = windowSeconds;\n invariant(false, `Unknown TWAP window: ${String(neverWindow)}`);\n }\n }\n}\n\nfunction serverSubscription(\n topic: string,\n type: string,\n): RtdsServerSubscription {\n return {\n key: `${topic}:${type}`,\n topic,\n type,\n };\n}\n\nfunction matcherFor(subscription: RtdsSpec): (event: RtdsEvent) => boolean {\n switch (subscription.topic) {\n case 'comments':\n // All `comments` narrowing happens client-side because the RTDS server\n // uses opaque substring matching on `filters` rather than structured\n // fields. When the caller sets `parentEntityId` or `parentEntityType`,\n // reaction events are dropped: their payloads carry only `commentID`,\n // not the parent context, so we can't verify the filter on them. Rule:\n // if a filter can't be verified on an event, the event doesn't match.\n // See docs/api-boundary-notes.md.\n return (event) => {\n if (event.topic !== 'comments') return false;\n if (\n subscription.types !== undefined &&\n subscription.types.length > 0 &&\n !subscription.types.includes(event.type)\n ) {\n return false;\n }\n const hasParentFilter =\n subscription.parentEntityId !== undefined ||\n subscription.parentEntityType !== undefined;\n if (hasParentFilter) {\n const carriesParentContext =\n event.type === 'comment_created' ||\n event.type === 'comment_removed';\n if (!carriesParentContext) return false;\n if (\n subscription.parentEntityId !== undefined &&\n event.payload.parentEntityID !== subscription.parentEntityId\n ) {\n return false;\n }\n if (\n subscription.parentEntityType !== undefined &&\n event.payload.parentEntityType !== subscription.parentEntityType\n ) {\n return false;\n }\n }\n return true;\n };\n case 'prices.crypto.binance':\n return (event) =>\n event.topic === 'prices.crypto.binance' &&\n (subscription.symbols === undefined ||\n subscription.symbols.length === 0 ||\n subscription.symbols.includes(event.payload.symbol));\n case 'prices.crypto.chainlink':\n return (event) =>\n event.topic === 'prices.crypto.chainlink' &&\n (subscription.symbols === undefined ||\n subscription.symbols.length === 0 ||\n subscription.symbols.includes(event.payload.symbol));\n case 'prices.crypto.chainlink.twap':\n return (event) =>\n event.topic === 'prices.crypto.chainlink.twap' &&\n event.payload.windowSeconds === subscription.windowSeconds &&\n (subscription.symbols === undefined ||\n subscription.symbols.length === 0 ||\n subscription.symbols.includes(event.payload.symbol));\n case 'prices.equity.pyth':\n // RTDS emits every event kind for a topic regardless of the `type` value\n // in the subscribe frame, so the caller's `types` filter must be\n // enforced client-side here.\n return (event) =>\n event.topic === 'prices.equity.pyth' &&\n event.payload.symbol.toLowerCase() ===\n subscription.symbol.toLowerCase() &&\n (subscription.types === undefined ||\n subscription.types.length === 0 ||\n subscription.types.includes(event.type));\n default: {\n const neverSpec: never = subscription;\n invariant(false, `Unknown RTDS topic: ${String(neverSpec)}`);\n }\n }\n}\n","import {\n type SportsEvent,\n SportsResultEventSchema,\n} from '@polymarket/bindings/subscriptions';\nimport type {\n SportsSubscription,\n SubscriptionHandle,\n} from '../actions/subscriptions';\nimport { createSubscriptionHandle } from './handle';\nimport { SportsWebSocketHeartbeat } from './heartbeat';\nimport {\n ReconnectScheduler,\n WebSocketConnection,\n type WebSocketConnectionResult,\n} from './lifecycle';\nimport {\n SubscriptionRegistry,\n type SubscriptionRegistryEntry,\n} from './registry';\nimport type { WebSocketSubscriptionManager } from './types';\n\ntype SportsSubscriptionEntry = SubscriptionRegistryEntry<\n SportsSubscription,\n SportsEvent\n>;\n\nexport type SportsWebSocketManagerOptions = {\n headers?: Record<string, string>;\n url: string;\n};\n\n/**\n * Sports WebSocket manager.\n *\n * The sports stream starts sending events immediately after connection and does\n * not require a subscribe frame. The server sends `ping`; clients must reply\n * with `pong` to keep the socket alive.\n */\nexport class SportsWebSocketManager\n implements WebSocketSubscriptionManager<SportsSubscription, SportsEvent>\n{\n readonly #headers: Record<string, string> | undefined;\n readonly #url: string;\n #closing: Promise<void> | undefined;\n readonly #connection = new WebSocketConnection({\n heartbeat: new SportsWebSocketHeartbeat(),\n });\n readonly #reconnectScheduler = new ReconnectScheduler();\n readonly #subscriptions = new SubscriptionRegistry<\n SportsSubscription,\n SportsEvent\n >();\n\n constructor(options: SportsWebSocketManagerOptions) {\n this.#headers = options.headers;\n this.#url = options.url;\n }\n\n async subscribe(\n subscription: SportsSubscription,\n ): Promise<SubscriptionHandle<SportsEvent>> {\n const { entry } = this.#subscriptions.add(subscription);\n\n await this.#registerSubscriber(entry);\n return createSubscriptionHandle(entry.subscriber.queue, () =>\n this.#closeSubscriber(entry),\n );\n }\n\n // Subscription handle lifecycle.\n\n async #registerSubscriber(entry: SportsSubscriptionEntry): Promise<void> {\n try {\n await this.#connect();\n } catch (error) {\n await this.#closeSubscriber(entry);\n throw error;\n }\n }\n\n async #closeSubscriber(entry: SportsSubscriptionEntry): Promise<void> {\n this.#subscriptions.remove(entry);\n\n if (!this.#subscriptions.hasActiveSubscriptions()) {\n await this.close();\n }\n }\n\n // Socket lifecycle.\n\n async close(): Promise<void> {\n if (this.#closing === undefined) {\n this.#closing = this.#shutdown().finally(() => {\n this.#closing = undefined;\n });\n }\n await this.#closing;\n }\n\n async #shutdown(): Promise<void> {\n this.#reconnectScheduler.stop();\n this.#subscriptions.endAll();\n\n await this.#connection.close();\n }\n\n #connect(): Promise<WebSocketConnectionResult> {\n return this.#connection.connect({\n onConnectionLost: () => this.#onConnectionLost(),\n onError: () => this.#onConnectionError(),\n onMessage: (message) => this.#onConnectionMessage(message),\n onOpen: () => this.#onConnectionOpen(),\n headers: this.#headers,\n url: this.#url,\n });\n }\n\n #onConnectionOpen(): void {\n this.#reconnectScheduler.resetBackoff();\n }\n\n #onConnectionMessage(message: unknown): void {\n const parsed = SportsResultEventSchema.safeParse(message);\n if (!parsed.success) return;\n this.#subscriptions.dispatch(parsed.data);\n }\n\n #onConnectionLost(): void {\n if (this.#subscriptions.hasActiveSubscriptions()) {\n this.#scheduleReconnect();\n }\n }\n\n #onConnectionError(): void {\n // Browser WebSockets report most failures as an error followed by close.\n // Keep iterators alive here so the close path can reconnect active handles.\n }\n\n #scheduleReconnect(): void {\n this.#reconnectScheduler.schedule({\n reconnect: () => this.#connect(),\n shouldReconnect: () => this.#subscriptions.hasActiveSubscriptions(),\n });\n }\n}\n","import { ApiKeySchema, EvmAddressSchema } from '@polymarket/bindings';\nimport type { ApiKeyCreds } from '@polymarket/bindings/clob';\nimport { WalletType } from '@polymarket/bindings/gamma';\nimport {\n expectEvmAddress,\n expectEvmSignature,\n invariant,\n isSameEvmAddress,\n type Prettify,\n} from '@polymarket/types';\nimport { z } from 'zod';\nimport {\n createOrDeriveApiKey,\n deleteApiKey,\n fetchApiKeys,\n} from './actions/auth';\nimport {\n type DeployDepositWalletError,\n deployDepositWallet,\n type IsWalletDeployedError,\n isWalletDeployed,\n type WaitForGaslessTransactionError,\n} from './actions/gasless';\nimport { createApiKeyAuthTypedDataPayload } from './authentication';\nimport {\n allActions,\n type PublicActions,\n type SecureActions,\n} from './decorators';\nimport { type EnvironmentConfig, production } from './environments';\nimport {\n CancelledSigningError,\n makeErrorGuard,\n RateLimitError,\n RequestRejectedError,\n SigningError,\n TimeoutError,\n TransactionFailedError,\n TransportError,\n UnexpectedResponseError,\n UserInputError,\n} from './errors';\nimport { buildHmacSignature } from './hmac';\nimport { parseUserInput } from './input';\nimport type { RateLimitUpdateListener } from './rate-limit';\nimport { JsonRpcClient } from './rpc';\nimport type { ServiceRequest } from './ServiceClient';\nimport { ServiceClient } from './ServiceClient';\nimport type { ApiKeyAuthorization, Signer } from './types';\nimport type { AccountIdentity } from './wallet';\nimport {\n deriveBeaconDepositWalletAddress,\n deriveUupsDepositWalletAddress,\n resolveAccountIdentity,\n} from './wallet';\nimport {\n ClobMarketWebSocketManager,\n ClobUserWebSocketManager,\n PerpsSessionManager,\n PerpsSubscriptionManager,\n type PublicWebSocketManagers,\n RfqQuoterWebSocketManager,\n RtdsWebSocketManager,\n type SecureWebSocketManagers,\n SportsWebSocketManager,\n} from './websockets';\nimport {\n type AuthenticationWorkflow,\n authenticateWith,\n requestAddress,\n} from './workflow';\n\ntype PublicContext = {\n /** @internal */\n apiKey?: ApiKeyAuthorization;\n /** @internal */\n environment: EnvironmentConfig;\n /** @internal */\n onRateLimitUpdate?: RateLimitUpdateListener;\n /** @internal */\n clob: ServiceClient;\n /** @internal */\n relayer: ServiceClient;\n /** @internal */\n rpc: JsonRpcClient;\n /** @internal */\n gamma: ServiceClient;\n /** @internal */\n data: ServiceClient;\n /** @internal */\n rfq: ServiceClient;\n /** @internal */\n perps: ServiceClient;\n /** @internal */\n webSockets: PublicWebSocketManagers;\n};\n\n// biome-ignore lint/complexity/noBannedTypes: intentional\nexport type ClientActions = {};\n\nexport type ClientDecorator<\n TPublicActions extends ClientActions = ClientActions,\n TSecureActions extends ClientActions = TPublicActions,\n> = {\n (client: BasePublicClient<ClientActions, ClientActions>): TPublicActions;\n (client: BaseSecureClient<ClientActions, ClientActions>): TSecureActions;\n};\n\ntype DecoratorPublicActions<TDecorator extends ClientDecorator> =\n TDecorator extends ClientDecorator<\n infer TPublicActions,\n infer _TSecureActions\n >\n ? TPublicActions\n : never;\n\ntype DecoratorSecureActions<TDecorator extends ClientDecorator> =\n TDecorator extends ClientDecorator<\n infer _TPublicActions,\n infer TSecureActions\n >\n ? TSecureActions\n : never;\n\nabstract class AbstractClient<TContext extends PublicContext> {\n // Keep the backing context off the public object shape so accidental\n // client logs do not print secure credentials.\n readonly #context: TContext;\n readonly #decorators: ClientDecorator[];\n\n protected get context(): TContext {\n return this.#context;\n }\n\n protected get decorators(): readonly ClientDecorator[] {\n return this.#decorators;\n }\n\n /** @internal */\n get environment(): EnvironmentConfig {\n return this.context.environment;\n }\n\n /** @internal */\n get clob(): ServiceClient {\n return this.context.clob;\n }\n\n /** @internal */\n get relayer(): ServiceClient {\n return this.context.relayer;\n }\n\n /** @internal */\n get rpc(): JsonRpcClient {\n return this.context.rpc;\n }\n\n /** @internal */\n get gamma(): ServiceClient {\n return this.context.gamma;\n }\n\n /** @internal */\n get data(): ServiceClient {\n return this.context.data;\n }\n\n /** @internal */\n get rfq(): ServiceClient {\n return this.context.rfq;\n }\n\n /** @internal */\n get perps(): ServiceClient {\n return this.context.perps;\n }\n\n /** @internal */\n get webSockets(): PublicWebSocketManagers {\n return this.context.webSockets;\n }\n\n /** @internal */\n get supportsGasless(): boolean {\n return this.context.apiKey?.supportGasless ?? false;\n }\n\n /** @internal */\n get hasBuilderApiKey(): boolean {\n return this.context.apiKey?.isBuilderKey ?? false;\n }\n\n constructor(context: TContext) {\n this.#context = context;\n this.#decorators = [];\n }\n\n protected async resolveClobHeaders(\n request: ServiceRequest,\n ): Promise<HeadersInit> {\n if (this.context.apiKey?.isBuilderKey) {\n return this.context.apiKey.authorize(request);\n }\n return Promise.resolve({});\n }\n\n protected async resolveRelayerHeaders(\n request: ServiceRequest,\n ): Promise<HeadersInit> {\n if (this.context.apiKey?.supportGasless) {\n return this.context.apiKey.authorize(request);\n }\n return Promise.resolve({});\n }\n\n protected rememberDecorator(decorator: ClientDecorator): void {\n this.#decorators.push(decorator);\n }\n}\n\nconst BeginAuthenticationCredentialsSchema = z.object({\n key: ApiKeySchema,\n passphrase: z.string(),\n secret: z.string(),\n});\n\nexport type BeginAuthenticationRequest = {\n /**\n * Wallet address to authenticate as.\n *\n * Pass the signer address itself to authenticate as an EOA account.\n */\n wallet: string;\n\n /**\n * Nonce used when creating or deriving fresh credentials.\n *\n * Mutually exclusive with `credentials`.\n *\n * @defaultValue 0\n */\n nonce?: number;\n\n /**\n * Existing API credentials to reuse when they remain valid.\n *\n * If these credentials are revoked or invalid, authentication falls back to\n * fresh authentication and the signer may be asked to sign again.\n */\n credentials?: ApiKeyCreds;\n};\n\nconst BeginAuthenticationRequestSchema: z.ZodType<BeginAuthenticationRequest> =\n z\n .object({\n wallet: EvmAddressSchema,\n credentials: BeginAuthenticationCredentialsSchema.optional(),\n nonce: z.number().int().nonnegative().optional(),\n })\n .superRefine((value, context) => {\n if (value.credentials !== undefined && value.nonce !== undefined) {\n context.addIssue({\n code: 'custom',\n message: '`credentials` and `nonce` are mutually exclusive.',\n path: ['nonce'],\n });\n }\n })\n .transform((value): BeginAuthenticationRequest => {\n if (value.credentials !== undefined) {\n return {\n wallet: value.wallet,\n credentials: value.credentials,\n };\n }\n\n if (value.nonce !== undefined) {\n return {\n wallet: value.wallet,\n nonce: value.nonce,\n };\n }\n\n return {\n wallet: value.wallet,\n };\n });\n\ntype PublicClientConfig = {\n environment: EnvironmentConfig;\n apiKey?: ApiKeyAuthorization;\n onRateLimitUpdate?: RateLimitUpdateListener;\n};\n\nclass BasePublicClient<\n TPublicActions extends ClientActions = ClientActions,\n TSecureActions extends ClientActions = TPublicActions,\n> extends AbstractClient<PublicContext> {\n constructor(config: PublicClientConfig) {\n super({\n apiKey: config.apiKey,\n environment: config.environment,\n onRateLimitUpdate: config.onRateLimitUpdate,\n data: new ServiceClient({\n headers: config.environment.data.headers,\n root: config.environment.data.rest,\n }),\n gamma: new ServiceClient({\n headers: config.environment.gamma.headers,\n root: config.environment.gamma.rest,\n }),\n clob: new ServiceClient({\n headers: config.environment.clob.headers,\n onRateLimitUpdate: config.onRateLimitUpdate,\n root: config.environment.clob.rest,\n resolveHeaders: (request) => this.resolveClobHeaders(request),\n }),\n relayer: new ServiceClient({\n headers: config.environment.relayer.headers,\n root: config.environment.relayer.rest,\n resolveHeaders: (request) => this.resolveRelayerHeaders(request),\n }),\n rfq: new ServiceClient({\n headers: config.environment.combos.headers,\n root: config.environment.combos.rest,\n }),\n perps: new ServiceClient({\n headers: config.environment.perps.headers,\n root: config.environment.perps.rest,\n }),\n rpc: new JsonRpcClient({ url: config.environment.rpc }),\n webSockets: {\n clobMarket: new ClobMarketWebSocketManager({\n headers: config.environment.clob.market.headers,\n url: config.environment.clob.market.ws,\n }),\n sports: new SportsWebSocketManager({\n headers: config.environment.sports.headers,\n url: config.environment.sports.ws,\n }),\n rtds: new RtdsWebSocketManager({\n headers: config.environment.rtds.headers,\n url: config.environment.rtds.ws,\n }),\n perpsSubscriptions: new PerpsSubscriptionManager({\n headers: config.environment.perps.headers,\n url: config.environment.perps.ws,\n }),\n },\n });\n }\n\n /**\n * Use this to narrow a {@link Client} union to {@link SecureClient}.\n *\n * @example\n * ```ts\n * if (client.isSecureClient()) {\n * client.credentials; // SecureClient\n * }\n * ```\n */\n isSecureClient(): this is BaseSecureClient<TPublicActions, TSecureActions> {\n return false;\n }\n\n /**\n * Use this to narrow a {@link Client} union to {@link PublicClient}.\n *\n * @example\n * ```ts\n * if (client.isPublicClient()) {\n * client.closeSubscriptions(); // PublicClient\n * }\n * ```\n */\n isPublicClient(): this is BasePublicClient<TPublicActions, TSecureActions> {\n return true;\n }\n\n /**\n * Closes all active realtime subscriptions owned by this client.\n *\n * @remarks\n * This ends active subscription iterators and closes shared websocket\n * connections. It does not affect authentication or other client state.\n *\n * @example\n * ```ts\n * await client.closeSubscriptions();\n * ```\n */\n async closeSubscriptions(): Promise<void> {\n await Promise.all([\n this.webSockets.clobMarket.close(),\n this.webSockets.rtds.close(),\n this.webSockets.sports.close(),\n this.webSockets.perpsSubscriptions.close(),\n ]).then(() => undefined);\n }\n\n /**\n * Returns a client typed with the methods contributed by the decorator.\n */\n extend<TDecorator extends ClientDecorator>(\n decorator: TDecorator,\n ): PublicClient<\n Prettify<TPublicActions & DecoratorPublicActions<TDecorator>>,\n Prettify<TSecureActions & DecoratorSecureActions<TDecorator>>\n > {\n this.rememberDecorator(decorator);\n Object.assign(this, decorator(this));\n return this as unknown as PublicClient<\n Prettify<TPublicActions & DecoratorPublicActions<TDecorator>>,\n Prettify<TSecureActions & DecoratorSecureActions<TDecorator>>\n >;\n }\n\n /**\n * Begins an authentication workflow that produces a {@link SecureClient}.\n *\n * @remarks\n * This is a low-level method for building wallet-interactive workflows. Most\n * applications should use {@link createSecureClient} instead.\n *\n * @internal\n */\n beginAuthentication(\n request: BeginAuthenticationRequest,\n signer: Signer,\n ): Promise<\n AuthenticationWorkflow<SecureClient<TPublicActions, TSecureActions>>\n > {\n const params = parseUserInput(request, BeginAuthenticationRequestSchema);\n\n return Promise.resolve(\n async function* (\n this: PublicClient<TPublicActions, TSecureActions>,\n ): AuthenticationWorkflow<SecureClient<TPublicActions, TSecureActions>> {\n const timestamp = Math.floor(Date.now() / 1000);\n const nonce = params?.nonce ?? 0;\n const signerAddress = expectEvmAddress(yield requestAddress());\n const wallet = expectEvmAddress(params.wallet);\n const identity = resolveAccountIdentity(\n this.environment,\n signerAddress,\n wallet,\n );\n\n if (params.credentials !== undefined) {\n const client = this.#createSecureClient(\n params.credentials,\n identity,\n signer,\n );\n\n try {\n const apiKeys = await fetchApiKeys(client);\n if (apiKeys.includes(params.credentials.key)) {\n return client;\n }\n } catch (error) {\n if (\n !(error instanceof RequestRejectedError) ||\n error.status !== 401\n ) {\n throw error;\n }\n }\n }\n\n const signature = yield {\n kind: 'signAuthMessage',\n payload: createApiKeyAuthTypedDataPayload({\n address: signerAddress,\n chainId: this.environment.chainId,\n nonce,\n timestamp,\n }),\n };\n const credentials = await createOrDeriveApiKey(this, {\n address: signerAddress,\n nonce,\n signature: expectEvmSignature(signature),\n timestamp,\n });\n\n return this.#createSecureClient(credentials, identity, signer);\n }.call(this as unknown as PublicClient<TPublicActions, TSecureActions>),\n );\n }\n\n #createSecureClient(\n credentials: ApiKeyCreds,\n account: AccountIdentity,\n signer: Signer,\n ): SecureClient<TPublicActions, TSecureActions> {\n const client = new BaseSecureClient({\n account: account,\n apiKey: this.context.apiKey,\n credentials,\n environment: this.environment,\n onRateLimitUpdate: this.context.onRateLimitUpdate,\n signer,\n });\n\n for (const decorator of this.decorators) {\n client.extend(decorator);\n }\n\n return client as SecureClient<TPublicActions, TSecureActions>;\n }\n}\n\nclass BaseSecureClient<\n TPublicActions extends ClientActions = ClientActions,\n TSecureActions extends ClientActions = TPublicActions,\n> extends AbstractClient<SecureContext> {\n #hasEndedAuthentication = false;\n\n /**\n * @remarks This is the choking point for all requests, so we can ensure that once\n * `endAuthentication` is called, no further authenticated requests can be made with this client instance.\n */\n protected override get context(): SecureContext {\n invariant(\n !this.#hasEndedAuthentication,\n 'This client has ended authentication and can no longer be used.',\n );\n\n return super.context;\n }\n\n protected endAuthenticationLifecycle(): void {\n this.#hasEndedAuthentication = true;\n }\n\n constructor(config: SecureClientConfig) {\n super({\n account: config.account,\n credentials: config.credentials,\n apiKey: config.apiKey,\n environment: config.environment,\n onRateLimitUpdate: config.onRateLimitUpdate,\n signer: config.signer,\n clob: new ServiceClient({\n headers: config.environment.clob.headers,\n onRateLimitUpdate: config.onRateLimitUpdate,\n root: config.environment.clob.rest,\n resolveHeaders: (request) => this.resolveClobHeaders(request),\n }),\n relayer: new ServiceClient({\n headers: config.environment.relayer.headers,\n root: config.environment.relayer.rest,\n resolveHeaders: (request) => this.resolveRelayerHeaders(request),\n }),\n rpc: new JsonRpcClient({ url: config.environment.rpc }),\n gamma: new ServiceClient({\n headers: config.environment.gamma.headers,\n root: config.environment.gamma.rest,\n }),\n data: new ServiceClient({\n headers: config.environment.data.headers,\n root: config.environment.data.rest,\n }),\n rfq: new ServiceClient({\n headers: config.environment.combos.headers,\n root: config.environment.combos.rest,\n }),\n perps: new ServiceClient({\n headers: config.environment.perps.headers,\n root: config.environment.perps.rest,\n }),\n secureClob: new ServiceClient({\n headers: config.environment.clob.headers,\n onRateLimitUpdate: config.onRateLimitUpdate,\n resolveHeaders: async (request) => ({\n ...(await this.resolveClobHeaders(request)),\n ...(await this.#createL2Headers(request)),\n }),\n root: config.environment.clob.rest,\n }),\n combos: new ServiceClient({\n headers: config.environment.combos.collateralReturn.headers,\n resolveHeaders: (request) => this.resolveRelayerHeaders(request),\n root: config.environment.combos.collateralReturn.rest,\n }),\n builderGateway: new ServiceClient({\n headers: config.environment.combos.builderGateway.headers,\n resolveHeaders: async (request) => ({\n ...(await this.#resolveBuilderGatewayHeaders(request)),\n ...(await this.#createL2Headers(request)),\n }),\n root: config.environment.combos.builderGateway.rest,\n }),\n webSockets: {\n clobMarket: new ClobMarketWebSocketManager({\n headers: config.environment.clob.market.headers,\n url: config.environment.clob.market.ws,\n }),\n clobUser: new ClobUserWebSocketManager({\n credentials: config.credentials,\n headers: config.environment.clob.user.headers,\n url: config.environment.clob.user.ws,\n }),\n rfqQuoter: new RfqQuoterWebSocketManager({\n account: config.account,\n chainId: config.environment.chainId,\n credentials: config.credentials,\n exchange: config.environment.contracts.exchangeV3,\n headers: config.environment.combos.headers,\n signer: config.signer,\n url: config.environment.combos.ws,\n }),\n sports: new SportsWebSocketManager({\n headers: config.environment.sports.headers,\n url: config.environment.sports.ws,\n }),\n rtds: new RtdsWebSocketManager({\n headers: config.environment.rtds.headers,\n url: config.environment.rtds.ws,\n }),\n perpsSubscriptions: new PerpsSubscriptionManager({\n headers: config.environment.perps.headers,\n url: config.environment.perps.ws,\n }),\n perpsSession: new PerpsSessionManager({\n chainId: config.environment.chainId,\n headers: config.environment.perps.headers,\n restUrl: config.environment.perps.rest,\n wsUrl: config.environment.perps.ws,\n }),\n },\n });\n }\n\n /**\n * API credentials for the authenticated session.\n *\n * @remarks\n * These credentials are sensitive. Store them securely if you want to create\n * another secure client later without requiring a new authentication signature\n * while the credentials remain valid.\n */\n get credentials(): ApiKeyCreds {\n return this.context.credentials;\n }\n\n /**\n * The authenticated account identity associated with this client, including the signer and wallet addresses and wallet type.\n */\n get account(): AccountIdentity {\n return this.context.account;\n }\n\n /** @internal */\n get signer(): Signer {\n return this.context.signer;\n }\n\n /** @internal */\n get secureClob(): ServiceClient {\n return this.context.secureClob;\n }\n\n /** @internal */\n get combos(): ServiceClient {\n return this.context.combos;\n }\n\n /** @internal */\n get builderGateway(): ServiceClient {\n return this.context.builderGateway;\n }\n\n /** @internal */\n override get webSockets(): SecureWebSocketManagers {\n return this.context.webSockets;\n }\n\n /**\n * Closes all active realtime subscriptions owned by this client.\n *\n * @remarks\n * Secure clients also close authenticated user-stream subscriptions. This\n * ends active subscription iterators and closes shared websocket connections.\n * It does not affect authentication or other client state.\n *\n * @example\n * ```ts\n * await client.closeSubscriptions();\n * ```\n */\n async closeSubscriptions(): Promise<void> {\n await Promise.allSettled([\n this.webSockets.clobMarket.close(),\n this.webSockets.rtds.close(),\n this.webSockets.sports.close(),\n this.webSockets.perpsSubscriptions.close(),\n this.webSockets.clobUser.close(),\n ]).then(() => undefined);\n }\n\n /**\n * Use this to narrow a {@link Client} union to {@link SecureClient}.\n *\n * @example\n * ```ts\n * if (client.isSecureClient()) {\n * client.credentials; // SecureClient\n * }\n * ```\n */\n isSecureClient(): this is BaseSecureClient<TPublicActions, TSecureActions> {\n return true;\n }\n\n /**\n * Use this to narrow a {@link Client} union to {@link PublicClient}.\n *\n * @example\n * ```ts\n * if (client.isPublicClient()) {\n * client.closeSubscriptions(); // PublicClient\n * }\n * ```\n */\n isPublicClient(): this is BasePublicClient<TPublicActions, TSecureActions> {\n return false;\n }\n\n /**\n * Returns a secure client typed with the methods contributed by the decorator.\n */\n extend<TDecorator extends ClientDecorator>(\n decorator: TDecorator,\n ): SecureClient<\n TPublicActions,\n Prettify<TSecureActions & DecoratorSecureActions<TDecorator>>\n > {\n this.rememberDecorator(decorator);\n Object.assign(this, decorator(this));\n\n return this as unknown as SecureClient<\n TPublicActions,\n Prettify<TSecureActions & DecoratorSecureActions<TDecorator>>\n >;\n }\n\n /**\n * Ends authentication for this client and returns a public client.\n *\n * @remarks\n * This revokes the current authenticated credential and invalidates the\n * current `SecureClient` instance.\n *\n * @example\n * ```ts\n * const publicClient = await secureClient.endAuthentication();\n * ```\n */\n async endAuthentication(): Promise<\n PublicClient<TPublicActions, TSecureActions>\n > {\n // Server-side revocation must not depend on local WebSocket cleanup.\n const closingSubscriptions = this.closeSubscriptions();\n const shuttingDownPerpsSessions = this.webSockets.perpsSession.shutdown();\n const shuttingDownRfqQuoter = this.webSockets.rfqQuoter.shutdown();\n const { apiKey, environment, onRateLimitUpdate } = this.context;\n\n try {\n await deleteApiKey(this);\n } finally {\n this.endAuthenticationLifecycle();\n await Promise.allSettled([\n closingSubscriptions,\n shuttingDownPerpsSessions,\n shuttingDownRfqQuoter,\n ]).then(() => undefined);\n }\n\n const client = new BasePublicClient({\n apiKey,\n environment,\n onRateLimitUpdate,\n });\n\n for (const decorator of this.decorators) {\n client.extend(decorator);\n }\n\n return client as PublicClient<TPublicActions, TSecureActions>;\n }\n\n // Builder gateway status reads authenticate with account headers only;\n // builder headers are required on the mutating requests.\n async #resolveBuilderGatewayHeaders(\n request: ServiceRequest,\n ): Promise<HeadersInit> {\n if (request.method !== 'GET' && this.context.apiKey?.isBuilderKey) {\n return this.context.apiKey.authorize(request);\n }\n return {};\n }\n\n async #createL2Headers(request: ServiceRequest): Promise<HeadersInit> {\n try {\n const timestamp = Math.floor(Date.now() / 1000);\n\n return {\n POLY_ADDRESS: this.account.signer,\n POLY_API_KEY: this.credentials.key,\n POLY_PASSPHRASE: this.credentials.passphrase,\n POLY_SIGNATURE: await buildHmacSignature(\n this.credentials.secret,\n timestamp,\n request.method,\n request.path,\n request.body,\n ),\n POLY_TIMESTAMP: `${timestamp}`,\n };\n } catch (error) {\n throw SigningError.fromError(\n error,\n 'Could not sign the L2-authenticated request',\n );\n }\n }\n}\n\ntype SecureContext = PublicContext & {\n /** @internal */\n account: AccountIdentity;\n /** @internal */\n credentials: ApiKeyCreds;\n /** @internal */\n signer: Signer;\n /** @internal */\n secureClob: ServiceClient;\n /** @internal */\n combos: ServiceClient;\n /** @internal */\n builderGateway: ServiceClient;\n /** @internal */\n webSockets: SecureWebSocketManagers;\n};\n\ntype SecureClientConfig = PublicClientConfig & {\n account: AccountIdentity;\n credentials: ApiKeyCreds;\n signer: Signer;\n};\n\nexport type PublicClient<\n TPublicActions extends ClientActions = PublicActions,\n TSecureActions extends ClientActions = SecureActions,\n> = BasePublicClient<TPublicActions, TSecureActions> & TPublicActions;\n\nexport type SecureClient<\n TPublicActions extends ClientActions = PublicActions,\n TSecureActions extends ClientActions = SecureActions,\n> = BaseSecureClient<TPublicActions, TSecureActions> & TSecureActions;\n\nexport { BasePublicClient, BaseSecureClient };\n\nexport type BaseClient<\n TPublicActions extends ClientActions = ClientActions,\n TSecureActions extends ClientActions = TPublicActions,\n> =\n | BasePublicClient<TPublicActions, TSecureActions>\n | BaseSecureClient<TPublicActions, TSecureActions>;\n\nexport type Client<\n TPublicActions extends ClientActions = ClientActions,\n TSecureActions extends ClientActions = TPublicActions,\n> =\n | PublicClient<TPublicActions, TSecureActions>\n | SecureClient<TPublicActions, TSecureActions>;\n\nexport type PublicClientOptions = {\n /**\n * The environment configuration used by the client.\n *\n * @defaultValue `production`\n */\n environment?: EnvironmentConfig;\n\n /**\n * Optional request authorization applied by the client when needed.\n */\n apiKey?: ApiKeyAuthorization;\n\n /**\n * Listener invoked whenever a response reports per-signer rate-limit state,\n * as order and cancellation responses do.\n *\n * @remarks\n * Use this to monitor remaining rate-limit capacity and warning-mode\n * signals, and adjust request patterns before requests are rejected.\n * Errors thrown by the listener and rejections from promises it returns are\n * ignored.\n */\n onRateLimitUpdate?: RateLimitUpdateListener;\n};\n\nexport type SecureClientOptions = PublicClientOptions & {\n /**\n * Wallet address to use as the account wallet.\n *\n * If omitted, the client uses the signer's deterministic Deposit Wallet as\n * the account wallet. Pass the signer address itself to explicitly trade as\n * an EOA account, or pass a supported Poly Deposit Wallet, Poly Safe, or Poly\n * Proxy wallet address to use that wallet as the account/funder.\n */\n wallet?: string;\n\n /**\n * Wallet-library adapter used to authenticate and complete wallet operations.\n */\n signer: Signer;\n} & (\n | {\n /**\n * Existing API credentials to reuse when they remain valid.\n */\n credentials?: ApiKeyCreds;\n nonce?: never;\n }\n | {\n credentials?: never;\n /**\n * Nonce used when creating or deriving fresh credentials.\n *\n * @defaultValue 0\n */\n nonce?: number;\n }\n );\n\n/**\n * Creates a new `PublicClient` instance.\n *\n * @example\n * ```ts\n * const client = createPublicClient();\n * ```\n */\nexport function createPublicClient(\n options: PublicClientOptions = {},\n): PublicClient<PublicActions, SecureActions> {\n return new BasePublicClient({\n environment: options.environment ?? production,\n apiKey: options.apiKey,\n onRateLimitUpdate: options.onRateLimitUpdate,\n }).extend(allActions);\n}\n\nexport type CreateSecureClientError =\n | CancelledSigningError\n | DeployDepositWalletError\n | IsWalletDeployedError\n | RateLimitError\n | RequestRejectedError\n | SigningError\n | TimeoutError\n | TransactionFailedError\n | TransportError\n | UnexpectedResponseError\n | UserInputError\n | WaitForGaslessTransactionError;\nexport const CreateSecureClientError = makeErrorGuard(\n CancelledSigningError,\n RateLimitError,\n RequestRejectedError,\n SigningError,\n TimeoutError,\n TransactionFailedError,\n TransportError,\n UnexpectedResponseError,\n UserInputError,\n);\n\nexport type SetupGaslessWalletError = UserInputError;\nexport const SetupGaslessWalletError = makeErrorGuard(UserInputError);\n\n/**\n * Creates a new authenticated `SecureClient` instance.\n *\n * @example\n * ```ts\n * const secureClient = await createSecureClient({\n * signer,\n * });\n * ```\n *\n * @throws {@link CreateSecureClientError}\n * Thrown on failure.\n */\nexport async function createSecureClient(\n options: SecureClientOptions,\n): Promise<SecureClient<PublicActions, SecureActions>> {\n const client = createPublicClient({\n environment: options.environment,\n apiKey: options.apiKey,\n onRateLimitUpdate: options.onRateLimitUpdate,\n });\n const wallet = await resolveRequestedWallet(client, options);\n\n const secureClient = await client\n .beginAuthentication(\n {\n wallet,\n credentials: options.credentials,\n nonce: options.nonce,\n },\n options.signer,\n )\n .then(authenticateWith(options.signer));\n\n if (secureClient.account.walletType === WalletType.EOA) {\n return secureClient;\n }\n\n const deployed = await isWalletDeployed(secureClient, {\n wallet: secureClient.account.wallet,\n type: secureClient.account.walletType,\n });\n\n if (deployed) {\n return secureClient;\n }\n\n if (secureClient.account.walletType === WalletType.DEPOSIT_WALLET) {\n await deployDefaultDepositWallet(secureClient);\n return secureClient;\n }\n\n throw new UserInputError(\n `Wallet ${secureClient.account.wallet} does not exist. Provide an existing wallet address, or omit wallet to use the default Deposit Wallet flow.`,\n );\n}\n\n/** Resolves the wallet address to authenticate as. */\nasync function resolveRequestedWallet(\n client: BasePublicClient,\n options: SecureClientOptions,\n): Promise<string> {\n if (options.wallet !== undefined) {\n return options.wallet;\n }\n\n const signerAddress = expectEvmAddress(await options.signer.getAddress());\n const legacyDepositWallet = deriveUupsDepositWalletAddress(\n signerAddress,\n client.environment.walletDerivation,\n );\n\n if (\n await isWalletDeployed(client, {\n wallet: legacyDepositWallet,\n type: WalletType.DEPOSIT_WALLET,\n })\n ) {\n return legacyDepositWallet;\n }\n\n return deriveBeaconDepositWalletAddress(\n signerAddress,\n client.environment.walletDerivation,\n );\n}\n\n/**\n * Deploys the signer's beacon Deposit Wallet for the secure client. The current\n * factory only deploys beacon wallets, so legacy UUPS wallets must already be\n * deployed and cannot be created through this path.\n */\nasync function deployDefaultDepositWallet(\n secureClient: SecureClient<PublicActions, SecureActions>,\n): Promise<void> {\n const currentDepositWallet = deriveBeaconDepositWalletAddress(\n secureClient.account.signer,\n secureClient.environment.walletDerivation,\n );\n\n if (!isSameEvmAddress(secureClient.account.wallet, currentDepositWallet)) {\n throw new UserInputError(\n `Wallet ${secureClient.account.wallet} does not match the expected Deposit Wallet ${currentDepositWallet} for this signer, nor a deployed wallet address.`,\n );\n }\n\n const handle = await deployDepositWallet(secureClient);\n await handle.wait();\n}\n"]}