@rhea-finance/cross-chain-aggregation-dex 1.0.5 → 2.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.
Files changed (60) hide show
  1. package/README.md +277 -270
  2. package/dist/executors/aptos.d.mts +19 -0
  3. package/dist/executors/aptos.d.ts +19 -0
  4. package/dist/executors/aptos.js +140 -0
  5. package/dist/executors/aptos.js.map +1 -0
  6. package/dist/executors/aptos.mjs +138 -0
  7. package/dist/executors/aptos.mjs.map +1 -0
  8. package/dist/executors/bitcoin.d.mts +22 -0
  9. package/dist/executors/bitcoin.d.ts +22 -0
  10. package/dist/executors/bitcoin.js +153 -0
  11. package/dist/executors/bitcoin.js.map +1 -0
  12. package/dist/executors/bitcoin.mjs +151 -0
  13. package/dist/executors/bitcoin.mjs.map +1 -0
  14. package/dist/executors/evm.d.mts +18 -0
  15. package/dist/executors/evm.d.ts +18 -0
  16. package/dist/executors/evm.js +233 -0
  17. package/dist/executors/evm.js.map +1 -0
  18. package/dist/executors/evm.mjs +231 -0
  19. package/dist/executors/evm.mjs.map +1 -0
  20. package/dist/executors/near.d.mts +18 -0
  21. package/dist/executors/near.d.ts +18 -0
  22. package/dist/executors/near.js +162 -0
  23. package/dist/executors/near.js.map +1 -0
  24. package/dist/executors/near.mjs +160 -0
  25. package/dist/executors/near.mjs.map +1 -0
  26. package/dist/executors/solana.d.mts +20 -0
  27. package/dist/executors/solana.d.ts +20 -0
  28. package/dist/executors/solana.js +151 -0
  29. package/dist/executors/solana.js.map +1 -0
  30. package/dist/executors/solana.mjs +149 -0
  31. package/dist/executors/solana.mjs.map +1 -0
  32. package/dist/executors/sui.d.mts +19 -0
  33. package/dist/executors/sui.d.ts +19 -0
  34. package/dist/executors/sui.js +154 -0
  35. package/dist/executors/sui.js.map +1 -0
  36. package/dist/executors/sui.mjs +152 -0
  37. package/dist/executors/sui.mjs.map +1 -0
  38. package/dist/executors/tron.d.mts +24 -0
  39. package/dist/executors/tron.d.ts +24 -0
  40. package/dist/executors/tron.js +161 -0
  41. package/dist/executors/tron.js.map +1 -0
  42. package/dist/executors/tron.mjs +159 -0
  43. package/dist/executors/tron.mjs.map +1 -0
  44. package/dist/executors/zcash.d.mts +19 -0
  45. package/dist/executors/zcash.d.ts +19 -0
  46. package/dist/executors/zcash.js +158 -0
  47. package/dist/executors/zcash.js.map +1 -0
  48. package/dist/executors/zcash.mjs +156 -0
  49. package/dist/executors/zcash.mjs.map +1 -0
  50. package/dist/index.d.mts +277 -306
  51. package/dist/index.d.ts +277 -306
  52. package/dist/index.js +2359 -631
  53. package/dist/index.js.map +1 -1
  54. package/dist/index.mjs +2332 -620
  55. package/dist/index.mjs.map +1 -1
  56. package/dist/registry-DRYUqs7T.d.mts +532 -0
  57. package/dist/registry-DRYUqs7T.d.ts +532 -0
  58. package/dist/shared-BdH3hWuP.d.ts +23 -0
  59. package/dist/shared-BqpFeosz.d.mts +23 -0
  60. package/package.json +51 -17
package/dist/index.mjs CHANGED
@@ -1,694 +1,2406 @@
1
- import Big from 'big.js';
1
+ import { z, ZodError } from 'zod';
2
2
 
3
- // src/utils/logger.ts
4
- var LOG_LEVELS = {
5
- silent: 0,
6
- error: 1,
7
- warn: 2,
8
- info: 3,
9
- debug: 4
3
+ // src/core/errors.ts
4
+ var SwapSdkError = class extends Error {
5
+ constructor(code, stage, message, options = {}) {
6
+ super(message);
7
+ this.code = code;
8
+ this.stage = stage;
9
+ this.options = options;
10
+ this.name = "SwapSdkError";
11
+ Object.setPrototypeOf(this, new.target.prototype);
12
+ }
13
+ get retryable() {
14
+ return this.options.retryable ?? false;
15
+ }
16
+ get cause() {
17
+ return this.options.cause;
18
+ }
19
+ get details() {
20
+ return this.options.details;
21
+ }
22
+ };
23
+ function asSwapSdkError(error, stage) {
24
+ if (error instanceof SwapSdkError) return error;
25
+ const message = error instanceof Error ? error.message : String(error);
26
+ return new SwapSdkError("API_ERROR", stage, message, { cause: error });
27
+ }
28
+
29
+ // src/api/ApiClient.ts
30
+ var DEFAULT_RETRY = {
31
+ maxRetries: 2,
32
+ baseDelayMs: 250,
33
+ maxDelayMs: 2e3,
34
+ jitter: true
35
+ };
36
+ var ApiClient = class {
37
+ constructor(config) {
38
+ this.config = config;
39
+ this.baseUrl = config.baseUrl.replace(/\/$/, "");
40
+ const fetchImpl = config.fetch ?? globalThis.fetch;
41
+ if (typeof fetchImpl !== "function") {
42
+ throw new SwapSdkError(
43
+ "INVALID_REQUEST",
44
+ "quote",
45
+ "Fetch is unavailable; inject fetch when using Node.js 16"
46
+ );
47
+ }
48
+ this.fetchImpl = fetchImpl.bind(globalThis);
49
+ }
50
+ quote(body, options = {}) {
51
+ return this.request("/api/swap/quote", "quote", {
52
+ ...options,
53
+ method: "POST",
54
+ body,
55
+ retryableOperation: true
56
+ });
57
+ }
58
+ build(body, options = {}) {
59
+ return this.request("/api/swap/swap", "build", {
60
+ ...options,
61
+ method: "POST",
62
+ body
63
+ });
64
+ }
65
+ submitOrder(body, options = {}) {
66
+ return this.request("/api/swap/order-submit", "submit", {
67
+ ...options,
68
+ method: "POST",
69
+ body
70
+ });
71
+ }
72
+ getOrderStatus(params, options = {}) {
73
+ return this.request("/api/swap/order-status", "status", {
74
+ ...options,
75
+ method: "GET",
76
+ retryableOperation: true,
77
+ query: {
78
+ orderId: params.orderId,
79
+ router: params.router,
80
+ chainId: params.chainId
81
+ }
82
+ });
83
+ }
84
+ report(body, options = {}) {
85
+ return this.request("/api/swap/report", "report", {
86
+ ...options,
87
+ method: "POST",
88
+ body
89
+ });
90
+ }
91
+ getHistory(params, options = {}) {
92
+ return this.request("/api/swap/history", "history", {
93
+ ...options,
94
+ method: "GET",
95
+ retryableOperation: true,
96
+ query: {
97
+ sender: params.sender,
98
+ pageNumber: params.pageNumber,
99
+ pageSize: params.pageSize
100
+ }
101
+ });
102
+ }
103
+ async request(path, stage, options) {
104
+ const url = this.buildUrl(path, options.query);
105
+ const headers = await this.buildHeaders(options.idempotencyKey);
106
+ const retry = this.retryConfig();
107
+ let attempt = 1;
108
+ for (; ; ) {
109
+ this.log({
110
+ level: "debug",
111
+ event: "api.request",
112
+ path,
113
+ stage,
114
+ attempt
115
+ });
116
+ try {
117
+ return await this.requestOnce(url, path, stage, options, headers, attempt);
118
+ } catch (error) {
119
+ const sdkError = error instanceof SwapSdkError ? error : new SwapSdkError("HTTP_ERROR", stage, "Network request failed", {
120
+ cause: error,
121
+ retryable: true
122
+ });
123
+ const canRetry = options.retryableOperation === true && sdkError.retryable && sdkError.code !== "REQUEST_ABORTED" && attempt <= retry.maxRetries;
124
+ if (!canRetry) throw sdkError;
125
+ this.log({
126
+ level: "warn",
127
+ event: "api.retry",
128
+ path,
129
+ stage,
130
+ attempt,
131
+ code: sdkError.code
132
+ });
133
+ await waitForRetry(this.retryDelay(attempt, retry), options.signal, stage);
134
+ attempt += 1;
135
+ }
136
+ }
137
+ }
138
+ async requestOnce(url, path, stage, options, headers, attempt) {
139
+ if (options.signal?.aborted) {
140
+ throw new SwapSdkError("REQUEST_ABORTED", stage, "Request aborted", {
141
+ cause: options.signal.reason
142
+ });
143
+ }
144
+ const controller = new AbortController();
145
+ const timeoutMs = this.config.timeoutMs ?? 15e3;
146
+ let timedOut = false;
147
+ const startedAt = Date.now();
148
+ const abortFromCaller = () => controller.abort(options.signal?.reason);
149
+ if (options.signal?.aborted) abortFromCaller();
150
+ options.signal?.addEventListener("abort", abortFromCaller, { once: true });
151
+ const timeout = setTimeout(() => {
152
+ timedOut = true;
153
+ controller.abort();
154
+ }, timeoutMs);
155
+ try {
156
+ const response = await this.fetchImpl(url, {
157
+ method: options.method,
158
+ headers,
159
+ body: options.body === void 0 ? void 0 : JSON.stringify(options.body),
160
+ signal: controller.signal
161
+ });
162
+ if (controller.signal.aborted) {
163
+ throw new SwapSdkError(
164
+ timedOut ? "REQUEST_TIMEOUT" : "REQUEST_ABORTED",
165
+ stage,
166
+ timedOut ? `Request timed out after ${timeoutMs}ms` : "Request aborted",
167
+ { retryable: timedOut }
168
+ );
169
+ }
170
+ this.log({
171
+ level: "debug",
172
+ event: "api.response",
173
+ path,
174
+ stage,
175
+ attempt,
176
+ status: response.status,
177
+ durationMs: Date.now() - startedAt
178
+ });
179
+ const text = await response.text();
180
+ const parsed = this.parseResponse(text, response.status, stage);
181
+ if (!response.ok) {
182
+ const message = this.readMessage(parsed) || `HTTP ${response.status}`;
183
+ if (response.status === 401 || response.status === 403) {
184
+ throw new SwapSdkError("AUTH_FAILED", stage, message);
185
+ }
186
+ if (response.status === 429) {
187
+ throw new SwapSdkError("RATE_LIMITED", stage, message, {
188
+ retryable: true
189
+ });
190
+ }
191
+ throw new SwapSdkError("HTTP_ERROR", stage, message, {
192
+ retryable: response.status >= 500,
193
+ details: { status: response.status }
194
+ });
195
+ }
196
+ if (!this.isEnvelope(parsed)) {
197
+ throw new SwapSdkError(
198
+ "INVALID_API_RESPONSE",
199
+ stage,
200
+ "Invalid unified swap API response envelope"
201
+ );
202
+ }
203
+ if (parsed.code !== 0) {
204
+ throw new SwapSdkError(
205
+ "API_ERROR",
206
+ stage,
207
+ parsed.msg || `Service returned code ${parsed.code}`,
208
+ { details: { apiCode: parsed.code } }
209
+ );
210
+ }
211
+ return parsed.data;
212
+ } catch (error) {
213
+ if (error instanceof SwapSdkError) throw error;
214
+ if (controller.signal.aborted) {
215
+ throw new SwapSdkError(
216
+ timedOut ? "REQUEST_TIMEOUT" : "REQUEST_ABORTED",
217
+ stage,
218
+ timedOut ? `Request timed out after ${timeoutMs}ms` : "Request aborted",
219
+ { cause: error, retryable: timedOut }
220
+ );
221
+ }
222
+ const details = networkFailureDetails(
223
+ error,
224
+ options.method,
225
+ path,
226
+ attempt
227
+ );
228
+ console.error("SDK network request failed", {
229
+ ...details,
230
+ stage
231
+ });
232
+ throw new SwapSdkError(
233
+ "HTTP_ERROR",
234
+ stage,
235
+ `Network request failed: ${details.causeName}: ${details.causeMessage}`,
236
+ {
237
+ cause: error,
238
+ retryable: true,
239
+ details
240
+ }
241
+ );
242
+ } finally {
243
+ clearTimeout(timeout);
244
+ options.signal?.removeEventListener("abort", abortFromCaller);
245
+ }
246
+ }
247
+ buildUrl(path, query) {
248
+ if (!query) return `${this.baseUrl}${path}`;
249
+ const search = new URLSearchParams();
250
+ for (const [key, value] of Object.entries(query)) {
251
+ if (value === void 0 || value === null) continue;
252
+ search.set(key, String(value));
253
+ }
254
+ const suffix = search.toString();
255
+ return suffix ? `${this.baseUrl}${path}?${suffix}` : `${this.baseUrl}${path}`;
256
+ }
257
+ async buildHeaders(idempotencyKey) {
258
+ const configured = typeof this.config.headers === "function" ? await this.config.headers() : this.config.headers ?? {};
259
+ const token = this.config.getAccessToken ? await this.config.getAccessToken() : this.config.apiKey;
260
+ return {
261
+ "Content-Type": "application/json",
262
+ ...token ? { Authorization: `Bearer ${token}` } : {},
263
+ ...idempotencyKey ? { "Idempotency-Key": idempotencyKey } : {},
264
+ ...configured
265
+ };
266
+ }
267
+ retryConfig() {
268
+ const configured = { ...DEFAULT_RETRY, ...this.config.retry };
269
+ if (!Number.isSafeInteger(configured.maxRetries) || configured.maxRetries < 0 || !Number.isFinite(configured.baseDelayMs) || configured.baseDelayMs < 0 || !Number.isFinite(configured.maxDelayMs) || configured.maxDelayMs < configured.baseDelayMs) {
270
+ throw new SwapSdkError(
271
+ "INVALID_REQUEST",
272
+ "quote",
273
+ "Invalid retry configuration"
274
+ );
275
+ }
276
+ return configured;
277
+ }
278
+ retryDelay(attempt, retry) {
279
+ const exponential = Math.min(
280
+ retry.maxDelayMs,
281
+ retry.baseDelayMs * 2 ** (attempt - 1)
282
+ );
283
+ return retry.jitter ? Math.min(retry.maxDelayMs, exponential * (0.5 + Math.random())) : exponential;
284
+ }
285
+ log(entry) {
286
+ try {
287
+ this.config.logger?.log(entry);
288
+ } catch {
289
+ }
290
+ }
291
+ parseResponse(text, status, stage) {
292
+ try {
293
+ return text ? JSON.parse(text) : {};
294
+ } catch (error) {
295
+ throw new SwapSdkError(
296
+ status >= 400 ? "HTTP_ERROR" : "INVALID_API_RESPONSE",
297
+ stage,
298
+ status >= 400 ? `HTTP ${status}` : "Response is not valid JSON",
299
+ { cause: error, retryable: status >= 500 }
300
+ );
301
+ }
302
+ }
303
+ isEnvelope(value) {
304
+ return typeof value === "object" && value !== null && "code" in value && typeof value.code === "number" && "msg" in value && typeof value.msg === "string" && "data" in value;
305
+ }
306
+ readMessage(value) {
307
+ if (typeof value !== "object" || value === null || !("msg" in value)) {
308
+ return void 0;
309
+ }
310
+ return typeof value.msg === "string" && value.msg.trim() ? value.msg.trim() : void 0;
311
+ }
312
+ };
313
+ function networkFailureDetails(error, method, path, attempt) {
314
+ const causeName = error instanceof Error && error.name.trim() ? error.name.trim() : "Error";
315
+ const rawMessage = error instanceof Error && error.message.trim() ? error.message.trim() : String(error);
316
+ const causeMessage = rawMessage.replace(
317
+ /\b(https?:\/\/[^\s?#]+)\?[^\s#]*/gi,
318
+ "$1?[redacted]"
319
+ );
320
+ return {
321
+ method,
322
+ path,
323
+ attempt,
324
+ causeName,
325
+ causeMessage
326
+ };
327
+ }
328
+ function waitForRetry(delayMs, signal, stage) {
329
+ return new Promise((resolve, reject) => {
330
+ if (signal?.aborted) {
331
+ reject(
332
+ new SwapSdkError("REQUEST_ABORTED", stage, "Request aborted", {
333
+ cause: signal.reason
334
+ })
335
+ );
336
+ return;
337
+ }
338
+ const onAbort = () => {
339
+ clearTimeout(timeout);
340
+ reject(
341
+ new SwapSdkError("REQUEST_ABORTED", stage, "Request aborted", {
342
+ cause: signal?.reason
343
+ })
344
+ );
345
+ };
346
+ const timeout = setTimeout(() => {
347
+ signal?.removeEventListener("abort", onAbort);
348
+ resolve();
349
+ }, delayMs);
350
+ signal?.addEventListener("abort", onAbort, { once: true });
351
+ });
352
+ }
353
+
354
+ // src/core/lifecycle.ts
355
+ var ORDER_STATUS_MAP = {
356
+ PENDING: "pending",
357
+ CREATED: "pending",
358
+ PROCESSING: "processing",
359
+ IN_PROGRESS: "processing",
360
+ SUCCESS: "completed",
361
+ COMPLETED: "completed",
362
+ FILLED: "completed",
363
+ FAILED: "failed",
364
+ REFUNDED: "refunded",
365
+ EXPIRED: "expired"
366
+ };
367
+ function normalizeOrderStatus(raw) {
368
+ const value = raw.status ?? raw.state;
369
+ if (typeof value !== "string") return "unknown";
370
+ return ORDER_STATUS_MAP[value.trim().toUpperCase()] ?? "unknown";
371
+ }
372
+
373
+ // src/core/registry.ts
374
+ var ExecutorRegistry = class {
375
+ constructor(executors = []) {
376
+ this.executors = /* @__PURE__ */ new Map();
377
+ for (const executor of executors) this.register(executor);
378
+ }
379
+ register(executor, allowOverride = false) {
380
+ for (const kind of executor.kinds) {
381
+ if (!allowOverride && this.executors.has(kind)) {
382
+ throw new SwapSdkError(
383
+ "INVALID_REQUEST",
384
+ "build",
385
+ `Executor already registered for ${kind}`
386
+ );
387
+ }
388
+ this.executors.set(kind, executor);
389
+ }
390
+ }
391
+ get(kind) {
392
+ const executor = this.executors.get(kind);
393
+ if (!executor) {
394
+ throw new SwapSdkError(
395
+ "EXECUTOR_NOT_FOUND",
396
+ "sign",
397
+ `No executor registered for ${kind}`
398
+ );
399
+ }
400
+ return executor;
401
+ }
402
+ getSigner(chain, requireSignMessage = false) {
403
+ const executor = Array.from(new Set(this.executors.values())).find(
404
+ (candidate) => candidate.signerChain === chain
405
+ );
406
+ if (!executor) {
407
+ throw new SwapSdkError(
408
+ "EXECUTOR_NOT_FOUND",
409
+ "sign",
410
+ `No executor registered for signer chain ${chain}`
411
+ );
412
+ }
413
+ if (!executor.getIdentityKey) {
414
+ throw new SwapSdkError(
415
+ "SIGNING_FAILED",
416
+ "sign",
417
+ `Executor for signer chain ${chain} must implement getIdentityKey`
418
+ );
419
+ }
420
+ if (requireSignMessage && !executor.signMessage) {
421
+ throw new SwapSdkError(
422
+ "SIGNING_FAILED",
423
+ "sign",
424
+ `Executor for signer chain ${chain} must implement signMessage`
425
+ );
426
+ }
427
+ return executor;
428
+ }
429
+ };
430
+
431
+ // src/normalizers/chain.ts
432
+ var CANONICAL_NON_EVM_CHAINS = /* @__PURE__ */ new Set([
433
+ "solana",
434
+ "aptos",
435
+ "near",
436
+ "tron",
437
+ "btc",
438
+ "zcash",
439
+ "sui"
440
+ ]);
441
+ var RAW_API_ALIASES = /* @__PURE__ */ new Map([
442
+ ["sol", "solana"],
443
+ ["501", "solana"],
444
+ ["637", "aptos"],
445
+ ["trx", "tron"],
446
+ ["bitcoin", "btc"],
447
+ ["zec", "zcash"]
448
+ ]);
449
+ var NATIVE_ADDRESSES = /* @__PURE__ */ new Map([
450
+ ["solana", "So11111111111111111111111111111111111111112"],
451
+ ["aptos", "0xa"],
452
+ ["near", "wrap.near"],
453
+ ["tron", "trx"],
454
+ ["btc", "btc"],
455
+ ["zcash", "nep141:zec.omft.near"],
456
+ ["sui", "0x2::sui::SUI"]
457
+ ]);
458
+ var EVM_ZERO_ADDRESS = "0x0000000000000000000000000000000000000000";
459
+ var DECIMAL_EVM_CHAIN_ID = /^[1-9]\d*$/;
460
+ function toApiChain(chain) {
461
+ if (DECIMAL_EVM_CHAIN_ID.test(chain) || CANONICAL_NON_EVM_CHAINS.has(chain)) {
462
+ return chain;
463
+ }
464
+ throw unsupportedChain(chain);
465
+ }
466
+ function fromApiChain(chain) {
467
+ const normalized = chain.trim().toLowerCase();
468
+ const alias = RAW_API_ALIASES.get(normalized);
469
+ if (alias) return alias;
470
+ if (CANONICAL_NON_EVM_CHAINS.has(normalized)) {
471
+ return normalized;
472
+ }
473
+ if (/^0x[0-9a-f]+$/.test(normalized)) {
474
+ const decimal = BigInt(normalized).toString();
475
+ if (decimal !== "0") return decimal;
476
+ }
477
+ if (DECIMAL_EVM_CHAIN_ID.test(normalized)) {
478
+ return BigInt(normalized).toString();
479
+ }
480
+ throw unsupportedChain(chain);
481
+ }
482
+ function toApiAssetAddress(asset) {
483
+ const explicit = asset.address.trim();
484
+ if (explicit) return explicit;
485
+ if (!asset.isNative) {
486
+ throw new SwapSdkError(
487
+ "INVALID_REQUEST",
488
+ "quote",
489
+ `Asset address is required for ${asset.chain}`
490
+ );
491
+ }
492
+ if (DECIMAL_EVM_CHAIN_ID.test(asset.chain)) return EVM_ZERO_ADDRESS;
493
+ const nativeAddress = NATIVE_ADDRESSES.get(asset.chain);
494
+ if (!nativeAddress) {
495
+ throw new SwapSdkError(
496
+ "UNSUPPORTED_CHAIN",
497
+ "quote",
498
+ `No native asset mapping for ${asset.chain}`
499
+ );
500
+ }
501
+ return nativeAddress;
502
+ }
503
+ function unsupportedChain(chain) {
504
+ return new SwapSdkError(
505
+ "UNSUPPORTED_CHAIN",
506
+ "quote",
507
+ `Unsupported chain: ${chain}`
508
+ );
509
+ }
510
+ var decimalStringSchema = z.string().regex(/^(0|[1-9]\d*)$/);
511
+ var nonEmptyStringSchema = z.string().trim().min(1);
512
+ var hexDataSchema = z.string().regex(/^0x(?:[0-9a-fA-F]{2})*$/);
513
+ var positiveIntegerSchema = z.number().int().positive();
514
+ var evmQuantitySchema = z.string().regex(/^(?:0|[1-9]\d*|0x[0-9a-fA-F]+)$/).transform(
515
+ (value) => value.startsWith("0x") ? BigInt(value).toString() : value
516
+ );
517
+ var evmTxSchema = z.object({
518
+ to: nonEmptyStringSchema,
519
+ data: hexDataSchema,
520
+ value: evmQuantitySchema,
521
+ gasLimit: evmQuantitySchema,
522
+ chainId: positiveIntegerSchema
523
+ });
524
+
525
+ // src/normalizers/build.ts
526
+ var tokenSchema = z.object({
527
+ address: z.string(),
528
+ symbol: z.string(),
529
+ decimals: z.number().int().nonnegative()
530
+ });
531
+ var commonBuildSchema = z.object({
532
+ isCrossChain: z.boolean(),
533
+ chainType: nonEmptyStringSchema,
534
+ router: nonEmptyStringSchema,
535
+ fromChain: nonEmptyStringSchema,
536
+ toChain: nonEmptyStringSchema,
537
+ tokenIn: tokenSchema,
538
+ tokenOut: tokenSchema,
539
+ amountIn: decimalStringSchema,
540
+ estimatedOut: decimalStringSchema,
541
+ minAmountOut: decimalStringSchema
542
+ });
543
+ var signingRequestSchema = z.object({
544
+ type: nonEmptyStringSchema,
545
+ router: nonEmptyStringSchema,
546
+ quoteId: nonEmptyStringSchema,
547
+ chainId: positiveIntegerSchema,
548
+ signingScheme: z.string().optional(),
549
+ typedData: z.object({
550
+ domain: z.record(z.string(), z.unknown()),
551
+ types: z.record(
552
+ z.string(),
553
+ z.array(z.object({ name: z.string(), type: z.string() }))
554
+ ),
555
+ primaryType: nonEmptyStringSchema,
556
+ message: z.record(z.string(), z.unknown())
557
+ }),
558
+ submit: z.object({
559
+ endpoint: z.string(),
560
+ method: z.string(),
561
+ params: z.record(z.string(), z.string())
562
+ }).optional()
563
+ });
564
+ var solanaTxSchema = z.object({
565
+ transaction: z.string(),
566
+ format: nonEmptyStringSchema,
567
+ addressLookupTableAddresses: z.array(z.string()).optional(),
568
+ recentBlockhash: z.string().optional(),
569
+ txValidUntil: z.number().optional(),
570
+ transactionSize: z.number().optional()
571
+ });
572
+ var aptosTxSchema = z.object({
573
+ function: nonEmptyStringSchema,
574
+ type_arguments: z.array(z.string()),
575
+ arguments: z.array(z.unknown())
576
+ });
577
+ var nearTxSchema = z.object({
578
+ signerId: z.string().optional(),
579
+ receiverId: nonEmptyStringSchema,
580
+ actions: z.array(z.unknown()).min(1)
581
+ });
582
+ var transferBaseSchema = z.object({
583
+ kind: nonEmptyStringSchema,
584
+ chainId: z.string().optional(),
585
+ chain: z.string().optional(),
586
+ amount: decimalStringSchema,
587
+ depositAddress: nonEmptyStringSchema
588
+ });
589
+ var tronTxSchema = transferBaseSchema.extend({
590
+ tokenAddress: z.string().optional(),
591
+ standard: z.string().optional()
592
+ });
593
+ var bitcoinTxSchema = transferBaseSchema.extend({
594
+ feeRate: z.number().positive().optional()
595
+ });
596
+ var zcashTxSchema = transferBaseSchema.extend({
597
+ decimals: z.number().int().nonnegative().optional()
598
+ });
599
+ var suiTxSchema = transferBaseSchema.extend({
600
+ coinType: nonEmptyStringSchema.refine(
601
+ (value) => !value.toLowerCase().startsWith("nep141:"),
602
+ "Sui coinType cannot be an OMFT asset id"
603
+ )
604
+ });
605
+ function normalizeBuild(raw, executionId = createExecutionId(), request) {
606
+ try {
607
+ const common = commonBuildSchema.parse(raw);
608
+ const fromChain = fromApiChain(common.fromChain);
609
+ const toChain = fromApiChain(common.toChain);
610
+ const lane = laneFromChainType(common.chainType, fromChain);
611
+ assertLaneMatchesChain(lane, fromChain);
612
+ const execution = normalizeExecution(raw, lane, fromChain);
613
+ const order = normalizeOrder(raw, execution);
614
+ const deposit = normalizeDeposit(raw.deposit);
615
+ return {
616
+ executionId,
617
+ ...raw.signingRequest?.quoteId ? { quoteId: raw.signingRequest.quoteId } : {},
618
+ isCrossChain: common.isCrossChain,
619
+ fromChain,
620
+ toChain,
621
+ tokenIn: { chain: fromChain, ...common.tokenIn },
622
+ tokenOut: { chain: toChain, ...common.tokenOut },
623
+ amountIn: common.amountIn,
624
+ estimatedOut: common.estimatedOut,
625
+ minAmountOut: common.minAmountOut,
626
+ router: common.router,
627
+ execution,
628
+ ...order ? { order } : {},
629
+ ...deposit ? { deposit } : {},
630
+ ...request ? { request: { ...request } } : {},
631
+ raw
632
+ };
633
+ } catch (error) {
634
+ if (error instanceof SwapSdkError) throw error;
635
+ throw invalidBuild(error);
636
+ }
637
+ }
638
+ function normalizeExecution(raw, lane, chain) {
639
+ switch (lane) {
640
+ case "evm":
641
+ return normalizeEvmExecution(raw, chain);
642
+ case "solana": {
643
+ const tx = solanaTxSchema.parse(raw.tx);
644
+ return {
645
+ kind: "solana-transaction",
646
+ chain,
647
+ transaction: tx.transaction,
648
+ format: tx.format,
649
+ metadata: {
650
+ ...tx.addressLookupTableAddresses ? { addressLookupTableAddresses: tx.addressLookupTableAddresses } : {},
651
+ ...tx.recentBlockhash ? { recentBlockhash: tx.recentBlockhash } : {},
652
+ ...tx.txValidUntil === void 0 ? {} : { txValidUntil: tx.txValidUntil },
653
+ ...tx.transactionSize === void 0 ? {} : { transactionSize: tx.transactionSize }
654
+ }
655
+ };
656
+ }
657
+ case "aptos": {
658
+ const tx = aptosTxSchema.parse(raw.tx);
659
+ return {
660
+ kind: "aptos-entry-function",
661
+ chain,
662
+ function: tx.function,
663
+ typeArguments: tx.type_arguments,
664
+ functionArguments: tx.arguments
665
+ };
666
+ }
667
+ case "near": {
668
+ const transactions = z.union([nearTxSchema, z.array(nearTxSchema).min(1)]).parse(raw.tx);
669
+ return {
670
+ kind: "near-transaction-batch",
671
+ chain,
672
+ transactions: Array.isArray(transactions) ? transactions : [transactions]
673
+ };
674
+ }
675
+ case "tron": {
676
+ const tx = tronTxSchema.parse(raw.tx);
677
+ assertKind(tx.kind, ["tron_transfer"]);
678
+ return {
679
+ kind: "tron-transfer",
680
+ chain,
681
+ amount: tx.amount,
682
+ depositAddress: tx.depositAddress,
683
+ ...tx.tokenAddress ? { tokenAddress: tx.tokenAddress } : {},
684
+ ...tx.standard ? { standard: tx.standard } : {}
685
+ };
686
+ }
687
+ case "bitcoin": {
688
+ const tx = bitcoinTxSchema.parse(raw.tx);
689
+ assertKind(tx.kind, ["btc_transfer", "utxo_transfer"]);
690
+ return {
691
+ kind: "bitcoin-transfer",
692
+ chain,
693
+ amount: tx.amount,
694
+ depositAddress: tx.depositAddress,
695
+ ...tx.feeRate === void 0 ? {} : { feeRate: tx.feeRate }
696
+ };
697
+ }
698
+ case "zcash": {
699
+ const tx = zcashTxSchema.parse(raw.tx);
700
+ assertKind(tx.kind, ["zcash_transfer", "utxo_transfer"]);
701
+ return {
702
+ kind: "zcash-transfer",
703
+ chain,
704
+ amount: tx.amount,
705
+ depositAddress: tx.depositAddress,
706
+ ...tx.decimals === void 0 ? {} : { decimals: tx.decimals }
707
+ };
708
+ }
709
+ case "sui": {
710
+ const candidate = typeof raw.tx === "object" && raw.tx !== null ? {
711
+ ...raw.tx,
712
+ coinType: "coinType" in raw.tx && raw.tx.coinType ? raw.tx.coinType : raw.tokenIn.address
713
+ } : raw.tx;
714
+ const tx = suiTxSchema.parse(candidate);
715
+ assertKind(tx.kind, ["sui_transfer"]);
716
+ return {
717
+ kind: "sui-transfer",
718
+ chain,
719
+ amount: tx.amount,
720
+ depositAddress: tx.depositAddress,
721
+ coinType: tx.coinType
722
+ };
723
+ }
724
+ }
725
+ }
726
+ function normalizeEvmExecution(raw, chain) {
727
+ const approval = normalizeEvmApproval(raw, chain);
728
+ if (raw.executionType === "signature" || raw.signingRequest) {
729
+ const request = signingRequestSchema.parse(raw.signingRequest);
730
+ assertEvmChainId(chain, request.chainId);
731
+ return {
732
+ kind: "evm-signature",
733
+ chain,
734
+ request,
735
+ ...approval ? { approval } : {}
736
+ };
737
+ }
738
+ const tx = evmTxSchema.parse(raw.tx);
739
+ assertEvmChainId(chain, tx.chainId);
740
+ return {
741
+ kind: "evm-transaction",
742
+ chain,
743
+ tx,
744
+ ...approval ? { approval } : {}
745
+ };
746
+ }
747
+ function normalizeEvmApproval(raw, chain) {
748
+ if (raw.approve) {
749
+ const approveTx = evmTxSchema.parse(raw.approve.tx);
750
+ assertEvmChainId(chain, approveTx.chainId);
751
+ return {
752
+ tx: approveTx,
753
+ spender: nonEmptyStringSchema.parse(raw.approve.spender)
754
+ };
755
+ }
756
+ return void 0;
757
+ }
758
+ function laneFromChainType(chainType, fromChain) {
759
+ const normalized = chainType.toLowerCase();
760
+ const aliases = {
761
+ evm: "evm",
762
+ solana: "solana",
763
+ sol: "solana",
764
+ aptos: "aptos",
765
+ near: "near",
766
+ tron: "tron",
767
+ btc: "bitcoin",
768
+ bitcoin: "bitcoin",
769
+ zcash: "zcash",
770
+ zec: "zcash",
771
+ sui: "sui"
772
+ };
773
+ if (normalized === "cross-chain") return laneFromChain(fromChain);
774
+ const lane = aliases[normalized];
775
+ if (!lane) {
776
+ throw new SwapSdkError(
777
+ "UNSUPPORTED_CHAIN",
778
+ "build",
779
+ `Unsupported build chainType: ${chainType}`
780
+ );
781
+ }
782
+ return lane;
783
+ }
784
+ function laneFromChain(chain) {
785
+ if (/^[1-9]\d*$/.test(chain)) return "evm";
786
+ const lanes = {
787
+ solana: "solana",
788
+ aptos: "aptos",
789
+ near: "near",
790
+ tron: "tron",
791
+ btc: "bitcoin",
792
+ zcash: "zcash",
793
+ sui: "sui"
794
+ };
795
+ const lane = lanes[chain];
796
+ if (!lane) {
797
+ throw new SwapSdkError(
798
+ "UNSUPPORTED_CHAIN",
799
+ "build",
800
+ `Unsupported source chain: ${chain}`
801
+ );
802
+ }
803
+ return lane;
804
+ }
805
+ function assertLaneMatchesChain(lane, chain) {
806
+ const chainLane = laneFromChain(chain);
807
+ if (lane !== chainLane) {
808
+ throw new SwapSdkError(
809
+ "CHAIN_MISMATCH",
810
+ "build",
811
+ `Build chainType ${lane} does not match source chain ${chain}`
812
+ );
813
+ }
814
+ }
815
+ function assertEvmChainId(chain, chainId) {
816
+ if (chain !== String(chainId)) {
817
+ throw new SwapSdkError(
818
+ "CHAIN_MISMATCH",
819
+ "build",
820
+ `EVM transaction chainId ${chainId} does not match ${chain}`
821
+ );
822
+ }
823
+ }
824
+ function assertKind(actual, allowed) {
825
+ if (!allowed.includes(actual.toLowerCase())) {
826
+ throw new SwapSdkError(
827
+ "INVALID_API_RESPONSE",
828
+ "build",
829
+ `Unexpected transaction kind: ${actual}`
830
+ );
831
+ }
832
+ }
833
+ function normalizeOrder(raw, execution) {
834
+ const depositOrderId = readRecordString(raw.deposit, "orderId");
835
+ const orderId = raw.orderId ?? depositOrderId;
836
+ if (!orderId) return void 0;
837
+ const router = raw.statusRouter ?? (execution.kind === "evm-signature" ? execution.request.router : void 0) ?? raw.router;
838
+ const chainId = execution.kind === "evm-signature" ? String(execution.request.chainId) : execution.kind === "evm-transaction" ? String(execution.tx.chainId) : void 0;
839
+ return { orderId, router, ...chainId ? { chainId } : {} };
840
+ }
841
+ function normalizeDeposit(value) {
842
+ if (typeof value !== "object" || value === null) return void 0;
843
+ const depositAddress = readRecordString(value, "depositAddress");
844
+ if (!depositAddress) return void 0;
845
+ return {
846
+ depositAddress,
847
+ ...readRecordString(value, "depositMemo") ? { depositMemo: readRecordString(value, "depositMemo") } : {},
848
+ ...readRecordString(value, "orderId") ? { orderId: readRecordString(value, "orderId") } : {},
849
+ ...readRecordString(value, "estimatedOut") ? { estimatedOut: decimalStringSchema.parse(readRecordString(value, "estimatedOut")) } : {},
850
+ ...readRecordString(value, "minAmountOut") ? { minAmountOut: decimalStringSchema.parse(readRecordString(value, "minAmountOut")) } : {},
851
+ ...typeof Reflect.get(value, "timeEstimate") === "number" || typeof Reflect.get(value, "timeEstimate") === "string" ? { timeEstimate: Reflect.get(value, "timeEstimate") } : {}
852
+ };
853
+ }
854
+ function readRecordString(value, key) {
855
+ if (typeof value !== "object" || value === null) return void 0;
856
+ const field = Reflect.get(value, key);
857
+ return typeof field === "string" && field.trim() ? field.trim() : void 0;
858
+ }
859
+ function createExecutionId() {
860
+ if (typeof globalThis.crypto?.randomUUID === "function") {
861
+ return globalThis.crypto.randomUUID();
862
+ }
863
+ return `swap_${Date.now()}_${Math.random().toString(36).slice(2)}`;
864
+ }
865
+ function invalidBuild(error) {
866
+ return new SwapSdkError(
867
+ "INVALID_API_RESPONSE",
868
+ "build",
869
+ "Invalid swap build response",
870
+ {
871
+ cause: error,
872
+ details: error instanceof ZodError ? {
873
+ issues: error.issues.map((issue) => ({
874
+ path: issue.path.join("."),
875
+ message: issue.message
876
+ }))
877
+ } : void 0
878
+ }
879
+ );
880
+ }
881
+
882
+ // src/types/chain.ts
883
+ var BASE_UNIT_AMOUNT = /^(0|[1-9]\d*)$/;
884
+ function assertBaseUnitAmount(value) {
885
+ if (!BASE_UNIT_AMOUNT.test(value)) {
886
+ throw new SwapSdkError(
887
+ "INVALID_REQUEST",
888
+ "quote",
889
+ `Invalid base-unit amount: ${value}`
890
+ );
891
+ }
892
+ return value;
893
+ }
894
+
895
+ // src/normalizers/quote.ts
896
+ var DEFAULT_QUOTE_WAITING_TIME_MS = 3e3;
897
+ function serializeQuoteRequest(request) {
898
+ validateQuoteRequest(request);
899
+ return {
900
+ ...request.extensions ?? {},
901
+ fromChain: toApiChain(request.fromChain),
902
+ toChain: toApiChain(request.toChain),
903
+ tokenIn: toApiAssetAddress(request.tokenIn),
904
+ tokenOut: toApiAssetAddress(request.tokenOut),
905
+ amountIn: request.amountIn,
906
+ slippage: request.slippageBps,
907
+ quoteWaitingTimeMs: request.quoteWaitingTimeMs ?? DEFAULT_QUOTE_WAITING_TIME_MS,
908
+ sender: request.sender.trim(),
909
+ ...request.recipient?.trim() ? { recipient: request.recipient.trim() } : {}
910
+ };
911
+ }
912
+ function normalizeQuote(request, raw, receivedAt = Date.now()) {
913
+ const bestRoute = normalizeRoute(raw.bestQuote, true);
914
+ if (!bestRoute) {
915
+ throw invalidQuote("Quote response does not contain a valid best route");
916
+ }
917
+ const quoteId = readOptionalString(raw.bestQuote.quoteId);
918
+ const apiRequest = Object.freeze({ ...serializeQuoteRequest(request) });
919
+ const buildContext = Object.freeze({
920
+ request: apiRequest,
921
+ router: bestRoute.router,
922
+ ...bestRoute.market ? { market: bestRoute.market } : {},
923
+ expectedOut: bestRoute.amountOut,
924
+ minAmountOut: bestRoute.minAmountOut,
925
+ preSwap: raw.bestQuote.preSwap ?? null,
926
+ bridge: raw.bestQuote.bridge ?? null,
927
+ ...quoteId ? { quoteId } : {}
928
+ });
929
+ const expiresAt = readTimestamp(
930
+ raw.bestQuote.expiresAt ?? raw.bestQuote.expirationTime
931
+ );
932
+ return {
933
+ ...quoteId ? { id: quoteId } : {},
934
+ fromChain: request.fromChain,
935
+ toChain: request.toChain,
936
+ tokenIn: { ...request.tokenIn },
937
+ tokenOut: { ...request.tokenOut },
938
+ amountIn: validateResponseAmount(request.amountIn, "amountIn"),
939
+ estimatedOut: bestRoute.amountOut,
940
+ minAmountOut: bestRoute.minAmountOut,
941
+ route: bestRoute,
942
+ alternatives: raw.allQuotes.flatMap((route) => {
943
+ try {
944
+ const normalized = normalizeRoute(route, false);
945
+ return normalized ? [normalized] : [];
946
+ } catch {
947
+ return [];
948
+ }
949
+ }),
950
+ receivedAt,
951
+ ...expiresAt === void 0 ? {} : { expiresAt },
952
+ buildContext,
953
+ raw
954
+ };
955
+ }
956
+ function validateQuoteRequest(request) {
957
+ assertBaseUnitAmount(request.amountIn);
958
+ if (!Number.isInteger(request.slippageBps) || request.slippageBps < 0) {
959
+ throw new SwapSdkError(
960
+ "INVALID_REQUEST",
961
+ "quote",
962
+ "slippageBps must be a non-negative integer"
963
+ );
964
+ }
965
+ if (request.slippageBps > 1e4) {
966
+ throw new SwapSdkError(
967
+ "INVALID_REQUEST",
968
+ "quote",
969
+ "slippageBps cannot exceed 10000"
970
+ );
971
+ }
972
+ if (request.quoteWaitingTimeMs !== void 0 && (!Number.isFinite(request.quoteWaitingTimeMs) || !Number.isInteger(request.quoteWaitingTimeMs) || request.quoteWaitingTimeMs < 0)) {
973
+ throw new SwapSdkError(
974
+ "INVALID_REQUEST",
975
+ "quote",
976
+ "quoteWaitingTimeMs must be a non-negative integer"
977
+ );
978
+ }
979
+ if (!request.sender.trim()) {
980
+ throw new SwapSdkError(
981
+ "INVALID_REQUEST",
982
+ "quote",
983
+ "sender is required"
984
+ );
985
+ }
986
+ if (request.tokenIn.chain !== request.fromChain) {
987
+ throw new SwapSdkError(
988
+ "CHAIN_MISMATCH",
989
+ "quote",
990
+ "tokenIn chain does not match fromChain"
991
+ );
992
+ }
993
+ if (request.tokenOut.chain !== request.toChain) {
994
+ throw new SwapSdkError(
995
+ "CHAIN_MISMATCH",
996
+ "quote",
997
+ "tokenOut chain does not match toChain"
998
+ );
999
+ }
1000
+ }
1001
+ function normalizeRoute(raw, required) {
1002
+ const router = readOptionalString(raw.router);
1003
+ const amountOutValue = raw.amountOut ?? raw.estimatedOut;
1004
+ const amountOut = readOptionalString(amountOutValue);
1005
+ const minAmountOut = readOptionalString(raw.minAmountOut) ?? amountOut;
1006
+ if (!router || !amountOut || !minAmountOut) {
1007
+ if (required) throw invalidQuote("Quote response is missing route fields");
1008
+ return void 0;
1009
+ }
1010
+ return {
1011
+ router,
1012
+ ...readOptionalString(raw.market) ? { market: readOptionalString(raw.market) } : {},
1013
+ amountOut: validateResponseAmount(amountOut, "amountOut"),
1014
+ minAmountOut: validateResponseAmount(minAmountOut, "minAmountOut"),
1015
+ raw
1016
+ };
1017
+ }
1018
+ function validateResponseAmount(value, field) {
1019
+ try {
1020
+ return assertBaseUnitAmount(value);
1021
+ } catch (error) {
1022
+ throw invalidQuote(`Quote response has invalid ${field}`, error);
1023
+ }
1024
+ }
1025
+ function readOptionalString(value) {
1026
+ return typeof value === "string" && value.trim() ? value.trim() : void 0;
1027
+ }
1028
+ function readTimestamp(value) {
1029
+ if (typeof value === "number" && Number.isFinite(value)) return value;
1030
+ if (typeof value === "string" && /^\d+$/.test(value)) return Number(value);
1031
+ return void 0;
1032
+ }
1033
+ function invalidQuote(message, cause) {
1034
+ return new SwapSdkError("INVALID_API_RESPONSE", "quote", message, {
1035
+ cause
1036
+ });
1037
+ }
1038
+ var historyRecordSchema = z.object({
1039
+ id: z.number().int(),
1040
+ sender: z.string(),
1041
+ recipient: z.unknown().optional(),
1042
+ from_hash: z.string(),
1043
+ to_hash: z.string().nullable().optional(),
1044
+ deposit_address: z.string().optional(),
1045
+ from_token: z.string(),
1046
+ to_token: z.string(),
1047
+ from_chain: z.string(),
1048
+ to_chain: z.string(),
1049
+ amount_in: decimalStringSchema.optional(),
1050
+ estimated_out: decimalStringSchema.optional(),
1051
+ actual_out: decimalStringSchema.nullable().optional(),
1052
+ router: z.string().optional(),
1053
+ status: z.string().optional(),
1054
+ swap_id: z.string().nullable().optional(),
1055
+ status_response: z.record(z.string(), z.unknown()).optional(),
1056
+ created_at: z.string().optional(),
1057
+ updated_at: z.string().optional()
1058
+ }).passthrough();
1059
+ var historyPageSchema = z.object({
1060
+ record_list: z.array(historyRecordSchema),
1061
+ page_number: z.number().int().nonnegative(),
1062
+ page_size: z.number().int().nonnegative(),
1063
+ total_page: z.number().int().nonnegative(),
1064
+ total_size: z.number().int().nonnegative()
1065
+ });
1066
+ var HISTORY_STATUS_MAP = {
1067
+ PENDING: "pending",
1068
+ CREATED: "pending",
1069
+ PROCESSING: "processing",
1070
+ IN_PROGRESS: "processing",
1071
+ SUCCESS: "completed",
1072
+ COMPLETED: "completed",
1073
+ FILLED: "completed",
1074
+ FAILED: "failed",
1075
+ REFUNDED: "refunded",
1076
+ EXPIRED: "expired"
1077
+ };
1078
+ var NATIVE_ASSET_IDS = {
1079
+ solana: [
1080
+ "sol",
1081
+ "So11111111111111111111111111111111111111112"
1082
+ ],
1083
+ aptos: ["0xa", "0x1::aptos_coin::AptosCoin"],
1084
+ near: ["near", "wrap.near"],
1085
+ tron: ["trx"],
1086
+ btc: ["btc", "bitcoin"],
1087
+ zcash: ["zec", "zcash", "nep141:zec.omft.near"],
1088
+ sui: ["0x2::sui::SUI"]
1089
+ };
1090
+ function normalizeHistory(raw) {
1091
+ const parsed = historyPageSchema.safeParse(raw);
1092
+ if (!parsed.success) {
1093
+ throw new SwapSdkError(
1094
+ "INVALID_API_RESPONSE",
1095
+ "history",
1096
+ "Invalid swap history response",
1097
+ {
1098
+ details: {
1099
+ issues: parsed.error.issues.map((issue) => ({
1100
+ path: issue.path.join("."),
1101
+ message: issue.message
1102
+ }))
1103
+ }
1104
+ }
1105
+ );
1106
+ }
1107
+ return {
1108
+ items: raw.record_list.map(normalizeHistoryItem),
1109
+ page: raw.page_number,
1110
+ pageSize: raw.page_size,
1111
+ totalPages: raw.total_page,
1112
+ totalItems: raw.total_size
1113
+ };
1114
+ }
1115
+ function normalizeHistoryStatus(status) {
1116
+ if (typeof status !== "string") return "unknown";
1117
+ return HISTORY_STATUS_MAP[status.trim().toUpperCase()] ?? "unknown";
1118
+ }
1119
+ function normalizeHistoryItem(raw) {
1120
+ const fromChain = fromApiChain(raw.from_chain);
1121
+ const toChain = fromApiChain(raw.to_chain);
1122
+ const createdAt = normalizeTimestamp(raw.created_at);
1123
+ const updatedAt = normalizeTimestamp(raw.updated_at);
1124
+ return {
1125
+ id: String(raw.id),
1126
+ sender: raw.sender,
1127
+ ...typeof raw.recipient === "string" && raw.recipient ? { recipient: raw.recipient } : {},
1128
+ fromChain,
1129
+ toChain,
1130
+ tokenIn: normalizeHistoryAsset(fromChain, raw.from_token),
1131
+ tokenOut: normalizeHistoryAsset(toChain, raw.to_token),
1132
+ ...raw.amount_in !== void 0 ? { amountIn: raw.amount_in } : {},
1133
+ ...raw.estimated_out !== void 0 ? { estimatedOut: raw.estimated_out } : {},
1134
+ ...raw.actual_out !== void 0 && raw.actual_out !== null ? { actualOut: raw.actual_out } : {},
1135
+ ...raw.from_hash ? { sourceTxHash: raw.from_hash } : {},
1136
+ ...raw.to_hash ? { destinationTxHash: raw.to_hash } : {},
1137
+ ...raw.swap_id ? { orderId: raw.swap_id } : {},
1138
+ ...raw.deposit_address ? { depositAddress: raw.deposit_address } : {},
1139
+ ...raw.router ? { router: raw.router } : {},
1140
+ status: normalizeHistoryStatus(raw.status),
1141
+ ...createdAt ? { createdAt } : {},
1142
+ ...updatedAt ? { updatedAt } : {},
1143
+ ...raw.status_response ? { statusResponse: raw.status_response } : {},
1144
+ raw
1145
+ };
1146
+ }
1147
+ function normalizeHistoryAsset(chain, address) {
1148
+ return {
1149
+ chain,
1150
+ address,
1151
+ ...isNativeAsset(chain, address) ? { isNative: true } : {}
1152
+ };
1153
+ }
1154
+ function isNativeAsset(chain, address) {
1155
+ const normalized = address.trim().toLowerCase();
1156
+ if (/^[1-9]\d*$/.test(chain) && (normalized === "0x0000000000000000000000000000000000000000" || normalized === "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee")) {
1157
+ return true;
1158
+ }
1159
+ return (NATIVE_ASSET_IDS[chain] ?? []).some(
1160
+ (candidate) => candidate.toLowerCase() === normalized
1161
+ );
1162
+ }
1163
+ function normalizeTimestamp(value) {
1164
+ if (!value?.trim()) return void 0;
1165
+ const trimmed = value.trim();
1166
+ const normalized = /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}(?:\.\d+)?$/.test(
1167
+ trimmed
1168
+ ) ? `${trimmed.replace(" ", "T")}Z` : trimmed;
1169
+ const date = new Date(normalized);
1170
+ return Number.isNaN(date.getTime()) ? void 0 : date.toISOString();
1171
+ }
1172
+
1173
+ // src/mca/quote.ts
1174
+ function serializeMcaQuoteRequest(request, signer) {
1175
+ const mcaAccountId = request.mcaAccountId.trim();
1176
+ if (!mcaAccountId) {
1177
+ throw invalidRequest("mcaAccountId is required");
1178
+ }
1179
+ if (signer.chain !== request.signerChain) {
1180
+ throw invalidRequest(
1181
+ `Resolved signer chain ${signer.chain} does not match requested signer chain ${request.signerChain}`
1182
+ );
1183
+ }
1184
+ const identityKey = signer.identityKey.trim();
1185
+ if (!identityKey) {
1186
+ throw invalidRequest("signer identityKey is required");
1187
+ }
1188
+ if (request.flow === "withdraw" && !/^(?:0|[1-9]\d*)(?:\.\d+)?$/.test(
1189
+ request.collateral.decreaseAmountBurrow.trim()
1190
+ )) {
1191
+ throw invalidRequest(
1192
+ "collateral.decreaseAmountBurrow must be a non-negative decimal string"
1193
+ );
1194
+ }
1195
+ const mca = {
1196
+ flow: request.flow,
1197
+ mcaAccountId,
1198
+ signer: {
1199
+ chain: signer.chain,
1200
+ identityKey
1201
+ },
1202
+ ...request.flow === "deposit" ? { useAsCollateral: request.collateral.useAsCollateral } : {
1203
+ needDecreaseCollateral: request.collateral.needDecrease,
1204
+ decreaseCollateralAmountBurrow: request.collateral.decreaseAmountBurrow,
1205
+ ...request.collateral.withdrawAll ? { withdrawAll: true } : {}
1206
+ },
1207
+ ...request.recipientMsgSignatures ? { recipientMsgSignatures: [...request.recipientMsgSignatures] } : {},
1208
+ ...request.depositSignerProofSignatures ? {
1209
+ depositSignerProofSignatures: [
1210
+ ...request.depositSignerProofSignatures
1211
+ ]
1212
+ } : {}
1213
+ };
1214
+ return {
1215
+ ...serializeQuoteRequest(request),
1216
+ mca
1217
+ };
1218
+ }
1219
+ function normalizeMcaQuote(request, signer, quote) {
1220
+ const mca = serializeMcaQuoteRequest(request, signer).mca;
1221
+ const base = {
1222
+ ...quote,
1223
+ flow: request.flow,
1224
+ mcaAccountId: request.mcaAccountId.trim(),
1225
+ signer: Object.freeze({
1226
+ ...signer,
1227
+ identityKey: signer.identityKey.trim()
1228
+ }),
1229
+ request,
1230
+ mca: Object.freeze({ ...mca })
1231
+ };
1232
+ if (request.flow === "deposit") {
1233
+ if (readString(quote.raw.nearDepositTxError)) {
1234
+ throw invalidResponse(String(quote.raw.nearDepositTxError));
1235
+ }
1236
+ return {
1237
+ ...base,
1238
+ flow: "deposit",
1239
+ executionMode: "deposit",
1240
+ request,
1241
+ ...quote.raw.nearDepositTx === void 0 ? {} : { nearDepositTx: quote.raw.nearDepositTx }
1242
+ };
1243
+ }
1244
+ if (readString(quote.raw.nearMcaWithdrawTxError)) {
1245
+ throw invalidResponse(String(quote.raw.nearMcaWithdrawTxError));
1246
+ }
1247
+ const mode = resolveWithdrawMode(request);
1248
+ const preview = mode === "withdraw-near" ? quote.raw.nearMcaWithdrawTx ?? quote.raw.mcaWithdrawToIntents : quote.raw.mcaWithdrawToIntents;
1249
+ if (!isPlainObject(preview)) {
1250
+ throw invalidResponse(
1251
+ mode === "withdraw-near" ? "MCA withdraw quote is missing nearMcaWithdrawTx" : "MCA withdraw quote is missing mcaWithdrawToIntents"
1252
+ );
1253
+ }
1254
+ return {
1255
+ ...base,
1256
+ flow: "withdraw",
1257
+ executionMode: mode,
1258
+ request,
1259
+ preview
1260
+ };
1261
+ }
1262
+ function resolveWithdrawMode(request) {
1263
+ if (request.executionPreference === "near") return "withdraw-near";
1264
+ if (request.executionPreference === "relayer") return "withdraw-relayer";
1265
+ const recipient = request.recipient?.trim();
1266
+ const boundNearAccountId = request.boundNearAccountId?.trim();
1267
+ return request.toChain === "near" && Boolean(recipient) && recipient === boundNearAccountId ? "withdraw-near" : "withdraw-relayer";
1268
+ }
1269
+ function isPlainObject(value) {
1270
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1271
+ }
1272
+ function readString(value) {
1273
+ return typeof value === "string" && value.trim() ? value.trim() : void 0;
1274
+ }
1275
+ function invalidRequest(message) {
1276
+ return new SwapSdkError("INVALID_REQUEST", "quote", message);
1277
+ }
1278
+ function invalidResponse(message) {
1279
+ return new SwapSdkError("INVALID_API_RESPONSE", "quote", message);
1280
+ }
1281
+
1282
+ // src/mca/signers.ts
1283
+ var DEFAULT_MCA_SIGNER_PRIORITY = [
1284
+ "evm",
1285
+ "solana",
1286
+ "btc",
1287
+ "aptos",
1288
+ "near",
1289
+ "zcash",
1290
+ "sui",
1291
+ "tron"
1292
+ ];
1293
+ var WALLET_KEYS = {
1294
+ evm: "EVM",
1295
+ solana: "Solana",
1296
+ btc: "Bitcoin",
1297
+ near: "Near",
1298
+ aptos: "Aptos",
1299
+ sui: "Sui",
1300
+ zcash: "Zcash",
1301
+ tron: "Tron"
10
1302
  };
11
- function getLogLevel() {
12
- if (typeof process !== "undefined" && process.env?.LOG_LEVEL) {
13
- const level = process.env.LOG_LEVEL.toLowerCase();
14
- if (LOG_LEVELS[level] !== void 0) {
15
- return level;
1303
+ function formatMcaWallet(chain, identityKey) {
1304
+ const identity = identityKey.trim();
1305
+ if (!identity) {
1306
+ throw new SwapSdkError(
1307
+ "INVALID_REQUEST",
1308
+ "sign",
1309
+ "MCA signer identityKey is required"
1310
+ );
1311
+ }
1312
+ return {
1313
+ [WALLET_KEYS[chain]]: chain === "evm" ? identity.replace(/^0x/i, "") : identity
1314
+ };
1315
+ }
1316
+ function selectMcaSigner(boundWallets, connectedSigners, priority = DEFAULT_MCA_SIGNER_PRIORITY) {
1317
+ for (const chain of priority) {
1318
+ const key = WALLET_KEYS[chain];
1319
+ const boundValues = boundWallets.flatMap((wallet) => {
1320
+ const value = wallet[key];
1321
+ return typeof value === "string" && value.trim() ? [value.trim()] : [];
1322
+ });
1323
+ if (boundValues.length === 0) continue;
1324
+ for (const signer of connectedSigners) {
1325
+ if (signer.chain !== chain) continue;
1326
+ const candidates = [signer.identityKey, signer.accountId].filter((value) => Boolean(value?.trim())).map((value) => normalizeIdentity(chain, value));
1327
+ if (boundValues.some(
1328
+ (bound) => candidates.includes(normalizeIdentity(chain, bound))
1329
+ )) {
1330
+ return signer;
1331
+ }
16
1332
  }
17
1333
  }
18
- return typeof process !== "undefined" && process.env?.NODE_ENV === "production" ? "warn" : "debug";
1334
+ return void 0;
19
1335
  }
20
- var currentLogLevel = getLogLevel();
21
- var currentLevelValue = LOG_LEVELS[currentLogLevel];
22
- function shouldLog(level) {
23
- return LOG_LEVELS[level] <= currentLevelValue;
1336
+ function isSameMcaSignerIdentity(a, b) {
1337
+ return a.chain === b.chain && normalizeIdentity(a.chain, a.identityKey) === normalizeIdentity(b.chain, b.identityKey);
24
1338
  }
25
- var logger = {
26
- debug: (...args) => {
27
- if (shouldLog("debug")) {
28
- console.debug(...args);
29
- }
30
- },
31
- info: (...args) => {
32
- if (shouldLog("info")) {
33
- console.info(...args);
1339
+ function normalizeIdentity(chain, value) {
1340
+ const trimmed = value.trim();
1341
+ if (chain === "evm") return trimmed.replace(/^0x/i, "").toLowerCase();
1342
+ if (chain === "sui" || chain === "aptos") return trimmed.toLowerCase();
1343
+ return trimmed;
1344
+ }
1345
+
1346
+ // src/utils/units.ts
1347
+ var HUMAN_AMOUNT = /^(0|[1-9]\d*)(?:\.(\d+))?$/;
1348
+ var MAX_DECIMALS = 255;
1349
+ function parseUnits(value, decimals) {
1350
+ assertDecimals(decimals);
1351
+ const match = HUMAN_AMOUNT.exec(value);
1352
+ if (!match) {
1353
+ throw invalid(`Invalid human-readable amount: ${value}`);
1354
+ }
1355
+ const whole = match[1];
1356
+ const fraction = match[2] ?? "";
1357
+ if (fraction.length > decimals) {
1358
+ throw invalid(
1359
+ `Amount has ${fraction.length} fractional digits but token supports ${decimals}`
1360
+ );
1361
+ }
1362
+ const combined = `${whole}${fraction.padEnd(decimals, "0")}`;
1363
+ return combined.replace(/^0+(?=\d)/, "") || "0";
1364
+ }
1365
+ function formatUnits(value, decimals) {
1366
+ assertDecimals(decimals);
1367
+ const amount = assertBaseUnitAmount(value);
1368
+ if (decimals === 0) return amount;
1369
+ const padded = amount.padStart(decimals + 1, "0");
1370
+ const whole = padded.slice(0, -decimals);
1371
+ const fraction = padded.slice(-decimals).replace(/0+$/, "");
1372
+ return fraction ? `${whole}.${fraction}` : whole;
1373
+ }
1374
+ function assertDecimals(decimals) {
1375
+ if (!Number.isSafeInteger(decimals) || decimals < 0 || decimals > MAX_DECIMALS) {
1376
+ throw invalid(`Invalid token decimals: ${String(decimals)}`);
1377
+ }
1378
+ }
1379
+ function invalid(message) {
1380
+ return new SwapSdkError("INVALID_REQUEST", "quote", message);
1381
+ }
1382
+
1383
+ // src/mca/withdraw.ts
1384
+ function extractMcaWithdrawBusiness(preview) {
1385
+ if (!isPlainObject2(preview)) return void 0;
1386
+ if (isPlainObject2(preview.business)) return cloneObject(preview.business);
1387
+ return extractPreviewField(preview, "business");
1388
+ }
1389
+ function extractMcaWithdrawSignerWallet(preview) {
1390
+ if (!isPlainObject2(preview)) return void 0;
1391
+ if (isPlainObject2(preview.signer_wallet)) {
1392
+ return cloneObject(preview.signer_wallet);
1393
+ }
1394
+ return extractPreviewField(preview, "signer_wallet");
1395
+ }
1396
+ function extractMcaWithdrawDepositAddress(input) {
1397
+ return pickString(input.snapshotDepositAddress) || pickString(input.storeDepositAddress) || extractDepositAddressFromObject(input.preview) || extractDepositAddressFromObject(input.bestQuote);
1398
+ }
1399
+ function buildNearMcaWithdrawTransactions(preview, input) {
1400
+ if (!isPlainObject2(preview)) {
1401
+ throw invalidPreview("MCA withdraw preview must be an object");
1402
+ }
1403
+ const fallbackAccount = input.mcaAccountId.trim();
1404
+ const executionArgs = {
1405
+ business: cloneObject(input.business),
1406
+ signer_wallet: cloneObject(input.signerWallet),
1407
+ signature: input.signature ?? ""
1408
+ };
1409
+ const transactions = Array.isArray(preview.transactions) ? preview.transactions : [];
1410
+ const mapped = transactions.flatMap((value) => {
1411
+ if (!isPlainObject2(value)) return [];
1412
+ const receiverId = pickString(value.contractId) || fallbackAccount;
1413
+ if (!receiverId) return [];
1414
+ const methodName = pickString(value.methodName) || "exec";
1415
+ const existingArgs = isPlainObject2(value.args) ? cloneObject(value.args) : {};
1416
+ return [
1417
+ {
1418
+ receiverId,
1419
+ actions: [
1420
+ {
1421
+ type: "FunctionCall",
1422
+ params: {
1423
+ methodName,
1424
+ args: { ...existingArgs, ...executionArgs },
1425
+ gas: normalizeGas(value.gas),
1426
+ deposit: normalizeDeposit2(value.deposit)
1427
+ }
1428
+ }
1429
+ ]
1430
+ }
1431
+ ];
1432
+ });
1433
+ if (mapped.length > 0) return mapped;
1434
+ if (!fallbackAccount) {
1435
+ throw invalidPreview("MCA withdraw preview is missing mcaAccountId");
1436
+ }
1437
+ return [
1438
+ {
1439
+ receiverId: fallbackAccount,
1440
+ actions: [
1441
+ {
1442
+ type: "FunctionCall",
1443
+ params: {
1444
+ methodName: "exec",
1445
+ args: executionArgs,
1446
+ gas: "300000000000000",
1447
+ deposit: "0"
1448
+ }
1449
+ }
1450
+ ]
34
1451
  }
35
- },
36
- warn: (...args) => {
37
- if (shouldLog("warn")) {
38
- console.warn(...args);
1452
+ ];
1453
+ }
1454
+ function buildMcaWithdrawRelayerRequest(input) {
1455
+ const mcaAccountId = input.mcaAccountId.trim();
1456
+ if (!mcaAccountId) {
1457
+ throw new SwapSdkError(
1458
+ "INVALID_REQUEST",
1459
+ "build",
1460
+ "mcaAccountId is required for an MCA relayer request"
1461
+ );
1462
+ }
1463
+ const recipient = pickString(input.quoteBuild.recipient) || pickString(input.recipientFallback);
1464
+ return {
1465
+ ...input.quoteBuild,
1466
+ ...recipient ? { recipient } : {},
1467
+ mcaRelayer: {
1468
+ ...input.mcaRelayer,
1469
+ wallet: cloneValue(input.mcaRelayer.wallet),
1470
+ business: cloneObject(input.mcaRelayer.business)
1471
+ },
1472
+ mca: {
1473
+ ...input.quoteBuild.mca ?? {},
1474
+ flow: input.quoteBuild.mca?.flow ?? input.quoteBuild.mca?.mcaFlow ?? "withdraw",
1475
+ mcaAccountId
1476
+ },
1477
+ deposit_address: input.depositAddress.trim(),
1478
+ is_cross_chain: input.isCrossChain,
1479
+ tx_type: "mca-withdraw-relayer",
1480
+ multi_addr: mcaAccountId
1481
+ };
1482
+ }
1483
+ function extractPreviewField(preview, field) {
1484
+ const transactions = preview.transactions;
1485
+ if (Array.isArray(transactions)) {
1486
+ for (const transaction of transactions) {
1487
+ if (!isPlainObject2(transaction) || !isPlainObject2(transaction.args)) {
1488
+ continue;
1489
+ }
1490
+ const value = parseObject(transaction.args[field]);
1491
+ if (value) return cloneObject(value);
39
1492
  }
40
- },
41
- error: (...args) => {
42
- if (shouldLog("error")) {
43
- console.error(...args);
1493
+ }
1494
+ const actions = preview.actions;
1495
+ if (Array.isArray(actions)) {
1496
+ for (const action of actions) {
1497
+ if (!isPlainObject2(action) || action.type !== "FunctionCall" || !isPlainObject2(action.params)) {
1498
+ continue;
1499
+ }
1500
+ const args = parseObject(action.params.args);
1501
+ if (!args) continue;
1502
+ const value = parseObject(args[field]);
1503
+ if (value) return cloneObject(value);
44
1504
  }
45
1505
  }
46
- };
47
-
48
- // src/utils/index.ts
49
- var bluechipTokensConfig = null;
50
- function setBluechipTokensConfig(config) {
51
- bluechipTokensConfig = config;
52
- }
53
- function getBluechipTokensConfig() {
54
- if (!bluechipTokensConfig) {
55
- logger.warn(
56
- "getBluechipTokensConfig - Bluechip tokens config not set, returning empty config"
57
- );
58
- return {};
1506
+ return void 0;
1507
+ }
1508
+ function extractDepositAddressFromObject(value) {
1509
+ if (!isPlainObject2(value)) return "";
1510
+ const direct = pickString(value.depositAddress) || pickString(value.deposit_address);
1511
+ if (direct) return direct;
1512
+ if (!isPlainObject2(value.deposit)) return "";
1513
+ return pickString(value.deposit.depositAddress) || pickString(value.deposit.deposit_address);
1514
+ }
1515
+ function parseObject(value) {
1516
+ if (isPlainObject2(value)) return value;
1517
+ if (typeof value !== "string" || !value.trim()) return void 0;
1518
+ try {
1519
+ const parsed = JSON.parse(value);
1520
+ return isPlainObject2(parsed) ? parsed : void 0;
1521
+ } catch {
1522
+ return void 0;
59
1523
  }
60
- return bluechipTokensConfig;
61
1524
  }
62
- function normalizeTokenId(tokenId, wrapNearContractId = "wrap.near") {
63
- if (!tokenId) {
64
- logger.error("normalizeTokenId - Empty tokenId:", tokenId);
65
- return "";
1525
+ function isPlainObject2(value) {
1526
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1527
+ }
1528
+ function pickString(value) {
1529
+ return typeof value === "string" && value.trim() ? value.trim() : "";
1530
+ }
1531
+ function normalizeGas(value) {
1532
+ if (typeof value === "number" && Number.isFinite(value) && value >= 0) {
1533
+ return BigInt(Math.trunc(value)) < 10000n ? (BigInt(Math.trunc(value)) * 1000000000000n).toString() : BigInt(Math.trunc(value)).toString();
66
1534
  }
67
- let normalized = tokenId.replace(/^nep141:/, "");
68
- if (normalized === "near") {
69
- normalized = wrapNearContractId;
1535
+ if (typeof value === "string" && /^\d+$/.test(value.trim())) {
1536
+ const gas = BigInt(value.trim());
1537
+ return gas < 10000n ? (gas * 1000000000000n).toString() : gas.toString();
70
1538
  }
71
- if (!normalized) {
72
- logger.error("normalizeTokenId - Result is empty:", {
73
- tokenId,
74
- normalized
75
- });
1539
+ return "300000000000000";
1540
+ }
1541
+ function normalizeDeposit2(value) {
1542
+ if (value === void 0 || value === null || value === "") return "0";
1543
+ const decimal = typeof value === "number" && Number.isFinite(value) && value >= 0 ? String(value) : typeof value === "string" ? value.trim() : "";
1544
+ if (!decimal) {
1545
+ throw invalidPreview("MCA withdraw transaction has an invalid NEAR deposit");
1546
+ }
1547
+ try {
1548
+ return parseUnits(decimal, 24);
1549
+ } catch (error) {
1550
+ throw new SwapSdkError(
1551
+ "INVALID_API_RESPONSE",
1552
+ "build",
1553
+ "MCA withdraw transaction has an invalid NEAR deposit",
1554
+ { cause: error }
1555
+ );
76
1556
  }
77
- return normalized;
78
1557
  }
79
- function isNearIntentsSupportedToken(token, bluechipTokens) {
80
- if (!token?.symbol || !token?.address) {
81
- return false;
1558
+ function cloneObject(value) {
1559
+ return cloneValue(value);
1560
+ }
1561
+ function cloneValue(value) {
1562
+ return JSON.parse(JSON.stringify(value));
1563
+ }
1564
+ function invalidPreview(message) {
1565
+ return new SwapSdkError("INVALID_API_RESPONSE", "build", message);
1566
+ }
1567
+
1568
+ // src/mca/McaSwapService.ts
1569
+ var McaSwapService = class {
1570
+ constructor(client, config) {
1571
+ this.client = client;
1572
+ this.relayerReports = /* @__PURE__ */ new Map();
1573
+ this.now = config.now ?? Date.now;
1574
+ this.maxQuoteAgeMs = config.maxQuoteAgeMs === void 0 ? 3e4 : config.maxQuoteAgeMs;
1575
+ this.reportMode = config.reportMode ?? "auto";
1576
+ this.onEvent = config.onEvent;
1577
+ this.resolveSignerIdentity = config.resolveSignerIdentity;
1578
+ this.resolveMessageSigner = config.resolveMessageSigner;
1579
+ this.buildStandardSwap = config.buildStandardSwap;
82
1580
  }
83
- const config = bluechipTokens || getBluechipTokensConfig();
84
- const normalizedSymbol = token.symbol.toUpperCase();
85
- const symbolKey = normalizedSymbol === "NEAR" || normalizedSymbol === "WNEAR" ? "NEAR" : normalizedSymbol;
86
- const tokenConfig = config[symbolKey];
87
- if (!tokenConfig) {
88
- return false;
1581
+ async quote(request, options = {}) {
1582
+ const signer = await this.readSignerIdentity(request.signerChain, "quote");
1583
+ const rawRequest = serializeMcaQuoteRequest(request, signer);
1584
+ const raw = await this.client.quoteRaw(rawRequest, options);
1585
+ const normalizationRequest = {
1586
+ ...request,
1587
+ extensions: {
1588
+ ...request.extensions ?? {},
1589
+ mca: rawRequest.mca
1590
+ }
1591
+ };
1592
+ const quote = normalizeQuote(normalizationRequest, raw, this.now());
1593
+ return normalizeMcaQuote(request, signer, quote);
89
1594
  }
90
- const normalizeAddress = (addr) => addr.replace(/^nep141:/, "").toLowerCase();
91
- const tokenAddress = normalizeAddress(token.address);
92
- const configAddress = normalizeAddress(tokenConfig.address || "");
93
- const configAssetId = tokenConfig.assetId ? normalizeAddress(tokenConfig.assetId) : "";
94
- return tokenAddress === configAddress || tokenAddress === configAssetId;
95
- }
96
- function findBestBluechipToken(bluechipTokens, wrapNearContractId = "wrap.near") {
97
- const preferredTokens = [];
98
- if (bluechipTokens.USDT?.address) {
99
- preferredTokens.push({
100
- address: bluechipTokens.USDT.address,
101
- symbol: "USDT",
102
- decimals: bluechipTokens.USDT.decimals || 6,
103
- chain: "near"
104
- });
1595
+ async build(input) {
1596
+ this.assertQuoteFresh(input.quote);
1597
+ if (input.quote.executionMode === "withdraw-relayer") {
1598
+ throw new SwapSdkError(
1599
+ "INVALID_REQUEST",
1600
+ "build",
1601
+ "MCA relayer withdraw requires a signature and must use swap()"
1602
+ );
1603
+ }
1604
+ const build = input.quote.executionMode === "deposit" ? await this.buildStandardSwap(input) : this.buildNearWithdraw(input.quote);
1605
+ return {
1606
+ ...build,
1607
+ reportContext: {
1608
+ ...build.reportContext,
1609
+ multiAddr: input.quote.mcaAccountId,
1610
+ ...input.quote.executionMode === "deposit" ? {
1611
+ txType: build.isCrossChain ? "cross-chain" : "same-chain"
1612
+ } : {}
1613
+ }
1614
+ };
105
1615
  }
106
- if (bluechipTokens.USDC?.address) {
107
- preferredTokens.push({
108
- address: bluechipTokens.USDC.address,
109
- symbol: "USDC",
110
- decimals: bluechipTokens.USDC.decimals || 6,
111
- chain: "near"
1616
+ async swap(input) {
1617
+ this.assertQuoteFresh(input.quote);
1618
+ if (input.quote.executionMode === "withdraw-relayer") {
1619
+ return this.executeRelayerWithdraw({ ...input, quote: input.quote });
1620
+ }
1621
+ const build = await this.build({
1622
+ quote: input.quote,
1623
+ signal: input.signal,
1624
+ idempotencyKey: input.idempotencyKey
112
1625
  });
113
- }
114
- if (bluechipTokens.NEAR?.address) {
115
- preferredTokens.push({
116
- address: bluechipTokens.NEAR.address,
117
- symbol: "wNEAR",
118
- decimals: bluechipTokens.NEAR.decimals || 24,
119
- chain: "near"
1626
+ const nearStatusKey = input.quote.executionMode === "withdraw-near" && input.waitFor === "completed" ? extractMcaWithdrawDepositAddress({
1627
+ preview: input.quote.preview,
1628
+ bestQuote: input.quote.raw.bestQuote
1629
+ }) : void 0;
1630
+ if (input.quote.executionMode === "withdraw-near" && input.waitFor === "completed" && !nearStatusKey) {
1631
+ throw new SwapSdkError(
1632
+ "INVALID_API_RESPONSE",
1633
+ "status",
1634
+ "MCA NEAR withdraw is missing a status deposit address"
1635
+ );
1636
+ }
1637
+ const result = await this.client.executeSwap({
1638
+ build,
1639
+ waitFor: input.quote.executionMode === "withdraw-near" && input.waitFor === "completed" ? "source-confirmed" : input.waitFor,
1640
+ signal: input.signal,
1641
+ onEvent: input.onEvent
120
1642
  });
1643
+ if (input.quote.executionMode === "withdraw-near" && input.waitFor === "completed") {
1644
+ const status = await this.client.waitForOrder({
1645
+ orderId: nearStatusKey,
1646
+ router: input.quote.route.router,
1647
+ signal: input.signal
1648
+ });
1649
+ this.emitEvent(
1650
+ {
1651
+ type: "order-status",
1652
+ executionId: result.executionId,
1653
+ status: status.status
1654
+ },
1655
+ input.onEvent
1656
+ );
1657
+ result.status = status.status === "unknown" || status.status === "pending" ? "processing" : status.status;
1658
+ if (status.status === "completed") {
1659
+ this.emitEvent(
1660
+ { type: "completed", executionId: result.executionId },
1661
+ input.onEvent
1662
+ );
1663
+ }
1664
+ }
1665
+ return result;
1666
+ }
1667
+ reportIfManaged(result) {
1668
+ const request = this.relayerReports.get(result.executionId);
1669
+ if (!request) return void 0;
1670
+ return this.client.reportRaw(request);
121
1671
  }
122
- if (preferredTokens.length === 0) {
123
- logger.warn(
124
- "findBestBluechipToken - No preferred tokens found, using wrap.near"
1672
+ buildNearWithdraw(quote) {
1673
+ const business = extractMcaWithdrawBusiness(quote.preview);
1674
+ if (!business) {
1675
+ throw new SwapSdkError(
1676
+ "INVALID_API_RESPONSE",
1677
+ "build",
1678
+ "MCA NEAR withdraw preview is missing business"
1679
+ );
1680
+ }
1681
+ const recipient = quote.request.recipient?.trim();
1682
+ const signerWallet = extractMcaWithdrawSignerWallet(quote.preview) ?? (recipient ? formatMcaWallet("near", recipient) : void 0);
1683
+ if (!signerWallet) {
1684
+ throw new SwapSdkError(
1685
+ "INVALID_REQUEST",
1686
+ "build",
1687
+ "MCA NEAR withdraw requires a NEAR recipient or signer_wallet"
1688
+ );
1689
+ }
1690
+ const transactions = buildNearMcaWithdrawTransactions(quote.preview, {
1691
+ business,
1692
+ signerWallet,
1693
+ signature: "",
1694
+ mcaAccountId: quote.mcaAccountId
1695
+ });
1696
+ const request = buildRequestFromQuote(quote);
1697
+ const depositAddress = extractMcaWithdrawDepositAddress({
1698
+ preview: quote.preview,
1699
+ bestQuote: quote.raw.bestQuote
1700
+ });
1701
+ const build = normalizeBuild(
1702
+ {
1703
+ isCrossChain: true,
1704
+ chainType: "near",
1705
+ router: quote.route.router,
1706
+ fromChain: request.fromChain,
1707
+ toChain: request.toChain,
1708
+ tokenIn: {
1709
+ address: request.tokenIn,
1710
+ symbol: quote.tokenIn.symbol ?? "",
1711
+ decimals: quote.tokenIn.decimals ?? 0
1712
+ },
1713
+ tokenOut: {
1714
+ address: request.tokenOut,
1715
+ symbol: quote.tokenOut.symbol ?? "",
1716
+ decimals: quote.tokenOut.decimals ?? 0
1717
+ },
1718
+ amountIn: quote.amountIn,
1719
+ estimatedOut: quote.estimatedOut,
1720
+ minAmountOut: quote.minAmountOut,
1721
+ tx: transactions,
1722
+ approve: null,
1723
+ ...depositAddress ? { deposit: { depositAddress } } : {}
1724
+ },
1725
+ void 0,
1726
+ request
125
1727
  );
126
1728
  return {
127
- address: wrapNearContractId,
128
- symbol: "wNEAR",
129
- decimals: 24,
130
- chain: "near"
1729
+ ...build,
1730
+ reportContext: {
1731
+ txType: "mca-withdraw-near",
1732
+ multiAddr: quote.mcaAccountId,
1733
+ ...depositAddress ? { depositAddress } : {},
1734
+ ...recipient ? { recipient } : {},
1735
+ isCrossChain: true
1736
+ }
131
1737
  };
132
1738
  }
133
- logger.debug("findBestBluechipToken - Selected token:", preferredTokens[0]);
134
- return preferredTokens[0];
135
- }
136
- function convertSlippageToBasisPoints(slippage) {
137
- if (slippage >= 1) {
138
- return Math.round(slippage);
1739
+ async executeRelayerWithdraw(input) {
1740
+ const executionId = createExecutionId();
1741
+ const emit = (event) => this.emitEvent(event, input.onEvent);
1742
+ try {
1743
+ const signer = this.resolveMessageSigner(input.quote.signer.chain);
1744
+ const currentSigner = await this.readSignerIdentity(
1745
+ input.quote.signer.chain,
1746
+ "sign",
1747
+ signer
1748
+ );
1749
+ assertSignerMatchesQuote(currentSigner, input.quote.signer);
1750
+ const business = extractMcaWithdrawBusiness(input.quote.preview);
1751
+ if (!business) {
1752
+ throw new SwapSdkError(
1753
+ "INVALID_API_RESPONSE",
1754
+ "sign",
1755
+ "MCA relayer preview is missing business"
1756
+ );
1757
+ }
1758
+ const message = readString2(input.quote.preview.messageToSign);
1759
+ if (!message) {
1760
+ throw new SwapSdkError(
1761
+ "INVALID_API_RESPONSE",
1762
+ "sign",
1763
+ "MCA relayer preview is missing messageToSign"
1764
+ );
1765
+ }
1766
+ const depositAddress = extractMcaWithdrawDepositAddress({
1767
+ snapshotDepositAddress: readString2(input.quote.raw.depositAddress),
1768
+ preview: input.quote.preview,
1769
+ bestQuote: input.quote.raw.bestQuote
1770
+ });
1771
+ if (!depositAddress) {
1772
+ throw new SwapSdkError(
1773
+ "INVALID_API_RESPONSE",
1774
+ "build",
1775
+ "MCA relayer preview is missing a deposit address"
1776
+ );
1777
+ }
1778
+ emit({ type: "signing-requested", executionId });
1779
+ await input.beforeSign?.({
1780
+ chain: currentSigner.chain,
1781
+ identityKey: currentSigner.identityKey,
1782
+ message,
1783
+ business
1784
+ });
1785
+ let signature;
1786
+ try {
1787
+ signature = (await signer.signMessage(message, {
1788
+ signal: input.signal,
1789
+ context: {
1790
+ flow: "withdraw",
1791
+ mcaAccountId: input.quote.mcaAccountId,
1792
+ business
1793
+ }
1794
+ })).trim();
1795
+ } catch (error) {
1796
+ if (error instanceof SwapSdkError) throw error;
1797
+ throw new SwapSdkError(
1798
+ "SIGNING_FAILED",
1799
+ "sign",
1800
+ "Failed to sign the MCA relayer message",
1801
+ { cause: error }
1802
+ );
1803
+ }
1804
+ if (!signature) {
1805
+ throw new SwapSdkError(
1806
+ "SIGNING_FAILED",
1807
+ "sign",
1808
+ "MCA signer returned an empty signature"
1809
+ );
1810
+ }
1811
+ const mcaRelayer = {
1812
+ mcaAccountId: input.quote.mcaAccountId,
1813
+ wallet: formatMcaWallet(
1814
+ currentSigner.chain,
1815
+ currentSigner.identityKey
1816
+ ),
1817
+ business,
1818
+ signature
1819
+ };
1820
+ const request = buildMcaWithdrawRelayerRequest({
1821
+ quoteBuild: buildRequestFromQuote(input.quote),
1822
+ mcaRelayer,
1823
+ isCrossChain: input.quote.raw.isCrossChain ?? true,
1824
+ depositAddress,
1825
+ mcaAccountId: input.quote.mcaAccountId,
1826
+ recipientFallback: input.quote.request.recipient
1827
+ });
1828
+ const raw = await this.client.buildRaw(request, {
1829
+ signal: input.signal,
1830
+ idempotencyKey: input.idempotencyKey
1831
+ });
1832
+ const orderId = readString2(raw.orderId) ?? readRecordString2(raw.deposit, "orderId");
1833
+ const router = readString2(raw.router) ?? input.quote.route.router;
1834
+ const submittedDepositAddress = readRecordString2(raw.deposit, "depositAddress") ?? depositAddress;
1835
+ if (!orderId || !router) {
1836
+ throw new SwapSdkError(
1837
+ "INVALID_API_RESPONSE",
1838
+ "submit",
1839
+ "MCA relayer submission is missing orderId or router"
1840
+ );
1841
+ }
1842
+ const reportRequest = {
1843
+ sender: input.quote.request.sender,
1844
+ recipient: input.quote.request.recipient ?? input.quote.request.sender,
1845
+ from_hash: orderId,
1846
+ from_token: request.tokenIn,
1847
+ to_token: request.tokenOut,
1848
+ deposit_address: submittedDepositAddress,
1849
+ from_chain: request.fromChain,
1850
+ to_chain: request.toChain,
1851
+ amount_in: request.amountIn,
1852
+ estimated_out: input.quote.estimatedOut,
1853
+ router,
1854
+ is_cross_chain: true,
1855
+ tx_type: "mca-withdraw-relayer",
1856
+ multi_addr: input.quote.mcaAccountId,
1857
+ swapId: orderId
1858
+ };
1859
+ this.relayerReports.set(executionId, reportRequest);
1860
+ const result = {
1861
+ executionId,
1862
+ status: "submitted",
1863
+ router,
1864
+ orderId,
1865
+ depositAddress: submittedDepositAddress,
1866
+ report: { status: "skipped" },
1867
+ raw
1868
+ };
1869
+ emit({ type: "submitted", executionId, orderId });
1870
+ if (this.reportMode === "auto") {
1871
+ try {
1872
+ await this.client.reportRaw(reportRequest, { signal: input.signal });
1873
+ result.report = { status: "reported" };
1874
+ } catch (error) {
1875
+ const warning = {
1876
+ code: "REPORT_FAILED",
1877
+ message: "MCA withdraw submitted but report failed",
1878
+ cause: error
1879
+ };
1880
+ result.report = { status: "failed", warning };
1881
+ emit({ type: "warning", executionId, warning });
1882
+ }
1883
+ }
1884
+ if (input.waitFor === "completed") {
1885
+ const status = await this.client.waitForOrder({
1886
+ orderId,
1887
+ router,
1888
+ signal: input.signal
1889
+ });
1890
+ emit({ type: "order-status", executionId, status: status.status });
1891
+ result.status = status.status === "unknown" || status.status === "pending" ? "processing" : status.status;
1892
+ if (status.status === "completed") {
1893
+ emit({ type: "completed", executionId });
1894
+ }
1895
+ }
1896
+ return result;
1897
+ } catch (error) {
1898
+ const sdkError = asSwapSdkError(error, "submit");
1899
+ emit({ type: "failed", executionId, error: sdkError });
1900
+ throw sdkError;
1901
+ }
139
1902
  }
140
- if (slippage > 0 && slippage < 0.01) {
141
- return Math.round(slippage * 1e4);
1903
+ async readSignerIdentity(chain, stage, provider = this.resolveSignerIdentity(chain)) {
1904
+ let identityKey;
1905
+ try {
1906
+ identityKey = (await provider.getIdentityKey()).trim();
1907
+ } catch (error) {
1908
+ if (error instanceof SwapSdkError) throw error;
1909
+ throw new SwapSdkError(
1910
+ "SIGNING_FAILED",
1911
+ stage,
1912
+ "Failed to read the MCA signer identity",
1913
+ { cause: error }
1914
+ );
1915
+ }
1916
+ if (!identityKey) {
1917
+ throw new SwapSdkError(
1918
+ "SIGNING_FAILED",
1919
+ stage,
1920
+ "MCA executor returned an empty signer identity"
1921
+ );
1922
+ }
1923
+ return { chain, identityKey };
142
1924
  }
143
- if (slippage >= 0.01 && slippage < 1) {
144
- return Math.round(slippage * 100);
1925
+ emitEvent(event, local) {
1926
+ this.onEvent?.(event);
1927
+ if (local !== this.onEvent) local?.(event);
145
1928
  }
146
- return Math.round(slippage);
147
- }
148
- function normalizeDestinationAsset(assetId, wrapNearContractId = "wrap.near") {
149
- if (!assetId) return assetId;
150
- if (assetId.startsWith("nep141:") || assetId.startsWith("nep245:")) {
151
- return assetId;
1929
+ assertQuoteFresh(quote) {
1930
+ const now = this.now();
1931
+ const expiredByApi = quote.expiresAt !== void 0 && now > quote.expiresAt;
1932
+ const expiredByAge = this.maxQuoteAgeMs !== null && now - quote.receivedAt > Math.max(0, this.maxQuoteAgeMs);
1933
+ if (expiredByApi || expiredByAge) {
1934
+ throw new SwapSdkError(
1935
+ "QUOTE_EXPIRED",
1936
+ "build",
1937
+ "Quote has expired; request a fresh quote"
1938
+ );
1939
+ }
152
1940
  }
153
- if (assetId === "near" || assetId === "nep141:near") {
154
- return `nep141:${wrapNearContractId}`;
1941
+ };
1942
+ function buildRequestFromQuote(quote) {
1943
+ const context = quote.buildContext;
1944
+ return {
1945
+ ...context.request,
1946
+ router: context.router,
1947
+ ...context.market ? { market: context.market } : {},
1948
+ expectedOut: context.expectedOut,
1949
+ minAmountOut: context.minAmountOut,
1950
+ preSwap: context.preSwap,
1951
+ bridge: context.bridge,
1952
+ ...context.quoteId ? { quoteId: context.quoteId } : {}
1953
+ };
1954
+ }
1955
+ function assertSignerMatchesQuote(signer, expected) {
1956
+ if (!isSameMcaSignerIdentity(signer, expected)) {
1957
+ throw new SwapSdkError(
1958
+ "SIGNING_FAILED",
1959
+ "sign",
1960
+ "MCA signer does not match the signer used for the quote"
1961
+ );
155
1962
  }
156
- if (assetId.includes(".")) {
157
- return `nep141:${normalizeTokenId(assetId, wrapNearContractId)}`;
1963
+ }
1964
+ function readString2(value) {
1965
+ return typeof value === "string" && value.trim() ? value.trim() : void 0;
1966
+ }
1967
+ function readRecordString2(value, field) {
1968
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
1969
+ return void 0;
158
1970
  }
159
- return assetId;
1971
+ return readString2(value[field]);
160
1972
  }
161
- var NearSmartRouter = class {
1973
+
1974
+ // src/client/SwapClient.ts
1975
+ var SwapClient = class {
162
1976
  constructor(config) {
163
- this.findPathAdapter = config.findPathAdapter;
164
- this.swapMultiDexPathAdapter = config.swapMultiDexPathAdapter;
165
- this.nearChainAdapter = config.nearChainAdapter;
166
- this.configAdapter = config.configAdapter;
167
- this.intentsQuotationAdapter = config.intentsQuotationAdapter;
168
- this.wrapNearContractId = this.configAdapter.getWrapNearContractId();
169
- this.refExchangeId = this.configAdapter.getRefExchangeId();
170
- this.tokenStorageDepositRead = this.configAdapter.getTokenStorageDepositRead?.() || "1250000000000000000000";
171
- this.aggregateDexContractId = this.configAdapter.getAggregateDexContractId?.() || void 0;
172
- }
173
- /**
174
- * 核心报价逻辑:并行比价 -> 获取 Intent 地址 -> SmartX 二次修正
175
- */
176
- async quote(params) {
1977
+ this.inFlight = /* @__PURE__ */ new Set();
1978
+ this.reportRequests = /* @__PURE__ */ new Map();
1979
+ this.config = config;
1980
+ this.api = new ApiClient(config);
1981
+ this.registry = new ExecutorRegistry(config.executors ?? []);
1982
+ this.reportMode = config.reportMode ?? "auto";
1983
+ this.now = config.now ?? Date.now;
1984
+ this.managedSwapFlow = new McaSwapService(this, {
1985
+ now: this.now,
1986
+ maxQuoteAgeMs: config.maxQuoteAgeMs,
1987
+ reportMode: this.reportMode,
1988
+ resolveSignerIdentity: (chain) => this.registry.getSigner(chain),
1989
+ resolveMessageSigner: (chain) => this.registry.getSigner(chain, true),
1990
+ buildStandardSwap: (input) => this.buildStandardSwap(input),
1991
+ ...config.onEvent ? { onEvent: config.onEvent } : {}
1992
+ });
1993
+ }
1994
+ quoteRaw(request, options = {}) {
1995
+ return this.api.quote(request, options);
1996
+ }
1997
+ async quote(request, options = {}) {
1998
+ if (isMcaQuoteRequest(request)) {
1999
+ return this.managedSwapFlow.quote(request, options);
2000
+ }
2001
+ return this.quoteStandard(request, options);
2002
+ }
2003
+ async quoteStandard(request, options = {}) {
2004
+ const rawRequest = serializeQuoteRequest(request);
2005
+ const raw = await this.api.quote(rawRequest, options);
2006
+ return normalizeQuote(request, raw, this.now());
2007
+ }
2008
+ buildRaw(request, options = {}) {
2009
+ return this.api.build(request, options);
2010
+ }
2011
+ async buildSwap(input) {
2012
+ if (isMcaQuote(input.quote)) {
2013
+ return this.managedSwapFlow.build({
2014
+ quote: input.quote,
2015
+ signal: input.signal,
2016
+ idempotencyKey: input.idempotencyKey
2017
+ });
2018
+ }
2019
+ return this.buildStandardSwap(input);
2020
+ }
2021
+ async buildStandardSwap(input) {
2022
+ this.assertQuoteFresh(input.quote);
2023
+ const executionId = createExecutionId();
2024
+ this.emit({ type: "build-started", executionId });
2025
+ const context = input.quote.buildContext;
2026
+ const request = {
2027
+ ...context.request,
2028
+ router: context.router,
2029
+ ...context.market ? { market: context.market } : {},
2030
+ expectedOut: context.expectedOut,
2031
+ minAmountOut: context.minAmountOut,
2032
+ preSwap: context.preSwap,
2033
+ bridge: context.bridge,
2034
+ ...context.quoteId ? { quoteId: context.quoteId } : {}
2035
+ };
2036
+ const raw = await this.api.build(request, {
2037
+ signal: input.signal,
2038
+ idempotencyKey: input.idempotencyKey
2039
+ });
2040
+ const build = normalizeBuild(raw, executionId, request);
2041
+ this.emit({ type: "build-completed", executionId });
2042
+ return build;
2043
+ }
2044
+ async executeSwap(input) {
2045
+ const { build } = input;
2046
+ if (this.inFlight.has(build.executionId)) {
2047
+ throw new SwapSdkError(
2048
+ "INVALID_REQUEST",
2049
+ "sign",
2050
+ `Execution ${build.executionId} is already in progress`
2051
+ );
2052
+ }
2053
+ this.inFlight.add(build.executionId);
2054
+ const emit = (event) => {
2055
+ this.emit(event);
2056
+ if (input.onEvent !== this.config.onEvent) input.onEvent?.(event);
2057
+ };
177
2058
  try {
178
- const { tokenIn, tokenOut, amountIn, slippage, recipient, refundTo } = params;
179
- if (!tokenIn?.address || !tokenOut?.address) {
180
- throw new Error("Missing token address");
181
- }
182
- const normalizedTokenIn = normalizeTokenId(tokenIn.address, this.wrapNearContractId);
183
- const normalizedTokenOut = normalizeTokenId(tokenOut.address, this.wrapNearContractId);
184
- const currentUser = refundTo || "";
185
- const slippageBps = convertSlippageToBasisPoints(slippage);
186
- const slippageDecimal = slippageBps / 1e4;
187
- const [findPathResp, smartxInitialResp] = await Promise.all([
188
- this.findPathAdapter.findPath({
189
- tokenIn: normalizedTokenIn,
190
- tokenOut: normalizedTokenOut,
191
- amountIn: String(amountIn),
192
- slippage: slippageDecimal,
193
- supportLedger: false
194
- }),
195
- this.swapMultiDexPathAdapter ? this.swapMultiDexPathAdapter.swapMultiDexPath({
196
- amountIn: String(amountIn),
197
- tokenIn: normalizedTokenIn,
198
- tokenOut: normalizedTokenOut,
199
- slippage: slippageDecimal,
200
- pathDeep: 2,
201
- chainId: 0,
202
- routerCount: 1,
203
- skipUnwrapNativeToken: false,
204
- user: currentUser,
205
- receiveUser: currentUser
206
- }) : Promise.resolve(null)
207
- ]);
208
- const findPathAmount = new Big(findPathResp?.result_data?.amount_out || 0);
209
- const smartxAmount = new Big(smartxInitialResp?.result_data?.amount_out || 0);
210
- let bestSource = "findPath";
211
- let bestAmountOut = findPathAmount;
212
- if (smartxAmount.gt(findPathAmount)) {
213
- bestSource = "smartx";
214
- bestAmountOut = smartxAmount;
215
- }
216
- if (bestAmountOut.eq(0)) {
217
- return { success: false, tokenIn, tokenOut, amountIn, amountOut: "0", minAmountOut: "0", routes: [], error: "No route found" };
218
- }
219
- let depositAddress = params.depositAddress || "";
220
- if (!depositAddress && this.intentsQuotationAdapter) {
221
- const originAsset = normalizedTokenIn.startsWith("nep141:") ? normalizedTokenIn : `nep141:${normalizedTokenIn}`;
222
- const destinationAsset = normalizedTokenOut.startsWith("nep141:") ? normalizedTokenOut : `nep141:${normalizedTokenOut}`;
223
- logger.debug("SmartRouter - Calling intents to get depositAddress:", {
224
- originAsset,
225
- destinationAsset,
226
- amount: String(amountIn),
227
- bestSource,
228
- currentUser
229
- });
230
- const intentsQuote = await this.intentsQuotationAdapter.quote({
231
- originAsset,
232
- destinationAsset,
233
- amount: String(amountIn),
234
- refundTo: refundTo || "",
235
- recipient: recipient || "",
236
- slippageTolerance: slippageBps,
237
- swapType: "EXACT_INPUT"
238
- });
239
- logger.debug("SmartRouter - Intents quote response:", {
240
- quoteStatus: intentsQuote.quoteStatus,
241
- message: intentsQuote.message,
242
- hasDepositAddress: !!intentsQuote.quoteSuccessResult?.quote?.depositAddress
243
- });
244
- if (intentsQuote.quoteStatus === "success") {
245
- depositAddress = intentsQuote.quoteSuccessResult?.quote?.depositAddress || "";
246
- logger.debug("SmartRouter - Got depositAddress from intents:", {
247
- depositAddress,
248
- hasDepositAddress: !!depositAddress
249
- });
250
- } else {
251
- logger.warn("SmartRouter - Intents quote failed:", {
252
- status: intentsQuote.quoteStatus,
253
- message: intentsQuote.message
254
- });
2059
+ const executor = this.registry.get(build.execution.kind);
2060
+ const context = {
2061
+ executionId: build.executionId,
2062
+ signal: input.signal,
2063
+ waitFor: input.waitFor ?? "submitted",
2064
+ emit,
2065
+ ...input.beforeSign ? { beforeSign: input.beforeSign } : {}
2066
+ };
2067
+ await executor.validate(build.execution, context);
2068
+ emit({ type: "signing-requested", executionId: build.executionId });
2069
+ const chainResult = await executor.execute(build.execution, context);
2070
+ let orderId = chainResult.orderId ?? build.order?.orderId;
2071
+ let orderRouter = build.order?.router;
2072
+ let orderChainId = build.order?.chainId;
2073
+ if (chainResult.signature) {
2074
+ if (build.execution.kind !== "evm-signature") {
2075
+ throw new SwapSdkError(
2076
+ "INVALID_TRANSACTION",
2077
+ "submit",
2078
+ "Only signature executions can submit signed orders"
2079
+ );
255
2080
  }
256
- } else {
257
- logger.debug("SmartRouter - No intentsQuotationAdapter configured, skipping intents call");
2081
+ const submitParams = build.execution.request.submit?.params;
2082
+ const submitRouter = readNonEmptyString(submitParams?.router) ?? build.execution.request.router;
2083
+ const submitQuoteId = readNonEmptyString(submitParams?.quoteId) ?? build.execution.request.quoteId;
2084
+ const signingScheme = readNonEmptyString(submitParams?.signingScheme) ?? chainResult.signingScheme ?? build.execution.request.signingScheme ?? "eip712";
2085
+ const submitted = await this.api.submitOrder(
2086
+ {
2087
+ router: submitRouter,
2088
+ quoteId: submitQuoteId,
2089
+ signature: chainResult.signature,
2090
+ signingScheme
2091
+ },
2092
+ { signal: input.signal }
2093
+ );
2094
+ orderId = submitted.orderId;
2095
+ orderRouter = readNonEmptyString(submitted.router) ?? submitRouter;
2096
+ orderChainId = String(
2097
+ submitted.chainId ?? build.execution.request.chainId
2098
+ );
258
2099
  }
259
- let finalSmartxResult = smartxInitialResp?.result_data;
260
- logger.debug("SmartRouter - Checking conditions for SmartX second call:", {
261
- bestSource,
262
- hasDepositAddress: !!depositAddress,
263
- depositAddress,
264
- hasSwapMultiDexPathAdapter: !!this.swapMultiDexPathAdapter,
265
- willCall: bestSource === "smartx" && depositAddress && this.swapMultiDexPathAdapter
266
- });
267
- if (bestSource === "smartx" && depositAddress && this.swapMultiDexPathAdapter) {
268
- logger.debug("SmartRouter - Re-calling SmartX with depositAddress:", {
269
- user: currentUser,
270
- receiveUser: depositAddress,
271
- tokenIn: normalizedTokenIn,
272
- tokenOut: normalizedTokenOut,
273
- amountIn: String(amountIn)
274
- });
275
- const smartxSecondResp = await this.swapMultiDexPathAdapter.swapMultiDexPath({
276
- amountIn: String(amountIn),
277
- tokenIn: normalizedTokenIn,
278
- tokenOut: normalizedTokenOut,
279
- slippage: slippageDecimal,
280
- pathDeep: 2,
281
- chainId: 0,
282
- routerCount: 1,
283
- skipUnwrapNativeToken: false,
284
- user: currentUser,
285
- receiveUser: depositAddress
286
- // 关键:替换为 intent 存款地址
2100
+ const result = {
2101
+ executionId: build.executionId,
2102
+ status: chainResult.status,
2103
+ router: build.router,
2104
+ ...chainResult.txHash ? { txHash: chainResult.txHash } : {},
2105
+ ...chainResult.txHashes ? { txHashes: chainResult.txHashes } : {},
2106
+ ...orderId ? { orderId } : {},
2107
+ ...build.deposit?.depositAddress ? { depositAddress: build.deposit.depositAddress } : {},
2108
+ report: { status: "skipped" },
2109
+ raw: chainResult.raw ?? build.raw
2110
+ };
2111
+ if (chainResult.status === "requires-user-action") {
2112
+ emit({
2113
+ type: "requires-user-action",
2114
+ executionId: build.executionId
287
2115
  });
288
- logger.debug("SmartRouter - SmartX second call response:", {
289
- result_code: smartxSecondResp?.result_code,
290
- result_message: smartxSecondResp?.result_message,
291
- hasData: !!smartxSecondResp?.result_data
2116
+ } else {
2117
+ emit({
2118
+ type: "submitted",
2119
+ executionId: build.executionId,
2120
+ ...chainResult.txHash ? { txHash: chainResult.txHash } : {},
2121
+ ...orderId ? { orderId } : {}
292
2122
  });
293
- if (smartxSecondResp?.result_code === 0 && smartxSecondResp?.result_data) {
294
- finalSmartxResult = smartxSecondResp.result_data;
295
- bestAmountOut = new Big(finalSmartxResult.amount_out || 0);
296
- logger.debug("SmartRouter - SmartX second call succeeded, updated amountOut:", {
297
- newAmountOut: bestAmountOut.toFixed(0)
298
- });
299
- } else {
300
- logger.warn("SmartRouter - SmartX second call failed, using initial result:", {
301
- result_code: smartxSecondResp?.result_code,
302
- result_message: smartxSecondResp?.result_message
2123
+ if (chainResult.status === "source-confirmed") {
2124
+ emit({
2125
+ type: "source-confirmed",
2126
+ executionId: build.executionId
303
2127
  });
304
2128
  }
305
- } else {
306
- logger.debug("SmartRouter - Skipping SmartX second call:", {
307
- reason: !bestSource ? "bestSource is not smartx" : !depositAddress ? "no depositAddress" : "no swapMultiDexPathAdapter",
308
- bestSource,
309
- depositAddress: depositAddress || "empty",
310
- hasAdapter: !!this.swapMultiDexPathAdapter
311
- });
312
2129
  }
313
- const commonResult = {
314
- success: true,
315
- tokenIn,
316
- tokenOut,
317
- amountIn: String(amountIn),
318
- amountOut: bestAmountOut.toFixed(0),
319
- depositAddress
320
- // 透传给执行阶段
321
- };
322
- if (bestSource === "smartx") {
323
- if (!finalSmartxResult) {
324
- return { success: false, tokenIn, tokenOut, amountIn, amountOut: "0", minAmountOut: "0", routes: [], error: "SmartX result data missing" };
2130
+ const reportRequest = this.createReportRequest(build, result);
2131
+ if (reportRequest) {
2132
+ this.reportRequests.set(build.executionId, reportRequest);
2133
+ }
2134
+ if (this.reportMode === "auto" && reportRequest) {
2135
+ try {
2136
+ await this.api.report(reportRequest, { signal: input.signal });
2137
+ result.report = { status: "reported" };
2138
+ } catch (error) {
2139
+ const warning = {
2140
+ code: "REPORT_FAILED",
2141
+ message: "Swap submitted but report failed",
2142
+ cause: error
2143
+ };
2144
+ result.report = { status: "failed", warning };
2145
+ emit({ type: "warning", executionId: build.executionId, warning });
325
2146
  }
326
- return {
327
- ...commonResult,
328
- minAmountOut: String(finalSmartxResult.min_amount_out || "0"),
329
- routes: [],
330
- quoteSource: "smartx",
331
- smartxResult: {
332
- amountIn: String(finalSmartxResult.amount_in || amountIn),
333
- amountOut: String(finalSmartxResult.amount_out || "0"),
334
- minAmountOut: String(finalSmartxResult.min_amount_out || "0"),
335
- dexs: finalSmartxResult.dexs,
336
- msg: finalSmartxResult.msg,
337
- signature: finalSmartxResult.signature,
338
- tokens: finalSmartxResult.tokens
339
- }
340
- };
341
2147
  }
342
- if (!findPathResp?.result_data) {
343
- return { success: false, tokenIn, tokenOut, amountIn, amountOut: "0", minAmountOut: "0", routes: [], error: "FindPath result data missing" };
2148
+ if ((input.waitFor ?? "submitted") === "completed" && orderId) {
2149
+ const status = await this.waitForOrder({
2150
+ orderId,
2151
+ router: orderRouter ?? build.router,
2152
+ chainId: orderChainId,
2153
+ signal: input.signal
2154
+ });
2155
+ result.status = status.status === "unknown" || status.status === "pending" ? "processing" : status.status;
2156
+ if (status.status === "completed") {
2157
+ emit({ type: "completed", executionId: build.executionId });
2158
+ }
344
2159
  }
345
- const { routes: serverRoutes, amount_out } = findPathResp.result_data;
346
- const minAmountOut = new Big(amount_out).mul(new Big(1).minus(slippageDecimal)).toFixed(0, Big.roundDown);
347
- return {
348
- ...commonResult,
349
- minAmountOut,
350
- routes: serverRoutes.map((r) => ({
351
- pools: r.pools.map((p) => ({ ...p, pool_id: Number(p.pool_id) })),
352
- amountIn,
353
- amountOut: r.amount_out || amount_out
354
- })),
355
- rawRoutes: serverRoutes,
356
- quoteSource: "findPath"
357
- };
2160
+ return result;
358
2161
  } catch (error) {
359
- logger.error("SmartRouter quote error:", error);
360
- return { success: false, tokenIn: params.tokenIn, tokenOut: params.tokenOut, amountIn: params.amountIn, amountOut: "0", minAmountOut: "0", routes: [], error: error.message };
2162
+ const sdkError = asSwapSdkError(error, "broadcast");
2163
+ emit({ type: "failed", executionId: build.executionId, error: sdkError });
2164
+ throw sdkError;
2165
+ } finally {
2166
+ this.inFlight.delete(build.executionId);
361
2167
  }
362
2168
  }
363
- /**
364
- * 执行逻辑:基于 quote 准备好的数据进行分发
365
- */
366
- async executeSwap(params) {
367
- try {
368
- const { quote, recipient, depositAddress } = params;
369
- const finalRecipient = quote.depositAddress || depositAddress || recipient;
370
- logger.debug("SmartRouter - executeSwap:", {
371
- quoteSource: quote.quoteSource,
372
- quoteDepositAddress: quote.depositAddress,
373
- paramsDepositAddress: depositAddress,
374
- recipient,
375
- finalRecipient
376
- });
377
- if (quote.quoteSource === "smartx") {
378
- return await this.executeSmartX(quote, finalRecipient);
379
- } else {
380
- return await this.executeRef(quote, finalRecipient);
381
- }
382
- } catch (error) {
383
- return { success: false, error: error?.message || "Execute failed" };
384
- }
385
- }
386
- async executeSmartX(quote, depositAddress) {
387
- const smartx = quote.smartxResult;
388
- const aggDexId = this.aggregateDexContractId;
389
- if (!smartx?.msg || !smartx?.signature || !aggDexId) {
390
- return { success: false, error: "SmartX data missing" };
391
- }
392
- const tokens = Array.from(/* @__PURE__ */ new Set([...smartx.tokens || [], quote.tokenIn.address]));
393
- const transactions = [];
394
- for (const token of tokens) {
395
- for (const target of [depositAddress, aggDexId]) {
396
- const isRegistered = await this.checkRegistration(token, target);
397
- if (!isRegistered) {
398
- transactions.push({
399
- contractId: token,
400
- methodName: "storage_deposit",
401
- args: { account_id: target, registration_only: true },
402
- gas: "50",
403
- expandDeposit: this.tokenStorageDepositRead
404
- });
405
- }
406
- }
2169
+ async swap(input) {
2170
+ if (isMcaQuote(input.quote)) {
2171
+ return this.managedSwapFlow.swap(input);
407
2172
  }
408
- transactions.push({
409
- contractId: quote.tokenIn.address,
410
- methodName: "ft_transfer_call",
411
- args: {
412
- receiver_id: aggDexId,
413
- amount: quote.amountIn,
414
- msg: JSON.stringify({ msg: smartx.msg, signature: smartx.signature })
415
- },
416
- gas: "300",
417
- expandDeposit: "1"
2173
+ const regularInput = input;
2174
+ const build = await this.buildSwap({
2175
+ quote: regularInput.quote,
2176
+ signal: regularInput.signal,
2177
+ idempotencyKey: regularInput.idempotencyKey
2178
+ });
2179
+ return this.executeSwap({
2180
+ build,
2181
+ waitFor: regularInput.waitFor,
2182
+ signal: regularInput.signal,
2183
+ onEvent: regularInput.onEvent,
2184
+ beforeSign: regularInput.beforeSign
418
2185
  });
419
- const result = await this.nearChainAdapter.call({ transactions });
420
- return this.handleCallResult(result);
421
- }
422
- async executeRef(quote, depositAddress) {
423
- const transactions = [];
424
- const routesToUse = quote.rawRoutes || quote.routes;
425
- const actions = routesToUse.flatMap(
426
- (r) => r.pools.map((p) => ({
427
- pool_id: Number(p.pool_id),
428
- token_in: p.token_in,
429
- token_out: p.token_out,
430
- amount_in: p.amount_in || void 0,
431
- amount_out: p.amount_out,
432
- fee: Number(p.fee)
433
- }))
2186
+ }
2187
+ async getOrderStatus(input) {
2188
+ const raw = await this.api.getOrderStatus(
2189
+ {
2190
+ orderId: input.orderId,
2191
+ router: input.router,
2192
+ chainId: input.chainId
2193
+ },
2194
+ { signal: input.signal }
434
2195
  );
435
- if (depositAddress && quote.tokenOut?.address) {
436
- const isRegistered = await this.checkRegistration(quote.tokenOut.address, depositAddress);
437
- if (!isRegistered) {
438
- transactions.push({
439
- contractId: quote.tokenOut.address,
440
- methodName: "storage_deposit",
441
- args: { account_id: depositAddress, registration_only: true },
442
- gas: "50",
443
- expandDeposit: this.tokenStorageDepositRead
444
- });
2196
+ return {
2197
+ orderId: input.orderId,
2198
+ router: input.router,
2199
+ status: normalizeOrderStatus(raw),
2200
+ raw
2201
+ };
2202
+ }
2203
+ async waitForOrder(input) {
2204
+ const intervalMs = input.intervalMs ?? 5e3;
2205
+ const timeoutMs = input.timeoutMs ?? 25e4;
2206
+ const startedAt = this.now();
2207
+ for (; ; ) {
2208
+ if (input.signal?.aborted) {
2209
+ throw new SwapSdkError(
2210
+ "REQUEST_ABORTED",
2211
+ "status",
2212
+ "Order polling aborted; any submitted transaction is unaffected"
2213
+ );
2214
+ }
2215
+ const result = await this.getOrderStatus(input);
2216
+ if (result.status === "completed" || result.status === "failed" || result.status === "refunded" || result.status === "expired") {
2217
+ return result;
445
2218
  }
2219
+ if (this.now() - startedAt >= timeoutMs) {
2220
+ throw new SwapSdkError(
2221
+ "ORDER_TIMEOUT",
2222
+ "status",
2223
+ `Order status timed out after ${timeoutMs}ms`,
2224
+ { retryable: true }
2225
+ );
2226
+ }
2227
+ await delay(intervalMs, input.signal);
446
2228
  }
447
- transactions.push({
448
- contractId: quote.tokenIn.address,
449
- methodName: "ft_transfer_call",
450
- args: {
451
- receiver_id: this.refExchangeId,
452
- amount: quote.amountIn,
453
- msg: JSON.stringify({ force: 0, actions, swap_out_recipient: depositAddress })
454
- },
455
- gas: "250",
456
- expandDeposit: "1"
457
- });
458
- const result = await this.nearChainAdapter.call({ transactions });
459
- return this.handleCallResult(result);
460
2229
  }
461
- async checkRegistration(token, accountId) {
462
- try {
463
- const balance = await this.nearChainAdapter.view({
464
- contractId: token,
465
- methodName: "storage_balance_of",
466
- args: { account_id: accountId }
467
- });
468
- return !!balance;
469
- } catch {
470
- return false;
471
- }
2230
+ submitOrderRaw(request, options = {}) {
2231
+ return this.api.submitOrder(request, options);
472
2232
  }
473
- handleCallResult(result) {
474
- if (result.status === "success") {
475
- return { success: true, txHash: result.txHash, txHashArray: result.txHashArr || [result.txHash] };
2233
+ getOrderStatusRaw(request, options = {}) {
2234
+ return this.api.getOrderStatus(request, options);
2235
+ }
2236
+ reportRaw(request, options = {}) {
2237
+ return this.api.report(request, options);
2238
+ }
2239
+ report(result) {
2240
+ const managedReport = this.managedSwapFlow.reportIfManaged(result);
2241
+ if (managedReport) return managedReport;
2242
+ const request = this.reportRequests.get(result.executionId);
2243
+ if (!request) {
2244
+ throw new SwapSdkError(
2245
+ "INVALID_REQUEST",
2246
+ "report",
2247
+ `No report context for execution ${result.executionId}`
2248
+ );
476
2249
  }
477
- return { success: false, error: result.message || "Transaction failed" };
2250
+ return this.api.report(request);
478
2251
  }
479
- getSupportedChain() {
480
- return "near";
2252
+ retryReport(result) {
2253
+ return this.report(result);
481
2254
  }
482
- };
483
- async function completeQuote(params, config) {
484
- const {
485
- sourceToken,
486
- targetToken,
487
- sourceChain,
488
- targetChain: _targetChain,
489
- // Reserved for future use
490
- amountIn,
491
- slippage,
492
- recipient,
493
- refundTo,
494
- depositAddress: providedDepositAddress
495
- } = params;
496
- const { intentsQuotationAdapter, dexRouter, bluechipTokens, configAdapter } = config;
497
- const wrapNearContractId = configAdapter.getWrapNearContractId();
498
- if (!sourceToken?.address) {
499
- throw new Error("Source token address is required");
500
- }
501
- if (!targetToken?.address) {
502
- throw new Error("Target token address is required");
503
- }
504
- const needsPreSwap = sourceChain === "near" && !isNearIntentsSupportedToken(sourceToken, bluechipTokens);
505
- const bluechipToken = findBestBluechipToken(
506
- bluechipTokens,
507
- wrapNearContractId
508
- );
509
- if (!bluechipToken?.address) {
510
- logger.error("DEX Aggregator - Failed to find bluechip token:", {
511
- bluechipToken,
512
- bluechipTokens
513
- });
514
- throw new Error("Failed to find bluechip token address");
2255
+ getHistoryRaw(params, options = {}) {
2256
+ return this.api.getHistory(params, options);
515
2257
  }
516
- logger.debug("DEX Aggregator - Using bluechip token:", {
517
- address: bluechipToken.address,
518
- symbol: bluechipToken.symbol,
519
- decimals: bluechipToken.decimals
520
- });
521
- let preSwapQuote = null;
522
- if (needsPreSwap) {
523
- if (!sourceToken?.address) {
524
- throw new Error("Source token address is required");
525
- }
526
- logger.debug("DEX Aggregator - Pre-swap quote params:", {
527
- tokenIn: {
528
- address: sourceToken.address,
529
- symbol: sourceToken.symbol
530
- },
531
- tokenOut: {
532
- address: bluechipToken.address,
533
- symbol: bluechipToken.symbol
2258
+ async getHistory(request, options = {}) {
2259
+ const raw = await this.api.getHistory(
2260
+ {
2261
+ sender: request.sender,
2262
+ ...request.page !== void 0 ? { pageNumber: request.page } : {},
2263
+ ...request.pageSize !== void 0 ? { pageSize: request.pageSize } : {}
534
2264
  },
535
- amountIn,
536
- slippage
537
- });
538
- if (!dexRouter) {
539
- throw new Error(
540
- `No DEX router registered for sourceChain=${sourceChain}`
541
- );
542
- }
543
- preSwapQuote = await dexRouter.quote({
544
- tokenIn: sourceToken,
545
- tokenOut: bluechipToken,
546
- amountIn,
547
- slippage,
548
- swapType: "EXACT_INPUT",
549
- recipient: recipient || refundTo,
550
- refundTo,
551
- depositAddress: providedDepositAddress
552
- // Pass depositAddress to enable SmartX second call
553
- });
554
- if (!preSwapQuote.success) {
555
- logger.error("DEX Aggregator - Pre-swap quote failed:", {
556
- error: preSwapQuote.error,
557
- tokenIn: sourceToken,
558
- tokenOut: bluechipToken
559
- });
560
- throw new Error(`Pre-swap quote failed: ${preSwapQuote.error}`);
561
- }
562
- const preSwapAmountOut = preSwapQuote.amountOut;
563
- if (!preSwapAmountOut || new Big(preSwapAmountOut).lte(0)) {
564
- logger.error("DEX Aggregator - Pre-swap amountOut is invalid:", {
565
- amountOut: preSwapAmountOut,
566
- tokenIn: sourceToken,
567
- tokenOut: bluechipToken
568
- });
569
- throw new Error(
570
- "Pre-swap returned invalid amount: amount is too small or zero"
2265
+ options
2266
+ );
2267
+ const page = normalizeHistory(raw);
2268
+ if (request.status === void 0) return page;
2269
+ const statuses = new Set(request.status);
2270
+ return {
2271
+ ...page,
2272
+ items: page.items.filter((item) => statuses.has(item.status)),
2273
+ filteredLocally: true
2274
+ };
2275
+ }
2276
+ emit(event) {
2277
+ this.config.onEvent?.(event);
2278
+ }
2279
+ assertQuoteFresh(quote) {
2280
+ const now = this.now();
2281
+ const maxAge = this.config.maxQuoteAgeMs === void 0 ? 3e4 : this.config.maxQuoteAgeMs;
2282
+ const expiredByApi = quote.expiresAt !== void 0 && now > quote.expiresAt;
2283
+ const expiredByAge = maxAge !== null && now - quote.receivedAt > Math.max(0, maxAge);
2284
+ if (expiredByApi || expiredByAge) {
2285
+ throw new SwapSdkError(
2286
+ "QUOTE_EXPIRED",
2287
+ "build",
2288
+ "Quote has expired; request a fresh quote"
571
2289
  );
572
2290
  }
573
- logger.debug("DEX Aggregator - Pre-swap quote success:", {
574
- amountOut: preSwapAmountOut,
575
- tokenOut: bluechipToken.symbol,
576
- decimals: bluechipToken.decimals
577
- });
578
2291
  }
579
- let normalizedSourceAsset;
580
- if (needsPreSwap) {
581
- const bluechipKey = bluechipToken.symbol?.toUpperCase() === "WNEAR" ? "NEAR" : bluechipToken.symbol?.toUpperCase();
582
- const bluechipTokenConfig = bluechipKey && bluechipTokens[bluechipKey] || void 0;
583
- if (bluechipTokenConfig?.assetId) {
584
- normalizedSourceAsset = bluechipTokenConfig.assetId;
585
- logger.debug("Using bluechip token assetId for NearIntents:", {
586
- symbol: bluechipToken.symbol,
587
- assetId: normalizedSourceAsset,
588
- contractAddress: bluechipToken.address
589
- });
590
- } else {
591
- normalizedSourceAsset = `nep141:${bluechipToken.address}`;
592
- logger.warn(
593
- "Bluechip token assetId not found, using contractAddress with prefix:",
594
- {
595
- symbol: bluechipToken.symbol,
596
- normalizedSourceAsset
597
- }
2292
+ createReportRequest(build, result) {
2293
+ const request = build.request;
2294
+ const reportContext = build.reportContext;
2295
+ const fromHash = reportContext?.fromHash ?? result.txHash ?? result.orderId;
2296
+ if (!request || !fromHash) return void 0;
2297
+ return {
2298
+ sender: reportContext?.sender ?? request.sender,
2299
+ recipient: reportContext?.recipient ?? request.recipient ?? request.sender,
2300
+ from_hash: fromHash,
2301
+ from_token: request.tokenIn,
2302
+ to_token: request.tokenOut,
2303
+ deposit_address: reportContext?.depositAddress ?? result.depositAddress ?? "",
2304
+ from_chain: request.fromChain,
2305
+ to_chain: request.toChain,
2306
+ is_cross_chain: reportContext?.isCrossChain ?? build.isCrossChain,
2307
+ amount_in: request.amountIn,
2308
+ estimated_out: build.estimatedOut,
2309
+ router: build.router,
2310
+ tx_type: reportContext?.txType ?? (build.isCrossChain ? "cross-chain" : "same-chain"),
2311
+ ...reportContext?.multiAddr ? { multi_addr: reportContext.multiAddr } : {},
2312
+ ...reportContext?.swapId ?? result.orderId ? { swapId: reportContext?.swapId ?? result.orderId } : {}
2313
+ };
2314
+ }
2315
+ };
2316
+ function isMcaQuoteRequest(request) {
2317
+ if (!("flow" in request) || !("mcaAccountId" in request)) return false;
2318
+ const flow = Reflect.get(request, "flow");
2319
+ const accountId = Reflect.get(request, "mcaAccountId");
2320
+ return (flow === "deposit" || flow === "withdraw") && typeof accountId === "string" && accountId.trim().length > 0;
2321
+ }
2322
+ function isMcaQuote(quote) {
2323
+ if (!("executionMode" in quote) || !("mcaAccountId" in quote)) {
2324
+ return false;
2325
+ }
2326
+ const mode = Reflect.get(quote, "executionMode");
2327
+ return mode === "deposit" || mode === "withdraw-near" || mode === "withdraw-relayer";
2328
+ }
2329
+ function readNonEmptyString(value) {
2330
+ return typeof value === "string" && value.trim() ? value.trim() : void 0;
2331
+ }
2332
+ function delay(ms, signal) {
2333
+ return new Promise((resolve, reject) => {
2334
+ if (signal?.aborted) {
2335
+ reject(
2336
+ new SwapSdkError(
2337
+ "REQUEST_ABORTED",
2338
+ "status",
2339
+ "Order polling aborted; any submitted transaction is unaffected"
2340
+ )
598
2341
  );
2342
+ return;
599
2343
  }
600
- } else {
601
- if (sourceToken.symbol) {
602
- const sourceKey = sourceToken.symbol.toUpperCase();
603
- const sourceTokenConfig = bluechipTokens[sourceKey];
604
- if (sourceTokenConfig?.assetId) {
605
- normalizedSourceAsset = sourceTokenConfig.assetId;
606
- } else {
607
- normalizedSourceAsset = normalizeTokenId(
608
- sourceToken.address,
609
- wrapNearContractId
610
- );
611
- if (!normalizedSourceAsset.startsWith("nep141:")) {
612
- normalizedSourceAsset = `nep141:${normalizedSourceAsset}`;
613
- }
614
- }
615
- } else {
616
- normalizedSourceAsset = normalizeTokenId(
617
- sourceToken.address,
618
- wrapNearContractId
2344
+ const onAbort = () => {
2345
+ clearTimeout(timeout);
2346
+ reject(
2347
+ new SwapSdkError(
2348
+ "REQUEST_ABORTED",
2349
+ "status",
2350
+ "Order polling aborted; any submitted transaction is unaffected"
2351
+ )
619
2352
  );
620
- if (!normalizedSourceAsset.startsWith("nep141:")) {
621
- normalizedSourceAsset = `nep141:${normalizedSourceAsset}`;
622
- }
623
- }
624
- }
625
- let normalizedTargetAsset = targetToken.address;
626
- if (normalizedTargetAsset && !normalizedTargetAsset.startsWith("nep141:") && !normalizedTargetAsset.startsWith("nep245:") && normalizedTargetAsset.includes(".")) {
627
- normalizedTargetAsset = `nep141:${normalizeTokenId(
628
- normalizedTargetAsset,
629
- wrapNearContractId
630
- )}`;
631
- }
632
- normalizedTargetAsset = normalizeDestinationAsset(normalizedTargetAsset, wrapNearContractId) || normalizedTargetAsset;
633
- const slippageBps = convertSlippageToBasisPoints(slippage);
634
- const intentsAmount = needsPreSwap ? preSwapQuote.amountOut : amountIn;
635
- logger.debug("DEX Aggregator - Calling NearIntents quotation:", {
636
- originAsset: normalizedSourceAsset,
637
- destinationAsset: normalizedTargetAsset,
638
- amount: intentsAmount,
639
- needsPreSwap,
640
- preSwapAmountOut: needsPreSwap ? preSwapQuote.amountOut : void 0
641
- });
642
- const swapTypeForIntents = needsPreSwap ? "FLEX_INPUT" : void 0;
643
- logger.debug("DEX Aggregator - swapType for NearIntents:", {
644
- needsPreSwap,
645
- swapType: swapTypeForIntents || "EXACT_INPUT (default)"
646
- });
647
- const intentsQuote = await intentsQuotationAdapter.quote({
648
- originAsset: normalizedSourceAsset,
649
- destinationAsset: normalizedTargetAsset,
650
- amount: intentsAmount,
651
- refundTo: refundTo || recipient,
652
- recipient,
653
- slippageTolerance: slippageBps,
654
- swapType: swapTypeForIntents
655
- });
656
- logger.debug("DEX Aggregator - NearIntents quotation result:", {
657
- quoteStatus: intentsQuote.quoteStatus,
658
- message: intentsQuote.message,
659
- hasDepositAddress: !!intentsQuote.quoteSuccessResult?.quote?.depositAddress
2353
+ };
2354
+ const timeout = setTimeout(() => {
2355
+ signal?.removeEventListener("abort", onAbort);
2356
+ resolve();
2357
+ }, Math.max(0, ms));
2358
+ signal?.addEventListener("abort", onAbort, { once: true });
660
2359
  });
661
- if (intentsQuote.quoteStatus !== "success") {
662
- const errorMessage = intentsQuote.message || "Unknown error";
663
- logger.error("DEX Aggregator - NearIntents quote failed:", {
664
- error: errorMessage,
665
- originAsset: normalizedSourceAsset,
666
- destinationAsset: normalizedTargetAsset,
667
- amount: intentsAmount,
668
- needsPreSwap,
669
- preSwapAmountOut: needsPreSwap ? preSwapQuote.amountOut : void 0
670
- });
671
- throw new Error(`Intents quote failed: ${errorMessage}`);
672
- }
673
- const depositAddress = providedDepositAddress || intentsQuote.quoteSuccessResult?.quote?.depositAddress || "";
674
- if (!depositAddress) {
675
- throw new Error("Deposit address not found in intents quote");
2360
+ }
2361
+
2362
+ // src/mca/collateral.ts
2363
+ function resolveMcaWithdrawPolicy(input) {
2364
+ const collateral = parseDecimal(input.collateralBalance, "collateralBalance");
2365
+ const available = parseDecimal(input.availableBalance, "availableBalance");
2366
+ const amount = parseDecimal(input.amountIn, "amountIn");
2367
+ const needDecrease = collateral.digits > 0n;
2368
+ return {
2369
+ needDecrease,
2370
+ decreaseAmountBurrow: needDecrease ? input.collateralBalance.trim() : "0",
2371
+ withdrawAll: input.isMax || available.digits > 0n && isAtLeastWithdrawAllThreshold(amount, available)
2372
+ };
2373
+ }
2374
+ function isAtLeastWithdrawAllThreshold(amount, available) {
2375
+ const [amountScaled, availableScaled] = alignScale(amount, available);
2376
+ return amountScaled * 1000000n >= availableScaled * 999999n;
2377
+ }
2378
+ function alignScale(a, b) {
2379
+ const scale = Math.max(a.scale, b.scale);
2380
+ return [
2381
+ a.digits * pow10(scale - a.scale),
2382
+ b.digits * pow10(scale - b.scale)
2383
+ ];
2384
+ }
2385
+ function parseDecimal(value, field) {
2386
+ const trimmed = value.trim();
2387
+ if (!/^(?:0|[1-9]\d*)(?:\.\d+)?$/.test(trimmed)) {
2388
+ throw new SwapSdkError(
2389
+ "INVALID_REQUEST",
2390
+ "quote",
2391
+ `${field} must be a non-negative decimal string`
2392
+ );
676
2393
  }
2394
+ const [integer = "0", fraction = ""] = trimmed.split(".");
677
2395
  return {
678
- intents: {
679
- quote: intentsQuote,
680
- depositAddress
681
- },
682
- preSwap: needsPreSwap ? {
683
- quote: preSwapQuote,
684
- tokenIn: sourceToken,
685
- tokenOut: bluechipToken,
686
- executor: dexRouter
687
- } : void 0,
688
- finalAmountOut: intentsQuote.quoteSuccessResult?.quote?.amountOut || "0"
2396
+ digits: BigInt(`${integer}${fraction}`),
2397
+ scale: fraction.length
689
2398
  };
690
2399
  }
2400
+ function pow10(exponent) {
2401
+ return 10n ** BigInt(exponent);
2402
+ }
691
2403
 
692
- export { NearSmartRouter, completeQuote, convertSlippageToBasisPoints, findBestBluechipToken, getBluechipTokensConfig, isNearIntentsSupportedToken, logger, normalizeDestinationAsset, normalizeTokenId, setBluechipTokensConfig };
2404
+ export { ApiClient, DEFAULT_MCA_SIGNER_PRIORITY, ExecutorRegistry, SwapClient, SwapSdkError, asSwapSdkError, assertBaseUnitAmount, buildMcaWithdrawRelayerRequest, buildNearMcaWithdrawTransactions, createExecutionId, extractMcaWithdrawBusiness, extractMcaWithdrawDepositAddress, extractMcaWithdrawSignerWallet, formatMcaWallet, formatUnits, fromApiChain, isSameMcaSignerIdentity, normalizeBuild, normalizeHistory, normalizeHistoryStatus, normalizeMcaQuote, normalizeOrderStatus, normalizeQuote, parseUnits, resolveMcaWithdrawPolicy, selectMcaSigner, serializeMcaQuoteRequest, serializeQuoteRequest, toApiAssetAddress, toApiChain };
693
2405
  //# sourceMappingURL=index.mjs.map
694
2406
  //# sourceMappingURL=index.mjs.map