@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
@@ -252,7 +252,7 @@ var init_logger = __esm({
252
252
  });
253
253
 
254
254
  // src/domain/multichain/api/constants.ts
255
- var infuraRpcUrls, RPC_HANDLED_METHODS, SDK_HANDLED_METHODS;
255
+ var infuraRpcUrls, RPC_HANDLED_METHODS, SDK_HANDLED_METHODS, EIP1193_PASSTHROUGH_METHODS;
256
256
  var init_constants = __esm({
257
257
  "src/domain/multichain/api/constants.ts"() {
258
258
  "use strict";
@@ -417,6 +417,11 @@ var init_constants = __esm({
417
417
  "eth_uninstallFilter"
418
418
  ]);
419
419
  SDK_HANDLED_METHODS = /* @__PURE__ */ new Set(["eth_accounts", "eth_chainId"]);
420
+ EIP1193_PASSTHROUGH_METHODS = /* @__PURE__ */ new Set([
421
+ "wallet_addEthereumChain",
422
+ "wallet_switchEthereumChain",
423
+ "eth_accounts"
424
+ ]);
420
425
  }
421
426
  });
422
427
 
@@ -472,7 +477,7 @@ var init_multichain = __esm({
472
477
  }
473
478
  /**
474
479
  * Merges the given options into the current instance options.
475
- * Only the mergeable keys are updated (api.supportedNetworks, versions, ui.*, mobile.*, transport.extensionId, debug).
480
+ * Only the mergeable keys are updated (api.supportedNetworks, analytics, versions, ui.*, mobile.*, transport.extensionId, debug).
476
481
  * The main thing to note is that the value for `dapp` is not merged as it does not make sense for
477
482
  * subsequent calls to `createMultichainClient` to have a different `dapp` value.
478
483
  * Used when createMultichainClient is called with an existing singleton.
@@ -480,23 +485,28 @@ var init_multichain = __esm({
480
485
  * @param partial - Options to merge/overwrite onto the current instance
481
486
  */
482
487
  mergeOptions(partial) {
483
- var _a2, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o;
488
+ var _a2, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q;
484
489
  const opts = this.options;
490
+ const analytics3 = __spreadValues(__spreadValues({}, opts.analytics), (_a2 = partial.analytics) != null ? _a2 : {});
491
+ if (((_b = opts.analytics) == null ? void 0 : _b.enabled) === false) {
492
+ analytics3.enabled = false;
493
+ }
485
494
  this.options = __spreadProps(__spreadValues({}, opts), {
486
495
  api: __spreadProps(__spreadValues({}, opts.api), {
487
- supportedNetworks: __spreadValues(__spreadValues({}, opts.api.supportedNetworks), (_b = (_a2 = partial.api) == null ? void 0 : _a2.supportedNetworks) != null ? _b : {})
496
+ supportedNetworks: __spreadValues(__spreadValues({}, opts.api.supportedNetworks), (_d = (_c = partial.api) == null ? void 0 : _c.supportedNetworks) != null ? _d : {})
488
497
  }),
489
- versions: __spreadValues(__spreadValues({}, opts.versions), (_c = partial.versions) != null ? _c : {}),
498
+ versions: __spreadValues(__spreadValues({}, opts.versions), (_e = partial.versions) != null ? _e : {}),
499
+ analytics: __spreadValues({}, analytics3),
490
500
  ui: __spreadProps(__spreadValues({}, opts.ui), {
491
- headless: (_e = (_d = partial.ui) == null ? void 0 : _d.headless) != null ? _e : opts.ui.headless,
492
- preferExtension: (_g = (_f = partial.ui) == null ? void 0 : _f.preferExtension) != null ? _g : opts.ui.preferExtension,
493
- showInstallModal: (_i = (_h = partial.ui) == null ? void 0 : _h.showInstallModal) != null ? _i : opts.ui.showInstallModal
501
+ headless: (_g = (_f = partial.ui) == null ? void 0 : _f.headless) != null ? _g : opts.ui.headless,
502
+ preferExtension: (_i = (_h = partial.ui) == null ? void 0 : _h.preferExtension) != null ? _i : opts.ui.preferExtension,
503
+ showInstallModal: (_k = (_j = partial.ui) == null ? void 0 : _j.showInstallModal) != null ? _k : opts.ui.showInstallModal
494
504
  }),
495
- mobile: __spreadValues(__spreadValues({}, opts.mobile), (_j = partial.mobile) != null ? _j : {}),
496
- transport: __spreadProps(__spreadValues({}, (_k = opts.transport) != null ? _k : {}), {
497
- extensionId: (_n = (_l = partial.transport) == null ? void 0 : _l.extensionId) != null ? _n : (_m = opts.transport) == null ? void 0 : _m.extensionId
505
+ mobile: __spreadValues(__spreadValues({}, opts.mobile), (_l = partial.mobile) != null ? _l : {}),
506
+ transport: __spreadProps(__spreadValues({}, (_m = opts.transport) != null ? _m : {}), {
507
+ extensionId: (_p = (_n = partial.transport) == null ? void 0 : _n.extensionId) != null ? _p : (_o = opts.transport) == null ? void 0 : _o.extensionId
498
508
  }),
499
- debug: (_o = partial.debug) != null ? _o : opts.debug
509
+ debug: (_q = partial.debug) != null ? _q : opts.debug
500
510
  });
501
511
  }
502
512
  };
@@ -562,7 +572,7 @@ function hasExtension() {
562
572
  return detectionPromise;
563
573
  });
564
574
  }
565
- var PlatformType, detectionPromise;
575
+ var PlatformType, NATIVE_METAMASK_EIP6963_RDNS, detectionPromise;
566
576
  var init_platform = __esm({
567
577
  "src/domain/platform/index.ts"() {
568
578
  "use strict";
@@ -574,6 +584,10 @@ var init_platform = __esm({
574
584
  PlatformType2["ReactNative"] = "react-native";
575
585
  return PlatformType2;
576
586
  })(PlatformType || {});
587
+ NATIVE_METAMASK_EIP6963_RDNS = /* @__PURE__ */ new Set([
588
+ "io.metamask",
589
+ "io.metamask.mobile"
590
+ ]);
577
591
  detectionPromise = (() => __async(null, null, function* () {
578
592
  const pt = getPlatformType();
579
593
  if (pt === "nodejs" /* NonBrowser */ || pt === "react-native" /* ReactNative */) {
@@ -581,23 +595,30 @@ var init_platform = __esm({
581
595
  }
582
596
  return new Promise((resolve) => {
583
597
  const providers = [];
598
+ const targetWindow = window;
584
599
  const handler = (event) => {
585
600
  var _a2, _b;
586
601
  if ((_b = (_a2 = event == null ? void 0 : event.detail) == null ? void 0 : _a2.info) == null ? void 0 : _b.rdns) {
587
602
  providers.push(event.detail);
588
603
  }
589
604
  };
590
- window.addEventListener("eip6963:announceProvider", handler);
591
- window.dispatchEvent(new Event("eip6963:requestProvider"));
605
+ targetWindow.addEventListener("eip6963:announceProvider", handler);
606
+ targetWindow.dispatchEvent(new Event("eip6963:requestProvider"));
592
607
  setTimeout(() => {
593
- window.removeEventListener("eip6963:announceProvider", handler);
594
- const hasMetaMask = providers.some(
595
- (provider) => {
596
- var _a2, _b;
597
- return (_b = (_a2 = provider == null ? void 0 : provider.info) == null ? void 0 : _a2.rdns) == null ? void 0 : _b.startsWith("io.metamask");
608
+ try {
609
+ if (typeof (targetWindow == null ? void 0 : targetWindow.removeEventListener) === "function") {
610
+ targetWindow.removeEventListener("eip6963:announceProvider", handler);
598
611
  }
599
- );
600
- resolve(hasMetaMask);
612
+ const hasMetaMask = providers.some(
613
+ (provider) => {
614
+ var _a2;
615
+ return typeof ((_a2 = provider == null ? void 0 : provider.info) == null ? void 0 : _a2.rdns) === "string" && NATIVE_METAMASK_EIP6963_RDNS.has(provider.info.rdns);
616
+ }
617
+ );
618
+ resolve(hasMetaMask);
619
+ } catch (e) {
620
+ resolve(false);
621
+ }
601
622
  }, 300);
602
623
  });
603
624
  }))();
@@ -1112,12 +1133,14 @@ var init_analytics = __esm({
1112
1133
 
1113
1134
  // src/domain/utils/index.ts
1114
1135
  function getVersion() {
1115
- return "0.0.0";
1136
+ return packageVersion;
1116
1137
  }
1138
+ var packageVersion;
1117
1139
  var init_utils2 = __esm({
1118
1140
  "src/domain/utils/index.ts"() {
1119
1141
  "use strict";
1120
1142
  init_analytics();
1143
+ packageVersion = false ? "unknown" : "1.0.0";
1121
1144
  }
1122
1145
  });
1123
1146
 
@@ -1154,7 +1177,8 @@ import {
1154
1177
  TransportTimeoutError
1155
1178
  } from "@metamask/multichain-api-client";
1156
1179
  import { JsonRpcError, providerErrors as providerErrors2, rpcErrors } from "@metamask/rpc-errors";
1157
- var DEFAULT_REQUEST_TIMEOUT2, 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;
1180
+ import { createDeferredPromise } from "@metamask/utils";
1181
+ var DEFAULT_REQUEST_TIMEOUT2, 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;
1158
1182
  var init_mwp = __esm({
1159
1183
  "src/multichain/transports/mwp/index.ts"() {
1160
1184
  "use strict";
@@ -1188,6 +1212,7 @@ var init_mwp = __esm({
1188
1212
  this.dappClient = dappClient;
1189
1213
  this.kvstore = kvstore;
1190
1214
  this.options = options;
1215
+ __privateAdd(this, _MWPTransport_instances);
1191
1216
  this.__pendingRequests = /* @__PURE__ */ new Map();
1192
1217
  this.notificationCallbacks = /* @__PURE__ */ new Set();
1193
1218
  this.dappClient.on("message", this.handleMessage.bind(this));
@@ -1267,6 +1292,23 @@ var init_mwp = __esm({
1267
1292
  const message = errorPayload instanceof Error ? errorPayload.message : JSON.stringify(errorPayload);
1268
1293
  return rpcErrors.internal({ message });
1269
1294
  }
1295
+ getResponseError(messagePayload) {
1296
+ if ("error" in messagePayload && messagePayload.error) {
1297
+ return messagePayload.error;
1298
+ }
1299
+ const { result } = messagePayload;
1300
+ if (typeof result === "object" && result !== null && "error" in result && result.error && this.isErrorPayload(result.error)) {
1301
+ return result.error;
1302
+ }
1303
+ return void 0;
1304
+ }
1305
+ isErrorPayload(errorPayload) {
1306
+ if (errorPayload instanceof Error) {
1307
+ return true;
1308
+ }
1309
+ const errorData = errorPayload;
1310
+ return typeof (errorData == null ? void 0 : errorData.code) === "number" && typeof (errorData == null ? void 0 : errorData.message) === "string";
1311
+ }
1270
1312
  handleMessage(message) {
1271
1313
  if (typeof message === "object" && message !== null) {
1272
1314
  if ("data" in message) {
@@ -1275,9 +1317,10 @@ var init_mwp = __esm({
1275
1317
  const request = this.pendingRequests.get(messagePayload.id);
1276
1318
  if (request) {
1277
1319
  clearTimeout(request.timeout);
1278
- if ("error" in messagePayload && messagePayload.error) {
1320
+ const responseError = this.getResponseError(messagePayload);
1321
+ if (responseError) {
1279
1322
  this.pendingRequests.delete(messagePayload.id);
1280
- request.reject(this.parseWalletError(messagePayload.error));
1323
+ request.reject(this.parseWalletError(responseError));
1281
1324
  return;
1282
1325
  }
1283
1326
  const requestWithName = __spreadProps(__spreadValues({}, messagePayload), {
@@ -1320,73 +1363,6 @@ var init_mwp = __esm({
1320
1363
  }
1321
1364
  }
1322
1365
  }
1323
- onResumeSuccess(resumeResolve, resumeReject, options) {
1324
- return __async(this, null, function* () {
1325
- var _a2, _b, _c, _d, _e, _f, _g;
1326
- try {
1327
- yield this.waitForWalletSessionIfNotCached();
1328
- const sessionRequest = yield this.request({
1329
- method: "wallet_getSession"
1330
- });
1331
- if (sessionRequest.error) {
1332
- return resumeReject(new Error(sessionRequest.error.message));
1333
- }
1334
- let walletSession = sessionRequest.result;
1335
- if (walletSession && options) {
1336
- const currentScopes = Object.keys(
1337
- (_a2 = walletSession == null ? void 0 : walletSession.sessionScopes) != null ? _a2 : {}
1338
- );
1339
- const proposedScopes = (_b = options == null ? void 0 : options.scopes) != null ? _b : [];
1340
- const proposedCaipAccountIds = (_c = options == null ? void 0 : options.caipAccountIds) != null ? _c : [];
1341
- const hasSameScopesAndAccounts = isSameScopesAndAccounts(
1342
- currentScopes,
1343
- proposedScopes,
1344
- walletSession,
1345
- proposedCaipAccountIds
1346
- );
1347
- if (options.forceRequest || !hasSameScopesAndAccounts) {
1348
- const optionalScopes = addValidAccounts(
1349
- getOptionalScopes((_d = options == null ? void 0 : options.scopes) != null ? _d : []),
1350
- getValidAccounts((_e = options == null ? void 0 : options.caipAccountIds) != null ? _e : [])
1351
- );
1352
- const sessionRequest2 = {
1353
- optionalScopes
1354
- };
1355
- const response = yield this.request({
1356
- method: "wallet_createSession",
1357
- params: sessionRequest2
1358
- });
1359
- if (response.error) {
1360
- return resumeReject(new Error(response.error.message));
1361
- }
1362
- walletSession = response.result;
1363
- }
1364
- } else if (!walletSession) {
1365
- const optionalScopes = addValidAccounts(
1366
- getOptionalScopes((_f = options == null ? void 0 : options.scopes) != null ? _f : []),
1367
- getValidAccounts((_g = options == null ? void 0 : options.caipAccountIds) != null ? _g : [])
1368
- );
1369
- const sessionRequest2 = { optionalScopes };
1370
- const response = yield this.request({
1371
- method: "wallet_createSession",
1372
- params: sessionRequest2
1373
- });
1374
- if (response.error) {
1375
- return resumeReject(new Error(response.error.message));
1376
- }
1377
- walletSession = response.result;
1378
- }
1379
- yield this.removeStoredPendingSessionRequest();
1380
- this.notifyCallbacks({
1381
- method: "wallet_sessionChanged",
1382
- params: walletSession
1383
- });
1384
- return resumeResolve();
1385
- } catch (err) {
1386
- return resumeReject(err);
1387
- }
1388
- });
1389
- }
1390
1366
  init() {
1391
1367
  return __async(this, null, function* () {
1392
1368
  });
@@ -1427,7 +1403,6 @@ var init_mwp = __esm({
1427
1403
  }
1428
1404
  connect(options) {
1429
1405
  return __async(this, null, function* () {
1430
- const { dappClient } = this;
1431
1406
  const session = yield this.getActiveSession();
1432
1407
  if (session) {
1433
1408
  logger("active session found", {
@@ -1436,116 +1411,11 @@ var init_mwp = __esm({
1436
1411
  expiresAt: session.expiresAt
1437
1412
  });
1438
1413
  }
1439
- const storedSessionRequestBeforeConnectionAttempt = yield this.getStoredPendingSessionRequest();
1440
- let timeout;
1441
- let initialConnectionMessageHandler;
1442
- const connectionPromise = new Promise((resolve, reject) => __async(this, null, function* () {
1443
- let connection;
1444
- if (session) {
1445
- connection = new Promise((resumeResolve, resumeReject) => {
1446
- var _a2;
1447
- if (this.dappClient.state === "CONNECTED") {
1448
- this.onResumeSuccess(resumeResolve, resumeReject, options);
1449
- } else {
1450
- this.dappClient.once("connected", () => __async(this, null, function* () {
1451
- this.onResumeSuccess(resumeResolve, resumeReject, options);
1452
- }));
1453
- dappClient.resume((_a2 = session == null ? void 0 : session.id) != null ? _a2 : "");
1454
- }
1455
- });
1456
- } else {
1457
- connection = new Promise(
1458
- (resolveConnection, rejectConnection) => {
1459
- var _a2, _b;
1460
- const optionalScopes = addValidAccounts(
1461
- getOptionalScopes((_a2 = options == null ? void 0 : options.scopes) != null ? _a2 : []),
1462
- getValidAccounts((_b = options == null ? void 0 : options.caipAccountIds) != null ? _b : [])
1463
- );
1464
- const sessionRequest = {
1465
- optionalScopes,
1466
- sessionProperties: options == null ? void 0 : options.sessionProperties
1467
- };
1468
- const request = {
1469
- jsonrpc: "2.0",
1470
- id: String(getUniqueRequestId()),
1471
- method: "wallet_createSession",
1472
- params: sessionRequest
1473
- };
1474
- initialConnectionMessageHandler = (message) => __async(this, null, function* () {
1475
- if (typeof message !== "object" || message === null) {
1476
- return;
1477
- }
1478
- if (!("data" in message)) {
1479
- return;
1480
- }
1481
- const messagePayload = message.data;
1482
- const isMatchingId = messagePayload.id === request.id;
1483
- const isMatchingMethod = messagePayload.method === "wallet_createSession" || messagePayload.method === "wallet_sessionChanged";
1484
- if (!isMatchingId && !isMatchingMethod) {
1485
- return;
1486
- }
1487
- if (messagePayload.error) {
1488
- return rejectConnection(
1489
- this.parseWalletError(messagePayload.error)
1490
- );
1491
- }
1492
- yield this.storeWalletSession(
1493
- request,
1494
- messagePayload
1495
- );
1496
- yield this.removeStoredPendingSessionRequest();
1497
- this.notifyCallbacks(messagePayload);
1498
- return resolveConnection();
1499
- });
1500
- this.dappClient.on("message", initialConnectionMessageHandler);
1501
- const platformType = getPlatformType();
1502
- const isQRCodeFlow = [
1503
- "web-desktop" /* DesktopWeb */,
1504
- "nodejs" /* NonBrowser */
1505
- ].includes(platformType);
1506
- const initialPayload = {
1507
- name: MULTICHAIN_PROVIDER_STREAM_NAME,
1508
- data: request
1509
- };
1510
- dappClient.connect({
1511
- mode: "trusted",
1512
- initialPayload: isQRCodeFlow ? void 0 : initialPayload
1513
- }).then(() => __async(this, null, function* () {
1514
- if (isQRCodeFlow) {
1515
- return dappClient.sendRequest(initialPayload);
1516
- }
1517
- return void 0;
1518
- })).catch((error) => {
1519
- if (initialConnectionMessageHandler) {
1520
- this.dappClient.off(
1521
- "message",
1522
- initialConnectionMessageHandler
1523
- );
1524
- }
1525
- rejectConnection(error);
1526
- });
1527
- }
1528
- );
1529
- }
1530
- timeout = setTimeout(
1531
- () => {
1532
- reject(new TransportTimeoutError());
1533
- },
1534
- storedSessionRequestBeforeConnectionAttempt ? this.options.resumeTimeout : this.options.connectionTimeout
1535
- );
1536
- connection.then(resolve).catch(reject);
1537
- }));
1538
- return connectionPromise.catch((error) => __async(this, null, function* () {
1414
+ const connection = session ? __privateMethod(this, _MWPTransport_instances, resumeSession_fn).call(this, session, options) : __privateMethod(this, _MWPTransport_instances, startSession_fn).call(this, options);
1415
+ return connection.catch((error) => __async(this, null, function* () {
1539
1416
  yield this.dappClient.disconnect();
1540
1417
  throw error;
1541
1418
  })).finally(() => {
1542
- if (timeout) {
1543
- clearTimeout(timeout);
1544
- }
1545
- if (initialConnectionMessageHandler) {
1546
- this.dappClient.off("message", initialConnectionMessageHandler);
1547
- initialConnectionMessageHandler = void 0;
1548
- }
1549
1419
  this.removeStoredPendingSessionRequest();
1550
1420
  });
1551
1421
  });
@@ -1804,6 +1674,188 @@ var init_mwp = __esm({
1804
1674
  });
1805
1675
  }
1806
1676
  };
1677
+ _MWPTransport_instances = new WeakSet();
1678
+ onResumeHandler_fn = function(options) {
1679
+ return __async(this, null, function* () {
1680
+ var _a2, _b, _c, _d, _e, _f, _g;
1681
+ yield this.waitForWalletSessionIfNotCached();
1682
+ const sessionResponse = yield this.request({ method: "wallet_getSession" });
1683
+ if (sessionResponse.error) {
1684
+ throw new Error(sessionResponse.error.message);
1685
+ }
1686
+ let walletSession = sessionResponse.result;
1687
+ if (walletSession && options) {
1688
+ const currentScopes = Object.keys(
1689
+ (_a2 = walletSession == null ? void 0 : walletSession.sessionScopes) != null ? _a2 : {}
1690
+ );
1691
+ const proposedScopes = (_b = options == null ? void 0 : options.scopes) != null ? _b : [];
1692
+ const proposedCaipAccountIds = (_c = options == null ? void 0 : options.caipAccountIds) != null ? _c : [];
1693
+ const hasSameScopesAndAccounts = isSameScopesAndAccounts(
1694
+ currentScopes,
1695
+ proposedScopes,
1696
+ walletSession,
1697
+ proposedCaipAccountIds
1698
+ );
1699
+ if (options.forceRequest || !hasSameScopesAndAccounts) {
1700
+ const optionalScopes = addValidAccounts(
1701
+ getOptionalScopes((_d = options == null ? void 0 : options.scopes) != null ? _d : []),
1702
+ getValidAccounts((_e = options == null ? void 0 : options.caipAccountIds) != null ? _e : [])
1703
+ );
1704
+ const sessionRequest = {
1705
+ optionalScopes
1706
+ };
1707
+ const response = yield this.request({
1708
+ method: "wallet_createSession",
1709
+ params: sessionRequest
1710
+ });
1711
+ if (response.error) {
1712
+ throw new Error(response.error.message);
1713
+ }
1714
+ walletSession = response.result;
1715
+ }
1716
+ } else if (!walletSession) {
1717
+ const optionalScopes = addValidAccounts(
1718
+ getOptionalScopes((_f = options == null ? void 0 : options.scopes) != null ? _f : []),
1719
+ getValidAccounts((_g = options == null ? void 0 : options.caipAccountIds) != null ? _g : [])
1720
+ );
1721
+ const sessionRequest = {
1722
+ optionalScopes
1723
+ };
1724
+ const response = yield this.request({
1725
+ method: "wallet_createSession",
1726
+ params: sessionRequest
1727
+ });
1728
+ if (response.error) {
1729
+ throw new Error(response.error.message);
1730
+ }
1731
+ walletSession = response.result;
1732
+ }
1733
+ yield this.removeStoredPendingSessionRequest();
1734
+ this.notifyCallbacks({
1735
+ method: "wallet_sessionChanged",
1736
+ params: walletSession
1737
+ });
1738
+ });
1739
+ };
1740
+ resumeSession_fn = function(session, options) {
1741
+ return __async(this, null, function* () {
1742
+ var _a2;
1743
+ const isContinuingPriorAttempt = (yield this.getStoredPendingSessionRequest()) !== null;
1744
+ const resumeDeferred = createDeferredPromise();
1745
+ const runOnResumeHandler = () => __async(this, null, function* () {
1746
+ try {
1747
+ resumeDeferred.resolve(yield __privateMethod(this, _MWPTransport_instances, onResumeHandler_fn).call(this, options));
1748
+ } catch (err) {
1749
+ resumeDeferred.reject(err);
1750
+ }
1751
+ });
1752
+ if (this.dappClient.state === "CONNECTED") {
1753
+ runOnResumeHandler();
1754
+ } else {
1755
+ this.dappClient.once("connected", runOnResumeHandler);
1756
+ this.dappClient.resume((_a2 = session.id) != null ? _a2 : "").catch((err) => resumeDeferred.reject(err));
1757
+ }
1758
+ const timeoutDeferred = createDeferredPromise();
1759
+ const timeout = setTimeout(
1760
+ () => timeoutDeferred.reject(new TransportTimeoutError()),
1761
+ isContinuingPriorAttempt ? this.options.resumeTimeout : this.options.connectionTimeout
1762
+ );
1763
+ const cleanup = () => this.dappClient.off("connected", runOnResumeHandler);
1764
+ return Promise.race([
1765
+ resumeDeferred.promise,
1766
+ timeoutDeferred.promise
1767
+ ]).finally(() => {
1768
+ clearTimeout(timeout);
1769
+ cleanup();
1770
+ });
1771
+ });
1772
+ };
1773
+ startSession_fn = function(options) {
1774
+ return __async(this, null, function* () {
1775
+ var _a2, _b;
1776
+ const { dappClient } = this;
1777
+ const isContinuingPriorAttempt = (yield this.getStoredPendingSessionRequest()) !== null;
1778
+ const connDeferred = createDeferredPromise();
1779
+ const optionalScopes = addValidAccounts(
1780
+ getOptionalScopes((_a2 = options == null ? void 0 : options.scopes) != null ? _a2 : []),
1781
+ getValidAccounts((_b = options == null ? void 0 : options.caipAccountIds) != null ? _b : [])
1782
+ );
1783
+ const sessionRequest = {
1784
+ optionalScopes,
1785
+ sessionProperties: options == null ? void 0 : options.sessionProperties
1786
+ };
1787
+ const request = {
1788
+ jsonrpc: "2.0",
1789
+ id: String(getUniqueRequestId()),
1790
+ method: "wallet_createSession",
1791
+ params: sessionRequest
1792
+ };
1793
+ let handler;
1794
+ const removeHandler = () => {
1795
+ if (handler) {
1796
+ this.dappClient.off("message", handler);
1797
+ handler = void 0;
1798
+ }
1799
+ };
1800
+ handler = (message) => __async(this, null, function* () {
1801
+ if (typeof message !== "object" || message === null) {
1802
+ return;
1803
+ }
1804
+ if (!("data" in message)) {
1805
+ return;
1806
+ }
1807
+ const messagePayload = message.data;
1808
+ const isMatchingId = messagePayload.id === request.id;
1809
+ const isMatchingMethod = messagePayload.method === "wallet_createSession" || messagePayload.method === "wallet_sessionChanged";
1810
+ if (!isMatchingId && !isMatchingMethod) {
1811
+ return;
1812
+ }
1813
+ const responseError = this.getResponseError(messagePayload);
1814
+ if (responseError) {
1815
+ connDeferred.reject(this.parseWalletError(responseError));
1816
+ return;
1817
+ }
1818
+ yield this.storeWalletSession(
1819
+ request,
1820
+ messagePayload
1821
+ );
1822
+ yield this.removeStoredPendingSessionRequest();
1823
+ this.notifyCallbacks(messagePayload);
1824
+ connDeferred.resolve();
1825
+ });
1826
+ this.dappClient.on("message", handler);
1827
+ const platformType = getPlatformType();
1828
+ const isQRCodeFlow = [
1829
+ "web-desktop" /* DesktopWeb */,
1830
+ "nodejs" /* NonBrowser */
1831
+ ].includes(platformType);
1832
+ const initialPayload = {
1833
+ name: MULTICHAIN_PROVIDER_STREAM_NAME,
1834
+ data: request
1835
+ };
1836
+ dappClient.connect({
1837
+ mode: "trusted",
1838
+ initialPayload: isQRCodeFlow ? void 0 : initialPayload
1839
+ }).then(() => __async(this, null, function* () {
1840
+ if (isQRCodeFlow) {
1841
+ return dappClient.sendRequest(initialPayload);
1842
+ }
1843
+ return void 0;
1844
+ })).catch((error) => connDeferred.reject(error));
1845
+ const timeoutDeferred = createDeferredPromise();
1846
+ const timeout = setTimeout(
1847
+ () => timeoutDeferred.reject(new TransportTimeoutError()),
1848
+ isContinuingPriorAttempt ? this.options.resumeTimeout : this.options.connectionTimeout
1849
+ );
1850
+ return Promise.race([
1851
+ connDeferred.promise,
1852
+ timeoutDeferred.promise
1853
+ ]).finally(() => {
1854
+ clearTimeout(timeout);
1855
+ removeHandler();
1856
+ });
1857
+ });
1858
+ };
1807
1859
  }
1808
1860
  });
1809
1861
 
@@ -2113,6 +2165,7 @@ import { analytics as analytics2 } from "@metamask/analytics";
2113
2165
  import {
2114
2166
  getMultichainClient
2115
2167
  } from "@metamask/multichain-api-client";
2168
+ import { createDeferredPromise as createDeferredPromise2 } from "@metamask/utils";
2116
2169
 
2117
2170
  // src/config/index.ts
2118
2171
  var MWP_RELAY_URL = "wss://mm-sdk-relay.api.cx.metamask.io/connection/websocket";
@@ -2236,6 +2289,17 @@ import { analytics } from "@metamask/analytics";
2236
2289
  init_domain();
2237
2290
  init_utils();
2238
2291
  init_analytics();
2292
+ function toRPCInvokeMethodErr(error) {
2293
+ var _a2;
2294
+ if (error instanceof RPCInvokeMethodErr) {
2295
+ return error;
2296
+ }
2297
+ const castError = error;
2298
+ return new RPCInvokeMethodErr(
2299
+ (_a2 = castError.message) != null ? _a2 : "Unknown error",
2300
+ castError.code
2301
+ );
2302
+ }
2239
2303
  var _RequestRouter_instances, withAnalyticsTracking_fn, trackWalletActionRequested_fn, trackWalletActionSucceeded_fn, trackWalletActionFailed_fn, trackWalletActionRejected_fn;
2240
2304
  var RequestRouter = class {
2241
2305
  constructor(transport, rpcClient, config, transportType) {
@@ -2255,6 +2319,9 @@ var RequestRouter = class {
2255
2319
  invokeMethod(options) {
2256
2320
  return __async(this, null, function* () {
2257
2321
  const { method } = options.request;
2322
+ if (EIP1193_PASSTHROUGH_METHODS.has(method)) {
2323
+ return this.handleWithEip1193Passthrough(options);
2324
+ }
2258
2325
  if (RPC_HANDLED_METHODS.has(method)) {
2259
2326
  return this.handleWithRpcNode(options);
2260
2327
  }
@@ -2264,6 +2331,29 @@ var RequestRouter = class {
2264
2331
  return this.handleWithWallet(options);
2265
2332
  });
2266
2333
  }
2334
+ /**
2335
+ * Forwards EIP-1193 / legacy provider methods (e.g. `wallet_addEthereumChain`,
2336
+ * `wallet_switchEthereumChain`, `eth_accounts`) directly to the underlying
2337
+ * transport's `sendEip1193Message`, bypassing the multichain
2338
+ * `wallet_invokeMethod` envelope. These methods are wallet-side concerns the
2339
+ * Multichain API does not model, so we forward the raw `{ method, params }`
2340
+ * payload and return the wallet's full JSON-RPC response envelope unchanged.
2341
+ *
2342
+ * Analytics tracking is intentionally skipped here: ecosystem clients
2343
+ * (e.g. `connect-evm`) emit their own `wallet_action_*` events around these
2344
+ * passthrough calls, and adding router-level tracking would double-count.
2345
+ *
2346
+ * @param options
2347
+ */
2348
+ handleWithEip1193Passthrough(options) {
2349
+ return __async(this, null, function* () {
2350
+ const response = yield this.transport.sendEip1193Message({
2351
+ method: options.request.method,
2352
+ params: options.request.params
2353
+ });
2354
+ return response.result;
2355
+ });
2356
+ }
2267
2357
  /**
2268
2358
  * Forwards the request directly to the wallet via the transport.
2269
2359
  *
@@ -2295,14 +2385,6 @@ var RequestRouter = class {
2295
2385
  }), 10);
2296
2386
  }
2297
2387
  const response = yield request;
2298
- if (response.error) {
2299
- const { error } = response;
2300
- throw new RPCInvokeMethodErr(
2301
- `RPC Request failed with code ${error.code}: ${error.message}`,
2302
- error.code,
2303
- error.message
2304
- );
2305
- }
2306
2388
  return response.result;
2307
2389
  }));
2308
2390
  });
@@ -2342,6 +2424,13 @@ _RequestRouter_instances = new WeakSet();
2342
2424
  withAnalyticsTracking_fn = function(options, execute) {
2343
2425
  return __async(this, null, function* () {
2344
2426
  var _a2;
2427
+ if (((_a2 = this.config.analytics) == null ? void 0 : _a2.enabled) === false) {
2428
+ try {
2429
+ return yield execute();
2430
+ } catch (error) {
2431
+ throw toRPCInvokeMethodErr(error);
2432
+ }
2433
+ }
2345
2434
  yield __privateMethod(this, _RequestRouter_instances, trackWalletActionRequested_fn).call(this, options);
2346
2435
  try {
2347
2436
  const result = yield execute();
@@ -2354,14 +2443,7 @@ withAnalyticsTracking_fn = function(options, execute) {
2354
2443
  } else {
2355
2444
  yield __privateMethod(this, _RequestRouter_instances, trackWalletActionFailed_fn).call(this, options, error);
2356
2445
  }
2357
- if (error instanceof RPCInvokeMethodErr) {
2358
- throw error;
2359
- }
2360
- const castError = error;
2361
- throw new RPCInvokeMethodErr(
2362
- (_a2 = castError.message) != null ? _a2 : "Unknown error",
2363
- castError.code
2364
- );
2446
+ throw toRPCInvokeMethodErr(error);
2365
2447
  }
2366
2448
  });
2367
2449
  };
@@ -2417,7 +2499,7 @@ import {
2417
2499
  getDefaultTransport
2418
2500
  } from "@metamask/multichain-api-client";
2419
2501
  var DEFAULT_REQUEST_TIMEOUT = 60 * 1e3;
2420
- var _notificationCallbacks, _transport, _defaultRequestOptions, _pendingRequests, _handleResponseListener, _handleNotificationListener, _DefaultTransport_instances, notifyCallbacks_fn, isMetamaskProviderEvent_fn, handleResponse_fn, handleNotification_fn, setupMessageListener_fn, init_fn;
2502
+ var _notificationCallbacks, _transport, _defaultRequestOptions, _pendingRequests, _handleResponseListener, _handleNotificationListener, _DefaultTransport_instances, notifyCallbacks_fn, parseWalletError_fn, isMetamaskProviderEvent_fn, handleResponse_fn, handleNotification_fn, setupMessageListener_fn, init_fn;
2421
2503
  var DefaultTransport = class {
2422
2504
  constructor() {
2423
2505
  __privateAdd(this, _DefaultTransport_instances);
@@ -2553,7 +2635,11 @@ var DefaultTransport = class {
2553
2635
  }
2554
2636
  request(_0) {
2555
2637
  return __async(this, arguments, function* (request, options = __privateGet(this, _defaultRequestOptions)) {
2556
- return __privateGet(this, _transport).request(request, options);
2638
+ const response = yield __privateGet(this, _transport).request(request, options);
2639
+ if (response.error) {
2640
+ throw __privateMethod(this, _DefaultTransport_instances, parseWalletError_fn).call(this, response.error);
2641
+ }
2642
+ return response;
2557
2643
  });
2558
2644
  }
2559
2645
  onNotification(callback) {
@@ -2597,6 +2683,16 @@ notifyCallbacks_fn = function(data) {
2597
2683
  }
2598
2684
  }
2599
2685
  };
2686
+ parseWalletError_fn = function(errorPayload) {
2687
+ const errorData = errorPayload;
2688
+ const error = new Error(
2689
+ typeof errorData.message === "string" ? errorData.message : "Request failed"
2690
+ );
2691
+ if (typeof errorData.code === "number") {
2692
+ error.code = errorData.code;
2693
+ }
2694
+ return error;
2695
+ };
2600
2696
  isMetamaskProviderEvent_fn = function(event) {
2601
2697
  var _a2, _b;
2602
2698
  return ((_b = (_a2 = event == null ? void 0 : event.data) == null ? void 0 : _a2.data) == null ? void 0 : _b.name) === "metamask-provider" && // eslint-disable-next-line no-restricted-globals
@@ -2619,13 +2715,7 @@ handleResponse_fn = function(event) {
2619
2715
  __privateGet(this, _pendingRequests).delete(responseId);
2620
2716
  const response = responseData;
2621
2717
  if ("error" in response && response.error) {
2622
- const error = new Error(
2623
- response.error.message || "Request failed"
2624
- );
2625
- if (typeof response.error.code === "number") {
2626
- error.code = response.error.code;
2627
- }
2628
- pendingRequest.reject(error);
2718
+ pendingRequest.reject(__privateMethod(this, _DefaultTransport_instances, parseWalletError_fn).call(this, response.error));
2629
2719
  } else {
2630
2720
  pendingRequest.resolve(response);
2631
2721
  }
@@ -2663,22 +2753,21 @@ init_fn = function() {
2663
2753
  // src/multichain/transports/multichainApiClientWrapper/index.ts
2664
2754
  init_utils();
2665
2755
  import { providerErrors } from "@metamask/rpc-errors";
2666
- var _notificationCallbacks2, _MultichainApiClientWrapperTransport_instances, walletCreateSession_fn, walletGetSession_fn, walletRevokeSession_fn, walletInvokeMethod_fn;
2756
+ var _notificationCallbacks2, _getTransport, _MultichainApiClientWrapperTransport_instances, walletCreateSession_fn, walletGetSession_fn, walletRevokeSession_fn, walletInvokeMethod_fn;
2667
2757
  var MultichainApiClientWrapperTransport = class {
2668
- constructor(metamaskConnectMultichain) {
2758
+ constructor(metamaskConnectMultichain, getTransport) {
2669
2759
  this.metamaskConnectMultichain = metamaskConnectMultichain;
2670
2760
  __privateAdd(this, _MultichainApiClientWrapperTransport_instances);
2671
2761
  __privateAdd(this, _notificationCallbacks2, /* @__PURE__ */ new Set());
2762
+ __privateAdd(this, _getTransport);
2763
+ __privateSet(this, _getTransport, getTransport);
2672
2764
  }
2673
2765
  isTransportDefined() {
2674
- try {
2675
- return Boolean(this.metamaskConnectMultichain.transport);
2676
- } catch (_error) {
2677
- return false;
2678
- }
2766
+ return __privateGet(this, _getTransport).call(this) !== void 0;
2679
2767
  }
2680
2768
  isTransportConnected() {
2681
- return this.isTransportDefined() && this.metamaskConnectMultichain.transport.isConnected();
2769
+ var _a2, _b;
2770
+ return (_b = (_a2 = __privateGet(this, _getTransport).call(this)) == null ? void 0 : _a2.isConnected()) != null ? _b : false;
2682
2771
  }
2683
2772
  clearNotificationCallbacks() {
2684
2773
  __privateGet(this, _notificationCallbacks2).clear();
@@ -2694,10 +2783,11 @@ var MultichainApiClientWrapperTransport = class {
2694
2783
  this.notificationListener = void 0;
2695
2784
  }
2696
2785
  setupTransportNotificationListener() {
2697
- if (!this.isTransportDefined() || this.notificationListener) {
2786
+ const transport = __privateGet(this, _getTransport).call(this);
2787
+ if (!transport || this.notificationListener) {
2698
2788
  return;
2699
2789
  }
2700
- this.notificationListener = this.metamaskConnectMultichain.transport.onNotification(
2790
+ this.notificationListener = transport.onNotification(
2701
2791
  this.notifyCallbacks.bind(this)
2702
2792
  );
2703
2793
  }
@@ -2747,6 +2837,7 @@ var MultichainApiClientWrapperTransport = class {
2747
2837
  }
2748
2838
  };
2749
2839
  _notificationCallbacks2 = new WeakMap();
2840
+ _getTransport = new WeakMap();
2750
2841
  _MultichainApiClientWrapperTransport_instances = new WeakSet();
2751
2842
  walletCreateSession_fn = function(request) {
2752
2843
  return __async(this, null, function* () {
@@ -2770,14 +2861,19 @@ walletCreateSession_fn = function(request) {
2770
2861
  accounts,
2771
2862
  createSessionParams.sessionProperties
2772
2863
  );
2773
- return this.metamaskConnectMultichain.transport.request({
2864
+ const transport = __privateGet(this, _getTransport).call(this);
2865
+ if (!transport) {
2866
+ throw new Error("Transport not initialized after connect");
2867
+ }
2868
+ return transport.request({
2774
2869
  method: "wallet_getSession"
2775
2870
  });
2776
2871
  });
2777
2872
  };
2778
2873
  walletGetSession_fn = function(request) {
2779
2874
  return __async(this, null, function* () {
2780
- if (!this.isTransportConnected()) {
2875
+ const transport = __privateGet(this, _getTransport).call(this);
2876
+ if (!(transport == null ? void 0 : transport.isConnected())) {
2781
2877
  return {
2782
2878
  jsonrpc: "2.0",
2783
2879
  id: request.id,
@@ -2786,7 +2882,7 @@ walletGetSession_fn = function(request) {
2786
2882
  }
2787
2883
  };
2788
2884
  }
2789
- return this.metamaskConnectMultichain.transport.request({
2885
+ return transport.request({
2790
2886
  method: "wallet_getSession"
2791
2887
  });
2792
2888
  });
@@ -2822,26 +2918,63 @@ walletInvokeMethod_fn = function(request) {
2822
2918
  init_utils();
2823
2919
  var logger2 = createLogger("metamask-sdk:core");
2824
2920
  var SINGLETON_KEY = "__METAMASK_CONNECT_MULTICHAIN_SINGLETON__";
2825
- var _a, _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;
2921
+ function normalizeAnalyticsOptions(analyticsOptions) {
2922
+ var _a2;
2923
+ return __spreadProps(__spreadValues({}, analyticsOptions != null ? analyticsOptions : {}), {
2924
+ enabled: (_a2 = analyticsOptions == null ? void 0 : analyticsOptions.enabled) != null ? _a2 : true,
2925
+ // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
2926
+ integrationType: (analyticsOptions == null ? void 0 : analyticsOptions.integrationType) || "direct"
2927
+ });
2928
+ }
2929
+ function isAnalyticsEnabled(options) {
2930
+ var _a2;
2931
+ return ((_a2 = options.analytics) == null ? void 0 : _a2.enabled) !== false;
2932
+ }
2933
+ function setupAnalyticsGlobals(options, storage, setAnonId) {
2934
+ return __async(this, null, function* () {
2935
+ var _a2, _b;
2936
+ if (!isAnalyticsEnabled(options)) {
2937
+ setAnonId == null ? void 0 : setAnonId(void 0);
2938
+ analytics2.disable();
2939
+ return;
2940
+ }
2941
+ const platform = getPlatformType();
2942
+ const isBrowser = platform === "in-app-browser" /* MetaMaskMobileWebview */ || platform === "web-desktop" /* DesktopWeb */ || platform === "web-mobile" /* MobileWeb */;
2943
+ const isReactNative2 = platform === "react-native" /* ReactNative */;
2944
+ if (!isBrowser && !isReactNative2) {
2945
+ return;
2946
+ }
2947
+ const dappId = getDappId(options.dapp);
2948
+ const anonId = yield storage.getAnonId();
2949
+ setAnonId == null ? void 0 : setAnonId(anonId);
2950
+ const { integrationType } = (_a2 = options.analytics) != null ? _a2 : {
2951
+ integrationType: ""
2952
+ };
2953
+ analytics2.setGlobalProperty("mmconnect_versions", (_b = options.versions) != null ? _b : {});
2954
+ analytics2.setGlobalProperty("dapp_id", dappId);
2955
+ analytics2.setGlobalProperty("anon_id", anonId);
2956
+ analytics2.setGlobalProperty("platform", platform);
2957
+ if (integrationType) {
2958
+ analytics2.setGlobalProperty("integration_types", [integrationType]);
2959
+ }
2960
+ analytics2.enable();
2961
+ });
2962
+ }
2963
+ var _a, _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;
2826
2964
  var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends MultichainCore {
2827
2965
  constructor(options) {
2828
- var _a2, _b, _c, _d, _e, _f;
2966
+ var _a2, _b, _c, _d;
2829
2967
  const withDappMetadata = setupDappMetadata(options);
2830
- const integrationType = ((_a2 = options.analytics) == null ? void 0 : _a2.integrationType) || "direct";
2831
2968
  const allOptions = __spreadProps(__spreadValues({}, withDappMetadata), {
2832
2969
  ui: __spreadProps(__spreadValues({}, withDappMetadata.ui), {
2833
- preferExtension: (_b = withDappMetadata.ui.preferExtension) != null ? _b : true,
2834
- showInstallModal: (_c = withDappMetadata.ui.showInstallModal) != null ? _c : false,
2835
- headless: (_d = withDappMetadata.ui.headless) != null ? _d : false
2836
- }),
2837
- analytics: __spreadProps(__spreadValues({}, (_e = options.analytics) != null ? _e : {}), {
2838
- integrationType
2970
+ preferExtension: (_a2 = withDappMetadata.ui.preferExtension) != null ? _a2 : true,
2971
+ showInstallModal: (_b = withDappMetadata.ui.showInstallModal) != null ? _b : false,
2972
+ headless: (_c = withDappMetadata.ui.headless) != null ? _c : false
2839
2973
  }),
2974
+ analytics: normalizeAnalyticsOptions(options.analytics),
2840
2975
  versions: __spreadValues({
2841
- // typeof guard needed: Metro (React Native) bundles TS source directly,
2842
- // bypassing the tsup build that substitutes __PACKAGE_VERSION__.
2843
- "connect-multichain": false ? "unknown" : "0.14.0"
2844
- }, (_f = options.versions) != null ? _f : {})
2976
+ "connect-multichain": getVersion()
2977
+ }, (_d = options.versions) != null ? _d : {})
2845
2978
  });
2846
2979
  super(allOptions);
2847
2980
  __privateAdd(this, _MetaMaskConnectMultichain_instances);
@@ -2856,7 +2989,8 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
2856
2989
  __privateAdd(this, _anonId);
2857
2990
  __privateAdd(this, _sdkInfo, `Sdk/Javascript SdkVersion/${getVersion()} Platform/${getPlatformType()} dApp/${(_a = this.options.dapp.url) != null ? _a : this.options.dapp.name} dAppTitle/${this.options.dapp.name}`);
2858
2991
  __privateSet(this, _providerTransportWrapper, new MultichainApiClientWrapperTransport(
2859
- this
2992
+ this,
2993
+ () => __privateGet(this, _transport2)
2860
2994
  ));
2861
2995
  __privateSet(this, _provider, getMultichainClient({
2862
2996
  transport: __privateGet(this, _providerTransportWrapper)
@@ -2875,12 +3009,6 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
2875
3009
  get provider() {
2876
3010
  return __privateGet(this, _provider);
2877
3011
  }
2878
- get transport() {
2879
- if (!__privateGet(this, _transport2)) {
2880
- throw new Error("Transport not initialized, establish connection first");
2881
- }
2882
- return __privateGet(this, _transport2);
2883
- }
2884
3012
  get dappClient() {
2885
3013
  if (!__privateGet(this, _dappClient)) {
2886
3014
  throw new Error("DappClient not initialized, establish connection first");
@@ -2894,28 +3022,33 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
2894
3022
  get storage() {
2895
3023
  return this.options.storage;
2896
3024
  }
3025
+ get version() {
3026
+ return getVersion();
3027
+ }
2897
3028
  // Creates a singleton instance of MetaMaskConnectMultichain.
2898
3029
  // If the singleton already exists, it merges the incoming options with the
2899
3030
  // existing singleton options for the following keys: `api.supportedNetworks`,
2900
- // `versions`, `ui.*`, `mobile.*`, `transport.extensionId`, `debug`. Take note
2901
- // that the value for `dapp` is not merged as it does not make sense for
2902
- // subsequent calls to `createMultichainClient` to have a different `dapp` value.
3031
+ // `analytics`, `versions`, `ui.*`, `mobile.*`, `transport.extensionId`,
3032
+ // `debug`. Take note that the value for `dapp` is not merged as it does not
3033
+ // make sense for subsequent calls to `createMultichainClient` to have a
3034
+ // different `dapp` value.
2903
3035
  static create(options) {
2904
3036
  return __async(this, null, function* () {
2905
- var _a2, _b;
3037
+ var _a2;
2906
3038
  const globalObject = getGlobalObject();
2907
3039
  const existing = globalObject[SINGLETON_KEY];
2908
3040
  if (existing) {
2909
3041
  const instance = yield existing;
3042
+ if (instance.version !== getVersion()) {
3043
+ console.warn(
3044
+ `MetaMask Connect does not support using multiple versions of @metamask/connect-multichain. Attempted to create a new instance with version ${getVersion()}, but an existing ${instance.version} singleton was already initialized. Using the existing ${instance.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.`
3045
+ );
3046
+ }
2910
3047
  instance.mergeOptions(options);
2911
- analytics2.setGlobalProperty(
2912
- "mmconnect_versions",
2913
- (_a2 = instance.options.versions) != null ? _a2 : {}
2914
- );
2915
- if ((_b = options.analytics) == null ? void 0 : _b.integrationType) {
2916
- analytics2.setGlobalProperty("integration_types", [
2917
- options.analytics.integrationType
2918
- ]);
3048
+ if (instance instanceof _MetaMaskConnectMultichain) {
3049
+ yield __privateMethod(_a2 = instance, _MetaMaskConnectMultichain_instances, setupAnalytics_fn).call(_a2);
3050
+ } else {
3051
+ yield setupAnalyticsGlobals(instance.options, instance.storage);
2919
3052
  }
2920
3053
  if (options.debug) {
2921
3054
  enableDebug("metamask-sdk:*");
@@ -2934,12 +3067,12 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
2934
3067
  }
2935
3068
  yield __privateMethod(_a3 = instance, _MetaMaskConnectMultichain_instances, init_fn2).call(_a3);
2936
3069
  return instance;
2937
- }))();
2938
- globalObject[SINGLETON_KEY] = instancePromise;
2939
- instancePromise.catch((error) => {
3070
+ }))().catch((error) => {
2940
3071
  globalObject[SINGLETON_KEY] = void 0;
2941
3072
  console.error("Error initializing MetaMaskConnectMultichain", error);
3073
+ throw error;
2942
3074
  });
3075
+ globalObject[SINGLETON_KEY] = instancePromise;
2943
3076
  return instancePromise;
2944
3077
  });
2945
3078
  }
@@ -2965,21 +3098,23 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
2965
3098
  } else {
2966
3099
  transportType = "mwp" /* MWP */;
2967
3100
  }
2968
- try {
2969
- const baseProps = yield getBaseAnalyticsProperties(
2970
- this.options,
2971
- this.storage
2972
- );
2973
- const dappConfiguredChains = Object.keys(
2974
- this.options.api.supportedNetworks
2975
- );
2976
- analytics2.track("mmconnect_connection_initiated", __spreadProps(__spreadValues({}, baseProps), {
2977
- transport_type: transportType,
2978
- dapp_configured_chains: dappConfiguredChains,
2979
- dapp_requested_chains: scopes
2980
- }));
2981
- } catch (error) {
2982
- logger2("Error tracking connection_initiated event", error);
3101
+ if (isAnalyticsEnabled(this.options)) {
3102
+ try {
3103
+ const baseProps = yield getBaseAnalyticsProperties(
3104
+ this.options,
3105
+ this.storage
3106
+ );
3107
+ const dappConfiguredChains = Object.keys(
3108
+ this.options.api.supportedNetworks
3109
+ );
3110
+ analytics2.track("mmconnect_connection_initiated", __spreadProps(__spreadValues({}, baseProps), {
3111
+ transport_type: transportType,
3112
+ dapp_configured_chains: dappConfiguredChains,
3113
+ dapp_requested_chains: scopes
3114
+ }));
3115
+ } catch (error) {
3116
+ logger2("Error tracking connection_initiated event", error);
3117
+ }
2983
3118
  }
2984
3119
  const sessionData = yield __privateMethod(this, _MetaMaskConnectMultichain_instances, getCaipSession_fn).call(this);
2985
3120
  const { mergedScopes, mergedCaipAccountIds, mergedSessionProperties } = mergeRequestedSessionWithExisting(
@@ -2997,9 +3132,9 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
2997
3132
  forceRequest
2998
3133
  }).then(() => __async(this, null, function* () {
2999
3134
  if (__privateGet(this, _transportType) === "mwp" /* MWP */) {
3000
- return this.storage.setTransport("mwp" /* MWP */);
3135
+ return this.storage.setTransportType("mwp" /* MWP */);
3001
3136
  }
3002
- return this.storage.setTransport("browser" /* Browser */);
3137
+ return this.storage.setTransportType("browser" /* Browser */);
3003
3138
  })), scopes, transportType);
3004
3139
  }
3005
3140
  if (platformType === "in-app-browser" /* MetaMaskMobileWebview */) {
@@ -3028,11 +3163,6 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
3028
3163
  return __privateMethod(this, _MetaMaskConnectMultichain_instances, handleConnection_fn).call(this, __privateMethod(this, _MetaMaskConnectMultichain_instances, showInstallModal_fn).call(this, shouldShowInstallModal, mergedScopes, mergedCaipAccountIds, nonEmptySessionProperties), scopes, transportType);
3029
3164
  });
3030
3165
  }
3031
- emit(event, args) {
3032
- var _a2, _b;
3033
- (_b = (_a2 = this.options.transport) == null ? void 0 : _a2.onNotification) == null ? void 0 : _b.call(_a2, { method: event, params: args });
3034
- super.emit(event, args);
3035
- }
3036
3166
  disconnect() {
3037
3167
  return __async(this, arguments, function* (scopes = []) {
3038
3168
  var _a2, _b, _c;
@@ -3042,7 +3172,7 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
3042
3172
  );
3043
3173
  yield (_a2 = __privateGet(this, _transport2)) == null ? void 0 : _a2.disconnect(scopes);
3044
3174
  if (remainingScopes.length === 0) {
3045
- yield this.storage.removeTransport();
3175
+ yield this.storage.removeTransportType();
3046
3176
  if (__privateGet(this, _transportType) !== "browser" /* Browser */) {
3047
3177
  yield (_b = __privateGet(this, _listener)) == null ? void 0 : _b.call(this);
3048
3178
  (_c = __privateGet(this, _beforeUnloadListener)) == null ? void 0 : _c.call(this);
@@ -3060,7 +3190,8 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
3060
3190
  invokeMethod(request) {
3061
3191
  return __async(this, null, function* () {
3062
3192
  var _a2;
3063
- const { transport, options } = this;
3193
+ const transport = __privateMethod(this, _MetaMaskConnectMultichain_instances, transportOrThrow_fn).call(this);
3194
+ const { options } = this;
3064
3195
  const rpcClient = new RpcClient(options, __privateGet(this, _sdkInfo));
3065
3196
  const requestRouter = new RequestRouter(
3066
3197
  transport,
@@ -3079,7 +3210,7 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
3079
3210
  const shouldOpenDeeplink = secure && !showInstallModal;
3080
3211
  if (shouldOpenDeeplink) {
3081
3212
  setTimeout(() => __async(this, null, function* () {
3082
- const session = yield this.transport.getActiveSession();
3213
+ const session = yield __privateMethod(this, _MetaMaskConnectMultichain_instances, transportOrThrow_fn).call(this).getActiveSession();
3083
3214
  if (!session) {
3084
3215
  throw new Error("No active session found");
3085
3216
  }
@@ -3103,10 +3234,13 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
3103
3234
  this.emit("wallet_sessionChanged", emptySession);
3104
3235
  return;
3105
3236
  }
3106
- const response = yield this.transport.request({
3237
+ const response = yield __privateGet(this, _transport2).request({
3107
3238
  method: "wallet_getSession"
3108
3239
  });
3109
- this.emit("wallet_sessionChanged", (_b = response.result) != null ? _b : emptySession);
3240
+ this.emit(
3241
+ "wallet_sessionChanged",
3242
+ (_b = response.result) != null ? _b : emptySession
3243
+ );
3110
3244
  });
3111
3245
  }
3112
3246
  };
@@ -3118,34 +3252,19 @@ _beforeUnloadListener = new WeakMap();
3118
3252
  _transportType = new WeakMap();
3119
3253
  _listener = new WeakMap();
3120
3254
  _anonId = new WeakMap();
3121
- _sdkInfo = new WeakMap();
3122
3255
  _MetaMaskConnectMultichain_instances = new WeakSet();
3256
+ transportOrThrow_fn = function() {
3257
+ if (!__privateGet(this, _transport2)) {
3258
+ throw new Error("Transport not initialized, establish connection first");
3259
+ }
3260
+ return __privateGet(this, _transport2);
3261
+ };
3262
+ _sdkInfo = new WeakMap();
3123
3263
  setupAnalytics_fn = function() {
3124
3264
  return __async(this, null, function* () {
3125
- var _a2, _b;
3126
- const platform = getPlatformType();
3127
- const isBrowser = platform === "in-app-browser" /* MetaMaskMobileWebview */ || platform === "web-desktop" /* DesktopWeb */ || platform === "web-mobile" /* MobileWeb */;
3128
- const isReactNative2 = platform === "react-native" /* ReactNative */;
3129
- if (!isBrowser && !isReactNative2) {
3130
- return;
3131
- }
3132
- const dappId = getDappId(this.options.dapp);
3133
- const anonId = yield this.storage.getAnonId();
3134
- __privateSet(this, _anonId, anonId);
3135
- const { integrationType } = (_a2 = this.options.analytics) != null ? _a2 : {
3136
- integrationType: ""
3137
- };
3138
- analytics2.setGlobalProperty(
3139
- "mmconnect_versions",
3140
- (_b = this.options.versions) != null ? _b : {}
3141
- );
3142
- analytics2.setGlobalProperty("dapp_id", dappId);
3143
- analytics2.setGlobalProperty("anon_id", anonId);
3144
- analytics2.setGlobalProperty("platform", platform);
3145
- if (integrationType) {
3146
- analytics2.setGlobalProperty("integration_types", [integrationType]);
3147
- }
3148
- analytics2.enable();
3265
+ yield setupAnalyticsGlobals(this.options, this.storage, (anonId) => {
3266
+ __privateSet(this, _anonId, anonId);
3267
+ });
3149
3268
  });
3150
3269
  };
3151
3270
  onTransportNotification_fn = function(payload) {
@@ -3166,7 +3285,7 @@ onTransportNotification_fn = function(payload) {
3166
3285
  };
3167
3286
  getStoredTransport_fn = function() {
3168
3287
  return __async(this, null, function* () {
3169
- const transportType = yield this.storage.getTransport();
3288
+ const transportType = yield this.storage.getTransportType();
3170
3289
  const hasExtensionInstalled = yield hasExtension();
3171
3290
  if (transportType) {
3172
3291
  if (transportType === "browser" /* Browser */) {
@@ -3194,7 +3313,7 @@ getStoredTransport_fn = function() {
3194
3313
  ));
3195
3314
  return apiTransport;
3196
3315
  }
3197
- yield this.storage.removeTransport();
3316
+ yield this.storage.removeTransportType();
3198
3317
  }
3199
3318
  return void 0;
3200
3319
  });
@@ -3204,15 +3323,15 @@ setupTransport_fn = function() {
3204
3323
  var _a2;
3205
3324
  const transport = yield __privateMethod(this, _MetaMaskConnectMultichain_instances, getStoredTransport_fn).call(this);
3206
3325
  if (transport) {
3207
- if (!this.transport.isConnected()) {
3326
+ if (!transport.isConnected()) {
3208
3327
  this.status = "connecting";
3209
- yield this.transport.connect();
3328
+ yield transport.connect();
3210
3329
  }
3211
3330
  this.status = "connected";
3212
3331
  if (__privateGet(this, _transportType) === "mwp" /* MWP */) {
3213
- yield this.storage.setTransport("mwp" /* MWP */);
3332
+ yield this.storage.setTransportType("mwp" /* MWP */);
3214
3333
  } else {
3215
- yield this.storage.setTransport("browser" /* Browser */);
3334
+ yield this.storage.setTransportType("browser" /* Browser */);
3216
3335
  }
3217
3336
  } else {
3218
3337
  this.status = "loaded";
@@ -3221,7 +3340,7 @@ setupTransport_fn = function() {
3221
3340
  if (hasExtensionInstalled && preferExtension) {
3222
3341
  yield __privateMethod(this, _MetaMaskConnectMultichain_instances, setupDefaultTransport_fn).call(this, { persist: false });
3223
3342
  try {
3224
- yield this.transport.init();
3343
+ yield __privateMethod(this, _MetaMaskConnectMultichain_instances, transportOrThrow_fn).call(this).init();
3225
3344
  } catch (error) {
3226
3345
  console.error("Passive init failed:", error);
3227
3346
  }
@@ -3234,7 +3353,7 @@ buildConnectionMetadata_fn = function() {
3234
3353
  dapp: this.options.dapp,
3235
3354
  sdk: { version: getVersion(), platform: getPlatformType() }
3236
3355
  };
3237
- if (__privateGet(this, _anonId)) {
3356
+ if (isAnalyticsEnabled(this.options) && __privateGet(this, _anonId)) {
3238
3357
  metadata.analytics = { remote_session_id: __privateGet(this, _anonId) };
3239
3358
  }
3240
3359
  return metadata;
@@ -3245,7 +3364,7 @@ init_fn2 = function() {
3245
3364
  yield __privateMethod(this, _MetaMaskConnectMultichain_instances, setupAnalytics_fn).call(this);
3246
3365
  yield __privateMethod(this, _MetaMaskConnectMultichain_instances, setupTransport_fn).call(this);
3247
3366
  } catch (error) {
3248
- yield this.storage.removeTransport();
3367
+ yield this.storage.removeTransportType();
3249
3368
  this.status = "pending";
3250
3369
  logger2("MetaMaskSDK error during initialization", error);
3251
3370
  }
@@ -3291,17 +3410,17 @@ setupMWP_fn = function() {
3291
3410
  __privateSet(this, _transport2, apiTransport);
3292
3411
  __privateSet(this, _transportType, "mwp" /* MWP */);
3293
3412
  __privateGet(this, _providerTransportWrapper).setupTransportNotificationListener();
3294
- __privateSet(this, _listener, this.transport.onNotification(
3413
+ __privateSet(this, _listener, apiTransport.onNotification(
3295
3414
  __privateMethod(this, _MetaMaskConnectMultichain_instances, onTransportNotification_fn).bind(this)
3296
3415
  ));
3297
- yield this.storage.setTransport("mwp" /* MWP */);
3416
+ yield this.storage.setTransportType("mwp" /* MWP */);
3298
3417
  });
3299
3418
  };
3300
3419
  onBeforeUnload_fn = function() {
3301
3420
  return __async(this, null, function* () {
3302
3421
  var _a2;
3303
3422
  if ((_a2 = this.options.ui.factory.modal) == null ? void 0 : _a2.isMounted) {
3304
- yield this.storage.removeTransport();
3423
+ yield this.storage.removeTransportType();
3305
3424
  }
3306
3425
  });
3307
3426
  };
@@ -3318,70 +3437,65 @@ createBeforeUnloadListener_fn = function() {
3318
3437
  };
3319
3438
  renderInstallModalAsync_fn = function(desktopPreferred, scopes, caipAccountIds, sessionProperties) {
3320
3439
  return __async(this, null, function* () {
3321
- return new Promise((resolve, reject) => {
3322
- this.options.ui.factory.renderInstallModal(
3323
- desktopPreferred,
3324
- () => __async(this, null, function* () {
3325
- if (this.dappClient.state === "CONNECTED" || this.dappClient.state === "CONNECTING") {
3326
- yield this.dappClient.disconnect();
3327
- }
3328
- return new Promise((_resolve) => {
3329
- this.dappClient.on(
3330
- "session_request",
3331
- (sessionRequest) => {
3332
- _resolve({
3333
- sessionRequest,
3334
- metadata: __privateMethod(this, _MetaMaskConnectMultichain_instances, buildConnectionMetadata_fn).call(this)
3335
- });
3336
- }
3337
- );
3338
- (() => __async(this, null, function* () {
3339
- var _a2;
3340
- try {
3341
- yield this.transport.connect({
3342
- scopes,
3343
- caipAccountIds,
3344
- sessionProperties
3345
- });
3346
- yield this.options.ui.factory.unload();
3347
- (_a2 = this.options.ui.factory.modal) == null ? void 0 : _a2.unmount();
3348
- this.status = "connected";
3349
- yield this.storage.setTransport("mwp" /* MWP */);
3350
- } catch (error) {
3351
- const { ProtocolError, ErrorCode } = yield import("@metamask/mobile-wallet-protocol-core");
3352
- if (error instanceof ProtocolError) {
3353
- if (error.code !== ErrorCode.REQUEST_EXPIRED) {
3354
- this.status = "disconnected";
3355
- yield this.options.ui.factory.unload(error);
3356
- reject(error);
3357
- }
3358
- } else {
3359
- this.status = "disconnected";
3360
- const normalizedError = error instanceof Error ? error : new Error(String(error));
3361
- yield this.options.ui.factory.unload(normalizedError);
3362
- reject(normalizedError);
3363
- }
3364
- }
3365
- }))().catch(() => {
3366
- });
3440
+ const completion = createDeferredPromise2();
3441
+ const createConnectionRequest = () => __async(this, null, function* () {
3442
+ if (this.dappClient.state === "CONNECTED" || this.dappClient.state === "CONNECTING") {
3443
+ yield this.dappClient.disconnect();
3444
+ }
3445
+ const sessionRequestDeferred = createDeferredPromise2();
3446
+ this.dappClient.on(
3447
+ "session_request",
3448
+ (sessionRequest) => {
3449
+ sessionRequestDeferred.resolve({
3450
+ sessionRequest,
3451
+ metadata: __privateMethod(this, _MetaMaskConnectMultichain_instances, buildConnectionMetadata_fn).call(this)
3367
3452
  });
3368
- }),
3369
- (error) => __async(this, null, function* () {
3370
- if (error) {
3371
- yield this.storage.removeTransport();
3372
- reject(error);
3373
- } else {
3374
- yield this.storage.setTransport("mwp" /* MWP */);
3375
- resolve();
3453
+ }
3454
+ );
3455
+ __privateMethod(this, _MetaMaskConnectMultichain_instances, transportOrThrow_fn).call(this).connect({ scopes, caipAccountIds, sessionProperties }).then(() => __async(this, null, function* () {
3456
+ var _a2;
3457
+ yield this.options.ui.factory.unload();
3458
+ (_a2 = this.options.ui.factory.modal) == null ? void 0 : _a2.unmount();
3459
+ this.status = "connected";
3460
+ yield this.storage.setTransportType("mwp" /* MWP */);
3461
+ })).catch((error) => __async(this, null, function* () {
3462
+ const { ProtocolError, ErrorCode } = yield import("@metamask/mobile-wallet-protocol-core");
3463
+ if (error instanceof ProtocolError) {
3464
+ if (error.code !== ErrorCode.REQUEST_EXPIRED) {
3465
+ this.status = "disconnected";
3466
+ yield this.options.ui.factory.unload(error);
3467
+ completion.reject(error);
3376
3468
  }
3377
- }),
3378
- (uri) => {
3379
- this.emit("display_uri", uri);
3469
+ } else {
3470
+ this.status = "disconnected";
3471
+ const normalizedError = error instanceof Error ? error : new Error(String(error));
3472
+ yield this.options.ui.factory.unload(normalizedError);
3473
+ completion.reject(normalizedError);
3380
3474
  }
3381
- ).catch((error) => {
3382
- reject(error instanceof Error ? error : new Error(String(error)));
3383
- });
3475
+ }));
3476
+ return sessionRequestDeferred.promise;
3384
3477
  });
3478
+ this.options.ui.factory.renderInstallModal(
3479
+ desktopPreferred,
3480
+ createConnectionRequest,
3481
+ (error) => __async(this, null, function* () {
3482
+ if (error) {
3483
+ yield this.storage.removeTransportType();
3484
+ completion.reject(error);
3485
+ } else {
3486
+ yield this.storage.setTransportType("mwp" /* MWP */);
3487
+ completion.resolve();
3488
+ }
3489
+ }),
3490
+ (uri) => {
3491
+ this.emit("display_uri", uri);
3492
+ }
3493
+ ).catch((error) => {
3494
+ completion.reject(
3495
+ error instanceof Error ? error : new Error(String(error))
3496
+ );
3497
+ });
3498
+ return completion.promise;
3385
3499
  });
3386
3500
  };
3387
3501
  showInstallModal_fn = function(desktopPreferred, scopes, caipAccountIds, sessionProperties) {
@@ -3397,39 +3511,37 @@ showInstallModal_fn = function(desktopPreferred, scopes, caipAccountIds, session
3397
3511
  };
3398
3512
  headlessConnect_fn = function(scopes, caipAccountIds, sessionProperties) {
3399
3513
  return __async(this, null, function* () {
3400
- return new Promise((resolve, reject) => {
3401
- if (this.dappClient.state === "CONNECTED" || this.dappClient.state === "CONNECTING") {
3402
- this.dappClient.disconnect().catch(() => {
3403
- });
3514
+ if (this.dappClient.state === "CONNECTED" || this.dappClient.state === "CONNECTING") {
3515
+ yield this.dappClient.disconnect().catch(() => void 0);
3516
+ }
3517
+ const onSessionRequest = (sessionRequest) => {
3518
+ const connectionRequest = {
3519
+ sessionRequest,
3520
+ metadata: __privateMethod(this, _MetaMaskConnectMultichain_instances, buildConnectionMetadata_fn).call(this)
3521
+ };
3522
+ const deeplink = this.options.ui.factory.createConnectionDeeplink(connectionRequest);
3523
+ this.emit("display_uri", deeplink);
3524
+ };
3525
+ this.dappClient.on("session_request", onSessionRequest);
3526
+ try {
3527
+ yield __privateMethod(this, _MetaMaskConnectMultichain_instances, transportOrThrow_fn).call(this).connect({
3528
+ scopes,
3529
+ caipAccountIds,
3530
+ sessionProperties
3531
+ });
3532
+ this.status = "connected";
3533
+ yield this.storage.setTransportType("mwp" /* MWP */);
3534
+ } catch (error) {
3535
+ const { ProtocolError } = yield import("@metamask/mobile-wallet-protocol-core");
3536
+ this.status = "disconnected";
3537
+ yield this.storage.removeTransportType();
3538
+ if (error instanceof ProtocolError || error instanceof Error) {
3539
+ throw error;
3404
3540
  }
3405
- this.dappClient.on(
3406
- "session_request",
3407
- (sessionRequest) => {
3408
- const connectionRequest = {
3409
- sessionRequest,
3410
- metadata: __privateMethod(this, _MetaMaskConnectMultichain_instances, buildConnectionMetadata_fn).call(this)
3411
- };
3412
- const deeplink = this.options.ui.factory.createConnectionDeeplink(connectionRequest);
3413
- this.emit("display_uri", deeplink);
3414
- }
3415
- );
3416
- this.transport.connect({ scopes, caipAccountIds, sessionProperties }).then(() => __async(this, null, function* () {
3417
- this.status = "connected";
3418
- yield this.storage.setTransport("mwp" /* MWP */);
3419
- resolve();
3420
- })).catch((error) => __async(this, null, function* () {
3421
- const { ProtocolError } = yield import("@metamask/mobile-wallet-protocol-core");
3422
- if (error instanceof ProtocolError) {
3423
- this.status = "disconnected";
3424
- yield this.storage.removeTransport();
3425
- reject(error);
3426
- } else {
3427
- this.status = "disconnected";
3428
- yield this.storage.removeTransport();
3429
- reject(error instanceof Error ? error : new Error(String(error)));
3430
- }
3431
- }));
3432
- });
3541
+ throw new Error(String(error));
3542
+ } finally {
3543
+ this.dappClient.off("session_request", onSessionRequest);
3544
+ }
3433
3545
  });
3434
3546
  };
3435
3547
  setupDefaultTransport_fn = function() {
@@ -3438,7 +3550,7 @@ setupDefaultTransport_fn = function() {
3438
3550
  return __privateGet(this, _transport2);
3439
3551
  }
3440
3552
  if (options == null ? void 0 : options.persist) {
3441
- yield this.storage.setTransport("browser" /* Browser */);
3553
+ yield this.storage.setTransportType("browser" /* Browser */);
3442
3554
  }
3443
3555
  const transport = new DefaultTransport();
3444
3556
  __privateSet(this, _listener, transport.onNotification(
@@ -3471,7 +3583,7 @@ deeplinkConnect_fn = function(scopes, caipAccountIds, sessionProperties) {
3471
3583
  };
3472
3584
  this.dappClient.on("message", dappClientMessageHandler);
3473
3585
  let timeout;
3474
- if (this.transport.isConnected()) {
3586
+ if (__privateMethod(this, _MetaMaskConnectMultichain_instances, transportOrThrow_fn).call(this).isConnected()) {
3475
3587
  timeout = setTimeout(() => {
3476
3588
  this.openSimpleDeeplinkIfNeeded();
3477
3589
  }, 250);
@@ -3499,8 +3611,8 @@ deeplinkConnect_fn = function(scopes, caipAccountIds, sessionProperties) {
3499
3611
  }
3500
3612
  );
3501
3613
  }
3502
- return this.transport.connect({ scopes, caipAccountIds, sessionProperties }).then(resolve).catch((error) => __async(this, null, function* () {
3503
- yield this.storage.removeTransport();
3614
+ return __privateMethod(this, _MetaMaskConnectMultichain_instances, transportOrThrow_fn).call(this).connect({ scopes, caipAccountIds, sessionProperties }).then(resolve).catch((error) => __async(this, null, function* () {
3615
+ yield this.storage.removeTransportType();
3504
3616
  this.dappClient.off("message", dappClientMessageHandler);
3505
3617
  reject(error instanceof Error ? error : new Error(String(error)));
3506
3618
  })).finally(() => {
@@ -3516,38 +3628,42 @@ handleConnection_fn = function(promise, scopes, transportType) {
3516
3628
  this.status = "connecting";
3517
3629
  return promise.then(() => __async(this, null, function* () {
3518
3630
  this.status = "connected";
3519
- try {
3520
- const baseProps = yield getBaseAnalyticsProperties(
3521
- this.options,
3522
- this.storage
3523
- );
3524
- analytics2.track("mmconnect_connection_established", __spreadProps(__spreadValues({}, baseProps), {
3525
- transport_type: transportType,
3526
- user_permissioned_chains: scopes
3527
- }));
3528
- } catch (error) {
3529
- logger2("Error tracking connection_established event", error);
3631
+ if (isAnalyticsEnabled(this.options)) {
3632
+ try {
3633
+ const baseProps = yield getBaseAnalyticsProperties(
3634
+ this.options,
3635
+ this.storage
3636
+ );
3637
+ analytics2.track("mmconnect_connection_established", __spreadProps(__spreadValues({}, baseProps), {
3638
+ transport_type: transportType,
3639
+ user_permissioned_chains: scopes
3640
+ }));
3641
+ } catch (error) {
3642
+ logger2("Error tracking connection_established event", error);
3643
+ }
3530
3644
  }
3531
3645
  return void 0;
3532
3646
  })).catch((error) => __async(this, null, function* () {
3533
3647
  this.status = "disconnected";
3534
- try {
3535
- const baseProps = yield getBaseAnalyticsProperties(
3536
- this.options,
3537
- this.storage
3538
- );
3539
- const isRejection = isRejectionError(error);
3540
- if (isRejection) {
3541
- analytics2.track("mmconnect_connection_rejected", __spreadProps(__spreadValues({}, baseProps), {
3542
- transport_type: transportType
3543
- }));
3544
- } else {
3545
- analytics2.track("mmconnect_connection_failed", __spreadValues(__spreadProps(__spreadValues({}, baseProps), {
3546
- transport_type: transportType
3547
- }), extractErrorDiagnostics(error)));
3648
+ if (isAnalyticsEnabled(this.options)) {
3649
+ try {
3650
+ const baseProps = yield getBaseAnalyticsProperties(
3651
+ this.options,
3652
+ this.storage
3653
+ );
3654
+ const isRejection = isRejectionError(error);
3655
+ if (isRejection) {
3656
+ analytics2.track("mmconnect_connection_rejected", __spreadProps(__spreadValues({}, baseProps), {
3657
+ transport_type: transportType
3658
+ }));
3659
+ } else {
3660
+ analytics2.track("mmconnect_connection_failed", __spreadValues(__spreadProps(__spreadValues({}, baseProps), {
3661
+ transport_type: transportType
3662
+ }), extractErrorDiagnostics(error)));
3663
+ }
3664
+ } catch (e) {
3665
+ logger2("Error tracking connection failed/rejected event", error);
3548
3666
  }
3549
- } catch (e) {
3550
- logger2("Error tracking connection failed/rejected event", error);
3551
3667
  }
3552
3668
  throw error;
3553
3669
  }));
@@ -3562,7 +3678,7 @@ getCaipSession_fn = function() {
3562
3678
  };
3563
3679
  if ((_a2 = __privateGet(this, _transport2)) == null ? void 0 : _a2.isConnected()) {
3564
3680
  try {
3565
- const response = yield this.transport.request({
3681
+ const response = yield __privateGet(this, _transport2).request({
3566
3682
  method: "wallet_getSession"
3567
3683
  });
3568
3684
  if (response.result) {
@@ -3656,14 +3772,14 @@ var Store = class extends StoreClient {
3656
3772
  super();
3657
3773
  this.adapter = adapter;
3658
3774
  }
3659
- getTransport() {
3775
+ getTransportType() {
3660
3776
  return __async(this, null, function* () {
3661
3777
  try {
3662
- const transport = yield this.adapter.get("multichain-transport");
3663
- if (!transport) {
3778
+ const transportType = yield this.adapter.get("multichain-transport");
3779
+ if (!transportType) {
3664
3780
  return null;
3665
3781
  }
3666
- return getTransportType(transport);
3782
+ return getTransportType(transportType);
3667
3783
  } catch (err) {
3668
3784
  throw new StorageGetErr(
3669
3785
  this.adapter.platform,
@@ -3673,10 +3789,10 @@ var Store = class extends StoreClient {
3673
3789
  }
3674
3790
  });
3675
3791
  }
3676
- setTransport(transport) {
3792
+ setTransportType(transportType) {
3677
3793
  return __async(this, null, function* () {
3678
3794
  try {
3679
- yield this.adapter.set("multichain-transport", transport);
3795
+ yield this.adapter.set("multichain-transport", transportType);
3680
3796
  } catch (err) {
3681
3797
  throw new StorageSetErr(
3682
3798
  this.adapter.platform,
@@ -3686,7 +3802,7 @@ var Store = class extends StoreClient {
3686
3802
  }
3687
3803
  });
3688
3804
  }
3689
- removeTransport() {
3805
+ removeTransportType() {
3690
3806
  return __async(this, null, function* () {
3691
3807
  try {
3692
3808
  yield this.adapter.delete("multichain-transport");
@@ -3900,7 +4016,11 @@ var BaseModalFactory = class {
3900
4016
  (_a3 = this.displayUriCallback) == null ? void 0 : _a3.call(this, newLink);
3901
4017
  return newLink;
3902
4018
  }),
3903
- onClose: this.onCloseModal.bind(this),
4019
+ onClose: (shouldTerminate) => {
4020
+ this.onCloseModal(shouldTerminate).catch((error) => {
4021
+ console.error("Failed to close modal:", error);
4022
+ });
4023
+ },
3904
4024
  startDesktopOnboarding: this.onStartDesktopOnboarding.bind(this),
3905
4025
  createConnectionRequest,
3906
4026
  onDisplayUri: this.displayUriCallback
@@ -3938,7 +4058,7 @@ function preload() {
3938
4058
  }
3939
4059
  try {
3940
4060
  const { defineCustomElements } = yield import("@metamask/multichain-ui/loader");
3941
- yield defineCustomElements();
4061
+ defineCustomElements();
3942
4062
  } catch (error) {
3943
4063
  console.error("Failed to load customElements:", error);
3944
4064
  }
@@ -3976,6 +4096,7 @@ var createMultichainClient = (options) => __async(null, null, function* () {
3976
4096
  }));
3977
4097
  });
3978
4098
  export {
4099
+ EIP1193_PASSTHROUGH_METHODS,
3979
4100
  EventEmitter,
3980
4101
  Modal,
3981
4102
  MultichainCore,
@@ -4003,6 +4124,7 @@ export {
4003
4124
  isEnabled,
4004
4125
  isMetamaskExtensionInstalled,
4005
4126
  isRejectionError,
4006
- isSecure
4127
+ isSecure,
4128
+ packageVersion
4007
4129
  };
4008
4130
  //# sourceMappingURL=connect-multichain.mjs.map