@metamask/connect-multichain 0.5.2 → 0.6.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 (139) hide show
  1. package/CHANGELOG.md +38 -1
  2. package/README.md +415 -3
  3. package/dist/browser/es/connect-multichain.d.mts +33 -9
  4. package/dist/browser/es/connect-multichain.mjs +864 -510
  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 +33 -9
  8. package/dist/browser/iife/connect-multichain.js +24802 -24331
  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 +33 -9
  12. package/dist/browser/umd/connect-multichain.js +864 -510
  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 +33 -9
  16. package/dist/node/cjs/connect-multichain.js +693 -340
  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 +33 -9
  20. package/dist/node/es/connect-multichain.mjs +694 -339
  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 +33 -9
  24. package/dist/react-native/es/connect-multichain.mjs +857 -503
  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/logger/index.d.ts +1 -1
  28. package/dist/src/domain/logger/index.d.ts.map +1 -1
  29. package/dist/src/domain/logger/index.js.map +1 -1
  30. package/dist/src/domain/multichain/api/constants.js.map +1 -1
  31. package/dist/src/domain/multichain/api/types.d.ts +1 -1
  32. package/dist/src/domain/multichain/api/types.d.ts.map +1 -1
  33. package/dist/src/domain/multichain/index.d.ts +15 -4
  34. package/dist/src/domain/multichain/index.d.ts.map +1 -1
  35. package/dist/src/domain/multichain/index.js +14 -0
  36. package/dist/src/domain/multichain/index.js.map +1 -1
  37. package/dist/src/domain/multichain/types.d.ts +14 -0
  38. package/dist/src/domain/multichain/types.d.ts.map +1 -1
  39. package/dist/src/domain/platform/index.d.ts.map +1 -1
  40. package/dist/src/domain/platform/index.js +1 -0
  41. package/dist/src/domain/platform/index.js.map +1 -1
  42. package/dist/src/index.browser.d.ts.map +1 -1
  43. package/dist/src/index.browser.js +9 -4
  44. package/dist/src/index.browser.js.map +1 -1
  45. package/dist/src/index.native.d.ts.map +1 -1
  46. package/dist/src/index.native.js +9 -4
  47. package/dist/src/index.native.js.map +1 -1
  48. package/dist/src/index.node.d.ts.map +1 -1
  49. package/dist/src/index.node.js +8 -4
  50. package/dist/src/index.node.js.map +1 -1
  51. package/dist/src/multichain/index.d.ts +4 -3
  52. package/dist/src/multichain/index.d.ts.map +1 -1
  53. package/dist/src/multichain/index.js +181 -59
  54. package/dist/src/multichain/index.js.map +1 -1
  55. package/dist/src/multichain/rpc/handlers/rpcClient.d.ts +9 -2
  56. package/dist/src/multichain/rpc/handlers/rpcClient.d.ts.map +1 -1
  57. package/dist/src/multichain/rpc/handlers/rpcClient.js +13 -3
  58. package/dist/src/multichain/rpc/handlers/rpcClient.js.map +1 -1
  59. package/dist/src/multichain/rpc/requestRouter.d.ts +14 -1
  60. package/dist/src/multichain/rpc/requestRouter.d.ts.map +1 -1
  61. package/dist/src/multichain/rpc/requestRouter.js +27 -5
  62. package/dist/src/multichain/rpc/requestRouter.js.map +1 -1
  63. package/dist/src/multichain/transports/default/index.d.ts +5 -3
  64. package/dist/src/multichain/transports/default/index.d.ts.map +1 -1
  65. package/dist/src/multichain/transports/default/index.js +31 -28
  66. package/dist/src/multichain/transports/default/index.js.map +1 -1
  67. package/dist/src/multichain/transports/multichainApiClientWrapper/index.d.ts +3 -3
  68. package/dist/src/multichain/transports/multichainApiClientWrapper/index.d.ts.map +1 -1
  69. package/dist/src/multichain/transports/multichainApiClientWrapper/index.js +33 -29
  70. package/dist/src/multichain/transports/multichainApiClientWrapper/index.js.map +1 -1
  71. package/dist/src/multichain/transports/mwp/KeyManager.d.ts.map +1 -1
  72. package/dist/src/multichain/transports/mwp/KeyManager.js.map +1 -1
  73. package/dist/src/multichain/transports/mwp/index.d.ts +16 -3
  74. package/dist/src/multichain/transports/mwp/index.d.ts.map +1 -1
  75. package/dist/src/multichain/transports/mwp/index.js +157 -39
  76. package/dist/src/multichain/transports/mwp/index.js.map +1 -1
  77. package/dist/src/multichain/utils/analytics.d.ts.map +1 -1
  78. package/dist/src/multichain/utils/analytics.js +1 -0
  79. package/dist/src/multichain/utils/analytics.js.map +1 -1
  80. package/dist/src/multichain/utils/index.d.ts +48 -0
  81. package/dist/src/multichain/utils/index.d.ts.map +1 -1
  82. package/dist/src/multichain/utils/index.js +91 -6
  83. package/dist/src/multichain/utils/index.js.map +1 -1
  84. package/dist/src/polyfills/buffer-shim.js +5 -11
  85. package/dist/src/polyfills/buffer-shim.js.map +1 -1
  86. package/dist/src/store/adapters/node.d.ts +1 -1
  87. package/dist/src/store/adapters/node.d.ts.map +1 -1
  88. package/dist/src/store/adapters/node.js +11 -4
  89. package/dist/src/store/adapters/node.js.map +1 -1
  90. package/dist/src/store/adapters/rn.d.ts.map +1 -1
  91. package/dist/src/store/adapters/rn.js +1 -0
  92. package/dist/src/store/adapters/rn.js.map +1 -1
  93. package/dist/src/store/adapters/web.d.ts +5 -5
  94. package/dist/src/store/adapters/web.d.ts.map +1 -1
  95. package/dist/src/store/adapters/web.js +7 -1
  96. package/dist/src/store/adapters/web.js.map +1 -1
  97. package/dist/src/store/index.d.ts.map +1 -1
  98. package/dist/src/store/index.js +2 -0
  99. package/dist/src/store/index.js.map +1 -1
  100. package/dist/src/ui/ModalFactory.d.ts.map +1 -1
  101. package/dist/src/ui/ModalFactory.js +1 -4
  102. package/dist/src/ui/ModalFactory.js.map +1 -1
  103. package/dist/src/ui/index.d.ts.map +1 -1
  104. package/dist/src/ui/index.js +2 -0
  105. package/dist/src/ui/index.js.map +1 -1
  106. package/dist/src/ui/index.native.d.ts.map +1 -1
  107. package/dist/src/ui/index.native.js +4 -1
  108. package/dist/src/ui/index.native.js.map +1 -1
  109. package/dist/src/ui/modals/base/AbstractInstallModal.d.ts +2 -3
  110. package/dist/src/ui/modals/base/AbstractInstallModal.d.ts.map +1 -1
  111. package/dist/src/ui/modals/base/AbstractInstallModal.js +28 -12
  112. package/dist/src/ui/modals/base/AbstractInstallModal.js.map +1 -1
  113. package/dist/src/ui/modals/base/AbstractOTPModal.d.ts +2 -2
  114. package/dist/src/ui/modals/base/AbstractOTPModal.d.ts.map +1 -1
  115. package/dist/src/ui/modals/base/AbstractOTPModal.js.map +1 -1
  116. package/dist/src/ui/modals/base/utils.d.ts +12 -0
  117. package/dist/src/ui/modals/base/utils.d.ts.map +1 -1
  118. package/dist/src/ui/modals/base/utils.js +16 -5
  119. package/dist/src/ui/modals/base/utils.js.map +1 -1
  120. package/dist/src/ui/modals/node/install.d.ts.map +1 -1
  121. package/dist/src/ui/modals/node/install.js +1 -1
  122. package/dist/src/ui/modals/node/install.js.map +1 -1
  123. package/dist/src/ui/modals/node/otp.d.ts.map +1 -1
  124. package/dist/src/ui/modals/node/otp.js +6 -2
  125. package/dist/src/ui/modals/node/otp.js.map +1 -1
  126. package/dist/src/ui/modals/rn/install.d.ts.map +1 -1
  127. package/dist/src/ui/modals/rn/install.js +7 -3
  128. package/dist/src/ui/modals/rn/install.js.map +1 -1
  129. package/dist/src/ui/modals/rn/otp.d.ts.map +1 -1
  130. package/dist/src/ui/modals/rn/otp.js +6 -2
  131. package/dist/src/ui/modals/rn/otp.js.map +1 -1
  132. package/dist/src/ui/modals/web/install.d.ts.map +1 -1
  133. package/dist/src/ui/modals/web/install.js +1 -1
  134. package/dist/src/ui/modals/web/install.js.map +1 -1
  135. package/dist/src/ui/modals/web/otp.d.ts.map +1 -1
  136. package/dist/src/ui/modals/web/otp.js +6 -2
  137. package/dist/src/ui/modals/web/otp.js.map +1 -1
  138. package/dist/types/connect-multichain.d.ts +33 -9
  139. package/package.json +3 -3
@@ -256,8 +256,8 @@ var init_logger = __esm({
256
256
  import_debug.default.enable(namespace);
257
257
  };
258
258
  isEnabled = (namespace, storage) => __async(null, null, function* () {
259
- var _a2;
260
- 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)) {
261
261
  const { DEBUG } = process.env;
262
262
  return isNamespaceEnabled(DEBUG, namespace);
263
263
  }
@@ -420,41 +420,69 @@ var init_multichain = __esm({
420
420
  super();
421
421
  this.options = options;
422
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
+ }
423
451
  };
424
452
  }
425
453
  });
426
454
 
427
455
  // src/domain/platform/index.ts
428
456
  function isNotBrowser() {
429
- var _a2;
457
+ var _a3;
430
458
  if (typeof window === "undefined") {
431
459
  return true;
432
460
  }
433
461
  if (!(window == null ? void 0 : window.navigator)) {
434
462
  return true;
435
463
  }
436
- 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") {
437
465
  return true;
438
466
  }
439
467
  return (navigator == null ? void 0 : navigator.product) === "ReactNative";
440
468
  }
441
469
  function isReactNative() {
442
- var _a2;
470
+ var _a3;
443
471
  const hasWindowNavigator = typeof window !== "undefined" && window.navigator !== void 0;
444
472
  const nav = hasWindowNavigator ? window.navigator : void 0;
445
473
  if (!nav) {
446
474
  return false;
447
475
  }
448
- return hasWindowNavigator && ((_a2 = window.navigator) == null ? void 0 : _a2.product) === "ReactNative";
476
+ return hasWindowNavigator && ((_a3 = window.navigator) == null ? void 0 : _a3.product) === "ReactNative";
449
477
  }
450
478
  function isMetaMaskMobileWebView() {
451
479
  return typeof window !== "undefined" && // @ts-expect-error ReactNativeWebView should be defined
452
480
  Boolean(window.ReactNativeWebView) && Boolean(window.navigator.userAgent.endsWith("MetaMaskMobile"));
453
481
  }
454
482
  function isMobile() {
455
- var _a2, _b;
483
+ var _a3, _b;
456
484
  const browser = import_bowser.default.parse(window.navigator.userAgent);
457
- return ((_a2 = browser == null ? void 0 : browser.platform) == null ? void 0 : _a2.type) === "mobile" || ((_b = browser == null ? void 0 : browser.platform) == null ? void 0 : _b.type) === "tablet";
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";
458
486
  }
459
487
  function getPlatformType() {
460
488
  if (isReactNative()) {
@@ -472,11 +500,11 @@ function getPlatformType() {
472
500
  return "web-desktop" /* DesktopWeb */;
473
501
  }
474
502
  function isMetamaskExtensionInstalled() {
475
- var _a2;
503
+ var _a3;
476
504
  if (typeof window === "undefined") {
477
505
  return false;
478
506
  }
479
- return Boolean((_a2 = window.ethereum) == null ? void 0 : _a2.isMetaMask);
507
+ return Boolean((_a3 = window.ethereum) == null ? void 0 : _a3.isMetaMask);
480
508
  }
481
509
  function isSecure() {
482
510
  const platformType = getPlatformType();
@@ -508,8 +536,8 @@ var init_platform = __esm({
508
536
  return new Promise((resolve) => {
509
537
  const providers = [];
510
538
  const handler = (event) => {
511
- var _a2, _b;
512
- 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) {
513
541
  providers.push(event.detail);
514
542
  }
515
543
  };
@@ -519,8 +547,8 @@ var init_platform = __esm({
519
547
  window.removeEventListener("eip6963:announceProvider", handler);
520
548
  const hasMetaMask = providers.some(
521
549
  (provider) => {
522
- var _a2, _b;
523
- return (_b = (_a2 = provider == null ? void 0 : provider.info) == null ? void 0 : _a2.rdns) == null ? void 0 : _b.startsWith("io.metamask");
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");
524
552
  }
525
553
  );
526
554
  resolve(hasMetaMask);
@@ -604,7 +632,103 @@ var init_ui = __esm({
604
632
  }
605
633
  });
606
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
+
607
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
+ }
608
732
  function base64Encode(str) {
609
733
  if (typeof btoa !== "undefined") {
610
734
  return btoa(str);
@@ -619,12 +743,13 @@ function compressString(str) {
619
743
  return base64Encode(binaryString);
620
744
  }
621
745
  function getDappId(dapp) {
622
- var _a2;
623
- return (_a2 = dapp.url) != null ? _a2 : dapp.name;
746
+ var _a3;
747
+ return (_a3 = dapp.url) != null ? _a3 : dapp.name;
624
748
  }
625
749
  function openDeeplink(options, deeplink, universalLink) {
750
+ var _a3;
626
751
  const { mobile } = options;
627
- const useDeeplink = mobile && mobile.useDeeplink !== void 0 ? mobile.useDeeplink : true;
752
+ const useDeeplink = (_a3 = mobile == null ? void 0 : mobile.useDeeplink) != null ? _a3 : true;
628
753
  if (useDeeplink) {
629
754
  if (typeof window !== "undefined") {
630
755
  window.location.href = deeplink;
@@ -637,6 +762,29 @@ function openDeeplink(options, deeplink, universalLink) {
637
762
  link.click();
638
763
  }
639
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
+ }
640
788
  function getOptionalScopes(scopes) {
641
789
  return scopes.reduce(
642
790
  (prev, scope) => __spreadProps(__spreadValues({}, prev), {
@@ -650,10 +798,10 @@ function getOptionalScopes(scopes) {
650
798
  );
651
799
  }
652
800
  function setupDappMetadata(options) {
653
- var _a2, _b;
801
+ var _a3, _b;
654
802
  const platform = getPlatformType();
655
803
  const isBrowser = platform === "web-desktop" /* DesktopWeb */ || platform === "web-mobile" /* MobileWeb */ || platform === "in-app-browser" /* MetaMaskMobileWebview */;
656
- if (!((_a2 = options.dapp) == null ? void 0 : _a2.name)) {
804
+ if (!((_a3 = options.dapp) == null ? void 0 : _a3.name)) {
657
805
  throw new Error("You must provide dapp name");
658
806
  }
659
807
  if (isBrowser) {
@@ -665,7 +813,7 @@ function setupDappMetadata(options) {
665
813
  throw new Error("You must provide dapp url");
666
814
  }
667
815
  const BASE_64_ICON_MAX_LENGTH = 163400;
668
- const urlPattern = /^(http|https):\/\/[^\s]*$/;
816
+ const urlPattern = /^(http|https):\/\/[^\s]*$/u;
669
817
  if (options.dapp) {
670
818
  if ("iconUrl" in options.dapp) {
671
819
  if (options.dapp.iconUrl && !urlPattern.test(options.dapp.iconUrl)) {
@@ -714,9 +862,12 @@ function getValidAccounts(caipAccountIds) {
714
862
  (caipAccounts, caipAccountId) => {
715
863
  try {
716
864
  return [...caipAccounts, (0, import_utils.parseCaipAccountId)(caipAccountId)];
717
- } catch (err) {
865
+ } catch (error) {
718
866
  const stringifiedAccountId = JSON.stringify(caipAccountId);
719
- console.error(`Invalid CAIP account ID: ${stringifiedAccountId}`, err);
867
+ console.error(
868
+ `Invalid CAIP account ID: ${stringifiedAccountId}`,
869
+ error
870
+ );
720
871
  return caipAccounts;
721
872
  }
722
873
  },
@@ -724,17 +875,17 @@ function getValidAccounts(caipAccountIds) {
724
875
  );
725
876
  }
726
877
  function addValidAccounts(optionalScopes, validAccounts) {
727
- var _a2;
878
+ var _a3;
728
879
  if (!optionalScopes || !(validAccounts == null ? void 0 : validAccounts.length)) {
729
880
  return optionalScopes;
730
881
  }
731
882
  const result = Object.fromEntries(
732
883
  Object.entries(optionalScopes).map(([scope, scopeData]) => {
733
- var _a3, _b, _c;
884
+ var _a4, _b, _c;
734
885
  return [
735
886
  scope,
736
887
  {
737
- methods: [...(_a3 = scopeData == null ? void 0 : scopeData.methods) != null ? _a3 : []],
888
+ methods: [...(_a4 = scopeData == null ? void 0 : scopeData.methods) != null ? _a4 : []],
738
889
  notifications: [...(_b = scopeData == null ? void 0 : scopeData.notifications) != null ? _b : []],
739
890
  accounts: [...(_c = scopeData == null ? void 0 : scopeData.accounts) != null ? _c : []]
740
891
  }
@@ -748,7 +899,7 @@ function addValidAccounts(optionalScopes, validAccounts) {
748
899
  if (!accountsByChain.has(chainKey)) {
749
900
  accountsByChain.set(chainKey, []);
750
901
  }
751
- (_a2 = accountsByChain.get(chainKey)) == null ? void 0 : _a2.push(accountId);
902
+ (_a3 = accountsByChain.get(chainKey)) == null ? void 0 : _a3.push(accountId);
752
903
  }
753
904
  for (const [scopeKey, scopeData] of Object.entries(result)) {
754
905
  if (!(scopeData == null ? void 0 : scopeData.accounts)) {
@@ -772,15 +923,15 @@ function addValidAccounts(optionalScopes, validAccounts) {
772
923
  }
773
924
  return result;
774
925
  }
775
- var import_pako, import_utils, extractFavicon;
776
- var init_utils = __esm({
926
+ var import_utils, import_pako, extractFavicon, MAX, idCounter, getUniqueRequestId;
927
+ var init_utils2 = __esm({
777
928
  "src/multichain/utils/index.ts"() {
778
929
  "use strict";
779
- import_pako = require("pako");
780
930
  import_utils = require("@metamask/utils");
931
+ import_pako = require("pako");
781
932
  init_domain();
782
933
  extractFavicon = () => {
783
- var _a2;
934
+ var _a3;
784
935
  if (typeof document === "undefined") {
785
936
  return void 0;
786
937
  }
@@ -788,98 +939,25 @@ var init_utils = __esm({
788
939
  const nodeList = document.getElementsByTagName("link");
789
940
  for (let i = 0; i < nodeList.length; i++) {
790
941
  if (nodeList[i].getAttribute("rel") === "icon" || nodeList[i].getAttribute("rel") === "shortcut icon") {
791
- favicon = (_a2 = nodeList[i].getAttribute("href")) != null ? _a2 : void 0;
942
+ favicon = (_a3 = nodeList[i].getAttribute("href")) != null ? _a3 : void 0;
792
943
  }
793
944
  }
794
945
  return favicon;
795
946
  };
796
- }
797
- });
798
-
799
- // src/multichain/utils/analytics.ts
800
- function isRejectionError(error) {
801
- var _a2, _b;
802
- if (typeof error !== "object" || error === null) {
803
- return false;
804
- }
805
- const errorObj = error;
806
- const errorCode = errorObj.code;
807
- const errorMessage = (_b = (_a2 = errorObj.message) == null ? void 0 : _a2.toLowerCase()) != null ? _b : "";
808
- return errorCode === 4001 || // User rejected request (common EIP-1193 code)
809
- errorCode === 4100 || // Unauthorized (common rejection code)
810
- errorMessage.includes("reject") || errorMessage.includes("denied") || errorMessage.includes("cancel") || errorMessage.includes("user");
811
- }
812
- function getBaseAnalyticsProperties(options, storage) {
813
- return __async(this, null, function* () {
814
- var _a2, _b;
815
- const version = getVersion();
816
- const dappId = getDappId(options.dapp);
817
- const platform = getPlatformType();
818
- const anonId = yield storage.getAnonId();
819
- const integrationType = (_b = (_a2 = options.analytics) == null ? void 0 : _a2.integrationType) != null ? _b : "unknown" /* UNKNOWN */;
820
- return {
821
- mmconnect_version: version,
822
- dapp_id: dappId,
823
- platform,
824
- integration_type: integrationType,
825
- anon_id: anonId
826
- };
827
- });
828
- }
829
- function getWalletActionAnalyticsProperties(options, storage, invokeOptions) {
830
- return __async(this, null, function* () {
831
- var _a2, _b;
832
- const version = getVersion();
833
- const dappId = getDappId(options.dapp);
834
- const anonId = yield storage.getAnonId();
835
- const integrationType = (_b = (_a2 = options.analytics) == null ? void 0 : _a2.integrationType) != null ? _b : "unknown";
836
- return {
837
- mmconnect_version: version,
838
- dapp_id: dappId,
839
- method: invokeOptions.request.method,
840
- integration_type: integrationType,
841
- caip_chain_id: invokeOptions.scope,
842
- anon_id: anonId
947
+ MAX = 4294967295;
948
+ idCounter = Math.floor(Math.random() * MAX);
949
+ getUniqueRequestId = () => {
950
+ idCounter = (idCounter + 1) % MAX;
951
+ return idCounter;
843
952
  };
844
- });
845
- }
846
- var init_analytics = __esm({
847
- "src/multichain/utils/analytics.ts"() {
848
- "use strict";
849
- init_utils();
850
- init_domain();
851
- }
852
- });
853
-
854
- // src/domain/utils/index.ts
855
- function getVersion() {
856
- return "0.0.0";
857
- }
858
- var init_utils2 = __esm({
859
- "src/domain/utils/index.ts"() {
860
- "use strict";
861
- init_analytics();
862
- }
863
- });
864
-
865
- // src/domain/index.ts
866
- var init_domain = __esm({
867
- "src/domain/index.ts"() {
868
- "use strict";
869
- init_errors();
870
- init_events();
871
- init_logger();
872
- init_multichain();
873
- init_platform();
874
- init_store();
875
- init_ui();
876
- init_utils2();
877
953
  }
878
954
  });
879
955
 
880
956
  // src/ui/modals/base/utils.ts
881
957
  function formatRemainingTime(milliseconds) {
882
- if (milliseconds <= 0) return "EXPIRED";
958
+ if (milliseconds <= 0) {
959
+ return "EXPIRED";
960
+ }
883
961
  const seconds = Math.floor(milliseconds / 1e3);
884
962
  return `${seconds}s`;
885
963
  }
@@ -892,9 +970,8 @@ function shouldLogCountdown(remainingSeconds) {
892
970
  return remainingSeconds % 10 === 0;
893
971
  } else if (remainingSeconds <= 300) {
894
972
  return remainingSeconds % 30 === 0;
895
- } else {
896
- return remainingSeconds % 60 === 0;
897
973
  }
974
+ return remainingSeconds % 60 === 0;
898
975
  }
899
976
  var init_utils3 = __esm({
900
977
  "src/ui/modals/base/utils.ts"() {
@@ -903,18 +980,18 @@ var init_utils3 = __esm({
903
980
  });
904
981
 
905
982
  // src/ui/modals/base/AbstractInstallModal.ts
906
- var logger3, AbstractInstallModal;
983
+ var logger3, _expirationInterval, _lastLoggedCountdown, AbstractInstallModal;
907
984
  var init_AbstractInstallModal = __esm({
908
985
  "src/ui/modals/base/AbstractInstallModal.ts"() {
909
986
  "use strict";
910
- init_domain();
911
987
  init_utils3();
988
+ init_domain();
912
989
  logger3 = createLogger("metamask-sdk:ui");
913
990
  AbstractInstallModal = class extends Modal {
914
991
  constructor() {
915
992
  super(...arguments);
916
- this.expirationInterval = null;
917
- this.lastLoggedCountdown = -1;
993
+ __privateAdd(this, _expirationInterval, null);
994
+ __privateAdd(this, _lastLoggedCountdown, -1);
918
995
  }
919
996
  get link() {
920
997
  return this.data;
@@ -942,17 +1019,17 @@ var init_AbstractInstallModal = __esm({
942
1019
  startExpirationCheck(connectionRequest) {
943
1020
  this.stopExpirationCheck();
944
1021
  let currentConnectionRequest = connectionRequest;
945
- this.expirationInterval = setInterval(() => __async(this, null, function* () {
1022
+ __privateSet(this, _expirationInterval, setInterval(() => __async(this, null, function* () {
946
1023
  const { sessionRequest } = currentConnectionRequest;
947
1024
  const now = Date.now();
948
1025
  const remainingMs = sessionRequest.expiresAt - now;
949
1026
  const remainingSeconds = Math.floor(remainingMs / 1e3);
950
- if (remainingMs > 0 && shouldLogCountdown(remainingSeconds) && this.lastLoggedCountdown !== remainingSeconds) {
1027
+ if (remainingMs > 0 && shouldLogCountdown(remainingSeconds) && __privateGet(this, _lastLoggedCountdown) !== remainingSeconds) {
951
1028
  const formattedTime = formatRemainingTime(remainingMs);
952
1029
  logger3(
953
1030
  `[UI: InstallModal-nodejs()] QR code expires in: ${formattedTime} (${remainingSeconds}s)`
954
1031
  );
955
- this.lastLoggedCountdown = remainingSeconds;
1032
+ __privateSet(this, _lastLoggedCountdown, remainingSeconds);
956
1033
  }
957
1034
  if (now >= sessionRequest.expiresAt) {
958
1035
  this.stopExpirationCheck();
@@ -964,7 +1041,7 @@ var init_AbstractInstallModal = __esm({
964
1041
  const generateQRCode = yield this.options.generateQRCode(
965
1042
  currentConnectionRequest
966
1043
  );
967
- this.lastLoggedCountdown = -1;
1044
+ __privateSet(this, _lastLoggedCountdown, -1);
968
1045
  this.updateLink(generateQRCode);
969
1046
  this.updateExpiresIn(remainingSeconds);
970
1047
  this.renderQRCode(generateQRCode, currentConnectionRequest);
@@ -974,18 +1051,20 @@ var init_AbstractInstallModal = __esm({
974
1051
  );
975
1052
  }
976
1053
  }
977
- }), 1e3);
1054
+ }), 1e3));
978
1055
  }
979
1056
  stopExpirationCheck() {
980
- if (this.expirationInterval) {
981
- clearInterval(this.expirationInterval);
982
- this.expirationInterval = null;
1057
+ if (__privateGet(this, _expirationInterval)) {
1058
+ clearInterval(__privateGet(this, _expirationInterval));
1059
+ __privateSet(this, _expirationInterval, null);
983
1060
  logger3(
984
1061
  "[UI: InstallModal-nodejs()] \u{1F6D1} Stopped QR code expiration checking"
985
1062
  );
986
1063
  }
987
1064
  }
988
1065
  };
1066
+ _expirationInterval = new WeakMap();
1067
+ _lastLoggedCountdown = new WeakMap();
989
1068
  }
990
1069
  });
991
1070
 
@@ -999,7 +1078,7 @@ var init_install = __esm({
999
1078
  renderQRCode() {
1000
1079
  }
1001
1080
  mount() {
1002
- var _a2;
1081
+ var _a3;
1003
1082
  const { options } = this;
1004
1083
  const modal = document.createElement(
1005
1084
  "mm-install-modal"
@@ -1016,14 +1095,14 @@ var init_install = __esm({
1016
1095
  );
1017
1096
  modal.link = options.link;
1018
1097
  this.instance = modal;
1019
- (_a2 = options.parentElement) == null ? void 0 : _a2.appendChild(modal);
1098
+ (_a3 = options.parentElement) == null ? void 0 : _a3.appendChild(modal);
1020
1099
  this.startExpirationCheck(options.connectionRequest);
1021
1100
  }
1022
1101
  unmount() {
1023
- var _a2;
1102
+ var _a3;
1024
1103
  const { options, instance: modal } = this;
1025
1104
  this.stopExpirationCheck();
1026
- if (modal && ((_a2 = options.parentElement) == null ? void 0 : _a2.contains(modal))) {
1105
+ if (modal && ((_a3 = options.parentElement) == null ? void 0 : _a3.contains(modal))) {
1027
1106
  options.parentElement.removeChild(modal);
1028
1107
  this.instance = void 0;
1029
1108
  }
@@ -1135,8 +1214,8 @@ var init_web2 = __esm({
1135
1214
  const request = store.get(key);
1136
1215
  request.onerror = () => reject(new Error("Failed to get value from IndexedDB."));
1137
1216
  request.onsuccess = () => {
1138
- var _a2;
1139
- return resolve((_a2 = request.result) != null ? _a2 : null);
1217
+ var _a3;
1218
+ return resolve((_a3 = request.result) != null ? _a3 : null);
1140
1219
  };
1141
1220
  } catch (error) {
1142
1221
  reject(error);
@@ -1180,7 +1259,7 @@ var init_web2 = __esm({
1180
1259
  }
1181
1260
  };
1182
1261
  _StoreAdapterWeb.stores = ["sdk-kv-store", "key-value-pairs"];
1183
- _StoreAdapterWeb.DB_NAME = "mmsdk";
1262
+ _StoreAdapterWeb.DB_NAME = "mmconnect";
1184
1263
  StoreAdapterWeb = _StoreAdapterWeb;
1185
1264
  }
1186
1265
  });
@@ -1220,10 +1299,13 @@ module.exports = __toCommonJS(index_browser_exports);
1220
1299
 
1221
1300
  // src/polyfills/buffer-shim.ts
1222
1301
  var import_buffer = require("buffer");
1223
- var g = typeof globalThis !== "undefined" ? globalThis : typeof global !== "undefined" ? global : typeof window !== "undefined" ? window : {};
1224
- if (!g.Buffer) {
1225
- g.Buffer = import_buffer.Buffer;
1226
- }
1302
+ init_utils2();
1303
+ var globalObj = getGlobalObject();
1304
+ var _a;
1305
+ (_a = globalObj.Buffer) != null ? _a : globalObj.Buffer = import_buffer.Buffer;
1306
+
1307
+ // src/index.browser.ts
1308
+ init_domain();
1227
1309
 
1228
1310
  // src/multichain/index.ts
1229
1311
  var import_analytics4 = require("@metamask/analytics");
@@ -1260,7 +1342,9 @@ var RpcClient = class {
1260
1342
  }
1261
1343
  /**
1262
1344
  * Routes the request to a configured RPC node.
1263
- * @param options - The invoke method options
1345
+ *
1346
+ * @param options - The invoke method options.
1347
+ * @returns The JSON response from the RPC node.
1264
1348
  */
1265
1349
  request(options) {
1266
1350
  return __async(this, null, function* () {
@@ -1272,17 +1356,25 @@ var RpcClient = class {
1272
1356
  id: getNextRpcId()
1273
1357
  });
1274
1358
  const rpcEndpoint = this.getRpcEndpoint(options.scope);
1275
- const rpcRequest = yield this.fetchWithTimeout(rpcEndpoint, body, "POST", this.getHeaders(rpcEndpoint), 3e4);
1359
+ const rpcRequest = yield this.fetchWithTimeout(
1360
+ rpcEndpoint,
1361
+ body,
1362
+ "POST",
1363
+ this.getHeaders(rpcEndpoint),
1364
+ 3e4
1365
+ );
1276
1366
  const response = yield this.parseResponse(rpcRequest);
1277
1367
  return response;
1278
1368
  });
1279
1369
  }
1280
1370
  getRpcEndpoint(scope) {
1281
- var _a2, _b, _c;
1282
- const supportedNetworks = (_c = (_b = (_a2 = this.config) == null ? void 0 : _a2.api) == null ? void 0 : _b.supportedNetworks) != null ? _c : {};
1371
+ var _a3, _b, _c;
1372
+ const supportedNetworks = (_c = (_b = (_a3 = this.config) == null ? void 0 : _a3.api) == null ? void 0 : _b.supportedNetworks) != null ? _c : {};
1283
1373
  const rpcEndpoint = supportedNetworks[scope];
1284
1374
  if (!rpcEndpoint) {
1285
- throw new MissingRpcEndpointErr(`No RPC endpoint found for scope ${scope}`);
1375
+ throw new MissingRpcEndpointErr(
1376
+ `No RPC endpoint found for scope ${scope}`
1377
+ );
1286
1378
  }
1287
1379
  return rpcEndpoint;
1288
1380
  }
@@ -1310,7 +1402,7 @@ var RpcClient = class {
1310
1402
  if (error instanceof Error && error.name === "AbortError") {
1311
1403
  throw new RPCReadonlyRequestErr(`Request timeout after ${timeout}ms`);
1312
1404
  }
1313
- throw new RPCReadonlyRequestErr(error instanceof Error ? error.message : "Unknown error");
1405
+ throw new RPCReadonlyRequestErr(error.message);
1314
1406
  }
1315
1407
  });
1316
1408
  }
@@ -1341,7 +1433,7 @@ var RpcClient = class {
1341
1433
  // src/multichain/rpc/requestRouter.ts
1342
1434
  var import_analytics2 = require("@metamask/analytics");
1343
1435
  init_domain();
1344
- init_utils();
1436
+ init_utils2();
1345
1437
  init_analytics();
1346
1438
  var _RequestRouter_instances, withAnalyticsTracking_fn, trackWalletActionRequested_fn, trackWalletActionSucceeded_fn, trackWalletActionFailed_fn, trackWalletActionRejected_fn;
1347
1439
  var RequestRouter = class {
@@ -1355,10 +1447,12 @@ var RequestRouter = class {
1355
1447
  * The main entry point for invoking an RPC method.
1356
1448
  * This method acts as a router, determining the correct handling strategy
1357
1449
  * for the request and delegating to the appropriate private handler.
1450
+ *
1451
+ * @param options
1358
1452
  */
1359
1453
  invokeMethod(options) {
1360
1454
  return __async(this, null, function* () {
1361
- const method = options.request.method;
1455
+ const { method } = options.request;
1362
1456
  if (RPC_HANDLED_METHODS.has(method)) {
1363
1457
  return this.handleWithRpcNode(options);
1364
1458
  }
@@ -1370,6 +1464,8 @@ var RequestRouter = class {
1370
1464
  }
1371
1465
  /**
1372
1466
  * Forwards the request directly to the wallet via the transport.
1467
+ *
1468
+ * @param options
1373
1469
  */
1374
1470
  handleWithWallet(options) {
1375
1471
  return __async(this, null, function* () {
@@ -1398,7 +1494,10 @@ var RequestRouter = class {
1398
1494
  }
1399
1495
  const response = yield request;
1400
1496
  if (response.error) {
1401
- throw new RPCInvokeMethodErr(`RPC Request failed with code ${response.error.code}: ${response.error.message}`);
1497
+ const { error } = response;
1498
+ throw new RPCInvokeMethodErr(
1499
+ `RPC Request failed with code ${error.code}: ${error.message}`
1500
+ );
1402
1501
  }
1403
1502
  return response.result;
1404
1503
  }));
@@ -1406,6 +1505,8 @@ var RequestRouter = class {
1406
1505
  }
1407
1506
  /**
1408
1507
  * Routes the request to a configured RPC node.
1508
+ *
1509
+ * @param options
1409
1510
  */
1410
1511
  handleWithRpcNode(options) {
1411
1512
  return __async(this, null, function* () {
@@ -1423,10 +1524,14 @@ var RequestRouter = class {
1423
1524
  }
1424
1525
  /**
1425
1526
  * Responds directly from the SDK's session state.
1527
+ *
1528
+ * @param options
1426
1529
  */
1427
1530
  handleWithSdkState(options) {
1428
1531
  return __async(this, null, function* () {
1429
- console.warn(`Method "${options.request.method}" is configured for SDK state handling, but this is not yet implemented. Falling back to wallet passthrough.`);
1532
+ console.warn(
1533
+ `Method "${options.request.method}" is configured for SDK state handling, but this is not yet implemented. Falling back to wallet passthrough.`
1534
+ );
1430
1535
  return this.handleWithWallet(options);
1431
1536
  });
1432
1537
  }
@@ -1446,40 +1551,59 @@ withAnalyticsTracking_fn = function(options, execute) {
1446
1551
  } else {
1447
1552
  yield __privateMethod(this, _RequestRouter_instances, trackWalletActionFailed_fn).call(this, options);
1448
1553
  }
1554
+ if (error instanceof RPCInvokeMethodErr) {
1555
+ throw error;
1556
+ }
1449
1557
  throw new RPCInvokeMethodErr(error.message);
1450
1558
  }
1451
1559
  });
1452
1560
  };
1453
1561
  trackWalletActionRequested_fn = function(options) {
1454
1562
  return __async(this, null, function* () {
1455
- const props = yield getWalletActionAnalyticsProperties(this.config, this.config.storage, options);
1563
+ const props = yield getWalletActionAnalyticsProperties(
1564
+ this.config,
1565
+ this.config.storage,
1566
+ options
1567
+ );
1456
1568
  import_analytics2.analytics.track("mmconnect_wallet_action_requested", props);
1457
1569
  });
1458
1570
  };
1459
1571
  trackWalletActionSucceeded_fn = function(options) {
1460
1572
  return __async(this, null, function* () {
1461
- const props = yield getWalletActionAnalyticsProperties(this.config, this.config.storage, options);
1573
+ const props = yield getWalletActionAnalyticsProperties(
1574
+ this.config,
1575
+ this.config.storage,
1576
+ options
1577
+ );
1462
1578
  import_analytics2.analytics.track("mmconnect_wallet_action_succeeded", props);
1463
1579
  });
1464
1580
  };
1465
1581
  trackWalletActionFailed_fn = function(options) {
1466
1582
  return __async(this, null, function* () {
1467
- const props = yield getWalletActionAnalyticsProperties(this.config, this.config.storage, options);
1583
+ const props = yield getWalletActionAnalyticsProperties(
1584
+ this.config,
1585
+ this.config.storage,
1586
+ options
1587
+ );
1468
1588
  import_analytics2.analytics.track("mmconnect_wallet_action_failed", props);
1469
1589
  });
1470
1590
  };
1471
1591
  trackWalletActionRejected_fn = function(options) {
1472
1592
  return __async(this, null, function* () {
1473
- const props = yield getWalletActionAnalyticsProperties(this.config, this.config.storage, options);
1593
+ const props = yield getWalletActionAnalyticsProperties(
1594
+ this.config,
1595
+ this.config.storage,
1596
+ options
1597
+ );
1474
1598
  import_analytics2.analytics.track("mmconnect_wallet_action_rejected", props);
1475
1599
  });
1476
1600
  };
1477
1601
 
1478
1602
  // src/multichain/transports/default/index.ts
1479
1603
  var import_multichain_api_client = require("@metamask/multichain-api-client");
1480
- init_utils();
1604
+ init_utils2();
1481
1605
  var DEFAULT_REQUEST_TIMEOUT = 60 * 1e3;
1482
- var _notificationCallbacks, _transport, _defaultRequestOptions, _reqId, _pendingRequests, _handleResponseListener, _handleNotificationListener, _DefaultTransport_instances, notifyCallbacks_fn, isMetamaskProviderEvent_fn, handleResponse_fn, handleNotification_fn, setupMessageListener_fn;
1606
+ var _notificationCallbacks, _transport, _defaultRequestOptions, _pendingRequests, _handleResponseListener, _handleNotificationListener, _DefaultTransport_instances, notifyCallbacks_fn, isMetamaskProviderEvent_fn, handleResponse_fn, handleNotification_fn, setupMessageListener_fn;
1483
1607
  var DefaultTransport = class {
1484
1608
  constructor() {
1485
1609
  __privateAdd(this, _DefaultTransport_instances);
@@ -1488,8 +1612,6 @@ var DefaultTransport = class {
1488
1612
  __privateAdd(this, _defaultRequestOptions, {
1489
1613
  timeout: DEFAULT_REQUEST_TIMEOUT
1490
1614
  });
1491
- // Use timestamp-based ID to avoid conflicts across disconnect/reconnect cycles
1492
- __privateAdd(this, _reqId, Date.now());
1493
1615
  __privateAdd(this, _pendingRequests, /* @__PURE__ */ new Map());
1494
1616
  __privateAdd(this, _handleResponseListener);
1495
1617
  __privateAdd(this, _handleNotificationListener);
@@ -1497,18 +1619,17 @@ var DefaultTransport = class {
1497
1619
  sendEip1193Message(payload, options) {
1498
1620
  return __async(this, null, function* () {
1499
1621
  __privateMethod(this, _DefaultTransport_instances, setupMessageListener_fn).call(this);
1500
- __privateSet(this, _reqId, __privateGet(this, _reqId) + 1);
1501
- const requestId = `${__privateGet(this, _reqId)}`;
1622
+ const requestId = String(getUniqueRequestId());
1502
1623
  const request = __spreadValues({
1503
1624
  jsonrpc: "2.0",
1504
1625
  id: requestId
1505
1626
  }, payload);
1506
1627
  return new Promise((resolve, reject) => {
1507
- var _a2;
1628
+ var _a3;
1508
1629
  const timeout = setTimeout(() => {
1509
1630
  __privateGet(this, _pendingRequests).delete(requestId);
1510
1631
  reject(new Error("Request timeout"));
1511
- }, (_a2 = options == null ? void 0 : options.timeout) != null ? _a2 : __privateGet(this, _defaultRequestOptions).timeout);
1632
+ }, (_a3 = options == null ? void 0 : options.timeout) != null ? _a3 : __privateGet(this, _defaultRequestOptions).timeout);
1512
1633
  __privateGet(this, _pendingRequests).set(requestId, {
1513
1634
  resolve: (response) => {
1514
1635
  resolve(response);
@@ -1532,7 +1653,7 @@ var DefaultTransport = class {
1532
1653
  }
1533
1654
  connect(options) {
1534
1655
  return __async(this, null, function* () {
1535
- var _a2, _b, _c, _d, _e, _f, _g;
1656
+ var _a3, _b, _c, _d, _e;
1536
1657
  __privateMethod(this, _DefaultTransport_instances, setupMessageListener_fn).call(this);
1537
1658
  yield __privateGet(this, _transport).connect();
1538
1659
  const sessionRequest = yield this.request(
@@ -1543,12 +1664,19 @@ var DefaultTransport = class {
1543
1664
  throw new Error(sessionRequest.error.message);
1544
1665
  }
1545
1666
  let walletSession = sessionRequest.result;
1667
+ const createSessionParams = {
1668
+ optionalScopes: addValidAccounts(
1669
+ getOptionalScopes((_a3 = options == null ? void 0 : options.scopes) != null ? _a3 : []),
1670
+ getValidAccounts((_b = options == null ? void 0 : options.caipAccountIds) != null ? _b : [])
1671
+ ),
1672
+ sessionProperties: options == null ? void 0 : options.sessionProperties
1673
+ };
1546
1674
  if (walletSession && options && !options.forceRequest) {
1547
1675
  const currentScopes = Object.keys(
1548
- (_a2 = walletSession == null ? void 0 : walletSession.sessionScopes) != null ? _a2 : {}
1676
+ (_c = walletSession == null ? void 0 : walletSession.sessionScopes) != null ? _c : {}
1549
1677
  );
1550
- const proposedScopes = (_b = options == null ? void 0 : options.scopes) != null ? _b : [];
1551
- const proposedCaipAccountIds = (_c = options == null ? void 0 : options.caipAccountIds) != null ? _c : [];
1678
+ const proposedScopes = (_d = options == null ? void 0 : options.scopes) != null ? _d : [];
1679
+ const proposedCaipAccountIds = (_e = options == null ? void 0 : options.caipAccountIds) != null ? _e : [];
1552
1680
  const hasSameScopesAndAccounts = isSameScopesAndAccounts(
1553
1681
  currentScopes,
1554
1682
  proposedScopes,
@@ -1556,17 +1684,6 @@ var DefaultTransport = class {
1556
1684
  proposedCaipAccountIds
1557
1685
  );
1558
1686
  if (!hasSameScopesAndAccounts) {
1559
- yield this.request(
1560
- { method: "wallet_revokeSession", params: walletSession },
1561
- __privateGet(this, _defaultRequestOptions)
1562
- );
1563
- const optionalScopes = addValidAccounts(
1564
- getOptionalScopes((_d = options == null ? void 0 : options.scopes) != null ? _d : []),
1565
- getValidAccounts((_e = options == null ? void 0 : options.caipAccountIds) != null ? _e : [])
1566
- );
1567
- const createSessionParams = {
1568
- optionalScopes
1569
- };
1570
1687
  const response = yield this.request(
1571
1688
  { method: "wallet_createSession", params: createSessionParams },
1572
1689
  __privateGet(this, _defaultRequestOptions)
@@ -1577,14 +1694,6 @@ var DefaultTransport = class {
1577
1694
  walletSession = response.result;
1578
1695
  }
1579
1696
  } else if (!walletSession || (options == null ? void 0 : options.forceRequest)) {
1580
- const optionalScopes = addValidAccounts(
1581
- getOptionalScopes((_f = options == null ? void 0 : options.scopes) != null ? _f : []),
1582
- getValidAccounts((_g = options == null ? void 0 : options.caipAccountIds) != null ? _g : [])
1583
- );
1584
- const createSessionParams = {
1585
- optionalScopes,
1586
- sessionProperties: options == null ? void 0 : options.sessionProperties
1587
- };
1588
1697
  const response = yield this.request(
1589
1698
  { method: "wallet_createSession", params: createSessionParams },
1590
1699
  __privateGet(this, _defaultRequestOptions)
@@ -1601,9 +1710,14 @@ var DefaultTransport = class {
1601
1710
  });
1602
1711
  }
1603
1712
  disconnect() {
1604
- return __async(this, null, function* () {
1713
+ return __async(this, arguments, function* (scopes = []) {
1714
+ yield this.request({ method: "wallet_revokeSession", params: { scopes } });
1715
+ const response = yield this.request({ method: "wallet_getSession" });
1716
+ const { sessionScopes } = response.result;
1717
+ if (Object.keys(sessionScopes).length > 0) {
1718
+ return;
1719
+ }
1605
1720
  __privateGet(this, _notificationCallbacks).clear();
1606
- yield this.request({ method: "wallet_revokeSession", params: {} });
1607
1721
  if (__privateGet(this, _handleResponseListener)) {
1608
1722
  window.removeEventListener("message", __privateGet(this, _handleResponseListener));
1609
1723
  __privateSet(this, _handleResponseListener, void 0);
@@ -1617,7 +1731,7 @@ var DefaultTransport = class {
1617
1731
  request.reject(new Error("Transport disconnected"));
1618
1732
  }
1619
1733
  __privateGet(this, _pendingRequests).clear();
1620
- return __privateGet(this, _transport).disconnect();
1734
+ yield __privateGet(this, _transport).disconnect();
1621
1735
  });
1622
1736
  }
1623
1737
  isConnected() {
@@ -1636,13 +1750,23 @@ var DefaultTransport = class {
1636
1750
  };
1637
1751
  }
1638
1752
  getActiveSession() {
1639
- throw new Error("getActiveSession is purposely not implemented for the DefaultTransport");
1753
+ return __async(this, null, function* () {
1754
+ throw new Error(
1755
+ "getActiveSession is purposely not implemented for the DefaultTransport"
1756
+ );
1757
+ });
1758
+ }
1759
+ getStoredPendingSessionRequest() {
1760
+ return __async(this, null, function* () {
1761
+ throw new Error(
1762
+ "getStoredPendingSessionRequest is purposely not implemented for the DefaultTransport"
1763
+ );
1764
+ });
1640
1765
  }
1641
1766
  };
1642
1767
  _notificationCallbacks = new WeakMap();
1643
1768
  _transport = new WeakMap();
1644
1769
  _defaultRequestOptions = new WeakMap();
1645
- _reqId = new WeakMap();
1646
1770
  _pendingRequests = new WeakMap();
1647
1771
  _handleResponseListener = new WeakMap();
1648
1772
  _handleNotificationListener = new WeakMap();
@@ -1660,16 +1784,16 @@ notifyCallbacks_fn = function(data) {
1660
1784
  }
1661
1785
  };
1662
1786
  isMetamaskProviderEvent_fn = function(event) {
1663
- var _a2, _b;
1664
- 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
1787
+ var _a3, _b;
1788
+ 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
1665
1789
  event.origin === location.origin;
1666
1790
  };
1667
1791
  handleResponse_fn = function(event) {
1668
- var _a2, _b;
1792
+ var _a3, _b;
1669
1793
  if (!__privateMethod(this, _DefaultTransport_instances, isMetamaskProviderEvent_fn).call(this, event)) {
1670
1794
  return;
1671
1795
  }
1672
- const responseData = (_b = (_a2 = event == null ? void 0 : event.data) == null ? void 0 : _a2.data) == null ? void 0 : _b.data;
1796
+ const responseData = (_b = (_a3 = event == null ? void 0 : event.data) == null ? void 0 : _a3.data) == null ? void 0 : _b.data;
1673
1797
  if (typeof responseData === "object" && responseData !== null && "method" in responseData) {
1674
1798
  return;
1675
1799
  }
@@ -1691,11 +1815,11 @@ handleResponse_fn = function(event) {
1691
1815
  }
1692
1816
  };
1693
1817
  handleNotification_fn = function(event) {
1694
- var _a2, _b;
1818
+ var _a3, _b;
1695
1819
  if (!__privateMethod(this, _DefaultTransport_instances, isMetamaskProviderEvent_fn).call(this, event)) {
1696
1820
  return;
1697
1821
  }
1698
- const responseData = (_b = (_a2 = event == null ? void 0 : event.data) == null ? void 0 : _a2.data) == null ? void 0 : _b.data;
1822
+ const responseData = (_b = (_a3 = event == null ? void 0 : event.data) == null ? void 0 : _a3.data) == null ? void 0 : _b.data;
1699
1823
  if (typeof responseData === "object" && responseData.method === "metamask_chainChanged" || responseData.method === "metamask_accountsChanged") {
1700
1824
  __privateMethod(this, _DefaultTransport_instances, notifyCallbacks_fn).call(this, responseData);
1701
1825
  }
@@ -1710,11 +1834,172 @@ setupMessageListener_fn = function() {
1710
1834
  window.addEventListener("message", __privateGet(this, _handleNotificationListener));
1711
1835
  };
1712
1836
 
1837
+ // src/multichain/transports/multichainApiClientWrapper/index.ts
1838
+ var import_rpc_errors = require("@metamask/rpc-errors");
1839
+ init_utils2();
1840
+ var _notificationCallbacks2, _MultichainApiClientWrapperTransport_instances, walletCreateSession_fn, walletGetSession_fn, walletRevokeSession_fn, walletInvokeMethod_fn;
1841
+ var MultichainApiClientWrapperTransport = class {
1842
+ constructor(metamaskConnectMultichain) {
1843
+ this.metamaskConnectMultichain = metamaskConnectMultichain;
1844
+ __privateAdd(this, _MultichainApiClientWrapperTransport_instances);
1845
+ __privateAdd(this, _notificationCallbacks2, /* @__PURE__ */ new Set());
1846
+ }
1847
+ isTransportDefined() {
1848
+ try {
1849
+ return Boolean(this.metamaskConnectMultichain.transport);
1850
+ } catch (_error) {
1851
+ return false;
1852
+ }
1853
+ }
1854
+ clearNotificationCallbacks() {
1855
+ __privateGet(this, _notificationCallbacks2).clear();
1856
+ }
1857
+ notifyCallbacks(data) {
1858
+ __privateGet(this, _notificationCallbacks2).forEach((callback) => {
1859
+ callback(data);
1860
+ });
1861
+ }
1862
+ clearTransportNotificationListener() {
1863
+ var _a3;
1864
+ (_a3 = this.notificationListener) == null ? void 0 : _a3.call(this);
1865
+ this.notificationListener = void 0;
1866
+ }
1867
+ setupTransportNotificationListener() {
1868
+ if (!this.isTransportDefined() || this.notificationListener) {
1869
+ return;
1870
+ }
1871
+ this.notificationListener = this.metamaskConnectMultichain.transport.onNotification(
1872
+ this.notifyCallbacks.bind(this)
1873
+ );
1874
+ }
1875
+ connect() {
1876
+ return __async(this, null, function* () {
1877
+ console.log("\u{1F4DA} connect");
1878
+ yield this.metamaskConnectMultichain.emitSessionChanged();
1879
+ });
1880
+ }
1881
+ disconnect() {
1882
+ return __async(this, null, function* () {
1883
+ return Promise.resolve();
1884
+ });
1885
+ }
1886
+ isConnected() {
1887
+ return true;
1888
+ }
1889
+ request(_0) {
1890
+ return __async(this, arguments, function* (params, _options = {}) {
1891
+ const id = getUniqueRequestId();
1892
+ const requestPayload = __spreadValues({
1893
+ id,
1894
+ jsonrpc: "2.0"
1895
+ }, params);
1896
+ switch (requestPayload.method) {
1897
+ case "wallet_createSession":
1898
+ return __privateMethod(this, _MultichainApiClientWrapperTransport_instances, walletCreateSession_fn).call(this, requestPayload);
1899
+ case "wallet_getSession":
1900
+ return __privateMethod(this, _MultichainApiClientWrapperTransport_instances, walletGetSession_fn).call(this, requestPayload);
1901
+ case "wallet_revokeSession":
1902
+ return __privateMethod(this, _MultichainApiClientWrapperTransport_instances, walletRevokeSession_fn).call(this, requestPayload);
1903
+ case "wallet_invokeMethod":
1904
+ return __privateMethod(this, _MultichainApiClientWrapperTransport_instances, walletInvokeMethod_fn).call(this, requestPayload);
1905
+ default:
1906
+ throw new Error(`Unsupported method: ${requestPayload.method}`);
1907
+ }
1908
+ throw new Error(`Unknown method: ${requestPayload.method}`);
1909
+ });
1910
+ }
1911
+ onNotification(callback) {
1912
+ this.setupTransportNotificationListener();
1913
+ __privateGet(this, _notificationCallbacks2).add(callback);
1914
+ return () => {
1915
+ __privateGet(this, _notificationCallbacks2).delete(callback);
1916
+ };
1917
+ }
1918
+ };
1919
+ _notificationCallbacks2 = new WeakMap();
1920
+ _MultichainApiClientWrapperTransport_instances = new WeakSet();
1921
+ walletCreateSession_fn = function(request) {
1922
+ return __async(this, null, function* () {
1923
+ console.log("\u{1F4DA} #walletCreateSession", request);
1924
+ const createSessionParams = request.params;
1925
+ const scopes = Object.keys(__spreadValues(__spreadValues({}, createSessionParams.optionalScopes), createSessionParams.requiredScopes));
1926
+ const scopeAccounts = [];
1927
+ scopes.forEach((scope) => {
1928
+ var _a3, _b, _c, _d;
1929
+ const requiredScope = (_a3 = createSessionParams.requiredScopes) == null ? void 0 : _a3[scope];
1930
+ const optionalScope = (_b = createSessionParams.optionalScopes) == null ? void 0 : _b[scope];
1931
+ if (requiredScope) {
1932
+ scopeAccounts.push(...(_c = requiredScope.accounts) != null ? _c : []);
1933
+ }
1934
+ if (optionalScope) {
1935
+ scopeAccounts.push(...(_d = optionalScope.accounts) != null ? _d : []);
1936
+ }
1937
+ });
1938
+ const accounts = [...new Set(scopeAccounts)];
1939
+ console.log("\u{1F4DA} SDK connect");
1940
+ yield this.metamaskConnectMultichain.connect(
1941
+ scopes,
1942
+ accounts,
1943
+ createSessionParams.sessionProperties
1944
+ );
1945
+ console.log("\u{1F4DA} SDK connected");
1946
+ return this.metamaskConnectMultichain.transport.request({
1947
+ method: "wallet_getSession"
1948
+ });
1949
+ });
1950
+ };
1951
+ walletGetSession_fn = function(request) {
1952
+ return __async(this, null, function* () {
1953
+ if (!this.isTransportDefined()) {
1954
+ return {
1955
+ jsonrpc: "2.0",
1956
+ id: request.id,
1957
+ result: {
1958
+ sessionScopes: {}
1959
+ }
1960
+ };
1961
+ }
1962
+ return this.metamaskConnectMultichain.transport.request({
1963
+ method: "wallet_getSession"
1964
+ });
1965
+ });
1966
+ };
1967
+ walletRevokeSession_fn = function(request) {
1968
+ return __async(this, null, function* () {
1969
+ var _a3;
1970
+ if (!this.isTransportDefined()) {
1971
+ return { jsonrpc: "2.0", id: request.id, result: true };
1972
+ }
1973
+ const revokeSessionParams = request.params;
1974
+ const scopes = (_a3 = revokeSessionParams == null ? void 0 : revokeSessionParams.scopes) != null ? _a3 : [];
1975
+ try {
1976
+ yield this.metamaskConnectMultichain.disconnect(scopes);
1977
+ return { jsonrpc: "2.0", id: request.id, result: true };
1978
+ } catch (_error) {
1979
+ return { jsonrpc: "2.0", id: request.id, result: false };
1980
+ }
1981
+ });
1982
+ };
1983
+ walletInvokeMethod_fn = function(request) {
1984
+ return __async(this, null, function* () {
1985
+ if (!this.isTransportDefined()) {
1986
+ return { error: import_rpc_errors.providerErrors.unauthorized() };
1987
+ }
1988
+ const result = this.metamaskConnectMultichain.invokeMethod(
1989
+ request.params
1990
+ );
1991
+ return {
1992
+ result
1993
+ };
1994
+ });
1995
+ };
1996
+
1713
1997
  // src/multichain/transports/mwp/index.ts
1714
1998
  var import_mobile_wallet_protocol_core = require("@metamask/mobile-wallet-protocol-core");
1715
1999
  var import_multichain_api_client2 = require("@metamask/multichain-api-client");
2000
+ var import_rpc_errors2 = require("@metamask/rpc-errors");
1716
2001
  init_domain();
1717
- init_utils();
2002
+ init_utils2();
1718
2003
 
1719
2004
  // src/multichain/transports/constants.ts
1720
2005
  var MULTICHAIN_PROVIDER_STREAM_NAME = "metamask-multichain-provider";
@@ -1727,6 +2012,7 @@ var DEFAULT_RESUME_TIMEOUT = 10 * 1e3;
1727
2012
  var SESSION_STORE_KEY = "cache_wallet_getSession";
1728
2013
  var ACCOUNTS_STORE_KEY = "cache_eth_accounts";
1729
2014
  var CHAIN_STORE_KEY = "cache_eth_chainId";
2015
+ var PENDING_SESSION_REQUEST_KEY = "pending_session_request";
1730
2016
  var CACHED_METHOD_LIST = [
1731
2017
  "wallet_getSession",
1732
2018
  "wallet_createSession",
@@ -1746,10 +2032,15 @@ var MWPTransport = class {
1746
2032
  this.dappClient = dappClient;
1747
2033
  this.kvstore = kvstore;
1748
2034
  this.options = options;
1749
- this.__reqId = 0;
1750
2035
  this.__pendingRequests = /* @__PURE__ */ new Map();
1751
2036
  this.notificationCallbacks = /* @__PURE__ */ new Set();
1752
2037
  this.dappClient.on("message", this.handleMessage.bind(this));
2038
+ this.dappClient.on("session_request", (sessionRequest) => {
2039
+ this.currentSessionRequest = sessionRequest;
2040
+ this.kvstore.set(PENDING_SESSION_REQUEST_KEY, JSON.stringify(sessionRequest)).catch((err) => {
2041
+ logger("Failed to store pending session request", err);
2042
+ });
2043
+ });
1753
2044
  if (typeof window !== "undefined" && typeof window.addEventListener !== "undefined") {
1754
2045
  this.windowFocusHandler = this.onWindowFocus.bind(this);
1755
2046
  window.addEventListener("focus", this.windowFocusHandler);
@@ -1764,6 +2055,34 @@ var MWPTransport = class {
1764
2055
  get sessionRequest() {
1765
2056
  return this.currentSessionRequest;
1766
2057
  }
2058
+ /**
2059
+ * Returns the stored pending session request from the dappClient session_request event, if any.
2060
+ *
2061
+ * @returns The stored SessionRequest, or null if none or invalid.
2062
+ */
2063
+ getStoredPendingSessionRequest() {
2064
+ return __async(this, null, function* () {
2065
+ try {
2066
+ const raw = yield this.kvstore.get(PENDING_SESSION_REQUEST_KEY);
2067
+ if (!raw) {
2068
+ return null;
2069
+ }
2070
+ return JSON.parse(raw);
2071
+ } catch (e) {
2072
+ return null;
2073
+ }
2074
+ });
2075
+ }
2076
+ /**
2077
+ * Removes the stored pending session request from the KVStore.
2078
+ * This is necessary to ensure that ConnectMultichain is able to correctly
2079
+ * infer the MWP Transport connection attempt status.
2080
+ */
2081
+ removeStoredPendingSessionRequest() {
2082
+ return __async(this, null, function* () {
2083
+ yield this.kvstore.delete(PENDING_SESSION_REQUEST_KEY);
2084
+ });
2085
+ }
1767
2086
  onWindowFocus() {
1768
2087
  if (!this.isConnected()) {
1769
2088
  this.dappClient.reconnect();
@@ -1780,6 +2099,17 @@ var MWPTransport = class {
1780
2099
  request.reject(error);
1781
2100
  }
1782
2101
  }
2102
+ parseWalletError(errorPayload) {
2103
+ const errorData = errorPayload;
2104
+ if (typeof errorData.code === "number" && typeof errorData.message === "string") {
2105
+ return import_rpc_errors2.providerErrors.custom({
2106
+ code: errorData.code,
2107
+ message: errorData.message
2108
+ });
2109
+ }
2110
+ const message = errorPayload instanceof Error ? errorPayload.message : JSON.stringify(errorPayload);
2111
+ return import_rpc_errors2.rpcErrors.internal({ message });
2112
+ }
1783
2113
  handleMessage(message) {
1784
2114
  if (typeof message === "object" && message !== null) {
1785
2115
  if ("data" in message) {
@@ -1787,6 +2117,12 @@ var MWPTransport = class {
1787
2117
  if ("id" in messagePayload && typeof messagePayload.id === "string") {
1788
2118
  const request = this.pendingRequests.get(messagePayload.id);
1789
2119
  if (request) {
2120
+ clearTimeout(request.timeout);
2121
+ if ("error" in messagePayload && messagePayload.error) {
2122
+ this.pendingRequests.delete(messagePayload.id);
2123
+ request.reject(this.parseWalletError(messagePayload.error));
2124
+ return;
2125
+ }
1790
2126
  const requestWithName = __spreadProps(__spreadValues({}, messagePayload), {
1791
2127
  method: request.method === "wallet_getSession" || request.method === "wallet_createSession" ? "wallet_sessionChanged" : request.method
1792
2128
  });
@@ -1794,7 +2130,6 @@ var MWPTransport = class {
1794
2130
  method: request.method === "wallet_getSession" || request.method === "wallet_createSession" ? "wallet_sessionChanged" : request.method,
1795
2131
  params: requestWithName.result
1796
2132
  });
1797
- clearTimeout(request.timeout);
1798
2133
  this.notifyCallbacks(notification);
1799
2134
  request.resolve(requestWithName);
1800
2135
  this.pendingRequests.delete(messagePayload.id);
@@ -1830,7 +2165,7 @@ var MWPTransport = class {
1830
2165
  }
1831
2166
  onResumeSuccess(resumeResolve, resumeReject, options) {
1832
2167
  return __async(this, null, function* () {
1833
- var _a2, _b, _c, _d, _e, _f, _g;
2168
+ var _a3, _b, _c, _d, _e, _f, _g;
1834
2169
  try {
1835
2170
  yield this.waitForWalletSessionIfNotCached();
1836
2171
  const sessionRequest = yield this.request({
@@ -1842,7 +2177,7 @@ var MWPTransport = class {
1842
2177
  let walletSession = sessionRequest.result;
1843
2178
  if (walletSession && options) {
1844
2179
  const currentScopes = Object.keys(
1845
- (_a2 = walletSession == null ? void 0 : walletSession.sessionScopes) != null ? _a2 : {}
2180
+ (_a3 = walletSession == null ? void 0 : walletSession.sessionScopes) != null ? _a3 : {}
1846
2181
  );
1847
2182
  const proposedScopes = (_b = options == null ? void 0 : options.scopes) != null ? _b : [];
1848
2183
  const proposedCaipAccountIds = (_c = options == null ? void 0 : options.caipAccountIds) != null ? _c : [];
@@ -1884,6 +2219,7 @@ var MWPTransport = class {
1884
2219
  }
1885
2220
  walletSession = response.result;
1886
2221
  }
2222
+ yield this.removeStoredPendingSessionRequest();
1887
2223
  this.notifyCallbacks({
1888
2224
  method: "wallet_sessionChanged",
1889
2225
  params: walletSession
@@ -1899,7 +2235,7 @@ var MWPTransport = class {
1899
2235
  return __async(this, null, function* () {
1900
2236
  const request = __spreadValues({
1901
2237
  jsonrpc: "2.0",
1902
- id: `${this.__reqId++}`
2238
+ id: String(getUniqueRequestId())
1903
2239
  }, payload);
1904
2240
  const cachedWalletSession = yield this.getCachedResponse(request);
1905
2241
  if (cachedWalletSession) {
@@ -1907,10 +2243,10 @@ var MWPTransport = class {
1907
2243
  return cachedWalletSession;
1908
2244
  }
1909
2245
  return new Promise((resolve, reject) => {
1910
- var _a2;
2246
+ var _a3;
1911
2247
  const timeout = setTimeout(() => {
1912
2248
  this.rejectRequest(request.id, new import_multichain_api_client2.TransportTimeoutError());
1913
- }, (_a2 = options == null ? void 0 : options.timeout) != null ? _a2 : this.options.requestTimeout);
2249
+ }, (_a3 = options == null ? void 0 : options.timeout) != null ? _a3 : this.options.requestTimeout);
1914
2250
  this.pendingRequests.set(request.id, {
1915
2251
  request,
1916
2252
  method: request.method,
@@ -1935,28 +2271,29 @@ var MWPTransport = class {
1935
2271
  if (session) {
1936
2272
  logger("active session found", session);
1937
2273
  }
2274
+ const storedSessionRequestBeforeConnectionAttempt = yield this.getStoredPendingSessionRequest();
1938
2275
  let timeout;
1939
2276
  let initialConnectionMessageHandler;
1940
2277
  const connectionPromise = new Promise((resolve, reject) => __async(this, null, function* () {
1941
2278
  let connection;
1942
2279
  if (session) {
1943
2280
  connection = new Promise((resumeResolve, resumeReject) => {
1944
- var _a2;
2281
+ var _a3;
1945
2282
  if (this.dappClient.state === "CONNECTED") {
1946
2283
  this.onResumeSuccess(resumeResolve, resumeReject, options);
1947
2284
  } else {
1948
2285
  this.dappClient.once("connected", () => __async(this, null, function* () {
1949
2286
  this.onResumeSuccess(resumeResolve, resumeReject, options);
1950
2287
  }));
1951
- dappClient.resume((_a2 = session == null ? void 0 : session.id) != null ? _a2 : "");
2288
+ dappClient.resume((_a3 = session == null ? void 0 : session.id) != null ? _a3 : "");
1952
2289
  }
1953
2290
  });
1954
2291
  } else {
1955
2292
  connection = new Promise(
1956
2293
  (resolveConnection, rejectConnection) => {
1957
- var _a2, _b;
2294
+ var _a3, _b;
1958
2295
  const optionalScopes = addValidAccounts(
1959
- getOptionalScopes((_a2 = options == null ? void 0 : options.scopes) != null ? _a2 : []),
2296
+ getOptionalScopes((_a3 = options == null ? void 0 : options.scopes) != null ? _a3 : []),
1960
2297
  getValidAccounts((_b = options == null ? void 0 : options.caipAccountIds) != null ? _b : [])
1961
2298
  );
1962
2299
  const sessionRequest = {
@@ -1965,33 +2302,35 @@ var MWPTransport = class {
1965
2302
  };
1966
2303
  const request = {
1967
2304
  jsonrpc: "2.0",
1968
- id: `${this.__reqId++}`,
2305
+ id: String(getUniqueRequestId()),
1969
2306
  method: "wallet_createSession",
1970
2307
  params: sessionRequest
1971
2308
  };
1972
2309
  initialConnectionMessageHandler = (message) => __async(this, null, function* () {
1973
- if (typeof message === "object" && message !== null) {
1974
- if ("data" in message) {
1975
- const messagePayload = message.data;
1976
- if (messagePayload.method === "wallet_createSession" || messagePayload.method === "wallet_sessionChanged") {
1977
- if (messagePayload.error) {
1978
- if (initialConnectionMessageHandler) {
1979
- this.dappClient.off(
1980
- "message",
1981
- initialConnectionMessageHandler
1982
- );
1983
- }
1984
- return rejectConnection(messagePayload.error);
1985
- }
1986
- yield this.storeWalletSession(
1987
- request,
1988
- messagePayload
1989
- );
1990
- this.notifyCallbacks(messagePayload);
1991
- return resolveConnection();
1992
- }
1993
- }
2310
+ if (typeof message !== "object" || message === null) {
2311
+ return;
2312
+ }
2313
+ if (!("data" in message)) {
2314
+ return;
2315
+ }
2316
+ const messagePayload = message.data;
2317
+ const isMatchingId = messagePayload.id === request.id;
2318
+ const isMatchingMethod = messagePayload.method === "wallet_createSession" || messagePayload.method === "wallet_sessionChanged";
2319
+ if (!isMatchingId && !isMatchingMethod) {
2320
+ return;
2321
+ }
2322
+ if (messagePayload.error) {
2323
+ return rejectConnection(
2324
+ this.parseWalletError(messagePayload.error)
2325
+ );
1994
2326
  }
2327
+ yield this.storeWalletSession(
2328
+ request,
2329
+ messagePayload
2330
+ );
2331
+ yield this.removeStoredPendingSessionRequest();
2332
+ this.notifyCallbacks(messagePayload);
2333
+ return resolveConnection();
1995
2334
  });
1996
2335
  this.dappClient.on("message", initialConnectionMessageHandler);
1997
2336
  dappClient.connect({
@@ -2012,14 +2351,18 @@ var MWPTransport = class {
2012
2351
  }
2013
2352
  );
2014
2353
  }
2015
- timeout = setTimeout(() => {
2016
- reject(new import_multichain_api_client2.TransportTimeoutError());
2017
- }, this.options.connectionTimeout);
2354
+ timeout = setTimeout(
2355
+ () => {
2356
+ reject(new import_multichain_api_client2.TransportTimeoutError());
2357
+ },
2358
+ storedSessionRequestBeforeConnectionAttempt ? this.options.resumeTimeout : this.options.connectionTimeout
2359
+ );
2018
2360
  connection.then(resolve).catch(reject);
2019
2361
  }));
2020
- return connectionPromise.catch((error) => {
2362
+ return connectionPromise.catch((error) => __async(this, null, function* () {
2363
+ yield this.dappClient.disconnect();
2021
2364
  throw error;
2022
- }).finally(() => {
2365
+ })).finally(() => {
2023
2366
  if (timeout) {
2024
2367
  clearTimeout(timeout);
2025
2368
  }
@@ -2027,24 +2370,68 @@ var MWPTransport = class {
2027
2370
  this.dappClient.off("message", initialConnectionMessageHandler);
2028
2371
  initialConnectionMessageHandler = void 0;
2029
2372
  }
2373
+ this.removeStoredPendingSessionRequest();
2030
2374
  });
2031
2375
  });
2032
2376
  }
2033
2377
  /**
2034
2378
  * Disconnects from the Mobile Wallet Protocol
2035
2379
  *
2380
+ * @param [scopes] - The scopes to revoke. If not provided or empty, all scopes will be revoked.
2036
2381
  * @returns Nothing
2037
2382
  */
2038
2383
  disconnect() {
2039
- return __async(this, null, function* () {
2040
- if (typeof window !== "undefined" && typeof window.removeEventListener !== "undefined" && this.windowFocusHandler) {
2041
- window.removeEventListener("focus", this.windowFocusHandler);
2042
- this.windowFocusHandler = void 0;
2043
- }
2044
- this.kvstore.delete(SESSION_STORE_KEY);
2045
- this.kvstore.delete(ACCOUNTS_STORE_KEY);
2046
- this.kvstore.delete(CHAIN_STORE_KEY);
2047
- return this.dappClient.disconnect();
2384
+ return __async(this, arguments, function* (scopes = []) {
2385
+ var _a3, _b;
2386
+ const cachedSession = yield this.getCachedResponse({
2387
+ jsonrpc: "2.0",
2388
+ id: "0",
2389
+ method: "wallet_getSession"
2390
+ });
2391
+ const cachedSessionScopes = (_b = (_a3 = cachedSession == null ? void 0 : cachedSession.result) == null ? void 0 : _a3.sessionScopes) != null ? _b : {};
2392
+ const remainingScopes = scopes.length === 0 ? [] : Object.keys(cachedSessionScopes).filter(
2393
+ (scope) => !scopes.includes(scope)
2394
+ );
2395
+ const newSessionScopes = Object.fromEntries(
2396
+ Object.entries(cachedSessionScopes).filter(
2397
+ ([key]) => remainingScopes.includes(key)
2398
+ )
2399
+ );
2400
+ this.request({ method: "wallet_revokeSession", params: { scopes } }).catch(
2401
+ (err) => {
2402
+ console.error("error revoking session", err);
2403
+ }
2404
+ );
2405
+ const remainingScopesIncludeEip155 = remainingScopes.some(
2406
+ (scope) => scope.includes("eip155")
2407
+ );
2408
+ if (!remainingScopesIncludeEip155) {
2409
+ this.kvstore.delete(ACCOUNTS_STORE_KEY);
2410
+ this.kvstore.delete(CHAIN_STORE_KEY);
2411
+ }
2412
+ if (remainingScopes.length > 0) {
2413
+ this.kvstore.set(
2414
+ SESSION_STORE_KEY,
2415
+ JSON.stringify({
2416
+ result: {
2417
+ sessionScopes: newSessionScopes
2418
+ }
2419
+ })
2420
+ );
2421
+ } else {
2422
+ this.kvstore.delete(SESSION_STORE_KEY);
2423
+ if (typeof window !== "undefined" && typeof window.removeEventListener !== "undefined" && this.windowFocusHandler) {
2424
+ window.removeEventListener("focus", this.windowFocusHandler);
2425
+ this.windowFocusHandler = void 0;
2426
+ }
2427
+ yield this.dappClient.disconnect();
2428
+ }
2429
+ this.notifyCallbacks({
2430
+ method: "wallet_sessionChanged",
2431
+ params: {
2432
+ sessionScopes: newSessionScopes
2433
+ }
2434
+ });
2048
2435
  });
2049
2436
  }
2050
2437
  /**
@@ -2089,7 +2476,7 @@ var MWPTransport = class {
2089
2476
  }
2090
2477
  getCachedResponse(request) {
2091
2478
  return __async(this, null, function* () {
2092
- var _a2;
2479
+ var _a3;
2093
2480
  if (request.method === "wallet_getSession") {
2094
2481
  const walletGetSession = yield this.kvstore.get(SESSION_STORE_KEY);
2095
2482
  if (walletGetSession) {
@@ -2097,7 +2484,7 @@ var MWPTransport = class {
2097
2484
  return {
2098
2485
  id: request.id,
2099
2486
  jsonrpc: "2.0",
2100
- result: (_a2 = walletSession.params) != null ? _a2 : walletSession.result,
2487
+ result: (_a3 = walletSession.params) != null ? _a3 : walletSession.result,
2101
2488
  // "what?... why walletSession.params?.."
2102
2489
  method: request.method
2103
2490
  };
@@ -2150,7 +2537,7 @@ var MWPTransport = class {
2150
2537
  return __async(this, null, function* () {
2151
2538
  const request = __spreadValues({
2152
2539
  jsonrpc: "2.0",
2153
- id: `${this.__reqId++}`
2540
+ id: String(getUniqueRequestId())
2154
2541
  }, payload);
2155
2542
  const cachedWalletSession = yield this.getCachedResponse(request);
2156
2543
  if (cachedWalletSession) {
@@ -2161,10 +2548,10 @@ var MWPTransport = class {
2161
2548
  yield this.attemptResumeSession();
2162
2549
  }
2163
2550
  return new Promise((resolve, reject) => {
2164
- var _a2;
2551
+ var _a3;
2165
2552
  const timeout = setTimeout(() => {
2166
2553
  this.rejectRequest(request.id, new import_multichain_api_client2.TransportTimeoutError());
2167
- }, (_a2 = options == null ? void 0 : options.timeout) != null ? _a2 : this.options.requestTimeout);
2554
+ }, (_a3 = options == null ? void 0 : options.timeout) != null ? _a3 : this.options.requestTimeout);
2168
2555
  this.pendingRequests.set(request.id, {
2169
2556
  request,
2170
2557
  method: request.method,
@@ -2232,6 +2619,7 @@ var MWPTransport = class {
2232
2619
  const timeoutPromise = new Promise((_resolve, reject) => {
2233
2620
  setTimeout(() => {
2234
2621
  unsubscribe();
2622
+ this.removeStoredPendingSessionRequest();
2235
2623
  reject(new import_multichain_api_client2.TransportTimeoutError());
2236
2624
  }, this.options.resumeTimeout);
2237
2625
  });
@@ -2268,172 +2656,15 @@ var KeyManager = class {
2268
2656
  var keymanager = new KeyManager();
2269
2657
 
2270
2658
  // src/multichain/index.ts
2271
- init_utils();
2272
-
2273
- // src/multichain/transports/multichainApiClientWrapper/index.ts
2274
- var import_rpc_errors = require("@metamask/rpc-errors");
2275
- var MAX = 4294967295;
2276
- var idCounter = Math.floor(Math.random() * MAX);
2277
- var getUniqueId = () => {
2278
- idCounter = (idCounter + 1) % MAX;
2279
- return idCounter;
2280
- };
2281
- var _MultichainApiClientWrapperTransport_instances, walletCreateSession_fn, walletGetSession_fn, walletRevokeSession_fn, walletInvokeMethod_fn;
2282
- var MultichainApiClientWrapperTransport = class {
2283
- constructor(metamaskConnectMultichain) {
2284
- this.metamaskConnectMultichain = metamaskConnectMultichain;
2285
- __privateAdd(this, _MultichainApiClientWrapperTransport_instances);
2286
- this.requestId = getUniqueId();
2287
- this.notificationCallbacks = /* @__PURE__ */ new Set();
2288
- }
2289
- isTransportDefined() {
2290
- try {
2291
- return Boolean(this.metamaskConnectMultichain.transport);
2292
- } catch (error) {
2293
- return false;
2294
- }
2295
- }
2296
- clearNotificationCallbacks() {
2297
- this.notificationCallbacks.clear();
2298
- }
2299
- notifyCallbacks(data) {
2300
- this.notificationCallbacks.forEach((callback) => {
2301
- callback(data);
2302
- });
2303
- }
2304
- setupNotifcationListener() {
2305
- this.metamaskConnectMultichain.transport.onNotification(
2306
- this.notifyCallbacks.bind(this)
2307
- );
2308
- }
2309
- connect() {
2310
- return __async(this, null, function* () {
2311
- console.log("\u{1F4DA} connect");
2312
- return Promise.resolve();
2313
- });
2314
- }
2315
- disconnect() {
2316
- return __async(this, null, function* () {
2317
- return Promise.resolve();
2318
- });
2319
- }
2320
- isConnected() {
2321
- return true;
2322
- }
2323
- request(_0) {
2324
- return __async(this, arguments, function* (params, _options = {}) {
2325
- const id = this.requestId++;
2326
- const requestPayload = __spreadValues({
2327
- id,
2328
- jsonrpc: "2.0"
2329
- }, params);
2330
- switch (requestPayload.method) {
2331
- case "wallet_createSession":
2332
- return __privateMethod(this, _MultichainApiClientWrapperTransport_instances, walletCreateSession_fn).call(this, requestPayload);
2333
- case "wallet_getSession":
2334
- return __privateMethod(this, _MultichainApiClientWrapperTransport_instances, walletGetSession_fn).call(this, requestPayload);
2335
- case "wallet_revokeSession":
2336
- return __privateMethod(this, _MultichainApiClientWrapperTransport_instances, walletRevokeSession_fn).call(this, requestPayload);
2337
- case "wallet_invokeMethod":
2338
- return __privateMethod(this, _MultichainApiClientWrapperTransport_instances, walletInvokeMethod_fn).call(this, requestPayload);
2339
- default:
2340
- throw new Error(`Unsupported method: ${requestPayload.method}`);
2341
- }
2342
- throw new Error(`Unknown method: ${requestPayload.method}`);
2343
- });
2344
- }
2345
- onNotification(callback) {
2346
- if (!this.isTransportDefined()) {
2347
- this.notificationCallbacks.add(callback);
2348
- return () => {
2349
- this.notificationCallbacks.delete(callback);
2350
- };
2351
- }
2352
- return this.metamaskConnectMultichain.transport.onNotification(callback);
2353
- }
2354
- };
2355
- _MultichainApiClientWrapperTransport_instances = new WeakSet();
2356
- walletCreateSession_fn = function(request) {
2357
- return __async(this, null, function* () {
2358
- console.log("\u{1F4DA} #walletCreateSession", request);
2359
- const createSessionParams = request.params;
2360
- const scopes = Object.keys(__spreadValues(__spreadValues({}, createSessionParams.optionalScopes), createSessionParams.requiredScopes));
2361
- const scopeAccounts = [];
2362
- scopes.forEach((scope) => {
2363
- var _a2, _b, _c, _d;
2364
- const requiredScope = (_a2 = createSessionParams.requiredScopes) == null ? void 0 : _a2[scope];
2365
- const optionalScope = (_b = createSessionParams.optionalScopes) == null ? void 0 : _b[scope];
2366
- if (requiredScope) {
2367
- scopeAccounts.push(...(_c = requiredScope.accounts) != null ? _c : []);
2368
- }
2369
- if (optionalScope) {
2370
- scopeAccounts.push(...(_d = optionalScope.accounts) != null ? _d : []);
2371
- }
2372
- });
2373
- const accounts = [...new Set(scopeAccounts)];
2374
- console.log("\u{1F4DA} SDK connect");
2375
- yield this.metamaskConnectMultichain.connect(
2376
- scopes,
2377
- accounts,
2378
- createSessionParams.sessionProperties
2379
- );
2380
- console.log("\u{1F4DA} SDK connected");
2381
- return this.metamaskConnectMultichain.transport.request({
2382
- method: "wallet_getSession"
2383
- });
2384
- });
2385
- };
2386
- walletGetSession_fn = function(request) {
2387
- return __async(this, null, function* () {
2388
- if (!this.isTransportDefined()) {
2389
- return {
2390
- jsonrpc: "2.0",
2391
- id: request.id,
2392
- result: {
2393
- sessionScopes: {}
2394
- }
2395
- };
2396
- }
2397
- return this.metamaskConnectMultichain.transport.request({
2398
- method: "wallet_getSession"
2399
- });
2400
- });
2401
- };
2402
- walletRevokeSession_fn = function(request) {
2403
- return __async(this, null, function* () {
2404
- if (!this.isTransportDefined()) {
2405
- return { jsonrpc: "2.0", id: request.id, result: true };
2406
- }
2407
- try {
2408
- this.metamaskConnectMultichain.disconnect();
2409
- return { jsonrpc: "2.0", id: request.id, result: true };
2410
- } catch (error) {
2411
- return { jsonrpc: "2.0", id: request.id, result: false };
2412
- }
2413
- });
2414
- };
2415
- walletInvokeMethod_fn = function(request) {
2416
- return __async(this, null, function* () {
2417
- if (!this.isTransportDefined()) {
2418
- return { error: import_rpc_errors.providerErrors.unauthorized() };
2419
- }
2420
- const result = this.metamaskConnectMultichain.invokeMethod(
2421
- request.params
2422
- );
2423
- return {
2424
- result
2425
- };
2426
- });
2427
- };
2428
-
2429
- // src/multichain/index.ts
2659
+ init_utils2();
2430
2660
  var logger2 = createLogger("metamask-sdk:core");
2431
- 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;
2661
+ var SINGLETON_KEY = "__METAMASK_CONNECT_MULTICHAIN_SINGLETON__";
2662
+ 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;
2432
2663
  var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends MultichainCore {
2433
2664
  constructor(options) {
2434
- var _a2, _b, _c, _d, _e, _f;
2665
+ var _a3, _b, _c, _d, _e, _f;
2435
2666
  const withDappMetadata = setupDappMetadata(options);
2436
- const integrationType = (_b = (_a2 = options.analytics) == null ? void 0 : _a2.integrationType) != null ? _b : "direct";
2667
+ const integrationType = (_b = (_a3 = options.analytics) == null ? void 0 : _a3.integrationType) != null ? _b : "direct";
2437
2668
  const allOptions = __spreadProps(__spreadValues({}, withDappMetadata), {
2438
2669
  ui: __spreadProps(__spreadValues({}, withDappMetadata.ui), {
2439
2670
  preferExtension: (_c = withDappMetadata.ui.preferExtension) != null ? _c : true,
@@ -2453,17 +2684,21 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
2453
2684
  __privateAdd(this, _beforeUnloadListener);
2454
2685
  this._status = "pending";
2455
2686
  __privateAdd(this, _listener);
2456
- __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}`);
2457
- __privateSet(this, _providerTransportWrapper, new MultichainApiClientWrapperTransport(this));
2458
- __privateSet(this, _provider, (0, import_multichain_api_client3.getMultichainClient)({ transport: __privateGet(this, _providerTransportWrapper) }));
2687
+ __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}`);
2688
+ __privateSet(this, _providerTransportWrapper, new MultichainApiClientWrapperTransport(
2689
+ this
2690
+ ));
2691
+ __privateSet(this, _provider, (0, import_multichain_api_client3.getMultichainClient)({
2692
+ transport: __privateGet(this, _providerTransportWrapper)
2693
+ }));
2459
2694
  }
2460
2695
  get status() {
2461
2696
  return this._status;
2462
2697
  }
2463
2698
  set status(value) {
2464
- var _a2, _b;
2699
+ var _a3, _b;
2465
2700
  this._status = value;
2466
- (_b = (_a2 = this.options.transport) == null ? void 0 : _a2.onNotification) == null ? void 0 : _b.call(_a2, {
2701
+ (_b = (_a3 = this.options.transport) == null ? void 0 : _a3.onNotification) == null ? void 0 : _b.call(_a3, {
2467
2702
  method: "stateChanged",
2468
2703
  params: value
2469
2704
  });
@@ -2489,27 +2724,54 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
2489
2724
  get transportType() {
2490
2725
  return __privateGet(this, _transport2) instanceof MWPTransport ? "mwp" /* MWP */ : "browser" /* Browser */;
2491
2726
  }
2727
+ // Creates a singleton instance of MetaMaskConnectMultichain.
2728
+ // If the singleton already exists, it merges the incoming options with the
2729
+ // existing singleton options for the following keys: `api.supportedNetworks`,
2730
+ // `ui.*`, `mobile.*`, `transport.extensionId`, `debug`. Take note that the
2731
+ // value for `dapp` is not merged as it does not make sense for subsequent calls to
2732
+ // `createMultichainClient` to have a different `dapp` value.
2492
2733
  static create(options) {
2493
2734
  return __async(this, null, function* () {
2494
- var _a2;
2495
- const instance = new _MetaMaskConnectMultichain(options);
2496
- const isEnabled2 = yield isEnabled(
2497
- "metamask-sdk:core",
2498
- instance.options.storage
2499
- );
2500
- if (isEnabled2) {
2501
- enableDebug("metamask-sdk:core");
2502
- }
2503
- yield __privateMethod(_a2 = instance, _MetaMaskConnectMultichain_instances, init_fn).call(_a2);
2504
- return instance;
2735
+ const globalObject = getGlobalObject();
2736
+ const existing = globalObject[SINGLETON_KEY];
2737
+ if (existing) {
2738
+ const instance = yield existing;
2739
+ instance.mergeOptions(options);
2740
+ if (options.debug) {
2741
+ enableDebug("metamask-sdk:*");
2742
+ }
2743
+ return instance;
2744
+ }
2745
+ const instancePromise = (() => __async(null, null, function* () {
2746
+ var _a3;
2747
+ const instance = new _MetaMaskConnectMultichain(options);
2748
+ const isEnabled2 = yield isEnabled(
2749
+ "metamask-sdk:core",
2750
+ instance.options.storage
2751
+ );
2752
+ if (isEnabled2) {
2753
+ enableDebug("metamask-sdk:core");
2754
+ }
2755
+ yield __privateMethod(_a3 = instance, _MetaMaskConnectMultichain_instances, init_fn).call(_a3);
2756
+ return instance;
2757
+ }))();
2758
+ globalObject[SINGLETON_KEY] = instancePromise;
2759
+ instancePromise.catch((error) => {
2760
+ globalObject[SINGLETON_KEY] = void 0;
2761
+ console.error("Error initializing MetaMaskConnectMultichain", error);
2762
+ });
2763
+ return instancePromise;
2505
2764
  });
2506
2765
  }
2507
2766
  // TODO: make this into param object
2508
2767
  connect(scopes, caipAccountIds, sessionProperties, forceRequest) {
2509
2768
  return __async(this, null, function* () {
2510
- var _a2;
2511
- if (this.status !== "connected") {
2512
- yield this.disconnect();
2769
+ var _a3;
2770
+ if (this.status === "connecting" && this.transportType === "mwp" /* MWP */) {
2771
+ yield __privateMethod(this, _MetaMaskConnectMultichain_instances, openConnectDeeplinkIfNeeded_fn).call(this);
2772
+ throw new Error(
2773
+ "Existing connection is pending. Please check your MetaMask Mobile app to continue."
2774
+ );
2513
2775
  }
2514
2776
  const { ui } = this.options;
2515
2777
  const platformType = getPlatformType();
@@ -2539,9 +2801,21 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
2539
2801
  } catch (error) {
2540
2802
  logger2("Error tracking connection_initiated event", error);
2541
2803
  }
2542
- const nonEmptySessionProperites = Object.keys(sessionProperties != null ? sessionProperties : {}).length > 0 ? sessionProperties : void 0;
2543
- if (((_a2 = __privateGet(this, _transport2)) == null ? void 0 : _a2.isConnected()) && !secure) {
2544
- return __privateMethod(this, _MetaMaskConnectMultichain_instances, handleConnection_fn).call(this, __privateGet(this, _transport2).connect({ scopes, caipAccountIds, sessionProperties: nonEmptySessionProperites, forceRequest }).then(() => __async(this, null, function* () {
2804
+ const sessionData = yield __privateMethod(this, _MetaMaskConnectMultichain_instances, getCaipSession_fn).call(this);
2805
+ const { mergedScopes, mergedCaipAccountIds, mergedSessionProperties } = mergeRequestedSessionWithExisting(
2806
+ sessionData,
2807
+ scopes,
2808
+ caipAccountIds,
2809
+ sessionProperties
2810
+ );
2811
+ const nonEmptySessionProperties = Object.keys(mergedSessionProperties != null ? mergedSessionProperties : {}).length > 0 ? mergedSessionProperties : void 0;
2812
+ if (((_a3 = __privateGet(this, _transport2)) == null ? void 0 : _a3.isConnected()) && !secure) {
2813
+ return __privateMethod(this, _MetaMaskConnectMultichain_instances, handleConnection_fn).call(this, __privateGet(this, _transport2).connect({
2814
+ scopes: mergedScopes,
2815
+ caipAccountIds: mergedCaipAccountIds,
2816
+ sessionProperties: nonEmptySessionProperties,
2817
+ forceRequest
2818
+ }).then(() => __async(this, null, function* () {
2545
2819
  if (__privateGet(this, _transport2) instanceof MWPTransport) {
2546
2820
  return this.storage.setTransport("mwp" /* MWP */);
2547
2821
  }
@@ -2550,38 +2824,54 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
2550
2824
  }
2551
2825
  if (platformType === "in-app-browser" /* MetaMaskMobileWebview */) {
2552
2826
  const defaultTransport = yield __privateMethod(this, _MetaMaskConnectMultichain_instances, setupDefaultTransport_fn).call(this);
2553
- return __privateMethod(this, _MetaMaskConnectMultichain_instances, handleConnection_fn).call(this, defaultTransport.connect({ scopes, caipAccountIds, sessionProperties: nonEmptySessionProperites, forceRequest }), scopes, transportType);
2827
+ return __privateMethod(this, _MetaMaskConnectMultichain_instances, handleConnection_fn).call(this, defaultTransport.connect({
2828
+ scopes: mergedScopes,
2829
+ caipAccountIds: mergedCaipAccountIds,
2830
+ sessionProperties: nonEmptySessionProperties,
2831
+ forceRequest
2832
+ }), scopes, transportType);
2554
2833
  }
2555
2834
  if (isWeb && hasExtensionInstalled && preferExtension) {
2556
2835
  const defaultTransport = yield __privateMethod(this, _MetaMaskConnectMultichain_instances, setupDefaultTransport_fn).call(this);
2557
- return __privateMethod(this, _MetaMaskConnectMultichain_instances, handleConnection_fn).call(this, defaultTransport.connect({ scopes, caipAccountIds, sessionProperties: nonEmptySessionProperites, forceRequest }), scopes, transportType);
2836
+ return __privateMethod(this, _MetaMaskConnectMultichain_instances, handleConnection_fn).call(this, defaultTransport.connect({
2837
+ scopes: mergedScopes,
2838
+ caipAccountIds: mergedCaipAccountIds,
2839
+ sessionProperties: nonEmptySessionProperties,
2840
+ forceRequest
2841
+ }), scopes, transportType);
2558
2842
  }
2559
2843
  yield __privateMethod(this, _MetaMaskConnectMultichain_instances, setupMWP_fn).call(this);
2560
2844
  const shouldShowInstallModal = hasExtensionInstalled ? showInstallModal : !preferExtension || showInstallModal;
2561
2845
  if (secure && !shouldShowInstallModal) {
2562
- return __privateMethod(this, _MetaMaskConnectMultichain_instances, handleConnection_fn).call(this, __privateMethod(this, _MetaMaskConnectMultichain_instances, deeplinkConnect_fn).call(this, scopes, caipAccountIds, nonEmptySessionProperites), scopes, transportType);
2846
+ return __privateMethod(this, _MetaMaskConnectMultichain_instances, handleConnection_fn).call(this, __privateMethod(this, _MetaMaskConnectMultichain_instances, deeplinkConnect_fn).call(this, mergedScopes, mergedCaipAccountIds, nonEmptySessionProperties), scopes, transportType);
2563
2847
  }
2564
- return __privateMethod(this, _MetaMaskConnectMultichain_instances, handleConnection_fn).call(this, __privateMethod(this, _MetaMaskConnectMultichain_instances, showInstallModal_fn).call(this, shouldShowInstallModal, scopes, caipAccountIds, nonEmptySessionProperites), scopes, transportType);
2848
+ return __privateMethod(this, _MetaMaskConnectMultichain_instances, handleConnection_fn).call(this, __privateMethod(this, _MetaMaskConnectMultichain_instances, showInstallModal_fn).call(this, shouldShowInstallModal, mergedScopes, mergedCaipAccountIds, nonEmptySessionProperties), scopes, transportType);
2565
2849
  });
2566
2850
  }
2567
2851
  emit(event, args) {
2568
- var _a2, _b;
2569
- (_b = (_a2 = this.options.transport) == null ? void 0 : _a2.onNotification) == null ? void 0 : _b.call(_a2, { method: event, params: args });
2852
+ var _a3, _b;
2853
+ (_b = (_a3 = this.options.transport) == null ? void 0 : _a3.onNotification) == null ? void 0 : _b.call(_a3, { method: event, params: args });
2570
2854
  super.emit(event, args);
2571
2855
  }
2572
2856
  disconnect() {
2573
- return __async(this, null, function* () {
2574
- var _a2, _b, _c;
2575
- yield (_a2 = __privateGet(this, _listener)) == null ? void 0 : _a2.call(this);
2576
- (_b = __privateGet(this, _beforeUnloadListener)) == null ? void 0 : _b.call(this);
2577
- yield (_c = __privateGet(this, _transport2)) == null ? void 0 : _c.disconnect();
2578
- yield this.storage.removeTransport();
2579
- this.emit("stateChanged", "disconnected");
2580
- __privateSet(this, _listener, void 0);
2581
- __privateSet(this, _beforeUnloadListener, void 0);
2582
- __privateSet(this, _transport2, void 0);
2583
- __privateGet(this, _providerTransportWrapper).clearNotificationCallbacks();
2584
- __privateSet(this, _dappClient, void 0);
2857
+ return __async(this, arguments, function* (scopes = []) {
2858
+ var _a3, _b, _c;
2859
+ const sessionData = yield __privateMethod(this, _MetaMaskConnectMultichain_instances, getCaipSession_fn).call(this);
2860
+ const remainingScopes = scopes.length === 0 ? [] : Object.keys(sessionData.sessionScopes).filter(
2861
+ (scope) => !scopes.includes(scope)
2862
+ );
2863
+ yield (_a3 = __privateGet(this, _transport2)) == null ? void 0 : _a3.disconnect(scopes);
2864
+ if (remainingScopes.length === 0) {
2865
+ yield (_b = __privateGet(this, _listener)) == null ? void 0 : _b.call(this);
2866
+ (_c = __privateGet(this, _beforeUnloadListener)) == null ? void 0 : _c.call(this);
2867
+ yield this.storage.removeTransport();
2868
+ __privateSet(this, _listener, void 0);
2869
+ __privateSet(this, _beforeUnloadListener, void 0);
2870
+ __privateSet(this, _transport2, void 0);
2871
+ __privateGet(this, _providerTransportWrapper).clearTransportNotificationListener();
2872
+ __privateSet(this, _dappClient, void 0);
2873
+ this.status = "disconnected";
2874
+ }
2585
2875
  });
2586
2876
  }
2587
2877
  invokeMethod(request) {
@@ -2593,7 +2883,7 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
2593
2883
  });
2594
2884
  }
2595
2885
  // DRY THIS WITH REQUEST ROUTER
2596
- openDeeplinkIfNeeded() {
2886
+ openSimpleDeeplinkIfNeeded() {
2597
2887
  const { ui, mobile } = this.options;
2598
2888
  const { showInstallModal = false } = ui != null ? ui : {};
2599
2889
  const secure = isSecure();
@@ -2613,6 +2903,23 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
2613
2903
  }), 10);
2614
2904
  }
2615
2905
  }
2906
+ // Provides a way for ecosystem clients (EVM, Solana, etc.) to get the current CAIP session data
2907
+ // when instantiating themselves (as they would have already missed any initial sessionChanged events emitted by ConnectMultichain)
2908
+ // without having to concern themselves with the current transport connection status.
2909
+ emitSessionChanged() {
2910
+ return __async(this, null, function* () {
2911
+ var _a3;
2912
+ const emptySession = { sessionScopes: {} };
2913
+ if (this.status !== "connected" && this.status !== "connecting") {
2914
+ this.emit("wallet_sessionChanged", emptySession);
2915
+ return;
2916
+ }
2917
+ const response = yield this.transport.request({
2918
+ method: "wallet_getSession"
2919
+ });
2920
+ this.emit("wallet_sessionChanged", (_a3 = response.result) != null ? _a3 : emptySession);
2921
+ });
2922
+ }
2616
2923
  };
2617
2924
  _provider = new WeakMap();
2618
2925
  _providerTransportWrapper = new WeakMap();
@@ -2624,7 +2931,7 @@ _sdkInfo = new WeakMap();
2624
2931
  _MetaMaskConnectMultichain_instances = new WeakSet();
2625
2932
  setupAnalytics_fn = function() {
2626
2933
  return __async(this, null, function* () {
2627
- var _a2;
2934
+ var _a3;
2628
2935
  const platform = getPlatformType();
2629
2936
  const isBrowser = platform === "in-app-browser" /* MetaMaskMobileWebview */ || platform === "web-desktop" /* DesktopWeb */ || platform === "web-mobile" /* MobileWeb */;
2630
2937
  const isReactNative2 = platform === "react-native" /* ReactNative */;
@@ -2634,7 +2941,7 @@ setupAnalytics_fn = function() {
2634
2941
  const version = getVersion();
2635
2942
  const dappId = getDappId(this.options.dapp);
2636
2943
  const anonId = yield this.storage.getAnonId();
2637
- const { integrationType } = (_a2 = this.options.analytics) != null ? _a2 : {
2944
+ const { integrationType } = (_a3 = this.options.analytics) != null ? _a3 : {
2638
2945
  integrationType: ""
2639
2946
  };
2640
2947
  import_analytics4.analytics.setGlobalProperty("mmconnect_version", version);
@@ -2647,9 +2954,9 @@ setupAnalytics_fn = function() {
2647
2954
  };
2648
2955
  onTransportNotification_fn = function(payload) {
2649
2956
  return __async(this, null, function* () {
2650
- var _a2;
2957
+ var _a3;
2651
2958
  if (typeof payload === "object" && payload !== null && "method" in payload) {
2652
- this.emit(payload.method, (_a2 = payload.params) != null ? _a2 : payload.result);
2959
+ this.emit(payload.method, (_a3 = payload.params) != null ? _a3 : payload.result);
2653
2960
  }
2654
2961
  });
2655
2962
  };
@@ -2662,7 +2969,7 @@ getStoredTransport_fn = function() {
2662
2969
  if (hasExtensionInstalled) {
2663
2970
  const apiTransport = new DefaultTransport();
2664
2971
  __privateSet(this, _transport2, apiTransport);
2665
- __privateGet(this, _providerTransportWrapper).setupNotifcationListener();
2972
+ __privateGet(this, _providerTransportWrapper).setupTransportNotificationListener();
2666
2973
  __privateSet(this, _listener, apiTransport.onNotification(
2667
2974
  __privateMethod(this, _MetaMaskConnectMultichain_instances, onTransportNotification_fn).bind(this)
2668
2975
  ));
@@ -2674,7 +2981,7 @@ getStoredTransport_fn = function() {
2674
2981
  const apiTransport = new MWPTransport(dappClient, kvstore);
2675
2982
  __privateSet(this, _dappClient, dappClient);
2676
2983
  __privateSet(this, _transport2, apiTransport);
2677
- __privateGet(this, _providerTransportWrapper).setupNotifcationListener();
2984
+ __privateGet(this, _providerTransportWrapper).setupTransportNotificationListener();
2678
2985
  __privateSet(this, _listener, apiTransport.onNotification(
2679
2986
  __privateMethod(this, _MetaMaskConnectMultichain_instances, onTransportNotification_fn).bind(this)
2680
2987
  ));
@@ -2706,25 +3013,17 @@ setupTransport_fn = function() {
2706
3013
  };
2707
3014
  init_fn = function() {
2708
3015
  return __async(this, null, function* () {
2709
- var _a2;
2710
3016
  try {
2711
- if (typeof window !== "undefined" && ((_a2 = window.mmsdk) == null ? void 0 : _a2.isInitialized)) {
2712
- logger2("MetaMaskSDK: init already initialized");
2713
- } else {
2714
- yield __privateMethod(this, _MetaMaskConnectMultichain_instances, setupAnalytics_fn).call(this);
2715
- yield __privateMethod(this, _MetaMaskConnectMultichain_instances, setupTransport_fn).call(this);
2716
- try {
2717
- const baseProps = yield getBaseAnalyticsProperties(
2718
- this.options,
2719
- this.storage
2720
- );
2721
- import_analytics4.analytics.track("mmconnect_initialized", baseProps);
2722
- } catch (error) {
2723
- logger2("Error tracking initialized event", error);
2724
- }
2725
- if (typeof window !== "undefined") {
2726
- window.mmsdk = this;
2727
- }
3017
+ yield __privateMethod(this, _MetaMaskConnectMultichain_instances, setupAnalytics_fn).call(this);
3018
+ yield __privateMethod(this, _MetaMaskConnectMultichain_instances, setupTransport_fn).call(this);
3019
+ try {
3020
+ const baseProps = yield getBaseAnalyticsProperties(
3021
+ this.options,
3022
+ this.storage
3023
+ );
3024
+ import_analytics4.analytics.track("mmconnect_initialized", baseProps);
3025
+ } catch (error) {
3026
+ logger2("Error tracking initialized event", error);
2728
3027
  }
2729
3028
  } catch (error) {
2730
3029
  yield this.storage.removeTransport();
@@ -2760,7 +3059,7 @@ setupMWP_fn = function() {
2760
3059
  __privateSet(this, _dappClient, dappClient);
2761
3060
  const apiTransport = new MWPTransport(dappClient, kvstore);
2762
3061
  __privateSet(this, _transport2, apiTransport);
2763
- __privateGet(this, _providerTransportWrapper).setupNotifcationListener();
3062
+ __privateGet(this, _providerTransportWrapper).setupTransportNotificationListener();
2764
3063
  __privateSet(this, _listener, this.transport.onNotification(
2765
3064
  __privateMethod(this, _MetaMaskConnectMultichain_instances, onTransportNotification_fn).bind(this)
2766
3065
  ));
@@ -2769,22 +3068,20 @@ setupMWP_fn = function() {
2769
3068
  };
2770
3069
  onBeforeUnload_fn = function() {
2771
3070
  return __async(this, null, function* () {
2772
- var _a2;
2773
- if ((_a2 = this.options.ui.factory.modal) == null ? void 0 : _a2.isMounted) {
3071
+ var _a3;
3072
+ if ((_a3 = this.options.ui.factory.modal) == null ? void 0 : _a3.isMounted) {
2774
3073
  yield this.storage.removeTransport();
2775
3074
  }
2776
3075
  });
2777
3076
  };
2778
3077
  createBeforeUnloadListener_fn = function() {
3078
+ const handler = __privateMethod(this, _MetaMaskConnectMultichain_instances, onBeforeUnload_fn).bind(this);
2779
3079
  if (typeof window !== "undefined" && typeof window.addEventListener !== "undefined") {
2780
- window.addEventListener("beforeunload", __privateMethod(this, _MetaMaskConnectMultichain_instances, onBeforeUnload_fn).bind(this));
3080
+ window.addEventListener("beforeunload", handler);
2781
3081
  }
2782
3082
  return () => {
2783
3083
  if (typeof window !== "undefined" && typeof window.removeEventListener !== "undefined") {
2784
- window.removeEventListener(
2785
- "beforeunload",
2786
- __privateMethod(this, _MetaMaskConnectMultichain_instances, onBeforeUnload_fn).bind(this)
2787
- );
3084
+ window.removeEventListener("beforeunload", handler);
2788
3085
  }
2789
3086
  };
2790
3087
  };
@@ -2814,24 +3111,29 @@ renderInstallModalAsync_fn = function(desktopPreferred, scopes, caipAccountIds,
2814
3111
  }
2815
3112
  );
2816
3113
  (() => __async(this, null, function* () {
2817
- var _a2;
3114
+ var _a3;
2818
3115
  try {
2819
- yield this.transport.connect({ scopes, caipAccountIds, sessionProperties });
3116
+ yield this.transport.connect({
3117
+ scopes,
3118
+ caipAccountIds,
3119
+ sessionProperties
3120
+ });
2820
3121
  yield this.options.ui.factory.unload();
2821
- (_a2 = this.options.ui.factory.modal) == null ? void 0 : _a2.unmount();
3122
+ (_a3 = this.options.ui.factory.modal) == null ? void 0 : _a3.unmount();
2822
3123
  this.status = "connected";
2823
3124
  yield this.storage.setTransport("mwp" /* MWP */);
2824
3125
  } catch (error) {
2825
3126
  if (error instanceof import_mobile_wallet_protocol_core2.ProtocolError) {
2826
3127
  if (error.code !== import_mobile_wallet_protocol_core2.ErrorCode.REQUEST_EXPIRED) {
2827
3128
  this.status = "disconnected";
3129
+ yield this.options.ui.factory.unload(error);
2828
3130
  reject(error);
2829
3131
  }
2830
3132
  } else {
2831
3133
  this.status = "disconnected";
2832
- reject(
2833
- error instanceof Error ? error : new Error(String(error))
2834
- );
3134
+ const normalizedError = error instanceof Error ? error : new Error(String(error));
3135
+ yield this.options.ui.factory.unload(normalizedError);
3136
+ reject(normalizedError);
2835
3137
  }
2836
3138
  }
2837
3139
  }))().catch(() => {
@@ -2858,8 +3160,8 @@ renderInstallModalAsync_fn = function(desktopPreferred, scopes, caipAccountIds,
2858
3160
  };
2859
3161
  showInstallModal_fn = function(desktopPreferred, scopes, caipAccountIds, sessionProperties) {
2860
3162
  return __async(this, null, function* () {
2861
- var _a2;
2862
- (_a2 = __privateGet(this, _beforeUnloadListener)) != null ? _a2 : __privateSet(this, _beforeUnloadListener, __privateMethod(this, _MetaMaskConnectMultichain_instances, createBeforeUnloadListener_fn).call(this));
3163
+ var _a3;
3164
+ (_a3 = __privateGet(this, _beforeUnloadListener)) != null ? _a3 : __privateSet(this, _beforeUnloadListener, __privateMethod(this, _MetaMaskConnectMultichain_instances, createBeforeUnloadListener_fn).call(this));
2863
3165
  if (this.options.ui.headless) {
2864
3166
  yield __privateMethod(this, _MetaMaskConnectMultichain_instances, headlessConnect_fn).call(this, scopes, caipAccountIds, sessionProperties);
2865
3167
  } else {
@@ -2918,15 +3220,15 @@ setupDefaultTransport_fn = function() {
2918
3220
  __privateMethod(this, _MetaMaskConnectMultichain_instances, onTransportNotification_fn).bind(this)
2919
3221
  ));
2920
3222
  __privateSet(this, _transport2, transport);
2921
- __privateGet(this, _providerTransportWrapper).setupNotifcationListener();
3223
+ __privateGet(this, _providerTransportWrapper).setupTransportNotificationListener();
2922
3224
  return transport;
2923
3225
  });
2924
3226
  };
2925
3227
  deeplinkConnect_fn = function(scopes, caipAccountIds, sessionProperties) {
2926
3228
  return __async(this, null, function* () {
2927
- return new Promise((resolve, reject) => {
3229
+ return new Promise((resolve, reject) => __async(this, null, function* () {
2928
3230
  const dappClientMessageHandler = (payload) => {
2929
- var _a2;
3231
+ var _a3;
2930
3232
  if (typeof payload !== "object" || payload === null || !("data" in payload)) {
2931
3233
  return;
2932
3234
  }
@@ -2936,7 +3238,7 @@ deeplinkConnect_fn = function(scopes, caipAccountIds, sessionProperties) {
2936
3238
  this.dappClient.off("message", dappClientMessageHandler);
2937
3239
  reject(data.error);
2938
3240
  }
2939
- if ((_a2 = data == null ? void 0 : data.result) == null ? void 0 : _a2.sessionScopes) {
3241
+ if ((_a3 = data == null ? void 0 : data.result) == null ? void 0 : _a3.sessionScopes) {
2940
3242
  this.dappClient.off("message", dappClientMessageHandler);
2941
3243
  }
2942
3244
  }
@@ -2945,13 +3247,13 @@ deeplinkConnect_fn = function(scopes, caipAccountIds, sessionProperties) {
2945
3247
  let timeout;
2946
3248
  if (this.transport.isConnected()) {
2947
3249
  timeout = setTimeout(() => {
2948
- this.openDeeplinkIfNeeded();
3250
+ this.openSimpleDeeplinkIfNeeded();
2949
3251
  }, 250);
2950
3252
  } else {
2951
3253
  this.dappClient.once(
2952
3254
  "session_request",
2953
3255
  (sessionRequest) => {
2954
- var _a2;
3256
+ var _a3;
2955
3257
  const connectionRequest = {
2956
3258
  sessionRequest,
2957
3259
  metadata: {
@@ -2966,7 +3268,7 @@ deeplinkConnect_fn = function(scopes, caipAccountIds, sessionProperties) {
2966
3268
  connectionRequest
2967
3269
  );
2968
3270
  this.emit("display_uri", deeplink);
2969
- if ((_a2 = this.options.mobile) == null ? void 0 : _a2.preferredOpenLink) {
3271
+ if ((_a3 = this.options.mobile) == null ? void 0 : _a3.preferredOpenLink) {
2970
3272
  this.options.mobile.preferredOpenLink(deeplink, "_self");
2971
3273
  } else {
2972
3274
  openDeeplink(this.options, deeplink, universalLink);
@@ -2983,7 +3285,7 @@ deeplinkConnect_fn = function(scopes, caipAccountIds, sessionProperties) {
2983
3285
  clearTimeout(timeout);
2984
3286
  }
2985
3287
  });
2986
- });
3288
+ }));
2987
3289
  });
2988
3290
  };
2989
3291
  handleConnection_fn = function(promise, scopes, transportType) {
@@ -3028,6 +3330,53 @@ handleConnection_fn = function(promise, scopes, transportType) {
3028
3330
  }));
3029
3331
  });
3030
3332
  };
3333
+ getCaipSession_fn = function() {
3334
+ return __async(this, null, function* () {
3335
+ let sessionData = {
3336
+ sessionScopes: {},
3337
+ sessionProperties: {}
3338
+ };
3339
+ if (this.status === "connected") {
3340
+ const response = yield this.transport.request({
3341
+ method: "wallet_getSession"
3342
+ });
3343
+ if (response.result) {
3344
+ sessionData = response.result;
3345
+ }
3346
+ }
3347
+ return sessionData;
3348
+ });
3349
+ };
3350
+ openConnectDeeplinkIfNeeded_fn = function() {
3351
+ return __async(this, null, function* () {
3352
+ var _a3, _b;
3353
+ const { ui } = this.options;
3354
+ const { showInstallModal = false } = ui != null ? ui : {};
3355
+ const secure = isSecure();
3356
+ const shouldOpenDeeplink = secure && !showInstallModal;
3357
+ if (!shouldOpenDeeplink) {
3358
+ return;
3359
+ }
3360
+ const storedSessionRequest = yield (_a3 = __privateGet(this, _transport2)) == null ? void 0 : _a3.getStoredPendingSessionRequest();
3361
+ if (!storedSessionRequest) {
3362
+ return;
3363
+ }
3364
+ const connectionRequest = {
3365
+ sessionRequest: storedSessionRequest,
3366
+ metadata: {
3367
+ dapp: this.options.dapp,
3368
+ sdk: { version: getVersion(), platform: getPlatformType() }
3369
+ }
3370
+ };
3371
+ const deeplink = this.options.ui.factory.createConnectionDeeplink(connectionRequest);
3372
+ const universalLink = this.options.ui.factory.createConnectionUniversalLink(connectionRequest);
3373
+ if ((_b = this.options.mobile) == null ? void 0 : _b.preferredOpenLink) {
3374
+ this.options.mobile.preferredOpenLink(deeplink, "_self");
3375
+ } else {
3376
+ openDeeplink(this.options, deeplink, universalLink);
3377
+ }
3378
+ });
3379
+ };
3031
3380
  var MetaMaskConnectMultichain = _MetaMaskConnectMultichain;
3032
3381
 
3033
3382
  // src/store/index.ts
@@ -3212,7 +3561,7 @@ var Store = class extends StoreClient {
3212
3561
  // src/ui/ModalFactory.ts
3213
3562
  var import_onboarding = __toESM(require("@metamask/onboarding"));
3214
3563
  init_domain();
3215
- init_utils();
3564
+ init_utils2();
3216
3565
  var BaseModalFactory = class {
3217
3566
  /**
3218
3567
  * Creates a new modal factory instance.
@@ -3235,8 +3584,8 @@ var BaseModalFactory = class {
3235
3584
  }
3236
3585
  unload(error) {
3237
3586
  return __async(this, null, function* () {
3238
- var _a2, _b;
3239
- (_a2 = this.modal) == null ? void 0 : _a2.unmount();
3587
+ var _a3, _b;
3588
+ (_a3 = this.modal) == null ? void 0 : _a3.unmount();
3240
3589
  yield (_b = this.successCallback) == null ? void 0 : _b.call(this, error);
3241
3590
  });
3242
3591
  }
@@ -3276,7 +3625,9 @@ var BaseModalFactory = class {
3276
3625
  }
3277
3626
  createConnectionDeeplink(connectionRequest) {
3278
3627
  if (!connectionRequest) {
3279
- throw new Error("createConnectionDeeplink can only be called with a connection request");
3628
+ throw new Error(
3629
+ "createConnectionDeeplink can only be called with a connection request"
3630
+ );
3280
3631
  }
3281
3632
  const json = JSON.stringify(connectionRequest);
3282
3633
  const compressed = compressString(json);
@@ -3304,8 +3655,8 @@ var BaseModalFactory = class {
3304
3655
  }
3305
3656
  renderInstallModal(showInstallModal, createConnectionRequest, successCallback, onDisplayUri) {
3306
3657
  return __async(this, null, function* () {
3307
- var _a2, _b;
3308
- (_a2 = this.modal) == null ? void 0 : _a2.unmount();
3658
+ var _a3, _b;
3659
+ (_a3 = this.modal) == null ? void 0 : _a3.unmount();
3309
3660
  yield this.preload();
3310
3661
  this.successCallback = successCallback;
3311
3662
  this.displayUriCallback = onDisplayUri;
@@ -3321,9 +3672,9 @@ var BaseModalFactory = class {
3321
3672
  link: qrCodeLink,
3322
3673
  sdkVersion: getVersion(),
3323
3674
  generateQRCode: (request) => __async(this, null, function* () {
3324
- var _a3;
3675
+ var _a4;
3325
3676
  const newLink = this.createConnectionDeeplink(request);
3326
- (_a3 = this.displayUriCallback) == null ? void 0 : _a3.call(this, newLink);
3677
+ (_a4 = this.displayUriCallback) == null ? void 0 : _a4.call(this, newLink);
3327
3678
  return newLink;
3328
3679
  }),
3329
3680
  onClose: this.onCloseModal.bind(this),
@@ -3337,8 +3688,8 @@ var BaseModalFactory = class {
3337
3688
  }
3338
3689
  renderOTPCodeModal(createOTPCode, successCallback, updateOTPCode) {
3339
3690
  return __async(this, null, function* () {
3340
- var _a2;
3341
- (_a2 = this.modal) == null ? void 0 : _a2.unmount();
3691
+ var _a3;
3692
+ (_a3 = this.modal) == null ? void 0 : _a3.unmount();
3342
3693
  yield this.preload();
3343
3694
  this.successCallback = successCallback;
3344
3695
  const container = this.getMountedContainer();
@@ -3382,14 +3733,17 @@ var ModalFactory = class extends BaseModalFactory {
3382
3733
  // src/index.browser.ts
3383
3734
  init_domain();
3384
3735
  var createMultichainClient = (options) => __async(null, null, function* () {
3736
+ if (options.debug) {
3737
+ enableDebug("metamask-sdk:*");
3738
+ }
3385
3739
  const uiModules = yield Promise.resolve().then(() => (init_web(), web_exports));
3386
3740
  let storage;
3387
- if (!options.storage) {
3741
+ if (options.storage) {
3742
+ storage = options.storage;
3743
+ } else {
3388
3744
  const { StoreAdapterWeb: StoreAdapterWeb2 } = yield Promise.resolve().then(() => (init_web2(), web_exports2));
3389
3745
  const adapter = new StoreAdapterWeb2();
3390
3746
  storage = new Store(adapter);
3391
- } else {
3392
- storage = options.storage;
3393
3747
  }
3394
3748
  const factory = new ModalFactory(uiModules);
3395
3749
  return MetaMaskConnectMultichain.create(__spreadProps(__spreadValues({}, options), {