@polymarket/client 0.1.0-beta.2 → 0.1.0-beta.4
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/README.md +2 -10
- package/dist/actions/index.d.ts +13 -12
- package/dist/actions/index.js +1 -1
- package/dist/chunk-76B5WBIO.js +2 -0
- package/dist/chunk-76B5WBIO.js.map +1 -0
- package/dist/ethers-v5.d.ts +2 -1
- package/dist/index.d.ts +57 -10
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/{sports-BDLhQVTP.d.ts → sports-shrXkDsG.d.ts} +31 -5
- package/dist/{types-D7tLX0ye.d.ts → types-BHjtOekI.d.ts} +1278 -352
- package/dist/viem.d.ts +2 -1
- package/package.json +11 -3
- package/dist/chunk-VQOVE5SC.js +0 -2
- package/dist/chunk-VQOVE5SC.js.map +0 -1
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/rewards.ts","../src/decorators/subscriptions.ts","../src/decorators/trading.ts","../src/decorators/wallet.ts","../src/decorators/index.ts","../src/environments.ts","../src/hmac.ts","../src/ServiceClient.ts","../src/websockets/handle.ts","../src/websockets/heartbeat.ts","../src/websockets/lifecycle.ts","../src/websockets/registry.ts","../src/websockets/clob/protocol.ts","../src/websockets/clob/market.ts","../src/websockets/clob/user.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","fetchPortfolioValue","fetchTradedMarketCount","downloadAccountingSnapshot","listMarketPositions","listActivity","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","fetchMarket","fetchMarketTags","listSeries","fetchSeries","listTags","fetchTag","fetchRelatedTags","fetchRelatedTagResources","search","listSports","fetchSportsMarketTypes","listTeams","fetchPublicProfile","listComments","fetchCommentsById","listCommentsByUserAddress","publicRewardsActions","listCurrentRewards","listMarketRewards","rewardsActions","fetchOrderScoring","fetchOrdersScoring","listUserEarningsForDay","fetchTotalEarningsForUserForDay","listUserEarningsAndMarketsConfig","fetchRewardPercentages","subscriptionsActions","subscriptions","subscribe","tradingActions","createMarketOrder","placeMarketOrder","createLimitOrder","placeLimitOrder","postOrder","postOrders","cancelOrder","cancelOrders","cancelAll","cancelMarketOrders","listOpenOrders","fetchOrder","walletActions","isGaslessReady","setupTradingApprovals","approveErc20","approveErc1155ForAll","transferErc20","splitPosition","mergePositions","redeemPositions","allActions","production","expectEvmAddress","buildHmacSignature","secret","timestamp","method","requestPath","body","message","cryptoKey","base64ToArrayBuffer","signature","toUrlSafeBase64","arrayBufferToBase64","base64","sanitizedBase64","binaryString","bytes","index","buffer","binary","byte","value","ServiceClient","#client","root","resolveHeaders","ky","path","options","#request","#normalizePath","#toResult","#send","#createRequest","#mergeHeaders","#serializeJson","json","sources","source","key","promise","ResultAsync","RateLimitError","#extractResponseErrorMessage","RequestRejectedError","TransportError","contentType","text","createSubscriptionHandle","queue","closeSubscription","closing","CLOB_HEARTBEAT_INTERVAL_MS","CLOB_HEARTBEAT_STALE_MS","RTDS_HEARTBEAT_INTERVAL_MS","RTDS_HEARTBEAT_STALE_MS","SPORTS_HEARTBEAT_STALE_MS","ClobWebSocketHeartbeat","#lastPongAt","#timer","send","setNonBlockingInterval","now","RtdsWebSocketHeartbeat","#lastMessageAt","SportsWebSocketHeartbeat","#lastPingAt","HEARTBEAT_WATCHDOG_INTERVAL_MS","RECONNECT_BASE_DELAY_MS","RECONNECT_MAX_DELAY_MS","ReconnectScheduler","#attempt","delay","reconnectDelay","setNonBlockingTimeout","#reconnect","WebSocketConnection","#heartbeat","#socket","#connecting","#watchdog","#clearCurrentSocket","connecting","#open","#sendRaw","socket","#takeCurrent","#stopHeartbeat","resolve","context","reject","onOpen","onOpenError","#markOpen","#startHeartbeat","event","raw","attempt","exponentialDelay","SubscriptionRegistry","#entries","#deriveServerState","subscription","subscriber","pushable","entry","#addEntry","before","syncMarketSubscription","after","addedAssets","difference","removedAssets","buildMarketSubscribeUpdate","firstActiveAsset","buildMarketUnsubscribeUpdate","syncUserSubscription","buildUserUnsubscribeUpdate","buildUserSubscribeUpdate","addedMarkets","removedMarkets","deriveMarketServerSubscription","entries","assets","customFeatureEnabled","tokenId","deriveUserServerSubscription","includeAllMarkets","markets","isAllMarketsUserSubscription","market","buildMarketSubscribeMessage","assetsIds","buildUserSubscribeMessage","credentials","marketMatcherFor","change","userMatcherFor","left","right","rightSet","ClobMarketWebSocketManager","#url","#closing","#connection","#reconnectScheduler","#subscriptions","#registerSubscriber","#closeSubscriber","#connect","#shutdown","#onConnectionClose","#onConnectionError","#onConnectionMessage","#onConnectionOpen","#sendInitialSubscription","events","eventData","parsed","MarketEventSchema","#scheduleReconnect","ClobUserWebSocketManager","#resolveCredentials","UserEventSchema","RtdsWebSocketManager","deriveRtdsServerState","url","matcherFor","subscriptionsToOpen","serverSubscriptionsAdded","#sendSubscribeFrame","subscriptionsToClose","serverSubscriptionsRemoved","#sendUnsubscribeFrame","#resubscribeActiveServerEntries","RealtimeEventSchema","buildSubscribeMessage","buildUnsubscribeMessage","activeByKey","serverSubscription","serverSubscriptionsFor","topic","type","invariant","SportsWebSocketManager","SportsResultEventSchema","AbstractClient","#context","#decorators","decorator","BeginAuthenticationCredentialsSchema","ApiKeySchema","BeginAuthenticationRequestSchema","EvmAddressSchema","BasePublicClient","JsonRpcClient","signer","params","parseUserInput","nonce","signerAddress","requestAddress","wallet","identity","resolveAccountIdentity","#createSecureClient","fetchApiKeys","createOrDeriveApiKey","expectEvmSignature","account","BaseSecureClient","_BaseSecureClient","#hasEndedAuthentication","#createL2Headers","isSameEvmAddress","WalletType","#createSecureClientForWallet","depositWallet","deriveCurrentDepositWalletAddress","deployDepositWallet","closingSubscriptions","apiKey","environment","deleteApiKey","createPublicClient","CreateSecureClientError","makeErrorGuard","CancelledSigningError","UnexpectedResponseError","UserInputError","SetupGaslessWalletError","TimeoutError","TransactionFailedError","createSecureClient","authenticateWith"],"mappings":"26HAiCA,IAAMA,EAAAA,CAAqCC,EAAE,MAAA,CAAO,CAClD,qBAAsBA,CAAAA,CAAE,MAAA,GAAS,GAAA,CAAI,CAAC,EACtC,sBAAA,CAAwBA,CAAAA,CAAE,QAAO,CAAE,GAAA,CAAI,CAAC,CAAA,CACxC,uBAAA,CAAyBA,EAAE,MAAA,EAAO,CAAE,GAAA,CAAI,CAAC,EACzC,sBAAA,CAAwBA,CAAAA,CAAE,QAAO,CAAE,GAAA,CAAI,CAAC,CAC1C,CAAC,EAEM,SAASC,EAAAA,CACdC,EACqB,CACrB,OAAO,IAAIC,CAAAA,CAA2BD,CAAM,CAC9C,CAEO,SAASE,GACdF,CAAAA,CACqB,CACrB,OAAO,IAAIG,CAAAA,CAA2BH,CAAM,CAC9C,CAEA,IAAMC,CAAAA,CAAN,KAAgE,CACrDG,EAAAA,CAET,WAAA,CAAYJ,EAAoC,CAC9C,IAAA,CAAKI,GAAUJ,EACjB,CAEA,IAAI,YAAA,EAAwB,CAC1B,OAAO,KACT,CAEA,IAAI,cAAA,EAA0B,CAC5B,OAA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AAAA,CAAQ,MAClB,CAAC,CAAA,CACK8K,CAAAA,CAAS9K,EAAQ,MAAA,EAAW,MAAMA,EAAQ,MAAA,CAAO,UAAA,GAEvD,OAAO3H,CAAAA,CACJ,oBACC,CACE,MAAA,CAAAyS,EACA,WAAA,CAAa9K,CAAAA,CAAQ,YACrB,KAAA,CAAOA,CAAAA,CAAQ,KACjB,CAAA,CACAA,CAAAA,CAAQ,MACV,CAAA,CACC,IAAA,CAAK8M,EAAiB9M,CAAAA,CAAQ,MAAM,CAAC,CAC1C","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 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 ListMarketPositionsRequest,\n type ListPositionsRequest,\n listAccountTrades,\n listActivity,\n listClosedPositions,\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?: TRequest['user'];\n }\n>;\n\nexport type SecureListPositionsRequest =\n DefaultAccountWallet<ListPositionsRequest>;\nexport type SecureListClosedPositionsRequest =\n DefaultAccountWallet<ListClosedPositionsRequest>;\nexport type SecureFetchPortfolioValueRequest =\n DefaultAccountWallet<FetchPortfolioValueRequest>;\nexport type SecureFetchTradedMarketCountRequest =\n DefaultAccountWallet<FetchTradedMarketCountRequest>;\nexport type SecureDownloadAccountingSnapshotRequest =\n DefaultAccountWallet<DownloadAccountingSnapshotRequest>;\nexport type SecureListActivityRequest =\n DefaultAccountWallet<ListActivityRequest>;\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 * 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 * @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>;\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 * 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 * @throws {@link ListActivityError}\n * Thrown on failure.\n */\n listActivity(request?: SecureListActivityRequest): Paginated<Activity[]>;\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 *\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 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 };\n}\n\nfunction withAccountWallet<TRequest extends { user?: string }>(\n client: BaseSecureClient,\n request: TRequest = {} as TRequest,\n): Omit<TRequest, 'user'> & { user: string } {\n return {\n ...request,\n user: request.user ?? client.account.wallet,\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 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 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 ListMarketPositionsError,\n ListPositionsError,\n} from '../actions';\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 {\n LastTradePrice,\n LastTradePriceForToken,\n OrderBook,\n PriceHistoryPoint,\n Prices,\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 a token.\n *\n * @throws {@link FetchMidpointError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const midpoint = await client.fetchMidpoint({ tokenId: '123' });\n * ```\n */\n fetchMidpoint(request: FetchMidpointRequest): Promise<string>;\n /**\n * Fetches midpoint prices for multiple tokens.\n *\n * @throws {@link FetchMidpointsError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const midpoints = await client.fetchMidpoints([{ tokenId: '123' }]);\n * ```\n */\n fetchMidpoints(\n request: FetchMidpointsRequest,\n ): Promise<Record<string, string>>;\n /**\n * Fetches the current quoted price for a token and side.\n *\n * @throws {@link FetchPriceError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const price = await client.fetchPrice({ tokenId: '123', side: OrderSide.BUY });\n * ```\n */\n fetchPrice(request: FetchPriceRequest): Promise<string>;\n /**\n * Fetches quoted prices for multiple tokens.\n *\n * @throws {@link FetchPricesError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const prices = await client.fetchPrices([{ tokenId: '123', side: OrderSide.BUY }]);\n * ```\n */\n fetchPrices(request: FetchPricesRequest): Promise<Prices>;\n /**\n * Fetches the current order book for a token.\n *\n * @throws {@link FetchOrderBookError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const book = await client.fetchOrderBook({ tokenId: '123' });\n * ```\n */\n fetchOrderBook(request: FetchOrderBookRequest): Promise<OrderBook>;\n /**\n * Fetches order books for multiple tokens.\n *\n * @throws {@link FetchOrderBooksError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const books = await client.fetchOrderBooks([{ tokenId: '123' }]);\n * ```\n */\n fetchOrderBooks(request: FetchOrderBooksRequest): Promise<OrderBook[]>;\n /**\n * Fetches the spread for a token.\n *\n * @throws {@link FetchSpreadError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const spread = await client.fetchSpread({ tokenId: '123' });\n * ```\n */\n fetchSpread(request: FetchSpreadRequest): Promise<string>;\n /**\n * Fetches spreads for multiple tokens.\n *\n * @throws {@link FetchSpreadsError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const spreads = await client.fetchSpreads([{ tokenId: '123' }]);\n * ```\n */\n fetchSpreads(request: FetchSpreadsRequest): Promise<Record<string, string>>;\n /**\n * Fetches the last traded price for a token.\n *\n * @throws {@link FetchLastTradePriceError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const price = await client.fetchLastTradePrice({ tokenId: '123' });\n * ```\n */\n fetchLastTradePrice(\n request: FetchLastTradePriceRequest,\n ): Promise<LastTradePrice>;\n /**\n * Fetches last traded prices for multiple tokens.\n *\n * @throws {@link FetchLastTradePricesError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const prices = await client.fetchLastTradePrices([{ tokenId: '123' }]);\n * ```\n */\n fetchLastTradePrices(\n request: FetchLastTradePricesRequest,\n ): Promise<LastTradePriceForToken[]>;\n /**\n * Fetches historical price points for a token.\n *\n * @throws {@link FetchPriceHistoryError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const history = await client.fetchPriceHistory({ tokenId: '123', 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 * tokenId: '123',\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 {\n Comment,\n Event,\n Market,\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 ListCommentsByUserAddressRequest,\n type ListCommentsRequest,\n type ListEventsRequest,\n type ListMarketsRequest,\n type ListSeriesRequest,\n type ListTagsRequest,\n type ListTeamsRequest,\n listComments,\n listCommentsByUserAddress,\n listEvents,\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 * @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 * @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 * Fetches a market.\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/market/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 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 * @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 fetchMarket: fetchMarket.bind(null, client),\n fetchMarketTags: fetchMarketTags.bind(null, client),\n listSeries: listSeries.bind(null, client),\n fetchSeries: fetchSeries.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 ListCommentsByUserAddressError,\n ListCommentsError,\n ListEventsError,\n ListMarketsError,\n ListSeriesError,\n ListSportsError,\n ListTagsError,\n ListTeamsError,\n SearchError,\n} from '../actions';\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 {\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 PublicSubscriptionsActions = {\n /**\n * Starts one or more realtime subscriptions on this client.\n *\n * @throws {@link SubscribeError}\n * Thrown when the realtime subscription cannot be established or fails.\n *\n * @example\n * ```ts\n * const handle = await client.subscribe([\n * { topic: 'market', tokenIds: ['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 the realtime subscription cannot be established or fails.\n *\n * @example\n * ```ts\n * const handle = await client.subscribe([\n * { topic: 'user' },\n * { topic: 'market', tokenIds: ['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 CancelOrdersResponse,\n OpenOrder,\n OrderResponse,\n OrderResponses,\n} from '@polymarket/bindings/clob';\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} from '../actions';\nimport type { SignedOrder } from '../actions/orders';\nimport type { BaseSecureClient } from '../clients';\nimport type { Paginated } from '../pagination';\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\n * ```ts\n * const order = await client.createMarketOrder({\n * amount: 10,\n * side: OrderSide.BUY,\n * tokenId: '123',\n * });\n * ```\n */\n createMarketOrder(request: PrepareMarketOrderRequest): Promise<SignedOrder>;\n /**\n * Creates and posts a market order for the authenticated account.\n *\n * @throws {@link PlaceMarketOrderError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const response = await client.placeMarketOrder({\n * amount: 10,\n * side: OrderSide.BUY,\n * tokenId: '123',\n * });\n *\n * // response: OrderResponse\n * ```\n */\n placeMarketOrder(request: PrepareMarketOrderRequest): Promise<OrderResponse>;\n /**\n * Creates a signed limit order for the authenticated account.\n *\n * @throws {@link CreateLimitOrderError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const order = await client.createLimitOrder({\n * postOnly: true,\n * price: 0.52,\n * side: OrderSide.BUY,\n * size: 10,\n * tokenId: '123',\n * });\n * ```\n */\n createLimitOrder(request: PrepareLimitOrderRequest): Promise<SignedOrder>;\n /**\n * Creates and posts a limit order for the authenticated account.\n *\n * @throws {@link PlaceLimitOrderError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const response = await client.placeLimitOrder({\n * postOnly: true,\n * price: 0.52,\n * side: OrderSide.BUY,\n * size: 10,\n * tokenId: '123',\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 * 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: string[]\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: string[]\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: string[]\n * ```\n */\n cancelAll(): Promise<CancelOrdersResponse>;\n /**\n * Cancels all open orders for the authenticated account that match the market or token 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: string[]\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 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} from '../actions';\n","import {\n approveErc20,\n approveErc1155ForAll,\n isGaslessReady,\n mergePositions,\n type PrepareErc20ApprovalRequest,\n type PrepareErc20TransferRequest,\n type PrepareErc1155ApprovalForAllRequest,\n type PrepareMergePositionsRequest,\n type PrepareRedeemPositionsRequest,\n type PrepareSplitPositionRequest,\n redeemPositions,\n setupTradingApprovals,\n splitPosition,\n transferErc20,\n} from '../actions';\nimport type { BaseSecureClient } from '../clients';\nimport type { TransactionHandle } from '../types';\n\nexport type SecureWalletActions = {\n /**\n * Checks whether the authenticated account wallet is ready for gasless transactions.\n *\n * @throws {@link IsGaslessReadyError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const ready = await client.isGaslessReady();\n * ```\n */\n isGaslessReady(): Promise<boolean>;\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 * const handle = await client.setupTradingApprovals();\n *\n * const outcome = await handle.wait();\n *\n * // outcome.transactionHash: TxHash\n * ```\n */\n setupTradingApprovals(): Promise<TransactionHandle>;\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.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 market positions.\n *\n * @throws {@link SplitPositionError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const handle = await client.splitPosition({\n * amount: 1n,\n * conditionId:\n * '0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef',\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 market positions back into collateral.\n *\n * @throws {@link MergePositionsError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const handle = await client.mergePositions({\n * amount: 'max',\n * conditionId:\n * '0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef',\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 resolved market positions.\n *\n * @throws {@link RedeemPositionsError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const handle = await client.redeemPositions({\n * conditionId:\n * '0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef',\n * });\n *\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 redeemPositions(\n request: PrepareRedeemPositionsRequest,\n ): Promise<TransactionHandle>;\n};\n\nexport function walletActions(client: BaseSecureClient): SecureWalletActions {\n return {\n isGaslessReady: isGaslessReady.bind(null, client),\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 };\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 SecureWalletActions.\nexport {\n ApproveErc20Error,\n ApproveErc1155ForAllError,\n IsGaslessReadyError,\n MergePositionsError,\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 PublicRewardsActions,\n rewardsActions,\n type SecureRewardsActions,\n} from './rewards';\nimport {\n type PublicSubscriptionsActions,\n type SecureSubscriptionsActions,\n subscriptionsActions,\n} from './subscriptions';\nimport { type SecureTradingActions, tradingActions } from './trading';\nimport { type SecureWalletActions, walletActions } from './wallet';\n\nexport type PublicActions = Prettify<\n DiscoveryActions &\n DataActions &\n AnalyticsActions &\n PublicAccountActions &\n PublicRewardsActions &\n PublicSubscriptionsActions\n>;\n\nexport type SecureActions = Prettify<\n DiscoveryActions &\n DataActions &\n AnalyticsActions &\n SecureAccountActions &\n SecureRewardsActions &\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 ...rewardsActions(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 ...rewardsActions(client),\n ...subscriptionsActions(client),\n };\n}\n\nexport * from './account';\nexport * from './analytics';\nexport * from './data';\nexport * from './discovery';\nexport * from './rewards';\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 EnvironmentConfig = {\n name: string;\n chainId: number;\n /** @internal */\n rpc: string;\n /** @internal */\n walletDerivation: WalletDerivationConfig;\n /** @internal */\n collateralToken: EvmAddress;\n /** @internal */\n conditionalTokens: EvmAddress;\n /** @internal */\n negRiskAdapter: EvmAddress;\n /** @internal */\n collateralAdapter: EvmAddress;\n /** @internal */\n negRiskCollateralAdapter: EvmAddress;\n /** @internal */\n standardExchange: EvmAddress;\n /** @internal */\n negRiskExchange: EvmAddress;\n /** @internal */\n autoRedeemOperator: EvmAddress;\n /** @internal */\n safeMultisend: EvmAddress;\n /** @internal */\n relayHub: EvmAddress;\n /** @internal */\n clob: string;\n /** @internal */\n clobMarketWs: string;\n /** @internal */\n clobUserWs: string;\n /** @internal */\n relayer: string;\n /** @internal */\n gamma: string;\n /** @internal */\n data: string;\n /** @internal */\n rtdsWs: string;\n /** @internal */\n sportsWs: string;\n /** @internal */\n relayerMaxPolls: number;\n /** @internal */\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 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 autoRedeemOperator: expectEvmAddress(\n '0xF3cFb6a6eBFeB51876289Eb235719EB1C65252B0',\n ),\n safeMultisend: expectEvmAddress('0xA238CBeb142c10Ef7Ad8442C6D1f9E89e07e7761'),\n relayHub: expectEvmAddress('0xD216153c06E857cD7f72665E0aF1d7D82172F494'),\n clob: 'https://clob.polymarket.com',\n clobMarketWs: 'wss://ws-subscriptions-clob.polymarket.com/ws/market',\n clobUserWs: 'wss://ws-subscriptions-clob.polymarket.com/ws/user',\n relayer: 'https://relayer-v2.polymarket.com',\n gamma: 'https://gamma-api.polymarket.com',\n data: 'https://data-api.polymarket.com',\n rtdsWs: 'wss://ws-live-data.polymarket.com',\n sportsWs: 'wss://sports-api.polymarket.com/ws',\n relayerMaxPolls: 100,\n relayerPollFrequencyMs: 2000,\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 { ResultAsync } from '@polymarket/types';\nimport ky, { type KyInstance } from 'ky';\nimport { RateLimitError, RequestRejectedError, TransportError } from './errors';\n\nexport type ServiceRequest = {\n method: 'DELETE' | 'GET' | 'POST';\n path: string;\n body?: string;\n headers?: HeadersInit;\n json?: unknown;\n params?: URLSearchParams;\n};\n\nexport type RequestHeadersResolver = (\n request: ServiceRequest,\n) => Promise<HeadersInit>;\n\nexport type ServiceClientConfig = {\n root: string;\n resolveHeaders?: RequestHeadersResolver;\n};\n\nexport type ServiceClientGetOptions = {\n headers?: HeadersInit;\n params?: URLSearchParams;\n};\n\nexport type ServiceClientPostOptions = {\n headers?: HeadersInit;\n json?: unknown;\n};\n\nexport type ServiceClientDeleteOptions = {\n headers?: HeadersInit;\n json?: unknown;\n params?: URLSearchParams;\n};\n\n/**\n * Internal wrapper around a service-scoped `ky` instance.\n */\nexport class ServiceClient {\n readonly #client: KyInstance;\n readonly #resolveHeaders?: RequestHeadersResolver;\n\n constructor({ root, resolveHeaders }: ServiceClientConfig) {\n this.#client = ky.create({ prefixUrl: root, throwHttpErrors: false });\n this.#resolveHeaders = resolveHeaders;\n }\n\n get(\n path: string,\n options: ServiceClientGetOptions = {},\n ): ResultAsync<\n Response,\n RateLimitError | RequestRejectedError | TransportError\n > {\n return this.#request('GET', path, options);\n }\n\n post(\n path: string,\n options: ServiceClientPostOptions = {},\n ): ResultAsync<\n Response,\n RateLimitError | RequestRejectedError | TransportError\n > {\n return this.#request('POST', path, options);\n }\n\n del(\n path: string,\n options: ServiceClientDeleteOptions = {},\n ): ResultAsync<\n Response,\n RateLimitError | RequestRejectedError | TransportError\n > {\n return this.#request('DELETE', path, options);\n }\n\n #normalizePath(path: string) {\n return path.startsWith('/') ? path.slice(1) : path;\n }\n\n #request(\n method: ServiceRequest['method'],\n path: string,\n options:\n | ServiceClientDeleteOptions\n | ServiceClientGetOptions\n | ServiceClientPostOptions,\n ): ResultAsync<\n Response,\n RateLimitError | RequestRejectedError | TransportError\n > {\n return this.#toResult(this.#send(method, path, options));\n }\n\n async #send(\n method: ServiceRequest['method'],\n path: string,\n options:\n | ServiceClientDeleteOptions\n | ServiceClientGetOptions\n | ServiceClientPostOptions,\n ): Promise<Response> {\n const request = this.#createRequest(method, path, options);\n const resolvedHeaders = await this.#resolveHeaders?.(request);\n const headers = this.#mergeHeaders(request.headers, resolvedHeaders);\n\n if (request.body !== undefined && !headers.has('content-type')) {\n headers.set('content-type', 'application/json');\n }\n\n return this.#client(this.#normalizePath(path), {\n body: request.body,\n headers,\n method,\n searchParams: request.params,\n });\n }\n\n #createRequest(\n method: ServiceRequest['method'],\n path: string,\n options:\n | ServiceClientDeleteOptions\n | ServiceClientGetOptions\n | ServiceClientPostOptions,\n ): ServiceRequest {\n return {\n body: 'json' in options ? this.#serializeJson(options.json) : undefined,\n headers: options.headers,\n json: 'json' in options ? options.json : undefined,\n method,\n params: 'params' in options ? options.params : undefined,\n path,\n };\n }\n\n #serializeJson(json: unknown): string | undefined {\n if (json === undefined) {\n return undefined;\n }\n\n return JSON.stringify(json);\n }\n\n #mergeHeaders(...sources: Array<HeadersInit | undefined>): Headers {\n const headers = new Headers();\n\n for (const source of sources) {\n if (source === undefined) {\n continue;\n }\n\n for (const [key, value] of new Headers(source).entries()) {\n headers.set(key, value);\n }\n }\n\n return headers;\n }\n\n #toResult(\n promise: Promise<Response>,\n ): ResultAsync<\n Response,\n | RateLimitError\n | RequestRejectedError\n | RequestRejectedError\n | TransportError\n > {\n return ResultAsync.fromPromise(\n promise.then(async (response) => {\n if (response.ok) {\n return response;\n }\n\n if (response.status === 429) {\n throw new RateLimitError(\n `Request to ${response.url} was rate limited`,\n );\n }\n\n const message = await this.#extractResponseErrorMessage(response);\n throw new RequestRejectedError(message, {\n status: response.status,\n });\n }),\n (error) => {\n if (\n error instanceof RateLimitError ||\n error instanceof RequestRejectedError\n ) {\n return error;\n }\n\n return TransportError.fromError(error);\n },\n );\n }\n\n async #extractResponseErrorMessage(response: Response) {\n const contentType = response.headers.get('content-type')?.toLowerCase();\n\n if (contentType?.includes('application/json')) {\n const { error } = await response\n .clone()\n .json()\n .catch(() => ({}));\n if (error) return `${String(error)} (${response.url})`;\n }\n\n if (contentType?.includes('text/plain')) {\n const text = await response\n .clone()\n .text()\n .then(\n (body) => body.trim(),\n () => '',\n );\n\n if (text) {\n return `${text} (${response.url})`;\n }\n }\n\n const server = response.headers.get('server')?.toLowerCase();\n if (server?.includes('cloudflare')) {\n return `Request to ${response.url} was blocked by Cloudflare with status ${response.status}`;\n }\n\n if (\n contentType?.includes('text/html') ||\n contentType?.includes('application/xhtml+xml')\n ) {\n return `Request to ${response.url} failed with status ${response.status} and an unexpected HTML response body`;\n }\n\n return `Request to ${response.url} failed with status ${response.status} and unreadable response body`;\n }\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 { setNonBlockingInterval } from '@polymarket/types';\nimport type { WebSocketHeartbeat } from './lifecycle';\n\nconst CLOB_HEARTBEAT_INTERVAL_MS = 10_000;\nconst CLOB_HEARTBEAT_STALE_MS = 30_000;\nconst RTDS_HEARTBEAT_INTERVAL_MS = 5_000;\nconst RTDS_HEARTBEAT_STALE_MS = 10 * 60_000;\nconst SPORTS_HEARTBEAT_STALE_MS = 30_000;\n\nexport class ClobWebSocketHeartbeat implements WebSocketHeartbeat {\n #lastPongAt = 0;\n #timer: ReturnType<typeof setInterval> | undefined;\n\n start(send: (message: string) => void): void {\n this.stop();\n this.#lastPongAt = Date.now();\n this.#timer = setNonBlockingInterval(() => {\n send('PING');\n }, CLOB_HEARTBEAT_INTERVAL_MS);\n }\n\n handleMessage(message: string): boolean {\n if (message !== 'PONG') return false;\n this.#lastPongAt = Date.now();\n return true;\n }\n\n isStale(now: number): boolean {\n return now - this.#lastPongAt > CLOB_HEARTBEAT_STALE_MS;\n }\n\n stop(): void {\n if (this.#timer !== undefined) {\n clearInterval(this.#timer);\n this.#timer = undefined;\n }\n }\n}\n\nexport class RtdsWebSocketHeartbeat implements WebSocketHeartbeat {\n #lastMessageAt = 0;\n #timer: ReturnType<typeof setInterval> | undefined;\n\n start(send: (message: string) => void): void {\n this.stop();\n this.#lastMessageAt = Date.now();\n this.#timer = setNonBlockingInterval(() => {\n send('PING');\n }, RTDS_HEARTBEAT_INTERVAL_MS);\n }\n\n handleMessage(): boolean {\n this.#lastMessageAt = Date.now();\n return false;\n }\n\n isStale(now: number): boolean {\n return now - this.#lastMessageAt > RTDS_HEARTBEAT_STALE_MS;\n }\n\n stop(): void {\n if (this.#timer !== undefined) {\n clearInterval(this.#timer);\n this.#timer = undefined;\n }\n }\n}\n\nexport class SportsWebSocketHeartbeat implements WebSocketHeartbeat {\n #lastPingAt = 0;\n #send: ((message: string) => void) | undefined;\n\n start(send: (message: string) => void): void {\n this.#lastPingAt = Date.now();\n this.#send = send;\n }\n\n stop(): void {\n this.#send = undefined;\n }\n\n handleMessage(message: string): boolean {\n if (message !== 'ping') return false;\n this.#lastPingAt = Date.now();\n this.#send?.('pong');\n return true;\n }\n\n isStale(now: number): boolean {\n return now - this.#lastPingAt > SPORTS_HEARTBEAT_STALE_MS;\n }\n}\n","import {\n setNonBlockingInterval,\n setNonBlockingTimeout,\n} from '@polymarket/types';\nimport { TransportError } from '../errors';\n\nexport type WebSocketHeartbeat = {\n handleMessage(message: string): boolean;\n isStale(now: number): boolean;\n start(send: (message: string) => void): void;\n stop(): void;\n};\n\nconst HEARTBEAT_WATCHDOG_INTERVAL_MS = 5_000;\nconst RECONNECT_BASE_DELAY_MS = 250;\nconst RECONNECT_MAX_DELAY_MS = 30_000;\n\nexport type ScheduleReconnectOptions = {\n shouldReconnect: () => boolean;\n reconnect: () => Promise<unknown>;\n};\n\nexport type WebSocketConnectionOptions<TContext = undefined> = {\n onClose: () => void;\n onError: () => void;\n onMessage: (message: unknown) => void;\n onOpen: (context: TContext) => void;\n prepare?: () => TContext | Promise<TContext>;\n url: string;\n};\n\nexport type WebSocketConnectionResult = {\n reusedOpenSocket: boolean;\n};\n\nexport type WebSocketConnectionConstructorOptions = {\n heartbeat: WebSocketHeartbeat;\n};\n\nexport class ReconnectScheduler {\n #timer: ReturnType<typeof setTimeout> | undefined;\n #attempt = 0;\n\n schedule(options: ScheduleReconnectOptions): void {\n if (this.#timer !== undefined || !options.shouldReconnect()) {\n return;\n }\n\n const delay = reconnectDelay(this.#attempt, {\n baseMs: RECONNECT_BASE_DELAY_MS,\n maxMs: RECONNECT_MAX_DELAY_MS,\n });\n this.#attempt += 1;\n this.#timer = setNonBlockingTimeout(() => {\n this.#timer = undefined;\n void this.#reconnect(options);\n }, delay);\n }\n\n stop(): void {\n if (this.#timer !== undefined) {\n clearTimeout(this.#timer);\n this.#timer = undefined;\n }\n }\n\n resetBackoff(): void {\n this.#attempt = 0;\n this.stop();\n }\n\n async #reconnect(options: ScheduleReconnectOptions): Promise<void> {\n if (!options.shouldReconnect()) return;\n try {\n await options.reconnect();\n } catch {\n this.schedule(options);\n }\n }\n}\n\nexport class WebSocketConnection {\n readonly #heartbeat: WebSocketHeartbeat;\n #socket: WebSocket | undefined;\n #connecting: Promise<WebSocketConnectionResult> | undefined;\n #watchdog: ReturnType<typeof setInterval> | undefined;\n\n constructor(options: WebSocketConnectionConstructorOptions) {\n this.#heartbeat = options.heartbeat;\n }\n\n connect<TContext = undefined>(\n options: WebSocketConnectionOptions<TContext>,\n ): Promise<WebSocketConnectionResult> {\n const socket = this.#socket;\n if (socket?.readyState === WebSocket.OPEN) {\n return Promise.resolve({ reusedOpenSocket: true });\n }\n this.#clearCurrentSocket();\n if (this.#connecting !== undefined) return this.#connecting;\n\n const connecting = this.#open(options)\n .then(() => ({ reusedOpenSocket: false }))\n .catch((error: unknown) => {\n if (this.#connecting === connecting) {\n this.#connecting = undefined;\n }\n throw error;\n });\n this.#connecting = connecting;\n return connecting;\n }\n\n send(message: unknown): boolean {\n return this.#sendRaw(JSON.stringify(message));\n }\n\n #sendRaw(message: string): boolean {\n // Reconnects and shutdown can race with protocol updates; callers use the\n // boolean result only when they need to know whether the frame was sent.\n if (this.#socket?.readyState !== WebSocket.OPEN) return false;\n this.#socket.send(message);\n return true;\n }\n\n async close(): Promise<void> {\n const socket = await this.#takeCurrent();\n this.#stopHeartbeat();\n if (socket === undefined || socket.readyState === WebSocket.CLOSED) return;\n\n await new Promise<void>((resolve) => {\n socket.addEventListener('close', () => resolve(), { once: true });\n if (socket.readyState !== WebSocket.CLOSING) {\n socket.close();\n }\n });\n }\n\n async #open<TContext>(\n options: WebSocketConnectionOptions<TContext>,\n ): Promise<WebSocket> {\n const context = await options.prepare?.();\n\n return new Promise<WebSocket>((resolve, reject) => {\n const socket = new WebSocket(options.url);\n\n const onOpen = () => {\n socket.removeEventListener('error', onOpenError);\n this.#markOpen(socket);\n this.#startHeartbeat();\n options.onOpen(context as TContext);\n resolve(socket);\n };\n const onOpenError = (event: Event) => {\n socket.removeEventListener('open', onOpen);\n reject(\n new TransportError(`WebSocket connection failed: ${options.url}`, {\n cause: event,\n }),\n );\n };\n\n socket.addEventListener('open', onOpen, { once: true });\n socket.addEventListener('error', onOpenError, { once: true });\n socket.addEventListener('message', (event) => {\n if (this.#socket !== socket) return;\n const message = String(event.data);\n if (this.#heartbeat.handleMessage(message)) return;\n\n let raw: unknown;\n try {\n raw = JSON.parse(message);\n } catch {\n return;\n }\n options.onMessage(raw);\n });\n socket.addEventListener('close', () => {\n if (this.#socket !== socket) return;\n this.#clearCurrentSocket();\n options.onClose();\n });\n socket.addEventListener('error', () => options.onError());\n });\n }\n\n #markOpen(socket: WebSocket): void {\n this.#socket = socket;\n this.#connecting = undefined;\n }\n\n #clearCurrentSocket(): void {\n this.#stopHeartbeat();\n this.#socket = undefined;\n }\n\n #startHeartbeat(): void {\n this.#stopHeartbeat();\n this.#heartbeat.start((message) => this.#sendRaw(message));\n this.#watchdog = setNonBlockingInterval(() => {\n if (!this.#heartbeat.isStale(Date.now())) return;\n const socket = this.#socket;\n if (socket?.readyState === WebSocket.OPEN) {\n // Let the normal close path reconnect and resubscribe active handles.\n socket.close();\n }\n }, HEARTBEAT_WATCHDOG_INTERVAL_MS);\n }\n\n #stopHeartbeat(): void {\n if (this.#watchdog !== undefined) {\n clearInterval(this.#watchdog);\n this.#watchdog = undefined;\n }\n this.#heartbeat.stop();\n }\n\n async #takeCurrent(): Promise<WebSocket | undefined> {\n const socket = this.#socket;\n const connecting = this.#connecting;\n\n this.#socket = undefined;\n this.#connecting = undefined;\n\n if (socket !== undefined) return socket;\n return connecting?.then(\n () => this.#socket,\n () => undefined,\n );\n }\n}\n\ntype ReconnectDelayOptions = {\n baseMs: number;\n maxMs: number;\n};\n\nfunction reconnectDelay(\n attempt: number,\n options: ReconnectDelayOptions,\n): number {\n const exponentialDelay = Math.min(\n options.baseMs * 2 ** attempt,\n options.maxMs,\n );\n return Math.random() * exponentialDelay;\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 tokenId of subscription.tokenIds) assets.add(tokenId);\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 return {\n auth: {\n apiKey: credentials.key,\n passphrase: credentials.passphrase,\n secret: credentials.secret,\n },\n markets: subscription.markets,\n type: 'user',\n };\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 return (event) => {\n switch (event.type) {\n case 'price_change':\n return event.payload.priceChanges.some((change) =>\n subscription.tokenIds.includes(change.tokenId),\n );\n case 'new_market':\n return subscription.customFeatureEnabled === true;\n case 'market_resolved':\n return (\n subscription.customFeatureEnabled === true &&\n (event.payload.tokenIds ?? []).some((tokenId) =>\n subscription.tokenIds.includes(tokenId),\n )\n );\n case 'best_bid_ask':\n return (\n subscription.customFeatureEnabled === true &&\n subscription.tokenIds.includes(event.payload.tokenId)\n );\n default:\n return subscription.tokenIds.includes(event.payload.tokenId);\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 { WebSocketManager } 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 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 WebSocketManager<MarketSubscription, MarketEvent>\n{\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.#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 onClose: () => this.#onConnectionClose(),\n onError: () => this.#onConnectionError(),\n onMessage: (message) => this.#onConnectionMessage(message),\n onOpen: () => this.#onConnectionOpen(),\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 #onConnectionClose(): 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 { WebSocketManager } from '../types';\nimport {\n buildUserSubscribeMessage,\n deriveUserServerSubscription,\n syncUserSubscription,\n type UserServerSubscription,\n type UserSubscriptionEntry,\n userMatcherFor,\n} from './protocol';\n\ntype ApiKeyCredsProvider = () => ApiKeyCreds;\n\nexport type ClobUserWebSocketManagerOptions = {\n resolveCredentials: ApiKeyCredsProvider;\n url: string;\n};\n\nexport class ClobUserWebSocketManager\n implements WebSocketManager<UserSubscription, UserEvent>\n{\n readonly #url: string;\n readonly #resolveCredentials: ApiKeyCredsProvider;\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.#url = options.url;\n this.#resolveCredentials = options.resolveCredentials;\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 onClose: () => this.#onConnectionClose(),\n onError: () => this.#onConnectionError(),\n onMessage: (message) => this.#onConnectionMessage(message),\n onOpen: (credentials) => this.#onConnectionOpen(credentials),\n prepare: () => this.#resolveCredentials(),\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 #onConnectionClose(): 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 {\n type CommentsEvent,\n type CryptoPricesEvent,\n type EquityPricesEvent,\n RealtimeEventSchema,\n} from '@polymarket/bindings/subscriptions';\nimport { invariant } from '@polymarket/types';\nimport type {\n CommentsSubscription,\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 { WebSocketManager } from './types';\n\ntype RtdsSpec =\n | CommentsSubscription\n | CryptoPricesSubscription\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\n/**\n * Realtime Data Service (RTDS) WebSocket manager.\n *\n * Implements {@link WebSocketManager} 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 WebSocketManager<RtdsSpec, RtdsEvent>\n{\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(url: string) {\n this.#url = 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 onClose: () => this.#onConnectionClose(),\n onError: () => this.#onConnectionError(),\n onMessage: (message) => this.#onConnectionMessage(message),\n onOpen: () => this.#onConnectionOpen(),\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 #onConnectionClose(): 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.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 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.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 { WebSocketManager } from './types';\n\ntype SportsSubscriptionEntry = SubscriptionRegistryEntry<\n SportsSubscription,\n SportsEvent\n>;\n\nexport type SportsWebSocketManagerOptions = {\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 WebSocketManager<SportsSubscription, SportsEvent>\n{\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.#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 onClose: () => this.#onConnectionClose(),\n onError: () => this.#onConnectionError(),\n onMessage: (message) => this.#onConnectionMessage(message),\n onOpen: () => this.#onConnectionOpen(),\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 #onConnectionClose(): 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 IsGaslessReadyError,\n isGaslessReady,\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 { 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 deriveCurrentDepositWalletAddress,\n resolveAccountIdentity,\n} from './wallet';\nimport {\n ClobMarketWebSocketManager,\n ClobUserWebSocketManager,\n type PublicWebSocketManagers,\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 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 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 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 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().positive().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};\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 data: new ServiceClient({ root: config.environment.data }),\n gamma: new ServiceClient({ root: config.environment.gamma }),\n clob: new ServiceClient({\n root: config.environment.clob,\n resolveHeaders: (request) => this.resolveClobHeaders(request),\n }),\n relayer: new ServiceClient({\n root: config.environment.relayer,\n resolveHeaders: (request) => this.resolveRelayerHeaders(request),\n }),\n rpc: new JsonRpcClient({ url: config.environment.rpc }),\n webSockets: {\n clobMarket: new ClobMarketWebSocketManager({\n url: config.environment.clobMarketWs,\n }),\n sports: new SportsWebSocketManager({\n url: config.environment.sportsWs,\n }),\n rtds: new RtdsWebSocketManager(config.environment.rtdsWs),\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 ]).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 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 signer: config.signer,\n clob: new ServiceClient({\n root: config.environment.clob,\n resolveHeaders: (request) => this.resolveClobHeaders(request),\n }),\n relayer: new ServiceClient({\n root: config.environment.relayer,\n resolveHeaders: (request) => this.resolveRelayerHeaders(request),\n }),\n rpc: new JsonRpcClient({ url: config.environment.rpc }),\n gamma: new ServiceClient({ root: config.environment.gamma }),\n data: new ServiceClient({ root: config.environment.data }),\n secureClob: new ServiceClient({\n resolveHeaders: async (request) => ({\n ...(await this.resolveClobHeaders(request)),\n ...(await this.#createL2Headers(request)),\n }),\n root: config.environment.clob,\n }),\n webSockets: {\n clobMarket: new ClobMarketWebSocketManager({\n url: config.environment.clobMarketWs,\n }),\n clobUser: new ClobUserWebSocketManager({\n resolveCredentials: () => this.credentials,\n url: config.environment.clobUserWs,\n }),\n sports: new SportsWebSocketManager({\n url: config.environment.sportsWs,\n }),\n rtds: new RtdsWebSocketManager(config.environment.rtdsWs),\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 invariant(\n this.context.signer !== undefined,\n 'Secure client does not have a signer. Create secure clients with createSecureClient to use wallet-interactive methods.',\n );\n\n return this.context.signer;\n }\n\n /**\n * Sets up a gasless wallet and returns a secure client bound to it.\n *\n * @remarks\n * If this client is already bound to a gasless wallet, this returns a secure\n * client for the current wallet. For EOA clients, this deploys or reuses the\n * authenticated signer's deterministic Deposit Wallet.\n *\n * @throws {@link SetupGaslessWalletError}\n * Thrown on failure.\n */\n async setupGaslessWallet(): Promise<\n SecureClient<TPublicActions, TSecureActions>\n > {\n const signerAddress = expectEvmAddress(await this.signer.getAddress());\n\n invariant(\n isSameEvmAddress(signerAddress, this.account.signer),\n 'The current signer address does not match the authenticated signer for this client.',\n );\n\n if (this.account.walletType !== WalletType.EOA) {\n return this.#createSecureClientForWallet(\n this.account.wallet,\n signerAddress,\n );\n }\n\n const depositWallet = await deriveCurrentDepositWalletAddress(\n this.rpc,\n signerAddress,\n this.environment.walletDerivation,\n );\n\n if (\n await isGaslessReady(this, {\n wallet: depositWallet,\n type: WalletType.DEPOSIT_WALLET,\n })\n ) {\n return this.#createSecureClientForWallet(depositWallet, signerAddress);\n }\n\n const handle = await deployDepositWallet(this);\n await handle.wait();\n\n return this.#createSecureClientForWallet(depositWallet, signerAddress);\n }\n\n #createSecureClientForWallet(\n wallet: AccountIdentity['wallet'],\n signerAddress: AccountIdentity['signer'],\n ): SecureClient<TPublicActions, TSecureActions> {\n const client = new BaseSecureClient<TPublicActions, TSecureActions>({\n account: resolveAccountIdentity(this.environment, signerAddress, wallet),\n apiKey: this.context.apiKey,\n credentials: this.credentials,\n environment: this.environment,\n signer: this.context.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 /** @internal */\n get secureClob(): ServiceClient {\n return this.context.secureClob;\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.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 { apiKey, environment } = this.context;\n\n try {\n await deleteApiKey(this);\n } finally {\n this.endAuthenticationLifecycle();\n await closingSubscriptions;\n }\n\n const client = new BasePublicClient({\n apiKey,\n environment,\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 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 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\nexport type SecureClientOptions = PublicClientOptions & {\n /**\n * Wallet address to use as the account wallet.\n *\n * If omitted, the client uses the signer address as the account wallet and\n * operates as an EOA account. EOA clients do not use gasless relayer flows:\n * approvals, transfers, and other wallet operations are submitted directly by\n * the signer and require the signer wallet to hold gas. Pass a supported Poly\n * Deposit Wallet, Poly Safe, or Poly Proxy wallet address to use that wallet\n * as the account/funder and enable gasless wallet operations when an API key\n * strategy supports them.\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 }).extend(allActions);\n}\n\nexport type CreateSecureClientError =\n | CancelledSigningError\n | RateLimitError\n | RequestRejectedError\n | SigningError\n | TransportError\n | UnexpectedResponseError\n | UserInputError;\nexport const CreateSecureClientError = makeErrorGuard(\n CancelledSigningError,\n RateLimitError,\n RequestRejectedError,\n SigningError,\n TransportError,\n UnexpectedResponseError,\n UserInputError,\n);\n\nexport type SetupGaslessWalletError =\n | DeployDepositWalletError\n | IsGaslessReadyError\n | SigningError\n | WaitForGaslessTransactionError\n | UserInputError;\nexport const SetupGaslessWalletError = makeErrorGuard(\n RateLimitError,\n RequestRejectedError,\n SigningError,\n TimeoutError,\n TransactionFailedError,\n TransportError,\n UnexpectedResponseError,\n UserInputError,\n);\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 });\n const wallet = options.wallet ?? (await options.signer.getAddress());\n\n return 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"]}
|
|
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/rewards.ts","../src/decorators/rfq.ts","../src/decorators/subscriptions.ts","../src/decorators/trading.ts","../src/decorators/wallet.ts","../src/decorators/index.ts","../src/environments.ts","../src/hmac.ts","../src/ServiceClient.ts","../src/websockets/handle.ts","../src/websockets/heartbeat.ts","../src/websockets/lifecycle.ts","../src/websockets/registry.ts","../src/websockets/clob/protocol.ts","../src/websockets/clob/market.ts","../src/websockets/clob/user.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","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","fetchMarket","fetchMarketTags","listSeries","fetchSeries","listTags","fetchTag","fetchRelatedTags","fetchRelatedTagResources","search","listSports","fetchSportsMarketTypes","listTeams","fetchPublicProfile","listComments","fetchCommentsById","listCommentsByUserAddress","publicRewardsActions","listCurrentRewards","listMarketRewards","rewardsActions","fetchOrderScoring","fetchOrdersScoring","listUserEarningsForDay","fetchTotalEarningsForUserForDay","listUserEarningsAndMarketsConfig","fetchRewardPercentages","rfqActions","openRfqSession","subscriptionsActions","subscriptions","subscribe","tradingActions","createMarketOrder","placeMarketOrder","createLimitOrder","placeLimitOrder","postOrder","postOrders","cancelOrder","cancelOrders","cancelAll","cancelMarketOrders","listOpenOrders","fetchOrder","walletActions","setupTradingApprovals","approveErc20","approveErc1155ForAll","transferErc20","splitPosition","mergePositions","redeemPositions","allActions","production","expectEvmAddress","preproduction","buildHmacSignature","secret","timestamp","method","requestPath","body","message","cryptoKey","base64ToArrayBuffer","signature","toUrlSafeBase64","arrayBufferToBase64","base64","sanitizedBase64","binaryString","bytes","index","buffer","binary","byte","value","ServiceClient","#client","root","resolveHeaders","ky","path","options","#request","#normalizePath","#toResult","#send","#createRequest","#mergeHeaders","#serializeJson","json","sources","source","key","promise","ResultAsync","RateLimitError","#extractResponseErrorMessage","RequestRejectedError","TransportError","contentType","text","createSubscriptionHandle","queue","closeSubscription","closing","CLOB_HEARTBEAT_INTERVAL_MS","CLOB_HEARTBEAT_STALE_MS","RTDS_HEARTBEAT_INTERVAL_MS","RTDS_HEARTBEAT_STALE_MS","SPORTS_HEARTBEAT_STALE_MS","ClobWebSocketHeartbeat","#lastPongAt","#timer","send","setNonBlockingInterval","now","RtdsWebSocketHeartbeat","#lastMessageAt","SportsWebSocketHeartbeat","#lastPingAt","HEARTBEAT_WATCHDOG_INTERVAL_MS","RECONNECT_BASE_DELAY_MS","RECONNECT_MAX_DELAY_MS","ReconnectScheduler","#attempt","delay","reconnectDelay","setNonBlockingTimeout","#reconnect","WebSocketConnection","#heartbeat","#socket","#connecting","#watchdog","#clearCurrentSocket","connecting","#open","#sendRaw","socket","#takeCurrent","#stopHeartbeat","resolve","context","reject","createWebSocket","onOpen","onOpenError","#markOpen","#startHeartbeat","event","raw","heartbeat","url","cause","attempt","exponentialDelay","SubscriptionRegistry","#entries","#deriveServerState","subscription","subscriber","pushable","entry","#addEntry","before","syncMarketSubscription","after","addedAssets","difference","removedAssets","buildMarketSubscribeUpdate","firstActiveAsset","buildMarketUnsubscribeUpdate","syncUserSubscription","buildUserUnsubscribeUpdate","buildUserSubscribeUpdate","addedMarkets","removedMarkets","deriveMarketServerSubscription","entries","assets","customFeatureEnabled","tokenId","deriveUserServerSubscription","includeAllMarkets","markets","isAllMarketsUserSubscription","market","buildMarketSubscribeMessage","assetsIds","buildUserSubscribeMessage","credentials","marketMatcherFor","change","userMatcherFor","left","right","rightSet","ClobMarketWebSocketManager","#url","#closing","#connection","#reconnectScheduler","#subscriptions","#registerSubscriber","#closeSubscriber","#connect","#shutdown","#onConnectionClose","#onConnectionError","#onConnectionMessage","#onConnectionOpen","#sendInitialSubscription","events","eventData","parsed","MarketEventSchema","#scheduleReconnect","ClobUserWebSocketManager","#credentials","UserEventSchema","toQuoteRequestEvent","controller","toConfirmationRequestEvent","rfqId","quoteId","RfqConfirmationDecision","toQuoteAck","toQuoteCancelAck","toConfirmationAck","createAuthMessage","account","identity","resolveOrderIdentity","createQuoteMessage","quote","createQuoteCancelMessage","createConfirmationResponseMessage","decision","PendingResponses","#pending","#timeoutMs","timeoutMs","timeoutMessage","pending","createPending","timeout","TimeoutError","remaining","resolvePromise","rejectPromise","BYTES32_ZERO","signRfqQuoteOrder","params","order","toBaseUnits","makerAmount","generateOrderSalt","encodeOrderSide","takerAmount","createExchangeOrderTypedDataPayload","createRfqExchangeDomain","createExchangeOrderSignature","side","price","size","OrderSide","DecimalishToBigIntSchema","DecimalishSchema","decimalToScaledInteger","RfqQuoteResponseSchema","parseRfqQuoteResponse","parseUserInput","createRfqQuote","defaultQuoteSize","signedOrder","quoteOrderPrice","quoteOrderSide","quoteOrderTokenId","RfqDirection","requestedSize","RfqRequestedSizeUnit","match","UserInputError","whole","fraction","scaledValue","AUTH_TIMEOUT_MS","ACK_TIMEOUT_MS","RfqQuoterWebSocketManager","#account","#chainId","#exchange","#headers","#signer","#session","#connectingSession","session","RfqWebSocketSession","#clearSession","connectingSession","#onClose","#queue","#auth","auth","authTimeout","#handleClose","#handleMessage","#sendAuthMessage","#shutdownWithError","#fail","#failPending","rawMessage","RfqKnownInboundMessageSchema","RfqQuoterInboundMessageSchema","#handleAuthMessage","quoteAckKey","quoteCancelAckKey","confirmationAckKey","#handleRfqError","RfqQuoteRejectedError","RfqCancelQuoteRejectedError","RfqConfirmationRejectedError","parsedResponse","reference","RtdsWebSocketManager","deriveRtdsServerState","matcherFor","subscriptionsToOpen","serverSubscriptionsAdded","#sendSubscribeFrame","subscriptionsToClose","serverSubscriptionsRemoved","#sendUnsubscribeFrame","#resubscribeActiveServerEntries","RealtimeEventSchema","buildSubscribeMessage","buildUnsubscribeMessage","activeByKey","serverSubscription","serverSubscriptionsFor","topic","type","invariant","SportsWebSocketManager","SportsResultEventSchema","AbstractClient","#context","#decorators","decorator","BeginAuthenticationCredentialsSchema","ApiKeySchema","BeginAuthenticationRequestSchema","EvmAddressSchema","BasePublicClient","JsonRpcClient","signer","nonce","signerAddress","requestAddress","wallet","resolveAccountIdentity","#createSecureClient","fetchApiKeys","createOrDeriveApiKey","expectEvmSignature","BaseSecureClient","#hasEndedAuthentication","#createL2Headers","closingSubscriptions","apiKey","environment","deleteApiKey","createPublicClient","CreateSecureClientError","makeErrorGuard","CancelledSigningError","TransactionFailedError","UnexpectedResponseError","SetupGaslessWalletError","createSecureClient","resolveRequestedWallet","secureClient","authenticateWith","WalletType","isWalletDeployed","deployDefaultDepositWallet","deriveCurrentDepositWalletAddress","currentDepositWallet","isSameEvmAddress","deployDepositWallet"],"mappings":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,CACiB,CACjB,GAAIA,CAAAA,CAAQ,MAAA,GAAW,MAAA,CACrB,OAAOA,CAAAA,CAAQ,MAAA,CAGjB,IAAMqR,CAAAA,CAAgBlT,gBAAAA,CAAiB,MAAM6B,CAAAA,CAAQ,MAAA,CAAO,UAAA,EAAY,CAAA,CAExE,OAAOkT,CAAAA,CACLhb,CAAAA,CAAO,GAAA,CACPmZ,CAAAA,CACAnZ,CAAAA,CAAO,WAAA,CAAY,gBACrB,CACF,CAQA,eAAe+a,EAAAA,CACbJ,CAAAA,CACe,CACf,IAAMM,CAAAA,CAAuB,MAAMD,CAAAA,CACjCL,CAAAA,CAAa,GAAA,CACbA,CAAAA,CAAa,OAAA,CAAQ,MAAA,CACrBA,CAAAA,CAAa,WAAA,CAAY,gBAC3B,CAAA,CAEA,GAAI,CAACO,gBAAAA,CAAiBP,CAAAA,CAAa,OAAA,CAAQ,MAAA,CAAQM,CAAoB,CAAA,CACrE,MAAM,IAAIzG,CAAAA,CACR,CAAA,OAAA,EAAUmG,CAAAA,CAAa,OAAA,CAAQ,MAAM,CAAA,4CAAA,EAA+CM,CAAoB,CAAA,gDAAA,CAC1G,CAAA,CAIF,KAAA,CADe,MAAME,EAAAA,CAAoBR,CAAY,CAAA,EACxC,IAAA,GACf","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 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 ListComboPositionsRequest,\n type ListMarketPositionsRequest,\n type ListPositionsRequest,\n listAccountTrades,\n listActivity,\n listClosedPositions,\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?: TRequest['user'];\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>;\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 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 * @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>;\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 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 * @throws {@link ListActivityError}\n * Thrown on failure.\n */\n listActivity(request?: SecureListActivityRequest): Paginated<Activity[]>;\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 *\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 };\n}\n\nfunction withAccountWallet<TRequest extends { user?: string }>(\n client: BaseSecureClient,\n request: TRequest = {} as TRequest,\n): Omit<TRequest, 'user'> & { user: string } {\n return {\n ...request,\n user: request.user ?? client.account.wallet,\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 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 ListComboPositionsError,\n ListMarketPositionsError,\n ListPositionsError,\n} from '../actions';\nexport { ComboPositionStatus } 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 {\n LastTradePrice,\n LastTradePriceForToken,\n OrderBook,\n PriceHistoryPoint,\n Prices,\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 a token.\n *\n * @throws {@link FetchMidpointError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const midpoint = await client.fetchMidpoint({ tokenId: '123' });\n * ```\n */\n fetchMidpoint(request: FetchMidpointRequest): Promise<string>;\n /**\n * Fetches midpoint prices for multiple tokens.\n *\n * @throws {@link FetchMidpointsError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const midpoints = await client.fetchMidpoints([{ tokenId: '123' }]);\n * ```\n */\n fetchMidpoints(\n request: FetchMidpointsRequest,\n ): Promise<Record<string, string>>;\n /**\n * Fetches the current quoted price for a token and side.\n *\n * @throws {@link FetchPriceError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const price = await client.fetchPrice({ tokenId: '123', side: OrderSide.BUY });\n * ```\n */\n fetchPrice(request: FetchPriceRequest): Promise<string>;\n /**\n * Fetches quoted prices for multiple tokens.\n *\n * @throws {@link FetchPricesError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const prices = await client.fetchPrices([{ tokenId: '123', side: OrderSide.BUY }]);\n * ```\n */\n fetchPrices(request: FetchPricesRequest): Promise<Prices>;\n /**\n * Fetches the current order book for a token.\n *\n * @throws {@link FetchOrderBookError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const book = await client.fetchOrderBook({ tokenId: '123' });\n * ```\n */\n fetchOrderBook(request: FetchOrderBookRequest): Promise<OrderBook>;\n /**\n * Fetches order books for multiple tokens.\n *\n * @throws {@link FetchOrderBooksError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const books = await client.fetchOrderBooks([{ tokenId: '123' }]);\n * ```\n */\n fetchOrderBooks(request: FetchOrderBooksRequest): Promise<OrderBook[]>;\n /**\n * Fetches the spread for a token.\n *\n * @throws {@link FetchSpreadError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const spread = await client.fetchSpread({ tokenId: '123' });\n * ```\n */\n fetchSpread(request: FetchSpreadRequest): Promise<string>;\n /**\n * Fetches spreads for multiple tokens.\n *\n * @throws {@link FetchSpreadsError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const spreads = await client.fetchSpreads([{ tokenId: '123' }]);\n * ```\n */\n fetchSpreads(request: FetchSpreadsRequest): Promise<Record<string, string>>;\n /**\n * Fetches the last traded price for a token.\n *\n * @throws {@link FetchLastTradePriceError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const price = await client.fetchLastTradePrice({ tokenId: '123' });\n * ```\n */\n fetchLastTradePrice(\n request: FetchLastTradePriceRequest,\n ): Promise<LastTradePrice>;\n /**\n * Fetches last traded prices for multiple tokens.\n *\n * @throws {@link FetchLastTradePricesError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const prices = await client.fetchLastTradePrices([{ tokenId: '123' }]);\n * ```\n */\n fetchLastTradePrices(\n request: FetchLastTradePricesRequest,\n ): Promise<LastTradePriceForToken[]>;\n /**\n * Fetches historical price points for a token.\n *\n * @throws {@link FetchPriceHistoryError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const history = await client.fetchPriceHistory({ tokenId: '123', 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 * tokenId: '123',\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 {\n Comment,\n Event,\n Market,\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 ListCommentsByUserAddressRequest,\n type ListCommentsRequest,\n type ListEventsRequest,\n type ListMarketsRequest,\n type ListSeriesRequest,\n type ListTagsRequest,\n type ListTeamsRequest,\n listComments,\n listCommentsByUserAddress,\n listEvents,\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 * @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 * Fetches a market.\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 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 * @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 fetchMarket: fetchMarket.bind(null, client),\n fetchMarketTags: fetchMarketTags.bind(null, client),\n listSeries: listSeries.bind(null, client),\n fetchSeries: fetchSeries.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 ListCommentsByUserAddressError,\n ListCommentsError,\n ListEventsError,\n ListMarketsError,\n ListSeriesError,\n ListSportsError,\n ListTagsError,\n ListTeamsError,\n SearchError,\n} from '../actions';\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 { openRfqSession, type RfqSession } from '../actions';\nimport type { BaseSecureClient } from '../clients';\n\nexport type {\n RfqCancelQuoteAck,\n RfqCancelQuoteRejectedErrorOptions,\n RfqConfirmationAck,\n RfqConfirmationRequest,\n RfqConfirmationRequestEvent,\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 RfqSession,\n} from '../actions/rfq';\nexport {\n OpenRfqSessionError,\n RfqCancelQuoteError,\n RfqCancelQuoteRejectedError,\n RfqConfirmationDecision,\n RfqConfirmationError,\n RfqConfirmationRejectedError,\n RfqDirection,\n RfqErrorCode,\n RfqExecutionStatus,\n RfqQuoteError,\n RfqQuoteRejectedError,\n RfqRequestedSizeUnit,\n RfqSide,\n} from '../actions/rfq';\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\nexport function rfqActions(client: BaseSecureClient): SecureRfqActions {\n return {\n openRfqSession() {\n return openRfqSession(client);\n },\n };\n}\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 PublicSubscriptionsActions = {\n /**\n * Starts one or more realtime subscriptions on this client.\n *\n * @throws {@link SubscribeError}\n * Thrown when the realtime subscription cannot be established or fails.\n *\n * @example\n * ```ts\n * const handle = await client.subscribe([\n * { topic: 'market', tokenIds: ['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 the realtime subscription cannot be established or fails.\n *\n * @example\n * ```ts\n * const handle = await client.subscribe([\n * { topic: 'user' },\n * { topic: 'market', tokenIds: ['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 CancelOrdersResponse,\n OpenOrder,\n OrderResponse,\n OrderResponses,\n} from '@polymarket/bindings/clob';\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} from '../actions';\nimport type { SignedOrder } from '../actions/orders';\nimport type { BaseSecureClient } from '../clients';\nimport type { Paginated } from '../pagination';\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\n * ```ts\n * const order = await client.createMarketOrder({\n * amount: 10,\n * side: OrderSide.BUY,\n * tokenId: '123',\n * });\n * ```\n */\n createMarketOrder(request: PrepareMarketOrderRequest): Promise<SignedOrder>;\n /**\n * Creates and posts a market order for the authenticated account.\n *\n * @throws {@link PlaceMarketOrderError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const response = await client.placeMarketOrder({\n * amount: 10,\n * side: OrderSide.BUY,\n * tokenId: '123',\n * });\n *\n * // response: OrderResponse\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 60 seconds 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\n * ```ts\n * const order = await client.createLimitOrder({\n * postOnly: true,\n * price: 0.52,\n * side: OrderSide.BUY,\n * size: 10,\n * tokenId: '123',\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 60 seconds 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 * postOnly: true,\n * price: 0.52,\n * side: OrderSide.BUY,\n * size: 10,\n * tokenId: '123',\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 * 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: string[]\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: string[]\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: string[]\n * ```\n */\n cancelAll(): Promise<CancelOrdersResponse>;\n /**\n * Cancels all open orders for the authenticated account that match the market or token 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: string[]\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 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} from '../actions';\n","import {\n approveErc20,\n approveErc1155ForAll,\n type DeprecatedTransactionHandle,\n mergePositions,\n type PrepareErc20ApprovalRequest,\n type PrepareErc20TransferRequest,\n type PrepareErc1155ApprovalForAllRequest,\n type PrepareMergePositionsRequest,\n type PrepareRedeemPositionsRequest,\n type PrepareSplitPositionRequest,\n redeemPositions,\n setupTradingApprovals,\n splitPosition,\n transferErc20,\n} from '../actions';\nimport type { BaseSecureClient } from '../clients';\nimport type { TransactionHandle } from '../types';\n\nexport type SecureWalletActions = {\n /**\n * @deprecated You no longer need to call this. `createSecureClient` ensures\n * the account wallet is set up for its trading flow, so this always resolves\n * to `true` and is retained only for backward compatibility.\n */\n isGaslessReady(): Promise<boolean>;\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<DeprecatedTransactionHandle>;\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.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 market or combo 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:\n * '0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef',\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 market or combo 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:\n * '0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef',\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 resolved market or combo positions.\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:\n * '0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef',\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 combo 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\nexport function walletActions(client: BaseSecureClient): SecureWalletActions {\n return {\n isGaslessReady: () => Promise.resolve(true),\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 };\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 SecureWalletActions.\nexport {\n ApproveErc20Error,\n ApproveErc1155ForAllError,\n MergePositionsError,\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 PublicRewardsActions,\n rewardsActions,\n type SecureRewardsActions,\n} from './rewards';\nimport { rfqActions, type SecureRfqActions } from './rfq';\nimport {\n type PublicSubscriptionsActions,\n type SecureSubscriptionsActions,\n subscriptionsActions,\n} from './subscriptions';\nimport { type SecureTradingActions, tradingActions } from './trading';\nimport { type SecureWalletActions, walletActions } from './wallet';\n\nexport type PublicActions = Prettify<\n DiscoveryActions &\n DataActions &\n AnalyticsActions &\n PublicAccountActions &\n PublicRewardsActions &\n PublicSubscriptionsActions\n>;\n\nexport type SecureActions = Prettify<\n DiscoveryActions &\n DataActions &\n AnalyticsActions &\n SecureAccountActions &\n SecureRewardsActions &\n SecureRfqActions &\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 ...rewardsActions(client),\n ...rfqActions(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 ...rewardsActions(client),\n ...subscriptionsActions(client),\n };\n}\n\nexport * from './account';\nexport * from './analytics';\nexport * from './data';\nexport * from './discovery';\nexport * from './rewards';\nexport * from './rfq';\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 EnvironmentConfig = {\n name: string;\n chainId: number;\n /** @internal */\n rpc: string;\n /** @internal */\n walletDerivation: WalletDerivationConfig;\n /** @internal */\n collateralToken: EvmAddress;\n /** @internal */\n conditionalTokens: EvmAddress;\n /** @internal */\n negRiskAdapter: EvmAddress;\n /** @internal */\n collateralAdapter: EvmAddress;\n /** @internal */\n negRiskCollateralAdapter: EvmAddress;\n /** @internal */\n standardExchange: EvmAddress;\n /** @internal */\n negRiskExchange: EvmAddress;\n /** @internal */\n exchangeV3: EvmAddress;\n /** @internal */\n protocolV2Router: EvmAddress;\n /** @internal */\n combinatorialModule: EvmAddress;\n /** @internal */\n positionManager: EvmAddress;\n /** @internal */\n autoRedeemOperator: EvmAddress;\n /** @internal */\n safeMultisend: EvmAddress;\n /** @internal */\n relayHub: EvmAddress;\n /** @internal */\n clob: string;\n /** @internal */\n clobMarketWs: string;\n /** @internal */\n clobUserWs: string;\n /** @internal */\n relayer: string;\n /** @internal */\n gamma: string;\n /** @internal */\n data: string;\n /** @internal */\n rtdsWs: string;\n /** @internal */\n sportsWs: string;\n /** @internal */\n rfqQuoterWs: string;\n /** @internal */\n rfqQuoterWsHeaders?: Record<string, string>;\n /** @internal */\n relayerMaxPolls: number;\n /** @internal */\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 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 combinatorialModule: expectEvmAddress(\n '0x30000034706c7d8e12009dab006be20000c031a8',\n ),\n positionManager: expectEvmAddress(\n '0x006F54F7f9A22e0000CC2AB60031000000ae9fEF',\n ),\n autoRedeemOperator: expectEvmAddress(\n '0xa1200000d0002264C9a1698e001292D00E1b00af',\n ),\n safeMultisend: expectEvmAddress('0xA238CBeb142c10Ef7Ad8442C6D1f9E89e07e7761'),\n relayHub: expectEvmAddress('0xD216153c06E857cD7f72665E0aF1d7D82172F494'),\n clob: 'https://clob.polymarket.com',\n clobMarketWs: 'wss://ws-subscriptions-clob.polymarket.com/ws/market',\n clobUserWs: 'wss://ws-subscriptions-clob.polymarket.com/ws/user',\n relayer: 'https://relayer-v2.polymarket.com',\n gamma: 'https://gamma-api.polymarket.com',\n data: 'https://data-api.polymarket.com',\n rtdsWs: 'wss://ws-live-data.polymarket.com',\n rfqQuoterWs: 'wss://combos-rfq-gateway-quoter.polymarket.sh/ws/rfq',\n sportsWs: 'wss://sports-api.polymarket.com/ws',\n relayerMaxPolls: 100,\n relayerPollFrequencyMs: 2000,\n};\n\n/** @internal */\nexport const preproduction = {\n ...production,\n name: 'preproduction',\n clob: 'https://clob-preprod-int-v2.polymarket.com',\n data: 'https://data-api-preprod-int.polymarket.com',\n gamma: 'https://gamma-api-preprod-int.polymarket.com',\n relayer: '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 { ResultAsync } from '@polymarket/types';\nimport ky, { type KyInstance } from 'ky';\nimport { RateLimitError, RequestRejectedError, TransportError } from './errors';\n\nexport type ServiceRequest = {\n method: 'DELETE' | 'GET' | 'POST';\n path: string;\n body?: string;\n headers?: HeadersInit;\n json?: unknown;\n params?: URLSearchParams;\n};\n\nexport type RequestHeadersResolver = (\n request: ServiceRequest,\n) => Promise<HeadersInit>;\n\nexport type ServiceClientConfig = {\n root: string;\n resolveHeaders?: RequestHeadersResolver;\n};\n\nexport type ServiceClientGetOptions = {\n headers?: HeadersInit;\n params?: URLSearchParams;\n};\n\nexport type ServiceClientPostOptions = {\n headers?: HeadersInit;\n json?: unknown;\n};\n\nexport type ServiceClientDeleteOptions = {\n headers?: HeadersInit;\n json?: unknown;\n params?: URLSearchParams;\n};\n\n/**\n * Internal wrapper around a service-scoped `ky` instance.\n */\nexport class ServiceClient {\n readonly #client: KyInstance;\n readonly #resolveHeaders?: RequestHeadersResolver;\n\n constructor({ root, resolveHeaders }: ServiceClientConfig) {\n this.#client = ky.create({ prefixUrl: root, throwHttpErrors: false });\n this.#resolveHeaders = resolveHeaders;\n }\n\n get(\n path: string,\n options: ServiceClientGetOptions = {},\n ): ResultAsync<\n Response,\n RateLimitError | RequestRejectedError | TransportError\n > {\n return this.#request('GET', path, options);\n }\n\n post(\n path: string,\n options: ServiceClientPostOptions = {},\n ): ResultAsync<\n Response,\n RateLimitError | RequestRejectedError | TransportError\n > {\n return this.#request('POST', path, options);\n }\n\n del(\n path: string,\n options: ServiceClientDeleteOptions = {},\n ): ResultAsync<\n Response,\n RateLimitError | RequestRejectedError | TransportError\n > {\n return this.#request('DELETE', path, options);\n }\n\n #normalizePath(path: string) {\n return path.startsWith('/') ? path.slice(1) : path;\n }\n\n #request(\n method: ServiceRequest['method'],\n path: string,\n options:\n | ServiceClientDeleteOptions\n | ServiceClientGetOptions\n | ServiceClientPostOptions,\n ): ResultAsync<\n Response,\n RateLimitError | RequestRejectedError | TransportError\n > {\n return this.#toResult(this.#send(method, path, options));\n }\n\n async #send(\n method: ServiceRequest['method'],\n path: string,\n options:\n | ServiceClientDeleteOptions\n | ServiceClientGetOptions\n | ServiceClientPostOptions,\n ): Promise<Response> {\n const request = this.#createRequest(method, path, options);\n const resolvedHeaders = await this.#resolveHeaders?.(request);\n const headers = this.#mergeHeaders(request.headers, resolvedHeaders);\n\n if (request.body !== undefined && !headers.has('content-type')) {\n headers.set('content-type', 'application/json');\n }\n\n return this.#client(this.#normalizePath(path), {\n body: request.body,\n headers,\n method,\n searchParams: request.params,\n });\n }\n\n #createRequest(\n method: ServiceRequest['method'],\n path: string,\n options:\n | ServiceClientDeleteOptions\n | ServiceClientGetOptions\n | ServiceClientPostOptions,\n ): ServiceRequest {\n return {\n body: 'json' in options ? this.#serializeJson(options.json) : undefined,\n headers: options.headers,\n json: 'json' in options ? options.json : undefined,\n method,\n params: 'params' in options ? options.params : undefined,\n path,\n };\n }\n\n #serializeJson(json: unknown): string | undefined {\n if (json === undefined) {\n return undefined;\n }\n\n return JSON.stringify(json);\n }\n\n #mergeHeaders(...sources: Array<HeadersInit | undefined>): Headers {\n const headers = new Headers();\n\n for (const source of sources) {\n if (source === undefined) {\n continue;\n }\n\n for (const [key, value] of new Headers(source).entries()) {\n headers.set(key, value);\n }\n }\n\n return headers;\n }\n\n #toResult(\n promise: Promise<Response>,\n ): ResultAsync<\n Response,\n | RateLimitError\n | RequestRejectedError\n | RequestRejectedError\n | TransportError\n > {\n return ResultAsync.fromPromise(\n promise.then(async (response) => {\n if (response.ok) {\n return response;\n }\n\n if (response.status === 429) {\n throw new RateLimitError(\n `Request to ${response.url} was rate limited`,\n );\n }\n\n const message = await this.#extractResponseErrorMessage(response);\n throw new RequestRejectedError(message, {\n status: response.status,\n });\n }),\n (error) => {\n if (\n error instanceof RateLimitError ||\n error instanceof RequestRejectedError\n ) {\n return error;\n }\n\n return TransportError.fromError(error);\n },\n );\n }\n\n async #extractResponseErrorMessage(response: Response) {\n const contentType = response.headers.get('content-type')?.toLowerCase();\n\n if (contentType?.includes('application/json')) {\n const { error } = await response\n .clone()\n .json()\n .catch(() => ({}));\n if (error) return `${String(error)} (${response.url})`;\n }\n\n if (contentType?.includes('text/plain')) {\n const text = await response\n .clone()\n .text()\n .then(\n (body) => body.trim(),\n () => '',\n );\n\n if (text) {\n return `${text} (${response.url})`;\n }\n }\n\n const server = response.headers.get('server')?.toLowerCase();\n if (server?.includes('cloudflare')) {\n return `Request to ${response.url} was blocked by Cloudflare with status ${response.status}`;\n }\n\n if (\n contentType?.includes('text/html') ||\n contentType?.includes('application/xhtml+xml')\n ) {\n return `Request to ${response.url} failed with status ${response.status} and an unexpected HTML response body`;\n }\n\n return `Request to ${response.url} failed with status ${response.status} and unreadable response body`;\n }\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 { setNonBlockingInterval } from '@polymarket/types';\nimport type { WebSocketHeartbeat } from './lifecycle';\n\nconst CLOB_HEARTBEAT_INTERVAL_MS = 10_000;\nconst CLOB_HEARTBEAT_STALE_MS = 30_000;\nconst RTDS_HEARTBEAT_INTERVAL_MS = 5_000;\nconst RTDS_HEARTBEAT_STALE_MS = 10 * 60_000;\nconst SPORTS_HEARTBEAT_STALE_MS = 30_000;\n\nexport class ClobWebSocketHeartbeat implements WebSocketHeartbeat {\n #lastPongAt = 0;\n #timer: ReturnType<typeof setInterval> | undefined;\n\n start(send: (message: string) => void): void {\n this.stop();\n this.#lastPongAt = Date.now();\n this.#timer = setNonBlockingInterval(() => {\n send('PING');\n }, CLOB_HEARTBEAT_INTERVAL_MS);\n }\n\n handleMessage(message: string): boolean {\n if (message !== 'PONG') return false;\n this.#lastPongAt = Date.now();\n return true;\n }\n\n isStale(now: number): boolean {\n return now - this.#lastPongAt > CLOB_HEARTBEAT_STALE_MS;\n }\n\n stop(): void {\n if (this.#timer !== undefined) {\n clearInterval(this.#timer);\n this.#timer = undefined;\n }\n }\n}\n\nexport class RtdsWebSocketHeartbeat implements WebSocketHeartbeat {\n #lastMessageAt = 0;\n #timer: ReturnType<typeof setInterval> | undefined;\n\n start(send: (message: string) => void): void {\n this.stop();\n this.#lastMessageAt = Date.now();\n this.#timer = setNonBlockingInterval(() => {\n send('PING');\n }, RTDS_HEARTBEAT_INTERVAL_MS);\n }\n\n handleMessage(): boolean {\n this.#lastMessageAt = Date.now();\n return false;\n }\n\n isStale(now: number): boolean {\n return now - this.#lastMessageAt > RTDS_HEARTBEAT_STALE_MS;\n }\n\n stop(): void {\n if (this.#timer !== undefined) {\n clearInterval(this.#timer);\n this.#timer = undefined;\n }\n }\n}\n\nexport class SportsWebSocketHeartbeat implements WebSocketHeartbeat {\n #lastPingAt = 0;\n #send: ((message: string) => void) | undefined;\n\n start(send: (message: string) => void): void {\n this.#lastPingAt = Date.now();\n this.#send = send;\n }\n\n stop(): void {\n this.#send = undefined;\n }\n\n handleMessage(message: string): boolean {\n if (message !== 'ping') return false;\n this.#lastPingAt = Date.now();\n this.#send?.('pong');\n return true;\n }\n\n isStale(now: number): boolean {\n return now - this.#lastPingAt > SPORTS_HEARTBEAT_STALE_MS;\n }\n}\n","import {\n setNonBlockingInterval,\n setNonBlockingTimeout,\n} from '@polymarket/types';\nimport { TransportError } from '../errors';\n\nexport type WebSocketHeartbeat = {\n handleMessage(message: string): boolean;\n isStale(now: number): boolean;\n start(send: (message: string) => void): void;\n stop(): void;\n};\n\nconst HEARTBEAT_WATCHDOG_INTERVAL_MS = 5_000;\nconst RECONNECT_BASE_DELAY_MS = 250;\nconst RECONNECT_MAX_DELAY_MS = 30_000;\n\nexport type ScheduleReconnectOptions = {\n shouldReconnect: () => boolean;\n reconnect: () => Promise<unknown>;\n};\n\nexport type WebSocketConnectionOptions<TContext = undefined> = {\n headers?: Record<string, string>;\n onClose: () => void;\n onError: () => void;\n onMessage: (message: unknown) => void;\n onOpen: (context: TContext) => void;\n prepare?: () => TContext | Promise<TContext>;\n url: string;\n};\n\nexport type WebSocketConnectionResult = {\n reusedOpenSocket: boolean;\n};\n\nexport type WebSocketConnectionConstructorOptions = {\n heartbeat?: WebSocketHeartbeat;\n};\n\nexport class ReconnectScheduler {\n #timer: ReturnType<typeof setTimeout> | undefined;\n #attempt = 0;\n\n schedule(options: ScheduleReconnectOptions): void {\n if (this.#timer !== undefined || !options.shouldReconnect()) {\n return;\n }\n\n const delay = reconnectDelay(this.#attempt, {\n baseMs: RECONNECT_BASE_DELAY_MS,\n maxMs: RECONNECT_MAX_DELAY_MS,\n });\n this.#attempt += 1;\n this.#timer = setNonBlockingTimeout(() => {\n this.#timer = undefined;\n void this.#reconnect(options);\n }, delay);\n }\n\n stop(): void {\n if (this.#timer !== undefined) {\n clearTimeout(this.#timer);\n this.#timer = undefined;\n }\n }\n\n resetBackoff(): void {\n this.#attempt = 0;\n this.stop();\n }\n\n async #reconnect(options: ScheduleReconnectOptions): Promise<void> {\n if (!options.shouldReconnect()) return;\n try {\n await options.reconnect();\n } catch {\n this.schedule(options);\n }\n }\n}\n\nexport class WebSocketConnection {\n readonly #heartbeat: WebSocketHeartbeat | undefined;\n #socket: WebSocket | undefined;\n #connecting: Promise<WebSocketConnectionResult> | undefined;\n #watchdog: ReturnType<typeof setInterval> | undefined;\n\n constructor(options: WebSocketConnectionConstructorOptions = {}) {\n this.#heartbeat = options.heartbeat;\n }\n\n connect<TContext = undefined>(\n options: WebSocketConnectionOptions<TContext>,\n ): Promise<WebSocketConnectionResult> {\n const socket = this.#socket;\n if (socket?.readyState === WebSocket.OPEN) {\n return Promise.resolve({ reusedOpenSocket: true });\n }\n this.#clearCurrentSocket();\n if (this.#connecting !== undefined) return this.#connecting;\n\n const connecting = this.#open(options)\n .then(() => ({ reusedOpenSocket: false }))\n .catch((error: unknown) => {\n if (this.#connecting === connecting) {\n this.#connecting = undefined;\n }\n throw error;\n });\n this.#connecting = connecting;\n return connecting;\n }\n\n send(message: unknown): boolean {\n return this.#sendRaw(JSON.stringify(message));\n }\n\n #sendRaw(message: string): boolean {\n // Reconnects and shutdown can race with protocol updates; callers use the\n // boolean result only when they need to know whether the frame was sent.\n if (this.#socket?.readyState !== WebSocket.OPEN) return false;\n this.#socket.send(message);\n return true;\n }\n\n async close(): Promise<void> {\n const socket = await this.#takeCurrent();\n this.#stopHeartbeat();\n if (socket === undefined || socket.readyState === WebSocket.CLOSED) return;\n\n await new Promise<void>((resolve) => {\n socket.addEventListener('close', () => resolve(), { once: true });\n if (socket.readyState !== WebSocket.CLOSING) {\n socket.close();\n }\n });\n }\n\n async #open<TContext>(\n options: WebSocketConnectionOptions<TContext>,\n ): Promise<WebSocket> {\n const context = await options.prepare?.();\n\n return new Promise<WebSocket>((resolve, reject) => {\n const socket = createWebSocket(options.url, options.headers);\n\n const onOpen = () => {\n socket.removeEventListener('error', onOpenError);\n this.#markOpen(socket);\n this.#startHeartbeat();\n options.onOpen(context as TContext);\n resolve(socket);\n };\n const onOpenError = (event: Event) => {\n socket.removeEventListener('open', onOpen);\n reject(\n new TransportError(`WebSocket connection failed: ${options.url}`, {\n cause: event,\n }),\n );\n };\n\n socket.addEventListener('open', onOpen, { once: true });\n socket.addEventListener('error', onOpenError, { once: true });\n socket.addEventListener('message', (event) => {\n if (this.#socket !== socket) return;\n const message = String(event.data);\n if (this.#heartbeat?.handleMessage(message)) return;\n\n let raw: unknown;\n try {\n raw = JSON.parse(message);\n } catch {\n return;\n }\n options.onMessage(raw);\n });\n socket.addEventListener('close', () => {\n if (this.#socket !== socket) return;\n this.#clearCurrentSocket();\n options.onClose();\n });\n socket.addEventListener('error', () => options.onError());\n });\n }\n\n #markOpen(socket: WebSocket): void {\n this.#socket = socket;\n this.#connecting = undefined;\n }\n\n #clearCurrentSocket(): void {\n this.#stopHeartbeat();\n this.#socket = undefined;\n }\n\n #startHeartbeat(): void {\n this.#stopHeartbeat();\n const heartbeat = this.#heartbeat;\n if (heartbeat === undefined) return;\n\n heartbeat.start((message) => this.#sendRaw(message));\n this.#watchdog = setNonBlockingInterval(() => {\n if (!heartbeat.isStale(Date.now())) return;\n const socket = this.#socket;\n if (socket?.readyState === WebSocket.OPEN) {\n // Let the normal close path reconnect and resubscribe active handles.\n socket.close();\n }\n }, HEARTBEAT_WATCHDOG_INTERVAL_MS);\n }\n\n #stopHeartbeat(): void {\n if (this.#watchdog !== undefined) {\n clearInterval(this.#watchdog);\n this.#watchdog = undefined;\n }\n this.#heartbeat?.stop();\n }\n\n async #takeCurrent(): Promise<WebSocket | undefined> {\n const socket = this.#socket;\n const connecting = this.#connecting;\n\n this.#socket = undefined;\n this.#connecting = undefined;\n\n if (socket !== undefined) return socket;\n return connecting?.then(\n () => this.#socket,\n () => undefined,\n );\n }\n}\n\nfunction createWebSocket(\n url: string,\n headers: Record<string, string> | undefined,\n): WebSocket {\n if (headers === undefined) return new WebSocket(url);\n\n try {\n const socket: unknown = Reflect.construct(WebSocket, [url, { headers }]);\n if (socket instanceof WebSocket) return socket;\n } catch (cause) {\n throw new TransportError(\n 'WebSocket headers require a header-capable WebSocket implementation.',\n { cause },\n );\n }\n\n throw new TransportError(\n 'WebSocket headers require a header-capable WebSocket implementation.',\n );\n}\n\ntype ReconnectDelayOptions = {\n baseMs: number;\n maxMs: number;\n};\n\nfunction reconnectDelay(\n attempt: number,\n options: ReconnectDelayOptions,\n): number {\n const exponentialDelay = Math.min(\n options.baseMs * 2 ** attempt,\n options.maxMs,\n );\n return Math.random() * exponentialDelay;\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 tokenId of subscription.tokenIds) assets.add(tokenId);\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 return {\n auth: {\n apiKey: credentials.key,\n passphrase: credentials.passphrase,\n secret: credentials.secret,\n },\n markets: subscription.markets,\n type: 'user',\n };\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 return (event) => {\n switch (event.type) {\n case 'price_change':\n return event.payload.priceChanges.some((change) =>\n subscription.tokenIds.includes(change.tokenId),\n );\n case 'new_market':\n return subscription.customFeatureEnabled === true;\n case 'market_resolved':\n return (\n subscription.customFeatureEnabled === true &&\n (event.payload.tokenIds ?? []).some((tokenId) =>\n subscription.tokenIds.includes(tokenId),\n )\n );\n case 'best_bid_ask':\n return (\n subscription.customFeatureEnabled === true &&\n subscription.tokenIds.includes(event.payload.tokenId)\n );\n default:\n return subscription.tokenIds.includes(event.payload.tokenId);\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 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 #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.#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 onClose: () => this.#onConnectionClose(),\n onError: () => this.#onConnectionError(),\n onMessage: (message) => this.#onConnectionMessage(message),\n onOpen: () => this.#onConnectionOpen(),\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 #onConnectionClose(): 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 url: string;\n};\n\nexport class ClobUserWebSocketManager\n implements WebSocketSubscriptionManager<UserSubscription, UserEvent>\n{\n readonly #url: string;\n readonly #credentials: ApiKeyCreds;\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.#url = options.url;\n this.#credentials = options.credentials;\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 onClose: () => this.#onConnectionClose(),\n onError: () => this.#onConnectionError(),\n onMessage: (message) => this.#onConnectionMessage(message),\n onOpen: (credentials) => this.#onConnectionOpen(credentials),\n prepare: () => this.#credentials,\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 #onConnectionClose(): 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 {\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} from '@polymarket/bindings/rfq';\nimport type {\n RfqCancelQuoteAck,\n RfqConfirmationAck,\n RfqConfirmationRequestEvent,\n RfqExecutionUpdateEvent,\n RfqQuoteReference,\n RfqQuoteRequestEvent,\n RfqQuoteResponse,\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 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/rfq';\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 { OrderSide, type PositionId, toBaseUnits } from '@polymarket/bindings';\nimport type { RfqSignedOrder } from '@polymarket/bindings/rfq';\nimport type { EvmAddress, EvmSignature, HexString } from '@polymarket/types';\nimport { SigningError } from '../../errors';\nimport {\n createExchangeOrderSignature,\n createExchangeOrderTypedDataPayload,\n ExchangeOrderProtocolVersion,\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 order: Omit<RfqSignedOrder, 'signature'> = {\n builder: BYTES32_ZERO,\n maker: identity.maker,\n makerAmount: toBaseUnits(\n makerAmount(params.orderSide, params.orderPrice, params.size),\n ),\n metadata: BYTES32_ZERO,\n salt: generateOrderSalt().toString(),\n side: encodeOrderSide(params.orderSide),\n signatureType: identity.signatureType,\n signer: identity.signer,\n takerAmount: toBaseUnits(\n takerAmount(params.orderSide, params.orderPrice, params.size),\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({\n domain: createRfqExchangeDomain(params),\n order,\n }),\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({\n domain: createRfqExchangeDomain(params),\n order,\n signature,\n }),\n };\n}\n\nfunction createRfqExchangeDomain(params: SignRfqQuoteOrderParams) {\n return {\n chainId: params.chainId,\n exchange: params.exchange,\n protocolVersion: ExchangeOrderProtocolVersion.V3,\n };\n}\n\nfunction makerAmount(side: OrderSide, price: bigint, size: bigint): string {\n if (side === OrderSide.SELL) return size.toString();\n\n return ((price * size + 999_999n) / 1_000_000n).toString();\n}\n\nfunction takerAmount(side: OrderSide, price: bigint, size: bigint): string {\n if (side === OrderSide.SELL) {\n return ((price * size) / 1_000_000n).toString();\n }\n\n return size.toString();\n}\n\nfunction encodeOrderSide(side: OrderSide): 0 | 1 {\n return side === OrderSide.BUY ? 0 : 1;\n}\n\nfunction generateOrderSalt(): bigint {\n const bytes = new Uint8Array(8);\n globalThis.crypto.getRandomValues(bytes);\n\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/rfq';\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 RfqKnownInboundMessageSchema,\n type RfqQuoteId,\n type RfqQuoteRequest,\n RfqQuoterInboundMessageSchema,\n type RfqQuoterOutboundMessage,\n} from '@polymarket/bindings/rfq';\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 { TransportError } from '../../errors';\nimport type { Signer } from '../../types';\nimport type { AccountIdentity } from '../../wallet';\nimport { WebSocketConnection } from '../lifecycle';\nimport {\n type RfqEventController,\n toConfirmationAck,\n toConfirmationRequestEvent,\n toExecutionUpdateEvent,\n toQuoteAck,\n toQuoteCancelAck,\n toQuoteRequestEvent,\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\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.#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 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 close(): Promise<void> {\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 onClose: () => this.#handleClose(),\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 await this.#shutdownWithError(error);\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();\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 if (!RfqKnownInboundMessageSchema.safeParse(rawMessage).success) return;\n\n const parsed = RfqQuoterInboundMessageSchema.safeParse(rawMessage);\n if (!parsed.success) {\n const error = new TransportError('Invalid RFQ quoter message.', {\n cause: parsed.error,\n });\n void this.#fail(error);\n return;\n }\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 '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 #handleClose(): void {\n this.#onClose();\n void this.close();\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 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 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 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 CryptoPricesEvent,\n type EquityPricesEvent,\n RealtimeEventSchema,\n} from '@polymarket/bindings/subscriptions';\nimport { invariant } from '@polymarket/types';\nimport type {\n CommentsSubscription,\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 | 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\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 #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(url: string) {\n this.#url = 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 onClose: () => this.#onConnectionClose(),\n onError: () => this.#onConnectionError(),\n onMessage: (message) => this.#onConnectionMessage(message),\n onOpen: () => this.#onConnectionOpen(),\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 #onConnectionClose(): 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.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 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.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 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 #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.#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 onClose: () => this.#onConnectionClose(),\n onError: () => this.#onConnectionError(),\n onMessage: (message) => this.#onConnectionMessage(message),\n onOpen: () => this.#onConnectionOpen(),\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 #onConnectionClose(): 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 { 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 deriveCurrentDepositWalletAddress,\n resolveAccountIdentity,\n} from './wallet';\nimport {\n ClobMarketWebSocketManager,\n ClobUserWebSocketManager,\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 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 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 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 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};\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 data: new ServiceClient({ root: config.environment.data }),\n gamma: new ServiceClient({ root: config.environment.gamma }),\n clob: new ServiceClient({\n root: config.environment.clob,\n resolveHeaders: (request) => this.resolveClobHeaders(request),\n }),\n relayer: new ServiceClient({\n root: config.environment.relayer,\n resolveHeaders: (request) => this.resolveRelayerHeaders(request),\n }),\n rpc: new JsonRpcClient({ url: config.environment.rpc }),\n webSockets: {\n clobMarket: new ClobMarketWebSocketManager({\n url: config.environment.clobMarketWs,\n }),\n sports: new SportsWebSocketManager({\n url: config.environment.sportsWs,\n }),\n rtds: new RtdsWebSocketManager(config.environment.rtdsWs),\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 ]).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 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 signer: config.signer,\n clob: new ServiceClient({\n root: config.environment.clob,\n resolveHeaders: (request) => this.resolveClobHeaders(request),\n }),\n relayer: new ServiceClient({\n root: config.environment.relayer,\n resolveHeaders: (request) => this.resolveRelayerHeaders(request),\n }),\n rpc: new JsonRpcClient({ url: config.environment.rpc }),\n gamma: new ServiceClient({ root: config.environment.gamma }),\n data: new ServiceClient({ root: config.environment.data }),\n secureClob: new ServiceClient({\n resolveHeaders: async (request) => ({\n ...(await this.resolveClobHeaders(request)),\n ...(await this.#createL2Headers(request)),\n }),\n root: config.environment.clob,\n }),\n webSockets: {\n clobMarket: new ClobMarketWebSocketManager({\n url: config.environment.clobMarketWs,\n }),\n clobUser: new ClobUserWebSocketManager({\n credentials: config.credentials,\n url: config.environment.clobUserWs,\n }),\n rfqQuoter: new RfqQuoterWebSocketManager({\n account: config.account,\n chainId: config.environment.chainId,\n credentials: config.credentials,\n exchange: config.environment.exchangeV3,\n headers: config.environment.rfqQuoterWsHeaders,\n signer: config.signer,\n url: config.environment.rfqQuoterWs,\n }),\n sports: new SportsWebSocketManager({\n url: config.environment.sportsWs,\n }),\n rtds: new RtdsWebSocketManager(config.environment.rtdsWs),\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 /**\n * @deprecated `createSecureClient` now sets up the account wallet for its\n * trading flow, so this is a no-op retained only for backward compatibility\n * and returns the current secure client.\n */\n setupGaslessWallet(): Promise<SecureClient<TPublicActions, TSecureActions>> {\n return Promise.resolve(\n this as unknown as SecureClient<TPublicActions, TSecureActions>,\n );\n }\n\n /** @internal */\n get secureClob(): ServiceClient {\n return this.context.secureClob;\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.clobUser.close(),\n this.webSockets.rfqQuoter.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 { apiKey, environment } = this.context;\n\n try {\n await deleteApiKey(this);\n } finally {\n this.endAuthenticationLifecycle();\n await closingSubscriptions;\n }\n\n const client = new BasePublicClient({\n apiKey,\n environment,\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 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 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\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 }).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 });\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/**\n * Resolves the wallet address to authenticate as. Defaults to the signer's\n * current deterministic Deposit Wallet when no wallet is provided.\n */\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\n return deriveCurrentDepositWalletAddress(\n client.rpc,\n signerAddress,\n client.environment.walletDerivation,\n );\n}\n\n/**\n * Deploys the signer's current deterministic Deposit Wallet for the secure\n * client. Only the current Deposit Wallet can be deployed: a provided Deposit\n * Wallet that does not match the current deterministic address would deploy a\n * different wallet than the client is bound to, so it is rejected.\n */\nasync function deployDefaultDepositWallet(\n secureClient: SecureClient<PublicActions, SecureActions>,\n): Promise<void> {\n const currentDepositWallet = await deriveCurrentDepositWalletAddress(\n secureClient.rpc,\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"]}
|