@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
@@ -34,14 +34,6 @@ var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read fr
34
34
  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);
35
35
  var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
36
36
  var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
37
- var __privateWrapper = (obj, member, setter, getter) => ({
38
- set _(value) {
39
- __privateSet(obj, member, value, setter);
40
- },
41
- get _() {
42
- return __privateGet(obj, member, getter);
43
- }
44
- });
45
37
  var __async = (__this, __arguments, generator) => {
46
38
  return new Promise((resolve, reject) => {
47
39
  var fulfilled = (value) => {
@@ -243,8 +235,8 @@ var init_logger = __esm({
243
235
  debug.enable(namespace);
244
236
  };
245
237
  isEnabled = (namespace, storage) => __async(null, null, function* () {
246
- var _a2;
247
- if ("process" in globalThis && ((_a2 = process == null ? void 0 : process.env) == null ? void 0 : _a2.DEBUG)) {
238
+ var _a3;
239
+ if ("process" in globalThis && ((_a3 = process == null ? void 0 : process.env) == null ? void 0 : _a3.DEBUG)) {
248
240
  const { DEBUG } = process.env;
249
241
  return isNamespaceEnabled(DEBUG, namespace);
250
242
  }
@@ -407,6 +399,34 @@ var init_multichain = __esm({
407
399
  super();
408
400
  this.options = options;
409
401
  }
402
+ /**
403
+ * Merges the given options into the current instance options.
404
+ * Only the mergeable keys are updated (api.supportedNetworks, ui.*, mobile.*, transport.extensionId, debug).
405
+ * The main thing to note is that the value for `dapp` is not merged as it does not make sense for
406
+ * subsequent calls to `createMultichainClient` to have a different `dapp` value.
407
+ * Used when createMultichainClient is called with an existing singleton.
408
+ *
409
+ * @param partial - Options to merge/overwrite onto the current instance
410
+ */
411
+ mergeOptions(partial) {
412
+ var _a3, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n;
413
+ const opts = this.options;
414
+ this.options = __spreadProps(__spreadValues({}, opts), {
415
+ api: __spreadProps(__spreadValues({}, opts.api), {
416
+ supportedNetworks: __spreadValues(__spreadValues({}, opts.api.supportedNetworks), (_b = (_a3 = partial.api) == null ? void 0 : _a3.supportedNetworks) != null ? _b : {})
417
+ }),
418
+ ui: __spreadProps(__spreadValues({}, opts.ui), {
419
+ headless: (_d = (_c = partial.ui) == null ? void 0 : _c.headless) != null ? _d : opts.ui.headless,
420
+ preferExtension: (_f = (_e = partial.ui) == null ? void 0 : _e.preferExtension) != null ? _f : opts.ui.preferExtension,
421
+ showInstallModal: (_h = (_g = partial.ui) == null ? void 0 : _g.showInstallModal) != null ? _h : opts.ui.showInstallModal
422
+ }),
423
+ mobile: __spreadValues(__spreadValues({}, opts.mobile), (_i = partial.mobile) != null ? _i : {}),
424
+ transport: __spreadProps(__spreadValues({}, (_j = opts.transport) != null ? _j : {}), {
425
+ extensionId: (_m = (_k = partial.transport) == null ? void 0 : _k.extensionId) != null ? _m : (_l = opts.transport) == null ? void 0 : _l.extensionId
426
+ }),
427
+ debug: (_n = partial.debug) != null ? _n : opts.debug
428
+ });
429
+ }
410
430
  };
411
431
  }
412
432
  });
@@ -414,35 +434,35 @@ var init_multichain = __esm({
414
434
  // src/domain/platform/index.ts
415
435
  import Bowser from "bowser";
416
436
  function isNotBrowser() {
417
- var _a2;
437
+ var _a3;
418
438
  if (typeof window === "undefined") {
419
439
  return true;
420
440
  }
421
441
  if (!(window == null ? void 0 : window.navigator)) {
422
442
  return true;
423
443
  }
424
- if (typeof global !== "undefined" && ((_a2 = global == null ? void 0 : global.navigator) == null ? void 0 : _a2.product) === "ReactNative") {
444
+ if (typeof global !== "undefined" && ((_a3 = global == null ? void 0 : global.navigator) == null ? void 0 : _a3.product) === "ReactNative") {
425
445
  return true;
426
446
  }
427
447
  return (navigator == null ? void 0 : navigator.product) === "ReactNative";
428
448
  }
429
449
  function isReactNative() {
430
- var _a2;
450
+ var _a3;
431
451
  const hasWindowNavigator = typeof window !== "undefined" && window.navigator !== void 0;
432
452
  const nav = hasWindowNavigator ? window.navigator : void 0;
433
453
  if (!nav) {
434
454
  return false;
435
455
  }
436
- return hasWindowNavigator && ((_a2 = window.navigator) == null ? void 0 : _a2.product) === "ReactNative";
456
+ return hasWindowNavigator && ((_a3 = window.navigator) == null ? void 0 : _a3.product) === "ReactNative";
437
457
  }
438
458
  function isMetaMaskMobileWebView() {
439
459
  return typeof window !== "undefined" && // @ts-expect-error ReactNativeWebView should be defined
440
460
  Boolean(window.ReactNativeWebView) && Boolean(window.navigator.userAgent.endsWith("MetaMaskMobile"));
441
461
  }
442
462
  function isMobile() {
443
- var _a2, _b;
463
+ var _a3, _b;
444
464
  const browser = Bowser.parse(window.navigator.userAgent);
445
- 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";
465
+ 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";
446
466
  }
447
467
  function getPlatformType() {
448
468
  if (isReactNative()) {
@@ -460,11 +480,11 @@ function getPlatformType() {
460
480
  return "web-desktop" /* DesktopWeb */;
461
481
  }
462
482
  function isMetamaskExtensionInstalled() {
463
- var _a2;
483
+ var _a3;
464
484
  if (typeof window === "undefined") {
465
485
  return false;
466
486
  }
467
- return Boolean((_a2 = window.ethereum) == null ? void 0 : _a2.isMetaMask);
487
+ return Boolean((_a3 = window.ethereum) == null ? void 0 : _a3.isMetaMask);
468
488
  }
469
489
  function isSecure() {
470
490
  const platformType = getPlatformType();
@@ -495,8 +515,8 @@ var init_platform = __esm({
495
515
  return new Promise((resolve) => {
496
516
  const providers = [];
497
517
  const handler = (event) => {
498
- var _a2, _b;
499
- if ((_b = (_a2 = event == null ? void 0 : event.detail) == null ? void 0 : _a2.info) == null ? void 0 : _b.rdns) {
518
+ var _a3, _b;
519
+ if ((_b = (_a3 = event == null ? void 0 : event.detail) == null ? void 0 : _a3.info) == null ? void 0 : _b.rdns) {
500
520
  providers.push(event.detail);
501
521
  }
502
522
  };
@@ -506,8 +526,8 @@ var init_platform = __esm({
506
526
  window.removeEventListener("eip6963:announceProvider", handler);
507
527
  const hasMetaMask = providers.some(
508
528
  (provider) => {
509
- var _a2, _b;
510
- return (_b = (_a2 = provider == null ? void 0 : provider.info) == null ? void 0 : _a2.rdns) == null ? void 0 : _b.startsWith("io.metamask");
529
+ var _a3, _b;
530
+ return (_b = (_a3 = provider == null ? void 0 : provider.info) == null ? void 0 : _a3.rdns) == null ? void 0 : _b.startsWith("io.metamask");
511
531
  }
512
532
  );
513
533
  resolve(hasMetaMask);
@@ -591,12 +611,108 @@ var init_ui = __esm({
591
611
  }
592
612
  });
593
613
 
614
+ // src/multichain/utils/analytics.ts
615
+ function isRejectionError(error) {
616
+ var _a3, _b;
617
+ if (typeof error !== "object" || error === null) {
618
+ return false;
619
+ }
620
+ const errorObj = error;
621
+ const errorCode = errorObj.code;
622
+ const errorMessage = (_b = (_a3 = errorObj.message) == null ? void 0 : _a3.toLowerCase()) != null ? _b : "";
623
+ return errorCode === 4001 || // User rejected request (common EIP-1193 code)
624
+ errorCode === 4100 || // Unauthorized (common rejection code)
625
+ errorMessage.includes("reject") || errorMessage.includes("denied") || errorMessage.includes("cancel") || errorMessage.includes("user");
626
+ }
627
+ function getBaseAnalyticsProperties(options, storage) {
628
+ return __async(this, null, function* () {
629
+ var _a3, _b;
630
+ const version = getVersion();
631
+ const dappId = getDappId(options.dapp);
632
+ const platform = getPlatformType();
633
+ const anonId = yield storage.getAnonId();
634
+ const integrationType = (_b = (_a3 = options.analytics) == null ? void 0 : _a3.integrationType) != null ? _b : "unknown" /* UNKNOWN */;
635
+ return {
636
+ mmconnect_version: version,
637
+ dapp_id: dappId,
638
+ platform,
639
+ integration_type: integrationType,
640
+ anon_id: anonId
641
+ };
642
+ });
643
+ }
644
+ function getWalletActionAnalyticsProperties(options, storage, invokeOptions) {
645
+ return __async(this, null, function* () {
646
+ var _a3, _b;
647
+ const version = getVersion();
648
+ const dappId = getDappId(options.dapp);
649
+ const anonId = yield storage.getAnonId();
650
+ const integrationType = (_b = (_a3 = options.analytics) == null ? void 0 : _a3.integrationType) != null ? _b : "unknown";
651
+ return {
652
+ mmconnect_version: version,
653
+ dapp_id: dappId,
654
+ method: invokeOptions.request.method,
655
+ integration_type: integrationType,
656
+ caip_chain_id: invokeOptions.scope,
657
+ anon_id: anonId
658
+ };
659
+ });
660
+ }
661
+ var init_analytics = __esm({
662
+ "src/multichain/utils/analytics.ts"() {
663
+ "use strict";
664
+ init_utils2();
665
+ init_domain();
666
+ }
667
+ });
668
+
669
+ // src/domain/utils/index.ts
670
+ function getVersion() {
671
+ return "0.0.0";
672
+ }
673
+ var init_utils = __esm({
674
+ "src/domain/utils/index.ts"() {
675
+ "use strict";
676
+ init_analytics();
677
+ }
678
+ });
679
+
680
+ // src/domain/index.ts
681
+ var init_domain = __esm({
682
+ "src/domain/index.ts"() {
683
+ "use strict";
684
+ init_errors();
685
+ init_events();
686
+ init_logger();
687
+ init_multichain();
688
+ init_platform();
689
+ init_store();
690
+ init_ui();
691
+ init_utils();
692
+ }
693
+ });
694
+
594
695
  // src/multichain/utils/index.ts
595
696
  import {
596
697
  parseCaipAccountId,
597
698
  parseCaipChainId
598
699
  } from "@metamask/utils";
599
700
  import { deflate } from "pako";
701
+ function getGlobalObject() {
702
+ if (typeof globalThis !== "undefined") {
703
+ return globalThis;
704
+ }
705
+ if (typeof global !== "undefined") {
706
+ return global;
707
+ }
708
+ if (typeof self !== "undefined") {
709
+ return self;
710
+ }
711
+ if (typeof window !== "undefined") {
712
+ return window;
713
+ }
714
+ throw new Error("Unable to locate global object");
715
+ }
600
716
  function base64Encode(str) {
601
717
  if (typeof btoa !== "undefined") {
602
718
  return btoa(str);
@@ -611,13 +727,13 @@ function compressString(str) {
611
727
  return base64Encode(binaryString);
612
728
  }
613
729
  function getDappId(dapp) {
614
- var _a2;
615
- return (_a2 = dapp.url) != null ? _a2 : dapp.name;
730
+ var _a3;
731
+ return (_a3 = dapp.url) != null ? _a3 : dapp.name;
616
732
  }
617
733
  function openDeeplink(options, deeplink, universalLink) {
618
- var _a2;
734
+ var _a3;
619
735
  const { mobile } = options;
620
- const useDeeplink = (_a2 = mobile == null ? void 0 : mobile.useDeeplink) != null ? _a2 : true;
736
+ const useDeeplink = (_a3 = mobile == null ? void 0 : mobile.useDeeplink) != null ? _a3 : true;
621
737
  if (useDeeplink) {
622
738
  if (typeof window !== "undefined") {
623
739
  window.location.href = deeplink;
@@ -630,6 +746,29 @@ function openDeeplink(options, deeplink, universalLink) {
630
746
  link.click();
631
747
  }
632
748
  }
749
+ function mergeRequestedSessionWithExisting(sessionData, scopes, caipAccountIds, sessionProperties) {
750
+ const existingCaipChainIds = Object.keys(sessionData.sessionScopes);
751
+ const existingCaipAccountIds = [];
752
+ Object.values(sessionData.sessionScopes).forEach((scopeObject) => {
753
+ if ((scopeObject == null ? void 0 : scopeObject.accounts) && Array.isArray(scopeObject.accounts)) {
754
+ scopeObject.accounts.forEach((account) => {
755
+ existingCaipAccountIds.push(account);
756
+ });
757
+ }
758
+ });
759
+ const mergedScopes = Array.from(
760
+ /* @__PURE__ */ new Set([...existingCaipChainIds, ...scopes])
761
+ );
762
+ const mergedCaipAccountIds = Array.from(
763
+ /* @__PURE__ */ new Set([...existingCaipAccountIds, ...caipAccountIds])
764
+ );
765
+ const mergedSessionProperties = __spreadValues(__spreadValues({}, sessionData.sessionProperties), sessionProperties);
766
+ return {
767
+ mergedScopes,
768
+ mergedCaipAccountIds,
769
+ mergedSessionProperties
770
+ };
771
+ }
633
772
  function getOptionalScopes(scopes) {
634
773
  return scopes.reduce(
635
774
  (prev, scope) => __spreadProps(__spreadValues({}, prev), {
@@ -642,11 +781,26 @@ function getOptionalScopes(scopes) {
642
781
  {}
643
782
  );
644
783
  }
784
+ function normalizeNativeUrl(url) {
785
+ var _a3;
786
+ const httpPattern = /^https?:\/\//u;
787
+ if (httpPattern.test(url)) {
788
+ return void 0;
789
+ }
790
+ const schemeMatch = url.match(/^([^:]*):\/\//u);
791
+ const rawScheme = (_a3 = schemeMatch == null ? void 0 : schemeMatch[1]) != null ? _a3 : url;
792
+ const sanitized = rawScheme.toLowerCase().replace(/[^a-z0-9-]/gu, "-").replace(/^-+|-+$/gu, "");
793
+ const subdomain = (sanitized || "unknown").slice(0, 63).replace(/-+$/u, "");
794
+ return {
795
+ url: `https://${subdomain}.rn.dapp.local`,
796
+ nativeScheme: url
797
+ };
798
+ }
645
799
  function setupDappMetadata(options) {
646
- var _a2, _b;
800
+ var _a3, _b;
647
801
  const platform = getPlatformType();
648
802
  const isBrowser = platform === "web-desktop" /* DesktopWeb */ || platform === "web-mobile" /* MobileWeb */ || platform === "in-app-browser" /* MetaMaskMobileWebview */;
649
- if (!((_a2 = options.dapp) == null ? void 0 : _a2.name)) {
803
+ if (!((_a3 = options.dapp) == null ? void 0 : _a3.name)) {
650
804
  throw new Error("You must provide dapp name");
651
805
  }
652
806
  if (isBrowser) {
@@ -657,6 +811,18 @@ function setupDappMetadata(options) {
657
811
  if (!((_b = options.dapp) == null ? void 0 : _b.url)) {
658
812
  throw new Error("You must provide dapp url");
659
813
  }
814
+ if (platform === "react-native" /* ReactNative */ && options.dapp.url) {
815
+ const normalized = normalizeNativeUrl(options.dapp.url);
816
+ if (normalized) {
817
+ console.info(
818
+ `Normalizing dapp URL for React Native: "${options.dapp.url}" -> "${normalized.url}"`
819
+ );
820
+ options.dapp = __spreadProps(__spreadValues({}, options.dapp), {
821
+ url: normalized.url,
822
+ nativeScheme: normalized.nativeScheme
823
+ });
824
+ }
825
+ }
660
826
  const BASE_64_ICON_MAX_LENGTH = 163400;
661
827
  const urlPattern = /^(http|https):\/\/[^\s]*$/u;
662
828
  if (options.dapp) {
@@ -720,17 +886,17 @@ function getValidAccounts(caipAccountIds) {
720
886
  );
721
887
  }
722
888
  function addValidAccounts(optionalScopes, validAccounts) {
723
- var _a2;
889
+ var _a3;
724
890
  if (!optionalScopes || !(validAccounts == null ? void 0 : validAccounts.length)) {
725
891
  return optionalScopes;
726
892
  }
727
893
  const result = Object.fromEntries(
728
894
  Object.entries(optionalScopes).map(([scope, scopeData]) => {
729
- var _a3, _b, _c;
895
+ var _a4, _b, _c;
730
896
  return [
731
897
  scope,
732
898
  {
733
- methods: [...(_a3 = scopeData == null ? void 0 : scopeData.methods) != null ? _a3 : []],
899
+ methods: [...(_a4 = scopeData == null ? void 0 : scopeData.methods) != null ? _a4 : []],
734
900
  notifications: [...(_b = scopeData == null ? void 0 : scopeData.notifications) != null ? _b : []],
735
901
  accounts: [...(_c = scopeData == null ? void 0 : scopeData.accounts) != null ? _c : []]
736
902
  }
@@ -744,7 +910,7 @@ function addValidAccounts(optionalScopes, validAccounts) {
744
910
  if (!accountsByChain.has(chainKey)) {
745
911
  accountsByChain.set(chainKey, []);
746
912
  }
747
- (_a2 = accountsByChain.get(chainKey)) == null ? void 0 : _a2.push(accountId);
913
+ (_a3 = accountsByChain.get(chainKey)) == null ? void 0 : _a3.push(accountId);
748
914
  }
749
915
  for (const [scopeKey, scopeData] of Object.entries(result)) {
750
916
  if (!(scopeData == null ? void 0 : scopeData.accounts)) {
@@ -768,13 +934,13 @@ function addValidAccounts(optionalScopes, validAccounts) {
768
934
  }
769
935
  return result;
770
936
  }
771
- var extractFavicon;
772
- var init_utils = __esm({
937
+ var extractFavicon, MAX, idCounter, getUniqueRequestId;
938
+ var init_utils2 = __esm({
773
939
  "src/multichain/utils/index.ts"() {
774
940
  "use strict";
775
941
  init_domain();
776
942
  extractFavicon = () => {
777
- var _a2;
943
+ var _a3;
778
944
  if (typeof document === "undefined") {
779
945
  return void 0;
780
946
  }
@@ -782,92 +948,17 @@ var init_utils = __esm({
782
948
  const nodeList = document.getElementsByTagName("link");
783
949
  for (let i = 0; i < nodeList.length; i++) {
784
950
  if (nodeList[i].getAttribute("rel") === "icon" || nodeList[i].getAttribute("rel") === "shortcut icon") {
785
- favicon = (_a2 = nodeList[i].getAttribute("href")) != null ? _a2 : void 0;
951
+ favicon = (_a3 = nodeList[i].getAttribute("href")) != null ? _a3 : void 0;
786
952
  }
787
953
  }
788
954
  return favicon;
789
955
  };
790
- }
791
- });
792
-
793
- // src/multichain/utils/analytics.ts
794
- function isRejectionError(error) {
795
- var _a2, _b;
796
- if (typeof error !== "object" || error === null) {
797
- return false;
798
- }
799
- const errorObj = error;
800
- const errorCode = errorObj.code;
801
- const errorMessage = (_b = (_a2 = errorObj.message) == null ? void 0 : _a2.toLowerCase()) != null ? _b : "";
802
- return errorCode === 4001 || // User rejected request (common EIP-1193 code)
803
- errorCode === 4100 || // Unauthorized (common rejection code)
804
- errorMessage.includes("reject") || errorMessage.includes("denied") || errorMessage.includes("cancel") || errorMessage.includes("user");
805
- }
806
- function getBaseAnalyticsProperties(options, storage) {
807
- return __async(this, null, function* () {
808
- var _a2, _b;
809
- const version = getVersion();
810
- const dappId = getDappId(options.dapp);
811
- const platform = getPlatformType();
812
- const anonId = yield storage.getAnonId();
813
- const integrationType = (_b = (_a2 = options.analytics) == null ? void 0 : _a2.integrationType) != null ? _b : "unknown" /* UNKNOWN */;
814
- return {
815
- mmconnect_version: version,
816
- dapp_id: dappId,
817
- platform,
818
- integration_type: integrationType,
819
- anon_id: anonId
820
- };
821
- });
822
- }
823
- function getWalletActionAnalyticsProperties(options, storage, invokeOptions) {
824
- return __async(this, null, function* () {
825
- var _a2, _b;
826
- const version = getVersion();
827
- const dappId = getDappId(options.dapp);
828
- const anonId = yield storage.getAnonId();
829
- const integrationType = (_b = (_a2 = options.analytics) == null ? void 0 : _a2.integrationType) != null ? _b : "unknown";
830
- return {
831
- mmconnect_version: version,
832
- dapp_id: dappId,
833
- method: invokeOptions.request.method,
834
- integration_type: integrationType,
835
- caip_chain_id: invokeOptions.scope,
836
- anon_id: anonId
956
+ MAX = 4294967295;
957
+ idCounter = Math.floor(Math.random() * MAX);
958
+ getUniqueRequestId = () => {
959
+ idCounter = (idCounter + 1) % MAX;
960
+ return idCounter;
837
961
  };
838
- });
839
- }
840
- var init_analytics = __esm({
841
- "src/multichain/utils/analytics.ts"() {
842
- "use strict";
843
- init_utils();
844
- init_domain();
845
- }
846
- });
847
-
848
- // src/domain/utils/index.ts
849
- function getVersion() {
850
- return "0.0.0";
851
- }
852
- var init_utils2 = __esm({
853
- "src/domain/utils/index.ts"() {
854
- "use strict";
855
- init_analytics();
856
- }
857
- });
858
-
859
- // src/domain/index.ts
860
- var init_domain = __esm({
861
- "src/domain/index.ts"() {
862
- "use strict";
863
- init_errors();
864
- init_events();
865
- init_logger();
866
- init_multichain();
867
- init_platform();
868
- init_store();
869
- init_ui();
870
- init_utils2();
871
962
  }
872
963
  });
873
964
 
@@ -996,7 +1087,7 @@ var init_install = __esm({
996
1087
  renderQRCode() {
997
1088
  }
998
1089
  mount() {
999
- var _a2;
1090
+ var _a3;
1000
1091
  const { options } = this;
1001
1092
  const modal = document.createElement(
1002
1093
  "mm-install-modal"
@@ -1013,14 +1104,14 @@ var init_install = __esm({
1013
1104
  );
1014
1105
  modal.link = options.link;
1015
1106
  this.instance = modal;
1016
- (_a2 = options.parentElement) == null ? void 0 : _a2.appendChild(modal);
1107
+ (_a3 = options.parentElement) == null ? void 0 : _a3.appendChild(modal);
1017
1108
  this.startExpirationCheck(options.connectionRequest);
1018
1109
  }
1019
1110
  unmount() {
1020
- var _a2;
1111
+ var _a3;
1021
1112
  const { options, instance: modal } = this;
1022
1113
  this.stopExpirationCheck();
1023
- if (modal && ((_a2 = options.parentElement) == null ? void 0 : _a2.contains(modal))) {
1114
+ if (modal && ((_a3 = options.parentElement) == null ? void 0 : _a3.contains(modal))) {
1024
1115
  options.parentElement.removeChild(modal);
1025
1116
  this.instance = void 0;
1026
1117
  }
@@ -1132,8 +1223,8 @@ var init_web2 = __esm({
1132
1223
  const request = store.get(key);
1133
1224
  request.onerror = () => reject(new Error("Failed to get value from IndexedDB."));
1134
1225
  request.onsuccess = () => {
1135
- var _a2;
1136
- return resolve((_a2 = request.result) != null ? _a2 : null);
1226
+ var _a3;
1227
+ return resolve((_a3 = request.result) != null ? _a3 : null);
1137
1228
  };
1138
1229
  } catch (error) {
1139
1230
  reject(error);
@@ -1177,17 +1268,17 @@ var init_web2 = __esm({
1177
1268
  }
1178
1269
  };
1179
1270
  _StoreAdapterWeb.stores = ["sdk-kv-store", "key-value-pairs"];
1180
- _StoreAdapterWeb.DB_NAME = "mmsdk";
1271
+ _StoreAdapterWeb.DB_NAME = "mmconnect";
1181
1272
  StoreAdapterWeb = _StoreAdapterWeb;
1182
1273
  }
1183
1274
  });
1184
1275
 
1185
1276
  // src/polyfills/buffer-shim.ts
1277
+ init_utils2();
1186
1278
  import { Buffer as Buffer2 } from "buffer";
1187
- var globalObj = typeof globalThis !== "undefined" ? globalThis : typeof global !== "undefined" ? global : typeof window !== "undefined" ? window : {};
1188
- if (!globalObj.Buffer) {
1189
- globalObj.Buffer = Buffer2;
1190
- }
1279
+ var globalObj = getGlobalObject();
1280
+ var _a;
1281
+ (_a = globalObj.Buffer) != null ? _a : globalObj.Buffer = Buffer2;
1191
1282
 
1192
1283
  // src/index.browser.ts
1193
1284
  init_domain();
@@ -1260,8 +1351,8 @@ var RpcClient = class {
1260
1351
  });
1261
1352
  }
1262
1353
  getRpcEndpoint(scope) {
1263
- var _a2, _b, _c;
1264
- const supportedNetworks = (_c = (_b = (_a2 = this.config) == null ? void 0 : _a2.api) == null ? void 0 : _b.supportedNetworks) != null ? _c : {};
1354
+ var _a3, _b, _c;
1355
+ const supportedNetworks = (_c = (_b = (_a3 = this.config) == null ? void 0 : _a3.api) == null ? void 0 : _b.supportedNetworks) != null ? _c : {};
1265
1356
  const rpcEndpoint = supportedNetworks[scope];
1266
1357
  if (!rpcEndpoint) {
1267
1358
  throw new MissingRpcEndpointErr(
@@ -1325,7 +1416,7 @@ var RpcClient = class {
1325
1416
  // src/multichain/rpc/requestRouter.ts
1326
1417
  import { analytics } from "@metamask/analytics";
1327
1418
  init_domain();
1328
- init_utils();
1419
+ init_utils2();
1329
1420
  init_analytics();
1330
1421
  var _RequestRouter_instances, withAnalyticsTracking_fn, trackWalletActionRequested_fn, trackWalletActionSucceeded_fn, trackWalletActionFailed_fn, trackWalletActionRejected_fn;
1331
1422
  var RequestRouter = class {
@@ -1492,12 +1583,12 @@ trackWalletActionRejected_fn = function(options) {
1492
1583
  };
1493
1584
 
1494
1585
  // src/multichain/transports/default/index.ts
1495
- init_utils();
1586
+ init_utils2();
1496
1587
  import {
1497
1588
  getDefaultTransport
1498
1589
  } from "@metamask/multichain-api-client";
1499
1590
  var DEFAULT_REQUEST_TIMEOUT = 60 * 1e3;
1500
- var _notificationCallbacks, _transport, _defaultRequestOptions, _reqId, _pendingRequests, _handleResponseListener, _handleNotificationListener, _DefaultTransport_instances, notifyCallbacks_fn, isMetamaskProviderEvent_fn, handleResponse_fn, handleNotification_fn, setupMessageListener_fn;
1591
+ var _notificationCallbacks, _transport, _defaultRequestOptions, _pendingRequests, _handleResponseListener, _handleNotificationListener, _DefaultTransport_instances, notifyCallbacks_fn, isMetamaskProviderEvent_fn, handleResponse_fn, handleNotification_fn, setupMessageListener_fn;
1501
1592
  var DefaultTransport = class {
1502
1593
  constructor() {
1503
1594
  __privateAdd(this, _DefaultTransport_instances);
@@ -1506,8 +1597,6 @@ var DefaultTransport = class {
1506
1597
  __privateAdd(this, _defaultRequestOptions, {
1507
1598
  timeout: DEFAULT_REQUEST_TIMEOUT
1508
1599
  });
1509
- // Use timestamp-based ID to avoid conflicts across disconnect/reconnect cycles
1510
- __privateAdd(this, _reqId, Date.now());
1511
1600
  __privateAdd(this, _pendingRequests, /* @__PURE__ */ new Map());
1512
1601
  __privateAdd(this, _handleResponseListener);
1513
1602
  __privateAdd(this, _handleNotificationListener);
@@ -1515,18 +1604,17 @@ var DefaultTransport = class {
1515
1604
  sendEip1193Message(payload, options) {
1516
1605
  return __async(this, null, function* () {
1517
1606
  __privateMethod(this, _DefaultTransport_instances, setupMessageListener_fn).call(this);
1518
- __privateSet(this, _reqId, __privateGet(this, _reqId) + 1);
1519
- const requestId = `${__privateGet(this, _reqId)}`;
1607
+ const requestId = String(getUniqueRequestId());
1520
1608
  const request = __spreadValues({
1521
1609
  jsonrpc: "2.0",
1522
1610
  id: requestId
1523
1611
  }, payload);
1524
1612
  return new Promise((resolve, reject) => {
1525
- var _a2;
1613
+ var _a3;
1526
1614
  const timeout = setTimeout(() => {
1527
1615
  __privateGet(this, _pendingRequests).delete(requestId);
1528
1616
  reject(new Error("Request timeout"));
1529
- }, (_a2 = options == null ? void 0 : options.timeout) != null ? _a2 : __privateGet(this, _defaultRequestOptions).timeout);
1617
+ }, (_a3 = options == null ? void 0 : options.timeout) != null ? _a3 : __privateGet(this, _defaultRequestOptions).timeout);
1530
1618
  __privateGet(this, _pendingRequests).set(requestId, {
1531
1619
  resolve: (response) => {
1532
1620
  resolve(response);
@@ -1550,7 +1638,7 @@ var DefaultTransport = class {
1550
1638
  }
1551
1639
  connect(options) {
1552
1640
  return __async(this, null, function* () {
1553
- var _a2, _b, _c, _d, _e;
1641
+ var _a3, _b, _c, _d, _e;
1554
1642
  __privateMethod(this, _DefaultTransport_instances, setupMessageListener_fn).call(this);
1555
1643
  yield __privateGet(this, _transport).connect();
1556
1644
  const sessionRequest = yield this.request(
@@ -1563,7 +1651,7 @@ var DefaultTransport = class {
1563
1651
  let walletSession = sessionRequest.result;
1564
1652
  const createSessionParams = {
1565
1653
  optionalScopes: addValidAccounts(
1566
- getOptionalScopes((_a2 = options == null ? void 0 : options.scopes) != null ? _a2 : []),
1654
+ getOptionalScopes((_a3 = options == null ? void 0 : options.scopes) != null ? _a3 : []),
1567
1655
  getValidAccounts((_b = options == null ? void 0 : options.caipAccountIds) != null ? _b : [])
1568
1656
  ),
1569
1657
  sessionProperties: options == null ? void 0 : options.sessionProperties
@@ -1581,10 +1669,6 @@ var DefaultTransport = class {
1581
1669
  proposedCaipAccountIds
1582
1670
  );
1583
1671
  if (!hasSameScopesAndAccounts) {
1584
- yield this.request(
1585
- { method: "wallet_revokeSession", params: walletSession },
1586
- __privateGet(this, _defaultRequestOptions)
1587
- );
1588
1672
  const response = yield this.request(
1589
1673
  { method: "wallet_createSession", params: createSessionParams },
1590
1674
  __privateGet(this, _defaultRequestOptions)
@@ -1611,9 +1695,14 @@ var DefaultTransport = class {
1611
1695
  });
1612
1696
  }
1613
1697
  disconnect() {
1614
- return __async(this, null, function* () {
1698
+ return __async(this, arguments, function* (scopes = []) {
1699
+ yield this.request({ method: "wallet_revokeSession", params: { scopes } });
1700
+ const response = yield this.request({ method: "wallet_getSession" });
1701
+ const { sessionScopes } = response.result;
1702
+ if (Object.keys(sessionScopes).length > 0) {
1703
+ return;
1704
+ }
1615
1705
  __privateGet(this, _notificationCallbacks).clear();
1616
- yield this.request({ method: "wallet_revokeSession", params: {} });
1617
1706
  if (__privateGet(this, _handleResponseListener)) {
1618
1707
  window.removeEventListener("message", __privateGet(this, _handleResponseListener));
1619
1708
  __privateSet(this, _handleResponseListener, void 0);
@@ -1627,7 +1716,7 @@ var DefaultTransport = class {
1627
1716
  request.reject(new Error("Transport disconnected"));
1628
1717
  }
1629
1718
  __privateGet(this, _pendingRequests).clear();
1630
- return __privateGet(this, _transport).disconnect();
1719
+ yield __privateGet(this, _transport).disconnect();
1631
1720
  });
1632
1721
  }
1633
1722
  isConnected() {
@@ -1652,11 +1741,17 @@ var DefaultTransport = class {
1652
1741
  );
1653
1742
  });
1654
1743
  }
1744
+ getStoredPendingSessionRequest() {
1745
+ return __async(this, null, function* () {
1746
+ throw new Error(
1747
+ "getStoredPendingSessionRequest is purposely not implemented for the DefaultTransport"
1748
+ );
1749
+ });
1750
+ }
1655
1751
  };
1656
1752
  _notificationCallbacks = new WeakMap();
1657
1753
  _transport = new WeakMap();
1658
1754
  _defaultRequestOptions = new WeakMap();
1659
- _reqId = new WeakMap();
1660
1755
  _pendingRequests = new WeakMap();
1661
1756
  _handleResponseListener = new WeakMap();
1662
1757
  _handleNotificationListener = new WeakMap();
@@ -1674,16 +1769,16 @@ notifyCallbacks_fn = function(data) {
1674
1769
  }
1675
1770
  };
1676
1771
  isMetamaskProviderEvent_fn = function(event) {
1677
- var _a2, _b;
1678
- 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
1772
+ var _a3, _b;
1773
+ 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
1679
1774
  event.origin === location.origin;
1680
1775
  };
1681
1776
  handleResponse_fn = function(event) {
1682
- var _a2, _b;
1777
+ var _a3, _b;
1683
1778
  if (!__privateMethod(this, _DefaultTransport_instances, isMetamaskProviderEvent_fn).call(this, event)) {
1684
1779
  return;
1685
1780
  }
1686
- const responseData = (_b = (_a2 = event == null ? void 0 : event.data) == null ? void 0 : _a2.data) == null ? void 0 : _b.data;
1781
+ const responseData = (_b = (_a3 = event == null ? void 0 : event.data) == null ? void 0 : _a3.data) == null ? void 0 : _b.data;
1687
1782
  if (typeof responseData === "object" && responseData !== null && "method" in responseData) {
1688
1783
  return;
1689
1784
  }
@@ -1705,11 +1800,11 @@ handleResponse_fn = function(event) {
1705
1800
  }
1706
1801
  };
1707
1802
  handleNotification_fn = function(event) {
1708
- var _a2, _b;
1803
+ var _a3, _b;
1709
1804
  if (!__privateMethod(this, _DefaultTransport_instances, isMetamaskProviderEvent_fn).call(this, event)) {
1710
1805
  return;
1711
1806
  }
1712
- const responseData = (_b = (_a2 = event == null ? void 0 : event.data) == null ? void 0 : _a2.data) == null ? void 0 : _b.data;
1807
+ const responseData = (_b = (_a3 = event == null ? void 0 : event.data) == null ? void 0 : _a3.data) == null ? void 0 : _b.data;
1713
1808
  if (typeof responseData === "object" && responseData.method === "metamask_chainChanged" || responseData.method === "metamask_accountsChanged") {
1714
1809
  __privateMethod(this, _DefaultTransport_instances, notifyCallbacks_fn).call(this, responseData);
1715
1810
  }
@@ -1725,19 +1820,13 @@ setupMessageListener_fn = function() {
1725
1820
  };
1726
1821
 
1727
1822
  // src/multichain/transports/multichainApiClientWrapper/index.ts
1823
+ init_utils2();
1728
1824
  import { providerErrors } from "@metamask/rpc-errors";
1729
- var MAX = 4294967295;
1730
- var idCounter = Math.floor(Math.random() * MAX);
1731
- var getUniqueId = () => {
1732
- idCounter = (idCounter + 1) % MAX;
1733
- return idCounter;
1734
- };
1735
- var _requestId, _notificationCallbacks2, _MultichainApiClientWrapperTransport_instances, walletCreateSession_fn, walletGetSession_fn, walletRevokeSession_fn, walletInvokeMethod_fn;
1825
+ var _notificationCallbacks2, _MultichainApiClientWrapperTransport_instances, walletCreateSession_fn, walletGetSession_fn, walletRevokeSession_fn, walletInvokeMethod_fn;
1736
1826
  var MultichainApiClientWrapperTransport = class {
1737
1827
  constructor(metamaskConnectMultichain) {
1738
1828
  this.metamaskConnectMultichain = metamaskConnectMultichain;
1739
1829
  __privateAdd(this, _MultichainApiClientWrapperTransport_instances);
1740
- __privateAdd(this, _requestId, getUniqueId());
1741
1830
  __privateAdd(this, _notificationCallbacks2, /* @__PURE__ */ new Set());
1742
1831
  }
1743
1832
  isTransportDefined() {
@@ -1755,15 +1844,23 @@ var MultichainApiClientWrapperTransport = class {
1755
1844
  callback(data);
1756
1845
  });
1757
1846
  }
1758
- setupNotifcationListener() {
1759
- this.metamaskConnectMultichain.transport.onNotification(
1847
+ clearTransportNotificationListener() {
1848
+ var _a3;
1849
+ (_a3 = this.notificationListener) == null ? void 0 : _a3.call(this);
1850
+ this.notificationListener = void 0;
1851
+ }
1852
+ setupTransportNotificationListener() {
1853
+ if (!this.isTransportDefined() || this.notificationListener) {
1854
+ return;
1855
+ }
1856
+ this.notificationListener = this.metamaskConnectMultichain.transport.onNotification(
1760
1857
  this.notifyCallbacks.bind(this)
1761
1858
  );
1762
1859
  }
1763
1860
  connect() {
1764
1861
  return __async(this, null, function* () {
1765
1862
  console.log("\u{1F4DA} connect");
1766
- return Promise.resolve();
1863
+ yield this.metamaskConnectMultichain.emitSessionChanged();
1767
1864
  });
1768
1865
  }
1769
1866
  disconnect() {
@@ -1776,7 +1873,7 @@ var MultichainApiClientWrapperTransport = class {
1776
1873
  }
1777
1874
  request(_0) {
1778
1875
  return __async(this, arguments, function* (params, _options = {}) {
1779
- const id = __privateWrapper(this, _requestId)._++;
1876
+ const id = getUniqueRequestId();
1780
1877
  const requestPayload = __spreadValues({
1781
1878
  id,
1782
1879
  jsonrpc: "2.0"
@@ -1797,27 +1894,23 @@ var MultichainApiClientWrapperTransport = class {
1797
1894
  });
1798
1895
  }
1799
1896
  onNotification(callback) {
1800
- if (!this.isTransportDefined()) {
1801
- __privateGet(this, _notificationCallbacks2).add(callback);
1802
- return () => {
1803
- __privateGet(this, _notificationCallbacks2).delete(callback);
1804
- };
1805
- }
1806
- return this.metamaskConnectMultichain.transport.onNotification(callback);
1897
+ this.setupTransportNotificationListener();
1898
+ __privateGet(this, _notificationCallbacks2).add(callback);
1899
+ return () => {
1900
+ __privateGet(this, _notificationCallbacks2).delete(callback);
1901
+ };
1807
1902
  }
1808
1903
  };
1809
- _requestId = new WeakMap();
1810
1904
  _notificationCallbacks2 = new WeakMap();
1811
1905
  _MultichainApiClientWrapperTransport_instances = new WeakSet();
1812
1906
  walletCreateSession_fn = function(request) {
1813
1907
  return __async(this, null, function* () {
1814
- console.log("\u{1F4DA} #walletCreateSession", request);
1815
1908
  const createSessionParams = request.params;
1816
1909
  const scopes = Object.keys(__spreadValues(__spreadValues({}, createSessionParams.optionalScopes), createSessionParams.requiredScopes));
1817
1910
  const scopeAccounts = [];
1818
1911
  scopes.forEach((scope) => {
1819
- var _a2, _b, _c, _d;
1820
- const requiredScope = (_a2 = createSessionParams.requiredScopes) == null ? void 0 : _a2[scope];
1912
+ var _a3, _b, _c, _d;
1913
+ const requiredScope = (_a3 = createSessionParams.requiredScopes) == null ? void 0 : _a3[scope];
1821
1914
  const optionalScope = (_b = createSessionParams.optionalScopes) == null ? void 0 : _b[scope];
1822
1915
  if (requiredScope) {
1823
1916
  scopeAccounts.push(...(_c = requiredScope.accounts) != null ? _c : []);
@@ -1857,11 +1950,14 @@ walletGetSession_fn = function(request) {
1857
1950
  };
1858
1951
  walletRevokeSession_fn = function(request) {
1859
1952
  return __async(this, null, function* () {
1953
+ var _a3;
1860
1954
  if (!this.isTransportDefined()) {
1861
1955
  return { jsonrpc: "2.0", id: request.id, result: true };
1862
1956
  }
1957
+ const revokeSessionParams = request.params;
1958
+ const scopes = (_a3 = revokeSessionParams == null ? void 0 : revokeSessionParams.scopes) != null ? _a3 : [];
1863
1959
  try {
1864
- this.metamaskConnectMultichain.disconnect();
1960
+ yield this.metamaskConnectMultichain.disconnect(scopes);
1865
1961
  return { jsonrpc: "2.0", id: request.id, result: true };
1866
1962
  } catch (_error) {
1867
1963
  return { jsonrpc: "2.0", id: request.id, result: false };
@@ -1884,11 +1980,12 @@ walletInvokeMethod_fn = function(request) {
1884
1980
 
1885
1981
  // src/multichain/transports/mwp/index.ts
1886
1982
  init_domain();
1887
- init_utils();
1983
+ init_utils2();
1888
1984
  import { SessionStore } from "@metamask/mobile-wallet-protocol-core";
1889
1985
  import {
1890
1986
  TransportTimeoutError
1891
1987
  } from "@metamask/multichain-api-client";
1988
+ import { JsonRpcError, providerErrors as providerErrors2, rpcErrors } from "@metamask/rpc-errors";
1892
1989
 
1893
1990
  // src/multichain/transports/constants.ts
1894
1991
  var MULTICHAIN_PROVIDER_STREAM_NAME = "metamask-multichain-provider";
@@ -1901,6 +1998,7 @@ var DEFAULT_RESUME_TIMEOUT = 10 * 1e3;
1901
1998
  var SESSION_STORE_KEY = "cache_wallet_getSession";
1902
1999
  var ACCOUNTS_STORE_KEY = "cache_eth_accounts";
1903
2000
  var CHAIN_STORE_KEY = "cache_eth_chainId";
2001
+ var PENDING_SESSION_REQUEST_KEY = "pending_session_request";
1904
2002
  var CACHED_METHOD_LIST = [
1905
2003
  "wallet_getSession",
1906
2004
  "wallet_createSession",
@@ -1920,10 +2018,15 @@ var MWPTransport = class {
1920
2018
  this.dappClient = dappClient;
1921
2019
  this.kvstore = kvstore;
1922
2020
  this.options = options;
1923
- this.__reqId = 0;
1924
2021
  this.__pendingRequests = /* @__PURE__ */ new Map();
1925
2022
  this.notificationCallbacks = /* @__PURE__ */ new Set();
1926
2023
  this.dappClient.on("message", this.handleMessage.bind(this));
2024
+ this.dappClient.on("session_request", (sessionRequest) => {
2025
+ this.currentSessionRequest = sessionRequest;
2026
+ this.kvstore.set(PENDING_SESSION_REQUEST_KEY, JSON.stringify(sessionRequest)).catch((err) => {
2027
+ logger("Failed to store pending session request", err);
2028
+ });
2029
+ });
1927
2030
  if (typeof window !== "undefined" && typeof window.addEventListener !== "undefined") {
1928
2031
  this.windowFocusHandler = this.onWindowFocus.bind(this);
1929
2032
  window.addEventListener("focus", this.windowFocusHandler);
@@ -1938,6 +2041,34 @@ var MWPTransport = class {
1938
2041
  get sessionRequest() {
1939
2042
  return this.currentSessionRequest;
1940
2043
  }
2044
+ /**
2045
+ * Returns the stored pending session request from the dappClient session_request event, if any.
2046
+ *
2047
+ * @returns The stored SessionRequest, or null if none or invalid.
2048
+ */
2049
+ getStoredPendingSessionRequest() {
2050
+ return __async(this, null, function* () {
2051
+ try {
2052
+ const raw = yield this.kvstore.get(PENDING_SESSION_REQUEST_KEY);
2053
+ if (!raw) {
2054
+ return null;
2055
+ }
2056
+ return JSON.parse(raw);
2057
+ } catch (e) {
2058
+ return null;
2059
+ }
2060
+ });
2061
+ }
2062
+ /**
2063
+ * Removes the stored pending session request from the KVStore.
2064
+ * This is necessary to ensure that ConnectMultichain is able to correctly
2065
+ * infer the MWP Transport connection attempt status.
2066
+ */
2067
+ removeStoredPendingSessionRequest() {
2068
+ return __async(this, null, function* () {
2069
+ yield this.kvstore.delete(PENDING_SESSION_REQUEST_KEY);
2070
+ });
2071
+ }
1941
2072
  onWindowFocus() {
1942
2073
  if (!this.isConnected()) {
1943
2074
  this.dappClient.reconnect();
@@ -1954,6 +2085,18 @@ var MWPTransport = class {
1954
2085
  request.reject(error);
1955
2086
  }
1956
2087
  }
2088
+ parseWalletError(errorPayload) {
2089
+ const errorData = errorPayload;
2090
+ if (typeof errorData.code === "number" && typeof errorData.message === "string") {
2091
+ const { code, message: message2 } = errorData;
2092
+ if (code >= 1e3 && code <= 4999) {
2093
+ return providerErrors2.custom({ code, message: message2 });
2094
+ }
2095
+ return new JsonRpcError(code, message2);
2096
+ }
2097
+ const message = errorPayload instanceof Error ? errorPayload.message : JSON.stringify(errorPayload);
2098
+ return rpcErrors.internal({ message });
2099
+ }
1957
2100
  handleMessage(message) {
1958
2101
  if (typeof message === "object" && message !== null) {
1959
2102
  if ("data" in message) {
@@ -1961,6 +2104,12 @@ var MWPTransport = class {
1961
2104
  if ("id" in messagePayload && typeof messagePayload.id === "string") {
1962
2105
  const request = this.pendingRequests.get(messagePayload.id);
1963
2106
  if (request) {
2107
+ clearTimeout(request.timeout);
2108
+ if ("error" in messagePayload && messagePayload.error) {
2109
+ this.pendingRequests.delete(messagePayload.id);
2110
+ request.reject(this.parseWalletError(messagePayload.error));
2111
+ return;
2112
+ }
1964
2113
  const requestWithName = __spreadProps(__spreadValues({}, messagePayload), {
1965
2114
  method: request.method === "wallet_getSession" || request.method === "wallet_createSession" ? "wallet_sessionChanged" : request.method
1966
2115
  });
@@ -1968,7 +2117,6 @@ var MWPTransport = class {
1968
2117
  method: request.method === "wallet_getSession" || request.method === "wallet_createSession" ? "wallet_sessionChanged" : request.method,
1969
2118
  params: requestWithName.result
1970
2119
  });
1971
- clearTimeout(request.timeout);
1972
2120
  this.notifyCallbacks(notification);
1973
2121
  request.resolve(requestWithName);
1974
2122
  this.pendingRequests.delete(messagePayload.id);
@@ -2004,7 +2152,7 @@ var MWPTransport = class {
2004
2152
  }
2005
2153
  onResumeSuccess(resumeResolve, resumeReject, options) {
2006
2154
  return __async(this, null, function* () {
2007
- var _a2, _b, _c, _d, _e, _f, _g;
2155
+ var _a3, _b, _c, _d, _e, _f, _g;
2008
2156
  try {
2009
2157
  yield this.waitForWalletSessionIfNotCached();
2010
2158
  const sessionRequest = yield this.request({
@@ -2016,7 +2164,7 @@ var MWPTransport = class {
2016
2164
  let walletSession = sessionRequest.result;
2017
2165
  if (walletSession && options) {
2018
2166
  const currentScopes = Object.keys(
2019
- (_a2 = walletSession == null ? void 0 : walletSession.sessionScopes) != null ? _a2 : {}
2167
+ (_a3 = walletSession == null ? void 0 : walletSession.sessionScopes) != null ? _a3 : {}
2020
2168
  );
2021
2169
  const proposedScopes = (_b = options == null ? void 0 : options.scopes) != null ? _b : [];
2022
2170
  const proposedCaipAccountIds = (_c = options == null ? void 0 : options.caipAccountIds) != null ? _c : [];
@@ -2058,6 +2206,7 @@ var MWPTransport = class {
2058
2206
  }
2059
2207
  walletSession = response.result;
2060
2208
  }
2209
+ yield this.removeStoredPendingSessionRequest();
2061
2210
  this.notifyCallbacks({
2062
2211
  method: "wallet_sessionChanged",
2063
2212
  params: walletSession
@@ -2073,7 +2222,7 @@ var MWPTransport = class {
2073
2222
  return __async(this, null, function* () {
2074
2223
  const request = __spreadValues({
2075
2224
  jsonrpc: "2.0",
2076
- id: `${this.__reqId++}`
2225
+ id: String(getUniqueRequestId())
2077
2226
  }, payload);
2078
2227
  const cachedWalletSession = yield this.getCachedResponse(request);
2079
2228
  if (cachedWalletSession) {
@@ -2081,10 +2230,10 @@ var MWPTransport = class {
2081
2230
  return cachedWalletSession;
2082
2231
  }
2083
2232
  return new Promise((resolve, reject) => {
2084
- var _a2;
2233
+ var _a3;
2085
2234
  const timeout = setTimeout(() => {
2086
2235
  this.rejectRequest(request.id, new TransportTimeoutError());
2087
- }, (_a2 = options == null ? void 0 : options.timeout) != null ? _a2 : this.options.requestTimeout);
2236
+ }, (_a3 = options == null ? void 0 : options.timeout) != null ? _a3 : this.options.requestTimeout);
2088
2237
  this.pendingRequests.set(request.id, {
2089
2238
  request,
2090
2239
  method: request.method,
@@ -2107,30 +2256,35 @@ var MWPTransport = class {
2107
2256
  const { dappClient } = this;
2108
2257
  const session = yield this.getActiveSession();
2109
2258
  if (session) {
2110
- logger("active session found", session);
2259
+ logger("active session found", {
2260
+ id: session.id,
2261
+ channel: session.channel,
2262
+ expiresAt: session.expiresAt
2263
+ });
2111
2264
  }
2265
+ const storedSessionRequestBeforeConnectionAttempt = yield this.getStoredPendingSessionRequest();
2112
2266
  let timeout;
2113
2267
  let initialConnectionMessageHandler;
2114
2268
  const connectionPromise = new Promise((resolve, reject) => __async(this, null, function* () {
2115
2269
  let connection;
2116
2270
  if (session) {
2117
2271
  connection = new Promise((resumeResolve, resumeReject) => {
2118
- var _a2;
2272
+ var _a3;
2119
2273
  if (this.dappClient.state === "CONNECTED") {
2120
2274
  this.onResumeSuccess(resumeResolve, resumeReject, options);
2121
2275
  } else {
2122
2276
  this.dappClient.once("connected", () => __async(this, null, function* () {
2123
2277
  this.onResumeSuccess(resumeResolve, resumeReject, options);
2124
2278
  }));
2125
- dappClient.resume((_a2 = session == null ? void 0 : session.id) != null ? _a2 : "");
2279
+ dappClient.resume((_a3 = session == null ? void 0 : session.id) != null ? _a3 : "");
2126
2280
  }
2127
2281
  });
2128
2282
  } else {
2129
2283
  connection = new Promise(
2130
2284
  (resolveConnection, rejectConnection) => {
2131
- var _a2, _b;
2285
+ var _a3, _b;
2132
2286
  const optionalScopes = addValidAccounts(
2133
- getOptionalScopes((_a2 = options == null ? void 0 : options.scopes) != null ? _a2 : []),
2287
+ getOptionalScopes((_a3 = options == null ? void 0 : options.scopes) != null ? _a3 : []),
2134
2288
  getValidAccounts((_b = options == null ? void 0 : options.caipAccountIds) != null ? _b : [])
2135
2289
  );
2136
2290
  const sessionRequest = {
@@ -2139,33 +2293,35 @@ var MWPTransport = class {
2139
2293
  };
2140
2294
  const request = {
2141
2295
  jsonrpc: "2.0",
2142
- id: `${this.__reqId++}`,
2296
+ id: String(getUniqueRequestId()),
2143
2297
  method: "wallet_createSession",
2144
2298
  params: sessionRequest
2145
2299
  };
2146
2300
  initialConnectionMessageHandler = (message) => __async(this, null, function* () {
2147
- if (typeof message === "object" && message !== null) {
2148
- if ("data" in message) {
2149
- const messagePayload = message.data;
2150
- if (messagePayload.method === "wallet_createSession" || messagePayload.method === "wallet_sessionChanged") {
2151
- if (messagePayload.error) {
2152
- if (initialConnectionMessageHandler) {
2153
- this.dappClient.off(
2154
- "message",
2155
- initialConnectionMessageHandler
2156
- );
2157
- }
2158
- return rejectConnection(messagePayload.error);
2159
- }
2160
- yield this.storeWalletSession(
2161
- request,
2162
- messagePayload
2163
- );
2164
- this.notifyCallbacks(messagePayload);
2165
- return resolveConnection();
2166
- }
2167
- }
2301
+ if (typeof message !== "object" || message === null) {
2302
+ return;
2303
+ }
2304
+ if (!("data" in message)) {
2305
+ return;
2168
2306
  }
2307
+ const messagePayload = message.data;
2308
+ const isMatchingId = messagePayload.id === request.id;
2309
+ const isMatchingMethod = messagePayload.method === "wallet_createSession" || messagePayload.method === "wallet_sessionChanged";
2310
+ if (!isMatchingId && !isMatchingMethod) {
2311
+ return;
2312
+ }
2313
+ if (messagePayload.error) {
2314
+ return rejectConnection(
2315
+ this.parseWalletError(messagePayload.error)
2316
+ );
2317
+ }
2318
+ yield this.storeWalletSession(
2319
+ request,
2320
+ messagePayload
2321
+ );
2322
+ yield this.removeStoredPendingSessionRequest();
2323
+ this.notifyCallbacks(messagePayload);
2324
+ return resolveConnection();
2169
2325
  });
2170
2326
  this.dappClient.on("message", initialConnectionMessageHandler);
2171
2327
  dappClient.connect({
@@ -2186,14 +2342,18 @@ var MWPTransport = class {
2186
2342
  }
2187
2343
  );
2188
2344
  }
2189
- timeout = setTimeout(() => {
2190
- reject(new TransportTimeoutError());
2191
- }, this.options.connectionTimeout);
2345
+ timeout = setTimeout(
2346
+ () => {
2347
+ reject(new TransportTimeoutError());
2348
+ },
2349
+ storedSessionRequestBeforeConnectionAttempt ? this.options.resumeTimeout : this.options.connectionTimeout
2350
+ );
2192
2351
  connection.then(resolve).catch(reject);
2193
2352
  }));
2194
- return connectionPromise.catch((error) => {
2353
+ return connectionPromise.catch((error) => __async(this, null, function* () {
2354
+ yield this.dappClient.disconnect();
2195
2355
  throw error;
2196
- }).finally(() => {
2356
+ })).finally(() => {
2197
2357
  if (timeout) {
2198
2358
  clearTimeout(timeout);
2199
2359
  }
@@ -2201,24 +2361,68 @@ var MWPTransport = class {
2201
2361
  this.dappClient.off("message", initialConnectionMessageHandler);
2202
2362
  initialConnectionMessageHandler = void 0;
2203
2363
  }
2364
+ this.removeStoredPendingSessionRequest();
2204
2365
  });
2205
2366
  });
2206
2367
  }
2207
2368
  /**
2208
2369
  * Disconnects from the Mobile Wallet Protocol
2209
2370
  *
2371
+ * @param [scopes] - The scopes to revoke. If not provided or empty, all scopes will be revoked.
2210
2372
  * @returns Nothing
2211
2373
  */
2212
2374
  disconnect() {
2213
- return __async(this, null, function* () {
2214
- if (typeof window !== "undefined" && typeof window.removeEventListener !== "undefined" && this.windowFocusHandler) {
2215
- window.removeEventListener("focus", this.windowFocusHandler);
2216
- this.windowFocusHandler = void 0;
2217
- }
2218
- this.kvstore.delete(SESSION_STORE_KEY);
2219
- this.kvstore.delete(ACCOUNTS_STORE_KEY);
2220
- this.kvstore.delete(CHAIN_STORE_KEY);
2221
- return this.dappClient.disconnect();
2375
+ return __async(this, arguments, function* (scopes = []) {
2376
+ var _a3, _b;
2377
+ const cachedSession = yield this.getCachedResponse({
2378
+ jsonrpc: "2.0",
2379
+ id: "0",
2380
+ method: "wallet_getSession"
2381
+ });
2382
+ const cachedSessionScopes = (_b = (_a3 = cachedSession == null ? void 0 : cachedSession.result) == null ? void 0 : _a3.sessionScopes) != null ? _b : {};
2383
+ const remainingScopes = scopes.length === 0 ? [] : Object.keys(cachedSessionScopes).filter(
2384
+ (scope) => !scopes.includes(scope)
2385
+ );
2386
+ const newSessionScopes = Object.fromEntries(
2387
+ Object.entries(cachedSessionScopes).filter(
2388
+ ([key]) => remainingScopes.includes(key)
2389
+ )
2390
+ );
2391
+ this.request({ method: "wallet_revokeSession", params: { scopes } }).catch(
2392
+ (err) => {
2393
+ console.error("error revoking session", err);
2394
+ }
2395
+ );
2396
+ const remainingScopesIncludeEip155 = remainingScopes.some(
2397
+ (scope) => scope.includes("eip155")
2398
+ );
2399
+ if (!remainingScopesIncludeEip155) {
2400
+ this.kvstore.delete(ACCOUNTS_STORE_KEY);
2401
+ this.kvstore.delete(CHAIN_STORE_KEY);
2402
+ }
2403
+ if (remainingScopes.length > 0) {
2404
+ this.kvstore.set(
2405
+ SESSION_STORE_KEY,
2406
+ JSON.stringify({
2407
+ result: {
2408
+ sessionScopes: newSessionScopes
2409
+ }
2410
+ })
2411
+ );
2412
+ } else {
2413
+ this.kvstore.delete(SESSION_STORE_KEY);
2414
+ if (typeof window !== "undefined" && typeof window.removeEventListener !== "undefined" && this.windowFocusHandler) {
2415
+ window.removeEventListener("focus", this.windowFocusHandler);
2416
+ this.windowFocusHandler = void 0;
2417
+ }
2418
+ yield this.dappClient.disconnect();
2419
+ }
2420
+ this.notifyCallbacks({
2421
+ method: "wallet_sessionChanged",
2422
+ params: {
2423
+ sessionScopes: newSessionScopes
2424
+ }
2425
+ });
2222
2426
  });
2223
2427
  }
2224
2428
  /**
@@ -2263,7 +2467,7 @@ var MWPTransport = class {
2263
2467
  }
2264
2468
  getCachedResponse(request) {
2265
2469
  return __async(this, null, function* () {
2266
- var _a2;
2470
+ var _a3;
2267
2471
  if (request.method === "wallet_getSession") {
2268
2472
  const walletGetSession = yield this.kvstore.get(SESSION_STORE_KEY);
2269
2473
  if (walletGetSession) {
@@ -2271,7 +2475,7 @@ var MWPTransport = class {
2271
2475
  return {
2272
2476
  id: request.id,
2273
2477
  jsonrpc: "2.0",
2274
- result: (_a2 = walletSession.params) != null ? _a2 : walletSession.result,
2478
+ result: (_a3 = walletSession.params) != null ? _a3 : walletSession.result,
2275
2479
  // "what?... why walletSession.params?.."
2276
2480
  method: request.method
2277
2481
  };
@@ -2324,7 +2528,7 @@ var MWPTransport = class {
2324
2528
  return __async(this, null, function* () {
2325
2529
  const request = __spreadValues({
2326
2530
  jsonrpc: "2.0",
2327
- id: `${this.__reqId++}`
2531
+ id: String(getUniqueRequestId())
2328
2532
  }, payload);
2329
2533
  const cachedWalletSession = yield this.getCachedResponse(request);
2330
2534
  if (cachedWalletSession) {
@@ -2335,10 +2539,10 @@ var MWPTransport = class {
2335
2539
  yield this.attemptResumeSession();
2336
2540
  }
2337
2541
  return new Promise((resolve, reject) => {
2338
- var _a2;
2542
+ var _a3;
2339
2543
  const timeout = setTimeout(() => {
2340
2544
  this.rejectRequest(request.id, new TransportTimeoutError());
2341
- }, (_a2 = options == null ? void 0 : options.timeout) != null ? _a2 : this.options.requestTimeout);
2545
+ }, (_a3 = options == null ? void 0 : options.timeout) != null ? _a3 : this.options.requestTimeout);
2342
2546
  this.pendingRequests.set(request.id, {
2343
2547
  request,
2344
2548
  method: request.method,
@@ -2406,6 +2610,7 @@ var MWPTransport = class {
2406
2610
  const timeoutPromise = new Promise((_resolve, reject) => {
2407
2611
  setTimeout(() => {
2408
2612
  unsubscribe();
2613
+ this.removeStoredPendingSessionRequest();
2409
2614
  reject(new TransportTimeoutError());
2410
2615
  }, this.options.resumeTimeout);
2411
2616
  });
@@ -2442,14 +2647,15 @@ var KeyManager = class {
2442
2647
  var keymanager = new KeyManager();
2443
2648
 
2444
2649
  // src/multichain/index.ts
2445
- init_utils();
2650
+ init_utils2();
2446
2651
  var logger2 = createLogger("metamask-sdk:core");
2447
- 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;
2652
+ var SINGLETON_KEY = "__METAMASK_CONNECT_MULTICHAIN_SINGLETON__";
2653
+ 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;
2448
2654
  var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends MultichainCore {
2449
2655
  constructor(options) {
2450
- var _a2, _b, _c, _d, _e, _f;
2656
+ var _a3, _b, _c, _d, _e, _f;
2451
2657
  const withDappMetadata = setupDappMetadata(options);
2452
- const integrationType = (_b = (_a2 = options.analytics) == null ? void 0 : _a2.integrationType) != null ? _b : "direct";
2658
+ const integrationType = (_b = (_a3 = options.analytics) == null ? void 0 : _a3.integrationType) != null ? _b : "direct";
2453
2659
  const allOptions = __spreadProps(__spreadValues({}, withDappMetadata), {
2454
2660
  ui: __spreadProps(__spreadValues({}, withDappMetadata.ui), {
2455
2661
  preferExtension: (_c = withDappMetadata.ui.preferExtension) != null ? _c : true,
@@ -2469,7 +2675,7 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
2469
2675
  __privateAdd(this, _beforeUnloadListener);
2470
2676
  this._status = "pending";
2471
2677
  __privateAdd(this, _listener);
2472
- __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}`);
2678
+ __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}`);
2473
2679
  __privateSet(this, _providerTransportWrapper, new MultichainApiClientWrapperTransport(
2474
2680
  this
2475
2681
  ));
@@ -2481,9 +2687,9 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
2481
2687
  return this._status;
2482
2688
  }
2483
2689
  set status(value) {
2484
- var _a2, _b;
2690
+ var _a3, _b;
2485
2691
  this._status = value;
2486
- (_b = (_a2 = this.options.transport) == null ? void 0 : _a2.onNotification) == null ? void 0 : _b.call(_a2, {
2692
+ (_b = (_a3 = this.options.transport) == null ? void 0 : _a3.onNotification) == null ? void 0 : _b.call(_a3, {
2487
2693
  method: "stateChanged",
2488
2694
  params: value
2489
2695
  });
@@ -2509,27 +2715,54 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
2509
2715
  get transportType() {
2510
2716
  return __privateGet(this, _transport2) instanceof MWPTransport ? "mwp" /* MWP */ : "browser" /* Browser */;
2511
2717
  }
2718
+ // Creates a singleton instance of MetaMaskConnectMultichain.
2719
+ // If the singleton already exists, it merges the incoming options with the
2720
+ // existing singleton options for the following keys: `api.supportedNetworks`,
2721
+ // `ui.*`, `mobile.*`, `transport.extensionId`, `debug`. Take note that the
2722
+ // value for `dapp` is not merged as it does not make sense for subsequent calls to
2723
+ // `createMultichainClient` to have a different `dapp` value.
2512
2724
  static create(options) {
2513
2725
  return __async(this, null, function* () {
2514
- var _a2;
2515
- const instance = new _MetaMaskConnectMultichain(options);
2516
- const isEnabled2 = yield isEnabled(
2517
- "metamask-sdk:core",
2518
- instance.options.storage
2519
- );
2520
- if (isEnabled2) {
2521
- enableDebug("metamask-sdk:core");
2522
- }
2523
- yield __privateMethod(_a2 = instance, _MetaMaskConnectMultichain_instances, init_fn).call(_a2);
2524
- return instance;
2726
+ const globalObject = getGlobalObject();
2727
+ const existing = globalObject[SINGLETON_KEY];
2728
+ if (existing) {
2729
+ const instance = yield existing;
2730
+ instance.mergeOptions(options);
2731
+ if (options.debug) {
2732
+ enableDebug("metamask-sdk:*");
2733
+ }
2734
+ return instance;
2735
+ }
2736
+ const instancePromise = (() => __async(null, null, function* () {
2737
+ var _a3;
2738
+ const instance = new _MetaMaskConnectMultichain(options);
2739
+ const isEnabled2 = yield isEnabled(
2740
+ "metamask-sdk:core",
2741
+ instance.options.storage
2742
+ );
2743
+ if (isEnabled2) {
2744
+ enableDebug("metamask-sdk:core");
2745
+ }
2746
+ yield __privateMethod(_a3 = instance, _MetaMaskConnectMultichain_instances, init_fn).call(_a3);
2747
+ return instance;
2748
+ }))();
2749
+ globalObject[SINGLETON_KEY] = instancePromise;
2750
+ instancePromise.catch((error) => {
2751
+ globalObject[SINGLETON_KEY] = void 0;
2752
+ console.error("Error initializing MetaMaskConnectMultichain", error);
2753
+ });
2754
+ return instancePromise;
2525
2755
  });
2526
2756
  }
2527
2757
  // TODO: make this into param object
2528
2758
  connect(scopes, caipAccountIds, sessionProperties, forceRequest) {
2529
2759
  return __async(this, null, function* () {
2530
- var _a2;
2531
- if (this.status !== "connected") {
2532
- yield this.disconnect();
2760
+ var _a3;
2761
+ if (this.status === "connecting" && this.transportType === "mwp" /* MWP */) {
2762
+ yield __privateMethod(this, _MetaMaskConnectMultichain_instances, openConnectDeeplinkIfNeeded_fn).call(this);
2763
+ throw new Error(
2764
+ "Existing connection is pending. Please check your MetaMask Mobile app to continue."
2765
+ );
2533
2766
  }
2534
2767
  const { ui } = this.options;
2535
2768
  const platformType = getPlatformType();
@@ -2559,12 +2792,19 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
2559
2792
  } catch (error) {
2560
2793
  logger2("Error tracking connection_initiated event", error);
2561
2794
  }
2562
- const nonEmptySessionProperites = Object.keys(sessionProperties != null ? sessionProperties : {}).length > 0 ? sessionProperties : void 0;
2563
- if (((_a2 = __privateGet(this, _transport2)) == null ? void 0 : _a2.isConnected()) && !secure) {
2795
+ const sessionData = yield __privateMethod(this, _MetaMaskConnectMultichain_instances, getCaipSession_fn).call(this);
2796
+ const { mergedScopes, mergedCaipAccountIds, mergedSessionProperties } = mergeRequestedSessionWithExisting(
2797
+ sessionData,
2798
+ scopes,
2799
+ caipAccountIds,
2800
+ sessionProperties
2801
+ );
2802
+ const nonEmptySessionProperties = Object.keys(mergedSessionProperties != null ? mergedSessionProperties : {}).length > 0 ? mergedSessionProperties : void 0;
2803
+ if (((_a3 = __privateGet(this, _transport2)) == null ? void 0 : _a3.isConnected()) && !secure) {
2564
2804
  return __privateMethod(this, _MetaMaskConnectMultichain_instances, handleConnection_fn).call(this, __privateGet(this, _transport2).connect({
2565
- scopes,
2566
- caipAccountIds,
2567
- sessionProperties: nonEmptySessionProperites,
2805
+ scopes: mergedScopes,
2806
+ caipAccountIds: mergedCaipAccountIds,
2807
+ sessionProperties: nonEmptySessionProperties,
2568
2808
  forceRequest
2569
2809
  }).then(() => __async(this, null, function* () {
2570
2810
  if (__privateGet(this, _transport2) instanceof MWPTransport) {
@@ -2576,47 +2816,53 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
2576
2816
  if (platformType === "in-app-browser" /* MetaMaskMobileWebview */) {
2577
2817
  const defaultTransport = yield __privateMethod(this, _MetaMaskConnectMultichain_instances, setupDefaultTransport_fn).call(this);
2578
2818
  return __privateMethod(this, _MetaMaskConnectMultichain_instances, handleConnection_fn).call(this, defaultTransport.connect({
2579
- scopes,
2580
- caipAccountIds,
2581
- sessionProperties: nonEmptySessionProperites,
2819
+ scopes: mergedScopes,
2820
+ caipAccountIds: mergedCaipAccountIds,
2821
+ sessionProperties: nonEmptySessionProperties,
2582
2822
  forceRequest
2583
2823
  }), scopes, transportType);
2584
2824
  }
2585
2825
  if (isWeb && hasExtensionInstalled && preferExtension) {
2586
2826
  const defaultTransport = yield __privateMethod(this, _MetaMaskConnectMultichain_instances, setupDefaultTransport_fn).call(this);
2587
2827
  return __privateMethod(this, _MetaMaskConnectMultichain_instances, handleConnection_fn).call(this, defaultTransport.connect({
2588
- scopes,
2589
- caipAccountIds,
2590
- sessionProperties: nonEmptySessionProperites,
2828
+ scopes: mergedScopes,
2829
+ caipAccountIds: mergedCaipAccountIds,
2830
+ sessionProperties: nonEmptySessionProperties,
2591
2831
  forceRequest
2592
2832
  }), scopes, transportType);
2593
2833
  }
2594
2834
  yield __privateMethod(this, _MetaMaskConnectMultichain_instances, setupMWP_fn).call(this);
2595
2835
  const shouldShowInstallModal = hasExtensionInstalled ? showInstallModal : !preferExtension || showInstallModal;
2596
2836
  if (secure && !shouldShowInstallModal) {
2597
- return __privateMethod(this, _MetaMaskConnectMultichain_instances, handleConnection_fn).call(this, __privateMethod(this, _MetaMaskConnectMultichain_instances, deeplinkConnect_fn).call(this, scopes, caipAccountIds, nonEmptySessionProperites), scopes, transportType);
2837
+ return __privateMethod(this, _MetaMaskConnectMultichain_instances, handleConnection_fn).call(this, __privateMethod(this, _MetaMaskConnectMultichain_instances, deeplinkConnect_fn).call(this, mergedScopes, mergedCaipAccountIds, nonEmptySessionProperties), scopes, transportType);
2598
2838
  }
2599
- return __privateMethod(this, _MetaMaskConnectMultichain_instances, handleConnection_fn).call(this, __privateMethod(this, _MetaMaskConnectMultichain_instances, showInstallModal_fn).call(this, shouldShowInstallModal, scopes, caipAccountIds, nonEmptySessionProperites), scopes, transportType);
2839
+ return __privateMethod(this, _MetaMaskConnectMultichain_instances, handleConnection_fn).call(this, __privateMethod(this, _MetaMaskConnectMultichain_instances, showInstallModal_fn).call(this, shouldShowInstallModal, mergedScopes, mergedCaipAccountIds, nonEmptySessionProperties), scopes, transportType);
2600
2840
  });
2601
2841
  }
2602
2842
  emit(event, args) {
2603
- var _a2, _b;
2604
- (_b = (_a2 = this.options.transport) == null ? void 0 : _a2.onNotification) == null ? void 0 : _b.call(_a2, { method: event, params: args });
2843
+ var _a3, _b;
2844
+ (_b = (_a3 = this.options.transport) == null ? void 0 : _a3.onNotification) == null ? void 0 : _b.call(_a3, { method: event, params: args });
2605
2845
  super.emit(event, args);
2606
2846
  }
2607
2847
  disconnect() {
2608
- return __async(this, null, function* () {
2609
- var _a2, _b, _c;
2610
- yield (_a2 = __privateGet(this, _listener)) == null ? void 0 : _a2.call(this);
2611
- (_b = __privateGet(this, _beforeUnloadListener)) == null ? void 0 : _b.call(this);
2612
- yield (_c = __privateGet(this, _transport2)) == null ? void 0 : _c.disconnect();
2613
- yield this.storage.removeTransport();
2614
- this.emit("stateChanged", "disconnected");
2615
- __privateSet(this, _listener, void 0);
2616
- __privateSet(this, _beforeUnloadListener, void 0);
2617
- __privateSet(this, _transport2, void 0);
2618
- __privateGet(this, _providerTransportWrapper).clearNotificationCallbacks();
2619
- __privateSet(this, _dappClient, void 0);
2848
+ return __async(this, arguments, function* (scopes = []) {
2849
+ var _a3, _b, _c;
2850
+ const sessionData = yield __privateMethod(this, _MetaMaskConnectMultichain_instances, getCaipSession_fn).call(this);
2851
+ const remainingScopes = scopes.length === 0 ? [] : Object.keys(sessionData.sessionScopes).filter(
2852
+ (scope) => !scopes.includes(scope)
2853
+ );
2854
+ yield (_a3 = __privateGet(this, _transport2)) == null ? void 0 : _a3.disconnect(scopes);
2855
+ if (remainingScopes.length === 0) {
2856
+ yield (_b = __privateGet(this, _listener)) == null ? void 0 : _b.call(this);
2857
+ (_c = __privateGet(this, _beforeUnloadListener)) == null ? void 0 : _c.call(this);
2858
+ yield this.storage.removeTransport();
2859
+ __privateSet(this, _listener, void 0);
2860
+ __privateSet(this, _beforeUnloadListener, void 0);
2861
+ __privateSet(this, _transport2, void 0);
2862
+ __privateGet(this, _providerTransportWrapper).clearTransportNotificationListener();
2863
+ __privateSet(this, _dappClient, void 0);
2864
+ this.status = "disconnected";
2865
+ }
2620
2866
  });
2621
2867
  }
2622
2868
  invokeMethod(request) {
@@ -2628,7 +2874,7 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
2628
2874
  });
2629
2875
  }
2630
2876
  // DRY THIS WITH REQUEST ROUTER
2631
- openDeeplinkIfNeeded() {
2877
+ openSimpleDeeplinkIfNeeded() {
2632
2878
  const { ui, mobile } = this.options;
2633
2879
  const { showInstallModal = false } = ui != null ? ui : {};
2634
2880
  const secure = isSecure();
@@ -2648,6 +2894,23 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
2648
2894
  }), 10);
2649
2895
  }
2650
2896
  }
2897
+ // Provides a way for ecosystem clients (EVM, Solana, etc.) to get the current CAIP session data
2898
+ // when instantiating themselves (as they would have already missed any initial sessionChanged events emitted by ConnectMultichain)
2899
+ // without having to concern themselves with the current transport connection status.
2900
+ emitSessionChanged() {
2901
+ return __async(this, null, function* () {
2902
+ var _a3;
2903
+ const emptySession = { sessionScopes: {} };
2904
+ if (this.status !== "connected" && this.status !== "connecting") {
2905
+ this.emit("wallet_sessionChanged", emptySession);
2906
+ return;
2907
+ }
2908
+ const response = yield this.transport.request({
2909
+ method: "wallet_getSession"
2910
+ });
2911
+ this.emit("wallet_sessionChanged", (_a3 = response.result) != null ? _a3 : emptySession);
2912
+ });
2913
+ }
2651
2914
  };
2652
2915
  _provider = new WeakMap();
2653
2916
  _providerTransportWrapper = new WeakMap();
@@ -2659,7 +2922,7 @@ _sdkInfo = new WeakMap();
2659
2922
  _MetaMaskConnectMultichain_instances = new WeakSet();
2660
2923
  setupAnalytics_fn = function() {
2661
2924
  return __async(this, null, function* () {
2662
- var _a2;
2925
+ var _a3;
2663
2926
  const platform = getPlatformType();
2664
2927
  const isBrowser = platform === "in-app-browser" /* MetaMaskMobileWebview */ || platform === "web-desktop" /* DesktopWeb */ || platform === "web-mobile" /* MobileWeb */;
2665
2928
  const isReactNative2 = platform === "react-native" /* ReactNative */;
@@ -2669,7 +2932,7 @@ setupAnalytics_fn = function() {
2669
2932
  const version = getVersion();
2670
2933
  const dappId = getDappId(this.options.dapp);
2671
2934
  const anonId = yield this.storage.getAnonId();
2672
- const { integrationType } = (_a2 = this.options.analytics) != null ? _a2 : {
2935
+ const { integrationType } = (_a3 = this.options.analytics) != null ? _a3 : {
2673
2936
  integrationType: ""
2674
2937
  };
2675
2938
  analytics2.setGlobalProperty("mmconnect_version", version);
@@ -2682,9 +2945,9 @@ setupAnalytics_fn = function() {
2682
2945
  };
2683
2946
  onTransportNotification_fn = function(payload) {
2684
2947
  return __async(this, null, function* () {
2685
- var _a2;
2948
+ var _a3;
2686
2949
  if (typeof payload === "object" && payload !== null && "method" in payload) {
2687
- this.emit(payload.method, (_a2 = payload.params) != null ? _a2 : payload.result);
2950
+ this.emit(payload.method, (_a3 = payload.params) != null ? _a3 : payload.result);
2688
2951
  }
2689
2952
  });
2690
2953
  };
@@ -2697,7 +2960,7 @@ getStoredTransport_fn = function() {
2697
2960
  if (hasExtensionInstalled) {
2698
2961
  const apiTransport = new DefaultTransport();
2699
2962
  __privateSet(this, _transport2, apiTransport);
2700
- __privateGet(this, _providerTransportWrapper).setupNotifcationListener();
2963
+ __privateGet(this, _providerTransportWrapper).setupTransportNotificationListener();
2701
2964
  __privateSet(this, _listener, apiTransport.onNotification(
2702
2965
  __privateMethod(this, _MetaMaskConnectMultichain_instances, onTransportNotification_fn).bind(this)
2703
2966
  ));
@@ -2709,7 +2972,7 @@ getStoredTransport_fn = function() {
2709
2972
  const apiTransport = new MWPTransport(dappClient, kvstore);
2710
2973
  __privateSet(this, _dappClient, dappClient);
2711
2974
  __privateSet(this, _transport2, apiTransport);
2712
- __privateGet(this, _providerTransportWrapper).setupNotifcationListener();
2975
+ __privateGet(this, _providerTransportWrapper).setupTransportNotificationListener();
2713
2976
  __privateSet(this, _listener, apiTransport.onNotification(
2714
2977
  __privateMethod(this, _MetaMaskConnectMultichain_instances, onTransportNotification_fn).bind(this)
2715
2978
  ));
@@ -2741,25 +3004,17 @@ setupTransport_fn = function() {
2741
3004
  };
2742
3005
  init_fn = function() {
2743
3006
  return __async(this, null, function* () {
2744
- var _a2;
2745
3007
  try {
2746
- if (typeof window !== "undefined" && ((_a2 = window.mmsdk) == null ? void 0 : _a2.isInitialized)) {
2747
- logger2("MetaMaskSDK: init already initialized");
2748
- } else {
2749
- yield __privateMethod(this, _MetaMaskConnectMultichain_instances, setupAnalytics_fn).call(this);
2750
- yield __privateMethod(this, _MetaMaskConnectMultichain_instances, setupTransport_fn).call(this);
2751
- try {
2752
- const baseProps = yield getBaseAnalyticsProperties(
2753
- this.options,
2754
- this.storage
2755
- );
2756
- analytics2.track("mmconnect_initialized", baseProps);
2757
- } catch (error) {
2758
- logger2("Error tracking initialized event", error);
2759
- }
2760
- if (typeof window !== "undefined") {
2761
- window.mmsdk = this;
2762
- }
3008
+ yield __privateMethod(this, _MetaMaskConnectMultichain_instances, setupAnalytics_fn).call(this);
3009
+ yield __privateMethod(this, _MetaMaskConnectMultichain_instances, setupTransport_fn).call(this);
3010
+ try {
3011
+ const baseProps = yield getBaseAnalyticsProperties(
3012
+ this.options,
3013
+ this.storage
3014
+ );
3015
+ analytics2.track("mmconnect_initialized", baseProps);
3016
+ } catch (error) {
3017
+ logger2("Error tracking initialized event", error);
2763
3018
  }
2764
3019
  } catch (error) {
2765
3020
  yield this.storage.removeTransport();
@@ -2795,7 +3050,7 @@ setupMWP_fn = function() {
2795
3050
  __privateSet(this, _dappClient, dappClient);
2796
3051
  const apiTransport = new MWPTransport(dappClient, kvstore);
2797
3052
  __privateSet(this, _transport2, apiTransport);
2798
- __privateGet(this, _providerTransportWrapper).setupNotifcationListener();
3053
+ __privateGet(this, _providerTransportWrapper).setupTransportNotificationListener();
2799
3054
  __privateSet(this, _listener, this.transport.onNotification(
2800
3055
  __privateMethod(this, _MetaMaskConnectMultichain_instances, onTransportNotification_fn).bind(this)
2801
3056
  ));
@@ -2804,22 +3059,20 @@ setupMWP_fn = function() {
2804
3059
  };
2805
3060
  onBeforeUnload_fn = function() {
2806
3061
  return __async(this, null, function* () {
2807
- var _a2;
2808
- if ((_a2 = this.options.ui.factory.modal) == null ? void 0 : _a2.isMounted) {
3062
+ var _a3;
3063
+ if ((_a3 = this.options.ui.factory.modal) == null ? void 0 : _a3.isMounted) {
2809
3064
  yield this.storage.removeTransport();
2810
3065
  }
2811
3066
  });
2812
3067
  };
2813
3068
  createBeforeUnloadListener_fn = function() {
3069
+ const handler = __privateMethod(this, _MetaMaskConnectMultichain_instances, onBeforeUnload_fn).bind(this);
2814
3070
  if (typeof window !== "undefined" && typeof window.addEventListener !== "undefined") {
2815
- window.addEventListener("beforeunload", __privateMethod(this, _MetaMaskConnectMultichain_instances, onBeforeUnload_fn).bind(this));
3071
+ window.addEventListener("beforeunload", handler);
2816
3072
  }
2817
3073
  return () => {
2818
3074
  if (typeof window !== "undefined" && typeof window.removeEventListener !== "undefined") {
2819
- window.removeEventListener(
2820
- "beforeunload",
2821
- __privateMethod(this, _MetaMaskConnectMultichain_instances, onBeforeUnload_fn).bind(this)
2822
- );
3075
+ window.removeEventListener("beforeunload", handler);
2823
3076
  }
2824
3077
  };
2825
3078
  };
@@ -2849,7 +3102,7 @@ renderInstallModalAsync_fn = function(desktopPreferred, scopes, caipAccountIds,
2849
3102
  }
2850
3103
  );
2851
3104
  (() => __async(this, null, function* () {
2852
- var _a2;
3105
+ var _a3;
2853
3106
  try {
2854
3107
  yield this.transport.connect({
2855
3108
  scopes,
@@ -2857,20 +3110,21 @@ renderInstallModalAsync_fn = function(desktopPreferred, scopes, caipAccountIds,
2857
3110
  sessionProperties
2858
3111
  });
2859
3112
  yield this.options.ui.factory.unload();
2860
- (_a2 = this.options.ui.factory.modal) == null ? void 0 : _a2.unmount();
3113
+ (_a3 = this.options.ui.factory.modal) == null ? void 0 : _a3.unmount();
2861
3114
  this.status = "connected";
2862
3115
  yield this.storage.setTransport("mwp" /* MWP */);
2863
3116
  } catch (error) {
2864
3117
  if (error instanceof ProtocolError) {
2865
3118
  if (error.code !== ErrorCode.REQUEST_EXPIRED) {
2866
3119
  this.status = "disconnected";
3120
+ yield this.options.ui.factory.unload(error);
2867
3121
  reject(error);
2868
3122
  }
2869
3123
  } else {
2870
3124
  this.status = "disconnected";
2871
- reject(
2872
- error instanceof Error ? error : new Error(String(error))
2873
- );
3125
+ const normalizedError = error instanceof Error ? error : new Error(String(error));
3126
+ yield this.options.ui.factory.unload(normalizedError);
3127
+ reject(normalizedError);
2874
3128
  }
2875
3129
  }
2876
3130
  }))().catch(() => {
@@ -2897,8 +3151,8 @@ renderInstallModalAsync_fn = function(desktopPreferred, scopes, caipAccountIds,
2897
3151
  };
2898
3152
  showInstallModal_fn = function(desktopPreferred, scopes, caipAccountIds, sessionProperties) {
2899
3153
  return __async(this, null, function* () {
2900
- var _a2;
2901
- (_a2 = __privateGet(this, _beforeUnloadListener)) != null ? _a2 : __privateSet(this, _beforeUnloadListener, __privateMethod(this, _MetaMaskConnectMultichain_instances, createBeforeUnloadListener_fn).call(this));
3154
+ var _a3;
3155
+ (_a3 = __privateGet(this, _beforeUnloadListener)) != null ? _a3 : __privateSet(this, _beforeUnloadListener, __privateMethod(this, _MetaMaskConnectMultichain_instances, createBeforeUnloadListener_fn).call(this));
2902
3156
  if (this.options.ui.headless) {
2903
3157
  yield __privateMethod(this, _MetaMaskConnectMultichain_instances, headlessConnect_fn).call(this, scopes, caipAccountIds, sessionProperties);
2904
3158
  } else {
@@ -2957,7 +3211,7 @@ setupDefaultTransport_fn = function() {
2957
3211
  __privateMethod(this, _MetaMaskConnectMultichain_instances, onTransportNotification_fn).bind(this)
2958
3212
  ));
2959
3213
  __privateSet(this, _transport2, transport);
2960
- __privateGet(this, _providerTransportWrapper).setupNotifcationListener();
3214
+ __privateGet(this, _providerTransportWrapper).setupTransportNotificationListener();
2961
3215
  return transport;
2962
3216
  });
2963
3217
  };
@@ -2965,7 +3219,7 @@ deeplinkConnect_fn = function(scopes, caipAccountIds, sessionProperties) {
2965
3219
  return __async(this, null, function* () {
2966
3220
  return new Promise((resolve, reject) => __async(this, null, function* () {
2967
3221
  const dappClientMessageHandler = (payload) => {
2968
- var _a2;
3222
+ var _a3;
2969
3223
  if (typeof payload !== "object" || payload === null || !("data" in payload)) {
2970
3224
  return;
2971
3225
  }
@@ -2975,7 +3229,7 @@ deeplinkConnect_fn = function(scopes, caipAccountIds, sessionProperties) {
2975
3229
  this.dappClient.off("message", dappClientMessageHandler);
2976
3230
  reject(data.error);
2977
3231
  }
2978
- if ((_a2 = data == null ? void 0 : data.result) == null ? void 0 : _a2.sessionScopes) {
3232
+ if ((_a3 = data == null ? void 0 : data.result) == null ? void 0 : _a3.sessionScopes) {
2979
3233
  this.dappClient.off("message", dappClientMessageHandler);
2980
3234
  }
2981
3235
  }
@@ -2984,13 +3238,13 @@ deeplinkConnect_fn = function(scopes, caipAccountIds, sessionProperties) {
2984
3238
  let timeout;
2985
3239
  if (this.transport.isConnected()) {
2986
3240
  timeout = setTimeout(() => {
2987
- this.openDeeplinkIfNeeded();
3241
+ this.openSimpleDeeplinkIfNeeded();
2988
3242
  }, 250);
2989
3243
  } else {
2990
3244
  this.dappClient.once(
2991
3245
  "session_request",
2992
3246
  (sessionRequest) => {
2993
- var _a2;
3247
+ var _a3;
2994
3248
  const connectionRequest = {
2995
3249
  sessionRequest,
2996
3250
  metadata: {
@@ -3005,7 +3259,7 @@ deeplinkConnect_fn = function(scopes, caipAccountIds, sessionProperties) {
3005
3259
  connectionRequest
3006
3260
  );
3007
3261
  this.emit("display_uri", deeplink);
3008
- if ((_a2 = this.options.mobile) == null ? void 0 : _a2.preferredOpenLink) {
3262
+ if ((_a3 = this.options.mobile) == null ? void 0 : _a3.preferredOpenLink) {
3009
3263
  this.options.mobile.preferredOpenLink(deeplink, "_self");
3010
3264
  } else {
3011
3265
  openDeeplink(this.options, deeplink, universalLink);
@@ -3067,6 +3321,53 @@ handleConnection_fn = function(promise, scopes, transportType) {
3067
3321
  }));
3068
3322
  });
3069
3323
  };
3324
+ getCaipSession_fn = function() {
3325
+ return __async(this, null, function* () {
3326
+ let sessionData = {
3327
+ sessionScopes: {},
3328
+ sessionProperties: {}
3329
+ };
3330
+ if (this.status === "connected") {
3331
+ const response = yield this.transport.request({
3332
+ method: "wallet_getSession"
3333
+ });
3334
+ if (response.result) {
3335
+ sessionData = response.result;
3336
+ }
3337
+ }
3338
+ return sessionData;
3339
+ });
3340
+ };
3341
+ openConnectDeeplinkIfNeeded_fn = function() {
3342
+ return __async(this, null, function* () {
3343
+ var _a3, _b;
3344
+ const { ui } = this.options;
3345
+ const { showInstallModal = false } = ui != null ? ui : {};
3346
+ const secure = isSecure();
3347
+ const shouldOpenDeeplink = secure && !showInstallModal;
3348
+ if (!shouldOpenDeeplink) {
3349
+ return;
3350
+ }
3351
+ const storedSessionRequest = yield (_a3 = __privateGet(this, _transport2)) == null ? void 0 : _a3.getStoredPendingSessionRequest();
3352
+ if (!storedSessionRequest) {
3353
+ return;
3354
+ }
3355
+ const connectionRequest = {
3356
+ sessionRequest: storedSessionRequest,
3357
+ metadata: {
3358
+ dapp: this.options.dapp,
3359
+ sdk: { version: getVersion(), platform: getPlatformType() }
3360
+ }
3361
+ };
3362
+ const deeplink = this.options.ui.factory.createConnectionDeeplink(connectionRequest);
3363
+ const universalLink = this.options.ui.factory.createConnectionUniversalLink(connectionRequest);
3364
+ if ((_b = this.options.mobile) == null ? void 0 : _b.preferredOpenLink) {
3365
+ this.options.mobile.preferredOpenLink(deeplink, "_self");
3366
+ } else {
3367
+ openDeeplink(this.options, deeplink, universalLink);
3368
+ }
3369
+ });
3370
+ };
3070
3371
  var MetaMaskConnectMultichain = _MetaMaskConnectMultichain;
3071
3372
 
3072
3373
  // src/store/index.ts
@@ -3251,7 +3552,7 @@ var Store = class extends StoreClient {
3251
3552
  // src/ui/ModalFactory.ts
3252
3553
  import MetaMaskOnboarding from "@metamask/onboarding";
3253
3554
  init_domain();
3254
- init_utils();
3555
+ init_utils2();
3255
3556
  var BaseModalFactory = class {
3256
3557
  /**
3257
3558
  * Creates a new modal factory instance.
@@ -3274,8 +3575,8 @@ var BaseModalFactory = class {
3274
3575
  }
3275
3576
  unload(error) {
3276
3577
  return __async(this, null, function* () {
3277
- var _a2, _b;
3278
- (_a2 = this.modal) == null ? void 0 : _a2.unmount();
3578
+ var _a3, _b;
3579
+ (_a3 = this.modal) == null ? void 0 : _a3.unmount();
3279
3580
  yield (_b = this.successCallback) == null ? void 0 : _b.call(this, error);
3280
3581
  });
3281
3582
  }
@@ -3345,8 +3646,8 @@ var BaseModalFactory = class {
3345
3646
  }
3346
3647
  renderInstallModal(showInstallModal, createConnectionRequest, successCallback, onDisplayUri) {
3347
3648
  return __async(this, null, function* () {
3348
- var _a2, _b;
3349
- (_a2 = this.modal) == null ? void 0 : _a2.unmount();
3649
+ var _a3, _b;
3650
+ (_a3 = this.modal) == null ? void 0 : _a3.unmount();
3350
3651
  yield this.preload();
3351
3652
  this.successCallback = successCallback;
3352
3653
  this.displayUriCallback = onDisplayUri;
@@ -3362,9 +3663,9 @@ var BaseModalFactory = class {
3362
3663
  link: qrCodeLink,
3363
3664
  sdkVersion: getVersion(),
3364
3665
  generateQRCode: (request) => __async(this, null, function* () {
3365
- var _a3;
3666
+ var _a4;
3366
3667
  const newLink = this.createConnectionDeeplink(request);
3367
- (_a3 = this.displayUriCallback) == null ? void 0 : _a3.call(this, newLink);
3668
+ (_a4 = this.displayUriCallback) == null ? void 0 : _a4.call(this, newLink);
3368
3669
  return newLink;
3369
3670
  }),
3370
3671
  onClose: this.onCloseModal.bind(this),
@@ -3378,8 +3679,8 @@ var BaseModalFactory = class {
3378
3679
  }
3379
3680
  renderOTPCodeModal(createOTPCode, successCallback, updateOTPCode) {
3380
3681
  return __async(this, null, function* () {
3381
- var _a2;
3382
- (_a2 = this.modal) == null ? void 0 : _a2.unmount();
3682
+ var _a3;
3683
+ (_a3 = this.modal) == null ? void 0 : _a3.unmount();
3383
3684
  yield this.preload();
3384
3685
  this.successCallback = successCallback;
3385
3686
  const container = this.getMountedContainer();