@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
@@ -273,7 +273,7 @@ var init_logger = __esm({
273
273
  });
274
274
 
275
275
  // src/domain/multichain/api/constants.ts
276
- var infuraRpcUrls, RPC_HANDLED_METHODS, SDK_HANDLED_METHODS;
276
+ var infuraRpcUrls, RPC_HANDLED_METHODS, SDK_HANDLED_METHODS, EIP1193_PASSTHROUGH_METHODS;
277
277
  var init_constants = __esm({
278
278
  "src/domain/multichain/api/constants.ts"() {
279
279
  "use strict";
@@ -438,6 +438,11 @@ var init_constants = __esm({
438
438
  "eth_uninstallFilter"
439
439
  ]);
440
440
  SDK_HANDLED_METHODS = /* @__PURE__ */ new Set(["eth_accounts", "eth_chainId"]);
441
+ EIP1193_PASSTHROUGH_METHODS = /* @__PURE__ */ new Set([
442
+ "wallet_addEthereumChain",
443
+ "wallet_switchEthereumChain",
444
+ "eth_accounts"
445
+ ]);
441
446
  }
442
447
  });
443
448
 
@@ -493,7 +498,7 @@ var init_multichain = __esm({
493
498
  }
494
499
  /**
495
500
  * Merges the given options into the current instance options.
496
- * Only the mergeable keys are updated (api.supportedNetworks, versions, ui.*, mobile.*, transport.extensionId, debug).
501
+ * Only the mergeable keys are updated (api.supportedNetworks, analytics, versions, ui.*, mobile.*, transport.extensionId, debug).
497
502
  * The main thing to note is that the value for `dapp` is not merged as it does not make sense for
498
503
  * subsequent calls to `createMultichainClient` to have a different `dapp` value.
499
504
  * Used when createMultichainClient is called with an existing singleton.
@@ -501,23 +506,28 @@ var init_multichain = __esm({
501
506
  * @param partial - Options to merge/overwrite onto the current instance
502
507
  */
503
508
  mergeOptions(partial) {
504
- var _a2, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o;
509
+ var _a2, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q;
505
510
  const opts = this.options;
511
+ const analytics3 = __spreadValues(__spreadValues({}, opts.analytics), (_a2 = partial.analytics) != null ? _a2 : {});
512
+ if (((_b = opts.analytics) == null ? void 0 : _b.enabled) === false) {
513
+ analytics3.enabled = false;
514
+ }
506
515
  this.options = __spreadProps(__spreadValues({}, opts), {
507
516
  api: __spreadProps(__spreadValues({}, opts.api), {
508
- supportedNetworks: __spreadValues(__spreadValues({}, opts.api.supportedNetworks), (_b = (_a2 = partial.api) == null ? void 0 : _a2.supportedNetworks) != null ? _b : {})
517
+ supportedNetworks: __spreadValues(__spreadValues({}, opts.api.supportedNetworks), (_d = (_c = partial.api) == null ? void 0 : _c.supportedNetworks) != null ? _d : {})
509
518
  }),
510
- versions: __spreadValues(__spreadValues({}, opts.versions), (_c = partial.versions) != null ? _c : {}),
519
+ versions: __spreadValues(__spreadValues({}, opts.versions), (_e = partial.versions) != null ? _e : {}),
520
+ analytics: __spreadValues({}, analytics3),
511
521
  ui: __spreadProps(__spreadValues({}, opts.ui), {
512
- headless: (_e = (_d = partial.ui) == null ? void 0 : _d.headless) != null ? _e : opts.ui.headless,
513
- preferExtension: (_g = (_f = partial.ui) == null ? void 0 : _f.preferExtension) != null ? _g : opts.ui.preferExtension,
514
- showInstallModal: (_i = (_h = partial.ui) == null ? void 0 : _h.showInstallModal) != null ? _i : opts.ui.showInstallModal
522
+ headless: (_g = (_f = partial.ui) == null ? void 0 : _f.headless) != null ? _g : opts.ui.headless,
523
+ preferExtension: (_i = (_h = partial.ui) == null ? void 0 : _h.preferExtension) != null ? _i : opts.ui.preferExtension,
524
+ showInstallModal: (_k = (_j = partial.ui) == null ? void 0 : _j.showInstallModal) != null ? _k : opts.ui.showInstallModal
515
525
  }),
516
- mobile: __spreadValues(__spreadValues({}, opts.mobile), (_j = partial.mobile) != null ? _j : {}),
517
- transport: __spreadProps(__spreadValues({}, (_k = opts.transport) != null ? _k : {}), {
518
- extensionId: (_n = (_l = partial.transport) == null ? void 0 : _l.extensionId) != null ? _n : (_m = opts.transport) == null ? void 0 : _m.extensionId
526
+ mobile: __spreadValues(__spreadValues({}, opts.mobile), (_l = partial.mobile) != null ? _l : {}),
527
+ transport: __spreadProps(__spreadValues({}, (_m = opts.transport) != null ? _m : {}), {
528
+ extensionId: (_p = (_n = partial.transport) == null ? void 0 : _n.extensionId) != null ? _p : (_o = opts.transport) == null ? void 0 : _o.extensionId
519
529
  }),
520
- debug: (_o = partial.debug) != null ? _o : opts.debug
530
+ debug: (_q = partial.debug) != null ? _q : opts.debug
521
531
  });
522
532
  }
523
533
  };
@@ -582,7 +592,7 @@ function hasExtension() {
582
592
  return detectionPromise;
583
593
  });
584
594
  }
585
- var import_bowser, PlatformType, detectionPromise;
595
+ var import_bowser, PlatformType, NATIVE_METAMASK_EIP6963_RDNS, detectionPromise;
586
596
  var init_platform = __esm({
587
597
  "src/domain/platform/index.ts"() {
588
598
  "use strict";
@@ -595,6 +605,10 @@ var init_platform = __esm({
595
605
  PlatformType2["ReactNative"] = "react-native";
596
606
  return PlatformType2;
597
607
  })(PlatformType || {});
608
+ NATIVE_METAMASK_EIP6963_RDNS = /* @__PURE__ */ new Set([
609
+ "io.metamask",
610
+ "io.metamask.mobile"
611
+ ]);
598
612
  detectionPromise = (() => __async(null, null, function* () {
599
613
  const pt = getPlatformType();
600
614
  if (pt === "nodejs" /* NonBrowser */ || pt === "react-native" /* ReactNative */) {
@@ -602,23 +616,30 @@ var init_platform = __esm({
602
616
  }
603
617
  return new Promise((resolve) => {
604
618
  const providers = [];
619
+ const targetWindow = window;
605
620
  const handler = (event) => {
606
621
  var _a2, _b;
607
622
  if ((_b = (_a2 = event == null ? void 0 : event.detail) == null ? void 0 : _a2.info) == null ? void 0 : _b.rdns) {
608
623
  providers.push(event.detail);
609
624
  }
610
625
  };
611
- window.addEventListener("eip6963:announceProvider", handler);
612
- window.dispatchEvent(new Event("eip6963:requestProvider"));
626
+ targetWindow.addEventListener("eip6963:announceProvider", handler);
627
+ targetWindow.dispatchEvent(new Event("eip6963:requestProvider"));
613
628
  setTimeout(() => {
614
- window.removeEventListener("eip6963:announceProvider", handler);
615
- const hasMetaMask = providers.some(
616
- (provider) => {
617
- var _a2, _b;
618
- return (_b = (_a2 = provider == null ? void 0 : provider.info) == null ? void 0 : _a2.rdns) == null ? void 0 : _b.startsWith("io.metamask");
629
+ try {
630
+ if (typeof (targetWindow == null ? void 0 : targetWindow.removeEventListener) === "function") {
631
+ targetWindow.removeEventListener("eip6963:announceProvider", handler);
619
632
  }
620
- );
621
- resolve(hasMetaMask);
633
+ const hasMetaMask = providers.some(
634
+ (provider) => {
635
+ var _a2;
636
+ return typeof ((_a2 = provider == null ? void 0 : provider.info) == null ? void 0 : _a2.rdns) === "string" && NATIVE_METAMASK_EIP6963_RDNS.has(provider.info.rdns);
637
+ }
638
+ );
639
+ resolve(hasMetaMask);
640
+ } catch (e) {
641
+ resolve(false);
642
+ }
622
643
  }, 300);
623
644
  });
624
645
  }))();
@@ -1130,12 +1151,14 @@ var init_analytics = __esm({
1130
1151
 
1131
1152
  // src/domain/utils/index.ts
1132
1153
  function getVersion() {
1133
- return "0.0.0";
1154
+ return packageVersion;
1134
1155
  }
1156
+ var packageVersion;
1135
1157
  var init_utils2 = __esm({
1136
1158
  "src/domain/utils/index.ts"() {
1137
1159
  "use strict";
1138
1160
  init_analytics();
1161
+ packageVersion = false ? "unknown" : "1.0.0";
1139
1162
  }
1140
1163
  });
1141
1164
 
@@ -1168,12 +1191,13 @@ var mwp_exports = {};
1168
1191
  __export(mwp_exports, {
1169
1192
  MWPTransport: () => MWPTransport
1170
1193
  });
1171
- var import_multichain_api_client2, import_rpc_errors2, 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;
1194
+ var import_multichain_api_client2, import_rpc_errors2, import_utils5, 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;
1172
1195
  var init_mwp = __esm({
1173
1196
  "src/multichain/transports/mwp/index.ts"() {
1174
1197
  "use strict";
1175
1198
  import_multichain_api_client2 = require("@metamask/multichain-api-client");
1176
1199
  import_rpc_errors2 = require("@metamask/rpc-errors");
1200
+ import_utils5 = require("@metamask/utils");
1177
1201
  init_domain();
1178
1202
  init_utils();
1179
1203
  init_constants2();
@@ -1204,6 +1228,7 @@ var init_mwp = __esm({
1204
1228
  this.dappClient = dappClient;
1205
1229
  this.kvstore = kvstore;
1206
1230
  this.options = options;
1231
+ __privateAdd(this, _MWPTransport_instances);
1207
1232
  this.__pendingRequests = /* @__PURE__ */ new Map();
1208
1233
  this.notificationCallbacks = /* @__PURE__ */ new Set();
1209
1234
  this.dappClient.on("message", this.handleMessage.bind(this));
@@ -1283,6 +1308,23 @@ var init_mwp = __esm({
1283
1308
  const message = errorPayload instanceof Error ? errorPayload.message : JSON.stringify(errorPayload);
1284
1309
  return import_rpc_errors2.rpcErrors.internal({ message });
1285
1310
  }
1311
+ getResponseError(messagePayload) {
1312
+ if ("error" in messagePayload && messagePayload.error) {
1313
+ return messagePayload.error;
1314
+ }
1315
+ const { result } = messagePayload;
1316
+ if (typeof result === "object" && result !== null && "error" in result && result.error && this.isErrorPayload(result.error)) {
1317
+ return result.error;
1318
+ }
1319
+ return void 0;
1320
+ }
1321
+ isErrorPayload(errorPayload) {
1322
+ if (errorPayload instanceof Error) {
1323
+ return true;
1324
+ }
1325
+ const errorData = errorPayload;
1326
+ return typeof (errorData == null ? void 0 : errorData.code) === "number" && typeof (errorData == null ? void 0 : errorData.message) === "string";
1327
+ }
1286
1328
  handleMessage(message) {
1287
1329
  if (typeof message === "object" && message !== null) {
1288
1330
  if ("data" in message) {
@@ -1291,9 +1333,10 @@ var init_mwp = __esm({
1291
1333
  const request = this.pendingRequests.get(messagePayload.id);
1292
1334
  if (request) {
1293
1335
  clearTimeout(request.timeout);
1294
- if ("error" in messagePayload && messagePayload.error) {
1336
+ const responseError = this.getResponseError(messagePayload);
1337
+ if (responseError) {
1295
1338
  this.pendingRequests.delete(messagePayload.id);
1296
- request.reject(this.parseWalletError(messagePayload.error));
1339
+ request.reject(this.parseWalletError(responseError));
1297
1340
  return;
1298
1341
  }
1299
1342
  const requestWithName = __spreadProps(__spreadValues({}, messagePayload), {
@@ -1336,73 +1379,6 @@ var init_mwp = __esm({
1336
1379
  }
1337
1380
  }
1338
1381
  }
1339
- onResumeSuccess(resumeResolve, resumeReject, options) {
1340
- return __async(this, null, function* () {
1341
- var _a2, _b, _c, _d, _e, _f, _g;
1342
- try {
1343
- yield this.waitForWalletSessionIfNotCached();
1344
- const sessionRequest = yield this.request({
1345
- method: "wallet_getSession"
1346
- });
1347
- if (sessionRequest.error) {
1348
- return resumeReject(new Error(sessionRequest.error.message));
1349
- }
1350
- let walletSession = sessionRequest.result;
1351
- if (walletSession && options) {
1352
- const currentScopes = Object.keys(
1353
- (_a2 = walletSession == null ? void 0 : walletSession.sessionScopes) != null ? _a2 : {}
1354
- );
1355
- const proposedScopes = (_b = options == null ? void 0 : options.scopes) != null ? _b : [];
1356
- const proposedCaipAccountIds = (_c = options == null ? void 0 : options.caipAccountIds) != null ? _c : [];
1357
- const hasSameScopesAndAccounts = isSameScopesAndAccounts(
1358
- currentScopes,
1359
- proposedScopes,
1360
- walletSession,
1361
- proposedCaipAccountIds
1362
- );
1363
- if (options.forceRequest || !hasSameScopesAndAccounts) {
1364
- const optionalScopes = addValidAccounts(
1365
- getOptionalScopes((_d = options == null ? void 0 : options.scopes) != null ? _d : []),
1366
- getValidAccounts((_e = options == null ? void 0 : options.caipAccountIds) != null ? _e : [])
1367
- );
1368
- const sessionRequest2 = {
1369
- optionalScopes
1370
- };
1371
- const response = yield this.request({
1372
- method: "wallet_createSession",
1373
- params: sessionRequest2
1374
- });
1375
- if (response.error) {
1376
- return resumeReject(new Error(response.error.message));
1377
- }
1378
- walletSession = response.result;
1379
- }
1380
- } else if (!walletSession) {
1381
- const optionalScopes = addValidAccounts(
1382
- getOptionalScopes((_f = options == null ? void 0 : options.scopes) != null ? _f : []),
1383
- getValidAccounts((_g = options == null ? void 0 : options.caipAccountIds) != null ? _g : [])
1384
- );
1385
- const sessionRequest2 = { optionalScopes };
1386
- const response = yield this.request({
1387
- method: "wallet_createSession",
1388
- params: sessionRequest2
1389
- });
1390
- if (response.error) {
1391
- return resumeReject(new Error(response.error.message));
1392
- }
1393
- walletSession = response.result;
1394
- }
1395
- yield this.removeStoredPendingSessionRequest();
1396
- this.notifyCallbacks({
1397
- method: "wallet_sessionChanged",
1398
- params: walletSession
1399
- });
1400
- return resumeResolve();
1401
- } catch (err) {
1402
- return resumeReject(err);
1403
- }
1404
- });
1405
- }
1406
1382
  init() {
1407
1383
  return __async(this, null, function* () {
1408
1384
  });
@@ -1443,7 +1419,6 @@ var init_mwp = __esm({
1443
1419
  }
1444
1420
  connect(options) {
1445
1421
  return __async(this, null, function* () {
1446
- const { dappClient } = this;
1447
1422
  const session = yield this.getActiveSession();
1448
1423
  if (session) {
1449
1424
  logger("active session found", {
@@ -1452,116 +1427,11 @@ var init_mwp = __esm({
1452
1427
  expiresAt: session.expiresAt
1453
1428
  });
1454
1429
  }
1455
- const storedSessionRequestBeforeConnectionAttempt = yield this.getStoredPendingSessionRequest();
1456
- let timeout;
1457
- let initialConnectionMessageHandler;
1458
- const connectionPromise = new Promise((resolve, reject) => __async(this, null, function* () {
1459
- let connection;
1460
- if (session) {
1461
- connection = new Promise((resumeResolve, resumeReject) => {
1462
- var _a2;
1463
- if (this.dappClient.state === "CONNECTED") {
1464
- this.onResumeSuccess(resumeResolve, resumeReject, options);
1465
- } else {
1466
- this.dappClient.once("connected", () => __async(this, null, function* () {
1467
- this.onResumeSuccess(resumeResolve, resumeReject, options);
1468
- }));
1469
- dappClient.resume((_a2 = session == null ? void 0 : session.id) != null ? _a2 : "");
1470
- }
1471
- });
1472
- } else {
1473
- connection = new Promise(
1474
- (resolveConnection, rejectConnection) => {
1475
- var _a2, _b;
1476
- const optionalScopes = addValidAccounts(
1477
- getOptionalScopes((_a2 = options == null ? void 0 : options.scopes) != null ? _a2 : []),
1478
- getValidAccounts((_b = options == null ? void 0 : options.caipAccountIds) != null ? _b : [])
1479
- );
1480
- const sessionRequest = {
1481
- optionalScopes,
1482
- sessionProperties: options == null ? void 0 : options.sessionProperties
1483
- };
1484
- const request = {
1485
- jsonrpc: "2.0",
1486
- id: String(getUniqueRequestId()),
1487
- method: "wallet_createSession",
1488
- params: sessionRequest
1489
- };
1490
- initialConnectionMessageHandler = (message) => __async(this, null, function* () {
1491
- if (typeof message !== "object" || message === null) {
1492
- return;
1493
- }
1494
- if (!("data" in message)) {
1495
- return;
1496
- }
1497
- const messagePayload = message.data;
1498
- const isMatchingId = messagePayload.id === request.id;
1499
- const isMatchingMethod = messagePayload.method === "wallet_createSession" || messagePayload.method === "wallet_sessionChanged";
1500
- if (!isMatchingId && !isMatchingMethod) {
1501
- return;
1502
- }
1503
- if (messagePayload.error) {
1504
- return rejectConnection(
1505
- this.parseWalletError(messagePayload.error)
1506
- );
1507
- }
1508
- yield this.storeWalletSession(
1509
- request,
1510
- messagePayload
1511
- );
1512
- yield this.removeStoredPendingSessionRequest();
1513
- this.notifyCallbacks(messagePayload);
1514
- return resolveConnection();
1515
- });
1516
- this.dappClient.on("message", initialConnectionMessageHandler);
1517
- const platformType = getPlatformType();
1518
- const isQRCodeFlow = [
1519
- "web-desktop" /* DesktopWeb */,
1520
- "nodejs" /* NonBrowser */
1521
- ].includes(platformType);
1522
- const initialPayload = {
1523
- name: MULTICHAIN_PROVIDER_STREAM_NAME,
1524
- data: request
1525
- };
1526
- dappClient.connect({
1527
- mode: "trusted",
1528
- initialPayload: isQRCodeFlow ? void 0 : initialPayload
1529
- }).then(() => __async(this, null, function* () {
1530
- if (isQRCodeFlow) {
1531
- return dappClient.sendRequest(initialPayload);
1532
- }
1533
- return void 0;
1534
- })).catch((error) => {
1535
- if (initialConnectionMessageHandler) {
1536
- this.dappClient.off(
1537
- "message",
1538
- initialConnectionMessageHandler
1539
- );
1540
- }
1541
- rejectConnection(error);
1542
- });
1543
- }
1544
- );
1545
- }
1546
- timeout = setTimeout(
1547
- () => {
1548
- reject(new import_multichain_api_client2.TransportTimeoutError());
1549
- },
1550
- storedSessionRequestBeforeConnectionAttempt ? this.options.resumeTimeout : this.options.connectionTimeout
1551
- );
1552
- connection.then(resolve).catch(reject);
1553
- }));
1554
- return connectionPromise.catch((error) => __async(this, null, function* () {
1430
+ const connection = session ? __privateMethod(this, _MWPTransport_instances, resumeSession_fn).call(this, session, options) : __privateMethod(this, _MWPTransport_instances, startSession_fn).call(this, options);
1431
+ return connection.catch((error) => __async(this, null, function* () {
1555
1432
  yield this.dappClient.disconnect();
1556
1433
  throw error;
1557
1434
  })).finally(() => {
1558
- if (timeout) {
1559
- clearTimeout(timeout);
1560
- }
1561
- if (initialConnectionMessageHandler) {
1562
- this.dappClient.off("message", initialConnectionMessageHandler);
1563
- initialConnectionMessageHandler = void 0;
1564
- }
1565
1435
  this.removeStoredPendingSessionRequest();
1566
1436
  });
1567
1437
  });
@@ -1820,6 +1690,188 @@ var init_mwp = __esm({
1820
1690
  });
1821
1691
  }
1822
1692
  };
1693
+ _MWPTransport_instances = new WeakSet();
1694
+ onResumeHandler_fn = function(options) {
1695
+ return __async(this, null, function* () {
1696
+ var _a2, _b, _c, _d, _e, _f, _g;
1697
+ yield this.waitForWalletSessionIfNotCached();
1698
+ const sessionResponse = yield this.request({ method: "wallet_getSession" });
1699
+ if (sessionResponse.error) {
1700
+ throw new Error(sessionResponse.error.message);
1701
+ }
1702
+ let walletSession = sessionResponse.result;
1703
+ if (walletSession && options) {
1704
+ const currentScopes = Object.keys(
1705
+ (_a2 = walletSession == null ? void 0 : walletSession.sessionScopes) != null ? _a2 : {}
1706
+ );
1707
+ const proposedScopes = (_b = options == null ? void 0 : options.scopes) != null ? _b : [];
1708
+ const proposedCaipAccountIds = (_c = options == null ? void 0 : options.caipAccountIds) != null ? _c : [];
1709
+ const hasSameScopesAndAccounts = isSameScopesAndAccounts(
1710
+ currentScopes,
1711
+ proposedScopes,
1712
+ walletSession,
1713
+ proposedCaipAccountIds
1714
+ );
1715
+ if (options.forceRequest || !hasSameScopesAndAccounts) {
1716
+ const optionalScopes = addValidAccounts(
1717
+ getOptionalScopes((_d = options == null ? void 0 : options.scopes) != null ? _d : []),
1718
+ getValidAccounts((_e = options == null ? void 0 : options.caipAccountIds) != null ? _e : [])
1719
+ );
1720
+ const sessionRequest = {
1721
+ optionalScopes
1722
+ };
1723
+ const response = yield this.request({
1724
+ method: "wallet_createSession",
1725
+ params: sessionRequest
1726
+ });
1727
+ if (response.error) {
1728
+ throw new Error(response.error.message);
1729
+ }
1730
+ walletSession = response.result;
1731
+ }
1732
+ } else if (!walletSession) {
1733
+ const optionalScopes = addValidAccounts(
1734
+ getOptionalScopes((_f = options == null ? void 0 : options.scopes) != null ? _f : []),
1735
+ getValidAccounts((_g = options == null ? void 0 : options.caipAccountIds) != null ? _g : [])
1736
+ );
1737
+ const sessionRequest = {
1738
+ optionalScopes
1739
+ };
1740
+ const response = yield this.request({
1741
+ method: "wallet_createSession",
1742
+ params: sessionRequest
1743
+ });
1744
+ if (response.error) {
1745
+ throw new Error(response.error.message);
1746
+ }
1747
+ walletSession = response.result;
1748
+ }
1749
+ yield this.removeStoredPendingSessionRequest();
1750
+ this.notifyCallbacks({
1751
+ method: "wallet_sessionChanged",
1752
+ params: walletSession
1753
+ });
1754
+ });
1755
+ };
1756
+ resumeSession_fn = function(session, options) {
1757
+ return __async(this, null, function* () {
1758
+ var _a2;
1759
+ const isContinuingPriorAttempt = (yield this.getStoredPendingSessionRequest()) !== null;
1760
+ const resumeDeferred = (0, import_utils5.createDeferredPromise)();
1761
+ const runOnResumeHandler = () => __async(this, null, function* () {
1762
+ try {
1763
+ resumeDeferred.resolve(yield __privateMethod(this, _MWPTransport_instances, onResumeHandler_fn).call(this, options));
1764
+ } catch (err) {
1765
+ resumeDeferred.reject(err);
1766
+ }
1767
+ });
1768
+ if (this.dappClient.state === "CONNECTED") {
1769
+ runOnResumeHandler();
1770
+ } else {
1771
+ this.dappClient.once("connected", runOnResumeHandler);
1772
+ this.dappClient.resume((_a2 = session.id) != null ? _a2 : "").catch((err) => resumeDeferred.reject(err));
1773
+ }
1774
+ const timeoutDeferred = (0, import_utils5.createDeferredPromise)();
1775
+ const timeout = setTimeout(
1776
+ () => timeoutDeferred.reject(new import_multichain_api_client2.TransportTimeoutError()),
1777
+ isContinuingPriorAttempt ? this.options.resumeTimeout : this.options.connectionTimeout
1778
+ );
1779
+ const cleanup = () => this.dappClient.off("connected", runOnResumeHandler);
1780
+ return Promise.race([
1781
+ resumeDeferred.promise,
1782
+ timeoutDeferred.promise
1783
+ ]).finally(() => {
1784
+ clearTimeout(timeout);
1785
+ cleanup();
1786
+ });
1787
+ });
1788
+ };
1789
+ startSession_fn = function(options) {
1790
+ return __async(this, null, function* () {
1791
+ var _a2, _b;
1792
+ const { dappClient } = this;
1793
+ const isContinuingPriorAttempt = (yield this.getStoredPendingSessionRequest()) !== null;
1794
+ const connDeferred = (0, import_utils5.createDeferredPromise)();
1795
+ const optionalScopes = addValidAccounts(
1796
+ getOptionalScopes((_a2 = options == null ? void 0 : options.scopes) != null ? _a2 : []),
1797
+ getValidAccounts((_b = options == null ? void 0 : options.caipAccountIds) != null ? _b : [])
1798
+ );
1799
+ const sessionRequest = {
1800
+ optionalScopes,
1801
+ sessionProperties: options == null ? void 0 : options.sessionProperties
1802
+ };
1803
+ const request = {
1804
+ jsonrpc: "2.0",
1805
+ id: String(getUniqueRequestId()),
1806
+ method: "wallet_createSession",
1807
+ params: sessionRequest
1808
+ };
1809
+ let handler;
1810
+ const removeHandler = () => {
1811
+ if (handler) {
1812
+ this.dappClient.off("message", handler);
1813
+ handler = void 0;
1814
+ }
1815
+ };
1816
+ handler = (message) => __async(this, null, function* () {
1817
+ if (typeof message !== "object" || message === null) {
1818
+ return;
1819
+ }
1820
+ if (!("data" in message)) {
1821
+ return;
1822
+ }
1823
+ const messagePayload = message.data;
1824
+ const isMatchingId = messagePayload.id === request.id;
1825
+ const isMatchingMethod = messagePayload.method === "wallet_createSession" || messagePayload.method === "wallet_sessionChanged";
1826
+ if (!isMatchingId && !isMatchingMethod) {
1827
+ return;
1828
+ }
1829
+ const responseError = this.getResponseError(messagePayload);
1830
+ if (responseError) {
1831
+ connDeferred.reject(this.parseWalletError(responseError));
1832
+ return;
1833
+ }
1834
+ yield this.storeWalletSession(
1835
+ request,
1836
+ messagePayload
1837
+ );
1838
+ yield this.removeStoredPendingSessionRequest();
1839
+ this.notifyCallbacks(messagePayload);
1840
+ connDeferred.resolve();
1841
+ });
1842
+ this.dappClient.on("message", handler);
1843
+ const platformType = getPlatformType();
1844
+ const isQRCodeFlow = [
1845
+ "web-desktop" /* DesktopWeb */,
1846
+ "nodejs" /* NonBrowser */
1847
+ ].includes(platformType);
1848
+ const initialPayload = {
1849
+ name: MULTICHAIN_PROVIDER_STREAM_NAME,
1850
+ data: request
1851
+ };
1852
+ dappClient.connect({
1853
+ mode: "trusted",
1854
+ initialPayload: isQRCodeFlow ? void 0 : initialPayload
1855
+ }).then(() => __async(this, null, function* () {
1856
+ if (isQRCodeFlow) {
1857
+ return dappClient.sendRequest(initialPayload);
1858
+ }
1859
+ return void 0;
1860
+ })).catch((error) => connDeferred.reject(error));
1861
+ const timeoutDeferred = (0, import_utils5.createDeferredPromise)();
1862
+ const timeout = setTimeout(
1863
+ () => timeoutDeferred.reject(new import_multichain_api_client2.TransportTimeoutError()),
1864
+ isContinuingPriorAttempt ? this.options.resumeTimeout : this.options.connectionTimeout
1865
+ );
1866
+ return Promise.race([
1867
+ connDeferred.promise,
1868
+ timeoutDeferred.promise
1869
+ ]).finally(() => {
1870
+ clearTimeout(timeout);
1871
+ removeHandler();
1872
+ });
1873
+ });
1874
+ };
1823
1875
  }
1824
1876
  });
1825
1877
 
@@ -2124,6 +2176,7 @@ var init_node2 = __esm({
2124
2176
  // src/index.node.ts
2125
2177
  var index_node_exports = {};
2126
2178
  __export(index_node_exports, {
2179
+ EIP1193_PASSTHROUGH_METHODS: () => EIP1193_PASSTHROUGH_METHODS,
2127
2180
  EventEmitter: () => EventEmitter,
2128
2181
  Modal: () => Modal,
2129
2182
  MultichainCore: () => MultichainCore,
@@ -2151,7 +2204,8 @@ __export(index_node_exports, {
2151
2204
  isEnabled: () => isEnabled,
2152
2205
  isMetamaskExtensionInstalled: () => isMetamaskExtensionInstalled,
2153
2206
  isRejectionError: () => isRejectionError,
2154
- isSecure: () => isSecure
2207
+ isSecure: () => isSecure,
2208
+ packageVersion: () => packageVersion
2155
2209
  });
2156
2210
  module.exports = __toCommonJS(index_node_exports);
2157
2211
  init_domain();
@@ -2159,6 +2213,7 @@ init_domain();
2159
2213
  // src/multichain/index.ts
2160
2214
  var import_analytics4 = require("@metamask/analytics");
2161
2215
  var import_multichain_api_client3 = require("@metamask/multichain-api-client");
2216
+ var import_utils7 = require("@metamask/utils");
2162
2217
 
2163
2218
  // src/config/index.ts
2164
2219
  var MWP_RELAY_URL = "wss://mm-sdk-relay.api.cx.metamask.io/connection/websocket";
@@ -2282,6 +2337,17 @@ var import_analytics2 = require("@metamask/analytics");
2282
2337
  init_domain();
2283
2338
  init_utils();
2284
2339
  init_analytics();
2340
+ function toRPCInvokeMethodErr(error) {
2341
+ var _a2;
2342
+ if (error instanceof RPCInvokeMethodErr) {
2343
+ return error;
2344
+ }
2345
+ const castError = error;
2346
+ return new RPCInvokeMethodErr(
2347
+ (_a2 = castError.message) != null ? _a2 : "Unknown error",
2348
+ castError.code
2349
+ );
2350
+ }
2285
2351
  var _RequestRouter_instances, withAnalyticsTracking_fn, trackWalletActionRequested_fn, trackWalletActionSucceeded_fn, trackWalletActionFailed_fn, trackWalletActionRejected_fn;
2286
2352
  var RequestRouter = class {
2287
2353
  constructor(transport, rpcClient, config, transportType) {
@@ -2301,6 +2367,9 @@ var RequestRouter = class {
2301
2367
  invokeMethod(options) {
2302
2368
  return __async(this, null, function* () {
2303
2369
  const { method } = options.request;
2370
+ if (EIP1193_PASSTHROUGH_METHODS.has(method)) {
2371
+ return this.handleWithEip1193Passthrough(options);
2372
+ }
2304
2373
  if (RPC_HANDLED_METHODS.has(method)) {
2305
2374
  return this.handleWithRpcNode(options);
2306
2375
  }
@@ -2310,6 +2379,29 @@ var RequestRouter = class {
2310
2379
  return this.handleWithWallet(options);
2311
2380
  });
2312
2381
  }
2382
+ /**
2383
+ * Forwards EIP-1193 / legacy provider methods (e.g. `wallet_addEthereumChain`,
2384
+ * `wallet_switchEthereumChain`, `eth_accounts`) directly to the underlying
2385
+ * transport's `sendEip1193Message`, bypassing the multichain
2386
+ * `wallet_invokeMethod` envelope. These methods are wallet-side concerns the
2387
+ * Multichain API does not model, so we forward the raw `{ method, params }`
2388
+ * payload and return the wallet's full JSON-RPC response envelope unchanged.
2389
+ *
2390
+ * Analytics tracking is intentionally skipped here: ecosystem clients
2391
+ * (e.g. `connect-evm`) emit their own `wallet_action_*` events around these
2392
+ * passthrough calls, and adding router-level tracking would double-count.
2393
+ *
2394
+ * @param options
2395
+ */
2396
+ handleWithEip1193Passthrough(options) {
2397
+ return __async(this, null, function* () {
2398
+ const response = yield this.transport.sendEip1193Message({
2399
+ method: options.request.method,
2400
+ params: options.request.params
2401
+ });
2402
+ return response.result;
2403
+ });
2404
+ }
2313
2405
  /**
2314
2406
  * Forwards the request directly to the wallet via the transport.
2315
2407
  *
@@ -2341,14 +2433,6 @@ var RequestRouter = class {
2341
2433
  }), 10);
2342
2434
  }
2343
2435
  const response = yield request;
2344
- if (response.error) {
2345
- const { error } = response;
2346
- throw new RPCInvokeMethodErr(
2347
- `RPC Request failed with code ${error.code}: ${error.message}`,
2348
- error.code,
2349
- error.message
2350
- );
2351
- }
2352
2436
  return response.result;
2353
2437
  }));
2354
2438
  });
@@ -2388,6 +2472,13 @@ _RequestRouter_instances = new WeakSet();
2388
2472
  withAnalyticsTracking_fn = function(options, execute) {
2389
2473
  return __async(this, null, function* () {
2390
2474
  var _a2;
2475
+ if (((_a2 = this.config.analytics) == null ? void 0 : _a2.enabled) === false) {
2476
+ try {
2477
+ return yield execute();
2478
+ } catch (error) {
2479
+ throw toRPCInvokeMethodErr(error);
2480
+ }
2481
+ }
2391
2482
  yield __privateMethod(this, _RequestRouter_instances, trackWalletActionRequested_fn).call(this, options);
2392
2483
  try {
2393
2484
  const result = yield execute();
@@ -2400,14 +2491,7 @@ withAnalyticsTracking_fn = function(options, execute) {
2400
2491
  } else {
2401
2492
  yield __privateMethod(this, _RequestRouter_instances, trackWalletActionFailed_fn).call(this, options, error);
2402
2493
  }
2403
- if (error instanceof RPCInvokeMethodErr) {
2404
- throw error;
2405
- }
2406
- const castError = error;
2407
- throw new RPCInvokeMethodErr(
2408
- (_a2 = castError.message) != null ? _a2 : "Unknown error",
2409
- castError.code
2410
- );
2494
+ throw toRPCInvokeMethodErr(error);
2411
2495
  }
2412
2496
  });
2413
2497
  };
@@ -2461,7 +2545,7 @@ trackWalletActionRejected_fn = function(options) {
2461
2545
  var import_multichain_api_client = require("@metamask/multichain-api-client");
2462
2546
  init_utils();
2463
2547
  var DEFAULT_REQUEST_TIMEOUT = 60 * 1e3;
2464
- var _notificationCallbacks, _transport, _defaultRequestOptions, _pendingRequests, _handleResponseListener, _handleNotificationListener, _DefaultTransport_instances, notifyCallbacks_fn, isMetamaskProviderEvent_fn, handleResponse_fn, handleNotification_fn, setupMessageListener_fn, init_fn;
2548
+ var _notificationCallbacks, _transport, _defaultRequestOptions, _pendingRequests, _handleResponseListener, _handleNotificationListener, _DefaultTransport_instances, notifyCallbacks_fn, parseWalletError_fn, isMetamaskProviderEvent_fn, handleResponse_fn, handleNotification_fn, setupMessageListener_fn, init_fn;
2465
2549
  var DefaultTransport = class {
2466
2550
  constructor() {
2467
2551
  __privateAdd(this, _DefaultTransport_instances);
@@ -2597,7 +2681,11 @@ var DefaultTransport = class {
2597
2681
  }
2598
2682
  request(_0) {
2599
2683
  return __async(this, arguments, function* (request, options = __privateGet(this, _defaultRequestOptions)) {
2600
- return __privateGet(this, _transport).request(request, options);
2684
+ const response = yield __privateGet(this, _transport).request(request, options);
2685
+ if (response.error) {
2686
+ throw __privateMethod(this, _DefaultTransport_instances, parseWalletError_fn).call(this, response.error);
2687
+ }
2688
+ return response;
2601
2689
  });
2602
2690
  }
2603
2691
  onNotification(callback) {
@@ -2641,6 +2729,16 @@ notifyCallbacks_fn = function(data) {
2641
2729
  }
2642
2730
  }
2643
2731
  };
2732
+ parseWalletError_fn = function(errorPayload) {
2733
+ const errorData = errorPayload;
2734
+ const error = new Error(
2735
+ typeof errorData.message === "string" ? errorData.message : "Request failed"
2736
+ );
2737
+ if (typeof errorData.code === "number") {
2738
+ error.code = errorData.code;
2739
+ }
2740
+ return error;
2741
+ };
2644
2742
  isMetamaskProviderEvent_fn = function(event) {
2645
2743
  var _a2, _b;
2646
2744
  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
@@ -2663,13 +2761,7 @@ handleResponse_fn = function(event) {
2663
2761
  __privateGet(this, _pendingRequests).delete(responseId);
2664
2762
  const response = responseData;
2665
2763
  if ("error" in response && response.error) {
2666
- const error = new Error(
2667
- response.error.message || "Request failed"
2668
- );
2669
- if (typeof response.error.code === "number") {
2670
- error.code = response.error.code;
2671
- }
2672
- pendingRequest.reject(error);
2764
+ pendingRequest.reject(__privateMethod(this, _DefaultTransport_instances, parseWalletError_fn).call(this, response.error));
2673
2765
  } else {
2674
2766
  pendingRequest.resolve(response);
2675
2767
  }
@@ -2707,22 +2799,21 @@ init_fn = function() {
2707
2799
  // src/multichain/transports/multichainApiClientWrapper/index.ts
2708
2800
  var import_rpc_errors = require("@metamask/rpc-errors");
2709
2801
  init_utils();
2710
- var _notificationCallbacks2, _MultichainApiClientWrapperTransport_instances, walletCreateSession_fn, walletGetSession_fn, walletRevokeSession_fn, walletInvokeMethod_fn;
2802
+ var _notificationCallbacks2, _getTransport, _MultichainApiClientWrapperTransport_instances, walletCreateSession_fn, walletGetSession_fn, walletRevokeSession_fn, walletInvokeMethod_fn;
2711
2803
  var MultichainApiClientWrapperTransport = class {
2712
- constructor(metamaskConnectMultichain) {
2804
+ constructor(metamaskConnectMultichain, getTransport) {
2713
2805
  this.metamaskConnectMultichain = metamaskConnectMultichain;
2714
2806
  __privateAdd(this, _MultichainApiClientWrapperTransport_instances);
2715
2807
  __privateAdd(this, _notificationCallbacks2, /* @__PURE__ */ new Set());
2808
+ __privateAdd(this, _getTransport);
2809
+ __privateSet(this, _getTransport, getTransport);
2716
2810
  }
2717
2811
  isTransportDefined() {
2718
- try {
2719
- return Boolean(this.metamaskConnectMultichain.transport);
2720
- } catch (_error) {
2721
- return false;
2722
- }
2812
+ return __privateGet(this, _getTransport).call(this) !== void 0;
2723
2813
  }
2724
2814
  isTransportConnected() {
2725
- return this.isTransportDefined() && this.metamaskConnectMultichain.transport.isConnected();
2815
+ var _a2, _b;
2816
+ return (_b = (_a2 = __privateGet(this, _getTransport).call(this)) == null ? void 0 : _a2.isConnected()) != null ? _b : false;
2726
2817
  }
2727
2818
  clearNotificationCallbacks() {
2728
2819
  __privateGet(this, _notificationCallbacks2).clear();
@@ -2738,10 +2829,11 @@ var MultichainApiClientWrapperTransport = class {
2738
2829
  this.notificationListener = void 0;
2739
2830
  }
2740
2831
  setupTransportNotificationListener() {
2741
- if (!this.isTransportDefined() || this.notificationListener) {
2832
+ const transport = __privateGet(this, _getTransport).call(this);
2833
+ if (!transport || this.notificationListener) {
2742
2834
  return;
2743
2835
  }
2744
- this.notificationListener = this.metamaskConnectMultichain.transport.onNotification(
2836
+ this.notificationListener = transport.onNotification(
2745
2837
  this.notifyCallbacks.bind(this)
2746
2838
  );
2747
2839
  }
@@ -2791,6 +2883,7 @@ var MultichainApiClientWrapperTransport = class {
2791
2883
  }
2792
2884
  };
2793
2885
  _notificationCallbacks2 = new WeakMap();
2886
+ _getTransport = new WeakMap();
2794
2887
  _MultichainApiClientWrapperTransport_instances = new WeakSet();
2795
2888
  walletCreateSession_fn = function(request) {
2796
2889
  return __async(this, null, function* () {
@@ -2814,14 +2907,19 @@ walletCreateSession_fn = function(request) {
2814
2907
  accounts,
2815
2908
  createSessionParams.sessionProperties
2816
2909
  );
2817
- return this.metamaskConnectMultichain.transport.request({
2910
+ const transport = __privateGet(this, _getTransport).call(this);
2911
+ if (!transport) {
2912
+ throw new Error("Transport not initialized after connect");
2913
+ }
2914
+ return transport.request({
2818
2915
  method: "wallet_getSession"
2819
2916
  });
2820
2917
  });
2821
2918
  };
2822
2919
  walletGetSession_fn = function(request) {
2823
2920
  return __async(this, null, function* () {
2824
- if (!this.isTransportConnected()) {
2921
+ const transport = __privateGet(this, _getTransport).call(this);
2922
+ if (!(transport == null ? void 0 : transport.isConnected())) {
2825
2923
  return {
2826
2924
  jsonrpc: "2.0",
2827
2925
  id: request.id,
@@ -2830,7 +2928,7 @@ walletGetSession_fn = function(request) {
2830
2928
  }
2831
2929
  };
2832
2930
  }
2833
- return this.metamaskConnectMultichain.transport.request({
2931
+ return transport.request({
2834
2932
  method: "wallet_getSession"
2835
2933
  });
2836
2934
  });
@@ -2866,26 +2964,63 @@ walletInvokeMethod_fn = function(request) {
2866
2964
  init_utils();
2867
2965
  var logger2 = createLogger("metamask-sdk:core");
2868
2966
  var SINGLETON_KEY = "__METAMASK_CONNECT_MULTICHAIN_SINGLETON__";
2869
- 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;
2967
+ function normalizeAnalyticsOptions(analyticsOptions) {
2968
+ var _a2;
2969
+ return __spreadProps(__spreadValues({}, analyticsOptions != null ? analyticsOptions : {}), {
2970
+ enabled: (_a2 = analyticsOptions == null ? void 0 : analyticsOptions.enabled) != null ? _a2 : true,
2971
+ // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
2972
+ integrationType: (analyticsOptions == null ? void 0 : analyticsOptions.integrationType) || "direct"
2973
+ });
2974
+ }
2975
+ function isAnalyticsEnabled(options) {
2976
+ var _a2;
2977
+ return ((_a2 = options.analytics) == null ? void 0 : _a2.enabled) !== false;
2978
+ }
2979
+ function setupAnalyticsGlobals(options, storage, setAnonId) {
2980
+ return __async(this, null, function* () {
2981
+ var _a2, _b;
2982
+ if (!isAnalyticsEnabled(options)) {
2983
+ setAnonId == null ? void 0 : setAnonId(void 0);
2984
+ import_analytics4.analytics.disable();
2985
+ return;
2986
+ }
2987
+ const platform = getPlatformType();
2988
+ const isBrowser = platform === "in-app-browser" /* MetaMaskMobileWebview */ || platform === "web-desktop" /* DesktopWeb */ || platform === "web-mobile" /* MobileWeb */;
2989
+ const isReactNative2 = platform === "react-native" /* ReactNative */;
2990
+ if (!isBrowser && !isReactNative2) {
2991
+ return;
2992
+ }
2993
+ const dappId = getDappId(options.dapp);
2994
+ const anonId = yield storage.getAnonId();
2995
+ setAnonId == null ? void 0 : setAnonId(anonId);
2996
+ const { integrationType } = (_a2 = options.analytics) != null ? _a2 : {
2997
+ integrationType: ""
2998
+ };
2999
+ import_analytics4.analytics.setGlobalProperty("mmconnect_versions", (_b = options.versions) != null ? _b : {});
3000
+ import_analytics4.analytics.setGlobalProperty("dapp_id", dappId);
3001
+ import_analytics4.analytics.setGlobalProperty("anon_id", anonId);
3002
+ import_analytics4.analytics.setGlobalProperty("platform", platform);
3003
+ if (integrationType) {
3004
+ import_analytics4.analytics.setGlobalProperty("integration_types", [integrationType]);
3005
+ }
3006
+ import_analytics4.analytics.enable();
3007
+ });
3008
+ }
3009
+ 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;
2870
3010
  var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends MultichainCore {
2871
3011
  constructor(options) {
2872
- var _a2, _b, _c, _d, _e, _f;
3012
+ var _a2, _b, _c, _d;
2873
3013
  const withDappMetadata = setupDappMetadata(options);
2874
- const integrationType = ((_a2 = options.analytics) == null ? void 0 : _a2.integrationType) || "direct";
2875
3014
  const allOptions = __spreadProps(__spreadValues({}, withDappMetadata), {
2876
3015
  ui: __spreadProps(__spreadValues({}, withDappMetadata.ui), {
2877
- preferExtension: (_b = withDappMetadata.ui.preferExtension) != null ? _b : true,
2878
- showInstallModal: (_c = withDappMetadata.ui.showInstallModal) != null ? _c : false,
2879
- headless: (_d = withDappMetadata.ui.headless) != null ? _d : false
2880
- }),
2881
- analytics: __spreadProps(__spreadValues({}, (_e = options.analytics) != null ? _e : {}), {
2882
- integrationType
3016
+ preferExtension: (_a2 = withDappMetadata.ui.preferExtension) != null ? _a2 : true,
3017
+ showInstallModal: (_b = withDappMetadata.ui.showInstallModal) != null ? _b : false,
3018
+ headless: (_c = withDappMetadata.ui.headless) != null ? _c : false
2883
3019
  }),
3020
+ analytics: normalizeAnalyticsOptions(options.analytics),
2884
3021
  versions: __spreadValues({
2885
- // typeof guard needed: Metro (React Native) bundles TS source directly,
2886
- // bypassing the tsup build that substitutes __PACKAGE_VERSION__.
2887
- "connect-multichain": false ? "unknown" : "0.14.0"
2888
- }, (_f = options.versions) != null ? _f : {})
3022
+ "connect-multichain": getVersion()
3023
+ }, (_d = options.versions) != null ? _d : {})
2889
3024
  });
2890
3025
  super(allOptions);
2891
3026
  __privateAdd(this, _MetaMaskConnectMultichain_instances);
@@ -2900,7 +3035,8 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
2900
3035
  __privateAdd(this, _anonId);
2901
3036
  __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}`);
2902
3037
  __privateSet(this, _providerTransportWrapper, new MultichainApiClientWrapperTransport(
2903
- this
3038
+ this,
3039
+ () => __privateGet(this, _transport2)
2904
3040
  ));
2905
3041
  __privateSet(this, _provider, (0, import_multichain_api_client3.getMultichainClient)({
2906
3042
  transport: __privateGet(this, _providerTransportWrapper)
@@ -2919,12 +3055,6 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
2919
3055
  get provider() {
2920
3056
  return __privateGet(this, _provider);
2921
3057
  }
2922
- get transport() {
2923
- if (!__privateGet(this, _transport2)) {
2924
- throw new Error("Transport not initialized, establish connection first");
2925
- }
2926
- return __privateGet(this, _transport2);
2927
- }
2928
3058
  get dappClient() {
2929
3059
  if (!__privateGet(this, _dappClient)) {
2930
3060
  throw new Error("DappClient not initialized, establish connection first");
@@ -2938,28 +3068,33 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
2938
3068
  get storage() {
2939
3069
  return this.options.storage;
2940
3070
  }
3071
+ get version() {
3072
+ return getVersion();
3073
+ }
2941
3074
  // Creates a singleton instance of MetaMaskConnectMultichain.
2942
3075
  // If the singleton already exists, it merges the incoming options with the
2943
3076
  // existing singleton options for the following keys: `api.supportedNetworks`,
2944
- // `versions`, `ui.*`, `mobile.*`, `transport.extensionId`, `debug`. Take note
2945
- // that the value for `dapp` is not merged as it does not make sense for
2946
- // subsequent calls to `createMultichainClient` to have a different `dapp` value.
3077
+ // `analytics`, `versions`, `ui.*`, `mobile.*`, `transport.extensionId`,
3078
+ // `debug`. Take note that the value for `dapp` is not merged as it does not
3079
+ // make sense for subsequent calls to `createMultichainClient` to have a
3080
+ // different `dapp` value.
2947
3081
  static create(options) {
2948
3082
  return __async(this, null, function* () {
2949
- var _a2, _b;
3083
+ var _a2;
2950
3084
  const globalObject = getGlobalObject();
2951
3085
  const existing = globalObject[SINGLETON_KEY];
2952
3086
  if (existing) {
2953
3087
  const instance = yield existing;
3088
+ if (instance.version !== getVersion()) {
3089
+ console.warn(
3090
+ `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.`
3091
+ );
3092
+ }
2954
3093
  instance.mergeOptions(options);
2955
- import_analytics4.analytics.setGlobalProperty(
2956
- "mmconnect_versions",
2957
- (_a2 = instance.options.versions) != null ? _a2 : {}
2958
- );
2959
- if ((_b = options.analytics) == null ? void 0 : _b.integrationType) {
2960
- import_analytics4.analytics.setGlobalProperty("integration_types", [
2961
- options.analytics.integrationType
2962
- ]);
3094
+ if (instance instanceof _MetaMaskConnectMultichain) {
3095
+ yield __privateMethod(_a2 = instance, _MetaMaskConnectMultichain_instances, setupAnalytics_fn).call(_a2);
3096
+ } else {
3097
+ yield setupAnalyticsGlobals(instance.options, instance.storage);
2963
3098
  }
2964
3099
  if (options.debug) {
2965
3100
  enableDebug("metamask-sdk:*");
@@ -2978,12 +3113,12 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
2978
3113
  }
2979
3114
  yield __privateMethod(_a3 = instance, _MetaMaskConnectMultichain_instances, init_fn2).call(_a3);
2980
3115
  return instance;
2981
- }))();
2982
- globalObject[SINGLETON_KEY] = instancePromise;
2983
- instancePromise.catch((error) => {
3116
+ }))().catch((error) => {
2984
3117
  globalObject[SINGLETON_KEY] = void 0;
2985
3118
  console.error("Error initializing MetaMaskConnectMultichain", error);
3119
+ throw error;
2986
3120
  });
3121
+ globalObject[SINGLETON_KEY] = instancePromise;
2987
3122
  return instancePromise;
2988
3123
  });
2989
3124
  }
@@ -3009,21 +3144,23 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
3009
3144
  } else {
3010
3145
  transportType = "mwp" /* MWP */;
3011
3146
  }
3012
- try {
3013
- const baseProps = yield getBaseAnalyticsProperties(
3014
- this.options,
3015
- this.storage
3016
- );
3017
- const dappConfiguredChains = Object.keys(
3018
- this.options.api.supportedNetworks
3019
- );
3020
- import_analytics4.analytics.track("mmconnect_connection_initiated", __spreadProps(__spreadValues({}, baseProps), {
3021
- transport_type: transportType,
3022
- dapp_configured_chains: dappConfiguredChains,
3023
- dapp_requested_chains: scopes
3024
- }));
3025
- } catch (error) {
3026
- logger2("Error tracking connection_initiated event", error);
3147
+ if (isAnalyticsEnabled(this.options)) {
3148
+ try {
3149
+ const baseProps = yield getBaseAnalyticsProperties(
3150
+ this.options,
3151
+ this.storage
3152
+ );
3153
+ const dappConfiguredChains = Object.keys(
3154
+ this.options.api.supportedNetworks
3155
+ );
3156
+ import_analytics4.analytics.track("mmconnect_connection_initiated", __spreadProps(__spreadValues({}, baseProps), {
3157
+ transport_type: transportType,
3158
+ dapp_configured_chains: dappConfiguredChains,
3159
+ dapp_requested_chains: scopes
3160
+ }));
3161
+ } catch (error) {
3162
+ logger2("Error tracking connection_initiated event", error);
3163
+ }
3027
3164
  }
3028
3165
  const sessionData = yield __privateMethod(this, _MetaMaskConnectMultichain_instances, getCaipSession_fn).call(this);
3029
3166
  const { mergedScopes, mergedCaipAccountIds, mergedSessionProperties } = mergeRequestedSessionWithExisting(
@@ -3041,9 +3178,9 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
3041
3178
  forceRequest
3042
3179
  }).then(() => __async(this, null, function* () {
3043
3180
  if (__privateGet(this, _transportType) === "mwp" /* MWP */) {
3044
- return this.storage.setTransport("mwp" /* MWP */);
3181
+ return this.storage.setTransportType("mwp" /* MWP */);
3045
3182
  }
3046
- return this.storage.setTransport("browser" /* Browser */);
3183
+ return this.storage.setTransportType("browser" /* Browser */);
3047
3184
  })), scopes, transportType);
3048
3185
  }
3049
3186
  if (platformType === "in-app-browser" /* MetaMaskMobileWebview */) {
@@ -3072,11 +3209,6 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
3072
3209
  return __privateMethod(this, _MetaMaskConnectMultichain_instances, handleConnection_fn).call(this, __privateMethod(this, _MetaMaskConnectMultichain_instances, showInstallModal_fn).call(this, shouldShowInstallModal, mergedScopes, mergedCaipAccountIds, nonEmptySessionProperties), scopes, transportType);
3073
3210
  });
3074
3211
  }
3075
- emit(event, args) {
3076
- var _a2, _b;
3077
- (_b = (_a2 = this.options.transport) == null ? void 0 : _a2.onNotification) == null ? void 0 : _b.call(_a2, { method: event, params: args });
3078
- super.emit(event, args);
3079
- }
3080
3212
  disconnect() {
3081
3213
  return __async(this, arguments, function* (scopes = []) {
3082
3214
  var _a2, _b, _c;
@@ -3086,7 +3218,7 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
3086
3218
  );
3087
3219
  yield (_a2 = __privateGet(this, _transport2)) == null ? void 0 : _a2.disconnect(scopes);
3088
3220
  if (remainingScopes.length === 0) {
3089
- yield this.storage.removeTransport();
3221
+ yield this.storage.removeTransportType();
3090
3222
  if (__privateGet(this, _transportType) !== "browser" /* Browser */) {
3091
3223
  yield (_b = __privateGet(this, _listener)) == null ? void 0 : _b.call(this);
3092
3224
  (_c = __privateGet(this, _beforeUnloadListener)) == null ? void 0 : _c.call(this);
@@ -3104,7 +3236,8 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
3104
3236
  invokeMethod(request) {
3105
3237
  return __async(this, null, function* () {
3106
3238
  var _a2;
3107
- const { transport, options } = this;
3239
+ const transport = __privateMethod(this, _MetaMaskConnectMultichain_instances, transportOrThrow_fn).call(this);
3240
+ const { options } = this;
3108
3241
  const rpcClient = new RpcClient(options, __privateGet(this, _sdkInfo));
3109
3242
  const requestRouter = new RequestRouter(
3110
3243
  transport,
@@ -3123,7 +3256,7 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
3123
3256
  const shouldOpenDeeplink = secure && !showInstallModal;
3124
3257
  if (shouldOpenDeeplink) {
3125
3258
  setTimeout(() => __async(this, null, function* () {
3126
- const session = yield this.transport.getActiveSession();
3259
+ const session = yield __privateMethod(this, _MetaMaskConnectMultichain_instances, transportOrThrow_fn).call(this).getActiveSession();
3127
3260
  if (!session) {
3128
3261
  throw new Error("No active session found");
3129
3262
  }
@@ -3147,10 +3280,13 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
3147
3280
  this.emit("wallet_sessionChanged", emptySession);
3148
3281
  return;
3149
3282
  }
3150
- const response = yield this.transport.request({
3283
+ const response = yield __privateGet(this, _transport2).request({
3151
3284
  method: "wallet_getSession"
3152
3285
  });
3153
- this.emit("wallet_sessionChanged", (_b = response.result) != null ? _b : emptySession);
3286
+ this.emit(
3287
+ "wallet_sessionChanged",
3288
+ (_b = response.result) != null ? _b : emptySession
3289
+ );
3154
3290
  });
3155
3291
  }
3156
3292
  };
@@ -3162,34 +3298,19 @@ _beforeUnloadListener = new WeakMap();
3162
3298
  _transportType = new WeakMap();
3163
3299
  _listener = new WeakMap();
3164
3300
  _anonId = new WeakMap();
3165
- _sdkInfo = new WeakMap();
3166
3301
  _MetaMaskConnectMultichain_instances = new WeakSet();
3302
+ transportOrThrow_fn = function() {
3303
+ if (!__privateGet(this, _transport2)) {
3304
+ throw new Error("Transport not initialized, establish connection first");
3305
+ }
3306
+ return __privateGet(this, _transport2);
3307
+ };
3308
+ _sdkInfo = new WeakMap();
3167
3309
  setupAnalytics_fn = function() {
3168
3310
  return __async(this, null, function* () {
3169
- var _a2, _b;
3170
- const platform = getPlatformType();
3171
- const isBrowser = platform === "in-app-browser" /* MetaMaskMobileWebview */ || platform === "web-desktop" /* DesktopWeb */ || platform === "web-mobile" /* MobileWeb */;
3172
- const isReactNative2 = platform === "react-native" /* ReactNative */;
3173
- if (!isBrowser && !isReactNative2) {
3174
- return;
3175
- }
3176
- const dappId = getDappId(this.options.dapp);
3177
- const anonId = yield this.storage.getAnonId();
3178
- __privateSet(this, _anonId, anonId);
3179
- const { integrationType } = (_a2 = this.options.analytics) != null ? _a2 : {
3180
- integrationType: ""
3181
- };
3182
- import_analytics4.analytics.setGlobalProperty(
3183
- "mmconnect_versions",
3184
- (_b = this.options.versions) != null ? _b : {}
3185
- );
3186
- import_analytics4.analytics.setGlobalProperty("dapp_id", dappId);
3187
- import_analytics4.analytics.setGlobalProperty("anon_id", anonId);
3188
- import_analytics4.analytics.setGlobalProperty("platform", platform);
3189
- if (integrationType) {
3190
- import_analytics4.analytics.setGlobalProperty("integration_types", [integrationType]);
3191
- }
3192
- import_analytics4.analytics.enable();
3311
+ yield setupAnalyticsGlobals(this.options, this.storage, (anonId) => {
3312
+ __privateSet(this, _anonId, anonId);
3313
+ });
3193
3314
  });
3194
3315
  };
3195
3316
  onTransportNotification_fn = function(payload) {
@@ -3210,7 +3331,7 @@ onTransportNotification_fn = function(payload) {
3210
3331
  };
3211
3332
  getStoredTransport_fn = function() {
3212
3333
  return __async(this, null, function* () {
3213
- const transportType = yield this.storage.getTransport();
3334
+ const transportType = yield this.storage.getTransportType();
3214
3335
  const hasExtensionInstalled = yield hasExtension();
3215
3336
  if (transportType) {
3216
3337
  if (transportType === "browser" /* Browser */) {
@@ -3238,7 +3359,7 @@ getStoredTransport_fn = function() {
3238
3359
  ));
3239
3360
  return apiTransport;
3240
3361
  }
3241
- yield this.storage.removeTransport();
3362
+ yield this.storage.removeTransportType();
3242
3363
  }
3243
3364
  return void 0;
3244
3365
  });
@@ -3248,15 +3369,15 @@ setupTransport_fn = function() {
3248
3369
  var _a2;
3249
3370
  const transport = yield __privateMethod(this, _MetaMaskConnectMultichain_instances, getStoredTransport_fn).call(this);
3250
3371
  if (transport) {
3251
- if (!this.transport.isConnected()) {
3372
+ if (!transport.isConnected()) {
3252
3373
  this.status = "connecting";
3253
- yield this.transport.connect();
3374
+ yield transport.connect();
3254
3375
  }
3255
3376
  this.status = "connected";
3256
3377
  if (__privateGet(this, _transportType) === "mwp" /* MWP */) {
3257
- yield this.storage.setTransport("mwp" /* MWP */);
3378
+ yield this.storage.setTransportType("mwp" /* MWP */);
3258
3379
  } else {
3259
- yield this.storage.setTransport("browser" /* Browser */);
3380
+ yield this.storage.setTransportType("browser" /* Browser */);
3260
3381
  }
3261
3382
  } else {
3262
3383
  this.status = "loaded";
@@ -3265,7 +3386,7 @@ setupTransport_fn = function() {
3265
3386
  if (hasExtensionInstalled && preferExtension) {
3266
3387
  yield __privateMethod(this, _MetaMaskConnectMultichain_instances, setupDefaultTransport_fn).call(this, { persist: false });
3267
3388
  try {
3268
- yield this.transport.init();
3389
+ yield __privateMethod(this, _MetaMaskConnectMultichain_instances, transportOrThrow_fn).call(this).init();
3269
3390
  } catch (error) {
3270
3391
  console.error("Passive init failed:", error);
3271
3392
  }
@@ -3278,7 +3399,7 @@ buildConnectionMetadata_fn = function() {
3278
3399
  dapp: this.options.dapp,
3279
3400
  sdk: { version: getVersion(), platform: getPlatformType() }
3280
3401
  };
3281
- if (__privateGet(this, _anonId)) {
3402
+ if (isAnalyticsEnabled(this.options) && __privateGet(this, _anonId)) {
3282
3403
  metadata.analytics = { remote_session_id: __privateGet(this, _anonId) };
3283
3404
  }
3284
3405
  return metadata;
@@ -3289,7 +3410,7 @@ init_fn2 = function() {
3289
3410
  yield __privateMethod(this, _MetaMaskConnectMultichain_instances, setupAnalytics_fn).call(this);
3290
3411
  yield __privateMethod(this, _MetaMaskConnectMultichain_instances, setupTransport_fn).call(this);
3291
3412
  } catch (error) {
3292
- yield this.storage.removeTransport();
3413
+ yield this.storage.removeTransportType();
3293
3414
  this.status = "pending";
3294
3415
  logger2("MetaMaskSDK error during initialization", error);
3295
3416
  }
@@ -3335,17 +3456,17 @@ setupMWP_fn = function() {
3335
3456
  __privateSet(this, _transport2, apiTransport);
3336
3457
  __privateSet(this, _transportType, "mwp" /* MWP */);
3337
3458
  __privateGet(this, _providerTransportWrapper).setupTransportNotificationListener();
3338
- __privateSet(this, _listener, this.transport.onNotification(
3459
+ __privateSet(this, _listener, apiTransport.onNotification(
3339
3460
  __privateMethod(this, _MetaMaskConnectMultichain_instances, onTransportNotification_fn).bind(this)
3340
3461
  ));
3341
- yield this.storage.setTransport("mwp" /* MWP */);
3462
+ yield this.storage.setTransportType("mwp" /* MWP */);
3342
3463
  });
3343
3464
  };
3344
3465
  onBeforeUnload_fn = function() {
3345
3466
  return __async(this, null, function* () {
3346
3467
  var _a2;
3347
3468
  if ((_a2 = this.options.ui.factory.modal) == null ? void 0 : _a2.isMounted) {
3348
- yield this.storage.removeTransport();
3469
+ yield this.storage.removeTransportType();
3349
3470
  }
3350
3471
  });
3351
3472
  };
@@ -3362,70 +3483,65 @@ createBeforeUnloadListener_fn = function() {
3362
3483
  };
3363
3484
  renderInstallModalAsync_fn = function(desktopPreferred, scopes, caipAccountIds, sessionProperties) {
3364
3485
  return __async(this, null, function* () {
3365
- return new Promise((resolve, reject) => {
3366
- this.options.ui.factory.renderInstallModal(
3367
- desktopPreferred,
3368
- () => __async(this, null, function* () {
3369
- if (this.dappClient.state === "CONNECTED" || this.dappClient.state === "CONNECTING") {
3370
- yield this.dappClient.disconnect();
3371
- }
3372
- return new Promise((_resolve) => {
3373
- this.dappClient.on(
3374
- "session_request",
3375
- (sessionRequest) => {
3376
- _resolve({
3377
- sessionRequest,
3378
- metadata: __privateMethod(this, _MetaMaskConnectMultichain_instances, buildConnectionMetadata_fn).call(this)
3379
- });
3380
- }
3381
- );
3382
- (() => __async(this, null, function* () {
3383
- var _a2;
3384
- try {
3385
- yield this.transport.connect({
3386
- scopes,
3387
- caipAccountIds,
3388
- sessionProperties
3389
- });
3390
- yield this.options.ui.factory.unload();
3391
- (_a2 = this.options.ui.factory.modal) == null ? void 0 : _a2.unmount();
3392
- this.status = "connected";
3393
- yield this.storage.setTransport("mwp" /* MWP */);
3394
- } catch (error) {
3395
- const { ProtocolError, ErrorCode } = yield import("@metamask/mobile-wallet-protocol-core");
3396
- if (error instanceof ProtocolError) {
3397
- if (error.code !== ErrorCode.REQUEST_EXPIRED) {
3398
- this.status = "disconnected";
3399
- yield this.options.ui.factory.unload(error);
3400
- reject(error);
3401
- }
3402
- } else {
3403
- this.status = "disconnected";
3404
- const normalizedError = error instanceof Error ? error : new Error(String(error));
3405
- yield this.options.ui.factory.unload(normalizedError);
3406
- reject(normalizedError);
3407
- }
3408
- }
3409
- }))().catch(() => {
3410
- });
3486
+ const completion = (0, import_utils7.createDeferredPromise)();
3487
+ const createConnectionRequest = () => __async(this, null, function* () {
3488
+ if (this.dappClient.state === "CONNECTED" || this.dappClient.state === "CONNECTING") {
3489
+ yield this.dappClient.disconnect();
3490
+ }
3491
+ const sessionRequestDeferred = (0, import_utils7.createDeferredPromise)();
3492
+ this.dappClient.on(
3493
+ "session_request",
3494
+ (sessionRequest) => {
3495
+ sessionRequestDeferred.resolve({
3496
+ sessionRequest,
3497
+ metadata: __privateMethod(this, _MetaMaskConnectMultichain_instances, buildConnectionMetadata_fn).call(this)
3411
3498
  });
3412
- }),
3413
- (error) => __async(this, null, function* () {
3414
- if (error) {
3415
- yield this.storage.removeTransport();
3416
- reject(error);
3417
- } else {
3418
- yield this.storage.setTransport("mwp" /* MWP */);
3419
- resolve();
3499
+ }
3500
+ );
3501
+ __privateMethod(this, _MetaMaskConnectMultichain_instances, transportOrThrow_fn).call(this).connect({ scopes, caipAccountIds, sessionProperties }).then(() => __async(this, null, function* () {
3502
+ var _a2;
3503
+ yield this.options.ui.factory.unload();
3504
+ (_a2 = this.options.ui.factory.modal) == null ? void 0 : _a2.unmount();
3505
+ this.status = "connected";
3506
+ yield this.storage.setTransportType("mwp" /* MWP */);
3507
+ })).catch((error) => __async(this, null, function* () {
3508
+ const { ProtocolError, ErrorCode } = yield import("@metamask/mobile-wallet-protocol-core");
3509
+ if (error instanceof ProtocolError) {
3510
+ if (error.code !== ErrorCode.REQUEST_EXPIRED) {
3511
+ this.status = "disconnected";
3512
+ yield this.options.ui.factory.unload(error);
3513
+ completion.reject(error);
3420
3514
  }
3421
- }),
3422
- (uri) => {
3423
- this.emit("display_uri", uri);
3515
+ } else {
3516
+ this.status = "disconnected";
3517
+ const normalizedError = error instanceof Error ? error : new Error(String(error));
3518
+ yield this.options.ui.factory.unload(normalizedError);
3519
+ completion.reject(normalizedError);
3424
3520
  }
3425
- ).catch((error) => {
3426
- reject(error instanceof Error ? error : new Error(String(error)));
3427
- });
3521
+ }));
3522
+ return sessionRequestDeferred.promise;
3428
3523
  });
3524
+ this.options.ui.factory.renderInstallModal(
3525
+ desktopPreferred,
3526
+ createConnectionRequest,
3527
+ (error) => __async(this, null, function* () {
3528
+ if (error) {
3529
+ yield this.storage.removeTransportType();
3530
+ completion.reject(error);
3531
+ } else {
3532
+ yield this.storage.setTransportType("mwp" /* MWP */);
3533
+ completion.resolve();
3534
+ }
3535
+ }),
3536
+ (uri) => {
3537
+ this.emit("display_uri", uri);
3538
+ }
3539
+ ).catch((error) => {
3540
+ completion.reject(
3541
+ error instanceof Error ? error : new Error(String(error))
3542
+ );
3543
+ });
3544
+ return completion.promise;
3429
3545
  });
3430
3546
  };
3431
3547
  showInstallModal_fn = function(desktopPreferred, scopes, caipAccountIds, sessionProperties) {
@@ -3441,39 +3557,37 @@ showInstallModal_fn = function(desktopPreferred, scopes, caipAccountIds, session
3441
3557
  };
3442
3558
  headlessConnect_fn = function(scopes, caipAccountIds, sessionProperties) {
3443
3559
  return __async(this, null, function* () {
3444
- return new Promise((resolve, reject) => {
3445
- if (this.dappClient.state === "CONNECTED" || this.dappClient.state === "CONNECTING") {
3446
- this.dappClient.disconnect().catch(() => {
3447
- });
3560
+ if (this.dappClient.state === "CONNECTED" || this.dappClient.state === "CONNECTING") {
3561
+ yield this.dappClient.disconnect().catch(() => void 0);
3562
+ }
3563
+ const onSessionRequest = (sessionRequest) => {
3564
+ const connectionRequest = {
3565
+ sessionRequest,
3566
+ metadata: __privateMethod(this, _MetaMaskConnectMultichain_instances, buildConnectionMetadata_fn).call(this)
3567
+ };
3568
+ const deeplink = this.options.ui.factory.createConnectionDeeplink(connectionRequest);
3569
+ this.emit("display_uri", deeplink);
3570
+ };
3571
+ this.dappClient.on("session_request", onSessionRequest);
3572
+ try {
3573
+ yield __privateMethod(this, _MetaMaskConnectMultichain_instances, transportOrThrow_fn).call(this).connect({
3574
+ scopes,
3575
+ caipAccountIds,
3576
+ sessionProperties
3577
+ });
3578
+ this.status = "connected";
3579
+ yield this.storage.setTransportType("mwp" /* MWP */);
3580
+ } catch (error) {
3581
+ const { ProtocolError } = yield import("@metamask/mobile-wallet-protocol-core");
3582
+ this.status = "disconnected";
3583
+ yield this.storage.removeTransportType();
3584
+ if (error instanceof ProtocolError || error instanceof Error) {
3585
+ throw error;
3448
3586
  }
3449
- this.dappClient.on(
3450
- "session_request",
3451
- (sessionRequest) => {
3452
- const connectionRequest = {
3453
- sessionRequest,
3454
- metadata: __privateMethod(this, _MetaMaskConnectMultichain_instances, buildConnectionMetadata_fn).call(this)
3455
- };
3456
- const deeplink = this.options.ui.factory.createConnectionDeeplink(connectionRequest);
3457
- this.emit("display_uri", deeplink);
3458
- }
3459
- );
3460
- this.transport.connect({ scopes, caipAccountIds, sessionProperties }).then(() => __async(this, null, function* () {
3461
- this.status = "connected";
3462
- yield this.storage.setTransport("mwp" /* MWP */);
3463
- resolve();
3464
- })).catch((error) => __async(this, null, function* () {
3465
- const { ProtocolError } = yield import("@metamask/mobile-wallet-protocol-core");
3466
- if (error instanceof ProtocolError) {
3467
- this.status = "disconnected";
3468
- yield this.storage.removeTransport();
3469
- reject(error);
3470
- } else {
3471
- this.status = "disconnected";
3472
- yield this.storage.removeTransport();
3473
- reject(error instanceof Error ? error : new Error(String(error)));
3474
- }
3475
- }));
3476
- });
3587
+ throw new Error(String(error));
3588
+ } finally {
3589
+ this.dappClient.off("session_request", onSessionRequest);
3590
+ }
3477
3591
  });
3478
3592
  };
3479
3593
  setupDefaultTransport_fn = function() {
@@ -3482,7 +3596,7 @@ setupDefaultTransport_fn = function() {
3482
3596
  return __privateGet(this, _transport2);
3483
3597
  }
3484
3598
  if (options == null ? void 0 : options.persist) {
3485
- yield this.storage.setTransport("browser" /* Browser */);
3599
+ yield this.storage.setTransportType("browser" /* Browser */);
3486
3600
  }
3487
3601
  const transport = new DefaultTransport();
3488
3602
  __privateSet(this, _listener, transport.onNotification(
@@ -3515,7 +3629,7 @@ deeplinkConnect_fn = function(scopes, caipAccountIds, sessionProperties) {
3515
3629
  };
3516
3630
  this.dappClient.on("message", dappClientMessageHandler);
3517
3631
  let timeout;
3518
- if (this.transport.isConnected()) {
3632
+ if (__privateMethod(this, _MetaMaskConnectMultichain_instances, transportOrThrow_fn).call(this).isConnected()) {
3519
3633
  timeout = setTimeout(() => {
3520
3634
  this.openSimpleDeeplinkIfNeeded();
3521
3635
  }, 250);
@@ -3543,8 +3657,8 @@ deeplinkConnect_fn = function(scopes, caipAccountIds, sessionProperties) {
3543
3657
  }
3544
3658
  );
3545
3659
  }
3546
- return this.transport.connect({ scopes, caipAccountIds, sessionProperties }).then(resolve).catch((error) => __async(this, null, function* () {
3547
- yield this.storage.removeTransport();
3660
+ return __privateMethod(this, _MetaMaskConnectMultichain_instances, transportOrThrow_fn).call(this).connect({ scopes, caipAccountIds, sessionProperties }).then(resolve).catch((error) => __async(this, null, function* () {
3661
+ yield this.storage.removeTransportType();
3548
3662
  this.dappClient.off("message", dappClientMessageHandler);
3549
3663
  reject(error instanceof Error ? error : new Error(String(error)));
3550
3664
  })).finally(() => {
@@ -3560,38 +3674,42 @@ handleConnection_fn = function(promise, scopes, transportType) {
3560
3674
  this.status = "connecting";
3561
3675
  return promise.then(() => __async(this, null, function* () {
3562
3676
  this.status = "connected";
3563
- try {
3564
- const baseProps = yield getBaseAnalyticsProperties(
3565
- this.options,
3566
- this.storage
3567
- );
3568
- import_analytics4.analytics.track("mmconnect_connection_established", __spreadProps(__spreadValues({}, baseProps), {
3569
- transport_type: transportType,
3570
- user_permissioned_chains: scopes
3571
- }));
3572
- } catch (error) {
3573
- logger2("Error tracking connection_established event", error);
3677
+ if (isAnalyticsEnabled(this.options)) {
3678
+ try {
3679
+ const baseProps = yield getBaseAnalyticsProperties(
3680
+ this.options,
3681
+ this.storage
3682
+ );
3683
+ import_analytics4.analytics.track("mmconnect_connection_established", __spreadProps(__spreadValues({}, baseProps), {
3684
+ transport_type: transportType,
3685
+ user_permissioned_chains: scopes
3686
+ }));
3687
+ } catch (error) {
3688
+ logger2("Error tracking connection_established event", error);
3689
+ }
3574
3690
  }
3575
3691
  return void 0;
3576
3692
  })).catch((error) => __async(this, null, function* () {
3577
3693
  this.status = "disconnected";
3578
- try {
3579
- const baseProps = yield getBaseAnalyticsProperties(
3580
- this.options,
3581
- this.storage
3582
- );
3583
- const isRejection = isRejectionError(error);
3584
- if (isRejection) {
3585
- import_analytics4.analytics.track("mmconnect_connection_rejected", __spreadProps(__spreadValues({}, baseProps), {
3586
- transport_type: transportType
3587
- }));
3588
- } else {
3589
- import_analytics4.analytics.track("mmconnect_connection_failed", __spreadValues(__spreadProps(__spreadValues({}, baseProps), {
3590
- transport_type: transportType
3591
- }), extractErrorDiagnostics(error)));
3694
+ if (isAnalyticsEnabled(this.options)) {
3695
+ try {
3696
+ const baseProps = yield getBaseAnalyticsProperties(
3697
+ this.options,
3698
+ this.storage
3699
+ );
3700
+ const isRejection = isRejectionError(error);
3701
+ if (isRejection) {
3702
+ import_analytics4.analytics.track("mmconnect_connection_rejected", __spreadProps(__spreadValues({}, baseProps), {
3703
+ transport_type: transportType
3704
+ }));
3705
+ } else {
3706
+ import_analytics4.analytics.track("mmconnect_connection_failed", __spreadValues(__spreadProps(__spreadValues({}, baseProps), {
3707
+ transport_type: transportType
3708
+ }), extractErrorDiagnostics(error)));
3709
+ }
3710
+ } catch (e) {
3711
+ logger2("Error tracking connection failed/rejected event", error);
3592
3712
  }
3593
- } catch (e) {
3594
- logger2("Error tracking connection failed/rejected event", error);
3595
3713
  }
3596
3714
  throw error;
3597
3715
  }));
@@ -3606,7 +3724,7 @@ getCaipSession_fn = function() {
3606
3724
  };
3607
3725
  if ((_a2 = __privateGet(this, _transport2)) == null ? void 0 : _a2.isConnected()) {
3608
3726
  try {
3609
- const response = yield this.transport.request({
3727
+ const response = yield __privateGet(this, _transport2).request({
3610
3728
  method: "wallet_getSession"
3611
3729
  });
3612
3730
  if (response.result) {
@@ -3700,14 +3818,14 @@ var Store = class extends StoreClient {
3700
3818
  super();
3701
3819
  this.adapter = adapter;
3702
3820
  }
3703
- getTransport() {
3821
+ getTransportType() {
3704
3822
  return __async(this, null, function* () {
3705
3823
  try {
3706
- const transport = yield this.adapter.get("multichain-transport");
3707
- if (!transport) {
3824
+ const transportType = yield this.adapter.get("multichain-transport");
3825
+ if (!transportType) {
3708
3826
  return null;
3709
3827
  }
3710
- return getTransportType(transport);
3828
+ return getTransportType(transportType);
3711
3829
  } catch (err) {
3712
3830
  throw new StorageGetErr(
3713
3831
  this.adapter.platform,
@@ -3717,10 +3835,10 @@ var Store = class extends StoreClient {
3717
3835
  }
3718
3836
  });
3719
3837
  }
3720
- setTransport(transport) {
3838
+ setTransportType(transportType) {
3721
3839
  return __async(this, null, function* () {
3722
3840
  try {
3723
- yield this.adapter.set("multichain-transport", transport);
3841
+ yield this.adapter.set("multichain-transport", transportType);
3724
3842
  } catch (err) {
3725
3843
  throw new StorageSetErr(
3726
3844
  this.adapter.platform,
@@ -3730,7 +3848,7 @@ var Store = class extends StoreClient {
3730
3848
  }
3731
3849
  });
3732
3850
  }
3733
- removeTransport() {
3851
+ removeTransportType() {
3734
3852
  return __async(this, null, function* () {
3735
3853
  try {
3736
3854
  yield this.adapter.delete("multichain-transport");
@@ -3944,7 +4062,11 @@ var BaseModalFactory = class {
3944
4062
  (_a3 = this.displayUriCallback) == null ? void 0 : _a3.call(this, newLink);
3945
4063
  return newLink;
3946
4064
  }),
3947
- onClose: this.onCloseModal.bind(this),
4065
+ onClose: (shouldTerminate) => {
4066
+ this.onCloseModal(shouldTerminate).catch((error) => {
4067
+ console.error("Failed to close modal:", error);
4068
+ });
4069
+ },
3948
4070
  startDesktopOnboarding: this.onStartDesktopOnboarding.bind(this),
3949
4071
  createConnectionRequest,
3950
4072
  onDisplayUri: this.displayUriCallback
@@ -3982,7 +4104,7 @@ function preload() {
3982
4104
  }
3983
4105
  try {
3984
4106
  const { defineCustomElements } = yield import("@metamask/multichain-ui/loader");
3985
- yield defineCustomElements();
4107
+ defineCustomElements();
3986
4108
  } catch (error) {
3987
4109
  console.error("Failed to load customElements:", error);
3988
4110
  }
@@ -4021,6 +4143,7 @@ var createMultichainClient = (options) => __async(null, null, function* () {
4021
4143
  });
4022
4144
  // Annotate the CommonJS export names for ESM import in node:
4023
4145
  0 && (module.exports = {
4146
+ EIP1193_PASSTHROUGH_METHODS,
4024
4147
  EventEmitter,
4025
4148
  Modal,
4026
4149
  MultichainCore,
@@ -4048,6 +4171,7 @@ var createMultichainClient = (options) => __async(null, null, function* () {
4048
4171
  isEnabled,
4049
4172
  isMetamaskExtensionInstalled,
4050
4173
  isRejectionError,
4051
- isSecure
4174
+ isSecure,
4175
+ packageVersion
4052
4176
  });
4053
4177
  //# sourceMappingURL=connect-multichain.js.map