@imtbl/sdk 0.1.3 → 0.1.4-alpha

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -7,6 +7,10 @@ var magicSdk = require('magic-sdk');
7
7
  var oidc = require('@magic-ext/oidc');
8
8
  var BN = require('bn.js');
9
9
  var encUtils = require('enc-utils');
10
+ var units = require('@ethersproject/units');
11
+ var bignumber = require('@ethersproject/bignumber');
12
+ var detectEthereumProvider = require('@metamask/detect-provider');
13
+ var providers = require('@ethersproject/providers');
10
14
 
11
15
  function _interopNamespaceDefault(e) {
12
16
  var n = Object.create(null);
@@ -569,6 +573,15 @@ async function signRaw(payload, signer) {
569
573
  const signature = deserializeSignature(await signer.signMessage(payload));
570
574
  return serializeEthSignature(signature);
571
575
  }
576
+ async function signMessage(message, signer) {
577
+ const ethAddress = await signer.getAddress();
578
+ const ethSignature = await signRaw(message, signer);
579
+ return {
580
+ message,
581
+ ethAddress,
582
+ ethSignature,
583
+ };
584
+ }
572
585
 
573
586
  /**
574
587
  * Helper method to convert token type to a SignableToken type
@@ -882,7 +895,7 @@ class ConfirmationScreen {
882
895
  }
883
896
 
884
897
  const ERC721$1 = 'ERC721';
885
- const transfer = ({ request, transfersApi, starkSigner, user, passportConfig, }) => {
898
+ const transfer$1 = ({ request, transfersApi, starkSigner, user, passportConfig, }) => {
886
899
  return withPassportError(async () => {
887
900
  const transferAmount = request.type === ERC721$1 ? '1' : request.amount;
888
901
  const getSignableTransferRequest = {
@@ -992,7 +1005,7 @@ async function batchNftTransfer({ user, starkSigner, request, transfersApi, pass
992
1005
  }
993
1006
 
994
1007
  const ERC721 = 'ERC721';
995
- async function createOrder({ starkSigner, user, request, ordersApi, passportConfig, }) {
1008
+ async function createOrder$1({ starkSigner, user, request, ordersApi, passportConfig, }) {
996
1009
  return withPassportError(async () => {
997
1010
  const ethAddress = user.etherKey;
998
1011
  const amountSell = request.sell.type === ERC721 ? '1' : request.sell.amount;
@@ -1047,7 +1060,7 @@ async function createOrder({ starkSigner, user, request, ordersApi, passportConf
1047
1060
  };
1048
1061
  }, PassportErrorType.CREATE_ORDER_ERROR);
1049
1062
  }
1050
- async function cancelOrder({ user, starkSigner, request, ordersApi, passportConfig, }) {
1063
+ async function cancelOrder$1({ user, starkSigner, request, ordersApi, passportConfig, }) {
1051
1064
  return withPassportError(async () => {
1052
1065
  const getSignableCancelOrderRequest = {
1053
1066
  order_id: request.order_id,
@@ -1082,7 +1095,7 @@ async function cancelOrder({ user, starkSigner, request, ordersApi, passportConf
1082
1095
  }, PassportErrorType.CANCEL_ORDER_ERROR);
1083
1096
  }
1084
1097
 
1085
- async function exchangeTransfer({ user, starkSigner, request, exchangesApi, }) {
1098
+ async function exchangeTransfer$1({ user, starkSigner, request, exchangesApi, }) {
1086
1099
  return withPassportError(async () => {
1087
1100
  const ethAddress = user.etherKey;
1088
1101
  const transferAmount = request.amount;
@@ -1125,7 +1138,7 @@ async function exchangeTransfer({ user, starkSigner, request, exchangesApi, }) {
1125
1138
  }, PassportErrorType.EXCHANGE_TRANSFER_ERROR);
1126
1139
  }
1127
1140
 
1128
- async function createTrade({ request, tradesApi, user, starkSigner, passportConfig, }) {
1141
+ async function createTrade$1({ request, tradesApi, user, starkSigner, passportConfig, }) {
1129
1142
  return withPassportError(async () => {
1130
1143
  const ethAddress = user.etherKey;
1131
1144
  const getSignableTradeRequest = {
@@ -1177,29 +1190,20 @@ async function createTrade({ request, tradesApi, user, starkSigner, passportConf
1177
1190
  class PassportImxProvider {
1178
1191
  user;
1179
1192
  starkSigner;
1180
- transfersApi;
1181
- ordersApi;
1182
1193
  passportConfig;
1183
- exchangesApi;
1184
- tradesApi;
1185
- constructor({ user, starkSigner, passportConfig }) {
1194
+ immutableXClient;
1195
+ constructor({ user, starkSigner, passportConfig, immutableXClient, }) {
1186
1196
  this.user = user;
1187
1197
  this.starkSigner = starkSigner;
1188
1198
  this.passportConfig = passportConfig;
1189
- const apiConfig = new coreSdk.Configuration({
1190
- basePath: passportConfig.imxApiBasePath,
1191
- });
1192
- this.transfersApi = new coreSdk.TransfersApi(apiConfig);
1193
- this.ordersApi = new coreSdk.OrdersApi(apiConfig);
1194
- this.exchangesApi = new coreSdk.ExchangesApi(apiConfig);
1195
- this.tradesApi = new coreSdk.TradesApi(apiConfig);
1199
+ this.immutableXClient = immutableXClient;
1196
1200
  }
1197
1201
  async transfer(request) {
1198
- return transfer({
1202
+ return transfer$1({
1199
1203
  request,
1200
1204
  user: this.user,
1201
1205
  starkSigner: this.starkSigner,
1202
- transfersApi: this.transfersApi,
1206
+ transfersApi: this.immutableXClient.transfersApi,
1203
1207
  passportConfig: this.passportConfig,
1204
1208
  });
1205
1209
  }
@@ -1210,29 +1214,29 @@ class PassportImxProvider {
1210
1214
  throw new PassportError('Operation not supported', PassportErrorType.OPERATION_NOT_SUPPORTED_ERROR);
1211
1215
  }
1212
1216
  createOrder(request) {
1213
- return createOrder({
1217
+ return createOrder$1({
1214
1218
  request,
1215
1219
  user: this.user,
1216
1220
  starkSigner: this.starkSigner,
1217
- ordersApi: this.ordersApi,
1221
+ ordersApi: this.immutableXClient.ordersApi,
1218
1222
  passportConfig: this.passportConfig,
1219
1223
  });
1220
1224
  }
1221
1225
  cancelOrder(request) {
1222
- return cancelOrder({
1226
+ return cancelOrder$1({
1223
1227
  request,
1224
1228
  user: this.user,
1225
1229
  starkSigner: this.starkSigner,
1226
- ordersApi: this.ordersApi,
1230
+ ordersApi: this.immutableXClient.ordersApi,
1227
1231
  passportConfig: this.passportConfig,
1228
1232
  });
1229
1233
  }
1230
1234
  createTrade(request) {
1231
- return createTrade({
1235
+ return createTrade$1({
1232
1236
  request,
1233
1237
  user: this.user,
1234
1238
  starkSigner: this.starkSigner,
1235
- tradesApi: this.tradesApi,
1239
+ tradesApi: this.immutableXClient.tradesApi,
1236
1240
  passportConfig: this.passportConfig,
1237
1241
  });
1238
1242
  }
@@ -1241,16 +1245,16 @@ class PassportImxProvider {
1241
1245
  request,
1242
1246
  user: this.user,
1243
1247
  starkSigner: this.starkSigner,
1244
- transfersApi: this.transfersApi,
1248
+ transfersApi: this.immutableXClient.transfersApi,
1245
1249
  passportConfig: this.passportConfig,
1246
1250
  });
1247
1251
  }
1248
1252
  exchangeTransfer(request) {
1249
- return exchangeTransfer({
1253
+ return exchangeTransfer$1({
1250
1254
  request,
1251
1255
  user: this.user,
1252
1256
  starkSigner: this.starkSigner,
1253
- exchangesApi: this.exchangesApi,
1257
+ exchangesApi: this.immutableXClient.exchangeApi,
1254
1258
  });
1255
1259
  }
1256
1260
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
@@ -1297,7 +1301,6 @@ class PassportConfiguration {
1297
1301
  passportDomain;
1298
1302
  magicPublishableApiKey;
1299
1303
  magicProviderId;
1300
- imxApiBasePath;
1301
1304
  oidcConfiguration;
1302
1305
  baseConfig;
1303
1306
  constructor({ baseConfig, overrides, ...oidcConfiguration }) {
@@ -1315,14 +1318,12 @@ class PassportConfiguration {
1315
1318
  'magicPublishableApiKey',
1316
1319
  'magicProviderId',
1317
1320
  'passportDomain',
1318
- 'imxApiBasePath',
1319
1321
  ], 'overrides');
1320
1322
  this.network = overrides.network;
1321
1323
  this.authenticationDomain = overrides.authenticationDomain;
1322
1324
  this.passportDomain = overrides.passportDomain;
1323
1325
  this.magicPublishableApiKey = overrides.magicPublishableApiKey;
1324
1326
  this.magicProviderId = overrides.magicProviderId;
1325
- this.imxApiBasePath = overrides.imxApiBasePath;
1326
1327
  }
1327
1328
  else {
1328
1329
  switch (baseConfig.environment) {
@@ -1332,7 +1333,6 @@ class PassportConfiguration {
1332
1333
  this.magicPublishableApiKey = 'pk_live_10F423798A540ED7';
1333
1334
  this.magicProviderId = 'fSMzaRQ4O7p4fttl7pCyGVtJS_G70P8SNsLXtPPGHo0=';
1334
1335
  this.passportDomain = 'https://passport.sandbox.immutable.com';
1335
- this.imxApiBasePath = 'https://api.sandbox.x.immutable.com';
1336
1336
  break;
1337
1337
  }
1338
1338
  case exports.Environment.PRODUCTION: {
@@ -1341,7 +1341,6 @@ class PassportConfiguration {
1341
1341
  this.magicPublishableApiKey = 'pk_live_10F423798A540ED7';
1342
1342
  this.magicProviderId = 'fSMzaRQ4O7p4fttl7pCyGVtJS_G70P8SNsLXtPPGHo0=';
1343
1343
  this.passportDomain = 'https://passport.immutable.com';
1344
- this.imxApiBasePath = 'https://api.x.immutable.com';
1345
1344
  break;
1346
1345
  }
1347
1346
  }
@@ -1386,11 +1385,16 @@ class Passport {
1386
1385
  authManager;
1387
1386
  magicAdapter;
1388
1387
  config;
1388
+ immutableXClient;
1389
1389
  constructor(passportModuleConfiguration) {
1390
- const passportConfiguration = new PassportConfiguration(passportModuleConfiguration);
1391
- this.config = passportConfiguration;
1390
+ this.config = new PassportConfiguration(passportModuleConfiguration);
1392
1391
  this.authManager = new AuthManager(this.config);
1393
1392
  this.magicAdapter = new MagicAdapter(this.config);
1393
+ this.immutableXClient =
1394
+ passportModuleConfiguration.overrides?.immutableXClient ||
1395
+ new ImmutableXClient({
1396
+ baseConfig: passportModuleConfiguration.baseConfig,
1397
+ });
1394
1398
  }
1395
1399
  async getImxProvider(user) {
1396
1400
  if (!user || !user.idToken) {
@@ -1405,6 +1409,7 @@ class Passport {
1405
1409
  user: updatedUser,
1406
1410
  starkSigner,
1407
1411
  passportConfig: this.config,
1412
+ immutableXClient: this.immutableXClient,
1408
1413
  });
1409
1414
  }
1410
1415
  const userWithEtherKey = user;
@@ -1412,6 +1417,7 @@ class Passport {
1412
1417
  user: userWithEtherKey,
1413
1418
  starkSigner,
1414
1419
  passportConfig: this.config,
1420
+ immutableXClient: this.immutableXClient,
1415
1421
  });
1416
1422
  }
1417
1423
  async connectImxSilent() {
@@ -1444,14 +1450,10 @@ class Passport {
1444
1450
  return user?.accessToken;
1445
1451
  }
1446
1452
  async registerUser(userAdminKeySigner, starkSigner, jwt) {
1447
- const configuration = new coreSdk.Configuration({
1448
- basePath: this.config.imxApiBasePath,
1449
- });
1450
- const usersApi = new coreSdk.UsersApi(configuration);
1451
1453
  await registerPassport({
1452
1454
  ethSigner: userAdminKeySigner,
1453
1455
  starkSigner,
1454
- usersApi,
1456
+ usersApi: this.immutableXClient.usersApi,
1455
1457
  }, jwt);
1456
1458
  const updatedUser = await this.authManager.requestRefreshTokenAfterRegistration();
1457
1459
  if (!updatedUser) {
@@ -1461,6 +1463,1754 @@ class Passport {
1461
1463
  }
1462
1464
  }
1463
1465
 
1466
+ function isChainValid(chainID, config) {
1467
+ return chainID === config.ethConfiguration.chainID;
1468
+ }
1469
+ async function validateChain(signer, config) {
1470
+ const chainID = await signer.getChainId();
1471
+ if (!isChainValid(chainID, config))
1472
+ throw new Error('The wallet used for this operation is not connected to the correct network.');
1473
+ }
1474
+
1475
+ async function transfer({ signers: { ethSigner, starkSigner }, request, config, }) {
1476
+ await validateChain(ethSigner, config.immutableXConfig);
1477
+ const ethAddress = await ethSigner.getAddress();
1478
+ const transfersApi = new coreSdk.TransfersApi(config.immutableXConfig.apiConfiguration);
1479
+ const transferAmount = request.type === 'ERC721' ? '1' : request.amount;
1480
+ const signableResult = await transfersApi.getSignableTransferV1({
1481
+ getSignableTransferRequest: {
1482
+ sender: ethAddress,
1483
+ token: convertToSignableToken(request),
1484
+ amount: transferAmount,
1485
+ receiver: request.receiver,
1486
+ },
1487
+ });
1488
+ const { signable_message: signableMessage, payload_hash: payloadHash } = signableResult.data;
1489
+ const ethSignature = await signRaw(signableMessage, ethSigner);
1490
+ const starkSignature = await starkSigner.signMessage(payloadHash);
1491
+ const transferSigningParams = {
1492
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1493
+ sender_stark_key: signableResult.data.sender_stark_key,
1494
+ sender_vault_id: signableResult.data.sender_vault_id,
1495
+ receiver_stark_key: signableResult.data.receiver_stark_key,
1496
+ receiver_vault_id: signableResult.data.receiver_vault_id,
1497
+ asset_id: signableResult.data.asset_id,
1498
+ amount: signableResult.data.amount,
1499
+ nonce: signableResult.data.nonce,
1500
+ expiration_timestamp: signableResult.data.expiration_timestamp,
1501
+ stark_signature: starkSignature,
1502
+ };
1503
+ const response = await transfersApi.createTransferV1({
1504
+ createTransferRequest: transferSigningParams,
1505
+ xImxEthAddress: ethAddress,
1506
+ xImxEthSignature: ethSignature,
1507
+ });
1508
+ return {
1509
+ sent_signature: response?.data.sent_signature,
1510
+ status: response?.data.status?.toString(),
1511
+ time: response?.data.time,
1512
+ transfer_id: response?.data.transfer_id,
1513
+ };
1514
+ }
1515
+ async function batchTransfer({ signers: { ethSigner, starkSigner }, request, config, }) {
1516
+ await validateChain(ethSigner, config.immutableXConfig);
1517
+ const ethAddress = await ethSigner.getAddress();
1518
+ const transfersApi = new coreSdk.TransfersApi(config.immutableXConfig.apiConfiguration);
1519
+ const signableRequests = request.map((nftTransfer) => {
1520
+ return {
1521
+ amount: '1',
1522
+ token: convertToSignableToken({
1523
+ type: 'ERC721',
1524
+ tokenId: nftTransfer.tokenId,
1525
+ tokenAddress: nftTransfer.tokenAddress,
1526
+ }),
1527
+ receiver: nftTransfer.receiver,
1528
+ };
1529
+ });
1530
+ const signableResult = await transfersApi.getSignableTransfer({
1531
+ getSignableTransferRequestV2: {
1532
+ sender_ether_key: ethAddress,
1533
+ signable_requests: signableRequests,
1534
+ },
1535
+ });
1536
+ const signableMessage = signableResult.data.signable_message;
1537
+ if (signableMessage === undefined) {
1538
+ throw new Error('Invalid response from Signable registration offchain');
1539
+ }
1540
+ const ethSignature = await signRaw(signableMessage, ethSigner);
1541
+ const requests = [];
1542
+ for (const resp of signableResult.data.signable_responses) {
1543
+ const starkSignature = await starkSigner.signMessage(resp.payload_hash);
1544
+ const req = {
1545
+ sender_vault_id: resp.sender_vault_id,
1546
+ receiver_stark_key: resp.receiver_stark_key,
1547
+ receiver_vault_id: resp.receiver_vault_id,
1548
+ asset_id: resp.asset_id,
1549
+ amount: resp.amount,
1550
+ nonce: resp.nonce,
1551
+ expiration_timestamp: resp.expiration_timestamp,
1552
+ stark_signature: starkSignature,
1553
+ };
1554
+ requests.push(req);
1555
+ }
1556
+ // TODO: throw error on missing payload hash?
1557
+ const transferSigningParams = {
1558
+ sender_stark_key: signableResult.data.sender_stark_key,
1559
+ requests,
1560
+ };
1561
+ const response = await transfersApi.createTransfer({
1562
+ createTransferRequestV2: transferSigningParams,
1563
+ xImxEthAddress: ethAddress,
1564
+ xImxEthSignature: ethSignature,
1565
+ });
1566
+ return {
1567
+ transfer_ids: response?.data.transfer_ids,
1568
+ };
1569
+ }
1570
+
1571
+ async function createOrder({ signers, request, config, }) {
1572
+ await validateChain(signers.ethSigner, config.immutableXConfig);
1573
+ const ethAddress = await signers.ethSigner.getAddress();
1574
+ const ordersApi = new coreSdk.OrdersApi(config.immutableXConfig.apiConfiguration);
1575
+ const amountSell = request.sell.type === 'ERC721' ? '1' : request.sell.amount;
1576
+ const amountBuy = request.buy.type === 'ERC721' ? '1' : request.buy.amount;
1577
+ const getSignableOrderRequest = {
1578
+ user: ethAddress,
1579
+ amount_buy: amountBuy,
1580
+ token_buy: convertToSignableToken(request.buy),
1581
+ amount_sell: amountSell,
1582
+ token_sell: convertToSignableToken(request.sell),
1583
+ fees: request.fees,
1584
+ expiration_timestamp: request.expiration_timestamp,
1585
+ };
1586
+ const getSignableOrderResponse = await ordersApi.getSignableOrder({
1587
+ getSignableOrderRequestV3: getSignableOrderRequest,
1588
+ });
1589
+ const { signable_message: signableMessage, payload_hash: payloadHash } = getSignableOrderResponse.data;
1590
+ const ethSignature = await signRaw(signableMessage, signers.ethSigner);
1591
+ const starkSignature = await signers.starkSigner.signMessage(payloadHash);
1592
+ const resp = getSignableOrderResponse.data;
1593
+ const orderParams = {
1594
+ createOrderRequest: {
1595
+ amount_buy: resp.amount_buy,
1596
+ amount_sell: resp.amount_sell,
1597
+ asset_id_buy: resp.asset_id_buy,
1598
+ asset_id_sell: resp.asset_id_sell,
1599
+ expiration_timestamp: resp.expiration_timestamp,
1600
+ include_fees: true,
1601
+ fees: request.fees,
1602
+ nonce: resp.nonce,
1603
+ stark_key: resp.stark_key,
1604
+ stark_signature: starkSignature,
1605
+ vault_id_buy: resp.vault_id_buy,
1606
+ vault_id_sell: resp.vault_id_sell,
1607
+ },
1608
+ xImxEthAddress: ethAddress,
1609
+ xImxEthSignature: ethSignature,
1610
+ };
1611
+ const createOrderResponse = await ordersApi.createOrder(orderParams);
1612
+ return {
1613
+ ...createOrderResponse.data,
1614
+ };
1615
+ }
1616
+ async function cancelOrder({ signers, request, config, }) {
1617
+ const ordersApi = new coreSdk.OrdersApi(config.immutableXConfig.apiConfiguration);
1618
+ const getSignableCancelOrderResponse = await ordersApi.getSignableCancelOrder({
1619
+ getSignableCancelOrderRequest: {
1620
+ order_id: request.order_id,
1621
+ },
1622
+ });
1623
+ const { signable_message: signableMessage, payload_hash: payloadHash } = getSignableCancelOrderResponse.data;
1624
+ const ethSignature = await signRaw(signableMessage, signers.ethSigner);
1625
+ const starkSignature = await signers.starkSigner.signMessage(payloadHash);
1626
+ const ethAddress = await signers.ethSigner.getAddress();
1627
+ const cancelOrderResponse = await ordersApi.cancelOrder({
1628
+ id: request.order_id.toString(),
1629
+ cancelOrderRequest: {
1630
+ order_id: request.order_id,
1631
+ stark_signature: starkSignature,
1632
+ },
1633
+ xImxEthAddress: ethAddress,
1634
+ xImxEthSignature: ethSignature,
1635
+ });
1636
+ return {
1637
+ order_id: cancelOrderResponse.data.order_id,
1638
+ status: cancelOrderResponse.data.status,
1639
+ };
1640
+ }
1641
+
1642
+ async function registerOffchain(signers, config) {
1643
+ await validateChain(signers.ethSigner, config.immutableXConfig);
1644
+ const usersApi = new coreSdk.UsersApi(config.immutableXConfig.apiConfiguration);
1645
+ const userAddress = await signers.ethSigner.getAddress();
1646
+ const starkPublicKey = await signers.starkSigner.getAddress();
1647
+ const signableResult = await usersApi.getSignableRegistrationOffchain({
1648
+ getSignableRegistrationRequest: {
1649
+ ether_key: userAddress,
1650
+ stark_key: starkPublicKey,
1651
+ },
1652
+ });
1653
+ const { signable_message: signableMessage, payload_hash: payloadHash } = signableResult.data;
1654
+ const ethSignature = await signRaw(signableMessage, signers.ethSigner);
1655
+ const starkSignature = await signers.starkSigner.signMessage(payloadHash);
1656
+ const registeredUser = await usersApi.registerUser({
1657
+ registerUserRequest: {
1658
+ eth_signature: ethSignature,
1659
+ ether_key: userAddress,
1660
+ stark_signature: starkSignature,
1661
+ stark_key: starkPublicKey,
1662
+ },
1663
+ });
1664
+ return registeredUser.data;
1665
+ }
1666
+ async function isRegisteredOnChain(starkPublicKey, ethSigner, config) {
1667
+ await validateChain(ethSigner, config.immutableXConfig);
1668
+ const registrationContract = coreSdk.Contracts.Registration.connect(config.immutableXConfig.ethConfiguration.registrationContractAddress, ethSigner);
1669
+ try {
1670
+ return await registrationContract.isRegistered(starkPublicKey);
1671
+ }
1672
+ catch (ex) {
1673
+ if (ex.reason === 'USER_UNREGISTERED') {
1674
+ return false;
1675
+ }
1676
+ throw ex;
1677
+ }
1678
+ }
1679
+ async function getSignableRegistrationOnchain(etherKey, starkPublicKey, usersApi) {
1680
+ const response = await usersApi.getSignableRegistration({
1681
+ getSignableRegistrationRequest: {
1682
+ ether_key: etherKey,
1683
+ stark_key: starkPublicKey,
1684
+ },
1685
+ });
1686
+ return {
1687
+ operator_signature: response.data.operator_signature,
1688
+ payload_hash: response.data.payload_hash,
1689
+ };
1690
+ }
1691
+
1692
+ const assertIsDefined = (value) => {
1693
+ if (value !== undefined)
1694
+ return value;
1695
+ throw new Error('undefined field exception');
1696
+ };
1697
+ async function prepareWithdrawalAction(params) {
1698
+ const { signers: { ethSigner, starkSigner }, type, config, } = params;
1699
+ await validateChain(ethSigner, params.config);
1700
+ const withdrawalsApi = new coreSdk.WithdrawalsApi(config.apiConfiguration);
1701
+ const withdrawalAmount = type === 'ERC721' ? '1' : params.amount;
1702
+ const signableWithdrawalResult = await withdrawalsApi.getSignableWithdrawal({
1703
+ getSignableWithdrawalRequest: {
1704
+ user: await ethSigner.getAddress(),
1705
+ token: convertToSignableToken(params),
1706
+ amount: withdrawalAmount,
1707
+ },
1708
+ });
1709
+ const { signable_message: signableMessage, payload_hash: payloadHash } = signableWithdrawalResult.data;
1710
+ const starkSignature = await starkSigner.signMessage(payloadHash);
1711
+ const { ethAddress, ethSignature } = await signMessage(signableMessage, ethSigner);
1712
+ const prepareWithdrawalResponse = await withdrawalsApi.createWithdrawal({
1713
+ createWithdrawalRequest: {
1714
+ stark_key: assertIsDefined(signableWithdrawalResult.data.stark_key),
1715
+ amount: withdrawalAmount,
1716
+ asset_id: assertIsDefined(signableWithdrawalResult.data.asset_id),
1717
+ vault_id: assertIsDefined(signableWithdrawalResult.data.vault_id),
1718
+ nonce: assertIsDefined(signableWithdrawalResult.data.nonce),
1719
+ stark_signature: starkSignature,
1720
+ },
1721
+ xImxEthAddress: ethAddress,
1722
+ xImxEthSignature: ethSignature,
1723
+ });
1724
+ return prepareWithdrawalResponse.data;
1725
+ }
1726
+
1727
+ async function getEncodeAssetInfo(assetType, tokenType, config, tokenData) {
1728
+ const encodingApi = new coreSdk.EncodingApi(config.apiConfiguration);
1729
+ const result = await encodingApi.encodeAsset({
1730
+ assetType,
1731
+ encodeAssetRequest: {
1732
+ token: {
1733
+ type: tokenType,
1734
+ ...(tokenData && { data: tokenData }),
1735
+ },
1736
+ },
1737
+ });
1738
+ return result.data;
1739
+ }
1740
+
1741
+ async function executeRegisterAndWithdrawERC20({ ethSigner, assetType, starkPublicKey, config, }) {
1742
+ const etherKey = await ethSigner.getAddress();
1743
+ const imxConfig = config.immutableXConfig;
1744
+ const usersApi = new coreSdk.UsersApi(imxConfig.apiConfiguration);
1745
+ const signableResult = await getSignableRegistrationOnchain(etherKey, starkPublicKey, usersApi);
1746
+ const contract = coreSdk.Contracts.Registration.connect(config.immutableXConfig.ethConfiguration.registrationContractAddress, ethSigner);
1747
+ const populatedTransaction = await contract.populateTransaction.registerAndWithdraw(etherKey, starkPublicKey, signableResult.operator_signature, assetType);
1748
+ return ethSigner.sendTransaction(populatedTransaction);
1749
+ }
1750
+ async function executeWithdrawERC20(ethSigner, assetType, starkPublicKey, config) {
1751
+ const contract = coreSdk.Contracts.Core.connect(config.ethConfiguration.coreContractAddress, ethSigner);
1752
+ const populatedTransaction = await contract.populateTransaction.withdraw(starkPublicKey, assetType);
1753
+ return ethSigner.sendTransaction(populatedTransaction);
1754
+ }
1755
+ async function completeERC20WithdrawalAction({ ethSigner, starkPublicKey, token, config, }) {
1756
+ await validateChain(ethSigner, config.immutableXConfig);
1757
+ const imxConfig = config.immutableXConfig;
1758
+ const assetType = await getEncodeAssetInfo('asset', 'ERC20', imxConfig, {
1759
+ token_address: token.tokenAddress,
1760
+ });
1761
+ const isRegistered = await isRegisteredOnChain(starkPublicKey, ethSigner, config);
1762
+ if (!isRegistered) {
1763
+ return executeRegisterAndWithdrawERC20({
1764
+ ethSigner,
1765
+ assetType: assetType.asset_type,
1766
+ starkPublicKey,
1767
+ config,
1768
+ });
1769
+ }
1770
+ else {
1771
+ return executeWithdrawERC20(ethSigner, assetType.asset_type, starkPublicKey, imxConfig);
1772
+ }
1773
+ }
1774
+
1775
+ async function executeWithdrawMintableERC721(ethSigner, assetType, starkPublicKey, mintingBlob, config) {
1776
+ const contract = coreSdk.Contracts.Core.connect(config.ethConfiguration.coreContractAddress, ethSigner);
1777
+ const populatedTransaction = await contract.populateTransaction.withdrawAndMint(starkPublicKey, assetType, mintingBlob);
1778
+ return ethSigner.sendTransaction(populatedTransaction);
1779
+ }
1780
+ async function executeRegisterAndWithdrawMintableERC721(ethSigner, assetType, starkPublicKey, mintingBlob, config) {
1781
+ const etherKey = await ethSigner.getAddress();
1782
+ const usersApi = new coreSdk.UsersApi(config.apiConfiguration);
1783
+ const signableResult = await getSignableRegistrationOnchain(etherKey, starkPublicKey, usersApi);
1784
+ const contract = coreSdk.Contracts.Registration.connect(config.ethConfiguration.registrationContractAddress, ethSigner);
1785
+ const populatedTransaction = await contract.populateTransaction.regsiterAndWithdrawAndMint(etherKey, starkPublicKey, signableResult.operator_signature, assetType, mintingBlob);
1786
+ return ethSigner.sendTransaction(populatedTransaction);
1787
+ }
1788
+ function getMintingBlob(token) {
1789
+ const id = token.data.id;
1790
+ const blueprint = token.data.blueprint || '';
1791
+ return encUtils__namespace.sanitizeHex(encUtils__namespace.utf8ToHex(`{${id}}:{${blueprint}}`));
1792
+ }
1793
+ async function completeMintableERC721Withdrawal(ethSigner, starkPublicKey, token, config) {
1794
+ const imxConfig = config.immutableXConfig;
1795
+ const assetType = await getEncodeAssetInfo('mintable-asset', 'ERC721', imxConfig, {
1796
+ id: token.data.id,
1797
+ token_address: token.data.tokenAddress,
1798
+ ...(token.data.blueprint && { blueprint: token.data.blueprint }),
1799
+ });
1800
+ const mintingBlob = getMintingBlob(token);
1801
+ const isRegistered = await isRegisteredOnChain(starkPublicKey, ethSigner, config);
1802
+ if (!isRegistered) {
1803
+ return executeRegisterAndWithdrawMintableERC721(ethSigner, assetType.asset_type, starkPublicKey, mintingBlob, imxConfig);
1804
+ }
1805
+ else {
1806
+ return executeWithdrawMintableERC721(ethSigner, assetType.asset_type, starkPublicKey, mintingBlob, imxConfig);
1807
+ }
1808
+ }
1809
+ async function executeRegisterAndWithdrawERC721(ethSigner, assetType, starkPublicKey, tokenId, config) {
1810
+ const etherKey = await ethSigner.getAddress();
1811
+ const usersApi = new coreSdk.UsersApi(config.apiConfiguration);
1812
+ const signableResult = await getSignableRegistrationOnchain(etherKey, starkPublicKey, usersApi);
1813
+ const contract = coreSdk.Contracts.Registration.connect(config.ethConfiguration.registrationContractAddress, ethSigner);
1814
+ const populatedTransaction = await contract.populateTransaction.registerAndWithdrawNft(etherKey, starkPublicKey, signableResult.operator_signature, assetType, tokenId);
1815
+ return ethSigner.sendTransaction(populatedTransaction);
1816
+ }
1817
+ async function executeWithdrawERC721(ethSigner, assetType, starkPublicKey, tokenId, config) {
1818
+ const contract = coreSdk.Contracts.Core.connect(config.ethConfiguration.coreContractAddress, ethSigner);
1819
+ const populatedTransaction = await contract.populateTransaction.withdrawNft(starkPublicKey, assetType, tokenId);
1820
+ return ethSigner.sendTransaction(populatedTransaction);
1821
+ }
1822
+ async function completeERC721Withdrawal(ethSigner, starkPublicKey, token, config) {
1823
+ const imxConfig = config.immutableXConfig;
1824
+ const assetType = await getEncodeAssetInfo('asset', 'ERC721', imxConfig, {
1825
+ token_id: token.tokenId,
1826
+ token_address: token.tokenAddress,
1827
+ });
1828
+ const isRegistered = await isRegisteredOnChain(starkPublicKey, ethSigner, config);
1829
+ if (!isRegistered) {
1830
+ return executeRegisterAndWithdrawERC721(ethSigner, assetType.asset_type, starkPublicKey, token.tokenId, imxConfig);
1831
+ }
1832
+ else {
1833
+ return executeWithdrawERC721(ethSigner, assetType.asset_type, starkPublicKey, token.tokenId, imxConfig);
1834
+ }
1835
+ }
1836
+ async function completeERC721WithdrawalAction({ ethSigner, starkPublicKey, token, config, }) {
1837
+ await validateChain(ethSigner, config.immutableXConfig);
1838
+ const tokenAddress = token.tokenAddress;
1839
+ const tokenId = token.tokenId;
1840
+ const imxConfig = config.immutableXConfig;
1841
+ const mintsApi = new coreSdk.MintsApi(imxConfig.apiConfiguration);
1842
+ return await mintsApi
1843
+ .getMintableTokenDetailsByClientTokenId({
1844
+ tokenAddress,
1845
+ tokenId,
1846
+ })
1847
+ .then((mintableToken) => completeMintableERC721Withdrawal(ethSigner, starkPublicKey, {
1848
+ type: 'ERC721',
1849
+ data: {
1850
+ id: tokenId,
1851
+ tokenAddress: tokenAddress,
1852
+ blueprint: mintableToken.data.blueprint,
1853
+ },
1854
+ }, config))
1855
+ .catch((error) => {
1856
+ if (error.response?.status === 404) {
1857
+ // token is already minted on L1
1858
+ return completeERC721Withdrawal(ethSigner, starkPublicKey, token, config);
1859
+ }
1860
+ throw error; // unable to recover from any other kind of error
1861
+ });
1862
+ }
1863
+
1864
+ async function executeRegisterAndWithdrawEth(ethSigner, assetType, starkPublicKey, config) {
1865
+ const etherKey = await ethSigner.getAddress();
1866
+ const usersApi = new coreSdk.UsersApi(config.apiConfiguration);
1867
+ const signableResult = await getSignableRegistrationOnchain(etherKey, starkPublicKey, usersApi);
1868
+ const contract = coreSdk.Contracts.Registration.connect(config.ethConfiguration.registrationContractAddress, ethSigner);
1869
+ const populatedTransaction = await contract.populateTransaction.registerAndWithdraw(etherKey, starkPublicKey, signableResult.operator_signature, assetType);
1870
+ return ethSigner.sendTransaction(populatedTransaction);
1871
+ }
1872
+ async function executeWithdrawEth(ethSigner, assetType, starkPublicKey, config) {
1873
+ const contract = coreSdk.Contracts.Core.connect(config.ethConfiguration.coreContractAddress, ethSigner);
1874
+ const populatedTransaction = await contract.populateTransaction.withdraw(starkPublicKey, assetType);
1875
+ return ethSigner.sendTransaction(populatedTransaction);
1876
+ }
1877
+ async function completeEthWithdrawalAction({ ethSigner, starkPublicKey, config, }) {
1878
+ await validateChain(ethSigner, config.immutableXConfig);
1879
+ const imxConfig = config.immutableXConfig;
1880
+ const assetType = await getEncodeAssetInfo('asset', 'ETH', imxConfig);
1881
+ const isRegistered = await isRegisteredOnChain(starkPublicKey, ethSigner, config);
1882
+ if (!isRegistered) {
1883
+ return executeRegisterAndWithdrawEth(ethSigner, assetType.asset_type, starkPublicKey, imxConfig);
1884
+ }
1885
+ else {
1886
+ return executeWithdrawEth(ethSigner, assetType.asset_type, starkPublicKey, imxConfig);
1887
+ }
1888
+ }
1889
+
1890
+ async function prepareWithdrawal({ signers, withdrawal, config, }) {
1891
+ return prepareWithdrawalAction({
1892
+ signers,
1893
+ config: config.immutableXConfig,
1894
+ ...withdrawal,
1895
+ });
1896
+ }
1897
+ async function completeWithdrawal({ signers: { ethSigner }, starkPublicKey, token, config, }) {
1898
+ switch (token.type) {
1899
+ case 'ETH':
1900
+ return completeEthWithdrawalAction({ ethSigner, starkPublicKey, config });
1901
+ case 'ERC20':
1902
+ return completeERC20WithdrawalAction({
1903
+ ethSigner,
1904
+ starkPublicKey,
1905
+ token,
1906
+ config,
1907
+ });
1908
+ case 'ERC721':
1909
+ return completeERC721WithdrawalAction({
1910
+ ethSigner,
1911
+ starkPublicKey,
1912
+ token,
1913
+ config,
1914
+ });
1915
+ }
1916
+ }
1917
+
1918
+ async function createTrade({ signers: { ethSigner, starkSigner }, request, config, }) {
1919
+ await validateChain(ethSigner, config.immutableXConfig);
1920
+ const ethAddress = await ethSigner.getAddress();
1921
+ const tradesApi = new coreSdk.TradesApi(config.immutableXConfig.apiConfiguration);
1922
+ const signableResult = await tradesApi.getSignableTrade({
1923
+ getSignableTradeRequest: {
1924
+ user: ethAddress,
1925
+ order_id: request.order_id,
1926
+ fees: request.fees,
1927
+ },
1928
+ });
1929
+ const { signable_message: signableMessage, payload_hash: payloadHash } = signableResult.data;
1930
+ const ethSignature = await signRaw(signableMessage, ethSigner);
1931
+ const starkSignature = await starkSigner.signMessage(payloadHash);
1932
+ const createTradeResponse = await tradesApi.createTrade({
1933
+ createTradeRequest: {
1934
+ amount_buy: signableResult.data.amount_buy,
1935
+ amount_sell: signableResult.data.amount_sell,
1936
+ asset_id_buy: signableResult.data.asset_id_buy,
1937
+ asset_id_sell: signableResult.data.asset_id_sell,
1938
+ expiration_timestamp: signableResult.data.expiration_timestamp,
1939
+ fee_info: signableResult.data.fee_info,
1940
+ fees: request.fees,
1941
+ include_fees: true,
1942
+ nonce: signableResult.data.nonce,
1943
+ order_id: request.order_id,
1944
+ stark_key: signableResult.data.stark_key,
1945
+ vault_id_buy: signableResult.data.vault_id_buy,
1946
+ vault_id_sell: signableResult.data.vault_id_sell,
1947
+ stark_signature: starkSignature,
1948
+ },
1949
+ xImxEthAddress: ethAddress,
1950
+ xImxEthSignature: ethSignature,
1951
+ });
1952
+ return createTradeResponse.data;
1953
+ }
1954
+
1955
+ async function depositEth({ signers: { ethSigner }, deposit, config, }) {
1956
+ await validateChain(ethSigner, config.immutableXConfig);
1957
+ const user = await ethSigner.getAddress();
1958
+ const data = {
1959
+ decimals: 18,
1960
+ };
1961
+ const amount = units.parseUnits(deposit.amount, 'wei');
1962
+ const imxConfig = config.immutableXConfig;
1963
+ const depositsApi = new coreSdk.DepositsApi(imxConfig.apiConfiguration);
1964
+ const encodingApi = new coreSdk.EncodingApi(imxConfig.apiConfiguration);
1965
+ const usersApi = new coreSdk.UsersApi(imxConfig.apiConfiguration);
1966
+ const getSignableDepositRequest = {
1967
+ user,
1968
+ token: {
1969
+ type: deposit.type,
1970
+ data,
1971
+ },
1972
+ amount: amount.toString(),
1973
+ };
1974
+ const signableDepositResult = await depositsApi.getSignableDeposit({
1975
+ getSignableDepositRequest,
1976
+ });
1977
+ const encodingResult = await encodingApi.encodeAsset({
1978
+ assetType: 'asset',
1979
+ encodeAssetRequest: {
1980
+ token: {
1981
+ type: deposit.type,
1982
+ },
1983
+ },
1984
+ });
1985
+ const assetType = encodingResult.data.asset_type;
1986
+ const starkPublicKey = signableDepositResult.data.stark_key;
1987
+ const vaultId = signableDepositResult.data.vault_id;
1988
+ const isRegistered = await isRegisteredOnChain(starkPublicKey, ethSigner, config);
1989
+ if (!isRegistered) {
1990
+ return executeRegisterAndDepositEth(ethSigner, amount, assetType, starkPublicKey, vaultId, imxConfig, usersApi);
1991
+ }
1992
+ else {
1993
+ return executeDepositEth(ethSigner, amount, assetType, starkPublicKey, vaultId, imxConfig);
1994
+ }
1995
+ }
1996
+ async function executeRegisterAndDepositEth(ethSigner, amount, assetType, starkPublicKey, vaultId, config, usersApi) {
1997
+ const etherKey = await ethSigner.getAddress();
1998
+ const coreContract = coreSdk.Contracts.Core.connect(config.ethConfiguration.coreContractAddress, ethSigner);
1999
+ const signableResult = await getSignableRegistrationOnchain(etherKey, starkPublicKey, usersApi);
2000
+ const populatedTransaction = await coreContract.populateTransaction.registerAndDepositEth(etherKey, starkPublicKey, signableResult.operator_signature, assetType, vaultId);
2001
+ return ethSigner.sendTransaction({ ...populatedTransaction, value: amount });
2002
+ }
2003
+ async function executeDepositEth(ethSigner, amount, assetType, starkPublicKey, vaultId, config) {
2004
+ const coreContract = coreSdk.Contracts.Core.connect(config.ethConfiguration.coreContractAddress, ethSigner);
2005
+ const populatedTransaction = await coreContract.populateTransaction['deposit(uint256,uint256,uint256)'](starkPublicKey, assetType, vaultId);
2006
+ return ethSigner.sendTransaction({ ...populatedTransaction, value: amount });
2007
+ }
2008
+
2009
+ async function depositERC20({ signers: { ethSigner }, deposit, config, }) {
2010
+ await validateChain(ethSigner, config.immutableXConfig);
2011
+ const { apiConfiguration, ethConfiguration } = config.immutableXConfig;
2012
+ const user = await ethSigner.getAddress();
2013
+ const tokensApi = new coreSdk.TokensApi(apiConfiguration);
2014
+ const depositsApi = new coreSdk.DepositsApi(apiConfiguration);
2015
+ const encodingApi = new coreSdk.EncodingApi(apiConfiguration);
2016
+ const usersApi = new coreSdk.UsersApi(apiConfiguration);
2017
+ // Get decimals for this specific ERC20
2018
+ const token = await tokensApi.getToken({ address: deposit.tokenAddress });
2019
+ const decimals = parseInt(token.data.decimals);
2020
+ const data = {
2021
+ decimals,
2022
+ token_address: deposit.tokenAddress,
2023
+ };
2024
+ const amount = units.parseUnits(deposit.amount, 0); // 0 to always use undecimalized value
2025
+ // Approve whether an amount of token from an account can be spent by a third-party account
2026
+ const tokenContract = coreSdk.Contracts.IERC20.connect(deposit.tokenAddress, ethSigner);
2027
+ const approveTransaction = await tokenContract.populateTransaction.approve(ethConfiguration.coreContractAddress, amount);
2028
+ await ethSigner.sendTransaction(approveTransaction);
2029
+ const getSignableDepositRequest = {
2030
+ user,
2031
+ token: {
2032
+ type: deposit.type,
2033
+ data,
2034
+ },
2035
+ amount: amount.toString(),
2036
+ };
2037
+ const signableDepositResult = await depositsApi.getSignableDeposit({
2038
+ getSignableDepositRequest,
2039
+ });
2040
+ // Perform encoding on asset details to get an assetType (required for stark contract request)
2041
+ const encodingResult = await encodingApi.encodeAsset({
2042
+ assetType: 'asset',
2043
+ encodeAssetRequest: {
2044
+ token: {
2045
+ type: deposit.type,
2046
+ data: {
2047
+ token_address: deposit.tokenAddress,
2048
+ },
2049
+ },
2050
+ },
2051
+ });
2052
+ const assetType = encodingResult.data.asset_type;
2053
+ const starkPublicKey = signableDepositResult.data.stark_key;
2054
+ const vaultId = signableDepositResult.data.vault_id;
2055
+ const quantizedAmount = bignumber.BigNumber.from(signableDepositResult.data.amount);
2056
+ const isRegistered = await isRegisteredOnChain(starkPublicKey, ethSigner, config);
2057
+ if (!isRegistered) {
2058
+ return executeRegisterAndDepositERC20(ethSigner, quantizedAmount, assetType, starkPublicKey, vaultId, ethConfiguration, usersApi);
2059
+ }
2060
+ else {
2061
+ return executeDepositERC20(ethSigner, quantizedAmount, assetType, starkPublicKey, vaultId, ethConfiguration);
2062
+ }
2063
+ }
2064
+ async function executeDepositERC20(ethSigner, quantizedAmount, assetType, starkPublicKey, vaultId, config) {
2065
+ const coreContract = coreSdk.Contracts.Core.connect(config.coreContractAddress, ethSigner);
2066
+ const populatedTransaction = await coreContract.populateTransaction.depositERC20(starkPublicKey, assetType, vaultId, quantizedAmount);
2067
+ return ethSigner.sendTransaction(populatedTransaction);
2068
+ }
2069
+ async function executeRegisterAndDepositERC20(ethSigner, quantizedAmount, assetType, starkPublicKey, vaultId, config, usersApi) {
2070
+ const etherKey = await ethSigner.getAddress();
2071
+ const coreContract = coreSdk.Contracts.Core.connect(config.coreContractAddress, ethSigner);
2072
+ const signableResult = await getSignableRegistrationOnchain(etherKey, starkPublicKey, usersApi);
2073
+ const populatedTransaction = await coreContract.populateTransaction.registerAndDepositERC20(etherKey, starkPublicKey, signableResult.operator_signature, assetType, vaultId, quantizedAmount);
2074
+ return ethSigner.sendTransaction(populatedTransaction);
2075
+ }
2076
+
2077
+ async function depositERC721({ signers: { ethSigner }, deposit, config, }) {
2078
+ await validateChain(ethSigner, config.immutableXConfig);
2079
+ const user = await ethSigner.getAddress();
2080
+ const { immutableXConfig } = config;
2081
+ const depositsApi = new coreSdk.DepositsApi(immutableXConfig.apiConfiguration);
2082
+ const encodingApi = new coreSdk.EncodingApi(immutableXConfig.apiConfiguration);
2083
+ const usersApi = new coreSdk.UsersApi(immutableXConfig.apiConfiguration);
2084
+ const data = {
2085
+ token_address: deposit.tokenAddress,
2086
+ token_id: deposit.tokenId,
2087
+ };
2088
+ const amount = '1';
2089
+ const getSignableDepositRequest = {
2090
+ user,
2091
+ token: {
2092
+ type: deposit.type,
2093
+ data,
2094
+ },
2095
+ amount: amount.toString(),
2096
+ };
2097
+ const signableDepositResult = await depositsApi.getSignableDeposit({
2098
+ getSignableDepositRequest,
2099
+ });
2100
+ // Perform encoding on asset details to get an assetType (required for stark contract request)
2101
+ const encodingResult = await encodingApi.encodeAsset({
2102
+ assetType: 'asset',
2103
+ encodeAssetRequest: {
2104
+ token: {
2105
+ type: deposit.type,
2106
+ data: {
2107
+ token_address: deposit.tokenAddress,
2108
+ token_id: deposit.tokenId,
2109
+ },
2110
+ },
2111
+ },
2112
+ });
2113
+ const assetType = encodingResult.data.asset_type;
2114
+ const starkPublicKey = signableDepositResult.data.stark_key;
2115
+ const vaultId = signableDepositResult.data.vault_id;
2116
+ const isRegistered = await isRegisteredOnChain(starkPublicKey, ethSigner, config);
2117
+ // Approve whether an amount of token from an account can be spent by a third-party account
2118
+ const tokenContract = coreSdk.Contracts.IERC721.connect(deposit.tokenAddress, ethSigner);
2119
+ const operator = immutableXConfig.ethConfiguration.coreContractAddress;
2120
+ const isApprovedForAll = await tokenContract.isApprovedForAll(user, operator);
2121
+ if (!isApprovedForAll) {
2122
+ await tokenContract.setApprovalForAll(operator, true);
2123
+ }
2124
+ if (!isRegistered) {
2125
+ const signableResult = await getSignableRegistrationOnchain(user, starkPublicKey, usersApi);
2126
+ const coreContract = coreSdk.Contracts.Core.connect(immutableXConfig.ethConfiguration.coreContractAddress, ethSigner);
2127
+ // Note: proxy registration contract registerAndDepositNft method is not used as it currently fails erc721 transfer ownership check
2128
+ await coreContract.registerUser(user, starkPublicKey, signableResult.operator_signature);
2129
+ }
2130
+ return executeDepositERC721(ethSigner, deposit.tokenId, assetType, starkPublicKey, vaultId, immutableXConfig);
2131
+ }
2132
+ async function executeDepositERC721(ethSigner, tokenId, assetType, starkPublicKey, vaultId, config) {
2133
+ const coreContract = coreSdk.Contracts.Core.connect(config.ethConfiguration.coreContractAddress, ethSigner);
2134
+ const populatedTransaction = await coreContract.populateTransaction.depositNft(starkPublicKey, assetType, vaultId, tokenId);
2135
+ return ethSigner.sendTransaction(populatedTransaction);
2136
+ }
2137
+
2138
+ async function deposit({ signers, deposit, config }) {
2139
+ switch (deposit.type) {
2140
+ case 'ETH':
2141
+ return depositEth({ signers, deposit, config });
2142
+ case 'ERC20':
2143
+ return depositERC20({ signers, deposit, config });
2144
+ case 'ERC721':
2145
+ return depositERC721({ signers, deposit, config });
2146
+ }
2147
+ }
2148
+
2149
+ async function exchangeTransfer({ signers, request, config, }) {
2150
+ await validateChain(signers.ethSigner, config.immutableXConfig);
2151
+ const exchangeApi = new coreSdk.ExchangesApi(config.immutableXConfig.apiConfiguration);
2152
+ const ethAddress = await signers.ethSigner.getAddress();
2153
+ const transferAmount = request.amount;
2154
+ const signableResult = await exchangeApi.getExchangeSignableTransfer({
2155
+ id: request.transactionID,
2156
+ getSignableTransferRequest: {
2157
+ sender: ethAddress,
2158
+ token: convertToSignableToken(request),
2159
+ amount: transferAmount,
2160
+ receiver: request.receiver,
2161
+ },
2162
+ });
2163
+ const { signable_message: signableMessage, payload_hash: payloadHash } = signableResult.data;
2164
+ const ethSignature = await signRaw(signableMessage, signers.ethSigner);
2165
+ const starkSignature = await signers.starkSigner.signMessage(payloadHash);
2166
+ const transferSigningParams = {
2167
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2168
+ sender_stark_key: signableResult.data.sender_stark_key,
2169
+ sender_vault_id: signableResult.data.sender_vault_id,
2170
+ receiver_stark_key: signableResult.data.receiver_stark_key,
2171
+ receiver_vault_id: signableResult.data.receiver_vault_id,
2172
+ asset_id: signableResult.data.asset_id,
2173
+ amount: signableResult.data.amount,
2174
+ nonce: signableResult.data.nonce,
2175
+ expiration_timestamp: signableResult.data.expiration_timestamp,
2176
+ stark_signature: starkSignature,
2177
+ };
2178
+ const response = await exchangeApi.createExchangeTransfer({
2179
+ id: request.transactionID,
2180
+ createTransferRequest: transferSigningParams,
2181
+ xImxEthAddress: ethAddress,
2182
+ xImxEthSignature: ethSignature,
2183
+ });
2184
+ return {
2185
+ sent_signature: response?.data.sent_signature,
2186
+ status: response?.data.status?.toString(),
2187
+ time: response?.data.time,
2188
+ transfer_id: response?.data.transfer_id,
2189
+ };
2190
+ }
2191
+
2192
+ class GenericIMXProvider {
2193
+ config;
2194
+ signers;
2195
+ constructor(config, ethSigner, starkSigner) {
2196
+ this.config = config;
2197
+ this.signers = { ethSigner, starkSigner };
2198
+ }
2199
+ async getAddress() {
2200
+ return await this.signers.ethSigner.getAddress();
2201
+ }
2202
+ registerOffchain() {
2203
+ return registerOffchain(this.signers, this.config);
2204
+ }
2205
+ batchNftTransfer(request) {
2206
+ return batchTransfer({
2207
+ signers: this.signers,
2208
+ request,
2209
+ config: this.config,
2210
+ });
2211
+ }
2212
+ cancelOrder(request) {
2213
+ return cancelOrder({
2214
+ signers: this.signers,
2215
+ request,
2216
+ config: this.config,
2217
+ });
2218
+ }
2219
+ completeWithdrawal(starkPublicKey, token) {
2220
+ return completeWithdrawal({
2221
+ config: this.config,
2222
+ signers: this.signers,
2223
+ token,
2224
+ starkPublicKey,
2225
+ });
2226
+ }
2227
+ createOrder(request) {
2228
+ return createOrder({
2229
+ signers: this.signers,
2230
+ request,
2231
+ config: this.config,
2232
+ });
2233
+ }
2234
+ createTrade(request) {
2235
+ return createTrade({
2236
+ signers: this.signers,
2237
+ request,
2238
+ config: this.config,
2239
+ });
2240
+ }
2241
+ deposit(tokenAmount) {
2242
+ return deposit({
2243
+ signers: this.signers,
2244
+ deposit: tokenAmount,
2245
+ config: this.config,
2246
+ });
2247
+ }
2248
+ exchangeTransfer(request) {
2249
+ return exchangeTransfer({
2250
+ signers: this.signers,
2251
+ request,
2252
+ config: this.config,
2253
+ });
2254
+ }
2255
+ async isRegisteredOnchain() {
2256
+ const starkPublicKey = await this.signers.starkSigner.getAddress();
2257
+ return isRegisteredOnChain(starkPublicKey, this.signers.ethSigner, this.config);
2258
+ }
2259
+ prepareWithdrawal(request) {
2260
+ return prepareWithdrawal({
2261
+ signers: this.signers,
2262
+ withdrawal: request,
2263
+ config: this.config,
2264
+ });
2265
+ }
2266
+ transfer(request) {
2267
+ return transfer({
2268
+ signers: this.signers,
2269
+ request,
2270
+ config: this.config,
2271
+ });
2272
+ }
2273
+ }
2274
+
2275
+ const WALLET_ACTION = {
2276
+ SWITCH_CHAIN: 'wallet_switchEthereumChain',
2277
+ CONNECT: 'eth_requestAccounts',
2278
+ };
2279
+ function isRequestableProvider(provider) {
2280
+ return !!provider?.request;
2281
+ }
2282
+ async function connectProvider(provider, chainID) {
2283
+ await provider.request({ method: WALLET_ACTION.CONNECT });
2284
+ if (chainID) {
2285
+ await provider.request({
2286
+ method: WALLET_ACTION.SWITCH_CHAIN,
2287
+ params: [{ chainId: `0x${chainID.toString(16)}` }],
2288
+ });
2289
+ }
2290
+ }
2291
+
2292
+ const ERRORS = {
2293
+ PROVIDER_NOT_FOUND: 'The Metamask provider was not found',
2294
+ };
2295
+ async function connect$1({ chainID, }) {
2296
+ const provider = (await detectEthereumProvider());
2297
+ if (!isRequestableProvider(provider)) {
2298
+ throw new Error(ERRORS.PROVIDER_NOT_FOUND);
2299
+ }
2300
+ await connectProvider(provider, chainID);
2301
+ // NOTE: if we want to listen to Metamask events in the future, we can add a
2302
+ // listener here.
2303
+ return new ethers.ethers.providers.Web3Provider(provider);
2304
+ }
2305
+
2306
+ const COMMUNICATION_TYPE = 'message';
2307
+ var RequestEventType;
2308
+ (function (RequestEventType) {
2309
+ RequestEventType["GET_CONNECTION_REQUEST"] = "GET_CONNECTION_REQUEST";
2310
+ RequestEventType["CONNECT_WALLET_REQUEST"] = "CONNECT_WALLET_REQUEST";
2311
+ RequestEventType["SIGN_MESSAGE_REQUEST"] = "SIGN_MESSAGE_REQUEST";
2312
+ RequestEventType["DISCONNECT_WALLET_REQUEST"] = "DISCONNECT_WALLET_REQUEST";
2313
+ })(RequestEventType || (RequestEventType = {}));
2314
+ var ResponseEventType;
2315
+ (function (ResponseEventType) {
2316
+ ResponseEventType["CONNECT_WALLET_RESPONSE"] = "CONNECT_WALLET_RESPONSE";
2317
+ ResponseEventType["SIGN_MESSAGE_RESPONSE"] = "SIGN_MESSAGE_RESPONSE";
2318
+ ResponseEventType["GET_CONNECTION_RESPONSE"] = "GET_CONNECTION_RESPONSE";
2319
+ ResponseEventType["DISCONNECT_WALLET_RESPONSE"] = "DISCONNECT_WALLET_RESPONSE";
2320
+ })(ResponseEventType || (ResponseEventType = {}));
2321
+
2322
+ function postRequestMessage(iframe, payload) {
2323
+ if (iframe && iframe.contentWindow) {
2324
+ iframe.contentWindow.postMessage(payload, new URL(iframe.src).origin);
2325
+ }
2326
+ }
2327
+
2328
+ function messageResponseListener(iframe, event, eventType, callback) {
2329
+ if (iframe && event.source !== iframe.contentWindow) {
2330
+ return;
2331
+ }
2332
+ const l2WalletMessage = event.data;
2333
+ if (l2WalletMessage.type !== eventType) {
2334
+ return;
2335
+ }
2336
+ callback(l2WalletMessage.details);
2337
+ }
2338
+
2339
+ class ImxSigner {
2340
+ publicAddress;
2341
+ iframe;
2342
+ constructor(publicAddress, iframe) {
2343
+ this.publicAddress = publicAddress;
2344
+ this.iframe = iframe;
2345
+ }
2346
+ getAddress() {
2347
+ return this.publicAddress;
2348
+ }
2349
+ signMessage(rawMessage) {
2350
+ return new Promise((resolve, reject) => {
2351
+ const listener = (event) => {
2352
+ messageResponseListener(this.iframe, event, ResponseEventType.SIGN_MESSAGE_RESPONSE, (messageDetails) => {
2353
+ window.removeEventListener(COMMUNICATION_TYPE, listener);
2354
+ if (!messageDetails.success) {
2355
+ reject(new Error(messageDetails.error?.message));
2356
+ }
2357
+ resolve(messageDetails.data.signedMessage);
2358
+ });
2359
+ };
2360
+ window.addEventListener(COMMUNICATION_TYPE, listener);
2361
+ postRequestMessage(this.iframe, {
2362
+ type: RequestEventType.SIGN_MESSAGE_REQUEST,
2363
+ details: { starkPublicKey: this.publicAddress, message: rawMessage },
2364
+ });
2365
+ });
2366
+ }
2367
+ getIFrame() {
2368
+ return this.iframe;
2369
+ }
2370
+ }
2371
+
2372
+ const IMX_WALLET_IFRAME_ID = 'imx-wallet-app';
2373
+ const IMX_WALLET_IFRAME_HOSTS = {
2374
+ [exports.Environment.SANDBOX]: 'https://wallets.sandbox.immutable.com',
2375
+ [exports.Environment.PRODUCTION]: 'https://wallets.immutable.com',
2376
+ };
2377
+ const IMX_WALLET_IFRAME_STYLE = 'display: none;';
2378
+ function getIFrame() {
2379
+ return document.querySelector(`iframe#${IMX_WALLET_IFRAME_ID}`);
2380
+ }
2381
+ async function setupIFrame(env) {
2382
+ return new Promise((resolve) => {
2383
+ const iframe = document.createElement('iframe');
2384
+ iframe.setAttribute('id', IMX_WALLET_IFRAME_ID);
2385
+ iframe.setAttribute('src', IMX_WALLET_IFRAME_HOSTS[env]);
2386
+ iframe.setAttribute('style', IMX_WALLET_IFRAME_STYLE);
2387
+ document.body.appendChild(iframe);
2388
+ iframe.onload = () => resolve(iframe);
2389
+ });
2390
+ }
2391
+ async function getOrSetupIFrame(env) {
2392
+ const iframe = getIFrame();
2393
+ if (iframe)
2394
+ return iframe;
2395
+ return await setupIFrame(env);
2396
+ }
2397
+
2398
+ const DEFAULT_CONNECTION_MESSAGE = 'Only sign this request if you’ve initiated an action with Immutable X.';
2399
+ const CONNECTION_FAILED_ERROR = 'The L2 IMX Wallet connection has failed';
2400
+ async function connect(l1Provider, env) {
2401
+ const l1Signer = l1Provider.getSigner();
2402
+ const address = await l1Signer.getAddress();
2403
+ const signature = await l1Signer.signMessage(DEFAULT_CONNECTION_MESSAGE);
2404
+ const iframe = await getOrSetupIFrame(env);
2405
+ return new Promise((resolve, reject) => {
2406
+ const listener = (event) => {
2407
+ messageResponseListener(iframe, event, ResponseEventType.CONNECT_WALLET_RESPONSE, (messageDetails) => {
2408
+ window.removeEventListener(COMMUNICATION_TYPE, listener);
2409
+ if (!messageDetails.success) {
2410
+ reject(new Error(CONNECTION_FAILED_ERROR));
2411
+ }
2412
+ resolve(new ImxSigner(messageDetails.data.starkPublicKey, iframe));
2413
+ });
2414
+ };
2415
+ window.addEventListener(COMMUNICATION_TYPE, listener);
2416
+ postRequestMessage(iframe, {
2417
+ type: RequestEventType.CONNECT_WALLET_REQUEST,
2418
+ details: { ethAddress: address, signature },
2419
+ });
2420
+ });
2421
+ }
2422
+ async function disconnect(imxSigner) {
2423
+ const iframe = imxSigner.getIFrame();
2424
+ return new Promise((resolve, reject) => {
2425
+ const listener = (event) => {
2426
+ messageResponseListener(iframe, event, ResponseEventType.DISCONNECT_WALLET_RESPONSE, (messageDetails) => {
2427
+ window.removeEventListener(COMMUNICATION_TYPE, listener);
2428
+ if (!messageDetails.success && messageDetails.error) {
2429
+ reject(messageDetails.error);
2430
+ }
2431
+ iframe.remove();
2432
+ resolve();
2433
+ });
2434
+ };
2435
+ window.addEventListener(COMMUNICATION_TYPE, listener);
2436
+ postRequestMessage(iframe, {
2437
+ type: RequestEventType.DISCONNECT_WALLET_REQUEST,
2438
+ details: { starkPublicKey: imxSigner.getAddress() },
2439
+ });
2440
+ });
2441
+ }
2442
+
2443
+ var ProviderErrorType;
2444
+ (function (ProviderErrorType) {
2445
+ ProviderErrorType["PROVIDER_CONNECTION_ERROR"] = "PROVIDER_CONNECTION_ERROR";
2446
+ ProviderErrorType["WALLET_CONNECTION_ERROR"] = "WALLET_CONNECTION_ERROR";
2447
+ })(ProviderErrorType || (ProviderErrorType = {}));
2448
+ class ProviderError extends Error {
2449
+ type;
2450
+ constructor(message, type) {
2451
+ super(message);
2452
+ this.type = type;
2453
+ }
2454
+ }
2455
+ const withProviderError = async (fn, customError) => {
2456
+ try {
2457
+ return await fn();
2458
+ }
2459
+ catch (error) {
2460
+ const errorMessage = customError.message || `${error.message}` || 'UnknownError';
2461
+ throw new ProviderError(errorMessage, customError.type);
2462
+ }
2463
+ };
2464
+
2465
+ class MetaMaskIMXProvider extends GenericIMXProvider {
2466
+ static imxSigner;
2467
+ constructor(config, ethSigner, starkSigner) {
2468
+ super(config, ethSigner, starkSigner);
2469
+ }
2470
+ static async connect(config) {
2471
+ return await withProviderError(async () => {
2472
+ const metaMaskProvider = await connect$1({
2473
+ chainID: config.immutableXConfig.ethConfiguration.chainID,
2474
+ });
2475
+ this.imxSigner = await connect(metaMaskProvider, config.baseConfig.environment);
2476
+ return new MetaMaskIMXProvider(config, metaMaskProvider.getSigner(), this.imxSigner);
2477
+ }, { type: ProviderErrorType.WALLET_CONNECTION_ERROR });
2478
+ }
2479
+ static async disconnect() {
2480
+ if (!this.imxSigner) {
2481
+ throw new ProviderError('Attempted to disconnect from the MetaMask IMX provider without an established connection', ProviderErrorType.PROVIDER_CONNECTION_ERROR);
2482
+ }
2483
+ return withProviderError(async () => {
2484
+ await disconnect(this.imxSigner);
2485
+ }, { type: ProviderErrorType.PROVIDER_CONNECTION_ERROR });
2486
+ }
2487
+ static async signMessage(message) {
2488
+ if (!this.imxSigner) {
2489
+ throw new ProviderError('Attempted to sign a message with the MetaMask IMX provider without an established connection', ProviderErrorType.PROVIDER_CONNECTION_ERROR);
2490
+ }
2491
+ return withProviderError(async () => {
2492
+ return await this.imxSigner.signMessage(message);
2493
+ }, { type: ProviderErrorType.PROVIDER_CONNECTION_ERROR });
2494
+ }
2495
+ }
2496
+
2497
+ class ProviderConfiguration {
2498
+ immutableXConfig;
2499
+ baseConfig;
2500
+ constructor({ baseConfig, overrides }) {
2501
+ this.baseConfig = baseConfig;
2502
+ if (overrides) {
2503
+ this.immutableXConfig = overrides.immutableXConfig;
2504
+ }
2505
+ else {
2506
+ switch (baseConfig.environment) {
2507
+ case exports.Environment.SANDBOX: {
2508
+ this.immutableXConfig = coreSdk.Config.SANDBOX;
2509
+ break;
2510
+ }
2511
+ case exports.Environment.PRODUCTION: {
2512
+ this.immutableXConfig = coreSdk.Config.PRODUCTION;
2513
+ break;
2514
+ }
2515
+ }
2516
+ }
2517
+ }
2518
+ }
2519
+
2520
+ function $parcel$interopDefault(a) {
2521
+ return a && a.__esModule ? a.default : a;
2522
+ }
2523
+
2524
+ const $762782b6c862d954$export$db5daa1b5156ccfe = [
2525
+ {
2526
+ constant: true,
2527
+ inputs: [],
2528
+ name: "name",
2529
+ outputs: [
2530
+ {
2531
+ name: "",
2532
+ type: "string"
2533
+ }
2534
+ ],
2535
+ payable: false,
2536
+ type: "function"
2537
+ },
2538
+ {
2539
+ constant: true,
2540
+ inputs: [],
2541
+ name: "decimals",
2542
+ outputs: [
2543
+ {
2544
+ name: "",
2545
+ type: "uint8"
2546
+ }
2547
+ ],
2548
+ payable: false,
2549
+ type: "function"
2550
+ },
2551
+ {
2552
+ constant: true,
2553
+ inputs: [
2554
+ {
2555
+ name: "_owner",
2556
+ type: "address"
2557
+ }
2558
+ ],
2559
+ name: "balanceOf",
2560
+ outputs: [
2561
+ {
2562
+ name: "balance",
2563
+ type: "uint256"
2564
+ }
2565
+ ],
2566
+ payable: false,
2567
+ type: "function"
2568
+ },
2569
+ {
2570
+ constant: true,
2571
+ inputs: [],
2572
+ name: "symbol",
2573
+ outputs: [
2574
+ {
2575
+ name: "",
2576
+ type: "string"
2577
+ }
2578
+ ],
2579
+ payable: false,
2580
+ type: "function"
2581
+ }
2582
+ ];
2583
+
2584
+
2585
+ exports.ConnectionProviders = void 0;
2586
+ (function(ConnectionProviders) {
2587
+ ConnectionProviders["METAMASK"] = "metamask";
2588
+ })(exports.ConnectionProviders || (exports.ConnectionProviders = {}));
2589
+
2590
+
2591
+ exports.ChainId = void 0;
2592
+ (function(ChainId) {
2593
+ ChainId[ChainId["ETHEREUM"] = 1] = "ETHEREUM";
2594
+ ChainId[ChainId["GOERLI"] = 5] = "GOERLI";
2595
+ ChainId[ChainId["POLYGON"] = 137] = "POLYGON";
2596
+ })(exports.ChainId || (exports.ChainId = {}));
2597
+ const $a47e48dd2c04791b$export$f61f4aaec62f6be9 = {
2598
+ [exports.ChainId.ETHEREUM]: {
2599
+ chainIdHex: "0x1",
2600
+ chainName: "Ethereum",
2601
+ rpcUrls: [
2602
+ "https://mainnet.infura.io/v3/"
2603
+ ],
2604
+ nativeCurrency: {
2605
+ name: "Ethereum",
2606
+ symbol: "ETH",
2607
+ decimals: 18
2608
+ },
2609
+ blockExplorerUrls: [
2610
+ "https://etherscan.io/"
2611
+ ]
2612
+ },
2613
+ [exports.ChainId.GOERLI]: {
2614
+ chainIdHex: "0x5",
2615
+ chainName: "Goerli",
2616
+ rpcUrls: [
2617
+ "https://goerli.infura.io/v3/"
2618
+ ],
2619
+ nativeCurrency: {
2620
+ name: "Goerli Eth",
2621
+ symbol: "ETH",
2622
+ decimals: 18
2623
+ },
2624
+ blockExplorerUrls: [
2625
+ "https://goerli.etherscan.io/"
2626
+ ]
2627
+ },
2628
+ [exports.ChainId.POLYGON]: {
2629
+ chainIdHex: "0x89",
2630
+ chainName: "Polygon",
2631
+ rpcUrls: [
2632
+ "https://polygon-rpc.com"
2633
+ ],
2634
+ nativeCurrency: {
2635
+ name: "MATIC",
2636
+ symbol: "MATIC",
2637
+ decimals: 18
2638
+ },
2639
+ blockExplorerUrls: [
2640
+ "https://polygonscan.com/"
2641
+ ]
2642
+ }
2643
+ };
2644
+ exports.NetworkFilterTypes = void 0;
2645
+ (function(NetworkFilterTypes) {
2646
+ NetworkFilterTypes["ALL"] = "all";
2647
+ })(exports.NetworkFilterTypes || (exports.NetworkFilterTypes = {}));
2648
+
2649
+
2650
+ exports.TokenFilterTypes = void 0;
2651
+ (function(TokenFilterTypes) {
2652
+ TokenFilterTypes["SWAP"] = "swap";
2653
+ TokenFilterTypes["BRIDGE"] = "bridge";
2654
+ TokenFilterTypes["ALL"] = "all";
2655
+ })(exports.TokenFilterTypes || (exports.TokenFilterTypes = {}));
2656
+
2657
+
2658
+
2659
+
2660
+ const $4f91c5f280efe242$export$a130407f3423b97d = {
2661
+ CHECK_CONNECTION: "eth_accounts",
2662
+ CONNECT: "eth_requestAccounts",
2663
+ ADD_NETWORK: "wallet_addEthereumChain",
2664
+ SWITCH_NETWORK: "wallet_switchEthereumChain"
2665
+ };
2666
+ exports.WalletFilterTypes = void 0;
2667
+ (function(WalletFilterTypes) {
2668
+ WalletFilterTypes["ALL"] = "all";
2669
+ WalletFilterTypes["DESKTOP"] = "desktop";
2670
+ WalletFilterTypes["MOBILE"] = "mobile";
2671
+ })(exports.WalletFilterTypes || (exports.WalletFilterTypes = {}));
2672
+
2673
+
2674
+
2675
+
2676
+ /**
2677
+ * The different types of errors that can be returned by the checkout process.
2678
+ */ exports.CheckoutErrorType = void 0;
2679
+ (function(CheckoutErrorType) {
2680
+ CheckoutErrorType["PROVIDER_PREFERENCE_ERROR"] = "PROVIDER_PREFERENCE_ERROR";
2681
+ CheckoutErrorType["CONNECT_PROVIDER_ERROR"] = "CONNECT_PROVIDER_ERROR";
2682
+ CheckoutErrorType["GET_BALANCE_ERROR"] = "GET_BALANCE_ERROR";
2683
+ CheckoutErrorType["GET_ERC20_BALANCE_ERROR"] = "GET_ERC20_BALANCE_ERROR";
2684
+ CheckoutErrorType["GET_NETWORK_INFO_ERROR"] = "GET_NETWORK_INFO_ERROR";
2685
+ CheckoutErrorType["METAMASK_PROVIDER_ERROR"] = "METAMASK_PROVIDER_ERROR";
2686
+ CheckoutErrorType["CHAIN_NOT_SUPPORTED_ERROR"] = "CHAIN_NOT_SUPPORTED_ERROR";
2687
+ CheckoutErrorType["PROVIDER_REQUEST_MISSING_ERROR"] = "PROVIDER_REQUEST_MISSING_ERROR";
2688
+ CheckoutErrorType["PROVIDER_REQUEST_FAILED_ERROR"] = "PROVIDER_REQUEST_FAILED_ERROR";
2689
+ CheckoutErrorType["USER_REJECTED_REQUEST_ERROR"] = "USER_REJECTED_REQUEST_ERROR";
2690
+ CheckoutErrorType["TRANSACTION_ERROR"] = "TRANSACTION_ERROR";
2691
+ })(exports.CheckoutErrorType || (exports.CheckoutErrorType = {}));
2692
+ class $a8bc256d81a5e2c1$export$b722478a3cbfa3bc extends Error {
2693
+ constructor(message, type, data){
2694
+ super(message);
2695
+ this.message = message;
2696
+ this.type = type;
2697
+ this.data = data;
2698
+ }
2699
+ }
2700
+ let $a8bc256d81a5e2c1$export$a22d4e0719ee6def;
2701
+ (function(CheckoutInternalErrorType) {
2702
+ CheckoutInternalErrorType["REJECTED_SWITCH_AFTER_ADDING_NETWORK"] = "REJECTED_SWITCH_AFTER_ADDING_NETWORK";
2703
+ })($a8bc256d81a5e2c1$export$a22d4e0719ee6def || ($a8bc256d81a5e2c1$export$a22d4e0719ee6def = {}));
2704
+ const $a8bc256d81a5e2c1$export$bacc563de539c6c3 = async (fn, customError)=>{
2705
+ try {
2706
+ return await fn();
2707
+ } catch (error) {
2708
+ const cause = `${error.message}` || "UnknownError";
2709
+ const errorMessage = customError.message ? `[${customError.type}]:${customError.message}. Cause:${cause}` : `[${customError.type}] Cause:${cause}`;
2710
+ if (error instanceof $a8bc256d81a5e2c1$export$b722478a3cbfa3bc) throw new $a8bc256d81a5e2c1$export$b722478a3cbfa3bc(errorMessage, customError.type, {
2711
+ ...customError.data,
2712
+ innerErrorType: error.type,
2713
+ ...error.data
2714
+ });
2715
+ throw new $a8bc256d81a5e2c1$export$b722478a3cbfa3bc(errorMessage, customError.type, {
2716
+ ...customError.data
2717
+ });
2718
+ }
2719
+ };
2720
+
2721
+
2722
+
2723
+
2724
+ /* eslint-disable @typescript-eslint/no-explicit-any */
2725
+
2726
+ /* eslint-disable @typescript-eslint/no-explicit-any */
2727
+
2728
+
2729
+
2730
+ async function $c99672cf2294e839$export$2d040992269b4717(providerPreference) {
2731
+ const provider = await $c99672cf2294e839$var$getWalletProviderForPreference(providerPreference);
2732
+ if (!provider.provider?.request) throw new ($a8bc256d81a5e2c1$export$b722478a3cbfa3bc)("Incompatible provider", (exports.CheckoutErrorType).PROVIDER_REQUEST_MISSING_ERROR, {
2733
+ details: `Unsupported provider for ${providerPreference}`
2734
+ });
2735
+ let accounts = [];
2736
+ try {
2737
+ accounts = await provider.provider.request({
2738
+ method: (0, $4f91c5f280efe242$export$a130407f3423b97d).CHECK_CONNECTION,
2739
+ params: []
2740
+ });
2741
+ } catch (err) {
2742
+ throw new ($a8bc256d81a5e2c1$export$b722478a3cbfa3bc)(`Check wallet connection request failed`, (exports.CheckoutErrorType).PROVIDER_REQUEST_FAILED_ERROR, {
2743
+ rpcMethod: ($4f91c5f280efe242$export$a130407f3423b97d).CHECK_CONNECTION
2744
+ });
2745
+ }
2746
+ // accounts[0] will have the active account if connected.
2747
+ return {
2748
+ isConnected: accounts && accounts.length > 0,
2749
+ walletAddress: accounts[0] ?? ""
2750
+ };
2751
+ }
2752
+ async function $c99672cf2294e839$export$fba2f6c3656e07c1(params) {
2753
+ const web3Provider = await $c99672cf2294e839$var$getWalletProviderForPreference(params.providerPreference);
2754
+ await ($a8bc256d81a5e2c1$export$bacc563de539c6c3)(async ()=>{
2755
+ if (!web3Provider || !web3Provider?.provider?.request) throw new ($a8bc256d81a5e2c1$export$b722478a3cbfa3bc)("Incompatible provider", (exports.CheckoutErrorType).PROVIDER_REQUEST_MISSING_ERROR, {
2756
+ details: `Unsupported provider for ${params.providerPreference}`
2757
+ });
2758
+ // this makes the request to the wallet to connect i.e request eth accounts ('eth_requestAccounts')
2759
+ await web3Provider.provider.request({
2760
+ method: ($4f91c5f280efe242$export$a130407f3423b97d).CONNECT,
2761
+ params: []
2762
+ });
2763
+ }, {
2764
+ type: (exports.CheckoutErrorType).USER_REJECTED_REQUEST_ERROR
2765
+ });
2766
+ return web3Provider;
2767
+ }
2768
+ async function $c99672cf2294e839$var$getWalletProviderForPreference(providerPreference) {
2769
+ let web3Provider = null;
2770
+ switch(providerPreference){
2771
+ case (exports.ConnectionProviders).METAMASK:
2772
+ web3Provider = await $c99672cf2294e839$var$getMetaMaskProvider();
2773
+ break;
2774
+ default:
2775
+ throw new ($a8bc256d81a5e2c1$export$b722478a3cbfa3bc)("Provider preference is not supported", (exports.CheckoutErrorType).PROVIDER_PREFERENCE_ERROR);
2776
+ }
2777
+ return web3Provider;
2778
+ }
2779
+ async function $c99672cf2294e839$var$getMetaMaskProvider() {
2780
+ const provider = await ($a8bc256d81a5e2c1$export$bacc563de539c6c3)(async ()=>{
2781
+ return await (detectEthereumProvider)();
2782
+ }, {
2783
+ type: (exports.CheckoutErrorType).METAMASK_PROVIDER_ERROR
2784
+ });
2785
+ if (!provider || !provider.request) throw new ($a8bc256d81a5e2c1$export$b722478a3cbfa3bc)("No MetaMask provider installed.", (exports.CheckoutErrorType).METAMASK_PROVIDER_ERROR);
2786
+ return new (providers.Web3Provider)(provider);
2787
+ }
2788
+
2789
+
2790
+ var $497c134ecbc8a50f$exports = {};
2791
+ $497c134ecbc8a50f$exports = JSON.parse('[{"chainId":1},{"chainId":137}]');
2792
+
2793
+
2794
+ const $de192de6ef100f9f$var$UNRECOGNISED_CHAIN_ERROR_CODE = 4902; // error code (MetaMask)
2795
+ async function $de192de6ef100f9f$export$79f13b4cfaaf0d09(provider) {
2796
+ return ($a8bc256d81a5e2c1$export$bacc563de539c6c3)(async ()=>{
2797
+ const network = await provider.getNetwork();
2798
+ if (!Object.values((exports.ChainId)).includes(network.chainId)) // return empty details
2799
+ return {
2800
+ chainId: network.chainId,
2801
+ name: network.name,
2802
+ isSupported: false
2803
+ };
2804
+ const chainIdNetworkInfo = ($a47e48dd2c04791b$export$f61f4aaec62f6be9)[network.chainId];
2805
+ return {
2806
+ name: chainIdNetworkInfo.chainName,
2807
+ chainId: parseInt(chainIdNetworkInfo.chainIdHex, 16),
2808
+ nativeCurrency: chainIdNetworkInfo.nativeCurrency,
2809
+ isSupported: true
2810
+ };
2811
+ }, {
2812
+ type: (exports.CheckoutErrorType).GET_NETWORK_INFO_ERROR
2813
+ });
2814
+ }
2815
+ async function $de192de6ef100f9f$export$b827d9418aeb5dbd(providerPreference, provider, chainId) {
2816
+ let currentProvider = provider;
2817
+ if (!Object.values((exports.ChainId)).includes(chainId)) throw new ($a8bc256d81a5e2c1$export$b722478a3cbfa3bc)(`Chain:${chainId} is not a supported chain`, (exports.CheckoutErrorType).CHAIN_NOT_SUPPORTED_ERROR);
2818
+ if (!currentProvider || !currentProvider.provider?.request) throw new ($a8bc256d81a5e2c1$export$b722478a3cbfa3bc)("Incompatible provider", (exports.CheckoutErrorType).PROVIDER_REQUEST_MISSING_ERROR, {
2819
+ details: `Unsupported provider`
2820
+ });
2821
+ // WT-1146 - Refer to the README in this folder for explantion on the switch network flow
2822
+ try {
2823
+ await $de192de6ef100f9f$var$switchNetworkInWallet(currentProvider, chainId);
2824
+ } catch (err) {
2825
+ if (err.code === $de192de6ef100f9f$var$UNRECOGNISED_CHAIN_ERROR_CODE) try {
2826
+ await $de192de6ef100f9f$var$addNetworkToWallet(currentProvider, chainId);
2827
+ } catch (err) {
2828
+ throw new ($a8bc256d81a5e2c1$export$b722478a3cbfa3bc)("User cancelled add network request", (exports.CheckoutErrorType).USER_REJECTED_REQUEST_ERROR);
2829
+ }
2830
+ else throw new ($a8bc256d81a5e2c1$export$b722478a3cbfa3bc)("User cancelled switch network request", (exports.CheckoutErrorType).USER_REJECTED_REQUEST_ERROR);
2831
+ }
2832
+ currentProvider = await ($c99672cf2294e839$export$fba2f6c3656e07c1)({
2833
+ providerPreference: providerPreference
2834
+ });
2835
+ if ((await currentProvider.getNetwork()).chainId !== chainId) // user didn't actually switch
2836
+ throw new ($a8bc256d81a5e2c1$export$b722478a3cbfa3bc)("User cancelled switch network request", (exports.CheckoutErrorType).USER_REJECTED_REQUEST_ERROR);
2837
+ // we can assume that if the above succeeds then user has successfully
2838
+ // switched to the network specified
2839
+ const newNetwork = ($a47e48dd2c04791b$export$f61f4aaec62f6be9)[chainId];
2840
+ return {
2841
+ network: {
2842
+ name: newNetwork.chainName,
2843
+ chainId: parseInt(newNetwork.chainIdHex, 16),
2844
+ nativeCurrency: newNetwork.nativeCurrency
2845
+ },
2846
+ provider: currentProvider
2847
+ };
2848
+ }
2849
+ async function $de192de6ef100f9f$export$3043f6442a9ef563({ type: type = (exports.NetworkFilterTypes).ALL , exclude: exclude }) {
2850
+ const list = ((/*@__PURE__*/$parcel$interopDefault($497c134ecbc8a50f$exports))).filter((network)=>{
2851
+ const allowAllTokens = type === (exports.NetworkFilterTypes).ALL;
2852
+ const networkNotExcluded = !(exclude || []).map((exc)=>exc.chainId).includes(network.chainId);
2853
+ return allowAllTokens && networkNotExcluded;
2854
+ });
2855
+ const allowedNetworks = [];
2856
+ list.forEach((element)=>{
2857
+ const newNetwork = ($a47e48dd2c04791b$export$f61f4aaec62f6be9)[element.chainId];
2858
+ allowedNetworks.push({
2859
+ name: newNetwork.chainName,
2860
+ chainId: parseInt(newNetwork.chainIdHex, 16),
2861
+ nativeCurrency: newNetwork.nativeCurrency,
2862
+ isSupported: true
2863
+ });
2864
+ });
2865
+ return {
2866
+ networks: allowedNetworks
2867
+ };
2868
+ }
2869
+ // these functions should not be exported. These functions should be used as part of an exported function e.g switchWalletNetwork() above.
2870
+ // make sure to check if(provider.provider?.request) in the exported function and throw an error
2871
+ async function $de192de6ef100f9f$var$switchNetworkInWallet(provider, chainId) {
2872
+ if (provider.provider?.request) return await provider.provider.request({
2873
+ method: ($4f91c5f280efe242$export$a130407f3423b97d).SWITCH_NETWORK,
2874
+ params: [
2875
+ {
2876
+ chainId: ($a47e48dd2c04791b$export$f61f4aaec62f6be9)[chainId].chainIdHex
2877
+ }
2878
+ ]
2879
+ });
2880
+ }
2881
+ async function $de192de6ef100f9f$var$addNetworkToWallet(provider, chainId) {
2882
+ if (provider.provider?.request) {
2883
+ const addNetwork = {
2884
+ chainId: ($a47e48dd2c04791b$export$f61f4aaec62f6be9)[chainId].chainIdHex,
2885
+ chainName: ($a47e48dd2c04791b$export$f61f4aaec62f6be9)[chainId].chainName,
2886
+ rpcUrls: ($a47e48dd2c04791b$export$f61f4aaec62f6be9)[chainId].rpcUrls,
2887
+ nativeCurrency: ($a47e48dd2c04791b$export$f61f4aaec62f6be9)[chainId].nativeCurrency,
2888
+ blockExplorerUrls: ($a47e48dd2c04791b$export$f61f4aaec62f6be9)[chainId].blockExplorerUrls
2889
+ };
2890
+ return await provider.provider.request({
2891
+ method: ($4f91c5f280efe242$export$a130407f3423b97d).ADD_NETWORK,
2892
+ params: [
2893
+ addNetwork
2894
+ ]
2895
+ });
2896
+ }
2897
+ }
2898
+
2899
+
2900
+
2901
+
2902
+
2903
+ var $cda6003506e4182e$exports = {};
2904
+ $cda6003506e4182e$exports = JSON.parse("[{\"address\":\"0x7D1AfA7B718fb893dB30A3aBc0Cfc608AaCfeBB0\",\"chainId\":137,\"name\":\"Matic\",\"symbol\":\"MATIC\",\"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 38.4 33.5' style='enable-background:new 0 0 38.4 33.5;' xml:space='preserve'%3E%3Cstyle type='text/css'%3E .st0%7Bfill:%238247E5;%7D%0A%3C/style%3E%3Cg%3E%3Cpath class='st0' d='M29,10.2c-0.7-0.4-1.6-0.4-2.4,0L21,13.5l-3.8,2.1l-5.5,3.3c-0.7,0.4-1.6,0.4-2.4,0L5,16.3 c-0.7-0.4-1.2-1.2-1.2-2.1v-5c0-0.8,0.4-1.6,1.2-2.1l4.3-2.5c0.7-0.4,1.6-0.4,2.4,0L16,7.2c0.7,0.4,1.2,1.2,1.2,2.1v3.3l3.8-2.2V7 c0-0.8-0.4-1.6-1.2-2.1l-8-4.7c-0.7-0.4-1.6-0.4-2.4,0L1.2,5C0.4,5.4,0,6.2,0,7v9.4c0,0.8,0.4,1.6,1.2,2.1l8.1,4.7 c0.7,0.4,1.6,0.4,2.4,0l5.5-3.2l3.8-2.2l5.5-3.2c0.7-0.4,1.6-0.4,2.4,0l4.3,2.5c0.7,0.4,1.2,1.2,1.2,2.1v5c0,0.8-0.4,1.6-1.2,2.1 L29,28.8c-0.7,0.4-1.6,0.4-2.4,0l-4.3-2.5c-0.7-0.4-1.2-1.2-1.2-2.1V21l-3.8,2.2v3.3c0,0.8,0.4,1.6,1.2,2.1l8.1,4.7 c0.7,0.4,1.6,0.4,2.4,0l8.1-4.7c0.7-0.4,1.2-1.2,1.2-2.1V17c0-0.8-0.4-1.6-1.2-2.1L29,10.2z'/%3E%3C/g%3E%3C/svg%3E%0A\",\"tokenFeatures\":[\"swap\",\"bridge\"]},{\"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\",\"chainId\":1,\"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\"]},{\"address\":\"0x7D1AfA7B718fb893dB30A3aBc0Cfc608AaCfeBB0\",\"chainId\":1,\"name\":\"Matic\",\"symbol\":\"MATIC\",\"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 38.4 33.5' style='enable-background:new 0 0 38.4 33.5;' xml:space='preserve'%3E%3Cstyle type='text/css'%3E .st0%7Bfill:%238247E5;%7D%0A%3C/style%3E%3Cg%3E%3Cpath class='st0' d='M29,10.2c-0.7-0.4-1.6-0.4-2.4,0L21,13.5l-3.8,2.1l-5.5,3.3c-0.7,0.4-1.6,0.4-2.4,0L5,16.3 c-0.7-0.4-1.2-1.2-1.2-2.1v-5c0-0.8,0.4-1.6,1.2-2.1l4.3-2.5c0.7-0.4,1.6-0.4,2.4,0L16,7.2c0.7,0.4,1.2,1.2,1.2,2.1v3.3l3.8-2.2V7 c0-0.8-0.4-1.6-1.2-2.1l-8-4.7c-0.7-0.4-1.6-0.4-2.4,0L1.2,5C0.4,5.4,0,6.2,0,7v9.4c0,0.8,0.4,1.6,1.2,2.1l8.1,4.7 c0.7,0.4,1.6,0.4,2.4,0l5.5-3.2l3.8-2.2l5.5-3.2c0.7-0.4,1.6-0.4,2.4,0l4.3,2.5c0.7,0.4,1.2,1.2,1.2,2.1v5c0,0.8-0.4,1.6-1.2,2.1 L29,28.8c-0.7,0.4-1.6,0.4-2.4,0l-4.3-2.5c-0.7-0.4-1.2-1.2-1.2-2.1V21l-3.8,2.2v3.3c0,0.8,0.4,1.6,1.2,2.1l8.1,4.7 c0.7,0.4,1.6,0.4,2.4,0l8.1-4.7c0.7-0.4,1.2-1.2,1.2-2.1V17c0-0.8-0.4-1.6-1.2-2.1L29,10.2z'/%3E%3C/g%3E%3C/svg%3E%0A\",\"tokenFeatures\":[\"swap\",\"bridge\"]},{\"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\",\"chainId\":5,\"tokenFeatures\":[\"swap\",\"bridge\"]},{\"address\":\"0x1facdd0165489f373255a90304650e15481b2c85\",\"chainId\":5,\"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\"]},{\"address\":\"0x123456789\",\"chainId\":5,\"name\":\"Swap Coin\",\"symbol\":\"SWC\",\"decimals\":18,\"tokenFeatures\":[\"swap\",\"fakeFeature\"]},{\"address\":\"0x123456789\",\"chainId\":5,\"name\":\"Bridge Coin\",\"symbol\":\"BDC\",\"decimals\":18,\"tokenFeatures\":[\"bridge\",\"fakeFeature\"]}]");
2905
+
2906
+
2907
+ const $efe60cea83bfc4e8$export$473cec51305fdae8 = async function({ type: type = (exports.TokenFilterTypes).ALL , chainId: chainId , exclude: exclude }) {
2908
+ // todo:For API call, use the CheckoutError with errorType:API_CALL_ERROR?? or any other
2909
+ const filteredTokenList = ((/*@__PURE__*/$parcel$interopDefault($cda6003506e4182e$exports))).filter((token)=>{
2910
+ const chainIdMatches = token.chainId == chainId;
2911
+ const tokenNotExcluded = !exclude?.map((excludeToken)=>excludeToken.address).includes(token.address || "");
2912
+ const allowAllTokens = type === (exports.TokenFilterTypes).ALL;
2913
+ const tokenAllowedForType = token.tokenFeatures.includes(type);
2914
+ return chainIdMatches && tokenNotExcluded && (allowAllTokens || tokenAllowedForType);
2915
+ }).map((token)=>{
2916
+ const { chainId: chainId , tokenFeatures: tokenFeatures , ...tokenInfo } = token;
2917
+ return tokenInfo;
2918
+ });
2919
+ return {
2920
+ tokens: filteredTokenList
2921
+ };
2922
+ };
2923
+
2924
+
2925
+
2926
+
2927
+ const $1564e43dde50bb61$export$df96cd8d56be0ab1 = async (provider, walletAddress)=>{
2928
+ return await ($a8bc256d81a5e2c1$export$bacc563de539c6c3)(async ()=>{
2929
+ const networkInfo = await ($de192de6ef100f9f$export$79f13b4cfaaf0d09)(provider);
2930
+ if (!networkInfo.isSupported) throw new ($a8bc256d81a5e2c1$export$b722478a3cbfa3bc)(`Chain:${networkInfo.chainId} is not a supported chain`, (exports.CheckoutErrorType).CHAIN_NOT_SUPPORTED_ERROR, {
2931
+ chainName: networkInfo.name
2932
+ });
2933
+ const balance = await provider.getBalance(walletAddress);
2934
+ return {
2935
+ balance: balance,
2936
+ formattedBalance: (ethers.utils).formatUnits(balance, networkInfo.nativeCurrency.decimals),
2937
+ token: networkInfo.nativeCurrency
2938
+ };
2939
+ }, {
2940
+ type: (exports.CheckoutErrorType).GET_BALANCE_ERROR
2941
+ });
2942
+ };
2943
+ async function $1564e43dde50bb61$export$60e0fe116a0e6ed0(provider, walletAddress, contractAddress) {
2944
+ return await ($a8bc256d81a5e2c1$export$bacc563de539c6c3)(async ()=>{
2945
+ const contract = new (ethers.Contract)(contractAddress, JSON.stringify(($762782b6c862d954$export$db5daa1b5156ccfe)), provider);
2946
+ const name = await contract.name();
2947
+ const symbol = await contract.symbol();
2948
+ const balance = await contract.balanceOf(walletAddress);
2949
+ const decimals = await contract.decimals();
2950
+ const formattedBalance = (ethers.utils).formatUnits(balance, decimals);
2951
+ return {
2952
+ balance: balance,
2953
+ formattedBalance: formattedBalance,
2954
+ token: {
2955
+ name: name,
2956
+ symbol: symbol,
2957
+ decimals: decimals,
2958
+ address: contractAddress
2959
+ }
2960
+ };
2961
+ }, {
2962
+ type: (exports.CheckoutErrorType).GET_ERC20_BALANCE_ERROR
2963
+ });
2964
+ }
2965
+ const $1564e43dde50bb61$export$fee49741664a4d7e = async (provider, walletAddress, chainId)=>{
2966
+ if (!Object.values((exports.ChainId)).includes(chainId)) throw new ($a8bc256d81a5e2c1$export$b722478a3cbfa3bc)(`ChainId ${chainId} is not supported`, (exports.CheckoutErrorType).CHAIN_NOT_SUPPORTED_ERROR);
2967
+ if (!provider.provider?.request) throw new ($a8bc256d81a5e2c1$export$b722478a3cbfa3bc)("provider object is missing request function", (exports.CheckoutErrorType).PROVIDER_REQUEST_MISSING_ERROR);
2968
+ const tokenList = await ($efe60cea83bfc4e8$export$473cec51305fdae8)({
2969
+ type: (exports.TokenFilterTypes).ALL,
2970
+ chainId: chainId
2971
+ });
2972
+ const allBalancePromises = [];
2973
+ allBalancePromises.push($1564e43dde50bb61$export$df96cd8d56be0ab1(provider, walletAddress));
2974
+ tokenList.tokens.filter((token)=>token.address).forEach((token)=>allBalancePromises.push($1564e43dde50bb61$export$60e0fe116a0e6ed0(provider, walletAddress, token.address ?? "")));
2975
+ const balanceResults = await Promise.allSettled(allBalancePromises);
2976
+ const getBalanceResults = balanceResults.filter((result)=>result.status === "fulfilled").map((fulfilledResult)=>fulfilledResult.value);
2977
+ return {
2978
+ balances: getBalanceResults
2979
+ };
2980
+ };
2981
+
2982
+
2983
+
2984
+
2985
+
2986
+
2987
+
2988
+
2989
+
2990
+ var $6f3c55a615003cbf$exports = {};
2991
+ $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"]}]');
2992
+
2993
+
2994
+ async function $5cdde2ffe6360fec$export$a822caa90d7eef09({ type: type = (exports.WalletFilterTypes).ALL , exclude: exclude }) {
2995
+ // todo:For async API call, use the CheckoutError with errorType:API_CALL_ERROR?? or any other
2996
+ const filteredWalletsList = ((/*@__PURE__*/$parcel$interopDefault($6f3c55a615003cbf$exports))).filter((wallet)=>{
2997
+ const walletNotExcluded = !exclude?.map((excludeWallet)=>excludeWallet.connectionProvider).includes(wallet.connectionProvider);
2998
+ const allowAllWallets = type === (exports.WalletFilterTypes).ALL;
2999
+ const walletsAllowedForType = wallet.platform.includes(type);
3000
+ return walletNotExcluded && (allowAllWallets || walletsAllowedForType);
3001
+ }).map((wallet)=>{
3002
+ const { platform: platform , ...walletInfo } = wallet;
3003
+ return walletInfo;
3004
+ });
3005
+ return {
3006
+ wallets: filteredWalletsList
3007
+ };
3008
+ }
3009
+
3010
+
3011
+
3012
+
3013
+
3014
+
3015
+ const $dbe95599a4661140$export$8e0e7ffc78696d30 = async (params)=>{
3016
+ const { provider: provider , transaction: transaction } = params;
3017
+ return await ($a8bc256d81a5e2c1$export$bacc563de539c6c3)(async ()=>{
3018
+ const transactionResponse = await provider.getSigner().sendTransaction(transaction);
3019
+ return {
3020
+ transactionResponse: transactionResponse
3021
+ };
3022
+ }, {
3023
+ type: (exports.CheckoutErrorType).TRANSACTION_ERROR
3024
+ });
3025
+ };
3026
+
3027
+
3028
+
3029
+
3030
+
3031
+ class $a8cb37a3fc8eb863$export$1f60ba4ec72508a0 {
3032
+ /**
3033
+ * Check if a wallet is connected to the current application without requesting permission from the wallet and hence triggering a connect popup.
3034
+ * @param {CheckConnectionParams} params - The necessary data required to verify a wallet connection status.
3035
+ * @returns Wallet connection status details.
3036
+ * @throws {@link ErrorType}
3037
+ */ async checkIsWalletConnected(params) {
3038
+ return $c99672cf2294e839$export$2d040992269b4717(params.providerPreference);
3039
+ }
3040
+ /**
3041
+ * Establish a connection with a wallet provider such as MetaMask and returns the provider object and the current network details.
3042
+ * @param {ConnectParams} params - The necessary data required to establish a connection with a wallet provider.
3043
+ * @returns Wallet provider and current network information.
3044
+ * @throws {@link ErrorType}
3045
+ */ async connect(params) {
3046
+ this.providerPreference = params.providerPreference;
3047
+ const provider = await $c99672cf2294e839$export$fba2f6c3656e07c1(params);
3048
+ const networkInfo = await $de192de6ef100f9f$export$79f13b4cfaaf0d09(provider);
3049
+ return {
3050
+ provider: provider,
3051
+ network: networkInfo
3052
+ };
3053
+ }
3054
+ /**
3055
+ * Switch the currently connected wallet to a new network.
3056
+ * @param {SwitchNetworkParams} params - The necessary data required to switch network.
3057
+ * @returns The new network information.
3058
+ * @throws {@link ErrorType}
3059
+ */ async switchNetwork(params) {
3060
+ if (!this.providerPreference) throw new ($a8bc256d81a5e2c1$export$b722478a3cbfa3bc)(`connect should be called before switchNetwork to set the provider preference`, (exports.CheckoutErrorType).PROVIDER_PREFERENCE_ERROR);
3061
+ return await $de192de6ef100f9f$export$b827d9418aeb5dbd(this.providerPreference, params.provider, params.chainId);
3062
+ }
3063
+ /**
3064
+ * Fetch the balance of the native token of the current connected network or, if a contract address is provided, it will return the balance of that ERC20 token. For example, if the wallet is connected to the Ethereum Mainnet then the function gets the wallet ETH L1 balance.
3065
+ * @param {GetBalanceParams} params - The necessary data required to fetch the wallet balance.
3066
+ * @returns Native token balance for the given wallet.
3067
+ * @throws {@link ErrorType}
3068
+ */ async getBalance(params) {
3069
+ if (!params.contractAddress || params.contractAddress === "") return await $1564e43dde50bb61$export$df96cd8d56be0ab1(params.provider, params.walletAddress);
3070
+ return await $1564e43dde50bb61$export$60e0fe116a0e6ed0(params.provider, params.walletAddress, params.contractAddress);
3071
+ }
3072
+ /**
3073
+ * Fetch all available balances (ERC20 & Native) of the current connected network of the given wallet. It will loop through the list of allowed tokens and check for balance on each one.
3074
+ * @param {GetAllBalancesParams} params - The necessary data required to fetch all the wallet balances.
3075
+ * @returns List of tokens balance for the given wallet.
3076
+ * @throws {@link ErrorType}
3077
+ */ async getAllBalances(params) {
3078
+ return $1564e43dde50bb61$export$fee49741664a4d7e(params.provider, params.walletAddress, params.chainId);
3079
+ }
3080
+ /**
3081
+ * Fetch the list of available networks that a wallet can add or/and switch to.
3082
+ * @param {GetNetworkAllowListParams} params - The necessary data required to fetch the list of available networks.
3083
+ * @returns List of networks.
3084
+ * @throws {@link ErrorType}
3085
+ */ async getNetworkAllowList(params) {
3086
+ return await $de192de6ef100f9f$export$3043f6442a9ef563(params);
3087
+ }
3088
+ /**
3089
+ * Get the list of tokens which are allowed to be used with the product.
3090
+ * @param {GetTokenAllowListParams} params - The necessary data required to fetch the list of allowed tokens.
3091
+ * @returns List of allowed tokens.
3092
+ * @throws {@link ErrorType}
3093
+ */ async getTokenAllowList(params) {
3094
+ return await $efe60cea83bfc4e8$export$473cec51305fdae8(params);
3095
+ }
3096
+ /**
3097
+ * Fetch the list of wallets which are available to connect with.
3098
+ * @param {GetWalletAllowListParams} params - The necessary data required to fetch the list of allowed wallets.
3099
+ * @returns List of allowed wallets.
3100
+ * @throws {@link ErrorType}
3101
+ */ async getWalletAllowList(params) {
3102
+ return await $5cdde2ffe6360fec$export$a822caa90d7eef09(params);
3103
+ }
3104
+ /**
3105
+ * Send a generic transaction to the provider.
3106
+ * @param {SendTransactionParams} params - The necessary data required to send a transaction.
3107
+ * @returns Transaction response.
3108
+ * @throws {@link ErrorType}
3109
+ * @remarks
3110
+ * Further documenation can be found at [MetaMask | Sending Transactions](https://docs.metamask.io/guide/sending-transactions.html).
3111
+ */ async sendTransaction(params) {
3112
+ return await $dbe95599a4661140$export$8e0e7ffc78696d30(params);
3113
+ }
3114
+ /**
3115
+ * Get network information about the currently selected network.
3116
+ * @param {GetNetworkParams} params - The necessary data required to get the current network information.
3117
+ * @returns Network details.
3118
+ * @throws {@link ErrorType}
3119
+ */ async getNetworkInfo(params) {
3120
+ return await $de192de6ef100f9f$export$79f13b4cfaaf0d09(params.provider);
3121
+ }
3122
+ }
3123
+
3124
+ function $parcel$export(e, n, v, s) {
3125
+ Object.defineProperty(e, n, {get: v, set: s, enumerable: true, configurable: true});
3126
+ }
3127
+ var $88e4c575901cd68c$exports = {};
3128
+
3129
+ $parcel$export($88e4c575901cd68c$exports, "IMTBLWidgetEvents", () => exports.IMTBLWidgetEvents);
3130
+ exports.IMTBLWidgetEvents = void 0;
3131
+ (function(IMTBLWidgetEvents) {
3132
+ IMTBLWidgetEvents["IMTBL_CONNECT_WIDGET_EVENT"] = "imtbl-connect-widget";
3133
+ IMTBLWidgetEvents["IMTBL_WALLET_WIDGET_EVENT"] = "imtbl-wallet-widget";
3134
+ IMTBLWidgetEvents["IMTBL_SWAP_WIDGET_EVENT"] = "imtbl-swap-widget";
3135
+ IMTBLWidgetEvents["IMTBL_BRIDGE_WIDGET_EVENT"] = "imtbl-bridge-widget";
3136
+ IMTBLWidgetEvents["IMTBL_BUY_WIDGET_EVENT"] = "imtbl-buy-widget";
3137
+ })(exports.IMTBLWidgetEvents || (exports.IMTBLWidgetEvents = {}));
3138
+
3139
+
3140
+ var $d71a87afc3136184$exports = {};
3141
+
3142
+ $parcel$export($d71a87afc3136184$exports, "ConnectEventType", () => exports.ConnectEventType);
3143
+ exports.ConnectEventType = void 0;
3144
+ (function(ConnectEventType) {
3145
+ ConnectEventType["SUCCESS"] = "success";
3146
+ ConnectEventType["FAILURE"] = "failure";
3147
+ ConnectEventType["CLOSE_WIDGET"] = "close-widget";
3148
+ })(exports.ConnectEventType || (exports.ConnectEventType = {}));
3149
+
3150
+
3151
+ var $9d0f1783d4d36e8a$exports = {};
3152
+
3153
+ $parcel$export($9d0f1783d4d36e8a$exports, "WalletEventType", () => exports.WalletEventType);
3154
+ //wallet widget events
3155
+ exports.WalletEventType = void 0;
3156
+ (function(WalletEventType) {
3157
+ WalletEventType["CLOSE_WIDGET"] = "close-widget";
3158
+ WalletEventType["NETWORK_SWITCH"] = "network-switch";
3159
+ })(exports.WalletEventType || (exports.WalletEventType = {}));
3160
+
3161
+
3162
+ var $5d497088f13bb116$exports = {};
3163
+
3164
+ $parcel$export($5d497088f13bb116$exports, "SwapEventType", () => exports.SwapEventType);
3165
+ exports.SwapEventType = void 0;
3166
+ (function(SwapEventType) {
3167
+ SwapEventType["SUCCESS"] = "success";
3168
+ SwapEventType["FAILURE"] = "failure";
3169
+ })(exports.SwapEventType || (exports.SwapEventType = {}));
3170
+
3171
+
3172
+ var $28a5fdc2f5e6c742$exports = {};
3173
+
3174
+ $parcel$export($28a5fdc2f5e6c742$exports, "BridgeEventType", () => exports.BridgeEventType);
3175
+ exports.BridgeEventType = void 0;
3176
+ (function(BridgeEventType) {
3177
+ BridgeEventType["CLOSE_WIDGET"] = "close-widget";
3178
+ BridgeEventType["SUCCESS"] = "success";
3179
+ BridgeEventType["FAILURE"] = "failure";
3180
+ })(exports.BridgeEventType || (exports.BridgeEventType = {}));
3181
+
3182
+
3183
+ var $ede253beebe0de4a$exports = {};
3184
+
3185
+ $parcel$export($ede253beebe0de4a$exports, "BuyEventType", () => exports.BuyEventType);
3186
+ exports.BuyEventType = void 0;
3187
+ (function(BuyEventType) {
3188
+ BuyEventType["SUCCESS"] = "success";
3189
+ BuyEventType["FAILURE"] = "failure";
3190
+ BuyEventType["NOT_CONNECTED"] = "not_connected";
3191
+ BuyEventType["CLOSE"] = "close";
3192
+ })(exports.BuyEventType || (exports.BuyEventType = {}));
3193
+
3194
+
3195
+ var $9234b4c577442a97$exports = {};
3196
+
3197
+ $parcel$export($9234b4c577442a97$exports, "Network", () => exports.Network);
3198
+ $parcel$export($9234b4c577442a97$exports, "WidgetTheme", () => exports.WidgetTheme);
3199
+ $parcel$export($9234b4c577442a97$exports, "ConnectionProviders", () => exports.ConnectionProviders);
3200
+
3201
+ exports.Network = void 0;
3202
+ (function(Network) {
3203
+ Network["ETHEREUM"] = "Ethereum";
3204
+ Network["GOERLI"] = "Goerli";
3205
+ Network["POLYGON"] = "Polygon";
3206
+ })(exports.Network || (exports.Network = {}));
3207
+ exports.WidgetTheme = void 0;
3208
+ (function(WidgetTheme) {
3209
+ WidgetTheme["LIGHT"] = "light";
3210
+ WidgetTheme["DARK"] = "dark";
3211
+ WidgetTheme["CUSTOM"] = "custom";
3212
+ })(exports.WidgetTheme || (exports.WidgetTheme = {}));
3213
+
1464
3214
  Object.defineProperty(exports, 'imxClientCreateStarkSigner', {
1465
3215
  enumerable: true,
1466
3216
  get: function () { return coreSdk.createStarkSigner; }
@@ -1469,7 +3219,11 @@ Object.defineProperty(exports, 'imxClientGenerateLegacyStarkPrivateKey', {
1469
3219
  enumerable: true,
1470
3220
  get: function () { return coreSdk.generateLegacyStarkPrivateKey; }
1471
3221
  });
3222
+ exports.Checkout = $a8cb37a3fc8eb863$export$1f60ba4ec72508a0;
3223
+ exports.GenericIMXProvider = GenericIMXProvider;
1472
3224
  exports.ImmutableConfiguration = ImmutableConfiguration;
1473
3225
  exports.ImmutableXClient = ImmutableXClient;
3226
+ exports.MetaMaskIMXProvider = MetaMaskIMXProvider;
1474
3227
  exports.Passport = Passport;
1475
3228
  exports.PassportError = PassportError;
3229
+ exports.ProviderConfiguration = ProviderConfiguration;