@gala-chain/gswap-sdk 0.0.9 → 1.0.0-rc.3

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,39 +1,97 @@
1
1
  // src/utils/validation.ts
2
- import BigNumber from "bignumber.js";
2
+ import BigNumber2 from "bignumber.js";
3
3
 
4
4
  // src/classes/gswap_sdk_error.ts
5
5
  var GSwapSDKError = class _GSwapSDKError extends Error {
6
- constructor(message, code, details) {
6
+ constructor(message, code, details, chainMessage, retryAfterMs) {
7
7
  super(message);
8
8
  this.code = code;
9
9
  this.details = details;
10
10
  this.name = "GSwapSDKError";
11
- }
11
+ this.chainMessage = chainMessage;
12
+ this.retryAfterMs = retryAfterMs;
13
+ }
14
+ code;
15
+ details;
16
+ chainMessage;
17
+ retryAfterMs;
18
+ /** Create the standard missing-signer error. */
12
19
  static noSignerError() {
13
20
  return new _GSwapSDKError(
14
21
  "This method requires a signer. Please provide a signer to the GSwap constructor.",
15
22
  "NO_SIGNER"
16
23
  );
17
24
  }
25
+ /** Create the error used when confirming a position write without a configured wallet address. */
26
+ static noWalletAddressError() {
27
+ return new _GSwapSDKError(
28
+ "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.",
29
+ "NO_WALLET_ADDRESS"
30
+ );
31
+ }
32
+ /** Create the error used when no pool can quote the requested pair. */
33
+ static noPoolAvailableError(tokenIn, tokenOut, fee) {
34
+ return new _GSwapSDKError("No pool is available for the requested pair.", "NO_POOL_AVAILABLE", {
35
+ tokenIn,
36
+ tokenOut,
37
+ ...fee === void 0 ? {} : { fee }
38
+ });
39
+ }
40
+ /** Create the error used when a pool lacks liquidity for a quote. */
41
+ static insufficientLiquidityError(tokenIn, tokenOut, fee) {
42
+ return new _GSwapSDKError(
43
+ "The selected pool has insufficient liquidity for the requested quote.",
44
+ "INSUFFICIENT_LIQUIDITY",
45
+ { tokenIn, tokenOut, ...fee === void 0 ? {} : { fee } }
46
+ );
47
+ }
48
+ /** Convert a chain-gateway bounce into a typed SDK error. */
49
+ static fromGatewayBounce(code, message, status, retryAfterMs) {
50
+ const details = { status, chainMessage: message };
51
+ if (retryAfterMs !== void 0) details["retryAfterMs"] = retryAfterMs;
52
+ const sdkMessage = code === "CHAIN_DISPATCH_FAILED" ? message : `Gateway rejected ${code}: ${message}`;
53
+ return new _GSwapSDKError(sdkMessage, code, details, message, retryAfterMs);
54
+ }
55
+ /** Convert a GalaChain `Status: 0` response into a typed SDK error. */
56
+ static fromChainError(errorKey, message, details) {
57
+ return new _GSwapSDKError(
58
+ `GalaChain error ${errorKey}: ${message}`,
59
+ errorKey,
60
+ { ...details, errorKey, message },
61
+ message
62
+ );
63
+ }
64
+ /** Create the error used when a token is not registered by the current DEX contract. */
65
+ static unknownTokenError(token) {
66
+ const tokenText = typeof token === "string" ? token : JSON.stringify(token);
67
+ return new _GSwapSDKError(
68
+ `Token ${tokenText} has no trading symbol on the new DEX contract (no gcdex pool includes it yet).`,
69
+ "UNKNOWN_TOKEN",
70
+ { token }
71
+ );
72
+ }
73
+ /** Create the error used when apply-results confirmation does not arrive in time. */
74
+ static confirmationTimeoutError(uniqueKey, cause) {
75
+ return new _GSwapSDKError(
76
+ "Transaction confirmation timed out; the trade may still apply. Confirm the same uniqueKey again later instead of resubmitting.",
77
+ "CONFIRMATION_TIMEOUT",
78
+ { uniqueKey, ...cause === void 0 ? {} : { cause } }
79
+ );
80
+ }
81
+ /** Convert an unexpected HTTP response into an SDK error. */
18
82
  static async fromErrorResponse(url, response) {
19
83
  const bodyText = await response.text();
20
- const bodyJson = (() => {
21
- try {
22
- return JSON.parse(bodyText);
23
- } catch {
24
- return void 0;
25
- }
26
- })();
27
- const errorKey = typeof bodyJson === "object" && bodyJson && "error" in bodyJson && typeof bodyJson.error === "object" && bodyJson.error && "ErrorKey" in bodyJson.error && typeof bodyJson.error.ErrorKey === "string" ? bodyJson.error.ErrorKey : void 0;
28
- const message = typeof bodyJson === "object" && bodyJson && "error" in bodyJson && typeof bodyJson.error === "object" && bodyJson.error && "Message" in bodyJson.error && typeof bodyJson.error.Message === "string" ? bodyJson.error.Message : void 0;
29
- if (errorKey && message) {
30
- return new _GSwapSDKError(`GalaChain Error ${errorKey} from ${url}: ${message}`, errorKey, {
31
- message,
84
+ const bodyJson = parseJson(bodyText);
85
+ const errorObject = getObjectProperty(bodyJson, "error");
86
+ const errorKey = getStringProperty(errorObject, "ErrorKey");
87
+ const message = getStringProperty(errorObject, "Message");
88
+ if (errorKey !== void 0 && message !== void 0) {
89
+ return new _GSwapSDKError(
90
+ `GalaChain Error ${errorKey} from ${url}: ${message}`,
32
91
  errorKey,
33
- status: response.status,
34
- body: bodyJson,
35
- url
36
- });
92
+ { message, errorKey, status: response.status, body: bodyJson, url },
93
+ message
94
+ );
37
95
  }
38
96
  return new _GSwapSDKError(`Unexpected HTTP Error ${response.status} from ${url}`, "HTTP_ERROR", {
39
97
  status: response.status,
@@ -41,49 +99,125 @@ var GSwapSDKError = class _GSwapSDKError extends Error {
41
99
  url
42
100
  });
43
101
  }
44
- static incorrectTokenOrderingError(specifiedToken0, specifiedToken1) {
45
- return new _GSwapSDKError(
46
- "Token ordering is incorrect. token0 should sort below token1.",
47
- "INCORRECT_TOKEN_ORDERING",
48
- {
49
- specifiedToken0,
50
- specifiedToken1
51
- }
52
- );
53
- }
54
- static transactionWaitTimeoutError(txId) {
55
- return new _GSwapSDKError("Transaction wait timed out.", "TRANSACTION_WAIT_TIMEOUT", {
56
- txId
57
- });
58
- }
59
- static transactionWaitFailedError(txId, detail) {
60
- const transactionHash = "transactionId" in detail && typeof detail.transactionId === "string" ? detail.transactionId : void 0;
61
- const { transactionId, ...rest } = detail;
62
- return new _GSwapSDKError("Transaction wait failed.", "TRANSACTION_WAIT_FAILED", {
63
- txId,
64
- transactionHash,
65
- ...rest
66
- });
102
+ };
103
+ function getObjectProperty(value, property) {
104
+ if (typeof value !== "object" || value === null || !(property in value)) return void 0;
105
+ const propertyValue = value[property];
106
+ return typeof propertyValue === "object" && propertyValue !== null ? propertyValue : void 0;
107
+ }
108
+ function getStringProperty(value, property) {
109
+ if (typeof value !== "object" || value === null || !(property in value)) return void 0;
110
+ const propertyValue = value[property];
111
+ return typeof propertyValue === "string" ? propertyValue : void 0;
112
+ }
113
+ function parseJson(text) {
114
+ try {
115
+ return JSON.parse(text);
116
+ } catch {
117
+ return void 0;
67
118
  }
68
- static socketConnectionRequiredError() {
69
- return new _GSwapSDKError(
70
- "This method requires a socket connection. Did you call connectSocket()?",
71
- "SOCKET_CONNECTION_REQUIRED"
119
+ }
120
+
121
+ // src/types/fees.ts
122
+ var FEE_TIER = /* @__PURE__ */ ((FEE_TIER2) => {
123
+ FEE_TIER2[FEE_TIER2["PERCENT_00_00"] = 0] = "PERCENT_00_00";
124
+ FEE_TIER2[FEE_TIER2["PERCENT_00_05"] = 500] = "PERCENT_00_05";
125
+ FEE_TIER2[FEE_TIER2["PERCENT_00_30"] = 3e3] = "PERCENT_00_30";
126
+ FEE_TIER2[FEE_TIER2["PERCENT_01_00"] = 1e4] = "PERCENT_01_00";
127
+ return FEE_TIER2;
128
+ })(FEE_TIER || {});
129
+ var TICK_SPACING_BY_FEE = {
130
+ [0 /* PERCENT_00_00 */]: 200,
131
+ [500 /* PERCENT_00_05 */]: 10,
132
+ [3e3 /* PERCENT_00_30 */]: 60,
133
+ [1e4 /* PERCENT_01_00 */]: 200
134
+ };
135
+ var ALL_FEE_TIERS = [
136
+ 0 /* PERCENT_00_00 */,
137
+ 500 /* PERCENT_00_05 */,
138
+ 3e3 /* PERCENT_00_30 */,
139
+ 1e4 /* PERCENT_01_00 */
140
+ ];
141
+
142
+ // src/utils/ticks.ts
143
+ import BigNumber from "bignumber.js";
144
+ import { Decimal } from "decimal.js";
145
+ var GC_MIN_TICK = -887272;
146
+ var GC_MAX_TICK = 887272;
147
+ var DexMath = BigNumber.clone({
148
+ DECIMAL_PLACES: 60,
149
+ ROUNDING_MODE: BigNumber.ROUND_DOWN
150
+ });
151
+ var DexDecimal = Decimal.clone({ precision: 60 });
152
+ function tickToSqrtPrice(tick) {
153
+ return new BigNumber(new DexDecimal(1.0001).pow(tick / 2).toString());
154
+ }
155
+ function sqrtPriceToTick(sqrtPrice) {
156
+ let value;
157
+ try {
158
+ value = new DexMath(sqrtPrice);
159
+ } catch {
160
+ return Number.NaN;
161
+ }
162
+ if (!value.isFinite() || value.isLessThanOrEqualTo(0)) return Number.NaN;
163
+ const approximate = Math.log(value.toNumber() ** 2) / Math.log(1.0001);
164
+ if (!Number.isFinite(approximate)) return Number.NaN;
165
+ let tick = Math.min(GC_MAX_TICK, Math.max(GC_MIN_TICK, Math.floor(approximate)));
166
+ while (tick < GC_MAX_TICK && tickToSqrtPrice(tick + 1).isLessThanOrEqualTo(value)) tick += 1;
167
+ while (tick > GC_MIN_TICK && tickToSqrtPrice(tick).isGreaterThan(value)) tick -= 1;
168
+ return tick;
169
+ }
170
+ function tickFromPrice(price) {
171
+ const priceText = typeof price === "string" ? price : typeof price === "number" ? price.toString() : BigNumber.isBigNumber(price) ? price.toString() : "NaN";
172
+ const value = new DexDecimal(priceText);
173
+ if (!value.isFinite() || value.lessThanOrEqualTo(0)) return Number.NaN;
174
+ if (!Number.isFinite(value.toNumber())) return Number.NaN;
175
+ const tick = value.ln().dividedBy(new DexDecimal(1.0001).ln()).floor().toNumber();
176
+ return Number.isFinite(tick) ? tick : Number.NaN;
177
+ }
178
+ function alignTickDown(tick, spacing) {
179
+ assertSpacing(spacing);
180
+ return Math.floor(tick / spacing) * spacing;
181
+ }
182
+ function alignTickUp(tick, spacing) {
183
+ assertSpacing(spacing);
184
+ return Math.ceil(tick / spacing) * spacing;
185
+ }
186
+ function assertTickRange(lower, upper, fee) {
187
+ const spacing = TICK_SPACING_BY_FEE[fee];
188
+ if (spacing === void 0) throw new RangeError(`Unsupported fee tier: ${fee}`);
189
+ if (!Number.isInteger(lower) || !Number.isInteger(upper)) {
190
+ throw new RangeError("Ticks must be integers");
191
+ }
192
+ if (lower < GC_MIN_TICK || upper > GC_MAX_TICK || lower >= upper) {
193
+ throw new RangeError(
194
+ `Tick range must satisfy ${GC_MIN_TICK} <= lower < upper <= ${GC_MAX_TICK}`
72
195
  );
73
196
  }
74
- static noPoolAvailableError(tokenIn, tokenOut, fee) {
75
- const message = fee !== void 0 ? `No pool available for the specified token pair at fee tier ${fee}` : "No pools available for the specified token pair";
76
- return new _GSwapSDKError(message, "NO_POOL_AVAILABLE", {
77
- tokenIn,
78
- tokenOut,
79
- fee
80
- });
197
+ if (lower % spacing !== 0 || upper % spacing !== 0) {
198
+ throw new RangeError(`Ticks must be aligned to spacing ${spacing}`);
81
199
  }
82
- };
200
+ }
201
+ function assertSpacing(spacing) {
202
+ if (!Number.isInteger(spacing) || spacing <= 0)
203
+ throw new RangeError("Tick spacing must be positive");
204
+ }
83
205
 
84
206
  // src/utils/validation.ts
85
207
  function validateNumericAmount(amount, parameterName, allowZero = false) {
86
- const bnAmount = BigNumber(amount);
208
+ if (typeof amount === "number") {
209
+ throw new GSwapSDKError(
210
+ `Invalid ${parameterName}: use a decimal string or BigNumber, not a JavaScript number`,
211
+ "VALIDATION_ERROR",
212
+ { type: "INVALID_NUMERIC_AMOUNT", parameterName, value: amount, reason: "number_input" }
213
+ );
214
+ }
215
+ let bnAmount;
216
+ try {
217
+ bnAmount = BigNumber2(amount);
218
+ } catch {
219
+ bnAmount = BigNumber2(NaN);
220
+ }
87
221
  if (!bnAmount.isFinite()) {
88
222
  throw new GSwapSDKError(
89
223
  `Invalid ${parameterName}: must be a finite number`,
@@ -118,10 +252,24 @@ function validateNumericAmount(amount, parameterName, allowZero = false) {
118
252
  }
119
253
  }
120
254
  function validatePriceValues(spotPrice, lowerPrice, upperPrice) {
121
- const bnSpotPrice = BigNumber(spotPrice);
122
- const bnLowerPrice = BigNumber(lowerPrice);
123
- let bnUpperPrice = BigNumber(upperPrice);
124
- bnUpperPrice = bnUpperPrice.isFinite() ? bnUpperPrice : BigNumber(1e18);
255
+ if ([spotPrice, lowerPrice, upperPrice].some((value) => typeof value === "number")) {
256
+ throw new GSwapSDKError(
257
+ "Invalid price values: use decimal strings or BigNumber values, not JavaScript numbers",
258
+ "VALIDATION_ERROR",
259
+ { type: "INVALID_NUMERIC_AMOUNT", reason: "number_input" }
260
+ );
261
+ }
262
+ const parse = (value) => {
263
+ try {
264
+ return BigNumber2(value);
265
+ } catch {
266
+ return BigNumber2(NaN);
267
+ }
268
+ };
269
+ const bnSpotPrice = parse(spotPrice);
270
+ const bnLowerPrice = parse(lowerPrice);
271
+ let bnUpperPrice = parse(upperPrice);
272
+ bnUpperPrice = bnUpperPrice.isFinite() ? bnUpperPrice : BigNumber2(1e18);
125
273
  if (!bnSpotPrice.isFinite() || !bnLowerPrice.isFinite() || !bnUpperPrice.isFinite() || !bnSpotPrice.isPositive() || !bnLowerPrice.isPositive() || !bnUpperPrice.isPositive()) {
126
274
  throw new GSwapSDKError(
127
275
  "Invalid price values: all prices must be finite and positive",
@@ -178,26 +326,30 @@ function validateTickRange(tickLower, tickUpper) {
178
326
  }
179
327
  );
180
328
  }
181
- if (tickLower < -886800 || tickUpper > 886800) {
329
+ if (tickLower < GC_MIN_TICK || tickUpper > GC_MAX_TICK) {
182
330
  throw new GSwapSDKError(
183
- "Invalid tick range: ticks must be between -886800 and 886800",
331
+ `Invalid tick range: ticks must be between ${GC_MIN_TICK} and ${GC_MAX_TICK}`,
184
332
  "VALIDATION_ERROR",
185
333
  {
186
334
  type: "INVALID_TICK_BOUNDS",
187
335
  tickLower,
188
336
  tickUpper,
189
- minTick: -886800,
190
- maxTick: 886800
337
+ minTick: GC_MIN_TICK,
338
+ maxTick: GC_MAX_TICK
191
339
  }
192
340
  );
193
341
  }
194
342
  }
195
343
  function validateFee(fee) {
196
- if (!Number.isInteger(fee) || fee < 0) {
197
- throw new GSwapSDKError("Invalid fee: must be a non-negative integer", "VALIDATION_ERROR", {
198
- type: "INVALID_FEE",
199
- value: fee
200
- });
344
+ if (!ALL_FEE_TIERS.some((tier) => Number(tier) === fee)) {
345
+ throw new GSwapSDKError(
346
+ "Invalid fee tier: must be one of 0, 500, 3000, or 10000",
347
+ "VALIDATION_ERROR",
348
+ {
349
+ type: "INVALID_FEE",
350
+ value: fee
351
+ }
352
+ );
201
353
  }
202
354
  }
203
355
  function validateTickSpacing(tickSpacing) {
@@ -241,6 +393,8 @@ var Assets = class {
241
393
  this.dexBackendBaseUrl = dexBackendBaseUrl;
242
394
  this.httpClient = httpClient;
243
395
  }
396
+ dexBackendBaseUrl;
397
+ httpClient;
244
398
  /**
245
399
  * Gets all token assets owned by a user with their balances.
246
400
  * @param ownerAddress - The wallet address to get assets for.
@@ -259,408 +413,555 @@ var Assets = class {
259
413
  async getUserAssets(ownerAddress, page = 1, limit = 10) {
260
414
  validateWalletAddress(ownerAddress);
261
415
  if (!Number.isInteger(page) || page < 1) {
262
- throw new Error("Invalid page: must be a positive integer");
416
+ throw new GSwapSDKError("Invalid page: must be a positive integer", "VALIDATION_ERROR", {
417
+ page
418
+ });
263
419
  }
264
420
  if (!Number.isInteger(limit) || limit < 1 || limit > 100) {
265
- throw new Error("Invalid limit: must be an integer between 1 and 100");
421
+ throw new GSwapSDKError(
422
+ "Invalid limit: must be an integer between 1 and 100",
423
+ "VALIDATION_ERROR",
424
+ { limit }
425
+ );
266
426
  }
267
- const json = await this.httpClient.sendGetRequest(this.dexBackendBaseUrl, "/user/assets", "", {
268
- address: ownerAddress,
269
- page: page.toString(),
270
- limit: limit.toString()
271
- });
272
- return {
273
- tokens: json.data.token.map((token) => ({
274
- ...token,
275
- decimals: parseInt(token.decimals, 10)
276
- })) || [],
277
- count: json.data.count || 0
278
- };
427
+ const json = await this.httpClient.sendGetRequest(
428
+ this.dexBackendBaseUrl,
429
+ "/user/assets",
430
+ "",
431
+ { address: ownerAddress, page: page.toString(), limit: limit.toString() }
432
+ );
433
+ return parseUserAssets(json);
279
434
  }
280
435
  };
281
-
282
- // src/classes/bundler.ts
283
- import crypto from "crypto";
284
-
285
- // src/utils/debug.ts
286
- import debug from "debug";
287
- var debugLog = debug("GSWAP_SDK");
288
-
289
- // src/classes/event_socket_client.ts
290
- import { EventEmitter } from "events";
291
- import { io } from "socket.io-client";
292
- var TradeEventEmitter = class extends EventEmitter {
293
- };
294
- var EventSocketClient = class extends TradeEventEmitter {
295
- socket = null;
296
- bundlerUrl;
297
- constructor(bundlerUrl) {
298
- super();
299
- this.bundlerUrl = bundlerUrl;
300
- }
301
- connect() {
302
- return new Promise((resolve, reject) => {
303
- var _a;
304
- if ((_a = this.socket) == null ? void 0 : _a.connected) {
305
- resolve();
306
- return;
436
+ function parseUserAssets(value) {
437
+ const data = getObjectProperty(value, "data");
438
+ const tokens = data == null ? void 0 : data["token"];
439
+ if (!Array.isArray(tokens) || !tokens.every(isRawUserAsset)) {
440
+ throw new GSwapSDKError(
441
+ "Backend returned an invalid user assets response.",
442
+ "INVALID_CHAIN_RESPONSE",
443
+ {
444
+ data: value
307
445
  }
308
- this.socket = io(this.bundlerUrl, {
309
- transports: ["websocket"],
310
- autoConnect: true
311
- });
312
- this.socket.on("connect", () => {
313
- console.log("Connected to bundler socket:", this.bundlerUrl);
314
- this.emit("connect");
315
- resolve();
316
- });
317
- this.socket.on("connect_error", (error) => {
318
- console.error("Failed to connect to bundler socket:", error);
319
- this.emit("error", error);
320
- reject(error);
321
- });
322
- this.socket.on("disconnect", (reason) => {
323
- console.log("Disconnected from bundler socket:", reason);
324
- this.emit("disconnect", reason);
325
- });
326
- this.socket.onAny((eventName, ...args) => {
327
- var _a2;
328
- if (typeof eventName === "string") {
329
- const [responseData] = args;
330
- this.emit("transaction", eventName, {
331
- ...responseData,
332
- transactionHash: (_a2 = responseData.data) == null ? void 0 : _a2.transactionId
333
- });
334
- }
335
- });
336
- });
446
+ );
337
447
  }
338
- disconnect() {
339
- if (this.socket) {
340
- this.socket.disconnect();
341
- this.socket = null;
448
+ const count = data == null ? void 0 : data["count"];
449
+ return {
450
+ tokens: tokens.map((token) => ({ ...token, decimals: parseInt(token.decimals, 10) })),
451
+ count: typeof count === "number" ? count : 0
452
+ };
453
+ }
454
+ function isRawUserAsset(value) {
455
+ if (typeof value !== "object" || value === null) return false;
456
+ const entry = value;
457
+ return typeof entry["image"] === "string" && typeof entry["name"] === "string" && typeof entry["decimals"] === "string" && /^\d+$/u.test(entry["decimals"]) && typeof entry["verify"] === "boolean" && typeof entry["symbol"] === "string" && typeof entry["quantity"] === "string";
458
+ }
459
+
460
+ // src/utils/transport.ts
461
+ async function requestWithTimeout(requestor, url, options, timeoutMs) {
462
+ const controller = new AbortController();
463
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
464
+ const externalSignal = options.signal;
465
+ const abortFromCaller = () => controller.abort();
466
+ externalSignal == null ? void 0 : externalSignal.addEventListener("abort", abortFromCaller, { once: true });
467
+ try {
468
+ return await requestor(url, { ...options, signal: controller.signal });
469
+ } catch (error) {
470
+ if (controller.signal.aborted) {
471
+ throw new GSwapSDKError(`Request timed out after ${timeoutMs} ms.`, "REQUEST_TIMEOUT", {
472
+ url,
473
+ timeoutMs,
474
+ cause: error
475
+ });
342
476
  }
477
+ throw error;
478
+ } finally {
479
+ clearTimeout(timer);
480
+ externalSignal == null ? void 0 : externalSignal.removeEventListener("abort", abortFromCaller);
343
481
  }
344
- isConnected() {
345
- var _a;
346
- return ((_a = this.socket) == null ? void 0 : _a.connected) ?? false;
347
- }
348
- };
482
+ }
483
+ async function readResponseBody(response) {
484
+ const text = await response.text();
485
+ return parseJson(text) ?? text;
486
+ }
487
+ function readHeader(response, name) {
488
+ var _a;
489
+ const headers = response.headers;
490
+ if (headers === void 0) return void 0;
491
+ if (hasHeaderGetter(headers)) {
492
+ const value2 = headers.get(name);
493
+ return value2 === null || value2 === "" ? void 0 : value2;
494
+ }
495
+ const value = (_a = Object.entries(headers).find(([key]) => key.toLowerCase() === name.toLowerCase())) == null ? void 0 : _a[1];
496
+ return value === void 0 || value === "" ? void 0 : value;
497
+ }
498
+ function readRetryAfter(response) {
499
+ const raw = readHeader(response, "retry-after");
500
+ if (raw === void 0) return void 0;
501
+ const seconds = Number(raw);
502
+ return Number.isFinite(seconds) && seconds >= 0 ? seconds * 1e3 : void 0;
503
+ }
504
+ function readBlockNumberHeader(response, headerName = "x-block-number") {
505
+ const raw = readHeader(response, headerName);
506
+ if (raw === void 0) return void 0;
507
+ const blockNumber = Number(raw);
508
+ return Number.isInteger(blockNumber) && blockNumber >= 0 ? blockNumber : void 0;
509
+ }
510
+ function hasHeaderGetter(headers) {
511
+ return "get" in headers && typeof headers.get === "function";
512
+ }
349
513
 
350
- // src/classes/tx_waiter.ts
351
- var TransactionWaiter = class {
352
- enabled = false;
353
- promiseInfoForTxId = /* @__PURE__ */ new Map();
354
- setEnabled(enabled) {
355
- this.enabled = enabled;
356
- if (!enabled) {
357
- for (const [txId, promiseInfo] of this.promiseInfoForTxId.entries()) {
358
- clearTimeout(promiseInfo.timeoutId);
359
- promiseInfo.reject(
360
- GSwapSDKError.transactionWaitFailedError(txId, {
361
- message: "Transaction waiter disabled"
362
- })
514
+ // src/classes/submitted_transaction.ts
515
+ var SubmittedTransaction = class {
516
+ method;
517
+ uniqueKey;
518
+ transactionId;
519
+ blockNumber;
520
+ mode;
521
+ /** The synchronous gateway result, or `undefined` when `mode === 'queued'`. */
522
+ result;
523
+ backendBaseUrl;
524
+ requestor;
525
+ requestTimeoutMs;
526
+ positionConfirmation;
527
+ /** Construct a submitted transaction from a successful gateway response.
528
+ *
529
+ * @example
530
+ * ```ts
531
+ * const transaction = new SubmittedTransaction({
532
+ * method: 'RequestTrade', mode: 'queued', uniqueKey: 'swap-1',
533
+ * transactionId: 'request-tx', result: undefined,
534
+ * dexBackendBaseUrl: 'https://dex.example', httpRequestor,
535
+ * });
536
+ * ```
537
+ */
538
+ constructor(options) {
539
+ this.method = options.method;
540
+ this.uniqueKey = options.uniqueKey;
541
+ this.transactionId = options.transactionId;
542
+ this.blockNumber = options.blockNumber ?? null;
543
+ this.mode = options.mode;
544
+ this.result = options.result;
545
+ this.backendBaseUrl = options.dexBackendBaseUrl.replace(/\/$/u, "");
546
+ this.requestor = options.httpRequestor;
547
+ this.requestTimeoutMs = options.requestTimeoutMs ?? 3e4;
548
+ this.positionConfirmation = options.positionConfirmation;
549
+ }
550
+ /** Confirm a queued RequestTrade or prove the affected position for a liquidity write.
551
+ *
552
+ * For RequestTrade, calling this method is required to learn the outcome: the queued
553
+ * acknowledgement proves acceptance, not execution.
554
+ *
555
+ * @example
556
+ * ```ts
557
+ * const applied = await submitted.confirm({ initialDelayMs: 3_000 });
558
+ * ```
559
+ */
560
+ async confirm(options) {
561
+ if (this.method === "RequestTrade") {
562
+ return this.confirmApplied(options);
563
+ }
564
+ return this.confirmPosition(options);
565
+ }
566
+ async confirmApplied(options) {
567
+ const schedule = createConfirmationSchedule(options, 3e3);
568
+ await schedule.waitForRead();
569
+ const url = `${this.backendBaseUrl}/v1/chain/apply-results/${encodeURIComponent(this.uniqueKey)}?channel=asset&contract=dex-contract`;
570
+ let lastError;
571
+ while (true) {
572
+ let response;
573
+ let body;
574
+ try {
575
+ response = await requestWithTimeout(
576
+ this.requestor,
577
+ url,
578
+ { method: "GET" },
579
+ this.requestTimeoutMs
363
580
  );
581
+ body = await readResponseBody(response);
582
+ } catch (error) {
583
+ lastError = error;
584
+ if (!await schedule.waitForRead()) break;
585
+ continue;
364
586
  }
365
- this.promiseInfoForTxId.clear();
366
- }
367
- }
368
- registerTxId(txId, timeoutMs) {
369
- if (this.promiseInfoForTxId.has(txId)) {
370
- throw new GSwapSDKError(
371
- `Transaction ID is already registered`,
372
- "TRANSACTION_ID_ALREADY_REGISTERED",
373
- { txId }
374
- );
375
- }
376
- if (!this.enabled) {
377
- return;
378
- }
379
- let resolve;
380
- let reject;
381
- const promise = new Promise((res, rej) => {
382
- resolve = res;
383
- reject = rej;
384
- });
385
- const timeoutId = setTimeout(() => {
386
- const promiseInfo = this.promiseInfoForTxId.get(txId);
387
- if (promiseInfo) {
388
- if (promiseInfo.waited) {
389
- promiseInfo.reject(GSwapSDKError.transactionWaitTimeoutError(txId));
390
- } else {
391
- promiseInfo.resolve({ txId, transactionHash: txId, Data: {} });
587
+ if (response.status === 200) {
588
+ return this.readAppliedResult(response, body, url);
589
+ }
590
+ if (response.status === 404 || response.status === 429 || isTransient(response.status)) {
591
+ if (response.status === 429) {
592
+ const retryAfter = readRetryAfter(response);
593
+ if (retryAfter !== void 0) {
594
+ if (!await schedule.waitForRead(retryAfter)) break;
595
+ continue;
596
+ }
392
597
  }
393
- this.promiseInfoForTxId.delete(txId);
598
+ } else {
599
+ throw new GSwapSDKError(bodyMessage(body), "CONFIRMATION_FAILED", {
600
+ status: response.status,
601
+ body,
602
+ url
603
+ });
394
604
  }
395
- }, timeoutMs);
396
- this.promiseInfoForTxId.set(txId, {
397
- promise,
398
- resolve,
399
- reject,
400
- timeoutId,
401
- waited: false
402
- });
403
- }
404
- wait(txId) {
405
- const promise = this.promiseInfoForTxId.get(txId);
406
- if (!promise) {
407
- throw new GSwapSDKError(
408
- `Transaction ID is not registered for waiting`,
409
- "TRANSACTION_ID_NOT_REGISTERED",
605
+ if (!await schedule.waitForRead()) break;
606
+ }
607
+ throw GSwapSDKError.confirmationTimeoutError(this.uniqueKey, lastError);
608
+ }
609
+ readAppliedResult(response, body, url) {
610
+ const record = asRecord(body);
611
+ const status = record == null ? void 0 : record["Status"];
612
+ const applyTransactionId = readHeader(response, "x-apply-transaction-id") ?? null;
613
+ const blockNumber = readBlockNumberHeader(response, "x-apply-block-number") ?? null;
614
+ if (status === 0) {
615
+ throw GSwapSDKError.fromChainError(
616
+ getStringProperty(record, "ErrorKey") ?? "CHAIN_ERROR",
617
+ getStringProperty(record, "Message") ?? "The chain rejected this trade.",
410
618
  {
411
- txId
619
+ uniqueKey: this.uniqueKey,
620
+ applyTransactionId,
621
+ blockNumber,
622
+ status: response.status,
623
+ body,
624
+ url
412
625
  }
413
626
  );
414
627
  }
415
- promise.waited = true;
416
- return promise.promise;
628
+ if (status !== 1) throw malformedConfirmation(response, body, url);
629
+ const result = parseTradeExecution(record == null ? void 0 : record["Data"]);
630
+ if (result === void 0) throw malformedConfirmation(response, body, url);
631
+ return {
632
+ uniqueKey: this.uniqueKey,
633
+ transactionId: applyTransactionId,
634
+ blockNumber,
635
+ requestTransactionId: this.transactionId,
636
+ result
637
+ };
417
638
  }
418
- notifySuccess(txId, data) {
419
- const promiseInfo = this.promiseInfoForTxId.get(txId);
420
- if (!promiseInfo) {
421
- return;
639
+ /** Confirm a liquidity write against the position's observable effect.
640
+ *
641
+ * @returns The position after the write, or `null` for a confirmed full close.
642
+ * @example
643
+ * ```ts
644
+ * const position = await submitted.confirm({ timeoutMs: 60_000 });
645
+ * ```
646
+ */
647
+ async confirmPosition(options) {
648
+ if (this.positionConfirmation === void 0) throw GSwapSDKError.noWalletAddressError();
649
+ const schedule = createConfirmationSchedule(options, 0);
650
+ await schedule.waitForRead();
651
+ while (true) {
652
+ const controller = new AbortController();
653
+ const timer = setTimeout(() => controller.abort(), this.requestTimeoutMs);
654
+ try {
655
+ const result = await this.positionConfirmation(controller.signal);
656
+ if (result.confirmed) return result.position;
657
+ } finally {
658
+ clearTimeout(timer);
659
+ }
660
+ if (!await schedule.waitForRead()) break;
422
661
  }
423
- clearTimeout(promiseInfo.timeoutId);
424
- promiseInfo.resolve({
425
- txId,
426
- transactionHash: data.transactionId,
427
- Data: data.Data
428
- });
429
- this.promiseInfoForTxId.delete(txId);
662
+ throw GSwapSDKError.confirmationTimeoutError(this.uniqueKey);
430
663
  }
431
- notifyFailure(txId, detail) {
432
- const promiseInfo = this.promiseInfoForTxId.get(txId);
433
- if (!promiseInfo) {
434
- return;
435
- }
436
- clearTimeout(promiseInfo.timeoutId);
437
- if (promiseInfo.waited) {
438
- promiseInfo.reject(GSwapSDKError.transactionWaitFailedError(txId, detail));
439
- } else {
440
- promiseInfo.resolve({ txId, transactionHash: txId, Data: {} });
664
+ };
665
+ function createConfirmationSchedule(options, defaultInitialDelayMs) {
666
+ const timeoutMs = Math.max(0, (options == null ? void 0 : options.timeoutMs) ?? 6e4);
667
+ const pollIntervalMs = Math.max(500, (options == null ? void 0 : options.pollIntervalMs) ?? 2e3);
668
+ const initialDelayMs = Math.max(0, (options == null ? void 0 : options.initialDelayMs) ?? defaultInitialDelayMs);
669
+ const deadline = Date.now() + timeoutMs;
670
+ let firstRead = true;
671
+ let attempt = 0;
672
+ return {
673
+ async waitForRead(retryAfterMs) {
674
+ if (firstRead) {
675
+ firstRead = false;
676
+ const remaining = Math.max(0, deadline - Date.now());
677
+ await delay(Math.min(initialDelayMs, remaining));
678
+ return true;
679
+ }
680
+ const backoff = Math.min(8e3, pollIntervalMs * 2 ** Math.min(attempt, 5));
681
+ attempt += 1;
682
+ const waitMs = retryAfterMs === void 0 ? jitter(backoff) : retryAfterMs;
683
+ if (Date.now() + waitMs > deadline) return false;
684
+ await delay(waitMs);
685
+ return true;
441
686
  }
442
- this.promiseInfoForTxId.delete(txId);
687
+ };
688
+ }
689
+ function parseTradeExecution(value) {
690
+ const record = asRecord(value);
691
+ if (record === void 0 || typeof record["token0"] !== "string" || typeof record["token1"] !== "string" || typeof record["fee"] !== "number") {
692
+ return void 0;
693
+ }
694
+ const optionalFields = [
695
+ "sell0Qty",
696
+ "sell1Qty",
697
+ "buy0Qty",
698
+ "buy1Qty",
699
+ "tradingFees",
700
+ "protocolFees",
701
+ "totalFees"
702
+ ];
703
+ for (const field of optionalFields) {
704
+ if (field in record && typeof record[field] !== "string") return void 0;
443
705
  }
444
- };
706
+ return {
707
+ token0: record["token0"],
708
+ token1: record["token1"],
709
+ fee: record["fee"],
710
+ ...Object.fromEntries(
711
+ optionalFields.flatMap(
712
+ (field) => typeof record[field] === "string" ? [[field, record[field]]] : []
713
+ )
714
+ )
715
+ };
716
+ }
717
+ function malformedConfirmation(response, body, url) {
718
+ return new GSwapSDKError(
719
+ "Transaction confirmation returned a malformed body",
720
+ "CONFIRMATION_FAILED",
721
+ { status: response.status, body, url }
722
+ );
723
+ }
724
+ function isTransient(status) {
725
+ return status === 500 || status === 502 || status === 503 || status === 504;
726
+ }
727
+ function bodyMessage(body) {
728
+ return getStringProperty(body, "message") ?? getStringProperty(body, "Message") ?? getStringProperty(getObjectProperty(body, "error"), "message") ?? getStringProperty(getObjectProperty(body, "error"), "Message") ?? (typeof body === "string" ? body : "Transaction confirmation failed");
729
+ }
730
+ function asRecord(value) {
731
+ return typeof value === "object" && value !== null ? value : void 0;
732
+ }
733
+ function delay(milliseconds) {
734
+ return new Promise((resolve) => setTimeout(resolve, milliseconds));
735
+ }
736
+ function jitter(milliseconds) {
737
+ return Math.max(0, Math.round(milliseconds * (0.9 + Math.random() * 0.2)));
738
+ }
445
739
 
446
- // src/classes/events.ts
447
- var Events = class _Events {
448
- globalSocketClient;
449
- globalWaitHelper = new TransactionWaiter();
450
- connectionPromise;
451
- static instance = new _Events();
452
- static tradeEventEmitterConstructor = EventSocketClient;
453
- /**
454
- * Establishes a global socket connection for real-time event streaming.
455
- * This connection is shared across all service instances.
456
- * @param bundlerBaseUrl - Optional bundler base URL. If not provided, uses default.
457
- * @returns The connected EventSocketClient.
458
- * @example
459
- * ```typescript
460
- * await eventsService.connectEventSocket();
461
- *
462
- * // Socket is now available for transaction updates
463
- * ```
464
- */
465
- async connectEventSocket(bundlerBaseUrl) {
466
- var _a;
467
- if (this.connectionPromise) {
468
- return this.connectionPromise;
469
- }
470
- if ((_a = this.globalSocketClient) == null ? void 0 : _a.isConnected()) {
471
- return this.globalSocketClient;
740
+ // src/classes/gateway.ts
741
+ var ChainGateway = class {
742
+ requestor;
743
+ walletAddress;
744
+ chainCallTimeoutMs;
745
+ requestTimeoutMs;
746
+ dexBackendBaseUrl;
747
+ /** Create a chain gateway client. */
748
+ constructor(options) {
749
+ this.dexBackendBaseUrl = trimTrailingSlash(options.dexBackendBaseUrl);
750
+ this.requestor = options.httpRequestor ?? fetch.bind(globalThis);
751
+ this.walletAddress = options.walletAddress;
752
+ this.chainCallTimeoutMs = options.chainCallTimeoutMs ?? 3e4;
753
+ this.requestTimeoutMs = this.chainCallTimeoutMs;
754
+ }
755
+ async submit(method, signedBody, options) {
756
+ if (method === "Trade") {
757
+ throw new GSwapSDKError(
758
+ "The synchronous Trade method was removed; swaps are queued through RequestTrade.",
759
+ "METHOD_NOT_SUPPORTED",
760
+ { method }
761
+ );
472
762
  }
473
- const url = bundlerBaseUrl ?? "https://bundle-backend-prod1.defi.gala.com";
474
- this.connectionPromise = (async () => {
475
- const client = new _Events.tradeEventEmitterConstructor(url);
476
- await client.connect();
477
- if (!this.globalWaitHelper) {
478
- this.globalWaitHelper = new TransactionWaiter();
763
+ const url = `${this.dexBackendBaseUrl}/v1/chain/asset/dex-contract/${method}`;
764
+ const headers = { "content-type": "application/json" };
765
+ const walletAddress = (options == null ? void 0 : options.walletAddress) ?? this.walletAddress;
766
+ if (walletAddress !== void 0) headers["X-Wallet-Address"] = walletAddress;
767
+ let response;
768
+ try {
769
+ response = await requestWithTimeout(
770
+ this.requestor,
771
+ url,
772
+ {
773
+ method: "POST",
774
+ headers,
775
+ body: JSON.stringify(signedBody)
776
+ },
777
+ this.chainCallTimeoutMs
778
+ );
779
+ } catch (error) {
780
+ if (error instanceof GSwapSDKError && error.code === "REQUEST_TIMEOUT") {
781
+ throw new GSwapSDKError(
782
+ "The submission outcome is unknown because the gateway request timed out. Confirm before retrying.",
783
+ "SUBMISSION_OUTCOME_UNKNOWN",
784
+ { uniqueKey: getStringProperty(signedBody, "uniqueKey") ?? "", cause: error }
785
+ );
479
786
  }
480
- client.on("transaction", this.internalHandleSocketMessage.bind(this));
481
- return client;
482
- })();
483
- this.globalSocketClient = await this.connectionPromise;
484
- this.connectionPromise = void 0;
485
- this.globalWaitHelper.setEnabled(true);
486
- return this.globalSocketClient;
487
- }
488
- /**
489
- * Disconnects the global socket connection and cleans up resources.
490
- */
491
- disconnectEventSocket() {
492
- if (this.globalSocketClient) {
493
- this.globalSocketClient.off("transaction", this.internalHandleSocketMessage.bind(this));
494
- this.globalSocketClient.disconnect();
495
- this.globalSocketClient = void 0;
496
- this.globalWaitHelper.setEnabled(false);
787
+ throw error;
497
788
  }
498
- }
499
- /**
500
- * Checks if the global socket connection is active.
501
- * @returns True if connected, false otherwise.
502
- */
503
- eventSocketConnected() {
504
- var _a;
505
- return ((_a = this.globalSocketClient) == null ? void 0 : _a.isConnected()) ?? false;
506
- }
507
- /**
508
- * Registers a transaction ID for waiting and timeout handling.
509
- * @param txId - The transaction ID to register.
510
- * @param timeoutMs - Timeout in milliseconds.
511
- */
512
- registerTxId(txId, timeoutMs) {
513
- this.globalWaitHelper.registerTxId(txId, timeoutMs);
514
- }
515
- /**
516
- * Waits for a transaction to complete.
517
- * @param txId - The transaction ID to wait for.
518
- * @returns Promise that resolves when the transaction completes.
519
- */
520
- async wait(txId) {
521
- if (!this.eventSocketConnected()) {
522
- throw GSwapSDKError.socketConnectionRequiredError();
789
+ const body = await readResponseBody(response);
790
+ if (!response.ok) {
791
+ throw gatewayError(response, body, url);
523
792
  }
524
- return this.globalWaitHelper.wait(txId);
525
- }
526
- /**
527
- * Internal handler for socket messages.
528
- * @param response - The bundler response.
529
- * @param txId - The transaction ID.
530
- */
531
- internalHandleSocketMessage(txId, response) {
532
- if (response.status === "PROCESSED") {
533
- this.globalWaitHelper.notifySuccess(txId, response.data);
534
- } else if (response.status === "FAILED") {
535
- this.globalWaitHelper.notifyFailure(txId, response.data);
536
- } else {
537
- debugLog(`Unknown response status for transaction ${txId}:`, response.status);
793
+ const envelope = asRecord2(body);
794
+ const data = asRecord2((envelope == null ? void 0 : envelope["data"]) ?? (envelope == null ? void 0 : envelope["Data"]));
795
+ if (data === void 0) {
796
+ throw invalidGatewayResponse(response, body, url, "Expected a data object.");
538
797
  }
539
- }
540
- };
541
-
542
- // src/classes/pending_transaction.ts
543
- var PendingTransaction = class {
544
- constructor(transactionId, message, error, waitDelegate) {
545
- this.transactionId = transactionId;
546
- this.message = message;
547
- this.error = error;
548
- this.waitDelegate = waitDelegate;
549
- }
550
- /**
551
- * Waits for the transaction to be confirmed.
552
- * This should be called immediately after receiving the PendingTransaction
553
- * to ensure proper event handling. If you delay calling this method and the
554
- * transaction confirms before you call this method, an error will be thrown.
555
- *
556
- * @returns A promise that resolves when the transaction is confirmed.
557
- */
558
- wait() {
559
- return this.waitDelegate();
560
- }
561
- };
562
-
563
- // src/classes/bundler.ts
564
- function randomUUID() {
565
- if (globalThis.crypto) {
566
- return globalThis.crypto.randomUUID();
567
- }
568
- return crypto.randomUUID();
569
- }
570
- var Bundler = class {
571
- constructor(bundlerBaseUrl, bundlingAPIBasePath, transactionWaitTimeoutMs, signer, httpClient) {
572
- this.bundlerBaseUrl = bundlerBaseUrl;
573
- this.bundlingAPIBasePath = bundlingAPIBasePath;
574
- this.transactionWaitTimeoutMs = transactionWaitTimeoutMs;
575
- this.signer = signer;
576
- this.httpClient = httpClient;
577
- }
578
- async signObject(methodName, toSign) {
579
- if (!this.signer) {
580
- throw GSwapSDKError.noSignerError();
798
+ const transactionId = getStringProperty(data, "transactionId");
799
+ const mode = getStringProperty(data, "mode");
800
+ const rawTransactionId = data["transactionId"];
801
+ const bodyBlockNumber = data["blockNumber"];
802
+ const invalidModeMessage = 'Gateway response must contain data.mode="sync" with data.result, or data.mode="queued".';
803
+ if (mode !== "sync" && mode !== "queued") {
804
+ throw invalidGatewayResponse(response, body, url, invalidModeMessage);
581
805
  }
582
- const withUniqueKey = {
583
- ...toSign,
584
- uniqueKey: toSign.uniqueKey ?? `galaswap - operation - ${randomUUID()}`
585
- };
586
- debugLog("Signing object for method", methodName, withUniqueKey);
587
- return this.signer.signObject(methodName, withUniqueKey);
588
- }
589
- async sendBundlerRequest(method, body, stringsInstructions) {
590
- if (!this.hasSigner()) {
591
- throw GSwapSDKError.noSignerError();
806
+ if ("transactionId" in data && typeof rawTransactionId !== "string" || bodyBlockNumber !== void 0 && bodyBlockNumber !== null && !isBlockNumber(bodyBlockNumber)) {
807
+ throw invalidGatewayResponse(response, body, url, invalidModeMessage);
592
808
  }
593
- const requestBody = {
594
- method,
595
- signedDto: await this.signObject(method, body),
596
- stringsInstructions
597
- };
598
- debugLog("Sending bundler request", method, requestBody);
599
- const response = await this.httpClient.sendPostRequest(
600
- this.bundlerBaseUrl,
601
- this.bundlingAPIBasePath,
602
- "",
603
- requestBody
604
- );
605
- debugLog("Received bundler response", method, response);
606
- Events.instance.registerTxId(response.data, this.transactionWaitTimeoutMs);
607
- const transaction = new PendingTransaction(
608
- response.data,
609
- response.message,
610
- response.error,
611
- () => {
612
- return Events.instance.wait(response.data);
809
+ if (method === "RequestTrade" && mode === "sync") {
810
+ throw invalidGatewayResponse(
811
+ response,
812
+ body,
813
+ url,
814
+ "The gateway executed RequestTrade synchronously, which this SDK refuses; RequestTrade must be queued."
815
+ );
816
+ }
817
+ if (method === "RequestTrade" && mode === "queued") {
818
+ const signedUniqueKey = getStringProperty(signedBody, "uniqueKey");
819
+ if ("uniqueKey" in data && (typeof data["uniqueKey"] !== "string" || data["uniqueKey"] !== signedUniqueKey)) {
820
+ throw invalidGatewayResponse(
821
+ response,
822
+ body,
823
+ url,
824
+ "Gateway response data.uniqueKey must match the signed RequestTrade uniqueKey."
825
+ );
613
826
  }
614
- );
615
- return transaction;
827
+ } else if (mode === "queued" || !("result" in data)) {
828
+ throw invalidGatewayResponse(response, body, url, invalidModeMessage);
829
+ }
830
+ if (mode === "sync") {
831
+ const embeddedResult = asRecord2(data["result"]);
832
+ if (embeddedResult !== void 0) {
833
+ const resultStatus = embeddedResult["Status"];
834
+ if (resultStatus !== void 0 && resultStatus !== 1) {
835
+ throw GSwapSDKError.fromChainError(
836
+ getStringProperty(embeddedResult, "ErrorKey") ?? "CHAIN_ERROR",
837
+ getStringProperty(embeddedResult, "Message") ?? "The chain rejected this write.",
838
+ { status: response.status, body, url }
839
+ );
840
+ }
841
+ }
842
+ }
843
+ const uniqueKey = getStringProperty(signedBody, "uniqueKey") ?? "";
844
+ const headerTransactionId = readHeader(response, "x-transaction-id");
845
+ const resolvedTransactionId = transactionId === void 0 || transactionId === "" ? headerTransactionId : transactionId;
846
+ const blockNumber = bodyBlockNumber === null || bodyBlockNumber === void 0 ? readBlockNumberHeader(response) : isBlockNumber(bodyBlockNumber) ? bodyBlockNumber : void 0;
847
+ return new SubmittedTransaction({
848
+ method,
849
+ uniqueKey,
850
+ transactionId: resolvedTransactionId === void 0 || resolvedTransactionId === "" ? null : resolvedTransactionId,
851
+ blockNumber: blockNumber ?? null,
852
+ mode,
853
+ result: mode === "queued" ? void 0 : data["result"],
854
+ dexBackendBaseUrl: this.dexBackendBaseUrl,
855
+ httpRequestor: this.requestor,
856
+ requestTimeoutMs: this.chainCallTimeoutMs,
857
+ ...(options == null ? void 0 : options.positionConfirmation) === void 0 ? {} : { positionConfirmation: options.positionConfirmation }
858
+ });
616
859
  }
617
- hasSigner() {
618
- return this.signer !== void 0;
860
+ /** Expose the requestor for sibling read services that share this gateway transport. */
861
+ get httpRequestor() {
862
+ return this.requestor;
619
863
  }
620
864
  };
865
+ function trimTrailingSlash(value) {
866
+ return value.replace(/\/$/u, "");
867
+ }
868
+ function invalidGatewayResponse(response, body, url, message) {
869
+ return new GSwapSDKError(message, "INVALID_GATEWAY_RESPONSE", {
870
+ status: response.status,
871
+ body,
872
+ url
873
+ });
874
+ }
875
+ function gatewayError(response, body, url) {
876
+ const object = asRecord2(body);
877
+ const nested = getObjectProperty(body, "error");
878
+ const code = getStringProperty(object, "code") ?? getStringProperty(nested, "code") ?? getStringProperty(nested, "ErrorKey") ?? "HTTP_ERROR";
879
+ const message = getStringProperty(object, "message") ?? getStringProperty(nested, "message") ?? getStringProperty(nested, "Message") ?? (typeof body === "string" ? body : `Gateway request failed with HTTP ${response.status}`);
880
+ const retryAfterMs = response.status === 429 ? readRetryAfter(response) : void 0;
881
+ if (code === "HTTP_ERROR") {
882
+ return new GSwapSDKError(message, code, { status: response.status, body, url });
883
+ }
884
+ return GSwapSDKError.fromGatewayBounce(code, message, response.status, retryAfterMs);
885
+ }
886
+ function asRecord2(value) {
887
+ return typeof value === "object" && value !== null ? value : void 0;
888
+ }
889
+ function isBlockNumber(value) {
890
+ return typeof value === "number" && Number.isInteger(value) && value >= 0;
891
+ }
892
+
893
+ // src/utils/debug.ts
894
+ import debug from "debug";
895
+ var debugLog = debug("GSWAP_SDK");
896
+
897
+ // src/version.ts
898
+ var SDK_VERSION = true ? "1.0.0-rc.3" : "1.0.0-rc.3";
621
899
 
622
900
  // src/classes/http_client.ts
623
901
  var HttpClient = class {
624
- constructor(httpRequestor = fetch) {
902
+ /** Create an HTTP client around fetch or an injected requestor. */
903
+ constructor(httpRequestor = fetch, timeoutMs = 3e4) {
625
904
  this.httpRequestor = httpRequestor;
905
+ this.timeoutMs = timeoutMs;
626
906
  }
627
- async sendRequest(method, baseUrl, basePath, endpoint, body) {
907
+ httpRequestor;
908
+ timeoutMs;
909
+ async sendRequest(method, baseUrl, basePath, endpoint, body, options) {
628
910
  const url = `${baseUrl}${basePath}${endpoint}`;
629
911
  debugLog(`Sending request to ${url} with body:`, body);
630
- const response = await this.httpRequestor(url, {
631
- method,
632
- headers: {
633
- "Content-Type": "application/json",
634
- "User-Agent": "GalaChain-SDK/0.0"
912
+ const response = await requestWithTimeout(
913
+ this.httpRequestor,
914
+ url,
915
+ {
916
+ method,
917
+ headers: {
918
+ "Content-Type": "application/json",
919
+ "User-Agent": `GalaChain-SDK/${SDK_VERSION}`
920
+ },
921
+ ...body ? { body: JSON.stringify(body) } : {},
922
+ ...(options == null ? void 0 : options.signal) === void 0 ? {} : { signal: options.signal }
635
923
  },
636
- ...body ? { body: JSON.stringify(body) } : {}
637
- });
924
+ this.timeoutMs
925
+ );
638
926
  if (!response.ok) {
639
927
  throw await GSwapSDKError.fromErrorResponse(url, response);
640
928
  }
641
- const json = await response.json();
929
+ const json = await readResponseBody(response);
642
930
  debugLog(`Response from ${baseUrl}${basePath}${endpoint}:`, json);
643
931
  return json;
644
932
  }
933
+ /** Send a JSON POST request and decode its response. */
645
934
  async sendPostRequest(baseUrl, basePath, endpoint, body) {
646
935
  return this.sendRequest("POST", baseUrl, basePath, endpoint, body);
647
936
  }
648
- async sendGetRequest(baseUrl, basePath, endpoint, params) {
937
+ /** Send a GET request with URL-encoded query parameters and decode its response. */
938
+ async sendGetRequest(baseUrl, basePath, endpoint, params, options) {
649
939
  const searchParams = params ? new URLSearchParams(params) : void 0;
650
940
  const endpointWithParams = searchParams ? `${endpoint}?${searchParams.toString()}` : endpoint;
651
- return this.sendRequest("GET", baseUrl, basePath, endpointWithParams, void 0);
941
+ return this.sendRequest("GET", baseUrl, basePath, endpointWithParams, void 0, options);
652
942
  }
653
943
  };
654
944
 
655
- // src/classes/pools.ts
656
- import BigNumber2 from "bignumber.js";
657
-
658
- // src/utils/token.ts
659
- function stringifyTokenClassKey(tokenClassKey, separator = "|") {
660
- if (typeof tokenClassKey === "string") {
661
- return tokenClassKey;
662
- }
663
- return `${tokenClassKey.collection}${separator}${tokenClassKey.category}${separator}${tokenClassKey.type}${separator}${tokenClassKey.additionalKey}`;
945
+ // src/utils/ordering.ts
946
+ function orderSymbols(a, b) {
947
+ return a < b ? [a, b] : [b, a];
948
+ }
949
+ function readOrderedSymbols(value) {
950
+ if (Array.isArray(value) && value.length >= 2) {
951
+ const token0 = value[0];
952
+ const token1 = value[1];
953
+ if (typeof token0 === "string" && typeof token1 === "string") return { token0, token1 };
954
+ }
955
+ if (typeof value === "object" && value !== null) {
956
+ const record = value;
957
+ const token0 = record["token0"];
958
+ const token1 = record["token1"];
959
+ if (typeof token0 === "string" && typeof token1 === "string") return { token0, token1 };
960
+ }
961
+ throw new GSwapSDKError("Unable to order trading symbols.", "VALIDATION_ERROR", { value });
962
+ }
963
+ function compositeKeyOf(token) {
964
+ return [token.collection, token.category, token.type, token.additionalKey].join("$");
664
965
  }
665
966
  function parseTokenClassKey(tokenClassKey) {
666
967
  if (typeof tokenClassKey === "object") {
@@ -671,12 +972,17 @@ function parseTokenClassKey(tokenClassKey) {
671
972
  additionalKey: tokenClassKey.additionalKey
672
973
  };
673
974
  }
674
- const [collection, category, type, additionalKey] = tokenClassKey.split("|");
675
- if (!collection || !category || !type || !additionalKey) {
676
- throw new GSwapSDKError(`Invalid token class key`, "INVALID_TOKEN_CLASS_KEY", {
677
- tokenClassKey
678
- });
975
+ const parts = tokenClassKey.includes("|") ? tokenClassKey.split("|") : tokenClassKey.split("$");
976
+ if (parts.length !== 4 || parts.some((part) => part.length === 0)) {
977
+ throw new GSwapSDKError(
978
+ "Invalid token class key: expected four non-empty parts",
979
+ "VALIDATION_ERROR",
980
+ {
981
+ tokenClassKey
982
+ }
983
+ );
679
984
  }
985
+ const [collection, category, type, additionalKey] = parts;
680
986
  return {
681
987
  collection,
682
988
  category,
@@ -684,1128 +990,1497 @@ function parseTokenClassKey(tokenClassKey) {
684
990
  additionalKey
685
991
  };
686
992
  }
687
- function compareTokens(first, second) {
688
- return stringifyTokenClassKey(first).localeCompare(stringifyTokenClassKey(second));
689
- }
690
- function getTokenOrdering(first, second, assertCorrectness, token1Data, token2Data) {
691
- const zeroForOne = compareTokens(first, second) < 0;
692
- if (zeroForOne) {
693
- return {
694
- token0: first,
695
- token1: second,
696
- zeroForOne,
697
- token0Attributes: token1Data,
698
- token1Attributes: token2Data
699
- };
700
- } else {
701
- if (assertCorrectness) {
702
- throw GSwapSDKError.incorrectTokenOrderingError(first, second);
703
- }
704
- return {
705
- token0: second,
706
- token1: first,
707
- zeroForOne,
708
- token0Attributes: token2Data,
709
- token1Attributes: token1Data
710
- };
711
- }
712
- }
713
993
 
714
994
  // src/classes/pools.ts
715
995
  var Pools = class {
716
- constructor(gatewayBaseUrl, dexContractBasePath, httpClient) {
717
- this.gatewayBaseUrl = gatewayBaseUrl;
718
- this.dexContractBasePath = dexContractBasePath;
719
- this.httpClient = httpClient;
996
+ /**
997
+ * Creates a pool service.
998
+ *
999
+ * @example
1000
+ * ```ts
1001
+ * const pools = new Pools(gateway, symbols);
1002
+ * ```
1003
+ */
1004
+ constructor(gateway, symbols) {
1005
+ this.gateway = gateway;
1006
+ this.symbols = symbols;
1007
+ this.http = new HttpClient(gateway.httpRequestor, gateway.requestTimeoutMs ?? 3e4);
1008
+ }
1009
+ gateway;
1010
+ symbols;
1011
+ http;
1012
+ /**
1013
+ * Fetches every current-contract pool from the swap backend.
1014
+ *
1015
+ * @example
1016
+ * ```ts
1017
+ * const pools = await service.getPools();
1018
+ * console.log(pools.length);
1019
+ * ```
1020
+ */
1021
+ async getPools(options) {
1022
+ const response = await this.http.sendGetRequest(
1023
+ this.gateway.dexBackendBaseUrl,
1024
+ "/v2/trade",
1025
+ "/pools",
1026
+ void 0,
1027
+ (options == null ? void 0 : options.signal) === void 0 ? void 0 : { signal: options.signal }
1028
+ );
1029
+ if (!Array.isArray(response.data) || !response.data.every(isPoolListInfo)) {
1030
+ throw new GSwapSDKError("Backend returned an invalid pool list.", "INVALID_CHAIN_RESPONSE", {
1031
+ data: response.data
1032
+ });
1033
+ }
1034
+ return response.data;
720
1035
  }
721
1036
  /**
722
- * Gets pool data for a specific token pair and fee tier.
1037
+ * Fetches one pool from the backend, preserving whether the request order was flipped.
1038
+ *
1039
+ * @example
1040
+ * ```ts
1041
+ * const pool = await service.getPool('GUSDC', 'GALA', 3000);
1042
+ * console.log(pool.flippedFromRequest);
1043
+ * ```
723
1044
  */
724
- async getPoolData(token0, token1, fee) {
1045
+ async getPool(token0, token1, fee) {
725
1046
  validateFee(fee);
726
- const token0Class = parseTokenClassKey(token0);
727
- const token1Class = parseTokenClassKey(token1);
728
- const ordering = getTokenOrdering(token0Class, token1Class, false);
729
- const responseBody = await this.httpClient.sendPostRequest(this.gatewayBaseUrl, this.dexContractBasePath, "/GetPoolData", {
730
- token0: ordering.token0,
731
- token1: ordering.token1,
732
- fee
733
- });
734
- const rawData = responseBody.Data;
735
- return {
736
- bitmap: rawData.bitmap,
737
- fee: rawData.fee,
738
- feeGrowthGlobal0: BigNumber2(rawData.feeGrowthGlobal0),
739
- feeGrowthGlobal1: BigNumber2(rawData.feeGrowthGlobal1),
740
- grossPoolLiquidity: BigNumber2(rawData.grossPoolLiquidity),
741
- liquidity: BigNumber2(rawData.liquidity),
742
- maxLiquidityPerTick: BigNumber2(rawData.maxLiquidityPerTick),
743
- protocolFees: rawData.protocolFees,
744
- protocolFeesToken0: BigNumber2(rawData.protocolFeesToken0),
745
- protocolFeesToken1: BigNumber2(rawData.protocolFeesToken1),
746
- sqrtPrice: BigNumber2(rawData.sqrtPrice),
747
- tickSpacing: rawData.tickSpacing,
748
- token0: rawData.token0,
749
- token0ClassKey: rawData.token0ClassKey,
750
- token1: rawData.token1,
751
- token1ClassKey: rawData.token1ClassKey
752
- };
1047
+ return this.getBackend("/pool", await this.backendParams(token0, token1, fee));
753
1048
  }
754
1049
  /**
755
- * Calculates the nearest valid tick value for a given price.
1050
+ * Fetches the current sqrt price, price, and tick for one pool.
1051
+ *
1052
+ * @example
1053
+ * ```ts
1054
+ * const slot0 = await service.getSlot0('GALA', 'GUSDC', 3000);
1055
+ * console.log(slot0.tick);
1056
+ * ```
756
1057
  */
757
- calculateTicksForPrice(price, tickSpacing) {
758
- validateNumericAmount(price, "price", true);
759
- validateTickSpacing(tickSpacing);
760
- const priceNumber = BigNumber2(price).toNumber();
761
- if (priceNumber === 0) {
762
- return -886800;
763
- }
764
- if (priceNumber === Infinity) {
765
- return 886800;
766
- }
767
- const uncoercedTicks = Math.round(Math.log(priceNumber) / Math.log(1.0001));
768
- const ticks = Math.floor(uncoercedTicks / tickSpacing) * tickSpacing;
769
- return Math.min(Math.max(ticks, -886800), 886800);
770
- }
771
- calculatePriceForTicks(tick) {
772
- if (tick === -886800) {
773
- return BigNumber2("0");
774
- } else if (tick === 886800) {
775
- return BigNumber2(Infinity);
776
- } else {
777
- const price = Math.pow(1.0001, tick);
778
- return BigNumber2(price);
779
- }
1058
+ async getSlot0(token0, token1, fee) {
1059
+ validateFee(fee);
1060
+ return this.getBackend("/slot0", await this.backendParams(token0, token1, fee));
780
1061
  }
781
1062
  /**
782
- * Calculates the current spot price of a pool based on sqrt price.
783
- * Price is defined as the amount of outToken you would receive for 1 inToken.
1063
+ * Fetches the complete chain composite pool snapshot, in canonical symbol order.
1064
+ *
1065
+ * @example
1066
+ * ```ts
1067
+ * const composite = await service.getCompositePool('GALA', 'GUSDC', 3000);
1068
+ * console.log(composite.positions?.length ?? 0);
1069
+ * ```
784
1070
  */
785
- calculateSpotPrice(inToken, outToken, poolSqrtPrice) {
786
- validateNumericAmount(poolSqrtPrice, "poolSqrtPrice");
787
- const ordering = getTokenOrdering(inToken, outToken, false);
788
- const poolPrice = BigNumber2(poolSqrtPrice).pow(2);
789
- if (ordering.zeroForOne) {
790
- return poolPrice;
791
- } else {
792
- return BigNumber2(1).div(poolPrice);
1071
+ async getCompositePool(token0, token1, fee) {
1072
+ validateFee(fee);
1073
+ const first = await resolveSymbol(this.symbols, token0);
1074
+ const second = await resolveSymbol(this.symbols, token1);
1075
+ const ordered = readOrderedSymbols(orderSymbols(first, second));
1076
+ return this.getBackend("/composite-pool", {
1077
+ token0: ordered.token0,
1078
+ token1: ordered.token1,
1079
+ fee: String(fee)
1080
+ });
1081
+ }
1082
+ async backendParams(token0, token1, fee) {
1083
+ return {
1084
+ token0: await resolveSymbol(this.symbols, token0),
1085
+ token1: await resolveSymbol(this.symbols, token1),
1086
+ fee: String(fee)
1087
+ };
1088
+ }
1089
+ async getBackend(endpoint, params) {
1090
+ try {
1091
+ const response = await this.http.sendGetRequest(
1092
+ this.gateway.dexBackendBaseUrl,
1093
+ "/v2/trade",
1094
+ endpoint,
1095
+ params
1096
+ );
1097
+ return response.data;
1098
+ } catch (error) {
1099
+ if (error instanceof GSwapSDKError) throw error;
1100
+ throw new GSwapSDKError("Pool request failed.", "HTTP_ERROR", { cause: error });
793
1101
  }
794
1102
  }
795
1103
  };
1104
+ async function resolveSymbol(symbols, token) {
1105
+ const resolved = await symbols.resolve(token);
1106
+ if (resolved.symbol.length > 0) return resolved.symbol;
1107
+ throw new GSwapSDKError("Token could not be resolved to a trading symbol.", "SYMBOL_NOT_FOUND", {
1108
+ token
1109
+ });
1110
+ }
1111
+ function isPoolListInfo(value) {
1112
+ if (typeof value !== "object" || value === null) return false;
1113
+ const row = value;
1114
+ const requiredNumbers = ["fee", "tickSpacing", "protocolFees", "tradingFees"];
1115
+ const optionalStrings = [
1116
+ "token0CompositeKey",
1117
+ "token1CompositeKey",
1118
+ "creator",
1119
+ "price",
1120
+ "sqrtPrice",
1121
+ "token0Tvl",
1122
+ "token1Tvl"
1123
+ ];
1124
+ const optionalNumbers = [
1125
+ "tick",
1126
+ "tvlUsd",
1127
+ "volume1d",
1128
+ "volume7d",
1129
+ "volume30d",
1130
+ "trades1d",
1131
+ "fee24h",
1132
+ "apr1d",
1133
+ "token0Price",
1134
+ "token1Price"
1135
+ ];
1136
+ return row["contractVersion"] === "v2" && typeof row["token0"] === "string" && typeof row["token1"] === "string" && typeof row["poolName"] === "string" && typeof row["poolRef"] === "string" && requiredNumbers.every((key) => isFiniteNumber(row[key])) && optionalStrings.every((key) => isOptionalString(row[key])) && optionalNumbers.every((key) => isOptionalNumber(row[key]));
1137
+ }
1138
+ function isFiniteNumber(value) {
1139
+ return typeof value === "number" && Number.isFinite(value);
1140
+ }
1141
+ function isOptionalString(value) {
1142
+ return value === void 0 || typeof value === "string";
1143
+ }
1144
+ function isOptionalNumber(value) {
1145
+ return value === void 0 || isFiniteNumber(value);
1146
+ }
796
1147
 
797
1148
  // src/classes/positions.ts
798
1149
  import BigNumber3 from "bignumber.js";
799
1150
  var Positions = class {
800
- constructor(gatewayBaseUrl, dexContractBasePath, bundlerService, poolService, httpClient, options) {
801
- this.gatewayBaseUrl = gatewayBaseUrl;
802
- this.dexContractBasePath = dexContractBasePath;
803
- this.options = options;
804
- this.httpClient = httpClient;
805
- this.bundlerService = bundlerService;
806
- this.poolService = poolService;
1151
+ constructor(gateway, symbols, signer, walletAddress) {
1152
+ this.gateway = gateway;
1153
+ this.symbols = symbols;
1154
+ this.signer = signer;
1155
+ this.walletAddress = walletAddress;
1156
+ this.http = new HttpClient(gateway.httpRequestor, gateway.requestTimeoutMs ?? 3e4);
807
1157
  }
808
- httpClient;
809
- bundlerService;
810
- poolService;
1158
+ gateway;
1159
+ symbols;
1160
+ signer;
1161
+ walletAddress;
1162
+ http;
811
1163
  /**
812
- * Get all liquidity positions for a specific wallet address.
813
- * @param ownerAddress - The wallet address to get positions for.
814
- * @param limit - Maximum number of positions to return.
815
- * @param bookmark - Pagination bookmark for retrieving additional results. If you call this function and it returns a bookmark that is not an empty string, you can pass that bookmark as this parameter in a subsequent call to fetch the next page.
816
- * @returns User positions and pagination bookmark
1164
+ * Gets all current-contract positions owned by an address.
1165
+ *
1166
+ * @param owner - GalaChain owner identity.
1167
+ * @returns Enriched positions from the v2 trade backend.
817
1168
  * @example
818
1169
  * ```typescript
819
- * const positions = await gSwap.positions.getUserPositions('eth|123...abc');
820
- * console.log(positions);
1170
+ * const positions = await gSwap.positions.getUserPositions('client|012345678901234567890123');
821
1171
  * ```
822
1172
  */
823
- async getUserPositions(ownerAddress, limit, bookmark) {
824
- const results = await this.sendUserPositionsRequest("/GetUserPositions", {
825
- user: ownerAddress,
826
- limit,
827
- bookmark
828
- });
829
- return {
830
- bookmark: results.nextBookMark,
831
- positions: results.positions
832
- };
1173
+ async getUserPositions(owner) {
1174
+ const response = await this.get("/positions", { user: owner });
1175
+ return response.data.map((position) => this.mapPosition(position));
833
1176
  }
834
1177
  /**
835
- * Gets detailed information about a specific liquidity position.
836
- * @param ownerAddress - The wallet address that owns the position.
837
- * @param position - Position parameters including tokens, fee, and tick range.
838
- * @param position.token0ClassKey - The first token in the position.
839
- * @param position.token1ClassKey - The second token in the position.
840
- * @param position.fee - The pool fee tier.
841
- * @param position.tickLower - The lower tick of the position range.
842
- * @param position.tickUpper - The upper tick of the position range.
843
- * @returns Detailed position information.
1178
+ * Gets one position, normalizing a caller-supplied reversed pair to canonical symbol order.
1179
+ * Reversed pairs also invert the price axis, so `[lower, upper]` becomes `[-upper, -lower]`.
1180
+ *
1181
+ * @param args - Pair, owner, fee, and position tick range.
1182
+ * @returns The position, or `null` when the backend returns 404.
844
1183
  * @example
845
1184
  * ```typescript
846
- * const position = await gSwap.positions.getPosition('eth|123...abc', {
847
- * token0ClassKey: 'GALA|Unit|none|none',
848
- * token1ClassKey: 'GUSDC|Unit|none|none',
849
- * fee: 500,
850
- * tickLower: -6000,
851
- * tickUpper: 6000
1185
+ * const position = await gSwap.positions.getPosition({
1186
+ * token0: 'GALA', token1: 'GUSDC', owner: 'client|012345678901234567890123',
1187
+ * fee: 3000, tickLower: -19200, tickUpper: 12000,
852
1188
  * });
853
- * console.log('Position:', position);
854
1189
  * ```
855
1190
  */
856
- async getPosition(ownerAddress, position) {
857
- const result = await this.sendPositionRequest("/GetPositions", {
858
- owner: ownerAddress,
859
- token0: parseTokenClassKey(position.token0ClassKey),
860
- token1: parseTokenClassKey(position.token1ClassKey),
861
- fee: position.fee,
862
- tickLower: position.tickLower,
863
- tickUpper: position.tickUpper
864
- });
865
- return result;
1191
+ async getPosition(args, signal) {
1192
+ const pair = await this.symbols.orderPair(args.token0, args.token1);
1193
+ const ticks = this.canonicalTicks(args.tickLower, args.tickUpper, pair.flipped);
1194
+ const response = await this.getNullable(
1195
+ "/position",
1196
+ {
1197
+ token0: pair.token0.symbol,
1198
+ token1: pair.token1.symbol,
1199
+ fee: `${args.fee}`,
1200
+ owner: args.owner,
1201
+ tickLower: `${ticks.tickLower}`,
1202
+ tickUpper: `${ticks.tickUpper}`
1203
+ },
1204
+ signal
1205
+ );
1206
+ return response === null ? null : this.mapPosition(response.data);
866
1207
  }
867
1208
  /**
868
- * Estimates the token amounts that would be received from removing liquidity from a position.
869
- * @param args - Parameters for estimating liquidity removal.
870
- * @param args.ownerAddress - The wallet address that owns the position.
871
- * @param args.positionId - The position identifier.
872
- * @param args.token0 - The first token in the pair.
873
- * @param args.token1 - The second token in the pair.
874
- * @param args.fee - The pool fee tier.
875
- * @param args.tickLower - The lower tick of the position range.
876
- * @param args.tickUpper - The upper tick of the position range.
877
- * @param args.amount - The amount of liquidity to remove.
878
- * @returns Estimated token amounts that would be received.
1209
+ * Estimates the other token amount and resulting liquidity for a deposit.
1210
+ *
1211
+ * @param args - Pair, tick range, deposit amount, and the amount's caller-side token index.
1212
+ * @returns Backend liquidity estimate.
879
1213
  * @example
880
1214
  * ```typescript
881
- * const estimation = await gSwap.positions.estimateRemoveLiquidity({
882
- * ownerAddress: 'client|635f048ab243d7eb7f5ba044',
883
- * positionId: '210f8e4dd1bbe1b4af4b977330ee7e4b68bc716f66e39c87a60fff0976ded3ea',
884
- * token0: 'GALA|Unit|none|none',
885
- * token1: 'GUSDT|Unit|none|none',
886
- * fee: 3000,
887
- * tickLower: -41100,
888
- * tickUpper: -40080,
889
- * amount: '1491.973332758921980256'
1215
+ * const estimate = await gSwap.positions.estimateAddLiquidity({
1216
+ * token0: 'GALA', token1: 'GUSDC', fee: 3000,
1217
+ * tickLower: -19200, tickUpper: 12000, amount: '100', amountIsToken0: true,
890
1218
  * });
891
- * console.log('Estimated tokens:', estimation);
892
1219
  * ```
893
1220
  */
894
- async estimateRemoveLiquidity(args) {
895
- validateWalletAddress(args.ownerAddress);
896
- validateFee(args.fee);
897
- validateTickRange(args.tickLower, args.tickUpper);
1221
+ async estimateAddLiquidity(args) {
898
1222
  validateNumericAmount(args.amount, "amount");
899
- const token0TokenClassKey = parseTokenClassKey(args.token0);
900
- const token1TokenClassKey = parseTokenClassKey(args.token1);
901
- const ordering = getTokenOrdering(token0TokenClassKey, token1TokenClassKey, false);
902
- const responseBody = await this.httpClient.sendPostRequest(this.gatewayBaseUrl, this.dexContractBasePath, "/GetRemoveLiquidityEstimation", {
903
- tickLower: args.tickLower,
904
- tickUpper: args.tickUpper,
905
- amount: BigNumber3(args.amount).toFixed(),
906
- token0: ordering.token0,
907
- token1: ordering.token1,
908
- fee: args.fee,
909
- owner: args.ownerAddress,
910
- positionId: args.positionId
1223
+ const response = await this.get("/add-liq-estimate", {
1224
+ token0: this.requestToken(args.token0),
1225
+ token1: this.requestToken(args.token1),
1226
+ fee: `${args.fee}`,
1227
+ tickLower: `${args.tickLower}`,
1228
+ tickUpper: `${args.tickUpper}`,
1229
+ amount: new BigNumber3(args.amount).toFixed(),
1230
+ amountIsToken0: String(args.amountIsToken0)
911
1231
  });
912
- return {
913
- amount0: BigNumber3(responseBody.Data.amount0),
914
- amount1: BigNumber3(responseBody.Data.amount1)
915
- };
1232
+ return response.data;
916
1233
  }
917
1234
  /**
918
- * Gets detailed information about a liquidity position by its ID.
919
- * @param ownerAddress - The wallet address that owns the position.
920
- * @param positionId - The unique identifier of the position.
921
- * @returns Detailed position information, or undefined if not found.
1235
+ * Estimates token amounts released by burning liquidity.
1236
+ *
1237
+ * @param args - Pair, tick range, fee tier, and liquidity quantity.
1238
+ * @returns Estimated token0 and token1 quantities.
922
1239
  * @example
923
1240
  * ```typescript
924
- * const position = await gSwap.positions.getPositionById('eth|123...abc', 'position-uuid-123');
925
- * if (position) {
926
- * console.log('Position found:', position);
927
- * } else {
928
- * console.log('Position not found');
929
- * }
1241
+ * const estimate = await gSwap.positions.estimateRemoveLiquidity({
1242
+ * token0: 'GALA', token1: 'GUSDC', fee: 3000,
1243
+ * tickLower: -19200, tickUpper: 12000, liquidity: '1000',
1244
+ * });
930
1245
  * ```
931
1246
  */
932
- async getPositionById(ownerAddress, positionId) {
933
- const userPositions = await this.getUserPositions(ownerAddress);
934
- const position = userPositions.positions.find((pos) => pos.positionId === positionId);
935
- if (!position) {
936
- return void 0;
937
- }
938
- return this.getPosition(ownerAddress, position);
1247
+ async estimateRemoveLiquidity(args) {
1248
+ validateNumericAmount(args.liquidity, "liquidity");
1249
+ const response = await this.get("/remove-liq-estimate", {
1250
+ token0: this.requestToken(args.token0),
1251
+ token1: this.requestToken(args.token1),
1252
+ fee: `${args.fee}`,
1253
+ tickLower: `${args.tickLower}`,
1254
+ tickUpper: `${args.tickUpper}`,
1255
+ liquidity: new BigNumber3(args.liquidity).toFixed()
1256
+ });
1257
+ return response.data;
939
1258
  }
940
1259
  /**
941
- * Creates a new position or adds liquidity to a position, using a specific tick range. Consider using `addLiquidityByPrice()` instead unless you want to use ticks directly.
942
- * @param args - Parameters for adding liquidity.
943
- * @param args.walletAddress - The wallet address adding liquidity.
944
- * @param args.positionId - The position identifier. If you're creating a new position, this should be an empty string.
945
- * @param args.token0 - The first token in the pair.
946
- * @param args.token1 - The second token in the pair.
947
- * @param args.fee - The pool fee tier.
948
- * @param args.tickLower - The lower tick of the position range.
949
- * @param args.tickUpper - The upper tick of the position range.
950
- * @param args.amount0Desired - Desired (also maximum) amount of token0 to add.
951
- * @param args.amount1Desired - Desired (also maximum) amount of token1 to add.
952
- * @param args.amount0Min - Minimum amount of token0 to add (slippage protection).
953
- * @param args.amount1Min - Minimum amount of token1 to add (slippage protection).
954
- * @returns Pending transaction.
1260
+ * Adds liquidity using an explicit tick range. Exactly one canonical deposit field is emitted.
1261
+ *
1262
+ * @param args - Pair, fee, range, deposit amount, and caller-side token index.
1263
+ * @returns The synchronously submitted transaction.
955
1264
  * @example
956
1265
  * ```typescript
957
- * const result = await gSwap.positions.addLiquidityByTicks({
958
- * walletAddress: 'eth|123...abc',
959
- * positionId: '',
960
- * token0: 'GALA|Unit|none|none',
961
- * token1: 'GUSDC|Unit|none|none',
962
- * fee: 500,
963
- * tickSpacing: 10,
964
- * tickLower: -6000,
965
- * tickUpper: 6000,
966
- * amount0Desired: '100',
967
- * amount1Desired: '50',
968
- * amount0Min: '95',
969
- * amount1Min: '47.5'
1266
+ * const tx = await gSwap.positions.addLiquidityByTicks({
1267
+ * token0: 'GALA', token1: 'GUSDC', fee: 3000,
1268
+ * tickLower: -19200, tickUpper: 12000, amount: '100', amountIsToken0: true,
970
1269
  * });
971
- * console.log('Liquidity added:', result);
1270
+ * await tx.confirm();
972
1271
  * ```
973
1272
  */
974
1273
  async addLiquidityByTicks(args) {
975
- var _a;
976
- const walletAddress = args.walletAddress ?? ((_a = this.options) == null ? void 0 : _a.walletAddress);
977
- validateWalletAddress(walletAddress);
978
1274
  validateFee(args.fee);
979
- validateTickRange(args.tickLower, args.tickUpper);
980
- validateNumericAmount(args.amount0Desired, "amount0Desired", true);
981
- validateNumericAmount(args.amount1Desired, "amount1Desired", true);
982
- validateNumericAmount(args.amount0Min, "amount0Min", true);
983
- validateNumericAmount(args.amount1Min, "amount1Min", true);
984
- const token0TokenClassKey = parseTokenClassKey(args.token0);
985
- const token1TokenClassKey = parseTokenClassKey(args.token1);
986
- const ordering = getTokenOrdering(
987
- token0TokenClassKey,
988
- token1TokenClassKey,
989
- true,
990
- [args.amount0Desired, args.amount0Min],
991
- [args.amount1Desired, args.amount1Min]
992
- );
993
- const toSign = {
994
- token0: ordering.token0,
995
- token1: ordering.token1,
1275
+ const pair = await this.symbols.orderPair(args.token0, args.token1);
1276
+ const ticks = this.canonicalTicks(args.tickLower, args.tickUpper, pair.flipped);
1277
+ assertTickRange(ticks.tickLower, ticks.tickUpper, args.fee);
1278
+ validateNumericAmount(args.amount, "amount");
1279
+ const amount = new BigNumber3(args.amount).toFixed();
1280
+ const dto = {
1281
+ token0: pair.token0.symbol,
1282
+ token1: pair.token1.symbol,
996
1283
  fee: args.fee,
997
- owner: args.walletAddress,
998
- tickLower: args.tickLower,
999
- tickUpper: args.tickUpper,
1000
- amount0Desired: BigNumber3(ordering.token0Attributes[0]).toFixed(),
1001
- amount1Desired: BigNumber3(ordering.token1Attributes[0]).toFixed(),
1002
- amount0Min: BigNumber3(ordering.token0Attributes[1]).toFixed(),
1003
- amount1Min: BigNumber3(ordering.token1Attributes[1]).toFixed(),
1004
- positionId: args.positionId,
1005
- liquidityProvider: args.walletAddress
1284
+ tickLower: ticks.tickLower,
1285
+ tickUpper: ticks.tickUpper,
1286
+ uniqueKey: this.uniqueKey(),
1287
+ ...pair.flipped !== args.amountIsToken0 ? { depositQuantityToken0: amount } : { depositQuantityToken1: amount }
1006
1288
  };
1007
- const token0StringKey = stringifyTokenClassKey(ordering.token0, "$");
1008
- const token1StringKey = stringifyTokenClassKey(ordering.token1, "$");
1009
- const poolString = `$pool$${token0StringKey}$${token1StringKey}$${args.fee}`;
1010
- const userPositionString = `$userPosition$${args.walletAddress}`;
1011
- const tokenBalance0 = `$tokenBalance$${token0StringKey}$${args.walletAddress}`;
1012
- const tokenBalance1 = `$tokenBalance$${token1StringKey}$${args.walletAddress}`;
1013
- const tokenBalance0Pool = `$tokenBalance$${token0StringKey}$${poolString}`;
1014
- const tokenBalance1Pool = `$tokenBalance$${token1StringKey}$${poolString}`;
1015
- const stringsInstructions = [
1016
- poolString,
1017
- userPositionString,
1018
- tokenBalance0,
1019
- tokenBalance1,
1020
- tokenBalance0Pool,
1021
- tokenBalance1Pool
1022
- ];
1023
- return this.bundlerService.sendBundlerRequest("AddLiquidity", toSign, stringsInstructions);
1289
+ return this.submit("AddLiquidity", dto, {
1290
+ kind: "add",
1291
+ identity: {
1292
+ token0: pair.token0.symbol,
1293
+ token1: pair.token1.symbol,
1294
+ fee: args.fee,
1295
+ tickLower: ticks.tickLower,
1296
+ tickUpper: ticks.tickUpper
1297
+ }
1298
+ });
1024
1299
  }
1025
1300
  /**
1026
- * Creates a new position or adds liquidity to a position, using a specified price range. Note that this method automatically converts your minPrice and maxPrice to ticks, rounding down if necessary.
1027
- * @param args - Parameters for adding liquidity.
1028
- * @param args.walletAddress - The wallet address adding liquidity.
1029
- * @param args.positionId - The position identifier. This should be an empty string if you are creating a new position.
1030
- * @param args.token0 - The first token in the pair.
1031
- * @param args.token1 - The second token in the pair.
1032
- * @param args.fee - The pool fee tier.
1033
- * @param args.tickSpacing - The tick spacing for the pool.
1034
- * @param args.minPrice - The minimum price for the position range.
1035
- * @param args.maxPrice - The maximum price for the position range.
1036
- * @param args.amount0Desired - Desired (also maximum) amount of token0 to add.
1037
- * @param args.amount1Desired - Desired (also maximum) amount of token1 to add.
1038
- * @param args.amount0Min - Minimum amount of token0 to add (slippage protection).
1039
- * @param args.amount1Min - Minimum amount of token1 to add (slippage protection).
1040
- * @returns Pending transaction.
1301
+ * Adds liquidity from prices, flooring the lower tick and ceiling the upper tick to fee spacing.
1302
+ * The resulting range is therefore no narrower than the requested price interval.
1303
+ *
1304
+ * @param args - Pair, fee, price range, deposit amount, and caller-side token index.
1305
+ * @returns The synchronously submitted transaction.
1041
1306
  * @example
1042
1307
  * ```typescript
1043
- * const result = await gSwap.positions.addLiquidityByPrice({
1044
- * walletAddress: 'eth|123...abc',
1045
- * positionId: '',
1046
- * token0: 'GALA|Unit|none|none',
1047
- * token1: 'GUSDC|Unit|none|none',
1048
- * fee: 500,
1049
- * tickSpacing: 10,
1050
- * minPrice: '0.45',
1051
- * maxPrice: '0.55',
1052
- * amount0Desired: '100',
1053
- * amount1Desired: '50',
1054
- * amount0Min: '95',
1055
- * amount1Min: '47.5'
1308
+ * const tx = await gSwap.positions.addLiquidityByPrice({
1309
+ * token0: 'GALA', token1: 'GUSDC', fee: 3000,
1310
+ * minPrice: '0.14', maxPrice: '0.16', amount: '100', amountIsToken0: true,
1056
1311
  * });
1057
- * console.log('Liquidity added with price range:', result);
1058
1312
  * ```
1059
1313
  */
1060
1314
  async addLiquidityByPrice(args) {
1061
- var _a, _b, _c, _d, _e;
1062
- const walletAddress = args.walletAddress ?? ((_a = this.options) == null ? void 0 : _a.walletAddress);
1063
- validateWalletAddress(walletAddress);
1064
1315
  validateFee(args.fee);
1065
- validateTickSpacing(args.tickSpacing);
1066
- validateNumericAmount(args.minPrice, "minPrice", true);
1067
- validateNumericAmount(args.maxPrice, "maxPrice");
1068
- validateNumericAmount(args.amount0Desired, "amount0Desired", true);
1069
- validateNumericAmount(args.amount1Desired, "amount1Desired", true);
1070
- validateNumericAmount(args.amount0Min, "amount0Min", true);
1071
- validateNumericAmount(args.amount1Min, "amount1Min", true);
1072
- if (BigNumber3(args.minPrice).isGreaterThan(BigNumber3(args.maxPrice))) {
1073
- throw new Error("Invalid price range: minPrice must be less than or equal to maxPrice");
1316
+ this.rejectNumber(args.minPrice, "minPrice");
1317
+ this.rejectNumber(args.maxPrice, "maxPrice");
1318
+ const minPrice = new BigNumber3(args.minPrice);
1319
+ const maxPrice = new BigNumber3(args.maxPrice);
1320
+ if (!minPrice.isFinite() || !maxPrice.isFinite() || minPrice.isLessThanOrEqualTo(0) || maxPrice.isLessThanOrEqualTo(0)) {
1321
+ throw new GSwapSDKError("Price bounds must be finite and positive.", "VALIDATION_ERROR");
1074
1322
  }
1075
- const token0TokenClassKey = parseTokenClassKey(args.token0);
1076
- const token1TokenClassKey = parseTokenClassKey(args.token1);
1077
- const ordering = getTokenOrdering(
1078
- token0TokenClassKey,
1079
- token1TokenClassKey,
1080
- true,
1081
- [args.amount0Desired, args.amount0Min],
1082
- [args.amount1Desired, args.amount1Min]
1083
- );
1084
- const minPriceTicks = this.poolService.calculateTicksForPrice(args.minPrice, args.tickSpacing);
1085
- const maxPriceTicks = this.poolService.calculateTicksForPrice(args.maxPrice, args.tickSpacing);
1086
- const tickLower = ordering.zeroForOne ? minPriceTicks : maxPriceTicks * -1;
1087
- const tickUpper = ordering.zeroForOne ? maxPriceTicks : minPriceTicks * -1;
1088
- const toSign = {
1089
- token0: ordering.token0,
1090
- token1: ordering.token1,
1323
+ if (minPrice.isGreaterThan(maxPrice)) {
1324
+ throw new GSwapSDKError(
1325
+ "minPrice must be less than or equal to maxPrice.",
1326
+ "VALIDATION_ERROR"
1327
+ );
1328
+ }
1329
+ const spacing = this.tickSpacing(args.fee);
1330
+ const tickLower = alignTickDown(tickFromPrice(minPrice), spacing);
1331
+ const tickUpper = alignTickUp(tickFromPrice(maxPrice), spacing);
1332
+ return this.addLiquidityByTicks({
1333
+ token0: args.token0,
1334
+ token1: args.token1,
1091
1335
  fee: args.fee,
1092
- owner: args.walletAddress,
1093
1336
  tickLower,
1094
1337
  tickUpper,
1095
- amount0Desired: (_b = ordering == null ? void 0 : ordering.token0Attributes) == null ? void 0 : _b[0],
1096
- amount1Desired: (_c = ordering == null ? void 0 : ordering.token1Attributes) == null ? void 0 : _c[0],
1097
- amount0Min: (_d = ordering == null ? void 0 : ordering.token0Attributes) == null ? void 0 : _d[1],
1098
- amount1Min: (_e = ordering == null ? void 0 : ordering.token1Attributes) == null ? void 0 : _e[1],
1099
- positionId: args.positionId
1100
- };
1101
- const token0StringKey = stringifyTokenClassKey(ordering.token0, "$");
1102
- const token1StringKey = stringifyTokenClassKey(ordering.token1, "$");
1103
- const poolString = `$pool$${token0StringKey}$${token1StringKey}$${args.fee}`;
1104
- const userPositionString = `$userPosition$${args.walletAddress}`;
1105
- const tokenBalance0 = `$tokenBalance$${token0StringKey}$${args.walletAddress}`;
1106
- const tokenBalance1 = `$tokenBalance$${token1StringKey}$${args.walletAddress}`;
1107
- const tokenBalance0Pool = `$tokenBalance$${token0StringKey}$${poolString}`;
1108
- const tokenBalance1Pool = `$tokenBalance$${token1StringKey}$${poolString}`;
1109
- const stringsInstructions = [
1110
- poolString,
1111
- userPositionString,
1112
- tokenBalance0,
1113
- tokenBalance1,
1114
- tokenBalance0Pool,
1115
- tokenBalance1Pool
1116
- ];
1117
- return this.bundlerService.sendBundlerRequest("AddLiquidity", toSign, stringsInstructions);
1338
+ amount: args.amount,
1339
+ amountIsToken0: args.amountIsToken0
1340
+ });
1118
1341
  }
1119
1342
  /**
1120
- * Removes liquidity from a position.
1121
- * @param args - Parameters for removing liquidity.
1122
- * @param args.walletAddress - The wallet address removing liquidity.
1123
- * @param args.positionId - The position identifier.
1124
- * @param args.token0 - The first token in the pair.
1125
- * @param args.token1 - The second token in the pair.
1126
- * @param args.fee - The pool fee tier.
1127
- * @param args.tickLower - The lower tick of the position range.
1128
- * @param args.tickUpper - The upper tick of the position range.
1129
- * @param args.amount - The amount of liquidity to remove.
1130
- * @param args.amount0Min - Minimum amount of token0 to receive (slippage protection, optional).
1131
- * @param args.amount1Min - Minimum amount of token1 to receive (slippage protection, optional).
1132
- * @returns Pending transaction.
1343
+ * Removes liquidity by withdrawing at most one canonical token quantity.
1344
+ * Omitting both amounts closes the position and sweeps all accrued fees.
1345
+ *
1346
+ * @param args - Pair, fee, range, and optional caller-side withdrawal amount.
1347
+ * @returns The synchronously submitted transaction.
1133
1348
  * @example
1134
1349
  * ```typescript
1135
- * // Remove 50% of liquidity from a position
1136
- * const result = await gSwap.positions.removeLiquidity({
1137
- * walletAddress: 'eth|123...abc',
1138
- * positionId: 'position-123',
1139
- * token0: 'GALA|Unit|none|none',
1140
- * token1: 'GUSDC|Unit|none|none',
1141
- * fee: 500,
1142
- * tickLower: -6000,
1143
- * tickUpper: 6000,
1144
- * amount: '50000000000000000000', // 50% of position liquidity
1145
- * amount0Min: '45',
1146
- * amount1Min: '22'
1350
+ * const tx = await gSwap.positions.removeLiquidity({
1351
+ * token0: 'GALA', token1: 'GUSDC', fee: 3000,
1352
+ * tickLower: -19200, tickUpper: 12000,
1147
1353
  * });
1148
- * console.log('Liquidity removed:', result);
1149
1354
  * ```
1150
1355
  */
1151
1356
  async removeLiquidity(args) {
1152
- var _a, _b, _c;
1153
- const walletAddress = args.walletAddress ?? ((_a = this.options) == null ? void 0 : _a.walletAddress);
1154
- validateWalletAddress(walletAddress);
1155
1357
  validateFee(args.fee);
1156
- validateTickRange(args.tickLower, args.tickUpper);
1157
- validateNumericAmount(args.amount, "amount");
1158
- if (args.amount0Min !== void 0) {
1159
- validateNumericAmount(args.amount0Min, "amount0Min", true);
1358
+ const pair = await this.symbols.orderPair(args.token0, args.token1);
1359
+ const ticks = this.canonicalTicks(args.tickLower, args.tickUpper, pair.flipped);
1360
+ assertTickRange(ticks.tickLower, ticks.tickUpper, args.fee);
1361
+ if (args.amount0 !== void 0 && args.amount1 !== void 0) {
1362
+ throw new GSwapSDKError("Provide at most one of amount0 or amount1.", "VALIDATION_ERROR");
1160
1363
  }
1161
- if (args.amount1Min !== void 0) {
1162
- validateNumericAmount(args.amount1Min, "amount1Min", true);
1163
- }
1164
- const token0TokenClassKey = parseTokenClassKey(args.token0);
1165
- const token1TokenClassKey = parseTokenClassKey(args.token1);
1166
- const ordering = getTokenOrdering(
1167
- token0TokenClassKey,
1168
- token1TokenClassKey,
1169
- true,
1170
- [args.amount0Min ?? 0],
1171
- [args.amount1Min ?? 0]
1172
- );
1173
- const toSign = {
1174
- token0: ordering.token0,
1175
- token1: ordering.token1,
1364
+ if (args.amount0 !== void 0) validateNumericAmount(args.amount0, "amount0");
1365
+ if (args.amount1 !== void 0) validateNumericAmount(args.amount1, "amount1");
1366
+ const withdrawal = args.amount0 !== void 0 ? pair.flipped ? { withdrawalQuantityToken1: new BigNumber3(args.amount0).toFixed() } : { withdrawalQuantityToken0: new BigNumber3(args.amount0).toFixed() } : args.amount1 !== void 0 ? pair.flipped ? { withdrawalQuantityToken0: new BigNumber3(args.amount1).toFixed() } : { withdrawalQuantityToken1: new BigNumber3(args.amount1).toFixed() } : {};
1367
+ const dto = {
1368
+ token0: pair.token0.symbol,
1369
+ token1: pair.token1.symbol,
1176
1370
  fee: args.fee,
1177
- tickLower: args.tickLower,
1178
- tickUpper: args.tickUpper,
1179
- amount: BigNumber3(args.amount).toFixed(),
1180
- amount0Min: ((_b = ordering == null ? void 0 : ordering.token0Attributes) == null ? void 0 : _b[0]) || "0",
1181
- amount1Min: ((_c = ordering == null ? void 0 : ordering.token1Attributes) == null ? void 0 : _c[0]) || "0",
1182
- positionId: args.positionId,
1183
- recipient: args.walletAddress
1371
+ tickLower: ticks.tickLower,
1372
+ tickUpper: ticks.tickUpper,
1373
+ uniqueKey: this.uniqueKey(),
1374
+ ...withdrawal
1184
1375
  };
1185
- const token0StringKey = stringifyTokenClassKey(ordering.token0, "$");
1186
- const token1StringKey = stringifyTokenClassKey(ordering.token1, "$");
1187
- const poolString = `$pool$${token0StringKey}$${token1StringKey}$${args.fee}`;
1188
- const userPositionString = `$userPosition$${args.walletAddress}`;
1189
- const tokenBalance0 = `$tokenBalance$${token0StringKey}$${args.walletAddress}`;
1190
- const tokenBalance1 = `$tokenBalance$${token1StringKey}$${args.walletAddress}`;
1191
- const tokenBalance0Pool = `$tokenBalance$${token0StringKey}$${poolString}`;
1192
- const tokenBalance1Pool = `$tokenBalance$${token1StringKey}$${poolString}`;
1193
- const stringsInstructions = [
1194
- poolString,
1195
- userPositionString,
1196
- tokenBalance0,
1197
- tokenBalance1,
1198
- tokenBalance0Pool,
1199
- tokenBalance1Pool
1200
- ];
1201
- return this.bundlerService.sendBundlerRequest("RemoveLiquidity", toSign, stringsInstructions);
1376
+ const isFullClose = args.amount0 === void 0 && args.amount1 === void 0;
1377
+ return this.submit("RemoveLiquidity", dto, {
1378
+ kind: isFullClose ? "removeFull" : "removePartial",
1379
+ identity: {
1380
+ token0: pair.token0.symbol,
1381
+ token1: pair.token1.symbol,
1382
+ fee: args.fee,
1383
+ tickLower: ticks.tickLower,
1384
+ tickUpper: ticks.tickUpper
1385
+ }
1386
+ });
1202
1387
  }
1203
1388
  /**
1204
- * Collects accumulated fees from a liquidity position.
1205
- * @param args - Parameters for collecting fees.
1206
- * @param args.walletAddress - The wallet address collecting fees.
1207
- * @param args.positionId - The position identifier.
1208
- * @param args.token0 - The first token in the pair.
1209
- * @param args.token1 - The second token in the pair.
1210
- * @param args.fee - The pool fee tier.
1211
- * @param args.tickLower - The lower tick of the position range.
1212
- * @param args.tickUpper - The upper tick of the position range.
1213
- * @param args.amount0Requested - Desired amount of token0 fees to collect.
1214
- * @param args.amount1Requested - Desired amount of token1 fees to collect.
1215
- * @returns Pending transaction.
1389
+ * Collects all accrued fees for a position; the contract does not support partial collection.
1390
+ *
1391
+ * @param args - Pair, fee, and tick range identifying the position.
1392
+ * @returns The synchronously submitted transaction.
1216
1393
  * @example
1217
1394
  * ```typescript
1218
- * // Collect all accumulated fees from a position
1219
- * const result = await gSwap.positions.collectPositionFees({
1220
- * walletAddress: 'eth|123...abc',
1221
- * positionId: 'position-123',
1222
- * token0: 'GALA|Unit|none|none',
1223
- * token1: 'GUSDC|Unit|none|none',
1224
- * fee: 500,
1225
- * tickLower: -6000,
1226
- * tickUpper: 6000,
1227
- * amount0Requested: '1000000000000000000', // Max fees available
1228
- * amount1Requested: '500000000' // Max fees available
1395
+ * const tx = await gSwap.positions.collectPositionFees({
1396
+ * token0: 'GALA', token1: 'GUSDC', fee: 3000,
1397
+ * tickLower: -19200, tickUpper: 12000,
1229
1398
  * });
1230
- * console.log('Fees collected:', result);
1231
1399
  * ```
1232
1400
  */
1233
1401
  async collectPositionFees(args) {
1234
- var _a;
1235
- const walletAddress = args.walletAddress ?? ((_a = this.options) == null ? void 0 : _a.walletAddress);
1236
- validateWalletAddress(walletAddress);
1237
1402
  validateFee(args.fee);
1238
- validateTickRange(args.tickLower, args.tickUpper);
1239
- validateNumericAmount(args.amount0Requested, "amount0Requested", true);
1240
- validateNumericAmount(args.amount1Requested, "amount1Requested", true);
1241
- const token0TokenClassKey = parseTokenClassKey(args.token0);
1242
- const token1TokenClassKey = parseTokenClassKey(args.token1);
1243
- const ordering = getTokenOrdering(
1244
- token0TokenClassKey,
1245
- token1TokenClassKey,
1246
- true,
1247
- [args.amount0Requested],
1248
- [args.amount1Requested]
1249
- );
1250
- const toSign = {
1251
- token0: ordering.token0,
1252
- token1: ordering.token1,
1403
+ const pair = await this.symbols.orderPair(args.token0, args.token1);
1404
+ const ticks = this.canonicalTicks(args.tickLower, args.tickUpper, pair.flipped);
1405
+ assertTickRange(ticks.tickLower, ticks.tickUpper, args.fee);
1406
+ const dto = {
1407
+ token0: pair.token0.symbol,
1408
+ token1: pair.token1.symbol,
1253
1409
  fee: args.fee,
1254
- amount0Requested: BigNumber3(ordering.token0Attributes[0]).toFixed(),
1255
- amount1Requested: BigNumber3(ordering.token1Attributes[0]).toFixed(),
1256
- tickLower: args.tickLower,
1257
- tickUpper: args.tickUpper,
1258
- positionId: args.positionId,
1259
- recipient: args.walletAddress
1410
+ tickLower: ticks.tickLower,
1411
+ tickUpper: ticks.tickUpper,
1412
+ uniqueKey: this.uniqueKey()
1260
1413
  };
1261
- const token0StringKey = stringifyTokenClassKey(ordering.token0, "$");
1262
- const token1StringKey = stringifyTokenClassKey(ordering.token1, "$");
1263
- const poolString = `$pool$${token0StringKey}$${token1StringKey}$${args.fee}`;
1264
- const userPositionString = `$userPosition$${args.walletAddress}`;
1265
- const tokenBalance0 = `$tokenBalance$${token0StringKey}$${args.walletAddress}`;
1266
- const tokenBalance1 = `$tokenBalance$${token1StringKey}$${args.walletAddress}`;
1267
- const tokenBalance0Pool = `$tokenBalance$${token0StringKey}$${poolString}`;
1268
- const tokenBalance1Pool = `$tokenBalance$${token1StringKey}$${poolString}`;
1269
- const stringsInstructions = [
1270
- poolString,
1271
- userPositionString,
1272
- tokenBalance0,
1273
- tokenBalance1,
1274
- tokenBalance0Pool,
1275
- tokenBalance1Pool
1276
- ];
1277
- return this.bundlerService.sendBundlerRequest(
1278
- "CollectPositionFees",
1279
- toSign,
1280
- stringsInstructions
1281
- );
1414
+ return this.submit("CollectPositionFees", dto, {
1415
+ kind: "collect",
1416
+ identity: {
1417
+ token0: pair.token0.symbol,
1418
+ token1: pair.token1.symbol,
1419
+ fee: args.fee,
1420
+ tickLower: ticks.tickLower,
1421
+ tickUpper: ticks.tickUpper
1422
+ }
1423
+ });
1282
1424
  }
1283
- calculateOptimalPositionSize(tokenAmount, spotPrice, lowerPrice, upperPrice, tokenDecimals, otherTokenDecimals) {
1284
- validateNumericAmount(tokenAmount, "tokenAmount");
1285
- validatePriceValues(spotPrice, lowerPrice, upperPrice);
1286
- validateTokenDecimals(tokenDecimals, "tokenDecimals");
1287
- validateTokenDecimals(otherTokenDecimals, "otherTokenDecimals");
1288
- const bnTokenAmount = BigNumber3(tokenAmount);
1289
- const bnSpotPrice = BigNumber3(spotPrice);
1290
- const bnLowerPrice = BigNumber3(lowerPrice);
1291
- let bnUpperPrice = BigNumber3(upperPrice);
1292
- bnUpperPrice = bnUpperPrice.isFinite() ? bnUpperPrice : BigNumber3(1e18);
1293
- const liquidityAmount = bnTokenAmount.times(10 ** (tokenDecimals - otherTokenDecimals)).times(bnSpotPrice.sqrt()).times(bnUpperPrice.sqrt()).div(bnUpperPrice.sqrt().minus(bnSpotPrice.sqrt()));
1294
- const yAmount = BigNumber3(liquidityAmount).times(bnSpotPrice.sqrt().minus(bnLowerPrice.sqrt()));
1295
- const untruncated = yAmount.div(BigNumber3(10).pow(tokenDecimals - otherTokenDecimals));
1296
- return BigNumber3.max(
1297
- BigNumber3(untruncated.toFixed(otherTokenDecimals, BigNumber3.ROUND_DOWN)),
1298
- 0
1299
- );
1425
+ /**
1426
+ * Creates a pool, resolving registered trading symbols and falling back to class collections.
1427
+ * Reversed symbol order inverts the supplied starting price or square-root price.
1428
+ *
1429
+ * @param args - Token class keys or references, fee, exactly one starting price field, and privacy options.
1430
+ * @returns The synchronously submitted transaction.
1431
+ * @example
1432
+ * ```typescript
1433
+ * const tx = await gSwap.positions.createPool({
1434
+ * token0: 'GALA|Unit|none|none', token1: 'GUSDC|Unit|none|none', fee: 3000,
1435
+ * startingPrice: '0.15',
1436
+ * });
1437
+ * ```
1438
+ */
1439
+ async createPool(args) {
1440
+ var _a, _b;
1441
+ const hasPrice = args.startingPrice !== void 0;
1442
+ const hasSqrtPrice = args.startingSqrtPrice !== void 0;
1443
+ if (hasPrice === hasSqrtPrice) {
1444
+ throw new GSwapSDKError(
1445
+ "Provide exactly one of startingPrice or startingSqrtPrice.",
1446
+ "VALIDATION_ERROR"
1447
+ );
1448
+ }
1449
+ validateFee(args.fee);
1450
+ const [tokenA, tokenB] = await Promise.all([
1451
+ this.resolveCreateToken(args.token0),
1452
+ this.resolveCreateToken(args.token1)
1453
+ ]);
1454
+ const flipped = tokenA.symbol > tokenB.symbol;
1455
+ const [token0, token1] = flipped ? [tokenB, tokenA] : [tokenA, tokenB];
1456
+ const sourcePriceInput = hasPrice ? args.startingPrice : args.startingSqrtPrice;
1457
+ this.rejectNumber(sourcePriceInput, hasPrice ? "startingPrice" : "startingSqrtPrice");
1458
+ const sourcePrice = new BigNumber3(sourcePriceInput);
1459
+ if (!sourcePrice.isFinite() || sourcePrice.isLessThanOrEqualTo(0)) {
1460
+ throw new GSwapSDKError("Starting price must be finite and positive.", "VALIDATION_ERROR");
1461
+ }
1462
+ const canonicalPrice = flipped ? new BigNumber3(1).dividedBy(sourcePrice) : sourcePrice;
1463
+ const dto = {
1464
+ token0Key: token0.classKey,
1465
+ token1Key: token1.classKey,
1466
+ token0Symbol: token0.symbol,
1467
+ token1Symbol: token1.symbol,
1468
+ fee: args.fee,
1469
+ uniqueKey: this.uniqueKey(),
1470
+ ...hasPrice ? { startingPrice: canonicalPrice.toFixed() } : { startingSqrtPrice: canonicalPrice.toFixed() },
1471
+ ...args.isPrivate === void 0 ? {} : { isPrivate: args.isPrivate },
1472
+ ...args.privateAccess === void 0 ? {} : { privateAccess: args.privateAccess }
1473
+ };
1474
+ const transaction = await this.submit("CreatePool", dto, {
1475
+ kind: "createPool",
1476
+ token0: token0.symbol,
1477
+ token1: token1.symbol,
1478
+ fee: args.fee
1479
+ });
1480
+ (_b = (_a = this.symbols).invalidate) == null ? void 0 : _b.call(_a);
1481
+ return transaction;
1300
1482
  }
1301
- async sendUserPositionsRequest(endpoint, body) {
1302
- const responseBody = await this.httpClient.sendPostRequest(this.gatewayBaseUrl, this.dexContractBasePath, endpoint, body);
1303
- return {
1304
- nextBookMark: responseBody.Data.nextBookMark,
1305
- positions: responseBody.Data.positions.map((position) => ({
1306
- ...position,
1307
- liquidity: BigNumber3(position.liquidity)
1308
- }))
1483
+ async submit(method, dto, confirmation) {
1484
+ if (this.signer === void 0) throw GSwapSDKError.noSignerError();
1485
+ const signed = await this.signer.signObject(method, dto);
1486
+ const submitOptions = this.walletAddress === void 0 ? {} : { walletAddress: this.walletAddress };
1487
+ const owner = this.walletAddress;
1488
+ const positionConfirmation = this.buildPositionConfirmation(confirmation, owner);
1489
+ const options = {
1490
+ ...submitOptions,
1491
+ ...positionConfirmation === void 0 ? {} : { positionConfirmation }
1492
+ };
1493
+ return this.gateway.submit(method, signed, options);
1494
+ }
1495
+ /**
1496
+ * Builds a confirmation closure that proves the write's own effect, not just that a
1497
+ * position row exists (true before most of these writes run too, for any operation on a
1498
+ * pre-existing position — existence alone would false-confirm before the write executes,
1499
+ * and would never confirm a full close, whose whole point is that the position stops
1500
+ * existing).
1501
+ *
1502
+ * The "before" state is captured lazily, on the confirmation closure's own first poll —
1503
+ * not eagerly here in `submit()` — so confirming a write never adds an extra round-trip to
1504
+ * the write itself; the cost of establishing the baseline is paid by `confirm()`, only if
1505
+ * and when the caller actually asks to confirm.
1506
+ */
1507
+ buildPositionConfirmation(confirmation, owner) {
1508
+ if (confirmation === void 0) return void 0;
1509
+ if (confirmation.kind === "createPool") {
1510
+ const { token0, token1, fee } = confirmation;
1511
+ return async (signal) => {
1512
+ const pool = await this.getNullable(
1513
+ "/pool",
1514
+ { token0, token1, fee: `${fee}` },
1515
+ signal
1516
+ );
1517
+ return pool === null ? { confirmed: false } : { confirmed: true, position: null };
1518
+ };
1519
+ }
1520
+ if (owner === void 0) return void 0;
1521
+ const { kind, identity } = confirmation;
1522
+ let baseline;
1523
+ return async (signal) => {
1524
+ const current = await this.getPosition({ ...identity, owner }, signal);
1525
+ if (baseline === void 0) {
1526
+ baseline = {
1527
+ liquidity: new BigNumber3((current == null ? void 0 : current.liquidity) ?? 0),
1528
+ fees: new BigNumber3((current == null ? void 0 : current.fees0) ?? 0).plus(new BigNumber3((current == null ? void 0 : current.fees1) ?? 0))
1529
+ };
1530
+ return kind === "removeFull" && current === null ? { confirmed: true, position: null } : { confirmed: false };
1531
+ }
1532
+ switch (kind) {
1533
+ case "add":
1534
+ return current !== null && new BigNumber3(current.liquidity).isGreaterThan(baseline.liquidity) ? { confirmed: true, position: current } : { confirmed: false };
1535
+ case "removePartial":
1536
+ return current !== null && new BigNumber3(current.liquidity).isLessThan(baseline.liquidity) ? { confirmed: true, position: current } : { confirmed: false };
1537
+ case "removeFull":
1538
+ return current === null ? { confirmed: true, position: null } : { confirmed: false };
1539
+ case "collect": {
1540
+ if (current === null) return { confirmed: false };
1541
+ const currentFees = new BigNumber3(current.fees0 ?? 0).plus(
1542
+ new BigNumber3(current.fees1 ?? 0)
1543
+ );
1544
+ if (currentFees.isLessThan(baseline.fees)) return { confirmed: true, position: current };
1545
+ if (baseline.fees.isZero() && currentFees.isZero())
1546
+ return { confirmed: true, position: current };
1547
+ return { confirmed: false };
1548
+ }
1549
+ }
1309
1550
  };
1310
1551
  }
1311
- async sendPositionRequest(endpoint, body) {
1312
- const responseBody = await this.httpClient.sendPostRequest(this.gatewayBaseUrl, this.dexContractBasePath, endpoint, body);
1552
+ async get(endpoint, params, signal) {
1553
+ return this.http.sendGetRequest(
1554
+ this.gateway.dexBackendBaseUrl,
1555
+ "/v2/trade",
1556
+ endpoint,
1557
+ params,
1558
+ signal === void 0 ? void 0 : { signal }
1559
+ );
1560
+ }
1561
+ async getNullable(endpoint, params, signal) {
1562
+ try {
1563
+ return await this.get(endpoint, params, signal);
1564
+ } catch (error) {
1565
+ if (this.isNotFound(error)) return null;
1566
+ throw error;
1567
+ }
1568
+ }
1569
+ isNotFound(error) {
1570
+ if (!(error instanceof GSwapSDKError) || error.details === void 0) return false;
1571
+ return error.details["status"] === 404;
1572
+ }
1573
+ mapPosition(position) {
1313
1574
  return {
1314
- ...responseBody.Data,
1315
- feeGrowthInside0Last: BigNumber3(responseBody.Data.feeGrowthInside0Last),
1316
- feeGrowthInside1Last: BigNumber3(responseBody.Data.feeGrowthInside1Last),
1317
- liquidity: BigNumber3(responseBody.Data.liquidity),
1318
- tokensOwed0: BigNumber3(responseBody.Data.tokensOwed0),
1319
- tokensOwed1: BigNumber3(responseBody.Data.tokensOwed1)
1575
+ token0Symbol: position.token0Symbol,
1576
+ token1Symbol: position.token1Symbol,
1577
+ ...position.token0CompositeKey === void 0 ? {} : { token0CompositeKey: position.token0CompositeKey },
1578
+ ...position.token1CompositeKey === void 0 ? {} : { token1CompositeKey: position.token1CompositeKey },
1579
+ fee: position.fee,
1580
+ tickLower: position.tickLower,
1581
+ tickUpper: position.tickUpper,
1582
+ liquidity: position.liquidity,
1583
+ amount0: position.amount0,
1584
+ amount1: position.amount1,
1585
+ inRange: position.inRange,
1586
+ ...position.currentTick === void 0 ? {} : { currentTick: position.currentTick },
1587
+ ...position.sqrtPrice === void 0 ? {} : { sqrtPrice: position.sqrtPrice },
1588
+ pool: position.poolRef ?? position.pool ?? "",
1589
+ owner: position.owner,
1590
+ ...position.fees0 === void 0 ? {} : { fees0: position.fees0 },
1591
+ ...position.fees1 === void 0 ? {} : { fees1: position.fees1 }
1320
1592
  };
1321
1593
  }
1594
+ requestToken(ref) {
1595
+ return typeof ref === "string" ? ref : compositeKeyOf(ref);
1596
+ }
1597
+ canonicalTicks(tickLower, tickUpper, flipped) {
1598
+ return flipped ? { tickLower: -tickUpper, tickUpper: -tickLower } : { tickLower, tickUpper };
1599
+ }
1600
+ tickSpacing(fee) {
1601
+ const spacing = TICK_SPACING_BY_FEE[fee];
1602
+ if (spacing === void 0) {
1603
+ throw new GSwapSDKError(`Unsupported fee tier: ${fee}.`, "VALIDATION_ERROR");
1604
+ }
1605
+ return spacing;
1606
+ }
1607
+ rejectNumber(value, parameterName) {
1608
+ if (typeof value === "number") {
1609
+ throw new GSwapSDKError(
1610
+ `Invalid ${parameterName}: use a decimal string or BigNumber, not a JavaScript number`,
1611
+ "VALIDATION_ERROR"
1612
+ );
1613
+ }
1614
+ }
1615
+ uniqueKey() {
1616
+ return `gswap-sdk-${globalThis.crypto.randomUUID()}`;
1617
+ }
1618
+ async resolveCreateToken(ref) {
1619
+ try {
1620
+ const lookupRef = typeof ref === "object" ? compositeKeyOf(ref) : ref;
1621
+ const resolved = await this.symbols.resolve(lookupRef);
1622
+ const suppliedClassKey = this.tryParseClassKey(ref);
1623
+ return {
1624
+ symbol: resolved.symbol,
1625
+ classKey: suppliedClassKey ?? parseTokenClassKey({
1626
+ collection: resolved.collection,
1627
+ category: resolved.category,
1628
+ type: resolved.type,
1629
+ additionalKey: resolved.additionalKey
1630
+ })
1631
+ };
1632
+ } catch (error) {
1633
+ if (!(error instanceof GSwapSDKError) || error.code !== "UNKNOWN_TOKEN") {
1634
+ throw error;
1635
+ }
1636
+ let classKey;
1637
+ try {
1638
+ classKey = parseTokenClassKey(ref);
1639
+ } catch {
1640
+ throw error;
1641
+ }
1642
+ return { symbol: classKey.collection, classKey };
1643
+ }
1644
+ }
1645
+ tryParseClassKey(ref) {
1646
+ try {
1647
+ return parseTokenClassKey(ref);
1648
+ } catch {
1649
+ return void 0;
1650
+ }
1651
+ }
1322
1652
  };
1323
1653
 
1324
1654
  // src/classes/quoting.ts
1325
1655
  import BigNumber4 from "bignumber.js";
1326
-
1327
- // src/types/fees.ts
1328
- var FEE_TIER = /* @__PURE__ */ ((FEE_TIER2) => {
1329
- FEE_TIER2[FEE_TIER2["PERCENT_00_05"] = 500] = "PERCENT_00_05";
1330
- FEE_TIER2[FEE_TIER2["PERCENT_00_30"] = 3e3] = "PERCENT_00_30";
1331
- FEE_TIER2[FEE_TIER2["PERCENT_01_00"] = 1e4] = "PERCENT_01_00";
1332
- return FEE_TIER2;
1333
- })(FEE_TIER || {});
1334
-
1335
- // src/classes/quoting.ts
1336
1656
  var Quoting = class {
1337
- constructor(gatewayBaseUrl, dexContractBasePath, httpClient) {
1338
- this.gatewayBaseUrl = gatewayBaseUrl;
1339
- this.dexContractBasePath = dexContractBasePath;
1340
- this.httpClient = httpClient ?? new HttpClient();
1657
+ /**
1658
+ * Creates a quote service.
1659
+ *
1660
+ * @example
1661
+ * ```ts
1662
+ * const quoting = new Quoting('https://swap-backend.stage.defi.ovh.gala.com', http, symbols);
1663
+ * ```
1664
+ */
1665
+ constructor(dexBackendBaseUrl, http, symbols) {
1666
+ this.dexBackendBaseUrl = dexBackendBaseUrl;
1667
+ this.http = http;
1668
+ this.symbols = symbols;
1341
1669
  }
1342
- httpClient;
1670
+ dexBackendBaseUrl;
1671
+ http;
1672
+ symbols;
1343
1673
  /**
1344
- * Gets a quote for an exact amount of token being sold.
1345
- * @param tokenIn - The input token to sell.
1346
- * @param tokenOut - The output token to buy.
1347
- * @param amountIn - The exact amount of input tokens you want to sell.
1348
- * @param fee - The pool fee tier. If not specified, will check all available fee tiers and return the best quote.
1349
- * @returns The expected number of tokens you will receive (buy) when/if you execute the swap.
1674
+ * Quotes the output for a positive exact-input amount.
1675
+ *
1676
+ * @example
1677
+ * ```ts
1678
+ * const quote = await quoting.quoteExactInput('GALA', 'GUSDC', '100');
1679
+ * console.log(quote.amountOut);
1680
+ * ```
1350
1681
  */
1351
1682
  async quoteExactInput(tokenIn, tokenOut, amountIn, fee) {
1352
1683
  validateNumericAmount(amountIn, "amountIn");
1353
- if (fee !== void 0) {
1354
- const result = await this.getSingleQuoteExactInput(tokenIn, tokenOut, fee, amountIn);
1355
- return result;
1356
- }
1357
- const allFees = [500 /* PERCENT_00_05 */, 3e3 /* PERCENT_00_30 */, 1e4 /* PERCENT_01_00 */];
1358
- const quotePromises = allFees.map(async (feeTier) => {
1359
- try {
1360
- return await this.getSingleQuoteExactInput(tokenIn, tokenOut, feeTier, amountIn);
1361
- } catch (err) {
1362
- if (err instanceof GSwapSDKError && (err.code === "CONFLICT" || err.code === "OBJECT_NOT_FOUND")) {
1363
- return void 0;
1364
- }
1365
- throw err;
1366
- }
1367
- });
1368
- const results = await Promise.all(quotePromises);
1369
- const quotes = results.filter((quote) => quote !== void 0);
1370
- if (quotes.length === 0) {
1371
- throw GSwapSDKError.noPoolAvailableError(tokenIn, tokenOut);
1372
- }
1373
- return quotes.reduce(
1374
- (best, current) => current.outTokenAmount.isGreaterThan(best.outTokenAmount) ? current : best
1375
- );
1684
+ return this.quote(tokenIn, tokenOut, { amountIn: toDecimalString(amountIn) }, fee);
1376
1685
  }
1377
1686
  /**
1378
- * Gets a quote for an exact amount of tokens being bought.
1379
- * @param tokenIn - The input token sell.
1380
- * @param tokenOut - The output token to buy.
1381
- * @param amountOut - The exact amount of output tokens you want to buy.
1382
- * @param fee - The pool fee tier. If not specified, will check all available fee tiers and return the best quote.
1383
- * @returns The expected number of tokens you will need to sell (input) to receive the specified amount of output tokens.
1687
+ * Quotes the input for a positive exact-output amount.
1688
+ *
1689
+ * @example
1690
+ * ```ts
1691
+ * const quote = await quoting.quoteExactOutput('GALA', 'GUSDC', '10', 3000);
1692
+ * console.log(quote.amountIn);
1693
+ * ```
1384
1694
  */
1385
1695
  async quoteExactOutput(tokenIn, tokenOut, amountOut, fee) {
1386
1696
  validateNumericAmount(amountOut, "amountOut");
1387
- if (fee !== void 0) {
1388
- const result = await this.getSingleQuoteExactOutput(tokenIn, tokenOut, amountOut, fee);
1389
- return result;
1390
- }
1391
- const allFees = [500 /* PERCENT_00_05 */, 3e3 /* PERCENT_00_30 */, 1e4 /* PERCENT_01_00 */];
1392
- const quotePromises = allFees.map(async (feeTier) => {
1393
- try {
1394
- return await this.getSingleQuoteExactOutput(tokenIn, tokenOut, amountOut, feeTier);
1395
- } catch (err) {
1396
- if (err instanceof GSwapSDKError && (err.code === "CONFLICT" || err.code === "OBJECT_NOT_FOUND")) {
1397
- return void 0;
1398
- }
1399
- throw err;
1400
- }
1401
- });
1402
- const results = await Promise.all(quotePromises);
1403
- const quotes = results.filter((quote) => quote !== void 0);
1404
- if (quotes.length === 0) {
1405
- throw GSwapSDKError.noPoolAvailableError(tokenIn, tokenOut);
1697
+ return this.quote(tokenIn, tokenOut, { amountOut: toDecimalString(amountOut) }, fee);
1698
+ }
1699
+ async quote(tokenIn, tokenOut, amount, fee) {
1700
+ validateOptionalFee(fee);
1701
+ const tokenInSymbol = await resolveSymbol2(this.symbols, tokenIn);
1702
+ const tokenOutSymbol = await resolveSymbol2(this.symbols, tokenOut);
1703
+ const params = {
1704
+ tokenIn: tokenInSymbol,
1705
+ tokenOut: tokenOutSymbol,
1706
+ ...amount
1707
+ };
1708
+ if (fee !== void 0) params["fee"] = String(fee);
1709
+ try {
1710
+ const response = await this.http.sendGetRequest(
1711
+ this.dexBackendBaseUrl,
1712
+ "/v2/trade",
1713
+ "/quote",
1714
+ params
1715
+ );
1716
+ return mapQuote(response.data);
1717
+ } catch (error) {
1718
+ throw mapQuoteError(error, tokenIn, tokenOut, fee);
1406
1719
  }
1407
- return quotes.reduce(
1408
- (best, current) => current.inTokenAmount.isLessThan(best.inTokenAmount) ? current : best
1409
- );
1410
1720
  }
1411
- async getSingleQuote(tokenIn, tokenOut, fee, amount, isExactInput) {
1412
- const tokenInClass = parseTokenClassKey(tokenIn);
1413
- const tokenOutClass = parseTokenClassKey(tokenOut);
1414
- const ordering = getTokenOrdering(tokenInClass, tokenOutClass, false);
1415
- const formattedAmount = isExactInput ? BigNumber4(amount).toFixed() : BigNumber4(amount).multipliedBy(-1).toFixed();
1416
- const response = await this.sendQuoteRequest("/QuoteExactAmount", {
1417
- ...ordering,
1418
- fee,
1419
- amount: formattedAmount
1721
+ };
1722
+ function mapQuote(value) {
1723
+ if (!isQuoteWire(value)) {
1724
+ throw new GSwapSDKError("Backend returned an invalid quote.", "INVALID_CHAIN_RESPONSE", {
1725
+ data: value
1420
1726
  });
1421
- const tokenInAmount = ordering.zeroForOne ? response.amount0 : response.amount1;
1422
- const tokenOutAmount = ordering.zeroForOne ? response.amount1 : response.amount0;
1423
- let currentPrice = response.currentSqrtPrice.pow(2);
1424
- let newPrice = response.newSqrtPrice.pow(2);
1425
- if (!ordering.zeroForOne) {
1426
- currentPrice = BigNumber4(1).dividedBy(currentPrice);
1427
- newPrice = BigNumber4(1).dividedBy(newPrice);
1727
+ }
1728
+ const wire = value;
1729
+ const currentPrice = wire.currentPrice !== void 0 ? new BigNumber4(wire.currentPrice) : orientPrice(wire.currentSqrtPrice, wire.tokenInIsToken0);
1730
+ const newPrice = wire.newPrice !== void 0 ? new BigNumber4(wire.newPrice) : orientPrice(wire.newSqrtPrice, wire.tokenInIsToken0);
1731
+ const priceImpact = newPrice.minus(currentPrice).dividedBy(currentPrice);
1732
+ return {
1733
+ contractVersion: wire.contractVersion,
1734
+ fee: wire.fee,
1735
+ amountIn: wire.amountIn,
1736
+ amountOut: wire.amountOut,
1737
+ ...wire.currentSqrtPrice === void 0 ? {} : { currentSqrtPrice: wire.currentSqrtPrice },
1738
+ ...wire.newSqrtPrice === void 0 ? {} : { newSqrtPrice: wire.newSqrtPrice },
1739
+ feeTier: wire.fee,
1740
+ newTick: wire.newTick,
1741
+ tradingFees: wire.tradingFees,
1742
+ protocolFees: wire.protocolFees,
1743
+ totalFees: wire.totalFees,
1744
+ feeTokenSymbol: wire.feeTokenSymbol,
1745
+ token0Symbol: wire.token0Symbol,
1746
+ token1Symbol: wire.token1Symbol,
1747
+ tokenInIsToken0: wire.tokenInIsToken0,
1748
+ currentPrice,
1749
+ newPrice,
1750
+ priceImpact
1751
+ };
1752
+ }
1753
+ var HighPrecision = BigNumber4.clone({ DECIMAL_PLACES: 60 });
1754
+ function orientPrice(sqrtPrice, tokenInIsToken0) {
1755
+ const poolPrice = new HighPrecision(sqrtPrice).pow(2);
1756
+ return tokenInIsToken0 ? poolPrice : new HighPrecision(1).dividedBy(poolPrice);
1757
+ }
1758
+ function isQuoteWire(value) {
1759
+ if (typeof value !== "object" || value === null) return false;
1760
+ const wire = value;
1761
+ const requiredStrings = [
1762
+ "amountIn",
1763
+ "amountOut",
1764
+ "tradingFees",
1765
+ "protocolFees",
1766
+ "totalFees",
1767
+ "feeTokenSymbol",
1768
+ "token0Symbol",
1769
+ "token1Symbol"
1770
+ ];
1771
+ return wire["contractVersion"] === "v2" && typeof wire["fee"] === "number" && Number.isFinite(wire["fee"]) && requiredStrings.every((key) => typeof wire[key] === "string") && typeof wire["newTick"] === "number" && Number.isInteger(wire["newTick"]) && typeof wire["tokenInIsToken0"] === "boolean" && optionalPositiveDecimal(wire["currentSqrtPrice"]) && optionalPositiveDecimal(wire["newSqrtPrice"]) && optionalPositiveDecimal(wire["currentPrice"]) && optionalPositiveDecimal(wire["newPrice"]) && (wire["currentSqrtPrice"] !== void 0 || wire["currentPrice"] !== void 0) && (wire["newSqrtPrice"] !== void 0 || wire["newPrice"] !== void 0);
1772
+ }
1773
+ function optionalPositiveDecimal(value) {
1774
+ if (value === void 0) return true;
1775
+ if (typeof value !== "string") return false;
1776
+ try {
1777
+ const decimal = new BigNumber4(value);
1778
+ return decimal.isFinite() && decimal.isGreaterThan(0);
1779
+ } catch {
1780
+ return false;
1781
+ }
1782
+ }
1783
+ function mapQuoteError(error, tokenIn, tokenOut, fee) {
1784
+ if (error instanceof GSwapSDKError) {
1785
+ const status = readStatus(error.details);
1786
+ const message = readMessage(error.details) ?? error.message;
1787
+ if (status === 404 || /no pool|no pools|pool does not exist/iu.test(message)) {
1788
+ return GSwapSDKError.noPoolAvailableError(tokenIn, tokenOut, fee);
1428
1789
  }
1429
- const priceImpact = newPrice.minus(currentPrice).dividedBy(currentPrice);
1430
- return {
1431
- amount0: response.amount0,
1432
- amount1: response.amount1,
1433
- currentPoolSqrtPrice: response.currentSqrtPrice,
1434
- newPoolSqrtPrice: response.newSqrtPrice,
1435
- currentPrice,
1436
- newPrice,
1437
- inTokenAmount: tokenInAmount.abs(),
1438
- outTokenAmount: tokenOutAmount.abs(),
1439
- priceImpact,
1440
- feeTier: fee
1441
- };
1790
+ if (status === 400 && /insufficient liquidity/iu.test(message)) {
1791
+ return GSwapSDKError.insufficientLiquidityError(tokenIn, tokenOut, fee);
1792
+ }
1793
+ return error;
1794
+ }
1795
+ return new GSwapSDKError("Quote request failed.", "HTTP_ERROR", {
1796
+ cause: error,
1797
+ tokenIn,
1798
+ tokenOut,
1799
+ fee
1800
+ });
1801
+ }
1802
+ function readStatus(details) {
1803
+ const status = details == null ? void 0 : details["status"];
1804
+ return typeof status === "number" ? status : void 0;
1805
+ }
1806
+ function readMessage(details) {
1807
+ const direct = details == null ? void 0 : details["message"];
1808
+ if (typeof direct === "string") return direct;
1809
+ const body = details == null ? void 0 : details["body"];
1810
+ if (typeof body !== "object" || body === null || Array.isArray(body)) return void 0;
1811
+ const message = body["message"];
1812
+ return typeof message === "string" ? message : void 0;
1813
+ }
1814
+ function validateOptionalFee(fee) {
1815
+ if (fee !== void 0 && !ALL_FEE_TIERS.some((tier) => Number(tier) === Number(fee))) {
1816
+ throw new GSwapSDKError(`Invalid fee tier: ${fee}`, "VALIDATION_ERROR", { fee });
1442
1817
  }
1443
- async getSingleQuoteExactInput(tokenIn, tokenOut, fee, amountIn) {
1444
- return this.getSingleQuote(tokenIn, tokenOut, fee, amountIn, true);
1818
+ }
1819
+ function toDecimalString(amount) {
1820
+ return new BigNumber4(amount).toFixed();
1821
+ }
1822
+ async function resolveSymbol2(symbols, token) {
1823
+ const resolved = await symbols.resolve(token);
1824
+ if (resolved.symbol.length > 0) return resolved.symbol;
1825
+ throw new GSwapSDKError("Token could not be resolved to a trading symbol.", "SYMBOL_NOT_FOUND", {
1826
+ token
1827
+ });
1828
+ }
1829
+
1830
+ // src/classes/symbols.ts
1831
+ var SYMBOL_CACHE_TTL_MS = 6e4;
1832
+ var Symbols = class {
1833
+ /** Create a symbol service backed by the swap backend. */
1834
+ constructor(gateway) {
1835
+ this.gateway = gateway;
1836
+ this.http = new HttpClient(gateway.httpRequestor, gateway.requestTimeoutMs);
1837
+ }
1838
+ gateway;
1839
+ cachedSymbols;
1840
+ cachedAt = 0;
1841
+ refreshInFlight;
1842
+ http;
1843
+ /** List all registered GalaChainDex trading symbols, cached for 60 seconds. */
1844
+ async list() {
1845
+ if (this.cachedSymbols !== void 0 && Date.now() - this.cachedAt < SYMBOL_CACHE_TTL_MS) {
1846
+ return this.cachedSymbols;
1847
+ }
1848
+ if (this.refreshInFlight !== void 0) return this.refreshInFlight;
1849
+ this.refreshInFlight = this.http.sendGetRequest(this.gateway.dexBackendBaseUrl, "/v2/trade", "/symbols").then((response) => parseSymbols(response.data)).then((symbols) => {
1850
+ this.cachedSymbols = symbols;
1851
+ this.cachedAt = Date.now();
1852
+ return symbols;
1853
+ }).finally(() => {
1854
+ this.refreshInFlight = void 0;
1855
+ });
1856
+ return this.refreshInFlight;
1445
1857
  }
1446
- async getSingleQuoteExactOutput(tokenIn, tokenOut, amountOut, fee) {
1447
- return this.getSingleQuote(tokenIn, tokenOut, fee, amountOut, false);
1858
+ /** Invalidate the cached symbol registry after a write changes registration state.
1859
+ *
1860
+ * @example
1861
+ * ```ts
1862
+ * gSwap.symbols.invalidate();
1863
+ * ```
1864
+ */
1865
+ invalidate() {
1866
+ this.cachedSymbols = void 0;
1867
+ this.cachedAt = 0;
1448
1868
  }
1449
- async sendQuoteRequest(endpoint, body) {
1450
- const response = await this.httpClient.sendPostRequest(
1451
- this.gatewayBaseUrl,
1452
- this.dexContractBasePath,
1453
- endpoint,
1454
- body
1869
+ /** Force one registry refresh, bypassing the cache.
1870
+ *
1871
+ * @example
1872
+ * ```ts
1873
+ * const symbols = await gSwap.symbols.refresh();
1874
+ * ```
1875
+ */
1876
+ async refresh() {
1877
+ this.invalidate();
1878
+ this.refreshInFlight = void 0;
1879
+ return this.list();
1880
+ }
1881
+ /** Resolve a symbol or token class key to its registered symbol metadata. */
1882
+ async resolve(ref) {
1883
+ let symbols = await this.list();
1884
+ const composite = typeof ref === "string" ? isCompositeKey(ref) ? compositeKeyOf(parseTokenClassKey(ref)) : void 0 : compositeKeyOf(ref);
1885
+ const resolved = symbols.find(
1886
+ (entry) => entry.symbol === ref || composite !== void 0 && compositeKeyOf(entry) === composite
1455
1887
  );
1456
- const responseBody = response;
1888
+ if (resolved === void 0) {
1889
+ symbols = await this.refresh();
1890
+ const refreshed = symbols.find(
1891
+ (entry) => entry.symbol === ref || composite !== void 0 && compositeKeyOf(entry) === composite
1892
+ );
1893
+ if (refreshed === void 0) throw GSwapSDKError.unknownTokenError(ref);
1894
+ return refreshed;
1895
+ }
1896
+ return resolved;
1897
+ }
1898
+ /** Resolve and put two token references in canonical trading-symbol order. */
1899
+ async orderPair(a, b) {
1900
+ const [resolvedA, resolvedB] = await Promise.all([this.resolve(a), this.resolve(b)]);
1901
+ const [token0Symbol, token1Symbol] = orderSymbols(resolvedA.symbol, resolvedB.symbol);
1457
1902
  return {
1458
- amount0: BigNumber4(responseBody.Data.amount0),
1459
- amount1: BigNumber4(responseBody.Data.amount1),
1460
- currentSqrtPrice: BigNumber4(responseBody.Data.currentSqrtPrice),
1461
- newSqrtPrice: BigNumber4(responseBody.Data.newSqrtPrice)
1903
+ token0: token0Symbol === resolvedA.symbol ? resolvedA : resolvedB,
1904
+ token1: token1Symbol === resolvedB.symbol ? resolvedB : resolvedA,
1905
+ flipped: token0Symbol !== resolvedA.symbol
1462
1906
  };
1463
1907
  }
1464
1908
  };
1909
+ function parseSymbols(value) {
1910
+ if (!Array.isArray(value) || !value.every(isTradingSymbol)) {
1911
+ throw new GSwapSDKError("Backend returned an invalid symbol list.", "INVALID_CHAIN_RESPONSE", {
1912
+ data: value
1913
+ });
1914
+ }
1915
+ return value;
1916
+ }
1917
+ function isTradingSymbol(value) {
1918
+ if (typeof value !== "object" || value === null) return false;
1919
+ const entry = value;
1920
+ 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;
1921
+ }
1922
+ function isCompositeKey(ref) {
1923
+ return ref.includes("|") || ref.includes("$");
1924
+ }
1465
1925
 
1466
1926
  // src/classes/swaps.ts
1467
1927
  import BigNumber5 from "bignumber.js";
1468
- var MIN_SQRT_PRICE_LIMIT = "0.000000000000000000094212147";
1469
- var MAX_SQRT_PRICE_LIMIT = "18446050999999999999";
1928
+ var UNIQUE_KEY_PATTERN = /^[A-Za-z0-9._:-]{1,128}$/u;
1470
1929
  var Swaps = class {
1471
- constructor(bundlerService, options) {
1472
- this.bundlerService = bundlerService;
1473
- this.options = options;
1930
+ /**
1931
+ * Creates a swap service.
1932
+ *
1933
+ * @example
1934
+ * ```ts
1935
+ * const swaps = new Swaps(gateway, symbols, signer, 'client|alice');
1936
+ * ```
1937
+ */
1938
+ constructor(gateway, symbols, signer, walletAddress) {
1939
+ this.gateway = gateway;
1940
+ this.symbols = symbols;
1941
+ this.signer = signer;
1942
+ this.walletAddress = walletAddress;
1474
1943
  }
1944
+ gateway;
1945
+ symbols;
1946
+ signer;
1947
+ walletAddress;
1475
1948
  /**
1476
- * Executes a token swap transaction.
1477
- * @param walletAddress - The wallet address executing the swap.
1478
- * @param tokenIn - The input token to sell.
1479
- * @param tokenOut - The output token to buy.
1480
- * @param fee - The pool fee tier.
1481
- * @param amount - Swap parameters specifying either exact input or exact output.
1482
- * @param amount.exactIn - For exact input swaps, the exact amount of input tokens to sell.
1483
- * @param amount.amountOutMinimum - For exact input swaps, the minimum amount of output tokens to buy (slippage protection).
1484
- * @param amount.exactOut - For exact output swaps, the exact amount of output tokens to buy.
1485
- * @param amount.amountInMaximum - For exact output swaps, the maximum amount of input tokens to sell (slippage protection).
1486
- * @returns Pending transaction.
1949
+ * Signs and submits an exact-input or exact-output RequestTrade DTO. The returned transaction
1950
+ * is QUEUED; call `await tx.confirm()` to obtain the executed trade or chain rejection.
1951
+ *
1487
1952
  * @example
1488
- * ```typescript
1489
- * // Exact input swap: sell 100 GALA for USDC
1490
- * const result = await swapsService.swap(
1491
- * 'GALA|Unit|none|none',
1492
- * 'GUSDC|Unit|none|none',
1493
- * 500,
1494
- * { exactIn: '100', amountOutMinimum: '45' },
1495
- * 'eth|123...abc', // your wallet address
1496
- * );
1497
- * console.log('Swap successful:', result);
1953
+ * ```ts
1954
+ * const submitted = await swaps.swap('GALA', 'GUSDC', 3000, {
1955
+ * exactIn: '100',
1956
+ * amountOutMinimum: '14',
1957
+ * });
1498
1958
  * ```
1499
1959
  */
1500
- async swap(tokenIn, tokenOut, fee, amount, walletAddress) {
1501
- var _a, _b;
1502
- walletAddress = walletAddress ?? ((_a = this.options) == null ? void 0 : _a.walletAddress);
1503
- validateWalletAddress(walletAddress);
1960
+ async swap(tokenIn, tokenOut, fee, amount) {
1504
1961
  validateFee(fee);
1962
+ const dto = await this.buildRequestTradeDto(tokenIn, tokenOut, fee, amount);
1963
+ if (this.signer === void 0) throw GSwapSDKError.noSignerError();
1964
+ const signedDto = await this.signer.signObject("RequestTrade", dto);
1965
+ const submitOptions = this.walletAddress === void 0 ? {} : { walletAddress: this.walletAddress };
1966
+ return this.gateway.submit("RequestTrade", signedDto, submitOptions);
1967
+ }
1968
+ /**
1969
+ * Confirm a swap by its durable `uniqueKey` without resubmitting it. This is the recovery
1970
+ * path after a `CONFIRMATION_TIMEOUT`, a `SUBMISSION_OUTCOME_UNKNOWN`, a `409` replay
1971
+ * conflict, or a process restart: it reads the same apply-results record that
1972
+ * `SubmittedTransaction.confirm()` reads (retained for 7 days) and resolves the applied trade
1973
+ * or throws the chain's rejection. The first read happens immediately unless
1974
+ * `initialDelayMs` is given.
1975
+ *
1976
+ * @example
1977
+ * ```ts
1978
+ * const applied = await swaps.confirmSwap('gswap-sdk-2f1c…');
1979
+ * ```
1980
+ */
1981
+ async confirmSwap(uniqueKey, options) {
1982
+ if (!UNIQUE_KEY_PATTERN.test(uniqueKey)) {
1983
+ throw new GSwapSDKError(
1984
+ 'uniqueKey must be 1-128 characters of A-Z, a-z, 0-9, ".", "_", ":" or "-".',
1985
+ "VALIDATION_ERROR",
1986
+ { uniqueKey }
1987
+ );
1988
+ }
1989
+ const transaction = new SubmittedTransaction({
1990
+ method: "RequestTrade",
1991
+ uniqueKey,
1992
+ transactionId: null,
1993
+ mode: "queued",
1994
+ result: void 0,
1995
+ dexBackendBaseUrl: this.gateway.dexBackendBaseUrl,
1996
+ httpRequestor: this.gateway.httpRequestor,
1997
+ requestTimeoutMs: this.gateway.requestTimeoutMs
1998
+ });
1999
+ return transaction.confirm({ initialDelayMs: 0, ...options });
2000
+ }
2001
+ async buildRequestTradeDto(tokenIn, tokenOut, fee, amount) {
2002
+ const tokenInSymbol = await resolveSymbol3(this.symbols, tokenIn);
2003
+ const tokenOutSymbol = await resolveSymbol3(this.symbols, tokenOut);
2004
+ const ordered = readOrderedSymbols(orderSymbols(tokenInSymbol, tokenOutSymbol));
2005
+ const tokenInIsToken0 = tokenInSymbol === ordered.token0;
2006
+ const dto = {
2007
+ token0: ordered.token0,
2008
+ token1: ordered.token1,
2009
+ fee,
2010
+ uniqueKey: `gswap-sdk-${globalThis.crypto.randomUUID()}`
2011
+ };
1505
2012
  if ("exactIn" in amount) {
1506
- validateNumericAmount(amount.exactIn, "exactIn");
2013
+ const exactIn = amount.exactIn;
2014
+ if (exactIn === void 0) {
2015
+ throw new GSwapSDKError("exactIn is required for an exact-input swap.", "VALIDATION_ERROR");
2016
+ }
2017
+ validateNumericAmount(exactIn, "exactIn");
2018
+ dto[tokenInIsToken0 ? "sell0Qty" : "sell1Qty"] = toDecimalString2(exactIn);
1507
2019
  if (amount.amountOutMinimum !== void 0) {
1508
2020
  validateNumericAmount(amount.amountOutMinimum, "amountOutMinimum", true);
2021
+ dto["amountOutMinimum"] = toDecimalString2(amount.amountOutMinimum);
1509
2022
  }
1510
2023
  } else {
1511
- validateNumericAmount(amount.exactOut, "exactOut");
2024
+ const exactOut = amount.exactOut;
2025
+ if (exactOut === void 0) {
2026
+ throw new GSwapSDKError(
2027
+ "exactOut is required for an exact-output swap.",
2028
+ "VALIDATION_ERROR"
2029
+ );
2030
+ }
2031
+ validateNumericAmount(exactOut, "exactOut");
2032
+ dto[tokenInIsToken0 ? "buy1Qty" : "buy0Qty"] = toDecimalString2(exactOut);
1512
2033
  if (amount.amountInMaximum !== void 0) {
1513
- validateNumericAmount(amount.amountInMaximum, "amountInMaximum");
2034
+ validateNumericAmount(amount.amountInMaximum, "amountInMaximum", true);
2035
+ dto["amountInMaximum"] = toDecimalString2(amount.amountInMaximum);
1514
2036
  }
1515
2037
  }
1516
- const ordering = getTokenOrdering(tokenIn, tokenOut, false);
1517
- const zeroForOne = stringifyTokenClassKey(tokenIn) === stringifyTokenClassKey(ordering.token0);
1518
- const rawAmount = "exactIn" in amount ? BigNumber5(amount.exactIn).toFixed() : BigNumber5(amount.exactOut).multipliedBy(-1).toFixed();
1519
- const rawAmountOutMinimum = "exactIn" in amount ? ((_b = amount.amountOutMinimum) == null ? void 0 : _b.toString()) ? BigNumber5(amount.amountOutMinimum).multipliedBy(-1).toFixed() : void 0 : BigNumber5(amount.exactOut ?? 0).multipliedBy(-1).toFixed();
1520
- const rawAmountInMaximum = "exactIn" in amount ? BigNumber5(amount.exactIn).toFixed() : amount.amountInMaximum ? BigNumber5(amount.amountInMaximum).toFixed() : void 0;
1521
- const toSign = {
1522
- token0: parseTokenClassKey(ordering.token0),
1523
- token1: parseTokenClassKey(ordering.token1),
1524
- fee,
1525
- amount: rawAmount,
1526
- zeroForOne,
1527
- sqrtPriceLimit: ordering.zeroForOne ? MIN_SQRT_PRICE_LIMIT : MAX_SQRT_PRICE_LIMIT,
1528
- recipient: walletAddress,
1529
- amountOutMinimum: rawAmountOutMinimum,
1530
- amountInMaximum: rawAmountInMaximum
1531
- };
1532
- const token0StringKey = stringifyTokenClassKey(ordering.token0, "$");
1533
- const token1StringKey = stringifyTokenClassKey(ordering.token1, "$");
1534
- const poolString = `$pool$${token0StringKey}$${token1StringKey}$${fee}`;
1535
- const tokenBalance0 = `$tokenBalance$${token0StringKey}$${walletAddress}`;
1536
- const tokenBalance1 = `$tokenBalance$${token1StringKey}$${walletAddress}`;
1537
- const tokenBalance0Pool = `$tokenBalance$${token0StringKey}$${poolString}`;
1538
- const tokenBalance1Pool = `$tokenBalance$${token1StringKey}$${poolString}`;
1539
- const stringsInstructions = [
1540
- poolString,
1541
- tokenBalance0,
1542
- tokenBalance1,
1543
- tokenBalance0Pool,
1544
- tokenBalance1Pool
1545
- ];
1546
- return this.bundlerService.sendBundlerRequest("Swap", toSign, stringsInstructions);
2038
+ return dto;
2039
+ }
2040
+ };
2041
+ function toDecimalString2(amount) {
2042
+ return new BigNumber5(amount).toFixed();
2043
+ }
2044
+ async function resolveSymbol3(symbols, token) {
2045
+ const resolved = await symbols.resolve(token);
2046
+ if (resolved.symbol.length > 0) return resolved.symbol;
2047
+ throw new GSwapSDKError("Token could not be resolved to a trading symbol.", "SYMBOL_NOT_FOUND", {
2048
+ token
2049
+ });
2050
+ }
2051
+
2052
+ // src/types/env.ts
2053
+ var GSWAP_ENVIRONMENTS = {
2054
+ prod: {
2055
+ dexBackendBaseUrl: "https://dex-backend-prod1.defi.gala.com"
2056
+ },
2057
+ stage: {
2058
+ dexBackendBaseUrl: "https://swap-backend.stage.defi.ovh.gala.com"
1547
2059
  }
1548
2060
  };
1549
2061
 
1550
2062
  // src/classes/gswap.ts
1551
2063
  var GSwap = class {
1552
- gatewayBaseUrl;
1553
- dexContractBasePath;
1554
- tokenContractBasePath;
1555
- bundlerBaseUrl;
1556
- bundlingAPIBasePath;
1557
2064
  dexBackendBaseUrl;
1558
- transactionWaitTimeoutMs;
2065
+ chainCallTimeoutMs;
1559
2066
  signer;
2067
+ walletAddress;
2068
+ gateway;
2069
+ symbols;
2070
+ quoting;
2071
+ pools;
2072
+ positions;
2073
+ swaps;
2074
+ assets;
1560
2075
  /**
1561
- * Quoting functionality for price discovery and trade estimation.
1562
- * Use this to get quotes for token swaps without executing transactions.
2076
+ * Create an SDK client for prod or stage.
1563
2077
  *
1564
2078
  * @example
1565
2079
  * ```typescript
1566
- * // Get the best quote across all fee tiers
1567
- * const quote = await gSwap.quoting.quoteExactInput(tokenA, tokenB, amount);
2080
+ * const gSwap = new GSwap({ env: 'stage' });
2081
+ * const symbols = await gSwap.symbols.list();
1568
2082
  * ```
1569
2083
  */
1570
- quoting;
2084
+ constructor(options) {
2085
+ const environment = GSWAP_ENVIRONMENTS[(options == null ? void 0 : options.env) ?? "prod"];
2086
+ this.dexBackendBaseUrl = trimTrailingSlash2(
2087
+ (options == null ? void 0 : options.dexBackendBaseUrl) ?? environment.dexBackendBaseUrl
2088
+ );
2089
+ this.chainCallTimeoutMs = (options == null ? void 0 : options.chainCallTimeoutMs) ?? 3e4;
2090
+ this.signer = options == null ? void 0 : options.signer;
2091
+ this.walletAddress = options == null ? void 0 : options.walletAddress;
2092
+ const httpClient = new HttpClient(options == null ? void 0 : options.httpRequestor, this.chainCallTimeoutMs);
2093
+ this.gateway = new ChainGateway({
2094
+ dexBackendBaseUrl: this.dexBackendBaseUrl,
2095
+ chainCallTimeoutMs: this.chainCallTimeoutMs,
2096
+ ...(options == null ? void 0 : options.httpRequestor) === void 0 ? {} : { httpRequestor: options.httpRequestor },
2097
+ ...this.walletAddress === void 0 ? {} : { walletAddress: this.walletAddress }
2098
+ });
2099
+ this.symbols = new Symbols(this.gateway);
2100
+ this.quoting = new Quoting(this.dexBackendBaseUrl, httpClient, this.symbols);
2101
+ this.pools = new Pools(this.gateway, this.symbols);
2102
+ this.positions = new Positions(this.gateway, this.symbols, this.signer, this.walletAddress);
2103
+ this.swaps = new Swaps(this.gateway, this.symbols, this.signer, this.walletAddress);
2104
+ this.assets = new Assets(this.dexBackendBaseUrl, httpClient);
2105
+ }
2106
+ };
2107
+ function trimTrailingSlash2(value) {
2108
+ return value.replace(/\/$/u, "");
2109
+ }
2110
+
2111
+ // src/classes/signers.ts
2112
+ import { serialize, signatures } from "@gala-chain/api";
2113
+
2114
+ // src/utils/eip712.ts
2115
+ function generateEIP712Types(typeName, params) {
2116
+ const types = {};
2117
+ types[typeName] = [];
2118
+ function fieldsFor(name) {
2119
+ const fields = types[name];
2120
+ if (!fields) throw new Error(`Missing EIP-712 type definition for ${name}`);
2121
+ return fields;
2122
+ }
2123
+ function addField(name, fieldValue, parentTypeName, onlyGetType = false) {
2124
+ if (Array.isArray(fieldValue)) {
2125
+ const type = fieldValue.length > 0 ? addField(name, fieldValue[0], parentTypeName, true) : "string";
2126
+ if (!onlyGetType) fieldsFor(parentTypeName).push({ name, type: (type ?? name) + "[]" });
2127
+ } else if (typeof fieldValue === "object" && fieldValue !== null) {
2128
+ if (types[name]) {
2129
+ throw new Error("Name collisions not yet supported");
2130
+ }
2131
+ types[name] = [];
2132
+ Object.entries(fieldValue).forEach(([key, value]) => {
2133
+ addField(key, value, name);
2134
+ });
2135
+ if (!onlyGetType) fieldsFor(parentTypeName).push({ name, type: name });
2136
+ } else {
2137
+ let eipType;
2138
+ switch (typeof fieldValue) {
2139
+ case "string":
2140
+ eipType = "string";
2141
+ break;
2142
+ case "number":
2143
+ eipType = "int256";
2144
+ break;
2145
+ case "boolean":
2146
+ eipType = "bool";
2147
+ break;
2148
+ case "bigint":
2149
+ case "symbol":
2150
+ case "undefined":
2151
+ case "function":
2152
+ case "object":
2153
+ throw new Error(
2154
+ `Unsupported type, ${typeof fieldValue}, value: ${Object.prototype.toString.call(fieldValue)}`
2155
+ );
2156
+ }
2157
+ if (onlyGetType) {
2158
+ return eipType;
2159
+ }
2160
+ fieldsFor(parentTypeName).push({ name, type: eipType });
2161
+ }
2162
+ return void 0;
2163
+ }
2164
+ Object.entries(params).forEach(([key, value]) => {
2165
+ addField(key, value, typeName);
2166
+ });
2167
+ return types;
2168
+ }
2169
+ var EIP712_DOMAIN = { name: "ethereum", chainId: 1 };
2170
+ var EIP712_CAPABLE_METHODS = /* @__PURE__ */ new Set([
2171
+ "RequestTrade",
2172
+ "AddLiquidity",
2173
+ "RemoveLiquidity",
2174
+ "CollectPositionFees"
2175
+ ]);
2176
+ function numericOr0(dto, field) {
2177
+ return typeof dto[field] === "number" ? dto[field] : 0;
2178
+ }
2179
+ function completeAddLiquidityFields(dto) {
2180
+ return {
2181
+ ...dto,
2182
+ amount0Desired: numericOr0(dto, "amount0Desired"),
2183
+ amount0Min: numericOr0(dto, "amount0Min"),
2184
+ amount1Desired: numericOr0(dto, "amount1Desired"),
2185
+ amount1Min: numericOr0(dto, "amount1Min"),
2186
+ positionId: dto["positionId"] ?? ""
2187
+ };
2188
+ }
2189
+ function completeRemoveLiquidityFields(dto) {
2190
+ return {
2191
+ ...dto,
2192
+ amount: numericOr0(dto, "amount"),
2193
+ amount0Min: numericOr0(dto, "amount0Min"),
2194
+ amount1Min: numericOr0(dto, "amount1Min"),
2195
+ positionId: dto["positionId"] ?? ""
2196
+ };
2197
+ }
2198
+ function completeCollectPositionFeesFields(dto) {
2199
+ return {
2200
+ ...dto,
2201
+ amount0Requested: numericOr0(dto, "amount0Requested"),
2202
+ amount1Requested: numericOr0(dto, "amount1Requested"),
2203
+ positionId: dto["positionId"] ?? ""
2204
+ };
2205
+ }
2206
+ var EIP712_FIELD_COMPLETERS = {
2207
+ AddLiquidity: completeAddLiquidityFields,
2208
+ RemoveLiquidity: completeRemoveLiquidityFields,
2209
+ CollectPositionFees: completeCollectPositionFeesFields
2210
+ };
2211
+ function buildEIP712Payload(methodName, dto) {
2212
+ const completer = EIP712_FIELD_COMPLETERS[methodName];
2213
+ const completedDto = completer ? completer(dto) : dto;
2214
+ const types = generateEIP712Types(methodName, completedDto);
2215
+ return { completedDto, types };
2216
+ }
2217
+
2218
+ // src/classes/signers.ts
2219
+ var ETHEREUM_SIGNED_MESSAGE = String.fromCharCode(25) + "Ethereum Signed Message:\n";
2220
+ function personalSignPrefixFor(dto) {
2221
+ const withoutPrefix = { ...dto };
2222
+ delete withoutPrefix["prefix"];
2223
+ const message = serialize(withoutPrefix);
2224
+ return ETHEREUM_SIGNED_MESSAGE + String(new TextEncoder().encode(message).length);
2225
+ }
2226
+ function getWalletProvider() {
2227
+ var _a;
2228
+ const globalObject = globalThis;
2229
+ const wallet = (_a = globalObject.window) == null ? void 0 : _a.gala;
2230
+ if (!wallet) {
2231
+ throw new GSwapSDKError(
2232
+ "Gala wallet is not available. Please ensure the Gala wallet is connected.",
2233
+ "GALA_WALLET_NOT_AVAILABLE"
2234
+ );
2235
+ }
2236
+ return wallet;
2237
+ }
2238
+ function getNativeSignature(value) {
2239
+ if (typeof value !== "string") {
2240
+ throw new GSwapSDKError("Wallet returned an invalid signature.", "INVALID_SIGNATURE");
2241
+ }
2242
+ if (!/^[0-9a-fA-F]{130}$/u.test(value)) {
2243
+ throw new GSwapSDKError("Wallet returned an invalid native signature.", "INVALID_SIGNATURE");
2244
+ }
2245
+ return value;
2246
+ }
2247
+ function getPersonalSignature(value) {
2248
+ if (typeof value !== "string" || !/^(?:0x)?[0-9a-fA-F]{130}$/u.test(value)) {
2249
+ throw new GSwapSDKError(
2250
+ "Wallet returned an invalid personal-sign signature.",
2251
+ "INVALID_SIGNATURE"
2252
+ );
2253
+ }
2254
+ return value;
2255
+ }
2256
+ function normalizeEthereumAccount(address, allowGalaPrefix) {
2257
+ const normalized = allowGalaPrefix && address.startsWith("eth|") ? address.slice(4) : address;
2258
+ if (!/^0x[0-9a-fA-F]{40}$/u.test(normalized)) {
2259
+ throw new GSwapSDKError(
2260
+ "Wallet address must be the selected Ethereum account in 0x-prefixed form.",
2261
+ "VALIDATION_ERROR",
2262
+ { type: "INVALID_WALLET_ADDRESS", value: address }
2263
+ );
2264
+ }
2265
+ return `0x${normalized.slice(2).toLowerCase()}`;
2266
+ }
2267
+ function getErrorMessage(error) {
2268
+ if (error instanceof Error) {
2269
+ return error.message;
2270
+ }
2271
+ if (typeof error === "string") {
2272
+ return error;
2273
+ }
2274
+ if (typeof error === "object" && error !== null && "message" in error) {
2275
+ const message = error.message;
2276
+ return typeof message === "string" ? message : "";
2277
+ }
2278
+ return "";
2279
+ }
2280
+ function isUnsupportedNativeSchemeError(error) {
2281
+ return /unsupported|unknown scheme/i.test(getErrorMessage(error));
2282
+ }
2283
+ function personalSign(provider, dto, walletAddress, methodName) {
2284
+ const prefix = personalSignPrefixFor(dto);
2285
+ const payload = { ...dto, prefix };
2286
+ const params = methodName !== void 0 ? [serialize(payload), walletAddress, methodName] : [serialize(dto), walletAddress];
2287
+ return provider.request({ method: methodName !== void 0 ? "gala_signChainDto" : "personal_sign", params }).then((value) => ({ ...payload, signature: getPersonalSignature(value) }));
2288
+ }
2289
+ function signEIP712(provider, methodName, dto, walletAddress) {
2290
+ const { completedDto, types } = buildEIP712Payload(methodName, dto);
2291
+ const prefix = personalSignPrefixFor(completedDto);
2292
+ const message = { ...completedDto, prefix };
2293
+ const eip712Domain = [
2294
+ { name: "name", type: "string" },
2295
+ { name: "chainId", type: "uint256" }
2296
+ ];
2297
+ const payload = {
2298
+ domain: EIP712_DOMAIN,
2299
+ types: { ...types, EIP712Domain: eip712Domain },
2300
+ primaryType: methodName,
2301
+ message
2302
+ };
2303
+ return provider.request({
2304
+ method: "eth_signTypedData_v4",
2305
+ params: [walletAddress, JSON.stringify(payload)]
2306
+ }).then((value) => ({
2307
+ ...message,
2308
+ types,
2309
+ domain: EIP712_DOMAIN,
2310
+ signature: getPersonalSignature(value)
2311
+ }));
2312
+ }
2313
+ var PrivateKeySigner = class {
2314
+ keyBuffer;
1571
2315
  /**
1572
- * Position management operations for liquidity positions.
1573
- * Use this to manage liquidity positions including creation, modification, and fee collection.
2316
+ * Creates a native signer from a hex or base64 secp256k1 private key.
1574
2317
  *
1575
2318
  * @example
1576
2319
  * ```typescript
1577
- * // Get all user positions
1578
- * const positions = await gSwap.positions.getUserPositions('eth|123...abc');
2320
+ * const signer = new PrivateKeySigner('1'.padStart(64, '0'));
2321
+ * const signed = await signer.signObject('RequestTrade', { token0: 'GALA', token1: 'GUSDC' });
2322
+ * ```
2323
+ */
2324
+ constructor(privateKey) {
2325
+ this.keyBuffer = signatures.normalizePrivateKey(privateKey);
2326
+ }
2327
+ /**
2328
+ * Signs the DTO with GalaChain native signing.
1579
2329
  *
1580
- * // Add liquidity to a position using price range
1581
- * const result = await gSwap.positions.addLiquidityByPrice({
1582
- * walletAddress: 'eth|123...abc',
1583
- * positionId: '',
1584
- * token0: 'GALA|Unit|none|none',
1585
- * token1: 'GUSDC|Unit|none|none',
1586
- * fee: 500,
1587
- * tickSpacing: 10,
1588
- * minPrice: '0.45',
1589
- * maxPrice: '0.55',
1590
- * amount0Desired: '100',
1591
- * amount1Desired: '50',
1592
- * amount0Min: '95',
1593
- * amount1Min: '47.5'
2330
+ * @example
2331
+ * ```typescript
2332
+ * const signed = await signer.signObject('RequestTrade', {
2333
+ * token0: 'GALA',
2334
+ * token1: 'GUSDC',
2335
+ * fee: 3000,
1594
2336
  * });
1595
2337
  * ```
1596
2338
  */
1597
- positions;
2339
+ signObject(_methodName, dto) {
2340
+ const signature = signatures.getSignature(dto, this.keyBuffer);
2341
+ return Promise.resolve({ ...dto, signature });
2342
+ }
2343
+ };
2344
+ var GalaWalletSigner = class {
2345
+ /** The wallet address supplied to Gala Wallet for each signing request. */
2346
+ walletAddress;
2347
+ /** The scheme currently used, including any automatic native-to-personal fallback. */
2348
+ effectiveScheme;
1598
2349
  /**
1599
- * Token swap operations for trading tokens.
1600
- * Use this to execute token swaps on the DEX.
2350
+ * Creates a Gala Wallet signer.
1601
2351
  *
1602
2352
  * @example
1603
2353
  * ```typescript
1604
- * // Execute an exact input swap: sell 100 GALA for USDC
1605
- * const result = await gSwap.swaps.swap(
1606
- * 'GALA|Unit|none|none',
1607
- * 'GUSDC|Unit|none|none',
1608
- * 500,
1609
- * { exactIn: '100', amountOutMinimum: '45' },
1610
- * 'eth|123...abc', // your wallet address
1611
- * );
2354
+ * const signer = new GalaWalletSigner('0x0123456789012345678901234567890123456789');
2355
+ * const signed = await signer.signObject('RequestTrade', { token0: 'GALA', token1: 'GUSDC' });
1612
2356
  * ```
2357
+ *
2358
+ * @param walletAddress - The selected Ethereum account (`0x` plus 40 hex digits); Gala Wallet's
2359
+ * `eth|0x...` form is also accepted and normalized.
2360
+ * @param options - Select native signing or personal-sign explicitly.
1613
2361
  */
1614
- swaps;
2362
+ constructor(walletAddress, options = {}) {
2363
+ this.walletAddress = normalizeEthereumAccount(walletAddress, true);
2364
+ this.effectiveScheme = options.scheme ?? "native";
2365
+ }
1615
2366
  /**
1616
- * User asset management operations.
1617
- * Use this to retrieve user token balances and asset information.
2367
+ * Signs a DTO through `gala_signChainDto`.
1618
2368
  *
1619
2369
  * @example
1620
2370
  * ```typescript
1621
- * // Get user assets with pagination
1622
- * const assets = await gSwap.assets.getUserAssets('eth|123...abc', 1, 20);
1623
- * console.log(`User has ${assets.count} different tokens`);
2371
+ * const signed = await signer.signObject('AddLiquidity', {
2372
+ * token0: 'GALA',
2373
+ * token1: 'GUSDC',
2374
+ * tickLower: -60,
2375
+ * tickUpper: 60,
2376
+ * });
1624
2377
  * ```
1625
2378
  */
1626
- assets;
2379
+ async signObject(methodName, dto) {
2380
+ const wallet = getWalletProvider();
2381
+ if (this.effectiveScheme === "personal-sign") {
2382
+ return personalSign(wallet, dto, this.walletAddress, methodName);
2383
+ }
2384
+ try {
2385
+ const signature = await wallet.request({
2386
+ method: "gala_signChainDto",
2387
+ params: [serialize(dto), this.walletAddress, methodName, "native"]
2388
+ });
2389
+ return { ...dto, signature: getNativeSignature(signature) };
2390
+ } catch (error) {
2391
+ if (!isUnsupportedNativeSchemeError(error)) {
2392
+ throw error;
2393
+ }
2394
+ this.effectiveScheme = "personal-sign";
2395
+ return personalSign(wallet, dto, this.walletAddress, methodName);
2396
+ }
2397
+ }
2398
+ };
2399
+ var BrowserWalletSigner = class {
1627
2400
  /**
1628
- * Event management operations for real-time socket connections.
1629
- * Use this to manage event streaming and transaction status updates.
2401
+ * Creates a browser-wallet signer.
2402
+ *
2403
+ * Defaults to `personal_sign` — unchanged from every existing integration, since it only ever
2404
+ * resolves the bare `eth|` identity and changing that silently would be a real behavior
2405
+ * break for anyone already depending on it. Pass `{ scheme: 'eip712' }` to correctly resolve
2406
+ * a registered `client|` alias instead, for `RequestTrade`/`AddLiquidity`/`RemoveLiquidity`/
2407
+ * `CollectPositionFees` (`EIP712_CAPABLE_METHODS`) — `CreatePool` and any other method still
2408
+ * falls back to `personal_sign` even in `'eip712'` mode, since its EIP-712 signing is a
2409
+ * separate, unsolved chain-side problem.
1630
2410
  *
1631
2411
  * @example
1632
2412
  * ```typescript
1633
- * // Connect to event socket for transaction updates
1634
- * await GSwap.events.connectEventSocket();
1635
- *
1636
- * // Check if socket is connected
1637
- * const isConnected = GSwap.events.eventSocketConnected();
2413
+ * const signer = new BrowserWalletSigner(window.ethereum, '0x0123456789012345678901234567890123456789');
2414
+ * const signed = await signer.signObject('RequestTrade', { token0: 'GALA', token1: 'GUSDC' });
2415
+ * ```
2416
+ * @example
2417
+ * ```typescript
2418
+ * // Correctly resolves a registered client| alias instead of the bare eth| address.
2419
+ * const signer = new BrowserWalletSigner(window.ethereum, walletAddress, { scheme: 'eip712' });
1638
2420
  * ```
1639
2421
  */
1640
- static events = Events.instance;
1641
- httpClient;
1642
- httpRequestor;
1643
- bundler;
1644
- pools;
2422
+ constructor(provider, walletAddress, options = {}) {
2423
+ this.provider = provider;
2424
+ this.walletAddress = normalizeEthereumAccount(walletAddress, false);
2425
+ this.scheme = options.scheme ?? "personal-sign";
2426
+ }
2427
+ provider;
2428
+ walletAddress;
2429
+ scheme;
1645
2430
  /**
1646
- * Creates a new SDK instance.
1647
- * @param options - Customization options.
1648
- * @param options.signer - The signer to use for authenticated operations. Required if you use any functionality that creates transactions (such as swapping). Not required for readonly operations.
1649
- * @param options.gatewayBaseUrl - Base URL for the GalaChain Gateway API.
1650
- * @param options.dexContractBasePath - Base path for DEX contract API endpoints, within the GalaChain Gateway API.
1651
- * @param options.tokenContractBasePath - Base path for token contract API endpoints, within the GalaChain Gateway API.
1652
- * @param options.bundlerBaseUrl - Base URL for the DEX transaction bundling API.
1653
- * @param options.bundlingAPIBasePath - Base path for transaction bundling API endpoints.
1654
- * @param options.dexBackendBaseUrl - Base URL for the DEX backend API (for user assets and other data).
1655
- * @param options.httpRequestor - Custom HTTP requestor to use for API calls. Defaults to the global `fetch` function.
1656
- * @param options.transactionWaitTimeoutMs - Timeout in milliseconds for waiting for transactions to complete. Defaults to 300,000 milliseconds (five minutes).
1657
- * @param options.walletAddress - Optional default wallet address for operations that require a wallet address (e.x. swapping). If not provided, you must specify the wallet address in each method call.
2431
+ * Signs the DTO with `eth_signTypedData_v4` (when constructed with `{ scheme: 'eip712' }` and
2432
+ * `methodName` is in `EIP712_CAPABLE_METHODS`) or the EIP-1193 `personal_sign` method
2433
+ * (otherwise — the default).
2434
+ *
2435
+ * @example
2436
+ * ```typescript
2437
+ * const signed = await signer.signObject('RequestTrade', {
2438
+ * token0: 'GALA',
2439
+ * token1: 'GUSDC',
2440
+ * fee: 3000,
2441
+ * });
2442
+ * ```
1658
2443
  */
1659
- constructor(options) {
1660
- var _a;
1661
- this.gatewayBaseUrl = ((_a = options == null ? void 0 : options.gatewayBaseUrl) == null ? void 0 : _a.replace(/\/$/, "")) ?? "https://gateway-mainnet.galachain.com";
1662
- this.dexContractBasePath = (options == null ? void 0 : options.dexContractBasePath) ?? "/api/asset/dexv3-contract";
1663
- this.tokenContractBasePath = (options == null ? void 0 : options.tokenContractBasePath) ?? "/api/asset/token-contract";
1664
- this.bundlerBaseUrl = (options == null ? void 0 : options.bundlerBaseUrl) ?? "https://bundle-backend-prod1.defi.gala.com";
1665
- this.bundlingAPIBasePath = (options == null ? void 0 : options.bundlingAPIBasePath) ?? "/bundle";
1666
- this.dexBackendBaseUrl = (options == null ? void 0 : options.dexBackendBaseUrl) ?? "https://dex-backend-prod1.defi.gala.com";
1667
- this.signer = options == null ? void 0 : options.signer;
1668
- this.transactionWaitTimeoutMs = (options == null ? void 0 : options.transactionWaitTimeoutMs) ?? 3e5;
1669
- this.httpRequestor = (options == null ? void 0 : options.httpRequestor) ?? fetch.bind(globalThis);
1670
- this.httpClient = new HttpClient(this.httpRequestor);
1671
- this.bundler = new Bundler(
1672
- this.bundlerBaseUrl,
1673
- this.bundlingAPIBasePath,
1674
- this.transactionWaitTimeoutMs,
1675
- this.signer,
1676
- this.httpClient
1677
- );
1678
- this.pools = new Pools(this.gatewayBaseUrl, this.dexContractBasePath, this.httpClient);
1679
- this.quoting = new Quoting(this.gatewayBaseUrl, this.dexContractBasePath, this.httpClient);
1680
- this.positions = new Positions(
1681
- this.gatewayBaseUrl,
1682
- this.dexContractBasePath,
1683
- this.bundler,
1684
- this.pools,
1685
- this.httpClient,
1686
- { walletAddress: options == null ? void 0 : options.walletAddress }
1687
- );
1688
- this.swaps = new Swaps(this.bundler, { walletAddress: options == null ? void 0 : options.walletAddress });
1689
- this.assets = new Assets(this.dexBackendBaseUrl, this.httpClient);
1690
- }
1691
- };
1692
-
1693
- // src/classes/signers.ts
1694
- import { signatures } from "@gala-chain/api";
1695
- import { calculatePersonalSignPrefix } from "@gala-chain/connect";
1696
- var PrivateKeySigner = class {
1697
- keyBuffer;
1698
- constructor(privateKey) {
1699
- this.keyBuffer = signatures.normalizePrivateKey(privateKey);
1700
- }
1701
- async signObject(_methodName, obj) {
1702
- const signature = signatures.getSignature(obj, this.keyBuffer);
1703
- return { ...obj, signature };
1704
- }
1705
- };
1706
- var GalaWalletSigner = class _GalaWalletSigner {
1707
- constructor(walletAddress) {
1708
- this.walletAddress = walletAddress;
1709
- }
1710
- async signObject(methodName, obj) {
1711
- const globalGala = global.gala;
1712
- if (!globalGala) {
1713
- throw new GSwapSDKError(
1714
- "Gala wallet is not available. Please ensure the Gala wallet is connected.",
1715
- "GALA_WALLET_NOT_AVAILABLE"
1716
- );
2444
+ signObject(methodName, dto) {
2445
+ if (this.scheme === "eip712" && EIP712_CAPABLE_METHODS.has(methodName)) {
2446
+ return signEIP712(this.provider, methodName, dto, this.walletAddress);
1717
2447
  }
1718
- const domain = { name: "ethereum", chainId: 1 };
1719
- const types = _GalaWalletSigner.generateEIP712Types(methodName, obj);
1720
- const signRequest = {
1721
- domain,
1722
- types,
1723
- Primary_type: methodName,
1724
- message: {
1725
- ...obj,
1726
- prefix: calculatePersonalSignPrefix(obj)
1727
- }
1728
- };
1729
- await globalGala.setAddress(this.walletAddress);
1730
- const signature = await globalGala.request({
1731
- method: "eth_signTypedData",
1732
- params: [JSON.stringify(signRequest), this.walletAddress]
1733
- });
1734
- return { ...obj, domain, types, signature };
1735
- }
1736
- static generateEIP712Types(typeName, params) {
1737
- const types = {};
1738
- types[typeName] = [];
1739
- function addField(name, fieldValue, parentTypeName, onlyGetType = false) {
1740
- if (fieldValue === void 0) {
1741
- } else if (Array.isArray(fieldValue)) {
1742
- const type = addField(name, fieldValue[0], parentTypeName, true);
1743
- if (!onlyGetType) types[parentTypeName].push({ name, type: (type ?? name) + "[]" });
1744
- } else if (typeof fieldValue === "object" && fieldValue !== null) {
1745
- if (types[name]) {
1746
- throw new GSwapSDKError(
1747
- "Name collisions not yet supported in EIP712 type generation",
1748
- "EIP712_NAME_COLLISION",
1749
- { name }
1750
- );
1751
- }
1752
- types[name] = [];
1753
- Object.entries(fieldValue).forEach(([key, value]) => {
1754
- addField(key, value, name);
1755
- });
1756
- if (!onlyGetType) types[parentTypeName].push({ name, type: name });
1757
- } else {
1758
- let eipType;
1759
- switch (typeof fieldValue) {
1760
- case "string":
1761
- eipType = "string";
1762
- break;
1763
- case "number":
1764
- eipType = "int256";
1765
- break;
1766
- case "boolean":
1767
- eipType = "bool";
1768
- break;
1769
- default:
1770
- throw new GSwapSDKError(
1771
- `Unsupported type for EIP712 signing: ${typeof fieldValue}`,
1772
- "EIP712_UNSUPPORTED_TYPE",
1773
- { type: typeof fieldValue, value: fieldValue }
1774
- );
1775
- }
1776
- if (onlyGetType) {
1777
- return eipType;
1778
- } else {
1779
- types[parentTypeName].push({ name, type: eipType });
1780
- }
1781
- }
1782
- }
1783
- Object.entries(params).forEach(([key, value]) => {
1784
- addField(key, value, typeName);
1785
- });
1786
- return types;
2448
+ return personalSign(this.provider, dto, this.walletAddress);
1787
2449
  }
1788
2450
  };
1789
2451
  export {
2452
+ ALL_FEE_TIERS,
1790
2453
  Assets,
1791
- Bundler,
1792
- EventSocketClient,
1793
- Events,
2454
+ BrowserWalletSigner,
2455
+ ChainGateway,
1794
2456
  FEE_TIER,
2457
+ GC_MAX_TICK,
2458
+ GC_MIN_TICK,
2459
+ GSWAP_ENVIRONMENTS,
1795
2460
  GSwap,
1796
2461
  GSwapSDKError,
1797
2462
  GalaWalletSigner,
1798
- PendingTransaction,
1799
2463
  Pools,
1800
2464
  Positions,
1801
2465
  PrivateKeySigner,
1802
2466
  Quoting,
2467
+ SubmittedTransaction,
1803
2468
  Swaps,
1804
- TradeEventEmitter,
1805
- compareTokens,
1806
- getTokenOrdering,
2469
+ Symbols,
2470
+ TICK_SPACING_BY_FEE,
2471
+ alignTickDown,
2472
+ alignTickUp,
2473
+ assertTickRange,
2474
+ compositeKeyOf,
2475
+ getObjectProperty,
2476
+ getStringProperty,
2477
+ orderSymbols,
2478
+ parseJson,
1807
2479
  parseTokenClassKey,
1808
- stringifyTokenClassKey,
2480
+ readOrderedSymbols,
2481
+ sqrtPriceToTick,
2482
+ tickFromPrice,
2483
+ tickToSqrtPrice,
1809
2484
  validateFee,
1810
2485
  validateNumericAmount,
1811
2486
  validatePriceValues,