@metamask/connect-multichain 0.5.3 → 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 (60) hide show
  1. package/CHANGELOG.md +27 -1
  2. package/README.md +9 -3
  3. package/dist/browser/es/connect-multichain.d.mts +27 -4
  4. package/dist/browser/es/connect-multichain.mjs +603 -333
  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 +27 -4
  8. package/dist/browser/iife/connect-multichain.js +3363 -2993
  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 +27 -4
  12. package/dist/browser/umd/connect-multichain.js +603 -333
  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 +27 -4
  16. package/dist/node/cjs/connect-multichain.js +421 -151
  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 +27 -4
  20. package/dist/node/es/connect-multichain.mjs +421 -151
  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 +27 -4
  24. package/dist/react-native/es/connect-multichain.mjs +596 -326
  25. package/dist/react-native/es/connect-multichain.mjs.map +1 -1
  26. package/dist/react-native/es/metafile-esm.json +1 -1
  27. package/dist/src/domain/multichain/index.d.ts +15 -4
  28. package/dist/src/domain/multichain/index.d.ts.map +1 -1
  29. package/dist/src/domain/multichain/index.js +14 -0
  30. package/dist/src/domain/multichain/index.js.map +1 -1
  31. package/dist/src/domain/multichain/types.d.ts +12 -0
  32. package/dist/src/domain/multichain/types.d.ts.map +1 -1
  33. package/dist/src/multichain/index.d.ts +3 -2
  34. package/dist/src/multichain/index.d.ts.map +1 -1
  35. package/dist/src/multichain/index.js +158 -61
  36. package/dist/src/multichain/index.js.map +1 -1
  37. package/dist/src/multichain/transports/default/index.d.ts +3 -1
  38. package/dist/src/multichain/transports/default/index.d.ts.map +1 -1
  39. package/dist/src/multichain/transports/default/index.js +17 -11
  40. package/dist/src/multichain/transports/default/index.js.map +1 -1
  41. package/dist/src/multichain/transports/multichainApiClientWrapper/index.d.ts +3 -1
  42. package/dist/src/multichain/transports/multichainApiClientWrapper/index.d.ts.map +1 -1
  43. package/dist/src/multichain/transports/multichainApiClientWrapper/index.js +28 -31
  44. package/dist/src/multichain/transports/multichainApiClientWrapper/index.js.map +1 -1
  45. package/dist/src/multichain/transports/mwp/index.d.ts +15 -2
  46. package/dist/src/multichain/transports/mwp/index.d.ts.map +1 -1
  47. package/dist/src/multichain/transports/mwp/index.js +155 -38
  48. package/dist/src/multichain/transports/mwp/index.js.map +1 -1
  49. package/dist/src/multichain/utils/index.d.ts +23 -0
  50. package/dist/src/multichain/utils/index.d.ts.map +1 -1
  51. package/dist/src/multichain/utils/index.js +57 -4
  52. package/dist/src/multichain/utils/index.js.map +1 -1
  53. package/dist/src/polyfills/buffer-shim.js +4 -14
  54. package/dist/src/polyfills/buffer-shim.js.map +1 -1
  55. package/dist/src/store/adapters/web.d.ts +1 -1
  56. package/dist/src/store/adapters/web.d.ts.map +1 -1
  57. package/dist/src/store/adapters/web.js +1 -1
  58. package/dist/src/store/adapters/web.js.map +1 -1
  59. package/dist/types/connect-multichain.d.ts +27 -4
  60. package/package.json +1 -1
@@ -34,14 +34,6 @@ var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read fr
34
34
  var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
35
35
  var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
36
36
  var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
37
- var __privateWrapper = (obj, member, setter, getter) => ({
38
- set _(value) {
39
- __privateSet(obj, member, value, setter);
40
- },
41
- get _() {
42
- return __privateGet(obj, member, getter);
43
- }
44
- });
45
37
  var __async = (__this, __arguments, generator) => {
46
38
  return new Promise((resolve, reject) => {
47
39
  var fulfilled = (value) => {
@@ -243,8 +235,8 @@ var init_logger = __esm({
243
235
  debug.enable(namespace);
244
236
  };
245
237
  isEnabled = (namespace, storage) => __async(null, null, function* () {
246
- var _a2;
247
- if ("process" in globalThis && ((_a2 = process == null ? void 0 : process.env) == null ? void 0 : _a2.DEBUG)) {
238
+ var _a3;
239
+ if ("process" in globalThis && ((_a3 = process == null ? void 0 : process.env) == null ? void 0 : _a3.DEBUG)) {
248
240
  const { DEBUG } = process.env;
249
241
  return isNamespaceEnabled(DEBUG, namespace);
250
242
  }
@@ -407,6 +399,34 @@ var init_multichain = __esm({
407
399
  super();
408
400
  this.options = options;
409
401
  }
402
+ /**
403
+ * Merges the given options into the current instance options.
404
+ * Only the mergeable keys are updated (api.supportedNetworks, ui.*, mobile.*, transport.extensionId, debug).
405
+ * The main thing to note is that the value for `dapp` is not merged as it does not make sense for
406
+ * subsequent calls to `createMultichainClient` to have a different `dapp` value.
407
+ * Used when createMultichainClient is called with an existing singleton.
408
+ *
409
+ * @param partial - Options to merge/overwrite onto the current instance
410
+ */
411
+ mergeOptions(partial) {
412
+ var _a3, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n;
413
+ const opts = this.options;
414
+ this.options = __spreadProps(__spreadValues({}, opts), {
415
+ api: __spreadProps(__spreadValues({}, opts.api), {
416
+ supportedNetworks: __spreadValues(__spreadValues({}, opts.api.supportedNetworks), (_b = (_a3 = partial.api) == null ? void 0 : _a3.supportedNetworks) != null ? _b : {})
417
+ }),
418
+ ui: __spreadProps(__spreadValues({}, opts.ui), {
419
+ headless: (_d = (_c = partial.ui) == null ? void 0 : _c.headless) != null ? _d : opts.ui.headless,
420
+ preferExtension: (_f = (_e = partial.ui) == null ? void 0 : _e.preferExtension) != null ? _f : opts.ui.preferExtension,
421
+ showInstallModal: (_h = (_g = partial.ui) == null ? void 0 : _g.showInstallModal) != null ? _h : opts.ui.showInstallModal
422
+ }),
423
+ mobile: __spreadValues(__spreadValues({}, opts.mobile), (_i = partial.mobile) != null ? _i : {}),
424
+ transport: __spreadProps(__spreadValues({}, (_j = opts.transport) != null ? _j : {}), {
425
+ extensionId: (_m = (_k = partial.transport) == null ? void 0 : _k.extensionId) != null ? _m : (_l = opts.transport) == null ? void 0 : _l.extensionId
426
+ }),
427
+ debug: (_n = partial.debug) != null ? _n : opts.debug
428
+ });
429
+ }
410
430
  };
411
431
  }
412
432
  });
@@ -414,35 +434,35 @@ var init_multichain = __esm({
414
434
  // src/domain/platform/index.ts
415
435
  import Bowser from "bowser";
416
436
  function isNotBrowser() {
417
- var _a2;
437
+ var _a3;
418
438
  if (typeof window === "undefined") {
419
439
  return true;
420
440
  }
421
441
  if (!(window == null ? void 0 : window.navigator)) {
422
442
  return true;
423
443
  }
424
- if (typeof global !== "undefined" && ((_a2 = global == null ? void 0 : global.navigator) == null ? void 0 : _a2.product) === "ReactNative") {
444
+ if (typeof global !== "undefined" && ((_a3 = global == null ? void 0 : global.navigator) == null ? void 0 : _a3.product) === "ReactNative") {
425
445
  return true;
426
446
  }
427
447
  return (navigator == null ? void 0 : navigator.product) === "ReactNative";
428
448
  }
429
449
  function isReactNative() {
430
- var _a2;
450
+ var _a3;
431
451
  const hasWindowNavigator = typeof window !== "undefined" && window.navigator !== void 0;
432
452
  const nav = hasWindowNavigator ? window.navigator : void 0;
433
453
  if (!nav) {
434
454
  return false;
435
455
  }
436
- return hasWindowNavigator && ((_a2 = window.navigator) == null ? void 0 : _a2.product) === "ReactNative";
456
+ return hasWindowNavigator && ((_a3 = window.navigator) == null ? void 0 : _a3.product) === "ReactNative";
437
457
  }
438
458
  function isMetaMaskMobileWebView() {
439
459
  return typeof window !== "undefined" && // @ts-expect-error ReactNativeWebView should be defined
440
460
  Boolean(window.ReactNativeWebView) && Boolean(window.navigator.userAgent.endsWith("MetaMaskMobile"));
441
461
  }
442
462
  function isMobile() {
443
- var _a2, _b;
463
+ var _a3, _b;
444
464
  const browser = Bowser.parse(window.navigator.userAgent);
445
- return ((_a2 = browser == null ? void 0 : browser.platform) == null ? void 0 : _a2.type) === "mobile" || ((_b = browser == null ? void 0 : browser.platform) == null ? void 0 : _b.type) === "tablet";
465
+ return ((_a3 = browser == null ? void 0 : browser.platform) == null ? void 0 : _a3.type) === "mobile" || ((_b = browser == null ? void 0 : browser.platform) == null ? void 0 : _b.type) === "tablet";
446
466
  }
447
467
  function getPlatformType() {
448
468
  if (isReactNative()) {
@@ -460,11 +480,11 @@ function getPlatformType() {
460
480
  return "web-desktop" /* DesktopWeb */;
461
481
  }
462
482
  function isMetamaskExtensionInstalled() {
463
- var _a2;
483
+ var _a3;
464
484
  if (typeof window === "undefined") {
465
485
  return false;
466
486
  }
467
- return Boolean((_a2 = window.ethereum) == null ? void 0 : _a2.isMetaMask);
487
+ return Boolean((_a3 = window.ethereum) == null ? void 0 : _a3.isMetaMask);
468
488
  }
469
489
  function isSecure() {
470
490
  const platformType = getPlatformType();
@@ -495,8 +515,8 @@ var init_platform = __esm({
495
515
  return new Promise((resolve) => {
496
516
  const providers = [];
497
517
  const handler = (event) => {
498
- var _a2, _b;
499
- if ((_b = (_a2 = event == null ? void 0 : event.detail) == null ? void 0 : _a2.info) == null ? void 0 : _b.rdns) {
518
+ var _a3, _b;
519
+ if ((_b = (_a3 = event == null ? void 0 : event.detail) == null ? void 0 : _a3.info) == null ? void 0 : _b.rdns) {
500
520
  providers.push(event.detail);
501
521
  }
502
522
  };
@@ -506,8 +526,8 @@ var init_platform = __esm({
506
526
  window.removeEventListener("eip6963:announceProvider", handler);
507
527
  const hasMetaMask = providers.some(
508
528
  (provider) => {
509
- var _a2, _b;
510
- return (_b = (_a2 = provider == null ? void 0 : provider.info) == null ? void 0 : _a2.rdns) == null ? void 0 : _b.startsWith("io.metamask");
529
+ var _a3, _b;
530
+ return (_b = (_a3 = provider == null ? void 0 : provider.info) == null ? void 0 : _a3.rdns) == null ? void 0 : _b.startsWith("io.metamask");
511
531
  }
512
532
  );
513
533
  resolve(hasMetaMask);
@@ -591,12 +611,108 @@ var init_ui = __esm({
591
611
  }
592
612
  });
593
613
 
614
+ // src/multichain/utils/analytics.ts
615
+ function isRejectionError(error) {
616
+ var _a3, _b;
617
+ if (typeof error !== "object" || error === null) {
618
+ return false;
619
+ }
620
+ const errorObj = error;
621
+ const errorCode = errorObj.code;
622
+ const errorMessage = (_b = (_a3 = errorObj.message) == null ? void 0 : _a3.toLowerCase()) != null ? _b : "";
623
+ return errorCode === 4001 || // User rejected request (common EIP-1193 code)
624
+ errorCode === 4100 || // Unauthorized (common rejection code)
625
+ errorMessage.includes("reject") || errorMessage.includes("denied") || errorMessage.includes("cancel") || errorMessage.includes("user");
626
+ }
627
+ function getBaseAnalyticsProperties(options, storage) {
628
+ return __async(this, null, function* () {
629
+ var _a3, _b;
630
+ const version = getVersion();
631
+ const dappId = getDappId(options.dapp);
632
+ const platform = getPlatformType();
633
+ const anonId = yield storage.getAnonId();
634
+ const integrationType = (_b = (_a3 = options.analytics) == null ? void 0 : _a3.integrationType) != null ? _b : "unknown" /* UNKNOWN */;
635
+ return {
636
+ mmconnect_version: version,
637
+ dapp_id: dappId,
638
+ platform,
639
+ integration_type: integrationType,
640
+ anon_id: anonId
641
+ };
642
+ });
643
+ }
644
+ function getWalletActionAnalyticsProperties(options, storage, invokeOptions) {
645
+ return __async(this, null, function* () {
646
+ var _a3, _b;
647
+ const version = getVersion();
648
+ const dappId = getDappId(options.dapp);
649
+ const anonId = yield storage.getAnonId();
650
+ const integrationType = (_b = (_a3 = options.analytics) == null ? void 0 : _a3.integrationType) != null ? _b : "unknown";
651
+ return {
652
+ mmconnect_version: version,
653
+ dapp_id: dappId,
654
+ method: invokeOptions.request.method,
655
+ integration_type: integrationType,
656
+ caip_chain_id: invokeOptions.scope,
657
+ anon_id: anonId
658
+ };
659
+ });
660
+ }
661
+ var init_analytics = __esm({
662
+ "src/multichain/utils/analytics.ts"() {
663
+ "use strict";
664
+ init_utils2();
665
+ init_domain();
666
+ }
667
+ });
668
+
669
+ // src/domain/utils/index.ts
670
+ function getVersion() {
671
+ return "0.0.0";
672
+ }
673
+ var init_utils = __esm({
674
+ "src/domain/utils/index.ts"() {
675
+ "use strict";
676
+ init_analytics();
677
+ }
678
+ });
679
+
680
+ // src/domain/index.ts
681
+ var init_domain = __esm({
682
+ "src/domain/index.ts"() {
683
+ "use strict";
684
+ init_errors();
685
+ init_events();
686
+ init_logger();
687
+ init_multichain();
688
+ init_platform();
689
+ init_store();
690
+ init_ui();
691
+ init_utils();
692
+ }
693
+ });
694
+
594
695
  // src/multichain/utils/index.ts
595
696
  import {
596
697
  parseCaipAccountId,
597
698
  parseCaipChainId
598
699
  } from "@metamask/utils";
599
700
  import { deflate } from "pako";
701
+ function getGlobalObject() {
702
+ if (typeof globalThis !== "undefined") {
703
+ return globalThis;
704
+ }
705
+ if (typeof global !== "undefined") {
706
+ return global;
707
+ }
708
+ if (typeof self !== "undefined") {
709
+ return self;
710
+ }
711
+ if (typeof window !== "undefined") {
712
+ return window;
713
+ }
714
+ throw new Error("Unable to locate global object");
715
+ }
600
716
  function base64Encode(str) {
601
717
  if (typeof btoa !== "undefined") {
602
718
  return btoa(str);
@@ -611,13 +727,13 @@ function compressString(str) {
611
727
  return base64Encode(binaryString);
612
728
  }
613
729
  function getDappId(dapp) {
614
- var _a2;
615
- return (_a2 = dapp.url) != null ? _a2 : dapp.name;
730
+ var _a3;
731
+ return (_a3 = dapp.url) != null ? _a3 : dapp.name;
616
732
  }
617
733
  function openDeeplink(options, deeplink, universalLink) {
618
- var _a2;
734
+ var _a3;
619
735
  const { mobile } = options;
620
- const useDeeplink = (_a2 = mobile == null ? void 0 : mobile.useDeeplink) != null ? _a2 : true;
736
+ const useDeeplink = (_a3 = mobile == null ? void 0 : mobile.useDeeplink) != null ? _a3 : true;
621
737
  if (useDeeplink) {
622
738
  if (typeof window !== "undefined") {
623
739
  window.location.href = deeplink;
@@ -630,6 +746,29 @@ function openDeeplink(options, deeplink, universalLink) {
630
746
  link.click();
631
747
  }
632
748
  }
749
+ function mergeRequestedSessionWithExisting(sessionData, scopes, caipAccountIds, sessionProperties) {
750
+ const existingCaipChainIds = Object.keys(sessionData.sessionScopes);
751
+ const existingCaipAccountIds = [];
752
+ Object.values(sessionData.sessionScopes).forEach((scopeObject) => {
753
+ if ((scopeObject == null ? void 0 : scopeObject.accounts) && Array.isArray(scopeObject.accounts)) {
754
+ scopeObject.accounts.forEach((account) => {
755
+ existingCaipAccountIds.push(account);
756
+ });
757
+ }
758
+ });
759
+ const mergedScopes = Array.from(
760
+ /* @__PURE__ */ new Set([...existingCaipChainIds, ...scopes])
761
+ );
762
+ const mergedCaipAccountIds = Array.from(
763
+ /* @__PURE__ */ new Set([...existingCaipAccountIds, ...caipAccountIds])
764
+ );
765
+ const mergedSessionProperties = __spreadValues(__spreadValues({}, sessionData.sessionProperties), sessionProperties);
766
+ return {
767
+ mergedScopes,
768
+ mergedCaipAccountIds,
769
+ mergedSessionProperties
770
+ };
771
+ }
633
772
  function getOptionalScopes(scopes) {
634
773
  return scopes.reduce(
635
774
  (prev, scope) => __spreadProps(__spreadValues({}, prev), {
@@ -643,10 +782,10 @@ function getOptionalScopes(scopes) {
643
782
  );
644
783
  }
645
784
  function setupDappMetadata(options) {
646
- var _a2, _b;
785
+ var _a3, _b;
647
786
  const platform = getPlatformType();
648
787
  const isBrowser = platform === "web-desktop" /* DesktopWeb */ || platform === "web-mobile" /* MobileWeb */ || platform === "in-app-browser" /* MetaMaskMobileWebview */;
649
- if (!((_a2 = options.dapp) == null ? void 0 : _a2.name)) {
788
+ if (!((_a3 = options.dapp) == null ? void 0 : _a3.name)) {
650
789
  throw new Error("You must provide dapp name");
651
790
  }
652
791
  if (isBrowser) {
@@ -720,17 +859,17 @@ function getValidAccounts(caipAccountIds) {
720
859
  );
721
860
  }
722
861
  function addValidAccounts(optionalScopes, validAccounts) {
723
- var _a2;
862
+ var _a3;
724
863
  if (!optionalScopes || !(validAccounts == null ? void 0 : validAccounts.length)) {
725
864
  return optionalScopes;
726
865
  }
727
866
  const result = Object.fromEntries(
728
867
  Object.entries(optionalScopes).map(([scope, scopeData]) => {
729
- var _a3, _b, _c;
868
+ var _a4, _b, _c;
730
869
  return [
731
870
  scope,
732
871
  {
733
- methods: [...(_a3 = scopeData == null ? void 0 : scopeData.methods) != null ? _a3 : []],
872
+ methods: [...(_a4 = scopeData == null ? void 0 : scopeData.methods) != null ? _a4 : []],
734
873
  notifications: [...(_b = scopeData == null ? void 0 : scopeData.notifications) != null ? _b : []],
735
874
  accounts: [...(_c = scopeData == null ? void 0 : scopeData.accounts) != null ? _c : []]
736
875
  }
@@ -744,7 +883,7 @@ function addValidAccounts(optionalScopes, validAccounts) {
744
883
  if (!accountsByChain.has(chainKey)) {
745
884
  accountsByChain.set(chainKey, []);
746
885
  }
747
- (_a2 = accountsByChain.get(chainKey)) == null ? void 0 : _a2.push(accountId);
886
+ (_a3 = accountsByChain.get(chainKey)) == null ? void 0 : _a3.push(accountId);
748
887
  }
749
888
  for (const [scopeKey, scopeData] of Object.entries(result)) {
750
889
  if (!(scopeData == null ? void 0 : scopeData.accounts)) {
@@ -768,13 +907,13 @@ function addValidAccounts(optionalScopes, validAccounts) {
768
907
  }
769
908
  return result;
770
909
  }
771
- var extractFavicon;
772
- var init_utils = __esm({
910
+ var extractFavicon, MAX, idCounter, getUniqueRequestId;
911
+ var init_utils2 = __esm({
773
912
  "src/multichain/utils/index.ts"() {
774
913
  "use strict";
775
914
  init_domain();
776
915
  extractFavicon = () => {
777
- var _a2;
916
+ var _a3;
778
917
  if (typeof document === "undefined") {
779
918
  return void 0;
780
919
  }
@@ -782,92 +921,17 @@ var init_utils = __esm({
782
921
  const nodeList = document.getElementsByTagName("link");
783
922
  for (let i = 0; i < nodeList.length; i++) {
784
923
  if (nodeList[i].getAttribute("rel") === "icon" || nodeList[i].getAttribute("rel") === "shortcut icon") {
785
- favicon = (_a2 = nodeList[i].getAttribute("href")) != null ? _a2 : void 0;
924
+ favicon = (_a3 = nodeList[i].getAttribute("href")) != null ? _a3 : void 0;
786
925
  }
787
926
  }
788
927
  return favicon;
789
928
  };
790
- }
791
- });
792
-
793
- // src/multichain/utils/analytics.ts
794
- function isRejectionError(error) {
795
- var _a2, _b;
796
- if (typeof error !== "object" || error === null) {
797
- return false;
798
- }
799
- const errorObj = error;
800
- const errorCode = errorObj.code;
801
- const errorMessage = (_b = (_a2 = errorObj.message) == null ? void 0 : _a2.toLowerCase()) != null ? _b : "";
802
- return errorCode === 4001 || // User rejected request (common EIP-1193 code)
803
- errorCode === 4100 || // Unauthorized (common rejection code)
804
- errorMessage.includes("reject") || errorMessage.includes("denied") || errorMessage.includes("cancel") || errorMessage.includes("user");
805
- }
806
- function getBaseAnalyticsProperties(options, storage) {
807
- return __async(this, null, function* () {
808
- var _a2, _b;
809
- const version = getVersion();
810
- const dappId = getDappId(options.dapp);
811
- const platform = getPlatformType();
812
- const anonId = yield storage.getAnonId();
813
- const integrationType = (_b = (_a2 = options.analytics) == null ? void 0 : _a2.integrationType) != null ? _b : "unknown" /* UNKNOWN */;
814
- return {
815
- mmconnect_version: version,
816
- dapp_id: dappId,
817
- platform,
818
- integration_type: integrationType,
819
- anon_id: anonId
929
+ MAX = 4294967295;
930
+ idCounter = Math.floor(Math.random() * MAX);
931
+ getUniqueRequestId = () => {
932
+ idCounter = (idCounter + 1) % MAX;
933
+ return idCounter;
820
934
  };
821
- });
822
- }
823
- function getWalletActionAnalyticsProperties(options, storage, invokeOptions) {
824
- return __async(this, null, function* () {
825
- var _a2, _b;
826
- const version = getVersion();
827
- const dappId = getDappId(options.dapp);
828
- const anonId = yield storage.getAnonId();
829
- const integrationType = (_b = (_a2 = options.analytics) == null ? void 0 : _a2.integrationType) != null ? _b : "unknown";
830
- return {
831
- mmconnect_version: version,
832
- dapp_id: dappId,
833
- method: invokeOptions.request.method,
834
- integration_type: integrationType,
835
- caip_chain_id: invokeOptions.scope,
836
- anon_id: anonId
837
- };
838
- });
839
- }
840
- var init_analytics = __esm({
841
- "src/multichain/utils/analytics.ts"() {
842
- "use strict";
843
- init_utils();
844
- init_domain();
845
- }
846
- });
847
-
848
- // src/domain/utils/index.ts
849
- function getVersion() {
850
- return "0.0.0";
851
- }
852
- var init_utils2 = __esm({
853
- "src/domain/utils/index.ts"() {
854
- "use strict";
855
- init_analytics();
856
- }
857
- });
858
-
859
- // src/domain/index.ts
860
- var init_domain = __esm({
861
- "src/domain/index.ts"() {
862
- "use strict";
863
- init_errors();
864
- init_events();
865
- init_logger();
866
- init_multichain();
867
- init_platform();
868
- init_store();
869
- init_ui();
870
- init_utils2();
871
935
  }
872
936
  });
873
937
 
@@ -1091,11 +1155,11 @@ var init_rn2 = __esm({
1091
1155
  });
1092
1156
 
1093
1157
  // src/polyfills/buffer-shim.ts
1158
+ init_utils2();
1094
1159
  import { Buffer as Buffer2 } from "buffer";
1095
- var globalObj = typeof globalThis !== "undefined" ? globalThis : typeof global !== "undefined" ? global : typeof window !== "undefined" ? window : {};
1096
- if (!globalObj.Buffer) {
1097
- globalObj.Buffer = Buffer2;
1098
- }
1160
+ var globalObj = getGlobalObject();
1161
+ var _a;
1162
+ (_a = globalObj.Buffer) != null ? _a : globalObj.Buffer = Buffer2;
1099
1163
 
1100
1164
  // src/index.native.ts
1101
1165
  init_domain();
@@ -1168,8 +1232,8 @@ var RpcClient = class {
1168
1232
  });
1169
1233
  }
1170
1234
  getRpcEndpoint(scope) {
1171
- var _a2, _b, _c;
1172
- 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 : {};
1173
1237
  const rpcEndpoint = supportedNetworks[scope];
1174
1238
  if (!rpcEndpoint) {
1175
1239
  throw new MissingRpcEndpointErr(
@@ -1233,7 +1297,7 @@ var RpcClient = class {
1233
1297
  // src/multichain/rpc/requestRouter.ts
1234
1298
  import { analytics } from "@metamask/analytics";
1235
1299
  init_domain();
1236
- init_utils();
1300
+ init_utils2();
1237
1301
  init_analytics();
1238
1302
  var _RequestRouter_instances, withAnalyticsTracking_fn, trackWalletActionRequested_fn, trackWalletActionSucceeded_fn, trackWalletActionFailed_fn, trackWalletActionRejected_fn;
1239
1303
  var RequestRouter = class {
@@ -1400,12 +1464,12 @@ trackWalletActionRejected_fn = function(options) {
1400
1464
  };
1401
1465
 
1402
1466
  // src/multichain/transports/default/index.ts
1403
- init_utils();
1467
+ init_utils2();
1404
1468
  import {
1405
1469
  getDefaultTransport
1406
1470
  } from "@metamask/multichain-api-client";
1407
1471
  var DEFAULT_REQUEST_TIMEOUT = 60 * 1e3;
1408
- 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;
1409
1473
  var DefaultTransport = class {
1410
1474
  constructor() {
1411
1475
  __privateAdd(this, _DefaultTransport_instances);
@@ -1414,8 +1478,6 @@ var DefaultTransport = class {
1414
1478
  __privateAdd(this, _defaultRequestOptions, {
1415
1479
  timeout: DEFAULT_REQUEST_TIMEOUT
1416
1480
  });
1417
- // Use timestamp-based ID to avoid conflicts across disconnect/reconnect cycles
1418
- __privateAdd(this, _reqId, Date.now());
1419
1481
  __privateAdd(this, _pendingRequests, /* @__PURE__ */ new Map());
1420
1482
  __privateAdd(this, _handleResponseListener);
1421
1483
  __privateAdd(this, _handleNotificationListener);
@@ -1423,18 +1485,17 @@ var DefaultTransport = class {
1423
1485
  sendEip1193Message(payload, options) {
1424
1486
  return __async(this, null, function* () {
1425
1487
  __privateMethod(this, _DefaultTransport_instances, setupMessageListener_fn).call(this);
1426
- __privateSet(this, _reqId, __privateGet(this, _reqId) + 1);
1427
- const requestId = `${__privateGet(this, _reqId)}`;
1488
+ const requestId = String(getUniqueRequestId());
1428
1489
  const request = __spreadValues({
1429
1490
  jsonrpc: "2.0",
1430
1491
  id: requestId
1431
1492
  }, payload);
1432
1493
  return new Promise((resolve, reject) => {
1433
- var _a2;
1494
+ var _a3;
1434
1495
  const timeout = setTimeout(() => {
1435
1496
  __privateGet(this, _pendingRequests).delete(requestId);
1436
1497
  reject(new Error("Request timeout"));
1437
- }, (_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);
1438
1499
  __privateGet(this, _pendingRequests).set(requestId, {
1439
1500
  resolve: (response) => {
1440
1501
  resolve(response);
@@ -1458,7 +1519,7 @@ var DefaultTransport = class {
1458
1519
  }
1459
1520
  connect(options) {
1460
1521
  return __async(this, null, function* () {
1461
- var _a2, _b, _c, _d, _e;
1522
+ var _a3, _b, _c, _d, _e;
1462
1523
  __privateMethod(this, _DefaultTransport_instances, setupMessageListener_fn).call(this);
1463
1524
  yield __privateGet(this, _transport).connect();
1464
1525
  const sessionRequest = yield this.request(
@@ -1471,7 +1532,7 @@ var DefaultTransport = class {
1471
1532
  let walletSession = sessionRequest.result;
1472
1533
  const createSessionParams = {
1473
1534
  optionalScopes: addValidAccounts(
1474
- getOptionalScopes((_a2 = options == null ? void 0 : options.scopes) != null ? _a2 : []),
1535
+ getOptionalScopes((_a3 = options == null ? void 0 : options.scopes) != null ? _a3 : []),
1475
1536
  getValidAccounts((_b = options == null ? void 0 : options.caipAccountIds) != null ? _b : [])
1476
1537
  ),
1477
1538
  sessionProperties: options == null ? void 0 : options.sessionProperties
@@ -1489,10 +1550,6 @@ var DefaultTransport = class {
1489
1550
  proposedCaipAccountIds
1490
1551
  );
1491
1552
  if (!hasSameScopesAndAccounts) {
1492
- yield this.request(
1493
- { method: "wallet_revokeSession", params: walletSession },
1494
- __privateGet(this, _defaultRequestOptions)
1495
- );
1496
1553
  const response = yield this.request(
1497
1554
  { method: "wallet_createSession", params: createSessionParams },
1498
1555
  __privateGet(this, _defaultRequestOptions)
@@ -1519,9 +1576,14 @@ var DefaultTransport = class {
1519
1576
  });
1520
1577
  }
1521
1578
  disconnect() {
1522
- 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
+ }
1523
1586
  __privateGet(this, _notificationCallbacks).clear();
1524
- yield this.request({ method: "wallet_revokeSession", params: {} });
1525
1587
  if (__privateGet(this, _handleResponseListener)) {
1526
1588
  window.removeEventListener("message", __privateGet(this, _handleResponseListener));
1527
1589
  __privateSet(this, _handleResponseListener, void 0);
@@ -1535,7 +1597,7 @@ var DefaultTransport = class {
1535
1597
  request.reject(new Error("Transport disconnected"));
1536
1598
  }
1537
1599
  __privateGet(this, _pendingRequests).clear();
1538
- return __privateGet(this, _transport).disconnect();
1600
+ yield __privateGet(this, _transport).disconnect();
1539
1601
  });
1540
1602
  }
1541
1603
  isConnected() {
@@ -1560,11 +1622,17 @@ var DefaultTransport = class {
1560
1622
  );
1561
1623
  });
1562
1624
  }
1625
+ getStoredPendingSessionRequest() {
1626
+ return __async(this, null, function* () {
1627
+ throw new Error(
1628
+ "getStoredPendingSessionRequest is purposely not implemented for the DefaultTransport"
1629
+ );
1630
+ });
1631
+ }
1563
1632
  };
1564
1633
  _notificationCallbacks = new WeakMap();
1565
1634
  _transport = new WeakMap();
1566
1635
  _defaultRequestOptions = new WeakMap();
1567
- _reqId = new WeakMap();
1568
1636
  _pendingRequests = new WeakMap();
1569
1637
  _handleResponseListener = new WeakMap();
1570
1638
  _handleNotificationListener = new WeakMap();
@@ -1582,16 +1650,16 @@ notifyCallbacks_fn = function(data) {
1582
1650
  }
1583
1651
  };
1584
1652
  isMetamaskProviderEvent_fn = function(event) {
1585
- var _a2, _b;
1586
- 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
1587
1655
  event.origin === location.origin;
1588
1656
  };
1589
1657
  handleResponse_fn = function(event) {
1590
- var _a2, _b;
1658
+ var _a3, _b;
1591
1659
  if (!__privateMethod(this, _DefaultTransport_instances, isMetamaskProviderEvent_fn).call(this, event)) {
1592
1660
  return;
1593
1661
  }
1594
- 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;
1595
1663
  if (typeof responseData === "object" && responseData !== null && "method" in responseData) {
1596
1664
  return;
1597
1665
  }
@@ -1613,11 +1681,11 @@ handleResponse_fn = function(event) {
1613
1681
  }
1614
1682
  };
1615
1683
  handleNotification_fn = function(event) {
1616
- var _a2, _b;
1684
+ var _a3, _b;
1617
1685
  if (!__privateMethod(this, _DefaultTransport_instances, isMetamaskProviderEvent_fn).call(this, event)) {
1618
1686
  return;
1619
1687
  }
1620
- 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;
1621
1689
  if (typeof responseData === "object" && responseData.method === "metamask_chainChanged" || responseData.method === "metamask_accountsChanged") {
1622
1690
  __privateMethod(this, _DefaultTransport_instances, notifyCallbacks_fn).call(this, responseData);
1623
1691
  }
@@ -1633,19 +1701,13 @@ setupMessageListener_fn = function() {
1633
1701
  };
1634
1702
 
1635
1703
  // src/multichain/transports/multichainApiClientWrapper/index.ts
1704
+ init_utils2();
1636
1705
  import { providerErrors } from "@metamask/rpc-errors";
1637
- var MAX = 4294967295;
1638
- var idCounter = Math.floor(Math.random() * MAX);
1639
- var getUniqueId = () => {
1640
- idCounter = (idCounter + 1) % MAX;
1641
- return idCounter;
1642
- };
1643
- var _requestId, _notificationCallbacks2, _MultichainApiClientWrapperTransport_instances, walletCreateSession_fn, walletGetSession_fn, walletRevokeSession_fn, walletInvokeMethod_fn;
1706
+ var _notificationCallbacks2, _MultichainApiClientWrapperTransport_instances, walletCreateSession_fn, walletGetSession_fn, walletRevokeSession_fn, walletInvokeMethod_fn;
1644
1707
  var MultichainApiClientWrapperTransport = class {
1645
1708
  constructor(metamaskConnectMultichain) {
1646
1709
  this.metamaskConnectMultichain = metamaskConnectMultichain;
1647
1710
  __privateAdd(this, _MultichainApiClientWrapperTransport_instances);
1648
- __privateAdd(this, _requestId, getUniqueId());
1649
1711
  __privateAdd(this, _notificationCallbacks2, /* @__PURE__ */ new Set());
1650
1712
  }
1651
1713
  isTransportDefined() {
@@ -1663,15 +1725,23 @@ var MultichainApiClientWrapperTransport = class {
1663
1725
  callback(data);
1664
1726
  });
1665
1727
  }
1666
- setupNotifcationListener() {
1667
- this.metamaskConnectMultichain.transport.onNotification(
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(
1668
1738
  this.notifyCallbacks.bind(this)
1669
1739
  );
1670
1740
  }
1671
1741
  connect() {
1672
1742
  return __async(this, null, function* () {
1673
1743
  console.log("\u{1F4DA} connect");
1674
- return Promise.resolve();
1744
+ yield this.metamaskConnectMultichain.emitSessionChanged();
1675
1745
  });
1676
1746
  }
1677
1747
  disconnect() {
@@ -1684,7 +1754,7 @@ var MultichainApiClientWrapperTransport = class {
1684
1754
  }
1685
1755
  request(_0) {
1686
1756
  return __async(this, arguments, function* (params, _options = {}) {
1687
- const id = __privateWrapper(this, _requestId)._++;
1757
+ const id = getUniqueRequestId();
1688
1758
  const requestPayload = __spreadValues({
1689
1759
  id,
1690
1760
  jsonrpc: "2.0"
@@ -1705,16 +1775,13 @@ var MultichainApiClientWrapperTransport = class {
1705
1775
  });
1706
1776
  }
1707
1777
  onNotification(callback) {
1708
- if (!this.isTransportDefined()) {
1709
- __privateGet(this, _notificationCallbacks2).add(callback);
1710
- return () => {
1711
- __privateGet(this, _notificationCallbacks2).delete(callback);
1712
- };
1713
- }
1714
- return this.metamaskConnectMultichain.transport.onNotification(callback);
1778
+ this.setupTransportNotificationListener();
1779
+ __privateGet(this, _notificationCallbacks2).add(callback);
1780
+ return () => {
1781
+ __privateGet(this, _notificationCallbacks2).delete(callback);
1782
+ };
1715
1783
  }
1716
1784
  };
1717
- _requestId = new WeakMap();
1718
1785
  _notificationCallbacks2 = new WeakMap();
1719
1786
  _MultichainApiClientWrapperTransport_instances = new WeakSet();
1720
1787
  walletCreateSession_fn = function(request) {
@@ -1724,8 +1791,8 @@ walletCreateSession_fn = function(request) {
1724
1791
  const scopes = Object.keys(__spreadValues(__spreadValues({}, createSessionParams.optionalScopes), createSessionParams.requiredScopes));
1725
1792
  const scopeAccounts = [];
1726
1793
  scopes.forEach((scope) => {
1727
- var _a2, _b, _c, _d;
1728
- const requiredScope = (_a2 = createSessionParams.requiredScopes) == null ? void 0 : _a2[scope];
1794
+ var _a3, _b, _c, _d;
1795
+ const requiredScope = (_a3 = createSessionParams.requiredScopes) == null ? void 0 : _a3[scope];
1729
1796
  const optionalScope = (_b = createSessionParams.optionalScopes) == null ? void 0 : _b[scope];
1730
1797
  if (requiredScope) {
1731
1798
  scopeAccounts.push(...(_c = requiredScope.accounts) != null ? _c : []);
@@ -1765,11 +1832,14 @@ walletGetSession_fn = function(request) {
1765
1832
  };
1766
1833
  walletRevokeSession_fn = function(request) {
1767
1834
  return __async(this, null, function* () {
1835
+ var _a3;
1768
1836
  if (!this.isTransportDefined()) {
1769
1837
  return { jsonrpc: "2.0", id: request.id, result: true };
1770
1838
  }
1839
+ const revokeSessionParams = request.params;
1840
+ const scopes = (_a3 = revokeSessionParams == null ? void 0 : revokeSessionParams.scopes) != null ? _a3 : [];
1771
1841
  try {
1772
- this.metamaskConnectMultichain.disconnect();
1842
+ yield this.metamaskConnectMultichain.disconnect(scopes);
1773
1843
  return { jsonrpc: "2.0", id: request.id, result: true };
1774
1844
  } catch (_error) {
1775
1845
  return { jsonrpc: "2.0", id: request.id, result: false };
@@ -1792,11 +1862,12 @@ walletInvokeMethod_fn = function(request) {
1792
1862
 
1793
1863
  // src/multichain/transports/mwp/index.ts
1794
1864
  init_domain();
1795
- init_utils();
1865
+ init_utils2();
1796
1866
  import { SessionStore } from "@metamask/mobile-wallet-protocol-core";
1797
1867
  import {
1798
1868
  TransportTimeoutError
1799
1869
  } from "@metamask/multichain-api-client";
1870
+ import { providerErrors as providerErrors2, rpcErrors } from "@metamask/rpc-errors";
1800
1871
 
1801
1872
  // src/multichain/transports/constants.ts
1802
1873
  var MULTICHAIN_PROVIDER_STREAM_NAME = "metamask-multichain-provider";
@@ -1809,6 +1880,7 @@ var DEFAULT_RESUME_TIMEOUT = 10 * 1e3;
1809
1880
  var SESSION_STORE_KEY = "cache_wallet_getSession";
1810
1881
  var ACCOUNTS_STORE_KEY = "cache_eth_accounts";
1811
1882
  var CHAIN_STORE_KEY = "cache_eth_chainId";
1883
+ var PENDING_SESSION_REQUEST_KEY = "pending_session_request";
1812
1884
  var CACHED_METHOD_LIST = [
1813
1885
  "wallet_getSession",
1814
1886
  "wallet_createSession",
@@ -1828,10 +1900,15 @@ var MWPTransport = class {
1828
1900
  this.dappClient = dappClient;
1829
1901
  this.kvstore = kvstore;
1830
1902
  this.options = options;
1831
- this.__reqId = 0;
1832
1903
  this.__pendingRequests = /* @__PURE__ */ new Map();
1833
1904
  this.notificationCallbacks = /* @__PURE__ */ new Set();
1834
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
+ });
1835
1912
  if (typeof window !== "undefined" && typeof window.addEventListener !== "undefined") {
1836
1913
  this.windowFocusHandler = this.onWindowFocus.bind(this);
1837
1914
  window.addEventListener("focus", this.windowFocusHandler);
@@ -1846,6 +1923,34 @@ var MWPTransport = class {
1846
1923
  get sessionRequest() {
1847
1924
  return this.currentSessionRequest;
1848
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
+ }
1849
1954
  onWindowFocus() {
1850
1955
  if (!this.isConnected()) {
1851
1956
  this.dappClient.reconnect();
@@ -1862,6 +1967,17 @@ var MWPTransport = class {
1862
1967
  request.reject(error);
1863
1968
  }
1864
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
+ }
1865
1981
  handleMessage(message) {
1866
1982
  if (typeof message === "object" && message !== null) {
1867
1983
  if ("data" in message) {
@@ -1869,6 +1985,12 @@ var MWPTransport = class {
1869
1985
  if ("id" in messagePayload && typeof messagePayload.id === "string") {
1870
1986
  const request = this.pendingRequests.get(messagePayload.id);
1871
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
+ }
1872
1994
  const requestWithName = __spreadProps(__spreadValues({}, messagePayload), {
1873
1995
  method: request.method === "wallet_getSession" || request.method === "wallet_createSession" ? "wallet_sessionChanged" : request.method
1874
1996
  });
@@ -1876,7 +1998,6 @@ var MWPTransport = class {
1876
1998
  method: request.method === "wallet_getSession" || request.method === "wallet_createSession" ? "wallet_sessionChanged" : request.method,
1877
1999
  params: requestWithName.result
1878
2000
  });
1879
- clearTimeout(request.timeout);
1880
2001
  this.notifyCallbacks(notification);
1881
2002
  request.resolve(requestWithName);
1882
2003
  this.pendingRequests.delete(messagePayload.id);
@@ -1912,7 +2033,7 @@ var MWPTransport = class {
1912
2033
  }
1913
2034
  onResumeSuccess(resumeResolve, resumeReject, options) {
1914
2035
  return __async(this, null, function* () {
1915
- var _a2, _b, _c, _d, _e, _f, _g;
2036
+ var _a3, _b, _c, _d, _e, _f, _g;
1916
2037
  try {
1917
2038
  yield this.waitForWalletSessionIfNotCached();
1918
2039
  const sessionRequest = yield this.request({
@@ -1924,7 +2045,7 @@ var MWPTransport = class {
1924
2045
  let walletSession = sessionRequest.result;
1925
2046
  if (walletSession && options) {
1926
2047
  const currentScopes = Object.keys(
1927
- (_a2 = walletSession == null ? void 0 : walletSession.sessionScopes) != null ? _a2 : {}
2048
+ (_a3 = walletSession == null ? void 0 : walletSession.sessionScopes) != null ? _a3 : {}
1928
2049
  );
1929
2050
  const proposedScopes = (_b = options == null ? void 0 : options.scopes) != null ? _b : [];
1930
2051
  const proposedCaipAccountIds = (_c = options == null ? void 0 : options.caipAccountIds) != null ? _c : [];
@@ -1966,6 +2087,7 @@ var MWPTransport = class {
1966
2087
  }
1967
2088
  walletSession = response.result;
1968
2089
  }
2090
+ yield this.removeStoredPendingSessionRequest();
1969
2091
  this.notifyCallbacks({
1970
2092
  method: "wallet_sessionChanged",
1971
2093
  params: walletSession
@@ -1981,7 +2103,7 @@ var MWPTransport = class {
1981
2103
  return __async(this, null, function* () {
1982
2104
  const request = __spreadValues({
1983
2105
  jsonrpc: "2.0",
1984
- id: `${this.__reqId++}`
2106
+ id: String(getUniqueRequestId())
1985
2107
  }, payload);
1986
2108
  const cachedWalletSession = yield this.getCachedResponse(request);
1987
2109
  if (cachedWalletSession) {
@@ -1989,10 +2111,10 @@ var MWPTransport = class {
1989
2111
  return cachedWalletSession;
1990
2112
  }
1991
2113
  return new Promise((resolve, reject) => {
1992
- var _a2;
2114
+ var _a3;
1993
2115
  const timeout = setTimeout(() => {
1994
2116
  this.rejectRequest(request.id, new TransportTimeoutError());
1995
- }, (_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);
1996
2118
  this.pendingRequests.set(request.id, {
1997
2119
  request,
1998
2120
  method: request.method,
@@ -2017,28 +2139,29 @@ var MWPTransport = class {
2017
2139
  if (session) {
2018
2140
  logger("active session found", session);
2019
2141
  }
2142
+ const storedSessionRequestBeforeConnectionAttempt = yield this.getStoredPendingSessionRequest();
2020
2143
  let timeout;
2021
2144
  let initialConnectionMessageHandler;
2022
2145
  const connectionPromise = new Promise((resolve, reject) => __async(this, null, function* () {
2023
2146
  let connection;
2024
2147
  if (session) {
2025
2148
  connection = new Promise((resumeResolve, resumeReject) => {
2026
- var _a2;
2149
+ var _a3;
2027
2150
  if (this.dappClient.state === "CONNECTED") {
2028
2151
  this.onResumeSuccess(resumeResolve, resumeReject, options);
2029
2152
  } else {
2030
2153
  this.dappClient.once("connected", () => __async(this, null, function* () {
2031
2154
  this.onResumeSuccess(resumeResolve, resumeReject, options);
2032
2155
  }));
2033
- dappClient.resume((_a2 = session == null ? void 0 : session.id) != null ? _a2 : "");
2156
+ dappClient.resume((_a3 = session == null ? void 0 : session.id) != null ? _a3 : "");
2034
2157
  }
2035
2158
  });
2036
2159
  } else {
2037
2160
  connection = new Promise(
2038
2161
  (resolveConnection, rejectConnection) => {
2039
- var _a2, _b;
2162
+ var _a3, _b;
2040
2163
  const optionalScopes = addValidAccounts(
2041
- getOptionalScopes((_a2 = options == null ? void 0 : options.scopes) != null ? _a2 : []),
2164
+ getOptionalScopes((_a3 = options == null ? void 0 : options.scopes) != null ? _a3 : []),
2042
2165
  getValidAccounts((_b = options == null ? void 0 : options.caipAccountIds) != null ? _b : [])
2043
2166
  );
2044
2167
  const sessionRequest = {
@@ -2047,33 +2170,35 @@ var MWPTransport = class {
2047
2170
  };
2048
2171
  const request = {
2049
2172
  jsonrpc: "2.0",
2050
- id: `${this.__reqId++}`,
2173
+ id: String(getUniqueRequestId()),
2051
2174
  method: "wallet_createSession",
2052
2175
  params: sessionRequest
2053
2176
  };
2054
2177
  initialConnectionMessageHandler = (message) => __async(this, null, function* () {
2055
- if (typeof message === "object" && message !== null) {
2056
- if ("data" in message) {
2057
- const messagePayload = message.data;
2058
- if (messagePayload.method === "wallet_createSession" || messagePayload.method === "wallet_sessionChanged") {
2059
- if (messagePayload.error) {
2060
- if (initialConnectionMessageHandler) {
2061
- this.dappClient.off(
2062
- "message",
2063
- initialConnectionMessageHandler
2064
- );
2065
- }
2066
- return rejectConnection(messagePayload.error);
2067
- }
2068
- yield this.storeWalletSession(
2069
- request,
2070
- messagePayload
2071
- );
2072
- this.notifyCallbacks(messagePayload);
2073
- return resolveConnection();
2074
- }
2075
- }
2178
+ if (typeof message !== "object" || message === null) {
2179
+ return;
2180
+ }
2181
+ if (!("data" in message)) {
2182
+ return;
2076
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
+ );
2194
+ }
2195
+ yield this.storeWalletSession(
2196
+ request,
2197
+ messagePayload
2198
+ );
2199
+ yield this.removeStoredPendingSessionRequest();
2200
+ this.notifyCallbacks(messagePayload);
2201
+ return resolveConnection();
2077
2202
  });
2078
2203
  this.dappClient.on("message", initialConnectionMessageHandler);
2079
2204
  dappClient.connect({
@@ -2094,14 +2219,18 @@ var MWPTransport = class {
2094
2219
  }
2095
2220
  );
2096
2221
  }
2097
- timeout = setTimeout(() => {
2098
- reject(new TransportTimeoutError());
2099
- }, this.options.connectionTimeout);
2222
+ timeout = setTimeout(
2223
+ () => {
2224
+ reject(new TransportTimeoutError());
2225
+ },
2226
+ storedSessionRequestBeforeConnectionAttempt ? this.options.resumeTimeout : this.options.connectionTimeout
2227
+ );
2100
2228
  connection.then(resolve).catch(reject);
2101
2229
  }));
2102
- return connectionPromise.catch((error) => {
2230
+ return connectionPromise.catch((error) => __async(this, null, function* () {
2231
+ yield this.dappClient.disconnect();
2103
2232
  throw error;
2104
- }).finally(() => {
2233
+ })).finally(() => {
2105
2234
  if (timeout) {
2106
2235
  clearTimeout(timeout);
2107
2236
  }
@@ -2109,24 +2238,68 @@ var MWPTransport = class {
2109
2238
  this.dappClient.off("message", initialConnectionMessageHandler);
2110
2239
  initialConnectionMessageHandler = void 0;
2111
2240
  }
2241
+ this.removeStoredPendingSessionRequest();
2112
2242
  });
2113
2243
  });
2114
2244
  }
2115
2245
  /**
2116
2246
  * Disconnects from the Mobile Wallet Protocol
2117
2247
  *
2248
+ * @param [scopes] - The scopes to revoke. If not provided or empty, all scopes will be revoked.
2118
2249
  * @returns Nothing
2119
2250
  */
2120
2251
  disconnect() {
2121
- return __async(this, null, function* () {
2122
- if (typeof window !== "undefined" && typeof window.removeEventListener !== "undefined" && this.windowFocusHandler) {
2123
- window.removeEventListener("focus", this.windowFocusHandler);
2124
- this.windowFocusHandler = void 0;
2125
- }
2126
- this.kvstore.delete(SESSION_STORE_KEY);
2127
- this.kvstore.delete(ACCOUNTS_STORE_KEY);
2128
- this.kvstore.delete(CHAIN_STORE_KEY);
2129
- 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
+ });
2130
2303
  });
2131
2304
  }
2132
2305
  /**
@@ -2171,7 +2344,7 @@ var MWPTransport = class {
2171
2344
  }
2172
2345
  getCachedResponse(request) {
2173
2346
  return __async(this, null, function* () {
2174
- var _a2;
2347
+ var _a3;
2175
2348
  if (request.method === "wallet_getSession") {
2176
2349
  const walletGetSession = yield this.kvstore.get(SESSION_STORE_KEY);
2177
2350
  if (walletGetSession) {
@@ -2179,7 +2352,7 @@ var MWPTransport = class {
2179
2352
  return {
2180
2353
  id: request.id,
2181
2354
  jsonrpc: "2.0",
2182
- result: (_a2 = walletSession.params) != null ? _a2 : walletSession.result,
2355
+ result: (_a3 = walletSession.params) != null ? _a3 : walletSession.result,
2183
2356
  // "what?... why walletSession.params?.."
2184
2357
  method: request.method
2185
2358
  };
@@ -2232,7 +2405,7 @@ var MWPTransport = class {
2232
2405
  return __async(this, null, function* () {
2233
2406
  const request = __spreadValues({
2234
2407
  jsonrpc: "2.0",
2235
- id: `${this.__reqId++}`
2408
+ id: String(getUniqueRequestId())
2236
2409
  }, payload);
2237
2410
  const cachedWalletSession = yield this.getCachedResponse(request);
2238
2411
  if (cachedWalletSession) {
@@ -2243,10 +2416,10 @@ var MWPTransport = class {
2243
2416
  yield this.attemptResumeSession();
2244
2417
  }
2245
2418
  return new Promise((resolve, reject) => {
2246
- var _a2;
2419
+ var _a3;
2247
2420
  const timeout = setTimeout(() => {
2248
2421
  this.rejectRequest(request.id, new TransportTimeoutError());
2249
- }, (_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);
2250
2423
  this.pendingRequests.set(request.id, {
2251
2424
  request,
2252
2425
  method: request.method,
@@ -2314,6 +2487,7 @@ var MWPTransport = class {
2314
2487
  const timeoutPromise = new Promise((_resolve, reject) => {
2315
2488
  setTimeout(() => {
2316
2489
  unsubscribe();
2490
+ this.removeStoredPendingSessionRequest();
2317
2491
  reject(new TransportTimeoutError());
2318
2492
  }, this.options.resumeTimeout);
2319
2493
  });
@@ -2350,14 +2524,15 @@ var KeyManager = class {
2350
2524
  var keymanager = new KeyManager();
2351
2525
 
2352
2526
  // src/multichain/index.ts
2353
- init_utils();
2527
+ init_utils2();
2354
2528
  var logger2 = createLogger("metamask-sdk:core");
2355
- 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;
2356
2531
  var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends MultichainCore {
2357
2532
  constructor(options) {
2358
- var _a2, _b, _c, _d, _e, _f;
2533
+ var _a3, _b, _c, _d, _e, _f;
2359
2534
  const withDappMetadata = setupDappMetadata(options);
2360
- 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";
2361
2536
  const allOptions = __spreadProps(__spreadValues({}, withDappMetadata), {
2362
2537
  ui: __spreadProps(__spreadValues({}, withDappMetadata.ui), {
2363
2538
  preferExtension: (_c = withDappMetadata.ui.preferExtension) != null ? _c : true,
@@ -2377,7 +2552,7 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
2377
2552
  __privateAdd(this, _beforeUnloadListener);
2378
2553
  this._status = "pending";
2379
2554
  __privateAdd(this, _listener);
2380
- __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}`);
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}`);
2381
2556
  __privateSet(this, _providerTransportWrapper, new MultichainApiClientWrapperTransport(
2382
2557
  this
2383
2558
  ));
@@ -2389,9 +2564,9 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
2389
2564
  return this._status;
2390
2565
  }
2391
2566
  set status(value) {
2392
- var _a2, _b;
2567
+ var _a3, _b;
2393
2568
  this._status = value;
2394
- (_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, {
2395
2570
  method: "stateChanged",
2396
2571
  params: value
2397
2572
  });
@@ -2417,27 +2592,54 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
2417
2592
  get transportType() {
2418
2593
  return __privateGet(this, _transport2) instanceof MWPTransport ? "mwp" /* MWP */ : "browser" /* Browser */;
2419
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.
2420
2601
  static create(options) {
2421
2602
  return __async(this, null, function* () {
2422
- var _a2;
2423
- const instance = new _MetaMaskConnectMultichain(options);
2424
- const isEnabled2 = yield isEnabled(
2425
- "metamask-sdk:core",
2426
- instance.options.storage
2427
- );
2428
- if (isEnabled2) {
2429
- enableDebug("metamask-sdk:core");
2430
- }
2431
- yield __privateMethod(_a2 = instance, _MetaMaskConnectMultichain_instances, init_fn).call(_a2);
2432
- 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;
2433
2632
  });
2434
2633
  }
2435
2634
  // TODO: make this into param object
2436
2635
  connect(scopes, caipAccountIds, sessionProperties, forceRequest) {
2437
2636
  return __async(this, null, function* () {
2438
- var _a2;
2439
- if (this.status !== "connected") {
2440
- 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
+ );
2441
2643
  }
2442
2644
  const { ui } = this.options;
2443
2645
  const platformType = getPlatformType();
@@ -2467,12 +2669,19 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
2467
2669
  } catch (error) {
2468
2670
  logger2("Error tracking connection_initiated event", error);
2469
2671
  }
2470
- const nonEmptySessionProperites = Object.keys(sessionProperties != null ? sessionProperties : {}).length > 0 ? sessionProperties : void 0;
2471
- if (((_a2 = __privateGet(this, _transport2)) == null ? void 0 : _a2.isConnected()) && !secure) {
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) {
2472
2681
  return __privateMethod(this, _MetaMaskConnectMultichain_instances, handleConnection_fn).call(this, __privateGet(this, _transport2).connect({
2473
- scopes,
2474
- caipAccountIds,
2475
- sessionProperties: nonEmptySessionProperites,
2682
+ scopes: mergedScopes,
2683
+ caipAccountIds: mergedCaipAccountIds,
2684
+ sessionProperties: nonEmptySessionProperties,
2476
2685
  forceRequest
2477
2686
  }).then(() => __async(this, null, function* () {
2478
2687
  if (__privateGet(this, _transport2) instanceof MWPTransport) {
@@ -2484,47 +2693,53 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
2484
2693
  if (platformType === "in-app-browser" /* MetaMaskMobileWebview */) {
2485
2694
  const defaultTransport = yield __privateMethod(this, _MetaMaskConnectMultichain_instances, setupDefaultTransport_fn).call(this);
2486
2695
  return __privateMethod(this, _MetaMaskConnectMultichain_instances, handleConnection_fn).call(this, defaultTransport.connect({
2487
- scopes,
2488
- caipAccountIds,
2489
- sessionProperties: nonEmptySessionProperites,
2696
+ scopes: mergedScopes,
2697
+ caipAccountIds: mergedCaipAccountIds,
2698
+ sessionProperties: nonEmptySessionProperties,
2490
2699
  forceRequest
2491
2700
  }), scopes, transportType);
2492
2701
  }
2493
2702
  if (isWeb && hasExtensionInstalled && preferExtension) {
2494
2703
  const defaultTransport = yield __privateMethod(this, _MetaMaskConnectMultichain_instances, setupDefaultTransport_fn).call(this);
2495
2704
  return __privateMethod(this, _MetaMaskConnectMultichain_instances, handleConnection_fn).call(this, defaultTransport.connect({
2496
- scopes,
2497
- caipAccountIds,
2498
- sessionProperties: nonEmptySessionProperites,
2705
+ scopes: mergedScopes,
2706
+ caipAccountIds: mergedCaipAccountIds,
2707
+ sessionProperties: nonEmptySessionProperties,
2499
2708
  forceRequest
2500
2709
  }), scopes, transportType);
2501
2710
  }
2502
2711
  yield __privateMethod(this, _MetaMaskConnectMultichain_instances, setupMWP_fn).call(this);
2503
2712
  const shouldShowInstallModal = hasExtensionInstalled ? showInstallModal : !preferExtension || showInstallModal;
2504
2713
  if (secure && !shouldShowInstallModal) {
2505
- 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);
2506
2715
  }
2507
- 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);
2508
2717
  });
2509
2718
  }
2510
2719
  emit(event, args) {
2511
- var _a2, _b;
2512
- (_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 });
2513
2722
  super.emit(event, args);
2514
2723
  }
2515
2724
  disconnect() {
2516
- return __async(this, null, function* () {
2517
- var _a2, _b, _c;
2518
- yield (_a2 = __privateGet(this, _listener)) == null ? void 0 : _a2.call(this);
2519
- (_b = __privateGet(this, _beforeUnloadListener)) == null ? void 0 : _b.call(this);
2520
- yield (_c = __privateGet(this, _transport2)) == null ? void 0 : _c.disconnect();
2521
- yield this.storage.removeTransport();
2522
- this.emit("stateChanged", "disconnected");
2523
- __privateSet(this, _listener, void 0);
2524
- __privateSet(this, _beforeUnloadListener, void 0);
2525
- __privateSet(this, _transport2, void 0);
2526
- __privateGet(this, _providerTransportWrapper).clearNotificationCallbacks();
2527
- __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
+ }
2528
2743
  });
2529
2744
  }
2530
2745
  invokeMethod(request) {
@@ -2536,7 +2751,7 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
2536
2751
  });
2537
2752
  }
2538
2753
  // DRY THIS WITH REQUEST ROUTER
2539
- openDeeplinkIfNeeded() {
2754
+ openSimpleDeeplinkIfNeeded() {
2540
2755
  const { ui, mobile } = this.options;
2541
2756
  const { showInstallModal = false } = ui != null ? ui : {};
2542
2757
  const secure = isSecure();
@@ -2556,6 +2771,23 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
2556
2771
  }), 10);
2557
2772
  }
2558
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
+ }
2559
2791
  };
2560
2792
  _provider = new WeakMap();
2561
2793
  _providerTransportWrapper = new WeakMap();
@@ -2567,7 +2799,7 @@ _sdkInfo = new WeakMap();
2567
2799
  _MetaMaskConnectMultichain_instances = new WeakSet();
2568
2800
  setupAnalytics_fn = function() {
2569
2801
  return __async(this, null, function* () {
2570
- var _a2;
2802
+ var _a3;
2571
2803
  const platform = getPlatformType();
2572
2804
  const isBrowser = platform === "in-app-browser" /* MetaMaskMobileWebview */ || platform === "web-desktop" /* DesktopWeb */ || platform === "web-mobile" /* MobileWeb */;
2573
2805
  const isReactNative2 = platform === "react-native" /* ReactNative */;
@@ -2577,7 +2809,7 @@ setupAnalytics_fn = function() {
2577
2809
  const version = getVersion();
2578
2810
  const dappId = getDappId(this.options.dapp);
2579
2811
  const anonId = yield this.storage.getAnonId();
2580
- const { integrationType } = (_a2 = this.options.analytics) != null ? _a2 : {
2812
+ const { integrationType } = (_a3 = this.options.analytics) != null ? _a3 : {
2581
2813
  integrationType: ""
2582
2814
  };
2583
2815
  analytics2.setGlobalProperty("mmconnect_version", version);
@@ -2590,9 +2822,9 @@ setupAnalytics_fn = function() {
2590
2822
  };
2591
2823
  onTransportNotification_fn = function(payload) {
2592
2824
  return __async(this, null, function* () {
2593
- var _a2;
2825
+ var _a3;
2594
2826
  if (typeof payload === "object" && payload !== null && "method" in payload) {
2595
- this.emit(payload.method, (_a2 = payload.params) != null ? _a2 : payload.result);
2827
+ this.emit(payload.method, (_a3 = payload.params) != null ? _a3 : payload.result);
2596
2828
  }
2597
2829
  });
2598
2830
  };
@@ -2605,7 +2837,7 @@ getStoredTransport_fn = function() {
2605
2837
  if (hasExtensionInstalled) {
2606
2838
  const apiTransport = new DefaultTransport();
2607
2839
  __privateSet(this, _transport2, apiTransport);
2608
- __privateGet(this, _providerTransportWrapper).setupNotifcationListener();
2840
+ __privateGet(this, _providerTransportWrapper).setupTransportNotificationListener();
2609
2841
  __privateSet(this, _listener, apiTransport.onNotification(
2610
2842
  __privateMethod(this, _MetaMaskConnectMultichain_instances, onTransportNotification_fn).bind(this)
2611
2843
  ));
@@ -2617,7 +2849,7 @@ getStoredTransport_fn = function() {
2617
2849
  const apiTransport = new MWPTransport(dappClient, kvstore);
2618
2850
  __privateSet(this, _dappClient, dappClient);
2619
2851
  __privateSet(this, _transport2, apiTransport);
2620
- __privateGet(this, _providerTransportWrapper).setupNotifcationListener();
2852
+ __privateGet(this, _providerTransportWrapper).setupTransportNotificationListener();
2621
2853
  __privateSet(this, _listener, apiTransport.onNotification(
2622
2854
  __privateMethod(this, _MetaMaskConnectMultichain_instances, onTransportNotification_fn).bind(this)
2623
2855
  ));
@@ -2649,25 +2881,17 @@ setupTransport_fn = function() {
2649
2881
  };
2650
2882
  init_fn = function() {
2651
2883
  return __async(this, null, function* () {
2652
- var _a2;
2653
2884
  try {
2654
- if (typeof window !== "undefined" && ((_a2 = window.mmsdk) == null ? void 0 : _a2.isInitialized)) {
2655
- logger2("MetaMaskSDK: init already initialized");
2656
- } else {
2657
- yield __privateMethod(this, _MetaMaskConnectMultichain_instances, setupAnalytics_fn).call(this);
2658
- yield __privateMethod(this, _MetaMaskConnectMultichain_instances, setupTransport_fn).call(this);
2659
- try {
2660
- const baseProps = yield getBaseAnalyticsProperties(
2661
- this.options,
2662
- this.storage
2663
- );
2664
- analytics2.track("mmconnect_initialized", baseProps);
2665
- } catch (error) {
2666
- logger2("Error tracking initialized event", error);
2667
- }
2668
- if (typeof window !== "undefined") {
2669
- window.mmsdk = this;
2670
- }
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);
2671
2895
  }
2672
2896
  } catch (error) {
2673
2897
  yield this.storage.removeTransport();
@@ -2703,7 +2927,7 @@ setupMWP_fn = function() {
2703
2927
  __privateSet(this, _dappClient, dappClient);
2704
2928
  const apiTransport = new MWPTransport(dappClient, kvstore);
2705
2929
  __privateSet(this, _transport2, apiTransport);
2706
- __privateGet(this, _providerTransportWrapper).setupNotifcationListener();
2930
+ __privateGet(this, _providerTransportWrapper).setupTransportNotificationListener();
2707
2931
  __privateSet(this, _listener, this.transport.onNotification(
2708
2932
  __privateMethod(this, _MetaMaskConnectMultichain_instances, onTransportNotification_fn).bind(this)
2709
2933
  ));
@@ -2712,22 +2936,20 @@ setupMWP_fn = function() {
2712
2936
  };
2713
2937
  onBeforeUnload_fn = function() {
2714
2938
  return __async(this, null, function* () {
2715
- var _a2;
2716
- 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) {
2717
2941
  yield this.storage.removeTransport();
2718
2942
  }
2719
2943
  });
2720
2944
  };
2721
2945
  createBeforeUnloadListener_fn = function() {
2946
+ const handler = __privateMethod(this, _MetaMaskConnectMultichain_instances, onBeforeUnload_fn).bind(this);
2722
2947
  if (typeof window !== "undefined" && typeof window.addEventListener !== "undefined") {
2723
- window.addEventListener("beforeunload", __privateMethod(this, _MetaMaskConnectMultichain_instances, onBeforeUnload_fn).bind(this));
2948
+ window.addEventListener("beforeunload", handler);
2724
2949
  }
2725
2950
  return () => {
2726
2951
  if (typeof window !== "undefined" && typeof window.removeEventListener !== "undefined") {
2727
- window.removeEventListener(
2728
- "beforeunload",
2729
- __privateMethod(this, _MetaMaskConnectMultichain_instances, onBeforeUnload_fn).bind(this)
2730
- );
2952
+ window.removeEventListener("beforeunload", handler);
2731
2953
  }
2732
2954
  };
2733
2955
  };
@@ -2757,7 +2979,7 @@ renderInstallModalAsync_fn = function(desktopPreferred, scopes, caipAccountIds,
2757
2979
  }
2758
2980
  );
2759
2981
  (() => __async(this, null, function* () {
2760
- var _a2;
2982
+ var _a3;
2761
2983
  try {
2762
2984
  yield this.transport.connect({
2763
2985
  scopes,
@@ -2765,20 +2987,21 @@ renderInstallModalAsync_fn = function(desktopPreferred, scopes, caipAccountIds,
2765
2987
  sessionProperties
2766
2988
  });
2767
2989
  yield this.options.ui.factory.unload();
2768
- (_a2 = this.options.ui.factory.modal) == null ? void 0 : _a2.unmount();
2990
+ (_a3 = this.options.ui.factory.modal) == null ? void 0 : _a3.unmount();
2769
2991
  this.status = "connected";
2770
2992
  yield this.storage.setTransport("mwp" /* MWP */);
2771
2993
  } catch (error) {
2772
2994
  if (error instanceof ProtocolError) {
2773
2995
  if (error.code !== ErrorCode.REQUEST_EXPIRED) {
2774
2996
  this.status = "disconnected";
2997
+ yield this.options.ui.factory.unload(error);
2775
2998
  reject(error);
2776
2999
  }
2777
3000
  } else {
2778
3001
  this.status = "disconnected";
2779
- reject(
2780
- error instanceof Error ? error : new Error(String(error))
2781
- );
3002
+ const normalizedError = error instanceof Error ? error : new Error(String(error));
3003
+ yield this.options.ui.factory.unload(normalizedError);
3004
+ reject(normalizedError);
2782
3005
  }
2783
3006
  }
2784
3007
  }))().catch(() => {
@@ -2805,8 +3028,8 @@ renderInstallModalAsync_fn = function(desktopPreferred, scopes, caipAccountIds,
2805
3028
  };
2806
3029
  showInstallModal_fn = function(desktopPreferred, scopes, caipAccountIds, sessionProperties) {
2807
3030
  return __async(this, null, function* () {
2808
- var _a2;
2809
- (_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));
2810
3033
  if (this.options.ui.headless) {
2811
3034
  yield __privateMethod(this, _MetaMaskConnectMultichain_instances, headlessConnect_fn).call(this, scopes, caipAccountIds, sessionProperties);
2812
3035
  } else {
@@ -2865,7 +3088,7 @@ setupDefaultTransport_fn = function() {
2865
3088
  __privateMethod(this, _MetaMaskConnectMultichain_instances, onTransportNotification_fn).bind(this)
2866
3089
  ));
2867
3090
  __privateSet(this, _transport2, transport);
2868
- __privateGet(this, _providerTransportWrapper).setupNotifcationListener();
3091
+ __privateGet(this, _providerTransportWrapper).setupTransportNotificationListener();
2869
3092
  return transport;
2870
3093
  });
2871
3094
  };
@@ -2873,7 +3096,7 @@ deeplinkConnect_fn = function(scopes, caipAccountIds, sessionProperties) {
2873
3096
  return __async(this, null, function* () {
2874
3097
  return new Promise((resolve, reject) => __async(this, null, function* () {
2875
3098
  const dappClientMessageHandler = (payload) => {
2876
- var _a2;
3099
+ var _a3;
2877
3100
  if (typeof payload !== "object" || payload === null || !("data" in payload)) {
2878
3101
  return;
2879
3102
  }
@@ -2883,7 +3106,7 @@ deeplinkConnect_fn = function(scopes, caipAccountIds, sessionProperties) {
2883
3106
  this.dappClient.off("message", dappClientMessageHandler);
2884
3107
  reject(data.error);
2885
3108
  }
2886
- 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) {
2887
3110
  this.dappClient.off("message", dappClientMessageHandler);
2888
3111
  }
2889
3112
  }
@@ -2892,13 +3115,13 @@ deeplinkConnect_fn = function(scopes, caipAccountIds, sessionProperties) {
2892
3115
  let timeout;
2893
3116
  if (this.transport.isConnected()) {
2894
3117
  timeout = setTimeout(() => {
2895
- this.openDeeplinkIfNeeded();
3118
+ this.openSimpleDeeplinkIfNeeded();
2896
3119
  }, 250);
2897
3120
  } else {
2898
3121
  this.dappClient.once(
2899
3122
  "session_request",
2900
3123
  (sessionRequest) => {
2901
- var _a2;
3124
+ var _a3;
2902
3125
  const connectionRequest = {
2903
3126
  sessionRequest,
2904
3127
  metadata: {
@@ -2913,7 +3136,7 @@ deeplinkConnect_fn = function(scopes, caipAccountIds, sessionProperties) {
2913
3136
  connectionRequest
2914
3137
  );
2915
3138
  this.emit("display_uri", deeplink);
2916
- if ((_a2 = this.options.mobile) == null ? void 0 : _a2.preferredOpenLink) {
3139
+ if ((_a3 = this.options.mobile) == null ? void 0 : _a3.preferredOpenLink) {
2917
3140
  this.options.mobile.preferredOpenLink(deeplink, "_self");
2918
3141
  } else {
2919
3142
  openDeeplink(this.options, deeplink, universalLink);
@@ -2975,6 +3198,53 @@ handleConnection_fn = function(promise, scopes, transportType) {
2975
3198
  }));
2976
3199
  });
2977
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
+ };
2978
3248
  var MetaMaskConnectMultichain = _MetaMaskConnectMultichain;
2979
3249
 
2980
3250
  // src/store/index.ts
@@ -3159,7 +3429,7 @@ var Store = class extends StoreClient {
3159
3429
  // src/ui/ModalFactory.ts
3160
3430
  import MetaMaskOnboarding from "@metamask/onboarding";
3161
3431
  init_domain();
3162
- init_utils();
3432
+ init_utils2();
3163
3433
  var BaseModalFactory = class {
3164
3434
  /**
3165
3435
  * Creates a new modal factory instance.
@@ -3182,8 +3452,8 @@ var BaseModalFactory = class {
3182
3452
  }
3183
3453
  unload(error) {
3184
3454
  return __async(this, null, function* () {
3185
- var _a2, _b;
3186
- (_a2 = this.modal) == null ? void 0 : _a2.unmount();
3455
+ var _a3, _b;
3456
+ (_a3 = this.modal) == null ? void 0 : _a3.unmount();
3187
3457
  yield (_b = this.successCallback) == null ? void 0 : _b.call(this, error);
3188
3458
  });
3189
3459
  }
@@ -3253,8 +3523,8 @@ var BaseModalFactory = class {
3253
3523
  }
3254
3524
  renderInstallModal(showInstallModal, createConnectionRequest, successCallback, onDisplayUri) {
3255
3525
  return __async(this, null, function* () {
3256
- var _a2, _b;
3257
- (_a2 = this.modal) == null ? void 0 : _a2.unmount();
3526
+ var _a3, _b;
3527
+ (_a3 = this.modal) == null ? void 0 : _a3.unmount();
3258
3528
  yield this.preload();
3259
3529
  this.successCallback = successCallback;
3260
3530
  this.displayUriCallback = onDisplayUri;
@@ -3270,9 +3540,9 @@ var BaseModalFactory = class {
3270
3540
  link: qrCodeLink,
3271
3541
  sdkVersion: getVersion(),
3272
3542
  generateQRCode: (request) => __async(this, null, function* () {
3273
- var _a3;
3543
+ var _a4;
3274
3544
  const newLink = this.createConnectionDeeplink(request);
3275
- (_a3 = this.displayUriCallback) == null ? void 0 : _a3.call(this, newLink);
3545
+ (_a4 = this.displayUriCallback) == null ? void 0 : _a4.call(this, newLink);
3276
3546
  return newLink;
3277
3547
  }),
3278
3548
  onClose: this.onCloseModal.bind(this),
@@ -3286,8 +3556,8 @@ var BaseModalFactory = class {
3286
3556
  }
3287
3557
  renderOTPCodeModal(createOTPCode, successCallback, updateOTPCode) {
3288
3558
  return __async(this, null, function* () {
3289
- var _a2;
3290
- (_a2 = this.modal) == null ? void 0 : _a2.unmount();
3559
+ var _a3;
3560
+ (_a3 = this.modal) == null ? void 0 : _a3.unmount();
3291
3561
  yield this.preload();
3292
3562
  this.successCallback = successCallback;
3293
3563
  const container = this.getMountedContainer();