@metamask/connect-multichain 0.15.0 → 1.1.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 (84) hide show
  1. package/CHANGELOG.md +36 -1
  2. package/README.md +0 -1
  3. package/dist/browser/es/connect-multichain.d.mts +18 -8
  4. package/dist/browser/es/connect-multichain.mjs +558 -378
  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 +18 -8
  8. package/dist/browser/iife/connect-multichain.js +571 -378
  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 +18 -8
  12. package/dist/browser/umd/connect-multichain.js +558 -378
  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 +18 -8
  16. package/dist/node/cjs/connect-multichain.js +560 -376
  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 +18 -8
  20. package/dist/node/es/connect-multichain.mjs +557 -375
  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 +18 -8
  24. package/dist/react-native/es/connect-multichain.mjs +556 -374
  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/errors/rpc.d.ts +11 -1
  28. package/dist/src/domain/errors/rpc.d.ts.map +1 -1
  29. package/dist/src/domain/errors/rpc.js +10 -2
  30. package/dist/src/domain/errors/rpc.js.map +1 -1
  31. package/dist/src/domain/multichain/api/constants.d.ts +1 -0
  32. package/dist/src/domain/multichain/api/constants.d.ts.map +1 -1
  33. package/dist/src/domain/multichain/api/constants.js +13 -0
  34. package/dist/src/domain/multichain/api/constants.js.map +1 -1
  35. package/dist/src/domain/multichain/index.d.ts +2 -2
  36. package/dist/src/domain/multichain/index.d.ts.map +1 -1
  37. package/dist/src/domain/multichain/index.js.map +1 -1
  38. package/dist/src/domain/multichain/types.d.ts +0 -1
  39. package/dist/src/domain/multichain/types.d.ts.map +1 -1
  40. package/dist/src/domain/platform/index.d.ts.map +1 -1
  41. package/dist/src/domain/platform/index.js +27 -5
  42. package/dist/src/domain/platform/index.js.map +1 -1
  43. package/dist/src/domain/store/client.d.ts +3 -3
  44. package/dist/src/domain/store/client.d.ts.map +1 -1
  45. package/dist/src/domain/utils/index.d.ts +1 -0
  46. package/dist/src/domain/utils/index.d.ts.map +1 -1
  47. package/dist/src/domain/utils/index.js +5 -1
  48. package/dist/src/domain/utils/index.js.map +1 -1
  49. package/dist/src/multichain/index.d.ts +2 -3
  50. package/dist/src/multichain/index.d.ts.map +1 -1
  51. package/dist/src/multichain/index.js +142 -147
  52. package/dist/src/multichain/index.js.map +1 -1
  53. package/dist/src/multichain/rpc/invocationError.d.ts +9 -0
  54. package/dist/src/multichain/rpc/invocationError.d.ts.map +1 -0
  55. package/dist/src/multichain/rpc/invocationError.js +99 -0
  56. package/dist/src/multichain/rpc/invocationError.js.map +1 -0
  57. package/dist/src/multichain/rpc/requestRouter.d.ts +15 -0
  58. package/dist/src/multichain/rpc/requestRouter.d.ts.map +1 -1
  59. package/dist/src/multichain/rpc/requestRouter.js +38 -20
  60. package/dist/src/multichain/rpc/requestRouter.js.map +1 -1
  61. package/dist/src/multichain/transports/default/index.d.ts.map +1 -1
  62. package/dist/src/multichain/transports/default/index.js +25 -10
  63. package/dist/src/multichain/transports/default/index.js.map +1 -1
  64. package/dist/src/multichain/transports/multichainApiClientWrapper/index.d.ts +2 -1
  65. package/dist/src/multichain/transports/multichainApiClientWrapper/index.d.ts.map +1 -1
  66. package/dist/src/multichain/transports/multichainApiClientWrapper/index.js +25 -17
  67. package/dist/src/multichain/transports/multichainApiClientWrapper/index.js.map +1 -1
  68. package/dist/src/multichain/transports/mwp/index.d.ts +3 -1
  69. package/dist/src/multichain/transports/mwp/index.d.ts.map +1 -1
  70. package/dist/src/multichain/transports/mwp/index.js +235 -172
  71. package/dist/src/multichain/transports/mwp/index.js.map +1 -1
  72. package/dist/src/store/index.d.ts +3 -3
  73. package/dist/src/store/index.d.ts.map +1 -1
  74. package/dist/src/store/index.js +8 -8
  75. package/dist/src/store/index.js.map +1 -1
  76. package/dist/src/ui/ModalFactory.d.ts.map +1 -1
  77. package/dist/src/ui/ModalFactory.js +5 -1
  78. package/dist/src/ui/ModalFactory.js.map +1 -1
  79. package/dist/src/ui/index.js +1 -1
  80. package/dist/src/ui/index.js.map +1 -1
  81. package/dist/src/ui/modals/web/install.d.ts.map +1 -1
  82. package/dist/src/ui/modals/web/install.js.map +1 -1
  83. package/dist/types/connect-multichain.d.ts +18 -8
  84. package/package.json +2 -2
@@ -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";
@@ -15755,7 +15768,15 @@ var MetaMaskSDK = (() => {
15755
15768
  _RPCReadonlyRequestErr.code = 52;
15756
15769
  RPCReadonlyRequestErr = _RPCReadonlyRequestErr;
15757
15770
  _RPCInvokeMethodErr = class _RPCInvokeMethodErr extends BaseErr {
15758
- constructor(reason, rpcCode, rpcMessage) {
15771
+ /**
15772
+ * @param reason - MetaMask Connect invokeMethod reason.
15773
+ * @param rpcCode - Original wallet JSON-RPC / EIP-1193 error code.
15774
+ * @param rpcMessage - Original provider-facing wallet message, sourced only
15775
+ * from the wallet's coded error. Unset when the wallet provides no message,
15776
+ * so it may differ from `reason`, which can fall back through the cause chain.
15777
+ * @param rpcData - Original JSON-RPC error data, when provided by the wallet.
15778
+ */
15779
+ constructor(reason, rpcCode, rpcMessage, rpcData) {
15759
15780
  super(
15760
15781
  `RPCErr${_RPCInvokeMethodErr.code}: RPC Client invoke method reason (${reason})`,
15761
15782
  _RPCInvokeMethodErr.code
@@ -15763,6 +15784,7 @@ var MetaMaskSDK = (() => {
15763
15784
  this.reason = reason;
15764
15785
  this.rpcCode = rpcCode;
15765
15786
  this.rpcMessage = rpcMessage;
15787
+ this.rpcData = rpcData;
15766
15788
  }
15767
15789
  };
15768
15790
  _RPCInvokeMethodErr.code = 53;
@@ -16066,7 +16088,7 @@ var MetaMaskSDK = (() => {
16066
16088
  });
16067
16089
 
16068
16090
  // src/domain/multichain/api/constants.ts
16069
- var infuraRpcUrls, RPC_HANDLED_METHODS, SDK_HANDLED_METHODS;
16091
+ var infuraRpcUrls, RPC_HANDLED_METHODS, SDK_HANDLED_METHODS, EIP1193_PASSTHROUGH_METHODS;
16070
16092
  var init_constants = __esm({
16071
16093
  "src/domain/multichain/api/constants.ts"() {
16072
16094
  "use strict";
@@ -16231,6 +16253,11 @@ var MetaMaskSDK = (() => {
16231
16253
  "eth_uninstallFilter"
16232
16254
  ]);
16233
16255
  SDK_HANDLED_METHODS = /* @__PURE__ */ new Set(["eth_accounts", "eth_chainId"]);
16256
+ EIP1193_PASSTHROUGH_METHODS = /* @__PURE__ */ new Set([
16257
+ "wallet_addEthereumChain",
16258
+ "wallet_switchEthereumChain",
16259
+ "eth_accounts"
16260
+ ]);
16234
16261
  }
16235
16262
  });
16236
16263
 
@@ -17016,7 +17043,7 @@ var MetaMaskSDK = (() => {
17016
17043
  return detectionPromise;
17017
17044
  });
17018
17045
  }
17019
- var import_bowser, PlatformType, detectionPromise;
17046
+ var import_bowser, PlatformType, NATIVE_METAMASK_EIP6963_RDNS, detectionPromise;
17020
17047
  var init_platform = __esm({
17021
17048
  "src/domain/platform/index.ts"() {
17022
17049
  "use strict";
@@ -17029,6 +17056,10 @@ var MetaMaskSDK = (() => {
17029
17056
  PlatformType2["ReactNative"] = "react-native";
17030
17057
  return PlatformType2;
17031
17058
  })(PlatformType || {});
17059
+ NATIVE_METAMASK_EIP6963_RDNS = /* @__PURE__ */ new Set([
17060
+ "io.metamask",
17061
+ "io.metamask.mobile"
17062
+ ]);
17032
17063
  detectionPromise = (() => __async(null, null, function* () {
17033
17064
  const pt = getPlatformType();
17034
17065
  if (pt === "nodejs" /* NonBrowser */ || pt === "react-native" /* ReactNative */) {
@@ -17036,23 +17067,30 @@ var MetaMaskSDK = (() => {
17036
17067
  }
17037
17068
  return new Promise((resolve) => {
17038
17069
  const providers = [];
17070
+ const targetWindow = window;
17039
17071
  const handler = (event) => {
17040
17072
  var _a4, _b;
17041
17073
  if ((_b = (_a4 = event == null ? void 0 : event.detail) == null ? void 0 : _a4.info) == null ? void 0 : _b.rdns) {
17042
17074
  providers.push(event.detail);
17043
17075
  }
17044
17076
  };
17045
- window.addEventListener("eip6963:announceProvider", handler);
17046
- window.dispatchEvent(new Event("eip6963:requestProvider"));
17077
+ targetWindow.addEventListener("eip6963:announceProvider", handler);
17078
+ targetWindow.dispatchEvent(new Event("eip6963:requestProvider"));
17047
17079
  setTimeout(() => {
17048
- window.removeEventListener("eip6963:announceProvider", handler);
17049
- const hasMetaMask = providers.some(
17050
- (provider) => {
17051
- var _a4, _b;
17052
- return (_b = (_a4 = provider == null ? void 0 : provider.info) == null ? void 0 : _a4.rdns) == null ? void 0 : _b.startsWith("io.metamask");
17080
+ try {
17081
+ if (typeof (targetWindow == null ? void 0 : targetWindow.removeEventListener) === "function") {
17082
+ targetWindow.removeEventListener("eip6963:announceProvider", handler);
17053
17083
  }
17054
- );
17055
- resolve(hasMetaMask);
17084
+ const hasMetaMask = providers.some(
17085
+ (provider) => {
17086
+ var _a4;
17087
+ return typeof ((_a4 = provider == null ? void 0 : provider.info) == null ? void 0 : _a4.rdns) === "string" && NATIVE_METAMASK_EIP6963_RDNS.has(provider.info.rdns);
17088
+ }
17089
+ );
17090
+ resolve(hasMetaMask);
17091
+ } catch (e) {
17092
+ resolve(false);
17093
+ }
17056
17094
  }, 300);
17057
17095
  });
17058
17096
  }))();
@@ -17297,12 +17335,14 @@ var MetaMaskSDK = (() => {
17297
17335
 
17298
17336
  // src/domain/utils/index.ts
17299
17337
  function getVersion() {
17300
- return "0.0.0";
17338
+ return packageVersion;
17301
17339
  }
17340
+ var packageVersion;
17302
17341
  var init_utils3 = __esm({
17303
17342
  "src/domain/utils/index.ts"() {
17304
17343
  "use strict";
17305
17344
  init_analytics();
17345
+ packageVersion = false ? "unknown" : "1.1.0";
17306
17346
  }
17307
17347
  });
17308
17348
 
@@ -25748,12 +25788,13 @@ var MetaMaskSDK = (() => {
25748
25788
  __export(mwp_exports, {
25749
25789
  MWPTransport: () => MWPTransport
25750
25790
  });
25751
- 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;
25791
+ 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;
25752
25792
  var init_mwp = __esm({
25753
25793
  "src/multichain/transports/mwp/index.ts"() {
25754
25794
  "use strict";
25755
25795
  init_dist3();
25756
25796
  init_dist4();
25797
+ init_dist2();
25757
25798
  init_domain();
25758
25799
  init_utils4();
25759
25800
  init_constants3();
@@ -25784,6 +25825,7 @@ var MetaMaskSDK = (() => {
25784
25825
  this.dappClient = dappClient;
25785
25826
  this.kvstore = kvstore;
25786
25827
  this.options = options;
25828
+ __privateAdd(this, _MWPTransport_instances);
25787
25829
  this.__pendingRequests = /* @__PURE__ */ new Map();
25788
25830
  this.notificationCallbacks = /* @__PURE__ */ new Set();
25789
25831
  this.dappClient.on("message", this.handleMessage.bind(this));
@@ -25855,14 +25897,33 @@ var MetaMaskSDK = (() => {
25855
25897
  const errorData = errorPayload;
25856
25898
  if (typeof errorData.code === "number" && typeof errorData.message === "string") {
25857
25899
  const { code, message: message2 } = errorData;
25900
+ const rawData = errorData.data;
25901
+ const data = isValidJson(rawData) ? rawData : void 0;
25858
25902
  if (code >= 1e3 && code <= 4999) {
25859
- return providerErrors.custom({ code, message: message2 });
25903
+ return providerErrors.custom({ code, message: message2, data });
25860
25904
  }
25861
- return new JsonRpcError(code, message2);
25905
+ return new JsonRpcError(code, message2, data);
25862
25906
  }
25863
25907
  const message = errorPayload instanceof Error ? errorPayload.message : JSON.stringify(errorPayload);
25864
25908
  return rpcErrors.internal({ message });
25865
25909
  }
25910
+ getResponseError(messagePayload) {
25911
+ if ("error" in messagePayload && messagePayload.error) {
25912
+ return messagePayload.error;
25913
+ }
25914
+ const { result } = messagePayload;
25915
+ if (typeof result === "object" && result !== null && "error" in result && result.error && this.isErrorPayload(result.error)) {
25916
+ return result.error;
25917
+ }
25918
+ return void 0;
25919
+ }
25920
+ isErrorPayload(errorPayload) {
25921
+ if (errorPayload instanceof Error) {
25922
+ return true;
25923
+ }
25924
+ const errorData = errorPayload;
25925
+ return typeof (errorData == null ? void 0 : errorData.code) === "number" && typeof (errorData == null ? void 0 : errorData.message) === "string";
25926
+ }
25866
25927
  handleMessage(message) {
25867
25928
  if (typeof message === "object" && message !== null) {
25868
25929
  if ("data" in message) {
@@ -25871,9 +25932,10 @@ var MetaMaskSDK = (() => {
25871
25932
  const request2 = this.pendingRequests.get(messagePayload.id);
25872
25933
  if (request2) {
25873
25934
  clearTimeout(request2.timeout);
25874
- if ("error" in messagePayload && messagePayload.error) {
25935
+ const responseError = this.getResponseError(messagePayload);
25936
+ if (responseError) {
25875
25937
  this.pendingRequests.delete(messagePayload.id);
25876
- request2.reject(this.parseWalletError(messagePayload.error));
25938
+ request2.reject(this.parseWalletError(responseError));
25877
25939
  return;
25878
25940
  }
25879
25941
  const requestWithName = __spreadProps(__spreadValues({}, messagePayload), {
@@ -25916,73 +25978,6 @@ var MetaMaskSDK = (() => {
25916
25978
  }
25917
25979
  }
25918
25980
  }
25919
- onResumeSuccess(resumeResolve, resumeReject, options) {
25920
- return __async(this, null, function* () {
25921
- var _a4, _b, _c, _d, _e, _f, _g;
25922
- try {
25923
- yield this.waitForWalletSessionIfNotCached();
25924
- const sessionRequest = yield this.request({
25925
- method: "wallet_getSession"
25926
- });
25927
- if (sessionRequest.error) {
25928
- return resumeReject(new Error(sessionRequest.error.message));
25929
- }
25930
- let walletSession = sessionRequest.result;
25931
- if (walletSession && options) {
25932
- const currentScopes = Object.keys(
25933
- (_a4 = walletSession == null ? void 0 : walletSession.sessionScopes) != null ? _a4 : {}
25934
- );
25935
- const proposedScopes = (_b = options == null ? void 0 : options.scopes) != null ? _b : [];
25936
- const proposedCaipAccountIds = (_c = options == null ? void 0 : options.caipAccountIds) != null ? _c : [];
25937
- const hasSameScopesAndAccounts = isSameScopesAndAccounts(
25938
- currentScopes,
25939
- proposedScopes,
25940
- walletSession,
25941
- proposedCaipAccountIds
25942
- );
25943
- if (options.forceRequest || !hasSameScopesAndAccounts) {
25944
- const optionalScopes = addValidAccounts(
25945
- getOptionalScopes((_d = options == null ? void 0 : options.scopes) != null ? _d : []),
25946
- getValidAccounts((_e = options == null ? void 0 : options.caipAccountIds) != null ? _e : [])
25947
- );
25948
- const sessionRequest2 = {
25949
- optionalScopes
25950
- };
25951
- const response = yield this.request({
25952
- method: "wallet_createSession",
25953
- params: sessionRequest2
25954
- });
25955
- if (response.error) {
25956
- return resumeReject(new Error(response.error.message));
25957
- }
25958
- walletSession = response.result;
25959
- }
25960
- } else if (!walletSession) {
25961
- const optionalScopes = addValidAccounts(
25962
- getOptionalScopes((_f = options == null ? void 0 : options.scopes) != null ? _f : []),
25963
- getValidAccounts((_g = options == null ? void 0 : options.caipAccountIds) != null ? _g : [])
25964
- );
25965
- const sessionRequest2 = { optionalScopes };
25966
- const response = yield this.request({
25967
- method: "wallet_createSession",
25968
- params: sessionRequest2
25969
- });
25970
- if (response.error) {
25971
- return resumeReject(new Error(response.error.message));
25972
- }
25973
- walletSession = response.result;
25974
- }
25975
- yield this.removeStoredPendingSessionRequest();
25976
- this.notifyCallbacks({
25977
- method: "wallet_sessionChanged",
25978
- params: walletSession
25979
- });
25980
- return resumeResolve();
25981
- } catch (err3) {
25982
- return resumeReject(err3);
25983
- }
25984
- });
25985
- }
25986
25981
  init() {
25987
25982
  return __async(this, null, function* () {
25988
25983
  });
@@ -26023,7 +26018,6 @@ var MetaMaskSDK = (() => {
26023
26018
  }
26024
26019
  connect(options) {
26025
26020
  return __async(this, null, function* () {
26026
- const { dappClient } = this;
26027
26021
  const session = yield this.getActiveSession();
26028
26022
  if (session) {
26029
26023
  logger("active session found", {
@@ -26032,116 +26026,11 @@ var MetaMaskSDK = (() => {
26032
26026
  expiresAt: session.expiresAt
26033
26027
  });
26034
26028
  }
26035
- const storedSessionRequestBeforeConnectionAttempt = yield this.getStoredPendingSessionRequest();
26036
- let timeout;
26037
- let initialConnectionMessageHandler;
26038
- const connectionPromise = new Promise((resolve, reject) => __async(this, null, function* () {
26039
- let connection;
26040
- if (session) {
26041
- connection = new Promise((resumeResolve, resumeReject) => {
26042
- var _a4;
26043
- if (this.dappClient.state === "CONNECTED") {
26044
- this.onResumeSuccess(resumeResolve, resumeReject, options);
26045
- } else {
26046
- this.dappClient.once("connected", () => __async(this, null, function* () {
26047
- this.onResumeSuccess(resumeResolve, resumeReject, options);
26048
- }));
26049
- dappClient.resume((_a4 = session == null ? void 0 : session.id) != null ? _a4 : "");
26050
- }
26051
- });
26052
- } else {
26053
- connection = new Promise(
26054
- (resolveConnection, rejectConnection) => {
26055
- var _a4, _b;
26056
- const optionalScopes = addValidAccounts(
26057
- getOptionalScopes((_a4 = options == null ? void 0 : options.scopes) != null ? _a4 : []),
26058
- getValidAccounts((_b = options == null ? void 0 : options.caipAccountIds) != null ? _b : [])
26059
- );
26060
- const sessionRequest = {
26061
- optionalScopes,
26062
- sessionProperties: options == null ? void 0 : options.sessionProperties
26063
- };
26064
- const request2 = {
26065
- jsonrpc: "2.0",
26066
- id: String(getUniqueRequestId()),
26067
- method: "wallet_createSession",
26068
- params: sessionRequest
26069
- };
26070
- initialConnectionMessageHandler = (message) => __async(this, null, function* () {
26071
- if (typeof message !== "object" || message === null) {
26072
- return;
26073
- }
26074
- if (!("data" in message)) {
26075
- return;
26076
- }
26077
- const messagePayload = message.data;
26078
- const isMatchingId = messagePayload.id === request2.id;
26079
- const isMatchingMethod = messagePayload.method === "wallet_createSession" || messagePayload.method === "wallet_sessionChanged";
26080
- if (!isMatchingId && !isMatchingMethod) {
26081
- return;
26082
- }
26083
- if (messagePayload.error) {
26084
- return rejectConnection(
26085
- this.parseWalletError(messagePayload.error)
26086
- );
26087
- }
26088
- yield this.storeWalletSession(
26089
- request2,
26090
- messagePayload
26091
- );
26092
- yield this.removeStoredPendingSessionRequest();
26093
- this.notifyCallbacks(messagePayload);
26094
- return resolveConnection();
26095
- });
26096
- this.dappClient.on("message", initialConnectionMessageHandler);
26097
- const platformType = getPlatformType();
26098
- const isQRCodeFlow = [
26099
- "web-desktop" /* DesktopWeb */,
26100
- "nodejs" /* NonBrowser */
26101
- ].includes(platformType);
26102
- const initialPayload = {
26103
- name: MULTICHAIN_PROVIDER_STREAM_NAME,
26104
- data: request2
26105
- };
26106
- dappClient.connect({
26107
- mode: "trusted",
26108
- initialPayload: isQRCodeFlow ? void 0 : initialPayload
26109
- }).then(() => __async(this, null, function* () {
26110
- if (isQRCodeFlow) {
26111
- return dappClient.sendRequest(initialPayload);
26112
- }
26113
- return void 0;
26114
- })).catch((error) => {
26115
- if (initialConnectionMessageHandler) {
26116
- this.dappClient.off(
26117
- "message",
26118
- initialConnectionMessageHandler
26119
- );
26120
- }
26121
- rejectConnection(error);
26122
- });
26123
- }
26124
- );
26125
- }
26126
- timeout = setTimeout(
26127
- () => {
26128
- reject(new TransportTimeoutError());
26129
- },
26130
- storedSessionRequestBeforeConnectionAttempt ? this.options.resumeTimeout : this.options.connectionTimeout
26131
- );
26132
- connection.then(resolve).catch(reject);
26133
- }));
26134
- return connectionPromise.catch((error) => __async(this, null, function* () {
26029
+ const connection = session ? __privateMethod(this, _MWPTransport_instances, resumeSession_fn).call(this, session, options) : __privateMethod(this, _MWPTransport_instances, startSession_fn).call(this, options);
26030
+ return connection.catch((error) => __async(this, null, function* () {
26135
26031
  yield this.dappClient.disconnect();
26136
26032
  throw error;
26137
26033
  })).finally(() => {
26138
- if (timeout) {
26139
- clearTimeout(timeout);
26140
- }
26141
- if (initialConnectionMessageHandler) {
26142
- this.dappClient.off("message", initialConnectionMessageHandler);
26143
- initialConnectionMessageHandler = void 0;
26144
- }
26145
26034
  this.removeStoredPendingSessionRequest();
26146
26035
  });
26147
26036
  });
@@ -26400,6 +26289,188 @@ var MetaMaskSDK = (() => {
26400
26289
  });
26401
26290
  }
26402
26291
  };
26292
+ _MWPTransport_instances = new WeakSet();
26293
+ onResumeHandler_fn = function(options) {
26294
+ return __async(this, null, function* () {
26295
+ var _a4, _b, _c, _d, _e, _f, _g;
26296
+ yield this.waitForWalletSessionIfNotCached();
26297
+ const sessionResponse = yield this.request({ method: "wallet_getSession" });
26298
+ if (sessionResponse.error) {
26299
+ throw new Error(sessionResponse.error.message);
26300
+ }
26301
+ let walletSession = sessionResponse.result;
26302
+ if (walletSession && options) {
26303
+ const currentScopes = Object.keys(
26304
+ (_a4 = walletSession == null ? void 0 : walletSession.sessionScopes) != null ? _a4 : {}
26305
+ );
26306
+ const proposedScopes = (_b = options == null ? void 0 : options.scopes) != null ? _b : [];
26307
+ const proposedCaipAccountIds = (_c = options == null ? void 0 : options.caipAccountIds) != null ? _c : [];
26308
+ const hasSameScopesAndAccounts = isSameScopesAndAccounts(
26309
+ currentScopes,
26310
+ proposedScopes,
26311
+ walletSession,
26312
+ proposedCaipAccountIds
26313
+ );
26314
+ if (options.forceRequest || !hasSameScopesAndAccounts) {
26315
+ const optionalScopes = addValidAccounts(
26316
+ getOptionalScopes((_d = options == null ? void 0 : options.scopes) != null ? _d : []),
26317
+ getValidAccounts((_e = options == null ? void 0 : options.caipAccountIds) != null ? _e : [])
26318
+ );
26319
+ const sessionRequest = {
26320
+ optionalScopes
26321
+ };
26322
+ const response = yield this.request({
26323
+ method: "wallet_createSession",
26324
+ params: sessionRequest
26325
+ });
26326
+ if (response.error) {
26327
+ throw new Error(response.error.message);
26328
+ }
26329
+ walletSession = response.result;
26330
+ }
26331
+ } else if (!walletSession) {
26332
+ const optionalScopes = addValidAccounts(
26333
+ getOptionalScopes((_f = options == null ? void 0 : options.scopes) != null ? _f : []),
26334
+ getValidAccounts((_g = options == null ? void 0 : options.caipAccountIds) != null ? _g : [])
26335
+ );
26336
+ const sessionRequest = {
26337
+ optionalScopes
26338
+ };
26339
+ const response = yield this.request({
26340
+ method: "wallet_createSession",
26341
+ params: sessionRequest
26342
+ });
26343
+ if (response.error) {
26344
+ throw new Error(response.error.message);
26345
+ }
26346
+ walletSession = response.result;
26347
+ }
26348
+ yield this.removeStoredPendingSessionRequest();
26349
+ this.notifyCallbacks({
26350
+ method: "wallet_sessionChanged",
26351
+ params: walletSession
26352
+ });
26353
+ });
26354
+ };
26355
+ resumeSession_fn = function(session, options) {
26356
+ return __async(this, null, function* () {
26357
+ var _a4;
26358
+ const isContinuingPriorAttempt = (yield this.getStoredPendingSessionRequest()) !== null;
26359
+ const resumeDeferred = createDeferredPromise();
26360
+ const runOnResumeHandler = () => __async(this, null, function* () {
26361
+ try {
26362
+ resumeDeferred.resolve(yield __privateMethod(this, _MWPTransport_instances, onResumeHandler_fn).call(this, options));
26363
+ } catch (err3) {
26364
+ resumeDeferred.reject(err3);
26365
+ }
26366
+ });
26367
+ if (this.dappClient.state === "CONNECTED") {
26368
+ runOnResumeHandler();
26369
+ } else {
26370
+ this.dappClient.once("connected", runOnResumeHandler);
26371
+ this.dappClient.resume((_a4 = session.id) != null ? _a4 : "").catch((err3) => resumeDeferred.reject(err3));
26372
+ }
26373
+ const timeoutDeferred = createDeferredPromise();
26374
+ const timeout = setTimeout(
26375
+ () => timeoutDeferred.reject(new TransportTimeoutError()),
26376
+ isContinuingPriorAttempt ? this.options.resumeTimeout : this.options.connectionTimeout
26377
+ );
26378
+ const cleanup = () => this.dappClient.off("connected", runOnResumeHandler);
26379
+ return Promise.race([
26380
+ resumeDeferred.promise,
26381
+ timeoutDeferred.promise
26382
+ ]).finally(() => {
26383
+ clearTimeout(timeout);
26384
+ cleanup();
26385
+ });
26386
+ });
26387
+ };
26388
+ startSession_fn = function(options) {
26389
+ return __async(this, null, function* () {
26390
+ var _a4, _b;
26391
+ const { dappClient } = this;
26392
+ const isContinuingPriorAttempt = (yield this.getStoredPendingSessionRequest()) !== null;
26393
+ const connDeferred = createDeferredPromise();
26394
+ const optionalScopes = addValidAccounts(
26395
+ getOptionalScopes((_a4 = options == null ? void 0 : options.scopes) != null ? _a4 : []),
26396
+ getValidAccounts((_b = options == null ? void 0 : options.caipAccountIds) != null ? _b : [])
26397
+ );
26398
+ const sessionRequest = {
26399
+ optionalScopes,
26400
+ sessionProperties: options == null ? void 0 : options.sessionProperties
26401
+ };
26402
+ const request2 = {
26403
+ jsonrpc: "2.0",
26404
+ id: String(getUniqueRequestId()),
26405
+ method: "wallet_createSession",
26406
+ params: sessionRequest
26407
+ };
26408
+ let handler;
26409
+ const removeHandler = () => {
26410
+ if (handler) {
26411
+ this.dappClient.off("message", handler);
26412
+ handler = void 0;
26413
+ }
26414
+ };
26415
+ handler = (message) => __async(this, null, function* () {
26416
+ if (typeof message !== "object" || message === null) {
26417
+ return;
26418
+ }
26419
+ if (!("data" in message)) {
26420
+ return;
26421
+ }
26422
+ const messagePayload = message.data;
26423
+ const isMatchingId = messagePayload.id === request2.id;
26424
+ const isMatchingMethod = messagePayload.method === "wallet_createSession" || messagePayload.method === "wallet_sessionChanged";
26425
+ if (!isMatchingId && !isMatchingMethod) {
26426
+ return;
26427
+ }
26428
+ const responseError = this.getResponseError(messagePayload);
26429
+ if (responseError) {
26430
+ connDeferred.reject(this.parseWalletError(responseError));
26431
+ return;
26432
+ }
26433
+ yield this.storeWalletSession(
26434
+ request2,
26435
+ messagePayload
26436
+ );
26437
+ yield this.removeStoredPendingSessionRequest();
26438
+ this.notifyCallbacks(messagePayload);
26439
+ connDeferred.resolve();
26440
+ });
26441
+ this.dappClient.on("message", handler);
26442
+ const platformType = getPlatformType();
26443
+ const isQRCodeFlow = [
26444
+ "web-desktop" /* DesktopWeb */,
26445
+ "nodejs" /* NonBrowser */
26446
+ ].includes(platformType);
26447
+ const initialPayload = {
26448
+ name: MULTICHAIN_PROVIDER_STREAM_NAME,
26449
+ data: request2
26450
+ };
26451
+ dappClient.connect({
26452
+ mode: "trusted",
26453
+ initialPayload: isQRCodeFlow ? void 0 : initialPayload
26454
+ }).then(() => __async(this, null, function* () {
26455
+ if (isQRCodeFlow) {
26456
+ return dappClient.sendRequest(initialPayload);
26457
+ }
26458
+ return void 0;
26459
+ })).catch((error) => connDeferred.reject(error));
26460
+ const timeoutDeferred = createDeferredPromise();
26461
+ const timeout = setTimeout(
26462
+ () => timeoutDeferred.reject(new TransportTimeoutError()),
26463
+ isContinuingPriorAttempt ? this.options.resumeTimeout : this.options.connectionTimeout
26464
+ );
26465
+ return Promise.race([
26466
+ connDeferred.promise,
26467
+ timeoutDeferred.promise
26468
+ ]).finally(() => {
26469
+ clearTimeout(timeout);
26470
+ removeHandler();
26471
+ });
26472
+ });
26473
+ };
26403
26474
  }
26404
26475
  });
26405
26476
 
@@ -37700,9 +37771,7 @@ ${new this._window.XMLSerializer().serializeToString(e3)}`;
37700
37771
  mount() {
37701
37772
  var _a4;
37702
37773
  const { options } = this;
37703
- const modal = document.createElement(
37704
- "mm-install-modal"
37705
- );
37774
+ const modal = document.createElement("mm-install-modal");
37706
37775
  modal.showInstallModal = options.showInstallModal;
37707
37776
  modal.addEventListener("close", (ev) => {
37708
37777
  const { detail } = ev;
@@ -37886,6 +37955,7 @@ ${new this._window.XMLSerializer().serializeToString(e3)}`;
37886
37955
  // src/index.browser.ts
37887
37956
  var index_browser_exports = {};
37888
37957
  __export(index_browser_exports, {
37958
+ EIP1193_PASSTHROUGH_METHODS: () => EIP1193_PASSTHROUGH_METHODS,
37889
37959
  EventEmitter: () => EventEmitter2,
37890
37960
  Modal: () => Modal,
37891
37961
  MultichainCore: () => MultichainCore,
@@ -37913,7 +37983,8 @@ ${new this._window.XMLSerializer().serializeToString(e3)}`;
37913
37983
  isEnabled: () => isEnabled,
37914
37984
  isMetamaskExtensionInstalled: () => isMetamaskExtensionInstalled,
37915
37985
  isRejectionError: () => isRejectionError,
37916
- isSecure: () => isSecure
37986
+ isSecure: () => isSecure,
37987
+ packageVersion: () => packageVersion
37917
37988
  });
37918
37989
 
37919
37990
  // src/polyfills/buffer-shim.ts
@@ -38531,6 +38602,7 @@ ${new this._window.XMLSerializer().serializeToString(e3)}`;
38531
38602
 
38532
38603
  // src/multichain/index.ts
38533
38604
  init_dist3();
38605
+ init_dist2();
38534
38606
 
38535
38607
  // src/config/index.ts
38536
38608
  var MWP_RELAY_URL = "wss://mm-sdk-relay.api.cx.metamask.io/connection/websocket";
@@ -38653,17 +38725,93 @@ ${new this._window.XMLSerializer().serializeToString(e3)}`;
38653
38725
  init_domain();
38654
38726
  init_utils4();
38655
38727
  init_analytics();
38728
+
38729
+ // src/multichain/rpc/invocationError.ts
38730
+ init_dist2();
38731
+ init_domain();
38732
+ var MAX_ERROR_CAUSE_DEPTH = 5;
38733
+ function getErrorObject(value) {
38734
+ if (typeof value === "object" && value !== null) {
38735
+ return value;
38736
+ }
38737
+ return void 0;
38738
+ }
38739
+ function getNumericCode(value) {
38740
+ return typeof value === "number" ? value : void 0;
38741
+ }
38742
+ function getNonEmptyMessage(value) {
38743
+ return typeof value === "string" && value.length > 0 ? value : void 0;
38744
+ }
38745
+ function getJsonData(value) {
38746
+ return value !== void 0 && isValidJson(value) ? value : void 0;
38747
+ }
38748
+ function getFirstNonEmptyMessage(values) {
38749
+ for (const value of values) {
38750
+ const message = getNonEmptyMessage(value);
38751
+ if (message !== void 0) {
38752
+ return message;
38753
+ }
38754
+ }
38755
+ return void 0;
38756
+ }
38757
+ function getErrorObjectChain(errorObject) {
38758
+ const chain2 = [];
38759
+ let currentObject = errorObject;
38760
+ for (let depth = 0; currentObject !== void 0 && depth < MAX_ERROR_CAUSE_DEPTH; depth += 1) {
38761
+ chain2.push(currentObject);
38762
+ currentObject = getErrorObject(currentObject.cause);
38763
+ }
38764
+ return chain2;
38765
+ }
38766
+ function getCodedErrorDetails(value) {
38767
+ const code = getNumericCode(value == null ? void 0 : value.code);
38768
+ if (code === void 0) {
38769
+ return void 0;
38770
+ }
38771
+ const message = getNonEmptyMessage(value == null ? void 0 : value.message);
38772
+ const data = getJsonData(value == null ? void 0 : value.data);
38773
+ return __spreadValues(__spreadValues({
38774
+ code
38775
+ }, message === void 0 ? {} : { message }), data === void 0 ? {} : { data });
38776
+ }
38777
+ function getInvocationErrorDetails(error) {
38778
+ var _a4, _b, _c, _d;
38779
+ const errorObject = getErrorObject(error);
38780
+ const errorObjectChain = getErrorObjectChain(errorObject);
38781
+ const primitiveMessage = getNonEmptyMessage(error);
38782
+ for (const [index, currentObject] of errorObjectChain.entries()) {
38783
+ const codedDetails = getCodedErrorDetails(currentObject);
38784
+ if (codedDetails) {
38785
+ const descendantObjects = errorObjectChain.slice(index + 1);
38786
+ const ancestorObjects = errorObjectChain.slice(0, index);
38787
+ const descendantMessage = getFirstNonEmptyMessage(
38788
+ descendantObjects.map((object4) => object4.message)
38789
+ );
38790
+ const ancestorMessage = getFirstNonEmptyMessage([
38791
+ primitiveMessage,
38792
+ ...ancestorObjects.map((object4) => object4.message)
38793
+ ]);
38794
+ const reason2 = (_c = (_b = (_a4 = codedDetails.message) != null ? _a4 : descendantMessage) != null ? _b : ancestorMessage) != null ? _c : "Unknown error";
38795
+ return __spreadValues(__spreadValues({
38796
+ reason: reason2,
38797
+ rpcCode: codedDetails.code
38798
+ }, codedDetails.message === void 0 ? {} : { rpcMessage: codedDetails.message }), codedDetails.data === void 0 ? {} : { rpcData: codedDetails.data });
38799
+ }
38800
+ }
38801
+ const reason = (_d = primitiveMessage != null ? primitiveMessage : getFirstNonEmptyMessage(errorObjectChain.map((object4) => object4.message))) != null ? _d : "Unknown error";
38802
+ return {
38803
+ reason
38804
+ };
38805
+ }
38656
38806
  function toRPCInvokeMethodErr(error) {
38657
- var _a4;
38658
38807
  if (error instanceof RPCInvokeMethodErr) {
38659
38808
  return error;
38660
38809
  }
38661
- const castError = error;
38662
- return new RPCInvokeMethodErr(
38663
- (_a4 = castError.message) != null ? _a4 : "Unknown error",
38664
- castError.code
38665
- );
38810
+ const { reason, rpcCode, rpcMessage, rpcData } = getInvocationErrorDetails(error);
38811
+ return new RPCInvokeMethodErr(reason, rpcCode, rpcMessage, rpcData);
38666
38812
  }
38813
+
38814
+ // src/multichain/rpc/requestRouter.ts
38667
38815
  var _RequestRouter_instances, withAnalyticsTracking_fn, trackWalletActionRequested_fn, trackWalletActionSucceeded_fn, trackWalletActionFailed_fn, trackWalletActionRejected_fn;
38668
38816
  var RequestRouter = class {
38669
38817
  constructor(transport, rpcClient, config, transportType) {
@@ -38683,6 +38831,9 @@ ${new this._window.XMLSerializer().serializeToString(e3)}`;
38683
38831
  invokeMethod(options) {
38684
38832
  return __async(this, null, function* () {
38685
38833
  const { method } = options.request;
38834
+ if (EIP1193_PASSTHROUGH_METHODS.has(method)) {
38835
+ return this.handleWithEip1193Passthrough(options);
38836
+ }
38686
38837
  if (RPC_HANDLED_METHODS.has(method)) {
38687
38838
  return this.handleWithRpcNode(options);
38688
38839
  }
@@ -38692,6 +38843,29 @@ ${new this._window.XMLSerializer().serializeToString(e3)}`;
38692
38843
  return this.handleWithWallet(options);
38693
38844
  });
38694
38845
  }
38846
+ /**
38847
+ * Forwards EIP-1193 / legacy provider methods (e.g. `wallet_addEthereumChain`,
38848
+ * `wallet_switchEthereumChain`, `eth_accounts`) directly to the underlying
38849
+ * transport's `sendEip1193Message`, bypassing the multichain
38850
+ * `wallet_invokeMethod` envelope. These methods are wallet-side concerns the
38851
+ * Multichain API does not model, so we forward the raw `{ method, params }`
38852
+ * payload and return the wallet's full JSON-RPC response envelope unchanged.
38853
+ *
38854
+ * Analytics tracking is intentionally skipped here: ecosystem clients
38855
+ * (e.g. `connect-evm`) emit their own `wallet_action_*` events around these
38856
+ * passthrough calls, and adding router-level tracking would double-count.
38857
+ *
38858
+ * @param options
38859
+ */
38860
+ handleWithEip1193Passthrough(options) {
38861
+ return __async(this, null, function* () {
38862
+ const response = yield this.transport.sendEip1193Message({
38863
+ method: options.request.method,
38864
+ params: options.request.params
38865
+ });
38866
+ return response.result;
38867
+ });
38868
+ }
38695
38869
  /**
38696
38870
  * Forwards the request directly to the wallet via the transport.
38697
38871
  *
@@ -38724,12 +38898,7 @@ ${new this._window.XMLSerializer().serializeToString(e3)}`;
38724
38898
  }
38725
38899
  const response = yield request2;
38726
38900
  if (response.error) {
38727
- const { error } = response;
38728
- throw new RPCInvokeMethodErr(
38729
- `RPC Request failed with code ${error.code}: ${error.message}`,
38730
- error.code,
38731
- error.message
38732
- );
38901
+ throw toRPCInvokeMethodErr(response.error);
38733
38902
  }
38734
38903
  return response.result;
38735
38904
  }));
@@ -38783,13 +38952,15 @@ ${new this._window.XMLSerializer().serializeToString(e3)}`;
38783
38952
  yield __privateMethod(this, _RequestRouter_instances, trackWalletActionSucceeded_fn).call(this, options);
38784
38953
  return result;
38785
38954
  } catch (error) {
38786
- const isRejection = isRejectionError(error);
38955
+ const normalizedError = toRPCInvokeMethodErr(error);
38956
+ const analyticsError = normalizedError.rpcCode === void 0 ? error : normalizedError;
38957
+ const isRejection = isRejectionError(analyticsError);
38787
38958
  if (isRejection) {
38788
38959
  yield __privateMethod(this, _RequestRouter_instances, trackWalletActionRejected_fn).call(this, options);
38789
38960
  } else {
38790
- yield __privateMethod(this, _RequestRouter_instances, trackWalletActionFailed_fn).call(this, options, error);
38961
+ yield __privateMethod(this, _RequestRouter_instances, trackWalletActionFailed_fn).call(this, options, analyticsError);
38791
38962
  }
38792
- throw toRPCInvokeMethodErr(error);
38963
+ throw normalizedError;
38793
38964
  }
38794
38965
  });
38795
38966
  };
@@ -38841,9 +39012,10 @@ ${new this._window.XMLSerializer().serializeToString(e3)}`;
38841
39012
 
38842
39013
  // src/multichain/transports/default/index.ts
38843
39014
  init_dist3();
39015
+ init_dist2();
38844
39016
  init_utils4();
38845
39017
  var DEFAULT_REQUEST_TIMEOUT2 = 60 * 1e3;
38846
- var _notificationCallbacks, _transport, _defaultRequestOptions, _pendingRequests, _handleResponseListener, _handleNotificationListener, _DefaultTransport_instances, notifyCallbacks_fn, isMetamaskProviderEvent_fn, handleResponse_fn, handleNotification_fn, setupMessageListener_fn, init_fn;
39018
+ var _notificationCallbacks, _transport, _defaultRequestOptions, _pendingRequests, _handleResponseListener, _handleNotificationListener, _DefaultTransport_instances, notifyCallbacks_fn, parseWalletError_fn, isMetamaskProviderEvent_fn, handleResponse_fn, handleNotification_fn, setupMessageListener_fn, init_fn;
38847
39019
  var DefaultTransport = class {
38848
39020
  constructor() {
38849
39021
  __privateAdd(this, _DefaultTransport_instances);
@@ -38979,7 +39151,11 @@ ${new this._window.XMLSerializer().serializeToString(e3)}`;
38979
39151
  }
38980
39152
  request(_0) {
38981
39153
  return __async(this, arguments, function* (request2, options = __privateGet(this, _defaultRequestOptions)) {
38982
- return __privateGet(this, _transport).request(request2, options);
39154
+ const response = yield __privateGet(this, _transport).request(request2, options);
39155
+ if (response.error) {
39156
+ throw __privateMethod(this, _DefaultTransport_instances, parseWalletError_fn).call(this, response.error);
39157
+ }
39158
+ return response;
38983
39159
  });
38984
39160
  }
38985
39161
  onNotification(callback) {
@@ -39023,6 +39199,20 @@ ${new this._window.XMLSerializer().serializeToString(e3)}`;
39023
39199
  }
39024
39200
  }
39025
39201
  };
39202
+ parseWalletError_fn = function(errorPayload) {
39203
+ const errorData = errorPayload;
39204
+ const error = new Error(
39205
+ typeof errorData.message === "string" ? errorData.message : "Request failed"
39206
+ );
39207
+ if (typeof errorData.code === "number") {
39208
+ error.code = errorData.code;
39209
+ }
39210
+ const { data } = errorData;
39211
+ if (isValidJson(data)) {
39212
+ error.data = data;
39213
+ }
39214
+ return error;
39215
+ };
39026
39216
  isMetamaskProviderEvent_fn = function(event) {
39027
39217
  var _a4, _b;
39028
39218
  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
@@ -39045,13 +39235,7 @@ ${new this._window.XMLSerializer().serializeToString(e3)}`;
39045
39235
  __privateGet(this, _pendingRequests).delete(responseId);
39046
39236
  const response = responseData;
39047
39237
  if ("error" in response && response.error) {
39048
- const error = new Error(
39049
- response.error.message || "Request failed"
39050
- );
39051
- if (typeof response.error.code === "number") {
39052
- error.code = response.error.code;
39053
- }
39054
- pendingRequest.reject(error);
39238
+ pendingRequest.reject(__privateMethod(this, _DefaultTransport_instances, parseWalletError_fn).call(this, response.error));
39055
39239
  } else {
39056
39240
  pendingRequest.resolve(response);
39057
39241
  }
@@ -39089,22 +39273,21 @@ ${new this._window.XMLSerializer().serializeToString(e3)}`;
39089
39273
  // src/multichain/transports/multichainApiClientWrapper/index.ts
39090
39274
  init_dist4();
39091
39275
  init_utils4();
39092
- var _notificationCallbacks2, _MultichainApiClientWrapperTransport_instances, walletCreateSession_fn, walletGetSession_fn, walletRevokeSession_fn, walletInvokeMethod_fn;
39276
+ var _notificationCallbacks2, _getTransport, _MultichainApiClientWrapperTransport_instances, walletCreateSession_fn, walletGetSession_fn, walletRevokeSession_fn, walletInvokeMethod_fn;
39093
39277
  var MultichainApiClientWrapperTransport = class {
39094
- constructor(metamaskConnectMultichain) {
39278
+ constructor(metamaskConnectMultichain, getTransport) {
39095
39279
  this.metamaskConnectMultichain = metamaskConnectMultichain;
39096
39280
  __privateAdd(this, _MultichainApiClientWrapperTransport_instances);
39097
39281
  __privateAdd(this, _notificationCallbacks2, /* @__PURE__ */ new Set());
39282
+ __privateAdd(this, _getTransport);
39283
+ __privateSet(this, _getTransport, getTransport);
39098
39284
  }
39099
39285
  isTransportDefined() {
39100
- try {
39101
- return Boolean(this.metamaskConnectMultichain.transport);
39102
- } catch (_error) {
39103
- return false;
39104
- }
39286
+ return __privateGet(this, _getTransport).call(this) !== void 0;
39105
39287
  }
39106
39288
  isTransportConnected() {
39107
- return this.isTransportDefined() && this.metamaskConnectMultichain.transport.isConnected();
39289
+ var _a4, _b;
39290
+ return (_b = (_a4 = __privateGet(this, _getTransport).call(this)) == null ? void 0 : _a4.isConnected()) != null ? _b : false;
39108
39291
  }
39109
39292
  clearNotificationCallbacks() {
39110
39293
  __privateGet(this, _notificationCallbacks2).clear();
@@ -39120,10 +39303,11 @@ ${new this._window.XMLSerializer().serializeToString(e3)}`;
39120
39303
  this.notificationListener = void 0;
39121
39304
  }
39122
39305
  setupTransportNotificationListener() {
39123
- if (!this.isTransportDefined() || this.notificationListener) {
39306
+ const transport = __privateGet(this, _getTransport).call(this);
39307
+ if (!transport || this.notificationListener) {
39124
39308
  return;
39125
39309
  }
39126
- this.notificationListener = this.metamaskConnectMultichain.transport.onNotification(
39310
+ this.notificationListener = transport.onNotification(
39127
39311
  this.notifyCallbacks.bind(this)
39128
39312
  );
39129
39313
  }
@@ -39173,6 +39357,7 @@ ${new this._window.XMLSerializer().serializeToString(e3)}`;
39173
39357
  }
39174
39358
  };
39175
39359
  _notificationCallbacks2 = new WeakMap();
39360
+ _getTransport = new WeakMap();
39176
39361
  _MultichainApiClientWrapperTransport_instances = new WeakSet();
39177
39362
  walletCreateSession_fn = function(request2) {
39178
39363
  return __async(this, null, function* () {
@@ -39196,14 +39381,19 @@ ${new this._window.XMLSerializer().serializeToString(e3)}`;
39196
39381
  accounts,
39197
39382
  createSessionParams.sessionProperties
39198
39383
  );
39199
- return this.metamaskConnectMultichain.transport.request({
39384
+ const transport = __privateGet(this, _getTransport).call(this);
39385
+ if (!transport) {
39386
+ throw new Error("Transport not initialized after connect");
39387
+ }
39388
+ return transport.request({
39200
39389
  method: "wallet_getSession"
39201
39390
  });
39202
39391
  });
39203
39392
  };
39204
39393
  walletGetSession_fn = function(request2) {
39205
39394
  return __async(this, null, function* () {
39206
- if (!this.isTransportConnected()) {
39395
+ const transport = __privateGet(this, _getTransport).call(this);
39396
+ if (!(transport == null ? void 0 : transport.isConnected())) {
39207
39397
  return {
39208
39398
  jsonrpc: "2.0",
39209
39399
  id: request2.id,
@@ -39212,7 +39402,7 @@ ${new this._window.XMLSerializer().serializeToString(e3)}`;
39212
39402
  }
39213
39403
  };
39214
39404
  }
39215
- return this.metamaskConnectMultichain.transport.request({
39405
+ return transport.request({
39216
39406
  method: "wallet_getSession"
39217
39407
  });
39218
39408
  });
@@ -39290,7 +39480,7 @@ ${new this._window.XMLSerializer().serializeToString(e3)}`;
39290
39480
  analytics.enable();
39291
39481
  });
39292
39482
  }
39293
- 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;
39483
+ 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;
39294
39484
  var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends MultichainCore {
39295
39485
  constructor(options) {
39296
39486
  var _a4, _b, _c, _d;
@@ -39303,9 +39493,7 @@ ${new this._window.XMLSerializer().serializeToString(e3)}`;
39303
39493
  }),
39304
39494
  analytics: normalizeAnalyticsOptions(options.analytics),
39305
39495
  versions: __spreadValues({
39306
- // typeof guard needed: Metro (React Native) bundles TS source directly,
39307
- // bypassing the tsup build that substitutes __PACKAGE_VERSION__.
39308
- "connect-multichain": false ? "unknown" : "0.15.0"
39496
+ "connect-multichain": getVersion()
39309
39497
  }, (_d = options.versions) != null ? _d : {})
39310
39498
  });
39311
39499
  super(allOptions);
@@ -39321,7 +39509,8 @@ ${new this._window.XMLSerializer().serializeToString(e3)}`;
39321
39509
  __privateAdd(this, _anonId);
39322
39510
  __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}`);
39323
39511
  __privateSet(this, _providerTransportWrapper, new MultichainApiClientWrapperTransport(
39324
- this
39512
+ this,
39513
+ () => __privateGet(this, _transport2)
39325
39514
  ));
39326
39515
  __privateSet(this, _provider, getMultichainClient({
39327
39516
  transport: __privateGet(this, _providerTransportWrapper)
@@ -39340,12 +39529,6 @@ ${new this._window.XMLSerializer().serializeToString(e3)}`;
39340
39529
  get provider() {
39341
39530
  return __privateGet(this, _provider);
39342
39531
  }
39343
- get transport() {
39344
- if (!__privateGet(this, _transport2)) {
39345
- throw new Error("Transport not initialized, establish connection first");
39346
- }
39347
- return __privateGet(this, _transport2);
39348
- }
39349
39532
  get dappClient() {
39350
39533
  if (!__privateGet(this, _dappClient)) {
39351
39534
  throw new Error("DappClient not initialized, establish connection first");
@@ -39359,6 +39542,9 @@ ${new this._window.XMLSerializer().serializeToString(e3)}`;
39359
39542
  get storage() {
39360
39543
  return this.options.storage;
39361
39544
  }
39545
+ get version() {
39546
+ return getVersion();
39547
+ }
39362
39548
  // Creates a singleton instance of MetaMaskConnectMultichain.
39363
39549
  // If the singleton already exists, it merges the incoming options with the
39364
39550
  // existing singleton options for the following keys: `api.supportedNetworks`,
@@ -39373,6 +39559,11 @@ ${new this._window.XMLSerializer().serializeToString(e3)}`;
39373
39559
  const existing = globalObject[SINGLETON_KEY];
39374
39560
  if (existing) {
39375
39561
  const instance2 = yield existing;
39562
+ if (instance2.version !== getVersion()) {
39563
+ console.warn(
39564
+ `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.`
39565
+ );
39566
+ }
39376
39567
  instance2.mergeOptions(options);
39377
39568
  if (instance2 instanceof _MetaMaskConnectMultichain) {
39378
39569
  yield __privateMethod(_a4 = instance2, _MetaMaskConnectMultichain_instances, setupAnalytics_fn).call(_a4);
@@ -39396,12 +39587,12 @@ ${new this._window.XMLSerializer().serializeToString(e3)}`;
39396
39587
  }
39397
39588
  yield __privateMethod(_a5 = instance2, _MetaMaskConnectMultichain_instances, init_fn2).call(_a5);
39398
39589
  return instance2;
39399
- }))();
39400
- globalObject[SINGLETON_KEY] = instancePromise;
39401
- instancePromise.catch((error) => {
39590
+ }))().catch((error) => {
39402
39591
  globalObject[SINGLETON_KEY] = void 0;
39403
39592
  console.error("Error initializing MetaMaskConnectMultichain", error);
39593
+ throw error;
39404
39594
  });
39595
+ globalObject[SINGLETON_KEY] = instancePromise;
39405
39596
  return instancePromise;
39406
39597
  });
39407
39598
  }
@@ -39461,9 +39652,9 @@ ${new this._window.XMLSerializer().serializeToString(e3)}`;
39461
39652
  forceRequest
39462
39653
  }).then(() => __async(this, null, function* () {
39463
39654
  if (__privateGet(this, _transportType) === "mwp" /* MWP */) {
39464
- return this.storage.setTransport("mwp" /* MWP */);
39655
+ return this.storage.setTransportType("mwp" /* MWP */);
39465
39656
  }
39466
- return this.storage.setTransport("browser" /* Browser */);
39657
+ return this.storage.setTransportType("browser" /* Browser */);
39467
39658
  })), scopes, transportType);
39468
39659
  }
39469
39660
  if (platformType === "in-app-browser" /* MetaMaskMobileWebview */) {
@@ -39492,11 +39683,6 @@ ${new this._window.XMLSerializer().serializeToString(e3)}`;
39492
39683
  return __privateMethod(this, _MetaMaskConnectMultichain_instances, handleConnection_fn).call(this, __privateMethod(this, _MetaMaskConnectMultichain_instances, showInstallModal_fn).call(this, shouldShowInstallModal, mergedScopes, mergedCaipAccountIds, nonEmptySessionProperties), scopes, transportType);
39493
39684
  });
39494
39685
  }
39495
- emit(event, args) {
39496
- var _a4, _b;
39497
- (_b = (_a4 = this.options.transport) == null ? void 0 : _a4.onNotification) == null ? void 0 : _b.call(_a4, { method: event, params: args });
39498
- super.emit(event, args);
39499
- }
39500
39686
  disconnect() {
39501
39687
  return __async(this, arguments, function* (scopes = []) {
39502
39688
  var _a4, _b, _c;
@@ -39506,7 +39692,7 @@ ${new this._window.XMLSerializer().serializeToString(e3)}`;
39506
39692
  );
39507
39693
  yield (_a4 = __privateGet(this, _transport2)) == null ? void 0 : _a4.disconnect(scopes);
39508
39694
  if (remainingScopes.length === 0) {
39509
- yield this.storage.removeTransport();
39695
+ yield this.storage.removeTransportType();
39510
39696
  if (__privateGet(this, _transportType) !== "browser" /* Browser */) {
39511
39697
  yield (_b = __privateGet(this, _listener)) == null ? void 0 : _b.call(this);
39512
39698
  (_c = __privateGet(this, _beforeUnloadListener)) == null ? void 0 : _c.call(this);
@@ -39524,7 +39710,8 @@ ${new this._window.XMLSerializer().serializeToString(e3)}`;
39524
39710
  invokeMethod(request2) {
39525
39711
  return __async(this, null, function* () {
39526
39712
  var _a4;
39527
- const { transport, options } = this;
39713
+ const transport = __privateMethod(this, _MetaMaskConnectMultichain_instances, transportOrThrow_fn).call(this);
39714
+ const { options } = this;
39528
39715
  const rpcClient = new RpcClient(options, __privateGet(this, _sdkInfo));
39529
39716
  const requestRouter = new RequestRouter(
39530
39717
  transport,
@@ -39543,7 +39730,7 @@ ${new this._window.XMLSerializer().serializeToString(e3)}`;
39543
39730
  const shouldOpenDeeplink = secure && !showInstallModal;
39544
39731
  if (shouldOpenDeeplink) {
39545
39732
  setTimeout(() => __async(this, null, function* () {
39546
- const session = yield this.transport.getActiveSession();
39733
+ const session = yield __privateMethod(this, _MetaMaskConnectMultichain_instances, transportOrThrow_fn).call(this).getActiveSession();
39547
39734
  if (!session) {
39548
39735
  throw new Error("No active session found");
39549
39736
  }
@@ -39567,10 +39754,13 @@ ${new this._window.XMLSerializer().serializeToString(e3)}`;
39567
39754
  this.emit("wallet_sessionChanged", emptySession);
39568
39755
  return;
39569
39756
  }
39570
- const response = yield this.transport.request({
39757
+ const response = yield __privateGet(this, _transport2).request({
39571
39758
  method: "wallet_getSession"
39572
39759
  });
39573
- this.emit("wallet_sessionChanged", (_b = response.result) != null ? _b : emptySession);
39760
+ this.emit(
39761
+ "wallet_sessionChanged",
39762
+ (_b = response.result) != null ? _b : emptySession
39763
+ );
39574
39764
  });
39575
39765
  }
39576
39766
  };
@@ -39582,8 +39772,14 @@ ${new this._window.XMLSerializer().serializeToString(e3)}`;
39582
39772
  _transportType = new WeakMap();
39583
39773
  _listener = new WeakMap();
39584
39774
  _anonId = new WeakMap();
39585
- _sdkInfo = new WeakMap();
39586
39775
  _MetaMaskConnectMultichain_instances = new WeakSet();
39776
+ transportOrThrow_fn = function() {
39777
+ if (!__privateGet(this, _transport2)) {
39778
+ throw new Error("Transport not initialized, establish connection first");
39779
+ }
39780
+ return __privateGet(this, _transport2);
39781
+ };
39782
+ _sdkInfo = new WeakMap();
39587
39783
  setupAnalytics_fn = function() {
39588
39784
  return __async(this, null, function* () {
39589
39785
  yield setupAnalyticsGlobals(this.options, this.storage, (anonId) => {
@@ -39609,7 +39805,7 @@ ${new this._window.XMLSerializer().serializeToString(e3)}`;
39609
39805
  };
39610
39806
  getStoredTransport_fn = function() {
39611
39807
  return __async(this, null, function* () {
39612
- const transportType = yield this.storage.getTransport();
39808
+ const transportType = yield this.storage.getTransportType();
39613
39809
  const hasExtensionInstalled = yield hasExtension();
39614
39810
  if (transportType) {
39615
39811
  if (transportType === "browser" /* Browser */) {
@@ -39637,7 +39833,7 @@ ${new this._window.XMLSerializer().serializeToString(e3)}`;
39637
39833
  ));
39638
39834
  return apiTransport;
39639
39835
  }
39640
- yield this.storage.removeTransport();
39836
+ yield this.storage.removeTransportType();
39641
39837
  }
39642
39838
  return void 0;
39643
39839
  });
@@ -39647,15 +39843,15 @@ ${new this._window.XMLSerializer().serializeToString(e3)}`;
39647
39843
  var _a4;
39648
39844
  const transport = yield __privateMethod(this, _MetaMaskConnectMultichain_instances, getStoredTransport_fn).call(this);
39649
39845
  if (transport) {
39650
- if (!this.transport.isConnected()) {
39846
+ if (!transport.isConnected()) {
39651
39847
  this.status = "connecting";
39652
- yield this.transport.connect();
39848
+ yield transport.connect();
39653
39849
  }
39654
39850
  this.status = "connected";
39655
39851
  if (__privateGet(this, _transportType) === "mwp" /* MWP */) {
39656
- yield this.storage.setTransport("mwp" /* MWP */);
39852
+ yield this.storage.setTransportType("mwp" /* MWP */);
39657
39853
  } else {
39658
- yield this.storage.setTransport("browser" /* Browser */);
39854
+ yield this.storage.setTransportType("browser" /* Browser */);
39659
39855
  }
39660
39856
  } else {
39661
39857
  this.status = "loaded";
@@ -39664,7 +39860,7 @@ ${new this._window.XMLSerializer().serializeToString(e3)}`;
39664
39860
  if (hasExtensionInstalled && preferExtension) {
39665
39861
  yield __privateMethod(this, _MetaMaskConnectMultichain_instances, setupDefaultTransport_fn).call(this, { persist: false });
39666
39862
  try {
39667
- yield this.transport.init();
39863
+ yield __privateMethod(this, _MetaMaskConnectMultichain_instances, transportOrThrow_fn).call(this).init();
39668
39864
  } catch (error) {
39669
39865
  console.error("Passive init failed:", error);
39670
39866
  }
@@ -39688,7 +39884,7 @@ ${new this._window.XMLSerializer().serializeToString(e3)}`;
39688
39884
  yield __privateMethod(this, _MetaMaskConnectMultichain_instances, setupAnalytics_fn).call(this);
39689
39885
  yield __privateMethod(this, _MetaMaskConnectMultichain_instances, setupTransport_fn).call(this);
39690
39886
  } catch (error) {
39691
- yield this.storage.removeTransport();
39887
+ yield this.storage.removeTransportType();
39692
39888
  this.status = "pending";
39693
39889
  logger2("MetaMaskSDK error during initialization", error);
39694
39890
  }
@@ -39734,17 +39930,17 @@ ${new this._window.XMLSerializer().serializeToString(e3)}`;
39734
39930
  __privateSet(this, _transport2, apiTransport);
39735
39931
  __privateSet(this, _transportType, "mwp" /* MWP */);
39736
39932
  __privateGet(this, _providerTransportWrapper).setupTransportNotificationListener();
39737
- __privateSet(this, _listener, this.transport.onNotification(
39933
+ __privateSet(this, _listener, apiTransport.onNotification(
39738
39934
  __privateMethod(this, _MetaMaskConnectMultichain_instances, onTransportNotification_fn).bind(this)
39739
39935
  ));
39740
- yield this.storage.setTransport("mwp" /* MWP */);
39936
+ yield this.storage.setTransportType("mwp" /* MWP */);
39741
39937
  });
39742
39938
  };
39743
39939
  onBeforeUnload_fn = function() {
39744
39940
  return __async(this, null, function* () {
39745
39941
  var _a4;
39746
39942
  if ((_a4 = this.options.ui.factory.modal) == null ? void 0 : _a4.isMounted) {
39747
- yield this.storage.removeTransport();
39943
+ yield this.storage.removeTransportType();
39748
39944
  }
39749
39945
  });
39750
39946
  };
@@ -39761,70 +39957,65 @@ ${new this._window.XMLSerializer().serializeToString(e3)}`;
39761
39957
  };
39762
39958
  renderInstallModalAsync_fn = function(desktopPreferred, scopes, caipAccountIds, sessionProperties) {
39763
39959
  return __async(this, null, function* () {
39764
- return new Promise((resolve, reject) => {
39765
- this.options.ui.factory.renderInstallModal(
39766
- desktopPreferred,
39767
- () => __async(this, null, function* () {
39768
- if (this.dappClient.state === "CONNECTED" || this.dappClient.state === "CONNECTING") {
39769
- yield this.dappClient.disconnect();
39770
- }
39771
- return new Promise((_resolve) => {
39772
- this.dappClient.on(
39773
- "session_request",
39774
- (sessionRequest) => {
39775
- _resolve({
39776
- sessionRequest,
39777
- metadata: __privateMethod(this, _MetaMaskConnectMultichain_instances, buildConnectionMetadata_fn).call(this)
39778
- });
39779
- }
39780
- );
39781
- (() => __async(this, null, function* () {
39782
- var _a4;
39783
- try {
39784
- yield this.transport.connect({
39785
- scopes,
39786
- caipAccountIds,
39787
- sessionProperties
39788
- });
39789
- yield this.options.ui.factory.unload();
39790
- (_a4 = this.options.ui.factory.modal) == null ? void 0 : _a4.unmount();
39791
- this.status = "connected";
39792
- yield this.storage.setTransport("mwp" /* MWP */);
39793
- } catch (error) {
39794
- const { ProtocolError, ErrorCode: ErrorCode4 } = yield Promise.resolve().then(() => __toESM(require_dist()));
39795
- if (error instanceof ProtocolError) {
39796
- if (error.code !== ErrorCode4.REQUEST_EXPIRED) {
39797
- this.status = "disconnected";
39798
- yield this.options.ui.factory.unload(error);
39799
- reject(error);
39800
- }
39801
- } else {
39802
- this.status = "disconnected";
39803
- const normalizedError = error instanceof Error ? error : new Error(String(error));
39804
- yield this.options.ui.factory.unload(normalizedError);
39805
- reject(normalizedError);
39806
- }
39807
- }
39808
- }))().catch(() => {
39809
- });
39960
+ const completion = createDeferredPromise();
39961
+ const createConnectionRequest = () => __async(this, null, function* () {
39962
+ if (this.dappClient.state === "CONNECTED" || this.dappClient.state === "CONNECTING") {
39963
+ yield this.dappClient.disconnect();
39964
+ }
39965
+ const sessionRequestDeferred = createDeferredPromise();
39966
+ this.dappClient.on(
39967
+ "session_request",
39968
+ (sessionRequest) => {
39969
+ sessionRequestDeferred.resolve({
39970
+ sessionRequest,
39971
+ metadata: __privateMethod(this, _MetaMaskConnectMultichain_instances, buildConnectionMetadata_fn).call(this)
39810
39972
  });
39811
- }),
39812
- (error) => __async(this, null, function* () {
39813
- if (error) {
39814
- yield this.storage.removeTransport();
39815
- reject(error);
39816
- } else {
39817
- yield this.storage.setTransport("mwp" /* MWP */);
39818
- resolve();
39973
+ }
39974
+ );
39975
+ __privateMethod(this, _MetaMaskConnectMultichain_instances, transportOrThrow_fn).call(this).connect({ scopes, caipAccountIds, sessionProperties }).then(() => __async(this, null, function* () {
39976
+ var _a4;
39977
+ yield this.options.ui.factory.unload();
39978
+ (_a4 = this.options.ui.factory.modal) == null ? void 0 : _a4.unmount();
39979
+ this.status = "connected";
39980
+ yield this.storage.setTransportType("mwp" /* MWP */);
39981
+ })).catch((error) => __async(this, null, function* () {
39982
+ const { ProtocolError, ErrorCode: ErrorCode4 } = yield Promise.resolve().then(() => __toESM(require_dist()));
39983
+ if (error instanceof ProtocolError) {
39984
+ if (error.code !== ErrorCode4.REQUEST_EXPIRED) {
39985
+ this.status = "disconnected";
39986
+ yield this.options.ui.factory.unload(error);
39987
+ completion.reject(error);
39819
39988
  }
39820
- }),
39821
- (uri) => {
39822
- this.emit("display_uri", uri);
39989
+ } else {
39990
+ this.status = "disconnected";
39991
+ const normalizedError = error instanceof Error ? error : new Error(String(error));
39992
+ yield this.options.ui.factory.unload(normalizedError);
39993
+ completion.reject(normalizedError);
39823
39994
  }
39824
- ).catch((error) => {
39825
- reject(error instanceof Error ? error : new Error(String(error)));
39826
- });
39995
+ }));
39996
+ return sessionRequestDeferred.promise;
39827
39997
  });
39998
+ this.options.ui.factory.renderInstallModal(
39999
+ desktopPreferred,
40000
+ createConnectionRequest,
40001
+ (error) => __async(this, null, function* () {
40002
+ if (error) {
40003
+ yield this.storage.removeTransportType();
40004
+ completion.reject(error);
40005
+ } else {
40006
+ yield this.storage.setTransportType("mwp" /* MWP */);
40007
+ completion.resolve();
40008
+ }
40009
+ }),
40010
+ (uri) => {
40011
+ this.emit("display_uri", uri);
40012
+ }
40013
+ ).catch((error) => {
40014
+ completion.reject(
40015
+ error instanceof Error ? error : new Error(String(error))
40016
+ );
40017
+ });
40018
+ return completion.promise;
39828
40019
  });
39829
40020
  };
39830
40021
  showInstallModal_fn = function(desktopPreferred, scopes, caipAccountIds, sessionProperties) {
@@ -39840,39 +40031,37 @@ ${new this._window.XMLSerializer().serializeToString(e3)}`;
39840
40031
  };
39841
40032
  headlessConnect_fn = function(scopes, caipAccountIds, sessionProperties) {
39842
40033
  return __async(this, null, function* () {
39843
- return new Promise((resolve, reject) => {
39844
- if (this.dappClient.state === "CONNECTED" || this.dappClient.state === "CONNECTING") {
39845
- this.dappClient.disconnect().catch(() => {
39846
- });
40034
+ if (this.dappClient.state === "CONNECTED" || this.dappClient.state === "CONNECTING") {
40035
+ yield this.dappClient.disconnect().catch(() => void 0);
40036
+ }
40037
+ const onSessionRequest = (sessionRequest) => {
40038
+ const connectionRequest = {
40039
+ sessionRequest,
40040
+ metadata: __privateMethod(this, _MetaMaskConnectMultichain_instances, buildConnectionMetadata_fn).call(this)
40041
+ };
40042
+ const deeplink = this.options.ui.factory.createConnectionDeeplink(connectionRequest);
40043
+ this.emit("display_uri", deeplink);
40044
+ };
40045
+ this.dappClient.on("session_request", onSessionRequest);
40046
+ try {
40047
+ yield __privateMethod(this, _MetaMaskConnectMultichain_instances, transportOrThrow_fn).call(this).connect({
40048
+ scopes,
40049
+ caipAccountIds,
40050
+ sessionProperties
40051
+ });
40052
+ this.status = "connected";
40053
+ yield this.storage.setTransportType("mwp" /* MWP */);
40054
+ } catch (error) {
40055
+ const { ProtocolError } = yield Promise.resolve().then(() => __toESM(require_dist()));
40056
+ this.status = "disconnected";
40057
+ yield this.storage.removeTransportType();
40058
+ if (error instanceof ProtocolError || error instanceof Error) {
40059
+ throw error;
39847
40060
  }
39848
- this.dappClient.on(
39849
- "session_request",
39850
- (sessionRequest) => {
39851
- const connectionRequest = {
39852
- sessionRequest,
39853
- metadata: __privateMethod(this, _MetaMaskConnectMultichain_instances, buildConnectionMetadata_fn).call(this)
39854
- };
39855
- const deeplink = this.options.ui.factory.createConnectionDeeplink(connectionRequest);
39856
- this.emit("display_uri", deeplink);
39857
- }
39858
- );
39859
- this.transport.connect({ scopes, caipAccountIds, sessionProperties }).then(() => __async(this, null, function* () {
39860
- this.status = "connected";
39861
- yield this.storage.setTransport("mwp" /* MWP */);
39862
- resolve();
39863
- })).catch((error) => __async(this, null, function* () {
39864
- const { ProtocolError } = yield Promise.resolve().then(() => __toESM(require_dist()));
39865
- if (error instanceof ProtocolError) {
39866
- this.status = "disconnected";
39867
- yield this.storage.removeTransport();
39868
- reject(error);
39869
- } else {
39870
- this.status = "disconnected";
39871
- yield this.storage.removeTransport();
39872
- reject(error instanceof Error ? error : new Error(String(error)));
39873
- }
39874
- }));
39875
- });
40061
+ throw new Error(String(error));
40062
+ } finally {
40063
+ this.dappClient.off("session_request", onSessionRequest);
40064
+ }
39876
40065
  });
39877
40066
  };
39878
40067
  setupDefaultTransport_fn = function() {
@@ -39881,7 +40070,7 @@ ${new this._window.XMLSerializer().serializeToString(e3)}`;
39881
40070
  return __privateGet(this, _transport2);
39882
40071
  }
39883
40072
  if (options == null ? void 0 : options.persist) {
39884
- yield this.storage.setTransport("browser" /* Browser */);
40073
+ yield this.storage.setTransportType("browser" /* Browser */);
39885
40074
  }
39886
40075
  const transport = new DefaultTransport();
39887
40076
  __privateSet(this, _listener, transport.onNotification(
@@ -39914,7 +40103,7 @@ ${new this._window.XMLSerializer().serializeToString(e3)}`;
39914
40103
  };
39915
40104
  this.dappClient.on("message", dappClientMessageHandler);
39916
40105
  let timeout;
39917
- if (this.transport.isConnected()) {
40106
+ if (__privateMethod(this, _MetaMaskConnectMultichain_instances, transportOrThrow_fn).call(this).isConnected()) {
39918
40107
  timeout = setTimeout(() => {
39919
40108
  this.openSimpleDeeplinkIfNeeded();
39920
40109
  }, 250);
@@ -39942,8 +40131,8 @@ ${new this._window.XMLSerializer().serializeToString(e3)}`;
39942
40131
  }
39943
40132
  );
39944
40133
  }
39945
- return this.transport.connect({ scopes, caipAccountIds, sessionProperties }).then(resolve).catch((error) => __async(this, null, function* () {
39946
- yield this.storage.removeTransport();
40134
+ return __privateMethod(this, _MetaMaskConnectMultichain_instances, transportOrThrow_fn).call(this).connect({ scopes, caipAccountIds, sessionProperties }).then(resolve).catch((error) => __async(this, null, function* () {
40135
+ yield this.storage.removeTransportType();
39947
40136
  this.dappClient.off("message", dappClientMessageHandler);
39948
40137
  reject(error instanceof Error ? error : new Error(String(error)));
39949
40138
  })).finally(() => {
@@ -40009,7 +40198,7 @@ ${new this._window.XMLSerializer().serializeToString(e3)}`;
40009
40198
  };
40010
40199
  if ((_a4 = __privateGet(this, _transport2)) == null ? void 0 : _a4.isConnected()) {
40011
40200
  try {
40012
- const response = yield this.transport.request({
40201
+ const response = yield __privateGet(this, _transport2).request({
40013
40202
  method: "wallet_getSession"
40014
40203
  });
40015
40204
  if (response.result) {
@@ -40103,14 +40292,14 @@ ${new this._window.XMLSerializer().serializeToString(e3)}`;
40103
40292
  super();
40104
40293
  this.adapter = adapter;
40105
40294
  }
40106
- getTransport() {
40295
+ getTransportType() {
40107
40296
  return __async(this, null, function* () {
40108
40297
  try {
40109
- const transport = yield this.adapter.get("multichain-transport");
40110
- if (!transport) {
40298
+ const transportType = yield this.adapter.get("multichain-transport");
40299
+ if (!transportType) {
40111
40300
  return null;
40112
40301
  }
40113
- return getTransportType(transport);
40302
+ return getTransportType(transportType);
40114
40303
  } catch (err3) {
40115
40304
  throw new StorageGetErr(
40116
40305
  this.adapter.platform,
@@ -40120,10 +40309,10 @@ ${new this._window.XMLSerializer().serializeToString(e3)}`;
40120
40309
  }
40121
40310
  });
40122
40311
  }
40123
- setTransport(transport) {
40312
+ setTransportType(transportType) {
40124
40313
  return __async(this, null, function* () {
40125
40314
  try {
40126
- yield this.adapter.set("multichain-transport", transport);
40315
+ yield this.adapter.set("multichain-transport", transportType);
40127
40316
  } catch (err3) {
40128
40317
  throw new StorageSetErr(
40129
40318
  this.adapter.platform,
@@ -40133,7 +40322,7 @@ ${new this._window.XMLSerializer().serializeToString(e3)}`;
40133
40322
  }
40134
40323
  });
40135
40324
  }
40136
- removeTransport() {
40325
+ removeTransportType() {
40137
40326
  return __async(this, null, function* () {
40138
40327
  try {
40139
40328
  yield this.adapter.delete("multichain-transport");
@@ -40616,7 +40805,11 @@ ${new this._window.XMLSerializer().serializeToString(e3)}`;
40616
40805
  (_a5 = this.displayUriCallback) == null ? void 0 : _a5.call(this, newLink);
40617
40806
  return newLink;
40618
40807
  }),
40619
- onClose: this.onCloseModal.bind(this),
40808
+ onClose: (shouldTerminate) => {
40809
+ this.onCloseModal(shouldTerminate).catch((error) => {
40810
+ console.error("Failed to close modal:", error);
40811
+ });
40812
+ },
40620
40813
  startDesktopOnboarding: this.onStartDesktopOnboarding.bind(this),
40621
40814
  createConnectionRequest,
40622
40815
  onDisplayUri: this.displayUriCallback
@@ -40654,7 +40847,7 @@ ${new this._window.XMLSerializer().serializeToString(e3)}`;
40654
40847
  }
40655
40848
  try {
40656
40849
  const { defineCustomElements: defineCustomElements2 } = yield Promise.resolve().then(() => (init_loader2(), loader_exports));
40657
- yield defineCustomElements2();
40850
+ defineCustomElements2();
40658
40851
  } catch (error) {
40659
40852
  console.error("Failed to load customElements:", error);
40660
40853
  }