@rango-dev/queue-manager-rango-preset 0.1.10-next.77

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 (57) hide show
  1. package/dist/actions/checkStatus.d.ts +12 -0
  2. package/dist/actions/checkStatus.d.ts.map +1 -0
  3. package/dist/actions/createTransaction.d.ts +11 -0
  4. package/dist/actions/createTransaction.d.ts.map +1 -0
  5. package/dist/actions/executeTransaction.d.ts +13 -0
  6. package/dist/actions/executeTransaction.d.ts.map +1 -0
  7. package/dist/actions/scheduleNextStep.d.ts +13 -0
  8. package/dist/actions/scheduleNextStep.d.ts.map +1 -0
  9. package/dist/actions/start.d.ts +4 -0
  10. package/dist/actions/start.d.ts.map +1 -0
  11. package/dist/constants.d.ts +9 -0
  12. package/dist/constants.d.ts.map +1 -0
  13. package/dist/helpers.d.ts +159 -0
  14. package/dist/helpers.d.ts.map +1 -0
  15. package/dist/hooks.d.ts +19 -0
  16. package/dist/hooks.d.ts.map +1 -0
  17. package/dist/index.d.ts +10 -0
  18. package/dist/index.d.ts.map +1 -0
  19. package/dist/index.js +8 -0
  20. package/dist/migration.d.ts +15 -0
  21. package/dist/migration.d.ts.map +1 -0
  22. package/dist/queue-manager-rango-preset.cjs.development.js +2249 -0
  23. package/dist/queue-manager-rango-preset.cjs.development.js.map +1 -0
  24. package/dist/queue-manager-rango-preset.cjs.production.min.js +2 -0
  25. package/dist/queue-manager-rango-preset.cjs.production.min.js.map +1 -0
  26. package/dist/queue-manager-rango-preset.esm.js +2242 -0
  27. package/dist/queue-manager-rango-preset.esm.js.map +1 -0
  28. package/dist/queueDef.d.ts +10 -0
  29. package/dist/queueDef.d.ts.map +1 -0
  30. package/dist/shared-api.d.ts +10 -0
  31. package/dist/shared-api.d.ts.map +1 -0
  32. package/dist/shared-errors.d.ts +56 -0
  33. package/dist/shared-errors.d.ts.map +1 -0
  34. package/dist/shared-sentry.d.ts +4 -0
  35. package/dist/shared-sentry.d.ts.map +1 -0
  36. package/dist/shared.d.ts +149 -0
  37. package/dist/shared.d.ts.map +1 -0
  38. package/dist/types.d.ts +46 -0
  39. package/dist/types.d.ts.map +1 -0
  40. package/package.json +59 -0
  41. package/readme.md +9 -0
  42. package/src/actions/checkStatus.ts +213 -0
  43. package/src/actions/createTransaction.ts +101 -0
  44. package/src/actions/executeTransaction.ts +117 -0
  45. package/src/actions/scheduleNextStep.ts +60 -0
  46. package/src/actions/start.ts +10 -0
  47. package/src/constants.ts +23 -0
  48. package/src/helpers.ts +1252 -0
  49. package/src/hooks.ts +75 -0
  50. package/src/index.ts +39 -0
  51. package/src/migration.ts +112 -0
  52. package/src/queueDef.ts +39 -0
  53. package/src/shared-api.ts +175 -0
  54. package/src/shared-errors.ts +156 -0
  55. package/src/shared-sentry.ts +24 -0
  56. package/src/shared.ts +333 -0
  57. package/src/types.ts +76 -0
@@ -0,0 +1,2242 @@
1
+ import BigNumber$1, { BigNumber } from 'bignumber.js';
2
+ import { WalletError, isWalletErrorCode, WalletErrorCode, TransactionType, getBlockChainNameFromId, WalletType, Network } from '@rango-dev/wallets-shared';
3
+ import { readAccountAddress } from '@rango-dev/wallets-core';
4
+ import { Status } from '@rango-dev/queue-manager-core';
5
+ import { captureException } from '@sentry/browser';
6
+
7
+ var SwapActionTypes;
8
+ (function (SwapActionTypes) {
9
+ SwapActionTypes["START"] = "START";
10
+ SwapActionTypes["SCHEDULE_NEXT_STEP"] = "SCHEDULE_NEXT_STEP";
11
+ SwapActionTypes["CREATE_TRANSACTION"] = "CREATE_TRANSACTION";
12
+ SwapActionTypes["EXECUTE_TRANSACTION"] = "EXECUTE_TRANSACTION";
13
+ SwapActionTypes["CHECK_TRANSACTION_STATUS"] = "CHECK_TRANSACTION_STATUS";
14
+ })(SwapActionTypes || (SwapActionTypes = {}));
15
+ var BlockReason;
16
+ (function (BlockReason) {
17
+ BlockReason["WAIT_FOR_CONNECT_WALLET"] = "waiting_for_connecting_wallet";
18
+ BlockReason["WAIT_FOR_NETWORK_CHANGE"] = "waiting_for_network_change";
19
+ BlockReason["DEPENDS_ON_OTHER_QUEUES"] = "depends_on_other_queues";
20
+ })(BlockReason || (BlockReason = {}));
21
+
22
+ function _regeneratorRuntime() {
23
+ _regeneratorRuntime = function () {
24
+ return exports;
25
+ };
26
+ var exports = {},
27
+ Op = Object.prototype,
28
+ hasOwn = Op.hasOwnProperty,
29
+ defineProperty = Object.defineProperty || function (obj, key, desc) {
30
+ obj[key] = desc.value;
31
+ },
32
+ $Symbol = "function" == typeof Symbol ? Symbol : {},
33
+ iteratorSymbol = $Symbol.iterator || "@@iterator",
34
+ asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator",
35
+ toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag";
36
+ function define(obj, key, value) {
37
+ return Object.defineProperty(obj, key, {
38
+ value: value,
39
+ enumerable: !0,
40
+ configurable: !0,
41
+ writable: !0
42
+ }), obj[key];
43
+ }
44
+ try {
45
+ define({}, "");
46
+ } catch (err) {
47
+ define = function (obj, key, value) {
48
+ return obj[key] = value;
49
+ };
50
+ }
51
+ function wrap(innerFn, outerFn, self, tryLocsList) {
52
+ var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator,
53
+ generator = Object.create(protoGenerator.prototype),
54
+ context = new Context(tryLocsList || []);
55
+ return defineProperty(generator, "_invoke", {
56
+ value: makeInvokeMethod(innerFn, self, context)
57
+ }), generator;
58
+ }
59
+ function tryCatch(fn, obj, arg) {
60
+ try {
61
+ return {
62
+ type: "normal",
63
+ arg: fn.call(obj, arg)
64
+ };
65
+ } catch (err) {
66
+ return {
67
+ type: "throw",
68
+ arg: err
69
+ };
70
+ }
71
+ }
72
+ exports.wrap = wrap;
73
+ var ContinueSentinel = {};
74
+ function Generator() {}
75
+ function GeneratorFunction() {}
76
+ function GeneratorFunctionPrototype() {}
77
+ var IteratorPrototype = {};
78
+ define(IteratorPrototype, iteratorSymbol, function () {
79
+ return this;
80
+ });
81
+ var getProto = Object.getPrototypeOf,
82
+ NativeIteratorPrototype = getProto && getProto(getProto(values([])));
83
+ NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype);
84
+ var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype);
85
+ function defineIteratorMethods(prototype) {
86
+ ["next", "throw", "return"].forEach(function (method) {
87
+ define(prototype, method, function (arg) {
88
+ return this._invoke(method, arg);
89
+ });
90
+ });
91
+ }
92
+ function AsyncIterator(generator, PromiseImpl) {
93
+ function invoke(method, arg, resolve, reject) {
94
+ var record = tryCatch(generator[method], generator, arg);
95
+ if ("throw" !== record.type) {
96
+ var result = record.arg,
97
+ value = result.value;
98
+ return value && "object" == typeof value && hasOwn.call(value, "__await") ? PromiseImpl.resolve(value.__await).then(function (value) {
99
+ invoke("next", value, resolve, reject);
100
+ }, function (err) {
101
+ invoke("throw", err, resolve, reject);
102
+ }) : PromiseImpl.resolve(value).then(function (unwrapped) {
103
+ result.value = unwrapped, resolve(result);
104
+ }, function (error) {
105
+ return invoke("throw", error, resolve, reject);
106
+ });
107
+ }
108
+ reject(record.arg);
109
+ }
110
+ var previousPromise;
111
+ defineProperty(this, "_invoke", {
112
+ value: function (method, arg) {
113
+ function callInvokeWithMethodAndArg() {
114
+ return new PromiseImpl(function (resolve, reject) {
115
+ invoke(method, arg, resolve, reject);
116
+ });
117
+ }
118
+ return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg();
119
+ }
120
+ });
121
+ }
122
+ function makeInvokeMethod(innerFn, self, context) {
123
+ var state = "suspendedStart";
124
+ return function (method, arg) {
125
+ if ("executing" === state) throw new Error("Generator is already running");
126
+ if ("completed" === state) {
127
+ if ("throw" === method) throw arg;
128
+ return doneResult();
129
+ }
130
+ for (context.method = method, context.arg = arg;;) {
131
+ var delegate = context.delegate;
132
+ if (delegate) {
133
+ var delegateResult = maybeInvokeDelegate(delegate, context);
134
+ if (delegateResult) {
135
+ if (delegateResult === ContinueSentinel) continue;
136
+ return delegateResult;
137
+ }
138
+ }
139
+ if ("next" === context.method) context.sent = context._sent = context.arg;else if ("throw" === context.method) {
140
+ if ("suspendedStart" === state) throw state = "completed", context.arg;
141
+ context.dispatchException(context.arg);
142
+ } else "return" === context.method && context.abrupt("return", context.arg);
143
+ state = "executing";
144
+ var record = tryCatch(innerFn, self, context);
145
+ if ("normal" === record.type) {
146
+ if (state = context.done ? "completed" : "suspendedYield", record.arg === ContinueSentinel) continue;
147
+ return {
148
+ value: record.arg,
149
+ done: context.done
150
+ };
151
+ }
152
+ "throw" === record.type && (state = "completed", context.method = "throw", context.arg = record.arg);
153
+ }
154
+ };
155
+ }
156
+ function maybeInvokeDelegate(delegate, context) {
157
+ var methodName = context.method,
158
+ method = delegate.iterator[methodName];
159
+ 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;
160
+ var record = tryCatch(method, delegate.iterator, context.arg);
161
+ if ("throw" === record.type) return context.method = "throw", context.arg = record.arg, context.delegate = null, ContinueSentinel;
162
+ var info = record.arg;
163
+ 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);
164
+ }
165
+ function pushTryEntry(locs) {
166
+ var entry = {
167
+ tryLoc: locs[0]
168
+ };
169
+ 1 in locs && (entry.catchLoc = locs[1]), 2 in locs && (entry.finallyLoc = locs[2], entry.afterLoc = locs[3]), this.tryEntries.push(entry);
170
+ }
171
+ function resetTryEntry(entry) {
172
+ var record = entry.completion || {};
173
+ record.type = "normal", delete record.arg, entry.completion = record;
174
+ }
175
+ function Context(tryLocsList) {
176
+ this.tryEntries = [{
177
+ tryLoc: "root"
178
+ }], tryLocsList.forEach(pushTryEntry, this), this.reset(!0);
179
+ }
180
+ function values(iterable) {
181
+ if (iterable) {
182
+ var iteratorMethod = iterable[iteratorSymbol];
183
+ if (iteratorMethod) return iteratorMethod.call(iterable);
184
+ if ("function" == typeof iterable.next) return iterable;
185
+ if (!isNaN(iterable.length)) {
186
+ var i = -1,
187
+ next = function next() {
188
+ for (; ++i < iterable.length;) if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next;
189
+ return next.value = undefined, next.done = !0, next;
190
+ };
191
+ return next.next = next;
192
+ }
193
+ }
194
+ return {
195
+ next: doneResult
196
+ };
197
+ }
198
+ function doneResult() {
199
+ return {
200
+ value: undefined,
201
+ done: !0
202
+ };
203
+ }
204
+ return GeneratorFunction.prototype = GeneratorFunctionPrototype, defineProperty(Gp, "constructor", {
205
+ value: GeneratorFunctionPrototype,
206
+ configurable: !0
207
+ }), defineProperty(GeneratorFunctionPrototype, "constructor", {
208
+ value: GeneratorFunction,
209
+ configurable: !0
210
+ }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction"), exports.isGeneratorFunction = function (genFun) {
211
+ var ctor = "function" == typeof genFun && genFun.constructor;
212
+ return !!ctor && (ctor === GeneratorFunction || "GeneratorFunction" === (ctor.displayName || ctor.name));
213
+ }, exports.mark = function (genFun) {
214
+ return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, "GeneratorFunction")), genFun.prototype = Object.create(Gp), genFun;
215
+ }, exports.awrap = function (arg) {
216
+ return {
217
+ __await: arg
218
+ };
219
+ }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () {
220
+ return this;
221
+ }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) {
222
+ void 0 === PromiseImpl && (PromiseImpl = Promise);
223
+ var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl);
224
+ return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) {
225
+ return result.done ? result.value : iter.next();
226
+ });
227
+ }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, "Generator"), define(Gp, iteratorSymbol, function () {
228
+ return this;
229
+ }), define(Gp, "toString", function () {
230
+ return "[object Generator]";
231
+ }), exports.keys = function (val) {
232
+ var object = Object(val),
233
+ keys = [];
234
+ for (var key in object) keys.push(key);
235
+ return keys.reverse(), function next() {
236
+ for (; keys.length;) {
237
+ var key = keys.pop();
238
+ if (key in object) return next.value = key, next.done = !1, next;
239
+ }
240
+ return next.done = !0, next;
241
+ };
242
+ }, exports.values = values, Context.prototype = {
243
+ constructor: Context,
244
+ reset: function (skipTempReset) {
245
+ 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);
246
+ },
247
+ stop: function () {
248
+ this.done = !0;
249
+ var rootRecord = this.tryEntries[0].completion;
250
+ if ("throw" === rootRecord.type) throw rootRecord.arg;
251
+ return this.rval;
252
+ },
253
+ dispatchException: function (exception) {
254
+ if (this.done) throw exception;
255
+ var context = this;
256
+ function handle(loc, caught) {
257
+ return record.type = "throw", record.arg = exception, context.next = loc, caught && (context.method = "next", context.arg = undefined), !!caught;
258
+ }
259
+ for (var i = this.tryEntries.length - 1; i >= 0; --i) {
260
+ var entry = this.tryEntries[i],
261
+ record = entry.completion;
262
+ if ("root" === entry.tryLoc) return handle("end");
263
+ if (entry.tryLoc <= this.prev) {
264
+ var hasCatch = hasOwn.call(entry, "catchLoc"),
265
+ hasFinally = hasOwn.call(entry, "finallyLoc");
266
+ if (hasCatch && hasFinally) {
267
+ if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0);
268
+ if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc);
269
+ } else if (hasCatch) {
270
+ if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0);
271
+ } else {
272
+ if (!hasFinally) throw new Error("try statement without catch or finally");
273
+ if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc);
274
+ }
275
+ }
276
+ }
277
+ },
278
+ abrupt: function (type, arg) {
279
+ for (var i = this.tryEntries.length - 1; i >= 0; --i) {
280
+ var entry = this.tryEntries[i];
281
+ if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) {
282
+ var finallyEntry = entry;
283
+ break;
284
+ }
285
+ }
286
+ finallyEntry && ("break" === type || "continue" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null);
287
+ var record = finallyEntry ? finallyEntry.completion : {};
288
+ return record.type = type, record.arg = arg, finallyEntry ? (this.method = "next", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record);
289
+ },
290
+ complete: function (record, afterLoc) {
291
+ if ("throw" === record.type) throw record.arg;
292
+ 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;
293
+ },
294
+ finish: function (finallyLoc) {
295
+ for (var i = this.tryEntries.length - 1; i >= 0; --i) {
296
+ var entry = this.tryEntries[i];
297
+ if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), ContinueSentinel;
298
+ }
299
+ },
300
+ catch: function (tryLoc) {
301
+ for (var i = this.tryEntries.length - 1; i >= 0; --i) {
302
+ var entry = this.tryEntries[i];
303
+ if (entry.tryLoc === tryLoc) {
304
+ var record = entry.completion;
305
+ if ("throw" === record.type) {
306
+ var thrown = record.arg;
307
+ resetTryEntry(entry);
308
+ }
309
+ return thrown;
310
+ }
311
+ }
312
+ throw new Error("illegal catch attempt");
313
+ },
314
+ delegateYield: function (iterable, resultName, nextLoc) {
315
+ return this.delegate = {
316
+ iterator: values(iterable),
317
+ resultName: resultName,
318
+ nextLoc: nextLoc
319
+ }, "next" === this.method && (this.arg = undefined), ContinueSentinel;
320
+ }
321
+ }, exports;
322
+ }
323
+ function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
324
+ try {
325
+ var info = gen[key](arg);
326
+ var value = info.value;
327
+ } catch (error) {
328
+ reject(error);
329
+ return;
330
+ }
331
+ if (info.done) {
332
+ resolve(value);
333
+ } else {
334
+ Promise.resolve(value).then(_next, _throw);
335
+ }
336
+ }
337
+ function _asyncToGenerator(fn) {
338
+ return function () {
339
+ var self = this,
340
+ args = arguments;
341
+ return new Promise(function (resolve, reject) {
342
+ var gen = fn.apply(self, args);
343
+ function _next(value) {
344
+ asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
345
+ }
346
+ function _throw(err) {
347
+ asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
348
+ }
349
+ _next(undefined);
350
+ });
351
+ };
352
+ }
353
+ function _extends() {
354
+ _extends = Object.assign ? Object.assign.bind() : function (target) {
355
+ for (var i = 1; i < arguments.length; i++) {
356
+ var source = arguments[i];
357
+ for (var key in source) {
358
+ if (Object.prototype.hasOwnProperty.call(source, key)) {
359
+ target[key] = source[key];
360
+ }
361
+ }
362
+ }
363
+ return target;
364
+ };
365
+ return _extends.apply(this, arguments);
366
+ }
367
+ function _inheritsLoose(subClass, superClass) {
368
+ subClass.prototype = Object.create(superClass.prototype);
369
+ subClass.prototype.constructor = subClass;
370
+ _setPrototypeOf(subClass, superClass);
371
+ }
372
+ function _getPrototypeOf(o) {
373
+ _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
374
+ return o.__proto__ || Object.getPrototypeOf(o);
375
+ };
376
+ return _getPrototypeOf(o);
377
+ }
378
+ function _setPrototypeOf(o, p) {
379
+ _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
380
+ o.__proto__ = p;
381
+ return o;
382
+ };
383
+ return _setPrototypeOf(o, p);
384
+ }
385
+ function _isNativeReflectConstruct() {
386
+ if (typeof Reflect === "undefined" || !Reflect.construct) return false;
387
+ if (Reflect.construct.sham) return false;
388
+ if (typeof Proxy === "function") return true;
389
+ try {
390
+ Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));
391
+ return true;
392
+ } catch (e) {
393
+ return false;
394
+ }
395
+ }
396
+ function _construct(Parent, args, Class) {
397
+ if (_isNativeReflectConstruct()) {
398
+ _construct = Reflect.construct.bind();
399
+ } else {
400
+ _construct = function _construct(Parent, args, Class) {
401
+ var a = [null];
402
+ a.push.apply(a, args);
403
+ var Constructor = Function.bind.apply(Parent, a);
404
+ var instance = new Constructor();
405
+ if (Class) _setPrototypeOf(instance, Class.prototype);
406
+ return instance;
407
+ };
408
+ }
409
+ return _construct.apply(null, arguments);
410
+ }
411
+ function _isNativeFunction(fn) {
412
+ return Function.toString.call(fn).indexOf("[native code]") !== -1;
413
+ }
414
+ function _wrapNativeSuper(Class) {
415
+ var _cache = typeof Map === "function" ? new Map() : undefined;
416
+ _wrapNativeSuper = function _wrapNativeSuper(Class) {
417
+ if (Class === null || !_isNativeFunction(Class)) return Class;
418
+ if (typeof Class !== "function") {
419
+ throw new TypeError("Super expression must either be null or a function");
420
+ }
421
+ if (typeof _cache !== "undefined") {
422
+ if (_cache.has(Class)) return _cache.get(Class);
423
+ _cache.set(Class, Wrapper);
424
+ }
425
+ function Wrapper() {
426
+ return _construct(Class, arguments, _getPrototypeOf(this).constructor);
427
+ }
428
+ Wrapper.prototype = Object.create(Class.prototype, {
429
+ constructor: {
430
+ value: Wrapper,
431
+ enumerable: false,
432
+ writable: true,
433
+ configurable: true
434
+ }
435
+ });
436
+ return _setPrototypeOf(Wrapper, Class);
437
+ };
438
+ return _wrapNativeSuper(Class);
439
+ }
440
+ function _assertThisInitialized(self) {
441
+ if (self === void 0) {
442
+ throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
443
+ }
444
+ return self;
445
+ }
446
+
447
+ var RANGO_DAPP_ID_QUERY = process.env.REACT_APP_RANGO_DAPP_ID_QUERY;
448
+ var BASE_URL = process.env.REACT_APP_BASE_URL;
449
+ var RANGO_COOKIE_HEADER = 'X-Rango-Id';
450
+ var ERROR_MESSAGE_WAIT_FOR_WALLET = 'Waiting for connecting wallet';
451
+ var ERROR_MESSAGE_WAIT_FOR_WALLET_DESCRIPTION_WRONG_WALLET = function ERROR_MESSAGE_WAIT_FOR_WALLET_DESCRIPTION_WRONG_WALLET(type, address) {
452
+ return "Please change your " + (type || 'wallet') + " account to " + (address || 'proper address');
453
+ };
454
+ var ERROR_MESSAGE_WAIT_FOR_WALLET_DESCRIPTION = function ERROR_MESSAGE_WAIT_FOR_WALLET_DESCRIPTION(type) {
455
+ return "Please connect to " + (type || 'your wallet') + " by using bellow button or top right button on page.";
456
+ };
457
+ var ERROR_MESSAGE_WAIT_FOR_CHANGE_NETWORK = function ERROR_MESSAGE_WAIT_FOR_CHANGE_NETWORK(network) {
458
+ return "Please change your network to " + network + ".";
459
+ };
460
+
461
+ var APIErrorCode;
462
+ (function (APIErrorCode) {
463
+ APIErrorCode["TX_FAIL"] = "TX_FAIL";
464
+ APIErrorCode["FETCH_TX_FAILED"] = "FETCH_TX_FAILED";
465
+ APIErrorCode["USER_REJECT"] = "USER_REJECT";
466
+ APIErrorCode["CALL_WALLET_FAILED"] = "CALL_WALLET_FAILED";
467
+ APIErrorCode["SEND_TX_FAILED"] = "SEND_TX_FAILED";
468
+ APIErrorCode["CALL_OR_SEND_FAILED"] = "CALL_OR_SEND_FAILED";
469
+ APIErrorCode["USER_CANCEL"] = "USER_CANCEL";
470
+ APIErrorCode["CLIENT_UNEXPECTED_BEHAVIOUR"] = "CLIENT_UNEXPECTED_BEHAVIOUR";
471
+ })(APIErrorCode || (APIErrorCode = {}));
472
+ var ApiMethodName;
473
+ (function (ApiMethodName) {
474
+ ApiMethodName["RequestingSwapTransaction"] = "Requesting Swap Transaction";
475
+ ApiMethodName["CreatingSwap"] = "Creating Swap";
476
+ ApiMethodName["CheckingTransactionStatus"] = "Checking transaction status";
477
+ ApiMethodName["CreateTransaction"] = "Create Transaction";
478
+ ApiMethodName["CheckApproval"] = "Check TX Approval";
479
+ ApiMethodName["GettingSwapDetail"] = "Getting Swap Detail";
480
+ ApiMethodName["GettingUserLimits"] = "Getting user limits";
481
+ })(ApiMethodName || (ApiMethodName = {}));
482
+ var TransactionName;
483
+ (function (TransactionName) {
484
+ TransactionName["GenericTransaction"] = "transaction";
485
+ TransactionName["SendingOneInchTransaction"] = "1inch transaction";
486
+ TransactionName["Approval"] = "approve transaction";
487
+ })(TransactionName || (TransactionName = {}));
488
+ var ERROR_ASSERTION_FAILED = 'Assertion failed (Unexpected behaviour)';
489
+ var ERROR_COMMUNICATING_WITH_API = function ERROR_COMMUNICATING_WITH_API(apiMethodName) {
490
+ return "Unexpected response from API (" + apiMethodName + ")";
491
+ };
492
+ var ERROR_CREATE_TRANSACTION = 'Create transaction failed in Rango Server';
493
+ var ERROR_INPUT_WALLET_NOT_FOUND = 'Input wallet not found';
494
+ var PrettyError = /*#__PURE__*/function (_Error) {
495
+ _inheritsLoose(PrettyError, _Error);
496
+ function PrettyError(code, m, root, detail) {
497
+ var _this;
498
+ _this = _Error.call(this, m) || this;
499
+ Object.setPrototypeOf(_assertThisInitialized(_this), PrettyError.prototype);
500
+ _this.code = code;
501
+ _this.detail = detail;
502
+ _this.root = root;
503
+ return _this;
504
+ }
505
+ var _proto = PrettyError.prototype;
506
+ _proto.getErrorDetail = function getErrorDetail() {
507
+ var rawMessage = typeof this.root === 'object' && this.root && this.root.error ? this.root.error : JSON.stringify(this.root);
508
+ var rootStr = typeof this.root === 'string' ? this.root : this.root instanceof Error ? this.root.message : rawMessage;
509
+ return {
510
+ extraMessage: this.message,
511
+ extraMessageDetail: this.detail || rootStr,
512
+ extraMessageErrorCode: this.code || null
513
+ };
514
+ };
515
+ PrettyError.AssertionFailed = function AssertionFailed(m) {
516
+ return new PrettyError(APIErrorCode.CLIENT_UNEXPECTED_BEHAVIOUR, ERROR_ASSERTION_FAILED, m);
517
+ };
518
+ PrettyError.BadStatusCode = function BadStatusCode(message, statusCode) {
519
+ return new PrettyError(APIErrorCode.TX_FAIL, message, null, "status code = " + statusCode);
520
+ };
521
+ PrettyError.CreateTransaction = function CreateTransaction(detail) {
522
+ return new PrettyError(APIErrorCode.FETCH_TX_FAILED, ERROR_CREATE_TRANSACTION, null, detail);
523
+ };
524
+ PrettyError.WalletMissing = function WalletMissing() {
525
+ return new PrettyError(APIErrorCode.CLIENT_UNEXPECTED_BEHAVIOUR, ERROR_INPUT_WALLET_NOT_FOUND, null, 'Server requested for a blockchain or address not selected by user');
526
+ };
527
+ PrettyError.BlockchainMissing = function BlockchainMissing() {
528
+ return new PrettyError(APIErrorCode.CLIENT_UNEXPECTED_BEHAVIOUR, ERROR_INPUT_WALLET_NOT_FOUND, null, 'Server requested for a blockchain or address not selected by user');
529
+ };
530
+ return PrettyError;
531
+ }( /*#__PURE__*/_wrapNativeSuper(Error));
532
+
533
+ var PendingSwapNetworkStatus;
534
+ (function (PendingSwapNetworkStatus) {
535
+ PendingSwapNetworkStatus["WaitingForConnectingWallet"] = "waitingForConnectingWallet";
536
+ PendingSwapNetworkStatus["WaitingForQueue"] = "waitingForQueue";
537
+ PendingSwapNetworkStatus["WaitingForNetworkChange"] = "waitingForNetworkChange";
538
+ PendingSwapNetworkStatus["NetworkChanged"] = "networkChanged";
539
+ })(PendingSwapNetworkStatus || (PendingSwapNetworkStatus = {}));
540
+ var MessageSeverity;
541
+ (function (MessageSeverity) {
542
+ MessageSeverity["error"] = "error";
543
+ MessageSeverity["warning"] = "warning";
544
+ MessageSeverity["info"] = "info";
545
+ MessageSeverity["success"] = "success";
546
+ })(MessageSeverity || (MessageSeverity = {}));
547
+ var getCurrentBlockchainOfOrNull = function getCurrentBlockchainOfOrNull(swap, step) {
548
+ try {
549
+ return getCurrentBlockchainOf(swap, step);
550
+ } catch (e) {
551
+ return null;
552
+ }
553
+ };
554
+ var getCurrentBlockchainOf = function getCurrentBlockchainOf(swap, step) {
555
+ var _step$evmTransaction, _step$evmApprovalTran, _step$starknetTransac, _step$starknetApprova, _step$tronTransaction, _step$tronApprovalTra, _step$cosmosTransacti, _step$solanaTransacti, _step$transferTransac;
556
+ 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);
557
+ if (!!b1) return b1;
558
+ var transferAddress = (_step$transferTransac = step.transferTransaction) == null ? void 0 : _step$transferTransac.fromWalletAddress;
559
+ if (!transferAddress) throw PrettyError.BlockchainMissing();
560
+ var blockchain = Object.keys(swap.wallets).find(function (b) {
561
+ var _swap$wallets$b;
562
+ return ((_swap$wallets$b = swap.wallets[b]) == null ? void 0 : _swap$wallets$b.address) === transferAddress;
563
+ }) || null;
564
+ if (blockchain == null) throw PrettyError.BlockchainMissing();
565
+ // TODO: check why it returns string
566
+ return blockchain;
567
+ };
568
+ var getEvmApproveUrl = function getEvmApproveUrl(tx, network, evmBasedBlockchains) {
569
+ var evmBlochain = evmBasedBlockchains.find(function (blockchain) {
570
+ return blockchain.name === network;
571
+ });
572
+ if (!evmBlochain) {
573
+ throw Error("unsupported network: " + network + " for getting approve url.");
574
+ }
575
+ if (evmBlochain.info.transactionUrl) return evmBlochain.info.transactionUrl.replace('{txHash}', tx.toLowerCase());
576
+ throw Error("Explorer url for " + network + " is not implemented");
577
+ };
578
+ var prettifyErrorMessage = function prettifyErrorMessage(obj) {
579
+ if (!obj) return {
580
+ extraMessage: '',
581
+ extraMessageErrorCode: null
582
+ };
583
+ if (obj instanceof PrettyError) return obj.getErrorDetail();
584
+ if (obj instanceof WalletError) {
585
+ var t = obj.getErrorDetail();
586
+ return {
587
+ extraMessage: t.message,
588
+ extraMessageDetail: t.detail,
589
+ extraMessageErrorCode: t.code
590
+ };
591
+ }
592
+ if (obj instanceof Error) return {
593
+ extraMessage: obj.toString(),
594
+ extraMessageErrorCode: null
595
+ };
596
+ if (typeof obj !== 'string') return {
597
+ extraMessage: JSON.stringify(obj),
598
+ extraMessageErrorCode: null
599
+ };
600
+ return {
601
+ extraMessage: obj,
602
+ extraMessageErrorCode: null
603
+ };
604
+ };
605
+ function getCookieId() {
606
+ var key = 'X-Rango-Id';
607
+ var cookieId = window.localStorage.getItem(key);
608
+ if (cookieId) {
609
+ return cookieId;
610
+ }
611
+ var value = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
612
+ window.localStorage.setItem(key, value);
613
+ return value;
614
+ }
615
+ function getNextStep(swap, currentStep) {
616
+ return swap.steps.find(function (step) {
617
+ return step.status !== 'failed' && step.status !== 'success' && step.id !== currentStep.id;
618
+ }) || null;
619
+ }
620
+ function getRelatedWalletOrNull(swap, currentStep) {
621
+ try {
622
+ return getRelatedWallet(swap, currentStep);
623
+ } catch (e) {
624
+ return null;
625
+ }
626
+ }
627
+
628
+ function logRPCError(error, swap, currentStep, walletType) {
629
+ try {
630
+ captureException(error, {
631
+ tags: {
632
+ requestId: swap.requestId,
633
+ rpc: true,
634
+ swapper: (currentStep == null ? void 0 : currentStep.swapperId) || '',
635
+ walletType: walletType || ''
636
+ },
637
+ level: 'warning'
638
+ });
639
+ } catch (e) {
640
+ console.log({
641
+ e: e
642
+ });
643
+ }
644
+ }
645
+
646
+ function checkSwapStatus(_x, _x2, _x3) {
647
+ return _checkSwapStatus.apply(this, arguments);
648
+ }
649
+ function _checkSwapStatus() {
650
+ _checkSwapStatus = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(requestId, txId, step) {
651
+ var _headers;
652
+ var url, body, response, apiError, res;
653
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
654
+ while (1) switch (_context.prev = _context.next) {
655
+ case 0:
656
+ url = BASE_URL + "/tx/check-status?" + RANGO_DAPP_ID_QUERY;
657
+ body = {
658
+ step: step,
659
+ txId: txId,
660
+ requestId: requestId
661
+ };
662
+ _context.next = 4;
663
+ return fetch(url, {
664
+ method: 'POST',
665
+ headers: (_headers = {}, _headers[RANGO_COOKIE_HEADER] = getCookieId(), _headers['content-type'] = 'application/json;charset=UTF-8', _headers),
666
+ body: JSON.stringify(body)
667
+ });
668
+ case 4:
669
+ response = _context.sent;
670
+ if (!(!!response.status && (response.status < 200 || response.status >= 400) || !response.ok)) {
671
+ _context.next = 8;
672
+ break;
673
+ }
674
+ apiError = ERROR_COMMUNICATING_WITH_API(ApiMethodName.CheckingTransactionStatus);
675
+ throw PrettyError.BadStatusCode(apiError, response.status);
676
+ case 8:
677
+ _context.next = 10;
678
+ return response.json();
679
+ case 10:
680
+ res = _context.sent;
681
+ return _context.abrupt("return", _extends({}, res, {
682
+ outputAmount: res.outputAmount ? new BigNumber(res.outputAmount) : null
683
+ }));
684
+ case 12:
685
+ case "end":
686
+ return _context.stop();
687
+ }
688
+ }, _callee);
689
+ }));
690
+ return _checkSwapStatus.apply(this, arguments);
691
+ }
692
+ function createTransaction(_x4) {
693
+ return _createTransaction.apply(this, arguments);
694
+ }
695
+ function _createTransaction() {
696
+ _createTransaction = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(request) {
697
+ var url, _headers2, response, result;
698
+ return _regeneratorRuntime().wrap(function _callee2$(_context2) {
699
+ while (1) switch (_context2.prev = _context2.next) {
700
+ case 0:
701
+ url = BASE_URL + "/tx/create?" + RANGO_DAPP_ID_QUERY;
702
+ _context2.prev = 1;
703
+ _context2.next = 4;
704
+ return fetch(url, {
705
+ method: 'POST',
706
+ headers: (_headers2 = {
707
+ 'content-type': 'application/json;charset=UTF-8'
708
+ }, _headers2[RANGO_COOKIE_HEADER] = getCookieId(), _headers2),
709
+ body: JSON.stringify(request)
710
+ });
711
+ case 4:
712
+ response = _context2.sent;
713
+ if (!(!!response.status && (response.status < 200 || response.status >= 400) || !response.ok)) {
714
+ _context2.next = 7;
715
+ break;
716
+ }
717
+ throw PrettyError.CreateTransaction("Error creating the transaction, status code: " + response.status);
718
+ case 7:
719
+ _context2.next = 9;
720
+ return response.json();
721
+ case 9:
722
+ result = _context2.sent;
723
+ if (!(!result.ok || !result.transaction)) {
724
+ _context2.next = 12;
725
+ break;
726
+ }
727
+ throw PrettyError.CreateTransaction(result.error || 'bad response from create tx endpoint');
728
+ case 12:
729
+ return _context2.abrupt("return", result);
730
+ case 15:
731
+ _context2.prev = 15;
732
+ _context2.t0 = _context2["catch"](1);
733
+ if (!(_context2.t0 instanceof Error)) {
734
+ _context2.next = 19;
735
+ break;
736
+ }
737
+ throw PrettyError.CreateTransaction(_context2.t0.message);
738
+ case 19:
739
+ throw _context2.t0;
740
+ case 20:
741
+ case "end":
742
+ return _context2.stop();
743
+ }
744
+ }, _callee2, null, [[1, 15]]);
745
+ }));
746
+ return _createTransaction.apply(this, arguments);
747
+ }
748
+ function checkApproved(_x5) {
749
+ return _checkApproved.apply(this, arguments);
750
+ }
751
+ function _checkApproved() {
752
+ _checkApproved = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3(requestId) {
753
+ var _headers3;
754
+ var url, response, apiError;
755
+ return _regeneratorRuntime().wrap(function _callee3$(_context3) {
756
+ while (1) switch (_context3.prev = _context3.next) {
757
+ case 0:
758
+ url = BASE_URL + "/tx/" + requestId + "/check-approval?" + RANGO_DAPP_ID_QUERY;
759
+ _context3.next = 3;
760
+ return fetch(url, {
761
+ method: 'GET',
762
+ headers: (_headers3 = {
763
+ 'content-type': 'application/json;charset=UTF-8'
764
+ }, _headers3[RANGO_COOKIE_HEADER] = getCookieId(), _headers3)
765
+ });
766
+ case 3:
767
+ response = _context3.sent;
768
+ if (!(!!response.status && (response.status < 200 || response.status >= 400) || !response.ok)) {
769
+ _context3.next = 7;
770
+ break;
771
+ }
772
+ apiError = ERROR_COMMUNICATING_WITH_API(ApiMethodName.CheckApproval);
773
+ throw PrettyError.BadStatusCode(apiError, response.status);
774
+ case 7:
775
+ _context3.next = 9;
776
+ return response.json();
777
+ case 9:
778
+ return _context3.abrupt("return", _context3.sent);
779
+ case 10:
780
+ case "end":
781
+ return _context3.stop();
782
+ }
783
+ }, _callee3);
784
+ }));
785
+ return _checkApproved.apply(this, arguments);
786
+ }
787
+ function isAPIErrorCode(value) {
788
+ return Object.values(APIErrorCode).includes(value);
789
+ }
790
+ function mapAppErrorCodesToAPIErrorCode(errorCode) {
791
+ var defaultErrorCode = APIErrorCode.CLIENT_UNEXPECTED_BEHAVIOUR;
792
+ try {
793
+ if (!errorCode) return defaultErrorCode;
794
+ if (isAPIErrorCode(errorCode)) return errorCode;
795
+ if (isWalletErrorCode(errorCode)) {
796
+ var _t;
797
+ var t = (_t = {}, _t[WalletErrorCode.REJECTED_BY_USER] = APIErrorCode.USER_REJECT, _t[WalletErrorCode.SIGN_TX_ERROR] = APIErrorCode.CALL_WALLET_FAILED, _t[WalletErrorCode.SEND_TX_ERROR] = APIErrorCode.SEND_TX_FAILED, _t[WalletErrorCode.NOT_IMPLEMENTED] = defaultErrorCode, _t[WalletErrorCode.OPERATION_UNSUPPORTED] = defaultErrorCode, _t[WalletErrorCode.UNEXPECTED_BEHAVIOUR] = defaultErrorCode, _t);
798
+ return t[errorCode];
799
+ }
800
+ return defaultErrorCode;
801
+ } catch (err) {
802
+ return defaultErrorCode;
803
+ }
804
+ }
805
+ function reportFailed(_x6, _x7, _x8, _x9, _x10) {
806
+ return _reportFailed.apply(this, arguments);
807
+ }
808
+ function _reportFailed() {
809
+ _reportFailed = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4(requestId, step, eventType, reason, walletType) {
810
+ var _headers4;
811
+ var url;
812
+ return _regeneratorRuntime().wrap(function _callee4$(_context4) {
813
+ while (1) switch (_context4.prev = _context4.next) {
814
+ case 0:
815
+ url = BASE_URL + "/tx/report-tx?" + RANGO_DAPP_ID_QUERY;
816
+ _context4.next = 3;
817
+ return fetch(url, {
818
+ method: 'POST',
819
+ headers: (_headers4 = {
820
+ 'content-type': 'application/json;charset=UTF-8'
821
+ }, _headers4[RANGO_COOKIE_HEADER] = getCookieId(), _headers4),
822
+ body: JSON.stringify({
823
+ requestId: requestId,
824
+ step: step,
825
+ eventType: eventType,
826
+ reason: reason,
827
+ tags: {
828
+ wallet: walletType
829
+ }
830
+ })
831
+ });
832
+ case 3:
833
+ case "end":
834
+ return _context4.stop();
835
+ }
836
+ }, _callee4);
837
+ }));
838
+ return _reportFailed.apply(this, arguments);
839
+ }
840
+
841
+ var swapClaimedBy = null;
842
+ /**
843
+ *
844
+ * We simply use module-level variable to keep track of which queue has claimed the execution of parallel runnings.
845
+ *
846
+ */
847
+ function claimQueue() {
848
+ return {
849
+ claimedBy: function claimedBy() {
850
+ var _swapClaimedBy;
851
+ return (_swapClaimedBy = swapClaimedBy) == null ? void 0 : _swapClaimedBy.id;
852
+ },
853
+ setClaimer: function setClaimer(queue_id) {
854
+ swapClaimedBy = {
855
+ id: queue_id
856
+ };
857
+ },
858
+ reset: function reset() {
859
+ swapClaimedBy = null;
860
+ }
861
+ };
862
+ }
863
+ /**
864
+ *
865
+ * Returns `steps`, if it's a `running` swap.
866
+ * Each `PendingSwap` has a `steps` inside it, `steps` shows how many tasks should be created and run to finish the swap.
867
+ *
868
+ */
869
+ var getCurrentStep = function getCurrentStep(swap) {
870
+ return swap.steps.find(function (step) {
871
+ return step.status !== 'failed' && step.status !== 'success';
872
+ }) || null;
873
+ };
874
+ /**
875
+ * When we are doing a swap, there are some common fields that will be updated together.
876
+ * This function helps us to update a swap status and also it will update some more fields like `extraMessageSeverity` based on the input.
877
+ */
878
+ function updateSwapStatus(_ref) {
879
+ var getStorage = _ref.getStorage,
880
+ setStorage = _ref.setStorage,
881
+ nextStatus = _ref.nextStatus,
882
+ nextStepStatus = _ref.nextStepStatus,
883
+ message = _ref.message,
884
+ details = _ref.details,
885
+ _ref$errorCode = _ref.errorCode,
886
+ errorCode = _ref$errorCode === void 0 ? null : _ref$errorCode;
887
+ var swap = getStorage().swapDetails;
888
+ var currentStep = getCurrentStep(swap);
889
+ if (!!nextStepStatus && !!currentStep) currentStep.status = nextStepStatus;
890
+ if (!!nextStatus) swap.status = nextStatus;
891
+ if (!!nextStatus && ['failed', 'success'].includes(nextStatus)) swap.finishTime = new Date().getTime().toString();
892
+ if (!!message) swap.extraMessage = message;
893
+ if (!!details) swap.extraMessageDetail = details;
894
+ if (!!nextStepStatus && ['failed'].includes(nextStepStatus)) {
895
+ var _getRelatedWalletOrNu;
896
+ //if user cancel the swap, we should pass relevant reason to the server.
897
+ var errorReason = details && details.includes('Warning') ? 'Swap canceled by user.' : details;
898
+ swap.extraMessageSeverity = MessageSeverity.error;
899
+ reportFailed(swap.requestId, (currentStep == null ? void 0 : currentStep.id) || 1, mapAppErrorCodesToAPIErrorCode(errorCode), errorReason || '', (currentStep ? (_getRelatedWalletOrNu = getRelatedWalletOrNull(swap, currentStep)) == null ? void 0 : _getRelatedWalletOrNu.walletType : null) || null).then();
900
+ } else if (!!nextStepStatus && ['running'].includes(nextStepStatus)) swap.extraMessageSeverity = MessageSeverity.info;else if (!!nextStepStatus && ['success', 'approved'].includes(nextStepStatus)) swap.extraMessageSeverity = MessageSeverity.success;else if (nextStepStatus && ['waitingForApproval'].includes(nextStepStatus)) swap.extraMessageSeverity = MessageSeverity.warning;
901
+ if (nextStepStatus === 'running' && currentStep) currentStep.startTransactionTime = new Date().getTime();
902
+ setStorage(_extends({}, getStorage(), {
903
+ swapDetails: swap
904
+ }));
905
+ return {
906
+ swap: swap,
907
+ step: currentStep
908
+ };
909
+ }
910
+ function setStepTransactionIds(_ref2, txId, eventType, notifier) {
911
+ var getStorage = _ref2.getStorage,
912
+ setStorage = _ref2.setStorage;
913
+ var swap = getStorage().swapDetails;
914
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
915
+ var currentStep = getCurrentStep(swap);
916
+ currentStep.executedTransactionId = txId || currentStep.executedTransactionId;
917
+ setStorage(_extends({}, getStorage(), {
918
+ swapDetails: swap
919
+ }));
920
+ notifier({
921
+ eventType: eventType,
922
+ swap: swap,
923
+ step: currentStep
924
+ });
925
+ }
926
+ /**
927
+ * If a swap needs a wallet to be connected,
928
+ * By calling this function some related fields will be updated to show a correct message and state for notfiying the user.
929
+ */
930
+ function markRunningSwapAsWaitingForConnectingWallet(_ref3, reason, reasonDetail) {
931
+ var getStorage = _ref3.getStorage,
932
+ setStorage = _ref3.setStorage;
933
+ var swap = getStorage().swapDetails;
934
+ var currentStep = getCurrentStep(swap);
935
+ if (!currentStep) return;
936
+ var currentTime = new Date();
937
+ swap.lastNotificationTime = currentTime.getTime().toString();
938
+ var isAlreadyMarked = currentStep.networkStatus === PendingSwapNetworkStatus.WaitingForConnectingWallet && swap.networkStatusExtraMessage === reason && swap.networkStatusExtraMessageDetail === reasonDetail;
939
+ if (isAlreadyMarked) {
940
+ return;
941
+ }
942
+ currentStep.networkStatus = PendingSwapNetworkStatus.WaitingForConnectingWallet;
943
+ swap.networkStatusExtraMessage = reason;
944
+ swap.networkStatusExtraMessageDetail = reasonDetail;
945
+ setStorage(_extends({}, getStorage(), {
946
+ swapDetails: swap
947
+ }));
948
+ }
949
+ /**
950
+ * If a swap needs a certain network to proceed,
951
+ * By calling this function some related fields will be updated to show a correct message and state for notfiying the user.
952
+ */
953
+ function markRunningSwapAsSwitchingNetwork(_ref4) {
954
+ var getStorage = _ref4.getStorage,
955
+ setStorage = _ref4.setStorage;
956
+ var swap = getStorage().swapDetails;
957
+ var currentStep = getCurrentStep(swap);
958
+ if (!currentStep) return;
959
+ // Generate message
960
+ var _getRequiredWallet = getRequiredWallet(swap),
961
+ type = _getRequiredWallet.type;
962
+ var fromBlockchain = getCurrentBlockchainOf(swap, currentStep);
963
+ var reason = "Change " + type + " wallet network to " + fromBlockchain;
964
+ var metamaskMessage = '';
965
+ if (type === WalletType.META_MASK) metamaskMessage = "(Networks -> Select '" + fromBlockchain + "' network.)";
966
+ var reasonDetail = "Please change your " + type + " wallet network to " + fromBlockchain + ". " + metamaskMessage;
967
+ var currentTime = new Date();
968
+ swap.lastNotificationTime = currentTime.getTime().toString();
969
+ currentStep.networkStatus = PendingSwapNetworkStatus.WaitingForNetworkChange;
970
+ swap.networkStatusExtraMessage = reason;
971
+ swap.networkStatusExtraMessageDetail = reasonDetail;
972
+ setStorage(_extends({}, getStorage(), {
973
+ swapDetails: swap
974
+ }));
975
+ return {
976
+ swap: swap,
977
+ step: currentStep
978
+ };
979
+ }
980
+ /**
981
+ * We are marking the queue as it depends on other queues to be run (on Parallel mode)
982
+ * By calling this function some related fields will be updated to show a correct message and state for notfiying the user.
983
+ */
984
+ function markRunningSwapAsDependsOnOtherQueues(_ref5) {
985
+ var getStorage = _ref5.getStorage,
986
+ setStorage = _ref5.setStorage;
987
+ var swap = getStorage().swapDetails;
988
+ var currentStep = getCurrentStep(swap);
989
+ if (!currentStep) return;
990
+ swap.networkStatusExtraMessage = '';
991
+ swap.networkStatusExtraMessageDetail = '';
992
+ currentStep.networkStatus = PendingSwapNetworkStatus.WaitingForQueue;
993
+ setStorage(_extends({}, getStorage(), {
994
+ swapDetails: swap
995
+ }));
996
+ return {
997
+ swap: swap,
998
+ step: currentStep
999
+ };
1000
+ }
1001
+ function delay(ms) {
1002
+ return new Promise(function (res) {
1003
+ return setTimeout(res, ms);
1004
+ });
1005
+ }
1006
+ var isEvmTransaction = function isEvmTransaction(tx) {
1007
+ return tx.type === TransactionType.EVM;
1008
+ };
1009
+ var isCosmosTransaction = function isCosmosTransaction(tx) {
1010
+ return tx.type === TransactionType.COSMOS;
1011
+ };
1012
+ var isSolanaTransaction = function isSolanaTransaction(tx) {
1013
+ return tx.type === TransactionType.SOLANA;
1014
+ };
1015
+ var isTrasnferTransaction = function isTrasnferTransaction(tx) {
1016
+ return tx.type === TransactionType.TRANSFER;
1017
+ };
1018
+ var isStarknetTransaction = function isStarknetTransaction(tx) {
1019
+ return tx.type === TransactionType.STARKNET;
1020
+ };
1021
+ var isTronTransaction = function isTronTransaction(tx) {
1022
+ return tx.type === TransactionType.TRON;
1023
+ };
1024
+ /**
1025
+ *
1026
+ * To execute a swap, we are keeping the user prefrences on what wallet they are going to use for a sepecific blockchain
1027
+ * By passing the swap and the network we are looking for, it returns the wallet name that user selected.
1028
+ *
1029
+ */
1030
+ var getSwapWalletType = function getSwapWalletType(swap, network) {
1031
+ var _swap$wallets$network;
1032
+ return (_swap$wallets$network = swap.wallets[network]) == null ? void 0 : _swap$wallets$network.walletType;
1033
+ };
1034
+ /**
1035
+ *
1036
+ * We are keeping the connected wallet in a specific structure (`Wallet`),
1037
+ * By using this function we normally want to check a specific wallet is connected and exists or not.
1038
+ *
1039
+ */
1040
+ function isWalletNull(wallet) {
1041
+ return wallet === null || (wallet == null ? void 0 : wallet.blockchains) === null || (wallet == null ? void 0 : wallet.blockchains.length) === 0;
1042
+ }
1043
+ /**
1044
+ * On our implementation for `wallets` package, We keep the instance in 2 ways
1045
+ * If it's a single chain wallet, it returns the instance directly,
1046
+ * If it's a multichain wallet, it returns a `Map` of instances.
1047
+ * This function will get the `ETHEREUM` instance in both types.
1048
+ */
1049
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1050
+ function getEvmProvider(providers, type) {
1051
+ if (type && providers[type]) {
1052
+ // 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.
1053
+ if (providers[type].size) return providers[type].get(Network.ETHEREUM);
1054
+ return providers[type];
1055
+ }
1056
+ return null;
1057
+ }
1058
+ /**
1059
+ * In a `PendingSwap`, each step needs a wallet to proceed,
1060
+ * By using this function we can access what wallet exactly we need to run current step.
1061
+ */
1062
+ function getRequiredWallet(swap) {
1063
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1064
+ var step = getCurrentStep(swap);
1065
+ var bcName = getCurrentBlockchainOfOrNull(swap, step);
1066
+ if (!bcName) {
1067
+ return {
1068
+ type: null,
1069
+ network: null,
1070
+ address: null
1071
+ };
1072
+ }
1073
+ var walletType = getSwapWalletType(swap, bcName);
1074
+ var sourceWallet = swap.wallets[bcName];
1075
+ return {
1076
+ type: walletType || null,
1077
+ network: bcName,
1078
+ address: sourceWallet ? sourceWallet.address : null
1079
+ };
1080
+ }
1081
+ /**
1082
+ * On EVM compatible wallets, There is one instance with different chains (like Polygon)
1083
+ * To get the chain from instance we will use this function.
1084
+ */
1085
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1086
+ function getChainId(_x) {
1087
+ return _getChainId.apply(this, arguments);
1088
+ }
1089
+ /**
1090
+ * For running a swap safely, we need to make sure about the state of wallet
1091
+ * which means the netowrk/chain of wallet should be exactly on what a transaction needs.
1092
+ */
1093
+ function _getChainId() {
1094
+ _getChainId = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(provider) {
1095
+ var chainId;
1096
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
1097
+ while (1) switch (_context.prev = _context.next) {
1098
+ case 0:
1099
+ _context.next = 2;
1100
+ return provider.request({
1101
+ method: 'eth_chainId'
1102
+ });
1103
+ case 2:
1104
+ _context.t0 = _context.sent;
1105
+ if (_context.t0) {
1106
+ _context.next = 5;
1107
+ break;
1108
+ }
1109
+ _context.t0 = provider == null ? void 0 : provider.chainId;
1110
+ case 5:
1111
+ chainId = _context.t0;
1112
+ return _context.abrupt("return", chainId);
1113
+ case 7:
1114
+ case "end":
1115
+ return _context.stop();
1116
+ }
1117
+ }, _callee);
1118
+ }));
1119
+ return _getChainId.apply(this, arguments);
1120
+ }
1121
+ function isNetworkMatchedForTransaction(_x2, _x3, _x4, _x5, _x6) {
1122
+ return _isNetworkMatchedForTransaction.apply(this, arguments);
1123
+ }
1124
+ /**
1125
+ * Returns the wallet address, based on the current step of `PendingSwap`.
1126
+ */
1127
+ function _isNetworkMatchedForTransaction() {
1128
+ _isNetworkMatchedForTransaction = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(swap, step, wallet, meta, providers) {
1129
+ var fromBlockChain, sourceWallet, provider, chainId, blockChain;
1130
+ return _regeneratorRuntime().wrap(function _callee2$(_context2) {
1131
+ while (1) switch (_context2.prev = _context2.next) {
1132
+ case 0:
1133
+ if (!isWalletNull(wallet)) {
1134
+ _context2.next = 3;
1135
+ break;
1136
+ }
1137
+ console.warn('wallet object is null');
1138
+ return _context2.abrupt("return", false);
1139
+ case 3:
1140
+ fromBlockChain = getCurrentBlockchainOfOrNull(swap, step);
1141
+ if (fromBlockChain) {
1142
+ _context2.next = 6;
1143
+ break;
1144
+ }
1145
+ return _context2.abrupt("return", false);
1146
+ case 6:
1147
+ if (!meta.evmBasedChains.find(function (evmBlochain) {
1148
+ return evmBlochain.name === fromBlockChain;
1149
+ })) {
1150
+ _context2.next = 30;
1151
+ break;
1152
+ }
1153
+ _context2.prev = 7;
1154
+ sourceWallet = swap.wallets[fromBlockChain];
1155
+ if (!sourceWallet) {
1156
+ _context2.next = 24;
1157
+ break;
1158
+ }
1159
+ if (![WalletType.META_MASK, WalletType.BINANCE_CHAIN, WalletType.XDEFI, WalletType.WALLET_CONNECT, WalletType.TRUST_WALLET, WalletType.COIN98, WalletType.EXODUS, WalletType.OKX, WalletType.COINBASE, WalletType.TOKEN_POCKET, WalletType.MATH, WalletType.SAFEPAL, WalletType.COSMOSTATION, WalletType.CLOVER, WalletType.BRAVE].includes(sourceWallet.walletType)) {
1160
+ _context2.next = 23;
1161
+ break;
1162
+ }
1163
+ provider = getEvmProvider(providers, sourceWallet.walletType);
1164
+ _context2.next = 14;
1165
+ return getChainId(provider);
1166
+ case 14:
1167
+ chainId = _context2.sent;
1168
+ if (!chainId) {
1169
+ _context2.next = 21;
1170
+ break;
1171
+ }
1172
+ blockChain = getBlockChainNameFromId(chainId, Object.entries(meta.blockchains).map(function (_ref7) {
1173
+ var blockchainMeta = _ref7[1];
1174
+ return blockchainMeta;
1175
+ }));
1176
+ if (!(blockChain && blockChain.toLowerCase() === fromBlockChain.toLowerCase())) {
1177
+ _context2.next = 19;
1178
+ break;
1179
+ }
1180
+ return _context2.abrupt("return", true);
1181
+ case 19:
1182
+ if (!(blockChain && blockChain.toLowerCase() !== fromBlockChain.toLowerCase())) {
1183
+ _context2.next = 21;
1184
+ break;
1185
+ }
1186
+ return _context2.abrupt("return", false);
1187
+ case 21:
1188
+ _context2.next = 24;
1189
+ break;
1190
+ case 23:
1191
+ return _context2.abrupt("return", true);
1192
+ case 24:
1193
+ _context2.next = 29;
1194
+ break;
1195
+ case 26:
1196
+ _context2.prev = 26;
1197
+ _context2.t0 = _context2["catch"](7);
1198
+ console.log(_context2.t0);
1199
+ case 29:
1200
+ return _context2.abrupt("return", false);
1201
+ case 30:
1202
+ return _context2.abrupt("return", true);
1203
+ case 31:
1204
+ case "end":
1205
+ return _context2.stop();
1206
+ }
1207
+ }, _callee2, null, [[7, 26]]);
1208
+ }));
1209
+ return _isNetworkMatchedForTransaction.apply(this, arguments);
1210
+ }
1211
+ var getCurrentAddressOf = function getCurrentAddressOf(swap, step) {
1212
+ var _step$evmTransaction, _step$evmApprovalTran, _step$cosmosTransacti, _step$solanaTransacti, _step$transferTransac, _step$transferTransac2;
1213
+ 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$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 && _step$transferTransac.fromWalletAddress ? {
1214
+ address: (_step$transferTransac2 = step.transferTransaction) == null ? void 0 : _step$transferTransac2.fromWalletAddress
1215
+ } : null) || null;
1216
+ if (result == null) throw PrettyError.WalletMissing();
1217
+ return result.address;
1218
+ };
1219
+ // Todo: Is it same with `getRequiredWallet`?
1220
+ function getRelatedWallet(swap, currentStep) {
1221
+ var walletAddress = getCurrentAddressOf(swap, currentStep);
1222
+ var walletKV = Object.keys(swap.wallets).map(function (k) {
1223
+ return {
1224
+ k: k,
1225
+ v: swap.wallets[k]
1226
+ };
1227
+ }).find(function (_ref6) {
1228
+ var v = _ref6.v;
1229
+ return v.address === walletAddress;
1230
+ }) || null;
1231
+ var blockchain = (walletKV == null ? void 0 : walletKV.k) || null;
1232
+ var wallet = (walletKV == null ? void 0 : walletKV.v) || null;
1233
+ var walletType = wallet == null ? void 0 : wallet.walletType;
1234
+ if (walletType === WalletType.UNKNOWN || wallet === null) throw PrettyError.AssertionFailed("Wallet for source " + blockchain + " not passed to transfer: walletType: " + walletType);
1235
+ return wallet;
1236
+ }
1237
+ var isTxAlreadyCreated = function isTxAlreadyCreated(swap, step) {
1238
+ var _step$evmTransaction2, _step$evmApprovalTran2, _step$cosmosTransacti2, _step$solanaTransacti2, _step$transferTransac3;
1239
+ 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$cosmosTransacti2 = step.cosmosTransaction) == null ? void 0 : _step$cosmosTransacti2.blockChain) || ''] || swap.wallets[((_step$solanaTransacti2 = step.solanaTransaction) == null ? void 0 : _step$solanaTransacti2.blockChain) || ''] || ((_step$transferTransac3 = step.transferTransaction) == null ? void 0 : _step$transferTransac3.fromWalletAddress) || null;
1240
+ return result !== null;
1241
+ };
1242
+ function resetNetworkStatus(actions) {
1243
+ var getStorage = actions.getStorage,
1244
+ setStorage = actions.setStorage;
1245
+ var swap = getStorage().swapDetails;
1246
+ var currentStep = getCurrentStep(swap);
1247
+ if (currentStep != null && currentStep.networkStatus) {
1248
+ currentStep.networkStatus = null;
1249
+ setStorage(_extends({}, getStorage(), {
1250
+ swapDetails: swap
1251
+ }));
1252
+ }
1253
+ }
1254
+ function updateNetworkStatus(actions, data) {
1255
+ if (data === void 0) {
1256
+ data = {
1257
+ message: '',
1258
+ details: '',
1259
+ status: null
1260
+ };
1261
+ }
1262
+ var _data = data,
1263
+ message = _data.message,
1264
+ details = _data.details,
1265
+ status = _data.status;
1266
+ var getStorage = actions.getStorage,
1267
+ setStorage = actions.setStorage;
1268
+ var swap = getStorage().swapDetails;
1269
+ var currentStep = getCurrentStep(swap);
1270
+ if (currentStep != null && currentStep.networkStatus) {
1271
+ swap.networkStatusExtraMessage = message;
1272
+ swap.networkStatusExtraMessageDetail = details;
1273
+ currentStep.networkStatus = status;
1274
+ setStorage(_extends({}, getStorage(), {
1275
+ swapDetails: swap
1276
+ }));
1277
+ }
1278
+ }
1279
+ /**
1280
+ * Event handler for blocked tasks.
1281
+ * If a transcation execution is manually blocked (like for parallel or waiting for walle),
1282
+ * This function will be called by queue manager using `queue definition`.
1283
+ *
1284
+ * It checks if the required wallet is connected, unblock the queue to be run.
1285
+ */
1286
+ function onBlockForConnectWallet(event, meta) {
1287
+ var context = meta.context,
1288
+ queue = meta.queue;
1289
+ var swap = queue.getStorage().swapDetails;
1290
+ if (!isRequiredWalletConnected(swap, context.state)) {
1291
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1292
+ var currentStep = getCurrentStep(swap);
1293
+ context.notifier({
1294
+ eventType: 'waiting_for_connecting_wallet',
1295
+ swap: swap,
1296
+ step: currentStep
1297
+ });
1298
+ markRunningSwapAsWaitingForConnectingWallet({
1299
+ getStorage: queue.getStorage.bind(queue),
1300
+ setStorage: queue.setStorage.bind(queue)
1301
+ }, ERROR_MESSAGE_WAIT_FOR_WALLET, event.reason.description);
1302
+ return;
1303
+ }
1304
+ queue.unblock();
1305
+ }
1306
+ /**
1307
+ * Event handler for blocked tasks.
1308
+ * If a transcation execution is manually blocked (like for parallel or waiting for walle),
1309
+ * This function will be called by queue manager using `queue definition`.
1310
+ *
1311
+ * It checks if the required network is connected, unblock the queue to be run.
1312
+ * Note: it automatically try to switch the network if its `provider` supports.
1313
+ */
1314
+ function onBlockForChangeNetwork(_event, meta) {
1315
+ var context = meta.context,
1316
+ queue = meta.queue;
1317
+ var swap = queue.getStorage().swapDetails;
1318
+ var currentStep = getCurrentStep(swap);
1319
+ if (!currentStep) return;
1320
+ var result = markRunningSwapAsSwitchingNetwork({
1321
+ getStorage: queue.getStorage.bind(queue),
1322
+ setStorage: queue.setStorage.bind(queue)
1323
+ });
1324
+ if (result) {
1325
+ context.notifier({
1326
+ eventType: 'waiting_for_network_change',
1327
+ swap: result.swap,
1328
+ step: result.step
1329
+ });
1330
+ }
1331
+ // Try to auto switch
1332
+ var _getRequiredWallet2 = getRequiredWallet(swap),
1333
+ type = _getRequiredWallet2.type,
1334
+ network = _getRequiredWallet2.network;
1335
+ if (!!type && !!network) {
1336
+ var _result = context.switchNetwork(type, network);
1337
+ if (_result) {
1338
+ _result.then(function () {
1339
+ queue.unblock();
1340
+ });
1341
+ }
1342
+ }
1343
+ }
1344
+ /**
1345
+ * Event handler for blocked tasks. (Parallel mode)
1346
+ * If a transcation execution is manually blocked (like for parallel or waiting for walle),
1347
+ * This function will be called by queue manager using `queue definition`.
1348
+ *
1349
+ * It checks the blocked tasks, if there is no active `claimed` queue, try to give it to the best candidate.
1350
+ */
1351
+ function onDependsOnOtherQueues(_event, meta) {
1352
+ var getBlockedTasks = meta.getBlockedTasks,
1353
+ forceExecute = meta.forceExecute,
1354
+ queue = meta.queue,
1355
+ manager = meta.manager;
1356
+ var _claimQueue = claimQueue(),
1357
+ setClaimer = _claimQueue.setClaimer,
1358
+ claimedBy = _claimQueue.claimedBy,
1359
+ reset = _claimQueue.reset;
1360
+ // We only needs those blocked tasks that have DEPENDS_ON_OTHER_QUEUES reason.
1361
+ var blockedTasks = getBlockedTasks().filter(function (task) {
1362
+ return task.reason.reason === BlockReason.DEPENDS_ON_OTHER_QUEUES;
1363
+ });
1364
+ if (blockedTasks.length === 0) {
1365
+ return;
1366
+ }
1367
+ var claimerId = claimedBy();
1368
+ var isClaimedByAnyQueue = !!claimerId;
1369
+ // Check if any queue `claimed` before, if yes, we don't should do anything.
1370
+ if (isClaimedByAnyQueue) {
1371
+ // We need to keep the latest swap messages
1372
+ markRunningSwapAsDependsOnOtherQueues({
1373
+ getStorage: queue.getStorage.bind(queue),
1374
+ setStorage: queue.setStorage.bind(queue)
1375
+ });
1376
+ return;
1377
+ }
1378
+ // Prioritize current queue to be run first.
1379
+ var task = blockedTasks.find(function (task) {
1380
+ return task.queue_id === meta.queue_id;
1381
+ });
1382
+ // If current task isn't available anymore, fallback to first blocked task.
1383
+ if (!task) {
1384
+ var firstBlockedTask = blockedTasks[0];
1385
+ task = firstBlockedTask;
1386
+ }
1387
+ setClaimer(task.queue_id);
1388
+ var claimedStorage = task.storage.get();
1389
+ var _getRequiredWallet3 = getRequiredWallet(claimedStorage.swapDetails),
1390
+ type = _getRequiredWallet3.type,
1391
+ network = _getRequiredWallet3.network,
1392
+ address = _getRequiredWallet3.address;
1393
+ // Run
1394
+ forceExecute(task.queue_id, {
1395
+ claimedBy: claimedBy(),
1396
+ resetClaimedBy: function resetClaimedBy() {
1397
+ reset();
1398
+ // TODO: Use key generator
1399
+ retryOn(type + "-" + network + "-" + address, manager);
1400
+ }
1401
+ });
1402
+ }
1403
+ function isRequiredWalletConnected(swap, getState) {
1404
+ var _getRequiredWallet4 = getRequiredWallet(swap),
1405
+ type = _getRequiredWallet4.type,
1406
+ address = _getRequiredWallet4.address;
1407
+ if (!type || !address) {
1408
+ return false;
1409
+ }
1410
+ var walletState = getState(type);
1411
+ var accounts = walletState.accounts;
1412
+ var connectedAccounts = accounts || [];
1413
+ return connectedAccounts.some(function (account) {
1414
+ var _readAccountAddress = readAccountAddress(account),
1415
+ accountAddress = _readAccountAddress.address;
1416
+ return address === accountAddress;
1417
+ });
1418
+ }
1419
+ function singTransaction(actions) {
1420
+ var getStorage = actions.getStorage,
1421
+ setStorage = actions.setStorage,
1422
+ failed = actions.failed,
1423
+ next = actions.next,
1424
+ schedule = actions.schedule,
1425
+ context = actions.context;
1426
+ var meta = context.meta,
1427
+ getSigners = context.getSigners,
1428
+ notifier = context.notifier;
1429
+ var swap = getStorage().swapDetails;
1430
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1431
+ var currentStep = getCurrentStep(swap);
1432
+ var evmTransaction = currentStep.evmTransaction,
1433
+ evmApprovalTransaction = currentStep.evmApprovalTransaction,
1434
+ cosmosTransaction = currentStep.cosmosTransaction,
1435
+ solanaTransaction = currentStep.solanaTransaction,
1436
+ transferTransaction = currentStep.transferTransaction;
1437
+ var sourceWallet = getRelatedWallet(swap, currentStep);
1438
+ var walletSigners = getSigners(sourceWallet.walletType);
1439
+ var onFinish = function onFinish() {
1440
+ if (actions.context.resetClaimedBy) {
1441
+ actions.context.resetClaimedBy();
1442
+ }
1443
+ };
1444
+ if (!!evmApprovalTransaction) {
1445
+ var spenderContract = evmApprovalTransaction == null ? void 0 : evmApprovalTransaction.to;
1446
+ if (!spenderContract) throw PrettyError.AssertionFailed('contract address is null for checking approval');
1447
+ // Update swap status
1448
+ var message = "waiting for approval of " + (currentStep == null ? void 0 : currentStep.fromSymbol) + " coin " + (sourceWallet.walletType === WalletType.WALLET_CONNECT ? 'on your mobile phone' : '');
1449
+ var updateResult = updateSwapStatus({
1450
+ getStorage: getStorage,
1451
+ setStorage: setStorage,
1452
+ nextStepStatus: 'waitingForApproval',
1453
+ message: message,
1454
+ details: 'Waiting for approve transaction to be mined and confirmed successfully'
1455
+ });
1456
+ notifier(_extends({
1457
+ eventType: 'confirm_contract'
1458
+ }, updateResult));
1459
+ // Execute transaction
1460
+ walletSigners.executeEvmTransaction(evmApprovalTransaction, meta).then(function (hash) {
1461
+ console.debug('transaction of approval minted successfully', hash);
1462
+ var approveUrl = getEvmApproveUrl(hash, getCurrentBlockchainOf(swap, currentStep), meta.evmBasedChains);
1463
+ currentStep.explorerUrl = [].concat(currentStep.explorerUrl || [], [{
1464
+ url: approveUrl,
1465
+ description: "approve"
1466
+ }]);
1467
+ // `currentStep` has been mutated, let's update storage.
1468
+ setStorage(_extends({}, getStorage(), {
1469
+ swapDetails: swap
1470
+ }));
1471
+ schedule(SwapActionTypes.CHECK_TRANSACTION_STATUS);
1472
+ next();
1473
+ onFinish();
1474
+ }, function (error) {
1475
+ var _error$root, _error$root2, _error$root3;
1476
+ if (swap.status === 'failed') return;
1477
+ console.debug('error in approving', error);
1478
+ var _prettifyErrorMessage = prettifyErrorMessage(error),
1479
+ extraMessage = _prettifyErrorMessage.extraMessage,
1480
+ extraMessageDetail = _prettifyErrorMessage.extraMessageDetail,
1481
+ extraMessageErrorCode = _prettifyErrorMessage.extraMessageErrorCode;
1482
+ 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) {
1483
+ logRPCError(error.root, swap, currentStep, sourceWallet == null ? void 0 : sourceWallet.walletType);
1484
+ }
1485
+ var updateResult = updateSwapStatus({
1486
+ getStorage: getStorage,
1487
+ setStorage: setStorage,
1488
+ nextStatus: 'failed',
1489
+ nextStepStatus: 'failed',
1490
+ message: extraMessage,
1491
+ details: extraMessageDetail,
1492
+ errorCode: extraMessageErrorCode
1493
+ });
1494
+ notifier(_extends({
1495
+ eventType: 'contract_rejected'
1496
+ }, updateResult));
1497
+ failed();
1498
+ onFinish();
1499
+ });
1500
+ return;
1501
+ }
1502
+ var executeMessage = 'executing transaction';
1503
+ var executeDetails = "" + (sourceWallet.walletType === WalletType.WALLET_CONNECT ? 'Check your mobile phone' : '');
1504
+ if (!!transferTransaction) {
1505
+ var _updateResult = updateSwapStatus({
1506
+ getStorage: getStorage,
1507
+ setStorage: setStorage,
1508
+ nextStepStatus: 'running',
1509
+ message: executeMessage,
1510
+ details: executeDetails
1511
+ });
1512
+ notifier(_extends({
1513
+ eventType: 'confirm_transfer'
1514
+ }, _updateResult));
1515
+ walletSigners.executeTransfer(transferTransaction, meta).then(function (txId) {
1516
+ setStepTransactionIds(actions, txId, 'transfer_confirmed', notifier);
1517
+ schedule(SwapActionTypes.CHECK_TRANSACTION_STATUS);
1518
+ next();
1519
+ onFinish();
1520
+ }, function (error) {
1521
+ if (swap.status === 'failed') return;
1522
+ var _prettifyErrorMessage2 = prettifyErrorMessage(error),
1523
+ extraMessage = _prettifyErrorMessage2.extraMessage,
1524
+ extraMessageDetail = _prettifyErrorMessage2.extraMessageDetail,
1525
+ extraMessageErrorCode = _prettifyErrorMessage2.extraMessageErrorCode;
1526
+ var updateResult = updateSwapStatus({
1527
+ getStorage: getStorage,
1528
+ setStorage: setStorage,
1529
+ nextStatus: 'failed',
1530
+ nextStepStatus: 'failed',
1531
+ message: extraMessage,
1532
+ details: extraMessageDetail,
1533
+ errorCode: extraMessageErrorCode
1534
+ });
1535
+ notifier(_extends({
1536
+ eventType: 'transfer_rejected'
1537
+ }, updateResult));
1538
+ failed();
1539
+ onFinish();
1540
+ });
1541
+ } else if (!!evmTransaction) {
1542
+ var _updateResult2 = updateSwapStatus({
1543
+ getStorage: getStorage,
1544
+ setStorage: setStorage,
1545
+ nextStepStatus: 'running',
1546
+ message: executeMessage,
1547
+ details: executeDetails
1548
+ });
1549
+ notifier(_extends({
1550
+ eventType: 'calling_smart_contract'
1551
+ }, _updateResult2));
1552
+ walletSigners.executeEvmTransaction(evmTransaction, meta).then(function (id) {
1553
+ setStepTransactionIds(actions, id, 'smart_contract_called', notifier);
1554
+ schedule(SwapActionTypes.CHECK_TRANSACTION_STATUS);
1555
+ next();
1556
+ onFinish();
1557
+ }, function (error) {
1558
+ var _error$root4, _error$root5, _error$root6;
1559
+ if (swap.status === 'failed') return;
1560
+ var _prettifyErrorMessage3 = prettifyErrorMessage(error),
1561
+ extraMessage = _prettifyErrorMessage3.extraMessage,
1562
+ extraMessageDetail = _prettifyErrorMessage3.extraMessageDetail,
1563
+ extraMessageErrorCode = _prettifyErrorMessage3.extraMessageErrorCode;
1564
+ if (error && error != null && error.root && error != null && (_error$root4 = error.root) != null && _error$root4.message && error != null && (_error$root5 = error.root) != null && _error$root5.code && error != null && (_error$root6 = error.root) != null && _error$root6.reason) {
1565
+ logRPCError(error.root, swap, currentStep, sourceWallet == null ? void 0 : sourceWallet.walletType);
1566
+ }
1567
+ var updateResult = updateSwapStatus({
1568
+ getStorage: getStorage,
1569
+ setStorage: setStorage,
1570
+ nextStatus: 'failed',
1571
+ nextStepStatus: 'failed',
1572
+ message: extraMessage,
1573
+ details: extraMessageDetail,
1574
+ errorCode: extraMessageErrorCode
1575
+ });
1576
+ notifier(_extends({
1577
+ eventType: 'smart_contract_call_failed'
1578
+ }, updateResult));
1579
+ failed();
1580
+ onFinish();
1581
+ });
1582
+ } else if (!!cosmosTransaction) {
1583
+ var _updateResult3 = updateSwapStatus({
1584
+ getStorage: getStorage,
1585
+ setStorage: setStorage,
1586
+ nextStepStatus: 'running',
1587
+ message: executeMessage,
1588
+ details: executeDetails
1589
+ });
1590
+ notifier(_extends({
1591
+ eventType: 'calling_smart_contract'
1592
+ }, _updateResult3));
1593
+ // If keplr wallet is executing contracts on terra, throw error. keplr doesn't support transfer or execute contracts. only IBC messages are supported
1594
+ if (((currentStep == null ? void 0 : currentStep.swapperId.toString()) === 'TerraSwap' || (currentStep == null ? void 0 : currentStep.swapperId.toString()) === 'ThorChain' && (currentStep == null ? void 0 : currentStep.fromBlockchain) === Network.TERRA || (currentStep == null ? void 0 : currentStep.swapperId.toString()) === 'Terra Bridge' && currentStep.fromBlockchain === Network.TERRA) &&
1595
+ // here we must allow ibc on terrastatus
1596
+ sourceWallet.walletType === WalletType.KEPLR) {
1597
+ var _prettifyErrorMessage4 = prettifyErrorMessage('Keplr only supports IBC Transactions on Terra. ' + 'Using Terra Bridge, TerraSwap and THORChain is not possible with Keplr. Please use TerraStation or Leap wallet'),
1598
+ extraMessage = _prettifyErrorMessage4.extraMessage,
1599
+ extraMessageDetail = _prettifyErrorMessage4.extraMessageDetail,
1600
+ extraMessageErrorCode = _prettifyErrorMessage4.extraMessageErrorCode;
1601
+ var _updateResult4 = updateSwapStatus({
1602
+ getStorage: getStorage,
1603
+ setStorage: setStorage,
1604
+ nextStatus: 'failed',
1605
+ nextStepStatus: 'failed',
1606
+ message: extraMessage,
1607
+ details: extraMessageDetail,
1608
+ errorCode: extraMessageErrorCode
1609
+ });
1610
+ notifier(_extends({
1611
+ eventType: 'smart_contract_call_failed'
1612
+ }, _updateResult4));
1613
+ failed();
1614
+ onFinish();
1615
+ return;
1616
+ }
1617
+ walletSigners.executeCosmosMessage(cosmosTransaction, meta).then(
1618
+ // todo
1619
+ function (id) {
1620
+ setStepTransactionIds(actions, id, 'smart_contract_called', notifier);
1621
+ schedule(SwapActionTypes.CHECK_TRANSACTION_STATUS);
1622
+ next();
1623
+ onFinish();
1624
+ }, function (error) {
1625
+ if (swap.status === 'failed') return;
1626
+ var _prettifyErrorMessage5 = prettifyErrorMessage(error),
1627
+ extraMessage = _prettifyErrorMessage5.extraMessage,
1628
+ extraMessageDetail = _prettifyErrorMessage5.extraMessageDetail,
1629
+ extraMessageErrorCode = _prettifyErrorMessage5.extraMessageErrorCode;
1630
+ var updateResult = updateSwapStatus({
1631
+ getStorage: getStorage,
1632
+ setStorage: setStorage,
1633
+ nextStatus: 'failed',
1634
+ nextStepStatus: 'failed',
1635
+ message: extraMessage,
1636
+ details: extraMessageDetail,
1637
+ errorCode: extraMessageErrorCode
1638
+ });
1639
+ notifier(_extends({
1640
+ eventType: 'smart_contract_call_failed'
1641
+ }, updateResult));
1642
+ failed();
1643
+ onFinish();
1644
+ });
1645
+ } else if (!!solanaTransaction) {
1646
+ var _updateResult5 = updateSwapStatus({
1647
+ getStorage: getStorage,
1648
+ setStorage: setStorage,
1649
+ nextStepStatus: 'running',
1650
+ message: executeMessage,
1651
+ details: executeDetails
1652
+ });
1653
+ notifier(_extends({
1654
+ eventType: 'calling_smart_contract'
1655
+ }, _updateResult5));
1656
+ var tx = solanaTransaction;
1657
+ walletSigners.executeSolanaTransaction(tx, swap.requestId).then(function (txId) {
1658
+ setStepTransactionIds(actions, txId, 'smart_contract_called', notifier);
1659
+ schedule(SwapActionTypes.CHECK_TRANSACTION_STATUS);
1660
+ next();
1661
+ onFinish();
1662
+ }, function (error) {
1663
+ if (swap.status === 'failed') return;
1664
+ var _prettifyErrorMessage6 = prettifyErrorMessage(error),
1665
+ extraMessage = _prettifyErrorMessage6.extraMessage,
1666
+ extraMessageDetail = _prettifyErrorMessage6.extraMessageDetail,
1667
+ extraMessageErrorCode = _prettifyErrorMessage6.extraMessageErrorCode;
1668
+ var updateResult = updateSwapStatus({
1669
+ getStorage: getStorage,
1670
+ setStorage: setStorage,
1671
+ nextStatus: 'failed',
1672
+ nextStepStatus: 'failed',
1673
+ message: extraMessage,
1674
+ details: extraMessageDetail,
1675
+ errorCode: extraMessageErrorCode
1676
+ });
1677
+ notifier(_extends({
1678
+ eventType: 'smart_contract_call_failed'
1679
+ }, updateResult));
1680
+ failed();
1681
+ onFinish();
1682
+ });
1683
+ }
1684
+ }
1685
+ /**
1686
+ *
1687
+ * Try to run blocked tasks by wallet and network name.
1688
+ * Goes through queues and extract blocked queues with matched wallet.
1689
+ * If found any blocked tasks with same wallet and network, runs them.
1690
+ * If not, runs only blocked tasks with matched wallet.
1691
+ *
1692
+ * @param wallet_network a string includes `wallet` type and `network` type.
1693
+ * @param manager
1694
+ * @returns
1695
+ */
1696
+ function retryOn(wallet_network, manager, options) {
1697
+ var _finalQueueToBeRun;
1698
+ if (options === void 0) {
1699
+ options = {
1700
+ fallbackToOnlyWallet: true
1701
+ };
1702
+ }
1703
+ var _wallet_network$split2 = wallet_network.split('-'),
1704
+ wallet = _wallet_network$split2[0],
1705
+ network = _wallet_network$split2[1];
1706
+ if (!wallet || !network) {
1707
+ return;
1708
+ }
1709
+ var walletAndNetworkMatched = [];
1710
+ var onlyWalletMatched = [];
1711
+ manager == null ? void 0 : manager.getAll().forEach(function (q) {
1712
+ // retry only on affected queues
1713
+ if (q.status === Status.BLOCKED) {
1714
+ var queueStorage = q.list.getStorage();
1715
+ var swap = queueStorage == null ? void 0 : queueStorage.swapDetails;
1716
+ if (swap) {
1717
+ var currentStep = getCurrentStep(swap);
1718
+ if (currentStep) {
1719
+ var _queueStorage$swapDet2, _queueStorage$swapDet3;
1720
+ if (currentStep.fromBlockchain == network && (queueStorage == null ? void 0 : (_queueStorage$swapDet2 = queueStorage.swapDetails.wallets[network]) == null ? void 0 : _queueStorage$swapDet2.walletType) === wallet) {
1721
+ walletAndNetworkMatched.push(q.list);
1722
+ } else if ((queueStorage == null ? void 0 : (_queueStorage$swapDet3 = queueStorage.swapDetails.wallets[currentStep.fromBlockchain]) == null ? void 0 : _queueStorage$swapDet3.walletType) === wallet) {
1723
+ onlyWalletMatched.push(q.list);
1724
+ }
1725
+ }
1726
+ }
1727
+ }
1728
+ });
1729
+ // const isWaitingForConnectWallet = (status: Status) =>
1730
+ var finalQueueToBeRun = undefined;
1731
+ if (walletAndNetworkMatched.length > 0) {
1732
+ finalQueueToBeRun = walletAndNetworkMatched[0];
1733
+ if (walletAndNetworkMatched.length > 1) {
1734
+ for (var i = 1; i < walletAndNetworkMatched.length; i++) {
1735
+ var currentQueue = walletAndNetworkMatched[i];
1736
+ markRunningSwapAsDependsOnOtherQueues({
1737
+ getStorage: currentQueue.getStorage.bind(currentQueue),
1738
+ setStorage: currentQueue.setStorage.bind(currentQueue)
1739
+ });
1740
+ }
1741
+ }
1742
+ } else if (onlyWalletMatched.length > 0 && options.fallbackToOnlyWallet) {
1743
+ finalQueueToBeRun = onlyWalletMatched[0];
1744
+ }
1745
+ (_finalQueueToBeRun = finalQueueToBeRun) == null ? void 0 : _finalQueueToBeRun.checkBlock();
1746
+ }
1747
+ /*
1748
+ For avoiding conflict by making too many requests to wallet, we need to make sure
1749
+ We only run one request at a time (In parallel mode).
1750
+ */
1751
+ function isNeedBlockQueueForParallel(step) {
1752
+ return !!step.evmTransaction || !!step.evmApprovalTransaction || !!step.cosmosTransaction;
1753
+ }
1754
+
1755
+ var INTERVAL_FOR_CHECK = 2000;
1756
+ /**
1757
+ * Subscribe to status of swap transaction by checking from server periodically.
1758
+ * After getting the status, notify the user and schedule `SCHEDULE_NEXT_STEP`.
1759
+ */
1760
+ function checkTransactionStatus(_x) {
1761
+ return _checkTransactionStatus.apply(this, arguments);
1762
+ }
1763
+ /**
1764
+ * Subscribe to status of approval transaction by checking from server periodically.
1765
+ * After getting the status, notify the user and schedule `SCHEDULE_NEXT_STEP`.
1766
+ */
1767
+ function _checkTransactionStatus() {
1768
+ _checkTransactionStatus = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(_ref) {
1769
+ var _status, _status2, _status3, _status4, _status5, _status6, _status7, _status8, _status9, _status10;
1770
+ var getStorage, setStorage, next, schedule, retry, context, swap, currentStep, txId, status, outputAmount, prevOutputAmount, newTransaction, nextStep;
1771
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
1772
+ while (1) switch (_context.prev = _context.next) {
1773
+ case 0:
1774
+ getStorage = _ref.getStorage, setStorage = _ref.setStorage, next = _ref.next, schedule = _ref.schedule, retry = _ref.retry, context = _ref.context;
1775
+ swap = getStorage().swapDetails; // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1776
+ currentStep = getCurrentStep(swap);
1777
+ txId = currentStep.executedTransactionId;
1778
+ status = null;
1779
+ _context.prev = 5;
1780
+ _context.next = 8;
1781
+ return checkSwapStatus(swap.requestId, txId, currentStep.id);
1782
+ case 8:
1783
+ status = _context.sent;
1784
+ _context.next = 17;
1785
+ break;
1786
+ case 11:
1787
+ _context.prev = 11;
1788
+ _context.t0 = _context["catch"](5);
1789
+ _context.next = 15;
1790
+ return delay(INTERVAL_FOR_CHECK);
1791
+ case 15:
1792
+ retry();
1793
+ return _context.abrupt("return");
1794
+ case 17:
1795
+ outputAmount = ((_status = status) == null ? void 0 : _status.outputAmount) || (!!currentStep.outputAmount ? new BigNumber$1(currentStep.outputAmount) : null);
1796
+ prevOutputAmount = currentStep.outputAmount;
1797
+ swap.extraMessage = ((_status2 = status) == null ? void 0 : _status2.extraMessage) || swap.extraMessage;
1798
+ swap.extraMessageSeverity = MessageSeverity.info;
1799
+ swap.extraMessageDetail = '';
1800
+ currentStep.status = ((_status3 = status) == null ? void 0 : _status3.status) || currentStep.status;
1801
+ currentStep.diagnosisUrl = ((_status4 = status) == null ? void 0 : _status4.diagnosisUrl) || currentStep.diagnosisUrl || null;
1802
+ currentStep.outputAmount = (outputAmount == null ? void 0 : outputAmount.toFixed()) || currentStep.outputAmount;
1803
+ currentStep.explorerUrl = ((_status5 = status) == null ? void 0 : _status5.explorerUrl) || currentStep.explorerUrl;
1804
+ currentStep.internalSteps = ((_status6 = status) == null ? void 0 : _status6.steps) || null;
1805
+ newTransaction = (_status7 = status) == null ? void 0 : _status7.newTx;
1806
+ if (!!newTransaction) {
1807
+ currentStep.status = 'created';
1808
+ currentStep.executedTransactionId = null;
1809
+ currentStep.transferTransaction = null;
1810
+ currentStep.cosmosTransaction = null;
1811
+ currentStep.evmTransaction = null;
1812
+ currentStep.solanaTransaction = null;
1813
+ currentStep.evmApprovalTransaction = null;
1814
+ currentStep.starknetApprovalTransaction = null;
1815
+ currentStep.starknetTransaction = null;
1816
+ currentStep.tronApprovalTransaction = null;
1817
+ currentStep.tronTransaction = null;
1818
+ if (isEvmTransaction(newTransaction)) {
1819
+ if (newTransaction.isApprovalTx) currentStep.evmApprovalTransaction = newTransaction;else currentStep.evmTransaction = newTransaction;
1820
+ } else if (isCosmosTransaction(newTransaction)) {
1821
+ currentStep.cosmosTransaction = newTransaction;
1822
+ } else if (isSolanaTransaction(newTransaction)) {
1823
+ currentStep.solanaTransaction = newTransaction;
1824
+ } else if (isTrasnferTransaction(newTransaction)) {
1825
+ currentStep.transferTransaction = newTransaction;
1826
+ } else if (isStarknetTransaction(newTransaction)) {
1827
+ if (newTransaction.isApprovalTx) currentStep.starknetApprovalTransaction = newTransaction;else currentStep.starknetTransaction = newTransaction;
1828
+ } else if (isTronTransaction(newTransaction)) {
1829
+ if (newTransaction.isApprovalTx) currentStep.tronApprovalTransaction = newTransaction;else currentStep.tronTransaction = newTransaction;
1830
+ }
1831
+ }
1832
+ if (prevOutputAmount === null && outputAmount !== null) context.notifier({
1833
+ eventType: 'step_completed_with_output',
1834
+ swap: swap,
1835
+ step: currentStep
1836
+ });
1837
+ if (currentStep.status === 'success') {
1838
+ nextStep = getNextStep(swap, currentStep);
1839
+ swap.extraMessageDetail = '';
1840
+ swap.extraMessage = !!nextStep ? "starting next step: " + nextStep.swapperId + ": " + nextStep.fromBlockchain + " -> " + nextStep.toBlockchain : '';
1841
+ }
1842
+ // Sync data with storage
1843
+ setStorage(_extends({}, getStorage(), {
1844
+ swapDetails: swap
1845
+ }));
1846
+ if (!(((_status8 = status) == null ? void 0 : _status8.status) === 'failed' || ((_status9 = status) == null ? void 0 : _status9.status) === 'success' || ((_status10 = status) == null ? void 0 : _status10.status) === 'running' && !!status.newTx)) {
1847
+ _context.next = 37;
1848
+ break;
1849
+ }
1850
+ schedule(SwapActionTypes.SCHEDULE_NEXT_STEP);
1851
+ next();
1852
+ _context.next = 40;
1853
+ break;
1854
+ case 37:
1855
+ _context.next = 39;
1856
+ return delay(INTERVAL_FOR_CHECK);
1857
+ case 39:
1858
+ retry();
1859
+ case 40:
1860
+ case "end":
1861
+ return _context.stop();
1862
+ }
1863
+ }, _callee, null, [[5, 11]]);
1864
+ }));
1865
+ return _checkTransactionStatus.apply(this, arguments);
1866
+ }
1867
+ function checkApprovalStatus(_x2) {
1868
+ return _checkApprovalStatus.apply(this, arguments);
1869
+ }
1870
+ /**
1871
+ *
1872
+ * For doing a swap the user needs to accept a `contract` so it can use the user balance.
1873
+ * There is two types of check status:
1874
+ * 1. Checking approval transaction (Give permission to a contract)
1875
+ * 2. Checking swap transaction.
1876
+ *
1877
+ */
1878
+ function _checkApprovalStatus() {
1879
+ _checkApprovalStatus = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(_ref2) {
1880
+ var getStorage, setStorage, next, schedule, retry, context, swap, currentStep, isApproved, response;
1881
+ return _regeneratorRuntime().wrap(function _callee2$(_context2) {
1882
+ while (1) switch (_context2.prev = _context2.next) {
1883
+ case 0:
1884
+ getStorage = _ref2.getStorage, setStorage = _ref2.setStorage, next = _ref2.next, schedule = _ref2.schedule, retry = _ref2.retry, context = _ref2.context;
1885
+ swap = getStorage().swapDetails; // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1886
+ currentStep = getCurrentStep(swap);
1887
+ isApproved = false;
1888
+ _context2.prev = 4;
1889
+ _context2.next = 7;
1890
+ return checkApproved(swap.requestId);
1891
+ case 7:
1892
+ response = _context2.sent;
1893
+ isApproved = response.isApproved;
1894
+ _context2.next = 14;
1895
+ break;
1896
+ case 11:
1897
+ _context2.prev = 11;
1898
+ _context2.t0 = _context2["catch"](4);
1899
+ console.error('Failed to check getApprovedAmount', _context2.t0);
1900
+ case 14:
1901
+ if (!isApproved) {
1902
+ _context2.next = 27;
1903
+ break;
1904
+ }
1905
+ currentStep.status = 'approved';
1906
+ swap.extraMessage = "Spending " + currentStep.fromSymbol + " approved successfully.";
1907
+ swap.extraMessageDetail = null;
1908
+ swap.extraMessageSeverity = MessageSeverity.success;
1909
+ currentStep.evmApprovalTransaction = null;
1910
+ currentStep.executedTransactionId = null;
1911
+ setStorage(_extends({}, getStorage(), {
1912
+ swapDetails: swap
1913
+ }));
1914
+ context.notifier({
1915
+ eventType: 'contract_confirmed',
1916
+ swap: swap,
1917
+ step: currentStep
1918
+ });
1919
+ schedule(SwapActionTypes.SCHEDULE_NEXT_STEP);
1920
+ next();
1921
+ _context2.next = 30;
1922
+ break;
1923
+ case 27:
1924
+ _context2.next = 29;
1925
+ return delay(2000);
1926
+ case 29:
1927
+ retry();
1928
+ case 30:
1929
+ case "end":
1930
+ return _context2.stop();
1931
+ }
1932
+ }, _callee2, null, [[4, 11]]);
1933
+ }));
1934
+ return _checkApprovalStatus.apply(this, arguments);
1935
+ }
1936
+ function checkStatus(_x3) {
1937
+ return _checkStatus.apply(this, arguments);
1938
+ }
1939
+ function _checkStatus() {
1940
+ _checkStatus = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3(actions) {
1941
+ var swap, currentStep;
1942
+ return _regeneratorRuntime().wrap(function _callee3$(_context3) {
1943
+ while (1) switch (_context3.prev = _context3.next) {
1944
+ case 0:
1945
+ swap = actions.getStorage().swapDetails; // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1946
+ currentStep = getCurrentStep(swap); // Reset network status
1947
+ // Because when check status is on `loading` or `failed` status, it shows previous message that isn't related to current state.
1948
+ resetNetworkStatus(actions);
1949
+ if (!(currentStep.status === 'running')) {
1950
+ _context3.next = 8;
1951
+ break;
1952
+ }
1953
+ _context3.next = 6;
1954
+ return checkTransactionStatus(actions);
1955
+ case 6:
1956
+ _context3.next = 11;
1957
+ break;
1958
+ case 8:
1959
+ if (!(currentStep.status === 'waitingForApproval')) {
1960
+ _context3.next = 11;
1961
+ break;
1962
+ }
1963
+ _context3.next = 11;
1964
+ return checkApprovalStatus(actions);
1965
+ case 11:
1966
+ case "end":
1967
+ return _context3.stop();
1968
+ }
1969
+ }, _callee3);
1970
+ }));
1971
+ return _checkStatus.apply(this, arguments);
1972
+ }
1973
+
1974
+ /**
1975
+ *
1976
+ * When a user asks for a swap, We first create the transaction by sending a request to server
1977
+ * Server will return the transaction that need to be sent to wallet.
1978
+ * It can be failed if server goes through an error, If not, we will schedule the `EXECTUTE_TRANSACTION`.
1979
+ *
1980
+ */
1981
+ function createTransaction$1(_x) {
1982
+ return _createTransaction$1.apply(this, arguments);
1983
+ }
1984
+ function _createTransaction$1() {
1985
+ _createTransaction$1 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(actions) {
1986
+ var setStorage, getStorage, next, schedule, context, swap, currentStep, evmTransaction, cosmosTransaction, transferTransaction, evmApprovalTransaction, solanaTransaction, request, _yield$requestTransac, transaction, _prettifyErrorMessage, extraMessage, extraMessageDetail, updateResult;
1987
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
1988
+ while (1) switch (_context.prev = _context.next) {
1989
+ case 0:
1990
+ setStorage = actions.setStorage, getStorage = actions.getStorage, next = actions.next, schedule = actions.schedule, context = actions.context;
1991
+ swap = getStorage().swapDetails; // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1992
+ currentStep = getCurrentStep(swap);
1993
+ evmTransaction = currentStep.evmTransaction, cosmosTransaction = currentStep.cosmosTransaction, transferTransaction = currentStep.transferTransaction, evmApprovalTransaction = currentStep.evmApprovalTransaction, solanaTransaction = currentStep.solanaTransaction;
1994
+ if (!(!evmTransaction && !cosmosTransaction && !transferTransaction && !evmApprovalTransaction && !solanaTransaction)) {
1995
+ _context.next = 25;
1996
+ break;
1997
+ }
1998
+ request = {
1999
+ requestId: swap.requestId,
2000
+ step: currentStep.id,
2001
+ userSettings: {
2002
+ slippage: swap.settings.slippage,
2003
+ infiniteApprove: swap.settings.infiniteApprove
2004
+ },
2005
+ validations: {
2006
+ balance: swap.validateBalanceOrFee,
2007
+ fee: swap.validateBalanceOrFee
2008
+ }
2009
+ };
2010
+ _context.prev = 6;
2011
+ _context.next = 9;
2012
+ return createTransaction(request);
2013
+ case 9:
2014
+ _yield$requestTransac = _context.sent;
2015
+ transaction = _yield$requestTransac.transaction;
2016
+ if (transaction) {
2017
+ if (isEvmTransaction(transaction)) {
2018
+ if (transaction.isApprovalTx) currentStep.evmApprovalTransaction = transaction;else currentStep.evmTransaction = transaction;
2019
+ } else if (isCosmosTransaction(transaction)) {
2020
+ currentStep.cosmosTransaction = transaction;
2021
+ } else if (isSolanaTransaction(transaction)) {
2022
+ currentStep.solanaTransaction = transaction;
2023
+ } else if (isTrasnferTransaction(transaction)) {
2024
+ currentStep.transferTransaction = transaction;
2025
+ }
2026
+ }
2027
+ setStorage(_extends({}, getStorage(), {
2028
+ swapDetails: swap
2029
+ }));
2030
+ schedule(SwapActionTypes.EXECUTE_TRANSACTION);
2031
+ next();
2032
+ _context.next = 25;
2033
+ break;
2034
+ case 17:
2035
+ _context.prev = 17;
2036
+ _context.t0 = _context["catch"](6);
2037
+ swap.status = 'failed';
2038
+ swap.finishTime = new Date().getTime().toString();
2039
+ _prettifyErrorMessage = prettifyErrorMessage(_context.t0), extraMessage = _prettifyErrorMessage.extraMessage, extraMessageDetail = _prettifyErrorMessage.extraMessageDetail;
2040
+ updateResult = updateSwapStatus({
2041
+ getStorage: getStorage,
2042
+ setStorage: setStorage,
2043
+ nextStatus: 'failed',
2044
+ nextStepStatus: 'failed',
2045
+ message: extraMessage,
2046
+ details: extraMessageDetail,
2047
+ errorCode: APIErrorCode.FETCH_TX_FAILED
2048
+ });
2049
+ context.notifier(_extends({
2050
+ eventType: 'task_failed'
2051
+ }, updateResult));
2052
+ actions.failed();
2053
+ case 25:
2054
+ case "end":
2055
+ return _context.stop();
2056
+ }
2057
+ }, _callee, null, [[6, 17]]);
2058
+ }));
2059
+ return _createTransaction$1.apply(this, arguments);
2060
+ }
2061
+
2062
+ /**
2063
+ * Excecute a created transaction.
2064
+ *
2065
+ * This function implemented the parallel mode by `claim` mechanism which means
2066
+ * All the queues the meet certain situation (like multiple evm transaction) will go through
2067
+ * a `claim` mechanims that decides which queue should be run and it blocks other ones.
2068
+ *
2069
+ * A queue will be go to sign process, if the wallet and network is matched.
2070
+ */
2071
+ function executeTransaction(_x) {
2072
+ return _executeTransaction.apply(this, arguments);
2073
+ }
2074
+ function _executeTransaction() {
2075
+ _executeTransaction = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(actions) {
2076
+ var _context$_queue;
2077
+ var getStorage, context, meta, wallets, providers, isClaimed, requestBlock, swap, currentStep, isWrongAddress, _getRequiredWallet, type, address, description, blockedFor, needsToBlockQueue, _blockedFor, networkMatched, fromBlockchain, details, _blockedFor2;
2078
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
2079
+ while (1) switch (_context.prev = _context.next) {
2080
+ case 0:
2081
+ getStorage = actions.getStorage, context = actions.context;
2082
+ meta = context.meta, wallets = context.wallets, providers = context.providers;
2083
+ isClaimed = context.claimedBy === ((_context$_queue = context._queue) == null ? void 0 : _context$_queue.id);
2084
+ requestBlock = function requestBlock(blockedFor) {
2085
+ actions.block(blockedFor);
2086
+ if (isClaimed && actions.context.resetClaimedBy) {
2087
+ actions.context.resetClaimedBy();
2088
+ }
2089
+ };
2090
+ swap = getStorage().swapDetails; // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2091
+ currentStep = getCurrentStep(swap); // Resetting network status, so we will set it again during the running of this task.
2092
+ resetNetworkStatus(actions);
2093
+ /* Make sure wallet is connected and also the connected wallet is matched with tx by checking address. */
2094
+ isWrongAddress = !isRequiredWalletConnected(swap, context.state);
2095
+ if (!isWrongAddress) {
2096
+ _context.next = 14;
2097
+ break;
2098
+ }
2099
+ _getRequiredWallet = getRequiredWallet(swap), type = _getRequiredWallet.type, address = _getRequiredWallet.address;
2100
+ description = !wallets ? ERROR_MESSAGE_WAIT_FOR_WALLET_DESCRIPTION(type) : ERROR_MESSAGE_WAIT_FOR_WALLET_DESCRIPTION_WRONG_WALLET(type, address);
2101
+ blockedFor = {
2102
+ reason: BlockReason.WAIT_FOR_CONNECT_WALLET,
2103
+ description: description
2104
+ };
2105
+ requestBlock(blockedFor);
2106
+ return _context.abrupt("return");
2107
+ case 14:
2108
+ /*
2109
+ For avoiding conflict by making too many requests to wallet, we need to make sure
2110
+ We only run one request at a time (In parallel mode).
2111
+ */
2112
+ needsToBlockQueue = isNeedBlockQueueForParallel(currentStep);
2113
+ if (!(needsToBlockQueue && !isClaimed && context.claimedBy)) {
2114
+ _context.next = 19;
2115
+ break;
2116
+ }
2117
+ _blockedFor = {
2118
+ reason: BlockReason.DEPENDS_ON_OTHER_QUEUES,
2119
+ description: 'Waiting for other running tasks to be finished',
2120
+ details: {}
2121
+ };
2122
+ requestBlock(_blockedFor);
2123
+ return _context.abrupt("return");
2124
+ case 19:
2125
+ _context.next = 21;
2126
+ return isNetworkMatchedForTransaction(swap, currentStep, wallets, meta, providers);
2127
+ case 21:
2128
+ networkMatched = _context.sent;
2129
+ if (networkMatched) {
2130
+ _context.next = 30;
2131
+ break;
2132
+ }
2133
+ fromBlockchain = getCurrentBlockchainOf(swap, currentStep);
2134
+ details = ERROR_MESSAGE_WAIT_FOR_CHANGE_NETWORK(fromBlockchain);
2135
+ _blockedFor2 = {
2136
+ reason: BlockReason.WAIT_FOR_NETWORK_CHANGE,
2137
+ details: details
2138
+ };
2139
+ requestBlock(_blockedFor2);
2140
+ return _context.abrupt("return");
2141
+ case 30:
2142
+ // Update network to mark it as network changed successfully.
2143
+ updateNetworkStatus(actions, {
2144
+ message: '',
2145
+ details: 'Wallet network changed successfully',
2146
+ status: PendingSwapNetworkStatus.NetworkChanged
2147
+ });
2148
+ case 31:
2149
+ // All the conditions are met. We can safely send the tx to wallet for sign.
2150
+ singTransaction(actions);
2151
+ case 32:
2152
+ case "end":
2153
+ return _context.stop();
2154
+ }
2155
+ }, _callee);
2156
+ }));
2157
+ return _executeTransaction.apply(this, arguments);
2158
+ }
2159
+
2160
+ /**
2161
+ *
2162
+ * This function is responsibe for scheduling the correct `action` based on `PendingSwap` status.
2163
+ * It means `action`s schedule this step to decide what should be the next step/task.
2164
+ *
2165
+ * It's acts like a `while(true)` and will `break` the loop on certain `action`s like `CHECK_STATUS`.
2166
+ *
2167
+ *
2168
+ */
2169
+ function scheduleNextStep(_ref) {
2170
+ var schedule = _ref.schedule,
2171
+ next = _ref.next,
2172
+ failed = _ref.failed,
2173
+ setStorage = _ref.setStorage,
2174
+ getStorage = _ref.getStorage,
2175
+ context = _ref.context;
2176
+ var swap = getStorage().swapDetails;
2177
+ var currentStep = getCurrentStep(swap);
2178
+ if (!!currentStep) {
2179
+ if (isTxAlreadyCreated(swap, currentStep)) {
2180
+ schedule(SwapActionTypes.EXECUTE_TRANSACTION);
2181
+ return next();
2182
+ }
2183
+ if (currentStep != null && currentStep.executedTransactionId) {
2184
+ schedule(SwapActionTypes.CHECK_TRANSACTION_STATUS);
2185
+ return next();
2186
+ }
2187
+ swap.status = 'running';
2188
+ setStorage(_extends({}, getStorage(), {
2189
+ swapDetails: swap
2190
+ }));
2191
+ schedule(SwapActionTypes.CREATE_TRANSACTION);
2192
+ next();
2193
+ } else {
2194
+ var isFailed = swap.steps.find(function (step) {
2195
+ return step.status === 'failed';
2196
+ });
2197
+ swap.status = isFailed ? 'failed' : 'success';
2198
+ swap.finishTime = new Date().getTime().toString();
2199
+ setStorage(_extends({}, getStorage(), {
2200
+ swapDetails: swap
2201
+ }));
2202
+ context.notifier({
2203
+ eventType: isFailed ? 'task_failed' : 'task_completed',
2204
+ swap: swap,
2205
+ step: null
2206
+ });
2207
+ if (isFailed) failed();else next();
2208
+ }
2209
+ }
2210
+
2211
+ function start(_ref) {
2212
+ var schedule = _ref.schedule,
2213
+ next = _ref.next;
2214
+ schedule(SwapActionTypes.SCHEDULE_NEXT_STEP);
2215
+ next();
2216
+ }
2217
+
2218
+ var _actions;
2219
+ /**
2220
+ *
2221
+ * The idea behind this queue is to be able dynamically add some steps.
2222
+ * After running a swap, it can be blocked (like on waiting for switch netwrok)
2223
+ * or waits for something happend (like checking status of a transaction from server)
2224
+ *
2225
+ */
2226
+ var swapQueueDef = {
2227
+ name: 'swap',
2228
+ actions: (_actions = {}, _actions[SwapActionTypes.START] = start, _actions[SwapActionTypes.SCHEDULE_NEXT_STEP] = scheduleNextStep, _actions[SwapActionTypes.CREATE_TRANSACTION] = createTransaction$1, _actions[SwapActionTypes.EXECUTE_TRANSACTION] = executeTransaction, _actions[SwapActionTypes.CHECK_TRANSACTION_STATUS] = checkStatus, _actions),
2229
+ run: [SwapActionTypes.START],
2230
+ whenTaskBlocked: function whenTaskBlocked(event, meta) {
2231
+ if (event.reason.reason === BlockReason.WAIT_FOR_CONNECT_WALLET) {
2232
+ onBlockForConnectWallet(event, meta);
2233
+ } else if (event.reason.reason === BlockReason.WAIT_FOR_NETWORK_CHANGE) {
2234
+ onBlockForChangeNetwork(event, meta);
2235
+ } else if (event.reason.reason === BlockReason.DEPENDS_ON_OTHER_QUEUES) {
2236
+ onDependsOnOtherQueues(event, meta);
2237
+ }
2238
+ }
2239
+ };
2240
+
2241
+ export { swapQueueDef };
2242
+ //# sourceMappingURL=queue-manager-rango-preset.esm.js.map