@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/browser/index.js +4 -2
- package/dist/browser/index.js.map +1 -1
- package/dist/index.cjs +2269 -2371
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1072 -1028
- package/dist/index.d.ts +1072 -1028
- package/dist/index.mjs +2210 -2305
- package/dist/index.mjs.map +1 -1
- package/package.json +19 -11
package/dist/index.mjs
CHANGED
|
@@ -1,2492 +1,2397 @@
|
|
|
1
|
-
|
|
2
|
-
import
|
|
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
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
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
|
-
|
|
105
|
-
|
|
106
|
-
|
|
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
|
-
|
|
110
|
-
|
|
111
|
-
|
|
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
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
110
|
+
try {
|
|
111
|
+
return JSON.parse(text);
|
|
112
|
+
} catch {
|
|
113
|
+
return;
|
|
114
|
+
}
|
|
119
115
|
}
|
|
120
116
|
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
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
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
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
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
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
|
-
|
|
158
|
+
const DexDecimal = Decimal.clone({ precision: 60 });
|
|
159
|
+
/** Convert a tick to the corresponding square-root price. */
|
|
152
160
|
function tickToSqrtPrice(tick) {
|
|
153
|
-
|
|
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
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
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
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
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
|
-
|
|
180
|
-
|
|
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
|
-
|
|
184
|
-
|
|
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
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
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
|
-
|
|
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
|
-
|
|
210
|
+
//#endregion
|
|
211
|
+
//#region src/utils/validation.ts
|
|
207
212
|
function validateNumericAmount(amount, parameterName, allowZero = false) {
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
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
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
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
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
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
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
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
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
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
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
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
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
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
|
-
|
|
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
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
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
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
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
|
-
|
|
456
|
-
|
|
457
|
-
|
|
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
|
-
|
|
383
|
+
//#endregion
|
|
384
|
+
//#region src/utils/transport.ts
|
|
461
385
|
async function requestWithTimeout(requestor, url, options, timeoutMs) {
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
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
|
-
|
|
485
|
-
|
|
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
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
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
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
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
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
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
|
-
|
|
439
|
+
return "get" in headers && typeof headers.get === "function";
|
|
512
440
|
}
|
|
513
441
|
|
|
514
|
-
|
|
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
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
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
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
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
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
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
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
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
|
-
|
|
628
|
+
return status === 500 || status === 502 || status === 503 || status === 504;
|
|
726
629
|
}
|
|
727
630
|
function bodyMessage(body) {
|
|
728
|
-
|
|
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
|
-
|
|
633
|
+
function asRecord$1(value) {
|
|
634
|
+
return typeof value === "object" && value !== null ? value : void 0;
|
|
732
635
|
}
|
|
733
636
|
function delay(milliseconds) {
|
|
734
|
-
|
|
637
|
+
return new Promise((resolve) => setTimeout(resolve, milliseconds));
|
|
735
638
|
}
|
|
736
639
|
function jitter(milliseconds) {
|
|
737
|
-
|
|
640
|
+
return Math.max(0, Math.round(milliseconds * (.9 + Math.random() * .2)));
|
|
738
641
|
}
|
|
739
642
|
|
|
740
|
-
|
|
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
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
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
|
-
|
|
730
|
+
function trimTrailingSlash$1(value) {
|
|
731
|
+
return value.replace(/\/$/u, "");
|
|
867
732
|
}
|
|
868
733
|
function invalidGatewayResponse(response, body, url, message) {
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
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
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
}
|
|
886
|
-
|
|
887
|
-
|
|
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
|
-
|
|
757
|
+
return typeof value === "number" && Number.isInteger(value) && value >= 0;
|
|
891
758
|
}
|
|
892
759
|
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
760
|
+
//#endregion
|
|
761
|
+
//#region src/utils/debug.ts
|
|
762
|
+
const debugLog = debug("GSWAP_SDK");
|
|
896
763
|
|
|
897
|
-
|
|
898
|
-
|
|
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
|
-
|
|
769
|
+
//#endregion
|
|
770
|
+
//#region src/classes/http_client.ts
|
|
901
771
|
var HttpClient = class {
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
|
|
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
|
-
|
|
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
|
-
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
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
|
-
|
|
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
|
-
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
|
|
1078
|
-
|
|
1079
|
-
|
|
1080
|
-
|
|
1081
|
-
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
|
|
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
|
-
|
|
1106
|
-
|
|
1107
|
-
|
|
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
|
-
|
|
1113
|
-
|
|
1114
|
-
|
|
1115
|
-
|
|
1116
|
-
|
|
1117
|
-
|
|
1118
|
-
|
|
1119
|
-
|
|
1120
|
-
|
|
1121
|
-
|
|
1122
|
-
|
|
1123
|
-
|
|
1124
|
-
|
|
1125
|
-
|
|
1126
|
-
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
|
|
1135
|
-
|
|
1136
|
-
|
|
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
|
-
|
|
1017
|
+
return typeof value === "number" && Number.isFinite(value);
|
|
1140
1018
|
}
|
|
1141
1019
|
function isOptionalString(value) {
|
|
1142
|
-
|
|
1020
|
+
return value === void 0 || typeof value === "string";
|
|
1143
1021
|
}
|
|
1144
1022
|
function isOptionalNumber(value) {
|
|
1145
|
-
|
|
1023
|
+
return value === void 0 || isFiniteNumber(value);
|
|
1146
1024
|
}
|
|
1147
1025
|
|
|
1148
|
-
|
|
1149
|
-
|
|
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
|
-
|
|
1152
|
-
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
1157
|
-
|
|
1158
|
-
|
|
1159
|
-
|
|
1160
|
-
|
|
1161
|
-
|
|
1162
|
-
|
|
1163
|
-
|
|
1164
|
-
|
|
1165
|
-
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
|
|
1169
|
-
|
|
1170
|
-
|
|
1171
|
-
|
|
1172
|
-
|
|
1173
|
-
|
|
1174
|
-
|
|
1175
|
-
|
|
1176
|
-
|
|
1177
|
-
|
|
1178
|
-
|
|
1179
|
-
|
|
1180
|
-
|
|
1181
|
-
|
|
1182
|
-
|
|
1183
|
-
|
|
1184
|
-
|
|
1185
|
-
|
|
1186
|
-
|
|
1187
|
-
|
|
1188
|
-
|
|
1189
|
-
|
|
1190
|
-
|
|
1191
|
-
|
|
1192
|
-
|
|
1193
|
-
|
|
1194
|
-
|
|
1195
|
-
|
|
1196
|
-
|
|
1197
|
-
|
|
1198
|
-
|
|
1199
|
-
|
|
1200
|
-
|
|
1201
|
-
|
|
1202
|
-
|
|
1203
|
-
|
|
1204
|
-
|
|
1205
|
-
|
|
1206
|
-
|
|
1207
|
-
|
|
1208
|
-
|
|
1209
|
-
|
|
1210
|
-
|
|
1211
|
-
|
|
1212
|
-
|
|
1213
|
-
|
|
1214
|
-
|
|
1215
|
-
|
|
1216
|
-
|
|
1217
|
-
|
|
1218
|
-
|
|
1219
|
-
|
|
1220
|
-
|
|
1221
|
-
|
|
1222
|
-
|
|
1223
|
-
|
|
1224
|
-
|
|
1225
|
-
|
|
1226
|
-
|
|
1227
|
-
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
|
|
1232
|
-
|
|
1233
|
-
|
|
1234
|
-
|
|
1235
|
-
|
|
1236
|
-
|
|
1237
|
-
|
|
1238
|
-
|
|
1239
|
-
|
|
1240
|
-
|
|
1241
|
-
|
|
1242
|
-
|
|
1243
|
-
|
|
1244
|
-
|
|
1245
|
-
|
|
1246
|
-
|
|
1247
|
-
|
|
1248
|
-
|
|
1249
|
-
|
|
1250
|
-
|
|
1251
|
-
|
|
1252
|
-
|
|
1253
|
-
|
|
1254
|
-
|
|
1255
|
-
|
|
1256
|
-
|
|
1257
|
-
|
|
1258
|
-
|
|
1259
|
-
|
|
1260
|
-
|
|
1261
|
-
|
|
1262
|
-
|
|
1263
|
-
|
|
1264
|
-
|
|
1265
|
-
|
|
1266
|
-
|
|
1267
|
-
|
|
1268
|
-
|
|
1269
|
-
|
|
1270
|
-
|
|
1271
|
-
|
|
1272
|
-
|
|
1273
|
-
|
|
1274
|
-
|
|
1275
|
-
|
|
1276
|
-
|
|
1277
|
-
|
|
1278
|
-
|
|
1279
|
-
|
|
1280
|
-
|
|
1281
|
-
|
|
1282
|
-
|
|
1283
|
-
|
|
1284
|
-
|
|
1285
|
-
|
|
1286
|
-
|
|
1287
|
-
|
|
1288
|
-
|
|
1289
|
-
|
|
1290
|
-
|
|
1291
|
-
|
|
1292
|
-
|
|
1293
|
-
|
|
1294
|
-
|
|
1295
|
-
|
|
1296
|
-
|
|
1297
|
-
|
|
1298
|
-
|
|
1299
|
-
|
|
1300
|
-
|
|
1301
|
-
|
|
1302
|
-
|
|
1303
|
-
|
|
1304
|
-
|
|
1305
|
-
|
|
1306
|
-
|
|
1307
|
-
|
|
1308
|
-
|
|
1309
|
-
|
|
1310
|
-
|
|
1311
|
-
|
|
1312
|
-
|
|
1313
|
-
|
|
1314
|
-
|
|
1315
|
-
|
|
1316
|
-
|
|
1317
|
-
|
|
1318
|
-
|
|
1319
|
-
|
|
1320
|
-
|
|
1321
|
-
|
|
1322
|
-
|
|
1323
|
-
|
|
1324
|
-
|
|
1325
|
-
|
|
1326
|
-
|
|
1327
|
-
|
|
1328
|
-
|
|
1329
|
-
|
|
1330
|
-
|
|
1331
|
-
|
|
1332
|
-
|
|
1333
|
-
|
|
1334
|
-
|
|
1335
|
-
|
|
1336
|
-
|
|
1337
|
-
|
|
1338
|
-
|
|
1339
|
-
|
|
1340
|
-
|
|
1341
|
-
|
|
1342
|
-
|
|
1343
|
-
|
|
1344
|
-
|
|
1345
|
-
|
|
1346
|
-
|
|
1347
|
-
|
|
1348
|
-
|
|
1349
|
-
|
|
1350
|
-
|
|
1351
|
-
|
|
1352
|
-
|
|
1353
|
-
|
|
1354
|
-
|
|
1355
|
-
|
|
1356
|
-
|
|
1357
|
-
|
|
1358
|
-
|
|
1359
|
-
|
|
1360
|
-
|
|
1361
|
-
|
|
1362
|
-
|
|
1363
|
-
|
|
1364
|
-
|
|
1365
|
-
|
|
1366
|
-
|
|
1367
|
-
|
|
1368
|
-
|
|
1369
|
-
|
|
1370
|
-
|
|
1371
|
-
|
|
1372
|
-
|
|
1373
|
-
|
|
1374
|
-
|
|
1375
|
-
|
|
1376
|
-
|
|
1377
|
-
|
|
1378
|
-
|
|
1379
|
-
|
|
1380
|
-
|
|
1381
|
-
|
|
1382
|
-
|
|
1383
|
-
|
|
1384
|
-
|
|
1385
|
-
|
|
1386
|
-
|
|
1387
|
-
|
|
1388
|
-
|
|
1389
|
-
|
|
1390
|
-
|
|
1391
|
-
|
|
1392
|
-
|
|
1393
|
-
|
|
1394
|
-
|
|
1395
|
-
|
|
1396
|
-
|
|
1397
|
-
|
|
1398
|
-
|
|
1399
|
-
|
|
1400
|
-
|
|
1401
|
-
|
|
1402
|
-
|
|
1403
|
-
|
|
1404
|
-
|
|
1405
|
-
|
|
1406
|
-
|
|
1407
|
-
|
|
1408
|
-
|
|
1409
|
-
|
|
1410
|
-
|
|
1411
|
-
|
|
1412
|
-
|
|
1413
|
-
|
|
1414
|
-
|
|
1415
|
-
|
|
1416
|
-
|
|
1417
|
-
|
|
1418
|
-
|
|
1419
|
-
|
|
1420
|
-
|
|
1421
|
-
|
|
1422
|
-
|
|
1423
|
-
|
|
1424
|
-
|
|
1425
|
-
|
|
1426
|
-
|
|
1427
|
-
|
|
1428
|
-
|
|
1429
|
-
|
|
1430
|
-
|
|
1431
|
-
|
|
1432
|
-
|
|
1433
|
-
|
|
1434
|
-
|
|
1435
|
-
|
|
1436
|
-
|
|
1437
|
-
|
|
1438
|
-
|
|
1439
|
-
|
|
1440
|
-
|
|
1441
|
-
|
|
1442
|
-
|
|
1443
|
-
|
|
1444
|
-
|
|
1445
|
-
|
|
1446
|
-
|
|
1447
|
-
|
|
1448
|
-
|
|
1449
|
-
|
|
1450
|
-
|
|
1451
|
-
|
|
1452
|
-
|
|
1453
|
-
|
|
1454
|
-
|
|
1455
|
-
|
|
1456
|
-
|
|
1457
|
-
|
|
1458
|
-
|
|
1459
|
-
|
|
1460
|
-
|
|
1461
|
-
|
|
1462
|
-
|
|
1463
|
-
|
|
1464
|
-
|
|
1465
|
-
|
|
1466
|
-
|
|
1467
|
-
|
|
1468
|
-
|
|
1469
|
-
|
|
1470
|
-
|
|
1471
|
-
|
|
1472
|
-
|
|
1473
|
-
|
|
1474
|
-
|
|
1475
|
-
|
|
1476
|
-
|
|
1477
|
-
|
|
1478
|
-
|
|
1479
|
-
|
|
1480
|
-
|
|
1481
|
-
|
|
1482
|
-
|
|
1483
|
-
|
|
1484
|
-
|
|
1485
|
-
|
|
1486
|
-
|
|
1487
|
-
|
|
1488
|
-
|
|
1489
|
-
|
|
1490
|
-
|
|
1491
|
-
|
|
1492
|
-
|
|
1493
|
-
|
|
1494
|
-
|
|
1495
|
-
|
|
1496
|
-
|
|
1497
|
-
|
|
1498
|
-
|
|
1499
|
-
|
|
1500
|
-
|
|
1501
|
-
|
|
1502
|
-
|
|
1503
|
-
|
|
1504
|
-
|
|
1505
|
-
|
|
1506
|
-
|
|
1507
|
-
|
|
1508
|
-
|
|
1509
|
-
|
|
1510
|
-
|
|
1511
|
-
|
|
1512
|
-
|
|
1513
|
-
|
|
1514
|
-
|
|
1515
|
-
|
|
1516
|
-
|
|
1517
|
-
|
|
1518
|
-
|
|
1519
|
-
|
|
1520
|
-
|
|
1521
|
-
|
|
1522
|
-
|
|
1523
|
-
|
|
1524
|
-
|
|
1525
|
-
|
|
1526
|
-
|
|
1527
|
-
|
|
1528
|
-
|
|
1529
|
-
|
|
1530
|
-
|
|
1531
|
-
|
|
1532
|
-
|
|
1533
|
-
|
|
1534
|
-
|
|
1535
|
-
|
|
1536
|
-
|
|
1537
|
-
|
|
1538
|
-
|
|
1539
|
-
|
|
1540
|
-
|
|
1541
|
-
|
|
1542
|
-
|
|
1543
|
-
|
|
1544
|
-
|
|
1545
|
-
|
|
1546
|
-
|
|
1547
|
-
|
|
1548
|
-
|
|
1549
|
-
|
|
1550
|
-
|
|
1551
|
-
|
|
1552
|
-
|
|
1553
|
-
|
|
1554
|
-
|
|
1555
|
-
|
|
1556
|
-
|
|
1557
|
-
|
|
1558
|
-
|
|
1559
|
-
|
|
1560
|
-
|
|
1561
|
-
|
|
1562
|
-
|
|
1563
|
-
|
|
1564
|
-
|
|
1565
|
-
|
|
1566
|
-
|
|
1567
|
-
|
|
1568
|
-
|
|
1569
|
-
|
|
1570
|
-
|
|
1571
|
-
|
|
1572
|
-
|
|
1573
|
-
|
|
1574
|
-
|
|
1575
|
-
|
|
1576
|
-
|
|
1577
|
-
|
|
1578
|
-
|
|
1579
|
-
|
|
1580
|
-
|
|
1581
|
-
|
|
1582
|
-
|
|
1583
|
-
|
|
1584
|
-
|
|
1585
|
-
|
|
1586
|
-
|
|
1587
|
-
|
|
1588
|
-
|
|
1589
|
-
|
|
1590
|
-
|
|
1591
|
-
|
|
1592
|
-
|
|
1593
|
-
|
|
1594
|
-
|
|
1595
|
-
|
|
1596
|
-
|
|
1597
|
-
|
|
1598
|
-
|
|
1599
|
-
|
|
1600
|
-
|
|
1601
|
-
|
|
1602
|
-
|
|
1603
|
-
|
|
1604
|
-
|
|
1605
|
-
|
|
1606
|
-
|
|
1607
|
-
|
|
1608
|
-
|
|
1609
|
-
|
|
1610
|
-
|
|
1611
|
-
|
|
1612
|
-
|
|
1613
|
-
|
|
1614
|
-
|
|
1615
|
-
|
|
1616
|
-
|
|
1617
|
-
|
|
1618
|
-
|
|
1619
|
-
|
|
1620
|
-
|
|
1621
|
-
|
|
1622
|
-
|
|
1623
|
-
|
|
1624
|
-
|
|
1625
|
-
|
|
1626
|
-
|
|
1627
|
-
|
|
1628
|
-
|
|
1629
|
-
|
|
1630
|
-
|
|
1631
|
-
|
|
1632
|
-
|
|
1633
|
-
|
|
1634
|
-
|
|
1635
|
-
|
|
1636
|
-
|
|
1637
|
-
|
|
1638
|
-
|
|
1639
|
-
|
|
1640
|
-
|
|
1641
|
-
|
|
1642
|
-
|
|
1643
|
-
|
|
1644
|
-
|
|
1645
|
-
|
|
1646
|
-
|
|
1647
|
-
|
|
1648
|
-
|
|
1649
|
-
|
|
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
|
-
|
|
1655
|
-
|
|
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
|
-
|
|
1659
|
-
|
|
1660
|
-
|
|
1661
|
-
|
|
1662
|
-
|
|
1663
|
-
|
|
1664
|
-
|
|
1665
|
-
|
|
1666
|
-
|
|
1667
|
-
|
|
1668
|
-
|
|
1669
|
-
|
|
1670
|
-
|
|
1671
|
-
|
|
1672
|
-
|
|
1673
|
-
|
|
1674
|
-
|
|
1675
|
-
|
|
1676
|
-
|
|
1677
|
-
|
|
1678
|
-
|
|
1679
|
-
|
|
1680
|
-
|
|
1681
|
-
|
|
1682
|
-
|
|
1683
|
-
|
|
1684
|
-
|
|
1685
|
-
|
|
1686
|
-
|
|
1687
|
-
|
|
1688
|
-
|
|
1689
|
-
|
|
1690
|
-
|
|
1691
|
-
|
|
1692
|
-
|
|
1693
|
-
|
|
1694
|
-
|
|
1695
|
-
|
|
1696
|
-
|
|
1697
|
-
|
|
1698
|
-
|
|
1699
|
-
|
|
1700
|
-
|
|
1701
|
-
|
|
1702
|
-
|
|
1703
|
-
|
|
1704
|
-
|
|
1705
|
-
|
|
1706
|
-
|
|
1707
|
-
|
|
1708
|
-
|
|
1709
|
-
|
|
1710
|
-
|
|
1711
|
-
|
|
1712
|
-
|
|
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
|
-
|
|
1724
|
-
|
|
1725
|
-
|
|
1726
|
-
|
|
1727
|
-
|
|
1728
|
-
|
|
1729
|
-
|
|
1730
|
-
|
|
1731
|
-
|
|
1732
|
-
|
|
1733
|
-
|
|
1734
|
-
|
|
1735
|
-
|
|
1736
|
-
|
|
1737
|
-
|
|
1738
|
-
|
|
1739
|
-
|
|
1740
|
-
|
|
1741
|
-
|
|
1742
|
-
|
|
1743
|
-
|
|
1744
|
-
|
|
1745
|
-
|
|
1746
|
-
|
|
1747
|
-
|
|
1748
|
-
|
|
1749
|
-
|
|
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
|
-
|
|
1756
|
-
|
|
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
|
-
|
|
1760
|
-
|
|
1761
|
-
|
|
1762
|
-
|
|
1763
|
-
|
|
1764
|
-
|
|
1765
|
-
|
|
1766
|
-
|
|
1767
|
-
|
|
1768
|
-
|
|
1769
|
-
|
|
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
|
-
|
|
1775
|
-
|
|
1776
|
-
|
|
1777
|
-
|
|
1778
|
-
|
|
1779
|
-
|
|
1780
|
-
|
|
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
|
-
|
|
1785
|
-
|
|
1786
|
-
|
|
1787
|
-
|
|
1788
|
-
|
|
1789
|
-
|
|
1790
|
-
|
|
1791
|
-
|
|
1792
|
-
|
|
1793
|
-
|
|
1794
|
-
|
|
1795
|
-
|
|
1796
|
-
|
|
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
|
-
|
|
1804
|
-
|
|
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
|
-
|
|
1808
|
-
|
|
1809
|
-
|
|
1810
|
-
|
|
1811
|
-
|
|
1812
|
-
|
|
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
|
-
|
|
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
|
-
|
|
1687
|
+
function toDecimalString$1(amount) {
|
|
1688
|
+
return new BigNumber(amount).toFixed();
|
|
1821
1689
|
}
|
|
1822
|
-
async function
|
|
1823
|
-
|
|
1824
|
-
|
|
1825
|
-
|
|
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
|
-
|
|
1831
|
-
|
|
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
|
-
|
|
1834
|
-
|
|
1835
|
-
|
|
1836
|
-
|
|
1837
|
-
|
|
1838
|
-
|
|
1839
|
-
|
|
1840
|
-
|
|
1841
|
-
|
|
1842
|
-
|
|
1843
|
-
|
|
1844
|
-
|
|
1845
|
-
|
|
1846
|
-
|
|
1847
|
-
|
|
1848
|
-
|
|
1849
|
-
|
|
1850
|
-
|
|
1851
|
-
|
|
1852
|
-
|
|
1853
|
-
|
|
1854
|
-
|
|
1855
|
-
|
|
1856
|
-
|
|
1857
|
-
|
|
1858
|
-
|
|
1859
|
-
|
|
1860
|
-
|
|
1861
|
-
|
|
1862
|
-
|
|
1863
|
-
|
|
1864
|
-
|
|
1865
|
-
|
|
1866
|
-
|
|
1867
|
-
|
|
1868
|
-
|
|
1869
|
-
|
|
1870
|
-
|
|
1871
|
-
|
|
1872
|
-
|
|
1873
|
-
|
|
1874
|
-
|
|
1875
|
-
|
|
1876
|
-
|
|
1877
|
-
|
|
1878
|
-
|
|
1879
|
-
|
|
1880
|
-
|
|
1881
|
-
|
|
1882
|
-
|
|
1883
|
-
|
|
1884
|
-
|
|
1885
|
-
|
|
1886
|
-
|
|
1887
|
-
|
|
1888
|
-
|
|
1889
|
-
|
|
1890
|
-
|
|
1891
|
-
|
|
1892
|
-
|
|
1893
|
-
|
|
1894
|
-
|
|
1895
|
-
|
|
1896
|
-
|
|
1897
|
-
|
|
1898
|
-
|
|
1899
|
-
|
|
1900
|
-
|
|
1901
|
-
|
|
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
|
-
|
|
1911
|
-
|
|
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
|
-
|
|
1919
|
-
|
|
1920
|
-
|
|
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
|
-
|
|
1781
|
+
return ref.includes("|") || ref.includes("$");
|
|
1924
1782
|
}
|
|
1925
1783
|
|
|
1926
|
-
|
|
1927
|
-
|
|
1928
|
-
|
|
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
|
-
|
|
1932
|
-
|
|
1933
|
-
|
|
1934
|
-
|
|
1935
|
-
|
|
1936
|
-
|
|
1937
|
-
|
|
1938
|
-
|
|
1939
|
-
|
|
1940
|
-
|
|
1941
|
-
|
|
1942
|
-
|
|
1943
|
-
|
|
1944
|
-
|
|
1945
|
-
|
|
1946
|
-
|
|
1947
|
-
|
|
1948
|
-
|
|
1949
|
-
|
|
1950
|
-
|
|
1951
|
-
|
|
1952
|
-
|
|
1953
|
-
|
|
1954
|
-
|
|
1955
|
-
|
|
1956
|
-
|
|
1957
|
-
|
|
1958
|
-
|
|
1959
|
-
|
|
1960
|
-
|
|
1961
|
-
|
|
1962
|
-
|
|
1963
|
-
|
|
1964
|
-
|
|
1965
|
-
|
|
1966
|
-
|
|
1967
|
-
|
|
1968
|
-
|
|
1969
|
-
|
|
1970
|
-
|
|
1971
|
-
|
|
1972
|
-
|
|
1973
|
-
|
|
1974
|
-
|
|
1975
|
-
|
|
1976
|
-
|
|
1977
|
-
|
|
1978
|
-
|
|
1979
|
-
|
|
1980
|
-
|
|
1981
|
-
|
|
1982
|
-
|
|
1983
|
-
|
|
1984
|
-
|
|
1985
|
-
|
|
1986
|
-
|
|
1987
|
-
|
|
1988
|
-
|
|
1989
|
-
|
|
1990
|
-
|
|
1991
|
-
|
|
1992
|
-
|
|
1993
|
-
|
|
1994
|
-
|
|
1995
|
-
|
|
1996
|
-
|
|
1997
|
-
|
|
1998
|
-
|
|
1999
|
-
|
|
2000
|
-
|
|
2001
|
-
|
|
2002
|
-
|
|
2003
|
-
|
|
2004
|
-
|
|
2005
|
-
|
|
2006
|
-
|
|
2007
|
-
|
|
2008
|
-
|
|
2009
|
-
|
|
2010
|
-
|
|
2011
|
-
|
|
2012
|
-
|
|
2013
|
-
|
|
2014
|
-
|
|
2015
|
-
|
|
2016
|
-
|
|
2017
|
-
|
|
2018
|
-
|
|
2019
|
-
|
|
2020
|
-
|
|
2021
|
-
|
|
2022
|
-
|
|
2023
|
-
|
|
2024
|
-
|
|
2025
|
-
|
|
2026
|
-
|
|
2027
|
-
|
|
2028
|
-
|
|
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
|
|
2042
|
-
|
|
1890
|
+
function toDecimalString(amount) {
|
|
1891
|
+
return new BigNumber(amount).toFixed();
|
|
2043
1892
|
}
|
|
2044
|
-
async function
|
|
2045
|
-
|
|
2046
|
-
|
|
2047
|
-
|
|
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
|
-
|
|
2053
|
-
|
|
2054
|
-
|
|
2055
|
-
|
|
2056
|
-
|
|
2057
|
-
|
|
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
|
-
|
|
1907
|
+
//#endregion
|
|
1908
|
+
//#region src/classes/gswap.ts
|
|
1909
|
+
/** Main entry point for the current GalaChainDex SDK. */
|
|
2063
1910
|
var GSwap = class {
|
|
2064
|
-
|
|
2065
|
-
|
|
2066
|
-
|
|
2067
|
-
|
|
2068
|
-
|
|
2069
|
-
|
|
2070
|
-
|
|
2071
|
-
|
|
2072
|
-
|
|
2073
|
-
|
|
2074
|
-
|
|
2075
|
-
|
|
2076
|
-
|
|
2077
|
-
|
|
2078
|
-
|
|
2079
|
-
|
|
2080
|
-
|
|
2081
|
-
|
|
2082
|
-
|
|
2083
|
-
|
|
2084
|
-
|
|
2085
|
-
|
|
2086
|
-
|
|
2087
|
-
|
|
2088
|
-
|
|
2089
|
-
|
|
2090
|
-
|
|
2091
|
-
|
|
2092
|
-
|
|
2093
|
-
|
|
2094
|
-
|
|
2095
|
-
|
|
2096
|
-
|
|
2097
|
-
|
|
2098
|
-
|
|
2099
|
-
|
|
2100
|
-
|
|
2101
|
-
|
|
2102
|
-
|
|
2103
|
-
|
|
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
|
|
2108
|
-
|
|
1952
|
+
function trimTrailingSlash(value) {
|
|
1953
|
+
return value.replace(/\/$/u, "");
|
|
2109
1954
|
}
|
|
2110
1955
|
|
|
2111
|
-
|
|
2112
|
-
|
|
2113
|
-
|
|
2114
|
-
|
|
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
|
-
|
|
2117
|
-
|
|
2118
|
-
|
|
2119
|
-
|
|
2120
|
-
|
|
2121
|
-
|
|
2122
|
-
|
|
2123
|
-
|
|
2124
|
-
|
|
2125
|
-
|
|
2126
|
-
|
|
2127
|
-
|
|
2128
|
-
|
|
2129
|
-
|
|
2130
|
-
|
|
2131
|
-
|
|
2132
|
-
|
|
2133
|
-
|
|
2134
|
-
|
|
2135
|
-
|
|
2136
|
-
|
|
2137
|
-
|
|
2138
|
-
|
|
2139
|
-
|
|
2140
|
-
|
|
2141
|
-
|
|
2142
|
-
|
|
2143
|
-
|
|
2144
|
-
|
|
2145
|
-
|
|
2146
|
-
|
|
2147
|
-
|
|
2148
|
-
|
|
2149
|
-
|
|
2150
|
-
|
|
2151
|
-
|
|
2152
|
-
|
|
2153
|
-
|
|
2154
|
-
|
|
2155
|
-
|
|
2156
|
-
|
|
2157
|
-
|
|
2158
|
-
|
|
2159
|
-
|
|
2160
|
-
|
|
2161
|
-
|
|
2162
|
-
|
|
2163
|
-
|
|
2164
|
-
|
|
2165
|
-
|
|
2166
|
-
|
|
2167
|
-
|
|
2168
|
-
}
|
|
2169
|
-
|
|
2170
|
-
|
|
2171
|
-
|
|
2172
|
-
|
|
2173
|
-
|
|
2174
|
-
|
|
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
|
-
|
|
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
|
-
|
|
2181
|
-
|
|
2182
|
-
|
|
2183
|
-
|
|
2184
|
-
|
|
2185
|
-
|
|
2186
|
-
|
|
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
|
-
|
|
2191
|
-
|
|
2192
|
-
|
|
2193
|
-
|
|
2194
|
-
|
|
2195
|
-
|
|
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
|
-
|
|
2200
|
-
|
|
2201
|
-
|
|
2202
|
-
|
|
2203
|
-
|
|
2204
|
-
|
|
2205
|
-
}
|
|
2206
|
-
|
|
2207
|
-
|
|
2208
|
-
|
|
2209
|
-
|
|
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
|
-
|
|
2213
|
-
|
|
2214
|
-
|
|
2215
|
-
|
|
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
|
-
|
|
2219
|
-
|
|
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
|
-
|
|
2222
|
-
|
|
2223
|
-
|
|
2224
|
-
|
|
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
|
-
|
|
2228
|
-
|
|
2229
|
-
|
|
2230
|
-
|
|
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
|
-
|
|
2240
|
-
|
|
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
|
-
|
|
2249
|
-
|
|
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
|
-
|
|
2258
|
-
|
|
2259
|
-
|
|
2260
|
-
|
|
2261
|
-
|
|
2262
|
-
|
|
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
|
-
|
|
2269
|
-
|
|
2270
|
-
|
|
2271
|
-
|
|
2272
|
-
|
|
2273
|
-
|
|
2274
|
-
|
|
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
|
-
|
|
2166
|
+
return /unsupported|unknown scheme/i.test(getErrorMessage(error));
|
|
2282
2167
|
}
|
|
2283
2168
|
function personalSign(provider, dto, walletAddress, methodName) {
|
|
2284
|
-
|
|
2285
|
-
|
|
2286
|
-
|
|
2287
|
-
|
|
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
|
-
|
|
2291
|
-
|
|
2292
|
-
|
|
2293
|
-
|
|
2294
|
-
|
|
2295
|
-
|
|
2296
|
-
|
|
2297
|
-
|
|
2298
|
-
|
|
2299
|
-
|
|
2300
|
-
|
|
2301
|
-
|
|
2302
|
-
|
|
2303
|
-
|
|
2304
|
-
|
|
2305
|
-
|
|
2306
|
-
|
|
2307
|
-
|
|
2308
|
-
|
|
2309
|
-
|
|
2310
|
-
|
|
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
|
-
|
|
2315
|
-
|
|
2316
|
-
|
|
2317
|
-
|
|
2318
|
-
|
|
2319
|
-
|
|
2320
|
-
|
|
2321
|
-
|
|
2322
|
-
|
|
2323
|
-
|
|
2324
|
-
|
|
2325
|
-
|
|
2326
|
-
|
|
2327
|
-
|
|
2328
|
-
|
|
2329
|
-
|
|
2330
|
-
|
|
2331
|
-
|
|
2332
|
-
|
|
2333
|
-
|
|
2334
|
-
|
|
2335
|
-
|
|
2336
|
-
|
|
2337
|
-
|
|
2338
|
-
|
|
2339
|
-
|
|
2340
|
-
|
|
2341
|
-
|
|
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
|
-
|
|
2346
|
-
|
|
2347
|
-
|
|
2348
|
-
|
|
2349
|
-
|
|
2350
|
-
|
|
2351
|
-
|
|
2352
|
-
|
|
2353
|
-
|
|
2354
|
-
|
|
2355
|
-
|
|
2356
|
-
|
|
2357
|
-
|
|
2358
|
-
|
|
2359
|
-
|
|
2360
|
-
|
|
2361
|
-
|
|
2362
|
-
|
|
2363
|
-
|
|
2364
|
-
|
|
2365
|
-
|
|
2366
|
-
|
|
2367
|
-
|
|
2368
|
-
|
|
2369
|
-
|
|
2370
|
-
|
|
2371
|
-
|
|
2372
|
-
|
|
2373
|
-
|
|
2374
|
-
|
|
2375
|
-
|
|
2376
|
-
|
|
2377
|
-
|
|
2378
|
-
|
|
2379
|
-
|
|
2380
|
-
|
|
2381
|
-
|
|
2382
|
-
|
|
2383
|
-
|
|
2384
|
-
|
|
2385
|
-
|
|
2386
|
-
|
|
2387
|
-
|
|
2388
|
-
|
|
2389
|
-
|
|
2390
|
-
|
|
2391
|
-
|
|
2392
|
-
|
|
2393
|
-
|
|
2394
|
-
|
|
2395
|
-
|
|
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
|
-
|
|
2402
|
-
|
|
2403
|
-
|
|
2404
|
-
|
|
2405
|
-
|
|
2406
|
-
|
|
2407
|
-
|
|
2408
|
-
|
|
2409
|
-
|
|
2410
|
-
|
|
2411
|
-
|
|
2412
|
-
|
|
2413
|
-
|
|
2414
|
-
|
|
2415
|
-
|
|
2416
|
-
|
|
2417
|
-
|
|
2418
|
-
|
|
2419
|
-
|
|
2420
|
-
|
|
2421
|
-
|
|
2422
|
-
|
|
2423
|
-
|
|
2424
|
-
|
|
2425
|
-
|
|
2426
|
-
|
|
2427
|
-
|
|
2428
|
-
|
|
2429
|
-
|
|
2430
|
-
|
|
2431
|
-
|
|
2432
|
-
|
|
2433
|
-
|
|
2434
|
-
|
|
2435
|
-
|
|
2436
|
-
|
|
2437
|
-
|
|
2438
|
-
|
|
2439
|
-
|
|
2440
|
-
|
|
2441
|
-
|
|
2442
|
-
|
|
2443
|
-
|
|
2444
|
-
|
|
2445
|
-
|
|
2446
|
-
|
|
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
|