@imtbl/sdk 0.1.6 → 0.1.7-alpha.1

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.cjs CHANGED
@@ -1,12 +1,23 @@
1
1
  'use strict';
2
2
 
3
3
  var coreSdk = require('@imtbl/core-sdk');
4
+ var guardian = require('@imtbl/guardian');
4
5
  var oidcClientTs = require('oidc-client-ts');
5
6
  var ethers = require('ethers');
6
7
  var magicSdk = require('magic-sdk');
7
8
  var oidc = require('@magic-ext/oidc');
8
9
  var BN = require('bn.js');
9
10
  var encUtils = require('enc-utils');
11
+ var constants = require('@opensea/seaport-js/lib/constants');
12
+ var FormData = require('form-data');
13
+ var fetch = require('node-fetch');
14
+ var seaportJs = require('@opensea/seaport-js');
15
+ var units = require('@ethersproject/units');
16
+ var bignumber = require('@ethersproject/bignumber');
17
+ var detectEthereumProvider = require('@metamask/detect-provider');
18
+ var providers = require('@ethersproject/providers');
19
+ var jsxRuntime = require('react/jsx-runtime');
20
+ require('react');
10
21
 
11
22
  function _interopNamespaceDefault(e) {
12
23
  var n = Object.create(null);
@@ -25,6 +36,7 @@ function _interopNamespaceDefault(e) {
25
36
  return Object.freeze(n);
26
37
  }
27
38
 
39
+ var guardian__namespace = /*#__PURE__*/_interopNamespaceDefault(guardian);
28
40
  var encUtils__namespace = /*#__PURE__*/_interopNamespaceDefault(encUtils);
29
41
 
30
42
  exports.Environment = void 0;
@@ -548,30 +560,40 @@ class ImmutableXClient {
548
560
  function serializeEthSignature(sig) {
549
561
  // This is because golang appends a recovery param
550
562
  // https://github.com/ethers-io/ethers.js/issues/823
551
- return encUtils__namespace.addHexPrefix(encUtils__namespace.padLeft(sig.r.toString(16), 64) +
552
- encUtils__namespace.padLeft(sig.s.toString(16), 64) +
553
- encUtils__namespace.padLeft(sig.recoveryParam?.toString(16) || '', 2));
563
+ return encUtils__namespace.addHexPrefix(encUtils__namespace.padLeft(sig.r.toString(16), 64)
564
+ + encUtils__namespace.padLeft(sig.s.toString(16), 64)
565
+ + encUtils__namespace.padLeft(sig.recoveryParam?.toString(16) || '', 2));
554
566
  }
555
567
  function importRecoveryParam(v) {
568
+ const isValidBigNumber = new BN(v, 16).cmp(new BN(27)) !== -1
569
+ ? new BN(v, 16).sub(new BN(27)).toNumber()
570
+ : new BN(v, 16).toNumber();
556
571
  return v.trim()
557
- ? new BN(v, 16).cmp(new BN(27)) !== -1
558
- ? new BN(v, 16).sub(new BN(27)).toNumber()
559
- : new BN(v, 16).toNumber()
572
+ ? isValidBigNumber
560
573
  : undefined;
561
574
  }
562
575
  // used chained with serializeEthSignature. serializeEthSignature(deserializeSignature(...))
563
576
  function deserializeSignature(sig, size = 64) {
564
- sig = encUtils__namespace.removeHexPrefix(sig);
577
+ const removedHexPrefixSig = encUtils__namespace.removeHexPrefix(sig);
565
578
  return {
566
- r: new BN(sig.substring(0, size), 'hex'),
567
- s: new BN(sig.substring(size, size * 2), 'hex'),
568
- recoveryParam: importRecoveryParam(sig.substring(size * 2, size * 2 + 2)),
579
+ r: new BN(removedHexPrefixSig.substring(0, size), 'hex'),
580
+ s: new BN(removedHexPrefixSig.substring(size, size * 2), 'hex'),
581
+ recoveryParam: importRecoveryParam(removedHexPrefixSig.substring(size * 2, size * 2 + 2)),
569
582
  };
570
583
  }
571
584
  async function signRaw(payload, signer) {
572
585
  const signature = deserializeSignature(await signer.signMessage(payload));
573
586
  return serializeEthSignature(signature);
574
587
  }
588
+ async function signMessage(message, signer) {
589
+ const ethAddress = await signer.getAddress();
590
+ const ethSignature = await signRaw(message, signer);
591
+ return {
592
+ message,
593
+ ethAddress,
594
+ ethSignature,
595
+ };
596
+ }
575
597
 
576
598
  /**
577
599
  * Helper method to convert token type to a SignableToken type
@@ -596,6 +618,7 @@ function convertToSignableToken(token) {
596
618
  },
597
619
  };
598
620
  case 'ETH':
621
+ default:
599
622
  return {
600
623
  type: 'ETH',
601
624
  data: {
@@ -899,7 +922,7 @@ class ConfirmationScreen {
899
922
  }
900
923
 
901
924
  const ERC721$1 = 'ERC721';
902
- const transfer = ({ request, transfersApi, starkSigner, user, passportConfig,
925
+ const transfer$1 = ({ request, transfersApi, starkSigner, user, passportConfig,
903
926
  // TODO: remove this eslint disable once we have a better solution
904
927
  // eslint-disable-next-line max-len
905
928
  }) => withPassportError(async () => {
@@ -1009,12 +1032,12 @@ async function batchNftTransfer({ user, starkSigner, request, transfersApi, pass
1009
1032
  }, PassportErrorType.TRANSFER_ERROR);
1010
1033
  }
1011
1034
 
1012
- const ERC721 = 'ERC721';
1013
- async function createOrder({ starkSigner, user, request, ordersApi, passportConfig, }) {
1035
+ const ERC721$2 = 'ERC721';
1036
+ async function createOrder$1({ starkSigner, user, request, ordersApi, passportConfig, }) {
1014
1037
  return withPassportError(async () => {
1015
1038
  const ethAddress = user.etherKey;
1016
- const amountSell = request.sell.type === ERC721 ? '1' : request.sell.amount;
1017
- const amountBuy = request.buy.type === ERC721 ? '1' : request.buy.amount;
1039
+ const amountSell = request.sell.type === ERC721$2 ? '1' : request.sell.amount;
1040
+ const amountBuy = request.buy.type === ERC721$2 ? '1' : request.buy.amount;
1018
1041
  const getSignableOrderRequestV3 = {
1019
1042
  user: ethAddress,
1020
1043
  amount_buy: amountBuy,
@@ -1066,7 +1089,7 @@ async function createOrder({ starkSigner, user, request, ordersApi, passportConf
1066
1089
  };
1067
1090
  }, PassportErrorType.CREATE_ORDER_ERROR);
1068
1091
  }
1069
- async function cancelOrder({ user, starkSigner, request, ordersApi, passportConfig, }) {
1092
+ async function cancelOrder$1({ user, starkSigner, request, ordersApi, passportConfig, }) {
1070
1093
  return withPassportError(async () => {
1071
1094
  const getSignableCancelOrderRequest = {
1072
1095
  order_id: request.order_id,
@@ -1102,7 +1125,7 @@ async function cancelOrder({ user, starkSigner, request, ordersApi, passportConf
1102
1125
  }, PassportErrorType.CANCEL_ORDER_ERROR);
1103
1126
  }
1104
1127
 
1105
- async function exchangeTransfer({ user, starkSigner, request, exchangesApi, }) {
1128
+ async function exchangeTransfer$1({ user, starkSigner, request, exchangesApi, }) {
1106
1129
  return withPassportError(async () => {
1107
1130
  const ethAddress = user.etherKey;
1108
1131
  const transferAmount = request.amount;
@@ -1146,7 +1169,7 @@ async function exchangeTransfer({ user, starkSigner, request, exchangesApi, }) {
1146
1169
  }, PassportErrorType.EXCHANGE_TRANSFER_ERROR);
1147
1170
  }
1148
1171
 
1149
- async function createTrade({ request, tradesApi, user, starkSigner, passportConfig, }) {
1172
+ async function createTrade$1({ request, tradesApi, user, starkSigner, passportConfig, }) {
1150
1173
  return withPassportError(async () => {
1151
1174
  const ethAddress = user.etherKey;
1152
1175
  const getSignableTradeRequest = {
@@ -1208,7 +1231,7 @@ class PassportImxProvider {
1208
1231
  this.immutableXClient = immutableXClient;
1209
1232
  }
1210
1233
  async transfer(request) {
1211
- return transfer({
1234
+ return transfer$1({
1212
1235
  request,
1213
1236
  user: this.user,
1214
1237
  starkSigner: this.starkSigner,
@@ -1227,7 +1250,7 @@ class PassportImxProvider {
1227
1250
  throw new PassportError('Operation not supported', PassportErrorType.OPERATION_NOT_SUPPORTED_ERROR);
1228
1251
  }
1229
1252
  createOrder(request) {
1230
- return createOrder({
1253
+ return createOrder$1({
1231
1254
  request,
1232
1255
  user: this.user,
1233
1256
  starkSigner: this.starkSigner,
@@ -1236,7 +1259,7 @@ class PassportImxProvider {
1236
1259
  });
1237
1260
  }
1238
1261
  cancelOrder(request) {
1239
- return cancelOrder({
1262
+ return cancelOrder$1({
1240
1263
  request,
1241
1264
  user: this.user,
1242
1265
  starkSigner: this.starkSigner,
@@ -1245,7 +1268,7 @@ class PassportImxProvider {
1245
1268
  });
1246
1269
  }
1247
1270
  createTrade(request) {
1248
- return createTrade({
1271
+ return createTrade$1({
1249
1272
  request,
1250
1273
  user: this.user,
1251
1274
  starkSigner: this.starkSigner,
@@ -1263,7 +1286,7 @@ class PassportImxProvider {
1263
1286
  });
1264
1287
  }
1265
1288
  exchangeTransfer(request) {
1266
- return exchangeTransfer({
1289
+ return exchangeTransfer$1({
1267
1290
  request,
1268
1291
  user: this.user,
1269
1292
  starkSigner: this.starkSigner,
@@ -1290,7 +1313,7 @@ class PassportImxProvider {
1290
1313
  throw new PassportError('Operation not supported', PassportErrorType.OPERATION_NOT_SUPPORTED_ERROR);
1291
1314
  }
1292
1315
  getAddress() {
1293
- return Promise.resolve(this.starkSigner.getAddress());
1316
+ return Promise.resolve(this.user.etherKey);
1294
1317
  }
1295
1318
  }
1296
1319
 
@@ -1400,6 +1423,7 @@ async function registerPassport({ ethSigner, starkSigner, usersApi }, authorizat
1400
1423
  }
1401
1424
 
1402
1425
  // TODO: Remove this once the dependency has been added
1426
+ // eslint-disable-next-line import/no-extraneous-dependencies
1403
1427
  class Passport {
1404
1428
  authManager;
1405
1429
  magicAdapter;
@@ -1481,6 +1505,3885 @@ class Passport {
1481
1505
  }
1482
1506
  }
1483
1507
 
1508
+ class BaseHttpRequest {
1509
+ config;
1510
+ constructor(config) {
1511
+ this.config = config;
1512
+ }
1513
+ }
1514
+
1515
+ class ApiError extends Error {
1516
+ url;
1517
+ status;
1518
+ statusText;
1519
+ body;
1520
+ request;
1521
+ constructor(request, response, message) {
1522
+ super(message);
1523
+ this.name = 'ApiError';
1524
+ this.url = response.url;
1525
+ this.status = response.status;
1526
+ this.statusText = response.statusText;
1527
+ this.body = response.body;
1528
+ this.request = request;
1529
+ }
1530
+ }
1531
+
1532
+ /* istanbul ignore file */
1533
+ /* tslint:disable */
1534
+ /* eslint-disable */
1535
+ class CancelError extends Error {
1536
+ constructor(message) {
1537
+ super(message);
1538
+ this.name = 'CancelError';
1539
+ }
1540
+ get isCancelled() {
1541
+ return true;
1542
+ }
1543
+ }
1544
+ class CancelablePromise {
1545
+ [Symbol.toStringTag];
1546
+ _isResolved;
1547
+ _isRejected;
1548
+ _isCancelled;
1549
+ _cancelHandlers;
1550
+ _promise;
1551
+ _resolve;
1552
+ _reject;
1553
+ constructor(executor) {
1554
+ this._isResolved = false;
1555
+ this._isRejected = false;
1556
+ this._isCancelled = false;
1557
+ this._cancelHandlers = [];
1558
+ this._promise = new Promise((resolve, reject) => {
1559
+ this._resolve = resolve;
1560
+ this._reject = reject;
1561
+ const onResolve = (value) => {
1562
+ if (this._isResolved || this._isRejected || this._isCancelled) {
1563
+ return;
1564
+ }
1565
+ this._isResolved = true;
1566
+ this._resolve?.(value);
1567
+ };
1568
+ const onReject = (reason) => {
1569
+ if (this._isResolved || this._isRejected || this._isCancelled) {
1570
+ return;
1571
+ }
1572
+ this._isRejected = true;
1573
+ this._reject?.(reason);
1574
+ };
1575
+ const onCancel = (cancelHandler) => {
1576
+ if (this._isResolved || this._isRejected || this._isCancelled) {
1577
+ return;
1578
+ }
1579
+ this._cancelHandlers.push(cancelHandler);
1580
+ };
1581
+ Object.defineProperty(onCancel, 'isResolved', {
1582
+ get: () => this._isResolved,
1583
+ });
1584
+ Object.defineProperty(onCancel, 'isRejected', {
1585
+ get: () => this._isRejected,
1586
+ });
1587
+ Object.defineProperty(onCancel, 'isCancelled', {
1588
+ get: () => this._isCancelled,
1589
+ });
1590
+ return executor(onResolve, onReject, onCancel);
1591
+ });
1592
+ }
1593
+ then(onFulfilled, onRejected) {
1594
+ return this._promise.then(onFulfilled, onRejected);
1595
+ }
1596
+ catch(onRejected) {
1597
+ return this._promise.catch(onRejected);
1598
+ }
1599
+ finally(onFinally) {
1600
+ return this._promise.finally(onFinally);
1601
+ }
1602
+ cancel() {
1603
+ if (this._isResolved || this._isRejected || this._isCancelled) {
1604
+ return;
1605
+ }
1606
+ this._isCancelled = true;
1607
+ if (this._cancelHandlers.length) {
1608
+ try {
1609
+ for (const cancelHandler of this._cancelHandlers) {
1610
+ cancelHandler();
1611
+ }
1612
+ }
1613
+ catch (error) {
1614
+ console.warn('Cancellation threw an error', error);
1615
+ return;
1616
+ }
1617
+ }
1618
+ this._cancelHandlers.length = 0;
1619
+ this._reject?.(new CancelError('Request aborted'));
1620
+ }
1621
+ get isCancelled() {
1622
+ return this._isCancelled;
1623
+ }
1624
+ }
1625
+
1626
+ /* istanbul ignore file */
1627
+ /* tslint:disable */
1628
+ /* eslint-disable */
1629
+ const isDefined = (value) => {
1630
+ return value !== undefined && value !== null;
1631
+ };
1632
+ const isString = (value) => {
1633
+ return typeof value === 'string';
1634
+ };
1635
+ const isStringWithValue = (value) => {
1636
+ return isString(value) && value !== '';
1637
+ };
1638
+ const isBlob = (value) => {
1639
+ return (typeof value === 'object' &&
1640
+ typeof value.type === 'string' &&
1641
+ typeof value.stream === 'function' &&
1642
+ typeof value.arrayBuffer === 'function' &&
1643
+ typeof value.constructor === 'function' &&
1644
+ typeof value.constructor.name === 'string' &&
1645
+ /^(Blob|File)$/.test(value.constructor.name) &&
1646
+ /^(Blob|File)$/.test(value[Symbol.toStringTag]));
1647
+ };
1648
+ const isFormData = (value) => {
1649
+ return value instanceof FormData;
1650
+ };
1651
+ const base64 = (str) => {
1652
+ try {
1653
+ return btoa(str);
1654
+ }
1655
+ catch (err) {
1656
+ // @ts-ignore
1657
+ return Buffer.from(str).toString('base64');
1658
+ }
1659
+ };
1660
+ const getQueryString = (params) => {
1661
+ const qs = [];
1662
+ const append = (key, value) => {
1663
+ qs.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`);
1664
+ };
1665
+ const process = (key, value) => {
1666
+ if (isDefined(value)) {
1667
+ if (Array.isArray(value)) {
1668
+ value.forEach(v => {
1669
+ process(key, v);
1670
+ });
1671
+ }
1672
+ else if (typeof value === 'object') {
1673
+ Object.entries(value).forEach(([k, v]) => {
1674
+ process(`${key}[${k}]`, v);
1675
+ });
1676
+ }
1677
+ else {
1678
+ append(key, value);
1679
+ }
1680
+ }
1681
+ };
1682
+ Object.entries(params).forEach(([key, value]) => {
1683
+ process(key, value);
1684
+ });
1685
+ if (qs.length > 0) {
1686
+ return `?${qs.join('&')}`;
1687
+ }
1688
+ return '';
1689
+ };
1690
+ const getUrl = (config, options) => {
1691
+ const encoder = config.ENCODE_PATH || encodeURI;
1692
+ const path = options.url
1693
+ .replace('{api-version}', config.VERSION)
1694
+ .replace(/{(.*?)}/g, (substring, group) => {
1695
+ if (options.path?.hasOwnProperty(group)) {
1696
+ return encoder(String(options.path[group]));
1697
+ }
1698
+ return substring;
1699
+ });
1700
+ const url = `${config.BASE}${path}`;
1701
+ if (options.query) {
1702
+ return `${url}${getQueryString(options.query)}`;
1703
+ }
1704
+ return url;
1705
+ };
1706
+ const getFormData = (options) => {
1707
+ if (options.formData) {
1708
+ const formData = new FormData();
1709
+ const process = (key, value) => {
1710
+ if (isString(value) || isBlob(value)) {
1711
+ formData.append(key, value);
1712
+ }
1713
+ else {
1714
+ formData.append(key, JSON.stringify(value));
1715
+ }
1716
+ };
1717
+ Object.entries(options.formData)
1718
+ .filter(([_, value]) => isDefined(value))
1719
+ .forEach(([key, value]) => {
1720
+ if (Array.isArray(value)) {
1721
+ value.forEach(v => process(key, v));
1722
+ }
1723
+ else {
1724
+ process(key, value);
1725
+ }
1726
+ });
1727
+ return formData;
1728
+ }
1729
+ return undefined;
1730
+ };
1731
+ const resolve = async (options, resolver) => {
1732
+ if (typeof resolver === 'function') {
1733
+ return resolver(options);
1734
+ }
1735
+ return resolver;
1736
+ };
1737
+ const getHeaders = async (config, options) => {
1738
+ const token = await resolve(options, config.TOKEN);
1739
+ const username = await resolve(options, config.USERNAME);
1740
+ const password = await resolve(options, config.PASSWORD);
1741
+ const additionalHeaders = await resolve(options, config.HEADERS);
1742
+ const headers = Object.entries({
1743
+ Accept: 'application/json',
1744
+ ...additionalHeaders,
1745
+ ...options.headers,
1746
+ })
1747
+ .filter(([_, value]) => isDefined(value))
1748
+ .reduce((headers, [key, value]) => ({
1749
+ ...headers,
1750
+ [key]: String(value),
1751
+ }), {});
1752
+ if (isStringWithValue(token)) {
1753
+ headers['Authorization'] = `Bearer ${token}`;
1754
+ }
1755
+ if (isStringWithValue(username) && isStringWithValue(password)) {
1756
+ const credentials = base64(`${username}:${password}`);
1757
+ headers['Authorization'] = `Basic ${credentials}`;
1758
+ }
1759
+ if (options.body) {
1760
+ if (options.mediaType) {
1761
+ headers['Content-Type'] = options.mediaType;
1762
+ }
1763
+ else if (isBlob(options.body)) {
1764
+ headers['Content-Type'] = 'application/octet-stream';
1765
+ }
1766
+ else if (isString(options.body)) {
1767
+ headers['Content-Type'] = 'text/plain';
1768
+ }
1769
+ else if (!isFormData(options.body)) {
1770
+ headers['Content-Type'] = 'application/json';
1771
+ }
1772
+ }
1773
+ return new fetch.Headers(headers);
1774
+ };
1775
+ const getRequestBody = (options) => {
1776
+ if (options.body) {
1777
+ if (options.mediaType?.includes('/json')) {
1778
+ return JSON.stringify(options.body);
1779
+ }
1780
+ else if (isString(options.body) || isBlob(options.body) || isFormData(options.body)) {
1781
+ return options.body;
1782
+ }
1783
+ else {
1784
+ return JSON.stringify(options.body);
1785
+ }
1786
+ }
1787
+ return undefined;
1788
+ };
1789
+ const sendRequest = async (options, url, body, formData, headers, onCancel) => {
1790
+ const controller = new AbortController();
1791
+ const request = {
1792
+ headers,
1793
+ method: options.method,
1794
+ body: body ?? formData,
1795
+ signal: controller.signal,
1796
+ };
1797
+ onCancel(() => controller.abort());
1798
+ return await fetch(url, request);
1799
+ };
1800
+ const getResponseHeader = (response, responseHeader) => {
1801
+ if (responseHeader) {
1802
+ const content = response.headers.get(responseHeader);
1803
+ if (isString(content)) {
1804
+ return content;
1805
+ }
1806
+ }
1807
+ return undefined;
1808
+ };
1809
+ const getResponseBody = async (response) => {
1810
+ if (response.status !== 204) {
1811
+ try {
1812
+ const contentType = response.headers.get('Content-Type');
1813
+ if (contentType) {
1814
+ const isJSON = contentType.toLowerCase().startsWith('application/json');
1815
+ if (isJSON) {
1816
+ return await response.json();
1817
+ }
1818
+ else {
1819
+ return await response.text();
1820
+ }
1821
+ }
1822
+ }
1823
+ catch (error) {
1824
+ console.error(error);
1825
+ }
1826
+ }
1827
+ return undefined;
1828
+ };
1829
+ const catchErrorCodes = (options, result) => {
1830
+ const errors = {
1831
+ 400: 'Bad Request',
1832
+ 401: 'Unauthorized',
1833
+ 403: 'Forbidden',
1834
+ 404: 'Not Found',
1835
+ 500: 'Internal Server Error',
1836
+ 502: 'Bad Gateway',
1837
+ 503: 'Service Unavailable',
1838
+ ...options.errors,
1839
+ };
1840
+ const error = errors[result.status];
1841
+ if (error) {
1842
+ throw new ApiError(options, result, error);
1843
+ }
1844
+ if (!result.ok) {
1845
+ throw new ApiError(options, result, 'Generic Error');
1846
+ }
1847
+ };
1848
+ /**
1849
+ * Request method
1850
+ * @param config The OpenAPI configuration object
1851
+ * @param options The request options from the service
1852
+ * @returns CancelablePromise<T>
1853
+ * @throws ApiError
1854
+ */
1855
+ const request = (config, options) => {
1856
+ return new CancelablePromise(async (resolve, reject, onCancel) => {
1857
+ try {
1858
+ const url = getUrl(config, options);
1859
+ const formData = getFormData(options);
1860
+ const body = getRequestBody(options);
1861
+ const headers = await getHeaders(config, options);
1862
+ if (!onCancel.isCancelled) {
1863
+ const response = await sendRequest(options, url, body, formData, headers, onCancel);
1864
+ const responseBody = await getResponseBody(response);
1865
+ const responseHeader = getResponseHeader(response, options.responseHeader);
1866
+ const result = {
1867
+ url,
1868
+ ok: response.ok,
1869
+ status: response.status,
1870
+ statusText: response.statusText,
1871
+ body: responseHeader ?? responseBody,
1872
+ };
1873
+ catchErrorCodes(options, result);
1874
+ resolve(result.body);
1875
+ }
1876
+ }
1877
+ catch (error) {
1878
+ reject(error);
1879
+ }
1880
+ });
1881
+ };
1882
+
1883
+ class NodeHttpRequest extends BaseHttpRequest {
1884
+ constructor(config) {
1885
+ super(config);
1886
+ }
1887
+ /**
1888
+ * Request method
1889
+ * @param options The request options from the service
1890
+ * @returns CancelablePromise<T>
1891
+ * @throws ApiError
1892
+ */
1893
+ request(options) {
1894
+ return request(this.config, options);
1895
+ }
1896
+ }
1897
+
1898
+ class OrdersService {
1899
+ httpRequest;
1900
+ constructor(httpRequest) {
1901
+ this.httpRequest = httpRequest;
1902
+ }
1903
+ /**
1904
+ * List all orders
1905
+ * List all orders
1906
+ * @returns Orders OK response.
1907
+ * @throws ApiError
1908
+ */
1909
+ listOrders({ chainId, pageSize = 100, sortBy, sortDirection, pageCursor, }) {
1910
+ return this.httpRequest.request({
1911
+ method: 'GET',
1912
+ url: '/v1/chains/{chain_id}/orders',
1913
+ path: {
1914
+ 'chain_id': chainId,
1915
+ },
1916
+ query: {
1917
+ 'page_size': pageSize,
1918
+ 'sort_by': sortBy,
1919
+ 'sort_direction': sortDirection,
1920
+ 'page_cursor': pageCursor,
1921
+ },
1922
+ errors: {
1923
+ 404: `not_found: Resource not found`,
1924
+ 500: `internal_error: Internal server error`,
1925
+ },
1926
+ });
1927
+ }
1928
+ /**
1929
+ * Create an order
1930
+ * Create an order
1931
+ * @returns Order Created response.
1932
+ * @throws ApiError
1933
+ */
1934
+ createOrder({ chainId, requestBody, }) {
1935
+ return this.httpRequest.request({
1936
+ method: 'POST',
1937
+ url: '/v1/chains/{chain_id}/orders',
1938
+ path: {
1939
+ 'chain_id': chainId,
1940
+ },
1941
+ body: requestBody,
1942
+ mediaType: 'application/json',
1943
+ errors: {
1944
+ 400: `bad_request: Bad Request`,
1945
+ 404: `not_found: Resource not found`,
1946
+ 500: `internal_error: Internal server error`,
1947
+ },
1948
+ });
1949
+ }
1950
+ /**
1951
+ * Get a single order by ID
1952
+ * Get a single order by ID
1953
+ * @returns Order OK response.
1954
+ * @throws ApiError
1955
+ */
1956
+ getOrder({ chainId, orderId, }) {
1957
+ return this.httpRequest.request({
1958
+ method: 'GET',
1959
+ url: '/v1/chains/{chain_id}/orders/{order_id}',
1960
+ path: {
1961
+ 'chain_id': chainId,
1962
+ 'order_id': orderId,
1963
+ },
1964
+ errors: {
1965
+ 404: `not_found: Resource not found`,
1966
+ 500: `internal_error: Internal server error`,
1967
+ },
1968
+ });
1969
+ }
1970
+ }
1971
+
1972
+ class OrderBookClient {
1973
+ orders;
1974
+ request;
1975
+ constructor(config, HttpRequest = NodeHttpRequest) {
1976
+ this.request = new HttpRequest({
1977
+ BASE: config?.BASE ?? 'https://order-book-mr.dev.imtbl.com',
1978
+ VERSION: config?.VERSION ?? '1.0.0',
1979
+ WITH_CREDENTIALS: config?.WITH_CREDENTIALS ?? false,
1980
+ CREDENTIALS: config?.CREDENTIALS ?? 'include',
1981
+ TOKEN: config?.TOKEN,
1982
+ USERNAME: config?.USERNAME,
1983
+ PASSWORD: config?.PASSWORD,
1984
+ HEADERS: config?.HEADERS,
1985
+ ENCODE_PATH: config?.ENCODE_PATH,
1986
+ });
1987
+ this.orders = new OrdersService(this.request);
1988
+ }
1989
+ }
1990
+
1991
+ /* istanbul ignore file */
1992
+ /* tslint:disable */
1993
+ /* eslint-disable */
1994
+ var BuyItem;
1995
+ (function (BuyItem) {
1996
+ (function (item_type) {
1997
+ item_type["ERC20"] = "ERC20";
1998
+ item_type["IMX"] = "IMX";
1999
+ })(BuyItem.item_type || (BuyItem.item_type = {}));
2000
+ })(BuyItem || (BuyItem = {}));
2001
+
2002
+ /* istanbul ignore file */
2003
+ /* tslint:disable */
2004
+ /* eslint-disable */
2005
+ var CreateOrderProtocolData;
2006
+ (function (CreateOrderProtocolData) {
2007
+ (function (order_type) {
2008
+ order_type["FULL_OPEN"] = "FULL_OPEN";
2009
+ })(CreateOrderProtocolData.order_type || (CreateOrderProtocolData.order_type = {}));
2010
+ })(CreateOrderProtocolData || (CreateOrderProtocolData = {}));
2011
+
2012
+ /* istanbul ignore file */
2013
+ /* tslint:disable */
2014
+ /* eslint-disable */
2015
+ var Fee;
2016
+ (function (Fee) {
2017
+ (function (fee_type) {
2018
+ fee_type["ROYALTY"] = "ROYALTY";
2019
+ })(Fee.fee_type || (Fee.fee_type = {}));
2020
+ })(Fee || (Fee = {}));
2021
+
2022
+ /* istanbul ignore file */
2023
+ /* tslint:disable */
2024
+ /* eslint-disable */
2025
+ var Order;
2026
+ (function (Order) {
2027
+ (function (status) {
2028
+ status["PENDING"] = "PENDING";
2029
+ status["ACTIVE"] = "ACTIVE";
2030
+ status["CANCELLED"] = "CANCELLED";
2031
+ status["INACTIVE"] = "INACTIVE";
2032
+ status["REJECTED"] = "REJECTED";
2033
+ status["FILLED"] = "FILLED";
2034
+ status["EXPIRED"] = "EXPIRED";
2035
+ })(Order.status || (Order.status = {}));
2036
+ })(Order || (Order = {}));
2037
+
2038
+ /* istanbul ignore file */
2039
+ /* tslint:disable */
2040
+ /* eslint-disable */
2041
+ var SellItem;
2042
+ (function (SellItem) {
2043
+ (function (item_type) {
2044
+ item_type["ERC721"] = "ERC721";
2045
+ })(SellItem.item_type || (SellItem.item_type = {}));
2046
+ })(SellItem || (SellItem = {}));
2047
+
2048
+ class ImmutableApiClient {
2049
+ orderbookService;
2050
+ chainId;
2051
+ constructor(orderbookService, chainId) {
2052
+ this.orderbookService = orderbookService;
2053
+ this.chainId = chainId;
2054
+ }
2055
+ async getOrder(orderId) {
2056
+ return this.orderbookService.getOrder({ chainId: this.chainId, orderId });
2057
+ }
2058
+ async createOrder({ orderHash, orderComponents, offerer, orderSignature, }) {
2059
+ if (orderComponents.offer.length !== 1) {
2060
+ throw new Error('Only one item can be listed at a time');
2061
+ }
2062
+ if (Number(orderComponents.offer[0].itemType) !== constants.ItemType.ERC721) {
2063
+ throw new Error('Only ERC721 tokens can be listed');
2064
+ }
2065
+ const considerationItemTypeTheSame = new Set([...orderComponents.consideration.map((c) => c.itemType)]).size === 1;
2066
+ if (!considerationItemTypeTheSame) {
2067
+ throw new Error('All consideration items must be of the same type');
2068
+ }
2069
+ return this.orderbookService.createOrder({
2070
+ chainId: this.chainId,
2071
+ requestBody: {
2072
+ order_hash: orderHash,
2073
+ account_address: offerer,
2074
+ buy: [
2075
+ {
2076
+ item_type: Number(orderComponents.consideration[0].itemType) === constants.ItemType.NATIVE
2077
+ ? BuyItem.item_type.IMX
2078
+ : BuyItem.item_type.ERC20,
2079
+ start_amount: orderComponents.consideration[0].startAmount,
2080
+ }
2081
+ ],
2082
+ buy_fees: orderComponents.consideration.length > 1
2083
+ ? [
2084
+ {
2085
+ amount: orderComponents.consideration[1].startAmount,
2086
+ recipient: orderComponents.consideration[1].recipient,
2087
+ fee_type: Fee.fee_type.ROYALTY,
2088
+ },
2089
+ ]
2090
+ : [],
2091
+ end_time: new Date(parseInt(`${orderComponents.endTime.toString()}000`, 10)).toISOString(),
2092
+ protocol_data: {
2093
+ order_type: CreateOrderProtocolData.order_type.FULL_OPEN,
2094
+ zone_address: orderComponents.zone,
2095
+ },
2096
+ salt: orderComponents.salt,
2097
+ sell: [{
2098
+ contract_address: orderComponents.offer[0].token,
2099
+ token_id: orderComponents.offer[0].identifierOrCriteria,
2100
+ item_type: SellItem.item_type.ERC721,
2101
+ }],
2102
+ signature: orderSignature,
2103
+ start_time: new Date(parseInt(`${orderComponents.startTime.toString()}000`, 10)).toISOString(),
2104
+ },
2105
+ });
2106
+ }
2107
+ }
2108
+
2109
+ class ImmutableApiClientFactory {
2110
+ chainId;
2111
+ orderbookClient;
2112
+ constructor(apiEndpoint, chainId) {
2113
+ this.chainId = chainId;
2114
+ this.orderbookClient = new OrderBookClient({
2115
+ // eslint-disable-next-line @typescript-eslint/naming-convention
2116
+ BASE: apiEndpoint,
2117
+ });
2118
+ }
2119
+ create() {
2120
+ return new ImmutableApiClient(this.orderbookClient.orders, this.chainId);
2121
+ }
2122
+ }
2123
+
2124
+ class ERC721 {
2125
+ erc721;
2126
+ constructor(erc721) {
2127
+ this.erc721 = erc721;
2128
+ }
2129
+ async royaltyInfo(tokenId, salePrice) {
2130
+ const [recipient, royaltyRequired] = await this.erc721.royaltyInfo(tokenId, salePrice);
2131
+ return { recipient, amountRequired: royaltyRequired.toString() };
2132
+ }
2133
+ }
2134
+
2135
+ /* Autogenerated file. Do not edit manually. */
2136
+ /* tslint:disable */
2137
+ /* eslint-disable */
2138
+ const _abi = [
2139
+ {
2140
+ inputs: [
2141
+ {
2142
+ internalType: "address",
2143
+ name: "owner_",
2144
+ type: "address",
2145
+ },
2146
+ {
2147
+ internalType: "string",
2148
+ name: "name_",
2149
+ type: "string",
2150
+ },
2151
+ {
2152
+ internalType: "string",
2153
+ name: "symbol_",
2154
+ type: "string",
2155
+ },
2156
+ {
2157
+ internalType: "string",
2158
+ name: "baseURI_",
2159
+ type: "string",
2160
+ },
2161
+ {
2162
+ internalType: "string",
2163
+ name: "contractURI_",
2164
+ type: "string",
2165
+ },
2166
+ {
2167
+ internalType: "address",
2168
+ name: "_receiver",
2169
+ type: "address",
2170
+ },
2171
+ {
2172
+ internalType: "uint96",
2173
+ name: "_feeNumerator",
2174
+ type: "uint96",
2175
+ },
2176
+ ],
2177
+ stateMutability: "nonpayable",
2178
+ type: "constructor",
2179
+ },
2180
+ {
2181
+ inputs: [
2182
+ {
2183
+ internalType: "address",
2184
+ name: "target",
2185
+ type: "address",
2186
+ },
2187
+ ],
2188
+ name: "ApproveTargetNotInAllowlist",
2189
+ type: "error",
2190
+ },
2191
+ {
2192
+ inputs: [
2193
+ {
2194
+ internalType: "address",
2195
+ name: "caller",
2196
+ type: "address",
2197
+ },
2198
+ ],
2199
+ name: "CallerNotInAllowlist",
2200
+ type: "error",
2201
+ },
2202
+ {
2203
+ anonymous: false,
2204
+ inputs: [
2205
+ {
2206
+ indexed: true,
2207
+ internalType: "address",
2208
+ name: "owner",
2209
+ type: "address",
2210
+ },
2211
+ {
2212
+ indexed: true,
2213
+ internalType: "address",
2214
+ name: "approved",
2215
+ type: "address",
2216
+ },
2217
+ {
2218
+ indexed: true,
2219
+ internalType: "uint256",
2220
+ name: "tokenId",
2221
+ type: "uint256",
2222
+ },
2223
+ ],
2224
+ name: "Approval",
2225
+ type: "event",
2226
+ },
2227
+ {
2228
+ anonymous: false,
2229
+ inputs: [
2230
+ {
2231
+ indexed: true,
2232
+ internalType: "address",
2233
+ name: "owner",
2234
+ type: "address",
2235
+ },
2236
+ {
2237
+ indexed: true,
2238
+ internalType: "address",
2239
+ name: "operator",
2240
+ type: "address",
2241
+ },
2242
+ {
2243
+ indexed: false,
2244
+ internalType: "bool",
2245
+ name: "approved",
2246
+ type: "bool",
2247
+ },
2248
+ ],
2249
+ name: "ApprovalForAll",
2250
+ type: "event",
2251
+ },
2252
+ {
2253
+ anonymous: false,
2254
+ inputs: [
2255
+ {
2256
+ indexed: true,
2257
+ internalType: "bytes32",
2258
+ name: "role",
2259
+ type: "bytes32",
2260
+ },
2261
+ {
2262
+ indexed: true,
2263
+ internalType: "bytes32",
2264
+ name: "previousAdminRole",
2265
+ type: "bytes32",
2266
+ },
2267
+ {
2268
+ indexed: true,
2269
+ internalType: "bytes32",
2270
+ name: "newAdminRole",
2271
+ type: "bytes32",
2272
+ },
2273
+ ],
2274
+ name: "RoleAdminChanged",
2275
+ type: "event",
2276
+ },
2277
+ {
2278
+ anonymous: false,
2279
+ inputs: [
2280
+ {
2281
+ indexed: true,
2282
+ internalType: "bytes32",
2283
+ name: "role",
2284
+ type: "bytes32",
2285
+ },
2286
+ {
2287
+ indexed: true,
2288
+ internalType: "address",
2289
+ name: "account",
2290
+ type: "address",
2291
+ },
2292
+ {
2293
+ indexed: true,
2294
+ internalType: "address",
2295
+ name: "sender",
2296
+ type: "address",
2297
+ },
2298
+ ],
2299
+ name: "RoleGranted",
2300
+ type: "event",
2301
+ },
2302
+ {
2303
+ anonymous: false,
2304
+ inputs: [
2305
+ {
2306
+ indexed: true,
2307
+ internalType: "bytes32",
2308
+ name: "role",
2309
+ type: "bytes32",
2310
+ },
2311
+ {
2312
+ indexed: true,
2313
+ internalType: "address",
2314
+ name: "account",
2315
+ type: "address",
2316
+ },
2317
+ {
2318
+ indexed: true,
2319
+ internalType: "address",
2320
+ name: "sender",
2321
+ type: "address",
2322
+ },
2323
+ ],
2324
+ name: "RoleRevoked",
2325
+ type: "event",
2326
+ },
2327
+ {
2328
+ anonymous: false,
2329
+ inputs: [
2330
+ {
2331
+ indexed: false,
2332
+ internalType: "address",
2333
+ name: "oldRegistry",
2334
+ type: "address",
2335
+ },
2336
+ {
2337
+ indexed: false,
2338
+ internalType: "address",
2339
+ name: "newRegistry",
2340
+ type: "address",
2341
+ },
2342
+ ],
2343
+ name: "RoyaltytAllowlistRegistryUpdated",
2344
+ type: "event",
2345
+ },
2346
+ {
2347
+ anonymous: false,
2348
+ inputs: [
2349
+ {
2350
+ indexed: true,
2351
+ internalType: "address",
2352
+ name: "from",
2353
+ type: "address",
2354
+ },
2355
+ {
2356
+ indexed: true,
2357
+ internalType: "address",
2358
+ name: "to",
2359
+ type: "address",
2360
+ },
2361
+ {
2362
+ indexed: true,
2363
+ internalType: "uint256",
2364
+ name: "tokenId",
2365
+ type: "uint256",
2366
+ },
2367
+ ],
2368
+ name: "Transfer",
2369
+ type: "event",
2370
+ },
2371
+ {
2372
+ inputs: [],
2373
+ name: "DEFAULT_ADMIN_ROLE",
2374
+ outputs: [
2375
+ {
2376
+ internalType: "bytes32",
2377
+ name: "",
2378
+ type: "bytes32",
2379
+ },
2380
+ ],
2381
+ stateMutability: "view",
2382
+ type: "function",
2383
+ },
2384
+ {
2385
+ inputs: [],
2386
+ name: "MINTER_ROLE",
2387
+ outputs: [
2388
+ {
2389
+ internalType: "bytes32",
2390
+ name: "",
2391
+ type: "bytes32",
2392
+ },
2393
+ ],
2394
+ stateMutability: "view",
2395
+ type: "function",
2396
+ },
2397
+ {
2398
+ inputs: [
2399
+ {
2400
+ internalType: "address",
2401
+ name: "to",
2402
+ type: "address",
2403
+ },
2404
+ {
2405
+ internalType: "uint256",
2406
+ name: "tokenId",
2407
+ type: "uint256",
2408
+ },
2409
+ ],
2410
+ name: "approve",
2411
+ outputs: [],
2412
+ stateMutability: "nonpayable",
2413
+ type: "function",
2414
+ },
2415
+ {
2416
+ inputs: [
2417
+ {
2418
+ internalType: "address",
2419
+ name: "owner",
2420
+ type: "address",
2421
+ },
2422
+ ],
2423
+ name: "balanceOf",
2424
+ outputs: [
2425
+ {
2426
+ internalType: "uint256",
2427
+ name: "",
2428
+ type: "uint256",
2429
+ },
2430
+ ],
2431
+ stateMutability: "view",
2432
+ type: "function",
2433
+ },
2434
+ {
2435
+ inputs: [],
2436
+ name: "baseURI",
2437
+ outputs: [
2438
+ {
2439
+ internalType: "string",
2440
+ name: "",
2441
+ type: "string",
2442
+ },
2443
+ ],
2444
+ stateMutability: "view",
2445
+ type: "function",
2446
+ },
2447
+ {
2448
+ inputs: [
2449
+ {
2450
+ internalType: "uint256",
2451
+ name: "tokenId",
2452
+ type: "uint256",
2453
+ },
2454
+ ],
2455
+ name: "burn",
2456
+ outputs: [],
2457
+ stateMutability: "nonpayable",
2458
+ type: "function",
2459
+ },
2460
+ {
2461
+ inputs: [],
2462
+ name: "contractURI",
2463
+ outputs: [
2464
+ {
2465
+ internalType: "string",
2466
+ name: "",
2467
+ type: "string",
2468
+ },
2469
+ ],
2470
+ stateMutability: "view",
2471
+ type: "function",
2472
+ },
2473
+ {
2474
+ inputs: [],
2475
+ name: "getAdmins",
2476
+ outputs: [
2477
+ {
2478
+ internalType: "address[]",
2479
+ name: "",
2480
+ type: "address[]",
2481
+ },
2482
+ ],
2483
+ stateMutability: "view",
2484
+ type: "function",
2485
+ },
2486
+ {
2487
+ inputs: [
2488
+ {
2489
+ internalType: "uint256",
2490
+ name: "tokenId",
2491
+ type: "uint256",
2492
+ },
2493
+ ],
2494
+ name: "getApproved",
2495
+ outputs: [
2496
+ {
2497
+ internalType: "address",
2498
+ name: "",
2499
+ type: "address",
2500
+ },
2501
+ ],
2502
+ stateMutability: "view",
2503
+ type: "function",
2504
+ },
2505
+ {
2506
+ inputs: [
2507
+ {
2508
+ internalType: "bytes32",
2509
+ name: "role",
2510
+ type: "bytes32",
2511
+ },
2512
+ ],
2513
+ name: "getRoleAdmin",
2514
+ outputs: [
2515
+ {
2516
+ internalType: "bytes32",
2517
+ name: "",
2518
+ type: "bytes32",
2519
+ },
2520
+ ],
2521
+ stateMutability: "view",
2522
+ type: "function",
2523
+ },
2524
+ {
2525
+ inputs: [
2526
+ {
2527
+ internalType: "bytes32",
2528
+ name: "role",
2529
+ type: "bytes32",
2530
+ },
2531
+ {
2532
+ internalType: "uint256",
2533
+ name: "index",
2534
+ type: "uint256",
2535
+ },
2536
+ ],
2537
+ name: "getRoleMember",
2538
+ outputs: [
2539
+ {
2540
+ internalType: "address",
2541
+ name: "",
2542
+ type: "address",
2543
+ },
2544
+ ],
2545
+ stateMutability: "view",
2546
+ type: "function",
2547
+ },
2548
+ {
2549
+ inputs: [
2550
+ {
2551
+ internalType: "bytes32",
2552
+ name: "role",
2553
+ type: "bytes32",
2554
+ },
2555
+ ],
2556
+ name: "getRoleMemberCount",
2557
+ outputs: [
2558
+ {
2559
+ internalType: "uint256",
2560
+ name: "",
2561
+ type: "uint256",
2562
+ },
2563
+ ],
2564
+ stateMutability: "view",
2565
+ type: "function",
2566
+ },
2567
+ {
2568
+ inputs: [
2569
+ {
2570
+ internalType: "address",
2571
+ name: "user",
2572
+ type: "address",
2573
+ },
2574
+ ],
2575
+ name: "grantMinterRole",
2576
+ outputs: [],
2577
+ stateMutability: "nonpayable",
2578
+ type: "function",
2579
+ },
2580
+ {
2581
+ inputs: [
2582
+ {
2583
+ internalType: "bytes32",
2584
+ name: "role",
2585
+ type: "bytes32",
2586
+ },
2587
+ {
2588
+ internalType: "address",
2589
+ name: "account",
2590
+ type: "address",
2591
+ },
2592
+ ],
2593
+ name: "grantRole",
2594
+ outputs: [],
2595
+ stateMutability: "nonpayable",
2596
+ type: "function",
2597
+ },
2598
+ {
2599
+ inputs: [
2600
+ {
2601
+ internalType: "bytes32",
2602
+ name: "role",
2603
+ type: "bytes32",
2604
+ },
2605
+ {
2606
+ internalType: "address",
2607
+ name: "account",
2608
+ type: "address",
2609
+ },
2610
+ ],
2611
+ name: "hasRole",
2612
+ outputs: [
2613
+ {
2614
+ internalType: "bool",
2615
+ name: "",
2616
+ type: "bool",
2617
+ },
2618
+ ],
2619
+ stateMutability: "view",
2620
+ type: "function",
2621
+ },
2622
+ {
2623
+ inputs: [
2624
+ {
2625
+ internalType: "address",
2626
+ name: "owner",
2627
+ type: "address",
2628
+ },
2629
+ {
2630
+ internalType: "address",
2631
+ name: "operator",
2632
+ type: "address",
2633
+ },
2634
+ ],
2635
+ name: "isApprovedForAll",
2636
+ outputs: [
2637
+ {
2638
+ internalType: "bool",
2639
+ name: "",
2640
+ type: "bool",
2641
+ },
2642
+ ],
2643
+ stateMutability: "view",
2644
+ type: "function",
2645
+ },
2646
+ {
2647
+ inputs: [
2648
+ {
2649
+ internalType: "address",
2650
+ name: "to",
2651
+ type: "address",
2652
+ },
2653
+ {
2654
+ internalType: "uint256",
2655
+ name: "amount",
2656
+ type: "uint256",
2657
+ },
2658
+ ],
2659
+ name: "mint",
2660
+ outputs: [],
2661
+ stateMutability: "nonpayable",
2662
+ type: "function",
2663
+ },
2664
+ {
2665
+ inputs: [],
2666
+ name: "name",
2667
+ outputs: [
2668
+ {
2669
+ internalType: "string",
2670
+ name: "",
2671
+ type: "string",
2672
+ },
2673
+ ],
2674
+ stateMutability: "view",
2675
+ type: "function",
2676
+ },
2677
+ {
2678
+ inputs: [
2679
+ {
2680
+ internalType: "uint256",
2681
+ name: "tokenId",
2682
+ type: "uint256",
2683
+ },
2684
+ ],
2685
+ name: "ownerOf",
2686
+ outputs: [
2687
+ {
2688
+ internalType: "address",
2689
+ name: "",
2690
+ type: "address",
2691
+ },
2692
+ ],
2693
+ stateMutability: "view",
2694
+ type: "function",
2695
+ },
2696
+ {
2697
+ inputs: [
2698
+ {
2699
+ internalType: "bytes32",
2700
+ name: "role",
2701
+ type: "bytes32",
2702
+ },
2703
+ {
2704
+ internalType: "address",
2705
+ name: "account",
2706
+ type: "address",
2707
+ },
2708
+ ],
2709
+ name: "renounceRole",
2710
+ outputs: [],
2711
+ stateMutability: "nonpayable",
2712
+ type: "function",
2713
+ },
2714
+ {
2715
+ inputs: [
2716
+ {
2717
+ internalType: "address",
2718
+ name: "user",
2719
+ type: "address",
2720
+ },
2721
+ ],
2722
+ name: "revokeMinterRole",
2723
+ outputs: [],
2724
+ stateMutability: "nonpayable",
2725
+ type: "function",
2726
+ },
2727
+ {
2728
+ inputs: [
2729
+ {
2730
+ internalType: "bytes32",
2731
+ name: "role",
2732
+ type: "bytes32",
2733
+ },
2734
+ {
2735
+ internalType: "address",
2736
+ name: "account",
2737
+ type: "address",
2738
+ },
2739
+ ],
2740
+ name: "revokeRole",
2741
+ outputs: [],
2742
+ stateMutability: "nonpayable",
2743
+ type: "function",
2744
+ },
2745
+ {
2746
+ inputs: [],
2747
+ name: "royaltyAllowlist",
2748
+ outputs: [
2749
+ {
2750
+ internalType: "contract IRoyaltyAllowlist",
2751
+ name: "",
2752
+ type: "address",
2753
+ },
2754
+ ],
2755
+ stateMutability: "view",
2756
+ type: "function",
2757
+ },
2758
+ {
2759
+ inputs: [
2760
+ {
2761
+ internalType: "uint256",
2762
+ name: "_tokenId",
2763
+ type: "uint256",
2764
+ },
2765
+ {
2766
+ internalType: "uint256",
2767
+ name: "_salePrice",
2768
+ type: "uint256",
2769
+ },
2770
+ ],
2771
+ name: "royaltyInfo",
2772
+ outputs: [
2773
+ {
2774
+ internalType: "address",
2775
+ name: "",
2776
+ type: "address",
2777
+ },
2778
+ {
2779
+ internalType: "uint256",
2780
+ name: "",
2781
+ type: "uint256",
2782
+ },
2783
+ ],
2784
+ stateMutability: "view",
2785
+ type: "function",
2786
+ },
2787
+ {
2788
+ inputs: [
2789
+ {
2790
+ internalType: "address",
2791
+ name: "from",
2792
+ type: "address",
2793
+ },
2794
+ {
2795
+ internalType: "address",
2796
+ name: "to",
2797
+ type: "address",
2798
+ },
2799
+ {
2800
+ internalType: "uint256",
2801
+ name: "tokenId",
2802
+ type: "uint256",
2803
+ },
2804
+ ],
2805
+ name: "safeTransferFrom",
2806
+ outputs: [],
2807
+ stateMutability: "nonpayable",
2808
+ type: "function",
2809
+ },
2810
+ {
2811
+ inputs: [
2812
+ {
2813
+ internalType: "address",
2814
+ name: "from",
2815
+ type: "address",
2816
+ },
2817
+ {
2818
+ internalType: "address",
2819
+ name: "to",
2820
+ type: "address",
2821
+ },
2822
+ {
2823
+ internalType: "uint256",
2824
+ name: "tokenId",
2825
+ type: "uint256",
2826
+ },
2827
+ {
2828
+ internalType: "bytes",
2829
+ name: "data",
2830
+ type: "bytes",
2831
+ },
2832
+ ],
2833
+ name: "safeTransferFrom",
2834
+ outputs: [],
2835
+ stateMutability: "nonpayable",
2836
+ type: "function",
2837
+ },
2838
+ {
2839
+ inputs: [
2840
+ {
2841
+ internalType: "address",
2842
+ name: "operator",
2843
+ type: "address",
2844
+ },
2845
+ {
2846
+ internalType: "bool",
2847
+ name: "approved",
2848
+ type: "bool",
2849
+ },
2850
+ ],
2851
+ name: "setApprovalForAll",
2852
+ outputs: [],
2853
+ stateMutability: "nonpayable",
2854
+ type: "function",
2855
+ },
2856
+ {
2857
+ inputs: [
2858
+ {
2859
+ internalType: "string",
2860
+ name: "baseURI_",
2861
+ type: "string",
2862
+ },
2863
+ ],
2864
+ name: "setBaseURI",
2865
+ outputs: [],
2866
+ stateMutability: "nonpayable",
2867
+ type: "function",
2868
+ },
2869
+ {
2870
+ inputs: [
2871
+ {
2872
+ internalType: "string",
2873
+ name: "_contractURI",
2874
+ type: "string",
2875
+ },
2876
+ ],
2877
+ name: "setContractURI",
2878
+ outputs: [],
2879
+ stateMutability: "nonpayable",
2880
+ type: "function",
2881
+ },
2882
+ {
2883
+ inputs: [
2884
+ {
2885
+ internalType: "address",
2886
+ name: "_royaltyAllowlist",
2887
+ type: "address",
2888
+ },
2889
+ ],
2890
+ name: "setRoyaltyAllowlistRegistry",
2891
+ outputs: [],
2892
+ stateMutability: "nonpayable",
2893
+ type: "function",
2894
+ },
2895
+ {
2896
+ inputs: [
2897
+ {
2898
+ internalType: "bytes4",
2899
+ name: "interfaceId",
2900
+ type: "bytes4",
2901
+ },
2902
+ ],
2903
+ name: "supportsInterface",
2904
+ outputs: [
2905
+ {
2906
+ internalType: "bool",
2907
+ name: "",
2908
+ type: "bool",
2909
+ },
2910
+ ],
2911
+ stateMutability: "view",
2912
+ type: "function",
2913
+ },
2914
+ {
2915
+ inputs: [],
2916
+ name: "symbol",
2917
+ outputs: [
2918
+ {
2919
+ internalType: "string",
2920
+ name: "",
2921
+ type: "string",
2922
+ },
2923
+ ],
2924
+ stateMutability: "view",
2925
+ type: "function",
2926
+ },
2927
+ {
2928
+ inputs: [
2929
+ {
2930
+ internalType: "uint256",
2931
+ name: "index",
2932
+ type: "uint256",
2933
+ },
2934
+ ],
2935
+ name: "tokenByIndex",
2936
+ outputs: [
2937
+ {
2938
+ internalType: "uint256",
2939
+ name: "",
2940
+ type: "uint256",
2941
+ },
2942
+ ],
2943
+ stateMutability: "view",
2944
+ type: "function",
2945
+ },
2946
+ {
2947
+ inputs: [
2948
+ {
2949
+ internalType: "address",
2950
+ name: "owner",
2951
+ type: "address",
2952
+ },
2953
+ {
2954
+ internalType: "uint256",
2955
+ name: "index",
2956
+ type: "uint256",
2957
+ },
2958
+ ],
2959
+ name: "tokenOfOwnerByIndex",
2960
+ outputs: [
2961
+ {
2962
+ internalType: "uint256",
2963
+ name: "",
2964
+ type: "uint256",
2965
+ },
2966
+ ],
2967
+ stateMutability: "view",
2968
+ type: "function",
2969
+ },
2970
+ {
2971
+ inputs: [
2972
+ {
2973
+ internalType: "uint256",
2974
+ name: "tokenId",
2975
+ type: "uint256",
2976
+ },
2977
+ ],
2978
+ name: "tokenURI",
2979
+ outputs: [
2980
+ {
2981
+ internalType: "string",
2982
+ name: "",
2983
+ type: "string",
2984
+ },
2985
+ ],
2986
+ stateMutability: "view",
2987
+ type: "function",
2988
+ },
2989
+ {
2990
+ inputs: [],
2991
+ name: "totalSupply",
2992
+ outputs: [
2993
+ {
2994
+ internalType: "uint256",
2995
+ name: "",
2996
+ type: "uint256",
2997
+ },
2998
+ ],
2999
+ stateMutability: "view",
3000
+ type: "function",
3001
+ },
3002
+ {
3003
+ inputs: [
3004
+ {
3005
+ internalType: "address",
3006
+ name: "from",
3007
+ type: "address",
3008
+ },
3009
+ {
3010
+ internalType: "address",
3011
+ name: "to",
3012
+ type: "address",
3013
+ },
3014
+ {
3015
+ internalType: "uint256",
3016
+ name: "tokenId",
3017
+ type: "uint256",
3018
+ },
3019
+ ],
3020
+ name: "transferFrom",
3021
+ outputs: [],
3022
+ stateMutability: "nonpayable",
3023
+ type: "function",
3024
+ },
3025
+ ];
3026
+ class ImmutableERC721Base__factory {
3027
+ static abi = _abi;
3028
+ static createInterface() {
3029
+ return new ethers.utils.Interface(_abi);
3030
+ }
3031
+ static connect(address, signerOrProvider) {
3032
+ return new ethers.Contract(address, _abi, signerOrProvider);
3033
+ }
3034
+ }
3035
+
3036
+ class ERC721Factory {
3037
+ erc721;
3038
+ constructor(contractAddress, provider) {
3039
+ this.erc721 = ImmutableERC721Base__factory.connect(contractAddress, provider);
3040
+ }
3041
+ create() {
3042
+ return new ERC721(this.erc721);
3043
+ }
3044
+ }
3045
+
3046
+ function getOrderComponentsFromMessage(orderMessage) {
3047
+ const data = JSON.parse(orderMessage);
3048
+ const orderComponents = data.message;
3049
+ orderComponents.salt = ethers.BigNumber.from(orderComponents.salt).toHexString();
3050
+ return orderComponents;
3051
+ }
3052
+
3053
+ // Add 20% more gas than estimate to prevent out of gas errors
3054
+ // This can always be overwritten by the user signing the transaction
3055
+ async function prepareTransaction(transactionMethods) {
3056
+ const transaction = await transactionMethods.buildTransaction();
3057
+ transaction.gasLimit = await transactionMethods.estimateGas();
3058
+ transaction.gasLimit = transaction.gasLimit
3059
+ .add(transaction.gasLimit.div(5));
3060
+ return transaction;
3061
+ }
3062
+
3063
+ function mapImmutableOrderToSeaportOrderComponents(order, counter, zoneAddress) {
3064
+ const considerationItems = order.buy.map((buyItem) => ({
3065
+ startAmount: buyItem.start_amount,
3066
+ endAmount: buyItem.start_amount,
3067
+ itemType: buyItem.item_type === 'ERC20' ? constants.ItemType.ERC20 : constants.ItemType.NATIVE,
3068
+ recipient: order.account_address,
3069
+ token: buyItem.contract_address || ethers.constants.AddressZero,
3070
+ identifierOrCriteria: '0',
3071
+ }));
3072
+ const fees = order.buy_fees.map((fee) => ({
3073
+ startAmount: fee.amount,
3074
+ endAmount: fee.amount,
3075
+ itemType: order.buy[0].item_type === 'ERC20' ? constants.ItemType.ERC20 : constants.ItemType.NATIVE,
3076
+ recipient: fee.recipient,
3077
+ token: order.buy[0].contract_address || ethers.constants.AddressZero,
3078
+ identifierOrCriteria: '0',
3079
+ }));
3080
+ return {
3081
+ conduitKey: ethers.constants.HashZero,
3082
+ consideration: [...considerationItems, ...fees],
3083
+ offer: order.sell.map((sellItem) => ({
3084
+ startAmount: '1',
3085
+ endAmount: '1',
3086
+ itemType: constants.ItemType.ERC721,
3087
+ token: sellItem.contract_address,
3088
+ identifierOrCriteria: sellItem.token_id,
3089
+ })),
3090
+ counter,
3091
+ endTime: Math.round(new Date(order.end_time).getTime() / 1000).toString(),
3092
+ startTime: Math.round(new Date(order.start_time).getTime() / 1000).toString(),
3093
+ salt: order.salt,
3094
+ offerer: order.account_address,
3095
+ zone: zoneAddress,
3096
+ totalOriginalConsiderationItems: 2,
3097
+ orderType: constants.OrderType.FULL_RESTRICTED,
3098
+ zoneHash: ethers.constants.HashZero,
3099
+ };
3100
+ }
3101
+
3102
+ class Seaport {
3103
+ seaport;
3104
+ provider;
3105
+ seaportContractAddress;
3106
+ zoneContractAddress;
3107
+ constructor(seaport, provider, seaportContractAddress, zoneContractAddress) {
3108
+ this.seaport = seaport;
3109
+ this.provider = provider;
3110
+ this.seaportContractAddress = seaportContractAddress;
3111
+ this.zoneContractAddress = zoneContractAddress;
3112
+ }
3113
+ async prepareSeaportOrder(offerer, listingItem, considerationItem, royaltyInfo, orderStart, orderExpiry) {
3114
+ const { actions } = await this.createSeaportOrder(offerer, listingItem, considerationItem, royaltyInfo, orderStart, orderExpiry);
3115
+ let approvalTransaction;
3116
+ const approvalAction = actions
3117
+ .find((action) => action.type === 'approval');
3118
+ if (approvalAction) {
3119
+ approvalTransaction = await prepareTransaction(approvalAction.transactionMethods);
3120
+ }
3121
+ const createAction = actions
3122
+ .find((action) => action.type === 'create');
3123
+ if (!createAction) {
3124
+ throw new Error('No create order action found');
3125
+ }
3126
+ const orderMessageToSign = await createAction.getMessageToSign();
3127
+ const orderComponents = getOrderComponentsFromMessage(orderMessageToSign);
3128
+ return {
3129
+ unsignedApprovalTransaction: approvalTransaction,
3130
+ typedOrderMessageForSigning: await this.getTypedDataFromOrderComponents(orderComponents),
3131
+ orderComponents,
3132
+ orderHash: await this.seaport.getOrderHash(orderComponents),
3133
+ };
3134
+ }
3135
+ async fulfilOrder(order, account) {
3136
+ const orderComponents = await this.mapImmutableOrderToSeaportOrderComponents(order);
3137
+ const { actions } = await this.seaport.fulfillOrders({
3138
+ accountAddress: account,
3139
+ fulfillOrderDetails: [{
3140
+ order: {
3141
+ parameters: orderComponents,
3142
+ signature: order.signature,
3143
+ },
3144
+ }],
3145
+ });
3146
+ let approvalTransaction;
3147
+ const approvalAction = actions
3148
+ .find((action) => action.type === 'approval');
3149
+ if (approvalAction) {
3150
+ approvalTransaction = await prepareTransaction(approvalAction.transactionMethods);
3151
+ }
3152
+ const fulfillmentAction = actions
3153
+ .find((action) => action.type === 'exchange');
3154
+ if (!fulfillmentAction) {
3155
+ throw new Error('No exchange action found');
3156
+ }
3157
+ const fulfillmentTransaction = await prepareTransaction(fulfillmentAction.transactionMethods);
3158
+ return {
3159
+ unsignedApprovalTransaction: approvalTransaction,
3160
+ unsignedFulfillmentTransaction: fulfillmentTransaction,
3161
+ };
3162
+ }
3163
+ async cancelOrder(order, account) {
3164
+ const orderComponents = await this.mapImmutableOrderToSeaportOrderComponents(order);
3165
+ const cancellationTransaction = await this.seaport.cancelOrders([orderComponents], account);
3166
+ return prepareTransaction(cancellationTransaction);
3167
+ }
3168
+ async mapImmutableOrderToSeaportOrderComponents(order) {
3169
+ const counterForOfferer = await this.seaport.getCounter(order.account_address);
3170
+ return mapImmutableOrderToSeaportOrderComponents(order, counterForOfferer.toString(), this.zoneContractAddress);
3171
+ }
3172
+ createSeaportOrder(offerer, listingItem, considerationItem, royaltyInfo, orderStart, orderExpiry) {
3173
+ return this.seaport.createOrder({
3174
+ allowPartialFills: false,
3175
+ offer: [
3176
+ {
3177
+ itemType: constants.ItemType.ERC721,
3178
+ token: listingItem.contractAddress,
3179
+ identifier: listingItem.tokenId,
3180
+ },
3181
+ ],
3182
+ consideration: [
3183
+ {
3184
+ token: considerationItem.type === 'ERC20' ? considerationItem.contractAddress : undefined,
3185
+ amount: considerationItem.amount,
3186
+ recipient: offerer,
3187
+ },
3188
+ {
3189
+ token: considerationItem.type === 'ERC20' ? considerationItem.contractAddress : undefined,
3190
+ amount: royaltyInfo.amountRequired,
3191
+ recipient: royaltyInfo.recipient,
3192
+ },
3193
+ ],
3194
+ startTime: (orderStart.getTime() / 1000).toFixed(0),
3195
+ endTime: (orderExpiry.getTime() / 1000).toFixed(0),
3196
+ zone: this.zoneContractAddress,
3197
+ restrictedByZone: true,
3198
+ }, offerer);
3199
+ }
3200
+ async getTypedDataFromOrderComponents(orderComponents) {
3201
+ const { chainId } = await this.provider.getNetwork();
3202
+ const domainData = {
3203
+ name: constants.SEAPORT_CONTRACT_NAME,
3204
+ version: constants.SEAPORT_CONTRACT_VERSION_V1_4,
3205
+ chainId,
3206
+ verifyingContract: this.seaportContractAddress,
3207
+ };
3208
+ return {
3209
+ domain: domainData,
3210
+ types: constants.EIP_712_ORDER_TYPE,
3211
+ value: orderComponents,
3212
+ };
3213
+ }
3214
+ }
3215
+
3216
+ class SeaportFactory {
3217
+ seaportContractAddress;
3218
+ zoneContractAddress;
3219
+ provider;
3220
+ seaport;
3221
+ constructor(seaportContractAddress, zoneContractAddress, provider) {
3222
+ this.seaportContractAddress = seaportContractAddress;
3223
+ this.zoneContractAddress = zoneContractAddress;
3224
+ this.provider = provider;
3225
+ this.seaport = new seaportJs.Seaport(provider, {
3226
+ seaportVersion: '1.4',
3227
+ balanceAndApprovalChecksOnOrderCreation: true,
3228
+ overrides: {
3229
+ contractAddress: seaportContractAddress,
3230
+ },
3231
+ });
3232
+ }
3233
+ create() {
3234
+ return new Seaport(this.seaport, this.provider, this.seaportContractAddress, this.zoneContractAddress);
3235
+ }
3236
+ }
3237
+
3238
+ /**
3239
+ * zkEVM orderbook SDK
3240
+ * @constructor
3241
+ * @param {OrderbookModuleConfiguration} config - Configuration for Immutable services.
3242
+ */
3243
+ class Orderbook {
3244
+ config;
3245
+ apiClient;
3246
+ seaport;
3247
+ constructor(config) {
3248
+ this.config = config;
3249
+ // TODO: Move endpoint lookup to a map based on env. Just using override to get dev started
3250
+ const apiEndpoint = config.overrides?.apiEndpoint;
3251
+ if (!apiEndpoint) {
3252
+ throw new Error('API endpoint must be provided as an override');
3253
+ }
3254
+ // TODO: Move chainId lookup to a map based on env. Just using override to get dev started
3255
+ const chainId = config.overrides?.chainId;
3256
+ if (!chainId) {
3257
+ throw new Error('ChainID must be provided as an override');
3258
+ }
3259
+ this.apiClient = new ImmutableApiClientFactory(apiEndpoint, chainId).create();
3260
+ this.seaport = new SeaportFactory(this.config.seaportContractAddress, this.config.zoneContractAddress, this.config.provider).create();
3261
+ }
3262
+ /**
3263
+ * Get an order by ID
3264
+ * @param {string} orderId - The orderId to find.
3265
+ * @return {Order} The returned order.
3266
+ */
3267
+ getOrder(orderId) {
3268
+ return this.apiClient.getOrder(orderId);
3269
+ }
3270
+ /**
3271
+ * Get required transactions and messages for signing prior to creating a listing
3272
+ * through the createOrder method
3273
+ * @param {PrepareListingParams} prepareListingParams - Details about the listing to be created.
3274
+ * @return {PrepareListingResponse} PrepareListingResponse includes
3275
+ * the unsigned approval transaction, the typed order message for signing and
3276
+ * the order components that can be submitted to `createOrder` with a signature.
3277
+ */
3278
+ async prepareListing({ offerer, listingItem, considerationItem, orderExpiry, }) {
3279
+ const erc721 = new ERC721Factory(listingItem.contractAddress, this.config.provider).create();
3280
+ const royaltyInfo = await erc721.royaltyInfo(listingItem.tokenId, considerationItem.amount);
3281
+ return this.seaport.prepareSeaportOrder(offerer, listingItem, considerationItem, royaltyInfo,
3282
+ // Default order start to now
3283
+ new Date(),
3284
+ // Default order expiry to 2 years from now
3285
+ orderExpiry || new Date(Date.now() + 1000 * 60 * 60 * 24 * 365 * 2));
3286
+ }
3287
+ /**
3288
+ * Create an order
3289
+ * @param {CreateOrderParams} createOrderParams - create an order with the given params.
3290
+ * @return {Order} The order created in the Immutable services.
3291
+ */
3292
+ createOrder(createOrderParams) {
3293
+ return this.apiClient.createOrder(createOrderParams);
3294
+ }
3295
+ /**
3296
+ * Get unsigned transactions that can be submitted to fulfil an open order. If the approval
3297
+ * transaction exists it must be signed and submitted to the chain before the fulfilment
3298
+ * transaction can be submitted or it will be reverted.
3299
+ * @param {string} orderId - The orderId to fulfil.
3300
+ * @param {string} fulfillerAddress - The address of the account fulfilling the order.
3301
+ * @return {FulfilOrderResponse} Approval and fulfilment transactions.
3302
+ */
3303
+ async fulfillOrder(orderId, fulfillerAddress) {
3304
+ const order = await this.apiClient.getOrder(orderId);
3305
+ if (order.status !== Order.status.ACTIVE) {
3306
+ throw new Error(`Cannot fulfil order that is not active. Current status: ${order.status}`);
3307
+ }
3308
+ return this.seaport.fulfilOrder(order, fulfillerAddress);
3309
+ }
3310
+ /**
3311
+ * Get an unsigned cancel order transaction. Orders can only be cancelled by
3312
+ * the account that created them.
3313
+ * @param {string} orderId - The orderId to cancel.
3314
+ * @param {string} accountAddress - The address of the account cancelling the order.
3315
+ * @return {CancelOrderResponse} The unsigned cancel order transaction
3316
+ */
3317
+ async cancelOrder(orderId, accountAddress) {
3318
+ const order = await this.apiClient.getOrder(orderId);
3319
+ if (order.status !== Order.status.ACTIVE
3320
+ && order.status !== Order.status.INACTIVE
3321
+ && order.status !== Order.status.PENDING) {
3322
+ throw new Error(`Cannot cancel order with status ${order.status}`);
3323
+ }
3324
+ if (order.account_address !== accountAddress.toLowerCase()) {
3325
+ throw new Error(`Only account ${order.account_address} can cancel order ${orderId}`);
3326
+ }
3327
+ const cancelOrderTransaction = await this.seaport.cancelOrder(order, accountAddress);
3328
+ return { unsignedCancelOrderTransaction: cancelOrderTransaction };
3329
+ }
3330
+ }
3331
+
3332
+ const module$1 = 'orderbook';
3333
+
3334
+ function isChainValid(chainID, config) {
3335
+ return chainID === config.ethConfiguration.chainID;
3336
+ }
3337
+ async function validateChain(signer, config) {
3338
+ const chainID = await signer.getChainId();
3339
+ if (!isChainValid(chainID, config)) {
3340
+ throw new Error('The wallet used for this operation is not connected to the correct network.');
3341
+ }
3342
+ }
3343
+
3344
+ async function transfer({ signers: { ethSigner, starkSigner }, request, config, }) {
3345
+ await validateChain(ethSigner, config.immutableXConfig);
3346
+ const ethAddress = await ethSigner.getAddress();
3347
+ const transfersApi = new coreSdk.TransfersApi(config.immutableXConfig.apiConfiguration);
3348
+ const transferAmount = request.type === 'ERC721' ? '1' : request.amount;
3349
+ const signableResult = await transfersApi.getSignableTransferV1({
3350
+ getSignableTransferRequest: {
3351
+ sender: ethAddress,
3352
+ token: convertToSignableToken(request),
3353
+ amount: transferAmount,
3354
+ receiver: request.receiver,
3355
+ },
3356
+ });
3357
+ const { signable_message: signableMessage, payload_hash: payloadHash } = signableResult.data;
3358
+ const ethSignature = await signRaw(signableMessage, ethSigner);
3359
+ const starkSignature = await starkSigner.signMessage(payloadHash);
3360
+ const transferSigningParams = {
3361
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
3362
+ sender_stark_key: signableResult.data.sender_stark_key,
3363
+ sender_vault_id: signableResult.data.sender_vault_id,
3364
+ receiver_stark_key: signableResult.data.receiver_stark_key,
3365
+ receiver_vault_id: signableResult.data.receiver_vault_id,
3366
+ asset_id: signableResult.data.asset_id,
3367
+ amount: signableResult.data.amount,
3368
+ nonce: signableResult.data.nonce,
3369
+ expiration_timestamp: signableResult.data.expiration_timestamp,
3370
+ stark_signature: starkSignature,
3371
+ };
3372
+ const response = await transfersApi.createTransferV1({
3373
+ createTransferRequest: transferSigningParams,
3374
+ xImxEthAddress: ethAddress,
3375
+ xImxEthSignature: ethSignature,
3376
+ });
3377
+ return {
3378
+ sent_signature: response?.data.sent_signature,
3379
+ status: response?.data.status?.toString(),
3380
+ time: response?.data.time,
3381
+ transfer_id: response?.data.transfer_id,
3382
+ };
3383
+ }
3384
+ async function batchTransfer({ signers: { ethSigner, starkSigner }, request, config, }) {
3385
+ await validateChain(ethSigner, config.immutableXConfig);
3386
+ const ethAddress = await ethSigner.getAddress();
3387
+ const transfersApi = new coreSdk.TransfersApi(config.immutableXConfig.apiConfiguration);
3388
+ const signableRequests = request.map((nftTransfer) => ({
3389
+ amount: '1',
3390
+ token: convertToSignableToken({
3391
+ type: 'ERC721',
3392
+ tokenId: nftTransfer.tokenId,
3393
+ tokenAddress: nftTransfer.tokenAddress,
3394
+ }),
3395
+ receiver: nftTransfer.receiver,
3396
+ }));
3397
+ const signableResult = await transfersApi.getSignableTransfer({
3398
+ getSignableTransferRequestV2: {
3399
+ sender_ether_key: ethAddress,
3400
+ signable_requests: signableRequests,
3401
+ },
3402
+ });
3403
+ const signableMessage = signableResult.data.signable_message;
3404
+ if (signableMessage === undefined) {
3405
+ throw new Error('Invalid response from Signable registration offchain');
3406
+ }
3407
+ const ethSignature = await signRaw(signableMessage, ethSigner);
3408
+ const requests = [];
3409
+ for (const resp of signableResult.data.signable_responses) {
3410
+ // TODO: remove once fixed
3411
+ // eslint-disable-next-line no-await-in-loop
3412
+ const starkSignature = await starkSigner.signMessage(resp.payload_hash);
3413
+ const req = {
3414
+ sender_vault_id: resp.sender_vault_id,
3415
+ receiver_stark_key: resp.receiver_stark_key,
3416
+ receiver_vault_id: resp.receiver_vault_id,
3417
+ asset_id: resp.asset_id,
3418
+ amount: resp.amount,
3419
+ nonce: resp.nonce,
3420
+ expiration_timestamp: resp.expiration_timestamp,
3421
+ stark_signature: starkSignature,
3422
+ };
3423
+ requests.push(req);
3424
+ }
3425
+ // TODO: throw error on missing payload hash?
3426
+ const transferSigningParams = {
3427
+ sender_stark_key: signableResult.data.sender_stark_key,
3428
+ requests,
3429
+ };
3430
+ const response = await transfersApi.createTransfer({
3431
+ createTransferRequestV2: transferSigningParams,
3432
+ xImxEthAddress: ethAddress,
3433
+ xImxEthSignature: ethSignature,
3434
+ });
3435
+ return {
3436
+ transfer_ids: response?.data.transfer_ids,
3437
+ };
3438
+ }
3439
+
3440
+ async function createOrder({ signers, request, config, }) {
3441
+ await validateChain(signers.ethSigner, config.immutableXConfig);
3442
+ const ethAddress = await signers.ethSigner.getAddress();
3443
+ const ordersApi = new coreSdk.OrdersApi(config.immutableXConfig.apiConfiguration);
3444
+ const amountSell = request.sell.type === 'ERC721' ? '1' : request.sell.amount;
3445
+ const amountBuy = request.buy.type === 'ERC721' ? '1' : request.buy.amount;
3446
+ const getSignableOrderRequest = {
3447
+ user: ethAddress,
3448
+ amount_buy: amountBuy,
3449
+ token_buy: convertToSignableToken(request.buy),
3450
+ amount_sell: amountSell,
3451
+ token_sell: convertToSignableToken(request.sell),
3452
+ fees: request.fees,
3453
+ expiration_timestamp: request.expiration_timestamp,
3454
+ };
3455
+ const getSignableOrderResponse = await ordersApi.getSignableOrder({
3456
+ getSignableOrderRequestV3: getSignableOrderRequest,
3457
+ });
3458
+ const { signable_message: signableMessage, payload_hash: payloadHash } = getSignableOrderResponse.data;
3459
+ const ethSignature = await signRaw(signableMessage, signers.ethSigner);
3460
+ const starkSignature = await signers.starkSigner.signMessage(payloadHash);
3461
+ const resp = getSignableOrderResponse.data;
3462
+ const orderParams = {
3463
+ createOrderRequest: {
3464
+ amount_buy: resp.amount_buy,
3465
+ amount_sell: resp.amount_sell,
3466
+ asset_id_buy: resp.asset_id_buy,
3467
+ asset_id_sell: resp.asset_id_sell,
3468
+ expiration_timestamp: resp.expiration_timestamp,
3469
+ include_fees: true,
3470
+ fees: request.fees,
3471
+ nonce: resp.nonce,
3472
+ stark_key: resp.stark_key,
3473
+ stark_signature: starkSignature,
3474
+ vault_id_buy: resp.vault_id_buy,
3475
+ vault_id_sell: resp.vault_id_sell,
3476
+ },
3477
+ xImxEthAddress: ethAddress,
3478
+ xImxEthSignature: ethSignature,
3479
+ };
3480
+ const createOrderResponse = await ordersApi.createOrder(orderParams);
3481
+ return {
3482
+ ...createOrderResponse.data,
3483
+ };
3484
+ }
3485
+ async function cancelOrder({ signers, request, config, }) {
3486
+ const ordersApi = new coreSdk.OrdersApi(config.immutableXConfig.apiConfiguration);
3487
+ const getSignableCancelOrderResponse = await ordersApi.getSignableCancelOrder({
3488
+ getSignableCancelOrderRequest: {
3489
+ order_id: request.order_id,
3490
+ },
3491
+ });
3492
+ const { signable_message: signableMessage, payload_hash: payloadHash } = getSignableCancelOrderResponse.data;
3493
+ const ethSignature = await signRaw(signableMessage, signers.ethSigner);
3494
+ const starkSignature = await signers.starkSigner.signMessage(payloadHash);
3495
+ const ethAddress = await signers.ethSigner.getAddress();
3496
+ const cancelOrderResponse = await ordersApi.cancelOrder({
3497
+ id: request.order_id.toString(),
3498
+ cancelOrderRequest: {
3499
+ order_id: request.order_id,
3500
+ stark_signature: starkSignature,
3501
+ },
3502
+ xImxEthAddress: ethAddress,
3503
+ xImxEthSignature: ethSignature,
3504
+ });
3505
+ return {
3506
+ order_id: cancelOrderResponse.data.order_id,
3507
+ status: cancelOrderResponse.data.status,
3508
+ };
3509
+ }
3510
+
3511
+ async function registerOffchain(signers, config) {
3512
+ await validateChain(signers.ethSigner, config.immutableXConfig);
3513
+ const usersApi = new coreSdk.UsersApi(config.immutableXConfig.apiConfiguration);
3514
+ const userAddress = await signers.ethSigner.getAddress();
3515
+ const starkPublicKey = await signers.starkSigner.getAddress();
3516
+ const signableResult = await usersApi.getSignableRegistrationOffchain({
3517
+ getSignableRegistrationRequest: {
3518
+ ether_key: userAddress,
3519
+ stark_key: starkPublicKey,
3520
+ },
3521
+ });
3522
+ const { signable_message: signableMessage, payload_hash: payloadHash } = signableResult.data;
3523
+ const ethSignature = await signRaw(signableMessage, signers.ethSigner);
3524
+ const starkSignature = await signers.starkSigner.signMessage(payloadHash);
3525
+ const registeredUser = await usersApi.registerUser({
3526
+ registerUserRequest: {
3527
+ eth_signature: ethSignature,
3528
+ ether_key: userAddress,
3529
+ stark_signature: starkSignature,
3530
+ stark_key: starkPublicKey,
3531
+ },
3532
+ });
3533
+ return registeredUser.data;
3534
+ }
3535
+ async function isRegisteredOnChain(starkPublicKey, ethSigner, config) {
3536
+ await validateChain(ethSigner, config.immutableXConfig);
3537
+ const registrationContract = coreSdk.Contracts.Registration.connect(config.immutableXConfig.ethConfiguration.registrationContractAddress, ethSigner);
3538
+ try {
3539
+ return await registrationContract.isRegistered(starkPublicKey);
3540
+ }
3541
+ catch (ex) {
3542
+ if (ex.reason === 'USER_UNREGISTERED') {
3543
+ return false;
3544
+ }
3545
+ throw ex;
3546
+ }
3547
+ }
3548
+ async function getSignableRegistrationOnchain(etherKey, starkPublicKey, usersApi) {
3549
+ const response = await usersApi.getSignableRegistration({
3550
+ getSignableRegistrationRequest: {
3551
+ ether_key: etherKey,
3552
+ stark_key: starkPublicKey,
3553
+ },
3554
+ });
3555
+ return {
3556
+ operator_signature: response.data.operator_signature,
3557
+ payload_hash: response.data.payload_hash,
3558
+ };
3559
+ }
3560
+
3561
+ const assertIsDefined = (value) => {
3562
+ if (value !== undefined)
3563
+ return value;
3564
+ throw new Error('undefined field exception');
3565
+ };
3566
+ async function prepareWithdrawalAction(params) {
3567
+ const { signers: { ethSigner, starkSigner }, type, config, } = params;
3568
+ await validateChain(ethSigner, params.config);
3569
+ const withdrawalsApi = new coreSdk.WithdrawalsApi(config.apiConfiguration);
3570
+ const withdrawalAmount = type === 'ERC721' ? '1' : params.amount;
3571
+ const signableWithdrawalResult = await withdrawalsApi.getSignableWithdrawal({
3572
+ getSignableWithdrawalRequest: {
3573
+ user: await ethSigner.getAddress(),
3574
+ token: convertToSignableToken(params),
3575
+ amount: withdrawalAmount,
3576
+ },
3577
+ });
3578
+ const { signable_message: signableMessage, payload_hash: payloadHash } = signableWithdrawalResult.data;
3579
+ const starkSignature = await starkSigner.signMessage(payloadHash);
3580
+ const { ethAddress, ethSignature } = await signMessage(signableMessage, ethSigner);
3581
+ const prepareWithdrawalResponse = await withdrawalsApi.createWithdrawal({
3582
+ createWithdrawalRequest: {
3583
+ stark_key: assertIsDefined(signableWithdrawalResult.data.stark_key),
3584
+ amount: withdrawalAmount,
3585
+ asset_id: assertIsDefined(signableWithdrawalResult.data.asset_id),
3586
+ vault_id: assertIsDefined(signableWithdrawalResult.data.vault_id),
3587
+ nonce: assertIsDefined(signableWithdrawalResult.data.nonce),
3588
+ stark_signature: starkSignature,
3589
+ },
3590
+ xImxEthAddress: ethAddress,
3591
+ xImxEthSignature: ethSignature,
3592
+ });
3593
+ return prepareWithdrawalResponse.data;
3594
+ }
3595
+
3596
+ async function getEncodeAssetInfo(assetType, tokenType, config, tokenData) {
3597
+ const encodingApi = new coreSdk.EncodingApi(config.apiConfiguration);
3598
+ const result = await encodingApi.encodeAsset({
3599
+ assetType,
3600
+ encodeAssetRequest: {
3601
+ token: {
3602
+ type: tokenType,
3603
+ ...(tokenData && { data: tokenData }),
3604
+ },
3605
+ },
3606
+ });
3607
+ return result.data;
3608
+ }
3609
+
3610
+ async function executeRegisterAndWithdrawERC20({ ethSigner, assetType, starkPublicKey, config, }) {
3611
+ const etherKey = await ethSigner.getAddress();
3612
+ const imxConfig = config.immutableXConfig;
3613
+ const usersApi = new coreSdk.UsersApi(imxConfig.apiConfiguration);
3614
+ const signableResult = await getSignableRegistrationOnchain(etherKey, starkPublicKey, usersApi);
3615
+ const contract = coreSdk.Contracts.Registration.connect(config.immutableXConfig.ethConfiguration.registrationContractAddress, ethSigner);
3616
+ const populatedTransaction = await contract.populateTransaction.registerAndWithdraw(etherKey, starkPublicKey, signableResult.operator_signature, assetType);
3617
+ return ethSigner.sendTransaction(populatedTransaction);
3618
+ }
3619
+ async function executeWithdrawERC20(ethSigner, assetType, starkPublicKey, config) {
3620
+ const contract = coreSdk.Contracts.Core.connect(config.ethConfiguration.coreContractAddress, ethSigner);
3621
+ const populatedTransaction = await contract.populateTransaction.withdraw(starkPublicKey, assetType);
3622
+ return ethSigner.sendTransaction(populatedTransaction);
3623
+ }
3624
+ async function completeERC20WithdrawalAction({ ethSigner, starkPublicKey, token, config, }) {
3625
+ await validateChain(ethSigner, config.immutableXConfig);
3626
+ const imxConfig = config.immutableXConfig;
3627
+ const assetType = await getEncodeAssetInfo('asset', 'ERC20', imxConfig, {
3628
+ token_address: token.tokenAddress,
3629
+ });
3630
+ const isRegistered = await isRegisteredOnChain(starkPublicKey, ethSigner, config);
3631
+ if (!isRegistered) {
3632
+ return executeRegisterAndWithdrawERC20({
3633
+ ethSigner,
3634
+ assetType: assetType.asset_type,
3635
+ starkPublicKey,
3636
+ config,
3637
+ });
3638
+ }
3639
+ return executeWithdrawERC20(ethSigner, assetType.asset_type, starkPublicKey, imxConfig);
3640
+ }
3641
+
3642
+ async function executeWithdrawMintableERC721(ethSigner, assetType, starkPublicKey, mintingBlob, config) {
3643
+ const contract = coreSdk.Contracts.Core.connect(config.ethConfiguration.coreContractAddress, ethSigner);
3644
+ const populatedTransaction = await contract.populateTransaction.withdrawAndMint(starkPublicKey, assetType, mintingBlob);
3645
+ return ethSigner.sendTransaction(populatedTransaction);
3646
+ }
3647
+ async function executeRegisterAndWithdrawMintableERC721(ethSigner, assetType, starkPublicKey, mintingBlob, config) {
3648
+ const etherKey = await ethSigner.getAddress();
3649
+ const usersApi = new coreSdk.UsersApi(config.apiConfiguration);
3650
+ const signableResult = await getSignableRegistrationOnchain(etherKey, starkPublicKey, usersApi);
3651
+ const contract = coreSdk.Contracts.Registration.connect(config.ethConfiguration.registrationContractAddress, ethSigner);
3652
+ const populatedTransaction = await contract.populateTransaction.regsiterAndWithdrawAndMint(etherKey, starkPublicKey, signableResult.operator_signature, assetType, mintingBlob);
3653
+ return ethSigner.sendTransaction(populatedTransaction);
3654
+ }
3655
+ function getMintingBlob(token) {
3656
+ const { id } = token.data;
3657
+ const blueprint = token.data.blueprint || '';
3658
+ return encUtils__namespace.sanitizeHex(encUtils__namespace.utf8ToHex(`{${id}}:{${blueprint}}`));
3659
+ }
3660
+ async function completeMintableERC721Withdrawal(ethSigner, starkPublicKey, token, config) {
3661
+ const imxConfig = config.immutableXConfig;
3662
+ const assetType = await getEncodeAssetInfo('mintable-asset', 'ERC721', imxConfig, {
3663
+ id: token.data.id,
3664
+ token_address: token.data.tokenAddress,
3665
+ ...(token.data.blueprint && { blueprint: token.data.blueprint }),
3666
+ });
3667
+ const mintingBlob = getMintingBlob(token);
3668
+ const isRegistered = await isRegisteredOnChain(starkPublicKey, ethSigner, config);
3669
+ if (!isRegistered) {
3670
+ return executeRegisterAndWithdrawMintableERC721(ethSigner, assetType.asset_type, starkPublicKey, mintingBlob, imxConfig);
3671
+ }
3672
+ return executeWithdrawMintableERC721(ethSigner, assetType.asset_type, starkPublicKey, mintingBlob, imxConfig);
3673
+ }
3674
+ async function executeRegisterAndWithdrawERC721(ethSigner, assetType, starkPublicKey, tokenId, config) {
3675
+ const etherKey = await ethSigner.getAddress();
3676
+ const usersApi = new coreSdk.UsersApi(config.apiConfiguration);
3677
+ const signableResult = await getSignableRegistrationOnchain(etherKey, starkPublicKey, usersApi);
3678
+ const contract = coreSdk.Contracts.Registration.connect(config.ethConfiguration.registrationContractAddress, ethSigner);
3679
+ const populatedTransaction = await contract.populateTransaction.registerAndWithdrawNft(etherKey, starkPublicKey, signableResult.operator_signature, assetType, tokenId);
3680
+ return ethSigner.sendTransaction(populatedTransaction);
3681
+ }
3682
+ async function executeWithdrawERC721(ethSigner, assetType, starkPublicKey, tokenId, config) {
3683
+ const contract = coreSdk.Contracts.Core.connect(config.ethConfiguration.coreContractAddress, ethSigner);
3684
+ const populatedTransaction = await contract.populateTransaction.withdrawNft(starkPublicKey, assetType, tokenId);
3685
+ return ethSigner.sendTransaction(populatedTransaction);
3686
+ }
3687
+ async function completeERC721Withdrawal(ethSigner, starkPublicKey, token, config) {
3688
+ const imxConfig = config.immutableXConfig;
3689
+ const assetType = await getEncodeAssetInfo('asset', 'ERC721', imxConfig, {
3690
+ token_id: token.tokenId,
3691
+ token_address: token.tokenAddress,
3692
+ });
3693
+ const isRegistered = await isRegisteredOnChain(starkPublicKey, ethSigner, config);
3694
+ if (!isRegistered) {
3695
+ return executeRegisterAndWithdrawERC721(ethSigner, assetType.asset_type, starkPublicKey, token.tokenId, imxConfig);
3696
+ }
3697
+ return executeWithdrawERC721(ethSigner, assetType.asset_type, starkPublicKey, token.tokenId, imxConfig);
3698
+ }
3699
+ async function completeERC721WithdrawalAction({ ethSigner, starkPublicKey, token, config, }) {
3700
+ await validateChain(ethSigner, config.immutableXConfig);
3701
+ const { tokenAddress } = token;
3702
+ const { tokenId } = token;
3703
+ const imxConfig = config.immutableXConfig;
3704
+ const mintsApi = new coreSdk.MintsApi(imxConfig.apiConfiguration);
3705
+ return await mintsApi
3706
+ .getMintableTokenDetailsByClientTokenId({
3707
+ tokenAddress,
3708
+ tokenId,
3709
+ })
3710
+ .then((mintableToken) => completeMintableERC721Withdrawal(ethSigner, starkPublicKey, {
3711
+ type: 'ERC721',
3712
+ data: {
3713
+ id: tokenId,
3714
+ tokenAddress,
3715
+ blueprint: mintableToken.data.blueprint,
3716
+ },
3717
+ }, config))
3718
+ .catch((error) => {
3719
+ if (error.response?.status === 404) {
3720
+ // token is already minted on L1
3721
+ return completeERC721Withdrawal(ethSigner, starkPublicKey, token, config);
3722
+ }
3723
+ throw error; // unable to recover from any other kind of error
3724
+ });
3725
+ }
3726
+
3727
+ async function executeRegisterAndWithdrawEth(ethSigner, assetType, starkPublicKey, config) {
3728
+ const etherKey = await ethSigner.getAddress();
3729
+ const usersApi = new coreSdk.UsersApi(config.apiConfiguration);
3730
+ const signableResult = await getSignableRegistrationOnchain(etherKey, starkPublicKey, usersApi);
3731
+ const contract = coreSdk.Contracts.Registration.connect(config.ethConfiguration.registrationContractAddress, ethSigner);
3732
+ const populatedTransaction = await contract.populateTransaction.registerAndWithdraw(etherKey, starkPublicKey, signableResult.operator_signature, assetType);
3733
+ return ethSigner.sendTransaction(populatedTransaction);
3734
+ }
3735
+ async function executeWithdrawEth(ethSigner, assetType, starkPublicKey, config) {
3736
+ const contract = coreSdk.Contracts.Core.connect(config.ethConfiguration.coreContractAddress, ethSigner);
3737
+ const populatedTransaction = await contract.populateTransaction.withdraw(starkPublicKey, assetType);
3738
+ return ethSigner.sendTransaction(populatedTransaction);
3739
+ }
3740
+ async function completeEthWithdrawalAction({ ethSigner, starkPublicKey, config, }) {
3741
+ await validateChain(ethSigner, config.immutableXConfig);
3742
+ const imxConfig = config.immutableXConfig;
3743
+ const assetType = await getEncodeAssetInfo('asset', 'ETH', imxConfig);
3744
+ const isRegistered = await isRegisteredOnChain(starkPublicKey, ethSigner, config);
3745
+ if (!isRegistered) {
3746
+ return executeRegisterAndWithdrawEth(ethSigner, assetType.asset_type, starkPublicKey, imxConfig);
3747
+ }
3748
+ return executeWithdrawEth(ethSigner, assetType.asset_type, starkPublicKey, imxConfig);
3749
+ }
3750
+
3751
+ async function prepareWithdrawal({ signers, withdrawal, config, }) {
3752
+ return prepareWithdrawalAction({
3753
+ signers,
3754
+ config: config.immutableXConfig,
3755
+ ...withdrawal,
3756
+ });
3757
+ }
3758
+ // TODO: remove once fixed
3759
+ // eslint-disable-next-line consistent-return
3760
+ async function completeWithdrawal({ signers: { ethSigner }, starkPublicKey, token, config, }) {
3761
+ // TODO: please add a reasonable default here
3762
+ // eslint-disable-next-line default-case
3763
+ switch (token.type) {
3764
+ case 'ETH':
3765
+ return completeEthWithdrawalAction({ ethSigner, starkPublicKey, config });
3766
+ case 'ERC20':
3767
+ return completeERC20WithdrawalAction({
3768
+ ethSigner,
3769
+ starkPublicKey,
3770
+ token,
3771
+ config,
3772
+ });
3773
+ case 'ERC721':
3774
+ return completeERC721WithdrawalAction({
3775
+ ethSigner,
3776
+ starkPublicKey,
3777
+ token,
3778
+ config,
3779
+ });
3780
+ }
3781
+ }
3782
+
3783
+ async function createTrade({ signers: { ethSigner, starkSigner }, request, config, }) {
3784
+ await validateChain(ethSigner, config.immutableXConfig);
3785
+ const ethAddress = await ethSigner.getAddress();
3786
+ const tradesApi = new coreSdk.TradesApi(config.immutableXConfig.apiConfiguration);
3787
+ const signableResult = await tradesApi.getSignableTrade({
3788
+ getSignableTradeRequest: {
3789
+ user: ethAddress,
3790
+ order_id: request.order_id,
3791
+ fees: request.fees,
3792
+ },
3793
+ });
3794
+ const { signable_message: signableMessage, payload_hash: payloadHash } = signableResult.data;
3795
+ const ethSignature = await signRaw(signableMessage, ethSigner);
3796
+ const starkSignature = await starkSigner.signMessage(payloadHash);
3797
+ const createTradeResponse = await tradesApi.createTrade({
3798
+ createTradeRequest: {
3799
+ amount_buy: signableResult.data.amount_buy,
3800
+ amount_sell: signableResult.data.amount_sell,
3801
+ asset_id_buy: signableResult.data.asset_id_buy,
3802
+ asset_id_sell: signableResult.data.asset_id_sell,
3803
+ expiration_timestamp: signableResult.data.expiration_timestamp,
3804
+ fee_info: signableResult.data.fee_info,
3805
+ fees: request.fees,
3806
+ include_fees: true,
3807
+ nonce: signableResult.data.nonce,
3808
+ order_id: request.order_id,
3809
+ stark_key: signableResult.data.stark_key,
3810
+ vault_id_buy: signableResult.data.vault_id_buy,
3811
+ vault_id_sell: signableResult.data.vault_id_sell,
3812
+ stark_signature: starkSignature,
3813
+ },
3814
+ xImxEthAddress: ethAddress,
3815
+ xImxEthSignature: ethSignature,
3816
+ });
3817
+ return createTradeResponse.data;
3818
+ }
3819
+
3820
+ async function executeRegisterAndDepositEth(ethSigner, amount, assetType, starkPublicKey, vaultId, config, usersApi) {
3821
+ const etherKey = await ethSigner.getAddress();
3822
+ const coreContract = coreSdk.Contracts.Core.connect(config.ethConfiguration.coreContractAddress, ethSigner);
3823
+ const signableResult = await getSignableRegistrationOnchain(etherKey, starkPublicKey, usersApi);
3824
+ const populatedTransaction = await coreContract.populateTransaction.registerAndDepositEth(etherKey, starkPublicKey, signableResult.operator_signature, assetType, vaultId);
3825
+ return ethSigner.sendTransaction({ ...populatedTransaction, value: amount });
3826
+ }
3827
+ async function executeDepositEth(ethSigner, amount, assetType, starkPublicKey, vaultId, config) {
3828
+ const coreContract = coreSdk.Contracts.Core.connect(config.ethConfiguration.coreContractAddress, ethSigner);
3829
+ const populatedTransaction = await coreContract.populateTransaction['deposit(uint256,uint256,uint256)'](starkPublicKey, assetType, vaultId);
3830
+ return ethSigner.sendTransaction({ ...populatedTransaction, value: amount });
3831
+ }
3832
+ async function depositEth({ signers: { ethSigner }, deposit, config, }) {
3833
+ await validateChain(ethSigner, config.immutableXConfig);
3834
+ const user = await ethSigner.getAddress();
3835
+ const data = {
3836
+ decimals: 18,
3837
+ };
3838
+ const amount = units.parseUnits(deposit.amount, 'wei');
3839
+ const imxConfig = config.immutableXConfig;
3840
+ const depositsApi = new coreSdk.DepositsApi(imxConfig.apiConfiguration);
3841
+ const encodingApi = new coreSdk.EncodingApi(imxConfig.apiConfiguration);
3842
+ const usersApi = new coreSdk.UsersApi(imxConfig.apiConfiguration);
3843
+ const getSignableDepositRequest = {
3844
+ user,
3845
+ token: {
3846
+ type: deposit.type,
3847
+ data,
3848
+ },
3849
+ amount: amount.toString(),
3850
+ };
3851
+ const signableDepositResult = await depositsApi.getSignableDeposit({
3852
+ getSignableDepositRequest,
3853
+ });
3854
+ const encodingResult = await encodingApi.encodeAsset({
3855
+ assetType: 'asset',
3856
+ encodeAssetRequest: {
3857
+ token: {
3858
+ type: deposit.type,
3859
+ },
3860
+ },
3861
+ });
3862
+ const assetType = encodingResult.data.asset_type;
3863
+ const starkPublicKey = signableDepositResult.data.stark_key;
3864
+ const vaultId = signableDepositResult.data.vault_id;
3865
+ const isRegistered = await isRegisteredOnChain(starkPublicKey, ethSigner, config);
3866
+ if (!isRegistered) {
3867
+ return executeRegisterAndDepositEth(ethSigner, amount, assetType, starkPublicKey, vaultId, imxConfig, usersApi);
3868
+ }
3869
+ return executeDepositEth(ethSigner, amount, assetType, starkPublicKey, vaultId, imxConfig);
3870
+ }
3871
+
3872
+ async function executeRegisterAndDepositERC20(ethSigner, quantizedAmount, assetType, starkPublicKey, vaultId, config, usersApi) {
3873
+ const etherKey = await ethSigner.getAddress();
3874
+ const coreContract = coreSdk.Contracts.Core.connect(config.coreContractAddress, ethSigner);
3875
+ const signableResult = await getSignableRegistrationOnchain(etherKey, starkPublicKey, usersApi);
3876
+ const populatedTransaction = await coreContract.populateTransaction.registerAndDepositERC20(etherKey, starkPublicKey, signableResult.operator_signature, assetType, vaultId, quantizedAmount);
3877
+ return ethSigner.sendTransaction(populatedTransaction);
3878
+ }
3879
+ async function executeDepositERC20(ethSigner, quantizedAmount, assetType, starkPublicKey, vaultId, config) {
3880
+ const coreContract = coreSdk.Contracts.Core.connect(config.coreContractAddress, ethSigner);
3881
+ const populatedTransaction = await coreContract.populateTransaction.depositERC20(starkPublicKey, assetType, vaultId, quantizedAmount);
3882
+ return ethSigner.sendTransaction(populatedTransaction);
3883
+ }
3884
+ async function depositERC20({ signers: { ethSigner }, deposit, config, }) {
3885
+ await validateChain(ethSigner, config.immutableXConfig);
3886
+ const { apiConfiguration, ethConfiguration } = config.immutableXConfig;
3887
+ const user = await ethSigner.getAddress();
3888
+ const tokensApi = new coreSdk.TokensApi(apiConfiguration);
3889
+ const depositsApi = new coreSdk.DepositsApi(apiConfiguration);
3890
+ const encodingApi = new coreSdk.EncodingApi(apiConfiguration);
3891
+ const usersApi = new coreSdk.UsersApi(apiConfiguration);
3892
+ // Get decimals for this specific ERC20
3893
+ const token = await tokensApi.getToken({ address: deposit.tokenAddress });
3894
+ // TODO: remove once fixed
3895
+ // eslint-disable-next-line radix
3896
+ const decimals = parseInt(token.data.decimals);
3897
+ const data = {
3898
+ decimals,
3899
+ token_address: deposit.tokenAddress,
3900
+ };
3901
+ const amount = units.parseUnits(deposit.amount, 0); // 0 to always use undecimalized value
3902
+ // Approve whether an amount of token from an account can be spent by a third-party account
3903
+ const tokenContract = coreSdk.Contracts.IERC20.connect(deposit.tokenAddress, ethSigner);
3904
+ const approveTransaction = await tokenContract.populateTransaction.approve(ethConfiguration.coreContractAddress, amount);
3905
+ await ethSigner.sendTransaction(approveTransaction);
3906
+ const getSignableDepositRequest = {
3907
+ user,
3908
+ token: {
3909
+ type: deposit.type,
3910
+ data,
3911
+ },
3912
+ amount: amount.toString(),
3913
+ };
3914
+ const signableDepositResult = await depositsApi.getSignableDeposit({
3915
+ getSignableDepositRequest,
3916
+ });
3917
+ // Perform encoding on asset details to get an assetType (required for stark contract request)
3918
+ const encodingResult = await encodingApi.encodeAsset({
3919
+ assetType: 'asset',
3920
+ encodeAssetRequest: {
3921
+ token: {
3922
+ type: deposit.type,
3923
+ data: {
3924
+ token_address: deposit.tokenAddress,
3925
+ },
3926
+ },
3927
+ },
3928
+ });
3929
+ const assetType = encodingResult.data.asset_type;
3930
+ const starkPublicKey = signableDepositResult.data.stark_key;
3931
+ const vaultId = signableDepositResult.data.vault_id;
3932
+ const quantizedAmount = bignumber.BigNumber.from(signableDepositResult.data.amount);
3933
+ const isRegistered = await isRegisteredOnChain(starkPublicKey, ethSigner, config);
3934
+ if (!isRegistered) {
3935
+ return executeRegisterAndDepositERC20(ethSigner, quantizedAmount, assetType, starkPublicKey, vaultId, ethConfiguration, usersApi);
3936
+ }
3937
+ return executeDepositERC20(ethSigner, quantizedAmount, assetType, starkPublicKey, vaultId, ethConfiguration);
3938
+ }
3939
+
3940
+ async function executeDepositERC721(ethSigner, tokenId, assetType, starkPublicKey, vaultId, config) {
3941
+ const coreContract = coreSdk.Contracts.Core.connect(config.ethConfiguration.coreContractAddress, ethSigner);
3942
+ const populatedTransaction = await coreContract.populateTransaction.depositNft(starkPublicKey, assetType, vaultId, tokenId);
3943
+ return ethSigner.sendTransaction(populatedTransaction);
3944
+ }
3945
+ async function depositERC721({ signers: { ethSigner }, deposit, config, }) {
3946
+ await validateChain(ethSigner, config.immutableXConfig);
3947
+ const user = await ethSigner.getAddress();
3948
+ const { immutableXConfig } = config;
3949
+ const depositsApi = new coreSdk.DepositsApi(immutableXConfig.apiConfiguration);
3950
+ const encodingApi = new coreSdk.EncodingApi(immutableXConfig.apiConfiguration);
3951
+ const usersApi = new coreSdk.UsersApi(immutableXConfig.apiConfiguration);
3952
+ const data = {
3953
+ token_address: deposit.tokenAddress,
3954
+ token_id: deposit.tokenId,
3955
+ };
3956
+ const amount = '1';
3957
+ const getSignableDepositRequest = {
3958
+ user,
3959
+ token: {
3960
+ type: deposit.type,
3961
+ data,
3962
+ },
3963
+ amount: amount.toString(),
3964
+ };
3965
+ const signableDepositResult = await depositsApi.getSignableDeposit({
3966
+ getSignableDepositRequest,
3967
+ });
3968
+ // Perform encoding on asset details to get an assetType (required for stark contract request)
3969
+ const encodingResult = await encodingApi.encodeAsset({
3970
+ assetType: 'asset',
3971
+ encodeAssetRequest: {
3972
+ token: {
3973
+ type: deposit.type,
3974
+ data: {
3975
+ token_address: deposit.tokenAddress,
3976
+ token_id: deposit.tokenId,
3977
+ },
3978
+ },
3979
+ },
3980
+ });
3981
+ const assetType = encodingResult.data.asset_type;
3982
+ const starkPublicKey = signableDepositResult.data.stark_key;
3983
+ const vaultId = signableDepositResult.data.vault_id;
3984
+ const isRegistered = await isRegisteredOnChain(starkPublicKey, ethSigner, config);
3985
+ // Approve whether an amount of token from an account can be spent by a third-party account
3986
+ const tokenContract = coreSdk.Contracts.IERC721.connect(deposit.tokenAddress, ethSigner);
3987
+ const operator = immutableXConfig.ethConfiguration.coreContractAddress;
3988
+ const isApprovedForAll = await tokenContract.isApprovedForAll(user, operator);
3989
+ if (!isApprovedForAll) {
3990
+ await tokenContract.setApprovalForAll(operator, true);
3991
+ }
3992
+ if (!isRegistered) {
3993
+ const signableResult = await getSignableRegistrationOnchain(user, starkPublicKey, usersApi);
3994
+ const coreContract = coreSdk.Contracts.Core.connect(immutableXConfig.ethConfiguration.coreContractAddress, ethSigner);
3995
+ // Note: proxy registration contract registerAndDepositNft method is not used as
3996
+ // it currently fails erc721 transfer ownership check
3997
+ await coreContract.registerUser(user, starkPublicKey, signableResult.operator_signature);
3998
+ }
3999
+ return executeDepositERC721(ethSigner, deposit.tokenId, assetType, starkPublicKey, vaultId, immutableXConfig);
4000
+ }
4001
+
4002
+ // TODO: remove once fixed deposit variable shadowing
4003
+ // eslint-disable-next-line consistent-return, @typescript-eslint/no-shadow
4004
+ async function deposit({ signers, deposit, config }) {
4005
+ // TODO: please add a reasonable default here
4006
+ // eslint-disable-next-line default-case
4007
+ switch (deposit.type) {
4008
+ case 'ETH':
4009
+ return depositEth({ signers, deposit, config });
4010
+ case 'ERC20':
4011
+ return depositERC20({ signers, deposit, config });
4012
+ case 'ERC721':
4013
+ return depositERC721({ signers, deposit, config });
4014
+ }
4015
+ }
4016
+
4017
+ async function exchangeTransfer({ signers, request, config, }) {
4018
+ await validateChain(signers.ethSigner, config.immutableXConfig);
4019
+ const exchangeApi = new coreSdk.ExchangesApi(config.immutableXConfig.apiConfiguration);
4020
+ const ethAddress = await signers.ethSigner.getAddress();
4021
+ const transferAmount = request.amount;
4022
+ const signableResult = await exchangeApi.getExchangeSignableTransfer({
4023
+ id: request.transactionID,
4024
+ getSignableTransferRequest: {
4025
+ sender: ethAddress,
4026
+ token: convertToSignableToken(request),
4027
+ amount: transferAmount,
4028
+ receiver: request.receiver,
4029
+ },
4030
+ });
4031
+ const { signable_message: signableMessage, payload_hash: payloadHash } = signableResult.data;
4032
+ const ethSignature = await signRaw(signableMessage, signers.ethSigner);
4033
+ const starkSignature = await signers.starkSigner.signMessage(payloadHash);
4034
+ const transferSigningParams = {
4035
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
4036
+ sender_stark_key: signableResult.data.sender_stark_key,
4037
+ sender_vault_id: signableResult.data.sender_vault_id,
4038
+ receiver_stark_key: signableResult.data.receiver_stark_key,
4039
+ receiver_vault_id: signableResult.data.receiver_vault_id,
4040
+ asset_id: signableResult.data.asset_id,
4041
+ amount: signableResult.data.amount,
4042
+ nonce: signableResult.data.nonce,
4043
+ expiration_timestamp: signableResult.data.expiration_timestamp,
4044
+ stark_signature: starkSignature,
4045
+ };
4046
+ const response = await exchangeApi.createExchangeTransfer({
4047
+ id: request.transactionID,
4048
+ createTransferRequest: transferSigningParams,
4049
+ xImxEthAddress: ethAddress,
4050
+ xImxEthSignature: ethSignature,
4051
+ });
4052
+ return {
4053
+ sent_signature: response?.data.sent_signature,
4054
+ status: response?.data.status?.toString(),
4055
+ time: response?.data.time,
4056
+ transfer_id: response?.data.transfer_id,
4057
+ };
4058
+ }
4059
+
4060
+ class GenericIMXProvider {
4061
+ config;
4062
+ signers;
4063
+ constructor(config, ethSigner, starkSigner) {
4064
+ this.config = config;
4065
+ this.signers = { ethSigner, starkSigner };
4066
+ }
4067
+ async getAddress() {
4068
+ return await this.signers.ethSigner.getAddress();
4069
+ }
4070
+ registerOffchain() {
4071
+ return registerOffchain(this.signers, this.config);
4072
+ }
4073
+ batchNftTransfer(request) {
4074
+ return batchTransfer({
4075
+ signers: this.signers,
4076
+ request,
4077
+ config: this.config,
4078
+ });
4079
+ }
4080
+ cancelOrder(request) {
4081
+ return cancelOrder({
4082
+ signers: this.signers,
4083
+ request,
4084
+ config: this.config,
4085
+ });
4086
+ }
4087
+ completeWithdrawal(starkPublicKey, token) {
4088
+ return completeWithdrawal({
4089
+ config: this.config,
4090
+ signers: this.signers,
4091
+ token,
4092
+ starkPublicKey,
4093
+ });
4094
+ }
4095
+ createOrder(request) {
4096
+ return createOrder({
4097
+ signers: this.signers,
4098
+ request,
4099
+ config: this.config,
4100
+ });
4101
+ }
4102
+ createTrade(request) {
4103
+ return createTrade({
4104
+ signers: this.signers,
4105
+ request,
4106
+ config: this.config,
4107
+ });
4108
+ }
4109
+ deposit(tokenAmount) {
4110
+ return deposit({
4111
+ signers: this.signers,
4112
+ deposit: tokenAmount,
4113
+ config: this.config,
4114
+ });
4115
+ }
4116
+ exchangeTransfer(request) {
4117
+ return exchangeTransfer({
4118
+ signers: this.signers,
4119
+ request,
4120
+ config: this.config,
4121
+ });
4122
+ }
4123
+ async isRegisteredOnchain() {
4124
+ const starkPublicKey = await this.signers.starkSigner.getAddress();
4125
+ return isRegisteredOnChain(starkPublicKey, this.signers.ethSigner, this.config);
4126
+ }
4127
+ prepareWithdrawal(request) {
4128
+ return prepareWithdrawal({
4129
+ signers: this.signers,
4130
+ withdrawal: request,
4131
+ config: this.config,
4132
+ });
4133
+ }
4134
+ transfer(request) {
4135
+ return transfer({
4136
+ signers: this.signers,
4137
+ request,
4138
+ config: this.config,
4139
+ });
4140
+ }
4141
+ }
4142
+
4143
+ const WALLET_ACTION = {
4144
+ // TODO: remove once fixed - consider using an enum
4145
+ // eslint-disable-next-line @typescript-eslint/naming-convention
4146
+ SWITCH_CHAIN: 'wallet_switchEthereumChain',
4147
+ // eslint-disable-next-line @typescript-eslint/naming-convention
4148
+ CONNECT: 'eth_requestAccounts',
4149
+ };
4150
+ function isRequestableProvider(provider) {
4151
+ return !!provider?.request;
4152
+ }
4153
+ async function connectProvider(provider, chainID) {
4154
+ await provider.request({ method: WALLET_ACTION.CONNECT });
4155
+ if (chainID) {
4156
+ await provider.request({
4157
+ method: WALLET_ACTION.SWITCH_CHAIN,
4158
+ params: [{ chainId: `0x${chainID.toString(16)}` }],
4159
+ });
4160
+ }
4161
+ }
4162
+
4163
+ const ERRORS = {
4164
+ // TODO: remove once fixed - consider using something in line with the naming convention
4165
+ // eslint-disable-next-line @typescript-eslint/naming-convention
4166
+ PROVIDER_NOT_FOUND: 'The Metamask provider was not found',
4167
+ };
4168
+ async function connect$1({ chainID, }) {
4169
+ const provider = (await detectEthereumProvider());
4170
+ if (!isRequestableProvider(provider)) {
4171
+ throw new Error(ERRORS.PROVIDER_NOT_FOUND);
4172
+ }
4173
+ await connectProvider(provider, chainID);
4174
+ // NOTE: if we want to listen to Metamask events in the future, we can add a
4175
+ // listener here.
4176
+ return new ethers.ethers.providers.Web3Provider(provider);
4177
+ }
4178
+
4179
+ const COMMUNICATION_TYPE = 'message';
4180
+ var RequestEventType;
4181
+ (function (RequestEventType) {
4182
+ RequestEventType["GET_CONNECTION_REQUEST"] = "GET_CONNECTION_REQUEST";
4183
+ RequestEventType["CONNECT_WALLET_REQUEST"] = "CONNECT_WALLET_REQUEST";
4184
+ RequestEventType["SIGN_MESSAGE_REQUEST"] = "SIGN_MESSAGE_REQUEST";
4185
+ RequestEventType["DISCONNECT_WALLET_REQUEST"] = "DISCONNECT_WALLET_REQUEST";
4186
+ })(RequestEventType || (RequestEventType = {}));
4187
+ var ResponseEventType;
4188
+ (function (ResponseEventType) {
4189
+ ResponseEventType["CONNECT_WALLET_RESPONSE"] = "CONNECT_WALLET_RESPONSE";
4190
+ ResponseEventType["SIGN_MESSAGE_RESPONSE"] = "SIGN_MESSAGE_RESPONSE";
4191
+ ResponseEventType["GET_CONNECTION_RESPONSE"] = "GET_CONNECTION_RESPONSE";
4192
+ ResponseEventType["DISCONNECT_WALLET_RESPONSE"] = "DISCONNECT_WALLET_RESPONSE";
4193
+ })(ResponseEventType || (ResponseEventType = {}));
4194
+
4195
+ function postRequestMessage(iframe, payload) {
4196
+ if (iframe && iframe.contentWindow) {
4197
+ iframe.contentWindow.postMessage(payload, new URL(iframe.src).origin);
4198
+ }
4199
+ }
4200
+
4201
+ function messageResponseListener(iframe, event, eventType, callback) {
4202
+ if (iframe && event.source !== iframe.contentWindow) {
4203
+ return;
4204
+ }
4205
+ const l2WalletMessage = event.data;
4206
+ if (l2WalletMessage.type !== eventType) {
4207
+ return;
4208
+ }
4209
+ callback(l2WalletMessage.details);
4210
+ }
4211
+
4212
+ class ImxSigner {
4213
+ publicAddress;
4214
+ iframe;
4215
+ constructor(publicAddress, iframe) {
4216
+ this.publicAddress = publicAddress;
4217
+ this.iframe = iframe;
4218
+ }
4219
+ getAddress() {
4220
+ return this.publicAddress;
4221
+ }
4222
+ signMessage(rawMessage) {
4223
+ return new Promise((resolve, reject) => {
4224
+ const listener = (event) => {
4225
+ messageResponseListener(this.iframe, event, ResponseEventType.SIGN_MESSAGE_RESPONSE, (messageDetails) => {
4226
+ window.removeEventListener(COMMUNICATION_TYPE, listener);
4227
+ if (!messageDetails.success) {
4228
+ reject(new Error(messageDetails.error?.message));
4229
+ }
4230
+ resolve(messageDetails.data.signedMessage);
4231
+ });
4232
+ };
4233
+ window.addEventListener(COMMUNICATION_TYPE, listener);
4234
+ postRequestMessage(this.iframe, {
4235
+ type: RequestEventType.SIGN_MESSAGE_REQUEST,
4236
+ details: { starkPublicKey: this.publicAddress, message: rawMessage },
4237
+ });
4238
+ });
4239
+ }
4240
+ getIFrame() {
4241
+ return this.iframe;
4242
+ }
4243
+ }
4244
+
4245
+ const IMX_WALLET_IFRAME_ID = 'imx-wallet-app';
4246
+ const IMX_WALLET_IFRAME_HOSTS = {
4247
+ [exports.Environment.SANDBOX]: 'https://wallets.sandbox.immutable.com',
4248
+ [exports.Environment.PRODUCTION]: 'https://wallets.immutable.com',
4249
+ };
4250
+ const IMX_WALLET_IFRAME_STYLE = 'display: none;';
4251
+ function getIFrame() {
4252
+ return document.querySelector(`iframe#${IMX_WALLET_IFRAME_ID}`);
4253
+ }
4254
+ async function setupIFrame(env) {
4255
+ return new Promise((resolve) => {
4256
+ const iframe = document.createElement('iframe');
4257
+ iframe.setAttribute('id', IMX_WALLET_IFRAME_ID);
4258
+ iframe.setAttribute('src', IMX_WALLET_IFRAME_HOSTS[env]);
4259
+ iframe.setAttribute('style', IMX_WALLET_IFRAME_STYLE);
4260
+ document.body.appendChild(iframe);
4261
+ iframe.onload = () => resolve(iframe);
4262
+ });
4263
+ }
4264
+ async function getOrSetupIFrame(env) {
4265
+ const iframe = getIFrame();
4266
+ if (iframe)
4267
+ return iframe;
4268
+ return await setupIFrame(env);
4269
+ }
4270
+
4271
+ const DEFAULT_CONNECTION_MESSAGE = 'Only sign this request if you’ve initiated an action with Immutable X.';
4272
+ const CONNECTION_FAILED_ERROR = 'The L2 IMX Wallet connection has failed';
4273
+ async function connect(l1Provider, env) {
4274
+ const l1Signer = l1Provider.getSigner();
4275
+ const address = await l1Signer.getAddress();
4276
+ const signature = await l1Signer.signMessage(DEFAULT_CONNECTION_MESSAGE);
4277
+ const iframe = await getOrSetupIFrame(env);
4278
+ return new Promise((resolve, reject) => {
4279
+ const listener = (event) => {
4280
+ messageResponseListener(iframe, event, ResponseEventType.CONNECT_WALLET_RESPONSE, (messageDetails) => {
4281
+ window.removeEventListener(COMMUNICATION_TYPE, listener);
4282
+ if (!messageDetails.success) {
4283
+ reject(new Error(CONNECTION_FAILED_ERROR));
4284
+ }
4285
+ resolve(new ImxSigner(messageDetails.data.starkPublicKey, iframe));
4286
+ });
4287
+ };
4288
+ window.addEventListener(COMMUNICATION_TYPE, listener);
4289
+ postRequestMessage(iframe, {
4290
+ type: RequestEventType.CONNECT_WALLET_REQUEST,
4291
+ details: { ethAddress: address, signature },
4292
+ });
4293
+ });
4294
+ }
4295
+ async function disconnect(imxSigner) {
4296
+ const iframe = imxSigner.getIFrame();
4297
+ return new Promise((resolve, reject) => {
4298
+ const listener = (event) => {
4299
+ messageResponseListener(iframe, event, ResponseEventType.DISCONNECT_WALLET_RESPONSE, (messageDetails) => {
4300
+ window.removeEventListener(COMMUNICATION_TYPE, listener);
4301
+ if (!messageDetails.success && messageDetails.error) {
4302
+ reject(messageDetails.error);
4303
+ }
4304
+ iframe.remove();
4305
+ resolve();
4306
+ });
4307
+ };
4308
+ window.addEventListener(COMMUNICATION_TYPE, listener);
4309
+ postRequestMessage(iframe, {
4310
+ type: RequestEventType.DISCONNECT_WALLET_REQUEST,
4311
+ details: { starkPublicKey: imxSigner.getAddress() },
4312
+ });
4313
+ });
4314
+ }
4315
+
4316
+ var ProviderErrorType;
4317
+ (function (ProviderErrorType) {
4318
+ ProviderErrorType["PROVIDER_CONNECTION_ERROR"] = "PROVIDER_CONNECTION_ERROR";
4319
+ ProviderErrorType["WALLET_CONNECTION_ERROR"] = "WALLET_CONNECTION_ERROR";
4320
+ })(ProviderErrorType || (ProviderErrorType = {}));
4321
+ class ProviderError extends Error {
4322
+ type;
4323
+ constructor(message, type) {
4324
+ super(message);
4325
+ this.type = type;
4326
+ }
4327
+ }
4328
+ const withProviderError = async (fn, customError) => {
4329
+ try {
4330
+ return await fn();
4331
+ }
4332
+ catch (error) {
4333
+ const errorMessage = customError.message || `${error.message}` || 'UnknownError';
4334
+ throw new ProviderError(errorMessage, customError.type);
4335
+ }
4336
+ };
4337
+
4338
+ class MetaMaskIMXProvider extends GenericIMXProvider {
4339
+ static imxSigner;
4340
+ static async connect(config) {
4341
+ return await withProviderError(async () => {
4342
+ const metaMaskProvider = await connect$1({
4343
+ chainID: config.immutableXConfig.ethConfiguration.chainID,
4344
+ });
4345
+ this.imxSigner = await connect(metaMaskProvider, config.baseConfig.environment);
4346
+ return new MetaMaskIMXProvider(config, metaMaskProvider.getSigner(), this.imxSigner);
4347
+ }, { type: ProviderErrorType.WALLET_CONNECTION_ERROR });
4348
+ }
4349
+ static async disconnect() {
4350
+ if (!this.imxSigner) {
4351
+ throw new ProviderError('Attempted to disconnect from the MetaMask IMX provider without an established connection', ProviderErrorType.PROVIDER_CONNECTION_ERROR);
4352
+ }
4353
+ return withProviderError(async () => {
4354
+ await disconnect(this.imxSigner);
4355
+ }, { type: ProviderErrorType.PROVIDER_CONNECTION_ERROR });
4356
+ }
4357
+ static async signMessage(message) {
4358
+ if (!this.imxSigner) {
4359
+ throw new ProviderError('Attempted to sign a message with the MetaMask IMX provider without an established connection', ProviderErrorType.PROVIDER_CONNECTION_ERROR);
4360
+ }
4361
+ return withProviderError(async () => await this.imxSigner.signMessage(message), { type: ProviderErrorType.PROVIDER_CONNECTION_ERROR });
4362
+ }
4363
+ }
4364
+
4365
+ class ProviderConfiguration {
4366
+ immutableXConfig;
4367
+ baseConfig;
4368
+ constructor({ baseConfig, overrides }) {
4369
+ this.baseConfig = baseConfig;
4370
+ if (overrides) {
4371
+ this.immutableXConfig = overrides.immutableXConfig;
4372
+ }
4373
+ else {
4374
+ // TODO: remove once a sensible default is chosen
4375
+ // eslint-disable-next-line default-case
4376
+ switch (baseConfig.environment) {
4377
+ case exports.Environment.SANDBOX: {
4378
+ this.immutableXConfig = coreSdk.Config.SANDBOX;
4379
+ break;
4380
+ }
4381
+ case exports.Environment.PRODUCTION: {
4382
+ this.immutableXConfig = coreSdk.Config.PRODUCTION;
4383
+ break;
4384
+ }
4385
+ }
4386
+ }
4387
+ }
4388
+ }
4389
+
4390
+ function $parcel$interopDefault(a) {
4391
+ return a && a.__esModule ? a.default : a;
4392
+ }
4393
+
4394
+ const $762782b6c862d954$export$db5daa1b5156ccfe = [
4395
+ {
4396
+ constant: true,
4397
+ inputs: [],
4398
+ name: "name",
4399
+ outputs: [
4400
+ {
4401
+ name: "",
4402
+ type: "string"
4403
+ }
4404
+ ],
4405
+ payable: false,
4406
+ type: "function"
4407
+ },
4408
+ {
4409
+ constant: true,
4410
+ inputs: [],
4411
+ name: "decimals",
4412
+ outputs: [
4413
+ {
4414
+ name: "",
4415
+ type: "uint8"
4416
+ }
4417
+ ],
4418
+ payable: false,
4419
+ type: "function"
4420
+ },
4421
+ {
4422
+ constant: true,
4423
+ inputs: [
4424
+ {
4425
+ name: "_owner",
4426
+ type: "address"
4427
+ }
4428
+ ],
4429
+ name: "balanceOf",
4430
+ outputs: [
4431
+ {
4432
+ name: "balance",
4433
+ type: "uint256"
4434
+ }
4435
+ ],
4436
+ payable: false,
4437
+ type: "function"
4438
+ },
4439
+ {
4440
+ constant: true,
4441
+ inputs: [],
4442
+ name: "symbol",
4443
+ outputs: [
4444
+ {
4445
+ name: "",
4446
+ type: "string"
4447
+ }
4448
+ ],
4449
+ payable: false,
4450
+ type: "function"
4451
+ }
4452
+ ];
4453
+
4454
+
4455
+
4456
+ const $bc2bfebf768286d3$export$6a2ba3c3bd042990 = {
4457
+ baseConfig: {
4458
+ environment: (exports.Environment).SANDBOX
4459
+ }
4460
+ };
4461
+
4462
+
4463
+ exports.ConnectionProviders = void 0;
4464
+ (function(ConnectionProviders) {
4465
+ ConnectionProviders["METAMASK"] = "metamask";
4466
+ })(exports.ConnectionProviders || (exports.ConnectionProviders = {}));
4467
+
4468
+
4469
+ exports.ChainId = void 0;
4470
+ (function(ChainId) {
4471
+ ChainId[ChainId["ETHEREUM"] = 1] = "ETHEREUM";
4472
+ ChainId[ChainId["SEPOLIA"] = 11155111] = "SEPOLIA";
4473
+ ChainId[ChainId["IMTBL_ZKEVM_DEVNET"] = 13373] = "IMTBL_ZKEVM_DEVNET";
4474
+ ChainId[ChainId["IMTBL_ZKEVM_TESTNET"] = 13372] = "IMTBL_ZKEVM_TESTNET";
4475
+ ChainId[ChainId["POLYGON_ZKEVM_TESTNET"] = 1442] = "POLYGON_ZKEVM_TESTNET";
4476
+ ChainId[ChainId["POLYGON_ZKEVM"] = 137] = "POLYGON_ZKEVM";
4477
+ })(exports.ChainId || (exports.ChainId = {}));
4478
+ const $a47e48dd2c04791b$export$6f24f3cef7d501c4 = new Map([
4479
+ [
4480
+ exports.ChainId.ETHEREUM,
4481
+ {
4482
+ chainIdHex: "0x1",
4483
+ chainName: "Ethereum",
4484
+ rpcUrls: [
4485
+ "https://mainnet.infura.io/v3/"
4486
+ ],
4487
+ nativeCurrency: {
4488
+ name: "Ethereum",
4489
+ symbol: "ETH",
4490
+ decimals: 18
4491
+ },
4492
+ blockExplorerUrls: [
4493
+ "https://etherscan.io/"
4494
+ ]
4495
+ }
4496
+ ],
4497
+ [
4498
+ exports.ChainId.IMTBL_ZKEVM_TESTNET,
4499
+ {
4500
+ chainIdHex: "0x343C",
4501
+ chainName: "Immutable zkEVM Testnet",
4502
+ rpcUrls: [
4503
+ "https://zkevm-rpc.sandbox.x.immutable.com"
4504
+ ],
4505
+ nativeCurrency: {
4506
+ name: "IMX",
4507
+ symbol: "IMX",
4508
+ decimals: 18
4509
+ }
4510
+ }
4511
+ ],
4512
+ [
4513
+ exports.ChainId.POLYGON_ZKEVM,
4514
+ {
4515
+ chainIdHex: "0x89",
4516
+ chainName: "Polygon zkEVM",
4517
+ rpcUrls: [
4518
+ "https://polygon-rpc.com"
4519
+ ],
4520
+ nativeCurrency: {
4521
+ name: "MATIC",
4522
+ symbol: "MATIC",
4523
+ decimals: 18
4524
+ },
4525
+ blockExplorerUrls: [
4526
+ "https://polygonscan.com/"
4527
+ ]
4528
+ }
4529
+ ]
4530
+ ]);
4531
+ const $a47e48dd2c04791b$export$3e81fc0987227f10 = new Map([
4532
+ [
4533
+ exports.ChainId.SEPOLIA,
4534
+ {
4535
+ chainIdHex: "0xaa36a7",
4536
+ chainName: "Sepolia",
4537
+ rpcUrls: [
4538
+ "https://sepolia.infura.io/v3/"
4539
+ ],
4540
+ nativeCurrency: {
4541
+ name: "Sep Eth",
4542
+ symbol: "ETH",
4543
+ decimals: 18
4544
+ },
4545
+ blockExplorerUrls: [
4546
+ "https://sepolia.etherscan.io/"
4547
+ ]
4548
+ }
4549
+ ],
4550
+ [
4551
+ exports.ChainId.IMTBL_ZKEVM_DEVNET,
4552
+ {
4553
+ chainIdHex: "0x343D",
4554
+ chainName: "Immutable zkEVM Devnet",
4555
+ rpcUrls: [
4556
+ "https://zkevm-rpc.dev.x.immutable.com/"
4557
+ ],
4558
+ nativeCurrency: {
4559
+ name: "IMX",
4560
+ symbol: "IMX",
4561
+ decimals: 18
4562
+ }
4563
+ }
4564
+ ],
4565
+ [
4566
+ exports.ChainId.POLYGON_ZKEVM_TESTNET,
4567
+ {
4568
+ chainIdHex: "0x5A2",
4569
+ chainName: "Polygon zkEVM Testnet",
4570
+ rpcUrls: [
4571
+ "https://rpc.public.zkevm-test.net"
4572
+ ],
4573
+ nativeCurrency: {
4574
+ name: "MATIC",
4575
+ symbol: "MATIC",
4576
+ decimals: 18
4577
+ },
4578
+ blockExplorerUrls: [
4579
+ "https://testnet-zkevm.polygonscan.com"
4580
+ ]
4581
+ }
4582
+ ]
4583
+ ]);
4584
+ exports.NetworkFilterTypes = void 0;
4585
+ (function(NetworkFilterTypes) {
4586
+ NetworkFilterTypes["ALL"] = "all";
4587
+ })(exports.NetworkFilterTypes || (exports.NetworkFilterTypes = {}));
4588
+
4589
+
4590
+ // TODO: fix circular dependency
4591
+ // eslint-disable-next-line import/no-cycle
4592
+ exports.TokenFilterTypes = void 0;
4593
+ (function(TokenFilterTypes) {
4594
+ TokenFilterTypes["SWAP"] = "swap";
4595
+ TokenFilterTypes["BRIDGE"] = "bridge";
4596
+ TokenFilterTypes["ALL"] = "all";
4597
+ })(exports.TokenFilterTypes || (exports.TokenFilterTypes = {}));
4598
+
4599
+
4600
+
4601
+
4602
+ // TODO: fix circular dependency
4603
+ // eslint-disable-next-line import/no-cycle
4604
+ let $4f91c5f280efe242$export$35b06f0d33f57e26;
4605
+ (function(WalletAction) {
4606
+ WalletAction["CHECK_CONNECTION"] = "eth_accounts";
4607
+ WalletAction["CONNECT"] = "eth_requestAccounts";
4608
+ WalletAction["ADD_NETWORK"] = "wallet_addEthereumChain";
4609
+ WalletAction["SWITCH_NETWORK"] = "wallet_switchEthereumChain";
4610
+ })($4f91c5f280efe242$export$35b06f0d33f57e26 || ($4f91c5f280efe242$export$35b06f0d33f57e26 = {}));
4611
+ exports.WalletFilterTypes = void 0;
4612
+ (function(WalletFilterTypes) {
4613
+ WalletFilterTypes["ALL"] = "all";
4614
+ WalletFilterTypes["DESKTOP"] = "desktop";
4615
+ WalletFilterTypes["MOBILE"] = "mobile";
4616
+ })(exports.WalletFilterTypes || (exports.WalletFilterTypes = {}));
4617
+
4618
+
4619
+
4620
+
4621
+ /**
4622
+ * The different types of errors that can be returned by the checkout process.
4623
+ */ exports.CheckoutErrorType = void 0;
4624
+ (function(CheckoutErrorType) {
4625
+ CheckoutErrorType["PROVIDER_PREFERENCE_ERROR"] = "PROVIDER_PREFERENCE_ERROR";
4626
+ CheckoutErrorType["CONNECT_PROVIDER_ERROR"] = "CONNECT_PROVIDER_ERROR";
4627
+ CheckoutErrorType["GET_BALANCE_ERROR"] = "GET_BALANCE_ERROR";
4628
+ CheckoutErrorType["GET_ERC20_BALANCE_ERROR"] = "GET_ERC20_BALANCE_ERROR";
4629
+ CheckoutErrorType["GET_NETWORK_INFO_ERROR"] = "GET_NETWORK_INFO_ERROR";
4630
+ CheckoutErrorType["METAMASK_PROVIDER_ERROR"] = "METAMASK_PROVIDER_ERROR";
4631
+ CheckoutErrorType["CHAIN_NOT_SUPPORTED_ERROR"] = "CHAIN_NOT_SUPPORTED_ERROR";
4632
+ CheckoutErrorType["PROVIDER_REQUEST_MISSING_ERROR"] = "PROVIDER_REQUEST_MISSING_ERROR";
4633
+ CheckoutErrorType["PROVIDER_REQUEST_FAILED_ERROR"] = "PROVIDER_REQUEST_FAILED_ERROR";
4634
+ CheckoutErrorType["USER_REJECTED_REQUEST_ERROR"] = "USER_REJECTED_REQUEST_ERROR";
4635
+ CheckoutErrorType["TRANSACTION_ERROR"] = "TRANSACTION_ERROR";
4636
+ })(exports.CheckoutErrorType || (exports.CheckoutErrorType = {}));
4637
+ class $a8bc256d81a5e2c1$export$b722478a3cbfa3bc extends Error {
4638
+ constructor(message, type, data){
4639
+ super(message);
4640
+ this.message = message;
4641
+ this.type = type;
4642
+ this.data = data;
4643
+ }
4644
+ }
4645
+ let $a8bc256d81a5e2c1$export$a22d4e0719ee6def;
4646
+ (function(CheckoutInternalErrorType) {
4647
+ CheckoutInternalErrorType["REJECTED_SWITCH_AFTER_ADDING_NETWORK"] = "REJECTED_SWITCH_AFTER_ADDING_NETWORK";
4648
+ })($a8bc256d81a5e2c1$export$a22d4e0719ee6def || ($a8bc256d81a5e2c1$export$a22d4e0719ee6def = {}));
4649
+ const $a8bc256d81a5e2c1$export$bacc563de539c6c3 = async (fn, customError)=>{
4650
+ try {
4651
+ return await fn();
4652
+ } catch (error) {
4653
+ const cause = `${error.message}` || "UnknownError";
4654
+ const errorMessage = customError.message ? `[${customError.type}]:${customError.message}. Cause:${cause}` : `[${customError.type}] Cause:${cause}`;
4655
+ if (error instanceof $a8bc256d81a5e2c1$export$b722478a3cbfa3bc) throw new $a8bc256d81a5e2c1$export$b722478a3cbfa3bc(errorMessage, customError.type, {
4656
+ ...customError.data,
4657
+ innerErrorType: error.type,
4658
+ ...error.data
4659
+ });
4660
+ throw new $a8bc256d81a5e2c1$export$b722478a3cbfa3bc(errorMessage, customError.type, {
4661
+ ...customError.data
4662
+ });
4663
+ }
4664
+ };
4665
+
4666
+
4667
+
4668
+
4669
+ /* eslint-disable @typescript-eslint/no-explicit-any */
4670
+
4671
+ /* eslint-disable @typescript-eslint/no-explicit-any */
4672
+
4673
+
4674
+
4675
+ async function $c99672cf2294e839$var$getMetaMaskProvider() {
4676
+ const provider = await ($a8bc256d81a5e2c1$export$bacc563de539c6c3)(async ()=>await (detectEthereumProvider)(), {
4677
+ type: (exports.CheckoutErrorType).METAMASK_PROVIDER_ERROR
4678
+ });
4679
+ if (!provider || !provider.request) throw new ($a8bc256d81a5e2c1$export$b722478a3cbfa3bc)("No MetaMask provider installed.", (exports.CheckoutErrorType).METAMASK_PROVIDER_ERROR);
4680
+ return new (providers.Web3Provider)(provider);
4681
+ }
4682
+ async function $c99672cf2294e839$var$getWalletProviderForPreference(providerPreference) {
4683
+ let web3Provider = null;
4684
+ switch(providerPreference){
4685
+ case (exports.ConnectionProviders).METAMASK:
4686
+ web3Provider = await $c99672cf2294e839$var$getMetaMaskProvider();
4687
+ break;
4688
+ default:
4689
+ throw new ($a8bc256d81a5e2c1$export$b722478a3cbfa3bc)("Provider preference is not supported", (exports.CheckoutErrorType).PROVIDER_PREFERENCE_ERROR);
4690
+ }
4691
+ return web3Provider;
4692
+ }
4693
+ async function $c99672cf2294e839$export$2d040992269b4717(providerPreference) {
4694
+ const provider = await $c99672cf2294e839$var$getWalletProviderForPreference(providerPreference);
4695
+ if (!provider.provider?.request) throw new ($a8bc256d81a5e2c1$export$b722478a3cbfa3bc)("Incompatible provider", (exports.CheckoutErrorType).PROVIDER_REQUEST_MISSING_ERROR, {
4696
+ details: `Unsupported provider for ${providerPreference}`
4697
+ });
4698
+ let accounts = [];
4699
+ try {
4700
+ accounts = await provider.provider.request({
4701
+ method: (0, $4f91c5f280efe242$export$35b06f0d33f57e26).CHECK_CONNECTION,
4702
+ params: []
4703
+ });
4704
+ } catch (err) {
4705
+ throw new ($a8bc256d81a5e2c1$export$b722478a3cbfa3bc)("Check wallet connection request failed", (exports.CheckoutErrorType).PROVIDER_REQUEST_FAILED_ERROR, {
4706
+ rpcMethod: ($4f91c5f280efe242$export$35b06f0d33f57e26).CHECK_CONNECTION
4707
+ });
4708
+ }
4709
+ // accounts[0] will have the active account if connected.
4710
+ return {
4711
+ isConnected: accounts && accounts.length > 0,
4712
+ walletAddress: accounts[0] ?? ""
4713
+ };
4714
+ }
4715
+ async function $c99672cf2294e839$export$fba2f6c3656e07c1(params) {
4716
+ const web3Provider = await $c99672cf2294e839$var$getWalletProviderForPreference(params.providerPreference);
4717
+ await ($a8bc256d81a5e2c1$export$bacc563de539c6c3)(async ()=>{
4718
+ if (!web3Provider || !web3Provider?.provider?.request) throw new ($a8bc256d81a5e2c1$export$b722478a3cbfa3bc)("Incompatible provider", (exports.CheckoutErrorType).PROVIDER_REQUEST_MISSING_ERROR, {
4719
+ details: `Unsupported provider for ${params.providerPreference}`
4720
+ });
4721
+ // this makes the request to the wallet to connect i.e request eth accounts ('eth_requestAccounts')
4722
+ await web3Provider.provider.request({
4723
+ method: ($4f91c5f280efe242$export$35b06f0d33f57e26).CONNECT,
4724
+ params: []
4725
+ });
4726
+ }, {
4727
+ type: (exports.CheckoutErrorType).USER_REJECTED_REQUEST_ERROR
4728
+ });
4729
+ return web3Provider;
4730
+ }
4731
+
4732
+
4733
+ var $497c134ecbc8a50f$exports = {};
4734
+ $497c134ecbc8a50f$exports = JSON.parse('[{"chainId":1},{"chainId":11155111},{"chainId":13372},{"chainId":13373},{"chainId":1442},{"chainId":137}]');
4735
+
4736
+
4737
+ const $de192de6ef100f9f$var$UNRECOGNISED_CHAIN_ERROR_CODE = 4902; // error code (MetaMask)
4738
+ // these functions should not be exported. These functions should be used as part of an exported function e.g switchWalletNetwork() above.
4739
+ // make sure to check if(provider.provider?.request) in the exported function and throw an error
4740
+ // eslint-disable-next-line consistent-return
4741
+ async function $de192de6ef100f9f$var$switchNetworkInWallet(networkMap, provider, chainId) {
4742
+ if (provider.provider?.request) return await provider.provider.request({
4743
+ method: ($4f91c5f280efe242$export$35b06f0d33f57e26).SWITCH_NETWORK,
4744
+ params: [
4745
+ {
4746
+ chainId: networkMap.get(chainId)?.chainIdHex
4747
+ }
4748
+ ]
4749
+ });
4750
+ }
4751
+ // TODO: Should these functions always return something?
4752
+ // eslint-disable-next-line consistent-return
4753
+ async function $de192de6ef100f9f$var$addNetworkToWallet(networkMap, provider, chainId) {
4754
+ if (provider.provider?.request) {
4755
+ const networkDetails = networkMap.get(chainId);
4756
+ const addNetwork = {
4757
+ chainId: networkDetails?.chainIdHex,
4758
+ chainName: networkDetails?.chainName,
4759
+ rpcUrls: networkDetails?.rpcUrls,
4760
+ nativeCurrency: networkDetails?.nativeCurrency,
4761
+ blockExplorerUrls: networkDetails?.blockExplorerUrls
4762
+ };
4763
+ return await provider.provider.request({
4764
+ method: ($4f91c5f280efe242$export$35b06f0d33f57e26).ADD_NETWORK,
4765
+ params: [
4766
+ addNetwork
4767
+ ]
4768
+ });
4769
+ }
4770
+ }
4771
+ async function $de192de6ef100f9f$export$79f13b4cfaaf0d09(config, provider) {
4772
+ const { networkMap: networkMap } = config;
4773
+ return ($a8bc256d81a5e2c1$export$bacc563de539c6c3)(async ()=>{
4774
+ const network = await provider.getNetwork();
4775
+ if (!Array.from(networkMap.keys()).includes(network.chainId)) // return empty details
4776
+ return {
4777
+ chainId: network.chainId,
4778
+ name: network.name,
4779
+ isSupported: false
4780
+ };
4781
+ const chainIdNetworkInfo = networkMap.get(network.chainId);
4782
+ return {
4783
+ name: chainIdNetworkInfo.chainName,
4784
+ chainId: parseInt(chainIdNetworkInfo.chainIdHex, 16),
4785
+ nativeCurrency: chainIdNetworkInfo.nativeCurrency,
4786
+ isSupported: true
4787
+ };
4788
+ }, {
4789
+ type: (exports.CheckoutErrorType).GET_NETWORK_INFO_ERROR
4790
+ });
4791
+ }
4792
+ async function $de192de6ef100f9f$export$b827d9418aeb5dbd(config, providerPreference, provider, chainId) {
4793
+ let currentProvider = provider;
4794
+ const { networkMap: networkMap } = config;
4795
+ if (!Object.values((exports.ChainId)).includes(chainId)) throw new ($a8bc256d81a5e2c1$export$b722478a3cbfa3bc)(`Chain:${chainId} is not a supported chain`, (exports.CheckoutErrorType).CHAIN_NOT_SUPPORTED_ERROR);
4796
+ if (!currentProvider || !currentProvider.provider?.request) throw new ($a8bc256d81a5e2c1$export$b722478a3cbfa3bc)("Incompatible provider", (exports.CheckoutErrorType).PROVIDER_REQUEST_MISSING_ERROR, {
4797
+ details: "Unsupported provider"
4798
+ });
4799
+ // WT-1146 - Refer to the README in this folder for explantion on the switch network flow
4800
+ try {
4801
+ await $de192de6ef100f9f$var$switchNetworkInWallet(networkMap, currentProvider, chainId);
4802
+ } catch (err) {
4803
+ if (err.code === $de192de6ef100f9f$var$UNRECOGNISED_CHAIN_ERROR_CODE) try {
4804
+ await $de192de6ef100f9f$var$addNetworkToWallet(networkMap, currentProvider, chainId);
4805
+ // eslint-disable-next-line @typescript-eslint/no-shadow
4806
+ } catch (err) {
4807
+ throw new ($a8bc256d81a5e2c1$export$b722478a3cbfa3bc)("User cancelled add network request", (exports.CheckoutErrorType).USER_REJECTED_REQUEST_ERROR);
4808
+ }
4809
+ else throw new ($a8bc256d81a5e2c1$export$b722478a3cbfa3bc)("User cancelled switch network request", (exports.CheckoutErrorType).USER_REJECTED_REQUEST_ERROR);
4810
+ }
4811
+ currentProvider = await ($c99672cf2294e839$export$fba2f6c3656e07c1)({
4812
+ providerPreference: providerPreference
4813
+ });
4814
+ if ((await currentProvider.getNetwork()).chainId !== chainId) // user didn't actually switch
4815
+ throw new ($a8bc256d81a5e2c1$export$b722478a3cbfa3bc)("User cancelled switch network request", (exports.CheckoutErrorType).USER_REJECTED_REQUEST_ERROR);
4816
+ // we can assume that if the above succeeds then user has successfully
4817
+ // switched to the network specified
4818
+ const newNetwork = networkMap.get(chainId);
4819
+ return {
4820
+ network: {
4821
+ name: newNetwork?.chainName,
4822
+ chainId: parseInt(newNetwork?.chainIdHex ?? "", 16),
4823
+ nativeCurrency: newNetwork?.nativeCurrency
4824
+ },
4825
+ provider: currentProvider
4826
+ };
4827
+ }
4828
+ async function $de192de6ef100f9f$export$3043f6442a9ef563(config, { type: type = (exports.NetworkFilterTypes).ALL , exclude: exclude }) {
4829
+ const { networkMap: networkMap } = config;
4830
+ const list = ((/*@__PURE__*/$parcel$interopDefault($497c134ecbc8a50f$exports))).filter((network)=>{
4831
+ const allowAllTokens = type === (exports.NetworkFilterTypes).ALL;
4832
+ const networkNotExcluded = !(exclude || []).map((exc)=>exc.chainId).includes(network.chainId);
4833
+ return allowAllTokens && networkNotExcluded;
4834
+ });
4835
+ const allowedNetworks = [];
4836
+ list.forEach((element)=>{
4837
+ const newNetwork = networkMap.get(element.chainId);
4838
+ if (newNetwork) allowedNetworks.push({
4839
+ name: newNetwork.chainName,
4840
+ chainId: parseInt(newNetwork.chainIdHex, 16),
4841
+ nativeCurrency: newNetwork.nativeCurrency,
4842
+ isSupported: true
4843
+ });
4844
+ });
4845
+ return {
4846
+ networks: allowedNetworks
4847
+ };
4848
+ }
4849
+
4850
+
4851
+
4852
+
4853
+
4854
+ var $cda6003506e4182e$exports = {};
4855
+ $cda6003506e4182e$exports = JSON.parse("[{\"chainId\":13373,\"name\":\"IMX\",\"symbol\":\"IMX\",\"decimals\":18,\"icon\":\"data:image/svg+xml,%3C%3Fxml version='1.0' encoding='utf-8'%3F%3E%3Csvg version='1.1' id='Layer_1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' x='0px' y='0px' viewBox='0 0 139 113' style='enable-background:new 0 0 139 113;' xml:space='preserve'%3E%3Cstyle type='text/css'%3E .st0%7Bclip-path:url(%23SVGID_00000053504646934646330740000009134454895836103350_);%7D .st1%7Bfill:%2317B5CB;%7D%0A%3C/style%3E%3Cg%3E%3Cdefs%3E%3Crect id='SVGID_1_' width='139' height='113'/%3E%3C/defs%3E%3CclipPath id='SVGID_00000035518931339590433170000002358037249938198420_'%3E%3Cuse xlink:href='%23SVGID_1_' style='overflow:visible;'/%3E%3C/clipPath%3E%3Cg style='clip-path:url(%23SVGID_00000035518931339590433170000002358037249938198420_);'%3E%3Cpath class='st1' d='M124.1,0h14.6L79.5,67.6c-1.5,1.7-1.6,4.3-0.1,6.1l34.1,39.7H98.3L66.8,76.6l-1.6-2c-1.5-1.7-1.4-4.4,0.1-6.1 L124.1,0z'/%3E%3Cpath class='st1' d='M91.2,73.7c-1-1.1-1.3-2.7-1-4.1c0.3-0.8,0.8-1.6,1.4-2.2l3.9-4.3l43.5,50.3h-13.8 C125.2,113.4,99.7,83.6,91.2,73.7z'/%3E%3Cpath class='st1' d='M15.2,113.4H0l46.6-53.9c1.5-1.7,1.5-4.3,0-6L0.4,0H15l46.5,53.9c1.2,1.6,1.4,3.9,0.1,5.4 C49.4,73.4,15.2,113.4,15.2,113.4z'/%3E%3Cpath class='st1' d='M40.6,0h-14l43.1,49.9c0,0,0.1-0.1,4.9-5.8c1.3-1.5,1.6-3.4,0.1-4.9C65.7,30,40.6,0,40.6,0z'/%3E%3Cpath class='st1' d='M82.6,34.8L112.5,0H98.3L82.7,18.2l-4.5,5.3c-1.5,1.7-1.6,4.3-0.1,6.1C79.2,30.9,82.6,34.8,82.6,34.8z'/%3E%3Cpath class='st1' d='M56.6,78.6l-29.9,34.8h14.1l15.6-18.2l4.5-5.3c1.5-1.7,1.6-4.3,0.1-6.1C59.9,82.5,56.6,78.6,56.6,78.6z'/%3E%3C/g%3E%3C/g%3E%3C/svg%3E%0A\",\"tokenFeatures\":[\"swap\",\"bridge\"]},{\"chainId\":13373,\"name\":\"FUN token\",\"address\":\"0xd8f1D29a1572FbCeF0B0C9541E50637Ad8804F21\",\"symbol\":\"FUN\",\"decimals\":18,\"icon\":\"data:image/svg+xml,%3C%3Fxml version='1.0' encoding='UTF-8'%3F%3E%3C!DOCTYPE svg PUBLIC '-//W3C//DTD SVG 1.1//EN' 'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'%3E%3Csvg xmlns='http://www.w3.org/2000/svg' xml:space='preserve' width='100%25' height='100%25' version='1.1' shape-rendering='geometricPrecision' text-rendering='geometricPrecision' image-rendering='optimizeQuality' fill-rule='evenodd' clip-rule='evenodd'%0AviewBox='0 0 784.37 1277.39' xmlns:xlink='http://www.w3.org/1999/xlink' xmlns:xodm='http://www.corel.com/coreldraw/odm/2003'%3E%3Cg id='Layer_x0020_1'%3E%3Cmetadata id='CorelCorpID_0Corel-Layer'/%3E%3Cg id='_1421394342400'%3E%3Cg%3E%3Cpolygon fill='%23343434' fill-rule='nonzero' points='392.07,0 383.5,29.11 383.5,873.74 392.07,882.29 784.13,650.54 '/%3E%3Cpolygon fill='%238C8C8C' fill-rule='nonzero' points='392.07,0 -0,650.54 392.07,882.29 392.07,472.33 '/%3E%3Cpolygon fill='%233C3C3B' fill-rule='nonzero' points='392.07,956.52 387.24,962.41 387.24,1263.28 392.07,1277.38 784.37,724.89 '/%3E%3Cpolygon fill='%238C8C8C' fill-rule='nonzero' points='392.07,1277.38 392.07,956.52 -0,724.89 '/%3E%3Cpolygon fill='%23141414' fill-rule='nonzero' points='392.07,882.29 784.13,650.54 392.07,472.33 '/%3E%3Cpolygon fill='%23393939' fill-rule='nonzero' points='0,650.54 392.07,882.29 392.07,472.33 '/%3E%3C/g%3E%3C/g%3E%3C/g%3E%3C/svg%3E%0A\",\"tokenFeatures\":[\"swap\",\"bridge\"]},{\"chainId\":13373,\"name\":\"USDC\",\"address\":\"0x5893A5c7bc615Dfd36D7383366d00FFFca5f7178\",\"symbol\":\"USDC\",\"decimals\":18,\"icon\":\"data:image/svg+xml,%3C%3Fxml version='1.0' encoding='UTF-8'%3F%3E%3C!DOCTYPE svg PUBLIC '-//W3C//DTD SVG 1.1//EN' 'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'%3E%3Csvg xmlns='http://www.w3.org/2000/svg' xml:space='preserve' width='100%25' height='100%25' version='1.1' shape-rendering='geometricPrecision' text-rendering='geometricPrecision' image-rendering='optimizeQuality' fill-rule='evenodd' clip-rule='evenodd'%0AviewBox='0 0 784.37 1277.39' xmlns:xlink='http://www.w3.org/1999/xlink' xmlns:xodm='http://www.corel.com/coreldraw/odm/2003'%3E%3Cg id='Layer_x0020_1'%3E%3Cmetadata id='CorelCorpID_0Corel-Layer'/%3E%3Cg id='_1421394342400'%3E%3Cg%3E%3Cpolygon fill='%23343434' fill-rule='nonzero' points='392.07,0 383.5,29.11 383.5,873.74 392.07,882.29 784.13,650.54 '/%3E%3Cpolygon fill='%238C8C8C' fill-rule='nonzero' points='392.07,0 -0,650.54 392.07,882.29 392.07,472.33 '/%3E%3Cpolygon fill='%233C3C3B' fill-rule='nonzero' points='392.07,956.52 387.24,962.41 387.24,1263.28 392.07,1277.38 784.37,724.89 '/%3E%3Cpolygon fill='%238C8C8C' fill-rule='nonzero' points='392.07,1277.38 392.07,956.52 -0,724.89 '/%3E%3Cpolygon fill='%23141414' fill-rule='nonzero' points='392.07,882.29 784.13,650.54 392.07,472.33 '/%3E%3Cpolygon fill='%23393939' fill-rule='nonzero' points='0,650.54 392.07,882.29 392.07,472.33 '/%3E%3C/g%3E%3C/g%3E%3C/g%3E%3C/svg%3E%0A\",\"tokenFeatures\":[\"swap\",\"bridge\"]},{\"chainId\":13373,\"name\":\"WETH\",\"address\":\"0xD6d9321DCC42377C1fa8cFec665182c463b2392C\",\"symbol\":\"WETH\",\"decimals\":18,\"icon\":\"data:image/svg+xml,%3C%3Fxml version='1.0' encoding='UTF-8'%3F%3E%3C!DOCTYPE svg PUBLIC '-//W3C//DTD SVG 1.1//EN' 'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'%3E%3Csvg xmlns='http://www.w3.org/2000/svg' xml:space='preserve' width='100%25' height='100%25' version='1.1' shape-rendering='geometricPrecision' text-rendering='geometricPrecision' image-rendering='optimizeQuality' fill-rule='evenodd' clip-rule='evenodd'%0AviewBox='0 0 784.37 1277.39' xmlns:xlink='http://www.w3.org/1999/xlink' xmlns:xodm='http://www.corel.com/coreldraw/odm/2003'%3E%3Cg id='Layer_x0020_1'%3E%3Cmetadata id='CorelCorpID_0Corel-Layer'/%3E%3Cg id='_1421394342400'%3E%3Cg%3E%3Cpolygon fill='%23343434' fill-rule='nonzero' points='392.07,0 383.5,29.11 383.5,873.74 392.07,882.29 784.13,650.54 '/%3E%3Cpolygon fill='%238C8C8C' fill-rule='nonzero' points='392.07,0 -0,650.54 392.07,882.29 392.07,472.33 '/%3E%3Cpolygon fill='%233C3C3B' fill-rule='nonzero' points='392.07,956.52 387.24,962.41 387.24,1263.28 392.07,1277.38 784.37,724.89 '/%3E%3Cpolygon fill='%238C8C8C' fill-rule='nonzero' points='392.07,1277.38 392.07,956.52 -0,724.89 '/%3E%3Cpolygon fill='%23141414' fill-rule='nonzero' points='392.07,882.29 784.13,650.54 392.07,472.33 '/%3E%3Cpolygon fill='%23393939' fill-rule='nonzero' points='0,650.54 392.07,882.29 392.07,472.33 '/%3E%3C/g%3E%3C/g%3E%3C/g%3E%3C/svg%3E%0A\",\"tokenFeatures\":[\"swap\",\"bridge\"]},{\"chainId\":1,\"name\":\"Ethereum\",\"symbol\":\"ETH\",\"decimals\":18,\"icon\":\"data:image/svg+xml,%3C%3Fxml version='1.0' encoding='UTF-8'%3F%3E%3C!DOCTYPE svg PUBLIC '-//W3C//DTD SVG 1.1//EN' 'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'%3E%3Csvg xmlns='http://www.w3.org/2000/svg' xml:space='preserve' width='100%25' height='100%25' version='1.1' shape-rendering='geometricPrecision' text-rendering='geometricPrecision' image-rendering='optimizeQuality' fill-rule='evenodd' clip-rule='evenodd'%0AviewBox='0 0 784.37 1277.39' xmlns:xlink='http://www.w3.org/1999/xlink' xmlns:xodm='http://www.corel.com/coreldraw/odm/2003'%3E%3Cg id='Layer_x0020_1'%3E%3Cmetadata id='CorelCorpID_0Corel-Layer'/%3E%3Cg id='_1421394342400'%3E%3Cg%3E%3Cpolygon fill='%23343434' fill-rule='nonzero' points='392.07,0 383.5,29.11 383.5,873.74 392.07,882.29 784.13,650.54 '/%3E%3Cpolygon fill='%238C8C8C' fill-rule='nonzero' points='392.07,0 -0,650.54 392.07,882.29 392.07,472.33 '/%3E%3Cpolygon fill='%233C3C3B' fill-rule='nonzero' points='392.07,956.52 387.24,962.41 387.24,1263.28 392.07,1277.38 784.37,724.89 '/%3E%3Cpolygon fill='%238C8C8C' fill-rule='nonzero' points='392.07,1277.38 392.07,956.52 -0,724.89 '/%3E%3Cpolygon fill='%23141414' fill-rule='nonzero' points='392.07,882.29 784.13,650.54 392.07,472.33 '/%3E%3Cpolygon fill='%23393939' fill-rule='nonzero' points='0,650.54 392.07,882.29 392.07,472.33 '/%3E%3C/g%3E%3C/g%3E%3C/g%3E%3C/svg%3E%0A\",\"tokenFeatures\":[\"swap\",\"bridge\"]},{\"address\":\"0xF57e7e7C23978C3cAEC3C3548E3D615c346e79fF\",\"chainId\":1,\"name\":\"Immutable X\",\"symbol\":\"IMX\",\"decimals\":18,\"icon\":\"data:image/svg+xml,%3C%3Fxml version='1.0' encoding='utf-8'%3F%3E%3Csvg version='1.1' id='Layer_1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' x='0px' y='0px' viewBox='0 0 139 113' style='enable-background:new 0 0 139 113;' xml:space='preserve'%3E%3Cstyle type='text/css'%3E .st0%7Bclip-path:url(%23SVGID_00000053504646934646330740000009134454895836103350_);%7D .st1%7Bfill:%2317B5CB;%7D%0A%3C/style%3E%3Cg%3E%3Cdefs%3E%3Crect id='SVGID_1_' width='139' height='113'/%3E%3C/defs%3E%3CclipPath id='SVGID_00000035518931339590433170000002358037249938198420_'%3E%3Cuse xlink:href='%23SVGID_1_' style='overflow:visible;'/%3E%3C/clipPath%3E%3Cg style='clip-path:url(%23SVGID_00000035518931339590433170000002358037249938198420_);'%3E%3Cpath class='st1' d='M124.1,0h14.6L79.5,67.6c-1.5,1.7-1.6,4.3-0.1,6.1l34.1,39.7H98.3L66.8,76.6l-1.6-2c-1.5-1.7-1.4-4.4,0.1-6.1 L124.1,0z'/%3E%3Cpath class='st1' d='M91.2,73.7c-1-1.1-1.3-2.7-1-4.1c0.3-0.8,0.8-1.6,1.4-2.2l3.9-4.3l43.5,50.3h-13.8 C125.2,113.4,99.7,83.6,91.2,73.7z'/%3E%3Cpath class='st1' d='M15.2,113.4H0l46.6-53.9c1.5-1.7,1.5-4.3,0-6L0.4,0H15l46.5,53.9c1.2,1.6,1.4,3.9,0.1,5.4 C49.4,73.4,15.2,113.4,15.2,113.4z'/%3E%3Cpath class='st1' d='M40.6,0h-14l43.1,49.9c0,0,0.1-0.1,4.9-5.8c1.3-1.5,1.6-3.4,0.1-4.9C65.7,30,40.6,0,40.6,0z'/%3E%3Cpath class='st1' d='M82.6,34.8L112.5,0H98.3L82.7,18.2l-4.5,5.3c-1.5,1.7-1.6,4.3-0.1,6.1C79.2,30.9,82.6,34.8,82.6,34.8z'/%3E%3Cpath class='st1' d='M56.6,78.6l-29.9,34.8h14.1l15.6-18.2l4.5-5.3c1.5-1.7,1.6-4.3,0.1-6.1C59.9,82.5,56.6,78.6,56.6,78.6z'/%3E%3C/g%3E%3C/g%3E%3C/svg%3E%0A\",\"tokenFeatures\":[\"swap\",\"bridge\"]},{\"chainId\":11155111,\"name\":\"Sep Eth\",\"symbol\":\"ETH\",\"decimals\":18,\"icon\":\"data:image/svg+xml,%3C%3Fxml version='1.0' encoding='UTF-8'%3F%3E%3C!DOCTYPE svg PUBLIC '-//W3C//DTD SVG 1.1//EN' 'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'%3E%3Csvg xmlns='http://www.w3.org/2000/svg' xml:space='preserve' width='100%25' height='100%25' version='1.1' shape-rendering='geometricPrecision' text-rendering='geometricPrecision' image-rendering='optimizeQuality' fill-rule='evenodd' clip-rule='evenodd'%0AviewBox='0 0 784.37 1277.39' xmlns:xlink='http://www.w3.org/1999/xlink' xmlns:xodm='http://www.corel.com/coreldraw/odm/2003'%3E%3Cg id='Layer_x0020_1'%3E%3Cmetadata id='CorelCorpID_0Corel-Layer'/%3E%3Cg id='_1421394342400'%3E%3Cg%3E%3Cpolygon fill='%23343434' fill-rule='nonzero' points='392.07,0 383.5,29.11 383.5,873.74 392.07,882.29 784.13,650.54 '/%3E%3Cpolygon fill='%238C8C8C' fill-rule='nonzero' points='392.07,0 -0,650.54 392.07,882.29 392.07,472.33 '/%3E%3Cpolygon fill='%233C3C3B' fill-rule='nonzero' points='392.07,956.52 387.24,962.41 387.24,1263.28 392.07,1277.38 784.37,724.89 '/%3E%3Cpolygon fill='%238C8C8C' fill-rule='nonzero' points='392.07,1277.38 392.07,956.52 -0,724.89 '/%3E%3Cpolygon fill='%23141414' fill-rule='nonzero' points='392.07,882.29 784.13,650.54 392.07,472.33 '/%3E%3Cpolygon fill='%23393939' fill-rule='nonzero' points='0,650.54 392.07,882.29 392.07,472.33 '/%3E%3C/g%3E%3C/g%3E%3C/g%3E%3C/svg%3E%0A\",\"tokenFeatures\":[\"swap\",\"bridge\"]},{\"chainId\":11155111,\"name\":\"Immutable Test token\",\"address\":\"0x40cAdc2BC5d25B9c669B8E09c68eCcb9B80873f7\",\"symbol\":\"TEST\",\"decimals\":18,\"icon\":\"data:image/svg+xml,%3C%3Fxml version='1.0' encoding='utf-8'%3F%3E%3Csvg version='1.1' id='Layer_1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' x='0px' y='0px' viewBox='0 0 139 113' style='enable-background:new 0 0 139 113;' xml:space='preserve'%3E%3Cstyle type='text/css'%3E .st0%7Bclip-path:url(%23SVGID_00000053504646934646330740000009134454895836103350_);%7D .st1%7Bfill:%2317B5CB;%7D%0A%3C/style%3E%3Cg%3E%3Cdefs%3E%3Crect id='SVGID_1_' width='139' height='113'/%3E%3C/defs%3E%3CclipPath id='SVGID_00000035518931339590433170000002358037249938198420_'%3E%3Cuse xlink:href='%23SVGID_1_' style='overflow:visible;'/%3E%3C/clipPath%3E%3Cg style='clip-path:url(%23SVGID_00000035518931339590433170000002358037249938198420_);'%3E%3Cpath class='st1' d='M124.1,0h14.6L79.5,67.6c-1.5,1.7-1.6,4.3-0.1,6.1l34.1,39.7H98.3L66.8,76.6l-1.6-2c-1.5-1.7-1.4-4.4,0.1-6.1 L124.1,0z'/%3E%3Cpath class='st1' d='M91.2,73.7c-1-1.1-1.3-2.7-1-4.1c0.3-0.8,0.8-1.6,1.4-2.2l3.9-4.3l43.5,50.3h-13.8 C125.2,113.4,99.7,83.6,91.2,73.7z'/%3E%3Cpath class='st1' d='M15.2,113.4H0l46.6-53.9c1.5-1.7,1.5-4.3,0-6L0.4,0H15l46.5,53.9c1.2,1.6,1.4,3.9,0.1,5.4 C49.4,73.4,15.2,113.4,15.2,113.4z'/%3E%3Cpath class='st1' d='M40.6,0h-14l43.1,49.9c0,0,0.1-0.1,4.9-5.8c1.3-1.5,1.6-3.4,0.1-4.9C65.7,30,40.6,0,40.6,0z'/%3E%3Cpath class='st1' d='M82.6,34.8L112.5,0H98.3L82.7,18.2l-4.5,5.3c-1.5,1.7-1.6,4.3-0.1,6.1C79.2,30.9,82.6,34.8,82.6,34.8z'/%3E%3Cpath class='st1' d='M56.6,78.6l-29.9,34.8h14.1l15.6-18.2l4.5-5.3c1.5-1.7,1.6-4.3,0.1-6.1C59.9,82.5,56.6,78.6,56.6,78.6z'/%3E%3C/g%3E%3C/g%3E%3C/svg%3E%0A\",\"tokenFeatures\":[\"swap\",\"bridge\"]},{\"chainId\":1442,\"name\":\"WETH\",\"address\":\"0x4F062A3EAeC3730560aB89b5CE5aC0ab2C5517aE\",\"symbol\":\"WETH\",\"decimals\":18,\"icon\":\"data:image/svg+xml,%3C%3Fxml version='1.0' encoding='UTF-8'%3F%3E%3C!DOCTYPE svg PUBLIC '-//W3C//DTD SVG 1.1//EN' 'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'%3E%3Csvg xmlns='http://www.w3.org/2000/svg' xml:space='preserve' width='100%25' height='100%25' version='1.1' shape-rendering='geometricPrecision' text-rendering='geometricPrecision' image-rendering='optimizeQuality' fill-rule='evenodd' clip-rule='evenodd'%0AviewBox='0 0 784.37 1277.39' xmlns:xlink='http://www.w3.org/1999/xlink' xmlns:xodm='http://www.corel.com/coreldraw/odm/2003'%3E%3Cg id='Layer_x0020_1'%3E%3Cmetadata id='CorelCorpID_0Corel-Layer'/%3E%3Cg id='_1421394342400'%3E%3Cg%3E%3Cpolygon fill='%23343434' fill-rule='nonzero' points='392.07,0 383.5,29.11 383.5,873.74 392.07,882.29 784.13,650.54 '/%3E%3Cpolygon fill='%238C8C8C' fill-rule='nonzero' points='392.07,0 -0,650.54 392.07,882.29 392.07,472.33 '/%3E%3Cpolygon fill='%233C3C3B' fill-rule='nonzero' points='392.07,956.52 387.24,962.41 387.24,1263.28 392.07,1277.38 784.37,724.89 '/%3E%3Cpolygon fill='%238C8C8C' fill-rule='nonzero' points='392.07,1277.38 392.07,956.52 -0,724.89 '/%3E%3Cpolygon fill='%23141414' fill-rule='nonzero' points='392.07,882.29 784.13,650.54 392.07,472.33 '/%3E%3Cpolygon fill='%23393939' fill-rule='nonzero' points='0,650.54 392.07,882.29 392.07,472.33 '/%3E%3C/g%3E%3C/g%3E%3C/g%3E%3C/svg%3E%0A\",\"tokenFeatures\":[\"swap\",\"bridge\"]},{\"address\":\"0x72958b06abdF2701AcE6ceb3cE0B8B1CE11E0851\",\"chainId\":1442,\"name\":\"Immutable X\",\"symbol\":\"IMX\",\"decimals\":18,\"icon\":\"data:image/svg+xml,%3C%3Fxml version='1.0' encoding='utf-8'%3F%3E%3Csvg version='1.1' id='Layer_1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' x='0px' y='0px' viewBox='0 0 139 113' style='enable-background:new 0 0 139 113;' xml:space='preserve'%3E%3Cstyle type='text/css'%3E .st0%7Bclip-path:url(%23SVGID_00000053504646934646330740000009134454895836103350_);%7D .st1%7Bfill:%2317B5CB;%7D%0A%3C/style%3E%3Cg%3E%3Cdefs%3E%3Crect id='SVGID_1_' width='139' height='113'/%3E%3C/defs%3E%3CclipPath id='SVGID_00000035518931339590433170000002358037249938198420_'%3E%3Cuse xlink:href='%23SVGID_1_' style='overflow:visible;'/%3E%3C/clipPath%3E%3Cg style='clip-path:url(%23SVGID_00000035518931339590433170000002358037249938198420_);'%3E%3Cpath class='st1' d='M124.1,0h14.6L79.5,67.6c-1.5,1.7-1.6,4.3-0.1,6.1l34.1,39.7H98.3L66.8,76.6l-1.6-2c-1.5-1.7-1.4-4.4,0.1-6.1 L124.1,0z'/%3E%3Cpath class='st1' d='M91.2,73.7c-1-1.1-1.3-2.7-1-4.1c0.3-0.8,0.8-1.6,1.4-2.2l3.9-4.3l43.5,50.3h-13.8 C125.2,113.4,99.7,83.6,91.2,73.7z'/%3E%3Cpath class='st1' d='M15.2,113.4H0l46.6-53.9c1.5-1.7,1.5-4.3,0-6L0.4,0H15l46.5,53.9c1.2,1.6,1.4,3.9,0.1,5.4 C49.4,73.4,15.2,113.4,15.2,113.4z'/%3E%3Cpath class='st1' d='M40.6,0h-14l43.1,49.9c0,0,0.1-0.1,4.9-5.8c1.3-1.5,1.6-3.4,0.1-4.9C65.7,30,40.6,0,40.6,0z'/%3E%3Cpath class='st1' d='M82.6,34.8L112.5,0H98.3L82.7,18.2l-4.5,5.3c-1.5,1.7-1.6,4.3-0.1,6.1C79.2,30.9,82.6,34.8,82.6,34.8z'/%3E%3Cpath class='st1' d='M56.6,78.6l-29.9,34.8h14.1l15.6-18.2l4.5-5.3c1.5-1.7,1.6-4.3,0.1-6.1C59.9,82.5,56.6,78.6,56.6,78.6z'/%3E%3C/g%3E%3C/g%3E%3C/svg%3E%0A\",\"tokenFeatures\":[\"swap\",\"bridge\"]}]");
4856
+
4857
+
4858
+ const $efe60cea83bfc4e8$var$filterTokenList = ({ type: type , chainId: chainId , exclude: exclude })=>((/*@__PURE__*/$parcel$interopDefault($cda6003506e4182e$exports))).filter((token)=>{
4859
+ const skipChainIdCheck = !chainId;
4860
+ const chainIdMatches = token.chainId === chainId;
4861
+ const tokenNotExcluded = !exclude?.map((excludeToken)=>excludeToken.address).includes(token.address || "");
4862
+ const allowAllTokens = type === (exports.TokenFilterTypes).ALL;
4863
+ const tokenAllowedForType = token.tokenFeatures.includes(type);
4864
+ return (skipChainIdCheck || chainIdMatches) && tokenNotExcluded && (allowAllTokens || tokenAllowedForType);
4865
+ });
4866
+ const $efe60cea83bfc4e8$export$473cec51305fdae8 = async ({ type: type = (exports.TokenFilterTypes).ALL , chainId: chainId , exclude: exclude })=>{
4867
+ const filteredTokenList = $efe60cea83bfc4e8$var$filterTokenList({
4868
+ type: type,
4869
+ chainId: chainId,
4870
+ exclude: exclude
4871
+ }).map((token)=>({
4872
+ name: token.name,
4873
+ symbol: token.symbol,
4874
+ decimals: token.decimals,
4875
+ address: token.address,
4876
+ icon: token.icon
4877
+ }));
4878
+ return {
4879
+ tokens: filteredTokenList
4880
+ };
4881
+ };
4882
+
4883
+
4884
+
4885
+
4886
+ const $1564e43dde50bb61$export$df96cd8d56be0ab1 = async (config, provider, walletAddress)=>await ($a8bc256d81a5e2c1$export$bacc563de539c6c3)(async ()=>{
4887
+ const networkInfo = await ($de192de6ef100f9f$export$79f13b4cfaaf0d09)(config, provider);
4888
+ if (!networkInfo.isSupported) throw new ($a8bc256d81a5e2c1$export$b722478a3cbfa3bc)(`Chain:${networkInfo.chainId} is not a supported chain`, (exports.CheckoutErrorType).CHAIN_NOT_SUPPORTED_ERROR, {
4889
+ chainName: networkInfo.name
4890
+ });
4891
+ const balance = await provider.getBalance(walletAddress);
4892
+ return {
4893
+ balance: balance,
4894
+ formattedBalance: (ethers.utils).formatUnits(balance, networkInfo.nativeCurrency.decimals),
4895
+ token: networkInfo.nativeCurrency
4896
+ };
4897
+ }, {
4898
+ type: (exports.CheckoutErrorType).GET_BALANCE_ERROR
4899
+ });
4900
+ async function $1564e43dde50bb61$export$60e0fe116a0e6ed0(provider, walletAddress, contractAddress) {
4901
+ return await ($a8bc256d81a5e2c1$export$bacc563de539c6c3)(async ()=>{
4902
+ const contract = new (ethers.Contract)(contractAddress, JSON.stringify(($762782b6c862d954$export$db5daa1b5156ccfe)), provider);
4903
+ const name = await contract.name();
4904
+ const symbol = await contract.symbol();
4905
+ const balance = await contract.balanceOf(walletAddress);
4906
+ const decimals = await contract.decimals();
4907
+ const formattedBalance = (ethers.utils).formatUnits(balance, decimals);
4908
+ return {
4909
+ balance: balance,
4910
+ formattedBalance: formattedBalance,
4911
+ token: {
4912
+ name: name,
4913
+ symbol: symbol,
4914
+ decimals: decimals,
4915
+ address: contractAddress
4916
+ }
4917
+ };
4918
+ }, {
4919
+ type: (exports.CheckoutErrorType).GET_ERC20_BALANCE_ERROR
4920
+ });
4921
+ }
4922
+ const $1564e43dde50bb61$export$fee49741664a4d7e = async (config, provider, walletAddress, chainId)=>{
4923
+ if (!Object.values((exports.ChainId)).includes(chainId)) throw new ($a8bc256d81a5e2c1$export$b722478a3cbfa3bc)(`ChainId ${chainId} is not supported`, (exports.CheckoutErrorType).CHAIN_NOT_SUPPORTED_ERROR);
4924
+ if (!provider.provider?.request) throw new ($a8bc256d81a5e2c1$export$b722478a3cbfa3bc)("provider object is missing request function", (exports.CheckoutErrorType).PROVIDER_REQUEST_MISSING_ERROR);
4925
+ const tokenList = await ($efe60cea83bfc4e8$export$473cec51305fdae8)({
4926
+ type: (exports.TokenFilterTypes).ALL,
4927
+ chainId: chainId
4928
+ });
4929
+ const allBalancePromises = [];
4930
+ allBalancePromises.push($1564e43dde50bb61$export$df96cd8d56be0ab1(config, provider, walletAddress));
4931
+ tokenList.tokens.filter((token)=>token.address).forEach((token)=>allBalancePromises.push($1564e43dde50bb61$export$60e0fe116a0e6ed0(provider, walletAddress, token.address ?? "")));
4932
+ const balanceResults = await Promise.allSettled(allBalancePromises);
4933
+ const getBalanceResults = balanceResults.filter((result)=>result.status === "fulfilled").map((fulfilledResult)=>fulfilledResult.value);
4934
+ return {
4935
+ balances: getBalanceResults
4936
+ };
4937
+ };
4938
+
4939
+
4940
+
4941
+
4942
+
4943
+
4944
+
4945
+
4946
+
4947
+ var $6f3c55a615003cbf$exports = {};
4948
+ $6f3c55a615003cbf$exports = JSON.parse('[{"connectionProvider":"metamask","icon":"some-icon-url","name":"MetaMask","description":"complete web3 wallet solution","platform":["desktop"]},{"connectionProvider":"passport","icon":"pp-icon","name":"Passport","description":"Web3 with your email!","platform":["mobile","desktop"]},{"connectionProvider":"gamestop","icon":"gme-icon","name":"GameStop","description":"Never stopping the game!","platform":["mobile"]}]');
4949
+
4950
+
4951
+ async function $5cdde2ffe6360fec$export$a822caa90d7eef09({ type: type = (exports.WalletFilterTypes).ALL , exclude: exclude }) {
4952
+ // todo:For async API call, use the CheckoutError with errorType:API_CALL_ERROR?? or any other
4953
+ const filteredWalletsList = ((/*@__PURE__*/$parcel$interopDefault($6f3c55a615003cbf$exports))).filter((wallet)=>{
4954
+ const walletNotExcluded = !exclude?.map((excludeWallet)=>excludeWallet.connectionProvider).includes(wallet.connectionProvider);
4955
+ const allowAllWallets = type === (exports.WalletFilterTypes).ALL;
4956
+ const walletsAllowedForType = wallet.platform.includes(type);
4957
+ return walletNotExcluded && (allowAllWallets || walletsAllowedForType);
4958
+ }).map((wallet)=>{
4959
+ const { platform: platform , ...walletInfo } = wallet;
4960
+ return walletInfo;
4961
+ });
4962
+ return {
4963
+ wallets: filteredWalletsList
4964
+ };
4965
+ }
4966
+
4967
+
4968
+
4969
+
4970
+
4971
+
4972
+ const $dbe95599a4661140$export$8e0e7ffc78696d30 = async (params)=>{
4973
+ const { provider: provider , transaction: transaction } = params;
4974
+ return await ($a8bc256d81a5e2c1$export$bacc563de539c6c3)(async ()=>{
4975
+ const transactionResponse = await provider.getSigner().sendTransaction(transaction);
4976
+ return {
4977
+ transactionResponse: transactionResponse
4978
+ };
4979
+ }, {
4980
+ type: (exports.CheckoutErrorType).TRANSACTION_ERROR
4981
+ });
4982
+ };
4983
+
4984
+
4985
+
4986
+
4987
+
4988
+
4989
+
4990
+
4991
+ class $4013c5c91bb535f6$export$47a4ed4a38b9eecf extends Error {
4992
+ constructor(message){
4993
+ super(message);
4994
+ this.message = message;
4995
+ }
4996
+ }
4997
+ class $4013c5c91bb535f6$export$4823433c4a67bbc6 {
4998
+ constructor(config){
4999
+ // validate input
5000
+ if (!Object.values((exports.Environment)).includes(config.baseConfig.environment)) throw new $4013c5c91bb535f6$export$47a4ed4a38b9eecf("Invalid checkout configuration of environment");
5001
+ this.environment = config.baseConfig.environment;
5002
+ this.networkMap = config.baseConfig.environment === (exports.Environment).PRODUCTION ? ($a47e48dd2c04791b$export$6f24f3cef7d501c4) : ($a47e48dd2c04791b$export$3e81fc0987227f10);
5003
+ }
5004
+ }
5005
+
5006
+
5007
+
5008
+
5009
+ class $a8cb37a3fc8eb863$export$1f60ba4ec72508a0 {
5010
+ constructor(config = ($bc2bfebf768286d3$export$6a2ba3c3bd042990)){
5011
+ this.config = new ($4013c5c91bb535f6$export$4823433c4a67bbc6)(config);
5012
+ }
5013
+ /**
5014
+ * Check if a wallet is connected to the current application
5015
+ * without requesting permission from the wallet and hence triggering a connect popup.
5016
+ * @param {CheckConnectionParams} params - The necessary data required to verify a wallet connection status.
5017
+ * @returns Wallet connection status details.
5018
+ * @throws {@link ErrorType}
5019
+ */ // eslint-disable-next-line class-methods-use-this
5020
+ async checkIsWalletConnected(params) {
5021
+ return $c99672cf2294e839$export$2d040992269b4717(params.providerPreference);
5022
+ }
5023
+ /**
5024
+ * Establish a connection with a wallet provider such as MetaMask and returns the provider object and the current network details.
5025
+ * @param {ConnectParams} params - The necessary data required to establish a connection with a wallet provider.
5026
+ * @returns Wallet provider and current network information.
5027
+ * @throws {@link ErrorType}
5028
+ */ async connect(params) {
5029
+ this.providerPreference = params.providerPreference;
5030
+ const provider = await $c99672cf2294e839$export$fba2f6c3656e07c1(params);
5031
+ const networkInfo = await $de192de6ef100f9f$export$79f13b4cfaaf0d09(this.config, provider);
5032
+ return {
5033
+ provider: provider,
5034
+ network: networkInfo
5035
+ };
5036
+ }
5037
+ /**
5038
+ * Switch the currently connected wallet to a new network.
5039
+ * @param {SwitchNetworkParams} params - The necessary data required to switch network.
5040
+ * @returns The new network information.
5041
+ * @throws {@link ErrorType}
5042
+ */ async switchNetwork(params) {
5043
+ if (!this.providerPreference) throw new ($a8bc256d81a5e2c1$export$b722478a3cbfa3bc)("connect should be called before switchNetwork to set the provider preference", (exports.CheckoutErrorType).PROVIDER_PREFERENCE_ERROR);
5044
+ return await $de192de6ef100f9f$export$b827d9418aeb5dbd(this.config, this.providerPreference, params.provider, params.chainId);
5045
+ }
5046
+ /**
5047
+ * Fetch the balance of the native token of the current connected network or,
5048
+ * if a contract address is provided, it will return the balance of that ERC20 token. For example,
5049
+ * if the wallet is connected to the Ethereum Mainnet then the function gets the wallet ETH L1 balance.
5050
+ * @param {GetBalanceParams} params - The necessary data required to fetch the wallet balance.
5051
+ * @returns Native token balance for the given wallet.
5052
+ * @throws {@link ErrorType}
5053
+ */ async getBalance(params) {
5054
+ if (!params.contractAddress || params.contractAddress === "") return await $1564e43dde50bb61$export$df96cd8d56be0ab1(this.config, params.provider, params.walletAddress);
5055
+ return await $1564e43dde50bb61$export$60e0fe116a0e6ed0(params.provider, params.walletAddress, params.contractAddress);
5056
+ }
5057
+ /**
5058
+ * Fetch all available balances (ERC20 & Native) of the current connected network of the given wallet.
5059
+ * It will loop through the list of allowed tokens and check for balance on each one.
5060
+ * @param {GetAllBalancesParams} params - The necessary data required to fetch all the wallet balances.
5061
+ * @returns List of tokens balance for the given wallet.
5062
+ * @throws {@link ErrorType}
5063
+ */ async getAllBalances(params) {
5064
+ return $1564e43dde50bb61$export$fee49741664a4d7e(this.config, params.provider, params.walletAddress, params.chainId);
5065
+ }
5066
+ /**
5067
+ * Fetch the list of available networks that a wallet can add or/and switch to.
5068
+ * @param {GetNetworkAllowListParams} params - The necessary data required to fetch the list of available networks.
5069
+ * @returns List of networks.
5070
+ * @throws {@link ErrorType}
5071
+ */ async getNetworkAllowList(params) {
5072
+ return await $de192de6ef100f9f$export$3043f6442a9ef563(this.config, params);
5073
+ }
5074
+ /**
5075
+ * Get the list of tokens which are allowed to be used with the product.
5076
+ * @param {GetTokenAllowListParams} params - The necessary data required to fetch the list of allowed tokens.
5077
+ * @returns List of allowed tokens.
5078
+ * @throws {@link ErrorType}
5079
+ */ // eslint-disable-next-line class-methods-use-this
5080
+ async getTokenAllowList(params) {
5081
+ return await $efe60cea83bfc4e8$export$473cec51305fdae8(params);
5082
+ }
5083
+ /**
5084
+ * Fetch the list of wallets which are available to connect with.
5085
+ * @param {GetWalletAllowListParams} params - The necessary data required to fetch the list of allowed wallets.
5086
+ * @returns List of allowed wallets.
5087
+ * @throws {@link ErrorType}
5088
+ */ // eslint-disable-next-line class-methods-use-this
5089
+ async getWalletAllowList(params) {
5090
+ return await $5cdde2ffe6360fec$export$a822caa90d7eef09(params);
5091
+ }
5092
+ /**
5093
+ * Send a generic transaction to the provider.
5094
+ * @param {SendTransactionParams} params - The necessary data required to send a transaction.
5095
+ * @returns Transaction response.
5096
+ * @throws {@link ErrorType}
5097
+ * @remarks
5098
+ * Further documenation can be found at [MetaMask | Sending Transactions](https://docs.metamask.io/guide/sending-transactions.html).
5099
+ */ // eslint-disable-next-line class-methods-use-this
5100
+ async sendTransaction(params) {
5101
+ return await $dbe95599a4661140$export$8e0e7ffc78696d30(params);
5102
+ }
5103
+ /**
5104
+ * Get network information about the currently selected network.
5105
+ * @param {GetNetworkParams} params - The necessary data required to get the current network information.
5106
+ * @returns Network details.
5107
+ * @throws {@link ErrorType}
5108
+ */ async getNetworkInfo(params) {
5109
+ return await $de192de6ef100f9f$export$79f13b4cfaaf0d09(this.config, params.provider);
5110
+ }
5111
+ }
5112
+
5113
+ function $parcel$export(e, n, v, s) {
5114
+ Object.defineProperty(e, n, {get: v, set: s, enumerable: true, configurable: true});
5115
+ }
5116
+ // Definitions | Events
5117
+ var $207ed853f11d19d5$exports = {};
5118
+
5119
+ $parcel$export($207ed853f11d19d5$exports, "IMTBLWidgetEvents", () => exports.IMTBLWidgetEvents);
5120
+ /**
5121
+ * Enum representing the events emitted by the widgets.
5122
+ */ exports.IMTBLWidgetEvents = void 0;
5123
+ (function(IMTBLWidgetEvents) {
5124
+ IMTBLWidgetEvents["IMTBL_CONNECT_WIDGET_EVENT"] = "imtbl-connect-widget";
5125
+ IMTBLWidgetEvents["IMTBL_WALLET_WIDGET_EVENT"] = "imtbl-wallet-widget";
5126
+ IMTBLWidgetEvents["IMTBL_SWAP_WIDGET_EVENT"] = "imtbl-swap-widget";
5127
+ IMTBLWidgetEvents["IMTBL_BRIDGE_WIDGET_EVENT"] = "imtbl-bridge-widget";
5128
+ IMTBLWidgetEvents["IMTBL_BUY_WIDGET_EVENT"] = "imtbl-buy-widget";
5129
+ IMTBLWidgetEvents["IMTBL_ONRAMP_WIDGET_EVENT"] = "imtbl-onramp-widget";
5130
+ })(exports.IMTBLWidgetEvents || (exports.IMTBLWidgetEvents = {}));
5131
+
5132
+
5133
+ var $a85ecdbd885c58ad$exports = {};
5134
+
5135
+ $parcel$export($a85ecdbd885c58ad$exports, "ConnectEventType", () => exports.ConnectEventType);
5136
+ exports.ConnectEventType = void 0;
5137
+ (function(ConnectEventType) {
5138
+ ConnectEventType["SUCCESS"] = "success";
5139
+ ConnectEventType["FAILURE"] = "failure";
5140
+ ConnectEventType["CLOSE_WIDGET"] = "close-widget";
5141
+ })(exports.ConnectEventType || (exports.ConnectEventType = {}));
5142
+
5143
+
5144
+ var $77b6aac5c353d4a9$exports = {};
5145
+
5146
+ $parcel$export($77b6aac5c353d4a9$exports, "WalletEventType", () => exports.WalletEventType);
5147
+ exports.WalletEventType = void 0;
5148
+ (function(WalletEventType) {
5149
+ WalletEventType["CLOSE_WIDGET"] = "close-widget";
5150
+ WalletEventType["NETWORK_SWITCH"] = "network-switch";
5151
+ WalletEventType["ADD_COINS"] = "add-coins";
5152
+ WalletEventType["REQUEST_SWAP"] = "request-swap";
5153
+ WalletEventType["REQUEST_BRIDGE"] = "request-bridge";
5154
+ WalletEventType["REQUEST_ONRAMP"] = "request-onramp";
5155
+ WalletEventType["DISCONNECT_WALLET"] = "disconnect-wallet";
5156
+ })(exports.WalletEventType || (exports.WalletEventType = {}));
5157
+
5158
+
5159
+ var $53d219e7f6bf0cd6$exports = {};
5160
+
5161
+ $parcel$export($53d219e7f6bf0cd6$exports, "SwapEventType", () => exports.SwapEventType);
5162
+ /**
5163
+ * Represents an event object emitted by the Swap Widget.
5164
+ * @property {SwapEventType} type - The type of the event.
5165
+ * @property {T} data - The data contained in the event.
5166
+ */ exports.SwapEventType = void 0;
5167
+ (function(SwapEventType) {
5168
+ SwapEventType["SUCCESS"] = "success";
5169
+ SwapEventType["FAILURE"] = "failure";
5170
+ SwapEventType["CLOSE_WIDGET"] = "close-widget";
5171
+ })(exports.SwapEventType || (exports.SwapEventType = {}));
5172
+
5173
+
5174
+ var $15cc9e120aa6f3bf$exports = {};
5175
+
5176
+ $parcel$export($15cc9e120aa6f3bf$exports, "BridgeEventType", () => exports.BridgeEventType);
5177
+ /**
5178
+ * Represents an event object emitted by the Bridge Widget.
5179
+ * @property {BridgeEventType} type - The type of the event.
5180
+ * @property {T} data - The data associated with the event.
5181
+ */ exports.BridgeEventType = void 0;
5182
+ (function(BridgeEventType) {
5183
+ BridgeEventType["CLOSE_WIDGET"] = "close-widget";
5184
+ BridgeEventType["SUCCESS"] = "success";
5185
+ BridgeEventType["FAILURE"] = "failure";
5186
+ })(exports.BridgeEventType || (exports.BridgeEventType = {}));
5187
+
5188
+
5189
+ var $98cbcca465beec95$exports = {};
5190
+
5191
+ $parcel$export($98cbcca465beec95$exports, "BuyEventType", () => exports.BuyEventType);
5192
+ /**
5193
+ * Represents an event object emitted by the Buy Widget.
5194
+ * @property {BuyEventType} type - The type of the event.
5195
+ * @property {T} data - The data contained in the event.
5196
+ */ exports.BuyEventType = void 0;
5197
+ (function(BuyEventType) {
5198
+ BuyEventType["SUCCESS"] = "success";
5199
+ BuyEventType["FAILURE"] = "failure";
5200
+ BuyEventType["NOT_CONNECTED"] = "not_connected";
5201
+ BuyEventType["CLOSE"] = "close";
5202
+ })(exports.BuyEventType || (exports.BuyEventType = {}));
5203
+
5204
+
5205
+ var $66ceef112c0ee49e$exports = {};
5206
+
5207
+ $parcel$export($66ceef112c0ee49e$exports, "OnRampEventType", () => exports.OnRampEventType);
5208
+ exports.OnRampEventType = void 0;
5209
+ exports.OnRampEventType || (exports.OnRampEventType = {});
5210
+ /* eslint-disable @typescript-eslint/naming-convention */
5211
+
5212
+ var $14d7a2bbb79e0dae$exports = {};
5213
+
5214
+ $parcel$export($14d7a2bbb79e0dae$exports, "Network", () => exports.Network);
5215
+ $parcel$export($14d7a2bbb79e0dae$exports, "WidgetTheme", () => exports.WidgetTheme);
5216
+ $parcel$export($14d7a2bbb79e0dae$exports, "CheckoutWidgetTagNames", () => exports.CheckoutWidgetTagNames);
5217
+ /**
5218
+ * Enum representing the networks supported by Checkout.
5219
+ */ exports.Network = void 0;
5220
+ (function(Network) {
5221
+ Network["ETHEREUM"] = "Ethereum";
5222
+ Network["SEPOLIA"] = "Sepolia";
5223
+ Network["IMTBL_ZKEVM_TESTNET"] = "Immutable zkEVM Testnet";
5224
+ Network["IMTBL_ZKEVM_DEVNET"] = "Immutable zkEVM Devnet";
5225
+ Network["POLYGON_ZKEVM_TESTNET"] = "Polygon zkEVM Testnet";
5226
+ Network["POLYGON_ZKEVM"] = "Polygon zkEVM";
5227
+ })(exports.Network || (exports.Network = {}));
5228
+ exports.WidgetTheme = void 0;
5229
+ (function(WidgetTheme) {
5230
+ WidgetTheme["LIGHT"] = "light";
5231
+ WidgetTheme["DARK"] = "dark";
5232
+ WidgetTheme["CUSTOM"] = "custom";
5233
+ })(exports.WidgetTheme || (exports.WidgetTheme = {}));
5234
+ exports.CheckoutWidgetTagNames = void 0;
5235
+ (function(CheckoutWidgetTagNames) {
5236
+ CheckoutWidgetTagNames["CONNECT"] = "imtbl-connect";
5237
+ CheckoutWidgetTagNames["WALLET"] = "imtbl-wallet";
5238
+ CheckoutWidgetTagNames["SWAP"] = "imtbl-swap";
5239
+ CheckoutWidgetTagNames["BUY"] = "imtbl-buy";
5240
+ CheckoutWidgetTagNames["BRIDGE"] = "imtbl-bridge";
5241
+ CheckoutWidgetTagNames["EXAMPLE"] = "imtbl-example";
5242
+ })(exports.CheckoutWidgetTagNames || (exports.CheckoutWidgetTagNames = {}));
5243
+
5244
+
5245
+ var $1f969328e5988c99$exports = {};
5246
+
5247
+ $parcel$export($1f969328e5988c99$exports, "BridgeReact", () => $1f969328e5988c99$export$30f61ebf204c69f6);
5248
+
5249
+
5250
+ function $1f969328e5988c99$export$30f61ebf204c69f6(props) {
5251
+ const { providerPreference: providerPreference , fromContractAddress: fromContractAddress , amount: amount , fromNetwork: fromNetwork } = props;
5252
+ const config = window.ImtblCheckoutWidgetConfig;
5253
+ return /*#__PURE__*/ (jsxRuntime.jsx)("imtbl-bridge", {
5254
+ widgetConfig: config,
5255
+ providerPreference: providerPreference,
5256
+ fromContractAddress: fromContractAddress ?? "",
5257
+ fromNetwork: fromNetwork ?? "",
5258
+ amount: amount ?? ""
5259
+ });
5260
+ }
5261
+
5262
+
5263
+ var $f22931ca9e2f35b6$exports = {};
5264
+
5265
+ $parcel$export($f22931ca9e2f35b6$exports, "BuyReact", () => $f22931ca9e2f35b6$export$d13582032b79b401);
5266
+
5267
+
5268
+ function $f22931ca9e2f35b6$export$d13582032b79b401(props) {
5269
+ const { providerPreference: providerPreference , orderId: orderId } = props;
5270
+ const config = window.ImtblCheckoutWidgetConfig;
5271
+ return /*#__PURE__*/ (jsxRuntime.jsx)("imtbl-buy", {
5272
+ widgetConfig: config,
5273
+ providerPreference: providerPreference,
5274
+ orderId: orderId
5275
+ });
5276
+ }
5277
+
5278
+
5279
+ var $f2083cd30e2f5c56$exports = {};
5280
+
5281
+ $parcel$export($f2083cd30e2f5c56$exports, "ConnectReact", () => $f2083cd30e2f5c56$export$49d62957f420a1e2);
5282
+
5283
+
5284
+ function $f2083cd30e2f5c56$export$49d62957f420a1e2(props) {
5285
+ const { providerPreference: providerPreference } = props;
5286
+ const config = window.ImtblCheckoutWidgetConfig;
5287
+ return /*#__PURE__*/ (jsxRuntime.jsx)("imtbl-connect", {
5288
+ widgetConfig: config,
5289
+ providerPreference: providerPreference ?? "metamask"
5290
+ });
5291
+ }
5292
+
5293
+
5294
+ var $a4fbb8e3a6aeff58$exports = {};
5295
+
5296
+ $parcel$export($a4fbb8e3a6aeff58$exports, "SwapReact", () => $a4fbb8e3a6aeff58$export$971e031379577f4);
5297
+ /* eslint-disable max-len */
5298
+
5299
+ function $a4fbb8e3a6aeff58$export$971e031379577f4(props) {
5300
+ const { providerPreference: providerPreference , fromContractAddress: fromContractAddress , amount: amount , toContractAddress: toContractAddress } = props;
5301
+ const config = window.ImtblCheckoutWidgetConfig;
5302
+ return /*#__PURE__*/ (jsxRuntime.jsx)("imtbl-swap", {
5303
+ widgetConfig: config,
5304
+ providerPreference: providerPreference,
5305
+ fromContractAddress: fromContractAddress ?? "",
5306
+ toContractAddress: toContractAddress ?? "",
5307
+ amount: amount ?? ""
5308
+ });
5309
+ }
5310
+
5311
+
5312
+ var $89d55ace0f8f1c07$exports = {};
5313
+
5314
+ $parcel$export($89d55ace0f8f1c07$exports, "WalletReact", () => $89d55ace0f8f1c07$export$ceaac94f34dba154);
5315
+
5316
+
5317
+ function $89d55ace0f8f1c07$export$ceaac94f34dba154(props) {
5318
+ const { providerPreference: providerPreference , useConnectWidget: useConnectWidget } = props;
5319
+ const config = window.ImtblCheckoutWidgetConfig;
5320
+ return /*#__PURE__*/ (jsxRuntime.jsx)("imtbl-wallet", {
5321
+ widgetConfig: config,
5322
+ useConnectWidget: useConnectWidget?.toString(),
5323
+ providerPreference: providerPreference ?? "metamask"
5324
+ });
5325
+ }
5326
+
5327
+
5328
+ var $d087956fd1002f80$exports = {};
5329
+
5330
+ $parcel$export($d087956fd1002f80$exports, "ExampleReact", () => $d087956fd1002f80$export$fa517eee6594d26c);
5331
+
5332
+
5333
+
5334
+ function $d087956fd1002f80$export$fa517eee6594d26c(props) {
5335
+ const { providerPreference: // eslint-disable-next-line @typescript-eslint/no-unused-vars
5336
+ providerPreference , environment: environment , theme: theme } = props;
5337
+ return /*#__PURE__*/ (jsxRuntime.jsx)("imtbl-example", {
5338
+ environment: environment ?? (exports.Environment).SANDBOX,
5339
+ theme: theme ?? "dark",
5340
+ providerPreference: providerPreference
5341
+ });
5342
+ }
5343
+
5344
+
5345
+ var $430e3eda76fa4d5f$exports = {};
5346
+
5347
+ $parcel$export($430e3eda76fa4d5f$exports, "CheckoutWidgets", () => $430e3eda76fa4d5f$export$af210a0808087845);
5348
+ $parcel$export($430e3eda76fa4d5f$exports, "UpdateConfig", () => $430e3eda76fa4d5f$export$bf1548ba7e61c17f);
5349
+ $parcel$export($430e3eda76fa4d5f$exports, "SetProvider", () => $430e3eda76fa4d5f$export$931068bc678f0d73);
5350
+ function $430e3eda76fa4d5f$export$af210a0808087845(config) {
5351
+ const checkoutWidgetJS = document.createElement("script");
5352
+ checkoutWidgetJS.setAttribute("src", "http://localhost:3000/lib/js/imtbl-checkout.js");
5353
+ document.head.appendChild(checkoutWidgetJS);
5354
+ window.ImtblCheckoutWidgetConfig = JSON.stringify(config);
5355
+ }
5356
+ function $430e3eda76fa4d5f$export$bf1548ba7e61c17f(config) {
5357
+ window.ImtblCheckoutWidgetConfig = JSON.stringify(config);
5358
+ }
5359
+ function $430e3eda76fa4d5f$export$931068bc678f0d73(tagName, provider) {
5360
+ if (!provider) {
5361
+ // eslint-disable-next-line no-console
5362
+ console.error("no provider parsed");
5363
+ return;
5364
+ }
5365
+ const elements = document.getElementsByTagName(tagName);
5366
+ const widget = elements[0];
5367
+ let attempts = 0;
5368
+ const maxAttempts = 10;
5369
+ let timer;
5370
+ const attemptToSetProvider = ()=>{
5371
+ try {
5372
+ widget.setProvider(provider);
5373
+ window.clearInterval(timer);
5374
+ } catch (err) {
5375
+ attempts++;
5376
+ if (attempts >= maxAttempts) {
5377
+ window.clearInterval(timer);
5378
+ // eslint-disable-next-line no-console
5379
+ console.error("failed to set the provider");
5380
+ }
5381
+ }
5382
+ };
5383
+ timer = window.setInterval(attemptToSetProvider, 10);
5384
+ attemptToSetProvider();
5385
+ }
5386
+
1484
5387
  Object.defineProperty(exports, 'imxClientCreateStarkSigner', {
1485
5388
  enumerable: true,
1486
5389
  get: function () { return coreSdk.createStarkSigner; }
@@ -1489,7 +5392,23 @@ Object.defineProperty(exports, 'imxClientGenerateLegacyStarkPrivateKey', {
1489
5392
  enumerable: true,
1490
5393
  get: function () { return coreSdk.generateLegacyStarkPrivateKey; }
1491
5394
  });
5395
+ exports.guardian = guardian__namespace;
5396
+ exports.BridgeReact = $1f969328e5988c99$export$30f61ebf204c69f6;
5397
+ exports.BuyReact = $f22931ca9e2f35b6$export$d13582032b79b401;
5398
+ exports.Checkout = $a8cb37a3fc8eb863$export$1f60ba4ec72508a0;
5399
+ exports.CheckoutWidgets = $430e3eda76fa4d5f$export$af210a0808087845;
5400
+ exports.ConnectReact = $f2083cd30e2f5c56$export$49d62957f420a1e2;
5401
+ exports.ExampleReact = $d087956fd1002f80$export$fa517eee6594d26c;
5402
+ exports.GenericIMXProvider = GenericIMXProvider;
1492
5403
  exports.ImmutableConfiguration = ImmutableConfiguration;
1493
5404
  exports.ImmutableXClient = ImmutableXClient;
5405
+ exports.MetaMaskIMXProvider = MetaMaskIMXProvider;
5406
+ exports.Orderbook = Orderbook;
1494
5407
  exports.Passport = Passport;
1495
5408
  exports.PassportError = PassportError;
5409
+ exports.ProviderConfiguration = ProviderConfiguration;
5410
+ exports.SetProvider = $430e3eda76fa4d5f$export$931068bc678f0d73;
5411
+ exports.SwapReact = $a4fbb8e3a6aeff58$export$971e031379577f4;
5412
+ exports.UpdateConfig = $430e3eda76fa4d5f$export$bf1548ba7e61c17f;
5413
+ exports.WalletReact = $89d55ace0f8f1c07$export$ceaac94f34dba154;
5414
+ exports.module = module$1;