@rango-dev/queue-manager-rango-preset 0.1.15-next.8 → 0.2.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 (49) hide show
  1. package/CHANGELOG.md +11 -0
  2. package/dist/actions/checkStatus.d.ts +11 -11
  3. package/dist/actions/checkStatus.d.ts.map +1 -1
  4. package/dist/actions/createTransaction.d.ts +10 -10
  5. package/dist/actions/createTransaction.d.ts.map +1 -1
  6. package/dist/actions/executeTransaction.d.ts +12 -12
  7. package/dist/actions/executeTransaction.d.ts.map +1 -1
  8. package/dist/actions/scheduleNextStep.d.ts +12 -12
  9. package/dist/actions/scheduleNextStep.d.ts.map +1 -1
  10. package/dist/actions/start.d.ts +3 -3
  11. package/dist/actions/start.d.ts.map +1 -1
  12. package/dist/configs.d.ts +7 -7
  13. package/dist/configs.d.ts.map +1 -1
  14. package/dist/constants.d.ts +5 -5
  15. package/dist/constants.d.ts.map +1 -1
  16. package/dist/helpers.d.ts +242 -242
  17. package/dist/helpers.d.ts.map +1 -1
  18. package/dist/hooks.d.ts +18 -18
  19. package/dist/hooks.d.ts.map +1 -1
  20. package/dist/index.d.ts +9 -8
  21. package/dist/index.d.ts.map +1 -1
  22. package/dist/index.js +2 -8
  23. package/dist/index.js.map +7 -0
  24. package/dist/migration.d.ts +14 -14
  25. package/dist/migration.d.ts.map +1 -1
  26. package/dist/numbers.d.ts +2 -2
  27. package/dist/numbers.d.ts.map +1 -1
  28. package/dist/queueDef.d.ts +9 -9
  29. package/dist/queueDef.d.ts.map +1 -1
  30. package/dist/services/httpService.d.ts +2 -2
  31. package/dist/services/httpService.d.ts.map +1 -1
  32. package/dist/services/index.d.ts +1 -1
  33. package/dist/services/index.d.ts.map +1 -1
  34. package/dist/shared-errors.d.ts +24 -24
  35. package/dist/shared-errors.d.ts.map +1 -1
  36. package/dist/shared-sentry.d.ts +3 -3
  37. package/dist/shared-sentry.d.ts.map +1 -1
  38. package/dist/shared.d.ts +158 -158
  39. package/dist/shared.d.ts.map +1 -1
  40. package/dist/types.d.ts +50 -50
  41. package/dist/types.d.ts.map +1 -1
  42. package/package.json +4 -5
  43. package/src/index.ts +8 -6
  44. package/dist/queue-manager-rango-preset.cjs.development.js +0 -2803
  45. package/dist/queue-manager-rango-preset.cjs.development.js.map +0 -1
  46. package/dist/queue-manager-rango-preset.cjs.production.min.js +0 -2
  47. package/dist/queue-manager-rango-preset.cjs.production.min.js.map +0 -1
  48. package/dist/queue-manager-rango-preset.esm.js +0 -2782
  49. package/dist/queue-manager-rango-preset.esm.js.map +0 -1
@@ -1,2782 +0,0 @@
1
- import { Network, getBlockChainNameFromId } from '@rango-dev/wallets-shared';
2
- import { readAccountAddress } from '@rango-dev/wallets-core';
3
- import { RangoClient, isEvmTransaction, isCosmosTransaction, isSolanaTransaction, isTransferTransaction, isStarknetTransaction, isTronTransaction, TransactionType } from 'rango-sdk';
4
- import { Status, Persistor, DB_NAME } from '@rango-dev/queue-manager-core';
5
- import { SignerError, isAPIErrorCode, isSignerErrorCode, SignerErrorCode, isCosmosBlockchain, isEvmBlockchain, isStarknetBlockchain, isTronBlockchain } from 'rango-types';
6
- import BigNumber from 'bignumber.js';
7
- import { captureException } from '@sentry/browser';
8
- import { useManager } from '@rango-dev/queue-manager-react';
9
- import { useState, useEffect } from 'react';
10
- import { v4 } from 'uuid';
11
-
12
- // this API key is limited and
13
- // it is only for test purpose
14
- var RANGO_PUBLIC_API_KEY = 'c6381a79-2817-4602-83bf-6a641a409e32';
15
- var configs = {
16
- API_KEY: RANGO_PUBLIC_API_KEY
17
- };
18
- function getConfig(name) {
19
- return configs[name] || '';
20
- }
21
- function initConfig(nextConfigs) {
22
- var clonedConfigs;
23
- if (typeof structuredClone === 'function') {
24
- clonedConfigs = structuredClone(nextConfigs);
25
- } else {
26
- clonedConfigs = JSON.parse(JSON.stringify(nextConfigs));
27
- }
28
- configs = clonedConfigs;
29
- return configs;
30
- }
31
-
32
- var SwapActionTypes;
33
- (function (SwapActionTypes) {
34
- SwapActionTypes["START"] = "START";
35
- SwapActionTypes["SCHEDULE_NEXT_STEP"] = "SCHEDULE_NEXT_STEP";
36
- SwapActionTypes["CREATE_TRANSACTION"] = "CREATE_TRANSACTION";
37
- SwapActionTypes["EXECUTE_TRANSACTION"] = "EXECUTE_TRANSACTION";
38
- SwapActionTypes["CHECK_TRANSACTION_STATUS"] = "CHECK_TRANSACTION_STATUS";
39
- })(SwapActionTypes || (SwapActionTypes = {}));
40
- var BlockReason;
41
- (function (BlockReason) {
42
- BlockReason["WAIT_FOR_CONNECT_WALLET"] = "waiting_for_connecting_wallet";
43
- BlockReason["WAIT_FOR_NETWORK_CHANGE"] = "waiting_for_network_change";
44
- BlockReason["DEPENDS_ON_OTHER_QUEUES"] = "depends_on_other_queues";
45
- })(BlockReason || (BlockReason = {}));
46
-
47
- function _regeneratorRuntime() {
48
- _regeneratorRuntime = function () {
49
- return exports;
50
- };
51
- var exports = {},
52
- Op = Object.prototype,
53
- hasOwn = Op.hasOwnProperty,
54
- defineProperty = Object.defineProperty || function (obj, key, desc) {
55
- obj[key] = desc.value;
56
- },
57
- $Symbol = "function" == typeof Symbol ? Symbol : {},
58
- iteratorSymbol = $Symbol.iterator || "@@iterator",
59
- asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator",
60
- toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag";
61
- function define(obj, key, value) {
62
- return Object.defineProperty(obj, key, {
63
- value: value,
64
- enumerable: !0,
65
- configurable: !0,
66
- writable: !0
67
- }), obj[key];
68
- }
69
- try {
70
- define({}, "");
71
- } catch (err) {
72
- define = function (obj, key, value) {
73
- return obj[key] = value;
74
- };
75
- }
76
- function wrap(innerFn, outerFn, self, tryLocsList) {
77
- var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator,
78
- generator = Object.create(protoGenerator.prototype),
79
- context = new Context(tryLocsList || []);
80
- return defineProperty(generator, "_invoke", {
81
- value: makeInvokeMethod(innerFn, self, context)
82
- }), generator;
83
- }
84
- function tryCatch(fn, obj, arg) {
85
- try {
86
- return {
87
- type: "normal",
88
- arg: fn.call(obj, arg)
89
- };
90
- } catch (err) {
91
- return {
92
- type: "throw",
93
- arg: err
94
- };
95
- }
96
- }
97
- exports.wrap = wrap;
98
- var ContinueSentinel = {};
99
- function Generator() {}
100
- function GeneratorFunction() {}
101
- function GeneratorFunctionPrototype() {}
102
- var IteratorPrototype = {};
103
- define(IteratorPrototype, iteratorSymbol, function () {
104
- return this;
105
- });
106
- var getProto = Object.getPrototypeOf,
107
- NativeIteratorPrototype = getProto && getProto(getProto(values([])));
108
- NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype);
109
- var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype);
110
- function defineIteratorMethods(prototype) {
111
- ["next", "throw", "return"].forEach(function (method) {
112
- define(prototype, method, function (arg) {
113
- return this._invoke(method, arg);
114
- });
115
- });
116
- }
117
- function AsyncIterator(generator, PromiseImpl) {
118
- function invoke(method, arg, resolve, reject) {
119
- var record = tryCatch(generator[method], generator, arg);
120
- if ("throw" !== record.type) {
121
- var result = record.arg,
122
- value = result.value;
123
- return value && "object" == typeof value && hasOwn.call(value, "__await") ? PromiseImpl.resolve(value.__await).then(function (value) {
124
- invoke("next", value, resolve, reject);
125
- }, function (err) {
126
- invoke("throw", err, resolve, reject);
127
- }) : PromiseImpl.resolve(value).then(function (unwrapped) {
128
- result.value = unwrapped, resolve(result);
129
- }, function (error) {
130
- return invoke("throw", error, resolve, reject);
131
- });
132
- }
133
- reject(record.arg);
134
- }
135
- var previousPromise;
136
- defineProperty(this, "_invoke", {
137
- value: function (method, arg) {
138
- function callInvokeWithMethodAndArg() {
139
- return new PromiseImpl(function (resolve, reject) {
140
- invoke(method, arg, resolve, reject);
141
- });
142
- }
143
- return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg();
144
- }
145
- });
146
- }
147
- function makeInvokeMethod(innerFn, self, context) {
148
- var state = "suspendedStart";
149
- return function (method, arg) {
150
- if ("executing" === state) throw new Error("Generator is already running");
151
- if ("completed" === state) {
152
- if ("throw" === method) throw arg;
153
- return doneResult();
154
- }
155
- for (context.method = method, context.arg = arg;;) {
156
- var delegate = context.delegate;
157
- if (delegate) {
158
- var delegateResult = maybeInvokeDelegate(delegate, context);
159
- if (delegateResult) {
160
- if (delegateResult === ContinueSentinel) continue;
161
- return delegateResult;
162
- }
163
- }
164
- if ("next" === context.method) context.sent = context._sent = context.arg;else if ("throw" === context.method) {
165
- if ("suspendedStart" === state) throw state = "completed", context.arg;
166
- context.dispatchException(context.arg);
167
- } else "return" === context.method && context.abrupt("return", context.arg);
168
- state = "executing";
169
- var record = tryCatch(innerFn, self, context);
170
- if ("normal" === record.type) {
171
- if (state = context.done ? "completed" : "suspendedYield", record.arg === ContinueSentinel) continue;
172
- return {
173
- value: record.arg,
174
- done: context.done
175
- };
176
- }
177
- "throw" === record.type && (state = "completed", context.method = "throw", context.arg = record.arg);
178
- }
179
- };
180
- }
181
- function maybeInvokeDelegate(delegate, context) {
182
- var methodName = context.method,
183
- method = delegate.iterator[methodName];
184
- if (undefined === method) return context.delegate = null, "throw" === methodName && delegate.iterator.return && (context.method = "return", context.arg = undefined, maybeInvokeDelegate(delegate, context), "throw" === context.method) || "return" !== methodName && (context.method = "throw", context.arg = new TypeError("The iterator does not provide a '" + methodName + "' method")), ContinueSentinel;
185
- var record = tryCatch(method, delegate.iterator, context.arg);
186
- if ("throw" === record.type) return context.method = "throw", context.arg = record.arg, context.delegate = null, ContinueSentinel;
187
- var info = record.arg;
188
- return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, "return" !== context.method && (context.method = "next", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = "throw", context.arg = new TypeError("iterator result is not an object"), context.delegate = null, ContinueSentinel);
189
- }
190
- function pushTryEntry(locs) {
191
- var entry = {
192
- tryLoc: locs[0]
193
- };
194
- 1 in locs && (entry.catchLoc = locs[1]), 2 in locs && (entry.finallyLoc = locs[2], entry.afterLoc = locs[3]), this.tryEntries.push(entry);
195
- }
196
- function resetTryEntry(entry) {
197
- var record = entry.completion || {};
198
- record.type = "normal", delete record.arg, entry.completion = record;
199
- }
200
- function Context(tryLocsList) {
201
- this.tryEntries = [{
202
- tryLoc: "root"
203
- }], tryLocsList.forEach(pushTryEntry, this), this.reset(!0);
204
- }
205
- function values(iterable) {
206
- if (iterable) {
207
- var iteratorMethod = iterable[iteratorSymbol];
208
- if (iteratorMethod) return iteratorMethod.call(iterable);
209
- if ("function" == typeof iterable.next) return iterable;
210
- if (!isNaN(iterable.length)) {
211
- var i = -1,
212
- next = function next() {
213
- for (; ++i < iterable.length;) if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next;
214
- return next.value = undefined, next.done = !0, next;
215
- };
216
- return next.next = next;
217
- }
218
- }
219
- return {
220
- next: doneResult
221
- };
222
- }
223
- function doneResult() {
224
- return {
225
- value: undefined,
226
- done: !0
227
- };
228
- }
229
- return GeneratorFunction.prototype = GeneratorFunctionPrototype, defineProperty(Gp, "constructor", {
230
- value: GeneratorFunctionPrototype,
231
- configurable: !0
232
- }), defineProperty(GeneratorFunctionPrototype, "constructor", {
233
- value: GeneratorFunction,
234
- configurable: !0
235
- }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction"), exports.isGeneratorFunction = function (genFun) {
236
- var ctor = "function" == typeof genFun && genFun.constructor;
237
- return !!ctor && (ctor === GeneratorFunction || "GeneratorFunction" === (ctor.displayName || ctor.name));
238
- }, exports.mark = function (genFun) {
239
- return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, "GeneratorFunction")), genFun.prototype = Object.create(Gp), genFun;
240
- }, exports.awrap = function (arg) {
241
- return {
242
- __await: arg
243
- };
244
- }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () {
245
- return this;
246
- }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) {
247
- void 0 === PromiseImpl && (PromiseImpl = Promise);
248
- var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl);
249
- return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) {
250
- return result.done ? result.value : iter.next();
251
- });
252
- }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, "Generator"), define(Gp, iteratorSymbol, function () {
253
- return this;
254
- }), define(Gp, "toString", function () {
255
- return "[object Generator]";
256
- }), exports.keys = function (val) {
257
- var object = Object(val),
258
- keys = [];
259
- for (var key in object) keys.push(key);
260
- return keys.reverse(), function next() {
261
- for (; keys.length;) {
262
- var key = keys.pop();
263
- if (key in object) return next.value = key, next.done = !1, next;
264
- }
265
- return next.done = !0, next;
266
- };
267
- }, exports.values = values, Context.prototype = {
268
- constructor: Context,
269
- reset: function (skipTempReset) {
270
- if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = "next", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) "t" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined);
271
- },
272
- stop: function () {
273
- this.done = !0;
274
- var rootRecord = this.tryEntries[0].completion;
275
- if ("throw" === rootRecord.type) throw rootRecord.arg;
276
- return this.rval;
277
- },
278
- dispatchException: function (exception) {
279
- if (this.done) throw exception;
280
- var context = this;
281
- function handle(loc, caught) {
282
- return record.type = "throw", record.arg = exception, context.next = loc, caught && (context.method = "next", context.arg = undefined), !!caught;
283
- }
284
- for (var i = this.tryEntries.length - 1; i >= 0; --i) {
285
- var entry = this.tryEntries[i],
286
- record = entry.completion;
287
- if ("root" === entry.tryLoc) return handle("end");
288
- if (entry.tryLoc <= this.prev) {
289
- var hasCatch = hasOwn.call(entry, "catchLoc"),
290
- hasFinally = hasOwn.call(entry, "finallyLoc");
291
- if (hasCatch && hasFinally) {
292
- if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0);
293
- if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc);
294
- } else if (hasCatch) {
295
- if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0);
296
- } else {
297
- if (!hasFinally) throw new Error("try statement without catch or finally");
298
- if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc);
299
- }
300
- }
301
- }
302
- },
303
- abrupt: function (type, arg) {
304
- for (var i = this.tryEntries.length - 1; i >= 0; --i) {
305
- var entry = this.tryEntries[i];
306
- if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) {
307
- var finallyEntry = entry;
308
- break;
309
- }
310
- }
311
- finallyEntry && ("break" === type || "continue" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null);
312
- var record = finallyEntry ? finallyEntry.completion : {};
313
- return record.type = type, record.arg = arg, finallyEntry ? (this.method = "next", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record);
314
- },
315
- complete: function (record, afterLoc) {
316
- if ("throw" === record.type) throw record.arg;
317
- return "break" === record.type || "continue" === record.type ? this.next = record.arg : "return" === record.type ? (this.rval = this.arg = record.arg, this.method = "return", this.next = "end") : "normal" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel;
318
- },
319
- finish: function (finallyLoc) {
320
- for (var i = this.tryEntries.length - 1; i >= 0; --i) {
321
- var entry = this.tryEntries[i];
322
- if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), ContinueSentinel;
323
- }
324
- },
325
- catch: function (tryLoc) {
326
- for (var i = this.tryEntries.length - 1; i >= 0; --i) {
327
- var entry = this.tryEntries[i];
328
- if (entry.tryLoc === tryLoc) {
329
- var record = entry.completion;
330
- if ("throw" === record.type) {
331
- var thrown = record.arg;
332
- resetTryEntry(entry);
333
- }
334
- return thrown;
335
- }
336
- }
337
- throw new Error("illegal catch attempt");
338
- },
339
- delegateYield: function (iterable, resultName, nextLoc) {
340
- return this.delegate = {
341
- iterator: values(iterable),
342
- resultName: resultName,
343
- nextLoc: nextLoc
344
- }, "next" === this.method && (this.arg = undefined), ContinueSentinel;
345
- }
346
- }, exports;
347
- }
348
- function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
349
- try {
350
- var info = gen[key](arg);
351
- var value = info.value;
352
- } catch (error) {
353
- reject(error);
354
- return;
355
- }
356
- if (info.done) {
357
- resolve(value);
358
- } else {
359
- Promise.resolve(value).then(_next, _throw);
360
- }
361
- }
362
- function _asyncToGenerator(fn) {
363
- return function () {
364
- var self = this,
365
- args = arguments;
366
- return new Promise(function (resolve, reject) {
367
- var gen = fn.apply(self, args);
368
- function _next(value) {
369
- asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
370
- }
371
- function _throw(err) {
372
- asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
373
- }
374
- _next(undefined);
375
- });
376
- };
377
- }
378
- function _extends() {
379
- _extends = Object.assign ? Object.assign.bind() : function (target) {
380
- for (var i = 1; i < arguments.length; i++) {
381
- var source = arguments[i];
382
- for (var key in source) {
383
- if (Object.prototype.hasOwnProperty.call(source, key)) {
384
- target[key] = source[key];
385
- }
386
- }
387
- }
388
- return target;
389
- };
390
- return _extends.apply(this, arguments);
391
- }
392
- function _inheritsLoose(subClass, superClass) {
393
- subClass.prototype = Object.create(superClass.prototype);
394
- subClass.prototype.constructor = subClass;
395
- _setPrototypeOf(subClass, superClass);
396
- }
397
- function _getPrototypeOf(o) {
398
- _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
399
- return o.__proto__ || Object.getPrototypeOf(o);
400
- };
401
- return _getPrototypeOf(o);
402
- }
403
- function _setPrototypeOf(o, p) {
404
- _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
405
- o.__proto__ = p;
406
- return o;
407
- };
408
- return _setPrototypeOf(o, p);
409
- }
410
- function _isNativeReflectConstruct() {
411
- if (typeof Reflect === "undefined" || !Reflect.construct) return false;
412
- if (Reflect.construct.sham) return false;
413
- if (typeof Proxy === "function") return true;
414
- try {
415
- Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));
416
- return true;
417
- } catch (e) {
418
- return false;
419
- }
420
- }
421
- function _construct(Parent, args, Class) {
422
- if (_isNativeReflectConstruct()) {
423
- _construct = Reflect.construct.bind();
424
- } else {
425
- _construct = function _construct(Parent, args, Class) {
426
- var a = [null];
427
- a.push.apply(a, args);
428
- var Constructor = Function.bind.apply(Parent, a);
429
- var instance = new Constructor();
430
- if (Class) _setPrototypeOf(instance, Class.prototype);
431
- return instance;
432
- };
433
- }
434
- return _construct.apply(null, arguments);
435
- }
436
- function _isNativeFunction(fn) {
437
- return Function.toString.call(fn).indexOf("[native code]") !== -1;
438
- }
439
- function _wrapNativeSuper(Class) {
440
- var _cache = typeof Map === "function" ? new Map() : undefined;
441
- _wrapNativeSuper = function _wrapNativeSuper(Class) {
442
- if (Class === null || !_isNativeFunction(Class)) return Class;
443
- if (typeof Class !== "function") {
444
- throw new TypeError("Super expression must either be null or a function");
445
- }
446
- if (typeof _cache !== "undefined") {
447
- if (_cache.has(Class)) return _cache.get(Class);
448
- _cache.set(Class, Wrapper);
449
- }
450
- function Wrapper() {
451
- return _construct(Class, arguments, _getPrototypeOf(this).constructor);
452
- }
453
- Wrapper.prototype = Object.create(Class.prototype, {
454
- constructor: {
455
- value: Wrapper,
456
- enumerable: false,
457
- writable: true,
458
- configurable: true
459
- }
460
- });
461
- return _setPrototypeOf(Wrapper, Class);
462
- };
463
- return _wrapNativeSuper(Class);
464
- }
465
- function _assertThisInitialized(self) {
466
- if (self === void 0) {
467
- throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
468
- }
469
- return self;
470
- }
471
-
472
- var ERROR_MESSAGE_DEPENDS_ON_OTHER_QUEUES = 'Waiting for other swaps to complete';
473
- var ERROR_MESSAGE_WAIT_FOR_WALLET = 'Waiting for connecting wallet';
474
- var ERROR_MESSAGE_WAIT_FOR_WALLET_DESCRIPTION_WRONG_WALLET = function ERROR_MESSAGE_WAIT_FOR_WALLET_DESCRIPTION_WRONG_WALLET(type, address) {
475
- return "Please change your " + (type || 'wallet') + " account to " + (address || 'proper address');
476
- };
477
- var ERROR_MESSAGE_WAIT_FOR_WALLET_DESCRIPTION = function ERROR_MESSAGE_WAIT_FOR_WALLET_DESCRIPTION(type) {
478
- return "Please connect to " + (type || 'your wallet') + " by using bellow button or top right button on page.";
479
- };
480
- var ERROR_MESSAGE_WAIT_FOR_CHANGE_NETWORK = function ERROR_MESSAGE_WAIT_FOR_CHANGE_NETWORK(network) {
481
- return "Please change your network to " + network + ".";
482
- };
483
-
484
- var ERROR_ASSERTION_FAILED = 'Assertion failed (Unexpected behaviour)';
485
- var ERROR_CREATE_TRANSACTION = 'Create transaction failed in Rango Server';
486
- var ERROR_INPUT_WALLET_NOT_FOUND = 'Input wallet not found';
487
- var PrettyError = /*#__PURE__*/function (_Error) {
488
- _inheritsLoose(PrettyError, _Error);
489
- function PrettyError(code, m, root, detail) {
490
- var _this;
491
- _this = _Error.call(this, m) || this;
492
- _this._isPrettyError = true;
493
- Object.setPrototypeOf(_assertThisInitialized(_this), PrettyError.prototype);
494
- PrettyError.prototype._isPrettyError = true;
495
- _this.code = code;
496
- _this.detail = detail;
497
- _this.root = root;
498
- return _this;
499
- }
500
- PrettyError.isPrettyError = function isPrettyError(obj) {
501
- return obj instanceof PrettyError || Object.prototype.hasOwnProperty.call(obj, '_isPrettyError');
502
- };
503
- var _proto = PrettyError.prototype;
504
- _proto.getErrorDetail = function getErrorDetail() {
505
- var rawMessage = typeof this.root === 'object' && this.root && this.root.error ? this.root.error : JSON.stringify(this.root);
506
- var rootStr = typeof this.root === 'string' ? this.root : this.root instanceof Error ? this.root.message : rawMessage;
507
- return {
508
- extraMessage: this.message,
509
- extraMessageDetail: this.detail || rootStr,
510
- extraMessageErrorCode: this.code || null
511
- };
512
- };
513
- PrettyError.AssertionFailed = function AssertionFailed(m) {
514
- return new PrettyError('CLIENT_UNEXPECTED_BEHAVIOUR', ERROR_ASSERTION_FAILED, m);
515
- };
516
- PrettyError.BadStatusCode = function BadStatusCode(message, statusCode) {
517
- return new PrettyError('TX_FAIL', message, null, "status code = " + statusCode);
518
- };
519
- PrettyError.CreateTransaction = function CreateTransaction(detail) {
520
- return new PrettyError('FETCH_TX_FAILED', ERROR_CREATE_TRANSACTION, null, detail);
521
- };
522
- PrettyError.WalletMissing = function WalletMissing() {
523
- return new PrettyError('CLIENT_UNEXPECTED_BEHAVIOUR', ERROR_INPUT_WALLET_NOT_FOUND, null, 'Server requested for a blockchain or address not selected by user');
524
- };
525
- PrettyError.BlockchainMissing = function BlockchainMissing() {
526
- return new PrettyError('CLIENT_UNEXPECTED_BEHAVIOUR', ERROR_INPUT_WALLET_NOT_FOUND, null, 'Server requested for a blockchain or address not selected by user');
527
- };
528
- return PrettyError;
529
- }( /*#__PURE__*/_wrapNativeSuper(Error));
530
- function mapAppErrorCodesToAPIErrorCode(errorCode) {
531
- var defaultErrorCode = 'CLIENT_UNEXPECTED_BEHAVIOUR';
532
- try {
533
- if (!errorCode) return defaultErrorCode;
534
- if (isAPIErrorCode(errorCode)) return errorCode;
535
- if (isSignerErrorCode(errorCode)) {
536
- var _t;
537
- var t = (_t = {}, _t[SignerErrorCode.REJECTED_BY_USER] = 'USER_REJECT', _t[SignerErrorCode.SIGN_TX_ERROR] = 'CALL_WALLET_FAILED', _t[SignerErrorCode.SEND_TX_ERROR] = 'SEND_TX_FAILED', _t[SignerErrorCode.NOT_IMPLEMENTED] = defaultErrorCode, _t[SignerErrorCode.OPERATION_UNSUPPORTED] = defaultErrorCode, _t[SignerErrorCode.UNEXPECTED_BEHAVIOUR] = defaultErrorCode, _t);
538
- return t[errorCode];
539
- }
540
- return defaultErrorCode;
541
- } catch (err) {
542
- return defaultErrorCode;
543
- }
544
- }
545
- var prettifyErrorMessage = function prettifyErrorMessage(obj) {
546
- if (!obj) return {
547
- extraMessage: '',
548
- extraMessageErrorCode: null
549
- };
550
- if (PrettyError.isPrettyError(obj)) return obj.getErrorDetail();
551
- if (SignerError.isSignerError(obj)) {
552
- var t = obj.getErrorDetail();
553
- return {
554
- extraMessage: t.message,
555
- extraMessageDetail: t.detail,
556
- extraMessageErrorCode: t.code
557
- };
558
- }
559
- if (obj instanceof Error) return {
560
- extraMessage: obj.toString(),
561
- extraMessageErrorCode: null
562
- };
563
- if (typeof obj !== 'string') return {
564
- extraMessage: JSON.stringify(obj),
565
- extraMessageErrorCode: null
566
- };
567
- return {
568
- extraMessage: obj,
569
- extraMessageErrorCode: null
570
- };
571
- };
572
-
573
- var numberToString = function numberToString(number, minDecimals, maxDecimals) {
574
- if (minDecimals === void 0) {
575
- minDecimals = null;
576
- }
577
- if (maxDecimals === void 0) {
578
- maxDecimals = null;
579
- }
580
- if (number === null) return '';
581
- if (number === '') return '';
582
- var n = new BigNumber(number);
583
- var roundingMode = 1;
584
- var maxI = 1000;
585
- for (var i = 0; i < 60; i++) {
586
- if (new BigNumber(n.toFixed(i, roundingMode)).eq(n)) {
587
- maxI = i;
588
- break;
589
- }
590
- }
591
- if (n.gte(10000)) return n.toFormat(0, roundingMode);
592
- if (n.gte(1000)) return n.toFormat(Math.min(maxI, Math.min(maxDecimals || 100, Math.max(minDecimals || 0, 1))), roundingMode);
593
- if (n.gte(100)) return n.toFormat(Math.min(maxI, Math.min(maxDecimals || 100, Math.max(minDecimals || 0, 1))), roundingMode);
594
- if (n.gte(1)) return n.toFormat(Math.min(maxI, Math.min(maxDecimals || 100, Math.max(minDecimals || 0, 2))), roundingMode);
595
- if (n.gte(0.01)) return n.toFormat(Math.min(maxI, Math.min(maxDecimals || 100, Math.max(minDecimals || 0, 4))), roundingMode);
596
- for (var _i = minDecimals || 4; _i < 17; _i++) if (n.gte(Math.pow(10, -_i))) return n.toFormat(Math.min(maxI, Math.min(maxDecimals || 100, Math.max(minDecimals || 0, _i))), roundingMode);
597
- if (n.isEqualTo(0)) return '0';
598
- return n.toFormat(Math.min(maxI, Math.min(maxDecimals || 100, Math.max(minDecimals || 0, 8))), roundingMode);
599
- };
600
-
601
- var PendingSwapNetworkStatus;
602
- (function (PendingSwapNetworkStatus) {
603
- PendingSwapNetworkStatus["WaitingForConnectingWallet"] = "waitingForConnectingWallet";
604
- PendingSwapNetworkStatus["WaitingForQueue"] = "waitingForQueue";
605
- PendingSwapNetworkStatus["WaitingForNetworkChange"] = "waitingForNetworkChange";
606
- PendingSwapNetworkStatus["NetworkChanged"] = "networkChanged";
607
- })(PendingSwapNetworkStatus || (PendingSwapNetworkStatus = {}));
608
- var MessageSeverity;
609
- (function (MessageSeverity) {
610
- MessageSeverity["error"] = "error";
611
- MessageSeverity["warning"] = "warning";
612
- MessageSeverity["info"] = "info";
613
- MessageSeverity["success"] = "success";
614
- })(MessageSeverity || (MessageSeverity = {}));
615
- var getCurrentBlockchainOfOrNull = function getCurrentBlockchainOfOrNull(swap, step) {
616
- try {
617
- return getCurrentBlockchainOf(swap, step);
618
- } catch (e) {
619
- return null;
620
- }
621
- };
622
- var getCurrentBlockchainOf = function getCurrentBlockchainOf(swap, step) {
623
- var _step$evmTransaction, _step$evmApprovalTran, _step$starknetTransac, _step$starknetApprova, _step$tronTransaction, _step$tronApprovalTra, _step$cosmosTransacti, _step$solanaTransacti, _step$transferTransac;
624
- var b1 = ((_step$evmTransaction = step.evmTransaction) == null ? void 0 : _step$evmTransaction.blockChain) || ((_step$evmApprovalTran = step.evmApprovalTransaction) == null ? void 0 : _step$evmApprovalTran.blockChain) || ((_step$starknetTransac = step.starknetTransaction) == null ? void 0 : _step$starknetTransac.blockChain) || ((_step$starknetApprova = step.starknetApprovalTransaction) == null ? void 0 : _step$starknetApprova.blockChain) || ((_step$tronTransaction = step.tronTransaction) == null ? void 0 : _step$tronTransaction.blockChain) || ((_step$tronApprovalTra = step.tronApprovalTransaction) == null ? void 0 : _step$tronApprovalTra.blockChain) || ((_step$cosmosTransacti = step.cosmosTransaction) == null ? void 0 : _step$cosmosTransacti.blockChain) || ((_step$solanaTransacti = step.solanaTransaction) == null ? void 0 : _step$solanaTransacti.blockChain);
625
- if (!!b1) return b1;
626
- var transferAddress = (_step$transferTransac = step.transferTransaction) == null ? void 0 : _step$transferTransac.fromWalletAddress;
627
- if (!transferAddress) throw PrettyError.BlockchainMissing();
628
- var blockchain = Object.keys(swap.wallets).find(function (b) {
629
- var _swap$wallets$b;
630
- return ((_swap$wallets$b = swap.wallets[b]) == null ? void 0 : _swap$wallets$b.address) === transferAddress;
631
- }) || null;
632
- if (blockchain == null) throw PrettyError.BlockchainMissing();
633
- // TODO: check why it returns string
634
- return blockchain;
635
- };
636
- var getBlockchainMetaExplorerBaseUrl = function getBlockchainMetaExplorerBaseUrl(blockchainMeta) {
637
- var _blockchainMeta$info;
638
- if (isCosmosBlockchain(blockchainMeta)) return (_blockchainMeta$info = blockchainMeta.info) == null ? void 0 : _blockchainMeta$info.explorerUrlToTx;else if (isEvmBlockchain(blockchainMeta) || isStarknetBlockchain(blockchainMeta) || isTronBlockchain(blockchainMeta)) return blockchainMeta.info.transactionUrl;
639
- return;
640
- };
641
- var getScannerUrl = function getScannerUrl(txHash, network, blockchainMetaMap) {
642
- var blockchainMeta = blockchainMetaMap[network];
643
- var baseUrl = getBlockchainMetaExplorerBaseUrl(blockchainMeta);
644
- if (!baseUrl) return;
645
- if (baseUrl.indexOf('/{txHash}') !== -1) return baseUrl.replace('{txHash}', txHash == null ? void 0 : txHash.toLowerCase());
646
- return baseUrl + "/" + (txHash == null ? void 0 : txHash.toLowerCase());
647
- };
648
- function getNextStep(swap, currentStep) {
649
- return swap.steps.find(function (step) {
650
- return step.status !== 'failed' && step.status !== 'success' && step.id !== currentStep.id;
651
- }) || null;
652
- }
653
- /**
654
- * Returns the wallet address, based on the current step of `PendingSwap`.
655
- */
656
- var getCurrentAddressOf = function getCurrentAddressOf(swap, step) {
657
- var _step$evmTransaction2, _step$evmApprovalTran2, _step$tronTransaction2, _step$tronApprovalTra2, _step$starknetTransac2, _step$starknetApprova2, _step$cosmosTransacti2, _step$solanaTransacti2, _step$transferTransac2, _step$transferTransac3;
658
- var result = swap.wallets[((_step$evmTransaction2 = step.evmTransaction) == null ? void 0 : _step$evmTransaction2.blockChain) || ''] || swap.wallets[((_step$evmApprovalTran2 = step.evmApprovalTransaction) == null ? void 0 : _step$evmApprovalTran2.blockChain) || ''] || swap.wallets[((_step$tronTransaction2 = step.tronTransaction) == null ? void 0 : _step$tronTransaction2.blockChain) || ''] || swap.wallets[((_step$tronApprovalTra2 = step.tronApprovalTransaction) == null ? void 0 : _step$tronApprovalTra2.blockChain) || ''] || swap.wallets[((_step$starknetTransac2 = step.starknetTransaction) == null ? void 0 : _step$starknetTransac2.blockChain) || ''] || swap.wallets[((_step$starknetApprova2 = step.starknetApprovalTransaction) == null ? void 0 : _step$starknetApprova2.blockChain) || ''] || swap.wallets[((_step$cosmosTransacti2 = step.cosmosTransaction) == null ? void 0 : _step$cosmosTransacti2.blockChain) || ''] || swap.wallets[((_step$solanaTransacti2 = step.solanaTransaction) == null ? void 0 : _step$solanaTransacti2.blockChain) || ''] || ((_step$transferTransac2 = step.transferTransaction) != null && _step$transferTransac2.fromWalletAddress ? {
659
- address: (_step$transferTransac3 = step.transferTransaction) == null ? void 0 : _step$transferTransac3.fromWalletAddress
660
- } : null) || null;
661
- if (result == null) throw PrettyError.WalletMissing();
662
- return result.address;
663
- };
664
- function getRelatedWallet(swap, currentStep) {
665
- var walletAddress = getCurrentAddressOf(swap, currentStep);
666
- var walletKV = Object.keys(swap.wallets).map(function (k) {
667
- return {
668
- k: k,
669
- v: swap.wallets[k]
670
- };
671
- }).find(function (_ref) {
672
- var v = _ref.v;
673
- return v.address === walletAddress;
674
- }) || null;
675
- var blockchain = (walletKV == null ? void 0 : walletKV.k) || null;
676
- var wallet = (walletKV == null ? void 0 : walletKV.v) || null;
677
- var walletType = wallet == null ? void 0 : wallet.walletType;
678
- if (wallet === null) throw PrettyError.AssertionFailed("Wallet for source " + blockchain + " not passed: walletType: " + walletType);
679
- return wallet;
680
- }
681
- function getRelatedWalletOrNull(swap, currentStep) {
682
- try {
683
- return getRelatedWallet(swap, currentStep);
684
- } catch (e) {
685
- return null;
686
- }
687
- }
688
- var getUsdPrice = function getUsdPrice(blockchain, symbol, address, allTokens) {
689
- var token = allTokens == null ? void 0 : allTokens.find(function (t) {
690
- var _t$symbol;
691
- return t.blockchain === blockchain && ((_t$symbol = t.symbol) == null ? void 0 : _t$symbol.toUpperCase()) === (symbol == null ? void 0 : symbol.toUpperCase()) && t.address === address;
692
- });
693
- return (token == null ? void 0 : token.usdPrice) || null;
694
- };
695
- function getUsdFeeOfStep(step, allTokens) {
696
- var totalFeeInUsd = new BigNumber(0);
697
- for (var i = 0; i < step.fee.length; i++) {
698
- var fee = step.fee[i];
699
- if (fee.expenseType === 'DECREASE_FROM_OUTPUT') continue;
700
- var unitPrice = getUsdPrice(fee.asset.blockchain, fee.asset.symbol, fee.asset.address, allTokens);
701
- totalFeeInUsd = totalFeeInUsd.plus(new BigNumber(fee.amount).multipliedBy(unitPrice || 0));
702
- }
703
- return totalFeeInUsd;
704
- }
705
- function calculatePendingSwap(inputAmount, bestRoute, wallets, settings, validateBalanceOrFee, meta) {
706
- var _bestRoute$result, _bestRoute$result$swa;
707
- var simulationResult = bestRoute.result;
708
- if (!simulationResult) throw Error('Simulation result should not be null');
709
- return {
710
- creationTime: new Date().getTime().toString(),
711
- finishTime: null,
712
- requestId: bestRoute.requestId || '',
713
- inputAmount: inputAmount,
714
- wallets: wallets,
715
- status: 'running',
716
- isPaused: false,
717
- extraMessage: null,
718
- extraMessageSeverity: null,
719
- extraMessageDetail: null,
720
- extraMessageErrorCode: null,
721
- networkStatusExtraMessage: null,
722
- networkStatusExtraMessageDetail: null,
723
- lastNotificationTime: null,
724
- settings: settings,
725
- simulationResult: simulationResult,
726
- validateBalanceOrFee: validateBalanceOrFee,
727
- steps: ((_bestRoute$result = bestRoute.result) == null ? void 0 : (_bestRoute$result$swa = _bestRoute$result.swaps) == null ? void 0 : _bestRoute$result$swa.map(function (swap, index) {
728
- return {
729
- id: index + 1,
730
- // from
731
- fromBlockchain: swap.from.blockchain,
732
- fromBlockchainLogo: swap.from.blockchainLogo,
733
- fromLogo: swap.from.logo,
734
- fromSymbol: swap.from.symbol,
735
- fromSymbolAddress: swap.from.address,
736
- fromDecimals: swap.from.decimals,
737
- fromAmountPrecision: swap.fromAmountPrecision,
738
- fromAmountMinValue: swap.fromAmountMinValue,
739
- fromAmountMaxValue: swap.fromAmountMaxValue,
740
- fromAmountRestrictionType: swap.fromAmountRestrictionType,
741
- // to
742
- toBlockchain: swap.to.blockchain,
743
- toBlockchainLogo: swap.to.blockchainLogo,
744
- toSymbol: swap.to.symbol,
745
- toSymbolAddress: swap.to.address,
746
- toDecimals: swap.to.decimals,
747
- toLogo: swap.to.logo,
748
- // swapper
749
- swapperId: swap.swapperId,
750
- swapperLogo: swap.swapperLogo,
751
- swapperType: swap.swapperType,
752
- // output, fee, timing
753
- expectedOutputAmountHumanReadable: swap.toAmount,
754
- outputAmount: '',
755
- feeInUsd: meta ? numberToString(getUsdFeeOfStep(swap, meta == null ? void 0 : meta.tokens), null, 8) : null,
756
- estimatedTimeInSeconds: swap.estimatedTimeInSeconds || null,
757
- // status, tracking
758
- status: 'created',
759
- networkStatus: null,
760
- startTransactionTime: new Date().getTime(),
761
- externalTransactionId: null,
762
- executedTransactionId: null,
763
- executedTransactionTime: null,
764
- explorerUrl: null,
765
- diagnosisUrl: null,
766
- trackingCode: null,
767
- internalSteps: null,
768
- // transactions
769
- evmTransaction: null,
770
- evmApprovalTransaction: null,
771
- starknetTransaction: null,
772
- starknetApprovalTransaction: null,
773
- tronTransaction: null,
774
- tronApprovalTransaction: null,
775
- cosmosTransaction: null,
776
- solanaTransaction: null,
777
- transferTransaction: null,
778
- // front fields
779
- hasAlreadyProceededToSign: false
780
- };
781
- })) || []
782
- };
783
- }
784
-
785
- function logRPCError(error, swap, currentStep, walletType) {
786
- try {
787
- captureException(error, {
788
- tags: {
789
- requestId: swap.requestId,
790
- rpc: true,
791
- swapper: (currentStep == null ? void 0 : currentStep.swapperId) || '',
792
- walletType: walletType || ''
793
- },
794
- level: 'warning'
795
- });
796
- } catch (e) {
797
- console.log({
798
- e: e
799
- });
800
- }
801
- }
802
-
803
- var rango = undefined;
804
- var httpService = function httpService() {
805
- if (rango) return rango;
806
- rango = new RangoClient(getConfig('API_KEY'), getConfig('BASE_URL'));
807
- return rango;
808
- };
809
-
810
- var swapClaimedBy = null;
811
- /**
812
- *
813
- * We simply use module-level variable to keep track of which queue has claimed the execution of parallel runnings.
814
- *
815
- */
816
- function claimQueue() {
817
- return {
818
- claimedBy: function claimedBy() {
819
- var _swapClaimedBy;
820
- return (_swapClaimedBy = swapClaimedBy) == null ? void 0 : _swapClaimedBy.id;
821
- },
822
- setClaimer: function setClaimer(queue_id) {
823
- swapClaimedBy = {
824
- id: queue_id
825
- };
826
- },
827
- reset: function reset() {
828
- swapClaimedBy = null;
829
- }
830
- };
831
- }
832
- var swapTransactionToDataMap = {};
833
- function useTransactionsData() {
834
- return {
835
- getTransactionDataByHash: function getTransactionDataByHash(hash) {
836
- return swapTransactionToDataMap[hash] || {};
837
- },
838
- setTransactionDataByHash: function setTransactionDataByHash(hash, data) {
839
- var r = swapTransactionToDataMap[hash];
840
- if (!r) swapTransactionToDataMap[hash] = {};
841
- swapTransactionToDataMap[hash].response = data.response || swapTransactionToDataMap[hash].response;
842
- swapTransactionToDataMap[hash].receiptReceived = data.receiptReceived || swapTransactionToDataMap[hash].receiptReceived || false;
843
- }
844
- };
845
- }
846
- /**
847
- * Sample inputs are:
848
- * - "metamask-ETH"
849
- * - "metamask-BSC-BSC:0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
850
- * - "token-pocket-BSC-BSC:0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
851
- * Returns "wallet and network" separately, even if the wallet is dashed inside.
852
- *
853
- */
854
- function splitWalletNetwork(input) {
855
- var removedAddressInput = (input == null ? void 0 : input.split(':')[0]) || '';
856
- var splittedInput = removedAddressInput.split('-');
857
- var network = splittedInput[splittedInput.length - 1];
858
- var walletNetwork = splittedInput.slice(0, -1);
859
- if (walletNetwork[walletNetwork.length - 1] === network) {
860
- walletNetwork.pop();
861
- }
862
- var wallet = walletNetwork.join('-');
863
- return [wallet, network];
864
- }
865
- /**
866
- *
867
- * Returns `steps`, if it's a `running` swap.
868
- * Each `PendingSwap` has a `steps` inside it, `steps` shows how many tasks should be created and run to finish the swap.
869
- *
870
- */
871
- var getCurrentStep = function getCurrentStep(swap) {
872
- return swap.steps.find(function (step) {
873
- return step.status !== 'failed' && step.status !== 'success';
874
- }) || null;
875
- };
876
- /**
877
- *
878
- * Returns current step transaction
879
- *
880
- */
881
- var getCurrentStepTx = function getCurrentStepTx(currentStep) {
882
- var evmTransaction = currentStep.evmTransaction,
883
- evmApprovalTransaction = currentStep.evmApprovalTransaction,
884
- cosmosTransaction = currentStep.cosmosTransaction,
885
- solanaTransaction = currentStep.solanaTransaction,
886
- transferTransaction = currentStep.transferTransaction,
887
- starknetApprovalTransaction = currentStep.starknetApprovalTransaction,
888
- starknetTransaction = currentStep.starknetTransaction,
889
- tronApprovalTransaction = currentStep.tronApprovalTransaction,
890
- tronTransaction = currentStep.tronTransaction;
891
- return evmTransaction || evmApprovalTransaction || cosmosTransaction || solanaTransaction || transferTransaction || starknetApprovalTransaction || starknetTransaction || tronApprovalTransaction || tronTransaction;
892
- };
893
- /**
894
- *
895
- * Set current step transaction
896
- *
897
- */
898
- var setCurrentStepTx = function setCurrentStepTx(currentStep, transaction) {
899
- currentStep.transferTransaction = null;
900
- currentStep.cosmosTransaction = null;
901
- currentStep.evmTransaction = null;
902
- currentStep.solanaTransaction = null;
903
- currentStep.evmApprovalTransaction = null;
904
- currentStep.starknetApprovalTransaction = null;
905
- currentStep.starknetTransaction = null;
906
- currentStep.tronApprovalTransaction = null;
907
- currentStep.tronTransaction = null;
908
- if (isEvmTransaction(transaction)) {
909
- if (transaction.isApprovalTx) currentStep.evmApprovalTransaction = transaction;else currentStep.evmTransaction = transaction;
910
- } else if (isCosmosTransaction(transaction)) {
911
- currentStep.cosmosTransaction = transaction;
912
- } else if (isSolanaTransaction(transaction)) {
913
- currentStep.solanaTransaction = transaction;
914
- } else if (isTransferTransaction(transaction)) {
915
- currentStep.transferTransaction = transaction;
916
- } else if (isStarknetTransaction(transaction)) {
917
- if (transaction.isApprovalTx) currentStep.starknetApprovalTransaction = transaction;else currentStep.starknetTransaction = transaction;
918
- } else if (isTronTransaction(transaction)) {
919
- if (transaction.isApprovalTx) currentStep.tronApprovalTransaction = transaction;else currentStep.tronTransaction = transaction;
920
- }
921
- return currentStep;
922
- };
923
- /**
924
- *
925
- * Returns current step transaction type
926
- *
927
- */
928
- var getCurrentStepTxType = function getCurrentStepTxType(currentStep) {
929
- var _getCurrentStepTx;
930
- return (_getCurrentStepTx = getCurrentStepTx(currentStep)) == null ? void 0 : _getCurrentStepTx.type;
931
- };
932
- /**
933
- *
934
- * Returns a boolean indicating that current step is an approval tx or not.
935
- *
936
- */
937
- var isApprovalCurrentStepTx = function isApprovalCurrentStepTx(currentStep) {
938
- var evmApprovalTransaction = currentStep.evmApprovalTransaction,
939
- starknetApprovalTransaction = currentStep.starknetApprovalTransaction,
940
- tronApprovalTransaction = currentStep.tronApprovalTransaction;
941
- return !!(evmApprovalTransaction || starknetApprovalTransaction || tronApprovalTransaction);
942
- };
943
- /**
944
- * When we are doing a swap, there are some common fields that will be updated together.
945
- * This function helps us to update a swap status and also it will update some more fields like `extraMessageSeverity` based on the input.
946
- */
947
- function updateSwapStatus(_ref) {
948
- var getStorage = _ref.getStorage,
949
- setStorage = _ref.setStorage,
950
- nextStatus = _ref.nextStatus,
951
- nextStepStatus = _ref.nextStepStatus,
952
- message = _ref.message,
953
- details = _ref.details,
954
- _ref$errorCode = _ref.errorCode,
955
- errorCode = _ref$errorCode === void 0 ? null : _ref$errorCode,
956
- hasAlreadyProceededToSign = _ref.hasAlreadyProceededToSign;
957
- var swap = getStorage().swapDetails;
958
- var currentStep = getCurrentStep(swap);
959
- if (!!nextStepStatus && !!currentStep) currentStep.status = nextStepStatus;
960
- if (nextStatus) swap.status = nextStatus;
961
- swap.hasAlreadyProceededToSign = hasAlreadyProceededToSign;
962
- if (!!nextStatus && ['failed', 'success'].includes(nextStatus)) swap.finishTime = new Date().getTime().toString();
963
- if (!!message || !!details) {
964
- swap.extraMessage = message || '';
965
- swap.extraMessageDetail = details || '';
966
- }
967
- if (!!nextStepStatus && ['failed'].includes(nextStepStatus)) {
968
- var _getRelatedWalletOrNu;
969
- //if user cancel the swap, we should pass relevant reason to the server.
970
- var errorReason = details && details.includes('Warning') ? 'Swap canceled by user.' : details;
971
- var walletType = (_getRelatedWalletOrNu = getRelatedWalletOrNull(swap, currentStep)) == null ? void 0 : _getRelatedWalletOrNu.walletType;
972
- swap.extraMessageSeverity = MessageSeverity.error;
973
- httpService().reportFailure({
974
- requestId: swap.requestId,
975
- step: (currentStep == null ? void 0 : currentStep.id) || 1,
976
- eventType: mapAppErrorCodesToAPIErrorCode(errorCode),
977
- reason: errorReason || '',
978
- data: walletType ? {
979
- wallet: walletType
980
- } : undefined
981
- }).then()["catch"]();
982
- } else if (!!nextStepStatus && ['running'].includes(nextStepStatus)) swap.extraMessageSeverity = MessageSeverity.info;else if (!!nextStepStatus && ['success', 'approved'].includes(nextStepStatus)) swap.extraMessageSeverity = MessageSeverity.success;else if (nextStepStatus && ['waitingForApproval'].includes(nextStepStatus)) swap.extraMessageSeverity = MessageSeverity.warning;
983
- if (nextStepStatus === 'running' && currentStep) currentStep.startTransactionTime = new Date().getTime();
984
- setStorage(_extends({}, getStorage(), {
985
- swapDetails: swap
986
- }));
987
- return {
988
- swap: swap,
989
- step: currentStep
990
- };
991
- }
992
- /**
993
- *
994
- * Set current step transaction hash, update pending swap status, and notify user if needed
995
- *
996
- */
997
- function setStepTransactionIds(_ref2, txId, notifier, eventType, explorerUrl) {
998
- var getStorage = _ref2.getStorage,
999
- setStorage = _ref2.setStorage;
1000
- var swap = getStorage().swapDetails;
1001
- swap.hasAlreadyProceededToSign = null;
1002
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1003
- var currentStep = getCurrentStep(swap);
1004
- currentStep.executedTransactionId = txId;
1005
- currentStep.executedTransactionTime = new Date().getTime().toString();
1006
- if (explorerUrl != null && explorerUrl.url) currentStep.explorerUrl = [].concat(currentStep.explorerUrl || [], [{
1007
- url: explorerUrl.url,
1008
- description: explorerUrl.description || null
1009
- }]);
1010
- if (eventType === 'check_tx_status') {
1011
- swap.extraMessage = 'Checking transaction status ...';
1012
- swap.extraMessageDetail = '';
1013
- swap.extraMessageSeverity = MessageSeverity.info;
1014
- } else if (eventType === 'check_approve_tx_status') {
1015
- swap.extraMessage = 'Checking approve transaction status ...';
1016
- swap.extraMessageDetail = '';
1017
- swap.extraMessageSeverity = MessageSeverity.info;
1018
- }
1019
- setStorage(_extends({}, getStorage(), {
1020
- swapDetails: swap
1021
- }));
1022
- if (eventType) notifier({
1023
- eventType: eventType,
1024
- swap: swap,
1025
- step: currentStep
1026
- });
1027
- }
1028
- /**
1029
- * If a swap needs a wallet to be connected,
1030
- * By calling this function some related fields will be updated to show a correct message and state for notfiying the user.
1031
- */
1032
- function markRunningSwapAsWaitingForConnectingWallet(_ref3, reason, reasonDetail) {
1033
- var getStorage = _ref3.getStorage,
1034
- setStorage = _ref3.setStorage;
1035
- var swap = getStorage().swapDetails;
1036
- var currentStep = getCurrentStep(swap);
1037
- if (!currentStep) return;
1038
- var currentTime = new Date();
1039
- swap.lastNotificationTime = currentTime.getTime().toString();
1040
- var isAlreadyMarked = currentStep.networkStatus === PendingSwapNetworkStatus.WaitingForConnectingWallet && swap.networkStatusExtraMessage === reason && swap.networkStatusExtraMessageDetail === reasonDetail;
1041
- if (isAlreadyMarked) {
1042
- return;
1043
- }
1044
- currentStep.networkStatus = PendingSwapNetworkStatus.WaitingForConnectingWallet;
1045
- swap.networkStatusExtraMessage = reason;
1046
- swap.networkStatusExtraMessageDetail = reasonDetail;
1047
- setStorage(_extends({}, getStorage(), {
1048
- swapDetails: swap
1049
- }));
1050
- }
1051
- /**
1052
- * If a swap needs a certain network to proceed,
1053
- * By calling this function some related fields will be updated to show a correct message and state for notfiying the user.
1054
- */
1055
- function markRunningSwapAsSwitchingNetwork(_ref4) {
1056
- var getStorage = _ref4.getStorage,
1057
- setStorage = _ref4.setStorage;
1058
- var swap = getStorage().swapDetails;
1059
- var currentStep = getCurrentStep(swap);
1060
- if (!currentStep) return;
1061
- // Generate message
1062
- var _getRequiredWallet = getRequiredWallet(swap),
1063
- type = _getRequiredWallet.type;
1064
- var fromBlockchain = getCurrentBlockchainOf(swap, currentStep);
1065
- var reason = "Change " + type + " wallet network to " + fromBlockchain;
1066
- var reasonDetail = "Please change your " + type + " wallet network to " + fromBlockchain + ".";
1067
- var currentTime = new Date();
1068
- swap.lastNotificationTime = currentTime.getTime().toString();
1069
- currentStep.networkStatus = PendingSwapNetworkStatus.WaitingForNetworkChange;
1070
- swap.networkStatusExtraMessage = reason;
1071
- swap.networkStatusExtraMessageDetail = reasonDetail;
1072
- setStorage(_extends({}, getStorage(), {
1073
- swapDetails: swap
1074
- }));
1075
- return {
1076
- swap: swap,
1077
- step: currentStep
1078
- };
1079
- }
1080
- /**
1081
- * We are marking the queue as it depends on other queues to be run (on Parallel mode)
1082
- * By calling this function some related fields will be updated to show a correct message and state for notfiying the user.
1083
- */
1084
- function markRunningSwapAsDependsOnOtherQueues(_ref5) {
1085
- var getStorage = _ref5.getStorage,
1086
- setStorage = _ref5.setStorage,
1087
- notifier = _ref5.notifier;
1088
- var swap = getStorage().swapDetails;
1089
- var currentStep = getCurrentStep(swap);
1090
- if (!currentStep) return;
1091
- swap.networkStatusExtraMessage = '';
1092
- swap.networkStatusExtraMessageDetail = '';
1093
- currentStep.networkStatus = PendingSwapNetworkStatus.WaitingForQueue;
1094
- notifier({
1095
- eventType: 'waiting_for_queue',
1096
- swap: swap,
1097
- step: currentStep
1098
- });
1099
- setStorage(_extends({}, getStorage(), {
1100
- swapDetails: swap
1101
- }));
1102
- return {
1103
- swap: swap,
1104
- step: currentStep
1105
- };
1106
- }
1107
- function delay(ms) {
1108
- return new Promise(function (res) {
1109
- return setTimeout(res, ms);
1110
- });
1111
- }
1112
- /**
1113
- *
1114
- * To execute a swap, we are keeping the user prefrences on what wallet they are going to use for a sepecific blockchain
1115
- * By passing the swap and the network we are looking for, it returns the wallet name that user selected.
1116
- *
1117
- */
1118
- var getSwapWalletType = function getSwapWalletType(swap, network) {
1119
- var _swap$wallets$network;
1120
- return (_swap$wallets$network = swap.wallets[network]) == null ? void 0 : _swap$wallets$network.walletType;
1121
- };
1122
- /**
1123
- *
1124
- * We are keeping the connected wallet in a specific structure (`Wallet`),
1125
- * By using this function we normally want to check a specific wallet is connected and exists or not.
1126
- *
1127
- */
1128
- function isWalletNull(wallet) {
1129
- return wallet === null || (wallet == null ? void 0 : wallet.blockchains) === null || (wallet == null ? void 0 : wallet.blockchains.length) === 0;
1130
- }
1131
- /**
1132
- * On our implementation for `wallets` package, We keep the instance in 2 ways
1133
- * If it's a single chain wallet, it returns the instance directly,
1134
- * If it's a multichain wallet, it returns a `Map` of instances.
1135
- * This function will get the `ETHEREUM` instance in both types.
1136
- */
1137
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1138
- function getEvmProvider(providers, type) {
1139
- if (type && providers[type]) {
1140
- // we need this because provider can return an instance or a map of instances, so what you are doing here is try to detect that.
1141
- if (providers[type].size) return providers[type].get(Network.ETHEREUM);
1142
- return providers[type];
1143
- }
1144
- return null;
1145
- }
1146
- /**
1147
- * In a `PendingSwap`, each step needs a wallet to proceed,
1148
- * By using this function we can access what wallet exactly we need to run current step.
1149
- */
1150
- function getRequiredWallet(swap) {
1151
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1152
- var step = getCurrentStep(swap);
1153
- var bcName = getCurrentBlockchainOfOrNull(swap, step);
1154
- if (!bcName) {
1155
- return {
1156
- type: null,
1157
- network: null,
1158
- address: null
1159
- };
1160
- }
1161
- var walletType = getSwapWalletType(swap, bcName);
1162
- var sourceWallet = swap.wallets[bcName];
1163
- return {
1164
- type: walletType || null,
1165
- network: bcName,
1166
- address: sourceWallet ? sourceWallet.address : null
1167
- };
1168
- }
1169
- /**
1170
- * On EVM compatible wallets, There is one instance with different chains (like Polygon)
1171
- * To get the chain from instance we will use this function.
1172
- */
1173
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1174
- function getChainId(_x) {
1175
- return _getChainId.apply(this, arguments);
1176
- }
1177
- /**
1178
- * For running a swap safely, we need to make sure about the state of wallet
1179
- * which means the netowrk/chain of wallet should be exactly on what a transaction needs.
1180
- */
1181
- function _getChainId() {
1182
- _getChainId = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(provider) {
1183
- var chainId;
1184
- return _regeneratorRuntime().wrap(function _callee$(_context) {
1185
- while (1) switch (_context.prev = _context.next) {
1186
- case 0:
1187
- _context.prev = 0;
1188
- _context.next = 3;
1189
- return provider.request({
1190
- method: 'eth_chainId'
1191
- });
1192
- case 3:
1193
- _context.t0 = _context.sent;
1194
- if (_context.t0) {
1195
- _context.next = 6;
1196
- break;
1197
- }
1198
- _context.t0 = provider == null ? void 0 : provider.chainId;
1199
- case 6:
1200
- chainId = _context.t0;
1201
- return _context.abrupt("return", chainId);
1202
- case 10:
1203
- _context.prev = 10;
1204
- _context.t1 = _context["catch"](0);
1205
- return _context.abrupt("return", provider == null ? void 0 : provider.chainId);
1206
- case 13:
1207
- case "end":
1208
- return _context.stop();
1209
- }
1210
- }, _callee, null, [[0, 10]]);
1211
- }));
1212
- return _getChainId.apply(this, arguments);
1213
- }
1214
- function isNetworkMatchedForTransaction(_x2, _x3, _x4, _x5, _x6) {
1215
- return _isNetworkMatchedForTransaction.apply(this, arguments);
1216
- }
1217
- function _isNetworkMatchedForTransaction() {
1218
- _isNetworkMatchedForTransaction = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(swap, step, wallet, meta, providers) {
1219
- var fromBlockChain, sourceWallet, provider, chainId, blockChain;
1220
- return _regeneratorRuntime().wrap(function _callee2$(_context2) {
1221
- while (1) switch (_context2.prev = _context2.next) {
1222
- case 0:
1223
- if (!isWalletNull(wallet)) {
1224
- _context2.next = 2;
1225
- break;
1226
- }
1227
- return _context2.abrupt("return", false);
1228
- case 2:
1229
- fromBlockChain = getCurrentBlockchainOfOrNull(swap, step);
1230
- if (fromBlockChain) {
1231
- _context2.next = 5;
1232
- break;
1233
- }
1234
- return _context2.abrupt("return", false);
1235
- case 5:
1236
- if (!meta.evmBasedChains.find(function (evmBlochain) {
1237
- return evmBlochain.name === fromBlockChain;
1238
- })) {
1239
- _context2.next = 25;
1240
- break;
1241
- }
1242
- _context2.prev = 6;
1243
- sourceWallet = swap.wallets[fromBlockChain];
1244
- if (!sourceWallet) {
1245
- _context2.next = 19;
1246
- break;
1247
- }
1248
- provider = getEvmProvider(providers, sourceWallet.walletType);
1249
- _context2.next = 12;
1250
- return getChainId(provider);
1251
- case 12:
1252
- chainId = _context2.sent;
1253
- if (!chainId) {
1254
- _context2.next = 19;
1255
- break;
1256
- }
1257
- blockChain = getBlockChainNameFromId(chainId, Object.entries(meta.blockchains).map(function (_ref7) {
1258
- var blockchainMeta = _ref7[1];
1259
- return blockchainMeta;
1260
- }));
1261
- if (!(blockChain && blockChain.toLowerCase() === fromBlockChain.toLowerCase())) {
1262
- _context2.next = 17;
1263
- break;
1264
- }
1265
- return _context2.abrupt("return", true);
1266
- case 17:
1267
- if (!(blockChain && blockChain.toLowerCase() !== fromBlockChain.toLowerCase())) {
1268
- _context2.next = 19;
1269
- break;
1270
- }
1271
- return _context2.abrupt("return", false);
1272
- case 19:
1273
- _context2.next = 24;
1274
- break;
1275
- case 21:
1276
- _context2.prev = 21;
1277
- _context2.t0 = _context2["catch"](6);
1278
- console.log(_context2.t0);
1279
- case 24:
1280
- return _context2.abrupt("return", false);
1281
- case 25:
1282
- return _context2.abrupt("return", true);
1283
- case 26:
1284
- case "end":
1285
- return _context2.stop();
1286
- }
1287
- }, _callee2, null, [[6, 21]]);
1288
- }));
1289
- return _isNetworkMatchedForTransaction.apply(this, arguments);
1290
- }
1291
- var isTxAlreadyCreated = function isTxAlreadyCreated(swap, step) {
1292
- var _step$evmTransaction, _step$evmApprovalTran, _step$tronTransaction, _step$tronApprovalTra, _step$starknetTransac, _step$starknetApprova, _step$cosmosTransacti, _step$solanaTransacti, _step$transferTransac;
1293
- var result = swap.wallets[((_step$evmTransaction = step.evmTransaction) == null ? void 0 : _step$evmTransaction.blockChain) || ''] || swap.wallets[((_step$evmApprovalTran = step.evmApprovalTransaction) == null ? void 0 : _step$evmApprovalTran.blockChain) || ''] || swap.wallets[((_step$tronTransaction = step.tronTransaction) == null ? void 0 : _step$tronTransaction.blockChain) || ''] || swap.wallets[((_step$tronApprovalTra = step.tronApprovalTransaction) == null ? void 0 : _step$tronApprovalTra.blockChain) || ''] || swap.wallets[((_step$starknetTransac = step.starknetTransaction) == null ? void 0 : _step$starknetTransac.blockChain) || ''] || swap.wallets[((_step$starknetApprova = step.starknetApprovalTransaction) == null ? void 0 : _step$starknetApprova.blockChain) || ''] || swap.wallets[((_step$cosmosTransacti = step.cosmosTransaction) == null ? void 0 : _step$cosmosTransacti.blockChain) || ''] || swap.wallets[((_step$solanaTransacti = step.solanaTransaction) == null ? void 0 : _step$solanaTransacti.blockChain) || ''] || ((_step$transferTransac = step.transferTransaction) == null ? void 0 : _step$transferTransac.fromWalletAddress) || null;
1294
- return result !== null;
1295
- };
1296
- function resetNetworkStatus(actions) {
1297
- var getStorage = actions.getStorage,
1298
- setStorage = actions.setStorage;
1299
- var swap = getStorage().swapDetails;
1300
- var currentStep = getCurrentStep(swap);
1301
- if (currentStep != null && currentStep.networkStatus) {
1302
- currentStep.networkStatus = null;
1303
- setStorage(_extends({}, getStorage(), {
1304
- swapDetails: swap
1305
- }));
1306
- }
1307
- }
1308
- function updateNetworkStatus(actions, data) {
1309
- if (data === void 0) {
1310
- data = {
1311
- message: '',
1312
- details: '',
1313
- status: null
1314
- };
1315
- }
1316
- var _data = data,
1317
- message = _data.message,
1318
- details = _data.details,
1319
- status = _data.status;
1320
- var getStorage = actions.getStorage,
1321
- setStorage = actions.setStorage;
1322
- var swap = getStorage().swapDetails;
1323
- var currentStep = getCurrentStep(swap);
1324
- if (currentStep != null && currentStep.networkStatus) {
1325
- swap.networkStatusExtraMessage = message;
1326
- swap.networkStatusExtraMessageDetail = details;
1327
- currentStep.networkStatus = status;
1328
- setStorage(_extends({}, getStorage(), {
1329
- swapDetails: swap
1330
- }));
1331
- }
1332
- }
1333
- /**
1334
- * Event handler for blocked tasks.
1335
- * If a transcation execution is manually blocked (like for parallel or waiting for wallet),
1336
- * This function will be called by queue manager using `queue definition`.
1337
- *
1338
- * It checks if the required wallet is connected, unblock the queue to be run.
1339
- */
1340
- function onBlockForConnectWallet(event, meta) {
1341
- var context = meta.context,
1342
- queue = meta.queue;
1343
- var swap = queue.getStorage().swapDetails;
1344
- var _isRequiredWalletConn = isRequiredWalletConnected(swap, context.state),
1345
- ok = _isRequiredWalletConn.ok,
1346
- reason = _isRequiredWalletConn.reason;
1347
- if (!ok) {
1348
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1349
- var currentStep = getCurrentStep(swap);
1350
- context.notifier({
1351
- eventType: reason === 'account_miss_match' ? 'waiting_for_change_wallet_account' : 'waiting_for_connecting_wallet',
1352
- swap: swap,
1353
- step: currentStep
1354
- });
1355
- markRunningSwapAsWaitingForConnectingWallet({
1356
- getStorage: queue.getStorage.bind(queue),
1357
- setStorage: queue.setStorage.bind(queue)
1358
- }, ERROR_MESSAGE_WAIT_FOR_WALLET, event.reason.description);
1359
- return;
1360
- }
1361
- queue.unblock();
1362
- }
1363
- /**
1364
- * Event handler for blocked tasks.
1365
- * If a transcation execution is manually blocked (like for parallel or waiting for walle),
1366
- * This function will be called by queue manager using `queue definition`.
1367
- *
1368
- * It checks if the required network is connected, unblock the queue to be run.
1369
- * Note: it automatically try to switch the network if its `provider` supports.
1370
- */
1371
- function onBlockForChangeNetwork(_event, meta) {
1372
- var context = meta.context,
1373
- queue = meta.queue;
1374
- var swap = queue.getStorage().swapDetails;
1375
- var currentStep = getCurrentStep(swap);
1376
- if (!currentStep || swap.status !== 'running') return;
1377
- var result = markRunningSwapAsSwitchingNetwork({
1378
- getStorage: queue.getStorage.bind(queue),
1379
- setStorage: queue.setStorage.bind(queue)
1380
- });
1381
- if (result) {
1382
- context.notifier({
1383
- eventType: 'waiting_for_network_change',
1384
- swap: result.swap,
1385
- step: result.step
1386
- });
1387
- }
1388
- // Try to auto switch
1389
- var _getRequiredWallet2 = getRequiredWallet(swap),
1390
- type = _getRequiredWallet2.type,
1391
- network = _getRequiredWallet2.network;
1392
- if (!!type && !!network) {
1393
- if (context.canSwitchNetworkTo(type, network)) {
1394
- var _result = context.switchNetwork(type, network);
1395
- if (_result) {
1396
- _result.then(function () {
1397
- queue.unblock();
1398
- })["catch"](function (error) {
1399
- // ignore switch network errors
1400
- console.log({
1401
- error: error
1402
- });
1403
- });
1404
- }
1405
- }
1406
- }
1407
- }
1408
- /**
1409
- * Event handler for blocked tasks. (Parallel mode)
1410
- * If a transcation execution flow is manually blocked (like for parallel or waiting for walle),
1411
- * This function will be called by queue manager using `queue definition`.
1412
- *
1413
- * It checks the blocked tasks, if there is no active `claimed` queue, try to give it to the best candidate.
1414
- */
1415
- function onDependsOnOtherQueues(_event, meta) {
1416
- var getBlockedTasks = meta.getBlockedTasks,
1417
- forceExecute = meta.forceExecute,
1418
- queue = meta.queue,
1419
- manager = meta.manager,
1420
- context = meta.context;
1421
- var _claimQueue = claimQueue(),
1422
- setClaimer = _claimQueue.setClaimer,
1423
- claimedBy = _claimQueue.claimedBy,
1424
- reset = _claimQueue.reset;
1425
- // We only needs those blocked tasks that have DEPENDS_ON_OTHER_QUEUES reason.
1426
- var blockedTasks = getBlockedTasks().filter(function (task) {
1427
- return task.reason.reason === BlockReason.DEPENDS_ON_OTHER_QUEUES;
1428
- });
1429
- if (blockedTasks.length === 0) {
1430
- return;
1431
- }
1432
- var claimerId = claimedBy();
1433
- var isClaimedByAnyQueue = !!claimerId;
1434
- if (claimerId === queue.id) return;
1435
- // Check if any queue `claimed` before, if yes, we don't should do anything.
1436
- if (isClaimedByAnyQueue) {
1437
- // We need to keep the latest swap messages
1438
- markRunningSwapAsDependsOnOtherQueues({
1439
- getStorage: queue.getStorage.bind(queue),
1440
- setStorage: queue.setStorage.bind(queue),
1441
- notifier: context.notifier
1442
- });
1443
- return;
1444
- }
1445
- // Prioritize current queue to be run first.
1446
- var task = blockedTasks.find(function (task) {
1447
- return task.queue_id === meta.queue_id;
1448
- });
1449
- // If current task isn't available anymore, fallback to first blocked task.
1450
- if (!task) {
1451
- var firstBlockedTask = blockedTasks[0];
1452
- task = firstBlockedTask;
1453
- }
1454
- setClaimer(task.queue_id);
1455
- var claimedStorage = task.storage.get();
1456
- var _getRequiredWallet3 = getRequiredWallet(claimedStorage.swapDetails),
1457
- type = _getRequiredWallet3.type,
1458
- network = _getRequiredWallet3.network,
1459
- address = _getRequiredWallet3.address;
1460
- // Run
1461
- forceExecute(task.queue_id, {
1462
- claimedBy: claimedBy(),
1463
- resetClaimedBy: function resetClaimedBy() {
1464
- reset();
1465
- // TODO: Use key generator
1466
- retryOn(type + "-" + network + ":" + address, context.notifier, manager, context.canSwitchNetworkTo);
1467
- }
1468
- });
1469
- }
1470
- function isRequiredWalletConnected(swap, getState) {
1471
- var _getRequiredWallet4 = getRequiredWallet(swap),
1472
- type = _getRequiredWallet4.type,
1473
- address = _getRequiredWallet4.address;
1474
- if (!type || !address) {
1475
- return {
1476
- ok: false,
1477
- reason: 'not_connected'
1478
- };
1479
- }
1480
- var walletState = getState(type);
1481
- var accounts = walletState.accounts,
1482
- connected = walletState.connected;
1483
- var connectedAccounts = accounts || [];
1484
- if (!connected) return {
1485
- ok: false,
1486
- reason: 'not_connected'
1487
- };
1488
- var matched = connectedAccounts.some(function (account) {
1489
- var _readAccountAddress = readAccountAddress(account),
1490
- accountAddress = _readAccountAddress.address;
1491
- return address.toLocaleLowerCase() === accountAddress.toLocaleLowerCase();
1492
- });
1493
- return {
1494
- ok: matched,
1495
- reason: 'account_miss_match'
1496
- };
1497
- }
1498
- function singTransaction(actions) {
1499
- var _useTransactionsData = useTransactionsData(),
1500
- setTransactionDataByHash = _useTransactionsData.setTransactionDataByHash;
1501
- var getStorage = actions.getStorage,
1502
- setStorage = actions.setStorage,
1503
- failed = actions.failed,
1504
- next = actions.next,
1505
- schedule = actions.schedule,
1506
- context = actions.context;
1507
- var meta = context.meta,
1508
- getSigners = context.getSigners,
1509
- notifier = context.notifier,
1510
- isMobileWallet = context.isMobileWallet;
1511
- var swap = getStorage().swapDetails;
1512
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1513
- var currentStep = getCurrentStep(swap);
1514
- var sourceWallet = getRelatedWallet(swap, currentStep);
1515
- var mobileWallet = isMobileWallet(sourceWallet == null ? void 0 : sourceWallet.walletType);
1516
- var walletAddress = getCurrentAddressOf(swap, currentStep);
1517
- var walletSigners = getSigners(sourceWallet.walletType);
1518
- var currentStepBlockchain = getCurrentBlockchainOf(swap, currentStep);
1519
- var onFinish = function onFinish() {
1520
- // TODO resetClaimedBy is undefined here
1521
- if (actions.context.resetClaimedBy) {
1522
- actions.context.resetClaimedBy();
1523
- }
1524
- };
1525
- var tx = getCurrentStepTx(currentStep);
1526
- var txType = tx == null ? void 0 : tx.type;
1527
- var isApproval = isApprovalCurrentStepTx(currentStep);
1528
- var isSmartContractCall = [TransactionType.EVM, TransactionType.STARKNET, TransactionType.TRON].includes(txType);
1529
- var hasAlreadyProceededToSign = typeof swap.hasAlreadyProceededToSign === 'boolean';
1530
- var nextStatus, nextStepStatus, eventType, message, details;
1531
- if (isApproval) {
1532
- message = "Waiting for approval of " + (currentStep == null ? void 0 : currentStep.fromSymbol) + " coin " + (mobileWallet ? 'on your mobile phone!' : '');
1533
- details = 'Waiting for approve transaction to be mined and confirmed successfully';
1534
- nextStepStatus = 'waitingForApproval';
1535
- nextStatus = undefined;
1536
- eventType = 'confirm_approve_contract';
1537
- } else if (hasAlreadyProceededToSign) {
1538
- message = 'Transaction is expired. Please try again.';
1539
- nextStepStatus = 'failed';
1540
- nextStatus = 'failed';
1541
- details = '';
1542
- eventType = 'transaction_expired';
1543
- } else {
1544
- message = 'Executing transaction ...';
1545
- nextStepStatus = 'running';
1546
- nextStatus = 'running';
1547
- details = "" + (mobileWallet ? 'Check your mobile phone!' : '');
1548
- eventType = isSmartContractCall ? 'calling_smart_contract' : 'confirm_transfer';
1549
- }
1550
- var updateResult = updateSwapStatus({
1551
- getStorage: getStorage,
1552
- setStorage: setStorage,
1553
- nextStepStatus: nextStepStatus,
1554
- nextStatus: nextStatus,
1555
- message: message,
1556
- details: details,
1557
- hasAlreadyProceededToSign: isApproval ? undefined : hasAlreadyProceededToSign,
1558
- errorCode: hasAlreadyProceededToSign ? 'TX_EXPIRED' : undefined
1559
- });
1560
- notifier(_extends({
1561
- eventType: eventType
1562
- }, updateResult));
1563
- if (hasAlreadyProceededToSign) {
1564
- failed();
1565
- onFinish();
1566
- return;
1567
- }
1568
- var signer = walletSigners.getSigner(txType);
1569
- signer.signAndSendTx(tx, walletAddress, null).then(function (_ref6) {
1570
- var hash = _ref6.hash,
1571
- response = _ref6.response;
1572
- var explorerUrl = getScannerUrl(hash, currentStepBlockchain, meta.blockchains);
1573
- setStepTransactionIds(actions, hash, notifier, isApproval ? 'check_approve_tx_status' : 'check_tx_status', explorerUrl ? {
1574
- url: explorerUrl,
1575
- description: isApproval ? 'Approve' : 'Swap'
1576
- } : undefined);
1577
- // response used for evm transactions to get receipt and track replaced
1578
- response && setTransactionDataByHash(hash, {
1579
- response: response
1580
- });
1581
- schedule(SwapActionTypes.CHECK_TRANSACTION_STATUS);
1582
- next();
1583
- onFinish();
1584
- }, function (error) {
1585
- var _error$root, _error$root2, _error$root3;
1586
- if (swap.status === 'failed') return;
1587
- var _prettifyErrorMessage = prettifyErrorMessage(error),
1588
- extraMessage = _prettifyErrorMessage.extraMessage,
1589
- extraMessageDetail = _prettifyErrorMessage.extraMessageDetail,
1590
- extraMessageErrorCode = _prettifyErrorMessage.extraMessageErrorCode;
1591
- // if it is an rpc error with details, send the log to sentry
1592
- if (error && error != null && error.root && error != null && (_error$root = error.root) != null && _error$root.message && error != null && (_error$root2 = error.root) != null && _error$root2.code && error != null && (_error$root3 = error.root) != null && _error$root3.reason) logRPCError(error.root, swap, currentStep, sourceWallet == null ? void 0 : sourceWallet.walletType);
1593
- var updateResult = updateSwapStatus({
1594
- getStorage: getStorage,
1595
- setStorage: setStorage,
1596
- nextStatus: 'failed',
1597
- nextStepStatus: 'failed',
1598
- message: extraMessage,
1599
- details: extraMessageDetail,
1600
- errorCode: extraMessageErrorCode
1601
- });
1602
- var eventType = extraMessageErrorCode === 'REJECTED_BY_USER' ? 'contract_rejected' : isSmartContractCall ? 'smart_contract_call_failed' : 'transfer_failed';
1603
- notifier(_extends({
1604
- eventType: eventType
1605
- }, updateResult));
1606
- failed();
1607
- onFinish();
1608
- });
1609
- }
1610
- function checkWaitingForConnectWalletChange(params) {
1611
- var wallet_network = params.wallet_network,
1612
- evmChains = params.evmChains,
1613
- manager = params.manager;
1614
- var _splitWalletNetwork = splitWalletNetwork(wallet_network),
1615
- wallet = _splitWalletNetwork[0],
1616
- network = _splitWalletNetwork[1];
1617
- // We only need change network for EVM chains.
1618
- if (!evmChains.some(function (chain) {
1619
- return chain.name == network;
1620
- })) return;
1621
- manager == null ? void 0 : manager.getAll().forEach(function (q) {
1622
- var queueStorage = q.list.getStorage();
1623
- var swap = queueStorage == null ? void 0 : queueStorage.swapDetails;
1624
- if (swap && swap.status === 'running') {
1625
- var currentStep = getCurrentStep(swap);
1626
- if (currentStep) {
1627
- var _queueStorage$swapDet;
1628
- var currentStepRequiredWallet = queueStorage == null ? void 0 : (_queueStorage$swapDet = queueStorage.swapDetails.wallets[currentStep.fromBlockchain]) == null ? void 0 : _queueStorage$swapDet.walletType;
1629
- var hasWaitingForConnect = Object.keys(q.list.state.tasks).some(function (taskId) {
1630
- var _task$blockedFor;
1631
- var task = q.list.state.tasks[taskId];
1632
- return task.status === Status.BLOCKED &&
1633
- // TODO double check later
1634
- [BlockReason.WAIT_FOR_CONNECT_WALLET].includes((_task$blockedFor = task.blockedFor) == null ? void 0 : _task$blockedFor.reason);
1635
- });
1636
- if (currentStepRequiredWallet === wallet && hasWaitingForConnect && getCurrentBlockchainOfOrNull(swap, currentStep) != network) {
1637
- var queueInstance = q.list;
1638
- var _getRequiredWallet5 = getRequiredWallet(swap),
1639
- type = _getRequiredWallet5.type;
1640
- var description = ERROR_MESSAGE_WAIT_FOR_CHANGE_NETWORK(type);
1641
- q.list.block({
1642
- reason: {
1643
- reason: BlockReason.WAIT_FOR_NETWORK_CHANGE,
1644
- description: description
1645
- },
1646
- silent: true
1647
- });
1648
- var result = markRunningSwapAsSwitchingNetwork({
1649
- getStorage: queueInstance.getStorage.bind(queueInstance),
1650
- setStorage: queueInstance.setStorage.bind(queueInstance)
1651
- });
1652
- if (result) {
1653
- params == null ? void 0 : params.notifier({
1654
- eventType: 'waiting_for_network_change',
1655
- swap: result.swap,
1656
- step: result.step
1657
- });
1658
- }
1659
- }
1660
- }
1661
- }
1662
- });
1663
- }
1664
- function checkWaitingForNetworkChange(manager) {
1665
- manager == null ? void 0 : manager.getAll().forEach(function (q) {
1666
- var hasWaitingForNetwork = Object.keys(q.list.state.tasks).some(function (taskId) {
1667
- var _task$blockedFor2;
1668
- var task = q.list.state.tasks[taskId];
1669
- return task.status === Status.BLOCKED && [BlockReason.WAIT_FOR_NETWORK_CHANGE, BlockReason.DEPENDS_ON_OTHER_QUEUES].includes((_task$blockedFor2 = task.blockedFor) == null ? void 0 : _task$blockedFor2.reason);
1670
- });
1671
- if (hasWaitingForNetwork) {
1672
- var _q$list$getStorage;
1673
- var swap = (_q$list$getStorage = q.list.getStorage()) == null ? void 0 : _q$list$getStorage.swapDetails;
1674
- if (swap.status === 'running') {
1675
- var _getRequiredWallet6 = getRequiredWallet(swap),
1676
- type = _getRequiredWallet6.type;
1677
- var description = ERROR_MESSAGE_WAIT_FOR_WALLET_DESCRIPTION(type);
1678
- // Change the block reason to waiting for connecting wallet
1679
- q.list.block({
1680
- reason: {
1681
- reason: BlockReason.WAIT_FOR_CONNECT_WALLET,
1682
- description: description
1683
- }
1684
- });
1685
- }
1686
- }
1687
- });
1688
- }
1689
- /**
1690
- * Get list of all running swaps
1691
- *
1692
- * @param manager
1693
- * @returns list of pending swaps
1694
- */
1695
- function getRunningSwaps(manager) {
1696
- var queues = (manager == null ? void 0 : manager.getAll()) || new Map();
1697
- var result = [];
1698
- queues.forEach(function (q) {
1699
- // retry only on affected queues
1700
- var queueStorage = q.list.getStorage();
1701
- var swap = queueStorage == null ? void 0 : queueStorage.swapDetails;
1702
- if (!swap || swap.status !== 'running') return;
1703
- result.push(swap);
1704
- });
1705
- return result;
1706
- }
1707
- /**
1708
- *
1709
- * Trying to reset notifications for pending swaps to correct message on page load.
1710
- * We could remove this after supporting auto connect for wallets.
1711
- *
1712
- * @param swaps
1713
- * @param notifier
1714
- * @returns
1715
- */
1716
- function resetRunningSwapNotifsOnPageLoad(runningSwaps, notifier) {
1717
- runningSwaps.forEach(function (swap) {
1718
- var currentStep = getCurrentStep(swap);
1719
- var eventType;
1720
- if ((currentStep == null ? void 0 : currentStep.networkStatus) === PendingSwapNetworkStatus.WaitingForQueue) eventType = 'waiting_for_queue';else if ((swap == null ? void 0 : swap.status) === 'running') {
1721
- eventType = 'waiting_for_connecting_wallet';
1722
- }
1723
- if (!!eventType && !!notifier) {
1724
- notifier({
1725
- eventType: eventType,
1726
- swap: swap,
1727
- step: currentStep
1728
- });
1729
- }
1730
- });
1731
- }
1732
- /**
1733
- *
1734
- * Try to run blocked tasks by wallet and network name.
1735
- * Goes through queues and extract blocked queues with matched wallet.
1736
- * If found any blocked tasks with same wallet and network, runs them.
1737
- * If not, runs only blocked tasks with matched wallet.
1738
- *
1739
- * @param wallet_network a string includes `wallet` type and `network` type.
1740
- * @param manager
1741
- * @returns
1742
- */
1743
- function retryOn(wallet_network, notifier, manager, canSwitchNetworkTo, options) {
1744
- var _finalQueueToBeRun, _finalQueueToBeRun2;
1745
- if (options === void 0) {
1746
- options = {
1747
- fallbackToOnlyWallet: true
1748
- };
1749
- }
1750
- var _splitWalletNetwork2 = splitWalletNetwork(wallet_network),
1751
- wallet = _splitWalletNetwork2[0],
1752
- network = _splitWalletNetwork2[1];
1753
- if (!wallet || !network) {
1754
- return;
1755
- }
1756
- var walletAndNetworkMatched = [];
1757
- var onlyWalletMatched = [];
1758
- manager == null ? void 0 : manager.getAll().forEach(function (q) {
1759
- // retry only on affected queues
1760
- if (q.status === Status.BLOCKED) {
1761
- var queueStorage = q.list.getStorage();
1762
- var swap = queueStorage == null ? void 0 : queueStorage.swapDetails;
1763
- if (swap && swap.status === 'running') {
1764
- var currentStep = getCurrentStep(swap);
1765
- if (currentStep) {
1766
- var _queueStorage$swapDet2, _queueStorage$swapDet3;
1767
- if (getCurrentBlockchainOfOrNull(swap, currentStep) == network && (queueStorage == null ? void 0 : (_queueStorage$swapDet2 = queueStorage.swapDetails.wallets[network]) == null ? void 0 : _queueStorage$swapDet2.walletType) === wallet) {
1768
- walletAndNetworkMatched.push(q.list);
1769
- } else if ((queueStorage == null ? void 0 : (_queueStorage$swapDet3 = queueStorage.swapDetails.wallets[currentStep.fromBlockchain]) == null ? void 0 : _queueStorage$swapDet3.walletType) === wallet) {
1770
- onlyWalletMatched.push(q.list);
1771
- }
1772
- }
1773
- }
1774
- }
1775
- });
1776
- var finalQueueToBeRun = undefined;
1777
- if (walletAndNetworkMatched.length > 0) {
1778
- finalQueueToBeRun = walletAndNetworkMatched[0];
1779
- if (walletAndNetworkMatched.length > 1) {
1780
- for (var i = 1; i < walletAndNetworkMatched.length; i++) {
1781
- var currentQueue = walletAndNetworkMatched[i];
1782
- markRunningSwapAsDependsOnOtherQueues({
1783
- getStorage: currentQueue.getStorage.bind(currentQueue),
1784
- setStorage: currentQueue.setStorage.bind(currentQueue),
1785
- notifier: notifier
1786
- });
1787
- }
1788
- }
1789
- } else if (onlyWalletMatched.length > 0 && options.fallbackToOnlyWallet) {
1790
- finalQueueToBeRun = onlyWalletMatched[0];
1791
- }
1792
- if (!(canSwitchNetworkTo != null && canSwitchNetworkTo(wallet, network))) (_finalQueueToBeRun = finalQueueToBeRun) == null ? void 0 : _finalQueueToBeRun.unblock();else (_finalQueueToBeRun2 = finalQueueToBeRun) == null ? void 0 : _finalQueueToBeRun2.checkBlock();
1793
- }
1794
- /*
1795
- For avoiding conflict by making too many requests to wallet, we need to make sure
1796
- We only run one request at a time (In parallel mode).
1797
- */
1798
- function isNeedBlockQueueForParallel(step) {
1799
- return !!step.evmTransaction || !!step.evmApprovalTransaction;
1800
- }
1801
- /*
1802
- Create transaction endpoint doesn't return error code on http status code,
1803
- For backward compatibilty with server and sdk, we use this wrapper to reject the promise.
1804
- */
1805
- function throwOnOK(_x7) {
1806
- return _throwOnOK.apply(this, arguments);
1807
- }
1808
- function _throwOnOK() {
1809
- _throwOnOK = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3(rawResponse) {
1810
- var responseBody;
1811
- return _regeneratorRuntime().wrap(function _callee3$(_context3) {
1812
- while (1) switch (_context3.prev = _context3.next) {
1813
- case 0:
1814
- _context3.next = 2;
1815
- return rawResponse;
1816
- case 2:
1817
- responseBody = _context3.sent;
1818
- if (!(!responseBody.ok || !responseBody.transaction)) {
1819
- _context3.next = 5;
1820
- break;
1821
- }
1822
- throw PrettyError.CreateTransaction(responseBody.error || 'bad response from create tx endpoint');
1823
- case 5:
1824
- return _context3.abrupt("return", responseBody);
1825
- case 6:
1826
- case "end":
1827
- return _context3.stop();
1828
- }
1829
- }, _callee3);
1830
- }));
1831
- return _throwOnOK.apply(this, arguments);
1832
- }
1833
- function cancelSwap(swap, manager) {
1834
- var _claimQueue2 = claimQueue(),
1835
- reset = _claimQueue2.reset;
1836
- swap.actions.cancel();
1837
- var updateResult = updateSwapStatus({
1838
- getStorage: swap.actions.getStorage,
1839
- setStorage: swap.actions.setStorage,
1840
- message: 'Swap canceled by user.',
1841
- details: "Warning: If you've already signed and sent a transaction, it won't be affected, but next swap steps will not be executed.",
1842
- nextStatus: 'failed',
1843
- nextStepStatus: 'failed',
1844
- errorCode: 'USER_CANCEL'
1845
- });
1846
- reset();
1847
- if (manager) manager == null ? void 0 : manager.retry();
1848
- return updateResult;
1849
- }
1850
-
1851
- var INTERVAL_FOR_CHECK = 5000;
1852
- /**
1853
- * Subscribe to status of swap transaction by checking from server periodically.
1854
- * After getting the status, notify the user and schedule `SCHEDULE_NEXT_STEP`.
1855
- */
1856
- function checkTransactionStatus(_x) {
1857
- return _checkTransactionStatus.apply(this, arguments);
1858
- }
1859
- /**
1860
- * Subscribe to status of approval transaction by checking from server periodically.
1861
- * After getting the status, notify the user and schedule `SCHEDULE_NEXT_STEP`.
1862
- */
1863
- function _checkTransactionStatus() {
1864
- _checkTransactionStatus = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(_ref) {
1865
- var _status, _status2, _status3, _status4, _status5, _status6, _status7, _status9, _status10, _status11;
1866
- var getStorage, setStorage, next, schedule, retry, failed, context, swap, meta, currentStep, txId, getTxReceiptFailed, status, signer, _useTransactionsData, getTransactionDataByHash, setTransactionDataByHash, txType, sourceWallet, _signer, _getTransactionDataBy, txResponse, receiptReceived, _yield$signer$wait, updatedTxHash, updatedTxResponse, currentStepBlockchain, explorerUrl, _currentStep$explorer, _prettifyErrorMessage, extraMessage, extraMessageDetail, extraMessageErrorCode, updateResult, outputAmount, prevOutputAmount, newTransaction, nextStep, _status8;
1867
- return _regeneratorRuntime().wrap(function _callee$(_context) {
1868
- while (1) switch (_context.prev = _context.next) {
1869
- case 0:
1870
- getStorage = _ref.getStorage, setStorage = _ref.setStorage, next = _ref.next, schedule = _ref.schedule, retry = _ref.retry, failed = _ref.failed, context = _ref.context;
1871
- swap = getStorage().swapDetails;
1872
- meta = context.meta; // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1873
- currentStep = getCurrentStep(swap);
1874
- if (currentStep != null && currentStep.executedTransactionId) {
1875
- _context.next = 6;
1876
- break;
1877
- }
1878
- return _context.abrupt("return");
1879
- case 6:
1880
- txId = currentStep.executedTransactionId;
1881
- getTxReceiptFailed = false;
1882
- status = null;
1883
- signer = null;
1884
- _useTransactionsData = useTransactionsData(), getTransactionDataByHash = _useTransactionsData.getTransactionDataByHash, setTransactionDataByHash = _useTransactionsData.setTransactionDataByHash;
1885
- try {
1886
- txType = getCurrentStepTxType(currentStep);
1887
- sourceWallet = getRelatedWallet(swap, currentStep);
1888
- if (txType && sourceWallet) signer = context.getSigners(sourceWallet.walletType).getSigner(txType);
1889
- } catch (error) {
1890
- // wallet is not connected yet
1891
- // no need to do anything
1892
- }
1893
- _context.prev = 12;
1894
- // if wallet is connected, try to get transaction reciept
1895
- _getTransactionDataBy = getTransactionDataByHash(txId), txResponse = _getTransactionDataBy.response, receiptReceived = _getTransactionDataBy.receiptReceived;
1896
- if (!((_signer = signer) != null && _signer.wait && !receiptReceived)) {
1897
- _context.next = 21;
1898
- break;
1899
- }
1900
- _context.next = 17;
1901
- return signer.wait(txId, txResponse);
1902
- case 17:
1903
- _yield$signer$wait = _context.sent;
1904
- updatedTxHash = _yield$signer$wait.hash;
1905
- updatedTxResponse = _yield$signer$wait.response;
1906
- if (updatedTxHash !== txId) {
1907
- currentStep.executedTransactionId = updatedTxHash || currentStep.executedTransactionId;
1908
- currentStepBlockchain = getCurrentBlockchainOf(swap, currentStep);
1909
- explorerUrl = getScannerUrl(currentStep.executedTransactionId, currentStepBlockchain, meta.blockchains);
1910
- if (explorerUrl) {
1911
- if (currentStep.explorerUrl && ((_currentStep$explorer = currentStep.explorerUrl) == null ? void 0 : _currentStep$explorer.length) >= 1) {
1912
- currentStep.explorerUrl[currentStep.explorerUrl.length - 1] = {
1913
- url: explorerUrl,
1914
- description: 'Replaced Swap'
1915
- };
1916
- }
1917
- }
1918
- txId = currentStep.executedTransactionId;
1919
- if (updatedTxHash && updatedTxResponse) setTransactionDataByHash(updatedTxHash, {
1920
- response: updatedTxResponse
1921
- });
1922
- } else {
1923
- setTransactionDataByHash(updatedTxHash, {
1924
- receiptReceived: true
1925
- });
1926
- }
1927
- case 21:
1928
- _context.next = 29;
1929
- break;
1930
- case 23:
1931
- _context.prev = 23;
1932
- _context.t0 = _context["catch"](12);
1933
- _prettifyErrorMessage = prettifyErrorMessage(_context.t0), extraMessage = _prettifyErrorMessage.extraMessage, extraMessageDetail = _prettifyErrorMessage.extraMessageDetail, extraMessageErrorCode = _prettifyErrorMessage.extraMessageErrorCode;
1934
- updateResult = updateSwapStatus({
1935
- getStorage: getStorage,
1936
- setStorage: setStorage,
1937
- nextStatus: 'failed',
1938
- nextStepStatus: 'failed',
1939
- message: extraMessage,
1940
- details: extraMessageDetail,
1941
- errorCode: extraMessageErrorCode
1942
- });
1943
- context == null ? void 0 : context.notifier(_extends({
1944
- eventType: 'task_failed'
1945
- }, updateResult));
1946
- getTxReceiptFailed = true;
1947
- // We shouldn't return here, because we need to trigger check status job in backend.
1948
- // This is not a ui requirement but the backend one.
1949
- case 29:
1950
- _context.prev = 29;
1951
- _context.next = 32;
1952
- return httpService().checkStatus({
1953
- requestId: swap.requestId,
1954
- txId: txId,
1955
- step: currentStep.id
1956
- });
1957
- case 32:
1958
- status = _context.sent;
1959
- _context.next = 41;
1960
- break;
1961
- case 35:
1962
- _context.prev = 35;
1963
- _context.t1 = _context["catch"](29);
1964
- _context.next = 39;
1965
- return delay(INTERVAL_FOR_CHECK);
1966
- case 39:
1967
- retry();
1968
- return _context.abrupt("return");
1969
- case 41:
1970
- if (!getTxReceiptFailed) {
1971
- _context.next = 43;
1972
- break;
1973
- }
1974
- return _context.abrupt("return", failed());
1975
- case 43:
1976
- if (!((currentStep == null ? void 0 : currentStep.status) === 'failed')) {
1977
- _context.next = 45;
1978
- break;
1979
- }
1980
- return _context.abrupt("return");
1981
- case 45:
1982
- outputAmount = ((_status = status) == null ? void 0 : _status.outputAmount) || (currentStep.outputAmount ? currentStep.outputAmount : null);
1983
- prevOutputAmount = currentStep.outputAmount || null;
1984
- swap.extraMessage = ((_status2 = status) == null ? void 0 : _status2.extraMessage) || swap.extraMessage;
1985
- swap.extraMessageSeverity = MessageSeverity.info;
1986
- swap.extraMessageDetail = '';
1987
- currentStep.status = ((_status3 = status) == null ? void 0 : _status3.status) || currentStep.status;
1988
- currentStep.diagnosisUrl = ((_status4 = status) == null ? void 0 : _status4.diagnosisUrl) || currentStep.diagnosisUrl || null;
1989
- currentStep.outputAmount = outputAmount || currentStep.outputAmount;
1990
- currentStep.explorerUrl = ((_status5 = status) == null ? void 0 : _status5.explorerUrl) || currentStep.explorerUrl;
1991
- currentStep.internalSteps = ((_status6 = status) == null ? void 0 : _status6.steps) || null;
1992
- newTransaction = (_status7 = status) == null ? void 0 : _status7.newTx;
1993
- if (newTransaction) {
1994
- currentStep.status = 'created';
1995
- currentStep.executedTransactionId = null;
1996
- currentStep.executedTransactionTime = null;
1997
- setCurrentStepTx(currentStep, newTransaction);
1998
- }
1999
- if (prevOutputAmount === null && outputAmount !== null) context.notifier({
2000
- eventType: 'step_completed_with_output',
2001
- swap: swap,
2002
- step: currentStep
2003
- });else if (prevOutputAmount === null && outputAmount === null) {
2004
- // it is needed to set notification after reloading the page
2005
- context.notifier({
2006
- eventType: 'check_tx_status',
2007
- swap: swap,
2008
- step: currentStep
2009
- });
2010
- }
2011
- if (currentStep.status === 'success') {
2012
- nextStep = getNextStep(swap, currentStep);
2013
- swap.extraMessageDetail = '';
2014
- swap.extraMessage = nextStep ? "starting next step: " + nextStep.swapperId + ": " + nextStep.fromBlockchain + " -> " + nextStep.toBlockchain : '';
2015
- } else if (currentStep.status === 'failed') {
2016
- swap.extraMessage = 'Transaction failed in blockchain';
2017
- swap.extraMessageSeverity = MessageSeverity.error;
2018
- swap.extraMessageDetail = ((_status8 = status) == null ? void 0 : _status8.extraMessage) || '';
2019
- swap.status = 'failed';
2020
- swap.finishTime = new Date().getTime().toString();
2021
- }
2022
- // Sync data with storage
2023
- setStorage(_extends({}, getStorage(), {
2024
- swapDetails: swap
2025
- }));
2026
- if (!(((_status9 = status) == null ? void 0 : _status9.status) === 'failed')) {
2027
- _context.next = 64;
2028
- break;
2029
- }
2030
- failed();
2031
- _context.next = 72;
2032
- break;
2033
- case 64:
2034
- if (!(((_status10 = status) == null ? void 0 : _status10.status) === 'success' || ((_status11 = status) == null ? void 0 : _status11.status) === 'running' && !!status.newTx)) {
2035
- _context.next = 69;
2036
- break;
2037
- }
2038
- schedule(SwapActionTypes.SCHEDULE_NEXT_STEP);
2039
- next();
2040
- _context.next = 72;
2041
- break;
2042
- case 69:
2043
- _context.next = 71;
2044
- return delay(INTERVAL_FOR_CHECK);
2045
- case 71:
2046
- retry();
2047
- case 72:
2048
- case "end":
2049
- return _context.stop();
2050
- }
2051
- }, _callee, null, [[12, 23], [29, 35]]);
2052
- }));
2053
- return _checkTransactionStatus.apply(this, arguments);
2054
- }
2055
- function checkApprovalStatus(_x2) {
2056
- return _checkApprovalStatus.apply(this, arguments);
2057
- }
2058
- /**
2059
- *
2060
- * For doing a swap the user needs to accept a `contract` so it can use the user balance.
2061
- * There is two types of check status:
2062
- * 1. Checking approval transaction (Give permission to a contract)
2063
- * 2. Checking swap transaction.
2064
- *
2065
- */
2066
- function _checkApprovalStatus() {
2067
- _checkApprovalStatus = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(_ref2) {
2068
- var getStorage, setStorage, next, schedule, retry, failed, context, swap, meta, _useTransactionsData2, getTransactionDataByHash, setTransactionDataByHash, currentStep, txId, signer, txType, sourceWallet, _signer2, _getTransactionDataBy2, txResponse, receiptReceived, _yield$signer$wait2, updatedTxHash, updatedTxResponse, currentStepBlockchain, explorerUrl, _currentStep$explorer2, _prettifyErrorMessage2, extraMessage, extraMessageDetail, extraMessageErrorCode, updateResult, isApproved, response, message, details, _updateResult;
2069
- return _regeneratorRuntime().wrap(function _callee2$(_context2) {
2070
- while (1) switch (_context2.prev = _context2.next) {
2071
- case 0:
2072
- getStorage = _ref2.getStorage, setStorage = _ref2.setStorage, next = _ref2.next, schedule = _ref2.schedule, retry = _ref2.retry, failed = _ref2.failed, context = _ref2.context;
2073
- swap = getStorage().swapDetails;
2074
- meta = context.meta;
2075
- _useTransactionsData2 = useTransactionsData(), getTransactionDataByHash = _useTransactionsData2.getTransactionDataByHash, setTransactionDataByHash = _useTransactionsData2.setTransactionDataByHash;
2076
- currentStep = getCurrentStep(swap);
2077
- if (currentStep) {
2078
- _context2.next = 8;
2079
- break;
2080
- }
2081
- console.log('ignore check status, current step is null');
2082
- return _context2.abrupt("return");
2083
- case 8:
2084
- if (currentStep != null && currentStep.executedTransactionId) {
2085
- _context2.next = 10;
2086
- break;
2087
- }
2088
- return _context2.abrupt("return");
2089
- case 10:
2090
- txId = currentStep.executedTransactionId;
2091
- signer = null;
2092
- try {
2093
- txType = getCurrentStepTxType(currentStep);
2094
- sourceWallet = getRelatedWallet(swap, currentStep);
2095
- if (txType && sourceWallet) signer = context.getSigners(sourceWallet.walletType).getSigner(txType);
2096
- } catch (error) {
2097
- // wallet is not connected yet
2098
- // no need to do anything
2099
- }
2100
- _context2.prev = 13;
2101
- _getTransactionDataBy2 = getTransactionDataByHash(txId), txResponse = _getTransactionDataBy2.response, receiptReceived = _getTransactionDataBy2.receiptReceived; // if wallet is connected, try to get transaction reciept
2102
- if (!((_signer2 = signer) != null && _signer2.wait && !receiptReceived)) {
2103
- _context2.next = 22;
2104
- break;
2105
- }
2106
- _context2.next = 18;
2107
- return signer.wait(txId, txResponse);
2108
- case 18:
2109
- _yield$signer$wait2 = _context2.sent;
2110
- updatedTxHash = _yield$signer$wait2.hash;
2111
- updatedTxResponse = _yield$signer$wait2.response;
2112
- if (updatedTxHash !== txId) {
2113
- currentStep.executedTransactionId = updatedTxHash || currentStep.executedTransactionId;
2114
- currentStepBlockchain = getCurrentBlockchainOf(swap, currentStep);
2115
- explorerUrl = getScannerUrl(currentStep.executedTransactionId, currentStepBlockchain, meta.blockchains);
2116
- if (explorerUrl) {
2117
- if (currentStep.explorerUrl && ((_currentStep$explorer2 = currentStep.explorerUrl) == null ? void 0 : _currentStep$explorer2.length) >= 1) {
2118
- currentStep.explorerUrl[currentStep.explorerUrl.length - 1] = {
2119
- url: explorerUrl,
2120
- description: 'Replaced Approve'
2121
- };
2122
- }
2123
- }
2124
- txId = currentStep.executedTransactionId;
2125
- if (updatedTxHash && updatedTxResponse) setTransactionDataByHash(updatedTxHash, {
2126
- response: updatedTxResponse
2127
- });
2128
- } else {
2129
- setTransactionDataByHash(updatedTxHash, {
2130
- receiptReceived: true
2131
- });
2132
- }
2133
- case 22:
2134
- _context2.next = 30;
2135
- break;
2136
- case 24:
2137
- _context2.prev = 24;
2138
- _context2.t0 = _context2["catch"](13);
2139
- _prettifyErrorMessage2 = prettifyErrorMessage(_context2.t0), extraMessage = _prettifyErrorMessage2.extraMessage, extraMessageDetail = _prettifyErrorMessage2.extraMessageDetail, extraMessageErrorCode = _prettifyErrorMessage2.extraMessageErrorCode;
2140
- updateResult = updateSwapStatus({
2141
- getStorage: getStorage,
2142
- setStorage: setStorage,
2143
- nextStatus: 'failed',
2144
- nextStepStatus: 'failed',
2145
- message: extraMessage,
2146
- details: extraMessageDetail,
2147
- errorCode: extraMessageErrorCode
2148
- });
2149
- context == null ? void 0 : context.notifier(_extends({
2150
- eventType: 'task_failed'
2151
- }, updateResult));
2152
- return _context2.abrupt("return", failed());
2153
- case 30:
2154
- isApproved = false;
2155
- _context2.prev = 31;
2156
- _context2.next = 34;
2157
- return httpService().checkApproval(swap.requestId, currentStep.executedTransactionId);
2158
- case 34:
2159
- response = _context2.sent;
2160
- if (!((currentStep == null ? void 0 : currentStep.status) === 'failed')) {
2161
- _context2.next = 37;
2162
- break;
2163
- }
2164
- return _context2.abrupt("return");
2165
- case 37:
2166
- isApproved = response.isApproved;
2167
- if (!isApproved && (response.txStatus === 'failed' || response.txStatus === 'success')) {
2168
- if (response.txStatus === 'failed') {
2169
- message = 'Approve transaction failed';
2170
- details = 'Smart contract approval tx failed in blockchain.';
2171
- } else {
2172
- message = 'Not enough approval';
2173
- if (response.requiredApprovedAmount && response.currentApprovedAmount) details = "Required approval: " + response.requiredApprovedAmount + ", current approval: " + response.currentApprovedAmount;else details = "You still don't have enough approval for this swap.";
2174
- }
2175
- // approve transaction failed on
2176
- // we should fail the whole swap
2177
- _updateResult = updateSwapStatus({
2178
- getStorage: getStorage,
2179
- setStorage: setStorage,
2180
- nextStatus: 'failed',
2181
- nextStepStatus: 'failed',
2182
- errorCode: 'INSUFFICIENT_APPROVE',
2183
- message: message,
2184
- details: details
2185
- });
2186
- context.notifier(_extends({
2187
- eventType: 'not_enough_approval'
2188
- }, _updateResult));
2189
- failed();
2190
- } else if (!isApproved) {
2191
- // it is needed to set notification after reloading the page
2192
- context.notifier({
2193
- eventType: 'check_approve_tx_status',
2194
- swap: swap,
2195
- step: currentStep
2196
- });
2197
- }
2198
- _context2.next = 44;
2199
- break;
2200
- case 41:
2201
- _context2.prev = 41;
2202
- _context2.t1 = _context2["catch"](31);
2203
- isApproved = false;
2204
- case 44:
2205
- if (!isApproved) {
2206
- _context2.next = 60;
2207
- break;
2208
- }
2209
- currentStep.status = 'approved';
2210
- swap.extraMessage = "Spending " + currentStep.fromSymbol + " approved successfully.";
2211
- swap.extraMessageDetail = null;
2212
- swap.extraMessageSeverity = MessageSeverity.success;
2213
- currentStep.evmApprovalTransaction = null;
2214
- currentStep.executedTransactionId = null;
2215
- currentStep.executedTransactionTime = null;
2216
- currentStep.starknetApprovalTransaction = null;
2217
- currentStep.tronApprovalTransaction = null;
2218
- setStorage(_extends({}, getStorage(), {
2219
- swapDetails: swap
2220
- }));
2221
- context.notifier({
2222
- eventType: 'contract_confirmed',
2223
- swap: swap,
2224
- step: currentStep
2225
- });
2226
- schedule(SwapActionTypes.SCHEDULE_NEXT_STEP);
2227
- next();
2228
- _context2.next = 63;
2229
- break;
2230
- case 60:
2231
- _context2.next = 62;
2232
- return delay(2000);
2233
- case 62:
2234
- retry();
2235
- case 63:
2236
- case "end":
2237
- return _context2.stop();
2238
- }
2239
- }, _callee2, null, [[13, 24], [31, 41]]);
2240
- }));
2241
- return _checkApprovalStatus.apply(this, arguments);
2242
- }
2243
- function checkStatus(_x3) {
2244
- return _checkStatus.apply(this, arguments);
2245
- }
2246
- function _checkStatus() {
2247
- _checkStatus = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3(actions) {
2248
- var swap, currentStep;
2249
- return _regeneratorRuntime().wrap(function _callee3$(_context3) {
2250
- while (1) switch (_context3.prev = _context3.next) {
2251
- case 0:
2252
- swap = actions.getStorage().swapDetails;
2253
- currentStep = getCurrentStep(swap);
2254
- if (currentStep) {
2255
- _context3.next = 5;
2256
- break;
2257
- }
2258
- console.log('ignore check status, current step is null', swap.requestId);
2259
- return _context3.abrupt("return");
2260
- case 5:
2261
- // Reset network status
2262
- // Because when check status is on `loading` or `failed` status, it shows previous message that isn't related to current state.
2263
- resetNetworkStatus(actions);
2264
- if (!(currentStep.status === 'running')) {
2265
- _context3.next = 11;
2266
- break;
2267
- }
2268
- _context3.next = 9;
2269
- return checkTransactionStatus(actions);
2270
- case 9:
2271
- _context3.next = 14;
2272
- break;
2273
- case 11:
2274
- if (!(currentStep.status === 'waitingForApproval')) {
2275
- _context3.next = 14;
2276
- break;
2277
- }
2278
- _context3.next = 14;
2279
- return checkApprovalStatus(actions);
2280
- case 14:
2281
- case "end":
2282
- return _context3.stop();
2283
- }
2284
- }, _callee3);
2285
- }));
2286
- return _checkStatus.apply(this, arguments);
2287
- }
2288
-
2289
- /**
2290
- *
2291
- * When a user asks for a swap, We first create the transaction by sending a request to server
2292
- * Server will return the transaction that need to be sent to wallet.
2293
- * It can be failed if server goes through an error, If not, we will schedule the `EXECTUTE_TRANSACTION`.
2294
- *
2295
- */
2296
- function createTransaction(_x) {
2297
- return _createTransaction.apply(this, arguments);
2298
- }
2299
- function _createTransaction() {
2300
- _createTransaction = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(actions) {
2301
- var setStorage, getStorage, next, schedule, context, swap, currentStep, transaction, request, _yield$throwOnOK, _transaction, _prettifyErrorMessage, extraMessage, extraMessageDetail, updateResult;
2302
- return _regeneratorRuntime().wrap(function _callee$(_context) {
2303
- while (1) switch (_context.prev = _context.next) {
2304
- case 0:
2305
- setStorage = actions.setStorage, getStorage = actions.getStorage, next = actions.next, schedule = actions.schedule, context = actions.context;
2306
- swap = getStorage().swapDetails; // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2307
- currentStep = getCurrentStep(swap);
2308
- transaction = getCurrentStepTx(currentStep);
2309
- if (transaction) {
2310
- _context.next = 25;
2311
- break;
2312
- }
2313
- request = {
2314
- requestId: swap.requestId,
2315
- step: currentStep.id,
2316
- userSettings: {
2317
- slippage: swap.settings.slippage,
2318
- infiniteApprove: swap.settings.infiniteApprove
2319
- },
2320
- validations: {
2321
- balance: swap.validateBalanceOrFee,
2322
- fee: swap.validateBalanceOrFee
2323
- }
2324
- };
2325
- _context.prev = 6;
2326
- _context.next = 9;
2327
- return throwOnOK(httpService().createTransaction(request));
2328
- case 9:
2329
- _yield$throwOnOK = _context.sent;
2330
- _transaction = _yield$throwOnOK.transaction;
2331
- if (_transaction) setCurrentStepTx(currentStep, _transaction);
2332
- setStorage(_extends({}, getStorage(), {
2333
- swapDetails: swap
2334
- }));
2335
- schedule(SwapActionTypes.EXECUTE_TRANSACTION);
2336
- next();
2337
- _context.next = 25;
2338
- break;
2339
- case 17:
2340
- _context.prev = 17;
2341
- _context.t0 = _context["catch"](6);
2342
- swap.status = 'failed';
2343
- swap.finishTime = new Date().getTime().toString();
2344
- _prettifyErrorMessage = prettifyErrorMessage(_context.t0), extraMessage = _prettifyErrorMessage.extraMessage, extraMessageDetail = _prettifyErrorMessage.extraMessageDetail;
2345
- updateResult = updateSwapStatus({
2346
- getStorage: getStorage,
2347
- setStorage: setStorage,
2348
- nextStatus: 'failed',
2349
- nextStepStatus: 'failed',
2350
- message: extraMessage,
2351
- details: extraMessageDetail,
2352
- errorCode: 'FETCH_TX_FAILED'
2353
- });
2354
- context.notifier(_extends({
2355
- eventType: 'task_failed'
2356
- }, updateResult));
2357
- actions.failed();
2358
- case 25:
2359
- case "end":
2360
- return _context.stop();
2361
- }
2362
- }, _callee, null, [[6, 17]]);
2363
- }));
2364
- return _createTransaction.apply(this, arguments);
2365
- }
2366
-
2367
- /**
2368
- * Excecute a created transaction.
2369
- *
2370
- * This function implemented the parallel mode by `claim` mechanism which means
2371
- * All the queues the meet certain situation (like multiple evm transaction) will go through
2372
- * a `claim` mechanims that decides which queue should be run and it blocks other ones.
2373
- *
2374
- * A queue will be go to sign process, if the wallet and network is matched.
2375
- */
2376
- function executeTransaction(_x) {
2377
- return _executeTransaction.apply(this, arguments);
2378
- }
2379
- function _executeTransaction() {
2380
- _executeTransaction = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(actions) {
2381
- var _context$_queue;
2382
- var getStorage, context, meta, wallets, providers, _claimQueue, claimedBy, isClaimed, requestBlock, swap, currentStep, isWrongAddress, _wallets$blockchains, _getRequiredWallet, type, address, isWalletInCompatible, description, blockedFor, networkMatched, claimerId, isClaimedByAnyQueue, details, _blockedFor, fromBlockchain, _details, _blockedFor2, needsToBlockQueue, _blockedFor3;
2383
- return _regeneratorRuntime().wrap(function _callee$(_context) {
2384
- while (1) switch (_context.prev = _context.next) {
2385
- case 0:
2386
- getStorage = actions.getStorage, context = actions.context;
2387
- meta = context.meta, wallets = context.wallets, providers = context.providers;
2388
- _claimQueue = claimQueue(), claimedBy = _claimQueue.claimedBy;
2389
- isClaimed = context.claimedBy === ((_context$_queue = context._queue) == null ? void 0 : _context$_queue.id);
2390
- requestBlock = function requestBlock(blockedFor) {
2391
- actions.block(blockedFor);
2392
- if (isClaimed && actions.context.resetClaimedBy) {
2393
- actions.context.resetClaimedBy();
2394
- }
2395
- };
2396
- swap = getStorage().swapDetails; // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2397
- currentStep = getCurrentStep(swap); // Resetting network status, so we will set it again during the running of this task.
2398
- resetNetworkStatus(actions);
2399
- /* Make sure wallet is connected and also the connected wallet is matched with tx by checking address. */
2400
- isWrongAddress = !isRequiredWalletConnected(swap, context.state).ok;
2401
- if (!isWrongAddress) {
2402
- _context.next = 16;
2403
- break;
2404
- }
2405
- _getRequiredWallet = getRequiredWallet(swap), type = _getRequiredWallet.type, address = _getRequiredWallet.address;
2406
- isWalletInCompatible = wallets == null ? void 0 : (_wallets$blockchains = wallets.blockchains) == null ? void 0 : _wallets$blockchains.find(function (w) {
2407
- var _w$accounts;
2408
- return !((_w$accounts = w.accounts) != null && _w$accounts.find(function (account) {
2409
- return account.walletType === type;
2410
- }));
2411
- });
2412
- description = !wallets || isWalletInCompatible ? ERROR_MESSAGE_WAIT_FOR_WALLET_DESCRIPTION(type) : ERROR_MESSAGE_WAIT_FOR_WALLET_DESCRIPTION_WRONG_WALLET(type, address);
2413
- blockedFor = {
2414
- reason: BlockReason.WAIT_FOR_CONNECT_WALLET,
2415
- description: description
2416
- };
2417
- requestBlock(blockedFor);
2418
- return _context.abrupt("return");
2419
- case 16:
2420
- _context.next = 18;
2421
- return isNetworkMatchedForTransaction(swap, currentStep, wallets, meta, providers);
2422
- case 18:
2423
- networkMatched = _context.sent;
2424
- claimerId = claimedBy();
2425
- isClaimedByAnyQueue = !!claimerId && !isClaimed;
2426
- if (!(isClaimedByAnyQueue && !networkMatched)) {
2427
- _context.next = 28;
2428
- break;
2429
- }
2430
- details = ERROR_MESSAGE_DEPENDS_ON_OTHER_QUEUES;
2431
- _blockedFor = {
2432
- reason: BlockReason.DEPENDS_ON_OTHER_QUEUES,
2433
- details: details
2434
- };
2435
- requestBlock(_blockedFor);
2436
- return _context.abrupt("return");
2437
- case 28:
2438
- if (networkMatched) {
2439
- _context.next = 36;
2440
- break;
2441
- }
2442
- fromBlockchain = getCurrentBlockchainOf(swap, currentStep);
2443
- _details = ERROR_MESSAGE_WAIT_FOR_CHANGE_NETWORK(fromBlockchain);
2444
- _blockedFor2 = {
2445
- reason: BlockReason.WAIT_FOR_NETWORK_CHANGE,
2446
- details: _details
2447
- };
2448
- requestBlock(_blockedFor2);
2449
- return _context.abrupt("return");
2450
- case 36:
2451
- // Update network to mark it as network changed successfully.
2452
- updateNetworkStatus(actions, {
2453
- message: '',
2454
- details: 'Wallet network changed successfully',
2455
- status: PendingSwapNetworkStatus.NetworkChanged
2456
- });
2457
- case 37:
2458
- /*
2459
- For avoiding conflict by making too many requests to wallet, we need to make sure
2460
- We only run one request at a time (In parallel mode).
2461
- */
2462
- needsToBlockQueue = isNeedBlockQueueForParallel(currentStep);
2463
- if (!(needsToBlockQueue && !isClaimed)) {
2464
- _context.next = 42;
2465
- break;
2466
- }
2467
- _blockedFor3 = {
2468
- reason: BlockReason.DEPENDS_ON_OTHER_QUEUES,
2469
- description: ERROR_MESSAGE_DEPENDS_ON_OTHER_QUEUES,
2470
- details: {}
2471
- };
2472
- requestBlock(_blockedFor3);
2473
- return _context.abrupt("return");
2474
- case 42:
2475
- // All the conditions are met. We can safely send the tx to wallet for sign.
2476
- singTransaction(actions);
2477
- case 43:
2478
- case "end":
2479
- return _context.stop();
2480
- }
2481
- }, _callee);
2482
- }));
2483
- return _executeTransaction.apply(this, arguments);
2484
- }
2485
-
2486
- /**
2487
- *
2488
- * This function is responsibe for scheduling the correct `action` based on `PendingSwap` status.
2489
- * It means `action`s schedule this step to decide what should be the next step/task.
2490
- *
2491
- * It's acts like a `while(true)` and will `break` the loop on certain `action`s like `CHECK_STATUS`.
2492
- *
2493
- *
2494
- */
2495
- function scheduleNextStep(_ref) {
2496
- var schedule = _ref.schedule,
2497
- next = _ref.next,
2498
- failed = _ref.failed,
2499
- setStorage = _ref.setStorage,
2500
- getStorage = _ref.getStorage,
2501
- context = _ref.context;
2502
- var swap = getStorage().swapDetails;
2503
- var currentStep = getCurrentStep(swap);
2504
- var isFailed = swap.steps.find(function (step) {
2505
- return step.status === 'failed';
2506
- });
2507
- if (!!currentStep && !isFailed) {
2508
- if (isTxAlreadyCreated(swap, currentStep)) {
2509
- schedule(SwapActionTypes.EXECUTE_TRANSACTION);
2510
- return next();
2511
- }
2512
- if (currentStep != null && currentStep.executedTransactionId) {
2513
- schedule(SwapActionTypes.CHECK_TRANSACTION_STATUS);
2514
- return next();
2515
- }
2516
- swap.status = 'running';
2517
- setStorage(_extends({}, getStorage(), {
2518
- swapDetails: swap
2519
- }));
2520
- schedule(SwapActionTypes.CREATE_TRANSACTION);
2521
- next();
2522
- } else {
2523
- swap.status = isFailed ? 'failed' : 'success';
2524
- swap.finishTime = new Date().getTime().toString();
2525
- setStorage(_extends({}, getStorage(), {
2526
- swapDetails: swap
2527
- }));
2528
- context.notifier({
2529
- eventType: isFailed ? 'task_failed' : 'task_completed',
2530
- swap: swap,
2531
- step: null
2532
- });
2533
- if (isFailed) failed();else next();
2534
- }
2535
- }
2536
-
2537
- function start(_ref) {
2538
- var schedule = _ref.schedule,
2539
- next = _ref.next;
2540
- schedule(SwapActionTypes.SCHEDULE_NEXT_STEP);
2541
- next();
2542
- }
2543
-
2544
- var _actions;
2545
- /**
2546
- *
2547
- * The idea behind this queue is to be able dynamically add some steps.
2548
- * After running a swap, it can be blocked (like on waiting for switch netwrok)
2549
- * or waits for something happend (like checking status of a transaction from server)
2550
- *
2551
- */
2552
- var swapQueueDef = {
2553
- name: 'swap',
2554
- actions: (_actions = {}, _actions[SwapActionTypes.START] = start, _actions[SwapActionTypes.SCHEDULE_NEXT_STEP] = scheduleNextStep, _actions[SwapActionTypes.CREATE_TRANSACTION] = createTransaction, _actions[SwapActionTypes.EXECUTE_TRANSACTION] = executeTransaction, _actions[SwapActionTypes.CHECK_TRANSACTION_STATUS] = checkStatus, _actions),
2555
- run: [SwapActionTypes.START],
2556
- whenTaskBlocked: function whenTaskBlocked(event, meta) {
2557
- if (event.reason.reason === BlockReason.WAIT_FOR_CONNECT_WALLET) {
2558
- onBlockForConnectWallet(event, meta);
2559
- } else if (event.reason.reason === BlockReason.WAIT_FOR_NETWORK_CHANGE) {
2560
- onBlockForChangeNetwork(event, meta);
2561
- } else if (event.reason.reason === BlockReason.DEPENDS_ON_OTHER_QUEUES) {
2562
- onDependsOnOtherQueues(event, meta);
2563
- }
2564
- }
2565
- };
2566
-
2567
- var MIGRATED_KEY = 'migratedToQueueManager';
2568
- /**
2569
- *
2570
- * If `MIGRATED_KEY` is set, it means we already migrated data from localstorage.
2571
- *
2572
- */
2573
- function migrated() {
2574
- return !!window.localStorage.getItem(MIGRATED_KEY);
2575
- }
2576
- function hasQueueManagerOnIDB() {
2577
- return _hasQueueManagerOnIDB.apply(this, arguments);
2578
- }
2579
- /**
2580
- *
2581
- * By calling this function, we first check if the data already migrated or not,
2582
- * If not, starting to migrating to IndexedDb with proper format that queue manager is understand.
2583
- *
2584
- */
2585
- function _hasQueueManagerOnIDB() {
2586
- _hasQueueManagerOnIDB = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
2587
- return _regeneratorRuntime().wrap(function _callee$(_context) {
2588
- while (1) switch (_context.prev = _context.next) {
2589
- case 0:
2590
- _context.prev = 0;
2591
- _context.next = 3;
2592
- return window.indexedDB.databases();
2593
- case 3:
2594
- return _context.abrupt("return", _context.sent.map(function (db) {
2595
- return db.name;
2596
- }).includes(DB_NAME));
2597
- case 6:
2598
- _context.prev = 6;
2599
- _context.t0 = _context["catch"](0);
2600
- return _context.abrupt("return", false);
2601
- case 9:
2602
- case "end":
2603
- return _context.stop();
2604
- }
2605
- }, _callee, null, [[0, 6]]);
2606
- }));
2607
- return _hasQueueManagerOnIDB.apply(this, arguments);
2608
- }
2609
- function migration() {
2610
- return _migration.apply(this, arguments);
2611
- }
2612
- function _migration() {
2613
- _migration = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2() {
2614
- var swapsFromStorage, hasIndexDB, swaps, convertedSwaps, persistor, promises;
2615
- return _regeneratorRuntime().wrap(function _callee2$(_context2) {
2616
- while (1) switch (_context2.prev = _context2.next) {
2617
- case 0:
2618
- swapsFromStorage = window.localStorage.getItem('pendingSwaps');
2619
- _context2.next = 3;
2620
- return hasQueueManagerOnIDB();
2621
- case 3:
2622
- hasIndexDB = _context2.sent;
2623
- if (!(!swapsFromStorage || migrated() || hasIndexDB)) {
2624
- _context2.next = 6;
2625
- break;
2626
- }
2627
- return _context2.abrupt("return", true);
2628
- case 6:
2629
- // For old users, but they didn't do any swaps yet.
2630
- swaps = JSON.parse(swapsFromStorage);
2631
- convertedSwaps = [];
2632
- swaps.forEach(function (swap) {
2633
- /*
2634
- For running task we need to add some more work
2635
- We need to create a queue task to be run and resume the running task from queue manager.
2636
- */
2637
- if (swap.status === 'running') {
2638
- var _tasks;
2639
- var taskId = v4();
2640
- var convertedSwap = {
2641
- id: swap.requestId,
2642
- createdAt: Number(swap.creationTime),
2643
- name: 'swap',
2644
- status: Status.RUNNING,
2645
- storage: {
2646
- swapDetails: swap
2647
- },
2648
- state: {
2649
- status: Status.RUNNING,
2650
- activeTaskIndex: 0,
2651
- tasks: (_tasks = {}, _tasks[taskId] = {
2652
- blockedFor: null,
2653
- status: Status.RUNNING
2654
- }, _tasks)
2655
- },
2656
- tasks: [{
2657
- id: taskId,
2658
- action: SwapActionTypes.SCHEDULE_NEXT_STEP
2659
- }]
2660
- };
2661
- convertedSwaps.push(convertedSwap);
2662
- } else {
2663
- /*
2664
- * For failed or successful swaps, we only move it to IndexedDB,
2665
- * And there is no need to consider them to be run.
2666
- */
2667
- var status = swap.status === 'success' ? Status.SUCCESS : Status.FAILED;
2668
- var _convertedSwap = {
2669
- id: swap.requestId,
2670
- createdAt: Number(swap.creationTime),
2671
- name: 'swap',
2672
- status: status,
2673
- storage: {
2674
- swapDetails: swap
2675
- },
2676
- state: {
2677
- status: status,
2678
- activeTaskIndex: 0,
2679
- tasks: {}
2680
- },
2681
- tasks: []
2682
- };
2683
- convertedSwaps.push(_convertedSwap);
2684
- }
2685
- });
2686
- // Getting an instance from persistor, so we can directly put our data inside it.
2687
- persistor = new Persistor();
2688
- promises = convertedSwaps.map(function (queue) {
2689
- return persistor.insertQueue(queue);
2690
- });
2691
- _context2.next = 13;
2692
- return Promise.all(promises);
2693
- case 13:
2694
- // Mark as the data has been successfully migrated.
2695
- window.localStorage.setItem(MIGRATED_KEY, '1');
2696
- return _context2.abrupt("return", true);
2697
- case 15:
2698
- case "end":
2699
- return _context2.stop();
2700
- }
2701
- }, _callee2);
2702
- }));
2703
- return _migration.apply(this, arguments);
2704
- }
2705
-
2706
- var isCalled = 0;
2707
- /**
2708
- *
2709
- * Runs a migration (old swaps from localstorage to queue manager's IndexedDB)
2710
- * It will be run only once on page load.
2711
- *
2712
- */
2713
- function useMigration() {
2714
- var isMigrated = migrated();
2715
- var _useState = useState(isMigrated),
2716
- status = _useState[0],
2717
- setStatus = _useState[1];
2718
- useEffect(function () {
2719
- _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
2720
- return _regeneratorRuntime().wrap(function _callee$(_context) {
2721
- while (1) switch (_context.prev = _context.next) {
2722
- case 0:
2723
- if (!isCalled) {
2724
- _context.next = 2;
2725
- break;
2726
- }
2727
- return _context.abrupt("return");
2728
- case 2:
2729
- isCalled = 1;
2730
- migration()["finally"](function () {
2731
- setStatus(true);
2732
- });
2733
- case 4:
2734
- case "end":
2735
- return _context.stop();
2736
- }
2737
- }, _callee);
2738
- }))();
2739
- }, []);
2740
- return {
2741
- status: status
2742
- };
2743
- }
2744
- /**
2745
- *
2746
- * On initial load and also connect/disconnet we may need to update swap's notified message.
2747
- * And also if a new wallet is connected we will retry the queue to see we can resume it or not.
2748
- *
2749
- */
2750
- function useQueueManager(params) {
2751
- var _useManager = useManager(),
2752
- manager = _useManager.manager;
2753
- useEffect(function () {
2754
- if (params.lastConnectedWallet) {
2755
- checkWaitingForConnectWalletChange({
2756
- evmChains: params.evmChains,
2757
- wallet_network: params.lastConnectedWallet,
2758
- manager: manager,
2759
- notifier: params.notifier
2760
- });
2761
- retryOn(params.lastConnectedWallet, params.notifier, manager, params.canSwitchNetworkTo);
2762
- }
2763
- }, [params.lastConnectedWallet]);
2764
- useEffect(function () {
2765
- if (params.disconnectedWallet) {
2766
- checkWaitingForNetworkChange(manager);
2767
- /*
2768
- We need to reset the state value, so if a wallet disconnected twice (after reconnect),
2769
- this effect will be run properly.
2770
- */
2771
- params.clearDisconnectedWallet();
2772
- }
2773
- }, [params.disconnectedWallet]);
2774
- }
2775
-
2776
- function makeQueueDefinition(configs) {
2777
- initConfig(configs);
2778
- return swapQueueDef;
2779
- }
2780
-
2781
- export { MessageSeverity, PendingSwapNetworkStatus, PrettyError, calculatePendingSwap, cancelSwap, checkWaitingForNetworkChange, getCurrentBlockchainOfOrNull, getCurrentStep, getEvmProvider, getRelatedWallet, getRelatedWalletOrNull, getRequiredWallet, getRunningSwaps, makeQueueDefinition, prettifyErrorMessage, resetRunningSwapNotifsOnPageLoad, splitWalletNetwork, updateSwapStatus, useMigration, useQueueManager };
2782
- //# sourceMappingURL=queue-manager-rango-preset.esm.js.map