@imtbl/sdk 0.4.0-alpha.2 → 0.4.1-alpha

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,15 +1,19 @@
1
- import globalAxios$1 from 'axios';
1
+ import axios$2 from 'axios';
2
2
  import { ImmutableX, Config, generateLegacyStarkPrivateKey, createStarkSigner, TransfersApi, OrdersApi as OrdersApi$1, UsersApi, Contracts, TradesApi, ExchangesApi, WithdrawalsApi, MintsApi, DepositsApi, EncodingApi, TokensApi as TokensApi$1 } from '@imtbl/core-sdk';
3
3
  export { createStarkSigner as imxClientCreateStarkSigner, generateLegacyStarkPrivateKey as imxClientGenerateLegacyStarkPrivateKey } from '@imtbl/core-sdk';
4
4
  import { UserManager } from 'oidc-client-ts';
5
5
  import jwt_decode from 'jwt-decode';
6
+ import * as crypto from 'crypto';
6
7
  import { Magic } from 'magic-sdk';
7
8
  import { OpenIdExtension } from '@magic-ext/oidc';
9
+ import { BigNumber as BigNumber$1, ethers, providers, constants, utils as utils$2, Contract as Contract$1, ContractFactory } from 'ethers';
8
10
  import BN$2 from 'bn.js';
9
11
  import * as encUtils from 'enc-utils';
10
12
  import { Web3Provider, JsonRpcProvider } from '@ethersproject/providers';
13
+ import { EventEmitter } from 'events';
14
+ import { walletContracts } from '@0xsequence/abi';
15
+ import { encodeSignature } from '@0xsequence/config';
11
16
  import FormData$2 from 'form-data';
12
- import { providers, BigNumber as BigNumber$1, constants, utils as utils$1, Contract as Contract$1, ethers, ContractFactory } from 'ethers';
13
17
  import { Seaport as Seaport$1 } from '@opensea/seaport-js';
14
18
  import { parseUnits } from '@ethersproject/units';
15
19
  import { BigNumber as BigNumber$2 } from '@ethersproject/bignumber';
@@ -37,6 +41,3302 @@ class ImmutableConfiguration {
37
41
  }
38
42
  }
39
43
 
44
+ function bind$1(fn, thisArg) {
45
+ return function wrap() {
46
+ return fn.apply(thisArg, arguments);
47
+ };
48
+ }
49
+
50
+ // utils is a library of generic helper functions non-specific to axios
51
+
52
+ const {toString: toString$1} = Object.prototype;
53
+ const {getPrototypeOf: getPrototypeOf$1} = Object;
54
+
55
+ const kindOf$1 = (cache => thing => {
56
+ const str = toString$1.call(thing);
57
+ return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase());
58
+ })(Object.create(null));
59
+
60
+ const kindOfTest$1 = (type) => {
61
+ type = type.toLowerCase();
62
+ return (thing) => kindOf$1(thing) === type
63
+ };
64
+
65
+ const typeOfTest$1 = type => thing => typeof thing === type;
66
+
67
+ /**
68
+ * Determine if a value is an Array
69
+ *
70
+ * @param {Object} val The value to test
71
+ *
72
+ * @returns {boolean} True if value is an Array, otherwise false
73
+ */
74
+ const {isArray: isArray$1} = Array;
75
+
76
+ /**
77
+ * Determine if a value is undefined
78
+ *
79
+ * @param {*} val The value to test
80
+ *
81
+ * @returns {boolean} True if the value is undefined, otherwise false
82
+ */
83
+ const isUndefined$1 = typeOfTest$1('undefined');
84
+
85
+ /**
86
+ * Determine if a value is a Buffer
87
+ *
88
+ * @param {*} val The value to test
89
+ *
90
+ * @returns {boolean} True if value is a Buffer, otherwise false
91
+ */
92
+ function isBuffer$1(val) {
93
+ return val !== null && !isUndefined$1(val) && val.constructor !== null && !isUndefined$1(val.constructor)
94
+ && isFunction$1(val.constructor.isBuffer) && val.constructor.isBuffer(val);
95
+ }
96
+
97
+ /**
98
+ * Determine if a value is an ArrayBuffer
99
+ *
100
+ * @param {*} val The value to test
101
+ *
102
+ * @returns {boolean} True if value is an ArrayBuffer, otherwise false
103
+ */
104
+ const isArrayBuffer$1 = kindOfTest$1('ArrayBuffer');
105
+
106
+
107
+ /**
108
+ * Determine if a value is a view on an ArrayBuffer
109
+ *
110
+ * @param {*} val The value to test
111
+ *
112
+ * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false
113
+ */
114
+ function isArrayBufferView$1(val) {
115
+ let result;
116
+ if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) {
117
+ result = ArrayBuffer.isView(val);
118
+ } else {
119
+ result = (val) && (val.buffer) && (isArrayBuffer$1(val.buffer));
120
+ }
121
+ return result;
122
+ }
123
+
124
+ /**
125
+ * Determine if a value is a String
126
+ *
127
+ * @param {*} val The value to test
128
+ *
129
+ * @returns {boolean} True if value is a String, otherwise false
130
+ */
131
+ const isString$2 = typeOfTest$1('string');
132
+
133
+ /**
134
+ * Determine if a value is a Function
135
+ *
136
+ * @param {*} val The value to test
137
+ * @returns {boolean} True if value is a Function, otherwise false
138
+ */
139
+ const isFunction$1 = typeOfTest$1('function');
140
+
141
+ /**
142
+ * Determine if a value is a Number
143
+ *
144
+ * @param {*} val The value to test
145
+ *
146
+ * @returns {boolean} True if value is a Number, otherwise false
147
+ */
148
+ const isNumber$1 = typeOfTest$1('number');
149
+
150
+ /**
151
+ * Determine if a value is an Object
152
+ *
153
+ * @param {*} thing The value to test
154
+ *
155
+ * @returns {boolean} True if value is an Object, otherwise false
156
+ */
157
+ const isObject$1 = (thing) => thing !== null && typeof thing === 'object';
158
+
159
+ /**
160
+ * Determine if a value is a Boolean
161
+ *
162
+ * @param {*} thing The value to test
163
+ * @returns {boolean} True if value is a Boolean, otherwise false
164
+ */
165
+ const isBoolean$1 = thing => thing === true || thing === false;
166
+
167
+ /**
168
+ * Determine if a value is a plain Object
169
+ *
170
+ * @param {*} val The value to test
171
+ *
172
+ * @returns {boolean} True if value is a plain Object, otherwise false
173
+ */
174
+ const isPlainObject$1 = (val) => {
175
+ if (kindOf$1(val) !== 'object') {
176
+ return false;
177
+ }
178
+
179
+ const prototype = getPrototypeOf$1(val);
180
+ return (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(Symbol.toStringTag in val) && !(Symbol.iterator in val);
181
+ };
182
+
183
+ /**
184
+ * Determine if a value is a Date
185
+ *
186
+ * @param {*} val The value to test
187
+ *
188
+ * @returns {boolean} True if value is a Date, otherwise false
189
+ */
190
+ const isDate$1 = kindOfTest$1('Date');
191
+
192
+ /**
193
+ * Determine if a value is a File
194
+ *
195
+ * @param {*} val The value to test
196
+ *
197
+ * @returns {boolean} True if value is a File, otherwise false
198
+ */
199
+ const isFile$1 = kindOfTest$1('File');
200
+
201
+ /**
202
+ * Determine if a value is a Blob
203
+ *
204
+ * @param {*} val The value to test
205
+ *
206
+ * @returns {boolean} True if value is a Blob, otherwise false
207
+ */
208
+ const isBlob$2 = kindOfTest$1('Blob');
209
+
210
+ /**
211
+ * Determine if a value is a FileList
212
+ *
213
+ * @param {*} val The value to test
214
+ *
215
+ * @returns {boolean} True if value is a File, otherwise false
216
+ */
217
+ const isFileList$1 = kindOfTest$1('FileList');
218
+
219
+ /**
220
+ * Determine if a value is a Stream
221
+ *
222
+ * @param {*} val The value to test
223
+ *
224
+ * @returns {boolean} True if value is a Stream, otherwise false
225
+ */
226
+ const isStream$1 = (val) => isObject$1(val) && isFunction$1(val.pipe);
227
+
228
+ /**
229
+ * Determine if a value is a FormData
230
+ *
231
+ * @param {*} thing The value to test
232
+ *
233
+ * @returns {boolean} True if value is an FormData, otherwise false
234
+ */
235
+ const isFormData$2 = (thing) => {
236
+ let kind;
237
+ return thing && (
238
+ (typeof FormData === 'function' && thing instanceof FormData) || (
239
+ isFunction$1(thing.append) && (
240
+ (kind = kindOf$1(thing)) === 'formdata' ||
241
+ // detect form-data instance
242
+ (kind === 'object' && isFunction$1(thing.toString) && thing.toString() === '[object FormData]')
243
+ )
244
+ )
245
+ )
246
+ };
247
+
248
+ /**
249
+ * Determine if a value is a URLSearchParams object
250
+ *
251
+ * @param {*} val The value to test
252
+ *
253
+ * @returns {boolean} True if value is a URLSearchParams object, otherwise false
254
+ */
255
+ const isURLSearchParams$1 = kindOfTest$1('URLSearchParams');
256
+
257
+ /**
258
+ * Trim excess whitespace off the beginning and end of a string
259
+ *
260
+ * @param {String} str The String to trim
261
+ *
262
+ * @returns {String} The String freed of excess whitespace
263
+ */
264
+ const trim$1 = (str) => str.trim ?
265
+ str.trim() : str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
266
+
267
+ /**
268
+ * Iterate over an Array or an Object invoking a function for each item.
269
+ *
270
+ * If `obj` is an Array callback will be called passing
271
+ * the value, index, and complete array for each item.
272
+ *
273
+ * If 'obj' is an Object callback will be called passing
274
+ * the value, key, and complete object for each property.
275
+ *
276
+ * @param {Object|Array} obj The object to iterate
277
+ * @param {Function} fn The callback to invoke for each item
278
+ *
279
+ * @param {Boolean} [allOwnKeys = false]
280
+ * @returns {any}
281
+ */
282
+ function forEach$1(obj, fn, {allOwnKeys = false} = {}) {
283
+ // Don't bother if no value provided
284
+ if (obj === null || typeof obj === 'undefined') {
285
+ return;
286
+ }
287
+
288
+ let i;
289
+ let l;
290
+
291
+ // Force an array if not already something iterable
292
+ if (typeof obj !== 'object') {
293
+ /*eslint no-param-reassign:0*/
294
+ obj = [obj];
295
+ }
296
+
297
+ if (isArray$1(obj)) {
298
+ // Iterate over array values
299
+ for (i = 0, l = obj.length; i < l; i++) {
300
+ fn.call(null, obj[i], i, obj);
301
+ }
302
+ } else {
303
+ // Iterate over object keys
304
+ const keys = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj);
305
+ const len = keys.length;
306
+ let key;
307
+
308
+ for (i = 0; i < len; i++) {
309
+ key = keys[i];
310
+ fn.call(null, obj[key], key, obj);
311
+ }
312
+ }
313
+ }
314
+
315
+ function findKey$1(obj, key) {
316
+ key = key.toLowerCase();
317
+ const keys = Object.keys(obj);
318
+ let i = keys.length;
319
+ let _key;
320
+ while (i-- > 0) {
321
+ _key = keys[i];
322
+ if (key === _key.toLowerCase()) {
323
+ return _key;
324
+ }
325
+ }
326
+ return null;
327
+ }
328
+
329
+ const _global$1 = (() => {
330
+ /*eslint no-undef:0*/
331
+ if (typeof globalThis !== "undefined") return globalThis;
332
+ return typeof self !== "undefined" ? self : (typeof window !== 'undefined' ? window : global)
333
+ })();
334
+
335
+ const isContextDefined$1 = (context) => !isUndefined$1(context) && context !== _global$1;
336
+
337
+ /**
338
+ * Accepts varargs expecting each argument to be an object, then
339
+ * immutably merges the properties of each object and returns result.
340
+ *
341
+ * When multiple objects contain the same key the later object in
342
+ * the arguments list will take precedence.
343
+ *
344
+ * Example:
345
+ *
346
+ * ```js
347
+ * var result = merge({foo: 123}, {foo: 456});
348
+ * console.log(result.foo); // outputs 456
349
+ * ```
350
+ *
351
+ * @param {Object} obj1 Object to merge
352
+ *
353
+ * @returns {Object} Result of all merge properties
354
+ */
355
+ function merge$1(/* obj1, obj2, obj3, ... */) {
356
+ const {caseless} = isContextDefined$1(this) && this || {};
357
+ const result = {};
358
+ const assignValue = (val, key) => {
359
+ const targetKey = caseless && findKey$1(result, key) || key;
360
+ if (isPlainObject$1(result[targetKey]) && isPlainObject$1(val)) {
361
+ result[targetKey] = merge$1(result[targetKey], val);
362
+ } else if (isPlainObject$1(val)) {
363
+ result[targetKey] = merge$1({}, val);
364
+ } else if (isArray$1(val)) {
365
+ result[targetKey] = val.slice();
366
+ } else {
367
+ result[targetKey] = val;
368
+ }
369
+ };
370
+
371
+ for (let i = 0, l = arguments.length; i < l; i++) {
372
+ arguments[i] && forEach$1(arguments[i], assignValue);
373
+ }
374
+ return result;
375
+ }
376
+
377
+ /**
378
+ * Extends object a by mutably adding to it the properties of object b.
379
+ *
380
+ * @param {Object} a The object to be extended
381
+ * @param {Object} b The object to copy properties from
382
+ * @param {Object} thisArg The object to bind function to
383
+ *
384
+ * @param {Boolean} [allOwnKeys]
385
+ * @returns {Object} The resulting value of object a
386
+ */
387
+ const extend$1 = (a, b, thisArg, {allOwnKeys}= {}) => {
388
+ forEach$1(b, (val, key) => {
389
+ if (thisArg && isFunction$1(val)) {
390
+ a[key] = bind$1(val, thisArg);
391
+ } else {
392
+ a[key] = val;
393
+ }
394
+ }, {allOwnKeys});
395
+ return a;
396
+ };
397
+
398
+ /**
399
+ * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)
400
+ *
401
+ * @param {string} content with BOM
402
+ *
403
+ * @returns {string} content value without BOM
404
+ */
405
+ const stripBOM$1 = (content) => {
406
+ if (content.charCodeAt(0) === 0xFEFF) {
407
+ content = content.slice(1);
408
+ }
409
+ return content;
410
+ };
411
+
412
+ /**
413
+ * Inherit the prototype methods from one constructor into another
414
+ * @param {function} constructor
415
+ * @param {function} superConstructor
416
+ * @param {object} [props]
417
+ * @param {object} [descriptors]
418
+ *
419
+ * @returns {void}
420
+ */
421
+ const inherits$1 = (constructor, superConstructor, props, descriptors) => {
422
+ constructor.prototype = Object.create(superConstructor.prototype, descriptors);
423
+ constructor.prototype.constructor = constructor;
424
+ Object.defineProperty(constructor, 'super', {
425
+ value: superConstructor.prototype
426
+ });
427
+ props && Object.assign(constructor.prototype, props);
428
+ };
429
+
430
+ /**
431
+ * Resolve object with deep prototype chain to a flat object
432
+ * @param {Object} sourceObj source object
433
+ * @param {Object} [destObj]
434
+ * @param {Function|Boolean} [filter]
435
+ * @param {Function} [propFilter]
436
+ *
437
+ * @returns {Object}
438
+ */
439
+ const toFlatObject$1 = (sourceObj, destObj, filter, propFilter) => {
440
+ let props;
441
+ let i;
442
+ let prop;
443
+ const merged = {};
444
+
445
+ destObj = destObj || {};
446
+ // eslint-disable-next-line no-eq-null,eqeqeq
447
+ if (sourceObj == null) return destObj;
448
+
449
+ do {
450
+ props = Object.getOwnPropertyNames(sourceObj);
451
+ i = props.length;
452
+ while (i-- > 0) {
453
+ prop = props[i];
454
+ if ((!propFilter || propFilter(prop, sourceObj, destObj)) && !merged[prop]) {
455
+ destObj[prop] = sourceObj[prop];
456
+ merged[prop] = true;
457
+ }
458
+ }
459
+ sourceObj = filter !== false && getPrototypeOf$1(sourceObj);
460
+ } while (sourceObj && (!filter || filter(sourceObj, destObj)) && sourceObj !== Object.prototype);
461
+
462
+ return destObj;
463
+ };
464
+
465
+ /**
466
+ * Determines whether a string ends with the characters of a specified string
467
+ *
468
+ * @param {String} str
469
+ * @param {String} searchString
470
+ * @param {Number} [position= 0]
471
+ *
472
+ * @returns {boolean}
473
+ */
474
+ const endsWith$1 = (str, searchString, position) => {
475
+ str = String(str);
476
+ if (position === undefined || position > str.length) {
477
+ position = str.length;
478
+ }
479
+ position -= searchString.length;
480
+ const lastIndex = str.indexOf(searchString, position);
481
+ return lastIndex !== -1 && lastIndex === position;
482
+ };
483
+
484
+
485
+ /**
486
+ * Returns new array from array like object or null if failed
487
+ *
488
+ * @param {*} [thing]
489
+ *
490
+ * @returns {?Array}
491
+ */
492
+ const toArray$1 = (thing) => {
493
+ if (!thing) return null;
494
+ if (isArray$1(thing)) return thing;
495
+ let i = thing.length;
496
+ if (!isNumber$1(i)) return null;
497
+ const arr = new Array(i);
498
+ while (i-- > 0) {
499
+ arr[i] = thing[i];
500
+ }
501
+ return arr;
502
+ };
503
+
504
+ /**
505
+ * Checking if the Uint8Array exists and if it does, it returns a function that checks if the
506
+ * thing passed in is an instance of Uint8Array
507
+ *
508
+ * @param {TypedArray}
509
+ *
510
+ * @returns {Array}
511
+ */
512
+ // eslint-disable-next-line func-names
513
+ const isTypedArray$1 = (TypedArray => {
514
+ // eslint-disable-next-line func-names
515
+ return thing => {
516
+ return TypedArray && thing instanceof TypedArray;
517
+ };
518
+ })(typeof Uint8Array !== 'undefined' && getPrototypeOf$1(Uint8Array));
519
+
520
+ /**
521
+ * For each entry in the object, call the function with the key and value.
522
+ *
523
+ * @param {Object<any, any>} obj - The object to iterate over.
524
+ * @param {Function} fn - The function to call for each entry.
525
+ *
526
+ * @returns {void}
527
+ */
528
+ const forEachEntry$1 = (obj, fn) => {
529
+ const generator = obj && obj[Symbol.iterator];
530
+
531
+ const iterator = generator.call(obj);
532
+
533
+ let result;
534
+
535
+ while ((result = iterator.next()) && !result.done) {
536
+ const pair = result.value;
537
+ fn.call(obj, pair[0], pair[1]);
538
+ }
539
+ };
540
+
541
+ /**
542
+ * It takes a regular expression and a string, and returns an array of all the matches
543
+ *
544
+ * @param {string} regExp - The regular expression to match against.
545
+ * @param {string} str - The string to search.
546
+ *
547
+ * @returns {Array<boolean>}
548
+ */
549
+ const matchAll$1 = (regExp, str) => {
550
+ let matches;
551
+ const arr = [];
552
+
553
+ while ((matches = regExp.exec(str)) !== null) {
554
+ arr.push(matches);
555
+ }
556
+
557
+ return arr;
558
+ };
559
+
560
+ /* Checking if the kindOfTest function returns true when passed an HTMLFormElement. */
561
+ const isHTMLForm$1 = kindOfTest$1('HTMLFormElement');
562
+
563
+ const toCamelCase$1 = str => {
564
+ return str.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,
565
+ function replacer(m, p1, p2) {
566
+ return p1.toUpperCase() + p2;
567
+ }
568
+ );
569
+ };
570
+
571
+ /* Creating a function that will check if an object has a property. */
572
+ const hasOwnProperty$1 = (({hasOwnProperty}) => (obj, prop) => hasOwnProperty.call(obj, prop))(Object.prototype);
573
+
574
+ /**
575
+ * Determine if a value is a RegExp object
576
+ *
577
+ * @param {*} val The value to test
578
+ *
579
+ * @returns {boolean} True if value is a RegExp object, otherwise false
580
+ */
581
+ const isRegExp$1 = kindOfTest$1('RegExp');
582
+
583
+ const reduceDescriptors$1 = (obj, reducer) => {
584
+ const descriptors = Object.getOwnPropertyDescriptors(obj);
585
+ const reducedDescriptors = {};
586
+
587
+ forEach$1(descriptors, (descriptor, name) => {
588
+ if (reducer(descriptor, name, obj) !== false) {
589
+ reducedDescriptors[name] = descriptor;
590
+ }
591
+ });
592
+
593
+ Object.defineProperties(obj, reducedDescriptors);
594
+ };
595
+
596
+ /**
597
+ * Makes all methods read-only
598
+ * @param {Object} obj
599
+ */
600
+
601
+ const freezeMethods$1 = (obj) => {
602
+ reduceDescriptors$1(obj, (descriptor, name) => {
603
+ // skip restricted props in strict mode
604
+ if (isFunction$1(obj) && ['arguments', 'caller', 'callee'].indexOf(name) !== -1) {
605
+ return false;
606
+ }
607
+
608
+ const value = obj[name];
609
+
610
+ if (!isFunction$1(value)) return;
611
+
612
+ descriptor.enumerable = false;
613
+
614
+ if ('writable' in descriptor) {
615
+ descriptor.writable = false;
616
+ return;
617
+ }
618
+
619
+ if (!descriptor.set) {
620
+ descriptor.set = () => {
621
+ throw Error('Can not rewrite read-only method \'' + name + '\'');
622
+ };
623
+ }
624
+ });
625
+ };
626
+
627
+ const toObjectSet$1 = (arrayOrString, delimiter) => {
628
+ const obj = {};
629
+
630
+ const define = (arr) => {
631
+ arr.forEach(value => {
632
+ obj[value] = true;
633
+ });
634
+ };
635
+
636
+ isArray$1(arrayOrString) ? define(arrayOrString) : define(String(arrayOrString).split(delimiter));
637
+
638
+ return obj;
639
+ };
640
+
641
+ const noop$1 = () => {};
642
+
643
+ const toFiniteNumber$1 = (value, defaultValue) => {
644
+ value = +value;
645
+ return Number.isFinite(value) ? value : defaultValue;
646
+ };
647
+
648
+ const ALPHA$1 = 'abcdefghijklmnopqrstuvwxyz';
649
+
650
+ const DIGIT$1 = '0123456789';
651
+
652
+ const ALPHABET$1 = {
653
+ DIGIT: DIGIT$1,
654
+ ALPHA: ALPHA$1,
655
+ ALPHA_DIGIT: ALPHA$1 + ALPHA$1.toUpperCase() + DIGIT$1
656
+ };
657
+
658
+ const generateString$1 = (size = 16, alphabet = ALPHABET$1.ALPHA_DIGIT) => {
659
+ let str = '';
660
+ const {length} = alphabet;
661
+ while (size--) {
662
+ str += alphabet[Math.random() * length|0];
663
+ }
664
+
665
+ return str;
666
+ };
667
+
668
+ /**
669
+ * If the thing is a FormData object, return true, otherwise return false.
670
+ *
671
+ * @param {unknown} thing - The thing to check.
672
+ *
673
+ * @returns {boolean}
674
+ */
675
+ function isSpecCompliantForm$1(thing) {
676
+ return !!(thing && isFunction$1(thing.append) && thing[Symbol.toStringTag] === 'FormData' && thing[Symbol.iterator]);
677
+ }
678
+
679
+ const toJSONObject$1 = (obj) => {
680
+ const stack = new Array(10);
681
+
682
+ const visit = (source, i) => {
683
+
684
+ if (isObject$1(source)) {
685
+ if (stack.indexOf(source) >= 0) {
686
+ return;
687
+ }
688
+
689
+ if(!('toJSON' in source)) {
690
+ stack[i] = source;
691
+ const target = isArray$1(source) ? [] : {};
692
+
693
+ forEach$1(source, (value, key) => {
694
+ const reducedValue = visit(value, i + 1);
695
+ !isUndefined$1(reducedValue) && (target[key] = reducedValue);
696
+ });
697
+
698
+ stack[i] = undefined;
699
+
700
+ return target;
701
+ }
702
+ }
703
+
704
+ return source;
705
+ };
706
+
707
+ return visit(obj, 0);
708
+ };
709
+
710
+ const isAsyncFn$1 = kindOfTest$1('AsyncFunction');
711
+
712
+ const isThenable$1 = (thing) =>
713
+ thing && (isObject$1(thing) || isFunction$1(thing)) && isFunction$1(thing.then) && isFunction$1(thing.catch);
714
+
715
+ var utils$1 = {
716
+ isArray: isArray$1,
717
+ isArrayBuffer: isArrayBuffer$1,
718
+ isBuffer: isBuffer$1,
719
+ isFormData: isFormData$2,
720
+ isArrayBufferView: isArrayBufferView$1,
721
+ isString: isString$2,
722
+ isNumber: isNumber$1,
723
+ isBoolean: isBoolean$1,
724
+ isObject: isObject$1,
725
+ isPlainObject: isPlainObject$1,
726
+ isUndefined: isUndefined$1,
727
+ isDate: isDate$1,
728
+ isFile: isFile$1,
729
+ isBlob: isBlob$2,
730
+ isRegExp: isRegExp$1,
731
+ isFunction: isFunction$1,
732
+ isStream: isStream$1,
733
+ isURLSearchParams: isURLSearchParams$1,
734
+ isTypedArray: isTypedArray$1,
735
+ isFileList: isFileList$1,
736
+ forEach: forEach$1,
737
+ merge: merge$1,
738
+ extend: extend$1,
739
+ trim: trim$1,
740
+ stripBOM: stripBOM$1,
741
+ inherits: inherits$1,
742
+ toFlatObject: toFlatObject$1,
743
+ kindOf: kindOf$1,
744
+ kindOfTest: kindOfTest$1,
745
+ endsWith: endsWith$1,
746
+ toArray: toArray$1,
747
+ forEachEntry: forEachEntry$1,
748
+ matchAll: matchAll$1,
749
+ isHTMLForm: isHTMLForm$1,
750
+ hasOwnProperty: hasOwnProperty$1,
751
+ hasOwnProp: hasOwnProperty$1, // an alias to avoid ESLint no-prototype-builtins detection
752
+ reduceDescriptors: reduceDescriptors$1,
753
+ freezeMethods: freezeMethods$1,
754
+ toObjectSet: toObjectSet$1,
755
+ toCamelCase: toCamelCase$1,
756
+ noop: noop$1,
757
+ toFiniteNumber: toFiniteNumber$1,
758
+ findKey: findKey$1,
759
+ global: _global$1,
760
+ isContextDefined: isContextDefined$1,
761
+ ALPHABET: ALPHABET$1,
762
+ generateString: generateString$1,
763
+ isSpecCompliantForm: isSpecCompliantForm$1,
764
+ toJSONObject: toJSONObject$1,
765
+ isAsyncFn: isAsyncFn$1,
766
+ isThenable: isThenable$1
767
+ };
768
+
769
+ /**
770
+ * Create an Error with the specified message, config, error code, request and response.
771
+ *
772
+ * @param {string} message The error message.
773
+ * @param {string} [code] The error code (for example, 'ECONNABORTED').
774
+ * @param {Object} [config] The config.
775
+ * @param {Object} [request] The request.
776
+ * @param {Object} [response] The response.
777
+ *
778
+ * @returns {Error} The created error.
779
+ */
780
+ function AxiosError$1(message, code, config, request, response) {
781
+ Error.call(this);
782
+
783
+ if (Error.captureStackTrace) {
784
+ Error.captureStackTrace(this, this.constructor);
785
+ } else {
786
+ this.stack = (new Error()).stack;
787
+ }
788
+
789
+ this.message = message;
790
+ this.name = 'AxiosError';
791
+ code && (this.code = code);
792
+ config && (this.config = config);
793
+ request && (this.request = request);
794
+ response && (this.response = response);
795
+ }
796
+
797
+ utils$1.inherits(AxiosError$1, Error, {
798
+ toJSON: function toJSON() {
799
+ return {
800
+ // Standard
801
+ message: this.message,
802
+ name: this.name,
803
+ // Microsoft
804
+ description: this.description,
805
+ number: this.number,
806
+ // Mozilla
807
+ fileName: this.fileName,
808
+ lineNumber: this.lineNumber,
809
+ columnNumber: this.columnNumber,
810
+ stack: this.stack,
811
+ // Axios
812
+ config: utils$1.toJSONObject(this.config),
813
+ code: this.code,
814
+ status: this.response && this.response.status ? this.response.status : null
815
+ };
816
+ }
817
+ });
818
+
819
+ const prototype$1$1 = AxiosError$1.prototype;
820
+ const descriptors$1 = {};
821
+
822
+ [
823
+ 'ERR_BAD_OPTION_VALUE',
824
+ 'ERR_BAD_OPTION',
825
+ 'ECONNABORTED',
826
+ 'ETIMEDOUT',
827
+ 'ERR_NETWORK',
828
+ 'ERR_FR_TOO_MANY_REDIRECTS',
829
+ 'ERR_DEPRECATED',
830
+ 'ERR_BAD_RESPONSE',
831
+ 'ERR_BAD_REQUEST',
832
+ 'ERR_CANCELED',
833
+ 'ERR_NOT_SUPPORT',
834
+ 'ERR_INVALID_URL'
835
+ // eslint-disable-next-line func-names
836
+ ].forEach(code => {
837
+ descriptors$1[code] = {value: code};
838
+ });
839
+
840
+ Object.defineProperties(AxiosError$1, descriptors$1);
841
+ Object.defineProperty(prototype$1$1, 'isAxiosError', {value: true});
842
+
843
+ // eslint-disable-next-line func-names
844
+ AxiosError$1.from = (error, code, config, request, response, customProps) => {
845
+ const axiosError = Object.create(prototype$1$1);
846
+
847
+ utils$1.toFlatObject(error, axiosError, function filter(obj) {
848
+ return obj !== Error.prototype;
849
+ }, prop => {
850
+ return prop !== 'isAxiosError';
851
+ });
852
+
853
+ AxiosError$1.call(axiosError, error.message, code, config, request, response);
854
+
855
+ axiosError.cause = error;
856
+
857
+ axiosError.name = error.name;
858
+
859
+ customProps && Object.assign(axiosError, customProps);
860
+
861
+ return axiosError;
862
+ };
863
+
864
+ // eslint-disable-next-line strict
865
+ var httpAdapter$1 = null;
866
+
867
+ /**
868
+ * Determines if the given thing is a array or js object.
869
+ *
870
+ * @param {string} thing - The object or array to be visited.
871
+ *
872
+ * @returns {boolean}
873
+ */
874
+ function isVisitable$1(thing) {
875
+ return utils$1.isPlainObject(thing) || utils$1.isArray(thing);
876
+ }
877
+
878
+ /**
879
+ * It removes the brackets from the end of a string
880
+ *
881
+ * @param {string} key - The key of the parameter.
882
+ *
883
+ * @returns {string} the key without the brackets.
884
+ */
885
+ function removeBrackets$1(key) {
886
+ return utils$1.endsWith(key, '[]') ? key.slice(0, -2) : key;
887
+ }
888
+
889
+ /**
890
+ * It takes a path, a key, and a boolean, and returns a string
891
+ *
892
+ * @param {string} path - The path to the current key.
893
+ * @param {string} key - The key of the current object being iterated over.
894
+ * @param {string} dots - If true, the key will be rendered with dots instead of brackets.
895
+ *
896
+ * @returns {string} The path to the current key.
897
+ */
898
+ function renderKey$1(path, key, dots) {
899
+ if (!path) return key;
900
+ return path.concat(key).map(function each(token, i) {
901
+ // eslint-disable-next-line no-param-reassign
902
+ token = removeBrackets$1(token);
903
+ return !dots && i ? '[' + token + ']' : token;
904
+ }).join(dots ? '.' : '');
905
+ }
906
+
907
+ /**
908
+ * If the array is an array and none of its elements are visitable, then it's a flat array.
909
+ *
910
+ * @param {Array<any>} arr - The array to check
911
+ *
912
+ * @returns {boolean}
913
+ */
914
+ function isFlatArray$1(arr) {
915
+ return utils$1.isArray(arr) && !arr.some(isVisitable$1);
916
+ }
917
+
918
+ const predicates$1 = utils$1.toFlatObject(utils$1, {}, null, function filter(prop) {
919
+ return /^is[A-Z]/.test(prop);
920
+ });
921
+
922
+ /**
923
+ * Convert a data object to FormData
924
+ *
925
+ * @param {Object} obj
926
+ * @param {?Object} [formData]
927
+ * @param {?Object} [options]
928
+ * @param {Function} [options.visitor]
929
+ * @param {Boolean} [options.metaTokens = true]
930
+ * @param {Boolean} [options.dots = false]
931
+ * @param {?Boolean} [options.indexes = false]
932
+ *
933
+ * @returns {Object}
934
+ **/
935
+
936
+ /**
937
+ * It converts an object into a FormData object
938
+ *
939
+ * @param {Object<any, any>} obj - The object to convert to form data.
940
+ * @param {string} formData - The FormData object to append to.
941
+ * @param {Object<string, any>} options
942
+ *
943
+ * @returns
944
+ */
945
+ function toFormData$1(obj, formData, options) {
946
+ if (!utils$1.isObject(obj)) {
947
+ throw new TypeError('target must be an object');
948
+ }
949
+
950
+ // eslint-disable-next-line no-param-reassign
951
+ formData = formData || new (FormData)();
952
+
953
+ // eslint-disable-next-line no-param-reassign
954
+ options = utils$1.toFlatObject(options, {
955
+ metaTokens: true,
956
+ dots: false,
957
+ indexes: false
958
+ }, false, function defined(option, source) {
959
+ // eslint-disable-next-line no-eq-null,eqeqeq
960
+ return !utils$1.isUndefined(source[option]);
961
+ });
962
+
963
+ const metaTokens = options.metaTokens;
964
+ // eslint-disable-next-line no-use-before-define
965
+ const visitor = options.visitor || defaultVisitor;
966
+ const dots = options.dots;
967
+ const indexes = options.indexes;
968
+ const _Blob = options.Blob || typeof Blob !== 'undefined' && Blob;
969
+ const useBlob = _Blob && utils$1.isSpecCompliantForm(formData);
970
+
971
+ if (!utils$1.isFunction(visitor)) {
972
+ throw new TypeError('visitor must be a function');
973
+ }
974
+
975
+ function convertValue(value) {
976
+ if (value === null) return '';
977
+
978
+ if (utils$1.isDate(value)) {
979
+ return value.toISOString();
980
+ }
981
+
982
+ if (!useBlob && utils$1.isBlob(value)) {
983
+ throw new AxiosError$1('Blob is not supported. Use a Buffer instead.');
984
+ }
985
+
986
+ if (utils$1.isArrayBuffer(value) || utils$1.isTypedArray(value)) {
987
+ return useBlob && typeof Blob === 'function' ? new Blob([value]) : Buffer.from(value);
988
+ }
989
+
990
+ return value;
991
+ }
992
+
993
+ /**
994
+ * Default visitor.
995
+ *
996
+ * @param {*} value
997
+ * @param {String|Number} key
998
+ * @param {Array<String|Number>} path
999
+ * @this {FormData}
1000
+ *
1001
+ * @returns {boolean} return true to visit the each prop of the value recursively
1002
+ */
1003
+ function defaultVisitor(value, key, path) {
1004
+ let arr = value;
1005
+
1006
+ if (value && !path && typeof value === 'object') {
1007
+ if (utils$1.endsWith(key, '{}')) {
1008
+ // eslint-disable-next-line no-param-reassign
1009
+ key = metaTokens ? key : key.slice(0, -2);
1010
+ // eslint-disable-next-line no-param-reassign
1011
+ value = JSON.stringify(value);
1012
+ } else if (
1013
+ (utils$1.isArray(value) && isFlatArray$1(value)) ||
1014
+ ((utils$1.isFileList(value) || utils$1.endsWith(key, '[]')) && (arr = utils$1.toArray(value))
1015
+ )) {
1016
+ // eslint-disable-next-line no-param-reassign
1017
+ key = removeBrackets$1(key);
1018
+
1019
+ arr.forEach(function each(el, index) {
1020
+ !(utils$1.isUndefined(el) || el === null) && formData.append(
1021
+ // eslint-disable-next-line no-nested-ternary
1022
+ indexes === true ? renderKey$1([key], index, dots) : (indexes === null ? key : key + '[]'),
1023
+ convertValue(el)
1024
+ );
1025
+ });
1026
+ return false;
1027
+ }
1028
+ }
1029
+
1030
+ if (isVisitable$1(value)) {
1031
+ return true;
1032
+ }
1033
+
1034
+ formData.append(renderKey$1(path, key, dots), convertValue(value));
1035
+
1036
+ return false;
1037
+ }
1038
+
1039
+ const stack = [];
1040
+
1041
+ const exposedHelpers = Object.assign(predicates$1, {
1042
+ defaultVisitor,
1043
+ convertValue,
1044
+ isVisitable: isVisitable$1
1045
+ });
1046
+
1047
+ function build(value, path) {
1048
+ if (utils$1.isUndefined(value)) return;
1049
+
1050
+ if (stack.indexOf(value) !== -1) {
1051
+ throw Error('Circular reference detected in ' + path.join('.'));
1052
+ }
1053
+
1054
+ stack.push(value);
1055
+
1056
+ utils$1.forEach(value, function each(el, key) {
1057
+ const result = !(utils$1.isUndefined(el) || el === null) && visitor.call(
1058
+ formData, el, utils$1.isString(key) ? key.trim() : key, path, exposedHelpers
1059
+ );
1060
+
1061
+ if (result === true) {
1062
+ build(el, path ? path.concat(key) : [key]);
1063
+ }
1064
+ });
1065
+
1066
+ stack.pop();
1067
+ }
1068
+
1069
+ if (!utils$1.isObject(obj)) {
1070
+ throw new TypeError('data must be an object');
1071
+ }
1072
+
1073
+ build(obj);
1074
+
1075
+ return formData;
1076
+ }
1077
+
1078
+ /**
1079
+ * It encodes a string by replacing all characters that are not in the unreserved set with
1080
+ * their percent-encoded equivalents
1081
+ *
1082
+ * @param {string} str - The string to encode.
1083
+ *
1084
+ * @returns {string} The encoded string.
1085
+ */
1086
+ function encode$1$1(str) {
1087
+ const charMap = {
1088
+ '!': '%21',
1089
+ "'": '%27',
1090
+ '(': '%28',
1091
+ ')': '%29',
1092
+ '~': '%7E',
1093
+ '%20': '+',
1094
+ '%00': '\x00'
1095
+ };
1096
+ return encodeURIComponent(str).replace(/[!'()~]|%20|%00/g, function replacer(match) {
1097
+ return charMap[match];
1098
+ });
1099
+ }
1100
+
1101
+ /**
1102
+ * It takes a params object and converts it to a FormData object
1103
+ *
1104
+ * @param {Object<string, any>} params - The parameters to be converted to a FormData object.
1105
+ * @param {Object<string, any>} options - The options object passed to the Axios constructor.
1106
+ *
1107
+ * @returns {void}
1108
+ */
1109
+ function AxiosURLSearchParams$1(params, options) {
1110
+ this._pairs = [];
1111
+
1112
+ params && toFormData$1(params, this, options);
1113
+ }
1114
+
1115
+ const prototype$2 = AxiosURLSearchParams$1.prototype;
1116
+
1117
+ prototype$2.append = function append(name, value) {
1118
+ this._pairs.push([name, value]);
1119
+ };
1120
+
1121
+ prototype$2.toString = function toString(encoder) {
1122
+ const _encode = encoder ? function(value) {
1123
+ return encoder.call(this, value, encode$1$1);
1124
+ } : encode$1$1;
1125
+
1126
+ return this._pairs.map(function each(pair) {
1127
+ return _encode(pair[0]) + '=' + _encode(pair[1]);
1128
+ }, '').join('&');
1129
+ };
1130
+
1131
+ /**
1132
+ * It replaces all instances of the characters `:`, `$`, `,`, `+`, `[`, and `]` with their
1133
+ * URI encoded counterparts
1134
+ *
1135
+ * @param {string} val The value to be encoded.
1136
+ *
1137
+ * @returns {string} The encoded value.
1138
+ */
1139
+ function encode$3(val) {
1140
+ return encodeURIComponent(val).
1141
+ replace(/%3A/gi, ':').
1142
+ replace(/%24/g, '$').
1143
+ replace(/%2C/gi, ',').
1144
+ replace(/%20/g, '+').
1145
+ replace(/%5B/gi, '[').
1146
+ replace(/%5D/gi, ']');
1147
+ }
1148
+
1149
+ /**
1150
+ * Build a URL by appending params to the end
1151
+ *
1152
+ * @param {string} url The base of the url (e.g., http://www.google.com)
1153
+ * @param {object} [params] The params to be appended
1154
+ * @param {?object} options
1155
+ *
1156
+ * @returns {string} The formatted url
1157
+ */
1158
+ function buildURL$1(url, params, options) {
1159
+ /*eslint no-param-reassign:0*/
1160
+ if (!params) {
1161
+ return url;
1162
+ }
1163
+
1164
+ const _encode = options && options.encode || encode$3;
1165
+
1166
+ const serializeFn = options && options.serialize;
1167
+
1168
+ let serializedParams;
1169
+
1170
+ if (serializeFn) {
1171
+ serializedParams = serializeFn(params, options);
1172
+ } else {
1173
+ serializedParams = utils$1.isURLSearchParams(params) ?
1174
+ params.toString() :
1175
+ new AxiosURLSearchParams$1(params, options).toString(_encode);
1176
+ }
1177
+
1178
+ if (serializedParams) {
1179
+ const hashmarkIndex = url.indexOf("#");
1180
+
1181
+ if (hashmarkIndex !== -1) {
1182
+ url = url.slice(0, hashmarkIndex);
1183
+ }
1184
+ url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams;
1185
+ }
1186
+
1187
+ return url;
1188
+ }
1189
+
1190
+ let InterceptorManager$2 = class InterceptorManager {
1191
+ constructor() {
1192
+ this.handlers = [];
1193
+ }
1194
+
1195
+ /**
1196
+ * Add a new interceptor to the stack
1197
+ *
1198
+ * @param {Function} fulfilled The function to handle `then` for a `Promise`
1199
+ * @param {Function} rejected The function to handle `reject` for a `Promise`
1200
+ *
1201
+ * @return {Number} An ID used to remove interceptor later
1202
+ */
1203
+ use(fulfilled, rejected, options) {
1204
+ this.handlers.push({
1205
+ fulfilled,
1206
+ rejected,
1207
+ synchronous: options ? options.synchronous : false,
1208
+ runWhen: options ? options.runWhen : null
1209
+ });
1210
+ return this.handlers.length - 1;
1211
+ }
1212
+
1213
+ /**
1214
+ * Remove an interceptor from the stack
1215
+ *
1216
+ * @param {Number} id The ID that was returned by `use`
1217
+ *
1218
+ * @returns {Boolean} `true` if the interceptor was removed, `false` otherwise
1219
+ */
1220
+ eject(id) {
1221
+ if (this.handlers[id]) {
1222
+ this.handlers[id] = null;
1223
+ }
1224
+ }
1225
+
1226
+ /**
1227
+ * Clear all interceptors from the stack
1228
+ *
1229
+ * @returns {void}
1230
+ */
1231
+ clear() {
1232
+ if (this.handlers) {
1233
+ this.handlers = [];
1234
+ }
1235
+ }
1236
+
1237
+ /**
1238
+ * Iterate over all the registered interceptors
1239
+ *
1240
+ * This method is particularly useful for skipping over any
1241
+ * interceptors that may have become `null` calling `eject`.
1242
+ *
1243
+ * @param {Function} fn The function to call for each interceptor
1244
+ *
1245
+ * @returns {void}
1246
+ */
1247
+ forEach(fn) {
1248
+ utils$1.forEach(this.handlers, function forEachHandler(h) {
1249
+ if (h !== null) {
1250
+ fn(h);
1251
+ }
1252
+ });
1253
+ }
1254
+ };
1255
+
1256
+ var InterceptorManager$1$1 = InterceptorManager$2;
1257
+
1258
+ var transitionalDefaults$1 = {
1259
+ silentJSONParsing: true,
1260
+ forcedJSONParsing: true,
1261
+ clarifyTimeoutError: false
1262
+ };
1263
+
1264
+ var URLSearchParams$1$1 = typeof URLSearchParams !== 'undefined' ? URLSearchParams : AxiosURLSearchParams$1;
1265
+
1266
+ var FormData$1$1 = typeof FormData !== 'undefined' ? FormData : null;
1267
+
1268
+ var Blob$1$1 = typeof Blob !== 'undefined' ? Blob : null;
1269
+
1270
+ /**
1271
+ * Determine if we're running in a standard browser environment
1272
+ *
1273
+ * This allows axios to run in a web worker, and react-native.
1274
+ * Both environments support XMLHttpRequest, but not fully standard globals.
1275
+ *
1276
+ * web workers:
1277
+ * typeof window -> undefined
1278
+ * typeof document -> undefined
1279
+ *
1280
+ * react-native:
1281
+ * navigator.product -> 'ReactNative'
1282
+ * nativescript
1283
+ * navigator.product -> 'NativeScript' or 'NS'
1284
+ *
1285
+ * @returns {boolean}
1286
+ */
1287
+ const isStandardBrowserEnv$1 = (() => {
1288
+ let product;
1289
+ if (typeof navigator !== 'undefined' && (
1290
+ (product = navigator.product) === 'ReactNative' ||
1291
+ product === 'NativeScript' ||
1292
+ product === 'NS')
1293
+ ) {
1294
+ return false;
1295
+ }
1296
+
1297
+ return typeof window !== 'undefined' && typeof document !== 'undefined';
1298
+ })();
1299
+
1300
+ /**
1301
+ * Determine if we're running in a standard browser webWorker environment
1302
+ *
1303
+ * Although the `isStandardBrowserEnv` method indicates that
1304
+ * `allows axios to run in a web worker`, the WebWorker will still be
1305
+ * filtered out due to its judgment standard
1306
+ * `typeof window !== 'undefined' && typeof document !== 'undefined'`.
1307
+ * This leads to a problem when axios post `FormData` in webWorker
1308
+ */
1309
+ const isStandardBrowserWebWorkerEnv$1 = (() => {
1310
+ return (
1311
+ typeof WorkerGlobalScope !== 'undefined' &&
1312
+ // eslint-disable-next-line no-undef
1313
+ self instanceof WorkerGlobalScope &&
1314
+ typeof self.importScripts === 'function'
1315
+ );
1316
+ })();
1317
+
1318
+
1319
+ var platform$1 = {
1320
+ isBrowser: true,
1321
+ classes: {
1322
+ URLSearchParams: URLSearchParams$1$1,
1323
+ FormData: FormData$1$1,
1324
+ Blob: Blob$1$1
1325
+ },
1326
+ isStandardBrowserEnv: isStandardBrowserEnv$1,
1327
+ isStandardBrowserWebWorkerEnv: isStandardBrowserWebWorkerEnv$1,
1328
+ protocols: ['http', 'https', 'file', 'blob', 'url', 'data']
1329
+ };
1330
+
1331
+ function toURLEncodedForm$1(data, options) {
1332
+ return toFormData$1(data, new platform$1.classes.URLSearchParams(), Object.assign({
1333
+ visitor: function(value, key, path, helpers) {
1334
+ if (platform$1.isNode && utils$1.isBuffer(value)) {
1335
+ this.append(key, value.toString('base64'));
1336
+ return false;
1337
+ }
1338
+
1339
+ return helpers.defaultVisitor.apply(this, arguments);
1340
+ }
1341
+ }, options));
1342
+ }
1343
+
1344
+ /**
1345
+ * It takes a string like `foo[x][y][z]` and returns an array like `['foo', 'x', 'y', 'z']
1346
+ *
1347
+ * @param {string} name - The name of the property to get.
1348
+ *
1349
+ * @returns An array of strings.
1350
+ */
1351
+ function parsePropPath$1(name) {
1352
+ // foo[x][y][z]
1353
+ // foo.x.y.z
1354
+ // foo-x-y-z
1355
+ // foo x y z
1356
+ return utils$1.matchAll(/\w+|\[(\w*)]/g, name).map(match => {
1357
+ return match[0] === '[]' ? '' : match[1] || match[0];
1358
+ });
1359
+ }
1360
+
1361
+ /**
1362
+ * Convert an array to an object.
1363
+ *
1364
+ * @param {Array<any>} arr - The array to convert to an object.
1365
+ *
1366
+ * @returns An object with the same keys and values as the array.
1367
+ */
1368
+ function arrayToObject$1(arr) {
1369
+ const obj = {};
1370
+ const keys = Object.keys(arr);
1371
+ let i;
1372
+ const len = keys.length;
1373
+ let key;
1374
+ for (i = 0; i < len; i++) {
1375
+ key = keys[i];
1376
+ obj[key] = arr[key];
1377
+ }
1378
+ return obj;
1379
+ }
1380
+
1381
+ /**
1382
+ * It takes a FormData object and returns a JavaScript object
1383
+ *
1384
+ * @param {string} formData The FormData object to convert to JSON.
1385
+ *
1386
+ * @returns {Object<string, any> | null} The converted object.
1387
+ */
1388
+ function formDataToJSON$1(formData) {
1389
+ function buildPath(path, value, target, index) {
1390
+ let name = path[index++];
1391
+ const isNumericKey = Number.isFinite(+name);
1392
+ const isLast = index >= path.length;
1393
+ name = !name && utils$1.isArray(target) ? target.length : name;
1394
+
1395
+ if (isLast) {
1396
+ if (utils$1.hasOwnProp(target, name)) {
1397
+ target[name] = [target[name], value];
1398
+ } else {
1399
+ target[name] = value;
1400
+ }
1401
+
1402
+ return !isNumericKey;
1403
+ }
1404
+
1405
+ if (!target[name] || !utils$1.isObject(target[name])) {
1406
+ target[name] = [];
1407
+ }
1408
+
1409
+ const result = buildPath(path, value, target[name], index);
1410
+
1411
+ if (result && utils$1.isArray(target[name])) {
1412
+ target[name] = arrayToObject$1(target[name]);
1413
+ }
1414
+
1415
+ return !isNumericKey;
1416
+ }
1417
+
1418
+ if (utils$1.isFormData(formData) && utils$1.isFunction(formData.entries)) {
1419
+ const obj = {};
1420
+
1421
+ utils$1.forEachEntry(formData, (name, value) => {
1422
+ buildPath(parsePropPath$1(name), value, obj, 0);
1423
+ });
1424
+
1425
+ return obj;
1426
+ }
1427
+
1428
+ return null;
1429
+ }
1430
+
1431
+ const DEFAULT_CONTENT_TYPE$1 = {
1432
+ 'Content-Type': undefined
1433
+ };
1434
+
1435
+ /**
1436
+ * It takes a string, tries to parse it, and if it fails, it returns the stringified version
1437
+ * of the input
1438
+ *
1439
+ * @param {any} rawValue - The value to be stringified.
1440
+ * @param {Function} parser - A function that parses a string into a JavaScript object.
1441
+ * @param {Function} encoder - A function that takes a value and returns a string.
1442
+ *
1443
+ * @returns {string} A stringified version of the rawValue.
1444
+ */
1445
+ function stringifySafely$1(rawValue, parser, encoder) {
1446
+ if (utils$1.isString(rawValue)) {
1447
+ try {
1448
+ (parser || JSON.parse)(rawValue);
1449
+ return utils$1.trim(rawValue);
1450
+ } catch (e) {
1451
+ if (e.name !== 'SyntaxError') {
1452
+ throw e;
1453
+ }
1454
+ }
1455
+ }
1456
+
1457
+ return (encoder || JSON.stringify)(rawValue);
1458
+ }
1459
+
1460
+ const defaults$2 = {
1461
+
1462
+ transitional: transitionalDefaults$1,
1463
+
1464
+ adapter: ['xhr', 'http'],
1465
+
1466
+ transformRequest: [function transformRequest(data, headers) {
1467
+ const contentType = headers.getContentType() || '';
1468
+ const hasJSONContentType = contentType.indexOf('application/json') > -1;
1469
+ const isObjectPayload = utils$1.isObject(data);
1470
+
1471
+ if (isObjectPayload && utils$1.isHTMLForm(data)) {
1472
+ data = new FormData(data);
1473
+ }
1474
+
1475
+ const isFormData = utils$1.isFormData(data);
1476
+
1477
+ if (isFormData) {
1478
+ if (!hasJSONContentType) {
1479
+ return data;
1480
+ }
1481
+ return hasJSONContentType ? JSON.stringify(formDataToJSON$1(data)) : data;
1482
+ }
1483
+
1484
+ if (utils$1.isArrayBuffer(data) ||
1485
+ utils$1.isBuffer(data) ||
1486
+ utils$1.isStream(data) ||
1487
+ utils$1.isFile(data) ||
1488
+ utils$1.isBlob(data)
1489
+ ) {
1490
+ return data;
1491
+ }
1492
+ if (utils$1.isArrayBufferView(data)) {
1493
+ return data.buffer;
1494
+ }
1495
+ if (utils$1.isURLSearchParams(data)) {
1496
+ headers.setContentType('application/x-www-form-urlencoded;charset=utf-8', false);
1497
+ return data.toString();
1498
+ }
1499
+
1500
+ let isFileList;
1501
+
1502
+ if (isObjectPayload) {
1503
+ if (contentType.indexOf('application/x-www-form-urlencoded') > -1) {
1504
+ return toURLEncodedForm$1(data, this.formSerializer).toString();
1505
+ }
1506
+
1507
+ if ((isFileList = utils$1.isFileList(data)) || contentType.indexOf('multipart/form-data') > -1) {
1508
+ const _FormData = this.env && this.env.FormData;
1509
+
1510
+ return toFormData$1(
1511
+ isFileList ? {'files[]': data} : data,
1512
+ _FormData && new _FormData(),
1513
+ this.formSerializer
1514
+ );
1515
+ }
1516
+ }
1517
+
1518
+ if (isObjectPayload || hasJSONContentType ) {
1519
+ headers.setContentType('application/json', false);
1520
+ return stringifySafely$1(data);
1521
+ }
1522
+
1523
+ return data;
1524
+ }],
1525
+
1526
+ transformResponse: [function transformResponse(data) {
1527
+ const transitional = this.transitional || defaults$2.transitional;
1528
+ const forcedJSONParsing = transitional && transitional.forcedJSONParsing;
1529
+ const JSONRequested = this.responseType === 'json';
1530
+
1531
+ if (data && utils$1.isString(data) && ((forcedJSONParsing && !this.responseType) || JSONRequested)) {
1532
+ const silentJSONParsing = transitional && transitional.silentJSONParsing;
1533
+ const strictJSONParsing = !silentJSONParsing && JSONRequested;
1534
+
1535
+ try {
1536
+ return JSON.parse(data);
1537
+ } catch (e) {
1538
+ if (strictJSONParsing) {
1539
+ if (e.name === 'SyntaxError') {
1540
+ throw AxiosError$1.from(e, AxiosError$1.ERR_BAD_RESPONSE, this, null, this.response);
1541
+ }
1542
+ throw e;
1543
+ }
1544
+ }
1545
+ }
1546
+
1547
+ return data;
1548
+ }],
1549
+
1550
+ /**
1551
+ * A timeout in milliseconds to abort a request. If set to 0 (default) a
1552
+ * timeout is not created.
1553
+ */
1554
+ timeout: 0,
1555
+
1556
+ xsrfCookieName: 'XSRF-TOKEN',
1557
+ xsrfHeaderName: 'X-XSRF-TOKEN',
1558
+
1559
+ maxContentLength: -1,
1560
+ maxBodyLength: -1,
1561
+
1562
+ env: {
1563
+ FormData: platform$1.classes.FormData,
1564
+ Blob: platform$1.classes.Blob
1565
+ },
1566
+
1567
+ validateStatus: function validateStatus(status) {
1568
+ return status >= 200 && status < 300;
1569
+ },
1570
+
1571
+ headers: {
1572
+ common: {
1573
+ 'Accept': 'application/json, text/plain, */*'
1574
+ }
1575
+ }
1576
+ };
1577
+
1578
+ utils$1.forEach(['delete', 'get', 'head'], function forEachMethodNoData(method) {
1579
+ defaults$2.headers[method] = {};
1580
+ });
1581
+
1582
+ utils$1.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
1583
+ defaults$2.headers[method] = utils$1.merge(DEFAULT_CONTENT_TYPE$1);
1584
+ });
1585
+
1586
+ var defaults$1$1 = defaults$2;
1587
+
1588
+ // RawAxiosHeaders whose duplicates are ignored by node
1589
+ // c.f. https://nodejs.org/api/http.html#http_message_headers
1590
+ const ignoreDuplicateOf$1 = utils$1.toObjectSet([
1591
+ 'age', 'authorization', 'content-length', 'content-type', 'etag',
1592
+ 'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since',
1593
+ 'last-modified', 'location', 'max-forwards', 'proxy-authorization',
1594
+ 'referer', 'retry-after', 'user-agent'
1595
+ ]);
1596
+
1597
+ /**
1598
+ * Parse headers into an object
1599
+ *
1600
+ * ```
1601
+ * Date: Wed, 27 Aug 2014 08:58:49 GMT
1602
+ * Content-Type: application/json
1603
+ * Connection: keep-alive
1604
+ * Transfer-Encoding: chunked
1605
+ * ```
1606
+ *
1607
+ * @param {String} rawHeaders Headers needing to be parsed
1608
+ *
1609
+ * @returns {Object} Headers parsed into an object
1610
+ */
1611
+ var parseHeaders$1 = rawHeaders => {
1612
+ const parsed = {};
1613
+ let key;
1614
+ let val;
1615
+ let i;
1616
+
1617
+ rawHeaders && rawHeaders.split('\n').forEach(function parser(line) {
1618
+ i = line.indexOf(':');
1619
+ key = line.substring(0, i).trim().toLowerCase();
1620
+ val = line.substring(i + 1).trim();
1621
+
1622
+ if (!key || (parsed[key] && ignoreDuplicateOf$1[key])) {
1623
+ return;
1624
+ }
1625
+
1626
+ if (key === 'set-cookie') {
1627
+ if (parsed[key]) {
1628
+ parsed[key].push(val);
1629
+ } else {
1630
+ parsed[key] = [val];
1631
+ }
1632
+ } else {
1633
+ parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
1634
+ }
1635
+ });
1636
+
1637
+ return parsed;
1638
+ };
1639
+
1640
+ const $internals$1 = Symbol('internals');
1641
+
1642
+ function normalizeHeader$1(header) {
1643
+ return header && String(header).trim().toLowerCase();
1644
+ }
1645
+
1646
+ function normalizeValue$1(value) {
1647
+ if (value === false || value == null) {
1648
+ return value;
1649
+ }
1650
+
1651
+ return utils$1.isArray(value) ? value.map(normalizeValue$1) : String(value);
1652
+ }
1653
+
1654
+ function parseTokens$1(str) {
1655
+ const tokens = Object.create(null);
1656
+ const tokensRE = /([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;
1657
+ let match;
1658
+
1659
+ while ((match = tokensRE.exec(str))) {
1660
+ tokens[match[1]] = match[2];
1661
+ }
1662
+
1663
+ return tokens;
1664
+ }
1665
+
1666
+ const isValidHeaderName$1 = (str) => /^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(str.trim());
1667
+
1668
+ function matchHeaderValue$1(context, value, header, filter, isHeaderNameFilter) {
1669
+ if (utils$1.isFunction(filter)) {
1670
+ return filter.call(this, value, header);
1671
+ }
1672
+
1673
+ if (isHeaderNameFilter) {
1674
+ value = header;
1675
+ }
1676
+
1677
+ if (!utils$1.isString(value)) return;
1678
+
1679
+ if (utils$1.isString(filter)) {
1680
+ return value.indexOf(filter) !== -1;
1681
+ }
1682
+
1683
+ if (utils$1.isRegExp(filter)) {
1684
+ return filter.test(value);
1685
+ }
1686
+ }
1687
+
1688
+ function formatHeader$1(header) {
1689
+ return header.trim()
1690
+ .toLowerCase().replace(/([a-z\d])(\w*)/g, (w, char, str) => {
1691
+ return char.toUpperCase() + str;
1692
+ });
1693
+ }
1694
+
1695
+ function buildAccessors$1(obj, header) {
1696
+ const accessorName = utils$1.toCamelCase(' ' + header);
1697
+
1698
+ ['get', 'set', 'has'].forEach(methodName => {
1699
+ Object.defineProperty(obj, methodName + accessorName, {
1700
+ value: function(arg1, arg2, arg3) {
1701
+ return this[methodName].call(this, header, arg1, arg2, arg3);
1702
+ },
1703
+ configurable: true
1704
+ });
1705
+ });
1706
+ }
1707
+
1708
+ let AxiosHeaders$2 = class AxiosHeaders {
1709
+ constructor(headers) {
1710
+ headers && this.set(headers);
1711
+ }
1712
+
1713
+ set(header, valueOrRewrite, rewrite) {
1714
+ const self = this;
1715
+
1716
+ function setHeader(_value, _header, _rewrite) {
1717
+ const lHeader = normalizeHeader$1(_header);
1718
+
1719
+ if (!lHeader) {
1720
+ throw new Error('header name must be a non-empty string');
1721
+ }
1722
+
1723
+ const key = utils$1.findKey(self, lHeader);
1724
+
1725
+ if(!key || self[key] === undefined || _rewrite === true || (_rewrite === undefined && self[key] !== false)) {
1726
+ self[key || _header] = normalizeValue$1(_value);
1727
+ }
1728
+ }
1729
+
1730
+ const setHeaders = (headers, _rewrite) =>
1731
+ utils$1.forEach(headers, (_value, _header) => setHeader(_value, _header, _rewrite));
1732
+
1733
+ if (utils$1.isPlainObject(header) || header instanceof this.constructor) {
1734
+ setHeaders(header, valueOrRewrite);
1735
+ } else if(utils$1.isString(header) && (header = header.trim()) && !isValidHeaderName$1(header)) {
1736
+ setHeaders(parseHeaders$1(header), valueOrRewrite);
1737
+ } else {
1738
+ header != null && setHeader(valueOrRewrite, header, rewrite);
1739
+ }
1740
+
1741
+ return this;
1742
+ }
1743
+
1744
+ get(header, parser) {
1745
+ header = normalizeHeader$1(header);
1746
+
1747
+ if (header) {
1748
+ const key = utils$1.findKey(this, header);
1749
+
1750
+ if (key) {
1751
+ const value = this[key];
1752
+
1753
+ if (!parser) {
1754
+ return value;
1755
+ }
1756
+
1757
+ if (parser === true) {
1758
+ return parseTokens$1(value);
1759
+ }
1760
+
1761
+ if (utils$1.isFunction(parser)) {
1762
+ return parser.call(this, value, key);
1763
+ }
1764
+
1765
+ if (utils$1.isRegExp(parser)) {
1766
+ return parser.exec(value);
1767
+ }
1768
+
1769
+ throw new TypeError('parser must be boolean|regexp|function');
1770
+ }
1771
+ }
1772
+ }
1773
+
1774
+ has(header, matcher) {
1775
+ header = normalizeHeader$1(header);
1776
+
1777
+ if (header) {
1778
+ const key = utils$1.findKey(this, header);
1779
+
1780
+ return !!(key && this[key] !== undefined && (!matcher || matchHeaderValue$1(this, this[key], key, matcher)));
1781
+ }
1782
+
1783
+ return false;
1784
+ }
1785
+
1786
+ delete(header, matcher) {
1787
+ const self = this;
1788
+ let deleted = false;
1789
+
1790
+ function deleteHeader(_header) {
1791
+ _header = normalizeHeader$1(_header);
1792
+
1793
+ if (_header) {
1794
+ const key = utils$1.findKey(self, _header);
1795
+
1796
+ if (key && (!matcher || matchHeaderValue$1(self, self[key], key, matcher))) {
1797
+ delete self[key];
1798
+
1799
+ deleted = true;
1800
+ }
1801
+ }
1802
+ }
1803
+
1804
+ if (utils$1.isArray(header)) {
1805
+ header.forEach(deleteHeader);
1806
+ } else {
1807
+ deleteHeader(header);
1808
+ }
1809
+
1810
+ return deleted;
1811
+ }
1812
+
1813
+ clear(matcher) {
1814
+ const keys = Object.keys(this);
1815
+ let i = keys.length;
1816
+ let deleted = false;
1817
+
1818
+ while (i--) {
1819
+ const key = keys[i];
1820
+ if(!matcher || matchHeaderValue$1(this, this[key], key, matcher, true)) {
1821
+ delete this[key];
1822
+ deleted = true;
1823
+ }
1824
+ }
1825
+
1826
+ return deleted;
1827
+ }
1828
+
1829
+ normalize(format) {
1830
+ const self = this;
1831
+ const headers = {};
1832
+
1833
+ utils$1.forEach(this, (value, header) => {
1834
+ const key = utils$1.findKey(headers, header);
1835
+
1836
+ if (key) {
1837
+ self[key] = normalizeValue$1(value);
1838
+ delete self[header];
1839
+ return;
1840
+ }
1841
+
1842
+ const normalized = format ? formatHeader$1(header) : String(header).trim();
1843
+
1844
+ if (normalized !== header) {
1845
+ delete self[header];
1846
+ }
1847
+
1848
+ self[normalized] = normalizeValue$1(value);
1849
+
1850
+ headers[normalized] = true;
1851
+ });
1852
+
1853
+ return this;
1854
+ }
1855
+
1856
+ concat(...targets) {
1857
+ return this.constructor.concat(this, ...targets);
1858
+ }
1859
+
1860
+ toJSON(asStrings) {
1861
+ const obj = Object.create(null);
1862
+
1863
+ utils$1.forEach(this, (value, header) => {
1864
+ value != null && value !== false && (obj[header] = asStrings && utils$1.isArray(value) ? value.join(', ') : value);
1865
+ });
1866
+
1867
+ return obj;
1868
+ }
1869
+
1870
+ [Symbol.iterator]() {
1871
+ return Object.entries(this.toJSON())[Symbol.iterator]();
1872
+ }
1873
+
1874
+ toString() {
1875
+ return Object.entries(this.toJSON()).map(([header, value]) => header + ': ' + value).join('\n');
1876
+ }
1877
+
1878
+ get [Symbol.toStringTag]() {
1879
+ return 'AxiosHeaders';
1880
+ }
1881
+
1882
+ static from(thing) {
1883
+ return thing instanceof this ? thing : new this(thing);
1884
+ }
1885
+
1886
+ static concat(first, ...targets) {
1887
+ const computed = new this(first);
1888
+
1889
+ targets.forEach((target) => computed.set(target));
1890
+
1891
+ return computed;
1892
+ }
1893
+
1894
+ static accessor(header) {
1895
+ const internals = this[$internals$1] = (this[$internals$1] = {
1896
+ accessors: {}
1897
+ });
1898
+
1899
+ const accessors = internals.accessors;
1900
+ const prototype = this.prototype;
1901
+
1902
+ function defineAccessor(_header) {
1903
+ const lHeader = normalizeHeader$1(_header);
1904
+
1905
+ if (!accessors[lHeader]) {
1906
+ buildAccessors$1(prototype, _header);
1907
+ accessors[lHeader] = true;
1908
+ }
1909
+ }
1910
+
1911
+ utils$1.isArray(header) ? header.forEach(defineAccessor) : defineAccessor(header);
1912
+
1913
+ return this;
1914
+ }
1915
+ };
1916
+
1917
+ AxiosHeaders$2.accessor(['Content-Type', 'Content-Length', 'Accept', 'Accept-Encoding', 'User-Agent', 'Authorization']);
1918
+
1919
+ utils$1.freezeMethods(AxiosHeaders$2.prototype);
1920
+ utils$1.freezeMethods(AxiosHeaders$2);
1921
+
1922
+ var AxiosHeaders$1$1 = AxiosHeaders$2;
1923
+
1924
+ /**
1925
+ * Transform the data for a request or a response
1926
+ *
1927
+ * @param {Array|Function} fns A single function or Array of functions
1928
+ * @param {?Object} response The response object
1929
+ *
1930
+ * @returns {*} The resulting transformed data
1931
+ */
1932
+ function transformData$1(fns, response) {
1933
+ const config = this || defaults$1$1;
1934
+ const context = response || config;
1935
+ const headers = AxiosHeaders$1$1.from(context.headers);
1936
+ let data = context.data;
1937
+
1938
+ utils$1.forEach(fns, function transform(fn) {
1939
+ data = fn.call(config, data, headers.normalize(), response ? response.status : undefined);
1940
+ });
1941
+
1942
+ headers.normalize();
1943
+
1944
+ return data;
1945
+ }
1946
+
1947
+ function isCancel$1(value) {
1948
+ return !!(value && value.__CANCEL__);
1949
+ }
1950
+
1951
+ /**
1952
+ * A `CanceledError` is an object that is thrown when an operation is canceled.
1953
+ *
1954
+ * @param {string=} message The message.
1955
+ * @param {Object=} config The config.
1956
+ * @param {Object=} request The request.
1957
+ *
1958
+ * @returns {CanceledError} The created error.
1959
+ */
1960
+ function CanceledError$1(message, config, request) {
1961
+ // eslint-disable-next-line no-eq-null,eqeqeq
1962
+ AxiosError$1.call(this, message == null ? 'canceled' : message, AxiosError$1.ERR_CANCELED, config, request);
1963
+ this.name = 'CanceledError';
1964
+ }
1965
+
1966
+ utils$1.inherits(CanceledError$1, AxiosError$1, {
1967
+ __CANCEL__: true
1968
+ });
1969
+
1970
+ /**
1971
+ * Resolve or reject a Promise based on response status.
1972
+ *
1973
+ * @param {Function} resolve A function that resolves the promise.
1974
+ * @param {Function} reject A function that rejects the promise.
1975
+ * @param {object} response The response.
1976
+ *
1977
+ * @returns {object} The response.
1978
+ */
1979
+ function settle$1(resolve, reject, response) {
1980
+ const validateStatus = response.config.validateStatus;
1981
+ if (!response.status || !validateStatus || validateStatus(response.status)) {
1982
+ resolve(response);
1983
+ } else {
1984
+ reject(new AxiosError$1(
1985
+ 'Request failed with status code ' + response.status,
1986
+ [AxiosError$1.ERR_BAD_REQUEST, AxiosError$1.ERR_BAD_RESPONSE][Math.floor(response.status / 100) - 4],
1987
+ response.config,
1988
+ response.request,
1989
+ response
1990
+ ));
1991
+ }
1992
+ }
1993
+
1994
+ var cookies$1 = platform$1.isStandardBrowserEnv ?
1995
+
1996
+ // Standard browser envs support document.cookie
1997
+ (function standardBrowserEnv() {
1998
+ return {
1999
+ write: function write(name, value, expires, path, domain, secure) {
2000
+ const cookie = [];
2001
+ cookie.push(name + '=' + encodeURIComponent(value));
2002
+
2003
+ if (utils$1.isNumber(expires)) {
2004
+ cookie.push('expires=' + new Date(expires).toGMTString());
2005
+ }
2006
+
2007
+ if (utils$1.isString(path)) {
2008
+ cookie.push('path=' + path);
2009
+ }
2010
+
2011
+ if (utils$1.isString(domain)) {
2012
+ cookie.push('domain=' + domain);
2013
+ }
2014
+
2015
+ if (secure === true) {
2016
+ cookie.push('secure');
2017
+ }
2018
+
2019
+ document.cookie = cookie.join('; ');
2020
+ },
2021
+
2022
+ read: function read(name) {
2023
+ const match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)'));
2024
+ return (match ? decodeURIComponent(match[3]) : null);
2025
+ },
2026
+
2027
+ remove: function remove(name) {
2028
+ this.write(name, '', Date.now() - 86400000);
2029
+ }
2030
+ };
2031
+ })() :
2032
+
2033
+ // Non standard browser env (web workers, react-native) lack needed support.
2034
+ (function nonStandardBrowserEnv() {
2035
+ return {
2036
+ write: function write() {},
2037
+ read: function read() { return null; },
2038
+ remove: function remove() {}
2039
+ };
2040
+ })();
2041
+
2042
+ /**
2043
+ * Determines whether the specified URL is absolute
2044
+ *
2045
+ * @param {string} url The URL to test
2046
+ *
2047
+ * @returns {boolean} True if the specified URL is absolute, otherwise false
2048
+ */
2049
+ function isAbsoluteURL$1(url) {
2050
+ // A URL is considered absolute if it begins with "<scheme>://" or "//" (protocol-relative URL).
2051
+ // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed
2052
+ // by any combination of letters, digits, plus, period, or hyphen.
2053
+ return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url);
2054
+ }
2055
+
2056
+ /**
2057
+ * Creates a new URL by combining the specified URLs
2058
+ *
2059
+ * @param {string} baseURL The base URL
2060
+ * @param {string} relativeURL The relative URL
2061
+ *
2062
+ * @returns {string} The combined URL
2063
+ */
2064
+ function combineURLs$1(baseURL, relativeURL) {
2065
+ return relativeURL
2066
+ ? baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '')
2067
+ : baseURL;
2068
+ }
2069
+
2070
+ /**
2071
+ * Creates a new URL by combining the baseURL with the requestedURL,
2072
+ * only when the requestedURL is not already an absolute URL.
2073
+ * If the requestURL is absolute, this function returns the requestedURL untouched.
2074
+ *
2075
+ * @param {string} baseURL The base URL
2076
+ * @param {string} requestedURL Absolute or relative URL to combine
2077
+ *
2078
+ * @returns {string} The combined full path
2079
+ */
2080
+ function buildFullPath$1(baseURL, requestedURL) {
2081
+ if (baseURL && !isAbsoluteURL$1(requestedURL)) {
2082
+ return combineURLs$1(baseURL, requestedURL);
2083
+ }
2084
+ return requestedURL;
2085
+ }
2086
+
2087
+ var isURLSameOrigin$1 = platform$1.isStandardBrowserEnv ?
2088
+
2089
+ // Standard browser envs have full support of the APIs needed to test
2090
+ // whether the request URL is of the same origin as current location.
2091
+ (function standardBrowserEnv() {
2092
+ const msie = /(msie|trident)/i.test(navigator.userAgent);
2093
+ const urlParsingNode = document.createElement('a');
2094
+ let originURL;
2095
+
2096
+ /**
2097
+ * Parse a URL to discover it's components
2098
+ *
2099
+ * @param {String} url The URL to be parsed
2100
+ * @returns {Object}
2101
+ */
2102
+ function resolveURL(url) {
2103
+ let href = url;
2104
+
2105
+ if (msie) {
2106
+ // IE needs attribute set twice to normalize properties
2107
+ urlParsingNode.setAttribute('href', href);
2108
+ href = urlParsingNode.href;
2109
+ }
2110
+
2111
+ urlParsingNode.setAttribute('href', href);
2112
+
2113
+ // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils
2114
+ return {
2115
+ href: urlParsingNode.href,
2116
+ protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',
2117
+ host: urlParsingNode.host,
2118
+ search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '',
2119
+ hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',
2120
+ hostname: urlParsingNode.hostname,
2121
+ port: urlParsingNode.port,
2122
+ pathname: (urlParsingNode.pathname.charAt(0) === '/') ?
2123
+ urlParsingNode.pathname :
2124
+ '/' + urlParsingNode.pathname
2125
+ };
2126
+ }
2127
+
2128
+ originURL = resolveURL(window.location.href);
2129
+
2130
+ /**
2131
+ * Determine if a URL shares the same origin as the current location
2132
+ *
2133
+ * @param {String} requestURL The URL to test
2134
+ * @returns {boolean} True if URL shares the same origin, otherwise false
2135
+ */
2136
+ return function isURLSameOrigin(requestURL) {
2137
+ const parsed = (utils$1.isString(requestURL)) ? resolveURL(requestURL) : requestURL;
2138
+ return (parsed.protocol === originURL.protocol &&
2139
+ parsed.host === originURL.host);
2140
+ };
2141
+ })() :
2142
+
2143
+ // Non standard browser envs (web workers, react-native) lack needed support.
2144
+ (function nonStandardBrowserEnv() {
2145
+ return function isURLSameOrigin() {
2146
+ return true;
2147
+ };
2148
+ })();
2149
+
2150
+ function parseProtocol$1(url) {
2151
+ const match = /^([-+\w]{1,25})(:?\/\/|:)/.exec(url);
2152
+ return match && match[1] || '';
2153
+ }
2154
+
2155
+ /**
2156
+ * Calculate data maxRate
2157
+ * @param {Number} [samplesCount= 10]
2158
+ * @param {Number} [min= 1000]
2159
+ * @returns {Function}
2160
+ */
2161
+ function speedometer$1(samplesCount, min) {
2162
+ samplesCount = samplesCount || 10;
2163
+ const bytes = new Array(samplesCount);
2164
+ const timestamps = new Array(samplesCount);
2165
+ let head = 0;
2166
+ let tail = 0;
2167
+ let firstSampleTS;
2168
+
2169
+ min = min !== undefined ? min : 1000;
2170
+
2171
+ return function push(chunkLength) {
2172
+ const now = Date.now();
2173
+
2174
+ const startedAt = timestamps[tail];
2175
+
2176
+ if (!firstSampleTS) {
2177
+ firstSampleTS = now;
2178
+ }
2179
+
2180
+ bytes[head] = chunkLength;
2181
+ timestamps[head] = now;
2182
+
2183
+ let i = tail;
2184
+ let bytesCount = 0;
2185
+
2186
+ while (i !== head) {
2187
+ bytesCount += bytes[i++];
2188
+ i = i % samplesCount;
2189
+ }
2190
+
2191
+ head = (head + 1) % samplesCount;
2192
+
2193
+ if (head === tail) {
2194
+ tail = (tail + 1) % samplesCount;
2195
+ }
2196
+
2197
+ if (now - firstSampleTS < min) {
2198
+ return;
2199
+ }
2200
+
2201
+ const passed = startedAt && now - startedAt;
2202
+
2203
+ return passed ? Math.round(bytesCount * 1000 / passed) : undefined;
2204
+ };
2205
+ }
2206
+
2207
+ function progressEventReducer$1(listener, isDownloadStream) {
2208
+ let bytesNotified = 0;
2209
+ const _speedometer = speedometer$1(50, 250);
2210
+
2211
+ return e => {
2212
+ const loaded = e.loaded;
2213
+ const total = e.lengthComputable ? e.total : undefined;
2214
+ const progressBytes = loaded - bytesNotified;
2215
+ const rate = _speedometer(progressBytes);
2216
+ const inRange = loaded <= total;
2217
+
2218
+ bytesNotified = loaded;
2219
+
2220
+ const data = {
2221
+ loaded,
2222
+ total,
2223
+ progress: total ? (loaded / total) : undefined,
2224
+ bytes: progressBytes,
2225
+ rate: rate ? rate : undefined,
2226
+ estimated: rate && total && inRange ? (total - loaded) / rate : undefined,
2227
+ event: e
2228
+ };
2229
+
2230
+ data[isDownloadStream ? 'download' : 'upload'] = true;
2231
+
2232
+ listener(data);
2233
+ };
2234
+ }
2235
+
2236
+ const isXHRAdapterSupported$1 = typeof XMLHttpRequest !== 'undefined';
2237
+
2238
+ var xhrAdapter$1 = isXHRAdapterSupported$1 && function (config) {
2239
+ return new Promise(function dispatchXhrRequest(resolve, reject) {
2240
+ let requestData = config.data;
2241
+ const requestHeaders = AxiosHeaders$1$1.from(config.headers).normalize();
2242
+ const responseType = config.responseType;
2243
+ let onCanceled;
2244
+ function done() {
2245
+ if (config.cancelToken) {
2246
+ config.cancelToken.unsubscribe(onCanceled);
2247
+ }
2248
+
2249
+ if (config.signal) {
2250
+ config.signal.removeEventListener('abort', onCanceled);
2251
+ }
2252
+ }
2253
+
2254
+ if (utils$1.isFormData(requestData)) {
2255
+ if (platform$1.isStandardBrowserEnv || platform$1.isStandardBrowserWebWorkerEnv) {
2256
+ requestHeaders.setContentType(false); // Let the browser set it
2257
+ } else {
2258
+ requestHeaders.setContentType('multipart/form-data;', false); // mobile/desktop app frameworks
2259
+ }
2260
+ }
2261
+
2262
+ let request = new XMLHttpRequest();
2263
+
2264
+ // HTTP basic authentication
2265
+ if (config.auth) {
2266
+ const username = config.auth.username || '';
2267
+ const password = config.auth.password ? unescape(encodeURIComponent(config.auth.password)) : '';
2268
+ requestHeaders.set('Authorization', 'Basic ' + btoa(username + ':' + password));
2269
+ }
2270
+
2271
+ const fullPath = buildFullPath$1(config.baseURL, config.url);
2272
+
2273
+ request.open(config.method.toUpperCase(), buildURL$1(fullPath, config.params, config.paramsSerializer), true);
2274
+
2275
+ // Set the request timeout in MS
2276
+ request.timeout = config.timeout;
2277
+
2278
+ function onloadend() {
2279
+ if (!request) {
2280
+ return;
2281
+ }
2282
+ // Prepare the response
2283
+ const responseHeaders = AxiosHeaders$1$1.from(
2284
+ 'getAllResponseHeaders' in request && request.getAllResponseHeaders()
2285
+ );
2286
+ const responseData = !responseType || responseType === 'text' || responseType === 'json' ?
2287
+ request.responseText : request.response;
2288
+ const response = {
2289
+ data: responseData,
2290
+ status: request.status,
2291
+ statusText: request.statusText,
2292
+ headers: responseHeaders,
2293
+ config,
2294
+ request
2295
+ };
2296
+
2297
+ settle$1(function _resolve(value) {
2298
+ resolve(value);
2299
+ done();
2300
+ }, function _reject(err) {
2301
+ reject(err);
2302
+ done();
2303
+ }, response);
2304
+
2305
+ // Clean up request
2306
+ request = null;
2307
+ }
2308
+
2309
+ if ('onloadend' in request) {
2310
+ // Use onloadend if available
2311
+ request.onloadend = onloadend;
2312
+ } else {
2313
+ // Listen for ready state to emulate onloadend
2314
+ request.onreadystatechange = function handleLoad() {
2315
+ if (!request || request.readyState !== 4) {
2316
+ return;
2317
+ }
2318
+
2319
+ // The request errored out and we didn't get a response, this will be
2320
+ // handled by onerror instead
2321
+ // With one exception: request that using file: protocol, most browsers
2322
+ // will return status as 0 even though it's a successful request
2323
+ if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) {
2324
+ return;
2325
+ }
2326
+ // readystate handler is calling before onerror or ontimeout handlers,
2327
+ // so we should call onloadend on the next 'tick'
2328
+ setTimeout(onloadend);
2329
+ };
2330
+ }
2331
+
2332
+ // Handle browser request cancellation (as opposed to a manual cancellation)
2333
+ request.onabort = function handleAbort() {
2334
+ if (!request) {
2335
+ return;
2336
+ }
2337
+
2338
+ reject(new AxiosError$1('Request aborted', AxiosError$1.ECONNABORTED, config, request));
2339
+
2340
+ // Clean up request
2341
+ request = null;
2342
+ };
2343
+
2344
+ // Handle low level network errors
2345
+ request.onerror = function handleError() {
2346
+ // Real errors are hidden from us by the browser
2347
+ // onerror should only fire if it's a network error
2348
+ reject(new AxiosError$1('Network Error', AxiosError$1.ERR_NETWORK, config, request));
2349
+
2350
+ // Clean up request
2351
+ request = null;
2352
+ };
2353
+
2354
+ // Handle timeout
2355
+ request.ontimeout = function handleTimeout() {
2356
+ let timeoutErrorMessage = config.timeout ? 'timeout of ' + config.timeout + 'ms exceeded' : 'timeout exceeded';
2357
+ const transitional = config.transitional || transitionalDefaults$1;
2358
+ if (config.timeoutErrorMessage) {
2359
+ timeoutErrorMessage = config.timeoutErrorMessage;
2360
+ }
2361
+ reject(new AxiosError$1(
2362
+ timeoutErrorMessage,
2363
+ transitional.clarifyTimeoutError ? AxiosError$1.ETIMEDOUT : AxiosError$1.ECONNABORTED,
2364
+ config,
2365
+ request));
2366
+
2367
+ // Clean up request
2368
+ request = null;
2369
+ };
2370
+
2371
+ // Add xsrf header
2372
+ // This is only done if running in a standard browser environment.
2373
+ // Specifically not if we're in a web worker, or react-native.
2374
+ if (platform$1.isStandardBrowserEnv) {
2375
+ // Add xsrf header
2376
+ const xsrfValue = (config.withCredentials || isURLSameOrigin$1(fullPath))
2377
+ && config.xsrfCookieName && cookies$1.read(config.xsrfCookieName);
2378
+
2379
+ if (xsrfValue) {
2380
+ requestHeaders.set(config.xsrfHeaderName, xsrfValue);
2381
+ }
2382
+ }
2383
+
2384
+ // Remove Content-Type if data is undefined
2385
+ requestData === undefined && requestHeaders.setContentType(null);
2386
+
2387
+ // Add headers to the request
2388
+ if ('setRequestHeader' in request) {
2389
+ utils$1.forEach(requestHeaders.toJSON(), function setRequestHeader(val, key) {
2390
+ request.setRequestHeader(key, val);
2391
+ });
2392
+ }
2393
+
2394
+ // Add withCredentials to request if needed
2395
+ if (!utils$1.isUndefined(config.withCredentials)) {
2396
+ request.withCredentials = !!config.withCredentials;
2397
+ }
2398
+
2399
+ // Add responseType to request if needed
2400
+ if (responseType && responseType !== 'json') {
2401
+ request.responseType = config.responseType;
2402
+ }
2403
+
2404
+ // Handle progress if needed
2405
+ if (typeof config.onDownloadProgress === 'function') {
2406
+ request.addEventListener('progress', progressEventReducer$1(config.onDownloadProgress, true));
2407
+ }
2408
+
2409
+ // Not all browsers support upload events
2410
+ if (typeof config.onUploadProgress === 'function' && request.upload) {
2411
+ request.upload.addEventListener('progress', progressEventReducer$1(config.onUploadProgress));
2412
+ }
2413
+
2414
+ if (config.cancelToken || config.signal) {
2415
+ // Handle cancellation
2416
+ // eslint-disable-next-line func-names
2417
+ onCanceled = cancel => {
2418
+ if (!request) {
2419
+ return;
2420
+ }
2421
+ reject(!cancel || cancel.type ? new CanceledError$1(null, config, request) : cancel);
2422
+ request.abort();
2423
+ request = null;
2424
+ };
2425
+
2426
+ config.cancelToken && config.cancelToken.subscribe(onCanceled);
2427
+ if (config.signal) {
2428
+ config.signal.aborted ? onCanceled() : config.signal.addEventListener('abort', onCanceled);
2429
+ }
2430
+ }
2431
+
2432
+ const protocol = parseProtocol$1(fullPath);
2433
+
2434
+ if (protocol && platform$1.protocols.indexOf(protocol) === -1) {
2435
+ reject(new AxiosError$1('Unsupported protocol ' + protocol + ':', AxiosError$1.ERR_BAD_REQUEST, config));
2436
+ return;
2437
+ }
2438
+
2439
+
2440
+ // Send the request
2441
+ request.send(requestData || null);
2442
+ });
2443
+ };
2444
+
2445
+ const knownAdapters$1 = {
2446
+ http: httpAdapter$1,
2447
+ xhr: xhrAdapter$1
2448
+ };
2449
+
2450
+ utils$1.forEach(knownAdapters$1, (fn, value) => {
2451
+ if(fn) {
2452
+ try {
2453
+ Object.defineProperty(fn, 'name', {value});
2454
+ } catch (e) {
2455
+ // eslint-disable-next-line no-empty
2456
+ }
2457
+ Object.defineProperty(fn, 'adapterName', {value});
2458
+ }
2459
+ });
2460
+
2461
+ var adapters$1 = {
2462
+ getAdapter: (adapters) => {
2463
+ adapters = utils$1.isArray(adapters) ? adapters : [adapters];
2464
+
2465
+ const {length} = adapters;
2466
+ let nameOrAdapter;
2467
+ let adapter;
2468
+
2469
+ for (let i = 0; i < length; i++) {
2470
+ nameOrAdapter = adapters[i];
2471
+ if((adapter = utils$1.isString(nameOrAdapter) ? knownAdapters$1[nameOrAdapter.toLowerCase()] : nameOrAdapter)) {
2472
+ break;
2473
+ }
2474
+ }
2475
+
2476
+ if (!adapter) {
2477
+ if (adapter === false) {
2478
+ throw new AxiosError$1(
2479
+ `Adapter ${nameOrAdapter} is not supported by the environment`,
2480
+ 'ERR_NOT_SUPPORT'
2481
+ );
2482
+ }
2483
+
2484
+ throw new Error(
2485
+ utils$1.hasOwnProp(knownAdapters$1, nameOrAdapter) ?
2486
+ `Adapter '${nameOrAdapter}' is not available in the build` :
2487
+ `Unknown adapter '${nameOrAdapter}'`
2488
+ );
2489
+ }
2490
+
2491
+ if (!utils$1.isFunction(adapter)) {
2492
+ throw new TypeError('adapter is not a function');
2493
+ }
2494
+
2495
+ return adapter;
2496
+ },
2497
+ adapters: knownAdapters$1
2498
+ };
2499
+
2500
+ /**
2501
+ * Throws a `CanceledError` if cancellation has been requested.
2502
+ *
2503
+ * @param {Object} config The config that is to be used for the request
2504
+ *
2505
+ * @returns {void}
2506
+ */
2507
+ function throwIfCancellationRequested$1(config) {
2508
+ if (config.cancelToken) {
2509
+ config.cancelToken.throwIfRequested();
2510
+ }
2511
+
2512
+ if (config.signal && config.signal.aborted) {
2513
+ throw new CanceledError$1(null, config);
2514
+ }
2515
+ }
2516
+
2517
+ /**
2518
+ * Dispatch a request to the server using the configured adapter.
2519
+ *
2520
+ * @param {object} config The config that is to be used for the request
2521
+ *
2522
+ * @returns {Promise} The Promise to be fulfilled
2523
+ */
2524
+ function dispatchRequest$1(config) {
2525
+ throwIfCancellationRequested$1(config);
2526
+
2527
+ config.headers = AxiosHeaders$1$1.from(config.headers);
2528
+
2529
+ // Transform request data
2530
+ config.data = transformData$1.call(
2531
+ config,
2532
+ config.transformRequest
2533
+ );
2534
+
2535
+ if (['post', 'put', 'patch'].indexOf(config.method) !== -1) {
2536
+ config.headers.setContentType('application/x-www-form-urlencoded', false);
2537
+ }
2538
+
2539
+ const adapter = adapters$1.getAdapter(config.adapter || defaults$1$1.adapter);
2540
+
2541
+ return adapter(config).then(function onAdapterResolution(response) {
2542
+ throwIfCancellationRequested$1(config);
2543
+
2544
+ // Transform response data
2545
+ response.data = transformData$1.call(
2546
+ config,
2547
+ config.transformResponse,
2548
+ response
2549
+ );
2550
+
2551
+ response.headers = AxiosHeaders$1$1.from(response.headers);
2552
+
2553
+ return response;
2554
+ }, function onAdapterRejection(reason) {
2555
+ if (!isCancel$1(reason)) {
2556
+ throwIfCancellationRequested$1(config);
2557
+
2558
+ // Transform response data
2559
+ if (reason && reason.response) {
2560
+ reason.response.data = transformData$1.call(
2561
+ config,
2562
+ config.transformResponse,
2563
+ reason.response
2564
+ );
2565
+ reason.response.headers = AxiosHeaders$1$1.from(reason.response.headers);
2566
+ }
2567
+ }
2568
+
2569
+ return Promise.reject(reason);
2570
+ });
2571
+ }
2572
+
2573
+ const headersToObject$1 = (thing) => thing instanceof AxiosHeaders$1$1 ? thing.toJSON() : thing;
2574
+
2575
+ /**
2576
+ * Config-specific merge-function which creates a new config-object
2577
+ * by merging two configuration objects together.
2578
+ *
2579
+ * @param {Object} config1
2580
+ * @param {Object} config2
2581
+ *
2582
+ * @returns {Object} New object resulting from merging config2 to config1
2583
+ */
2584
+ function mergeConfig$1(config1, config2) {
2585
+ // eslint-disable-next-line no-param-reassign
2586
+ config2 = config2 || {};
2587
+ const config = {};
2588
+
2589
+ function getMergedValue(target, source, caseless) {
2590
+ if (utils$1.isPlainObject(target) && utils$1.isPlainObject(source)) {
2591
+ return utils$1.merge.call({caseless}, target, source);
2592
+ } else if (utils$1.isPlainObject(source)) {
2593
+ return utils$1.merge({}, source);
2594
+ } else if (utils$1.isArray(source)) {
2595
+ return source.slice();
2596
+ }
2597
+ return source;
2598
+ }
2599
+
2600
+ // eslint-disable-next-line consistent-return
2601
+ function mergeDeepProperties(a, b, caseless) {
2602
+ if (!utils$1.isUndefined(b)) {
2603
+ return getMergedValue(a, b, caseless);
2604
+ } else if (!utils$1.isUndefined(a)) {
2605
+ return getMergedValue(undefined, a, caseless);
2606
+ }
2607
+ }
2608
+
2609
+ // eslint-disable-next-line consistent-return
2610
+ function valueFromConfig2(a, b) {
2611
+ if (!utils$1.isUndefined(b)) {
2612
+ return getMergedValue(undefined, b);
2613
+ }
2614
+ }
2615
+
2616
+ // eslint-disable-next-line consistent-return
2617
+ function defaultToConfig2(a, b) {
2618
+ if (!utils$1.isUndefined(b)) {
2619
+ return getMergedValue(undefined, b);
2620
+ } else if (!utils$1.isUndefined(a)) {
2621
+ return getMergedValue(undefined, a);
2622
+ }
2623
+ }
2624
+
2625
+ // eslint-disable-next-line consistent-return
2626
+ function mergeDirectKeys(a, b, prop) {
2627
+ if (prop in config2) {
2628
+ return getMergedValue(a, b);
2629
+ } else if (prop in config1) {
2630
+ return getMergedValue(undefined, a);
2631
+ }
2632
+ }
2633
+
2634
+ const mergeMap = {
2635
+ url: valueFromConfig2,
2636
+ method: valueFromConfig2,
2637
+ data: valueFromConfig2,
2638
+ baseURL: defaultToConfig2,
2639
+ transformRequest: defaultToConfig2,
2640
+ transformResponse: defaultToConfig2,
2641
+ paramsSerializer: defaultToConfig2,
2642
+ timeout: defaultToConfig2,
2643
+ timeoutMessage: defaultToConfig2,
2644
+ withCredentials: defaultToConfig2,
2645
+ adapter: defaultToConfig2,
2646
+ responseType: defaultToConfig2,
2647
+ xsrfCookieName: defaultToConfig2,
2648
+ xsrfHeaderName: defaultToConfig2,
2649
+ onUploadProgress: defaultToConfig2,
2650
+ onDownloadProgress: defaultToConfig2,
2651
+ decompress: defaultToConfig2,
2652
+ maxContentLength: defaultToConfig2,
2653
+ maxBodyLength: defaultToConfig2,
2654
+ beforeRedirect: defaultToConfig2,
2655
+ transport: defaultToConfig2,
2656
+ httpAgent: defaultToConfig2,
2657
+ httpsAgent: defaultToConfig2,
2658
+ cancelToken: defaultToConfig2,
2659
+ socketPath: defaultToConfig2,
2660
+ responseEncoding: defaultToConfig2,
2661
+ validateStatus: mergeDirectKeys,
2662
+ headers: (a, b) => mergeDeepProperties(headersToObject$1(a), headersToObject$1(b), true)
2663
+ };
2664
+
2665
+ utils$1.forEach(Object.keys(Object.assign({}, config1, config2)), function computeConfigValue(prop) {
2666
+ const merge = mergeMap[prop] || mergeDeepProperties;
2667
+ const configValue = merge(config1[prop], config2[prop], prop);
2668
+ (utils$1.isUndefined(configValue) && merge !== mergeDirectKeys) || (config[prop] = configValue);
2669
+ });
2670
+
2671
+ return config;
2672
+ }
2673
+
2674
+ const VERSION$1 = "1.4.0";
2675
+
2676
+ const validators$1$1 = {};
2677
+
2678
+ // eslint-disable-next-line func-names
2679
+ ['object', 'boolean', 'number', 'function', 'string', 'symbol'].forEach((type, i) => {
2680
+ validators$1$1[type] = function validator(thing) {
2681
+ return typeof thing === type || 'a' + (i < 1 ? 'n ' : ' ') + type;
2682
+ };
2683
+ });
2684
+
2685
+ const deprecatedWarnings$1 = {};
2686
+
2687
+ /**
2688
+ * Transitional option validator
2689
+ *
2690
+ * @param {function|boolean?} validator - set to false if the transitional option has been removed
2691
+ * @param {string?} version - deprecated version / removed since version
2692
+ * @param {string?} message - some message with additional info
2693
+ *
2694
+ * @returns {function}
2695
+ */
2696
+ validators$1$1.transitional = function transitional(validator, version, message) {
2697
+ function formatMessage(opt, desc) {
2698
+ return '[Axios v' + VERSION$1 + '] Transitional option \'' + opt + '\'' + desc + (message ? '. ' + message : '');
2699
+ }
2700
+
2701
+ // eslint-disable-next-line func-names
2702
+ return (value, opt, opts) => {
2703
+ if (validator === false) {
2704
+ throw new AxiosError$1(
2705
+ formatMessage(opt, ' has been removed' + (version ? ' in ' + version : '')),
2706
+ AxiosError$1.ERR_DEPRECATED
2707
+ );
2708
+ }
2709
+
2710
+ if (version && !deprecatedWarnings$1[opt]) {
2711
+ deprecatedWarnings$1[opt] = true;
2712
+ // eslint-disable-next-line no-console
2713
+ console.warn(
2714
+ formatMessage(
2715
+ opt,
2716
+ ' has been deprecated since v' + version + ' and will be removed in the near future'
2717
+ )
2718
+ );
2719
+ }
2720
+
2721
+ return validator ? validator(value, opt, opts) : true;
2722
+ };
2723
+ };
2724
+
2725
+ /**
2726
+ * Assert object's properties type
2727
+ *
2728
+ * @param {object} options
2729
+ * @param {object} schema
2730
+ * @param {boolean?} allowUnknown
2731
+ *
2732
+ * @returns {object}
2733
+ */
2734
+
2735
+ function assertOptions$1(options, schema, allowUnknown) {
2736
+ if (typeof options !== 'object') {
2737
+ throw new AxiosError$1('options must be an object', AxiosError$1.ERR_BAD_OPTION_VALUE);
2738
+ }
2739
+ const keys = Object.keys(options);
2740
+ let i = keys.length;
2741
+ while (i-- > 0) {
2742
+ const opt = keys[i];
2743
+ const validator = schema[opt];
2744
+ if (validator) {
2745
+ const value = options[opt];
2746
+ const result = value === undefined || validator(value, opt, options);
2747
+ if (result !== true) {
2748
+ throw new AxiosError$1('option ' + opt + ' must be ' + result, AxiosError$1.ERR_BAD_OPTION_VALUE);
2749
+ }
2750
+ continue;
2751
+ }
2752
+ if (allowUnknown !== true) {
2753
+ throw new AxiosError$1('Unknown option ' + opt, AxiosError$1.ERR_BAD_OPTION);
2754
+ }
2755
+ }
2756
+ }
2757
+
2758
+ var validator$1 = {
2759
+ assertOptions: assertOptions$1,
2760
+ validators: validators$1$1
2761
+ };
2762
+
2763
+ const validators$2 = validator$1.validators;
2764
+
2765
+ /**
2766
+ * Create a new instance of Axios
2767
+ *
2768
+ * @param {Object} instanceConfig The default config for the instance
2769
+ *
2770
+ * @return {Axios} A new instance of Axios
2771
+ */
2772
+ let Axios$2 = class Axios {
2773
+ constructor(instanceConfig) {
2774
+ this.defaults = instanceConfig;
2775
+ this.interceptors = {
2776
+ request: new InterceptorManager$1$1(),
2777
+ response: new InterceptorManager$1$1()
2778
+ };
2779
+ }
2780
+
2781
+ /**
2782
+ * Dispatch a request
2783
+ *
2784
+ * @param {String|Object} configOrUrl The config specific for this request (merged with this.defaults)
2785
+ * @param {?Object} config
2786
+ *
2787
+ * @returns {Promise} The Promise to be fulfilled
2788
+ */
2789
+ request(configOrUrl, config) {
2790
+ /*eslint no-param-reassign:0*/
2791
+ // Allow for axios('example/url'[, config]) a la fetch API
2792
+ if (typeof configOrUrl === 'string') {
2793
+ config = config || {};
2794
+ config.url = configOrUrl;
2795
+ } else {
2796
+ config = configOrUrl || {};
2797
+ }
2798
+
2799
+ config = mergeConfig$1(this.defaults, config);
2800
+
2801
+ const {transitional, paramsSerializer, headers} = config;
2802
+
2803
+ if (transitional !== undefined) {
2804
+ validator$1.assertOptions(transitional, {
2805
+ silentJSONParsing: validators$2.transitional(validators$2.boolean),
2806
+ forcedJSONParsing: validators$2.transitional(validators$2.boolean),
2807
+ clarifyTimeoutError: validators$2.transitional(validators$2.boolean)
2808
+ }, false);
2809
+ }
2810
+
2811
+ if (paramsSerializer != null) {
2812
+ if (utils$1.isFunction(paramsSerializer)) {
2813
+ config.paramsSerializer = {
2814
+ serialize: paramsSerializer
2815
+ };
2816
+ } else {
2817
+ validator$1.assertOptions(paramsSerializer, {
2818
+ encode: validators$2.function,
2819
+ serialize: validators$2.function
2820
+ }, true);
2821
+ }
2822
+ }
2823
+
2824
+ // Set config.method
2825
+ config.method = (config.method || this.defaults.method || 'get').toLowerCase();
2826
+
2827
+ let contextHeaders;
2828
+
2829
+ // Flatten headers
2830
+ contextHeaders = headers && utils$1.merge(
2831
+ headers.common,
2832
+ headers[config.method]
2833
+ );
2834
+
2835
+ contextHeaders && utils$1.forEach(
2836
+ ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'],
2837
+ (method) => {
2838
+ delete headers[method];
2839
+ }
2840
+ );
2841
+
2842
+ config.headers = AxiosHeaders$1$1.concat(contextHeaders, headers);
2843
+
2844
+ // filter out skipped interceptors
2845
+ const requestInterceptorChain = [];
2846
+ let synchronousRequestInterceptors = true;
2847
+ this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {
2848
+ if (typeof interceptor.runWhen === 'function' && interceptor.runWhen(config) === false) {
2849
+ return;
2850
+ }
2851
+
2852
+ synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous;
2853
+
2854
+ requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected);
2855
+ });
2856
+
2857
+ const responseInterceptorChain = [];
2858
+ this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {
2859
+ responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);
2860
+ });
2861
+
2862
+ let promise;
2863
+ let i = 0;
2864
+ let len;
2865
+
2866
+ if (!synchronousRequestInterceptors) {
2867
+ const chain = [dispatchRequest$1.bind(this), undefined];
2868
+ chain.unshift.apply(chain, requestInterceptorChain);
2869
+ chain.push.apply(chain, responseInterceptorChain);
2870
+ len = chain.length;
2871
+
2872
+ promise = Promise.resolve(config);
2873
+
2874
+ while (i < len) {
2875
+ promise = promise.then(chain[i++], chain[i++]);
2876
+ }
2877
+
2878
+ return promise;
2879
+ }
2880
+
2881
+ len = requestInterceptorChain.length;
2882
+
2883
+ let newConfig = config;
2884
+
2885
+ i = 0;
2886
+
2887
+ while (i < len) {
2888
+ const onFulfilled = requestInterceptorChain[i++];
2889
+ const onRejected = requestInterceptorChain[i++];
2890
+ try {
2891
+ newConfig = onFulfilled(newConfig);
2892
+ } catch (error) {
2893
+ onRejected.call(this, error);
2894
+ break;
2895
+ }
2896
+ }
2897
+
2898
+ try {
2899
+ promise = dispatchRequest$1.call(this, newConfig);
2900
+ } catch (error) {
2901
+ return Promise.reject(error);
2902
+ }
2903
+
2904
+ i = 0;
2905
+ len = responseInterceptorChain.length;
2906
+
2907
+ while (i < len) {
2908
+ promise = promise.then(responseInterceptorChain[i++], responseInterceptorChain[i++]);
2909
+ }
2910
+
2911
+ return promise;
2912
+ }
2913
+
2914
+ getUri(config) {
2915
+ config = mergeConfig$1(this.defaults, config);
2916
+ const fullPath = buildFullPath$1(config.baseURL, config.url);
2917
+ return buildURL$1(fullPath, config.params, config.paramsSerializer);
2918
+ }
2919
+ };
2920
+
2921
+ // Provide aliases for supported request methods
2922
+ utils$1.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) {
2923
+ /*eslint func-names:0*/
2924
+ Axios$2.prototype[method] = function(url, config) {
2925
+ return this.request(mergeConfig$1(config || {}, {
2926
+ method,
2927
+ url,
2928
+ data: (config || {}).data
2929
+ }));
2930
+ };
2931
+ });
2932
+
2933
+ utils$1.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
2934
+ /*eslint func-names:0*/
2935
+
2936
+ function generateHTTPMethod(isForm) {
2937
+ return function httpMethod(url, data, config) {
2938
+ return this.request(mergeConfig$1(config || {}, {
2939
+ method,
2940
+ headers: isForm ? {
2941
+ 'Content-Type': 'multipart/form-data'
2942
+ } : {},
2943
+ url,
2944
+ data
2945
+ }));
2946
+ };
2947
+ }
2948
+
2949
+ Axios$2.prototype[method] = generateHTTPMethod();
2950
+
2951
+ Axios$2.prototype[method + 'Form'] = generateHTTPMethod(true);
2952
+ });
2953
+
2954
+ var Axios$1$1 = Axios$2;
2955
+
2956
+ /**
2957
+ * A `CancelToken` is an object that can be used to request cancellation of an operation.
2958
+ *
2959
+ * @param {Function} executor The executor function.
2960
+ *
2961
+ * @returns {CancelToken}
2962
+ */
2963
+ let CancelToken$2 = class CancelToken {
2964
+ constructor(executor) {
2965
+ if (typeof executor !== 'function') {
2966
+ throw new TypeError('executor must be a function.');
2967
+ }
2968
+
2969
+ let resolvePromise;
2970
+
2971
+ this.promise = new Promise(function promiseExecutor(resolve) {
2972
+ resolvePromise = resolve;
2973
+ });
2974
+
2975
+ const token = this;
2976
+
2977
+ // eslint-disable-next-line func-names
2978
+ this.promise.then(cancel => {
2979
+ if (!token._listeners) return;
2980
+
2981
+ let i = token._listeners.length;
2982
+
2983
+ while (i-- > 0) {
2984
+ token._listeners[i](cancel);
2985
+ }
2986
+ token._listeners = null;
2987
+ });
2988
+
2989
+ // eslint-disable-next-line func-names
2990
+ this.promise.then = onfulfilled => {
2991
+ let _resolve;
2992
+ // eslint-disable-next-line func-names
2993
+ const promise = new Promise(resolve => {
2994
+ token.subscribe(resolve);
2995
+ _resolve = resolve;
2996
+ }).then(onfulfilled);
2997
+
2998
+ promise.cancel = function reject() {
2999
+ token.unsubscribe(_resolve);
3000
+ };
3001
+
3002
+ return promise;
3003
+ };
3004
+
3005
+ executor(function cancel(message, config, request) {
3006
+ if (token.reason) {
3007
+ // Cancellation has already been requested
3008
+ return;
3009
+ }
3010
+
3011
+ token.reason = new CanceledError$1(message, config, request);
3012
+ resolvePromise(token.reason);
3013
+ });
3014
+ }
3015
+
3016
+ /**
3017
+ * Throws a `CanceledError` if cancellation has been requested.
3018
+ */
3019
+ throwIfRequested() {
3020
+ if (this.reason) {
3021
+ throw this.reason;
3022
+ }
3023
+ }
3024
+
3025
+ /**
3026
+ * Subscribe to the cancel signal
3027
+ */
3028
+
3029
+ subscribe(listener) {
3030
+ if (this.reason) {
3031
+ listener(this.reason);
3032
+ return;
3033
+ }
3034
+
3035
+ if (this._listeners) {
3036
+ this._listeners.push(listener);
3037
+ } else {
3038
+ this._listeners = [listener];
3039
+ }
3040
+ }
3041
+
3042
+ /**
3043
+ * Unsubscribe from the cancel signal
3044
+ */
3045
+
3046
+ unsubscribe(listener) {
3047
+ if (!this._listeners) {
3048
+ return;
3049
+ }
3050
+ const index = this._listeners.indexOf(listener);
3051
+ if (index !== -1) {
3052
+ this._listeners.splice(index, 1);
3053
+ }
3054
+ }
3055
+
3056
+ /**
3057
+ * Returns an object that contains a new `CancelToken` and a function that, when called,
3058
+ * cancels the `CancelToken`.
3059
+ */
3060
+ static source() {
3061
+ let cancel;
3062
+ const token = new CancelToken(function executor(c) {
3063
+ cancel = c;
3064
+ });
3065
+ return {
3066
+ token,
3067
+ cancel
3068
+ };
3069
+ }
3070
+ };
3071
+
3072
+ var CancelToken$1$1 = CancelToken$2;
3073
+
3074
+ /**
3075
+ * Syntactic sugar for invoking a function and expanding an array for arguments.
3076
+ *
3077
+ * Common use case would be to use `Function.prototype.apply`.
3078
+ *
3079
+ * ```js
3080
+ * function f(x, y, z) {}
3081
+ * var args = [1, 2, 3];
3082
+ * f.apply(null, args);
3083
+ * ```
3084
+ *
3085
+ * With `spread` this example can be re-written.
3086
+ *
3087
+ * ```js
3088
+ * spread(function(x, y, z) {})([1, 2, 3]);
3089
+ * ```
3090
+ *
3091
+ * @param {Function} callback
3092
+ *
3093
+ * @returns {Function}
3094
+ */
3095
+ function spread$1(callback) {
3096
+ return function wrap(arr) {
3097
+ return callback.apply(null, arr);
3098
+ };
3099
+ }
3100
+
3101
+ /**
3102
+ * Determines whether the payload is an error thrown by Axios
3103
+ *
3104
+ * @param {*} payload The value to test
3105
+ *
3106
+ * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false
3107
+ */
3108
+ function isAxiosError$1(payload) {
3109
+ return utils$1.isObject(payload) && (payload.isAxiosError === true);
3110
+ }
3111
+
3112
+ const HttpStatusCode$2 = {
3113
+ Continue: 100,
3114
+ SwitchingProtocols: 101,
3115
+ Processing: 102,
3116
+ EarlyHints: 103,
3117
+ Ok: 200,
3118
+ Created: 201,
3119
+ Accepted: 202,
3120
+ NonAuthoritativeInformation: 203,
3121
+ NoContent: 204,
3122
+ ResetContent: 205,
3123
+ PartialContent: 206,
3124
+ MultiStatus: 207,
3125
+ AlreadyReported: 208,
3126
+ ImUsed: 226,
3127
+ MultipleChoices: 300,
3128
+ MovedPermanently: 301,
3129
+ Found: 302,
3130
+ SeeOther: 303,
3131
+ NotModified: 304,
3132
+ UseProxy: 305,
3133
+ Unused: 306,
3134
+ TemporaryRedirect: 307,
3135
+ PermanentRedirect: 308,
3136
+ BadRequest: 400,
3137
+ Unauthorized: 401,
3138
+ PaymentRequired: 402,
3139
+ Forbidden: 403,
3140
+ NotFound: 404,
3141
+ MethodNotAllowed: 405,
3142
+ NotAcceptable: 406,
3143
+ ProxyAuthenticationRequired: 407,
3144
+ RequestTimeout: 408,
3145
+ Conflict: 409,
3146
+ Gone: 410,
3147
+ LengthRequired: 411,
3148
+ PreconditionFailed: 412,
3149
+ PayloadTooLarge: 413,
3150
+ UriTooLong: 414,
3151
+ UnsupportedMediaType: 415,
3152
+ RangeNotSatisfiable: 416,
3153
+ ExpectationFailed: 417,
3154
+ ImATeapot: 418,
3155
+ MisdirectedRequest: 421,
3156
+ UnprocessableEntity: 422,
3157
+ Locked: 423,
3158
+ FailedDependency: 424,
3159
+ TooEarly: 425,
3160
+ UpgradeRequired: 426,
3161
+ PreconditionRequired: 428,
3162
+ TooManyRequests: 429,
3163
+ RequestHeaderFieldsTooLarge: 431,
3164
+ UnavailableForLegalReasons: 451,
3165
+ InternalServerError: 500,
3166
+ NotImplemented: 501,
3167
+ BadGateway: 502,
3168
+ ServiceUnavailable: 503,
3169
+ GatewayTimeout: 504,
3170
+ HttpVersionNotSupported: 505,
3171
+ VariantAlsoNegotiates: 506,
3172
+ InsufficientStorage: 507,
3173
+ LoopDetected: 508,
3174
+ NotExtended: 510,
3175
+ NetworkAuthenticationRequired: 511,
3176
+ };
3177
+
3178
+ Object.entries(HttpStatusCode$2).forEach(([key, value]) => {
3179
+ HttpStatusCode$2[value] = key;
3180
+ });
3181
+
3182
+ var HttpStatusCode$1$1 = HttpStatusCode$2;
3183
+
3184
+ /**
3185
+ * Create an instance of Axios
3186
+ *
3187
+ * @param {Object} defaultConfig The default config for the instance
3188
+ *
3189
+ * @returns {Axios} A new instance of Axios
3190
+ */
3191
+ function createInstance$1(defaultConfig) {
3192
+ const context = new Axios$1$1(defaultConfig);
3193
+ const instance = bind$1(Axios$1$1.prototype.request, context);
3194
+
3195
+ // Copy axios.prototype to instance
3196
+ utils$1.extend(instance, Axios$1$1.prototype, context, {allOwnKeys: true});
3197
+
3198
+ // Copy context to instance
3199
+ utils$1.extend(instance, context, null, {allOwnKeys: true});
3200
+
3201
+ // Factory for creating new instances
3202
+ instance.create = function create(instanceConfig) {
3203
+ return createInstance$1(mergeConfig$1(defaultConfig, instanceConfig));
3204
+ };
3205
+
3206
+ return instance;
3207
+ }
3208
+
3209
+ // Create the default instance to be exported
3210
+ const axios$1 = createInstance$1(defaults$1$1);
3211
+
3212
+ // Expose Axios class to allow class inheritance
3213
+ axios$1.Axios = Axios$1$1;
3214
+
3215
+ // Expose Cancel & CancelToken
3216
+ axios$1.CanceledError = CanceledError$1;
3217
+ axios$1.CancelToken = CancelToken$1$1;
3218
+ axios$1.isCancel = isCancel$1;
3219
+ axios$1.VERSION = VERSION$1;
3220
+ axios$1.toFormData = toFormData$1;
3221
+
3222
+ // Expose AxiosError class
3223
+ axios$1.AxiosError = AxiosError$1;
3224
+
3225
+ // alias for CanceledError for backward compatibility
3226
+ axios$1.Cancel = axios$1.CanceledError;
3227
+
3228
+ // Expose all/spread
3229
+ axios$1.all = function all(promises) {
3230
+ return Promise.all(promises);
3231
+ };
3232
+
3233
+ axios$1.spread = spread$1;
3234
+
3235
+ // Expose isAxiosError
3236
+ axios$1.isAxiosError = isAxiosError$1;
3237
+
3238
+ // Expose mergeConfig
3239
+ axios$1.mergeConfig = mergeConfig$1;
3240
+
3241
+ axios$1.AxiosHeaders = AxiosHeaders$1$1;
3242
+
3243
+ axios$1.formToJSON = thing => formDataToJSON$1(utils$1.isHTMLForm(thing) ? new FormData(thing) : thing);
3244
+
3245
+ axios$1.HttpStatusCode = HttpStatusCode$1$1;
3246
+
3247
+ axios$1.default = axios$1;
3248
+
3249
+ // this module should only have a default export
3250
+ var globalAxios$1 = axios$1;
3251
+
3252
+ /* tslint:disable */
3253
+ /* eslint-disable */
3254
+ /**
3255
+ * Immutable X API
3256
+ * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
3257
+ *
3258
+ * The version of the OpenAPI document: 3.0
3259
+ * Contact: support@immutable.com
3260
+ *
3261
+ * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
3262
+ * https://openapi-generator.tech
3263
+ * Do not edit the class manually.
3264
+ */
3265
+ let Configuration$1 = class Configuration {
3266
+ /**
3267
+ * parameter for apiKey security
3268
+ * @param name security name
3269
+ * @memberof Configuration
3270
+ */
3271
+ apiKey;
3272
+ /**
3273
+ * parameter for basic security
3274
+ *
3275
+ * @type {string}
3276
+ * @memberof Configuration
3277
+ */
3278
+ username;
3279
+ /**
3280
+ * parameter for basic security
3281
+ *
3282
+ * @type {string}
3283
+ * @memberof Configuration
3284
+ */
3285
+ password;
3286
+ /**
3287
+ * parameter for oauth2 security
3288
+ * @param name security name
3289
+ * @param scopes oauth2 scope
3290
+ * @memberof Configuration
3291
+ */
3292
+ accessToken;
3293
+ /**
3294
+ * override base path
3295
+ *
3296
+ * @type {string}
3297
+ * @memberof Configuration
3298
+ */
3299
+ basePath;
3300
+ /**
3301
+ * base options for axios calls
3302
+ *
3303
+ * @type {any}
3304
+ * @memberof Configuration
3305
+ */
3306
+ baseOptions;
3307
+ /**
3308
+ * The FormData constructor that will be used to create multipart form data
3309
+ * requests. You can inject this here so that execution environments that
3310
+ * do not support the FormData class can still run the generated client.
3311
+ *
3312
+ * @type {new () => FormData}
3313
+ */
3314
+ formDataCtor;
3315
+ constructor(param = {}) {
3316
+ this.apiKey = param.apiKey;
3317
+ this.username = param.username;
3318
+ this.password = param.password;
3319
+ this.accessToken = param.accessToken;
3320
+ this.basePath = param.basePath;
3321
+ this.baseOptions = param.baseOptions;
3322
+ this.formDataCtor = param.formDataCtor;
3323
+ }
3324
+ /**
3325
+ * Check if the given MIME is a JSON MIME.
3326
+ * JSON MIME examples:
3327
+ * application/json
3328
+ * application/json; charset=UTF8
3329
+ * APPLICATION/JSON
3330
+ * application/vnd.company+json
3331
+ * @param mime - MIME (Multipurpose Internet Mail Extensions)
3332
+ * @return True if the given MIME is JSON, false otherwise.
3333
+ */
3334
+ isJsonMime(mime) {
3335
+ const jsonMime = new RegExp('^(application\/json|[^;/ \t]+\/[^;/ \t]+[+]json)[ \t]*(;.*)?$', 'i');
3336
+ return mime !== null && (jsonMime.test(mime) || mime.toLowerCase() === 'application/json-patch+json');
3337
+ }
3338
+ };
3339
+
40
3340
  /* tslint:disable */
41
3341
  /* eslint-disable */
42
3342
  /**
@@ -1745,7 +5045,7 @@ class TokensApi extends BaseAPI$1 {
1745
5045
  * https://openapi-generator.tech
1746
5046
  * Do not edit the class manually.
1747
5047
  */
1748
- let Configuration$1 = class Configuration {
5048
+ let Configuration$2 = class Configuration {
1749
5049
  /**
1750
5050
  * parameter for apiKey security
1751
5051
  * @param name security name
@@ -2157,59 +5457,122 @@ const TokenContractType = {
2157
5457
  */
2158
5458
 
2159
5459
  var index = /*#__PURE__*/Object.freeze({
2160
- __proto__: null,
2161
- APIError400AllOfCodeEnum: APIError400AllOfCodeEnum,
2162
- APIError401AllOfCodeEnum: APIError401AllOfCodeEnum,
2163
- APIError403AllOfCodeEnum: APIError403AllOfCodeEnum,
2164
- APIError404AllOfCodeEnum: APIError404AllOfCodeEnum,
2165
- APIError429AllOfCodeEnum: APIError429AllOfCodeEnum,
2166
- APIError500AllOfCodeEnum: APIError500AllOfCodeEnum,
2167
- ActivitiesApi: ActivitiesApi,
2168
- ActivitiesApiAxiosParamCreator: ActivitiesApiAxiosParamCreator,
2169
- ActivitiesApiFactory: ActivitiesApiFactory,
2170
- ActivitiesApiFp: ActivitiesApiFp,
2171
- ActivityType: ActivityType,
2172
- ChainsApi: ChainsApi,
2173
- ChainsApiAxiosParamCreator: ChainsApiAxiosParamCreator,
2174
- ChainsApiFactory: ChainsApiFactory,
2175
- ChainsApiFp: ChainsApiFp,
2176
- CollectionContractType: CollectionContractType,
2177
- CollectionsApi: CollectionsApi,
2178
- CollectionsApiAxiosParamCreator: CollectionsApiAxiosParamCreator,
2179
- CollectionsApiFactory: CollectionsApiFactory,
2180
- CollectionsApiFp: CollectionsApiFp,
2181
- Configuration: Configuration$1,
2182
- CreateOrderProtocolDataOrderTypeEnum: CreateOrderProtocolDataOrderTypeEnum,
2183
- ERC20ItemItemTypeEnum: ERC20ItemItemTypeEnum,
2184
- ERC721ItemItemTypeEnum: ERC721ItemItemTypeEnum,
2185
- FeeFeeTypeEnum: FeeFeeTypeEnum,
2186
- NFTContractType: NFTContractType,
2187
- NativeItemItemTypeEnum: NativeItemItemTypeEnum,
2188
- NftOwnersApi: NftOwnersApi,
2189
- NftOwnersApiAxiosParamCreator: NftOwnersApiAxiosParamCreator,
2190
- NftOwnersApiFactory: NftOwnersApiFactory,
2191
- NftOwnersApiFp: NftOwnersApiFp,
2192
- NftsApi: NftsApi,
2193
- NftsApiAxiosParamCreator: NftsApiAxiosParamCreator,
2194
- NftsApiFactory: NftsApiFactory,
2195
- NftsApiFp: NftsApiFp,
2196
- OrderStatus: OrderStatus$1,
2197
- OrdersApi: OrdersApi,
2198
- OrdersApiAxiosParamCreator: OrdersApiAxiosParamCreator,
2199
- OrdersApiFactory: OrdersApiFactory,
2200
- OrdersApiFp: OrdersApiFp,
2201
- PassportApi: PassportApi,
2202
- PassportApiAxiosParamCreator: PassportApiAxiosParamCreator,
2203
- PassportApiFactory: PassportApiFactory,
2204
- PassportApiFp: PassportApiFp,
2205
- SaleFeeTypeEnum: SaleFeeTypeEnum,
2206
- TokenContractType: TokenContractType,
2207
- TokensApi: TokensApi,
2208
- TokensApiAxiosParamCreator: TokensApiAxiosParamCreator,
2209
- TokensApiFactory: TokensApiFactory,
2210
- TokensApiFp: TokensApiFp
5460
+ __proto__: null,
5461
+ APIError400AllOfCodeEnum: APIError400AllOfCodeEnum,
5462
+ APIError401AllOfCodeEnum: APIError401AllOfCodeEnum,
5463
+ APIError403AllOfCodeEnum: APIError403AllOfCodeEnum,
5464
+ APIError404AllOfCodeEnum: APIError404AllOfCodeEnum,
5465
+ APIError429AllOfCodeEnum: APIError429AllOfCodeEnum,
5466
+ APIError500AllOfCodeEnum: APIError500AllOfCodeEnum,
5467
+ ActivitiesApi: ActivitiesApi,
5468
+ ActivitiesApiAxiosParamCreator: ActivitiesApiAxiosParamCreator,
5469
+ ActivitiesApiFactory: ActivitiesApiFactory,
5470
+ ActivitiesApiFp: ActivitiesApiFp,
5471
+ ActivityType: ActivityType,
5472
+ ChainsApi: ChainsApi,
5473
+ ChainsApiAxiosParamCreator: ChainsApiAxiosParamCreator,
5474
+ ChainsApiFactory: ChainsApiFactory,
5475
+ ChainsApiFp: ChainsApiFp,
5476
+ CollectionContractType: CollectionContractType,
5477
+ CollectionsApi: CollectionsApi,
5478
+ CollectionsApiAxiosParamCreator: CollectionsApiAxiosParamCreator,
5479
+ CollectionsApiFactory: CollectionsApiFactory,
5480
+ CollectionsApiFp: CollectionsApiFp,
5481
+ Configuration: Configuration$2,
5482
+ CreateOrderProtocolDataOrderTypeEnum: CreateOrderProtocolDataOrderTypeEnum,
5483
+ ERC20ItemItemTypeEnum: ERC20ItemItemTypeEnum,
5484
+ ERC721ItemItemTypeEnum: ERC721ItemItemTypeEnum,
5485
+ FeeFeeTypeEnum: FeeFeeTypeEnum,
5486
+ NFTContractType: NFTContractType,
5487
+ NativeItemItemTypeEnum: NativeItemItemTypeEnum,
5488
+ NftOwnersApi: NftOwnersApi,
5489
+ NftOwnersApiAxiosParamCreator: NftOwnersApiAxiosParamCreator,
5490
+ NftOwnersApiFactory: NftOwnersApiFactory,
5491
+ NftOwnersApiFp: NftOwnersApiFp,
5492
+ NftsApi: NftsApi,
5493
+ NftsApiAxiosParamCreator: NftsApiAxiosParamCreator,
5494
+ NftsApiFactory: NftsApiFactory,
5495
+ NftsApiFp: NftsApiFp,
5496
+ OrderStatus: OrderStatus$1,
5497
+ OrdersApi: OrdersApi,
5498
+ OrdersApiAxiosParamCreator: OrdersApiAxiosParamCreator,
5499
+ OrdersApiFactory: OrdersApiFactory,
5500
+ OrdersApiFp: OrdersApiFp,
5501
+ PassportApi: PassportApi,
5502
+ PassportApiAxiosParamCreator: PassportApiAxiosParamCreator,
5503
+ PassportApiFactory: PassportApiFactory,
5504
+ PassportApiFp: PassportApiFp,
5505
+ SaleFeeTypeEnum: SaleFeeTypeEnum,
5506
+ TokenContractType: TokenContractType,
5507
+ TokensApi: TokensApi,
5508
+ TokensApiAxiosParamCreator: TokensApiAxiosParamCreator,
5509
+ TokensApiFactory: TokensApiFactory,
5510
+ TokensApiFp: TokensApiFp
2211
5511
  });
2212
5512
 
5513
+ class MultiRollupApiClients {
5514
+ config;
5515
+ activitiesApi;
5516
+ chainsApi;
5517
+ collectionApi;
5518
+ nftOwnersApi;
5519
+ nftsApi;
5520
+ ordersApi;
5521
+ passportApi;
5522
+ constructor(config) {
5523
+ this.config = config;
5524
+ this.activitiesApi = new ActivitiesApi(config.indexer);
5525
+ this.chainsApi = new ChainsApi(config.indexer);
5526
+ this.collectionApi = new CollectionsApi(config.indexer);
5527
+ this.nftOwnersApi = new NftOwnersApi(config.indexer);
5528
+ this.nftsApi = new NftsApi(config.indexer);
5529
+ this.ordersApi = new OrdersApi(config.orderBook);
5530
+ this.passportApi = new PassportApi(config.passport);
5531
+ }
5532
+ }
5533
+
5534
+ // eslint-disable-next-line @typescript-eslint/naming-convention
5535
+ const defaultHeaders$1 = { 'x-sdk-version': 'ts-immutable-sdk-0.4.1-alpha' };
5536
+ const createConfig = ({ basePath, headers, }) => {
5537
+ if (!basePath.trim()) {
5538
+ throw Error('basePath can not be empty');
5539
+ }
5540
+ const composedHeaders = { ...defaultHeaders$1, ...(headers || {}) };
5541
+ const apiConfigOptions = {
5542
+ basePath,
5543
+ baseOptions: { headers: composedHeaders },
5544
+ };
5545
+ return new Configuration$1(apiConfigOptions);
5546
+ };
5547
+ /**
5548
+ * Creates a Configuration for the specified environment
5549
+ * @returns an MultiRollupAPIConfiguration
5550
+ */
5551
+ const multiRollupConfig = {
5552
+ getProduction: () => ({
5553
+ indexer: createConfig({
5554
+ basePath: 'https://indexer-mr.imtbl.com',
5555
+ }),
5556
+ orderBook: createConfig({
5557
+ basePath: 'https://order-book-mr.imtbl.com',
5558
+ }),
5559
+ passport: createConfig({
5560
+ basePath: 'https://api.immutable.com',
5561
+ }),
5562
+ }),
5563
+ getSandbox: () => ({
5564
+ indexer: createConfig({
5565
+ basePath: 'https://indexer-mr.sandbox.imtbl.com',
5566
+ }),
5567
+ orderBook: createConfig({
5568
+ basePath: 'https://order-book-mr.sandbox.imtbl.com',
5569
+ }),
5570
+ passport: createConfig({
5571
+ basePath: 'https://api.sandbox.immutable.com',
5572
+ }),
5573
+ }),
5574
+ };
5575
+
2213
5576
  /**
2214
5577
  * Custom Error class that is returned from the API when a request fails
2215
5578
  */
@@ -2229,7 +5592,7 @@ class APIError extends Error {
2229
5592
 
2230
5593
  /* eslint-disable implicit-arrow-linebreak */
2231
5594
  const defaultHeaders = {
2232
- sdkVersion: 'ts-immutable-sdk-multi-rollup-api-client-0.4.0-alpha.2',
5595
+ sdkVersion: 'ts-immutable-sdk-multi-rollup-api-client-0.4.1-alpha',
2233
5596
  };
2234
5597
  /**
2235
5598
  * createAPIConfiguration to create a custom Configuration
@@ -2285,7 +5648,7 @@ class BlockchainDataConfiguration {
2285
5648
  * @returns APIError
2286
5649
  */
2287
5650
  function formatError(error) {
2288
- if (globalAxios$1.isAxiosError(error) && error.response) {
5651
+ if (axios$2.isAxiosError(error) && error.response) {
2289
5652
  const apiError = error.response.data;
2290
5653
  if (apiError.code && apiError.message) {
2291
5654
  return new APIError({
@@ -2495,7 +5858,7 @@ const createImmutableXConfiguration = ({ basePath, chainID, coreContractAddress,
2495
5858
  chainID,
2496
5859
  coreContractAddress,
2497
5860
  registrationContractAddress,
2498
- sdkVersion: 'ts-immutable-sdk-0.4.0-alpha.2',
5861
+ sdkVersion: 'ts-immutable-sdk-0.4.1-alpha',
2499
5862
  });
2500
5863
  /**
2501
5864
  * Sets `sdkVersion` at the time of build
@@ -6451,7 +9814,7 @@ const TransactionsApiAxiosParamCreator = function (configuration) {
6451
9814
  * @summary Info for a specific transaction
6452
9815
  * @param {string} transactionID The id of the starkex transaction to retrieve
6453
9816
  * @param {'starkex' | 'evm'} chainType roll up type
6454
- * @param {number} [chainID] ID of evm chain
9817
+ * @param {string} [chainID] ID of evm chain
6455
9818
  * @param {*} [options] Override http request option.
6456
9819
  * @throws {RequiredError}
6457
9820
  */
@@ -6526,7 +9889,7 @@ const TransactionsApiFp = function (configuration) {
6526
9889
  * @summary Info for a specific transaction
6527
9890
  * @param {string} transactionID The id of the starkex transaction to retrieve
6528
9891
  * @param {'starkex' | 'evm'} chainType roll up type
6529
- * @param {number} [chainID] ID of evm chain
9892
+ * @param {string} [chainID] ID of evm chain
6530
9893
  * @param {*} [options] Override http request option.
6531
9894
  * @throws {RequiredError}
6532
9895
  */
@@ -6666,6 +10029,24 @@ class Configuration {
6666
10029
  }
6667
10030
  }
6668
10031
 
10032
+ /* tslint:disable */
10033
+ /* eslint-disable */
10034
+ /**
10035
+ * Guardian
10036
+ * Guardian API
10037
+ *
10038
+ * The version of the OpenAPI document: 1.0.0
10039
+ * Contact: support@immutable.com
10040
+ *
10041
+ * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
10042
+ * https://openapi-generator.tech
10043
+ * Do not edit the class manually.
10044
+ */
10045
+ const TransactionApprovalRequestChainTypeEnum = {
10046
+ Starkex: 'starkex',
10047
+ Evm: 'evm'
10048
+ };
10049
+
6669
10050
  // used to sign message with L1 keys. Used for registration
6670
10051
  function serializeEthSignature(sig) {
6671
10052
  // This is because golang appends a recovery param
@@ -6773,10 +10154,17 @@ const withPassportError = async (fn, customErrorType) => {
6773
10154
  };
6774
10155
 
6775
10156
  const keyCrendentials = 'passport_credentials';
10157
+ const KEY_PKCE_STATE = 'pkce_state';
10158
+ const KEY_PKCE_VERIFIER = 'pkce_verifier';
6776
10159
  const validCredentialsMinTtlSec = 3600; // 1 hour
6777
10160
  class DeviceCredentialsManager {
6778
10161
  saveCredentials(tokenResponse) {
6779
- localStorage.setItem(keyCrendentials, JSON.stringify(tokenResponse));
10162
+ if (this.areValid(tokenResponse)) {
10163
+ localStorage.setItem(keyCrendentials, JSON.stringify(tokenResponse));
10164
+ }
10165
+ else {
10166
+ throw Error('Invalid credentials.');
10167
+ }
6780
10168
  }
6781
10169
  getCredentials() {
6782
10170
  const credentialsJson = localStorage.getItem(keyCrendentials);
@@ -6794,14 +10182,31 @@ class DeviceCredentialsManager {
6794
10182
  return false;
6795
10183
  }
6796
10184
  isTokenValid(jwt) {
6797
- const tokenPayload = jwt_decode(jwt);
6798
- const expiresAt = tokenPayload.exp ?? 0;
6799
- const now = (Date.now() / 1000) + validCredentialsMinTtlSec;
6800
- return expiresAt > now;
10185
+ try {
10186
+ const tokenPayload = jwt_decode(jwt);
10187
+ const expiresAt = tokenPayload.exp ?? 0;
10188
+ const now = (Date.now() / 1000) + validCredentialsMinTtlSec;
10189
+ return expiresAt > now;
10190
+ }
10191
+ catch (error) {
10192
+ return false;
10193
+ }
6801
10194
  }
6802
10195
  clearCredentials() {
6803
10196
  localStorage.removeItem(keyCrendentials);
6804
10197
  }
10198
+ savePKCEData(data) {
10199
+ localStorage.setItem(KEY_PKCE_STATE, data.state);
10200
+ localStorage.setItem(KEY_PKCE_VERIFIER, data.verifier);
10201
+ }
10202
+ getPKCEData() {
10203
+ const state = localStorage.getItem(KEY_PKCE_STATE);
10204
+ const verifier = localStorage.getItem(KEY_PKCE_VERIFIER);
10205
+ if (state && verifier) {
10206
+ return { state, verifier };
10207
+ }
10208
+ return null;
10209
+ }
6805
10210
  }
6806
10211
 
6807
10212
  const formUrlEncodedHeader = {
@@ -6843,10 +10248,12 @@ class AuthManager {
6843
10248
  userManager;
6844
10249
  config;
6845
10250
  deviceCredentialsManager;
10251
+ logoutMode;
6846
10252
  constructor(config) {
6847
10253
  this.config = config;
6848
10254
  this.userManager = new UserManager(getAuthConfiguration(config));
6849
10255
  this.deviceCredentialsManager = new DeviceCredentialsManager();
10256
+ this.logoutMode = config.oidcConfiguration.logoutMode || 'redirect';
6850
10257
  }
6851
10258
  static mapOidcUserToDomainModel = (oidcUser) => {
6852
10259
  const passport = oidcUser.profile?.passport;
@@ -6911,7 +10318,7 @@ class AuthManager {
6911
10318
  }
6912
10319
  async loginWithDeviceFlow() {
6913
10320
  return withPassportError(async () => {
6914
- const response = await globalAxios$1.post(`${this.config.authenticationDomain}/oauth/device/code`, {
10321
+ const response = await axios$2.post(`${this.config.authenticationDomain}/oauth/device/code`, {
6915
10322
  client_id: this.config.oidcConfiguration.clientId,
6916
10323
  scope: this.config.oidcConfiguration.scope,
6917
10324
  audience: this.config.oidcConfiguration.audience,
@@ -6944,7 +10351,7 @@ class AuthManager {
6944
10351
  return user;
6945
10352
  }
6946
10353
  catch (error) {
6947
- if (globalAxios$1.isAxiosError(error)) {
10354
+ if (axios$2.isAxiosError(error)) {
6948
10355
  const responseError = error.response?.data;
6949
10356
  switch (responseError.error) {
6950
10357
  case 'authorization_pending':
@@ -6969,13 +10376,66 @@ class AuthManager {
6969
10376
  }
6970
10377
  /* eslint-enable no-await-in-loop */
6971
10378
  async getDeviceFlowToken(deviceCode) {
6972
- const response = await globalAxios$1.post(`${this.config.authenticationDomain}/oauth/token`, {
10379
+ const response = await axios$2.post(`${this.config.authenticationDomain}/oauth/token`, {
6973
10380
  client_id: this.config.oidcConfiguration.clientId,
6974
10381
  grant_type: 'urn:ietf:params:oauth:grant-type:device_code',
6975
10382
  device_code: deviceCode,
6976
10383
  }, formUrlEncodedHeader);
6977
10384
  return response.data;
6978
10385
  }
10386
+ static base64URLEncode(str) {
10387
+ return str.toString('base64')
10388
+ .replace(/\+/g, '-')
10389
+ .replace(/\//g, '_')
10390
+ .replace(/=/g, '');
10391
+ }
10392
+ static sha256(buffer) {
10393
+ return crypto.createHash('sha256').update(buffer).digest();
10394
+ }
10395
+ getPKCEAuthorizationUrl() {
10396
+ const verifier = AuthManager.base64URLEncode(crypto.randomBytes(32));
10397
+ const challenge = AuthManager.base64URLEncode(AuthManager.sha256(verifier));
10398
+ // https://auth0.com/docs/secure/attack-protection/state-parameters
10399
+ const state = AuthManager.base64URLEncode(crypto.randomBytes(32));
10400
+ this.deviceCredentialsManager.savePKCEData({ state, verifier });
10401
+ return `${this.config.authenticationDomain}/authorize?`
10402
+ + 'response_type=code'
10403
+ + `&code_challenge=${challenge}`
10404
+ + '&code_challenge_method=S256'
10405
+ + `&client_id=${this.config.oidcConfiguration.clientId}`
10406
+ + `&redirect_uri=${this.config.oidcConfiguration.redirectUri}`
10407
+ + `&scope=${this.config.oidcConfiguration.scope}`
10408
+ + `&state=${state}`
10409
+ + `&audience=${this.config.oidcConfiguration.audience}`;
10410
+ }
10411
+ async connectImxPKCEFlow(authorizationCode, state) {
10412
+ return withPassportError(async () => {
10413
+ const pkceData = this.deviceCredentialsManager.getPKCEData();
10414
+ if (!pkceData) {
10415
+ throw new Error('No code verifier or state for PKCE');
10416
+ }
10417
+ if (state !== pkceData.state) {
10418
+ throw new Error('Provided state does not match stored state');
10419
+ }
10420
+ const tokenResponse = await this.getPKCEToken(authorizationCode, pkceData.verifier);
10421
+ const user = AuthManager.mapDeviceTokenResponseToDomainUserModel(tokenResponse);
10422
+ // Only persist credentials that contain the necessary data
10423
+ if (user.imx?.ethAddress && user.imx?.starkAddress && user.imx?.userAdminAddress) {
10424
+ this.deviceCredentialsManager.saveCredentials(tokenResponse);
10425
+ }
10426
+ return user;
10427
+ }, PassportErrorType.AUTHENTICATION_ERROR);
10428
+ }
10429
+ async getPKCEToken(authorizationCode, codeVerifier) {
10430
+ const response = await axios$2.post(`${this.config.authenticationDomain}/oauth/token`, {
10431
+ client_id: this.config.oidcConfiguration.clientId,
10432
+ grant_type: 'authorization_code',
10433
+ code_verifier: codeVerifier,
10434
+ code: authorizationCode,
10435
+ redirect_uri: this.config.oidcConfiguration.redirectUri,
10436
+ }, formUrlEncodedHeader);
10437
+ return response.data;
10438
+ }
6979
10439
  async connectImxWithCredentials(tokenResponse) {
6980
10440
  return withPassportError(async () => {
6981
10441
  if (this.deviceCredentialsManager.areValid(tokenResponse)) {
@@ -6992,7 +10452,7 @@ class AuthManager {
6992
10452
  }, PassportErrorType.AUTHENTICATION_ERROR);
6993
10453
  }
6994
10454
  async refreshToken(refreshToken) {
6995
- const response = await globalAxios$1.post(`${this.config.authenticationDomain}/oauth/token`, {
10455
+ const response = await axios$2.post(`${this.config.authenticationDomain}/oauth/token`, {
6996
10456
  client_id: this.config.oidcConfiguration.clientId,
6997
10457
  grant_type: 'refresh_token',
6998
10458
  refresh_token: refreshToken,
@@ -7000,7 +10460,15 @@ class AuthManager {
7000
10460
  return response.data;
7001
10461
  }
7002
10462
  async logout() {
7003
- return withPassportError(async () => this.userManager.signoutRedirect(), PassportErrorType.LOGOUT_ERROR);
10463
+ return withPassportError(async () => {
10464
+ if (this.logoutMode === 'silent') {
10465
+ return this.userManager.signoutSilent();
10466
+ }
10467
+ return this.userManager.signoutRedirect();
10468
+ }, PassportErrorType.LOGOUT_ERROR);
10469
+ }
10470
+ async logoutSilentCallback(url) {
10471
+ return this.userManager.signoutSilentCallback(url);
7004
10472
  }
7005
10473
  async logoutDeviceFlow() {
7006
10474
  return withPassportError(async () => {
@@ -7096,6 +10564,53 @@ const retryWithDelay = async (fn, options) => {
7096
10564
  }
7097
10565
  };
7098
10566
 
10567
+ /**
10568
+ * ProviderErrors should take priority over RpcErrorCodes
10569
+ */
10570
+ var ProviderErrorCode;
10571
+ (function (ProviderErrorCode) {
10572
+ ProviderErrorCode[ProviderErrorCode["USER_REJECTED_REQUEST"] = 4001] = "USER_REJECTED_REQUEST";
10573
+ ProviderErrorCode[ProviderErrorCode["UNAUTHORIZED"] = 4100] = "UNAUTHORIZED";
10574
+ ProviderErrorCode[ProviderErrorCode["UNSUPPORTED_METHOD"] = 4200] = "UNSUPPORTED_METHOD";
10575
+ ProviderErrorCode[ProviderErrorCode["DISCONNECTED"] = 4900] = "DISCONNECTED";
10576
+ })(ProviderErrorCode || (ProviderErrorCode = {}));
10577
+ var RpcErrorCode;
10578
+ (function (RpcErrorCode) {
10579
+ RpcErrorCode[RpcErrorCode["RPC_SERVER_ERROR"] = -32000] = "RPC_SERVER_ERROR";
10580
+ RpcErrorCode[RpcErrorCode["INVALID_REQUEST"] = -32600] = "INVALID_REQUEST";
10581
+ RpcErrorCode[RpcErrorCode["METHOD_NOT_FOUND"] = -32601] = "METHOD_NOT_FOUND";
10582
+ RpcErrorCode[RpcErrorCode["INVALID_PARAMS"] = -32602] = "INVALID_PARAMS";
10583
+ RpcErrorCode[RpcErrorCode["INTERNAL_ERROR"] = -32603] = "INTERNAL_ERROR";
10584
+ RpcErrorCode[RpcErrorCode["PARSE_ERROR"] = -32700] = "PARSE_ERROR";
10585
+ RpcErrorCode[RpcErrorCode["USER_REJECTED_REQUEST"] = -32003] = "USER_REJECTED_REQUEST";
10586
+ })(RpcErrorCode || (RpcErrorCode = {}));
10587
+ class JsonRpcError extends Error {
10588
+ message;
10589
+ code;
10590
+ constructor(code, message) {
10591
+ super(message);
10592
+ this.message = message;
10593
+ this.code = code;
10594
+ }
10595
+ }
10596
+
10597
+ const convertBigNumberishToString = (value) => BigNumber$1.from(value).toString();
10598
+ const transformGuardianTransactions = (txs) => {
10599
+ try {
10600
+ return txs.map((t) => ({
10601
+ delegateCall: t.delegateCall === true,
10602
+ revertOnError: t.revertOnError === true,
10603
+ gasLimit: t.gasLimit ? convertBigNumberishToString(t.gasLimit) : '0',
10604
+ target: t.to ?? ethers.constants.AddressZero,
10605
+ value: t.value ? convertBigNumberishToString(t.value) : '0',
10606
+ data: t.data ? t.data.toString() : '0x00',
10607
+ }));
10608
+ }
10609
+ catch (error) {
10610
+ const errorMessage = (error instanceof Error) ? error.message : String(error);
10611
+ throw new JsonRpcError(RpcErrorCode.INVALID_PARAMS, `Transaction failed to parsing: ${errorMessage}`);
10612
+ }
10613
+ };
7099
10614
  class GuardianClient {
7100
10615
  transactionAPI;
7101
10616
  confirmationScreen;
@@ -7130,7 +10645,7 @@ class GuardianClient {
7130
10645
  });
7131
10646
  const { confirmationRequired } = evaluateStarkexRes.data;
7132
10647
  if (confirmationRequired) {
7133
- const confirmationResult = await this.confirmationScreen.startGuardianTransaction(payloadHash, this.imxEtherAddress);
10648
+ const confirmationResult = await this.confirmationScreen.startGuardianTransaction(payloadHash, this.imxEtherAddress, TransactionApprovalRequestChainTypeEnum.Starkex);
7134
10649
  if (!confirmationResult.confirmed) {
7135
10650
  throw new Error('Transaction rejected by user');
7136
10651
  }
@@ -7139,6 +10654,47 @@ class GuardianClient {
7139
10654
  this.confirmationScreen.closeWindow();
7140
10655
  }
7141
10656
  }
10657
+ async evaluateEVMTransaction({ chainId, nonce, user, metaTransactions, }) {
10658
+ const headers = { Authorization: `Bearer ${user.accessToken}` };
10659
+ const guardianTransactions = transformGuardianTransactions(metaTransactions);
10660
+ try {
10661
+ const transactionEvaluationResponseAxiosResponse = await this.transactionAPI.evaluateTransaction({
10662
+ id: 'evm',
10663
+ transactionEvaluationRequest: {
10664
+ chainType: 'evm',
10665
+ chainId,
10666
+ transactionData: {
10667
+ nonce,
10668
+ userAddress: user.zkEvm.ethAddress,
10669
+ metaTransactions: guardianTransactions,
10670
+ },
10671
+ },
10672
+ }, { headers });
10673
+ return transactionEvaluationResponseAxiosResponse.data;
10674
+ }
10675
+ catch (error) {
10676
+ const errorMessage = (error instanceof Error) ? error.message : String(error);
10677
+ throw new JsonRpcError(RpcErrorCode.INTERNAL_ERROR, `Transaction failed to validate with error: ${errorMessage}`);
10678
+ }
10679
+ }
10680
+ async validateEVMTransaction({ chainId, nonce, user, metaTransactions, }) {
10681
+ const transactionEvaluationResponse = await this.evaluateEVMTransaction({
10682
+ chainId,
10683
+ nonce,
10684
+ user,
10685
+ metaTransactions,
10686
+ });
10687
+ const { confirmationRequired, transactionId } = transactionEvaluationResponse;
10688
+ if (confirmationRequired && !!transactionId) {
10689
+ const confirmationResult = await this.confirmationScreen.startGuardianTransaction(transactionId, this.imxEtherAddress, TransactionApprovalRequestChainTypeEnum.Evm, chainId);
10690
+ if (!confirmationResult.confirmed) {
10691
+ throw new JsonRpcError(RpcErrorCode.USER_REJECTED_REQUEST, 'Transaction rejected by user ');
10692
+ }
10693
+ }
10694
+ else {
10695
+ this.confirmationScreen.closeWindow();
10696
+ }
10697
+ }
7142
10698
  }
7143
10699
 
7144
10700
  async function exchangeTransfer$1({ user, starkSigner, request, exchangesApi, }) {
@@ -7203,6 +10759,7 @@ async function createOrder$1({ starkSigner, user, request, ordersApi, guardianCl
7203
10759
  amount_sell: amountSell,
7204
10760
  token_sell: convertToSignableToken(request.sell),
7205
10761
  fees: request.fees,
10762
+ split_fees: true,
7206
10763
  expiration_timestamp: request.expiration_timestamp,
7207
10764
  };
7208
10765
  const getSignableOrderResponse = await ordersApi.getSignableOrder({
@@ -7576,6 +11133,10 @@ class PassportImxProviderFactory {
7576
11133
  const user = await this.authManager.connectImxDeviceFlow(deviceCode, interval, timeoutMs);
7577
11134
  return this.createProviderInstance(user);
7578
11135
  }
11136
+ async getProviderWithPKCEFlow(authorizationCode, state) {
11137
+ const user = await this.authManager.connectImxPKCEFlow(authorizationCode, state);
11138
+ return this.createProviderInstance(user);
11139
+ }
7579
11140
  async getProviderWithCredentials(tokenResponse) {
7580
11141
  const user = await this.authManager.connectImxWithCredentials(tokenResponse);
7581
11142
  if (!user) {
@@ -7657,6 +11218,10 @@ class PassportConfiguration {
7657
11218
  magicProviderId;
7658
11219
  oidcConfiguration;
7659
11220
  baseConfig;
11221
+ zkEvmChainId;
11222
+ zkEvmRpcUrl;
11223
+ relayerUrl;
11224
+ multiRollupConfig;
7660
11225
  constructor({ baseConfig, overrides, ...oidcConfiguration }) {
7661
11226
  validateConfiguration(oidcConfiguration, [
7662
11227
  'clientId',
@@ -7669,10 +11234,16 @@ class PassportConfiguration {
7669
11234
  validateConfiguration(overrides, [
7670
11235
  'network',
7671
11236
  'authenticationDomain',
11237
+ 'passportDomain',
7672
11238
  'magicPublishableApiKey',
7673
11239
  'magicProviderId',
7674
- 'passportDomain',
11240
+ 'zkEvmRpcUrl',
11241
+ 'zkEvmChainId',
11242
+ 'relayerUrl',
7675
11243
  'imxPublicApiDomain',
11244
+ 'indexerMrBasePath',
11245
+ 'orderBookMrBasePath',
11246
+ 'passportMrBasePath',
7676
11247
  ], 'overrides');
7677
11248
  this.network = overrides.network;
7678
11249
  this.authenticationDomain = overrides.authenticationDomain;
@@ -7680,6 +11251,20 @@ class PassportConfiguration {
7680
11251
  this.imxPublicApiDomain = overrides.imxPublicApiDomain;
7681
11252
  this.magicPublishableApiKey = overrides.magicPublishableApiKey;
7682
11253
  this.magicProviderId = overrides.magicProviderId;
11254
+ this.zkEvmRpcUrl = overrides.zkEvmRpcUrl;
11255
+ this.zkEvmChainId = overrides.zkEvmChainId;
11256
+ this.relayerUrl = overrides.relayerUrl;
11257
+ this.multiRollupConfig = {
11258
+ indexer: createConfig({
11259
+ basePath: overrides.indexerMrBasePath,
11260
+ }),
11261
+ orderBook: createConfig({
11262
+ basePath: overrides.orderBookMrBasePath,
11263
+ }),
11264
+ passport: createConfig({
11265
+ basePath: overrides.passportMrBasePath,
11266
+ }),
11267
+ };
7683
11268
  }
7684
11269
  else {
7685
11270
  switch (baseConfig.environment) {
@@ -7690,6 +11275,10 @@ class PassportConfiguration {
7690
11275
  this.magicProviderId = 'fSMzaRQ4O7p4fttl7pCyGVtJS_G70P8SNsLXtPPGHo0=';
7691
11276
  this.passportDomain = 'https://passport.immutable.com';
7692
11277
  this.imxPublicApiDomain = 'https://api.immutable.com';
11278
+ this.zkEvmRpcUrl = ''; // TODO: ID-785 Update once mainnet has been deployed
11279
+ this.zkEvmChainId = ''; // TODO: ID-785 Update once mainnet has been deployed
11280
+ this.relayerUrl = 'https://api.immutable.com/relayer-mr';
11281
+ this.multiRollupConfig = multiRollupConfig.getProduction();
7693
11282
  break;
7694
11283
  }
7695
11284
  case Environment$1.SANDBOX:
@@ -7700,6 +11289,10 @@ class PassportConfiguration {
7700
11289
  this.magicProviderId = 'fSMzaRQ4O7p4fttl7pCyGVtJS_G70P8SNsLXtPPGHo0=';
7701
11290
  this.passportDomain = 'https://passport.sandbox.immutable.com';
7702
11291
  this.imxPublicApiDomain = 'https://api.sandbox.immutable.com';
11292
+ this.zkEvmRpcUrl = 'https://zkevm-rpc.sandbox.x.immutable.com';
11293
+ this.zkEvmChainId = 'eip155:13392';
11294
+ this.relayerUrl = 'https://api.sandbox.immutable.com/relayer-mr';
11295
+ this.multiRollupConfig = multiRollupConfig.getSandbox();
7703
11296
  break;
7704
11297
  }
7705
11298
  }
@@ -7807,7 +11400,7 @@ class ConfirmationScreen {
7807
11400
  }, CONFIRMATION_WINDOW_CLOSED_POLLING_DURATION);
7808
11401
  });
7809
11402
  }
7810
- startGuardianTransaction(transactionId, imxEtherAddress) {
11403
+ startGuardianTransaction(transactionId, imxEtherAddress, chainType, chainId) {
7811
11404
  return new Promise((resolve, reject) => {
7812
11405
  const messageHandler = ({ data, origin }) => {
7813
11406
  if (origin !== this.config.passportDomain
@@ -7836,7 +11429,16 @@ class ConfirmationScreen {
7836
11429
  return;
7837
11430
  }
7838
11431
  // eslint-disable-next-line max-len
7839
- this.confirmationWindow.location.href = `${this.config.passportDomain}/transaction-confirmation/transaction.html?transactionId=${transactionId}&imxEtherAddress=${imxEtherAddress}&chainType=starkex`;
11432
+ let href = '';
11433
+ if (chainType === TransactionApprovalRequestChainTypeEnum.Starkex) {
11434
+ // eslint-disable-next-line max-len
11435
+ href = `${this.config.passportDomain}/transaction-confirmation/transaction.html?transactionId=${transactionId}&imxEtherAddress=${imxEtherAddress}&chainType=starkex`;
11436
+ }
11437
+ else {
11438
+ // eslint-disable-next-line max-len
11439
+ href = `${this.config.passportDomain}/transaction-confirmation/zkevm?transactionId=${transactionId}&imxEtherAddress=${imxEtherAddress}&chainType=evm&chainId=${chainId}`;
11440
+ }
11441
+ this.confirmationWindow.location.href = href;
7840
11442
  // https://stackoverflow.com/questions/9388380/capture-the-close-event-of-popup-window-in-javascript/48240128#48240128
7841
11443
  const timer = setInterval(() => {
7842
11444
  if (this.confirmationWindow?.closed) {
@@ -7860,6 +11462,476 @@ class ConfirmationScreen {
7860
11462
  }
7861
11463
  }
7862
11464
 
11465
+ var RelayerTransactionStatus;
11466
+ (function (RelayerTransactionStatus) {
11467
+ RelayerTransactionStatus["PENDING"] = "PENDING";
11468
+ RelayerTransactionStatus["SUBMITTED"] = "SUBMITTED";
11469
+ RelayerTransactionStatus["SUCCESSFUL"] = "SUCCESSFUL";
11470
+ RelayerTransactionStatus["REVERTED"] = "REVERTED";
11471
+ RelayerTransactionStatus["FAILED"] = "FAILED";
11472
+ })(RelayerTransactionStatus || (RelayerTransactionStatus = {}));
11473
+ var ProviderEvent;
11474
+ (function (ProviderEvent) {
11475
+ ProviderEvent["ACCOUNTS_CHANGED"] = "accountsChanged";
11476
+ })(ProviderEvent || (ProviderEvent = {}));
11477
+
11478
+ class TypedEventEmitter {
11479
+ emitter = new EventEmitter();
11480
+ emit(eventName, ...eventArg) {
11481
+ this.emitter.emit(eventName, ...eventArg);
11482
+ }
11483
+ on(eventName, handler) {
11484
+ this.emitter.on(eventName, handler);
11485
+ }
11486
+ removeListener(eventName, handler) {
11487
+ this.emitter.removeListener(eventName, handler);
11488
+ }
11489
+ }
11490
+
11491
+ class RelayerClient {
11492
+ config;
11493
+ constructor({ config }) {
11494
+ this.config = config;
11495
+ }
11496
+ async postToRelayer(request) {
11497
+ const body = {
11498
+ id: 1,
11499
+ jsonrpc: '2.0',
11500
+ ...request,
11501
+ };
11502
+ const response = await fetch(`${this.config.relayerUrl}/v1/transactions`, {
11503
+ method: 'POST',
11504
+ headers: {
11505
+ 'Content-Type': 'application/json',
11506
+ },
11507
+ body: JSON.stringify(body),
11508
+ });
11509
+ const jsonResponse = await response.json();
11510
+ if (jsonResponse.error) {
11511
+ throw jsonResponse.error;
11512
+ }
11513
+ return jsonResponse;
11514
+ }
11515
+ async ethSendTransaction(to, data) {
11516
+ const payload = {
11517
+ method: 'eth_sendTransaction',
11518
+ params: [{
11519
+ to,
11520
+ data,
11521
+ chainId: this.config.zkEvmChainId.toString(),
11522
+ }],
11523
+ };
11524
+ const { result } = await this.postToRelayer(payload);
11525
+ return result;
11526
+ }
11527
+ async imGetTransactionByHash(hash) {
11528
+ const payload = {
11529
+ method: 'im_getTransactionByHash',
11530
+ params: [hash],
11531
+ };
11532
+ const { result } = await this.postToRelayer(payload);
11533
+ return result;
11534
+ }
11535
+ async imGetFeeOptions(userAddress, data) {
11536
+ const payload = {
11537
+ method: 'im_getFeeOptions',
11538
+ params: [{
11539
+ userAddress,
11540
+ data,
11541
+ chainId: this.config.zkEvmChainId.toString(),
11542
+ }],
11543
+ };
11544
+ const { result } = await this.postToRelayer(payload);
11545
+ return result;
11546
+ }
11547
+ }
11548
+
11549
+ const MESSAGE_TO_SIGN = 'Only sign this message from Immutable Passport';
11550
+ async function registerZkEvmUser({ authManager, magicProvider, multiRollupApiClients, accessToken, }) {
11551
+ const web3Provider = new Web3Provider(magicProvider);
11552
+ const ethSigner = web3Provider.getSigner();
11553
+ const ethereumAddress = await ethSigner.getAddress();
11554
+ const ethereumSignature = await signRaw(MESSAGE_TO_SIGN, ethSigner);
11555
+ const headers = { Authorization: `Bearer ${accessToken}` };
11556
+ try {
11557
+ await multiRollupApiClients.passportApi.createCounterfactualAddress({
11558
+ createCounterfactualAddressRequest: {
11559
+ ethereumAddress,
11560
+ ethereumSignature,
11561
+ },
11562
+ }, { headers });
11563
+ }
11564
+ catch (error) {
11565
+ throw new JsonRpcError(RpcErrorCode.INTERNAL_ERROR, `Failed to create counterfactual address: ${error}`);
11566
+ }
11567
+ const user = await authManager.loginSilent();
11568
+ if (!user?.zkEvm) {
11569
+ throw new JsonRpcError(RpcErrorCode.INTERNAL_ERROR, 'Failed to refresh user details');
11570
+ }
11571
+ return user;
11572
+ }
11573
+
11574
+ const loginZkEvmUser = async ({ authManager, config, magicAdapter, multiRollupApiClients, }) => {
11575
+ const user = await authManager.getUser() || await authManager.login();
11576
+ if (!user.idToken) {
11577
+ throw new Error('User is missing idToken');
11578
+ }
11579
+ const magicProvider = await magicAdapter.login(user.idToken, config.network);
11580
+ if (!user.zkEvm) {
11581
+ // Generate counterfactual address and retrieve updated Auth0 user
11582
+ const userZkevm = await registerZkEvmUser({
11583
+ authManager,
11584
+ magicProvider,
11585
+ multiRollupApiClients,
11586
+ accessToken: user.accessToken,
11587
+ });
11588
+ return {
11589
+ user: userZkevm,
11590
+ magicProvider,
11591
+ };
11592
+ }
11593
+ return {
11594
+ user: user,
11595
+ magicProvider,
11596
+ };
11597
+ };
11598
+
11599
+ // These are ignored by the Relayer but for consistency we set them to the
11600
+ // appropriate values for a 1/1 wallet.
11601
+ //
11602
+ // Weight of a single signature in the multisig
11603
+ const SIGNATURE_WEIGHT = 1;
11604
+ // Total required weight in the multisig
11605
+ const SIGNATURE_THRESHOLD = 1;
11606
+ const ETH_SIGN_FLAG = '02';
11607
+ const ETH_SIGN_PREFIX = '\x19\x01';
11608
+ const META_TRANSACTIONS_TYPE = `tuple(
11609
+ bool delegateCall,
11610
+ bool revertOnError,
11611
+ uint256 gasLimit,
11612
+ address target,
11613
+ uint256 value,
11614
+ bytes data
11615
+ )[]`;
11616
+ function getNormalisedTransactions(txs) {
11617
+ return txs.map((t) => ({
11618
+ delegateCall: t.delegateCall === true,
11619
+ revertOnError: t.revertOnError === true,
11620
+ gasLimit: t.gasLimit ?? ethers.constants.Zero,
11621
+ target: t.to ?? ethers.constants.AddressZero,
11622
+ value: t.value ?? ethers.constants.Zero,
11623
+ data: t.data ?? [],
11624
+ }));
11625
+ }
11626
+ function digestOfTransactionsAndNonce(nonce, normalisedTransactions) {
11627
+ const packMetaTransactionsNonceData = ethers.utils.defaultAbiCoder.encode(['uint256', META_TRANSACTIONS_TYPE], [nonce, normalisedTransactions]);
11628
+ return ethers.utils.keccak256(packMetaTransactionsNonceData);
11629
+ }
11630
+ const getNonce = async (jsonRpcProvider, smartContractWalletAddress) => {
11631
+ const code = await jsonRpcProvider.send('eth_getCode', [smartContractWalletAddress, 'latest']);
11632
+ if (code && code !== '0x') {
11633
+ const contract = new ethers.Contract(smartContractWalletAddress, walletContracts.mainModule.abi, jsonRpcProvider);
11634
+ return contract.nonce();
11635
+ }
11636
+ return 0;
11637
+ };
11638
+ const getSignedMetaTransactions = async (metaTransactions, nonce, chainId, walletAddress, signer) => {
11639
+ const normalisedMetaTransactions = getNormalisedTransactions(metaTransactions);
11640
+ // Get the hash
11641
+ const digest = digestOfTransactionsAndNonce(nonce, normalisedMetaTransactions);
11642
+ const completePayload = ethers.utils.solidityPack(['string', 'uint256', 'address', 'bytes32'], [ETH_SIGN_PREFIX, chainId, walletAddress, digest]);
11643
+ const hash = ethers.utils.keccak256(completePayload);
11644
+ // Sign the digest
11645
+ const hashArray = ethers.utils.arrayify(hash);
11646
+ const ethsigNoType = await signer.signMessage(hashArray);
11647
+ const signedDigest = `${ethsigNoType}${ETH_SIGN_FLAG}`;
11648
+ // Add metadata
11649
+ const encodedSignature = encodeSignature({
11650
+ threshold: SIGNATURE_THRESHOLD,
11651
+ signers: [
11652
+ {
11653
+ weight: SIGNATURE_WEIGHT,
11654
+ signature: signedDigest,
11655
+ },
11656
+ ],
11657
+ });
11658
+ // Encode the transaction;
11659
+ const walletInterface = new ethers.utils.Interface(walletContracts.mainModule.abi);
11660
+ return walletInterface.encodeFunctionData(walletInterface.getFunction('execute'), [
11661
+ normalisedMetaTransactions,
11662
+ nonce,
11663
+ encodedSignature,
11664
+ ]);
11665
+ };
11666
+ const chainIdNumber = (chainId) => {
11667
+ const caip2Components = chainId.split(':');
11668
+ if (caip2Components.length !== 2) {
11669
+ throw new Error('Invalid configuration, chain ID is not in CAIP-2 format');
11670
+ }
11671
+ return BigNumber$1.from(caip2Components[1]);
11672
+ };
11673
+
11674
+ const MAX_TRANSACTION_HASH_RETRIEVAL_RETRIES = 30;
11675
+ const TRANSACTION_HASH_RETRIEVAL_WAIT = 1000;
11676
+ const sendTransaction = async ({ params, magicProvider, jsonRpcProvider, relayerClient, guardianClient, config, user, }) => {
11677
+ const popupWindowSize = { width: 480, height: 580 };
11678
+ guardianClient.loading(popupWindowSize);
11679
+ const transactionRequest = params[0];
11680
+ if (!transactionRequest.to) {
11681
+ throw new JsonRpcError(RpcErrorCode.INVALID_PARAMS, 'eth_sendTransaction requires a "to" field');
11682
+ }
11683
+ const chainId = chainIdNumber(config.zkEvmChainId);
11684
+ const magicWeb3Provider = new Web3Provider(magicProvider);
11685
+ const signer = magicWeb3Provider.getSigner();
11686
+ const nonce = await getNonce(jsonRpcProvider, user.zkEvm.ethAddress);
11687
+ const metaTransaction = {
11688
+ to: transactionRequest.to,
11689
+ data: transactionRequest.data,
11690
+ nonce,
11691
+ value: transactionRequest.value,
11692
+ revertOnError: true,
11693
+ };
11694
+ // NOTE: We sign the transaction before getting the fee options because
11695
+ // accurate estimation of a transaction gas cost is only possible if the smart
11696
+ // wallet contract can actually execute it (in a simulated environment) - and
11697
+ // it can only execute signed transactions.
11698
+ const signedTransaction = await getSignedMetaTransactions([metaTransaction], nonce, chainId, user.zkEvm.ethAddress, signer);
11699
+ // TODO: ID-698 Add support for non-native gas payments (e.g ERC20, feeTransaction initialisation must change)
11700
+ // NOTE: "Fee Options" represent the multiple ways we could pay for the gas
11701
+ // used in this transaction. Each fee option has a "recipientAddress" we
11702
+ // should transfer the payment to, an amount and a currency. We choose one
11703
+ // option and build a transaction that sends the expected currency amount for
11704
+ // that option to the specified address.
11705
+ const feeOptions = await relayerClient.imGetFeeOptions(user.zkEvm.ethAddress, signedTransaction);
11706
+ const imxFeeOption = feeOptions.find((feeOption) => feeOption.tokenSymbol === 'IMX');
11707
+ if (!imxFeeOption) {
11708
+ throw new Error('Failed to retrieve fees for IMX token');
11709
+ }
11710
+ const feeMetaTransaction = {
11711
+ nonce,
11712
+ to: imxFeeOption.recipientAddress,
11713
+ value: imxFeeOption.tokenPrice,
11714
+ revertOnError: true,
11715
+ };
11716
+ await guardianClient.validateEVMTransaction({
11717
+ chainId: config.zkEvmChainId,
11718
+ nonce: convertBigNumberishToString(nonce),
11719
+ user,
11720
+ metaTransactions: [metaTransaction, feeMetaTransaction],
11721
+ });
11722
+ // NOTE: We sign again because we now are adding the fee transaction, so the
11723
+ // whole payload is different and needs a new signature.
11724
+ const signedTransactions = await getSignedMetaTransactions([metaTransaction, feeMetaTransaction], nonce, chainId, user.zkEvm.ethAddress, signer);
11725
+ // TODO: ID-697 Evaluate transactions through Guardian
11726
+ const relayerId = await relayerClient.ethSendTransaction(user.zkEvm.ethAddress, signedTransactions);
11727
+ const retrieveRelayerTransaction = async () => {
11728
+ const tx = await relayerClient.imGetTransactionByHash(relayerId);
11729
+ // NOTE: The transaction hash is only available from the Relayer once the
11730
+ // transaction is actually submitted onchain. Hence we need to poll the
11731
+ // Relayer get transaction endpoint until the status transitions to one that
11732
+ // has the hash available.
11733
+ if (tx.status === RelayerTransactionStatus.PENDING) {
11734
+ throw new Error();
11735
+ }
11736
+ return tx;
11737
+ };
11738
+ const relayerTransaction = await retryWithDelay(retrieveRelayerTransaction, {
11739
+ retries: MAX_TRANSACTION_HASH_RETRIEVAL_RETRIES,
11740
+ interval: TRANSACTION_HASH_RETRIEVAL_WAIT,
11741
+ finalErr: new JsonRpcError(RpcErrorCode.RPC_SERVER_ERROR, 'transaction hash not generated in time'),
11742
+ });
11743
+ if (![RelayerTransactionStatus.SUBMITTED, RelayerTransactionStatus.SUCCESSFUL].includes(relayerTransaction.status)) {
11744
+ throw new JsonRpcError(RpcErrorCode.RPC_SERVER_ERROR, `Transaction failed to submit with status ${relayerTransaction.status}`);
11745
+ }
11746
+ return relayerTransaction.hash;
11747
+ };
11748
+
11749
+ class ZkEvmProvider {
11750
+ authManager;
11751
+ config;
11752
+ confirmationScreen;
11753
+ magicAdapter;
11754
+ relayerClient;
11755
+ transactionAPI;
11756
+ multiRollupApiClients;
11757
+ jsonRpcProvider; // Used for read
11758
+ eventEmitter;
11759
+ magicProvider; // Used for signing
11760
+ user;
11761
+ constructor({ authManager, magicAdapter, config, confirmationScreen, multiRollupApiClients, }) {
11762
+ this.authManager = authManager;
11763
+ this.magicAdapter = magicAdapter;
11764
+ this.config = config;
11765
+ this.confirmationScreen = confirmationScreen;
11766
+ this.relayerClient = new RelayerClient({ config });
11767
+ this.transactionAPI = new TransactionsApi(new Configuration({
11768
+ basePath: this.config.imxPublicApiDomain,
11769
+ }));
11770
+ this.jsonRpcProvider = new JsonRpcProvider(this.config.zkEvmRpcUrl);
11771
+ this.multiRollupApiClients = multiRollupApiClients;
11772
+ this.eventEmitter = new TypedEventEmitter();
11773
+ }
11774
+ isLoggedIn() {
11775
+ return this.magicProvider !== undefined && this.user !== undefined;
11776
+ }
11777
+ async performRequest(request) {
11778
+ switch (request.method) {
11779
+ case 'eth_requestAccounts': {
11780
+ if (this.isLoggedIn()) {
11781
+ return [this.user.zkEvm.ethAddress];
11782
+ }
11783
+ const { magicProvider, user } = await loginZkEvmUser({
11784
+ authManager: this.authManager,
11785
+ config: this.config,
11786
+ magicAdapter: this.magicAdapter,
11787
+ multiRollupApiClients: this.multiRollupApiClients,
11788
+ });
11789
+ this.user = user;
11790
+ this.magicProvider = magicProvider;
11791
+ this.eventEmitter.emit(ProviderEvent.ACCOUNTS_CHANGED, [this.user.zkEvm.ethAddress]);
11792
+ return [this.user.zkEvm.ethAddress];
11793
+ }
11794
+ case 'eth_sendTransaction': {
11795
+ if (!this.isLoggedIn()) {
11796
+ throw new JsonRpcError(ProviderErrorCode.UNAUTHORIZED, 'Unauthorised - call eth_requestAccounts first');
11797
+ }
11798
+ const guardianClient = new GuardianClient({
11799
+ imxPublicApiDomain: this.config.imxPublicApiDomain,
11800
+ accessToken: this.user.accessToken,
11801
+ confirmationScreen: this.confirmationScreen,
11802
+ imxEtherAddress: this.user?.imx?.ethAddress || '',
11803
+ });
11804
+ return sendTransaction({
11805
+ params: request.params || [],
11806
+ magicProvider: this.magicProvider,
11807
+ guardianClient,
11808
+ jsonRpcProvider: this.jsonRpcProvider,
11809
+ config: this.config,
11810
+ relayerClient: this.relayerClient,
11811
+ user: this.user,
11812
+ });
11813
+ }
11814
+ case 'eth_accounts': {
11815
+ return this.isLoggedIn() ? [this.user.zkEvm.ethAddress] : [];
11816
+ }
11817
+ // Pass through methods
11818
+ case 'eth_gasPrice':
11819
+ case 'eth_getBalance':
11820
+ case 'eth_getStorageAt':
11821
+ case 'eth_estimateGas':
11822
+ case 'eth_call':
11823
+ case 'eth_blockNumber':
11824
+ case 'eth_chainId':
11825
+ case 'eth_getBlockByHash':
11826
+ case 'eth_getBlockByNumber':
11827
+ case 'eth_getTransactionByHash':
11828
+ case 'eth_getTransactionReceipt':
11829
+ case 'eth_getTransactionCount': {
11830
+ return this.jsonRpcProvider.send(request.method, request.params || []);
11831
+ }
11832
+ default: {
11833
+ throw new JsonRpcError(ProviderErrorCode.UNSUPPORTED_METHOD, 'Method not supported');
11834
+ }
11835
+ }
11836
+ }
11837
+ async performJsonRpcRequest(request) {
11838
+ const { id, jsonrpc } = request;
11839
+ try {
11840
+ const result = await this.performRequest(request);
11841
+ return {
11842
+ id,
11843
+ jsonrpc,
11844
+ result,
11845
+ };
11846
+ }
11847
+ catch (error) {
11848
+ let jsonRpcError;
11849
+ if (error instanceof JsonRpcError) {
11850
+ jsonRpcError = error;
11851
+ }
11852
+ else if (error instanceof Error) {
11853
+ jsonRpcError = new JsonRpcError(RpcErrorCode.INTERNAL_ERROR, error.message);
11854
+ }
11855
+ else {
11856
+ jsonRpcError = new JsonRpcError(RpcErrorCode.INTERNAL_ERROR, 'Internal error');
11857
+ }
11858
+ return {
11859
+ id,
11860
+ jsonrpc,
11861
+ error: jsonRpcError,
11862
+ };
11863
+ }
11864
+ }
11865
+ async request(request) {
11866
+ try {
11867
+ return this.performRequest(request);
11868
+ }
11869
+ catch (error) {
11870
+ if (error instanceof JsonRpcError) {
11871
+ throw error;
11872
+ }
11873
+ if (error instanceof Error) {
11874
+ throw new JsonRpcError(RpcErrorCode.INTERNAL_ERROR, error.message);
11875
+ }
11876
+ throw new JsonRpcError(RpcErrorCode.INTERNAL_ERROR, 'Internal error');
11877
+ }
11878
+ }
11879
+ sendAsync(request, callback) {
11880
+ if (!callback) {
11881
+ throw new Error('No callback provided');
11882
+ }
11883
+ if (Array.isArray(request)) {
11884
+ Promise.all(request.map(this.performJsonRpcRequest)).then((result) => {
11885
+ callback(null, result);
11886
+ }).catch((error) => {
11887
+ callback(error, []);
11888
+ });
11889
+ }
11890
+ else {
11891
+ this.performJsonRpcRequest(request).then((result) => {
11892
+ callback(null, result);
11893
+ }).catch((error) => {
11894
+ callback(error, null);
11895
+ });
11896
+ }
11897
+ }
11898
+ async send(request, callbackOrParams, callback) {
11899
+ // Web3 >= 1.0.0-beta.38 calls `send` with method and parameters.
11900
+ if (typeof request === 'string') {
11901
+ if (typeof callbackOrParams === 'function') {
11902
+ return this.sendAsync({
11903
+ method: request,
11904
+ params: [],
11905
+ }, callbackOrParams);
11906
+ }
11907
+ if (callback) {
11908
+ return this.sendAsync({
11909
+ method: request,
11910
+ params: Array.isArray(callbackOrParams) ? callbackOrParams : [],
11911
+ }, callback);
11912
+ }
11913
+ return this.request({
11914
+ method: request,
11915
+ params: Array.isArray(callbackOrParams) ? callbackOrParams : [],
11916
+ });
11917
+ }
11918
+ // Web3 <= 1.0.0-beta.37 uses `send` with a callback for async queries.
11919
+ if (typeof callbackOrParams === 'function') {
11920
+ return this.sendAsync(request, callbackOrParams);
11921
+ }
11922
+ if (!Array.isArray(request) && typeof request === 'object') {
11923
+ return this.performJsonRpcRequest(request);
11924
+ }
11925
+ throw new JsonRpcError(RpcErrorCode.INVALID_REQUEST, 'Invalid request');
11926
+ }
11927
+ on(event, listener) {
11928
+ this.eventEmitter.on(event, listener);
11929
+ }
11930
+ removeListener(event, listener) {
11931
+ this.eventEmitter.removeListener(event, listener);
11932
+ }
11933
+ }
11934
+
7863
11935
  class Passport {
7864
11936
  authManager;
7865
11937
  config;
@@ -7867,6 +11939,7 @@ class Passport {
7867
11939
  immutableXClient;
7868
11940
  magicAdapter;
7869
11941
  passportImxProviderFactory;
11942
+ multiRollupApiClients;
7870
11943
  constructor(passportModuleConfiguration) {
7871
11944
  this.config = new PassportConfiguration(passportModuleConfiguration);
7872
11945
  this.authManager = new AuthManager(this.config);
@@ -7876,6 +11949,7 @@ class Passport {
7876
11949
  || new ImmutableXClient({
7877
11950
  baseConfig: passportModuleConfiguration.baseConfig,
7878
11951
  });
11952
+ this.multiRollupApiClients = new MultiRollupApiClients(this.config.multiRollupConfig);
7879
11953
  this.passportImxProviderFactory = new PassportImxProviderFactory({
7880
11954
  authManager: this.authManager,
7881
11955
  config: this.config,
@@ -7896,6 +11970,12 @@ class Passport {
7896
11970
  async connectImxDeviceFlow(deviceCode, interval, timeoutMs) {
7897
11971
  return this.passportImxProviderFactory.getProviderWithDeviceFlow(deviceCode, interval, timeoutMs);
7898
11972
  }
11973
+ getPKCEAuthorizationUrl() {
11974
+ return this.authManager.getPKCEAuthorizationUrl();
11975
+ }
11976
+ async connectImxPKCEFlow(authorizationCode, state) {
11977
+ return this.passportImxProviderFactory.getProviderWithPKCEFlow(authorizationCode, state);
11978
+ }
7899
11979
  /**
7900
11980
  * @returns {boolean} the stored device flow credentials if they exist
7901
11981
  */
@@ -7905,12 +11985,29 @@ class Passport {
7905
11985
  async connectImxWithCredentials(tokenResponse) {
7906
11986
  return this.passportImxProviderFactory.getProviderWithCredentials(tokenResponse);
7907
11987
  }
11988
+ // TODO ID-926 Make method public once development has been finalised
11989
+ connectEvm() {
11990
+ return new ZkEvmProvider({
11991
+ authManager: this.authManager,
11992
+ magicAdapter: this.magicAdapter,
11993
+ config: this.config,
11994
+ confirmationScreen: this.confirmationScreen,
11995
+ multiRollupApiClients: this.multiRollupApiClients,
11996
+ });
11997
+ }
7908
11998
  async loginCallback() {
7909
11999
  return this.authManager.loginCallback();
7910
12000
  }
7911
12001
  async logout() {
7912
12002
  return this.authManager.logout();
7913
12003
  }
12004
+ /**
12005
+ * This method should only be called from the logout redirect uri
12006
+ * when logout mode is 'silent'.
12007
+ */
12008
+ async logoutSilentCallback(url) {
12009
+ return this.authManager.logoutSilentCallback(url);
12010
+ }
7914
12011
  async logoutDeviceFlow() {
7915
12012
  return this.authManager.logoutDeviceFlow();
7916
12013
  }
@@ -8211,7 +12308,7 @@ const getRequestBody = (options) => {
8211
12308
  return undefined;
8212
12309
  };
8213
12310
  const sendRequest = async (config, options, url, body, formData, headers, onCancel) => {
8214
- const source = globalAxios$1.CancelToken.source();
12311
+ const source = axios$2.CancelToken.source();
8215
12312
  const requestConfig = {
8216
12313
  url,
8217
12314
  headers,
@@ -8222,7 +12319,7 @@ const sendRequest = async (config, options, url, body, formData, headers, onCanc
8222
12319
  };
8223
12320
  onCancel(() => source.cancel('The user aborted a request.'));
8224
12321
  try {
8225
- return await globalAxios$1.request(requestConfig);
12322
+ return await axios$2.request(requestConfig);
8226
12323
  }
8227
12324
  catch (error) {
8228
12325
  const axiosError = error;
@@ -8827,31 +12924,25 @@ class ImmutableApiClientFactory {
8827
12924
  }
8828
12925
  }
8829
12926
 
8830
- const DEVNET_CHAIN_NAME = 'imtbl-zkevm-devnet';
8831
12927
  const TESTNET_CHAIN_NAME = 'imtbl-zkevm-testnet';
8832
12928
  const MAINNET_CHAIN_NAME = 'imtbl-zkevm-mainnet';
8833
- function getOrderbookConfig(chainName) {
8834
- switch (chainName) {
8835
- case DEVNET_CHAIN_NAME:
12929
+ function getOrderbookConfig(environment) {
12930
+ switch (environment) {
12931
+ case Environment$1.SANDBOX:
8836
12932
  return {
8837
- seaportContractAddress: '0x41388404Efb7a68Fd31d75CEf71dF91e2BDBa2fb',
8838
- zoneContractAddress: '0xCb5063b0c1dcF4f7fed8E7eaa79faf9859792767',
8839
- apiEndpoint: 'https://order-book-mr.dev.imtbl.com',
8840
- provider: new providers.JsonRpcProvider('https://zkevm-rpc.dev.x.immutable.com'),
8841
- };
8842
- case TESTNET_CHAIN_NAME:
8843
- return {
8844
- seaportContractAddress: '0x45E23dA18804F99Cf67408AeBE85F67c958381Ff',
8845
- zoneContractAddress: '0x25b00b7eb97eab6194798E9B8eF63Aa526D5bd7E',
12933
+ seaportContractAddress: '0x474989C4D25DD41B0B9b1ECb4643B9Fe25f83B19',
12934
+ zoneContractAddress: '0x6FeDb4949E5b452700A8a8956999a7E05B6770F3',
8846
12935
  apiEndpoint: 'https://order-book-mr.sandbox.imtbl.com',
12936
+ chainName: TESTNET_CHAIN_NAME,
8847
12937
  provider: new providers.JsonRpcProvider('https://zkevm-rpc.sandbox.x.immutable.com'),
8848
12938
  };
8849
- case MAINNET_CHAIN_NAME:
8850
- // not yet deployed
12939
+ // not yet deployed
12940
+ case Environment$1.PRODUCTION:
8851
12941
  return {
8852
12942
  seaportContractAddress: '',
8853
12943
  zoneContractAddress: '',
8854
12944
  apiEndpoint: 'https://order-book-mr.imtbl.com',
12945
+ chainName: MAINNET_CHAIN_NAME,
8855
12946
  provider: new providers.JsonRpcProvider('https://zkevm-rpc.x.immutable.com'),
8856
12947
  };
8857
12948
  default:
@@ -9764,7 +13855,7 @@ const _abi$3 = [
9764
13855
  class ImmutableERC721Base__factory {
9765
13856
  static abi = _abi$3;
9766
13857
  static createInterface() {
9767
- return new utils$1.Interface(_abi$3);
13858
+ return new utils$2.Interface(_abi$3);
9768
13859
  }
9769
13860
  static connect(address, signerOrProvider) {
9770
13861
  return new Contract$1(address, _abi$3, signerOrProvider);
@@ -9810,21 +13901,19 @@ class Orderbook {
9810
13901
  apiClient;
9811
13902
  seaport;
9812
13903
  orderbookConfig;
9813
- constructor(config, localConfig) {
9814
- // either use preconfigured config or local config passed in
9815
- const maybeConfig = getOrderbookConfig(config.overrides?.chainName) || localConfig;
9816
- if (!maybeConfig) {
9817
- throw new Error('Orderbook configuration not passed, either select one of the preseet chainNames or pass in localConfig');
9818
- }
9819
- this.orderbookConfig = maybeConfig;
9820
- const { apiEndpoint } = this.orderbookConfig;
9821
- if (!apiEndpoint) {
9822
- throw new Error('API endpoint must be provided as an override');
13904
+ constructor(config) {
13905
+ const obConfig = getOrderbookConfig(config.baseConfig.environment);
13906
+ const finalConfig = {
13907
+ ...obConfig,
13908
+ ...config.overrides,
13909
+ };
13910
+ if (!finalConfig) {
13911
+ throw new Error('Orderbook configuration not passed, please specify the environment under config.baseConfig.environment');
9823
13912
  }
9824
- // TODO: Move chainId lookup to a map based on env. Just using override to get dev started
9825
- const chainName = config.overrides?.chainName;
9826
- if (!chainName) {
9827
- throw new Error('chainName must be provided as an override');
13913
+ this.orderbookConfig = finalConfig;
13914
+ const { apiEndpoint, chainName } = this.orderbookConfig;
13915
+ if (!apiEndpoint) {
13916
+ throw new Error('API endpoint must be provided');
9828
13917
  }
9829
13918
  this.apiClient = new ImmutableApiClientFactory(apiEndpoint, chainName, this.orderbookConfig.seaportContractAddress).create();
9830
13919
  const seaportLibFactory = new SeaportLibFactory(this.orderbookConfig.seaportContractAddress, this.orderbookConfig.provider);
@@ -21159,7 +25248,7 @@ const ETH_MAINNET_CHAIN_ID = 'eip155:1';
21159
25248
  /**
21160
25249
  * @constant {string} ZKEVM_DEVNET_CHAIN_ID - The chain ID for the zkEVM devnet (EIP-155 compatible format).
21161
25250
  */
21162
- const ZKEVM_DEVNET_CHAIN_ID = 'eip155:13403';
25251
+ const ZKEVM_DEVNET_CHAIN_ID = 'eip155:13423';
21163
25252
  /**
21164
25253
  /**
21165
25254
  * @constant {string} ZKEVM_TESTNET_CHAIN_ID - The chain ID for the zkEVM testnet (EIP-155 compatible format).
@@ -21217,14 +25306,14 @@ const SUPPORTED_BRIDGES_FOR_ENVIRONMENT = {
21217
25306
  */
21218
25307
  const CONTRACTS_FOR_BRIDGE = new Map()
21219
25308
  .set(ETH_SEPOLIA_TO_ZKEVM_DEVNET, {
21220
- rootChainERC20Predicate: '0x15Dd735de418B6d290727aed82cC25F8966dE4A5',
21221
- rootChainStateSender: '0xb3Bac13799dAca9D9eC9307303a65fA1218b4724',
25309
+ rootChainERC20Predicate: '0xf0b3435411A74F1aeCBD0fd6D53a90D5227fEeba',
25310
+ rootChainStateSender: '0x868097dbAcfD431F441d09D0e4D3B5eD3182E597',
21222
25311
  childChainERC20Predicate: '0x0000000000000000000000000000000000001004',
21223
25312
  childChainStateReceiver: '0x0000000000000000000000000000000000001001',
21224
25313
  })
21225
25314
  .set(ETH_SEPOLIA_TO_ZKEVM_TESTNET, {
21226
- rootChainERC20Predicate: '0x9A7E4C4337a70C6754a9672F5ba69084463794B8',
21227
- rootChainStateSender: '0xfBfF6FD165adFA113bE39eE85ef030A996153253',
25315
+ rootChainERC20Predicate: '0x0C15a8359865867CdCC44f98b2F3fd5DF098C7E0',
25316
+ rootChainStateSender: '0x4C80001188db53dbc2eaAb32d5ef825feEedECA5',
21228
25317
  childChainERC20Predicate: '0x0000000000000000000000000000000000001004',
21229
25318
  childChainStateReceiver: '0x0000000000000000000000000000000000001001',
21230
25319
  })
@@ -21645,7 +25734,7 @@ const _abi$2 = [
21645
25734
  let ERC20__factory$1 = class ERC20__factory {
21646
25735
  static abi = _abi$2;
21647
25736
  static createInterface() {
21648
- return new utils$1.Interface(_abi$2);
25737
+ return new utils$2.Interface(_abi$2);
21649
25738
  }
21650
25739
  static connect(address, signerOrProvider) {
21651
25740
  return new Contract$1(address, _abi$2, signerOrProvider);
@@ -21816,7 +25905,7 @@ function getQuote(otherCurrency, tradeType, tradeInfo, slippage) {
21816
25905
  }
21817
25906
 
21818
25907
  const IMMUTABLE_TESTNET_RPC_URL = 'https://zkevm-rpc.sandbox.x.immutable.com';
21819
- const IMMUTABLE_TESTNET_CHAIN_ID = 13392;
25908
+ const IMMUTABLE_TESTNET_CHAIN_ID = 13372;
21820
25909
 
21821
25910
  const TIMX_IMMUTABLE_TESTNET = {
21822
25911
  chainId: IMMUTABLE_TESTNET_CHAIN_ID,
@@ -22013,7 +26102,7 @@ class Multicall__factory extends ContractFactory {
22013
26102
  static bytecode = _bytecode$1$1;
22014
26103
  static abi = _abi$1$1;
22015
26104
  static createInterface() {
22016
- return new utils$1.Interface(_abi$1$1);
26105
+ return new utils$2.Interface(_abi$1$1);
22017
26106
  }
22018
26107
  static connect(address, signerOrProvider) {
22019
26108
  return new Contract$1(address, _abi$1$1, signerOrProvider);
@@ -23037,7 +27126,7 @@ class UniswapV3Pool__factory extends ContractFactory {
23037
27126
  static bytecode = _bytecode;
23038
27127
  static abi = _abi;
23039
27128
  static createInterface() {
23040
- return new utils$1.Interface(_abi);
27129
+ return new utils$2.Interface(_abi);
23041
27130
  }
23042
27131
  static connect(address, signerOrProvider) {
23043
27132
  return new Contract$1(address, _abi, signerOrProvider);
@@ -23455,16 +27544,28 @@ const SUPPORTED_CHAIN_IDS_FOR_ENVIRONMENT = {
23455
27544
  [Environment$1.PRODUCTION]: SUPPORTED_PRODUCTION_CHAINS,
23456
27545
  };
23457
27546
  function validateOverrides(overrides) {
23458
- Object.entries(overrides).forEach(([key, value]) => {
23459
- if (!value) {
27547
+ const keysToCheck = ['rpcURL', 'exchangeContracts', 'commonRoutingTokens', 'nativeToken'];
27548
+ for (const key of keysToCheck) {
27549
+ if (!overrides[key]) {
23460
27550
  throw new InvalidConfigurationError(`Missing override: ${key}`);
23461
27551
  }
23462
- });
27552
+ }
23463
27553
  Object.entries(overrides.exchangeContracts).forEach(([key, contract]) => {
23464
27554
  if (!isValidNonZeroAddress(contract)) {
23465
27555
  throw new InvalidConfigurationError(`Invalid exchange contract address for ${key}`);
23466
27556
  }
23467
27557
  });
27558
+ if (!overrides.secondaryFees) {
27559
+ return;
27560
+ }
27561
+ for (const secondaryFee of overrides.secondaryFees) {
27562
+ if (!isValidNonZeroAddress(secondaryFee.feeRecipient)) {
27563
+ throw new InvalidConfigurationError(`Invalid secondary fee recipient address: ${secondaryFee.feeRecipient}`);
27564
+ }
27565
+ if (secondaryFee.feeBasisPoints < 0 || secondaryFee.feeBasisPoints > 10000) {
27566
+ throw new InvalidConfigurationError(`Invalid secondary fee percentage: ${secondaryFee.feeBasisPoints}`);
27567
+ }
27568
+ }
23468
27569
  }
23469
27570
  /**
23470
27571
  * {@link ExchangeConfiguration} is used to configure the {@link Exchange} class.
@@ -23474,6 +27575,7 @@ function validateOverrides(overrides) {
23474
27575
  class ExchangeConfiguration {
23475
27576
  baseConfig;
23476
27577
  chain;
27578
+ secondaryFees;
23477
27579
  constructor({ chainId, baseConfig, overrides }) {
23478
27580
  this.baseConfig = baseConfig;
23479
27581
  if (overrides) {
@@ -23485,8 +27587,10 @@ class ExchangeConfiguration {
23485
27587
  commonRoutingTokens: overrides.commonRoutingTokens,
23486
27588
  nativeToken: overrides.nativeToken,
23487
27589
  };
27590
+ this.secondaryFees = overrides.secondaryFees ? overrides.secondaryFees : [];
23488
27591
  return;
23489
27592
  }
27593
+ this.secondaryFees = [];
23490
27594
  const chain = SUPPORTED_CHAIN_IDS_FOR_ENVIRONMENT[baseConfig.environment][chainId];
23491
27595
  if (!chain) {
23492
27596
  throw new ChainNotSupportedError(chainId, baseConfig.environment);
@@ -23500,11 +27604,13 @@ class Exchange {
23500
27604
  router;
23501
27605
  chainId;
23502
27606
  nativeToken;
27607
+ secondaryFees;
23503
27608
  constructor(configuration) {
23504
27609
  const config = new ExchangeConfiguration(configuration);
23505
27610
  this.chainId = config.chain.chainId;
23506
27611
  this.nativeToken = config.chain.nativeToken;
23507
27612
  this.provider = new ethers.providers.JsonRpcProvider(config.chain.rpcUrl);
27613
+ this.secondaryFees = config.secondaryFees;
23508
27614
  this.router = new Router(this.provider, config.chain.commonRoutingTokens, {
23509
27615
  multicallAddress: config.chain.contracts.multicall,
23510
27616
  factoryAddress: config.chain.contracts.coreFactory,
@@ -23587,6 +27693,9 @@ class Exchange {
23587
27693
  async getUnsignedSwapTxFromAmountOut(fromAddress, tokenInAddress, tokenOutAddress, amountOut, slippagePercent = DEFAULT_SLIPPAGE, maxHops = DEFAULT_MAX_HOPS, deadline = DEFAULT_DEADLINE) {
23588
27694
  return await this.getUnsignedSwapTx(fromAddress, tokenInAddress, tokenOutAddress, amountOut, slippagePercent, maxHops, deadline, TradeType.EXACT_OUTPUT);
23589
27695
  }
27696
+ thereAreSecondaryFees() {
27697
+ return this.secondaryFees.length > 0;
27698
+ }
23590
27699
  }
23591
27700
 
23592
27701
  /* eslint-disable class-methods-use-this */
@@ -23663,8 +27772,8 @@ const $762782b6c862d954$export$db5daa1b5156ccfe = [
23663
27772
  */ var $0472f23319457bfb$export$c06e1e7429de6283;
23664
27773
  (function(ChainId) {
23665
27774
  ChainId[ChainId["IMTBL_ZKEVM_MAINNET"] = 13371] = "IMTBL_ZKEVM_MAINNET";
23666
- ChainId[ChainId["IMTBL_ZKEVM_TESTNET"] = 13392] = "IMTBL_ZKEVM_TESTNET";
23667
- ChainId[ChainId["IMTBL_ZKEVM_DEVNET"] = 13403] = "IMTBL_ZKEVM_DEVNET";
27775
+ ChainId[ChainId["IMTBL_ZKEVM_TESTNET"] = 13372] = "IMTBL_ZKEVM_TESTNET";
27776
+ ChainId[ChainId["IMTBL_ZKEVM_DEVNET"] = 13423] = "IMTBL_ZKEVM_DEVNET";
23668
27777
  ChainId[ChainId["ETHEREUM"] = 1] = "ETHEREUM";
23669
27778
  ChainId[ChainId["SEPOLIA"] = 11155111] = "SEPOLIA";
23670
27779
  })($0472f23319457bfb$export$c06e1e7429de6283 || ($0472f23319457bfb$export$c06e1e7429de6283 = {}));
@@ -23749,6 +27858,10 @@ const $d85ad1457a3f1a83$export$161d4a74df65fc08 = {
23749
27858
  [(Environment$1).SANDBOX]: "https://checkout-api.sandbox.immutable.com",
23750
27859
  [(Environment$1).PRODUCTION]: "https://checkout-api.immutable.com"
23751
27860
  };
27861
+ const $d85ad1457a3f1a83$export$7b057be2a3f512cc = {
27862
+ [(Environment$1).SANDBOX]: "https://zkevm-rpc.sandbox.x.immutable.com",
27863
+ [(Environment$1).PRODUCTION]: "https://zkevm-rpc.x.immutable.com"
27864
+ };
23752
27865
  const $d85ad1457a3f1a83$export$6f24f3cef7d501c4 = new Map([
23753
27866
  [
23754
27867
  ($0472f23319457bfb$export$c06e1e7429de6283).ETHEREUM,
@@ -23774,7 +27887,7 @@ const $d85ad1457a3f1a83$export$6f24f3cef7d501c4 = new Map([
23774
27887
  chainIdHex: `0x${($0472f23319457bfb$export$c06e1e7429de6283).IMTBL_ZKEVM_MAINNET.toString(16)}`,
23775
27888
  chainName: ($0472f23319457bfb$export$b874c6b1dfe85e02).IMTBL_ZKEVM_MAINNET,
23776
27889
  rpcUrls: [
23777
- "https://zkevm-rpc.x.immutable.com"
27890
+ "https://rpc.immutable.com"
23778
27891
  ],
23779
27892
  nativeCurrency: {
23780
27893
  name: "IMX",
@@ -23809,7 +27922,7 @@ const $d85ad1457a3f1a83$export$3e81fc0987227f10 = new Map([
23809
27922
  chainIdHex: `0x${($0472f23319457bfb$export$c06e1e7429de6283).IMTBL_ZKEVM_TESTNET.toString(16)}`,
23810
27923
  chainName: ($0472f23319457bfb$export$b874c6b1dfe85e02).IMTBL_ZKEVM_TESTNET,
23811
27924
  rpcUrls: [
23812
- "https://zkevm-rpc.sandbox.x.immutable.com"
27925
+ "https://rpc.testnet.immutable.com"
23813
27926
  ],
23814
27927
  nativeCurrency: {
23815
27928
  name: "IMX",
@@ -24085,7 +28198,7 @@ const $1564e43dde50bb61$export$df96cd8d56be0ab1 = async (config, web3Provider, w
24085
28198
  const balance = await web3Provider.getBalance(walletAddress);
24086
28199
  return {
24087
28200
  balance: balance,
24088
- formattedBalance: (utils$1).formatUnits(balance, networkInfo.nativeCurrency.decimals),
28201
+ formattedBalance: (utils$2).formatUnits(balance, networkInfo.nativeCurrency.decimals),
24089
28202
  token: networkInfo.nativeCurrency
24090
28203
  };
24091
28204
  }, {
@@ -24098,7 +28211,7 @@ async function $1564e43dde50bb61$export$60e0fe116a0e6ed0(web3Provider, walletAdd
24098
28211
  const symbol = await contract.symbol();
24099
28212
  const balance = await contract.balanceOf(walletAddress);
24100
28213
  const decimals = await contract.decimals();
24101
- const formattedBalance = (utils$1).formatUnits(balance, decimals);
28214
+ const formattedBalance = (utils$2).formatUnits(balance, decimals);
24102
28215
  return {
24103
28216
  balance: balance,
24104
28217
  formattedBalance: formattedBalance,
@@ -24185,16 +28298,19 @@ async function $5c763be0b0b81038$var$getMetaMaskProvider() {
24185
28298
  if (!provider || !provider.request) throw new ($a8bc256d81a5e2c1$export$b722478a3cbfa3bc)("No MetaMask provider installed.", ($a8bc256d81a5e2c1$export$e3dc0620abde7f5a).METAMASK_PROVIDER_ERROR);
24186
28299
  return new (Web3Provider)(provider);
24187
28300
  }
24188
- async function $5c763be0b0b81038$export$500fbc0cd14cdbaa(defaultProvider) {
24189
- let web3Provider = null;
24190
- switch(defaultProvider){
28301
+ async function $5c763be0b0b81038$export$500fbc0cd14cdbaa(walletProviderName) {
28302
+ let provider = null;
28303
+ switch(walletProviderName){
24191
28304
  case ($e768639828688ca3$export$2d7a51a18d87e21d).METAMASK:
24192
- web3Provider = await $5c763be0b0b81038$var$getMetaMaskProvider();
28305
+ provider = await $5c763be0b0b81038$var$getMetaMaskProvider();
24193
28306
  break;
24194
28307
  default:
24195
28308
  throw new ($a8bc256d81a5e2c1$export$b722478a3cbfa3bc)("Provider not supported", ($a8bc256d81a5e2c1$export$e3dc0620abde7f5a).DEFAULT_PROVIDER_ERROR);
24196
28309
  }
24197
- return web3Provider;
28310
+ return {
28311
+ provider: provider,
28312
+ walletProviderName: walletProviderName
28313
+ };
24198
28314
  }
24199
28315
 
24200
28316
 
@@ -24203,9 +28319,8 @@ async function $5c763be0b0b81038$export$500fbc0cd14cdbaa(defaultProvider) {
24203
28319
 
24204
28320
 
24205
28321
 
24206
-
24207
28322
  function $bb88265fe45a0393$export$ebe4804963e71f98(web3Provider) {
24208
- if (web3Provider && web3Provider instanceof (Web3Provider) && web3Provider.provider?.request) return true;
28323
+ if (web3Provider && web3Provider.provider?.request && typeof web3Provider.provider.request === "function") return true;
24209
28324
  return false;
24210
28325
  }
24211
28326
  async function $bb88265fe45a0393$export$9e1fd9cc88c637a0(config, web3Provider, validateProviderOptions) {
@@ -24370,7 +28485,7 @@ class $a492ee374ae7b613$export$d902b56530cd5f87 {
24370
28485
  static async makeHttpRequest(url) {
24371
28486
  let response;
24372
28487
  try {
24373
- response = await (0, globalAxios$1).get(url);
28488
+ response = await (0, axios$2).get(url);
24374
28489
  } catch (error) {
24375
28490
  throw new Error(`Error fetching from api: ${error.message}`);
24376
28491
  }
@@ -24415,10 +28530,23 @@ class $4013c5c91bb535f6$export$6ad73ea7e1b6f37f extends Error {
24415
28530
  this.message = message;
24416
28531
  }
24417
28532
  }
24418
- const $4013c5c91bb535f6$var$networkMap = (prod, dev)=>{
24419
- if (dev) return $d85ad1457a3f1a83$export$3a9ebede6a150274;
24420
- if (prod) return $d85ad1457a3f1a83$export$6f24f3cef7d501c4;
24421
- return $d85ad1457a3f1a83$export$3e81fc0987227f10;
28533
+ const $4013c5c91bb535f6$var$networkMap = (prod, dev, local)=>{
28534
+ let networks;
28535
+ if (dev) networks = ($d85ad1457a3f1a83$export$3a9ebede6a150274);
28536
+ else if (prod) {
28537
+ networks = ($d85ad1457a3f1a83$export$6f24f3cef7d501c4);
28538
+ if (local) {
28539
+ const rpcUrls = networks.get(($0472f23319457bfb$export$c06e1e7429de6283).IMTBL_ZKEVM_MAINNET)?.rpcUrls;
28540
+ rpcUrls?.splice(0, 1, ($d85ad1457a3f1a83$export$7b057be2a3f512cc)[(Environment$1).PRODUCTION]);
28541
+ }
28542
+ } else {
28543
+ networks = ($d85ad1457a3f1a83$export$3e81fc0987227f10);
28544
+ if (local) {
28545
+ const rpcUrls = networks.get(($0472f23319457bfb$export$c06e1e7429de6283).IMTBL_ZKEVM_TESTNET)?.rpcUrls;
28546
+ rpcUrls?.splice(0, 1, ($d85ad1457a3f1a83$export$7b057be2a3f512cc)[(Environment$1).SANDBOX]);
28547
+ }
28548
+ }
28549
+ return networks;
24422
28550
  };
24423
28551
  const $4013c5c91bb535f6$export$9b794d067cdd1af6 = (config)=>{
24424
28552
  // DevMode and Sandbox will both use Sepolia.
@@ -24436,6 +28564,11 @@ class $4013c5c91bb535f6$export$4823433c4a67bbc6 {
24436
28564
  // This will be used to get around the lack of
24437
28565
  // Environment.DEVELOPMENT
24438
28566
  isDevelopment = false;
28567
+ // This is a hidden feature that is only available
28568
+ // when building the project from source code.
28569
+ // This will be used to get around the lack of
28570
+ // Environment.LOCAL_DEVELOPMENT
28571
+ isLocal = false;
24439
28572
  isProduction;
24440
28573
  remote;
24441
28574
  environment;
@@ -24445,7 +28578,7 @@ class $4013c5c91bb535f6$export$4823433c4a67bbc6 {
24445
28578
  this.environment = config.baseConfig.environment;
24446
28579
  // Developer mode will super set any environment configuration
24447
28580
  this.isProduction = !this.isDevelopment && this.environment === (Environment$1).PRODUCTION;
24448
- this.networkMap = $4013c5c91bb535f6$var$networkMap(this.isProduction, this.isDevelopment);
28581
+ this.networkMap = $4013c5c91bb535f6$var$networkMap(this.isProduction, this.isDevelopment, this.isLocal);
24449
28582
  this.remote = new ($a492ee374ae7b613$export$d902b56530cd5f87)({
24450
28583
  isDevelopment: this.isDevelopment,
24451
28584
  isProduction: this.isProduction
@@ -24509,7 +28642,7 @@ async function $2e7bf45a7c9a9570$var$swapGasEstimator(config) {
24509
28642
  try {
24510
28643
  const exchange = await $67fc622a2b913d5f$export$7cf6178417769841(chainId, config);
24511
28644
  // Create a fake transaction to get the gas from the quote
24512
- const { swap: swap } = await exchange.getUnsignedSwapTxFromAmountIn($2e7bf45a7c9a9570$var$DUMMY_WALLET_ADDRESS, inAddress, outAddress, (0, BigNumber$1).from((0, utils$1).parseUnits("1", $2e7bf45a7c9a9570$var$DEFAULT_TOKEN_DECIMALS)));
28645
+ const { swap: swap } = await exchange.getUnsignedSwapTxFromAmountIn($2e7bf45a7c9a9570$var$DUMMY_WALLET_ADDRESS, inAddress, outAddress, (0, BigNumber$1).from((0, utils$2).parseUnits("1", $2e7bf45a7c9a9570$var$DEFAULT_TOKEN_DECIMALS)));
24513
28646
  if (swap.gasFeeEstimate === null) return {
24514
28647
  gasEstimateType: (0, $de275b98d2b651c3$export$788b1fd17f3dad84).SWAP,
24515
28648
  gasFee: {}
@@ -24591,10 +28724,7 @@ class $a8cb37a3fc8eb863$export$1f60ba4ec72508a0 {
24591
28724
  * @param {CreateProviderParams} params - The parameters for creating the provider.
24592
28725
  * @returns {Promise<CreateProviderResult>} A promise that resolves to the created provider.
24593
28726
  */ async createProvider(params) {
24594
- const web3Provider = await $5c763be0b0b81038$export$500fbc0cd14cdbaa(params.walletProvider);
24595
- return {
24596
- provider: web3Provider
24597
- };
28727
+ return await $5c763be0b0b81038$export$500fbc0cd14cdbaa(params.walletProvider);
24598
28728
  }
24599
28729
  /**
24600
28730
  * Checks if a wallet is connected to the specified provider.
@@ -24711,7 +28841,7 @@ class $a8cb37a3fc8eb863$export$1f60ba4ec72508a0 {
24711
28841
  function $parcel$export(e, n, v, s) {
24712
28842
  Object.defineProperty(e, n, {get: v, set: s, enumerable: true, configurable: true});
24713
28843
  }
24714
- const $d663162fd5a0853f$export$38a083d9fb5551ca = "0.4.0-alpha.2";
28844
+ const $d663162fd5a0853f$export$38a083d9fb5551ca = "0.4.1-alpha";
24715
28845
  const $d663162fd5a0853f$export$83bf90b30cdfd29f = ()=>false;
24716
28846
  const $d663162fd5a0853f$export$1169f5475725171b = ()=>$d663162fd5a0853f$export$38a083d9fb5551ca;
24717
28847
 
@@ -25297,7 +29427,7 @@ class ERC20__factory extends ContractFactory {
25297
29427
  static bytecode = _bytecode$2;
25298
29428
  static abi = _abi$4;
25299
29429
  static createInterface() {
25300
- return new utils$1.Interface(_abi$4);
29430
+ return new utils$2.Interface(_abi$4);
25301
29431
  }
25302
29432
  static connect(address, signerOrProvider) {
25303
29433
  return new Contract$1(address, _abi$4, signerOrProvider);
@@ -26221,7 +30351,7 @@ class ImmutableERC721PermissionedMintable__factory extends ContractFactory {
26221
30351
  static bytecode = _bytecode$1;
26222
30352
  static abi = _abi$1;
26223
30353
  static createInterface() {
26224
- return new utils$1.Interface(_abi$1);
30354
+ return new utils$2.Interface(_abi$1);
26225
30355
  }
26226
30356
  static connect(address, signerOrProvider) {
26227
30357
  return new Contract$1(address, _abi$1, signerOrProvider);
@@ -26510,4 +30640,4 @@ class ERC721PermissionedMintable {
26510
30640
  }
26511
30641
  }
26512
30642
 
26513
- export { APIError, BlockchainData, $15cc9e120aa6f3bf$export$d1bfa21f7c76447a as BridgeEventType, $1f969328e5988c99$export$30f61ebf204c69f6 as BridgeReact, $d85ad1457a3f1a83$export$161d4a74df65fc08 as CHECKOUT_API_BASE_URL, $0472f23319457bfb$export$c06e1e7429de6283 as ChainId, $0472f23319457bfb$export$b874c6b1dfe85e02 as ChainName, $a8cb37a3fc8eb863$export$1f60ba4ec72508a0 as Checkout, $a8bc256d81a5e2c1$export$e3dc0620abde7f5a as CheckoutErrorType, $045213b18e9f1f94$export$75be0f6af9650f2c as CheckoutWidgetTagNames, $430e3eda76fa4d5f$export$af210a0808087845 as CheckoutWidgets, $a85ecdbd885c58ad$export$e72e7f9969a47dd3 as ConnectEventType, $f2083cd30e2f5c56$export$49d62957f420a1e2 as ConnectReact, ERC20, ERC721PermissionedMintable, Environment$1 as Environment, $de275b98d2b651c3$export$788b1fd17f3dad84 as GasEstimateType, GenericIMXProvider, $207ed853f11d19d5$export$5a0ace85cae72d45 as IMTBLWidgetEvents, ImmutableConfiguration, ImmutableXClient, MetaMaskIMXProvider, $a47e48dd2c04791b$export$1f05a55fe0680cc7 as NetworkFilterTypes, Networks, $ad06b030b1a3ba34$export$b80d2daf830437b9 as OrchestrationEventType, Orderbook, Passport, PassportError, ProviderConfiguration, $53d219e7f6bf0cd6$export$140a49745ab55563 as SwapEventType, $a4fbb8e3a6aeff58$export$971e031379577f4 as SwapReact, $08d5ddc39acd6833$export$fd9b17d87f4121d2 as TokenFilterTypes, $430e3eda76fa4d5f$export$bf1548ba7e61c17f as UpdateConfig, $77b6aac5c353d4a9$export$d9be06b70b28c742 as WalletEventType, $4f91c5f280efe242$export$a75605c67ea83a5a as WalletFilterTypes, $e768639828688ca3$export$2d7a51a18d87e21d as WalletProviderName, $89d55ace0f8f1c07$export$ceaac94f34dba154 as WalletReact, $045213b18e9f1f94$export$c88931fdc51854eb as WidgetTheme, module };
30643
+ export { APIError, BlockchainData, $15cc9e120aa6f3bf$export$d1bfa21f7c76447a as BridgeEventType, $1f969328e5988c99$export$30f61ebf204c69f6 as BridgeReact, $d85ad1457a3f1a83$export$161d4a74df65fc08 as CHECKOUT_API_BASE_URL, $0472f23319457bfb$export$c06e1e7429de6283 as ChainId, $0472f23319457bfb$export$b874c6b1dfe85e02 as ChainName, $a8cb37a3fc8eb863$export$1f60ba4ec72508a0 as Checkout, $a8bc256d81a5e2c1$export$e3dc0620abde7f5a as CheckoutErrorType, $045213b18e9f1f94$export$75be0f6af9650f2c as CheckoutWidgetTagNames, $430e3eda76fa4d5f$export$af210a0808087845 as CheckoutWidgets, $a85ecdbd885c58ad$export$e72e7f9969a47dd3 as ConnectEventType, $f2083cd30e2f5c56$export$49d62957f420a1e2 as ConnectReact, ERC20, ERC721PermissionedMintable, Environment$1 as Environment, $de275b98d2b651c3$export$788b1fd17f3dad84 as GasEstimateType, GenericIMXProvider, $207ed853f11d19d5$export$5a0ace85cae72d45 as IMTBLWidgetEvents, ImmutableConfiguration, ImmutableXClient, JsonRpcError, MetaMaskIMXProvider, $a47e48dd2c04791b$export$1f05a55fe0680cc7 as NetworkFilterTypes, Networks, $ad06b030b1a3ba34$export$b80d2daf830437b9 as OrchestrationEventType, Orderbook, Passport, PassportError, ProviderConfiguration, ProviderErrorCode, ProviderEvent, RpcErrorCode, $53d219e7f6bf0cd6$export$140a49745ab55563 as SwapEventType, $a4fbb8e3a6aeff58$export$971e031379577f4 as SwapReact, $08d5ddc39acd6833$export$fd9b17d87f4121d2 as TokenFilterTypes, $430e3eda76fa4d5f$export$bf1548ba7e61c17f as UpdateConfig, $77b6aac5c353d4a9$export$d9be06b70b28c742 as WalletEventType, $4f91c5f280efe242$export$a75605c67ea83a5a as WalletFilterTypes, $e768639828688ca3$export$2d7a51a18d87e21d as WalletProviderName, $89d55ace0f8f1c07$export$ceaac94f34dba154 as WalletReact, $045213b18e9f1f94$export$c88931fdc51854eb as WidgetTheme, module };