@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 _a3, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o;
488
+ var _a3, _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), (_a3 = partial.analytics) != null ? _a3 : {});
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 = (_a3 = partial.api) == null ? void 0 : _a3.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 _a3, _b;
586
601
  if ((_b = (_a3 = event == null ? void 0 : event.detail) == null ? void 0 : _a3.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 _a3, _b;
597
- return (_b = (_a3 = provider == null ? void 0 : provider.info) == null ? void 0 : _a3.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 _a3;
615
+ return typeof ((_a3 = provider == null ? void 0 : provider.info) == null ? void 0 : _a3.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
  }))();
@@ -842,12 +863,14 @@ var init_analytics = __esm({
842
863
 
843
864
  // src/domain/utils/index.ts
844
865
  function getVersion() {
845
- return "0.0.0";
866
+ return packageVersion;
846
867
  }
868
+ var packageVersion;
847
869
  var init_utils = __esm({
848
870
  "src/domain/utils/index.ts"() {
849
871
  "use strict";
850
872
  init_analytics();
873
+ packageVersion = false ? "unknown" : "1.0.0";
851
874
  }
852
875
  });
853
876
 
@@ -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 _a3, _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
- (_a3 = walletSession == null ? void 0 : walletSession.sessionScopes) != null ? _a3 : {}
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 _a3;
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((_a3 = session == null ? void 0 : session.id) != null ? _a3 : "");
1454
- }
1455
- });
1456
- } else {
1457
- connection = new Promise(
1458
- (resolveConnection, rejectConnection) => {
1459
- var _a3, _b;
1460
- const optionalScopes = addValidAccounts(
1461
- getOptionalScopes((_a3 = options == null ? void 0 : options.scopes) != null ? _a3 : []),
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 _a3, _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
+ (_a3 = walletSession == null ? void 0 : walletSession.sessionScopes) != null ? _a3 : {}
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 _a3;
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((_a3 = session.id) != null ? _a3 : "").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 _a3, _b;
1776
+ const { dappClient } = this;
1777
+ const isContinuingPriorAttempt = (yield this.getStoredPendingSessionRequest()) !== null;
1778
+ const connDeferred = createDeferredPromise();
1779
+ const optionalScopes = addValidAccounts(
1780
+ getOptionalScopes((_a3 = options == null ? void 0 : options.scopes) != null ? _a3 : []),
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
 
@@ -2083,6 +2135,7 @@ import { analytics as analytics2 } from "@metamask/analytics";
2083
2135
  import {
2084
2136
  getMultichainClient
2085
2137
  } from "@metamask/multichain-api-client";
2138
+ import { createDeferredPromise as createDeferredPromise2 } from "@metamask/utils";
2086
2139
 
2087
2140
  // src/config/index.ts
2088
2141
  var MWP_RELAY_URL = "wss://mm-sdk-relay.api.cx.metamask.io/connection/websocket";
@@ -2206,6 +2259,17 @@ import { analytics } from "@metamask/analytics";
2206
2259
  init_domain();
2207
2260
  init_utils2();
2208
2261
  init_analytics();
2262
+ function toRPCInvokeMethodErr(error) {
2263
+ var _a3;
2264
+ if (error instanceof RPCInvokeMethodErr) {
2265
+ return error;
2266
+ }
2267
+ const castError = error;
2268
+ return new RPCInvokeMethodErr(
2269
+ (_a3 = castError.message) != null ? _a3 : "Unknown error",
2270
+ castError.code
2271
+ );
2272
+ }
2209
2273
  var _RequestRouter_instances, withAnalyticsTracking_fn, trackWalletActionRequested_fn, trackWalletActionSucceeded_fn, trackWalletActionFailed_fn, trackWalletActionRejected_fn;
2210
2274
  var RequestRouter = class {
2211
2275
  constructor(transport, rpcClient, config, transportType) {
@@ -2225,6 +2289,9 @@ var RequestRouter = class {
2225
2289
  invokeMethod(options) {
2226
2290
  return __async(this, null, function* () {
2227
2291
  const { method } = options.request;
2292
+ if (EIP1193_PASSTHROUGH_METHODS.has(method)) {
2293
+ return this.handleWithEip1193Passthrough(options);
2294
+ }
2228
2295
  if (RPC_HANDLED_METHODS.has(method)) {
2229
2296
  return this.handleWithRpcNode(options);
2230
2297
  }
@@ -2234,6 +2301,29 @@ var RequestRouter = class {
2234
2301
  return this.handleWithWallet(options);
2235
2302
  });
2236
2303
  }
2304
+ /**
2305
+ * Forwards EIP-1193 / legacy provider methods (e.g. `wallet_addEthereumChain`,
2306
+ * `wallet_switchEthereumChain`, `eth_accounts`) directly to the underlying
2307
+ * transport's `sendEip1193Message`, bypassing the multichain
2308
+ * `wallet_invokeMethod` envelope. These methods are wallet-side concerns the
2309
+ * Multichain API does not model, so we forward the raw `{ method, params }`
2310
+ * payload and return the wallet's full JSON-RPC response envelope unchanged.
2311
+ *
2312
+ * Analytics tracking is intentionally skipped here: ecosystem clients
2313
+ * (e.g. `connect-evm`) emit their own `wallet_action_*` events around these
2314
+ * passthrough calls, and adding router-level tracking would double-count.
2315
+ *
2316
+ * @param options
2317
+ */
2318
+ handleWithEip1193Passthrough(options) {
2319
+ return __async(this, null, function* () {
2320
+ const response = yield this.transport.sendEip1193Message({
2321
+ method: options.request.method,
2322
+ params: options.request.params
2323
+ });
2324
+ return response.result;
2325
+ });
2326
+ }
2237
2327
  /**
2238
2328
  * Forwards the request directly to the wallet via the transport.
2239
2329
  *
@@ -2265,14 +2355,6 @@ var RequestRouter = class {
2265
2355
  }), 10);
2266
2356
  }
2267
2357
  const response = yield request;
2268
- if (response.error) {
2269
- const { error } = response;
2270
- throw new RPCInvokeMethodErr(
2271
- `RPC Request failed with code ${error.code}: ${error.message}`,
2272
- error.code,
2273
- error.message
2274
- );
2275
- }
2276
2358
  return response.result;
2277
2359
  }));
2278
2360
  });
@@ -2312,6 +2394,13 @@ _RequestRouter_instances = new WeakSet();
2312
2394
  withAnalyticsTracking_fn = function(options, execute) {
2313
2395
  return __async(this, null, function* () {
2314
2396
  var _a3;
2397
+ if (((_a3 = this.config.analytics) == null ? void 0 : _a3.enabled) === false) {
2398
+ try {
2399
+ return yield execute();
2400
+ } catch (error) {
2401
+ throw toRPCInvokeMethodErr(error);
2402
+ }
2403
+ }
2315
2404
  yield __privateMethod(this, _RequestRouter_instances, trackWalletActionRequested_fn).call(this, options);
2316
2405
  try {
2317
2406
  const result = yield execute();
@@ -2324,14 +2413,7 @@ withAnalyticsTracking_fn = function(options, execute) {
2324
2413
  } else {
2325
2414
  yield __privateMethod(this, _RequestRouter_instances, trackWalletActionFailed_fn).call(this, options, error);
2326
2415
  }
2327
- if (error instanceof RPCInvokeMethodErr) {
2328
- throw error;
2329
- }
2330
- const castError = error;
2331
- throw new RPCInvokeMethodErr(
2332
- (_a3 = castError.message) != null ? _a3 : "Unknown error",
2333
- castError.code
2334
- );
2416
+ throw toRPCInvokeMethodErr(error);
2335
2417
  }
2336
2418
  });
2337
2419
  };
@@ -2387,7 +2469,7 @@ import {
2387
2469
  getDefaultTransport
2388
2470
  } from "@metamask/multichain-api-client";
2389
2471
  var DEFAULT_REQUEST_TIMEOUT = 60 * 1e3;
2390
- var _notificationCallbacks, _transport, _defaultRequestOptions, _pendingRequests, _handleResponseListener, _handleNotificationListener, _DefaultTransport_instances, notifyCallbacks_fn, isMetamaskProviderEvent_fn, handleResponse_fn, handleNotification_fn, setupMessageListener_fn, init_fn;
2472
+ var _notificationCallbacks, _transport, _defaultRequestOptions, _pendingRequests, _handleResponseListener, _handleNotificationListener, _DefaultTransport_instances, notifyCallbacks_fn, parseWalletError_fn, isMetamaskProviderEvent_fn, handleResponse_fn, handleNotification_fn, setupMessageListener_fn, init_fn;
2391
2473
  var DefaultTransport = class {
2392
2474
  constructor() {
2393
2475
  __privateAdd(this, _DefaultTransport_instances);
@@ -2523,7 +2605,11 @@ var DefaultTransport = class {
2523
2605
  }
2524
2606
  request(_0) {
2525
2607
  return __async(this, arguments, function* (request, options = __privateGet(this, _defaultRequestOptions)) {
2526
- return __privateGet(this, _transport).request(request, options);
2608
+ const response = yield __privateGet(this, _transport).request(request, options);
2609
+ if (response.error) {
2610
+ throw __privateMethod(this, _DefaultTransport_instances, parseWalletError_fn).call(this, response.error);
2611
+ }
2612
+ return response;
2527
2613
  });
2528
2614
  }
2529
2615
  onNotification(callback) {
@@ -2567,6 +2653,16 @@ notifyCallbacks_fn = function(data) {
2567
2653
  }
2568
2654
  }
2569
2655
  };
2656
+ parseWalletError_fn = function(errorPayload) {
2657
+ const errorData = errorPayload;
2658
+ const error = new Error(
2659
+ typeof errorData.message === "string" ? errorData.message : "Request failed"
2660
+ );
2661
+ if (typeof errorData.code === "number") {
2662
+ error.code = errorData.code;
2663
+ }
2664
+ return error;
2665
+ };
2570
2666
  isMetamaskProviderEvent_fn = function(event) {
2571
2667
  var _a3, _b;
2572
2668
  return ((_b = (_a3 = event == null ? void 0 : event.data) == null ? void 0 : _a3.data) == null ? void 0 : _b.name) === "metamask-provider" && // eslint-disable-next-line no-restricted-globals
@@ -2589,13 +2685,7 @@ handleResponse_fn = function(event) {
2589
2685
  __privateGet(this, _pendingRequests).delete(responseId);
2590
2686
  const response = responseData;
2591
2687
  if ("error" in response && response.error) {
2592
- const error = new Error(
2593
- response.error.message || "Request failed"
2594
- );
2595
- if (typeof response.error.code === "number") {
2596
- error.code = response.error.code;
2597
- }
2598
- pendingRequest.reject(error);
2688
+ pendingRequest.reject(__privateMethod(this, _DefaultTransport_instances, parseWalletError_fn).call(this, response.error));
2599
2689
  } else {
2600
2690
  pendingRequest.resolve(response);
2601
2691
  }
@@ -2633,22 +2723,21 @@ init_fn = function() {
2633
2723
  // src/multichain/transports/multichainApiClientWrapper/index.ts
2634
2724
  init_utils2();
2635
2725
  import { providerErrors } from "@metamask/rpc-errors";
2636
- var _notificationCallbacks2, _MultichainApiClientWrapperTransport_instances, walletCreateSession_fn, walletGetSession_fn, walletRevokeSession_fn, walletInvokeMethod_fn;
2726
+ var _notificationCallbacks2, _getTransport, _MultichainApiClientWrapperTransport_instances, walletCreateSession_fn, walletGetSession_fn, walletRevokeSession_fn, walletInvokeMethod_fn;
2637
2727
  var MultichainApiClientWrapperTransport = class {
2638
- constructor(metamaskConnectMultichain) {
2728
+ constructor(metamaskConnectMultichain, getTransport) {
2639
2729
  this.metamaskConnectMultichain = metamaskConnectMultichain;
2640
2730
  __privateAdd(this, _MultichainApiClientWrapperTransport_instances);
2641
2731
  __privateAdd(this, _notificationCallbacks2, /* @__PURE__ */ new Set());
2732
+ __privateAdd(this, _getTransport);
2733
+ __privateSet(this, _getTransport, getTransport);
2642
2734
  }
2643
2735
  isTransportDefined() {
2644
- try {
2645
- return Boolean(this.metamaskConnectMultichain.transport);
2646
- } catch (_error) {
2647
- return false;
2648
- }
2736
+ return __privateGet(this, _getTransport).call(this) !== void 0;
2649
2737
  }
2650
2738
  isTransportConnected() {
2651
- return this.isTransportDefined() && this.metamaskConnectMultichain.transport.isConnected();
2739
+ var _a3, _b;
2740
+ return (_b = (_a3 = __privateGet(this, _getTransport).call(this)) == null ? void 0 : _a3.isConnected()) != null ? _b : false;
2652
2741
  }
2653
2742
  clearNotificationCallbacks() {
2654
2743
  __privateGet(this, _notificationCallbacks2).clear();
@@ -2664,10 +2753,11 @@ var MultichainApiClientWrapperTransport = class {
2664
2753
  this.notificationListener = void 0;
2665
2754
  }
2666
2755
  setupTransportNotificationListener() {
2667
- if (!this.isTransportDefined() || this.notificationListener) {
2756
+ const transport = __privateGet(this, _getTransport).call(this);
2757
+ if (!transport || this.notificationListener) {
2668
2758
  return;
2669
2759
  }
2670
- this.notificationListener = this.metamaskConnectMultichain.transport.onNotification(
2760
+ this.notificationListener = transport.onNotification(
2671
2761
  this.notifyCallbacks.bind(this)
2672
2762
  );
2673
2763
  }
@@ -2717,6 +2807,7 @@ var MultichainApiClientWrapperTransport = class {
2717
2807
  }
2718
2808
  };
2719
2809
  _notificationCallbacks2 = new WeakMap();
2810
+ _getTransport = new WeakMap();
2720
2811
  _MultichainApiClientWrapperTransport_instances = new WeakSet();
2721
2812
  walletCreateSession_fn = function(request) {
2722
2813
  return __async(this, null, function* () {
@@ -2740,14 +2831,19 @@ walletCreateSession_fn = function(request) {
2740
2831
  accounts,
2741
2832
  createSessionParams.sessionProperties
2742
2833
  );
2743
- return this.metamaskConnectMultichain.transport.request({
2834
+ const transport = __privateGet(this, _getTransport).call(this);
2835
+ if (!transport) {
2836
+ throw new Error("Transport not initialized after connect");
2837
+ }
2838
+ return transport.request({
2744
2839
  method: "wallet_getSession"
2745
2840
  });
2746
2841
  });
2747
2842
  };
2748
2843
  walletGetSession_fn = function(request) {
2749
2844
  return __async(this, null, function* () {
2750
- if (!this.isTransportConnected()) {
2845
+ const transport = __privateGet(this, _getTransport).call(this);
2846
+ if (!(transport == null ? void 0 : transport.isConnected())) {
2751
2847
  return {
2752
2848
  jsonrpc: "2.0",
2753
2849
  id: request.id,
@@ -2756,7 +2852,7 @@ walletGetSession_fn = function(request) {
2756
2852
  }
2757
2853
  };
2758
2854
  }
2759
- return this.metamaskConnectMultichain.transport.request({
2855
+ return transport.request({
2760
2856
  method: "wallet_getSession"
2761
2857
  });
2762
2858
  });
@@ -2792,26 +2888,63 @@ walletInvokeMethod_fn = function(request) {
2792
2888
  init_utils2();
2793
2889
  var logger2 = createLogger("metamask-sdk:core");
2794
2890
  var SINGLETON_KEY = "__METAMASK_CONNECT_MULTICHAIN_SINGLETON__";
2795
- var _a2, _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;
2891
+ function normalizeAnalyticsOptions(analyticsOptions) {
2892
+ var _a3;
2893
+ return __spreadProps(__spreadValues({}, analyticsOptions != null ? analyticsOptions : {}), {
2894
+ enabled: (_a3 = analyticsOptions == null ? void 0 : analyticsOptions.enabled) != null ? _a3 : true,
2895
+ // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
2896
+ integrationType: (analyticsOptions == null ? void 0 : analyticsOptions.integrationType) || "direct"
2897
+ });
2898
+ }
2899
+ function isAnalyticsEnabled(options) {
2900
+ var _a3;
2901
+ return ((_a3 = options.analytics) == null ? void 0 : _a3.enabled) !== false;
2902
+ }
2903
+ function setupAnalyticsGlobals(options, storage, setAnonId) {
2904
+ return __async(this, null, function* () {
2905
+ var _a3, _b;
2906
+ if (!isAnalyticsEnabled(options)) {
2907
+ setAnonId == null ? void 0 : setAnonId(void 0);
2908
+ analytics2.disable();
2909
+ return;
2910
+ }
2911
+ const platform = getPlatformType();
2912
+ const isBrowser = platform === "in-app-browser" /* MetaMaskMobileWebview */ || platform === "web-desktop" /* DesktopWeb */ || platform === "web-mobile" /* MobileWeb */;
2913
+ const isReactNative2 = platform === "react-native" /* ReactNative */;
2914
+ if (!isBrowser && !isReactNative2) {
2915
+ return;
2916
+ }
2917
+ const dappId = getDappId(options.dapp);
2918
+ const anonId = yield storage.getAnonId();
2919
+ setAnonId == null ? void 0 : setAnonId(anonId);
2920
+ const { integrationType } = (_a3 = options.analytics) != null ? _a3 : {
2921
+ integrationType: ""
2922
+ };
2923
+ analytics2.setGlobalProperty("mmconnect_versions", (_b = options.versions) != null ? _b : {});
2924
+ analytics2.setGlobalProperty("dapp_id", dappId);
2925
+ analytics2.setGlobalProperty("anon_id", anonId);
2926
+ analytics2.setGlobalProperty("platform", platform);
2927
+ if (integrationType) {
2928
+ analytics2.setGlobalProperty("integration_types", [integrationType]);
2929
+ }
2930
+ analytics2.enable();
2931
+ });
2932
+ }
2933
+ var _a2, _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;
2796
2934
  var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends MultichainCore {
2797
2935
  constructor(options) {
2798
- var _a3, _b, _c, _d, _e, _f;
2936
+ var _a3, _b, _c, _d;
2799
2937
  const withDappMetadata = setupDappMetadata(options);
2800
- const integrationType = ((_a3 = options.analytics) == null ? void 0 : _a3.integrationType) || "direct";
2801
2938
  const allOptions = __spreadProps(__spreadValues({}, withDappMetadata), {
2802
2939
  ui: __spreadProps(__spreadValues({}, withDappMetadata.ui), {
2803
- preferExtension: (_b = withDappMetadata.ui.preferExtension) != null ? _b : true,
2804
- showInstallModal: (_c = withDappMetadata.ui.showInstallModal) != null ? _c : false,
2805
- headless: (_d = withDappMetadata.ui.headless) != null ? _d : false
2806
- }),
2807
- analytics: __spreadProps(__spreadValues({}, (_e = options.analytics) != null ? _e : {}), {
2808
- integrationType
2940
+ preferExtension: (_a3 = withDappMetadata.ui.preferExtension) != null ? _a3 : true,
2941
+ showInstallModal: (_b = withDappMetadata.ui.showInstallModal) != null ? _b : false,
2942
+ headless: (_c = withDappMetadata.ui.headless) != null ? _c : false
2809
2943
  }),
2944
+ analytics: normalizeAnalyticsOptions(options.analytics),
2810
2945
  versions: __spreadValues({
2811
- // typeof guard needed: Metro (React Native) bundles TS source directly,
2812
- // bypassing the tsup build that substitutes __PACKAGE_VERSION__.
2813
- "connect-multichain": false ? "unknown" : "0.14.0"
2814
- }, (_f = options.versions) != null ? _f : {})
2946
+ "connect-multichain": getVersion()
2947
+ }, (_d = options.versions) != null ? _d : {})
2815
2948
  });
2816
2949
  super(allOptions);
2817
2950
  __privateAdd(this, _MetaMaskConnectMultichain_instances);
@@ -2826,7 +2959,8 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
2826
2959
  __privateAdd(this, _anonId);
2827
2960
  __privateAdd(this, _sdkInfo, `Sdk/Javascript SdkVersion/${getVersion()} Platform/${getPlatformType()} dApp/${(_a2 = this.options.dapp.url) != null ? _a2 : this.options.dapp.name} dAppTitle/${this.options.dapp.name}`);
2828
2961
  __privateSet(this, _providerTransportWrapper, new MultichainApiClientWrapperTransport(
2829
- this
2962
+ this,
2963
+ () => __privateGet(this, _transport2)
2830
2964
  ));
2831
2965
  __privateSet(this, _provider, getMultichainClient({
2832
2966
  transport: __privateGet(this, _providerTransportWrapper)
@@ -2845,12 +2979,6 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
2845
2979
  get provider() {
2846
2980
  return __privateGet(this, _provider);
2847
2981
  }
2848
- get transport() {
2849
- if (!__privateGet(this, _transport2)) {
2850
- throw new Error("Transport not initialized, establish connection first");
2851
- }
2852
- return __privateGet(this, _transport2);
2853
- }
2854
2982
  get dappClient() {
2855
2983
  if (!__privateGet(this, _dappClient)) {
2856
2984
  throw new Error("DappClient not initialized, establish connection first");
@@ -2864,28 +2992,33 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
2864
2992
  get storage() {
2865
2993
  return this.options.storage;
2866
2994
  }
2995
+ get version() {
2996
+ return getVersion();
2997
+ }
2867
2998
  // Creates a singleton instance of MetaMaskConnectMultichain.
2868
2999
  // If the singleton already exists, it merges the incoming options with the
2869
3000
  // existing singleton options for the following keys: `api.supportedNetworks`,
2870
- // `versions`, `ui.*`, `mobile.*`, `transport.extensionId`, `debug`. Take note
2871
- // that the value for `dapp` is not merged as it does not make sense for
2872
- // subsequent calls to `createMultichainClient` to have a different `dapp` value.
3001
+ // `analytics`, `versions`, `ui.*`, `mobile.*`, `transport.extensionId`,
3002
+ // `debug`. Take note that the value for `dapp` is not merged as it does not
3003
+ // make sense for subsequent calls to `createMultichainClient` to have a
3004
+ // different `dapp` value.
2873
3005
  static create(options) {
2874
3006
  return __async(this, null, function* () {
2875
- var _a3, _b;
3007
+ var _a3;
2876
3008
  const globalObject = getGlobalObject();
2877
3009
  const existing = globalObject[SINGLETON_KEY];
2878
3010
  if (existing) {
2879
3011
  const instance = yield existing;
3012
+ if (instance.version !== getVersion()) {
3013
+ console.warn(
3014
+ `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.`
3015
+ );
3016
+ }
2880
3017
  instance.mergeOptions(options);
2881
- analytics2.setGlobalProperty(
2882
- "mmconnect_versions",
2883
- (_a3 = instance.options.versions) != null ? _a3 : {}
2884
- );
2885
- if ((_b = options.analytics) == null ? void 0 : _b.integrationType) {
2886
- analytics2.setGlobalProperty("integration_types", [
2887
- options.analytics.integrationType
2888
- ]);
3018
+ if (instance instanceof _MetaMaskConnectMultichain) {
3019
+ yield __privateMethod(_a3 = instance, _MetaMaskConnectMultichain_instances, setupAnalytics_fn).call(_a3);
3020
+ } else {
3021
+ yield setupAnalyticsGlobals(instance.options, instance.storage);
2889
3022
  }
2890
3023
  if (options.debug) {
2891
3024
  enableDebug("metamask-sdk:*");
@@ -2904,12 +3037,12 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
2904
3037
  }
2905
3038
  yield __privateMethod(_a4 = instance, _MetaMaskConnectMultichain_instances, init_fn2).call(_a4);
2906
3039
  return instance;
2907
- }))();
2908
- globalObject[SINGLETON_KEY] = instancePromise;
2909
- instancePromise.catch((error) => {
3040
+ }))().catch((error) => {
2910
3041
  globalObject[SINGLETON_KEY] = void 0;
2911
3042
  console.error("Error initializing MetaMaskConnectMultichain", error);
3043
+ throw error;
2912
3044
  });
3045
+ globalObject[SINGLETON_KEY] = instancePromise;
2913
3046
  return instancePromise;
2914
3047
  });
2915
3048
  }
@@ -2935,21 +3068,23 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
2935
3068
  } else {
2936
3069
  transportType = "mwp" /* MWP */;
2937
3070
  }
2938
- try {
2939
- const baseProps = yield getBaseAnalyticsProperties(
2940
- this.options,
2941
- this.storage
2942
- );
2943
- const dappConfiguredChains = Object.keys(
2944
- this.options.api.supportedNetworks
2945
- );
2946
- analytics2.track("mmconnect_connection_initiated", __spreadProps(__spreadValues({}, baseProps), {
2947
- transport_type: transportType,
2948
- dapp_configured_chains: dappConfiguredChains,
2949
- dapp_requested_chains: scopes
2950
- }));
2951
- } catch (error) {
2952
- logger2("Error tracking connection_initiated event", error);
3071
+ if (isAnalyticsEnabled(this.options)) {
3072
+ try {
3073
+ const baseProps = yield getBaseAnalyticsProperties(
3074
+ this.options,
3075
+ this.storage
3076
+ );
3077
+ const dappConfiguredChains = Object.keys(
3078
+ this.options.api.supportedNetworks
3079
+ );
3080
+ analytics2.track("mmconnect_connection_initiated", __spreadProps(__spreadValues({}, baseProps), {
3081
+ transport_type: transportType,
3082
+ dapp_configured_chains: dappConfiguredChains,
3083
+ dapp_requested_chains: scopes
3084
+ }));
3085
+ } catch (error) {
3086
+ logger2("Error tracking connection_initiated event", error);
3087
+ }
2953
3088
  }
2954
3089
  const sessionData = yield __privateMethod(this, _MetaMaskConnectMultichain_instances, getCaipSession_fn).call(this);
2955
3090
  const { mergedScopes, mergedCaipAccountIds, mergedSessionProperties } = mergeRequestedSessionWithExisting(
@@ -2967,9 +3102,9 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
2967
3102
  forceRequest
2968
3103
  }).then(() => __async(this, null, function* () {
2969
3104
  if (__privateGet(this, _transportType) === "mwp" /* MWP */) {
2970
- return this.storage.setTransport("mwp" /* MWP */);
3105
+ return this.storage.setTransportType("mwp" /* MWP */);
2971
3106
  }
2972
- return this.storage.setTransport("browser" /* Browser */);
3107
+ return this.storage.setTransportType("browser" /* Browser */);
2973
3108
  })), scopes, transportType);
2974
3109
  }
2975
3110
  if (platformType === "in-app-browser" /* MetaMaskMobileWebview */) {
@@ -2998,11 +3133,6 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
2998
3133
  return __privateMethod(this, _MetaMaskConnectMultichain_instances, handleConnection_fn).call(this, __privateMethod(this, _MetaMaskConnectMultichain_instances, showInstallModal_fn).call(this, shouldShowInstallModal, mergedScopes, mergedCaipAccountIds, nonEmptySessionProperties), scopes, transportType);
2999
3134
  });
3000
3135
  }
3001
- emit(event, args) {
3002
- var _a3, _b;
3003
- (_b = (_a3 = this.options.transport) == null ? void 0 : _a3.onNotification) == null ? void 0 : _b.call(_a3, { method: event, params: args });
3004
- super.emit(event, args);
3005
- }
3006
3136
  disconnect() {
3007
3137
  return __async(this, arguments, function* (scopes = []) {
3008
3138
  var _a3, _b, _c;
@@ -3012,7 +3142,7 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
3012
3142
  );
3013
3143
  yield (_a3 = __privateGet(this, _transport2)) == null ? void 0 : _a3.disconnect(scopes);
3014
3144
  if (remainingScopes.length === 0) {
3015
- yield this.storage.removeTransport();
3145
+ yield this.storage.removeTransportType();
3016
3146
  if (__privateGet(this, _transportType) !== "browser" /* Browser */) {
3017
3147
  yield (_b = __privateGet(this, _listener)) == null ? void 0 : _b.call(this);
3018
3148
  (_c = __privateGet(this, _beforeUnloadListener)) == null ? void 0 : _c.call(this);
@@ -3030,7 +3160,8 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
3030
3160
  invokeMethod(request) {
3031
3161
  return __async(this, null, function* () {
3032
3162
  var _a3;
3033
- const { transport, options } = this;
3163
+ const transport = __privateMethod(this, _MetaMaskConnectMultichain_instances, transportOrThrow_fn).call(this);
3164
+ const { options } = this;
3034
3165
  const rpcClient = new RpcClient(options, __privateGet(this, _sdkInfo));
3035
3166
  const requestRouter = new RequestRouter(
3036
3167
  transport,
@@ -3049,7 +3180,7 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
3049
3180
  const shouldOpenDeeplink = secure && !showInstallModal;
3050
3181
  if (shouldOpenDeeplink) {
3051
3182
  setTimeout(() => __async(this, null, function* () {
3052
- const session = yield this.transport.getActiveSession();
3183
+ const session = yield __privateMethod(this, _MetaMaskConnectMultichain_instances, transportOrThrow_fn).call(this).getActiveSession();
3053
3184
  if (!session) {
3054
3185
  throw new Error("No active session found");
3055
3186
  }
@@ -3073,10 +3204,13 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
3073
3204
  this.emit("wallet_sessionChanged", emptySession);
3074
3205
  return;
3075
3206
  }
3076
- const response = yield this.transport.request({
3207
+ const response = yield __privateGet(this, _transport2).request({
3077
3208
  method: "wallet_getSession"
3078
3209
  });
3079
- this.emit("wallet_sessionChanged", (_b = response.result) != null ? _b : emptySession);
3210
+ this.emit(
3211
+ "wallet_sessionChanged",
3212
+ (_b = response.result) != null ? _b : emptySession
3213
+ );
3080
3214
  });
3081
3215
  }
3082
3216
  };
@@ -3088,34 +3222,19 @@ _beforeUnloadListener = new WeakMap();
3088
3222
  _transportType = new WeakMap();
3089
3223
  _listener = new WeakMap();
3090
3224
  _anonId = new WeakMap();
3091
- _sdkInfo = new WeakMap();
3092
3225
  _MetaMaskConnectMultichain_instances = new WeakSet();
3226
+ transportOrThrow_fn = function() {
3227
+ if (!__privateGet(this, _transport2)) {
3228
+ throw new Error("Transport not initialized, establish connection first");
3229
+ }
3230
+ return __privateGet(this, _transport2);
3231
+ };
3232
+ _sdkInfo = new WeakMap();
3093
3233
  setupAnalytics_fn = function() {
3094
3234
  return __async(this, null, function* () {
3095
- var _a3, _b;
3096
- const platform = getPlatformType();
3097
- const isBrowser = platform === "in-app-browser" /* MetaMaskMobileWebview */ || platform === "web-desktop" /* DesktopWeb */ || platform === "web-mobile" /* MobileWeb */;
3098
- const isReactNative2 = platform === "react-native" /* ReactNative */;
3099
- if (!isBrowser && !isReactNative2) {
3100
- return;
3101
- }
3102
- const dappId = getDappId(this.options.dapp);
3103
- const anonId = yield this.storage.getAnonId();
3104
- __privateSet(this, _anonId, anonId);
3105
- const { integrationType } = (_a3 = this.options.analytics) != null ? _a3 : {
3106
- integrationType: ""
3107
- };
3108
- analytics2.setGlobalProperty(
3109
- "mmconnect_versions",
3110
- (_b = this.options.versions) != null ? _b : {}
3111
- );
3112
- analytics2.setGlobalProperty("dapp_id", dappId);
3113
- analytics2.setGlobalProperty("anon_id", anonId);
3114
- analytics2.setGlobalProperty("platform", platform);
3115
- if (integrationType) {
3116
- analytics2.setGlobalProperty("integration_types", [integrationType]);
3117
- }
3118
- analytics2.enable();
3235
+ yield setupAnalyticsGlobals(this.options, this.storage, (anonId) => {
3236
+ __privateSet(this, _anonId, anonId);
3237
+ });
3119
3238
  });
3120
3239
  };
3121
3240
  onTransportNotification_fn = function(payload) {
@@ -3136,7 +3255,7 @@ onTransportNotification_fn = function(payload) {
3136
3255
  };
3137
3256
  getStoredTransport_fn = function() {
3138
3257
  return __async(this, null, function* () {
3139
- const transportType = yield this.storage.getTransport();
3258
+ const transportType = yield this.storage.getTransportType();
3140
3259
  const hasExtensionInstalled = yield hasExtension();
3141
3260
  if (transportType) {
3142
3261
  if (transportType === "browser" /* Browser */) {
@@ -3164,7 +3283,7 @@ getStoredTransport_fn = function() {
3164
3283
  ));
3165
3284
  return apiTransport;
3166
3285
  }
3167
- yield this.storage.removeTransport();
3286
+ yield this.storage.removeTransportType();
3168
3287
  }
3169
3288
  return void 0;
3170
3289
  });
@@ -3174,15 +3293,15 @@ setupTransport_fn = function() {
3174
3293
  var _a3;
3175
3294
  const transport = yield __privateMethod(this, _MetaMaskConnectMultichain_instances, getStoredTransport_fn).call(this);
3176
3295
  if (transport) {
3177
- if (!this.transport.isConnected()) {
3296
+ if (!transport.isConnected()) {
3178
3297
  this.status = "connecting";
3179
- yield this.transport.connect();
3298
+ yield transport.connect();
3180
3299
  }
3181
3300
  this.status = "connected";
3182
3301
  if (__privateGet(this, _transportType) === "mwp" /* MWP */) {
3183
- yield this.storage.setTransport("mwp" /* MWP */);
3302
+ yield this.storage.setTransportType("mwp" /* MWP */);
3184
3303
  } else {
3185
- yield this.storage.setTransport("browser" /* Browser */);
3304
+ yield this.storage.setTransportType("browser" /* Browser */);
3186
3305
  }
3187
3306
  } else {
3188
3307
  this.status = "loaded";
@@ -3191,7 +3310,7 @@ setupTransport_fn = function() {
3191
3310
  if (hasExtensionInstalled && preferExtension) {
3192
3311
  yield __privateMethod(this, _MetaMaskConnectMultichain_instances, setupDefaultTransport_fn).call(this, { persist: false });
3193
3312
  try {
3194
- yield this.transport.init();
3313
+ yield __privateMethod(this, _MetaMaskConnectMultichain_instances, transportOrThrow_fn).call(this).init();
3195
3314
  } catch (error) {
3196
3315
  console.error("Passive init failed:", error);
3197
3316
  }
@@ -3204,7 +3323,7 @@ buildConnectionMetadata_fn = function() {
3204
3323
  dapp: this.options.dapp,
3205
3324
  sdk: { version: getVersion(), platform: getPlatformType() }
3206
3325
  };
3207
- if (__privateGet(this, _anonId)) {
3326
+ if (isAnalyticsEnabled(this.options) && __privateGet(this, _anonId)) {
3208
3327
  metadata.analytics = { remote_session_id: __privateGet(this, _anonId) };
3209
3328
  }
3210
3329
  return metadata;
@@ -3215,7 +3334,7 @@ init_fn2 = function() {
3215
3334
  yield __privateMethod(this, _MetaMaskConnectMultichain_instances, setupAnalytics_fn).call(this);
3216
3335
  yield __privateMethod(this, _MetaMaskConnectMultichain_instances, setupTransport_fn).call(this);
3217
3336
  } catch (error) {
3218
- yield this.storage.removeTransport();
3337
+ yield this.storage.removeTransportType();
3219
3338
  this.status = "pending";
3220
3339
  logger2("MetaMaskSDK error during initialization", error);
3221
3340
  }
@@ -3261,17 +3380,17 @@ setupMWP_fn = function() {
3261
3380
  __privateSet(this, _transport2, apiTransport);
3262
3381
  __privateSet(this, _transportType, "mwp" /* MWP */);
3263
3382
  __privateGet(this, _providerTransportWrapper).setupTransportNotificationListener();
3264
- __privateSet(this, _listener, this.transport.onNotification(
3383
+ __privateSet(this, _listener, apiTransport.onNotification(
3265
3384
  __privateMethod(this, _MetaMaskConnectMultichain_instances, onTransportNotification_fn).bind(this)
3266
3385
  ));
3267
- yield this.storage.setTransport("mwp" /* MWP */);
3386
+ yield this.storage.setTransportType("mwp" /* MWP */);
3268
3387
  });
3269
3388
  };
3270
3389
  onBeforeUnload_fn = function() {
3271
3390
  return __async(this, null, function* () {
3272
3391
  var _a3;
3273
3392
  if ((_a3 = this.options.ui.factory.modal) == null ? void 0 : _a3.isMounted) {
3274
- yield this.storage.removeTransport();
3393
+ yield this.storage.removeTransportType();
3275
3394
  }
3276
3395
  });
3277
3396
  };
@@ -3288,70 +3407,65 @@ createBeforeUnloadListener_fn = function() {
3288
3407
  };
3289
3408
  renderInstallModalAsync_fn = function(desktopPreferred, scopes, caipAccountIds, sessionProperties) {
3290
3409
  return __async(this, null, function* () {
3291
- return new Promise((resolve, reject) => {
3292
- this.options.ui.factory.renderInstallModal(
3293
- desktopPreferred,
3294
- () => __async(this, null, function* () {
3295
- if (this.dappClient.state === "CONNECTED" || this.dappClient.state === "CONNECTING") {
3296
- yield this.dappClient.disconnect();
3297
- }
3298
- return new Promise((_resolve) => {
3299
- this.dappClient.on(
3300
- "session_request",
3301
- (sessionRequest) => {
3302
- _resolve({
3303
- sessionRequest,
3304
- metadata: __privateMethod(this, _MetaMaskConnectMultichain_instances, buildConnectionMetadata_fn).call(this)
3305
- });
3306
- }
3307
- );
3308
- (() => __async(this, null, function* () {
3309
- var _a3;
3310
- try {
3311
- yield this.transport.connect({
3312
- scopes,
3313
- caipAccountIds,
3314
- sessionProperties
3315
- });
3316
- yield this.options.ui.factory.unload();
3317
- (_a3 = this.options.ui.factory.modal) == null ? void 0 : _a3.unmount();
3318
- this.status = "connected";
3319
- yield this.storage.setTransport("mwp" /* MWP */);
3320
- } catch (error) {
3321
- const { ProtocolError, ErrorCode } = yield import("@metamask/mobile-wallet-protocol-core");
3322
- if (error instanceof ProtocolError) {
3323
- if (error.code !== ErrorCode.REQUEST_EXPIRED) {
3324
- this.status = "disconnected";
3325
- yield this.options.ui.factory.unload(error);
3326
- reject(error);
3327
- }
3328
- } else {
3329
- this.status = "disconnected";
3330
- const normalizedError = error instanceof Error ? error : new Error(String(error));
3331
- yield this.options.ui.factory.unload(normalizedError);
3332
- reject(normalizedError);
3333
- }
3334
- }
3335
- }))().catch(() => {
3336
- });
3410
+ const completion = createDeferredPromise2();
3411
+ const createConnectionRequest = () => __async(this, null, function* () {
3412
+ if (this.dappClient.state === "CONNECTED" || this.dappClient.state === "CONNECTING") {
3413
+ yield this.dappClient.disconnect();
3414
+ }
3415
+ const sessionRequestDeferred = createDeferredPromise2();
3416
+ this.dappClient.on(
3417
+ "session_request",
3418
+ (sessionRequest) => {
3419
+ sessionRequestDeferred.resolve({
3420
+ sessionRequest,
3421
+ metadata: __privateMethod(this, _MetaMaskConnectMultichain_instances, buildConnectionMetadata_fn).call(this)
3337
3422
  });
3338
- }),
3339
- (error) => __async(this, null, function* () {
3340
- if (error) {
3341
- yield this.storage.removeTransport();
3342
- reject(error);
3343
- } else {
3344
- yield this.storage.setTransport("mwp" /* MWP */);
3345
- resolve();
3423
+ }
3424
+ );
3425
+ __privateMethod(this, _MetaMaskConnectMultichain_instances, transportOrThrow_fn).call(this).connect({ scopes, caipAccountIds, sessionProperties }).then(() => __async(this, null, function* () {
3426
+ var _a3;
3427
+ yield this.options.ui.factory.unload();
3428
+ (_a3 = this.options.ui.factory.modal) == null ? void 0 : _a3.unmount();
3429
+ this.status = "connected";
3430
+ yield this.storage.setTransportType("mwp" /* MWP */);
3431
+ })).catch((error) => __async(this, null, function* () {
3432
+ const { ProtocolError, ErrorCode } = yield import("@metamask/mobile-wallet-protocol-core");
3433
+ if (error instanceof ProtocolError) {
3434
+ if (error.code !== ErrorCode.REQUEST_EXPIRED) {
3435
+ this.status = "disconnected";
3436
+ yield this.options.ui.factory.unload(error);
3437
+ completion.reject(error);
3346
3438
  }
3347
- }),
3348
- (uri) => {
3349
- this.emit("display_uri", uri);
3439
+ } else {
3440
+ this.status = "disconnected";
3441
+ const normalizedError = error instanceof Error ? error : new Error(String(error));
3442
+ yield this.options.ui.factory.unload(normalizedError);
3443
+ completion.reject(normalizedError);
3350
3444
  }
3351
- ).catch((error) => {
3352
- reject(error instanceof Error ? error : new Error(String(error)));
3353
- });
3445
+ }));
3446
+ return sessionRequestDeferred.promise;
3354
3447
  });
3448
+ this.options.ui.factory.renderInstallModal(
3449
+ desktopPreferred,
3450
+ createConnectionRequest,
3451
+ (error) => __async(this, null, function* () {
3452
+ if (error) {
3453
+ yield this.storage.removeTransportType();
3454
+ completion.reject(error);
3455
+ } else {
3456
+ yield this.storage.setTransportType("mwp" /* MWP */);
3457
+ completion.resolve();
3458
+ }
3459
+ }),
3460
+ (uri) => {
3461
+ this.emit("display_uri", uri);
3462
+ }
3463
+ ).catch((error) => {
3464
+ completion.reject(
3465
+ error instanceof Error ? error : new Error(String(error))
3466
+ );
3467
+ });
3468
+ return completion.promise;
3355
3469
  });
3356
3470
  };
3357
3471
  showInstallModal_fn = function(desktopPreferred, scopes, caipAccountIds, sessionProperties) {
@@ -3367,39 +3481,37 @@ showInstallModal_fn = function(desktopPreferred, scopes, caipAccountIds, session
3367
3481
  };
3368
3482
  headlessConnect_fn = function(scopes, caipAccountIds, sessionProperties) {
3369
3483
  return __async(this, null, function* () {
3370
- return new Promise((resolve, reject) => {
3371
- if (this.dappClient.state === "CONNECTED" || this.dappClient.state === "CONNECTING") {
3372
- this.dappClient.disconnect().catch(() => {
3373
- });
3484
+ if (this.dappClient.state === "CONNECTED" || this.dappClient.state === "CONNECTING") {
3485
+ yield this.dappClient.disconnect().catch(() => void 0);
3486
+ }
3487
+ const onSessionRequest = (sessionRequest) => {
3488
+ const connectionRequest = {
3489
+ sessionRequest,
3490
+ metadata: __privateMethod(this, _MetaMaskConnectMultichain_instances, buildConnectionMetadata_fn).call(this)
3491
+ };
3492
+ const deeplink = this.options.ui.factory.createConnectionDeeplink(connectionRequest);
3493
+ this.emit("display_uri", deeplink);
3494
+ };
3495
+ this.dappClient.on("session_request", onSessionRequest);
3496
+ try {
3497
+ yield __privateMethod(this, _MetaMaskConnectMultichain_instances, transportOrThrow_fn).call(this).connect({
3498
+ scopes,
3499
+ caipAccountIds,
3500
+ sessionProperties
3501
+ });
3502
+ this.status = "connected";
3503
+ yield this.storage.setTransportType("mwp" /* MWP */);
3504
+ } catch (error) {
3505
+ const { ProtocolError } = yield import("@metamask/mobile-wallet-protocol-core");
3506
+ this.status = "disconnected";
3507
+ yield this.storage.removeTransportType();
3508
+ if (error instanceof ProtocolError || error instanceof Error) {
3509
+ throw error;
3374
3510
  }
3375
- this.dappClient.on(
3376
- "session_request",
3377
- (sessionRequest) => {
3378
- const connectionRequest = {
3379
- sessionRequest,
3380
- metadata: __privateMethod(this, _MetaMaskConnectMultichain_instances, buildConnectionMetadata_fn).call(this)
3381
- };
3382
- const deeplink = this.options.ui.factory.createConnectionDeeplink(connectionRequest);
3383
- this.emit("display_uri", deeplink);
3384
- }
3385
- );
3386
- this.transport.connect({ scopes, caipAccountIds, sessionProperties }).then(() => __async(this, null, function* () {
3387
- this.status = "connected";
3388
- yield this.storage.setTransport("mwp" /* MWP */);
3389
- resolve();
3390
- })).catch((error) => __async(this, null, function* () {
3391
- const { ProtocolError } = yield import("@metamask/mobile-wallet-protocol-core");
3392
- if (error instanceof ProtocolError) {
3393
- this.status = "disconnected";
3394
- yield this.storage.removeTransport();
3395
- reject(error);
3396
- } else {
3397
- this.status = "disconnected";
3398
- yield this.storage.removeTransport();
3399
- reject(error instanceof Error ? error : new Error(String(error)));
3400
- }
3401
- }));
3402
- });
3511
+ throw new Error(String(error));
3512
+ } finally {
3513
+ this.dappClient.off("session_request", onSessionRequest);
3514
+ }
3403
3515
  });
3404
3516
  };
3405
3517
  setupDefaultTransport_fn = function() {
@@ -3408,7 +3520,7 @@ setupDefaultTransport_fn = function() {
3408
3520
  return __privateGet(this, _transport2);
3409
3521
  }
3410
3522
  if (options == null ? void 0 : options.persist) {
3411
- yield this.storage.setTransport("browser" /* Browser */);
3523
+ yield this.storage.setTransportType("browser" /* Browser */);
3412
3524
  }
3413
3525
  const transport = new DefaultTransport();
3414
3526
  __privateSet(this, _listener, transport.onNotification(
@@ -3441,7 +3553,7 @@ deeplinkConnect_fn = function(scopes, caipAccountIds, sessionProperties) {
3441
3553
  };
3442
3554
  this.dappClient.on("message", dappClientMessageHandler);
3443
3555
  let timeout;
3444
- if (this.transport.isConnected()) {
3556
+ if (__privateMethod(this, _MetaMaskConnectMultichain_instances, transportOrThrow_fn).call(this).isConnected()) {
3445
3557
  timeout = setTimeout(() => {
3446
3558
  this.openSimpleDeeplinkIfNeeded();
3447
3559
  }, 250);
@@ -3469,8 +3581,8 @@ deeplinkConnect_fn = function(scopes, caipAccountIds, sessionProperties) {
3469
3581
  }
3470
3582
  );
3471
3583
  }
3472
- return this.transport.connect({ scopes, caipAccountIds, sessionProperties }).then(resolve).catch((error) => __async(this, null, function* () {
3473
- yield this.storage.removeTransport();
3584
+ return __privateMethod(this, _MetaMaskConnectMultichain_instances, transportOrThrow_fn).call(this).connect({ scopes, caipAccountIds, sessionProperties }).then(resolve).catch((error) => __async(this, null, function* () {
3585
+ yield this.storage.removeTransportType();
3474
3586
  this.dappClient.off("message", dappClientMessageHandler);
3475
3587
  reject(error instanceof Error ? error : new Error(String(error)));
3476
3588
  })).finally(() => {
@@ -3486,38 +3598,42 @@ handleConnection_fn = function(promise, scopes, transportType) {
3486
3598
  this.status = "connecting";
3487
3599
  return promise.then(() => __async(this, null, function* () {
3488
3600
  this.status = "connected";
3489
- try {
3490
- const baseProps = yield getBaseAnalyticsProperties(
3491
- this.options,
3492
- this.storage
3493
- );
3494
- analytics2.track("mmconnect_connection_established", __spreadProps(__spreadValues({}, baseProps), {
3495
- transport_type: transportType,
3496
- user_permissioned_chains: scopes
3497
- }));
3498
- } catch (error) {
3499
- logger2("Error tracking connection_established event", error);
3601
+ if (isAnalyticsEnabled(this.options)) {
3602
+ try {
3603
+ const baseProps = yield getBaseAnalyticsProperties(
3604
+ this.options,
3605
+ this.storage
3606
+ );
3607
+ analytics2.track("mmconnect_connection_established", __spreadProps(__spreadValues({}, baseProps), {
3608
+ transport_type: transportType,
3609
+ user_permissioned_chains: scopes
3610
+ }));
3611
+ } catch (error) {
3612
+ logger2("Error tracking connection_established event", error);
3613
+ }
3500
3614
  }
3501
3615
  return void 0;
3502
3616
  })).catch((error) => __async(this, null, function* () {
3503
3617
  this.status = "disconnected";
3504
- try {
3505
- const baseProps = yield getBaseAnalyticsProperties(
3506
- this.options,
3507
- this.storage
3508
- );
3509
- const isRejection = isRejectionError(error);
3510
- if (isRejection) {
3511
- analytics2.track("mmconnect_connection_rejected", __spreadProps(__spreadValues({}, baseProps), {
3512
- transport_type: transportType
3513
- }));
3514
- } else {
3515
- analytics2.track("mmconnect_connection_failed", __spreadValues(__spreadProps(__spreadValues({}, baseProps), {
3516
- transport_type: transportType
3517
- }), extractErrorDiagnostics(error)));
3618
+ if (isAnalyticsEnabled(this.options)) {
3619
+ try {
3620
+ const baseProps = yield getBaseAnalyticsProperties(
3621
+ this.options,
3622
+ this.storage
3623
+ );
3624
+ const isRejection = isRejectionError(error);
3625
+ if (isRejection) {
3626
+ analytics2.track("mmconnect_connection_rejected", __spreadProps(__spreadValues({}, baseProps), {
3627
+ transport_type: transportType
3628
+ }));
3629
+ } else {
3630
+ analytics2.track("mmconnect_connection_failed", __spreadValues(__spreadProps(__spreadValues({}, baseProps), {
3631
+ transport_type: transportType
3632
+ }), extractErrorDiagnostics(error)));
3633
+ }
3634
+ } catch (e) {
3635
+ logger2("Error tracking connection failed/rejected event", error);
3518
3636
  }
3519
- } catch (e) {
3520
- logger2("Error tracking connection failed/rejected event", error);
3521
3637
  }
3522
3638
  throw error;
3523
3639
  }));
@@ -3532,7 +3648,7 @@ getCaipSession_fn = function() {
3532
3648
  };
3533
3649
  if ((_a3 = __privateGet(this, _transport2)) == null ? void 0 : _a3.isConnected()) {
3534
3650
  try {
3535
- const response = yield this.transport.request({
3651
+ const response = yield __privateGet(this, _transport2).request({
3536
3652
  method: "wallet_getSession"
3537
3653
  });
3538
3654
  if (response.result) {
@@ -3626,14 +3742,14 @@ var Store = class extends StoreClient {
3626
3742
  super();
3627
3743
  this.adapter = adapter;
3628
3744
  }
3629
- getTransport() {
3745
+ getTransportType() {
3630
3746
  return __async(this, null, function* () {
3631
3747
  try {
3632
- const transport = yield this.adapter.get("multichain-transport");
3633
- if (!transport) {
3748
+ const transportType = yield this.adapter.get("multichain-transport");
3749
+ if (!transportType) {
3634
3750
  return null;
3635
3751
  }
3636
- return getTransportType(transport);
3752
+ return getTransportType(transportType);
3637
3753
  } catch (err) {
3638
3754
  throw new StorageGetErr(
3639
3755
  this.adapter.platform,
@@ -3643,10 +3759,10 @@ var Store = class extends StoreClient {
3643
3759
  }
3644
3760
  });
3645
3761
  }
3646
- setTransport(transport) {
3762
+ setTransportType(transportType) {
3647
3763
  return __async(this, null, function* () {
3648
3764
  try {
3649
- yield this.adapter.set("multichain-transport", transport);
3765
+ yield this.adapter.set("multichain-transport", transportType);
3650
3766
  } catch (err) {
3651
3767
  throw new StorageSetErr(
3652
3768
  this.adapter.platform,
@@ -3656,7 +3772,7 @@ var Store = class extends StoreClient {
3656
3772
  }
3657
3773
  });
3658
3774
  }
3659
- removeTransport() {
3775
+ removeTransportType() {
3660
3776
  return __async(this, null, function* () {
3661
3777
  try {
3662
3778
  yield this.adapter.delete("multichain-transport");
@@ -3870,7 +3986,11 @@ var BaseModalFactory = class {
3870
3986
  (_a4 = this.displayUriCallback) == null ? void 0 : _a4.call(this, newLink);
3871
3987
  return newLink;
3872
3988
  }),
3873
- onClose: this.onCloseModal.bind(this),
3989
+ onClose: (shouldTerminate) => {
3990
+ this.onCloseModal(shouldTerminate).catch((error) => {
3991
+ console.error("Failed to close modal:", error);
3992
+ });
3993
+ },
3874
3994
  startDesktopOnboarding: this.onStartDesktopOnboarding.bind(this),
3875
3995
  createConnectionRequest,
3876
3996
  onDisplayUri: this.displayUriCallback
@@ -3941,6 +4061,7 @@ Original error: ${error instanceof Error ? error.message : error}`
3941
4061
  }));
3942
4062
  });
3943
4063
  export {
4064
+ EIP1193_PASSTHROUGH_METHODS,
3944
4065
  EventEmitter,
3945
4066
  Modal,
3946
4067
  MultichainCore,
@@ -3968,6 +4089,7 @@ export {
3968
4089
  isEnabled,
3969
4090
  isMetamaskExtensionInstalled,
3970
4091
  isRejectionError,
3971
- isSecure
4092
+ isSecure,
4093
+ packageVersion
3972
4094
  };
3973
4095
  //# sourceMappingURL=connect-multichain.mjs.map