@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
@@ -55,14 +55,6 @@ var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read fr
55
55
  var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
56
56
  var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
57
57
  var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
58
- var __privateWrapper = (obj, member, setter, getter) => ({
59
- set _(value) {
60
- __privateSet(obj, member, value, setter);
61
- },
62
- get _() {
63
- return __privateGet(obj, member, getter);
64
- }
65
- });
66
58
  var __async = (__this, __arguments, generator) => {
67
59
  return new Promise((resolve, reject) => {
68
60
  var fulfilled = (value) => {
@@ -428,6 +420,34 @@ var init_multichain = __esm({
428
420
  super();
429
421
  this.options = options;
430
422
  }
423
+ /**
424
+ * Merges the given options into the current instance options.
425
+ * Only the mergeable keys are updated (api.supportedNetworks, ui.*, mobile.*, transport.extensionId, debug).
426
+ * The main thing to note is that the value for `dapp` is not merged as it does not make sense for
427
+ * subsequent calls to `createMultichainClient` to have a different `dapp` value.
428
+ * Used when createMultichainClient is called with an existing singleton.
429
+ *
430
+ * @param partial - Options to merge/overwrite onto the current instance
431
+ */
432
+ mergeOptions(partial) {
433
+ var _a2, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n;
434
+ const opts = this.options;
435
+ this.options = __spreadProps(__spreadValues({}, opts), {
436
+ api: __spreadProps(__spreadValues({}, opts.api), {
437
+ supportedNetworks: __spreadValues(__spreadValues({}, opts.api.supportedNetworks), (_b = (_a2 = partial.api) == null ? void 0 : _a2.supportedNetworks) != null ? _b : {})
438
+ }),
439
+ ui: __spreadProps(__spreadValues({}, opts.ui), {
440
+ headless: (_d = (_c = partial.ui) == null ? void 0 : _c.headless) != null ? _d : opts.ui.headless,
441
+ preferExtension: (_f = (_e = partial.ui) == null ? void 0 : _e.preferExtension) != null ? _f : opts.ui.preferExtension,
442
+ showInstallModal: (_h = (_g = partial.ui) == null ? void 0 : _g.showInstallModal) != null ? _h : opts.ui.showInstallModal
443
+ }),
444
+ mobile: __spreadValues(__spreadValues({}, opts.mobile), (_i = partial.mobile) != null ? _i : {}),
445
+ transport: __spreadProps(__spreadValues({}, (_j = opts.transport) != null ? _j : {}), {
446
+ extensionId: (_m = (_k = partial.transport) == null ? void 0 : _k.extensionId) != null ? _m : (_l = opts.transport) == null ? void 0 : _l.extensionId
447
+ }),
448
+ debug: (_n = partial.debug) != null ? _n : opts.debug
449
+ });
450
+ }
431
451
  };
432
452
  }
433
453
  });
@@ -613,6 +633,21 @@ var init_ui = __esm({
613
633
  });
614
634
 
615
635
  // src/multichain/utils/index.ts
636
+ function getGlobalObject() {
637
+ if (typeof globalThis !== "undefined") {
638
+ return globalThis;
639
+ }
640
+ if (typeof global !== "undefined") {
641
+ return global;
642
+ }
643
+ if (typeof self !== "undefined") {
644
+ return self;
645
+ }
646
+ if (typeof window !== "undefined") {
647
+ return window;
648
+ }
649
+ throw new Error("Unable to locate global object");
650
+ }
616
651
  function base64Encode(str) {
617
652
  if (typeof btoa !== "undefined") {
618
653
  return btoa(str);
@@ -646,6 +681,29 @@ function openDeeplink(options, deeplink, universalLink) {
646
681
  link.click();
647
682
  }
648
683
  }
684
+ function mergeRequestedSessionWithExisting(sessionData, scopes, caipAccountIds, sessionProperties) {
685
+ const existingCaipChainIds = Object.keys(sessionData.sessionScopes);
686
+ const existingCaipAccountIds = [];
687
+ Object.values(sessionData.sessionScopes).forEach((scopeObject) => {
688
+ if ((scopeObject == null ? void 0 : scopeObject.accounts) && Array.isArray(scopeObject.accounts)) {
689
+ scopeObject.accounts.forEach((account) => {
690
+ existingCaipAccountIds.push(account);
691
+ });
692
+ }
693
+ });
694
+ const mergedScopes = Array.from(
695
+ /* @__PURE__ */ new Set([...existingCaipChainIds, ...scopes])
696
+ );
697
+ const mergedCaipAccountIds = Array.from(
698
+ /* @__PURE__ */ new Set([...existingCaipAccountIds, ...caipAccountIds])
699
+ );
700
+ const mergedSessionProperties = __spreadValues(__spreadValues({}, sessionData.sessionProperties), sessionProperties);
701
+ return {
702
+ mergedScopes,
703
+ mergedCaipAccountIds,
704
+ mergedSessionProperties
705
+ };
706
+ }
649
707
  function getOptionalScopes(scopes) {
650
708
  return scopes.reduce(
651
709
  (prev, scope) => __spreadProps(__spreadValues({}, prev), {
@@ -784,7 +842,7 @@ function addValidAccounts(optionalScopes, validAccounts) {
784
842
  }
785
843
  return result;
786
844
  }
787
- var import_utils, import_pako, extractFavicon;
845
+ var import_utils, import_pako, extractFavicon, MAX, idCounter, getUniqueRequestId;
788
846
  var init_utils = __esm({
789
847
  "src/multichain/utils/index.ts"() {
790
848
  "use strict";
@@ -805,6 +863,12 @@ var init_utils = __esm({
805
863
  }
806
864
  return favicon;
807
865
  };
866
+ MAX = 4294967295;
867
+ idCounter = Math.floor(Math.random() * MAX);
868
+ getUniqueRequestId = () => {
869
+ idCounter = (idCounter + 1) % MAX;
870
+ return idCounter;
871
+ };
808
872
  }
809
873
  });
810
874
 
@@ -1475,7 +1539,7 @@ trackWalletActionRejected_fn = function(options) {
1475
1539
  var import_multichain_api_client = require("@metamask/multichain-api-client");
1476
1540
  init_utils();
1477
1541
  var DEFAULT_REQUEST_TIMEOUT = 60 * 1e3;
1478
- var _notificationCallbacks, _transport, _defaultRequestOptions, _reqId, _pendingRequests, _handleResponseListener, _handleNotificationListener, _DefaultTransport_instances, notifyCallbacks_fn, isMetamaskProviderEvent_fn, handleResponse_fn, handleNotification_fn, setupMessageListener_fn;
1542
+ var _notificationCallbacks, _transport, _defaultRequestOptions, _pendingRequests, _handleResponseListener, _handleNotificationListener, _DefaultTransport_instances, notifyCallbacks_fn, isMetamaskProviderEvent_fn, handleResponse_fn, handleNotification_fn, setupMessageListener_fn;
1479
1543
  var DefaultTransport = class {
1480
1544
  constructor() {
1481
1545
  __privateAdd(this, _DefaultTransport_instances);
@@ -1484,8 +1548,6 @@ var DefaultTransport = class {
1484
1548
  __privateAdd(this, _defaultRequestOptions, {
1485
1549
  timeout: DEFAULT_REQUEST_TIMEOUT
1486
1550
  });
1487
- // Use timestamp-based ID to avoid conflicts across disconnect/reconnect cycles
1488
- __privateAdd(this, _reqId, Date.now());
1489
1551
  __privateAdd(this, _pendingRequests, /* @__PURE__ */ new Map());
1490
1552
  __privateAdd(this, _handleResponseListener);
1491
1553
  __privateAdd(this, _handleNotificationListener);
@@ -1493,8 +1555,7 @@ var DefaultTransport = class {
1493
1555
  sendEip1193Message(payload, options) {
1494
1556
  return __async(this, null, function* () {
1495
1557
  __privateMethod(this, _DefaultTransport_instances, setupMessageListener_fn).call(this);
1496
- __privateSet(this, _reqId, __privateGet(this, _reqId) + 1);
1497
- const requestId = `${__privateGet(this, _reqId)}`;
1558
+ const requestId = String(getUniqueRequestId());
1498
1559
  const request = __spreadValues({
1499
1560
  jsonrpc: "2.0",
1500
1561
  id: requestId
@@ -1559,10 +1620,6 @@ var DefaultTransport = class {
1559
1620
  proposedCaipAccountIds
1560
1621
  );
1561
1622
  if (!hasSameScopesAndAccounts) {
1562
- yield this.request(
1563
- { method: "wallet_revokeSession", params: walletSession },
1564
- __privateGet(this, _defaultRequestOptions)
1565
- );
1566
1623
  const response = yield this.request(
1567
1624
  { method: "wallet_createSession", params: createSessionParams },
1568
1625
  __privateGet(this, _defaultRequestOptions)
@@ -1589,9 +1646,14 @@ var DefaultTransport = class {
1589
1646
  });
1590
1647
  }
1591
1648
  disconnect() {
1592
- return __async(this, null, function* () {
1649
+ return __async(this, arguments, function* (scopes = []) {
1650
+ yield this.request({ method: "wallet_revokeSession", params: { scopes } });
1651
+ const response = yield this.request({ method: "wallet_getSession" });
1652
+ const { sessionScopes } = response.result;
1653
+ if (Object.keys(sessionScopes).length > 0) {
1654
+ return;
1655
+ }
1593
1656
  __privateGet(this, _notificationCallbacks).clear();
1594
- yield this.request({ method: "wallet_revokeSession", params: {} });
1595
1657
  if (__privateGet(this, _handleResponseListener)) {
1596
1658
  window.removeEventListener("message", __privateGet(this, _handleResponseListener));
1597
1659
  __privateSet(this, _handleResponseListener, void 0);
@@ -1605,7 +1667,7 @@ var DefaultTransport = class {
1605
1667
  request.reject(new Error("Transport disconnected"));
1606
1668
  }
1607
1669
  __privateGet(this, _pendingRequests).clear();
1608
- return __privateGet(this, _transport).disconnect();
1670
+ yield __privateGet(this, _transport).disconnect();
1609
1671
  });
1610
1672
  }
1611
1673
  isConnected() {
@@ -1630,11 +1692,17 @@ var DefaultTransport = class {
1630
1692
  );
1631
1693
  });
1632
1694
  }
1695
+ getStoredPendingSessionRequest() {
1696
+ return __async(this, null, function* () {
1697
+ throw new Error(
1698
+ "getStoredPendingSessionRequest is purposely not implemented for the DefaultTransport"
1699
+ );
1700
+ });
1701
+ }
1633
1702
  };
1634
1703
  _notificationCallbacks = new WeakMap();
1635
1704
  _transport = new WeakMap();
1636
1705
  _defaultRequestOptions = new WeakMap();
1637
- _reqId = new WeakMap();
1638
1706
  _pendingRequests = new WeakMap();
1639
1707
  _handleResponseListener = new WeakMap();
1640
1708
  _handleNotificationListener = new WeakMap();
@@ -1704,18 +1772,12 @@ setupMessageListener_fn = function() {
1704
1772
 
1705
1773
  // src/multichain/transports/multichainApiClientWrapper/index.ts
1706
1774
  var import_rpc_errors = require("@metamask/rpc-errors");
1707
- var MAX = 4294967295;
1708
- var idCounter = Math.floor(Math.random() * MAX);
1709
- var getUniqueId = () => {
1710
- idCounter = (idCounter + 1) % MAX;
1711
- return idCounter;
1712
- };
1713
- var _requestId, _notificationCallbacks2, _MultichainApiClientWrapperTransport_instances, walletCreateSession_fn, walletGetSession_fn, walletRevokeSession_fn, walletInvokeMethod_fn;
1775
+ init_utils();
1776
+ var _notificationCallbacks2, _MultichainApiClientWrapperTransport_instances, walletCreateSession_fn, walletGetSession_fn, walletRevokeSession_fn, walletInvokeMethod_fn;
1714
1777
  var MultichainApiClientWrapperTransport = class {
1715
1778
  constructor(metamaskConnectMultichain) {
1716
1779
  this.metamaskConnectMultichain = metamaskConnectMultichain;
1717
1780
  __privateAdd(this, _MultichainApiClientWrapperTransport_instances);
1718
- __privateAdd(this, _requestId, getUniqueId());
1719
1781
  __privateAdd(this, _notificationCallbacks2, /* @__PURE__ */ new Set());
1720
1782
  }
1721
1783
  isTransportDefined() {
@@ -1733,15 +1795,23 @@ var MultichainApiClientWrapperTransport = class {
1733
1795
  callback(data);
1734
1796
  });
1735
1797
  }
1736
- setupNotifcationListener() {
1737
- this.metamaskConnectMultichain.transport.onNotification(
1798
+ clearTransportNotificationListener() {
1799
+ var _a2;
1800
+ (_a2 = this.notificationListener) == null ? void 0 : _a2.call(this);
1801
+ this.notificationListener = void 0;
1802
+ }
1803
+ setupTransportNotificationListener() {
1804
+ if (!this.isTransportDefined() || this.notificationListener) {
1805
+ return;
1806
+ }
1807
+ this.notificationListener = this.metamaskConnectMultichain.transport.onNotification(
1738
1808
  this.notifyCallbacks.bind(this)
1739
1809
  );
1740
1810
  }
1741
1811
  connect() {
1742
1812
  return __async(this, null, function* () {
1743
1813
  console.log("\u{1F4DA} connect");
1744
- return Promise.resolve();
1814
+ yield this.metamaskConnectMultichain.emitSessionChanged();
1745
1815
  });
1746
1816
  }
1747
1817
  disconnect() {
@@ -1754,7 +1824,7 @@ var MultichainApiClientWrapperTransport = class {
1754
1824
  }
1755
1825
  request(_0) {
1756
1826
  return __async(this, arguments, function* (params, _options = {}) {
1757
- const id = __privateWrapper(this, _requestId)._++;
1827
+ const id = getUniqueRequestId();
1758
1828
  const requestPayload = __spreadValues({
1759
1829
  id,
1760
1830
  jsonrpc: "2.0"
@@ -1775,16 +1845,13 @@ var MultichainApiClientWrapperTransport = class {
1775
1845
  });
1776
1846
  }
1777
1847
  onNotification(callback) {
1778
- if (!this.isTransportDefined()) {
1779
- __privateGet(this, _notificationCallbacks2).add(callback);
1780
- return () => {
1781
- __privateGet(this, _notificationCallbacks2).delete(callback);
1782
- };
1783
- }
1784
- return this.metamaskConnectMultichain.transport.onNotification(callback);
1848
+ this.setupTransportNotificationListener();
1849
+ __privateGet(this, _notificationCallbacks2).add(callback);
1850
+ return () => {
1851
+ __privateGet(this, _notificationCallbacks2).delete(callback);
1852
+ };
1785
1853
  }
1786
1854
  };
1787
- _requestId = new WeakMap();
1788
1855
  _notificationCallbacks2 = new WeakMap();
1789
1856
  _MultichainApiClientWrapperTransport_instances = new WeakSet();
1790
1857
  walletCreateSession_fn = function(request) {
@@ -1835,11 +1902,14 @@ walletGetSession_fn = function(request) {
1835
1902
  };
1836
1903
  walletRevokeSession_fn = function(request) {
1837
1904
  return __async(this, null, function* () {
1905
+ var _a2;
1838
1906
  if (!this.isTransportDefined()) {
1839
1907
  return { jsonrpc: "2.0", id: request.id, result: true };
1840
1908
  }
1909
+ const revokeSessionParams = request.params;
1910
+ const scopes = (_a2 = revokeSessionParams == null ? void 0 : revokeSessionParams.scopes) != null ? _a2 : [];
1841
1911
  try {
1842
- this.metamaskConnectMultichain.disconnect();
1912
+ yield this.metamaskConnectMultichain.disconnect(scopes);
1843
1913
  return { jsonrpc: "2.0", id: request.id, result: true };
1844
1914
  } catch (_error) {
1845
1915
  return { jsonrpc: "2.0", id: request.id, result: false };
@@ -1863,6 +1933,7 @@ walletInvokeMethod_fn = function(request) {
1863
1933
  // src/multichain/transports/mwp/index.ts
1864
1934
  var import_mobile_wallet_protocol_core = require("@metamask/mobile-wallet-protocol-core");
1865
1935
  var import_multichain_api_client2 = require("@metamask/multichain-api-client");
1936
+ var import_rpc_errors2 = require("@metamask/rpc-errors");
1866
1937
  init_domain();
1867
1938
  init_utils();
1868
1939
 
@@ -1877,6 +1948,7 @@ var DEFAULT_RESUME_TIMEOUT = 10 * 1e3;
1877
1948
  var SESSION_STORE_KEY = "cache_wallet_getSession";
1878
1949
  var ACCOUNTS_STORE_KEY = "cache_eth_accounts";
1879
1950
  var CHAIN_STORE_KEY = "cache_eth_chainId";
1951
+ var PENDING_SESSION_REQUEST_KEY = "pending_session_request";
1880
1952
  var CACHED_METHOD_LIST = [
1881
1953
  "wallet_getSession",
1882
1954
  "wallet_createSession",
@@ -1896,10 +1968,15 @@ var MWPTransport = class {
1896
1968
  this.dappClient = dappClient;
1897
1969
  this.kvstore = kvstore;
1898
1970
  this.options = options;
1899
- this.__reqId = 0;
1900
1971
  this.__pendingRequests = /* @__PURE__ */ new Map();
1901
1972
  this.notificationCallbacks = /* @__PURE__ */ new Set();
1902
1973
  this.dappClient.on("message", this.handleMessage.bind(this));
1974
+ this.dappClient.on("session_request", (sessionRequest) => {
1975
+ this.currentSessionRequest = sessionRequest;
1976
+ this.kvstore.set(PENDING_SESSION_REQUEST_KEY, JSON.stringify(sessionRequest)).catch((err) => {
1977
+ logger("Failed to store pending session request", err);
1978
+ });
1979
+ });
1903
1980
  if (typeof window !== "undefined" && typeof window.addEventListener !== "undefined") {
1904
1981
  this.windowFocusHandler = this.onWindowFocus.bind(this);
1905
1982
  window.addEventListener("focus", this.windowFocusHandler);
@@ -1914,6 +1991,34 @@ var MWPTransport = class {
1914
1991
  get sessionRequest() {
1915
1992
  return this.currentSessionRequest;
1916
1993
  }
1994
+ /**
1995
+ * Returns the stored pending session request from the dappClient session_request event, if any.
1996
+ *
1997
+ * @returns The stored SessionRequest, or null if none or invalid.
1998
+ */
1999
+ getStoredPendingSessionRequest() {
2000
+ return __async(this, null, function* () {
2001
+ try {
2002
+ const raw = yield this.kvstore.get(PENDING_SESSION_REQUEST_KEY);
2003
+ if (!raw) {
2004
+ return null;
2005
+ }
2006
+ return JSON.parse(raw);
2007
+ } catch (e) {
2008
+ return null;
2009
+ }
2010
+ });
2011
+ }
2012
+ /**
2013
+ * Removes the stored pending session request from the KVStore.
2014
+ * This is necessary to ensure that ConnectMultichain is able to correctly
2015
+ * infer the MWP Transport connection attempt status.
2016
+ */
2017
+ removeStoredPendingSessionRequest() {
2018
+ return __async(this, null, function* () {
2019
+ yield this.kvstore.delete(PENDING_SESSION_REQUEST_KEY);
2020
+ });
2021
+ }
1917
2022
  onWindowFocus() {
1918
2023
  if (!this.isConnected()) {
1919
2024
  this.dappClient.reconnect();
@@ -1930,6 +2035,17 @@ var MWPTransport = class {
1930
2035
  request.reject(error);
1931
2036
  }
1932
2037
  }
2038
+ parseWalletError(errorPayload) {
2039
+ const errorData = errorPayload;
2040
+ if (typeof errorData.code === "number" && typeof errorData.message === "string") {
2041
+ return import_rpc_errors2.providerErrors.custom({
2042
+ code: errorData.code,
2043
+ message: errorData.message
2044
+ });
2045
+ }
2046
+ const message = errorPayload instanceof Error ? errorPayload.message : JSON.stringify(errorPayload);
2047
+ return import_rpc_errors2.rpcErrors.internal({ message });
2048
+ }
1933
2049
  handleMessage(message) {
1934
2050
  if (typeof message === "object" && message !== null) {
1935
2051
  if ("data" in message) {
@@ -1937,6 +2053,12 @@ var MWPTransport = class {
1937
2053
  if ("id" in messagePayload && typeof messagePayload.id === "string") {
1938
2054
  const request = this.pendingRequests.get(messagePayload.id);
1939
2055
  if (request) {
2056
+ clearTimeout(request.timeout);
2057
+ if ("error" in messagePayload && messagePayload.error) {
2058
+ this.pendingRequests.delete(messagePayload.id);
2059
+ request.reject(this.parseWalletError(messagePayload.error));
2060
+ return;
2061
+ }
1940
2062
  const requestWithName = __spreadProps(__spreadValues({}, messagePayload), {
1941
2063
  method: request.method === "wallet_getSession" || request.method === "wallet_createSession" ? "wallet_sessionChanged" : request.method
1942
2064
  });
@@ -1944,7 +2066,6 @@ var MWPTransport = class {
1944
2066
  method: request.method === "wallet_getSession" || request.method === "wallet_createSession" ? "wallet_sessionChanged" : request.method,
1945
2067
  params: requestWithName.result
1946
2068
  });
1947
- clearTimeout(request.timeout);
1948
2069
  this.notifyCallbacks(notification);
1949
2070
  request.resolve(requestWithName);
1950
2071
  this.pendingRequests.delete(messagePayload.id);
@@ -2034,6 +2155,7 @@ var MWPTransport = class {
2034
2155
  }
2035
2156
  walletSession = response.result;
2036
2157
  }
2158
+ yield this.removeStoredPendingSessionRequest();
2037
2159
  this.notifyCallbacks({
2038
2160
  method: "wallet_sessionChanged",
2039
2161
  params: walletSession
@@ -2049,7 +2171,7 @@ var MWPTransport = class {
2049
2171
  return __async(this, null, function* () {
2050
2172
  const request = __spreadValues({
2051
2173
  jsonrpc: "2.0",
2052
- id: `${this.__reqId++}`
2174
+ id: String(getUniqueRequestId())
2053
2175
  }, payload);
2054
2176
  const cachedWalletSession = yield this.getCachedResponse(request);
2055
2177
  if (cachedWalletSession) {
@@ -2085,6 +2207,7 @@ var MWPTransport = class {
2085
2207
  if (session) {
2086
2208
  logger("active session found", session);
2087
2209
  }
2210
+ const storedSessionRequestBeforeConnectionAttempt = yield this.getStoredPendingSessionRequest();
2088
2211
  let timeout;
2089
2212
  let initialConnectionMessageHandler;
2090
2213
  const connectionPromise = new Promise((resolve, reject) => __async(this, null, function* () {
@@ -2115,33 +2238,35 @@ var MWPTransport = class {
2115
2238
  };
2116
2239
  const request = {
2117
2240
  jsonrpc: "2.0",
2118
- id: `${this.__reqId++}`,
2241
+ id: String(getUniqueRequestId()),
2119
2242
  method: "wallet_createSession",
2120
2243
  params: sessionRequest
2121
2244
  };
2122
2245
  initialConnectionMessageHandler = (message) => __async(this, null, function* () {
2123
- if (typeof message === "object" && message !== null) {
2124
- if ("data" in message) {
2125
- const messagePayload = message.data;
2126
- if (messagePayload.method === "wallet_createSession" || messagePayload.method === "wallet_sessionChanged") {
2127
- if (messagePayload.error) {
2128
- if (initialConnectionMessageHandler) {
2129
- this.dappClient.off(
2130
- "message",
2131
- initialConnectionMessageHandler
2132
- );
2133
- }
2134
- return rejectConnection(messagePayload.error);
2135
- }
2136
- yield this.storeWalletSession(
2137
- request,
2138
- messagePayload
2139
- );
2140
- this.notifyCallbacks(messagePayload);
2141
- return resolveConnection();
2142
- }
2143
- }
2246
+ if (typeof message !== "object" || message === null) {
2247
+ return;
2248
+ }
2249
+ if (!("data" in message)) {
2250
+ return;
2251
+ }
2252
+ const messagePayload = message.data;
2253
+ const isMatchingId = messagePayload.id === request.id;
2254
+ const isMatchingMethod = messagePayload.method === "wallet_createSession" || messagePayload.method === "wallet_sessionChanged";
2255
+ if (!isMatchingId && !isMatchingMethod) {
2256
+ return;
2144
2257
  }
2258
+ if (messagePayload.error) {
2259
+ return rejectConnection(
2260
+ this.parseWalletError(messagePayload.error)
2261
+ );
2262
+ }
2263
+ yield this.storeWalletSession(
2264
+ request,
2265
+ messagePayload
2266
+ );
2267
+ yield this.removeStoredPendingSessionRequest();
2268
+ this.notifyCallbacks(messagePayload);
2269
+ return resolveConnection();
2145
2270
  });
2146
2271
  this.dappClient.on("message", initialConnectionMessageHandler);
2147
2272
  dappClient.connect({
@@ -2162,14 +2287,18 @@ var MWPTransport = class {
2162
2287
  }
2163
2288
  );
2164
2289
  }
2165
- timeout = setTimeout(() => {
2166
- reject(new import_multichain_api_client2.TransportTimeoutError());
2167
- }, this.options.connectionTimeout);
2290
+ timeout = setTimeout(
2291
+ () => {
2292
+ reject(new import_multichain_api_client2.TransportTimeoutError());
2293
+ },
2294
+ storedSessionRequestBeforeConnectionAttempt ? this.options.resumeTimeout : this.options.connectionTimeout
2295
+ );
2168
2296
  connection.then(resolve).catch(reject);
2169
2297
  }));
2170
- return connectionPromise.catch((error) => {
2298
+ return connectionPromise.catch((error) => __async(this, null, function* () {
2299
+ yield this.dappClient.disconnect();
2171
2300
  throw error;
2172
- }).finally(() => {
2301
+ })).finally(() => {
2173
2302
  if (timeout) {
2174
2303
  clearTimeout(timeout);
2175
2304
  }
@@ -2177,24 +2306,68 @@ var MWPTransport = class {
2177
2306
  this.dappClient.off("message", initialConnectionMessageHandler);
2178
2307
  initialConnectionMessageHandler = void 0;
2179
2308
  }
2309
+ this.removeStoredPendingSessionRequest();
2180
2310
  });
2181
2311
  });
2182
2312
  }
2183
2313
  /**
2184
2314
  * Disconnects from the Mobile Wallet Protocol
2185
2315
  *
2316
+ * @param [scopes] - The scopes to revoke. If not provided or empty, all scopes will be revoked.
2186
2317
  * @returns Nothing
2187
2318
  */
2188
2319
  disconnect() {
2189
- return __async(this, null, function* () {
2190
- if (typeof window !== "undefined" && typeof window.removeEventListener !== "undefined" && this.windowFocusHandler) {
2191
- window.removeEventListener("focus", this.windowFocusHandler);
2192
- this.windowFocusHandler = void 0;
2193
- }
2194
- this.kvstore.delete(SESSION_STORE_KEY);
2195
- this.kvstore.delete(ACCOUNTS_STORE_KEY);
2196
- this.kvstore.delete(CHAIN_STORE_KEY);
2197
- return this.dappClient.disconnect();
2320
+ return __async(this, arguments, function* (scopes = []) {
2321
+ var _a2, _b;
2322
+ const cachedSession = yield this.getCachedResponse({
2323
+ jsonrpc: "2.0",
2324
+ id: "0",
2325
+ method: "wallet_getSession"
2326
+ });
2327
+ const cachedSessionScopes = (_b = (_a2 = cachedSession == null ? void 0 : cachedSession.result) == null ? void 0 : _a2.sessionScopes) != null ? _b : {};
2328
+ const remainingScopes = scopes.length === 0 ? [] : Object.keys(cachedSessionScopes).filter(
2329
+ (scope) => !scopes.includes(scope)
2330
+ );
2331
+ const newSessionScopes = Object.fromEntries(
2332
+ Object.entries(cachedSessionScopes).filter(
2333
+ ([key]) => remainingScopes.includes(key)
2334
+ )
2335
+ );
2336
+ this.request({ method: "wallet_revokeSession", params: { scopes } }).catch(
2337
+ (err) => {
2338
+ console.error("error revoking session", err);
2339
+ }
2340
+ );
2341
+ const remainingScopesIncludeEip155 = remainingScopes.some(
2342
+ (scope) => scope.includes("eip155")
2343
+ );
2344
+ if (!remainingScopesIncludeEip155) {
2345
+ this.kvstore.delete(ACCOUNTS_STORE_KEY);
2346
+ this.kvstore.delete(CHAIN_STORE_KEY);
2347
+ }
2348
+ if (remainingScopes.length > 0) {
2349
+ this.kvstore.set(
2350
+ SESSION_STORE_KEY,
2351
+ JSON.stringify({
2352
+ result: {
2353
+ sessionScopes: newSessionScopes
2354
+ }
2355
+ })
2356
+ );
2357
+ } else {
2358
+ this.kvstore.delete(SESSION_STORE_KEY);
2359
+ if (typeof window !== "undefined" && typeof window.removeEventListener !== "undefined" && this.windowFocusHandler) {
2360
+ window.removeEventListener("focus", this.windowFocusHandler);
2361
+ this.windowFocusHandler = void 0;
2362
+ }
2363
+ yield this.dappClient.disconnect();
2364
+ }
2365
+ this.notifyCallbacks({
2366
+ method: "wallet_sessionChanged",
2367
+ params: {
2368
+ sessionScopes: newSessionScopes
2369
+ }
2370
+ });
2198
2371
  });
2199
2372
  }
2200
2373
  /**
@@ -2300,7 +2473,7 @@ var MWPTransport = class {
2300
2473
  return __async(this, null, function* () {
2301
2474
  const request = __spreadValues({
2302
2475
  jsonrpc: "2.0",
2303
- id: `${this.__reqId++}`
2476
+ id: String(getUniqueRequestId())
2304
2477
  }, payload);
2305
2478
  const cachedWalletSession = yield this.getCachedResponse(request);
2306
2479
  if (cachedWalletSession) {
@@ -2382,6 +2555,7 @@ var MWPTransport = class {
2382
2555
  const timeoutPromise = new Promise((_resolve, reject) => {
2383
2556
  setTimeout(() => {
2384
2557
  unsubscribe();
2558
+ this.removeStoredPendingSessionRequest();
2385
2559
  reject(new import_multichain_api_client2.TransportTimeoutError());
2386
2560
  }, this.options.resumeTimeout);
2387
2561
  });
@@ -2420,7 +2594,8 @@ var keymanager = new KeyManager();
2420
2594
  // src/multichain/index.ts
2421
2595
  init_utils();
2422
2596
  var logger2 = createLogger("metamask-sdk:core");
2423
- 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;
2597
+ var SINGLETON_KEY = "__METAMASK_CONNECT_MULTICHAIN_SINGLETON__";
2598
+ 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, getCaipSession_fn, openConnectDeeplinkIfNeeded_fn;
2424
2599
  var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends MultichainCore {
2425
2600
  constructor(options) {
2426
2601
  var _a2, _b, _c, _d, _e, _f;
@@ -2485,27 +2660,54 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
2485
2660
  get transportType() {
2486
2661
  return __privateGet(this, _transport2) instanceof MWPTransport ? "mwp" /* MWP */ : "browser" /* Browser */;
2487
2662
  }
2663
+ // Creates a singleton instance of MetaMaskConnectMultichain.
2664
+ // If the singleton already exists, it merges the incoming options with the
2665
+ // existing singleton options for the following keys: `api.supportedNetworks`,
2666
+ // `ui.*`, `mobile.*`, `transport.extensionId`, `debug`. Take note that the
2667
+ // value for `dapp` is not merged as it does not make sense for subsequent calls to
2668
+ // `createMultichainClient` to have a different `dapp` value.
2488
2669
  static create(options) {
2489
2670
  return __async(this, null, function* () {
2490
- var _a2;
2491
- const instance = new _MetaMaskConnectMultichain(options);
2492
- const isEnabled2 = yield isEnabled(
2493
- "metamask-sdk:core",
2494
- instance.options.storage
2495
- );
2496
- if (isEnabled2) {
2497
- enableDebug("metamask-sdk:core");
2671
+ const globalObject = getGlobalObject();
2672
+ const existing = globalObject[SINGLETON_KEY];
2673
+ if (existing) {
2674
+ const instance = yield existing;
2675
+ instance.mergeOptions(options);
2676
+ if (options.debug) {
2677
+ enableDebug("metamask-sdk:*");
2678
+ }
2679
+ return instance;
2498
2680
  }
2499
- yield __privateMethod(_a2 = instance, _MetaMaskConnectMultichain_instances, init_fn).call(_a2);
2500
- return instance;
2681
+ const instancePromise = (() => __async(null, null, function* () {
2682
+ var _a2;
2683
+ const instance = new _MetaMaskConnectMultichain(options);
2684
+ const isEnabled2 = yield isEnabled(
2685
+ "metamask-sdk:core",
2686
+ instance.options.storage
2687
+ );
2688
+ if (isEnabled2) {
2689
+ enableDebug("metamask-sdk:core");
2690
+ }
2691
+ yield __privateMethod(_a2 = instance, _MetaMaskConnectMultichain_instances, init_fn).call(_a2);
2692
+ return instance;
2693
+ }))();
2694
+ globalObject[SINGLETON_KEY] = instancePromise;
2695
+ instancePromise.catch((error) => {
2696
+ globalObject[SINGLETON_KEY] = void 0;
2697
+ console.error("Error initializing MetaMaskConnectMultichain", error);
2698
+ });
2699
+ return instancePromise;
2501
2700
  });
2502
2701
  }
2503
2702
  // TODO: make this into param object
2504
2703
  connect(scopes, caipAccountIds, sessionProperties, forceRequest) {
2505
2704
  return __async(this, null, function* () {
2506
2705
  var _a2;
2507
- if (this.status !== "connected") {
2508
- yield this.disconnect();
2706
+ if (this.status === "connecting" && this.transportType === "mwp" /* MWP */) {
2707
+ yield __privateMethod(this, _MetaMaskConnectMultichain_instances, openConnectDeeplinkIfNeeded_fn).call(this);
2708
+ throw new Error(
2709
+ "Existing connection is pending. Please check your MetaMask Mobile app to continue."
2710
+ );
2509
2711
  }
2510
2712
  const { ui } = this.options;
2511
2713
  const platformType = getPlatformType();
@@ -2535,12 +2737,19 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
2535
2737
  } catch (error) {
2536
2738
  logger2("Error tracking connection_initiated event", error);
2537
2739
  }
2538
- const nonEmptySessionProperites = Object.keys(sessionProperties != null ? sessionProperties : {}).length > 0 ? sessionProperties : void 0;
2740
+ const sessionData = yield __privateMethod(this, _MetaMaskConnectMultichain_instances, getCaipSession_fn).call(this);
2741
+ const { mergedScopes, mergedCaipAccountIds, mergedSessionProperties } = mergeRequestedSessionWithExisting(
2742
+ sessionData,
2743
+ scopes,
2744
+ caipAccountIds,
2745
+ sessionProperties
2746
+ );
2747
+ const nonEmptySessionProperties = Object.keys(mergedSessionProperties != null ? mergedSessionProperties : {}).length > 0 ? mergedSessionProperties : void 0;
2539
2748
  if (((_a2 = __privateGet(this, _transport2)) == null ? void 0 : _a2.isConnected()) && !secure) {
2540
2749
  return __privateMethod(this, _MetaMaskConnectMultichain_instances, handleConnection_fn).call(this, __privateGet(this, _transport2).connect({
2541
- scopes,
2542
- caipAccountIds,
2543
- sessionProperties: nonEmptySessionProperites,
2750
+ scopes: mergedScopes,
2751
+ caipAccountIds: mergedCaipAccountIds,
2752
+ sessionProperties: nonEmptySessionProperties,
2544
2753
  forceRequest
2545
2754
  }).then(() => __async(this, null, function* () {
2546
2755
  if (__privateGet(this, _transport2) instanceof MWPTransport) {
@@ -2552,27 +2761,27 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
2552
2761
  if (platformType === "in-app-browser" /* MetaMaskMobileWebview */) {
2553
2762
  const defaultTransport = yield __privateMethod(this, _MetaMaskConnectMultichain_instances, setupDefaultTransport_fn).call(this);
2554
2763
  return __privateMethod(this, _MetaMaskConnectMultichain_instances, handleConnection_fn).call(this, defaultTransport.connect({
2555
- scopes,
2556
- caipAccountIds,
2557
- sessionProperties: nonEmptySessionProperites,
2764
+ scopes: mergedScopes,
2765
+ caipAccountIds: mergedCaipAccountIds,
2766
+ sessionProperties: nonEmptySessionProperties,
2558
2767
  forceRequest
2559
2768
  }), scopes, transportType);
2560
2769
  }
2561
2770
  if (isWeb && hasExtensionInstalled && preferExtension) {
2562
2771
  const defaultTransport = yield __privateMethod(this, _MetaMaskConnectMultichain_instances, setupDefaultTransport_fn).call(this);
2563
2772
  return __privateMethod(this, _MetaMaskConnectMultichain_instances, handleConnection_fn).call(this, defaultTransport.connect({
2564
- scopes,
2565
- caipAccountIds,
2566
- sessionProperties: nonEmptySessionProperites,
2773
+ scopes: mergedScopes,
2774
+ caipAccountIds: mergedCaipAccountIds,
2775
+ sessionProperties: nonEmptySessionProperties,
2567
2776
  forceRequest
2568
2777
  }), scopes, transportType);
2569
2778
  }
2570
2779
  yield __privateMethod(this, _MetaMaskConnectMultichain_instances, setupMWP_fn).call(this);
2571
2780
  const shouldShowInstallModal = hasExtensionInstalled ? showInstallModal : !preferExtension || showInstallModal;
2572
2781
  if (secure && !shouldShowInstallModal) {
2573
- return __privateMethod(this, _MetaMaskConnectMultichain_instances, handleConnection_fn).call(this, __privateMethod(this, _MetaMaskConnectMultichain_instances, deeplinkConnect_fn).call(this, scopes, caipAccountIds, nonEmptySessionProperites), scopes, transportType);
2782
+ return __privateMethod(this, _MetaMaskConnectMultichain_instances, handleConnection_fn).call(this, __privateMethod(this, _MetaMaskConnectMultichain_instances, deeplinkConnect_fn).call(this, mergedScopes, mergedCaipAccountIds, nonEmptySessionProperties), scopes, transportType);
2574
2783
  }
2575
- return __privateMethod(this, _MetaMaskConnectMultichain_instances, handleConnection_fn).call(this, __privateMethod(this, _MetaMaskConnectMultichain_instances, showInstallModal_fn).call(this, shouldShowInstallModal, scopes, caipAccountIds, nonEmptySessionProperites), scopes, transportType);
2784
+ return __privateMethod(this, _MetaMaskConnectMultichain_instances, handleConnection_fn).call(this, __privateMethod(this, _MetaMaskConnectMultichain_instances, showInstallModal_fn).call(this, shouldShowInstallModal, mergedScopes, mergedCaipAccountIds, nonEmptySessionProperties), scopes, transportType);
2576
2785
  });
2577
2786
  }
2578
2787
  emit(event, args) {
@@ -2581,18 +2790,24 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
2581
2790
  super.emit(event, args);
2582
2791
  }
2583
2792
  disconnect() {
2584
- return __async(this, null, function* () {
2793
+ return __async(this, arguments, function* (scopes = []) {
2585
2794
  var _a2, _b, _c;
2586
- yield (_a2 = __privateGet(this, _listener)) == null ? void 0 : _a2.call(this);
2587
- (_b = __privateGet(this, _beforeUnloadListener)) == null ? void 0 : _b.call(this);
2588
- yield (_c = __privateGet(this, _transport2)) == null ? void 0 : _c.disconnect();
2589
- yield this.storage.removeTransport();
2590
- this.emit("stateChanged", "disconnected");
2591
- __privateSet(this, _listener, void 0);
2592
- __privateSet(this, _beforeUnloadListener, void 0);
2593
- __privateSet(this, _transport2, void 0);
2594
- __privateGet(this, _providerTransportWrapper).clearNotificationCallbacks();
2595
- __privateSet(this, _dappClient, void 0);
2795
+ const sessionData = yield __privateMethod(this, _MetaMaskConnectMultichain_instances, getCaipSession_fn).call(this);
2796
+ const remainingScopes = scopes.length === 0 ? [] : Object.keys(sessionData.sessionScopes).filter(
2797
+ (scope) => !scopes.includes(scope)
2798
+ );
2799
+ yield (_a2 = __privateGet(this, _transport2)) == null ? void 0 : _a2.disconnect(scopes);
2800
+ if (remainingScopes.length === 0) {
2801
+ yield (_b = __privateGet(this, _listener)) == null ? void 0 : _b.call(this);
2802
+ (_c = __privateGet(this, _beforeUnloadListener)) == null ? void 0 : _c.call(this);
2803
+ yield this.storage.removeTransport();
2804
+ __privateSet(this, _listener, void 0);
2805
+ __privateSet(this, _beforeUnloadListener, void 0);
2806
+ __privateSet(this, _transport2, void 0);
2807
+ __privateGet(this, _providerTransportWrapper).clearTransportNotificationListener();
2808
+ __privateSet(this, _dappClient, void 0);
2809
+ this.status = "disconnected";
2810
+ }
2596
2811
  });
2597
2812
  }
2598
2813
  invokeMethod(request) {
@@ -2604,7 +2819,7 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
2604
2819
  });
2605
2820
  }
2606
2821
  // DRY THIS WITH REQUEST ROUTER
2607
- openDeeplinkIfNeeded() {
2822
+ openSimpleDeeplinkIfNeeded() {
2608
2823
  const { ui, mobile } = this.options;
2609
2824
  const { showInstallModal = false } = ui != null ? ui : {};
2610
2825
  const secure = isSecure();
@@ -2624,6 +2839,23 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
2624
2839
  }), 10);
2625
2840
  }
2626
2841
  }
2842
+ // Provides a way for ecosystem clients (EVM, Solana, etc.) to get the current CAIP session data
2843
+ // when instantiating themselves (as they would have already missed any initial sessionChanged events emitted by ConnectMultichain)
2844
+ // without having to concern themselves with the current transport connection status.
2845
+ emitSessionChanged() {
2846
+ return __async(this, null, function* () {
2847
+ var _a2;
2848
+ const emptySession = { sessionScopes: {} };
2849
+ if (this.status !== "connected" && this.status !== "connecting") {
2850
+ this.emit("wallet_sessionChanged", emptySession);
2851
+ return;
2852
+ }
2853
+ const response = yield this.transport.request({
2854
+ method: "wallet_getSession"
2855
+ });
2856
+ this.emit("wallet_sessionChanged", (_a2 = response.result) != null ? _a2 : emptySession);
2857
+ });
2858
+ }
2627
2859
  };
2628
2860
  _provider = new WeakMap();
2629
2861
  _providerTransportWrapper = new WeakMap();
@@ -2673,7 +2905,7 @@ getStoredTransport_fn = function() {
2673
2905
  if (hasExtensionInstalled) {
2674
2906
  const apiTransport = new DefaultTransport();
2675
2907
  __privateSet(this, _transport2, apiTransport);
2676
- __privateGet(this, _providerTransportWrapper).setupNotifcationListener();
2908
+ __privateGet(this, _providerTransportWrapper).setupTransportNotificationListener();
2677
2909
  __privateSet(this, _listener, apiTransport.onNotification(
2678
2910
  __privateMethod(this, _MetaMaskConnectMultichain_instances, onTransportNotification_fn).bind(this)
2679
2911
  ));
@@ -2685,7 +2917,7 @@ getStoredTransport_fn = function() {
2685
2917
  const apiTransport = new MWPTransport(dappClient, kvstore);
2686
2918
  __privateSet(this, _dappClient, dappClient);
2687
2919
  __privateSet(this, _transport2, apiTransport);
2688
- __privateGet(this, _providerTransportWrapper).setupNotifcationListener();
2920
+ __privateGet(this, _providerTransportWrapper).setupTransportNotificationListener();
2689
2921
  __privateSet(this, _listener, apiTransport.onNotification(
2690
2922
  __privateMethod(this, _MetaMaskConnectMultichain_instances, onTransportNotification_fn).bind(this)
2691
2923
  ));
@@ -2717,25 +2949,17 @@ setupTransport_fn = function() {
2717
2949
  };
2718
2950
  init_fn = function() {
2719
2951
  return __async(this, null, function* () {
2720
- var _a2;
2721
2952
  try {
2722
- if (typeof window !== "undefined" && ((_a2 = window.mmsdk) == null ? void 0 : _a2.isInitialized)) {
2723
- logger2("MetaMaskSDK: init already initialized");
2724
- } else {
2725
- yield __privateMethod(this, _MetaMaskConnectMultichain_instances, setupAnalytics_fn).call(this);
2726
- yield __privateMethod(this, _MetaMaskConnectMultichain_instances, setupTransport_fn).call(this);
2727
- try {
2728
- const baseProps = yield getBaseAnalyticsProperties(
2729
- this.options,
2730
- this.storage
2731
- );
2732
- import_analytics4.analytics.track("mmconnect_initialized", baseProps);
2733
- } catch (error) {
2734
- logger2("Error tracking initialized event", error);
2735
- }
2736
- if (typeof window !== "undefined") {
2737
- window.mmsdk = this;
2738
- }
2953
+ yield __privateMethod(this, _MetaMaskConnectMultichain_instances, setupAnalytics_fn).call(this);
2954
+ yield __privateMethod(this, _MetaMaskConnectMultichain_instances, setupTransport_fn).call(this);
2955
+ try {
2956
+ const baseProps = yield getBaseAnalyticsProperties(
2957
+ this.options,
2958
+ this.storage
2959
+ );
2960
+ import_analytics4.analytics.track("mmconnect_initialized", baseProps);
2961
+ } catch (error) {
2962
+ logger2("Error tracking initialized event", error);
2739
2963
  }
2740
2964
  } catch (error) {
2741
2965
  yield this.storage.removeTransport();
@@ -2771,7 +2995,7 @@ setupMWP_fn = function() {
2771
2995
  __privateSet(this, _dappClient, dappClient);
2772
2996
  const apiTransport = new MWPTransport(dappClient, kvstore);
2773
2997
  __privateSet(this, _transport2, apiTransport);
2774
- __privateGet(this, _providerTransportWrapper).setupNotifcationListener();
2998
+ __privateGet(this, _providerTransportWrapper).setupTransportNotificationListener();
2775
2999
  __privateSet(this, _listener, this.transport.onNotification(
2776
3000
  __privateMethod(this, _MetaMaskConnectMultichain_instances, onTransportNotification_fn).bind(this)
2777
3001
  ));
@@ -2787,15 +3011,13 @@ onBeforeUnload_fn = function() {
2787
3011
  });
2788
3012
  };
2789
3013
  createBeforeUnloadListener_fn = function() {
3014
+ const handler = __privateMethod(this, _MetaMaskConnectMultichain_instances, onBeforeUnload_fn).bind(this);
2790
3015
  if (typeof window !== "undefined" && typeof window.addEventListener !== "undefined") {
2791
- window.addEventListener("beforeunload", __privateMethod(this, _MetaMaskConnectMultichain_instances, onBeforeUnload_fn).bind(this));
3016
+ window.addEventListener("beforeunload", handler);
2792
3017
  }
2793
3018
  return () => {
2794
3019
  if (typeof window !== "undefined" && typeof window.removeEventListener !== "undefined") {
2795
- window.removeEventListener(
2796
- "beforeunload",
2797
- __privateMethod(this, _MetaMaskConnectMultichain_instances, onBeforeUnload_fn).bind(this)
2798
- );
3020
+ window.removeEventListener("beforeunload", handler);
2799
3021
  }
2800
3022
  };
2801
3023
  };
@@ -2840,13 +3062,14 @@ renderInstallModalAsync_fn = function(desktopPreferred, scopes, caipAccountIds,
2840
3062
  if (error instanceof import_mobile_wallet_protocol_core2.ProtocolError) {
2841
3063
  if (error.code !== import_mobile_wallet_protocol_core2.ErrorCode.REQUEST_EXPIRED) {
2842
3064
  this.status = "disconnected";
3065
+ yield this.options.ui.factory.unload(error);
2843
3066
  reject(error);
2844
3067
  }
2845
3068
  } else {
2846
3069
  this.status = "disconnected";
2847
- reject(
2848
- error instanceof Error ? error : new Error(String(error))
2849
- );
3070
+ const normalizedError = error instanceof Error ? error : new Error(String(error));
3071
+ yield this.options.ui.factory.unload(normalizedError);
3072
+ reject(normalizedError);
2850
3073
  }
2851
3074
  }
2852
3075
  }))().catch(() => {
@@ -2933,7 +3156,7 @@ setupDefaultTransport_fn = function() {
2933
3156
  __privateMethod(this, _MetaMaskConnectMultichain_instances, onTransportNotification_fn).bind(this)
2934
3157
  ));
2935
3158
  __privateSet(this, _transport2, transport);
2936
- __privateGet(this, _providerTransportWrapper).setupNotifcationListener();
3159
+ __privateGet(this, _providerTransportWrapper).setupTransportNotificationListener();
2937
3160
  return transport;
2938
3161
  });
2939
3162
  };
@@ -2960,7 +3183,7 @@ deeplinkConnect_fn = function(scopes, caipAccountIds, sessionProperties) {
2960
3183
  let timeout;
2961
3184
  if (this.transport.isConnected()) {
2962
3185
  timeout = setTimeout(() => {
2963
- this.openDeeplinkIfNeeded();
3186
+ this.openSimpleDeeplinkIfNeeded();
2964
3187
  }, 250);
2965
3188
  } else {
2966
3189
  this.dappClient.once(
@@ -3043,6 +3266,53 @@ handleConnection_fn = function(promise, scopes, transportType) {
3043
3266
  }));
3044
3267
  });
3045
3268
  };
3269
+ getCaipSession_fn = function() {
3270
+ return __async(this, null, function* () {
3271
+ let sessionData = {
3272
+ sessionScopes: {},
3273
+ sessionProperties: {}
3274
+ };
3275
+ if (this.status === "connected") {
3276
+ const response = yield this.transport.request({
3277
+ method: "wallet_getSession"
3278
+ });
3279
+ if (response.result) {
3280
+ sessionData = response.result;
3281
+ }
3282
+ }
3283
+ return sessionData;
3284
+ });
3285
+ };
3286
+ openConnectDeeplinkIfNeeded_fn = function() {
3287
+ return __async(this, null, function* () {
3288
+ var _a2, _b;
3289
+ const { ui } = this.options;
3290
+ const { showInstallModal = false } = ui != null ? ui : {};
3291
+ const secure = isSecure();
3292
+ const shouldOpenDeeplink = secure && !showInstallModal;
3293
+ if (!shouldOpenDeeplink) {
3294
+ return;
3295
+ }
3296
+ const storedSessionRequest = yield (_a2 = __privateGet(this, _transport2)) == null ? void 0 : _a2.getStoredPendingSessionRequest();
3297
+ if (!storedSessionRequest) {
3298
+ return;
3299
+ }
3300
+ const connectionRequest = {
3301
+ sessionRequest: storedSessionRequest,
3302
+ metadata: {
3303
+ dapp: this.options.dapp,
3304
+ sdk: { version: getVersion(), platform: getPlatformType() }
3305
+ }
3306
+ };
3307
+ const deeplink = this.options.ui.factory.createConnectionDeeplink(connectionRequest);
3308
+ const universalLink = this.options.ui.factory.createConnectionUniversalLink(connectionRequest);
3309
+ if ((_b = this.options.mobile) == null ? void 0 : _b.preferredOpenLink) {
3310
+ this.options.mobile.preferredOpenLink(deeplink, "_self");
3311
+ } else {
3312
+ openDeeplink(this.options, deeplink, universalLink);
3313
+ }
3314
+ });
3315
+ };
3046
3316
  var MetaMaskConnectMultichain = _MetaMaskConnectMultichain;
3047
3317
 
3048
3318
  // src/store/index.ts