@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
@@ -235,8 +235,8 @@ var init_logger = __esm({
235
235
  debug.enable(namespace);
236
236
  };
237
237
  isEnabled = (namespace, storage) => __async(null, null, function* () {
238
- var _a2;
239
- if ("process" in globalThis && ((_a2 = process == null ? void 0 : process.env) == null ? void 0 : _a2.DEBUG)) {
238
+ var _a3;
239
+ if ("process" in globalThis && ((_a3 = process == null ? void 0 : process.env) == null ? void 0 : _a3.DEBUG)) {
240
240
  const { DEBUG } = process.env;
241
241
  return isNamespaceEnabled(DEBUG, namespace);
242
242
  }
@@ -399,6 +399,34 @@ var init_multichain = __esm({
399
399
  super();
400
400
  this.options = options;
401
401
  }
402
+ /**
403
+ * Merges the given options into the current instance options.
404
+ * Only the mergeable keys are updated (api.supportedNetworks, ui.*, mobile.*, transport.extensionId, debug).
405
+ * The main thing to note is that the value for `dapp` is not merged as it does not make sense for
406
+ * subsequent calls to `createMultichainClient` to have a different `dapp` value.
407
+ * Used when createMultichainClient is called with an existing singleton.
408
+ *
409
+ * @param partial - Options to merge/overwrite onto the current instance
410
+ */
411
+ mergeOptions(partial) {
412
+ var _a3, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n;
413
+ const opts = this.options;
414
+ this.options = __spreadProps(__spreadValues({}, opts), {
415
+ api: __spreadProps(__spreadValues({}, opts.api), {
416
+ supportedNetworks: __spreadValues(__spreadValues({}, opts.api.supportedNetworks), (_b = (_a3 = partial.api) == null ? void 0 : _a3.supportedNetworks) != null ? _b : {})
417
+ }),
418
+ ui: __spreadProps(__spreadValues({}, opts.ui), {
419
+ headless: (_d = (_c = partial.ui) == null ? void 0 : _c.headless) != null ? _d : opts.ui.headless,
420
+ preferExtension: (_f = (_e = partial.ui) == null ? void 0 : _e.preferExtension) != null ? _f : opts.ui.preferExtension,
421
+ showInstallModal: (_h = (_g = partial.ui) == null ? void 0 : _g.showInstallModal) != null ? _h : opts.ui.showInstallModal
422
+ }),
423
+ mobile: __spreadValues(__spreadValues({}, opts.mobile), (_i = partial.mobile) != null ? _i : {}),
424
+ transport: __spreadProps(__spreadValues({}, (_j = opts.transport) != null ? _j : {}), {
425
+ extensionId: (_m = (_k = partial.transport) == null ? void 0 : _k.extensionId) != null ? _m : (_l = opts.transport) == null ? void 0 : _l.extensionId
426
+ }),
427
+ debug: (_n = partial.debug) != null ? _n : opts.debug
428
+ });
429
+ }
402
430
  };
403
431
  }
404
432
  });
@@ -406,35 +434,35 @@ var init_multichain = __esm({
406
434
  // src/domain/platform/index.ts
407
435
  import Bowser from "bowser";
408
436
  function isNotBrowser() {
409
- var _a2;
437
+ var _a3;
410
438
  if (typeof window === "undefined") {
411
439
  return true;
412
440
  }
413
441
  if (!(window == null ? void 0 : window.navigator)) {
414
442
  return true;
415
443
  }
416
- if (typeof global !== "undefined" && ((_a2 = global == null ? void 0 : global.navigator) == null ? void 0 : _a2.product) === "ReactNative") {
444
+ if (typeof global !== "undefined" && ((_a3 = global == null ? void 0 : global.navigator) == null ? void 0 : _a3.product) === "ReactNative") {
417
445
  return true;
418
446
  }
419
447
  return (navigator == null ? void 0 : navigator.product) === "ReactNative";
420
448
  }
421
449
  function isReactNative() {
422
- var _a2;
450
+ var _a3;
423
451
  const hasWindowNavigator = typeof window !== "undefined" && window.navigator !== void 0;
424
452
  const nav = hasWindowNavigator ? window.navigator : void 0;
425
453
  if (!nav) {
426
454
  return false;
427
455
  }
428
- return hasWindowNavigator && ((_a2 = window.navigator) == null ? void 0 : _a2.product) === "ReactNative";
456
+ return hasWindowNavigator && ((_a3 = window.navigator) == null ? void 0 : _a3.product) === "ReactNative";
429
457
  }
430
458
  function isMetaMaskMobileWebView() {
431
459
  return typeof window !== "undefined" && // @ts-expect-error ReactNativeWebView should be defined
432
460
  Boolean(window.ReactNativeWebView) && Boolean(window.navigator.userAgent.endsWith("MetaMaskMobile"));
433
461
  }
434
462
  function isMobile() {
435
- var _a2, _b;
463
+ var _a3, _b;
436
464
  const browser = Bowser.parse(window.navigator.userAgent);
437
- return ((_a2 = browser == null ? void 0 : browser.platform) == null ? void 0 : _a2.type) === "mobile" || ((_b = browser == null ? void 0 : browser.platform) == null ? void 0 : _b.type) === "tablet";
465
+ return ((_a3 = browser == null ? void 0 : browser.platform) == null ? void 0 : _a3.type) === "mobile" || ((_b = browser == null ? void 0 : browser.platform) == null ? void 0 : _b.type) === "tablet";
438
466
  }
439
467
  function getPlatformType() {
440
468
  if (isReactNative()) {
@@ -452,11 +480,11 @@ function getPlatformType() {
452
480
  return "web-desktop" /* DesktopWeb */;
453
481
  }
454
482
  function isMetamaskExtensionInstalled() {
455
- var _a2;
483
+ var _a3;
456
484
  if (typeof window === "undefined") {
457
485
  return false;
458
486
  }
459
- return Boolean((_a2 = window.ethereum) == null ? void 0 : _a2.isMetaMask);
487
+ return Boolean((_a3 = window.ethereum) == null ? void 0 : _a3.isMetaMask);
460
488
  }
461
489
  function isSecure() {
462
490
  const platformType = getPlatformType();
@@ -487,8 +515,8 @@ var init_platform = __esm({
487
515
  return new Promise((resolve) => {
488
516
  const providers = [];
489
517
  const handler = (event) => {
490
- var _a2, _b;
491
- if ((_b = (_a2 = event == null ? void 0 : event.detail) == null ? void 0 : _a2.info) == null ? void 0 : _b.rdns) {
518
+ var _a3, _b;
519
+ if ((_b = (_a3 = event == null ? void 0 : event.detail) == null ? void 0 : _a3.info) == null ? void 0 : _b.rdns) {
492
520
  providers.push(event.detail);
493
521
  }
494
522
  };
@@ -498,8 +526,8 @@ var init_platform = __esm({
498
526
  window.removeEventListener("eip6963:announceProvider", handler);
499
527
  const hasMetaMask = providers.some(
500
528
  (provider) => {
501
- var _a2, _b;
502
- return (_b = (_a2 = provider == null ? void 0 : provider.info) == null ? void 0 : _a2.rdns) == null ? void 0 : _b.startsWith("io.metamask");
529
+ var _a3, _b;
530
+ return (_b = (_a3 = provider == null ? void 0 : provider.info) == null ? void 0 : _a3.rdns) == null ? void 0 : _b.startsWith("io.metamask");
503
531
  }
504
532
  );
505
533
  resolve(hasMetaMask);
@@ -583,12 +611,108 @@ var init_ui = __esm({
583
611
  }
584
612
  });
585
613
 
614
+ // src/multichain/utils/analytics.ts
615
+ function isRejectionError(error) {
616
+ var _a3, _b;
617
+ if (typeof error !== "object" || error === null) {
618
+ return false;
619
+ }
620
+ const errorObj = error;
621
+ const errorCode = errorObj.code;
622
+ const errorMessage = (_b = (_a3 = errorObj.message) == null ? void 0 : _a3.toLowerCase()) != null ? _b : "";
623
+ return errorCode === 4001 || // User rejected request (common EIP-1193 code)
624
+ errorCode === 4100 || // Unauthorized (common rejection code)
625
+ errorMessage.includes("reject") || errorMessage.includes("denied") || errorMessage.includes("cancel") || errorMessage.includes("user");
626
+ }
627
+ function getBaseAnalyticsProperties(options, storage) {
628
+ return __async(this, null, function* () {
629
+ var _a3, _b;
630
+ const version = getVersion();
631
+ const dappId = getDappId(options.dapp);
632
+ const platform = getPlatformType();
633
+ const anonId = yield storage.getAnonId();
634
+ const integrationType = (_b = (_a3 = options.analytics) == null ? void 0 : _a3.integrationType) != null ? _b : "unknown" /* UNKNOWN */;
635
+ return {
636
+ mmconnect_version: version,
637
+ dapp_id: dappId,
638
+ platform,
639
+ integration_type: integrationType,
640
+ anon_id: anonId
641
+ };
642
+ });
643
+ }
644
+ function getWalletActionAnalyticsProperties(options, storage, invokeOptions) {
645
+ return __async(this, null, function* () {
646
+ var _a3, _b;
647
+ const version = getVersion();
648
+ const dappId = getDappId(options.dapp);
649
+ const anonId = yield storage.getAnonId();
650
+ const integrationType = (_b = (_a3 = options.analytics) == null ? void 0 : _a3.integrationType) != null ? _b : "unknown";
651
+ return {
652
+ mmconnect_version: version,
653
+ dapp_id: dappId,
654
+ method: invokeOptions.request.method,
655
+ integration_type: integrationType,
656
+ caip_chain_id: invokeOptions.scope,
657
+ anon_id: anonId
658
+ };
659
+ });
660
+ }
661
+ var init_analytics = __esm({
662
+ "src/multichain/utils/analytics.ts"() {
663
+ "use strict";
664
+ init_utils2();
665
+ init_domain();
666
+ }
667
+ });
668
+
669
+ // src/domain/utils/index.ts
670
+ function getVersion() {
671
+ return "0.0.0";
672
+ }
673
+ var init_utils = __esm({
674
+ "src/domain/utils/index.ts"() {
675
+ "use strict";
676
+ init_analytics();
677
+ }
678
+ });
679
+
680
+ // src/domain/index.ts
681
+ var init_domain = __esm({
682
+ "src/domain/index.ts"() {
683
+ "use strict";
684
+ init_errors();
685
+ init_events();
686
+ init_logger();
687
+ init_multichain();
688
+ init_platform();
689
+ init_store();
690
+ init_ui();
691
+ init_utils();
692
+ }
693
+ });
694
+
586
695
  // src/multichain/utils/index.ts
587
- import { deflate } from "pako";
588
696
  import {
589
697
  parseCaipAccountId,
590
698
  parseCaipChainId
591
699
  } from "@metamask/utils";
700
+ import { deflate } from "pako";
701
+ function getGlobalObject() {
702
+ if (typeof globalThis !== "undefined") {
703
+ return globalThis;
704
+ }
705
+ if (typeof global !== "undefined") {
706
+ return global;
707
+ }
708
+ if (typeof self !== "undefined") {
709
+ return self;
710
+ }
711
+ if (typeof window !== "undefined") {
712
+ return window;
713
+ }
714
+ throw new Error("Unable to locate global object");
715
+ }
592
716
  function base64Encode(str) {
593
717
  if (typeof btoa !== "undefined") {
594
718
  return btoa(str);
@@ -603,12 +727,13 @@ function compressString(str) {
603
727
  return base64Encode(binaryString);
604
728
  }
605
729
  function getDappId(dapp) {
606
- var _a2;
607
- return (_a2 = dapp.url) != null ? _a2 : dapp.name;
730
+ var _a3;
731
+ return (_a3 = dapp.url) != null ? _a3 : dapp.name;
608
732
  }
609
733
  function openDeeplink(options, deeplink, universalLink) {
734
+ var _a3;
610
735
  const { mobile } = options;
611
- const useDeeplink = mobile && mobile.useDeeplink !== void 0 ? mobile.useDeeplink : true;
736
+ const useDeeplink = (_a3 = mobile == null ? void 0 : mobile.useDeeplink) != null ? _a3 : true;
612
737
  if (useDeeplink) {
613
738
  if (typeof window !== "undefined") {
614
739
  window.location.href = deeplink;
@@ -621,6 +746,29 @@ function openDeeplink(options, deeplink, universalLink) {
621
746
  link.click();
622
747
  }
623
748
  }
749
+ function mergeRequestedSessionWithExisting(sessionData, scopes, caipAccountIds, sessionProperties) {
750
+ const existingCaipChainIds = Object.keys(sessionData.sessionScopes);
751
+ const existingCaipAccountIds = [];
752
+ Object.values(sessionData.sessionScopes).forEach((scopeObject) => {
753
+ if ((scopeObject == null ? void 0 : scopeObject.accounts) && Array.isArray(scopeObject.accounts)) {
754
+ scopeObject.accounts.forEach((account) => {
755
+ existingCaipAccountIds.push(account);
756
+ });
757
+ }
758
+ });
759
+ const mergedScopes = Array.from(
760
+ /* @__PURE__ */ new Set([...existingCaipChainIds, ...scopes])
761
+ );
762
+ const mergedCaipAccountIds = Array.from(
763
+ /* @__PURE__ */ new Set([...existingCaipAccountIds, ...caipAccountIds])
764
+ );
765
+ const mergedSessionProperties = __spreadValues(__spreadValues({}, sessionData.sessionProperties), sessionProperties);
766
+ return {
767
+ mergedScopes,
768
+ mergedCaipAccountIds,
769
+ mergedSessionProperties
770
+ };
771
+ }
624
772
  function getOptionalScopes(scopes) {
625
773
  return scopes.reduce(
626
774
  (prev, scope) => __spreadProps(__spreadValues({}, prev), {
@@ -634,10 +782,10 @@ function getOptionalScopes(scopes) {
634
782
  );
635
783
  }
636
784
  function setupDappMetadata(options) {
637
- var _a2, _b;
785
+ var _a3, _b;
638
786
  const platform = getPlatformType();
639
787
  const isBrowser = platform === "web-desktop" /* DesktopWeb */ || platform === "web-mobile" /* MobileWeb */ || platform === "in-app-browser" /* MetaMaskMobileWebview */;
640
- if (!((_a2 = options.dapp) == null ? void 0 : _a2.name)) {
788
+ if (!((_a3 = options.dapp) == null ? void 0 : _a3.name)) {
641
789
  throw new Error("You must provide dapp name");
642
790
  }
643
791
  if (isBrowser) {
@@ -649,7 +797,7 @@ function setupDappMetadata(options) {
649
797
  throw new Error("You must provide dapp url");
650
798
  }
651
799
  const BASE_64_ICON_MAX_LENGTH = 163400;
652
- const urlPattern = /^(http|https):\/\/[^\s]*$/;
800
+ const urlPattern = /^(http|https):\/\/[^\s]*$/u;
653
801
  if (options.dapp) {
654
802
  if ("iconUrl" in options.dapp) {
655
803
  if (options.dapp.iconUrl && !urlPattern.test(options.dapp.iconUrl)) {
@@ -698,9 +846,12 @@ function getValidAccounts(caipAccountIds) {
698
846
  (caipAccounts, caipAccountId) => {
699
847
  try {
700
848
  return [...caipAccounts, parseCaipAccountId(caipAccountId)];
701
- } catch (err) {
849
+ } catch (error) {
702
850
  const stringifiedAccountId = JSON.stringify(caipAccountId);
703
- console.error(`Invalid CAIP account ID: ${stringifiedAccountId}`, err);
851
+ console.error(
852
+ `Invalid CAIP account ID: ${stringifiedAccountId}`,
853
+ error
854
+ );
704
855
  return caipAccounts;
705
856
  }
706
857
  },
@@ -708,17 +859,17 @@ function getValidAccounts(caipAccountIds) {
708
859
  );
709
860
  }
710
861
  function addValidAccounts(optionalScopes, validAccounts) {
711
- var _a2;
862
+ var _a3;
712
863
  if (!optionalScopes || !(validAccounts == null ? void 0 : validAccounts.length)) {
713
864
  return optionalScopes;
714
865
  }
715
866
  const result = Object.fromEntries(
716
867
  Object.entries(optionalScopes).map(([scope, scopeData]) => {
717
- var _a3, _b, _c;
868
+ var _a4, _b, _c;
718
869
  return [
719
870
  scope,
720
871
  {
721
- methods: [...(_a3 = scopeData == null ? void 0 : scopeData.methods) != null ? _a3 : []],
872
+ methods: [...(_a4 = scopeData == null ? void 0 : scopeData.methods) != null ? _a4 : []],
722
873
  notifications: [...(_b = scopeData == null ? void 0 : scopeData.notifications) != null ? _b : []],
723
874
  accounts: [...(_c = scopeData == null ? void 0 : scopeData.accounts) != null ? _c : []]
724
875
  }
@@ -732,7 +883,7 @@ function addValidAccounts(optionalScopes, validAccounts) {
732
883
  if (!accountsByChain.has(chainKey)) {
733
884
  accountsByChain.set(chainKey, []);
734
885
  }
735
- (_a2 = accountsByChain.get(chainKey)) == null ? void 0 : _a2.push(accountId);
886
+ (_a3 = accountsByChain.get(chainKey)) == null ? void 0 : _a3.push(accountId);
736
887
  }
737
888
  for (const [scopeKey, scopeData] of Object.entries(result)) {
738
889
  if (!(scopeData == null ? void 0 : scopeData.accounts)) {
@@ -756,13 +907,13 @@ function addValidAccounts(optionalScopes, validAccounts) {
756
907
  }
757
908
  return result;
758
909
  }
759
- var extractFavicon;
760
- var init_utils = __esm({
910
+ var extractFavicon, MAX, idCounter, getUniqueRequestId;
911
+ var init_utils2 = __esm({
761
912
  "src/multichain/utils/index.ts"() {
762
913
  "use strict";
763
914
  init_domain();
764
915
  extractFavicon = () => {
765
- var _a2;
916
+ var _a3;
766
917
  if (typeof document === "undefined") {
767
918
  return void 0;
768
919
  }
@@ -770,98 +921,25 @@ var init_utils = __esm({
770
921
  const nodeList = document.getElementsByTagName("link");
771
922
  for (let i = 0; i < nodeList.length; i++) {
772
923
  if (nodeList[i].getAttribute("rel") === "icon" || nodeList[i].getAttribute("rel") === "shortcut icon") {
773
- favicon = (_a2 = nodeList[i].getAttribute("href")) != null ? _a2 : void 0;
924
+ favicon = (_a3 = nodeList[i].getAttribute("href")) != null ? _a3 : void 0;
774
925
  }
775
926
  }
776
927
  return favicon;
777
928
  };
778
- }
779
- });
780
-
781
- // src/multichain/utils/analytics.ts
782
- function isRejectionError(error) {
783
- var _a2, _b;
784
- if (typeof error !== "object" || error === null) {
785
- return false;
786
- }
787
- const errorObj = error;
788
- const errorCode = errorObj.code;
789
- const errorMessage = (_b = (_a2 = errorObj.message) == null ? void 0 : _a2.toLowerCase()) != null ? _b : "";
790
- return errorCode === 4001 || // User rejected request (common EIP-1193 code)
791
- errorCode === 4100 || // Unauthorized (common rejection code)
792
- errorMessage.includes("reject") || errorMessage.includes("denied") || errorMessage.includes("cancel") || errorMessage.includes("user");
793
- }
794
- function getBaseAnalyticsProperties(options, storage) {
795
- return __async(this, null, function* () {
796
- var _a2, _b;
797
- const version = getVersion();
798
- const dappId = getDappId(options.dapp);
799
- const platform = getPlatformType();
800
- const anonId = yield storage.getAnonId();
801
- const integrationType = (_b = (_a2 = options.analytics) == null ? void 0 : _a2.integrationType) != null ? _b : "unknown" /* UNKNOWN */;
802
- return {
803
- mmconnect_version: version,
804
- dapp_id: dappId,
805
- platform,
806
- integration_type: integrationType,
807
- anon_id: anonId
808
- };
809
- });
810
- }
811
- function getWalletActionAnalyticsProperties(options, storage, invokeOptions) {
812
- return __async(this, null, function* () {
813
- var _a2, _b;
814
- const version = getVersion();
815
- const dappId = getDappId(options.dapp);
816
- const anonId = yield storage.getAnonId();
817
- const integrationType = (_b = (_a2 = options.analytics) == null ? void 0 : _a2.integrationType) != null ? _b : "unknown";
818
- return {
819
- mmconnect_version: version,
820
- dapp_id: dappId,
821
- method: invokeOptions.request.method,
822
- integration_type: integrationType,
823
- caip_chain_id: invokeOptions.scope,
824
- anon_id: anonId
929
+ MAX = 4294967295;
930
+ idCounter = Math.floor(Math.random() * MAX);
931
+ getUniqueRequestId = () => {
932
+ idCounter = (idCounter + 1) % MAX;
933
+ return idCounter;
825
934
  };
826
- });
827
- }
828
- var init_analytics = __esm({
829
- "src/multichain/utils/analytics.ts"() {
830
- "use strict";
831
- init_utils();
832
- init_domain();
833
- }
834
- });
835
-
836
- // src/domain/utils/index.ts
837
- function getVersion() {
838
- return "0.0.0";
839
- }
840
- var init_utils2 = __esm({
841
- "src/domain/utils/index.ts"() {
842
- "use strict";
843
- init_analytics();
844
- }
845
- });
846
-
847
- // src/domain/index.ts
848
- var init_domain = __esm({
849
- "src/domain/index.ts"() {
850
- "use strict";
851
- init_errors();
852
- init_events();
853
- init_logger();
854
- init_multichain();
855
- init_platform();
856
- init_store();
857
- init_ui();
858
- init_utils2();
859
935
  }
860
936
  });
861
937
 
862
938
  // src/ui/modals/base/utils.ts
863
939
  function formatRemainingTime(milliseconds) {
864
- if (milliseconds <= 0) return "EXPIRED";
940
+ if (milliseconds <= 0) {
941
+ return "EXPIRED";
942
+ }
865
943
  const seconds = Math.floor(milliseconds / 1e3);
866
944
  return `${seconds}s`;
867
945
  }
@@ -874,9 +952,8 @@ function shouldLogCountdown(remainingSeconds) {
874
952
  return remainingSeconds % 10 === 0;
875
953
  } else if (remainingSeconds <= 300) {
876
954
  return remainingSeconds % 30 === 0;
877
- } else {
878
- return remainingSeconds % 60 === 0;
879
955
  }
956
+ return remainingSeconds % 60 === 0;
880
957
  }
881
958
  var init_utils3 = __esm({
882
959
  "src/ui/modals/base/utils.ts"() {
@@ -885,18 +962,18 @@ var init_utils3 = __esm({
885
962
  });
886
963
 
887
964
  // src/ui/modals/base/AbstractInstallModal.ts
888
- var logger3, AbstractInstallModal;
965
+ var logger3, _expirationInterval, _lastLoggedCountdown, AbstractInstallModal;
889
966
  var init_AbstractInstallModal = __esm({
890
967
  "src/ui/modals/base/AbstractInstallModal.ts"() {
891
968
  "use strict";
892
- init_domain();
893
969
  init_utils3();
970
+ init_domain();
894
971
  logger3 = createLogger("metamask-sdk:ui");
895
972
  AbstractInstallModal = class extends Modal {
896
973
  constructor() {
897
974
  super(...arguments);
898
- this.expirationInterval = null;
899
- this.lastLoggedCountdown = -1;
975
+ __privateAdd(this, _expirationInterval, null);
976
+ __privateAdd(this, _lastLoggedCountdown, -1);
900
977
  }
901
978
  get link() {
902
979
  return this.data;
@@ -924,17 +1001,17 @@ var init_AbstractInstallModal = __esm({
924
1001
  startExpirationCheck(connectionRequest) {
925
1002
  this.stopExpirationCheck();
926
1003
  let currentConnectionRequest = connectionRequest;
927
- this.expirationInterval = setInterval(() => __async(this, null, function* () {
1004
+ __privateSet(this, _expirationInterval, setInterval(() => __async(this, null, function* () {
928
1005
  const { sessionRequest } = currentConnectionRequest;
929
1006
  const now = Date.now();
930
1007
  const remainingMs = sessionRequest.expiresAt - now;
931
1008
  const remainingSeconds = Math.floor(remainingMs / 1e3);
932
- if (remainingMs > 0 && shouldLogCountdown(remainingSeconds) && this.lastLoggedCountdown !== remainingSeconds) {
1009
+ if (remainingMs > 0 && shouldLogCountdown(remainingSeconds) && __privateGet(this, _lastLoggedCountdown) !== remainingSeconds) {
933
1010
  const formattedTime = formatRemainingTime(remainingMs);
934
1011
  logger3(
935
1012
  `[UI: InstallModal-nodejs()] QR code expires in: ${formattedTime} (${remainingSeconds}s)`
936
1013
  );
937
- this.lastLoggedCountdown = remainingSeconds;
1014
+ __privateSet(this, _lastLoggedCountdown, remainingSeconds);
938
1015
  }
939
1016
  if (now >= sessionRequest.expiresAt) {
940
1017
  this.stopExpirationCheck();
@@ -946,7 +1023,7 @@ var init_AbstractInstallModal = __esm({
946
1023
  const generateQRCode = yield this.options.generateQRCode(
947
1024
  currentConnectionRequest
948
1025
  );
949
- this.lastLoggedCountdown = -1;
1026
+ __privateSet(this, _lastLoggedCountdown, -1);
950
1027
  this.updateLink(generateQRCode);
951
1028
  this.updateExpiresIn(remainingSeconds);
952
1029
  this.renderQRCode(generateQRCode, currentConnectionRequest);
@@ -956,18 +1033,20 @@ var init_AbstractInstallModal = __esm({
956
1033
  );
957
1034
  }
958
1035
  }
959
- }), 1e3);
1036
+ }), 1e3));
960
1037
  }
961
1038
  stopExpirationCheck() {
962
- if (this.expirationInterval) {
963
- clearInterval(this.expirationInterval);
964
- this.expirationInterval = null;
1039
+ if (__privateGet(this, _expirationInterval)) {
1040
+ clearInterval(__privateGet(this, _expirationInterval));
1041
+ __privateSet(this, _expirationInterval, null);
965
1042
  logger3(
966
1043
  "[UI: InstallModal-nodejs()] \u{1F6D1} Stopped QR code expiration checking"
967
1044
  );
968
1045
  }
969
1046
  }
970
1047
  };
1048
+ _expirationInterval = new WeakMap();
1049
+ _lastLoggedCountdown = new WeakMap();
971
1050
  }
972
1051
  });
973
1052
 
@@ -1076,11 +1155,14 @@ var init_rn2 = __esm({
1076
1155
  });
1077
1156
 
1078
1157
  // src/polyfills/buffer-shim.ts
1158
+ init_utils2();
1079
1159
  import { Buffer as Buffer2 } from "buffer";
1080
- var g = typeof globalThis !== "undefined" ? globalThis : typeof global !== "undefined" ? global : typeof window !== "undefined" ? window : {};
1081
- if (!g.Buffer) {
1082
- g.Buffer = Buffer2;
1083
- }
1160
+ var globalObj = getGlobalObject();
1161
+ var _a;
1162
+ (_a = globalObj.Buffer) != null ? _a : globalObj.Buffer = Buffer2;
1163
+
1164
+ // src/index.native.ts
1165
+ init_domain();
1084
1166
 
1085
1167
  // src/multichain/index.ts
1086
1168
  import { analytics as analytics2 } from "@metamask/analytics";
@@ -1124,7 +1206,9 @@ var RpcClient = class {
1124
1206
  }
1125
1207
  /**
1126
1208
  * Routes the request to a configured RPC node.
1127
- * @param options - The invoke method options
1209
+ *
1210
+ * @param options - The invoke method options.
1211
+ * @returns The JSON response from the RPC node.
1128
1212
  */
1129
1213
  request(options) {
1130
1214
  return __async(this, null, function* () {
@@ -1136,17 +1220,25 @@ var RpcClient = class {
1136
1220
  id: getNextRpcId()
1137
1221
  });
1138
1222
  const rpcEndpoint = this.getRpcEndpoint(options.scope);
1139
- const rpcRequest = yield this.fetchWithTimeout(rpcEndpoint, body, "POST", this.getHeaders(rpcEndpoint), 3e4);
1223
+ const rpcRequest = yield this.fetchWithTimeout(
1224
+ rpcEndpoint,
1225
+ body,
1226
+ "POST",
1227
+ this.getHeaders(rpcEndpoint),
1228
+ 3e4
1229
+ );
1140
1230
  const response = yield this.parseResponse(rpcRequest);
1141
1231
  return response;
1142
1232
  });
1143
1233
  }
1144
1234
  getRpcEndpoint(scope) {
1145
- var _a2, _b, _c;
1146
- const supportedNetworks = (_c = (_b = (_a2 = this.config) == null ? void 0 : _a2.api) == null ? void 0 : _b.supportedNetworks) != null ? _c : {};
1235
+ var _a3, _b, _c;
1236
+ const supportedNetworks = (_c = (_b = (_a3 = this.config) == null ? void 0 : _a3.api) == null ? void 0 : _b.supportedNetworks) != null ? _c : {};
1147
1237
  const rpcEndpoint = supportedNetworks[scope];
1148
1238
  if (!rpcEndpoint) {
1149
- throw new MissingRpcEndpointErr(`No RPC endpoint found for scope ${scope}`);
1239
+ throw new MissingRpcEndpointErr(
1240
+ `No RPC endpoint found for scope ${scope}`
1241
+ );
1150
1242
  }
1151
1243
  return rpcEndpoint;
1152
1244
  }
@@ -1174,7 +1266,7 @@ var RpcClient = class {
1174
1266
  if (error instanceof Error && error.name === "AbortError") {
1175
1267
  throw new RPCReadonlyRequestErr(`Request timeout after ${timeout}ms`);
1176
1268
  }
1177
- throw new RPCReadonlyRequestErr(error instanceof Error ? error.message : "Unknown error");
1269
+ throw new RPCReadonlyRequestErr(error.message);
1178
1270
  }
1179
1271
  });
1180
1272
  }
@@ -1205,7 +1297,7 @@ var RpcClient = class {
1205
1297
  // src/multichain/rpc/requestRouter.ts
1206
1298
  import { analytics } from "@metamask/analytics";
1207
1299
  init_domain();
1208
- init_utils();
1300
+ init_utils2();
1209
1301
  init_analytics();
1210
1302
  var _RequestRouter_instances, withAnalyticsTracking_fn, trackWalletActionRequested_fn, trackWalletActionSucceeded_fn, trackWalletActionFailed_fn, trackWalletActionRejected_fn;
1211
1303
  var RequestRouter = class {
@@ -1219,10 +1311,12 @@ var RequestRouter = class {
1219
1311
  * The main entry point for invoking an RPC method.
1220
1312
  * This method acts as a router, determining the correct handling strategy
1221
1313
  * for the request and delegating to the appropriate private handler.
1314
+ *
1315
+ * @param options
1222
1316
  */
1223
1317
  invokeMethod(options) {
1224
1318
  return __async(this, null, function* () {
1225
- const method = options.request.method;
1319
+ const { method } = options.request;
1226
1320
  if (RPC_HANDLED_METHODS.has(method)) {
1227
1321
  return this.handleWithRpcNode(options);
1228
1322
  }
@@ -1234,6 +1328,8 @@ var RequestRouter = class {
1234
1328
  }
1235
1329
  /**
1236
1330
  * Forwards the request directly to the wallet via the transport.
1331
+ *
1332
+ * @param options
1237
1333
  */
1238
1334
  handleWithWallet(options) {
1239
1335
  return __async(this, null, function* () {
@@ -1262,7 +1358,10 @@ var RequestRouter = class {
1262
1358
  }
1263
1359
  const response = yield request;
1264
1360
  if (response.error) {
1265
- throw new RPCInvokeMethodErr(`RPC Request failed with code ${response.error.code}: ${response.error.message}`);
1361
+ const { error } = response;
1362
+ throw new RPCInvokeMethodErr(
1363
+ `RPC Request failed with code ${error.code}: ${error.message}`
1364
+ );
1266
1365
  }
1267
1366
  return response.result;
1268
1367
  }));
@@ -1270,6 +1369,8 @@ var RequestRouter = class {
1270
1369
  }
1271
1370
  /**
1272
1371
  * Routes the request to a configured RPC node.
1372
+ *
1373
+ * @param options
1273
1374
  */
1274
1375
  handleWithRpcNode(options) {
1275
1376
  return __async(this, null, function* () {
@@ -1287,10 +1388,14 @@ var RequestRouter = class {
1287
1388
  }
1288
1389
  /**
1289
1390
  * Responds directly from the SDK's session state.
1391
+ *
1392
+ * @param options
1290
1393
  */
1291
1394
  handleWithSdkState(options) {
1292
1395
  return __async(this, null, function* () {
1293
- console.warn(`Method "${options.request.method}" is configured for SDK state handling, but this is not yet implemented. Falling back to wallet passthrough.`);
1396
+ console.warn(
1397
+ `Method "${options.request.method}" is configured for SDK state handling, but this is not yet implemented. Falling back to wallet passthrough.`
1398
+ );
1294
1399
  return this.handleWithWallet(options);
1295
1400
  });
1296
1401
  }
@@ -1310,42 +1415,61 @@ withAnalyticsTracking_fn = function(options, execute) {
1310
1415
  } else {
1311
1416
  yield __privateMethod(this, _RequestRouter_instances, trackWalletActionFailed_fn).call(this, options);
1312
1417
  }
1418
+ if (error instanceof RPCInvokeMethodErr) {
1419
+ throw error;
1420
+ }
1313
1421
  throw new RPCInvokeMethodErr(error.message);
1314
1422
  }
1315
1423
  });
1316
1424
  };
1317
1425
  trackWalletActionRequested_fn = function(options) {
1318
1426
  return __async(this, null, function* () {
1319
- const props = yield getWalletActionAnalyticsProperties(this.config, this.config.storage, options);
1427
+ const props = yield getWalletActionAnalyticsProperties(
1428
+ this.config,
1429
+ this.config.storage,
1430
+ options
1431
+ );
1320
1432
  analytics.track("mmconnect_wallet_action_requested", props);
1321
1433
  });
1322
1434
  };
1323
1435
  trackWalletActionSucceeded_fn = function(options) {
1324
1436
  return __async(this, null, function* () {
1325
- const props = yield getWalletActionAnalyticsProperties(this.config, this.config.storage, options);
1437
+ const props = yield getWalletActionAnalyticsProperties(
1438
+ this.config,
1439
+ this.config.storage,
1440
+ options
1441
+ );
1326
1442
  analytics.track("mmconnect_wallet_action_succeeded", props);
1327
1443
  });
1328
1444
  };
1329
1445
  trackWalletActionFailed_fn = function(options) {
1330
1446
  return __async(this, null, function* () {
1331
- const props = yield getWalletActionAnalyticsProperties(this.config, this.config.storage, options);
1447
+ const props = yield getWalletActionAnalyticsProperties(
1448
+ this.config,
1449
+ this.config.storage,
1450
+ options
1451
+ );
1332
1452
  analytics.track("mmconnect_wallet_action_failed", props);
1333
1453
  });
1334
1454
  };
1335
1455
  trackWalletActionRejected_fn = function(options) {
1336
1456
  return __async(this, null, function* () {
1337
- const props = yield getWalletActionAnalyticsProperties(this.config, this.config.storage, options);
1457
+ const props = yield getWalletActionAnalyticsProperties(
1458
+ this.config,
1459
+ this.config.storage,
1460
+ options
1461
+ );
1338
1462
  analytics.track("mmconnect_wallet_action_rejected", props);
1339
1463
  });
1340
1464
  };
1341
1465
 
1342
1466
  // src/multichain/transports/default/index.ts
1343
- init_utils();
1467
+ init_utils2();
1344
1468
  import {
1345
1469
  getDefaultTransport
1346
1470
  } from "@metamask/multichain-api-client";
1347
1471
  var DEFAULT_REQUEST_TIMEOUT = 60 * 1e3;
1348
- var _notificationCallbacks, _transport, _defaultRequestOptions, _reqId, _pendingRequests, _handleResponseListener, _handleNotificationListener, _DefaultTransport_instances, notifyCallbacks_fn, isMetamaskProviderEvent_fn, handleResponse_fn, handleNotification_fn, setupMessageListener_fn;
1472
+ var _notificationCallbacks, _transport, _defaultRequestOptions, _pendingRequests, _handleResponseListener, _handleNotificationListener, _DefaultTransport_instances, notifyCallbacks_fn, isMetamaskProviderEvent_fn, handleResponse_fn, handleNotification_fn, setupMessageListener_fn;
1349
1473
  var DefaultTransport = class {
1350
1474
  constructor() {
1351
1475
  __privateAdd(this, _DefaultTransport_instances);
@@ -1354,8 +1478,6 @@ var DefaultTransport = class {
1354
1478
  __privateAdd(this, _defaultRequestOptions, {
1355
1479
  timeout: DEFAULT_REQUEST_TIMEOUT
1356
1480
  });
1357
- // Use timestamp-based ID to avoid conflicts across disconnect/reconnect cycles
1358
- __privateAdd(this, _reqId, Date.now());
1359
1481
  __privateAdd(this, _pendingRequests, /* @__PURE__ */ new Map());
1360
1482
  __privateAdd(this, _handleResponseListener);
1361
1483
  __privateAdd(this, _handleNotificationListener);
@@ -1363,18 +1485,17 @@ var DefaultTransport = class {
1363
1485
  sendEip1193Message(payload, options) {
1364
1486
  return __async(this, null, function* () {
1365
1487
  __privateMethod(this, _DefaultTransport_instances, setupMessageListener_fn).call(this);
1366
- __privateSet(this, _reqId, __privateGet(this, _reqId) + 1);
1367
- const requestId = `${__privateGet(this, _reqId)}`;
1488
+ const requestId = String(getUniqueRequestId());
1368
1489
  const request = __spreadValues({
1369
1490
  jsonrpc: "2.0",
1370
1491
  id: requestId
1371
1492
  }, payload);
1372
1493
  return new Promise((resolve, reject) => {
1373
- var _a2;
1494
+ var _a3;
1374
1495
  const timeout = setTimeout(() => {
1375
1496
  __privateGet(this, _pendingRequests).delete(requestId);
1376
1497
  reject(new Error("Request timeout"));
1377
- }, (_a2 = options == null ? void 0 : options.timeout) != null ? _a2 : __privateGet(this, _defaultRequestOptions).timeout);
1498
+ }, (_a3 = options == null ? void 0 : options.timeout) != null ? _a3 : __privateGet(this, _defaultRequestOptions).timeout);
1378
1499
  __privateGet(this, _pendingRequests).set(requestId, {
1379
1500
  resolve: (response) => {
1380
1501
  resolve(response);
@@ -1398,7 +1519,7 @@ var DefaultTransport = class {
1398
1519
  }
1399
1520
  connect(options) {
1400
1521
  return __async(this, null, function* () {
1401
- var _a2, _b, _c, _d, _e, _f, _g;
1522
+ var _a3, _b, _c, _d, _e;
1402
1523
  __privateMethod(this, _DefaultTransport_instances, setupMessageListener_fn).call(this);
1403
1524
  yield __privateGet(this, _transport).connect();
1404
1525
  const sessionRequest = yield this.request(
@@ -1409,12 +1530,19 @@ var DefaultTransport = class {
1409
1530
  throw new Error(sessionRequest.error.message);
1410
1531
  }
1411
1532
  let walletSession = sessionRequest.result;
1533
+ const createSessionParams = {
1534
+ optionalScopes: addValidAccounts(
1535
+ getOptionalScopes((_a3 = options == null ? void 0 : options.scopes) != null ? _a3 : []),
1536
+ getValidAccounts((_b = options == null ? void 0 : options.caipAccountIds) != null ? _b : [])
1537
+ ),
1538
+ sessionProperties: options == null ? void 0 : options.sessionProperties
1539
+ };
1412
1540
  if (walletSession && options && !options.forceRequest) {
1413
1541
  const currentScopes = Object.keys(
1414
- (_a2 = walletSession == null ? void 0 : walletSession.sessionScopes) != null ? _a2 : {}
1542
+ (_c = walletSession == null ? void 0 : walletSession.sessionScopes) != null ? _c : {}
1415
1543
  );
1416
- const proposedScopes = (_b = options == null ? void 0 : options.scopes) != null ? _b : [];
1417
- const proposedCaipAccountIds = (_c = options == null ? void 0 : options.caipAccountIds) != null ? _c : [];
1544
+ const proposedScopes = (_d = options == null ? void 0 : options.scopes) != null ? _d : [];
1545
+ const proposedCaipAccountIds = (_e = options == null ? void 0 : options.caipAccountIds) != null ? _e : [];
1418
1546
  const hasSameScopesAndAccounts = isSameScopesAndAccounts(
1419
1547
  currentScopes,
1420
1548
  proposedScopes,
@@ -1422,17 +1550,6 @@ var DefaultTransport = class {
1422
1550
  proposedCaipAccountIds
1423
1551
  );
1424
1552
  if (!hasSameScopesAndAccounts) {
1425
- yield this.request(
1426
- { method: "wallet_revokeSession", params: walletSession },
1427
- __privateGet(this, _defaultRequestOptions)
1428
- );
1429
- const optionalScopes = addValidAccounts(
1430
- getOptionalScopes((_d = options == null ? void 0 : options.scopes) != null ? _d : []),
1431
- getValidAccounts((_e = options == null ? void 0 : options.caipAccountIds) != null ? _e : [])
1432
- );
1433
- const createSessionParams = {
1434
- optionalScopes
1435
- };
1436
1553
  const response = yield this.request(
1437
1554
  { method: "wallet_createSession", params: createSessionParams },
1438
1555
  __privateGet(this, _defaultRequestOptions)
@@ -1443,14 +1560,6 @@ var DefaultTransport = class {
1443
1560
  walletSession = response.result;
1444
1561
  }
1445
1562
  } else if (!walletSession || (options == null ? void 0 : options.forceRequest)) {
1446
- const optionalScopes = addValidAccounts(
1447
- getOptionalScopes((_f = options == null ? void 0 : options.scopes) != null ? _f : []),
1448
- getValidAccounts((_g = options == null ? void 0 : options.caipAccountIds) != null ? _g : [])
1449
- );
1450
- const createSessionParams = {
1451
- optionalScopes,
1452
- sessionProperties: options == null ? void 0 : options.sessionProperties
1453
- };
1454
1563
  const response = yield this.request(
1455
1564
  { method: "wallet_createSession", params: createSessionParams },
1456
1565
  __privateGet(this, _defaultRequestOptions)
@@ -1467,9 +1576,14 @@ var DefaultTransport = class {
1467
1576
  });
1468
1577
  }
1469
1578
  disconnect() {
1470
- return __async(this, null, function* () {
1579
+ return __async(this, arguments, function* (scopes = []) {
1580
+ yield this.request({ method: "wallet_revokeSession", params: { scopes } });
1581
+ const response = yield this.request({ method: "wallet_getSession" });
1582
+ const { sessionScopes } = response.result;
1583
+ if (Object.keys(sessionScopes).length > 0) {
1584
+ return;
1585
+ }
1471
1586
  __privateGet(this, _notificationCallbacks).clear();
1472
- yield this.request({ method: "wallet_revokeSession", params: {} });
1473
1587
  if (__privateGet(this, _handleResponseListener)) {
1474
1588
  window.removeEventListener("message", __privateGet(this, _handleResponseListener));
1475
1589
  __privateSet(this, _handleResponseListener, void 0);
@@ -1483,7 +1597,7 @@ var DefaultTransport = class {
1483
1597
  request.reject(new Error("Transport disconnected"));
1484
1598
  }
1485
1599
  __privateGet(this, _pendingRequests).clear();
1486
- return __privateGet(this, _transport).disconnect();
1600
+ yield __privateGet(this, _transport).disconnect();
1487
1601
  });
1488
1602
  }
1489
1603
  isConnected() {
@@ -1502,13 +1616,23 @@ var DefaultTransport = class {
1502
1616
  };
1503
1617
  }
1504
1618
  getActiveSession() {
1505
- throw new Error("getActiveSession is purposely not implemented for the DefaultTransport");
1619
+ return __async(this, null, function* () {
1620
+ throw new Error(
1621
+ "getActiveSession is purposely not implemented for the DefaultTransport"
1622
+ );
1623
+ });
1624
+ }
1625
+ getStoredPendingSessionRequest() {
1626
+ return __async(this, null, function* () {
1627
+ throw new Error(
1628
+ "getStoredPendingSessionRequest is purposely not implemented for the DefaultTransport"
1629
+ );
1630
+ });
1506
1631
  }
1507
1632
  };
1508
1633
  _notificationCallbacks = new WeakMap();
1509
1634
  _transport = new WeakMap();
1510
1635
  _defaultRequestOptions = new WeakMap();
1511
- _reqId = new WeakMap();
1512
1636
  _pendingRequests = new WeakMap();
1513
1637
  _handleResponseListener = new WeakMap();
1514
1638
  _handleNotificationListener = new WeakMap();
@@ -1526,16 +1650,16 @@ notifyCallbacks_fn = function(data) {
1526
1650
  }
1527
1651
  };
1528
1652
  isMetamaskProviderEvent_fn = function(event) {
1529
- var _a2, _b;
1530
- 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
1653
+ var _a3, _b;
1654
+ 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
1531
1655
  event.origin === location.origin;
1532
1656
  };
1533
1657
  handleResponse_fn = function(event) {
1534
- var _a2, _b;
1658
+ var _a3, _b;
1535
1659
  if (!__privateMethod(this, _DefaultTransport_instances, isMetamaskProviderEvent_fn).call(this, event)) {
1536
1660
  return;
1537
1661
  }
1538
- const responseData = (_b = (_a2 = event == null ? void 0 : event.data) == null ? void 0 : _a2.data) == null ? void 0 : _b.data;
1662
+ const responseData = (_b = (_a3 = event == null ? void 0 : event.data) == null ? void 0 : _a3.data) == null ? void 0 : _b.data;
1539
1663
  if (typeof responseData === "object" && responseData !== null && "method" in responseData) {
1540
1664
  return;
1541
1665
  }
@@ -1557,11 +1681,11 @@ handleResponse_fn = function(event) {
1557
1681
  }
1558
1682
  };
1559
1683
  handleNotification_fn = function(event) {
1560
- var _a2, _b;
1684
+ var _a3, _b;
1561
1685
  if (!__privateMethod(this, _DefaultTransport_instances, isMetamaskProviderEvent_fn).call(this, event)) {
1562
1686
  return;
1563
1687
  }
1564
- const responseData = (_b = (_a2 = event == null ? void 0 : event.data) == null ? void 0 : _a2.data) == null ? void 0 : _b.data;
1688
+ const responseData = (_b = (_a3 = event == null ? void 0 : event.data) == null ? void 0 : _a3.data) == null ? void 0 : _b.data;
1565
1689
  if (typeof responseData === "object" && responseData.method === "metamask_chainChanged" || responseData.method === "metamask_accountsChanged") {
1566
1690
  __privateMethod(this, _DefaultTransport_instances, notifyCallbacks_fn).call(this, responseData);
1567
1691
  }
@@ -1576,13 +1700,174 @@ setupMessageListener_fn = function() {
1576
1700
  window.addEventListener("message", __privateGet(this, _handleNotificationListener));
1577
1701
  };
1578
1702
 
1703
+ // src/multichain/transports/multichainApiClientWrapper/index.ts
1704
+ init_utils2();
1705
+ import { providerErrors } from "@metamask/rpc-errors";
1706
+ var _notificationCallbacks2, _MultichainApiClientWrapperTransport_instances, walletCreateSession_fn, walletGetSession_fn, walletRevokeSession_fn, walletInvokeMethod_fn;
1707
+ var MultichainApiClientWrapperTransport = class {
1708
+ constructor(metamaskConnectMultichain) {
1709
+ this.metamaskConnectMultichain = metamaskConnectMultichain;
1710
+ __privateAdd(this, _MultichainApiClientWrapperTransport_instances);
1711
+ __privateAdd(this, _notificationCallbacks2, /* @__PURE__ */ new Set());
1712
+ }
1713
+ isTransportDefined() {
1714
+ try {
1715
+ return Boolean(this.metamaskConnectMultichain.transport);
1716
+ } catch (_error) {
1717
+ return false;
1718
+ }
1719
+ }
1720
+ clearNotificationCallbacks() {
1721
+ __privateGet(this, _notificationCallbacks2).clear();
1722
+ }
1723
+ notifyCallbacks(data) {
1724
+ __privateGet(this, _notificationCallbacks2).forEach((callback) => {
1725
+ callback(data);
1726
+ });
1727
+ }
1728
+ clearTransportNotificationListener() {
1729
+ var _a3;
1730
+ (_a3 = this.notificationListener) == null ? void 0 : _a3.call(this);
1731
+ this.notificationListener = void 0;
1732
+ }
1733
+ setupTransportNotificationListener() {
1734
+ if (!this.isTransportDefined() || this.notificationListener) {
1735
+ return;
1736
+ }
1737
+ this.notificationListener = this.metamaskConnectMultichain.transport.onNotification(
1738
+ this.notifyCallbacks.bind(this)
1739
+ );
1740
+ }
1741
+ connect() {
1742
+ return __async(this, null, function* () {
1743
+ console.log("\u{1F4DA} connect");
1744
+ yield this.metamaskConnectMultichain.emitSessionChanged();
1745
+ });
1746
+ }
1747
+ disconnect() {
1748
+ return __async(this, null, function* () {
1749
+ return Promise.resolve();
1750
+ });
1751
+ }
1752
+ isConnected() {
1753
+ return true;
1754
+ }
1755
+ request(_0) {
1756
+ return __async(this, arguments, function* (params, _options = {}) {
1757
+ const id = getUniqueRequestId();
1758
+ const requestPayload = __spreadValues({
1759
+ id,
1760
+ jsonrpc: "2.0"
1761
+ }, params);
1762
+ switch (requestPayload.method) {
1763
+ case "wallet_createSession":
1764
+ return __privateMethod(this, _MultichainApiClientWrapperTransport_instances, walletCreateSession_fn).call(this, requestPayload);
1765
+ case "wallet_getSession":
1766
+ return __privateMethod(this, _MultichainApiClientWrapperTransport_instances, walletGetSession_fn).call(this, requestPayload);
1767
+ case "wallet_revokeSession":
1768
+ return __privateMethod(this, _MultichainApiClientWrapperTransport_instances, walletRevokeSession_fn).call(this, requestPayload);
1769
+ case "wallet_invokeMethod":
1770
+ return __privateMethod(this, _MultichainApiClientWrapperTransport_instances, walletInvokeMethod_fn).call(this, requestPayload);
1771
+ default:
1772
+ throw new Error(`Unsupported method: ${requestPayload.method}`);
1773
+ }
1774
+ throw new Error(`Unknown method: ${requestPayload.method}`);
1775
+ });
1776
+ }
1777
+ onNotification(callback) {
1778
+ this.setupTransportNotificationListener();
1779
+ __privateGet(this, _notificationCallbacks2).add(callback);
1780
+ return () => {
1781
+ __privateGet(this, _notificationCallbacks2).delete(callback);
1782
+ };
1783
+ }
1784
+ };
1785
+ _notificationCallbacks2 = new WeakMap();
1786
+ _MultichainApiClientWrapperTransport_instances = new WeakSet();
1787
+ walletCreateSession_fn = function(request) {
1788
+ return __async(this, null, function* () {
1789
+ console.log("\u{1F4DA} #walletCreateSession", request);
1790
+ const createSessionParams = request.params;
1791
+ const scopes = Object.keys(__spreadValues(__spreadValues({}, createSessionParams.optionalScopes), createSessionParams.requiredScopes));
1792
+ const scopeAccounts = [];
1793
+ scopes.forEach((scope) => {
1794
+ var _a3, _b, _c, _d;
1795
+ const requiredScope = (_a3 = createSessionParams.requiredScopes) == null ? void 0 : _a3[scope];
1796
+ const optionalScope = (_b = createSessionParams.optionalScopes) == null ? void 0 : _b[scope];
1797
+ if (requiredScope) {
1798
+ scopeAccounts.push(...(_c = requiredScope.accounts) != null ? _c : []);
1799
+ }
1800
+ if (optionalScope) {
1801
+ scopeAccounts.push(...(_d = optionalScope.accounts) != null ? _d : []);
1802
+ }
1803
+ });
1804
+ const accounts = [...new Set(scopeAccounts)];
1805
+ console.log("\u{1F4DA} SDK connect");
1806
+ yield this.metamaskConnectMultichain.connect(
1807
+ scopes,
1808
+ accounts,
1809
+ createSessionParams.sessionProperties
1810
+ );
1811
+ console.log("\u{1F4DA} SDK connected");
1812
+ return this.metamaskConnectMultichain.transport.request({
1813
+ method: "wallet_getSession"
1814
+ });
1815
+ });
1816
+ };
1817
+ walletGetSession_fn = function(request) {
1818
+ return __async(this, null, function* () {
1819
+ if (!this.isTransportDefined()) {
1820
+ return {
1821
+ jsonrpc: "2.0",
1822
+ id: request.id,
1823
+ result: {
1824
+ sessionScopes: {}
1825
+ }
1826
+ };
1827
+ }
1828
+ return this.metamaskConnectMultichain.transport.request({
1829
+ method: "wallet_getSession"
1830
+ });
1831
+ });
1832
+ };
1833
+ walletRevokeSession_fn = function(request) {
1834
+ return __async(this, null, function* () {
1835
+ var _a3;
1836
+ if (!this.isTransportDefined()) {
1837
+ return { jsonrpc: "2.0", id: request.id, result: true };
1838
+ }
1839
+ const revokeSessionParams = request.params;
1840
+ const scopes = (_a3 = revokeSessionParams == null ? void 0 : revokeSessionParams.scopes) != null ? _a3 : [];
1841
+ try {
1842
+ yield this.metamaskConnectMultichain.disconnect(scopes);
1843
+ return { jsonrpc: "2.0", id: request.id, result: true };
1844
+ } catch (_error) {
1845
+ return { jsonrpc: "2.0", id: request.id, result: false };
1846
+ }
1847
+ });
1848
+ };
1849
+ walletInvokeMethod_fn = function(request) {
1850
+ return __async(this, null, function* () {
1851
+ if (!this.isTransportDefined()) {
1852
+ return { error: providerErrors.unauthorized() };
1853
+ }
1854
+ const result = this.metamaskConnectMultichain.invokeMethod(
1855
+ request.params
1856
+ );
1857
+ return {
1858
+ result
1859
+ };
1860
+ });
1861
+ };
1862
+
1579
1863
  // src/multichain/transports/mwp/index.ts
1580
1864
  init_domain();
1581
- init_utils();
1865
+ init_utils2();
1582
1866
  import { SessionStore } from "@metamask/mobile-wallet-protocol-core";
1583
1867
  import {
1584
1868
  TransportTimeoutError
1585
1869
  } from "@metamask/multichain-api-client";
1870
+ import { providerErrors as providerErrors2, rpcErrors } from "@metamask/rpc-errors";
1586
1871
 
1587
1872
  // src/multichain/transports/constants.ts
1588
1873
  var MULTICHAIN_PROVIDER_STREAM_NAME = "metamask-multichain-provider";
@@ -1595,6 +1880,7 @@ var DEFAULT_RESUME_TIMEOUT = 10 * 1e3;
1595
1880
  var SESSION_STORE_KEY = "cache_wallet_getSession";
1596
1881
  var ACCOUNTS_STORE_KEY = "cache_eth_accounts";
1597
1882
  var CHAIN_STORE_KEY = "cache_eth_chainId";
1883
+ var PENDING_SESSION_REQUEST_KEY = "pending_session_request";
1598
1884
  var CACHED_METHOD_LIST = [
1599
1885
  "wallet_getSession",
1600
1886
  "wallet_createSession",
@@ -1614,10 +1900,15 @@ var MWPTransport = class {
1614
1900
  this.dappClient = dappClient;
1615
1901
  this.kvstore = kvstore;
1616
1902
  this.options = options;
1617
- this.__reqId = 0;
1618
1903
  this.__pendingRequests = /* @__PURE__ */ new Map();
1619
1904
  this.notificationCallbacks = /* @__PURE__ */ new Set();
1620
1905
  this.dappClient.on("message", this.handleMessage.bind(this));
1906
+ this.dappClient.on("session_request", (sessionRequest) => {
1907
+ this.currentSessionRequest = sessionRequest;
1908
+ this.kvstore.set(PENDING_SESSION_REQUEST_KEY, JSON.stringify(sessionRequest)).catch((err) => {
1909
+ logger("Failed to store pending session request", err);
1910
+ });
1911
+ });
1621
1912
  if (typeof window !== "undefined" && typeof window.addEventListener !== "undefined") {
1622
1913
  this.windowFocusHandler = this.onWindowFocus.bind(this);
1623
1914
  window.addEventListener("focus", this.windowFocusHandler);
@@ -1632,6 +1923,34 @@ var MWPTransport = class {
1632
1923
  get sessionRequest() {
1633
1924
  return this.currentSessionRequest;
1634
1925
  }
1926
+ /**
1927
+ * Returns the stored pending session request from the dappClient session_request event, if any.
1928
+ *
1929
+ * @returns The stored SessionRequest, or null if none or invalid.
1930
+ */
1931
+ getStoredPendingSessionRequest() {
1932
+ return __async(this, null, function* () {
1933
+ try {
1934
+ const raw = yield this.kvstore.get(PENDING_SESSION_REQUEST_KEY);
1935
+ if (!raw) {
1936
+ return null;
1937
+ }
1938
+ return JSON.parse(raw);
1939
+ } catch (e) {
1940
+ return null;
1941
+ }
1942
+ });
1943
+ }
1944
+ /**
1945
+ * Removes the stored pending session request from the KVStore.
1946
+ * This is necessary to ensure that ConnectMultichain is able to correctly
1947
+ * infer the MWP Transport connection attempt status.
1948
+ */
1949
+ removeStoredPendingSessionRequest() {
1950
+ return __async(this, null, function* () {
1951
+ yield this.kvstore.delete(PENDING_SESSION_REQUEST_KEY);
1952
+ });
1953
+ }
1635
1954
  onWindowFocus() {
1636
1955
  if (!this.isConnected()) {
1637
1956
  this.dappClient.reconnect();
@@ -1648,6 +1967,17 @@ var MWPTransport = class {
1648
1967
  request.reject(error);
1649
1968
  }
1650
1969
  }
1970
+ parseWalletError(errorPayload) {
1971
+ const errorData = errorPayload;
1972
+ if (typeof errorData.code === "number" && typeof errorData.message === "string") {
1973
+ return providerErrors2.custom({
1974
+ code: errorData.code,
1975
+ message: errorData.message
1976
+ });
1977
+ }
1978
+ const message = errorPayload instanceof Error ? errorPayload.message : JSON.stringify(errorPayload);
1979
+ return rpcErrors.internal({ message });
1980
+ }
1651
1981
  handleMessage(message) {
1652
1982
  if (typeof message === "object" && message !== null) {
1653
1983
  if ("data" in message) {
@@ -1655,6 +1985,12 @@ var MWPTransport = class {
1655
1985
  if ("id" in messagePayload && typeof messagePayload.id === "string") {
1656
1986
  const request = this.pendingRequests.get(messagePayload.id);
1657
1987
  if (request) {
1988
+ clearTimeout(request.timeout);
1989
+ if ("error" in messagePayload && messagePayload.error) {
1990
+ this.pendingRequests.delete(messagePayload.id);
1991
+ request.reject(this.parseWalletError(messagePayload.error));
1992
+ return;
1993
+ }
1658
1994
  const requestWithName = __spreadProps(__spreadValues({}, messagePayload), {
1659
1995
  method: request.method === "wallet_getSession" || request.method === "wallet_createSession" ? "wallet_sessionChanged" : request.method
1660
1996
  });
@@ -1662,7 +1998,6 @@ var MWPTransport = class {
1662
1998
  method: request.method === "wallet_getSession" || request.method === "wallet_createSession" ? "wallet_sessionChanged" : request.method,
1663
1999
  params: requestWithName.result
1664
2000
  });
1665
- clearTimeout(request.timeout);
1666
2001
  this.notifyCallbacks(notification);
1667
2002
  request.resolve(requestWithName);
1668
2003
  this.pendingRequests.delete(messagePayload.id);
@@ -1698,7 +2033,7 @@ var MWPTransport = class {
1698
2033
  }
1699
2034
  onResumeSuccess(resumeResolve, resumeReject, options) {
1700
2035
  return __async(this, null, function* () {
1701
- var _a2, _b, _c, _d, _e, _f, _g;
2036
+ var _a3, _b, _c, _d, _e, _f, _g;
1702
2037
  try {
1703
2038
  yield this.waitForWalletSessionIfNotCached();
1704
2039
  const sessionRequest = yield this.request({
@@ -1710,7 +2045,7 @@ var MWPTransport = class {
1710
2045
  let walletSession = sessionRequest.result;
1711
2046
  if (walletSession && options) {
1712
2047
  const currentScopes = Object.keys(
1713
- (_a2 = walletSession == null ? void 0 : walletSession.sessionScopes) != null ? _a2 : {}
2048
+ (_a3 = walletSession == null ? void 0 : walletSession.sessionScopes) != null ? _a3 : {}
1714
2049
  );
1715
2050
  const proposedScopes = (_b = options == null ? void 0 : options.scopes) != null ? _b : [];
1716
2051
  const proposedCaipAccountIds = (_c = options == null ? void 0 : options.caipAccountIds) != null ? _c : [];
@@ -1752,6 +2087,7 @@ var MWPTransport = class {
1752
2087
  }
1753
2088
  walletSession = response.result;
1754
2089
  }
2090
+ yield this.removeStoredPendingSessionRequest();
1755
2091
  this.notifyCallbacks({
1756
2092
  method: "wallet_sessionChanged",
1757
2093
  params: walletSession
@@ -1767,7 +2103,7 @@ var MWPTransport = class {
1767
2103
  return __async(this, null, function* () {
1768
2104
  const request = __spreadValues({
1769
2105
  jsonrpc: "2.0",
1770
- id: `${this.__reqId++}`
2106
+ id: String(getUniqueRequestId())
1771
2107
  }, payload);
1772
2108
  const cachedWalletSession = yield this.getCachedResponse(request);
1773
2109
  if (cachedWalletSession) {
@@ -1775,10 +2111,10 @@ var MWPTransport = class {
1775
2111
  return cachedWalletSession;
1776
2112
  }
1777
2113
  return new Promise((resolve, reject) => {
1778
- var _a2;
2114
+ var _a3;
1779
2115
  const timeout = setTimeout(() => {
1780
2116
  this.rejectRequest(request.id, new TransportTimeoutError());
1781
- }, (_a2 = options == null ? void 0 : options.timeout) != null ? _a2 : this.options.requestTimeout);
2117
+ }, (_a3 = options == null ? void 0 : options.timeout) != null ? _a3 : this.options.requestTimeout);
1782
2118
  this.pendingRequests.set(request.id, {
1783
2119
  request,
1784
2120
  method: request.method,
@@ -1803,28 +2139,29 @@ var MWPTransport = class {
1803
2139
  if (session) {
1804
2140
  logger("active session found", session);
1805
2141
  }
2142
+ const storedSessionRequestBeforeConnectionAttempt = yield this.getStoredPendingSessionRequest();
1806
2143
  let timeout;
1807
2144
  let initialConnectionMessageHandler;
1808
2145
  const connectionPromise = new Promise((resolve, reject) => __async(this, null, function* () {
1809
2146
  let connection;
1810
2147
  if (session) {
1811
2148
  connection = new Promise((resumeResolve, resumeReject) => {
1812
- var _a2;
2149
+ var _a3;
1813
2150
  if (this.dappClient.state === "CONNECTED") {
1814
2151
  this.onResumeSuccess(resumeResolve, resumeReject, options);
1815
2152
  } else {
1816
2153
  this.dappClient.once("connected", () => __async(this, null, function* () {
1817
2154
  this.onResumeSuccess(resumeResolve, resumeReject, options);
1818
2155
  }));
1819
- dappClient.resume((_a2 = session == null ? void 0 : session.id) != null ? _a2 : "");
2156
+ dappClient.resume((_a3 = session == null ? void 0 : session.id) != null ? _a3 : "");
1820
2157
  }
1821
2158
  });
1822
2159
  } else {
1823
2160
  connection = new Promise(
1824
2161
  (resolveConnection, rejectConnection) => {
1825
- var _a2, _b;
2162
+ var _a3, _b;
1826
2163
  const optionalScopes = addValidAccounts(
1827
- getOptionalScopes((_a2 = options == null ? void 0 : options.scopes) != null ? _a2 : []),
2164
+ getOptionalScopes((_a3 = options == null ? void 0 : options.scopes) != null ? _a3 : []),
1828
2165
  getValidAccounts((_b = options == null ? void 0 : options.caipAccountIds) != null ? _b : [])
1829
2166
  );
1830
2167
  const sessionRequest = {
@@ -1833,33 +2170,35 @@ var MWPTransport = class {
1833
2170
  };
1834
2171
  const request = {
1835
2172
  jsonrpc: "2.0",
1836
- id: `${this.__reqId++}`,
2173
+ id: String(getUniqueRequestId()),
1837
2174
  method: "wallet_createSession",
1838
2175
  params: sessionRequest
1839
2176
  };
1840
2177
  initialConnectionMessageHandler = (message) => __async(this, null, function* () {
1841
- if (typeof message === "object" && message !== null) {
1842
- if ("data" in message) {
1843
- const messagePayload = message.data;
1844
- if (messagePayload.method === "wallet_createSession" || messagePayload.method === "wallet_sessionChanged") {
1845
- if (messagePayload.error) {
1846
- if (initialConnectionMessageHandler) {
1847
- this.dappClient.off(
1848
- "message",
1849
- initialConnectionMessageHandler
1850
- );
1851
- }
1852
- return rejectConnection(messagePayload.error);
1853
- }
1854
- yield this.storeWalletSession(
1855
- request,
1856
- messagePayload
1857
- );
1858
- this.notifyCallbacks(messagePayload);
1859
- return resolveConnection();
1860
- }
1861
- }
2178
+ if (typeof message !== "object" || message === null) {
2179
+ return;
2180
+ }
2181
+ if (!("data" in message)) {
2182
+ return;
2183
+ }
2184
+ const messagePayload = message.data;
2185
+ const isMatchingId = messagePayload.id === request.id;
2186
+ const isMatchingMethod = messagePayload.method === "wallet_createSession" || messagePayload.method === "wallet_sessionChanged";
2187
+ if (!isMatchingId && !isMatchingMethod) {
2188
+ return;
2189
+ }
2190
+ if (messagePayload.error) {
2191
+ return rejectConnection(
2192
+ this.parseWalletError(messagePayload.error)
2193
+ );
1862
2194
  }
2195
+ yield this.storeWalletSession(
2196
+ request,
2197
+ messagePayload
2198
+ );
2199
+ yield this.removeStoredPendingSessionRequest();
2200
+ this.notifyCallbacks(messagePayload);
2201
+ return resolveConnection();
1863
2202
  });
1864
2203
  this.dappClient.on("message", initialConnectionMessageHandler);
1865
2204
  dappClient.connect({
@@ -1880,14 +2219,18 @@ var MWPTransport = class {
1880
2219
  }
1881
2220
  );
1882
2221
  }
1883
- timeout = setTimeout(() => {
1884
- reject(new TransportTimeoutError());
1885
- }, this.options.connectionTimeout);
2222
+ timeout = setTimeout(
2223
+ () => {
2224
+ reject(new TransportTimeoutError());
2225
+ },
2226
+ storedSessionRequestBeforeConnectionAttempt ? this.options.resumeTimeout : this.options.connectionTimeout
2227
+ );
1886
2228
  connection.then(resolve).catch(reject);
1887
2229
  }));
1888
- return connectionPromise.catch((error) => {
2230
+ return connectionPromise.catch((error) => __async(this, null, function* () {
2231
+ yield this.dappClient.disconnect();
1889
2232
  throw error;
1890
- }).finally(() => {
2233
+ })).finally(() => {
1891
2234
  if (timeout) {
1892
2235
  clearTimeout(timeout);
1893
2236
  }
@@ -1895,24 +2238,68 @@ var MWPTransport = class {
1895
2238
  this.dappClient.off("message", initialConnectionMessageHandler);
1896
2239
  initialConnectionMessageHandler = void 0;
1897
2240
  }
2241
+ this.removeStoredPendingSessionRequest();
1898
2242
  });
1899
2243
  });
1900
2244
  }
1901
2245
  /**
1902
2246
  * Disconnects from the Mobile Wallet Protocol
1903
2247
  *
2248
+ * @param [scopes] - The scopes to revoke. If not provided or empty, all scopes will be revoked.
1904
2249
  * @returns Nothing
1905
2250
  */
1906
2251
  disconnect() {
1907
- return __async(this, null, function* () {
1908
- if (typeof window !== "undefined" && typeof window.removeEventListener !== "undefined" && this.windowFocusHandler) {
1909
- window.removeEventListener("focus", this.windowFocusHandler);
1910
- this.windowFocusHandler = void 0;
1911
- }
1912
- this.kvstore.delete(SESSION_STORE_KEY);
1913
- this.kvstore.delete(ACCOUNTS_STORE_KEY);
1914
- this.kvstore.delete(CHAIN_STORE_KEY);
1915
- return this.dappClient.disconnect();
2252
+ return __async(this, arguments, function* (scopes = []) {
2253
+ var _a3, _b;
2254
+ const cachedSession = yield this.getCachedResponse({
2255
+ jsonrpc: "2.0",
2256
+ id: "0",
2257
+ method: "wallet_getSession"
2258
+ });
2259
+ const cachedSessionScopes = (_b = (_a3 = cachedSession == null ? void 0 : cachedSession.result) == null ? void 0 : _a3.sessionScopes) != null ? _b : {};
2260
+ const remainingScopes = scopes.length === 0 ? [] : Object.keys(cachedSessionScopes).filter(
2261
+ (scope) => !scopes.includes(scope)
2262
+ );
2263
+ const newSessionScopes = Object.fromEntries(
2264
+ Object.entries(cachedSessionScopes).filter(
2265
+ ([key]) => remainingScopes.includes(key)
2266
+ )
2267
+ );
2268
+ this.request({ method: "wallet_revokeSession", params: { scopes } }).catch(
2269
+ (err) => {
2270
+ console.error("error revoking session", err);
2271
+ }
2272
+ );
2273
+ const remainingScopesIncludeEip155 = remainingScopes.some(
2274
+ (scope) => scope.includes("eip155")
2275
+ );
2276
+ if (!remainingScopesIncludeEip155) {
2277
+ this.kvstore.delete(ACCOUNTS_STORE_KEY);
2278
+ this.kvstore.delete(CHAIN_STORE_KEY);
2279
+ }
2280
+ if (remainingScopes.length > 0) {
2281
+ this.kvstore.set(
2282
+ SESSION_STORE_KEY,
2283
+ JSON.stringify({
2284
+ result: {
2285
+ sessionScopes: newSessionScopes
2286
+ }
2287
+ })
2288
+ );
2289
+ } else {
2290
+ this.kvstore.delete(SESSION_STORE_KEY);
2291
+ if (typeof window !== "undefined" && typeof window.removeEventListener !== "undefined" && this.windowFocusHandler) {
2292
+ window.removeEventListener("focus", this.windowFocusHandler);
2293
+ this.windowFocusHandler = void 0;
2294
+ }
2295
+ yield this.dappClient.disconnect();
2296
+ }
2297
+ this.notifyCallbacks({
2298
+ method: "wallet_sessionChanged",
2299
+ params: {
2300
+ sessionScopes: newSessionScopes
2301
+ }
2302
+ });
1916
2303
  });
1917
2304
  }
1918
2305
  /**
@@ -1957,7 +2344,7 @@ var MWPTransport = class {
1957
2344
  }
1958
2345
  getCachedResponse(request) {
1959
2346
  return __async(this, null, function* () {
1960
- var _a2;
2347
+ var _a3;
1961
2348
  if (request.method === "wallet_getSession") {
1962
2349
  const walletGetSession = yield this.kvstore.get(SESSION_STORE_KEY);
1963
2350
  if (walletGetSession) {
@@ -1965,7 +2352,7 @@ var MWPTransport = class {
1965
2352
  return {
1966
2353
  id: request.id,
1967
2354
  jsonrpc: "2.0",
1968
- result: (_a2 = walletSession.params) != null ? _a2 : walletSession.result,
2355
+ result: (_a3 = walletSession.params) != null ? _a3 : walletSession.result,
1969
2356
  // "what?... why walletSession.params?.."
1970
2357
  method: request.method
1971
2358
  };
@@ -2018,7 +2405,7 @@ var MWPTransport = class {
2018
2405
  return __async(this, null, function* () {
2019
2406
  const request = __spreadValues({
2020
2407
  jsonrpc: "2.0",
2021
- id: `${this.__reqId++}`
2408
+ id: String(getUniqueRequestId())
2022
2409
  }, payload);
2023
2410
  const cachedWalletSession = yield this.getCachedResponse(request);
2024
2411
  if (cachedWalletSession) {
@@ -2029,10 +2416,10 @@ var MWPTransport = class {
2029
2416
  yield this.attemptResumeSession();
2030
2417
  }
2031
2418
  return new Promise((resolve, reject) => {
2032
- var _a2;
2419
+ var _a3;
2033
2420
  const timeout = setTimeout(() => {
2034
2421
  this.rejectRequest(request.id, new TransportTimeoutError());
2035
- }, (_a2 = options == null ? void 0 : options.timeout) != null ? _a2 : this.options.requestTimeout);
2422
+ }, (_a3 = options == null ? void 0 : options.timeout) != null ? _a3 : this.options.requestTimeout);
2036
2423
  this.pendingRequests.set(request.id, {
2037
2424
  request,
2038
2425
  method: request.method,
@@ -2100,6 +2487,7 @@ var MWPTransport = class {
2100
2487
  const timeoutPromise = new Promise((_resolve, reject) => {
2101
2488
  setTimeout(() => {
2102
2489
  unsubscribe();
2490
+ this.removeStoredPendingSessionRequest();
2103
2491
  reject(new TransportTimeoutError());
2104
2492
  }, this.options.resumeTimeout);
2105
2493
  });
@@ -2136,172 +2524,15 @@ var KeyManager = class {
2136
2524
  var keymanager = new KeyManager();
2137
2525
 
2138
2526
  // src/multichain/index.ts
2139
- init_utils();
2140
-
2141
- // src/multichain/transports/multichainApiClientWrapper/index.ts
2142
- import { providerErrors } from "@metamask/rpc-errors";
2143
- var MAX = 4294967295;
2144
- var idCounter = Math.floor(Math.random() * MAX);
2145
- var getUniqueId = () => {
2146
- idCounter = (idCounter + 1) % MAX;
2147
- return idCounter;
2148
- };
2149
- var _MultichainApiClientWrapperTransport_instances, walletCreateSession_fn, walletGetSession_fn, walletRevokeSession_fn, walletInvokeMethod_fn;
2150
- var MultichainApiClientWrapperTransport = class {
2151
- constructor(metamaskConnectMultichain) {
2152
- this.metamaskConnectMultichain = metamaskConnectMultichain;
2153
- __privateAdd(this, _MultichainApiClientWrapperTransport_instances);
2154
- this.requestId = getUniqueId();
2155
- this.notificationCallbacks = /* @__PURE__ */ new Set();
2156
- }
2157
- isTransportDefined() {
2158
- try {
2159
- return Boolean(this.metamaskConnectMultichain.transport);
2160
- } catch (error) {
2161
- return false;
2162
- }
2163
- }
2164
- clearNotificationCallbacks() {
2165
- this.notificationCallbacks.clear();
2166
- }
2167
- notifyCallbacks(data) {
2168
- this.notificationCallbacks.forEach((callback) => {
2169
- callback(data);
2170
- });
2171
- }
2172
- setupNotifcationListener() {
2173
- this.metamaskConnectMultichain.transport.onNotification(
2174
- this.notifyCallbacks.bind(this)
2175
- );
2176
- }
2177
- connect() {
2178
- return __async(this, null, function* () {
2179
- console.log("\u{1F4DA} connect");
2180
- return Promise.resolve();
2181
- });
2182
- }
2183
- disconnect() {
2184
- return __async(this, null, function* () {
2185
- return Promise.resolve();
2186
- });
2187
- }
2188
- isConnected() {
2189
- return true;
2190
- }
2191
- request(_0) {
2192
- return __async(this, arguments, function* (params, _options = {}) {
2193
- const id = this.requestId++;
2194
- const requestPayload = __spreadValues({
2195
- id,
2196
- jsonrpc: "2.0"
2197
- }, params);
2198
- switch (requestPayload.method) {
2199
- case "wallet_createSession":
2200
- return __privateMethod(this, _MultichainApiClientWrapperTransport_instances, walletCreateSession_fn).call(this, requestPayload);
2201
- case "wallet_getSession":
2202
- return __privateMethod(this, _MultichainApiClientWrapperTransport_instances, walletGetSession_fn).call(this, requestPayload);
2203
- case "wallet_revokeSession":
2204
- return __privateMethod(this, _MultichainApiClientWrapperTransport_instances, walletRevokeSession_fn).call(this, requestPayload);
2205
- case "wallet_invokeMethod":
2206
- return __privateMethod(this, _MultichainApiClientWrapperTransport_instances, walletInvokeMethod_fn).call(this, requestPayload);
2207
- default:
2208
- throw new Error(`Unsupported method: ${requestPayload.method}`);
2209
- }
2210
- throw new Error(`Unknown method: ${requestPayload.method}`);
2211
- });
2212
- }
2213
- onNotification(callback) {
2214
- if (!this.isTransportDefined()) {
2215
- this.notificationCallbacks.add(callback);
2216
- return () => {
2217
- this.notificationCallbacks.delete(callback);
2218
- };
2219
- }
2220
- return this.metamaskConnectMultichain.transport.onNotification(callback);
2221
- }
2222
- };
2223
- _MultichainApiClientWrapperTransport_instances = new WeakSet();
2224
- walletCreateSession_fn = function(request) {
2225
- return __async(this, null, function* () {
2226
- console.log("\u{1F4DA} #walletCreateSession", request);
2227
- const createSessionParams = request.params;
2228
- const scopes = Object.keys(__spreadValues(__spreadValues({}, createSessionParams.optionalScopes), createSessionParams.requiredScopes));
2229
- const scopeAccounts = [];
2230
- scopes.forEach((scope) => {
2231
- var _a2, _b, _c, _d;
2232
- const requiredScope = (_a2 = createSessionParams.requiredScopes) == null ? void 0 : _a2[scope];
2233
- const optionalScope = (_b = createSessionParams.optionalScopes) == null ? void 0 : _b[scope];
2234
- if (requiredScope) {
2235
- scopeAccounts.push(...(_c = requiredScope.accounts) != null ? _c : []);
2236
- }
2237
- if (optionalScope) {
2238
- scopeAccounts.push(...(_d = optionalScope.accounts) != null ? _d : []);
2239
- }
2240
- });
2241
- const accounts = [...new Set(scopeAccounts)];
2242
- console.log("\u{1F4DA} SDK connect");
2243
- yield this.metamaskConnectMultichain.connect(
2244
- scopes,
2245
- accounts,
2246
- createSessionParams.sessionProperties
2247
- );
2248
- console.log("\u{1F4DA} SDK connected");
2249
- return this.metamaskConnectMultichain.transport.request({
2250
- method: "wallet_getSession"
2251
- });
2252
- });
2253
- };
2254
- walletGetSession_fn = function(request) {
2255
- return __async(this, null, function* () {
2256
- if (!this.isTransportDefined()) {
2257
- return {
2258
- jsonrpc: "2.0",
2259
- id: request.id,
2260
- result: {
2261
- sessionScopes: {}
2262
- }
2263
- };
2264
- }
2265
- return this.metamaskConnectMultichain.transport.request({
2266
- method: "wallet_getSession"
2267
- });
2268
- });
2269
- };
2270
- walletRevokeSession_fn = function(request) {
2271
- return __async(this, null, function* () {
2272
- if (!this.isTransportDefined()) {
2273
- return { jsonrpc: "2.0", id: request.id, result: true };
2274
- }
2275
- try {
2276
- this.metamaskConnectMultichain.disconnect();
2277
- return { jsonrpc: "2.0", id: request.id, result: true };
2278
- } catch (error) {
2279
- return { jsonrpc: "2.0", id: request.id, result: false };
2280
- }
2281
- });
2282
- };
2283
- walletInvokeMethod_fn = function(request) {
2284
- return __async(this, null, function* () {
2285
- if (!this.isTransportDefined()) {
2286
- return { error: providerErrors.unauthorized() };
2287
- }
2288
- const result = this.metamaskConnectMultichain.invokeMethod(
2289
- request.params
2290
- );
2291
- return {
2292
- result
2293
- };
2294
- });
2295
- };
2296
-
2297
- // src/multichain/index.ts
2527
+ init_utils2();
2298
2528
  var logger2 = createLogger("metamask-sdk:core");
2299
- 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;
2529
+ var SINGLETON_KEY = "__METAMASK_CONNECT_MULTICHAIN_SINGLETON__";
2530
+ 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;
2300
2531
  var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends MultichainCore {
2301
2532
  constructor(options) {
2302
- var _a2, _b, _c, _d, _e, _f;
2533
+ var _a3, _b, _c, _d, _e, _f;
2303
2534
  const withDappMetadata = setupDappMetadata(options);
2304
- const integrationType = (_b = (_a2 = options.analytics) == null ? void 0 : _a2.integrationType) != null ? _b : "direct";
2535
+ const integrationType = (_b = (_a3 = options.analytics) == null ? void 0 : _a3.integrationType) != null ? _b : "direct";
2305
2536
  const allOptions = __spreadProps(__spreadValues({}, withDappMetadata), {
2306
2537
  ui: __spreadProps(__spreadValues({}, withDappMetadata.ui), {
2307
2538
  preferExtension: (_c = withDappMetadata.ui.preferExtension) != null ? _c : true,
@@ -2321,17 +2552,21 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
2321
2552
  __privateAdd(this, _beforeUnloadListener);
2322
2553
  this._status = "pending";
2323
2554
  __privateAdd(this, _listener);
2324
- __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}`);
2325
- __privateSet(this, _providerTransportWrapper, new MultichainApiClientWrapperTransport(this));
2326
- __privateSet(this, _provider, getMultichainClient({ transport: __privateGet(this, _providerTransportWrapper) }));
2555
+ __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}`);
2556
+ __privateSet(this, _providerTransportWrapper, new MultichainApiClientWrapperTransport(
2557
+ this
2558
+ ));
2559
+ __privateSet(this, _provider, getMultichainClient({
2560
+ transport: __privateGet(this, _providerTransportWrapper)
2561
+ }));
2327
2562
  }
2328
2563
  get status() {
2329
2564
  return this._status;
2330
2565
  }
2331
2566
  set status(value) {
2332
- var _a2, _b;
2567
+ var _a3, _b;
2333
2568
  this._status = value;
2334
- (_b = (_a2 = this.options.transport) == null ? void 0 : _a2.onNotification) == null ? void 0 : _b.call(_a2, {
2569
+ (_b = (_a3 = this.options.transport) == null ? void 0 : _a3.onNotification) == null ? void 0 : _b.call(_a3, {
2335
2570
  method: "stateChanged",
2336
2571
  params: value
2337
2572
  });
@@ -2357,27 +2592,54 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
2357
2592
  get transportType() {
2358
2593
  return __privateGet(this, _transport2) instanceof MWPTransport ? "mwp" /* MWP */ : "browser" /* Browser */;
2359
2594
  }
2595
+ // Creates a singleton instance of MetaMaskConnectMultichain.
2596
+ // If the singleton already exists, it merges the incoming options with the
2597
+ // existing singleton options for the following keys: `api.supportedNetworks`,
2598
+ // `ui.*`, `mobile.*`, `transport.extensionId`, `debug`. Take note that the
2599
+ // value for `dapp` is not merged as it does not make sense for subsequent calls to
2600
+ // `createMultichainClient` to have a different `dapp` value.
2360
2601
  static create(options) {
2361
2602
  return __async(this, null, function* () {
2362
- var _a2;
2363
- const instance = new _MetaMaskConnectMultichain(options);
2364
- const isEnabled2 = yield isEnabled(
2365
- "metamask-sdk:core",
2366
- instance.options.storage
2367
- );
2368
- if (isEnabled2) {
2369
- enableDebug("metamask-sdk:core");
2370
- }
2371
- yield __privateMethod(_a2 = instance, _MetaMaskConnectMultichain_instances, init_fn).call(_a2);
2372
- return instance;
2603
+ const globalObject = getGlobalObject();
2604
+ const existing = globalObject[SINGLETON_KEY];
2605
+ if (existing) {
2606
+ const instance = yield existing;
2607
+ instance.mergeOptions(options);
2608
+ if (options.debug) {
2609
+ enableDebug("metamask-sdk:*");
2610
+ }
2611
+ return instance;
2612
+ }
2613
+ const instancePromise = (() => __async(null, null, function* () {
2614
+ var _a3;
2615
+ const instance = new _MetaMaskConnectMultichain(options);
2616
+ const isEnabled2 = yield isEnabled(
2617
+ "metamask-sdk:core",
2618
+ instance.options.storage
2619
+ );
2620
+ if (isEnabled2) {
2621
+ enableDebug("metamask-sdk:core");
2622
+ }
2623
+ yield __privateMethod(_a3 = instance, _MetaMaskConnectMultichain_instances, init_fn).call(_a3);
2624
+ return instance;
2625
+ }))();
2626
+ globalObject[SINGLETON_KEY] = instancePromise;
2627
+ instancePromise.catch((error) => {
2628
+ globalObject[SINGLETON_KEY] = void 0;
2629
+ console.error("Error initializing MetaMaskConnectMultichain", error);
2630
+ });
2631
+ return instancePromise;
2373
2632
  });
2374
2633
  }
2375
2634
  // TODO: make this into param object
2376
2635
  connect(scopes, caipAccountIds, sessionProperties, forceRequest) {
2377
2636
  return __async(this, null, function* () {
2378
- var _a2;
2379
- if (this.status !== "connected") {
2380
- yield this.disconnect();
2637
+ var _a3;
2638
+ if (this.status === "connecting" && this.transportType === "mwp" /* MWP */) {
2639
+ yield __privateMethod(this, _MetaMaskConnectMultichain_instances, openConnectDeeplinkIfNeeded_fn).call(this);
2640
+ throw new Error(
2641
+ "Existing connection is pending. Please check your MetaMask Mobile app to continue."
2642
+ );
2381
2643
  }
2382
2644
  const { ui } = this.options;
2383
2645
  const platformType = getPlatformType();
@@ -2407,9 +2669,21 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
2407
2669
  } catch (error) {
2408
2670
  logger2("Error tracking connection_initiated event", error);
2409
2671
  }
2410
- const nonEmptySessionProperites = Object.keys(sessionProperties != null ? sessionProperties : {}).length > 0 ? sessionProperties : void 0;
2411
- if (((_a2 = __privateGet(this, _transport2)) == null ? void 0 : _a2.isConnected()) && !secure) {
2412
- return __privateMethod(this, _MetaMaskConnectMultichain_instances, handleConnection_fn).call(this, __privateGet(this, _transport2).connect({ scopes, caipAccountIds, sessionProperties: nonEmptySessionProperites, forceRequest }).then(() => __async(this, null, function* () {
2672
+ const sessionData = yield __privateMethod(this, _MetaMaskConnectMultichain_instances, getCaipSession_fn).call(this);
2673
+ const { mergedScopes, mergedCaipAccountIds, mergedSessionProperties } = mergeRequestedSessionWithExisting(
2674
+ sessionData,
2675
+ scopes,
2676
+ caipAccountIds,
2677
+ sessionProperties
2678
+ );
2679
+ const nonEmptySessionProperties = Object.keys(mergedSessionProperties != null ? mergedSessionProperties : {}).length > 0 ? mergedSessionProperties : void 0;
2680
+ if (((_a3 = __privateGet(this, _transport2)) == null ? void 0 : _a3.isConnected()) && !secure) {
2681
+ return __privateMethod(this, _MetaMaskConnectMultichain_instances, handleConnection_fn).call(this, __privateGet(this, _transport2).connect({
2682
+ scopes: mergedScopes,
2683
+ caipAccountIds: mergedCaipAccountIds,
2684
+ sessionProperties: nonEmptySessionProperties,
2685
+ forceRequest
2686
+ }).then(() => __async(this, null, function* () {
2413
2687
  if (__privateGet(this, _transport2) instanceof MWPTransport) {
2414
2688
  return this.storage.setTransport("mwp" /* MWP */);
2415
2689
  }
@@ -2418,38 +2692,54 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
2418
2692
  }
2419
2693
  if (platformType === "in-app-browser" /* MetaMaskMobileWebview */) {
2420
2694
  const defaultTransport = yield __privateMethod(this, _MetaMaskConnectMultichain_instances, setupDefaultTransport_fn).call(this);
2421
- return __privateMethod(this, _MetaMaskConnectMultichain_instances, handleConnection_fn).call(this, defaultTransport.connect({ scopes, caipAccountIds, sessionProperties: nonEmptySessionProperites, forceRequest }), scopes, transportType);
2695
+ return __privateMethod(this, _MetaMaskConnectMultichain_instances, handleConnection_fn).call(this, defaultTransport.connect({
2696
+ scopes: mergedScopes,
2697
+ caipAccountIds: mergedCaipAccountIds,
2698
+ sessionProperties: nonEmptySessionProperties,
2699
+ forceRequest
2700
+ }), scopes, transportType);
2422
2701
  }
2423
2702
  if (isWeb && hasExtensionInstalled && preferExtension) {
2424
2703
  const defaultTransport = yield __privateMethod(this, _MetaMaskConnectMultichain_instances, setupDefaultTransport_fn).call(this);
2425
- return __privateMethod(this, _MetaMaskConnectMultichain_instances, handleConnection_fn).call(this, defaultTransport.connect({ scopes, caipAccountIds, sessionProperties: nonEmptySessionProperites, forceRequest }), scopes, transportType);
2704
+ return __privateMethod(this, _MetaMaskConnectMultichain_instances, handleConnection_fn).call(this, defaultTransport.connect({
2705
+ scopes: mergedScopes,
2706
+ caipAccountIds: mergedCaipAccountIds,
2707
+ sessionProperties: nonEmptySessionProperties,
2708
+ forceRequest
2709
+ }), scopes, transportType);
2426
2710
  }
2427
2711
  yield __privateMethod(this, _MetaMaskConnectMultichain_instances, setupMWP_fn).call(this);
2428
2712
  const shouldShowInstallModal = hasExtensionInstalled ? showInstallModal : !preferExtension || showInstallModal;
2429
2713
  if (secure && !shouldShowInstallModal) {
2430
- return __privateMethod(this, _MetaMaskConnectMultichain_instances, handleConnection_fn).call(this, __privateMethod(this, _MetaMaskConnectMultichain_instances, deeplinkConnect_fn).call(this, scopes, caipAccountIds, nonEmptySessionProperites), scopes, transportType);
2714
+ return __privateMethod(this, _MetaMaskConnectMultichain_instances, handleConnection_fn).call(this, __privateMethod(this, _MetaMaskConnectMultichain_instances, deeplinkConnect_fn).call(this, mergedScopes, mergedCaipAccountIds, nonEmptySessionProperties), scopes, transportType);
2431
2715
  }
2432
- return __privateMethod(this, _MetaMaskConnectMultichain_instances, handleConnection_fn).call(this, __privateMethod(this, _MetaMaskConnectMultichain_instances, showInstallModal_fn).call(this, shouldShowInstallModal, scopes, caipAccountIds, nonEmptySessionProperites), scopes, transportType);
2716
+ return __privateMethod(this, _MetaMaskConnectMultichain_instances, handleConnection_fn).call(this, __privateMethod(this, _MetaMaskConnectMultichain_instances, showInstallModal_fn).call(this, shouldShowInstallModal, mergedScopes, mergedCaipAccountIds, nonEmptySessionProperties), scopes, transportType);
2433
2717
  });
2434
2718
  }
2435
2719
  emit(event, args) {
2436
- var _a2, _b;
2437
- (_b = (_a2 = this.options.transport) == null ? void 0 : _a2.onNotification) == null ? void 0 : _b.call(_a2, { method: event, params: args });
2720
+ var _a3, _b;
2721
+ (_b = (_a3 = this.options.transport) == null ? void 0 : _a3.onNotification) == null ? void 0 : _b.call(_a3, { method: event, params: args });
2438
2722
  super.emit(event, args);
2439
2723
  }
2440
2724
  disconnect() {
2441
- return __async(this, null, function* () {
2442
- var _a2, _b, _c;
2443
- yield (_a2 = __privateGet(this, _listener)) == null ? void 0 : _a2.call(this);
2444
- (_b = __privateGet(this, _beforeUnloadListener)) == null ? void 0 : _b.call(this);
2445
- yield (_c = __privateGet(this, _transport2)) == null ? void 0 : _c.disconnect();
2446
- yield this.storage.removeTransport();
2447
- this.emit("stateChanged", "disconnected");
2448
- __privateSet(this, _listener, void 0);
2449
- __privateSet(this, _beforeUnloadListener, void 0);
2450
- __privateSet(this, _transport2, void 0);
2451
- __privateGet(this, _providerTransportWrapper).clearNotificationCallbacks();
2452
- __privateSet(this, _dappClient, void 0);
2725
+ return __async(this, arguments, function* (scopes = []) {
2726
+ var _a3, _b, _c;
2727
+ const sessionData = yield __privateMethod(this, _MetaMaskConnectMultichain_instances, getCaipSession_fn).call(this);
2728
+ const remainingScopes = scopes.length === 0 ? [] : Object.keys(sessionData.sessionScopes).filter(
2729
+ (scope) => !scopes.includes(scope)
2730
+ );
2731
+ yield (_a3 = __privateGet(this, _transport2)) == null ? void 0 : _a3.disconnect(scopes);
2732
+ if (remainingScopes.length === 0) {
2733
+ yield (_b = __privateGet(this, _listener)) == null ? void 0 : _b.call(this);
2734
+ (_c = __privateGet(this, _beforeUnloadListener)) == null ? void 0 : _c.call(this);
2735
+ yield this.storage.removeTransport();
2736
+ __privateSet(this, _listener, void 0);
2737
+ __privateSet(this, _beforeUnloadListener, void 0);
2738
+ __privateSet(this, _transport2, void 0);
2739
+ __privateGet(this, _providerTransportWrapper).clearTransportNotificationListener();
2740
+ __privateSet(this, _dappClient, void 0);
2741
+ this.status = "disconnected";
2742
+ }
2453
2743
  });
2454
2744
  }
2455
2745
  invokeMethod(request) {
@@ -2461,7 +2751,7 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
2461
2751
  });
2462
2752
  }
2463
2753
  // DRY THIS WITH REQUEST ROUTER
2464
- openDeeplinkIfNeeded() {
2754
+ openSimpleDeeplinkIfNeeded() {
2465
2755
  const { ui, mobile } = this.options;
2466
2756
  const { showInstallModal = false } = ui != null ? ui : {};
2467
2757
  const secure = isSecure();
@@ -2481,6 +2771,23 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
2481
2771
  }), 10);
2482
2772
  }
2483
2773
  }
2774
+ // Provides a way for ecosystem clients (EVM, Solana, etc.) to get the current CAIP session data
2775
+ // when instantiating themselves (as they would have already missed any initial sessionChanged events emitted by ConnectMultichain)
2776
+ // without having to concern themselves with the current transport connection status.
2777
+ emitSessionChanged() {
2778
+ return __async(this, null, function* () {
2779
+ var _a3;
2780
+ const emptySession = { sessionScopes: {} };
2781
+ if (this.status !== "connected" && this.status !== "connecting") {
2782
+ this.emit("wallet_sessionChanged", emptySession);
2783
+ return;
2784
+ }
2785
+ const response = yield this.transport.request({
2786
+ method: "wallet_getSession"
2787
+ });
2788
+ this.emit("wallet_sessionChanged", (_a3 = response.result) != null ? _a3 : emptySession);
2789
+ });
2790
+ }
2484
2791
  };
2485
2792
  _provider = new WeakMap();
2486
2793
  _providerTransportWrapper = new WeakMap();
@@ -2492,7 +2799,7 @@ _sdkInfo = new WeakMap();
2492
2799
  _MetaMaskConnectMultichain_instances = new WeakSet();
2493
2800
  setupAnalytics_fn = function() {
2494
2801
  return __async(this, null, function* () {
2495
- var _a2;
2802
+ var _a3;
2496
2803
  const platform = getPlatformType();
2497
2804
  const isBrowser = platform === "in-app-browser" /* MetaMaskMobileWebview */ || platform === "web-desktop" /* DesktopWeb */ || platform === "web-mobile" /* MobileWeb */;
2498
2805
  const isReactNative2 = platform === "react-native" /* ReactNative */;
@@ -2502,7 +2809,7 @@ setupAnalytics_fn = function() {
2502
2809
  const version = getVersion();
2503
2810
  const dappId = getDappId(this.options.dapp);
2504
2811
  const anonId = yield this.storage.getAnonId();
2505
- const { integrationType } = (_a2 = this.options.analytics) != null ? _a2 : {
2812
+ const { integrationType } = (_a3 = this.options.analytics) != null ? _a3 : {
2506
2813
  integrationType: ""
2507
2814
  };
2508
2815
  analytics2.setGlobalProperty("mmconnect_version", version);
@@ -2515,9 +2822,9 @@ setupAnalytics_fn = function() {
2515
2822
  };
2516
2823
  onTransportNotification_fn = function(payload) {
2517
2824
  return __async(this, null, function* () {
2518
- var _a2;
2825
+ var _a3;
2519
2826
  if (typeof payload === "object" && payload !== null && "method" in payload) {
2520
- this.emit(payload.method, (_a2 = payload.params) != null ? _a2 : payload.result);
2827
+ this.emit(payload.method, (_a3 = payload.params) != null ? _a3 : payload.result);
2521
2828
  }
2522
2829
  });
2523
2830
  };
@@ -2530,7 +2837,7 @@ getStoredTransport_fn = function() {
2530
2837
  if (hasExtensionInstalled) {
2531
2838
  const apiTransport = new DefaultTransport();
2532
2839
  __privateSet(this, _transport2, apiTransport);
2533
- __privateGet(this, _providerTransportWrapper).setupNotifcationListener();
2840
+ __privateGet(this, _providerTransportWrapper).setupTransportNotificationListener();
2534
2841
  __privateSet(this, _listener, apiTransport.onNotification(
2535
2842
  __privateMethod(this, _MetaMaskConnectMultichain_instances, onTransportNotification_fn).bind(this)
2536
2843
  ));
@@ -2542,7 +2849,7 @@ getStoredTransport_fn = function() {
2542
2849
  const apiTransport = new MWPTransport(dappClient, kvstore);
2543
2850
  __privateSet(this, _dappClient, dappClient);
2544
2851
  __privateSet(this, _transport2, apiTransport);
2545
- __privateGet(this, _providerTransportWrapper).setupNotifcationListener();
2852
+ __privateGet(this, _providerTransportWrapper).setupTransportNotificationListener();
2546
2853
  __privateSet(this, _listener, apiTransport.onNotification(
2547
2854
  __privateMethod(this, _MetaMaskConnectMultichain_instances, onTransportNotification_fn).bind(this)
2548
2855
  ));
@@ -2574,25 +2881,17 @@ setupTransport_fn = function() {
2574
2881
  };
2575
2882
  init_fn = function() {
2576
2883
  return __async(this, null, function* () {
2577
- var _a2;
2578
2884
  try {
2579
- if (typeof window !== "undefined" && ((_a2 = window.mmsdk) == null ? void 0 : _a2.isInitialized)) {
2580
- logger2("MetaMaskSDK: init already initialized");
2581
- } else {
2582
- yield __privateMethod(this, _MetaMaskConnectMultichain_instances, setupAnalytics_fn).call(this);
2583
- yield __privateMethod(this, _MetaMaskConnectMultichain_instances, setupTransport_fn).call(this);
2584
- try {
2585
- const baseProps = yield getBaseAnalyticsProperties(
2586
- this.options,
2587
- this.storage
2588
- );
2589
- analytics2.track("mmconnect_initialized", baseProps);
2590
- } catch (error) {
2591
- logger2("Error tracking initialized event", error);
2592
- }
2593
- if (typeof window !== "undefined") {
2594
- window.mmsdk = this;
2595
- }
2885
+ yield __privateMethod(this, _MetaMaskConnectMultichain_instances, setupAnalytics_fn).call(this);
2886
+ yield __privateMethod(this, _MetaMaskConnectMultichain_instances, setupTransport_fn).call(this);
2887
+ try {
2888
+ const baseProps = yield getBaseAnalyticsProperties(
2889
+ this.options,
2890
+ this.storage
2891
+ );
2892
+ analytics2.track("mmconnect_initialized", baseProps);
2893
+ } catch (error) {
2894
+ logger2("Error tracking initialized event", error);
2596
2895
  }
2597
2896
  } catch (error) {
2598
2897
  yield this.storage.removeTransport();
@@ -2628,7 +2927,7 @@ setupMWP_fn = function() {
2628
2927
  __privateSet(this, _dappClient, dappClient);
2629
2928
  const apiTransport = new MWPTransport(dappClient, kvstore);
2630
2929
  __privateSet(this, _transport2, apiTransport);
2631
- __privateGet(this, _providerTransportWrapper).setupNotifcationListener();
2930
+ __privateGet(this, _providerTransportWrapper).setupTransportNotificationListener();
2632
2931
  __privateSet(this, _listener, this.transport.onNotification(
2633
2932
  __privateMethod(this, _MetaMaskConnectMultichain_instances, onTransportNotification_fn).bind(this)
2634
2933
  ));
@@ -2637,22 +2936,20 @@ setupMWP_fn = function() {
2637
2936
  };
2638
2937
  onBeforeUnload_fn = function() {
2639
2938
  return __async(this, null, function* () {
2640
- var _a2;
2641
- if ((_a2 = this.options.ui.factory.modal) == null ? void 0 : _a2.isMounted) {
2939
+ var _a3;
2940
+ if ((_a3 = this.options.ui.factory.modal) == null ? void 0 : _a3.isMounted) {
2642
2941
  yield this.storage.removeTransport();
2643
2942
  }
2644
2943
  });
2645
2944
  };
2646
2945
  createBeforeUnloadListener_fn = function() {
2946
+ const handler = __privateMethod(this, _MetaMaskConnectMultichain_instances, onBeforeUnload_fn).bind(this);
2647
2947
  if (typeof window !== "undefined" && typeof window.addEventListener !== "undefined") {
2648
- window.addEventListener("beforeunload", __privateMethod(this, _MetaMaskConnectMultichain_instances, onBeforeUnload_fn).bind(this));
2948
+ window.addEventListener("beforeunload", handler);
2649
2949
  }
2650
2950
  return () => {
2651
2951
  if (typeof window !== "undefined" && typeof window.removeEventListener !== "undefined") {
2652
- window.removeEventListener(
2653
- "beforeunload",
2654
- __privateMethod(this, _MetaMaskConnectMultichain_instances, onBeforeUnload_fn).bind(this)
2655
- );
2952
+ window.removeEventListener("beforeunload", handler);
2656
2953
  }
2657
2954
  };
2658
2955
  };
@@ -2682,24 +2979,29 @@ renderInstallModalAsync_fn = function(desktopPreferred, scopes, caipAccountIds,
2682
2979
  }
2683
2980
  );
2684
2981
  (() => __async(this, null, function* () {
2685
- var _a2;
2982
+ var _a3;
2686
2983
  try {
2687
- yield this.transport.connect({ scopes, caipAccountIds, sessionProperties });
2984
+ yield this.transport.connect({
2985
+ scopes,
2986
+ caipAccountIds,
2987
+ sessionProperties
2988
+ });
2688
2989
  yield this.options.ui.factory.unload();
2689
- (_a2 = this.options.ui.factory.modal) == null ? void 0 : _a2.unmount();
2990
+ (_a3 = this.options.ui.factory.modal) == null ? void 0 : _a3.unmount();
2690
2991
  this.status = "connected";
2691
2992
  yield this.storage.setTransport("mwp" /* MWP */);
2692
2993
  } catch (error) {
2693
2994
  if (error instanceof ProtocolError) {
2694
2995
  if (error.code !== ErrorCode.REQUEST_EXPIRED) {
2695
2996
  this.status = "disconnected";
2997
+ yield this.options.ui.factory.unload(error);
2696
2998
  reject(error);
2697
2999
  }
2698
3000
  } else {
2699
3001
  this.status = "disconnected";
2700
- reject(
2701
- error instanceof Error ? error : new Error(String(error))
2702
- );
3002
+ const normalizedError = error instanceof Error ? error : new Error(String(error));
3003
+ yield this.options.ui.factory.unload(normalizedError);
3004
+ reject(normalizedError);
2703
3005
  }
2704
3006
  }
2705
3007
  }))().catch(() => {
@@ -2726,8 +3028,8 @@ renderInstallModalAsync_fn = function(desktopPreferred, scopes, caipAccountIds,
2726
3028
  };
2727
3029
  showInstallModal_fn = function(desktopPreferred, scopes, caipAccountIds, sessionProperties) {
2728
3030
  return __async(this, null, function* () {
2729
- var _a2;
2730
- (_a2 = __privateGet(this, _beforeUnloadListener)) != null ? _a2 : __privateSet(this, _beforeUnloadListener, __privateMethod(this, _MetaMaskConnectMultichain_instances, createBeforeUnloadListener_fn).call(this));
3031
+ var _a3;
3032
+ (_a3 = __privateGet(this, _beforeUnloadListener)) != null ? _a3 : __privateSet(this, _beforeUnloadListener, __privateMethod(this, _MetaMaskConnectMultichain_instances, createBeforeUnloadListener_fn).call(this));
2731
3033
  if (this.options.ui.headless) {
2732
3034
  yield __privateMethod(this, _MetaMaskConnectMultichain_instances, headlessConnect_fn).call(this, scopes, caipAccountIds, sessionProperties);
2733
3035
  } else {
@@ -2786,15 +3088,15 @@ setupDefaultTransport_fn = function() {
2786
3088
  __privateMethod(this, _MetaMaskConnectMultichain_instances, onTransportNotification_fn).bind(this)
2787
3089
  ));
2788
3090
  __privateSet(this, _transport2, transport);
2789
- __privateGet(this, _providerTransportWrapper).setupNotifcationListener();
3091
+ __privateGet(this, _providerTransportWrapper).setupTransportNotificationListener();
2790
3092
  return transport;
2791
3093
  });
2792
3094
  };
2793
3095
  deeplinkConnect_fn = function(scopes, caipAccountIds, sessionProperties) {
2794
3096
  return __async(this, null, function* () {
2795
- return new Promise((resolve, reject) => {
3097
+ return new Promise((resolve, reject) => __async(this, null, function* () {
2796
3098
  const dappClientMessageHandler = (payload) => {
2797
- var _a2;
3099
+ var _a3;
2798
3100
  if (typeof payload !== "object" || payload === null || !("data" in payload)) {
2799
3101
  return;
2800
3102
  }
@@ -2804,7 +3106,7 @@ deeplinkConnect_fn = function(scopes, caipAccountIds, sessionProperties) {
2804
3106
  this.dappClient.off("message", dappClientMessageHandler);
2805
3107
  reject(data.error);
2806
3108
  }
2807
- if ((_a2 = data == null ? void 0 : data.result) == null ? void 0 : _a2.sessionScopes) {
3109
+ if ((_a3 = data == null ? void 0 : data.result) == null ? void 0 : _a3.sessionScopes) {
2808
3110
  this.dappClient.off("message", dappClientMessageHandler);
2809
3111
  }
2810
3112
  }
@@ -2813,13 +3115,13 @@ deeplinkConnect_fn = function(scopes, caipAccountIds, sessionProperties) {
2813
3115
  let timeout;
2814
3116
  if (this.transport.isConnected()) {
2815
3117
  timeout = setTimeout(() => {
2816
- this.openDeeplinkIfNeeded();
3118
+ this.openSimpleDeeplinkIfNeeded();
2817
3119
  }, 250);
2818
3120
  } else {
2819
3121
  this.dappClient.once(
2820
3122
  "session_request",
2821
3123
  (sessionRequest) => {
2822
- var _a2;
3124
+ var _a3;
2823
3125
  const connectionRequest = {
2824
3126
  sessionRequest,
2825
3127
  metadata: {
@@ -2834,7 +3136,7 @@ deeplinkConnect_fn = function(scopes, caipAccountIds, sessionProperties) {
2834
3136
  connectionRequest
2835
3137
  );
2836
3138
  this.emit("display_uri", deeplink);
2837
- if ((_a2 = this.options.mobile) == null ? void 0 : _a2.preferredOpenLink) {
3139
+ if ((_a3 = this.options.mobile) == null ? void 0 : _a3.preferredOpenLink) {
2838
3140
  this.options.mobile.preferredOpenLink(deeplink, "_self");
2839
3141
  } else {
2840
3142
  openDeeplink(this.options, deeplink, universalLink);
@@ -2851,7 +3153,7 @@ deeplinkConnect_fn = function(scopes, caipAccountIds, sessionProperties) {
2851
3153
  clearTimeout(timeout);
2852
3154
  }
2853
3155
  });
2854
- });
3156
+ }));
2855
3157
  });
2856
3158
  };
2857
3159
  handleConnection_fn = function(promise, scopes, transportType) {
@@ -2896,6 +3198,53 @@ handleConnection_fn = function(promise, scopes, transportType) {
2896
3198
  }));
2897
3199
  });
2898
3200
  };
3201
+ getCaipSession_fn = function() {
3202
+ return __async(this, null, function* () {
3203
+ let sessionData = {
3204
+ sessionScopes: {},
3205
+ sessionProperties: {}
3206
+ };
3207
+ if (this.status === "connected") {
3208
+ const response = yield this.transport.request({
3209
+ method: "wallet_getSession"
3210
+ });
3211
+ if (response.result) {
3212
+ sessionData = response.result;
3213
+ }
3214
+ }
3215
+ return sessionData;
3216
+ });
3217
+ };
3218
+ openConnectDeeplinkIfNeeded_fn = function() {
3219
+ return __async(this, null, function* () {
3220
+ var _a3, _b;
3221
+ const { ui } = this.options;
3222
+ const { showInstallModal = false } = ui != null ? ui : {};
3223
+ const secure = isSecure();
3224
+ const shouldOpenDeeplink = secure && !showInstallModal;
3225
+ if (!shouldOpenDeeplink) {
3226
+ return;
3227
+ }
3228
+ const storedSessionRequest = yield (_a3 = __privateGet(this, _transport2)) == null ? void 0 : _a3.getStoredPendingSessionRequest();
3229
+ if (!storedSessionRequest) {
3230
+ return;
3231
+ }
3232
+ const connectionRequest = {
3233
+ sessionRequest: storedSessionRequest,
3234
+ metadata: {
3235
+ dapp: this.options.dapp,
3236
+ sdk: { version: getVersion(), platform: getPlatformType() }
3237
+ }
3238
+ };
3239
+ const deeplink = this.options.ui.factory.createConnectionDeeplink(connectionRequest);
3240
+ const universalLink = this.options.ui.factory.createConnectionUniversalLink(connectionRequest);
3241
+ if ((_b = this.options.mobile) == null ? void 0 : _b.preferredOpenLink) {
3242
+ this.options.mobile.preferredOpenLink(deeplink, "_self");
3243
+ } else {
3244
+ openDeeplink(this.options, deeplink, universalLink);
3245
+ }
3246
+ });
3247
+ };
2899
3248
  var MetaMaskConnectMultichain = _MetaMaskConnectMultichain;
2900
3249
 
2901
3250
  // src/store/index.ts
@@ -3080,7 +3429,7 @@ var Store = class extends StoreClient {
3080
3429
  // src/ui/ModalFactory.ts
3081
3430
  import MetaMaskOnboarding from "@metamask/onboarding";
3082
3431
  init_domain();
3083
- init_utils();
3432
+ init_utils2();
3084
3433
  var BaseModalFactory = class {
3085
3434
  /**
3086
3435
  * Creates a new modal factory instance.
@@ -3103,8 +3452,8 @@ var BaseModalFactory = class {
3103
3452
  }
3104
3453
  unload(error) {
3105
3454
  return __async(this, null, function* () {
3106
- var _a2, _b;
3107
- (_a2 = this.modal) == null ? void 0 : _a2.unmount();
3455
+ var _a3, _b;
3456
+ (_a3 = this.modal) == null ? void 0 : _a3.unmount();
3108
3457
  yield (_b = this.successCallback) == null ? void 0 : _b.call(this, error);
3109
3458
  });
3110
3459
  }
@@ -3144,7 +3493,9 @@ var BaseModalFactory = class {
3144
3493
  }
3145
3494
  createConnectionDeeplink(connectionRequest) {
3146
3495
  if (!connectionRequest) {
3147
- throw new Error("createConnectionDeeplink can only be called with a connection request");
3496
+ throw new Error(
3497
+ "createConnectionDeeplink can only be called with a connection request"
3498
+ );
3148
3499
  }
3149
3500
  const json = JSON.stringify(connectionRequest);
3150
3501
  const compressed = compressString(json);
@@ -3172,8 +3523,8 @@ var BaseModalFactory = class {
3172
3523
  }
3173
3524
  renderInstallModal(showInstallModal, createConnectionRequest, successCallback, onDisplayUri) {
3174
3525
  return __async(this, null, function* () {
3175
- var _a2, _b;
3176
- (_a2 = this.modal) == null ? void 0 : _a2.unmount();
3526
+ var _a3, _b;
3527
+ (_a3 = this.modal) == null ? void 0 : _a3.unmount();
3177
3528
  yield this.preload();
3178
3529
  this.successCallback = successCallback;
3179
3530
  this.displayUriCallback = onDisplayUri;
@@ -3189,9 +3540,9 @@ var BaseModalFactory = class {
3189
3540
  link: qrCodeLink,
3190
3541
  sdkVersion: getVersion(),
3191
3542
  generateQRCode: (request) => __async(this, null, function* () {
3192
- var _a3;
3543
+ var _a4;
3193
3544
  const newLink = this.createConnectionDeeplink(request);
3194
- (_a3 = this.displayUriCallback) == null ? void 0 : _a3.call(this, newLink);
3545
+ (_a4 = this.displayUriCallback) == null ? void 0 : _a4.call(this, newLink);
3195
3546
  return newLink;
3196
3547
  }),
3197
3548
  onClose: this.onCloseModal.bind(this),
@@ -3205,8 +3556,8 @@ var BaseModalFactory = class {
3205
3556
  }
3206
3557
  renderOTPCodeModal(createOTPCode, successCallback, updateOTPCode) {
3207
3558
  return __async(this, null, function* () {
3208
- var _a2;
3209
- (_a2 = this.modal) == null ? void 0 : _a2.unmount();
3559
+ var _a3;
3560
+ (_a3 = this.modal) == null ? void 0 : _a3.unmount();
3210
3561
  yield this.preload();
3211
3562
  this.successCallback = successCallback;
3212
3563
  const container = this.getMountedContainer();
@@ -3237,14 +3588,17 @@ var ModalFactory = class extends BaseModalFactory {
3237
3588
  // src/index.native.ts
3238
3589
  init_domain();
3239
3590
  var createMultichainClient = (options) => __async(null, null, function* () {
3591
+ if (options.debug) {
3592
+ enableDebug("metamask-sdk:*");
3593
+ }
3240
3594
  const uiModules = yield Promise.resolve().then(() => (init_rn(), rn_exports));
3241
3595
  let storage;
3242
- if (!options.storage) {
3596
+ if (options.storage) {
3597
+ storage = options.storage;
3598
+ } else {
3243
3599
  const { StoreAdapterRN: StoreAdapterRN2 } = yield Promise.resolve().then(() => (init_rn2(), rn_exports2));
3244
3600
  const adapter = new StoreAdapterRN2();
3245
3601
  storage = new Store(adapter);
3246
- } else {
3247
- storage = options.storage;
3248
3602
  }
3249
3603
  const factory = new ModalFactory(uiModules);
3250
3604
  return MetaMaskConnectMultichain.create(__spreadProps(__spreadValues({}, options), {