@metamask/connect-multichain 0.5.3 → 0.7.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 (60) hide show
  1. package/CHANGELOG.md +41 -1
  2. package/README.md +30 -22
  3. package/dist/browser/es/connect-multichain.d.mts +29 -4
  4. package/dist/browser/es/connect-multichain.mjs +636 -335
  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 +29 -4
  8. package/dist/browser/iife/connect-multichain.js +3487 -3072
  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 +29 -4
  12. package/dist/browser/umd/connect-multichain.js +636 -335
  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 +29 -4
  16. package/dist/node/cjs/connect-multichain.js +454 -153
  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 +29 -4
  20. package/dist/node/es/connect-multichain.mjs +454 -153
  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 +29 -4
  24. package/dist/react-native/es/connect-multichain.mjs +629 -328
  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/index.d.ts +15 -4
  28. package/dist/src/domain/multichain/index.d.ts.map +1 -1
  29. package/dist/src/domain/multichain/index.js +14 -0
  30. package/dist/src/domain/multichain/index.js.map +1 -1
  31. package/dist/src/domain/multichain/types.d.ts +14 -0
  32. package/dist/src/domain/multichain/types.d.ts.map +1 -1
  33. package/dist/src/multichain/index.d.ts +3 -2
  34. package/dist/src/multichain/index.d.ts.map +1 -1
  35. package/dist/src/multichain/index.js +158 -61
  36. package/dist/src/multichain/index.js.map +1 -1
  37. package/dist/src/multichain/transports/default/index.d.ts +3 -1
  38. package/dist/src/multichain/transports/default/index.d.ts.map +1 -1
  39. package/dist/src/multichain/transports/default/index.js +17 -11
  40. package/dist/src/multichain/transports/default/index.js.map +1 -1
  41. package/dist/src/multichain/transports/multichainApiClientWrapper/index.d.ts +3 -1
  42. package/dist/src/multichain/transports/multichainApiClientWrapper/index.d.ts.map +1 -1
  43. package/dist/src/multichain/transports/multichainApiClientWrapper/index.js +28 -32
  44. package/dist/src/multichain/transports/multichainApiClientWrapper/index.js.map +1 -1
  45. package/dist/src/multichain/transports/mwp/index.d.ts +15 -2
  46. package/dist/src/multichain/transports/mwp/index.d.ts.map +1 -1
  47. package/dist/src/multichain/transports/mwp/index.js +161 -39
  48. package/dist/src/multichain/transports/mwp/index.js.map +1 -1
  49. package/dist/src/multichain/utils/index.d.ts +23 -0
  50. package/dist/src/multichain/utils/index.d.ts.map +1 -1
  51. package/dist/src/multichain/utils/index.js +94 -4
  52. package/dist/src/multichain/utils/index.js.map +1 -1
  53. package/dist/src/polyfills/buffer-shim.js +4 -14
  54. package/dist/src/polyfills/buffer-shim.js.map +1 -1
  55. package/dist/src/store/adapters/web.d.ts +1 -1
  56. package/dist/src/store/adapters/web.d.ts.map +1 -1
  57. package/dist/src/store/adapters/web.js +1 -1
  58. package/dist/src/store/adapters/web.js.map +1 -1
  59. package/dist/types/connect-multichain.d.ts +29 -4
  60. package/package.json +2 -2
@@ -55,14 +55,6 @@ var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read fr
55
55
  var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
56
56
  var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
57
57
  var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
58
- var __privateWrapper = (obj, member, setter, getter) => ({
59
- set _(value) {
60
- __privateSet(obj, member, value, setter);
61
- },
62
- get _() {
63
- return __privateGet(obj, member, getter);
64
- }
65
- });
66
58
  var __async = (__this, __arguments, generator) => {
67
59
  return new Promise((resolve, reject) => {
68
60
  var fulfilled = (value) => {
@@ -264,8 +256,8 @@ var init_logger = __esm({
264
256
  import_debug.default.enable(namespace);
265
257
  };
266
258
  isEnabled = (namespace, storage) => __async(null, null, function* () {
267
- var _a2;
268
- if ("process" in globalThis && ((_a2 = process == null ? void 0 : process.env) == null ? void 0 : _a2.DEBUG)) {
259
+ var _a3;
260
+ if ("process" in globalThis && ((_a3 = process == null ? void 0 : process.env) == null ? void 0 : _a3.DEBUG)) {
269
261
  const { DEBUG } = process.env;
270
262
  return isNamespaceEnabled(DEBUG, namespace);
271
263
  }
@@ -428,41 +420,69 @@ var init_multichain = __esm({
428
420
  super();
429
421
  this.options = options;
430
422
  }
423
+ /**
424
+ * Merges the given options into the current instance options.
425
+ * Only the mergeable keys are updated (api.supportedNetworks, ui.*, mobile.*, transport.extensionId, debug).
426
+ * The main thing to note is that the value for `dapp` is not merged as it does not make sense for
427
+ * subsequent calls to `createMultichainClient` to have a different `dapp` value.
428
+ * Used when createMultichainClient is called with an existing singleton.
429
+ *
430
+ * @param partial - Options to merge/overwrite onto the current instance
431
+ */
432
+ mergeOptions(partial) {
433
+ var _a3, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n;
434
+ const opts = this.options;
435
+ this.options = __spreadProps(__spreadValues({}, opts), {
436
+ api: __spreadProps(__spreadValues({}, opts.api), {
437
+ supportedNetworks: __spreadValues(__spreadValues({}, opts.api.supportedNetworks), (_b = (_a3 = partial.api) == null ? void 0 : _a3.supportedNetworks) != null ? _b : {})
438
+ }),
439
+ ui: __spreadProps(__spreadValues({}, opts.ui), {
440
+ headless: (_d = (_c = partial.ui) == null ? void 0 : _c.headless) != null ? _d : opts.ui.headless,
441
+ preferExtension: (_f = (_e = partial.ui) == null ? void 0 : _e.preferExtension) != null ? _f : opts.ui.preferExtension,
442
+ showInstallModal: (_h = (_g = partial.ui) == null ? void 0 : _g.showInstallModal) != null ? _h : opts.ui.showInstallModal
443
+ }),
444
+ mobile: __spreadValues(__spreadValues({}, opts.mobile), (_i = partial.mobile) != null ? _i : {}),
445
+ transport: __spreadProps(__spreadValues({}, (_j = opts.transport) != null ? _j : {}), {
446
+ extensionId: (_m = (_k = partial.transport) == null ? void 0 : _k.extensionId) != null ? _m : (_l = opts.transport) == null ? void 0 : _l.extensionId
447
+ }),
448
+ debug: (_n = partial.debug) != null ? _n : opts.debug
449
+ });
450
+ }
431
451
  };
432
452
  }
433
453
  });
434
454
 
435
455
  // src/domain/platform/index.ts
436
456
  function isNotBrowser() {
437
- var _a2;
457
+ var _a3;
438
458
  if (typeof window === "undefined") {
439
459
  return true;
440
460
  }
441
461
  if (!(window == null ? void 0 : window.navigator)) {
442
462
  return true;
443
463
  }
444
- if (typeof global !== "undefined" && ((_a2 = global == null ? void 0 : global.navigator) == null ? void 0 : _a2.product) === "ReactNative") {
464
+ if (typeof global !== "undefined" && ((_a3 = global == null ? void 0 : global.navigator) == null ? void 0 : _a3.product) === "ReactNative") {
445
465
  return true;
446
466
  }
447
467
  return (navigator == null ? void 0 : navigator.product) === "ReactNative";
448
468
  }
449
469
  function isReactNative() {
450
- var _a2;
470
+ var _a3;
451
471
  const hasWindowNavigator = typeof window !== "undefined" && window.navigator !== void 0;
452
472
  const nav = hasWindowNavigator ? window.navigator : void 0;
453
473
  if (!nav) {
454
474
  return false;
455
475
  }
456
- return hasWindowNavigator && ((_a2 = window.navigator) == null ? void 0 : _a2.product) === "ReactNative";
476
+ return hasWindowNavigator && ((_a3 = window.navigator) == null ? void 0 : _a3.product) === "ReactNative";
457
477
  }
458
478
  function isMetaMaskMobileWebView() {
459
479
  return typeof window !== "undefined" && // @ts-expect-error ReactNativeWebView should be defined
460
480
  Boolean(window.ReactNativeWebView) && Boolean(window.navigator.userAgent.endsWith("MetaMaskMobile"));
461
481
  }
462
482
  function isMobile() {
463
- var _a2, _b;
483
+ var _a3, _b;
464
484
  const browser = import_bowser.default.parse(window.navigator.userAgent);
465
- 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";
485
+ return ((_a3 = browser == null ? void 0 : browser.platform) == null ? void 0 : _a3.type) === "mobile" || ((_b = browser == null ? void 0 : browser.platform) == null ? void 0 : _b.type) === "tablet";
466
486
  }
467
487
  function getPlatformType() {
468
488
  if (isReactNative()) {
@@ -480,11 +500,11 @@ function getPlatformType() {
480
500
  return "web-desktop" /* DesktopWeb */;
481
501
  }
482
502
  function isMetamaskExtensionInstalled() {
483
- var _a2;
503
+ var _a3;
484
504
  if (typeof window === "undefined") {
485
505
  return false;
486
506
  }
487
- return Boolean((_a2 = window.ethereum) == null ? void 0 : _a2.isMetaMask);
507
+ return Boolean((_a3 = window.ethereum) == null ? void 0 : _a3.isMetaMask);
488
508
  }
489
509
  function isSecure() {
490
510
  const platformType = getPlatformType();
@@ -516,8 +536,8 @@ var init_platform = __esm({
516
536
  return new Promise((resolve) => {
517
537
  const providers = [];
518
538
  const handler = (event) => {
519
- var _a2, _b;
520
- if ((_b = (_a2 = event == null ? void 0 : event.detail) == null ? void 0 : _a2.info) == null ? void 0 : _b.rdns) {
539
+ var _a3, _b;
540
+ if ((_b = (_a3 = event == null ? void 0 : event.detail) == null ? void 0 : _a3.info) == null ? void 0 : _b.rdns) {
521
541
  providers.push(event.detail);
522
542
  }
523
543
  };
@@ -527,8 +547,8 @@ var init_platform = __esm({
527
547
  window.removeEventListener("eip6963:announceProvider", handler);
528
548
  const hasMetaMask = providers.some(
529
549
  (provider) => {
530
- var _a2, _b;
531
- return (_b = (_a2 = provider == null ? void 0 : provider.info) == null ? void 0 : _a2.rdns) == null ? void 0 : _b.startsWith("io.metamask");
550
+ var _a3, _b;
551
+ return (_b = (_a3 = provider == null ? void 0 : provider.info) == null ? void 0 : _a3.rdns) == null ? void 0 : _b.startsWith("io.metamask");
532
552
  }
533
553
  );
534
554
  resolve(hasMetaMask);
@@ -612,7 +632,103 @@ var init_ui = __esm({
612
632
  }
613
633
  });
614
634
 
635
+ // src/multichain/utils/analytics.ts
636
+ function isRejectionError(error) {
637
+ var _a3, _b;
638
+ if (typeof error !== "object" || error === null) {
639
+ return false;
640
+ }
641
+ const errorObj = error;
642
+ const errorCode = errorObj.code;
643
+ const errorMessage = (_b = (_a3 = errorObj.message) == null ? void 0 : _a3.toLowerCase()) != null ? _b : "";
644
+ return errorCode === 4001 || // User rejected request (common EIP-1193 code)
645
+ errorCode === 4100 || // Unauthorized (common rejection code)
646
+ errorMessage.includes("reject") || errorMessage.includes("denied") || errorMessage.includes("cancel") || errorMessage.includes("user");
647
+ }
648
+ function getBaseAnalyticsProperties(options, storage) {
649
+ return __async(this, null, function* () {
650
+ var _a3, _b;
651
+ const version = getVersion();
652
+ const dappId = getDappId(options.dapp);
653
+ const platform = getPlatformType();
654
+ const anonId = yield storage.getAnonId();
655
+ const integrationType = (_b = (_a3 = options.analytics) == null ? void 0 : _a3.integrationType) != null ? _b : "unknown" /* UNKNOWN */;
656
+ return {
657
+ mmconnect_version: version,
658
+ dapp_id: dappId,
659
+ platform,
660
+ integration_type: integrationType,
661
+ anon_id: anonId
662
+ };
663
+ });
664
+ }
665
+ function getWalletActionAnalyticsProperties(options, storage, invokeOptions) {
666
+ return __async(this, null, function* () {
667
+ var _a3, _b;
668
+ const version = getVersion();
669
+ const dappId = getDappId(options.dapp);
670
+ const anonId = yield storage.getAnonId();
671
+ const integrationType = (_b = (_a3 = options.analytics) == null ? void 0 : _a3.integrationType) != null ? _b : "unknown";
672
+ return {
673
+ mmconnect_version: version,
674
+ dapp_id: dappId,
675
+ method: invokeOptions.request.method,
676
+ integration_type: integrationType,
677
+ caip_chain_id: invokeOptions.scope,
678
+ anon_id: anonId
679
+ };
680
+ });
681
+ }
682
+ var init_analytics = __esm({
683
+ "src/multichain/utils/analytics.ts"() {
684
+ "use strict";
685
+ init_utils2();
686
+ init_domain();
687
+ }
688
+ });
689
+
690
+ // src/domain/utils/index.ts
691
+ function getVersion() {
692
+ return "0.0.0";
693
+ }
694
+ var init_utils = __esm({
695
+ "src/domain/utils/index.ts"() {
696
+ "use strict";
697
+ init_analytics();
698
+ }
699
+ });
700
+
701
+ // src/domain/index.ts
702
+ var init_domain = __esm({
703
+ "src/domain/index.ts"() {
704
+ "use strict";
705
+ init_errors();
706
+ init_events();
707
+ init_logger();
708
+ init_multichain();
709
+ init_platform();
710
+ init_store();
711
+ init_ui();
712
+ init_utils();
713
+ }
714
+ });
715
+
615
716
  // src/multichain/utils/index.ts
717
+ function getGlobalObject() {
718
+ if (typeof globalThis !== "undefined") {
719
+ return globalThis;
720
+ }
721
+ if (typeof global !== "undefined") {
722
+ return global;
723
+ }
724
+ if (typeof self !== "undefined") {
725
+ return self;
726
+ }
727
+ if (typeof window !== "undefined") {
728
+ return window;
729
+ }
730
+ throw new Error("Unable to locate global object");
731
+ }
616
732
  function base64Encode(str) {
617
733
  if (typeof btoa !== "undefined") {
618
734
  return btoa(str);
@@ -627,13 +743,13 @@ function compressString(str) {
627
743
  return base64Encode(binaryString);
628
744
  }
629
745
  function getDappId(dapp) {
630
- var _a2;
631
- return (_a2 = dapp.url) != null ? _a2 : dapp.name;
746
+ var _a3;
747
+ return (_a3 = dapp.url) != null ? _a3 : dapp.name;
632
748
  }
633
749
  function openDeeplink(options, deeplink, universalLink) {
634
- var _a2;
750
+ var _a3;
635
751
  const { mobile } = options;
636
- const useDeeplink = (_a2 = mobile == null ? void 0 : mobile.useDeeplink) != null ? _a2 : true;
752
+ const useDeeplink = (_a3 = mobile == null ? void 0 : mobile.useDeeplink) != null ? _a3 : true;
637
753
  if (useDeeplink) {
638
754
  if (typeof window !== "undefined") {
639
755
  window.location.href = deeplink;
@@ -646,6 +762,29 @@ function openDeeplink(options, deeplink, universalLink) {
646
762
  link.click();
647
763
  }
648
764
  }
765
+ function mergeRequestedSessionWithExisting(sessionData, scopes, caipAccountIds, sessionProperties) {
766
+ const existingCaipChainIds = Object.keys(sessionData.sessionScopes);
767
+ const existingCaipAccountIds = [];
768
+ Object.values(sessionData.sessionScopes).forEach((scopeObject) => {
769
+ if ((scopeObject == null ? void 0 : scopeObject.accounts) && Array.isArray(scopeObject.accounts)) {
770
+ scopeObject.accounts.forEach((account) => {
771
+ existingCaipAccountIds.push(account);
772
+ });
773
+ }
774
+ });
775
+ const mergedScopes = Array.from(
776
+ /* @__PURE__ */ new Set([...existingCaipChainIds, ...scopes])
777
+ );
778
+ const mergedCaipAccountIds = Array.from(
779
+ /* @__PURE__ */ new Set([...existingCaipAccountIds, ...caipAccountIds])
780
+ );
781
+ const mergedSessionProperties = __spreadValues(__spreadValues({}, sessionData.sessionProperties), sessionProperties);
782
+ return {
783
+ mergedScopes,
784
+ mergedCaipAccountIds,
785
+ mergedSessionProperties
786
+ };
787
+ }
649
788
  function getOptionalScopes(scopes) {
650
789
  return scopes.reduce(
651
790
  (prev, scope) => __spreadProps(__spreadValues({}, prev), {
@@ -658,11 +797,26 @@ function getOptionalScopes(scopes) {
658
797
  {}
659
798
  );
660
799
  }
800
+ function normalizeNativeUrl(url) {
801
+ var _a3;
802
+ const httpPattern = /^https?:\/\//u;
803
+ if (httpPattern.test(url)) {
804
+ return void 0;
805
+ }
806
+ const schemeMatch = url.match(/^([^:]*):\/\//u);
807
+ const rawScheme = (_a3 = schemeMatch == null ? void 0 : schemeMatch[1]) != null ? _a3 : url;
808
+ const sanitized = rawScheme.toLowerCase().replace(/[^a-z0-9-]/gu, "-").replace(/^-+|-+$/gu, "");
809
+ const subdomain = (sanitized || "unknown").slice(0, 63).replace(/-+$/u, "");
810
+ return {
811
+ url: `https://${subdomain}.rn.dapp.local`,
812
+ nativeScheme: url
813
+ };
814
+ }
661
815
  function setupDappMetadata(options) {
662
- var _a2, _b;
816
+ var _a3, _b;
663
817
  const platform = getPlatformType();
664
818
  const isBrowser = platform === "web-desktop" /* DesktopWeb */ || platform === "web-mobile" /* MobileWeb */ || platform === "in-app-browser" /* MetaMaskMobileWebview */;
665
- if (!((_a2 = options.dapp) == null ? void 0 : _a2.name)) {
819
+ if (!((_a3 = options.dapp) == null ? void 0 : _a3.name)) {
666
820
  throw new Error("You must provide dapp name");
667
821
  }
668
822
  if (isBrowser) {
@@ -673,6 +827,18 @@ function setupDappMetadata(options) {
673
827
  if (!((_b = options.dapp) == null ? void 0 : _b.url)) {
674
828
  throw new Error("You must provide dapp url");
675
829
  }
830
+ if (platform === "react-native" /* ReactNative */ && options.dapp.url) {
831
+ const normalized = normalizeNativeUrl(options.dapp.url);
832
+ if (normalized) {
833
+ console.info(
834
+ `Normalizing dapp URL for React Native: "${options.dapp.url}" -> "${normalized.url}"`
835
+ );
836
+ options.dapp = __spreadProps(__spreadValues({}, options.dapp), {
837
+ url: normalized.url,
838
+ nativeScheme: normalized.nativeScheme
839
+ });
840
+ }
841
+ }
676
842
  const BASE_64_ICON_MAX_LENGTH = 163400;
677
843
  const urlPattern = /^(http|https):\/\/[^\s]*$/u;
678
844
  if (options.dapp) {
@@ -736,17 +902,17 @@ function getValidAccounts(caipAccountIds) {
736
902
  );
737
903
  }
738
904
  function addValidAccounts(optionalScopes, validAccounts) {
739
- var _a2;
905
+ var _a3;
740
906
  if (!optionalScopes || !(validAccounts == null ? void 0 : validAccounts.length)) {
741
907
  return optionalScopes;
742
908
  }
743
909
  const result = Object.fromEntries(
744
910
  Object.entries(optionalScopes).map(([scope, scopeData]) => {
745
- var _a3, _b, _c;
911
+ var _a4, _b, _c;
746
912
  return [
747
913
  scope,
748
914
  {
749
- methods: [...(_a3 = scopeData == null ? void 0 : scopeData.methods) != null ? _a3 : []],
915
+ methods: [...(_a4 = scopeData == null ? void 0 : scopeData.methods) != null ? _a4 : []],
750
916
  notifications: [...(_b = scopeData == null ? void 0 : scopeData.notifications) != null ? _b : []],
751
917
  accounts: [...(_c = scopeData == null ? void 0 : scopeData.accounts) != null ? _c : []]
752
918
  }
@@ -760,7 +926,7 @@ function addValidAccounts(optionalScopes, validAccounts) {
760
926
  if (!accountsByChain.has(chainKey)) {
761
927
  accountsByChain.set(chainKey, []);
762
928
  }
763
- (_a2 = accountsByChain.get(chainKey)) == null ? void 0 : _a2.push(accountId);
929
+ (_a3 = accountsByChain.get(chainKey)) == null ? void 0 : _a3.push(accountId);
764
930
  }
765
931
  for (const [scopeKey, scopeData] of Object.entries(result)) {
766
932
  if (!(scopeData == null ? void 0 : scopeData.accounts)) {
@@ -784,15 +950,15 @@ function addValidAccounts(optionalScopes, validAccounts) {
784
950
  }
785
951
  return result;
786
952
  }
787
- var import_utils, import_pako, extractFavicon;
788
- var init_utils = __esm({
953
+ var import_utils, import_pako, extractFavicon, MAX, idCounter, getUniqueRequestId;
954
+ var init_utils2 = __esm({
789
955
  "src/multichain/utils/index.ts"() {
790
956
  "use strict";
791
957
  import_utils = require("@metamask/utils");
792
958
  import_pako = require("pako");
793
959
  init_domain();
794
960
  extractFavicon = () => {
795
- var _a2;
961
+ var _a3;
796
962
  if (typeof document === "undefined") {
797
963
  return void 0;
798
964
  }
@@ -800,92 +966,17 @@ var init_utils = __esm({
800
966
  const nodeList = document.getElementsByTagName("link");
801
967
  for (let i = 0; i < nodeList.length; i++) {
802
968
  if (nodeList[i].getAttribute("rel") === "icon" || nodeList[i].getAttribute("rel") === "shortcut icon") {
803
- favicon = (_a2 = nodeList[i].getAttribute("href")) != null ? _a2 : void 0;
969
+ favicon = (_a3 = nodeList[i].getAttribute("href")) != null ? _a3 : void 0;
804
970
  }
805
971
  }
806
972
  return favicon;
807
973
  };
808
- }
809
- });
810
-
811
- // src/multichain/utils/analytics.ts
812
- function isRejectionError(error) {
813
- var _a2, _b;
814
- if (typeof error !== "object" || error === null) {
815
- return false;
816
- }
817
- const errorObj = error;
818
- const errorCode = errorObj.code;
819
- const errorMessage = (_b = (_a2 = errorObj.message) == null ? void 0 : _a2.toLowerCase()) != null ? _b : "";
820
- return errorCode === 4001 || // User rejected request (common EIP-1193 code)
821
- errorCode === 4100 || // Unauthorized (common rejection code)
822
- errorMessage.includes("reject") || errorMessage.includes("denied") || errorMessage.includes("cancel") || errorMessage.includes("user");
823
- }
824
- function getBaseAnalyticsProperties(options, storage) {
825
- return __async(this, null, function* () {
826
- var _a2, _b;
827
- const version = getVersion();
828
- const dappId = getDappId(options.dapp);
829
- const platform = getPlatformType();
830
- const anonId = yield storage.getAnonId();
831
- const integrationType = (_b = (_a2 = options.analytics) == null ? void 0 : _a2.integrationType) != null ? _b : "unknown" /* UNKNOWN */;
832
- return {
833
- mmconnect_version: version,
834
- dapp_id: dappId,
835
- platform,
836
- integration_type: integrationType,
837
- anon_id: anonId
838
- };
839
- });
840
- }
841
- function getWalletActionAnalyticsProperties(options, storage, invokeOptions) {
842
- return __async(this, null, function* () {
843
- var _a2, _b;
844
- const version = getVersion();
845
- const dappId = getDappId(options.dapp);
846
- const anonId = yield storage.getAnonId();
847
- const integrationType = (_b = (_a2 = options.analytics) == null ? void 0 : _a2.integrationType) != null ? _b : "unknown";
848
- return {
849
- mmconnect_version: version,
850
- dapp_id: dappId,
851
- method: invokeOptions.request.method,
852
- integration_type: integrationType,
853
- caip_chain_id: invokeOptions.scope,
854
- anon_id: anonId
974
+ MAX = 4294967295;
975
+ idCounter = Math.floor(Math.random() * MAX);
976
+ getUniqueRequestId = () => {
977
+ idCounter = (idCounter + 1) % MAX;
978
+ return idCounter;
855
979
  };
856
- });
857
- }
858
- var init_analytics = __esm({
859
- "src/multichain/utils/analytics.ts"() {
860
- "use strict";
861
- init_utils();
862
- init_domain();
863
- }
864
- });
865
-
866
- // src/domain/utils/index.ts
867
- function getVersion() {
868
- return "0.0.0";
869
- }
870
- var init_utils2 = __esm({
871
- "src/domain/utils/index.ts"() {
872
- "use strict";
873
- init_analytics();
874
- }
875
- });
876
-
877
- // src/domain/index.ts
878
- var init_domain = __esm({
879
- "src/domain/index.ts"() {
880
- "use strict";
881
- init_errors();
882
- init_events();
883
- init_logger();
884
- init_multichain();
885
- init_platform();
886
- init_store();
887
- init_ui();
888
- init_utils2();
889
980
  }
890
981
  });
891
982
 
@@ -1014,7 +1105,7 @@ var init_install = __esm({
1014
1105
  renderQRCode() {
1015
1106
  }
1016
1107
  mount() {
1017
- var _a2;
1108
+ var _a3;
1018
1109
  const { options } = this;
1019
1110
  const modal = document.createElement(
1020
1111
  "mm-install-modal"
@@ -1031,14 +1122,14 @@ var init_install = __esm({
1031
1122
  );
1032
1123
  modal.link = options.link;
1033
1124
  this.instance = modal;
1034
- (_a2 = options.parentElement) == null ? void 0 : _a2.appendChild(modal);
1125
+ (_a3 = options.parentElement) == null ? void 0 : _a3.appendChild(modal);
1035
1126
  this.startExpirationCheck(options.connectionRequest);
1036
1127
  }
1037
1128
  unmount() {
1038
- var _a2;
1129
+ var _a3;
1039
1130
  const { options, instance: modal } = this;
1040
1131
  this.stopExpirationCheck();
1041
- if (modal && ((_a2 = options.parentElement) == null ? void 0 : _a2.contains(modal))) {
1132
+ if (modal && ((_a3 = options.parentElement) == null ? void 0 : _a3.contains(modal))) {
1042
1133
  options.parentElement.removeChild(modal);
1043
1134
  this.instance = void 0;
1044
1135
  }
@@ -1150,8 +1241,8 @@ var init_web2 = __esm({
1150
1241
  const request = store.get(key);
1151
1242
  request.onerror = () => reject(new Error("Failed to get value from IndexedDB."));
1152
1243
  request.onsuccess = () => {
1153
- var _a2;
1154
- return resolve((_a2 = request.result) != null ? _a2 : null);
1244
+ var _a3;
1245
+ return resolve((_a3 = request.result) != null ? _a3 : null);
1155
1246
  };
1156
1247
  } catch (error) {
1157
1248
  reject(error);
@@ -1195,7 +1286,7 @@ var init_web2 = __esm({
1195
1286
  }
1196
1287
  };
1197
1288
  _StoreAdapterWeb.stores = ["sdk-kv-store", "key-value-pairs"];
1198
- _StoreAdapterWeb.DB_NAME = "mmsdk";
1289
+ _StoreAdapterWeb.DB_NAME = "mmconnect";
1199
1290
  StoreAdapterWeb = _StoreAdapterWeb;
1200
1291
  }
1201
1292
  });
@@ -1235,10 +1326,10 @@ module.exports = __toCommonJS(index_browser_exports);
1235
1326
 
1236
1327
  // src/polyfills/buffer-shim.ts
1237
1328
  var import_buffer = require("buffer");
1238
- var globalObj = typeof globalThis !== "undefined" ? globalThis : typeof global !== "undefined" ? global : typeof window !== "undefined" ? window : {};
1239
- if (!globalObj.Buffer) {
1240
- globalObj.Buffer = import_buffer.Buffer;
1241
- }
1329
+ init_utils2();
1330
+ var globalObj = getGlobalObject();
1331
+ var _a;
1332
+ (_a = globalObj.Buffer) != null ? _a : globalObj.Buffer = import_buffer.Buffer;
1242
1333
 
1243
1334
  // src/index.browser.ts
1244
1335
  init_domain();
@@ -1304,8 +1395,8 @@ var RpcClient = class {
1304
1395
  });
1305
1396
  }
1306
1397
  getRpcEndpoint(scope) {
1307
- var _a2, _b, _c;
1308
- const supportedNetworks = (_c = (_b = (_a2 = this.config) == null ? void 0 : _a2.api) == null ? void 0 : _b.supportedNetworks) != null ? _c : {};
1398
+ var _a3, _b, _c;
1399
+ const supportedNetworks = (_c = (_b = (_a3 = this.config) == null ? void 0 : _a3.api) == null ? void 0 : _b.supportedNetworks) != null ? _c : {};
1309
1400
  const rpcEndpoint = supportedNetworks[scope];
1310
1401
  if (!rpcEndpoint) {
1311
1402
  throw new MissingRpcEndpointErr(
@@ -1369,7 +1460,7 @@ var RpcClient = class {
1369
1460
  // src/multichain/rpc/requestRouter.ts
1370
1461
  var import_analytics2 = require("@metamask/analytics");
1371
1462
  init_domain();
1372
- init_utils();
1463
+ init_utils2();
1373
1464
  init_analytics();
1374
1465
  var _RequestRouter_instances, withAnalyticsTracking_fn, trackWalletActionRequested_fn, trackWalletActionSucceeded_fn, trackWalletActionFailed_fn, trackWalletActionRejected_fn;
1375
1466
  var RequestRouter = class {
@@ -1537,9 +1628,9 @@ trackWalletActionRejected_fn = function(options) {
1537
1628
 
1538
1629
  // src/multichain/transports/default/index.ts
1539
1630
  var import_multichain_api_client = require("@metamask/multichain-api-client");
1540
- init_utils();
1631
+ init_utils2();
1541
1632
  var DEFAULT_REQUEST_TIMEOUT = 60 * 1e3;
1542
- var _notificationCallbacks, _transport, _defaultRequestOptions, _reqId, _pendingRequests, _handleResponseListener, _handleNotificationListener, _DefaultTransport_instances, notifyCallbacks_fn, isMetamaskProviderEvent_fn, handleResponse_fn, handleNotification_fn, setupMessageListener_fn;
1633
+ var _notificationCallbacks, _transport, _defaultRequestOptions, _pendingRequests, _handleResponseListener, _handleNotificationListener, _DefaultTransport_instances, notifyCallbacks_fn, isMetamaskProviderEvent_fn, handleResponse_fn, handleNotification_fn, setupMessageListener_fn;
1543
1634
  var DefaultTransport = class {
1544
1635
  constructor() {
1545
1636
  __privateAdd(this, _DefaultTransport_instances);
@@ -1548,8 +1639,6 @@ var DefaultTransport = class {
1548
1639
  __privateAdd(this, _defaultRequestOptions, {
1549
1640
  timeout: DEFAULT_REQUEST_TIMEOUT
1550
1641
  });
1551
- // Use timestamp-based ID to avoid conflicts across disconnect/reconnect cycles
1552
- __privateAdd(this, _reqId, Date.now());
1553
1642
  __privateAdd(this, _pendingRequests, /* @__PURE__ */ new Map());
1554
1643
  __privateAdd(this, _handleResponseListener);
1555
1644
  __privateAdd(this, _handleNotificationListener);
@@ -1557,18 +1646,17 @@ var DefaultTransport = class {
1557
1646
  sendEip1193Message(payload, options) {
1558
1647
  return __async(this, null, function* () {
1559
1648
  __privateMethod(this, _DefaultTransport_instances, setupMessageListener_fn).call(this);
1560
- __privateSet(this, _reqId, __privateGet(this, _reqId) + 1);
1561
- const requestId = `${__privateGet(this, _reqId)}`;
1649
+ const requestId = String(getUniqueRequestId());
1562
1650
  const request = __spreadValues({
1563
1651
  jsonrpc: "2.0",
1564
1652
  id: requestId
1565
1653
  }, payload);
1566
1654
  return new Promise((resolve, reject) => {
1567
- var _a2;
1655
+ var _a3;
1568
1656
  const timeout = setTimeout(() => {
1569
1657
  __privateGet(this, _pendingRequests).delete(requestId);
1570
1658
  reject(new Error("Request timeout"));
1571
- }, (_a2 = options == null ? void 0 : options.timeout) != null ? _a2 : __privateGet(this, _defaultRequestOptions).timeout);
1659
+ }, (_a3 = options == null ? void 0 : options.timeout) != null ? _a3 : __privateGet(this, _defaultRequestOptions).timeout);
1572
1660
  __privateGet(this, _pendingRequests).set(requestId, {
1573
1661
  resolve: (response) => {
1574
1662
  resolve(response);
@@ -1592,7 +1680,7 @@ var DefaultTransport = class {
1592
1680
  }
1593
1681
  connect(options) {
1594
1682
  return __async(this, null, function* () {
1595
- var _a2, _b, _c, _d, _e;
1683
+ var _a3, _b, _c, _d, _e;
1596
1684
  __privateMethod(this, _DefaultTransport_instances, setupMessageListener_fn).call(this);
1597
1685
  yield __privateGet(this, _transport).connect();
1598
1686
  const sessionRequest = yield this.request(
@@ -1605,7 +1693,7 @@ var DefaultTransport = class {
1605
1693
  let walletSession = sessionRequest.result;
1606
1694
  const createSessionParams = {
1607
1695
  optionalScopes: addValidAccounts(
1608
- getOptionalScopes((_a2 = options == null ? void 0 : options.scopes) != null ? _a2 : []),
1696
+ getOptionalScopes((_a3 = options == null ? void 0 : options.scopes) != null ? _a3 : []),
1609
1697
  getValidAccounts((_b = options == null ? void 0 : options.caipAccountIds) != null ? _b : [])
1610
1698
  ),
1611
1699
  sessionProperties: options == null ? void 0 : options.sessionProperties
@@ -1623,10 +1711,6 @@ var DefaultTransport = class {
1623
1711
  proposedCaipAccountIds
1624
1712
  );
1625
1713
  if (!hasSameScopesAndAccounts) {
1626
- yield this.request(
1627
- { method: "wallet_revokeSession", params: walletSession },
1628
- __privateGet(this, _defaultRequestOptions)
1629
- );
1630
1714
  const response = yield this.request(
1631
1715
  { method: "wallet_createSession", params: createSessionParams },
1632
1716
  __privateGet(this, _defaultRequestOptions)
@@ -1653,9 +1737,14 @@ var DefaultTransport = class {
1653
1737
  });
1654
1738
  }
1655
1739
  disconnect() {
1656
- return __async(this, null, function* () {
1740
+ return __async(this, arguments, function* (scopes = []) {
1741
+ yield this.request({ method: "wallet_revokeSession", params: { scopes } });
1742
+ const response = yield this.request({ method: "wallet_getSession" });
1743
+ const { sessionScopes } = response.result;
1744
+ if (Object.keys(sessionScopes).length > 0) {
1745
+ return;
1746
+ }
1657
1747
  __privateGet(this, _notificationCallbacks).clear();
1658
- yield this.request({ method: "wallet_revokeSession", params: {} });
1659
1748
  if (__privateGet(this, _handleResponseListener)) {
1660
1749
  window.removeEventListener("message", __privateGet(this, _handleResponseListener));
1661
1750
  __privateSet(this, _handleResponseListener, void 0);
@@ -1669,7 +1758,7 @@ var DefaultTransport = class {
1669
1758
  request.reject(new Error("Transport disconnected"));
1670
1759
  }
1671
1760
  __privateGet(this, _pendingRequests).clear();
1672
- return __privateGet(this, _transport).disconnect();
1761
+ yield __privateGet(this, _transport).disconnect();
1673
1762
  });
1674
1763
  }
1675
1764
  isConnected() {
@@ -1694,11 +1783,17 @@ var DefaultTransport = class {
1694
1783
  );
1695
1784
  });
1696
1785
  }
1786
+ getStoredPendingSessionRequest() {
1787
+ return __async(this, null, function* () {
1788
+ throw new Error(
1789
+ "getStoredPendingSessionRequest is purposely not implemented for the DefaultTransport"
1790
+ );
1791
+ });
1792
+ }
1697
1793
  };
1698
1794
  _notificationCallbacks = new WeakMap();
1699
1795
  _transport = new WeakMap();
1700
1796
  _defaultRequestOptions = new WeakMap();
1701
- _reqId = new WeakMap();
1702
1797
  _pendingRequests = new WeakMap();
1703
1798
  _handleResponseListener = new WeakMap();
1704
1799
  _handleNotificationListener = new WeakMap();
@@ -1716,16 +1811,16 @@ notifyCallbacks_fn = function(data) {
1716
1811
  }
1717
1812
  };
1718
1813
  isMetamaskProviderEvent_fn = function(event) {
1719
- var _a2, _b;
1720
- 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
1814
+ var _a3, _b;
1815
+ return ((_b = (_a3 = event == null ? void 0 : event.data) == null ? void 0 : _a3.data) == null ? void 0 : _b.name) === "metamask-provider" && // eslint-disable-next-line no-restricted-globals
1721
1816
  event.origin === location.origin;
1722
1817
  };
1723
1818
  handleResponse_fn = function(event) {
1724
- var _a2, _b;
1819
+ var _a3, _b;
1725
1820
  if (!__privateMethod(this, _DefaultTransport_instances, isMetamaskProviderEvent_fn).call(this, event)) {
1726
1821
  return;
1727
1822
  }
1728
- const responseData = (_b = (_a2 = event == null ? void 0 : event.data) == null ? void 0 : _a2.data) == null ? void 0 : _b.data;
1823
+ const responseData = (_b = (_a3 = event == null ? void 0 : event.data) == null ? void 0 : _a3.data) == null ? void 0 : _b.data;
1729
1824
  if (typeof responseData === "object" && responseData !== null && "method" in responseData) {
1730
1825
  return;
1731
1826
  }
@@ -1747,11 +1842,11 @@ handleResponse_fn = function(event) {
1747
1842
  }
1748
1843
  };
1749
1844
  handleNotification_fn = function(event) {
1750
- var _a2, _b;
1845
+ var _a3, _b;
1751
1846
  if (!__privateMethod(this, _DefaultTransport_instances, isMetamaskProviderEvent_fn).call(this, event)) {
1752
1847
  return;
1753
1848
  }
1754
- const responseData = (_b = (_a2 = event == null ? void 0 : event.data) == null ? void 0 : _a2.data) == null ? void 0 : _b.data;
1849
+ const responseData = (_b = (_a3 = event == null ? void 0 : event.data) == null ? void 0 : _a3.data) == null ? void 0 : _b.data;
1755
1850
  if (typeof responseData === "object" && responseData.method === "metamask_chainChanged" || responseData.method === "metamask_accountsChanged") {
1756
1851
  __privateMethod(this, _DefaultTransport_instances, notifyCallbacks_fn).call(this, responseData);
1757
1852
  }
@@ -1768,18 +1863,12 @@ setupMessageListener_fn = function() {
1768
1863
 
1769
1864
  // src/multichain/transports/multichainApiClientWrapper/index.ts
1770
1865
  var import_rpc_errors = require("@metamask/rpc-errors");
1771
- var MAX = 4294967295;
1772
- var idCounter = Math.floor(Math.random() * MAX);
1773
- var getUniqueId = () => {
1774
- idCounter = (idCounter + 1) % MAX;
1775
- return idCounter;
1776
- };
1777
- var _requestId, _notificationCallbacks2, _MultichainApiClientWrapperTransport_instances, walletCreateSession_fn, walletGetSession_fn, walletRevokeSession_fn, walletInvokeMethod_fn;
1866
+ init_utils2();
1867
+ var _notificationCallbacks2, _MultichainApiClientWrapperTransport_instances, walletCreateSession_fn, walletGetSession_fn, walletRevokeSession_fn, walletInvokeMethod_fn;
1778
1868
  var MultichainApiClientWrapperTransport = class {
1779
1869
  constructor(metamaskConnectMultichain) {
1780
1870
  this.metamaskConnectMultichain = metamaskConnectMultichain;
1781
1871
  __privateAdd(this, _MultichainApiClientWrapperTransport_instances);
1782
- __privateAdd(this, _requestId, getUniqueId());
1783
1872
  __privateAdd(this, _notificationCallbacks2, /* @__PURE__ */ new Set());
1784
1873
  }
1785
1874
  isTransportDefined() {
@@ -1797,15 +1886,23 @@ var MultichainApiClientWrapperTransport = class {
1797
1886
  callback(data);
1798
1887
  });
1799
1888
  }
1800
- setupNotifcationListener() {
1801
- this.metamaskConnectMultichain.transport.onNotification(
1889
+ clearTransportNotificationListener() {
1890
+ var _a3;
1891
+ (_a3 = this.notificationListener) == null ? void 0 : _a3.call(this);
1892
+ this.notificationListener = void 0;
1893
+ }
1894
+ setupTransportNotificationListener() {
1895
+ if (!this.isTransportDefined() || this.notificationListener) {
1896
+ return;
1897
+ }
1898
+ this.notificationListener = this.metamaskConnectMultichain.transport.onNotification(
1802
1899
  this.notifyCallbacks.bind(this)
1803
1900
  );
1804
1901
  }
1805
1902
  connect() {
1806
1903
  return __async(this, null, function* () {
1807
1904
  console.log("\u{1F4DA} connect");
1808
- return Promise.resolve();
1905
+ yield this.metamaskConnectMultichain.emitSessionChanged();
1809
1906
  });
1810
1907
  }
1811
1908
  disconnect() {
@@ -1818,7 +1915,7 @@ var MultichainApiClientWrapperTransport = class {
1818
1915
  }
1819
1916
  request(_0) {
1820
1917
  return __async(this, arguments, function* (params, _options = {}) {
1821
- const id = __privateWrapper(this, _requestId)._++;
1918
+ const id = getUniqueRequestId();
1822
1919
  const requestPayload = __spreadValues({
1823
1920
  id,
1824
1921
  jsonrpc: "2.0"
@@ -1839,27 +1936,23 @@ var MultichainApiClientWrapperTransport = class {
1839
1936
  });
1840
1937
  }
1841
1938
  onNotification(callback) {
1842
- if (!this.isTransportDefined()) {
1843
- __privateGet(this, _notificationCallbacks2).add(callback);
1844
- return () => {
1845
- __privateGet(this, _notificationCallbacks2).delete(callback);
1846
- };
1847
- }
1848
- return this.metamaskConnectMultichain.transport.onNotification(callback);
1939
+ this.setupTransportNotificationListener();
1940
+ __privateGet(this, _notificationCallbacks2).add(callback);
1941
+ return () => {
1942
+ __privateGet(this, _notificationCallbacks2).delete(callback);
1943
+ };
1849
1944
  }
1850
1945
  };
1851
- _requestId = new WeakMap();
1852
1946
  _notificationCallbacks2 = new WeakMap();
1853
1947
  _MultichainApiClientWrapperTransport_instances = new WeakSet();
1854
1948
  walletCreateSession_fn = function(request) {
1855
1949
  return __async(this, null, function* () {
1856
- console.log("\u{1F4DA} #walletCreateSession", request);
1857
1950
  const createSessionParams = request.params;
1858
1951
  const scopes = Object.keys(__spreadValues(__spreadValues({}, createSessionParams.optionalScopes), createSessionParams.requiredScopes));
1859
1952
  const scopeAccounts = [];
1860
1953
  scopes.forEach((scope) => {
1861
- var _a2, _b, _c, _d;
1862
- const requiredScope = (_a2 = createSessionParams.requiredScopes) == null ? void 0 : _a2[scope];
1954
+ var _a3, _b, _c, _d;
1955
+ const requiredScope = (_a3 = createSessionParams.requiredScopes) == null ? void 0 : _a3[scope];
1863
1956
  const optionalScope = (_b = createSessionParams.optionalScopes) == null ? void 0 : _b[scope];
1864
1957
  if (requiredScope) {
1865
1958
  scopeAccounts.push(...(_c = requiredScope.accounts) != null ? _c : []);
@@ -1899,11 +1992,14 @@ walletGetSession_fn = function(request) {
1899
1992
  };
1900
1993
  walletRevokeSession_fn = function(request) {
1901
1994
  return __async(this, null, function* () {
1995
+ var _a3;
1902
1996
  if (!this.isTransportDefined()) {
1903
1997
  return { jsonrpc: "2.0", id: request.id, result: true };
1904
1998
  }
1999
+ const revokeSessionParams = request.params;
2000
+ const scopes = (_a3 = revokeSessionParams == null ? void 0 : revokeSessionParams.scopes) != null ? _a3 : [];
1905
2001
  try {
1906
- this.metamaskConnectMultichain.disconnect();
2002
+ yield this.metamaskConnectMultichain.disconnect(scopes);
1907
2003
  return { jsonrpc: "2.0", id: request.id, result: true };
1908
2004
  } catch (_error) {
1909
2005
  return { jsonrpc: "2.0", id: request.id, result: false };
@@ -1927,8 +2023,9 @@ walletInvokeMethod_fn = function(request) {
1927
2023
  // src/multichain/transports/mwp/index.ts
1928
2024
  var import_mobile_wallet_protocol_core = require("@metamask/mobile-wallet-protocol-core");
1929
2025
  var import_multichain_api_client2 = require("@metamask/multichain-api-client");
2026
+ var import_rpc_errors2 = require("@metamask/rpc-errors");
1930
2027
  init_domain();
1931
- init_utils();
2028
+ init_utils2();
1932
2029
 
1933
2030
  // src/multichain/transports/constants.ts
1934
2031
  var MULTICHAIN_PROVIDER_STREAM_NAME = "metamask-multichain-provider";
@@ -1941,6 +2038,7 @@ var DEFAULT_RESUME_TIMEOUT = 10 * 1e3;
1941
2038
  var SESSION_STORE_KEY = "cache_wallet_getSession";
1942
2039
  var ACCOUNTS_STORE_KEY = "cache_eth_accounts";
1943
2040
  var CHAIN_STORE_KEY = "cache_eth_chainId";
2041
+ var PENDING_SESSION_REQUEST_KEY = "pending_session_request";
1944
2042
  var CACHED_METHOD_LIST = [
1945
2043
  "wallet_getSession",
1946
2044
  "wallet_createSession",
@@ -1960,10 +2058,15 @@ var MWPTransport = class {
1960
2058
  this.dappClient = dappClient;
1961
2059
  this.kvstore = kvstore;
1962
2060
  this.options = options;
1963
- this.__reqId = 0;
1964
2061
  this.__pendingRequests = /* @__PURE__ */ new Map();
1965
2062
  this.notificationCallbacks = /* @__PURE__ */ new Set();
1966
2063
  this.dappClient.on("message", this.handleMessage.bind(this));
2064
+ this.dappClient.on("session_request", (sessionRequest) => {
2065
+ this.currentSessionRequest = sessionRequest;
2066
+ this.kvstore.set(PENDING_SESSION_REQUEST_KEY, JSON.stringify(sessionRequest)).catch((err) => {
2067
+ logger("Failed to store pending session request", err);
2068
+ });
2069
+ });
1967
2070
  if (typeof window !== "undefined" && typeof window.addEventListener !== "undefined") {
1968
2071
  this.windowFocusHandler = this.onWindowFocus.bind(this);
1969
2072
  window.addEventListener("focus", this.windowFocusHandler);
@@ -1978,6 +2081,34 @@ var MWPTransport = class {
1978
2081
  get sessionRequest() {
1979
2082
  return this.currentSessionRequest;
1980
2083
  }
2084
+ /**
2085
+ * Returns the stored pending session request from the dappClient session_request event, if any.
2086
+ *
2087
+ * @returns The stored SessionRequest, or null if none or invalid.
2088
+ */
2089
+ getStoredPendingSessionRequest() {
2090
+ return __async(this, null, function* () {
2091
+ try {
2092
+ const raw = yield this.kvstore.get(PENDING_SESSION_REQUEST_KEY);
2093
+ if (!raw) {
2094
+ return null;
2095
+ }
2096
+ return JSON.parse(raw);
2097
+ } catch (e) {
2098
+ return null;
2099
+ }
2100
+ });
2101
+ }
2102
+ /**
2103
+ * Removes the stored pending session request from the KVStore.
2104
+ * This is necessary to ensure that ConnectMultichain is able to correctly
2105
+ * infer the MWP Transport connection attempt status.
2106
+ */
2107
+ removeStoredPendingSessionRequest() {
2108
+ return __async(this, null, function* () {
2109
+ yield this.kvstore.delete(PENDING_SESSION_REQUEST_KEY);
2110
+ });
2111
+ }
1981
2112
  onWindowFocus() {
1982
2113
  if (!this.isConnected()) {
1983
2114
  this.dappClient.reconnect();
@@ -1994,6 +2125,18 @@ var MWPTransport = class {
1994
2125
  request.reject(error);
1995
2126
  }
1996
2127
  }
2128
+ parseWalletError(errorPayload) {
2129
+ const errorData = errorPayload;
2130
+ if (typeof errorData.code === "number" && typeof errorData.message === "string") {
2131
+ const { code, message: message2 } = errorData;
2132
+ if (code >= 1e3 && code <= 4999) {
2133
+ return import_rpc_errors2.providerErrors.custom({ code, message: message2 });
2134
+ }
2135
+ return new import_rpc_errors2.JsonRpcError(code, message2);
2136
+ }
2137
+ const message = errorPayload instanceof Error ? errorPayload.message : JSON.stringify(errorPayload);
2138
+ return import_rpc_errors2.rpcErrors.internal({ message });
2139
+ }
1997
2140
  handleMessage(message) {
1998
2141
  if (typeof message === "object" && message !== null) {
1999
2142
  if ("data" in message) {
@@ -2001,6 +2144,12 @@ var MWPTransport = class {
2001
2144
  if ("id" in messagePayload && typeof messagePayload.id === "string") {
2002
2145
  const request = this.pendingRequests.get(messagePayload.id);
2003
2146
  if (request) {
2147
+ clearTimeout(request.timeout);
2148
+ if ("error" in messagePayload && messagePayload.error) {
2149
+ this.pendingRequests.delete(messagePayload.id);
2150
+ request.reject(this.parseWalletError(messagePayload.error));
2151
+ return;
2152
+ }
2004
2153
  const requestWithName = __spreadProps(__spreadValues({}, messagePayload), {
2005
2154
  method: request.method === "wallet_getSession" || request.method === "wallet_createSession" ? "wallet_sessionChanged" : request.method
2006
2155
  });
@@ -2008,7 +2157,6 @@ var MWPTransport = class {
2008
2157
  method: request.method === "wallet_getSession" || request.method === "wallet_createSession" ? "wallet_sessionChanged" : request.method,
2009
2158
  params: requestWithName.result
2010
2159
  });
2011
- clearTimeout(request.timeout);
2012
2160
  this.notifyCallbacks(notification);
2013
2161
  request.resolve(requestWithName);
2014
2162
  this.pendingRequests.delete(messagePayload.id);
@@ -2044,7 +2192,7 @@ var MWPTransport = class {
2044
2192
  }
2045
2193
  onResumeSuccess(resumeResolve, resumeReject, options) {
2046
2194
  return __async(this, null, function* () {
2047
- var _a2, _b, _c, _d, _e, _f, _g;
2195
+ var _a3, _b, _c, _d, _e, _f, _g;
2048
2196
  try {
2049
2197
  yield this.waitForWalletSessionIfNotCached();
2050
2198
  const sessionRequest = yield this.request({
@@ -2056,7 +2204,7 @@ var MWPTransport = class {
2056
2204
  let walletSession = sessionRequest.result;
2057
2205
  if (walletSession && options) {
2058
2206
  const currentScopes = Object.keys(
2059
- (_a2 = walletSession == null ? void 0 : walletSession.sessionScopes) != null ? _a2 : {}
2207
+ (_a3 = walletSession == null ? void 0 : walletSession.sessionScopes) != null ? _a3 : {}
2060
2208
  );
2061
2209
  const proposedScopes = (_b = options == null ? void 0 : options.scopes) != null ? _b : [];
2062
2210
  const proposedCaipAccountIds = (_c = options == null ? void 0 : options.caipAccountIds) != null ? _c : [];
@@ -2098,6 +2246,7 @@ var MWPTransport = class {
2098
2246
  }
2099
2247
  walletSession = response.result;
2100
2248
  }
2249
+ yield this.removeStoredPendingSessionRequest();
2101
2250
  this.notifyCallbacks({
2102
2251
  method: "wallet_sessionChanged",
2103
2252
  params: walletSession
@@ -2113,7 +2262,7 @@ var MWPTransport = class {
2113
2262
  return __async(this, null, function* () {
2114
2263
  const request = __spreadValues({
2115
2264
  jsonrpc: "2.0",
2116
- id: `${this.__reqId++}`
2265
+ id: String(getUniqueRequestId())
2117
2266
  }, payload);
2118
2267
  const cachedWalletSession = yield this.getCachedResponse(request);
2119
2268
  if (cachedWalletSession) {
@@ -2121,10 +2270,10 @@ var MWPTransport = class {
2121
2270
  return cachedWalletSession;
2122
2271
  }
2123
2272
  return new Promise((resolve, reject) => {
2124
- var _a2;
2273
+ var _a3;
2125
2274
  const timeout = setTimeout(() => {
2126
2275
  this.rejectRequest(request.id, new import_multichain_api_client2.TransportTimeoutError());
2127
- }, (_a2 = options == null ? void 0 : options.timeout) != null ? _a2 : this.options.requestTimeout);
2276
+ }, (_a3 = options == null ? void 0 : options.timeout) != null ? _a3 : this.options.requestTimeout);
2128
2277
  this.pendingRequests.set(request.id, {
2129
2278
  request,
2130
2279
  method: request.method,
@@ -2147,30 +2296,35 @@ var MWPTransport = class {
2147
2296
  const { dappClient } = this;
2148
2297
  const session = yield this.getActiveSession();
2149
2298
  if (session) {
2150
- logger("active session found", session);
2299
+ logger("active session found", {
2300
+ id: session.id,
2301
+ channel: session.channel,
2302
+ expiresAt: session.expiresAt
2303
+ });
2151
2304
  }
2305
+ const storedSessionRequestBeforeConnectionAttempt = yield this.getStoredPendingSessionRequest();
2152
2306
  let timeout;
2153
2307
  let initialConnectionMessageHandler;
2154
2308
  const connectionPromise = new Promise((resolve, reject) => __async(this, null, function* () {
2155
2309
  let connection;
2156
2310
  if (session) {
2157
2311
  connection = new Promise((resumeResolve, resumeReject) => {
2158
- var _a2;
2312
+ var _a3;
2159
2313
  if (this.dappClient.state === "CONNECTED") {
2160
2314
  this.onResumeSuccess(resumeResolve, resumeReject, options);
2161
2315
  } else {
2162
2316
  this.dappClient.once("connected", () => __async(this, null, function* () {
2163
2317
  this.onResumeSuccess(resumeResolve, resumeReject, options);
2164
2318
  }));
2165
- dappClient.resume((_a2 = session == null ? void 0 : session.id) != null ? _a2 : "");
2319
+ dappClient.resume((_a3 = session == null ? void 0 : session.id) != null ? _a3 : "");
2166
2320
  }
2167
2321
  });
2168
2322
  } else {
2169
2323
  connection = new Promise(
2170
2324
  (resolveConnection, rejectConnection) => {
2171
- var _a2, _b;
2325
+ var _a3, _b;
2172
2326
  const optionalScopes = addValidAccounts(
2173
- getOptionalScopes((_a2 = options == null ? void 0 : options.scopes) != null ? _a2 : []),
2327
+ getOptionalScopes((_a3 = options == null ? void 0 : options.scopes) != null ? _a3 : []),
2174
2328
  getValidAccounts((_b = options == null ? void 0 : options.caipAccountIds) != null ? _b : [])
2175
2329
  );
2176
2330
  const sessionRequest = {
@@ -2179,33 +2333,35 @@ var MWPTransport = class {
2179
2333
  };
2180
2334
  const request = {
2181
2335
  jsonrpc: "2.0",
2182
- id: `${this.__reqId++}`,
2336
+ id: String(getUniqueRequestId()),
2183
2337
  method: "wallet_createSession",
2184
2338
  params: sessionRequest
2185
2339
  };
2186
2340
  initialConnectionMessageHandler = (message) => __async(this, null, function* () {
2187
- if (typeof message === "object" && message !== null) {
2188
- if ("data" in message) {
2189
- const messagePayload = message.data;
2190
- if (messagePayload.method === "wallet_createSession" || messagePayload.method === "wallet_sessionChanged") {
2191
- if (messagePayload.error) {
2192
- if (initialConnectionMessageHandler) {
2193
- this.dappClient.off(
2194
- "message",
2195
- initialConnectionMessageHandler
2196
- );
2197
- }
2198
- return rejectConnection(messagePayload.error);
2199
- }
2200
- yield this.storeWalletSession(
2201
- request,
2202
- messagePayload
2203
- );
2204
- this.notifyCallbacks(messagePayload);
2205
- return resolveConnection();
2206
- }
2207
- }
2341
+ if (typeof message !== "object" || message === null) {
2342
+ return;
2343
+ }
2344
+ if (!("data" in message)) {
2345
+ return;
2208
2346
  }
2347
+ const messagePayload = message.data;
2348
+ const isMatchingId = messagePayload.id === request.id;
2349
+ const isMatchingMethod = messagePayload.method === "wallet_createSession" || messagePayload.method === "wallet_sessionChanged";
2350
+ if (!isMatchingId && !isMatchingMethod) {
2351
+ return;
2352
+ }
2353
+ if (messagePayload.error) {
2354
+ return rejectConnection(
2355
+ this.parseWalletError(messagePayload.error)
2356
+ );
2357
+ }
2358
+ yield this.storeWalletSession(
2359
+ request,
2360
+ messagePayload
2361
+ );
2362
+ yield this.removeStoredPendingSessionRequest();
2363
+ this.notifyCallbacks(messagePayload);
2364
+ return resolveConnection();
2209
2365
  });
2210
2366
  this.dappClient.on("message", initialConnectionMessageHandler);
2211
2367
  dappClient.connect({
@@ -2226,14 +2382,18 @@ var MWPTransport = class {
2226
2382
  }
2227
2383
  );
2228
2384
  }
2229
- timeout = setTimeout(() => {
2230
- reject(new import_multichain_api_client2.TransportTimeoutError());
2231
- }, this.options.connectionTimeout);
2385
+ timeout = setTimeout(
2386
+ () => {
2387
+ reject(new import_multichain_api_client2.TransportTimeoutError());
2388
+ },
2389
+ storedSessionRequestBeforeConnectionAttempt ? this.options.resumeTimeout : this.options.connectionTimeout
2390
+ );
2232
2391
  connection.then(resolve).catch(reject);
2233
2392
  }));
2234
- return connectionPromise.catch((error) => {
2393
+ return connectionPromise.catch((error) => __async(this, null, function* () {
2394
+ yield this.dappClient.disconnect();
2235
2395
  throw error;
2236
- }).finally(() => {
2396
+ })).finally(() => {
2237
2397
  if (timeout) {
2238
2398
  clearTimeout(timeout);
2239
2399
  }
@@ -2241,24 +2401,68 @@ var MWPTransport = class {
2241
2401
  this.dappClient.off("message", initialConnectionMessageHandler);
2242
2402
  initialConnectionMessageHandler = void 0;
2243
2403
  }
2404
+ this.removeStoredPendingSessionRequest();
2244
2405
  });
2245
2406
  });
2246
2407
  }
2247
2408
  /**
2248
2409
  * Disconnects from the Mobile Wallet Protocol
2249
2410
  *
2411
+ * @param [scopes] - The scopes to revoke. If not provided or empty, all scopes will be revoked.
2250
2412
  * @returns Nothing
2251
2413
  */
2252
2414
  disconnect() {
2253
- return __async(this, null, function* () {
2254
- if (typeof window !== "undefined" && typeof window.removeEventListener !== "undefined" && this.windowFocusHandler) {
2255
- window.removeEventListener("focus", this.windowFocusHandler);
2256
- this.windowFocusHandler = void 0;
2257
- }
2258
- this.kvstore.delete(SESSION_STORE_KEY);
2259
- this.kvstore.delete(ACCOUNTS_STORE_KEY);
2260
- this.kvstore.delete(CHAIN_STORE_KEY);
2261
- return this.dappClient.disconnect();
2415
+ return __async(this, arguments, function* (scopes = []) {
2416
+ var _a3, _b;
2417
+ const cachedSession = yield this.getCachedResponse({
2418
+ jsonrpc: "2.0",
2419
+ id: "0",
2420
+ method: "wallet_getSession"
2421
+ });
2422
+ const cachedSessionScopes = (_b = (_a3 = cachedSession == null ? void 0 : cachedSession.result) == null ? void 0 : _a3.sessionScopes) != null ? _b : {};
2423
+ const remainingScopes = scopes.length === 0 ? [] : Object.keys(cachedSessionScopes).filter(
2424
+ (scope) => !scopes.includes(scope)
2425
+ );
2426
+ const newSessionScopes = Object.fromEntries(
2427
+ Object.entries(cachedSessionScopes).filter(
2428
+ ([key]) => remainingScopes.includes(key)
2429
+ )
2430
+ );
2431
+ this.request({ method: "wallet_revokeSession", params: { scopes } }).catch(
2432
+ (err) => {
2433
+ console.error("error revoking session", err);
2434
+ }
2435
+ );
2436
+ const remainingScopesIncludeEip155 = remainingScopes.some(
2437
+ (scope) => scope.includes("eip155")
2438
+ );
2439
+ if (!remainingScopesIncludeEip155) {
2440
+ this.kvstore.delete(ACCOUNTS_STORE_KEY);
2441
+ this.kvstore.delete(CHAIN_STORE_KEY);
2442
+ }
2443
+ if (remainingScopes.length > 0) {
2444
+ this.kvstore.set(
2445
+ SESSION_STORE_KEY,
2446
+ JSON.stringify({
2447
+ result: {
2448
+ sessionScopes: newSessionScopes
2449
+ }
2450
+ })
2451
+ );
2452
+ } else {
2453
+ this.kvstore.delete(SESSION_STORE_KEY);
2454
+ if (typeof window !== "undefined" && typeof window.removeEventListener !== "undefined" && this.windowFocusHandler) {
2455
+ window.removeEventListener("focus", this.windowFocusHandler);
2456
+ this.windowFocusHandler = void 0;
2457
+ }
2458
+ yield this.dappClient.disconnect();
2459
+ }
2460
+ this.notifyCallbacks({
2461
+ method: "wallet_sessionChanged",
2462
+ params: {
2463
+ sessionScopes: newSessionScopes
2464
+ }
2465
+ });
2262
2466
  });
2263
2467
  }
2264
2468
  /**
@@ -2303,7 +2507,7 @@ var MWPTransport = class {
2303
2507
  }
2304
2508
  getCachedResponse(request) {
2305
2509
  return __async(this, null, function* () {
2306
- var _a2;
2510
+ var _a3;
2307
2511
  if (request.method === "wallet_getSession") {
2308
2512
  const walletGetSession = yield this.kvstore.get(SESSION_STORE_KEY);
2309
2513
  if (walletGetSession) {
@@ -2311,7 +2515,7 @@ var MWPTransport = class {
2311
2515
  return {
2312
2516
  id: request.id,
2313
2517
  jsonrpc: "2.0",
2314
- result: (_a2 = walletSession.params) != null ? _a2 : walletSession.result,
2518
+ result: (_a3 = walletSession.params) != null ? _a3 : walletSession.result,
2315
2519
  // "what?... why walletSession.params?.."
2316
2520
  method: request.method
2317
2521
  };
@@ -2364,7 +2568,7 @@ var MWPTransport = class {
2364
2568
  return __async(this, null, function* () {
2365
2569
  const request = __spreadValues({
2366
2570
  jsonrpc: "2.0",
2367
- id: `${this.__reqId++}`
2571
+ id: String(getUniqueRequestId())
2368
2572
  }, payload);
2369
2573
  const cachedWalletSession = yield this.getCachedResponse(request);
2370
2574
  if (cachedWalletSession) {
@@ -2375,10 +2579,10 @@ var MWPTransport = class {
2375
2579
  yield this.attemptResumeSession();
2376
2580
  }
2377
2581
  return new Promise((resolve, reject) => {
2378
- var _a2;
2582
+ var _a3;
2379
2583
  const timeout = setTimeout(() => {
2380
2584
  this.rejectRequest(request.id, new import_multichain_api_client2.TransportTimeoutError());
2381
- }, (_a2 = options == null ? void 0 : options.timeout) != null ? _a2 : this.options.requestTimeout);
2585
+ }, (_a3 = options == null ? void 0 : options.timeout) != null ? _a3 : this.options.requestTimeout);
2382
2586
  this.pendingRequests.set(request.id, {
2383
2587
  request,
2384
2588
  method: request.method,
@@ -2446,6 +2650,7 @@ var MWPTransport = class {
2446
2650
  const timeoutPromise = new Promise((_resolve, reject) => {
2447
2651
  setTimeout(() => {
2448
2652
  unsubscribe();
2653
+ this.removeStoredPendingSessionRequest();
2449
2654
  reject(new import_multichain_api_client2.TransportTimeoutError());
2450
2655
  }, this.options.resumeTimeout);
2451
2656
  });
@@ -2482,14 +2687,15 @@ var KeyManager = class {
2482
2687
  var keymanager = new KeyManager();
2483
2688
 
2484
2689
  // src/multichain/index.ts
2485
- init_utils();
2690
+ init_utils2();
2486
2691
  var logger2 = createLogger("metamask-sdk:core");
2487
- var _a, _provider, _providerTransportWrapper, _transport2, _dappClient, _beforeUnloadListener, _listener, _sdkInfo, _MetaMaskConnectMultichain_instances, setupAnalytics_fn, onTransportNotification_fn, getStoredTransport_fn, setupTransport_fn, init_fn, createDappClient_fn, setupMWP_fn, onBeforeUnload_fn, createBeforeUnloadListener_fn, renderInstallModalAsync_fn, showInstallModal_fn, headlessConnect_fn, setupDefaultTransport_fn, deeplinkConnect_fn, handleConnection_fn;
2692
+ var SINGLETON_KEY = "__METAMASK_CONNECT_MULTICHAIN_SINGLETON__";
2693
+ var _a2, _provider, _providerTransportWrapper, _transport2, _dappClient, _beforeUnloadListener, _listener, _sdkInfo, _MetaMaskConnectMultichain_instances, setupAnalytics_fn, onTransportNotification_fn, getStoredTransport_fn, setupTransport_fn, init_fn, createDappClient_fn, setupMWP_fn, onBeforeUnload_fn, createBeforeUnloadListener_fn, renderInstallModalAsync_fn, showInstallModal_fn, headlessConnect_fn, setupDefaultTransport_fn, deeplinkConnect_fn, handleConnection_fn, getCaipSession_fn, openConnectDeeplinkIfNeeded_fn;
2488
2694
  var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends MultichainCore {
2489
2695
  constructor(options) {
2490
- var _a2, _b, _c, _d, _e, _f;
2696
+ var _a3, _b, _c, _d, _e, _f;
2491
2697
  const withDappMetadata = setupDappMetadata(options);
2492
- const integrationType = (_b = (_a2 = options.analytics) == null ? void 0 : _a2.integrationType) != null ? _b : "direct";
2698
+ const integrationType = (_b = (_a3 = options.analytics) == null ? void 0 : _a3.integrationType) != null ? _b : "direct";
2493
2699
  const allOptions = __spreadProps(__spreadValues({}, withDappMetadata), {
2494
2700
  ui: __spreadProps(__spreadValues({}, withDappMetadata.ui), {
2495
2701
  preferExtension: (_c = withDappMetadata.ui.preferExtension) != null ? _c : true,
@@ -2509,7 +2715,7 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
2509
2715
  __privateAdd(this, _beforeUnloadListener);
2510
2716
  this._status = "pending";
2511
2717
  __privateAdd(this, _listener);
2512
- __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}`);
2718
+ __privateAdd(this, _sdkInfo, `Sdk/Javascript SdkVersion/${getVersion()} Platform/${getPlatformType()} dApp/${(_a2 = this.options.dapp.url) != null ? _a2 : this.options.dapp.name} dAppTitle/${this.options.dapp.name}`);
2513
2719
  __privateSet(this, _providerTransportWrapper, new MultichainApiClientWrapperTransport(
2514
2720
  this
2515
2721
  ));
@@ -2521,9 +2727,9 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
2521
2727
  return this._status;
2522
2728
  }
2523
2729
  set status(value) {
2524
- var _a2, _b;
2730
+ var _a3, _b;
2525
2731
  this._status = value;
2526
- (_b = (_a2 = this.options.transport) == null ? void 0 : _a2.onNotification) == null ? void 0 : _b.call(_a2, {
2732
+ (_b = (_a3 = this.options.transport) == null ? void 0 : _a3.onNotification) == null ? void 0 : _b.call(_a3, {
2527
2733
  method: "stateChanged",
2528
2734
  params: value
2529
2735
  });
@@ -2549,27 +2755,54 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
2549
2755
  get transportType() {
2550
2756
  return __privateGet(this, _transport2) instanceof MWPTransport ? "mwp" /* MWP */ : "browser" /* Browser */;
2551
2757
  }
2758
+ // Creates a singleton instance of MetaMaskConnectMultichain.
2759
+ // If the singleton already exists, it merges the incoming options with the
2760
+ // existing singleton options for the following keys: `api.supportedNetworks`,
2761
+ // `ui.*`, `mobile.*`, `transport.extensionId`, `debug`. Take note that the
2762
+ // value for `dapp` is not merged as it does not make sense for subsequent calls to
2763
+ // `createMultichainClient` to have a different `dapp` value.
2552
2764
  static create(options) {
2553
2765
  return __async(this, null, function* () {
2554
- var _a2;
2555
- const instance = new _MetaMaskConnectMultichain(options);
2556
- const isEnabled2 = yield isEnabled(
2557
- "metamask-sdk:core",
2558
- instance.options.storage
2559
- );
2560
- if (isEnabled2) {
2561
- enableDebug("metamask-sdk:core");
2562
- }
2563
- yield __privateMethod(_a2 = instance, _MetaMaskConnectMultichain_instances, init_fn).call(_a2);
2564
- return instance;
2766
+ const globalObject = getGlobalObject();
2767
+ const existing = globalObject[SINGLETON_KEY];
2768
+ if (existing) {
2769
+ const instance = yield existing;
2770
+ instance.mergeOptions(options);
2771
+ if (options.debug) {
2772
+ enableDebug("metamask-sdk:*");
2773
+ }
2774
+ return instance;
2775
+ }
2776
+ const instancePromise = (() => __async(null, null, function* () {
2777
+ var _a3;
2778
+ const instance = new _MetaMaskConnectMultichain(options);
2779
+ const isEnabled2 = yield isEnabled(
2780
+ "metamask-sdk:core",
2781
+ instance.options.storage
2782
+ );
2783
+ if (isEnabled2) {
2784
+ enableDebug("metamask-sdk:core");
2785
+ }
2786
+ yield __privateMethod(_a3 = instance, _MetaMaskConnectMultichain_instances, init_fn).call(_a3);
2787
+ return instance;
2788
+ }))();
2789
+ globalObject[SINGLETON_KEY] = instancePromise;
2790
+ instancePromise.catch((error) => {
2791
+ globalObject[SINGLETON_KEY] = void 0;
2792
+ console.error("Error initializing MetaMaskConnectMultichain", error);
2793
+ });
2794
+ return instancePromise;
2565
2795
  });
2566
2796
  }
2567
2797
  // TODO: make this into param object
2568
2798
  connect(scopes, caipAccountIds, sessionProperties, forceRequest) {
2569
2799
  return __async(this, null, function* () {
2570
- var _a2;
2571
- if (this.status !== "connected") {
2572
- yield this.disconnect();
2800
+ var _a3;
2801
+ if (this.status === "connecting" && this.transportType === "mwp" /* MWP */) {
2802
+ yield __privateMethod(this, _MetaMaskConnectMultichain_instances, openConnectDeeplinkIfNeeded_fn).call(this);
2803
+ throw new Error(
2804
+ "Existing connection is pending. Please check your MetaMask Mobile app to continue."
2805
+ );
2573
2806
  }
2574
2807
  const { ui } = this.options;
2575
2808
  const platformType = getPlatformType();
@@ -2599,12 +2832,19 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
2599
2832
  } catch (error) {
2600
2833
  logger2("Error tracking connection_initiated event", error);
2601
2834
  }
2602
- const nonEmptySessionProperites = Object.keys(sessionProperties != null ? sessionProperties : {}).length > 0 ? sessionProperties : void 0;
2603
- if (((_a2 = __privateGet(this, _transport2)) == null ? void 0 : _a2.isConnected()) && !secure) {
2835
+ const sessionData = yield __privateMethod(this, _MetaMaskConnectMultichain_instances, getCaipSession_fn).call(this);
2836
+ const { mergedScopes, mergedCaipAccountIds, mergedSessionProperties } = mergeRequestedSessionWithExisting(
2837
+ sessionData,
2838
+ scopes,
2839
+ caipAccountIds,
2840
+ sessionProperties
2841
+ );
2842
+ const nonEmptySessionProperties = Object.keys(mergedSessionProperties != null ? mergedSessionProperties : {}).length > 0 ? mergedSessionProperties : void 0;
2843
+ if (((_a3 = __privateGet(this, _transport2)) == null ? void 0 : _a3.isConnected()) && !secure) {
2604
2844
  return __privateMethod(this, _MetaMaskConnectMultichain_instances, handleConnection_fn).call(this, __privateGet(this, _transport2).connect({
2605
- scopes,
2606
- caipAccountIds,
2607
- sessionProperties: nonEmptySessionProperites,
2845
+ scopes: mergedScopes,
2846
+ caipAccountIds: mergedCaipAccountIds,
2847
+ sessionProperties: nonEmptySessionProperties,
2608
2848
  forceRequest
2609
2849
  }).then(() => __async(this, null, function* () {
2610
2850
  if (__privateGet(this, _transport2) instanceof MWPTransport) {
@@ -2616,47 +2856,53 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
2616
2856
  if (platformType === "in-app-browser" /* MetaMaskMobileWebview */) {
2617
2857
  const defaultTransport = yield __privateMethod(this, _MetaMaskConnectMultichain_instances, setupDefaultTransport_fn).call(this);
2618
2858
  return __privateMethod(this, _MetaMaskConnectMultichain_instances, handleConnection_fn).call(this, defaultTransport.connect({
2619
- scopes,
2620
- caipAccountIds,
2621
- sessionProperties: nonEmptySessionProperites,
2859
+ scopes: mergedScopes,
2860
+ caipAccountIds: mergedCaipAccountIds,
2861
+ sessionProperties: nonEmptySessionProperties,
2622
2862
  forceRequest
2623
2863
  }), scopes, transportType);
2624
2864
  }
2625
2865
  if (isWeb && hasExtensionInstalled && preferExtension) {
2626
2866
  const defaultTransport = yield __privateMethod(this, _MetaMaskConnectMultichain_instances, setupDefaultTransport_fn).call(this);
2627
2867
  return __privateMethod(this, _MetaMaskConnectMultichain_instances, handleConnection_fn).call(this, defaultTransport.connect({
2628
- scopes,
2629
- caipAccountIds,
2630
- sessionProperties: nonEmptySessionProperites,
2868
+ scopes: mergedScopes,
2869
+ caipAccountIds: mergedCaipAccountIds,
2870
+ sessionProperties: nonEmptySessionProperties,
2631
2871
  forceRequest
2632
2872
  }), scopes, transportType);
2633
2873
  }
2634
2874
  yield __privateMethod(this, _MetaMaskConnectMultichain_instances, setupMWP_fn).call(this);
2635
2875
  const shouldShowInstallModal = hasExtensionInstalled ? showInstallModal : !preferExtension || showInstallModal;
2636
2876
  if (secure && !shouldShowInstallModal) {
2637
- return __privateMethod(this, _MetaMaskConnectMultichain_instances, handleConnection_fn).call(this, __privateMethod(this, _MetaMaskConnectMultichain_instances, deeplinkConnect_fn).call(this, scopes, caipAccountIds, nonEmptySessionProperites), scopes, transportType);
2877
+ return __privateMethod(this, _MetaMaskConnectMultichain_instances, handleConnection_fn).call(this, __privateMethod(this, _MetaMaskConnectMultichain_instances, deeplinkConnect_fn).call(this, mergedScopes, mergedCaipAccountIds, nonEmptySessionProperties), scopes, transportType);
2638
2878
  }
2639
- return __privateMethod(this, _MetaMaskConnectMultichain_instances, handleConnection_fn).call(this, __privateMethod(this, _MetaMaskConnectMultichain_instances, showInstallModal_fn).call(this, shouldShowInstallModal, scopes, caipAccountIds, nonEmptySessionProperites), scopes, transportType);
2879
+ return __privateMethod(this, _MetaMaskConnectMultichain_instances, handleConnection_fn).call(this, __privateMethod(this, _MetaMaskConnectMultichain_instances, showInstallModal_fn).call(this, shouldShowInstallModal, mergedScopes, mergedCaipAccountIds, nonEmptySessionProperties), scopes, transportType);
2640
2880
  });
2641
2881
  }
2642
2882
  emit(event, args) {
2643
- var _a2, _b;
2644
- (_b = (_a2 = this.options.transport) == null ? void 0 : _a2.onNotification) == null ? void 0 : _b.call(_a2, { method: event, params: args });
2883
+ var _a3, _b;
2884
+ (_b = (_a3 = this.options.transport) == null ? void 0 : _a3.onNotification) == null ? void 0 : _b.call(_a3, { method: event, params: args });
2645
2885
  super.emit(event, args);
2646
2886
  }
2647
2887
  disconnect() {
2648
- return __async(this, null, function* () {
2649
- var _a2, _b, _c;
2650
- yield (_a2 = __privateGet(this, _listener)) == null ? void 0 : _a2.call(this);
2651
- (_b = __privateGet(this, _beforeUnloadListener)) == null ? void 0 : _b.call(this);
2652
- yield (_c = __privateGet(this, _transport2)) == null ? void 0 : _c.disconnect();
2653
- yield this.storage.removeTransport();
2654
- this.emit("stateChanged", "disconnected");
2655
- __privateSet(this, _listener, void 0);
2656
- __privateSet(this, _beforeUnloadListener, void 0);
2657
- __privateSet(this, _transport2, void 0);
2658
- __privateGet(this, _providerTransportWrapper).clearNotificationCallbacks();
2659
- __privateSet(this, _dappClient, void 0);
2888
+ return __async(this, arguments, function* (scopes = []) {
2889
+ var _a3, _b, _c;
2890
+ const sessionData = yield __privateMethod(this, _MetaMaskConnectMultichain_instances, getCaipSession_fn).call(this);
2891
+ const remainingScopes = scopes.length === 0 ? [] : Object.keys(sessionData.sessionScopes).filter(
2892
+ (scope) => !scopes.includes(scope)
2893
+ );
2894
+ yield (_a3 = __privateGet(this, _transport2)) == null ? void 0 : _a3.disconnect(scopes);
2895
+ if (remainingScopes.length === 0) {
2896
+ yield (_b = __privateGet(this, _listener)) == null ? void 0 : _b.call(this);
2897
+ (_c = __privateGet(this, _beforeUnloadListener)) == null ? void 0 : _c.call(this);
2898
+ yield this.storage.removeTransport();
2899
+ __privateSet(this, _listener, void 0);
2900
+ __privateSet(this, _beforeUnloadListener, void 0);
2901
+ __privateSet(this, _transport2, void 0);
2902
+ __privateGet(this, _providerTransportWrapper).clearTransportNotificationListener();
2903
+ __privateSet(this, _dappClient, void 0);
2904
+ this.status = "disconnected";
2905
+ }
2660
2906
  });
2661
2907
  }
2662
2908
  invokeMethod(request) {
@@ -2668,7 +2914,7 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
2668
2914
  });
2669
2915
  }
2670
2916
  // DRY THIS WITH REQUEST ROUTER
2671
- openDeeplinkIfNeeded() {
2917
+ openSimpleDeeplinkIfNeeded() {
2672
2918
  const { ui, mobile } = this.options;
2673
2919
  const { showInstallModal = false } = ui != null ? ui : {};
2674
2920
  const secure = isSecure();
@@ -2688,6 +2934,23 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
2688
2934
  }), 10);
2689
2935
  }
2690
2936
  }
2937
+ // Provides a way for ecosystem clients (EVM, Solana, etc.) to get the current CAIP session data
2938
+ // when instantiating themselves (as they would have already missed any initial sessionChanged events emitted by ConnectMultichain)
2939
+ // without having to concern themselves with the current transport connection status.
2940
+ emitSessionChanged() {
2941
+ return __async(this, null, function* () {
2942
+ var _a3;
2943
+ const emptySession = { sessionScopes: {} };
2944
+ if (this.status !== "connected" && this.status !== "connecting") {
2945
+ this.emit("wallet_sessionChanged", emptySession);
2946
+ return;
2947
+ }
2948
+ const response = yield this.transport.request({
2949
+ method: "wallet_getSession"
2950
+ });
2951
+ this.emit("wallet_sessionChanged", (_a3 = response.result) != null ? _a3 : emptySession);
2952
+ });
2953
+ }
2691
2954
  };
2692
2955
  _provider = new WeakMap();
2693
2956
  _providerTransportWrapper = new WeakMap();
@@ -2699,7 +2962,7 @@ _sdkInfo = new WeakMap();
2699
2962
  _MetaMaskConnectMultichain_instances = new WeakSet();
2700
2963
  setupAnalytics_fn = function() {
2701
2964
  return __async(this, null, function* () {
2702
- var _a2;
2965
+ var _a3;
2703
2966
  const platform = getPlatformType();
2704
2967
  const isBrowser = platform === "in-app-browser" /* MetaMaskMobileWebview */ || platform === "web-desktop" /* DesktopWeb */ || platform === "web-mobile" /* MobileWeb */;
2705
2968
  const isReactNative2 = platform === "react-native" /* ReactNative */;
@@ -2709,7 +2972,7 @@ setupAnalytics_fn = function() {
2709
2972
  const version = getVersion();
2710
2973
  const dappId = getDappId(this.options.dapp);
2711
2974
  const anonId = yield this.storage.getAnonId();
2712
- const { integrationType } = (_a2 = this.options.analytics) != null ? _a2 : {
2975
+ const { integrationType } = (_a3 = this.options.analytics) != null ? _a3 : {
2713
2976
  integrationType: ""
2714
2977
  };
2715
2978
  import_analytics4.analytics.setGlobalProperty("mmconnect_version", version);
@@ -2722,9 +2985,9 @@ setupAnalytics_fn = function() {
2722
2985
  };
2723
2986
  onTransportNotification_fn = function(payload) {
2724
2987
  return __async(this, null, function* () {
2725
- var _a2;
2988
+ var _a3;
2726
2989
  if (typeof payload === "object" && payload !== null && "method" in payload) {
2727
- this.emit(payload.method, (_a2 = payload.params) != null ? _a2 : payload.result);
2990
+ this.emit(payload.method, (_a3 = payload.params) != null ? _a3 : payload.result);
2728
2991
  }
2729
2992
  });
2730
2993
  };
@@ -2737,7 +3000,7 @@ getStoredTransport_fn = function() {
2737
3000
  if (hasExtensionInstalled) {
2738
3001
  const apiTransport = new DefaultTransport();
2739
3002
  __privateSet(this, _transport2, apiTransport);
2740
- __privateGet(this, _providerTransportWrapper).setupNotifcationListener();
3003
+ __privateGet(this, _providerTransportWrapper).setupTransportNotificationListener();
2741
3004
  __privateSet(this, _listener, apiTransport.onNotification(
2742
3005
  __privateMethod(this, _MetaMaskConnectMultichain_instances, onTransportNotification_fn).bind(this)
2743
3006
  ));
@@ -2749,7 +3012,7 @@ getStoredTransport_fn = function() {
2749
3012
  const apiTransport = new MWPTransport(dappClient, kvstore);
2750
3013
  __privateSet(this, _dappClient, dappClient);
2751
3014
  __privateSet(this, _transport2, apiTransport);
2752
- __privateGet(this, _providerTransportWrapper).setupNotifcationListener();
3015
+ __privateGet(this, _providerTransportWrapper).setupTransportNotificationListener();
2753
3016
  __privateSet(this, _listener, apiTransport.onNotification(
2754
3017
  __privateMethod(this, _MetaMaskConnectMultichain_instances, onTransportNotification_fn).bind(this)
2755
3018
  ));
@@ -2781,25 +3044,17 @@ setupTransport_fn = function() {
2781
3044
  };
2782
3045
  init_fn = function() {
2783
3046
  return __async(this, null, function* () {
2784
- var _a2;
2785
3047
  try {
2786
- if (typeof window !== "undefined" && ((_a2 = window.mmsdk) == null ? void 0 : _a2.isInitialized)) {
2787
- logger2("MetaMaskSDK: init already initialized");
2788
- } else {
2789
- yield __privateMethod(this, _MetaMaskConnectMultichain_instances, setupAnalytics_fn).call(this);
2790
- yield __privateMethod(this, _MetaMaskConnectMultichain_instances, setupTransport_fn).call(this);
2791
- try {
2792
- const baseProps = yield getBaseAnalyticsProperties(
2793
- this.options,
2794
- this.storage
2795
- );
2796
- import_analytics4.analytics.track("mmconnect_initialized", baseProps);
2797
- } catch (error) {
2798
- logger2("Error tracking initialized event", error);
2799
- }
2800
- if (typeof window !== "undefined") {
2801
- window.mmsdk = this;
2802
- }
3048
+ yield __privateMethod(this, _MetaMaskConnectMultichain_instances, setupAnalytics_fn).call(this);
3049
+ yield __privateMethod(this, _MetaMaskConnectMultichain_instances, setupTransport_fn).call(this);
3050
+ try {
3051
+ const baseProps = yield getBaseAnalyticsProperties(
3052
+ this.options,
3053
+ this.storage
3054
+ );
3055
+ import_analytics4.analytics.track("mmconnect_initialized", baseProps);
3056
+ } catch (error) {
3057
+ logger2("Error tracking initialized event", error);
2803
3058
  }
2804
3059
  } catch (error) {
2805
3060
  yield this.storage.removeTransport();
@@ -2835,7 +3090,7 @@ setupMWP_fn = function() {
2835
3090
  __privateSet(this, _dappClient, dappClient);
2836
3091
  const apiTransport = new MWPTransport(dappClient, kvstore);
2837
3092
  __privateSet(this, _transport2, apiTransport);
2838
- __privateGet(this, _providerTransportWrapper).setupNotifcationListener();
3093
+ __privateGet(this, _providerTransportWrapper).setupTransportNotificationListener();
2839
3094
  __privateSet(this, _listener, this.transport.onNotification(
2840
3095
  __privateMethod(this, _MetaMaskConnectMultichain_instances, onTransportNotification_fn).bind(this)
2841
3096
  ));
@@ -2844,22 +3099,20 @@ setupMWP_fn = function() {
2844
3099
  };
2845
3100
  onBeforeUnload_fn = function() {
2846
3101
  return __async(this, null, function* () {
2847
- var _a2;
2848
- if ((_a2 = this.options.ui.factory.modal) == null ? void 0 : _a2.isMounted) {
3102
+ var _a3;
3103
+ if ((_a3 = this.options.ui.factory.modal) == null ? void 0 : _a3.isMounted) {
2849
3104
  yield this.storage.removeTransport();
2850
3105
  }
2851
3106
  });
2852
3107
  };
2853
3108
  createBeforeUnloadListener_fn = function() {
3109
+ const handler = __privateMethod(this, _MetaMaskConnectMultichain_instances, onBeforeUnload_fn).bind(this);
2854
3110
  if (typeof window !== "undefined" && typeof window.addEventListener !== "undefined") {
2855
- window.addEventListener("beforeunload", __privateMethod(this, _MetaMaskConnectMultichain_instances, onBeforeUnload_fn).bind(this));
3111
+ window.addEventListener("beforeunload", handler);
2856
3112
  }
2857
3113
  return () => {
2858
3114
  if (typeof window !== "undefined" && typeof window.removeEventListener !== "undefined") {
2859
- window.removeEventListener(
2860
- "beforeunload",
2861
- __privateMethod(this, _MetaMaskConnectMultichain_instances, onBeforeUnload_fn).bind(this)
2862
- );
3115
+ window.removeEventListener("beforeunload", handler);
2863
3116
  }
2864
3117
  };
2865
3118
  };
@@ -2889,7 +3142,7 @@ renderInstallModalAsync_fn = function(desktopPreferred, scopes, caipAccountIds,
2889
3142
  }
2890
3143
  );
2891
3144
  (() => __async(this, null, function* () {
2892
- var _a2;
3145
+ var _a3;
2893
3146
  try {
2894
3147
  yield this.transport.connect({
2895
3148
  scopes,
@@ -2897,20 +3150,21 @@ renderInstallModalAsync_fn = function(desktopPreferred, scopes, caipAccountIds,
2897
3150
  sessionProperties
2898
3151
  });
2899
3152
  yield this.options.ui.factory.unload();
2900
- (_a2 = this.options.ui.factory.modal) == null ? void 0 : _a2.unmount();
3153
+ (_a3 = this.options.ui.factory.modal) == null ? void 0 : _a3.unmount();
2901
3154
  this.status = "connected";
2902
3155
  yield this.storage.setTransport("mwp" /* MWP */);
2903
3156
  } catch (error) {
2904
3157
  if (error instanceof import_mobile_wallet_protocol_core2.ProtocolError) {
2905
3158
  if (error.code !== import_mobile_wallet_protocol_core2.ErrorCode.REQUEST_EXPIRED) {
2906
3159
  this.status = "disconnected";
3160
+ yield this.options.ui.factory.unload(error);
2907
3161
  reject(error);
2908
3162
  }
2909
3163
  } else {
2910
3164
  this.status = "disconnected";
2911
- reject(
2912
- error instanceof Error ? error : new Error(String(error))
2913
- );
3165
+ const normalizedError = error instanceof Error ? error : new Error(String(error));
3166
+ yield this.options.ui.factory.unload(normalizedError);
3167
+ reject(normalizedError);
2914
3168
  }
2915
3169
  }
2916
3170
  }))().catch(() => {
@@ -2937,8 +3191,8 @@ renderInstallModalAsync_fn = function(desktopPreferred, scopes, caipAccountIds,
2937
3191
  };
2938
3192
  showInstallModal_fn = function(desktopPreferred, scopes, caipAccountIds, sessionProperties) {
2939
3193
  return __async(this, null, function* () {
2940
- var _a2;
2941
- (_a2 = __privateGet(this, _beforeUnloadListener)) != null ? _a2 : __privateSet(this, _beforeUnloadListener, __privateMethod(this, _MetaMaskConnectMultichain_instances, createBeforeUnloadListener_fn).call(this));
3194
+ var _a3;
3195
+ (_a3 = __privateGet(this, _beforeUnloadListener)) != null ? _a3 : __privateSet(this, _beforeUnloadListener, __privateMethod(this, _MetaMaskConnectMultichain_instances, createBeforeUnloadListener_fn).call(this));
2942
3196
  if (this.options.ui.headless) {
2943
3197
  yield __privateMethod(this, _MetaMaskConnectMultichain_instances, headlessConnect_fn).call(this, scopes, caipAccountIds, sessionProperties);
2944
3198
  } else {
@@ -2997,7 +3251,7 @@ setupDefaultTransport_fn = function() {
2997
3251
  __privateMethod(this, _MetaMaskConnectMultichain_instances, onTransportNotification_fn).bind(this)
2998
3252
  ));
2999
3253
  __privateSet(this, _transport2, transport);
3000
- __privateGet(this, _providerTransportWrapper).setupNotifcationListener();
3254
+ __privateGet(this, _providerTransportWrapper).setupTransportNotificationListener();
3001
3255
  return transport;
3002
3256
  });
3003
3257
  };
@@ -3005,7 +3259,7 @@ deeplinkConnect_fn = function(scopes, caipAccountIds, sessionProperties) {
3005
3259
  return __async(this, null, function* () {
3006
3260
  return new Promise((resolve, reject) => __async(this, null, function* () {
3007
3261
  const dappClientMessageHandler = (payload) => {
3008
- var _a2;
3262
+ var _a3;
3009
3263
  if (typeof payload !== "object" || payload === null || !("data" in payload)) {
3010
3264
  return;
3011
3265
  }
@@ -3015,7 +3269,7 @@ deeplinkConnect_fn = function(scopes, caipAccountIds, sessionProperties) {
3015
3269
  this.dappClient.off("message", dappClientMessageHandler);
3016
3270
  reject(data.error);
3017
3271
  }
3018
- if ((_a2 = data == null ? void 0 : data.result) == null ? void 0 : _a2.sessionScopes) {
3272
+ if ((_a3 = data == null ? void 0 : data.result) == null ? void 0 : _a3.sessionScopes) {
3019
3273
  this.dappClient.off("message", dappClientMessageHandler);
3020
3274
  }
3021
3275
  }
@@ -3024,13 +3278,13 @@ deeplinkConnect_fn = function(scopes, caipAccountIds, sessionProperties) {
3024
3278
  let timeout;
3025
3279
  if (this.transport.isConnected()) {
3026
3280
  timeout = setTimeout(() => {
3027
- this.openDeeplinkIfNeeded();
3281
+ this.openSimpleDeeplinkIfNeeded();
3028
3282
  }, 250);
3029
3283
  } else {
3030
3284
  this.dappClient.once(
3031
3285
  "session_request",
3032
3286
  (sessionRequest) => {
3033
- var _a2;
3287
+ var _a3;
3034
3288
  const connectionRequest = {
3035
3289
  sessionRequest,
3036
3290
  metadata: {
@@ -3045,7 +3299,7 @@ deeplinkConnect_fn = function(scopes, caipAccountIds, sessionProperties) {
3045
3299
  connectionRequest
3046
3300
  );
3047
3301
  this.emit("display_uri", deeplink);
3048
- if ((_a2 = this.options.mobile) == null ? void 0 : _a2.preferredOpenLink) {
3302
+ if ((_a3 = this.options.mobile) == null ? void 0 : _a3.preferredOpenLink) {
3049
3303
  this.options.mobile.preferredOpenLink(deeplink, "_self");
3050
3304
  } else {
3051
3305
  openDeeplink(this.options, deeplink, universalLink);
@@ -3107,6 +3361,53 @@ handleConnection_fn = function(promise, scopes, transportType) {
3107
3361
  }));
3108
3362
  });
3109
3363
  };
3364
+ getCaipSession_fn = function() {
3365
+ return __async(this, null, function* () {
3366
+ let sessionData = {
3367
+ sessionScopes: {},
3368
+ sessionProperties: {}
3369
+ };
3370
+ if (this.status === "connected") {
3371
+ const response = yield this.transport.request({
3372
+ method: "wallet_getSession"
3373
+ });
3374
+ if (response.result) {
3375
+ sessionData = response.result;
3376
+ }
3377
+ }
3378
+ return sessionData;
3379
+ });
3380
+ };
3381
+ openConnectDeeplinkIfNeeded_fn = function() {
3382
+ return __async(this, null, function* () {
3383
+ var _a3, _b;
3384
+ const { ui } = this.options;
3385
+ const { showInstallModal = false } = ui != null ? ui : {};
3386
+ const secure = isSecure();
3387
+ const shouldOpenDeeplink = secure && !showInstallModal;
3388
+ if (!shouldOpenDeeplink) {
3389
+ return;
3390
+ }
3391
+ const storedSessionRequest = yield (_a3 = __privateGet(this, _transport2)) == null ? void 0 : _a3.getStoredPendingSessionRequest();
3392
+ if (!storedSessionRequest) {
3393
+ return;
3394
+ }
3395
+ const connectionRequest = {
3396
+ sessionRequest: storedSessionRequest,
3397
+ metadata: {
3398
+ dapp: this.options.dapp,
3399
+ sdk: { version: getVersion(), platform: getPlatformType() }
3400
+ }
3401
+ };
3402
+ const deeplink = this.options.ui.factory.createConnectionDeeplink(connectionRequest);
3403
+ const universalLink = this.options.ui.factory.createConnectionUniversalLink(connectionRequest);
3404
+ if ((_b = this.options.mobile) == null ? void 0 : _b.preferredOpenLink) {
3405
+ this.options.mobile.preferredOpenLink(deeplink, "_self");
3406
+ } else {
3407
+ openDeeplink(this.options, deeplink, universalLink);
3408
+ }
3409
+ });
3410
+ };
3110
3411
  var MetaMaskConnectMultichain = _MetaMaskConnectMultichain;
3111
3412
 
3112
3413
  // src/store/index.ts
@@ -3291,7 +3592,7 @@ var Store = class extends StoreClient {
3291
3592
  // src/ui/ModalFactory.ts
3292
3593
  var import_onboarding = __toESM(require("@metamask/onboarding"));
3293
3594
  init_domain();
3294
- init_utils();
3595
+ init_utils2();
3295
3596
  var BaseModalFactory = class {
3296
3597
  /**
3297
3598
  * Creates a new modal factory instance.
@@ -3314,8 +3615,8 @@ var BaseModalFactory = class {
3314
3615
  }
3315
3616
  unload(error) {
3316
3617
  return __async(this, null, function* () {
3317
- var _a2, _b;
3318
- (_a2 = this.modal) == null ? void 0 : _a2.unmount();
3618
+ var _a3, _b;
3619
+ (_a3 = this.modal) == null ? void 0 : _a3.unmount();
3319
3620
  yield (_b = this.successCallback) == null ? void 0 : _b.call(this, error);
3320
3621
  });
3321
3622
  }
@@ -3385,8 +3686,8 @@ var BaseModalFactory = class {
3385
3686
  }
3386
3687
  renderInstallModal(showInstallModal, createConnectionRequest, successCallback, onDisplayUri) {
3387
3688
  return __async(this, null, function* () {
3388
- var _a2, _b;
3389
- (_a2 = this.modal) == null ? void 0 : _a2.unmount();
3689
+ var _a3, _b;
3690
+ (_a3 = this.modal) == null ? void 0 : _a3.unmount();
3390
3691
  yield this.preload();
3391
3692
  this.successCallback = successCallback;
3392
3693
  this.displayUriCallback = onDisplayUri;
@@ -3402,9 +3703,9 @@ var BaseModalFactory = class {
3402
3703
  link: qrCodeLink,
3403
3704
  sdkVersion: getVersion(),
3404
3705
  generateQRCode: (request) => __async(this, null, function* () {
3405
- var _a3;
3706
+ var _a4;
3406
3707
  const newLink = this.createConnectionDeeplink(request);
3407
- (_a3 = this.displayUriCallback) == null ? void 0 : _a3.call(this, newLink);
3708
+ (_a4 = this.displayUriCallback) == null ? void 0 : _a4.call(this, newLink);
3408
3709
  return newLink;
3409
3710
  }),
3410
3711
  onClose: this.onCloseModal.bind(this),
@@ -3418,8 +3719,8 @@ var BaseModalFactory = class {
3418
3719
  }
3419
3720
  renderOTPCodeModal(createOTPCode, successCallback, updateOTPCode) {
3420
3721
  return __async(this, null, function* () {
3421
- var _a2;
3422
- (_a2 = this.modal) == null ? void 0 : _a2.unmount();
3722
+ var _a3;
3723
+ (_a3 = this.modal) == null ? void 0 : _a3.unmount();
3423
3724
  yield this.preload();
3424
3725
  this.successCallback = successCallback;
3425
3726
  const container = this.getMountedContainer();