@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
 
@@ -1976,9 +2028,7 @@ var init_install = __esm({
1976
2028
  mount() {
1977
2029
  var _a3;
1978
2030
  const { options } = this;
1979
- const modal = document.createElement(
1980
- "mm-install-modal"
1981
- );
2031
+ const modal = document.createElement("mm-install-modal");
1982
2032
  modal.showInstallModal = options.showInstallModal;
1983
2033
  modal.addEventListener("close", (ev) => {
1984
2034
  const { detail } = ev;
@@ -2174,6 +2224,7 @@ import { analytics as analytics2 } from "@metamask/analytics";
2174
2224
  import {
2175
2225
  getMultichainClient
2176
2226
  } from "@metamask/multichain-api-client";
2227
+ import { createDeferredPromise as createDeferredPromise2 } from "@metamask/utils";
2177
2228
 
2178
2229
  // src/config/index.ts
2179
2230
  var MWP_RELAY_URL = "wss://mm-sdk-relay.api.cx.metamask.io/connection/websocket";
@@ -2297,6 +2348,17 @@ import { analytics } from "@metamask/analytics";
2297
2348
  init_domain();
2298
2349
  init_utils2();
2299
2350
  init_analytics();
2351
+ function toRPCInvokeMethodErr(error) {
2352
+ var _a3;
2353
+ if (error instanceof RPCInvokeMethodErr) {
2354
+ return error;
2355
+ }
2356
+ const castError = error;
2357
+ return new RPCInvokeMethodErr(
2358
+ (_a3 = castError.message) != null ? _a3 : "Unknown error",
2359
+ castError.code
2360
+ );
2361
+ }
2300
2362
  var _RequestRouter_instances, withAnalyticsTracking_fn, trackWalletActionRequested_fn, trackWalletActionSucceeded_fn, trackWalletActionFailed_fn, trackWalletActionRejected_fn;
2301
2363
  var RequestRouter = class {
2302
2364
  constructor(transport, rpcClient, config, transportType) {
@@ -2316,6 +2378,9 @@ var RequestRouter = class {
2316
2378
  invokeMethod(options) {
2317
2379
  return __async(this, null, function* () {
2318
2380
  const { method } = options.request;
2381
+ if (EIP1193_PASSTHROUGH_METHODS.has(method)) {
2382
+ return this.handleWithEip1193Passthrough(options);
2383
+ }
2319
2384
  if (RPC_HANDLED_METHODS.has(method)) {
2320
2385
  return this.handleWithRpcNode(options);
2321
2386
  }
@@ -2325,6 +2390,29 @@ var RequestRouter = class {
2325
2390
  return this.handleWithWallet(options);
2326
2391
  });
2327
2392
  }
2393
+ /**
2394
+ * Forwards EIP-1193 / legacy provider methods (e.g. `wallet_addEthereumChain`,
2395
+ * `wallet_switchEthereumChain`, `eth_accounts`) directly to the underlying
2396
+ * transport's `sendEip1193Message`, bypassing the multichain
2397
+ * `wallet_invokeMethod` envelope. These methods are wallet-side concerns the
2398
+ * Multichain API does not model, so we forward the raw `{ method, params }`
2399
+ * payload and return the wallet's full JSON-RPC response envelope unchanged.
2400
+ *
2401
+ * Analytics tracking is intentionally skipped here: ecosystem clients
2402
+ * (e.g. `connect-evm`) emit their own `wallet_action_*` events around these
2403
+ * passthrough calls, and adding router-level tracking would double-count.
2404
+ *
2405
+ * @param options
2406
+ */
2407
+ handleWithEip1193Passthrough(options) {
2408
+ return __async(this, null, function* () {
2409
+ const response = yield this.transport.sendEip1193Message({
2410
+ method: options.request.method,
2411
+ params: options.request.params
2412
+ });
2413
+ return response.result;
2414
+ });
2415
+ }
2328
2416
  /**
2329
2417
  * Forwards the request directly to the wallet via the transport.
2330
2418
  *
@@ -2356,14 +2444,6 @@ var RequestRouter = class {
2356
2444
  }), 10);
2357
2445
  }
2358
2446
  const response = yield request;
2359
- if (response.error) {
2360
- const { error } = response;
2361
- throw new RPCInvokeMethodErr(
2362
- `RPC Request failed with code ${error.code}: ${error.message}`,
2363
- error.code,
2364
- error.message
2365
- );
2366
- }
2367
2447
  return response.result;
2368
2448
  }));
2369
2449
  });
@@ -2403,6 +2483,13 @@ _RequestRouter_instances = new WeakSet();
2403
2483
  withAnalyticsTracking_fn = function(options, execute) {
2404
2484
  return __async(this, null, function* () {
2405
2485
  var _a3;
2486
+ if (((_a3 = this.config.analytics) == null ? void 0 : _a3.enabled) === false) {
2487
+ try {
2488
+ return yield execute();
2489
+ } catch (error) {
2490
+ throw toRPCInvokeMethodErr(error);
2491
+ }
2492
+ }
2406
2493
  yield __privateMethod(this, _RequestRouter_instances, trackWalletActionRequested_fn).call(this, options);
2407
2494
  try {
2408
2495
  const result = yield execute();
@@ -2415,14 +2502,7 @@ withAnalyticsTracking_fn = function(options, execute) {
2415
2502
  } else {
2416
2503
  yield __privateMethod(this, _RequestRouter_instances, trackWalletActionFailed_fn).call(this, options, error);
2417
2504
  }
2418
- if (error instanceof RPCInvokeMethodErr) {
2419
- throw error;
2420
- }
2421
- const castError = error;
2422
- throw new RPCInvokeMethodErr(
2423
- (_a3 = castError.message) != null ? _a3 : "Unknown error",
2424
- castError.code
2425
- );
2505
+ throw toRPCInvokeMethodErr(error);
2426
2506
  }
2427
2507
  });
2428
2508
  };
@@ -2478,7 +2558,7 @@ import {
2478
2558
  getDefaultTransport
2479
2559
  } from "@metamask/multichain-api-client";
2480
2560
  var DEFAULT_REQUEST_TIMEOUT = 60 * 1e3;
2481
- var _notificationCallbacks, _transport, _defaultRequestOptions, _pendingRequests, _handleResponseListener, _handleNotificationListener, _DefaultTransport_instances, notifyCallbacks_fn, isMetamaskProviderEvent_fn, handleResponse_fn, handleNotification_fn, setupMessageListener_fn, init_fn;
2561
+ var _notificationCallbacks, _transport, _defaultRequestOptions, _pendingRequests, _handleResponseListener, _handleNotificationListener, _DefaultTransport_instances, notifyCallbacks_fn, parseWalletError_fn, isMetamaskProviderEvent_fn, handleResponse_fn, handleNotification_fn, setupMessageListener_fn, init_fn;
2482
2562
  var DefaultTransport = class {
2483
2563
  constructor() {
2484
2564
  __privateAdd(this, _DefaultTransport_instances);
@@ -2614,7 +2694,11 @@ var DefaultTransport = class {
2614
2694
  }
2615
2695
  request(_0) {
2616
2696
  return __async(this, arguments, function* (request, options = __privateGet(this, _defaultRequestOptions)) {
2617
- return __privateGet(this, _transport).request(request, options);
2697
+ const response = yield __privateGet(this, _transport).request(request, options);
2698
+ if (response.error) {
2699
+ throw __privateMethod(this, _DefaultTransport_instances, parseWalletError_fn).call(this, response.error);
2700
+ }
2701
+ return response;
2618
2702
  });
2619
2703
  }
2620
2704
  onNotification(callback) {
@@ -2658,6 +2742,16 @@ notifyCallbacks_fn = function(data) {
2658
2742
  }
2659
2743
  }
2660
2744
  };
2745
+ parseWalletError_fn = function(errorPayload) {
2746
+ const errorData = errorPayload;
2747
+ const error = new Error(
2748
+ typeof errorData.message === "string" ? errorData.message : "Request failed"
2749
+ );
2750
+ if (typeof errorData.code === "number") {
2751
+ error.code = errorData.code;
2752
+ }
2753
+ return error;
2754
+ };
2661
2755
  isMetamaskProviderEvent_fn = function(event) {
2662
2756
  var _a3, _b;
2663
2757
  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
@@ -2680,13 +2774,7 @@ handleResponse_fn = function(event) {
2680
2774
  __privateGet(this, _pendingRequests).delete(responseId);
2681
2775
  const response = responseData;
2682
2776
  if ("error" in response && response.error) {
2683
- const error = new Error(
2684
- response.error.message || "Request failed"
2685
- );
2686
- if (typeof response.error.code === "number") {
2687
- error.code = response.error.code;
2688
- }
2689
- pendingRequest.reject(error);
2777
+ pendingRequest.reject(__privateMethod(this, _DefaultTransport_instances, parseWalletError_fn).call(this, response.error));
2690
2778
  } else {
2691
2779
  pendingRequest.resolve(response);
2692
2780
  }
@@ -2724,22 +2812,21 @@ init_fn = function() {
2724
2812
  // src/multichain/transports/multichainApiClientWrapper/index.ts
2725
2813
  init_utils2();
2726
2814
  import { providerErrors } from "@metamask/rpc-errors";
2727
- var _notificationCallbacks2, _MultichainApiClientWrapperTransport_instances, walletCreateSession_fn, walletGetSession_fn, walletRevokeSession_fn, walletInvokeMethod_fn;
2815
+ var _notificationCallbacks2, _getTransport, _MultichainApiClientWrapperTransport_instances, walletCreateSession_fn, walletGetSession_fn, walletRevokeSession_fn, walletInvokeMethod_fn;
2728
2816
  var MultichainApiClientWrapperTransport = class {
2729
- constructor(metamaskConnectMultichain) {
2817
+ constructor(metamaskConnectMultichain, getTransport) {
2730
2818
  this.metamaskConnectMultichain = metamaskConnectMultichain;
2731
2819
  __privateAdd(this, _MultichainApiClientWrapperTransport_instances);
2732
2820
  __privateAdd(this, _notificationCallbacks2, /* @__PURE__ */ new Set());
2821
+ __privateAdd(this, _getTransport);
2822
+ __privateSet(this, _getTransport, getTransport);
2733
2823
  }
2734
2824
  isTransportDefined() {
2735
- try {
2736
- return Boolean(this.metamaskConnectMultichain.transport);
2737
- } catch (_error) {
2738
- return false;
2739
- }
2825
+ return __privateGet(this, _getTransport).call(this) !== void 0;
2740
2826
  }
2741
2827
  isTransportConnected() {
2742
- return this.isTransportDefined() && this.metamaskConnectMultichain.transport.isConnected();
2828
+ var _a3, _b;
2829
+ return (_b = (_a3 = __privateGet(this, _getTransport).call(this)) == null ? void 0 : _a3.isConnected()) != null ? _b : false;
2743
2830
  }
2744
2831
  clearNotificationCallbacks() {
2745
2832
  __privateGet(this, _notificationCallbacks2).clear();
@@ -2755,10 +2842,11 @@ var MultichainApiClientWrapperTransport = class {
2755
2842
  this.notificationListener = void 0;
2756
2843
  }
2757
2844
  setupTransportNotificationListener() {
2758
- if (!this.isTransportDefined() || this.notificationListener) {
2845
+ const transport = __privateGet(this, _getTransport).call(this);
2846
+ if (!transport || this.notificationListener) {
2759
2847
  return;
2760
2848
  }
2761
- this.notificationListener = this.metamaskConnectMultichain.transport.onNotification(
2849
+ this.notificationListener = transport.onNotification(
2762
2850
  this.notifyCallbacks.bind(this)
2763
2851
  );
2764
2852
  }
@@ -2808,6 +2896,7 @@ var MultichainApiClientWrapperTransport = class {
2808
2896
  }
2809
2897
  };
2810
2898
  _notificationCallbacks2 = new WeakMap();
2899
+ _getTransport = new WeakMap();
2811
2900
  _MultichainApiClientWrapperTransport_instances = new WeakSet();
2812
2901
  walletCreateSession_fn = function(request) {
2813
2902
  return __async(this, null, function* () {
@@ -2831,14 +2920,19 @@ walletCreateSession_fn = function(request) {
2831
2920
  accounts,
2832
2921
  createSessionParams.sessionProperties
2833
2922
  );
2834
- return this.metamaskConnectMultichain.transport.request({
2923
+ const transport = __privateGet(this, _getTransport).call(this);
2924
+ if (!transport) {
2925
+ throw new Error("Transport not initialized after connect");
2926
+ }
2927
+ return transport.request({
2835
2928
  method: "wallet_getSession"
2836
2929
  });
2837
2930
  });
2838
2931
  };
2839
2932
  walletGetSession_fn = function(request) {
2840
2933
  return __async(this, null, function* () {
2841
- if (!this.isTransportConnected()) {
2934
+ const transport = __privateGet(this, _getTransport).call(this);
2935
+ if (!(transport == null ? void 0 : transport.isConnected())) {
2842
2936
  return {
2843
2937
  jsonrpc: "2.0",
2844
2938
  id: request.id,
@@ -2847,7 +2941,7 @@ walletGetSession_fn = function(request) {
2847
2941
  }
2848
2942
  };
2849
2943
  }
2850
- return this.metamaskConnectMultichain.transport.request({
2944
+ return transport.request({
2851
2945
  method: "wallet_getSession"
2852
2946
  });
2853
2947
  });
@@ -2883,26 +2977,63 @@ walletInvokeMethod_fn = function(request) {
2883
2977
  init_utils2();
2884
2978
  var logger2 = createLogger("metamask-sdk:core");
2885
2979
  var SINGLETON_KEY = "__METAMASK_CONNECT_MULTICHAIN_SINGLETON__";
2886
- 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;
2980
+ function normalizeAnalyticsOptions(analyticsOptions) {
2981
+ var _a3;
2982
+ return __spreadProps(__spreadValues({}, analyticsOptions != null ? analyticsOptions : {}), {
2983
+ enabled: (_a3 = analyticsOptions == null ? void 0 : analyticsOptions.enabled) != null ? _a3 : true,
2984
+ // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
2985
+ integrationType: (analyticsOptions == null ? void 0 : analyticsOptions.integrationType) || "direct"
2986
+ });
2987
+ }
2988
+ function isAnalyticsEnabled(options) {
2989
+ var _a3;
2990
+ return ((_a3 = options.analytics) == null ? void 0 : _a3.enabled) !== false;
2991
+ }
2992
+ function setupAnalyticsGlobals(options, storage, setAnonId) {
2993
+ return __async(this, null, function* () {
2994
+ var _a3, _b;
2995
+ if (!isAnalyticsEnabled(options)) {
2996
+ setAnonId == null ? void 0 : setAnonId(void 0);
2997
+ analytics2.disable();
2998
+ return;
2999
+ }
3000
+ const platform = getPlatformType();
3001
+ const isBrowser = platform === "in-app-browser" /* MetaMaskMobileWebview */ || platform === "web-desktop" /* DesktopWeb */ || platform === "web-mobile" /* MobileWeb */;
3002
+ const isReactNative2 = platform === "react-native" /* ReactNative */;
3003
+ if (!isBrowser && !isReactNative2) {
3004
+ return;
3005
+ }
3006
+ const dappId = getDappId(options.dapp);
3007
+ const anonId = yield storage.getAnonId();
3008
+ setAnonId == null ? void 0 : setAnonId(anonId);
3009
+ const { integrationType } = (_a3 = options.analytics) != null ? _a3 : {
3010
+ integrationType: ""
3011
+ };
3012
+ analytics2.setGlobalProperty("mmconnect_versions", (_b = options.versions) != null ? _b : {});
3013
+ analytics2.setGlobalProperty("dapp_id", dappId);
3014
+ analytics2.setGlobalProperty("anon_id", anonId);
3015
+ analytics2.setGlobalProperty("platform", platform);
3016
+ if (integrationType) {
3017
+ analytics2.setGlobalProperty("integration_types", [integrationType]);
3018
+ }
3019
+ analytics2.enable();
3020
+ });
3021
+ }
3022
+ 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;
2887
3023
  var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends MultichainCore {
2888
3024
  constructor(options) {
2889
- var _a3, _b, _c, _d, _e, _f;
3025
+ var _a3, _b, _c, _d;
2890
3026
  const withDappMetadata = setupDappMetadata(options);
2891
- const integrationType = ((_a3 = options.analytics) == null ? void 0 : _a3.integrationType) || "direct";
2892
3027
  const allOptions = __spreadProps(__spreadValues({}, withDappMetadata), {
2893
3028
  ui: __spreadProps(__spreadValues({}, withDappMetadata.ui), {
2894
- preferExtension: (_b = withDappMetadata.ui.preferExtension) != null ? _b : true,
2895
- showInstallModal: (_c = withDappMetadata.ui.showInstallModal) != null ? _c : false,
2896
- headless: (_d = withDappMetadata.ui.headless) != null ? _d : false
2897
- }),
2898
- analytics: __spreadProps(__spreadValues({}, (_e = options.analytics) != null ? _e : {}), {
2899
- integrationType
3029
+ preferExtension: (_a3 = withDappMetadata.ui.preferExtension) != null ? _a3 : true,
3030
+ showInstallModal: (_b = withDappMetadata.ui.showInstallModal) != null ? _b : false,
3031
+ headless: (_c = withDappMetadata.ui.headless) != null ? _c : false
2900
3032
  }),
3033
+ analytics: normalizeAnalyticsOptions(options.analytics),
2901
3034
  versions: __spreadValues({
2902
- // typeof guard needed: Metro (React Native) bundles TS source directly,
2903
- // bypassing the tsup build that substitutes __PACKAGE_VERSION__.
2904
- "connect-multichain": false ? "unknown" : "0.14.0"
2905
- }, (_f = options.versions) != null ? _f : {})
3035
+ "connect-multichain": getVersion()
3036
+ }, (_d = options.versions) != null ? _d : {})
2906
3037
  });
2907
3038
  super(allOptions);
2908
3039
  __privateAdd(this, _MetaMaskConnectMultichain_instances);
@@ -2917,7 +3048,8 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
2917
3048
  __privateAdd(this, _anonId);
2918
3049
  __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}`);
2919
3050
  __privateSet(this, _providerTransportWrapper, new MultichainApiClientWrapperTransport(
2920
- this
3051
+ this,
3052
+ () => __privateGet(this, _transport2)
2921
3053
  ));
2922
3054
  __privateSet(this, _provider, getMultichainClient({
2923
3055
  transport: __privateGet(this, _providerTransportWrapper)
@@ -2936,12 +3068,6 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
2936
3068
  get provider() {
2937
3069
  return __privateGet(this, _provider);
2938
3070
  }
2939
- get transport() {
2940
- if (!__privateGet(this, _transport2)) {
2941
- throw new Error("Transport not initialized, establish connection first");
2942
- }
2943
- return __privateGet(this, _transport2);
2944
- }
2945
3071
  get dappClient() {
2946
3072
  if (!__privateGet(this, _dappClient)) {
2947
3073
  throw new Error("DappClient not initialized, establish connection first");
@@ -2955,28 +3081,33 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
2955
3081
  get storage() {
2956
3082
  return this.options.storage;
2957
3083
  }
3084
+ get version() {
3085
+ return getVersion();
3086
+ }
2958
3087
  // Creates a singleton instance of MetaMaskConnectMultichain.
2959
3088
  // If the singleton already exists, it merges the incoming options with the
2960
3089
  // existing singleton options for the following keys: `api.supportedNetworks`,
2961
- // `versions`, `ui.*`, `mobile.*`, `transport.extensionId`, `debug`. Take note
2962
- // that the value for `dapp` is not merged as it does not make sense for
2963
- // subsequent calls to `createMultichainClient` to have a different `dapp` value.
3090
+ // `analytics`, `versions`, `ui.*`, `mobile.*`, `transport.extensionId`,
3091
+ // `debug`. Take note that the value for `dapp` is not merged as it does not
3092
+ // make sense for subsequent calls to `createMultichainClient` to have a
3093
+ // different `dapp` value.
2964
3094
  static create(options) {
2965
3095
  return __async(this, null, function* () {
2966
- var _a3, _b;
3096
+ var _a3;
2967
3097
  const globalObject = getGlobalObject();
2968
3098
  const existing = globalObject[SINGLETON_KEY];
2969
3099
  if (existing) {
2970
3100
  const instance = yield existing;
3101
+ if (instance.version !== getVersion()) {
3102
+ console.warn(
3103
+ `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.`
3104
+ );
3105
+ }
2971
3106
  instance.mergeOptions(options);
2972
- analytics2.setGlobalProperty(
2973
- "mmconnect_versions",
2974
- (_a3 = instance.options.versions) != null ? _a3 : {}
2975
- );
2976
- if ((_b = options.analytics) == null ? void 0 : _b.integrationType) {
2977
- analytics2.setGlobalProperty("integration_types", [
2978
- options.analytics.integrationType
2979
- ]);
3107
+ if (instance instanceof _MetaMaskConnectMultichain) {
3108
+ yield __privateMethod(_a3 = instance, _MetaMaskConnectMultichain_instances, setupAnalytics_fn).call(_a3);
3109
+ } else {
3110
+ yield setupAnalyticsGlobals(instance.options, instance.storage);
2980
3111
  }
2981
3112
  if (options.debug) {
2982
3113
  enableDebug("metamask-sdk:*");
@@ -2995,12 +3126,12 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
2995
3126
  }
2996
3127
  yield __privateMethod(_a4 = instance, _MetaMaskConnectMultichain_instances, init_fn2).call(_a4);
2997
3128
  return instance;
2998
- }))();
2999
- globalObject[SINGLETON_KEY] = instancePromise;
3000
- instancePromise.catch((error) => {
3129
+ }))().catch((error) => {
3001
3130
  globalObject[SINGLETON_KEY] = void 0;
3002
3131
  console.error("Error initializing MetaMaskConnectMultichain", error);
3132
+ throw error;
3003
3133
  });
3134
+ globalObject[SINGLETON_KEY] = instancePromise;
3004
3135
  return instancePromise;
3005
3136
  });
3006
3137
  }
@@ -3026,21 +3157,23 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
3026
3157
  } else {
3027
3158
  transportType = "mwp" /* MWP */;
3028
3159
  }
3029
- try {
3030
- const baseProps = yield getBaseAnalyticsProperties(
3031
- this.options,
3032
- this.storage
3033
- );
3034
- const dappConfiguredChains = Object.keys(
3035
- this.options.api.supportedNetworks
3036
- );
3037
- analytics2.track("mmconnect_connection_initiated", __spreadProps(__spreadValues({}, baseProps), {
3038
- transport_type: transportType,
3039
- dapp_configured_chains: dappConfiguredChains,
3040
- dapp_requested_chains: scopes
3041
- }));
3042
- } catch (error) {
3043
- logger2("Error tracking connection_initiated event", error);
3160
+ if (isAnalyticsEnabled(this.options)) {
3161
+ try {
3162
+ const baseProps = yield getBaseAnalyticsProperties(
3163
+ this.options,
3164
+ this.storage
3165
+ );
3166
+ const dappConfiguredChains = Object.keys(
3167
+ this.options.api.supportedNetworks
3168
+ );
3169
+ analytics2.track("mmconnect_connection_initiated", __spreadProps(__spreadValues({}, baseProps), {
3170
+ transport_type: transportType,
3171
+ dapp_configured_chains: dappConfiguredChains,
3172
+ dapp_requested_chains: scopes
3173
+ }));
3174
+ } catch (error) {
3175
+ logger2("Error tracking connection_initiated event", error);
3176
+ }
3044
3177
  }
3045
3178
  const sessionData = yield __privateMethod(this, _MetaMaskConnectMultichain_instances, getCaipSession_fn).call(this);
3046
3179
  const { mergedScopes, mergedCaipAccountIds, mergedSessionProperties } = mergeRequestedSessionWithExisting(
@@ -3058,9 +3191,9 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
3058
3191
  forceRequest
3059
3192
  }).then(() => __async(this, null, function* () {
3060
3193
  if (__privateGet(this, _transportType) === "mwp" /* MWP */) {
3061
- return this.storage.setTransport("mwp" /* MWP */);
3194
+ return this.storage.setTransportType("mwp" /* MWP */);
3062
3195
  }
3063
- return this.storage.setTransport("browser" /* Browser */);
3196
+ return this.storage.setTransportType("browser" /* Browser */);
3064
3197
  })), scopes, transportType);
3065
3198
  }
3066
3199
  if (platformType === "in-app-browser" /* MetaMaskMobileWebview */) {
@@ -3089,11 +3222,6 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
3089
3222
  return __privateMethod(this, _MetaMaskConnectMultichain_instances, handleConnection_fn).call(this, __privateMethod(this, _MetaMaskConnectMultichain_instances, showInstallModal_fn).call(this, shouldShowInstallModal, mergedScopes, mergedCaipAccountIds, nonEmptySessionProperties), scopes, transportType);
3090
3223
  });
3091
3224
  }
3092
- emit(event, args) {
3093
- var _a3, _b;
3094
- (_b = (_a3 = this.options.transport) == null ? void 0 : _a3.onNotification) == null ? void 0 : _b.call(_a3, { method: event, params: args });
3095
- super.emit(event, args);
3096
- }
3097
3225
  disconnect() {
3098
3226
  return __async(this, arguments, function* (scopes = []) {
3099
3227
  var _a3, _b, _c;
@@ -3103,7 +3231,7 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
3103
3231
  );
3104
3232
  yield (_a3 = __privateGet(this, _transport2)) == null ? void 0 : _a3.disconnect(scopes);
3105
3233
  if (remainingScopes.length === 0) {
3106
- yield this.storage.removeTransport();
3234
+ yield this.storage.removeTransportType();
3107
3235
  if (__privateGet(this, _transportType) !== "browser" /* Browser */) {
3108
3236
  yield (_b = __privateGet(this, _listener)) == null ? void 0 : _b.call(this);
3109
3237
  (_c = __privateGet(this, _beforeUnloadListener)) == null ? void 0 : _c.call(this);
@@ -3121,7 +3249,8 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
3121
3249
  invokeMethod(request) {
3122
3250
  return __async(this, null, function* () {
3123
3251
  var _a3;
3124
- const { transport, options } = this;
3252
+ const transport = __privateMethod(this, _MetaMaskConnectMultichain_instances, transportOrThrow_fn).call(this);
3253
+ const { options } = this;
3125
3254
  const rpcClient = new RpcClient(options, __privateGet(this, _sdkInfo));
3126
3255
  const requestRouter = new RequestRouter(
3127
3256
  transport,
@@ -3140,7 +3269,7 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
3140
3269
  const shouldOpenDeeplink = secure && !showInstallModal;
3141
3270
  if (shouldOpenDeeplink) {
3142
3271
  setTimeout(() => __async(this, null, function* () {
3143
- const session = yield this.transport.getActiveSession();
3272
+ const session = yield __privateMethod(this, _MetaMaskConnectMultichain_instances, transportOrThrow_fn).call(this).getActiveSession();
3144
3273
  if (!session) {
3145
3274
  throw new Error("No active session found");
3146
3275
  }
@@ -3164,10 +3293,13 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
3164
3293
  this.emit("wallet_sessionChanged", emptySession);
3165
3294
  return;
3166
3295
  }
3167
- const response = yield this.transport.request({
3296
+ const response = yield __privateGet(this, _transport2).request({
3168
3297
  method: "wallet_getSession"
3169
3298
  });
3170
- this.emit("wallet_sessionChanged", (_b = response.result) != null ? _b : emptySession);
3299
+ this.emit(
3300
+ "wallet_sessionChanged",
3301
+ (_b = response.result) != null ? _b : emptySession
3302
+ );
3171
3303
  });
3172
3304
  }
3173
3305
  };
@@ -3179,34 +3311,19 @@ _beforeUnloadListener = new WeakMap();
3179
3311
  _transportType = new WeakMap();
3180
3312
  _listener = new WeakMap();
3181
3313
  _anonId = new WeakMap();
3182
- _sdkInfo = new WeakMap();
3183
3314
  _MetaMaskConnectMultichain_instances = new WeakSet();
3315
+ transportOrThrow_fn = function() {
3316
+ if (!__privateGet(this, _transport2)) {
3317
+ throw new Error("Transport not initialized, establish connection first");
3318
+ }
3319
+ return __privateGet(this, _transport2);
3320
+ };
3321
+ _sdkInfo = new WeakMap();
3184
3322
  setupAnalytics_fn = function() {
3185
3323
  return __async(this, null, function* () {
3186
- var _a3, _b;
3187
- const platform = getPlatformType();
3188
- const isBrowser = platform === "in-app-browser" /* MetaMaskMobileWebview */ || platform === "web-desktop" /* DesktopWeb */ || platform === "web-mobile" /* MobileWeb */;
3189
- const isReactNative2 = platform === "react-native" /* ReactNative */;
3190
- if (!isBrowser && !isReactNative2) {
3191
- return;
3192
- }
3193
- const dappId = getDappId(this.options.dapp);
3194
- const anonId = yield this.storage.getAnonId();
3195
- __privateSet(this, _anonId, anonId);
3196
- const { integrationType } = (_a3 = this.options.analytics) != null ? _a3 : {
3197
- integrationType: ""
3198
- };
3199
- analytics2.setGlobalProperty(
3200
- "mmconnect_versions",
3201
- (_b = this.options.versions) != null ? _b : {}
3202
- );
3203
- analytics2.setGlobalProperty("dapp_id", dappId);
3204
- analytics2.setGlobalProperty("anon_id", anonId);
3205
- analytics2.setGlobalProperty("platform", platform);
3206
- if (integrationType) {
3207
- analytics2.setGlobalProperty("integration_types", [integrationType]);
3208
- }
3209
- analytics2.enable();
3324
+ yield setupAnalyticsGlobals(this.options, this.storage, (anonId) => {
3325
+ __privateSet(this, _anonId, anonId);
3326
+ });
3210
3327
  });
3211
3328
  };
3212
3329
  onTransportNotification_fn = function(payload) {
@@ -3227,7 +3344,7 @@ onTransportNotification_fn = function(payload) {
3227
3344
  };
3228
3345
  getStoredTransport_fn = function() {
3229
3346
  return __async(this, null, function* () {
3230
- const transportType = yield this.storage.getTransport();
3347
+ const transportType = yield this.storage.getTransportType();
3231
3348
  const hasExtensionInstalled = yield hasExtension();
3232
3349
  if (transportType) {
3233
3350
  if (transportType === "browser" /* Browser */) {
@@ -3255,7 +3372,7 @@ getStoredTransport_fn = function() {
3255
3372
  ));
3256
3373
  return apiTransport;
3257
3374
  }
3258
- yield this.storage.removeTransport();
3375
+ yield this.storage.removeTransportType();
3259
3376
  }
3260
3377
  return void 0;
3261
3378
  });
@@ -3265,15 +3382,15 @@ setupTransport_fn = function() {
3265
3382
  var _a3;
3266
3383
  const transport = yield __privateMethod(this, _MetaMaskConnectMultichain_instances, getStoredTransport_fn).call(this);
3267
3384
  if (transport) {
3268
- if (!this.transport.isConnected()) {
3385
+ if (!transport.isConnected()) {
3269
3386
  this.status = "connecting";
3270
- yield this.transport.connect();
3387
+ yield transport.connect();
3271
3388
  }
3272
3389
  this.status = "connected";
3273
3390
  if (__privateGet(this, _transportType) === "mwp" /* MWP */) {
3274
- yield this.storage.setTransport("mwp" /* MWP */);
3391
+ yield this.storage.setTransportType("mwp" /* MWP */);
3275
3392
  } else {
3276
- yield this.storage.setTransport("browser" /* Browser */);
3393
+ yield this.storage.setTransportType("browser" /* Browser */);
3277
3394
  }
3278
3395
  } else {
3279
3396
  this.status = "loaded";
@@ -3282,7 +3399,7 @@ setupTransport_fn = function() {
3282
3399
  if (hasExtensionInstalled && preferExtension) {
3283
3400
  yield __privateMethod(this, _MetaMaskConnectMultichain_instances, setupDefaultTransport_fn).call(this, { persist: false });
3284
3401
  try {
3285
- yield this.transport.init();
3402
+ yield __privateMethod(this, _MetaMaskConnectMultichain_instances, transportOrThrow_fn).call(this).init();
3286
3403
  } catch (error) {
3287
3404
  console.error("Passive init failed:", error);
3288
3405
  }
@@ -3295,7 +3412,7 @@ buildConnectionMetadata_fn = function() {
3295
3412
  dapp: this.options.dapp,
3296
3413
  sdk: { version: getVersion(), platform: getPlatformType() }
3297
3414
  };
3298
- if (__privateGet(this, _anonId)) {
3415
+ if (isAnalyticsEnabled(this.options) && __privateGet(this, _anonId)) {
3299
3416
  metadata.analytics = { remote_session_id: __privateGet(this, _anonId) };
3300
3417
  }
3301
3418
  return metadata;
@@ -3306,7 +3423,7 @@ init_fn2 = function() {
3306
3423
  yield __privateMethod(this, _MetaMaskConnectMultichain_instances, setupAnalytics_fn).call(this);
3307
3424
  yield __privateMethod(this, _MetaMaskConnectMultichain_instances, setupTransport_fn).call(this);
3308
3425
  } catch (error) {
3309
- yield this.storage.removeTransport();
3426
+ yield this.storage.removeTransportType();
3310
3427
  this.status = "pending";
3311
3428
  logger2("MetaMaskSDK error during initialization", error);
3312
3429
  }
@@ -3352,17 +3469,17 @@ setupMWP_fn = function() {
3352
3469
  __privateSet(this, _transport2, apiTransport);
3353
3470
  __privateSet(this, _transportType, "mwp" /* MWP */);
3354
3471
  __privateGet(this, _providerTransportWrapper).setupTransportNotificationListener();
3355
- __privateSet(this, _listener, this.transport.onNotification(
3472
+ __privateSet(this, _listener, apiTransport.onNotification(
3356
3473
  __privateMethod(this, _MetaMaskConnectMultichain_instances, onTransportNotification_fn).bind(this)
3357
3474
  ));
3358
- yield this.storage.setTransport("mwp" /* MWP */);
3475
+ yield this.storage.setTransportType("mwp" /* MWP */);
3359
3476
  });
3360
3477
  };
3361
3478
  onBeforeUnload_fn = function() {
3362
3479
  return __async(this, null, function* () {
3363
3480
  var _a3;
3364
3481
  if ((_a3 = this.options.ui.factory.modal) == null ? void 0 : _a3.isMounted) {
3365
- yield this.storage.removeTransport();
3482
+ yield this.storage.removeTransportType();
3366
3483
  }
3367
3484
  });
3368
3485
  };
@@ -3379,70 +3496,65 @@ createBeforeUnloadListener_fn = function() {
3379
3496
  };
3380
3497
  renderInstallModalAsync_fn = function(desktopPreferred, scopes, caipAccountIds, sessionProperties) {
3381
3498
  return __async(this, null, function* () {
3382
- return new Promise((resolve, reject) => {
3383
- this.options.ui.factory.renderInstallModal(
3384
- desktopPreferred,
3385
- () => __async(this, null, function* () {
3386
- if (this.dappClient.state === "CONNECTED" || this.dappClient.state === "CONNECTING") {
3387
- yield this.dappClient.disconnect();
3388
- }
3389
- return new Promise((_resolve) => {
3390
- this.dappClient.on(
3391
- "session_request",
3392
- (sessionRequest) => {
3393
- _resolve({
3394
- sessionRequest,
3395
- metadata: __privateMethod(this, _MetaMaskConnectMultichain_instances, buildConnectionMetadata_fn).call(this)
3396
- });
3397
- }
3398
- );
3399
- (() => __async(this, null, function* () {
3400
- var _a3;
3401
- try {
3402
- yield this.transport.connect({
3403
- scopes,
3404
- caipAccountIds,
3405
- sessionProperties
3406
- });
3407
- yield this.options.ui.factory.unload();
3408
- (_a3 = this.options.ui.factory.modal) == null ? void 0 : _a3.unmount();
3409
- this.status = "connected";
3410
- yield this.storage.setTransport("mwp" /* MWP */);
3411
- } catch (error) {
3412
- const { ProtocolError, ErrorCode } = yield import("@metamask/mobile-wallet-protocol-core");
3413
- if (error instanceof ProtocolError) {
3414
- if (error.code !== ErrorCode.REQUEST_EXPIRED) {
3415
- this.status = "disconnected";
3416
- yield this.options.ui.factory.unload(error);
3417
- reject(error);
3418
- }
3419
- } else {
3420
- this.status = "disconnected";
3421
- const normalizedError = error instanceof Error ? error : new Error(String(error));
3422
- yield this.options.ui.factory.unload(normalizedError);
3423
- reject(normalizedError);
3424
- }
3425
- }
3426
- }))().catch(() => {
3427
- });
3499
+ const completion = createDeferredPromise2();
3500
+ const createConnectionRequest = () => __async(this, null, function* () {
3501
+ if (this.dappClient.state === "CONNECTED" || this.dappClient.state === "CONNECTING") {
3502
+ yield this.dappClient.disconnect();
3503
+ }
3504
+ const sessionRequestDeferred = createDeferredPromise2();
3505
+ this.dappClient.on(
3506
+ "session_request",
3507
+ (sessionRequest) => {
3508
+ sessionRequestDeferred.resolve({
3509
+ sessionRequest,
3510
+ metadata: __privateMethod(this, _MetaMaskConnectMultichain_instances, buildConnectionMetadata_fn).call(this)
3428
3511
  });
3429
- }),
3430
- (error) => __async(this, null, function* () {
3431
- if (error) {
3432
- yield this.storage.removeTransport();
3433
- reject(error);
3434
- } else {
3435
- yield this.storage.setTransport("mwp" /* MWP */);
3436
- resolve();
3512
+ }
3513
+ );
3514
+ __privateMethod(this, _MetaMaskConnectMultichain_instances, transportOrThrow_fn).call(this).connect({ scopes, caipAccountIds, sessionProperties }).then(() => __async(this, null, function* () {
3515
+ var _a3;
3516
+ yield this.options.ui.factory.unload();
3517
+ (_a3 = this.options.ui.factory.modal) == null ? void 0 : _a3.unmount();
3518
+ this.status = "connected";
3519
+ yield this.storage.setTransportType("mwp" /* MWP */);
3520
+ })).catch((error) => __async(this, null, function* () {
3521
+ const { ProtocolError, ErrorCode } = yield import("@metamask/mobile-wallet-protocol-core");
3522
+ if (error instanceof ProtocolError) {
3523
+ if (error.code !== ErrorCode.REQUEST_EXPIRED) {
3524
+ this.status = "disconnected";
3525
+ yield this.options.ui.factory.unload(error);
3526
+ completion.reject(error);
3437
3527
  }
3438
- }),
3439
- (uri) => {
3440
- this.emit("display_uri", uri);
3528
+ } else {
3529
+ this.status = "disconnected";
3530
+ const normalizedError = error instanceof Error ? error : new Error(String(error));
3531
+ yield this.options.ui.factory.unload(normalizedError);
3532
+ completion.reject(normalizedError);
3441
3533
  }
3442
- ).catch((error) => {
3443
- reject(error instanceof Error ? error : new Error(String(error)));
3444
- });
3534
+ }));
3535
+ return sessionRequestDeferred.promise;
3445
3536
  });
3537
+ this.options.ui.factory.renderInstallModal(
3538
+ desktopPreferred,
3539
+ createConnectionRequest,
3540
+ (error) => __async(this, null, function* () {
3541
+ if (error) {
3542
+ yield this.storage.removeTransportType();
3543
+ completion.reject(error);
3544
+ } else {
3545
+ yield this.storage.setTransportType("mwp" /* MWP */);
3546
+ completion.resolve();
3547
+ }
3548
+ }),
3549
+ (uri) => {
3550
+ this.emit("display_uri", uri);
3551
+ }
3552
+ ).catch((error) => {
3553
+ completion.reject(
3554
+ error instanceof Error ? error : new Error(String(error))
3555
+ );
3556
+ });
3557
+ return completion.promise;
3446
3558
  });
3447
3559
  };
3448
3560
  showInstallModal_fn = function(desktopPreferred, scopes, caipAccountIds, sessionProperties) {
@@ -3458,39 +3570,37 @@ showInstallModal_fn = function(desktopPreferred, scopes, caipAccountIds, session
3458
3570
  };
3459
3571
  headlessConnect_fn = function(scopes, caipAccountIds, sessionProperties) {
3460
3572
  return __async(this, null, function* () {
3461
- return new Promise((resolve, reject) => {
3462
- if (this.dappClient.state === "CONNECTED" || this.dappClient.state === "CONNECTING") {
3463
- this.dappClient.disconnect().catch(() => {
3464
- });
3573
+ if (this.dappClient.state === "CONNECTED" || this.dappClient.state === "CONNECTING") {
3574
+ yield this.dappClient.disconnect().catch(() => void 0);
3575
+ }
3576
+ const onSessionRequest = (sessionRequest) => {
3577
+ const connectionRequest = {
3578
+ sessionRequest,
3579
+ metadata: __privateMethod(this, _MetaMaskConnectMultichain_instances, buildConnectionMetadata_fn).call(this)
3580
+ };
3581
+ const deeplink = this.options.ui.factory.createConnectionDeeplink(connectionRequest);
3582
+ this.emit("display_uri", deeplink);
3583
+ };
3584
+ this.dappClient.on("session_request", onSessionRequest);
3585
+ try {
3586
+ yield __privateMethod(this, _MetaMaskConnectMultichain_instances, transportOrThrow_fn).call(this).connect({
3587
+ scopes,
3588
+ caipAccountIds,
3589
+ sessionProperties
3590
+ });
3591
+ this.status = "connected";
3592
+ yield this.storage.setTransportType("mwp" /* MWP */);
3593
+ } catch (error) {
3594
+ const { ProtocolError } = yield import("@metamask/mobile-wallet-protocol-core");
3595
+ this.status = "disconnected";
3596
+ yield this.storage.removeTransportType();
3597
+ if (error instanceof ProtocolError || error instanceof Error) {
3598
+ throw error;
3465
3599
  }
3466
- this.dappClient.on(
3467
- "session_request",
3468
- (sessionRequest) => {
3469
- const connectionRequest = {
3470
- sessionRequest,
3471
- metadata: __privateMethod(this, _MetaMaskConnectMultichain_instances, buildConnectionMetadata_fn).call(this)
3472
- };
3473
- const deeplink = this.options.ui.factory.createConnectionDeeplink(connectionRequest);
3474
- this.emit("display_uri", deeplink);
3475
- }
3476
- );
3477
- this.transport.connect({ scopes, caipAccountIds, sessionProperties }).then(() => __async(this, null, function* () {
3478
- this.status = "connected";
3479
- yield this.storage.setTransport("mwp" /* MWP */);
3480
- resolve();
3481
- })).catch((error) => __async(this, null, function* () {
3482
- const { ProtocolError } = yield import("@metamask/mobile-wallet-protocol-core");
3483
- if (error instanceof ProtocolError) {
3484
- this.status = "disconnected";
3485
- yield this.storage.removeTransport();
3486
- reject(error);
3487
- } else {
3488
- this.status = "disconnected";
3489
- yield this.storage.removeTransport();
3490
- reject(error instanceof Error ? error : new Error(String(error)));
3491
- }
3492
- }));
3493
- });
3600
+ throw new Error(String(error));
3601
+ } finally {
3602
+ this.dappClient.off("session_request", onSessionRequest);
3603
+ }
3494
3604
  });
3495
3605
  };
3496
3606
  setupDefaultTransport_fn = function() {
@@ -3499,7 +3609,7 @@ setupDefaultTransport_fn = function() {
3499
3609
  return __privateGet(this, _transport2);
3500
3610
  }
3501
3611
  if (options == null ? void 0 : options.persist) {
3502
- yield this.storage.setTransport("browser" /* Browser */);
3612
+ yield this.storage.setTransportType("browser" /* Browser */);
3503
3613
  }
3504
3614
  const transport = new DefaultTransport();
3505
3615
  __privateSet(this, _listener, transport.onNotification(
@@ -3532,7 +3642,7 @@ deeplinkConnect_fn = function(scopes, caipAccountIds, sessionProperties) {
3532
3642
  };
3533
3643
  this.dappClient.on("message", dappClientMessageHandler);
3534
3644
  let timeout;
3535
- if (this.transport.isConnected()) {
3645
+ if (__privateMethod(this, _MetaMaskConnectMultichain_instances, transportOrThrow_fn).call(this).isConnected()) {
3536
3646
  timeout = setTimeout(() => {
3537
3647
  this.openSimpleDeeplinkIfNeeded();
3538
3648
  }, 250);
@@ -3560,8 +3670,8 @@ deeplinkConnect_fn = function(scopes, caipAccountIds, sessionProperties) {
3560
3670
  }
3561
3671
  );
3562
3672
  }
3563
- return this.transport.connect({ scopes, caipAccountIds, sessionProperties }).then(resolve).catch((error) => __async(this, null, function* () {
3564
- yield this.storage.removeTransport();
3673
+ return __privateMethod(this, _MetaMaskConnectMultichain_instances, transportOrThrow_fn).call(this).connect({ scopes, caipAccountIds, sessionProperties }).then(resolve).catch((error) => __async(this, null, function* () {
3674
+ yield this.storage.removeTransportType();
3565
3675
  this.dappClient.off("message", dappClientMessageHandler);
3566
3676
  reject(error instanceof Error ? error : new Error(String(error)));
3567
3677
  })).finally(() => {
@@ -3577,38 +3687,42 @@ handleConnection_fn = function(promise, scopes, transportType) {
3577
3687
  this.status = "connecting";
3578
3688
  return promise.then(() => __async(this, null, function* () {
3579
3689
  this.status = "connected";
3580
- try {
3581
- const baseProps = yield getBaseAnalyticsProperties(
3582
- this.options,
3583
- this.storage
3584
- );
3585
- analytics2.track("mmconnect_connection_established", __spreadProps(__spreadValues({}, baseProps), {
3586
- transport_type: transportType,
3587
- user_permissioned_chains: scopes
3588
- }));
3589
- } catch (error) {
3590
- logger2("Error tracking connection_established event", error);
3690
+ if (isAnalyticsEnabled(this.options)) {
3691
+ try {
3692
+ const baseProps = yield getBaseAnalyticsProperties(
3693
+ this.options,
3694
+ this.storage
3695
+ );
3696
+ analytics2.track("mmconnect_connection_established", __spreadProps(__spreadValues({}, baseProps), {
3697
+ transport_type: transportType,
3698
+ user_permissioned_chains: scopes
3699
+ }));
3700
+ } catch (error) {
3701
+ logger2("Error tracking connection_established event", error);
3702
+ }
3591
3703
  }
3592
3704
  return void 0;
3593
3705
  })).catch((error) => __async(this, null, function* () {
3594
3706
  this.status = "disconnected";
3595
- try {
3596
- const baseProps = yield getBaseAnalyticsProperties(
3597
- this.options,
3598
- this.storage
3599
- );
3600
- const isRejection = isRejectionError(error);
3601
- if (isRejection) {
3602
- analytics2.track("mmconnect_connection_rejected", __spreadProps(__spreadValues({}, baseProps), {
3603
- transport_type: transportType
3604
- }));
3605
- } else {
3606
- analytics2.track("mmconnect_connection_failed", __spreadValues(__spreadProps(__spreadValues({}, baseProps), {
3607
- transport_type: transportType
3608
- }), extractErrorDiagnostics(error)));
3707
+ if (isAnalyticsEnabled(this.options)) {
3708
+ try {
3709
+ const baseProps = yield getBaseAnalyticsProperties(
3710
+ this.options,
3711
+ this.storage
3712
+ );
3713
+ const isRejection = isRejectionError(error);
3714
+ if (isRejection) {
3715
+ analytics2.track("mmconnect_connection_rejected", __spreadProps(__spreadValues({}, baseProps), {
3716
+ transport_type: transportType
3717
+ }));
3718
+ } else {
3719
+ analytics2.track("mmconnect_connection_failed", __spreadValues(__spreadProps(__spreadValues({}, baseProps), {
3720
+ transport_type: transportType
3721
+ }), extractErrorDiagnostics(error)));
3722
+ }
3723
+ } catch (e) {
3724
+ logger2("Error tracking connection failed/rejected event", error);
3609
3725
  }
3610
- } catch (e) {
3611
- logger2("Error tracking connection failed/rejected event", error);
3612
3726
  }
3613
3727
  throw error;
3614
3728
  }));
@@ -3623,7 +3737,7 @@ getCaipSession_fn = function() {
3623
3737
  };
3624
3738
  if ((_a3 = __privateGet(this, _transport2)) == null ? void 0 : _a3.isConnected()) {
3625
3739
  try {
3626
- const response = yield this.transport.request({
3740
+ const response = yield __privateGet(this, _transport2).request({
3627
3741
  method: "wallet_getSession"
3628
3742
  });
3629
3743
  if (response.result) {
@@ -3717,14 +3831,14 @@ var Store = class extends StoreClient {
3717
3831
  super();
3718
3832
  this.adapter = adapter;
3719
3833
  }
3720
- getTransport() {
3834
+ getTransportType() {
3721
3835
  return __async(this, null, function* () {
3722
3836
  try {
3723
- const transport = yield this.adapter.get("multichain-transport");
3724
- if (!transport) {
3837
+ const transportType = yield this.adapter.get("multichain-transport");
3838
+ if (!transportType) {
3725
3839
  return null;
3726
3840
  }
3727
- return getTransportType(transport);
3841
+ return getTransportType(transportType);
3728
3842
  } catch (err) {
3729
3843
  throw new StorageGetErr(
3730
3844
  this.adapter.platform,
@@ -3734,10 +3848,10 @@ var Store = class extends StoreClient {
3734
3848
  }
3735
3849
  });
3736
3850
  }
3737
- setTransport(transport) {
3851
+ setTransportType(transportType) {
3738
3852
  return __async(this, null, function* () {
3739
3853
  try {
3740
- yield this.adapter.set("multichain-transport", transport);
3854
+ yield this.adapter.set("multichain-transport", transportType);
3741
3855
  } catch (err) {
3742
3856
  throw new StorageSetErr(
3743
3857
  this.adapter.platform,
@@ -3747,7 +3861,7 @@ var Store = class extends StoreClient {
3747
3861
  }
3748
3862
  });
3749
3863
  }
3750
- removeTransport() {
3864
+ removeTransportType() {
3751
3865
  return __async(this, null, function* () {
3752
3866
  try {
3753
3867
  yield this.adapter.delete("multichain-transport");
@@ -3961,7 +4075,11 @@ var BaseModalFactory = class {
3961
4075
  (_a4 = this.displayUriCallback) == null ? void 0 : _a4.call(this, newLink);
3962
4076
  return newLink;
3963
4077
  }),
3964
- onClose: this.onCloseModal.bind(this),
4078
+ onClose: (shouldTerminate) => {
4079
+ this.onCloseModal(shouldTerminate).catch((error) => {
4080
+ console.error("Failed to close modal:", error);
4081
+ });
4082
+ },
3965
4083
  startDesktopOnboarding: this.onStartDesktopOnboarding.bind(this),
3966
4084
  createConnectionRequest,
3967
4085
  onDisplayUri: this.displayUriCallback
@@ -3999,7 +4117,7 @@ function preload() {
3999
4117
  }
4000
4118
  try {
4001
4119
  const { defineCustomElements } = yield import("@metamask/multichain-ui/loader");
4002
- yield defineCustomElements();
4120
+ defineCustomElements();
4003
4121
  } catch (error) {
4004
4122
  console.error("Failed to load customElements:", error);
4005
4123
  }
@@ -4037,6 +4155,7 @@ var createMultichainClient = (options) => __async(null, null, function* () {
4037
4155
  }));
4038
4156
  });
4039
4157
  export {
4158
+ EIP1193_PASSTHROUGH_METHODS,
4040
4159
  EventEmitter,
4041
4160
  Modal,
4042
4161
  MultichainCore,
@@ -4064,6 +4183,7 @@ export {
4064
4183
  isEnabled,
4065
4184
  isMetamaskExtensionInstalled,
4066
4185
  isRejectionError,
4067
- isSecure
4186
+ isSecure,
4187
+ packageVersion
4068
4188
  };
4069
4189
  //# sourceMappingURL=connect-multichain.mjs.map