@kuest/sdk 0.0.0-stage → 0.13.1

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.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/authorization.ts","../src/authentication.ts","../src/client-metadata.ts","../src/decorators/account.ts","../src/decorators/analytics.ts","../src/decorators/data.ts","../src/decorators/discovery.ts","../src/decorators/perps.ts","../src/decorators/rewards.ts","../src/decorators/rfq.ts","../src/decorators/session-keys.ts","../src/decorators/subscriptions.ts","../src/decorators/trading.ts","../src/decorators/wallet.ts","../src/decorators/index.ts","../src/environments.ts","../src/websockets/handle.ts","../src/websockets/registry.ts","../src/websockets/clob/protocol.ts","../src/websockets/clob/market.ts","../src/websockets/clob/user.ts","../src/websockets/perps/manager.ts","../src/websockets/perps/subscription.ts","../src/websockets/realtime/protocol.ts","../src/websockets/realtime/session.ts","../src/websockets/realtime/socket.ts","../src/websockets/realtime/pool.ts","../src/websockets/realtime/manager.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","options","assertNotAborted","#fetchBuilderKeyHeaders","error","RequestAbortedError","SigningError","#resolveHeaders","signal","headers","resolvedHeaders","withAbort","requestHeaders","fetch","response","body","createApiKeyAuthTypedDataPayload","domain","TypedData","packageVersion","createClientMetadata","detectRuntime","runtime","runtimeVersion","userAgent","browsers","name","pattern","match","version","publicAccountActions","client","listPositions","listComboPositions","fetchPortfolioValue","fetchTraderLeaderboardStanding","fetchUserStats","fetchUserPnl","fetchUserVolume","downloadAccountingSnapshot","listActivity","listComboActivity","withAccountWallet","accountActions","actions","listAccountTrades","fetchNotifications","dropNotifications","fetchClosedOnlyMode","analyticsActions","listBuilderTrades","listBuilderLeaderboard","fetchBuilderVolume","listTraderLeaderboard","listBiggestWinners","dataActions","fetchTokenReferences","fetchEventLiveVolume","fetchResolutions","fetchMidpoint","fetchMidpoints","fetchPrice","fetchPrices","fetchOrderBook","fetchOrderBooks","fetchSpread","fetchSpreads","fetchLastTradePrice","fetchLastTradePrices","listPriceHistory","estimateMarketPrice","fetchOpenInterest","listMarketHolders","listTrades","discoveryActions","listEvents","fetchEvent","fetchEventTags","listMarkets","listComboMarkets","fetchMarket","fetchMarketTags","listSeries","fetchSeries","listMarketClarifications","listTags","fetchTag","fetchRelatedTags","fetchRelatedTagResources","search","listSports","fetchSportsMarketTypes","listTeams","fetchPublicProfile","listComments","fetchCommentsById","listCommentsByUserAddress","perpsActions","fetchPerpsPositionSnapshots","fetchPerpsRegistration","fetchPerpsBuilderStatus","fetchPerpsBook","fetchPerpsFees","fetchPerpsInstruments","fetchPerpsTicker","fetchPerpsTickers","listPerpsCandles","listPerpsFundingHistory","listPerpsTrades","depositToPerps","openPerpsSession","revokePerpsCredentials","transferPerpsCollateral","withdrawFromPerps","publicRewardsActions","fetchCurrentRebates","listRewardMarkets","listCurrentRewards","listMarketRewards","rewardsActions","fetchOrderScoring","fetchOrdersScoring","listUserEarningsForDay","fetchTotalEarningsForUserForDay","listUserEarningsAndMarketsConfig","fetchRewardPercentages","rfqActions","openRfqSession","params","requestComboQuote","acceptComboQuote","waitForComboFill","sessionKeyActions","authorizeSessionKey","fetchSessionKeys","revokeSessionKey","subscriptionsActions","subscriptions","subscribe","tradingActions","sendOrderHeartbeat","createMarketOrder","placeMarketOrder","createLimitOrder","placeLimitOrder","postOrder","postOrders","waitForOrderFillSettlement","cancelOrder","cancelOrders","cancelAll","cancelMarketOrders","listOpenOrders","fetchOrder","publicWalletActions","fetchTradingApprovalsState","walletActions","setupTradingApprovals","approveErc20","approveErc1155ForAll","transferErc20","convert","prepareConvert","horizontalSplit","prepareHorizontalSplit","horizontalMerge","prepareHorizontalMerge","splitPosition","mergePositions","redeemPositions","planCollateralReturn","executeCollateralReturnPlan","allActions","production","expectEvmAddress","forkEnvironmentConfig","fork","base","forkRestEndpoint","forkWebSocketEndpoint","forkRestWebSocketEndpoint","forkHeaders","preproduction","createSubscriptionHandle","queue","closeSubscription","closing","SubscriptionRegistry","#entries","#deriveServerState","subscription","subscriber","pushable","entry","#addEntry","before","event","syncMarketSubscription","send","after","addedAssets","difference","removedAssets","buildMarketSubscribeUpdate","firstActiveAsset","buildMarketUnsubscribeUpdate","syncUserSubscription","buildUserUnsubscribeUpdate","buildUserSubscribeUpdate","addedMarkets","removedMarkets","deriveMarketServerSubscription","entries","assets","customFeatureEnabled","assetId","deriveUserServerSubscription","includeAllMarkets","markets","isAllMarketsUserSubscription","market","buildMarketSubscribeMessage","assetsIds","buildUserSubscribeMessage","credentials","message","marketMatcherFor","assetIds","change","userMatcherFor","left","right","rightSet","value","ClobMarketWebSocketManager","#headers","#url","#closing","#connection","WebSocketConnection","ClobWebSocketHeartbeat","#reconnectScheduler","ReconnectScheduler","#subscriptions","#registerSubscriber","#closeSubscriber","#connect","#shutdown","#onConnectionLost","#onConnectionError","#onConnectionMessage","#onConnectionOpen","#sendInitialSubscription","events","eventData","parsed","MarketEventSchema","#scheduleReconnect","ClobUserWebSocketManager","#credentials","UserEventSchema","PerpsSessionManager","#chainId","#fetch","#restUrl","#wsUrl","#sessions","#connectingSessions","#connecting","#hasShutdown","builderAttribution","approveBuilderFee","includeBuilderFills","TransportError","session","PerpsSession","closedSession","#clearSession","connecting","sessions","connectingSessions","promise","PerpsSubscriptionManager","#nextRequestId","PerpsWebSocketHeartbeat","derivePerpsSubscriptionServerState","matcherFor","#sendSubscribeFrame","channelsAdded","#sendUnsubscribeFrame","channelsRemoved","PerpsMarketDataEventSchema","channels","#buildChannelFrame","req","tickerInstrumentIds","statisticInstrumentIds","subscribeAllTickers","subscribeAllStatistics","channelFor","instrumentId","channel","invariant","subscriptionsFor","spec","symbols","provider","symbol","polyboltReconnectDelay","code","attempt","PriceSession","#scheduler","#keys","#ops","#flushTimer","#idleTimer","#authenticated","#closed","#flushing","#restarting","#generation","#keyTarget","#lastDropAt","connection","key","listener","state","resolve","reject","#enqueue","awaitAcceptance","setNonBlockingTimeout","#open","cause","#rejectKeys","#schedule","generation","confirmation","#subscribed","#event","#recordDrop","info","#lost","RequestRejectedError","RealtimeKnownErrorCode","#fail","#restart","op","keys","last","#scheduleFlush","#flush","next","batch","rejections","rejection","rejectedKeys","rejectedKey","item","payload","refreshSnapshot","now","#reset","ConnectionLostError","states","listeners","unsubscribe","current","ready","timer","previous","source","timestamp","history","data","point","PolyboltConnection","#options","PolyboltWebSocketHeartbeat","#pending","#events","#requestId","#lastSent","#cancel","#message","secret","passphrase","#request","PolyboltAckOp","operation","rejected","offset","candidate","toWireSubscription","frame","index","rid","pending","ack","PolyboltAckSchema","matches","pendingChannel","envelope","PolyboltEnvelopeSchema","parsePolyboltEvent","PolyboltChannel","SocketPool","#sockets","#closers","releases","closed","terminalError","close","release","fail","socket","#place","requestedProvider","sockets","RealtimeWebSocketManager","#pool","toQuoteRequestEvent","controller","toConfirmationRequestEvent","rfqId","quoteId","RfqConfirmationDecision","toQuoteAck","toQuoteCancelAck","toConfirmationAck","createAuthMessage","account","identity","resolveOrderIdentity","createQuoteMessage","quote","createQuoteCancelMessage","createConfirmationResponseMessage","decision","PendingResponses","#timeoutMs","timeoutMs","timeoutMessage","createPending","timeout","TimeoutError","remaining","resolvePromise","rejectPromise","BYTES32_ZERO","signRfqQuoteOrder","createExchangeV3OrderDomain","order","toBaseUnits","calculateExchangeOrderMakerAmount","generateRfqOrderSalt","encodeExchangeOrderSide","calculateExchangeOrderTakerAmount","signature","createExchangeOrderTypedDataPayload","createExchangeOrderSignature","bytes","byte","DecimalishToBigIntSchema","DecimalishSchema","decimalToScaledInteger","RfqQuoteResponseSchema","price","parseRfqQuoteResponse","parseUserInput","createRfqQuote","size","defaultQuoteSize","signedOrder","quoteOrderPrice","quoteOrderSide","quoteOrderTokenId","RfqDirection","OrderSide","requestedSize","RfqRequestedSizeUnit","UserInputError","whole","fraction","scaledValue","AUTH_TIMEOUT_MS","ACK_TIMEOUT_MS","RfqQuoterWebSocketManager","#account","#exchange","#signer","#session","#connectingSession","RfqWebSocketSession","connectingSession","#onClose","#queue","#auth","auth","authTimeout","#handleConnectionLost","#handleMessage","#sendAuthMessage","#send","#failPending","#shutdownWithError","rawMessage","RfqQuoterInboundMessageSchema","#handleAuthMessage","quoteAckKey","quoteCancelAckKey","confirmationAckKey","#handleRfqError","RfqQuoteRejectedError","RfqCancelQuoteRejectedError","RfqConfirmationRejectedError","parsedResponse","reference","RtdsWebSocketManager","RtdsWebSocketHeartbeat","deriveRtdsServerState","subscriptionsToOpen","serverSubscriptionsAdded","subscriptionsToClose","serverSubscriptionsRemoved","#resubscribeActiveServerEntries","RealtimeEventSchema","buildSubscribeMessage","buildUnsubscribeMessage","activeByKey","serverSubscription","serverSubscriptionsFor","topic","type","twapServerTopic","windowSeconds","SportsWebSocketManager","SportsWebSocketHeartbeat","SportsResultEventSchema","AbstractClient","#context","#decorators","context","decorator","BeginAuthenticationCredentialsSchema","ApiKeySchema","BeginAuthenticationRequestSchema","EvmAddressSchema","createPredictionsService","metadata","ServiceClient","BasePublicClient","JsonRpcClient","signer","nonce","signerAddress","requestAddress","wallet","resolveAccountIdentity","#createSecureClient","fetchApiKeys","createOrDeriveApiKey","expectEvmSignature","BaseSecureClient","#hasEndedAuthentication","realtime","#createL2Headers","#resolveBuilderGatewayHeaders","closingSubscriptions","shuttingDownPerpsSessions","shuttingDownRfqQuoter","apiKey","environment","onRateLimitUpdate","deleteApiKey","buildHmacSignature","createPublicClient","parseSiteConfig","CreateSecureClientError","makeErrorGuard","CancelledSigningError","RateLimitError","TransactionFailedError","UnexpectedResponseError","SetupGaslessWalletError","createSecureClient","resolveRequestedWallet","secureClient","authenticateWith","WalletType","isWalletDeployed","deployDefaultDepositWallet","legacyDepositWallet","deriveUupsDepositWalletAddress","deriveBeaconDepositWalletAddress","currentDepositWallet","isSameEvmAddress","deployDepositWallet"],"mappings":"6xSAsCA,IAAMA,EAAAA,CAAqCC,CAAAA,CAAE,OAAO,CAClD,qBAAA,CAAuBA,EAAE,MAAA,EAAO,CAAE,GAAA,CAAI,CAAC,EACvC,uBAAA,CAAyBA,CAAAA,CAAE,QAAO,CAAE,GAAA,CAAI,CAAC,CAAA,CACzC,wBAAA,CAA0BA,EAAE,MAAA,EAAO,CAAE,IAAI,CAAC,CAAA,CAC1C,wBAAyBA,CAAAA,CAAE,MAAA,GAAS,GAAA,CAAI,CAAC,CAC3C,CAAC,CAAA,CAEM,SAASC,EAAAA,CACdC,CAAAA,CACqB,CACrB,OAAO,IAAIC,GAA2BD,CAAM,CAC9C,CAEO,SAASE,EAAAA,CACdF,EACqB,CACrB,OAAO,IAAIG,EAAAA,CAA2BH,CAAM,CAC9C,CAEA,IAAMC,EAAAA,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,OAAO,KACT,CAEA,MAAM,SAAA,CACJK,GAAAA,CACAC,EACsB,CACtB,GAAI,CACF,OAAAC,GAAAA,CAAiBD,GAAS,MAAM,CAAA,CACzB,MAAM,IAAA,CAAKE,EAAAA,CAAwBH,IAASC,CAAO,CAC5D,OAASG,GAAAA,CAAO,CACd,MAAIA,GAAAA,YAAiBC,CAAAA,CAA2BD,GAAAA,CAC1CE,CAAAA,CAAa,UACjBF,GAAAA,CACA,uDACF,CACF,CACF,CAEA,KAAMG,EAAAA,CAAgBC,CAAAA,CAAwC,CAC5D,IAAMC,CAAAA,CAAU,KAAKV,EAAAA,CAAQ,OAAA,CACvBW,EACJ,OAAOD,CAAAA,EAAY,WACf,MAAME,GAAAA,C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AA,CAAQ,MAAM,+CAA+CQ,CAAoB,CAAA,gDAAA,CAC1G,EAIF,KAAA,CADe,MAAME,GAAoBV,CAAY,CAAA,EACxC,OACf","file":"index.js","sourcesContent":["import { z } from 'zod';\nimport { RequestAbortedError, SigningError } from './errors';\nimport { assertNotAborted, withAbort } from './request-options';\nimport type {\n ApiKeyAuthorization,\n ApiKeyAuthorizationOptions,\n ApiKeyAuthorizationRequest,\n} 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 KUEST_BUILDER_API_KEY: z.string().min(1),\n KUEST_BUILDER_TIMESTAMP: z.string().min(1),\n KUEST_BUILDER_PASSPHRASE: z.string().min(1),\n KUEST_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(\n request: ApiKeyAuthorizationRequest,\n options?: ApiKeyAuthorizationOptions,\n ): Promise<HeadersInit> {\n try {\n assertNotAborted(options?.signal);\n return await this.#fetchBuilderKeyHeaders(request, options);\n } catch (error) {\n if (error instanceof RequestAbortedError) throw error;\n throw SigningError.fromError(\n error,\n 'Could not authorize the builder-authenticated request',\n );\n }\n }\n\n async #resolveHeaders(signal?: AbortSignal): Promise<Headers> {\n const headers = this.#config.headers;\n const resolvedHeaders =\n typeof headers === 'function'\n ? await withAbort(Promise.resolve(headers()), signal)\n : 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 options?: ApiKeyAuthorizationOptions,\n ): Promise<HeadersInit> {\n const headers = await this.#resolveHeaders(options?.signal);\n assertNotAborted(options?.signal);\n const fetch = options?.fetch ?? globalThis.fetch;\n const response = await withAbort(\n 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,\n method: 'POST',\n mode: 'cors',\n signal: options?.signal,\n }),\n options?.signal,\n );\n\n if (!response.ok) {\n throw new Error(\n `Remote signer rejected request with status ${response.status}`,\n );\n }\n\n const body: unknown = await withAbort(response.json(), options?.signal);\n return RemoteBuilderSigningResponseSchema.parse(body);\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 '@kuest/types';\nimport { TypedData } from 'ox';\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 const domain = {\n chainId: request.chainId,\n name: 'ClobAuthDomain',\n version: '1',\n };\n\n return {\n domain,\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 EIP712Domain: TypedData.extractEip712DomainTypes(domain),\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 { version as sourcePackageVersion } from '../package.json';\n\ndeclare const __SDK_CLIENT_VERSION__: string;\n\nconst packageVersion =\n typeof __SDK_CLIENT_VERSION__ === 'string'\n ? __SDK_CLIENT_VERSION__\n : sourcePackageVersion;\n\ntype RuntimeGlobals = {\n Bun?: { version?: unknown };\n Deno?: { version?: { deno?: unknown } };\n process?: { versions?: { node?: unknown }; release?: { name?: unknown } };\n navigator?: { userAgent?: unknown };\n window?: unknown;\n self?: unknown;\n importScripts?: unknown;\n};\n\n/**\n * Package/runtime diagnostics, sampled once when constructing a client.\n * Runtime names are bun, deno, nodejs, edge, chrome, firefox, safari, browser,\n * worker, or unknown. Browser versions are best-effort user-agent values.\n * @internal\n */\nexport function createClientMetadata(): string {\n return `@kuest/sdk@${packageVersion}:${detectRuntime()}`;\n}\n\nfunction detectRuntime(): string {\n try {\n const runtime = globalThis as RuntimeGlobals;\n if (runtime.Bun !== undefined) {\n return `bun@${runtimeVersion(runtime.Bun.version)}`;\n }\n if (runtime.Deno !== undefined) {\n return `deno@${runtimeVersion(runtime.Deno.version?.deno)}`;\n }\n if (\n runtime.process?.versions?.node !== undefined ||\n runtime.process?.release?.name === 'node'\n ) {\n return `nodejs@${runtimeVersion(runtime.process?.versions?.node)}`;\n }\n\n const userAgent = runtime.navigator?.userAgent;\n if (typeof userAgent === 'string') {\n const browsers: Array<[string, RegExp]> = [\n ['edge', /\\bEdg(?:e|A|iOS)?(?:\\/([\\d.]+))?/],\n ['chrome', /\\b(?:HeadlessChrome|Chrome|Chromium|CriOS)(?:\\/([\\d.]+))?/],\n ['firefox', /\\b(?:Firefox|FxiOS)(?:\\/([\\d.]+))?/],\n ];\n for (const [name, pattern] of browsers) {\n const match = pattern.exec(userAgent);\n if (match !== null) return `${name}@${runtimeVersion(match[1])}`;\n }\n if (/\\bSafari\\//.test(userAgent)) {\n return `safari@${runtimeVersion(/\\bVersion\\/([\\d.]+)/.exec(userAgent)?.[1])}`;\n }\n }\n\n if (runtime.window !== undefined) return 'browser@unknown';\n if (\n runtime.self !== undefined ||\n typeof runtime.importScripts === 'function'\n ) {\n return 'worker@unknown';\n }\n if (runtime.navigator !== undefined) return 'browser@unknown';\n } catch {\n // Host globals can have restricted getters. Diagnostics must never prevent\n // client creation or require additional runtime permissions.\n }\n return 'unknown@unknown';\n}\n\nfunction runtimeVersion(version: unknown): string {\n return typeof version === 'string' &&\n /^[0-9][0-9A-Za-z.+_-]{0,63}$/.test(version)\n ? version\n : 'unknown';\n}\n","import type { ClobTrade, NotificationsResponse } from '@kuest/bindings/clob';\nimport type {\n Activity,\n ComboActivity,\n ComboPosition,\n PortfolioValue,\n Position,\n TraderLeaderboardStanding,\n UserPnlSeries,\n UserStats,\n UserVolume,\n} from '@kuest/bindings/data';\nimport type { Prettify } from '@kuest/types';\nimport {\n type DownloadAccountingSnapshotRequest,\n type DropNotificationsRequest,\n downloadAccountingSnapshot,\n dropNotifications,\n type FetchPortfolioValueRequest,\n type FetchTraderLeaderboardStandingRequest,\n type FetchUserPnlRequest,\n type FetchUserStatsRequest,\n type FetchUserVolumeRequest,\n fetchClosedOnlyMode,\n fetchNotifications,\n fetchPortfolioValue,\n fetchTraderLeaderboardStanding,\n fetchUserPnl,\n fetchUserStats,\n fetchUserVolume,\n type ListAccountTradesRequest,\n type ListActivityRequest,\n type ListComboActivityRequest,\n type ListComboPositionsRequest,\n type ListPositionsRequest,\n listAccountTrades,\n listActivity,\n listComboActivity,\n listComboPositions,\n listPositions,\n} from '../actions';\nimport type {\n BaseClient,\n BasePublicClient,\n BaseSecureClient,\n} from '../clients';\nimport type { Paginated } from '../pagination';\nimport type { RequestOptions } from '../request-options';\n\ntype DefaultAccountWallet<TRequest extends { user?: string }> = Prettify<\n Omit<TRequest, 'user'> & {\n /**\n * Wallet address to use.\n *\n * @defaultValue `client.account.wallet`\n */\n user?: string;\n }\n>;\n\nexport type SecureListPositionsRequest =\n DefaultAccountWallet<ListPositionsRequest>;\nexport type SecureListComboPositionsRequest =\n DefaultAccountWallet<ListComboPositionsRequest>;\nexport type SecureFetchPortfolioValueRequest =\n DefaultAccountWallet<FetchPortfolioValueRequest>;\nexport type SecureFetchTraderLeaderboardStandingRequest =\n DefaultAccountWallet<FetchTraderLeaderboardStandingRequest>;\nexport type SecureFetchUserPnlRequest =\n DefaultAccountWallet<FetchUserPnlRequest>;\nexport type SecureFetchUserStatsRequest =\n DefaultAccountWallet<FetchUserStatsRequest>;\nexport type SecureFetchUserVolumeRequest =\n DefaultAccountWallet<FetchUserVolumeRequest>;\nexport type SecureDownloadAccountingSnapshotRequest =\n DefaultAccountWallet<DownloadAccountingSnapshotRequest>;\nexport type SecureListActivityRequest =\n DefaultAccountWallet<ListActivityRequest>;\nexport type SecureListComboActivityRequest =\n DefaultAccountWallet<ListComboActivityRequest>;\n\nexport type PublicAccountActions = Prettify<{\n /**\n * Lists positions for a wallet, or a market's holders when anchored on a\n * single `conditionId` without a `user`.\n *\n * `OPEN` (the default) includes settled-but-unredeemed winners;\n * `REDEEMABLE` narrows to those winners, `REDEEMABLE_LOST` lists held\n * zero-payout positions, `MERGEABLE` lists live complementary pairs, and\n * `CLOSED` lists exited positions. Lost rows report `status: 'REDEEMABLE'`;\n * mergeable rows report `status: 'OPEN'`.\n *\n * `REDEEMABLE_LOST` requires `user`. For `MERGEABLE`, provide `user` to\n * filter to mergeable positions; a `conditionId`-only request falls back\n * to the broader `OPEN` listing.\n *\n * `sortBy` defaults to `TOKENS` for `MERGEABLE`, `REALIZED_PNL` for\n * `CLOSED`, and `CURRENT_VALUE` for the other statuses.\n * For wallet-anchored `CLOSED` listings, `TOKENS`, `CURRENT_VALUE`, `PRICE`\n * and `UNREALIZED_PNL` sort by realized PnL in the requested direction.\n * Keep the original filters and requested sort when resuming a cursor. If\n * an older cursor is rejected with HTTP 400 because the ordering changed,\n * discard it and explicitly fetch a new first page; the paginator does not\n * restart the listing.\n * `title` filters by case-insensitive substring (max 200 Unicode characters).\n * `%` and `_` are wildcards. Blank input is ignored; other patterns are\n * preserved unchanged on every page, including cursor replay.\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(\n request: ListPositionsRequest,\n options?: RequestOptions,\n ): Paginated<Position[]>;\n /**\n * Lists combo positions for a wallet.\n *\n * @throws {@link ListComboPositionsError}\n * Thrown on failure.\n *\n * @example\n * Fetch the first page of results:\n * ```ts\n * const paginator = client.listComboPositions({\n * user: '0x7c3db723f1d4d8cb9c550095203b686cb11e5c6b',\n * pageSize: 10,\n * });\n *\n * const firstPage = await paginator.firstPage();\n * ```\n *\n * @example\n * Filter to any of several resolved statuses:\n * ```ts\n * const paginator = client.listComboPositions({\n * user: '0x7c3db723f1d4d8cb9c550095203b686cb11e5c6b',\n * status: [\n * ComboPositionStatus.ResolvedWin,\n * ComboPositionStatus.ResolvedPartial,\n * ComboPositionStatus.ResolvedLoss,\n * ],\n * });\n * ```\n */\n listComboPositions(\n request: ListComboPositionsRequest,\n options?: RequestOptions,\n ): Paginated<ComboPosition[]>;\n /**\n * Fetches the total value for a wallet's positions.\n *\n * When `conditionIds` is present, only those single-market positions are\n * included; portfolio-level combo positions are excluded. Accepts at most\n * 20 distinct condition IDs.\n *\n * @throws {@link FetchPortfolioValueError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const value = await client.fetchPortfolioValue({\n * user: '0x7c3db723f1d4d8cb9c550095203b686cb11e5c6b',\n * conditionIds: ['0xe546672750517f62c45a5a00067481981e62b9c20fa8220203232c9dc8fd2093'],\n * });\n * ```\n */\n fetchPortfolioValue(\n request: FetchPortfolioValueRequest,\n options?: RequestOptions,\n ): Promise<PortfolioValue>;\n /**\n * Fetches one trader's standing on both the PnL and volume boards.\n *\n * `window` defaults to one day and `category` to overall. A `null` rank means\n * the trader is unranked on that board. Returns `null` for an unknown wallet.\n *\n * @throws {@link FetchTraderLeaderboardStandingError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const standing = await client.fetchTraderLeaderboardStanding({\n * user: '0xa71093cafc0c099b4ccab24c3cb8018d817923c4',\n * window: LeaderboardWindow.All,\n * });\n * ```\n */\n fetchTraderLeaderboardStanding(\n request: FetchTraderLeaderboardStandingRequest,\n options?: RequestOptions,\n ): Promise<TraderLeaderboardStanding | null>;\n /**\n * Fetches profile and lifetime trading statistics for a wallet.\n *\n * `tradedMarketCount` is the exact number of distinct markets traded.\n *\n * Returns `null` when the wallet is not a known user.\n *\n * @throws {@link FetchUserStatsError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const stats = await client.fetchUserStats({\n * user: '0x7c3db723f1d4d8cb9c550095203b686cb11e5c6b',\n * });\n * ```\n */\n fetchUserStats(\n request: FetchUserStatsRequest,\n options?: RequestOptions,\n ): Promise<UserStats | null>;\n /**\n * Fetches a wallet's cumulative PnL series.\n *\n * `interval` defaults to one day and `fidelity` defaults to one hour. Each\n * point is cumulative through its timestamp; nullable amounts mean the\n * source was unavailable and are never coerced to zero.\n *\n * @throws {@link FetchUserPnlError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const pnl = await client.fetchUserPnl({\n * user: '0x7c3db723f1d4d8cb9c550095203b686cb11e5c6b',\n * interval: UserPnlInterval.OneWeek,\n * fidelity: UserPnlFidelity.ThreeHours,\n * });\n * ```\n */\n fetchUserPnl(\n request: FetchUserPnlRequest,\n options?: RequestOptions,\n ): Promise<UserPnlSeries>;\n /**\n * Fetches a wallet's trading volume for a time window.\n *\n * Volume is returned in shares and USD. Window bounds accept epoch seconds\n * or `Date` values and are widened to whole UTC days.\n *\n * @throws {@link FetchUserVolumeError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const volume = await client.fetchUserVolume({\n * user: '0x7c3db723f1d4d8cb9c550095203b686cb11e5c6b',\n * window: { start: new Date('2026-08-01T00:00:00Z') },\n * });\n * ```\n */\n fetchUserVolume(\n request: FetchUserVolumeRequest,\n options?: RequestOptions,\n ): Promise<UserVolume>;\n /**\n * Downloads an accounting snapshot archive for a wallet.\n *\n * @throws {@link DownloadAccountingSnapshotError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const snapshot = await client.downloadAccountingSnapshot({\n * user: '0x7c3db723f1d4d8cb9c550095203b686cb11e5c6b',\n * });\n * ```\n */\n downloadAccountingSnapshot(\n request: DownloadAccountingSnapshotRequest,\n options?: RequestOptions,\n ): Promise<Blob>;\n /**\n * Lists wallet activity.\n * Trades and redemptions expose available token outcomes. Narrow splits, merges and redemptions on\n * `isCombo` before using market-only metadata; a basket's outcome names its\n * token side, not a selected leg.\n *\n * Every activity type is included by default, including deposits and\n * withdrawals; use the `type` filter to narrow results. An omitted `window`\n * serves the most recent three years; `window: 'full'` requests the complete\n * history. Window bounds accept Unix epoch seconds or `Date` values. Results\n * are newest-first by default. `pageSize` defaults to 100 (max 1000), and\n * transient rate limits are retried by default.\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(\n request: ListActivityRequest,\n options?: RequestOptions,\n ): Paginated<Activity[]>;\n /**\n * Lists combo lifecycle activity for a wallet.\n *\n * @throws {@link ListComboActivityError}\n * Thrown on failure.\n *\n * @example\n * Fetch the first page of results:\n * ```ts\n * const paginator = client.listComboActivity({\n * user: '0x7c3db723f1d4d8cb9c550095203b686cb11e5c6b',\n * pageSize: 10,\n * });\n *\n * const firstPage = await paginator.firstPage();\n * ```\n */\n listComboActivity(\n request: ListComboActivityRequest,\n options?: RequestOptions,\n ): Paginated<ComboActivity[]>;\n}>;\n\nexport type SecureAccountActions = Prettify<{\n /**\n * Lists positions for a wallet across their lifecycle.\n *\n * Defaults to the authenticated account's wallet when `user` is omitted.\n * This also supplies the wallet required by `REDEEMABLE_LOST` and scopes\n * `MERGEABLE` to that wallet's live complementary pairs.\n * To list a market's holders (a `conditionId` anchor with no wallet), use\n * a public client's `listPositions` instead; its `MERGEABLE` filter falls\n * back to `OPEN` without `user`, and `REDEEMABLE_LOST` requires `user`.\n *\n * `OPEN` (the default) includes settled-but-unredeemed winners;\n * `REDEEMABLE` narrows to those winners, `REDEEMABLE_LOST` lists held\n * zero-payout positions, `MERGEABLE` lists live complementary pairs, and\n * `CLOSED` lists exited positions. Lost rows report `status: 'REDEEMABLE'`;\n * mergeable rows report `status: 'OPEN'`.\n *\n * `sortBy` defaults to `TOKENS` for `MERGEABLE`, `REALIZED_PNL` for\n * `CLOSED`, and `CURRENT_VALUE` for the other statuses.\n * For wallet-anchored `CLOSED` listings, `TOKENS`, `CURRENT_VALUE`, `PRICE`\n * and `UNREALIZED_PNL` sort by realized PnL in the requested direction.\n * Keep the original filters and requested sort when resuming a cursor. If\n * an older cursor is rejected with HTTP 400 because the ordering changed,\n * discard it and explicitly fetch a new first page; the paginator does not\n * restart the listing.\n * `title` filters by case-insensitive substring (max 200 Unicode characters).\n * `%` and `_` are wildcards. Blank input is ignored; other patterns are\n * preserved unchanged on every page, including cursor replay.\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(\n request?: SecureListPositionsRequest,\n options?: RequestOptions,\n ): Paginated<Position[]>;\n /**\n * Lists combo positions for a wallet.\n *\n * Defaults to the authenticated account's wallet when `user` is omitted.\n *\n * @throws {@link ListComboPositionsError}\n * Thrown on failure.\n *\n * @example\n * Filter the authenticated account's positions to multiple statuses:\n * ```ts\n * const paginator = client.listComboPositions({\n * status: [\n * ComboPositionStatus.ResolvedWin,\n * ComboPositionStatus.ResolvedPartial,\n * ],\n * });\n * ```\n */\n listComboPositions(\n request?: SecureListComboPositionsRequest,\n options?: RequestOptions,\n ): Paginated<ComboPosition[]>;\n /**\n * Fetches the total value for a wallet's positions.\n *\n * When `conditionIds` is present, only those single-market positions are\n * included; portfolio-level combo positions are excluded. Accepts at most\n * 20 distinct condition IDs.\n *\n * Defaults to the authenticated account's wallet when `user` is omitted.\n *\n * @throws {@link FetchPortfolioValueError}\n * Thrown on failure.\n */\n fetchPortfolioValue(\n request?: SecureFetchPortfolioValueRequest,\n options?: RequestOptions,\n ): Promise<PortfolioValue>;\n /**\n * Fetches one trader's standing on both the PnL and volume boards.\n *\n * Defaults to the authenticated account's wallet when `user` is omitted.\n * `window` defaults to one day and `category` to overall. A `null` rank means\n * the trader is unranked on that board. Returns `null` for an unknown wallet.\n *\n * @throws {@link FetchTraderLeaderboardStandingError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const standing = await client.fetchTraderLeaderboardStanding({\n * window: LeaderboardWindow.All,\n * });\n * ```\n */\n fetchTraderLeaderboardStanding(\n request?: SecureFetchTraderLeaderboardStandingRequest,\n options?: RequestOptions,\n ): Promise<TraderLeaderboardStanding | null>;\n /**\n * Fetches profile and lifetime trading statistics for a wallet.\n *\n * `tradedMarketCount` is the exact number of distinct markets traded.\n *\n * Defaults to the authenticated account's wallet when `user` is omitted.\n * Returns `null` when the wallet is not a known user.\n *\n * @throws {@link FetchUserStatsError}\n * Thrown on failure.\n */\n fetchUserStats(\n request?: SecureFetchUserStatsRequest,\n options?: RequestOptions,\n ): Promise<UserStats | null>;\n /**\n * Fetches the cumulative PnL series for a wallet.\n *\n * Defaults to the authenticated account's wallet when `user` is omitted.\n * `interval` defaults to one day and `fidelity` defaults to one hour.\n *\n * @throws {@link FetchUserPnlError}\n * Thrown on failure.\n */\n fetchUserPnl(\n request?: SecureFetchUserPnlRequest,\n options?: RequestOptions,\n ): Promise<UserPnlSeries>;\n /**\n * Fetches trading volume for a wallet over a time window.\n *\n * Defaults to the authenticated account's wallet when `user` is omitted.\n * Window bounds accept epoch seconds or `Date` values and are widened to\n * whole UTC days.\n *\n * @throws {@link FetchUserVolumeError}\n * Thrown on failure.\n */\n fetchUserVolume(\n request?: SecureFetchUserVolumeRequest,\n options?: RequestOptions,\n ): Promise<UserVolume>;\n /**\n * Downloads an accounting snapshot archive for a wallet.\n *\n * Defaults to the authenticated account's wallet when `user` is omitted.\n *\n * @throws {@link DownloadAccountingSnapshotError}\n * Thrown on failure.\n */\n downloadAccountingSnapshot(\n request?: SecureDownloadAccountingSnapshotRequest,\n options?: RequestOptions,\n ): Promise<Blob>;\n /**\n * Lists wallet activity.\n * Trades and redemptions expose available token outcomes. Narrow splits, merges and redemptions on\n * `isCombo` before using market-only metadata; a basket's outcome names its\n * token side, not a selected leg.\n *\n * Defaults to the authenticated account's wallet when `user` is omitted.\n *\n * Every activity type is included by default, including deposits and\n * withdrawals; use the `type` filter to narrow results. An omitted `window`\n * serves the most recent three years; `window: 'full'` requests the complete\n * history. Window bounds accept Unix epoch seconds or `Date` values. Results\n * are newest-first by default. `pageSize` defaults to 100 (max 1000), and\n * transient rate limits are retried by default.\n *\n * @throws {@link ListActivityError}\n * Thrown on failure.\n */\n listActivity(\n request?: SecureListActivityRequest,\n options?: RequestOptions,\n ): Paginated<Activity[]>;\n /**\n * Lists combo lifecycle activity for a wallet.\n *\n * Defaults to the authenticated account's wallet when `user` is omitted.\n *\n * @throws {@link ListComboActivityError}\n * Thrown on failure.\n */\n listComboActivity(\n request?: SecureListComboActivityRequest,\n options?: RequestOptions,\n ): Paginated<ComboActivity[]>;\n /**\n * Lists trades for the authenticated account across all pages.\n *\n * @throws {@link ListAccountTradesError}\n * Thrown on failure.\n *\n * @example\n * Fetch the first page of results:\n * ```ts\n * const paginator = client.listAccountTrades({\n * market: '0x0000000000000000000000000000000000000000000000000000000000000001',\n * });\n *\n * const firstPage = await paginator.firstPage();\n *\n * // Optionally, fetch additional pages:\n * for await (const page of paginator.from(firstPage.nextCursor)) {\n * // page.items: ClobTrade[]\n * }\n * ```\n *\n * @example\n * Loop through all pages with `for await`:\n * ```ts\n * const paginator = client.listAccountTrades({\n * market: '0x0000000000000000000000000000000000000000000000000000000000000001',\n * });\n *\n * for await (const page of paginator) {\n * // page.items: ClobTrade[]\n * }\n * ```\n */\n listAccountTrades(\n request?: ListAccountTradesRequest,\n options?: RequestOptions,\n ): Paginated<ClobTrade[]>;\n /**\n * Fetches notifications for the authenticated account.\n * Notifications of a kind this SDK version does not recognize are omitted.\n *\n * @throws {@link FetchNotificationsError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const notifications = await client.fetchNotifications();\n * ```\n */\n fetchNotifications(options?: RequestOptions): 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(options?: RequestOptions): Promise<boolean>;\n}>;\n\nfunction publicAccountActions(client: BaseClient): PublicAccountActions {\n return {\n listPositions: listPositions.bind(null, client),\n listComboPositions: listComboPositions.bind(null, client),\n fetchPortfolioValue: fetchPortfolioValue.bind(null, client),\n fetchTraderLeaderboardStanding: fetchTraderLeaderboardStanding.bind(\n null,\n client,\n ),\n fetchUserStats: fetchUserStats.bind(null, client),\n fetchUserPnl: fetchUserPnl.bind(null, client),\n fetchUserVolume: fetchUserVolume.bind(null, client),\n downloadAccountingSnapshot: downloadAccountingSnapshot.bind(null, client),\n listActivity: listActivity.bind(null, client),\n listComboActivity: listComboActivity.bind(null, client),\n };\n}\n\ntype WithAccountWallet<TRequest> = Omit<TRequest, 'user'> & { user: string };\n\nfunction withAccountWallet<TRequest extends { user?: string }>(\n client: BaseSecureClient,\n request: TRequest = {} as TRequest,\n): WithAccountWallet<TRequest> {\n if (\n request === null ||\n typeof request !== 'object' ||\n Array.isArray(request)\n ) {\n return request as WithAccountWallet<TRequest>;\n }\n\n return {\n ...request,\n user: request.user === undefined ? client.account.wallet : request.user,\n };\n}\n\nexport function accountActions(client: BasePublicClient): PublicAccountActions;\nexport function accountActions(client: BaseSecureClient): SecureAccountActions;\nexport function accountActions(\n client: BaseClient,\n): PublicAccountActions | SecureAccountActions {\n const actions = publicAccountActions(client);\n\n if (client.isPublicClient()) {\n return actions;\n }\n\n return {\n ...actions,\n listPositions: (\n request?: SecureListPositionsRequest,\n options?: RequestOptions,\n ) => listPositions(client, withAccountWallet(client, request), options),\n listComboPositions: (\n request?: SecureListComboPositionsRequest,\n options?: RequestOptions,\n ) =>\n listComboPositions(client, withAccountWallet(client, request), options),\n fetchPortfolioValue: (\n request?: SecureFetchPortfolioValueRequest,\n options?: RequestOptions,\n ) =>\n fetchPortfolioValue(client, withAccountWallet(client, request), options),\n fetchTraderLeaderboardStanding: (\n request?: SecureFetchTraderLeaderboardStandingRequest,\n options?: RequestOptions,\n ) =>\n fetchTraderLeaderboardStanding(\n client,\n withAccountWallet(client, request),\n options,\n ),\n fetchUserStats: (\n request?: SecureFetchUserStatsRequest,\n options?: RequestOptions,\n ) => fetchUserStats(client, withAccountWallet(client, request), options),\n fetchUserPnl: (\n request?: SecureFetchUserPnlRequest,\n options?: RequestOptions,\n ) => fetchUserPnl(client, withAccountWallet(client, request), options),\n fetchUserVolume: (\n request?: SecureFetchUserVolumeRequest,\n options?: RequestOptions,\n ) => fetchUserVolume(client, withAccountWallet(client, request), options),\n downloadAccountingSnapshot: (\n request?: SecureDownloadAccountingSnapshotRequest,\n options?: RequestOptions,\n ) =>\n downloadAccountingSnapshot(\n client,\n withAccountWallet(client, request),\n options,\n ),\n listActivity: (\n request?: SecureListActivityRequest,\n options?: RequestOptions,\n ) => listActivity(client, withAccountWallet(client, request), options),\n listComboActivity: (\n request?: SecureListComboActivityRequest,\n options?: RequestOptions,\n ) => listComboActivity(client, withAccountWallet(client, request), options),\n listAccountTrades: listAccountTrades.bind(null, client),\n fetchNotifications: fetchNotifications.bind(null, client),\n dropNotifications: dropNotifications.bind(null, client),\n fetchClosedOnlyMode: fetchClosedOnlyMode.bind(null, client),\n };\n}\n\n// Error unions and runtime `isError` guards for every action bound above.\n// Surfaced at the root entry point through `export * from './decorators'`.\n// Keep this list in sync with the methods on PublicAccountActions / SecureAccountActions.\nexport {\n DownloadAccountingSnapshotError,\n DropNotificationsError,\n FetchClosedOnlyModeError,\n FetchNotificationsError,\n FetchPortfolioValueError,\n FetchTraderLeaderboardStandingError,\n FetchUserPnlError,\n FetchUserStatsError,\n FetchUserVolumeError,\n ListAccountTradesError,\n ListActivityError,\n ListComboActivityError,\n ListComboPositionsError,\n ListPositionsError,\n} from '../actions';\nexport {\n ComboActivityType,\n SortDirection,\n TipSide,\n TradeFilterType,\n} from '../actions/activity';\nexport type { ComboPositionStatusFilter } from '../actions/portfolio';\nexport {\n ComboPositionSortBy,\n ComboPositionStatus,\n PositionFilterType,\n PositionSortBy,\n PositionStatus,\n UserPnlFidelity,\n UserPnlInterval,\n} from '../actions/portfolio';\n","import type { BuilderTrade } from '@kuest/bindings/clob';\nimport type {\n BiggestWinner,\n BuilderStanding,\n BuilderVolumePoint,\n TraderLeaderboardEntry,\n} from '@kuest/bindings/data';\nimport {\n type FetchBuilderVolumeRequest,\n fetchBuilderVolume,\n type ListBiggestWinnersRequest,\n type ListBuilderLeaderboardRequest,\n type ListBuilderTradesRequest,\n type ListTraderLeaderboardRequest,\n listBiggestWinners,\n listBuilderLeaderboard,\n listBuilderTrades,\n listTraderLeaderboard,\n} from '../actions';\nimport type {\n BaseClient,\n BasePublicClient,\n BaseSecureClient,\n} from '../clients';\nimport type { Paginated } from '../pagination';\nimport type { RequestOptions } from '../request-options';\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 options?: RequestOptions,\n ): Paginated<BuilderTrade[]>;\n\n /**\n * Lists builder leaderboard rankings.\n *\n * Builders are ranked by attributed share volume within `window`, which\n * defaults to one day. `builderCode` is the stable identifier; names and\n * profile images are display metadata. `pageSize` defaults to 100 (max 1000).\n * Transient rate limits are retried by default.\n *\n * @throws {@link ListBuilderLeaderboardError}\n * Thrown on failure.\n *\n * @example\n * Fetch the first page of results:\n * ```ts\n * const paginator = client.listBuilderLeaderboard({\n * pageSize: 10,\n * window: LeaderboardWindow.Day,\n * });\n *\n * const firstPage = await paginator.firstPage();\n *\n * // Optionally, fetch additional pages:\n * for await (const page of paginator.from(firstPage.nextCursor)) {\n * // page.items: BuilderStanding[]\n * }\n * ```\n *\n * @example\n * Loop through all pages with `for await`:\n * ```ts\n * const paginator = client.listBuilderLeaderboard({\n * pageSize: 10,\n * window: LeaderboardWindow.Day,\n * });\n *\n * for await (const page of paginator) {\n * // page.items: BuilderStanding[]\n * }\n * ```\n */\n listBuilderLeaderboard(\n request?: ListBuilderLeaderboardRequest,\n options?: RequestOptions,\n ): Paginated<BuilderStanding[]>;\n\n /**\n * Fetches the per-builder volume time series.\n *\n * `interval` controls bucket width and defaults to daily; use\n * {@link BuilderVolumeInterval.Year} for one bucket per calendar year.\n * `bucketLimit` returns that many complete recent buckets (default 30, max 90),\n * not that many builder rows. Results are newest bucket first, and volume is\n * measured in shares. Transient rate limits are retried by default.\n *\n * @throws {@link FetchBuilderVolumeError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const volume = await client.fetchBuilderVolume({\n * interval: BuilderVolumeInterval.Day,\n * bucketLimit: 7,\n * });\n * ```\n */\n fetchBuilderVolume(\n request?: FetchBuilderVolumeRequest,\n options?: RequestOptions,\n ): Promise<BuilderVolumePoint[]>;\n\n /**\n * Lists trader leaderboard rankings.\n *\n * `window` defaults to one day, `category` to overall, and `sortBy` to PnL.\n * Finite-window PnL is marked equity change net of flows, while all-time PnL\n * is realized only. Volume is measured in shares. Tied traders share a rank\n * and the next rank skips. `pageSize` defaults to 100 (max 1000).\n *\n * @throws {@link ListTraderLeaderboardError}\n * Thrown on failure.\n *\n * @example\n * Fetch the first page of results:\n * ```ts\n * const paginator = client.listTraderLeaderboard({\n * pageSize: 10,\n * sortBy: TraderLeaderboardSort.Pnl,\n * window: LeaderboardWindow.Week,\n * });\n *\n * const firstPage = await paginator.firstPage();\n *\n * // Optionally, fetch additional pages:\n * for await (const page of paginator.from(firstPage.nextCursor)) {\n * // page.items: TraderLeaderboardEntry[]\n * }\n * ```\n *\n * @example\n * Loop through all pages with `for await`:\n * ```ts\n * const paginator = client.listTraderLeaderboard({\n * pageSize: 10,\n * sortBy: TraderLeaderboardSort.Pnl,\n * window: LeaderboardWindow.Week,\n * });\n *\n * for await (const page of paginator) {\n * // page.items: TraderLeaderboardEntry[]\n * }\n * ```\n */\n listTraderLeaderboard(\n request?: ListTraderLeaderboardRequest,\n options?: RequestOptions,\n ): Paginated<TraderLeaderboardEntry[]>;\n\n /**\n * Lists the largest individual winning positions.\n *\n * The board has one row per position, ranked by its resolution profit.\n * `window` applies to resolution time and defaults to one day; `category`\n * defaults to overall. Equal profits retain distinct row ordinals. Combo rows\n * have no parent event, so branch on `kind` before using event metadata.\n * `pageSize` defaults to 100 (max 1000).\n *\n * @throws {@link ListBiggestWinnersError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const paginator = client.listBiggestWinners({\n * category: 'sports',\n * pageSize: 10,\n * window: LeaderboardWindow.Week,\n * });\n *\n * for await (const page of paginator) {\n * // page.items: BiggestWinner[]\n * }\n * ```\n */\n listBiggestWinners(\n request?: ListBiggestWinnersRequest,\n options?: RequestOptions,\n ): Paginated<BiggestWinner[]>;\n};\n\nexport function analyticsActions(client: BasePublicClient): AnalyticsActions;\nexport function analyticsActions(client: BaseSecureClient): AnalyticsActions;\nexport function analyticsActions(client: BaseClient): AnalyticsActions {\n return {\n listBuilderTrades: listBuilderTrades.bind(null, client),\n listBuilderLeaderboard: listBuilderLeaderboard.bind(null, client),\n fetchBuilderVolume: fetchBuilderVolume.bind(null, client),\n listTraderLeaderboard: listTraderLeaderboard.bind(null, client),\n listBiggestWinners: listBiggestWinners.bind(null, client),\n };\n}\n\n// Error unions and runtime `isError` guards for every action bound above.\n// Surfaced at the root entry point through `export * from './decorators'`.\n// Keep this list in sync with the methods on AnalyticsActions.\nexport {\n BiggestWinnerKind,\n BuilderVolumeInterval,\n FetchBuilderVolumeError,\n LeaderboardWindow,\n ListBiggestWinnersError,\n ListBuilderLeaderboardError,\n ListBuilderTradesError,\n ListTraderLeaderboardError,\n TraderLeaderboardSort,\n} from '../actions';\n","import type { DecimalString } from '@kuest/bindings';\nimport type {\n LastTradePrice,\n LastTradePriceForAsset,\n Midpoints,\n OrderBook,\n Prices,\n Spreads,\n} from '@kuest/bindings/clob';\nimport type {\n LiveVolume,\n MetaHolder,\n OpenInterest,\n PriceHistoryPoint,\n Resolution,\n TokenReference,\n Trade,\n} from '@kuest/bindings/data';\nimport {\n type EstimateMarketPriceRequest,\n estimateMarketPrice,\n type FetchEventLiveVolumeRequest,\n type FetchLastTradePriceRequest,\n type FetchLastTradePricesRequest,\n type FetchMidpointRequest,\n type FetchMidpointsRequest,\n type FetchOpenInterestRequest,\n type FetchOrderBookRequest,\n type FetchOrderBooksRequest,\n type FetchPriceRequest,\n type FetchPricesRequest,\n type FetchResolutionsRequest,\n type FetchSpreadRequest,\n type FetchSpreadsRequest,\n type FetchTokenReferencesRequest,\n fetchEventLiveVolume,\n fetchLastTradePrice,\n fetchLastTradePrices,\n fetchMidpoint,\n fetchMidpoints,\n fetchOpenInterest,\n fetchOrderBook,\n fetchOrderBooks,\n fetchPrice,\n fetchPrices,\n fetchResolutions,\n fetchSpread,\n fetchSpreads,\n fetchTokenReferences,\n type ListMarketHoldersRequest,\n type ListPriceHistoryRequest,\n type ListTradesRequest,\n listMarketHolders,\n listPriceHistory,\n listTrades,\n} from '../actions';\nimport type {\n BaseClient,\n BasePublicClient,\n BaseSecureClient,\n} from '../clients';\nimport type { Paginated } from '../pagination';\nimport type { RequestOptions } from '../request-options';\n\nexport type DataActions = {\n /**\n * Fetches reference and settlement metadata for outcome assets.\n *\n * Provide exactly one selector family: up to 50 distinct decimal `assetIds`,\n * or up to 10 distinct 31-byte or 32-byte hex `conditionIds`. Elements are\n * trimmed, blanks dropped, and duplicates removed in first-seen order.\n * Decimal IDs have leading zeros stripped and at most 78 remaining digits.\n * Conditions are lowercased without changing their width.\n *\n * Returns a direct collection. Unknown selectors contribute no rows; asset\n * lookups retain request order and condition groups retain server order.\n * Overlapping conditions can repeat assets. Settlement metadata and outcome\n * labels can lag by up to a minute. Transient rate limits are retried automatically.\n *\n * @throws {@link FetchTokenReferencesError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const references = await client.fetchTokenReferences({ assetIds: ['123'] });\n * ```\n */\n fetchTokenReferences(\n request: FetchTokenReferencesRequest,\n options?: RequestOptions,\n ): Promise<TokenReference[]>;\n /**\n * Fetches cumulative taker volume for one or more events.\n *\n * Results contain one row per market, ordered by taker volume descending, and\n * a total across all returned markets. Volume is measured in shares. Event\n * IDs must be positive 32-bit integers. Transient rate limits are retried\n * by default.\n *\n * @throws {@link FetchEventLiveVolumeError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const volume = await client.fetchEventLiveVolume({\n * eventIds: ['160707'],\n * });\n * ```\n */\n fetchEventLiveVolume(\n request: FetchEventLiveVolumeRequest,\n options?: RequestOptions,\n ): Promise<LiveVolume>;\n /**\n * Fetches resolution lifecycle rows by question, condition, or event.\n *\n * Provide exactly one selector. Condition and event lookups accept at most\n * 20 distinct IDs and return one row per matching condition. Missing\n * resolutions return an empty array. A 31-byte protocol v2 market condition\n * ID is right-padded to its canonical 32-byte form. A 31-byte combo condition\n * ID is rejected.\n *\n * @throws {@link FetchResolutionsError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const resolutions = await client.fetchResolutions({\n * eventIds: ['903193'],\n * });\n * ```\n */\n fetchResolutions(\n request: FetchResolutionsRequest,\n options?: RequestOptions,\n ): Promise<Resolution[]>;\n /**\n * Fetches the midpoint price for an exchange asset as a decimal string.\n *\n * @throws {@link FetchMidpointError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const midpoint = await client.fetchMidpoint({ assetId: '0x0122…0000' });\n * ```\n */\n fetchMidpoint(\n request: FetchMidpointRequest,\n options?: RequestOptions,\n ): Promise<DecimalString>;\n /**\n * Fetches midpoint prices for multiple exchange assets as an asset ID keyed lookup.\n *\n * @throws {@link FetchMidpointsError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const midpoints = await client.fetchMidpoints([{ assetId: '0x0122…0000' }]);\n * ```\n */\n fetchMidpoints(\n request: FetchMidpointsRequest,\n options?: RequestOptions,\n ): Promise<Midpoints>;\n /**\n * Fetches the current quoted price for an exchange asset and side as a decimal string.\n *\n * @throws {@link FetchPriceError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const price = await client.fetchPrice({ assetId: '0x0122…0000', side: OrderSide.BUY });\n * ```\n */\n fetchPrice(\n request: FetchPriceRequest,\n options?: RequestOptions,\n ): Promise<DecimalString>;\n /**\n * Fetches quoted prices for multiple exchange assets as an asset ID keyed lookup.\n *\n * @throws {@link FetchPricesError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const prices = await client.fetchPrices([{ assetId: '0x0122…0000', side: OrderSide.BUY }]);\n * ```\n */\n fetchPrices(\n request: FetchPricesRequest,\n options?: RequestOptions,\n ): Promise<Prices>;\n /**\n * Fetches the current order book for an exchange asset.\n *\n * @throws {@link FetchOrderBookError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const book = await client.fetchOrderBook({ assetId: '0x0122…0000' });\n * ```\n */\n fetchOrderBook(\n request: FetchOrderBookRequest,\n options?: RequestOptions,\n ): Promise<OrderBook>;\n /**\n * Fetches order books for multiple exchange assets.\n *\n * @throws {@link FetchOrderBooksError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const books = await client.fetchOrderBooks([{ assetId: '0x0122…0000' }]);\n * ```\n */\n fetchOrderBooks(\n request: FetchOrderBooksRequest,\n options?: RequestOptions,\n ): Promise<OrderBook[]>;\n /**\n * Fetches the spread for an exchange asset as a decimal string.\n *\n * @throws {@link FetchSpreadError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const spread = await client.fetchSpread({ assetId: '0x0122…0000' });\n * ```\n */\n fetchSpread(\n request: FetchSpreadRequest,\n options?: RequestOptions,\n ): Promise<DecimalString>;\n /**\n * Fetches spreads for multiple exchange assets as an asset ID keyed lookup.\n *\n * @throws {@link FetchSpreadsError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const spreads = await client.fetchSpreads([{ assetId: '0x0122…0000' }]);\n * ```\n */\n fetchSpreads(\n request: FetchSpreadsRequest,\n options?: RequestOptions,\n ): Promise<Spreads>;\n /**\n * Fetches the last traded price for an exchange asset.\n *\n * Returns `null` when the asset has not traded.\n *\n * @throws {@link FetchLastTradePriceError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const trade = await client.fetchLastTradePrice({ assetId: '0x0122…0000' });\n *\n * // trade === LastTradePrice | null\n * ```\n */\n fetchLastTradePrice(\n request: FetchLastTradePriceRequest,\n options?: RequestOptions,\n ): Promise<LastTradePrice | null>;\n /**\n * Fetches last traded prices for multiple exchange assets.\n *\n * Assets without trades are omitted from the response. Match returned rows by\n * `assetId`; the array is not positionally aligned with the request.\n *\n * @throws {@link FetchLastTradePricesError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const trades = await client.fetchLastTradePrices([{ assetId: '0x0122…0000' }]);\n * const trade = trades.find((candidate) => candidate.assetId === '0x0122…0000');\n * ```\n */\n fetchLastTradePrices(\n request: FetchLastTradePricesRequest,\n options?: RequestOptions,\n ): Promise<LastTradePriceForAsset[]>;\n /**\n * Lists historical price observations for an exchange asset.\n *\n * Select exactly one time form: a relative `interval`, an explicit `start`\n * with optional `end`, or the latest observation at or before an `asOf`\n * instant. Time inputs accept Unix epoch seconds or `Date` values. When\n * `bucketSeconds` is omitted, resolution is selected automatically for the\n * requested window and reported on each point as `resolutionSeconds`. An\n * explicit bucket is used exactly as requested and may produce an empty series\n * when that resolution is unavailable for the window. Prices are decimal\n * strings and returned timestamps are Unix epoch milliseconds. Series pages\n * are ordered oldest first; an `asOf` request returns at most one item. Series\n * page sizes default to and are capped at 10,000 points. Transient rate limits\n * are retried by default.\n *\n * @throws {@link ListPriceHistoryError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const history = client.listPriceHistory({\n * assetId: '17023124228269928849020611259015948850061676830917875073785033885105715180702',\n * interval: PriceHistoryInterval.OneDay,\n * bucketSeconds: 3600,\n * });\n *\n * for await (const page of history) {\n * // page.items: PriceHistoryPoint[]\n * }\n * ```\n */\n listPriceHistory(\n request: ListPriceHistoryRequest,\n options?: RequestOptions,\n ): Paginated<PriceHistoryPoint[]>;\n /**\n * Estimates the price level a market order would cross at current book depth.\n *\n * For BUY orders, `amount` is the amount of collateral to spend. For SELL\n * orders, `shares` is the number of shares to sell.\n *\n * @throws {@link EstimateMarketPriceError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const price = await client.estimateMarketPrice({\n * assetId: '0x0122…0000',\n * side: OrderSide.BUY,\n * amount: 10,\n * });\n * ```\n */\n estimateMarketPrice(\n request: EstimateMarketPriceRequest,\n options?: RequestOptions,\n ): Promise<number>;\n /**\n * Fetches priced gross open interest for selected markets or globally.\n *\n * `conditionIds` accepts up to 20 distinct market condition IDs. Omit it for\n * the global aggregate, whose `conditionId` is `null`. A requested servable\n * market with no holdings has a zero value; an absent row means the market\n * is not servable. Values are in USDC. Transient rate limits are retried\n * by default.\n *\n * @throws {@link FetchOpenInterestError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const openInterest = await client.fetchOpenInterest({\n * conditionIds: ['0xe546672750517f62c45a5a00067481981e62b9c20fa8220203232c9dc8fd2093'],\n * });\n * ```\n */\n fetchOpenInterest(\n request?: FetchOpenInterestRequest,\n options?: RequestOptions,\n ): Promise<OpenInterest[]>;\n /**\n * Lists top holders grouped by outcome for one or more markets.\n *\n * `conditionIds` accepts up to 20 distinct market condition IDs. `pageSize`\n * defaults to 100 (max 1000) and applies separately to each outcome. Merge\n * matching `assetId` groups across pages rather than relying on array position.\n * `minBalance` uses display shares and defaults to `0`; `1` means one share,\n * equivalent to 1,000,000 base units.\n * Amounts are net holdings by default. `includePnl` switches to per-outcome\n * gross holdings and adds position economics; it requires one condition ID and\n * a page size of at most 100. Transient rate limits are retried by default.\n *\n * @throws {@link ListMarketHoldersError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const result = client.listMarketHolders({\n * conditionIds: ['0xe546672750517f62c45a5a00067481981e62b9c20fa8220203232c9dc8fd2093'],\n * pageSize: 5,\n * });\n *\n * for await (const page of result) {\n * // page.items: MetaHolder[]\n * }\n * ```\n */\n listMarketHolders(\n request: ListMarketHoldersRequest,\n options?: RequestOptions,\n ): Paginated<MetaHolder[]>;\n /**\n * Lists trades for a wallet, market, or event — or the global recent-trades\n * feed when no filter is given.\n *\n * Only the taker side of each match is returned by default\n * (`takerOnly: false` includes maker rows), and a dust filter of 0.01\n * shares applies unless `filterType`/`filterAmount` say otherwise (either\n * may be sent alone). `conditionId` accepts at most 20 distinct ids. `pageSize`\n * defaults to 100 (max 1000). `window: 'full'` requests the complete\n * history; an omitted window serves the recent feed. Window bounds accept\n * Unix epoch seconds or `Date` values. Transient rate limits are retried\n * by default.\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(\n request?: ListTradesRequest,\n options?: RequestOptions,\n ): 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 fetchTokenReferences: fetchTokenReferences.bind(null, client),\n fetchEventLiveVolume: fetchEventLiveVolume.bind(null, client),\n fetchResolutions: fetchResolutions.bind(null, client),\n fetchMidpoint: fetchMidpoint.bind(null, client),\n fetchMidpoints: fetchMidpoints.bind(null, client),\n fetchPrice: fetchPrice.bind(null, client),\n fetchPrices: fetchPrices.bind(null, client),\n fetchOrderBook: fetchOrderBook.bind(null, client),\n fetchOrderBooks: fetchOrderBooks.bind(null, client),\n fetchSpread: fetchSpread.bind(null, client),\n fetchSpreads: fetchSpreads.bind(null, client),\n fetchLastTradePrice: fetchLastTradePrice.bind(null, client),\n fetchLastTradePrices: fetchLastTradePrices.bind(null, client),\n listPriceHistory: listPriceHistory.bind(null, client),\n estimateMarketPrice: estimateMarketPrice.bind(null, client),\n fetchOpenInterest: fetchOpenInterest.bind(null, client),\n listMarketHolders: listMarketHolders.bind(null, client),\n listTrades: listTrades.bind(null, client),\n };\n}\n\nexport type { FetchTokenReferencesRequest } from '../actions';\n// Error unions and runtime `isError` guards for every action bound above.\n// Surfaced at the root entry point through `export * from './decorators'`.\n// Keep this list in sync with the methods on DataActions.\nexport {\n EstimateMarketPriceError,\n FetchEventLiveVolumeError,\n FetchLastTradePriceError,\n FetchLastTradePricesError,\n FetchMidpointError,\n FetchMidpointsError,\n FetchOpenInterestError,\n FetchOrderBookError,\n FetchOrderBooksError,\n FetchPriceError,\n FetchPricesError,\n FetchResolutionsError,\n FetchSpreadError,\n FetchSpreadsError,\n FetchTokenReferencesError,\n ListMarketHoldersError,\n ListPriceHistoryError,\n ListTradesError,\n PriceHistoryInterval,\n ResolutionMarketType,\n ResolutionReporter,\n ResolutionSettlementTimeBasis,\n ResolutionSource,\n ResolutionStatus,\n} from '../actions';\n","import type { ComboMarket } from '@kuest/bindings/combos';\nimport type {\n Comment,\n Event,\n Market,\n MarketClarification,\n PublicProfile,\n RelatedTag,\n Series,\n SportsMarketTypesResponse,\n SportsMetadata,\n Tag,\n TagReference,\n Team,\n} from '@kuest/bindings/gamma';\nimport {\n type FetchCommentsByIdRequest,\n type FetchEventRequest,\n type FetchEventTagsRequest,\n type FetchMarketRequest,\n type FetchMarketTagsRequest,\n type FetchPublicProfileRequest,\n type FetchRelatedTagResourcesRequest,\n type FetchRelatedTagsRequest,\n type FetchSeriesRequest,\n type FetchTagRequest,\n fetchCommentsById,\n fetchEvent,\n fetchEventTags,\n fetchMarket,\n fetchMarketTags,\n fetchPublicProfile,\n fetchRelatedTagResources,\n fetchRelatedTags,\n fetchSeries,\n fetchSportsMarketTypes,\n fetchTag,\n type ListComboMarketsRequest,\n type ListCommentsByUserAddressRequest,\n type ListCommentsRequest,\n type ListEventsRequest,\n type ListMarketClarificationsRequest,\n type ListMarketsRequest,\n type ListSeriesRequest,\n type ListTagsRequest,\n type ListTeamsRequest,\n listComboMarkets,\n listComments,\n listCommentsByUserAddress,\n listEvents,\n listMarketClarifications,\n listMarkets,\n listSeries,\n listSports,\n listTags,\n listTeams,\n type SearchRequest,\n type SearchResults,\n search,\n} from '../actions';\nimport type {\n BaseClient,\n BasePublicClient,\n BaseSecureClient,\n} from '../clients';\nimport type { Paginated } from '../pagination';\nimport type { RequestOptions } from '../request-options';\n\nexport type DiscoveryActions = {\n /**\n * Lists events.\n *\n * Defaults to open events. Pass `closed: true` for closed events or\n * `closed: 'any'` for either state; no identifier filter is required.\n * Optionally filter by protocol with `version: ProtocolVersion.V1` or\n * `ProtocolVersion.V2`, or pass both in an array to include both protocols.\n * Arrays accept one or two values. Omitting `version` uses the current server\n * default of CTF events (v1).\n *\n * @remarks\n * Cursors continue the exact query they were minted for and are rejected for\n * a different one before any request. Cursors saved from earlier versions\n * keep working with the same arguments.\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(\n request?: ListEventsRequest,\n options?: RequestOptions,\n ): 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://operator.example/event/example-event',\n * });\n * ```\n */\n fetchEvent(\n request: FetchEventRequest,\n options?: RequestOptions,\n ): 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(\n request: FetchEventTagsRequest,\n options?: RequestOptions,\n ): Promise<TagReference[]>;\n\n /**\n * Lists markets.\n *\n * Defaults to open markets. Pass `closed: true` for closed markets or\n * `closed: 'any'` for either state. The latter requires a non-empty `ids`,\n * `slug`, `clobTokenIds`, `positionIds`, `conditionIds`, or `questionIds` filter.\n *\n * @remarks\n * Legacy multi-outcome markets cannot be represented by the binary\n * {@link Market} model and are omitted from results.\n *\n * Select one protocol with `version`, or pass both protocol versions in an array.\n * Arrays accept one or two values. Omitting `version` uses the current server\n * default of CTF markets (v1). Filter v2 markets by `resolutionStatus`, `requestIds`, or\n * `onchainEventIds`. Each ID filter accepts at most 100 values. V1 markets\n * use the separate `umaResolutionStatus` filter.\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(\n request?: ListMarketsRequest,\n options?: RequestOptions,\n ): Paginated<Market[]>;\n\n /**\n * Lists markets available for Combos.\n *\n * @throws {@link ListComboMarketsError}\n * Thrown on failure.\n *\n * @example\n * Fetch the first page of results:\n * ```ts\n * const paginator = client.listComboMarkets({\n * pageSize: 10,\n * });\n *\n * const firstPage = await paginator.firstPage();\n *\n * // Optionally, fetch additional pages:\n * for await (const page of paginator.from(firstPage.nextCursor)) {\n * // page.items: ComboMarket[]\n * }\n * ```\n *\n * @example\n * Loop through all pages with `for await`:\n * ```ts\n * const paginator = client.listComboMarkets({\n * pageSize: 10,\n * });\n *\n * for await (const page of paginator) {\n * // page.items: ComboMarket[]\n * }\n * ```\n *\n * @example\n * Omit markets the caller has already displayed:\n * ```ts\n * const paginator = client.listComboMarkets({\n * exclude: ['0x4cd77d456c83e7d8c569a8fb8f6396c3f40154f657e6d970733e2b1b6a7110ff'],\n * pageSize: 10,\n * });\n * ```\n */\n listComboMarkets(\n request?: ListComboMarketsRequest,\n options?: RequestOptions,\n ): Paginated<ComboMarket[]>;\n\n /**\n * Fetches a market.\n *\n * @remarks\n * Legacy multi-outcome markets cannot be represented by the binary\n * {@link Market} model, so fetching one fails with an\n * `UnexpectedResponseError`.\n *\n * @throws {@link FetchMarketError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const market = await client.fetchMarket({\n * id: '12345',\n * });\n *\n * const marketBySlug = await client.fetchMarket({\n * slug: 'some-market-slug',\n * });\n *\n * const marketByUrl = await client.fetchMarket({\n * url: 'https://operator.example/event/example-market',\n * });\n * ```\n */\n fetchMarket(\n request: FetchMarketRequest,\n options?: RequestOptions,\n ): 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(\n request: FetchMarketTagsRequest,\n options?: RequestOptions,\n ): 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(\n request?: ListSeriesRequest,\n options?: RequestOptions,\n ): 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(\n request: FetchSeriesRequest,\n options?: RequestOptions,\n ): Promise<Series>;\n\n /**\n * Lists market clarifications — notes that resolve ambiguity in how a market\n * settles.\n *\n * @throws {@link ListMarketClarificationsError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const paginator = client.listMarketClarifications({\n * marketId: '512038',\n * });\n *\n * for await (const page of paginator) {\n * // page.items: MarketClarification[]\n * }\n * ```\n */\n listMarketClarifications(\n request?: ListMarketClarificationsRequest,\n options?: RequestOptions,\n ): Paginated<MarketClarification[]>;\n\n /**\n * Lists tags.\n *\n * @throws {@link ListTagsError}\n * Thrown on failure.\n *\n * @example\n * Fetch the first page of results:\n * ```ts\n * const paginator = client.listTags({\n * pageSize: 10,\n * });\n *\n * const firstPage = await paginator.firstPage();\n *\n * // Optionally, fetch additional pages:\n * for await (const page of paginator.from(firstPage.nextCursor)) {\n * // page.items: Tag[]\n * }\n * ```\n *\n * @example\n * Loop through all pages with `for await`:\n * ```ts\n * const paginator = client.listTags({\n * pageSize: 10,\n * });\n *\n * for await (const page of paginator) {\n * // page.items: Tag[]\n * }\n * ```\n */\n listTags(\n request?: ListTagsRequest,\n options?: RequestOptions,\n ): 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, options?: RequestOptions): 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(\n request: FetchRelatedTagsRequest,\n options?: RequestOptions,\n ): 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 options?: RequestOptions,\n ): Promise<Tag[]>;\n\n /**\n * Runs a public full-text search.\n *\n * `keepClosedMarkets` is an hour window for including recently closed markets\n * when searching active events.\n *\n * Search serves up to 100 pages. If more results may exist at that boundary,\n * automatic iteration yields the page with `limitReached: true` and stops\n * normally, keeping `hasMore` true. Explicitly following its cursor throws\n * {@link PaginationLimitError} before any request. Completeness is unknown.\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(\n request: SearchRequest,\n options?: RequestOptions,\n ): 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(options?: RequestOptions): 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(\n options?: RequestOptions,\n ): 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(\n request?: ListTeamsRequest,\n options?: RequestOptions,\n ): 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 options?: RequestOptions,\n ): Promise<PublicProfile | null>;\n\n /**\n * Lists comments for an event or series.\n *\n * @remarks\n * Without `order`, pages are newest first and `ascending` is ignored. With\n * `order` (`id` or `createdAt`), pages are ascending unless `ascending` is\n * `false`.\n *\n * Reads without `holdersOnly` or `getPositions` and with one of those orders\n * page through the whole thread. Their cursors continue that exact query and\n * are rejected for a different parent, order or direction.\n *\n * Reads with `holdersOnly`, `getPositions` or another order serve pages up to\n * offset 200. Automatic iteration yields the last accessible full page with\n * `limitReached: true` and stops normally; `hasMore` stays true because\n * completeness cannot be established. Explicitly following its cursor throws\n * {@link PaginationLimitError} before any request. Cursors saved from earlier\n * versions keep working with the same arguments.\n *\n * `pageSize` counts top-level comments; replies ride along in the same page.\n * A thread ending exactly on a page boundary may return one final empty page.\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(\n request: ListCommentsRequest,\n options?: RequestOptions,\n ): 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(\n request: FetchCommentsByIdRequest,\n options?: RequestOptions,\n ): Promise<Comment[]>;\n\n /**\n * Lists comments written by a wallet address.\n *\n * @remarks\n * Pages starting past offset 200 are not served. Automatic iteration yields\n * the last accessible full page with `limitReached: true` and stops normally;\n * `hasMore` stays true because completeness cannot be established. Explicitly\n * following its cursor throws {@link PaginationLimitError} before any request.\n *\n * This is a hard stop for this listing: there are no range filters to\n * retrieve the remaining comments.\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: 'createdAt',\n * ascending: false,\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: 'createdAt',\n * ascending: false,\n * });\n *\n * for await (const page of paginator) {\n * // page.items: Comment[]\n * }\n * ```\n */\n listCommentsByUserAddress(\n request: ListCommentsByUserAddressRequest,\n options?: RequestOptions,\n ): Paginated<Comment[]>;\n};\n\nexport function discoveryActions(client: BasePublicClient): DiscoveryActions;\nexport function discoveryActions(client: BaseSecureClient): DiscoveryActions;\nexport function discoveryActions(client: BaseClient): DiscoveryActions {\n return {\n listEvents: listEvents.bind(null, client),\n fetchEvent: fetchEvent.bind(null, client),\n fetchEventTags: fetchEventTags.bind(null, client),\n listMarkets: listMarkets.bind(null, client),\n listComboMarkets: listComboMarkets.bind(null, client),\n fetchMarket: fetchMarket.bind(null, client),\n fetchMarketTags: fetchMarketTags.bind(null, client),\n listSeries: listSeries.bind(null, client),\n fetchSeries: fetchSeries.bind(null, client),\n listMarketClarifications: listMarketClarifications.bind(null, client),\n listTags: listTags.bind(null, client),\n fetchTag: fetchTag.bind(null, client),\n fetchRelatedTags: fetchRelatedTags.bind(null, client),\n fetchRelatedTagResources: fetchRelatedTagResources.bind(null, client),\n search: search.bind(null, client),\n listSports: listSports.bind(null, client),\n fetchSportsMarketTypes: fetchSportsMarketTypes.bind(null, client),\n listTeams: listTeams.bind(null, client),\n fetchPublicProfile: fetchPublicProfile.bind(null, client),\n listComments: listComments.bind(null, client),\n fetchCommentsById: fetchCommentsById.bind(null, client),\n listCommentsByUserAddress: listCommentsByUserAddress.bind(null, client),\n };\n}\n\n// Error unions and runtime `isError` guards for every action bound above.\n// Surfaced at the root entry point through `export * from './decorators'`.\n// Keep this list in sync with the methods on DiscoveryActions.\nexport {\n FetchCommentsByIdError,\n FetchEventError,\n FetchEventTagsError,\n FetchMarketError,\n FetchMarketTagsError,\n FetchPublicProfileError,\n FetchRelatedTagResourcesError,\n FetchRelatedTagsError,\n FetchSeriesError,\n FetchSportsMarketTypesError,\n FetchTagError,\n ListComboMarketsError,\n ListCommentsByUserAddressError,\n ListCommentsError,\n ListEventsError,\n ListMarketsError,\n ListSeriesError,\n ListSportsError,\n ListTagsError,\n ListTeamsError,\n SearchError,\n} from '../actions';\n","import type {\n PerpsBook,\n PerpsBuilderStatus,\n PerpsCandle,\n PerpsFeeScheduleEntry,\n PerpsFundingRate,\n PerpsInstrument,\n PerpsInternalTransferId,\n PerpsPositionSnapshots,\n PerpsPublicTrade,\n PerpsTicker,\n PerpsWithdrawalId,\n} from '@kuest/bindings/perps';\nimport {\n type DepositToPerpsRequest,\n depositToPerps,\n type FetchPerpsBookRequest,\n type FetchPerpsInstrumentsRequest,\n type FetchPerpsTickerRequest,\n type FetchPerpsTickersRequest,\n fetchPerpsBook,\n fetchPerpsFees,\n fetchPerpsInstruments,\n fetchPerpsTicker,\n fetchPerpsTickers,\n type ListPerpsCandlesRequest,\n type ListPerpsFundingHistoryRequest,\n type ListPerpsTradesRequest,\n listPerpsCandles,\n listPerpsFundingHistory,\n listPerpsTrades,\n type OpenPerpsSessionRequest,\n openPerpsSession,\n type PerpsSession,\n type RevokePerpsCredentialsRequest,\n revokePerpsCredentials,\n type TransferPerpsCollateralRequest,\n transferPerpsCollateral,\n type WithdrawFromPerpsRequest,\n withdrawFromPerps,\n} from '../actions';\nimport {\n type FetchPerpsBuilderStatusRequest,\n fetchPerpsBuilderStatus,\n} from '../actions/perps/builders';\nimport {\n type FetchPerpsPositionSnapshotsRequest,\n fetchPerpsPositionSnapshots,\n} from '../actions/perps/position-snapshots';\nimport {\n type FetchPerpsRegistrationRequest,\n fetchPerpsRegistration,\n} from '../actions/perps/registration';\nimport type {\n BaseClient,\n BasePublicClient,\n BaseSecureClient,\n} from '../clients';\n\n/** @experimental This API may change in a breaking way in any release, including patch releases. */\nexport {\n FetchPerpsPositionSnapshotsError,\n type FetchPerpsPositionSnapshotsRequest,\n type PerpsPositionSnapshotFill,\n type PerpsPositionSnapshotSelection,\n} from '../actions/perps/position-snapshots';\n\nimport type { Paginated } from '../pagination';\nimport type { RequestOptions } from '../request-options';\nimport type { TransactionHandle } from '../types';\n\n/** @experimental This API may change in a breaking way in any release, including patch releases. */\nexport type {\n ArmPerpsAutoCancelRequest,\n CancelAllPerpsOrdersRequest,\n CancelPerpsOrderRequest,\n CancelPerpsOrdersRequest,\n CreatePerpsSessionRequest,\n DepositToPerpsRequest,\n DisarmPerpsAutoCancelRequest,\n FetchPerpsAccountConfigRequest,\n FetchPerpsBookRequest,\n FetchPerpsInstrumentsRequest,\n FetchPerpsOpenOrdersRequest,\n FetchPerpsOrdersRequest,\n FetchPerpsTickerRequest,\n FetchPerpsTickersRequest,\n ListPerpsCandlesRequest,\n ListPerpsDepositsRequest,\n ListPerpsEquityHistoryRequest,\n ListPerpsFillsRequest,\n ListPerpsFundingHistoryRequest,\n ListPerpsFundingPaymentsRequest,\n ListPerpsInternalTransfersRequest,\n ListPerpsNotificationsRequest,\n ListPerpsPnlHistoryRequest,\n ListPerpsTradesRequest,\n ListPerpsWithdrawalsRequest,\n MarkPerpsNotificationsReadRequest,\n OpenPerpsSessionRequest,\n PerpsAutoCancelStatus,\n PerpsBookDepth,\n PerpsCancelOptions,\n PerpsCancelOrderResult,\n PerpsCancelRetryOptions,\n PerpsOrderRequest,\n PerpsPlacedTpSlOrder,\n PerpsPlacedTpSlOrders,\n PerpsPlaceFokOrderRequest,\n PerpsPlaceGtcOrderRequest,\n PerpsPlaceGtdOrderRequest,\n PerpsPlaceIocOrderRequest,\n PerpsPositionTpSlTrigger,\n PerpsPositionTrailingStop,\n PerpsPostOrderAck,\n PerpsSession,\n PerpsSessionAccountError,\n PerpsSessionEvent,\n PerpsSessionLifecycleError,\n PerpsSessionTradingError,\n PerpsTpSlTrigger,\n PerpsTrailingStop,\n PerpsUpdateLeverageBatchResult,\n PerpsUpdateLeverageRejection,\n PerpsUpdateLeverageResult,\n PlacePerpsOrderRequest,\n PlacePerpsOrderResult,\n PlacePerpsOrderWithTpSlRequest,\n PlacePerpsOrderWithTpSlResult,\n PlacePerpsPositionTpSlRequest,\n PlacePerpsPositionTpSlResult,\n PostPerpsOrdersRequest,\n ResumePerpsSessionRequest,\n RevokePerpsCredentialsRequest,\n TransferPerpsCollateralRequest,\n UpdatePerpsLeverageRequest,\n UpdatePerpsLeveragesRequest,\n UpdatePerpsMarginRequest,\n WithdrawFromPerpsRequest,\n} from '../actions';\n/** @experimental This API may change in a breaking way in any release, including patch releases. */\nexport {\n ArmPerpsAutoCancelError,\n DepositToPerpsError,\n FetchPerpsBookError,\n FetchPerpsFeesError,\n FetchPerpsInstrumentsError,\n FetchPerpsTickerError,\n FetchPerpsTickersError,\n ListPerpsCandlesError,\n ListPerpsFundingHistoryError,\n ListPerpsTradesError,\n OpenPerpsSessionError,\n RevokePerpsCredentialsError,\n TransferPerpsCollateralError,\n UpdatePerpsLeverageError,\n UpdatePerpsLeveragesError,\n UpdatePerpsMarginError,\n WithdrawFromPerpsError,\n} from '../actions';\n/** @experimental This API may change in a breaking way in any release, including patch releases. */\nexport {\n ApprovePerpsBuilderFeeError,\n type ApprovePerpsBuilderFeeRequest,\n FetchPerpsBuilderStatusError,\n type FetchPerpsBuilderStatusRequest,\n} from '../actions/perps/builders';\n/** @experimental This API may change in a breaking way in any release, including patch releases. */\nexport {\n FetchPerpsRegistrationError,\n type FetchPerpsRegistrationRequest,\n} from '../actions/perps/registration';\n/** @experimental This API may change in a breaking way in any release, including patch releases. */\nexport {\n FetchPerpsBuilderApprovalsError,\n type FetchPerpsBuilderApprovalsRequest,\n FetchPerpsBuilderEarningsSummaryError,\n type FetchPerpsBuilderEarningsSummaryRequest,\n ListPerpsBuilderEarningsError,\n type ListPerpsBuilderEarningsRequest,\n type PerpsBuilderFillUpdateEvent,\n type PerpsBuilderTermsInput,\n RevokePerpsBuilderFeeError,\n} from '../websockets/perps/session';\n\n/**\n * @experimental This API may change in a breaking way in any release, including patch releases.\n */\nexport type PublicPerpsActions = {\n /** Fetches ordered snapshots anonymously, including on secure clients. Use\n * session.fetchPositionSnapshots for owner-only leverage and PnL percentage.\n * No pagination or automatic retries of item statuses.\n * @throws {@link FetchPerpsPositionSnapshotsError} Thrown on failure.\n * @experimental This API may change in a breaking way in any release, including patch releases.\n */\n fetchPerpsPositionSnapshots(\n request: FetchPerpsPositionSnapshotsRequest,\n options?: RequestOptions,\n ): Promise<PerpsPositionSnapshots>;\n /**\n * Fetches whether an address has a Perps account without authentication.\n * Registration is permanent; a false result may be cached for up to ten seconds.\n * @throws {@link FetchPerpsRegistrationError} Thrown on failure.\n * @experimental This API may change in a breaking way in any release, including patch releases.\n */\n fetchPerpsRegistration(\n request: FetchPerpsRegistrationRequest,\n options?: RequestOptions,\n ): Promise<boolean>;\n /**\n * Fetches public builder availability and the platform fee cap.\n * @throws {@link FetchPerpsBuilderStatusError} Thrown on failure.\n * @experimental This API may change in a breaking way in any release, including patch releases.\n */\n fetchPerpsBuilderStatus(\n request: FetchPerpsBuilderStatusRequest,\n options?: RequestOptions,\n ): Promise<PerpsBuilderStatus>;\n /**\n * Fetches Perps instruments.\n *\n * @example\n * ```ts\n * const instruments = await client.fetchPerpsInstruments();\n * ```\n *\n * @throws {@link FetchPerpsInstrumentsError}\n * Thrown on failure.\n *\n * @experimental This API may change in a breaking way in any release, including patch releases.\n */\n fetchPerpsInstruments(\n request?: FetchPerpsInstrumentsRequest,\n options?: RequestOptions,\n ): Promise<PerpsInstrument[]>;\n\n /**\n * Fetches the current Perps ticker for an instrument.\n *\n * @example\n * ```ts\n * const ticker = await client.fetchPerpsTicker({ instrumentId: 1 });\n * ```\n *\n * @throws {@link FetchPerpsTickerError}\n * Thrown on failure.\n *\n * @experimental This API may change in a breaking way in any release, including patch releases.\n */\n fetchPerpsTicker(\n request: FetchPerpsTickerRequest,\n options?: RequestOptions,\n ): Promise<PerpsTicker>;\n\n /**\n * Fetches current Perps tickers.\n *\n * @example\n * ```ts\n * const tickers = await client.fetchPerpsTickers();\n * ```\n *\n * @throws {@link FetchPerpsTickersError}\n * Thrown on failure.\n *\n * @experimental This API may change in a breaking way in any release, including patch releases.\n */\n fetchPerpsTickers(\n request?: FetchPerpsTickersRequest,\n options?: RequestOptions,\n ): Promise<PerpsTicker[]>;\n\n /**\n * Fetches a Perps order book.\n *\n * @example\n * ```ts\n * const book = await client.fetchPerpsBook({ instrumentId: 1, depth: 100 });\n * ```\n *\n * @throws {@link FetchPerpsBookError}\n * Thrown on failure.\n *\n * @experimental This API may change in a breaking way in any release, including patch releases.\n */\n fetchPerpsBook(\n request: FetchPerpsBookRequest,\n options?: RequestOptions,\n ): Promise<PerpsBook>;\n\n /**\n * Lists Perps candles for an instrument with SDK-owned pagination.\n *\n * @example\n * ```ts\n * for await (const candles of client.listPerpsCandles({\n * instrumentId: 1,\n * interval: PerpsKlineInterval.OneMinute,\n * })) {\n * console.log(candles);\n * }\n * ```\n *\n * @throws {@link ListPerpsCandlesError}\n * Thrown on failure.\n *\n * @experimental This API may change in a breaking way in any release, including patch releases.\n */\n listPerpsCandles(\n request: ListPerpsCandlesRequest,\n options?: RequestOptions,\n ): Paginated<PerpsCandle[]>;\n\n /**\n * Lists Perps funding-rate history for an instrument with SDK-owned pagination.\n *\n * @example\n * ```ts\n * for await (const rates of client.listPerpsFundingHistory({\n * instrumentId: 1,\n * })) {\n * console.log(rates);\n * }\n * ```\n *\n * @throws {@link ListPerpsFundingHistoryError}\n * Thrown on failure.\n *\n * @experimental This API may change in a breaking way in any release, including patch releases.\n */\n listPerpsFundingHistory(\n request: ListPerpsFundingHistoryRequest,\n options?: RequestOptions,\n ): Paginated<PerpsFundingRate[]>;\n\n /**\n * Lists recent Perps trades for an instrument with SDK-owned pagination.\n *\n * @example\n * ```ts\n * for await (const trades of client.listPerpsTrades({ instrumentId: 1 })) {\n * console.log(trades);\n * }\n * ```\n *\n * @throws {@link ListPerpsTradesError}\n * Thrown on failure.\n *\n * @experimental This API may change in a breaking way in any release, including patch releases.\n */\n listPerpsTrades(\n request: ListPerpsTradesRequest,\n options?: RequestOptions,\n ): Paginated<PerpsPublicTrade[]>;\n\n /**\n * Fetches the Perps fee schedule.\n *\n * @example\n * ```ts\n * const fees = await client.fetchPerpsFees();\n * ```\n *\n * @throws {@link FetchPerpsFeesError}\n * Thrown on failure.\n *\n * @experimental This API may change in a breaking way in any release, including patch releases.\n */\n fetchPerpsFees(options?: RequestOptions): Promise<PerpsFeeScheduleEntry[]>;\n};\n\n/**\n * @experimental This API may change in a breaking way in any release, including patch releases.\n */\nexport type SecurePerpsActions = PublicPerpsActions & {\n /**\n * Deposits collateral into Perps for the authenticated signer account.\n *\n * @example\n * ```ts\n * const transaction = await client.depositToPerps({ amount: 100_000_000n });\n * ```\n *\n * @throws {@link DepositToPerpsError}\n * Thrown on failure.\n *\n * @experimental This API may change in a breaking way in any release, including patch releases.\n */\n depositToPerps(request: DepositToPerpsRequest): Promise<TransactionHandle>;\n\n /**\n * Opens a Perps account session.\n *\n * @remarks\n * Omit `expiresIn` to create new delegated Perps credentials that expire after\n * one week. Pass `expiresIn` as a duration in milliseconds to use a shorter or\n * longer credential lifetime, or pass existing credentials to validate and\n * resume a previous session.\n * Pass `builderAttribution` to select a builder for new orders and TP/SL exits.\n * Opening or resuming checks builder availability and uses the lower of the\n * builder cap and the trader's saved approved maximum. Missing approval counts\n * as zero. A zero effective fee disables attribution without failing setup.\n * Approve a maximum explicitly with `session.approveBuilderFee({ maxFeeRate })`.\n * The builder address defaults to the session's selected builder.\n * Opening a session never grants consent. Approval remains valid until revoked\n * or replaced and does not need to be repeated for each session.\n * Set `includeBuilderFills` to receive builder receipts in the session iterator.\n *\n * @example\n * ```ts\n * const session = await client.openPerpsSession({\n * builderAttribution: builderAddress,\n * });\n * ```\n *\n * @throws {@link OpenPerpsSessionError}\n * Thrown on failure.\n *\n * @experimental This API may change in a breaking way in any release, including patch releases.\n */\n openPerpsSession(request?: OpenPerpsSessionRequest): Promise<PerpsSession>;\n\n /**\n * Revokes delegated Perps credentials by proxy address.\n *\n * @remarks\n * This can revoke credentials outside the currently open Perps session.\n *\n * @example\n * ```ts\n * await client.revokePerpsCredentials({ proxy: session.credentials.proxy });\n * ```\n *\n * @throws {@link RevokePerpsCredentialsError}\n * Thrown on failure.\n *\n * @experimental This API may change in a breaking way in any release, including patch releases.\n */\n revokePerpsCredentials(request: RevokePerpsCredentialsRequest): Promise<void>;\n\n /**\n * Transfers Perps collateral to another account.\n *\n * @remarks\n * This owner-signed request is attempted once. If a timeout or server error\n * occurs after submission, reconcile through internal-transfer history using\n * the label before submitting another transfer.\n *\n * @example\n * ```ts\n * const transferId = await client.transferPerpsCollateral({\n * recipient: '0x70997970C51812dc3A010C7d01b50e0d17dc79C8',\n * amount: '100.00',\n * label: 'treasury-rebalance-42',\n * });\n * ```\n *\n * @throws {@link TransferPerpsCollateralError}\n * Thrown on failure.\n *\n * @experimental This API may change in a breaking way in any release, including patch releases.\n */\n transferPerpsCollateral(\n request: TransferPerpsCollateralRequest,\n ): Promise<PerpsInternalTransferId>;\n\n /**\n * Requests a Perps withdrawal to the authenticated wallet.\n *\n * @example\n * ```ts\n * const withdrawalId = await client.withdrawFromPerps({ amount: 100_000_000n });\n * ```\n *\n * @throws {@link WithdrawFromPerpsError}\n * Thrown on failure.\n *\n * @experimental This API may change in a breaking way in any release, including patch releases.\n */\n withdrawFromPerps(\n request: WithdrawFromPerpsRequest,\n ): Promise<PerpsWithdrawalId>;\n};\n\n/**\n * @experimental This API may change in a breaking way in any release, including patch releases.\n */\nexport type PerpsActions = PublicPerpsActions;\n\n/**\n * @experimental This API may change in a breaking way in any release, including patch releases.\n */\nexport function perpsActions(client: BasePublicClient): PublicPerpsActions;\n/**\n * @experimental This API may change in a breaking way in any release, including patch releases.\n */\nexport function perpsActions(client: BaseSecureClient): SecurePerpsActions;\n/**\n * @experimental This API may change in a breaking way in any release, including patch releases.\n */\nexport function perpsActions(\n client: BaseClient,\n): PublicPerpsActions | SecurePerpsActions {\n const actions: PublicPerpsActions = {\n fetchPerpsPositionSnapshots: fetchPerpsPositionSnapshots.bind(null, client),\n fetchPerpsRegistration: fetchPerpsRegistration.bind(null, client),\n fetchPerpsBuilderStatus: fetchPerpsBuilderStatus.bind(null, client),\n fetchPerpsBook: fetchPerpsBook.bind(null, client),\n fetchPerpsFees: fetchPerpsFees.bind(null, client),\n fetchPerpsInstruments: fetchPerpsInstruments.bind(null, client),\n fetchPerpsTicker: fetchPerpsTicker.bind(null, client),\n fetchPerpsTickers: fetchPerpsTickers.bind(null, client),\n listPerpsCandles: listPerpsCandles.bind(null, client),\n listPerpsFundingHistory: listPerpsFundingHistory.bind(null, client),\n listPerpsTrades: listPerpsTrades.bind(null, client),\n };\n\n if (!client.isSecureClient()) return actions;\n\n return {\n ...actions,\n depositToPerps: (request) => depositToPerps(client, request),\n openPerpsSession: (request) => openPerpsSession(client, request),\n revokePerpsCredentials: (request) =>\n revokePerpsCredentials(client, request),\n transferPerpsCollateral: transferPerpsCollateral.bind(null, client),\n withdrawFromPerps: (request) => withdrawFromPerps(client, request),\n };\n}\n\n/** @experimental This API may change in a breaking way in any release, including patch releases. */\nexport type {\n PerpsChase,\n PerpsChaseAccepted,\n PerpsChaseId,\n} from '@kuest/bindings/perps';\n/** @experimental This API may change in a breaking way in any release, including patch releases. */\nexport {\n type PerpsTwap,\n type PerpsTwapAccepted,\n type PerpsTwapId,\n PerpsTwapStatus,\n} from '@kuest/bindings/perps';\n/** @experimental This API may change in a breaking way in any release, including patch releases. */\nexport {\n CancelPerpsChaseError,\n type CancelPerpsChaseRequest,\n CreatePerpsChaseError,\n type CreatePerpsChaseRequest,\n FetchPerpsChasesError,\n} from '../websockets/perps/actions/chases';\n/** @experimental This API may change in a breaking way in any release, including patch releases. */\nexport {\n CancelPerpsTwapError,\n type CancelPerpsTwapRequest,\n CreatePerpsTwapError,\n type CreatePerpsTwapRequest,\n FetchPerpsTwapsError,\n PausePerpsTwapError,\n type PausePerpsTwapRequest,\n ResumePerpsTwapError,\n type ResumePerpsTwapRequest,\n} from '../websockets/perps/actions/twaps';\n","import type {\n CurrentReward,\n MarketReward,\n OrdersScoringResponse,\n RebatedFee,\n RewardMarket,\n RewardsPercentages,\n TotalUserEarning,\n UserEarning,\n UserRewardsEarning,\n} from '@kuest/bindings/clob';\nimport type { Prettify } from '@kuest/types';\nimport {\n type FetchCurrentRebatesRequest,\n type FetchOrderScoringRequest,\n type FetchOrdersScoringRequest,\n type FetchTotalEarningsForUserForDayRequest,\n fetchCurrentRebates,\n fetchOrderScoring,\n fetchOrdersScoring,\n fetchRewardPercentages,\n fetchTotalEarningsForUserForDay,\n type ListCurrentRewardsRequest,\n type ListMarketRewardsRequest,\n type ListRewardMarketsRequest,\n type ListUserEarningsAndMarketsConfigRequest,\n type ListUserEarningsForDayRequest,\n listCurrentRewards,\n listMarketRewards,\n listRewardMarkets,\n listUserEarningsAndMarketsConfig,\n listUserEarningsForDay,\n} from '../actions';\nimport type {\n BaseClient,\n BasePublicClient,\n BaseSecureClient,\n} from '../clients';\nimport type { Paginated } from '../pagination';\nimport type { RequestOptions } from '../request-options';\n\nexport type PublicRewardsActions = {\n /**\n * Fetches maker fee rebates for a calendar day as a direct collection.\n * Amounts are decimal strings in USDC units. No authentication is required.\n * Returns an empty array when the maker has no rebates for the date.\n * @throws {@link FetchCurrentRebatesError} Thrown on failure.\n * @example\n * ```ts\n * const rebates = await client.fetchCurrentRebates({ date: '2026-10-06', makerAddress });\n * ```\n */\n fetchCurrentRebates(\n request: FetchCurrentRebatesRequest,\n options?: RequestOptions,\n ): Promise<RebatedFee[]>;\n\n /**\n * Lists active markets with reward configurations and discovery metadata.\n * Configurations may be empty. Positive ranges are min-exclusive and max-inclusive; zero disables a bound.\n * Pages default to 100 items (maximum 500). With orderBy, sortDirection defaults to ASC; otherwise order is unspecified.\n * @throws {@link ListRewardMarketsError} Thrown on failure.\n * @example\n * ```ts\n * for await (const page of client.listRewardMarkets({ query: 'sports' })) {\n * console.log(page.items);\n * }\n * ```\n */\n listRewardMarkets(\n request?: ListRewardMarketsRequest,\n options?: RequestOptions,\n ): Paginated<RewardMarket[]>;\n\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 options?: RequestOptions,\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 options?: RequestOptions,\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(\n request: FetchOrderScoringRequest,\n options?: RequestOptions,\n ): 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 options?: RequestOptions,\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 options?: RequestOptions,\n ): Paginated<UserEarning[]>;\n /**\n * Fetches total earnings for the authenticated account on a given day.\n * Set `sponsored: true` to include sponsored rewards and the native/sponsored\n * breakdown. Omitted or false returns native rewards only; absent breakdown\n * fields remain undefined.\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 options?: RequestOptions,\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 options?: RequestOptions,\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(\n options?: RequestOptions,\n ): Promise<RewardsPercentages>;\n }\n>;\n\nfunction publicRewardsActions(client: BaseClient): PublicRewardsActions {\n return {\n fetchCurrentRebates: fetchCurrentRebates.bind(null, client),\n listRewardMarkets: listRewardMarkets.bind(null, client),\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 FetchCurrentRebatesError,\n type FetchCurrentRebatesRequest,\n FetchOrderScoringError,\n FetchOrdersScoringError,\n FetchRewardPercentagesError,\n FetchTotalEarningsForUserForDayError,\n ListCurrentRewardsError,\n ListMarketRewardsError,\n ListRewardMarketsError,\n type ListRewardMarketsRequest,\n ListUserEarningsAndMarketsConfigError,\n ListUserEarningsForDayError,\n} from '../actions';\n","import type {\n AcceptComboQuoteParams,\n AcceptComboQuoteResult,\n RequestComboQuoteParams,\n RequestComboQuoteResult,\n RfqSession,\n WaitForComboFillParams,\n WaitForComboFillResult,\n} from '../actions';\nimport {\n acceptComboQuote,\n openRfqSession,\n requestComboQuote,\n waitForComboFill,\n} from '../actions';\nimport type { BaseSecureClient } from '../clients';\n\nexport type {\n BuilderRfqError,\n ComboQuote,\n FetchRfqStatusParams,\n RfqCancelQuoteAck,\n RfqCancelQuoteRejectedErrorOptions,\n RfqConfirmationAck,\n RfqConfirmationRequest,\n RfqConfirmationRequestEvent,\n RfqErrorCode,\n RfqEvent,\n RfqExecutionUpdate,\n RfqId,\n RfqQuoteId,\n RfqQuoteReference,\n RfqQuoteRejectedErrorOptions,\n RfqQuoteRequest,\n RfqQuoteRequestEvent,\n RfqQuoteResponse,\n RfqQuoteSource,\n RfqRequestedSize,\n RfqRequestorPublicId,\n RfqRequestRejectedErrorOptions,\n RfqSession,\n RfqStatusResult,\n RfqTrade,\n RfqTradeEvent,\n} from '../actions/rfq';\nexport {\n AcceptComboQuoteError,\n ComboAcceptFailureReason,\n ComboQuoteUnavailableReason,\n FetchRfqStatusError,\n OpenRfqSessionError,\n RequestComboQuoteError,\n RfqCancelQuoteError,\n RfqCancelQuoteRejectedError,\n RfqConfirmationDecision,\n RfqConfirmationError,\n RfqConfirmationRejectedError,\n RfqDirection,\n RfqExecutionStatus,\n RfqKnownErrorCode,\n RfqQuoteError,\n RfqQuoteRejectedError,\n RfqRejectionCode,\n RfqRequestedSizeUnit,\n RfqRequestRejectedError,\n RfqSide,\n RfqStatus,\n WaitForComboFillError,\n} from '../actions/rfq';\nexport type {\n AcceptComboQuoteParams,\n AcceptComboQuoteResult,\n RequestComboQuoteParams,\n RequestComboQuoteResult,\n WaitForComboFillParams,\n WaitForComboFillResult,\n};\n\nexport type SecureRfqActions = {\n /**\n * Opens an RFQ event session.\n *\n * @remarks\n * The returned async iterator is a stream, not a worker queue. Await inside the\n * loop to process RFQ events sequentially, or dispatch handlers without awaiting\n * them to fan out handling when quote windows are tight.\n *\n * @example\n * Quote the full requested size:\n * ```ts\n * const session = await client.openRfqSession();\n *\n * for await (const event of session) {\n * switch (event.type) {\n * case 'quote_request':\n * await event.quote({ price: 0.45 });\n * break;\n *\n * case 'execution_update':\n * // event.rfqId: RfqId\n * // event.status: RfqExecutionStatus\n * // event.txHash: TxHash | undefined\n * break;\n * }\n * }\n * ```\n *\n * @example\n * Quote a specific outcome-token size. `0.5` means half of one share, not\n * half of one 6-decimal base unit:\n * ```ts\n * const session = await client.openRfqSession();\n *\n * for await (const event of session) {\n * switch (event.type) {\n * case 'quote_request':\n * await event.quote({ price: 0.45, size: 0.5 });\n * break;\n *\n * // …\n * }\n * }\n * ```\n *\n * @example\n * Cancel a submitted quote using the live session:\n * ```ts\n * const session = await client.openRfqSession();\n *\n * for await (const event of session) {\n * switch (event.type) {\n * case 'quote_request': {\n * const ref = await event.quote({ price: 0.45 });\n *\n * if (shouldCancel(ref)) {\n * await session.cancelQuote(ref);\n * }\n * break;\n * }\n *\n * // …\n * }\n * }\n * ```\n * The cancellation ack means the backend processed the request; it does not\n * guarantee the quote was withdrawn from an already-selected RFQ.\n *\n * @example\n * Handle Last Look confirmation requests:\n * ```ts\n * const session = await client.openRfqSession();\n *\n * for await (const event of session) {\n * switch (event.type) {\n * case 'quote_request':\n * await event.quote({ price: 0.45 });\n * break;\n *\n * case 'confirmation_request':\n * await event.confirm();\n * break;\n *\n * // …\n * }\n * }\n * ```\n * Any maker can quote permissionlessly. Last Look confirmation requests are\n * only sent to makers with Last Look enabled.\n *\n * @example\n * Choose collateral or inventory per request:\n * ```ts\n * const session = await client.openRfqSession();\n *\n * for await (const event of session) {\n * switch (event.type) {\n * case 'quote_request': {\n * switch (event.direction) {\n * case RfqDirection.Buy:\n * await event.quote({\n * price: 0.45,\n * source: chooseSource(event.yesPositionId, event.requestedSize),\n * });\n * break;\n *\n * case RfqDirection.Sell:\n * await event.quote({\n * price: 0.45,\n * source: chooseSource(event.noPositionId, event.requestedSize),\n * });\n * break;\n * }\n * break;\n * }\n *\n * case 'confirmation_request':\n * await event.confirm();\n * break;\n *\n * // …\n * }\n * }\n *\n * function chooseSource(positionId: PositionId, requestedSize: RfqRequestedSize): RfqQuoteSource {\n * return hasInventory(positionId, requestedSize) ? 'inventory' : 'collateral';\n * }\n * ```\n *\n * @throws {@link OpenRfqSessionError}\n * Thrown on failure.\n */\n openRfqSession(): Promise<RfqSession>;\n\n /**\n * Requests a quote for a combo of positions.\n *\n * @remarks\n * Resolves when the quote competition window closes. A request that\n * attracts no usable quotes is a normal outcome, returned as `quote: null`\n * with a reason rather than thrown.\n *\n * A winning quote is self-contained JSON data and may be persisted or\n * routed to another process before acceptance.\n *\n * Requires a Builder API Key in the client configuration, via\n * `builderApiKey(...)` or `remoteBuilderSigning(...)`.\n *\n * @throws {@link RequestComboQuoteError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const result = await client.requestComboQuote({\n * legPositionIds: ['123', '456'],\n * direction: OrderSide.BUY,\n * amount: 100,\n * });\n *\n * if (result.quote !== null) {\n * // result.quote.blendedPrice: DecimalString\n * // result.quote.totalRequired: DecimalString\n * // SELL quotes also carry result.quote.netReceive after fees.\n * // result.quote.expiresAt: EpochMilliseconds\n * }\n * ```\n */\n requestComboQuote(\n params: RequestComboQuoteParams,\n ): Promise<RequestComboQuoteResult>;\n\n /**\n * Accepts a self-contained combo quote, signing the acceptance order for\n * the authenticated account.\n *\n * @remarks\n * Resolves at the maker last-look outcome. A maker declining or the\n * acceptance window expiring is a normal outcome, returned as\n * `status: 'failed'`. `status: 'executing'` means the trade was handed off\n * for onchain execution; follow it with `waitForComboFill`.\n *\n * A transport failure or unrecognized acceptance response is retried once\n * automatically; this is safe because an already-accepted RFQ reports its\n * current status instead of executing twice. After such a retry\n * `takerOrderHash` is absent because the retried order was not the one\n * recorded.\n *\n * The quote is JSON-serializable and may cross process boundaries before\n * acceptance. The accepting client must represent the same account and\n * builder identity used to request it.\n * Treat the quote as signing-sensitive data: preserve its integrity across\n * process boundaries and do not accept fields modified by an untrusted client.\n *\n * @throws {@link AcceptComboQuoteError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const result = await client.requestComboQuote({\n * legPositionIds: ['123', '456'],\n * direction: OrderSide.BUY,\n * amount: 100,\n * });\n *\n * if (result.quote !== null) {\n * const acceptance = await client.acceptComboQuote(result.quote);\n * }\n * ```\n */\n acceptComboQuote(\n params: AcceptComboQuoteParams,\n ): Promise<AcceptComboQuoteResult>;\n\n /**\n * Waits for an accepted RFQ to reach a terminal state.\n *\n * @remarks\n * Polls the RFQ status until it is filled (or confirmed onchain),\n * `FAILED`, `EXPIRED`, or `CANCELED`. Terminal failure is a normal outcome\n * and is returned, not thrown. A `TimeoutError` does not mean the trade\n * failed; resume with the `fetchRfqStatus` action from\n * `@kuest/sdk/actions`.\n *\n * @throws {@link WaitForComboFillError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const fill = await client.waitForComboFill({ rfqId });\n *\n * if (fill.status === RfqStatus.Filled) {\n * // fill.txHash: TxHash\n * }\n * ```\n */\n waitForComboFill(\n params: WaitForComboFillParams,\n ): Promise<WaitForComboFillResult>;\n};\n\nexport function rfqActions(client: BaseSecureClient): SecureRfqActions {\n return {\n openRfqSession() {\n return openRfqSession(client);\n },\n requestComboQuote(params: RequestComboQuoteParams) {\n return requestComboQuote(client, params);\n },\n acceptComboQuote(params: AcceptComboQuoteParams) {\n return acceptComboQuote(client, params);\n },\n waitForComboFill(params: WaitForComboFillParams) {\n return waitForComboFill(client, params);\n },\n };\n}\n","import {\n type AuthorizeSessionKeyRequest,\n type AuthorizeSessionKeyResult,\n authorizeSessionKey,\n fetchSessionKeys,\n type RevokeSessionKeyRequest,\n revokeSessionKey,\n type SessionKey,\n} from '../actions';\nimport type { BaseSecureClient } from '../clients';\nimport type { RequestOptions } from '../request-options';\n\nexport type SessionKeyActions = {\n /**\n * Authorizes an externally managed signer for selected venues.\n *\n * The SDK receives only the public address. The application remains\n * responsible for generating, storing, and protecting the private key.\n * When scopes are omitted, authorization defaults to `ALL`.\n * The authorization expires 180 days after it is created.\n * Requires builder API-key authentication.\n *\n * @remarks\n * Resolves after the submitted transaction is confirmed and the session key\n * appears in the active session-key list.\n *\n * @example\n * ```ts\n * const authorization = await client.authorizeSessionKey({\n * address: sessionAddress,\n * });\n * ```\n *\n * @throws {@link AuthorizeSessionKeyError}\n * Thrown on failure.\n */\n authorizeSessionKey(\n request: AuthorizeSessionKeyRequest,\n ): Promise<AuthorizeSessionKeyResult>;\n\n /**\n * Fetches the active session keys authorized for the Deposit Wallet.\n *\n * @example\n * ```ts\n * const sessionKeys = await client.fetchSessionKeys();\n * ```\n *\n * @throws {@link FetchSessionKeysError}\n * Thrown on failure.\n */\n fetchSessionKeys(options?: RequestOptions): Promise<SessionKey[]>;\n\n /**\n * Revokes a session key authorized for the Deposit Wallet.\n *\n * Returns once the session key is removed from the active-key registry and can\n * no longer be used. The on-chain transaction may still be pending.\n * Requires API-key authentication that supports gasless transactions.\n *\n * @example\n * ```ts\n * await client.revokeSessionKey({\n * address: sessionAddress,\n * });\n * ```\n *\n * @throws {@link RevokeSessionKeyError}\n * Thrown on failure.\n */\n revokeSessionKey(request: RevokeSessionKeyRequest): Promise<void>;\n};\n\nexport function sessionKeyActions(client: BaseSecureClient): SessionKeyActions {\n return {\n authorizeSessionKey: authorizeSessionKey.bind(null, client),\n fetchSessionKeys: fetchSessionKeys.bind(null, client),\n revokeSessionKey: revokeSessionKey.bind(null, client),\n };\n}\n\nexport type {\n AuthorizeSessionKeyRequest,\n AuthorizeSessionKeyResult,\n RevokeSessionKeyRequest,\n SessionKey,\n SessionKeyScope,\n} from '../actions';\nexport {\n AuthorizeSessionKeyError,\n FetchSessionKeysError,\n RevokeSessionKeyError,\n SessionKeyKnownScope,\n} from '../actions';\n","import {\n type EventForSubscriptionSpecs,\n type PublicSubscriptionSpec,\n type SecureSubscriptionSpec,\n type SubscriptionHandle,\n subscribe,\n} from '../actions';\nimport type {\n BaseClient,\n BasePublicClient,\n BaseSecureClient,\n} from '../clients';\n\nexport type {\n CommentsEvent,\n CommentsSubscription,\n CryptoPriceEvent,\n CryptoPriceSnapshotEvent,\n CryptoPriceSubscription,\n CryptoPricesBinanceEvent,\n CryptoPricesChainlinkEvent,\n CryptoPricesChainlinkTwapEvent,\n CryptoPricesChainlinkTwapSixtyEvent,\n CryptoPricesChainlinkTwapSubscription,\n CryptoPricesChainlinkTwapThirtyEvent,\n CryptoPricesChainlinkTwapWindowSeconds,\n CryptoPricesEvent,\n CryptoPricesSubscription,\n CryptoTwapPriceEvent,\n CryptoTwapPriceSnapshotEvent,\n CryptoTwapPriceSubscription,\n EquityPriceEvent,\n EquityPriceSubscription,\n EquityPricesEvent,\n EquityPricesSubscription,\n EquityTwapPriceEvent,\n EquityTwapPriceSnapshotEvent,\n EquityTwapPriceSubscription,\n PriceSource,\n PriceSubscription,\n PriceSubscriptionConfirmation,\n SubscriptionHandle,\n} from '../actions';\nexport { KnownPriceSource, PriceProvider, SubscribeError } from '../actions';\n\nexport type PublicSubscriptionsActions = {\n /**\n * Starts one or more realtime subscriptions on this client.\n *\n * @throws {@link SubscribeError}\n * Thrown when subscription input is invalid or a realtime subscription fails.\n *\n * @example\n * ```ts\n * const handle = await client.subscribe([\n * { topic: 'market', assetIds: ['123'] },\n * ]);\n *\n * for await (const event of handle) {\n * // event: StandardMarketEvent\n * }\n * ```\n */\n subscribe<const TSubscriptions extends readonly PublicSubscriptionSpec[]>(\n subscriptions: TSubscriptions,\n ): Promise<SubscriptionHandle<EventForSubscriptionSpecs<TSubscriptions>>>;\n};\n\nexport type SecureSubscriptionsActions = {\n /**\n * Starts one or more realtime subscriptions on this client.\n *\n * The `prices.crypto`, `prices.crypto.twap`, `prices.equity`, and\n * `prices.equity.twap` topics\n * require explicit filters and include history snapshots and live updates.\n * Legacy source-named topics retain their existing filter and event behavior.\n * These four topics include `source`, identifying the source of the update\n * or entire history batch, including empty batches. Unknown source names remain\n * strings. Crypto sources are constant; equity sources may change across\n * reconnects. Cached history starts fresh whenever the source changes.\n * These four topics accept an optional `provider` pin. Omit it to follow the\n * default. A pin may fall back or be ignored when selection is disabled;\n * `source` always identifies the actual producer. Different provider choices,\n * including omission, use separate connections, even if they serve the same source.\n * An optional `onSubscribed` callback reports the provider the server confirms,\n * on acceptance and after every reconnect.\n * Event `seq` values are scoped to one channel on one WebSocket connection\n * and reset after reconnecting. Subscriptions with more than 64 filters use\n * multiple connections, so their sequence values may interleave.\n *\n * @throws {@link SubscribeError}\n * Thrown when subscription input is invalid or a realtime subscription fails.\n *\n * @example\n * ```ts\n * const handle = await client.subscribe([\n * { topic: 'user' },\n * { topic: 'market', assetIds: ['123'] },\n * ]);\n *\n * for await (const event of handle) {\n * // event: StandardMarketEvent | UserEvent\n * }\n * ```\n */\n subscribe<const TSubscriptions extends readonly SecureSubscriptionSpec[]>(\n subscriptions: TSubscriptions,\n ): Promise<SubscriptionHandle<EventForSubscriptionSpecs<TSubscriptions>>>;\n};\n\nexport function subscriptionsActions(\n client: BasePublicClient,\n): PublicSubscriptionsActions;\nexport function subscriptionsActions(\n client: BaseSecureClient,\n): SecureSubscriptionsActions;\nexport function subscriptionsActions(\n client: BaseClient,\n): PublicSubscriptionsActions | SecureSubscriptionsActions {\n // Wrap instead of `bind` so the method preserves its generic type parameter\n // and can narrow the resolved event type per call site.\n if (client.isSecureClient()) {\n return {\n subscribe<const TSubscriptions extends readonly SecureSubscriptionSpec[]>(\n subscriptions: TSubscriptions,\n ): Promise<\n SubscriptionHandle<EventForSubscriptionSpecs<TSubscriptions>>\n > {\n return subscribe(client, subscriptions);\n },\n };\n }\n\n return {\n subscribe<const TSubscriptions extends readonly PublicSubscriptionSpec[]>(\n subscriptions: TSubscriptions,\n ): Promise<SubscriptionHandle<EventForSubscriptionSpecs<TSubscriptions>>> {\n return subscribe(client, subscriptions);\n },\n };\n}\n","import type {\n AcceptedOrderResponse,\n CancelOrdersResponse,\n OpenOrder,\n OrderHeartbeat,\n OrderResponse,\n OrderResponses,\n} from '@kuest/bindings/clob';\nimport type { TxHash } from '@kuest/types';\nimport {\n type CancelMarketOrdersRequest,\n type CancelOrderRequest,\n type CancelOrdersRequest,\n cancelAll,\n cancelMarketOrders,\n cancelOrder,\n cancelOrders,\n createLimitOrder,\n createMarketOrder,\n type FetchOrderRequest,\n fetchOrder,\n type ListOpenOrdersRequest,\n listOpenOrders,\n type PostOrdersRequest,\n type PrepareLimitOrderRequest,\n type PrepareMarketOrderRequest,\n placeLimitOrder,\n placeMarketOrder,\n postOrder,\n postOrders,\n type SendOrderHeartbeatRequest,\n sendOrderHeartbeat,\n type WaitForOrderFillSettlementRequest,\n waitForOrderFillSettlement,\n} from '../actions';\nimport type { SignedOrder } from '../actions/orders';\nimport type { BaseSecureClient } from '../clients';\nimport type { Paginated } from '../pagination';\nimport type { RequestOptions } from '../request-options';\n\nexport type { OrderSignature, SignedOrder } from '../actions';\n\nexport type SecureTradingActions = {\n /**\n * Sends one authenticated order heartbeat and returns the next heartbeat ID.\n * The first accepted send enables timeout cancellation for ALL open orders owned\n * by this API key, across markets and processes. Only start when you can keep\n * sending every five seconds. After ten seconds without an accepted send, the\n * server attempts cancel-all; cancellation timing and success are not guaranteed.\n * Start with an empty ID, serialize sends per key, and retain every returned ID.\n * No timer or automatic retry is started. A mismatch does not refresh the deadline;\n * retry explicitly with OrderHeartbeatMismatchError.heartbeatId. A lost response\n * may follow an accepted send, so failure does not prove registration is inactive.\n * There is no disarm operation. Stopping sends or closing the client leaves the\n * deadline active. On shutdown, stop placing orders and explicitly cancel/verify\n * orders you intend to remove. Expiry removes the registration; a later accepted\n * send registers again. This is separate from WebSocket connection keepalive.\n * @throws {@link SendOrderHeartbeatError} Thrown on failure.\n * @example\n * ```ts\n * const heartbeat = await client.sendOrderHeartbeat();\n * const next = await client.sendOrderHeartbeat({ heartbeatId: heartbeat.heartbeatId });\n * ```\n */\n sendOrderHeartbeat(\n request?: SendOrderHeartbeatRequest,\n ): Promise<OrderHeartbeat>;\n\n /**\n * Creates a signed market order for the authenticated account.\n *\n * @throws {@link CreateMarketOrderError}\n * Thrown on failure.\n *\n * @example Basic market buy\n * ```ts\n * const order = await client.createMarketOrder({\n * assetId: '0x0122…0000',\n * amount: 10,\n * side: OrderSide.BUY,\n * });\n * ```\n *\n * @example Protected market buy\n * ```ts\n * const order = await client.createMarketOrder({\n * assetId: '0x0122…0000',\n * amount: 10,\n * maxPrice: '0.55',\n * side: OrderSide.BUY,\n * });\n * ```\n */\n createMarketOrder(request: PrepareMarketOrderRequest): Promise<SignedOrder>;\n /**\n * Creates and posts a market order for the authenticated account.\n *\n * @remarks\n * Settlement happens asynchronously, so a matched response is not\n * guaranteed to carry settlement transaction hashes. Use\n * `waitForOrderFillSettlement` to obtain them reliably.\n *\n * @throws {@link PlaceMarketOrderError}\n * Thrown on failure.\n *\n * @example Basic market buy\n * ```ts\n * const response = await client.placeMarketOrder({\n * assetId: '0x0122…0000',\n * amount: 10,\n * side: OrderSide.BUY,\n * });\n *\n * // response: OrderResponse\n * ```\n *\n * @example Protected market sell\n * ```ts\n * const response = await client.placeMarketOrder({\n * assetId: '0x0122…0000',\n * minPrice: '0.54',\n * shares: 10,\n * side: OrderSide.SELL,\n * });\n *\n * // response: OrderResponse\n * ```\n *\n * @example Market buy followed to settlement\n * ```ts\n * const response = await client.placeMarketOrder({\n * assetId: '0x0122…0000',\n * amount: 10,\n * side: OrderSide.BUY,\n * });\n *\n * if (response.ok) {\n * const hashes = await client.waitForOrderFillSettlement(response);\n * // hashes: TxHash[]\n * }\n * ```\n */\n placeMarketOrder(request: PrepareMarketOrderRequest): Promise<OrderResponse>;\n /**\n * Creates a signed limit order for the authenticated account.\n *\n * @remarks\n * GTD expirations must be at least 3 minutes in the future. Add your own\n * buffer for network latency and clock skew when deriving an expiration from\n * the current time.\n *\n * @throws {@link CreateLimitOrderError}\n * Thrown on failure.\n *\n * @example CTF limit order\n * ```ts\n * const order = await client.createLimitOrder({\n * assetId: '0x0122…0000',\n * postOnly: true,\n * price: 0.52,\n * side: OrderSide.BUY,\n * size: 10,\n * });\n * ```\n */\n createLimitOrder(request: PrepareLimitOrderRequest): Promise<SignedOrder>;\n /**\n * Creates and posts a limit order for the authenticated account.\n *\n * @remarks\n * GTD expirations must be at least 3 minutes in the future. Add your own\n * buffer for network latency and clock skew when deriving an expiration from\n * the current time.\n *\n * @throws {@link PlaceLimitOrderError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const response = await client.placeLimitOrder({\n * assetId: '0x0122…0000',\n * postOnly: true,\n * price: 0.52,\n * side: OrderSide.BUY,\n * size: 10,\n * });\n *\n * // response: OrderResponse\n * ```\n */\n placeLimitOrder(request: PrepareLimitOrderRequest): Promise<OrderResponse>;\n /**\n * Posts a signed order for the authenticated account.\n *\n * @throws {@link PostOrderError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const response = await client.postOrder(signedOrder);\n * ```\n */\n postOrder(order: SignedOrder): Promise<OrderResponse>;\n /**\n * Posts multiple signed orders for the authenticated account.\n *\n * @remarks\n * Accepts between 1 and 15 orders, matching the current service limit.\n *\n * @throws {@link PostOrdersError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const responses = await client.postOrders([firstSignedOrder, secondSignedOrder]);\n * ```\n */\n postOrders(orders: PostOrdersRequest): Promise<OrderResponses>;\n /**\n * Waits until every fill listed in an order response reaches a terminal\n * settlement outcome and returns the settlement transaction hashes.\n *\n * @remarks\n * Settlement covers the fills listed in this order response. These are the\n * fills that happened immediately when the order was accepted. It does not\n * wait for later fills of any remaining quantity resting on the book;\n * subscribe to the `user` channel to follow those.\n *\n * @throws {@link WaitForOrderFillSettlementError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const response = await client.placeMarketOrder({\n * assetId: '0x0122…0000',\n * amount: 10,\n * side: OrderSide.BUY,\n * });\n *\n * if (response.ok) {\n * const hashes = await client.waitForOrderFillSettlement(response);\n * // hashes: TxHash[]\n * }\n * ```\n */\n waitForOrderFillSettlement(\n order: AcceptedOrderResponse,\n request?: WaitForOrderFillSettlementRequest,\n ): Promise<TxHash[]>;\n /**\n * Cancels a single open order for the authenticated account.\n *\n * @throws {@link CancelOrderError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const response = await client.cancelOrder({ orderId: '123' });\n *\n * // response.canceled: OrderId[]\n * ```\n */\n cancelOrder(request: CancelOrderRequest): Promise<CancelOrdersResponse>;\n /**\n * Cancels multiple open orders for the authenticated account.\n *\n * @throws {@link CancelOrdersError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const response = await client.cancelOrders({ orderIds: ['1', '2'] });\n *\n * // response.canceled: OrderId[]\n * ```\n */\n cancelOrders(request: CancelOrdersRequest): Promise<CancelOrdersResponse>;\n /**\n * Cancels all open orders for the authenticated account.\n *\n * @throws {@link CancelAllError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const response = await client.cancelAll();\n *\n * // response.canceled: OrderId[]\n * ```\n */\n cancelAll(): Promise<CancelOrdersResponse>;\n /**\n * Cancels all open orders for the authenticated account that match the market or asset filter.\n *\n * @throws {@link CancelMarketOrdersError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const response = await client.cancelMarketOrders({\n * market: '0x0000000000000000000000000000000000000000000000000000000000000001',\n * });\n *\n * // response.canceled: OrderId[]\n * ```\n */\n cancelMarketOrders(\n request: CancelMarketOrdersRequest,\n ): Promise<CancelOrdersResponse>;\n /**\n * Lists open orders for the authenticated account across all pages.\n *\n * @throws {@link ListOpenOrdersError}\n * Thrown on failure.\n *\n * @example\n * Fetch the first page of results:\n * ```ts\n * const paginator = client.listOpenOrders({\n * market: '0x0000000000000000000000000000000000000000000000000000000000000001',\n * });\n *\n * const firstPage = await paginator.firstPage();\n *\n * // Optionally, fetch additional pages:\n * for await (const page of paginator.from(firstPage.nextCursor)) {\n * // page.items: OpenOrder[]\n * }\n * ```\n *\n * @example\n * Loop through all pages with `for await`:\n * ```ts\n * const paginator = client.listOpenOrders({\n * market: '0x0000000000000000000000000000000000000000000000000000000000000001',\n * });\n *\n * for await (const page of paginator) {\n * // page.items: OpenOrder[]\n * }\n * ```\n */\n listOpenOrders(\n request?: ListOpenOrdersRequest,\n options?: RequestOptions,\n ): 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(\n request: FetchOrderRequest,\n options?: RequestOptions,\n ): Promise<OpenOrder>;\n};\n\nexport function tradingActions(client: BaseSecureClient): SecureTradingActions;\nexport function tradingActions(client: BaseSecureClient): SecureTradingActions {\n return {\n sendOrderHeartbeat: sendOrderHeartbeat.bind(null, client),\n createMarketOrder: createMarketOrder.bind(null, client),\n placeMarketOrder: placeMarketOrder.bind(null, client),\n createLimitOrder: createLimitOrder.bind(null, client),\n placeLimitOrder: placeLimitOrder.bind(null, client),\n postOrder: postOrder(client),\n postOrders: postOrders(client),\n waitForOrderFillSettlement: waitForOrderFillSettlement.bind(null, client),\n cancelOrder: cancelOrder.bind(null, client),\n cancelOrders: cancelOrders.bind(null, client),\n cancelAll: cancelAll.bind(null, client),\n cancelMarketOrders: cancelMarketOrders.bind(null, client),\n listOpenOrders: listOpenOrders.bind(null, client),\n fetchOrder: fetchOrder.bind(null, client),\n };\n}\n\n// Error unions and runtime `isError` guards for every action bound above.\n// Surfaced at the root entry point through `export * from './decorators'`.\n// Keep this list in sync with the methods on SecureTradingActions.\nexport {\n CancelAllError,\n CancelMarketOrdersError,\n CancelOrderError,\n CancelOrdersError,\n CreateLimitOrderError,\n CreateMarketOrderError,\n FetchOrderError,\n ListOpenOrdersError,\n PlaceLimitOrderError,\n PlaceMarketOrderError,\n PostOrderError,\n PostOrdersError,\n SendOrderHeartbeatError,\n type SendOrderHeartbeatRequest,\n WaitForOrderFillSettlementError,\n} from '../actions';\n","import {\n approveErc20,\n approveErc1155ForAll,\n type CollateralReturnPlanResponse,\n type ConvertWorkflow,\n convert,\n type ExecuteCollateralReturnPlanRequest,\n executeCollateralReturnPlan,\n type FetchTradingApprovalsStateRequest,\n fetchTradingApprovalsState,\n type HorizontalMergeWorkflow,\n type HorizontalSplitWorkflow,\n horizontalMerge,\n horizontalSplit,\n mergePositions,\n type PrepareConvertRequest,\n type PrepareErc20ApprovalRequest,\n type PrepareErc20TransferRequest,\n type PrepareErc1155ApprovalForAllRequest,\n type PrepareHorizontalMergeRequest,\n type PrepareHorizontalSplitRequest,\n type PrepareMergePositionsRequest,\n type PrepareRedeemPositionsRequest,\n type PrepareSplitPositionRequest,\n planCollateralReturn,\n prepareConvert,\n prepareHorizontalMerge,\n prepareHorizontalSplit,\n redeemPositions,\n setupTradingApprovals,\n splitPosition,\n type TradingApprovalsState,\n transferErc20,\n} from '../actions';\nimport type {\n BaseClient,\n BasePublicClient,\n BaseSecureClient,\n} from '../clients';\nimport type { RequestOptions } from '../request-options';\nimport type { TransactionHandle } from '../types';\n\nexport type PublicWalletActions = {\n /**\n * Reads the approvals a wallet is missing for supported trading workflows.\n *\n * Reads the wallet's current approval state. Recent grants and revocations\n * may take time to appear. It does not require a signer or submit\n * transactions. Trading setup re-checks approvals before preparing them.\n *\n * @throws {@link FetchTradingApprovalsStateError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const state = await client.fetchTradingApprovalsState({\n * user: '0x1234…',\n * });\n * ```\n */\n fetchTradingApprovalsState(\n request: FetchTradingApprovalsStateRequest,\n options?: RequestOptions,\n ): Promise<TradingApprovalsState>;\n};\n\nexport type SecureWalletActions = {\n /**\n * Converts NO into YES for all other conditions.\n * Derives the event and NO condition index from the market's condition ID.\n * Includes Other unless converting NO(Other).\n * Requires PositionManager operator approval for the Router; approvals are not submitted automatically.\n * Signs and submits; call the returned handle's wait() to confirm.\n * @throws {@link ConvertError} Thrown on failure.\n */\n convert(request: PrepareConvertRequest): Promise<TransactionHandle>;\n /**\n * Prepares a workflow: Converts NO into YES for all other conditions.\n * Derives the event and NO condition index from the market's condition ID.\n * Includes Other unless converting NO(Other).\n * Requires PositionManager operator approval for the Router; approvals are not submitted automatically.\n * Preparing does not sign or submit; advance the workflow to execute it.\n * @throws {@link PrepareConvertError} Thrown on failure.\n */\n prepareConvert(request: PrepareConvertRequest): Promise<ConvertWorkflow>;\n /**\n * Splits pUSD into YES for every condition, including Other.\n * Uses the event containing the supplied market condition.\n * Requires pUSD spending approval for the Router; approvals are not submitted automatically.\n * Signs and submits; call the returned handle's wait() to confirm.\n * @throws {@link HorizontalSplitError} Thrown on failure.\n */\n horizontalSplit(\n request: PrepareHorizontalSplitRequest,\n ): Promise<TransactionHandle>;\n /**\n * Prepares a workflow: Splits pUSD into YES for every condition, including Other.\n * Uses the event containing the supplied market condition.\n * Requires pUSD spending approval for the Router; approvals are not submitted automatically.\n * Preparing does not sign or submit; advance the workflow to execute it.\n * @throws {@link PrepareHorizontalSplitError} Thrown on failure.\n */\n prepareHorizontalSplit(\n request: PrepareHorizontalSplitRequest,\n ): Promise<HorizontalSplitWorkflow>;\n /**\n * Merges equal YES amounts from every condition, including Other, into pUSD.\n * Uses the event containing the supplied market condition.\n * Requires PositionManager operator approval for the Router; approvals are not submitted automatically.\n * Signs and submits; call the returned handle's wait() to confirm.\n * @throws {@link HorizontalMergeError} Thrown on failure.\n */\n horizontalMerge(\n request: PrepareHorizontalMergeRequest,\n ): Promise<TransactionHandle>;\n /**\n * Prepares a workflow: Merges equal YES amounts from every condition, including Other, into pUSD.\n * Uses the event containing the supplied market condition.\n * Requires PositionManager operator approval for the Router; approvals are not submitted automatically.\n * Preparing does not sign or submit; advance the workflow to execute it.\n * @throws {@link PrepareHorizontalMergeError} Thrown on failure.\n */\n prepareHorizontalMerge(\n request: PrepareHorizontalMergeRequest,\n ): Promise<HorizontalMergeWorkflow>;\n\n /**\n * Reads the approvals a wallet is missing for supported trading workflows.\n *\n * Reads the authenticated account's wallet approval state. Recent grants\n * and revocations may take time to appear. It does not submit transactions.\n * Trading setup re-checks approvals before preparing them.\n *\n * @throws {@link FetchTradingApprovalsStateError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const state = await client.fetchTradingApprovalsState();\n * ```\n */\n fetchTradingApprovalsState(\n options?: RequestOptions,\n ): Promise<TradingApprovalsState>;\n /**\n * Sets up the approvals required for trading and supported position lifecycle workflows.\n *\n * @throws {@link SetupTradingApprovalsError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * await client.setupTradingApprovals();\n * ```\n */\n setupTradingApprovals(): Promise<void>;\n /**\n * Approves ERC-20 token spending for the authenticated account.\n *\n * @throws {@link ApproveErc20Error}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const handle = await client.approveErc20({\n * amount: 'max',\n * spenderAddress: '0x1234…',\n * tokenAddress: '0x5678…',\n * });\n *\n * const outcome = await handle.wait();\n *\n * // outcome.transactionHash: TxHash\n * ```\n */\n approveErc20(\n request: PrepareErc20ApprovalRequest,\n ): Promise<TransactionHandle>;\n /**\n * Approves or revokes ERC-1155 operator access for the authenticated account.\n *\n * @throws {@link ApproveErc1155ForAllError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const handle = await client.approveErc1155ForAll({\n * operatorAddress: '0x1234…',\n * tokenAddress: '0x5678…',\n * });\n *\n * const outcome = await handle.wait();\n *\n * // outcome.transactionHash: TxHash\n * ```\n */\n approveErc1155ForAll(\n request: PrepareErc1155ApprovalForAllRequest,\n ): Promise<TransactionHandle>;\n /**\n * Transfers ERC-20 tokens from the authenticated account.\n *\n * @throws {@link TransferErc20Error}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const handle = await client.transferErc20({\n * amount: 1n,\n * recipientAddress: client.account.signer,\n * tokenAddress: client.environment.contracts.collateralToken,\n * });\n *\n * const outcome = await handle.wait();\n *\n * // outcome.transactionHash: TxHash\n * ```\n */\n transferErc20(\n request: PrepareErc20TransferRequest,\n ): Promise<TransactionHandle>;\n /**\n * Splits collateral into positions.\n *\n * @throws {@link SplitPositionError}\n * Thrown on failure.\n *\n * @example Split a market by condition ID.\n * ```ts\n * const handle = await client.splitPosition({\n * amount: 1n,\n * conditionId: '0x123…',\n * });\n *\n * const outcome = await handle.wait();\n *\n * // outcome.transactionHash: TxHash\n * ```\n *\n * @example Split a combo by legs.\n * ```ts\n * const handle = await client.splitPosition({\n * amount: 1n,\n * legs: ['123', '456'],\n * });\n *\n * const outcome = await handle.wait();\n *\n * // outcome.transactionHash: TxHash\n * ```\n */\n splitPosition(\n request: PrepareSplitPositionRequest,\n ): Promise<TransactionHandle>;\n /**\n * Merges complementary positions back into collateral.\n *\n * @throws {@link MergePositionsError}\n * Thrown on failure.\n *\n * @example Merge a market by condition ID.\n * ```ts\n * const handle = await client.mergePositions({\n * amount: 'max',\n * conditionId: '0x123…',\n * });\n *\n * const outcome = await handle.wait();\n *\n * // outcome.transactionHash: TxHash\n * ```\n *\n * @example Merge a combo by legs.\n * ```ts\n * const handle = await client.mergePositions({\n * amount: 'max',\n * legs: ['123', '456'],\n * });\n *\n * const outcome = await handle.wait();\n *\n * // outcome.transactionHash: TxHash\n * ```\n */\n mergePositions(\n request: PrepareMergePositionsRequest,\n ): Promise<TransactionHandle>;\n /**\n * Redeems held positions for a market or a specific position by ID.\n *\n * @throws {@link RedeemPositionsError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * // Redeem a market by condition ID.\n * const handle = await client.redeemPositions({\n * conditionId: '0x123…',\n * });\n *\n * const outcome = await handle.wait();\n *\n * // outcome.transactionHash: TxHash\n * ```\n *\n * @example Redeem a market by market ID.\n * ```ts\n * const handle = await client.redeemPositions({\n * marketId: '12345',\n * });\n *\n * const outcome = await handle.wait();\n *\n * // outcome.transactionHash: TxHash\n * ```\n */\n redeemPositions(\n request: PrepareRedeemPositionsRequest,\n ): Promise<TransactionHandle>;\n /**\n * Plans a collateral return for the authenticated account.\n *\n * The returned plan is an inspectable artifact: review the collateral it\n * releases, the inputs it consumes, and the residual-position impact, and\n * apply any application-specific limits before executing it with\n * {@link SecureWalletActions.executeCollateralReturnPlan | executeCollateralReturnPlan}.\n * A truncated plan is one executable chunk of a larger return; execute and\n * confirm it before requesting the next plan.\n *\n * @throws {@link PlanCollateralReturnError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * let plan: CollateralReturnPlanResponse;\n *\n * do {\n * plan = await client.planCollateralReturn();\n *\n * // Inspect the return and residual-position impact, and apply any\n * // application-specific limits before signing.\n * const handle = await client.executeCollateralReturnPlan({ plan });\n * await handle.wait();\n * } while (plan.truncated);\n * ```\n */\n planCollateralReturn(): Promise<CollateralReturnPlanResponse>;\n /**\n * Executes a collateral return plan for the authenticated account.\n *\n * Execution signs and submits the exact call carried by the plan; nothing is\n * recomputed on the client, and no approval transactions are run implicitly.\n * Confirmation stays explicit through the returned handle's `wait()`.\n *\n * If wallet state changed since the plan was created, the service rejects\n * the submission; request a fresh plan and execute that instead.\n *\n * @throws {@link ExecuteCollateralReturnPlanError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const plan = await client.planCollateralReturn();\n *\n * const handle = await client.executeCollateralReturnPlan({ plan });\n * const outcome = await handle.wait();\n *\n * // outcome.transactionHash: TxHash\n * ```\n */\n executeCollateralReturnPlan(\n request: ExecuteCollateralReturnPlanRequest,\n ): Promise<TransactionHandle>;\n};\n\nfunction publicWalletActions(client: BaseClient): PublicWalletActions {\n return {\n fetchTradingApprovalsState: fetchTradingApprovalsState.bind(null, client),\n };\n}\n\nexport function walletActions(client: BasePublicClient): PublicWalletActions;\nexport function walletActions(client: BaseSecureClient): SecureWalletActions;\nexport function walletActions(\n client: BaseClient,\n): PublicWalletActions | SecureWalletActions {\n const actions = publicWalletActions(client);\n\n if (client.isPublicClient()) {\n return actions;\n }\n\n return {\n ...actions,\n fetchTradingApprovalsState: (options?: RequestOptions) =>\n fetchTradingApprovalsState(\n client,\n { user: client.account.wallet },\n options,\n ),\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 convert: convert.bind(null, client),\n prepareConvert: prepareConvert.bind(null, client),\n horizontalSplit: horizontalSplit.bind(null, client),\n prepareHorizontalSplit: prepareHorizontalSplit.bind(null, client),\n horizontalMerge: horizontalMerge.bind(null, client),\n prepareHorizontalMerge: prepareHorizontalMerge.bind(null, client),\n splitPosition: splitPosition.bind(null, client),\n mergePositions: mergePositions.bind(null, client),\n redeemPositions: redeemPositions.bind(null, client),\n planCollateralReturn: planCollateralReturn.bind(null, client),\n executeCollateralReturnPlan: executeCollateralReturnPlan.bind(null, client),\n };\n}\n\n// Public collateral-return model types surfaced alongside the bound methods.\nexport type {\n CollateralReturnOperation,\n CollateralReturnOperationKind,\n CollateralReturnPlanResponse,\n CollateralReturnPositionAmount,\n CollateralReturnPositionSummary,\n CollateralReturnRouterCall,\n ConvertWorkflow,\n Erc20TradingApproval,\n Erc1155TradingApproval,\n ExecuteCollateralReturnPlanRequest,\n FetchTradingApprovalsStateRequest,\n HorizontalMergeWorkflow,\n HorizontalSplitWorkflow,\n NegRiskWorkflow,\n PrepareConvertRequest,\n PrepareHorizontalMergeRequest,\n PrepareHorizontalSplitRequest,\n TradingApprovalRequirements,\n TradingApprovalsState,\n} from '../actions';\n// Error unions and runtime `isError` guards for every action bound above.\n// Surfaced at the root entry point through `export * from './decorators'`.\n// Keep this list in sync with the methods on SecureWalletActions.\nexport {\n ApproveErc20Error,\n ApproveErc1155ForAllError,\n CollateralReturnKnownOperationKind,\n ConvertError,\n ExecuteCollateralReturnPlanError,\n FetchTradingApprovalsStateError,\n HorizontalMergeError,\n HorizontalSplitError,\n MergePositionsError,\n PlanCollateralReturnError,\n PrepareConvertError,\n PrepareHorizontalMergeError,\n PrepareHorizontalSplitError,\n RedeemPositionsError,\n SetupTradingApprovalsError,\n SplitPositionError,\n TransferErc20Error,\n} from '../actions';\n","import type { Prettify } from '@kuest/types';\nimport type {\n BaseClient,\n BasePublicClient,\n BaseSecureClient,\n} from '../clients';\nimport {\n accountActions,\n type PublicAccountActions,\n type SecureAccountActions,\n} from './account';\nimport { type AnalyticsActions, analyticsActions } from './analytics';\nimport { type DataActions, dataActions } from './data';\nimport { type DiscoveryActions, discoveryActions } from './discovery';\nimport {\n type PublicPerpsActions,\n perpsActions,\n type SecurePerpsActions,\n} from './perps';\nimport {\n type PublicRewardsActions,\n rewardsActions,\n type SecureRewardsActions,\n} from './rewards';\nimport { rfqActions, type SecureRfqActions } from './rfq';\nimport { type SessionKeyActions, sessionKeyActions } from './session-keys';\nimport {\n type PublicSubscriptionsActions,\n type SecureSubscriptionsActions,\n subscriptionsActions,\n} from './subscriptions';\nimport { type SecureTradingActions, tradingActions } from './trading';\nimport {\n type PublicWalletActions,\n type SecureWalletActions,\n walletActions,\n} from './wallet';\n\nexport type PublicActions = Prettify<\n DiscoveryActions &\n DataActions &\n AnalyticsActions &\n PublicPerpsActions &\n PublicAccountActions &\n PublicRewardsActions &\n PublicSubscriptionsActions &\n PublicWalletActions\n>;\n\nexport type SecureActions = Prettify<\n DiscoveryActions &\n DataActions &\n AnalyticsActions &\n SecurePerpsActions &\n SecureAccountActions &\n SecureRewardsActions &\n SecureRfqActions &\n SessionKeyActions &\n SecureSubscriptionsActions &\n SecureWalletActions &\n SecureTradingActions\n>;\n\nexport function allActions(client: BasePublicClient): PublicActions;\nexport function allActions(client: BaseSecureClient): SecureActions;\nexport function allActions(client: BaseClient): PublicActions | SecureActions {\n if (client.isSecureClient()) {\n return {\n ...accountActions(client),\n ...analyticsActions(client),\n ...dataActions(client),\n ...discoveryActions(client),\n ...perpsActions(client),\n ...rewardsActions(client),\n ...rfqActions(client),\n ...sessionKeyActions(client),\n ...subscriptionsActions(client),\n ...tradingActions(client),\n ...walletActions(client),\n };\n }\n\n return {\n ...accountActions(client),\n ...analyticsActions(client),\n ...dataActions(client),\n ...discoveryActions(client),\n ...perpsActions(client),\n ...rewardsActions(client),\n ...subscriptionsActions(client),\n ...walletActions(client),\n };\n}\n\nexport * from './account';\nexport * from './analytics';\nexport * from './data';\nexport * from './discovery';\nexport * from './perps';\nexport * from './rewards';\nexport * from './rfq';\nexport * from './session-keys';\nexport * from './subscriptions';\nexport * from './trading';\nexport * from './wallet';\n","import { type EvmAddress, expectEvmAddress } from '@kuest/types';\nimport type { Hex } from 'ox';\n\nexport type WalletDerivationConfig = {\n depositWalletFactory: EvmAddress;\n depositWalletBeacon: EvmAddress;\n depositWalletImplementation: EvmAddress;\n proxyFactory: EvmAddress;\n proxyImplementation: EvmAddress;\n safeFactory: EvmAddress;\n safeInitCodeHash: Hex.Hex;\n};\n\nexport type RestEndpoint = {\n rest: string;\n headers?: Record<string, string>;\n};\n\nexport type WebSocketEndpoint = {\n ws: string;\n headers?: Record<string, string>;\n};\n\nexport type ClobEndpoints = RestEndpoint & {\n market: WebSocketEndpoint;\n user: WebSocketEndpoint;\n};\n\nexport type CombosEndpoints = RestEndpoint &\n WebSocketEndpoint & {\n builderGateway: RestEndpoint;\n collateralReturn: RestEndpoint;\n };\n\n/**\n * @experimental This API may change in a breaking way in any release, including patch releases.\n */\nexport type PerpsEndpoints = RestEndpoint & WebSocketEndpoint;\n\nexport type EnvironmentContracts = {\n collateralToken: EvmAddress;\n conditionalTokens: EvmAddress;\n negRiskAdapter: EvmAddress;\n collateralAdapter: EvmAddress;\n negRiskCollateralAdapter: EvmAddress;\n standardExchange: EvmAddress;\n negRiskExchange: EvmAddress;\n exchangeV3: EvmAddress;\n protocolV2Router: EvmAddress;\n binaryModule: EvmAddress;\n negRiskModule: EvmAddress;\n combinatorialModule: EvmAddress;\n positionManager: EvmAddress;\n autoRedeemOperator: EvmAddress;\n safeMultisend: EvmAddress;\n relayHub: EvmAddress;\n perpsDepositContract: EvmAddress;\n};\n\nexport type EnvironmentConfig = {\n name: string;\n chainId: number;\n /** @internal */\n rpc: string;\n /** @internal */\n walletDerivation: WalletDerivationConfig;\n /** @internal */\n contracts: EnvironmentContracts;\n /** @internal */\n predictions: RestEndpoint;\n /** @internal */\n clob: ClobEndpoints;\n /** @internal */\n relayer: RestEndpoint;\n /** @internal */\n gamma: RestEndpoint;\n /** @internal */\n data: RestEndpoint;\n /** @internal */\n combos: CombosEndpoints;\n /** @internal */\n perps: PerpsEndpoints;\n /** @internal */\n realtime: WebSocketEndpoint;\n /** @internal @deprecated Retained temporarily for legacy RTDS streams. */\n rtds: WebSocketEndpoint;\n /** @internal */\n sports: WebSocketEndpoint;\n /** @internal */\n relayerMaxPolls: number;\n /** @internal */\n relayerPollFrequencyMs: number;\n};\n\ntype EnvironmentConfigForkEndpoint = Partial<RestEndpoint & WebSocketEndpoint>;\n\nexport type EnvironmentConfigFork = {\n name: string;\n chainId?: number;\n rpc?: string;\n walletDerivation?: Partial<WalletDerivationConfig>;\n contracts?: Partial<EnvironmentContracts>;\n predictions?: Partial<RestEndpoint>;\n clob?: Partial<RestEndpoint> & {\n market?: Partial<WebSocketEndpoint>;\n user?: Partial<WebSocketEndpoint>;\n };\n relayer?: Partial<RestEndpoint>;\n gamma?: Partial<RestEndpoint>;\n data?: Partial<RestEndpoint>;\n combos?: EnvironmentConfigForkEndpoint & {\n builderGateway?: Partial<RestEndpoint>;\n collateralReturn?: Partial<RestEndpoint>;\n };\n perps?: EnvironmentConfigForkEndpoint;\n realtime?: Partial<WebSocketEndpoint>;\n /** @deprecated Retained temporarily for legacy RTDS streams. */\n rtds?: Partial<WebSocketEndpoint>;\n sports?: Partial<WebSocketEndpoint>;\n relayerMaxPolls?: number;\n relayerPollFrequencyMs?: number;\n};\n\n/**\n * The production environment configuration.\n */\nexport const production: EnvironmentConfig = {\n name: 'production',\n chainId: 137,\n rpc: 'https://unconfigured.invalid',\n walletDerivation: {\n depositWalletFactory: expectEvmAddress(\n '0x2CcdC6C5dDcd895aFcCD259F291de9b618A5cA6c',\n ),\n depositWalletBeacon: expectEvmAddress(\n '0x74a618eBdd62Ff8579A8FE94f5B888d7623b9C35',\n ),\n depositWalletImplementation: expectEvmAddress(\n '0x65507Fa36589B3b2ceD54E77999909e843691e44',\n ),\n proxyFactory: expectEvmAddress(\n '0xaB45c5A4B0c941a2F231C04C3f49182e1A254052',\n ),\n proxyImplementation: expectEvmAddress(\n '0x44e999d5c2F66Ef0861317f9A4805AC2e90aEB4f',\n ),\n safeFactory: expectEvmAddress('0xaacFeEa03eb1561C4e67d661e40682Bd20E3541b'),\n safeInitCodeHash:\n '0x2bce2127ff07fb632d16c8347c4ebf501f4841168bed00d9e6ef715ddb6fcecf',\n },\n contracts: {\n collateralToken: expectEvmAddress(\n '0x3c499c542cef5e3811e1192ce70d8cc03d5c3359',\n ),\n conditionalTokens: expectEvmAddress(\n '0x4682048725865bf17067bd85fF518527A262A9C7',\n ),\n negRiskAdapter: expectEvmAddress(\n '0xd9416E904e1ab925ad72F03F6D6ce0Aa80fd2dC5',\n ),\n collateralAdapter: expectEvmAddress(\n '0xAdA100Db00Ca00073811820692005400218FcE1f',\n ),\n negRiskCollateralAdapter: expectEvmAddress(\n '0xadA2005600Dec949baf300f4C6120000bDB6eAab',\n ),\n standardExchange: expectEvmAddress(\n '0xaa1b8dE834E16eC69C044F5300041673C968c9eF',\n ),\n negRiskExchange: expectEvmAddress(\n '0xe7FA09cA716FDf498d74AFF618d32AFeacc310aB',\n ),\n exchangeV3: expectEvmAddress('0xe3333700cA9d93003F00f0F71f8515005F6c00Aa'),\n protocolV2Router: expectEvmAddress(\n '0x12121212006e4CD160D18e3f00711DA5c3372600',\n ),\n binaryModule: expectEvmAddress(\n '0x1000008dD9001B968442c1000017eaE6E0dA00Ba',\n ),\n negRiskModule: expectEvmAddress(\n '0x200000900045e3B6259600682756002200028933',\n ),\n combinatorialModule: expectEvmAddress(\n '0x30000034706c7d8e12009dab006be20000c031a8',\n ),\n positionManager: expectEvmAddress(\n '0x006F54F7f9A22e0000CC2AB60031000000ae9fEF',\n ),\n autoRedeemOperator: expectEvmAddress(\n '0xa1200000d0002264C9a1698e001292D00E1b00af',\n ),\n safeMultisend: expectEvmAddress(\n '0xA238CBeb142c10Ef7Ad8442C6D1f9E89e07e7761',\n ),\n relayHub: expectEvmAddress('0xE2a6dC9a931538adB7efFA2E1D9eC60a65735117'),\n perpsDepositContract: expectEvmAddress(\n '0xDCa4af75705dbB50f62437045afF9921947917d2',\n ),\n },\n predictions: { rest: 'https://unconfigured.invalid' },\n clob: {\n rest: 'https://unconfigured.invalid',\n market: { ws: 'wss://unconfigured.invalid/ws/market' },\n user: { ws: 'wss://unconfigured.invalid/ws/user' },\n },\n relayer: { rest: 'https://unconfigured.invalid' },\n gamma: { rest: 'https://unconfigured.invalid' },\n data: { rest: 'https://unconfigured.invalid' },\n combos: {\n rest: 'https://unconfigured.invalid',\n ws: 'wss://unconfigured.invalid/ws/rfq',\n builderGateway: {\n rest: 'https://unconfigured.invalid',\n },\n collateralReturn: {\n rest: 'https://unconfigured.invalid',\n },\n },\n perps: {\n rest: 'https://unconfigured.invalid',\n ws: 'wss://unconfigured.invalid/v1/ws',\n },\n realtime: { ws: 'wss://unconfigured.invalid/ws' },\n rtds: { ws: 'wss://unconfigured.invalid' },\n sports: { ws: 'wss://unconfigured.invalid/ws' },\n relayerMaxPolls: 100,\n relayerPollFrequencyMs: 2000,\n};\n\n/**\n * Forks an environment config from production unless a different base is passed.\n *\n * @experimental This helper is intended for advanced custom environment use,\n * not general SDK usage. Its signature may change without notice.\n */\nexport function forkEnvironmentConfig(\n fork: EnvironmentConfigFork,\n base: EnvironmentConfig = production,\n): EnvironmentConfig {\n return {\n ...base,\n ...fork,\n walletDerivation: {\n ...base.walletDerivation,\n ...fork.walletDerivation,\n },\n contracts: {\n ...base.contracts,\n ...fork.contracts,\n },\n clob: {\n ...forkRestEndpoint(base.clob, fork.clob),\n market: forkWebSocketEndpoint(base.clob.market, fork.clob?.market),\n user: forkWebSocketEndpoint(base.clob.user, fork.clob?.user),\n },\n predictions: forkRestEndpoint(base.predictions, fork.predictions),\n relayer: forkRestEndpoint(base.relayer, fork.relayer),\n gamma: forkRestEndpoint(base.gamma, fork.gamma),\n data: forkRestEndpoint(base.data, fork.data),\n combos: {\n ...forkRestWebSocketEndpoint(base.combos, fork.combos),\n builderGateway: forkRestEndpoint(\n base.combos.builderGateway,\n fork.combos?.builderGateway,\n ),\n collateralReturn: forkRestEndpoint(\n base.combos.collateralReturn,\n fork.combos?.collateralReturn,\n ),\n },\n perps: forkRestWebSocketEndpoint(base.perps, fork.perps),\n realtime: forkWebSocketEndpoint(base.realtime, fork.realtime),\n rtds: forkWebSocketEndpoint(base.rtds, fork.rtds),\n sports: forkWebSocketEndpoint(base.sports, fork.sports),\n };\n}\n\nfunction forkRestEndpoint(\n base: RestEndpoint,\n fork: Partial<RestEndpoint> | undefined,\n): RestEndpoint {\n return {\n ...base,\n ...fork,\n headers: forkHeaders(base.headers, fork?.headers),\n };\n}\n\nfunction forkWebSocketEndpoint(\n base: WebSocketEndpoint,\n fork: Partial<WebSocketEndpoint> | undefined,\n): WebSocketEndpoint {\n return {\n ...base,\n ...fork,\n headers: forkHeaders(base.headers, fork?.headers),\n };\n}\n\nfunction forkRestWebSocketEndpoint<\n TEndpoint extends RestEndpoint & WebSocketEndpoint,\n>(base: TEndpoint, fork: EnvironmentConfigForkEndpoint | undefined): TEndpoint {\n return {\n ...base,\n ...fork,\n headers: forkHeaders(base.headers, fork?.headers),\n };\n}\n\nfunction forkHeaders(\n base: Record<string, string> | undefined,\n fork: Record<string, string> | undefined,\n): Record<string, string> | undefined {\n if (base === undefined && fork === undefined) return undefined;\n return { ...base, ...fork };\n}\n\n/** @internal */\nexport const preproduction = forkEnvironmentConfig({\n name: 'preproduction',\n predictions: { rest: 'https://unconfigured.invalid' },\n clob: { rest: 'https://unconfigured.invalid' },\n data: { rest: 'https://unconfigured.invalid' },\n gamma: { rest: 'https://unconfigured.invalid' },\n relayer: { rest: 'https://unconfigured.invalid' },\n});\n","import type { Pushable } from 'it-pushable';\nimport type { SubscriptionHandle } from '../actions/subscriptions';\n\nexport function createSubscriptionHandle<TEvent>(\n queue: Pushable<TEvent>,\n closeSubscription: () => Promise<void>,\n): SubscriptionHandle<TEvent> {\n let closing: Promise<void> | undefined;\n\n return {\n close: () => {\n if (closing === undefined) {\n closing = Promise.resolve(queue.return()).then(() =>\n closeSubscription(),\n );\n }\n return closing;\n },\n [Symbol.asyncIterator]() {\n return queue[Symbol.asyncIterator]();\n },\n };\n}\n","import { type Pushable, pushable } from 'it-pushable';\n\nexport type SubscriptionRegistrySubscriber<TEvent> = {\n matches?: (event: TEvent) => boolean;\n queue: Pushable<TEvent>;\n};\n\nexport type SubscriptionRegistryEntry<TSubscription, TEvent> = {\n subscription: TSubscription;\n subscriber: SubscriptionRegistrySubscriber<TEvent>;\n};\n\nexport type SubscriptionRegistryChange<TState> = {\n before: TState;\n after: TState;\n};\n\nexport type SubscriptionRegistryAddOptions<TEvent> = {\n matches?: (event: TEvent) => boolean;\n};\n\nexport type SubscriptionRegistryAddResult<TSubscription, TEvent, TState> = {\n change: SubscriptionRegistryChange<TState>;\n entry: SubscriptionRegistryEntry<TSubscription, TEvent>;\n};\n\ntype DeriveServerState<TSubscription, TEvent, TState> = (\n entries: Iterable<SubscriptionRegistryEntry<TSubscription, TEvent>>,\n) => TState;\n\nexport type SubscriptionRegistryOptions<TSubscription, TEvent, TState> = {\n deriveServerState: DeriveServerState<TSubscription, TEvent, TState>;\n};\n\nexport class SubscriptionRegistry<\n TSubscription,\n TEvent,\n TServerState = undefined,\n> {\n readonly #entries = new Set<\n SubscriptionRegistryEntry<TSubscription, TEvent>\n >();\n readonly #deriveServerState: DeriveServerState<\n TSubscription,\n TEvent,\n TServerState\n >;\n\n constructor(\n options?: SubscriptionRegistryOptions<TSubscription, TEvent, TServerState>,\n ) {\n this.#deriveServerState =\n options?.deriveServerState ?? (() => undefined as TServerState);\n }\n\n add(\n subscription: TSubscription,\n options: SubscriptionRegistryAddOptions<TEvent> = {},\n ): SubscriptionRegistryAddResult<TSubscription, TEvent, TServerState> {\n const subscriber: SubscriptionRegistrySubscriber<TEvent> = {\n queue: pushable<TEvent>({ objectMode: true }),\n };\n if (options.matches !== undefined) {\n subscriber.matches = options.matches;\n }\n const entry: SubscriptionRegistryEntry<TSubscription, TEvent> = {\n subscription,\n subscriber,\n };\n return { change: this.#addEntry(entry), entry };\n }\n\n #addEntry(\n entry: SubscriptionRegistryEntry<TSubscription, TEvent>,\n ): SubscriptionRegistryChange<TServerState> {\n const before = this.serverState();\n this.#entries.add(entry);\n return { before, after: this.serverState() };\n }\n\n remove(\n entry: SubscriptionRegistryEntry<TSubscription, TEvent>,\n ): SubscriptionRegistryChange<TServerState> {\n const before = this.serverState();\n this.#entries.delete(entry);\n entry.subscriber.queue.end();\n return { before, after: this.serverState() };\n }\n\n dispatch(event: TEvent): void {\n for (const { subscriber } of this.#entries) {\n if (subscriber.matches === undefined || subscriber.matches(event)) {\n subscriber.queue.push(event);\n }\n }\n }\n\n hasActiveSubscriptions(): boolean {\n return this.#entries.size > 0;\n }\n\n endAll(error?: Error): void {\n for (const { subscriber } of this.#entries) {\n subscriber.queue.end(error);\n }\n this.#entries.clear();\n }\n\n serverState(): TServerState {\n return this.#deriveServerState(this.#entries);\n }\n}\n","import type { ApiKeyCreds } from '@kuest/bindings/clob';\nimport type { MarketEvent, UserEvent } from '@kuest/bindings/subscriptions';\nimport type {\n MarketSubscription,\n UserSubscription,\n} from '../../actions/subscriptions';\nimport type { SubscriptionRegistryEntry } from '../registry';\n\nexport type SendWebSocketMessage = (message: unknown) => void;\n\nexport type MarketSubscriptionEntry = SubscriptionRegistryEntry<\n MarketSubscription,\n MarketEvent\n>;\n\nexport type MarketServerSubscription = {\n assetsIds: string[];\n customFeatureEnabled: boolean;\n};\n\nexport type UserSubscriptionEntry = SubscriptionRegistryEntry<\n UserSubscription,\n UserEvent\n>;\n\nexport type UserServerSubscription = {\n includeAllMarkets: boolean;\n markets: string[];\n};\n\nexport function syncMarketSubscription(\n send: SendWebSocketMessage,\n before: MarketServerSubscription,\n after: MarketServerSubscription,\n): void {\n const addedAssets = difference(after.assetsIds, before.assetsIds);\n const removedAssets = difference(before.assetsIds, after.assetsIds);\n\n if (addedAssets.length > 0) {\n send(buildMarketSubscribeUpdate(addedAssets, after.customFeatureEnabled));\n }\n const firstActiveAsset = after.assetsIds[0];\n if (\n addedAssets.length === 0 &&\n before.customFeatureEnabled !== after.customFeatureEnabled &&\n firstActiveAsset !== undefined\n ) {\n // CLOB applies `custom_feature_enabled` before rejecting duplicate assets as\n // \"NO NEW ASSETS\", so this toggles connection-level custom events in place.\n send(\n buildMarketSubscribeUpdate(\n [firstActiveAsset],\n after.customFeatureEnabled,\n ),\n );\n }\n if (removedAssets.length > 0) {\n send(buildMarketUnsubscribeUpdate(removedAssets));\n }\n}\n\nexport function syncUserSubscription(\n send: SendWebSocketMessage,\n before: UserServerSubscription,\n after: UserServerSubscription,\n): void {\n if (after.includeAllMarkets) {\n if (!before.includeAllMarkets && before.markets.length > 0) {\n send(buildUserUnsubscribeUpdate(before.markets));\n }\n return;\n }\n\n if (before.includeAllMarkets) {\n if (after.markets.length > 0) {\n send(buildUserSubscribeUpdate(after.markets));\n }\n return;\n }\n\n const addedMarkets = difference(after.markets, before.markets);\n const removedMarkets = difference(before.markets, after.markets);\n\n if (addedMarkets.length > 0) {\n send(buildUserSubscribeUpdate(addedMarkets));\n }\n if (removedMarkets.length > 0) {\n send(buildUserUnsubscribeUpdate(removedMarkets));\n }\n}\n\nexport function deriveMarketServerSubscription(\n entries: Iterable<MarketSubscriptionEntry>,\n): MarketServerSubscription {\n const assets = new Set<string>();\n let customFeatureEnabled = false;\n for (const { subscription } of entries) {\n for (const assetId of subscription.assetIds ?? subscription.tokenIds) {\n assets.add(assetId);\n }\n customFeatureEnabled ||= subscription.customFeatureEnabled === true;\n }\n return { assetsIds: Array.from(assets), customFeatureEnabled };\n}\n\nexport function deriveUserServerSubscription(\n entries: Iterable<UserSubscriptionEntry>,\n): UserServerSubscription {\n let includeAllMarkets = false;\n const markets = new Set<string>();\n for (const { subscription } of entries) {\n if (isAllMarketsUserSubscription(subscription)) {\n includeAllMarkets = true;\n continue;\n }\n for (const market of subscription.markets ?? []) markets.add(market);\n }\n return {\n includeAllMarkets,\n markets: includeAllMarkets ? [] : Array.from(markets),\n };\n}\n\nexport function buildMarketSubscribeMessage(\n subscription: MarketServerSubscription,\n): unknown {\n return {\n assets_ids: subscription.assetsIds,\n custom_feature_enabled: subscription.customFeatureEnabled,\n type: 'market',\n };\n}\n\nfunction buildMarketSubscribeUpdate(\n assetsIds: readonly string[],\n customFeatureEnabled: boolean,\n): unknown {\n return {\n assets_ids: assetsIds,\n custom_feature_enabled: customFeatureEnabled,\n operation: 'subscribe',\n };\n}\n\nfunction buildMarketUnsubscribeUpdate(assetsIds: readonly string[]): unknown {\n return {\n assets_ids: assetsIds,\n operation: 'unsubscribe',\n };\n}\n\nexport function buildUserSubscribeMessage(\n subscription: UserServerSubscription,\n credentials: ApiKeyCreds,\n): unknown {\n const message: {\n auth: { apiKey: string; passphrase: string; secret: string };\n markets?: string[];\n type: 'user';\n } = {\n auth: {\n apiKey: credentials.key,\n passphrase: credentials.passphrase,\n secret: credentials.secret,\n },\n type: 'user',\n };\n if (!subscription.includeAllMarkets) {\n message.markets = subscription.markets;\n }\n return message;\n}\n\nfunction buildUserSubscribeUpdate(markets: readonly string[]): unknown {\n return {\n markets,\n operation: 'subscribe',\n };\n}\n\nfunction buildUserUnsubscribeUpdate(markets: readonly string[]): unknown {\n return {\n markets,\n operation: 'unsubscribe',\n };\n}\n\nexport function marketMatcherFor(\n subscription: MarketSubscription,\n): (event: MarketEvent) => boolean {\n const assetIds = subscription.assetIds ?? subscription.tokenIds;\n return (event) => {\n switch (event.type) {\n case 'price_change':\n return event.payload.priceChanges.some((change) =>\n assetIds.includes(change.assetId),\n );\n case 'new_market':\n return subscription.customFeatureEnabled === true;\n case 'market_resolved':\n return (\n subscription.customFeatureEnabled === true &&\n (event.payload.assetIds ?? []).some((assetId) =>\n assetIds.includes(assetId),\n )\n );\n case 'best_bid_ask':\n return (\n subscription.customFeatureEnabled === true &&\n assetIds.includes(event.payload.assetId)\n );\n default:\n return assetIds.includes(event.payload.assetId);\n }\n };\n}\n\nexport function userMatcherFor(\n subscription: UserSubscription,\n): (event: UserEvent) => boolean {\n if (isAllMarketsUserSubscription(subscription)) {\n return () => true;\n }\n\n const markets = new Set(\n (subscription.markets ?? []).map((market) => market.toLowerCase()),\n );\n return (event) => markets.has(event.payload.market.toLowerCase());\n}\n\nfunction isAllMarketsUserSubscription(subscription: UserSubscription): boolean {\n return (subscription.markets?.length ?? 0) === 0;\n}\n\nfunction difference(\n left: readonly string[],\n right: readonly string[],\n): string[] {\n const rightSet = new Set(right);\n return left.filter((value) => !rightSet.has(value));\n}\n","import {\n type MarketEvent,\n MarketEventSchema,\n} from '@kuest/bindings/subscriptions';\nimport type {\n MarketSubscription,\n SubscriptionHandle,\n} from '../../actions/subscriptions';\nimport { createSubscriptionHandle } from '../handle';\nimport { ClobWebSocketHeartbeat } from '../heartbeat';\nimport {\n ReconnectScheduler,\n WebSocketConnection,\n type WebSocketConnectionResult,\n} from '../lifecycle';\nimport {\n SubscriptionRegistry,\n type SubscriptionRegistryChange,\n} from '../registry';\nimport type { WebSocketSubscriptionManager } from '../types';\nimport {\n buildMarketSubscribeMessage,\n deriveMarketServerSubscription,\n type MarketServerSubscription,\n type MarketSubscriptionEntry,\n marketMatcherFor,\n syncMarketSubscription,\n} from './protocol';\n\nexport type ClobMarketWebSocketManagerOptions = {\n headers?: Record<string, string>;\n url: string;\n};\n\n/**\n * CLOB market WebSocket manager.\n *\n * The CLOB server tracks market subscriptions by asset id on the connection.\n * Incremental subscribe/unsubscribe frames mutate that server-side asset set.\n */\nexport class ClobMarketWebSocketManager\n implements WebSocketSubscriptionManager<MarketSubscription, MarketEvent>\n{\n readonly #headers: Record<string, string> | undefined;\n readonly #url: string;\n #closing: Promise<void> | undefined;\n readonly #connection = new WebSocketConnection({\n heartbeat: new ClobWebSocketHeartbeat(),\n });\n readonly #reconnectScheduler = new ReconnectScheduler();\n readonly #subscriptions = new SubscriptionRegistry<\n MarketSubscription,\n MarketEvent,\n MarketServerSubscription\n >({ deriveServerState: deriveMarketServerSubscription });\n\n constructor(options: ClobMarketWebSocketManagerOptions) {\n this.#headers = options.headers;\n this.#url = options.url;\n }\n\n async subscribe(\n subscription: MarketSubscription,\n ): Promise<SubscriptionHandle<MarketEvent>> {\n const { change, entry } = this.#subscriptions.add(subscription, {\n matches: marketMatcherFor(subscription),\n });\n\n await this.#registerSubscriber(entry, change);\n return createSubscriptionHandle(entry.subscriber.queue, () =>\n this.#closeSubscriber(entry),\n );\n }\n\n async #registerSubscriber(\n entry: MarketSubscriptionEntry,\n change: SubscriptionRegistryChange<MarketServerSubscription>,\n ): Promise<void> {\n const { before, after } = change;\n\n try {\n const connection = await this.#connect();\n if (connection.reusedOpenSocket) {\n syncMarketSubscription(\n (message) => this.#connection.send(message),\n before,\n after,\n );\n }\n } catch (error) {\n await this.#closeSubscriber(entry);\n throw error;\n }\n }\n\n async #closeSubscriber(entry: MarketSubscriptionEntry): Promise<void> {\n const { before, after } = this.#subscriptions.remove(entry);\n\n if (!this.#subscriptions.hasActiveSubscriptions()) {\n await this.close();\n return;\n }\n\n syncMarketSubscription(\n (message) => this.#connection.send(message),\n before,\n after,\n );\n }\n\n async close(): Promise<void> {\n if (this.#closing === undefined) {\n this.#closing = this.#shutdown().finally(() => {\n this.#closing = undefined;\n });\n }\n await this.#closing;\n }\n\n async #shutdown(): Promise<void> {\n this.#reconnectScheduler.stop();\n this.#subscriptions.endAll();\n\n await this.#connection.close();\n }\n\n #connect(): Promise<WebSocketConnectionResult> {\n return this.#connection.connect({\n onConnectionLost: () => this.#onConnectionLost(),\n onError: () => this.#onConnectionError(),\n onMessage: (message) => this.#onConnectionMessage(message),\n onOpen: () => this.#onConnectionOpen(),\n headers: this.#headers,\n url: this.#url,\n });\n }\n\n #onConnectionOpen(): void {\n this.#reconnectScheduler.resetBackoff();\n this.#sendInitialSubscription();\n }\n\n #onConnectionMessage(message: unknown): void {\n const events = Array.isArray(message) ? message : [message];\n for (const eventData of events) {\n const parsed = MarketEventSchema.safeParse(eventData);\n if (!parsed.success) continue;\n this.#subscriptions.dispatch(parsed.data);\n }\n }\n\n #onConnectionLost(): void {\n if (this.#subscriptions.hasActiveSubscriptions()) {\n this.#scheduleReconnect();\n }\n }\n\n #onConnectionError(): void {\n // Browser WebSockets report most failures as an error followed by close.\n // Keep iterators alive here so the close path can reconnect active handles.\n }\n\n #sendInitialSubscription(): void {\n this.#connection.send(\n buildMarketSubscribeMessage(this.#subscriptions.serverState()),\n );\n }\n\n #scheduleReconnect(): void {\n this.#reconnectScheduler.schedule({\n reconnect: () => this.#connect(),\n shouldReconnect: () => this.#subscriptions.hasActiveSubscriptions(),\n });\n }\n}\n","import type { ApiKeyCreds } from '@kuest/bindings/clob';\nimport { type UserEvent, UserEventSchema } from '@kuest/bindings/subscriptions';\nimport type {\n SubscriptionHandle,\n UserSubscription,\n} from '../../actions/subscriptions';\nimport { createSubscriptionHandle } from '../handle';\nimport { ClobWebSocketHeartbeat } from '../heartbeat';\nimport {\n ReconnectScheduler,\n WebSocketConnection,\n type WebSocketConnectionResult,\n} from '../lifecycle';\nimport {\n SubscriptionRegistry,\n type SubscriptionRegistryChange,\n} from '../registry';\nimport type { WebSocketSubscriptionManager } from '../types';\nimport {\n buildUserSubscribeMessage,\n deriveUserServerSubscription,\n syncUserSubscription,\n type UserServerSubscription,\n type UserSubscriptionEntry,\n userMatcherFor,\n} from './protocol';\n\nexport type ClobUserWebSocketManagerOptions = {\n credentials: ApiKeyCreds;\n headers?: Record<string, string>;\n url: string;\n};\n\nexport class ClobUserWebSocketManager\n implements WebSocketSubscriptionManager<UserSubscription, UserEvent>\n{\n readonly #credentials: ApiKeyCreds;\n readonly #headers: Record<string, string> | undefined;\n readonly #url: string;\n #closing: Promise<void> | undefined;\n readonly #connection = new WebSocketConnection({\n heartbeat: new ClobWebSocketHeartbeat(),\n });\n readonly #reconnectScheduler = new ReconnectScheduler();\n readonly #subscriptions = new SubscriptionRegistry<\n UserSubscription,\n UserEvent,\n UserServerSubscription\n >({ deriveServerState: deriveUserServerSubscription });\n\n constructor(options: ClobUserWebSocketManagerOptions) {\n this.#credentials = options.credentials;\n this.#headers = options.headers;\n this.#url = options.url;\n }\n\n async subscribe(\n subscription: UserSubscription,\n ): Promise<SubscriptionHandle<UserEvent>> {\n const { change, entry } = this.#subscriptions.add(subscription, {\n matches: userMatcherFor(subscription),\n });\n\n await this.#registerSubscriber(entry, change);\n return createSubscriptionHandle(entry.subscriber.queue, () =>\n this.#closeSubscriber(entry),\n );\n }\n\n async #registerSubscriber(\n entry: UserSubscriptionEntry,\n change: SubscriptionRegistryChange<UserServerSubscription>,\n ): Promise<void> {\n const { before, after } = change;\n\n try {\n const connection = await this.#connect();\n if (connection.reusedOpenSocket) {\n syncUserSubscription(\n (message) => this.#connection.send(message),\n before,\n after,\n );\n }\n } catch (error) {\n await this.#closeSubscriber(entry);\n throw error;\n }\n }\n\n async #closeSubscriber(entry: UserSubscriptionEntry): Promise<void> {\n const { before, after } = this.#subscriptions.remove(entry);\n\n if (!this.#subscriptions.hasActiveSubscriptions()) {\n await this.close();\n return;\n }\n\n syncUserSubscription(\n (message) => this.#connection.send(message),\n before,\n after,\n );\n }\n\n async close(): Promise<void> {\n if (this.#closing === undefined) {\n this.#closing = this.#shutdown().finally(() => {\n this.#closing = undefined;\n });\n }\n await this.#closing;\n }\n\n async #shutdown(): Promise<void> {\n this.#reconnectScheduler.stop();\n this.#subscriptions.endAll();\n\n await this.#connection.close();\n }\n\n #connect(): Promise<WebSocketConnectionResult> {\n return this.#connection.connect({\n onConnectionLost: () => this.#onConnectionLost(),\n onError: () => this.#onConnectionError(),\n onMessage: (message) => this.#onConnectionMessage(message),\n onOpen: (credentials) => this.#onConnectionOpen(credentials),\n prepare: () => this.#credentials,\n headers: this.#headers,\n url: this.#url,\n });\n }\n\n #onConnectionOpen(credentials: ApiKeyCreds): void {\n this.#reconnectScheduler.resetBackoff();\n this.#sendInitialSubscription(credentials);\n }\n\n #onConnectionMessage(message: unknown): void {\n const events = Array.isArray(message) ? message : [message];\n for (const eventData of events) {\n const parsed = UserEventSchema.safeParse(eventData);\n if (!parsed.success) continue;\n this.#subscriptions.dispatch(parsed.data);\n }\n }\n\n #onConnectionLost(): void {\n if (this.#subscriptions.hasActiveSubscriptions()) {\n this.#scheduleReconnect();\n }\n }\n\n #onConnectionError(): void {\n // Browser WebSockets report most failures as an error followed by close.\n // Keep iterators alive here so the close path can reconnect active handles.\n }\n\n #sendInitialSubscription(credentials: ApiKeyCreds): void {\n this.#connection.send(\n buildUserSubscribeMessage(this.#subscriptions.serverState(), credentials),\n );\n }\n\n #scheduleReconnect(): void {\n this.#reconnectScheduler.schedule({\n reconnect: () => this.#connect(),\n shouldReconnect: () => this.#subscriptions.hasActiveSubscriptions(),\n });\n }\n}\n","import type { PerpsCredentials } from '@kuest/bindings/perps';\nimport type { PerpsBuilderFeeApprover } from '../../actions/perps/builders';\nimport { TransportError } from '../../errors';\nimport type { Fetch } from '../../request-options';\nimport type { PerpsBuilderTermsInput } from './actions/builder-terms';\nimport { PerpsSession } from './session';\n\n/**\n * @experimental This API may change in a breaking way in any release, including patch releases.\n */\nexport type PerpsSessionManagerOptions = {\n chainId: number;\n fetch?: Fetch;\n headers?: Record<string, string>;\n restUrl: string;\n wsUrl: string;\n};\n\n/**\n * @experimental This API may change in a breaking way in any release, including patch releases.\n */\nexport class PerpsSessionManager {\n readonly #chainId: number;\n readonly #fetch: Fetch | undefined;\n readonly #headers: Record<string, string> | undefined;\n readonly #restUrl: string;\n readonly #wsUrl: string;\n readonly #sessions = new Set<PerpsSession>();\n readonly #connectingSessions = new Set<PerpsSession>();\n readonly #connecting = new Set<Promise<PerpsSession>>();\n #hasShutdown = false;\n\n /**\n * @experimental This API may change in a breaking way in any release, including patch releases.\n */\n constructor(options: PerpsSessionManagerOptions) {\n this.#chainId = options.chainId;\n this.#fetch = options.fetch;\n this.#headers = options.headers;\n this.#restUrl = options.restUrl;\n this.#wsUrl = options.wsUrl;\n }\n\n /**\n * Connects credentials with an optional builder for new orders.\n * Builder defaults belong to this session, not the credentials.\n *\n * @experimental This API may change in a breaking way in any release, including patch releases.\n */\n connect(\n credentials: PerpsCredentials,\n builderAttribution?: string | PerpsBuilderTermsInput,\n approveBuilderFee?: PerpsBuilderFeeApprover,\n includeBuilderFills?: boolean,\n ): Promise<PerpsSession> {\n if (this.#hasShutdown) {\n return Promise.reject(\n new TransportError('Perps session manager has been shut down.'),\n );\n }\n\n const session = new PerpsSession({\n builderAttribution,\n approveBuilderFee,\n includeBuilderFills,\n chainId: this.#chainId,\n credentials,\n fetch: this.#fetch,\n headers: this.#headers,\n onClose: (closedSession) => this.#clearSession(closedSession),\n restUrl: this.#restUrl,\n wsUrl: this.#wsUrl,\n });\n this.#connectingSessions.add(session);\n\n let connecting!: Promise<PerpsSession>;\n connecting = (async () => {\n try {\n await session.connect();\n if (this.#hasShutdown) {\n await session.close();\n throw new TransportError('Perps session manager has been shut down.');\n }\n this.#sessions.add(session);\n return session;\n } catch (error) {\n await session.close();\n throw error;\n } finally {\n this.#connecting.delete(connecting);\n this.#connectingSessions.delete(session);\n }\n })();\n\n this.#connecting.add(connecting);\n return connecting;\n }\n\n /**\n * @experimental This API may change in a breaking way in any release, including patch releases.\n */\n async shutdown(): Promise<void> {\n this.#hasShutdown = true;\n const sessions = Array.from(this.#sessions);\n const connectingSessions = Array.from(this.#connectingSessions);\n const connecting = Array.from(this.#connecting);\n\n this.#sessions.clear();\n this.#connectingSessions.clear();\n this.#connecting.clear();\n\n await Promise.allSettled([\n ...sessions.map((session) => session.close()),\n ...connectingSessions.map((session) => session.close()),\n ...connecting.map((promise) => promise.catch(() => undefined)),\n ]).then(() => undefined);\n }\n\n #clearSession(session: PerpsSession): void {\n this.#sessions.delete(session);\n this.#connectingSessions.delete(session);\n }\n}\n","import {\n type PerpsMarketDataEvent,\n PerpsMarketDataEventSchema,\n} from '@kuest/bindings/subscriptions';\nimport { invariant } from '@kuest/types';\nimport type {\n PerpsMarketDataSubscription,\n SubscriptionHandle,\n} from '../../actions/subscriptions';\nimport { createSubscriptionHandle } from '../handle';\nimport { PerpsWebSocketHeartbeat } from '../heartbeat';\nimport {\n ReconnectScheduler,\n WebSocketConnection,\n type WebSocketConnectionResult,\n} from '../lifecycle';\nimport {\n SubscriptionRegistry,\n type SubscriptionRegistryChange,\n type SubscriptionRegistryEntry,\n} from '../registry';\nimport type { WebSocketSubscriptionManager } from '../types';\n\ntype PerpsSubscriptionEntry = SubscriptionRegistryEntry<\n PerpsMarketDataSubscription,\n PerpsMarketDataEvent\n>;\n\ntype PerpsSubscriptionServerState = Set<string>;\n\n/**\n * @experimental This API may change in a breaking way in any release, including patch releases.\n */\nexport type PerpsSubscriptionManagerOptions = {\n headers?: Record<string, string>;\n url: string;\n};\n\n/**\n * Perps public subscription WebSocket manager.\n *\n * The Perps server tracks subscriptions by channel string. This manager keeps\n * SDK-level topic specs separate from upstream channel names and resubscribes\n * active channels after reconnects.\n *\n * @experimental This API may change in a breaking way in any release, including patch releases.\n */\nexport class PerpsSubscriptionManager\n implements\n WebSocketSubscriptionManager<\n PerpsMarketDataSubscription,\n PerpsMarketDataEvent\n >\n{\n readonly #headers: Record<string, string> | undefined;\n readonly #url: string;\n #closing: Promise<void> | undefined;\n #nextRequestId = 1;\n readonly #connection = new WebSocketConnection({\n heartbeat: new PerpsWebSocketHeartbeat(),\n });\n readonly #reconnectScheduler = new ReconnectScheduler();\n readonly #subscriptions = new SubscriptionRegistry<\n PerpsMarketDataSubscription,\n PerpsMarketDataEvent,\n PerpsSubscriptionServerState\n >({ deriveServerState: derivePerpsSubscriptionServerState });\n\n /**\n * @experimental This API may change in a breaking way in any release, including patch releases.\n */\n constructor(options: PerpsSubscriptionManagerOptions) {\n this.#headers = options.headers;\n this.#url = options.url;\n }\n\n /**\n * @experimental This API may change in a breaking way in any release, including patch releases.\n */\n async subscribe(\n subscription: PerpsMarketDataSubscription,\n ): Promise<SubscriptionHandle<PerpsMarketDataEvent>> {\n const { change, entry } = this.#subscriptions.add(subscription, {\n matches: matcherFor(subscription),\n });\n await this.#registerSubscriber(entry, change);\n return createSubscriptionHandle(entry.subscriber.queue, () =>\n this.#closeSubscriber(entry),\n );\n }\n\n async #registerSubscriber(\n entry: PerpsSubscriptionEntry,\n change: SubscriptionRegistryChange<PerpsSubscriptionServerState>,\n ): Promise<void> {\n try {\n const connection = await this.#connect();\n if (connection.reusedOpenSocket) {\n this.#sendSubscribeFrame(channelsAdded(change.before, change.after));\n this.#sendUnsubscribeFrame(\n channelsRemoved(change.before, change.after),\n );\n }\n } catch (error) {\n await this.#closeSubscriber(entry);\n throw error;\n }\n }\n\n async #closeSubscriber(entry: PerpsSubscriptionEntry): Promise<void> {\n const { before, after } = this.#subscriptions.remove(entry);\n this.#sendSubscribeFrame(channelsAdded(before, after));\n this.#sendUnsubscribeFrame(channelsRemoved(before, after));\n if (!this.#subscriptions.hasActiveSubscriptions()) {\n await this.close();\n }\n }\n\n /**\n * @experimental This API may change in a breaking way in any release, including patch releases.\n */\n async close(): Promise<void> {\n if (this.#closing === undefined) {\n this.#closing = this.#shutdown().finally(() => {\n this.#closing = undefined;\n });\n }\n await this.#closing;\n }\n\n async #shutdown(): Promise<void> {\n this.#reconnectScheduler.stop();\n this.#subscriptions.endAll();\n\n await this.#connection.close();\n }\n\n #connect(): Promise<WebSocketConnectionResult> {\n return this.#connection.connect({\n onConnectionLost: () => this.#onConnectionLost(),\n onError: () => this.#onConnectionError(),\n onMessage: (message) => this.#onConnectionMessage(message),\n onOpen: () => this.#onConnectionOpen(),\n headers: this.#headers,\n url: this.#url,\n });\n }\n\n #onConnectionOpen(): void {\n this.#reconnectScheduler.resetBackoff();\n this.#sendSubscribeFrame(Array.from(this.#subscriptions.serverState()));\n }\n\n #onConnectionMessage(message: unknown): void {\n const parsed = PerpsMarketDataEventSchema.safeParse(message);\n if (!parsed.success) return;\n this.#subscriptions.dispatch(parsed.data);\n }\n\n #onConnectionLost(): void {\n if (this.#subscriptions.hasActiveSubscriptions()) {\n this.#scheduleReconnect();\n }\n }\n\n #onConnectionError(): void {\n // Browser WebSockets report most failures as an error followed by close.\n // Keep iterators alive here so the close path can reconnect active handles.\n }\n\n #sendSubscribeFrame(channels: readonly string[]): void {\n if (channels.length === 0) return;\n this.#connection.send(this.#buildChannelFrame('sub', channels));\n }\n\n #sendUnsubscribeFrame(channels: readonly string[]): void {\n if (channels.length === 0) return;\n this.#connection.send(this.#buildChannelFrame('unsub', channels));\n }\n\n #buildChannelFrame(req: 'sub' | 'unsub', channels: readonly string[]) {\n return {\n id: this.#nextRequestId++,\n req,\n chs: channels,\n };\n }\n\n #scheduleReconnect(): void {\n this.#reconnectScheduler.schedule({\n reconnect: () => this.#connect(),\n shouldReconnect: () => this.#subscriptions.hasActiveSubscriptions(),\n });\n }\n}\n\nfunction derivePerpsSubscriptionServerState(\n entries: Iterable<PerpsSubscriptionEntry>,\n): PerpsSubscriptionServerState {\n const channels = new Set<string>();\n const tickerInstrumentIds = new Set<number>();\n const statisticInstrumentIds = new Set<number>();\n let subscribeAllTickers = false;\n let subscribeAllStatistics = false;\n\n for (const { subscription } of entries) {\n switch (subscription.topic) {\n case 'perps.tickers':\n if (subscription.instrumentId === undefined) {\n subscribeAllTickers = true;\n } else {\n tickerInstrumentIds.add(subscription.instrumentId);\n }\n break;\n case 'perps.statistics':\n if (subscription.instrumentId === undefined) {\n subscribeAllStatistics = true;\n } else {\n statisticInstrumentIds.add(subscription.instrumentId);\n }\n break;\n default:\n channels.add(channelFor(subscription));\n }\n }\n\n if (subscribeAllTickers) {\n channels.add('tickers::all');\n } else {\n for (const instrumentId of tickerInstrumentIds) {\n channels.add(`tickers::${instrumentId}`);\n }\n }\n\n if (subscribeAllStatistics) {\n channels.add('statistics::all');\n } else {\n for (const instrumentId of statisticInstrumentIds) {\n channels.add(`statistics::${instrumentId}`);\n }\n }\n\n return channels;\n}\n\nfunction channelsAdded(\n before: ReadonlySet<string>,\n after: ReadonlySet<string>,\n): string[] {\n return Array.from(after).filter((channel) => !before.has(channel));\n}\n\nfunction channelsRemoved(\n before: ReadonlySet<string>,\n after: ReadonlySet<string>,\n): string[] {\n return Array.from(before).filter((channel) => !after.has(channel));\n}\n\nfunction channelFor(subscription: PerpsMarketDataSubscription): string {\n switch (subscription.topic) {\n case 'perps.trades':\n return `trades::${subscription.instrumentId}`;\n case 'perps.bbo':\n return `bbo::${subscription.instrumentId}`;\n case 'perps.book':\n return `book::${subscription.instrumentId}`;\n case 'perps.candles':\n return `klines::${subscription.instrumentId}::${subscription.interval}`;\n case 'perps.tickers':\n return subscription.instrumentId === undefined\n ? 'tickers::all'\n : `tickers::${subscription.instrumentId}`;\n case 'perps.statistics':\n return subscription.instrumentId === undefined\n ? 'statistics::all'\n : `statistics::${subscription.instrumentId}`;\n default: {\n const neverSpec: never = subscription;\n invariant(false, `Unknown Perps topic: ${String(neverSpec)}`);\n }\n }\n}\n\nfunction matcherFor(\n subscription: PerpsMarketDataSubscription,\n): (event: PerpsMarketDataEvent) => boolean {\n switch (subscription.topic) {\n case 'perps.trades':\n return (event) =>\n event.topic === 'perps.trades' &&\n event.channel === `trades::${subscription.instrumentId}`;\n case 'perps.bbo':\n case 'perps.book':\n return (event) =>\n event.topic === subscription.topic &&\n event.payload.instrumentId === subscription.instrumentId;\n case 'perps.candles':\n return (event) =>\n event.topic === 'perps.candles' &&\n event.payload.instrumentId === subscription.instrumentId &&\n event.payload.interval === subscription.interval;\n case 'perps.tickers':\n case 'perps.statistics':\n return (event) =>\n event.topic === subscription.topic &&\n (subscription.instrumentId === undefined ||\n event.payload.instrumentId === subscription.instrumentId);\n default: {\n const neverSpec: never = subscription;\n invariant(false, `Unknown Perps topic: ${String(neverSpec)}`);\n }\n }\n}\n","import type { PriceProvider } from '@kuest/bindings/subscriptions';\nimport type { PriceSubscription } from '../../actions/subscriptions';\n\n/** @internal A single canonical price subscription shared by listeners. */\nexport type PriceKey =\n | {\n key: string;\n topic: 'prices.crypto';\n symbol: string;\n provider?: PriceProvider;\n }\n | {\n key: string;\n topic: 'prices.crypto.twap' | 'prices.equity.twap';\n symbol: string;\n windowSeconds: 60;\n provider?: PriceProvider;\n }\n | {\n key: string;\n topic: 'prices.equity';\n symbol: string;\n provider?: PriceProvider;\n };\n\nexport function subscriptionsFor(spec: PriceSubscription): PriceKey[] {\n const symbols = 'symbol' in spec ? [spec.symbol.toLowerCase()] : spec.symbols;\n const { provider } = spec;\n return symbols.map((symbol) => {\n if (\n spec.topic === 'prices.crypto.twap' ||\n spec.topic === 'prices.equity.twap'\n ) {\n return {\n key: JSON.stringify([spec.topic, symbol, 60, provider]),\n topic: spec.topic,\n symbol,\n windowSeconds: 60,\n provider,\n };\n }\n return {\n key: JSON.stringify([spec.topic, symbol, provider]),\n topic: spec.topic,\n symbol,\n provider,\n };\n });\n}\n\nexport function polyboltReconnectDelay(code: number, attempt: number): number {\n return (\n Math.random() *\n (code === 4003 ? 10_000 : Math.min(1_000 * 2 ** attempt, 30_000))\n );\n}\n","import {\n type PriceEvent,\n RealtimeKnownErrorCode,\n} from '@kuest/bindings/subscriptions';\nimport { setNonBlockingTimeout } from '@kuest/types';\nimport type { PriceSubscriptionConfirmation } from '../../actions/subscriptions';\nimport {\n ConnectionLostError,\n RequestRejectedError,\n TransportError,\n} from '../../errors';\nimport { ReconnectScheduler, type WebSocketCloseInfo } from '../lifecycle';\nimport { type PriceKey, polyboltReconnectDelay } from './protocol';\n\ntype KeyState = {\n subscription: PriceKey;\n listeners: Set<PriceListener>;\n ready: Promise<void>;\n resolve: () => void;\n reject: (error: Error) => void;\n subscribed: boolean;\n accepted: boolean;\n snapshot?: PriceEvent;\n confirmation?: PriceSubscriptionConfirmation;\n};\nexport type PriceListener = {\n subscribed?: (confirmation: PriceSubscriptionConfirmation) => void;\n event: (event: PriceEvent) => void;\n end: (error: Error) => void;\n};\nexport enum PriceSubscriptionOperation {\n Subscribe = 'subscribe',\n Unsubscribe = 'unsubscribe',\n}\nexport type PriceSubscriptionRejection = {\n key: string;\n error: RequestRejectedError;\n};\nexport type PriceSessionEvents = {\n subscribed: (\n subscription: PriceKey,\n confirmation: PriceSubscriptionConfirmation,\n ) => void;\n event: (event: PriceEvent) => void;\n dropped: () => void;\n disconnected: (info: WebSocketCloseInfo) => void;\n};\n/** @internal Operations required by subscription policy, independent of a wire protocol. */\nexport type PriceSessionConnection = {\n open: (events: PriceSessionEvents) => Promise<void>;\n authorize: () => Promise<void>;\n change: (\n operation: PriceSubscriptionOperation,\n subscriptions: readonly PriceKey[],\n ) => Promise<PriceSubscriptionRejection[]>;\n close: () => Promise<void>;\n};\ntype QueuedOp = { op: PriceSubscriptionOperation; keys: KeyState[] };\n\n/** @internal Owns acceptance, listener sharing, recovery, and subscription ordering. */\nexport class PriceSession {\n readonly #connection: PriceSessionConnection;\n readonly #scheduler = new ReconnectScheduler();\n readonly #keys = new Map<string, KeyState>();\n #ops: QueuedOp[] = [];\n #flushTimer: ReturnType<typeof setTimeout> | undefined;\n #idleTimer: ReturnType<typeof setTimeout> | undefined;\n #authenticated = false;\n #closed = false;\n #flushing = false;\n #restarting = false;\n #connecting: Promise<void> | undefined;\n #generation = 0;\n #keyTarget = 64;\n #lastDropAt = Number.NEGATIVE_INFINITY;\n\n constructor(connection: PriceSessionConnection) {\n this.#connection = connection;\n }\n get size(): number {\n return this.#keys.size;\n }\n has(key: string): boolean {\n return this.#keys.has(key);\n }\n get closed(): boolean {\n return this.#closed;\n }\n get keyTarget(): number {\n return Date.now() - this.#lastDropAt >= 60_000 ? 64 : this.#keyTarget;\n }\n\n add(subscription: PriceKey, listener: PriceListener): Promise<void> {\n clearTimeout(this.#idleTimer);\n let state = this.#keys.get(subscription.key);\n if (state === undefined) {\n const { promise, resolve, reject } = Promise.withResolvers<void>();\n // Reconnects may reject a ready promise before the caller attaches its await.\n void promise.catch(() => undefined);\n state = {\n subscription,\n listeners: new Set(),\n ready: promise,\n resolve,\n reject,\n subscribed: false,\n accepted: false,\n };\n this.#keys.set(subscription.key, state);\n if (this.#authenticated)\n this.#enqueue(PriceSubscriptionOperation.Subscribe, [state]);\n }\n state.listeners.add(listener);\n if (state.confirmation !== undefined)\n listener.subscribed?.({ ...state.confirmation });\n if (state.snapshot !== undefined) listener.event(state.snapshot);\n if (\n !this.#authenticated &&\n !this.#restarting &&\n this.#connecting === undefined &&\n !this.#scheduler.isScheduled\n ) {\n void this.#connect();\n }\n // A joining caller does not own a handle until acceptance. Bound its wait\n // independently so an existing listener can continue reconnecting.\n return awaitAcceptance(state.ready);\n }\n\n remove(key: string, listener: PriceListener): void {\n const state = this.#keys.get(key);\n if (state === undefined) return;\n state.listeners.delete(listener);\n if (state.listeners.size > 0) return;\n this.#keys.delete(key);\n state.reject(new TransportError('Realtime subscription closed.'));\n // Retain unsubscribe ordering even when subscribe is already in flight.\n if (this.#authenticated)\n this.#enqueue(PriceSubscriptionOperation.Unsubscribe, [state]);\n if (this.#keys.size === 0)\n this.#idleTimer = setNonBlockingTimeout(() => {\n void this.close();\n }, 1_000);\n }\n\n #connect(): Promise<void> {\n if (this.#closed || this.#restarting) return Promise.resolve();\n if (this.#connecting !== undefined) return this.#connecting;\n const connecting = this.#open()\n .catch((cause: unknown) => {\n this.#rejectKeys(\n [...this.#keys.values()].filter((key) => !key.accepted),\n TransportError.fromError(cause),\n );\n })\n .finally(() => {\n if (this.#connecting === connecting) this.#connecting = undefined;\n if (!this.#authenticated) this.#schedule(1006);\n });\n this.#connecting = connecting;\n return connecting;\n }\n\n async #open(): Promise<void> {\n const generation = this.#generation;\n await this.#connection.open({\n subscribed: (subscription, confirmation) =>\n this.#subscribed(subscription, confirmation),\n event: (event) => this.#event(event),\n dropped: () => this.#recordDrop(),\n disconnected: (info) => this.#lost(info),\n });\n if (this.#closed || generation !== this.#generation) return;\n try {\n await this.#connection.authorize();\n if (this.#closed || generation !== this.#generation) return;\n this.#authenticated = true;\n this.#enqueue(PriceSubscriptionOperation.Subscribe, [\n ...this.#keys.values(),\n ]);\n } catch (error) {\n if (this.#closed || generation !== this.#generation) return;\n if (\n error instanceof RequestRejectedError &&\n error.code !== RealtimeKnownErrorCode.AuthUnavailable\n ) {\n this.#fail(error);\n } else {\n await this.#restart(1006);\n }\n }\n }\n\n #enqueue(op: PriceSubscriptionOperation, keys: KeyState[]): void {\n if (keys.length === 0) return;\n const last = this.#ops.at(-1);\n if (last?.op === op) last.keys.push(...keys);\n else this.#ops.push({ op, keys });\n this.#scheduleFlush();\n }\n\n #scheduleFlush(): void {\n if (\n this.#flushTimer !== undefined ||\n this.#flushing ||\n !this.#authenticated ||\n this.#closed\n )\n return;\n // Collect adjacent changes; the connection owns operation pacing.\n this.#flushTimer = setNonBlockingTimeout(() => {\n this.#flushTimer = undefined;\n void this.#flush();\n }, 10);\n }\n\n async #flush(): Promise<void> {\n if (!this.#authenticated || this.#closed) return;\n const next = this.#ops.shift();\n if (next === undefined) return;\n const batch = [...new Set(next.keys)].filter(\n (key) =>\n next.op === PriceSubscriptionOperation.Unsubscribe ||\n this.#keys.get(key.subscription.key) === key,\n );\n if (batch.length === 0) {\n this.#scheduleFlush();\n return;\n }\n const generation = this.#generation;\n this.#flushing = true;\n try {\n const rejections = await this.#connection.change(\n next.op,\n batch.map(({ subscription }) => subscription),\n );\n if (generation !== this.#generation || this.#closed) return;\n if (\n next.op === PriceSubscriptionOperation.Unsubscribe &&\n rejections.length > 0\n ) {\n const rejection = rejections[0];\n if (rejection !== undefined) throw rejection.error;\n }\n if (next.op === PriceSubscriptionOperation.Subscribe) {\n this.#scheduler.resetBackoff();\n const rejectedKeys = new Set(\n rejections.map((rejection) => rejection.key),\n );\n for (const key of batch) {\n if (rejectedKeys.has(key.subscription.key)) continue;\n key.subscribed = true;\n key.accepted = true;\n key.resolve();\n }\n for (const { key: rejectedKey, error } of rejections) {\n const key = batch.find(\n (item) => item.subscription.key === rejectedKey,\n );\n if (key !== undefined) this.#rejectKeys([key], error, false);\n }\n }\n } catch (error) {\n if (generation !== this.#generation || this.#closed) return;\n if (\n error instanceof RequestRejectedError &&\n next.op === PriceSubscriptionOperation.Subscribe\n ) {\n this.#rejectKeys(batch, error);\n } else {\n // Acceptance is uncertain after an ack timeout or send failure. A new\n // connection clears upstream state and replays the remaining keys.\n // Rejected unsubscriptions need the same cleanup for orphaned filters.\n await this.#restart(1006);\n }\n } finally {\n this.#flushing = false;\n this.#scheduleFlush();\n }\n }\n\n #subscribed(\n subscription: PriceKey,\n confirmation: PriceSubscriptionConfirmation,\n ): void {\n const state = this.#keys.get(subscription.key);\n if (state?.subscription !== subscription) return;\n state.confirmation = { ...confirmation };\n for (const listener of [...state.listeners])\n listener.subscribed?.({ ...confirmation });\n }\n\n #event(event: PriceEvent): void {\n for (const state of this.#keys.values()) {\n const subscription = state.subscription;\n if (subscription.topic !== event.topic) continue;\n const payload = event.payload;\n if (payload.symbol.toLowerCase() !== subscription.symbol) continue;\n if (\n (subscription.topic === 'prices.crypto.twap' ||\n subscription.topic === 'prices.equity.twap') &&\n (!('windowSeconds' in payload) ||\n payload.windowSeconds !== subscription.windowSeconds)\n )\n continue;\n state.snapshot = refreshSnapshot(state.snapshot, event);\n for (const listener of state.listeners) listener.event(event);\n }\n }\n\n #recordDrop(): void {\n const now = Date.now();\n if (now - this.#lastDropAt < 5_000) return;\n this.#keyTarget = Math.max(1, Math.floor(this.keyTarget / 2));\n this.#lastDropAt = now;\n }\n\n #reset(): void {\n this.#generation++;\n this.#authenticated = false;\n this.#ops = [];\n clearTimeout(this.#flushTimer);\n this.#flushTimer = undefined;\n for (const state of this.#keys.values()) {\n state.snapshot = undefined;\n state.confirmation = undefined;\n if (!state.subscribed) continue;\n const { promise, resolve, reject } = Promise.withResolvers<void>();\n void promise.catch(() => undefined);\n state.ready = promise;\n state.resolve = resolve;\n state.reject = reject;\n state.subscribed = false;\n }\n }\n\n #lost(info: WebSocketCloseInfo): void {\n const error = new ConnectionLostError('Realtime connection closed.', info);\n this.#reset();\n if (info.code === 4001 || info.code === 4008) this.#fail(error);\n else this.#schedule(info.code);\n }\n\n async #restart(code: number): Promise<void> {\n this.#restarting = true;\n this.#reset();\n try {\n await this.#connection.close();\n } finally {\n this.#restarting = false;\n this.#schedule(code);\n }\n }\n\n #schedule(code: number): void {\n this.#scheduler.schedule({\n delayPolicy: (attempt) => polyboltReconnectDelay(code, attempt),\n shouldReconnect: () => !this.#closed && this.#keys.size > 0,\n reconnect: () => this.#connect(),\n });\n }\n\n #fail(error: Error): void {\n // Ending one multi-key handle removes listeners from other keys. Snapshot\n // the fanout first so every handle still observes the terminal error.\n const states = [...this.#keys.values()];\n const listeners = new Set(states.flatMap((key) => [...key.listeners]));\n for (const key of states) key.reject(error);\n for (const listener of listeners) listener.end(error);\n void this.close();\n }\n\n #rejectKeys(keys: KeyState[], error: Error, unsubscribe = true): void {\n const current = keys.filter(\n (key) => this.#keys.get(key.subscription.key) === key,\n );\n // Listener teardown can remove several keys. Capture the fanout before\n // notifying anyone and never reject a replacement state for the same key.\n const listeners = new Set(current.flatMap((key) => [...key.listeners]));\n for (const key of current) {\n this.#keys.delete(key.subscription.key);\n key.reject(error);\n }\n if (unsubscribe && this.#authenticated)\n this.#enqueue(PriceSubscriptionOperation.Unsubscribe, current);\n for (const listener of listeners) listener.end(error);\n if (this.#keys.size === 0) {\n this.#idleTimer = setNonBlockingTimeout(() => {\n void this.close();\n }, 1_000);\n }\n }\n\n async close(): Promise<void> {\n if (this.#closed) return;\n this.#closed = true;\n this.#scheduler.stop();\n clearTimeout(this.#idleTimer);\n const error = new TransportError('Realtime connection closed.');\n this.#reset();\n for (const key of this.#keys.values()) {\n key.reject(error);\n }\n this.#keys.clear();\n await this.#connection.close();\n }\n}\n\nfunction awaitAcceptance(ready: Promise<void>): Promise<void> {\n return new Promise((resolve, reject) => {\n const timer = setNonBlockingTimeout(() => {\n reject(\n new TransportError(\n 'Realtime subscription was not accepted within 30 seconds.',\n ),\n );\n }, 30_000);\n void ready.then(\n () => {\n clearTimeout(timer);\n resolve();\n },\n (error: unknown) => {\n clearTimeout(timer);\n reject(error);\n },\n );\n });\n}\n\n// A handle joining a shared key needs current history, not the barrier from\n// when the first handle connected. Maintain the same two-minute window locally.\nfunction refreshSnapshot(\n previous: PriceEvent | undefined,\n event: PriceEvent,\n): PriceEvent | undefined {\n if (event.type === 'subscribe') return event;\n const { symbol, source, timestamp, value } = event.payload;\n const history =\n previous?.type === 'subscribe' && previous.payload.source === source\n ? previous.payload.data\n : [];\n if ((history.at(-1)?.timestamp ?? 0) > timestamp) return previous;\n const data = [\n ...history.filter(\n (point) =>\n point.timestamp > timestamp - 120_000 && point.timestamp < timestamp,\n ),\n { timestamp, value },\n ];\n if (\n event.topic === 'prices.crypto.twap' ||\n event.topic === 'prices.equity.twap'\n )\n return {\n ...event,\n type: 'subscribe',\n payload: {\n symbol,\n source,\n data,\n windowSeconds: event.payload.windowSeconds,\n },\n };\n return { ...event, type: 'subscribe', payload: { symbol, source, data } };\n}\n","import type { ApiKeyCreds } from '@kuest/bindings/clob';\nimport {\n PolyboltAckOp,\n PolyboltAckSchema,\n PolyboltChannel,\n PolyboltEnvelopeSchema,\n type PolyboltSubscription,\n parsePolyboltEvent,\n} from '@kuest/bindings/subscriptions';\nimport { setNonBlockingTimeout } from '@kuest/types';\nimport {\n ConnectionLostError,\n RequestRejectedError,\n TransportError,\n} from '../../errors';\nimport { PolyboltWebSocketHeartbeat } from '../heartbeat';\nimport { WebSocketConnection } from '../lifecycle';\nimport type { PriceKey } from './protocol';\nimport {\n type PriceSessionConnection,\n type PriceSessionEvents,\n PriceSubscriptionOperation,\n type PriceSubscriptionRejection,\n} from './session';\n\ntype PendingRejection = { index: number; error: RequestRejectedError };\ntype PendingOp = {\n op: PolyboltAckOp;\n channels: (string | undefined)[];\n subscriptions: readonly PriceKey[];\n rejections: PendingRejection[];\n resolve: (rejections: PendingRejection[]) => void;\n reject: (error: Error) => void;\n timer?: ReturnType<typeof setTimeout>;\n sendTimer?: ReturnType<typeof setTimeout>;\n};\nexport type PolyboltConnectionOptions = {\n url: string;\n headers?: Record<string, string>;\n credentials: ApiKeyCreds;\n};\n\n/** @internal Adapts price operations and events to the PolyBolt wire protocol. */\nexport class PolyboltConnection implements PriceSessionConnection {\n readonly #options: PolyboltConnectionOptions;\n readonly #connection = new WebSocketConnection({\n heartbeat: new PolyboltWebSocketHeartbeat(),\n connectTimeoutMs: 10_000,\n closeTimeoutMs: 1_000,\n });\n readonly #pending = new Map<string, PendingOp>();\n #events: PriceSessionEvents | undefined;\n #requestId = 0;\n #lastSent = 0;\n #generation = 0;\n\n constructor(options: PolyboltConnectionOptions) {\n this.#options = options;\n }\n\n async open(events: PriceSessionEvents): Promise<void> {\n this.#events = events;\n const generation = this.#generation;\n await this.#connection.connect({\n url: this.#options.url,\n headers: this.#options.headers,\n onOpen: () => undefined,\n onError: () => undefined,\n onConnectionLost: (info) => {\n if (generation !== this.#generation) return;\n this.#cancel(\n new ConnectionLostError('Realtime connection closed.', info),\n );\n events.disconnected(info);\n },\n onMessage: (message) => {\n if (generation === this.#generation) this.#message(message);\n },\n });\n }\n\n async authorize(): Promise<void> {\n const { key, secret, passphrase } = this.#options.credentials;\n await this.#request(\n { op: 'auth', auth: { apiKey: key, secret, passphrase } },\n PolyboltAckOp.Authed,\n [],\n );\n }\n\n async change(\n operation: PriceSubscriptionOperation,\n subscriptions: readonly PriceKey[],\n ): Promise<PriceSubscriptionRejection[]> {\n const rejected: PriceSubscriptionRejection[] = [];\n let offset = 0;\n while (offset < subscriptions.length) {\n const batch: PolyboltSubscription[] = [];\n while (offset + batch.length < subscriptions.length) {\n const subscription = subscriptions[offset + batch.length];\n if (subscription === undefined) break;\n const candidate = toWireSubscription(subscription);\n const frame = {\n op: operation,\n subscriptions: [...batch, candidate],\n rid: String(this.#requestId + 1),\n };\n if (\n batch.length > 0 &&\n new TextEncoder().encode(JSON.stringify(frame)).length > 60_000\n )\n break;\n batch.push(candidate);\n }\n const rejections = await this.#request(\n { op: operation, subscriptions: batch },\n operation === PriceSubscriptionOperation.Subscribe\n ? PolyboltAckOp.Subscribed\n : PolyboltAckOp.Unsubscribed,\n batch.map(({ channel }) => channel),\n subscriptions.slice(offset, offset + batch.length),\n );\n for (const { index, error } of rejections) {\n const subscription = subscriptions[offset + index];\n if (subscription !== undefined)\n rejected.push({ key: subscription.key, error });\n }\n offset += batch.length;\n }\n return rejected;\n }\n\n #request(\n frame: object,\n op: PolyboltAckOp,\n channels: PolyboltChannel[],\n subscriptions: readonly PriceKey[] = [],\n ): Promise<PendingRejection[]> {\n const rid = String(++this.#requestId);\n return new Promise((resolve, reject) => {\n const pending: PendingOp = {\n op,\n channels: [...channels],\n subscriptions,\n rejections: [],\n resolve,\n reject,\n };\n this.#pending.set(rid, pending);\n // Capacity-one pacing covers authentication and every operation frame.\n pending.sendTimer = setNonBlockingTimeout(\n () => {\n pending.timer = setNonBlockingTimeout(() => {\n this.#pending.delete(rid);\n reject(\n new TransportError(\n 'Realtime acknowledgement timed out after 10 seconds.',\n ),\n );\n }, 10_000);\n this.#lastSent = Date.now();\n try {\n if (!this.#connection.send({ ...frame, rid }))\n throw new TransportError('Realtime connection is not open.');\n } catch (cause) {\n clearTimeout(pending.timer);\n this.#pending.delete(rid);\n reject(TransportError.fromError(cause));\n }\n },\n Math.max(0, 110 - (Date.now() - this.#lastSent)),\n );\n });\n }\n\n #message(message: unknown): void {\n const ack = PolyboltAckSchema.safeParse(message);\n if (ack.success) {\n const { op, rid, code, channel, provider } = ack.data;\n const pending = rid === undefined ? undefined : this.#pending.get(rid);\n if (pending === undefined) return;\n if (op === PolyboltAckOp.Error && code !== undefined) {\n const error = new RequestRejectedError(\n `Realtime subscription rejected: ${code}`,\n { status: 200, code },\n );\n const matches = pending.channels.flatMap((pendingChannel, index) =>\n pendingChannel === channel ? [index] : [],\n );\n if (channel === undefined || matches.length !== 1) {\n pending.reject(error);\n } else {\n const index = matches[0];\n if (index === undefined) return;\n pending.channels[index] = undefined;\n pending.rejections.push({ index, error });\n if (\n pending.channels.some(\n (pendingChannel) => pendingChannel !== undefined,\n )\n )\n return;\n pending.resolve(pending.rejections);\n }\n } else if (op === pending.op) {\n if (pending.channels.length > 0) {\n // Batch acknowledgements arrive in request order and omit symbols.\n const index = pending.channels.findIndex(\n (pendingChannel) => pendingChannel !== undefined,\n );\n if (index < 0 || pending.channels[index] !== channel) return;\n pending.channels[index] = undefined;\n const subscription = pending.subscriptions[index];\n if (op === PolyboltAckOp.Subscribed && subscription !== undefined)\n this.#events?.subscribed(subscription, {\n symbol: subscription.symbol,\n provider,\n });\n if (\n pending.channels.some(\n (pendingChannel) => pendingChannel !== undefined,\n )\n )\n return;\n }\n pending.resolve(pending.rejections);\n } else return;\n clearTimeout(pending.timer);\n if (rid !== undefined) this.#pending.delete(rid);\n return;\n }\n const envelope = PolyboltEnvelopeSchema.safeParse(message);\n if (!envelope.success) return;\n const event = parsePolyboltEvent(envelope.data);\n if (event !== undefined) this.#events?.event(event);\n if ((envelope.data.dropped ?? 0) > 0) this.#events?.dropped();\n }\n\n #cancel(error: Error): void {\n for (const pending of this.#pending.values()) {\n clearTimeout(pending.sendTimer);\n clearTimeout(pending.timer);\n pending.reject(error);\n }\n this.#pending.clear();\n }\n\n async close(): Promise<void> {\n this.#generation++;\n this.#events = undefined;\n this.#cancel(new TransportError('Realtime connection closed.'));\n await this.#connection.close();\n }\n}\n\nfunction toWireSubscription(subscription: PriceKey): PolyboltSubscription {\n switch (subscription.topic) {\n case 'prices.crypto':\n return {\n channel: PolyboltChannel.Crypto,\n filter: {\n symbol: subscription.symbol,\n provider: subscription.provider,\n },\n };\n case 'prices.crypto.twap':\n return {\n channel: PolyboltChannel.Twap,\n filter: {\n symbol: subscription.symbol,\n window_seconds: subscription.windowSeconds,\n provider: subscription.provider,\n },\n };\n case 'prices.equity':\n return {\n channel: PolyboltChannel.Equity,\n filter: {\n symbol: subscription.symbol,\n provider: subscription.provider,\n },\n };\n case 'prices.equity.twap':\n return {\n channel: PolyboltChannel.EquityTwap,\n filter: {\n symbol: subscription.symbol,\n window_seconds: subscription.windowSeconds,\n provider: subscription.provider,\n },\n };\n }\n}\n","import type { PriceEvent, PriceProvider } from '@kuest/bindings/subscriptions';\nimport { pushable } from 'it-pushable';\nimport type {\n PriceSubscription,\n SubscriptionHandle,\n} from '../../actions/subscriptions';\nimport { TransportError } from '../../errors';\nimport { subscriptionsFor } from './protocol';\nimport { type PriceListener, PriceSession } from './session';\nimport { PolyboltConnection, type PolyboltConnectionOptions } from './socket';\n\n/** @internal Keeps each filter on exactly one connection until it is removed. */\nexport class SocketPool {\n readonly #options: PolyboltConnectionOptions;\n readonly #sockets = new Map<PriceSession, PriceProvider | undefined>();\n readonly #closers = new Set<() => Promise<void>>();\n constructor(options: PolyboltConnectionOptions) {\n this.#options = options;\n }\n\n async subscribe(\n spec: PriceSubscription,\n ): Promise<SubscriptionHandle<PriceEvent>> {\n const subscriptions = [\n ...new Map(\n subscriptionsFor(spec).map((subscription) => [\n subscription.key,\n subscription,\n ]),\n ).values(),\n ];\n const queue = pushable<PriceEvent>({ objectMode: true });\n const releases: (() => void)[] = [];\n let closed = false;\n let terminalError: Error | undefined;\n const close = async () => {\n if (closed) return;\n closed = true;\n for (const release of releases) release();\n if (terminalError === undefined) await queue.return();\n else queue.end(terminalError);\n this.#closers.delete(close);\n };\n this.#closers.add(close);\n const fail = (cause: unknown) => {\n if (closed) return;\n terminalError = TransportError.fromError(cause);\n queue.end(terminalError);\n void close();\n };\n try {\n // A cached confirmation can call back synchronously inside `add`, so every\n // promise is created and given a handler before any of them is awaited.\n const pending = subscriptions.map((subscription) => {\n if (closed) return Promise.resolve();\n const socket = this.#place(subscription.key, subscription.provider);\n const listener: PriceListener = {\n subscribed(confirmation) {\n if (closed || !('onSubscribed' in spec)) return;\n try {\n void Promise.resolve(spec.onSubscribed?.(confirmation)).catch(\n fail,\n );\n } catch (cause) {\n fail(cause);\n }\n },\n event(event) {\n if (closed) return;\n if (\n 'types' in spec &&\n spec.types !== undefined &&\n spec.types.length > 0 &&\n !spec.types.includes(event.type)\n )\n return;\n const payload =\n 'symbol' in event.payload\n ? {\n ...event.payload,\n symbol:\n 'symbol' in subscription\n ? subscription.symbol\n : event.payload.symbol,\n }\n : event.payload;\n // Each shared key uses the same canonical symbol spelling.\n queue.push({\n ...event,\n payload,\n } as PriceEvent);\n },\n end(error) {\n terminalError = error;\n queue.end(error);\n void close();\n },\n };\n releases.push(() => socket.remove(subscription.key, listener));\n return socket.add(subscription, listener);\n });\n for (const promise of pending) promise.catch(() => undefined);\n await Promise.all(pending);\n if (terminalError !== undefined) throw terminalError;\n } catch (error) {\n await close();\n throw terminalError ?? error;\n }\n return {\n close,\n async *[Symbol.asyncIterator]() {\n try {\n yield* queue;\n } finally {\n await close();\n }\n },\n };\n }\n\n #place(key: string, provider: PriceProvider | undefined): PriceSession {\n for (const socket of this.#sockets.keys()) {\n if (socket.closed) this.#sockets.delete(socket);\n else if (socket.has(key)) return socket;\n }\n // Different pins can collapse to one server key or produce indistinguishable\n // fallback streams. Keep each connection's requested-provider group fixed,\n // including while idle and across reconnects.\n for (const [socket, requestedProvider] of this.#sockets)\n if (requestedProvider === provider && socket.size < socket.keyTarget)\n return socket;\n const socket = new PriceSession(new PolyboltConnection(this.#options));\n this.#sockets.set(socket, provider);\n return socket;\n }\n\n async close(): Promise<void> {\n await Promise.all([...this.#closers].map((close) => close()));\n const sockets = [...this.#sockets.keys()];\n this.#sockets.clear();\n await Promise.all(sockets.map((socket) => socket.close()));\n }\n}\n","import type { ApiKeyCreds } from '@kuest/bindings/clob';\nimport type { PriceEvent } from '@kuest/bindings/subscriptions';\nimport type {\n EventForSubscriptionSpec,\n PriceSubscription,\n SubscriptionHandle,\n} from '../../actions/subscriptions';\nimport type { WebSocketSubscriptionManager } from '../types';\nimport { SocketPool } from './pool';\n\nexport type { SubscribeError } from '../../actions/subscriptions';\n\nexport type RealtimeWebSocketManagerOptions = {\n url: string;\n headers?: Record<string, string>;\n credentials: ApiKeyCreds;\n};\n\n/** @internal Manages authenticated realtime prices across shared connections. */\nexport class RealtimeWebSocketManager\n implements WebSocketSubscriptionManager<PriceSubscription, PriceEvent>\n{\n readonly #pool: SocketPool;\n\n constructor(options: RealtimeWebSocketManagerOptions) {\n this.#pool = new SocketPool(options);\n }\n\n /**\n * Starts a price subscription and awaits server acceptance.\n * @throws {@link SubscribeError} When input is invalid or the subscription fails.\n */\n async subscribe<const TSpec extends PriceSubscription>(\n spec: TSpec,\n ): Promise<SubscriptionHandle<EventForSubscriptionSpec<TSpec>>> {\n return this.#pool.subscribe(spec) as Promise<\n SubscriptionHandle<EventForSubscriptionSpec<TSpec>>\n >;\n }\n\n /** Closes every active price subscription and shared connection. */\n async close(): Promise<void> {\n await this.#pool.close();\n }\n}\n","import {\n type RfqConfirmationAck as BindingRfqConfirmationAck,\n type RfqQuoteAck as BindingRfqQuoteAck,\n type RfqQuoteCancelAck as BindingRfqQuoteCancelAck,\n RfqConfirmationDecision,\n type RfqConfirmationRequest,\n type RfqExecutionUpdate,\n type RfqId,\n type RfqQuoteId,\n type RfqQuoteRequest,\n type RfqTrade,\n} from '@kuest/bindings/combos';\nimport type {\n RfqCancelQuoteAck,\n RfqConfirmationAck,\n RfqConfirmationRequestEvent,\n RfqExecutionUpdateEvent,\n RfqQuoteReference,\n RfqQuoteRequestEvent,\n RfqQuoteResponse,\n RfqTradeEvent,\n} from '../../actions/rfq';\n\nexport interface RfqEventController {\n quote(\n request: RfqQuoteRequest,\n response: RfqQuoteResponse,\n ): Promise<RfqQuoteReference>;\n respondToConfirmation(\n rfqId: RfqId,\n quoteId: RfqQuoteId,\n decision: RfqConfirmationDecision,\n ): Promise<RfqConfirmationAck>;\n}\n\nexport function toQuoteRequestEvent(\n controller: RfqEventController,\n message: RfqQuoteRequest,\n): RfqQuoteRequestEvent {\n return {\n ...message,\n quote: (request) => controller.quote(message, request),\n };\n}\n\nexport function toConfirmationRequestEvent(\n controller: RfqEventController,\n message: RfqConfirmationRequest,\n): RfqConfirmationRequestEvent {\n const rfqId = message.rfqId;\n const quoteId = message.quoteId;\n return {\n ...message,\n confirm: () =>\n controller.respondToConfirmation(\n rfqId,\n quoteId,\n RfqConfirmationDecision.Confirm,\n ),\n decline: () =>\n controller.respondToConfirmation(\n rfqId,\n quoteId,\n RfqConfirmationDecision.Decline,\n ),\n };\n}\n\nexport function toExecutionUpdateEvent(\n message: RfqExecutionUpdate,\n): RfqExecutionUpdateEvent {\n return message;\n}\n\nexport function toTradeEvent(message: RfqTrade): RfqTradeEvent {\n return message;\n}\n\nexport function toQuoteAck(message: BindingRfqQuoteAck): RfqQuoteReference {\n return {\n quoteId: message.quoteId,\n rfqId: message.rfqId,\n };\n}\n\nexport function toQuoteCancelAck(\n message: BindingRfqQuoteCancelAck,\n): RfqCancelQuoteAck {\n return {\n quoteId: message.quoteId,\n rfqId: message.rfqId,\n };\n}\n\nexport function toConfirmationAck(\n message: BindingRfqConfirmationAck,\n): RfqConfirmationAck {\n return {\n quoteId: message.quoteId,\n rfqId: message.rfqId,\n };\n}\n","import type { ApiKeyCreds } from '@kuest/bindings/clob';\nimport type {\n RfqAuthMessage,\n RfqConfirmationDecision,\n RfqConfirmationResponseMessage,\n RfqId,\n RfqQuoteCancelMessage,\n RfqQuoteId,\n RfqQuoteMessage,\n RfqQuoteRequest,\n} from '@kuest/bindings/combos';\nimport type { AccountIdentity } from '../../wallet';\nimport { resolveOrderIdentity } from '../../wallet';\nimport type { RfqQuote } from './quote';\n\nexport function createAuthMessage(\n account: AccountIdentity,\n credentials: ApiKeyCreds,\n): RfqAuthMessage {\n const identity = resolveOrderIdentity(account);\n\n return {\n auth: {\n apiKey: credentials.key,\n passphrase: credentials.passphrase,\n secret: credentials.secret,\n },\n identity: {\n maker_address: identity.maker,\n signature_type: identity.signatureType,\n signer_address: identity.signer,\n },\n type: 'auth',\n };\n}\n\nexport function createQuoteMessage(\n request: RfqQuoteRequest,\n quote: RfqQuote,\n): RfqQuoteMessage {\n return {\n price_e6: quote.price.toString(),\n rfq_id: request.rfqId,\n signed_order: quote.signedOrder,\n size_e6: quote.size.toString(),\n type: 'RFQ_QUOTE',\n };\n}\n\nexport function createQuoteCancelMessage(\n account: AccountIdentity,\n rfqId: RfqId,\n quoteId: RfqQuoteId,\n): RfqQuoteCancelMessage {\n const identity = resolveOrderIdentity(account);\n\n return {\n maker_address: identity.maker,\n quote_id: quoteId,\n rfq_id: rfqId,\n signer_address: identity.signer,\n type: 'RFQ_QUOTE_CANCEL',\n };\n}\n\nexport function createConfirmationResponseMessage(\n rfqId: RfqId,\n quoteId: RfqQuoteId,\n decision: RfqConfirmationDecision,\n): RfqConfirmationResponseMessage {\n return {\n decision,\n quote_id: quoteId,\n rfq_id: rfqId,\n type: 'RFQ_CONFIRMATION_RESPONSE',\n };\n}\n","import { setNonBlockingTimeout } from '@kuest/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 { type OrderSide, type PositionId, toBaseUnits } from '@kuest/bindings';\nimport type { RfqSignedOrder } from '@kuest/bindings/combos';\nimport type { EvmAddress, EvmSignature, HexString } from '@kuest/types';\nimport { SigningError } from '../../errors';\nimport {\n calculateExchangeOrderMakerAmount,\n calculateExchangeOrderTakerAmount,\n createExchangeOrderSignature,\n createExchangeOrderTypedDataPayload,\n createExchangeV3OrderDomain,\n encodeExchangeOrderSide,\n} from '../../exchange';\nimport type { Signer } from '../../types';\nimport type { AccountIdentity } from '../../wallet';\nimport { resolveOrderIdentity } from '../../wallet';\n\nconst BYTES32_ZERO =\n '0x0000000000000000000000000000000000000000000000000000000000000000' satisfies HexString;\n\nexport type SignRfqQuoteOrderParams = {\n account: AccountIdentity;\n chainId: number;\n exchange: EvmAddress;\n orderPrice: bigint;\n orderSide: OrderSide;\n signer: Signer;\n size: bigint;\n tokenId: PositionId;\n};\n\nexport async function signRfqQuoteOrder(\n params: SignRfqQuoteOrderParams,\n): Promise<RfqSignedOrder> {\n const identity = resolveOrderIdentity(params.account);\n const domain = createExchangeV3OrderDomain({\n chainId: params.chainId,\n exchange: params.exchange,\n });\n const order: Omit<RfqSignedOrder, 'signature'> = {\n builder: BYTES32_ZERO,\n maker: identity.maker,\n makerAmount: toBaseUnits(\n calculateExchangeOrderMakerAmount(\n params.orderSide,\n params.orderPrice,\n params.size,\n ),\n ),\n metadata: BYTES32_ZERO,\n salt: generateRfqOrderSalt().toString(),\n side: encodeExchangeOrderSide(params.orderSide),\n signatureType: identity.signatureType,\n signer: identity.signer,\n takerAmount: toBaseUnits(\n calculateExchangeOrderTakerAmount(\n params.orderSide,\n params.orderPrice,\n params.size,\n ),\n ),\n timestamp: Math.floor(Date.now() / 1000).toString(),\n tokenId: params.tokenId,\n };\n\n let signature: EvmSignature;\n try {\n signature = await params.signer.signTypedData(\n createExchangeOrderTypedDataPayload({ domain, order }),\n );\n } catch (error) {\n throw SigningError.fromError(error, 'Could not sign the RFQ quote order.');\n }\n\n return {\n ...order,\n signature: createExchangeOrderSignature({ domain, order, signature }),\n };\n}\n\nfunction generateRfqOrderSalt(): bigint {\n const bytes = new Uint8Array(8);\n globalThis.crypto.getRandomValues(bytes);\n\n // RFQ salts stay strings on the wire, so the full 64-bit value is lossless.\n return BigInt(\n `0x${Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('')}`,\n );\n}\n","import {\n DecimalishSchema,\n type DecimalString,\n OrderSide,\n type PositionId,\n} from '@kuest/bindings';\nimport {\n RfqDirection,\n type RfqQuoteRequest,\n type RfqRequestedSize,\n RfqRequestedSizeUnit,\n type RfqSignedOrder,\n} from '@kuest/bindings/combos';\nimport type { EvmAddress } from '@kuest/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 '@kuest/bindings/clob';\nimport {\n type RfqConfirmationDecision,\n type RfqErrorMessage,\n type RfqId,\n type RfqQuoteId,\n type RfqQuoteRequest,\n RfqQuoterInboundMessageSchema,\n type RfqQuoterOutboundMessage,\n} from '@kuest/bindings/combos';\nimport { type EvmAddress, setNonBlockingTimeout } from '@kuest/types';\nimport { type Pushable, pushable } from 'it-pushable';\nimport type {\n RfqCancelQuoteAck,\n RfqConfirmationAck,\n RfqEvent,\n RfqQuoteReference,\n RfqQuoteResponse,\n RfqSession,\n} from '../../actions/rfq';\nimport {\n RfqCancelQuoteRejectedError,\n RfqConfirmationRejectedError,\n RfqQuoteRejectedError,\n} from '../../actions/rfq';\nimport { ConnectionLostError, TransportError } from '../../errors';\nimport type { Signer } from '../../types';\nimport type { AccountIdentity } from '../../wallet';\nimport { type WebSocketCloseInfo, WebSocketConnection } from '../lifecycle';\nimport {\n type RfqEventController,\n toConfirmationAck,\n toConfirmationRequestEvent,\n toExecutionUpdateEvent,\n toQuoteAck,\n toQuoteCancelAck,\n toQuoteRequestEvent,\n toTradeEvent,\n} from './events';\nimport {\n createAuthMessage,\n createConfirmationResponseMessage,\n createQuoteCancelMessage,\n createQuoteMessage,\n} from './messages';\nimport { PendingResponses } from './pending';\nimport { createRfqQuote, parseRfqQuoteResponse } from './quote';\n\nconst AUTH_TIMEOUT_MS = 30_000;\nconst ACK_TIMEOUT_MS = 30_000;\n\nexport type RfqQuoterWebSocketManagerOptions = {\n account: AccountIdentity;\n chainId: number;\n credentials: ApiKeyCreds;\n exchange: EvmAddress;\n headers?: Record<string, string>;\n signer: Signer;\n url: string;\n};\n\nexport class RfqQuoterWebSocketManager {\n readonly #account: AccountIdentity;\n readonly #chainId: number;\n readonly #credentials: ApiKeyCreds;\n readonly #exchange: EvmAddress;\n readonly #headers: Record<string, string> | undefined;\n readonly #signer: Signer;\n readonly #url: string;\n #session: RfqWebSocketSession | undefined;\n #connectingSession: RfqWebSocketSession | undefined;\n #connecting: Promise<RfqSession> | undefined;\n #hasShutdown = false;\n\n constructor(options: RfqQuoterWebSocketManagerOptions) {\n this.#account = options.account;\n this.#chainId = options.chainId;\n this.#credentials = options.credentials;\n this.#exchange = options.exchange;\n this.#headers = options.headers;\n this.#signer = options.signer;\n this.#url = options.url;\n }\n\n async connect(): Promise<RfqSession> {\n if (this.#hasShutdown) {\n throw new TransportError('RFQ quoter manager has been shut down.');\n }\n\n if (this.#session !== undefined) {\n if (!this.#session.closed) return this.#session;\n this.#session = undefined;\n }\n if (this.#connecting !== undefined) return this.#connecting;\n\n const session = new RfqWebSocketSession({\n account: this.#account,\n chainId: this.#chainId,\n credentials: this.#credentials,\n exchange: this.#exchange,\n headers: this.#headers,\n onClose: () => this.#clearSession(session),\n signer: this.#signer,\n url: this.#url,\n });\n this.#connectingSession = session;\n\n let connecting!: Promise<RfqSession>;\n connecting = (async () => {\n try {\n await session.connect();\n if (this.#hasShutdown) {\n await session.close();\n throw new TransportError('RFQ quoter manager has been shut down.');\n }\n this.#session = session;\n return session;\n } catch (error) {\n await session.close();\n throw error;\n } finally {\n if (this.#connecting === connecting) {\n this.#connecting = undefined;\n }\n if (this.#connectingSession === session) {\n this.#connectingSession = undefined;\n }\n }\n })();\n\n this.#connecting = connecting;\n return connecting;\n }\n\n async shutdown(): Promise<void> {\n this.#hasShutdown = true;\n const session = this.#session;\n const connectingSession = this.#connectingSession;\n const connecting = this.#connecting;\n\n this.#session = undefined;\n this.#connectingSession = undefined;\n this.#connecting = undefined;\n\n await Promise.allSettled([\n session?.close(),\n connectingSession?.close(),\n connecting?.catch(() => undefined),\n ]).then(() => undefined);\n }\n\n #clearSession(session: RfqWebSocketSession): void {\n if (this.#session === session) {\n this.#session = undefined;\n }\n if (this.#connectingSession === session) {\n this.#connectingSession = undefined;\n }\n }\n}\n\ntype RfqWebSocketSessionConfig = {\n account: AccountIdentity;\n chainId: number;\n credentials: ApiKeyCreds;\n exchange: EvmAddress;\n headers?: Record<string, string>;\n onClose: () => void;\n signer: Signer;\n url: string;\n};\n\nclass RfqWebSocketSession implements RfqSession, RfqEventController {\n readonly #account: AccountIdentity;\n readonly #chainId: number;\n readonly #credentials: ApiKeyCreds;\n readonly #exchange: EvmAddress;\n readonly #headers: Record<string, string> | undefined;\n readonly #onClose: () => void;\n readonly #signer: Signer;\n readonly #url: string;\n readonly #connection = new WebSocketConnection();\n readonly #queue: Pushable<RfqEvent> = pushable({ objectMode: true });\n readonly #pending = new PendingResponses(ACK_TIMEOUT_MS);\n #closing: Promise<void> | undefined;\n #auth: PendingResponse<void> | undefined;\n\n constructor(options: RfqWebSocketSessionConfig) {\n this.#account = options.account;\n this.#chainId = options.chainId;\n this.#credentials = options.credentials;\n this.#exchange = options.exchange;\n this.#headers = options.headers;\n this.#onClose = options.onClose;\n this.#signer = options.signer;\n this.#url = options.url;\n }\n\n get closed(): boolean {\n return this.#closing !== undefined;\n }\n\n async connect(): Promise<void> {\n const auth = createPending<void>();\n this.#auth = auth;\n const authTimeout = setNonBlockingTimeout(() => {\n auth.reject(new TransportError('RFQ quoter authentication timed out.'));\n }, AUTH_TIMEOUT_MS);\n\n try {\n await this.#connection.connect({\n headers: this.#headers,\n onConnectionLost: (info) => this.#handleConnectionLost(info),\n onError: () => undefined,\n onMessage: (message) => this.#handleMessage(message),\n onOpen: () => this.#sendAuthMessage(),\n url: this.#url,\n });\n await auth.promise;\n } finally {\n clearTimeout(authTimeout);\n this.#auth = undefined;\n }\n }\n\n async #send(message: RfqQuoterOutboundMessage): Promise<void> {\n if (!this.#connection.send(message)) {\n throw new TransportError('RFQ quoter websocket is not open.');\n }\n }\n\n async close(): Promise<void> {\n if (this.#closing === undefined) {\n this.#closing = this.#shutdown();\n }\n await this.#closing;\n }\n\n [Symbol.asyncIterator](): AsyncIterator<RfqEvent> {\n return this.#queue[Symbol.asyncIterator]();\n }\n\n async #shutdown(): Promise<void> {\n const error = new TransportError('RFQ quoter websocket closed.');\n this.#failPending(error);\n this.#queue.end();\n await this.#connection.close();\n this.#onClose();\n }\n\n async #fail(error: Error): Promise<void> {\n if (this.#closing === undefined) {\n this.#closing = this.#shutdownWithError(error);\n }\n await this.#closing;\n }\n\n async #shutdownWithError(error: Error): Promise<void> {\n this.#failPending(error);\n this.#queue.end(error);\n await this.#connection.close();\n this.#onClose();\n }\n\n #failPending(error: Error): void {\n this.#auth?.reject(error);\n this.#pending.rejectAll(error);\n }\n\n #sendAuthMessage(): void {\n this.#connection.send(createAuthMessage(this.#account, this.#credentials));\n }\n\n #handleMessage(rawMessage: unknown): void {\n if (this.#closing !== undefined) return;\n\n const parsed = RfqQuoterInboundMessageSchema.safeParse(rawMessage);\n if (!parsed.success) return;\n\n const message = parsed.data;\n switch (message.type) {\n case 'auth':\n this.#handleAuthMessage(message);\n return;\n case 'quote_request':\n this.#queue.push(toQuoteRequestEvent(this, message));\n return;\n case 'quote_ack':\n this.#pending.resolve(quoteAckKey(message.rfqId), toQuoteAck(message));\n return;\n case 'quote_cancel_ack':\n this.#pending.resolve(\n quoteCancelAckKey(message.rfqId, message.quoteId),\n toQuoteCancelAck(message),\n );\n return;\n case 'confirmation_request':\n this.#queue.push(toConfirmationRequestEvent(this, message));\n return;\n case 'confirmation_ack':\n this.#pending.resolve(\n confirmationAckKey(message.rfqId, message.quoteId),\n toConfirmationAck(message),\n );\n return;\n case 'execution_update':\n this.#queue.push(toExecutionUpdateEvent(message));\n return;\n case 'trade':\n this.#queue.push(toTradeEvent(message));\n return;\n case 'rfq_error':\n this.#handleRfqError(message);\n return;\n }\n }\n\n #handleAuthMessage(message: { error?: string; success: boolean }): void {\n if (message.success === true) {\n this.#auth?.resolve(undefined);\n return;\n }\n this.#auth?.reject(\n new TransportError(`RFQ quoter authentication failed: ${message.error}`),\n );\n }\n\n #handleConnectionLost(info: WebSocketCloseInfo): void {\n void this.#fail(\n new ConnectionLostError('RFQ quoter connection lost.', info),\n );\n }\n\n // Unsupported RFQ_ERROR request types are ignored for forward compatibility.\n // Known outbound request errors without enough IDs are protocol failures.\n #handleRfqError(message: RfqErrorMessage): void {\n if (message.requestType === 'RFQ_QUOTE') {\n if (message.rfqId === undefined) {\n void this.#fail(new TransportError('Uncorrelated RFQ quoter error.'));\n return;\n }\n\n this.#pending.reject(\n quoteAckKey(message.rfqId),\n new RfqQuoteRejectedError(message.message, {\n code: message.code,\n errorId: message.errorId,\n rfqId: message.rfqId,\n }),\n );\n return;\n }\n\n if (message.requestType === 'RFQ_QUOTE_CANCEL') {\n if (message.rfqId === undefined || message.quoteId === undefined) {\n void this.#fail(new TransportError('Uncorrelated RFQ quoter error.'));\n return;\n }\n\n this.#pending.reject(\n quoteCancelAckKey(message.rfqId, message.quoteId),\n new RfqCancelQuoteRejectedError(message.message, {\n code: message.code,\n errorId: message.errorId,\n quoteId: message.quoteId,\n rfqId: message.rfqId,\n }),\n );\n return;\n }\n\n if (message.requestType === 'RFQ_CONFIRMATION_RESPONSE') {\n if (message.rfqId === undefined || message.quoteId === undefined) {\n void this.#fail(new TransportError('Uncorrelated RFQ quoter error.'));\n return;\n }\n\n this.#pending.reject(\n confirmationAckKey(message.rfqId, message.quoteId),\n new RfqConfirmationRejectedError(message.message, {\n code: message.code,\n errorId: message.errorId,\n quoteId: message.quoteId,\n rfqId: message.rfqId,\n }),\n );\n }\n }\n\n async quote(\n request: RfqQuoteRequest,\n response: RfqQuoteResponse,\n ): Promise<RfqQuoteReference> {\n const parsedResponse = parseRfqQuoteResponse(response);\n const quote = await createRfqQuote({\n account: this.#account,\n chainId: this.#chainId,\n exchange: this.#exchange,\n request,\n response: parsedResponse,\n signer: this.#signer,\n });\n const pending = this.#pending.waitFor<RfqQuoteReference>(\n quoteAckKey(request.rfqId),\n `Timed out waiting for RFQ quote acknowledgement for ${request.rfqId}.`,\n );\n try {\n await this.#send(createQuoteMessage(request, quote));\n return await pending;\n } catch (error) {\n this.#pending.remove(quoteAckKey(request.rfqId), pending);\n throw error;\n }\n }\n\n async cancelQuote(reference: RfqQuoteReference): Promise<RfqCancelQuoteAck> {\n const key = quoteCancelAckKey(reference.rfqId, reference.quoteId);\n const pending = this.#pending.waitFor<RfqCancelQuoteAck>(\n key,\n `Timed out waiting for RFQ quote cancellation acknowledgement for ${reference.rfqId}.`,\n );\n try {\n await this.#send(\n createQuoteCancelMessage(\n this.#account,\n reference.rfqId,\n reference.quoteId,\n ),\n );\n return await pending;\n } catch (error) {\n this.#pending.remove(key, pending);\n throw error;\n }\n }\n\n async respondToConfirmation(\n rfqId: RfqId,\n quoteId: RfqQuoteId,\n decision: RfqConfirmationDecision,\n ): Promise<RfqConfirmationAck> {\n const key = confirmationAckKey(rfqId, quoteId);\n const pending = this.#pending.waitFor<RfqConfirmationAck>(\n key,\n `Timed out waiting for RFQ confirmation acknowledgement for ${rfqId}.`,\n );\n try {\n await this.#send(\n createConfirmationResponseMessage(rfqId, quoteId, decision),\n );\n return await pending;\n } catch (error) {\n this.#pending.remove(key, pending);\n throw error;\n }\n }\n}\n\nfunction quoteAckKey(rfqId: RfqId): string {\n return `ACK_RFQ_QUOTE:${rfqId}`;\n}\n\nfunction quoteCancelAckKey(rfqId: RfqId, quoteId: RfqQuoteId): string {\n return `ACK_RFQ_QUOTE_CANCEL:${rfqId}:${quoteId}`;\n}\n\nfunction confirmationAckKey(rfqId: RfqId, quoteId: RfqQuoteId): string {\n return `ACK_RFQ_CONFIRMATION_RESPONSE:${rfqId}:${quoteId}`;\n}\n\ntype PendingResponse<T> = {\n promise: Promise<T>;\n reject(error: Error): void;\n resolve(value: T): void;\n};\n\nfunction createPending<T>(): PendingResponse<T> {\n let resolve!: (value: T) => void;\n let reject!: (error: Error) => void;\n const promise = new Promise<T>((resolvePromise, rejectPromise) => {\n resolve = resolvePromise;\n reject = rejectPromise;\n });\n return { promise, reject, resolve };\n}\n","import {\n type CommentsEvent,\n type CryptoPricesChainlinkTwapWindowSeconds,\n type CryptoPricesEvent,\n type EquityPricesEvent,\n RealtimeEventSchema,\n} from '@kuest/bindings/subscriptions';\nimport { invariant } from '@kuest/types';\nimport type {\n CommentsSubscription,\n CryptoPricesChainlinkTwapSubscription,\n CryptoPricesSubscription,\n EquityPricesSubscription,\n SubscriptionHandle,\n} from '../actions/subscriptions';\nimport { createSubscriptionHandle } from './handle';\nimport { RtdsWebSocketHeartbeat } from './heartbeat';\nimport {\n ReconnectScheduler,\n WebSocketConnection,\n type WebSocketConnectionResult,\n} from './lifecycle';\nimport {\n SubscriptionRegistry,\n type SubscriptionRegistryChange,\n type SubscriptionRegistryEntry,\n} from './registry';\nimport type { WebSocketSubscriptionManager } from './types';\n\ntype RtdsSpec =\n | CommentsSubscription\n | CryptoPricesSubscription\n | CryptoPricesChainlinkTwapSubscription\n | EquityPricesSubscription;\n\ntype RtdsEvent = CommentsEvent | CryptoPricesEvent | EquityPricesEvent;\n\ntype RtdsSubscriptionEntry = SubscriptionRegistryEntry<RtdsSpec, RtdsEvent>;\n\ntype RtdsServerSubscription = {\n key: string;\n topic: string;\n type: string;\n};\n\ntype RtdsServerState = Map<string, RtdsServerSubscription>;\n\nexport type RtdsWebSocketManagerOptions = {\n headers?: Record<string, string>;\n url: string;\n};\n\n/**\n * Realtime Data Service (RTDS) WebSocket manager.\n *\n * @deprecated Retained temporarily for legacy price and comment streams.\n *\n * Implements {@link WebSocketSubscriptionManager} for the comments, crypto prices, and\n * equity prices topics multiplexed over a single shared upstream socket\n * opened lazily on the first subscribe.\n */\nexport class RtdsWebSocketManager\n implements WebSocketSubscriptionManager<RtdsSpec, RtdsEvent>\n{\n readonly #headers: Record<string, string> | undefined;\n readonly #url: string;\n #closing: Promise<void> | undefined;\n readonly #connection = new WebSocketConnection({\n heartbeat: new RtdsWebSocketHeartbeat(),\n });\n readonly #reconnectScheduler = new ReconnectScheduler();\n readonly #subscriptions = new SubscriptionRegistry<\n RtdsSpec,\n RtdsEvent,\n RtdsServerState\n >({ deriveServerState: deriveRtdsServerState });\n\n constructor(options: RtdsWebSocketManagerOptions) {\n this.#headers = options.headers;\n this.#url = options.url;\n }\n\n async subscribe(\n subscription: RtdsSpec,\n ): Promise<SubscriptionHandle<RtdsEvent>> {\n const { change, entry } = this.#subscriptions.add(subscription, {\n matches: matcherFor(subscription),\n });\n await this.#registerSubscriber(entry, change);\n return createSubscriptionHandle(entry.subscriber.queue, () =>\n this.#closeSubscriber(entry),\n );\n }\n\n // Subscription handle lifecycle.\n\n async #registerSubscriber(\n entry: RtdsSubscriptionEntry,\n change: SubscriptionRegistryChange<RtdsServerState>,\n ): Promise<void> {\n try {\n const connection = await this.#connect();\n if (connection.reusedOpenSocket) {\n const { before, after } = change;\n const subscriptionsToOpen = serverSubscriptionsAdded(before, after);\n this.#sendSubscribeFrame(subscriptionsToOpen);\n }\n } catch (error) {\n await this.#closeSubscriber(entry);\n throw error;\n }\n }\n\n async #closeSubscriber(entry: RtdsSubscriptionEntry): Promise<void> {\n const { before, after } = this.#subscriptions.remove(entry);\n const subscriptionsToClose = serverSubscriptionsRemoved(before, after);\n this.#sendUnsubscribeFrame(subscriptionsToClose);\n if (!this.#subscriptions.hasActiveSubscriptions()) {\n await this.close();\n }\n }\n\n // Socket lifecycle.\n\n async close(): Promise<void> {\n if (this.#closing === undefined) {\n this.#closing = this.#shutdown().finally(() => {\n this.#closing = undefined;\n });\n }\n await this.#closing;\n }\n\n async #shutdown(): Promise<void> {\n this.#reconnectScheduler.stop();\n this.#subscriptions.endAll();\n\n await this.#connection.close();\n }\n\n #connect(): Promise<WebSocketConnectionResult> {\n return this.#connection.connect({\n onConnectionLost: () => this.#onConnectionLost(),\n onError: () => this.#onConnectionError(),\n onMessage: (message) => this.#onConnectionMessage(message),\n onOpen: () => this.#onConnectionOpen(),\n headers: this.#headers,\n url: this.#url,\n });\n }\n\n #onConnectionOpen(): void {\n this.#reconnectScheduler.resetBackoff();\n this.#resubscribeActiveServerEntries();\n }\n\n #onConnectionMessage(message: unknown): void {\n const parsed = RealtimeEventSchema.safeParse(message);\n if (!parsed.success) return;\n this.#subscriptions.dispatch(parsed.data);\n }\n\n #onConnectionLost(): void {\n if (this.#subscriptions.hasActiveSubscriptions()) {\n this.#scheduleReconnect();\n }\n }\n\n #onConnectionError(): void {\n // Browser WebSockets report most failures as an error followed by close.\n // Keep iterators alive here so the close path can reconnect active handles.\n }\n\n // RTDS subscribe/unsubscribe frames.\n\n #resubscribeActiveServerEntries(): void {\n this.#sendSubscribeFrame(\n Array.from(this.#subscriptions.serverState().values()),\n );\n }\n\n #sendSubscribeFrame(subscriptions: readonly RtdsServerSubscription[]): void {\n if (subscriptions.length === 0) return;\n this.#connection.send(buildSubscribeMessage(subscriptions));\n }\n\n #sendUnsubscribeFrame(\n subscriptions: readonly RtdsServerSubscription[],\n ): void {\n if (subscriptions.length === 0) return;\n this.#connection.send(buildUnsubscribeMessage(subscriptions));\n }\n\n #scheduleReconnect(): void {\n this.#reconnectScheduler.schedule({\n reconnect: () => this.#connect(),\n shouldReconnect: () => this.#subscriptions.hasActiveSubscriptions(),\n });\n }\n}\n\nfunction serverSubscriptionsAdded(\n before: ReadonlyMap<string, RtdsServerSubscription>,\n after: ReadonlyMap<string, RtdsServerSubscription>,\n): RtdsServerSubscription[] {\n return Array.from(after).flatMap(([key, subscription]) =>\n before.has(key) ? [] : [subscription],\n );\n}\n\nfunction serverSubscriptionsRemoved(\n before: ReadonlyMap<string, RtdsServerSubscription>,\n after: ReadonlyMap<string, RtdsServerSubscription>,\n): RtdsServerSubscription[] {\n return Array.from(before).flatMap(([key, subscription]) =>\n after.has(key) ? [] : [subscription],\n );\n}\n\nfunction deriveRtdsServerState(\n entries: Iterable<RtdsSubscriptionEntry>,\n): RtdsServerState {\n const activeByKey = new Map<string, RtdsServerSubscription>();\n for (const { subscription } of entries) {\n for (const serverSubscription of serverSubscriptionsFor(subscription)) {\n if (!activeByKey.has(serverSubscription.key)) {\n activeByKey.set(serverSubscription.key, serverSubscription);\n }\n }\n }\n return activeByKey;\n}\n\nfunction buildSubscribeMessage(\n subscriptions: readonly RtdsServerSubscription[],\n): unknown {\n return {\n action: 'subscribe',\n subscriptions: subscriptions.map(({ topic, type }) => ({ topic, type })),\n };\n}\n\nfunction buildUnsubscribeMessage(\n subscriptions: readonly RtdsServerSubscription[],\n): unknown {\n return {\n action: 'unsubscribe',\n subscriptions: subscriptions.map(({ topic, type }) => ({ topic, type })),\n };\n}\n\nfunction serverSubscriptionsFor(\n subscription: RtdsSpec,\n): RtdsServerSubscription[] {\n switch (subscription.topic) {\n case 'comments':\n // RTDS tracks subscription state per (topic, type): different comment\n // event types coexist independently on the same socket, so one entry\n // per requested type. No server-side filters — any narrowing by\n // parentEntityID/parentEntityType happens client-side via matcherFor.\n return (subscription.types ?? ['comment_created']).map((type) =>\n serverSubscription('comments', type),\n );\n case 'prices.crypto.binance':\n // Subscribe broadly and filter client-side. Sending a second subscribe\n // frame with a different `filters` value on the same socket causes the\n // server to replace the prior subscription rather than add one, so\n // multiple subscribers on the same manager cannot share a socket while\n // using server-side filters. See docs/api-boundary-notes.md.\n return [serverSubscription('crypto_prices', 'update')];\n case 'prices.crypto.chainlink':\n // RTDS tracks one filter per topic per connection, so a second subscribe\n // with a different filter replaces the first. Subscribe broadly and\n // filter client-side — see docs/api-boundary-notes.md.\n return [serverSubscription('crypto_prices_chainlink', 'update')];\n case 'prices.crypto.chainlink.twap':\n // Each TWAP window is a distinct RTDS topic. Subscribe broadly within\n // the requested window and narrow symbols client-side so subscribers for\n // the same window can safely share a socket.\n return [\n serverSubscription(\n twapServerTopic(subscription.windowSeconds),\n 'update',\n ),\n ];\n case 'prices.equity.pyth':\n // Same per-topic replace-on-resubscribe constraint as crypto_prices. A\n // single unfiltered subscribe covers every active equity symbol; the\n // client-side matcher narrows to the caller's requested symbol.\n return [serverSubscription('equity_prices', 'update')];\n default: {\n const neverSpec: never = subscription;\n invariant(false, `Unknown RTDS topic: ${String(neverSpec)}`);\n }\n }\n}\n\nfunction twapServerTopic(\n windowSeconds: CryptoPricesChainlinkTwapWindowSeconds,\n): string {\n switch (windowSeconds) {\n case 30:\n return 'crypto_prices_twap_thirty';\n case 60:\n return 'crypto_prices_twap_sixty';\n default: {\n const neverWindow: never = windowSeconds;\n invariant(false, `Unknown TWAP window: ${String(neverWindow)}`);\n }\n }\n}\n\nfunction serverSubscription(\n topic: string,\n type: string,\n): RtdsServerSubscription {\n return {\n key: `${topic}:${type}`,\n topic,\n type,\n };\n}\n\nfunction matcherFor(subscription: RtdsSpec): (event: RtdsEvent) => boolean {\n switch (subscription.topic) {\n case 'comments':\n // All `comments` narrowing happens client-side because the RTDS server\n // uses opaque substring matching on `filters` rather than structured\n // fields. When the caller sets `parentEntityId` or `parentEntityType`,\n // reaction events are dropped: their payloads carry only `commentID`,\n // not the parent context, so we can't verify the filter on them. Rule:\n // if a filter can't be verified on an event, the event doesn't match.\n // See docs/api-boundary-notes.md.\n return (event) => {\n if (event.topic !== 'comments') return false;\n if (\n subscription.types !== undefined &&\n subscription.types.length > 0 &&\n !subscription.types.includes(event.type)\n ) {\n return false;\n }\n const hasParentFilter =\n subscription.parentEntityId !== undefined ||\n subscription.parentEntityType !== undefined;\n if (hasParentFilter) {\n const carriesParentContext =\n event.type === 'comment_created' ||\n event.type === 'comment_removed';\n if (!carriesParentContext) return false;\n if (\n subscription.parentEntityId !== undefined &&\n event.payload.parentEntityID !== subscription.parentEntityId\n ) {\n return false;\n }\n if (\n subscription.parentEntityType !== undefined &&\n event.payload.parentEntityType !== subscription.parentEntityType\n ) {\n return false;\n }\n }\n return true;\n };\n case 'prices.crypto.binance':\n return (event) =>\n event.topic === 'prices.crypto.binance' &&\n (subscription.symbols === undefined ||\n subscription.symbols.length === 0 ||\n subscription.symbols.includes(event.payload.symbol));\n case 'prices.crypto.chainlink':\n return (event) =>\n event.topic === 'prices.crypto.chainlink' &&\n (subscription.symbols === undefined ||\n subscription.symbols.length === 0 ||\n subscription.symbols.includes(event.payload.symbol));\n case 'prices.crypto.chainlink.twap':\n return (event) =>\n event.topic === 'prices.crypto.chainlink.twap' &&\n event.payload.windowSeconds === subscription.windowSeconds &&\n (subscription.symbols === undefined ||\n subscription.symbols.length === 0 ||\n subscription.symbols.includes(event.payload.symbol));\n case 'prices.equity.pyth':\n // RTDS emits every event kind for a topic regardless of the `type` value\n // in the subscribe frame, so the caller's `types` filter must be\n // enforced client-side here.\n return (event) =>\n event.topic === 'prices.equity.pyth' &&\n event.payload.symbol.toLowerCase() ===\n subscription.symbol.toLowerCase() &&\n (subscription.types === undefined ||\n subscription.types.length === 0 ||\n subscription.types.includes(event.type));\n default: {\n const neverSpec: never = subscription;\n invariant(false, `Unknown RTDS topic: ${String(neverSpec)}`);\n }\n }\n}\n","import {\n type SportsEvent,\n SportsResultEventSchema,\n} from '@kuest/bindings/subscriptions';\nimport type {\n SportsSubscription,\n SubscriptionHandle,\n} from '../actions/subscriptions';\nimport { createSubscriptionHandle } from './handle';\nimport { SportsWebSocketHeartbeat } from './heartbeat';\nimport {\n ReconnectScheduler,\n WebSocketConnection,\n type WebSocketConnectionResult,\n} from './lifecycle';\nimport {\n SubscriptionRegistry,\n type SubscriptionRegistryEntry,\n} from './registry';\nimport type { WebSocketSubscriptionManager } from './types';\n\ntype SportsSubscriptionEntry = SubscriptionRegistryEntry<\n SportsSubscription,\n SportsEvent\n>;\n\nexport type SportsWebSocketManagerOptions = {\n headers?: Record<string, string>;\n url: string;\n};\n\n/**\n * Sports WebSocket manager.\n *\n * The sports stream starts sending events immediately after connection and does\n * not require a subscribe frame. The server sends `ping`; clients must reply\n * with `pong` to keep the socket alive.\n */\nexport class SportsWebSocketManager\n implements WebSocketSubscriptionManager<SportsSubscription, SportsEvent>\n{\n readonly #headers: Record<string, string> | undefined;\n readonly #url: string;\n #closing: Promise<void> | undefined;\n readonly #connection = new WebSocketConnection({\n heartbeat: new SportsWebSocketHeartbeat(),\n });\n readonly #reconnectScheduler = new ReconnectScheduler();\n readonly #subscriptions = new SubscriptionRegistry<\n SportsSubscription,\n SportsEvent\n >();\n\n constructor(options: SportsWebSocketManagerOptions) {\n this.#headers = options.headers;\n this.#url = options.url;\n }\n\n async subscribe(\n subscription: SportsSubscription,\n ): Promise<SubscriptionHandle<SportsEvent>> {\n const { entry } = this.#subscriptions.add(subscription);\n\n await this.#registerSubscriber(entry);\n return createSubscriptionHandle(entry.subscriber.queue, () =>\n this.#closeSubscriber(entry),\n );\n }\n\n // Subscription handle lifecycle.\n\n async #registerSubscriber(entry: SportsSubscriptionEntry): Promise<void> {\n try {\n await this.#connect();\n } catch (error) {\n await this.#closeSubscriber(entry);\n throw error;\n }\n }\n\n async #closeSubscriber(entry: SportsSubscriptionEntry): Promise<void> {\n this.#subscriptions.remove(entry);\n\n if (!this.#subscriptions.hasActiveSubscriptions()) {\n await this.close();\n }\n }\n\n // Socket lifecycle.\n\n async close(): Promise<void> {\n if (this.#closing === undefined) {\n this.#closing = this.#shutdown().finally(() => {\n this.#closing = undefined;\n });\n }\n await this.#closing;\n }\n\n async #shutdown(): Promise<void> {\n this.#reconnectScheduler.stop();\n this.#subscriptions.endAll();\n\n await this.#connection.close();\n }\n\n #connect(): Promise<WebSocketConnectionResult> {\n return this.#connection.connect({\n onConnectionLost: () => this.#onConnectionLost(),\n onError: () => this.#onConnectionError(),\n onMessage: (message) => this.#onConnectionMessage(message),\n onOpen: () => this.#onConnectionOpen(),\n headers: this.#headers,\n url: this.#url,\n });\n }\n\n #onConnectionOpen(): void {\n this.#reconnectScheduler.resetBackoff();\n }\n\n #onConnectionMessage(message: unknown): void {\n const parsed = SportsResultEventSchema.safeParse(message);\n if (!parsed.success) return;\n this.#subscriptions.dispatch(parsed.data);\n }\n\n #onConnectionLost(): void {\n if (this.#subscriptions.hasActiveSubscriptions()) {\n this.#scheduleReconnect();\n }\n }\n\n #onConnectionError(): void {\n // Browser WebSockets report most failures as an error followed by close.\n // Keep iterators alive here so the close path can reconnect active handles.\n }\n\n #scheduleReconnect(): void {\n this.#reconnectScheduler.schedule({\n reconnect: () => this.#connect(),\n shouldReconnect: () => this.#subscriptions.hasActiveSubscriptions(),\n });\n }\n}\n","import { ApiKeySchema, EvmAddressSchema } from '@kuest/bindings';\nimport type { ApiKeyCreds } from '@kuest/bindings/clob';\nimport { WalletType } from '@kuest/bindings/gamma';\nimport {\n expectEvmAddress,\n expectEvmSignature,\n invariant,\n isSameEvmAddress,\n type Prettify,\n} from '@kuest/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 { createClientMetadata } from './client-metadata';\nimport {\n allActions,\n type PublicActions,\n type SecureActions,\n} from './decorators';\nimport { type EnvironmentConfig, production } from './environments';\nimport {\n CancelledSigningError,\n makeErrorGuard,\n RateLimitError,\n RequestRejectedError,\n SigningError,\n TimeoutError,\n TransactionFailedError,\n TransportError,\n UnexpectedResponseError,\n UserInputError,\n} from './errors';\nimport { buildHmacSignature } from './hmac';\nimport { parseUserInput } from './input';\nimport type { RateLimitUpdateListener } from './rate-limit';\nimport type { Fetch } from './request-options';\nimport { JsonRpcClient } from './rpc';\nimport type { ServiceRequest } from './ServiceClient';\nimport { ServiceClient } from './ServiceClient';\nimport { parseSiteConfig, type SiteConfig } from './site-config';\nimport type { ApiKeyAuthorization, Signer } from './types';\nimport type { AccountIdentity } from './wallet';\nimport {\n deriveBeaconDepositWalletAddress,\n deriveUupsDepositWalletAddress,\n resolveAccountIdentity,\n} from './wallet';\nimport {\n ClobMarketWebSocketManager,\n ClobUserWebSocketManager,\n PerpsSessionManager,\n PerpsSubscriptionManager,\n type PublicWebSocketManagers,\n RealtimeWebSocketManager,\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 fetch?: Fetch;\n /** @internal */\n apiKey?: ApiKeyAuthorization;\n /** @internal */\n environment: EnvironmentConfig;\n /** @internal */\n siteConfig: SiteConfig | undefined;\n /** @internal */\n onRateLimitUpdate?: RateLimitUpdateListener;\n /** @internal */\n predictions: ServiceClient;\n /** @internal */\n clob: ServiceClient;\n /** @internal */\n relayer: ServiceClient;\n /** @internal */\n rpc: JsonRpcClient;\n /** @internal */\n gamma: ServiceClient;\n /** @internal */\n data: ServiceClient;\n /** @internal */\n rfq: ServiceClient;\n /** @internal */\n perps: ServiceClient;\n /** @internal */\n webSockets: PublicWebSocketManagers;\n};\n\n// biome-ignore lint/complexity/noBannedTypes: intentional\nexport type ClientActions = {};\n\nexport type ClientDecorator<\n TPublicActions extends ClientActions = ClientActions,\n TSecureActions extends ClientActions = TPublicActions,\n> = {\n (client: BasePublicClient<ClientActions, ClientActions>): TPublicActions;\n (client: BaseSecureClient<ClientActions, ClientActions>): TSecureActions;\n};\n\ntype DecoratorPublicActions<TDecorator extends ClientDecorator> =\n TDecorator extends ClientDecorator<\n infer TPublicActions,\n infer _TSecureActions\n >\n ? TPublicActions\n : never;\n\ntype DecoratorSecureActions<TDecorator extends ClientDecorator> =\n TDecorator extends ClientDecorator<\n infer _TPublicActions,\n infer TSecureActions\n >\n ? TSecureActions\n : never;\n\nabstract class AbstractClient<TContext extends PublicContext> {\n // Keep the backing context off the public object shape so accidental\n // client logs do not print secure credentials.\n readonly #context: TContext;\n readonly #decorators: ClientDecorator[];\n\n protected get context(): TContext {\n return this.#context;\n }\n\n protected get decorators(): readonly ClientDecorator[] {\n return this.#decorators;\n }\n\n /** @internal */\n get environment(): EnvironmentConfig {\n return this.context.environment;\n }\n\n /** @internal Public operator settings supplied explicitly by the caller. */\n get siteConfig(): SiteConfig | undefined {\n return this.context.siteConfig;\n }\n\n /**\n * Service client for prediction requests using the configured endpoint.\n * Requests return promises with parsed response data.\n *\n * @experimental Upstream-only service, unconfigured for SDK. Breaking changes may occur in any release, including patch releases.\n */\n get predictions(): ServiceClient {\n return this.context.predictions;\n }\n\n /** @internal */\n get clob(): ServiceClient {\n return this.context.clob;\n }\n\n /** @internal */\n get relayer(): ServiceClient {\n return this.context.relayer;\n }\n\n /** @internal */\n get rpc(): JsonRpcClient {\n return this.context.rpc;\n }\n\n /** @internal */\n get gamma(): ServiceClient {\n return this.context.gamma;\n }\n\n /** @internal */\n get data(): ServiceClient {\n return this.context.data;\n }\n\n /** @internal */\n get rfq(): ServiceClient {\n return this.context.rfq;\n }\n\n /** @internal */\n get perps(): ServiceClient {\n return this.context.perps;\n }\n\n /** @internal Shared managers for realtime subscriptions. */\n get webSockets(): PublicWebSocketManagers {\n return this.context.webSockets;\n }\n\n /** @internal */\n get supportsGasless(): boolean {\n return this.context.apiKey?.supportGasless ?? false;\n }\n\n /** @internal */\n get hasBuilderApiKey(): boolean {\n return this.context.apiKey?.isBuilderKey ?? false;\n }\n\n constructor(context: TContext) {\n this.#context = context;\n this.#decorators = [];\n }\n\n protected async resolveClobHeaders(\n request: ServiceRequest,\n ): Promise<HeadersInit> {\n if (this.context.apiKey?.isBuilderKey) {\n return this.context.apiKey.authorize(request, {\n fetch: this.context.fetch,\n signal: request.signal,\n });\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 fetch: this.context.fetch,\n signal: request.signal,\n });\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 fetch?: Fetch;\n environment: EnvironmentConfig;\n siteConfig?: SiteConfig;\n apiKey?: ApiKeyAuthorization;\n onRateLimitUpdate?: RateLimitUpdateListener;\n};\n\n// Public and secure clients share one predictions endpoint configuration.\nfunction createPredictionsService(config: PublicClientConfig): ServiceClient {\n const metadata = createClientMetadata();\n return new ServiceClient({\n fetch: config.fetch,\n retryMutations: false,\n headers: config.environment.predictions.headers,\n root: config.environment.predictions.rest,\n resolveHeaders: async () => ({ KUEST_CLIENT: metadata }),\n });\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 siteConfig: config.siteConfig,\n fetch: config.fetch,\n onRateLimitUpdate: config.onRateLimitUpdate,\n predictions: createPredictionsService(config),\n data: new ServiceClient({\n fetch: config.fetch,\n headers: config.environment.data.headers,\n root: config.environment.data.rest,\n }),\n gamma: new ServiceClient({\n fetch: config.fetch,\n headers: config.environment.gamma.headers,\n root: config.environment.gamma.rest,\n }),\n clob: new ServiceClient({\n fetch: config.fetch,\n headers: config.environment.clob.headers,\n onRateLimitUpdate: config.onRateLimitUpdate,\n root: config.environment.clob.rest,\n resolveHeaders: (request) => this.resolveClobHeaders(request),\n }),\n relayer: new ServiceClient({\n fetch: config.fetch,\n headers: config.environment.relayer.headers,\n root: config.environment.relayer.rest,\n resolveHeaders: (request) => this.resolveRelayerHeaders(request),\n }),\n rfq: new ServiceClient({\n fetch: config.fetch,\n headers: config.environment.combos.headers,\n root: config.environment.combos.rest,\n }),\n perps: new ServiceClient({\n fetch: config.fetch,\n headers: config.environment.perps.headers,\n root: config.environment.perps.rest,\n }),\n rpc: new JsonRpcClient({\n url: config.environment.rpc,\n fetch: config.fetch,\n }),\n webSockets: {\n clobMarket: new ClobMarketWebSocketManager({\n headers: config.environment.clob.market.headers,\n url: config.environment.clob.market.ws,\n }),\n sports: new SportsWebSocketManager({\n headers: config.environment.sports.headers,\n url: config.environment.sports.ws,\n }),\n rtds: new RtdsWebSocketManager({\n headers: config.environment.rtds.headers,\n url: config.environment.rtds.ws,\n }),\n perpsSubscriptions: new PerpsSubscriptionManager({\n headers: config.environment.perps.headers,\n url: config.environment.perps.ws,\n }),\n },\n });\n }\n\n /**\n * Use this to narrow a {@link Client} union to {@link SecureClient}.\n *\n * @example\n * ```ts\n * if (client.isSecureClient()) {\n * client.credentials; // SecureClient\n * }\n * ```\n */\n isSecureClient(): this is BaseSecureClient<TPublicActions, TSecureActions> {\n return false;\n }\n\n /**\n * Use this to narrow a {@link Client} union to {@link PublicClient}.\n *\n * @example\n * ```ts\n * if (client.isPublicClient()) {\n * client.closeSubscriptions(); // PublicClient\n * }\n * ```\n */\n isPublicClient(): this is BasePublicClient<TPublicActions, TSecureActions> {\n return true;\n }\n\n /**\n * Closes all active realtime subscriptions owned by this client.\n *\n * @remarks\n * This ends active subscription iterators and closes shared websocket\n * connections. It does not affect authentication or other client state.\n *\n * @example\n * ```ts\n * await client.closeSubscriptions();\n * ```\n */\n async closeSubscriptions(): Promise<void> {\n await Promise.all([\n this.webSockets.clobMarket.close(),\n this.webSockets.rtds.close(),\n this.webSockets.sports.close(),\n this.webSockets.perpsSubscriptions.close(),\n ]).then(() => undefined);\n }\n\n /**\n * Returns a client typed with the methods contributed by the decorator.\n */\n extend<TDecorator extends ClientDecorator>(\n decorator: TDecorator,\n ): PublicClient<\n Prettify<TPublicActions & DecoratorPublicActions<TDecorator>>,\n Prettify<TSecureActions & DecoratorSecureActions<TDecorator>>\n > {\n this.rememberDecorator(decorator);\n Object.assign(this, decorator(this));\n return this as unknown as PublicClient<\n Prettify<TPublicActions & DecoratorPublicActions<TDecorator>>,\n Prettify<TSecureActions & DecoratorSecureActions<TDecorator>>\n >;\n }\n\n /**\n * Begins an authentication workflow that produces a {@link SecureClient}.\n *\n * @remarks\n * This is a low-level method for building wallet-interactive workflows. Most\n * applications should use {@link createSecureClient} instead.\n *\n * @internal\n */\n beginAuthentication(\n request: BeginAuthenticationRequest,\n signer: Signer,\n ): Promise<\n AuthenticationWorkflow<SecureClient<TPublicActions, TSecureActions>>\n > {\n const params = parseUserInput(request, BeginAuthenticationRequestSchema);\n\n return Promise.resolve(\n async function* (\n this: PublicClient<TPublicActions, TSecureActions>,\n ): AuthenticationWorkflow<SecureClient<TPublicActions, TSecureActions>> {\n const timestamp = Math.floor(Date.now() / 1000);\n const nonce = params?.nonce ?? 0;\n const signerAddress = expectEvmAddress(yield requestAddress());\n const wallet = expectEvmAddress(params.wallet);\n const identity = resolveAccountIdentity(\n this.environment,\n signerAddress,\n wallet,\n );\n\n if (params.credentials !== undefined) {\n const client = this.#createSecureClient(\n params.credentials,\n identity,\n signer,\n );\n\n try {\n const apiKeys = await fetchApiKeys(client);\n if (apiKeys.includes(params.credentials.key)) {\n return client;\n }\n } catch (error) {\n if (\n !(error instanceof RequestRejectedError) ||\n error.status !== 401\n ) {\n throw error;\n }\n }\n }\n\n const signature = yield {\n kind: 'signAuthMessage',\n payload: createApiKeyAuthTypedDataPayload({\n address: signerAddress,\n chainId: this.environment.chainId,\n nonce,\n timestamp,\n }),\n };\n const credentials = await createOrDeriveApiKey(this, {\n address: signerAddress,\n nonce,\n signature: expectEvmSignature(signature),\n timestamp,\n });\n\n return this.#createSecureClient(credentials, identity, signer);\n }.call(this as unknown as PublicClient<TPublicActions, TSecureActions>),\n );\n }\n\n #createSecureClient(\n credentials: ApiKeyCreds,\n account: AccountIdentity,\n signer: Signer,\n ): SecureClient<TPublicActions, TSecureActions> {\n const client = new BaseSecureClient({\n account: account,\n apiKey: this.context.apiKey,\n credentials,\n environment: this.environment,\n siteConfig: this.siteConfig,\n onRateLimitUpdate: this.context.onRateLimitUpdate,\n fetch: this.context.fetch,\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 const realtime = new RealtimeWebSocketManager({\n url: config.environment.realtime.ws,\n headers: config.environment.realtime.headers,\n credentials: config.credentials,\n });\n super({\n account: config.account,\n credentials: config.credentials,\n apiKey: config.apiKey,\n environment: config.environment,\n siteConfig: config.siteConfig,\n fetch: config.fetch,\n onRateLimitUpdate: config.onRateLimitUpdate,\n signer: config.signer,\n predictions: createPredictionsService(config),\n clob: new ServiceClient({\n fetch: config.fetch,\n headers: config.environment.clob.headers,\n onRateLimitUpdate: config.onRateLimitUpdate,\n root: config.environment.clob.rest,\n resolveHeaders: (request) => this.resolveClobHeaders(request),\n }),\n relayer: new ServiceClient({\n fetch: config.fetch,\n headers: config.environment.relayer.headers,\n root: config.environment.relayer.rest,\n resolveHeaders: (request) => this.resolveRelayerHeaders(request),\n }),\n rpc: new JsonRpcClient({\n url: config.environment.rpc,\n fetch: config.fetch,\n }),\n gamma: new ServiceClient({\n fetch: config.fetch,\n headers: config.environment.gamma.headers,\n root: config.environment.gamma.rest,\n }),\n data: new ServiceClient({\n fetch: config.fetch,\n headers: config.environment.data.headers,\n root: config.environment.data.rest,\n }),\n rfq: new ServiceClient({\n fetch: config.fetch,\n headers: config.environment.combos.headers,\n root: config.environment.combos.rest,\n }),\n perps: new ServiceClient({\n fetch: config.fetch,\n headers: config.environment.perps.headers,\n root: config.environment.perps.rest,\n }),\n secureClob: new ServiceClient({\n fetch: config.fetch,\n headers: config.environment.clob.headers,\n onRateLimitUpdate: config.onRateLimitUpdate,\n resolveHeaders: async (request) => ({\n ...(await this.resolveClobHeaders(request)),\n ...(await this.#createL2Headers(request)),\n }),\n root: config.environment.clob.rest,\n }),\n combos: new ServiceClient({\n fetch: config.fetch,\n headers: config.environment.combos.collateralReturn.headers,\n resolveHeaders: (request) => this.resolveRelayerHeaders(request),\n root: config.environment.combos.collateralReturn.rest,\n }),\n builderGateway: new ServiceClient({\n fetch: config.fetch,\n headers: config.environment.combos.builderGateway.headers,\n resolveHeaders: async (request) => ({\n ...(await this.#resolveBuilderGatewayHeaders(request)),\n ...(await this.#createL2Headers(request)),\n }),\n root: config.environment.combos.builderGateway.rest,\n }),\n webSockets: {\n clobMarket: new ClobMarketWebSocketManager({\n headers: config.environment.clob.market.headers,\n url: config.environment.clob.market.ws,\n }),\n clobUser: new ClobUserWebSocketManager({\n credentials: config.credentials,\n headers: config.environment.clob.user.headers,\n url: config.environment.clob.user.ws,\n }),\n rfqQuoter: new RfqQuoterWebSocketManager({\n account: config.account,\n chainId: config.environment.chainId,\n credentials: config.credentials,\n exchange: config.environment.contracts.exchangeV3,\n headers: config.environment.combos.headers,\n signer: config.signer,\n url: config.environment.combos.ws,\n }),\n sports: new SportsWebSocketManager({\n headers: config.environment.sports.headers,\n url: config.environment.sports.ws,\n }),\n realtime,\n rtds: new RtdsWebSocketManager({\n headers: config.environment.rtds.headers,\n url: config.environment.rtds.ws,\n }),\n perpsSubscriptions: new PerpsSubscriptionManager({\n headers: config.environment.perps.headers,\n url: config.environment.perps.ws,\n }),\n perpsSession: new PerpsSessionManager({\n fetch: config.fetch,\n chainId: config.environment.chainId,\n headers: config.environment.perps.headers,\n restUrl: config.environment.perps.rest,\n wsUrl: config.environment.perps.ws,\n }),\n },\n });\n }\n\n /**\n * API credentials for the authenticated session.\n *\n * @remarks\n * These credentials are sensitive. Store them securely if you want to create\n * another secure client later without requiring a new authentication signature\n * while the credentials remain valid.\n */\n get credentials(): ApiKeyCreds {\n return this.context.credentials;\n }\n\n /**\n * The authenticated account identity associated with this client, including the signer and wallet addresses and wallet type.\n */\n get account(): AccountIdentity {\n return this.context.account;\n }\n\n /** @internal */\n get signer(): Signer {\n return this.context.signer;\n }\n\n /** @internal */\n get secureClob(): ServiceClient {\n return this.context.secureClob;\n }\n\n /** @internal */\n get combos(): ServiceClient {\n return this.context.combos;\n }\n\n /** @internal */\n get builderGateway(): ServiceClient {\n return this.context.builderGateway;\n }\n\n /** @internal Shared managers for public and authenticated realtime subscriptions. */\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.realtime.close(),\n this.webSockets.rtds.close(),\n this.webSockets.sports.close(),\n this.webSockets.perpsSubscriptions.close(),\n this.webSockets.clobUser.close(),\n ]).then(() => undefined);\n }\n\n /**\n * Use this to narrow a {@link Client} union to {@link SecureClient}.\n *\n * @example\n * ```ts\n * if (client.isSecureClient()) {\n * client.credentials; // SecureClient\n * }\n * ```\n */\n isSecureClient(): this is BaseSecureClient<TPublicActions, TSecureActions> {\n return true;\n }\n\n /**\n * Use this to narrow a {@link Client} union to {@link PublicClient}.\n *\n * @example\n * ```ts\n * if (client.isPublicClient()) {\n * client.closeSubscriptions(); // PublicClient\n * }\n * ```\n */\n isPublicClient(): this is BasePublicClient<TPublicActions, TSecureActions> {\n return false;\n }\n\n /**\n * Returns a secure client typed with the methods contributed by the decorator.\n */\n extend<TDecorator extends ClientDecorator>(\n decorator: TDecorator,\n ): SecureClient<\n TPublicActions,\n Prettify<TSecureActions & DecoratorSecureActions<TDecorator>>\n > {\n this.rememberDecorator(decorator);\n Object.assign(this, decorator(this));\n\n return this as unknown as SecureClient<\n TPublicActions,\n Prettify<TSecureActions & DecoratorSecureActions<TDecorator>>\n >;\n }\n\n /**\n * Ends authentication for this client and returns a public client.\n *\n * @remarks\n * This revokes the current authenticated credential and invalidates the\n * current `SecureClient` instance.\n *\n * @example\n * ```ts\n * const publicClient = await secureClient.endAuthentication();\n * ```\n */\n async endAuthentication(): Promise<\n PublicClient<TPublicActions, TSecureActions>\n > {\n // Server-side revocation must not depend on local WebSocket cleanup.\n const closingSubscriptions = this.closeSubscriptions();\n const shuttingDownPerpsSessions = this.webSockets.perpsSession.shutdown();\n const shuttingDownRfqQuoter = this.webSockets.rfqQuoter.shutdown();\n const { apiKey, environment, onRateLimitUpdate, fetch } = this.context;\n\n try {\n await deleteApiKey(this);\n } finally {\n this.endAuthenticationLifecycle();\n await Promise.allSettled([\n closingSubscriptions,\n shuttingDownPerpsSessions,\n shuttingDownRfqQuoter,\n ]).then(() => undefined);\n }\n\n const client = new BasePublicClient({\n apiKey,\n environment,\n onRateLimitUpdate,\n fetch,\n });\n\n for (const decorator of this.decorators) {\n client.extend(decorator);\n }\n\n return client as PublicClient<TPublicActions, TSecureActions>;\n }\n\n // Builder gateway status reads authenticate with account headers only;\n // builder headers are required on the mutating requests.\n async #resolveBuilderGatewayHeaders(\n request: ServiceRequest,\n ): Promise<HeadersInit> {\n if (request.method !== 'GET' && this.context.apiKey?.isBuilderKey) {\n return this.context.apiKey.authorize(request, {\n fetch: this.context.fetch,\n signal: request.signal,\n });\n }\n return {};\n }\n\n async #createL2Headers(request: ServiceRequest): Promise<HeadersInit> {\n try {\n const timestamp = Math.floor(Date.now() / 1000);\n\n return {\n KUEST_ADDRESS: this.account.signer,\n KUEST_API_KEY: this.credentials.key,\n KUEST_PASSPHRASE: this.credentials.passphrase,\n KUEST_SIGNATURE: await buildHmacSignature(\n this.credentials.secret,\n timestamp,\n request.method,\n request.path,\n request.body,\n ),\n KUEST_TIMESTAMP: `${timestamp}`,\n };\n } catch (error) {\n throw SigningError.fromError(\n error,\n 'Could not sign the L2-authenticated request',\n );\n }\n }\n}\n\ntype SecureContext = PublicContext & {\n /** @internal */\n account: AccountIdentity;\n /** @internal */\n credentials: ApiKeyCreds;\n /** @internal */\n signer: Signer;\n /** @internal */\n secureClob: ServiceClient;\n /** @internal */\n combos: ServiceClient;\n /** @internal */\n builderGateway: ServiceClient;\n /** @internal */\n webSockets: SecureWebSocketManagers;\n};\n\ntype SecureClientConfig = PublicClientConfig & {\n account: AccountIdentity;\n credentials: ApiKeyCreds;\n signer: Signer;\n};\n\nexport type PublicClient<\n TPublicActions extends ClientActions = PublicActions,\n TSecureActions extends ClientActions = SecureActions,\n> = BasePublicClient<TPublicActions, TSecureActions> & TPublicActions;\n\nexport type SecureClient<\n TPublicActions extends ClientActions = PublicActions,\n TSecureActions extends ClientActions = SecureActions,\n> = BaseSecureClient<TPublicActions, TSecureActions> & TSecureActions;\n\nexport { BasePublicClient, BaseSecureClient };\n\nexport type BaseClient<\n TPublicActions extends ClientActions = ClientActions,\n TSecureActions extends ClientActions = TPublicActions,\n> =\n | BasePublicClient<TPublicActions, TSecureActions>\n | BaseSecureClient<TPublicActions, TSecureActions>;\n\nexport type Client<\n TPublicActions extends ClientActions = ClientActions,\n TSecureActions extends ClientActions = TPublicActions,\n> =\n | PublicClient<TPublicActions, TSecureActions>\n | SecureClient<TPublicActions, TSecureActions>;\n\nexport type PublicClientOptions = {\n /**\n * Fetch-compatible implementation for SDK-owned HTTP requests. Defaults to native fetch.\n *\n * @experimental This API may change in a breaking way in any release, including patch releases.\n */\n fetch?: Fetch;\n /**\n * The environment configuration used by the client.\n *\n * @defaultValue `production`\n */\n environment?: EnvironmentConfig;\n\n /** Optional public site settings. Node callers may use `loadSiteConfig()` from the `/node` entrypoint. */\n siteConfig?: SiteConfig;\n\n /**\n * Optional request authorization applied by the client when needed.\n */\n apiKey?: ApiKeyAuthorization;\n\n /**\n * Listener invoked whenever a response reports per-signer rate-limit state,\n * as order and cancellation responses do.\n *\n * @remarks\n * Use this to monitor remaining rate-limit capacity and warning-mode\n * signals, and adjust request patterns before requests are rejected.\n * Errors thrown by the listener and rejections from promises it returns are\n * ignored.\n */\n onRateLimitUpdate?: RateLimitUpdateListener;\n};\n\nexport type SecureClientOptions = PublicClientOptions & {\n /**\n * Wallet address to use as the account wallet.\n *\n * If omitted, the client uses the signer's deterministic Deposit Wallet as\n * the account wallet. Pass the signer address itself to explicitly trade as\n * an EOA account, or pass a supported Poly Deposit Wallet, Poly Safe, or Poly\n * Proxy wallet address to use that wallet as the account/funder.\n */\n wallet?: string;\n\n /**\n * Wallet-library adapter used to authenticate and complete wallet operations.\n */\n signer: Signer;\n} & (\n | {\n /**\n * Existing API credentials to reuse when they remain valid.\n */\n credentials?: ApiKeyCreds;\n nonce?: never;\n }\n | {\n credentials?: never;\n /**\n * Nonce used when creating or deriving fresh credentials.\n *\n * @defaultValue 0\n */\n nonce?: number;\n }\n );\n\n/**\n * Creates a new `PublicClient` instance.\n *\n * @example\n * ```ts\n * const client = createPublicClient();\n * ```\n */\nexport function createPublicClient(\n options: PublicClientOptions = {},\n): PublicClient<PublicActions, SecureActions> {\n return new BasePublicClient({\n environment: options.environment ?? production,\n siteConfig: options.siteConfig\n ? parseSiteConfig(options.siteConfig)\n : undefined,\n apiKey: options.apiKey,\n onRateLimitUpdate: options.onRateLimitUpdate,\n fetch: options.fetch,\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 siteConfig: options.siteConfig,\n apiKey: options.apiKey,\n onRateLimitUpdate: options.onRateLimitUpdate,\n fetch: options.fetch,\n });\n const wallet = await resolveRequestedWallet(client, options);\n\n const secureClient = await client\n .beginAuthentication(\n {\n wallet,\n credentials: options.credentials,\n nonce: options.nonce,\n },\n options.signer,\n )\n .then(authenticateWith(options.signer));\n\n if (secureClient.account.walletType === WalletType.EOA) {\n return secureClient;\n }\n\n const deployed = await isWalletDeployed(secureClient, {\n wallet: secureClient.account.wallet,\n type: secureClient.account.walletType,\n });\n\n if (deployed) {\n return secureClient;\n }\n\n if (secureClient.account.walletType === WalletType.DEPOSIT_WALLET) {\n await deployDefaultDepositWallet(secureClient);\n return secureClient;\n }\n\n throw new UserInputError(\n `Wallet ${secureClient.account.wallet} does not exist. Provide an existing wallet address, or omit wallet to use the default Deposit Wallet flow.`,\n );\n}\n\n/** Resolves the wallet address to authenticate as. */\nasync function resolveRequestedWallet(\n client: BasePublicClient,\n options: SecureClientOptions,\n): Promise<string> {\n if (options.wallet !== undefined) {\n return options.wallet;\n }\n\n const signerAddress = expectEvmAddress(await options.signer.getAddress());\n const legacyDepositWallet = deriveUupsDepositWalletAddress(\n signerAddress,\n client.environment.walletDerivation,\n );\n\n if (\n await isWalletDeployed(client, {\n wallet: legacyDepositWallet,\n type: WalletType.DEPOSIT_WALLET,\n })\n ) {\n return legacyDepositWallet;\n }\n\n return deriveBeaconDepositWalletAddress(\n signerAddress,\n client.environment.walletDerivation,\n );\n}\n\n/**\n * Deploys the signer's beacon Deposit Wallet for the secure client. The current\n * factory only deploys beacon wallets, so legacy UUPS wallets must already be\n * deployed and cannot be created through this path.\n */\nasync function deployDefaultDepositWallet(\n secureClient: SecureClient<PublicActions, SecureActions>,\n): Promise<void> {\n const currentDepositWallet = deriveBeaconDepositWalletAddress(\n secureClient.account.signer,\n secureClient.environment.walletDerivation,\n );\n\n if (!isSameEvmAddress(secureClient.account.wallet, currentDepositWallet)) {\n throw new UserInputError(\n `Wallet ${secureClient.account.wallet} does not match the expected Deposit Wallet ${currentDepositWallet} for this signer, nor a deployed wallet address.`,\n );\n }\n\n const handle = await deployDepositWallet(secureClient);\n await handle.wait();\n}\n"]}