@metamask/connect-multichain 0.14.0 → 1.0.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 (77) hide show
  1. package/CHANGELOG.md +35 -1
  2. package/README.md +19 -19
  3. package/dist/browser/es/connect-multichain.d.mts +23 -10
  4. package/dist/browser/es/connect-multichain.mjs +595 -475
  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 +23 -10
  8. package/dist/browser/iife/connect-multichain.js +626 -475
  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 +23 -10
  12. package/dist/browser/umd/connect-multichain.js +595 -475
  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 +23 -10
  16. package/dist/node/cjs/connect-multichain.js +597 -473
  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 +23 -10
  20. package/dist/node/es/connect-multichain.mjs +594 -472
  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 +23 -10
  24. package/dist/react-native/es/connect-multichain.mjs +593 -471
  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/api/constants.d.ts +1 -0
  28. package/dist/src/domain/multichain/api/constants.d.ts.map +1 -1
  29. package/dist/src/domain/multichain/api/constants.js +13 -0
  30. package/dist/src/domain/multichain/api/constants.js.map +1 -1
  31. package/dist/src/domain/multichain/index.d.ts +3 -3
  32. package/dist/src/domain/multichain/index.d.ts.map +1 -1
  33. package/dist/src/domain/multichain/index.js +7 -3
  34. package/dist/src/domain/multichain/index.js.map +1 -1
  35. package/dist/src/domain/multichain/types.d.ts +15 -4
  36. package/dist/src/domain/multichain/types.d.ts.map +1 -1
  37. package/dist/src/domain/platform/index.d.ts.map +1 -1
  38. package/dist/src/domain/platform/index.js +27 -5
  39. package/dist/src/domain/platform/index.js.map +1 -1
  40. package/dist/src/domain/store/client.d.ts +3 -3
  41. package/dist/src/domain/store/client.d.ts.map +1 -1
  42. package/dist/src/domain/utils/index.d.ts +1 -0
  43. package/dist/src/domain/utils/index.d.ts.map +1 -1
  44. package/dist/src/domain/utils/index.js +5 -1
  45. package/dist/src/domain/utils/index.js.map +1 -1
  46. package/dist/src/multichain/index.d.ts +2 -3
  47. package/dist/src/multichain/index.d.ts.map +1 -1
  48. package/dist/src/multichain/index.js +248 -207
  49. package/dist/src/multichain/index.js.map +1 -1
  50. package/dist/src/multichain/rpc/requestRouter.d.ts +15 -0
  51. package/dist/src/multichain/rpc/requestRouter.d.ts.map +1 -1
  52. package/dist/src/multichain/rpc/requestRouter.js +54 -10
  53. package/dist/src/multichain/rpc/requestRouter.js.map +1 -1
  54. package/dist/src/multichain/transports/default/index.d.ts.map +1 -1
  55. package/dist/src/multichain/transports/default/index.js +16 -10
  56. package/dist/src/multichain/transports/default/index.js.map +1 -1
  57. package/dist/src/multichain/transports/multichainApiClientWrapper/index.d.ts +2 -1
  58. package/dist/src/multichain/transports/multichainApiClientWrapper/index.d.ts.map +1 -1
  59. package/dist/src/multichain/transports/multichainApiClientWrapper/index.js +25 -17
  60. package/dist/src/multichain/transports/multichainApiClientWrapper/index.js.map +1 -1
  61. package/dist/src/multichain/transports/mwp/index.d.ts +3 -1
  62. package/dist/src/multichain/transports/mwp/index.d.ts.map +1 -1
  63. package/dist/src/multichain/transports/mwp/index.js +227 -170
  64. package/dist/src/multichain/transports/mwp/index.js.map +1 -1
  65. package/dist/src/store/index.d.ts +3 -3
  66. package/dist/src/store/index.d.ts.map +1 -1
  67. package/dist/src/store/index.js +8 -8
  68. package/dist/src/store/index.js.map +1 -1
  69. package/dist/src/ui/ModalFactory.d.ts.map +1 -1
  70. package/dist/src/ui/ModalFactory.js +5 -1
  71. package/dist/src/ui/ModalFactory.js.map +1 -1
  72. package/dist/src/ui/index.js +1 -1
  73. package/dist/src/ui/index.js.map +1 -1
  74. package/dist/src/ui/modals/web/install.d.ts.map +1 -1
  75. package/dist/src/ui/modals/web/install.js.map +1 -1
  76. package/dist/types/connect-multichain.d.ts +23 -10
  77. package/package.json +3 -3
@@ -9518,6 +9518,19 @@ var MetaMaskSDK = (() => {
9518
9518
  });
9519
9519
 
9520
9520
  // ../../node_modules/@metamask/utils/dist/promise.mjs
9521
+ function createDeferredPromise({ suppressUnhandledRejection = false } = {}) {
9522
+ let resolve;
9523
+ let reject;
9524
+ const promise = new Promise((innerResolve, innerReject) => {
9525
+ resolve = innerResolve;
9526
+ reject = innerReject;
9527
+ });
9528
+ if (suppressUnhandledRejection) {
9529
+ promise.catch((_error) => {
9530
+ });
9531
+ }
9532
+ return { promise, resolve, reject };
9533
+ }
9521
9534
  var init_promise = __esm({
9522
9535
  "../../node_modules/@metamask/utils/dist/promise.mjs"() {
9523
9536
  "use strict";
@@ -16066,7 +16079,7 @@ var MetaMaskSDK = (() => {
16066
16079
  });
16067
16080
 
16068
16081
  // src/domain/multichain/api/constants.ts
16069
- var infuraRpcUrls, RPC_HANDLED_METHODS, SDK_HANDLED_METHODS;
16082
+ var infuraRpcUrls, RPC_HANDLED_METHODS, SDK_HANDLED_METHODS, EIP1193_PASSTHROUGH_METHODS;
16070
16083
  var init_constants = __esm({
16071
16084
  "src/domain/multichain/api/constants.ts"() {
16072
16085
  "use strict";
@@ -16231,6 +16244,11 @@ var MetaMaskSDK = (() => {
16231
16244
  "eth_uninstallFilter"
16232
16245
  ]);
16233
16246
  SDK_HANDLED_METHODS = /* @__PURE__ */ new Set(["eth_accounts", "eth_chainId"]);
16247
+ EIP1193_PASSTHROUGH_METHODS = /* @__PURE__ */ new Set([
16248
+ "wallet_addEthereumChain",
16249
+ "wallet_switchEthereumChain",
16250
+ "eth_accounts"
16251
+ ]);
16234
16252
  }
16235
16253
  });
16236
16254
 
@@ -16286,7 +16304,7 @@ var MetaMaskSDK = (() => {
16286
16304
  }
16287
16305
  /**
16288
16306
  * Merges the given options into the current instance options.
16289
- * Only the mergeable keys are updated (api.supportedNetworks, versions, ui.*, mobile.*, transport.extensionId, debug).
16307
+ * Only the mergeable keys are updated (api.supportedNetworks, analytics, versions, ui.*, mobile.*, transport.extensionId, debug).
16290
16308
  * The main thing to note is that the value for `dapp` is not merged as it does not make sense for
16291
16309
  * subsequent calls to `createMultichainClient` to have a different `dapp` value.
16292
16310
  * Used when createMultichainClient is called with an existing singleton.
@@ -16294,23 +16312,28 @@ var MetaMaskSDK = (() => {
16294
16312
  * @param partial - Options to merge/overwrite onto the current instance
16295
16313
  */
16296
16314
  mergeOptions(partial) {
16297
- var _a4, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o;
16315
+ var _a4, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q;
16298
16316
  const opts = this.options;
16317
+ const analytics2 = __spreadValues(__spreadValues({}, opts.analytics), (_a4 = partial.analytics) != null ? _a4 : {});
16318
+ if (((_b = opts.analytics) == null ? void 0 : _b.enabled) === false) {
16319
+ analytics2.enabled = false;
16320
+ }
16299
16321
  this.options = __spreadProps(__spreadValues({}, opts), {
16300
16322
  api: __spreadProps(__spreadValues({}, opts.api), {
16301
- supportedNetworks: __spreadValues(__spreadValues({}, opts.api.supportedNetworks), (_b = (_a4 = partial.api) == null ? void 0 : _a4.supportedNetworks) != null ? _b : {})
16323
+ supportedNetworks: __spreadValues(__spreadValues({}, opts.api.supportedNetworks), (_d = (_c = partial.api) == null ? void 0 : _c.supportedNetworks) != null ? _d : {})
16302
16324
  }),
16303
- versions: __spreadValues(__spreadValues({}, opts.versions), (_c = partial.versions) != null ? _c : {}),
16325
+ versions: __spreadValues(__spreadValues({}, opts.versions), (_e = partial.versions) != null ? _e : {}),
16326
+ analytics: __spreadValues({}, analytics2),
16304
16327
  ui: __spreadProps(__spreadValues({}, opts.ui), {
16305
- headless: (_e = (_d = partial.ui) == null ? void 0 : _d.headless) != null ? _e : opts.ui.headless,
16306
- preferExtension: (_g = (_f = partial.ui) == null ? void 0 : _f.preferExtension) != null ? _g : opts.ui.preferExtension,
16307
- showInstallModal: (_i = (_h = partial.ui) == null ? void 0 : _h.showInstallModal) != null ? _i : opts.ui.showInstallModal
16328
+ headless: (_g = (_f = partial.ui) == null ? void 0 : _f.headless) != null ? _g : opts.ui.headless,
16329
+ preferExtension: (_i = (_h = partial.ui) == null ? void 0 : _h.preferExtension) != null ? _i : opts.ui.preferExtension,
16330
+ showInstallModal: (_k = (_j = partial.ui) == null ? void 0 : _j.showInstallModal) != null ? _k : opts.ui.showInstallModal
16308
16331
  }),
16309
- mobile: __spreadValues(__spreadValues({}, opts.mobile), (_j = partial.mobile) != null ? _j : {}),
16310
- transport: __spreadProps(__spreadValues({}, (_k = opts.transport) != null ? _k : {}), {
16311
- extensionId: (_n = (_l = partial.transport) == null ? void 0 : _l.extensionId) != null ? _n : (_m = opts.transport) == null ? void 0 : _m.extensionId
16332
+ mobile: __spreadValues(__spreadValues({}, opts.mobile), (_l = partial.mobile) != null ? _l : {}),
16333
+ transport: __spreadProps(__spreadValues({}, (_m = opts.transport) != null ? _m : {}), {
16334
+ extensionId: (_p = (_n = partial.transport) == null ? void 0 : _n.extensionId) != null ? _p : (_o = opts.transport) == null ? void 0 : _o.extensionId
16312
16335
  }),
16313
- debug: (_o = partial.debug) != null ? _o : opts.debug
16336
+ debug: (_q = partial.debug) != null ? _q : opts.debug
16314
16337
  });
16315
16338
  }
16316
16339
  };
@@ -17011,7 +17034,7 @@ var MetaMaskSDK = (() => {
17011
17034
  return detectionPromise;
17012
17035
  });
17013
17036
  }
17014
- var import_bowser, PlatformType, detectionPromise;
17037
+ var import_bowser, PlatformType, NATIVE_METAMASK_EIP6963_RDNS, detectionPromise;
17015
17038
  var init_platform = __esm({
17016
17039
  "src/domain/platform/index.ts"() {
17017
17040
  "use strict";
@@ -17024,6 +17047,10 @@ var MetaMaskSDK = (() => {
17024
17047
  PlatformType2["ReactNative"] = "react-native";
17025
17048
  return PlatformType2;
17026
17049
  })(PlatformType || {});
17050
+ NATIVE_METAMASK_EIP6963_RDNS = /* @__PURE__ */ new Set([
17051
+ "io.metamask",
17052
+ "io.metamask.mobile"
17053
+ ]);
17027
17054
  detectionPromise = (() => __async(null, null, function* () {
17028
17055
  const pt = getPlatformType();
17029
17056
  if (pt === "nodejs" /* NonBrowser */ || pt === "react-native" /* ReactNative */) {
@@ -17031,23 +17058,30 @@ var MetaMaskSDK = (() => {
17031
17058
  }
17032
17059
  return new Promise((resolve) => {
17033
17060
  const providers = [];
17061
+ const targetWindow = window;
17034
17062
  const handler = (event) => {
17035
17063
  var _a4, _b;
17036
17064
  if ((_b = (_a4 = event == null ? void 0 : event.detail) == null ? void 0 : _a4.info) == null ? void 0 : _b.rdns) {
17037
17065
  providers.push(event.detail);
17038
17066
  }
17039
17067
  };
17040
- window.addEventListener("eip6963:announceProvider", handler);
17041
- window.dispatchEvent(new Event("eip6963:requestProvider"));
17068
+ targetWindow.addEventListener("eip6963:announceProvider", handler);
17069
+ targetWindow.dispatchEvent(new Event("eip6963:requestProvider"));
17042
17070
  setTimeout(() => {
17043
- window.removeEventListener("eip6963:announceProvider", handler);
17044
- const hasMetaMask = providers.some(
17045
- (provider) => {
17046
- var _a4, _b;
17047
- return (_b = (_a4 = provider == null ? void 0 : provider.info) == null ? void 0 : _a4.rdns) == null ? void 0 : _b.startsWith("io.metamask");
17071
+ try {
17072
+ if (typeof (targetWindow == null ? void 0 : targetWindow.removeEventListener) === "function") {
17073
+ targetWindow.removeEventListener("eip6963:announceProvider", handler);
17048
17074
  }
17049
- );
17050
- resolve(hasMetaMask);
17075
+ const hasMetaMask = providers.some(
17076
+ (provider) => {
17077
+ var _a4;
17078
+ return typeof ((_a4 = provider == null ? void 0 : provider.info) == null ? void 0 : _a4.rdns) === "string" && NATIVE_METAMASK_EIP6963_RDNS.has(provider.info.rdns);
17079
+ }
17080
+ );
17081
+ resolve(hasMetaMask);
17082
+ } catch (e) {
17083
+ resolve(false);
17084
+ }
17051
17085
  }, 300);
17052
17086
  });
17053
17087
  }))();
@@ -17292,12 +17326,14 @@ var MetaMaskSDK = (() => {
17292
17326
 
17293
17327
  // src/domain/utils/index.ts
17294
17328
  function getVersion() {
17295
- return "0.0.0";
17329
+ return packageVersion;
17296
17330
  }
17331
+ var packageVersion;
17297
17332
  var init_utils3 = __esm({
17298
17333
  "src/domain/utils/index.ts"() {
17299
17334
  "use strict";
17300
17335
  init_analytics();
17336
+ packageVersion = false ? "unknown" : "1.0.0";
17301
17337
  }
17302
17338
  });
17303
17339
 
@@ -25743,12 +25779,13 @@ var MetaMaskSDK = (() => {
25743
25779
  __export(mwp_exports, {
25744
25780
  MWPTransport: () => MWPTransport
25745
25781
  });
25746
- var DEFAULT_REQUEST_TIMEOUT3, CONNECTION_GRACE_PERIOD, DEFAULT_CONNECTION_TIMEOUT, DEFAULT_RESUME_TIMEOUT, SESSION_STORE_KEY, ACCOUNTS_STORE_KEY, CHAIN_STORE_KEY, PENDING_SESSION_REQUEST_KEY, CACHED_METHOD_LIST, CACHED_RESET_METHOD_LIST, logger, MWPTransport;
25782
+ var DEFAULT_REQUEST_TIMEOUT3, CONNECTION_GRACE_PERIOD, DEFAULT_CONNECTION_TIMEOUT, DEFAULT_RESUME_TIMEOUT, SESSION_STORE_KEY, ACCOUNTS_STORE_KEY, CHAIN_STORE_KEY, PENDING_SESSION_REQUEST_KEY, CACHED_METHOD_LIST, CACHED_RESET_METHOD_LIST, logger, _MWPTransport_instances, onResumeHandler_fn, resumeSession_fn, startSession_fn, MWPTransport;
25747
25783
  var init_mwp = __esm({
25748
25784
  "src/multichain/transports/mwp/index.ts"() {
25749
25785
  "use strict";
25750
25786
  init_dist3();
25751
25787
  init_dist4();
25788
+ init_dist2();
25752
25789
  init_domain();
25753
25790
  init_utils4();
25754
25791
  init_constants3();
@@ -25779,6 +25816,7 @@ var MetaMaskSDK = (() => {
25779
25816
  this.dappClient = dappClient;
25780
25817
  this.kvstore = kvstore;
25781
25818
  this.options = options;
25819
+ __privateAdd(this, _MWPTransport_instances);
25782
25820
  this.__pendingRequests = /* @__PURE__ */ new Map();
25783
25821
  this.notificationCallbacks = /* @__PURE__ */ new Set();
25784
25822
  this.dappClient.on("message", this.handleMessage.bind(this));
@@ -25858,6 +25896,23 @@ var MetaMaskSDK = (() => {
25858
25896
  const message = errorPayload instanceof Error ? errorPayload.message : JSON.stringify(errorPayload);
25859
25897
  return rpcErrors.internal({ message });
25860
25898
  }
25899
+ getResponseError(messagePayload) {
25900
+ if ("error" in messagePayload && messagePayload.error) {
25901
+ return messagePayload.error;
25902
+ }
25903
+ const { result } = messagePayload;
25904
+ if (typeof result === "object" && result !== null && "error" in result && result.error && this.isErrorPayload(result.error)) {
25905
+ return result.error;
25906
+ }
25907
+ return void 0;
25908
+ }
25909
+ isErrorPayload(errorPayload) {
25910
+ if (errorPayload instanceof Error) {
25911
+ return true;
25912
+ }
25913
+ const errorData = errorPayload;
25914
+ return typeof (errorData == null ? void 0 : errorData.code) === "number" && typeof (errorData == null ? void 0 : errorData.message) === "string";
25915
+ }
25861
25916
  handleMessage(message) {
25862
25917
  if (typeof message === "object" && message !== null) {
25863
25918
  if ("data" in message) {
@@ -25866,9 +25921,10 @@ var MetaMaskSDK = (() => {
25866
25921
  const request2 = this.pendingRequests.get(messagePayload.id);
25867
25922
  if (request2) {
25868
25923
  clearTimeout(request2.timeout);
25869
- if ("error" in messagePayload && messagePayload.error) {
25924
+ const responseError = this.getResponseError(messagePayload);
25925
+ if (responseError) {
25870
25926
  this.pendingRequests.delete(messagePayload.id);
25871
- request2.reject(this.parseWalletError(messagePayload.error));
25927
+ request2.reject(this.parseWalletError(responseError));
25872
25928
  return;
25873
25929
  }
25874
25930
  const requestWithName = __spreadProps(__spreadValues({}, messagePayload), {
@@ -25911,73 +25967,6 @@ var MetaMaskSDK = (() => {
25911
25967
  }
25912
25968
  }
25913
25969
  }
25914
- onResumeSuccess(resumeResolve, resumeReject, options) {
25915
- return __async(this, null, function* () {
25916
- var _a4, _b, _c, _d, _e, _f, _g;
25917
- try {
25918
- yield this.waitForWalletSessionIfNotCached();
25919
- const sessionRequest = yield this.request({
25920
- method: "wallet_getSession"
25921
- });
25922
- if (sessionRequest.error) {
25923
- return resumeReject(new Error(sessionRequest.error.message));
25924
- }
25925
- let walletSession = sessionRequest.result;
25926
- if (walletSession && options) {
25927
- const currentScopes = Object.keys(
25928
- (_a4 = walletSession == null ? void 0 : walletSession.sessionScopes) != null ? _a4 : {}
25929
- );
25930
- const proposedScopes = (_b = options == null ? void 0 : options.scopes) != null ? _b : [];
25931
- const proposedCaipAccountIds = (_c = options == null ? void 0 : options.caipAccountIds) != null ? _c : [];
25932
- const hasSameScopesAndAccounts = isSameScopesAndAccounts(
25933
- currentScopes,
25934
- proposedScopes,
25935
- walletSession,
25936
- proposedCaipAccountIds
25937
- );
25938
- if (options.forceRequest || !hasSameScopesAndAccounts) {
25939
- const optionalScopes = addValidAccounts(
25940
- getOptionalScopes((_d = options == null ? void 0 : options.scopes) != null ? _d : []),
25941
- getValidAccounts((_e = options == null ? void 0 : options.caipAccountIds) != null ? _e : [])
25942
- );
25943
- const sessionRequest2 = {
25944
- optionalScopes
25945
- };
25946
- const response = yield this.request({
25947
- method: "wallet_createSession",
25948
- params: sessionRequest2
25949
- });
25950
- if (response.error) {
25951
- return resumeReject(new Error(response.error.message));
25952
- }
25953
- walletSession = response.result;
25954
- }
25955
- } else if (!walletSession) {
25956
- const optionalScopes = addValidAccounts(
25957
- getOptionalScopes((_f = options == null ? void 0 : options.scopes) != null ? _f : []),
25958
- getValidAccounts((_g = options == null ? void 0 : options.caipAccountIds) != null ? _g : [])
25959
- );
25960
- const sessionRequest2 = { optionalScopes };
25961
- const response = yield this.request({
25962
- method: "wallet_createSession",
25963
- params: sessionRequest2
25964
- });
25965
- if (response.error) {
25966
- return resumeReject(new Error(response.error.message));
25967
- }
25968
- walletSession = response.result;
25969
- }
25970
- yield this.removeStoredPendingSessionRequest();
25971
- this.notifyCallbacks({
25972
- method: "wallet_sessionChanged",
25973
- params: walletSession
25974
- });
25975
- return resumeResolve();
25976
- } catch (err3) {
25977
- return resumeReject(err3);
25978
- }
25979
- });
25980
- }
25981
25970
  init() {
25982
25971
  return __async(this, null, function* () {
25983
25972
  });
@@ -26018,7 +26007,6 @@ var MetaMaskSDK = (() => {
26018
26007
  }
26019
26008
  connect(options) {
26020
26009
  return __async(this, null, function* () {
26021
- const { dappClient } = this;
26022
26010
  const session = yield this.getActiveSession();
26023
26011
  if (session) {
26024
26012
  logger("active session found", {
@@ -26027,116 +26015,11 @@ var MetaMaskSDK = (() => {
26027
26015
  expiresAt: session.expiresAt
26028
26016
  });
26029
26017
  }
26030
- const storedSessionRequestBeforeConnectionAttempt = yield this.getStoredPendingSessionRequest();
26031
- let timeout;
26032
- let initialConnectionMessageHandler;
26033
- const connectionPromise = new Promise((resolve, reject) => __async(this, null, function* () {
26034
- let connection;
26035
- if (session) {
26036
- connection = new Promise((resumeResolve, resumeReject) => {
26037
- var _a4;
26038
- if (this.dappClient.state === "CONNECTED") {
26039
- this.onResumeSuccess(resumeResolve, resumeReject, options);
26040
- } else {
26041
- this.dappClient.once("connected", () => __async(this, null, function* () {
26042
- this.onResumeSuccess(resumeResolve, resumeReject, options);
26043
- }));
26044
- dappClient.resume((_a4 = session == null ? void 0 : session.id) != null ? _a4 : "");
26045
- }
26046
- });
26047
- } else {
26048
- connection = new Promise(
26049
- (resolveConnection, rejectConnection) => {
26050
- var _a4, _b;
26051
- const optionalScopes = addValidAccounts(
26052
- getOptionalScopes((_a4 = options == null ? void 0 : options.scopes) != null ? _a4 : []),
26053
- getValidAccounts((_b = options == null ? void 0 : options.caipAccountIds) != null ? _b : [])
26054
- );
26055
- const sessionRequest = {
26056
- optionalScopes,
26057
- sessionProperties: options == null ? void 0 : options.sessionProperties
26058
- };
26059
- const request2 = {
26060
- jsonrpc: "2.0",
26061
- id: String(getUniqueRequestId()),
26062
- method: "wallet_createSession",
26063
- params: sessionRequest
26064
- };
26065
- initialConnectionMessageHandler = (message) => __async(this, null, function* () {
26066
- if (typeof message !== "object" || message === null) {
26067
- return;
26068
- }
26069
- if (!("data" in message)) {
26070
- return;
26071
- }
26072
- const messagePayload = message.data;
26073
- const isMatchingId = messagePayload.id === request2.id;
26074
- const isMatchingMethod = messagePayload.method === "wallet_createSession" || messagePayload.method === "wallet_sessionChanged";
26075
- if (!isMatchingId && !isMatchingMethod) {
26076
- return;
26077
- }
26078
- if (messagePayload.error) {
26079
- return rejectConnection(
26080
- this.parseWalletError(messagePayload.error)
26081
- );
26082
- }
26083
- yield this.storeWalletSession(
26084
- request2,
26085
- messagePayload
26086
- );
26087
- yield this.removeStoredPendingSessionRequest();
26088
- this.notifyCallbacks(messagePayload);
26089
- return resolveConnection();
26090
- });
26091
- this.dappClient.on("message", initialConnectionMessageHandler);
26092
- const platformType = getPlatformType();
26093
- const isQRCodeFlow = [
26094
- "web-desktop" /* DesktopWeb */,
26095
- "nodejs" /* NonBrowser */
26096
- ].includes(platformType);
26097
- const initialPayload = {
26098
- name: MULTICHAIN_PROVIDER_STREAM_NAME,
26099
- data: request2
26100
- };
26101
- dappClient.connect({
26102
- mode: "trusted",
26103
- initialPayload: isQRCodeFlow ? void 0 : initialPayload
26104
- }).then(() => __async(this, null, function* () {
26105
- if (isQRCodeFlow) {
26106
- return dappClient.sendRequest(initialPayload);
26107
- }
26108
- return void 0;
26109
- })).catch((error) => {
26110
- if (initialConnectionMessageHandler) {
26111
- this.dappClient.off(
26112
- "message",
26113
- initialConnectionMessageHandler
26114
- );
26115
- }
26116
- rejectConnection(error);
26117
- });
26118
- }
26119
- );
26120
- }
26121
- timeout = setTimeout(
26122
- () => {
26123
- reject(new TransportTimeoutError());
26124
- },
26125
- storedSessionRequestBeforeConnectionAttempt ? this.options.resumeTimeout : this.options.connectionTimeout
26126
- );
26127
- connection.then(resolve).catch(reject);
26128
- }));
26129
- return connectionPromise.catch((error) => __async(this, null, function* () {
26018
+ const connection = session ? __privateMethod(this, _MWPTransport_instances, resumeSession_fn).call(this, session, options) : __privateMethod(this, _MWPTransport_instances, startSession_fn).call(this, options);
26019
+ return connection.catch((error) => __async(this, null, function* () {
26130
26020
  yield this.dappClient.disconnect();
26131
26021
  throw error;
26132
26022
  })).finally(() => {
26133
- if (timeout) {
26134
- clearTimeout(timeout);
26135
- }
26136
- if (initialConnectionMessageHandler) {
26137
- this.dappClient.off("message", initialConnectionMessageHandler);
26138
- initialConnectionMessageHandler = void 0;
26139
- }
26140
26023
  this.removeStoredPendingSessionRequest();
26141
26024
  });
26142
26025
  });
@@ -26395,6 +26278,188 @@ var MetaMaskSDK = (() => {
26395
26278
  });
26396
26279
  }
26397
26280
  };
26281
+ _MWPTransport_instances = new WeakSet();
26282
+ onResumeHandler_fn = function(options) {
26283
+ return __async(this, null, function* () {
26284
+ var _a4, _b, _c, _d, _e, _f, _g;
26285
+ yield this.waitForWalletSessionIfNotCached();
26286
+ const sessionResponse = yield this.request({ method: "wallet_getSession" });
26287
+ if (sessionResponse.error) {
26288
+ throw new Error(sessionResponse.error.message);
26289
+ }
26290
+ let walletSession = sessionResponse.result;
26291
+ if (walletSession && options) {
26292
+ const currentScopes = Object.keys(
26293
+ (_a4 = walletSession == null ? void 0 : walletSession.sessionScopes) != null ? _a4 : {}
26294
+ );
26295
+ const proposedScopes = (_b = options == null ? void 0 : options.scopes) != null ? _b : [];
26296
+ const proposedCaipAccountIds = (_c = options == null ? void 0 : options.caipAccountIds) != null ? _c : [];
26297
+ const hasSameScopesAndAccounts = isSameScopesAndAccounts(
26298
+ currentScopes,
26299
+ proposedScopes,
26300
+ walletSession,
26301
+ proposedCaipAccountIds
26302
+ );
26303
+ if (options.forceRequest || !hasSameScopesAndAccounts) {
26304
+ const optionalScopes = addValidAccounts(
26305
+ getOptionalScopes((_d = options == null ? void 0 : options.scopes) != null ? _d : []),
26306
+ getValidAccounts((_e = options == null ? void 0 : options.caipAccountIds) != null ? _e : [])
26307
+ );
26308
+ const sessionRequest = {
26309
+ optionalScopes
26310
+ };
26311
+ const response = yield this.request({
26312
+ method: "wallet_createSession",
26313
+ params: sessionRequest
26314
+ });
26315
+ if (response.error) {
26316
+ throw new Error(response.error.message);
26317
+ }
26318
+ walletSession = response.result;
26319
+ }
26320
+ } else if (!walletSession) {
26321
+ const optionalScopes = addValidAccounts(
26322
+ getOptionalScopes((_f = options == null ? void 0 : options.scopes) != null ? _f : []),
26323
+ getValidAccounts((_g = options == null ? void 0 : options.caipAccountIds) != null ? _g : [])
26324
+ );
26325
+ const sessionRequest = {
26326
+ optionalScopes
26327
+ };
26328
+ const response = yield this.request({
26329
+ method: "wallet_createSession",
26330
+ params: sessionRequest
26331
+ });
26332
+ if (response.error) {
26333
+ throw new Error(response.error.message);
26334
+ }
26335
+ walletSession = response.result;
26336
+ }
26337
+ yield this.removeStoredPendingSessionRequest();
26338
+ this.notifyCallbacks({
26339
+ method: "wallet_sessionChanged",
26340
+ params: walletSession
26341
+ });
26342
+ });
26343
+ };
26344
+ resumeSession_fn = function(session, options) {
26345
+ return __async(this, null, function* () {
26346
+ var _a4;
26347
+ const isContinuingPriorAttempt = (yield this.getStoredPendingSessionRequest()) !== null;
26348
+ const resumeDeferred = createDeferredPromise();
26349
+ const runOnResumeHandler = () => __async(this, null, function* () {
26350
+ try {
26351
+ resumeDeferred.resolve(yield __privateMethod(this, _MWPTransport_instances, onResumeHandler_fn).call(this, options));
26352
+ } catch (err3) {
26353
+ resumeDeferred.reject(err3);
26354
+ }
26355
+ });
26356
+ if (this.dappClient.state === "CONNECTED") {
26357
+ runOnResumeHandler();
26358
+ } else {
26359
+ this.dappClient.once("connected", runOnResumeHandler);
26360
+ this.dappClient.resume((_a4 = session.id) != null ? _a4 : "").catch((err3) => resumeDeferred.reject(err3));
26361
+ }
26362
+ const timeoutDeferred = createDeferredPromise();
26363
+ const timeout = setTimeout(
26364
+ () => timeoutDeferred.reject(new TransportTimeoutError()),
26365
+ isContinuingPriorAttempt ? this.options.resumeTimeout : this.options.connectionTimeout
26366
+ );
26367
+ const cleanup = () => this.dappClient.off("connected", runOnResumeHandler);
26368
+ return Promise.race([
26369
+ resumeDeferred.promise,
26370
+ timeoutDeferred.promise
26371
+ ]).finally(() => {
26372
+ clearTimeout(timeout);
26373
+ cleanup();
26374
+ });
26375
+ });
26376
+ };
26377
+ startSession_fn = function(options) {
26378
+ return __async(this, null, function* () {
26379
+ var _a4, _b;
26380
+ const { dappClient } = this;
26381
+ const isContinuingPriorAttempt = (yield this.getStoredPendingSessionRequest()) !== null;
26382
+ const connDeferred = createDeferredPromise();
26383
+ const optionalScopes = addValidAccounts(
26384
+ getOptionalScopes((_a4 = options == null ? void 0 : options.scopes) != null ? _a4 : []),
26385
+ getValidAccounts((_b = options == null ? void 0 : options.caipAccountIds) != null ? _b : [])
26386
+ );
26387
+ const sessionRequest = {
26388
+ optionalScopes,
26389
+ sessionProperties: options == null ? void 0 : options.sessionProperties
26390
+ };
26391
+ const request2 = {
26392
+ jsonrpc: "2.0",
26393
+ id: String(getUniqueRequestId()),
26394
+ method: "wallet_createSession",
26395
+ params: sessionRequest
26396
+ };
26397
+ let handler;
26398
+ const removeHandler = () => {
26399
+ if (handler) {
26400
+ this.dappClient.off("message", handler);
26401
+ handler = void 0;
26402
+ }
26403
+ };
26404
+ handler = (message) => __async(this, null, function* () {
26405
+ if (typeof message !== "object" || message === null) {
26406
+ return;
26407
+ }
26408
+ if (!("data" in message)) {
26409
+ return;
26410
+ }
26411
+ const messagePayload = message.data;
26412
+ const isMatchingId = messagePayload.id === request2.id;
26413
+ const isMatchingMethod = messagePayload.method === "wallet_createSession" || messagePayload.method === "wallet_sessionChanged";
26414
+ if (!isMatchingId && !isMatchingMethod) {
26415
+ return;
26416
+ }
26417
+ const responseError = this.getResponseError(messagePayload);
26418
+ if (responseError) {
26419
+ connDeferred.reject(this.parseWalletError(responseError));
26420
+ return;
26421
+ }
26422
+ yield this.storeWalletSession(
26423
+ request2,
26424
+ messagePayload
26425
+ );
26426
+ yield this.removeStoredPendingSessionRequest();
26427
+ this.notifyCallbacks(messagePayload);
26428
+ connDeferred.resolve();
26429
+ });
26430
+ this.dappClient.on("message", handler);
26431
+ const platformType = getPlatformType();
26432
+ const isQRCodeFlow = [
26433
+ "web-desktop" /* DesktopWeb */,
26434
+ "nodejs" /* NonBrowser */
26435
+ ].includes(platformType);
26436
+ const initialPayload = {
26437
+ name: MULTICHAIN_PROVIDER_STREAM_NAME,
26438
+ data: request2
26439
+ };
26440
+ dappClient.connect({
26441
+ mode: "trusted",
26442
+ initialPayload: isQRCodeFlow ? void 0 : initialPayload
26443
+ }).then(() => __async(this, null, function* () {
26444
+ if (isQRCodeFlow) {
26445
+ return dappClient.sendRequest(initialPayload);
26446
+ }
26447
+ return void 0;
26448
+ })).catch((error) => connDeferred.reject(error));
26449
+ const timeoutDeferred = createDeferredPromise();
26450
+ const timeout = setTimeout(
26451
+ () => timeoutDeferred.reject(new TransportTimeoutError()),
26452
+ isContinuingPriorAttempt ? this.options.resumeTimeout : this.options.connectionTimeout
26453
+ );
26454
+ return Promise.race([
26455
+ connDeferred.promise,
26456
+ timeoutDeferred.promise
26457
+ ]).finally(() => {
26458
+ clearTimeout(timeout);
26459
+ removeHandler();
26460
+ });
26461
+ });
26462
+ };
26398
26463
  }
26399
26464
  });
26400
26465
 
@@ -37695,9 +37760,7 @@ ${new this._window.XMLSerializer().serializeToString(e3)}`;
37695
37760
  mount() {
37696
37761
  var _a4;
37697
37762
  const { options } = this;
37698
- const modal = document.createElement(
37699
- "mm-install-modal"
37700
- );
37763
+ const modal = document.createElement("mm-install-modal");
37701
37764
  modal.showInstallModal = options.showInstallModal;
37702
37765
  modal.addEventListener("close", (ev) => {
37703
37766
  const { detail } = ev;
@@ -37881,6 +37944,7 @@ ${new this._window.XMLSerializer().serializeToString(e3)}`;
37881
37944
  // src/index.browser.ts
37882
37945
  var index_browser_exports = {};
37883
37946
  __export(index_browser_exports, {
37947
+ EIP1193_PASSTHROUGH_METHODS: () => EIP1193_PASSTHROUGH_METHODS,
37884
37948
  EventEmitter: () => EventEmitter2,
37885
37949
  Modal: () => Modal,
37886
37950
  MultichainCore: () => MultichainCore,
@@ -37908,7 +37972,8 @@ ${new this._window.XMLSerializer().serializeToString(e3)}`;
37908
37972
  isEnabled: () => isEnabled,
37909
37973
  isMetamaskExtensionInstalled: () => isMetamaskExtensionInstalled,
37910
37974
  isRejectionError: () => isRejectionError,
37911
- isSecure: () => isSecure
37975
+ isSecure: () => isSecure,
37976
+ packageVersion: () => packageVersion
37912
37977
  });
37913
37978
 
37914
37979
  // src/polyfills/buffer-shim.ts
@@ -38422,6 +38487,17 @@ ${new this._window.XMLSerializer().serializeToString(e3)}`;
38422
38487
  this.batch.push(item);
38423
38488
  this.schedule();
38424
38489
  }
38490
+ /**
38491
+ * Clears queued items and cancels the scheduled flush.
38492
+ */
38493
+ clear() {
38494
+ this.batch = [];
38495
+ this.currentTimeoutMs = this.baseTimeoutMs;
38496
+ if (this.timeoutId) {
38497
+ clearTimeout(this.timeoutId);
38498
+ this.timeoutId = null;
38499
+ }
38500
+ }
38425
38501
  schedule() {
38426
38502
  if (this.batch.length > 0 && !this.timeoutId) {
38427
38503
  this.timeoutId = setTimeout(() => {
@@ -38473,6 +38549,13 @@ ${new this._window.XMLSerializer().serializeToString(e3)}`;
38473
38549
  enable() {
38474
38550
  this.enabled = true;
38475
38551
  }
38552
+ /**
38553
+ * Disables analytics and drops queued events.
38554
+ */
38555
+ disable() {
38556
+ this.enabled = false;
38557
+ this.sender.clear();
38558
+ }
38476
38559
  setGlobalProperty(key, value) {
38477
38560
  if (key === "integration_types") {
38478
38561
  const existing = Array.isArray(this.properties.integration_types) ? this.properties.integration_types : [];
@@ -38508,6 +38591,7 @@ ${new this._window.XMLSerializer().serializeToString(e3)}`;
38508
38591
 
38509
38592
  // src/multichain/index.ts
38510
38593
  init_dist3();
38594
+ init_dist2();
38511
38595
 
38512
38596
  // src/config/index.ts
38513
38597
  var MWP_RELAY_URL = "wss://mm-sdk-relay.api.cx.metamask.io/connection/websocket";
@@ -38630,6 +38714,17 @@ ${new this._window.XMLSerializer().serializeToString(e3)}`;
38630
38714
  init_domain();
38631
38715
  init_utils4();
38632
38716
  init_analytics();
38717
+ function toRPCInvokeMethodErr(error) {
38718
+ var _a4;
38719
+ if (error instanceof RPCInvokeMethodErr) {
38720
+ return error;
38721
+ }
38722
+ const castError = error;
38723
+ return new RPCInvokeMethodErr(
38724
+ (_a4 = castError.message) != null ? _a4 : "Unknown error",
38725
+ castError.code
38726
+ );
38727
+ }
38633
38728
  var _RequestRouter_instances, withAnalyticsTracking_fn, trackWalletActionRequested_fn, trackWalletActionSucceeded_fn, trackWalletActionFailed_fn, trackWalletActionRejected_fn;
38634
38729
  var RequestRouter = class {
38635
38730
  constructor(transport, rpcClient, config, transportType) {
@@ -38649,6 +38744,9 @@ ${new this._window.XMLSerializer().serializeToString(e3)}`;
38649
38744
  invokeMethod(options) {
38650
38745
  return __async(this, null, function* () {
38651
38746
  const { method } = options.request;
38747
+ if (EIP1193_PASSTHROUGH_METHODS.has(method)) {
38748
+ return this.handleWithEip1193Passthrough(options);
38749
+ }
38652
38750
  if (RPC_HANDLED_METHODS.has(method)) {
38653
38751
  return this.handleWithRpcNode(options);
38654
38752
  }
@@ -38658,6 +38756,29 @@ ${new this._window.XMLSerializer().serializeToString(e3)}`;
38658
38756
  return this.handleWithWallet(options);
38659
38757
  });
38660
38758
  }
38759
+ /**
38760
+ * Forwards EIP-1193 / legacy provider methods (e.g. `wallet_addEthereumChain`,
38761
+ * `wallet_switchEthereumChain`, `eth_accounts`) directly to the underlying
38762
+ * transport's `sendEip1193Message`, bypassing the multichain
38763
+ * `wallet_invokeMethod` envelope. These methods are wallet-side concerns the
38764
+ * Multichain API does not model, so we forward the raw `{ method, params }`
38765
+ * payload and return the wallet's full JSON-RPC response envelope unchanged.
38766
+ *
38767
+ * Analytics tracking is intentionally skipped here: ecosystem clients
38768
+ * (e.g. `connect-evm`) emit their own `wallet_action_*` events around these
38769
+ * passthrough calls, and adding router-level tracking would double-count.
38770
+ *
38771
+ * @param options
38772
+ */
38773
+ handleWithEip1193Passthrough(options) {
38774
+ return __async(this, null, function* () {
38775
+ const response = yield this.transport.sendEip1193Message({
38776
+ method: options.request.method,
38777
+ params: options.request.params
38778
+ });
38779
+ return response.result;
38780
+ });
38781
+ }
38661
38782
  /**
38662
38783
  * Forwards the request directly to the wallet via the transport.
38663
38784
  *
@@ -38689,14 +38810,6 @@ ${new this._window.XMLSerializer().serializeToString(e3)}`;
38689
38810
  }), 10);
38690
38811
  }
38691
38812
  const response = yield request2;
38692
- if (response.error) {
38693
- const { error } = response;
38694
- throw new RPCInvokeMethodErr(
38695
- `RPC Request failed with code ${error.code}: ${error.message}`,
38696
- error.code,
38697
- error.message
38698
- );
38699
- }
38700
38813
  return response.result;
38701
38814
  }));
38702
38815
  });
@@ -38736,6 +38849,13 @@ ${new this._window.XMLSerializer().serializeToString(e3)}`;
38736
38849
  withAnalyticsTracking_fn = function(options, execute) {
38737
38850
  return __async(this, null, function* () {
38738
38851
  var _a4;
38852
+ if (((_a4 = this.config.analytics) == null ? void 0 : _a4.enabled) === false) {
38853
+ try {
38854
+ return yield execute();
38855
+ } catch (error) {
38856
+ throw toRPCInvokeMethodErr(error);
38857
+ }
38858
+ }
38739
38859
  yield __privateMethod(this, _RequestRouter_instances, trackWalletActionRequested_fn).call(this, options);
38740
38860
  try {
38741
38861
  const result = yield execute();
@@ -38748,14 +38868,7 @@ ${new this._window.XMLSerializer().serializeToString(e3)}`;
38748
38868
  } else {
38749
38869
  yield __privateMethod(this, _RequestRouter_instances, trackWalletActionFailed_fn).call(this, options, error);
38750
38870
  }
38751
- if (error instanceof RPCInvokeMethodErr) {
38752
- throw error;
38753
- }
38754
- const castError = error;
38755
- throw new RPCInvokeMethodErr(
38756
- (_a4 = castError.message) != null ? _a4 : "Unknown error",
38757
- castError.code
38758
- );
38871
+ throw toRPCInvokeMethodErr(error);
38759
38872
  }
38760
38873
  });
38761
38874
  };
@@ -38809,7 +38922,7 @@ ${new this._window.XMLSerializer().serializeToString(e3)}`;
38809
38922
  init_dist3();
38810
38923
  init_utils4();
38811
38924
  var DEFAULT_REQUEST_TIMEOUT2 = 60 * 1e3;
38812
- var _notificationCallbacks, _transport, _defaultRequestOptions, _pendingRequests, _handleResponseListener, _handleNotificationListener, _DefaultTransport_instances, notifyCallbacks_fn, isMetamaskProviderEvent_fn, handleResponse_fn, handleNotification_fn, setupMessageListener_fn, init_fn;
38925
+ var _notificationCallbacks, _transport, _defaultRequestOptions, _pendingRequests, _handleResponseListener, _handleNotificationListener, _DefaultTransport_instances, notifyCallbacks_fn, parseWalletError_fn, isMetamaskProviderEvent_fn, handleResponse_fn, handleNotification_fn, setupMessageListener_fn, init_fn;
38813
38926
  var DefaultTransport = class {
38814
38927
  constructor() {
38815
38928
  __privateAdd(this, _DefaultTransport_instances);
@@ -38945,7 +39058,11 @@ ${new this._window.XMLSerializer().serializeToString(e3)}`;
38945
39058
  }
38946
39059
  request(_0) {
38947
39060
  return __async(this, arguments, function* (request2, options = __privateGet(this, _defaultRequestOptions)) {
38948
- return __privateGet(this, _transport).request(request2, options);
39061
+ const response = yield __privateGet(this, _transport).request(request2, options);
39062
+ if (response.error) {
39063
+ throw __privateMethod(this, _DefaultTransport_instances, parseWalletError_fn).call(this, response.error);
39064
+ }
39065
+ return response;
38949
39066
  });
38950
39067
  }
38951
39068
  onNotification(callback) {
@@ -38989,6 +39106,16 @@ ${new this._window.XMLSerializer().serializeToString(e3)}`;
38989
39106
  }
38990
39107
  }
38991
39108
  };
39109
+ parseWalletError_fn = function(errorPayload) {
39110
+ const errorData = errorPayload;
39111
+ const error = new Error(
39112
+ typeof errorData.message === "string" ? errorData.message : "Request failed"
39113
+ );
39114
+ if (typeof errorData.code === "number") {
39115
+ error.code = errorData.code;
39116
+ }
39117
+ return error;
39118
+ };
38992
39119
  isMetamaskProviderEvent_fn = function(event) {
38993
39120
  var _a4, _b;
38994
39121
  return ((_b = (_a4 = event == null ? void 0 : event.data) == null ? void 0 : _a4.data) == null ? void 0 : _b.name) === "metamask-provider" && // eslint-disable-next-line no-restricted-globals
@@ -39011,13 +39138,7 @@ ${new this._window.XMLSerializer().serializeToString(e3)}`;
39011
39138
  __privateGet(this, _pendingRequests).delete(responseId);
39012
39139
  const response = responseData;
39013
39140
  if ("error" in response && response.error) {
39014
- const error = new Error(
39015
- response.error.message || "Request failed"
39016
- );
39017
- if (typeof response.error.code === "number") {
39018
- error.code = response.error.code;
39019
- }
39020
- pendingRequest.reject(error);
39141
+ pendingRequest.reject(__privateMethod(this, _DefaultTransport_instances, parseWalletError_fn).call(this, response.error));
39021
39142
  } else {
39022
39143
  pendingRequest.resolve(response);
39023
39144
  }
@@ -39055,22 +39176,21 @@ ${new this._window.XMLSerializer().serializeToString(e3)}`;
39055
39176
  // src/multichain/transports/multichainApiClientWrapper/index.ts
39056
39177
  init_dist4();
39057
39178
  init_utils4();
39058
- var _notificationCallbacks2, _MultichainApiClientWrapperTransport_instances, walletCreateSession_fn, walletGetSession_fn, walletRevokeSession_fn, walletInvokeMethod_fn;
39179
+ var _notificationCallbacks2, _getTransport, _MultichainApiClientWrapperTransport_instances, walletCreateSession_fn, walletGetSession_fn, walletRevokeSession_fn, walletInvokeMethod_fn;
39059
39180
  var MultichainApiClientWrapperTransport = class {
39060
- constructor(metamaskConnectMultichain) {
39181
+ constructor(metamaskConnectMultichain, getTransport) {
39061
39182
  this.metamaskConnectMultichain = metamaskConnectMultichain;
39062
39183
  __privateAdd(this, _MultichainApiClientWrapperTransport_instances);
39063
39184
  __privateAdd(this, _notificationCallbacks2, /* @__PURE__ */ new Set());
39185
+ __privateAdd(this, _getTransport);
39186
+ __privateSet(this, _getTransport, getTransport);
39064
39187
  }
39065
39188
  isTransportDefined() {
39066
- try {
39067
- return Boolean(this.metamaskConnectMultichain.transport);
39068
- } catch (_error) {
39069
- return false;
39070
- }
39189
+ return __privateGet(this, _getTransport).call(this) !== void 0;
39071
39190
  }
39072
39191
  isTransportConnected() {
39073
- return this.isTransportDefined() && this.metamaskConnectMultichain.transport.isConnected();
39192
+ var _a4, _b;
39193
+ return (_b = (_a4 = __privateGet(this, _getTransport).call(this)) == null ? void 0 : _a4.isConnected()) != null ? _b : false;
39074
39194
  }
39075
39195
  clearNotificationCallbacks() {
39076
39196
  __privateGet(this, _notificationCallbacks2).clear();
@@ -39086,10 +39206,11 @@ ${new this._window.XMLSerializer().serializeToString(e3)}`;
39086
39206
  this.notificationListener = void 0;
39087
39207
  }
39088
39208
  setupTransportNotificationListener() {
39089
- if (!this.isTransportDefined() || this.notificationListener) {
39209
+ const transport = __privateGet(this, _getTransport).call(this);
39210
+ if (!transport || this.notificationListener) {
39090
39211
  return;
39091
39212
  }
39092
- this.notificationListener = this.metamaskConnectMultichain.transport.onNotification(
39213
+ this.notificationListener = transport.onNotification(
39093
39214
  this.notifyCallbacks.bind(this)
39094
39215
  );
39095
39216
  }
@@ -39139,6 +39260,7 @@ ${new this._window.XMLSerializer().serializeToString(e3)}`;
39139
39260
  }
39140
39261
  };
39141
39262
  _notificationCallbacks2 = new WeakMap();
39263
+ _getTransport = new WeakMap();
39142
39264
  _MultichainApiClientWrapperTransport_instances = new WeakSet();
39143
39265
  walletCreateSession_fn = function(request2) {
39144
39266
  return __async(this, null, function* () {
@@ -39162,14 +39284,19 @@ ${new this._window.XMLSerializer().serializeToString(e3)}`;
39162
39284
  accounts,
39163
39285
  createSessionParams.sessionProperties
39164
39286
  );
39165
- return this.metamaskConnectMultichain.transport.request({
39287
+ const transport = __privateGet(this, _getTransport).call(this);
39288
+ if (!transport) {
39289
+ throw new Error("Transport not initialized after connect");
39290
+ }
39291
+ return transport.request({
39166
39292
  method: "wallet_getSession"
39167
39293
  });
39168
39294
  });
39169
39295
  };
39170
39296
  walletGetSession_fn = function(request2) {
39171
39297
  return __async(this, null, function* () {
39172
- if (!this.isTransportConnected()) {
39298
+ const transport = __privateGet(this, _getTransport).call(this);
39299
+ if (!(transport == null ? void 0 : transport.isConnected())) {
39173
39300
  return {
39174
39301
  jsonrpc: "2.0",
39175
39302
  id: request2.id,
@@ -39178,7 +39305,7 @@ ${new this._window.XMLSerializer().serializeToString(e3)}`;
39178
39305
  }
39179
39306
  };
39180
39307
  }
39181
- return this.metamaskConnectMultichain.transport.request({
39308
+ return transport.request({
39182
39309
  method: "wallet_getSession"
39183
39310
  });
39184
39311
  });
@@ -39214,26 +39341,63 @@ ${new this._window.XMLSerializer().serializeToString(e3)}`;
39214
39341
  init_utils4();
39215
39342
  var logger2 = createLogger("metamask-sdk:core");
39216
39343
  var SINGLETON_KEY = "__METAMASK_CONNECT_MULTICHAIN_SINGLETON__";
39217
- var _a3, _provider, _providerTransportWrapper, _transport2, _dappClient, _beforeUnloadListener, _transportType, _listener, _anonId, _sdkInfo, _MetaMaskConnectMultichain_instances, setupAnalytics_fn, onTransportNotification_fn, getStoredTransport_fn, setupTransport_fn, buildConnectionMetadata_fn, init_fn2, createDappClient_fn, setupMWP_fn, onBeforeUnload_fn, createBeforeUnloadListener_fn, renderInstallModalAsync_fn, showInstallModal_fn, headlessConnect_fn, setupDefaultTransport_fn, deeplinkConnect_fn, handleConnection_fn, getCaipSession_fn, openConnectDeeplinkIfNeeded_fn;
39344
+ function normalizeAnalyticsOptions(analyticsOptions) {
39345
+ var _a4;
39346
+ return __spreadProps(__spreadValues({}, analyticsOptions != null ? analyticsOptions : {}), {
39347
+ enabled: (_a4 = analyticsOptions == null ? void 0 : analyticsOptions.enabled) != null ? _a4 : true,
39348
+ // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
39349
+ integrationType: (analyticsOptions == null ? void 0 : analyticsOptions.integrationType) || "direct"
39350
+ });
39351
+ }
39352
+ function isAnalyticsEnabled(options) {
39353
+ var _a4;
39354
+ return ((_a4 = options.analytics) == null ? void 0 : _a4.enabled) !== false;
39355
+ }
39356
+ function setupAnalyticsGlobals(options, storage, setAnonId) {
39357
+ return __async(this, null, function* () {
39358
+ var _a4, _b;
39359
+ if (!isAnalyticsEnabled(options)) {
39360
+ setAnonId == null ? void 0 : setAnonId(void 0);
39361
+ analytics.disable();
39362
+ return;
39363
+ }
39364
+ const platform = getPlatformType();
39365
+ const isBrowser = platform === "in-app-browser" /* MetaMaskMobileWebview */ || platform === "web-desktop" /* DesktopWeb */ || platform === "web-mobile" /* MobileWeb */;
39366
+ const isReactNative2 = platform === "react-native" /* ReactNative */;
39367
+ if (!isBrowser && !isReactNative2) {
39368
+ return;
39369
+ }
39370
+ const dappId = getDappId(options.dapp);
39371
+ const anonId = yield storage.getAnonId();
39372
+ setAnonId == null ? void 0 : setAnonId(anonId);
39373
+ const { integrationType } = (_a4 = options.analytics) != null ? _a4 : {
39374
+ integrationType: ""
39375
+ };
39376
+ analytics.setGlobalProperty("mmconnect_versions", (_b = options.versions) != null ? _b : {});
39377
+ analytics.setGlobalProperty("dapp_id", dappId);
39378
+ analytics.setGlobalProperty("anon_id", anonId);
39379
+ analytics.setGlobalProperty("platform", platform);
39380
+ if (integrationType) {
39381
+ analytics.setGlobalProperty("integration_types", [integrationType]);
39382
+ }
39383
+ analytics.enable();
39384
+ });
39385
+ }
39386
+ var _a3, _provider, _providerTransportWrapper, _transport2, _dappClient, _beforeUnloadListener, _transportType, _listener, _anonId, _MetaMaskConnectMultichain_instances, transportOrThrow_fn, _sdkInfo, setupAnalytics_fn, onTransportNotification_fn, getStoredTransport_fn, setupTransport_fn, buildConnectionMetadata_fn, init_fn2, createDappClient_fn, setupMWP_fn, onBeforeUnload_fn, createBeforeUnloadListener_fn, renderInstallModalAsync_fn, showInstallModal_fn, headlessConnect_fn, setupDefaultTransport_fn, deeplinkConnect_fn, handleConnection_fn, getCaipSession_fn, openConnectDeeplinkIfNeeded_fn;
39218
39387
  var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends MultichainCore {
39219
39388
  constructor(options) {
39220
- var _a4, _b, _c, _d, _e, _f;
39389
+ var _a4, _b, _c, _d;
39221
39390
  const withDappMetadata = setupDappMetadata(options);
39222
- const integrationType = ((_a4 = options.analytics) == null ? void 0 : _a4.integrationType) || "direct";
39223
39391
  const allOptions = __spreadProps(__spreadValues({}, withDappMetadata), {
39224
39392
  ui: __spreadProps(__spreadValues({}, withDappMetadata.ui), {
39225
- preferExtension: (_b = withDappMetadata.ui.preferExtension) != null ? _b : true,
39226
- showInstallModal: (_c = withDappMetadata.ui.showInstallModal) != null ? _c : false,
39227
- headless: (_d = withDappMetadata.ui.headless) != null ? _d : false
39228
- }),
39229
- analytics: __spreadProps(__spreadValues({}, (_e = options.analytics) != null ? _e : {}), {
39230
- integrationType
39393
+ preferExtension: (_a4 = withDappMetadata.ui.preferExtension) != null ? _a4 : true,
39394
+ showInstallModal: (_b = withDappMetadata.ui.showInstallModal) != null ? _b : false,
39395
+ headless: (_c = withDappMetadata.ui.headless) != null ? _c : false
39231
39396
  }),
39397
+ analytics: normalizeAnalyticsOptions(options.analytics),
39232
39398
  versions: __spreadValues({
39233
- // typeof guard needed: Metro (React Native) bundles TS source directly,
39234
- // bypassing the tsup build that substitutes __PACKAGE_VERSION__.
39235
- "connect-multichain": false ? "unknown" : "0.14.0"
39236
- }, (_f = options.versions) != null ? _f : {})
39399
+ "connect-multichain": getVersion()
39400
+ }, (_d = options.versions) != null ? _d : {})
39237
39401
  });
39238
39402
  super(allOptions);
39239
39403
  __privateAdd(this, _MetaMaskConnectMultichain_instances);
@@ -39248,7 +39412,8 @@ ${new this._window.XMLSerializer().serializeToString(e3)}`;
39248
39412
  __privateAdd(this, _anonId);
39249
39413
  __privateAdd(this, _sdkInfo, `Sdk/Javascript SdkVersion/${getVersion()} Platform/${getPlatformType()} dApp/${(_a3 = this.options.dapp.url) != null ? _a3 : this.options.dapp.name} dAppTitle/${this.options.dapp.name}`);
39250
39414
  __privateSet(this, _providerTransportWrapper, new MultichainApiClientWrapperTransport(
39251
- this
39415
+ this,
39416
+ () => __privateGet(this, _transport2)
39252
39417
  ));
39253
39418
  __privateSet(this, _provider, getMultichainClient({
39254
39419
  transport: __privateGet(this, _providerTransportWrapper)
@@ -39267,12 +39432,6 @@ ${new this._window.XMLSerializer().serializeToString(e3)}`;
39267
39432
  get provider() {
39268
39433
  return __privateGet(this, _provider);
39269
39434
  }
39270
- get transport() {
39271
- if (!__privateGet(this, _transport2)) {
39272
- throw new Error("Transport not initialized, establish connection first");
39273
- }
39274
- return __privateGet(this, _transport2);
39275
- }
39276
39435
  get dappClient() {
39277
39436
  if (!__privateGet(this, _dappClient)) {
39278
39437
  throw new Error("DappClient not initialized, establish connection first");
@@ -39286,28 +39445,33 @@ ${new this._window.XMLSerializer().serializeToString(e3)}`;
39286
39445
  get storage() {
39287
39446
  return this.options.storage;
39288
39447
  }
39448
+ get version() {
39449
+ return getVersion();
39450
+ }
39289
39451
  // Creates a singleton instance of MetaMaskConnectMultichain.
39290
39452
  // If the singleton already exists, it merges the incoming options with the
39291
39453
  // existing singleton options for the following keys: `api.supportedNetworks`,
39292
- // `versions`, `ui.*`, `mobile.*`, `transport.extensionId`, `debug`. Take note
39293
- // that the value for `dapp` is not merged as it does not make sense for
39294
- // subsequent calls to `createMultichainClient` to have a different `dapp` value.
39454
+ // `analytics`, `versions`, `ui.*`, `mobile.*`, `transport.extensionId`,
39455
+ // `debug`. Take note that the value for `dapp` is not merged as it does not
39456
+ // make sense for subsequent calls to `createMultichainClient` to have a
39457
+ // different `dapp` value.
39295
39458
  static create(options) {
39296
39459
  return __async(this, null, function* () {
39297
- var _a4, _b;
39460
+ var _a4;
39298
39461
  const globalObject = getGlobalObject();
39299
39462
  const existing = globalObject[SINGLETON_KEY];
39300
39463
  if (existing) {
39301
39464
  const instance2 = yield existing;
39465
+ if (instance2.version !== getVersion()) {
39466
+ console.warn(
39467
+ `MetaMask Connect does not support using multiple versions of @metamask/connect-multichain. Attempted to create a new instance with version ${getVersion()}, but an existing ${instance2.version} singleton was already initialized. Using the existing ${instance2.version} singleton. This is NOT supported and may lead to unexpected behavior. Please ensure there is only one version of @metamask/connect-multichain package resolved in your application.`
39468
+ );
39469
+ }
39302
39470
  instance2.mergeOptions(options);
39303
- analytics.setGlobalProperty(
39304
- "mmconnect_versions",
39305
- (_a4 = instance2.options.versions) != null ? _a4 : {}
39306
- );
39307
- if ((_b = options.analytics) == null ? void 0 : _b.integrationType) {
39308
- analytics.setGlobalProperty("integration_types", [
39309
- options.analytics.integrationType
39310
- ]);
39471
+ if (instance2 instanceof _MetaMaskConnectMultichain) {
39472
+ yield __privateMethod(_a4 = instance2, _MetaMaskConnectMultichain_instances, setupAnalytics_fn).call(_a4);
39473
+ } else {
39474
+ yield setupAnalyticsGlobals(instance2.options, instance2.storage);
39311
39475
  }
39312
39476
  if (options.debug) {
39313
39477
  enableDebug("metamask-sdk:*");
@@ -39326,12 +39490,12 @@ ${new this._window.XMLSerializer().serializeToString(e3)}`;
39326
39490
  }
39327
39491
  yield __privateMethod(_a5 = instance2, _MetaMaskConnectMultichain_instances, init_fn2).call(_a5);
39328
39492
  return instance2;
39329
- }))();
39330
- globalObject[SINGLETON_KEY] = instancePromise;
39331
- instancePromise.catch((error) => {
39493
+ }))().catch((error) => {
39332
39494
  globalObject[SINGLETON_KEY] = void 0;
39333
39495
  console.error("Error initializing MetaMaskConnectMultichain", error);
39496
+ throw error;
39334
39497
  });
39498
+ globalObject[SINGLETON_KEY] = instancePromise;
39335
39499
  return instancePromise;
39336
39500
  });
39337
39501
  }
@@ -39357,21 +39521,23 @@ ${new this._window.XMLSerializer().serializeToString(e3)}`;
39357
39521
  } else {
39358
39522
  transportType = "mwp" /* MWP */;
39359
39523
  }
39360
- try {
39361
- const baseProps = yield getBaseAnalyticsProperties(
39362
- this.options,
39363
- this.storage
39364
- );
39365
- const dappConfiguredChains = Object.keys(
39366
- this.options.api.supportedNetworks
39367
- );
39368
- analytics.track("mmconnect_connection_initiated", __spreadProps(__spreadValues({}, baseProps), {
39369
- transport_type: transportType,
39370
- dapp_configured_chains: dappConfiguredChains,
39371
- dapp_requested_chains: scopes
39372
- }));
39373
- } catch (error) {
39374
- logger2("Error tracking connection_initiated event", error);
39524
+ if (isAnalyticsEnabled(this.options)) {
39525
+ try {
39526
+ const baseProps = yield getBaseAnalyticsProperties(
39527
+ this.options,
39528
+ this.storage
39529
+ );
39530
+ const dappConfiguredChains = Object.keys(
39531
+ this.options.api.supportedNetworks
39532
+ );
39533
+ analytics.track("mmconnect_connection_initiated", __spreadProps(__spreadValues({}, baseProps), {
39534
+ transport_type: transportType,
39535
+ dapp_configured_chains: dappConfiguredChains,
39536
+ dapp_requested_chains: scopes
39537
+ }));
39538
+ } catch (error) {
39539
+ logger2("Error tracking connection_initiated event", error);
39540
+ }
39375
39541
  }
39376
39542
  const sessionData = yield __privateMethod(this, _MetaMaskConnectMultichain_instances, getCaipSession_fn).call(this);
39377
39543
  const { mergedScopes, mergedCaipAccountIds, mergedSessionProperties } = mergeRequestedSessionWithExisting(
@@ -39389,9 +39555,9 @@ ${new this._window.XMLSerializer().serializeToString(e3)}`;
39389
39555
  forceRequest
39390
39556
  }).then(() => __async(this, null, function* () {
39391
39557
  if (__privateGet(this, _transportType) === "mwp" /* MWP */) {
39392
- return this.storage.setTransport("mwp" /* MWP */);
39558
+ return this.storage.setTransportType("mwp" /* MWP */);
39393
39559
  }
39394
- return this.storage.setTransport("browser" /* Browser */);
39560
+ return this.storage.setTransportType("browser" /* Browser */);
39395
39561
  })), scopes, transportType);
39396
39562
  }
39397
39563
  if (platformType === "in-app-browser" /* MetaMaskMobileWebview */) {
@@ -39420,11 +39586,6 @@ ${new this._window.XMLSerializer().serializeToString(e3)}`;
39420
39586
  return __privateMethod(this, _MetaMaskConnectMultichain_instances, handleConnection_fn).call(this, __privateMethod(this, _MetaMaskConnectMultichain_instances, showInstallModal_fn).call(this, shouldShowInstallModal, mergedScopes, mergedCaipAccountIds, nonEmptySessionProperties), scopes, transportType);
39421
39587
  });
39422
39588
  }
39423
- emit(event, args) {
39424
- var _a4, _b;
39425
- (_b = (_a4 = this.options.transport) == null ? void 0 : _a4.onNotification) == null ? void 0 : _b.call(_a4, { method: event, params: args });
39426
- super.emit(event, args);
39427
- }
39428
39589
  disconnect() {
39429
39590
  return __async(this, arguments, function* (scopes = []) {
39430
39591
  var _a4, _b, _c;
@@ -39434,7 +39595,7 @@ ${new this._window.XMLSerializer().serializeToString(e3)}`;
39434
39595
  );
39435
39596
  yield (_a4 = __privateGet(this, _transport2)) == null ? void 0 : _a4.disconnect(scopes);
39436
39597
  if (remainingScopes.length === 0) {
39437
- yield this.storage.removeTransport();
39598
+ yield this.storage.removeTransportType();
39438
39599
  if (__privateGet(this, _transportType) !== "browser" /* Browser */) {
39439
39600
  yield (_b = __privateGet(this, _listener)) == null ? void 0 : _b.call(this);
39440
39601
  (_c = __privateGet(this, _beforeUnloadListener)) == null ? void 0 : _c.call(this);
@@ -39452,7 +39613,8 @@ ${new this._window.XMLSerializer().serializeToString(e3)}`;
39452
39613
  invokeMethod(request2) {
39453
39614
  return __async(this, null, function* () {
39454
39615
  var _a4;
39455
- const { transport, options } = this;
39616
+ const transport = __privateMethod(this, _MetaMaskConnectMultichain_instances, transportOrThrow_fn).call(this);
39617
+ const { options } = this;
39456
39618
  const rpcClient = new RpcClient(options, __privateGet(this, _sdkInfo));
39457
39619
  const requestRouter = new RequestRouter(
39458
39620
  transport,
@@ -39471,7 +39633,7 @@ ${new this._window.XMLSerializer().serializeToString(e3)}`;
39471
39633
  const shouldOpenDeeplink = secure && !showInstallModal;
39472
39634
  if (shouldOpenDeeplink) {
39473
39635
  setTimeout(() => __async(this, null, function* () {
39474
- const session = yield this.transport.getActiveSession();
39636
+ const session = yield __privateMethod(this, _MetaMaskConnectMultichain_instances, transportOrThrow_fn).call(this).getActiveSession();
39475
39637
  if (!session) {
39476
39638
  throw new Error("No active session found");
39477
39639
  }
@@ -39495,10 +39657,13 @@ ${new this._window.XMLSerializer().serializeToString(e3)}`;
39495
39657
  this.emit("wallet_sessionChanged", emptySession);
39496
39658
  return;
39497
39659
  }
39498
- const response = yield this.transport.request({
39660
+ const response = yield __privateGet(this, _transport2).request({
39499
39661
  method: "wallet_getSession"
39500
39662
  });
39501
- this.emit("wallet_sessionChanged", (_b = response.result) != null ? _b : emptySession);
39663
+ this.emit(
39664
+ "wallet_sessionChanged",
39665
+ (_b = response.result) != null ? _b : emptySession
39666
+ );
39502
39667
  });
39503
39668
  }
39504
39669
  };
@@ -39510,34 +39675,19 @@ ${new this._window.XMLSerializer().serializeToString(e3)}`;
39510
39675
  _transportType = new WeakMap();
39511
39676
  _listener = new WeakMap();
39512
39677
  _anonId = new WeakMap();
39513
- _sdkInfo = new WeakMap();
39514
39678
  _MetaMaskConnectMultichain_instances = new WeakSet();
39679
+ transportOrThrow_fn = function() {
39680
+ if (!__privateGet(this, _transport2)) {
39681
+ throw new Error("Transport not initialized, establish connection first");
39682
+ }
39683
+ return __privateGet(this, _transport2);
39684
+ };
39685
+ _sdkInfo = new WeakMap();
39515
39686
  setupAnalytics_fn = function() {
39516
39687
  return __async(this, null, function* () {
39517
- var _a4, _b;
39518
- const platform = getPlatformType();
39519
- const isBrowser = platform === "in-app-browser" /* MetaMaskMobileWebview */ || platform === "web-desktop" /* DesktopWeb */ || platform === "web-mobile" /* MobileWeb */;
39520
- const isReactNative2 = platform === "react-native" /* ReactNative */;
39521
- if (!isBrowser && !isReactNative2) {
39522
- return;
39523
- }
39524
- const dappId = getDappId(this.options.dapp);
39525
- const anonId = yield this.storage.getAnonId();
39526
- __privateSet(this, _anonId, anonId);
39527
- const { integrationType } = (_a4 = this.options.analytics) != null ? _a4 : {
39528
- integrationType: ""
39529
- };
39530
- analytics.setGlobalProperty(
39531
- "mmconnect_versions",
39532
- (_b = this.options.versions) != null ? _b : {}
39533
- );
39534
- analytics.setGlobalProperty("dapp_id", dappId);
39535
- analytics.setGlobalProperty("anon_id", anonId);
39536
- analytics.setGlobalProperty("platform", platform);
39537
- if (integrationType) {
39538
- analytics.setGlobalProperty("integration_types", [integrationType]);
39539
- }
39540
- analytics.enable();
39688
+ yield setupAnalyticsGlobals(this.options, this.storage, (anonId) => {
39689
+ __privateSet(this, _anonId, anonId);
39690
+ });
39541
39691
  });
39542
39692
  };
39543
39693
  onTransportNotification_fn = function(payload) {
@@ -39558,7 +39708,7 @@ ${new this._window.XMLSerializer().serializeToString(e3)}`;
39558
39708
  };
39559
39709
  getStoredTransport_fn = function() {
39560
39710
  return __async(this, null, function* () {
39561
- const transportType = yield this.storage.getTransport();
39711
+ const transportType = yield this.storage.getTransportType();
39562
39712
  const hasExtensionInstalled = yield hasExtension();
39563
39713
  if (transportType) {
39564
39714
  if (transportType === "browser" /* Browser */) {
@@ -39586,7 +39736,7 @@ ${new this._window.XMLSerializer().serializeToString(e3)}`;
39586
39736
  ));
39587
39737
  return apiTransport;
39588
39738
  }
39589
- yield this.storage.removeTransport();
39739
+ yield this.storage.removeTransportType();
39590
39740
  }
39591
39741
  return void 0;
39592
39742
  });
@@ -39596,15 +39746,15 @@ ${new this._window.XMLSerializer().serializeToString(e3)}`;
39596
39746
  var _a4;
39597
39747
  const transport = yield __privateMethod(this, _MetaMaskConnectMultichain_instances, getStoredTransport_fn).call(this);
39598
39748
  if (transport) {
39599
- if (!this.transport.isConnected()) {
39749
+ if (!transport.isConnected()) {
39600
39750
  this.status = "connecting";
39601
- yield this.transport.connect();
39751
+ yield transport.connect();
39602
39752
  }
39603
39753
  this.status = "connected";
39604
39754
  if (__privateGet(this, _transportType) === "mwp" /* MWP */) {
39605
- yield this.storage.setTransport("mwp" /* MWP */);
39755
+ yield this.storage.setTransportType("mwp" /* MWP */);
39606
39756
  } else {
39607
- yield this.storage.setTransport("browser" /* Browser */);
39757
+ yield this.storage.setTransportType("browser" /* Browser */);
39608
39758
  }
39609
39759
  } else {
39610
39760
  this.status = "loaded";
@@ -39613,7 +39763,7 @@ ${new this._window.XMLSerializer().serializeToString(e3)}`;
39613
39763
  if (hasExtensionInstalled && preferExtension) {
39614
39764
  yield __privateMethod(this, _MetaMaskConnectMultichain_instances, setupDefaultTransport_fn).call(this, { persist: false });
39615
39765
  try {
39616
- yield this.transport.init();
39766
+ yield __privateMethod(this, _MetaMaskConnectMultichain_instances, transportOrThrow_fn).call(this).init();
39617
39767
  } catch (error) {
39618
39768
  console.error("Passive init failed:", error);
39619
39769
  }
@@ -39626,7 +39776,7 @@ ${new this._window.XMLSerializer().serializeToString(e3)}`;
39626
39776
  dapp: this.options.dapp,
39627
39777
  sdk: { version: getVersion(), platform: getPlatformType() }
39628
39778
  };
39629
- if (__privateGet(this, _anonId)) {
39779
+ if (isAnalyticsEnabled(this.options) && __privateGet(this, _anonId)) {
39630
39780
  metadata.analytics = { remote_session_id: __privateGet(this, _anonId) };
39631
39781
  }
39632
39782
  return metadata;
@@ -39637,7 +39787,7 @@ ${new this._window.XMLSerializer().serializeToString(e3)}`;
39637
39787
  yield __privateMethod(this, _MetaMaskConnectMultichain_instances, setupAnalytics_fn).call(this);
39638
39788
  yield __privateMethod(this, _MetaMaskConnectMultichain_instances, setupTransport_fn).call(this);
39639
39789
  } catch (error) {
39640
- yield this.storage.removeTransport();
39790
+ yield this.storage.removeTransportType();
39641
39791
  this.status = "pending";
39642
39792
  logger2("MetaMaskSDK error during initialization", error);
39643
39793
  }
@@ -39683,17 +39833,17 @@ ${new this._window.XMLSerializer().serializeToString(e3)}`;
39683
39833
  __privateSet(this, _transport2, apiTransport);
39684
39834
  __privateSet(this, _transportType, "mwp" /* MWP */);
39685
39835
  __privateGet(this, _providerTransportWrapper).setupTransportNotificationListener();
39686
- __privateSet(this, _listener, this.transport.onNotification(
39836
+ __privateSet(this, _listener, apiTransport.onNotification(
39687
39837
  __privateMethod(this, _MetaMaskConnectMultichain_instances, onTransportNotification_fn).bind(this)
39688
39838
  ));
39689
- yield this.storage.setTransport("mwp" /* MWP */);
39839
+ yield this.storage.setTransportType("mwp" /* MWP */);
39690
39840
  });
39691
39841
  };
39692
39842
  onBeforeUnload_fn = function() {
39693
39843
  return __async(this, null, function* () {
39694
39844
  var _a4;
39695
39845
  if ((_a4 = this.options.ui.factory.modal) == null ? void 0 : _a4.isMounted) {
39696
- yield this.storage.removeTransport();
39846
+ yield this.storage.removeTransportType();
39697
39847
  }
39698
39848
  });
39699
39849
  };
@@ -39710,70 +39860,65 @@ ${new this._window.XMLSerializer().serializeToString(e3)}`;
39710
39860
  };
39711
39861
  renderInstallModalAsync_fn = function(desktopPreferred, scopes, caipAccountIds, sessionProperties) {
39712
39862
  return __async(this, null, function* () {
39713
- return new Promise((resolve, reject) => {
39714
- this.options.ui.factory.renderInstallModal(
39715
- desktopPreferred,
39716
- () => __async(this, null, function* () {
39717
- if (this.dappClient.state === "CONNECTED" || this.dappClient.state === "CONNECTING") {
39718
- yield this.dappClient.disconnect();
39719
- }
39720
- return new Promise((_resolve) => {
39721
- this.dappClient.on(
39722
- "session_request",
39723
- (sessionRequest) => {
39724
- _resolve({
39725
- sessionRequest,
39726
- metadata: __privateMethod(this, _MetaMaskConnectMultichain_instances, buildConnectionMetadata_fn).call(this)
39727
- });
39728
- }
39729
- );
39730
- (() => __async(this, null, function* () {
39731
- var _a4;
39732
- try {
39733
- yield this.transport.connect({
39734
- scopes,
39735
- caipAccountIds,
39736
- sessionProperties
39737
- });
39738
- yield this.options.ui.factory.unload();
39739
- (_a4 = this.options.ui.factory.modal) == null ? void 0 : _a4.unmount();
39740
- this.status = "connected";
39741
- yield this.storage.setTransport("mwp" /* MWP */);
39742
- } catch (error) {
39743
- const { ProtocolError, ErrorCode: ErrorCode4 } = yield Promise.resolve().then(() => __toESM(require_dist()));
39744
- if (error instanceof ProtocolError) {
39745
- if (error.code !== ErrorCode4.REQUEST_EXPIRED) {
39746
- this.status = "disconnected";
39747
- yield this.options.ui.factory.unload(error);
39748
- reject(error);
39749
- }
39750
- } else {
39751
- this.status = "disconnected";
39752
- const normalizedError = error instanceof Error ? error : new Error(String(error));
39753
- yield this.options.ui.factory.unload(normalizedError);
39754
- reject(normalizedError);
39755
- }
39756
- }
39757
- }))().catch(() => {
39758
- });
39863
+ const completion = createDeferredPromise();
39864
+ const createConnectionRequest = () => __async(this, null, function* () {
39865
+ if (this.dappClient.state === "CONNECTED" || this.dappClient.state === "CONNECTING") {
39866
+ yield this.dappClient.disconnect();
39867
+ }
39868
+ const sessionRequestDeferred = createDeferredPromise();
39869
+ this.dappClient.on(
39870
+ "session_request",
39871
+ (sessionRequest) => {
39872
+ sessionRequestDeferred.resolve({
39873
+ sessionRequest,
39874
+ metadata: __privateMethod(this, _MetaMaskConnectMultichain_instances, buildConnectionMetadata_fn).call(this)
39759
39875
  });
39760
- }),
39761
- (error) => __async(this, null, function* () {
39762
- if (error) {
39763
- yield this.storage.removeTransport();
39764
- reject(error);
39765
- } else {
39766
- yield this.storage.setTransport("mwp" /* MWP */);
39767
- resolve();
39876
+ }
39877
+ );
39878
+ __privateMethod(this, _MetaMaskConnectMultichain_instances, transportOrThrow_fn).call(this).connect({ scopes, caipAccountIds, sessionProperties }).then(() => __async(this, null, function* () {
39879
+ var _a4;
39880
+ yield this.options.ui.factory.unload();
39881
+ (_a4 = this.options.ui.factory.modal) == null ? void 0 : _a4.unmount();
39882
+ this.status = "connected";
39883
+ yield this.storage.setTransportType("mwp" /* MWP */);
39884
+ })).catch((error) => __async(this, null, function* () {
39885
+ const { ProtocolError, ErrorCode: ErrorCode4 } = yield Promise.resolve().then(() => __toESM(require_dist()));
39886
+ if (error instanceof ProtocolError) {
39887
+ if (error.code !== ErrorCode4.REQUEST_EXPIRED) {
39888
+ this.status = "disconnected";
39889
+ yield this.options.ui.factory.unload(error);
39890
+ completion.reject(error);
39768
39891
  }
39769
- }),
39770
- (uri) => {
39771
- this.emit("display_uri", uri);
39892
+ } else {
39893
+ this.status = "disconnected";
39894
+ const normalizedError = error instanceof Error ? error : new Error(String(error));
39895
+ yield this.options.ui.factory.unload(normalizedError);
39896
+ completion.reject(normalizedError);
39772
39897
  }
39773
- ).catch((error) => {
39774
- reject(error instanceof Error ? error : new Error(String(error)));
39775
- });
39898
+ }));
39899
+ return sessionRequestDeferred.promise;
39776
39900
  });
39901
+ this.options.ui.factory.renderInstallModal(
39902
+ desktopPreferred,
39903
+ createConnectionRequest,
39904
+ (error) => __async(this, null, function* () {
39905
+ if (error) {
39906
+ yield this.storage.removeTransportType();
39907
+ completion.reject(error);
39908
+ } else {
39909
+ yield this.storage.setTransportType("mwp" /* MWP */);
39910
+ completion.resolve();
39911
+ }
39912
+ }),
39913
+ (uri) => {
39914
+ this.emit("display_uri", uri);
39915
+ }
39916
+ ).catch((error) => {
39917
+ completion.reject(
39918
+ error instanceof Error ? error : new Error(String(error))
39919
+ );
39920
+ });
39921
+ return completion.promise;
39777
39922
  });
39778
39923
  };
39779
39924
  showInstallModal_fn = function(desktopPreferred, scopes, caipAccountIds, sessionProperties) {
@@ -39789,39 +39934,37 @@ ${new this._window.XMLSerializer().serializeToString(e3)}`;
39789
39934
  };
39790
39935
  headlessConnect_fn = function(scopes, caipAccountIds, sessionProperties) {
39791
39936
  return __async(this, null, function* () {
39792
- return new Promise((resolve, reject) => {
39793
- if (this.dappClient.state === "CONNECTED" || this.dappClient.state === "CONNECTING") {
39794
- this.dappClient.disconnect().catch(() => {
39795
- });
39937
+ if (this.dappClient.state === "CONNECTED" || this.dappClient.state === "CONNECTING") {
39938
+ yield this.dappClient.disconnect().catch(() => void 0);
39939
+ }
39940
+ const onSessionRequest = (sessionRequest) => {
39941
+ const connectionRequest = {
39942
+ sessionRequest,
39943
+ metadata: __privateMethod(this, _MetaMaskConnectMultichain_instances, buildConnectionMetadata_fn).call(this)
39944
+ };
39945
+ const deeplink = this.options.ui.factory.createConnectionDeeplink(connectionRequest);
39946
+ this.emit("display_uri", deeplink);
39947
+ };
39948
+ this.dappClient.on("session_request", onSessionRequest);
39949
+ try {
39950
+ yield __privateMethod(this, _MetaMaskConnectMultichain_instances, transportOrThrow_fn).call(this).connect({
39951
+ scopes,
39952
+ caipAccountIds,
39953
+ sessionProperties
39954
+ });
39955
+ this.status = "connected";
39956
+ yield this.storage.setTransportType("mwp" /* MWP */);
39957
+ } catch (error) {
39958
+ const { ProtocolError } = yield Promise.resolve().then(() => __toESM(require_dist()));
39959
+ this.status = "disconnected";
39960
+ yield this.storage.removeTransportType();
39961
+ if (error instanceof ProtocolError || error instanceof Error) {
39962
+ throw error;
39796
39963
  }
39797
- this.dappClient.on(
39798
- "session_request",
39799
- (sessionRequest) => {
39800
- const connectionRequest = {
39801
- sessionRequest,
39802
- metadata: __privateMethod(this, _MetaMaskConnectMultichain_instances, buildConnectionMetadata_fn).call(this)
39803
- };
39804
- const deeplink = this.options.ui.factory.createConnectionDeeplink(connectionRequest);
39805
- this.emit("display_uri", deeplink);
39806
- }
39807
- );
39808
- this.transport.connect({ scopes, caipAccountIds, sessionProperties }).then(() => __async(this, null, function* () {
39809
- this.status = "connected";
39810
- yield this.storage.setTransport("mwp" /* MWP */);
39811
- resolve();
39812
- })).catch((error) => __async(this, null, function* () {
39813
- const { ProtocolError } = yield Promise.resolve().then(() => __toESM(require_dist()));
39814
- if (error instanceof ProtocolError) {
39815
- this.status = "disconnected";
39816
- yield this.storage.removeTransport();
39817
- reject(error);
39818
- } else {
39819
- this.status = "disconnected";
39820
- yield this.storage.removeTransport();
39821
- reject(error instanceof Error ? error : new Error(String(error)));
39822
- }
39823
- }));
39824
- });
39964
+ throw new Error(String(error));
39965
+ } finally {
39966
+ this.dappClient.off("session_request", onSessionRequest);
39967
+ }
39825
39968
  });
39826
39969
  };
39827
39970
  setupDefaultTransport_fn = function() {
@@ -39830,7 +39973,7 @@ ${new this._window.XMLSerializer().serializeToString(e3)}`;
39830
39973
  return __privateGet(this, _transport2);
39831
39974
  }
39832
39975
  if (options == null ? void 0 : options.persist) {
39833
- yield this.storage.setTransport("browser" /* Browser */);
39976
+ yield this.storage.setTransportType("browser" /* Browser */);
39834
39977
  }
39835
39978
  const transport = new DefaultTransport();
39836
39979
  __privateSet(this, _listener, transport.onNotification(
@@ -39863,7 +40006,7 @@ ${new this._window.XMLSerializer().serializeToString(e3)}`;
39863
40006
  };
39864
40007
  this.dappClient.on("message", dappClientMessageHandler);
39865
40008
  let timeout;
39866
- if (this.transport.isConnected()) {
40009
+ if (__privateMethod(this, _MetaMaskConnectMultichain_instances, transportOrThrow_fn).call(this).isConnected()) {
39867
40010
  timeout = setTimeout(() => {
39868
40011
  this.openSimpleDeeplinkIfNeeded();
39869
40012
  }, 250);
@@ -39891,8 +40034,8 @@ ${new this._window.XMLSerializer().serializeToString(e3)}`;
39891
40034
  }
39892
40035
  );
39893
40036
  }
39894
- return this.transport.connect({ scopes, caipAccountIds, sessionProperties }).then(resolve).catch((error) => __async(this, null, function* () {
39895
- yield this.storage.removeTransport();
40037
+ return __privateMethod(this, _MetaMaskConnectMultichain_instances, transportOrThrow_fn).call(this).connect({ scopes, caipAccountIds, sessionProperties }).then(resolve).catch((error) => __async(this, null, function* () {
40038
+ yield this.storage.removeTransportType();
39896
40039
  this.dappClient.off("message", dappClientMessageHandler);
39897
40040
  reject(error instanceof Error ? error : new Error(String(error)));
39898
40041
  })).finally(() => {
@@ -39908,38 +40051,42 @@ ${new this._window.XMLSerializer().serializeToString(e3)}`;
39908
40051
  this.status = "connecting";
39909
40052
  return promise.then(() => __async(this, null, function* () {
39910
40053
  this.status = "connected";
39911
- try {
39912
- const baseProps = yield getBaseAnalyticsProperties(
39913
- this.options,
39914
- this.storage
39915
- );
39916
- analytics.track("mmconnect_connection_established", __spreadProps(__spreadValues({}, baseProps), {
39917
- transport_type: transportType,
39918
- user_permissioned_chains: scopes
39919
- }));
39920
- } catch (error) {
39921
- logger2("Error tracking connection_established event", error);
40054
+ if (isAnalyticsEnabled(this.options)) {
40055
+ try {
40056
+ const baseProps = yield getBaseAnalyticsProperties(
40057
+ this.options,
40058
+ this.storage
40059
+ );
40060
+ analytics.track("mmconnect_connection_established", __spreadProps(__spreadValues({}, baseProps), {
40061
+ transport_type: transportType,
40062
+ user_permissioned_chains: scopes
40063
+ }));
40064
+ } catch (error) {
40065
+ logger2("Error tracking connection_established event", error);
40066
+ }
39922
40067
  }
39923
40068
  return void 0;
39924
40069
  })).catch((error) => __async(this, null, function* () {
39925
40070
  this.status = "disconnected";
39926
- try {
39927
- const baseProps = yield getBaseAnalyticsProperties(
39928
- this.options,
39929
- this.storage
39930
- );
39931
- const isRejection = isRejectionError(error);
39932
- if (isRejection) {
39933
- analytics.track("mmconnect_connection_rejected", __spreadProps(__spreadValues({}, baseProps), {
39934
- transport_type: transportType
39935
- }));
39936
- } else {
39937
- analytics.track("mmconnect_connection_failed", __spreadValues(__spreadProps(__spreadValues({}, baseProps), {
39938
- transport_type: transportType
39939
- }), extractErrorDiagnostics(error)));
40071
+ if (isAnalyticsEnabled(this.options)) {
40072
+ try {
40073
+ const baseProps = yield getBaseAnalyticsProperties(
40074
+ this.options,
40075
+ this.storage
40076
+ );
40077
+ const isRejection = isRejectionError(error);
40078
+ if (isRejection) {
40079
+ analytics.track("mmconnect_connection_rejected", __spreadProps(__spreadValues({}, baseProps), {
40080
+ transport_type: transportType
40081
+ }));
40082
+ } else {
40083
+ analytics.track("mmconnect_connection_failed", __spreadValues(__spreadProps(__spreadValues({}, baseProps), {
40084
+ transport_type: transportType
40085
+ }), extractErrorDiagnostics(error)));
40086
+ }
40087
+ } catch (e) {
40088
+ logger2("Error tracking connection failed/rejected event", error);
39940
40089
  }
39941
- } catch (e) {
39942
- logger2("Error tracking connection failed/rejected event", error);
39943
40090
  }
39944
40091
  throw error;
39945
40092
  }));
@@ -39954,7 +40101,7 @@ ${new this._window.XMLSerializer().serializeToString(e3)}`;
39954
40101
  };
39955
40102
  if ((_a4 = __privateGet(this, _transport2)) == null ? void 0 : _a4.isConnected()) {
39956
40103
  try {
39957
- const response = yield this.transport.request({
40104
+ const response = yield __privateGet(this, _transport2).request({
39958
40105
  method: "wallet_getSession"
39959
40106
  });
39960
40107
  if (response.result) {
@@ -40048,14 +40195,14 @@ ${new this._window.XMLSerializer().serializeToString(e3)}`;
40048
40195
  super();
40049
40196
  this.adapter = adapter;
40050
40197
  }
40051
- getTransport() {
40198
+ getTransportType() {
40052
40199
  return __async(this, null, function* () {
40053
40200
  try {
40054
- const transport = yield this.adapter.get("multichain-transport");
40055
- if (!transport) {
40201
+ const transportType = yield this.adapter.get("multichain-transport");
40202
+ if (!transportType) {
40056
40203
  return null;
40057
40204
  }
40058
- return getTransportType(transport);
40205
+ return getTransportType(transportType);
40059
40206
  } catch (err3) {
40060
40207
  throw new StorageGetErr(
40061
40208
  this.adapter.platform,
@@ -40065,10 +40212,10 @@ ${new this._window.XMLSerializer().serializeToString(e3)}`;
40065
40212
  }
40066
40213
  });
40067
40214
  }
40068
- setTransport(transport) {
40215
+ setTransportType(transportType) {
40069
40216
  return __async(this, null, function* () {
40070
40217
  try {
40071
- yield this.adapter.set("multichain-transport", transport);
40218
+ yield this.adapter.set("multichain-transport", transportType);
40072
40219
  } catch (err3) {
40073
40220
  throw new StorageSetErr(
40074
40221
  this.adapter.platform,
@@ -40078,7 +40225,7 @@ ${new this._window.XMLSerializer().serializeToString(e3)}`;
40078
40225
  }
40079
40226
  });
40080
40227
  }
40081
- removeTransport() {
40228
+ removeTransportType() {
40082
40229
  return __async(this, null, function* () {
40083
40230
  try {
40084
40231
  yield this.adapter.delete("multichain-transport");
@@ -40561,7 +40708,11 @@ ${new this._window.XMLSerializer().serializeToString(e3)}`;
40561
40708
  (_a5 = this.displayUriCallback) == null ? void 0 : _a5.call(this, newLink);
40562
40709
  return newLink;
40563
40710
  }),
40564
- onClose: this.onCloseModal.bind(this),
40711
+ onClose: (shouldTerminate) => {
40712
+ this.onCloseModal(shouldTerminate).catch((error) => {
40713
+ console.error("Failed to close modal:", error);
40714
+ });
40715
+ },
40565
40716
  startDesktopOnboarding: this.onStartDesktopOnboarding.bind(this),
40566
40717
  createConnectionRequest,
40567
40718
  onDisplayUri: this.displayUriCallback
@@ -40599,7 +40750,7 @@ ${new this._window.XMLSerializer().serializeToString(e3)}`;
40599
40750
  }
40600
40751
  try {
40601
40752
  const { defineCustomElements: defineCustomElements2 } = yield Promise.resolve().then(() => (init_loader2(), loader_exports));
40602
- yield defineCustomElements2();
40753
+ defineCustomElements2();
40603
40754
  } catch (error) {
40604
40755
  console.error("Failed to load customElements:", error);
40605
40756
  }