@metamask/connect-multichain 0.3.1 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/CHANGELOG.md +35 -13
  2. package/README.md +1 -1
  3. package/dist/browser/es/connect-multichain.d.mts +4 -6
  4. package/dist/browser/es/connect-multichain.mjs +593 -588
  5. package/dist/browser/es/connect-multichain.mjs.map +1 -1
  6. package/dist/browser/es/metafile-esm.json +1 -1
  7. package/dist/browser/iife/connect-multichain.d.ts +4 -6
  8. package/dist/browser/iife/connect-multichain.js +3821 -2109
  9. package/dist/browser/iife/connect-multichain.js.map +1 -1
  10. package/dist/browser/iife/metafile-iife.json +1 -1
  11. package/dist/browser/umd/connect-multichain.d.ts +4 -6
  12. package/dist/browser/umd/connect-multichain.js +593 -588
  13. package/dist/browser/umd/connect-multichain.js.map +1 -1
  14. package/dist/browser/umd/metafile-cjs.json +1 -1
  15. package/dist/node/cjs/connect-multichain.d.ts +4 -6
  16. package/dist/node/cjs/connect-multichain.js +594 -600
  17. package/dist/node/cjs/connect-multichain.js.map +1 -1
  18. package/dist/node/cjs/metafile-cjs.json +1 -1
  19. package/dist/node/es/connect-multichain.d.mts +4 -6
  20. package/dist/node/es/connect-multichain.mjs +593 -599
  21. package/dist/node/es/connect-multichain.mjs.map +1 -1
  22. package/dist/node/es/metafile-esm.json +1 -1
  23. package/dist/react-native/es/connect-multichain.d.mts +4 -6
  24. package/dist/react-native/es/connect-multichain.mjs +580 -584
  25. package/dist/react-native/es/connect-multichain.mjs.map +1 -1
  26. package/dist/react-native/es/metafile-esm.json +1 -1
  27. package/dist/src/domain/multichain/types.d.ts +2 -4
  28. package/dist/src/domain/multichain/types.d.ts.map +1 -1
  29. package/dist/src/multichain/index.d.ts +3 -22
  30. package/dist/src/multichain/index.d.ts.map +1 -1
  31. package/dist/src/multichain/index.js +422 -424
  32. package/dist/src/multichain/index.js.map +1 -1
  33. package/dist/src/multichain/rpc/requestRouter.js +17 -19
  34. package/dist/src/multichain/rpc/requestRouter.js.map +1 -1
  35. package/dist/src/multichain/transports/default/index.d.ts +2 -0
  36. package/dist/src/multichain/transports/default/index.d.ts.map +1 -1
  37. package/dist/src/multichain/transports/default/index.js +6 -0
  38. package/dist/src/multichain/transports/default/index.js.map +1 -1
  39. package/dist/src/multichain/transports/mwp/index.d.ts +2 -1
  40. package/dist/src/multichain/transports/mwp/index.d.ts.map +1 -1
  41. package/dist/src/multichain/transports/mwp/index.js +41 -16
  42. package/dist/src/multichain/transports/mwp/index.js.map +1 -1
  43. package/dist/src/ui/index.d.ts +2 -6
  44. package/dist/src/ui/index.d.ts.map +1 -1
  45. package/dist/src/ui/index.js +8 -49
  46. package/dist/src/ui/index.js.map +1 -1
  47. package/dist/src/ui/modals/node/install.js +2 -2
  48. package/dist/src/ui/modals/node/install.js.map +1 -1
  49. package/dist/src/ui/preload.native.d.ts +5 -0
  50. package/dist/src/ui/preload.native.d.ts.map +1 -0
  51. package/dist/src/ui/preload.native.js +18 -0
  52. package/dist/src/ui/preload.native.js.map +1 -0
  53. package/dist/src/ui/preload.web.d.ts +5 -0
  54. package/dist/src/ui/preload.web.d.ts.map +1 -0
  55. package/dist/src/ui/{qr.js → preload.web.js} +13 -18
  56. package/dist/src/ui/preload.web.js.map +1 -0
  57. package/dist/types/connect-multichain.d.ts +4 -6
  58. package/package.json +7 -7
  59. package/dist/src/ui/qr.d.ts +0 -3
  60. package/dist/src/ui/qr.d.ts.map +0 -1
  61. package/dist/src/ui/qr.js.map +0 -1
@@ -256,8 +256,8 @@ var init_logger = __esm({
256
256
  import_debug.default.enable(namespace);
257
257
  };
258
258
  isEnabled = (namespace, storage) => __async(null, null, function* () {
259
- var _a;
260
- if ("process" in globalThis && ((_a = process == null ? void 0 : process.env) == null ? void 0 : _a.DEBUG)) {
259
+ var _a2;
260
+ if ("process" in globalThis && ((_a2 = process == null ? void 0 : process.env) == null ? void 0 : _a2.DEBUG)) {
261
261
  const { DEBUG } = process.env;
262
262
  return isNamespaceEnabled(DEBUG, namespace);
263
263
  }
@@ -426,35 +426,35 @@ var init_multichain = __esm({
426
426
 
427
427
  // src/domain/platform/index.ts
428
428
  function isNotBrowser() {
429
- var _a;
429
+ var _a2;
430
430
  if (typeof window === "undefined") {
431
431
  return true;
432
432
  }
433
433
  if (!(window == null ? void 0 : window.navigator)) {
434
434
  return true;
435
435
  }
436
- if (typeof global !== "undefined" && ((_a = global == null ? void 0 : global.navigator) == null ? void 0 : _a.product) === "ReactNative") {
436
+ if (typeof global !== "undefined" && ((_a2 = global == null ? void 0 : global.navigator) == null ? void 0 : _a2.product) === "ReactNative") {
437
437
  return true;
438
438
  }
439
439
  return (navigator == null ? void 0 : navigator.product) === "ReactNative";
440
440
  }
441
441
  function isReactNative() {
442
- var _a;
442
+ var _a2;
443
443
  const hasWindowNavigator = typeof window !== "undefined" && window.navigator !== void 0;
444
444
  const nav = hasWindowNavigator ? window.navigator : void 0;
445
445
  if (!nav) {
446
446
  return false;
447
447
  }
448
- return hasWindowNavigator && ((_a = window.navigator) == null ? void 0 : _a.product) === "ReactNative";
448
+ return hasWindowNavigator && ((_a2 = window.navigator) == null ? void 0 : _a2.product) === "ReactNative";
449
449
  }
450
450
  function isMetaMaskMobileWebView() {
451
451
  return typeof window !== "undefined" && // @ts-expect-error ReactNativeWebView should be defined
452
452
  Boolean(window.ReactNativeWebView) && Boolean(window.navigator.userAgent.endsWith("MetaMaskMobile"));
453
453
  }
454
454
  function isMobile() {
455
- var _a, _b;
455
+ var _a2, _b;
456
456
  const browser = import_bowser.default.parse(window.navigator.userAgent);
457
- return ((_a = browser == null ? void 0 : browser.platform) == null ? void 0 : _a.type) === "mobile" || ((_b = browser == null ? void 0 : browser.platform) == null ? void 0 : _b.type) === "tablet";
457
+ return ((_a2 = browser == null ? void 0 : browser.platform) == null ? void 0 : _a2.type) === "mobile" || ((_b = browser == null ? void 0 : browser.platform) == null ? void 0 : _b.type) === "tablet";
458
458
  }
459
459
  function getPlatformType() {
460
460
  if (isReactNative()) {
@@ -472,11 +472,11 @@ function getPlatformType() {
472
472
  return "web-desktop" /* DesktopWeb */;
473
473
  }
474
474
  function isMetamaskExtensionInstalled() {
475
- var _a;
475
+ var _a2;
476
476
  if (typeof window === "undefined") {
477
477
  return false;
478
478
  }
479
- return Boolean((_a = window.ethereum) == null ? void 0 : _a.isMetaMask);
479
+ return Boolean((_a2 = window.ethereum) == null ? void 0 : _a2.isMetaMask);
480
480
  }
481
481
  function isSecure() {
482
482
  const platformType = getPlatformType();
@@ -508,8 +508,8 @@ var init_platform = __esm({
508
508
  return new Promise((resolve) => {
509
509
  const providers = [];
510
510
  const handler = (event) => {
511
- var _a, _b;
512
- if ((_b = (_a = event == null ? void 0 : event.detail) == null ? void 0 : _a.info) == null ? void 0 : _b.rdns) {
511
+ var _a2, _b;
512
+ if ((_b = (_a2 = event == null ? void 0 : event.detail) == null ? void 0 : _a2.info) == null ? void 0 : _b.rdns) {
513
513
  providers.push(event.detail);
514
514
  }
515
515
  };
@@ -519,8 +519,8 @@ var init_platform = __esm({
519
519
  window.removeEventListener("eip6963:announceProvider", handler);
520
520
  const hasMetaMask = providers.some(
521
521
  (provider) => {
522
- var _a, _b;
523
- return (_b = (_a = provider == null ? void 0 : provider.info) == null ? void 0 : _a.rdns) == null ? void 0 : _b.startsWith("io.metamask");
522
+ var _a2, _b;
523
+ return (_b = (_a2 = provider == null ? void 0 : provider.info) == null ? void 0 : _a2.rdns) == null ? void 0 : _b.startsWith("io.metamask");
524
524
  }
525
525
  );
526
526
  resolve(hasMetaMask);
@@ -619,8 +619,8 @@ function compressString(str) {
619
619
  return base64Encode(binaryString);
620
620
  }
621
621
  function getDappId(dapp) {
622
- var _a;
623
- return (_a = dapp.url) != null ? _a : dapp.name;
622
+ var _a2;
623
+ return (_a2 = dapp.url) != null ? _a2 : dapp.name;
624
624
  }
625
625
  function openDeeplink(options, deeplink, universalLink) {
626
626
  const { mobile } = options;
@@ -650,10 +650,10 @@ function getOptionalScopes(scopes) {
650
650
  );
651
651
  }
652
652
  function setupDappMetadata(options) {
653
- var _a, _b;
653
+ var _a2, _b;
654
654
  const platform = getPlatformType();
655
655
  const isBrowser = platform === "web-desktop" /* DesktopWeb */ || platform === "web-mobile" /* MobileWeb */ || platform === "in-app-browser" /* MetaMaskMobileWebview */;
656
- if (!((_a = options.dapp) == null ? void 0 : _a.name)) {
656
+ if (!((_a2 = options.dapp) == null ? void 0 : _a2.name)) {
657
657
  throw new Error("You must provide dapp name");
658
658
  }
659
659
  if (isBrowser) {
@@ -724,17 +724,17 @@ function getValidAccounts(caipAccountIds) {
724
724
  );
725
725
  }
726
726
  function addValidAccounts(optionalScopes, validAccounts) {
727
- var _a;
727
+ var _a2;
728
728
  if (!optionalScopes || !(validAccounts == null ? void 0 : validAccounts.length)) {
729
729
  return optionalScopes;
730
730
  }
731
731
  const result = Object.fromEntries(
732
732
  Object.entries(optionalScopes).map(([scope, scopeData]) => {
733
- var _a2, _b, _c;
733
+ var _a3, _b, _c;
734
734
  return [
735
735
  scope,
736
736
  {
737
- methods: [...(_a2 = scopeData == null ? void 0 : scopeData.methods) != null ? _a2 : []],
737
+ methods: [...(_a3 = scopeData == null ? void 0 : scopeData.methods) != null ? _a3 : []],
738
738
  notifications: [...(_b = scopeData == null ? void 0 : scopeData.notifications) != null ? _b : []],
739
739
  accounts: [...(_c = scopeData == null ? void 0 : scopeData.accounts) != null ? _c : []]
740
740
  }
@@ -748,7 +748,7 @@ function addValidAccounts(optionalScopes, validAccounts) {
748
748
  if (!accountsByChain.has(chainKey)) {
749
749
  accountsByChain.set(chainKey, []);
750
750
  }
751
- (_a = accountsByChain.get(chainKey)) == null ? void 0 : _a.push(accountId);
751
+ (_a2 = accountsByChain.get(chainKey)) == null ? void 0 : _a2.push(accountId);
752
752
  }
753
753
  for (const [scopeKey, scopeData] of Object.entries(result)) {
754
754
  if (!(scopeData == null ? void 0 : scopeData.accounts)) {
@@ -780,7 +780,7 @@ var init_utils = __esm({
780
780
  import_utils = require("@metamask/utils");
781
781
  init_domain();
782
782
  extractFavicon = () => {
783
- var _a;
783
+ var _a2;
784
784
  if (typeof document === "undefined") {
785
785
  return void 0;
786
786
  }
@@ -788,7 +788,7 @@ var init_utils = __esm({
788
788
  const nodeList = document.getElementsByTagName("link");
789
789
  for (let i = 0; i < nodeList.length; i++) {
790
790
  if (nodeList[i].getAttribute("rel") === "icon" || nodeList[i].getAttribute("rel") === "shortcut icon") {
791
- favicon = (_a = nodeList[i].getAttribute("href")) != null ? _a : void 0;
791
+ favicon = (_a2 = nodeList[i].getAttribute("href")) != null ? _a2 : void 0;
792
792
  }
793
793
  }
794
794
  return favicon;
@@ -798,25 +798,25 @@ var init_utils = __esm({
798
798
 
799
799
  // src/multichain/utils/analytics.ts
800
800
  function isRejectionError(error) {
801
- var _a, _b;
801
+ var _a2, _b;
802
802
  if (typeof error !== "object" || error === null) {
803
803
  return false;
804
804
  }
805
805
  const errorObj = error;
806
806
  const errorCode = errorObj.code;
807
- const errorMessage = (_b = (_a = errorObj.message) == null ? void 0 : _a.toLowerCase()) != null ? _b : "";
807
+ const errorMessage = (_b = (_a2 = errorObj.message) == null ? void 0 : _a2.toLowerCase()) != null ? _b : "";
808
808
  return errorCode === 4001 || // User rejected request (common EIP-1193 code)
809
809
  errorCode === 4100 || // Unauthorized (common rejection code)
810
810
  errorMessage.includes("reject") || errorMessage.includes("denied") || errorMessage.includes("cancel") || errorMessage.includes("user");
811
811
  }
812
812
  function getBaseAnalyticsProperties(options, storage) {
813
813
  return __async(this, null, function* () {
814
- var _a, _b;
814
+ var _a2, _b;
815
815
  const version = getVersion();
816
816
  const dappId = getDappId(options.dapp);
817
817
  const platform = getPlatformType();
818
818
  const anonId = yield storage.getAnonId();
819
- const integrationType = (_b = (_a = options.analytics) == null ? void 0 : _a.integrationType) != null ? _b : "unknown" /* UNKNOWN */;
819
+ const integrationType = (_b = (_a2 = options.analytics) == null ? void 0 : _a2.integrationType) != null ? _b : "unknown" /* UNKNOWN */;
820
820
  return {
821
821
  mmconnect_version: version,
822
822
  dapp_id: dappId,
@@ -828,11 +828,11 @@ function getBaseAnalyticsProperties(options, storage) {
828
828
  }
829
829
  function getWalletActionAnalyticsProperties(options, storage, invokeOptions) {
830
830
  return __async(this, null, function* () {
831
- var _a, _b;
831
+ var _a2, _b;
832
832
  const version = getVersion();
833
833
  const dappId = getDappId(options.dapp);
834
834
  const anonId = yield storage.getAnonId();
835
- const integrationType = (_b = (_a = options.analytics) == null ? void 0 : _a.integrationType) != null ? _b : "unknown";
835
+ const integrationType = (_b = (_a2 = options.analytics) == null ? void 0 : _a2.integrationType) != null ? _b : "unknown";
836
836
  return {
837
837
  mmconnect_version: version,
838
838
  dapp_id: dappId,
@@ -1004,7 +1004,7 @@ var init_install = __esm({
1004
1004
  renderQRCode() {
1005
1005
  }
1006
1006
  mount() {
1007
- var _a;
1007
+ var _a2;
1008
1008
  const { options } = this;
1009
1009
  const modal = document.createElement(
1010
1010
  "mm-install-modal"
@@ -1021,14 +1021,14 @@ var init_install = __esm({
1021
1021
  );
1022
1022
  modal.link = options.link;
1023
1023
  this.instance = modal;
1024
- (_a = options.parentElement) == null ? void 0 : _a.appendChild(modal);
1024
+ (_a2 = options.parentElement) == null ? void 0 : _a2.appendChild(modal);
1025
1025
  this.startExpirationCheck(options.connectionRequest);
1026
1026
  }
1027
1027
  unmount() {
1028
- var _a;
1028
+ var _a2;
1029
1029
  const { options, instance: modal } = this;
1030
1030
  this.stopExpirationCheck();
1031
- if (modal && ((_a = options.parentElement) == null ? void 0 : _a.contains(modal))) {
1031
+ if (modal && ((_a2 = options.parentElement) == null ? void 0 : _a2.contains(modal))) {
1032
1032
  options.parentElement.removeChild(modal);
1033
1033
  this.instance = void 0;
1034
1034
  }
@@ -1140,8 +1140,8 @@ var init_web2 = __esm({
1140
1140
  const request = store.get(key);
1141
1141
  request.onerror = () => reject(new Error("Failed to get value from IndexedDB."));
1142
1142
  request.onsuccess = () => {
1143
- var _a;
1144
- return resolve((_a = request.result) != null ? _a : null);
1143
+ var _a2;
1144
+ return resolve((_a2 = request.result) != null ? _a2 : null);
1145
1145
  };
1146
1146
  } catch (error) {
1147
1147
  reject(error);
@@ -1276,8 +1276,8 @@ var RpcClient = class {
1276
1276
  });
1277
1277
  }
1278
1278
  getRpcEndpoint(scope) {
1279
- var _a, _b, _c;
1280
- const supportedNetworks = (_c = (_b = (_a = this.config) == null ? void 0 : _a.api) == null ? void 0 : _b.supportedNetworks) != null ? _c : {};
1279
+ var _a2, _b, _c;
1280
+ const supportedNetworks = (_c = (_b = (_a2 = this.config) == null ? void 0 : _a2.api) == null ? void 0 : _b.supportedNetworks) != null ? _c : {};
1281
1281
  const rpcEndpoint = supportedNetworks[scope];
1282
1282
  if (!rpcEndpoint) {
1283
1283
  throw new MissingRpcEndpointErr(`No RPC endpoint found for scope ${scope}`);
@@ -1381,13 +1381,18 @@ var RequestRouter = class {
1381
1381
  const secure = isSecure();
1382
1382
  const shouldOpenDeeplink = secure && !showInstallModal;
1383
1383
  if (shouldOpenDeeplink) {
1384
- setTimeout(() => {
1384
+ setTimeout(() => __async(this, null, function* () {
1385
+ const session = yield this.transport.getActiveSession();
1386
+ if (!session) {
1387
+ throw new Error("No active session found");
1388
+ }
1389
+ const url = `${METAMASK_DEEPLINK_BASE}/mwp?id=${encodeURIComponent(session.id)}`;
1385
1390
  if (mobile == null ? void 0 : mobile.preferredOpenLink) {
1386
- mobile.preferredOpenLink(METAMASK_DEEPLINK_BASE, "_self");
1391
+ mobile.preferredOpenLink(url, "_self");
1387
1392
  } else {
1388
- openDeeplink(this.config, METAMASK_DEEPLINK_BASE, METAMASK_CONNECT_BASE_URL);
1393
+ openDeeplink(this.config, url, METAMASK_CONNECT_BASE_URL);
1389
1394
  }
1390
- }, 10);
1395
+ }), 10);
1391
1396
  }
1392
1397
  const response = yield request;
1393
1398
  if (response.error) {
@@ -1427,24 +1432,17 @@ var RequestRouter = class {
1427
1432
  _RequestRouter_instances = new WeakSet();
1428
1433
  withAnalyticsTracking_fn = function(options, execute) {
1429
1434
  return __async(this, null, function* () {
1430
- var _a, _b, _c;
1431
- if ((_a = this.config.analytics) == null ? void 0 : _a.enabled) {
1432
- yield __privateMethod(this, _RequestRouter_instances, trackWalletActionRequested_fn).call(this, options);
1433
- }
1435
+ yield __privateMethod(this, _RequestRouter_instances, trackWalletActionRequested_fn).call(this, options);
1434
1436
  try {
1435
1437
  const result = yield execute();
1436
- if ((_b = this.config.analytics) == null ? void 0 : _b.enabled) {
1437
- yield __privateMethod(this, _RequestRouter_instances, trackWalletActionSucceeded_fn).call(this, options);
1438
- }
1438
+ yield __privateMethod(this, _RequestRouter_instances, trackWalletActionSucceeded_fn).call(this, options);
1439
1439
  return result;
1440
1440
  } catch (error) {
1441
- if ((_c = this.config.analytics) == null ? void 0 : _c.enabled) {
1442
- const isRejection = isRejectionError(error);
1443
- if (isRejection) {
1444
- yield __privateMethod(this, _RequestRouter_instances, trackWalletActionRejected_fn).call(this, options);
1445
- } else {
1446
- yield __privateMethod(this, _RequestRouter_instances, trackWalletActionFailed_fn).call(this, options);
1447
- }
1441
+ const isRejection = isRejectionError(error);
1442
+ if (isRejection) {
1443
+ yield __privateMethod(this, _RequestRouter_instances, trackWalletActionRejected_fn).call(this, options);
1444
+ } else {
1445
+ yield __privateMethod(this, _RequestRouter_instances, trackWalletActionFailed_fn).call(this, options);
1448
1446
  }
1449
1447
  throw new RPCInvokeMethodErr(error.message);
1450
1448
  }
@@ -1504,11 +1502,11 @@ var DefaultTransport = class {
1504
1502
  id: requestId
1505
1503
  }, payload);
1506
1504
  return new Promise((resolve, reject) => {
1507
- var _a;
1505
+ var _a2;
1508
1506
  const timeout = setTimeout(() => {
1509
1507
  __privateGet(this, _pendingRequests).delete(requestId);
1510
1508
  reject(new Error("Request timeout"));
1511
- }, (_a = options == null ? void 0 : options.timeout) != null ? _a : __privateGet(this, _defaultRequestOptions).timeout);
1509
+ }, (_a2 = options == null ? void 0 : options.timeout) != null ? _a2 : __privateGet(this, _defaultRequestOptions).timeout);
1512
1510
  __privateGet(this, _pendingRequests).set(requestId, {
1513
1511
  resolve: (response) => {
1514
1512
  resolve(response);
@@ -1532,7 +1530,7 @@ var DefaultTransport = class {
1532
1530
  }
1533
1531
  connect(options) {
1534
1532
  return __async(this, null, function* () {
1535
- var _a, _b, _c, _d, _e, _f, _g;
1533
+ var _a2, _b, _c, _d, _e, _f, _g;
1536
1534
  __privateMethod(this, _DefaultTransport_instances, setupMessageListener_fn).call(this);
1537
1535
  yield __privateGet(this, _transport).connect();
1538
1536
  const sessionRequest = yield this.request(
@@ -1545,7 +1543,7 @@ var DefaultTransport = class {
1545
1543
  let walletSession = sessionRequest.result;
1546
1544
  if (walletSession && options && !options.forceRequest) {
1547
1545
  const currentScopes = Object.keys(
1548
- (_a = walletSession == null ? void 0 : walletSession.sessionScopes) != null ? _a : {}
1546
+ (_a2 = walletSession == null ? void 0 : walletSession.sessionScopes) != null ? _a2 : {}
1549
1547
  );
1550
1548
  const proposedScopes = (_b = options == null ? void 0 : options.scopes) != null ? _b : [];
1551
1549
  const proposedCaipAccountIds = (_c = options == null ? void 0 : options.caipAccountIds) != null ? _c : [];
@@ -1634,6 +1632,9 @@ var DefaultTransport = class {
1634
1632
  __privateGet(this, _notificationCallbacks).delete(callback);
1635
1633
  };
1636
1634
  }
1635
+ getActiveSession() {
1636
+ throw new Error("getActiveSession is purposely not implemented for the DefaultTransport");
1637
+ }
1637
1638
  };
1638
1639
  _notificationCallbacks = new WeakMap();
1639
1640
  _transport = new WeakMap();
@@ -1656,16 +1657,16 @@ notifyCallbacks_fn = function(data) {
1656
1657
  }
1657
1658
  };
1658
1659
  isMetamaskProviderEvent_fn = function(event) {
1659
- var _a, _b;
1660
- return ((_b = (_a = event == null ? void 0 : event.data) == null ? void 0 : _a.data) == null ? void 0 : _b.name) === "metamask-provider" && // eslint-disable-next-line no-restricted-globals
1660
+ var _a2, _b;
1661
+ return ((_b = (_a2 = event == null ? void 0 : event.data) == null ? void 0 : _a2.data) == null ? void 0 : _b.name) === "metamask-provider" && // eslint-disable-next-line no-restricted-globals
1661
1662
  event.origin === location.origin;
1662
1663
  };
1663
1664
  handleResponse_fn = function(event) {
1664
- var _a, _b;
1665
+ var _a2, _b;
1665
1666
  if (!__privateMethod(this, _DefaultTransport_instances, isMetamaskProviderEvent_fn).call(this, event)) {
1666
1667
  return;
1667
1668
  }
1668
- const responseData = (_b = (_a = event == null ? void 0 : event.data) == null ? void 0 : _a.data) == null ? void 0 : _b.data;
1669
+ const responseData = (_b = (_a2 = event == null ? void 0 : event.data) == null ? void 0 : _a2.data) == null ? void 0 : _b.data;
1669
1670
  if (typeof responseData === "object" && responseData !== null && "method" in responseData) {
1670
1671
  return;
1671
1672
  }
@@ -1687,11 +1688,11 @@ handleResponse_fn = function(event) {
1687
1688
  }
1688
1689
  };
1689
1690
  handleNotification_fn = function(event) {
1690
- var _a, _b;
1691
+ var _a2, _b;
1691
1692
  if (!__privateMethod(this, _DefaultTransport_instances, isMetamaskProviderEvent_fn).call(this, event)) {
1692
1693
  return;
1693
1694
  }
1694
- const responseData = (_b = (_a = event == null ? void 0 : event.data) == null ? void 0 : _a.data) == null ? void 0 : _b.data;
1695
+ const responseData = (_b = (_a2 = event == null ? void 0 : event.data) == null ? void 0 : _a2.data) == null ? void 0 : _b.data;
1695
1696
  if (typeof responseData === "object" && responseData.method === "metamask_chainChanged" || responseData.method === "metamask_accountsChanged") {
1696
1697
  __privateMethod(this, _DefaultTransport_instances, notifyCallbacks_fn).call(this, responseData);
1697
1698
  }
@@ -1817,7 +1818,7 @@ var MWPTransport = class {
1817
1818
  }
1818
1819
  onResumeSuccess(resumeResolve, resumeReject, options) {
1819
1820
  return __async(this, null, function* () {
1820
- var _a, _b, _c, _d, _e, _f, _g;
1821
+ var _a2, _b, _c, _d, _e, _f, _g;
1821
1822
  try {
1822
1823
  const sessionRequest = yield this.request({
1823
1824
  method: "wallet_getSession"
@@ -1828,7 +1829,7 @@ var MWPTransport = class {
1828
1829
  let walletSession = sessionRequest.result;
1829
1830
  if (walletSession && options) {
1830
1831
  const currentScopes = Object.keys(
1831
- (_a = walletSession == null ? void 0 : walletSession.sessionScopes) != null ? _a : {}
1832
+ (_a2 = walletSession == null ? void 0 : walletSession.sessionScopes) != null ? _a2 : {}
1832
1833
  );
1833
1834
  const proposedScopes = (_b = options == null ? void 0 : options.scopes) != null ? _b : [];
1834
1835
  const proposedCaipAccountIds = (_c = options == null ? void 0 : options.caipAccountIds) != null ? _c : [];
@@ -1893,10 +1894,10 @@ var MWPTransport = class {
1893
1894
  return cachedWalletSession;
1894
1895
  }
1895
1896
  return new Promise((resolve, reject) => {
1896
- var _a;
1897
+ var _a2;
1897
1898
  const timeout = setTimeout(() => {
1898
1899
  this.rejectRequest(request.id, new import_multichain_api_client2.TransportTimeoutError());
1899
- }, (_a = options == null ? void 0 : options.timeout) != null ? _a : this.options.requestTimeout);
1900
+ }, (_a2 = options == null ? void 0 : options.timeout) != null ? _a2 : this.options.requestTimeout);
1900
1901
  this.pendingRequests.set(request.id, {
1901
1902
  request,
1902
1903
  method: request.method,
@@ -1916,38 +1917,33 @@ var MWPTransport = class {
1916
1917
  }
1917
1918
  connect(options) {
1918
1919
  return __async(this, null, function* () {
1919
- const { dappClient, kvstore } = this;
1920
- const sessionStore = new import_mobile_wallet_protocol_core.SessionStore(kvstore);
1921
- let session;
1922
- try {
1923
- const [activeSession] = yield sessionStore.list();
1924
- if (activeSession) {
1925
- logger("active session found", activeSession);
1926
- session = activeSession;
1927
- }
1928
- } catch (e) {
1920
+ const { dappClient } = this;
1921
+ const session = yield this.getActiveSession();
1922
+ if (session) {
1923
+ logger("active session found", session);
1929
1924
  }
1930
1925
  let timeout;
1926
+ let initialConnectionMessageHandler;
1931
1927
  const connectionPromise = new Promise((resolve, reject) => {
1932
1928
  let connection;
1933
1929
  if (session) {
1934
1930
  connection = new Promise((resumeResolve, resumeReject) => {
1935
- var _a;
1931
+ var _a2;
1936
1932
  if (this.dappClient.state === "CONNECTED") {
1937
1933
  this.onResumeSuccess(resumeResolve, resumeReject, options);
1938
1934
  } else {
1939
1935
  this.dappClient.once("connected", () => __async(this, null, function* () {
1940
1936
  this.onResumeSuccess(resumeResolve, resumeReject, options);
1941
1937
  }));
1942
- dappClient.resume((_a = session == null ? void 0 : session.id) != null ? _a : "");
1938
+ dappClient.resume((_a2 = session == null ? void 0 : session.id) != null ? _a2 : "");
1943
1939
  }
1944
1940
  });
1945
1941
  } else {
1946
1942
  connection = new Promise(
1947
1943
  (resolveConnection, rejectConnection) => {
1948
- var _a, _b;
1944
+ var _a2, _b;
1949
1945
  const optionalScopes = addValidAccounts(
1950
- getOptionalScopes((_a = options == null ? void 0 : options.scopes) != null ? _a : []),
1946
+ getOptionalScopes((_a2 = options == null ? void 0 : options.scopes) != null ? _a2 : []),
1951
1947
  getValidAccounts((_b = options == null ? void 0 : options.caipAccountIds) != null ? _b : [])
1952
1948
  );
1953
1949
  const sessionRequest = {
@@ -1959,12 +1955,18 @@ var MWPTransport = class {
1959
1955
  method: "wallet_createSession",
1960
1956
  params: sessionRequest
1961
1957
  };
1962
- this.dappClient.on("message", (message) => __async(this, null, function* () {
1958
+ initialConnectionMessageHandler = (message) => __async(this, null, function* () {
1963
1959
  if (typeof message === "object" && message !== null) {
1964
1960
  if ("data" in message) {
1965
1961
  const messagePayload = message.data;
1966
1962
  if (messagePayload.method === "wallet_createSession" || messagePayload.method === "wallet_sessionChanged") {
1967
1963
  if (messagePayload.error) {
1964
+ if (initialConnectionMessageHandler) {
1965
+ this.dappClient.off(
1966
+ "message",
1967
+ initialConnectionMessageHandler
1968
+ );
1969
+ }
1968
1970
  return rejectConnection(messagePayload.error);
1969
1971
  }
1970
1972
  yield this.storeWalletSession(
@@ -1976,14 +1978,23 @@ var MWPTransport = class {
1976
1978
  }
1977
1979
  }
1978
1980
  }
1979
- }));
1981
+ });
1982
+ this.dappClient.on("message", initialConnectionMessageHandler);
1980
1983
  dappClient.connect({
1981
1984
  mode: "trusted",
1982
1985
  initialPayload: {
1983
1986
  name: MULTICHAIN_PROVIDER_STREAM_NAME,
1984
1987
  data: request
1985
1988
  }
1986
- }).catch(rejectConnection);
1989
+ }).catch((error) => {
1990
+ if (initialConnectionMessageHandler) {
1991
+ this.dappClient.off(
1992
+ "message",
1993
+ initialConnectionMessageHandler
1994
+ );
1995
+ }
1996
+ rejectConnection(error);
1997
+ });
1987
1998
  }
1988
1999
  );
1989
2000
  }
@@ -1992,10 +2003,16 @@ var MWPTransport = class {
1992
2003
  }, this.options.connectionTimeout);
1993
2004
  connection.then(resolve).catch(reject);
1994
2005
  });
1995
- return connectionPromise.finally(() => {
2006
+ return connectionPromise.catch((error) => {
2007
+ throw error;
2008
+ }).finally(() => {
1996
2009
  if (timeout) {
1997
2010
  clearTimeout(timeout);
1998
2011
  }
2012
+ if (initialConnectionMessageHandler) {
2013
+ this.dappClient.off("message", initialConnectionMessageHandler);
2014
+ initialConnectionMessageHandler = void 0;
2015
+ }
1999
2016
  });
2000
2017
  });
2001
2018
  }
@@ -2058,7 +2075,7 @@ var MWPTransport = class {
2058
2075
  }
2059
2076
  getCachedResponse(request) {
2060
2077
  return __async(this, null, function* () {
2061
- var _a;
2078
+ var _a2;
2062
2079
  if (request.method === "wallet_getSession") {
2063
2080
  const walletGetSession = yield this.kvstore.get(SESSION_STORE_KEY);
2064
2081
  if (walletGetSession) {
@@ -2066,7 +2083,7 @@ var MWPTransport = class {
2066
2083
  return {
2067
2084
  id: request.id,
2068
2085
  jsonrpc: "2.0",
2069
- result: (_a = walletSession.params) != null ? _a : walletSession.result,
2086
+ result: (_a2 = walletSession.params) != null ? _a2 : walletSession.result,
2070
2087
  // "what?... why walletSession.params?.."
2071
2088
  method: request.method
2072
2089
  };
@@ -2130,10 +2147,10 @@ var MWPTransport = class {
2130
2147
  yield this.attemptResumeSession();
2131
2148
  }
2132
2149
  return new Promise((resolve, reject) => {
2133
- var _a;
2150
+ var _a2;
2134
2151
  const timeout = setTimeout(() => {
2135
2152
  this.rejectRequest(request.id, new import_multichain_api_client2.TransportTimeoutError());
2136
- }, (_a = options == null ? void 0 : options.timeout) != null ? _a : this.options.requestTimeout);
2153
+ }, (_a2 = options == null ? void 0 : options.timeout) != null ? _a2 : this.options.requestTimeout);
2137
2154
  this.pendingRequests.set(request.id, {
2138
2155
  request,
2139
2156
  method: request.method,
@@ -2157,6 +2174,19 @@ var MWPTransport = class {
2157
2174
  this.notificationCallbacks.delete(callback);
2158
2175
  };
2159
2176
  }
2177
+ getActiveSession() {
2178
+ return __async(this, null, function* () {
2179
+ const { kvstore } = this;
2180
+ const sessionStore = new import_mobile_wallet_protocol_core.SessionStore(kvstore);
2181
+ try {
2182
+ const [activeSession] = yield sessionStore.list();
2183
+ return activeSession;
2184
+ } catch (error) {
2185
+ logger("error getting active session", error);
2186
+ return void 0;
2187
+ }
2188
+ });
2189
+ }
2160
2190
  };
2161
2191
 
2162
2192
  // src/multichain/transports/mwp/KeyManager.ts
@@ -2189,73 +2219,74 @@ var keymanager = new KeyManager();
2189
2219
  // src/multichain/index.ts
2190
2220
  init_utils();
2191
2221
  var logger2 = createLogger("metamask-sdk:core");
2192
- var MultichainSDK = class _MultichainSDK extends MultichainCore {
2222
+ var _a, _provider, _transport2, _dappClient, _beforeUnloadListener, _listener, _sdkInfo, _MultichainSDK_instances, setupAnalytics_fn, onTransportNotification_fn, getStoredTransport_fn, setupTransport_fn, init_fn, createDappClient_fn, setupMWP_fn, onBeforeUnload_fn, createBeforeUnloadListener_fn, renderInstallModalAsync_fn, showInstallModal_fn, setupDefaultTransport_fn, deeplinkConnect_fn, handleConnection_fn;
2223
+ var _MultichainSDK = class _MultichainSDK extends MultichainCore {
2193
2224
  constructor(options) {
2194
- var _a, _b, _c, _d, _e, _f, _g;
2225
+ var _a2, _b, _c, _d, _e, _f;
2195
2226
  const withDappMetadata = setupDappMetadata(options);
2196
- const integrationType = ((_a = options.analytics) == null ? void 0 : _a.enabled) ? options.analytics.integrationType : "direct";
2227
+ const integrationType = (_b = (_a2 = options.analytics) == null ? void 0 : _a2.integrationType) != null ? _b : "direct";
2197
2228
  const allOptions = __spreadProps(__spreadValues({}, withDappMetadata), {
2198
2229
  ui: __spreadProps(__spreadValues({}, withDappMetadata.ui), {
2199
- preferExtension: (_b = withDappMetadata.ui.preferExtension) != null ? _b : true,
2200
- showInstallModal: (_c = withDappMetadata.ui.showInstallModal) != null ? _c : false,
2201
- headless: (_d = withDappMetadata.ui.headless) != null ? _d : false
2230
+ preferExtension: (_c = withDappMetadata.ui.preferExtension) != null ? _c : true,
2231
+ showInstallModal: (_d = withDappMetadata.ui.showInstallModal) != null ? _d : false,
2232
+ headless: (_e = withDappMetadata.ui.headless) != null ? _e : false
2202
2233
  }),
2203
- analytics: __spreadProps(__spreadValues({}, (_e = options.analytics) != null ? _e : {}), {
2204
- enabled: (_g = (_f = options.analytics) == null ? void 0 : _f.enabled) != null ? _g : true,
2234
+ analytics: __spreadProps(__spreadValues({}, (_f = options.analytics) != null ? _f : {}), {
2205
2235
  integrationType
2206
2236
  })
2207
2237
  });
2208
2238
  super(allOptions);
2209
- this.__provider = void 0;
2210
- this.__transport = void 0;
2211
- this.__dappClient = void 0;
2212
- this.__state = "pending";
2239
+ __privateAdd(this, _MultichainSDK_instances);
2240
+ __privateAdd(this, _provider);
2241
+ __privateAdd(this, _transport2);
2242
+ __privateAdd(this, _dappClient);
2243
+ __privateAdd(this, _beforeUnloadListener);
2244
+ this._state = "pending";
2245
+ __privateAdd(this, _listener);
2246
+ __privateAdd(this, _sdkInfo, `Sdk/Javascript SdkVersion/${getVersion()} Platform/${getPlatformType()} dApp/${(_a = this.options.dapp.url) != null ? _a : this.options.dapp.name} dAppTitle/${this.options.dapp.name}`);
2213
2247
  }
2214
2248
  get state() {
2215
- return this.__state;
2249
+ return this._state;
2216
2250
  }
2217
2251
  set state(value) {
2218
- var _a, _b;
2219
- this.__state = value;
2220
- (_b = (_a = this.options.transport) == null ? void 0 : _a.onNotification) == null ? void 0 : _b.call(_a, {
2252
+ var _a2, _b;
2253
+ this._state = value;
2254
+ (_b = (_a2 = this.options.transport) == null ? void 0 : _a2.onNotification) == null ? void 0 : _b.call(_a2, {
2221
2255
  method: "stateChanged",
2222
2256
  params: value
2223
2257
  });
2224
2258
  }
2225
2259
  get provider() {
2226
- if (!this.__provider && this.__transport) {
2227
- this.__provider = (0, import_multichain_api_client3.getMultichainClient)({ transport: this.__transport });
2228
- return this.__provider;
2260
+ if (!__privateGet(this, _provider) && __privateGet(this, _transport2)) {
2261
+ __privateSet(this, _provider, (0, import_multichain_api_client3.getMultichainClient)({ transport: __privateGet(this, _transport2) }));
2262
+ return __privateGet(this, _provider);
2229
2263
  }
2230
- if (!this.__provider) {
2264
+ if (!__privateGet(this, _provider)) {
2231
2265
  throw new Error("Provider not initialized, establish connection first");
2232
2266
  }
2233
- return this.__provider;
2267
+ return __privateGet(this, _provider);
2234
2268
  }
2235
2269
  get transport() {
2236
- if (!this.__transport) {
2270
+ if (!__privateGet(this, _transport2)) {
2237
2271
  throw new Error("Transport not initialized, establish connection first");
2238
2272
  }
2239
- return this.__transport;
2273
+ return __privateGet(this, _transport2);
2240
2274
  }
2241
2275
  get dappClient() {
2242
- if (!this.__dappClient) {
2276
+ if (!__privateGet(this, _dappClient)) {
2243
2277
  throw new Error("DappClient not initialized, establish connection first");
2244
2278
  }
2245
- return this.__dappClient;
2279
+ return __privateGet(this, _dappClient);
2246
2280
  }
2247
2281
  get storage() {
2248
2282
  return this.options.storage;
2249
2283
  }
2250
2284
  get transportType() {
2251
- return this.__transport instanceof MWPTransport ? "mwp" /* MWP */ : "browser" /* Browser */;
2252
- }
2253
- get sdkInfo() {
2254
- var _a;
2255
- return `Sdk/Javascript SdkVersion/${getVersion()} Platform/${getPlatformType()} dApp/${(_a = this.options.dapp.url) != null ? _a : this.options.dapp.name} dAppTitle/${this.options.dapp.name}`;
2285
+ return __privateGet(this, _transport2) instanceof MWPTransport ? "mwp" /* MWP */ : "browser" /* Browser */;
2256
2286
  }
2257
2287
  static create(options) {
2258
2288
  return __async(this, null, function* () {
2289
+ var _a2;
2259
2290
  const instance = new _MultichainSDK(options);
2260
2291
  const isEnabled2 = yield isEnabled(
2261
2292
  "metamask-sdk:core",
@@ -2264,353 +2295,16 @@ var MultichainSDK = class _MultichainSDK extends MultichainCore {
2264
2295
  if (isEnabled2) {
2265
2296
  enableDebug("metamask-sdk:core");
2266
2297
  }
2267
- yield instance.init();
2298
+ yield __privateMethod(_a2 = instance, _MultichainSDK_instances, init_fn).call(_a2);
2268
2299
  return instance;
2269
2300
  });
2270
2301
  }
2271
- setupAnalytics() {
2272
- return __async(this, null, function* () {
2273
- var _a, _b;
2274
- if (!((_a = this.options.analytics) == null ? void 0 : _a.enabled)) {
2275
- return;
2276
- }
2277
- const platform = getPlatformType();
2278
- const isBrowser = platform === "in-app-browser" /* MetaMaskMobileWebview */ || platform === "web-desktop" /* DesktopWeb */ || platform === "web-mobile" /* MobileWeb */;
2279
- const isReactNative2 = platform === "react-native" /* ReactNative */;
2280
- if (!isBrowser && !isReactNative2) {
2281
- return;
2282
- }
2283
- const version = getVersion();
2284
- const dappId = getDappId(this.options.dapp);
2285
- const anonId = yield this.storage.getAnonId();
2286
- const { integrationType } = (_b = this.options.analytics) != null ? _b : {
2287
- integrationType: ""
2288
- };
2289
- import_analytics4.analytics.setGlobalProperty("mmconnect_version", version);
2290
- import_analytics4.analytics.setGlobalProperty("dapp_id", dappId);
2291
- import_analytics4.analytics.setGlobalProperty("anon_id", anonId);
2292
- import_analytics4.analytics.setGlobalProperty("platform", platform);
2293
- import_analytics4.analytics.setGlobalProperty("integration_type", integrationType);
2294
- import_analytics4.analytics.enable();
2295
- });
2296
- }
2297
- onTransportNotification(payload) {
2298
- return __async(this, null, function* () {
2299
- var _a;
2300
- if (typeof payload === "object" && payload !== null && "method" in payload) {
2301
- this.emit(payload.method, (_a = payload.params) != null ? _a : payload.result);
2302
- }
2303
- });
2304
- }
2305
- getStoredTransport() {
2306
- return __async(this, null, function* () {
2307
- const transportType = yield this.storage.getTransport();
2308
- const hasExtensionInstalled = yield hasExtension();
2309
- if (transportType) {
2310
- if (transportType === "browser" /* Browser */) {
2311
- if (hasExtensionInstalled) {
2312
- const apiTransport = new DefaultTransport();
2313
- this.__transport = apiTransport;
2314
- this.listener = apiTransport.onNotification(
2315
- this.onTransportNotification.bind(this)
2316
- );
2317
- return apiTransport;
2318
- }
2319
- } else if (transportType === "mwp" /* MWP */) {
2320
- const { adapter: kvstore } = this.options.storage;
2321
- const dappClient = yield this.createDappClient();
2322
- const apiTransport = new MWPTransport(dappClient, kvstore);
2323
- this.__dappClient = dappClient;
2324
- this.__transport = apiTransport;
2325
- this.listener = apiTransport.onNotification(
2326
- this.onTransportNotification.bind(this)
2327
- );
2328
- return apiTransport;
2329
- }
2330
- yield this.storage.removeTransport();
2331
- }
2332
- return void 0;
2333
- });
2334
- }
2335
- setupTransport() {
2336
- return __async(this, null, function* () {
2337
- const transport = yield this.getStoredTransport();
2338
- if (transport) {
2339
- if (!this.transport.isConnected()) {
2340
- this.state = "connecting";
2341
- yield this.transport.connect();
2342
- }
2343
- this.state = "connected";
2344
- if (this.transport instanceof MWPTransport) {
2345
- yield this.storage.setTransport("mwp" /* MWP */);
2346
- } else {
2347
- yield this.storage.setTransport("browser" /* Browser */);
2348
- }
2349
- } else {
2350
- this.state = "loaded";
2351
- }
2352
- });
2353
- }
2354
- init() {
2355
- return __async(this, null, function* () {
2356
- var _a, _b;
2357
- try {
2358
- if (typeof window !== "undefined" && ((_a = window.mmsdk) == null ? void 0 : _a.isInitialized)) {
2359
- logger2("MetaMaskSDK: init already initialized");
2360
- } else {
2361
- yield this.setupAnalytics();
2362
- yield this.setupTransport();
2363
- if ((_b = this.options.analytics) == null ? void 0 : _b.enabled) {
2364
- try {
2365
- const baseProps = yield getBaseAnalyticsProperties(
2366
- this.options,
2367
- this.storage
2368
- );
2369
- import_analytics4.analytics.track("mmconnect_initialized", baseProps);
2370
- } catch (error) {
2371
- logger2("Error tracking initialized event", error);
2372
- }
2373
- }
2374
- if (typeof window !== "undefined") {
2375
- window.mmsdk = this;
2376
- }
2377
- }
2378
- } catch (error) {
2379
- yield this.storage.removeTransport();
2380
- this.state = "pending";
2381
- logger2("MetaMaskSDK error during initialization", error);
2382
- }
2383
- });
2384
- }
2385
- createDappClient() {
2386
- return __async(this, null, function* () {
2387
- const { adapter: kvstore } = this.options.storage;
2388
- const sessionstore = new import_mobile_wallet_protocol_core2.SessionStore(kvstore);
2389
- const websocket = (
2390
- // eslint-disable-next-line no-negated-condition
2391
- typeof window !== "undefined" ? WebSocket : (yield import("ws")).WebSocket
2392
- );
2393
- const transport = yield import_mobile_wallet_protocol_core2.WebSocketTransport.create({
2394
- url: MWP_RELAY_URL,
2395
- kvstore,
2396
- websocket
2397
- });
2398
- const dappClient = new import_mobile_wallet_protocol_dapp_client.DappClient({ transport, sessionstore, keymanager });
2399
- return dappClient;
2400
- });
2401
- }
2402
- setupMWP() {
2403
- return __async(this, null, function* () {
2404
- if (this.__transport instanceof MWPTransport) {
2405
- return;
2406
- }
2407
- const { adapter: kvstore } = this.options.storage;
2408
- const dappClient = yield this.createDappClient();
2409
- this.__dappClient = dappClient;
2410
- const apiTransport = new MWPTransport(dappClient, kvstore);
2411
- this.__transport = apiTransport;
2412
- this.listener = this.transport.onNotification(
2413
- this.onTransportNotification.bind(this)
2414
- );
2415
- yield this.storage.setTransport("mwp" /* MWP */);
2416
- });
2417
- }
2418
- onBeforeUnload() {
2419
- return __async(this, null, function* () {
2420
- var _a;
2421
- if ((_a = this.options.ui.factory.modal) == null ? void 0 : _a.isMounted) {
2422
- yield this.storage.removeTransport();
2423
- }
2424
- });
2425
- }
2426
- createBeforeUnloadListener() {
2427
- if (typeof window !== "undefined" && typeof window.addEventListener !== "undefined") {
2428
- window.addEventListener("beforeunload", this.onBeforeUnload.bind(this));
2429
- }
2430
- return () => {
2431
- if (typeof window !== "undefined" && typeof window.removeEventListener !== "undefined") {
2432
- window.removeEventListener(
2433
- "beforeunload",
2434
- this.onBeforeUnload.bind(this)
2435
- );
2436
- }
2437
- };
2438
- }
2439
- showInstallModal(desktopPreferred, scopes, caipAccountIds) {
2440
- return __async(this, null, function* () {
2441
- var _a;
2442
- (_a = this.__beforeUnloadListener) != null ? _a : this.__beforeUnloadListener = this.createBeforeUnloadListener();
2443
- return new Promise((resolve, reject) => {
2444
- this.options.ui.factory.renderInstallModal(
2445
- desktopPreferred,
2446
- () => __async(this, null, function* () {
2447
- if (this.dappClient.state === "CONNECTED" || this.dappClient.state === "CONNECTING") {
2448
- yield this.dappClient.disconnect();
2449
- }
2450
- return new Promise((resolveConnectionRequest) => {
2451
- this.dappClient.on(
2452
- "session_request",
2453
- (sessionRequest) => {
2454
- resolveConnectionRequest({
2455
- sessionRequest,
2456
- metadata: {
2457
- dapp: this.options.dapp,
2458
- sdk: {
2459
- version: getVersion(),
2460
- platform: getPlatformType()
2461
- }
2462
- }
2463
- });
2464
- }
2465
- );
2466
- this.transport.connect({ scopes, caipAccountIds }).then(() => {
2467
- var _a2;
2468
- this.options.ui.factory.unload();
2469
- (_a2 = this.options.ui.factory.modal) == null ? void 0 : _a2.unmount();
2470
- this.state = "connected";
2471
- return this.storage.setTransport("mwp" /* MWP */);
2472
- }).catch((error) => {
2473
- if (error instanceof import_mobile_wallet_protocol_core2.ProtocolError) {
2474
- if (error.code !== import_mobile_wallet_protocol_core2.ErrorCode.REQUEST_EXPIRED) {
2475
- this.state = "disconnected";
2476
- reject(error);
2477
- }
2478
- } else {
2479
- this.state = "disconnected";
2480
- reject(error);
2481
- }
2482
- });
2483
- });
2484
- }),
2485
- (error) => __async(this, null, function* () {
2486
- if (!error) {
2487
- yield this.storage.setTransport("mwp" /* MWP */);
2488
- resolve();
2489
- } else {
2490
- yield this.storage.removeTransport();
2491
- reject(error);
2492
- }
2493
- })
2494
- );
2495
- });
2496
- });
2497
- }
2498
- setupDefaultTransport() {
2499
- return __async(this, null, function* () {
2500
- this.state = "connecting";
2501
- yield this.storage.setTransport("browser" /* Browser */);
2502
- const transport = new DefaultTransport();
2503
- this.listener = transport.onNotification(
2504
- this.onTransportNotification.bind(this)
2505
- );
2506
- this.__transport = transport;
2507
- return transport;
2508
- });
2509
- }
2510
- deeplinkConnect(scopes, caipAccountIds) {
2511
- return __async(this, null, function* () {
2512
- return new Promise((resolve, reject) => __async(this, null, function* () {
2513
- this.dappClient.on("message", (payload) => {
2514
- var _a, _b, _c;
2515
- const data = payload.data;
2516
- if (typeof data === "object" && data !== null) {
2517
- if ("method" in data && data.method === "wallet_createSession") {
2518
- if (data.error) {
2519
- this.state = "loaded";
2520
- return reject(data.error);
2521
- }
2522
- const session = (_a = data.params) != null ? _a : data.result;
2523
- if (session) {
2524
- (_c = (_b = this.options.transport) == null ? void 0 : _b.onNotification) == null ? void 0 : _c.call(_b, payload.data);
2525
- this.emit("wallet_sessionChanged", session);
2526
- }
2527
- }
2528
- }
2529
- });
2530
- let timeout;
2531
- if (!this.transport.isConnected()) {
2532
- this.dappClient.once(
2533
- "session_request",
2534
- (sessionRequest) => {
2535
- var _a;
2536
- const connectionRequest = {
2537
- sessionRequest,
2538
- metadata: {
2539
- dapp: this.options.dapp,
2540
- sdk: { version: getVersion(), platform: getPlatformType() }
2541
- }
2542
- };
2543
- const deeplink = this.options.ui.factory.createDeeplink(connectionRequest);
2544
- const universalLink = this.options.ui.factory.createUniversalLink(connectionRequest);
2545
- if ((_a = this.options.mobile) == null ? void 0 : _a.preferredOpenLink) {
2546
- this.options.mobile.preferredOpenLink(deeplink, "_self");
2547
- } else {
2548
- openDeeplink(this.options, deeplink, universalLink);
2549
- }
2550
- }
2551
- );
2552
- }
2553
- this.transport.connect({ scopes, caipAccountIds }).then(resolve).catch((error) => {
2554
- this.storage.removeTransport();
2555
- reject(error);
2556
- }).finally(() => {
2557
- if (timeout) {
2558
- clearTimeout(timeout);
2559
- }
2560
- });
2561
- }));
2562
- });
2563
- }
2564
- handleConnection(promise, scopes, transportType) {
2565
- return __async(this, null, function* () {
2566
- this.state = "connecting";
2567
- return promise.then(() => __async(this, null, function* () {
2568
- var _a;
2569
- this.state = "connected";
2570
- if ((_a = this.options.analytics) == null ? void 0 : _a.enabled) {
2571
- try {
2572
- const baseProps = yield getBaseAnalyticsProperties(
2573
- this.options,
2574
- this.storage
2575
- );
2576
- import_analytics4.analytics.track("mmconnect_connection_established", __spreadProps(__spreadValues({}, baseProps), {
2577
- transport_type: transportType,
2578
- user_permissioned_chains: scopes
2579
- }));
2580
- } catch (error) {
2581
- logger2("Error tracking connection_established event", error);
2582
- }
2583
- }
2584
- })).catch((error) => __async(this, null, function* () {
2585
- var _a;
2586
- this.state = "disconnected";
2587
- if ((_a = this.options.analytics) == null ? void 0 : _a.enabled) {
2588
- try {
2589
- const baseProps = yield getBaseAnalyticsProperties(
2590
- this.options,
2591
- this.storage
2592
- );
2593
- const isRejection = isRejectionError(error);
2594
- if (isRejection) {
2595
- import_analytics4.analytics.track("mmconnect_connection_rejected", __spreadProps(__spreadValues({}, baseProps), {
2596
- transport_type: transportType
2597
- }));
2598
- } else {
2599
- import_analytics4.analytics.track("mmconnect_connection_failed", __spreadProps(__spreadValues({}, baseProps), {
2600
- transport_type: transportType
2601
- }));
2602
- }
2603
- } catch (e) {
2604
- logger2("Error tracking connection failed/rejected event", error);
2605
- }
2606
- }
2607
- return Promise.reject(error);
2608
- }));
2609
- });
2610
- }
2611
2302
  connect(scopes, caipAccountIds, forceRequest) {
2612
2303
  return __async(this, null, function* () {
2613
- var _a, _b;
2304
+ var _a2;
2305
+ if (this.state !== "connected") {
2306
+ yield this.disconnect();
2307
+ }
2614
2308
  const { ui } = this.options;
2615
2309
  const platformType = getPlatformType();
2616
2310
  const isWeb = platformType === "in-app-browser" /* MetaMaskMobileWebview */ || platformType === "web-desktop" /* DesktopWeb */;
@@ -2623,96 +2317,72 @@ var MultichainSDK = class _MultichainSDK extends MultichainCore {
2623
2317
  } else {
2624
2318
  transportType = "mwp" /* MWP */;
2625
2319
  }
2626
- if ((_a = this.options.analytics) == null ? void 0 : _a.enabled) {
2627
- try {
2628
- const baseProps = yield getBaseAnalyticsProperties(
2629
- this.options,
2630
- this.storage
2631
- );
2632
- const dappConfiguredChains = Object.keys(
2633
- this.options.api.supportedNetworks
2634
- );
2635
- import_analytics4.analytics.track("mmconnect_connection_initiated", __spreadProps(__spreadValues({}, baseProps), {
2636
- transport_type: transportType,
2637
- dapp_configured_chains: dappConfiguredChains,
2638
- dapp_requested_chains: scopes
2639
- }));
2640
- } catch (error) {
2641
- logger2("Error tracking connection_initiated event", error);
2642
- }
2643
- }
2644
- if (((_b = this.__transport) == null ? void 0 : _b.isConnected()) && !secure) {
2645
- return this.handleConnection(
2646
- this.__transport.connect({ scopes, caipAccountIds, forceRequest }).then(() => {
2647
- if (this.__transport instanceof MWPTransport) {
2648
- return this.storage.setTransport("mwp" /* MWP */);
2649
- } else {
2650
- return this.storage.setTransport("browser" /* Browser */);
2651
- }
2652
- }),
2653
- scopes,
2654
- transportType
2320
+ try {
2321
+ const baseProps = yield getBaseAnalyticsProperties(
2322
+ this.options,
2323
+ this.storage
2655
2324
  );
2325
+ const dappConfiguredChains = Object.keys(
2326
+ this.options.api.supportedNetworks
2327
+ );
2328
+ import_analytics4.analytics.track("mmconnect_connection_initiated", __spreadProps(__spreadValues({}, baseProps), {
2329
+ transport_type: transportType,
2330
+ dapp_configured_chains: dappConfiguredChains,
2331
+ dapp_requested_chains: scopes
2332
+ }));
2333
+ } catch (error) {
2334
+ logger2("Error tracking connection_initiated event", error);
2335
+ }
2336
+ if (((_a2 = __privateGet(this, _transport2)) == null ? void 0 : _a2.isConnected()) && !secure) {
2337
+ return __privateMethod(this, _MultichainSDK_instances, handleConnection_fn).call(this, __privateGet(this, _transport2).connect({ scopes, caipAccountIds, forceRequest }).then(() => __async(this, null, function* () {
2338
+ if (__privateGet(this, _transport2) instanceof MWPTransport) {
2339
+ return this.storage.setTransport("mwp" /* MWP */);
2340
+ }
2341
+ return this.storage.setTransport("browser" /* Browser */);
2342
+ })), scopes, transportType);
2656
2343
  }
2657
2344
  if (platformType === "in-app-browser" /* MetaMaskMobileWebview */) {
2658
- const defaultTransport = yield this.setupDefaultTransport();
2659
- return this.handleConnection(
2660
- defaultTransport.connect({ scopes, caipAccountIds, forceRequest }),
2661
- scopes,
2662
- transportType
2663
- );
2345
+ const defaultTransport = yield __privateMethod(this, _MultichainSDK_instances, setupDefaultTransport_fn).call(this);
2346
+ return __privateMethod(this, _MultichainSDK_instances, handleConnection_fn).call(this, defaultTransport.connect({ scopes, caipAccountIds, forceRequest }), scopes, transportType);
2664
2347
  }
2665
2348
  if (isWeb && hasExtensionInstalled && preferExtension) {
2666
- const defaultTransport = yield this.setupDefaultTransport();
2667
- return this.handleConnection(
2668
- defaultTransport.connect({ scopes, caipAccountIds, forceRequest }),
2669
- scopes,
2670
- transportType
2671
- );
2349
+ const defaultTransport = yield __privateMethod(this, _MultichainSDK_instances, setupDefaultTransport_fn).call(this);
2350
+ return __privateMethod(this, _MultichainSDK_instances, handleConnection_fn).call(this, defaultTransport.connect({ scopes, caipAccountIds, forceRequest }), scopes, transportType);
2672
2351
  }
2673
- yield this.setupMWP();
2352
+ yield __privateMethod(this, _MultichainSDK_instances, setupMWP_fn).call(this);
2674
2353
  const shouldShowInstallModal = hasExtensionInstalled ? showInstallModal : !preferExtension || showInstallModal;
2675
2354
  if (secure && !shouldShowInstallModal) {
2676
- return this.handleConnection(
2677
- this.deeplinkConnect(scopes, caipAccountIds),
2678
- scopes,
2679
- transportType
2680
- );
2355
+ return __privateMethod(this, _MultichainSDK_instances, handleConnection_fn).call(this, __privateMethod(this, _MultichainSDK_instances, deeplinkConnect_fn).call(this, scopes, caipAccountIds), scopes, transportType);
2681
2356
  }
2682
- return this.handleConnection(
2683
- this.showInstallModal(shouldShowInstallModal, scopes, caipAccountIds),
2684
- scopes,
2685
- transportType
2686
- );
2357
+ return __privateMethod(this, _MultichainSDK_instances, handleConnection_fn).call(this, __privateMethod(this, _MultichainSDK_instances, showInstallModal_fn).call(this, shouldShowInstallModal, scopes, caipAccountIds), scopes, transportType);
2687
2358
  });
2688
2359
  }
2689
2360
  emit(event, args) {
2690
- var _a, _b;
2691
- (_b = (_a = this.options.transport) == null ? void 0 : _a.onNotification) == null ? void 0 : _b.call(_a, { method: event, params: args });
2361
+ var _a2, _b;
2362
+ (_b = (_a2 = this.options.transport) == null ? void 0 : _a2.onNotification) == null ? void 0 : _b.call(_a2, { method: event, params: args });
2692
2363
  super.emit(event, args);
2693
2364
  }
2694
2365
  disconnect() {
2695
2366
  return __async(this, null, function* () {
2696
- var _a, _b, _c;
2697
- (_a = this.listener) == null ? void 0 : _a.call(this);
2698
- (_b = this.__beforeUnloadListener) == null ? void 0 : _b.call(this);
2699
- yield (_c = this.__transport) == null ? void 0 : _c.disconnect();
2367
+ var _a2, _b, _c;
2368
+ yield (_a2 = __privateGet(this, _listener)) == null ? void 0 : _a2.call(this);
2369
+ (_b = __privateGet(this, _beforeUnloadListener)) == null ? void 0 : _b.call(this);
2370
+ yield (_c = __privateGet(this, _transport2)) == null ? void 0 : _c.disconnect();
2700
2371
  yield this.storage.removeTransport();
2701
- this.emit("wallet_sessionChanged", void 0);
2702
2372
  this.emit("stateChanged", "disconnected");
2703
- this.listener = void 0;
2704
- this.__beforeUnloadListener = void 0;
2705
- this.__transport = void 0;
2706
- this.__provider = void 0;
2707
- this.__dappClient = void 0;
2373
+ __privateSet(this, _listener, void 0);
2374
+ __privateSet(this, _beforeUnloadListener, void 0);
2375
+ __privateSet(this, _transport2, void 0);
2376
+ __privateSet(this, _provider, void 0);
2377
+ __privateSet(this, _dappClient, void 0);
2708
2378
  });
2709
2379
  }
2710
2380
  invokeMethod(request) {
2711
2381
  return __async(this, null, function* () {
2712
- var _a;
2713
- const { sdkInfo, transport, options } = this;
2714
- (_a = this.__provider) != null ? _a : this.__provider = (0, import_multichain_api_client3.getMultichainClient)({ transport });
2715
- const rpcClient = new RpcClient(options, sdkInfo);
2382
+ var _a2;
2383
+ const { transport, options } = this;
2384
+ (_a2 = __privateGet(this, _provider)) != null ? _a2 : __privateSet(this, _provider, (0, import_multichain_api_client3.getMultichainClient)({ transport }));
2385
+ const rpcClient = new RpcClient(options, __privateGet(this, _sdkInfo));
2716
2386
  const requestRouter = new RequestRouter(transport, rpcClient, options);
2717
2387
  return requestRouter.invokeMethod(request);
2718
2388
  });
@@ -2724,20 +2394,381 @@ var MultichainSDK = class _MultichainSDK extends MultichainCore {
2724
2394
  const secure = isSecure();
2725
2395
  const shouldOpenDeeplink = secure && !showInstallModal;
2726
2396
  if (shouldOpenDeeplink) {
2727
- setTimeout(() => {
2397
+ setTimeout(() => __async(this, null, function* () {
2398
+ const session = yield this.transport.getActiveSession();
2399
+ if (!session) {
2400
+ throw new Error("No active session found");
2401
+ }
2402
+ const url = `${METAMASK_DEEPLINK_BASE}/mwp?id=${encodeURIComponent(session.id)}`;
2728
2403
  if (mobile == null ? void 0 : mobile.preferredOpenLink) {
2729
- mobile.preferredOpenLink(METAMASK_DEEPLINK_BASE, "_self");
2404
+ mobile.preferredOpenLink(url, "_self");
2730
2405
  } else {
2731
- openDeeplink(
2406
+ openDeeplink(this.options, url, METAMASK_CONNECT_BASE_URL);
2407
+ }
2408
+ }), 10);
2409
+ }
2410
+ }
2411
+ };
2412
+ _provider = new WeakMap();
2413
+ _transport2 = new WeakMap();
2414
+ _dappClient = new WeakMap();
2415
+ _beforeUnloadListener = new WeakMap();
2416
+ _listener = new WeakMap();
2417
+ _sdkInfo = new WeakMap();
2418
+ _MultichainSDK_instances = new WeakSet();
2419
+ setupAnalytics_fn = function() {
2420
+ return __async(this, null, function* () {
2421
+ var _a2;
2422
+ const platform = getPlatformType();
2423
+ const isBrowser = platform === "in-app-browser" /* MetaMaskMobileWebview */ || platform === "web-desktop" /* DesktopWeb */ || platform === "web-mobile" /* MobileWeb */;
2424
+ const isReactNative2 = platform === "react-native" /* ReactNative */;
2425
+ if (!isBrowser && !isReactNative2) {
2426
+ return;
2427
+ }
2428
+ const version = getVersion();
2429
+ const dappId = getDappId(this.options.dapp);
2430
+ const anonId = yield this.storage.getAnonId();
2431
+ const { integrationType } = (_a2 = this.options.analytics) != null ? _a2 : {
2432
+ integrationType: ""
2433
+ };
2434
+ import_analytics4.analytics.setGlobalProperty("mmconnect_version", version);
2435
+ import_analytics4.analytics.setGlobalProperty("dapp_id", dappId);
2436
+ import_analytics4.analytics.setGlobalProperty("anon_id", anonId);
2437
+ import_analytics4.analytics.setGlobalProperty("platform", platform);
2438
+ import_analytics4.analytics.setGlobalProperty("integration_type", integrationType);
2439
+ import_analytics4.analytics.enable();
2440
+ });
2441
+ };
2442
+ onTransportNotification_fn = function(payload) {
2443
+ return __async(this, null, function* () {
2444
+ var _a2;
2445
+ if (typeof payload === "object" && payload !== null && "method" in payload) {
2446
+ this.emit(payload.method, (_a2 = payload.params) != null ? _a2 : payload.result);
2447
+ }
2448
+ });
2449
+ };
2450
+ getStoredTransport_fn = function() {
2451
+ return __async(this, null, function* () {
2452
+ const transportType = yield this.storage.getTransport();
2453
+ const hasExtensionInstalled = yield hasExtension();
2454
+ if (transportType) {
2455
+ if (transportType === "browser" /* Browser */) {
2456
+ if (hasExtensionInstalled) {
2457
+ const apiTransport = new DefaultTransport();
2458
+ __privateSet(this, _transport2, apiTransport);
2459
+ __privateSet(this, _listener, apiTransport.onNotification(
2460
+ __privateMethod(this, _MultichainSDK_instances, onTransportNotification_fn).bind(this)
2461
+ ));
2462
+ return apiTransport;
2463
+ }
2464
+ } else if (transportType === "mwp" /* MWP */) {
2465
+ const { adapter: kvstore } = this.options.storage;
2466
+ const dappClient = yield __privateMethod(this, _MultichainSDK_instances, createDappClient_fn).call(this);
2467
+ const apiTransport = new MWPTransport(dappClient, kvstore);
2468
+ __privateSet(this, _dappClient, dappClient);
2469
+ __privateSet(this, _transport2, apiTransport);
2470
+ __privateSet(this, _listener, apiTransport.onNotification(
2471
+ __privateMethod(this, _MultichainSDK_instances, onTransportNotification_fn).bind(this)
2472
+ ));
2473
+ return apiTransport;
2474
+ }
2475
+ yield this.storage.removeTransport();
2476
+ }
2477
+ return void 0;
2478
+ });
2479
+ };
2480
+ setupTransport_fn = function() {
2481
+ return __async(this, null, function* () {
2482
+ const transport = yield __privateMethod(this, _MultichainSDK_instances, getStoredTransport_fn).call(this);
2483
+ if (transport) {
2484
+ if (!this.transport.isConnected()) {
2485
+ this.state = "connecting";
2486
+ yield this.transport.connect();
2487
+ }
2488
+ this.state = "connected";
2489
+ if (this.transport instanceof MWPTransport) {
2490
+ yield this.storage.setTransport("mwp" /* MWP */);
2491
+ } else {
2492
+ yield this.storage.setTransport("browser" /* Browser */);
2493
+ }
2494
+ } else {
2495
+ this.state = "loaded";
2496
+ }
2497
+ });
2498
+ };
2499
+ init_fn = function() {
2500
+ return __async(this, null, function* () {
2501
+ var _a2;
2502
+ try {
2503
+ if (typeof window !== "undefined" && ((_a2 = window.mmsdk) == null ? void 0 : _a2.isInitialized)) {
2504
+ logger2("MetaMaskSDK: init already initialized");
2505
+ } else {
2506
+ yield __privateMethod(this, _MultichainSDK_instances, setupAnalytics_fn).call(this);
2507
+ yield __privateMethod(this, _MultichainSDK_instances, setupTransport_fn).call(this);
2508
+ try {
2509
+ const baseProps = yield getBaseAnalyticsProperties(
2732
2510
  this.options,
2733
- METAMASK_DEEPLINK_BASE,
2734
- METAMASK_CONNECT_BASE_URL
2511
+ this.storage
2735
2512
  );
2513
+ import_analytics4.analytics.track("mmconnect_initialized", baseProps);
2514
+ } catch (error) {
2515
+ logger2("Error tracking initialized event", error);
2516
+ }
2517
+ if (typeof window !== "undefined") {
2518
+ window.mmsdk = this;
2736
2519
  }
2737
- }, 10);
2520
+ }
2521
+ } catch (error) {
2522
+ yield this.storage.removeTransport();
2523
+ this.state = "pending";
2524
+ logger2("MetaMaskSDK error during initialization", error);
2738
2525
  }
2739
- }
2526
+ });
2527
+ };
2528
+ createDappClient_fn = function() {
2529
+ return __async(this, null, function* () {
2530
+ const { adapter: kvstore } = this.options.storage;
2531
+ const sessionstore = new import_mobile_wallet_protocol_core2.SessionStore(kvstore);
2532
+ const websocket = (
2533
+ // eslint-disable-next-line no-negated-condition
2534
+ typeof window !== "undefined" ? WebSocket : (yield import("ws")).WebSocket
2535
+ );
2536
+ const transport = yield import_mobile_wallet_protocol_core2.WebSocketTransport.create({
2537
+ url: MWP_RELAY_URL,
2538
+ kvstore,
2539
+ websocket
2540
+ });
2541
+ const dappClient = new import_mobile_wallet_protocol_dapp_client.DappClient({ transport, sessionstore, keymanager });
2542
+ return dappClient;
2543
+ });
2544
+ };
2545
+ setupMWP_fn = function() {
2546
+ return __async(this, null, function* () {
2547
+ if (__privateGet(this, _transport2) instanceof MWPTransport) {
2548
+ return;
2549
+ }
2550
+ const { adapter: kvstore } = this.options.storage;
2551
+ const dappClient = yield __privateMethod(this, _MultichainSDK_instances, createDappClient_fn).call(this);
2552
+ __privateSet(this, _dappClient, dappClient);
2553
+ const apiTransport = new MWPTransport(dappClient, kvstore);
2554
+ __privateSet(this, _transport2, apiTransport);
2555
+ __privateSet(this, _listener, this.transport.onNotification(
2556
+ __privateMethod(this, _MultichainSDK_instances, onTransportNotification_fn).bind(this)
2557
+ ));
2558
+ yield this.storage.setTransport("mwp" /* MWP */);
2559
+ });
2560
+ };
2561
+ onBeforeUnload_fn = function() {
2562
+ return __async(this, null, function* () {
2563
+ var _a2;
2564
+ if ((_a2 = this.options.ui.factory.modal) == null ? void 0 : _a2.isMounted) {
2565
+ yield this.storage.removeTransport();
2566
+ }
2567
+ });
2568
+ };
2569
+ createBeforeUnloadListener_fn = function() {
2570
+ if (typeof window !== "undefined" && typeof window.addEventListener !== "undefined") {
2571
+ window.addEventListener("beforeunload", __privateMethod(this, _MultichainSDK_instances, onBeforeUnload_fn).bind(this));
2572
+ }
2573
+ return () => {
2574
+ if (typeof window !== "undefined" && typeof window.removeEventListener !== "undefined") {
2575
+ window.removeEventListener(
2576
+ "beforeunload",
2577
+ __privateMethod(this, _MultichainSDK_instances, onBeforeUnload_fn).bind(this)
2578
+ );
2579
+ }
2580
+ };
2581
+ };
2582
+ renderInstallModalAsync_fn = function(desktopPreferred, scopes, caipAccountIds) {
2583
+ return __async(this, null, function* () {
2584
+ return new Promise((resolve, reject) => {
2585
+ this.options.ui.factory.renderInstallModal(
2586
+ desktopPreferred,
2587
+ () => __async(this, null, function* () {
2588
+ if (this.dappClient.state === "CONNECTED" || this.dappClient.state === "CONNECTING") {
2589
+ yield this.dappClient.disconnect();
2590
+ }
2591
+ return new Promise((_resolve) => {
2592
+ this.dappClient.on(
2593
+ "session_request",
2594
+ (sessionRequest) => {
2595
+ _resolve({
2596
+ sessionRequest,
2597
+ metadata: {
2598
+ dapp: this.options.dapp,
2599
+ sdk: {
2600
+ version: getVersion(),
2601
+ platform: getPlatformType()
2602
+ }
2603
+ }
2604
+ });
2605
+ }
2606
+ );
2607
+ (() => __async(this, null, function* () {
2608
+ var _a2;
2609
+ try {
2610
+ yield this.transport.connect({ scopes, caipAccountIds });
2611
+ yield this.options.ui.factory.unload();
2612
+ (_a2 = this.options.ui.factory.modal) == null ? void 0 : _a2.unmount();
2613
+ this.state = "connected";
2614
+ yield this.storage.setTransport("mwp" /* MWP */);
2615
+ } catch (error) {
2616
+ if (error instanceof import_mobile_wallet_protocol_core2.ProtocolError) {
2617
+ if (error.code !== import_mobile_wallet_protocol_core2.ErrorCode.REQUEST_EXPIRED) {
2618
+ this.state = "disconnected";
2619
+ reject(error);
2620
+ }
2621
+ } else {
2622
+ this.state = "disconnected";
2623
+ reject(
2624
+ error instanceof Error ? error : new Error(String(error))
2625
+ );
2626
+ }
2627
+ }
2628
+ }))().catch(() => {
2629
+ });
2630
+ });
2631
+ }),
2632
+ (error) => __async(this, null, function* () {
2633
+ if (error) {
2634
+ yield this.storage.removeTransport();
2635
+ reject(error);
2636
+ } else {
2637
+ yield this.storage.setTransport("mwp" /* MWP */);
2638
+ resolve();
2639
+ }
2640
+ })
2641
+ ).catch((error) => {
2642
+ reject(error instanceof Error ? error : new Error(String(error)));
2643
+ });
2644
+ });
2645
+ });
2646
+ };
2647
+ showInstallModal_fn = function(desktopPreferred, scopes, caipAccountIds) {
2648
+ return __async(this, null, function* () {
2649
+ var _a2;
2650
+ (_a2 = __privateGet(this, _beforeUnloadListener)) != null ? _a2 : __privateSet(this, _beforeUnloadListener, __privateMethod(this, _MultichainSDK_instances, createBeforeUnloadListener_fn).call(this));
2651
+ yield __privateMethod(this, _MultichainSDK_instances, renderInstallModalAsync_fn).call(this, desktopPreferred, scopes, caipAccountIds);
2652
+ });
2653
+ };
2654
+ setupDefaultTransport_fn = function() {
2655
+ return __async(this, null, function* () {
2656
+ this.state = "connecting";
2657
+ yield this.storage.setTransport("browser" /* Browser */);
2658
+ const transport = new DefaultTransport();
2659
+ __privateSet(this, _listener, transport.onNotification(
2660
+ __privateMethod(this, _MultichainSDK_instances, onTransportNotification_fn).bind(this)
2661
+ ));
2662
+ __privateSet(this, _transport2, transport);
2663
+ return transport;
2664
+ });
2665
+ };
2666
+ deeplinkConnect_fn = function(scopes, caipAccountIds) {
2667
+ return __async(this, null, function* () {
2668
+ return new Promise((resolve, reject) => {
2669
+ const dappClientMessageHandler = (payload) => {
2670
+ var _a2;
2671
+ if (typeof payload !== "object" || payload === null || !("data" in payload)) {
2672
+ return;
2673
+ }
2674
+ const data = payload.data;
2675
+ if (typeof data === "object" && data !== null) {
2676
+ if (data.error) {
2677
+ this.dappClient.off("message", dappClientMessageHandler);
2678
+ reject(data.error);
2679
+ }
2680
+ if ((_a2 = data == null ? void 0 : data.result) == null ? void 0 : _a2.sessionScopes) {
2681
+ this.dappClient.off("message", dappClientMessageHandler);
2682
+ }
2683
+ }
2684
+ };
2685
+ this.dappClient.on("message", dappClientMessageHandler);
2686
+ let timeout;
2687
+ if (this.transport.isConnected()) {
2688
+ timeout = setTimeout(() => {
2689
+ this.openDeeplinkIfNeeded();
2690
+ }, 250);
2691
+ } else {
2692
+ this.dappClient.once(
2693
+ "session_request",
2694
+ (sessionRequest) => {
2695
+ var _a2;
2696
+ const connectionRequest = {
2697
+ sessionRequest,
2698
+ metadata: {
2699
+ dapp: this.options.dapp,
2700
+ sdk: { version: getVersion(), platform: getPlatformType() }
2701
+ }
2702
+ };
2703
+ const deeplink = this.options.ui.factory.createConnectionDeeplink(
2704
+ connectionRequest
2705
+ );
2706
+ const universalLink = this.options.ui.factory.createConnectionUniversalLink(
2707
+ connectionRequest
2708
+ );
2709
+ if ((_a2 = this.options.mobile) == null ? void 0 : _a2.preferredOpenLink) {
2710
+ this.options.mobile.preferredOpenLink(deeplink, "_self");
2711
+ } else {
2712
+ openDeeplink(this.options, deeplink, universalLink);
2713
+ }
2714
+ }
2715
+ );
2716
+ }
2717
+ return this.transport.connect({ scopes, caipAccountIds }).then(resolve).catch((error) => __async(this, null, function* () {
2718
+ yield this.storage.removeTransport();
2719
+ this.dappClient.off("message", dappClientMessageHandler);
2720
+ reject(error instanceof Error ? error : new Error(String(error)));
2721
+ })).finally(() => {
2722
+ if (timeout) {
2723
+ clearTimeout(timeout);
2724
+ }
2725
+ });
2726
+ });
2727
+ });
2728
+ };
2729
+ handleConnection_fn = function(promise, scopes, transportType) {
2730
+ return __async(this, null, function* () {
2731
+ this.state = "connecting";
2732
+ return promise.then(() => __async(this, null, function* () {
2733
+ this.state = "connected";
2734
+ try {
2735
+ const baseProps = yield getBaseAnalyticsProperties(
2736
+ this.options,
2737
+ this.storage
2738
+ );
2739
+ import_analytics4.analytics.track("mmconnect_connection_established", __spreadProps(__spreadValues({}, baseProps), {
2740
+ transport_type: transportType,
2741
+ user_permissioned_chains: scopes
2742
+ }));
2743
+ } catch (error) {
2744
+ logger2("Error tracking connection_established event", error);
2745
+ }
2746
+ return void 0;
2747
+ })).catch((error) => __async(this, null, function* () {
2748
+ this.state = "disconnected";
2749
+ try {
2750
+ const baseProps = yield getBaseAnalyticsProperties(
2751
+ this.options,
2752
+ this.storage
2753
+ );
2754
+ const isRejection = isRejectionError(error);
2755
+ if (isRejection) {
2756
+ import_analytics4.analytics.track("mmconnect_connection_rejected", __spreadProps(__spreadValues({}, baseProps), {
2757
+ transport_type: transportType
2758
+ }));
2759
+ } else {
2760
+ import_analytics4.analytics.track("mmconnect_connection_failed", __spreadProps(__spreadValues({}, baseProps), {
2761
+ transport_type: transportType
2762
+ }));
2763
+ }
2764
+ } catch (e) {
2765
+ logger2("Error tracking connection failed/rejected event", error);
2766
+ }
2767
+ throw error;
2768
+ }));
2769
+ });
2740
2770
  };
2771
+ var MultichainSDK = _MultichainSDK;
2741
2772
 
2742
2773
  // src/store/index.ts
2743
2774
  var uuid = __toESM(require("uuid"));
@@ -2921,50 +2952,24 @@ var Store = class extends StoreClient {
2921
2952
  // src/ui/index.ts
2922
2953
  var import_onboarding = __toESM(require("@metamask/onboarding"));
2923
2954
  init_domain();
2955
+ init_utils();
2924
2956
 
2925
- // src/ui/qr.ts
2926
- var encodeQRImpl = null;
2927
- function preloadQR() {
2957
+ // src/ui/preload.web.ts
2958
+ function preload() {
2928
2959
  return __async(this, null, function* () {
2929
- if (encodeQRImpl) {
2960
+ if (typeof document === "undefined") {
2930
2961
  return;
2931
2962
  }
2932
- const mod = yield import("@paulmillr/qr");
2933
- encodeQRImpl = mod.default;
2963
+ try {
2964
+ const { defineCustomElements } = yield import("@metamask/multichain-ui/loader");
2965
+ yield defineCustomElements();
2966
+ } catch (error) {
2967
+ console.error("Failed to load customElements:", error);
2968
+ }
2934
2969
  });
2935
2970
  }
2936
2971
 
2937
2972
  // src/ui/index.ts
2938
- init_utils();
2939
- var __instance;
2940
- function preload() {
2941
- return __async(this, null, function* () {
2942
- if (false) {
2943
- __instance != null ? __instance : __instance = yield null.then((loader) => __async(null, null, function* () {
2944
- if (typeof (loader == null ? void 0 : loader.defineCustomElements) === "function") {
2945
- loader.defineCustomElements();
2946
- }
2947
- return Promise.resolve(loader);
2948
- })).catch((error) => __async(null, null, function* () {
2949
- console.error(`Gracefully Failed to load modal customElements:`, error);
2950
- return Promise.resolve(void 0);
2951
- }));
2952
- } else {
2953
- const dynamicImport = (0, eval)("import");
2954
- __instance != null ? __instance : __instance = yield dynamicImport(
2955
- "@metamask/multichain-ui/dist/loader/index.js"
2956
- ).then((loader) => __async(null, null, function* () {
2957
- if (typeof (loader == null ? void 0 : loader.defineCustomElements) === "function") {
2958
- loader.defineCustomElements();
2959
- }
2960
- return Promise.resolve(loader);
2961
- })).catch((error) => __async(null, null, function* () {
2962
- console.error(`Gracefully Failed to load modal customElements:`, error);
2963
- return Promise.resolve(void 0);
2964
- }));
2965
- }
2966
- });
2967
- }
2968
2973
  var ModalFactory = class {
2969
2974
  /**
2970
2975
  * Creates a new modal factory instance.
@@ -2987,8 +2992,8 @@ var ModalFactory = class {
2987
2992
  }
2988
2993
  unload(error) {
2989
2994
  return __async(this, null, function* () {
2990
- var _a, _b;
2991
- (_a = this.modal) == null ? void 0 : _a.unmount();
2995
+ var _a2, _b;
2996
+ (_a2 = this.modal) == null ? void 0 : _a2.unmount();
2992
2997
  yield (_b = this.successCallback) == null ? void 0 : _b.call(this, error);
2993
2998
  });
2994
2999
  }
@@ -3026,16 +3031,16 @@ var ModalFactory = class {
3026
3031
  }
3027
3032
  return container;
3028
3033
  }
3029
- createDeeplink(connectionRequest) {
3034
+ createConnectionDeeplink(connectionRequest) {
3030
3035
  if (!connectionRequest) {
3031
- throw new Error("createDeeplink can only be called with a connection request");
3036
+ throw new Error("createConnectionDeeplink can only be called with a connection request");
3032
3037
  }
3033
3038
  const json = JSON.stringify(connectionRequest);
3034
3039
  const compressed = compressString(json);
3035
3040
  const urlEncoded = encodeURIComponent(compressed);
3036
3041
  return `${METAMASK_DEEPLINK_BASE}/mwp?p=${urlEncoded}&c=1`;
3037
3042
  }
3038
- createUniversalLink(connectionRequest) {
3043
+ createConnectionUniversalLink(connectionRequest) {
3039
3044
  if (!connectionRequest) {
3040
3045
  return `${METAMASK_CONNECT_BASE_URL}`;
3041
3046
  }
@@ -3056,13 +3061,13 @@ var ModalFactory = class {
3056
3061
  }
3057
3062
  renderInstallModal(showInstallModal, createConnectionRequest, successCallback) {
3058
3063
  return __async(this, null, function* () {
3059
- var _a;
3060
- (_a = this.modal) == null ? void 0 : _a.unmount();
3061
- yield Promise.all([preload(), preloadQR()]);
3064
+ var _a2;
3065
+ (_a2 = this.modal) == null ? void 0 : _a2.unmount();
3066
+ yield preload();
3062
3067
  this.successCallback = successCallback;
3063
3068
  const parentElement = this.getMountedContainer();
3064
3069
  const connectionRequest = yield createConnectionRequest();
3065
- const qrCodeLink = this.createDeeplink(connectionRequest);
3070
+ const qrCodeLink = this.createConnectionDeeplink(connectionRequest);
3066
3071
  const modal = new this.options.InstallModal({
3067
3072
  expiresIn: (connectionRequest.sessionRequest.expiresAt - Date.now()) / 1e3,
3068
3073
  connectionRequest,
@@ -3071,7 +3076,7 @@ var ModalFactory = class {
3071
3076
  link: qrCodeLink,
3072
3077
  sdkVersion: getVersion(),
3073
3078
  generateQRCode: (request) => __async(this, null, function* () {
3074
- return this.createDeeplink(request);
3079
+ return this.createConnectionDeeplink(request);
3075
3080
  }),
3076
3081
  onClose: this.onCloseModal.bind(this),
3077
3082
  startDesktopOnboarding: this.onStartDesktopOnboarding.bind(this),
@@ -3083,9 +3088,9 @@ var ModalFactory = class {
3083
3088
  }
3084
3089
  renderOTPCodeModal(createOTPCode, successCallback, updateOTPCode) {
3085
3090
  return __async(this, null, function* () {
3086
- var _a;
3087
- (_a = this.modal) == null ? void 0 : _a.unmount();
3088
- yield Promise.all([preload(), preloadQR()]);
3091
+ var _a2;
3092
+ (_a2 = this.modal) == null ? void 0 : _a2.unmount();
3093
+ yield preload();
3089
3094
  this.successCallback = successCallback;
3090
3095
  const container = this.getMountedContainer();
3091
3096
  const otpCode = yield createOTPCode();