@gala-chain/gswap-sdk 1.1.1 → 1.2.0-rc.10
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 +42 -9
- package/dist/browser/_virtual/_@oxc-project_runtime@0.151.0/helpers/esm/defineProperty.js +1 -0
- package/dist/browser/_virtual/_@oxc-project_runtime@0.151.0/helpers/esm/toPrimitive.js +1 -0
- package/dist/browser/_virtual/_@oxc-project_runtime@0.151.0/helpers/esm/toPropertyKey.js +1 -0
- package/dist/browser/_virtual/_@oxc-project_runtime@0.151.0/helpers/esm/typeof.js +1 -0
- package/dist/browser/classes/apply_results.js +2 -0
- package/dist/browser/classes/apply_results.js.map +1 -0
- package/dist/browser/classes/assets.js +2 -0
- package/dist/browser/classes/assets.js.map +1 -0
- package/dist/browser/classes/dex_fees.js +2 -0
- package/dist/browser/classes/dex_fees.js.map +1 -0
- package/dist/browser/classes/error_catalog.js +2 -0
- package/dist/browser/classes/error_catalog.js.map +1 -0
- package/dist/browser/classes/error_phase_table.js +2 -0
- package/dist/browser/classes/error_phase_table.js.map +1 -0
- package/dist/browser/classes/error_phases.js +2 -0
- package/dist/browser/classes/error_phases.js.map +1 -0
- package/dist/browser/classes/gateway.js +2 -0
- package/dist/browser/classes/gateway.js.map +1 -0
- package/dist/browser/classes/gdex_stream.js +2 -0
- package/dist/browser/classes/gdex_stream.js.map +1 -0
- package/dist/browser/classes/gswap.js +2 -0
- package/dist/browser/classes/gswap.js.map +1 -0
- package/dist/browser/classes/gswap_sdk_error.js +2 -0
- package/dist/browser/classes/gswap_sdk_error.js.map +1 -0
- package/dist/browser/classes/http_client.js +2 -0
- package/dist/browser/classes/http_client.js.map +1 -0
- package/dist/browser/classes/pending_swap_fate.js +2 -0
- package/dist/browser/classes/pending_swap_fate.js.map +1 -0
- package/dist/browser/classes/pending_swaps.js +2 -0
- package/dist/browser/classes/pending_swaps.js.map +1 -0
- package/dist/browser/classes/pools.js +2 -0
- package/dist/browser/classes/pools.js.map +1 -0
- package/dist/browser/classes/positions.js +2 -0
- package/dist/browser/classes/positions.js.map +1 -0
- package/dist/browser/classes/quoting.js +2 -0
- package/dist/browser/classes/quoting.js.map +1 -0
- package/dist/browser/classes/shadow_submit.js +2 -0
- package/dist/browser/classes/shadow_submit.js.map +1 -0
- package/dist/browser/classes/signers.js +2 -0
- package/dist/browser/classes/signers.js.map +1 -0
- package/dist/browser/classes/storage_adapters.js +2 -0
- package/dist/browser/classes/storage_adapters.js.map +1 -0
- package/dist/browser/classes/submitted_transaction.js +2 -0
- package/dist/browser/classes/submitted_transaction.js.map +1 -0
- package/dist/browser/classes/swaps.js +2 -0
- package/dist/browser/classes/swaps.js.map +1 -0
- package/dist/browser/classes/symbols.js +2 -0
- package/dist/browser/classes/symbols.js.map +1 -0
- package/dist/browser/index.js +1 -5
- package/dist/browser/types/env.js +2 -0
- package/dist/browser/types/env.js.map +1 -0
- package/dist/browser/types/fees.js +2 -0
- package/dist/browser/types/fees.js.map +1 -0
- package/dist/browser/utils/axios_requestor.js +2 -0
- package/dist/browser/utils/axios_requestor.js.map +1 -0
- package/dist/browser/utils/chain_dto_signing.js +3 -0
- package/dist/browser/utils/chain_dto_signing.js.map +1 -0
- package/dist/browser/utils/class_key.js +2 -0
- package/dist/browser/utils/class_key.js.map +1 -0
- package/dist/browser/utils/classification.js +2 -0
- package/dist/browser/utils/classification.js.map +1 -0
- package/dist/browser/utils/confirmation_schedule.js +2 -0
- package/dist/browser/utils/confirmation_schedule.js.map +1 -0
- package/dist/browser/utils/confirmation_state.js +2 -0
- package/dist/browser/utils/confirmation_state.js.map +1 -0
- package/dist/browser/utils/debug.js +2 -0
- package/dist/browser/utils/debug.js.map +1 -0
- package/dist/browser/utils/dto_builders.js +2 -0
- package/dist/browser/utils/dto_builders.js.map +1 -0
- package/dist/browser/utils/eip712.js +4 -0
- package/dist/browser/utils/eip712.js.map +1 -0
- package/dist/browser/utils/error_brand.js +2 -0
- package/dist/browser/utils/error_brand.js.map +1 -0
- package/dist/browser/utils/ethers_provider.js +2 -0
- package/dist/browser/utils/ethers_provider.js.map +1 -0
- package/dist/browser/utils/failure_classification.js +2 -0
- package/dist/browser/utils/failure_classification.js.map +1 -0
- package/dist/browser/utils/failure_guards.js +2 -0
- package/dist/browser/utils/failure_guards.js.map +1 -0
- package/dist/browser/utils/failure_outcomes.js +2 -0
- package/dist/browser/utils/failure_outcomes.js.map +1 -0
- package/dist/browser/utils/failure_view.js +2 -0
- package/dist/browser/utils/failure_view.js.map +1 -0
- package/dist/browser/utils/fetch_failure.js +2 -0
- package/dist/browser/utils/fetch_failure.js.map +1 -0
- package/dist/browser/utils/lenient.js +2 -0
- package/dist/browser/utils/lenient.js.map +1 -0
- package/dist/browser/utils/ordering.js +2 -0
- package/dist/browser/utils/ordering.js.map +1 -0
- package/dist/browser/utils/pre_send.js +2 -0
- package/dist/browser/utils/pre_send.js.map +1 -0
- package/dist/browser/utils/reconnection.js +2 -0
- package/dist/browser/utils/reconnection.js.map +1 -0
- package/dist/browser/utils/server_message.js +2 -0
- package/dist/browser/utils/server_message.js.map +1 -0
- package/dist/browser/utils/shadow_errors.js +2 -0
- package/dist/browser/utils/shadow_errors.js.map +1 -0
- package/dist/browser/utils/signing.js +3 -0
- package/dist/browser/utils/signing.js.map +1 -0
- package/dist/browser/utils/submit_state.js +2 -0
- package/dist/browser/utils/submit_state.js.map +1 -0
- package/dist/browser/utils/tick_align.js +2 -0
- package/dist/browser/utils/tick_align.js.map +1 -0
- package/dist/browser/utils/tick_math.js +2 -0
- package/dist/browser/utils/tick_math.js.map +1 -0
- package/dist/browser/utils/tick_range.js +2 -0
- package/dist/browser/utils/tick_range.js.map +1 -0
- package/dist/browser/utils/ticks.js +2 -0
- package/dist/browser/utils/ticks.js.map +1 -0
- package/dist/browser/utils/transport.js +2 -0
- package/dist/browser/utils/transport.js.map +1 -0
- package/dist/browser/utils/typed_data.js +2 -0
- package/dist/browser/utils/typed_data.js.map +1 -0
- package/dist/browser/utils/unique_key.js +2 -0
- package/dist/browser/utils/unique_key.js.map +1 -0
- package/dist/browser/utils/unique_key_syntax.js +2 -0
- package/dist/browser/utils/unique_key_syntax.js.map +1 -0
- package/dist/browser/utils/validation.js +2 -0
- package/dist/browser/utils/validation.js.map +1 -0
- package/dist/browser/utils/wallet_rejection.js +2 -0
- package/dist/browser/utils/wallet_rejection.js.map +1 -0
- package/dist/browser/version.js +2 -0
- package/dist/browser/version.js.map +1 -0
- package/dist/browser/wallet.js +2 -0
- package/dist/browser/wallet.js.map +1 -0
- package/dist/index.cjs +8064 -2479
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +4659 -652
- package/dist/index.d.ts +4659 -652
- package/dist/index.mjs +7896 -2427
- package/dist/index.mjs.map +1 -1
- package/dist/wallet.cjs +159 -0
- package/dist/wallet.cjs.map +1 -0
- package/dist/wallet.d.cts +74 -0
- package/dist/wallet.d.ts +74 -0
- package/dist/wallet.mjs +156 -0
- package/dist/wallet.mjs.map +1 -0
- package/package.json +38 -10
- package/dist/browser/index.js.map +0 -1
package/README.md
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
# gSwap SDK
|
|
2
2
|
|
|
3
3
|
`@gala-chain/gswap-sdk` is the TypeScript SDK for the current GalaChain DEX
|
|
4
|
-
contract.
|
|
5
|
-
|
|
4
|
+
contract. It uses trading symbols for pool operations, signs writes with the
|
|
5
|
+
signer supplied by the application, and submits them through the Chain
|
|
6
6
|
Gateway. Swap requests are queued for later application.
|
|
7
7
|
|
|
8
8
|
## Install
|
|
@@ -11,6 +11,18 @@ Gateway. Swap requests are queued for later application.
|
|
|
11
11
|
npm install @gala-chain/gswap-sdk
|
|
12
12
|
```
|
|
13
13
|
|
|
14
|
+
`latest` is `1.1.1`. The 1.2.0 line (signing primitives, the error catalog,
|
|
15
|
+
failure classification, the `/wallet` subpath) is published as release
|
|
16
|
+
candidates under the `rc` dist-tag until 1.2.0 ships, and a `^1.1.1` range does
|
|
17
|
+
not resolve a prerelease:
|
|
18
|
+
|
|
19
|
+
```bash
|
|
20
|
+
npm install @gala-chain/gswap-sdk@rc
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
This README and the documentation site describe the `rc` line. Pin an exact
|
|
24
|
+
version (`@gala-chain/gswap-sdk@1.2.0-rc.10`) for a wallet or app build.
|
|
25
|
+
|
|
14
26
|
## Quick start
|
|
15
27
|
|
|
16
28
|
```typescript
|
|
@@ -65,17 +77,38 @@ See the [realtime stream guide](./docs/docs/tutorial-basics/realtime-stream.md).
|
|
|
65
77
|
|
|
66
78
|
## Signers and identity
|
|
67
79
|
|
|
68
|
-
| Signer | Scheme
|
|
69
|
-
| --------------------- |
|
|
70
|
-
| `PrivateKeySigner` | GalaChain native signature
|
|
71
|
-
| `GalaWalletSigner` | Native `gala_signChainDto
|
|
72
|
-
| `BrowserWalletSigner` | EIP-1193 `personal_sign`
|
|
80
|
+
| Signer | Scheme | Identity resolved by the chain |
|
|
81
|
+
| --------------------- | ------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------- |
|
|
82
|
+
| `PrivateKeySigner` | GalaChain native signature | Recovered from the private key |
|
|
83
|
+
| `GalaWalletSigner` | Native `gala_signChainDto`; opt-in `personal-sign` needs a wallet build with fix 34ca4e4 (unreleased) | Selected account (`0x...`, `eth\|...`, `client\|...`) |
|
|
84
|
+
| `BrowserWalletSigner` | EIP-1193 `personal_sign`; opt-in `{ scheme: 'eip712' }` (`eth_signTypedData_v4`) | Selected Ethereum account (`eip712` also resolves a `client\|` alias) |
|
|
73
85
|
|
|
74
86
|
Native signing is the default for server keys and current Gala Wallets.
|
|
75
87
|
Browser wallet personal-sign signs the bare serialized DTO (the wallet applies
|
|
76
88
|
the EIP-191 header) and sends that header as the DTO's `prefix`, which is what
|
|
77
|
-
the chain prepends when it recovers the signer. EIP-712 is
|
|
78
|
-
|
|
89
|
+
the chain prepends when it recovers the signer. EIP-712 is opt-in on
|
|
90
|
+
`BrowserWalletSigner` for `RequestTrade`, `AddLiquidity`, `RemoveLiquidity` and
|
|
91
|
+
`CollectPositionFees` (`CreatePool` still uses personal-sign); it is not the
|
|
92
|
+
default and not part of the Gala Wallet path. See
|
|
93
|
+
[Signing and Identity](./docs/docs/other/signing-and-identity.md).
|
|
94
|
+
|
|
95
|
+
## Wallet and app integration
|
|
96
|
+
|
|
97
|
+
The SDK core is platform neutral (only `fetch`, `globalThis.crypto` and timers) and ships the
|
|
98
|
+
building blocks a wallet or app needs, each behind an adapter: `confirmAppliedTrade` (apply-results
|
|
99
|
+
polling with `AbortSignal`, `AppliedTradeError`), `PendingSwapStore` (async `StorageAdapter`;
|
|
100
|
+
`storageAdapterFromChromeStorage(chrome.storage.local)` for an extension, `webStorageAdapter(localStorage)`
|
|
101
|
+
for a web app),
|
|
102
|
+
`DexFees` (DryRun fee quotes), `swaps.swapShadow` (dark swaps through `X-Shadow`), a configurable
|
|
103
|
+
`uniqueKeyPrefix`, and the realtime stream with an injected `WebSocket` (and an `apiKey` for
|
|
104
|
+
server-side clients). See [App and Wallet Integration](./docs/docs/other/app-integration.md).
|
|
105
|
+
|
|
106
|
+
Errors carry a stable `code` and flat `params` that an app localizes; `classifyFailure`,
|
|
107
|
+
`pendingSwapFateFor`, `isNoMarket` and the other deciders answer retry and outcome questions from the
|
|
108
|
+
code, never from message text ([Error Handling](./docs/docs/other/error-handling.md)). App-shell code
|
|
109
|
+
that must not load the SDK imports its wallet helpers from `@gala-chain/gswap-sdk/wallet`
|
|
110
|
+
([Bundle size](./docs/docs/other/bundle-size.md)). Tick and price math, including the contract's
|
|
111
|
+
in-range rule, is in [Tick and Price Math](./docs/docs/other/tick-and-price-math.md).
|
|
79
112
|
|
|
80
113
|
## Documentation
|
|
81
114
|
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import e from"./toPropertyKey.js";function t(t,n,r){return(n=e(n))in t?Object.defineProperty(t,n,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[n]=r,t}export{t as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import e from"./typeof.js";function t(t,n){if(e(t)!=`object`||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var i=r.call(t,n||`default`);if(e(i)!=`object`)return i;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(n===`string`?String:Number)(t)}export{t as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import e from"./typeof.js";import t from"./toPrimitive.js";function n(n){var r=t(n,`string`);return e(r)==`symbol`?r:r+``}export{n as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function e(t){"@babel/helpers - typeof";return e=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},e(t)}export{e as default};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{createConfirmationSchedule as e,throwIfAborted as t}from"../utils/confirmation_schedule.js";import{serverMessageOfBody as n}from"../utils/server_message.js";import{isValidUniqueKey as r}from"../utils/unique_key_syntax.js";import{GSwapSDKError as i,getStringProperty as a}from"./gswap_sdk_error.js";import{buildRequestHeaders as o,fetchRequestor as s,readBlockNumberHeader as c,readHeader as l,readResponseBody as u,readRetryAfter as d,requestWithTimeout as f}from"../utils/transport.js";var p=class extends i{constructor(e,t,n={}){super(e,t,n),this.name=`AppliedTradeError`}};async function m(i,a,c){let{uniqueKey:l}=a;if(!r(l))throw new p(`INVALID_UNIQUE_KEY`,{uniqueKey:String(l)},{uniqueKey:l});let m=i.httpRequestor??s,g=i.requestTimeoutMs??3e4,_=c?.signal,y=e=>new p(`CONFIRMATION_ABORTED`,{},{uniqueKey:l,cause:e}),b=`${i.dexBackendBaseUrl.replace(/\/$/u,``)}/v1/chain/apply-results/${encodeURIComponent(l)}?channel=asset&contract=dex-contract`,x=e(c,3e3,y);await x.waitForRead();let S;for(;;){t(_,y);let e,r;try{e=await f(m,b,{method:`GET`,headers:o(i.wire),..._===void 0?{}:{signal:_}},g),r=await u(e)}catch(e){if(t(_,y),S=e,!await x.waitForRead())break;continue}if(t(_,y),e.status===200)return h(a,e,r,b);if(e.status===404||e.status===429||v(e.status)){let t=e.status===429?d(e):void 0;if(!await x.waitForRead(t))break;continue}throw new p(`CONFIRMATION_FAILED`,{status:e.status,serverMessage:n(r)},{uniqueKey:l,status:e.status,body:r,url:b})}throw new p(`CONFIRMATION_TIMEOUT`,{},{uniqueKey:l,requestTransactionId:a.requestTransactionId,url:b,cause:S})}function h(e,t,n,r){let{uniqueKey:i}=e,o=y(n),s=o?.uniqueKey??o?.UniqueKey;if(typeof s==`string`&&s!==i)throw new p(`CONFIRMATION_KEY_MISMATCH`,{},{uniqueKey:i,status:t.status,body:n,url:r});let u=o?.Status,d=l(t,`x-apply-transaction-id`)??null,f=c(t,`x-apply-block-number`)??null;if(u===0)throw new p(`CHAIN_REJECTED`,{errorKey:a(o,`ErrorKey`)??`CHAIN_ERROR`,serverMessage:a(o,`Message`)??``},{uniqueKey:i,requestTransactionId:e.requestTransactionId,applyTransactionId:d,blockNumber:f,status:t.status,body:n,url:r});if(u!==1)throw g(e,t,n,r);let m=_(o?.Data);if(m===void 0)throw g(e,t,n,r);return{uniqueKey:i,transactionId:d,blockNumber:f,requestTransactionId:e.requestTransactionId,result:m}}function g(e,t,n,r){return new p(`CONFIRMATION_MALFORMED`,{},{uniqueKey:e.uniqueKey,status:t.status,body:n,url:r})}function _(e){let t=y(e);if(t===void 0||typeof t.token0!=`string`||typeof t.token1!=`string`||typeof t.fee!=`number`)return;let n=[`sell0Qty`,`sell1Qty`,`buy0Qty`,`buy1Qty`,`tradingFees`,`protocolFees`,`totalFees`];for(let e of n)if(e in t&&typeof t[e]!=`string`)return;return{token0:t.token0,token1:t.token1,fee:t.fee,...Object.fromEntries(n.flatMap(e=>typeof t[e]==`string`?[[e,t[e]]]:[]))}}function v(e){return e===500||e===502||e===503||e===504}function y(e){return typeof e==`object`&&e?e:void 0}export{p as AppliedTradeError,m as confirmAppliedTrade};
|
|
2
|
+
//# sourceMappingURL=apply_results.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"apply_results.js","names":[],"sources":["../../../src/classes/apply_results.ts"],"sourcesContent":["import type { ConfirmOptions } from '../types/confirm_options.js';\nimport type { HttpRequestor, HTTPResponse } from '../types/http_requestor.js';\nimport type { AppliedTrade, TradeExecution } from '../types/v2_results.js';\nimport { createConfirmationSchedule, throwIfAborted } from '../utils/confirmation_schedule.js';\nimport { serverMessageOfBody } from '../utils/server_message.js';\nimport { isValidUniqueKey } from '../utils/unique_key_syntax.js';\nimport type { WireOptions } from '../types/wire.js';\nimport {\n buildRequestHeaders,\n fetchRequestor,\n readBlockNumberHeader,\n readHeader,\n readResponseBody,\n readRetryAfter,\n requestWithTimeout,\n} from '../utils/transport.js';\nimport type { GSwapErrorCode, GSwapErrorParams } from './error_catalog.js';\nimport { getStringProperty, GSwapSDKError, type GSwapErrorContext } from './gswap_sdk_error.js';\n\n/**\n * The AutoApplier waits at least 2 s before applying and the apply lands ~6-8 s after the\n * acknowledgement, so a read at t=0 is a guaranteed 404.\n */\nconst DEFAULT_INITIAL_DELAY_MS = 3_000;\nconst DEFAULT_REQUEST_TIMEOUT_MS = 30_000;\n\n/**\n * The outcome of a queued RequestTrade that could not be delivered as an {@link AppliedTrade}.\n * `code` says why:\n *\n * - `CONFIRMATION_TIMEOUT`: no terminal result before the deadline. The trade may still apply;\n * confirm the same `uniqueKey` again later and never resubmit.\n * - `CONFIRMATION_ABORTED`: the caller's `signal` aborted. Nothing is known about the outcome.\n * - `CONFIRMATION_FAILED`: the apply-results read got a terminal HTTP status (`params.status`;\n * `params.serverMessage` is the failing body's own message, `''` when it had none: server\n * text is data, relay it or ignore it). The outcome is unknown.\n * - `CONFIRMATION_MALFORMED` / `CONFIRMATION_KEY_MISMATCH`: the apply result is not a usable\n * answer for this key. The outcome is unknown.\n * - `INVALID_UNIQUE_KEY`: the key is not a valid apply-results key; nothing was read. TERMINAL:\n * no retry can ever succeed (the SDK never signs such a key, so a stored one is corrupt), so a\n * resume loop must forget the swap. `PendingSwapStore.list` already prunes such entries.\n * - `CHAIN_REJECTED`: the chain REJECTED the trade; `params.errorKey` is the chain `ErrorKey` (or\n * `CHAIN_ERROR`) and `params.serverMessage` its English message.\n *\n * `uniqueKey` is always set and, where known, `requestTransactionId`, `applyTransactionId`,\n * `blockNumber`, `status`, `body`, `url` and the last transport `cause`.\n */\nexport class AppliedTradeError<C extends GSwapErrorCode = GSwapErrorCode> extends GSwapSDKError<C> {\n constructor(code: C, params: GSwapErrorParams<C>, context: GSwapErrorContext = {}) {\n super(code, params, context);\n this.name = 'AppliedTradeError';\n }\n}\n\n/** The transport and backend a confirmation reads from. */\nexport interface ApplyResultsClient {\n /** Swap backend origin, e.g. `https://dex-backend-prod1.defi.gala.com` (no trailing path). */\n dexBackendBaseUrl: string;\n /** Defaults to the global `fetch`. */\n httpRequestor?: HttpRequestor | undefined;\n /** Per-read timeout in milliseconds (default 30 000). */\n requestTimeoutMs?: number | undefined;\n /** Request headers of the poll (`userAgent`, `headers`); see {@link WireOptions}. */\n wire?: WireOptions | undefined;\n}\n\n/** What identifies the queued trade to confirm. */\nexport interface AppliedTradeInput {\n uniqueKey: string;\n /** The transaction id of the queued request, carried through to the result; `null` if unknown. */\n requestTransactionId: string | null;\n}\n\n/**\n * Polls `GET /v1/chain/apply-results/{uniqueKey}?channel=asset&contract=dex-contract` until the\n * queued RequestTrade reaches a terminal state.\n *\n * Pacing: wait `initialDelayMs` (default 3 s), then read; on 404, 429, 500, 502, 503, 504 or a\n * transport error wait with jittered exponential backoff (`pollIntervalMs` doubling to 8 s,\n * `Retry-After` honored as seconds or an HTTP date) until `timeoutMs`. Any other status is\n * terminal. At least one read is always made.\n *\n * @returns The applied trade.\n * @throws AppliedTradeError - see its documentation for every `code`.\n * @example\n * ```ts\n * const applied = await confirmAppliedTrade(\n * { dexBackendBaseUrl: 'https://dex-backend-prod1.defi.gala.com' },\n * { uniqueKey, requestTransactionId: null },\n * { initialDelayMs: 0, timeoutMs: 60_000, signal: controller.signal },\n * );\n * ```\n */\nexport async function confirmAppliedTrade(\n client: ApplyResultsClient,\n input: AppliedTradeInput,\n options?: ConfirmOptions,\n): Promise<AppliedTrade> {\n const { uniqueKey } = input;\n if (!isValidUniqueKey(uniqueKey)) {\n throw new AppliedTradeError(\n 'INVALID_UNIQUE_KEY',\n { uniqueKey: String(uniqueKey) },\n { uniqueKey },\n );\n }\n const requestor = client.httpRequestor ?? fetchRequestor;\n const requestTimeoutMs = client.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;\n const signal = options?.signal;\n const abortError = (cause?: unknown): Error =>\n new AppliedTradeError('CONFIRMATION_ABORTED', {}, { uniqueKey, cause });\n const url = `${client.dexBackendBaseUrl.replace(/\\/$/u, '')}/v1/chain/apply-results/${encodeURIComponent(uniqueKey)}?channel=asset&contract=dex-contract`;\n\n const schedule = createConfirmationSchedule(options, DEFAULT_INITIAL_DELAY_MS, abortError);\n await schedule.waitForRead();\n let lastError: unknown;\n\n while (true) {\n throwIfAborted(signal, abortError);\n let response: HTTPResponse;\n let body: unknown;\n try {\n response = await requestWithTimeout(\n requestor,\n url,\n {\n method: 'GET',\n headers: buildRequestHeaders(client.wire),\n ...(signal === undefined ? {} : { signal }),\n },\n requestTimeoutMs,\n );\n body = await readResponseBody(response);\n } catch (error: unknown) {\n throwIfAborted(signal, abortError);\n lastError = error;\n if (!(await schedule.waitForRead())) break;\n continue;\n }\n throwIfAborted(signal, abortError);\n\n if (response.status === 200) return readAppliedResult(input, response, body, url);\n\n if (response.status === 404 || response.status === 429 || isTransient(response.status)) {\n const retryAfter = response.status === 429 ? readRetryAfter(response) : undefined;\n if (!(await schedule.waitForRead(retryAfter))) break;\n continue;\n }\n\n throw new AppliedTradeError(\n 'CONFIRMATION_FAILED',\n { status: response.status, serverMessage: serverMessageOfBody(body) },\n { uniqueKey, status: response.status, body, url },\n );\n }\n\n throw new AppliedTradeError(\n 'CONFIRMATION_TIMEOUT',\n {},\n { uniqueKey, requestTransactionId: input.requestTransactionId, url, cause: lastError },\n );\n}\n\nfunction readAppliedResult(\n input: AppliedTradeInput,\n response: HTTPResponse,\n body: unknown,\n url: string,\n): AppliedTrade {\n const { uniqueKey } = input;\n const record = asRecord(body);\n const responseKey = record?.['uniqueKey'] ?? record?.['UniqueKey'];\n if (typeof responseKey === 'string' && responseKey !== uniqueKey) {\n throw new AppliedTradeError(\n 'CONFIRMATION_KEY_MISMATCH',\n {},\n { uniqueKey, status: response.status, body, url },\n );\n }\n const status = record?.['Status'];\n const applyTransactionId = readHeader(response, 'x-apply-transaction-id') ?? null;\n const blockNumber = readBlockNumberHeader(response, 'x-apply-block-number') ?? null;\n if (status === 0) {\n const errorKey = getStringProperty(record, 'ErrorKey') ?? 'CHAIN_ERROR';\n const chainMessage = getStringProperty(record, 'Message') ?? '';\n throw new AppliedTradeError(\n 'CHAIN_REJECTED',\n { errorKey, serverMessage: chainMessage },\n {\n uniqueKey,\n requestTransactionId: input.requestTransactionId,\n applyTransactionId,\n blockNumber,\n status: response.status,\n body,\n url,\n },\n );\n }\n if (status !== 1) throw malformed(input, response, body, url);\n const result = parseTradeExecution(record?.['Data']);\n if (result === undefined) throw malformed(input, response, body, url);\n return {\n uniqueKey,\n transactionId: applyTransactionId,\n blockNumber,\n requestTransactionId: input.requestTransactionId,\n result,\n };\n}\n\nfunction malformed(\n input: AppliedTradeInput,\n response: HTTPResponse,\n body: unknown,\n url: string,\n): AppliedTradeError<'CONFIRMATION_MALFORMED'> {\n return new AppliedTradeError(\n 'CONFIRMATION_MALFORMED',\n {},\n { uniqueKey: input.uniqueKey, status: response.status, body, url },\n );\n}\n\nfunction parseTradeExecution(value: unknown): TradeExecution | undefined {\n const record = asRecord(value);\n if (\n record === undefined ||\n typeof record['token0'] !== 'string' ||\n typeof record['token1'] !== 'string' ||\n typeof record['fee'] !== 'number'\n ) {\n return undefined;\n }\n const optionalFields = [\n 'sell0Qty',\n 'sell1Qty',\n 'buy0Qty',\n 'buy1Qty',\n 'tradingFees',\n 'protocolFees',\n 'totalFees',\n ] as const;\n for (const field of optionalFields) {\n if (field in record && typeof record[field] !== 'string') return undefined;\n }\n return {\n token0: record['token0'],\n token1: record['token1'],\n fee: record['fee'],\n ...Object.fromEntries(\n optionalFields.flatMap((field) =>\n typeof record[field] === 'string' ? [[field, record[field]]] : [],\n ),\n ),\n };\n}\n\nfunction isTransient(status: number): boolean {\n return status === 500 || status === 502 || status === 503 || status === 504;\n}\n\nfunction asRecord(value: unknown): Record<string, unknown> | undefined {\n return typeof value === 'object' && value !== null\n ? (value as Record<string, unknown>)\n : undefined;\n}\n"],"mappings":"8eA+CA,IAAa,EAAb,cAAkF,CAAiB,CACjG,YAAY,EAAS,EAA6B,EAA6B,CAAC,EAAG,CACjF,MAAM,EAAM,EAAQ,CAAO,EAC3B,KAAK,KAAO,mBACd,CACF,EAyCA,eAAsB,EACpB,EACA,EACA,EACuB,CACvB,GAAM,CAAE,aAAc,EACtB,GAAI,CAAC,EAAiB,CAAS,EAC7B,MAAM,IAAI,EACR,qBACA,CAAE,UAAW,OAAO,CAAS,CAAE,EAC/B,CAAE,WAAU,CACd,EAEF,IAAM,EAAY,EAAO,eAAiB,EACpC,EAAmB,EAAO,kBAAoB,IAC9C,EAAS,GAAS,OAClB,EAAc,GAClB,IAAI,EAAkB,uBAAwB,CAAC,EAAG,CAAE,YAAW,OAAM,CAAC,EAClE,EAAM,GAAG,EAAO,kBAAkB,QAAQ,OAAQ,EAAE,EAAE,0BAA0B,mBAAmB,CAAS,EAAE,sCAE9G,EAAW,EAA2B,EAAS,IAA0B,CAAU,EACzF,MAAM,EAAS,YAAY,EAC3B,IAAI,EAEJ,OAAa,CACX,EAAe,EAAQ,CAAU,EACjC,IAAI,EACA,EACJ,GAAI,CACF,EAAW,MAAM,EACf,EACA,EACA,CACE,OAAQ,MACR,QAAS,EAAoB,EAAO,IAAI,EACxC,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ACA,qBAAsB,EAAM,qBAC5B,qBACA,cACA,OAAQ,EAAS,OACjB,OACA,KACF,CACF,EAEF,GAAI,IAAW,EAAG,MAAM,EAAU,EAAO,EAAU,EAAM,CAAG,EAC5D,IAAM,EAAS,EAAoB,GAAS,IAAO,EACnD,GAAI,IAAW,IAAA,GAAW,MAAM,EAAU,EAAO,EAAU,EAAM,CAAG,EACpE,MAAO,CACL,YACA,cAAe,EACf,cACA,qBAAsB,EAAM,qBAC5B,QACF,CACF,CAEA,SAAS,EACP,EACA,EACA,EACA,EAC6C,CAC7C,OAAO,IAAI,EACT,yBACA,CAAC,EACD,CAAE,UAAW,EAAM,UAAW,OAAQ,EAAS,OAAQ,OAAM,KAAI,CACnE,CACF,CAEA,SAAS,EAAoB,EAA4C,CACvE,IAAM,EAAS,EAAS,CAAK,EAC7B,GACE,IAAW,IAAA,IACX,OAAO,EAAO,QAAc,UAC5B,OAAO,EAAO,QAAc,UAC5B,OAAO,EAAO,KAAW,SAEzB,OAEF,IAAM,EAAiB,CACrB,WACA,WACA,UACA,UACA,cACA,eACA,WACF,EACA,IAAK,IAAM,KAAS,EAClB,GAAI,KAAS,GAAU,OAAO,EAAO,IAAW,SAAU,OAE5D,MAAO,CACL,OAAQ,EAAO,OACf,OAAQ,EAAO,OACf,IAAK,EAAO,IACZ,GAAG,OAAO,YACR,EAAe,QAAS,GACtB,OAAO,EAAO,IAAW,SAAW,CAAC,CAAC,EAAO,EAAO,EAAM,CAAC,EAAI,CAAC,CAClE,CACF,CACF,CACF,CAEA,SAAS,EAAY,EAAyB,CAC5C,OAAO,IAAW,KAAO,IAAW,KAAO,IAAW,KAAO,IAAW,GAC1E,CAEA,SAAS,EAAS,EAAqD,CACrE,OAAO,OAAO,GAAU,UAAY,EAC/B,EACD,IAAA,EACN"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{GSwapSDKError as e,getObjectProperty as t}from"./gswap_sdk_error.js";import{validateWalletAddress as n}from"../utils/validation.js";var r=class{constructor(e,t){this.dexBackendBaseUrl=e,this.httpClient=t}async getUserAssets(t,r=1,a=10){if(n(t),!Number.isInteger(r)||r<1)throw new e(`INVALID_PAGE`,{value:r});if(!Number.isInteger(a)||a<1||a>100)throw new e(`INVALID_LIMIT`,{value:a,min:1,max:100});return i(await this.httpClient.sendGetRequest(this.dexBackendBaseUrl,`/user/assets`,``,{address:t,page:r.toString(),limit:a.toString()}))}};function i(n){let r=t(n,`data`),i=r?.token;if(!Array.isArray(i)||!i.every(a))throw new e(`INVALID_CHAIN_RESPONSE`,{resource:`user assets response`},{body:n});let o=r?.count;return{tokens:i.map(e=>({...e,decimals:parseInt(e.decimals,10)})),count:typeof o==`number`?o:0}}function a(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.image==`string`&&typeof t.name==`string`&&typeof t.decimals==`string`&&/^\d+$/u.test(t.decimals)&&typeof t.verify==`boolean`&&typeof t.symbol==`string`&&typeof t.quantity==`string`}export{r as Assets};
|
|
2
|
+
//# sourceMappingURL=assets.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"assets.js","names":[],"sources":["../../../src/classes/assets.ts"],"sourcesContent":["import type { UserAsset, UserAssetsResult } from '../types/v2_results.js';\nimport { validateWalletAddress } from '../utils/validation.js';\nimport { getObjectProperty, GSwapSDKError } from './gswap_sdk_error.js';\nimport type { HttpClient } from './http_client.js';\n\n/**\n * Service for handling user asset operations.\n * Provides functionality to retrieve user token balances and asset information.\n */\nexport class Assets {\n constructor(\n private readonly dexBackendBaseUrl: string,\n private readonly httpClient: HttpClient,\n ) {}\n\n /**\n * Gets all token assets owned by a user with their balances.\n * @param ownerAddress - The wallet address to get assets for.\n * @param page - Page number for pagination (default: 1).\n * @param limit - Maximum number of assets to return per page (default: 10).\n * @returns User assets including token information and balances.\n * @example\n * ```typescript\n * const assets = await assetsService.getUserAssets('eth|123...abc', 1, 20);\n * console.log(`User has ${assets.count} different tokens`);\n * assets.tokens.forEach(token => {\n * console.log(`${token.symbol}: ${token.quantity}`);\n * });\n * ```\n */\n async getUserAssets(\n ownerAddress: string,\n page: number = 1,\n limit: number = 10,\n ): Promise<UserAssetsResult> {\n validateWalletAddress(ownerAddress);\n\n if (!Number.isInteger(page) || page < 1) {\n throw new GSwapSDKError('INVALID_PAGE', { value: page });\n }\n\n if (!Number.isInteger(limit) || limit < 1 || limit > 100) {\n throw new GSwapSDKError('INVALID_LIMIT', { value: limit, min: 1, max: 100 });\n }\n\n const json: unknown = await this.httpClient.sendGetRequest(\n this.dexBackendBaseUrl,\n '/user/assets',\n '',\n { address: ownerAddress, page: page.toString(), limit: limit.toString() },\n );\n return parseUserAssets(json);\n }\n}\n\nfunction parseUserAssets(value: unknown): UserAssetsResult {\n const data = getObjectProperty(value, 'data');\n // Not getObjectProperty — that's typed for object properties, and Array.isArray on its\n // Record<string, unknown> return type narrows to any[] instead of a real array type.\n const tokens: unknown = data?.['token'];\n if (!Array.isArray(tokens) || !tokens.every(isRawUserAsset)) {\n throw new GSwapSDKError(\n 'INVALID_CHAIN_RESPONSE',\n { resource: 'user assets response' },\n { body: value },\n );\n }\n const count = data?.['count'];\n return {\n tokens: tokens.map((token) => ({ ...token, decimals: parseInt(token.decimals, 10) })),\n count: typeof count === 'number' ? count : 0,\n };\n}\n\ntype RawUserAsset = Omit<UserAsset, 'decimals'> & { decimals: string };\n\nfunction isRawUserAsset(value: unknown): value is RawUserAsset {\n if (typeof value !== 'object' || value === null) return false;\n const entry = value as Record<string, unknown>;\n return (\n typeof entry['image'] === 'string' &&\n typeof entry['name'] === 'string' &&\n typeof entry['decimals'] === 'string' &&\n /^\\d+$/u.test(entry['decimals']) &&\n typeof entry['verify'] === 'boolean' &&\n typeof entry['symbol'] === 'string' &&\n typeof entry['quantity'] === 'string'\n );\n}\n"],"mappings":"2IASA,IAAa,EAAb,KAAoB,CAClB,YACE,EACA,EACA,CAFiB,KAAA,kBAAA,EACA,KAAA,WAAA,CAChB,CAiBH,MAAM,cACJ,EACA,EAA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import{GSwapSDKError as t}from"./gswap_sdk_error.js";import{buildRequestHeaders as n,fetchRequestor as r,readResponseBody as i,requestWithTimeout as a}from"../utils/transport.js";import{signPreSend as o}from"../utils/pre_send.js";const s=[`Swap`,`RequestTrade`,`AddLiquidity`,`RemoveLiquidity`,`CollectPositionFees`,`CreatePool`],c=`DryRun`,l=`galaconnect-operation-`;function u(e){return typeof e==`string`&&s.includes(e)}function d(e,t){return u(t)&&typeof e?.token0==`string`&&typeof e.token1==`string`}function f(e){let t={...e};for(let e of[`signature`,`prefix`,`types`,`domain`,`trace`])delete t[e];return t}function p(e,t,n,r,i=l){return o(e,c,{callerPublicKey:t,method:n,dto:r,uniqueKey:`${i}${globalThis.crypto.randomUUID()}`})}var m=class{constructor(t,n){this.signer=n,e(this,`requestor`,void 0),e(this,`baseUrl`,void 0),e(this,`requestTimeoutMs`,void 0),e(this,`wire`,void 0),this.requestor=t.httpRequestor??r,this.baseUrl=t.dexBackendBaseUrl.replace(/\/$/u,``),this.requestTimeoutMs=t.requestTimeoutMs??3e4,this.wire=t.wire}async quote(e,r,o,s={}){if(this.signer===void 0)throw t.noSignerError();let c=s.channel??`asset`,l=s.contract??`dexv3-contract`,u=await p(this.signer,e,r,f(o)),d=`${this.baseUrl}/wallet/connect/galachain/api/${encodeURIComponent(c)}/${encodeURIComponent(l)}/${encodeURIComponent(r)}/fee`,m,g,_;try{let e=await a(this.requestor,d,{method:`POST`,headers:n(this.wire,{json:!0,defaults:{Accept:`application/json`}}),body:JSON.stringify(u)},this.requestTimeoutMs);m=e.status,g=e.ok,_=g?await i(e):void 0}catch{return null}return g?h(_):l===`dex-contract`&&(m===403||m===404)?{source:`default`,fees:[{feeInGala:`0`}]}:null}};function h(e){if(typeof e!=`object`||!e)return null;let t=e.fees;return!Array.isArray(t)||typeof t[0]?.feeInGala!=`string`?null:e}export{s as DEX_FEE_METHODS,c as DRY_RUN_METHOD,l as DRY_RUN_UNIQUE_KEY_PREFIX,m as DexFees,p as buildDryRunWrapper,d as isCurrentContractDexMessage,u as isDexFeeMethod,f as toChainDto};
|
|
2
|
+
//# sourceMappingURL=dex_fees.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"dex_fees.js","names":[],"sources":["../../../src/classes/dex_fees.ts"],"sourcesContent":["import type { HttpRequestor } from '../types/http_requestor.js';\nimport type { WireOptions } from '../types/wire.js';\nimport {\n buildRequestHeaders,\n fetchRequestor,\n readResponseBody,\n requestWithTimeout,\n} from '../utils/transport.js';\nimport { signPreSend } from '../utils/pre_send.js';\nimport { GSwapSDKError } from './gswap_sdk_error.js';\nimport type { GalaChainSigner } from './signers.js';\n\n/** DEX methods the backend accepts a fee quote for (its allow-list enumerates the same six). */\nexport const DEX_FEE_METHODS = [\n 'Swap',\n 'RequestTrade',\n 'AddLiquidity',\n 'RemoveLiquidity',\n 'CollectPositionFees',\n 'CreatePool',\n] as const;\n/** A chain method whose network fee `DexFees.quote` can price (see `isDexFeeMethod`). */\nexport type DexFeeMethod = (typeof DEX_FEE_METHODS)[number];\n\n/** Which pool contract the DTO being quoted targets: legacy (V3) or current (GalaChainDex). */\nexport type DexFeeContract = 'dexv3-contract' | 'dex-contract';\n\n/** The chain method name the signed DryRun wrapper is signed under. */\nexport const DRY_RUN_METHOD = 'DryRun';\n\n/** `uniqueKey` prefix of the DryRun WRAPPER (distinct from the inner DTO's key). */\nexport const DRY_RUN_UNIQUE_KEY_PREFIX = 'galaconnect-operation-';\n\n/** True when `method` is a DEX method a fee can be quoted for. */\nexport function isDexFeeMethod(method: unknown): method is DexFeeMethod {\n return typeof method === 'string' && (DEX_FEE_METHODS as readonly string[]).includes(method);\n}\n\n/** Current-contract typed DEX messages use trading symbols instead of TokenClassKey objects. */\nexport function isCurrentContractDexMessage(\n message: Record<string, unknown> | null | undefined,\n method: unknown,\n): boolean {\n return (\n isDexFeeMethod(method) &&\n typeof message?.['token0'] === 'string' &&\n typeof message['token1'] === 'string'\n );\n}\n\n/**\n * The backend's response. It ALWAYS carries a usable `fees[0].feeInGala`: the backend decides what\n * to serve when the chain cannot price the operation, so the client never invents a fee.\n *\n * `source` is informational: `'dry-run'` is simulated on chain and authoritative (possibly a\n * legitimate `'0'`), `'default'` means the chain could not price it and the platform default was\n * served.\n */\nexport interface DexFeeQuote {\n fees: Array<{ feeInGala: string }>;\n source: 'dry-run' | 'default';\n}\n\n/**\n * Reduces an EIP-712 approval `message` to the DTO the chain actually receives: drops the signing\n * envelope (`signature`, `prefix`, `types`, `domain`) and transport metadata (`trace`).\n */\nexport function toChainDto(message: Record<string, unknown>): Record<string, unknown> {\n const chainDto: Record<string, unknown> = { ...message };\n for (const field of ['signature', 'prefix', 'types', 'domain', 'trace']) {\n delete chainDto[field];\n }\n return chainDto;\n}\n\n/**\n * Signs the DryRun WRAPPER the gateway accepts for every contract:\n * `{ callerPublicKey, method, dto: <inner DTO object>, uniqueKey, signature }`. The inner DTO\n * travels unsigned and as an object; no `signerPublicKey` is sent because the signature already\n * recovers it (the gateway rejects it as REDUNDANT_SIGNER_PUBLIC_KEY). The wrapper carries its own\n * `uniqueKey`, distinct from the DTO's.\n */\nexport function buildDryRunWrapper(\n signer: GalaChainSigner,\n callerPublicKey: string,\n method: string,\n dto: Record<string, unknown>,\n uniqueKeyPrefix: string = DRY_RUN_UNIQUE_KEY_PREFIX,\n): Promise<Record<string, unknown>> {\n return signPreSend(signer, DRY_RUN_METHOD, {\n callerPublicKey,\n method,\n dto,\n uniqueKey: `${uniqueKeyPrefix}${globalThis.crypto.randomUUID()}`,\n });\n}\n\n/** The transport and backend a fee quote reads from. */\nexport interface DexFeesClient {\n /** Swap backend origin, e.g. `https://dex-backend-prod1.defi.gala.com`. */\n dexBackendBaseUrl: string;\n /** Defaults to the global `fetch`. */\n httpRequestor?: HttpRequestor | undefined;\n /** Per-request timeout in milliseconds (default 30 000). */\n requestTimeoutMs?: number | undefined;\n /**\n * Request headers of the fee POST (`userAgent`, `headers`); see {@link WireOptions}. The SDK's\n * `Accept: application/json` is a default that `wire.headers` may replace.\n */\n wire?: WireOptions | undefined;\n}\n\n/** Options for a single quote. */\nexport interface DexFeeQuoteOptions {\n /** GalaChain channel. Default `asset`. */\n channel?: string | undefined;\n /**\n * Contract the DTO targets. Default `dexv3-contract` (what every legacy caller quotes against);\n * a current-contract operation must pass `dex-contract` explicitly.\n */\n contract?: DexFeeContract | undefined;\n}\n\n/**\n * Network-fee quote for GalaChain DEX methods, derived from a server-side DryRun.\n *\n * The client only SIGNS the DryRun wrapper (with whatever {@link GalaChainSigner} it is given) and\n * the backend forwards it to the gateway, where the simulated writes carry the fee; the backend\n * never holds a key. Intended for wallets: the DTO quoted is the typed message a dApp handed over.\n *\n * @example\n * ```ts\n * const fees = new DexFees({ dexBackendBaseUrl }, new PrivateKeySigner(sessionKey));\n * const quote = await fees.quote(publicKey, 'RequestTrade', toChainDto(message), {\n * contract: 'dex-contract',\n * });\n * const feeInGala = quote?.fees[0]?.feeInGala;\n * ```\n */\nexport class DexFees {\n private readonly requestor: HttpRequestor;\n private readonly baseUrl: string;\n private readonly requestTimeoutMs: number;\n private readonly wire: WireOptions | undefined;\n\n constructor(\n client: DexFeesClient,\n private readonly signer: GalaChainSigner | undefined,\n ) {\n this.requestor = client.httpRequestor ?? fetchRequestor;\n this.baseUrl = client.dexBackendBaseUrl.replace(/\\/$/u, '');\n this.requestTimeoutMs = client.requestTimeoutMs ?? 30_000;\n this.wire = client.wire;\n }\n\n /**\n * Quotes the network fee for `method` applied to `message`. The message is reduced with\n * {@link toChainDto} first, so an EIP-712 approval message can be passed as is.\n *\n * Resolves `null` when the BACKEND could not be reached or answered unusably (offline, 4xx/5xx,\n * malformed body): a transport outcome, not a fee. Deciding what to charge when the chain is\n * silent is the backend's job (it serves `source: 'default'`), so the client never substitutes\n * a fee of its own, with ONE exception that mirrors the wallet: a `dex-contract` quote answered\n * 403 or 404 means the contract has no fee route yet and resolves `{ source: 'default', '0' }`.\n * Never throws on transport, so a fee lookup cannot block or break a signing screen.\n *\n * @throws GSwapSDKError NO_SIGNER when constructed without a signer; `SIGNING_FAILED` or\n * `KEY_PROVIDER_FAILED` (a pre-send error, the original as `cause`) when the signer fails, for\n * example a locked wallet.\n */\n public async quote(\n callerPublicKey: string,\n method: DexFeeMethod,\n message: Record<string, unknown>,\n options: DexFeeQuoteOptions = {},\n ): Promise<DexFeeQuote | null> {\n if (this.signer === undefined) throw GSwapSDKError.noSignerError();\n const channel = options.channel ?? 'asset';\n const contract = options.contract ?? 'dexv3-contract';\n const wrapper = await buildDryRunWrapper(\n this.signer,\n callerPublicKey,\n method,\n toChainDto(message),\n );\n const url = `${this.baseUrl}/wallet/connect/galachain/api/${encodeURIComponent(channel)}/${encodeURIComponent(contract)}/${encodeURIComponent(method)}/fee`;\n\n let status: number;\n let ok: boolean;\n let body: unknown;\n try {\n const response = await requestWithTimeout(\n this.requestor,\n url,\n {\n method: 'POST',\n headers: buildRequestHeaders(this.wire, {\n json: true,\n defaults: { Accept: 'application/json' },\n }),\n body: JSON.stringify(wrapper),\n },\n this.requestTimeoutMs,\n );\n status = response.status;\n ok = response.ok;\n body = ok ? await readResponseBody(response) : undefined;\n } catch {\n return null;\n }\n\n if (!ok) {\n if (contract === 'dex-contract' && (status === 403 || status === 404)) {\n return { source: 'default', fees: [{ feeInGala: '0' }] };\n }\n return null;\n }\n // Accept whatever fee the backend served: 'default' is as usable as 'dry-run'. Only a body\n // missing the fee outright is unusable.\n return readQuote(body);\n }\n}\n\nfunction readQuote(body: unknown): DexFeeQuote | null {\n if (typeof body !== 'object' || body === null) return null;\n const fees = (body as { fees?: unknown }).fees;\n if (\n !Array.isArray(fees) ||\n typeof (fees[0] as { feeInGala?: unknown } | undefined)?.feeInGala !== 'string'\n ) {\n return null;\n }\n return body as DexFeeQuote;\n}\n"],"mappings":"6TAaA,MAAa,EAAkB,CAC7B,OACA,eACA,eACA,kBACA,sBACA,YACF,EAQa,EAAiB,SAGjB,EAA4B,yBAGzC,SAAgB,EAAe,EAAyC,CACtE,O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B,KAAK,UACL,EACA,CACE,OAAQ,OACR,QAAS,EAAoB,KAAK,KAAM,CACtC,KAAM,GACN,SAAU,CAAE,OAAQ,kBAAmB,CACzC,CAAC,EACD,KAAM,KAAK,UAAU,CAAO,CAC9B,EACA,KAAK,gBACP,EACA,EAAS,EAAS,OAClB,EAAK,EAAS,GACd,EAAO,EAAK,MAAM,EAAiB,CAAQ,EAAI,IAAA,EACjD,MAAQ,CACN,OAAO,IACT,CAUA,OARK,EAQE,EAAU,CAAI,EAPf,IAAa,iBAAmB,IAAW,KAAO,IAAW,KACxD,CAAE,OAAQ,UAAW,KAAM,CAAC,CAAE,UAAW,GAAI,CAAC,CAAE,EAElD,IAKX,CACF,EAEA,SAAS,EAAU,EAAmC,CACpD,GAAI,OAAO,GAAS,WAAY,EAAe,OAAO,KACtD,IAAM,EAAQ,EAA4B,KAO1C,MALE,CAAC,MAAM,QAAQ,CAAI,GACnB,OAAQ,EAAK,EAAE,EAA0C,WAAc,SAEhE,KAEF,CACT"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e=[`wrong_length`,`bad_encoding`,`not_on_curve`,`no_key_provided`],t=[`timeout`,`transport`],n=[`user_rejected`,`failed`],r=`0,500,3000,10000`,i={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_TIMEOUT:{phase:`in_flight`,template:`Request to {url} timed out after {timeoutMs} ms.`,params:{url:`string`,timeoutMs:`number`}},TRANSPORT_ERROR:{phase:`in_flight`,template:`The request to {url} failed before the server answered.`,params:{url:`string`}},REQUEST_FAILED:{phase:`in_flight`,template:`The {operation} request failed.`,params:{operation:`string`}},INVALID_TIMEOUT:{phase:`pre_send`,template:`{field} must be a positive number of milliseconds, or Infinity for no timeout (got {value}).`,params:{field:`string`,value:`number`}},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`}},GALA_WALLET_NOT_AVAILABLE:{phase:`pre_send`,template:`Gala wallet is not available. Please ensure the Gala wallet is connected.`,params:{}},WALLET_UNAVAILABLE:{phase:`pre_send`,template:`No wallet is connected.`,params:{}},MALFORMED_WALLET_REQUEST:{phase:`pre_send`,template:`Wallet {method} request is malformed.`,params:{method:`string`}},UNSUPPORTED_WALLET_METHOD:{phase:`pre_send`,template:`Unsupported wallet method {method}.`,params:{method:`string`}},INVALID_SIGNATURE:{phase:`pre_send`,template:`Wallet returned an invalid {scheme} signature.`,params:{scheme:`string`}},INVALID_CHAIN_ID:{phase:`pre_send`,template:`Wallet returned an invalid chain id ({chainId}).`,params:{chainId:`string`}},SIGNER_ADDRESS_MISMATCH:{phase:`pre_send`,template:`The signing key does not belong to the expected account.`,params:{}},INVALID_PRIVATE_KEY:{phase:`pre_send`,template:`Invalid private key: {reason}.`,params:{reason:e}},SIGNING_FAILED:{phase:`pre_send`,template:`Signing the {method} request failed ({reason}); nothing was sent.`,params:{method:`string`,reason:n}},KEY_PROVIDER_FAILED:{phase:`pre_send`,template:`The signing key could not be fetched; nothing was sent.`,params:{}},TOKEN_RESOLUTION_FAILED:{phase:`pre_send`,template:`Token {token} could not be looked up; nothing was sent.`,params:{token:`string`}},INVALID_SIGNING_HASH_LENGTH:{phase:`pre_send`,template:`secp256k1 can only sign a 32-byte hash (got {length}).`,params:{length:`number`}},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:{}},INVALID_WALLET_ADDRESS:{phase:`pre_send`,template:`Invalid {field}: "{value}" is not an accepted wallet address form.`,params:{field:`string`,value:`string`}},INVALID_DECIMAL:{phase:`pre_send`,template:`Invalid decimal quantity: {value}`,params:{value:`string`}},PERSONAL_SIGN_NOT_JSON:{phase:`pre_send`,template:`Personal-sign DTO is not valid JSON`,params:{}},PERSONAL_SIGN_NOT_OBJECT:{phase:`pre_send`,template:`Personal-sign DTO must be a JSON object`,params:{}},PERSONAL_SIGN_BAD_PREFIX:{phase:`pre_send`,template:`Personal-sign DTO prefix is not an EIP-191 "Ethereum Signed Message" header`,params:{}},PERSONAL_SIGN_ENVELOPE_FIELDS:{phase:`pre_send`,template:`Personal-sign DTO carries signing-envelope field(s): {fields}`,params:{fields:`string`}},PERSONAL_SIGN_NOT_CANONICAL:{phase:`pre_send`,template:`Personal-sign DTO is not in canonical serialized form`,params:{}},EIP712_NAME_COLLISION:{phase:`pre_send`,template:`Name collisions are not supported when deriving EIP-712 types ({name}).`,params:{name:`string`}},EIP712_UNSUPPORTED_VALUE:{phase:`pre_send`,template:`Unsupported EIP-712 value of type {valueType}.`,params:{valueType:`string`}},TYPED_DATA_NOT_STRING:{phase:`pre_send`,template:`Invalid typed data: {what} must be a string`,params:{what:`string`}},TYPED_DATA_UNPAIRED_SURROGATE:{phase:`pre_send`,template:`Invalid typed data: {what} has an unpaired surrogate`,params:{what:`string`}},TYPED_DATA_NOT_HEX_BYTES:{phase:`pre_send`,template:`Invalid typed data: {what} must be an even-length 0x hex string`,params:{what:`string`}},TYPED_DATA_NOT_SAFE_INTEGER:{phase:`pre_send`,template:`Invalid typed data: {what} must be a safe integer`,params:{what:`string`}},TYPED_DATA_NOT_INTEGER:{phase:`pre_send`,template:`Invalid typed data: {what} must be an integer`,params:{what:`string`}},TYPED_DATA_NOT_BOOLEAN:{phase:`pre_send`,template:`Invalid typed data: bool must be a boolean`,params:{}},TYPED_DATA_BAD_ADDRESS:{phase:`pre_send`,template:`Invalid typed data: address must be 0x followed by 40 hex digits`,params:{}},TYPED_DATA_BAD_CHECKSUM:{phase:`pre_send`,template:`Invalid typed data: address has a bad checksum`,params:{}},TYPED_DATA_BYTES_LENGTH:{phase:`pre_send`,template:`Invalid typed data: {type} must be exactly {width} bytes`,params:{type:`string`,width:`number`}},TYPED_DATA_OUT_OF_BOUNDS:{phase:`pre_send`,template:`Invalid typed data: value out of bounds for {type}`,params:{type:`string`}},TYPED_DATA_UNSUPPORTED_TYPE:{phase:`pre_send`,template:`Invalid typed data: unsupported type "{type}"`,params:{type:`string`}},TYPED_DATA_FIELDS_NOT_LIST:{phase:`pre_send`,template:`Invalid typed data: type {typeName} must be a list of fields`,params:{typeName:`string`}},TYPED_DATA_FIELD_MALFORMED:{phase:`pre_send`,template:`Invalid typed data: type {typeName} has a field without a string name and type`,params:{typeName:`string`}},TYPED_DATA_INVALID_FIELD_NAME:{phase:`pre_send`,template:`Invalid typed data: invalid field name "{name}"`,params:{name:`string`}},TYPED_DATA_DUPLICATE_FIELD:{phase:`pre_send`,template:`Invalid typed data: duplicate field "{name}" in {typeName}`,params:{name:`string`,typeName:`string`}},TYPED_DATA_INVALID_TYPE_NAME:{phase:`pre_send`,template:`Invalid typed data: invalid type name "{name}"`,params:{name:`string`}},TYPED_DATA_CIRCULAR_TYPE:{phase:`pre_send`,template:`Invalid typed data: circular type reference in {typeName}`,params:{typeName:`string`}},TYPED_DATA_UNKNOWN_FIELD_TYPE:{phase:`pre_send`,template:`Invalid typed data: unknown type "{type}" in {typeName}`,params:{type:`string`,typeName:`string`}},TYPED_DATA_NO_PRIMARY_TYPE:{phase:`pre_send`,template:`Invalid typed data: missing primary type`,params:{}},TYPED_DATA_AMBIGUOUS_PRIMARY_TYPE:{phase:`pre_send`,template:`Invalid typed data: ambiguous primary types or unused types ({roots})`,params:{roots:`string`}},TYPED_DATA_ARRAY_EXPECTED:{phase:`pre_send`,template:`Invalid typed data: {type} array value must be an array`,params:{type:`string`}},TYPED_DATA_ARRAY_LENGTH_MISMATCH:{phase:`pre_send`,template:`Invalid typed data: array length mismatch`,params:{}},TYPED_DATA_STRUCT_NOT_OBJECT:{phase:`pre_send`,template:`Invalid typed data: {typeName} value must be an object`,params:{typeName:`string`}},TYPED_DATA_MISSING_FIELD:{phase:`pre_send`,template:`Invalid typed data: {typeName} value is missing field "{field}"`,params:{typeName:`string`,field:`string`}},TYPED_DATA_DOMAIN_NOT_OBJECT:{phase:`pre_send`,template:`Invalid typed data: domain must be an object`,params:{}},TYPED_DATA_INVALID_DOMAIN_KEY:{phase:`pre_send`,template:`Invalid typed data: invalid typed-data domain key {key}`,params:{key:`string`}},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`}},INVALID_UNIQUE_KEY:{phase:`pre_send`,template:`The uniqueKey "{uniqueKey}" must be 1-128 characters of A-Z, a-z, 0-9, ".", "_", ":" or "-".`,params:{uniqueKey:`string`}},INVALID_UNIQUE_KEY_PREFIX:{phase:`pre_send`,template:`uniqueKeyPrefix "{uniqueKeyPrefix}" must be at most {maxLength} characters of A-Z, a-z, 0-9, ".", "_", ":" or "-".`,params:{uniqueKeyPrefix:`string`,maxLength:`number`}},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`}}},a=Object.fromEntries(Object.entries(i).map(([e,t])=>[e,t.template])),o=/\{([A-Za-z0-9_]+)\}/gu;function s(e,t){return e.replace(o,(e,n)=>{let r=t[n];return typeof r==`string`||typeof r==`number`||typeof r==`boolean`?String(r):e})}export{r as ALLOWED_FEE_TIERS_TEXT,i as GSWAP_ERROR_CATALOG,e as INVALID_PRIVATE_KEY_REASONS,n as SIGNING_FAILURE_REASONS,t as SUBMISSION_OUTCOME_UNKNOWN_REASONS,a as gswapErrorTemplates,s as renderGSwapErrorTemplate};
|
|
2
|
+
//# sourceMappingURL=error_catalog.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"error_catalog.js","names":[],"sources":["../../../src/classes/error_catalog.ts"],"sourcesContent":["/**\n * The catalog of every error the SDK throws: the SINGLE source of truth for its `code`, the\n * named parameters it carries and the English template its `message` is generated from.\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 * {@link GSwapErrorContext}.\n */\n\nimport type { GSwapErrorPhase } from './error_phases.js';\n\n/**\n * The kinds a param can have: a primitive, or a CLOSED set of string tokens (a readonly tuple).\n * A closed set is a documented union: an app maps each member to its own text and can check that\n * it covered all of them, and a new member is a compile error until it does.\n */\nexport type GSwapErrorParamKind = 'string' | 'number' | 'boolean' | readonly string[];\n\n/** One catalog entry. */\nexport interface GSwapErrorCatalogEntry {\n /** The phase this code is thrown in, unless a throw site says otherwise (see {@link GSwapErrorPhase}). */\n readonly phase: GSwapErrorPhase;\n /** English message template with `{placeholder}` markers. */\n readonly template: string;\n /** Param name to kind. Every param is required and appears in the template, except `unrendered`. */\n readonly params: Readonly<Record<string, GSwapErrorParamKind>>;\n /**\n * Params that are carried for the app but deliberately NOT placeholders of the template. Used\n * for `serverMessage` on the codes whose failing answer may be anything (a proxy's page, a\n * validation list): the server's text is data for the app to relay or ignore, and keeping it out\n * of `message` means it cannot reach a log line or a user interface by accident.\n */\n readonly unrendered?: readonly string[];\n}\n\n/**\n * Why a private key was refused (`INVALID_PRIVATE_KEY.params.reason`). A token for the app to map\n * to its own text, never English and never any part of the key.\n *\n * - `wrong_length`: raw bytes that are not 32 bytes long.\n * - `bad_encoding`: a string that is neither 64 hex characters (optionally `0x`-prefixed, 63 is\n * left-padded) nor a 44-character base64 string.\n * - `not_on_curve`: 32 bytes that are not a valid secp256k1 secret scalar.\n * - `no_key_provided`: a lazy key provider returned something that is not a string.\n */\nexport const INVALID_PRIVATE_KEY_REASONS = [\n 'wrong_length',\n 'bad_encoding',\n 'not_on_curve',\n 'no_key_provided',\n] as const;\n\n/** One member of {@link INVALID_PRIVATE_KEY_REASONS}. */\nexport type InvalidPrivateKeyReason = (typeof INVALID_PRIVATE_KEY_REASONS)[number];\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/**\n * Why a signer could not produce a signature (`SIGNING_FAILED.params.reason`). A token for the\n * app to map to its own text.\n *\n * - `user_rejected`: the person declined in their wallet (an EIP-1193 `4001`, an ethers\n * `ACTION_REJECTED`, or a wallet that words it \"User rejected/denied ...\"). Nothing is wrong:\n * they may simply try again.\n * - `failed`: anything else the signer threw (a locked wallet, an unreachable extension, a wallet\n * that refused). The original error is `cause`.\n */\nexport const SIGNING_FAILURE_REASONS = ['user_rejected', 'failed'] as const;\n\n/** One member of {@link SIGNING_FAILURE_REASONS}. */\nexport type SigningFailureReason = (typeof SIGNING_FAILURE_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 catalog. Add a code here before throwing it anywhere. */\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_TIMEOUT: {\n phase: 'in_flight',\n template: 'Request to {url} timed out after {timeoutMs} ms.',\n params: { url: 'string', timeoutMs: 'number' },\n },\n TRANSPORT_ERROR: {\n phase: 'in_flight',\n template: 'The request to {url} failed before the server answered.',\n params: { url: 'string' },\n },\n REQUEST_FAILED: {\n phase: 'in_flight',\n template: 'The {operation} request failed.',\n params: { operation: 'string' },\n },\n INVALID_TIMEOUT: {\n phase: 'pre_send',\n template:\n '{field} must be a positive number of milliseconds, or Infinity for no timeout (got {value}).',\n params: { field: 'string', value: 'number' },\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 GALA_WALLET_NOT_AVAILABLE: {\n phase: 'pre_send',\n template: 'Gala wallet is not available. Please ensure the Gala wallet is connected.',\n params: {},\n },\n WALLET_UNAVAILABLE: {\n phase: 'pre_send',\n template: 'No wallet is connected.',\n params: {},\n },\n MALFORMED_WALLET_REQUEST: {\n phase: 'pre_send',\n template: 'Wallet {method} request is malformed.',\n params: { method: 'string' },\n },\n UNSUPPORTED_WALLET_METHOD: {\n phase: 'pre_send',\n template: 'Unsupported wallet method {method}.',\n params: { method: 'string' },\n },\n INVALID_SIGNATURE: {\n phase: 'pre_send',\n template: 'Wallet returned an invalid {scheme} signature.',\n params: { scheme: 'string' },\n },\n INVALID_CHAIN_ID: {\n phase: 'pre_send',\n template: 'Wallet returned an invalid chain id ({chainId}).',\n params: { chainId: 'string' },\n },\n SIGNER_ADDRESS_MISMATCH: {\n phase: 'pre_send',\n template: 'The signing key does not belong to the expected account.',\n params: {},\n },\n INVALID_PRIVATE_KEY: {\n phase: 'pre_send',\n template: 'Invalid private key: {reason}.',\n params: { reason: INVALID_PRIVATE_KEY_REASONS },\n },\n SIGNING_FAILED: {\n phase: 'pre_send',\n template: 'Signing the {method} request failed ({reason}); nothing was sent.',\n params: { method: 'string', reason: SIGNING_FAILURE_REASONS },\n },\n KEY_PROVIDER_FAILED: {\n phase: 'pre_send',\n template: 'The signing key could not be fetched; nothing was sent.',\n params: {},\n },\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 INVALID_SIGNING_HASH_LENGTH: {\n phase: 'pre_send',\n template: 'secp256k1 can only sign a 32-byte hash (got {length}).',\n params: { length: 'number' },\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 INVALID_WALLET_ADDRESS: {\n phase: 'pre_send',\n template: 'Invalid {field}: \"{value}\" is not an accepted wallet address form.',\n params: { field: 'string', value: 'string' },\n },\n INVALID_DECIMAL: {\n phase: 'pre_send',\n template: 'Invalid decimal quantity: {value}',\n params: { value: 'string' },\n },\n\n // ------------------------------------------------------------------------- personal-sign DTOs\n PERSONAL_SIGN_NOT_JSON: {\n phase: 'pre_send',\n template: 'Personal-sign DTO is not valid JSON',\n params: {},\n },\n PERSONAL_SIGN_NOT_OBJECT: {\n phase: 'pre_send',\n template: 'Personal-sign DTO must be a JSON object',\n params: {},\n },\n PERSONAL_SIGN_BAD_PREFIX: {\n phase: 'pre_send',\n template: 'Personal-sign DTO prefix is not an EIP-191 \"Ethereum Signed Message\" header',\n params: {},\n },\n PERSONAL_SIGN_ENVELOPE_FIELDS: {\n phase: 'pre_send',\n template: 'Personal-sign DTO carries signing-envelope field(s): {fields}',\n params: { fields: 'string' },\n },\n PERSONAL_SIGN_NOT_CANONICAL: {\n phase: 'pre_send',\n template: 'Personal-sign DTO is not in canonical serialized form',\n params: {},\n },\n\n // ------------------------------------------------------------------ EIP-712 payload derivation\n EIP712_NAME_COLLISION: {\n phase: 'pre_send',\n template: 'Name collisions are not supported when deriving EIP-712 types ({name}).',\n params: { name: 'string' },\n },\n EIP712_UNSUPPORTED_VALUE: {\n phase: 'pre_send',\n template: 'Unsupported EIP-712 value of type {valueType}.',\n params: { valueType: 'string' },\n },\n\n // ----------------------------------------------------------------------------- EIP-712 typed data\n TYPED_DATA_NOT_STRING: {\n phase: 'pre_send',\n template: 'Invalid typed data: {what} must be a string',\n params: { what: 'string' },\n },\n TYPED_DATA_UNPAIRED_SURROGATE: {\n phase: 'pre_send',\n template: 'Invalid typed data: {what} has an unpaired surrogate',\n params: { what: 'string' },\n },\n TYPED_DATA_NOT_HEX_BYTES: {\n phase: 'pre_send',\n template: 'Invalid typed data: {what} must be an even-length 0x hex string',\n params: { what: 'string' },\n },\n TYPED_DATA_NOT_SAFE_INTEGER: {\n phase: 'pre_send',\n template: 'Invalid typed data: {what} must be a safe integer',\n params: { what: 'string' },\n },\n TYPED_DATA_NOT_INTEGER: {\n phase: 'pre_send',\n template: 'Invalid typed data: {what} must be an integer',\n params: { what: 'string' },\n },\n TYPED_DATA_NOT_BOOLEAN: {\n phase: 'pre_send',\n template: 'Invalid typed data: bool must be a boolean',\n params: {},\n },\n TYPED_DATA_BAD_ADDRESS: {\n phase: 'pre_send',\n template: 'Invalid typed data: address must be 0x followed by 40 hex digits',\n params: {},\n },\n TYPED_DATA_BAD_CHECKSUM: {\n phase: 'pre_send',\n template: 'Invalid typed data: address has a bad checksum',\n params: {},\n },\n TYPED_DATA_BYTES_LENGTH: {\n phase: 'pre_send',\n template: 'Invalid typed data: {type} must be exactly {width} bytes',\n params: { type: 'string', width: 'number' },\n },\n TYPED_DATA_OUT_OF_BOUNDS: {\n phase: 'pre_send',\n template: 'Invalid typed data: value out of bounds for {type}',\n params: { type: 'string' },\n },\n TYPED_DATA_UNSUPPORTED_TYPE: {\n phase: 'pre_send',\n template: 'Invalid typed data: unsupported type \"{type}\"',\n params: { type: 'string' },\n },\n TYPED_DATA_FIELDS_NOT_LIST: {\n phase: 'pre_send',\n template: 'Invalid typed data: type {typeName} must be a list of fields',\n params: { typeName: 'string' },\n },\n TYPED_DATA_FIELD_MALFORMED: {\n phase: 'pre_send',\n template: 'Invalid typed data: type {typeName} has a field without a string name and type',\n params: { typeName: 'string' },\n },\n TYPED_DATA_INVALID_FIELD_NAME: {\n phase: 'pre_send',\n template: 'Invalid typed data: invalid field name \"{name}\"',\n params: { name: 'string' },\n },\n TYPED_DATA_DUPLICATE_FIELD: {\n phase: 'pre_send',\n template: 'Invalid typed data: duplicate field \"{name}\" in {typeName}',\n params: { name: 'string', typeName: 'string' },\n },\n TYPED_DATA_INVALID_TYPE_NAME: {\n phase: 'pre_send',\n template: 'Invalid typed data: invalid type name \"{name}\"',\n params: { name: 'string' },\n },\n TYPED_DATA_CIRCULAR_TYPE: {\n phase: 'pre_send',\n template: 'Invalid typed data: circular type reference in {typeName}',\n params: { typeName: 'string' },\n },\n TYPED_DATA_UNKNOWN_FIELD_TYPE: {\n phase: 'pre_send',\n template: 'Invalid typed data: unknown type \"{type}\" in {typeName}',\n params: { type: 'string', typeName: 'string' },\n },\n TYPED_DATA_NO_PRIMARY_TYPE: {\n phase: 'pre_send',\n template: 'Invalid typed data: missing primary type',\n params: {},\n },\n TYPED_DATA_AMBIGUOUS_PRIMARY_TYPE: {\n phase: 'pre_send',\n template: 'Invalid typed data: ambiguous primary types or unused types ({roots})',\n params: { roots: 'string' },\n },\n TYPED_DATA_ARRAY_EXPECTED: {\n phase: 'pre_send',\n template: 'Invalid typed data: {type} array value must be an array',\n params: { type: 'string' },\n },\n TYPED_DATA_ARRAY_LENGTH_MISMATCH: {\n phase: 'pre_send',\n template: 'Invalid typed data: array length mismatch',\n params: {},\n },\n TYPED_DATA_STRUCT_NOT_OBJECT: {\n phase: 'pre_send',\n template: 'Invalid typed data: {typeName} value must be an object',\n params: { typeName: 'string' },\n },\n TYPED_DATA_MISSING_FIELD: {\n phase: 'pre_send',\n template: 'Invalid typed data: {typeName} value is missing field \"{field}\"',\n params: { typeName: 'string', field: 'string' },\n },\n TYPED_DATA_DOMAIN_NOT_OBJECT: {\n phase: 'pre_send',\n template: 'Invalid typed data: domain must be an object',\n params: {},\n },\n TYPED_DATA_INVALID_DOMAIN_KEY: {\n phase: 'pre_send',\n template: 'Invalid typed data: invalid typed-data domain key {key}',\n params: { key: 'string' },\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 INVALID_UNIQUE_KEY: {\n phase: 'pre_send',\n template:\n 'The uniqueKey \"{uniqueKey}\" must be 1-128 characters of A-Z, a-z, 0-9, \".\", \"_\", \":\" or \"-\".',\n params: { uniqueKey: 'string' },\n },\n INVALID_UNIQUE_KEY_PREFIX: {\n phase: 'pre_send',\n template:\n 'uniqueKeyPrefix \"{uniqueKeyPrefix}\" must be at most {maxLength} characters of A-Z, a-z, 0-9, \".\", \"_\", \":\" or \"-\".',\n params: { uniqueKeyPrefix: 'string', maxLength: 'number' },\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} as const satisfies Record<string, GSwapErrorCatalogEntry>;\n\n/** Every error code the SDK can throw. */\nexport type GSwapErrorCode = keyof typeof GSWAP_ERROR_CATALOG;\n\ninterface KindToType {\n string: string;\n number: number;\n boolean: boolean;\n}\n\n/** The value type of a param kind: a primitive, or the union of a closed set's members. */\ntype ParamValue<K> = K extends readonly (infer Member)[]\n ? Member\n : K extends keyof KindToType\n ? KindToType[K]\n : never;\n\n/** The named params of one error code: a flat object of primitives (or closed string tokens). */\nexport type GSwapErrorParams<C extends GSwapErrorCode> = {\n readonly [P in keyof (typeof GSWAP_ERROR_CATALOG)[C]['params']]: ParamValue<\n (typeof GSWAP_ERROR_CATALOG)[C]['params'][P]\n >;\n};\n\n/**\n * The English template of every 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.\n */\nexport const gswapErrorTemplates: { readonly [C in GSwapErrorCode]: string } = Object.fromEntries(\n Object.entries(GSWAP_ERROR_CATALOG).map(([code, entry]) => [code, entry.template]),\n) as { readonly [C in GSwapErrorCode]: string };\n\nconst PLACEHOLDER = /\\{([A-Za-z0-9_]+)\\}/gu;\n\n/** Fills a template's `{placeholders}` from `params`; an unknown placeholder is left as written. */\nexport function renderGSwapErrorTemplate(\n template: string,\n params: Readonly<Record<string, unknown>>,\n): string {\n return template.replace(PLACEHOLDER, (whole, name: string) => {\n const value = params[name];\n return typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean'\n ? String(value)\n : whole;\n });\n}\n\n/** The placeholder names a template uses, in order of first appearance. */\nexport function templatePlaceholders(template: string): string[] {\n return [...new Set([...template.matchAll(PLACEHOLDER)].map((match) => match[1] as string))];\n}\n"],"mappings":"AAwDA,MAAa,EAA8B,CACzC,eACA,eACA,eACA,iBACF,EAea,EAAqC,CAAC,UAAW,WAAW,EAe5D,EAA0B,CAAC,gBA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C7B,EACA,gBAAiB,CACf,MAAO,WACP,SAAU,gEACV,OAAQ,CAAE,OAAQ,SAAU,UAAW,QAAS,CAClD,EACA,gBAAiB,CACf,MAAO,WACP,SAAU,gEACV,OAAQ,CAAE,MAAO,SAAU,QAAS,QAAS,CAC/C,EACA,mBAAoB,CAClB,MAAO,WACP,SAAU,8DACV,OAAQ,CAAE,MAAO,QAAS,CAC5B,EACA,aAAc,CACZ,MAAO,WACP,SAAU,uDACV,OAAQ,CAAE,MAAO,QAAS,CAC5B,EACA,cAAe,CACb,MAAO,WACP,SAAU,8DACV,OAAQ,CAAE,MAAO,SAAU,IAAK,SAAU,IAAK,QAAS,CAC1D,CACF,EA6Ba,EAAkE,OAAO,YACpF,OAAO,QAAQ,CAAmB,CAAC,CAAC,KAAK,CAAC,EAAM,KAAW,CAAC,EAAM,EAAM,QAAQ,CAAC,CACnF,EAEM,EAAc,wBAGpB,SAAgB,EACd,EACA,EACQ,CACR,OAAO,EAAS,QAAQ,GAAc,EAAO,IAAiB,CAC5D,IAAM,EAAQ,EAAO,GACrB,OAAO,OAAO,GAAU,UAAY,OAAO,GAAU,UAAY,OAAO,GAAU,UAC9E,OAAO,CAAK,EACZ,CACN,CAAC,CACH"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e={HTTP_ERROR:`post_send`,UPDATE_REQUIRED:`post_send`,REQUEST_TIMEOUT:`in_flight`,TRANSPORT_ERROR:`in_flight`,REQUEST_FAILED:`in_flight`,INVALID_TIMEOUT:`pre_send`,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`,GALA_WALLET_NOT_AVAILABLE:`pre_send`,WALLET_UNAVAILABLE:`pre_send`,MALFORMED_WALLET_REQUEST:`pre_send`,UNSUPPORTED_WALLET_METHOD:`pre_send`,INVALID_SIGNATURE:`pre_send`,INVALID_CHAIN_ID:`pre_send`,SIGNER_ADDRESS_MISMATCH:`pre_send`,INVALID_PRIVATE_KEY:`pre_send`,SIGNING_FAILED:`pre_send`,KEY_PROVIDER_FAILED:`pre_send`,TOKEN_RESOLUTION_FAILED:`pre_send`,INVALID_SIGNING_HASH_LENGTH:`pre_send`,MISSING_WALLET_ADDRESS:`pre_send`,INVALID_WALLET_ADDRESS:`pre_send`,INVALID_DECIMAL:`pre_send`,PERSONAL_SIGN_NOT_JSON:`pre_send`,PERSONAL_SIGN_NOT_OBJECT:`pre_send`,PERSONAL_SIGN_BAD_PREFIX:`pre_send`,PERSONAL_SIGN_ENVELOPE_FIELDS:`pre_send`,PERSONAL_SIGN_NOT_CANONICAL:`pre_send`,EIP712_NAME_COLLISION:`pre_send`,EIP712_UNSUPPORTED_VALUE:`pre_send`,TYPED_DATA_NOT_STRING:`pre_send`,TYPED_DATA_UNPAIRED_SURROGATE:`pre_send`,TYPED_DATA_NOT_HEX_BYTES:`pre_send`,TYPED_DATA_NOT_SAFE_INTEGER:`pre_send`,TYPED_DATA_NOT_INTEGER:`pre_send`,TYPED_DATA_NOT_BOOLEAN:`pre_send`,TYPED_DATA_BAD_ADDRESS:`pre_send`,TYPED_DATA_BAD_CHECKSUM:`pre_send`,TYPED_DATA_BYTES_LENGTH:`pre_send`,TYPED_DATA_OUT_OF_BOUNDS:`pre_send`,TYPED_DATA_UNSUPPORTED_TYPE:`pre_send`,TYPED_DATA_FIELDS_NOT_LIST:`pre_send`,TYPED_DATA_FIELD_MALFORMED:`pre_send`,TYPED_DATA_INVALID_FIELD_NAME:`pre_send`,TYPED_DATA_DUPLICATE_FIELD:`pre_send`,TYPED_DATA_INVALID_TYPE_NAME:`pre_send`,TYPED_DATA_CIRCULAR_TYPE:`pre_send`,TYPED_DATA_UNKNOWN_FIELD_TYPE:`pre_send`,TYPED_DATA_NO_PRIMARY_TYPE:`pre_send`,TYPED_DATA_AMBIGUOUS_PRIMARY_TYPE:`pre_send`,TYPED_DATA_ARRAY_EXPECTED:`pre_send`,TYPED_DATA_ARRAY_LENGTH_MISMATCH:`pre_send`,TYPED_DATA_STRUCT_NOT_OBJECT:`pre_send`,TYPED_DATA_MISSING_FIELD:`pre_send`,TYPED_DATA_DOMAIN_NOT_OBJECT:`pre_send`,TYPED_DATA_INVALID_DOMAIN_KEY:`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`,INVALID_UNIQUE_KEY:`pre_send`,INVALID_UNIQUE_KEY_PREFIX:`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`};function t(t){return Object.hasOwn(e,t)}function n(n){return n.phase===void 0?t(n.code)?e[n.code]:void 0:n.phase}export{e as GSWAP_ERROR_PHASE_BY_CODE,t as isCatalogCode,n as phaseOfView};
|
|
2
|
+
//# sourceMappingURL=error_phase_table.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"error_phase_table.js","names":[],"sources":["../../../src/classes/error_phase_table.ts"],"sourcesContent":["import type { GSWAP_ERROR_CATALOG, GSwapErrorCode } from './error_catalog.js';\nimport type { GSwapErrorPhase } from './error_phases.js';\nimport type { FailureView } from '../utils/failure_view.js';\n\n/**\n * The phase of every 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 * ~20 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.\n */\nexport const GSWAP_ERROR_PHASE_BY_CODE = {\n HTTP_ERROR: 'post_send',\n UPDATE_REQUIRED: 'post_send',\n REQUEST_TIMEOUT: 'in_flight',\n TRANSPORT_ERROR: 'in_flight',\n REQUEST_FAILED: 'in_flight',\n INVALID_TIMEOUT: 'pre_send',\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 GALA_WALLET_NOT_AVAILABLE: 'pre_send',\n WALLET_UNAVAILABLE: 'pre_send',\n MALFORMED_WALLET_REQUEST: 'pre_send',\n UNSUPPORTED_WALLET_METHOD: 'pre_send',\n INVALID_SIGNATURE: 'pre_send',\n INVALID_CHAIN_ID: 'pre_send',\n SIGNER_ADDRESS_MISMATCH: 'pre_send',\n INVALID_PRIVATE_KEY: 'pre_send',\n SIGNING_FAILED: 'pre_send',\n KEY_PROVIDER_FAILED: 'pre_send',\n TOKEN_RESOLUTION_FAILED: 'pre_send',\n INVALID_SIGNING_HASH_LENGTH: 'pre_send',\n MISSING_WALLET_ADDRESS: 'pre_send',\n INVALID_WALLET_ADDRESS: 'pre_send',\n INVALID_DECIMAL: 'pre_send',\n PERSONAL_SIGN_NOT_JSON: 'pre_send',\n PERSONAL_SIGN_NOT_OBJECT: 'pre_send',\n PERSONAL_SIGN_BAD_PREFIX: 'pre_send',\n PERSONAL_SIGN_ENVELOPE_FIELDS: 'pre_send',\n PERSONAL_SIGN_NOT_CANONICAL: 'pre_send',\n EIP712_NAME_COLLISION: 'pre_send',\n EIP712_UNSUPPORTED_VALUE: 'pre_send',\n TYPED_DATA_NOT_STRING: 'pre_send',\n TYPED_DATA_UNPAIRED_SURROGATE: 'pre_send',\n TYPED_DATA_NOT_HEX_BYTES: 'pre_send',\n TYPED_DATA_NOT_SAFE_INTEGER: 'pre_send',\n TYPED_DATA_NOT_INTEGER: 'pre_send',\n TYPED_DATA_NOT_BOOLEAN: 'pre_send',\n TYPED_DATA_BAD_ADDRESS: 'pre_send',\n TYPED_DATA_BAD_CHECKSUM: 'pre_send',\n TYPED_DATA_BYTES_LENGTH: 'pre_send',\n TYPED_DATA_OUT_OF_BOUNDS: 'pre_send',\n TYPED_DATA_UNSUPPORTED_TYPE: 'pre_send',\n TYPED_DATA_FIELDS_NOT_LIST: 'pre_send',\n TYPED_DATA_FIELD_MALFORMED: 'pre_send',\n TYPED_DATA_INVALID_FIELD_NAME: 'pre_send',\n TYPED_DATA_DUPLICATE_FIELD: 'pre_send',\n TYPED_DATA_INVALID_TYPE_NAME: 'pre_send',\n TYPED_DATA_CIRCULAR_TYPE: 'pre_send',\n TYPED_DATA_UNKNOWN_FIELD_TYPE: 'pre_send',\n TYPED_DATA_NO_PRIMARY_TYPE: 'pre_send',\n TYPED_DATA_AMBIGUOUS_PRIMARY_TYPE: 'pre_send',\n TYPED_DATA_ARRAY_EXPECTED: 'pre_send',\n TYPED_DATA_ARRAY_LENGTH_MISMATCH: 'pre_send',\n TYPED_DATA_STRUCT_NOT_OBJECT: 'pre_send',\n TYPED_DATA_MISSING_FIELD: 'pre_send',\n TYPED_DATA_DOMAIN_NOT_OBJECT: 'pre_send',\n TYPED_DATA_INVALID_DOMAIN_KEY: '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 INVALID_UNIQUE_KEY: 'pre_send',\n INVALID_UNIQUE_KEY_PREFIX: '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} as const satisfies {\n readonly [C in GSwapErrorCode]: (typeof GSWAP_ERROR_CATALOG)[C]['phase'];\n};\n\n/** True for a code the SDK catalog defines. */\nexport function isCatalogCode(code: string): code is GSwapErrorCode {\n return Object.hasOwn(GSWAP_ERROR_PHASE_BY_CODE, code);\n}\n\n/** The phase of a view: the one it states, else the catalog's phase for its code, else `undefined`. */\nexport function phaseOfView(view: FailureView): GSwapErrorPhase | undefined {\n if (view.phase !== undefined) return view.phase;\n return isCatalogCode(view.code) ? GSWAP_ERROR_PHASE_BY_CODE[view.code] : undefined;\n}\n"],"mappings":"AAYA,MAAa,EAA4B,CACvC,WAAY,YACZ,gBAAiB,YACjB,gBAAiB,YACjB,gBAAiB,YACjB,eAAgB,YAChB,gBAAiB,WACjB,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,0BAA2B,WAC3B,mBAAoB,WACpB,yBAA0B,WAC1B,0BAA2B,WAC3B,kBAAmB,WACnB,iBAAkB,WAClB,wBAAyB,WACzB,oBAAqB,WACrB,eAAgB,WAChB,oBAAqB,WACrB,wBAAyB,WACzB,4BAA6B,WAC7B,uBAAwB,WACxB,uBAAwB,WACxB,gBAAiB,WACjB,uBAAwB,WAC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AQ,IAAA,GADpC,EAAK,KAE5C"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"error_phases.js","names":[],"sources":["../../../src/classes/error_phases.ts"],"sourcesContent":["/**\n * How far an operation had got when it failed, measured against the request it exists to send:\n * for a write, the POST that carries the signed DTO to the gateway; for a read, the GET.\n *\n * - `pre_send`: NOTHING was transmitted. Everything up to the request (validation, symbol\n * resolution, the signer, the wallet, a key provider) ran and failed, so no write can have been\n * queued. A write that failed `pre_send` is never \"maybe applied\".\n * - `in_flight`: the request left (or may have left) and no answer was read: a timeout, a broken\n * connection, a stream that dropped. For a write the outcome is unknown.\n * - `post_send`: an answer was read, or the write was already accepted: a refusal, an\n * acknowledgement that proves nothing, an unusable body, and every failure of a confirmation.\n *\n * Each catalog entry declares the phase its code is thrown in; a throw site where the same code\n * can occur in another phase overrides it (`GSwapErrorContext.phase`). It is a typed property of\n * every `GSwapSDKError` (`error.phase`) and `isPreSendError(error)` reads it.\n *\n * This module has no imports, on purpose: it is the closed set of phases, shared by the catalog,\n * the light phase table (`error_phase_table.ts`) and the failure view.\n */\nexport const GSWAP_ERROR_PHASES = ['pre_send', 'in_flight', 'post_send'] as const;\n\n/** One member of {@link GSWAP_ERROR_PHASES}. */\nexport type GSwapErrorPhase = (typeof GSWAP_ERROR_PHASES)[number];\n"],"mappings":"AAmBA,MAAa,EAAqB,CAAC,WAAY,YAAa,WAAW"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{serverMessageOfBody as e}from"../utils/server_message.js";import t from"../_virtual/_@oxc-project_runtime@0.151.0/helpers/esm/defineProperty.js";import{GSwapSDKError as n,getObjectProperty as r,getStringProperty as i,isGSwapError as a}from"./gswap_sdk_error.js";import{buildRequestHeaders as o,fetchRequestor as s,readBlockNumberHeader as c,readHeader as l,readResponseBody as u,readRetryAfter as d,requestWithTimeout as f,validateTimeoutMs as p}from"../utils/transport.js";import{shadowFailures as m}from"../utils/shadow_errors.js";import{SubmittedTransaction as h}from"./submitted_transaction.js";var g=class{constructor(e){t(this,`requestor`,void 0),t(this,`walletAddress`,void 0),t(this,`chainCallTimeoutMs`,void 0),t(this,`isTransportFailure`,void 0),t(this,`answerOfRejectionHook`,void 0),t(this,`requestTimeoutMs`,void 0),t(this,`dexBackendBaseUrl`,void 0),t(this,`wire`,void 0),this.dexBackendBaseUrl=_(e.dexBackendBaseUrl),this.requestor=e.httpRequestor??s,this.walletAddress=e.walletAddress,this.chainCallTimeoutMs=p(e.chainCallTimeoutMs??3e4,`chainCallTimeoutMs`),this.requestTimeoutMs=this.chainCallTimeoutMs,this.wire=e.wire??{},this.isTransportFailure=e.isTransportFailure,this.answerOfRejectionHook=e.answerOfRejection}async submit(t,r,a){if(t===`Trade`)throw new n(`METHOD_NOT_SUPPORTED`,{method:t});let s=this.writeUrl(t),u=a?.walletAddress??this.walletAddress,d=o(this.wire,{json:!0,fixed:u===void 0?{}:{"X-Wallet-Address":u}}),{response:f,body:p}=await this.post(t,s,d,r),m=i(r,`uniqueKey`)??``,g=v(f,p,s,m);if(!f.ok)throw b(f,p,s,m);let _=x(p);if(_?.error===!0)throw new n(`GATEWAY_REPORTED_ERROR`,{serverMessage:e(_)},g);let C=x(_?.data??_?.Data);if(C===void 0)throw new n(`GATEWAY_DATA_MISSING`,{},g);let w=i(C,`transactionId`),T=i(C,`mode`),E=C.transactionId,D=C.blockNumber,O=()=>new n(`GATEWAY_MODE_INVALID`,{},g);if(T!==`sync`&&T!==`queued`||`transactionId`in C&&typeof E!=`string`||D!=null&&!S(D))throw O();if(t===`RequestTrade`&&T===`sync`)throw new n(`GATEWAY_SYNC_REQUEST_TRADE`,{},g);if(t===`RequestTrade`&&T===`queued`)y(f,p,s,C,r);else if(T===`queued`||!(`result`in C))throw O();if(T===`sync`){let e=x(C.result);if(e!==void 0){let t=e.Status;if(t!==void 0&&t!==1)throw n.fromChainError(i(e,`ErrorKey`)??`CHAIN_ERROR`,i(e,`Message`)??``,g)}}let k=l(f,`x-transaction-id`),A=w===void 0||w===``?k:w,j=D==null?c(f):S(D)?D:void 0;return new h({method:t,uniqueKey:m,transactionId:A===void 0||A===``?null:A,blockNumber:j??null,mode:T,result:T===`queued`?void 0:C.result,envelope:p,dexBackendBaseUrl:this.dexBackendBaseUrl,httpRequestor:this.requestor,requestTimeoutMs:this.chainCallTimeoutMs,wire:this.wire,...a?.positionConfirmation===void 0?{}:{positionConfirmation:a.positionConfirmation}})}async submitShadow(e,t,n){return m(()=>this.sendShadow(e,t,n))}async sendShadow(e,t,r){if(e===`Trade`)throw new n(`METHOD_NOT_SUPPORTED`,{method:e});let i=r?.walletAddress??this.walletAddress;if(i===void 0)throw new n(`SHADOW_SUBMIT_NEEDS_WALLET_ADDRESS`,{});let a=o(this.wire,{json:!0,fixed:{"X-Wallet-Address":i,"X-Shadow":`true`}}),{response:s,body:c}=await this.post(e,this.writeUrl(e),a,t);return{httpStatus:s.status,body:c}}writeUrl(e){return`${this.dexBackendBaseUrl}/v1/chain/asset/dex-contract/${e}`}async post(e,t,r,o){let s;try{s=JSON.stringify(o)}catch(t){throw new n(`SIGNING_FAILED`,{method:e,reason:`failed`},{cause:t})}let c=(e,r)=>new n(`SUBMISSION_OUTCOME_UNKNOWN`,{reason:e},{uniqueKey:i(o,`uniqueKey`)??``,url:t,cause:r}),l;try{l=await f(this.requestor,t,{method:`POST`,headers:r,body:s},this.chainCallTimeoutMs)}catch(e){if(a(e,`REQUEST_TIMEOUT`))throw c(`timeout`,e);if(a(e,`TRANSPORT_ERROR`)||this.isTransportRejection(e))throw c(`transport`,e);let t=this.answerOfRejection(e);if(t!==void 0)return t;throw e}try{return{response:l,body:await u(l)}}catch(e){throw c(`transport`,e)}}answerOfRejection(e){let t;try{t=this.answerOfRejectionHook?.(e)}catch{return}if(t===void 0)return;let{status:n,body:r,headers:i}=t;if(!Number.isInteger(n)||n<100||n>599)return;let a=typeof r==`string`?r:``;return{response:{ok:n>=200&&n<300,status:n,json:async()=>r,text:async()=>a,headers:i??{}},body:r}}isTransportRejection(e){try{return this.isTransportFailure?.(e)===!0}catch{return!1}}get httpRequestor(){return this.requestor}};function _(e){return e.replace(/\/$/u,``)}function v(e,t,n,r){return{status:e.status,body:t,url:n,...r===void 0||r===``?{}:{uniqueKey:r}}}function y(e,t,r,a,o){let s=i(o,`uniqueKey`)??``,c=a.uniqueKey;if(typeof c==`string`&&c!==``&&c===s)return;let l=c==null||c===``,u={...v(e,t,r),uniqueKey:s};throw l?new n(`MISSING_UNIQUE_KEY`,{},u):new n(`UNIQUE_KEY_MISMATCH`,{},u)}function b(t,a,o,s){if(t.status===426)return new n(`UPDATE_REQUIRED`,{status:t.status},v(t,a,o,s));let c=x(a),l=r(a,`error`),u=i(c,`code`)??i(l,`code`)??i(l,`ErrorKey`)??`HTTP_ERROR`,f=e(a),p=t.status===429?d(t):void 0;return u===`HTTP_ERROR`?new n(`HTTP_ERROR`,{status:t.status,url:o,serverMessage:f},v(t,a,o,s)):n.fromGatewayBounce(u,f,t.status,a,o,p,s===``?void 0:s)}function x(e){return typeof e==`object`&&e?e:void 0}function S(e){return typeof e==`number`&&Number.isInteger(e)&&e>=0}export{g as ChainGateway};
|
|
2
|
+
//# sourceMappingURL=gateway.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"gateway.js","names":[],"sources":["../../../src/classes/gateway.ts"],"sourcesContent":["import type { HttpRequestor, HTTPResponse } from '../types/http_requestor.js';\nimport type { WireOptions } from '../types/wire.js';\nimport {\n getObjectProperty,\n getStringProperty,\n GSwapSDKError,\n isGSwapError,\n UPDATE_REQUIRED_STATUS,\n type GSwapErrorContext,\n} from './gswap_sdk_error.js';\nimport { serverMessageOfBody } from '../utils/server_message.js';\nimport { shadowFailures } from '../utils/shadow_errors.js';\nimport type { SubmissionOutcomeUnknownReason } from './error_catalog.js';\nimport type { ShadowSubmitResult } from './shadow_submit.js';\nimport { SubmittedTransaction, type PositionConfirmationResult } from './submitted_transaction.js';\nimport {\n buildRequestHeaders,\n fetchRequestor,\n readBlockNumberHeader,\n readHeader,\n readResponseBody,\n readRetryAfter,\n requestWithTimeout,\n validateTimeoutMs,\n} from '../utils/transport.js';\nimport type { AppliedTrade, Position } from '../types/v2_results.js';\n\n/** Options for a chain-gateway client. */\nexport interface ChainGatewayOptions {\n dexBackendBaseUrl: string;\n httpRequestor?: HttpRequestor | undefined;\n walletAddress?: string | undefined;\n /**\n * Timeout of every gateway request in milliseconds (default 30 000); also the per-read timeout\n * of the services built on this gateway and of `confirm()`. `Infinity` arms no timer, for an\n * app whose HTTP stack owns request lifetimes.\n */\n chainCallTimeoutMs?: number | undefined;\n /**\n * Wire format of every request of this gateway and of the services built on it: the headers\n * (`userAgent`, `headers`) of reads AND of the POSTs that submit writes, and the query encoding\n * of reads. `X-Wallet-Address` and `X-Shadow` always win over a same-named `wire.headers` entry.\n */\n wire?: WireOptions | undefined;\n /**\n * Tells the gateway which rejections of YOUR `httpRequestor` mean \"no HTTP answer arrived\" (the\n * connection failed, was reset or dropped), as opposed to an answer your requestor turned into\n * an error (an interceptor that rejects on a 4xx, a version wall). Used only when submitting a\n * write: a rejection it accepts becomes `SUBMISSION_OUTCOME_UNKNOWN` with `reason: 'transport'`\n * (the request may have been queued; the original error is `cause`), and any other rejection\n * reaches the caller unchanged. The SDK's own `TRANSPORT_ERROR` (the default `fetch` requestor,\n * `httpRequestorFromAxios`) always counts, so this is only for requestors that reject with\n * their own errors. Never throw from it; a throw is treated as \"not a transport failure\".\n *\n * @example\n * ```ts\n * new ChainGateway({\n * dexBackendBaseUrl,\n * httpRequestor: galaFetch, // a fetch wrapper: its TypeError is the network failing\n * isTransportFailure: (error) => error instanceof TypeError,\n * });\n * ```\n */\n isTransportFailure?: ((error: unknown) => boolean) | undefined;\n /**\n * Tells the gateway which rejections of YOUR `httpRequestor` are an HTTP ANSWER, and what the\n * answer was: a requestor built on an HTTP client that rejects every non-2xx (an interceptor\n * that throws on a 4xx, a version wall that throws on a 426) loses the answer the SDK reads\n * errors from. Return `{ status, body }` (the parsed JSON, or the raw text; `headers` for\n * `Retry-After`) for such a rejection and the write is handled exactly as if the requestor had\n * resolved that answer: the gateway's own code becomes its catalogued error\n * (`DTO_INVALID`, `RATE_LIMITED`, `CHAIN_DISPATCH_FAILED`, ...), an uncoded body `HTTP_ERROR`,\n * both carrying the signed `uniqueKey` and classified by `classifyFailure` as a write. Return\n * `undefined` for any other rejection: it reaches the caller unchanged. Used only when\n * submitting a write; `isTransportFailure` is asked first (no answer proves nothing, so\n * \"maybe queued\" wins), and a throw from this hook, or a `status` outside 100-599, means \"not an\n * answer\". Never throw from it.\n *\n * @example\n * ```ts\n * new ChainGateway({\n * dexBackendBaseUrl,\n * httpRequestor: httpRequestorFromAxios(instance, { rejectOnHttpError: true }),\n * answerOfRejection: (error) =>\n * error instanceof GatewayError && error.status !== undefined\n * ? { status: error.status, body: error.data }\n * : undefined,\n * });\n * ```\n */\n answerOfRejection?: ((error: unknown) => RejectedAnswer | undefined) | undefined;\n}\n\n/** The HTTP answer a rejection of the app's requestor stands for (see `ChainGatewayOptions.answerOfRejection`). */\nexport interface RejectedAnswer {\n /** The HTTP status of the answer (100-599). */\n status: number;\n /** The answer's body: parsed JSON when it was JSON, else the raw text. */\n body: unknown;\n /** The answer's headers, for `Retry-After`. */\n headers?: Record<string, string | undefined> | undefined;\n}\n\n/** Optional attribution and operation-specific confirmation hooks for a write. */\nexport interface ChainSubmitOptions {\n walletAddress?: string | undefined;\n positionConfirmation?: ((signal: AbortSignal) => Promise<PositionConfirmationResult>) | undefined;\n}\n\n/** Thin client for backend-routed v2 writes: synchronous liquidity writes and queued RequestTrade. */\nexport class ChainGateway {\n private readonly requestor: HttpRequestor;\n private readonly walletAddress: string | undefined;\n private readonly chainCallTimeoutMs: number;\n private readonly isTransportFailure: ((error: unknown) => boolean) | undefined;\n private readonly answerOfRejectionHook:\n ((error: unknown) => RejectedAnswer | undefined) | undefined;\n /** The request timeout in milliseconds (`Infinity` when no timer is armed). */\n public readonly requestTimeoutMs: number;\n /** The swap backend base URL every request is sent to, without a trailing slash. */\n public readonly dexBackendBaseUrl: string;\n /** Wire format shared by the read services built on this gateway. */\n public readonly wire: WireOptions;\n\n /** Create a chain gateway client. */\n constructor(options: ChainGatewayOptions) {\n this.dexBackendBaseUrl = trimTrailingSlash(options.dexBackendBaseUrl);\n this.requestor = options.httpRequestor ?? fetchRequestor;\n this.walletAddress = options.walletAddress;\n this.chainCallTimeoutMs = validateTimeoutMs(\n options.chainCallTimeoutMs ?? 30_000,\n 'chainCallTimeoutMs',\n );\n this.requestTimeoutMs = this.chainCallTimeoutMs;\n this.wire = options.wire ?? {};\n this.isTransportFailure = options.isTransportFailure;\n this.answerOfRejectionHook = options.answerOfRejection;\n }\n\n /**\n * Submit a signed v2 DTO through the chain gateway.\n *\n * @throws GSwapSDKError `SUBMISSION_OUTCOME_UNKNOWN` when no answer was read: `params.reason` is\n * `'timeout'` (the POST exceeded `chainCallTimeoutMs`) or `'transport'` (the connection failed\n * or broke off). Either way the write MAY have been queued: keep `error.uniqueKey` and confirm\n * it. Whether to offer the user a Retry (a NEW request under a fresh key) is the app's policy;\n * the SDK states only that the outcome is unknown. Reads keep `TRANSPORT_ERROR`.\n */\n public async submit(\n method: 'RequestTrade',\n signedBody: Record<string, unknown>,\n options?: ChainSubmitOptions,\n ): Promise<SubmittedTransaction<AppliedTrade>>;\n public async submit(\n method: string,\n signedBody: Record<string, unknown>,\n options?: ChainSubmitOptions,\n ): Promise<SubmittedTransaction<Position | null>>;\n public async submit(\n method: string,\n signedBody: Record<string, unknown>,\n options?: ChainSubmitOptions,\n ): Promise<SubmittedTransaction> {\n // The synchronous swap was removed from the contract and from this SDK. This is the only\n // place the retired name may appear in the write path; the class guard in\n // tests/foundation.test.ts pins that nothing signs or submits it.\n if (method === 'Trade') {\n throw new GSwapSDKError('METHOD_NOT_SUPPORTED', { method });\n }\n const url = this.writeUrl(method);\n const walletAddress = options?.walletAddress ?? this.walletAddress;\n const headers = buildRequestHeaders(this.wire, {\n json: true,\n fixed: walletAddress === undefined ? {} : { 'X-Wallet-Address': walletAddress },\n });\n const { response, body } = await this.post(method, url, headers, signedBody);\n // Every failure after an answer names the write it is about, so an app can confirm it and a\n // failure classifier can tell a write's HTTP failure from a read's.\n const uniqueKey = getStringProperty(signedBody, 'uniqueKey') ?? '';\n const context = responseContext(response, body, url, uniqueKey);\n\n if (!response.ok) {\n throw gatewayError(response, body, url, uniqueKey);\n }\n\n const envelope = asRecord(body);\n // `error: true` is the gateway refusing the write, even inside a 2xx. It is never a transaction.\n if (envelope?.['error'] === true) {\n throw new GSwapSDKError(\n 'GATEWAY_REPORTED_ERROR',\n { serverMessage: serverMessageOfBody(envelope) },\n context,\n );\n }\n const data = asRecord(envelope?.['data'] ?? envelope?.['Data']);\n if (data === undefined) {\n throw new GSwapSDKError('GATEWAY_DATA_MISSING', {}, context);\n }\n\n const transactionId = getStringProperty(data, 'transactionId');\n const mode = getStringProperty(data, 'mode');\n const rawTransactionId = data['transactionId'];\n const bodyBlockNumber = data['blockNumber'];\n const invalidMode = (): GSwapSDKError<'GATEWAY_MODE_INVALID'> =>\n new GSwapSDKError('GATEWAY_MODE_INVALID', {}, context);\n if (mode !== 'sync' && mode !== 'queued') {\n throw invalidMode();\n }\n if (\n ('transactionId' in data && typeof rawTransactionId !== 'string') ||\n (bodyBlockNumber !== undefined && bodyBlockNumber !== null && !isBlockNumber(bodyBlockNumber))\n ) {\n throw invalidMode();\n }\n if (method === 'RequestTrade' && mode === 'sync') {\n throw new GSwapSDKError('GATEWAY_SYNC_REQUEST_TRADE', {}, context);\n }\n if (method === 'RequestTrade' && mode === 'queued') {\n assertQueuedUnderSignedKey(response, body, url, data, signedBody);\n } else if (mode === 'queued' || !('result' in data)) {\n throw invalidMode();\n }\n\n // Only synchronous writes carry an executed chain result in the gateway response.\n if (mode === 'sync') {\n const embeddedResult = asRecord(data['result']);\n if (embeddedResult !== undefined) {\n const resultStatus = embeddedResult['Status'];\n if (resultStatus !== undefined && resultStatus !== 1) {\n throw GSwapSDKError.fromChainError(\n getStringProperty(embeddedResult, 'ErrorKey') ?? 'CHAIN_ERROR',\n getStringProperty(embeddedResult, 'Message') ?? '',\n context,\n );\n }\n }\n }\n\n const headerTransactionId = readHeader(response, 'x-transaction-id');\n const resolvedTransactionId =\n transactionId === undefined || transactionId === '' ? headerTransactionId : transactionId;\n const blockNumber: number | undefined =\n bodyBlockNumber === null || bodyBlockNumber === undefined\n ? readBlockNumberHeader(response)\n : isBlockNumber(bodyBlockNumber)\n ? bodyBlockNumber\n : undefined;\n return new SubmittedTransaction({\n method,\n uniqueKey,\n transactionId:\n resolvedTransactionId === undefined || resolvedTransactionId === ''\n ? null\n : resolvedTransactionId,\n blockNumber: blockNumber ?? null,\n mode,\n result: mode === 'queued' ? undefined : data['result'],\n envelope: body,\n dexBackendBaseUrl: this.dexBackendBaseUrl,\n httpRequestor: this.requestor,\n requestTimeoutMs: this.chainCallTimeoutMs,\n wire: this.wire,\n ...(options?.positionConfirmation === undefined\n ? {}\n : { positionConfirmation: options.positionConfirmation }),\n });\n }\n\n /**\n * Submit a signed v2 DTO as a SHADOW (dark) write: the same route and body as {@link submit},\n * plus `X-Wallet-Address` and `X-Shadow: true`, so defi-backend marks the transaction private\n * before it reaches the contract. The wallet address is required (the backend resolves the\n * owner from it).\n *\n * Unlike `submit`, EVERY HTTP status resolves: the result is the raw `{ httpStatus, body }`,\n * because shadow failures are classified from the status together with the body's `code`\n * (`SHADOW_UNAVAILABLE`, `SHADOW_UNSUPPORTED_TYPE`, `SHADOW_RELAY_REJECTED`);\n * see `readShadowSubmitOutcome`. Only a failure to get an answer rejects, and it rejects with\n * `SUBMISSION_OUTCOME_UNKNOWN` (`params.reason` `'timeout'` or `'transport'`): the request may\n * have been accepted. Every error it throws has `error.shadow === true`, and a non-SDK object\n * that escapes (your requestor's own rejection) answers `isShadowError(error)`.\n *\n * @example\n * ```ts\n * const result = await gateway.submitShadow('RequestTrade', signedDto, { walletAddress });\n * const outcome = readShadowSubmitOutcome('RequestTrade', signedDto, result);\n * ```\n */\n public async submitShadow(\n method: string,\n signedBody: Record<string, unknown>,\n options?: ChainSubmitOptions,\n ): Promise<ShadowSubmitResult> {\n return shadowFailures(() => this.sendShadow(method, signedBody, options));\n }\n\n private async sendShadow(\n method: string,\n signedBody: Record<string, unknown>,\n options?: ChainSubmitOptions,\n ): Promise<ShadowSubmitResult> {\n if (method === 'Trade') {\n throw new GSwapSDKError('METHOD_NOT_SUPPORTED', { method });\n }\n const walletAddress = options?.walletAddress ?? this.walletAddress;\n if (walletAddress === undefined) {\n throw new GSwapSDKError('SHADOW_SUBMIT_NEEDS_WALLET_ADDRESS', {});\n }\n // Header order is frontend_v2's: X-Wallet-Address, then X-Shadow.\n const headers = buildRequestHeaders(this.wire, {\n json: true,\n fixed: { 'X-Wallet-Address': walletAddress, 'X-Shadow': 'true' },\n });\n const { response, body } = await this.post(method, this.writeUrl(method), headers, signedBody);\n return { httpStatus: response.status, body };\n }\n\n private writeUrl(method: string): string {\n return `${this.dexBackendBaseUrl}/v1/chain/asset/dex-contract/${method}`;\n }\n\n /**\n * POSTs a signed body and reads the answer. Neither a timeout nor a transport failure proves the\n * write was not submitted, so both are `SUBMISSION_OUTCOME_UNKNOWN` (`params.reason` says which),\n * never a retryable read failure. A rejection that is an answer (see `isTransportFailure`) is\n * rethrown unchanged.\n */\n private async post(\n method: string,\n url: string,\n headers: Record<string, string>,\n signedBody: Record<string, unknown>,\n ): Promise<{ response: HTTPResponse; body: unknown }> {\n // Serialized BEFORE the request is attempted and outside the try below: a body that cannot be\n // serialized (a cycle, a BigInt) was never sent, so it must not be mistaken for a transport\n // failure the app's `isTransportFailure` might claim, which would call it \"maybe queued\".\n let payload: string;\n try {\n payload = JSON.stringify(signedBody);\n } catch (cause: unknown) {\n throw new GSwapSDKError('SIGNING_FAILED', { method, reason: 'failed' }, { cause });\n }\n const outcomeUnknown = (\n reason: SubmissionOutcomeUnknownReason,\n cause: unknown,\n ): GSwapSDKError<'SUBMISSION_OUTCOME_UNKNOWN'> =>\n new GSwapSDKError(\n 'SUBMISSION_OUTCOME_UNKNOWN',\n { reason },\n { uniqueKey: getStringProperty(signedBody, 'uniqueKey') ?? '', url, cause },\n );\n let response: HTTPResponse;\n try {\n response = await requestWithTimeout(\n this.requestor,\n url,\n {\n method: 'POST',\n headers,\n body: payload,\n },\n this.chainCallTimeoutMs,\n );\n } catch (error: unknown) {\n if (isGSwapError(error, 'REQUEST_TIMEOUT')) throw outcomeUnknown('timeout', error);\n if (isGSwapError(error, 'TRANSPORT_ERROR') || this.isTransportRejection(error)) {\n throw outcomeUnknown('transport', error);\n }\n // A rejection that IS an HTTP answer (the app's interceptor rejecting on a non-2xx, a\n // version wall) is handled exactly as the answer would have been, so the app does not\n // rebuild the SDK's error from it. Anything else the app's requestor threw reaches the\n // caller unchanged.\n const answered = this.answerOfRejection(error);\n if (answered !== undefined) return answered;\n throw error;\n }\n try {\n return { response, body: await readResponseBody(response) };\n } catch (error: unknown) {\n // The answer's headers arrived but its body broke off: the status alone does not say what\n // the gateway did with the write.\n throw outcomeUnknown('transport', error);\n }\n }\n\n /**\n * The HTTP answer a rejection of the app's requestor stands for, as the response the gateway\n * would have read. `undefined` when the app named none, when its hook throws, or when what it\n * returned is not an HTTP status; then the rejection is not an answer.\n */\n private answerOfRejection(error: unknown): { response: HTTPResponse; body: unknown } | undefined {\n let answer: RejectedAnswer | undefined;\n try {\n answer = this.answerOfRejectionHook?.(error);\n } catch {\n return undefined;\n }\n if (answer === undefined) return undefined;\n const { status, body, headers } = answer;\n if (!Number.isInteger(status) || status < 100 || status > 599) return undefined;\n const text = typeof body === 'string' ? body : '';\n const response: HTTPResponse = {\n ok: status >= 200 && status < 300,\n status,\n json: async () => body,\n text: async () => text,\n headers: headers ?? {},\n };\n return { response, body };\n }\n\n private isTransportRejection(error: unknown): boolean {\n try {\n return this.isTransportFailure?.(error) === true;\n } catch {\n return false;\n }\n }\n\n /** Expose the requestor for sibling read services that share this gateway transport. */\n public get httpRequestor(): HttpRequestor {\n return this.requestor;\n }\n}\n\nfunction trimTrailingSlash(value: string): string {\n return value.replace(/\\/$/u, '');\n}\n\nfunction responseContext(\n response: HTTPResponse,\n body: unknown,\n url: string,\n uniqueKey?: string,\n): GSwapErrorContext {\n return {\n status: response.status,\n body,\n url,\n ...(uniqueKey === undefined || uniqueKey === '' ? {} : { uniqueKey }),\n };\n}\n\n/**\n * A queued RequestTrade acknowledgement is a swap only if it names the exact key that was signed:\n * the key is the only handle `confirm()` and every recovery path have on the trade, so an\n * acknowledgement without it (or with another) proves nothing about THIS request. Fails closed:\n * an absent echo is as unacceptable as a wrong one. The code is `MISSING_UNIQUE_KEY` or\n * `UNIQUE_KEY_MISMATCH`, `error.uniqueKey` the signed key.\n *\n * Only RequestTrade is checked: a synchronous write is proven by its own executed chain result,\n * and the apps never required an echo for it.\n */\nfunction assertQueuedUnderSignedKey(\n response: HTTPResponse,\n body: unknown,\n url: string,\n data: Record<string, unknown>,\n signedBody: Record<string, unknown>,\n): void {\n const signedUniqueKey = getStringProperty(signedBody, 'uniqueKey') ?? '';\n const echoed = data['uniqueKey'];\n if (typeof echoed === 'string' && echoed !== '' && echoed === signedUniqueKey) return;\n const missing = echoed === undefined || echoed === null || echoed === '';\n const context: GSwapErrorContext = {\n ...responseContext(response, body, url),\n uniqueKey: signedUniqueKey,\n };\n throw missing\n ? new GSwapSDKError('MISSING_UNIQUE_KEY', {}, context)\n : new GSwapSDKError('UNIQUE_KEY_MISMATCH', {}, context);\n}\n\nfunction gatewayError(\n response: HTTPResponse,\n body: unknown,\n url: string,\n uniqueKey: string,\n): GSwapSDKError {\n // The version wall is decided by the status alone, whatever the body names: nothing was queued.\n if (response.status === UPDATE_REQUIRED_STATUS) {\n return new GSwapSDKError(\n 'UPDATE_REQUIRED',\n { status: response.status },\n responseContext(response, body, url, uniqueKey),\n );\n }\n const object = asRecord(body);\n const nested = getObjectProperty(body, 'error');\n const code =\n getStringProperty(object, 'code') ??\n getStringProperty(nested, 'code') ??\n getStringProperty(nested, 'ErrorKey') ??\n 'HTTP_ERROR';\n // Missing server text is an empty param, never SDK-written English standing in for it. A body\n // that is not JSON (an HTML 502 page, a WAF block) is kept as error.bodyText.\n const message = serverMessageOfBody(body);\n const retryAfterMs = response.status === 429 ? readRetryAfter(response) : undefined;\n if (code === 'HTTP_ERROR') {\n return new GSwapSDKError(\n 'HTTP_ERROR',\n { status: response.status, url, serverMessage: message },\n responseContext(response, body, url, uniqueKey),\n );\n }\n return GSwapSDKError.fromGatewayBounce(\n code,\n message,\n response.status,\n body,\n url,\n retryAfterMs,\n uniqueKey === '' ? undefined : uniqueKey,\n );\n}\n\nfunction asRecord(value: unknown): Record<string, unknown> | undefined {\n return typeof value === 'object' && value !== null\n ? (value as Record<string, unknown>)\n : undefined;\n}\n\nfunction isBlockNumber(value: unknown): value is number {\n return typeof value === 'number' && Number.isInteger(value) && value >= 0;\n}\n"],"mappings":"8lBA8GA,IAAa,EAAb,KAA0B,CAexB,YAAY,EAA8B,CAdzB,EAAA,KAAA,YAAA,IAAA,EAAA,EACA,EAAA,KAAA,gBAAA,IAAA,EAAA,EACA,EAAA,KAAA,qBAAA,IAAA,EAAA,EACA,EAAA,KAAA,qBAAA,IAAA,EAAA,EACA,EAAA,KAAA,wBAAA,IAAA,EAAA,EAGD,EAAA,KAAA,mBAAA,IAAA,EAAA,EAEA,EAAA,KAAA,oBAAA,IAAA,EAAA,EAEA,EAAA,KAAA,OAAA,IAAA,EAAA,EAId,KAAK,kBAAoB,EAAkB,EAAQ,iBAAiB,EACpE,KAAK,UAAY,EAAQ,eAAiB,EAC1C,KAAK,cAAgB,EAAQ,cAC7B,KAAK,mBAAqB,EACxB,EAAQ,oBAAsB,IAC9B,oBACF,EACA,KAAK,iBAAmB,KAAK,mBAC7B,KAAK,KAAO,EAAQ,MAAQ,CAAC,EAC7B,KAAK,mBAAqB,EAAQ,mBAClC,KAAK,sBAAwB,EAAQ,iBACvC,CA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,MAAM,GAChC,EAAkB,EAAQ,UAAU,GACpC,aAGI,EAAU,EAAoB,CAAI,EAClC,EAAe,EAAS,SAAW,IAAM,EAAe,CAAQ,EAAI,IAAA,GAQ1E,OAPI,IAAS,aACJ,IAAI,EACT,aACA,CAAE,OAAQ,EAAS,OAAQ,MAAK,cAAe,CAAQ,EACvD,EAAgB,EAAU,EAAM,EAAK,CAAS,CAChD,EAEK,EAAc,kBACnB,EACA,EACA,EAAS,OACT,EACA,EACA,EACA,IAAc,GAAK,IAAA,GAAY,CACjC,CACF,CAEA,SAAS,EAAS,EAAqD,CACrE,OAAO,OAAO,GAAU,UAAY,EAC/B,EACD,IAAA,EACN,CAEA,SAAS,EAAc,EAAiC,CACtD,OAAO,OAAO,GAAU,UAAY,OAAO,UAAU,CAAK,GAAK,GAAS,CAC1E"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import e from"../_virtual/_@oxc-project_runtime@0.151.0/helpers/esm/defineProperty.js";import{GSwapSDKError as t}from"./gswap_sdk_error.js";import{GSWAP_ENVIRONMENTS as n}from"../types/env.js";import{debugLog as r}from"../utils/debug.js";import{ReconnectionBackoff as i}from"../utils/reconnection.js";const a=`gdex.jsonrpc.v1`,o=[`add`,`remove`,`collect`];function s(e){let{pool:t}=e;return(e.version===`v1`||e.version===`v2`)&&typeof t==`object`&&!!t&&typeof e.poolHash==`string`&&typeof e.transactionId==`string`&&o.includes(e.action)&&typeof e.owner==`string`&&typeof e.amount0==`string`&&typeof e.amount1==`string`&&typeof e.blockNumber==`number`&&typeof e.timestamp==`string`}var c=class extends Error{constructor(t,n,r){super(n),e(this,`code`,void 0),e(this,`data`,void 0),this.name=`GdexStreamError`,this.code=t,r!==void 0&&(this.data=r)}};function l(e){let t=typeof e==`object`&&e?e.subscriptionId:void 0;if(typeof t!=`string`)throw new c(-32603,`GDEX subscribe response is missing its subscriptionId`);return t}var u=class{constructor(r={}){e(this,`url`,void 0),e(this,`requestTimeoutMs`,void 0),e(this,`apiKey`,void 0),e(this,`webSocketConstructor`,void 0),e(this,`backoff`,void 0),e(this,`socket`,void 0),e(this,`connectPromise`,void 0),e(this,`nextRequestId`,0),e(this,`pending`,/* @__PURE__ */ new Map),e(this,`subscriptionsByServerId`,/* @__PURE__ */ new Map),e(this,`activeSubscriptions`,/* @__PURE__ */ new Set),e(this,`intentionalClose`,!1),e(this,`reconnecting`,!1),e(this,`reconnectTimer`,void 0),e(this,`reconnectDelayResolve`,void 0),this.url=r.url??n.prod.dexBackendWsUrl,this.requestTimeoutMs=r.requestTimeoutMs??15e3,this.backoff=new i({maxAttempts:r.reconnectAttempts??5,baseDelayMs:r.reconnectDelayMs??2e3});let a=r.webSocketImpl??globalThis.WebSocket;if(typeof a!=`function`)throw new t(`STREAM_WEBSOCKET_UNAVAILABLE`,{});if(this.webSocketConstructor=a,r.apiKey!==void 0){if(r.apiKey===``||r.webSocketImpl===void 0)throw new t(`STREAM_API_KEY_UNUSABLE`,{});this.apiKey=r.apiKey}}connect(){return this.isConnected()?Promise.resolve():this.connectPromise?this.connectPromise:(this.intentionalClose=!1,this.clearReconnectTimer(),this.connectPromise=this.openSocket(),this.connectPromise)}disconnect(){this.intentionalClose=!0,this.reconnecting=!1,this.clearReconnectTimer(),this.rejectPending(new t(`STREAM_DISCONNECTED`,{}));let e=this.socket;this.socket=void 0,this.connectPromise=void 0,e?.close(1e3,`client disconnect`)}isConnected(){return this.socket?.readyState===1}request(e,t){return this.send(e,t)}send(e,n,r){if(!this.isConnected()||!this.socket)return Promise.reject(new t(`STREAM_NOT_CONNECTED`,{}));let i=++this.nextRequestId,a={jsonrpc:`2.0`,id:i,method:e};return n!==void 0&&(a.params=n),new Promise((n,o)=>{let s=setTimeout(()=>{this.pending.delete(i),o(new t(`STREAM_REQUEST_TIMEOUT`,{method:e,timeoutMs:this.requestTimeoutMs}))},this.requestTimeoutMs);this.pending.set(i,{resolve:e=>n(e),reject:o,timeout:s,onResult:r});try{this.socket?.send(JSON.stringify(a))}catch(e){clearTimeout(s),this.pending.delete(i),o(e instanceof Error?e:Error(String(e)))}})}serverInfo(){return this.request(`gdex_serverInfo`)}ping(){return this.request(`gdex_ping`)}getPool(e){return this.request(`gdex_getPool`,e)}getBalance(e,t){return this.request(`gdex_getBalance`,t===void 0?{owner:e}:{owner:e,tokenClassKey:t})}getPositions(e){return this.request(`gdex_getPositions`,e)}getBlockHeight(){return this.request(`gdex_getBlockHeight`)}quote(e){return this.request(`gdex_quote`,e)}getToken(e){return this.request(`gdex_getToken`,{tokenClassKey:e})}subscribeSwaps(e,t={}){return this.subscribe(`swap`,e,t)}subscribePool(e,t,n={}){return this.subscribe(`pool`,t,{...e,...n})}subscribeBalances(e,t,n={}){return this.subscribe(`balance`,t,{owner:e,...n})}subscribePoolCreated(e,t={}){return this.subscribe(`poolCreated`,e,t)}subscribeLiquidity(e,t={}){return this.subscribe(`liquidity`,t=>{s(t)?e(t):r(`Ignoring a malformed liquidity event from the GDEX stream`)},t)}subscribeBlocks(e,t={}){return this.subscribe(`blocks`,e,t)}openSocket(){return new Promise((e,n)=>{let i=!1,o=this.apiKey===void 0?new this.webSocketConstructor(this.url,a):new this.webSocketConstructor(this.url,a,{headers:{"x-api-key":this.apiKey}});this.socket=o,o.onopen=()=>{this.socket===o&&(i=!0,this.connectPromise=void 0,this.reconnecting||this.backoff.reset(),r(`Connected to GDEX stream`),e())},o.onmessage=e=>this.handleMessage(e.data),o.onerror=()=>{i||n(new t(`STREAM_CONNECT_FAILED`,{url:this.url}))},o.onclose=e=>{this.socket===o&&(this.socket=void 0,this.connectPromise=void 0,i||n(new t(`STREAM_CLOSED_BEFORE_CONNECT`,{closeCode:e.code??0})),this.rejectPending(new t(`STREAM_CONNECTION_CLOSED`,{closeCode:e.code??0})),!this.intentionalClose&&!this.reconnecting&&this.startReconnectLoop())}})}handleMessage(e){if(typeof e!=`string`){r(`Ignoring non-text GDEX WebSocket frame`);return}let t;try{t=JSON.parse(e)}catch{r(`Ignoring invalid JSON from GDEX stream`);return}if(typeof t.id==`number`){let e=this.pending.get(t.id);if(!e)return;if(clearTimeout(e.timeout),this.pending.delete(t.id),t.error){let n=typeof t.error.code==`number`?t.error.code:-32603,r=typeof t.error.message==`string`?t.error.message:`GDEX request failed`;e.reject(new c(n,r,t.error.data))}else{try{e.onResult?.(t.result)}catch(t){e.reject(t instanceof Error?t:Error(String(t)));return}e.resolve(t.result)}return}if(t.method!==`gdex_subscription`||!this.isRecord(t.params))return;let n=t.params.subscription,i=t.params.result;if(typeof n!=`string`||!this.isRecord(i))return;let a=this.subscriptionsByServerId.get(n);if(a?.active)try{a.callback(i)}catch(e){r(`GDEX subscription callback failed`,e)}}async subscribe(e,t,n){let r={channel:e,...n},i={subscriptionId:``,unsubscribe:async()=>this.unsubscribe(a)},a={serverId:``,params:r,callback:t,handle:i,active:!0};return await this.send(`gdex_subscribe`,r,e=>{let t=l(e);a.serverId=t,i.subscriptionId=t,this.activeSubscriptions.add(a),this.subscriptionsByServerId.set(t,a)}),i}async unsubscribe(e){e.active&&(e.active=!1,this.activeSubscriptions.delete(e),this.subscriptionsByServerId.delete(e.serverId),this.isConnected()&&await this.request(`gdex_unsubscribe`,{subscriptionId:e.serverId}))}startReconnectLoop(){this.reconnecting||this.intentionalClose||(this.reconnecting=!0,this.reconnectLoop())}async reconnectLoop(){for(;!this.intentionalClose&&this.backoff.shouldRetry();){let e=this.backoff.nextDelayMs();if(this.backoff.recordAttempt(),r(`GDEX reconnect attempt ${this.backoff.attemptCount}/${this.backoff.maxAttempts} in ${e}ms`),await this.waitForReconnectDelay(e),this.intentionalClose)break;try{await this.openSocket(),await this.resubscribeAll(),this.backoff.reset(),this.reconnecting=!1;return}catch(e){r(`GDEX reconnect failed: ${e instanceof Error?e.message:String(e)}`)}}this.reconnecting=!1,this.intentionalClose||r(`GDEX reconnection attempts exhausted`)}async resubscribeAll(){this.subscriptionsByServerId.clear();for(let e of this.activeSubscriptions){if(!e.active)continue;let t={...e.params,snapshot:!0},n=await this.resubscribeWithRateLimitRetry(t,t=>{let n=l(t);e.active&&(e.serverId=n,e.handle.subscriptionId=n,this.subscriptionsByServerId.set(n,e))});e.active||await this.request(`gdex_unsubscribe`,{subscriptionId:n.subscriptionId})}}async resubscribeWithRateLimitRetry(e,t){for(let n=0;;n++)try{return await this.send(`gdex_subscribe`,e,t)}catch(e){if(!(e instanceof c)||e.code!==-32003||n>=5)throw e;let t=this.readRetryAfterMs(e.data);r(`GDEX resubscribe rate limited; retrying in ${t}ms`),await new Promise(e=>setTimeout(e,t))}}waitForReconnectDelay(e){return new Promise(t=>{this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.reconnectDelayResolve=void 0,t()},e),this.reconnectDelayResolve=t})}clearReconnectTimer(){this.reconnectTimer!==void 0&&clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0;let e=this.reconnectDelayResolve;this.reconnectDelayResolve=void 0,e?.()}rejectPending(e){for(let t of this.pending.values())clearTimeout(t.timeout),t.reject(e);this.pending.clear()}readRetryAfterMs(e){return!this.isRecord(e)||typeof e.retryAfterMs!=`number`||e.retryAfterMs<0?1e3:e.retryAfterMs}isRecord(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}};export{c as GdexStreamError,u as GdexStreamService,s as isGdexLiquidityEvent};
|
|
2
|
+
//# sourceMappingURL=gdex_stream.js.map
|