@gala-chain/gswap-sdk 2.0.0 → 2.1.0-beta.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.
- package/README.md +8 -2
- package/dist/browser/classes/apply_results.js.map +1 -1
- package/dist/browser/classes/assets.js.map +1 -1
- package/dist/browser/classes/dex_fees.js +1 -1
- package/dist/browser/classes/dex_fees.js.map +1 -1
- package/dist/browser/classes/gateway.js +1 -1
- package/dist/browser/classes/gateway.js.map +1 -1
- package/dist/browser/classes/gdex_stream.js +1 -1
- package/dist/browser/classes/gdex_stream.js.map +1 -1
- package/dist/browser/classes/gswap.js +1 -1
- package/dist/browser/classes/gswap.js.map +1 -1
- package/dist/browser/classes/gswap_error_catalog.js +1 -1
- package/dist/browser/classes/gswap_error_catalog.js.map +1 -1
- package/dist/browser/classes/gswap_error_phase_table.js +1 -1
- package/dist/browser/classes/gswap_error_phase_table.js.map +1 -1
- package/dist/browser/classes/gswap_sdk_error.js +1 -1
- package/dist/browser/classes/gswap_sdk_error.js.map +1 -1
- package/dist/browser/classes/http_client.js.map +1 -1
- package/dist/browser/classes/leaderboard.js.map +1 -1
- package/dist/browser/classes/market.js.map +1 -1
- package/dist/browser/classes/onramper.js.map +1 -1
- package/dist/browser/classes/pending_swap_fate.js.map +1 -1
- package/dist/browser/classes/pending_swaps.js +1 -1
- package/dist/browser/classes/pending_swaps.js.map +1 -1
- package/dist/browser/classes/pools.js +1 -1
- package/dist/browser/classes/pools.js.map +1 -1
- package/dist/browser/classes/positions.js +1 -1
- package/dist/browser/classes/positions.js.map +1 -1
- package/dist/browser/classes/quoting.js +1 -1
- package/dist/browser/classes/quoting.js.map +1 -1
- package/dist/browser/classes/shadow_submit.js.map +1 -1
- package/dist/browser/classes/storage_adapters.js.map +1 -1
- package/dist/browser/classes/submitted_transaction.js +1 -1
- package/dist/browser/classes/submitted_transaction.js.map +1 -1
- package/dist/browser/classes/swaps.js +1 -1
- package/dist/browser/classes/swaps.js.map +1 -1
- package/dist/browser/classes/symbols.js +1 -1
- package/dist/browser/classes/symbols.js.map +1 -1
- package/dist/browser/types/env.js.map +1 -1
- package/dist/browser/types/fees.js.map +1 -1
- package/dist/browser/types/market.js.map +1 -1
- package/dist/browser/utils/chain_contract.js +2 -0
- package/dist/browser/utils/chain_contract.js.map +1 -0
- package/dist/browser/utils/classification.js.map +1 -1
- package/dist/browser/utils/confirmation_schedule.js.map +1 -1
- package/dist/browser/utils/confirmation_state.js.map +1 -1
- package/dist/browser/utils/debug.js.map +1 -1
- package/dist/browser/utils/dto_builders.js.map +1 -1
- package/dist/browser/utils/failure_classification.js +1 -1
- package/dist/browser/utils/failure_classification.js.map +1 -1
- package/dist/browser/utils/failure_guards.js +1 -1
- package/dist/browser/utils/failure_guards.js.map +1 -1
- package/dist/browser/utils/lenient.js.map +1 -1
- package/dist/browser/utils/ordering.js.map +1 -1
- package/dist/browser/utils/reconnection.js +1 -1
- package/dist/browser/utils/reconnection.js.map +1 -1
- package/dist/browser/utils/resolve_pre_send.js.map +1 -1
- package/dist/browser/utils/server_message.js.map +1 -1
- package/dist/browser/utils/shadow_errors.js.map +1 -1
- package/dist/browser/utils/submit_state.js.map +1 -1
- package/dist/browser/utils/tick_align.js.map +1 -1
- package/dist/browser/utils/tick_math.js.map +1 -1
- package/dist/browser/utils/tick_range.js.map +1 -1
- package/dist/browser/utils/ticks.js.map +1 -1
- package/dist/browser/utils/validation.js.map +1 -1
- package/dist/index.cjs +23 -6
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +13 -5
- package/dist/index.d.ts +13 -5
- package/dist/index.mjs +23 -6
- package/dist/index.mjs.map +1 -1
- package/package.json +3 -3
- /package/dist/browser/_virtual/{_@oxc-project_runtime@0.153.0 → _@oxc-project_runtime@0.154.0}/helpers/esm/defineProperty.js +0 -0
- /package/dist/browser/_virtual/{_@oxc-project_runtime@0.153.0 → _@oxc-project_runtime@0.154.0}/helpers/esm/toPrimitive.js +0 -0
- /package/dist/browser/_virtual/{_@oxc-project_runtime@0.153.0 → _@oxc-project_runtime@0.154.0}/helpers/esm/toPropertyKey.js +0 -0
- /package/dist/browser/_virtual/{_@oxc-project_runtime@0.153.0 → _@oxc-project_runtime@0.154.0}/helpers/esm/typeof.js +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"gdex_stream.js","names":["_defineProperty","GDEX_SUBPROTOCOL","LIQUIDITY_ACTIONS","isGdexLiquidityEvent","value","\"version\"","pool","\"poolHash\"","\"transactionId\"","\"action\"","\"owner\"","\"amount0\"","\"amount1\"","\"blockNumber\"","\"timestamp\"","GdexStreamError","message","code","data","readSubscriptionId","id","GdexStreamService","config","GSWAP_ENVIRONMENTS","ReconnectionBackoff","implementation","GSwapSDKError","socket","method","params","frame","\"params\"","timeout","reject","resolve","error","selector","ref","userRef","owner","tokenClassKey","opts","cb","filter","event","debugLog","opened","pending","errorMessage","subscriptionId","\"subscription\"","result","\"result\"","subscription","options","handle","serverId","delay","attempt","onResult","retryAfterMs","\"retryAfterMs\""],"sources":["../../../src/classes/gdex_stream.ts"],"sourcesContent":["import { GSWAP_ENVIRONMENTS } from '../types/env.js';\nimport { debugLog } from '../utils/debug.js';\nimport { userRef } from '../utils/validation.js';\nimport { ReconnectionBackoff } from '../utils/reconnection.js';\nimport { GSwapSDKError } from './gswap_sdk_error.js';\n\nconst GDEX_SUBPROTOCOL = 'gdex.jsonrpc.v1';\nconst RATE_LIMITED = -32003;\nconst MAX_RESUBSCRIBE_RATE_RETRIES = 5;\nconst WEBSOCKET_OPEN = 1;\n\n/** Options for {@link GdexStreamService}. */\nexport interface GdexStreamConfig {\n /** Stream endpoint. Defaults to production (`wss://dex-backend-prod1.defi.gala.com/ws`). */\n url?: string | undefined;\n /** Reconnect attempts after an unexpected close. Default 5. */\n reconnectAttempts?: number | undefined;\n /** Delay before the first reconnect attempt; doubles each attempt. Default 2000 ms. */\n reconnectDelayMs?: number | undefined;\n /** How long a request waits for its response. Default 15000 ms. */\n requestTimeoutMs?: number | undefined;\n /**\n * A standards-compatible WebSocket constructor. Required on Node.js older than 22, which has no\n * global `WebSocket` (pass the one from the `ws` package).\n */\n webSocketImpl?: unknown;\n /**\n * Presents `x-api-key` on the WebSocket upgrade request, which the swap backend uses to serve the\n * PRIVILEGED view (shadow swaps with the wallet unredacted). Without it, or with a wrong key, the\n * connection is simply public: the server never says whether a privileged mode exists.\n *\n * It must travel as an HTTP header, because the server reads no other credential, and a browser\n * `WebSocket` cannot set headers. So this option needs a constructor that accepts them as its\n * third argument (`{ headers }`): the `ws` package on Node.js, or React Native's built-in\n * `WebSocket`. It therefore REQUIRES `webSocketImpl` (the platform default is never assumed to\n * honor headers, and a key that is silently dropped would look like a working privileged\n * connection); the constructor throws otherwise. Use it from server-side code only: a key\n * shipped inside a browser or app bundle is not a secret. Browser clients stay public.\n */\n apiKey?: string | undefined;\n}\n\n/** The channels of the realtime stream. */\nexport type GdexChannel = 'pool' | 'balance' | 'poolCreated' | 'swap' | 'liquidity' | 'blocks';\n\n/** A pool named by its two token class keys (pipe form) and fee tier. */\nexport interface GdexPoolKey {\n token0ClassKey: string;\n token1ClassKey: string;\n fee: number;\n}\n\n/** A pool named either by its key or by its hash (`v2:<poolRef>` for a v2 pool). */\nexport type GdexPoolSelector = { pool: GdexPoolKey } | { poolHash: string };\n\n/** Options common to every subscription. */\nexport interface GdexSubscribeOptions {\n /** Send the current state right after the subscribe response. */\n snapshot?: boolean | undefined;\n /** Trim each event to these fields; identity and envelope fields always stay. */\n fields?: string[] | undefined;\n}\n\n/** Filters for {@link GdexStreamService.subscribeLiquidity}; all optional. */\nexport interface GdexLiquidityFilter {\n /** Only this pool, named by its key. */\n pool?: GdexPoolKey | undefined;\n /** Only this pool, named by its hash (`v2:<poolRef>` for a v2 pool). */\n poolHash?: string | undefined;\n /** Only events for this LP wallet (the position's owner). */\n owner?: string | undefined;\n /** Only this transaction. */\n transactionId?: string | undefined;\n /** Contract version filter. */\n version?: 'v1' | 'v2' | 'all' | undefined;\n}\n\n/** One committed add, remove or collect, as the `liquidity` channel reports it. */\nexport interface GdexLiquidityEvent {\n version: 'v1' | 'v2';\n pool: GdexPoolKey;\n poolHash: string;\n transactionId: string;\n /** `add`, `remove` or `collect`. */\n action: 'add' | 'remove' | 'collect';\n /** The position's owner (the LP wallet). */\n owner: string;\n /** v1: the position id. v2: the chain position key `<pool>|<tickLow>|<tickHigh>|<owner>`. */\n positionId?: string;\n tickLower?: number;\n tickUpper?: number;\n /** v2 only: the position's liquidity after the operation; `\"0\"` means it is closed. */\n liquidityAfter?: string;\n /** Principal moved: deposited by an add, withdrawn by a remove, `\"0\"` for a collect. */\n amount0: string;\n amount1: string;\n /** Fees paid out. v2: always present (`\"0\"` for an add). v1: present on a collect only. */\n fees0?: string;\n fees1?: string;\n /** v2 only. */\n token0Symbol?: string;\n token1Symbol?: string;\n blockNumber: number;\n timestamp: string;\n}\n\nconst LIQUIDITY_ACTIONS: readonly unknown[] = ['add', 'remove', 'collect'];\n\n/** Whether a stream payload carries every field of a {@link GdexLiquidityEvent}. */\nexport function isGdexLiquidityEvent(\n value: Record<string, unknown>,\n): value is Record<string, unknown> & GdexLiquidityEvent {\n const { pool } = value;\n return (\n (value['version'] === 'v1' || value['version'] === 'v2') &&\n typeof pool === 'object' &&\n pool !== null &&\n typeof value['poolHash'] === 'string' &&\n typeof value['transactionId'] === 'string' &&\n LIQUIDITY_ACTIONS.includes(value['action']) &&\n typeof value['owner'] === 'string' &&\n typeof value['amount0'] === 'string' &&\n typeof value['amount1'] === 'string' &&\n typeof value['blockNumber'] === 'number' &&\n typeof value['timestamp'] === 'string'\n );\n}\n\n/** A live subscription. */\nexport interface GdexSubscription {\n subscriptionId: string;\n unsubscribe(): Promise<void>;\n}\n\n/** A JSON-RPC error answered by the stream. */\nexport class GdexStreamError extends Error {\n /** The JSON-RPC error code. */\n readonly code: number;\n /** The error's optional `data` member, as the server sent it. */\n readonly data?: unknown;\n\n constructor(code: number, message: string, data?: unknown) {\n super(message);\n this.name = 'GdexStreamError';\n this.code = code;\n if (data !== undefined) this.data = data;\n }\n}\n\ninterface WebSocketLike {\n readonly readyState: number;\n send(data: string): void;\n close(code?: number, reason?: string): void;\n onopen: ((event: unknown) => void) | null;\n onmessage: ((event: { data: unknown }) => void) | null;\n onclose: ((event: { code?: number; reason?: string }) => void) | null;\n onerror: ((event: unknown) => void) | null;\n}\n\ninterface WebSocketConstructor {\n new (\n url: string,\n protocols?: string | string[],\n options?: { headers: Record<string, string> },\n ): WebSocketLike;\n}\n\ninterface PendingRequest {\n resolve(value: unknown): void;\n reject(error: Error): void;\n timeout: ReturnType<typeof setTimeout>;\n /**\n * Runs SYNCHRONOUSLY when the response frame is handled, before any frame that follows it in\n * the same read. Subscriptions register here: the server writes a snapshot right after the\n * subscribe response, and a runtime that delivers both frames without yielding to microtasks\n * (Node's `ws` does, for frames in one chunk) would otherwise drop the snapshot because the\n * awaiting caller has not registered the subscription yet.\n */\n onResult?: ((value: unknown) => void) | undefined;\n}\n\ntype EventCallback = (event: Record<string, unknown>) => void;\n\ninterface ActiveSubscription {\n serverId: string;\n readonly params: Record<string, unknown>;\n readonly callback: EventCallback;\n readonly handle: MutableGdexSubscription;\n active: boolean;\n}\n\ninterface MutableGdexSubscription extends GdexSubscription {\n subscriptionId: string;\n}\n\nfunction readSubscriptionId(value: unknown): string {\n const id =\n typeof value === 'object' && value !== null\n ? (value as { subscriptionId?: unknown }).subscriptionId\n : undefined;\n if (typeof id !== 'string') {\n throw new GdexStreamError(-32603, 'GDEX subscribe response is missing its subscriptionId');\n }\n return id;\n}\n\ninterface JsonRpcResponse {\n id?: unknown;\n method?: unknown;\n result?: unknown;\n error?: { code?: unknown; message?: unknown; data?: unknown };\n params?: unknown;\n}\n\n/**\n * Client for the gSwap realtime stream (gdex WebSocket Protocol v1): JSON-RPC 2.0 over one raw\n * WebSocket, with automatic reconnect and resubscribe.\n *\n * @example\n * ```typescript\n * const stream = new GdexStreamService();\n * await stream.connect();\n * await stream.subscribeLiquidity(event => console.log(event.action, event.owner), {\n * owner: 'client|618ae395c1c653111d3315be',\n * });\n * ```\n */\nexport class GdexStreamService {\n private readonly url: string;\n private readonly requestTimeoutMs: number;\n private readonly apiKey: string | undefined;\n private readonly webSocketConstructor: WebSocketConstructor;\n private readonly backoff: ReconnectionBackoff;\n private socket: WebSocketLike | undefined;\n private connectPromise: Promise<void> | undefined;\n private nextRequestId = 0;\n private readonly pending = new Map<number, PendingRequest>();\n private readonly subscriptionsByServerId = new Map<string, ActiveSubscription>();\n private readonly activeSubscriptions = new Set<ActiveSubscription>();\n private intentionalClose = false;\n private reconnecting = false;\n private reconnectTimer: ReturnType<typeof setTimeout> | undefined;\n private reconnectDelayResolve: (() => void) | undefined;\n\n constructor(config: GdexStreamConfig = {}) {\n this.url = config.url ?? GSWAP_ENVIRONMENTS.prod.dexBackendWsUrl;\n this.requestTimeoutMs = config.requestTimeoutMs ?? 15_000;\n this.backoff = new ReconnectionBackoff({\n maxAttempts: config.reconnectAttempts ?? 5,\n baseDelayMs: config.reconnectDelayMs ?? 2_000,\n });\n\n const implementation =\n config.webSocketImpl ?? (globalThis as { WebSocket?: unknown }).WebSocket;\n if (typeof implementation !== 'function') {\n throw new GSwapSDKError('STREAM_WEBSOCKET_UNAVAILABLE', {});\n }\n this.webSocketConstructor = implementation as WebSocketConstructor;\n if (config.apiKey !== undefined) {\n if (config.apiKey === '' || config.webSocketImpl === undefined) {\n throw new GSwapSDKError('STREAM_API_KEY_UNUSABLE', {});\n }\n this.apiKey = config.apiKey;\n }\n }\n\n /** Open the connection. Resolves at once when already connected. */\n connect(): Promise<void> {\n if (this.isConnected()) return Promise.resolve();\n if (this.connectPromise) return this.connectPromise;\n this.intentionalClose = false;\n this.clearReconnectTimer();\n this.connectPromise = this.openSocket();\n return this.connectPromise;\n }\n\n /** Close the connection and stop reconnecting. */\n disconnect(): void {\n this.intentionalClose = true;\n this.reconnecting = false;\n this.clearReconnectTimer();\n this.rejectPending(new GSwapSDKError('STREAM_DISCONNECTED', {}));\n const socket = this.socket;\n this.socket = undefined;\n this.connectPromise = undefined;\n socket?.close(1000, 'client disconnect');\n }\n\n /** `true` while the socket is open (false while connecting, reconnecting or after `disconnect()`). */\n isConnected(): boolean {\n return this.socket?.readyState === WEBSOCKET_OPEN;\n }\n\n /** Raw JSON-RPC escape hatch. */\n request<T = unknown>(method: string, params?: Record<string, unknown>): Promise<T> {\n return this.send<T>(method, params);\n }\n\n private send<T>(\n method: string,\n params: Record<string, unknown> | undefined,\n onResult?: (value: unknown) => void,\n ): Promise<T> {\n if (!this.isConnected() || !this.socket) {\n return Promise.reject(new GSwapSDKError('STREAM_NOT_CONNECTED', {}));\n }\n\n const id = ++this.nextRequestId;\n const frame: Record<string, unknown> = { jsonrpc: '2.0', id, method };\n if (params !== undefined) frame['params'] = params;\n\n return new Promise<T>((resolve, reject) => {\n const timeout = setTimeout(() => {\n this.pending.delete(id);\n reject(\n new GSwapSDKError('STREAM_REQUEST_TIMEOUT', { method, timeoutMs: this.requestTimeoutMs }),\n );\n }, this.requestTimeoutMs);\n this.pending.set(id, { resolve: (value) => resolve(value as T), reject, timeout, onResult });\n\n try {\n this.socket?.send(JSON.stringify(frame));\n } catch (error) {\n clearTimeout(timeout);\n this.pending.delete(id);\n reject(error instanceof Error ? error : new Error(String(error)));\n }\n });\n }\n\n /** `gdex_serverInfo`: the server's own description of itself, as it sends it. */\n serverInfo(): Promise<Record<string, unknown>> {\n return this.request('gdex_serverInfo');\n }\n\n /** `gdex_ping`: a round trip that answers `{ pong, serverTime }`. */\n ping(): Promise<{ pong: boolean; serverTime: string }> {\n return this.request('gdex_ping');\n }\n\n /** `gdex_getPool`: the current state of one pool, selected by its key or hash. */\n getPool(selector: GdexPoolSelector): Promise<Record<string, unknown>> {\n return this.request('gdex_getPool', selector);\n }\n\n /** `gdex_getBalance`: an owner's balances, or only the one of `tokenClassKey` when given. */\n async getBalance(owner: string, tokenClassKey?: string): Promise<Record<string, unknown>> {\n const ref = userRef(owner, 'owner');\n return this.request(\n 'gdex_getBalance',\n tokenClassKey === undefined ? { owner: ref } : { owner: ref, tokenClassKey },\n );\n }\n\n /**\n * `gdex_getPositions`: an owner's positions, optionally in one pool, a page at a time. Pass the\n * returned `bookmark` back in as `bookmark` for the next page.\n */\n async getPositions(opts: {\n owner: string;\n pool?: GdexPoolKey;\n poolHash?: string;\n limit?: number;\n bookmark?: string;\n }): Promise<{ positions: Record<string, unknown>[]; bookmark: string }> {\n return this.request('gdex_getPositions', { ...opts, owner: userRef(opts.owner, 'owner') });\n }\n\n /** `gdex_getBlockHeight`: the block number the server reports, with its timestamp. */\n getBlockHeight(): Promise<{ blockNumber: number; timestamp: string }> {\n return this.request('gdex_getBlockHeight');\n }\n\n /** `gdex_quote`: a quote over the stream; give exactly one of `amountIn` or `amountOut`. */\n quote(params: {\n tokenIn: string;\n tokenOut: string;\n fee?: number;\n amountIn?: string;\n amountOut?: string;\n }): Promise<Record<string, unknown>> {\n return this.request('gdex_quote', params);\n }\n\n /** `gdex_getToken`: the server's record of one token class, as it sends it. */\n getToken(tokenClassKey: string): Promise<Record<string, unknown>> {\n return this.request('gdex_getToken', { tokenClassKey });\n }\n\n /** One event per committed swap. Omit the pool to receive every pool's swaps. */\n subscribeSwaps(\n cb: (event: Record<string, unknown>) => void,\n opts: GdexSubscribeOptions & {\n pool?: GdexPoolKey;\n poolHash?: string;\n transactionId?: string;\n } = {},\n ): Promise<GdexSubscription> {\n return this.subscribe('swap', cb, opts);\n }\n\n /**\n * State changes of one pool (price, tick, reserves, liquidity). These events carry no acting wallet:\n * on v2 `creator` is whoever created the pool, not whoever just traded or added liquidity. For\n * \"who did it\", use {@link subscribeLiquidity} (`owner`) or {@link subscribeSwaps} (`sender`).\n */\n subscribePool(\n selector: GdexPoolSelector,\n cb: (event: Record<string, unknown>) => void,\n opts: GdexSubscribeOptions = {},\n ): Promise<GdexSubscription> {\n return this.subscribe('pool', cb, { ...selector, ...opts });\n }\n\n /** Balance changes of one wallet. */\n async subscribeBalances(\n owner: string,\n cb: (event: Record<string, unknown>) => void,\n opts: GdexSubscribeOptions & { tokenClassKey?: string } = {},\n ): Promise<GdexSubscription> {\n return this.subscribe('balance', cb, { owner: userRef(owner, 'owner'), ...opts });\n }\n\n /** Each newly created pool. */\n subscribePoolCreated(\n cb: (event: Record<string, unknown>) => void,\n opts: GdexSubscribeOptions & { tokenClassKey?: string } = {},\n ): Promise<GdexSubscription> {\n return this.subscribe('poolCreated', cb, opts);\n }\n\n /**\n * One event per committed AddLiquidity, RemoveLiquidity and CollectPositionFees, on both contract\n * versions. Every filter is optional; with none, every liquidity event arrives. These events never\n * appear on {@link subscribeSwaps}. There is no snapshot: read positions with {@link getPositions}.\n * Deduplicate by `transactionId` plus `positionId`: a v1 BatchSubmit can hold several operations\n * under one transaction id.\n */\n async subscribeLiquidity(\n cb: (event: GdexLiquidityEvent) => void,\n opts: GdexSubscribeOptions & GdexLiquidityFilter = {},\n ): Promise<GdexSubscription> {\n const filter =\n opts.owner === undefined ? opts : { ...opts, owner: userRef(opts.owner, 'owner') };\n return this.subscribe(\n 'liquidity',\n (event) => {\n if (isGdexLiquidityEvent(event)) cb(event);\n else debugLog('Ignoring a malformed liquidity event from the GDEX stream');\n },\n filter,\n );\n }\n\n /** Each block-height advance. */\n subscribeBlocks(\n cb: (event: Record<string, unknown>) => void,\n opts: GdexSubscribeOptions = {},\n ): Promise<GdexSubscription> {\n return this.subscribe('blocks', cb, opts);\n }\n\n private openSocket(): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n let opened = false;\n const socket =\n this.apiKey === undefined\n ? new this.webSocketConstructor(this.url, GDEX_SUBPROTOCOL)\n : new this.webSocketConstructor(this.url, GDEX_SUBPROTOCOL, {\n headers: { 'x-api-key': this.apiKey },\n });\n this.socket = socket;\n\n socket.onopen = () => {\n if (this.socket !== socket) return;\n opened = true;\n this.connectPromise = undefined;\n if (!this.reconnecting) this.backoff.reset();\n debugLog('Connected to GDEX stream');\n resolve();\n };\n socket.onmessage = (event) => this.handleMessage(event.data);\n socket.onerror = () => {\n if (!opened) reject(new GSwapSDKError('STREAM_CONNECT_FAILED', { url: this.url }));\n };\n socket.onclose = (event) => {\n if (this.socket !== socket) return;\n this.socket = undefined;\n this.connectPromise = undefined;\n if (!opened) {\n reject(new GSwapSDKError('STREAM_CLOSED_BEFORE_CONNECT', { closeCode: event.code ?? 0 }));\n }\n this.rejectPending(\n new GSwapSDKError('STREAM_CONNECTION_CLOSED', { closeCode: event.code ?? 0 }),\n );\n if (!this.intentionalClose && !this.reconnecting) this.startReconnectLoop();\n };\n });\n }\n\n private handleMessage(data: unknown): void {\n if (typeof data !== 'string') {\n debugLog('Ignoring non-text GDEX WebSocket frame');\n return;\n }\n\n let message: JsonRpcResponse;\n try {\n message = JSON.parse(data) as JsonRpcResponse;\n } catch {\n debugLog('Ignoring invalid JSON from GDEX stream');\n return;\n }\n\n if (typeof message.id === 'number') {\n const pending = this.pending.get(message.id);\n if (!pending) return;\n clearTimeout(pending.timeout);\n this.pending.delete(message.id);\n if (message.error) {\n const code = typeof message.error.code === 'number' ? message.error.code : -32603;\n const errorMessage =\n typeof message.error.message === 'string' ? message.error.message : 'GDEX request failed';\n pending.reject(new GdexStreamError(code, errorMessage, message.error.data));\n } else {\n try {\n pending.onResult?.(message.result);\n } catch (error) {\n pending.reject(error instanceof Error ? error : new Error(String(error)));\n return;\n }\n pending.resolve(message.result);\n }\n return;\n }\n\n if (message.method !== 'gdex_subscription' || !this.isRecord(message.params)) return;\n const subscriptionId = message.params['subscription'];\n const result = message.params['result'];\n if (typeof subscriptionId !== 'string' || !this.isRecord(result)) return;\n const subscription = this.subscriptionsByServerId.get(subscriptionId);\n if (!subscription?.active) return;\n try {\n subscription.callback(result);\n } catch (error) {\n debugLog('GDEX subscription callback failed', error);\n }\n }\n\n private async subscribe(\n channel: GdexChannel,\n callback: EventCallback,\n options: object,\n ): Promise<GdexSubscription> {\n const params: Record<string, unknown> = { channel, ...options };\n const handle: MutableGdexSubscription = {\n subscriptionId: '',\n unsubscribe: async () => this.unsubscribe(subscription),\n };\n const subscription: ActiveSubscription = {\n serverId: '',\n params,\n callback,\n handle,\n active: true,\n };\n // Registered inside the response handler, not after the await: see PendingRequest.onResult.\n await this.send('gdex_subscribe', params, (value) => {\n const serverId = readSubscriptionId(value);\n subscription.serverId = serverId;\n handle.subscriptionId = serverId;\n this.activeSubscriptions.add(subscription);\n this.subscriptionsByServerId.set(serverId, subscription);\n });\n return handle;\n }\n\n private async unsubscribe(subscription: ActiveSubscription): Promise<void> {\n if (!subscription.active) return;\n subscription.active = false;\n this.activeSubscriptions.delete(subscription);\n this.subscriptionsByServerId.delete(subscription.serverId);\n if (this.isConnected()) {\n await this.request('gdex_unsubscribe', { subscriptionId: subscription.serverId });\n }\n }\n\n private startReconnectLoop(): void {\n if (this.reconnecting || this.intentionalClose) return;\n this.reconnecting = true;\n void this.reconnectLoop();\n }\n\n private async reconnectLoop(): Promise<void> {\n while (!this.intentionalClose && this.backoff.shouldRetry()) {\n const delay = this.backoff.nextDelayMs();\n this.backoff.recordAttempt();\n debugLog(\n `GDEX reconnect attempt ${this.backoff.attemptCount}/${this.backoff.maxAttempts} in ${delay}ms`,\n );\n await this.waitForReconnectDelay(delay);\n // `disconnect()` can run while the asynchronous delay is pending.\n if (this.intentionalClose) break;\n\n try {\n await this.openSocket();\n await this.resubscribeAll();\n this.backoff.reset();\n this.reconnecting = false;\n return;\n } catch (error) {\n debugLog(\n `GDEX reconnect failed: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n this.reconnecting = false;\n if (!this.intentionalClose) debugLog('GDEX reconnection attempts exhausted');\n }\n\n private async resubscribeAll(): Promise<void> {\n this.subscriptionsByServerId.clear();\n for (const subscription of this.activeSubscriptions) {\n if (!subscription.active) continue;\n const params = { ...subscription.params, snapshot: true };\n const result = await this.resubscribeWithRateLimitRetry(params, (value) => {\n const serverId = readSubscriptionId(value);\n // The consumer can unsubscribe while the asynchronous subscribe request is pending.\n if (!subscription.active) return;\n subscription.serverId = serverId;\n subscription.handle.subscriptionId = serverId;\n this.subscriptionsByServerId.set(serverId, subscription);\n });\n if (!subscription.active) {\n await this.request('gdex_unsubscribe', { subscriptionId: result.subscriptionId });\n }\n }\n }\n\n private async resubscribeWithRateLimitRetry(\n params: Record<string, unknown>,\n onResult: (value: unknown) => void,\n ): Promise<{ subscriptionId: string }> {\n for (let attempt = 0; ; attempt++) {\n try {\n return await this.send('gdex_subscribe', params, onResult);\n } catch (error) {\n if (\n !(error instanceof GdexStreamError) ||\n error.code !== RATE_LIMITED ||\n attempt >= MAX_RESUBSCRIBE_RATE_RETRIES\n ) {\n throw error;\n }\n const retryAfterMs = this.readRetryAfterMs(error.data);\n debugLog(`GDEX resubscribe rate limited; retrying in ${retryAfterMs}ms`);\n await new Promise<void>((resolve) => setTimeout(resolve, retryAfterMs));\n }\n }\n }\n\n private waitForReconnectDelay(delay: number): Promise<void> {\n return new Promise((resolve) => {\n this.reconnectTimer = setTimeout(() => {\n this.reconnectTimer = undefined;\n this.reconnectDelayResolve = undefined;\n resolve();\n }, delay);\n this.reconnectDelayResolve = resolve;\n });\n }\n\n private clearReconnectTimer(): void {\n if (this.reconnectTimer !== undefined) clearTimeout(this.reconnectTimer);\n this.reconnectTimer = undefined;\n const resolve = this.reconnectDelayResolve;\n this.reconnectDelayResolve = undefined;\n resolve?.();\n }\n\n private rejectPending(error: Error): void {\n for (const pending of this.pending.values()) {\n clearTimeout(pending.timeout);\n pending.reject(error);\n }\n this.pending.clear();\n }\n\n private readRetryAfterMs(data: unknown): number {\n if (\n !this.isRecord(data) ||\n typeof data['retryAfterMs'] !== 'number' ||\n data['retryAfterMs'] < 0\n )\n return 1_000;\n return data['retryAfterMs'];\n }\n\n private isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n }\n}\n"],"mappings":"8VAMA,MAAMC,EAAmB,kBAoGnBC,EAAwC,CAAC,MAAO,SAA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\"version\"","pool","\"poolHash\"","\"transactionId\"","\"action\"","\"owner\"","\"amount0\"","\"amount1\"","\"blockNumber\"","\"timestamp\"","GdexStreamError","message","code","data","readSubscriptionId","id","GdexStreamService","config","GSWAP_ENVIRONMENTS","ReconnectionBackoff","implementation","GSwapSDKError","socket","method","params","frame","\"params\"","timeout","reject","resolve","error","selector","ref","userRef","owner","tokenClassKey","opts","cb","filter","event","debugLog","opened","pending","errorMessage","subscriptionId","\"subscription\"","result","\"result\"","subscription","options","handle","serverId","delay","attempt","onResult","retryAfterMs","\"retryAfterMs\""],"sources":["../../../src/classes/gdex_stream.ts"],"sourcesContent":["import { GSWAP_ENVIRONMENTS } from '../types/env.js';\nimport { debugLog } from '../utils/debug.js';\nimport { userRef } from '../utils/validation.js';\nimport { ReconnectionBackoff } from '../utils/reconnection.js';\nimport { GSwapSDKError } from './gswap_sdk_error.js';\n\nconst GDEX_SUBPROTOCOL = 'gdex.jsonrpc.v1';\nconst RATE_LIMITED = -32003;\nconst MAX_RESUBSCRIBE_RATE_RETRIES = 5;\nconst WEBSOCKET_OPEN = 1;\n\n/** Options for {@link GdexStreamService}. */\nexport interface GdexStreamConfig {\n /** Stream endpoint. Defaults to production (`wss://dex-backend-prod1.defi.gala.com/ws`). */\n url?: string | undefined;\n /** Reconnect attempts after an unexpected close. Default 5. */\n reconnectAttempts?: number | undefined;\n /** Delay before the first reconnect attempt; doubles each attempt. Default 2000 ms. */\n reconnectDelayMs?: number | undefined;\n /** How long a request waits for its response. Default 15000 ms. */\n requestTimeoutMs?: number | undefined;\n /**\n * A standards-compatible WebSocket constructor. Required on Node.js older than 22, which has no\n * global `WebSocket` (pass the one from the `ws` package).\n */\n webSocketImpl?: unknown;\n /**\n * Presents `x-api-key` on the WebSocket upgrade request, which the swap backend uses to serve the\n * PRIVILEGED view (shadow swaps with the wallet unredacted). Without it, or with a wrong key, the\n * connection is simply public: the server never says whether a privileged mode exists.\n *\n * It must travel as an HTTP header, because the server reads no other credential, and a browser\n * `WebSocket` cannot set headers. So this option needs a constructor that accepts them as its\n * third argument (`{ headers }`): the `ws` package on Node.js, or React Native's built-in\n * `WebSocket`. It therefore REQUIRES `webSocketImpl` (the platform default is never assumed to\n * honor headers, and a key that is silently dropped would look like a working privileged\n * connection); the constructor throws otherwise. Use it from server-side code only: a key\n * shipped inside a browser or app bundle is not a secret. Browser clients stay public.\n */\n apiKey?: string | undefined;\n}\n\n/** The channels of the realtime stream. */\nexport type GdexChannel = 'pool' | 'balance' | 'poolCreated' | 'swap' | 'liquidity' | 'blocks';\n\n/** A pool named by its two token class keys (pipe form) and fee tier. */\nexport interface GdexPoolKey {\n token0ClassKey: string;\n token1ClassKey: string;\n fee: number;\n}\n\n/** A pool named either by its key or by its hash (`v2:<poolRef>` for a v2 pool). */\nexport type GdexPoolSelector = { pool: GdexPoolKey } | { poolHash: string };\n\n/** Options common to every subscription. */\nexport interface GdexSubscribeOptions {\n /** Send the current state right after the subscribe response. */\n snapshot?: boolean | undefined;\n /** Trim each event to these fields; identity and envelope fields always stay. */\n fields?: string[] | undefined;\n}\n\n/** Filters for {@link GdexStreamService.subscribeLiquidity}; all optional. */\nexport interface GdexLiquidityFilter {\n /** Only this pool, named by its key. */\n pool?: GdexPoolKey | undefined;\n /** Only this pool, named by its hash (`v2:<poolRef>` for a v2 pool). */\n poolHash?: string | undefined;\n /** Only events for this LP wallet (the position's owner). */\n owner?: string | undefined;\n /** Only this transaction. */\n transactionId?: string | undefined;\n /** Contract version filter. */\n version?: 'v1' | 'v2' | 'all' | undefined;\n}\n\n/** One committed add, remove or collect, as the `liquidity` channel reports it. */\nexport interface GdexLiquidityEvent {\n version: 'v1' | 'v2';\n pool: GdexPoolKey;\n poolHash: string;\n transactionId: string;\n /** `add`, `remove` or `collect`. */\n action: 'add' | 'remove' | 'collect';\n /** The position's owner (the LP wallet). */\n owner: string;\n /** v1: the position id. v2: the chain position key `<pool>|<tickLow>|<tickHigh>|<owner>`. */\n positionId?: string;\n tickLower?: number;\n tickUpper?: number;\n /** v2 only: the position's liquidity after the operation; `\"0\"` means it is closed. */\n liquidityAfter?: string;\n /** Principal moved: deposited by an add, withdrawn by a remove, `\"0\"` for a collect. */\n amount0: string;\n amount1: string;\n /** Fees paid out. v2: always present (`\"0\"` for an add). v1: present on a collect only. */\n fees0?: string;\n fees1?: string;\n /** v2 only. */\n token0Symbol?: string;\n token1Symbol?: string;\n blockNumber: number;\n timestamp: string;\n}\n\nconst LIQUIDITY_ACTIONS: readonly unknown[] = ['add', 'remove', 'collect'];\n\n/** Whether a stream payload carries every field of a {@link GdexLiquidityEvent}. */\nexport function isGdexLiquidityEvent(\n value: Record<string, unknown>,\n): value is Record<string, unknown> & GdexLiquidityEvent {\n const { pool } = value;\n return (\n (value['version'] === 'v1' || value['version'] === 'v2') &&\n typeof pool === 'object' &&\n pool !== null &&\n typeof value['poolHash'] === 'string' &&\n typeof value['transactionId'] === 'string' &&\n LIQUIDITY_ACTIONS.includes(value['action']) &&\n typeof value['owner'] === 'string' &&\n typeof value['amount0'] === 'string' &&\n typeof value['amount1'] === 'string' &&\n typeof value['blockNumber'] === 'number' &&\n typeof value['timestamp'] === 'string'\n );\n}\n\n/** A live subscription. */\nexport interface GdexSubscription {\n subscriptionId: string;\n unsubscribe(): Promise<void>;\n}\n\n/** A JSON-RPC error answered by the stream. */\nexport class GdexStreamError extends Error {\n /** The JSON-RPC error code. */\n readonly code: number;\n /** The error's optional `data` member, as the server sent it. */\n readonly data?: unknown;\n\n constructor(code: number, message: string, data?: unknown) {\n super(message);\n this.name = 'GdexStreamError';\n this.code = code;\n if (data !== undefined) this.data = data;\n }\n}\n\ninterface WebSocketLike {\n readonly readyState: number;\n send(data: string): void;\n close(code?: number, reason?: string): void;\n onopen: ((event: unknown) => void) | null;\n onmessage: ((event: { data: unknown }) => void) | null;\n onclose: ((event: { code?: number; reason?: string }) => void) | null;\n onerror: ((event: unknown) => void) | null;\n}\n\ninterface WebSocketConstructor {\n new (\n url: string,\n protocols?: string | string[],\n options?: { headers: Record<string, string> },\n ): WebSocketLike;\n}\n\ninterface PendingRequest {\n resolve(value: unknown): void;\n reject(error: Error): void;\n timeout: ReturnType<typeof setTimeout>;\n /**\n * Runs SYNCHRONOUSLY when the response frame is handled, before any frame that follows it in\n * the same read. Subscriptions register here: the server writes a snapshot right after the\n * subscribe response, and a runtime that delivers both frames without yielding to microtasks\n * (Node's `ws` does, for frames in one chunk) would otherwise drop the snapshot because the\n * awaiting caller has not registered the subscription yet.\n */\n onResult?: ((value: unknown) => void) | undefined;\n}\n\ntype EventCallback = (event: Record<string, unknown>) => void;\n\ninterface ActiveSubscription {\n serverId: string;\n readonly params: Record<string, unknown>;\n readonly callback: EventCallback;\n readonly handle: MutableGdexSubscription;\n active: boolean;\n}\n\ninterface MutableGdexSubscription extends GdexSubscription {\n subscriptionId: string;\n}\n\nfunction readSubscriptionId(value: unknown): string {\n const id =\n typeof value === 'object' && value !== null\n ? (value as { subscriptionId?: unknown }).subscriptionId\n : undefined;\n if (typeof id !== 'string') {\n throw new GdexStreamError(-32603, 'GDEX subscribe response is missing its subscriptionId');\n }\n return id;\n}\n\ninterface JsonRpcResponse {\n id?: unknown;\n method?: unknown;\n result?: unknown;\n error?: { code?: unknown; message?: unknown; data?: unknown };\n params?: unknown;\n}\n\n/**\n * Client for the gSwap realtime stream (gdex WebSocket Protocol v1): JSON-RPC 2.0 over one raw\n * WebSocket, with automatic reconnect and resubscribe.\n *\n * @example\n * ```typescript\n * const stream = new GdexStreamService();\n * await stream.connect();\n * await stream.subscribeLiquidity(event => console.log(event.action, event.owner), {\n * owner: 'client|618ae395c1c653111d3315be',\n * });\n * ```\n */\nexport class GdexStreamService {\n private readonly url: string;\n private readonly requestTimeoutMs: number;\n private readonly apiKey: string | undefined;\n private readonly webSocketConstructor: WebSocketConstructor;\n private readonly backoff: ReconnectionBackoff;\n private socket: WebSocketLike | undefined;\n private connectPromise: Promise<void> | undefined;\n private nextRequestId = 0;\n private readonly pending = new Map<number, PendingRequest>();\n private readonly subscriptionsByServerId = new Map<string, ActiveSubscription>();\n private readonly activeSubscriptions = new Set<ActiveSubscription>();\n private intentionalClose = false;\n private reconnecting = false;\n private reconnectTimer: ReturnType<typeof setTimeout> | undefined;\n private reconnectDelayResolve: (() => void) | undefined;\n\n constructor(config: GdexStreamConfig = {}) {\n this.url = config.url ?? GSWAP_ENVIRONMENTS.prod.dexBackendWsUrl;\n this.requestTimeoutMs = config.requestTimeoutMs ?? 15_000;\n this.backoff = new ReconnectionBackoff({\n maxAttempts: config.reconnectAttempts ?? 5,\n baseDelayMs: config.reconnectDelayMs ?? 2_000,\n });\n\n const implementation =\n config.webSocketImpl ?? (globalThis as { WebSocket?: unknown }).WebSocket;\n if (typeof implementation !== 'function') {\n throw new GSwapSDKError('STREAM_WEBSOCKET_UNAVAILABLE', {});\n }\n this.webSocketConstructor = implementation as WebSocketConstructor;\n if (config.apiKey !== undefined) {\n if (config.apiKey === '' || config.webSocketImpl === undefined) {\n throw new GSwapSDKError('STREAM_API_KEY_UNUSABLE', {});\n }\n this.apiKey = config.apiKey;\n }\n }\n\n /** Open the connection. Resolves at once when already connected. */\n connect(): Promise<void> {\n if (this.isConnected()) return Promise.resolve();\n if (this.connectPromise) return this.connectPromise;\n this.intentionalClose = false;\n this.clearReconnectTimer();\n this.connectPromise = this.openSocket();\n return this.connectPromise;\n }\n\n /** Close the connection and stop reconnecting. */\n disconnect(): void {\n this.intentionalClose = true;\n this.reconnecting = false;\n this.clearReconnectTimer();\n this.rejectPending(new GSwapSDKError('STREAM_DISCONNECTED', {}));\n const socket = this.socket;\n this.socket = undefined;\n this.connectPromise = undefined;\n socket?.close(1000, 'client disconnect');\n }\n\n /** `true` while the socket is open (false while connecting, reconnecting or after `disconnect()`). */\n isConnected(): boolean {\n return this.socket?.readyState === WEBSOCKET_OPEN;\n }\n\n /** Raw JSON-RPC escape hatch. */\n request<T = unknown>(method: string, params?: Record<string, unknown>): Promise<T> {\n return this.send<T>(method, params);\n }\n\n private send<T>(\n method: string,\n params: Record<string, unknown> | undefined,\n onResult?: (value: unknown) => void,\n ): Promise<T> {\n if (!this.isConnected() || !this.socket) {\n return Promise.reject(new GSwapSDKError('STREAM_NOT_CONNECTED', {}));\n }\n\n const id = ++this.nextRequestId;\n const frame: Record<string, unknown> = { jsonrpc: '2.0', id, method };\n if (params !== undefined) frame['params'] = params;\n\n return new Promise<T>((resolve, reject) => {\n const timeout = setTimeout(() => {\n this.pending.delete(id);\n reject(\n new GSwapSDKError('STREAM_REQUEST_TIMEOUT', { method, timeoutMs: this.requestTimeoutMs }),\n );\n }, this.requestTimeoutMs);\n this.pending.set(id, { resolve: (value) => resolve(value as T), reject, timeout, onResult });\n\n try {\n this.socket?.send(JSON.stringify(frame));\n } catch (error) {\n clearTimeout(timeout);\n this.pending.delete(id);\n reject(error instanceof Error ? error : new Error(String(error)));\n }\n });\n }\n\n /** `gdex_serverInfo`: the server's own description of itself, as it sends it. */\n serverInfo(): Promise<Record<string, unknown>> {\n return this.request('gdex_serverInfo');\n }\n\n /** `gdex_ping`: a round trip that answers `{ pong, serverTime }`. */\n ping(): Promise<{ pong: boolean; serverTime: string }> {\n return this.request('gdex_ping');\n }\n\n /** `gdex_getPool`: the current state of one pool, selected by its key or hash. */\n getPool(selector: GdexPoolSelector): Promise<Record<string, unknown>> {\n return this.request('gdex_getPool', selector);\n }\n\n /** `gdex_getBalance`: an owner's balances, or only the one of `tokenClassKey` when given. */\n async getBalance(owner: string, tokenClassKey?: string): Promise<Record<string, unknown>> {\n const ref = userRef(owner, 'owner');\n return this.request(\n 'gdex_getBalance',\n tokenClassKey === undefined ? { owner: ref } : { owner: ref, tokenClassKey },\n );\n }\n\n /**\n * `gdex_getPositions`: an owner's positions, optionally in one pool, a page at a time. Pass the\n * returned `bookmark` back in as `bookmark` for the next page.\n */\n async getPositions(opts: {\n owner: string;\n pool?: GdexPoolKey;\n poolHash?: string;\n limit?: number;\n bookmark?: string;\n }): Promise<{ positions: Record<string, unknown>[]; bookmark: string }> {\n return this.request('gdex_getPositions', { ...opts, owner: userRef(opts.owner, 'owner') });\n }\n\n /** `gdex_getBlockHeight`: the block number the server reports, with its timestamp. */\n getBlockHeight(): Promise<{ blockNumber: number; timestamp: string }> {\n return this.request('gdex_getBlockHeight');\n }\n\n /** `gdex_quote`: a quote over the stream; give exactly one of `amountIn` or `amountOut`. */\n quote(params: {\n tokenIn: string;\n tokenOut: string;\n fee?: number;\n amountIn?: string;\n amountOut?: string;\n }): Promise<Record<string, unknown>> {\n return this.request('gdex_quote', params);\n }\n\n /** `gdex_getToken`: the server's record of one token class, as it sends it. */\n getToken(tokenClassKey: string): Promise<Record<string, unknown>> {\n return this.request('gdex_getToken', { tokenClassKey });\n }\n\n /** One event per committed swap. Omit the pool to receive every pool's swaps. */\n subscribeSwaps(\n cb: (event: Record<string, unknown>) => void,\n opts: GdexSubscribeOptions & {\n pool?: GdexPoolKey;\n poolHash?: string;\n transactionId?: string;\n } = {},\n ): Promise<GdexSubscription> {\n return this.subscribe('swap', cb, opts);\n }\n\n /**\n * State changes of one pool (price, tick, reserves, liquidity). These events carry no acting wallet:\n * on v2 `creator` is whoever created the pool, not whoever just traded or added liquidity. For\n * \"who did it\", use {@link subscribeLiquidity} (`owner`) or {@link subscribeSwaps} (`sender`).\n */\n subscribePool(\n selector: GdexPoolSelector,\n cb: (event: Record<string, unknown>) => void,\n opts: GdexSubscribeOptions = {},\n ): Promise<GdexSubscription> {\n return this.subscribe('pool', cb, { ...selector, ...opts });\n }\n\n /** Balance changes of one wallet. */\n async subscribeBalances(\n owner: string,\n cb: (event: Record<string, unknown>) => void,\n opts: GdexSubscribeOptions & { tokenClassKey?: string } = {},\n ): Promise<GdexSubscription> {\n return this.subscribe('balance', cb, { owner: userRef(owner, 'owner'), ...opts });\n }\n\n /** Each newly created pool. */\n subscribePoolCreated(\n cb: (event: Record<string, unknown>) => void,\n opts: GdexSubscribeOptions & { tokenClassKey?: string } = {},\n ): Promise<GdexSubscription> {\n return this.subscribe('poolCreated', cb, opts);\n }\n\n /**\n * One event per committed AddLiquidity, RemoveLiquidity and CollectPositionFees, on both contract\n * versions. Every filter is optional; with none, every liquidity event arrives. These events never\n * appear on {@link subscribeSwaps}. There is no snapshot: read positions with {@link getPositions}.\n * Deduplicate by `transactionId` plus `positionId`: a v1 BatchSubmit can hold several operations\n * under one transaction id.\n */\n async subscribeLiquidity(\n cb: (event: GdexLiquidityEvent) => void,\n opts: GdexSubscribeOptions & GdexLiquidityFilter = {},\n ): Promise<GdexSubscription> {\n const filter =\n opts.owner === undefined ? opts : { ...opts, owner: userRef(opts.owner, 'owner') };\n return this.subscribe(\n 'liquidity',\n (event) => {\n if (isGdexLiquidityEvent(event)) cb(event);\n else debugLog('Ignoring a malformed liquidity event from the GDEX stream');\n },\n filter,\n );\n }\n\n /** Each block-height advance. */\n subscribeBlocks(\n cb: (event: Record<string, unknown>) => void,\n opts: GdexSubscribeOptions = {},\n ): Promise<GdexSubscription> {\n return this.subscribe('blocks', cb, opts);\n }\n\n private openSocket(): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n let opened = false;\n const socket =\n this.apiKey === undefined\n ? new this.webSocketConstructor(this.url, GDEX_SUBPROTOCOL)\n : new this.webSocketConstructor(this.url, GDEX_SUBPROTOCOL, {\n headers: { 'x-api-key': this.apiKey },\n });\n this.socket = socket;\n\n socket.onopen = () => {\n if (this.socket !== socket) return;\n opened = true;\n this.connectPromise = undefined;\n if (!this.reconnecting) this.backoff.reset();\n debugLog('Connected to GDEX stream');\n resolve();\n };\n socket.onmessage = (event) => this.handleMessage(event.data);\n socket.onerror = () => {\n if (!opened) reject(new GSwapSDKError('STREAM_CONNECT_FAILED', { url: this.url }));\n };\n socket.onclose = (event) => {\n if (this.socket !== socket) return;\n this.socket = undefined;\n this.connectPromise = undefined;\n if (!opened) {\n reject(new GSwapSDKError('STREAM_CLOSED_BEFORE_CONNECT', { closeCode: event.code ?? 0 }));\n }\n this.rejectPending(\n new GSwapSDKError('STREAM_CONNECTION_CLOSED', { closeCode: event.code ?? 0 }),\n );\n if (!this.intentionalClose && !this.reconnecting) this.startReconnectLoop();\n };\n });\n }\n\n private handleMessage(data: unknown): void {\n if (typeof data !== 'string') {\n debugLog('Ignoring non-text GDEX WebSocket frame');\n return;\n }\n\n let message: JsonRpcResponse;\n try {\n message = JSON.parse(data) as JsonRpcResponse;\n } catch {\n debugLog('Ignoring invalid JSON from GDEX stream');\n return;\n }\n\n if (typeof message.id === 'number') {\n const pending = this.pending.get(message.id);\n if (!pending) return;\n clearTimeout(pending.timeout);\n this.pending.delete(message.id);\n if (message.error) {\n const code = typeof message.error.code === 'number' ? message.error.code : -32603;\n const errorMessage =\n typeof message.error.message === 'string' ? message.error.message : 'GDEX request failed';\n pending.reject(new GdexStreamError(code, errorMessage, message.error.data));\n } else {\n try {\n pending.onResult?.(message.result);\n } catch (error) {\n pending.reject(error instanceof Error ? error : new Error(String(error)));\n return;\n }\n pending.resolve(message.result);\n }\n return;\n }\n\n if (message.method !== 'gdex_subscription' || !this.isRecord(message.params)) return;\n const subscriptionId = message.params['subscription'];\n const result = message.params['result'];\n if (typeof subscriptionId !== 'string' || !this.isRecord(result)) return;\n const subscription = this.subscriptionsByServerId.get(subscriptionId);\n if (!subscription?.active) return;\n try {\n subscription.callback(result);\n } catch (error) {\n debugLog('GDEX subscription callback failed', error);\n }\n }\n\n private async subscribe(\n channel: GdexChannel,\n callback: EventCallback,\n options: object,\n ): Promise<GdexSubscription> {\n const params: Record<string, unknown> = { channel, ...options };\n const handle: MutableGdexSubscription = {\n subscriptionId: '',\n unsubscribe: async () => this.unsubscribe(subscription),\n };\n const subscription: ActiveSubscription = {\n serverId: '',\n params,\n callback,\n handle,\n active: true,\n };\n // Registered inside the response handler, not after the await: see PendingRequest.onResult.\n await this.send('gdex_subscribe', params, (value) => {\n const serverId = readSubscriptionId(value);\n subscription.serverId = serverId;\n handle.subscriptionId = serverId;\n this.activeSubscriptions.add(subscription);\n this.subscriptionsByServerId.set(serverId, subscription);\n });\n return handle;\n }\n\n private async unsubscribe(subscription: ActiveSubscription): Promise<void> {\n if (!subscription.active) return;\n subscription.active = false;\n this.activeSubscriptions.delete(subscription);\n this.subscriptionsByServerId.delete(subscription.serverId);\n if (this.isConnected()) {\n await this.request('gdex_unsubscribe', { subscriptionId: subscription.serverId });\n }\n }\n\n private startReconnectLoop(): void {\n if (this.reconnecting || this.intentionalClose) return;\n this.reconnecting = true;\n void this.reconnectLoop();\n }\n\n private async reconnectLoop(): Promise<void> {\n while (!this.intentionalClose && this.backoff.shouldRetry()) {\n const delay = this.backoff.nextDelayMs();\n this.backoff.recordAttempt();\n debugLog(\n `GDEX reconnect attempt ${this.backoff.attemptCount}/${this.backoff.maxAttempts} in ${delay}ms`,\n );\n await this.waitForReconnectDelay(delay);\n // `disconnect()` can run while the asynchronous delay is pending.\n if (this.intentionalClose) break;\n\n try {\n await this.openSocket();\n await this.resubscribeAll();\n this.backoff.reset();\n this.reconnecting = false;\n return;\n } catch (error) {\n debugLog(\n `GDEX reconnect failed: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n this.reconnecting = false;\n if (!this.intentionalClose) debugLog('GDEX reconnection attempts exhausted');\n }\n\n private async resubscribeAll(): Promise<void> {\n this.subscriptionsByServerId.clear();\n for (const subscription of this.activeSubscriptions) {\n if (!subscription.active) continue;\n const params = { ...subscription.params, snapshot: true };\n const result = await this.resubscribeWithRateLimitRetry(params, (value) => {\n const serverId = readSubscriptionId(value);\n // The consumer can unsubscribe while the asynchronous subscribe request is pending.\n if (!subscription.active) return;\n subscription.serverId = serverId;\n subscription.handle.subscriptionId = serverId;\n this.subscriptionsByServerId.set(serverId, subscription);\n });\n if (!subscription.active) {\n await this.request('gdex_unsubscribe', { subscriptionId: result.subscriptionId });\n }\n }\n }\n\n private async resubscribeWithRateLimitRetry(\n params: Record<string, unknown>,\n onResult: (value: unknown) => void,\n ): Promise<{ subscriptionId: string }> {\n for (let attempt = 0; ; attempt++) {\n try {\n return await this.send('gdex_subscribe', params, onResult);\n } catch (error) {\n if (\n !(error instanceof GdexStreamError) ||\n error.code !== RATE_LIMITED ||\n attempt >= MAX_RESUBSCRIBE_RATE_RETRIES\n ) {\n throw error;\n }\n const retryAfterMs = this.readRetryAfterMs(error.data);\n debugLog(`GDEX resubscribe rate limited; retrying in ${retryAfterMs}ms`);\n await new Promise<void>((resolve) => setTimeout(resolve, retryAfterMs));\n }\n }\n }\n\n private waitForReconnectDelay(delay: number): Promise<void> {\n return new Promise((resolve) => {\n this.reconnectTimer = setTimeout(() => {\n this.reconnectTimer = undefined;\n this.reconnectDelayResolve = undefined;\n resolve();\n }, delay);\n this.reconnectDelayResolve = resolve;\n });\n }\n\n private clearReconnectTimer(): void {\n if (this.reconnectTimer !== undefined) clearTimeout(this.reconnectTimer);\n this.reconnectTimer = undefined;\n const resolve = this.reconnectDelayResolve;\n this.reconnectDelayResolve = undefined;\n resolve?.();\n }\n\n private rejectPending(error: Error): void {\n for (const pending of this.pending.values()) {\n clearTimeout(pending.timeout);\n pending.reject(error);\n }\n this.pending.clear();\n }\n\n private readRetryAfterMs(data: unknown): number {\n if (\n !this.isRecord(data) ||\n typeof data['retryAfterMs'] !== 'number' ||\n data['retryAfterMs'] < 0\n )\n return 1_000;\n return data['retryAfterMs'];\n }\n\n private isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n }\n}\n"],"mappings":"A,8VAMA,MAAMC,EAAmB,kBAoGnBC,EAAwC,CAAC,MAAO,SAAU,SAAS,EAGzE,SAAgBC,EACd,EACuD,CACvD,GAAM,CAAE,QAASC,EACjB,OACGA,EAAMC,UAAe,MAAQD,EAAMC,UAAe,OACnD,OAAOC,GAAS,YAChBA,GACA,OAAOF,EAAMG,UAAgB,UAC7B,OAAOH,EAAMI,eAAqB,UAClCN,EAAkB,SAASE,EAAMK,MAAS,GAC1C,OAAOL,EAAMM,OAAa,UAC1B,OAAON,EAAMO,SAAe,UAC5B,OAAOP,EA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vE,MAAM,IAAI,QAAe,GAAY,WAAW1B,EAAS0B,CAAY,CAAC,CACxE,CAEJ,CAEA,sBAA8B,EAA8B,CAC1D,OAAO,IAAI,QAAS,GAAY,CAC9B,KAAK,eAAiB,eAAiB,CACrC,KAAK,eAAiB,IAAA,GACtB,KAAK,sBAAwB,IAAA,GAC7B1B,EAAQ,CACV,EAAGuB,CAAK,EACR,KAAK,sBAAwBvB,CAC/B,CAAC,CACH,CAEA,qBAAoC,CAC9B,KAAK,iBAAmB,IAAA,IAAW,aAAa,KAAK,cAAc,EACvE,KAAK,eAAiB,IAAA,GACtB,IAAMA,EAAU,KAAK,sBACrB,KAAK,sBAAwB,IAAA,GAC7BA,IAAU,CACZ,CAEA,cAAsB,EAAoB,CACxC,IAAK,IAAMa,KAAW,KAAK,QAAQ,OAAO,EACxC,aAAaA,EAAQ,OAAO,EAC5BA,EAAQ,OAAOZ,CAAK,EAEtB,KAAK,QAAQ,MAAM,CACrB,CAEA,iBAAyB,EAAuB,CAO9C,MALE,CAAC,KAAK,SAASjB,CAAI,GACnB,OAAOA,EAAK2C,cAAoB,UAChC3C,EAAK2C,aAAkB,EAEhB,IACF3C,EAAK2C,YACd,CAEA,SAAiB,EAAkD,CACjE,OAAO,OAAOzD,GAAU,YAAYA,GAAkB,CAAC,MAAM,QAAQA,CAAK,CAC5E,CACF,E"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import e from"../_virtual/_@oxc-project_runtime@0.
|
|
1
|
+
import e from"../_virtual/_@oxc-project_runtime@0.154.0/helpers/esm/defineProperty.js";import{userRef as t}from"../utils/validation.js";import{Assets as n}from"./assets.js";import{DexFees as r}from"./dex_fees.js";import{ChainGateway as i}from"./gateway.js";import{GSWAP_ENVIRONMENTS as a}from"../types/env.js";import{GdexStreamService as o}from"./gdex_stream.js";import{HttpClient as s}from"./http_client.js";import{Leaderboard as c}from"./leaderboard.js";import{Market as l}from"./market.js";import{Onramper as u}from"./onramper.js";import{CanonicalSymbols as d,Symbols as f}from"./symbols.js";import{Pools as p}from"./pools.js";import{Positions as m}from"./positions.js";import{Quoting as h}from"./quoting.js";import{Swaps as g}from"./swaps.js";var _=class{constructor(o){e(this,`dexBackendBaseUrl`,void 0),e(this,`chainCallTimeoutMs`,void 0),e(this,`signer`,void 0),e(this,`walletAddress`,void 0),e(this,`gateway`,void 0),e(this,`symbols`,void 0),e(this,`quoting`,void 0),e(this,`pools`,void 0),e(this,`positions`,void 0),e(this,`swaps`,void 0),e(this,`assets`,void 0),e(this,`market`,void 0),e(this,`leaderboard`,void 0),e(this,`onramper`,void 0),e(this,`fees`,void 0),e(this,`dexBackendWsUrl`,void 0),e(this,`webSocketImpl`,void 0),e(this,`streamApiKey`,void 0),e(this,`streamClient`,void 0);let _=a[o?.env??`prod`];this.dexBackendBaseUrl=v(o?.dexBackendBaseUrl??_.dexBackendBaseUrl),this.chainCallTimeoutMs=o?.chainCallTimeoutMs??3e4,this.signer=o?.signer,this.walletAddress=o?.walletAddress===void 0?void 0:t(o.walletAddress,`walletAddress`);let y=new s(o?.httpRequestor,this.chainCallTimeoutMs,o?.wire);this.gateway=new i({dexBackendBaseUrl:this.dexBackendBaseUrl,chainCallTimeoutMs:this.chainCallTimeoutMs,...o?.wire===void 0?{}:{wire:o.wire},...o?.httpRequestor===void 0?{}:{httpRequestor:o.httpRequestor},...this.walletAddress===void 0?{}:{walletAddress:this.walletAddress}});let b={onInvalidEntry:o?.onInvalidEntry};this.symbols=new f(this.gateway,b);let x=o?.symbolResolution===`canonical`?new d:this.symbols;this.quoting=new h(this.gateway,x),this.pools=new p(this.gateway,x,b);let S={uniqueKeyPrefix:o?.uniqueKeyPrefix,...b};this.positions=new m(this.gateway,x,this.signer,this.walletAddress,S),this.swaps=new g(this.gateway,x,this.signer,this.walletAddress,S),this.assets=new n(this.dexBackendBaseUrl,y),this.market=new l(this.dexBackendBaseUrl,y,b),this.leaderboard=new c(this.dexBackendBaseUrl,y,b),this.onramper=new u(this.dexBackendBaseUrl,y),this.fees=new r(this.gateway,this.signer),this.dexBackendWsUrl=o?.dexBackendWsUrl??(o?.dexBackendBaseUrl===void 0?_.dexBackendWsUrl:`${this.dexBackendBaseUrl.replace(/^http/u,`ws`)}/ws`),this.webSocketImpl=o?.webSocketImpl,this.streamApiKey=o?.streamApiKey}get stream(){return this.streamClient??(this.streamClient=new o({url:this.dexBackendWsUrl,...this.webSocketImpl===void 0?{}:{webSocketImpl:this.webSocketImpl},...this.streamApiKey===void 0?{}:{apiKey:this.streamApiKey}})),this.streamClient}};function v(e){return e.replace(/\/$/u,``)}export{_ as GSwap};
|
|
2
2
|
//# sourceMappingURL=gswap.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"gswap.js","names":["_defineProperty","GSwap","environment","GSWAP_ENVIRONMENTS","options","trimTrailingSlash","userRef","httpClient","HttpClient","ChainGateway","lenient","Symbols","resolver","CanonicalSymbols","Quoting","Pools","keyOptions","Positions","Swaps","Assets","Market","Leaderboard","Onramper","DexFees","GdexStreamService","value"],"sources":["../../../src/classes/gswap.ts"],"sourcesContent":["import { Assets } from './assets.js';\nimport { DexFees } from './dex_fees.js';\nimport { ChainGateway } from './gateway.js';\nimport { GdexStreamService } from './gdex_stream.js';\nimport { HttpClient } from './http_client.js';\nimport { Leaderboard } from './leaderboard.js';\nimport { Market } from './market.js';\nimport { Onramper } from './onramper.js';\nimport { Pools } from './pools.js';\nimport { Positions } from './positions.js';\nimport { Quoting } from './quoting.js';\nimport type { GalaChainSigner, HttpRequestor, WireOptions } from '@gala-chain/gala-core-sdk';\nimport { CanonicalSymbols, Symbols } from './symbols.js';\nimport type { InvalidEntryHandler } from '../utils/lenient.js';\nimport { userRef } from '../utils/validation.js';\nimport { Swaps } from './swaps.js';\nimport type { GSwapEnv } from '../types/env.js';\nimport { GSWAP_ENVIRONMENTS } from '../types/env.js';\n\n/** Options for constructing a backend-routed SDK client. */\nexport interface GSwapOptions {\n /** Signs every write. Without one, reads work and any write throws `NO_SIGNER`. */\n signer?: GalaChainSigner | undefined;\n /**\n * The selected account, sent as `X-Wallet-Address` on writes (attribution only; the chain\n * recovers the signer from the signature). Required for shadow writes. Any spelling of an\n * Ethereum account (`eth|<40 hex>` in any casing, `0x...`, bare hex) is sent as `eth|<EIP-55>`,\n * `client|<id>` as written; a mixed-case spelling that is not the checksum is refused at\n * construction (`INVALID_WALLET_ADDRESS`), and `eth|0x...` (not an address form) is refused as\n * core's `INVALID_ETH_USER_REF_PREFIX`.\n */\n walletAddress?: string | undefined;\n /** `'stage'` or `'prod'` swap backend preset; defaults to `'prod'`. */\n env?: GSwapEnv | undefined;\n /** Overrides the preset's swap backend base URL (a test or private deployment). */\n dexBackendBaseUrl?: string | undefined;\n /** HTTP transport for every request; defaults to the global `fetch`. */\n httpRequestor?: HttpRequestor | undefined;\n /** Request timeout in milliseconds (default 30 000); `Infinity` arms no timer. */\n chainCallTimeoutMs?: number | undefined;\n /** Query encoding and `User-Agent` of the read requests (see {@link WireOptions}). */\n wire?: WireOptions | undefined;\n /**\n * How tokens are turned into trading symbols. `'registry'` (default) reads the symbol registry\n * once (`GET /v2/trade/symbols`, cached) and accepts symbols or class keys. `'canonical'` makes\n * no registry request: the caller passes the backend's canonical trading symbols (from a quote,\n * an estimate or a position), reads send tokens and ticks exactly as given (composite keys\n * included) and the backend orients the pair; see {@link CanonicalSymbols}.\n */\n symbolResolution?: 'registry' | 'canonical' | undefined;\n /**\n * Told about every row of a pool, symbol, position, price, price-series, season or leaderboard\n * answer that was skipped as unusable (see {@link InvalidEntryHandler}); without it such rows are\n * skipped silently.\n */\n onInvalidEntry?: InvalidEntryHandler | undefined;\n /** Realtime stream endpoint. Defaults to the environment's, or is derived from `dexBackendBaseUrl`. */\n dexBackendWsUrl?: string | undefined;\n /** WebSocket constructor for the realtime stream; required on Node.js older than 22. */\n webSocketImpl?: unknown;\n /**\n * `x-api-key` for the privileged stream view; server-side only, and it requires `webSocketImpl`\n * (see `GdexStreamConfig.apiKey`).\n */\n streamApiKey?: string | undefined;\n /**\n * Prefix of every write's `uniqueKey` (`<prefix><uuid>`). Defaults to `galaswap-operation-`,\n * what the Gala Wallet and the gSwap web app send; the backend does not depend on it.\n */\n uniqueKeyPrefix?: string | undefined;\n}\n\n/**\n * Main entry point for the current GalaChainDex SDK: one client bundling the services that read\n * and write through the swap backend (`quoting`, `swaps`, `pools`, `positions`, `assets`,\n * `market`, `leaderboard`, `onramper`, `symbols`, `fees`, `stream`). See {@link GSwapOptions} for\n * configuration.\n */\nexport class GSwap {\n /** The swap backend base URL every request goes to, without a trailing slash. */\n public readonly dexBackendBaseUrl: string;\n /** The request timeout in milliseconds (default 30 000; `Infinity` arms no timer). */\n public readonly chainCallTimeoutMs: number;\n /** The signer given at construction, if any. */\n public readonly signer: GalaChainSigner | undefined;\n /**\n * The account given at construction, if any, in the gateway's spelling (`eth|<EIP-55>`;\n * `client|<id>` as given).\n */\n public readonly walletAddress: string | undefined;\n /** The chain-gateway client every other service reads and writes through. */\n public readonly gateway: ChainGateway;\n /** The trading-symbol registry. */\n public readonly symbols: Symbols;\n /** Read-only exact-input and exact-output quotes. */\n public readonly quoting: Quoting;\n /** Pool, slot0 and composite-pool reads. */\n public readonly pools: Pools;\n /** Position reads, liquidity estimates and liquidity / pool-creation writes. */\n public readonly positions: Positions;\n /** Queued swaps (`RequestTrade`), dark swaps and swap confirmation. */\n public readonly swaps: Swaps;\n /** User token balances. */\n public readonly assets: Assets;\n /** USD prices, price series and the platform volume totals. */\n public readonly market: Market;\n /** Trading-competition seasons and rankings. */\n public readonly leaderboard: Leaderboard;\n /** The Onramper (fiat on-ramp) widget URL. */\n public readonly onramper: Onramper;\n /** Network-fee quotes (DryRun) signed with this client's signer. */\n public readonly fees: DexFees;\n /** The realtime stream endpoint {@link GSwap.stream} connects to. */\n public readonly dexBackendWsUrl: string;\n private readonly webSocketImpl: unknown;\n private readonly streamApiKey: string | undefined;\n private streamClient: GdexStreamService | undefined;\n\n /**\n * Create an SDK client for prod (the default) or stage, or for a `dexBackendBaseUrl` of your own.\n *\n * @example\n * ```typescript\n * const gSwap = new GSwap({ env: 'stage' });\n * const symbols = await gSwap.symbols.list();\n * ```\n */\n constructor(options?: GSwapOptions) {\n const environment = GSWAP_ENVIRONMENTS[options?.env ?? 'prod'];\n this.dexBackendBaseUrl = trimTrailingSlash(\n options?.dexBackendBaseUrl ?? environment.dexBackendBaseUrl,\n );\n this.chainCallTimeoutMs = options?.chainCallTimeoutMs ?? 30_000;\n this.signer = options?.signer;\n this.walletAddress =\n options?.walletAddress === undefined\n ? undefined\n : userRef(options.walletAddress, 'walletAddress');\n\n const httpClient = new HttpClient(\n options?.httpRequestor,\n this.chainCallTimeoutMs,\n options?.wire,\n );\n this.gateway = new ChainGateway({\n dexBackendBaseUrl: this.dexBackendBaseUrl,\n chainCallTimeoutMs: this.chainCallTimeoutMs,\n ...(options?.wire === undefined ? {} : { wire: options.wire }),\n ...(options?.httpRequestor === undefined ? {} : { httpRequestor: options.httpRequestor }),\n ...(this.walletAddress === undefined ? {} : { walletAddress: this.walletAddress }),\n });\n const lenient = { onInvalidEntry: options?.onInvalidEntry };\n this.symbols = new Symbols(this.gateway, lenient);\n // The services resolve tokens through the registry by default; the offline resolver sends the\n // caller's canonical symbols and keys as they are and never reads the registry.\n const resolver =\n options?.symbolResolution === 'canonical' ? new CanonicalSymbols() : this.symbols;\n this.quoting = new Quoting(this.gateway, resolver);\n this.pools = new Pools(this.gateway, resolver, lenient);\n const keyOptions = { uniqueKeyPrefix: options?.uniqueKeyPrefix, ...lenient };\n this.positions = new Positions(\n this.gateway,\n resolver,\n this.signer,\n this.walletAddress,\n keyOptions,\n );\n this.swaps = new Swaps(this.gateway, resolver, this.signer, this.walletAddress, keyOptions);\n this.assets = new Assets(this.dexBackendBaseUrl, httpClient);\n this.market = new Market(this.dexBackendBaseUrl, httpClient, lenient);\n this.leaderboard = new Leaderboard(this.dexBackendBaseUrl, httpClient, lenient);\n this.onramper = new Onramper(this.dexBackendBaseUrl, httpClient);\n this.fees = new DexFees(this.gateway, this.signer);\n this.dexBackendWsUrl =\n options?.dexBackendWsUrl ??\n (options?.dexBackendBaseUrl === undefined\n ? environment.dexBackendWsUrl\n : `${this.dexBackendBaseUrl.replace(/^http/u, 'ws')}/ws`);\n this.webSocketImpl = options?.webSocketImpl;\n this.streamApiKey = options?.streamApiKey;\n }\n\n /**\n * The realtime stream client for this environment (created on first use, not connected until you\n * call `connect()`).\n *\n * @example\n * ```typescript\n * const gSwap = new GSwap({ env: 'stage' });\n * await gSwap.stream.connect();\n * await gSwap.stream.subscribeLiquidity((event) => console.log(event.action, event.amount0));\n * ```\n */\n get stream(): GdexStreamService {\n this.streamClient ??= new GdexStreamService({\n url: this.dexBackendWsUrl,\n ...(this.webSocketImpl === undefined ? {} : { webSocketImpl: this.webSocketImpl }),\n ...(this.streamApiKey === undefined ? {} : { apiKey: this.streamApiKey }),\n });\n return this.streamClient;\n }\n}\n\nfunction trimTrailingSlash(value: string): string {\n return value.replace(/\\/$/u, '');\n}\n"],"mappings":"2uBA8EA,IAAaC,EAAb,KAAmB,CAiDjB,YAAY,EAAwB,CA/CpBD,EAAA,KAAA,oBAAA,IAAA,EAAA,EAEAA,EAAA,KAAA,qBAAA,IAAA,EAAA,EAEAA,EAAA,KAAA,SAAA,IAAA,EAAA,EAKAA,EAAA,KAAA,gBAAA,IAAA,EAAA,EAEAA,EAAA,KAAA,UAAA,IAAA,EAAA,EAEAA,EAAA,KAAA,UAAA,IAAA,EAAA,EAEAA,EAAA,KAAA,UAAA,IAAA,EAAA,EAEAA,EAAA,KAAA,QAAA,IAAA,EAAA,EAEAA,EAAA,KAAA,YAAA,IAAA,EAAA,EAEAA,EAAA,KAAA,QAAA,IAAA,EAAA,EAEAA,EAAA,KAAA,SAAA,IAAA,EAAA,EAEAA,EAAA,KAAA,SAAA,IAAA,EAAA,EAEAA,EAAA,KAAA,cAAA,IAAA,EAAA,EAEAA,EAAA,KAAA,WAAA,IAAA,EAAA,EAEAA,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,IAAIE,EAAM,KAAK,QAASN,EAAU,KAAK,OAAQ,KAAK,cAAeI,CAAU,EAC1F,KAAK,OAAS,IAAIG,EAAO,KAAK,kBAAmBZ,CAAU,EAC3D,KAAK,OAAS,IAAIa,EAAO,KAAK,kBAAmBb,EAAYG,CAAO,EACpE,KAAK,YAAc,IAAIW,EAAY,KAAK,kBAAmBd,EAAYG,CAAO,EAC9E,KAAK,SAAW,IAAIY,EAAS,KAAK,kBAAmBf,CAAU,EAC/D,KAAK,KAAO,IAAIgB,EAAQ,KAAK,QAAS,KAAK,MAAM,EACjD,KAAK,gBACHnB,GAAS,kBACRA,GAAS,oBAAsB,IAAA,GAC5BF,EAAY,gBACZ,GAAG,KAAK,kBAAkB,QAAQ,SAAU,IAAI,EAAE,MACxD,KAAK,cAAgBE,GAAS,cAC9B,KAAK,aAAeA,GAAS,YAC/B,CAaA,IAAI,QAA4B,CAM9B,OALA,KAAK,eAAL,KAAK,aAAiB,IAAIoB,EAAkB,CAC1C,IAAK,KAAK,gBACV,GAAI,KAAK,gBAAkB,IAAA,GAAY,CAAC,EAAI,CAAE,cAAe,KAAK,aAAc,EAChF,GAAI,KAAK,eAAiB,IAAA,GAAY,CAAC,EAAI,CAAE,OAAQ,KAAK,YAAa,CACzE,CAAC,GACM,KAAK,YACd,CACF,EAEA,SAASnB,EAAkB,EAAuB,CAChD,OAAOoB,EAAM,QAAQ,OAAQ,EAAE,CACjC"}
|
|
1
|
+
{"version":3,"file":"gswap.js","names":["_defineProperty","GSwap","environment","GSWAP_ENVIRONMENTS","options","trimTrailingSlash","userRef","httpClient","HttpClient","ChainGateway","lenient","Symbols","resolver","CanonicalSymbols","Quoting","Pools","keyOptions","Positions","Swaps","Assets","Market","Leaderboard","Onramper","DexFees","GdexStreamService","value"],"sources":["../../../src/classes/gswap.ts"],"sourcesContent":["import { Assets } from './assets.js';\nimport { DexFees } from './dex_fees.js';\nimport { ChainGateway } from './gateway.js';\nimport { GdexStreamService } from './gdex_stream.js';\nimport { HttpClient } from './http_client.js';\nimport { Leaderboard } from './leaderboard.js';\nimport { Market } from './market.js';\nimport { Onramper } from './onramper.js';\nimport { Pools } from './pools.js';\nimport { Positions } from './positions.js';\nimport { Quoting } from './quoting.js';\nimport type { GalaChainSigner, HttpRequestor, WireOptions } from '@gala-chain/gala-core-sdk';\nimport { CanonicalSymbols, Symbols } from './symbols.js';\nimport type { InvalidEntryHandler } from '../utils/lenient.js';\nimport { userRef } from '../utils/validation.js';\nimport { Swaps } from './swaps.js';\nimport type { GSwapEnv } from '../types/env.js';\nimport { GSWAP_ENVIRONMENTS } from '../types/env.js';\n\n/** Options for constructing a backend-routed SDK client. */\nexport interface GSwapOptions {\n /** Signs every write. Without one, reads work and any write throws `NO_SIGNER`. */\n signer?: GalaChainSigner | undefined;\n /**\n * The selected account, sent as `X-Wallet-Address` on writes (attribution only; the chain\n * recovers the signer from the signature). Required for shadow writes. Any spelling of an\n * Ethereum account (`eth|<40 hex>` in any casing, `0x...`, bare hex) is sent as `eth|<EIP-55>`,\n * `client|<id>` as written; a mixed-case spelling that is not the checksum is refused at\n * construction (`INVALID_WALLET_ADDRESS`), and `eth|0x...` (not an address form) is refused as\n * core's `INVALID_ETH_USER_REF_PREFIX`.\n */\n walletAddress?: string | undefined;\n /** `'stage'` or `'prod'` swap backend preset; defaults to `'prod'`. */\n env?: GSwapEnv | undefined;\n /** Overrides the preset's swap backend base URL (a test or private deployment). */\n dexBackendBaseUrl?: string | undefined;\n /** HTTP transport for every request; defaults to the global `fetch`. */\n httpRequestor?: HttpRequestor | undefined;\n /** Request timeout in milliseconds (default 30 000); `Infinity` arms no timer. */\n chainCallTimeoutMs?: number | undefined;\n /** Query encoding and `User-Agent` of the read requests (see {@link WireOptions}). */\n wire?: WireOptions | undefined;\n /**\n * How tokens are turned into trading symbols. `'registry'` (default) reads the symbol registry\n * once (`GET /v2/trade/symbols`, cached) and accepts symbols or class keys. `'canonical'` makes\n * no registry request: the caller passes the backend's canonical trading symbols (from a quote,\n * an estimate or a position), reads send tokens and ticks exactly as given (composite keys\n * included) and the backend orients the pair; see {@link CanonicalSymbols}.\n */\n symbolResolution?: 'registry' | 'canonical' | undefined;\n /**\n * Told about every row of a pool, symbol, position, price, price-series, season or leaderboard\n * answer that was skipped as unusable (see {@link InvalidEntryHandler}); without it such rows are\n * skipped silently.\n */\n onInvalidEntry?: InvalidEntryHandler | undefined;\n /** Realtime stream endpoint. Defaults to the environment's, or is derived from `dexBackendBaseUrl`. */\n dexBackendWsUrl?: string | undefined;\n /** WebSocket constructor for the realtime stream; required on Node.js older than 22. */\n webSocketImpl?: unknown;\n /**\n * `x-api-key` for the privileged stream view; server-side only, and it requires `webSocketImpl`\n * (see `GdexStreamConfig.apiKey`).\n */\n streamApiKey?: string | undefined;\n /**\n * Prefix of every write's `uniqueKey` (`<prefix><uuid>`). Defaults to `galaswap-operation-`,\n * what the Gala Wallet and the gSwap web app send; the backend does not depend on it.\n */\n uniqueKeyPrefix?: string | undefined;\n}\n\n/**\n * Main entry point for the current GalaChainDex SDK: one client bundling the services that read\n * and write through the swap backend (`quoting`, `swaps`, `pools`, `positions`, `assets`,\n * `market`, `leaderboard`, `onramper`, `symbols`, `fees`, `stream`). See {@link GSwapOptions} for\n * configuration.\n */\nexport class GSwap {\n /** The swap backend base URL every request goes to, without a trailing slash. */\n public readonly dexBackendBaseUrl: string;\n /** The request timeout in milliseconds (default 30 000; `Infinity` arms no timer). */\n public readonly chainCallTimeoutMs: number;\n /** The signer given at construction, if any. */\n public readonly signer: GalaChainSigner | undefined;\n /**\n * The account given at construction, if any, in the gateway's spelling (`eth|<EIP-55>`;\n * `client|<id>` as given).\n */\n public readonly walletAddress: string | undefined;\n /** The chain-gateway client every other service reads and writes through. */\n public readonly gateway: ChainGateway;\n /** The trading-symbol registry. */\n public readonly symbols: Symbols;\n /** Read-only exact-input and exact-output quotes. */\n public readonly quoting: Quoting;\n /** Pool, slot0 and composite-pool reads. */\n public readonly pools: Pools;\n /** Position reads, liquidity estimates and liquidity / pool-creation writes. */\n public readonly positions: Positions;\n /** Queued swaps (`RequestTrade`), dark swaps and swap confirmation. */\n public readonly swaps: Swaps;\n /** User token balances. */\n public readonly assets: Assets;\n /** USD prices, price series and the platform volume totals. */\n public readonly market: Market;\n /** Trading-competition seasons and rankings. */\n public readonly leaderboard: Leaderboard;\n /** The Onramper (fiat on-ramp) widget URL. */\n public readonly onramper: Onramper;\n /** Network-fee quotes (DryRun) signed with this client's signer. */\n public readonly fees: DexFees;\n /** The realtime stream endpoint {@link GSwap.stream} connects to. */\n public readonly dexBackendWsUrl: string;\n private readonly webSocketImpl: unknown;\n private readonly streamApiKey: string | undefined;\n private streamClient: GdexStreamService | undefined;\n\n /**\n * Create an SDK client for prod (the default) or stage, or for a `dexBackendBaseUrl` of your own.\n *\n * @example\n * ```typescript\n * const gSwap = new GSwap({ env: 'stage' });\n * const symbols = await gSwap.symbols.list();\n * ```\n */\n constructor(options?: GSwapOptions) {\n const environment = GSWAP_ENVIRONMENTS[options?.env ?? 'prod'];\n this.dexBackendBaseUrl = trimTrailingSlash(\n options?.dexBackendBaseUrl ?? environment.dexBackendBaseUrl,\n );\n this.chainCallTimeoutMs = options?.chainCallTimeoutMs ?? 30_000;\n this.signer = options?.signer;\n this.walletAddress =\n options?.walletAddress === undefined\n ? undefined\n : userRef(options.walletAddress, 'walletAddress');\n\n const httpClient = new HttpClient(\n options?.httpRequestor,\n this.chainCallTimeoutMs,\n options?.wire,\n );\n this.gateway = new ChainGateway({\n dexBackendBaseUrl: this.dexBackendBaseUrl,\n chainCallTimeoutMs: this.chainCallTimeoutMs,\n ...(options?.wire === undefined ? {} : { wire: options.wire }),\n ...(options?.httpRequestor === undefined ? {} : { httpRequestor: options.httpRequestor }),\n ...(this.walletAddress === undefined ? {} : { walletAddress: this.walletAddress }),\n });\n const lenient = { onInvalidEntry: options?.onInvalidEntry };\n this.symbols = new Symbols(this.gateway, lenient);\n // The services resolve tokens through the registry by default; the offline resolver sends the\n // caller's canonical symbols and keys as they are and never reads the registry.\n const resolver =\n options?.symbolResolution === 'canonical' ? new CanonicalSymbols() : this.symbols;\n this.quoting = new Quoting(this.gateway, resolver);\n this.pools = new Pools(this.gateway, resolver, lenient);\n const keyOptions = { uniqueKeyPrefix: options?.uniqueKeyPrefix, ...lenient };\n this.positions = new Positions(\n this.gateway,\n resolver,\n this.signer,\n this.walletAddress,\n keyOptions,\n );\n this.swaps = new Swaps(this.gateway, resolver, this.signer, this.walletAddress, keyOptions);\n this.assets = new Assets(this.dexBackendBaseUrl, httpClient);\n this.market = new Market(this.dexBackendBaseUrl, httpClient, lenient);\n this.leaderboard = new Leaderboard(this.dexBackendBaseUrl, httpClient, lenient);\n this.onramper = new Onramper(this.dexBackendBaseUrl, httpClient);\n this.fees = new DexFees(this.gateway, this.signer);\n this.dexBackendWsUrl =\n options?.dexBackendWsUrl ??\n (options?.dexBackendBaseUrl === undefined\n ? environment.dexBackendWsUrl\n : `${this.dexBackendBaseUrl.replace(/^http/u, 'ws')}/ws`);\n this.webSocketImpl = options?.webSocketImpl;\n this.streamApiKey = options?.streamApiKey;\n }\n\n /**\n * The realtime stream client for this environment (created on first use, not connected until you\n * call `connect()`).\n *\n * @example\n * ```typescript\n * const gSwap = new GSwap({ env: 'stage' });\n * await gSwap.stream.connect();\n * await gSwap.stream.subscribeLiquidity((event) => console.log(event.action, event.amount0));\n * ```\n */\n get stream(): GdexStreamService {\n this.streamClient ??= new GdexStreamService({\n url: this.dexBackendWsUrl,\n ...(this.webSocketImpl === undefined ? {} : { webSocketImpl: this.webSocketImpl }),\n ...(this.streamApiKey === undefined ? {} : { apiKey: this.streamApiKey }),\n });\n return this.streamClient;\n }\n}\n\nfunction trimTrailingSlash(value: string): string {\n return value.replace(/\\/$/u, '');\n}\n"],"mappings":"A,2uBA8EA,IAAaC,EAAb,KAAmB,CAiDjB,YAAY,EAAwB,CA/CpBD,EAAA,KAAA,oBAAA,IAAA,EAAA,EAEAA,EAAA,KAAA,qBAAA,IAAA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K,YAAa,CACzE,CAAC,GACM,KAAK,YACd,CACF,EAEA,SAASnB,EAAkB,EAAuB,CAChD,OAAOoB,EAAM,QAAQ,OAAQ,EAAE,CACjC,C"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{GALA_ERROR_CATALOG as e}from"@gala-chain/gala-core-sdk";const t=[`timeout`,`transport`],n=`0,500,3000,10000`,r={HTTP_ERROR:{phase:`post_send`,template:`Unexpected HTTP error {status} from {url}.`,params:{status:`number`,url:`string`,serverMessage:`string`},unrendered:[`serverMessage`]},UPDATE_REQUIRED:{phase:`post_send`,template:`The backend refused this app version and requires an update (HTTP {status}); nothing was queued.`,params:{status:`number`}},REQUEST_FAILED:{phase:`in_flight`,template:`The {operation} request failed.`,params:{operation:`string`}},METHOD_NOT_SUPPORTED:{phase:`pre_send`,template:`The method {method} is not supported; swaps are queued through RequestTrade.`,params:{method:`string`}},SUBMISSION_OUTCOME_UNKNOWN:{phase:`in_flight`,template:`The submission outcome is unknown ({reason}): the request may have reached the gateway. Confirm before retrying.`,params:{reason:t}},GATEWAY_REPORTED_ERROR:{phase:`post_send`,template:`The gateway reported an error for this write: {serverMessage}`,params:{serverMessage:`string`}},GATEWAY_DATA_MISSING:{phase:`post_send`,template:`The gateway response is missing its data object.`,params:{}},GATEWAY_MODE_INVALID:{phase:`post_send`,template:`Gateway response must contain data.mode="sync" with data.result, or data.mode="queued".`,params:{}},GATEWAY_SYNC_REQUEST_TRADE:{phase:`post_send`,template:`The gateway executed RequestTrade synchronously, which this SDK refuses; RequestTrade must be queued.`,params:{}},MISSING_UNIQUE_KEY:{phase:`post_send`,template:`The gateway acknowledged RequestTrade without echoing its uniqueKey, so it cannot be tied to the signed request.`,params:{}},UNIQUE_KEY_MISMATCH:{phase:`post_send`,template:`Gateway response data.uniqueKey must match the signed RequestTrade uniqueKey.`,params:{}},SHADOW_NOT_QUEUED:{phase:`post_send`,template:`The swap backend did not queue the shadow request.`,params:{}},SHADOW_SUBMIT_NEEDS_WALLET_ADDRESS:{phase:`pre_send`,template:`A shadow submission needs a walletAddress (the X-Wallet-Address header): pass one to the GSwap constructor or to this call.`,params:{}},METHOD_NOT_ALLOWED:{phase:`post_send`,template:`The gateway does not expose this contract method: {serverMessage}`,params:{serverMessage:`string`}},SIGNATURE_INVALID:{phase:`post_send`,template:`The gateway could not verify the signature: {serverMessage}`,params:{serverMessage:`string`}},SIGNER_MISMATCH:{phase:`post_send`,template:`The recovered signer does not match an actor named by the operation: {serverMessage}`,params:{serverMessage:`string`}},DTO_INVALID:{phase:`post_send`,template:`The gateway rejected the DTO shape: {serverMessage}`,params:{serverMessage:`string`}},BOUNDS_VIOLATION:{phase:`post_send`,template:`The gateway rejected a numeric, tick, symbol or range bound: {serverMessage}`,params:{serverMessage:`string`}},SYMBOL_CONFLICT:{phase:`post_send`,template:`The CreatePool symbol is already owned by another class: {serverMessage}`,params:{serverMessage:`string`}},RATE_LIMITED:{phase:`post_send`,template:`The gateway rate-limited this signer: {serverMessage}`,params:{serverMessage:`string`}},CHAIN_DISPATCH_FAILED:{phase:`post_send`,template:`The chain dispatch failed (chain error key "{errorKey}"): {serverMessage}`,params:{errorKey:`string`,serverMessage:`string`}},GATEWAY_REJECTED:{phase:`post_send`,template:`Gateway rejected {gatewayCode}: {serverMessage}`,params:{gatewayCode:`string`,serverMessage:`string`}},CHAIN_REJECTED:{phase:`post_send`,template:`GalaChain error {errorKey}: {serverMessage}`,params:{errorKey:`string`,serverMessage:`string`}},INVALID_CHAIN_RESPONSE:{phase:`post_send`,template:`Backend returned an invalid {resource}.`,params:{resource:`string`}},INVALID_POSITION_RESPONSE:{phase:`post_send`,template:`Backend returned an invalid position ({reason}).`,params:{reason:`string`}},CONFIRMATION_TIMEOUT:{phase:`post_send`,template:`Transaction confirmation timed out; the trade may still apply. Confirm the same uniqueKey again later instead of resubmitting.`,params:{}},CONFIRMATION_ABORTED:{phase:`post_send`,template:`Transaction confirmation was aborted.`,params:{}},CONFIRMATION_FAILED:{phase:`post_send`,template:`Transaction confirmation failed with HTTP {status}.`,params:{status:`number`,serverMessage:`string`},unrendered:[`serverMessage`]},CONFIRMATION_MALFORMED:{phase:`post_send`,template:`Transaction confirmation returned a malformed body.`,params:{}},CONFIRMATION_KEY_MISMATCH:{phase:`post_send`,template:`Apply result key did not match the requested key.`,params:{}},NO_SIGNER:{phase:`pre_send`,template:`This method requires a signer. Please provide a signer to the GSwap constructor.`,params:{}},NO_WALLET_ADDRESS:{phase:`post_send`,template:`Cannot confirm this write: no walletAddress was provided to the GSwap constructor, so the resulting position cannot be looked up to confirm it landed on chain.`,params:{}},NO_POOL_AVAILABLE:{phase:`post_send`,template:`No pool is available for {tokenIn}/{tokenOut} (fee tier {fee}).`,params:{tokenIn:`string`,tokenOut:`string`,fee:`string`}},INSUFFICIENT_LIQUIDITY:{phase:`post_send`,template:`The selected pool has insufficient liquidity for {tokenIn}/{tokenOut} (fee tier {fee}).`,params:{tokenIn:`string`,tokenOut:`string`,fee:`string`}},UNKNOWN_TOKEN:{phase:`pre_send`,template:`Token {token} is not registered on the DEX contract: it has no trading symbol.`,params:{token:`string`}},SYMBOL_NOT_FOUND:{phase:`pre_send`,template:`Token {token} could not be resolved to a trading symbol.`,params:{token:`string`}},STREAM_API_KEY_UNUSABLE:{phase:`pre_send`,template:`GdexStreamConfig.apiKey needs a non-empty key and an explicit webSocketImpl that accepts upgrade headers as its third argument (the "ws" package, or React Native). A browser WebSocket cannot send x-api-key, so the key would be silently dropped.`,params:{}},STREAM_WEBSOCKET_UNAVAILABLE:{phase:`pre_send`,template:`GdexStreamService requires a standards-compatible WebSocket constructor. Node.js versions before 22 must provide one with config.webSocketImpl (for example, from the "ws" package).`,params:{}},STREAM_NOT_CONNECTED:{phase:`pre_send`,template:`GDEX stream is not connected. Call connect() first.`,params:{}},STREAM_DISCONNECTED:{phase:`in_flight`,template:`GDEX stream disconnected.`,params:{}},STREAM_REQUEST_TIMEOUT:{phase:`in_flight`,template:`GDEX request "{method}" timed out after {timeoutMs} ms.`,params:{method:`string`,timeoutMs:`number`}},STREAM_CONNECT_FAILED:{phase:`in_flight`,template:`Failed to connect to GDEX stream at {url}.`,params:{url:`string`}},STREAM_CLOSED_BEFORE_CONNECT:{phase:`in_flight`,template:`GDEX stream closed before connecting (code {closeCode}).`,params:{closeCode:`number`}},STREAM_CONNECTION_CLOSED:{phase:`in_flight`,template:`GDEX stream connection closed (code {closeCode}).`,params:{closeCode:`number`}},TOKEN_RESOLUTION_FAILED:{phase:`pre_send`,template:`Token {token} could not be looked up; nothing was sent.`,params:{token:`string`}},MISSING_WALLET_ADDRESS:{phase:`pre_send`,template:`Invalid wallet address: No wallet address provided. Either provide a wallet address to the function you are calling, or set one when instantiating GSwapSDK.`,params:{}},NON_CANONICAL_PAIR:{phase:`pre_send`,template:`The pair {token0}/{token1} is not in canonical order: token0 must sort before token1.`,params:{token0:`string`,token1:`string`}},UNORDERABLE_SYMBOLS:{phase:`pre_send`,template:`Unable to order trading symbols: expected a pair of symbols, got {received}.`,params:{received:`string`}},INVALID_TOKEN_CLASS_KEY:{phase:`pre_send`,template:`Invalid token class key "{tokenClassKey}": expected a collection followed by category, type and additionalKey`,params:{tokenClassKey:`string`}},INCOMPLETE_TOKEN_CLASS_KEY:{phase:`pre_send`,template:`Token class key "{compositeKey}" is missing {part}.`,params:{compositeKey:`string`,part:`string`}},INVALID_TRADING_SYMBOL:{phase:`pre_send`,template:`Invalid trading symbol "{symbol}": must be 1-32 ASCII letters and digits and not a reserved word (Token, Unit, none).`,params:{symbol:`string`}},NO_VALID_TRADING_SYMBOL:{phase:`pre_send`,template:`No valid trading symbol for token class {classKey}: "{displaySymbol}" is not an acceptable symbol and none is registered`,params:{classKey:`string`,displaySymbol:`string`}},TOKEN_SYMBOL_NOT_REGISTERED:{phase:`pre_send`,template:`Token {token} is not registered in the trading-symbol registry yet; pass token0Symbol/token1Symbol (the token class symbol) to propose one. A symbol cannot be derived from a class key.`,params:{token:`string`}},SYMBOL_DISAGREES_WITH_REGISTRY:{phase:`pre_send`,template:`Supplied symbol {suppliedSymbol} for {token} disagrees with the registered trading symbol {registeredSymbol}.`,params:{token:`string`,suppliedSymbol:`string`,registeredSymbol:`string`}},CREATE_POOL_NEEDS_CLASS_KEY:{phase:`pre_send`,template:`createPool needs each token as a class key; {token} is a bare trading symbol, which does not carry one.`,params:{token:`string`}},AMOUNT_IS_JS_NUMBER:{phase:`pre_send`,template:`Invalid {field}: use a decimal string or BigNumber, not a JavaScript number`,params:{field:`string`}},AMOUNT_NOT_FINITE:{phase:`pre_send`,template:`Invalid {field}: must be a finite number (got {value})`,params:{field:`string`,value:`string`}},AMOUNT_NOT_POSITIVE:{phase:`pre_send`,template:`Invalid {field}: must be positive (got {value})`,params:{field:`string`,value:`string`}},AMOUNT_NEGATIVE:{phase:`pre_send`,template:`Invalid {field}: must not be negative (got {value})`,params:{field:`string`,value:`string`}},PRICE_VALUES_IS_JS_NUMBER:{phase:`pre_send`,template:`Invalid price values: use decimal strings or BigNumber values, not JavaScript numbers`,params:{}},INVALID_PRICE_VALUES:{phase:`pre_send`,template:`Invalid price values: all prices must be finite and positive (spot {spotPrice}, lower {lowerPrice}, upper {upperPrice})`,params:{spotPrice:`string`,lowerPrice:`string`,upperPrice:`string`}},INVALID_PRICE_RANGE:{phase:`pre_send`,template:`Invalid price range: lower price {lowerPrice} must be less than or equal to upper price {upperPrice}`,params:{lowerPrice:`string`,upperPrice:`string`}},INVALID_PRICE_BOUNDS:{phase:`pre_send`,template:`Price bounds must be finite and positive (minPrice {minPrice}, maxPrice {maxPrice}).`,params:{minPrice:`string`,maxPrice:`string`}},PRICE_BOUNDS_ORDER:{phase:`pre_send`,template:`minPrice {minPrice} must be less than or equal to maxPrice {maxPrice}.`,params:{minPrice:`string`,maxPrice:`string`}},INVALID_STARTING_PRICE:{phase:`pre_send`,template:`Starting price must be finite and positive (got {value}).`,params:{value:`string`}},INVALID_SQRT_PRICE:{phase:`pre_send`,template:`Cannot invert a non-positive sqrt price ({sqrtPrice}).`,params:{sqrtPrice:`string`}},INVALID_TOKEN_DECIMALS:{phase:`pre_send`,template:`Invalid {field}: must be a non-negative integer (got {value})`,params:{field:`string`,value:`number`}},TICKS_NOT_INTEGERS:{phase:`pre_send`,template:`Invalid tick values: ticks must be integers (got {tickLower} and {tickUpper})`,params:{tickLower:`number`,tickUpper:`number`}},INVALID_TICK_RANGE:{phase:`pre_send`,template:`Invalid tick range: tickLower {tickLower} must be less than tickUpper {tickUpper}`,params:{tickLower:`number`,tickUpper:`number`}},TICKS_OUT_OF_BOUNDS:{phase:`pre_send`,template:`Invalid tick range: ticks {tickLower} and {tickUpper} must be between {minTick} and {maxTick}`,params:{tickLower:`number`,tickUpper:`number`,minTick:`number`,maxTick:`number`}},TICKS_NOT_ALIGNED:{phase:`pre_send`,template:`Ticks {tickLower} and {tickUpper} must be aligned to spacing {spacing}.`,params:{tickLower:`number`,tickUpper:`number`,spacing:`number`}},INVALID_TICK_SPACING:{phase:`pre_send`,template:`Invalid tick spacing: must be a positive integer (got {value})`,params:{value:`number`}},INVALID_FEE:{phase:`pre_send`,template:`Invalid {field}: {value} is not a supported fee tier; must be one of {allowed}.`,params:{field:`string`,value:`number`,allowed:`string`}},EXACT_AMOUNT_REQUIRED:{phase:`pre_send`,template:`{field} is required for this swap.`,params:{field:`string`}},EXACTLY_ONE_OF_REQUIRED:{phase:`pre_send`,template:`Provide exactly one of {first} or {second}.`,params:{first:`string`,second:`string`}},AT_MOST_ONE_OF_ALLOWED:{phase:`pre_send`,template:`Provide at most one of {first} or {second}.`,params:{first:`string`,second:`string`}},POOL_MISMATCH:{phase:`pre_send`,template:`tokenIn {tokenIn} and tokenOut {tokenOut} must be the two tokens of the pinned pool {poolToken0}/{poolToken1}.`,params:{tokenIn:`string`,tokenOut:`string`,poolToken0:`string`,poolToken1:`string`}},INVALID_DTO:{phase:`pre_send`,template:`{method} DTO field {field} is invalid (expected {expected}).`,params:{method:`string`,field:`string`,expected:`string`}},DTO_NOT_CANONICAL:{phase:`pre_send`,template:`The {method} DTO is not in the form the SDK builders produce; build it with the matching build function and submit that.`,params:{method:`string`}},SEARCH_TOO_LONG:{phase:`pre_send`,template:`search must be at most {maxLength} characters (got {length}).`,params:{length:`number`,maxLength:`number`}},INVALID_SORT_BY:{phase:`pre_send`,template:`sortBy "{value}" is not allowed; it must be one of {allowed}.`,params:{value:`string`,allowed:`string`}},INVALID_SORT_ORDER:{phase:`pre_send`,template:`sortOrder "{value}" is not allowed; it must be asc or desc.`,params:{value:`string`}},INVALID_PAGE:{phase:`pre_send`,template:`page must be an integer of at least 1 (got {value}).`,params:{value:`number`}},INVALID_LIMIT:{phase:`pre_send`,template:`limit must be an integer from {min} to {max} (got {value}).`,params:{value:`number`,min:`number`,max:`number`}},INVALID_MARKET_TOKEN:{phase:`pre_send`,template:`A market read names a token by a symbol or class key of 1 to 120 letters, digits and . _ $ + / : | - characters (got "{token}").`,params:{token:`string`}},INVALID_TIMEFRAME:{phase:`pre_send`,template:`timeframe "{value}" is not allowed; it must be one of {allowed}.`,params:{value:`string`,allowed:`string`}},INVALID_SEASON_ID:{phase:`pre_send`,template:`seasonId must be an integer of at least 1 (got {value}).`,params:{value:`string`}},INVALID_POLL_INTERVAL:{phase:`pre_send`,template:`intervalMs must be a finite number of milliseconds of at least 1 (got {value}).`,params:{value:`string`}}},i={...e,...r},a=Object.fromEntries(Object.entries(r).map(([e,t])=>[e,t.template]));export{n as ALLOWED_FEE_TIERS_TEXT,r as GSWAP_ERROR_CATALOG,i as GSWAP_SDK_ERROR_ENTRIES,t as SUBMISSION_OUTCOME_UNKNOWN_REASONS,a as gswapErrorTemplates};
|
|
1
|
+
import{GALA_ERROR_CATALOG as e}from"@gala-chain/gala-core-sdk";const t=[`timeout`,`transport`],n=`0,500,3000,10000`,r={HTTP_ERROR:{phase:`post_send`,template:`Unexpected HTTP error {status} from {url}.`,params:{status:`number`,url:`string`,serverMessage:`string`},unrendered:[`serverMessage`]},UPDATE_REQUIRED:{phase:`post_send`,template:`The backend refused this app version and requires an update (HTTP {status}); nothing was queued.`,params:{status:`number`}},REQUEST_FAILED:{phase:`in_flight`,template:`The {operation} request failed.`,params:{operation:`string`}},METHOD_NOT_SUPPORTED:{phase:`pre_send`,template:`The method {method} is not supported; swaps are queued through RequestTrade.`,params:{method:`string`}},SUBMISSION_OUTCOME_UNKNOWN:{phase:`in_flight`,template:`The submission outcome is unknown ({reason}): the request may have reached the gateway. Confirm before retrying.`,params:{reason:t}},GATEWAY_REPORTED_ERROR:{phase:`post_send`,template:`The gateway reported an error for this write: {serverMessage}`,params:{serverMessage:`string`}},GATEWAY_DATA_MISSING:{phase:`post_send`,template:`The gateway response is missing its data object.`,params:{}},GATEWAY_MODE_INVALID:{phase:`post_send`,template:`Gateway response must contain data.mode="sync" with data.result, or data.mode="queued".`,params:{}},GATEWAY_SYNC_REQUEST_TRADE:{phase:`post_send`,template:`The gateway executed RequestTrade synchronously, which this SDK refuses; RequestTrade must be queued.`,params:{}},MISSING_UNIQUE_KEY:{phase:`post_send`,template:`The gateway acknowledged RequestTrade without echoing its uniqueKey, so it cannot be tied to the signed request.`,params:{}},UNIQUE_KEY_MISMATCH:{phase:`post_send`,template:`Gateway response data.uniqueKey must match the signed RequestTrade uniqueKey.`,params:{}},SHADOW_NOT_QUEUED:{phase:`post_send`,template:`The swap backend did not queue the shadow request.`,params:{}},SHADOW_SUBMIT_NEEDS_WALLET_ADDRESS:{phase:`pre_send`,template:`A shadow submission needs a walletAddress (the X-Wallet-Address header): pass one to the GSwap constructor or to this call.`,params:{}},METHOD_NOT_ALLOWED:{phase:`post_send`,template:`The gateway does not expose this contract method: {serverMessage}`,params:{serverMessage:`string`}},SIGNATURE_INVALID:{phase:`post_send`,template:`The gateway could not verify the signature: {serverMessage}`,params:{serverMessage:`string`}},SIGNER_MISMATCH:{phase:`post_send`,template:`The recovered signer does not match an actor named by the operation: {serverMessage}`,params:{serverMessage:`string`}},DTO_INVALID:{phase:`post_send`,template:`The gateway rejected the DTO shape: {serverMessage}`,params:{serverMessage:`string`}},DTO_OPERATION_MISMATCH:{phase:`post_send`,template:`The signed DTO has no dtoOperation, or one that is not the call it was sent to: {serverMessage}`,params:{serverMessage:`string`}},BOUNDS_VIOLATION:{phase:`post_send`,template:`The gateway rejected a numeric, tick, symbol or range bound: {serverMessage}`,params:{serverMessage:`string`}},SYMBOL_CONFLICT:{phase:`post_send`,template:`The CreatePool symbol is already owned by another class: {serverMessage}`,params:{serverMessage:`string`}},RATE_LIMITED:{phase:`post_send`,template:`The gateway rate-limited this signer: {serverMessage}`,params:{serverMessage:`string`}},CHAIN_DISPATCH_FAILED:{phase:`post_send`,template:`The chain dispatch failed (chain error key "{errorKey}"): {serverMessage}`,params:{errorKey:`string`,serverMessage:`string`}},GATEWAY_REJECTED:{phase:`post_send`,template:`Gateway rejected {gatewayCode}: {serverMessage}`,params:{gatewayCode:`string`,serverMessage:`string`}},CHAIN_REJECTED:{phase:`post_send`,template:`GalaChain error {errorKey}: {serverMessage}`,params:{errorKey:`string`,serverMessage:`string`}},INVALID_CHAIN_RESPONSE:{phase:`post_send`,template:`Backend returned an invalid {resource}.`,params:{resource:`string`}},INVALID_POSITION_RESPONSE:{phase:`post_send`,template:`Backend returned an invalid position ({reason}).`,params:{reason:`string`}},CONFIRMATION_TIMEOUT:{phase:`post_send`,template:`Transaction confirmation timed out; the trade may still apply. Confirm the same uniqueKey again later instead of resubmitting.`,params:{}},CONFIRMATION_ABORTED:{phase:`post_send`,template:`Transaction confirmation was aborted.`,params:{}},CONFIRMATION_FAILED:{phase:`post_send`,template:`Transaction confirmation failed with HTTP {status}.`,params:{status:`number`,serverMessage:`string`},unrendered:[`serverMessage`]},CONFIRMATION_MALFORMED:{phase:`post_send`,template:`Transaction confirmation returned a malformed body.`,params:{}},CONFIRMATION_KEY_MISMATCH:{phase:`post_send`,template:`Apply result key did not match the requested key.`,params:{}},NO_SIGNER:{phase:`pre_send`,template:`This method requires a signer. Please provide a signer to the GSwap constructor.`,params:{}},NO_WALLET_ADDRESS:{phase:`post_send`,template:`Cannot confirm this write: no walletAddress was provided to the GSwap constructor, so the resulting position cannot be looked up to confirm it landed on chain.`,params:{}},NO_POOL_AVAILABLE:{phase:`post_send`,template:`No pool is available for {tokenIn}/{tokenOut} (fee tier {fee}).`,params:{tokenIn:`string`,tokenOut:`string`,fee:`string`}},INSUFFICIENT_LIQUIDITY:{phase:`post_send`,template:`The selected pool has insufficient liquidity for {tokenIn}/{tokenOut} (fee tier {fee}).`,params:{tokenIn:`string`,tokenOut:`string`,fee:`string`}},UNKNOWN_TOKEN:{phase:`pre_send`,template:`Token {token} is not registered on the DEX contract: it has no trading symbol.`,params:{token:`string`}},SYMBOL_NOT_FOUND:{phase:`pre_send`,template:`Token {token} could not be resolved to a trading symbol.`,params:{token:`string`}},STREAM_API_KEY_UNUSABLE:{phase:`pre_send`,template:`GdexStreamConfig.apiKey needs a non-empty key and an explicit webSocketImpl that accepts upgrade headers as its third argument (the "ws" package, or React Native). A browser WebSocket cannot send x-api-key, so the key would be silently dropped.`,params:{}},STREAM_WEBSOCKET_UNAVAILABLE:{phase:`pre_send`,template:`GdexStreamService requires a standards-compatible WebSocket constructor. Node.js versions before 22 must provide one with config.webSocketImpl (for example, from the "ws" package).`,params:{}},STREAM_NOT_CONNECTED:{phase:`pre_send`,template:`GDEX stream is not connected. Call connect() first.`,params:{}},STREAM_DISCONNECTED:{phase:`in_flight`,template:`GDEX stream disconnected.`,params:{}},STREAM_REQUEST_TIMEOUT:{phase:`in_flight`,template:`GDEX request "{method}" timed out after {timeoutMs} ms.`,params:{method:`string`,timeoutMs:`number`}},STREAM_CONNECT_FAILED:{phase:`in_flight`,template:`Failed to connect to GDEX stream at {url}.`,params:{url:`string`}},STREAM_CLOSED_BEFORE_CONNECT:{phase:`in_flight`,template:`GDEX stream closed before connecting (code {closeCode}).`,params:{closeCode:`number`}},STREAM_CONNECTION_CLOSED:{phase:`in_flight`,template:`GDEX stream connection closed (code {closeCode}).`,params:{closeCode:`number`}},TOKEN_RESOLUTION_FAILED:{phase:`pre_send`,template:`Token {token} could not be looked up; nothing was sent.`,params:{token:`string`}},MISSING_WALLET_ADDRESS:{phase:`pre_send`,template:`Invalid wallet address: No wallet address provided. Either provide a wallet address to the function you are calling, or set one when instantiating GSwapSDK.`,params:{}},NON_CANONICAL_PAIR:{phase:`pre_send`,template:`The pair {token0}/{token1} is not in canonical order: token0 must sort before token1.`,params:{token0:`string`,token1:`string`}},UNORDERABLE_SYMBOLS:{phase:`pre_send`,template:`Unable to order trading symbols: expected a pair of symbols, got {received}.`,params:{received:`string`}},INVALID_TOKEN_CLASS_KEY:{phase:`pre_send`,template:`Invalid token class key "{tokenClassKey}": expected a collection followed by category, type and additionalKey`,params:{tokenClassKey:`string`}},INCOMPLETE_TOKEN_CLASS_KEY:{phase:`pre_send`,template:`Token class key "{compositeKey}" is missing {part}.`,params:{compositeKey:`string`,part:`string`}},INVALID_TRADING_SYMBOL:{phase:`pre_send`,template:`Invalid trading symbol "{symbol}": must be 1-32 ASCII letters and digits and not a reserved word (Token, Unit, none).`,params:{symbol:`string`}},NO_VALID_TRADING_SYMBOL:{phase:`pre_send`,template:`No valid trading symbol for token class {classKey}: "{displaySymbol}" is not an acceptable symbol and none is registered`,params:{classKey:`string`,displaySymbol:`string`}},TOKEN_SYMBOL_NOT_REGISTERED:{phase:`pre_send`,template:`Token {token} is not registered in the trading-symbol registry yet; pass token0Symbol/token1Symbol (the token class symbol) to propose one. A symbol cannot be derived from a class key.`,params:{token:`string`}},SYMBOL_DISAGREES_WITH_REGISTRY:{phase:`pre_send`,template:`Supplied symbol {suppliedSymbol} for {token} disagrees with the registered trading symbol {registeredSymbol}.`,params:{token:`string`,suppliedSymbol:`string`,registeredSymbol:`string`}},CREATE_POOL_NEEDS_CLASS_KEY:{phase:`pre_send`,template:`createPool needs each token as a class key; {token} is a bare trading symbol, which does not carry one.`,params:{token:`string`}},AMOUNT_IS_JS_NUMBER:{phase:`pre_send`,template:`Invalid {field}: use a decimal string or BigNumber, not a JavaScript number`,params:{field:`string`}},AMOUNT_NOT_FINITE:{phase:`pre_send`,template:`Invalid {field}: must be a finite number (got {value})`,params:{field:`string`,value:`string`}},AMOUNT_NOT_POSITIVE:{phase:`pre_send`,template:`Invalid {field}: must be positive (got {value})`,params:{field:`string`,value:`string`}},AMOUNT_NEGATIVE:{phase:`pre_send`,template:`Invalid {field}: must not be negative (got {value})`,params:{field:`string`,value:`string`}},PRICE_VALUES_IS_JS_NUMBER:{phase:`pre_send`,template:`Invalid price values: use decimal strings or BigNumber values, not JavaScript numbers`,params:{}},INVALID_PRICE_VALUES:{phase:`pre_send`,template:`Invalid price values: all prices must be finite and positive (spot {spotPrice}, lower {lowerPrice}, upper {upperPrice})`,params:{spotPrice:`string`,lowerPrice:`string`,upperPrice:`string`}},INVALID_PRICE_RANGE:{phase:`pre_send`,template:`Invalid price range: lower price {lowerPrice} must be less than or equal to upper price {upperPrice}`,params:{lowerPrice:`string`,upperPrice:`string`}},INVALID_PRICE_BOUNDS:{phase:`pre_send`,template:`Price bounds must be finite and positive (minPrice {minPrice}, maxPrice {maxPrice}).`,params:{minPrice:`string`,maxPrice:`string`}},PRICE_BOUNDS_ORDER:{phase:`pre_send`,template:`minPrice {minPrice} must be less than or equal to maxPrice {maxPrice}.`,params:{minPrice:`string`,maxPrice:`string`}},INVALID_STARTING_PRICE:{phase:`pre_send`,template:`Starting price must be finite and positive (got {value}).`,params:{value:`string`}},INVALID_SQRT_PRICE:{phase:`pre_send`,template:`Cannot invert a non-positive sqrt price ({sqrtPrice}).`,params:{sqrtPrice:`string`}},INVALID_TOKEN_DECIMALS:{phase:`pre_send`,template:`Invalid {field}: must be a non-negative integer (got {value})`,params:{field:`string`,value:`number`}},TICKS_NOT_INTEGERS:{phase:`pre_send`,template:`Invalid tick values: ticks must be integers (got {tickLower} and {tickUpper})`,params:{tickLower:`number`,tickUpper:`number`}},INVALID_TICK_RANGE:{phase:`pre_send`,template:`Invalid tick range: tickLower {tickLower} must be less than tickUpper {tickUpper}`,params:{tickLower:`number`,tickUpper:`number`}},TICKS_OUT_OF_BOUNDS:{phase:`pre_send`,template:`Invalid tick range: ticks {tickLower} and {tickUpper} must be between {minTick} and {maxTick}`,params:{tickLower:`number`,tickUpper:`number`,minTick:`number`,maxTick:`number`}},TICKS_NOT_ALIGNED:{phase:`pre_send`,template:`Ticks {tickLower} and {tickUpper} must be aligned to spacing {spacing}.`,params:{tickLower:`number`,tickUpper:`number`,spacing:`number`}},INVALID_TICK_SPACING:{phase:`pre_send`,template:`Invalid tick spacing: must be a positive integer (got {value})`,params:{value:`number`}},INVALID_FEE:{phase:`pre_send`,template:`Invalid {field}: {value} is not a supported fee tier; must be one of {allowed}.`,params:{field:`string`,value:`number`,allowed:`string`}},EXACT_AMOUNT_REQUIRED:{phase:`pre_send`,template:`{field} is required for this swap.`,params:{field:`string`}},EXACTLY_ONE_OF_REQUIRED:{phase:`pre_send`,template:`Provide exactly one of {first} or {second}.`,params:{first:`string`,second:`string`}},AT_MOST_ONE_OF_ALLOWED:{phase:`pre_send`,template:`Provide at most one of {first} or {second}.`,params:{first:`string`,second:`string`}},POOL_MISMATCH:{phase:`pre_send`,template:`tokenIn {tokenIn} and tokenOut {tokenOut} must be the two tokens of the pinned pool {poolToken0}/{poolToken1}.`,params:{tokenIn:`string`,tokenOut:`string`,poolToken0:`string`,poolToken1:`string`}},INVALID_DTO:{phase:`pre_send`,template:`{method} DTO field {field} is invalid (expected {expected}).`,params:{method:`string`,field:`string`,expected:`string`}},DTO_NOT_CANONICAL:{phase:`pre_send`,template:`The {method} DTO is not in the form the SDK builders produce; build it with the matching build function and submit that.`,params:{method:`string`}},SEARCH_TOO_LONG:{phase:`pre_send`,template:`search must be at most {maxLength} characters (got {length}).`,params:{length:`number`,maxLength:`number`}},INVALID_SORT_BY:{phase:`pre_send`,template:`sortBy "{value}" is not allowed; it must be one of {allowed}.`,params:{value:`string`,allowed:`string`}},INVALID_SORT_ORDER:{phase:`pre_send`,template:`sortOrder "{value}" is not allowed; it must be asc or desc.`,params:{value:`string`}},INVALID_PAGE:{phase:`pre_send`,template:`page must be an integer of at least 1 (got {value}).`,params:{value:`number`}},INVALID_LIMIT:{phase:`pre_send`,template:`limit must be an integer from {min} to {max} (got {value}).`,params:{value:`number`,min:`number`,max:`number`}},INVALID_MARKET_TOKEN:{phase:`pre_send`,template:`A market read names a token by a symbol or class key of 1 to 120 letters, digits and . _ $ + / : | - characters (got "{token}").`,params:{token:`string`}},INVALID_TIMEFRAME:{phase:`pre_send`,template:`timeframe "{value}" is not allowed; it must be one of {allowed}.`,params:{value:`string`,allowed:`string`}},INVALID_SEASON_ID:{phase:`pre_send`,template:`seasonId must be an integer of at least 1 (got {value}).`,params:{value:`string`}},INVALID_POLL_INTERVAL:{phase:`pre_send`,template:`intervalMs must be a finite number of milliseconds of at least 1 (got {value}).`,params:{value:`string`}}},i={...e,...r},a=Object.fromEntries(Object.entries(r).map(([e,t])=>[e,t.template]));export{n as ALLOWED_FEE_TIERS_TEXT,r as GSWAP_ERROR_CATALOG,i as GSWAP_SDK_ERROR_ENTRIES,t as SUBMISSION_OUTCOME_UNKNOWN_REASONS,a as gswapErrorTemplates};
|
|
2
2
|
//# sourceMappingURL=gswap_error_catalog.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"gswap_error_catalog.js","names":["SUBMISSION_OUTCOME_UNKNOWN_REASONS","ALLOWED_FEE_TIERS_TEXT","GSWAP_ERROR_CATALOG","GSWAP_SDK_ERROR_ENTRIES","GALA_ERROR_CATALOG","gswapErrorTemplates","code","entry"],"sources":["../../../src/classes/gswap_error_catalog.ts"],"sourcesContent":["/**\n * The catalog of every error code gswap-sdk ITSELF throws (the DEX codes): the SINGLE source of\n * truth for its `code`, the named parameters it carries and the English template its `message` is\n * generated from. The codes of the signing, transport and wallet layer (`INVALID_PRIVATE_KEY`,\n * `REQUEST_TIMEOUT`, `SIGNING_FAILED`, `TYPED_DATA_*`, ...) live in `@gala-chain/gala-core-sdk`'s\n * `GALA_ERROR_CATALOG`; no code is defined in both. A `GSwapSDKError` can carry a code of either\n * catalog (`GSwapErrorCode` is the union), and reads its template from both.\n *\n * - `code` is the only discriminator. It is stable: apps branch on it, never on message text.\n * - `params` are the named placeholders of the error: a flat object of primitives (string,\n * number, boolean) that an app feeds to its own localization (i18next, ICU, FormatJS).\n * Raw server payloads are never params (they are `error.body` / `error.bodyText`), and no\n * secret (private key, signature, raw DTO) ever is.\n * - `template` is English with `{placeholder}` markers. `error.message` is generated from it\n * and the params, so the two cannot drift. It is for logs and developers: it is not stable and\n * must not be shown to users or matched on.\n *\n * Every placeholder in a template is a declared param and every declared param is a placeholder,\n * except the few `unrendered` params that carry server text for the app and are kept out of\n * `message` on purpose (pinned by tests/error_catalog.test.ts). Facts that are not placeholders (HTTP status, URL,\n * `uniqueKey`, transaction ids, the raw body, the cause) are typed properties of the error, see\n * `GalaErrorContext`.\n */\n\nimport {\n GALA_ERROR_CATALOG,\n type ErrorParamsOf,\n type GalaErrorCatalogEntry,\n type GalaErrorCode,\n} from '@gala-chain/gala-core-sdk';\n\n/**\n * Why the outcome of a write submission is unknown (`SUBMISSION_OUTCOME_UNKNOWN.params.reason`).\n * Both say the same thing about the swap (it MAY have been queued: never resubmit under a fresh\n * key, confirm `error.uniqueKey` instead) and differ only in what happened to the request.\n *\n * - `timeout`: the POST exceeded the gateway's timeout; the request may still be running.\n * - `transport`: the POST failed before an HTTP answer was read (offline, connection reset, DNS,\n * CORS, a body that broke off). The bytes may have reached the server and been queued, so this\n * does NOT prove the swap was not sent.\n */\nexport const SUBMISSION_OUTCOME_UNKNOWN_REASONS = ['timeout', 'transport'] as const;\n\n/** One member of {@link SUBMISSION_OUTCOME_UNKNOWN_REASONS}. */\nexport type SubmissionOutcomeUnknownReason = (typeof SUBMISSION_OUTCOME_UNKNOWN_REASONS)[number];\n\n/** The fee tiers as they appear in `INVALID_FEE.allowed`. */\nexport const ALLOWED_FEE_TIERS_TEXT = '0,500,3000,10000';\n\n/** The whole DEX catalog. Add a code here before throwing it anywhere in gswap-sdk. */\nexport const GSWAP_ERROR_CATALOG = {\n // ---------------------------------------------------------------------------------- transport\n HTTP_ERROR: {\n phase: 'post_send',\n template: 'Unexpected HTTP error {status} from {url}.',\n params: { status: 'number', url: 'string', serverMessage: 'string' },\n unrendered: ['serverMessage'],\n },\n UPDATE_REQUIRED: {\n phase: 'post_send',\n template:\n 'The backend refused this app version and requires an update (HTTP {status}); nothing was queued.',\n params: { status: 'number' },\n },\n REQUEST_FAILED: {\n phase: 'in_flight',\n template: 'The {operation} request failed.',\n params: { operation: 'string' },\n },\n\n // ----------------------------------------------------------------------------------- gateway\n METHOD_NOT_SUPPORTED: {\n phase: 'pre_send',\n template: 'The method {method} is not supported; swaps are queued through RequestTrade.',\n params: { method: 'string' },\n },\n SUBMISSION_OUTCOME_UNKNOWN: {\n phase: 'in_flight',\n template:\n 'The submission outcome is unknown ({reason}): the request may have reached the gateway. Confirm before retrying.',\n params: { reason: SUBMISSION_OUTCOME_UNKNOWN_REASONS },\n },\n GATEWAY_REPORTED_ERROR: {\n phase: 'post_send',\n template: 'The gateway reported an error for this write: {serverMessage}',\n params: { serverMessage: 'string' },\n },\n GATEWAY_DATA_MISSING: {\n phase: 'post_send',\n template: 'The gateway response is missing its data object.',\n params: {},\n },\n GATEWAY_MODE_INVALID: {\n phase: 'post_send',\n template:\n 'Gateway response must contain data.mode=\"sync\" with data.result, or data.mode=\"queued\".',\n params: {},\n },\n GATEWAY_SYNC_REQUEST_TRADE: {\n phase: 'post_send',\n template:\n 'The gateway executed RequestTrade synchronously, which this SDK refuses; RequestTrade must be queued.',\n params: {},\n },\n MISSING_UNIQUE_KEY: {\n phase: 'post_send',\n template:\n 'The gateway acknowledged RequestTrade without echoing its uniqueKey, so it cannot be tied to the signed request.',\n params: {},\n },\n UNIQUE_KEY_MISMATCH: {\n phase: 'post_send',\n template: 'Gateway response data.uniqueKey must match the signed RequestTrade uniqueKey.',\n params: {},\n },\n SHADOW_NOT_QUEUED: {\n phase: 'post_send',\n template: 'The swap backend did not queue the shadow request.',\n params: {},\n },\n SHADOW_SUBMIT_NEEDS_WALLET_ADDRESS: {\n phase: 'pre_send',\n template:\n 'A shadow submission needs a walletAddress (the X-Wallet-Address header): pass one to the GSwap constructor or to this call.',\n params: {},\n },\n METHOD_NOT_ALLOWED: {\n phase: 'post_send',\n template: 'The gateway does not expose this contract method: {serverMessage}',\n params: { serverMessage: 'string' },\n },\n SIGNATURE_INVALID: {\n phase: 'post_send',\n template: 'The gateway could not verify the signature: {serverMessage}',\n params: { serverMessage: 'string' },\n },\n SIGNER_MISMATCH: {\n phase: 'post_send',\n template:\n 'The recovered signer does not match an actor named by the operation: {serverMessage}',\n params: { serverMessage: 'string' },\n },\n DTO_INVALID: {\n phase: 'post_send',\n template: 'The gateway rejected the DTO shape: {serverMessage}',\n params: { serverMessage: 'string' },\n },\n BOUNDS_VIOLATION: {\n phase: 'post_send',\n template: 'The gateway rejected a numeric, tick, symbol or range bound: {serverMessage}',\n params: { serverMessage: 'string' },\n },\n SYMBOL_CONFLICT: {\n phase: 'post_send',\n template: 'The CreatePool symbol is already owned by another class: {serverMessage}',\n params: { serverMessage: 'string' },\n },\n RATE_LIMITED: {\n phase: 'post_send',\n template: 'The gateway rate-limited this signer: {serverMessage}',\n params: { serverMessage: 'string' },\n },\n CHAIN_DISPATCH_FAILED: {\n phase: 'post_send',\n template: 'The chain dispatch failed (chain error key \"{errorKey}\"): {serverMessage}',\n params: { errorKey: 'string', serverMessage: 'string' },\n },\n GATEWAY_REJECTED: {\n phase: 'post_send',\n template: 'Gateway rejected {gatewayCode}: {serverMessage}',\n params: { gatewayCode: 'string', serverMessage: 'string' },\n },\n CHAIN_REJECTED: {\n phase: 'post_send',\n template: 'GalaChain error {errorKey}: {serverMessage}',\n params: { errorKey: 'string', serverMessage: 'string' },\n },\n INVALID_CHAIN_RESPONSE: {\n phase: 'post_send',\n template: 'Backend returned an invalid {resource}.',\n params: { resource: 'string' },\n },\n INVALID_POSITION_RESPONSE: {\n phase: 'post_send',\n template: 'Backend returned an invalid position ({reason}).',\n params: { reason: 'string' },\n },\n\n // -------------------------------------------------------------------------------- confirmation\n CONFIRMATION_TIMEOUT: {\n phase: 'post_send',\n template:\n 'Transaction confirmation timed out; the trade may still apply. Confirm the same uniqueKey again later instead of resubmitting.',\n params: {},\n },\n CONFIRMATION_ABORTED: {\n phase: 'post_send',\n template: 'Transaction confirmation was aborted.',\n params: {},\n },\n CONFIRMATION_FAILED: {\n phase: 'post_send',\n template: 'Transaction confirmation failed with HTTP {status}.',\n params: { status: 'number', serverMessage: 'string' },\n unrendered: ['serverMessage'],\n },\n CONFIRMATION_MALFORMED: {\n phase: 'post_send',\n template: 'Transaction confirmation returned a malformed body.',\n params: {},\n },\n CONFIRMATION_KEY_MISMATCH: {\n phase: 'post_send',\n template: 'Apply result key did not match the requested key.',\n params: {},\n },\n\n // ----------------------------------------------------------------------------------- services\n NO_SIGNER: {\n phase: 'pre_send',\n template: 'This method requires a signer. Please provide a signer to the GSwap constructor.',\n params: {},\n },\n NO_WALLET_ADDRESS: {\n phase: 'post_send',\n template:\n 'Cannot confirm this write: no walletAddress was provided to the GSwap constructor, so the resulting position cannot be looked up to confirm it landed on chain.',\n params: {},\n },\n NO_POOL_AVAILABLE: {\n phase: 'post_send',\n template: 'No pool is available for {tokenIn}/{tokenOut} (fee tier {fee}).',\n params: { tokenIn: 'string', tokenOut: 'string', fee: 'string' },\n },\n INSUFFICIENT_LIQUIDITY: {\n phase: 'post_send',\n template:\n 'The selected pool has insufficient liquidity for {tokenIn}/{tokenOut} (fee tier {fee}).',\n params: { tokenIn: 'string', tokenOut: 'string', fee: 'string' },\n },\n UNKNOWN_TOKEN: {\n phase: 'pre_send',\n template: 'Token {token} is not registered on the DEX contract: it has no trading symbol.',\n params: { token: 'string' },\n },\n SYMBOL_NOT_FOUND: {\n phase: 'pre_send',\n template: 'Token {token} could not be resolved to a trading symbol.',\n params: { token: 'string' },\n },\n STREAM_API_KEY_UNUSABLE: {\n phase: 'pre_send',\n template:\n 'GdexStreamConfig.apiKey needs a non-empty key and an explicit webSocketImpl that accepts upgrade headers as its third argument (the \"ws\" package, or React Native). A browser WebSocket cannot send x-api-key, so the key would be silently dropped.',\n params: {},\n },\n STREAM_WEBSOCKET_UNAVAILABLE: {\n phase: 'pre_send',\n template:\n 'GdexStreamService requires a standards-compatible WebSocket constructor. Node.js versions before 22 must provide one with config.webSocketImpl (for example, from the \"ws\" package).',\n params: {},\n },\n STREAM_NOT_CONNECTED: {\n phase: 'pre_send',\n template: 'GDEX stream is not connected. Call connect() first.',\n params: {},\n },\n STREAM_DISCONNECTED: {\n phase: 'in_flight',\n template: 'GDEX stream disconnected.',\n params: {},\n },\n STREAM_REQUEST_TIMEOUT: {\n phase: 'in_flight',\n template: 'GDEX request \"{method}\" timed out after {timeoutMs} ms.',\n params: { method: 'string', timeoutMs: 'number' },\n },\n STREAM_CONNECT_FAILED: {\n phase: 'in_flight',\n template: 'Failed to connect to GDEX stream at {url}.',\n params: { url: 'string' },\n },\n STREAM_CLOSED_BEFORE_CONNECT: {\n phase: 'in_flight',\n template: 'GDEX stream closed before connecting (code {closeCode}).',\n params: { closeCode: 'number' },\n },\n STREAM_CONNECTION_CLOSED: {\n phase: 'in_flight',\n template: 'GDEX stream connection closed (code {closeCode}).',\n params: { closeCode: 'number' },\n },\n\n // ------------------------------------------------------------------------------ wallet / keys\n TOKEN_RESOLUTION_FAILED: {\n phase: 'pre_send',\n template: 'Token {token} could not be looked up; nothing was sent.',\n params: { token: 'string' },\n },\n MISSING_WALLET_ADDRESS: {\n phase: 'pre_send',\n template:\n 'Invalid wallet address: No wallet address provided. Either provide a wallet address to the function you are calling, or set one when instantiating GSwapSDK.',\n params: {},\n },\n\n // ------------------------------------------------------------------------ input validation\n NON_CANONICAL_PAIR: {\n phase: 'pre_send',\n template:\n 'The pair {token0}/{token1} is not in canonical order: token0 must sort before token1.',\n params: { token0: 'string', token1: 'string' },\n },\n UNORDERABLE_SYMBOLS: {\n phase: 'pre_send',\n template: 'Unable to order trading symbols: expected a pair of symbols, got {received}.',\n params: { received: 'string' },\n },\n INVALID_TOKEN_CLASS_KEY: {\n phase: 'pre_send',\n template:\n 'Invalid token class key \"{tokenClassKey}\": expected a collection followed by category, type and additionalKey',\n params: { tokenClassKey: 'string' },\n },\n INCOMPLETE_TOKEN_CLASS_KEY: {\n phase: 'pre_send',\n template: 'Token class key \"{compositeKey}\" is missing {part}.',\n params: { compositeKey: 'string', part: 'string' },\n },\n INVALID_TRADING_SYMBOL: {\n phase: 'pre_send',\n template:\n 'Invalid trading symbol \"{symbol}\": must be 1-32 ASCII letters and digits and not a reserved word (Token, Unit, none).',\n params: { symbol: 'string' },\n },\n NO_VALID_TRADING_SYMBOL: {\n phase: 'pre_send',\n template:\n 'No valid trading symbol for token class {classKey}: \"{displaySymbol}\" is not an acceptable symbol and none is registered',\n params: { classKey: 'string', displaySymbol: 'string' },\n },\n TOKEN_SYMBOL_NOT_REGISTERED: {\n phase: 'pre_send',\n template:\n 'Token {token} is not registered in the trading-symbol registry yet; pass token0Symbol/token1Symbol (the token class symbol) to propose one. A symbol cannot be derived from a class key.',\n params: { token: 'string' },\n },\n SYMBOL_DISAGREES_WITH_REGISTRY: {\n phase: 'pre_send',\n template:\n 'Supplied symbol {suppliedSymbol} for {token} disagrees with the registered trading symbol {registeredSymbol}.',\n params: { token: 'string', suppliedSymbol: 'string', registeredSymbol: 'string' },\n },\n CREATE_POOL_NEEDS_CLASS_KEY: {\n phase: 'pre_send',\n template:\n 'createPool needs each token as a class key; {token} is a bare trading symbol, which does not carry one.',\n params: { token: 'string' },\n },\n AMOUNT_IS_JS_NUMBER: {\n phase: 'pre_send',\n template: 'Invalid {field}: use a decimal string or BigNumber, not a JavaScript number',\n params: { field: 'string' },\n },\n AMOUNT_NOT_FINITE: {\n phase: 'pre_send',\n template: 'Invalid {field}: must be a finite number (got {value})',\n params: { field: 'string', value: 'string' },\n },\n AMOUNT_NOT_POSITIVE: {\n phase: 'pre_send',\n template: 'Invalid {field}: must be positive (got {value})',\n params: { field: 'string', value: 'string' },\n },\n AMOUNT_NEGATIVE: {\n phase: 'pre_send',\n template: 'Invalid {field}: must not be negative (got {value})',\n params: { field: 'string', value: 'string' },\n },\n PRICE_VALUES_IS_JS_NUMBER: {\n phase: 'pre_send',\n template:\n 'Invalid price values: use decimal strings or BigNumber values, not JavaScript numbers',\n params: {},\n },\n INVALID_PRICE_VALUES: {\n phase: 'pre_send',\n template:\n 'Invalid price values: all prices must be finite and positive (spot {spotPrice}, lower {lowerPrice}, upper {upperPrice})',\n params: { spotPrice: 'string', lowerPrice: 'string', upperPrice: 'string' },\n },\n INVALID_PRICE_RANGE: {\n phase: 'pre_send',\n template:\n 'Invalid price range: lower price {lowerPrice} must be less than or equal to upper price {upperPrice}',\n params: { lowerPrice: 'string', upperPrice: 'string' },\n },\n INVALID_PRICE_BOUNDS: {\n phase: 'pre_send',\n template:\n 'Price bounds must be finite and positive (minPrice {minPrice}, maxPrice {maxPrice}).',\n params: { minPrice: 'string', maxPrice: 'string' },\n },\n PRICE_BOUNDS_ORDER: {\n phase: 'pre_send',\n template: 'minPrice {minPrice} must be less than or equal to maxPrice {maxPrice}.',\n params: { minPrice: 'string', maxPrice: 'string' },\n },\n INVALID_STARTING_PRICE: {\n phase: 'pre_send',\n template: 'Starting price must be finite and positive (got {value}).',\n params: { value: 'string' },\n },\n INVALID_SQRT_PRICE: {\n phase: 'pre_send',\n template: 'Cannot invert a non-positive sqrt price ({sqrtPrice}).',\n params: { sqrtPrice: 'string' },\n },\n INVALID_TOKEN_DECIMALS: {\n phase: 'pre_send',\n template: 'Invalid {field}: must be a non-negative integer (got {value})',\n params: { field: 'string', value: 'number' },\n },\n TICKS_NOT_INTEGERS: {\n phase: 'pre_send',\n template: 'Invalid tick values: ticks must be integers (got {tickLower} and {tickUpper})',\n params: { tickLower: 'number', tickUpper: 'number' },\n },\n INVALID_TICK_RANGE: {\n phase: 'pre_send',\n template: 'Invalid tick range: tickLower {tickLower} must be less than tickUpper {tickUpper}',\n params: { tickLower: 'number', tickUpper: 'number' },\n },\n TICKS_OUT_OF_BOUNDS: {\n phase: 'pre_send',\n template:\n 'Invalid tick range: ticks {tickLower} and {tickUpper} must be between {minTick} and {maxTick}',\n params: { tickLower: 'number', tickUpper: 'number', minTick: 'number', maxTick: 'number' },\n },\n TICKS_NOT_ALIGNED: {\n phase: 'pre_send',\n template: 'Ticks {tickLower} and {tickUpper} must be aligned to spacing {spacing}.',\n params: { tickLower: 'number', tickUpper: 'number', spacing: 'number' },\n },\n INVALID_TICK_SPACING: {\n phase: 'pre_send',\n template: 'Invalid tick spacing: must be a positive integer (got {value})',\n params: { value: 'number' },\n },\n INVALID_FEE: {\n phase: 'pre_send',\n template: 'Invalid {field}: {value} is not a supported fee tier; must be one of {allowed}.',\n params: { field: 'string', value: 'number', allowed: 'string' },\n },\n EXACT_AMOUNT_REQUIRED: {\n phase: 'pre_send',\n template: '{field} is required for this swap.',\n params: { field: 'string' },\n },\n EXACTLY_ONE_OF_REQUIRED: {\n phase: 'pre_send',\n template: 'Provide exactly one of {first} or {second}.',\n params: { first: 'string', second: 'string' },\n },\n AT_MOST_ONE_OF_ALLOWED: {\n phase: 'pre_send',\n template: 'Provide at most one of {first} or {second}.',\n params: { first: 'string', second: 'string' },\n },\n POOL_MISMATCH: {\n phase: 'pre_send',\n template:\n 'tokenIn {tokenIn} and tokenOut {tokenOut} must be the two tokens of the pinned pool {poolToken0}/{poolToken1}.',\n params: {\n tokenIn: 'string',\n tokenOut: 'string',\n poolToken0: 'string',\n poolToken1: 'string',\n },\n },\n INVALID_DTO: {\n phase: 'pre_send',\n template: '{method} DTO field {field} is invalid (expected {expected}).',\n params: { method: 'string', field: 'string', expected: 'string' },\n },\n DTO_NOT_CANONICAL: {\n phase: 'pre_send',\n template:\n 'The {method} DTO is not in the form the SDK builders produce; build it with the matching build function and submit that.',\n params: { method: 'string' },\n },\n SEARCH_TOO_LONG: {\n phase: 'pre_send',\n template: 'search must be at most {maxLength} characters (got {length}).',\n params: { length: 'number', maxLength: 'number' },\n },\n INVALID_SORT_BY: {\n phase: 'pre_send',\n template: 'sortBy \"{value}\" is not allowed; it must be one of {allowed}.',\n params: { value: 'string', allowed: 'string' },\n },\n INVALID_SORT_ORDER: {\n phase: 'pre_send',\n template: 'sortOrder \"{value}\" is not allowed; it must be asc or desc.',\n params: { value: 'string' },\n },\n INVALID_PAGE: {\n phase: 'pre_send',\n template: 'page must be an integer of at least 1 (got {value}).',\n params: { value: 'number' },\n },\n INVALID_LIMIT: {\n phase: 'pre_send',\n template: 'limit must be an integer from {min} to {max} (got {value}).',\n params: { value: 'number', min: 'number', max: 'number' },\n },\n INVALID_MARKET_TOKEN: {\n phase: 'pre_send',\n template:\n 'A market read names a token by a symbol or class key of 1 to 120 letters, digits and . _ $ + / : | - characters (got \"{token}\").',\n params: { token: 'string' },\n },\n INVALID_TIMEFRAME: {\n phase: 'pre_send',\n template: 'timeframe \"{value}\" is not allowed; it must be one of {allowed}.',\n params: { value: 'string', allowed: 'string' },\n },\n INVALID_SEASON_ID: {\n phase: 'pre_send',\n template: 'seasonId must be an integer of at least 1 (got {value}).',\n params: { value: 'string' },\n },\n INVALID_POLL_INTERVAL: {\n phase: 'pre_send',\n template: 'intervalMs must be a finite number of milliseconds of at least 1 (got {value}).',\n params: { value: 'string' },\n },\n} as const satisfies Record<string, GalaErrorCatalogEntry>;\n\n/** Every code a `GSwapSDKError` can carry: the core codes and gswap-sdk's own DEX codes. */\nexport type GSwapErrorCode = GalaErrorCode | keyof typeof GSWAP_ERROR_CATALOG;\n\n/** Both catalogs as one type: a code of either reads its entry here. */\ntype GSwapCatalog = typeof GALA_ERROR_CATALOG & typeof GSWAP_ERROR_CATALOG;\n\n/** The named params of one error code (core or DEX): a flat object of primitives (or closed string tokens). */\nexport type GSwapErrorParams<C extends GSwapErrorCode> = ErrorParamsOf<GSwapCatalog, C>;\n\n/**\n * The catalog `GSwapSDKError` reads templates and phases from: core's entries and the DEX entries,\n * merged (never redefined: the two key sets are disjoint, pinned by tests/error_catalog.test.ts).\n */\nexport const GSWAP_SDK_ERROR_ENTRIES: Readonly<Record<GSwapErrorCode, GalaErrorCatalogEntry>> = {\n ...GALA_ERROR_CATALOG,\n ...GSWAP_ERROR_CATALOG,\n};\n\n/**\n * The English template of every DEX error code, `{placeholder}` markers included. An optional seed\n * or fallback for an app's own translations; the SDK's `message` is generated from it. The core\n * codes' templates are `galaErrorTemplates` from `@gala-chain/gala-core-sdk`: an app that seeds\n * every code a `GSwapSDKError` can carry merges the two.\n */\nexport const gswapErrorTemplates: { readonly [C in keyof typeof GSWAP_ERROR_CATALOG]: string } =\n Object.fromEntries(\n Object.entries(GSWAP_ERROR_CATALOG).map(([code, entry]) => [code, entry.template]),\n ) as { readonly [C in keyof typeof GSWAP_ERROR_CATALOG]: string };\n"],"mappings":"+DAyCA,MAAaA,EAAqC,CAAC,UAAW,WAAW,EAM5DC,EAAyB,mBAGzBC,EAAsB,CAEjC,WAAY,CACV,MAAO,YACP,SAAU,6CACV,OAAQ,CAAE,OAAQ,SAAU,IAAK,SAAU,cAAe,QAAS,EACnE,WAAY,CAAC,eAAe,CAC9B,EACA,gBAAiB,CACf,MAAO,YACP,SACE,mGACF,OAAQ,CAAE,OAAQ,QAAS,CAC7B,EACA,eAAgB,CACd,MAAO,YACP,SAAU,kCACV,OAAQ,CAAE,UAAW,QAAS,CAChC,EAGA,qBAAsB,CACpB,MAAO,WACP,SAAU,+EACV,OAAQ,CAAE,OAAQ,QAAS,CAC7B,EACA,2BAA4B,CAC1B,MAAO,YACP,SACE,mHACF,OAAQ,CAAE,OAAQF,CAAmC,CACvD,EACA,uBAAwB,CACtB,MAAO,YACP,SAAU,gEACV,OAAQ,CAAE,cAAe,QAAS,CACpC,EACA,qBAAsB,CACpB,MAAO,YACP,SAAU,mDACV,OAAQ,CAAC,CACX,EACA,qBAA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AS,CAC5B,EACA,sBAAuB,CACrB,MAAO,WACP,SAAU,kFACV,OAAQ,CAAE,MAAO,QAAS,CAC5B,CACF,EAeaG,EAAmF,CAC9F,GAAGC,EACH,GAAGF,CACL,EAQaG,EACX,OAAO,YACL,OAAO,QAAQH,CAAmB,CAAC,CAAC,KAAK,CAACI,EAAMC,KAAW,CAACD,EAAMC,EAAM,QAAQ,CAAC,CACnF"}
|
|
1
|
+
{"version":3,"file":"gswap_error_catalog.js","names":["SUBMISSION_OUTCOME_UNKNOWN_REASONS","ALLOWED_FEE_TIERS_TEXT","GSWAP_ERROR_CATALOG","GSWAP_SDK_ERROR_ENTRIES","GALA_ERROR_CATALOG","gswapErrorTemplates","code","entry"],"sources":["../../../src/classes/gswap_error_catalog.ts"],"sourcesContent":["/**\n * The catalog of every error code gswap-sdk ITSELF throws (the DEX codes): the SINGLE source of\n * truth for its `code`, the named parameters it carries and the English template its `message` is\n * generated from. The codes of the signing, transport and wallet layer (`INVALID_PRIVATE_KEY`,\n * `REQUEST_TIMEOUT`, `SIGNING_FAILED`, `TYPED_DATA_*`, ...) live in `@gala-chain/gala-core-sdk`'s\n * `GALA_ERROR_CATALOG`; no code is defined in both. A `GSwapSDKError` can carry a code of either\n * catalog (`GSwapErrorCode` is the union), and reads its template from both.\n *\n * - `code` is the only discriminator. It is stable: apps branch on it, never on message text.\n * - `params` are the named placeholders of the error: a flat object of primitives (string,\n * number, boolean) that an app feeds to its own localization (i18next, ICU, FormatJS).\n * Raw server payloads are never params (they are `error.body` / `error.bodyText`), and no\n * secret (private key, signature, raw DTO) ever is.\n * - `template` is English with `{placeholder}` markers. `error.message` is generated from it\n * and the params, so the two cannot drift. It is for logs and developers: it is not stable and\n * must not be shown to users or matched on.\n *\n * Every placeholder in a template is a declared param and every declared param is a placeholder,\n * except the few `unrendered` params that carry server text for the app and are kept out of\n * `message` on purpose (pinned by tests/error_catalog.test.ts). Facts that are not placeholders (HTTP status, URL,\n * `uniqueKey`, transaction ids, the raw body, the cause) are typed properties of the error, see\n * `GalaErrorContext`.\n */\n\nimport {\n GALA_ERROR_CATALOG,\n type ErrorParamsOf,\n type GalaErrorCatalogEntry,\n type GalaErrorCode,\n} from '@gala-chain/gala-core-sdk';\n\n/**\n * Why the outcome of a write submission is unknown (`SUBMISSION_OUTCOME_UNKNOWN.params.reason`).\n * Both say the same thing about the swap (it MAY have been queued: never resubmit under a fresh\n * key, confirm `error.uniqueKey` instead) and differ only in what happened to the request.\n *\n * - `timeout`: the POST exceeded the gateway's timeout; the request may still be running.\n * - `transport`: the POST failed before an HTTP answer was read (offline, connection reset, DNS,\n * CORS, a body that broke off). The bytes may have reached the server and been queued, so this\n * does NOT prove the swap was not sent.\n */\nexport const SUBMISSION_OUTCOME_UNKNOWN_REASONS = ['timeout', 'transport'] as const;\n\n/** One member of {@link SUBMISSION_OUTCOME_UNKNOWN_REASONS}. */\nexport type SubmissionOutcomeUnknownReason = (typeof SUBMISSION_OUTCOME_UNKNOWN_REASONS)[number];\n\n/** The fee tiers as they appear in `INVALID_FEE.allowed`. */\nexport const ALLOWED_FEE_TIERS_TEXT = '0,500,3000,10000';\n\n/** The whole DEX catalog. Add a code here before throwing it anywhere in gswap-sdk. */\nexport const GSWAP_ERROR_CATALOG = {\n // ---------------------------------------------------------------------------------- transport\n HTTP_ERROR: {\n phase: 'post_send',\n template: 'Unexpected HTTP error {status} from {url}.',\n params: { status: 'number', url: 'string', serverMessage: 'string' },\n unrendered: ['serverMessage'],\n },\n UPDATE_REQUIRED: {\n phase: 'post_send',\n template:\n 'The backend refused this app version and requires an update (HTTP {status}); nothing was queued.',\n params: { status: 'number' },\n },\n REQUEST_FAILED: {\n phase: 'in_flight',\n template: 'The {operation} request failed.',\n params: { operation: 'string' },\n },\n\n // ----------------------------------------------------------------------------------- gateway\n METHOD_NOT_SUPPORTED: {\n phase: 'pre_send',\n template: 'The method {method} is not supported; swaps are queued through RequestTrade.',\n params: { method: 'string' },\n },\n SUBMISSION_OUTCOME_UNKNOWN: {\n phase: 'in_flight',\n template:\n 'The submission outcome is unknown ({reason}): the request may have reached the gateway. Confirm before retrying.',\n params: { reason: SUBMISSION_OUTCOME_UNKNOWN_REASONS },\n },\n GATEWAY_REPORTED_ERROR: {\n phase: 'post_send',\n template: 'The gateway reported an error for this write: {serverMessage}',\n params: { serverMessage: 'string' },\n },\n GATEWAY_DATA_MISSING: {\n phase: 'post_send',\n template: 'The gateway response is missing its data object.',\n params: {},\n },\n GATEWAY_MODE_INVALID: {\n phase: 'post_send',\n template:\n 'Gateway response must contain data.mode=\"sync\" with data.result, or data.mode=\"queued\".',\n params: {},\n },\n GATEWAY_SYNC_REQUEST_TRADE: {\n phase: 'post_send',\n template:\n 'The gateway executed RequestTrade synchronously, which this SDK refuses; RequestTrade must be queued.',\n params: {},\n },\n MISSING_UNIQUE_KEY: {\n phase: 'post_send',\n template:\n 'The gateway acknowledged RequestTrade without echoing its uniqueKey, so it cannot be tied to the signed request.',\n params: {},\n },\n UNIQUE_KEY_MISMATCH: {\n phase: 'post_send',\n template: 'Gateway response data.uniqueKey must match the signed RequestTrade uniqueKey.',\n params: {},\n },\n SHADOW_NOT_QUEUED: {\n phase: 'post_send',\n template: 'The swap backend did not queue the shadow request.',\n params: {},\n },\n SHADOW_SUBMIT_NEEDS_WALLET_ADDRESS: {\n phase: 'pre_send',\n template:\n 'A shadow submission needs a walletAddress (the X-Wallet-Address header): pass one to the GSwap constructor or to this call.',\n params: {},\n },\n METHOD_NOT_ALLOWED: {\n phase: 'post_send',\n template: 'The gateway does not expose this contract method: {serverMessage}',\n params: { serverMessage: 'string' },\n },\n SIGNATURE_INVALID: {\n phase: 'post_send',\n template: 'The gateway could not verify the signature: {serverMessage}',\n params: { serverMessage: 'string' },\n },\n SIGNER_MISMATCH: {\n phase: 'post_send',\n template:\n 'The recovered signer does not match an actor named by the operation: {serverMessage}',\n params: { serverMessage: 'string' },\n },\n DTO_INVALID: {\n phase: 'post_send',\n template: 'The gateway rejected the DTO shape: {serverMessage}',\n params: { serverMessage: 'string' },\n },\n DTO_OPERATION_MISMATCH: {\n phase: 'post_send',\n template:\n 'The signed DTO has no dtoOperation, or one that is not the call it was sent to: {serverMessage}',\n params: { serverMessage: 'string' },\n },\n BOUNDS_VIOLATION: {\n phase: 'post_send',\n template: 'The gateway rejected a numeric, tick, symbol or range bound: {serverMessage}',\n params: { serverMessage: 'string' },\n },\n SYMBOL_CONFLICT: {\n phase: 'post_send',\n template: 'The CreatePool symbol is already owned by another class: {serverMessage}',\n params: { serverMessage: 'string' },\n },\n RATE_LIMITED: {\n phase: 'post_send',\n template: 'The gateway rate-limited this signer: {serverMessage}',\n params: { serverMessage: 'string' },\n },\n CHAIN_DISPATCH_FAILED: {\n phase: 'post_send',\n template: 'The chain dispatch failed (chain error key \"{errorKey}\"): {serverMessage}',\n params: { errorKey: 'string', serverMessage: 'string' },\n },\n GATEWAY_REJECTED: {\n phase: 'post_send',\n template: 'Gateway rejected {gatewayCode}: {serverMessage}',\n params: { gatewayCode: 'string', serverMessage: 'string' },\n },\n CHAIN_REJECTED: {\n phase: 'post_send',\n template: 'GalaChain error {errorKey}: {serverMessage}',\n params: { errorKey: 'string', serverMessage: 'string' },\n },\n INVALID_CHAIN_RESPONSE: {\n phase: 'post_send',\n template: 'Backend returned an invalid {resource}.',\n params: { resource: 'string' },\n },\n INVALID_POSITION_RESPONSE: {\n phase: 'post_send',\n template: 'Backend returned an invalid position ({reason}).',\n params: { reason: 'string' },\n },\n\n // -------------------------------------------------------------------------------- confirmation\n CONFIRMATION_TIMEOUT: {\n phase: 'post_send',\n template:\n 'Transaction confirmation timed out; the trade may still apply. Confirm the same uniqueKey again later instead of resubmitting.',\n params: {},\n },\n CONFIRMATION_ABORTED: {\n phase: 'post_send',\n template: 'Transaction confirmation was aborted.',\n params: {},\n },\n CONFIRMATION_FAILED: {\n phase: 'post_send',\n template: 'Transaction confirmation failed with HTTP {status}.',\n params: { status: 'number', serverMessage: 'string' },\n unrendered: ['serverMessage'],\n },\n CONFIRMATION_MALFORMED: {\n phase: 'post_send',\n template: 'Transaction confirmation returned a malformed body.',\n params: {},\n },\n CONFIRMATION_KEY_MISMATCH: {\n phase: 'post_send',\n template: 'Apply result key did not match the requested key.',\n params: {},\n },\n\n // ----------------------------------------------------------------------------------- services\n NO_SIGNER: {\n phase: 'pre_send',\n template: 'This method requires a signer. Please provide a signer to the GSwap constructor.',\n params: {},\n },\n NO_WALLET_ADDRESS: {\n phase: 'post_send',\n template:\n 'Cannot confirm this write: no walletAddress was provided to the GSwap constructor, so the resulting position cannot be looked up to confirm it landed on chain.',\n params: {},\n },\n NO_POOL_AVAILABLE: {\n phase: 'post_send',\n template: 'No pool is available for {tokenIn}/{tokenOut} (fee tier {fee}).',\n params: { tokenIn: 'string', tokenOut: 'string', fee: 'string' },\n },\n INSUFFICIENT_LIQUIDITY: {\n phase: 'post_send',\n template:\n 'The selected pool has insufficient liquidity for {tokenIn}/{tokenOut} (fee tier {fee}).',\n params: { tokenIn: 'string', tokenOut: 'string', fee: 'string' },\n },\n UNKNOWN_TOKEN: {\n phase: 'pre_send',\n template: 'Token {token} is not registered on the DEX contract: it has no trading symbol.',\n params: { token: 'string' },\n },\n SYMBOL_NOT_FOUND: {\n phase: 'pre_send',\n template: 'Token {token} could not be resolved to a trading symbol.',\n params: { token: 'string' },\n },\n STREAM_API_KEY_UNUSABLE: {\n phase: 'pre_send',\n template:\n 'GdexStreamConfig.apiKey needs a non-empty key and an explicit webSocketImpl that accepts upgrade headers as its third argument (the \"ws\" package, or React Native). A browser WebSocket cannot send x-api-key, so the key would be silently dropped.',\n params: {},\n },\n STREAM_WEBSOCKET_UNAVAILABLE: {\n phase: 'pre_send',\n template:\n 'GdexStreamService requires a standards-compatible WebSocket constructor. Node.js versions before 22 must provide one with config.webSocketImpl (for example, from the \"ws\" package).',\n params: {},\n },\n STREAM_NOT_CONNECTED: {\n phase: 'pre_send',\n template: 'GDEX stream is not connected. Call connect() first.',\n params: {},\n },\n STREAM_DISCONNECTED: {\n phase: 'in_flight',\n template: 'GDEX stream disconnected.',\n params: {},\n },\n STREAM_REQUEST_TIMEOUT: {\n phase: 'in_flight',\n template: 'GDEX request \"{method}\" timed out after {timeoutMs} ms.',\n params: { method: 'string', timeoutMs: 'number' },\n },\n STREAM_CONNECT_FAILED: {\n phase: 'in_flight',\n template: 'Failed to connect to GDEX stream at {url}.',\n params: { url: 'string' },\n },\n STREAM_CLOSED_BEFORE_CONNECT: {\n phase: 'in_flight',\n template: 'GDEX stream closed before connecting (code {closeCode}).',\n params: { closeCode: 'number' },\n },\n STREAM_CONNECTION_CLOSED: {\n phase: 'in_flight',\n template: 'GDEX stream connection closed (code {closeCode}).',\n params: { closeCode: 'number' },\n },\n\n // ------------------------------------------------------------------------------ wallet / keys\n TOKEN_RESOLUTION_FAILED: {\n phase: 'pre_send',\n template: 'Token {token} could not be looked up; nothing was sent.',\n params: { token: 'string' },\n },\n MISSING_WALLET_ADDRESS: {\n phase: 'pre_send',\n template:\n 'Invalid wallet address: No wallet address provided. Either provide a wallet address to the function you are calling, or set one when instantiating GSwapSDK.',\n params: {},\n },\n\n // ------------------------------------------------------------------------ input validation\n NON_CANONICAL_PAIR: {\n phase: 'pre_send',\n template:\n 'The pair {token0}/{token1} is not in canonical order: token0 must sort before token1.',\n params: { token0: 'string', token1: 'string' },\n },\n UNORDERABLE_SYMBOLS: {\n phase: 'pre_send',\n template: 'Unable to order trading symbols: expected a pair of symbols, got {received}.',\n params: { received: 'string' },\n },\n INVALID_TOKEN_CLASS_KEY: {\n phase: 'pre_send',\n template:\n 'Invalid token class key \"{tokenClassKey}\": expected a collection followed by category, type and additionalKey',\n params: { tokenClassKey: 'string' },\n },\n INCOMPLETE_TOKEN_CLASS_KEY: {\n phase: 'pre_send',\n template: 'Token class key \"{compositeKey}\" is missing {part}.',\n params: { compositeKey: 'string', part: 'string' },\n },\n INVALID_TRADING_SYMBOL: {\n phase: 'pre_send',\n template:\n 'Invalid trading symbol \"{symbol}\": must be 1-32 ASCII letters and digits and not a reserved word (Token, Unit, none).',\n params: { symbol: 'string' },\n },\n NO_VALID_TRADING_SYMBOL: {\n phase: 'pre_send',\n template:\n 'No valid trading symbol for token class {classKey}: \"{displaySymbol}\" is not an acceptable symbol and none is registered',\n params: { classKey: 'string', displaySymbol: 'string' },\n },\n TOKEN_SYMBOL_NOT_REGISTERED: {\n phase: 'pre_send',\n template:\n 'Token {token} is not registered in the trading-symbol registry yet; pass token0Symbol/token1Symbol (the token class symbol) to propose one. A symbol cannot be derived from a class key.',\n params: { token: 'string' },\n },\n SYMBOL_DISAGREES_WITH_REGISTRY: {\n phase: 'pre_send',\n template:\n 'Supplied symbol {suppliedSymbol} for {token} disagrees with the registered trading symbol {registeredSymbol}.',\n params: { token: 'string', suppliedSymbol: 'string', registeredSymbol: 'string' },\n },\n CREATE_POOL_NEEDS_CLASS_KEY: {\n phase: 'pre_send',\n template:\n 'createPool needs each token as a class key; {token} is a bare trading symbol, which does not carry one.',\n params: { token: 'string' },\n },\n AMOUNT_IS_JS_NUMBER: {\n phase: 'pre_send',\n template: 'Invalid {field}: use a decimal string or BigNumber, not a JavaScript number',\n params: { field: 'string' },\n },\n AMOUNT_NOT_FINITE: {\n phase: 'pre_send',\n template: 'Invalid {field}: must be a finite number (got {value})',\n params: { field: 'string', value: 'string' },\n },\n AMOUNT_NOT_POSITIVE: {\n phase: 'pre_send',\n template: 'Invalid {field}: must be positive (got {value})',\n params: { field: 'string', value: 'string' },\n },\n AMOUNT_NEGATIVE: {\n phase: 'pre_send',\n template: 'Invalid {field}: must not be negative (got {value})',\n params: { field: 'string', value: 'string' },\n },\n PRICE_VALUES_IS_JS_NUMBER: {\n phase: 'pre_send',\n template:\n 'Invalid price values: use decimal strings or BigNumber values, not JavaScript numbers',\n params: {},\n },\n INVALID_PRICE_VALUES: {\n phase: 'pre_send',\n template:\n 'Invalid price values: all prices must be finite and positive (spot {spotPrice}, lower {lowerPrice}, upper {upperPrice})',\n params: { spotPrice: 'string', lowerPrice: 'string', upperPrice: 'string' },\n },\n INVALID_PRICE_RANGE: {\n phase: 'pre_send',\n template:\n 'Invalid price range: lower price {lowerPrice} must be less than or equal to upper price {upperPrice}',\n params: { lowerPrice: 'string', upperPrice: 'string' },\n },\n INVALID_PRICE_BOUNDS: {\n phase: 'pre_send',\n template:\n 'Price bounds must be finite and positive (minPrice {minPrice}, maxPrice {maxPrice}).',\n params: { minPrice: 'string', maxPrice: 'string' },\n },\n PRICE_BOUNDS_ORDER: {\n phase: 'pre_send',\n template: 'minPrice {minPrice} must be less than or equal to maxPrice {maxPrice}.',\n params: { minPrice: 'string', maxPrice: 'string' },\n },\n INVALID_STARTING_PRICE: {\n phase: 'pre_send',\n template: 'Starting price must be finite and positive (got {value}).',\n params: { value: 'string' },\n },\n INVALID_SQRT_PRICE: {\n phase: 'pre_send',\n template: 'Cannot invert a non-positive sqrt price ({sqrtPrice}).',\n params: { sqrtPrice: 'string' },\n },\n INVALID_TOKEN_DECIMALS: {\n phase: 'pre_send',\n template: 'Invalid {field}: must be a non-negative integer (got {value})',\n params: { field: 'string', value: 'number' },\n },\n TICKS_NOT_INTEGERS: {\n phase: 'pre_send',\n template: 'Invalid tick values: ticks must be integers (got {tickLower} and {tickUpper})',\n params: { tickLower: 'number', tickUpper: 'number' },\n },\n INVALID_TICK_RANGE: {\n phase: 'pre_send',\n template: 'Invalid tick range: tickLower {tickLower} must be less than tickUpper {tickUpper}',\n params: { tickLower: 'number', tickUpper: 'number' },\n },\n TICKS_OUT_OF_BOUNDS: {\n phase: 'pre_send',\n template:\n 'Invalid tick range: ticks {tickLower} and {tickUpper} must be between {minTick} and {maxTick}',\n params: { tickLower: 'number', tickUpper: 'number', minTick: 'number', maxTick: 'number' },\n },\n TICKS_NOT_ALIGNED: {\n phase: 'pre_send',\n template: 'Ticks {tickLower} and {tickUpper} must be aligned to spacing {spacing}.',\n params: { tickLower: 'number', tickUpper: 'number', spacing: 'number' },\n },\n INVALID_TICK_SPACING: {\n phase: 'pre_send',\n template: 'Invalid tick spacing: must be a positive integer (got {value})',\n params: { value: 'number' },\n },\n INVALID_FEE: {\n phase: 'pre_send',\n template: 'Invalid {field}: {value} is not a supported fee tier; must be one of {allowed}.',\n params: { field: 'string', value: 'number', allowed: 'string' },\n },\n EXACT_AMOUNT_REQUIRED: {\n phase: 'pre_send',\n template: '{field} is required for this swap.',\n params: { field: 'string' },\n },\n EXACTLY_ONE_OF_REQUIRED: {\n phase: 'pre_send',\n template: 'Provide exactly one of {first} or {second}.',\n params: { first: 'string', second: 'string' },\n },\n AT_MOST_ONE_OF_ALLOWED: {\n phase: 'pre_send',\n template: 'Provide at most one of {first} or {second}.',\n params: { first: 'string', second: 'string' },\n },\n POOL_MISMATCH: {\n phase: 'pre_send',\n template:\n 'tokenIn {tokenIn} and tokenOut {tokenOut} must be the two tokens of the pinned pool {poolToken0}/{poolToken1}.',\n params: {\n tokenIn: 'string',\n tokenOut: 'string',\n poolToken0: 'string',\n poolToken1: 'string',\n },\n },\n INVALID_DTO: {\n phase: 'pre_send',\n template: '{method} DTO field {field} is invalid (expected {expected}).',\n params: { method: 'string', field: 'string', expected: 'string' },\n },\n DTO_NOT_CANONICAL: {\n phase: 'pre_send',\n template:\n 'The {method} DTO is not in the form the SDK builders produce; build it with the matching build function and submit that.',\n params: { method: 'string' },\n },\n SEARCH_TOO_LONG: {\n phase: 'pre_send',\n template: 'search must be at most {maxLength} characters (got {length}).',\n params: { length: 'number', maxLength: 'number' },\n },\n INVALID_SORT_BY: {\n phase: 'pre_send',\n template: 'sortBy \"{value}\" is not allowed; it must be one of {allowed}.',\n params: { value: 'string', allowed: 'string' },\n },\n INVALID_SORT_ORDER: {\n phase: 'pre_send',\n template: 'sortOrder \"{value}\" is not allowed; it must be asc or desc.',\n params: { value: 'string' },\n },\n INVALID_PAGE: {\n phase: 'pre_send',\n template: 'page must be an integer of at least 1 (got {value}).',\n params: { value: 'number' },\n },\n INVALID_LIMIT: {\n phase: 'pre_send',\n template: 'limit must be an integer from {min} to {max} (got {value}).',\n params: { value: 'number', min: 'number', max: 'number' },\n },\n INVALID_MARKET_TOKEN: {\n phase: 'pre_send',\n template:\n 'A market read names a token by a symbol or class key of 1 to 120 letters, digits and . _ $ + / : | - characters (got \"{token}\").',\n params: { token: 'string' },\n },\n INVALID_TIMEFRAME: {\n phase: 'pre_send',\n template: 'timeframe \"{value}\" is not allowed; it must be one of {allowed}.',\n params: { value: 'string', allowed: 'string' },\n },\n INVALID_SEASON_ID: {\n phase: 'pre_send',\n template: 'seasonId must be an integer of at least 1 (got {value}).',\n params: { value: 'string' },\n },\n INVALID_POLL_INTERVAL: {\n phase: 'pre_send',\n template: 'intervalMs must be a finite number of milliseconds of at least 1 (got {value}).',\n params: { value: 'string' },\n },\n} as const satisfies Record<string, GalaErrorCatalogEntry>;\n\n/** Every code a `GSwapSDKError` can carry: the core codes and gswap-sdk's own DEX codes. */\nexport type GSwapErrorCode = GalaErrorCode | keyof typeof GSWAP_ERROR_CATALOG;\n\n/** Both catalogs as one type: a code of either reads its entry here. */\ntype GSwapCatalog = typeof GALA_ERROR_CATALOG & typeof GSWAP_ERROR_CATALOG;\n\n/** The named params of one error code (core or DEX): a flat object of primitives (or closed string tokens). */\nexport type GSwapErrorParams<C extends GSwapErrorCode> = ErrorParamsOf<GSwapCatalog, C>;\n\n/**\n * The catalog `GSwapSDKError` reads templates and phases from: core's entries and the DEX entries,\n * merged (never redefined: the two key sets are disjoint, pinned by tests/error_catalog.test.ts).\n */\nexport const GSWAP_SDK_ERROR_ENTRIES: Readonly<Record<GSwapErrorCode, GalaErrorCatalogEntry>> = {\n ...GALA_ERROR_CATALOG,\n ...GSWAP_ERROR_CATALOG,\n};\n\n/**\n * The English template of every DEX error code, `{placeholder}` markers included. An optional seed\n * or fallback for an app's own translations; the SDK's `message` is generated from it. The core\n * codes' templates are `galaErrorTemplates` from `@gala-chain/gala-core-sdk`: an app that seeds\n * every code a `GSwapSDKError` can carry merges the two.\n */\nexport const gswapErrorTemplates: { readonly [C in keyof typeof GSWAP_ERROR_CATALOG]: string } =\n Object.fromEntries(\n Object.entries(GSWAP_ERROR_CATALOG).map(([code, entry]) => [code, entry.template]),\n ) as { readonly [C in keyof typeof GSWAP_ERROR_CATALOG]: string };\n"],"mappings":"A,+DAyCA,MAAaA,EAAqC,CAAC,UAAW,WAAW,EAM5DC,EAAyB,mBAGzBC,EAAsB,CAEjC,WAAY,CACV,MAAO,YACP,SAAU,6CACV,OAAQ,CAAE,OAAQ,SAAU,IAAK,SAAU,cAAe,QAAS,EACnE,WAAY,CAAC,eAAe,CAC9B,EACA,gBAAiB,CACf,MAAO,YACP,SACE,mGACF,OAAQ,CAAE,OAAQ,QAAS,CAC7B,EACA,eAAgB,CACd,MAAO,YACP,SAAU,kCACV,OAAQ,CAAE,UAAW,QAAS,CAChC,EAGA,qBAAsB,CACpB,MAAO,WACP,SAAU,+EACV,OAAQ,CAAE,OAAQ,QAAS,CAC7B,EACA,2BAA4B,CAC1B,MAAO,YACP,SACE,mHACF,OAAQ,CAAE,OAAQF,CAAmC,CACvD,EACA,uBAAwB,CACtB,MAAO,YACP,SAAU,gEACV,OAAQ,CAAE,cAAe,QAAS,CACpC,EACA,qBAAsB,CACpB,MAAO,YACP,SAAU,mDACV,OAAQ,CAAC,CACX,EACA,qBAAsB,CACpB,MAAO,YACP,SACE,0FACF,OAAQ,CAAC,CACX,EACA,2BAA4B,CAC1B,MAAO,YACP,SACE,wGACF,OAAQ,CAAC,CACX,EACA,mBAAoB,CAClB,MAAO,YACP,SACE,mHACF,OAAQ,CAAC,CACX,EACA,oBAAqB,CACnB,MAAO,YACP,SAAU,gFACV,OAAQ,CAAC,CACX,EACA,kBAAmB,CACjB,MAAO,YACP,SAAU,qDACV,OAAQ,CAAC,CACX,EACA,mCAAoC,CAClC,MAAO,WACP,SACE,8HACF,OAAQ,CAAC,CACX,EACA,mBAAoB,CAClB,MAAO,YACP,SAAU,oEACV,OAAQ,CAAE,cAAe,QAAS,CACpC,EACA,kBAA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core-sdk";const n={HTTP_ERROR:`post_send`,UPDATE_REQUIRED:`post_send`,REQUEST_FAILED:`in_flight`,METHOD_NOT_SUPPORTED:`pre_send`,SUBMISSION_OUTCOME_UNKNOWN:`in_flight`,GATEWAY_REPORTED_ERROR:`post_send`,GATEWAY_DATA_MISSING:`post_send`,GATEWAY_MODE_INVALID:`post_send`,GATEWAY_SYNC_REQUEST_TRADE:`post_send`,MISSING_UNIQUE_KEY:`post_send`,UNIQUE_KEY_MISMATCH:`post_send`,SHADOW_NOT_QUEUED:`post_send`,SHADOW_SUBMIT_NEEDS_WALLET_ADDRESS:`pre_send`,METHOD_NOT_ALLOWED:`post_send`,SIGNATURE_INVALID:`post_send`,SIGNER_MISMATCH:`post_send`,DTO_INVALID:`post_send`,BOUNDS_VIOLATION:`post_send`,SYMBOL_CONFLICT:`post_send`,RATE_LIMITED:`post_send`,CHAIN_DISPATCH_FAILED:`post_send`,GATEWAY_REJECTED:`post_send`,CHAIN_REJECTED:`post_send`,INVALID_CHAIN_RESPONSE:`post_send`,INVALID_POSITION_RESPONSE:`post_send`,CONFIRMATION_TIMEOUT:`post_send`,CONFIRMATION_ABORTED:`post_send`,CONFIRMATION_FAILED:`post_send`,CONFIRMATION_MALFORMED:`post_send`,CONFIRMATION_KEY_MISMATCH:`post_send`,NO_SIGNER:`pre_send`,NO_WALLET_ADDRESS:`post_send`,NO_POOL_AVAILABLE:`post_send`,INSUFFICIENT_LIQUIDITY:`post_send`,UNKNOWN_TOKEN:`pre_send`,SYMBOL_NOT_FOUND:`pre_send`,STREAM_API_KEY_UNUSABLE:`pre_send`,STREAM_WEBSOCKET_UNAVAILABLE:`pre_send`,STREAM_NOT_CONNECTED:`pre_send`,STREAM_DISCONNECTED:`in_flight`,STREAM_REQUEST_TIMEOUT:`in_flight`,STREAM_CONNECT_FAILED:`in_flight`,STREAM_CLOSED_BEFORE_CONNECT:`in_flight`,STREAM_CONNECTION_CLOSED:`in_flight`,TOKEN_RESOLUTION_FAILED:`pre_send`,MISSING_WALLET_ADDRESS:`pre_send`,NON_CANONICAL_PAIR:`pre_send`,UNORDERABLE_SYMBOLS:`pre_send`,INVALID_TOKEN_CLASS_KEY:`pre_send`,INCOMPLETE_TOKEN_CLASS_KEY:`pre_send`,INVALID_TRADING_SYMBOL:`pre_send`,NO_VALID_TRADING_SYMBOL:`pre_send`,TOKEN_SYMBOL_NOT_REGISTERED:`pre_send`,SYMBOL_DISAGREES_WITH_REGISTRY:`pre_send`,CREATE_POOL_NEEDS_CLASS_KEY:`pre_send`,AMOUNT_IS_JS_NUMBER:`pre_send`,AMOUNT_NOT_FINITE:`pre_send`,AMOUNT_NOT_POSITIVE:`pre_send`,AMOUNT_NEGATIVE:`pre_send`,PRICE_VALUES_IS_JS_NUMBER:`pre_send`,INVALID_PRICE_VALUES:`pre_send`,INVALID_PRICE_RANGE:`pre_send`,INVALID_PRICE_BOUNDS:`pre_send`,PRICE_BOUNDS_ORDER:`pre_send`,INVALID_STARTING_PRICE:`pre_send`,INVALID_SQRT_PRICE:`pre_send`,INVALID_TOKEN_DECIMALS:`pre_send`,TICKS_NOT_INTEGERS:`pre_send`,INVALID_TICK_RANGE:`pre_send`,TICKS_OUT_OF_BOUNDS:`pre_send`,TICKS_NOT_ALIGNED:`pre_send`,INVALID_TICK_SPACING:`pre_send`,INVALID_FEE:`pre_send`,EXACT_AMOUNT_REQUIRED:`pre_send`,EXACTLY_ONE_OF_REQUIRED:`pre_send`,AT_MOST_ONE_OF_ALLOWED:`pre_send`,POOL_MISMATCH:`pre_send`,INVALID_DTO:`pre_send`,DTO_NOT_CANONICAL:`pre_send`,SEARCH_TOO_LONG:`pre_send`,INVALID_SORT_BY:`pre_send`,INVALID_SORT_ORDER:`pre_send`,INVALID_PAGE:`pre_send`,INVALID_LIMIT:`pre_send`,INVALID_MARKET_TOKEN:`pre_send`,INVALID_TIMEFRAME:`pre_send`,INVALID_SEASON_ID:`pre_send`,INVALID_POLL_INTERVAL:`pre_send`};function r(e){return Object.hasOwn(n,e)}function i(e){return t(e)||r(e)}function a(i){return i.phase===void 0?t(i.code)?e[i.code]:r(i.code)?n[i.code]:void 0:i.phase}export{n as GSWAP_ERROR_PHASE_BY_CODE,i as isCatalogCode,a as phaseOfView};
|
|
1
|
+
import{GALA_ERROR_PHASE_BY_CODE as e,isGalaCatalogCode as t}from"@gala-chain/gala-core-sdk";const n={HTTP_ERROR:`post_send`,UPDATE_REQUIRED:`post_send`,REQUEST_FAILED:`in_flight`,METHOD_NOT_SUPPORTED:`pre_send`,SUBMISSION_OUTCOME_UNKNOWN:`in_flight`,GATEWAY_REPORTED_ERROR:`post_send`,GATEWAY_DATA_MISSING:`post_send`,GATEWAY_MODE_INVALID:`post_send`,GATEWAY_SYNC_REQUEST_TRADE:`post_send`,MISSING_UNIQUE_KEY:`post_send`,UNIQUE_KEY_MISMATCH:`post_send`,SHADOW_NOT_QUEUED:`post_send`,SHADOW_SUBMIT_NEEDS_WALLET_ADDRESS:`pre_send`,METHOD_NOT_ALLOWED:`post_send`,SIGNATURE_INVALID:`post_send`,SIGNER_MISMATCH:`post_send`,DTO_INVALID:`post_send`,DTO_OPERATION_MISMATCH:`post_send`,BOUNDS_VIOLATION:`post_send`,SYMBOL_CONFLICT:`post_send`,RATE_LIMITED:`post_send`,CHAIN_DISPATCH_FAILED:`post_send`,GATEWAY_REJECTED:`post_send`,CHAIN_REJECTED:`post_send`,INVALID_CHAIN_RESPONSE:`post_send`,INVALID_POSITION_RESPONSE:`post_send`,CONFIRMATION_TIMEOUT:`post_send`,CONFIRMATION_ABORTED:`post_send`,CONFIRMATION_FAILED:`post_send`,CONFIRMATION_MALFORMED:`post_send`,CONFIRMATION_KEY_MISMATCH:`post_send`,NO_SIGNER:`pre_send`,NO_WALLET_ADDRESS:`post_send`,NO_POOL_AVAILABLE:`post_send`,INSUFFICIENT_LIQUIDITY:`post_send`,UNKNOWN_TOKEN:`pre_send`,SYMBOL_NOT_FOUND:`pre_send`,STREAM_API_KEY_UNUSABLE:`pre_send`,STREAM_WEBSOCKET_UNAVAILABLE:`pre_send`,STREAM_NOT_CONNECTED:`pre_send`,STREAM_DISCONNECTED:`in_flight`,STREAM_REQUEST_TIMEOUT:`in_flight`,STREAM_CONNECT_FAILED:`in_flight`,STREAM_CLOSED_BEFORE_CONNECT:`in_flight`,STREAM_CONNECTION_CLOSED:`in_flight`,TOKEN_RESOLUTION_FAILED:`pre_send`,MISSING_WALLET_ADDRESS:`pre_send`,NON_CANONICAL_PAIR:`pre_send`,UNORDERABLE_SYMBOLS:`pre_send`,INVALID_TOKEN_CLASS_KEY:`pre_send`,INCOMPLETE_TOKEN_CLASS_KEY:`pre_send`,INVALID_TRADING_SYMBOL:`pre_send`,NO_VALID_TRADING_SYMBOL:`pre_send`,TOKEN_SYMBOL_NOT_REGISTERED:`pre_send`,SYMBOL_DISAGREES_WITH_REGISTRY:`pre_send`,CREATE_POOL_NEEDS_CLASS_KEY:`pre_send`,AMOUNT_IS_JS_NUMBER:`pre_send`,AMOUNT_NOT_FINITE:`pre_send`,AMOUNT_NOT_POSITIVE:`pre_send`,AMOUNT_NEGATIVE:`pre_send`,PRICE_VALUES_IS_JS_NUMBER:`pre_send`,INVALID_PRICE_VALUES:`pre_send`,INVALID_PRICE_RANGE:`pre_send`,INVALID_PRICE_BOUNDS:`pre_send`,PRICE_BOUNDS_ORDER:`pre_send`,INVALID_STARTING_PRICE:`pre_send`,INVALID_SQRT_PRICE:`pre_send`,INVALID_TOKEN_DECIMALS:`pre_send`,TICKS_NOT_INTEGERS:`pre_send`,INVALID_TICK_RANGE:`pre_send`,TICKS_OUT_OF_BOUNDS:`pre_send`,TICKS_NOT_ALIGNED:`pre_send`,INVALID_TICK_SPACING:`pre_send`,INVALID_FEE:`pre_send`,EXACT_AMOUNT_REQUIRED:`pre_send`,EXACTLY_ONE_OF_REQUIRED:`pre_send`,AT_MOST_ONE_OF_ALLOWED:`pre_send`,POOL_MISMATCH:`pre_send`,INVALID_DTO:`pre_send`,DTO_NOT_CANONICAL:`pre_send`,SEARCH_TOO_LONG:`pre_send`,INVALID_SORT_BY:`pre_send`,INVALID_SORT_ORDER:`pre_send`,INVALID_PAGE:`pre_send`,INVALID_LIMIT:`pre_send`,INVALID_MARKET_TOKEN:`pre_send`,INVALID_TIMEFRAME:`pre_send`,INVALID_SEASON_ID:`pre_send`,INVALID_POLL_INTERVAL:`pre_send`};function r(e){return Object.hasOwn(n,e)}function i(e){return t(e)||r(e)}function a(i){return i.phase===void 0?t(i.code)?e[i.code]:r(i.code)?n[i.code]:void 0:i.phase}export{n as GSWAP_ERROR_PHASE_BY_CODE,i as isCatalogCode,a as phaseOfView};
|
|
2
2
|
//# sourceMappingURL=gswap_error_phase_table.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"gswap_error_phase_table.js","names":["GSWAP_ERROR_PHASE_BY_CODE","isDexCatalogCode","code","isCatalogCode","isGalaCatalogCode","phaseOfView","view","GALA_ERROR_PHASE_BY_CODE"],"sources":["../../../src/classes/gswap_error_phase_table.ts"],"sourcesContent":["import {\n GALA_ERROR_PHASE_BY_CODE,\n isGalaCatalogCode,\n type FailureView,\n type GalaErrorPhase,\n} from '@gala-chain/gala-core-sdk';\nimport type { GSWAP_ERROR_CATALOG, GSwapErrorCode } from './gswap_error_catalog.js';\n\n/**\n * The phase of every DEX catalog code, WITHOUT the catalog. The failure guards (`classifyFailure`,\n * `mayHaveBeenQueued`, ...) need only a code's phase, and the catalog's English templates are\n * ~15 kB: reading the phase from here keeps an app shell that imports a guard from loading them.\n * The catalog entry is still where a code is declared; this table is checked against it AT\n * COMPILE TIME, in both directions (a missing code, an extra code or a different phase is a type\n * error), so the two cannot drift. The core codes' phases are core's `GALA_ERROR_PHASE_BY_CODE`.\n */\nexport const GSWAP_ERROR_PHASE_BY_CODE = {\n HTTP_ERROR: 'post_send',\n UPDATE_REQUIRED: 'post_send',\n REQUEST_FAILED: 'in_flight',\n METHOD_NOT_SUPPORTED: 'pre_send',\n SUBMISSION_OUTCOME_UNKNOWN: 'in_flight',\n GATEWAY_REPORTED_ERROR: 'post_send',\n GATEWAY_DATA_MISSING: 'post_send',\n GATEWAY_MODE_INVALID: 'post_send',\n GATEWAY_SYNC_REQUEST_TRADE: 'post_send',\n MISSING_UNIQUE_KEY: 'post_send',\n UNIQUE_KEY_MISMATCH: 'post_send',\n SHADOW_NOT_QUEUED: 'post_send',\n SHADOW_SUBMIT_NEEDS_WALLET_ADDRESS: 'pre_send',\n METHOD_NOT_ALLOWED: 'post_send',\n SIGNATURE_INVALID: 'post_send',\n SIGNER_MISMATCH: 'post_send',\n DTO_INVALID: 'post_send',\n BOUNDS_VIOLATION: 'post_send',\n SYMBOL_CONFLICT: 'post_send',\n RATE_LIMITED: 'post_send',\n CHAIN_DISPATCH_FAILED: 'post_send',\n GATEWAY_REJECTED: 'post_send',\n CHAIN_REJECTED: 'post_send',\n INVALID_CHAIN_RESPONSE: 'post_send',\n INVALID_POSITION_RESPONSE: 'post_send',\n CONFIRMATION_TIMEOUT: 'post_send',\n CONFIRMATION_ABORTED: 'post_send',\n CONFIRMATION_FAILED: 'post_send',\n CONFIRMATION_MALFORMED: 'post_send',\n CONFIRMATION_KEY_MISMATCH: 'post_send',\n NO_SIGNER: 'pre_send',\n NO_WALLET_ADDRESS: 'post_send',\n NO_POOL_AVAILABLE: 'post_send',\n INSUFFICIENT_LIQUIDITY: 'post_send',\n UNKNOWN_TOKEN: 'pre_send',\n SYMBOL_NOT_FOUND: 'pre_send',\n STREAM_API_KEY_UNUSABLE: 'pre_send',\n STREAM_WEBSOCKET_UNAVAILABLE: 'pre_send',\n STREAM_NOT_CONNECTED: 'pre_send',\n STREAM_DISCONNECTED: 'in_flight',\n STREAM_REQUEST_TIMEOUT: 'in_flight',\n STREAM_CONNECT_FAILED: 'in_flight',\n STREAM_CLOSED_BEFORE_CONNECT: 'in_flight',\n STREAM_CONNECTION_CLOSED: 'in_flight',\n TOKEN_RESOLUTION_FAILED: 'pre_send',\n MISSING_WALLET_ADDRESS: 'pre_send',\n NON_CANONICAL_PAIR: 'pre_send',\n UNORDERABLE_SYMBOLS: 'pre_send',\n INVALID_TOKEN_CLASS_KEY: 'pre_send',\n INCOMPLETE_TOKEN_CLASS_KEY: 'pre_send',\n INVALID_TRADING_SYMBOL: 'pre_send',\n NO_VALID_TRADING_SYMBOL: 'pre_send',\n TOKEN_SYMBOL_NOT_REGISTERED: 'pre_send',\n SYMBOL_DISAGREES_WITH_REGISTRY: 'pre_send',\n CREATE_POOL_NEEDS_CLASS_KEY: 'pre_send',\n AMOUNT_IS_JS_NUMBER: 'pre_send',\n AMOUNT_NOT_FINITE: 'pre_send',\n AMOUNT_NOT_POSITIVE: 'pre_send',\n AMOUNT_NEGATIVE: 'pre_send',\n PRICE_VALUES_IS_JS_NUMBER: 'pre_send',\n INVALID_PRICE_VALUES: 'pre_send',\n INVALID_PRICE_RANGE: 'pre_send',\n INVALID_PRICE_BOUNDS: 'pre_send',\n PRICE_BOUNDS_ORDER: 'pre_send',\n INVALID_STARTING_PRICE: 'pre_send',\n INVALID_SQRT_PRICE: 'pre_send',\n INVALID_TOKEN_DECIMALS: 'pre_send',\n TICKS_NOT_INTEGERS: 'pre_send',\n INVALID_TICK_RANGE: 'pre_send',\n TICKS_OUT_OF_BOUNDS: 'pre_send',\n TICKS_NOT_ALIGNED: 'pre_send',\n INVALID_TICK_SPACING: 'pre_send',\n INVALID_FEE: 'pre_send',\n EXACT_AMOUNT_REQUIRED: 'pre_send',\n EXACTLY_ONE_OF_REQUIRED: 'pre_send',\n AT_MOST_ONE_OF_ALLOWED: 'pre_send',\n POOL_MISMATCH: 'pre_send',\n INVALID_DTO: 'pre_send',\n DTO_NOT_CANONICAL: 'pre_send',\n SEARCH_TOO_LONG: 'pre_send',\n INVALID_SORT_BY: 'pre_send',\n INVALID_SORT_ORDER: 'pre_send',\n INVALID_PAGE: 'pre_send',\n INVALID_LIMIT: 'pre_send',\n INVALID_MARKET_TOKEN: 'pre_send',\n INVALID_TIMEFRAME: 'pre_send',\n INVALID_SEASON_ID: 'pre_send',\n INVALID_POLL_INTERVAL: 'pre_send',\n} as const satisfies {\n readonly [C in keyof typeof GSWAP_ERROR_CATALOG]: (typeof GSWAP_ERROR_CATALOG)[C]['phase'];\n};\n\n/** True for a DEX code (gswap-sdk's own catalog). */\nfunction isDexCatalogCode(code: string): code is keyof typeof GSWAP_ERROR_PHASE_BY_CODE {\n return Object.hasOwn(GSWAP_ERROR_PHASE_BY_CODE, code);\n}\n\n/** True for a code a `GSwapSDKError` can carry: a core code or a DEX code. */\nexport function isCatalogCode(code: string): code is GSwapErrorCode {\n return isGalaCatalogCode(code) || isDexCatalogCode(code);\n}\n\n/**\n * The phase of a view: the one it states, else the catalog's phase for its code (core's or the\n * DEX catalog's), else `undefined`.\n */\nexport function phaseOfView(view: FailureView): GalaErrorPhase | undefined {\n if (view.phase !== undefined) return view.phase;\n if (isGalaCatalogCode(view.code)) return GALA_ERROR_PHASE_BY_CODE[view.code];\n return isDexCatalogCode(view.code) ? GSWAP_ERROR_PHASE_BY_CODE[view.code] : undefined;\n}\n"],"mappings":"4FAgBA,MAAaA,EAA4B,CACvC,WAAY,YACZ,gBAAiB,YACjB,eAAgB,YAChB,qBAAsB,WACtB,2BAA4B,YAC5B,uBAAwB,YACxB,qBAAsB,YACtB,qBAAsB,YACtB,2BAA4B,YAC5B,mBAAoB,YACpB,oBAAqB,YACrB,kBAAmB,YACnB,mCAAoC,WACpC,mBAAoB,YACpB,kBAAmB,YACnB,gBAAiB,YACjB,YAAa,YACb,iBAAkB,YAClB,gBAAiB,YACjB,aAAc,YACd,sBAAuB,YACvB,iBAAkB,YAClB,eAAgB,YAChB,uBAAwB,YACxB,0BAA2B,YAC3B,qBAAsB,YACtB,qBAAsB,YACtB,oBAAqB,YACrB,uBAAwB,YACxB,0BAA2B,YAC3B,UAAW,WACX,kBAAmB,YACnB,kBAAmB,YACnB,uBAAwB,YACxB,cAAe,WACf,iBAAkB,WAClB,wBAAyB,WACzB,6BAA8B,WAC9B,qBAAsB,WACtB,oBAAqB,YACrB,uBAAwB,YACxB,sBAAuB,YACvB,6BAA8B,YAC9B,yBAA0B,YAC1B,wBAAyB,WACzB,uBAAwB,WACxB,mBAAoB,WACpB,oBAAqB,WACrB,wBAAyB,WACzB,2BAA4B,WAC5B,uBAAwB,WACxB,wBAAyB,WACzB,4BAA6B,WAC7B,+BAAgC,WAChC,4BAA6B,WAC7B,oBAAqB,WACrB,kBAAmB,WACnB,oBAAqB,WACrB,gBAAiB,WACjB,0BAA2B,WAC3B,qBAAsB,WACtB,oBAAqB,WACrB,qBAAsB,WACtB,mBAAoB,WACpB,uBAAwB,WACxB,mBAAoB,WACpB,uBAAwB,WACxB,mBAAoB,WACpB,mBAAoB,WACpB,oBAAqB,WACrB,kBAAmB,WACnB,qBAAsB,WACtB,YAAa,WACb,sBAAuB,WACvB,wBAAyB,WACzB,uBAAwB,WACxB,cAAe,WACf,YAAa,WACb,kBAAmB,WACnB,gBAAiB,WACjB,gBAAiB,WACjB,mBAAoB,WACpB,aAAc,WACd,cAAe,WACf,qBAAsB,WACtB,kBAAmB,WACnB,kBAAmB,WACnB,sBAAuB,UACzB,EAKA,SAASC,EAAiB,EAA8D,CACtF,OAAO,OAAO,OAAOD,EAA2BE,CAAI,CACtD,CAGA,SAAgBC,EAAc,EAAsC,CAClE,OAAOC,EAAkBF,CAAI,GAAKD,EAAiBC,CAAI,CACzD,CAMA,SAAgBG,EAAY,EAA+C,CAGzE,OAFIC,EAAK,QAAU,IAAA,GACfF,EAAkBE,EAAK,IAAI,EAAUC,EAAyBD,EAAK,MAChEL,EAAiBK,EAAK,IAAI,EAAIN,EAA0BM,EAAK,MAAQ,IAAA,GAFvCA,EAAK,KAG5C"}
|
|
1
|
+
{"version":3,"file":"gswap_error_phase_table.js","names":["GSWAP_ERROR_PHASE_BY_CODE","isDexCatalogCode","code","isCatalogCode","isGalaCatalogCode","phaseOfView","view","GALA_ERROR_PHASE_BY_CODE"],"sources":["../../../src/classes/gswap_error_phase_table.ts"],"sourcesContent":["import {\n GALA_ERROR_PHASE_BY_CODE,\n isGalaCatalogCode,\n type FailureView,\n type GalaErrorPhase,\n} from '@gala-chain/gala-core-sdk';\nimport type { GSWAP_ERROR_CATALOG, GSwapErrorCode } from './gswap_error_catalog.js';\n\n/**\n * The phase of every DEX catalog code, WITHOUT the catalog. The failure guards (`classifyFailure`,\n * `mayHaveBeenQueued`, ...) need only a code's phase, and the catalog's English templates are\n * ~15 kB: reading the phase from here keeps an app shell that imports a guard from loading them.\n * The catalog entry is still where a code is declared; this table is checked against it AT\n * COMPILE TIME, in both directions (a missing code, an extra code or a different phase is a type\n * error), so the two cannot drift. The core codes' phases are core's `GALA_ERROR_PHASE_BY_CODE`.\n */\nexport const GSWAP_ERROR_PHASE_BY_CODE = {\n HTTP_ERROR: 'post_send',\n UPDATE_REQUIRED: 'post_send',\n REQUEST_FAILED: 'in_flight',\n METHOD_NOT_SUPPORTED: 'pre_send',\n SUBMISSION_OUTCOME_UNKNOWN: 'in_flight',\n GATEWAY_REPORTED_ERROR: 'post_send',\n GATEWAY_DATA_MISSING: 'post_send',\n GATEWAY_MODE_INVALID: 'post_send',\n GATEWAY_SYNC_REQUEST_TRADE: 'post_send',\n MISSING_UNIQUE_KEY: 'post_send',\n UNIQUE_KEY_MISMATCH: 'post_send',\n SHADOW_NOT_QUEUED: 'post_send',\n SHADOW_SUBMIT_NEEDS_WALLET_ADDRESS: 'pre_send',\n METHOD_NOT_ALLOWED: 'post_send',\n SIGNATURE_INVALID: 'post_send',\n SIGNER_MISMATCH: 'post_send',\n DTO_INVALID: 'post_send',\n DTO_OPERATION_MISMATCH: 'post_send',\n BOUNDS_VIOLATION: 'post_send',\n SYMBOL_CONFLICT: 'post_send',\n RATE_LIMITED: 'post_send',\n CHAIN_DISPATCH_FAILED: 'post_send',\n GATEWAY_REJECTED: 'post_send',\n CHAIN_REJECTED: 'post_send',\n INVALID_CHAIN_RESPONSE: 'post_send',\n INVALID_POSITION_RESPONSE: 'post_send',\n CONFIRMATION_TIMEOUT: 'post_send',\n CONFIRMATION_ABORTED: 'post_send',\n CONFIRMATION_FAILED: 'post_send',\n CONFIRMATION_MALFORMED: 'post_send',\n CONFIRMATION_KEY_MISMATCH: 'post_send',\n NO_SIGNER: 'pre_send',\n NO_WALLET_ADDRESS: 'post_send',\n NO_POOL_AVAILABLE: 'post_send',\n INSUFFICIENT_LIQUIDITY: 'post_send',\n UNKNOWN_TOKEN: 'pre_send',\n SYMBOL_NOT_FOUND: 'pre_send',\n STREAM_API_KEY_UNUSABLE: 'pre_send',\n STREAM_WEBSOCKET_UNAVAILABLE: 'pre_send',\n STREAM_NOT_CONNECTED: 'pre_send',\n STREAM_DISCONNECTED: 'in_flight',\n STREAM_REQUEST_TIMEOUT: 'in_flight',\n STREAM_CONNECT_FAILED: 'in_flight',\n STREAM_CLOSED_BEFORE_CONNECT: 'in_flight',\n STREAM_CONNECTION_CLOSED: 'in_flight',\n TOKEN_RESOLUTION_FAILED: 'pre_send',\n MISSING_WALLET_ADDRESS: 'pre_send',\n NON_CANONICAL_PAIR: 'pre_send',\n UNORDERABLE_SYMBOLS: 'pre_send',\n INVALID_TOKEN_CLASS_KEY: 'pre_send',\n INCOMPLETE_TOKEN_CLASS_KEY: 'pre_send',\n INVALID_TRADING_SYMBOL: 'pre_send',\n NO_VALID_TRADING_SYMBOL: 'pre_send',\n TOKEN_SYMBOL_NOT_REGISTERED: 'pre_send',\n SYMBOL_DISAGREES_WITH_REGISTRY: 'pre_send',\n CREATE_POOL_NEEDS_CLASS_KEY: 'pre_send',\n AMOUNT_IS_JS_NUMBER: 'pre_send',\n AMOUNT_NOT_FINITE: 'pre_send',\n AMOUNT_NOT_POSITIVE: 'pre_send',\n AMOUNT_NEGATIVE: 'pre_send',\n PRICE_VALUES_IS_JS_NUMBER: 'pre_send',\n INVALID_PRICE_VALUES: 'pre_send',\n INVALID_PRICE_RANGE: 'pre_send',\n INVALID_PRICE_BOUNDS: 'pre_send',\n PRICE_BOUNDS_ORDER: 'pre_send',\n INVALID_STARTING_PRICE: 'pre_send',\n INVALID_SQRT_PRICE: 'pre_send',\n INVALID_TOKEN_DECIMALS: 'pre_send',\n TICKS_NOT_INTEGERS: 'pre_send',\n INVALID_TICK_RANGE: 'pre_send',\n TICKS_OUT_OF_BOUNDS: 'pre_send',\n TICKS_NOT_ALIGNED: 'pre_send',\n INVALID_TICK_SPACING: 'pre_send',\n INVALID_FEE: 'pre_send',\n EXACT_AMOUNT_REQUIRED: 'pre_send',\n EXACTLY_ONE_OF_REQUIRED: 'pre_send',\n AT_MOST_ONE_OF_ALLOWED: 'pre_send',\n POOL_MISMATCH: 'pre_send',\n INVALID_DTO: 'pre_send',\n DTO_NOT_CANONICAL: 'pre_send',\n SEARCH_TOO_LONG: 'pre_send',\n INVALID_SORT_BY: 'pre_send',\n INVALID_SORT_ORDER: 'pre_send',\n INVALID_PAGE: 'pre_send',\n INVALID_LIMIT: 'pre_send',\n INVALID_MARKET_TOKEN: 'pre_send',\n INVALID_TIMEFRAME: 'pre_send',\n INVALID_SEASON_ID: 'pre_send',\n INVALID_POLL_INTERVAL: 'pre_send',\n} as const satisfies {\n readonly [C in keyof typeof GSWAP_ERROR_CATALOG]: (typeof GSWAP_ERROR_CATALOG)[C]['phase'];\n};\n\n/** True for a DEX code (gswap-sdk's own catalog). */\nfunction isDexCatalogCode(code: string): code is keyof typeof GSWAP_ERROR_PHASE_BY_CODE {\n return Object.hasOwn(GSWAP_ERROR_PHASE_BY_CODE, code);\n}\n\n/** True for a code a `GSwapSDKError` can carry: a core code or a DEX code. */\nexport function isCatalogCode(code: string): code is GSwapErrorCode {\n return isGalaCatalogCode(code) || isDexCatalogCode(code);\n}\n\n/**\n * The phase of a view: the one it states, else the catalog's phase for its code (core's or the\n * DEX catalog's), else `undefined`.\n */\nexport function phaseOfView(view: FailureView): GalaErrorPhase | undefined {\n if (view.phase !== undefined) return view.phase;\n if (isGalaCatalogCode(view.code)) return GALA_ERROR_PHASE_BY_CODE[view.code];\n return isDexCatalogCode(view.code) ? GSWAP_ERROR_PHASE_BY_CODE[view.code] : undefined;\n}\n"],"mappings":"A,4FAgBA,MAAaA,EAA4B,CACvC,WAAY,YACZ,gBAAiB,YACjB,eAAgB,YAChB,qBAAsB,WACtB,2BAA4B,YAC5B,uBAAwB,YACxB,qBAAsB,YACtB,qBAAsB,YACtB,2BAA4B,YAC5B,mBAAoB,YACpB,oBAAqB,YACrB,kBAAmB,YACnB,mCAAoC,WACpC,mBAAoB,YACpB,kBAAmB,YACnB,gBAAiB,YACjB,YAAa,YACb,uBAAwB,YACxB,iBAAkB,YAClB,gBAAiB,YACjB,aAAc,YACd,sBAAuB,YACvB,iBAAkB,YAClB,eAAgB,YAChB,uBAAwB,YACxB,0BAA2B,YAC3B,qBAAsB,YACtB,qBAAsB,YACtB,oBAAqB,YACrB,uBAAwB,YACxB,0BAA2B,YAC3B,UAAW,WACX,kBAAmB,YACnB,kBAAmB,YACnB,uBAAwB,YACxB,cAAe,WACf,iBAAkB,WAClB,wBAAyB,WACzB,6BAA8B,WAC9B,qBAAsB,WACtB,oBAAqB,YACrB,uBAAwB,YACxB,sBAAuB,YACvB,6BAA8B,YAC9B,yBAA0B,YAC1B,wBAAyB,WACzB,uBAAwB,WACxB,mBAAoB,WACpB,oBAAqB,WACrB,wBAAyB,WACzB,2BAA4B,WAC5B,uBAAwB,WACxB,wBAAyB,WACzB,4BAA6B,WAC7B,+BAAgC,WAChC,4BAA6B,WAC7B,oBAAqB,WACrB,kBAAmB,WACnB,oBAAqB,WACrB,gBAAiB,WACjB,0BAA2B,WAC3B,qBAAsB,WACtB,oBAAqB,WACrB,qBAAsB,WACtB,mBAAoB,WACpB,uBAAwB,WACxB,mBAAoB,WACpB,uBAAwB,WACxB,mBAAoB,WACpB,mBAAoB,WACpB,oBAAqB,WACrB,kBAAmB,WACnB,qBAAsB,WACtB,YAAa,WACb,sBAAuB,WACvB,wBAAyB,WACzB,uBAAwB,WACxB,cAAe,WACf,YAAa,WACb,kBAAmB,WACnB,gBAAiB,WACjB,gBAAiB,WACjB,mBAAoB,WACpB,aAAc,WACd,cAAe,WACf,qBAAsB,WACtB,kBAAmB,WACnB,kBAAmB,WACnB,sBAAuB,UACzB,EAKA,SAASC,EAAiB,EAA8D,CACtF,OAAO,OAAO,OAAOD,EAA2BE,CAAI,CACtD,CAGA,SAAgBC,EAAc,EAAsC,CAClE,OAAOC,EAAkBF,CAAI,GAAKD,EAAiBC,CAAI,CACzD,CAMA,SAAgBG,EAAY,EAA+C,CAGzE,OAFIC,EAAK,QAAU,IAAA,GACfF,EAAkBE,EAAK,IAAI,EAAUC,EAAyBD,EAAK,MAChEL,EAAiBK,EAAK,IAAI,EAAIN,EAA0BM,EAAK,MAAQ,IAAA,GAFvCA,EAAK,KAG5C,C"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{serverMessageOfBody as e}from"../utils/server_message.js";import{GSWAP_SDK_ERROR_ENTRIES as t}from"./gswap_error_catalog.js";import{phaseOfView as n}from"./gswap_error_phase_table.js";import r from"../_virtual/_@oxc-project_runtime@0.
|
|
1
|
+
import{serverMessageOfBody as e}from"../utils/server_message.js";import{GSWAP_SDK_ERROR_ENTRIES as t}from"./gswap_error_catalog.js";import{phaseOfView as n}from"./gswap_error_phase_table.js";import r from"../_virtual/_@oxc-project_runtime@0.154.0/helpers/esm/defineProperty.js";import{GalaSDKError as i,parseJson as a,toFailureView as o}from"@gala-chain/gala-core-sdk";const s=426;var c=class t extends i{constructor(e,t,n={}){super(e,t,n),this.name=`GSwapSDKError`}get notFound(){return super.notFound||this.code===`NO_POOL_AVAILABLE`||this.code===`UNKNOWN_TOKEN`}static noSignerError(){return new t(`NO_SIGNER`,{})}static noWalletAddressError(){return new t(`NO_WALLET_ADDRESS`,{})}static noPoolAvailableError(e,n,r,i){return new t(`NO_POOL_AVAILABLE`,{tokenIn:l(e),tokenOut:l(n),fee:u(r)},d(i))}static insufficientLiquidityError(e,n,r,i){return new t(`INSUFFICIENT_LIQUIDITY`,{tokenIn:l(e),tokenOut:l(n),fee:u(r)},d(i))}static fromGatewayBounce(e,n,r,i,a,o,s){let c={status:r,body:i,url:a,retryAfterMs:o,uniqueKey:s},l={serverMessage:n};switch(e){case`METHOD_NOT_ALLOWED`:return new t(`METHOD_NOT_ALLOWED`,l,c);case`SIGNATURE_INVALID`:return new t(`SIGNATURE_INVALID`,l,c);case`SIGNER_MISMATCH`:return new t(`SIGNER_MISMATCH`,l,c);case`DTO_INVALID`:return new t(`DTO_INVALID`,l,c);case`DTO_OPERATION_MISMATCH`:return new t(`DTO_OPERATION_MISMATCH`,l,c);case`BOUNDS_VIOLATION`:return new t(`BOUNDS_VIOLATION`,l,c);case`SYMBOL_CONFLICT`:return new t(`SYMBOL_CONFLICT`,l,c);case`RATE_LIMITED`:return new t(`RATE_LIMITED`,l,c);case`CHAIN_DISPATCH_FAILED`:return new t(`CHAIN_DISPATCH_FAILED`,{...l,errorKey:h(i,`errorKey`)??``},c);default:return new t(`GATEWAY_REJECTED`,{gatewayCode:e,serverMessage:n},c)}}static fromChainError(e,n,r){return new t(`CHAIN_REJECTED`,{errorKey:e,serverMessage:n},r)}static unknownTokenError(e,n){return new t(`UNKNOWN_TOKEN`,{token:l(e)},d(n))}static confirmationTimeoutError(e,n){return new t(`CONFIRMATION_TIMEOUT`,{},{uniqueKey:e,cause:n})}static fromStatus(e,n={}){let{url:r,uniqueKey:i,write:a,serverMessage:o,body:s,retryAfterMs:c}=n,l=a??(i!==void 0&&i!==``);if(l&&(i===void 0||i===``))throw new t(`INVALID_UNIQUE_KEY`,{uniqueKey:i??``});let u={status:e,body:s,url:r,retryAfterMs:c,uniqueKey:l?i:void 0,write:l,phase:`post_send`};return e===426?new t(`UPDATE_REQUIRED`,{status:e},u):new t(`HTTP_ERROR`,{status:e,url:r??``,serverMessage:o??``},u)}static async fromErrorResponse(n,r){let i=await r.text(),o=a(i),s=m(o,`error`),c=h(s,`ErrorKey`),l=h(s,`Message`),u={status:r.status,body:o??i,url:n,write:!1};return r.status===426?new t(`UPDATE_REQUIRED`,{status:r.status},u):c!==void 0&&l!==void 0?new t(`CHAIN_REJECTED`,{errorKey:c,serverMessage:l},u):new t(`HTTP_ERROR`,{status:r.status,url:n,serverMessage:e(o)},u)}};r(c,`catalog`,t);function l(e){return typeof e==`string`?e:[e.collection,e.category,e.type,e.additionalKey].join(`$`)}function u(e){return e===void 0?`any`:String(e)}function d(e){return e===void 0?{}:{status:e.status,body:e.body??e.bodyText,url:e.url,phase:`post_send`,write:e.write}}function f(e,t){return e instanceof i&&(t===void 0||e.code===t)}function p(e){let t=o(e);return t!==void 0&&n(t)===`pre_send`}function m(e,t){if(typeof e!=`object`||!e||!(t in e))return;let n=e[t];return typeof n==`object`&&n?n:void 0}function h(e,t){if(typeof e!=`object`||!e||!(t in e))return;let n=e[t];return typeof n==`string`?n:void 0}export{c as GSwapSDKError,s as UPDATE_REQUIRED_STATUS,m as getObjectProperty,h as getStringProperty,f as isGSwapError,p as isPreSendError};
|
|
2
2
|
//# sourceMappingURL=gswap_sdk_error.js.map
|