@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,
@@ -877,30 +877,6 @@ var init_domain = __esm({
877
877
  }
878
878
  });
879
879
 
880
- // src/ui/qr.ts
881
- function preloadQR() {
882
- return __async(this, null, function* () {
883
- if (encodeQRImpl) {
884
- return;
885
- }
886
- const mod = yield import("@paulmillr/qr");
887
- encodeQRImpl = mod.default;
888
- });
889
- }
890
- function encodeQRSync(input) {
891
- if (!encodeQRImpl) {
892
- throw new Error("QR module not preloaded. Call preloadQR() first.");
893
- }
894
- return encodeQRImpl(input, "ascii");
895
- }
896
- var encodeQRImpl;
897
- var init_qr = __esm({
898
- "src/ui/qr.ts"() {
899
- "use strict";
900
- encodeQRImpl = null;
901
- }
902
- });
903
-
904
880
  // src/ui/modals/base/utils.ts
905
881
  function formatRemainingTime(milliseconds) {
906
882
  if (milliseconds <= 0) return "EXPIRED";
@@ -1019,12 +995,12 @@ var init_AbstractInstallModal = __esm({
1019
995
  });
1020
996
 
1021
997
  // src/ui/modals/node/install.ts
1022
- var logger4, InstallModal;
998
+ var import_qr, logger4, InstallModal;
1023
999
  var init_install = __esm({
1024
1000
  "src/ui/modals/node/install.ts"() {
1025
1001
  "use strict";
1026
1002
  init_domain();
1027
- init_qr();
1003
+ import_qr = __toESM(require("@paulmillr/qr"));
1028
1004
  init_AbstractInstallModal();
1029
1005
  init_utils3();
1030
1006
  logger4 = createLogger("metamask-sdk:ui");
@@ -1032,7 +1008,7 @@ var init_install = __esm({
1032
1008
  displayQRWithCountdown(qrCodeLink, expiresInMs) {
1033
1009
  const isExpired = expiresInMs <= 0;
1034
1010
  const formattedTime = formatRemainingTime(expiresInMs);
1035
- const qrCode = encodeQRSync(qrCodeLink);
1011
+ const qrCode = (0, import_qr.default)(qrCodeLink, "ascii");
1036
1012
  console.clear();
1037
1013
  console.log(qrCode);
1038
1014
  if (isExpired) {
@@ -1140,8 +1116,8 @@ var init_node2 = __esm({
1140
1116
  }
1141
1117
  get(key) {
1142
1118
  return __async(this, null, function* () {
1143
- var _a;
1144
- return (_a = this.storage.get(key)) != null ? _a : null;
1119
+ var _a2;
1120
+ return (_a2 = this.storage.get(key)) != null ? _a2 : null;
1145
1121
  });
1146
1122
  }
1147
1123
  set(key, value) {
@@ -1244,8 +1220,8 @@ var RpcClient = class {
1244
1220
  });
1245
1221
  }
1246
1222
  getRpcEndpoint(scope) {
1247
- var _a, _b, _c;
1248
- const supportedNetworks = (_c = (_b = (_a = this.config) == null ? void 0 : _a.api) == null ? void 0 : _b.supportedNetworks) != null ? _c : {};
1223
+ var _a2, _b, _c;
1224
+ const supportedNetworks = (_c = (_b = (_a2 = this.config) == null ? void 0 : _a2.api) == null ? void 0 : _b.supportedNetworks) != null ? _c : {};
1249
1225
  const rpcEndpoint = supportedNetworks[scope];
1250
1226
  if (!rpcEndpoint) {
1251
1227
  throw new MissingRpcEndpointErr(`No RPC endpoint found for scope ${scope}`);
@@ -1349,13 +1325,18 @@ var RequestRouter = class {
1349
1325
  const secure = isSecure();
1350
1326
  const shouldOpenDeeplink = secure && !showInstallModal;
1351
1327
  if (shouldOpenDeeplink) {
1352
- setTimeout(() => {
1328
+ setTimeout(() => __async(this, null, function* () {
1329
+ const session = yield this.transport.getActiveSession();
1330
+ if (!session) {
1331
+ throw new Error("No active session found");
1332
+ }
1333
+ const url = `${METAMASK_DEEPLINK_BASE}/mwp?id=${encodeURIComponent(session.id)}`;
1353
1334
  if (mobile == null ? void 0 : mobile.preferredOpenLink) {
1354
- mobile.preferredOpenLink(METAMASK_DEEPLINK_BASE, "_self");
1335
+ mobile.preferredOpenLink(url, "_self");
1355
1336
  } else {
1356
- openDeeplink(this.config, METAMASK_DEEPLINK_BASE, METAMASK_CONNECT_BASE_URL);
1337
+ openDeeplink(this.config, url, METAMASK_CONNECT_BASE_URL);
1357
1338
  }
1358
- }, 10);
1339
+ }), 10);
1359
1340
  }
1360
1341
  const response = yield request;
1361
1342
  if (response.error) {
@@ -1395,24 +1376,17 @@ var RequestRouter = class {
1395
1376
  _RequestRouter_instances = new WeakSet();
1396
1377
  withAnalyticsTracking_fn = function(options, execute) {
1397
1378
  return __async(this, null, function* () {
1398
- var _a, _b, _c;
1399
- if ((_a = this.config.analytics) == null ? void 0 : _a.enabled) {
1400
- yield __privateMethod(this, _RequestRouter_instances, trackWalletActionRequested_fn).call(this, options);
1401
- }
1379
+ yield __privateMethod(this, _RequestRouter_instances, trackWalletActionRequested_fn).call(this, options);
1402
1380
  try {
1403
1381
  const result = yield execute();
1404
- if ((_b = this.config.analytics) == null ? void 0 : _b.enabled) {
1405
- yield __privateMethod(this, _RequestRouter_instances, trackWalletActionSucceeded_fn).call(this, options);
1406
- }
1382
+ yield __privateMethod(this, _RequestRouter_instances, trackWalletActionSucceeded_fn).call(this, options);
1407
1383
  return result;
1408
1384
  } catch (error) {
1409
- if ((_c = this.config.analytics) == null ? void 0 : _c.enabled) {
1410
- const isRejection = isRejectionError(error);
1411
- if (isRejection) {
1412
- yield __privateMethod(this, _RequestRouter_instances, trackWalletActionRejected_fn).call(this, options);
1413
- } else {
1414
- yield __privateMethod(this, _RequestRouter_instances, trackWalletActionFailed_fn).call(this, options);
1415
- }
1385
+ const isRejection = isRejectionError(error);
1386
+ if (isRejection) {
1387
+ yield __privateMethod(this, _RequestRouter_instances, trackWalletActionRejected_fn).call(this, options);
1388
+ } else {
1389
+ yield __privateMethod(this, _RequestRouter_instances, trackWalletActionFailed_fn).call(this, options);
1416
1390
  }
1417
1391
  throw new RPCInvokeMethodErr(error.message);
1418
1392
  }
@@ -1472,11 +1446,11 @@ var DefaultTransport = class {
1472
1446
  id: requestId
1473
1447
  }, payload);
1474
1448
  return new Promise((resolve, reject) => {
1475
- var _a;
1449
+ var _a2;
1476
1450
  const timeout = setTimeout(() => {
1477
1451
  __privateGet(this, _pendingRequests).delete(requestId);
1478
1452
  reject(new Error("Request timeout"));
1479
- }, (_a = options == null ? void 0 : options.timeout) != null ? _a : __privateGet(this, _defaultRequestOptions).timeout);
1453
+ }, (_a2 = options == null ? void 0 : options.timeout) != null ? _a2 : __privateGet(this, _defaultRequestOptions).timeout);
1480
1454
  __privateGet(this, _pendingRequests).set(requestId, {
1481
1455
  resolve: (response) => {
1482
1456
  resolve(response);
@@ -1500,7 +1474,7 @@ var DefaultTransport = class {
1500
1474
  }
1501
1475
  connect(options) {
1502
1476
  return __async(this, null, function* () {
1503
- var _a, _b, _c, _d, _e, _f, _g;
1477
+ var _a2, _b, _c, _d, _e, _f, _g;
1504
1478
  __privateMethod(this, _DefaultTransport_instances, setupMessageListener_fn).call(this);
1505
1479
  yield __privateGet(this, _transport).connect();
1506
1480
  const sessionRequest = yield this.request(
@@ -1513,7 +1487,7 @@ var DefaultTransport = class {
1513
1487
  let walletSession = sessionRequest.result;
1514
1488
  if (walletSession && options && !options.forceRequest) {
1515
1489
  const currentScopes = Object.keys(
1516
- (_a = walletSession == null ? void 0 : walletSession.sessionScopes) != null ? _a : {}
1490
+ (_a2 = walletSession == null ? void 0 : walletSession.sessionScopes) != null ? _a2 : {}
1517
1491
  );
1518
1492
  const proposedScopes = (_b = options == null ? void 0 : options.scopes) != null ? _b : [];
1519
1493
  const proposedCaipAccountIds = (_c = options == null ? void 0 : options.caipAccountIds) != null ? _c : [];
@@ -1602,6 +1576,9 @@ var DefaultTransport = class {
1602
1576
  __privateGet(this, _notificationCallbacks).delete(callback);
1603
1577
  };
1604
1578
  }
1579
+ getActiveSession() {
1580
+ throw new Error("getActiveSession is purposely not implemented for the DefaultTransport");
1581
+ }
1605
1582
  };
1606
1583
  _notificationCallbacks = new WeakMap();
1607
1584
  _transport = new WeakMap();
@@ -1624,16 +1601,16 @@ notifyCallbacks_fn = function(data) {
1624
1601
  }
1625
1602
  };
1626
1603
  isMetamaskProviderEvent_fn = function(event) {
1627
- var _a, _b;
1628
- 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
1604
+ var _a2, _b;
1605
+ 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
1629
1606
  event.origin === location.origin;
1630
1607
  };
1631
1608
  handleResponse_fn = function(event) {
1632
- var _a, _b;
1609
+ var _a2, _b;
1633
1610
  if (!__privateMethod(this, _DefaultTransport_instances, isMetamaskProviderEvent_fn).call(this, event)) {
1634
1611
  return;
1635
1612
  }
1636
- const responseData = (_b = (_a = event == null ? void 0 : event.data) == null ? void 0 : _a.data) == null ? void 0 : _b.data;
1613
+ const responseData = (_b = (_a2 = event == null ? void 0 : event.data) == null ? void 0 : _a2.data) == null ? void 0 : _b.data;
1637
1614
  if (typeof responseData === "object" && responseData !== null && "method" in responseData) {
1638
1615
  return;
1639
1616
  }
@@ -1655,11 +1632,11 @@ handleResponse_fn = function(event) {
1655
1632
  }
1656
1633
  };
1657
1634
  handleNotification_fn = function(event) {
1658
- var _a, _b;
1635
+ var _a2, _b;
1659
1636
  if (!__privateMethod(this, _DefaultTransport_instances, isMetamaskProviderEvent_fn).call(this, event)) {
1660
1637
  return;
1661
1638
  }
1662
- const responseData = (_b = (_a = event == null ? void 0 : event.data) == null ? void 0 : _a.data) == null ? void 0 : _b.data;
1639
+ const responseData = (_b = (_a2 = event == null ? void 0 : event.data) == null ? void 0 : _a2.data) == null ? void 0 : _b.data;
1663
1640
  if (typeof responseData === "object" && responseData.method === "metamask_chainChanged" || responseData.method === "metamask_accountsChanged") {
1664
1641
  __privateMethod(this, _DefaultTransport_instances, notifyCallbacks_fn).call(this, responseData);
1665
1642
  }
@@ -1785,7 +1762,7 @@ var MWPTransport = class {
1785
1762
  }
1786
1763
  onResumeSuccess(resumeResolve, resumeReject, options) {
1787
1764
  return __async(this, null, function* () {
1788
- var _a, _b, _c, _d, _e, _f, _g;
1765
+ var _a2, _b, _c, _d, _e, _f, _g;
1789
1766
  try {
1790
1767
  const sessionRequest = yield this.request({
1791
1768
  method: "wallet_getSession"
@@ -1796,7 +1773,7 @@ var MWPTransport = class {
1796
1773
  let walletSession = sessionRequest.result;
1797
1774
  if (walletSession && options) {
1798
1775
  const currentScopes = Object.keys(
1799
- (_a = walletSession == null ? void 0 : walletSession.sessionScopes) != null ? _a : {}
1776
+ (_a2 = walletSession == null ? void 0 : walletSession.sessionScopes) != null ? _a2 : {}
1800
1777
  );
1801
1778
  const proposedScopes = (_b = options == null ? void 0 : options.scopes) != null ? _b : [];
1802
1779
  const proposedCaipAccountIds = (_c = options == null ? void 0 : options.caipAccountIds) != null ? _c : [];
@@ -1861,10 +1838,10 @@ var MWPTransport = class {
1861
1838
  return cachedWalletSession;
1862
1839
  }
1863
1840
  return new Promise((resolve, reject) => {
1864
- var _a;
1841
+ var _a2;
1865
1842
  const timeout = setTimeout(() => {
1866
1843
  this.rejectRequest(request.id, new import_multichain_api_client2.TransportTimeoutError());
1867
- }, (_a = options == null ? void 0 : options.timeout) != null ? _a : this.options.requestTimeout);
1844
+ }, (_a2 = options == null ? void 0 : options.timeout) != null ? _a2 : this.options.requestTimeout);
1868
1845
  this.pendingRequests.set(request.id, {
1869
1846
  request,
1870
1847
  method: request.method,
@@ -1884,38 +1861,33 @@ var MWPTransport = class {
1884
1861
  }
1885
1862
  connect(options) {
1886
1863
  return __async(this, null, function* () {
1887
- const { dappClient, kvstore } = this;
1888
- const sessionStore = new import_mobile_wallet_protocol_core.SessionStore(kvstore);
1889
- let session;
1890
- try {
1891
- const [activeSession] = yield sessionStore.list();
1892
- if (activeSession) {
1893
- logger("active session found", activeSession);
1894
- session = activeSession;
1895
- }
1896
- } catch (e) {
1864
+ const { dappClient } = this;
1865
+ const session = yield this.getActiveSession();
1866
+ if (session) {
1867
+ logger("active session found", session);
1897
1868
  }
1898
1869
  let timeout;
1870
+ let initialConnectionMessageHandler;
1899
1871
  const connectionPromise = new Promise((resolve, reject) => {
1900
1872
  let connection;
1901
1873
  if (session) {
1902
1874
  connection = new Promise((resumeResolve, resumeReject) => {
1903
- var _a;
1875
+ var _a2;
1904
1876
  if (this.dappClient.state === "CONNECTED") {
1905
1877
  this.onResumeSuccess(resumeResolve, resumeReject, options);
1906
1878
  } else {
1907
1879
  this.dappClient.once("connected", () => __async(this, null, function* () {
1908
1880
  this.onResumeSuccess(resumeResolve, resumeReject, options);
1909
1881
  }));
1910
- dappClient.resume((_a = session == null ? void 0 : session.id) != null ? _a : "");
1882
+ dappClient.resume((_a2 = session == null ? void 0 : session.id) != null ? _a2 : "");
1911
1883
  }
1912
1884
  });
1913
1885
  } else {
1914
1886
  connection = new Promise(
1915
1887
  (resolveConnection, rejectConnection) => {
1916
- var _a, _b;
1888
+ var _a2, _b;
1917
1889
  const optionalScopes = addValidAccounts(
1918
- getOptionalScopes((_a = options == null ? void 0 : options.scopes) != null ? _a : []),
1890
+ getOptionalScopes((_a2 = options == null ? void 0 : options.scopes) != null ? _a2 : []),
1919
1891
  getValidAccounts((_b = options == null ? void 0 : options.caipAccountIds) != null ? _b : [])
1920
1892
  );
1921
1893
  const sessionRequest = {
@@ -1927,12 +1899,18 @@ var MWPTransport = class {
1927
1899
  method: "wallet_createSession",
1928
1900
  params: sessionRequest
1929
1901
  };
1930
- this.dappClient.on("message", (message) => __async(this, null, function* () {
1902
+ initialConnectionMessageHandler = (message) => __async(this, null, function* () {
1931
1903
  if (typeof message === "object" && message !== null) {
1932
1904
  if ("data" in message) {
1933
1905
  const messagePayload = message.data;
1934
1906
  if (messagePayload.method === "wallet_createSession" || messagePayload.method === "wallet_sessionChanged") {
1935
1907
  if (messagePayload.error) {
1908
+ if (initialConnectionMessageHandler) {
1909
+ this.dappClient.off(
1910
+ "message",
1911
+ initialConnectionMessageHandler
1912
+ );
1913
+ }
1936
1914
  return rejectConnection(messagePayload.error);
1937
1915
  }
1938
1916
  yield this.storeWalletSession(
@@ -1944,14 +1922,23 @@ var MWPTransport = class {
1944
1922
  }
1945
1923
  }
1946
1924
  }
1947
- }));
1925
+ });
1926
+ this.dappClient.on("message", initialConnectionMessageHandler);
1948
1927
  dappClient.connect({
1949
1928
  mode: "trusted",
1950
1929
  initialPayload: {
1951
1930
  name: MULTICHAIN_PROVIDER_STREAM_NAME,
1952
1931
  data: request
1953
1932
  }
1954
- }).catch(rejectConnection);
1933
+ }).catch((error) => {
1934
+ if (initialConnectionMessageHandler) {
1935
+ this.dappClient.off(
1936
+ "message",
1937
+ initialConnectionMessageHandler
1938
+ );
1939
+ }
1940
+ rejectConnection(error);
1941
+ });
1955
1942
  }
1956
1943
  );
1957
1944
  }
@@ -1960,10 +1947,16 @@ var MWPTransport = class {
1960
1947
  }, this.options.connectionTimeout);
1961
1948
  connection.then(resolve).catch(reject);
1962
1949
  });
1963
- return connectionPromise.finally(() => {
1950
+ return connectionPromise.catch((error) => {
1951
+ throw error;
1952
+ }).finally(() => {
1964
1953
  if (timeout) {
1965
1954
  clearTimeout(timeout);
1966
1955
  }
1956
+ if (initialConnectionMessageHandler) {
1957
+ this.dappClient.off("message", initialConnectionMessageHandler);
1958
+ initialConnectionMessageHandler = void 0;
1959
+ }
1967
1960
  });
1968
1961
  });
1969
1962
  }
@@ -2026,7 +2019,7 @@ var MWPTransport = class {
2026
2019
  }
2027
2020
  getCachedResponse(request) {
2028
2021
  return __async(this, null, function* () {
2029
- var _a;
2022
+ var _a2;
2030
2023
  if (request.method === "wallet_getSession") {
2031
2024
  const walletGetSession = yield this.kvstore.get(SESSION_STORE_KEY);
2032
2025
  if (walletGetSession) {
@@ -2034,7 +2027,7 @@ var MWPTransport = class {
2034
2027
  return {
2035
2028
  id: request.id,
2036
2029
  jsonrpc: "2.0",
2037
- result: (_a = walletSession.params) != null ? _a : walletSession.result,
2030
+ result: (_a2 = walletSession.params) != null ? _a2 : walletSession.result,
2038
2031
  // "what?... why walletSession.params?.."
2039
2032
  method: request.method
2040
2033
  };
@@ -2098,10 +2091,10 @@ var MWPTransport = class {
2098
2091
  yield this.attemptResumeSession();
2099
2092
  }
2100
2093
  return new Promise((resolve, reject) => {
2101
- var _a;
2094
+ var _a2;
2102
2095
  const timeout = setTimeout(() => {
2103
2096
  this.rejectRequest(request.id, new import_multichain_api_client2.TransportTimeoutError());
2104
- }, (_a = options == null ? void 0 : options.timeout) != null ? _a : this.options.requestTimeout);
2097
+ }, (_a2 = options == null ? void 0 : options.timeout) != null ? _a2 : this.options.requestTimeout);
2105
2098
  this.pendingRequests.set(request.id, {
2106
2099
  request,
2107
2100
  method: request.method,
@@ -2125,6 +2118,19 @@ var MWPTransport = class {
2125
2118
  this.notificationCallbacks.delete(callback);
2126
2119
  };
2127
2120
  }
2121
+ getActiveSession() {
2122
+ return __async(this, null, function* () {
2123
+ const { kvstore } = this;
2124
+ const sessionStore = new import_mobile_wallet_protocol_core.SessionStore(kvstore);
2125
+ try {
2126
+ const [activeSession] = yield sessionStore.list();
2127
+ return activeSession;
2128
+ } catch (error) {
2129
+ logger("error getting active session", error);
2130
+ return void 0;
2131
+ }
2132
+ });
2133
+ }
2128
2134
  };
2129
2135
 
2130
2136
  // src/multichain/transports/mwp/KeyManager.ts
@@ -2157,73 +2163,74 @@ var keymanager = new KeyManager();
2157
2163
  // src/multichain/index.ts
2158
2164
  init_utils();
2159
2165
  var logger2 = createLogger("metamask-sdk:core");
2160
- var MultichainSDK = class _MultichainSDK extends MultichainCore {
2166
+ 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;
2167
+ var _MultichainSDK = class _MultichainSDK extends MultichainCore {
2161
2168
  constructor(options) {
2162
- var _a, _b, _c, _d, _e, _f, _g;
2169
+ var _a2, _b, _c, _d, _e, _f;
2163
2170
  const withDappMetadata = setupDappMetadata(options);
2164
- const integrationType = ((_a = options.analytics) == null ? void 0 : _a.enabled) ? options.analytics.integrationType : "direct";
2171
+ const integrationType = (_b = (_a2 = options.analytics) == null ? void 0 : _a2.integrationType) != null ? _b : "direct";
2165
2172
  const allOptions = __spreadProps(__spreadValues({}, withDappMetadata), {
2166
2173
  ui: __spreadProps(__spreadValues({}, withDappMetadata.ui), {
2167
- preferExtension: (_b = withDappMetadata.ui.preferExtension) != null ? _b : true,
2168
- showInstallModal: (_c = withDappMetadata.ui.showInstallModal) != null ? _c : false,
2169
- headless: (_d = withDappMetadata.ui.headless) != null ? _d : false
2174
+ preferExtension: (_c = withDappMetadata.ui.preferExtension) != null ? _c : true,
2175
+ showInstallModal: (_d = withDappMetadata.ui.showInstallModal) != null ? _d : false,
2176
+ headless: (_e = withDappMetadata.ui.headless) != null ? _e : false
2170
2177
  }),
2171
- analytics: __spreadProps(__spreadValues({}, (_e = options.analytics) != null ? _e : {}), {
2172
- enabled: (_g = (_f = options.analytics) == null ? void 0 : _f.enabled) != null ? _g : true,
2178
+ analytics: __spreadProps(__spreadValues({}, (_f = options.analytics) != null ? _f : {}), {
2173
2179
  integrationType
2174
2180
  })
2175
2181
  });
2176
2182
  super(allOptions);
2177
- this.__provider = void 0;
2178
- this.__transport = void 0;
2179
- this.__dappClient = void 0;
2180
- this.__state = "pending";
2183
+ __privateAdd(this, _MultichainSDK_instances);
2184
+ __privateAdd(this, _provider);
2185
+ __privateAdd(this, _transport2);
2186
+ __privateAdd(this, _dappClient);
2187
+ __privateAdd(this, _beforeUnloadListener);
2188
+ this._state = "pending";
2189
+ __privateAdd(this, _listener);
2190
+ __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}`);
2181
2191
  }
2182
2192
  get state() {
2183
- return this.__state;
2193
+ return this._state;
2184
2194
  }
2185
2195
  set state(value) {
2186
- var _a, _b;
2187
- this.__state = value;
2188
- (_b = (_a = this.options.transport) == null ? void 0 : _a.onNotification) == null ? void 0 : _b.call(_a, {
2196
+ var _a2, _b;
2197
+ this._state = value;
2198
+ (_b = (_a2 = this.options.transport) == null ? void 0 : _a2.onNotification) == null ? void 0 : _b.call(_a2, {
2189
2199
  method: "stateChanged",
2190
2200
  params: value
2191
2201
  });
2192
2202
  }
2193
2203
  get provider() {
2194
- if (!this.__provider && this.__transport) {
2195
- this.__provider = (0, import_multichain_api_client3.getMultichainClient)({ transport: this.__transport });
2196
- return this.__provider;
2204
+ if (!__privateGet(this, _provider) && __privateGet(this, _transport2)) {
2205
+ __privateSet(this, _provider, (0, import_multichain_api_client3.getMultichainClient)({ transport: __privateGet(this, _transport2) }));
2206
+ return __privateGet(this, _provider);
2197
2207
  }
2198
- if (!this.__provider) {
2208
+ if (!__privateGet(this, _provider)) {
2199
2209
  throw new Error("Provider not initialized, establish connection first");
2200
2210
  }
2201
- return this.__provider;
2211
+ return __privateGet(this, _provider);
2202
2212
  }
2203
2213
  get transport() {
2204
- if (!this.__transport) {
2214
+ if (!__privateGet(this, _transport2)) {
2205
2215
  throw new Error("Transport not initialized, establish connection first");
2206
2216
  }
2207
- return this.__transport;
2217
+ return __privateGet(this, _transport2);
2208
2218
  }
2209
2219
  get dappClient() {
2210
- if (!this.__dappClient) {
2220
+ if (!__privateGet(this, _dappClient)) {
2211
2221
  throw new Error("DappClient not initialized, establish connection first");
2212
2222
  }
2213
- return this.__dappClient;
2223
+ return __privateGet(this, _dappClient);
2214
2224
  }
2215
2225
  get storage() {
2216
2226
  return this.options.storage;
2217
2227
  }
2218
2228
  get transportType() {
2219
- return this.__transport instanceof MWPTransport ? "mwp" /* MWP */ : "browser" /* Browser */;
2220
- }
2221
- get sdkInfo() {
2222
- var _a;
2223
- return `Sdk/Javascript SdkVersion/${getVersion()} Platform/${getPlatformType()} dApp/${(_a = this.options.dapp.url) != null ? _a : this.options.dapp.name} dAppTitle/${this.options.dapp.name}`;
2229
+ return __privateGet(this, _transport2) instanceof MWPTransport ? "mwp" /* MWP */ : "browser" /* Browser */;
2224
2230
  }
2225
2231
  static create(options) {
2226
2232
  return __async(this, null, function* () {
2233
+ var _a2;
2227
2234
  const instance = new _MultichainSDK(options);
2228
2235
  const isEnabled2 = yield isEnabled(
2229
2236
  "metamask-sdk:core",
@@ -2232,353 +2239,16 @@ var MultichainSDK = class _MultichainSDK extends MultichainCore {
2232
2239
  if (isEnabled2) {
2233
2240
  enableDebug("metamask-sdk:core");
2234
2241
  }
2235
- yield instance.init();
2242
+ yield __privateMethod(_a2 = instance, _MultichainSDK_instances, init_fn).call(_a2);
2236
2243
  return instance;
2237
2244
  });
2238
2245
  }
2239
- setupAnalytics() {
2240
- return __async(this, null, function* () {
2241
- var _a, _b;
2242
- if (!((_a = this.options.analytics) == null ? void 0 : _a.enabled)) {
2243
- return;
2244
- }
2245
- const platform = getPlatformType();
2246
- const isBrowser = platform === "in-app-browser" /* MetaMaskMobileWebview */ || platform === "web-desktop" /* DesktopWeb */ || platform === "web-mobile" /* MobileWeb */;
2247
- const isReactNative2 = platform === "react-native" /* ReactNative */;
2248
- if (!isBrowser && !isReactNative2) {
2249
- return;
2250
- }
2251
- const version = getVersion();
2252
- const dappId = getDappId(this.options.dapp);
2253
- const anonId = yield this.storage.getAnonId();
2254
- const { integrationType } = (_b = this.options.analytics) != null ? _b : {
2255
- integrationType: ""
2256
- };
2257
- import_analytics4.analytics.setGlobalProperty("mmconnect_version", version);
2258
- import_analytics4.analytics.setGlobalProperty("dapp_id", dappId);
2259
- import_analytics4.analytics.setGlobalProperty("anon_id", anonId);
2260
- import_analytics4.analytics.setGlobalProperty("platform", platform);
2261
- import_analytics4.analytics.setGlobalProperty("integration_type", integrationType);
2262
- import_analytics4.analytics.enable();
2263
- });
2264
- }
2265
- onTransportNotification(payload) {
2266
- return __async(this, null, function* () {
2267
- var _a;
2268
- if (typeof payload === "object" && payload !== null && "method" in payload) {
2269
- this.emit(payload.method, (_a = payload.params) != null ? _a : payload.result);
2270
- }
2271
- });
2272
- }
2273
- getStoredTransport() {
2274
- return __async(this, null, function* () {
2275
- const transportType = yield this.storage.getTransport();
2276
- const hasExtensionInstalled = yield hasExtension();
2277
- if (transportType) {
2278
- if (transportType === "browser" /* Browser */) {
2279
- if (hasExtensionInstalled) {
2280
- const apiTransport = new DefaultTransport();
2281
- this.__transport = apiTransport;
2282
- this.listener = apiTransport.onNotification(
2283
- this.onTransportNotification.bind(this)
2284
- );
2285
- return apiTransport;
2286
- }
2287
- } else if (transportType === "mwp" /* MWP */) {
2288
- const { adapter: kvstore } = this.options.storage;
2289
- const dappClient = yield this.createDappClient();
2290
- const apiTransport = new MWPTransport(dappClient, kvstore);
2291
- this.__dappClient = dappClient;
2292
- this.__transport = apiTransport;
2293
- this.listener = apiTransport.onNotification(
2294
- this.onTransportNotification.bind(this)
2295
- );
2296
- return apiTransport;
2297
- }
2298
- yield this.storage.removeTransport();
2299
- }
2300
- return void 0;
2301
- });
2302
- }
2303
- setupTransport() {
2304
- return __async(this, null, function* () {
2305
- const transport = yield this.getStoredTransport();
2306
- if (transport) {
2307
- if (!this.transport.isConnected()) {
2308
- this.state = "connecting";
2309
- yield this.transport.connect();
2310
- }
2311
- this.state = "connected";
2312
- if (this.transport instanceof MWPTransport) {
2313
- yield this.storage.setTransport("mwp" /* MWP */);
2314
- } else {
2315
- yield this.storage.setTransport("browser" /* Browser */);
2316
- }
2317
- } else {
2318
- this.state = "loaded";
2319
- }
2320
- });
2321
- }
2322
- init() {
2323
- return __async(this, null, function* () {
2324
- var _a, _b;
2325
- try {
2326
- if (typeof window !== "undefined" && ((_a = window.mmsdk) == null ? void 0 : _a.isInitialized)) {
2327
- logger2("MetaMaskSDK: init already initialized");
2328
- } else {
2329
- yield this.setupAnalytics();
2330
- yield this.setupTransport();
2331
- if ((_b = this.options.analytics) == null ? void 0 : _b.enabled) {
2332
- try {
2333
- const baseProps = yield getBaseAnalyticsProperties(
2334
- this.options,
2335
- this.storage
2336
- );
2337
- import_analytics4.analytics.track("mmconnect_initialized", baseProps);
2338
- } catch (error) {
2339
- logger2("Error tracking initialized event", error);
2340
- }
2341
- }
2342
- if (typeof window !== "undefined") {
2343
- window.mmsdk = this;
2344
- }
2345
- }
2346
- } catch (error) {
2347
- yield this.storage.removeTransport();
2348
- this.state = "pending";
2349
- logger2("MetaMaskSDK error during initialization", error);
2350
- }
2351
- });
2352
- }
2353
- createDappClient() {
2354
- return __async(this, null, function* () {
2355
- const { adapter: kvstore } = this.options.storage;
2356
- const sessionstore = new import_mobile_wallet_protocol_core2.SessionStore(kvstore);
2357
- const websocket = (
2358
- // eslint-disable-next-line no-negated-condition
2359
- typeof window !== "undefined" ? WebSocket : (yield import("ws")).WebSocket
2360
- );
2361
- const transport = yield import_mobile_wallet_protocol_core2.WebSocketTransport.create({
2362
- url: MWP_RELAY_URL,
2363
- kvstore,
2364
- websocket
2365
- });
2366
- const dappClient = new import_mobile_wallet_protocol_dapp_client.DappClient({ transport, sessionstore, keymanager });
2367
- return dappClient;
2368
- });
2369
- }
2370
- setupMWP() {
2371
- return __async(this, null, function* () {
2372
- if (this.__transport instanceof MWPTransport) {
2373
- return;
2374
- }
2375
- const { adapter: kvstore } = this.options.storage;
2376
- const dappClient = yield this.createDappClient();
2377
- this.__dappClient = dappClient;
2378
- const apiTransport = new MWPTransport(dappClient, kvstore);
2379
- this.__transport = apiTransport;
2380
- this.listener = this.transport.onNotification(
2381
- this.onTransportNotification.bind(this)
2382
- );
2383
- yield this.storage.setTransport("mwp" /* MWP */);
2384
- });
2385
- }
2386
- onBeforeUnload() {
2387
- return __async(this, null, function* () {
2388
- var _a;
2389
- if ((_a = this.options.ui.factory.modal) == null ? void 0 : _a.isMounted) {
2390
- yield this.storage.removeTransport();
2391
- }
2392
- });
2393
- }
2394
- createBeforeUnloadListener() {
2395
- if (typeof window !== "undefined" && typeof window.addEventListener !== "undefined") {
2396
- window.addEventListener("beforeunload", this.onBeforeUnload.bind(this));
2397
- }
2398
- return () => {
2399
- if (typeof window !== "undefined" && typeof window.removeEventListener !== "undefined") {
2400
- window.removeEventListener(
2401
- "beforeunload",
2402
- this.onBeforeUnload.bind(this)
2403
- );
2404
- }
2405
- };
2406
- }
2407
- showInstallModal(desktopPreferred, scopes, caipAccountIds) {
2408
- return __async(this, null, function* () {
2409
- var _a;
2410
- (_a = this.__beforeUnloadListener) != null ? _a : this.__beforeUnloadListener = this.createBeforeUnloadListener();
2411
- return new Promise((resolve, reject) => {
2412
- this.options.ui.factory.renderInstallModal(
2413
- desktopPreferred,
2414
- () => __async(this, null, function* () {
2415
- if (this.dappClient.state === "CONNECTED" || this.dappClient.state === "CONNECTING") {
2416
- yield this.dappClient.disconnect();
2417
- }
2418
- return new Promise((resolveConnectionRequest) => {
2419
- this.dappClient.on(
2420
- "session_request",
2421
- (sessionRequest) => {
2422
- resolveConnectionRequest({
2423
- sessionRequest,
2424
- metadata: {
2425
- dapp: this.options.dapp,
2426
- sdk: {
2427
- version: getVersion(),
2428
- platform: getPlatformType()
2429
- }
2430
- }
2431
- });
2432
- }
2433
- );
2434
- this.transport.connect({ scopes, caipAccountIds }).then(() => {
2435
- var _a2;
2436
- this.options.ui.factory.unload();
2437
- (_a2 = this.options.ui.factory.modal) == null ? void 0 : _a2.unmount();
2438
- this.state = "connected";
2439
- return this.storage.setTransport("mwp" /* MWP */);
2440
- }).catch((error) => {
2441
- if (error instanceof import_mobile_wallet_protocol_core2.ProtocolError) {
2442
- if (error.code !== import_mobile_wallet_protocol_core2.ErrorCode.REQUEST_EXPIRED) {
2443
- this.state = "disconnected";
2444
- reject(error);
2445
- }
2446
- } else {
2447
- this.state = "disconnected";
2448
- reject(error);
2449
- }
2450
- });
2451
- });
2452
- }),
2453
- (error) => __async(this, null, function* () {
2454
- if (!error) {
2455
- yield this.storage.setTransport("mwp" /* MWP */);
2456
- resolve();
2457
- } else {
2458
- yield this.storage.removeTransport();
2459
- reject(error);
2460
- }
2461
- })
2462
- );
2463
- });
2464
- });
2465
- }
2466
- setupDefaultTransport() {
2467
- return __async(this, null, function* () {
2468
- this.state = "connecting";
2469
- yield this.storage.setTransport("browser" /* Browser */);
2470
- const transport = new DefaultTransport();
2471
- this.listener = transport.onNotification(
2472
- this.onTransportNotification.bind(this)
2473
- );
2474
- this.__transport = transport;
2475
- return transport;
2476
- });
2477
- }
2478
- deeplinkConnect(scopes, caipAccountIds) {
2479
- return __async(this, null, function* () {
2480
- return new Promise((resolve, reject) => __async(this, null, function* () {
2481
- this.dappClient.on("message", (payload) => {
2482
- var _a, _b, _c;
2483
- const data = payload.data;
2484
- if (typeof data === "object" && data !== null) {
2485
- if ("method" in data && data.method === "wallet_createSession") {
2486
- if (data.error) {
2487
- this.state = "loaded";
2488
- return reject(data.error);
2489
- }
2490
- const session = (_a = data.params) != null ? _a : data.result;
2491
- if (session) {
2492
- (_c = (_b = this.options.transport) == null ? void 0 : _b.onNotification) == null ? void 0 : _c.call(_b, payload.data);
2493
- this.emit("wallet_sessionChanged", session);
2494
- }
2495
- }
2496
- }
2497
- });
2498
- let timeout;
2499
- if (!this.transport.isConnected()) {
2500
- this.dappClient.once(
2501
- "session_request",
2502
- (sessionRequest) => {
2503
- var _a;
2504
- const connectionRequest = {
2505
- sessionRequest,
2506
- metadata: {
2507
- dapp: this.options.dapp,
2508
- sdk: { version: getVersion(), platform: getPlatformType() }
2509
- }
2510
- };
2511
- const deeplink = this.options.ui.factory.createDeeplink(connectionRequest);
2512
- const universalLink = this.options.ui.factory.createUniversalLink(connectionRequest);
2513
- if ((_a = this.options.mobile) == null ? void 0 : _a.preferredOpenLink) {
2514
- this.options.mobile.preferredOpenLink(deeplink, "_self");
2515
- } else {
2516
- openDeeplink(this.options, deeplink, universalLink);
2517
- }
2518
- }
2519
- );
2520
- }
2521
- this.transport.connect({ scopes, caipAccountIds }).then(resolve).catch((error) => {
2522
- this.storage.removeTransport();
2523
- reject(error);
2524
- }).finally(() => {
2525
- if (timeout) {
2526
- clearTimeout(timeout);
2527
- }
2528
- });
2529
- }));
2530
- });
2531
- }
2532
- handleConnection(promise, scopes, transportType) {
2533
- return __async(this, null, function* () {
2534
- this.state = "connecting";
2535
- return promise.then(() => __async(this, null, function* () {
2536
- var _a;
2537
- this.state = "connected";
2538
- if ((_a = this.options.analytics) == null ? void 0 : _a.enabled) {
2539
- try {
2540
- const baseProps = yield getBaseAnalyticsProperties(
2541
- this.options,
2542
- this.storage
2543
- );
2544
- import_analytics4.analytics.track("mmconnect_connection_established", __spreadProps(__spreadValues({}, baseProps), {
2545
- transport_type: transportType,
2546
- user_permissioned_chains: scopes
2547
- }));
2548
- } catch (error) {
2549
- logger2("Error tracking connection_established event", error);
2550
- }
2551
- }
2552
- })).catch((error) => __async(this, null, function* () {
2553
- var _a;
2554
- this.state = "disconnected";
2555
- if ((_a = this.options.analytics) == null ? void 0 : _a.enabled) {
2556
- try {
2557
- const baseProps = yield getBaseAnalyticsProperties(
2558
- this.options,
2559
- this.storage
2560
- );
2561
- const isRejection = isRejectionError(error);
2562
- if (isRejection) {
2563
- import_analytics4.analytics.track("mmconnect_connection_rejected", __spreadProps(__spreadValues({}, baseProps), {
2564
- transport_type: transportType
2565
- }));
2566
- } else {
2567
- import_analytics4.analytics.track("mmconnect_connection_failed", __spreadProps(__spreadValues({}, baseProps), {
2568
- transport_type: transportType
2569
- }));
2570
- }
2571
- } catch (e) {
2572
- logger2("Error tracking connection failed/rejected event", error);
2573
- }
2574
- }
2575
- return Promise.reject(error);
2576
- }));
2577
- });
2578
- }
2579
2246
  connect(scopes, caipAccountIds, forceRequest) {
2580
2247
  return __async(this, null, function* () {
2581
- var _a, _b;
2248
+ var _a2;
2249
+ if (this.state !== "connected") {
2250
+ yield this.disconnect();
2251
+ }
2582
2252
  const { ui } = this.options;
2583
2253
  const platformType = getPlatformType();
2584
2254
  const isWeb = platformType === "in-app-browser" /* MetaMaskMobileWebview */ || platformType === "web-desktop" /* DesktopWeb */;
@@ -2591,96 +2261,72 @@ var MultichainSDK = class _MultichainSDK extends MultichainCore {
2591
2261
  } else {
2592
2262
  transportType = "mwp" /* MWP */;
2593
2263
  }
2594
- if ((_a = this.options.analytics) == null ? void 0 : _a.enabled) {
2595
- try {
2596
- const baseProps = yield getBaseAnalyticsProperties(
2597
- this.options,
2598
- this.storage
2599
- );
2600
- const dappConfiguredChains = Object.keys(
2601
- this.options.api.supportedNetworks
2602
- );
2603
- import_analytics4.analytics.track("mmconnect_connection_initiated", __spreadProps(__spreadValues({}, baseProps), {
2604
- transport_type: transportType,
2605
- dapp_configured_chains: dappConfiguredChains,
2606
- dapp_requested_chains: scopes
2607
- }));
2608
- } catch (error) {
2609
- logger2("Error tracking connection_initiated event", error);
2610
- }
2611
- }
2612
- if (((_b = this.__transport) == null ? void 0 : _b.isConnected()) && !secure) {
2613
- return this.handleConnection(
2614
- this.__transport.connect({ scopes, caipAccountIds, forceRequest }).then(() => {
2615
- if (this.__transport instanceof MWPTransport) {
2616
- return this.storage.setTransport("mwp" /* MWP */);
2617
- } else {
2618
- return this.storage.setTransport("browser" /* Browser */);
2619
- }
2620
- }),
2621
- scopes,
2622
- transportType
2264
+ try {
2265
+ const baseProps = yield getBaseAnalyticsProperties(
2266
+ this.options,
2267
+ this.storage
2623
2268
  );
2269
+ const dappConfiguredChains = Object.keys(
2270
+ this.options.api.supportedNetworks
2271
+ );
2272
+ import_analytics4.analytics.track("mmconnect_connection_initiated", __spreadProps(__spreadValues({}, baseProps), {
2273
+ transport_type: transportType,
2274
+ dapp_configured_chains: dappConfiguredChains,
2275
+ dapp_requested_chains: scopes
2276
+ }));
2277
+ } catch (error) {
2278
+ logger2("Error tracking connection_initiated event", error);
2279
+ }
2280
+ if (((_a2 = __privateGet(this, _transport2)) == null ? void 0 : _a2.isConnected()) && !secure) {
2281
+ return __privateMethod(this, _MultichainSDK_instances, handleConnection_fn).call(this, __privateGet(this, _transport2).connect({ scopes, caipAccountIds, forceRequest }).then(() => __async(this, null, function* () {
2282
+ if (__privateGet(this, _transport2) instanceof MWPTransport) {
2283
+ return this.storage.setTransport("mwp" /* MWP */);
2284
+ }
2285
+ return this.storage.setTransport("browser" /* Browser */);
2286
+ })), scopes, transportType);
2624
2287
  }
2625
2288
  if (platformType === "in-app-browser" /* MetaMaskMobileWebview */) {
2626
- const defaultTransport = yield this.setupDefaultTransport();
2627
- return this.handleConnection(
2628
- defaultTransport.connect({ scopes, caipAccountIds, forceRequest }),
2629
- scopes,
2630
- transportType
2631
- );
2289
+ const defaultTransport = yield __privateMethod(this, _MultichainSDK_instances, setupDefaultTransport_fn).call(this);
2290
+ return __privateMethod(this, _MultichainSDK_instances, handleConnection_fn).call(this, defaultTransport.connect({ scopes, caipAccountIds, forceRequest }), scopes, transportType);
2632
2291
  }
2633
2292
  if (isWeb && hasExtensionInstalled && preferExtension) {
2634
- const defaultTransport = yield this.setupDefaultTransport();
2635
- return this.handleConnection(
2636
- defaultTransport.connect({ scopes, caipAccountIds, forceRequest }),
2637
- scopes,
2638
- transportType
2639
- );
2293
+ const defaultTransport = yield __privateMethod(this, _MultichainSDK_instances, setupDefaultTransport_fn).call(this);
2294
+ return __privateMethod(this, _MultichainSDK_instances, handleConnection_fn).call(this, defaultTransport.connect({ scopes, caipAccountIds, forceRequest }), scopes, transportType);
2640
2295
  }
2641
- yield this.setupMWP();
2296
+ yield __privateMethod(this, _MultichainSDK_instances, setupMWP_fn).call(this);
2642
2297
  const shouldShowInstallModal = hasExtensionInstalled ? showInstallModal : !preferExtension || showInstallModal;
2643
2298
  if (secure && !shouldShowInstallModal) {
2644
- return this.handleConnection(
2645
- this.deeplinkConnect(scopes, caipAccountIds),
2646
- scopes,
2647
- transportType
2648
- );
2299
+ return __privateMethod(this, _MultichainSDK_instances, handleConnection_fn).call(this, __privateMethod(this, _MultichainSDK_instances, deeplinkConnect_fn).call(this, scopes, caipAccountIds), scopes, transportType);
2649
2300
  }
2650
- return this.handleConnection(
2651
- this.showInstallModal(shouldShowInstallModal, scopes, caipAccountIds),
2652
- scopes,
2653
- transportType
2654
- );
2301
+ return __privateMethod(this, _MultichainSDK_instances, handleConnection_fn).call(this, __privateMethod(this, _MultichainSDK_instances, showInstallModal_fn).call(this, shouldShowInstallModal, scopes, caipAccountIds), scopes, transportType);
2655
2302
  });
2656
2303
  }
2657
2304
  emit(event, args) {
2658
- var _a, _b;
2659
- (_b = (_a = this.options.transport) == null ? void 0 : _a.onNotification) == null ? void 0 : _b.call(_a, { method: event, params: args });
2305
+ var _a2, _b;
2306
+ (_b = (_a2 = this.options.transport) == null ? void 0 : _a2.onNotification) == null ? void 0 : _b.call(_a2, { method: event, params: args });
2660
2307
  super.emit(event, args);
2661
2308
  }
2662
2309
  disconnect() {
2663
2310
  return __async(this, null, function* () {
2664
- var _a, _b, _c;
2665
- (_a = this.listener) == null ? void 0 : _a.call(this);
2666
- (_b = this.__beforeUnloadListener) == null ? void 0 : _b.call(this);
2667
- yield (_c = this.__transport) == null ? void 0 : _c.disconnect();
2311
+ var _a2, _b, _c;
2312
+ yield (_a2 = __privateGet(this, _listener)) == null ? void 0 : _a2.call(this);
2313
+ (_b = __privateGet(this, _beforeUnloadListener)) == null ? void 0 : _b.call(this);
2314
+ yield (_c = __privateGet(this, _transport2)) == null ? void 0 : _c.disconnect();
2668
2315
  yield this.storage.removeTransport();
2669
- this.emit("wallet_sessionChanged", void 0);
2670
2316
  this.emit("stateChanged", "disconnected");
2671
- this.listener = void 0;
2672
- this.__beforeUnloadListener = void 0;
2673
- this.__transport = void 0;
2674
- this.__provider = void 0;
2675
- this.__dappClient = void 0;
2317
+ __privateSet(this, _listener, void 0);
2318
+ __privateSet(this, _beforeUnloadListener, void 0);
2319
+ __privateSet(this, _transport2, void 0);
2320
+ __privateSet(this, _provider, void 0);
2321
+ __privateSet(this, _dappClient, void 0);
2676
2322
  });
2677
2323
  }
2678
2324
  invokeMethod(request) {
2679
2325
  return __async(this, null, function* () {
2680
- var _a;
2681
- const { sdkInfo, transport, options } = this;
2682
- (_a = this.__provider) != null ? _a : this.__provider = (0, import_multichain_api_client3.getMultichainClient)({ transport });
2683
- const rpcClient = new RpcClient(options, sdkInfo);
2326
+ var _a2;
2327
+ const { transport, options } = this;
2328
+ (_a2 = __privateGet(this, _provider)) != null ? _a2 : __privateSet(this, _provider, (0, import_multichain_api_client3.getMultichainClient)({ transport }));
2329
+ const rpcClient = new RpcClient(options, __privateGet(this, _sdkInfo));
2684
2330
  const requestRouter = new RequestRouter(transport, rpcClient, options);
2685
2331
  return requestRouter.invokeMethod(request);
2686
2332
  });
@@ -2692,20 +2338,381 @@ var MultichainSDK = class _MultichainSDK extends MultichainCore {
2692
2338
  const secure = isSecure();
2693
2339
  const shouldOpenDeeplink = secure && !showInstallModal;
2694
2340
  if (shouldOpenDeeplink) {
2695
- setTimeout(() => {
2341
+ setTimeout(() => __async(this, null, function* () {
2342
+ const session = yield this.transport.getActiveSession();
2343
+ if (!session) {
2344
+ throw new Error("No active session found");
2345
+ }
2346
+ const url = `${METAMASK_DEEPLINK_BASE}/mwp?id=${encodeURIComponent(session.id)}`;
2696
2347
  if (mobile == null ? void 0 : mobile.preferredOpenLink) {
2697
- mobile.preferredOpenLink(METAMASK_DEEPLINK_BASE, "_self");
2348
+ mobile.preferredOpenLink(url, "_self");
2698
2349
  } else {
2699
- openDeeplink(
2350
+ openDeeplink(this.options, url, METAMASK_CONNECT_BASE_URL);
2351
+ }
2352
+ }), 10);
2353
+ }
2354
+ }
2355
+ };
2356
+ _provider = new WeakMap();
2357
+ _transport2 = new WeakMap();
2358
+ _dappClient = new WeakMap();
2359
+ _beforeUnloadListener = new WeakMap();
2360
+ _listener = new WeakMap();
2361
+ _sdkInfo = new WeakMap();
2362
+ _MultichainSDK_instances = new WeakSet();
2363
+ setupAnalytics_fn = function() {
2364
+ return __async(this, null, function* () {
2365
+ var _a2;
2366
+ const platform = getPlatformType();
2367
+ const isBrowser = platform === "in-app-browser" /* MetaMaskMobileWebview */ || platform === "web-desktop" /* DesktopWeb */ || platform === "web-mobile" /* MobileWeb */;
2368
+ const isReactNative2 = platform === "react-native" /* ReactNative */;
2369
+ if (!isBrowser && !isReactNative2) {
2370
+ return;
2371
+ }
2372
+ const version = getVersion();
2373
+ const dappId = getDappId(this.options.dapp);
2374
+ const anonId = yield this.storage.getAnonId();
2375
+ const { integrationType } = (_a2 = this.options.analytics) != null ? _a2 : {
2376
+ integrationType: ""
2377
+ };
2378
+ import_analytics4.analytics.setGlobalProperty("mmconnect_version", version);
2379
+ import_analytics4.analytics.setGlobalProperty("dapp_id", dappId);
2380
+ import_analytics4.analytics.setGlobalProperty("anon_id", anonId);
2381
+ import_analytics4.analytics.setGlobalProperty("platform", platform);
2382
+ import_analytics4.analytics.setGlobalProperty("integration_type", integrationType);
2383
+ import_analytics4.analytics.enable();
2384
+ });
2385
+ };
2386
+ onTransportNotification_fn = function(payload) {
2387
+ return __async(this, null, function* () {
2388
+ var _a2;
2389
+ if (typeof payload === "object" && payload !== null && "method" in payload) {
2390
+ this.emit(payload.method, (_a2 = payload.params) != null ? _a2 : payload.result);
2391
+ }
2392
+ });
2393
+ };
2394
+ getStoredTransport_fn = function() {
2395
+ return __async(this, null, function* () {
2396
+ const transportType = yield this.storage.getTransport();
2397
+ const hasExtensionInstalled = yield hasExtension();
2398
+ if (transportType) {
2399
+ if (transportType === "browser" /* Browser */) {
2400
+ if (hasExtensionInstalled) {
2401
+ const apiTransport = new DefaultTransport();
2402
+ __privateSet(this, _transport2, apiTransport);
2403
+ __privateSet(this, _listener, apiTransport.onNotification(
2404
+ __privateMethod(this, _MultichainSDK_instances, onTransportNotification_fn).bind(this)
2405
+ ));
2406
+ return apiTransport;
2407
+ }
2408
+ } else if (transportType === "mwp" /* MWP */) {
2409
+ const { adapter: kvstore } = this.options.storage;
2410
+ const dappClient = yield __privateMethod(this, _MultichainSDK_instances, createDappClient_fn).call(this);
2411
+ const apiTransport = new MWPTransport(dappClient, kvstore);
2412
+ __privateSet(this, _dappClient, dappClient);
2413
+ __privateSet(this, _transport2, apiTransport);
2414
+ __privateSet(this, _listener, apiTransport.onNotification(
2415
+ __privateMethod(this, _MultichainSDK_instances, onTransportNotification_fn).bind(this)
2416
+ ));
2417
+ return apiTransport;
2418
+ }
2419
+ yield this.storage.removeTransport();
2420
+ }
2421
+ return void 0;
2422
+ });
2423
+ };
2424
+ setupTransport_fn = function() {
2425
+ return __async(this, null, function* () {
2426
+ const transport = yield __privateMethod(this, _MultichainSDK_instances, getStoredTransport_fn).call(this);
2427
+ if (transport) {
2428
+ if (!this.transport.isConnected()) {
2429
+ this.state = "connecting";
2430
+ yield this.transport.connect();
2431
+ }
2432
+ this.state = "connected";
2433
+ if (this.transport instanceof MWPTransport) {
2434
+ yield this.storage.setTransport("mwp" /* MWP */);
2435
+ } else {
2436
+ yield this.storage.setTransport("browser" /* Browser */);
2437
+ }
2438
+ } else {
2439
+ this.state = "loaded";
2440
+ }
2441
+ });
2442
+ };
2443
+ init_fn = function() {
2444
+ return __async(this, null, function* () {
2445
+ var _a2;
2446
+ try {
2447
+ if (typeof window !== "undefined" && ((_a2 = window.mmsdk) == null ? void 0 : _a2.isInitialized)) {
2448
+ logger2("MetaMaskSDK: init already initialized");
2449
+ } else {
2450
+ yield __privateMethod(this, _MultichainSDK_instances, setupAnalytics_fn).call(this);
2451
+ yield __privateMethod(this, _MultichainSDK_instances, setupTransport_fn).call(this);
2452
+ try {
2453
+ const baseProps = yield getBaseAnalyticsProperties(
2700
2454
  this.options,
2701
- METAMASK_DEEPLINK_BASE,
2702
- METAMASK_CONNECT_BASE_URL
2455
+ this.storage
2703
2456
  );
2457
+ import_analytics4.analytics.track("mmconnect_initialized", baseProps);
2458
+ } catch (error) {
2459
+ logger2("Error tracking initialized event", error);
2460
+ }
2461
+ if (typeof window !== "undefined") {
2462
+ window.mmsdk = this;
2704
2463
  }
2705
- }, 10);
2464
+ }
2465
+ } catch (error) {
2466
+ yield this.storage.removeTransport();
2467
+ this.state = "pending";
2468
+ logger2("MetaMaskSDK error during initialization", error);
2706
2469
  }
2707
- }
2470
+ });
2471
+ };
2472
+ createDappClient_fn = function() {
2473
+ return __async(this, null, function* () {
2474
+ const { adapter: kvstore } = this.options.storage;
2475
+ const sessionstore = new import_mobile_wallet_protocol_core2.SessionStore(kvstore);
2476
+ const websocket = (
2477
+ // eslint-disable-next-line no-negated-condition
2478
+ typeof window !== "undefined" ? WebSocket : (yield import("ws")).WebSocket
2479
+ );
2480
+ const transport = yield import_mobile_wallet_protocol_core2.WebSocketTransport.create({
2481
+ url: MWP_RELAY_URL,
2482
+ kvstore,
2483
+ websocket
2484
+ });
2485
+ const dappClient = new import_mobile_wallet_protocol_dapp_client.DappClient({ transport, sessionstore, keymanager });
2486
+ return dappClient;
2487
+ });
2488
+ };
2489
+ setupMWP_fn = function() {
2490
+ return __async(this, null, function* () {
2491
+ if (__privateGet(this, _transport2) instanceof MWPTransport) {
2492
+ return;
2493
+ }
2494
+ const { adapter: kvstore } = this.options.storage;
2495
+ const dappClient = yield __privateMethod(this, _MultichainSDK_instances, createDappClient_fn).call(this);
2496
+ __privateSet(this, _dappClient, dappClient);
2497
+ const apiTransport = new MWPTransport(dappClient, kvstore);
2498
+ __privateSet(this, _transport2, apiTransport);
2499
+ __privateSet(this, _listener, this.transport.onNotification(
2500
+ __privateMethod(this, _MultichainSDK_instances, onTransportNotification_fn).bind(this)
2501
+ ));
2502
+ yield this.storage.setTransport("mwp" /* MWP */);
2503
+ });
2504
+ };
2505
+ onBeforeUnload_fn = function() {
2506
+ return __async(this, null, function* () {
2507
+ var _a2;
2508
+ if ((_a2 = this.options.ui.factory.modal) == null ? void 0 : _a2.isMounted) {
2509
+ yield this.storage.removeTransport();
2510
+ }
2511
+ });
2512
+ };
2513
+ createBeforeUnloadListener_fn = function() {
2514
+ if (typeof window !== "undefined" && typeof window.addEventListener !== "undefined") {
2515
+ window.addEventListener("beforeunload", __privateMethod(this, _MultichainSDK_instances, onBeforeUnload_fn).bind(this));
2516
+ }
2517
+ return () => {
2518
+ if (typeof window !== "undefined" && typeof window.removeEventListener !== "undefined") {
2519
+ window.removeEventListener(
2520
+ "beforeunload",
2521
+ __privateMethod(this, _MultichainSDK_instances, onBeforeUnload_fn).bind(this)
2522
+ );
2523
+ }
2524
+ };
2525
+ };
2526
+ renderInstallModalAsync_fn = function(desktopPreferred, scopes, caipAccountIds) {
2527
+ return __async(this, null, function* () {
2528
+ return new Promise((resolve, reject) => {
2529
+ this.options.ui.factory.renderInstallModal(
2530
+ desktopPreferred,
2531
+ () => __async(this, null, function* () {
2532
+ if (this.dappClient.state === "CONNECTED" || this.dappClient.state === "CONNECTING") {
2533
+ yield this.dappClient.disconnect();
2534
+ }
2535
+ return new Promise((_resolve) => {
2536
+ this.dappClient.on(
2537
+ "session_request",
2538
+ (sessionRequest) => {
2539
+ _resolve({
2540
+ sessionRequest,
2541
+ metadata: {
2542
+ dapp: this.options.dapp,
2543
+ sdk: {
2544
+ version: getVersion(),
2545
+ platform: getPlatformType()
2546
+ }
2547
+ }
2548
+ });
2549
+ }
2550
+ );
2551
+ (() => __async(this, null, function* () {
2552
+ var _a2;
2553
+ try {
2554
+ yield this.transport.connect({ scopes, caipAccountIds });
2555
+ yield this.options.ui.factory.unload();
2556
+ (_a2 = this.options.ui.factory.modal) == null ? void 0 : _a2.unmount();
2557
+ this.state = "connected";
2558
+ yield this.storage.setTransport("mwp" /* MWP */);
2559
+ } catch (error) {
2560
+ if (error instanceof import_mobile_wallet_protocol_core2.ProtocolError) {
2561
+ if (error.code !== import_mobile_wallet_protocol_core2.ErrorCode.REQUEST_EXPIRED) {
2562
+ this.state = "disconnected";
2563
+ reject(error);
2564
+ }
2565
+ } else {
2566
+ this.state = "disconnected";
2567
+ reject(
2568
+ error instanceof Error ? error : new Error(String(error))
2569
+ );
2570
+ }
2571
+ }
2572
+ }))().catch(() => {
2573
+ });
2574
+ });
2575
+ }),
2576
+ (error) => __async(this, null, function* () {
2577
+ if (error) {
2578
+ yield this.storage.removeTransport();
2579
+ reject(error);
2580
+ } else {
2581
+ yield this.storage.setTransport("mwp" /* MWP */);
2582
+ resolve();
2583
+ }
2584
+ })
2585
+ ).catch((error) => {
2586
+ reject(error instanceof Error ? error : new Error(String(error)));
2587
+ });
2588
+ });
2589
+ });
2590
+ };
2591
+ showInstallModal_fn = function(desktopPreferred, scopes, caipAccountIds) {
2592
+ return __async(this, null, function* () {
2593
+ var _a2;
2594
+ (_a2 = __privateGet(this, _beforeUnloadListener)) != null ? _a2 : __privateSet(this, _beforeUnloadListener, __privateMethod(this, _MultichainSDK_instances, createBeforeUnloadListener_fn).call(this));
2595
+ yield __privateMethod(this, _MultichainSDK_instances, renderInstallModalAsync_fn).call(this, desktopPreferred, scopes, caipAccountIds);
2596
+ });
2597
+ };
2598
+ setupDefaultTransport_fn = function() {
2599
+ return __async(this, null, function* () {
2600
+ this.state = "connecting";
2601
+ yield this.storage.setTransport("browser" /* Browser */);
2602
+ const transport = new DefaultTransport();
2603
+ __privateSet(this, _listener, transport.onNotification(
2604
+ __privateMethod(this, _MultichainSDK_instances, onTransportNotification_fn).bind(this)
2605
+ ));
2606
+ __privateSet(this, _transport2, transport);
2607
+ return transport;
2608
+ });
2609
+ };
2610
+ deeplinkConnect_fn = function(scopes, caipAccountIds) {
2611
+ return __async(this, null, function* () {
2612
+ return new Promise((resolve, reject) => {
2613
+ const dappClientMessageHandler = (payload) => {
2614
+ var _a2;
2615
+ if (typeof payload !== "object" || payload === null || !("data" in payload)) {
2616
+ return;
2617
+ }
2618
+ const data = payload.data;
2619
+ if (typeof data === "object" && data !== null) {
2620
+ if (data.error) {
2621
+ this.dappClient.off("message", dappClientMessageHandler);
2622
+ reject(data.error);
2623
+ }
2624
+ if ((_a2 = data == null ? void 0 : data.result) == null ? void 0 : _a2.sessionScopes) {
2625
+ this.dappClient.off("message", dappClientMessageHandler);
2626
+ }
2627
+ }
2628
+ };
2629
+ this.dappClient.on("message", dappClientMessageHandler);
2630
+ let timeout;
2631
+ if (this.transport.isConnected()) {
2632
+ timeout = setTimeout(() => {
2633
+ this.openDeeplinkIfNeeded();
2634
+ }, 250);
2635
+ } else {
2636
+ this.dappClient.once(
2637
+ "session_request",
2638
+ (sessionRequest) => {
2639
+ var _a2;
2640
+ const connectionRequest = {
2641
+ sessionRequest,
2642
+ metadata: {
2643
+ dapp: this.options.dapp,
2644
+ sdk: { version: getVersion(), platform: getPlatformType() }
2645
+ }
2646
+ };
2647
+ const deeplink = this.options.ui.factory.createConnectionDeeplink(
2648
+ connectionRequest
2649
+ );
2650
+ const universalLink = this.options.ui.factory.createConnectionUniversalLink(
2651
+ connectionRequest
2652
+ );
2653
+ if ((_a2 = this.options.mobile) == null ? void 0 : _a2.preferredOpenLink) {
2654
+ this.options.mobile.preferredOpenLink(deeplink, "_self");
2655
+ } else {
2656
+ openDeeplink(this.options, deeplink, universalLink);
2657
+ }
2658
+ }
2659
+ );
2660
+ }
2661
+ return this.transport.connect({ scopes, caipAccountIds }).then(resolve).catch((error) => __async(this, null, function* () {
2662
+ yield this.storage.removeTransport();
2663
+ this.dappClient.off("message", dappClientMessageHandler);
2664
+ reject(error instanceof Error ? error : new Error(String(error)));
2665
+ })).finally(() => {
2666
+ if (timeout) {
2667
+ clearTimeout(timeout);
2668
+ }
2669
+ });
2670
+ });
2671
+ });
2672
+ };
2673
+ handleConnection_fn = function(promise, scopes, transportType) {
2674
+ return __async(this, null, function* () {
2675
+ this.state = "connecting";
2676
+ return promise.then(() => __async(this, null, function* () {
2677
+ this.state = "connected";
2678
+ try {
2679
+ const baseProps = yield getBaseAnalyticsProperties(
2680
+ this.options,
2681
+ this.storage
2682
+ );
2683
+ import_analytics4.analytics.track("mmconnect_connection_established", __spreadProps(__spreadValues({}, baseProps), {
2684
+ transport_type: transportType,
2685
+ user_permissioned_chains: scopes
2686
+ }));
2687
+ } catch (error) {
2688
+ logger2("Error tracking connection_established event", error);
2689
+ }
2690
+ return void 0;
2691
+ })).catch((error) => __async(this, null, function* () {
2692
+ this.state = "disconnected";
2693
+ try {
2694
+ const baseProps = yield getBaseAnalyticsProperties(
2695
+ this.options,
2696
+ this.storage
2697
+ );
2698
+ const isRejection = isRejectionError(error);
2699
+ if (isRejection) {
2700
+ import_analytics4.analytics.track("mmconnect_connection_rejected", __spreadProps(__spreadValues({}, baseProps), {
2701
+ transport_type: transportType
2702
+ }));
2703
+ } else {
2704
+ import_analytics4.analytics.track("mmconnect_connection_failed", __spreadProps(__spreadValues({}, baseProps), {
2705
+ transport_type: transportType
2706
+ }));
2707
+ }
2708
+ } catch (e) {
2709
+ logger2("Error tracking connection failed/rejected event", error);
2710
+ }
2711
+ throw error;
2712
+ }));
2713
+ });
2708
2714
  };
2715
+ var MultichainSDK = _MultichainSDK;
2709
2716
 
2710
2717
  // src/store/index.ts
2711
2718
  var uuid = __toESM(require("uuid"));
@@ -2889,37 +2896,24 @@ var Store = class extends StoreClient {
2889
2896
  // src/ui/index.ts
2890
2897
  var import_onboarding = __toESM(require("@metamask/onboarding"));
2891
2898
  init_domain();
2892
- init_qr();
2893
2899
  init_utils();
2894
- var __instance;
2900
+
2901
+ // src/ui/preload.web.ts
2895
2902
  function preload() {
2896
2903
  return __async(this, null, function* () {
2897
- if (false) {
2898
- __instance != null ? __instance : __instance = yield null.then((loader) => __async(null, null, function* () {
2899
- if (typeof (loader == null ? void 0 : loader.defineCustomElements) === "function") {
2900
- loader.defineCustomElements();
2901
- }
2902
- return Promise.resolve(loader);
2903
- })).catch((error) => __async(null, null, function* () {
2904
- console.error(`Gracefully Failed to load modal customElements:`, error);
2905
- return Promise.resolve(void 0);
2906
- }));
2907
- } else {
2908
- const dynamicImport = (0, eval)("import");
2909
- __instance != null ? __instance : __instance = yield dynamicImport(
2910
- "@metamask/multichain-ui/dist/loader/index.js"
2911
- ).then((loader) => __async(null, null, function* () {
2912
- if (typeof (loader == null ? void 0 : loader.defineCustomElements) === "function") {
2913
- loader.defineCustomElements();
2914
- }
2915
- return Promise.resolve(loader);
2916
- })).catch((error) => __async(null, null, function* () {
2917
- console.error(`Gracefully Failed to load modal customElements:`, error);
2918
- return Promise.resolve(void 0);
2919
- }));
2904
+ if (typeof document === "undefined") {
2905
+ return;
2906
+ }
2907
+ try {
2908
+ const { defineCustomElements } = yield import("@metamask/multichain-ui/loader");
2909
+ yield defineCustomElements();
2910
+ } catch (error) {
2911
+ console.error("Failed to load customElements:", error);
2920
2912
  }
2921
2913
  });
2922
2914
  }
2915
+
2916
+ // src/ui/index.ts
2923
2917
  var ModalFactory = class {
2924
2918
  /**
2925
2919
  * Creates a new modal factory instance.
@@ -2942,8 +2936,8 @@ var ModalFactory = class {
2942
2936
  }
2943
2937
  unload(error) {
2944
2938
  return __async(this, null, function* () {
2945
- var _a, _b;
2946
- (_a = this.modal) == null ? void 0 : _a.unmount();
2939
+ var _a2, _b;
2940
+ (_a2 = this.modal) == null ? void 0 : _a2.unmount();
2947
2941
  yield (_b = this.successCallback) == null ? void 0 : _b.call(this, error);
2948
2942
  });
2949
2943
  }
@@ -2981,16 +2975,16 @@ var ModalFactory = class {
2981
2975
  }
2982
2976
  return container;
2983
2977
  }
2984
- createDeeplink(connectionRequest) {
2978
+ createConnectionDeeplink(connectionRequest) {
2985
2979
  if (!connectionRequest) {
2986
- throw new Error("createDeeplink can only be called with a connection request");
2980
+ throw new Error("createConnectionDeeplink can only be called with a connection request");
2987
2981
  }
2988
2982
  const json = JSON.stringify(connectionRequest);
2989
2983
  const compressed = compressString(json);
2990
2984
  const urlEncoded = encodeURIComponent(compressed);
2991
2985
  return `${METAMASK_DEEPLINK_BASE}/mwp?p=${urlEncoded}&c=1`;
2992
2986
  }
2993
- createUniversalLink(connectionRequest) {
2987
+ createConnectionUniversalLink(connectionRequest) {
2994
2988
  if (!connectionRequest) {
2995
2989
  return `${METAMASK_CONNECT_BASE_URL}`;
2996
2990
  }
@@ -3011,13 +3005,13 @@ var ModalFactory = class {
3011
3005
  }
3012
3006
  renderInstallModal(showInstallModal, createConnectionRequest, successCallback) {
3013
3007
  return __async(this, null, function* () {
3014
- var _a;
3015
- (_a = this.modal) == null ? void 0 : _a.unmount();
3016
- yield Promise.all([preload(), preloadQR()]);
3008
+ var _a2;
3009
+ (_a2 = this.modal) == null ? void 0 : _a2.unmount();
3010
+ yield preload();
3017
3011
  this.successCallback = successCallback;
3018
3012
  const parentElement = this.getMountedContainer();
3019
3013
  const connectionRequest = yield createConnectionRequest();
3020
- const qrCodeLink = this.createDeeplink(connectionRequest);
3014
+ const qrCodeLink = this.createConnectionDeeplink(connectionRequest);
3021
3015
  const modal = new this.options.InstallModal({
3022
3016
  expiresIn: (connectionRequest.sessionRequest.expiresAt - Date.now()) / 1e3,
3023
3017
  connectionRequest,
@@ -3026,7 +3020,7 @@ var ModalFactory = class {
3026
3020
  link: qrCodeLink,
3027
3021
  sdkVersion: getVersion(),
3028
3022
  generateQRCode: (request) => __async(this, null, function* () {
3029
- return this.createDeeplink(request);
3023
+ return this.createConnectionDeeplink(request);
3030
3024
  }),
3031
3025
  onClose: this.onCloseModal.bind(this),
3032
3026
  startDesktopOnboarding: this.onStartDesktopOnboarding.bind(this),
@@ -3038,9 +3032,9 @@ var ModalFactory = class {
3038
3032
  }
3039
3033
  renderOTPCodeModal(createOTPCode, successCallback, updateOTPCode) {
3040
3034
  return __async(this, null, function* () {
3041
- var _a;
3042
- (_a = this.modal) == null ? void 0 : _a.unmount();
3043
- yield Promise.all([preload(), preloadQR()]);
3035
+ var _a2;
3036
+ (_a2 = this.modal) == null ? void 0 : _a2.unmount();
3037
+ yield preload();
3044
3038
  this.successCallback = successCallback;
3045
3039
  const container = this.getMountedContainer();
3046
3040
  const otpCode = yield createOTPCode();