@rango-dev/queue-manager-rango-preset 0.1.15-next.7 → 0.1.15-next.9

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