@gala-chain/gswap-sdk 1.1.0 → 1.2.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,8 +1,66 @@
1
1
  import BigNumber from "bignumber.js";
2
2
  import { Decimal } from "decimal.js";
3
3
  import debug from "debug";
4
- import { serialize, signatures } from "@gala-chain/api";
4
+ import { secp256k1 } from "@noble/curves/secp256k1";
5
+ import { keccak_256 } from "@noble/hashes/sha3";
6
+ import { bytesToHex } from "@noble/hashes/utils";
5
7
 
8
+ //#region src/utils/confirmation_schedule.ts
9
+ const DEFAULT_TIMEOUT_MS = 6e4;
10
+ const DEFAULT_POLL_INTERVAL_MS = 2e3;
11
+ const MIN_POLL_INTERVAL_MS = 500;
12
+ const MAX_BACKOFF_MS = 8e3;
13
+ /**
14
+ * Builds the schedule for one `confirm()` call. `abortError` creates the error thrown when
15
+ * `options.signal` aborts, so each confirmation kind keeps its own error type and details.
16
+ */
17
+ function createConfirmationSchedule(options, defaultInitialDelayMs, abortError) {
18
+ const timeoutMs = Math.max(0, (options === null || options === void 0 ? void 0 : options.timeoutMs) ?? DEFAULT_TIMEOUT_MS);
19
+ const pollIntervalMs = Math.max(MIN_POLL_INTERVAL_MS, (options === null || options === void 0 ? void 0 : options.pollIntervalMs) ?? DEFAULT_POLL_INTERVAL_MS);
20
+ const initialDelayMs = Math.max(0, (options === null || options === void 0 ? void 0 : options.initialDelayMs) ?? defaultInitialDelayMs);
21
+ const signal = options === null || options === void 0 ? void 0 : options.signal;
22
+ const deadline = Date.now() + timeoutMs;
23
+ let firstRead = true;
24
+ let attempt = 0;
25
+ return { async waitForRead(retryAfterMs) {
26
+ throwIfAborted(signal, abortError);
27
+ if (firstRead) {
28
+ firstRead = false;
29
+ const remaining = Math.max(0, deadline - Date.now());
30
+ await delay(Math.min(initialDelayMs, remaining), signal, abortError);
31
+ return true;
32
+ }
33
+ const backoff = Math.min(MAX_BACKOFF_MS, pollIntervalMs * 2 ** Math.min(attempt, 5));
34
+ attempt += 1;
35
+ const waitMs = retryAfterMs === void 0 ? jitter(backoff) : Math.max(0, retryAfterMs);
36
+ if (Date.now() + waitMs > deadline) return false;
37
+ await delay(waitMs, signal, abortError);
38
+ return true;
39
+ } };
40
+ }
41
+ /** Throws `abortError(signal.reason)` when the signal has aborted. */
42
+ function throwIfAborted(signal, abortError) {
43
+ if ((signal === null || signal === void 0 ? void 0 : signal.aborted) === true) throw abortError(signal.reason);
44
+ }
45
+ function delay(milliseconds, signal, abortError) {
46
+ if ((signal === null || signal === void 0 ? void 0 : signal.aborted) === true) return Promise.reject(abortError(signal.reason));
47
+ return new Promise((resolve, reject) => {
48
+ const onAbort = () => {
49
+ clearTimeout(timer);
50
+ reject(abortError(signal === null || signal === void 0 ? void 0 : signal.reason));
51
+ };
52
+ const timer = setTimeout(() => {
53
+ signal === null || signal === void 0 || signal.removeEventListener("abort", onAbort);
54
+ resolve();
55
+ }, milliseconds);
56
+ signal === null || signal === void 0 || signal.addEventListener("abort", onAbort, { once: true });
57
+ });
58
+ }
59
+ function jitter(milliseconds) {
60
+ return Math.max(0, Math.round(milliseconds * (.9 + Math.random() * .2)));
61
+ }
62
+
63
+ //#endregion
6
64
  //#region src/classes/gswap_sdk_error.ts
7
65
  /** Error raised by the SDK for validation, gateway, chain, or transaction failures. */
8
66
  var GSwapSDKError = class GSwapSDKError extends Error {
@@ -10,6 +68,19 @@ var GSwapSDKError = class GSwapSDKError extends Error {
10
68
  details;
11
69
  chainMessage;
12
70
  retryAfterMs;
71
+ /** The HTTP status of the response that caused this error, when there was one. */
72
+ status;
73
+ /**
74
+ * The response body parsed as JSON, when the failing response had one; `undefined` for a body
75
+ * that was not JSON (see {@link bodyText}). Never part of {@link message}.
76
+ */
77
+ body;
78
+ /**
79
+ * The raw text of a failing response whose body was NOT JSON (a proxy's HTML 502, a WAF page,
80
+ * an empty body). It is kept here for diagnostics and is never copied into {@link message} or
81
+ * {@link userMessage}, so it cannot reach a user interface by accident.
82
+ */
83
+ bodyText;
13
84
  constructor(message, code, details, chainMessage, retryAfterMs) {
14
85
  super(message);
15
86
  this.code = code;
@@ -17,6 +88,32 @@ var GSwapSDKError = class GSwapSDKError extends Error {
17
88
  this.name = "GSwapSDKError";
18
89
  this.chainMessage = chainMessage;
19
90
  this.retryAfterMs = retryAfterMs;
91
+ const status = details === null || details === void 0 ? void 0 : details["status"];
92
+ this.status = typeof status === "number" ? status : void 0;
93
+ const body = details === null || details === void 0 ? void 0 : details["body"];
94
+ this.body = typeof body === "string" ? void 0 : body;
95
+ this.bodyText = typeof body === "string" ? body : void 0;
96
+ }
97
+ /**
98
+ * A message that is safe to show a user as is: the server's own message when it sent one
99
+ * (a gateway or chain rejection), a neutral line naming the status for an HTTP failure with no
100
+ * readable answer, and otherwise {@link message}. Apps that word these differently (a
101
+ * "network busy" line for a 502, say) branch on {@link code} and {@link status} instead.
102
+ */
103
+ get userMessage() {
104
+ if (this.chainMessage !== void 0 && this.chainMessage !== "") return this.chainMessage;
105
+ if (this.code === "HTTP_ERROR" && this.status !== void 0) return `The server answered with an unexpected response (HTTP ${this.status}).`;
106
+ return this.message;
107
+ }
108
+ /**
109
+ * True when the failure means "that market, pool or position does not exist" rather than
110
+ * "something went wrong": an HTTP 404, a pair with no pool at any fee tier
111
+ * (`NO_POOL_AVAILABLE`), or a token the DEX contract has no trading symbol for
112
+ * (`UNKNOWN_TOKEN`). A pool that exists but is too thin (`INSUFFICIENT_LIQUIDITY`) is NOT
113
+ * not-found.
114
+ */
115
+ get notFound() {
116
+ return this.status === 404 || this.code === "NO_POOL_AVAILABLE" || this.code === "UNKNOWN_TOKEN";
20
117
  }
21
118
  /** Create the standard missing-signer error. */
22
119
  static noSignerError() {
@@ -26,21 +123,38 @@ var GSwapSDKError = class GSwapSDKError extends Error {
26
123
  static noWalletAddressError() {
27
124
  return new GSwapSDKError("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.", "NO_WALLET_ADDRESS");
28
125
  }
29
- /** Create the error used when no pool can quote the requested pair. */
30
- static noPoolAvailableError(tokenIn, tokenOut, fee) {
126
+ /**
127
+ * Create the error used when no pool can quote the requested pair. `source` is the backend
128
+ * answer that said so; its status, body and message are kept (the message as `chainMessage`,
129
+ * so {@link userMessage} is the server's own wording).
130
+ */
131
+ static noPoolAvailableError(tokenIn, tokenOut, fee, source) {
31
132
  return new GSwapSDKError("No pool is available for the requested pair.", "NO_POOL_AVAILABLE", {
32
133
  tokenIn,
33
134
  tokenOut,
34
- ...fee === void 0 ? {} : { fee }
35
- });
135
+ ...fee === void 0 ? {} : { fee },
136
+ ...sourceDetails(source)
137
+ }, source === null || source === void 0 ? void 0 : source.serverMessage);
36
138
  }
37
- /** Create the error used when a pool lacks liquidity for a quote. */
38
- static insufficientLiquidityError(tokenIn, tokenOut, fee) {
139
+ /** Create the error used when a pool lacks liquidity for a quote. `source` as for {@link noPoolAvailableError}. */
140
+ static insufficientLiquidityError(tokenIn, tokenOut, fee, source) {
39
141
  return new GSwapSDKError("The selected pool has insufficient liquidity for the requested quote.", "INSUFFICIENT_LIQUIDITY", {
40
142
  tokenIn,
41
143
  tokenOut,
42
- ...fee === void 0 ? {} : { fee }
43
- });
144
+ ...fee === void 0 ? {} : { fee },
145
+ ...sourceDetails(source)
146
+ }, source === null || source === void 0 ? void 0 : source.serverMessage);
147
+ }
148
+ /**
149
+ * The message the server put in a JSON answer (`message`, or `error.Message`), when this error
150
+ * came from an HTTP response that had one.
151
+ */
152
+ get serverMessage() {
153
+ var _this$details;
154
+ const direct = (_this$details = this.details) === null || _this$details === void 0 ? void 0 : _this$details["message"];
155
+ if (typeof direct === "string") return direct;
156
+ const body = this.body;
157
+ return getStringProperty(body, "message") ?? getStringProperty(body, "Message") ?? getStringProperty(getObjectProperty(body, "error"), "Message");
44
158
  }
45
159
  /** Convert a chain-gateway bounce into a typed SDK error. */
46
160
  static fromGatewayBounce(code, message, status, retryAfterMs) {
@@ -93,6 +207,15 @@ var GSwapSDKError = class GSwapSDKError extends Error {
93
207
  });
94
208
  }
95
209
  };
210
+ /** The HTTP facts of the error a classified error was derived from. */
211
+ function sourceDetails(source) {
212
+ if (source === void 0) return {};
213
+ return {
214
+ ...source.status === void 0 ? {} : { status: source.status },
215
+ ...source.body === void 0 ? {} : { body: source.body },
216
+ ...source.bodyText === void 0 ? {} : { body: source.bodyText }
217
+ };
218
+ }
96
219
  /** Narrow an object property without trusting a cast at a network boundary. */
97
220
  function getObjectProperty(value, property) {
98
221
  if (typeof value !== "object" || value === null || !(property in value)) return void 0;
@@ -114,6 +237,280 @@ function parseJson(text) {
114
237
  }
115
238
  }
116
239
 
240
+ //#endregion
241
+ //#region src/utils/transport.ts
242
+ /**
243
+ * Arms the abort timer for a request. `Infinity` means "never time out": `setTimeout` would turn
244
+ * it into 1 ms, so no timer is armed at all. Returns a function that disarms it.
245
+ */
246
+ function armTimeout(controller, timeoutMs) {
247
+ if (timeoutMs === Infinity) return () => void 0;
248
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
249
+ return () => clearTimeout(timer);
250
+ }
251
+ /**
252
+ * Validates a request timeout in milliseconds: a positive finite number, or `Infinity` for none.
253
+ *
254
+ * @throws GSwapSDKError VALIDATION_ERROR otherwise.
255
+ */
256
+ function validateTimeoutMs(timeoutMs, name) {
257
+ if (timeoutMs === Infinity || Number.isFinite(timeoutMs) && timeoutMs > 0) return timeoutMs;
258
+ throw new GSwapSDKError(`${name} must be a positive number of milliseconds, or Infinity for no timeout.`, "VALIDATION_ERROR", { [name]: timeoutMs });
259
+ }
260
+ const READABLE_QUERY_SAFE = /[A-Za-z0-9\-._~!'()*$|:,]/u;
261
+ function encodeReadable(text) {
262
+ let out = "";
263
+ for (const char of text) if (char === " ") out += "+";
264
+ else if (READABLE_QUERY_SAFE.test(char)) out += char;
265
+ else out += encodeScalar(char);
266
+ return out;
267
+ }
268
+ /** Percent-encodes one code point; a lone surrogate becomes U+FFFD, as `URLSearchParams` does. */
269
+ function encodeScalar(char) {
270
+ try {
271
+ return encodeURIComponent(char);
272
+ } catch {
273
+ return "%EF%BF%BD";
274
+ }
275
+ }
276
+ /** Serializes GET parameters, in insertion order, in the encoding the wire options select. */
277
+ function buildQueryString(params, encoding = "standard") {
278
+ if (encoding === "readable") return Object.entries(params).map(([key, value]) => `${encodeReadable(key)}=${encodeReadable(value)}`).join("&");
279
+ return new URLSearchParams(params).toString();
280
+ }
281
+ async function requestWithTimeout(requestor, url, options, timeoutMs) {
282
+ const controller = new AbortController();
283
+ const disarm = armTimeout(controller, timeoutMs);
284
+ const externalSignal = options.signal;
285
+ const abortFromCaller = () => controller.abort();
286
+ externalSignal === null || externalSignal === void 0 || externalSignal.addEventListener("abort", abortFromCaller, { once: true });
287
+ try {
288
+ return await requestor(url, {
289
+ ...options,
290
+ signal: controller.signal
291
+ });
292
+ } catch (error) {
293
+ if (controller.signal.aborted) throw new GSwapSDKError(`Request timed out after ${timeoutMs} ms.`, "REQUEST_TIMEOUT", {
294
+ url,
295
+ timeoutMs,
296
+ cause: error
297
+ });
298
+ throw error;
299
+ } finally {
300
+ disarm();
301
+ externalSignal === null || externalSignal === void 0 || externalSignal.removeEventListener("abort", abortFromCaller);
302
+ }
303
+ }
304
+ async function readResponseBody(response) {
305
+ const text = await response.text();
306
+ return parseJson(text) ?? text;
307
+ }
308
+ /** Read a case-insensitive response header from either supported header shape. */
309
+ function readHeader(response, name) {
310
+ var _Object$entries$find;
311
+ const headers = response.headers;
312
+ if (headers === void 0) return void 0;
313
+ if (hasHeaderGetter(headers)) {
314
+ const value = headers.get(name);
315
+ return value === null || value === "" ? void 0 : value;
316
+ }
317
+ const value = (_Object$entries$find = Object.entries(headers).find(([key]) => key.toLowerCase() === name.toLowerCase())) === null || _Object$entries$find === void 0 ? void 0 : _Object$entries$find[1];
318
+ return value === void 0 || value === "" ? void 0 : value;
319
+ }
320
+ /** Read a Retry-After header (delta-seconds or an HTTP date) as non-negative milliseconds. */
321
+ function readRetryAfter(response) {
322
+ const raw = readHeader(response, "retry-after");
323
+ if (raw === void 0) return void 0;
324
+ const seconds = Number(raw);
325
+ if (Number.isFinite(seconds) && seconds >= 0) return seconds * 1e3;
326
+ const timestamp = Date.parse(raw);
327
+ return Number.isNaN(timestamp) ? void 0 : Math.max(0, timestamp - Date.now());
328
+ }
329
+ /** Read a non-negative integer block number header. */
330
+ function readBlockNumberHeader(response, headerName = "x-block-number") {
331
+ const raw = readHeader(response, headerName);
332
+ if (raw === void 0) return void 0;
333
+ const blockNumber = Number(raw);
334
+ return Number.isInteger(blockNumber) && blockNumber >= 0 ? blockNumber : void 0;
335
+ }
336
+ function hasHeaderGetter(headers) {
337
+ return "get" in headers && typeof headers.get === "function";
338
+ }
339
+
340
+ //#endregion
341
+ //#region src/classes/apply_results.ts
342
+ /** The apply-results key constraint of the swap backend (`apply-results.dto.ts`). */
343
+ const UNIQUE_KEY_PATTERN$1 = /^[A-Za-z0-9._:-]{1,128}$/u;
344
+ /**
345
+ * The AutoApplier waits at least 2 s before applying and the apply lands ~6-8 s after the
346
+ * acknowledgement, so a read at t=0 is a guaranteed 404.
347
+ */
348
+ const DEFAULT_INITIAL_DELAY_MS = 3e3;
349
+ const DEFAULT_REQUEST_TIMEOUT_MS = 3e4;
350
+ /**
351
+ * The outcome of a queued RequestTrade that could not be delivered as an {@link AppliedTrade}.
352
+ * `code` says why:
353
+ *
354
+ * - `CONFIRMATION_TIMEOUT`: no terminal result before the deadline. The trade may still apply;
355
+ * confirm the same `uniqueKey` again later and never resubmit.
356
+ * - `CONFIRMATION_ABORTED`: the caller's `signal` aborted. Nothing is known about the outcome.
357
+ * - `CONFIRMATION_FAILED`: the apply-results read itself failed (malformed key or body, a
358
+ * non-retryable HTTP status). The outcome is unknown.
359
+ * - anything else: the chain REJECTED the trade; `code` is the chain `ErrorKey` (or
360
+ * `CHAIN_ERROR`) and `chainMessage` is its message, which is also `message`.
361
+ *
362
+ * `details` always carries `uniqueKey` and, where known, `requestTransactionId`,
363
+ * `applyTransactionId`, `blockNumber`, `status`, `body`, `url` and the last transport `cause`.
364
+ */
365
+ var AppliedTradeError = class extends GSwapSDKError {
366
+ constructor(message, code, details = {}, chainMessage) {
367
+ super(message, code, details, chainMessage);
368
+ this.name = "AppliedTradeError";
369
+ }
370
+ };
371
+ /**
372
+ * Polls `GET /v1/chain/apply-results/{uniqueKey}?channel=asset&contract=dex-contract` until the
373
+ * queued RequestTrade reaches a terminal state.
374
+ *
375
+ * Pacing: wait `initialDelayMs` (default 3 s), then read; on 404, 429, 500, 502, 503, 504 or a
376
+ * transport error wait with jittered exponential backoff (`pollIntervalMs` doubling to 8 s,
377
+ * `Retry-After` honored as seconds or an HTTP date) until `timeoutMs`. Any other status is
378
+ * terminal. At least one read is always made.
379
+ *
380
+ * @returns The applied trade.
381
+ * @throws AppliedTradeError - see its documentation for every `code`.
382
+ * @example
383
+ * ```ts
384
+ * const applied = await confirmAppliedTrade(
385
+ * { dexBackendBaseUrl: 'https://dex-backend-prod1.defi.gala.com' },
386
+ * { uniqueKey, requestTransactionId: null },
387
+ * { initialDelayMs: 0, timeoutMs: 60_000, signal: controller.signal },
388
+ * );
389
+ * ```
390
+ */
391
+ async function confirmAppliedTrade(client, input, options) {
392
+ const { uniqueKey } = input;
393
+ if (!UNIQUE_KEY_PATTERN$1.test(uniqueKey)) throw new AppliedTradeError("uniqueKey must be 1-128 characters of A-Z, a-z, 0-9, \".\", \"_\", \":\" or \"-\".", "CONFIRMATION_FAILED", { uniqueKey });
394
+ const requestor = client.httpRequestor ?? fetch.bind(globalThis);
395
+ const requestTimeoutMs = client.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
396
+ const signal = options === null || options === void 0 ? void 0 : options.signal;
397
+ const abortError = (cause) => new AppliedTradeError("Transaction confirmation was aborted.", "CONFIRMATION_ABORTED", {
398
+ uniqueKey,
399
+ ...cause === void 0 ? {} : { cause }
400
+ });
401
+ const url = `${client.dexBackendBaseUrl.replace(/\/$/u, "")}/v1/chain/apply-results/${encodeURIComponent(uniqueKey)}?channel=asset&contract=dex-contract`;
402
+ const schedule = createConfirmationSchedule(options, DEFAULT_INITIAL_DELAY_MS, abortError);
403
+ await schedule.waitForRead();
404
+ let lastError;
405
+ while (true) {
406
+ throwIfAborted(signal, abortError);
407
+ let response;
408
+ let body;
409
+ try {
410
+ response = await requestWithTimeout(requestor, url, {
411
+ method: "GET",
412
+ ...signal === void 0 ? {} : { signal }
413
+ }, requestTimeoutMs);
414
+ body = await readResponseBody(response);
415
+ } catch (error) {
416
+ throwIfAborted(signal, abortError);
417
+ lastError = error;
418
+ if (!await schedule.waitForRead()) break;
419
+ continue;
420
+ }
421
+ throwIfAborted(signal, abortError);
422
+ if (response.status === 200) return readAppliedResult(input, response, body, url);
423
+ if (response.status === 404 || response.status === 429 || isTransient(response.status)) {
424
+ const retryAfter = response.status === 429 ? readRetryAfter(response) : void 0;
425
+ if (!await schedule.waitForRead(retryAfter)) break;
426
+ continue;
427
+ }
428
+ throw new AppliedTradeError(bodyMessage(body), "CONFIRMATION_FAILED", {
429
+ uniqueKey,
430
+ status: response.status,
431
+ body,
432
+ url
433
+ });
434
+ }
435
+ throw new AppliedTradeError("Transaction confirmation timed out; the trade may still apply. Confirm the same uniqueKey again later instead of resubmitting.", "CONFIRMATION_TIMEOUT", {
436
+ uniqueKey,
437
+ requestTransactionId: input.requestTransactionId,
438
+ url,
439
+ ...lastError === void 0 ? {} : { cause: lastError }
440
+ });
441
+ }
442
+ function readAppliedResult(input, response, body, url) {
443
+ const { uniqueKey } = input;
444
+ const record = asRecord$2(body);
445
+ const responseKey = (record === null || record === void 0 ? void 0 : record["uniqueKey"]) ?? (record === null || record === void 0 ? void 0 : record["UniqueKey"]);
446
+ if (typeof responseKey === "string" && responseKey !== uniqueKey) throw malformed(input, response, body, url, "Apply result key did not match the requested key.");
447
+ const status = record === null || record === void 0 ? void 0 : record["Status"];
448
+ const applyTransactionId = readHeader(response, "x-apply-transaction-id") ?? null;
449
+ const blockNumber = readBlockNumberHeader(response, "x-apply-block-number") ?? null;
450
+ if (status === 0) {
451
+ const errorKey = getStringProperty(record, "ErrorKey") ?? "CHAIN_ERROR";
452
+ const chainMessage = getStringProperty(record, "Message") ?? "The chain rejected this trade.";
453
+ throw new AppliedTradeError(chainMessage, errorKey, {
454
+ uniqueKey,
455
+ requestTransactionId: input.requestTransactionId,
456
+ applyTransactionId,
457
+ blockNumber,
458
+ status: response.status,
459
+ body,
460
+ url,
461
+ errorKey,
462
+ message: chainMessage
463
+ }, chainMessage);
464
+ }
465
+ if (status !== 1) throw malformed(input, response, body, url);
466
+ const result = parseTradeExecution(record === null || record === void 0 ? void 0 : record["Data"]);
467
+ if (result === void 0) throw malformed(input, response, body, url);
468
+ return {
469
+ uniqueKey,
470
+ transactionId: applyTransactionId,
471
+ blockNumber,
472
+ requestTransactionId: input.requestTransactionId,
473
+ result
474
+ };
475
+ }
476
+ function malformed(input, response, body, url, message = "Transaction confirmation returned a malformed body") {
477
+ return new AppliedTradeError(message, "CONFIRMATION_FAILED", {
478
+ uniqueKey: input.uniqueKey,
479
+ status: response.status,
480
+ body,
481
+ url
482
+ });
483
+ }
484
+ function parseTradeExecution(value) {
485
+ const record = asRecord$2(value);
486
+ if (record === void 0 || typeof record["token0"] !== "string" || typeof record["token1"] !== "string" || typeof record["fee"] !== "number") return;
487
+ const optionalFields = [
488
+ "sell0Qty",
489
+ "sell1Qty",
490
+ "buy0Qty",
491
+ "buy1Qty",
492
+ "tradingFees",
493
+ "protocolFees",
494
+ "totalFees"
495
+ ];
496
+ for (const field of optionalFields) if (field in record && typeof record[field] !== "string") return void 0;
497
+ return {
498
+ token0: record["token0"],
499
+ token1: record["token1"],
500
+ fee: record["fee"],
501
+ ...Object.fromEntries(optionalFields.flatMap((field) => typeof record[field] === "string" ? [[field, record[field]]] : []))
502
+ };
503
+ }
504
+ function isTransient(status) {
505
+ return status === 500 || status === 502 || status === 503 || status === 504;
506
+ }
507
+ function bodyMessage(body) {
508
+ return getStringProperty(body, "message") ?? getStringProperty(body, "Message") ?? getStringProperty(getObjectProperty(body, "error"), "message") ?? getStringProperty(getObjectProperty(body, "error"), "Message") ?? "Transaction confirmation failed";
509
+ }
510
+ function asRecord$2(value) {
511
+ return typeof value === "object" && value !== null ? value : void 0;
512
+ }
513
+
117
514
  //#endregion
118
515
  //#region src/types/fees.ts
119
516
  /**
@@ -206,6 +603,33 @@ function assertTickRange(lower, upper, fee) {
206
603
  function assertSpacing(spacing) {
207
604
  if (!Number.isInteger(spacing) || spacing <= 0) throw new RangeError("Tick spacing must be positive");
208
605
  }
606
+ /**
607
+ * Puts a `slot0` answer into the frame of the request. The backend always answers in the pool's
608
+ * canonical order and says so with `flippedFromRequest`; when the caller asked for the reverse
609
+ * order the price is inverted here (at 60 significant digits, so a very large or very small
610
+ * reciprocal keeps its precision) and the tick is re-derived from the inverted price with the
611
+ * contract's greatest-tick rule. Negating the tick instead is wrong for a price between ticks
612
+ * (and `-t - 1` is wrong for a price exactly on a tick: sqrtPrice 1 / tick 0 stays 1 / 0).
613
+ *
614
+ * @example
615
+ * ```ts
616
+ * const slot0 = await gSwap.pools.getSlot0('A', 'B', 500);
617
+ * const { sqrtPrice, tick } = frameSlot0(slot0);
618
+ * ```
619
+ */
620
+ function frameSlot0(slot0) {
621
+ if (slot0.flippedFromRequest !== true) return {
622
+ sqrtPrice: slot0.sqrtPrice,
623
+ tick: slot0.tick
624
+ };
625
+ const inverted = new DexDecimal(1).dividedBy(new DexDecimal(slot0.sqrtPrice));
626
+ if (!inverted.isFinite() || inverted.lessThanOrEqualTo(0)) throw new GSwapSDKError("Cannot invert a non-positive sqrt price.", "VALIDATION_ERROR", { sqrtPrice: slot0.sqrtPrice });
627
+ const sqrtPrice = inverted.toString();
628
+ return {
629
+ sqrtPrice,
630
+ tick: sqrtPriceToTick(sqrtPrice)
631
+ };
632
+ }
209
633
 
210
634
  //#endregion
211
635
  //#region src/utils/validation.ts
@@ -321,6 +745,36 @@ function validateWalletAddress(address) {
321
745
  value: address
322
746
  });
323
747
  }
748
+ /** Words the chain gateway refuses as a trading symbol. */
749
+ const RESERVED_TRADING_SYMBOLS = /* @__PURE__ */ new Set([
750
+ "Token",
751
+ "Unit",
752
+ "none"
753
+ ]);
754
+ const TRADING_SYMBOL_PATTERN = /^[A-Za-z0-9]+$/u;
755
+ const MAX_TRADING_SYMBOL_LENGTH = 32;
756
+ /**
757
+ * True when `symbol` is acceptable to propose into the trading-symbol registry: ASCII letters and
758
+ * digits only, 1 to 32 characters, and not a reserved word (`Token`, `Unit`, `none`) — the rules
759
+ * the chain gateway enforces on a CreatePool symbol.
760
+ */
761
+ function isProposableTradingSymbol(symbol) {
762
+ return TRADING_SYMBOL_PATTERN.test(symbol) && symbol.length <= MAX_TRADING_SYMBOL_LENGTH && !RESERVED_TRADING_SYMBOLS.has(symbol);
763
+ }
764
+ /**
765
+ * Asserts that a pair is in the contract's canonical order (`token0 < token1` by plain string
766
+ * comparison), which every write DTO requires. A pair a caller took from a stale quote or
767
+ * position can be reversed; signing it would sign something other than what was priced.
768
+ *
769
+ * @throws GSwapSDKError VALIDATION_ERROR (`details.type` = `NON_CANONICAL_PAIR`) otherwise.
770
+ */
771
+ function assertCanonicalPair(token0, token1) {
772
+ if (!(token0 < token1)) throw new GSwapSDKError(`The pair ${token0}/${token1} is not in canonical order: token0 must sort before token1.`, "VALIDATION_ERROR", {
773
+ type: "NON_CANONICAL_PAIR",
774
+ token0,
775
+ token1
776
+ });
777
+ }
324
778
 
325
779
  //#endregion
326
780
  //#region src/classes/assets.ts
@@ -381,62 +835,139 @@ function isRawUserAsset(value) {
381
835
  }
382
836
 
383
837
  //#endregion
384
- //#region src/utils/transport.ts
385
- async function requestWithTimeout(requestor, url, options, timeoutMs) {
386
- const controller = new AbortController();
387
- const timer = setTimeout(() => controller.abort(), timeoutMs);
388
- const externalSignal = options.signal;
389
- const abortFromCaller = () => controller.abort();
390
- externalSignal === null || externalSignal === void 0 || externalSignal.addEventListener("abort", abortFromCaller, { once: true });
391
- try {
392
- return await requestor(url, {
393
- ...options,
394
- signal: controller.signal
395
- });
396
- } catch (error) {
397
- if (controller.signal.aborted) throw new GSwapSDKError(`Request timed out after ${timeoutMs} ms.`, "REQUEST_TIMEOUT", {
398
- url,
399
- timeoutMs,
400
- cause: error
401
- });
402
- throw error;
403
- } finally {
404
- clearTimeout(timer);
405
- externalSignal === null || externalSignal === void 0 || externalSignal.removeEventListener("abort", abortFromCaller);
406
- }
407
- }
408
- async function readResponseBody(response) {
409
- const text = await response.text();
410
- return parseJson(text) ?? text;
838
+ //#region src/classes/dex_fees.ts
839
+ /** DEX methods the backend accepts a fee quote for (its allow-list enumerates the same six). */
840
+ const DEX_FEE_METHODS = [
841
+ "Swap",
842
+ "RequestTrade",
843
+ "AddLiquidity",
844
+ "RemoveLiquidity",
845
+ "CollectPositionFees",
846
+ "CreatePool"
847
+ ];
848
+ /** The chain method name the signed DryRun wrapper is signed under. */
849
+ const DRY_RUN_METHOD = "DryRun";
850
+ /** `uniqueKey` prefix of the DryRun WRAPPER (distinct from the inner DTO's key). */
851
+ const DRY_RUN_UNIQUE_KEY_PREFIX = "galaconnect-operation-";
852
+ /** True when `method` is a DEX method a fee can be quoted for. */
853
+ function isDexFeeMethod(method) {
854
+ return typeof method === "string" && DEX_FEE_METHODS.includes(method);
411
855
  }
412
- /** Read a case-insensitive response header from either supported header shape. */
413
- function readHeader(response, name) {
414
- var _Object$entries$find;
415
- const headers = response.headers;
416
- if (headers === void 0) return void 0;
417
- if (hasHeaderGetter(headers)) {
418
- const value = headers.get(name);
419
- return value === null || value === "" ? void 0 : value;
420
- }
421
- const value = (_Object$entries$find = Object.entries(headers).find(([key]) => key.toLowerCase() === name.toLowerCase())) === null || _Object$entries$find === void 0 ? void 0 : _Object$entries$find[1];
422
- return value === void 0 || value === "" ? void 0 : value;
856
+ /** Current-contract typed DEX messages use trading symbols instead of TokenClassKey objects. */
857
+ function isCurrentContractDexMessage(message, method) {
858
+ return isDexFeeMethod(method) && typeof (message === null || message === void 0 ? void 0 : message["token0"]) === "string" && typeof message["token1"] === "string";
423
859
  }
424
- /** Read a non-negative Retry-After header as milliseconds. */
425
- function readRetryAfter(response) {
426
- const raw = readHeader(response, "retry-after");
427
- if (raw === void 0) return void 0;
428
- const seconds = Number(raw);
429
- return Number.isFinite(seconds) && seconds >= 0 ? seconds * 1e3 : void 0;
860
+ /**
861
+ * Reduces an EIP-712 approval `message` to the DTO the chain actually receives: drops the signing
862
+ * envelope (`signature`, `prefix`, `types`, `domain`) and transport metadata (`trace`).
863
+ */
864
+ function toChainDto(message) {
865
+ const chainDto = { ...message };
866
+ for (const field of [
867
+ "signature",
868
+ "prefix",
869
+ "types",
870
+ "domain",
871
+ "trace"
872
+ ]) delete chainDto[field];
873
+ return chainDto;
430
874
  }
431
- /** Read a non-negative integer block number header. */
432
- function readBlockNumberHeader(response, headerName = "x-block-number") {
433
- const raw = readHeader(response, headerName);
434
- if (raw === void 0) return void 0;
435
- const blockNumber = Number(raw);
436
- return Number.isInteger(blockNumber) && blockNumber >= 0 ? blockNumber : void 0;
875
+ /**
876
+ * Signs the DryRun WRAPPER the gateway accepts for every contract:
877
+ * `{ callerPublicKey, method, dto: <inner DTO object>, uniqueKey, signature }`. The inner DTO
878
+ * travels unsigned and as an object; no `signerPublicKey` is sent because the signature already
879
+ * recovers it (the gateway rejects it as REDUNDANT_SIGNER_PUBLIC_KEY). The wrapper carries its own
880
+ * `uniqueKey`, distinct from the DTO's.
881
+ */
882
+ function buildDryRunWrapper(signer, callerPublicKey, method, dto, uniqueKeyPrefix = DRY_RUN_UNIQUE_KEY_PREFIX) {
883
+ return signer.signObject(DRY_RUN_METHOD, {
884
+ callerPublicKey,
885
+ method,
886
+ dto,
887
+ uniqueKey: `${uniqueKeyPrefix}${globalThis.crypto.randomUUID()}`
888
+ });
437
889
  }
438
- function hasHeaderGetter(headers) {
439
- return "get" in headers && typeof headers.get === "function";
890
+ /**
891
+ * Network-fee quote for GalaChain DEX methods, derived from a server-side DryRun.
892
+ *
893
+ * The client only SIGNS the DryRun wrapper (with whatever {@link GalaChainSigner} it is given) and
894
+ * the backend forwards it to the gateway, where the simulated writes carry the fee; the backend
895
+ * never holds a key. Intended for wallets: the DTO quoted is the typed message a dApp handed over.
896
+ *
897
+ * @example
898
+ * ```ts
899
+ * const fees = new DexFees({ dexBackendBaseUrl }, new PrivateKeySigner(sessionKey));
900
+ * const quote = await fees.quote(publicKey, 'RequestTrade', toChainDto(message), {
901
+ * contract: 'dex-contract',
902
+ * });
903
+ * const feeInGala = quote?.fees[0]?.feeInGala;
904
+ * ```
905
+ */
906
+ var DexFees = class {
907
+ signer;
908
+ requestor;
909
+ baseUrl;
910
+ requestTimeoutMs;
911
+ constructor(client, signer) {
912
+ this.signer = signer;
913
+ this.requestor = client.httpRequestor ?? fetch.bind(globalThis);
914
+ this.baseUrl = client.dexBackendBaseUrl.replace(/\/$/u, "");
915
+ this.requestTimeoutMs = client.requestTimeoutMs ?? 3e4;
916
+ }
917
+ /**
918
+ * Quotes the network fee for `method` applied to `message`. The message is reduced with
919
+ * {@link toChainDto} first, so an EIP-712 approval message can be passed as is.
920
+ *
921
+ * Resolves `null` when the BACKEND could not be reached or answered unusably (offline, 4xx/5xx,
922
+ * malformed body): a transport outcome, not a fee. Deciding what to charge when the chain is
923
+ * silent is the backend's job (it serves `source: 'default'`), so the client never substitutes
924
+ * a fee of its own, with ONE exception that mirrors the wallet: a `dex-contract` quote answered
925
+ * 403 or 404 means the contract has no fee route yet and resolves `{ source: 'default', '0' }`.
926
+ * Never throws on transport, so a fee lookup cannot block or break a signing screen.
927
+ *
928
+ * @throws GSwapSDKError NO_SIGNER when constructed without a signer; any error the signer
929
+ * throws (for example a locked wallet) propagates unchanged.
930
+ */
931
+ async quote(callerPublicKey, method, message, options = {}) {
932
+ if (this.signer === void 0) throw GSwapSDKError.noSignerError();
933
+ const channel = options.channel ?? "asset";
934
+ const contract = options.contract ?? "dexv3-contract";
935
+ const wrapper = await buildDryRunWrapper(this.signer, callerPublicKey, method, toChainDto(message));
936
+ const url = `${this.baseUrl}/wallet/connect/galachain/api/${encodeURIComponent(channel)}/${encodeURIComponent(contract)}/${encodeURIComponent(method)}/fee`;
937
+ let status;
938
+ let ok;
939
+ let body;
940
+ try {
941
+ const response = await requestWithTimeout(this.requestor, url, {
942
+ method: "POST",
943
+ headers: {
944
+ "Content-Type": "application/json",
945
+ Accept: "application/json"
946
+ },
947
+ body: JSON.stringify(wrapper)
948
+ }, this.requestTimeoutMs);
949
+ status = response.status;
950
+ ok = response.ok;
951
+ body = ok ? await readResponseBody(response) : void 0;
952
+ } catch {
953
+ return null;
954
+ }
955
+ if (!ok) {
956
+ if (contract === "dex-contract" && (status === 403 || status === 404)) return {
957
+ source: "default",
958
+ fees: [{ feeInGala: "0" }]
959
+ };
960
+ return null;
961
+ }
962
+ return readQuote(body);
963
+ }
964
+ };
965
+ function readQuote(body) {
966
+ var _fees$;
967
+ if (typeof body !== "object" || body === null) return null;
968
+ const fees = body.fees;
969
+ if (!Array.isArray(fees) || typeof ((_fees$ = fees[0]) === null || _fees$ === void 0 ? void 0 : _fees$.feeInGala) !== "string") return null;
970
+ return body;
440
971
  }
441
972
 
442
973
  //#endregion
@@ -450,6 +981,12 @@ var SubmittedTransaction = class {
450
981
  mode;
451
982
  /** The synchronous gateway result, or `undefined` when `mode === 'queued'`. */
452
983
  result;
984
+ /**
985
+ * The gateway's whole JSON answer as it came (`{ status, message, error, data }`), for an app
986
+ * that hands the backend's own envelope to its callers; `undefined` for a transaction built from
987
+ * a uniqueKey alone.
988
+ */
989
+ envelope;
453
990
  backendBaseUrl;
454
991
  requestor;
455
992
  requestTimeoutMs;
@@ -472,6 +1009,7 @@ var SubmittedTransaction = class {
472
1009
  this.blockNumber = options.blockNumber ?? null;
473
1010
  this.mode = options.mode;
474
1011
  this.result = options.result;
1012
+ this.envelope = options.envelope;
475
1013
  this.backendBaseUrl = options.dexBackendBaseUrl.replace(/\/$/u, "");
476
1014
  this.requestor = options.httpRequestor;
477
1015
  this.requestTimeoutMs = options.requestTimeoutMs ?? 3e4;
@@ -491,63 +1029,15 @@ var SubmittedTransaction = class {
491
1029
  if (this.method === "RequestTrade") return this.confirmApplied(options);
492
1030
  return this.confirmPosition(options);
493
1031
  }
494
- async confirmApplied(options) {
495
- const schedule = createConfirmationSchedule(options, 3e3);
496
- await schedule.waitForRead();
497
- const url = `${this.backendBaseUrl}/v1/chain/apply-results/${encodeURIComponent(this.uniqueKey)}?channel=asset&contract=dex-contract`;
498
- let lastError;
499
- while (true) {
500
- let response;
501
- let body;
502
- try {
503
- response = await requestWithTimeout(this.requestor, url, { method: "GET" }, this.requestTimeoutMs);
504
- body = await readResponseBody(response);
505
- } catch (error) {
506
- lastError = error;
507
- if (!await schedule.waitForRead()) break;
508
- continue;
509
- }
510
- if (response.status === 200) return this.readAppliedResult(response, body, url);
511
- if (response.status === 404 || response.status === 429 || isTransient(response.status)) {
512
- if (response.status === 429) {
513
- const retryAfter = readRetryAfter(response);
514
- if (retryAfter !== void 0) {
515
- if (!await schedule.waitForRead(retryAfter)) break;
516
- continue;
517
- }
518
- }
519
- } else throw new GSwapSDKError(bodyMessage(body), "CONFIRMATION_FAILED", {
520
- status: response.status,
521
- body,
522
- url
523
- });
524
- if (!await schedule.waitForRead()) break;
525
- }
526
- throw GSwapSDKError.confirmationTimeoutError(this.uniqueKey, lastError);
527
- }
528
- readAppliedResult(response, body, url) {
529
- const record = asRecord$1(body);
530
- const status = record === null || record === void 0 ? void 0 : record["Status"];
531
- const applyTransactionId = readHeader(response, "x-apply-transaction-id") ?? null;
532
- const blockNumber = readBlockNumberHeader(response, "x-apply-block-number") ?? null;
533
- if (status === 0) throw GSwapSDKError.fromChainError(getStringProperty(record, "ErrorKey") ?? "CHAIN_ERROR", getStringProperty(record, "Message") ?? "The chain rejected this trade.", {
534
- uniqueKey: this.uniqueKey,
535
- applyTransactionId,
536
- blockNumber,
537
- status: response.status,
538
- body,
539
- url
540
- });
541
- if (status !== 1) throw malformedConfirmation(response, body, url);
542
- const result = parseTradeExecution(record === null || record === void 0 ? void 0 : record["Data"]);
543
- if (result === void 0) throw malformedConfirmation(response, body, url);
544
- return {
1032
+ confirmApplied(options) {
1033
+ return confirmAppliedTrade({
1034
+ dexBackendBaseUrl: this.backendBaseUrl,
1035
+ httpRequestor: this.requestor,
1036
+ requestTimeoutMs: this.requestTimeoutMs
1037
+ }, {
545
1038
  uniqueKey: this.uniqueKey,
546
- transactionId: applyTransactionId,
547
- blockNumber,
548
- requestTransactionId: this.transactionId,
549
- result
550
- };
1039
+ requestTransactionId: this.transactionId
1040
+ }, options);
551
1041
  }
552
1042
  /** Confirm a liquidity write against the position's observable effect.
553
1043
  *
@@ -559,86 +1049,33 @@ var SubmittedTransaction = class {
559
1049
  */
560
1050
  async confirmPosition(options) {
561
1051
  if (this.positionConfirmation === void 0) throw GSwapSDKError.noWalletAddressError();
562
- const schedule = createConfirmationSchedule(options, 0);
1052
+ const callerSignal = options === null || options === void 0 ? void 0 : options.signal;
1053
+ const abortError = (cause) => new GSwapSDKError("Transaction confirmation was aborted.", "CONFIRMATION_ABORTED", {
1054
+ uniqueKey: this.uniqueKey,
1055
+ ...cause === void 0 ? {} : { cause }
1056
+ });
1057
+ const schedule = createConfirmationSchedule(options, 0, abortError);
563
1058
  await schedule.waitForRead();
564
1059
  while (true) {
565
1060
  const controller = new AbortController();
566
- const timer = setTimeout(() => controller.abort(), this.requestTimeoutMs);
1061
+ const disarm = armTimeout(controller, this.requestTimeoutMs);
1062
+ const forwardAbort = () => controller.abort();
1063
+ callerSignal === null || callerSignal === void 0 || callerSignal.addEventListener("abort", forwardAbort, { once: true });
567
1064
  try {
568
1065
  const result = await this.positionConfirmation(controller.signal);
569
1066
  if (result.confirmed) return result.position;
1067
+ } catch (error) {
1068
+ throwIfAborted(callerSignal, abortError);
1069
+ throw error;
570
1070
  } finally {
571
- clearTimeout(timer);
1071
+ disarm();
1072
+ callerSignal === null || callerSignal === void 0 || callerSignal.removeEventListener("abort", forwardAbort);
572
1073
  }
573
1074
  if (!await schedule.waitForRead()) break;
574
1075
  }
575
1076
  throw GSwapSDKError.confirmationTimeoutError(this.uniqueKey);
576
1077
  }
577
1078
  };
578
- function createConfirmationSchedule(options, defaultInitialDelayMs) {
579
- const timeoutMs = Math.max(0, (options === null || options === void 0 ? void 0 : options.timeoutMs) ?? 6e4);
580
- const pollIntervalMs = Math.max(500, (options === null || options === void 0 ? void 0 : options.pollIntervalMs) ?? 2e3);
581
- const initialDelayMs = Math.max(0, (options === null || options === void 0 ? void 0 : options.initialDelayMs) ?? defaultInitialDelayMs);
582
- const deadline = Date.now() + timeoutMs;
583
- let firstRead = true;
584
- let attempt = 0;
585
- return { async waitForRead(retryAfterMs) {
586
- if (firstRead) {
587
- firstRead = false;
588
- const remaining = Math.max(0, deadline - Date.now());
589
- await delay(Math.min(initialDelayMs, remaining));
590
- return true;
591
- }
592
- const backoff = Math.min(8e3, pollIntervalMs * 2 ** Math.min(attempt, 5));
593
- attempt += 1;
594
- const waitMs = retryAfterMs === void 0 ? jitter(backoff) : retryAfterMs;
595
- if (Date.now() + waitMs > deadline) return false;
596
- await delay(waitMs);
597
- return true;
598
- } };
599
- }
600
- function parseTradeExecution(value) {
601
- const record = asRecord$1(value);
602
- if (record === void 0 || typeof record["token0"] !== "string" || typeof record["token1"] !== "string" || typeof record["fee"] !== "number") return;
603
- const optionalFields = [
604
- "sell0Qty",
605
- "sell1Qty",
606
- "buy0Qty",
607
- "buy1Qty",
608
- "tradingFees",
609
- "protocolFees",
610
- "totalFees"
611
- ];
612
- for (const field of optionalFields) if (field in record && typeof record[field] !== "string") return void 0;
613
- return {
614
- token0: record["token0"],
615
- token1: record["token1"],
616
- fee: record["fee"],
617
- ...Object.fromEntries(optionalFields.flatMap((field) => typeof record[field] === "string" ? [[field, record[field]]] : []))
618
- };
619
- }
620
- function malformedConfirmation(response, body, url) {
621
- return new GSwapSDKError("Transaction confirmation returned a malformed body", "CONFIRMATION_FAILED", {
622
- status: response.status,
623
- body,
624
- url
625
- });
626
- }
627
- function isTransient(status) {
628
- return status === 500 || status === 502 || status === 503 || status === 504;
629
- }
630
- function bodyMessage(body) {
631
- return getStringProperty(body, "message") ?? getStringProperty(body, "Message") ?? getStringProperty(getObjectProperty(body, "error"), "message") ?? getStringProperty(getObjectProperty(body, "error"), "Message") ?? (typeof body === "string" ? body : "Transaction confirmation failed");
632
- }
633
- function asRecord$1(value) {
634
- return typeof value === "object" && value !== null ? value : void 0;
635
- }
636
- function delay(milliseconds) {
637
- return new Promise((resolve) => setTimeout(resolve, milliseconds));
638
- }
639
- function jitter(milliseconds) {
640
- return Math.max(0, Math.round(milliseconds * (.9 + Math.random() * .2)));
641
- }
642
1079
 
643
1080
  //#endregion
644
1081
  //#region src/classes/gateway.ts
@@ -649,38 +1086,28 @@ var ChainGateway = class {
649
1086
  chainCallTimeoutMs;
650
1087
  requestTimeoutMs;
651
1088
  dexBackendBaseUrl;
1089
+ /** Wire format shared by the read services built on this gateway. */
1090
+ wire;
652
1091
  /** Create a chain gateway client. */
653
1092
  constructor(options) {
654
1093
  this.dexBackendBaseUrl = trimTrailingSlash$1(options.dexBackendBaseUrl);
655
1094
  this.requestor = options.httpRequestor ?? fetch.bind(globalThis);
656
1095
  this.walletAddress = options.walletAddress;
657
- this.chainCallTimeoutMs = options.chainCallTimeoutMs ?? 3e4;
1096
+ this.chainCallTimeoutMs = validateTimeoutMs(options.chainCallTimeoutMs ?? 3e4, "chainCallTimeoutMs");
658
1097
  this.requestTimeoutMs = this.chainCallTimeoutMs;
1098
+ this.wire = options.wire ?? {};
659
1099
  }
660
1100
  async submit(method, signedBody, options) {
661
1101
  if (method === "Trade") throw new GSwapSDKError("The synchronous Trade method was removed; swaps are queued through RequestTrade.", "METHOD_NOT_SUPPORTED", { method });
662
- const url = `${this.dexBackendBaseUrl}/v1/chain/asset/dex-contract/${method}`;
1102
+ const url = this.writeUrl(method);
663
1103
  const headers = { "content-type": "application/json" };
664
1104
  const walletAddress = (options === null || options === void 0 ? void 0 : options.walletAddress) ?? this.walletAddress;
665
1105
  if (walletAddress !== void 0) headers["X-Wallet-Address"] = walletAddress;
666
- let response;
667
- try {
668
- response = await requestWithTimeout(this.requestor, url, {
669
- method: "POST",
670
- headers,
671
- body: JSON.stringify(signedBody)
672
- }, this.chainCallTimeoutMs);
673
- } catch (error) {
674
- if (error instanceof GSwapSDKError && error.code === "REQUEST_TIMEOUT") throw new GSwapSDKError("The submission outcome is unknown because the gateway request timed out. Confirm before retrying.", "SUBMISSION_OUTCOME_UNKNOWN", {
675
- uniqueKey: getStringProperty(signedBody, "uniqueKey") ?? "",
676
- cause: error
677
- });
678
- throw error;
679
- }
1106
+ const response = await this.post(url, headers, signedBody);
680
1107
  const body = await readResponseBody(response);
681
1108
  if (!response.ok) throw gatewayError(response, body, url);
682
- const envelope = asRecord(body);
683
- const data = asRecord((envelope === null || envelope === void 0 ? void 0 : envelope["data"]) ?? (envelope === null || envelope === void 0 ? void 0 : envelope["Data"]));
1109
+ const envelope = asRecord$1(body);
1110
+ const data = asRecord$1((envelope === null || envelope === void 0 ? void 0 : envelope["data"]) ?? (envelope === null || envelope === void 0 ? void 0 : envelope["Data"]));
684
1111
  if (data === void 0) throw invalidGatewayResponse(response, body, url, "Expected a data object.");
685
1112
  const transactionId = getStringProperty(data, "transactionId");
686
1113
  const mode = getStringProperty(data, "mode");
@@ -695,7 +1122,7 @@ var ChainGateway = class {
695
1122
  if ("uniqueKey" in data && (typeof data["uniqueKey"] !== "string" || data["uniqueKey"] !== signedUniqueKey)) throw invalidGatewayResponse(response, body, url, "Gateway response data.uniqueKey must match the signed RequestTrade uniqueKey.");
696
1123
  } else if (mode === "queued" || !("result" in data)) throw invalidGatewayResponse(response, body, url, invalidModeMessage);
697
1124
  if (mode === "sync") {
698
- const embeddedResult = asRecord(data["result"]);
1125
+ const embeddedResult = asRecord$1(data["result"]);
699
1126
  if (embeddedResult !== void 0) {
700
1127
  const resultStatus = embeddedResult["Status"];
701
1128
  if (resultStatus !== void 0 && resultStatus !== 1) throw GSwapSDKError.fromChainError(getStringProperty(embeddedResult, "ErrorKey") ?? "CHAIN_ERROR", getStringProperty(embeddedResult, "Message") ?? "The chain rejected this write.", {
@@ -705,22 +1132,75 @@ var ChainGateway = class {
705
1132
  });
706
1133
  }
707
1134
  }
708
- const uniqueKey = getStringProperty(signedBody, "uniqueKey") ?? "";
709
- const headerTransactionId = readHeader(response, "x-transaction-id");
710
- const resolvedTransactionId = transactionId === void 0 || transactionId === "" ? headerTransactionId : transactionId;
711
- const blockNumber = bodyBlockNumber === null || bodyBlockNumber === void 0 ? readBlockNumberHeader(response) : isBlockNumber(bodyBlockNumber) ? bodyBlockNumber : void 0;
712
- return new SubmittedTransaction({
713
- method,
714
- uniqueKey,
715
- transactionId: resolvedTransactionId === void 0 || resolvedTransactionId === "" ? null : resolvedTransactionId,
716
- blockNumber: blockNumber ?? null,
717
- mode,
718
- result: mode === "queued" ? void 0 : data["result"],
719
- dexBackendBaseUrl: this.dexBackendBaseUrl,
720
- httpRequestor: this.requestor,
721
- requestTimeoutMs: this.chainCallTimeoutMs,
722
- ...(options === null || options === void 0 ? void 0 : options.positionConfirmation) === void 0 ? {} : { positionConfirmation: options.positionConfirmation }
723
- });
1135
+ const uniqueKey = getStringProperty(signedBody, "uniqueKey") ?? "";
1136
+ const headerTransactionId = readHeader(response, "x-transaction-id");
1137
+ const resolvedTransactionId = transactionId === void 0 || transactionId === "" ? headerTransactionId : transactionId;
1138
+ const blockNumber = bodyBlockNumber === null || bodyBlockNumber === void 0 ? readBlockNumberHeader(response) : isBlockNumber(bodyBlockNumber) ? bodyBlockNumber : void 0;
1139
+ return new SubmittedTransaction({
1140
+ method,
1141
+ uniqueKey,
1142
+ transactionId: resolvedTransactionId === void 0 || resolvedTransactionId === "" ? null : resolvedTransactionId,
1143
+ blockNumber: blockNumber ?? null,
1144
+ mode,
1145
+ result: mode === "queued" ? void 0 : data["result"],
1146
+ envelope: body,
1147
+ dexBackendBaseUrl: this.dexBackendBaseUrl,
1148
+ httpRequestor: this.requestor,
1149
+ requestTimeoutMs: this.chainCallTimeoutMs,
1150
+ ...(options === null || options === void 0 ? void 0 : options.positionConfirmation) === void 0 ? {} : { positionConfirmation: options.positionConfirmation }
1151
+ });
1152
+ }
1153
+ /**
1154
+ * Submit a signed v2 DTO as a SHADOW (dark) write: the same route and body as {@link submit},
1155
+ * plus `X-Wallet-Address` and `X-Shadow: true`, so defi-backend marks the transaction private
1156
+ * before it reaches the contract. The wallet address is required (the backend resolves the
1157
+ * owner from it).
1158
+ *
1159
+ * Unlike `submit`, EVERY HTTP status resolves: the result is the raw `{ httpStatus, body }`,
1160
+ * because shadow failures are classified from the status together with the body's `code`
1161
+ * (`SHADOW_UNAVAILABLE`, `SHADOW_DISABLED`, `SHADOW_UNSUPPORTED_TYPE`, `SHADOW_RELAY_REJECTED`);
1162
+ * see `readShadowSubmitOutcome`. Only a transport failure rejects, and a timeout rejects
1163
+ * with `SUBMISSION_OUTCOME_UNKNOWN`.
1164
+ *
1165
+ * @example
1166
+ * ```ts
1167
+ * const result = await gateway.submitShadow('RequestTrade', signedDto, { walletAddress });
1168
+ * const outcome = readShadowSubmitOutcome('RequestTrade', signedDto, result);
1169
+ * ```
1170
+ */
1171
+ async submitShadow(method, signedBody, options) {
1172
+ if (method === "Trade") throw new GSwapSDKError("The synchronous Trade method was removed; swaps are queued through RequestTrade.", "METHOD_NOT_SUPPORTED", { method });
1173
+ const walletAddress = (options === null || options === void 0 ? void 0 : options.walletAddress) ?? this.walletAddress;
1174
+ if (walletAddress === void 0) throw new GSwapSDKError("A shadow submission needs a walletAddress (the X-Wallet-Address header): pass one to the GSwap constructor or to this call.", "NO_WALLET_ADDRESS");
1175
+ const headers = {
1176
+ "content-type": "application/json",
1177
+ "X-Wallet-Address": walletAddress,
1178
+ "X-Shadow": "true"
1179
+ };
1180
+ const response = await this.post(this.writeUrl(method), headers, signedBody);
1181
+ return {
1182
+ httpStatus: response.status,
1183
+ body: await readResponseBody(response)
1184
+ };
1185
+ }
1186
+ writeUrl(method) {
1187
+ return `${this.dexBackendBaseUrl}/v1/chain/asset/dex-contract/${method}`;
1188
+ }
1189
+ /** POSTs a signed body; a timeout means the outcome is unknown, never "not submitted". */
1190
+ async post(url, headers, signedBody) {
1191
+ try {
1192
+ return await requestWithTimeout(this.requestor, url, {
1193
+ method: "POST",
1194
+ headers,
1195
+ body: JSON.stringify(signedBody)
1196
+ }, this.chainCallTimeoutMs);
1197
+ } catch (error) {
1198
+ if (error instanceof GSwapSDKError && error.code === "REQUEST_TIMEOUT") throw new GSwapSDKError("The submission outcome is unknown because the gateway request timed out. Confirm before retrying.", "SUBMISSION_OUTCOME_UNKNOWN", {
1199
+ uniqueKey: getStringProperty(signedBody, "uniqueKey") ?? "",
1200
+ cause: error
1201
+ });
1202
+ throw error;
1203
+ }
724
1204
  }
725
1205
  /** Expose the requestor for sibling read services that share this gateway transport. */
726
1206
  get httpRequestor() {
@@ -738,10 +1218,10 @@ function invalidGatewayResponse(response, body, url, message) {
738
1218
  });
739
1219
  }
740
1220
  function gatewayError(response, body, url) {
741
- const object = asRecord(body);
1221
+ const object = asRecord$1(body);
742
1222
  const nested = getObjectProperty(body, "error");
743
1223
  const code = getStringProperty(object, "code") ?? getStringProperty(nested, "code") ?? getStringProperty(nested, "ErrorKey") ?? "HTTP_ERROR";
744
- const message = getStringProperty(object, "message") ?? getStringProperty(nested, "message") ?? getStringProperty(nested, "Message") ?? (typeof body === "string" ? body : `Gateway request failed with HTTP ${response.status}`);
1224
+ const message = getStringProperty(object, "message") ?? getStringProperty(nested, "message") ?? getStringProperty(nested, "Message") ?? `Gateway request failed with HTTP ${response.status}`;
745
1225
  const retryAfterMs = response.status === 429 ? readRetryAfter(response) : void 0;
746
1226
  if (code === "HTTP_ERROR") return new GSwapSDKError(message, code, {
747
1227
  status: response.status,
@@ -750,7 +1230,7 @@ function gatewayError(response, body, url) {
750
1230
  });
751
1231
  return GSwapSDKError.fromGatewayBounce(code, message, response.status, retryAfterMs);
752
1232
  }
753
- function asRecord(value) {
1233
+ function asRecord$1(value) {
754
1234
  return typeof value === "object" && value !== null ? value : void 0;
755
1235
  }
756
1236
  function isBlockNumber(value) {
@@ -841,6 +1321,11 @@ var GdexStreamError = class extends Error {
841
1321
  if (data !== void 0) this.data = data;
842
1322
  }
843
1323
  };
1324
+ function readSubscriptionId(value) {
1325
+ const id = typeof value === "object" && value !== null ? value.subscriptionId : void 0;
1326
+ if (typeof id !== "string") throw new GdexStreamError(-32603, "GDEX subscribe response is missing its subscriptionId");
1327
+ return id;
1328
+ }
844
1329
  /**
845
1330
  * Client for the gSwap realtime stream (gdex WebSocket Protocol v1): JSON-RPC 2.0 over one raw
846
1331
  * WebSocket, with automatic reconnect and resubscribe.
@@ -857,6 +1342,7 @@ var GdexStreamError = class extends Error {
857
1342
  var GdexStreamService = class {
858
1343
  url;
859
1344
  requestTimeoutMs;
1345
+ apiKey;
860
1346
  webSocketConstructor;
861
1347
  backoff;
862
1348
  socket;
@@ -879,6 +1365,10 @@ var GdexStreamService = class {
879
1365
  const implementation = config.webSocketImpl ?? globalThis.WebSocket;
880
1366
  if (typeof implementation !== "function") throw new Error("GdexStreamService requires a standards-compatible WebSocket constructor. Node.js versions before 22 must provide one with config.webSocketImpl (for example, from the \"ws\" package).");
881
1367
  this.webSocketConstructor = implementation;
1368
+ if (config.apiKey !== void 0) {
1369
+ if (config.apiKey === "" || config.webSocketImpl === void 0) throw new GSwapSDKError("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.", "VALIDATION_ERROR");
1370
+ this.apiKey = config.apiKey;
1371
+ }
882
1372
  }
883
1373
  /** Open the connection. Resolves at once when already connected. */
884
1374
  connect() {
@@ -906,6 +1396,9 @@ var GdexStreamService = class {
906
1396
  }
907
1397
  /** Raw JSON-RPC escape hatch. */
908
1398
  request(method, params) {
1399
+ return this.send(method, params);
1400
+ }
1401
+ send(method, params, onResult) {
909
1402
  if (!this.isConnected() || !this.socket) return Promise.reject(/* @__PURE__ */ new Error("GDEX stream is not connected. Call connect() first."));
910
1403
  const id = ++this.nextRequestId;
911
1404
  const frame = {
@@ -922,7 +1415,8 @@ var GdexStreamService = class {
922
1415
  this.pending.set(id, {
923
1416
  resolve: (value) => resolve(value),
924
1417
  reject,
925
- timeout
1418
+ timeout,
1419
+ onResult
926
1420
  });
927
1421
  try {
928
1422
  var _this$socket2;
@@ -965,7 +1459,11 @@ var GdexStreamService = class {
965
1459
  subscribeSwaps(cb, opts = {}) {
966
1460
  return this.subscribe("swap", cb, opts);
967
1461
  }
968
- /** State changes of one pool. */
1462
+ /**
1463
+ * State changes of one pool (price, tick, reserves, liquidity). These events carry no acting wallet:
1464
+ * on v2 `creator` is whoever created the pool, not whoever just traded or added liquidity. For
1465
+ * "who did it", use {@link subscribeLiquidity} (`owner`) or {@link subscribeSwaps} (`sender`).
1466
+ */
969
1467
  subscribePool(selector, cb, opts = {}) {
970
1468
  return this.subscribe("pool", cb, {
971
1469
  ...selector,
@@ -1003,7 +1501,7 @@ var GdexStreamService = class {
1003
1501
  openSocket() {
1004
1502
  return new Promise((resolve, reject) => {
1005
1503
  let opened = false;
1006
- const socket = new this.webSocketConstructor(this.url, GDEX_SUBPROTOCOL);
1504
+ const socket = this.apiKey === void 0 ? new this.webSocketConstructor(this.url, GDEX_SUBPROTOCOL) : new this.webSocketConstructor(this.url, GDEX_SUBPROTOCOL, { headers: { "x-api-key": this.apiKey } });
1007
1505
  this.socket = socket;
1008
1506
  socket.onopen = () => {
1009
1507
  if (this.socket !== socket) return;
@@ -1048,7 +1546,16 @@ var GdexStreamService = class {
1048
1546
  const code = typeof message.error.code === "number" ? message.error.code : -32603;
1049
1547
  const errorMessage = typeof message.error.message === "string" ? message.error.message : "GDEX request failed";
1050
1548
  pending.reject(new GdexStreamError(code, errorMessage, message.error.data));
1051
- } else pending.resolve(message.result);
1549
+ } else {
1550
+ try {
1551
+ var _pending$onResult;
1552
+ (_pending$onResult = pending.onResult) === null || _pending$onResult === void 0 || _pending$onResult.call(pending, message.result);
1553
+ } catch (error) {
1554
+ pending.reject(error instanceof Error ? error : new Error(String(error)));
1555
+ return;
1556
+ }
1557
+ pending.resolve(message.result);
1558
+ }
1052
1559
  return;
1053
1560
  }
1054
1561
  if (message.method !== "gdex_subscription" || !this.isRecord(message.params)) return;
@@ -1068,21 +1575,24 @@ var GdexStreamService = class {
1068
1575
  channel,
1069
1576
  ...options
1070
1577
  };
1071
- const result = await this.request("gdex_subscribe", params);
1072
- let active;
1073
1578
  const handle = {
1074
- subscriptionId: result.subscriptionId,
1075
- unsubscribe: async () => this.unsubscribe(active)
1579
+ subscriptionId: "",
1580
+ unsubscribe: async () => this.unsubscribe(subscription)
1076
1581
  };
1077
- active = {
1078
- serverId: result.subscriptionId,
1582
+ const subscription = {
1583
+ serverId: "",
1079
1584
  params,
1080
1585
  callback,
1081
1586
  handle,
1082
1587
  active: true
1083
1588
  };
1084
- this.activeSubscriptions.add(active);
1085
- this.subscriptionsByServerId.set(active.serverId, active);
1589
+ await this.send("gdex_subscribe", params, (value) => {
1590
+ const serverId = readSubscriptionId(value);
1591
+ subscription.serverId = serverId;
1592
+ handle.subscriptionId = serverId;
1593
+ this.activeSubscriptions.add(subscription);
1594
+ this.subscriptionsByServerId.set(serverId, subscription);
1595
+ });
1086
1596
  return handle;
1087
1597
  }
1088
1598
  async unsubscribe(subscription) {
@@ -1125,19 +1635,19 @@ var GdexStreamService = class {
1125
1635
  ...subscription.params,
1126
1636
  snapshot: true
1127
1637
  };
1128
- const result = await this.resubscribeWithRateLimitRetry(params);
1129
- if (!subscription.active) {
1130
- await this.request("gdex_unsubscribe", { subscriptionId: result.subscriptionId });
1131
- continue;
1132
- }
1133
- subscription.serverId = result.subscriptionId;
1134
- subscription.handle.subscriptionId = result.subscriptionId;
1135
- this.subscriptionsByServerId.set(result.subscriptionId, subscription);
1638
+ const result = await this.resubscribeWithRateLimitRetry(params, (value) => {
1639
+ const serverId = readSubscriptionId(value);
1640
+ if (!subscription.active) return;
1641
+ subscription.serverId = serverId;
1642
+ subscription.handle.subscriptionId = serverId;
1643
+ this.subscriptionsByServerId.set(serverId, subscription);
1644
+ });
1645
+ if (!subscription.active) await this.request("gdex_unsubscribe", { subscriptionId: result.subscriptionId });
1136
1646
  }
1137
1647
  }
1138
- async resubscribeWithRateLimitRetry(params) {
1648
+ async resubscribeWithRateLimitRetry(params, onResult) {
1139
1649
  for (let attempt = 0;; attempt++) try {
1140
- return await this.request("gdex_subscribe", params);
1650
+ return await this.send("gdex_subscribe", params, onResult);
1141
1651
  } catch (error) {
1142
1652
  if (!(error instanceof GdexStreamError) || error.code !== RATE_LIMITED || attempt >= MAX_RESUBSCRIBE_RATE_RETRIES) throw error;
1143
1653
  const retryAfterMs = this.readRetryAfterMs(error.data);
@@ -1181,28 +1691,35 @@ var GdexStreamService = class {
1181
1691
  //#endregion
1182
1692
  //#region src/version.ts
1183
1693
  /** Package version embedded by the bundler, with a source-test fallback. */
1184
- const SDK_VERSION = "1.1.0";
1694
+ const SDK_VERSION = "1.2.0-rc.1";
1185
1695
 
1186
1696
  //#endregion
1187
1697
  //#region src/classes/http_client.ts
1188
1698
  var HttpClient = class {
1189
1699
  httpRequestor;
1190
1700
  timeoutMs;
1191
- /** Create an HTTP client around fetch or an injected requestor. */
1192
- constructor(httpRequestor = fetch, timeoutMs = 3e4) {
1701
+ wire;
1702
+ /**
1703
+ * Create an HTTP client around fetch or an injected requestor. `wire` selects the query
1704
+ * encoding and the `User-Agent` (see {@link WireOptions}).
1705
+ */
1706
+ constructor(httpRequestor = fetch, timeoutMs = 3e4, wire = {}) {
1193
1707
  this.httpRequestor = httpRequestor;
1194
1708
  this.timeoutMs = timeoutMs;
1709
+ this.wire = wire;
1195
1710
  }
1196
1711
  async sendRequest(method, baseUrl, basePath, endpoint, body, options) {
1197
1712
  const url = `${baseUrl}${basePath}${endpoint}`;
1198
1713
  debugLog(`Sending request to ${url} with body:`, body);
1714
+ const hasBody = Boolean(body);
1199
1715
  const response = await requestWithTimeout(this.httpRequestor, url, {
1200
1716
  method,
1201
1717
  headers: {
1202
- "Content-Type": "application/json",
1203
- "User-Agent": `GalaChain-SDK/${SDK_VERSION}`
1718
+ ...hasBody ? { "Content-Type": "application/json" } : {},
1719
+ ...this.wire.userAgent === false ? {} : { "User-Agent": this.wire.userAgent ?? `GalaChain-SDK/${"1.2.0-rc.1"}` },
1720
+ ...this.wire.headers
1204
1721
  },
1205
- ...body ? { body: JSON.stringify(body) } : {},
1722
+ ...hasBody ? { body: JSON.stringify(body) } : {},
1206
1723
  ...(options === null || options === void 0 ? void 0 : options.signal) === void 0 ? {} : { signal: options.signal }
1207
1724
  }, this.timeoutMs);
1208
1725
  if (!response.ok) throw await GSwapSDKError.fromErrorResponse(url, response);
@@ -1216,12 +1733,65 @@ var HttpClient = class {
1216
1733
  }
1217
1734
  /** Send a GET request with URL-encoded query parameters and decode its response. */
1218
1735
  async sendGetRequest(baseUrl, basePath, endpoint, params, options) {
1219
- const searchParams = params ? new URLSearchParams(params) : void 0;
1220
- const endpointWithParams = searchParams ? `${endpoint}?${searchParams.toString()}` : endpoint;
1736
+ const endpointWithParams = params ? `${endpoint}?${buildQueryString(params, this.wire.queryEncoding)}` : endpoint;
1221
1737
  return this.sendRequest("GET", baseUrl, basePath, endpointWithParams, void 0, options);
1222
1738
  }
1223
1739
  };
1224
1740
 
1741
+ //#endregion
1742
+ //#region src/utils/lenient.ts
1743
+ /** A usable row. */
1744
+ function entryOk(value) {
1745
+ return {
1746
+ ok: true,
1747
+ value
1748
+ };
1749
+ }
1750
+ /** An unusable row, with the reason it is reported under. */
1751
+ function entryRejected(reason) {
1752
+ return {
1753
+ ok: false,
1754
+ reason
1755
+ };
1756
+ }
1757
+ /**
1758
+ * Reads a list answer row by row: a row that cannot be used is skipped and reported, instead of
1759
+ * rejecting the whole list because of one bad row. An answer that is not a list at all is still
1760
+ * `INVALID_CHAIN_RESPONSE`: nothing in it can be trusted.
1761
+ */
1762
+ function readEntries(source, data, parse, onInvalidEntry) {
1763
+ if (!Array.isArray(data)) throw new GSwapSDKError(`Backend returned an invalid ${source} list.`, "INVALID_CHAIN_RESPONSE", { data });
1764
+ const rows = [];
1765
+ data.forEach((entry, index) => {
1766
+ const parsed = parse(entry);
1767
+ if (parsed.ok) {
1768
+ rows.push(parsed.value);
1769
+ return;
1770
+ }
1771
+ try {
1772
+ onInvalidEntry === null || onInvalidEntry === void 0 || onInvalidEntry({
1773
+ source,
1774
+ index,
1775
+ entry,
1776
+ reason: parsed.reason
1777
+ });
1778
+ } catch {}
1779
+ });
1780
+ return rows;
1781
+ }
1782
+ /** A plain JSON object (not null, not an array). */
1783
+ function asEntryRecord(value) {
1784
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
1785
+ }
1786
+ /** A finite number, or a non-empty numeric string, as a number; otherwise `undefined`. */
1787
+ function finiteNumberOf(value) {
1788
+ if (typeof value === "number") return Number.isFinite(value) ? value : void 0;
1789
+ if (typeof value === "string" && value.trim() !== "") {
1790
+ const parsed = Number(value);
1791
+ return Number.isFinite(parsed) ? parsed : void 0;
1792
+ }
1793
+ }
1794
+
1225
1795
  //#endregion
1226
1796
  //#region src/utils/ordering.ts
1227
1797
  /** Return two trading symbols in the contract's plain-string order. */
@@ -1300,39 +1870,250 @@ function parseTokenClassKey(tokenClassKey) {
1300
1870
  };
1301
1871
  }
1302
1872
 
1873
+ //#endregion
1874
+ //#region src/classes/symbols.ts
1875
+ const SYMBOL_CACHE_TTL_MS = 6e4;
1876
+ /** Symbol registry client for the current GalaChainDex contract. */
1877
+ var Symbols = class {
1878
+ gateway;
1879
+ options;
1880
+ cachedSymbols;
1881
+ cachedAt = 0;
1882
+ refreshInFlight;
1883
+ http;
1884
+ /**
1885
+ * Create a symbol service backed by the swap backend. `onInvalidEntry` is told about every
1886
+ * registry row that was skipped as unusable (see {@link InvalidEntryHandler}).
1887
+ */
1888
+ constructor(gateway, options = {}) {
1889
+ this.gateway = gateway;
1890
+ this.options = options;
1891
+ this.http = new HttpClient(gateway.httpRequestor, gateway.requestTimeoutMs, gateway.wire);
1892
+ }
1893
+ /**
1894
+ * List all registered GalaChainDex trading symbols, cached for 60 seconds. A registry row that
1895
+ * is not a usable symbol is skipped (and reported to `onInvalidEntry`) instead of failing the
1896
+ * whole list.
1897
+ */
1898
+ async list() {
1899
+ if (this.cachedSymbols !== void 0 && Date.now() - this.cachedAt < SYMBOL_CACHE_TTL_MS) return this.cachedSymbols;
1900
+ if (this.refreshInFlight !== void 0) return this.refreshInFlight;
1901
+ this.refreshInFlight = this.http.sendGetRequest(this.gateway.dexBackendBaseUrl, "/v2/trade", "/symbols").then((response) => readEntries("symbols", response.data, parseTradingSymbol, this.options.onInvalidEntry)).then((symbols) => {
1902
+ this.cachedSymbols = symbols;
1903
+ this.cachedAt = Date.now();
1904
+ return symbols;
1905
+ }).finally(() => {
1906
+ this.refreshInFlight = void 0;
1907
+ });
1908
+ return this.refreshInFlight;
1909
+ }
1910
+ /** Invalidate the cached symbol registry after a write changes registration state.
1911
+ *
1912
+ * @example
1913
+ * ```ts
1914
+ * gSwap.symbols.invalidate();
1915
+ * ```
1916
+ */
1917
+ invalidate() {
1918
+ this.cachedSymbols = void 0;
1919
+ this.cachedAt = 0;
1920
+ }
1921
+ /** Force one registry refresh, bypassing the cache.
1922
+ *
1923
+ * @example
1924
+ * ```ts
1925
+ * const symbols = await gSwap.symbols.refresh();
1926
+ * ```
1927
+ */
1928
+ async refresh() {
1929
+ this.invalidate();
1930
+ this.refreshInFlight = void 0;
1931
+ return this.list();
1932
+ }
1933
+ /** Resolve a symbol or token class key to its registered symbol metadata. */
1934
+ async resolve(ref) {
1935
+ let symbols = await this.list();
1936
+ const composite = typeof ref === "string" ? isCompositeKey(ref) ? compositeKeyOf(parseTokenClassKey(ref)) : void 0 : compositeKeyOf(ref);
1937
+ const resolved = symbols.find((entry) => entry.symbol === ref || composite !== void 0 && compositeKeyOf(entry) === composite);
1938
+ if (resolved === void 0) {
1939
+ symbols = await this.refresh();
1940
+ const refreshed = symbols.find((entry) => entry.symbol === ref || composite !== void 0 && compositeKeyOf(entry) === composite);
1941
+ if (refreshed === void 0) throw GSwapSDKError.unknownTokenError(ref);
1942
+ return refreshed;
1943
+ }
1944
+ return resolved;
1945
+ }
1946
+ /**
1947
+ * The trading symbol to put in a token's first CreatePool.
1948
+ *
1949
+ * 1. The symbol ALREADY registered for exactly this class key, if any: proposing another one
1950
+ * fails the gateway's registry-conflict check.
1951
+ * 2. Otherwise `displaySymbol` (the token's curated symbol), when it is proposable
1952
+ * ({@link isProposableTradingSymbol}).
1953
+ * 3. Otherwise a `VALIDATION_ERROR`: a symbol is never derived from the key (BNB's collection is
1954
+ * `GBNB`, a launchpad token's is the reserved word `Token`).
1955
+ *
1956
+ * `registryFailure: 'ignore'` treats an unreachable registry as an empty one and falls through
1957
+ * to step 2 (the gateway still rejects a conflicting symbol); the default `'throw'` propagates
1958
+ * the failure.
1959
+ *
1960
+ * @example
1961
+ * ```ts
1962
+ * const symbol = await gSwap.symbols.proposeSymbol(
1963
+ * { collection: 'GALA_TEST1', category: 'Unit', type: 'none', additionalKey: 'none' },
1964
+ * 'GALATEST',
1965
+ * );
1966
+ * ```
1967
+ */
1968
+ async proposeSymbol(classKey, displaySymbol, options = {}) {
1969
+ let registry = [];
1970
+ try {
1971
+ registry = await this.list();
1972
+ } catch (error) {
1973
+ if (options.registryFailure !== "ignore") throw error;
1974
+ }
1975
+ const wanted = compositeKeyOf(classKey);
1976
+ const registered = registry.find((entry) => entry.collection === classKey.collection && entry.category === classKey.category && entry.type === classKey.type && entry.additionalKey === classKey.additionalKey);
1977
+ if (registered !== void 0) return registered.symbol;
1978
+ if (isProposableTradingSymbol(displaySymbol)) return displaySymbol;
1979
+ throw new GSwapSDKError(`No valid trading symbol for token class ${wanted}: "${displaySymbol}" is not an acceptable symbol and none is registered`, "VALIDATION_ERROR", {
1980
+ classKey,
1981
+ displaySymbol
1982
+ });
1983
+ }
1984
+ /** Resolve and put two token references in canonical trading-symbol order. */
1985
+ async orderPair(a, b) {
1986
+ const [resolvedA, resolvedB] = await Promise.all([this.resolve(a), this.resolve(b)]);
1987
+ const [token0Symbol, token1Symbol] = orderSymbols(resolvedA.symbol, resolvedB.symbol);
1988
+ return {
1989
+ token0: token0Symbol === resolvedA.symbol ? resolvedA : resolvedB,
1990
+ token1: token1Symbol === resolvedB.symbol ? resolvedB : resolvedA,
1991
+ flipped: token0Symbol !== resolvedA.symbol
1992
+ };
1993
+ }
1994
+ };
1995
+ /** Reads one registry row: all four class-key parts, a symbol and non-negative integer decimals. */
1996
+ function parseTradingSymbol(value) {
1997
+ const entry = asEntryRecord(value);
1998
+ if (entry === void 0) return entryRejected("the row is not an object");
1999
+ const { symbol, collection, category, type, additionalKey, decimals } = entry;
2000
+ if (typeof symbol !== "string") return entryRejected("symbol is not a string");
2001
+ if (symbol.length === 0) return entryRejected("symbol is empty");
2002
+ if (typeof collection !== "string") return entryRejected("collection is not a string");
2003
+ if (typeof category !== "string") return entryRejected("category is not a string");
2004
+ if (typeof type !== "string") return entryRejected("type is not a string");
2005
+ if (typeof additionalKey !== "string") return entryRejected("additionalKey is not a string");
2006
+ if (typeof decimals !== "number" || !Number.isInteger(decimals) || decimals < 0) return entryRejected("decimals is not a non-negative integer");
2007
+ return entryOk({
2008
+ symbol,
2009
+ collection,
2010
+ category,
2011
+ type,
2012
+ additionalKey,
2013
+ decimals
2014
+ });
2015
+ }
2016
+ function isCompositeKey(ref) {
2017
+ return ref.includes("|") || ref.includes("$");
2018
+ }
2019
+ /** A token reference as the caller wrote it: a string verbatim, a class key as its `$` composite. */
2020
+ function rawTokenOf(ref) {
2021
+ return typeof ref === "string" ? ref : compositeKeyOf(ref);
2022
+ }
2023
+ /** The trading symbol of a reference, or `SYMBOL_NOT_FOUND` when the resolver has none. */
2024
+ async function tradingSymbolOf(resolver, ref) {
2025
+ const resolved = await resolver.resolve(ref);
2026
+ if (resolved.symbol.length > 0) return resolved.symbol;
2027
+ throw new GSwapSDKError("Token could not be resolved to a trading symbol.", "SYMBOL_NOT_FOUND", { token: ref });
2028
+ }
2029
+ /** What a read request names a token by: the reference itself in pass-through mode, else its symbol. */
2030
+ async function queryTokenOf(resolver, ref) {
2031
+ return resolver.passthrough === true ? rawTokenOf(ref) : tradingSymbolOf(resolver, ref);
2032
+ }
2033
+ /**
2034
+ * The offline resolver for apps that already hold the backend's canonical trading symbols (from
2035
+ * `/quote`, `/add-liq-estimate`, a position row) and must not make a registry request of their own.
2036
+ *
2037
+ * - `resolve` accepts a bare trading symbol and returns it as is; a class key (object, `$` or `|`
2038
+ * form) is not a symbol and is refused as `UNKNOWN_TOKEN`. `createPool` relies on that refusal to
2039
+ * fall back to the symbols its caller supplies.
2040
+ * - `orderPair` orders two symbols by plain string comparison, as the contract does.
2041
+ * - Reads are pass-through (see {@link TokenResolver.passthrough}): the caller's references go on
2042
+ * the wire verbatim, composite keys included, and the backend orients the pair.
2043
+ *
2044
+ * @example
2045
+ * ```ts
2046
+ * const swaps = new Swaps(gateway, new CanonicalSymbols(), signer, walletAddress);
2047
+ * await swaps.swap('GALA', 'GUSDC', 3000, { exactIn: '10' });
2048
+ * ```
2049
+ */
2050
+ var CanonicalSymbols = class {
2051
+ passthrough = true;
2052
+ /** Resolve a bare trading symbol to itself. */
2053
+ resolve(ref) {
2054
+ if (typeof ref === "string" && !isCompositeKey(ref)) return Promise.resolve({
2055
+ symbol: ref,
2056
+ collection: "",
2057
+ category: "",
2058
+ type: "",
2059
+ additionalKey: "",
2060
+ decimals: 0
2061
+ });
2062
+ return Promise.reject(GSwapSDKError.unknownTokenError(ref));
2063
+ }
2064
+ /** Put two symbols in canonical (string) order. */
2065
+ async orderPair(a, b) {
2066
+ const [resolvedA, resolvedB] = await Promise.all([this.resolve(a), this.resolve(b)]);
2067
+ const [first] = orderSymbols(resolvedA.symbol, resolvedB.symbol);
2068
+ const flipped = first !== resolvedA.symbol;
2069
+ return {
2070
+ token0: flipped ? resolvedB : resolvedA,
2071
+ token1: flipped ? resolvedA : resolvedB,
2072
+ flipped
2073
+ };
2074
+ }
2075
+ /** There is no registry state to drop. */
2076
+ invalidate() {}
2077
+ };
2078
+
1303
2079
  //#endregion
1304
2080
  //#region src/classes/pools.ts
1305
2081
  /** Read-only pool and current-price access for the current GalaChainDex contract. */
1306
2082
  var Pools = class {
1307
2083
  gateway;
1308
2084
  symbols;
2085
+ options;
1309
2086
  /**
1310
- * Creates a pool service.
2087
+ * Creates a pool service. `options.onInvalidEntry` is told about every pool row that was
2088
+ * skipped as unusable (see {@link InvalidEntryHandler}).
1311
2089
  *
1312
2090
  * @example
1313
2091
  * ```ts
1314
2092
  * const pools = new Pools(gateway, symbols);
1315
2093
  * ```
1316
2094
  */
1317
- constructor(gateway, symbols) {
2095
+ constructor(gateway, symbols, options = {}) {
1318
2096
  this.gateway = gateway;
1319
2097
  this.symbols = symbols;
1320
- this.http = new HttpClient(gateway.httpRequestor, gateway.requestTimeoutMs ?? 3e4);
2098
+ this.options = options;
2099
+ this.http = new HttpClient(gateway.httpRequestor, gateway.requestTimeoutMs ?? 3e4, gateway.wire);
1321
2100
  }
1322
2101
  http;
1323
2102
  /**
1324
- * Fetches every current-contract pool from the swap backend.
2103
+ * Fetches current-contract pools from the swap backend, optionally searched, sorted and paged
2104
+ * by the backend. A row that is not a usable pool is skipped and reported to `onInvalidEntry`
2105
+ * instead of failing the whole list; an answer that is not a list at all is
2106
+ * `INVALID_CHAIN_RESPONSE`.
1325
2107
  *
1326
2108
  * @example
1327
2109
  * ```ts
1328
- * const pools = await service.getPools();
1329
- * console.log(pools.length);
2110
+ * const top = await service.getPools({ sortBy: 'tvl', sortOrder: 'desc', page: 1, limit: 8 });
2111
+ * console.log(top.length);
1330
2112
  * ```
1331
2113
  */
1332
2114
  async getPools(options) {
1333
- const response = await this.http.sendGetRequest(this.gateway.dexBackendBaseUrl, "/v2/trade", "/pools", void 0, (options === null || options === void 0 ? void 0 : options.signal) === void 0 ? void 0 : { signal: options.signal });
1334
- if (!Array.isArray(response.data) || !response.data.every(isPoolListInfo)) throw new GSwapSDKError("Backend returned an invalid pool list.", "INVALID_CHAIN_RESPONSE", { data: response.data });
1335
- return response.data;
2115
+ const response = await this.http.sendGetRequest(this.gateway.dexBackendBaseUrl, "/v2/trade", "/pools", poolListParams(options), (options === null || options === void 0 ? void 0 : options.signal) === void 0 ? void 0 : { signal: options.signal });
2116
+ return readEntries("pools", response.data, parsePoolListInfo, (options === null || options === void 0 ? void 0 : options.onInvalidEntry) ?? this.options.onInvalidEntry);
1336
2117
  }
1337
2118
  /**
1338
2119
  * Fetches one pool from the backend, preserving whether the request order was flipped.
@@ -1371,8 +2152,13 @@ var Pools = class {
1371
2152
  */
1372
2153
  async getCompositePool(token0, token1, fee) {
1373
2154
  validateFee(fee);
1374
- const first = await resolveSymbol$2(this.symbols, token0);
1375
- const second = await resolveSymbol$2(this.symbols, token1);
2155
+ if (this.symbols.passthrough === true) return this.getBackend("/composite-pool", {
2156
+ token0: rawTokenOf(token0),
2157
+ token1: rawTokenOf(token1),
2158
+ fee: String(fee)
2159
+ });
2160
+ const first = await tradingSymbolOf(this.symbols, token0);
2161
+ const second = await tradingSymbolOf(this.symbols, token1);
1376
2162
  const ordered = readOrderedSymbols(orderSymbols(first, second));
1377
2163
  return this.getBackend("/composite-pool", {
1378
2164
  token0: ordered.token0,
@@ -1382,8 +2168,8 @@ var Pools = class {
1382
2168
  }
1383
2169
  async backendParams(token0, token1, fee) {
1384
2170
  return {
1385
- token0: await resolveSymbol$2(this.symbols, token0),
1386
- token1: await resolveSymbol$2(this.symbols, token1),
2171
+ token0: await queryTokenOf(this.symbols, token0),
2172
+ token1: await queryTokenOf(this.symbols, token1),
1387
2173
  fee: String(fee)
1388
2174
  };
1389
2175
  }
@@ -1395,53 +2181,449 @@ var Pools = class {
1395
2181
  throw new GSwapSDKError("Pool request failed.", "HTTP_ERROR", { cause: error });
1396
2182
  }
1397
2183
  }
1398
- };
1399
- async function resolveSymbol$2(symbols, token) {
1400
- const resolved = await symbols.resolve(token);
1401
- if (resolved.symbol.length > 0) return resolved.symbol;
1402
- throw new GSwapSDKError("Token could not be resolved to a trading symbol.", "SYMBOL_NOT_FOUND", { token });
2184
+ };
2185
+ const SORT_KEYS = [
2186
+ "tvl",
2187
+ "volume1d",
2188
+ "volume30d"
2189
+ ];
2190
+ const MAX_SEARCH_LENGTH = 64;
2191
+ const MAX_PAGE_SIZE = 1e3;
2192
+ /** The pool-list query, in the order the apps write it: search, sortBy, sortOrder, page, limit. */
2193
+ function poolListParams(options) {
2194
+ if (options === void 0) return void 0;
2195
+ const params = {};
2196
+ if (options.search !== void 0) {
2197
+ if (options.search.length > MAX_SEARCH_LENGTH) throw new GSwapSDKError(`search must be at most ${MAX_SEARCH_LENGTH} characters.`, "VALIDATION_ERROR", { search: options.search });
2198
+ params["search"] = options.search;
2199
+ }
2200
+ if (options.sortBy !== void 0) {
2201
+ if (!SORT_KEYS.includes(options.sortBy)) throw new GSwapSDKError(`sortBy must be one of ${SORT_KEYS.join(", ")}.`, "VALIDATION_ERROR", { sortBy: options.sortBy });
2202
+ params["sortBy"] = options.sortBy;
2203
+ }
2204
+ if (options.sortOrder !== void 0) {
2205
+ if (options.sortOrder !== "asc" && options.sortOrder !== "desc") throw new GSwapSDKError("sortOrder must be asc or desc.", "VALIDATION_ERROR", { sortOrder: options.sortOrder });
2206
+ params["sortOrder"] = options.sortOrder;
2207
+ }
2208
+ if (options.page !== void 0) {
2209
+ if (!Number.isInteger(options.page) || options.page < 1) throw new GSwapSDKError("page must be an integer of at least 1.", "VALIDATION_ERROR", { page: options.page });
2210
+ params["page"] = String(options.page);
2211
+ }
2212
+ if (options.limit !== void 0) {
2213
+ if (!Number.isInteger(options.limit) || options.limit < 1 || options.limit > MAX_PAGE_SIZE) throw new GSwapSDKError(`limit must be an integer from 1 to ${MAX_PAGE_SIZE}.`, "VALIDATION_ERROR", { limit: options.limit });
2214
+ params["limit"] = String(options.limit);
2215
+ }
2216
+ return Object.keys(params).length === 0 ? void 0 : params;
2217
+ }
2218
+ const OPTIONAL_POOL_STRINGS = [
2219
+ "poolName",
2220
+ "token0CompositeKey",
2221
+ "token1CompositeKey",
2222
+ "token0Image",
2223
+ "token1Image",
2224
+ "creator",
2225
+ "price",
2226
+ "sqrtPrice",
2227
+ "token0Tvl",
2228
+ "token1Tvl"
2229
+ ];
2230
+ const OPTIONAL_POOL_NUMBERS = [
2231
+ "tickSpacing",
2232
+ "protocolFees",
2233
+ "tradingFees",
2234
+ "tick",
2235
+ "volume1d",
2236
+ "volume7d",
2237
+ "volume30d",
2238
+ "trades1d",
2239
+ "fee24h",
2240
+ "token0Price",
2241
+ "token1Price"
2242
+ ];
2243
+ /** Fields the apps accept as a number or a numeric string (the wallet does `Number(row.x)`). */
2244
+ const NUMERIC_POOL_FIELDS = [
2245
+ "fee",
2246
+ "tvlUsd",
2247
+ "apr1d"
2248
+ ];
2249
+ /**
2250
+ * Reads one pool-list row the way the apps do: the identity (`token0`, `token1`, `poolRef`) and
2251
+ * `fee` must be usable, every other field is optional but, when present, must have its type.
2252
+ * `fee`, `tvlUsd` and `apr1d` may arrive as numeric strings and are returned as numbers. Fields
2253
+ * the SDK does not know are kept.
2254
+ */
2255
+ function parsePoolListInfo(entry) {
2256
+ const row = asEntryRecord(entry);
2257
+ if (row === void 0) return entryRejected("the row is not an object");
2258
+ for (const key of [
2259
+ "token0",
2260
+ "token1",
2261
+ "poolRef"
2262
+ ]) if (typeof row[key] !== "string") return entryRejected(`${key} is not a string`);
2263
+ if (row["contractVersion"] !== void 0 && row["contractVersion"] !== "v2") return entryRejected("contractVersion is not v2");
2264
+ const normalized = { ...row };
2265
+ for (const key of NUMERIC_POOL_FIELDS) {
2266
+ const raw = row[key];
2267
+ if (raw === void 0 && key !== "fee") continue;
2268
+ const value = finiteNumberOf(raw);
2269
+ if (value === void 0) return entryRejected(`${key} is not a number`);
2270
+ normalized[key] = value;
2271
+ }
2272
+ for (const key of OPTIONAL_POOL_STRINGS) if (row[key] !== void 0 && typeof row[key] !== "string") return entryRejected(`${key} is not a string`);
2273
+ for (const key of OPTIONAL_POOL_NUMBERS) {
2274
+ const value = row[key];
2275
+ if (value !== void 0 && (typeof value !== "number" || !Number.isFinite(value))) return entryRejected(`${key} is not a number`);
2276
+ }
2277
+ return entryOk(normalized);
2278
+ }
2279
+
2280
+ //#endregion
2281
+ //#region src/utils/unique_key.ts
2282
+ /**
2283
+ * The `uniqueKey` prefix frontend_v2 and wallet_extension have always sent
2284
+ * (`galaswap-operation-<uuid>`). defi-backend does not depend on it: the chain-write verifier
2285
+ * only requires a non-empty key of at most 256 characters, and apply-results accepts
2286
+ * `[A-Za-z0-9._:-]{1,128}`; the only code that mints a prefixed key itself is the server-side v1
2287
+ * trade builder, which nothing reads back by prefix.
2288
+ */
2289
+ const DEFAULT_UNIQUE_KEY_PREFIX = "galaswap-operation-";
2290
+ /** A canonical UUID is 36 characters; the apply-results key limit is 128. */
2291
+ const MAX_UNIQUE_KEY_PREFIX_LENGTH = 92;
2292
+ const UNIQUE_KEY_PREFIX_PATTERN = /^[A-Za-z0-9._:-]*$/u;
2293
+ /**
2294
+ * Validates a caller-supplied `uniqueKey` prefix. The whole key (`<prefix><uuid>`) must stay a
2295
+ * valid apply-results key, otherwise `confirm()` could never read the outcome of the write.
2296
+ *
2297
+ * @throws GSwapSDKError VALIDATION_ERROR when the prefix has characters outside `A-Za-z0-9._:-` or
2298
+ * is longer than 92 characters.
2299
+ */
2300
+ function resolveUniqueKeyPrefix(prefix) {
2301
+ if (prefix === void 0) return DEFAULT_UNIQUE_KEY_PREFIX;
2302
+ if (!UNIQUE_KEY_PREFIX_PATTERN.test(prefix) || prefix.length > MAX_UNIQUE_KEY_PREFIX_LENGTH) throw new GSwapSDKError(`uniqueKeyPrefix must be at most ${MAX_UNIQUE_KEY_PREFIX_LENGTH} characters of A-Z, a-z, 0-9, ".", "_", ":" or "-".`, "VALIDATION_ERROR", { uniqueKeyPrefix: prefix });
2303
+ return prefix;
2304
+ }
2305
+ /** The swap backend's apply-results key constraint (`apply-results.dto.ts`). */
2306
+ const UNIQUE_KEY_PATTERN = /^[A-Za-z0-9._:-]{1,128}$/u;
2307
+ /**
2308
+ * Validates a caller-supplied write `uniqueKey`: 1 to 128 characters of `A-Za-z0-9._:-`, the
2309
+ * shape the apply-results route accepts, so the write's outcome can always be read back with
2310
+ * `confirm()`. A key is one attempt's identity: reuse it only to retry that same attempt.
2311
+ *
2312
+ * @throws GSwapSDKError VALIDATION_ERROR otherwise.
2313
+ */
2314
+ function assertUniqueKey(uniqueKey) {
2315
+ if (typeof uniqueKey !== "string" || !UNIQUE_KEY_PATTERN.test(uniqueKey)) throw new GSwapSDKError("uniqueKey must be 1-128 characters of A-Z, a-z, 0-9, \".\", \"_\", \":\" or \"-\".", "VALIDATION_ERROR", { uniqueKey });
2316
+ }
2317
+ /** A fresh per-attempt key: `<prefix><random UUID>`. */
2318
+ function createUniqueKey(prefix) {
2319
+ return `${prefix}${globalThis.crypto.randomUUID()}`;
2320
+ }
2321
+
2322
+ //#endregion
2323
+ //#region src/utils/dto_builders.ts
2324
+ const decimalString = (amount) => new BigNumber(amount).toFixed();
2325
+ /**
2326
+ * Builds the RequestTrade DTO: `exactIn` sells that much of the input token (`sell0Qty` or
2327
+ * `sell1Qty`), `exactOut` buys that much of the output token (`buy1Qty` or `buy0Qty`), plus the
2328
+ * side's slippage bound and an optional `priceLimit`. Key order: `token0, token1, fee, uniqueKey,
2329
+ * <quantity>, amountOutMinimum | amountInMaximum, priceLimit`.
2330
+ *
2331
+ * @example
2332
+ * ```ts
2333
+ * const dto = buildRequestTradeDto({
2334
+ * token0: quote.token0Symbol, token1: quote.token1Symbol,
2335
+ * tokenInIsToken0: quote.tokenInIsToken0, fee: quote.fee,
2336
+ * uniqueKey: createUniqueKey('galaswap-operation-'),
2337
+ * exactIn: '100', amountOutMinimum: '14',
2338
+ * });
2339
+ * ```
2340
+ */
2341
+ function buildRequestTradeDto(input) {
2342
+ validateFee(input.fee);
2343
+ assertCanonicalPair(input.token0, input.token1);
2344
+ assertUniqueKey(input.uniqueKey);
2345
+ const dto = {
2346
+ token0: input.token0,
2347
+ token1: input.token1,
2348
+ fee: input.fee,
2349
+ uniqueKey: input.uniqueKey
2350
+ };
2351
+ if ("exactIn" in input) {
2352
+ const exactIn = input.exactIn;
2353
+ if (exactIn === void 0) throw new GSwapSDKError("exactIn is required for an exact-input swap.", "VALIDATION_ERROR");
2354
+ validateNumericAmount(exactIn, "exactIn");
2355
+ dto[input.tokenInIsToken0 ? "sell0Qty" : "sell1Qty"] = decimalString(exactIn);
2356
+ if (input.amountOutMinimum !== void 0) {
2357
+ validateNumericAmount(input.amountOutMinimum, "amountOutMinimum", true);
2358
+ dto["amountOutMinimum"] = decimalString(input.amountOutMinimum);
2359
+ }
2360
+ } else {
2361
+ const exactOut = input.exactOut;
2362
+ if (exactOut === void 0) throw new GSwapSDKError("exactOut is required for an exact-output swap.", "VALIDATION_ERROR");
2363
+ validateNumericAmount(exactOut, "exactOut");
2364
+ dto[input.tokenInIsToken0 ? "buy1Qty" : "buy0Qty"] = decimalString(exactOut);
2365
+ if (input.amountInMaximum !== void 0) {
2366
+ validateNumericAmount(input.amountInMaximum, "amountInMaximum", true);
2367
+ dto["amountInMaximum"] = decimalString(input.amountInMaximum);
2368
+ }
2369
+ }
2370
+ if (input.priceLimit !== void 0) {
2371
+ validateNumericAmount(input.priceLimit, "priceLimit");
2372
+ dto["priceLimit"] = decimalString(input.priceLimit);
2373
+ }
2374
+ return dto;
2375
+ }
2376
+ function assertPoolPosition(input) {
2377
+ validateFee(input.fee);
2378
+ assertCanonicalPair(input.token0, input.token1);
2379
+ assertTickRange(input.tickLower, input.tickUpper, input.fee);
2380
+ assertUniqueKey(input.uniqueKey);
2381
+ }
2382
+ /**
2383
+ * Builds the AddLiquidity DTO: exactly one of `depositQuantityToken0` / `depositQuantityToken1`
2384
+ * (the other side is derived on chain). Key order: `token0, token1, fee, tickLower, tickUpper,
2385
+ * uniqueKey, <deposit>`.
2386
+ */
2387
+ function buildAddLiquidityDto(input) {
2388
+ assertPoolPosition(input);
2389
+ const side = onlyOne(input.depositQuantityToken0, input.depositQuantityToken1, "depositQuantityToken0", "depositQuantityToken1");
2390
+ if (side === void 0) throw new GSwapSDKError("Provide exactly one of depositQuantityToken0 or depositQuantityToken1.", "VALIDATION_ERROR");
2391
+ validateNumericAmount(side.amount, side.name);
2392
+ return {
2393
+ token0: input.token0,
2394
+ token1: input.token1,
2395
+ fee: input.fee,
2396
+ tickLower: input.tickLower,
2397
+ tickUpper: input.tickUpper,
2398
+ uniqueKey: input.uniqueKey,
2399
+ [side.name]: decimalString(side.amount)
2400
+ };
2401
+ }
2402
+ /**
2403
+ * Builds the RemoveLiquidity DTO: at most one of `withdrawalQuantityToken0` /
2404
+ * `withdrawalQuantityToken1`; omitting both closes the position and sweeps its fees.
2405
+ */
2406
+ function buildRemoveLiquidityDto(input) {
2407
+ assertPoolPosition(input);
2408
+ const side = onlyOne(input.withdrawalQuantityToken0, input.withdrawalQuantityToken1, "withdrawalQuantityToken0", "withdrawalQuantityToken1", true);
2409
+ if (side !== void 0) validateNumericAmount(side.amount, side.name);
2410
+ return {
2411
+ token0: input.token0,
2412
+ token1: input.token1,
2413
+ fee: input.fee,
2414
+ tickLower: input.tickLower,
2415
+ tickUpper: input.tickUpper,
2416
+ uniqueKey: input.uniqueKey,
2417
+ ...side === void 0 ? {} : { [side.name]: decimalString(side.amount) }
2418
+ };
2419
+ }
2420
+ /** Builds the CollectPositionFees DTO (the contract sweeps all of a position's fees). */
2421
+ function buildCollectPositionFeesDto(input) {
2422
+ assertPoolPosition(input);
2423
+ return {
2424
+ token0: input.token0,
2425
+ token1: input.token1,
2426
+ fee: input.fee,
2427
+ tickLower: input.tickLower,
2428
+ tickUpper: input.tickUpper,
2429
+ uniqueKey: input.uniqueKey
2430
+ };
2431
+ }
2432
+ /**
2433
+ * Builds the CreatePool DTO. Key order: `token0Key, token1Key, fee, startingPrice |
2434
+ * startingSqrtPrice, token0Symbol, token1Symbol, uniqueKey, name, isPrivate, privateAccess`.
2435
+ * Prices are those of the canonical pair (token1 per token0); a price quoted the other way round
2436
+ * is inverted by the caller before it gets here.
2437
+ */
2438
+ function buildCreatePoolDto(input) {
2439
+ validateFee(input.fee);
2440
+ assertUniqueKey(input.uniqueKey);
2441
+ assertCanonicalPair(input.token0Symbol, input.token1Symbol);
2442
+ for (const symbol of [input.token0Symbol, input.token1Symbol]) if (!isProposableTradingSymbol(symbol)) throw new GSwapSDKError("Invalid trading symbol: must be 1-32 ASCII letters and digits and not a reserved word (Token, Unit, none).", "VALIDATION_ERROR", { symbol });
2443
+ for (const key of [input.token0Key, input.token1Key]) assertClassKey(key);
2444
+ const price = onlyOne(input.startingPrice, input.startingSqrtPrice, "startingPrice", "startingSqrtPrice");
2445
+ if (price === void 0) throw new GSwapSDKError("Provide exactly one of startingPrice or startingSqrtPrice.", "VALIDATION_ERROR");
2446
+ if (typeof price.amount === "number") throw new GSwapSDKError(`Invalid ${price.name}: use a decimal string or BigNumber, not a JavaScript number`, "VALIDATION_ERROR");
2447
+ const parsed = new BigNumber(price.amount);
2448
+ if (!parsed.isFinite() || parsed.isLessThanOrEqualTo(0)) throw new GSwapSDKError("Starting price must be finite and positive.", "VALIDATION_ERROR");
2449
+ return {
2450
+ token0Key: input.token0Key,
2451
+ token1Key: input.token1Key,
2452
+ fee: input.fee,
2453
+ [price.name]: parsed.toFixed(),
2454
+ token0Symbol: input.token0Symbol,
2455
+ token1Symbol: input.token1Symbol,
2456
+ uniqueKey: input.uniqueKey,
2457
+ ...input.name === void 0 || input.name === "" ? {} : { name: input.name },
2458
+ ...input.isPrivate === void 0 ? {} : { isPrivate: input.isPrivate },
2459
+ ...input.privateAccess === void 0 ? {} : { privateAccess: input.privateAccess }
2460
+ };
2461
+ }
2462
+ function assertClassKey(key) {
2463
+ for (const part of [
2464
+ "collection",
2465
+ "category",
2466
+ "type",
2467
+ "additionalKey"
2468
+ ]) if (typeof key[part] !== "string" || key[part].length === 0) throw new GSwapSDKError(`Token class key is missing ${part}.`, "VALIDATION_ERROR", { key });
2469
+ }
2470
+ /**
2471
+ * Of two mutually exclusive fields, the one that is set (`undefined` when neither is);
2472
+ * both set is a `VALIDATION_ERROR`, and so is neither unless `allowNeither`.
2473
+ */
2474
+ function onlyOne(first, second, firstName, secondName, allowNeither = false) {
2475
+ if (first !== void 0 && second !== void 0) throw new GSwapSDKError(allowNeither ? `Provide at most one of ${firstName} or ${secondName}.` : `Provide exactly one of ${firstName} or ${secondName}.`, "VALIDATION_ERROR");
2476
+ if (first !== void 0) return {
2477
+ name: firstName,
2478
+ amount: first
2479
+ };
2480
+ if (second !== void 0) return {
2481
+ name: secondName,
2482
+ amount: second
2483
+ };
2484
+ }
2485
+ function invalidDto(method, field, expected) {
2486
+ return new GSwapSDKError(`${method} DTO field ${field} must be ${expected}.`, "VALIDATION_ERROR", {
2487
+ type: "INVALID_DTO",
2488
+ method,
2489
+ field
2490
+ });
2491
+ }
2492
+ /**
2493
+ * Rebuilds a DTO from its own fields with the builder of its method: the canonical form of the
2494
+ * DTO, with the same validation. Key order and decimal text are the builder's.
2495
+ */
2496
+ function rebuildV2Dto(method, dto) {
2497
+ const text = (field) => {
2498
+ const value = dto[field];
2499
+ if (typeof value !== "string") throw invalidDto(method, field, "a string");
2500
+ return value;
2501
+ };
2502
+ const integer = (field) => {
2503
+ const value = dto[field];
2504
+ if (typeof value !== "number") throw invalidDto(method, field, "a number");
2505
+ return value;
2506
+ };
2507
+ const optionalText = (field) => dto[field] === void 0 ? void 0 : text(field);
2508
+ const classKey = (field) => {
2509
+ const value = dto[field];
2510
+ if (typeof value !== "object" || value === null) throw invalidDto(method, field, "a class key");
2511
+ const key = value;
2512
+ const part = (name) => {
2513
+ if (typeof key[name] !== "string") throw invalidDto(method, `${field}.${name}`, "a string");
2514
+ return key[name];
2515
+ };
2516
+ return {
2517
+ collection: part("collection"),
2518
+ category: part("category"),
2519
+ type: part("type"),
2520
+ additionalKey: part("additionalKey")
2521
+ };
2522
+ };
2523
+ const base = () => ({
2524
+ token0: text("token0"),
2525
+ token1: text("token1"),
2526
+ fee: integer("fee")
2527
+ });
2528
+ const uniqueKey = text("uniqueKey");
2529
+ const position = () => ({
2530
+ ...base(),
2531
+ uniqueKey,
2532
+ tickLower: integer("tickLower"),
2533
+ tickUpper: integer("tickUpper")
2534
+ });
2535
+ switch (method) {
2536
+ case "RequestTrade": {
2537
+ const qty = [
2538
+ "sell0Qty",
2539
+ "sell1Qty",
2540
+ "buy0Qty",
2541
+ "buy1Qty"
2542
+ ].filter((f) => dto[f] !== void 0);
2543
+ const [field] = qty;
2544
+ if (qty.length !== 1 || field === void 0) throw invalidDto(method, "sell0Qty|sell1Qty|buy0Qty|buy1Qty", "present exactly once");
2545
+ const tokenInIsToken0 = field === "sell0Qty" || field === "buy1Qty";
2546
+ const shared = {
2547
+ ...base(),
2548
+ uniqueKey,
2549
+ tokenInIsToken0
2550
+ };
2551
+ const priceLimit = optionalText("priceLimit");
2552
+ return field.startsWith("sell") ? buildRequestTradeDto({
2553
+ ...shared,
2554
+ exactIn: text(field),
2555
+ amountOutMinimum: optionalText("amountOutMinimum"),
2556
+ priceLimit
2557
+ }) : buildRequestTradeDto({
2558
+ ...shared,
2559
+ exactOut: text(field),
2560
+ amountInMaximum: optionalText("amountInMaximum"),
2561
+ priceLimit
2562
+ });
2563
+ }
2564
+ case "AddLiquidity": {
2565
+ const token0Side = optionalText("depositQuantityToken0");
2566
+ const token1Side = optionalText("depositQuantityToken1");
2567
+ return buildAddLiquidityDto({
2568
+ ...position(),
2569
+ ...token0Side === void 0 ? { depositQuantityToken1: token1Side } : { depositQuantityToken0: token0Side }
2570
+ });
2571
+ }
2572
+ case "RemoveLiquidity": return buildRemoveLiquidityDto({
2573
+ ...position(),
2574
+ withdrawalQuantityToken0: optionalText("withdrawalQuantityToken0"),
2575
+ withdrawalQuantityToken1: optionalText("withdrawalQuantityToken1")
2576
+ });
2577
+ case "CollectPositionFees": return buildCollectPositionFeesDto(position());
2578
+ case "CreatePool": {
2579
+ const price = optionalText("startingPrice");
2580
+ const sqrtPrice = optionalText("startingSqrtPrice");
2581
+ const privateAccess = dto["privateAccess"];
2582
+ if (privateAccess !== void 0 && (!Array.isArray(privateAccess) || privateAccess.some((entry) => typeof entry !== "string"))) throw invalidDto(method, "privateAccess", "an array of strings");
2583
+ if (dto["isPrivate"] !== void 0 && typeof dto["isPrivate"] !== "boolean") throw invalidDto(method, "isPrivate", "a boolean");
2584
+ return buildCreatePoolDto({
2585
+ token0Key: classKey("token0Key"),
2586
+ token1Key: classKey("token1Key"),
2587
+ token0Symbol: text("token0Symbol"),
2588
+ token1Symbol: text("token1Symbol"),
2589
+ fee: integer("fee"),
2590
+ uniqueKey,
2591
+ name: optionalText("name"),
2592
+ isPrivate: dto["isPrivate"],
2593
+ privateAccess,
2594
+ ...price === void 0 ? { startingSqrtPrice: sqrtPrice } : { startingPrice: price }
2595
+ });
2596
+ }
2597
+ }
1403
2598
  }
1404
- function isPoolListInfo(value) {
1405
- if (typeof value !== "object" || value === null) return false;
1406
- const row = value;
1407
- return row["contractVersion"] === "v2" && typeof row["token0"] === "string" && typeof row["token1"] === "string" && typeof row["poolName"] === "string" && typeof row["poolRef"] === "string" && [
1408
- "fee",
1409
- "tickSpacing",
1410
- "protocolFees",
1411
- "tradingFees"
1412
- ].every((key) => isFiniteNumber(row[key])) && [
1413
- "token0CompositeKey",
1414
- "token1CompositeKey",
1415
- "creator",
1416
- "price",
1417
- "sqrtPrice",
1418
- "token0Tvl",
1419
- "token1Tvl"
1420
- ].every((key) => isOptionalString(row[key])) && [
1421
- "tick",
1422
- "tvlUsd",
1423
- "volume1d",
1424
- "volume7d",
1425
- "volume30d",
1426
- "trades1d",
1427
- "fee24h",
1428
- "apr1d",
1429
- "token0Price",
1430
- "token1Price"
1431
- ].every((key) => isOptionalNumber(row[key]));
1432
- }
1433
- function isFiniteNumber(value) {
1434
- return typeof value === "number" && Number.isFinite(value);
1435
- }
1436
- function isOptionalString(value) {
1437
- return value === void 0 || typeof value === "string";
1438
- }
1439
- function isOptionalNumber(value) {
1440
- return value === void 0 || isFiniteNumber(value);
2599
+ /**
2600
+ * Asserts that `dto` is EXACTLY what the builder of `method` produces for its own fields — the
2601
+ * same fields, canonical decimal text, builder key order, nothing extra (no `signature`). The
2602
+ * `submit*` methods use it so that what an app showed a user (a DTO it built) is byte for byte
2603
+ * what gets signed; a DTO edited by hand, or built elsewhere, is refused rather than signed.
2604
+ *
2605
+ * @throws GSwapSDKError VALIDATION_ERROR (`details.type` = `INVALID_DTO` or `DTO_NOT_CANONICAL`).
2606
+ */
2607
+ function assertCanonicalV2Dto(method, dto) {
2608
+ const rebuilt = rebuildV2Dto(method, dto);
2609
+ if (JSON.stringify(rebuilt) !== JSON.stringify(dto)) throw new GSwapSDKError(`The ${method} DTO is not in the form the SDK builders produce; build it with the matching build function and submit that.`, "VALIDATION_ERROR", {
2610
+ type: "DTO_NOT_CANONICAL",
2611
+ method
2612
+ });
1441
2613
  }
1442
2614
 
1443
2615
  //#endregion
1444
2616
  //#region src/classes/positions.ts
2617
+ /** The pool position a liquidity DTO names, as its confirmation needs it. */
2618
+ function identityOf(dto) {
2619
+ return {
2620
+ token0: dto.token0,
2621
+ token1: dto.token1,
2622
+ fee: dto.fee,
2623
+ tickLower: dto.tickLower,
2624
+ tickUpper: dto.tickUpper
2625
+ };
2626
+ }
1445
2627
  /**
1446
2628
  * Manages current-contract concentrated-liquidity positions.
1447
2629
  *
@@ -1457,26 +2639,32 @@ var Positions = class {
1457
2639
  symbols;
1458
2640
  signer;
1459
2641
  walletAddress;
1460
- constructor(gateway, symbols, signer, walletAddress) {
2642
+ constructor(gateway, symbols, signer, walletAddress, options = {}) {
1461
2643
  this.gateway = gateway;
1462
2644
  this.symbols = symbols;
1463
2645
  this.signer = signer;
1464
2646
  this.walletAddress = walletAddress;
1465
- this.http = new HttpClient(gateway.httpRequestor, gateway.requestTimeoutMs ?? 3e4);
2647
+ this.http = new HttpClient(gateway.httpRequestor, gateway.requestTimeoutMs ?? 3e4, gateway.wire);
2648
+ this.uniqueKeyPrefix = resolveUniqueKeyPrefix(options.uniqueKeyPrefix);
2649
+ this.onInvalidEntry = options.onInvalidEntry;
1466
2650
  }
1467
2651
  http;
2652
+ uniqueKeyPrefix;
2653
+ onInvalidEntry;
1468
2654
  /**
1469
2655
  * Gets all current-contract positions owned by an address.
1470
2656
  *
1471
2657
  * @param owner - GalaChain owner identity.
1472
- * @returns Enriched positions from the v2 trade backend.
2658
+ * @returns Enriched positions from the v2 trade backend, token images included. A row that is
2659
+ * not a usable position is skipped and reported to `onInvalidEntry`.
1473
2660
  * @example
1474
2661
  * ```typescript
1475
2662
  * const positions = await gSwap.positions.getUserPositions('client|012345678901234567890123');
1476
2663
  * ```
1477
2664
  */
1478
2665
  async getUserPositions(owner) {
1479
- return (await this.get("/positions", { user: owner })).data.map((position) => this.mapPosition(position));
2666
+ const response = await this.get("/positions", { user: owner });
2667
+ return readEntries("positions", response.data, parsePosition, this.onInvalidEntry);
1480
2668
  }
1481
2669
  /**
1482
2670
  * Gets one position, normalizing a caller-supplied reversed pair to canonical symbol order.
@@ -1493,17 +2681,65 @@ var Positions = class {
1493
2681
  * ```
1494
2682
  */
1495
2683
  async getPosition(args, signal) {
2684
+ const response = await this.getNullable("/position", await this.positionParams(args), signal);
2685
+ return response === null ? null : readPositionBody(response.data);
2686
+ }
2687
+ /**
2688
+ * Reads one position and classifies the outcome instead of throwing: `found` with the position
2689
+ * (fees included), `not_found` (the backend's HTTP 404, which it sends only when the chain
2690
+ * itself has no such position) or `unknown` (any other failure, carried as `error`). Use it
2691
+ * to confirm a write: `unknown` is "no evidence either way", never a confirmed absence.
2692
+ *
2693
+ * Only the caller's own abort rethrows. With a pass-through resolver ({@link CanonicalSymbols})
2694
+ * the pair and ticks go to the backend exactly as given and the backend orients them.
2695
+ *
2696
+ * @example
2697
+ * ```typescript
2698
+ * const read = await gSwap.positions.readPosition({
2699
+ * token0: 'GALA', token1: 'GUSDC', owner: 'client|012345678901234567890123',
2700
+ * fee: 3000, tickLower: -19200, tickUpper: 12000,
2701
+ * });
2702
+ * if (read.kind === 'found') console.log(read.data.fees0);
2703
+ * ```
2704
+ */
2705
+ async readPosition(args, signal) {
2706
+ try {
2707
+ const position = await this.getPosition(args, signal);
2708
+ return position === null ? { kind: "not_found" } : {
2709
+ kind: "found",
2710
+ data: position
2711
+ };
2712
+ } catch (error) {
2713
+ if ((signal === null || signal === void 0 ? void 0 : signal.aborted) === true) throw error;
2714
+ return {
2715
+ kind: "unknown",
2716
+ error: error instanceof GSwapSDKError ? error : new GSwapSDKError("Position request failed.", "HTTP_ERROR", { cause: error })
2717
+ };
2718
+ }
2719
+ }
2720
+ /**
2721
+ * The `/position` query: canonical symbols and canonical ticks after a client-side flip, or,
2722
+ * for a pass-through resolver, the caller's references and ticks untouched.
2723
+ */
2724
+ async positionParams(args) {
2725
+ if (this.symbols.passthrough === true) return {
2726
+ token0: rawTokenOf(args.token0),
2727
+ token1: rawTokenOf(args.token1),
2728
+ fee: `${args.fee}`,
2729
+ owner: args.owner,
2730
+ tickLower: `${args.tickLower}`,
2731
+ tickUpper: `${args.tickUpper}`
2732
+ };
1496
2733
  const pair = await this.symbols.orderPair(args.token0, args.token1);
1497
2734
  const ticks = this.canonicalTicks(args.tickLower, args.tickUpper, pair.flipped);
1498
- const response = await this.getNullable("/position", {
2735
+ return {
1499
2736
  token0: pair.token0.symbol,
1500
2737
  token1: pair.token1.symbol,
1501
2738
  fee: `${args.fee}`,
1502
2739
  owner: args.owner,
1503
2740
  tickLower: `${ticks.tickLower}`,
1504
2741
  tickUpper: `${ticks.tickUpper}`
1505
- }, signal);
1506
- return response === null ? null : this.mapPosition(response.data);
2742
+ };
1507
2743
  }
1508
2744
  /**
1509
2745
  * Estimates the other token amount and resulting liquidity for a deposit.
@@ -1521,8 +2757,8 @@ var Positions = class {
1521
2757
  async estimateAddLiquidity(args) {
1522
2758
  validateNumericAmount(args.amount, "amount");
1523
2759
  return (await this.get("/add-liq-estimate", {
1524
- token0: this.requestToken(args.token0),
1525
- token1: this.requestToken(args.token1),
2760
+ token0: rawTokenOf(args.token0),
2761
+ token1: rawTokenOf(args.token1),
1526
2762
  fee: `${args.fee}`,
1527
2763
  tickLower: `${args.tickLower}`,
1528
2764
  tickUpper: `${args.tickUpper}`,
@@ -1546,8 +2782,8 @@ var Positions = class {
1546
2782
  async estimateRemoveLiquidity(args) {
1547
2783
  validateNumericAmount(args.liquidity, "liquidity");
1548
2784
  return (await this.get("/remove-liq-estimate", {
1549
- token0: this.requestToken(args.token0),
1550
- token1: this.requestToken(args.token1),
2785
+ token0: rawTokenOf(args.token0),
2786
+ token1: rawTokenOf(args.token1),
1551
2787
  fee: `${args.fee}`,
1552
2788
  tickLower: `${args.tickLower}`,
1553
2789
  tickUpper: `${args.tickUpper}`,
@@ -1569,30 +2805,54 @@ var Positions = class {
1569
2805
  * ```
1570
2806
  */
1571
2807
  async addLiquidityByTicks(args) {
2808
+ return this.submitAddLiquidity(await this.buildAddLiquidity(args));
2809
+ }
2810
+ /**
2811
+ * Builds the AddLiquidity DTO that {@link addLiquidityByTicks} would sign, without signing or
2812
+ * sending it: to show in an approval popup, or to sign elsewhere. Submit exactly this DTO with
2813
+ * {@link submitAddLiquidity}. The pure counterpart, with canonical inputs and no resolution,
2814
+ * is `buildAddLiquidityDto`.
2815
+ *
2816
+ * @example
2817
+ * ```typescript
2818
+ * const dto = await gSwap.positions.buildAddLiquidity({
2819
+ * token0: 'GALA', token1: 'GUSDC', fee: 3000,
2820
+ * tickLower: -19200, tickUpper: 12000, amount: '100', amountIsToken0: true,
2821
+ * });
2822
+ * ```
2823
+ */
2824
+ async buildAddLiquidity(args) {
1572
2825
  validateFee(args.fee);
1573
2826
  const pair = await this.symbols.orderPair(args.token0, args.token1);
1574
2827
  const ticks = this.canonicalTicks(args.tickLower, args.tickUpper, pair.flipped);
1575
2828
  assertTickRange(ticks.tickLower, ticks.tickUpper, args.fee);
1576
2829
  validateNumericAmount(args.amount, "amount");
1577
- const amount = new BigNumber(args.amount).toFixed();
1578
- const dto = {
2830
+ const base = {
1579
2831
  token0: pair.token0.symbol,
1580
2832
  token1: pair.token1.symbol,
1581
2833
  fee: args.fee,
1582
2834
  tickLower: ticks.tickLower,
1583
2835
  tickUpper: ticks.tickUpper,
1584
- uniqueKey: this.uniqueKey(),
1585
- ...pair.flipped !== args.amountIsToken0 ? { depositQuantityToken0: amount } : { depositQuantityToken1: amount }
2836
+ uniqueKey: this.uniqueKeyFor(args.uniqueKey)
1586
2837
  };
2838
+ return pair.flipped !== args.amountIsToken0 ? buildAddLiquidityDto({
2839
+ ...base,
2840
+ depositQuantityToken0: args.amount
2841
+ }) : buildAddLiquidityDto({
2842
+ ...base,
2843
+ depositQuantityToken1: args.amount
2844
+ });
2845
+ }
2846
+ /**
2847
+ * Signs and submits a DTO built by {@link buildAddLiquidity} or `buildAddLiquidityDto`; it must
2848
+ * be exactly what the builder produces. The returned transaction confirms by proving the
2849
+ * position's liquidity grew.
2850
+ */
2851
+ async submitAddLiquidity(dto) {
2852
+ assertCanonicalV2Dto("AddLiquidity", dto);
1587
2853
  return this.submit("AddLiquidity", dto, {
1588
2854
  kind: "add",
1589
- identity: {
1590
- token0: pair.token0.symbol,
1591
- token1: pair.token1.symbol,
1592
- fee: args.fee,
1593
- tickLower: ticks.tickLower,
1594
- tickUpper: ticks.tickUpper
1595
- }
2855
+ identity: identityOf(dto)
1596
2856
  });
1597
2857
  }
1598
2858
  /**
@@ -1627,7 +2887,8 @@ var Positions = class {
1627
2887
  tickLower,
1628
2888
  tickUpper,
1629
2889
  amount: args.amount,
1630
- amountIsToken0: args.amountIsToken0
2890
+ amountIsToken0: args.amountIsToken0,
2891
+ uniqueKey: args.uniqueKey
1631
2892
  });
1632
2893
  }
1633
2894
  /**
@@ -1645,6 +2906,14 @@ var Positions = class {
1645
2906
  * ```
1646
2907
  */
1647
2908
  async removeLiquidity(args) {
2909
+ return this.submitRemoveLiquidity(await this.buildRemoveLiquidity(args));
2910
+ }
2911
+ /**
2912
+ * Builds the RemoveLiquidity DTO that {@link removeLiquidity} would sign, without signing or
2913
+ * sending it. Submit exactly this DTO with {@link submitRemoveLiquidity}. The pure counterpart
2914
+ * is `buildRemoveLiquidityDto`.
2915
+ */
2916
+ async buildRemoveLiquidity(args) {
1648
2917
  validateFee(args.fee);
1649
2918
  const pair = await this.symbols.orderPair(args.token0, args.token1);
1650
2919
  const ticks = this.canonicalTicks(args.tickLower, args.tickUpper, pair.flipped);
@@ -1652,26 +2921,29 @@ var Positions = class {
1652
2921
  if (args.amount0 !== void 0 && args.amount1 !== void 0) throw new GSwapSDKError("Provide at most one of amount0 or amount1.", "VALIDATION_ERROR");
1653
2922
  if (args.amount0 !== void 0) validateNumericAmount(args.amount0, "amount0");
1654
2923
  if (args.amount1 !== void 0) validateNumericAmount(args.amount1, "amount1");
1655
- const withdrawal = args.amount0 !== void 0 ? pair.flipped ? { withdrawalQuantityToken1: new BigNumber(args.amount0).toFixed() } : { withdrawalQuantityToken0: new BigNumber(args.amount0).toFixed() } : args.amount1 !== void 0 ? pair.flipped ? { withdrawalQuantityToken0: new BigNumber(args.amount1).toFixed() } : { withdrawalQuantityToken1: new BigNumber(args.amount1).toFixed() } : {};
1656
- const dto = {
2924
+ const [canonical0, canonical1] = pair.flipped ? [args.amount1, args.amount0] : [args.amount0, args.amount1];
2925
+ return buildRemoveLiquidityDto({
1657
2926
  token0: pair.token0.symbol,
1658
2927
  token1: pair.token1.symbol,
1659
2928
  fee: args.fee,
1660
2929
  tickLower: ticks.tickLower,
1661
2930
  tickUpper: ticks.tickUpper,
1662
- uniqueKey: this.uniqueKey(),
1663
- ...withdrawal
1664
- };
1665
- const isFullClose = args.amount0 === void 0 && args.amount1 === void 0;
2931
+ uniqueKey: this.uniqueKeyFor(args.uniqueKey),
2932
+ withdrawalQuantityToken0: canonical0,
2933
+ withdrawalQuantityToken1: canonical1
2934
+ });
2935
+ }
2936
+ /**
2937
+ * Signs and submits a DTO built by {@link buildRemoveLiquidity} or `buildRemoveLiquidityDto`;
2938
+ * it must be exactly what the builder produces. A DTO with no withdrawal quantity closes the
2939
+ * position, and the returned transaction then confirms by proving the position is gone.
2940
+ */
2941
+ async submitRemoveLiquidity(dto) {
2942
+ assertCanonicalV2Dto("RemoveLiquidity", dto);
2943
+ const isFullClose = dto.withdrawalQuantityToken0 === void 0 && dto.withdrawalQuantityToken1 === void 0;
1666
2944
  return this.submit("RemoveLiquidity", dto, {
1667
2945
  kind: isFullClose ? "removeFull" : "removePartial",
1668
- identity: {
1669
- token0: pair.token0.symbol,
1670
- token1: pair.token1.symbol,
1671
- fee: args.fee,
1672
- tickLower: ticks.tickLower,
1673
- tickUpper: ticks.tickUpper
1674
- }
2946
+ identity: identityOf(dto)
1675
2947
  });
1676
2948
  }
1677
2949
  /**
@@ -1688,27 +2960,36 @@ var Positions = class {
1688
2960
  * ```
1689
2961
  */
1690
2962
  async collectPositionFees(args) {
2963
+ return this.submitCollectPositionFees(await this.buildCollectPositionFees(args));
2964
+ }
2965
+ /**
2966
+ * Builds the CollectPositionFees DTO that {@link collectPositionFees} would sign, without
2967
+ * signing or sending it. Submit exactly this DTO with {@link submitCollectPositionFees}. The
2968
+ * pure counterpart is `buildCollectPositionFeesDto`.
2969
+ */
2970
+ async buildCollectPositionFees(args) {
1691
2971
  validateFee(args.fee);
1692
2972
  const pair = await this.symbols.orderPair(args.token0, args.token1);
1693
2973
  const ticks = this.canonicalTicks(args.tickLower, args.tickUpper, pair.flipped);
1694
2974
  assertTickRange(ticks.tickLower, ticks.tickUpper, args.fee);
1695
- const dto = {
2975
+ return buildCollectPositionFeesDto({
1696
2976
  token0: pair.token0.symbol,
1697
2977
  token1: pair.token1.symbol,
1698
2978
  fee: args.fee,
1699
2979
  tickLower: ticks.tickLower,
1700
2980
  tickUpper: ticks.tickUpper,
1701
- uniqueKey: this.uniqueKey()
1702
- };
2981
+ uniqueKey: this.uniqueKeyFor(args.uniqueKey)
2982
+ });
2983
+ }
2984
+ /**
2985
+ * Signs and submits a DTO built by {@link buildCollectPositionFees} or
2986
+ * `buildCollectPositionFeesDto`; it must be exactly what the builder produces.
2987
+ */
2988
+ async submitCollectPositionFees(dto) {
2989
+ assertCanonicalV2Dto("CollectPositionFees", dto);
1703
2990
  return this.submit("CollectPositionFees", dto, {
1704
2991
  kind: "collect",
1705
- identity: {
1706
- token0: pair.token0.symbol,
1707
- token1: pair.token1.symbol,
1708
- fee: args.fee,
1709
- tickLower: ticks.tickLower,
1710
- tickUpper: ticks.tickUpper
1711
- }
2992
+ identity: identityOf(dto)
1712
2993
  });
1713
2994
  }
1714
2995
  /**
@@ -1733,7 +3014,15 @@ var Positions = class {
1733
3014
  * ```
1734
3015
  */
1735
3016
  async createPool(args) {
1736
- var _this$symbols$invalid, _this$symbols;
3017
+ return this.submitCreatePool(await this.buildCreatePool(args));
3018
+ }
3019
+ /**
3020
+ * Builds the CreatePool DTO that {@link createPool} would sign, without signing or sending it:
3021
+ * symbols resolved or proposed, the pair put in canonical order and the price inverted when it
3022
+ * was reversed. Submit exactly this DTO with {@link submitCreatePool}. The pure counterpart,
3023
+ * with canonical inputs, is `buildCreatePoolDto`.
3024
+ */
3025
+ async buildCreatePool(args) {
1737
3026
  const hasPrice = args.startingPrice !== void 0;
1738
3027
  if (hasPrice === (args.startingSqrtPrice !== void 0)) throw new GSwapSDKError("Provide exactly one of startingPrice or startingSqrtPrice.", "VALIDATION_ERROR");
1739
3028
  validateFee(args.fee);
@@ -1745,22 +3034,38 @@ var Positions = class {
1745
3034
  const sourcePrice = new BigNumber(sourcePriceInput);
1746
3035
  if (!sourcePrice.isFinite() || sourcePrice.isLessThanOrEqualTo(0)) throw new GSwapSDKError("Starting price must be finite and positive.", "VALIDATION_ERROR");
1747
3036
  const canonicalPrice = flipped ? new BigNumber(1).dividedBy(sourcePrice) : sourcePrice;
1748
- const dto = {
3037
+ const shared = {
1749
3038
  token0Key: token0.classKey,
1750
3039
  token1Key: token1.classKey,
1751
3040
  token0Symbol: token0.symbol,
1752
3041
  token1Symbol: token1.symbol,
1753
3042
  fee: args.fee,
1754
- uniqueKey: this.uniqueKey(),
1755
- ...hasPrice ? { startingPrice: canonicalPrice.toFixed() } : { startingSqrtPrice: canonicalPrice.toFixed() },
1756
- ...args.isPrivate === void 0 ? {} : { isPrivate: args.isPrivate },
1757
- ...args.privateAccess === void 0 ? {} : { privateAccess: args.privateAccess }
3043
+ uniqueKey: this.uniqueKeyFor(args.uniqueKey),
3044
+ name: args.name,
3045
+ isPrivate: args.isPrivate,
3046
+ privateAccess: args.privateAccess
1758
3047
  };
3048
+ return hasPrice ? buildCreatePoolDto({
3049
+ ...shared,
3050
+ startingPrice: canonicalPrice
3051
+ }) : buildCreatePoolDto({
3052
+ ...shared,
3053
+ startingSqrtPrice: canonicalPrice
3054
+ });
3055
+ }
3056
+ /**
3057
+ * Signs and submits a DTO built by {@link buildCreatePool} or `buildCreatePoolDto`; it must be
3058
+ * exactly what the builder produces. The returned transaction confirms by the pool existing, and
3059
+ * the cached symbol registry is dropped, since the pool may have registered new symbols.
3060
+ */
3061
+ async submitCreatePool(dto) {
3062
+ var _this$symbols$invalid, _this$symbols;
3063
+ assertCanonicalV2Dto("CreatePool", dto);
1759
3064
  const transaction = await this.submit("CreatePool", dto, {
1760
3065
  kind: "createPool",
1761
- token0: token0.symbol,
1762
- token1: token1.symbol,
1763
- fee: args.fee
3066
+ token0: dto.token0Symbol,
3067
+ token1: dto.token1Symbol,
3068
+ fee: dto.fee
1764
3069
  });
1765
3070
  (_this$symbols$invalid = (_this$symbols = this.symbols).invalidate) === null || _this$symbols$invalid === void 0 || _this$symbols$invalid.call(_this$symbols);
1766
3071
  return transaction;
@@ -1866,30 +3171,6 @@ var Positions = class {
1866
3171
  if (!(error instanceof GSwapSDKError) || error.details === void 0) return false;
1867
3172
  return error.details["status"] === 404;
1868
3173
  }
1869
- mapPosition(position) {
1870
- return {
1871
- token0Symbol: position.token0Symbol,
1872
- token1Symbol: position.token1Symbol,
1873
- ...position.token0CompositeKey === void 0 ? {} : { token0CompositeKey: position.token0CompositeKey },
1874
- ...position.token1CompositeKey === void 0 ? {} : { token1CompositeKey: position.token1CompositeKey },
1875
- fee: position.fee,
1876
- tickLower: position.tickLower,
1877
- tickUpper: position.tickUpper,
1878
- liquidity: position.liquidity,
1879
- amount0: position.amount0,
1880
- amount1: position.amount1,
1881
- inRange: position.inRange,
1882
- ...position.currentTick === void 0 ? {} : { currentTick: position.currentTick },
1883
- ...position.sqrtPrice === void 0 ? {} : { sqrtPrice: position.sqrtPrice },
1884
- pool: position.poolRef ?? position.pool ?? "",
1885
- owner: position.owner,
1886
- ...position.fees0 === void 0 ? {} : { fees0: position.fees0 },
1887
- ...position.fees1 === void 0 ? {} : { fees1: position.fees1 }
1888
- };
1889
- }
1890
- requestToken(ref) {
1891
- return typeof ref === "string" ? ref : compositeKeyOf(ref);
1892
- }
1893
3174
  canonicalTicks(tickLower, tickUpper, flipped) {
1894
3175
  return flipped ? {
1895
3176
  tickLower: -tickUpper,
@@ -1907,8 +3188,11 @@ var Positions = class {
1907
3188
  rejectNumber(value, parameterName) {
1908
3189
  if (typeof value === "number") throw new GSwapSDKError(`Invalid ${parameterName}: use a decimal string or BigNumber, not a JavaScript number`, "VALIDATION_ERROR");
1909
3190
  }
1910
- uniqueKey() {
1911
- return `gswap-sdk-${globalThis.crypto.randomUUID()}`;
3191
+ /** The caller's `uniqueKey` (validated), else a fresh one. */
3192
+ uniqueKeyFor(supplied) {
3193
+ if (supplied === void 0) return createUniqueKey(this.uniqueKeyPrefix);
3194
+ assertUniqueKey(supplied);
3195
+ return supplied;
1912
3196
  }
1913
3197
  async resolveCreateToken(ref, symbolOverride) {
1914
3198
  try {
@@ -1920,6 +3204,7 @@ var Positions = class {
1920
3204
  registeredSymbol: resolved.symbol
1921
3205
  });
1922
3206
  const suppliedClassKey = this.tryParseClassKey(ref);
3207
+ if (suppliedClassKey === void 0 && resolved.collection === "") throw new GSwapSDKError("createPool needs each token as a class key; a bare trading symbol does not carry one.", "VALIDATION_ERROR", { token: ref });
1923
3208
  return {
1924
3209
  symbol: resolved.symbol,
1925
3210
  classKey: suppliedClassKey ?? parseTokenClassKey({
@@ -1938,7 +3223,7 @@ var Positions = class {
1938
3223
  throw error;
1939
3224
  }
1940
3225
  if (symbolOverride === void 0 || symbolOverride === "") throw new GSwapSDKError("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.", "VALIDATION_ERROR", { token: ref });
1941
- if (!/^[A-Za-z0-9]+$/u.test(symbolOverride)) throw new GSwapSDKError("Invalid trading symbol: must be ASCII letters and digits only.", "VALIDATION_ERROR", { symbol: symbolOverride });
3226
+ if (!isProposableTradingSymbol(symbolOverride)) throw new GSwapSDKError("Invalid trading symbol: must be 1-32 ASCII letters and digits and not a reserved word (Token, Unit, none).", "VALIDATION_ERROR", { symbol: symbolOverride });
1942
3227
  return {
1943
3228
  symbol: symbolOverride,
1944
3229
  classKey
@@ -1953,27 +3238,94 @@ var Positions = class {
1953
3238
  }
1954
3239
  }
1955
3240
  };
3241
+ const REQUIRED_POSITION_STRINGS = [
3242
+ "token0Symbol",
3243
+ "token1Symbol",
3244
+ "owner",
3245
+ "liquidity",
3246
+ "amount0",
3247
+ "amount1"
3248
+ ];
3249
+ const REQUIRED_POSITION_NUMBERS = [
3250
+ "fee",
3251
+ "tickLower",
3252
+ "tickUpper"
3253
+ ];
3254
+ const OPTIONAL_POSITION_STRINGS = [
3255
+ "token0CompositeKey",
3256
+ "token1CompositeKey",
3257
+ "token0Image",
3258
+ "token1Image",
3259
+ "sqrtPrice",
3260
+ "fees0",
3261
+ "fees1"
3262
+ ];
3263
+ /**
3264
+ * Reads one position row of `/positions` or `/position`: the pair, owner, range, liquidity and
3265
+ * amounts must be usable; the composite keys, token images, current tick and price, and the
3266
+ * escrowed fees are carried when present. `pool` is the pool reference (`poolRef` wins over
3267
+ * `pool`; `''` when the row names neither).
3268
+ */
3269
+ function parsePosition(value) {
3270
+ const wire = asEntryRecord(value);
3271
+ if (wire === void 0) return entryRejected("the row is not an object");
3272
+ for (const key of REQUIRED_POSITION_STRINGS) if (typeof wire[key] !== "string") return entryRejected(`${key} is not a string`);
3273
+ for (const key of REQUIRED_POSITION_NUMBERS) {
3274
+ const number = wire[key];
3275
+ if (typeof number !== "number" || !Number.isFinite(number)) return entryRejected(`${key} is not a number`);
3276
+ }
3277
+ if (typeof wire["inRange"] !== "boolean") return entryRejected("inRange is not a boolean");
3278
+ for (const key of OPTIONAL_POSITION_STRINGS) if (wire[key] !== void 0 && typeof wire[key] !== "string") return entryRejected(`${key} is not a string`);
3279
+ const currentTick = wire["currentTick"];
3280
+ if (currentTick !== void 0 && (typeof currentTick !== "number" || !Number.isFinite(currentTick))) return entryRejected("currentTick is not a number");
3281
+ const pool = wire["poolRef"] ?? wire["pool"] ?? "";
3282
+ if (typeof pool !== "string") return entryRejected("pool is not a string");
3283
+ const optional = Object.fromEntries([...OPTIONAL_POSITION_STRINGS, "currentTick"].flatMap((key) => wire[key] === void 0 ? [] : [[key, wire[key]]]));
3284
+ return entryOk({
3285
+ token0Symbol: wire["token0Symbol"],
3286
+ token1Symbol: wire["token1Symbol"],
3287
+ fee: wire["fee"],
3288
+ tickLower: wire["tickLower"],
3289
+ tickUpper: wire["tickUpper"],
3290
+ liquidity: wire["liquidity"],
3291
+ amount0: wire["amount0"],
3292
+ amount1: wire["amount1"],
3293
+ inRange: wire["inRange"],
3294
+ pool,
3295
+ owner: wire["owner"],
3296
+ ...optional
3297
+ });
3298
+ }
3299
+ /** The position inside a `/position` answer, or `INVALID_CHAIN_RESPONSE` when it is not one. */
3300
+ function readPositionBody(data) {
3301
+ const parsed = parsePosition(data);
3302
+ if (parsed.ok) return parsed.value;
3303
+ throw new GSwapSDKError("Backend returned an invalid position.", "INVALID_CHAIN_RESPONSE", {
3304
+ data,
3305
+ reason: parsed.reason
3306
+ });
3307
+ }
1956
3308
 
1957
3309
  //#endregion
1958
3310
  //#region src/classes/quoting.ts
1959
3311
  /** Read-only quote service backed by the v2 offline quote engine. */
1960
3312
  var Quoting = class {
1961
- dexBackendBaseUrl;
1962
- http;
3313
+ gateway;
1963
3314
  symbols;
1964
3315
  /**
1965
3316
  * Creates a quote service.
1966
3317
  *
1967
3318
  * @example
1968
3319
  * ```ts
1969
- * const quoting = new Quoting('https://swap-backend.stage.defi.ovh.gala.com', http, symbols);
3320
+ * const quoting = new Quoting(gateway, symbols); // a ChainGateway, or any { dexBackendBaseUrl, httpRequestor }
1970
3321
  * ```
1971
3322
  */
1972
- constructor(dexBackendBaseUrl, http, symbols) {
1973
- this.dexBackendBaseUrl = dexBackendBaseUrl;
1974
- this.http = http;
3323
+ constructor(gateway, symbols) {
3324
+ this.gateway = gateway;
1975
3325
  this.symbols = symbols;
3326
+ this.http = new HttpClient(gateway.httpRequestor, gateway.requestTimeoutMs ?? 3e4, gateway.wire);
1976
3327
  }
3328
+ http;
1977
3329
  /**
1978
3330
  * Quotes the output for a positive exact-input amount.
1979
3331
  *
@@ -1985,7 +3337,7 @@ var Quoting = class {
1985
3337
  */
1986
3338
  async quoteExactInput(tokenIn, tokenOut, amountIn, fee) {
1987
3339
  validateNumericAmount(amountIn, "amountIn");
1988
- return this.quote(tokenIn, tokenOut, { amountIn: toDecimalString$1(amountIn) }, fee);
3340
+ return this.quote(tokenIn, tokenOut, { amountIn: toDecimalString(amountIn) }, fee);
1989
3341
  }
1990
3342
  /**
1991
3343
  * Quotes the input for a positive exact-output amount.
@@ -1998,18 +3350,18 @@ var Quoting = class {
1998
3350
  */
1999
3351
  async quoteExactOutput(tokenIn, tokenOut, amountOut, fee) {
2000
3352
  validateNumericAmount(amountOut, "amountOut");
2001
- return this.quote(tokenIn, tokenOut, { amountOut: toDecimalString$1(amountOut) }, fee);
3353
+ return this.quote(tokenIn, tokenOut, { amountOut: toDecimalString(amountOut) }, fee);
2002
3354
  }
2003
3355
  async quote(tokenIn, tokenOut, amount, fee) {
2004
3356
  validateOptionalFee(fee);
2005
3357
  const params = {
2006
- tokenIn: await resolveSymbol$1(this.symbols, tokenIn),
2007
- tokenOut: await resolveSymbol$1(this.symbols, tokenOut),
3358
+ tokenIn: await queryTokenOf(this.symbols, tokenIn),
3359
+ tokenOut: await queryTokenOf(this.symbols, tokenOut),
2008
3360
  ...amount
2009
3361
  };
2010
3362
  if (fee !== void 0) params["fee"] = String(fee);
2011
3363
  try {
2012
- return mapQuote((await this.http.sendGetRequest(this.dexBackendBaseUrl, "/v2/trade", "/quote", params)).data);
3364
+ return mapQuote((await this.http.sendGetRequest(this.gateway.dexBackendBaseUrl, "/v2/trade", "/quote", params)).data);
2013
3365
  } catch (error) {
2014
3366
  throw mapQuoteError(error, tokenIn, tokenOut, fee);
2015
3367
  }
@@ -2071,12 +3423,19 @@ function optionalPositiveDecimal(value) {
2071
3423
  return false;
2072
3424
  }
2073
3425
  }
3426
+ /**
3427
+ * The ways the backend says a pair has no market at all: a token the DEX contract never
3428
+ * registered ("has no trading symbol on the new DEX contract"), no pool at ANY fee tier ("No
3429
+ * pools found with sufficient liquidity"), or a missing pool ("Pool does not exist on the new
3430
+ * DEX contract"). A pool that exists but is too thin says "Insufficient liquidity: ..." instead.
3431
+ */
3432
+ const NO_MARKET_MESSAGE = /no pool|no pools|pool does not exist|has no trading symbol on the new DEX contract/iu;
2074
3433
  function mapQuoteError(error, tokenIn, tokenOut, fee) {
2075
3434
  if (error instanceof GSwapSDKError) {
2076
3435
  const status = readStatus(error.details);
2077
3436
  const message = readMessage(error.details) ?? error.message;
2078
- if (status === 404 || /no pool|no pools|pool does not exist/iu.test(message)) return GSwapSDKError.noPoolAvailableError(tokenIn, tokenOut, fee);
2079
- if (status === 400 && /insufficient liquidity/iu.test(message)) return GSwapSDKError.insufficientLiquidityError(tokenIn, tokenOut, fee);
3437
+ if (status === 404 || NO_MARKET_MESSAGE.test(message)) return GSwapSDKError.noPoolAvailableError(tokenIn, tokenOut, fee, error);
3438
+ if (status === 400 && /insufficient liquidity/iu.test(message)) return GSwapSDKError.insufficientLiquidityError(tokenIn, tokenOut, fee, error);
2080
3439
  return error;
2081
3440
  }
2082
3441
  return new GSwapSDKError("Quote request failed.", "HTTP_ERROR", {
@@ -2101,107 +3460,112 @@ function readMessage(details) {
2101
3460
  function validateOptionalFee(fee) {
2102
3461
  if (fee !== void 0 && !ALL_FEE_TIERS.some((tier) => Number(tier) === Number(fee))) throw new GSwapSDKError(`Invalid fee tier: ${fee}`, "VALIDATION_ERROR", { fee });
2103
3462
  }
2104
- function toDecimalString$1(amount) {
3463
+ function toDecimalString(amount) {
2105
3464
  return new BigNumber(amount).toFixed();
2106
3465
  }
2107
- async function resolveSymbol$1(symbols, token) {
2108
- const resolved = await symbols.resolve(token);
2109
- if (resolved.symbol.length > 0) return resolved.symbol;
2110
- throw new GSwapSDKError("Token could not be resolved to a trading symbol.", "SYMBOL_NOT_FOUND", { token });
2111
- }
2112
3466
 
2113
3467
  //#endregion
2114
- //#region src/classes/symbols.ts
2115
- const SYMBOL_CACHE_TTL_MS = 6e4;
2116
- /** Symbol registry client for the current GalaChainDex contract. */
2117
- var Symbols = class {
2118
- gateway;
2119
- cachedSymbols;
2120
- cachedAt = 0;
2121
- refreshInFlight;
2122
- http;
2123
- /** Create a symbol service backed by the swap backend. */
2124
- constructor(gateway) {
2125
- this.gateway = gateway;
2126
- this.http = new HttpClient(gateway.httpRequestor, gateway.requestTimeoutMs);
2127
- }
2128
- /** List all registered GalaChainDex trading symbols, cached for 60 seconds. */
2129
- async list() {
2130
- if (this.cachedSymbols !== void 0 && Date.now() - this.cachedAt < SYMBOL_CACHE_TTL_MS) return this.cachedSymbols;
2131
- if (this.refreshInFlight !== void 0) return this.refreshInFlight;
2132
- this.refreshInFlight = this.http.sendGetRequest(this.gateway.dexBackendBaseUrl, "/v2/trade", "/symbols").then((response) => parseSymbols(response.data)).then((symbols) => {
2133
- this.cachedSymbols = symbols;
2134
- this.cachedAt = Date.now();
2135
- return symbols;
2136
- }).finally(() => {
2137
- this.refreshInFlight = void 0;
2138
- });
2139
- return this.refreshInFlight;
2140
- }
2141
- /** Invalidate the cached symbol registry after a write changes registration state.
2142
- *
2143
- * @example
2144
- * ```ts
2145
- * gSwap.symbols.invalidate();
2146
- * ```
2147
- */
2148
- invalidate() {
2149
- this.cachedSymbols = void 0;
2150
- this.cachedAt = 0;
2151
- }
2152
- /** Force one registry refresh, bypassing the cache.
2153
- *
2154
- * @example
2155
- * ```ts
2156
- * const symbols = await gSwap.symbols.refresh();
2157
- * ```
2158
- */
2159
- async refresh() {
2160
- this.invalidate();
2161
- this.refreshInFlight = void 0;
2162
- return this.list();
2163
- }
2164
- /** Resolve a symbol or token class key to its registered symbol metadata. */
2165
- async resolve(ref) {
2166
- let symbols = await this.list();
2167
- const composite = typeof ref === "string" ? isCompositeKey(ref) ? compositeKeyOf(parseTokenClassKey(ref)) : void 0 : compositeKeyOf(ref);
2168
- const resolved = symbols.find((entry) => entry.symbol === ref || composite !== void 0 && compositeKeyOf(entry) === composite);
2169
- if (resolved === void 0) {
2170
- symbols = await this.refresh();
2171
- const refreshed = symbols.find((entry) => entry.symbol === ref || composite !== void 0 && compositeKeyOf(entry) === composite);
2172
- if (refreshed === void 0) throw GSwapSDKError.unknownTokenError(ref);
2173
- return refreshed;
3468
+ //#region src/classes/shadow_submit.ts
3469
+ /** Maps an HTTP status to a failure kind: 503 retryable, 400 disabled, anything else unknown. */
3470
+ function classifyShadowSubmitStatus(status) {
3471
+ if (status === 503) return "unavailable";
3472
+ if (status === 400) return "disabled";
3473
+ return "unknown";
3474
+ }
3475
+ /**
3476
+ * Prefers the body `code` (stable across status remaps) and falls back to the HTTP status.
3477
+ * `SHADOW_UNAVAILABLE` is the only retryable case; `SHADOW_RELAY_REJECTED` is a terminal gateway
3478
+ * rejection; the two other 400 codes and any unknown 400 map to "disabled".
3479
+ */
3480
+ function classifyShadowSubmitError(status, code) {
3481
+ if (code === "SHADOW_UNAVAILABLE") return "unavailable";
3482
+ if (code === "SHADOW_RELAY_REJECTED") return "rejected";
3483
+ if (code === "SHADOW_DISABLED" || code === "SHADOW_UNSUPPORTED_TYPE") return "disabled";
3484
+ return classifyShadowSubmitStatus(status);
3485
+ }
3486
+ /**
3487
+ * Normalizes a shadow write's raw answer.
3488
+ *
3489
+ * A 2xx envelope with `error === false` is a success when it is a queued RequestTrade that
3490
+ * acknowledges the EXACT signed `uniqueKey`, or a synchronous (`mode: 'sync'`) liquidity write.
3491
+ * Everything else is classified as a failure from the status and the body's `code`.
3492
+ *
3493
+ * @throws GSwapSDKError INVALID_GATEWAY_RESPONSE when a RequestTrade success does not queue the
3494
+ * signed `uniqueKey` (a synchronous or mismatched answer must never be accepted as a swap).
3495
+ */
3496
+ function readShadowSubmitOutcome(method, signedBody, result) {
3497
+ const { httpStatus, body } = result;
3498
+ const envelope = asRecord(body);
3499
+ if (httpStatus >= 200 && httpStatus < 300 && (envelope === null || envelope === void 0 ? void 0 : envelope["error"]) === false) {
3500
+ const data = asRecord(envelope["data"]);
3501
+ const rawTransactionId = typeof (data === null || data === void 0 ? void 0 : data["transactionId"]) === "string" ? data["transactionId"] : void 0;
3502
+ if (method === "RequestTrade") {
3503
+ const requestedKey = signedBody["uniqueKey"];
3504
+ if ((data === null || data === void 0 ? void 0 : data["mode"]) !== "queued" || typeof requestedKey !== "string" || data["uniqueKey"] !== requestedKey) throw new GSwapSDKError(`The swap backend did not queue the request ${typeof requestedKey === "string" ? requestedKey : ""}.`, "INVALID_GATEWAY_RESPONSE", {
3505
+ httpStatus,
3506
+ body
3507
+ });
3508
+ return {
3509
+ ok: true,
3510
+ bundleId: rawTransactionId ?? "",
3511
+ queued: {
3512
+ uniqueKey: requestedKey,
3513
+ requestTransactionId: rawTransactionId ?? null
3514
+ }
3515
+ };
2174
3516
  }
2175
- return resolved;
2176
- }
2177
- /** Resolve and put two token references in canonical trading-symbol order. */
2178
- async orderPair(a, b) {
2179
- const [resolvedA, resolvedB] = await Promise.all([this.resolve(a), this.resolve(b)]);
2180
- const [token0Symbol, token1Symbol] = orderSymbols(resolvedA.symbol, resolvedB.symbol);
2181
- return {
2182
- token0: token0Symbol === resolvedA.symbol ? resolvedA : resolvedB,
2183
- token1: token1Symbol === resolvedB.symbol ? resolvedB : resolvedA,
2184
- flipped: token0Symbol !== resolvedA.symbol
3517
+ if ((data === null || data === void 0 ? void 0 : data["mode"]) === "sync") return {
3518
+ ok: true,
3519
+ bundleId: rawTransactionId ?? ""
2185
3520
  };
2186
3521
  }
2187
- };
2188
- function parseSymbols(value) {
2189
- if (!Array.isArray(value) || !value.every(isTradingSymbol)) throw new GSwapSDKError("Backend returned an invalid symbol list.", "INVALID_CHAIN_RESPONSE", { data: value });
2190
- return value;
2191
- }
2192
- function isTradingSymbol(value) {
2193
- if (typeof value !== "object" || value === null) return false;
2194
- const entry = value;
2195
- return typeof entry["symbol"] === "string" && typeof entry["collection"] === "string" && typeof entry["category"] === "string" && typeof entry["type"] === "string" && typeof entry["additionalKey"] === "string" && typeof entry["decimals"] === "number" && Number.isInteger(entry["decimals"]) && entry["decimals"] >= 0;
3522
+ const kind = classifyShadowSubmitError(httpStatus, getStringProperty(body, "code"));
3523
+ if (kind === "rejected") return {
3524
+ ok: false,
3525
+ kind: "rejected",
3526
+ retryable: false,
3527
+ message: getStringProperty(body, "message") ?? ""
3528
+ };
3529
+ return kind === "unavailable" ? {
3530
+ ok: false,
3531
+ kind,
3532
+ retryable: true
3533
+ } : {
3534
+ ok: false,
3535
+ kind,
3536
+ retryable: false
3537
+ };
2196
3538
  }
2197
- function isCompositeKey(ref) {
2198
- return ref.includes("|") || ref.includes("$");
3539
+ function asRecord(value) {
3540
+ return typeof value === "object" && value !== null ? value : void 0;
2199
3541
  }
2200
3542
 
2201
3543
  //#endregion
2202
3544
  //#region src/classes/swaps.ts
2203
- /** The swap backend's apply-results key constraint (`apply-results.dto.ts`). */
2204
- const UNIQUE_KEY_PATTERN = /^[A-Za-z0-9._:-]{1,128}$/u;
3545
+ /**
3546
+ * The route of a quote: its fee tier and pool, with `tokenIn` / `tokenOut` taken from
3547
+ * `tokenInIsToken0`, nothing re-derived. Use it to swap in exactly the pool a quote priced:
3548
+ *
3549
+ * @example
3550
+ * ```ts
3551
+ * const route = swapRouteFromQuote(quote);
3552
+ * await swaps.swap(route.tokenIn, route.tokenOut, route.fee, { exactIn: '100' }, { pool: route.pool });
3553
+ * ```
3554
+ */
3555
+ function swapRouteFromQuote(quote) {
3556
+ validateFee(quote.fee);
3557
+ assertCanonicalPair(quote.token0Symbol, quote.token1Symbol);
3558
+ const [tokenIn, tokenOut] = quote.tokenInIsToken0 ? [quote.token0Symbol, quote.token1Symbol] : [quote.token1Symbol, quote.token0Symbol];
3559
+ return {
3560
+ tokenIn,
3561
+ tokenOut,
3562
+ fee: quote.fee,
3563
+ pool: {
3564
+ token0: quote.token0Symbol,
3565
+ token1: quote.token1Symbol
3566
+ }
3567
+ };
3568
+ }
2205
3569
  /** Executes queued current-contract RequestTrade operations through the Chain Gateway. */
2206
3570
  var Swaps = class {
2207
3571
  gateway;
@@ -2216,12 +3580,14 @@ var Swaps = class {
2216
3580
  * const swaps = new Swaps(gateway, symbols, signer, 'client|alice');
2217
3581
  * ```
2218
3582
  */
2219
- constructor(gateway, symbols, signer, walletAddress) {
3583
+ constructor(gateway, symbols, signer, walletAddress, options = {}) {
2220
3584
  this.gateway = gateway;
2221
3585
  this.symbols = symbols;
2222
3586
  this.signer = signer;
2223
3587
  this.walletAddress = walletAddress;
3588
+ this.uniqueKeyPrefix = resolveUniqueKeyPrefix(options.uniqueKeyPrefix);
2224
3589
  }
3590
+ uniqueKeyPrefix;
2225
3591
  /**
2226
3592
  * Signs and submits an exact-input or exact-output RequestTrade DTO. The returned transaction
2227
3593
  * is QUEUED; call `await tx.confirm()` to obtain the executed trade or chain rejection.
@@ -2234,13 +3600,97 @@ var Swaps = class {
2234
3600
  * });
2235
3601
  * ```
2236
3602
  */
2237
- async swap(tokenIn, tokenOut, fee, amount) {
3603
+ async swap(tokenIn, tokenOut, fee, amount, options) {
3604
+ return this.submitSwap(await this.buildSwap(tokenIn, tokenOut, fee, amount, options));
3605
+ }
3606
+ /**
3607
+ * Signs and submits a SHADOW (dark) swap: the same RequestTrade as {@link swap}, relayed with
3608
+ * `X-Shadow: true` so defi-backend marks it private before it reaches the contract. Requires a
3609
+ * `walletAddress`. Resolves the normalized outcome instead of throwing on a gateway refusal:
3610
+ * `ok: false` carries `unavailable` (retryable), `disabled`, `rejected` (with the gateway's
3611
+ * message) or `unknown`. A success carries `queued`, to be confirmed with
3612
+ * `confirmSwap(queued.uniqueKey)`; never fall back to a public swap on failure.
3613
+ *
3614
+ * @example
3615
+ * ```ts
3616
+ * const outcome = await swaps.swapShadow('GALA', 'GUSDC', 3000, { exactIn: '100' });
3617
+ * if (outcome.ok && outcome.queued) await swaps.confirmSwap(outcome.queued.uniqueKey);
3618
+ * ```
3619
+ */
3620
+ async swapShadow(tokenIn, tokenOut, fee, amount, options) {
3621
+ return this.submitSwapShadow(await this.buildSwap(tokenIn, tokenOut, fee, amount, options));
3622
+ }
3623
+ /**
3624
+ * Builds the RequestTrade DTO that {@link swap} would sign, without signing or sending it: to
3625
+ * show in an approval popup, to remember its `uniqueKey`, or to sign elsewhere. Submit exactly
3626
+ * this DTO with {@link submitSwap}. The pure counterpart, with canonical inputs and no
3627
+ * resolution, is `buildRequestTradeDto`.
3628
+ *
3629
+ * @example
3630
+ * ```ts
3631
+ * const dto = await swaps.buildSwap('GALA', 'GUSDC', 3000, { exactIn: '100' });
3632
+ * showApproval(dto);
3633
+ * const submitted = await swaps.submitSwap(dto);
3634
+ * ```
3635
+ */
3636
+ async buildSwap(tokenIn, tokenOut, fee, amount, options) {
2238
3637
  validateFee(fee);
2239
- const dto = await this.buildRequestTradeDto(tokenIn, tokenOut, fee, amount);
3638
+ const uniqueKey = (options === null || options === void 0 ? void 0 : options.uniqueKey) ?? createUniqueKey(this.uniqueKeyPrefix);
3639
+ assertUniqueKey(uniqueKey);
3640
+ const tokenInSymbol = await tradingSymbolOf(this.symbols, tokenIn);
3641
+ const tokenOutSymbol = await tradingSymbolOf(this.symbols, tokenOut);
3642
+ const ordered = this.orientPool(tokenInSymbol, tokenOutSymbol, options === null || options === void 0 ? void 0 : options.pool);
3643
+ return buildRequestTradeDto({
3644
+ token0: ordered.token0,
3645
+ token1: ordered.token1,
3646
+ fee,
3647
+ tokenInIsToken0: tokenInSymbol === ordered.token0,
3648
+ uniqueKey,
3649
+ ...amount
3650
+ });
3651
+ }
3652
+ /**
3653
+ * Signs and submits a DTO built by {@link buildSwap} or `buildRequestTradeDto`. The DTO must be
3654
+ * exactly what the builder produces (no signature, canonical decimals, builder key order), so
3655
+ * what an app showed is what gets signed.
3656
+ *
3657
+ * @example
3658
+ * ```ts
3659
+ * const submitted = await swaps.submitSwap(dto);
3660
+ * const applied = await submitted.confirm();
3661
+ * ```
3662
+ */
3663
+ async submitSwap(dto) {
3664
+ const signed = await this.signRequestTrade(dto);
3665
+ return this.gateway.submit("RequestTrade", signed, this.submitOptions());
3666
+ }
3667
+ /** Signs and shadow-submits a DTO built by {@link buildSwap}; see {@link swapShadow}. */
3668
+ async submitSwapShadow(dto) {
3669
+ const signed = await this.signRequestTrade(dto);
3670
+ const result = await this.gateway.submitShadow("RequestTrade", signed, this.submitOptions());
3671
+ return readShadowSubmitOutcome("RequestTrade", signed, result);
3672
+ }
3673
+ submitOptions() {
3674
+ return this.walletAddress === void 0 ? {} : { walletAddress: this.walletAddress };
3675
+ }
3676
+ async signRequestTrade(dto) {
3677
+ assertCanonicalV2Dto("RequestTrade", dto);
2240
3678
  if (this.signer === void 0) throw GSwapSDKError.noSignerError();
2241
- const signedDto = await this.signer.signObject("RequestTrade", dto);
2242
- const submitOptions = this.walletAddress === void 0 ? {} : { walletAddress: this.walletAddress };
2243
- return this.gateway.submit("RequestTrade", signedDto, submitOptions);
3679
+ return this.signer.signObject("RequestTrade", dto);
3680
+ }
3681
+ /** The pool's two symbols in contract order: the quote's own when pinned, else string order. */
3682
+ orientPool(tokenInSymbol, tokenOutSymbol, pool) {
3683
+ if (pool === void 0) return readOrderedSymbols(orderSymbols(tokenInSymbol, tokenOutSymbol));
3684
+ if (!(tokenInSymbol === pool.token0 && tokenOutSymbol === pool.token1 || tokenInSymbol === pool.token1 && tokenOutSymbol === pool.token0)) throw new GSwapSDKError("tokenIn and tokenOut must be the two tokens of the pinned pool.", "VALIDATION_ERROR", {
3685
+ type: "POOL_MISMATCH",
3686
+ tokenIn: tokenInSymbol,
3687
+ tokenOut: tokenOutSymbol,
3688
+ pool
3689
+ });
3690
+ return {
3691
+ token0: pool.token0,
3692
+ token1: pool.token1
3693
+ };
2244
3694
  }
2245
3695
  /**
2246
3696
  * Confirm a swap by its durable `uniqueKey` without resubmitting it. This is the recovery
@@ -2252,11 +3702,11 @@ var Swaps = class {
2252
3702
  *
2253
3703
  * @example
2254
3704
  * ```ts
2255
- * const applied = await swaps.confirmSwap('gswap-sdk-2f1c…');
3705
+ * const applied = await swaps.confirmSwap('galaswap-operation-2f1c…');
2256
3706
  * ```
2257
3707
  */
2258
3708
  async confirmSwap(uniqueKey, options) {
2259
- if (!UNIQUE_KEY_PATTERN.test(uniqueKey)) throw new GSwapSDKError("uniqueKey must be 1-128 characters of A-Z, a-z, 0-9, \".\", \"_\", \":\" or \"-\".", "VALIDATION_ERROR", { uniqueKey });
3709
+ assertUniqueKey(uniqueKey);
2260
3710
  return new SubmittedTransaction({
2261
3711
  method: "RequestTrade",
2262
3712
  uniqueKey,
@@ -2271,47 +3721,7 @@ var Swaps = class {
2271
3721
  ...options
2272
3722
  });
2273
3723
  }
2274
- async buildRequestTradeDto(tokenIn, tokenOut, fee, amount) {
2275
- const tokenInSymbol = await resolveSymbol(this.symbols, tokenIn);
2276
- const tokenOutSymbol = await resolveSymbol(this.symbols, tokenOut);
2277
- const ordered = readOrderedSymbols(orderSymbols(tokenInSymbol, tokenOutSymbol));
2278
- const tokenInIsToken0 = tokenInSymbol === ordered.token0;
2279
- const dto = {
2280
- token0: ordered.token0,
2281
- token1: ordered.token1,
2282
- fee,
2283
- uniqueKey: `gswap-sdk-${globalThis.crypto.randomUUID()}`
2284
- };
2285
- if ("exactIn" in amount) {
2286
- const exactIn = amount.exactIn;
2287
- if (exactIn === void 0) throw new GSwapSDKError("exactIn is required for an exact-input swap.", "VALIDATION_ERROR");
2288
- validateNumericAmount(exactIn, "exactIn");
2289
- dto[tokenInIsToken0 ? "sell0Qty" : "sell1Qty"] = toDecimalString(exactIn);
2290
- if (amount.amountOutMinimum !== void 0) {
2291
- validateNumericAmount(amount.amountOutMinimum, "amountOutMinimum", true);
2292
- dto["amountOutMinimum"] = toDecimalString(amount.amountOutMinimum);
2293
- }
2294
- } else {
2295
- const exactOut = amount.exactOut;
2296
- if (exactOut === void 0) throw new GSwapSDKError("exactOut is required for an exact-output swap.", "VALIDATION_ERROR");
2297
- validateNumericAmount(exactOut, "exactOut");
2298
- dto[tokenInIsToken0 ? "buy1Qty" : "buy0Qty"] = toDecimalString(exactOut);
2299
- if (amount.amountInMaximum !== void 0) {
2300
- validateNumericAmount(amount.amountInMaximum, "amountInMaximum", true);
2301
- dto["amountInMaximum"] = toDecimalString(amount.amountInMaximum);
2302
- }
2303
- }
2304
- return dto;
2305
- }
2306
3724
  };
2307
- function toDecimalString(amount) {
2308
- return new BigNumber(amount).toFixed();
2309
- }
2310
- async function resolveSymbol(symbols, token) {
2311
- const resolved = await symbols.resolve(token);
2312
- if (resolved.symbol.length > 0) return resolved.symbol;
2313
- throw new GSwapSDKError("Token could not be resolved to a trading symbol.", "SYMBOL_NOT_FOUND", { token });
2314
- }
2315
3725
 
2316
3726
  //#endregion
2317
3727
  //#region src/classes/gswap.ts
@@ -2328,8 +3738,11 @@ var GSwap = class {
2328
3738
  positions;
2329
3739
  swaps;
2330
3740
  assets;
3741
+ /** Network-fee quotes (DryRun) signed with this client's signer. */
3742
+ fees;
2331
3743
  dexBackendWsUrl;
2332
3744
  webSocketImpl;
3745
+ streamApiKey;
2333
3746
  streamClient;
2334
3747
  /**
2335
3748
  * Create an SDK client for prod or stage.
@@ -2346,21 +3759,30 @@ var GSwap = class {
2346
3759
  this.chainCallTimeoutMs = (options === null || options === void 0 ? void 0 : options.chainCallTimeoutMs) ?? 3e4;
2347
3760
  this.signer = options === null || options === void 0 ? void 0 : options.signer;
2348
3761
  this.walletAddress = options === null || options === void 0 ? void 0 : options.walletAddress;
2349
- const httpClient = new HttpClient(options === null || options === void 0 ? void 0 : options.httpRequestor, this.chainCallTimeoutMs);
3762
+ const httpClient = new HttpClient(options === null || options === void 0 ? void 0 : options.httpRequestor, this.chainCallTimeoutMs, options === null || options === void 0 ? void 0 : options.wire);
2350
3763
  this.gateway = new ChainGateway({
2351
3764
  dexBackendBaseUrl: this.dexBackendBaseUrl,
2352
3765
  chainCallTimeoutMs: this.chainCallTimeoutMs,
3766
+ ...(options === null || options === void 0 ? void 0 : options.wire) === void 0 ? {} : { wire: options.wire },
2353
3767
  ...(options === null || options === void 0 ? void 0 : options.httpRequestor) === void 0 ? {} : { httpRequestor: options.httpRequestor },
2354
3768
  ...this.walletAddress === void 0 ? {} : { walletAddress: this.walletAddress }
2355
3769
  });
2356
- this.symbols = new Symbols(this.gateway);
2357
- this.quoting = new Quoting(this.dexBackendBaseUrl, httpClient, this.symbols);
2358
- this.pools = new Pools(this.gateway, this.symbols);
2359
- this.positions = new Positions(this.gateway, this.symbols, this.signer, this.walletAddress);
2360
- this.swaps = new Swaps(this.gateway, this.symbols, this.signer, this.walletAddress);
3770
+ const lenient = { onInvalidEntry: options === null || options === void 0 ? void 0 : options.onInvalidEntry };
3771
+ this.symbols = new Symbols(this.gateway, lenient);
3772
+ const resolver = (options === null || options === void 0 ? void 0 : options.symbolResolution) === "canonical" ? new CanonicalSymbols() : this.symbols;
3773
+ this.quoting = new Quoting(this.gateway, resolver);
3774
+ this.pools = new Pools(this.gateway, resolver, lenient);
3775
+ const keyOptions = {
3776
+ uniqueKeyPrefix: options === null || options === void 0 ? void 0 : options.uniqueKeyPrefix,
3777
+ ...lenient
3778
+ };
3779
+ this.positions = new Positions(this.gateway, resolver, this.signer, this.walletAddress, keyOptions);
3780
+ this.swaps = new Swaps(this.gateway, resolver, this.signer, this.walletAddress, keyOptions);
2361
3781
  this.assets = new Assets(this.dexBackendBaseUrl, httpClient);
3782
+ this.fees = new DexFees(this.gateway, this.signer);
2362
3783
  this.dexBackendWsUrl = (options === null || options === void 0 ? void 0 : options.dexBackendWsUrl) ?? ((options === null || options === void 0 ? void 0 : options.dexBackendBaseUrl) === void 0 ? environment.dexBackendWsUrl : `${this.dexBackendBaseUrl.replace(/^http/u, "ws")}/ws`);
2363
3784
  this.webSocketImpl = options === null || options === void 0 ? void 0 : options.webSocketImpl;
3785
+ this.streamApiKey = options === null || options === void 0 ? void 0 : options.streamApiKey;
2364
3786
  }
2365
3787
  /**
2366
3788
  * The realtime stream client for this environment (created on first use, not connected until you
@@ -2376,7 +3798,8 @@ var GSwap = class {
2376
3798
  get stream() {
2377
3799
  this.streamClient ??= new GdexStreamService({
2378
3800
  url: this.dexBackendWsUrl,
2379
- ...this.webSocketImpl === void 0 ? {} : { webSocketImpl: this.webSocketImpl }
3801
+ ...this.webSocketImpl === void 0 ? {} : { webSocketImpl: this.webSocketImpl },
3802
+ ...this.streamApiKey === void 0 ? {} : { apiKey: this.streamApiKey }
2380
3803
  });
2381
3804
  return this.streamClient;
2382
3805
  }
@@ -2385,9 +3808,149 @@ function trimTrailingSlash(value) {
2385
3808
  return value.replace(/\/$/u, "");
2386
3809
  }
2387
3810
 
3811
+ //#endregion
3812
+ //#region src/classes/pending_swaps.ts
3813
+ /** Key the wallet_extension has always used; its storage value is a plain array of entries. */
3814
+ const PENDING_SWAPS_STORAGE_KEY = "pendingSwaps.v1";
3815
+ /** Entries older than this are dropped the next time a wallet's swaps are listed. */
3816
+ const PENDING_SWAP_EXPIRY_MS = 6048e5;
3817
+ /**
3818
+ * Remembers queued swaps so their outcome can be confirmed after the UI, popup or service worker
3819
+ * that submitted them is gone (`confirmAppliedTrade` with the stored `uniqueKey`).
3820
+ *
3821
+ * Guarantees:
3822
+ * - Persistence is best effort and NEVER throws: a failing or missing storage must not turn an
3823
+ * accepted request into a client-side resubmission. `list` resolves `[]` when storage fails.
3824
+ * - Operations of one store instance are serialized, so concurrent `remember` / `forget` calls
3825
+ * cannot lose each other's write (read-modify-write over an async adapter). Two store instances
3826
+ * over the same storage (for example popup and service worker) are not coordinated.
3827
+ * - Entries that do not match the expected shape are ignored and dropped on the next write.
3828
+ * - Entries expire after seven days (an entry exactly seven days old is expired; frontend_v2
3829
+ * kept it for that one millisecond); `list` removes them from storage, which frontend_v2 never
3830
+ * did on read.
3831
+ * - New entries go to the end (or `insertAt: 'start'`); `list` returns the wallet's entries in
3832
+ * stored order (or `listOrder: 'newest-first'`).
3833
+ * - The stored shape is wallet_extension's by default; `storageKey`, `darkFlagField`, `insertAt`
3834
+ * and `listOrder` reproduce frontend_v2's. JSON key order inside an entry is not preserved.
3835
+ *
3836
+ * Passing no `storage` yields a store that remembers nothing.
3837
+ *
3838
+ * @example
3839
+ * ```ts
3840
+ * const store = new PendingSwapStore({
3841
+ * get: async (key) => (await chrome.storage.local.get(key))[key],
3842
+ * set: (key, value) => chrome.storage.local.set({ [key]: value }),
3843
+ * });
3844
+ * await store.remember({ uniqueKey, requestTransactionId, wallet, token0Symbol: 'GALA',
3845
+ * token1Symbol: 'GUSDC', isDarkSwap: false, createdAt: Date.now() });
3846
+ * for (const swap of await store.list(wallet)) await confirmAppliedTrade(client, swap);
3847
+ * ```
3848
+ */
3849
+ var PendingSwapStore = class {
3850
+ storage;
3851
+ storageKey;
3852
+ darkFlagField;
3853
+ insertAt;
3854
+ listOrder;
3855
+ now;
3856
+ queue = Promise.resolve();
3857
+ constructor(storage, options = {}) {
3858
+ this.storage = storage;
3859
+ this.storageKey = options.storageKey ?? "pendingSwaps.v1";
3860
+ this.darkFlagField = options.darkFlagField ?? "isDarkSwap";
3861
+ this.insertAt = options.insertAt ?? "end";
3862
+ this.listOrder = options.listOrder ?? "stored";
3863
+ this.now = options.now ?? Date.now;
3864
+ }
3865
+ /** Saves (or replaces, by `uniqueKey`) a pending swap. */
3866
+ remember(swap) {
3867
+ return this.enqueue(async (storage) => {
3868
+ const others = (await this.read(storage)).filter((entry) => entry.uniqueKey !== swap.uniqueKey).map(this.toStored);
3869
+ const stored = this.toStored(swap);
3870
+ await storage.set(this.storageKey, this.insertAt === "end" ? [...others, stored] : [stored, ...others]);
3871
+ });
3872
+ }
3873
+ /** Removes a pending swap once its outcome is known. */
3874
+ forget(uniqueKey) {
3875
+ return this.enqueue(async (storage) => {
3876
+ const current = await this.read(storage);
3877
+ await storage.set(this.storageKey, current.filter((entry) => entry.uniqueKey !== uniqueKey).map(this.toStored));
3878
+ });
3879
+ }
3880
+ /** The wallet's unexpired pending swaps (see `listOrder`). Expired entries are pruned. */
3881
+ async list(wallet) {
3882
+ return await this.enqueue(async (storage) => {
3883
+ const current = await this.read(storage);
3884
+ const now = this.now();
3885
+ const fresh = current.filter((entry) => now - entry.createdAt < 6048e5);
3886
+ if (fresh.length !== current.length) await storage.set(this.storageKey, fresh.map(this.toStored));
3887
+ const mine = fresh.filter((entry) => entry.wallet === wallet);
3888
+ return this.listOrder === "newest-first" ? mine.sort((left, right) => right.createdAt - left.createdAt) : mine;
3889
+ }) ?? [];
3890
+ }
3891
+ enqueue(operation) {
3892
+ const storage = this.storage;
3893
+ if (storage === void 0) return Promise.resolve(void 0);
3894
+ const run = this.queue.then(async () => {
3895
+ try {
3896
+ return await operation(storage);
3897
+ } catch {
3898
+ return;
3899
+ }
3900
+ });
3901
+ this.queue = run;
3902
+ return run;
3903
+ }
3904
+ async read(storage) {
3905
+ const value = await storage.get(this.storageKey);
3906
+ if (!Array.isArray(value)) return [];
3907
+ const entries = [];
3908
+ for (const item of value) {
3909
+ const entry = this.fromStored(item);
3910
+ if (entry !== void 0) entries.push(entry);
3911
+ }
3912
+ return entries;
3913
+ }
3914
+ toStored = (swap) => ({
3915
+ uniqueKey: swap.uniqueKey,
3916
+ requestTransactionId: swap.requestTransactionId,
3917
+ wallet: swap.wallet,
3918
+ token0Symbol: swap.token0Symbol,
3919
+ token1Symbol: swap.token1Symbol,
3920
+ [this.darkFlagField]: swap.isDarkSwap,
3921
+ createdAt: swap.createdAt
3922
+ });
3923
+ fromStored(value) {
3924
+ if (value === null || typeof value !== "object") return void 0;
3925
+ const entry = value;
3926
+ const flag = entry[this.darkFlagField];
3927
+ const { uniqueKey, requestTransactionId, wallet, token0Symbol, token1Symbol, createdAt } = entry;
3928
+ if (typeof uniqueKey !== "string" || !(typeof requestTransactionId === "string" || requestTransactionId === null) || typeof wallet !== "string" || typeof token0Symbol !== "string" || typeof token1Symbol !== "string" || typeof flag !== "boolean" || typeof createdAt !== "number" || !Number.isFinite(createdAt)) return;
3929
+ return {
3930
+ uniqueKey,
3931
+ requestTransactionId,
3932
+ wallet,
3933
+ token0Symbol,
3934
+ token1Symbol,
3935
+ isDarkSwap: flag,
3936
+ createdAt
3937
+ };
3938
+ }
3939
+ };
3940
+
2388
3941
  //#endregion
2389
3942
  //#region src/utils/eip712.ts
2390
3943
  /**
3944
+ * Genuine EIP-712 typed-data signing for the four v2 dex-contract operations proven (2026-09-16,
3945
+ * live bisection against stage — see defi-backend's `chain-findings-artifact` memory /
3946
+ * https://claude.ai/artifact/3N9MevSjoQdU7gqnVB3dfU) to recover the `client|` identity correctly
3947
+ * via `eth_signTypedData_v4`, unlike `personal_sign` (which only ever resolves the bare `eth|`
3948
+ * form — see `BrowserWalletSigner`'s own doc comment). Mirrors frontend_v2's
3949
+ * `src/Services/eip712Types.ts` + `readWriteUtilsV2.ts`'s `EIP712_FIELD_COMPLETERS` exactly —
3950
+ * ported here rather than shared as a package because gswap-sdk has no frontend_v2 dependency
3951
+ * and should not gain one for four small functions.
3952
+ */
3953
+ /**
2391
3954
  * Derives the EIP-712 `types` for a DTO from its runtime shape.
2392
3955
  *
2393
3956
  * The generated `types` travel with the signed payload and are what BOTH sides hash, so they
@@ -2452,11 +4015,24 @@ function generateEIP712Types(typeName, params) {
2452
4015
  });
2453
4016
  return types;
2454
4017
  }
2455
- /** Matches every genuine-EIP-712 probe that has actually recovered `client|` on stage. */
2456
- const EIP712_DOMAIN = {
2457
- name: "ethereum",
2458
- chainId: 1
2459
- };
4018
+ /**
4019
+ * Builds the EIP-712 domain from the wallet's LIVE `eth_chainId` result, exactly like frontend_v2
4020
+ * (DEFI-1895): a wallet hashes whatever domain it is handed, and MetaMask refuses a `chainId` that
4021
+ * differs from its active network, so a hardcoded `1` breaks every wallet that is not on Mainnet.
4022
+ * defi-backend recovers the signer from the `domain` the payload carries (live-proven for chain
4023
+ * ids 1, 56 and 11155111), so following the wallet is correct on every network.
4024
+ *
4025
+ * @param chainId - The raw `eth_chainId` result: a `0x` hex string (the JSON-RPC form) or an integer.
4026
+ * @throws GSwapSDKError (`INVALID_CHAIN_ID`) when the wallet answers with anything else.
4027
+ */
4028
+ function eip712DomainFor(chainId) {
4029
+ const parsed = typeof chainId === "string" && /^0x[0-9a-fA-F]+$/u.test(chainId) ? Number(chainId) : typeof chainId === "number" ? chainId : NaN;
4030
+ if (!Number.isSafeInteger(parsed) || parsed <= 0) throw new GSwapSDKError("Wallet returned an invalid chain id.", "INVALID_CHAIN_ID", { chainId });
4031
+ return {
4032
+ name: "ethereum",
4033
+ chainId: parsed
4034
+ };
4035
+ }
2460
4036
  /**
2461
4037
  * The four v2 operations proven to recover the signer correctly via genuine EIP-712: `RequestTrade`
2462
4038
  * never had the problem (one numeric field). `AddLiquidity`/`RemoveLiquidity`/
@@ -2553,15 +4129,216 @@ function buildEIP712Payload(methodName, dto) {
2553
4129
  }
2554
4130
 
2555
4131
  //#endregion
2556
- //#region src/classes/signers.ts
4132
+ //#region src/utils/signing.ts
4133
+ /**
4134
+ * SDK-owned signing primitives.
4135
+ *
4136
+ * Everything the SDK needs to produce a GalaChain signature lives here, with no dependency on
4137
+ * `@gala-chain/api` (which drags `secp256k1` native bindings, `reflect-metadata`, `class-validator`
4138
+ * and its own `bignumber.js` major into every consumer). The only runtime dependencies are the
4139
+ * audited, pure-JS `@noble/curves` (secp256k1) and `@noble/hashes` (keccak256), which run
4140
+ * unchanged in browsers, MV3 service workers, Node and React Native/Hermes.
4141
+ *
4142
+ * Every function here is pinned byte-for-byte to the signatures produced by `@gala-chain/api`
4143
+ * (`serialize`, `signatures.getSignature`), `@gala-chain/connect`, the Gala Wallet extension and
4144
+ * frontend_v2 by the golden-vector suite in `tests/signing-golden.test.ts`.
4145
+ */
4146
+ const textEncoder$1 = new TextEncoder();
4147
+ function toDeterministicNode(node) {
4148
+ if (node === null || node === void 0) return node;
4149
+ if (node instanceof RegExp) return node.toString();
4150
+ const candidate = node;
4151
+ return typeof candidate.toJSON === "function" ? Reflect.apply(candidate.toJSON, node, []) : node;
4152
+ }
4153
+ function deterministicNode(rawNode) {
4154
+ const node = toDeterministicNode(rawNode);
4155
+ if (node === void 0) return void 0;
4156
+ if (typeof node !== "object" || node === null) return JSON.stringify(node);
4157
+ if (Array.isArray(node)) return `[${node.map((item) => deterministicNode(item) ?? "null").join(",")}]`;
4158
+ const record = node;
4159
+ const members = [];
4160
+ for (const key of Object.keys(record).sort()) {
4161
+ const value = deterministicNode(record[key]);
4162
+ if (value === void 0) continue;
4163
+ members.push(`${JSON.stringify(key)}:${value}`);
4164
+ }
4165
+ return `{${members.join(",")}}`;
4166
+ }
4167
+ /**
4168
+ * GalaChain's deterministic JSON: object keys sorted (UTF-16 code-unit order) at every depth, no
4169
+ * whitespace, `undefined`/function members dropped, `toJSON()` honored. Byte-identical to
4170
+ * `serialize` from `@gala-chain/api` / `json-stringify-deterministic` for every JSON-shaped
4171
+ * value, which is all a DTO ever is.
4172
+ *
4173
+ * @throws TypeError for circular structures and BigInt values (as `JSON.stringify` does) and
4174
+ * when the value itself has no JSON representation (`undefined`, a function, a symbol).
4175
+ */
4176
+ function serialize(value) {
4177
+ JSON.stringify(value);
4178
+ const result = deterministicNode(value);
4179
+ if (result === void 0) throw new TypeError("Cannot serialize a value with no JSON representation.");
4180
+ return result;
4181
+ }
4182
+ /**
4183
+ * The exact string GalaChain hashes for a DTO: the (optional, string) `prefix` field PREPENDED to
4184
+ * the deterministic serialization of the DTO WITHOUT `signature`, `multisig`, `trace` and `prefix`.
4185
+ * Equivalent to `@gala-chain/api` 3.x `getPayloadToSign` for every non-EIP-712 DTO.
4186
+ */
4187
+ function getPayloadToSign(dto) {
4188
+ const { prefix, ...rest } = dto;
4189
+ delete rest["signature"];
4190
+ delete rest["multisig"];
4191
+ delete rest["trace"];
4192
+ return (typeof prefix === "string" ? prefix : "") + serialize(rest);
4193
+ }
2557
4194
  const ETHEREUM_SIGNED_MESSAGE = String.fromCharCode(25) + "Ethereum Signed Message:\n";
2558
- /** The EIP-191 header for `dto`'s canonical JSON (UTF-8 byte length; any `prefix` on it is ignored). */
4195
+ /**
4196
+ * The EIP-191 header for `message`: `"\x19Ethereum Signed Message:\n"` + the message's UTF-8 BYTE
4197
+ * length. This is what a wallet's `personal_sign` prepends, and what the chain recomputes when it
4198
+ * recovers a personal-signed DTO.
4199
+ */
4200
+ function calculatePersonalSignPrefix(message) {
4201
+ return ETHEREUM_SIGNED_MESSAGE + String(textEncoder$1.encode(message).length);
4202
+ }
4203
+ /**
4204
+ * The EIP-191 header for `serialize(dto)` (any `prefix` already on the DTO is ignored). This is
4205
+ * deliberately the same string the signers hand a wallet to sign, so the header's length can never
4206
+ * disagree with the signed message. Wallet-neutral: it is the value both a browser wallet's
4207
+ * `personal_sign` and Gala Wallet's `gala_signChainDto` (personal-sign scheme) prepend.
4208
+ */
2559
4209
  function personalSignPrefixFor(dto) {
2560
4210
  const withoutPrefix = { ...dto };
2561
4211
  delete withoutPrefix["prefix"];
2562
- const message = serialize(withoutPrefix);
2563
- return ETHEREUM_SIGNED_MESSAGE + String(new TextEncoder().encode(message).length);
4212
+ return calculatePersonalSignPrefix(serialize(withoutPrefix));
4213
+ }
4214
+ /**
4215
+ * The `@gala-chain/connect`-style prefix frontend_v2 puts in the body of an EIP-712 write: the
4216
+ * EIP-191 header whose number counts the prefix string ITSELF plus the body (the UTF-8 length of
4217
+ * `getPayloadToSign({ ...dto, prefix })`), found by fixpoint because adding the prefix changes the
4218
+ * length (a body of 99 bytes settles on 101).
4219
+ *
4220
+ * It is NOT a personal-sign prefix (a personal-sign write with this value recovers a phantom
4221
+ * signer; use `personalSignPrefixFor`). Under EIP-712 the field is an untyped extra that the
4222
+ * typed-data hash ignores and defi-backend recomputes, so it only exists to keep the submitted
4223
+ * body byte-identical to what frontend_v2 has always sent.
4224
+ */
4225
+ function fixpointPrefixFor(dto) {
4226
+ const withoutPrefix = { ...dto };
4227
+ delete withoutPrefix["prefix"];
4228
+ let payloadLength = textEncoder$1.encode(getPayloadToSign(withoutPrefix)).length;
4229
+ let prefix = ETHEREUM_SIGNED_MESSAGE + String(payloadLength);
4230
+ let previousLength = -1;
4231
+ while (payloadLength !== previousLength) {
4232
+ previousLength = payloadLength;
4233
+ prefix = ETHEREUM_SIGNED_MESSAGE + String(payloadLength);
4234
+ payloadLength = textEncoder$1.encode(getPayloadToSign({
4235
+ ...withoutPrefix,
4236
+ prefix
4237
+ })).length;
4238
+ }
4239
+ return prefix;
4240
+ }
4241
+ function invalidPrivateKey(reason) {
4242
+ return new GSwapSDKError(`Invalid private key: ${reason}`, "VALIDATION_ERROR", { type: "INVALID_PRIVATE_KEY" });
4243
+ }
4244
+ const BASE64_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
4245
+ function decodeBase64(input) {
4246
+ if (!/^[A-Za-z0-9+/]+={0,2}$/u.test(input) || input.length % 4 !== 0) return void 0;
4247
+ const unpadded = input.replace(/=+$/u, "");
4248
+ const bytes = [];
4249
+ let buffer = 0;
4250
+ let bits = 0;
4251
+ for (const char of unpadded) {
4252
+ buffer = buffer << 6 | BASE64_ALPHABET.indexOf(char);
4253
+ bits += 6;
4254
+ if (bits >= 8) {
4255
+ bits -= 8;
4256
+ bytes.push(buffer >> bits & 255);
4257
+ }
4258
+ }
4259
+ return Uint8Array.from(bytes);
4260
+ }
4261
+ function decodeHex(input) {
4262
+ const bytes = new Uint8Array(input.length / 2);
4263
+ for (let index = 0; index < bytes.length; index += 1) bytes[index] = parseInt(input.slice(index * 2, index * 2 + 2), 16);
4264
+ return bytes;
4265
+ }
4266
+ /**
4267
+ * Normalizes a secp256k1 private key to a fresh 32-byte array (the caller may zero it). Also
4268
+ * accepts 32 raw bytes, which are validated and copied. For strings it accepts what `@gala-chain/api`'s
4269
+ * `normalizePrivateKey` accepted for a usable key: 64 hex characters (optionally `0x`-prefixed;
4270
+ * a 63-character hex key is left-padded with a zero) or a 44-character base64 string.
4271
+ *
4272
+ * @throws GSwapSDKError (`VALIDATION_ERROR`) for any other shape or an out-of-range scalar.
4273
+ */
4274
+ function normalizePrivateKey(input) {
4275
+ if (typeof input !== "string") {
4276
+ if (!(input instanceof Uint8Array) || input.length !== 32) throw invalidPrivateKey("expected exactly 32 bytes.");
4277
+ if (!secp256k1.utils.isValidSecretKey(input)) throw invalidPrivateKey("not a valid secp256k1 scalar.");
4278
+ return Uint8Array.from(input);
4279
+ }
4280
+ const withoutPrefix = input.startsWith("0x") ? input.slice(2) : input;
4281
+ let key;
4282
+ if (/^[0-9a-fA-F]{63,64}$/u.test(withoutPrefix)) key = decodeHex(withoutPrefix.length === 63 ? `0${withoutPrefix}` : withoutPrefix);
4283
+ else if (withoutPrefix.length === 44) key = decodeBase64(withoutPrefix);
4284
+ if ((key === null || key === void 0 ? void 0 : key.length) !== 32) throw invalidPrivateKey("expected 64 hex characters or a 44-character base64 string.");
4285
+ if (!secp256k1.utils.isValidSecretKey(key)) throw invalidPrivateKey("not a valid secp256k1 scalar.");
4286
+ return key;
4287
+ }
4288
+ /**
4289
+ * Signs a 32-byte keccak256 hash and returns GalaChain's recoverable signature: 64 hex `r` +
4290
+ * 64 hex `s` + `1b`/`1c` (`v`), lowercase, no `0x`. Deterministic (RFC 6979) and low-S, exactly
4291
+ * what `@gala-chain/api` and the Gala Wallet produce. A DER signature carries no recovery byte
4292
+ * and cannot be used: the chain RECOVERS the signer from the signature.
4293
+ */
4294
+ function signHash(privateKey, hash) {
4295
+ if (hash.length !== 32) throw new GSwapSDKError(`secp256k1 can only sign a 32-byte hash (got ${hash.length}).`, "VALIDATION_ERROR");
4296
+ const signature = secp256k1.sign(hash, privateKey, {
4297
+ prehash: false,
4298
+ lowS: true
4299
+ });
4300
+ return bytesToHex(signature.toBytes("compact")) + (signature.recovery === 1 ? "1c" : "1b");
2564
4301
  }
4302
+ /**
4303
+ * The lowercase `0x` Ethereum address (last 20 bytes of keccak256 of the uncompressed public key)
4304
+ * of a normalized private key. The Gala `eth|` identity of a key is this address.
4305
+ */
4306
+ function ethAddressOfPrivateKey(privateKey) {
4307
+ const publicKey = secp256k1.getPublicKey(privateKey, false);
4308
+ return `0x${bytesToHex(keccak_256(publicKey.slice(1)).slice(-20))}`;
4309
+ }
4310
+ /** keccak256 of a string's UTF-8 bytes. */
4311
+ function keccak256Utf8(data) {
4312
+ return keccak_256(textEncoder$1.encode(data));
4313
+ }
4314
+ /**
4315
+ * GalaChain NATIVE signature over an already-serialized DTO: keccak256 of the exact bytes, with no
4316
+ * prefix and no signature envelope. The caller owns serialization, so the bytes shown to a user
4317
+ * and the bytes signed can never diverge.
4318
+ */
4319
+ function signSerializedNative(privateKey, serializedDto) {
4320
+ return signHash(privateKey, keccak256Utf8(serializedDto));
4321
+ }
4322
+ /**
4323
+ * GalaChain NATIVE signature for a DTO: keccak256 of `getPayloadToSign(dto)`, signed with
4324
+ * secp256k1. Byte-identical to `signatures.getSignature` from `@gala-chain/api`.
4325
+ */
4326
+ function signNative(privateKey, dto) {
4327
+ return signSerializedNative(privateKey, getPayloadToSign(dto));
4328
+ }
4329
+ /**
4330
+ * Personal-sign hash and signature: keccak256(`prefix` + `message`), both hashed VERBATIM with no
4331
+ * further EIP-191 wrapping. Passing `prefix = calculatePersonalSignPrefix(message)` reproduces a
4332
+ * wallet's `personal_sign` of `message`. Gala Wallet's `gala_signChainDto` (personal-sign
4333
+ * scheme) hashes `prefix` + the exact string it is handed, which can differ from the bare message
4334
+ * (see the `signatureOverPrefixlessBody` vectors); that quirk is why the two inputs stay separate.
4335
+ */
4336
+ function signPersonalMessage(privateKey, prefix, message) {
4337
+ return signHash(privateKey, keccak256Utf8(prefix + message));
4338
+ }
4339
+
4340
+ //#endregion
4341
+ //#region src/classes/signers.ts
2565
4342
  function getWalletProvider() {
2566
4343
  var _globalObject$window;
2567
4344
  const wallet = (_globalObject$window = globalThis.window) === null || _globalObject$window === void 0 ? void 0 : _globalObject$window.gala;
@@ -2570,7 +4347,7 @@ function getWalletProvider() {
2570
4347
  }
2571
4348
  function getNativeSignature(value) {
2572
4349
  if (typeof value !== "string") throw new GSwapSDKError("Wallet returned an invalid signature.", "INVALID_SIGNATURE");
2573
- if (!/^[0-9a-fA-F]{130}$/u.test(value)) throw new GSwapSDKError("Wallet returned an invalid native signature.", "INVALID_SIGNATURE");
4350
+ if (!/^(?:0x)?[0-9a-fA-F]{130}$/u.test(value)) throw new GSwapSDKError("Wallet returned an invalid native signature.", "INVALID_SIGNATURE");
2574
4351
  return value;
2575
4352
  }
2576
4353
  function getPersonalSignature(value) {
@@ -2583,19 +4360,48 @@ function normalizeEthereumAccount(address, allowGalaPrefix) {
2583
4360
  type: "INVALID_WALLET_ADDRESS",
2584
4361
  value: address
2585
4362
  });
2586
- return `0x${normalized.slice(2).toLowerCase()}`;
4363
+ return normalized;
2587
4364
  }
2588
- function getErrorMessage(error) {
2589
- if (error instanceof Error) return error.message;
2590
- if (typeof error === "string") return error;
2591
- if (typeof error === "object" && error !== null && "message" in error) {
2592
- const message = error.message;
2593
- return typeof message === "string" ? message : "";
2594
- }
2595
- return "";
4365
+ /**
4366
+ * The account handed to Gala Wallet as the signer address. An Ethereum account is held to the
4367
+ * same strict check as ever (`0x` plus 40 hex digits; `eth|` plus 40 hex digits, with or without
4368
+ * `0x`, is normalized to it). A GalaChain id the wallet can also be asked to sign for is passed
4369
+ * through verbatim: `client|` plus 24 hex digits, or the bare 24 hex digits that frontend_v2 keeps
4370
+ * in `state.user.wallet` after a direct `client|` login. Nothing else is accepted.
4371
+ */
4372
+ function normalizeGalaWalletAccount(address) {
4373
+ const eth = /^eth\|(?:0x)?([0-9a-fA-F]{40})$/u.exec(address);
4374
+ if ((eth === null || eth === void 0 ? void 0 : eth[1]) !== void 0) return `0x${eth[1]}`;
4375
+ if (/^0x[0-9a-fA-F]{40}$/u.test(address) || /^(?:client\|)?[0-9a-fA-F]{24}$/u.test(address)) return address;
4376
+ throw new GSwapSDKError("Wallet address must be the selected Ethereum account (0x plus 40 hex digits, or eth|...) or a GalaChain id (client|... or 24 hex digits).", "VALIDATION_ERROR", {
4377
+ type: "INVALID_WALLET_ADDRESS",
4378
+ value: address
4379
+ });
4380
+ }
4381
+ /** An identity Gala Wallet can act as: an account form above, any `eth|`/`client|` alias, verbatim. */
4382
+ function assertWalletIdentity(identity) {
4383
+ if (!/^(?:eth\|(?:0x)?[0-9a-fA-F]{40}|0x[0-9a-fA-F]{40}|(?:client\|)?[0-9a-fA-F]{24})$/u.test(identity)) throw new GSwapSDKError("selectAddress must be an eth| or client| identity, or an account in one of the accepted forms.", "VALIDATION_ERROR", {
4384
+ type: "INVALID_WALLET_ADDRESS",
4385
+ value: identity
4386
+ });
2596
4387
  }
2597
- function isUnsupportedNativeSchemeError(error) {
2598
- return /unsupported|unknown scheme/i.test(getErrorMessage(error));
4388
+ /** Provider-wide queue: `setAddress` + the signature request must not interleave across signers. */
4389
+ const walletIdentityQueue = /* @__PURE__ */ new WeakMap();
4390
+ /**
4391
+ * Runs `signWith` with `identity` selected on a Gala Wallet that supports `setAddress`. Gala
4392
+ * Wallet holds ONE current account, so two signatures for different identities in flight at once
4393
+ * would sign as whichever selection came last; the pair (select, sign) is therefore serialized
4394
+ * per provider. A failed selection fails the signature (nothing is requested).
4395
+ */
4396
+ function withSelectedIdentity(wallet, identity, signWith) {
4397
+ const { setAddress } = wallet;
4398
+ if (identity === void 0 || typeof setAddress !== "function") return signWith();
4399
+ const run = (walletIdentityQueue.get(wallet) ?? Promise.resolve()).catch(() => void 0).then(async () => {
4400
+ await setAddress.call(wallet, identity);
4401
+ return signWith();
4402
+ });
4403
+ walletIdentityQueue.set(wallet, run);
4404
+ return run;
2599
4405
  }
2600
4406
  function personalSign(provider, dto, walletAddress, methodName) {
2601
4407
  const prefix = personalSignPrefixFor(dto);
@@ -2626,9 +4432,13 @@ function personalSign(provider, dto, walletAddress, methodName) {
2626
4432
  * byte-for-byte equivalent (same recovered address from the same signature against both
2627
4433
  * constructions) before this shipped, since gswap-sdk deliberately has no ethers dependency.
2628
4434
  */
2629
- function signEIP712(provider, methodName, dto, walletAddress) {
4435
+ async function signEIP712(provider, methodName, dto, walletAddress) {
2630
4436
  const { completedDto, types } = buildEIP712Payload(methodName, dto);
2631
- const prefix = personalSignPrefixFor(completedDto);
4437
+ const domain = eip712DomainFor(await provider.request({
4438
+ method: "eth_chainId",
4439
+ params: []
4440
+ }));
4441
+ const prefix = fixpointPrefixFor(completedDto);
2632
4442
  const message = {
2633
4443
  ...completedDto,
2634
4444
  prefix
@@ -2641,7 +4451,7 @@ function signEIP712(provider, methodName, dto, walletAddress) {
2641
4451
  type: "uint256"
2642
4452
  }];
2643
4453
  const payload = {
2644
- domain: EIP712_DOMAIN,
4454
+ domain,
2645
4455
  types: {
2646
4456
  ...types,
2647
4457
  EIP712Domain: eip712Domain
@@ -2649,15 +4459,16 @@ function signEIP712(provider, methodName, dto, walletAddress) {
2649
4459
  primaryType: methodName,
2650
4460
  message
2651
4461
  };
2652
- return provider.request({
4462
+ const value = await provider.request({
2653
4463
  method: "eth_signTypedData_v4",
2654
4464
  params: [walletAddress, JSON.stringify(payload)]
2655
- }).then((value) => ({
4465
+ });
4466
+ return {
2656
4467
  ...message,
4468
+ signature: getPersonalSignature(value),
2657
4469
  types,
2658
- domain: EIP712_DOMAIN,
2659
- signature: getPersonalSignature(value)
2660
- }));
4470
+ domain
4471
+ };
2661
4472
  }
2662
4473
  /**
2663
4474
  * A GalaChain native signer backed by a secp256k1 private key.
@@ -2666,7 +4477,7 @@ function signEIP712(provider, methodName, dto, walletAddress) {
2666
4477
  * or EIP-712 metadata. The private-key identity is recovered by the chain.
2667
4478
  */
2668
4479
  var PrivateKeySigner = class {
2669
- keyBuffer;
4480
+ privateKey;
2670
4481
  /**
2671
4482
  * Creates a native signer from a hex or base64 secp256k1 private key.
2672
4483
  *
@@ -2677,7 +4488,7 @@ var PrivateKeySigner = class {
2677
4488
  * ```
2678
4489
  */
2679
4490
  constructor(privateKey) {
2680
- this.keyBuffer = signatures.normalizePrivateKey(privateKey);
4491
+ this.privateKey = normalizePrivateKey(privateKey);
2681
4492
  }
2682
4493
  /**
2683
4494
  * Signs the DTO with GalaChain native signing.
@@ -2692,7 +4503,7 @@ var PrivateKeySigner = class {
2692
4503
  * ```
2693
4504
  */
2694
4505
  signObject(_methodName, dto) {
2695
- const signature = signatures.getSignature(dto, this.keyBuffer);
4506
+ const signature = signNative(this.privateKey, dto);
2696
4507
  return Promise.resolve({
2697
4508
  ...dto,
2698
4509
  signature
@@ -2700,18 +4511,66 @@ var PrivateKeySigner = class {
2700
4511
  }
2701
4512
  };
2702
4513
  /**
2703
- * A Gala Wallet signer using native GalaChain signing, with an opt-in personal-sign mode and
2704
- * automatic fallback for older wallets.
4514
+ * Creates the native-signing equivalent of {@link PrivateKeySigner} for apps that must not hold a
4515
+ * key in a long-lived object (an extension that reads its session key at sign time).
4516
+ *
4517
+ * `getPrivateKey` is called once per `signObject` call, never cached, never shared between calls
4518
+ * (concurrent signatures each fetch their own key), and the normalized key bytes are zeroed
4519
+ * before `signObject` settles, also on failure. A rejection or exception from `getPrivateKey` is
4520
+ * passed through unchanged, so the app's own "wallet is locked" error reaches its caller; a key
4521
+ * that is not a valid secp256k1 key string is a `VALIDATION_ERROR` (`INVALID_PRIVATE_KEY`).
4522
+ * Signatures are byte-identical to `new PrivateKeySigner(key).signObject(...)`.
4523
+ *
4524
+ * A JavaScript string cannot be wiped; the provider owns the lifetime of the string it returns.
4525
+ *
4526
+ * @example
4527
+ * ```typescript
4528
+ * const signer = createLazyPrivateKeySigner(
4529
+ * () => SecurityHelper.getSessionSecret(SecurityHelper.SESSION_PRIVATE_KEY_KEY),
4530
+ * { expectedAddress: account.address },
4531
+ * );
4532
+ * const gswap = new GSwap({ signer });
4533
+ * ```
4534
+ */
4535
+ function createLazyPrivateKeySigner(getPrivateKey, options = {}) {
4536
+ const expected = options.expectedAddress;
4537
+ if (expected !== void 0) normalizeEthereumAccount(expected, true);
4538
+ const expectedLower = expected === null || expected === void 0 ? void 0 : expected.replace(/^eth\|/u, "").toLowerCase();
4539
+ return { async signObject(_methodName, dto) {
4540
+ const provided = await getPrivateKey();
4541
+ if (typeof provided !== "string") throw new GSwapSDKError("Invalid private key: the provider returned no key.", "VALIDATION_ERROR", { type: "INVALID_PRIVATE_KEY" });
4542
+ const key = normalizePrivateKey(provided);
4543
+ try {
4544
+ if (expectedLower !== void 0 && ethAddressOfPrivateKey(key) !== expectedLower) throw new GSwapSDKError("The signing key does not belong to the expected account.", "SIGNER_ADDRESS_MISMATCH");
4545
+ return {
4546
+ ...dto,
4547
+ signature: signNative(key, dto)
4548
+ };
4549
+ } finally {
4550
+ key.fill(0);
4551
+ }
4552
+ } };
4553
+ }
4554
+ /**
4555
+ * A Gala Wallet signer using native GalaChain signing, with an opt-in personal-sign mode.
4556
+ *
4557
+ * The selected Ethereum account is passed to Gala Wallet. There is NO automatic fallback: a
4558
+ * wallet that rejects `native` surfaces its error to the caller, because the only alternative,
4559
+ * `personal-sign`, silently recovers a phantom signer on every released Gala Wallet.
2705
4560
  *
2706
- * The selected Ethereum account is passed to Gala Wallet. Personal-sign resolves the bare
2707
- * `eth|` identity; the legacy EIP-712 `eth_signTypedData` path is not used. The fallback calls
2708
- * `gala_signChainDto([serialize({ ...dto, prefix }), walletAddress, methodName])`.
4561
+ * `scheme: 'personal-sign'` calls
4562
+ * `gala_signChainDto([serialize({ ...dto, prefix }), walletAddress, methodName])` and REQUIRES
4563
+ * a wallet build that contains wallet_extension commit 3ad7ae6 (strips the embedded `prefix`
4564
+ * field and hashes `prefix` + the prefix-less canonical body, the chain's scheme). Wallets
4565
+ * released before that fix hash the string with the `prefix` field still inside it and the
4566
+ * signature recovers to an address nobody holds, so only opt in once the fixed wallet is
4567
+ * released. See SIGNING-PARITY.md.
2709
4568
  */
2710
4569
  var GalaWalletSigner = class {
2711
4570
  /** The wallet address supplied to Gala Wallet for each signing request. */
2712
4571
  walletAddress;
2713
- /** The scheme currently used, including any automatic native-to-personal fallback. */
2714
- effectiveScheme;
4572
+ /** The signing scheme used for every request; it never changes after construction. */
4573
+ scheme;
2715
4574
  /**
2716
4575
  * Creates a Gala Wallet signer.
2717
4576
  *
@@ -2721,14 +4580,23 @@ var GalaWalletSigner = class {
2721
4580
  * const signed = await signer.signObject('RequestTrade', { token0: 'GALA', token1: 'GUSDC' });
2722
4581
  * ```
2723
4582
  *
2724
- * @param walletAddress - The selected Ethereum account (`0x` plus 40 hex digits); Gala Wallet's
2725
- * `eth|0x...` form is also accepted and normalized.
2726
- * @param options - Select native signing or personal-sign explicitly.
4583
+ * @param walletAddress - The account passed to Gala Wallet as the signer address. An Ethereum
4584
+ * account is `0x` plus 40 hex digits (Gala Wallet's `eth|...` form is normalized to it and held
4585
+ * to the same check); a GalaChain id is `client|` plus 24 hex digits, or the bare 24 hex digits
4586
+ * frontend_v2 keeps for a direct `client|` login, and is passed through unchanged.
4587
+ * @param options - Select native signing (default) or personal-sign explicitly.
4588
+ * `'personal-sign'` requires a Gala Wallet build with wallet_extension commit 3ad7ae6.
4589
+ * `selectAddress` is the identity (`client|...` / `eth|...`) Gala Wallet is switched to with
4590
+ * `window.gala.setAddress` before every signature, when the wallet offers it.
2727
4591
  */
2728
4592
  constructor(walletAddress, options = {}) {
2729
- this.walletAddress = normalizeEthereumAccount(walletAddress, true);
2730
- this.effectiveScheme = options.scheme ?? "native";
4593
+ this.walletAddress = normalizeGalaWalletAccount(walletAddress);
4594
+ this.scheme = options.scheme ?? "native";
4595
+ if (options.selectAddress !== void 0) assertWalletIdentity(options.selectAddress);
4596
+ this.selectAddress = options.selectAddress;
2731
4597
  }
4598
+ /** The identity Gala Wallet is switched to before each signature, if one was given. */
4599
+ selectAddress;
2732
4600
  /**
2733
4601
  * Signs a DTO through `gala_signChainDto`.
2734
4602
  *
@@ -2744,8 +4612,8 @@ var GalaWalletSigner = class {
2744
4612
  */
2745
4613
  async signObject(methodName, dto) {
2746
4614
  const wallet = getWalletProvider();
2747
- if (this.effectiveScheme === "personal-sign") return personalSign(wallet, dto, this.walletAddress, methodName);
2748
- try {
4615
+ return withSelectedIdentity(wallet, this.selectAddress, async () => {
4616
+ if (this.scheme === "personal-sign") return personalSign(wallet, dto, this.walletAddress, methodName);
2749
4617
  const signature = await wallet.request({
2750
4618
  method: "gala_signChainDto",
2751
4619
  params: [
@@ -2759,11 +4627,7 @@ var GalaWalletSigner = class {
2759
4627
  ...dto,
2760
4628
  signature: getNativeSignature(signature)
2761
4629
  };
2762
- } catch (error) {
2763
- if (!isUnsupportedNativeSchemeError(error)) throw error;
2764
- this.effectiveScheme = "personal-sign";
2765
- return personalSign(wallet, dto, this.walletAddress, methodName);
2766
- }
4630
+ });
2767
4631
  }
2768
4632
  };
2769
4633
  /**
@@ -2825,5 +4689,476 @@ var BrowserWalletSigner = class {
2825
4689
  };
2826
4690
 
2827
4691
  //#endregion
2828
- export { ALL_FEE_TIERS, Assets, BrowserWalletSigner, ChainGateway, FEE_TIER, GC_MAX_TICK, GC_MIN_TICK, GSWAP_ENVIRONMENTS, GSwap, GSwapSDKError, GalaWalletSigner, GdexStreamError, GdexStreamService, Pools, Positions, PrivateKeySigner, Quoting, SubmittedTransaction, Swaps, Symbols, TICK_SPACING_BY_FEE, alignTickDown, alignTickUp, assertTickRange, compositeKeyOf, getObjectProperty, getStringProperty, isGdexLiquidityEvent, orderSymbols, parseJson, parseTokenClassKey, readOrderedSymbols, sqrtPriceToTick, tickFromPrice, tickToSqrtPrice, validateFee, validateNumericAmount, validatePriceValues, validateTickRange, validateTickSpacing, validateTokenDecimals, validateWalletAddress };
4692
+ //#region src/utils/chain_dto_signing.ts
4693
+ /**
4694
+ * String-key signing entry points for apps that hold a private key only briefly (the Gala Wallet
4695
+ * extension reads its session key at sign time and must not keep it in a long-lived object).
4696
+ *
4697
+ * These are thin, byte-exact ports of the functions the wallet shipped in
4698
+ * `wallet_extension/src/helpers/wallet/signing.ts` (including the fail-closed personal-sign
4699
+ * payload resolver from its commit 3ad7ae6), re-expressed over the SDK's own primitives. Every
4700
+ * function takes the key as a string (`0x`-optional hex, or base64) or as bytes, normalizes it per
4701
+ * call, and zeroes the normalized copy before returning, so nothing in this module retains a key.
4702
+ * A JavaScript string cannot be wiped; the caller owns the lifetime of the string it passes in.
4703
+ */
4704
+ /**
4705
+ * Runs `action` with a private normalized copy of the key, zeroed afterwards (also when `action`
4706
+ * throws). Bytes given by the caller are copied, never modified: the caller owns them.
4707
+ */
4708
+ function withPrivateKey(privateKey, action) {
4709
+ const key = normalizePrivateKey(privateKey);
4710
+ try {
4711
+ return action(key);
4712
+ } finally {
4713
+ key.fill(0);
4714
+ }
4715
+ }
4716
+ /**
4717
+ * GalaChain NATIVE signature over an already-serialized DTO: keccak256 of the exact bytes with no
4718
+ * prefix and no envelope (wallet `signChainDtoNative`). The caller owns serialization, so the
4719
+ * bytes a user reviewed and the bytes signed cannot diverge.
4720
+ *
4721
+ * @returns 130 lowercase hex characters, `r || s || v` with `v` = `1b`/`1c`, no `0x`.
4722
+ */
4723
+ function signChainDtoNative(privateKey, serializedDto) {
4724
+ return withPrivateKey(privateKey, (key) => signSerializedNative(key, serializedDto));
4725
+ }
4726
+ /**
4727
+ * The personal-sign hash primitive (wallet `signChainDtoHash`): keccak256(`prefix` + `message`),
4728
+ * both verbatim, with no further EIP-191 wrap. `message` must be the DTO's serialization WITHOUT
4729
+ * its `prefix` field; callers holding a dApp-supplied string go through `signChainDtoPersonalSign`,
4730
+ * which derives both inputs from it.
4731
+ */
4732
+ function signChainDtoHash(privateKey, prefix, message) {
4733
+ return withPrivateKey(privateKey, (key) => signPersonalMessage(key, prefix, message));
4734
+ }
4735
+ const PERSONAL_SIGN_HEADER = String.fromCharCode(25) + "Ethereum Signed Message:\n";
4736
+ const PERSONAL_SIGN_LENGTH_PATTERN = /^(?:0|[1-9][0-9]*)$/u;
4737
+ function isPersonalSignHeader(prefix) {
4738
+ return prefix.startsWith(PERSONAL_SIGN_HEADER) && PERSONAL_SIGN_LENGTH_PATTERN.test(prefix.slice(26));
4739
+ }
4740
+ /**
4741
+ * Top-level fields that would make the chain (`getPayloadToSign`) or defi-backend's personal-sign
4742
+ * verifier hash something other than `prefix + serialize(dto minus prefix)`. An unsigned DTO from
4743
+ * a dApp never legitimately carries any of them, so they fail closed. Order is part of the error
4744
+ * message the wallet shows its user.
4745
+ */
4746
+ const PERSONAL_SIGN_FORBIDDEN_FIELDS = [
4747
+ "signature",
4748
+ "multisig",
4749
+ "trace",
4750
+ "types",
4751
+ "domain",
4752
+ "stringsInstructions"
4753
+ ];
4754
+ function refusePersonalSign(message, type) {
4755
+ throw new GSwapSDKError(message, "INVALID_PERSONAL_SIGN_DTO", { type });
4756
+ }
4757
+ /**
4758
+ * Derives what to hash for a `gala_signChainDto` personal-sign request from the exact string the
4759
+ * dApp sent (and the approval card displayed): wallet `resolvePersonalSignChainDtoPayload`.
4760
+ *
4761
+ * The dApp submits `{ ...dto, prefix, signature }`, which the chain recovers from
4762
+ * `keccak256(prefix + serialize(dto WITHOUT prefix))`. So when the string embeds a `prefix`
4763
+ * field, that field is removed and the remainder re-serialized; the prefix used is the dApp's own
4764
+ * value byte for byte. A string with no `prefix` field is hashed verbatim with an empty prefix
4765
+ * (chain-equivalent to a native signature of that exact string).
4766
+ *
4767
+ * Fails closed (throws `GSwapSDKError` `INVALID_PERSONAL_SIGN_DTO`, message text identical to the
4768
+ * wallet's) on: malformed JSON; JSON that is not a plain object; a `prefix` that is not an EIP-191
4769
+ * "Ethereum Signed Message" header; any signing-envelope field (`signature`, `multisig`, `trace`,
4770
+ * `types`, `domain`, `stringsInstructions`); and a string that is not already the canonical
4771
+ * serialization of what it parses to (duplicate keys, lossy numbers, key-order tricks the card
4772
+ * would render differently). Stripping `prefix` is therefore the ONLY byte change between the
4773
+ * reviewed string and the signed message.
4774
+ */
4775
+ function resolvePersonalSignChainDtoPayload(data) {
4776
+ let parsed;
4777
+ try {
4778
+ parsed = JSON.parse(data);
4779
+ } catch {
4780
+ return refusePersonalSign("Personal-sign DTO is not valid JSON", "NOT_JSON");
4781
+ }
4782
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) return refusePersonalSign("Personal-sign DTO must be a JSON object", "NOT_OBJECT");
4783
+ const dto = parsed;
4784
+ if (!Object.prototype.hasOwnProperty.call(dto, "prefix")) return {
4785
+ prefix: "",
4786
+ message: data
4787
+ };
4788
+ const { prefix, ...withoutPrefix } = dto;
4789
+ if (typeof prefix !== "string" || !isPersonalSignHeader(prefix)) return refusePersonalSign("Personal-sign DTO prefix is not an EIP-191 \"Ethereum Signed Message\" header", "BAD_PREFIX");
4790
+ const forbidden = PERSONAL_SIGN_FORBIDDEN_FIELDS.filter((field) => Object.prototype.hasOwnProperty.call(withoutPrefix, field));
4791
+ if (forbidden.length > 0) return refusePersonalSign(`Personal-sign DTO carries signing-envelope field(s): ${forbidden.join(", ")}`, "ENVELOPE_FIELDS");
4792
+ if (serialize(dto) !== data) return refusePersonalSign("Personal-sign DTO is not in canonical serialized form", "NOT_CANONICAL");
4793
+ return {
4794
+ prefix,
4795
+ message: serialize(withoutPrefix)
4796
+ };
4797
+ }
4798
+ /**
4799
+ * Signs a GalaChain personal-sign scheme DTO from the exact string a dApp sent through
4800
+ * `gala_signChainDto` (wallet `signChainDtoPersonalSign`). See
4801
+ * `resolvePersonalSignChainDtoPayload` for what is signed and what is refused; the signature
4802
+ * recovers, under the chain's `getPayloadToSign`, to this key for the DTO the dApp submits with
4803
+ * its `prefix`, and equals a `personal_sign` of the bare body when that prefix is the EIP-191
4804
+ * header of the bare body's byte length.
4805
+ *
4806
+ * @throws GSwapSDKError (`INVALID_PERSONAL_SIGN_DTO`) before any signing when the input is refused.
4807
+ */
4808
+ function signChainDtoPersonalSign(privateKey, data) {
4809
+ const { prefix, message } = resolvePersonalSignChainDtoPayload(data);
4810
+ return signChainDtoHash(privateKey, prefix, message);
4811
+ }
4812
+ /**
4813
+ * Raw object signing (wallet `signObject`), used for transfers, bridge and fee-dry-run DTOs the
4814
+ * wallet signs itself. Removes ONLY `signature`, signs `keccak256(serialize(rest))` natively
4815
+ * (no `prefix` handling, and `trace` / `multisig` stay in the signed bytes, unlike
4816
+ * `signNative`), and returns `{ signature, ...rest }` with the signature as the FIRST key, exactly
4817
+ * like the wallet. Callers that must not sign extra fields strip them first.
4818
+ */
4819
+ function signRawObject(privateKey, obj) {
4820
+ const rest = { ...obj };
4821
+ delete rest["signature"];
4822
+ return {
4823
+ signature: signChainDtoNative(privateKey, serialize(rest)),
4824
+ ...rest
4825
+ };
4826
+ }
4827
+ /**
4828
+ * Drops the `EIP712Domain` entry from a dApp-supplied types map (a typed-data encoder derives the
4829
+ * domain type itself and rejects an explicit one). The order of the remaining types is preserved.
4830
+ */
4831
+ function stripEip712DomainType(types) {
4832
+ const stripped = {};
4833
+ for (const typeName of Object.keys(types)) if (typeName !== "EIP712Domain") stripped[typeName] = types[typeName];
4834
+ return stripped;
4835
+ }
4836
+ /**
4837
+ * `collection$category$type$additionalKey` for a token-class object (wallet `decodeTokenData`).
4838
+ * Lenient on purpose: any missing or non-string part becomes `''`, so a display layer never
4839
+ * throws on odd input.
4840
+ */
4841
+ function tokenClassDollarKey(token) {
4842
+ const part = (field) => {
4843
+ const value = token === null || token === void 0 ? void 0 : token[field];
4844
+ return typeof value === "string" ? value : "";
4845
+ };
4846
+ return `${part("collection")}$${part("category")}$${part("type")}$${part("additionalKey")}`;
4847
+ }
4848
+ /**
4849
+ * A quantity in the form GalaChain's `IsBigNumber` validator accepts: FIXED notation, no leading
4850
+ * zeros, no trailing decimal zeros (`BigNumber#toFixed()`; never `toString()`, which turns
4851
+ * `0.00000001` into `1e-8`, and never a JS number in between).
4852
+ *
4853
+ * @throws GSwapSDKError (`VALIDATION_ERROR`) for a value that is not a finite number. The wallet's
4854
+ * `cleanNumber` returned the string `'NaN'` there; signing that text can only fail on chain.
4855
+ */
4856
+ function canonicalDecimalString(value) {
4857
+ let parsed = new BigNumber(NaN);
4858
+ try {
4859
+ parsed = new BigNumber(value);
4860
+ } catch {}
4861
+ if (!parsed.isFinite()) throw new GSwapSDKError(`Invalid decimal quantity: ${String(value)}`, "VALIDATION_ERROR", { type: "INVALID_DECIMAL" });
4862
+ return parsed.toFixed();
4863
+ }
4864
+
4865
+ //#endregion
4866
+ //#region src/utils/typed_data.ts
4867
+ /**
4868
+ * EIP-712 (`eth_signTypedData_v4`) hashing and signing for ARBITRARY dApp typed data, built on the
4869
+ * SDK's own primitives (`@noble/curves`, `@noble/hashes`) so a wallet can sign a dApp's typed-data
4870
+ * approval without ethers. It replaces the wallet's `new ethers.Wallet(key).signTypedData(...)`
4871
+ * and is pinned to it: the golden suite reproduces every fixture signature exactly and a seeded
4872
+ * differential fuzz compares the digest and signature with ethers for every supported type.
4873
+ *
4874
+ * Compared with ethers this encoder is deliberately STRICTER (it fails closed rather than coerce):
4875
+ * `bool` accepts only a boolean, numbers accept only safe integers / decimal or `0x` strings,
4876
+ * strings must be well-formed UTF-16, struct values must be objects whose fields are their own
4877
+ * properties, and every struct, field and type name must be a plain identifier. Anything ethers
4878
+ * accepts that is NOT in that set is refused here instead of being signed in a different shape
4879
+ * from what a user reviewed.
4880
+ */
4881
+ const textEncoder = new TextEncoder();
4882
+ const IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/u;
4883
+ const TYPE_SYNTAX = /^([A-Za-z_$][A-Za-z0-9_$]*)((?:\[(?:0|[1-9][0-9]*)?\])*)$/u;
4884
+ const BIGINT_DECIMAL = /^-?[0-9]+$/u;
4885
+ const BIGINT_HEX = /^-?0x[0-9a-fA-F]+$/u;
4886
+ const MAX_UINT256 = (1n << 256n) - 1n;
4887
+ /** The EIP-712 domain members and their types, in the order ethers (and the spec) hash them. */
4888
+ const DOMAIN_FIELDS = [
4889
+ {
4890
+ name: "name",
4891
+ type: "string"
4892
+ },
4893
+ {
4894
+ name: "version",
4895
+ type: "string"
4896
+ },
4897
+ {
4898
+ name: "chainId",
4899
+ type: "uint256"
4900
+ },
4901
+ {
4902
+ name: "verifyingContract",
4903
+ type: "address"
4904
+ },
4905
+ {
4906
+ name: "salt",
4907
+ type: "bytes32"
4908
+ }
4909
+ ];
4910
+ function refuse(message, details) {
4911
+ throw new GSwapSDKError(`Invalid typed data: ${message}`, "INVALID_TYPED_DATA", details);
4912
+ }
4913
+ function concat(parts) {
4914
+ const out = new Uint8Array(parts.reduce((total, part) => total + part.length, 0));
4915
+ let offset = 0;
4916
+ for (const part of parts) {
4917
+ out.set(part, offset);
4918
+ offset += part.length;
4919
+ }
4920
+ return out;
4921
+ }
4922
+ function bigintToWord(value) {
4923
+ const word = /* @__PURE__ */ new Uint8Array(32);
4924
+ let rest = value < 0n ? value + (1n << 256n) : value;
4925
+ if (rest < 0n || rest > MAX_UINT256) return refuse("integer does not fit in 256 bits");
4926
+ for (let index = 31; index >= 0; index -= 1) {
4927
+ word[index] = Number(rest & 255n);
4928
+ rest >>= 8n;
4929
+ }
4930
+ return word;
4931
+ }
4932
+ function hexToBytes(hex) {
4933
+ const body = hex.slice(2);
4934
+ const out = new Uint8Array(body.length / 2);
4935
+ for (let index = 0; index < out.length; index += 1) out[index] = parseInt(body.slice(index * 2, index * 2 + 2), 16);
4936
+ return out;
4937
+ }
4938
+ function toBytes(value, what) {
4939
+ if (value instanceof Uint8Array) return value;
4940
+ if (typeof value === "string" && /^0x(?:[0-9a-fA-F]{2})*$/u.test(value)) return hexToBytes(value);
4941
+ return refuse(`${what} must be an even-length 0x hex string`);
4942
+ }
4943
+ function toBigInt(value, what) {
4944
+ if (typeof value === "bigint") return value;
4945
+ if (typeof value === "number") {
4946
+ if (!Number.isSafeInteger(value)) return refuse(`${what} must be a safe integer`);
4947
+ return BigInt(value);
4948
+ }
4949
+ if (typeof value === "string") {
4950
+ if (BIGINT_DECIMAL.test(value)) return BigInt(value);
4951
+ if (BIGINT_HEX.test(value)) return value.startsWith("-") ? -BigInt(value.slice(1)) : BigInt(value);
4952
+ }
4953
+ return refuse(`${what} must be an integer`);
4954
+ }
4955
+ function utf8(value, what) {
4956
+ if (typeof value !== "string") return refuse(`${what} must be a string`);
4957
+ for (let index = 0; index < value.length; index += 1) {
4958
+ const unit = value.charCodeAt(index);
4959
+ if (unit >= 55296 && unit <= 56319) {
4960
+ const next = value.charCodeAt(index + 1);
4961
+ if (!(next >= 56320 && next <= 57343)) return refuse(`${what} has an unpaired surrogate`);
4962
+ index += 1;
4963
+ } else if (unit >= 56320 && unit <= 57343) return refuse(`${what} has an unpaired surrogate`);
4964
+ }
4965
+ return textEncoder.encode(value);
4966
+ }
4967
+ /** EIP-55: a mixed-case address must carry the right checksum; all-lower / all-upper is accepted. */
4968
+ function addressBytes(value) {
4969
+ if (typeof value !== "string" || !/^0x[0-9a-fA-F]{40}$/u.test(value)) return refuse("address must be 0x followed by 40 hex digits");
4970
+ const digits = value.slice(2);
4971
+ if (/[A-F]/u.test(digits) && /[a-f]/u.test(digits)) {
4972
+ const hash = keccak_256(textEncoder.encode(digits.toLowerCase()));
4973
+ for (let index = 0; index < 40; index += 1) {
4974
+ const nibble = hash[index >> 1] >> (index % 2 === 0 ? 4 : 0) & 15;
4975
+ const char = digits.charAt(index);
4976
+ if (char !== (nibble >= 8 ? char.toUpperCase() : char.toLowerCase())) return refuse("address has a bad checksum");
4977
+ }
4978
+ }
4979
+ return hexToBytes(value);
4980
+ }
4981
+ /** The encoder for a non-struct, non-array type, or undefined when `base` is not one. */
4982
+ function leafEncoder(base) {
4983
+ if (base === "string") return (value) => keccak_256(utf8(value, "string"));
4984
+ if (base === "bytes") return (value) => keccak_256(toBytes(value, "bytes"));
4985
+ if (base === "bool") return (value) => {
4986
+ if (typeof value !== "boolean") return refuse("bool must be a boolean");
4987
+ return bigintToWord(value ? 1n : 0n);
4988
+ };
4989
+ if (base === "address") return (value) => concat([/* @__PURE__ */ new Uint8Array(12), addressBytes(value)]);
4990
+ const fixed = /^bytes([1-9][0-9]?)$/u.exec(base);
4991
+ if (fixed !== null) {
4992
+ const width = Number(fixed[1]);
4993
+ if (width > 32 || String(width) !== fixed[1]) return void 0;
4994
+ return (value) => {
4995
+ const bytes = toBytes(value, base);
4996
+ if (bytes.length !== width) return refuse(`${base} must be exactly ${width} bytes`);
4997
+ return concat([bytes, new Uint8Array(32 - width)]);
4998
+ };
4999
+ }
5000
+ const integer = /^(u?)int([1-9][0-9]*)$/u.exec(base);
5001
+ if (integer !== null) {
5002
+ const width = Number(integer[2]);
5003
+ if (width % 8 !== 0 || width > 256 || String(width) !== integer[2]) return void 0;
5004
+ const signed = integer[1] === "";
5005
+ const lower = signed ? -(1n << BigInt(width - 1)) : 0n;
5006
+ const upper = signed ? (1n << BigInt(width - 1)) - 1n : (1n << BigInt(width)) - 1n;
5007
+ return (value) => {
5008
+ const number = toBigInt(value, base);
5009
+ if (number < lower || number > upper) return refuse(`value out of bounds for ${base}`);
5010
+ return bigintToWord(number);
5011
+ };
5012
+ }
5013
+ }
5014
+ function parseType(type) {
5015
+ const match = TYPE_SYNTAX.exec(type);
5016
+ if (match === null) return refuse(`unsupported type "${type}"`);
5017
+ const dimensions = [...(match[2] ?? "").matchAll(/\[([0-9]*)\]/gu)].map((dimension) => dimension[1] === "" ? -1 : Number(dimension[1]));
5018
+ return {
5019
+ base: match[1],
5020
+ dimensions
5021
+ };
5022
+ }
5023
+ function parseFields(typeName, rawFields) {
5024
+ if (!Array.isArray(rawFields)) return refuse(`type ${typeName} must be a list of fields`);
5025
+ const seen = /* @__PURE__ */ new Set();
5026
+ return rawFields.map((raw) => {
5027
+ const field = raw;
5028
+ if (typeof (field === null || field === void 0 ? void 0 : field.name) !== "string" || typeof field.type !== "string") return refuse(`type ${typeName} has a field without a string name and type`);
5029
+ if (!IDENTIFIER.test(field.name)) return refuse(`invalid field name "${field.name}"`);
5030
+ if (seen.has(field.name)) return refuse(`duplicate field "${field.name}" in ${typeName}`);
5031
+ seen.add(field.name);
5032
+ const parsed = parseType(field.type);
5033
+ const base = parsed.base === "uint" || parsed.base === "int" ? `${parsed.base}256` : parsed.base;
5034
+ return {
5035
+ name: field.name,
5036
+ type: base + field.type.slice(parsed.base.length)
5037
+ };
5038
+ });
5039
+ }
5040
+ /**
5041
+ * Builds the struct encoder for a set of type definitions: validates the type graph (unknown or
5042
+ * circular references, duplicate fields) and infers the primary type as the single type no other
5043
+ * type references, exactly like ethers' `TypedDataEncoder`.
5044
+ */
5045
+ function createStructEncoder(rawTypes) {
5046
+ const names = Object.keys(rawTypes);
5047
+ const fields = /* @__PURE__ */ new Map();
5048
+ for (const name of names) {
5049
+ if (!IDENTIFIER.test(name)) return refuse(`invalid type name "${name}"`);
5050
+ fields.set(name, parseFields(name, rawTypes[name]));
5051
+ }
5052
+ const children = /* @__PURE__ */ new Map();
5053
+ const parents = /* @__PURE__ */ new Map();
5054
+ for (const name of names) {
5055
+ children.set(name, /* @__PURE__ */ new Set());
5056
+ parents.set(name, /* @__PURE__ */ new Set());
5057
+ }
5058
+ for (const [name, list] of fields) for (const field of list) {
5059
+ var _children$get, _parents$get;
5060
+ const { base } = parseType(field.type);
5061
+ if (base === name) return refuse(`circular type reference in ${name}`);
5062
+ if (leafEncoder(base) !== void 0) continue;
5063
+ if (!fields.has(base)) return refuse(`unknown type "${base}" in ${name}`);
5064
+ (_children$get = children.get(name)) === null || _children$get === void 0 || _children$get.add(base);
5065
+ (_parents$get = parents.get(base)) === null || _parents$get === void 0 || _parents$get.add(name);
5066
+ }
5067
+ const roots = names.filter((name) => {
5068
+ var _parents$get2;
5069
+ return ((_parents$get2 = parents.get(name)) === null || _parents$get2 === void 0 ? void 0 : _parents$get2.size) === 0;
5070
+ });
5071
+ if (roots.length === 0) return refuse("missing primary type");
5072
+ if (roots.length > 1) return refuse("ambiguous primary types or unused types", { roots });
5073
+ const primaryType = roots[0];
5074
+ const visiting = /* @__PURE__ */ new Set();
5075
+ const checked = /* @__PURE__ */ new Set();
5076
+ const checkCircular = (name) => {
5077
+ if (visiting.has(name)) return refuse(`circular type reference at ${name}`);
5078
+ if (checked.has(name)) return;
5079
+ visiting.add(name);
5080
+ for (const child of children.get(name) ?? []) checkCircular(child);
5081
+ visiting.delete(name);
5082
+ checked.add(name);
5083
+ };
5084
+ checkCircular(primaryType);
5085
+ const dependencies = (name, found) => {
5086
+ for (const child of children.get(name) ?? []) if (!found.has(child)) {
5087
+ found.add(child);
5088
+ dependencies(child, found);
5089
+ }
5090
+ return found;
5091
+ };
5092
+ const encodeOne = (name) => `${name}(${(fields.get(name) ?? []).map((field) => `${field.type} ${field.name}`).join(",")})`;
5093
+ const typeHashes = /* @__PURE__ */ new Map();
5094
+ for (const name of names) {
5095
+ const sorted = [...dependencies(name, /* @__PURE__ */ new Set())].filter((dep) => dep !== name).sort();
5096
+ typeHashes.set(name, keccak_256(textEncoder.encode([name, ...sorted].map(encodeOne).join(""))));
5097
+ }
5098
+ const encodeValue = (parsed, value, depth) => {
5099
+ const dimension = parsed.dimensions[parsed.dimensions.length - 1 - depth];
5100
+ if (dimension !== void 0) {
5101
+ if (!Array.isArray(value)) return refuse(`${parsed.base} array value must be an array`);
5102
+ if (dimension !== -1 && dimension !== value.length) return refuse("array length mismatch");
5103
+ return keccak_256(concat(value.map((item) => encodeValue(parsed, item, depth + 1))));
5104
+ }
5105
+ const leaf = leafEncoder(parsed.base);
5106
+ if (leaf !== void 0) return leaf(value);
5107
+ return hashStruct(parsed.base, value);
5108
+ };
5109
+ function hashStruct(typeName, value) {
5110
+ const list = fields.get(typeName);
5111
+ const typeHash = typeHashes.get(typeName);
5112
+ if (list === void 0 || typeHash === void 0) return refuse(`unknown type "${typeName}"`);
5113
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return refuse(`${typeName} value must be an object`);
5114
+ const record = value;
5115
+ const words = list.map((field) => {
5116
+ if (!Object.prototype.hasOwnProperty.call(record, field.name)) return refuse(`${typeName} value is missing field "${field.name}"`);
5117
+ return encodeValue(parseType(field.type), record[field.name], 0);
5118
+ });
5119
+ return keccak_256(concat([typeHash, ...words]));
5120
+ }
5121
+ return {
5122
+ primaryType,
5123
+ hashStruct
5124
+ };
5125
+ }
5126
+ function hashDomain(domain) {
5127
+ if (domain === null || typeof domain !== "object" || Array.isArray(domain)) return refuse("domain must be an object");
5128
+ for (const key of Object.keys(domain)) if (!DOMAIN_FIELDS.some((field) => field.name === key)) return refuse(`invalid typed-data domain key ${JSON.stringify(key)}`);
5129
+ return createStructEncoder({ EIP712Domain: DOMAIN_FIELDS.filter((field) => Object.prototype.hasOwnProperty.call(domain, field.name)) }).hashStruct("EIP712Domain", domain);
5130
+ }
5131
+ /**
5132
+ * The EIP-712 digest `keccak256(0x1901 || domainSeparator || hashStruct(primaryType, message))`
5133
+ * that a wallet signs for `eth_signTypedData_v4`. The primary type is inferred, as ethers does.
5134
+ *
5135
+ * @throws GSwapSDKError (`INVALID_TYPED_DATA`) for any type graph or value it cannot encode
5136
+ * exactly (see the module note on strictness).
5137
+ */
5138
+ function hashTypedData(payload) {
5139
+ const domainHash = hashDomain(payload.domain);
5140
+ const encoder = createStructEncoder(payload.types);
5141
+ const structHash = encoder.hashStruct(encoder.primaryType, payload.message);
5142
+ return keccak_256(concat([
5143
+ Uint8Array.of(25, 1),
5144
+ domainHash,
5145
+ structHash
5146
+ ]));
5147
+ }
5148
+ /**
5149
+ * Signs a dApp's EIP-712 typed-data approval (the wallet's `signTypedMessage` path), replacing
5150
+ * `new ethers.Wallet(key).signTypedData(domain, types, message)`. `types` must already have
5151
+ * `EIP712Domain` removed (`stripEip712DomainType`).
5152
+ *
5153
+ * @returns `0x` + r + s + v with `v` = `0x1b`/`0x1c` (27/28): ethers' serialized signature form,
5154
+ * recoverable with `verifyTypedData` / `eth_signTypedData_v4` verifiers. Rejects (never throws
5155
+ * synchronously) on invalid input.
5156
+ */
5157
+ async function signTypedDataPayload(privateKey, payload) {
5158
+ const digest = hashTypedData(payload);
5159
+ return withPrivateKey(privateKey, (key) => `0x${signHash(key, digest)}`);
5160
+ }
5161
+
5162
+ //#endregion
5163
+ export { ALL_FEE_TIERS, AppliedTradeError, Assets, BrowserWalletSigner, CanonicalSymbols, ChainGateway, DEFAULT_UNIQUE_KEY_PREFIX, DEX_FEE_METHODS, DRY_RUN_METHOD, DRY_RUN_UNIQUE_KEY_PREFIX, DexFees, EIP712_CAPABLE_METHODS, FEE_TIER, GC_MAX_TICK, GC_MIN_TICK, GSWAP_ENVIRONMENTS, GSwap, GSwapSDKError, GalaWalletSigner, GdexStreamError, GdexStreamService, PENDING_SWAPS_STORAGE_KEY, PENDING_SWAP_EXPIRY_MS, PendingSwapStore, Pools, Positions, PrivateKeySigner, Quoting, SubmittedTransaction, Swaps, Symbols, TICK_SPACING_BY_FEE, alignTickDown, alignTickUp, assertCanonicalPair, assertCanonicalV2Dto, assertTickRange, assertUniqueKey, buildAddLiquidityDto, buildCollectPositionFeesDto, buildCreatePoolDto, buildDryRunWrapper, buildEIP712Payload, buildRemoveLiquidityDto, buildRequestTradeDto, calculatePersonalSignPrefix, canonicalDecimalString, classifyShadowSubmitError, classifyShadowSubmitStatus, compositeKeyOf, confirmAppliedTrade, createLazyPrivateKeySigner, createUniqueKey, eip712DomainFor, ethAddressOfPrivateKey, fixpointPrefixFor, frameSlot0, generateEIP712Types, getObjectProperty, getPayloadToSign, getStringProperty, hashTypedData, isCurrentContractDexMessage, isDexFeeMethod, isGdexLiquidityEvent, isProposableTradingSymbol, normalizePrivateKey, orderSymbols, parseJson, parseTokenClassKey, personalSignPrefixFor, queryTokenOf, rawTokenOf, readOrderedSymbols, readShadowSubmitOutcome, resolvePersonalSignChainDtoPayload, resolveUniqueKeyPrefix, serialize, signChainDtoHash, signChainDtoNative, signChainDtoPersonalSign, signNative, signPersonalMessage, signRawObject, signSerializedNative, signTypedDataPayload, sqrtPriceToTick, stripEip712DomainType, swapRouteFromQuote, tickFromPrice, tickToSqrtPrice, toChainDto, tokenClassDollarKey, tradingSymbolOf, validateFee, validateNumericAmount, validatePriceValues, validateTickRange, validateTickSpacing, validateTokenDecimals, validateWalletAddress, withPrivateKey };
2829
5164
  //# sourceMappingURL=index.mjs.map