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

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