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