@metamask/connect-multichain 0.15.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 (76) hide show
  1. package/CHANGELOG.md +28 -1
  2. package/README.md +0 -1
  3. package/dist/browser/es/connect-multichain.d.mts +7 -6
  4. package/dist/browser/es/connect-multichain.mjs +451 -368
  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 +7 -6
  8. package/dist/browser/iife/connect-multichain.js +464 -368
  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 +7 -6
  12. package/dist/browser/umd/connect-multichain.js +451 -368
  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 +7 -6
  16. package/dist/node/cjs/connect-multichain.js +453 -366
  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 +7 -6
  20. package/dist/node/es/connect-multichain.mjs +450 -365
  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 +7 -6
  24. package/dist/react-native/es/connect-multichain.mjs +449 -364
  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 +2 -2
  32. package/dist/src/domain/multichain/index.d.ts.map +1 -1
  33. package/dist/src/domain/multichain/index.js.map +1 -1
  34. package/dist/src/domain/multichain/types.d.ts +0 -1
  35. package/dist/src/domain/multichain/types.d.ts.map +1 -1
  36. package/dist/src/domain/platform/index.d.ts.map +1 -1
  37. package/dist/src/domain/platform/index.js +27 -5
  38. package/dist/src/domain/platform/index.js.map +1 -1
  39. package/dist/src/domain/store/client.d.ts +3 -3
  40. package/dist/src/domain/store/client.d.ts.map +1 -1
  41. package/dist/src/domain/utils/index.d.ts +1 -0
  42. package/dist/src/domain/utils/index.d.ts.map +1 -1
  43. package/dist/src/domain/utils/index.js +5 -1
  44. package/dist/src/domain/utils/index.js.map +1 -1
  45. package/dist/src/multichain/index.d.ts +2 -3
  46. package/dist/src/multichain/index.d.ts.map +1 -1
  47. package/dist/src/multichain/index.js +142 -147
  48. package/dist/src/multichain/index.js.map +1 -1
  49. package/dist/src/multichain/rpc/requestRouter.d.ts +15 -0
  50. package/dist/src/multichain/rpc/requestRouter.d.ts.map +1 -1
  51. package/dist/src/multichain/rpc/requestRouter.js +31 -5
  52. package/dist/src/multichain/rpc/requestRouter.js.map +1 -1
  53. package/dist/src/multichain/transports/default/index.d.ts.map +1 -1
  54. package/dist/src/multichain/transports/default/index.js +16 -10
  55. package/dist/src/multichain/transports/default/index.js.map +1 -1
  56. package/dist/src/multichain/transports/multichainApiClientWrapper/index.d.ts +2 -1
  57. package/dist/src/multichain/transports/multichainApiClientWrapper/index.d.ts.map +1 -1
  58. package/dist/src/multichain/transports/multichainApiClientWrapper/index.js +25 -17
  59. package/dist/src/multichain/transports/multichainApiClientWrapper/index.js.map +1 -1
  60. package/dist/src/multichain/transports/mwp/index.d.ts +3 -1
  61. package/dist/src/multichain/transports/mwp/index.d.ts.map +1 -1
  62. package/dist/src/multichain/transports/mwp/index.js +227 -170
  63. package/dist/src/multichain/transports/mwp/index.js.map +1 -1
  64. package/dist/src/store/index.d.ts +3 -3
  65. package/dist/src/store/index.d.ts.map +1 -1
  66. package/dist/src/store/index.js +8 -8
  67. package/dist/src/store/index.js.map +1 -1
  68. package/dist/src/ui/ModalFactory.d.ts.map +1 -1
  69. package/dist/src/ui/ModalFactory.js +5 -1
  70. package/dist/src/ui/ModalFactory.js.map +1 -1
  71. package/dist/src/ui/index.js +1 -1
  72. package/dist/src/ui/index.js.map +1 -1
  73. package/dist/src/ui/modals/web/install.d.ts.map +1 -1
  74. package/dist/src/ui/modals/web/install.js.map +1 -1
  75. package/dist/types/connect-multichain.d.ts +7 -6
  76. package/package.json +2 -2
@@ -273,7 +273,7 @@ var init_logger = __esm({
273
273
  });
274
274
 
275
275
  // src/domain/multichain/api/constants.ts
276
- var infuraRpcUrls, RPC_HANDLED_METHODS, SDK_HANDLED_METHODS;
276
+ var infuraRpcUrls, RPC_HANDLED_METHODS, SDK_HANDLED_METHODS, EIP1193_PASSTHROUGH_METHODS;
277
277
  var init_constants = __esm({
278
278
  "src/domain/multichain/api/constants.ts"() {
279
279
  "use strict";
@@ -438,6 +438,11 @@ var init_constants = __esm({
438
438
  "eth_uninstallFilter"
439
439
  ]);
440
440
  SDK_HANDLED_METHODS = /* @__PURE__ */ new Set(["eth_accounts", "eth_chainId"]);
441
+ EIP1193_PASSTHROUGH_METHODS = /* @__PURE__ */ new Set([
442
+ "wallet_addEthereumChain",
443
+ "wallet_switchEthereumChain",
444
+ "eth_accounts"
445
+ ]);
441
446
  }
442
447
  });
443
448
 
@@ -587,7 +592,7 @@ function hasExtension() {
587
592
  return detectionPromise;
588
593
  });
589
594
  }
590
- var import_bowser, PlatformType, detectionPromise;
595
+ var import_bowser, PlatformType, NATIVE_METAMASK_EIP6963_RDNS, detectionPromise;
591
596
  var init_platform = __esm({
592
597
  "src/domain/platform/index.ts"() {
593
598
  "use strict";
@@ -600,6 +605,10 @@ var init_platform = __esm({
600
605
  PlatformType2["ReactNative"] = "react-native";
601
606
  return PlatformType2;
602
607
  })(PlatformType || {});
608
+ NATIVE_METAMASK_EIP6963_RDNS = /* @__PURE__ */ new Set([
609
+ "io.metamask",
610
+ "io.metamask.mobile"
611
+ ]);
603
612
  detectionPromise = (() => __async(null, null, function* () {
604
613
  const pt = getPlatformType();
605
614
  if (pt === "nodejs" /* NonBrowser */ || pt === "react-native" /* ReactNative */) {
@@ -607,23 +616,30 @@ var init_platform = __esm({
607
616
  }
608
617
  return new Promise((resolve) => {
609
618
  const providers = [];
619
+ const targetWindow = window;
610
620
  const handler = (event) => {
611
621
  var _a3, _b;
612
622
  if ((_b = (_a3 = event == null ? void 0 : event.detail) == null ? void 0 : _a3.info) == null ? void 0 : _b.rdns) {
613
623
  providers.push(event.detail);
614
624
  }
615
625
  };
616
- window.addEventListener("eip6963:announceProvider", handler);
617
- window.dispatchEvent(new Event("eip6963:requestProvider"));
626
+ targetWindow.addEventListener("eip6963:announceProvider", handler);
627
+ targetWindow.dispatchEvent(new Event("eip6963:requestProvider"));
618
628
  setTimeout(() => {
619
- window.removeEventListener("eip6963:announceProvider", handler);
620
- const hasMetaMask = providers.some(
621
- (provider) => {
622
- var _a3, _b;
623
- return (_b = (_a3 = provider == null ? void 0 : provider.info) == null ? void 0 : _a3.rdns) == null ? void 0 : _b.startsWith("io.metamask");
629
+ try {
630
+ if (typeof (targetWindow == null ? void 0 : targetWindow.removeEventListener) === "function") {
631
+ targetWindow.removeEventListener("eip6963:announceProvider", handler);
624
632
  }
625
- );
626
- resolve(hasMetaMask);
633
+ const hasMetaMask = providers.some(
634
+ (provider) => {
635
+ var _a3;
636
+ return typeof ((_a3 = provider == null ? void 0 : provider.info) == null ? void 0 : _a3.rdns) === "string" && NATIVE_METAMASK_EIP6963_RDNS.has(provider.info.rdns);
637
+ }
638
+ );
639
+ resolve(hasMetaMask);
640
+ } catch (e) {
641
+ resolve(false);
642
+ }
627
643
  }, 300);
628
644
  });
629
645
  }))();
@@ -868,12 +884,14 @@ var init_analytics = __esm({
868
884
 
869
885
  // src/domain/utils/index.ts
870
886
  function getVersion() {
871
- return "0.0.0";
887
+ return packageVersion;
872
888
  }
889
+ var packageVersion;
873
890
  var init_utils = __esm({
874
891
  "src/domain/utils/index.ts"() {
875
892
  "use strict";
876
893
  init_analytics();
894
+ packageVersion = false ? "unknown" : "1.0.0";
877
895
  }
878
896
  });
879
897
 
@@ -1173,12 +1191,13 @@ var mwp_exports = {};
1173
1191
  __export(mwp_exports, {
1174
1192
  MWPTransport: () => MWPTransport
1175
1193
  });
1176
- var import_multichain_api_client2, import_rpc_errors2, DEFAULT_REQUEST_TIMEOUT2, CONNECTION_GRACE_PERIOD, DEFAULT_CONNECTION_TIMEOUT, DEFAULT_RESUME_TIMEOUT, SESSION_STORE_KEY, ACCOUNTS_STORE_KEY, CHAIN_STORE_KEY, PENDING_SESSION_REQUEST_KEY, CACHED_METHOD_LIST, CACHED_RESET_METHOD_LIST, logger, MWPTransport;
1194
+ var import_multichain_api_client2, import_rpc_errors2, import_utils6, 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;
1177
1195
  var init_mwp = __esm({
1178
1196
  "src/multichain/transports/mwp/index.ts"() {
1179
1197
  "use strict";
1180
1198
  import_multichain_api_client2 = require("@metamask/multichain-api-client");
1181
1199
  import_rpc_errors2 = require("@metamask/rpc-errors");
1200
+ import_utils6 = require("@metamask/utils");
1182
1201
  init_domain();
1183
1202
  init_utils2();
1184
1203
  init_constants2();
@@ -1209,6 +1228,7 @@ var init_mwp = __esm({
1209
1228
  this.dappClient = dappClient;
1210
1229
  this.kvstore = kvstore;
1211
1230
  this.options = options;
1231
+ __privateAdd(this, _MWPTransport_instances);
1212
1232
  this.__pendingRequests = /* @__PURE__ */ new Map();
1213
1233
  this.notificationCallbacks = /* @__PURE__ */ new Set();
1214
1234
  this.dappClient.on("message", this.handleMessage.bind(this));
@@ -1288,6 +1308,23 @@ var init_mwp = __esm({
1288
1308
  const message = errorPayload instanceof Error ? errorPayload.message : JSON.stringify(errorPayload);
1289
1309
  return import_rpc_errors2.rpcErrors.internal({ message });
1290
1310
  }
1311
+ getResponseError(messagePayload) {
1312
+ if ("error" in messagePayload && messagePayload.error) {
1313
+ return messagePayload.error;
1314
+ }
1315
+ const { result } = messagePayload;
1316
+ if (typeof result === "object" && result !== null && "error" in result && result.error && this.isErrorPayload(result.error)) {
1317
+ return result.error;
1318
+ }
1319
+ return void 0;
1320
+ }
1321
+ isErrorPayload(errorPayload) {
1322
+ if (errorPayload instanceof Error) {
1323
+ return true;
1324
+ }
1325
+ const errorData = errorPayload;
1326
+ return typeof (errorData == null ? void 0 : errorData.code) === "number" && typeof (errorData == null ? void 0 : errorData.message) === "string";
1327
+ }
1291
1328
  handleMessage(message) {
1292
1329
  if (typeof message === "object" && message !== null) {
1293
1330
  if ("data" in message) {
@@ -1296,9 +1333,10 @@ var init_mwp = __esm({
1296
1333
  const request = this.pendingRequests.get(messagePayload.id);
1297
1334
  if (request) {
1298
1335
  clearTimeout(request.timeout);
1299
- if ("error" in messagePayload && messagePayload.error) {
1336
+ const responseError = this.getResponseError(messagePayload);
1337
+ if (responseError) {
1300
1338
  this.pendingRequests.delete(messagePayload.id);
1301
- request.reject(this.parseWalletError(messagePayload.error));
1339
+ request.reject(this.parseWalletError(responseError));
1302
1340
  return;
1303
1341
  }
1304
1342
  const requestWithName = __spreadProps(__spreadValues({}, messagePayload), {
@@ -1341,73 +1379,6 @@ var init_mwp = __esm({
1341
1379
  }
1342
1380
  }
1343
1381
  }
1344
- onResumeSuccess(resumeResolve, resumeReject, options) {
1345
- return __async(this, null, function* () {
1346
- var _a3, _b, _c, _d, _e, _f, _g;
1347
- try {
1348
- yield this.waitForWalletSessionIfNotCached();
1349
- const sessionRequest = yield this.request({
1350
- method: "wallet_getSession"
1351
- });
1352
- if (sessionRequest.error) {
1353
- return resumeReject(new Error(sessionRequest.error.message));
1354
- }
1355
- let walletSession = sessionRequest.result;
1356
- if (walletSession && options) {
1357
- const currentScopes = Object.keys(
1358
- (_a3 = walletSession == null ? void 0 : walletSession.sessionScopes) != null ? _a3 : {}
1359
- );
1360
- const proposedScopes = (_b = options == null ? void 0 : options.scopes) != null ? _b : [];
1361
- const proposedCaipAccountIds = (_c = options == null ? void 0 : options.caipAccountIds) != null ? _c : [];
1362
- const hasSameScopesAndAccounts = isSameScopesAndAccounts(
1363
- currentScopes,
1364
- proposedScopes,
1365
- walletSession,
1366
- proposedCaipAccountIds
1367
- );
1368
- if (options.forceRequest || !hasSameScopesAndAccounts) {
1369
- const optionalScopes = addValidAccounts(
1370
- getOptionalScopes((_d = options == null ? void 0 : options.scopes) != null ? _d : []),
1371
- getValidAccounts((_e = options == null ? void 0 : options.caipAccountIds) != null ? _e : [])
1372
- );
1373
- const sessionRequest2 = {
1374
- optionalScopes
1375
- };
1376
- const response = yield this.request({
1377
- method: "wallet_createSession",
1378
- params: sessionRequest2
1379
- });
1380
- if (response.error) {
1381
- return resumeReject(new Error(response.error.message));
1382
- }
1383
- walletSession = response.result;
1384
- }
1385
- } else if (!walletSession) {
1386
- const optionalScopes = addValidAccounts(
1387
- getOptionalScopes((_f = options == null ? void 0 : options.scopes) != null ? _f : []),
1388
- getValidAccounts((_g = options == null ? void 0 : options.caipAccountIds) != null ? _g : [])
1389
- );
1390
- const sessionRequest2 = { optionalScopes };
1391
- const response = yield this.request({
1392
- method: "wallet_createSession",
1393
- params: sessionRequest2
1394
- });
1395
- if (response.error) {
1396
- return resumeReject(new Error(response.error.message));
1397
- }
1398
- walletSession = response.result;
1399
- }
1400
- yield this.removeStoredPendingSessionRequest();
1401
- this.notifyCallbacks({
1402
- method: "wallet_sessionChanged",
1403
- params: walletSession
1404
- });
1405
- return resumeResolve();
1406
- } catch (err) {
1407
- return resumeReject(err);
1408
- }
1409
- });
1410
- }
1411
1382
  init() {
1412
1383
  return __async(this, null, function* () {
1413
1384
  });
@@ -1448,7 +1419,6 @@ var init_mwp = __esm({
1448
1419
  }
1449
1420
  connect(options) {
1450
1421
  return __async(this, null, function* () {
1451
- const { dappClient } = this;
1452
1422
  const session = yield this.getActiveSession();
1453
1423
  if (session) {
1454
1424
  logger("active session found", {
@@ -1457,116 +1427,11 @@ var init_mwp = __esm({
1457
1427
  expiresAt: session.expiresAt
1458
1428
  });
1459
1429
  }
1460
- const storedSessionRequestBeforeConnectionAttempt = yield this.getStoredPendingSessionRequest();
1461
- let timeout;
1462
- let initialConnectionMessageHandler;
1463
- const connectionPromise = new Promise((resolve, reject) => __async(this, null, function* () {
1464
- let connection;
1465
- if (session) {
1466
- connection = new Promise((resumeResolve, resumeReject) => {
1467
- var _a3;
1468
- if (this.dappClient.state === "CONNECTED") {
1469
- this.onResumeSuccess(resumeResolve, resumeReject, options);
1470
- } else {
1471
- this.dappClient.once("connected", () => __async(this, null, function* () {
1472
- this.onResumeSuccess(resumeResolve, resumeReject, options);
1473
- }));
1474
- dappClient.resume((_a3 = session == null ? void 0 : session.id) != null ? _a3 : "");
1475
- }
1476
- });
1477
- } else {
1478
- connection = new Promise(
1479
- (resolveConnection, rejectConnection) => {
1480
- var _a3, _b;
1481
- const optionalScopes = addValidAccounts(
1482
- getOptionalScopes((_a3 = options == null ? void 0 : options.scopes) != null ? _a3 : []),
1483
- getValidAccounts((_b = options == null ? void 0 : options.caipAccountIds) != null ? _b : [])
1484
- );
1485
- const sessionRequest = {
1486
- optionalScopes,
1487
- sessionProperties: options == null ? void 0 : options.sessionProperties
1488
- };
1489
- const request = {
1490
- jsonrpc: "2.0",
1491
- id: String(getUniqueRequestId()),
1492
- method: "wallet_createSession",
1493
- params: sessionRequest
1494
- };
1495
- initialConnectionMessageHandler = (message) => __async(this, null, function* () {
1496
- if (typeof message !== "object" || message === null) {
1497
- return;
1498
- }
1499
- if (!("data" in message)) {
1500
- return;
1501
- }
1502
- const messagePayload = message.data;
1503
- const isMatchingId = messagePayload.id === request.id;
1504
- const isMatchingMethod = messagePayload.method === "wallet_createSession" || messagePayload.method === "wallet_sessionChanged";
1505
- if (!isMatchingId && !isMatchingMethod) {
1506
- return;
1507
- }
1508
- if (messagePayload.error) {
1509
- return rejectConnection(
1510
- this.parseWalletError(messagePayload.error)
1511
- );
1512
- }
1513
- yield this.storeWalletSession(
1514
- request,
1515
- messagePayload
1516
- );
1517
- yield this.removeStoredPendingSessionRequest();
1518
- this.notifyCallbacks(messagePayload);
1519
- return resolveConnection();
1520
- });
1521
- this.dappClient.on("message", initialConnectionMessageHandler);
1522
- const platformType = getPlatformType();
1523
- const isQRCodeFlow = [
1524
- "web-desktop" /* DesktopWeb */,
1525
- "nodejs" /* NonBrowser */
1526
- ].includes(platformType);
1527
- const initialPayload = {
1528
- name: MULTICHAIN_PROVIDER_STREAM_NAME,
1529
- data: request
1530
- };
1531
- dappClient.connect({
1532
- mode: "trusted",
1533
- initialPayload: isQRCodeFlow ? void 0 : initialPayload
1534
- }).then(() => __async(this, null, function* () {
1535
- if (isQRCodeFlow) {
1536
- return dappClient.sendRequest(initialPayload);
1537
- }
1538
- return void 0;
1539
- })).catch((error) => {
1540
- if (initialConnectionMessageHandler) {
1541
- this.dappClient.off(
1542
- "message",
1543
- initialConnectionMessageHandler
1544
- );
1545
- }
1546
- rejectConnection(error);
1547
- });
1548
- }
1549
- );
1550
- }
1551
- timeout = setTimeout(
1552
- () => {
1553
- reject(new import_multichain_api_client2.TransportTimeoutError());
1554
- },
1555
- storedSessionRequestBeforeConnectionAttempt ? this.options.resumeTimeout : this.options.connectionTimeout
1556
- );
1557
- connection.then(resolve).catch(reject);
1558
- }));
1559
- return connectionPromise.catch((error) => __async(this, null, function* () {
1430
+ const connection = session ? __privateMethod(this, _MWPTransport_instances, resumeSession_fn).call(this, session, options) : __privateMethod(this, _MWPTransport_instances, startSession_fn).call(this, options);
1431
+ return connection.catch((error) => __async(this, null, function* () {
1560
1432
  yield this.dappClient.disconnect();
1561
1433
  throw error;
1562
1434
  })).finally(() => {
1563
- if (timeout) {
1564
- clearTimeout(timeout);
1565
- }
1566
- if (initialConnectionMessageHandler) {
1567
- this.dappClient.off("message", initialConnectionMessageHandler);
1568
- initialConnectionMessageHandler = void 0;
1569
- }
1570
1435
  this.removeStoredPendingSessionRequest();
1571
1436
  });
1572
1437
  });
@@ -1825,6 +1690,188 @@ var init_mwp = __esm({
1825
1690
  });
1826
1691
  }
1827
1692
  };
1693
+ _MWPTransport_instances = new WeakSet();
1694
+ onResumeHandler_fn = function(options) {
1695
+ return __async(this, null, function* () {
1696
+ var _a3, _b, _c, _d, _e, _f, _g;
1697
+ yield this.waitForWalletSessionIfNotCached();
1698
+ const sessionResponse = yield this.request({ method: "wallet_getSession" });
1699
+ if (sessionResponse.error) {
1700
+ throw new Error(sessionResponse.error.message);
1701
+ }
1702
+ let walletSession = sessionResponse.result;
1703
+ if (walletSession && options) {
1704
+ const currentScopes = Object.keys(
1705
+ (_a3 = walletSession == null ? void 0 : walletSession.sessionScopes) != null ? _a3 : {}
1706
+ );
1707
+ const proposedScopes = (_b = options == null ? void 0 : options.scopes) != null ? _b : [];
1708
+ const proposedCaipAccountIds = (_c = options == null ? void 0 : options.caipAccountIds) != null ? _c : [];
1709
+ const hasSameScopesAndAccounts = isSameScopesAndAccounts(
1710
+ currentScopes,
1711
+ proposedScopes,
1712
+ walletSession,
1713
+ proposedCaipAccountIds
1714
+ );
1715
+ if (options.forceRequest || !hasSameScopesAndAccounts) {
1716
+ const optionalScopes = addValidAccounts(
1717
+ getOptionalScopes((_d = options == null ? void 0 : options.scopes) != null ? _d : []),
1718
+ getValidAccounts((_e = options == null ? void 0 : options.caipAccountIds) != null ? _e : [])
1719
+ );
1720
+ const sessionRequest = {
1721
+ optionalScopes
1722
+ };
1723
+ const response = yield this.request({
1724
+ method: "wallet_createSession",
1725
+ params: sessionRequest
1726
+ });
1727
+ if (response.error) {
1728
+ throw new Error(response.error.message);
1729
+ }
1730
+ walletSession = response.result;
1731
+ }
1732
+ } else if (!walletSession) {
1733
+ const optionalScopes = addValidAccounts(
1734
+ getOptionalScopes((_f = options == null ? void 0 : options.scopes) != null ? _f : []),
1735
+ getValidAccounts((_g = options == null ? void 0 : options.caipAccountIds) != null ? _g : [])
1736
+ );
1737
+ const sessionRequest = {
1738
+ optionalScopes
1739
+ };
1740
+ const response = yield this.request({
1741
+ method: "wallet_createSession",
1742
+ params: sessionRequest
1743
+ });
1744
+ if (response.error) {
1745
+ throw new Error(response.error.message);
1746
+ }
1747
+ walletSession = response.result;
1748
+ }
1749
+ yield this.removeStoredPendingSessionRequest();
1750
+ this.notifyCallbacks({
1751
+ method: "wallet_sessionChanged",
1752
+ params: walletSession
1753
+ });
1754
+ });
1755
+ };
1756
+ resumeSession_fn = function(session, options) {
1757
+ return __async(this, null, function* () {
1758
+ var _a3;
1759
+ const isContinuingPriorAttempt = (yield this.getStoredPendingSessionRequest()) !== null;
1760
+ const resumeDeferred = (0, import_utils6.createDeferredPromise)();
1761
+ const runOnResumeHandler = () => __async(this, null, function* () {
1762
+ try {
1763
+ resumeDeferred.resolve(yield __privateMethod(this, _MWPTransport_instances, onResumeHandler_fn).call(this, options));
1764
+ } catch (err) {
1765
+ resumeDeferred.reject(err);
1766
+ }
1767
+ });
1768
+ if (this.dappClient.state === "CONNECTED") {
1769
+ runOnResumeHandler();
1770
+ } else {
1771
+ this.dappClient.once("connected", runOnResumeHandler);
1772
+ this.dappClient.resume((_a3 = session.id) != null ? _a3 : "").catch((err) => resumeDeferred.reject(err));
1773
+ }
1774
+ const timeoutDeferred = (0, import_utils6.createDeferredPromise)();
1775
+ const timeout = setTimeout(
1776
+ () => timeoutDeferred.reject(new import_multichain_api_client2.TransportTimeoutError()),
1777
+ isContinuingPriorAttempt ? this.options.resumeTimeout : this.options.connectionTimeout
1778
+ );
1779
+ const cleanup = () => this.dappClient.off("connected", runOnResumeHandler);
1780
+ return Promise.race([
1781
+ resumeDeferred.promise,
1782
+ timeoutDeferred.promise
1783
+ ]).finally(() => {
1784
+ clearTimeout(timeout);
1785
+ cleanup();
1786
+ });
1787
+ });
1788
+ };
1789
+ startSession_fn = function(options) {
1790
+ return __async(this, null, function* () {
1791
+ var _a3, _b;
1792
+ const { dappClient } = this;
1793
+ const isContinuingPriorAttempt = (yield this.getStoredPendingSessionRequest()) !== null;
1794
+ const connDeferred = (0, import_utils6.createDeferredPromise)();
1795
+ const optionalScopes = addValidAccounts(
1796
+ getOptionalScopes((_a3 = options == null ? void 0 : options.scopes) != null ? _a3 : []),
1797
+ getValidAccounts((_b = options == null ? void 0 : options.caipAccountIds) != null ? _b : [])
1798
+ );
1799
+ const sessionRequest = {
1800
+ optionalScopes,
1801
+ sessionProperties: options == null ? void 0 : options.sessionProperties
1802
+ };
1803
+ const request = {
1804
+ jsonrpc: "2.0",
1805
+ id: String(getUniqueRequestId()),
1806
+ method: "wallet_createSession",
1807
+ params: sessionRequest
1808
+ };
1809
+ let handler;
1810
+ const removeHandler = () => {
1811
+ if (handler) {
1812
+ this.dappClient.off("message", handler);
1813
+ handler = void 0;
1814
+ }
1815
+ };
1816
+ handler = (message) => __async(this, null, function* () {
1817
+ if (typeof message !== "object" || message === null) {
1818
+ return;
1819
+ }
1820
+ if (!("data" in message)) {
1821
+ return;
1822
+ }
1823
+ const messagePayload = message.data;
1824
+ const isMatchingId = messagePayload.id === request.id;
1825
+ const isMatchingMethod = messagePayload.method === "wallet_createSession" || messagePayload.method === "wallet_sessionChanged";
1826
+ if (!isMatchingId && !isMatchingMethod) {
1827
+ return;
1828
+ }
1829
+ const responseError = this.getResponseError(messagePayload);
1830
+ if (responseError) {
1831
+ connDeferred.reject(this.parseWalletError(responseError));
1832
+ return;
1833
+ }
1834
+ yield this.storeWalletSession(
1835
+ request,
1836
+ messagePayload
1837
+ );
1838
+ yield this.removeStoredPendingSessionRequest();
1839
+ this.notifyCallbacks(messagePayload);
1840
+ connDeferred.resolve();
1841
+ });
1842
+ this.dappClient.on("message", handler);
1843
+ const platformType = getPlatformType();
1844
+ const isQRCodeFlow = [
1845
+ "web-desktop" /* DesktopWeb */,
1846
+ "nodejs" /* NonBrowser */
1847
+ ].includes(platformType);
1848
+ const initialPayload = {
1849
+ name: MULTICHAIN_PROVIDER_STREAM_NAME,
1850
+ data: request
1851
+ };
1852
+ dappClient.connect({
1853
+ mode: "trusted",
1854
+ initialPayload: isQRCodeFlow ? void 0 : initialPayload
1855
+ }).then(() => __async(this, null, function* () {
1856
+ if (isQRCodeFlow) {
1857
+ return dappClient.sendRequest(initialPayload);
1858
+ }
1859
+ return void 0;
1860
+ })).catch((error) => connDeferred.reject(error));
1861
+ const timeoutDeferred = (0, import_utils6.createDeferredPromise)();
1862
+ const timeout = setTimeout(
1863
+ () => timeoutDeferred.reject(new import_multichain_api_client2.TransportTimeoutError()),
1864
+ isContinuingPriorAttempt ? this.options.resumeTimeout : this.options.connectionTimeout
1865
+ );
1866
+ return Promise.race([
1867
+ connDeferred.promise,
1868
+ timeoutDeferred.promise
1869
+ ]).finally(() => {
1870
+ clearTimeout(timeout);
1871
+ removeHandler();
1872
+ });
1873
+ });
1874
+ };
1828
1875
  }
1829
1876
  });
1830
1877
 
@@ -1997,9 +2044,7 @@ var init_install = __esm({
1997
2044
  mount() {
1998
2045
  var _a3;
1999
2046
  const { options } = this;
2000
- const modal = document.createElement(
2001
- "mm-install-modal"
2002
- );
2047
+ const modal = document.createElement("mm-install-modal");
2003
2048
  modal.showInstallModal = options.showInstallModal;
2004
2049
  modal.addEventListener("close", (ev) => {
2005
2050
  const { detail } = ev;
@@ -2183,6 +2228,7 @@ var init_web2 = __esm({
2183
2228
  // src/index.browser.ts
2184
2229
  var index_browser_exports = {};
2185
2230
  __export(index_browser_exports, {
2231
+ EIP1193_PASSTHROUGH_METHODS: () => EIP1193_PASSTHROUGH_METHODS,
2186
2232
  EventEmitter: () => EventEmitter,
2187
2233
  Modal: () => Modal,
2188
2234
  MultichainCore: () => MultichainCore,
@@ -2210,7 +2256,8 @@ __export(index_browser_exports, {
2210
2256
  isEnabled: () => isEnabled,
2211
2257
  isMetamaskExtensionInstalled: () => isMetamaskExtensionInstalled,
2212
2258
  isRejectionError: () => isRejectionError,
2213
- isSecure: () => isSecure
2259
+ isSecure: () => isSecure,
2260
+ packageVersion: () => packageVersion
2214
2261
  });
2215
2262
  module.exports = __toCommonJS(index_browser_exports);
2216
2263
 
@@ -2227,6 +2274,7 @@ init_domain();
2227
2274
  // src/multichain/index.ts
2228
2275
  var import_analytics4 = require("@metamask/analytics");
2229
2276
  var import_multichain_api_client3 = require("@metamask/multichain-api-client");
2277
+ var import_utils8 = require("@metamask/utils");
2230
2278
 
2231
2279
  // src/config/index.ts
2232
2280
  var MWP_RELAY_URL = "wss://mm-sdk-relay.api.cx.metamask.io/connection/websocket";
@@ -2380,6 +2428,9 @@ var RequestRouter = class {
2380
2428
  invokeMethod(options) {
2381
2429
  return __async(this, null, function* () {
2382
2430
  const { method } = options.request;
2431
+ if (EIP1193_PASSTHROUGH_METHODS.has(method)) {
2432
+ return this.handleWithEip1193Passthrough(options);
2433
+ }
2383
2434
  if (RPC_HANDLED_METHODS.has(method)) {
2384
2435
  return this.handleWithRpcNode(options);
2385
2436
  }
@@ -2389,6 +2440,29 @@ var RequestRouter = class {
2389
2440
  return this.handleWithWallet(options);
2390
2441
  });
2391
2442
  }
2443
+ /**
2444
+ * Forwards EIP-1193 / legacy provider methods (e.g. `wallet_addEthereumChain`,
2445
+ * `wallet_switchEthereumChain`, `eth_accounts`) directly to the underlying
2446
+ * transport's `sendEip1193Message`, bypassing the multichain
2447
+ * `wallet_invokeMethod` envelope. These methods are wallet-side concerns the
2448
+ * Multichain API does not model, so we forward the raw `{ method, params }`
2449
+ * payload and return the wallet's full JSON-RPC response envelope unchanged.
2450
+ *
2451
+ * Analytics tracking is intentionally skipped here: ecosystem clients
2452
+ * (e.g. `connect-evm`) emit their own `wallet_action_*` events around these
2453
+ * passthrough calls, and adding router-level tracking would double-count.
2454
+ *
2455
+ * @param options
2456
+ */
2457
+ handleWithEip1193Passthrough(options) {
2458
+ return __async(this, null, function* () {
2459
+ const response = yield this.transport.sendEip1193Message({
2460
+ method: options.request.method,
2461
+ params: options.request.params
2462
+ });
2463
+ return response.result;
2464
+ });
2465
+ }
2392
2466
  /**
2393
2467
  * Forwards the request directly to the wallet via the transport.
2394
2468
  *
@@ -2420,14 +2494,6 @@ var RequestRouter = class {
2420
2494
  }), 10);
2421
2495
  }
2422
2496
  const response = yield request;
2423
- if (response.error) {
2424
- const { error } = response;
2425
- throw new RPCInvokeMethodErr(
2426
- `RPC Request failed with code ${error.code}: ${error.message}`,
2427
- error.code,
2428
- error.message
2429
- );
2430
- }
2431
2497
  return response.result;
2432
2498
  }));
2433
2499
  });
@@ -2540,7 +2606,7 @@ trackWalletActionRejected_fn = function(options) {
2540
2606
  var import_multichain_api_client = require("@metamask/multichain-api-client");
2541
2607
  init_utils2();
2542
2608
  var DEFAULT_REQUEST_TIMEOUT = 60 * 1e3;
2543
- var _notificationCallbacks, _transport, _defaultRequestOptions, _pendingRequests, _handleResponseListener, _handleNotificationListener, _DefaultTransport_instances, notifyCallbacks_fn, isMetamaskProviderEvent_fn, handleResponse_fn, handleNotification_fn, setupMessageListener_fn, init_fn;
2609
+ var _notificationCallbacks, _transport, _defaultRequestOptions, _pendingRequests, _handleResponseListener, _handleNotificationListener, _DefaultTransport_instances, notifyCallbacks_fn, parseWalletError_fn, isMetamaskProviderEvent_fn, handleResponse_fn, handleNotification_fn, setupMessageListener_fn, init_fn;
2544
2610
  var DefaultTransport = class {
2545
2611
  constructor() {
2546
2612
  __privateAdd(this, _DefaultTransport_instances);
@@ -2676,7 +2742,11 @@ var DefaultTransport = class {
2676
2742
  }
2677
2743
  request(_0) {
2678
2744
  return __async(this, arguments, function* (request, options = __privateGet(this, _defaultRequestOptions)) {
2679
- return __privateGet(this, _transport).request(request, options);
2745
+ const response = yield __privateGet(this, _transport).request(request, options);
2746
+ if (response.error) {
2747
+ throw __privateMethod(this, _DefaultTransport_instances, parseWalletError_fn).call(this, response.error);
2748
+ }
2749
+ return response;
2680
2750
  });
2681
2751
  }
2682
2752
  onNotification(callback) {
@@ -2720,6 +2790,16 @@ notifyCallbacks_fn = function(data) {
2720
2790
  }
2721
2791
  }
2722
2792
  };
2793
+ parseWalletError_fn = function(errorPayload) {
2794
+ const errorData = errorPayload;
2795
+ const error = new Error(
2796
+ typeof errorData.message === "string" ? errorData.message : "Request failed"
2797
+ );
2798
+ if (typeof errorData.code === "number") {
2799
+ error.code = errorData.code;
2800
+ }
2801
+ return error;
2802
+ };
2723
2803
  isMetamaskProviderEvent_fn = function(event) {
2724
2804
  var _a3, _b;
2725
2805
  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
@@ -2742,13 +2822,7 @@ handleResponse_fn = function(event) {
2742
2822
  __privateGet(this, _pendingRequests).delete(responseId);
2743
2823
  const response = responseData;
2744
2824
  if ("error" in response && response.error) {
2745
- const error = new Error(
2746
- response.error.message || "Request failed"
2747
- );
2748
- if (typeof response.error.code === "number") {
2749
- error.code = response.error.code;
2750
- }
2751
- pendingRequest.reject(error);
2825
+ pendingRequest.reject(__privateMethod(this, _DefaultTransport_instances, parseWalletError_fn).call(this, response.error));
2752
2826
  } else {
2753
2827
  pendingRequest.resolve(response);
2754
2828
  }
@@ -2786,22 +2860,21 @@ init_fn = function() {
2786
2860
  // src/multichain/transports/multichainApiClientWrapper/index.ts
2787
2861
  var import_rpc_errors = require("@metamask/rpc-errors");
2788
2862
  init_utils2();
2789
- var _notificationCallbacks2, _MultichainApiClientWrapperTransport_instances, walletCreateSession_fn, walletGetSession_fn, walletRevokeSession_fn, walletInvokeMethod_fn;
2863
+ var _notificationCallbacks2, _getTransport, _MultichainApiClientWrapperTransport_instances, walletCreateSession_fn, walletGetSession_fn, walletRevokeSession_fn, walletInvokeMethod_fn;
2790
2864
  var MultichainApiClientWrapperTransport = class {
2791
- constructor(metamaskConnectMultichain) {
2865
+ constructor(metamaskConnectMultichain, getTransport) {
2792
2866
  this.metamaskConnectMultichain = metamaskConnectMultichain;
2793
2867
  __privateAdd(this, _MultichainApiClientWrapperTransport_instances);
2794
2868
  __privateAdd(this, _notificationCallbacks2, /* @__PURE__ */ new Set());
2869
+ __privateAdd(this, _getTransport);
2870
+ __privateSet(this, _getTransport, getTransport);
2795
2871
  }
2796
2872
  isTransportDefined() {
2797
- try {
2798
- return Boolean(this.metamaskConnectMultichain.transport);
2799
- } catch (_error) {
2800
- return false;
2801
- }
2873
+ return __privateGet(this, _getTransport).call(this) !== void 0;
2802
2874
  }
2803
2875
  isTransportConnected() {
2804
- return this.isTransportDefined() && this.metamaskConnectMultichain.transport.isConnected();
2876
+ var _a3, _b;
2877
+ return (_b = (_a3 = __privateGet(this, _getTransport).call(this)) == null ? void 0 : _a3.isConnected()) != null ? _b : false;
2805
2878
  }
2806
2879
  clearNotificationCallbacks() {
2807
2880
  __privateGet(this, _notificationCallbacks2).clear();
@@ -2817,10 +2890,11 @@ var MultichainApiClientWrapperTransport = class {
2817
2890
  this.notificationListener = void 0;
2818
2891
  }
2819
2892
  setupTransportNotificationListener() {
2820
- if (!this.isTransportDefined() || this.notificationListener) {
2893
+ const transport = __privateGet(this, _getTransport).call(this);
2894
+ if (!transport || this.notificationListener) {
2821
2895
  return;
2822
2896
  }
2823
- this.notificationListener = this.metamaskConnectMultichain.transport.onNotification(
2897
+ this.notificationListener = transport.onNotification(
2824
2898
  this.notifyCallbacks.bind(this)
2825
2899
  );
2826
2900
  }
@@ -2870,6 +2944,7 @@ var MultichainApiClientWrapperTransport = class {
2870
2944
  }
2871
2945
  };
2872
2946
  _notificationCallbacks2 = new WeakMap();
2947
+ _getTransport = new WeakMap();
2873
2948
  _MultichainApiClientWrapperTransport_instances = new WeakSet();
2874
2949
  walletCreateSession_fn = function(request) {
2875
2950
  return __async(this, null, function* () {
@@ -2893,14 +2968,19 @@ walletCreateSession_fn = function(request) {
2893
2968
  accounts,
2894
2969
  createSessionParams.sessionProperties
2895
2970
  );
2896
- return this.metamaskConnectMultichain.transport.request({
2971
+ const transport = __privateGet(this, _getTransport).call(this);
2972
+ if (!transport) {
2973
+ throw new Error("Transport not initialized after connect");
2974
+ }
2975
+ return transport.request({
2897
2976
  method: "wallet_getSession"
2898
2977
  });
2899
2978
  });
2900
2979
  };
2901
2980
  walletGetSession_fn = function(request) {
2902
2981
  return __async(this, null, function* () {
2903
- if (!this.isTransportConnected()) {
2982
+ const transport = __privateGet(this, _getTransport).call(this);
2983
+ if (!(transport == null ? void 0 : transport.isConnected())) {
2904
2984
  return {
2905
2985
  jsonrpc: "2.0",
2906
2986
  id: request.id,
@@ -2909,7 +2989,7 @@ walletGetSession_fn = function(request) {
2909
2989
  }
2910
2990
  };
2911
2991
  }
2912
- return this.metamaskConnectMultichain.transport.request({
2992
+ return transport.request({
2913
2993
  method: "wallet_getSession"
2914
2994
  });
2915
2995
  });
@@ -2987,7 +3067,7 @@ function setupAnalyticsGlobals(options, storage, setAnonId) {
2987
3067
  import_analytics4.analytics.enable();
2988
3068
  });
2989
3069
  }
2990
- 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;
3070
+ 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;
2991
3071
  var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends MultichainCore {
2992
3072
  constructor(options) {
2993
3073
  var _a3, _b, _c, _d;
@@ -3000,9 +3080,7 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
3000
3080
  }),
3001
3081
  analytics: normalizeAnalyticsOptions(options.analytics),
3002
3082
  versions: __spreadValues({
3003
- // typeof guard needed: Metro (React Native) bundles TS source directly,
3004
- // bypassing the tsup build that substitutes __PACKAGE_VERSION__.
3005
- "connect-multichain": false ? "unknown" : "0.15.0"
3083
+ "connect-multichain": getVersion()
3006
3084
  }, (_d = options.versions) != null ? _d : {})
3007
3085
  });
3008
3086
  super(allOptions);
@@ -3018,7 +3096,8 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
3018
3096
  __privateAdd(this, _anonId);
3019
3097
  __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}`);
3020
3098
  __privateSet(this, _providerTransportWrapper, new MultichainApiClientWrapperTransport(
3021
- this
3099
+ this,
3100
+ () => __privateGet(this, _transport2)
3022
3101
  ));
3023
3102
  __privateSet(this, _provider, (0, import_multichain_api_client3.getMultichainClient)({
3024
3103
  transport: __privateGet(this, _providerTransportWrapper)
@@ -3037,12 +3116,6 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
3037
3116
  get provider() {
3038
3117
  return __privateGet(this, _provider);
3039
3118
  }
3040
- get transport() {
3041
- if (!__privateGet(this, _transport2)) {
3042
- throw new Error("Transport not initialized, establish connection first");
3043
- }
3044
- return __privateGet(this, _transport2);
3045
- }
3046
3119
  get dappClient() {
3047
3120
  if (!__privateGet(this, _dappClient)) {
3048
3121
  throw new Error("DappClient not initialized, establish connection first");
@@ -3056,6 +3129,9 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
3056
3129
  get storage() {
3057
3130
  return this.options.storage;
3058
3131
  }
3132
+ get version() {
3133
+ return getVersion();
3134
+ }
3059
3135
  // Creates a singleton instance of MetaMaskConnectMultichain.
3060
3136
  // If the singleton already exists, it merges the incoming options with the
3061
3137
  // existing singleton options for the following keys: `api.supportedNetworks`,
@@ -3070,6 +3146,11 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
3070
3146
  const existing = globalObject[SINGLETON_KEY];
3071
3147
  if (existing) {
3072
3148
  const instance = yield existing;
3149
+ if (instance.version !== getVersion()) {
3150
+ console.warn(
3151
+ `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.`
3152
+ );
3153
+ }
3073
3154
  instance.mergeOptions(options);
3074
3155
  if (instance instanceof _MetaMaskConnectMultichain) {
3075
3156
  yield __privateMethod(_a3 = instance, _MetaMaskConnectMultichain_instances, setupAnalytics_fn).call(_a3);
@@ -3093,12 +3174,12 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
3093
3174
  }
3094
3175
  yield __privateMethod(_a4 = instance, _MetaMaskConnectMultichain_instances, init_fn2).call(_a4);
3095
3176
  return instance;
3096
- }))();
3097
- globalObject[SINGLETON_KEY] = instancePromise;
3098
- instancePromise.catch((error) => {
3177
+ }))().catch((error) => {
3099
3178
  globalObject[SINGLETON_KEY] = void 0;
3100
3179
  console.error("Error initializing MetaMaskConnectMultichain", error);
3180
+ throw error;
3101
3181
  });
3182
+ globalObject[SINGLETON_KEY] = instancePromise;
3102
3183
  return instancePromise;
3103
3184
  });
3104
3185
  }
@@ -3158,9 +3239,9 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
3158
3239
  forceRequest
3159
3240
  }).then(() => __async(this, null, function* () {
3160
3241
  if (__privateGet(this, _transportType) === "mwp" /* MWP */) {
3161
- return this.storage.setTransport("mwp" /* MWP */);
3242
+ return this.storage.setTransportType("mwp" /* MWP */);
3162
3243
  }
3163
- return this.storage.setTransport("browser" /* Browser */);
3244
+ return this.storage.setTransportType("browser" /* Browser */);
3164
3245
  })), scopes, transportType);
3165
3246
  }
3166
3247
  if (platformType === "in-app-browser" /* MetaMaskMobileWebview */) {
@@ -3189,11 +3270,6 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
3189
3270
  return __privateMethod(this, _MetaMaskConnectMultichain_instances, handleConnection_fn).call(this, __privateMethod(this, _MetaMaskConnectMultichain_instances, showInstallModal_fn).call(this, shouldShowInstallModal, mergedScopes, mergedCaipAccountIds, nonEmptySessionProperties), scopes, transportType);
3190
3271
  });
3191
3272
  }
3192
- emit(event, args) {
3193
- var _a3, _b;
3194
- (_b = (_a3 = this.options.transport) == null ? void 0 : _a3.onNotification) == null ? void 0 : _b.call(_a3, { method: event, params: args });
3195
- super.emit(event, args);
3196
- }
3197
3273
  disconnect() {
3198
3274
  return __async(this, arguments, function* (scopes = []) {
3199
3275
  var _a3, _b, _c;
@@ -3203,7 +3279,7 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
3203
3279
  );
3204
3280
  yield (_a3 = __privateGet(this, _transport2)) == null ? void 0 : _a3.disconnect(scopes);
3205
3281
  if (remainingScopes.length === 0) {
3206
- yield this.storage.removeTransport();
3282
+ yield this.storage.removeTransportType();
3207
3283
  if (__privateGet(this, _transportType) !== "browser" /* Browser */) {
3208
3284
  yield (_b = __privateGet(this, _listener)) == null ? void 0 : _b.call(this);
3209
3285
  (_c = __privateGet(this, _beforeUnloadListener)) == null ? void 0 : _c.call(this);
@@ -3221,7 +3297,8 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
3221
3297
  invokeMethod(request) {
3222
3298
  return __async(this, null, function* () {
3223
3299
  var _a3;
3224
- const { transport, options } = this;
3300
+ const transport = __privateMethod(this, _MetaMaskConnectMultichain_instances, transportOrThrow_fn).call(this);
3301
+ const { options } = this;
3225
3302
  const rpcClient = new RpcClient(options, __privateGet(this, _sdkInfo));
3226
3303
  const requestRouter = new RequestRouter(
3227
3304
  transport,
@@ -3240,7 +3317,7 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
3240
3317
  const shouldOpenDeeplink = secure && !showInstallModal;
3241
3318
  if (shouldOpenDeeplink) {
3242
3319
  setTimeout(() => __async(this, null, function* () {
3243
- const session = yield this.transport.getActiveSession();
3320
+ const session = yield __privateMethod(this, _MetaMaskConnectMultichain_instances, transportOrThrow_fn).call(this).getActiveSession();
3244
3321
  if (!session) {
3245
3322
  throw new Error("No active session found");
3246
3323
  }
@@ -3264,10 +3341,13 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
3264
3341
  this.emit("wallet_sessionChanged", emptySession);
3265
3342
  return;
3266
3343
  }
3267
- const response = yield this.transport.request({
3344
+ const response = yield __privateGet(this, _transport2).request({
3268
3345
  method: "wallet_getSession"
3269
3346
  });
3270
- this.emit("wallet_sessionChanged", (_b = response.result) != null ? _b : emptySession);
3347
+ this.emit(
3348
+ "wallet_sessionChanged",
3349
+ (_b = response.result) != null ? _b : emptySession
3350
+ );
3271
3351
  });
3272
3352
  }
3273
3353
  };
@@ -3279,8 +3359,14 @@ _beforeUnloadListener = new WeakMap();
3279
3359
  _transportType = new WeakMap();
3280
3360
  _listener = new WeakMap();
3281
3361
  _anonId = new WeakMap();
3282
- _sdkInfo = new WeakMap();
3283
3362
  _MetaMaskConnectMultichain_instances = new WeakSet();
3363
+ transportOrThrow_fn = function() {
3364
+ if (!__privateGet(this, _transport2)) {
3365
+ throw new Error("Transport not initialized, establish connection first");
3366
+ }
3367
+ return __privateGet(this, _transport2);
3368
+ };
3369
+ _sdkInfo = new WeakMap();
3284
3370
  setupAnalytics_fn = function() {
3285
3371
  return __async(this, null, function* () {
3286
3372
  yield setupAnalyticsGlobals(this.options, this.storage, (anonId) => {
@@ -3306,7 +3392,7 @@ onTransportNotification_fn = function(payload) {
3306
3392
  };
3307
3393
  getStoredTransport_fn = function() {
3308
3394
  return __async(this, null, function* () {
3309
- const transportType = yield this.storage.getTransport();
3395
+ const transportType = yield this.storage.getTransportType();
3310
3396
  const hasExtensionInstalled = yield hasExtension();
3311
3397
  if (transportType) {
3312
3398
  if (transportType === "browser" /* Browser */) {
@@ -3334,7 +3420,7 @@ getStoredTransport_fn = function() {
3334
3420
  ));
3335
3421
  return apiTransport;
3336
3422
  }
3337
- yield this.storage.removeTransport();
3423
+ yield this.storage.removeTransportType();
3338
3424
  }
3339
3425
  return void 0;
3340
3426
  });
@@ -3344,15 +3430,15 @@ setupTransport_fn = function() {
3344
3430
  var _a3;
3345
3431
  const transport = yield __privateMethod(this, _MetaMaskConnectMultichain_instances, getStoredTransport_fn).call(this);
3346
3432
  if (transport) {
3347
- if (!this.transport.isConnected()) {
3433
+ if (!transport.isConnected()) {
3348
3434
  this.status = "connecting";
3349
- yield this.transport.connect();
3435
+ yield transport.connect();
3350
3436
  }
3351
3437
  this.status = "connected";
3352
3438
  if (__privateGet(this, _transportType) === "mwp" /* MWP */) {
3353
- yield this.storage.setTransport("mwp" /* MWP */);
3439
+ yield this.storage.setTransportType("mwp" /* MWP */);
3354
3440
  } else {
3355
- yield this.storage.setTransport("browser" /* Browser */);
3441
+ yield this.storage.setTransportType("browser" /* Browser */);
3356
3442
  }
3357
3443
  } else {
3358
3444
  this.status = "loaded";
@@ -3361,7 +3447,7 @@ setupTransport_fn = function() {
3361
3447
  if (hasExtensionInstalled && preferExtension) {
3362
3448
  yield __privateMethod(this, _MetaMaskConnectMultichain_instances, setupDefaultTransport_fn).call(this, { persist: false });
3363
3449
  try {
3364
- yield this.transport.init();
3450
+ yield __privateMethod(this, _MetaMaskConnectMultichain_instances, transportOrThrow_fn).call(this).init();
3365
3451
  } catch (error) {
3366
3452
  console.error("Passive init failed:", error);
3367
3453
  }
@@ -3385,7 +3471,7 @@ init_fn2 = function() {
3385
3471
  yield __privateMethod(this, _MetaMaskConnectMultichain_instances, setupAnalytics_fn).call(this);
3386
3472
  yield __privateMethod(this, _MetaMaskConnectMultichain_instances, setupTransport_fn).call(this);
3387
3473
  } catch (error) {
3388
- yield this.storage.removeTransport();
3474
+ yield this.storage.removeTransportType();
3389
3475
  this.status = "pending";
3390
3476
  logger2("MetaMaskSDK error during initialization", error);
3391
3477
  }
@@ -3431,17 +3517,17 @@ setupMWP_fn = function() {
3431
3517
  __privateSet(this, _transport2, apiTransport);
3432
3518
  __privateSet(this, _transportType, "mwp" /* MWP */);
3433
3519
  __privateGet(this, _providerTransportWrapper).setupTransportNotificationListener();
3434
- __privateSet(this, _listener, this.transport.onNotification(
3520
+ __privateSet(this, _listener, apiTransport.onNotification(
3435
3521
  __privateMethod(this, _MetaMaskConnectMultichain_instances, onTransportNotification_fn).bind(this)
3436
3522
  ));
3437
- yield this.storage.setTransport("mwp" /* MWP */);
3523
+ yield this.storage.setTransportType("mwp" /* MWP */);
3438
3524
  });
3439
3525
  };
3440
3526
  onBeforeUnload_fn = function() {
3441
3527
  return __async(this, null, function* () {
3442
3528
  var _a3;
3443
3529
  if ((_a3 = this.options.ui.factory.modal) == null ? void 0 : _a3.isMounted) {
3444
- yield this.storage.removeTransport();
3530
+ yield this.storage.removeTransportType();
3445
3531
  }
3446
3532
  });
3447
3533
  };
@@ -3458,70 +3544,65 @@ createBeforeUnloadListener_fn = function() {
3458
3544
  };
3459
3545
  renderInstallModalAsync_fn = function(desktopPreferred, scopes, caipAccountIds, sessionProperties) {
3460
3546
  return __async(this, null, function* () {
3461
- return new Promise((resolve, reject) => {
3462
- this.options.ui.factory.renderInstallModal(
3463
- desktopPreferred,
3464
- () => __async(this, null, function* () {
3465
- if (this.dappClient.state === "CONNECTED" || this.dappClient.state === "CONNECTING") {
3466
- yield this.dappClient.disconnect();
3467
- }
3468
- return new Promise((_resolve) => {
3469
- this.dappClient.on(
3470
- "session_request",
3471
- (sessionRequest) => {
3472
- _resolve({
3473
- sessionRequest,
3474
- metadata: __privateMethod(this, _MetaMaskConnectMultichain_instances, buildConnectionMetadata_fn).call(this)
3475
- });
3476
- }
3477
- );
3478
- (() => __async(this, null, function* () {
3479
- var _a3;
3480
- try {
3481
- yield this.transport.connect({
3482
- scopes,
3483
- caipAccountIds,
3484
- sessionProperties
3485
- });
3486
- yield this.options.ui.factory.unload();
3487
- (_a3 = this.options.ui.factory.modal) == null ? void 0 : _a3.unmount();
3488
- this.status = "connected";
3489
- yield this.storage.setTransport("mwp" /* MWP */);
3490
- } catch (error) {
3491
- const { ProtocolError, ErrorCode } = yield import("@metamask/mobile-wallet-protocol-core");
3492
- if (error instanceof ProtocolError) {
3493
- if (error.code !== ErrorCode.REQUEST_EXPIRED) {
3494
- this.status = "disconnected";
3495
- yield this.options.ui.factory.unload(error);
3496
- reject(error);
3497
- }
3498
- } else {
3499
- this.status = "disconnected";
3500
- const normalizedError = error instanceof Error ? error : new Error(String(error));
3501
- yield this.options.ui.factory.unload(normalizedError);
3502
- reject(normalizedError);
3503
- }
3504
- }
3505
- }))().catch(() => {
3506
- });
3547
+ const completion = (0, import_utils8.createDeferredPromise)();
3548
+ const createConnectionRequest = () => __async(this, null, function* () {
3549
+ if (this.dappClient.state === "CONNECTED" || this.dappClient.state === "CONNECTING") {
3550
+ yield this.dappClient.disconnect();
3551
+ }
3552
+ const sessionRequestDeferred = (0, import_utils8.createDeferredPromise)();
3553
+ this.dappClient.on(
3554
+ "session_request",
3555
+ (sessionRequest) => {
3556
+ sessionRequestDeferred.resolve({
3557
+ sessionRequest,
3558
+ metadata: __privateMethod(this, _MetaMaskConnectMultichain_instances, buildConnectionMetadata_fn).call(this)
3507
3559
  });
3508
- }),
3509
- (error) => __async(this, null, function* () {
3510
- if (error) {
3511
- yield this.storage.removeTransport();
3512
- reject(error);
3513
- } else {
3514
- yield this.storage.setTransport("mwp" /* MWP */);
3515
- resolve();
3560
+ }
3561
+ );
3562
+ __privateMethod(this, _MetaMaskConnectMultichain_instances, transportOrThrow_fn).call(this).connect({ scopes, caipAccountIds, sessionProperties }).then(() => __async(this, null, function* () {
3563
+ var _a3;
3564
+ yield this.options.ui.factory.unload();
3565
+ (_a3 = this.options.ui.factory.modal) == null ? void 0 : _a3.unmount();
3566
+ this.status = "connected";
3567
+ yield this.storage.setTransportType("mwp" /* MWP */);
3568
+ })).catch((error) => __async(this, null, function* () {
3569
+ const { ProtocolError, ErrorCode } = yield import("@metamask/mobile-wallet-protocol-core");
3570
+ if (error instanceof ProtocolError) {
3571
+ if (error.code !== ErrorCode.REQUEST_EXPIRED) {
3572
+ this.status = "disconnected";
3573
+ yield this.options.ui.factory.unload(error);
3574
+ completion.reject(error);
3516
3575
  }
3517
- }),
3518
- (uri) => {
3519
- this.emit("display_uri", uri);
3576
+ } else {
3577
+ this.status = "disconnected";
3578
+ const normalizedError = error instanceof Error ? error : new Error(String(error));
3579
+ yield this.options.ui.factory.unload(normalizedError);
3580
+ completion.reject(normalizedError);
3520
3581
  }
3521
- ).catch((error) => {
3522
- reject(error instanceof Error ? error : new Error(String(error)));
3523
- });
3582
+ }));
3583
+ return sessionRequestDeferred.promise;
3524
3584
  });
3585
+ this.options.ui.factory.renderInstallModal(
3586
+ desktopPreferred,
3587
+ createConnectionRequest,
3588
+ (error) => __async(this, null, function* () {
3589
+ if (error) {
3590
+ yield this.storage.removeTransportType();
3591
+ completion.reject(error);
3592
+ } else {
3593
+ yield this.storage.setTransportType("mwp" /* MWP */);
3594
+ completion.resolve();
3595
+ }
3596
+ }),
3597
+ (uri) => {
3598
+ this.emit("display_uri", uri);
3599
+ }
3600
+ ).catch((error) => {
3601
+ completion.reject(
3602
+ error instanceof Error ? error : new Error(String(error))
3603
+ );
3604
+ });
3605
+ return completion.promise;
3525
3606
  });
3526
3607
  };
3527
3608
  showInstallModal_fn = function(desktopPreferred, scopes, caipAccountIds, sessionProperties) {
@@ -3537,39 +3618,37 @@ showInstallModal_fn = function(desktopPreferred, scopes, caipAccountIds, session
3537
3618
  };
3538
3619
  headlessConnect_fn = function(scopes, caipAccountIds, sessionProperties) {
3539
3620
  return __async(this, null, function* () {
3540
- return new Promise((resolve, reject) => {
3541
- if (this.dappClient.state === "CONNECTED" || this.dappClient.state === "CONNECTING") {
3542
- this.dappClient.disconnect().catch(() => {
3543
- });
3621
+ if (this.dappClient.state === "CONNECTED" || this.dappClient.state === "CONNECTING") {
3622
+ yield this.dappClient.disconnect().catch(() => void 0);
3623
+ }
3624
+ const onSessionRequest = (sessionRequest) => {
3625
+ const connectionRequest = {
3626
+ sessionRequest,
3627
+ metadata: __privateMethod(this, _MetaMaskConnectMultichain_instances, buildConnectionMetadata_fn).call(this)
3628
+ };
3629
+ const deeplink = this.options.ui.factory.createConnectionDeeplink(connectionRequest);
3630
+ this.emit("display_uri", deeplink);
3631
+ };
3632
+ this.dappClient.on("session_request", onSessionRequest);
3633
+ try {
3634
+ yield __privateMethod(this, _MetaMaskConnectMultichain_instances, transportOrThrow_fn).call(this).connect({
3635
+ scopes,
3636
+ caipAccountIds,
3637
+ sessionProperties
3638
+ });
3639
+ this.status = "connected";
3640
+ yield this.storage.setTransportType("mwp" /* MWP */);
3641
+ } catch (error) {
3642
+ const { ProtocolError } = yield import("@metamask/mobile-wallet-protocol-core");
3643
+ this.status = "disconnected";
3644
+ yield this.storage.removeTransportType();
3645
+ if (error instanceof ProtocolError || error instanceof Error) {
3646
+ throw error;
3544
3647
  }
3545
- this.dappClient.on(
3546
- "session_request",
3547
- (sessionRequest) => {
3548
- const connectionRequest = {
3549
- sessionRequest,
3550
- metadata: __privateMethod(this, _MetaMaskConnectMultichain_instances, buildConnectionMetadata_fn).call(this)
3551
- };
3552
- const deeplink = this.options.ui.factory.createConnectionDeeplink(connectionRequest);
3553
- this.emit("display_uri", deeplink);
3554
- }
3555
- );
3556
- this.transport.connect({ scopes, caipAccountIds, sessionProperties }).then(() => __async(this, null, function* () {
3557
- this.status = "connected";
3558
- yield this.storage.setTransport("mwp" /* MWP */);
3559
- resolve();
3560
- })).catch((error) => __async(this, null, function* () {
3561
- const { ProtocolError } = yield import("@metamask/mobile-wallet-protocol-core");
3562
- if (error instanceof ProtocolError) {
3563
- this.status = "disconnected";
3564
- yield this.storage.removeTransport();
3565
- reject(error);
3566
- } else {
3567
- this.status = "disconnected";
3568
- yield this.storage.removeTransport();
3569
- reject(error instanceof Error ? error : new Error(String(error)));
3570
- }
3571
- }));
3572
- });
3648
+ throw new Error(String(error));
3649
+ } finally {
3650
+ this.dappClient.off("session_request", onSessionRequest);
3651
+ }
3573
3652
  });
3574
3653
  };
3575
3654
  setupDefaultTransport_fn = function() {
@@ -3578,7 +3657,7 @@ setupDefaultTransport_fn = function() {
3578
3657
  return __privateGet(this, _transport2);
3579
3658
  }
3580
3659
  if (options == null ? void 0 : options.persist) {
3581
- yield this.storage.setTransport("browser" /* Browser */);
3660
+ yield this.storage.setTransportType("browser" /* Browser */);
3582
3661
  }
3583
3662
  const transport = new DefaultTransport();
3584
3663
  __privateSet(this, _listener, transport.onNotification(
@@ -3611,7 +3690,7 @@ deeplinkConnect_fn = function(scopes, caipAccountIds, sessionProperties) {
3611
3690
  };
3612
3691
  this.dappClient.on("message", dappClientMessageHandler);
3613
3692
  let timeout;
3614
- if (this.transport.isConnected()) {
3693
+ if (__privateMethod(this, _MetaMaskConnectMultichain_instances, transportOrThrow_fn).call(this).isConnected()) {
3615
3694
  timeout = setTimeout(() => {
3616
3695
  this.openSimpleDeeplinkIfNeeded();
3617
3696
  }, 250);
@@ -3639,8 +3718,8 @@ deeplinkConnect_fn = function(scopes, caipAccountIds, sessionProperties) {
3639
3718
  }
3640
3719
  );
3641
3720
  }
3642
- return this.transport.connect({ scopes, caipAccountIds, sessionProperties }).then(resolve).catch((error) => __async(this, null, function* () {
3643
- yield this.storage.removeTransport();
3721
+ return __privateMethod(this, _MetaMaskConnectMultichain_instances, transportOrThrow_fn).call(this).connect({ scopes, caipAccountIds, sessionProperties }).then(resolve).catch((error) => __async(this, null, function* () {
3722
+ yield this.storage.removeTransportType();
3644
3723
  this.dappClient.off("message", dappClientMessageHandler);
3645
3724
  reject(error instanceof Error ? error : new Error(String(error)));
3646
3725
  })).finally(() => {
@@ -3706,7 +3785,7 @@ getCaipSession_fn = function() {
3706
3785
  };
3707
3786
  if ((_a3 = __privateGet(this, _transport2)) == null ? void 0 : _a3.isConnected()) {
3708
3787
  try {
3709
- const response = yield this.transport.request({
3788
+ const response = yield __privateGet(this, _transport2).request({
3710
3789
  method: "wallet_getSession"
3711
3790
  });
3712
3791
  if (response.result) {
@@ -3800,14 +3879,14 @@ var Store = class extends StoreClient {
3800
3879
  super();
3801
3880
  this.adapter = adapter;
3802
3881
  }
3803
- getTransport() {
3882
+ getTransportType() {
3804
3883
  return __async(this, null, function* () {
3805
3884
  try {
3806
- const transport = yield this.adapter.get("multichain-transport");
3807
- if (!transport) {
3885
+ const transportType = yield this.adapter.get("multichain-transport");
3886
+ if (!transportType) {
3808
3887
  return null;
3809
3888
  }
3810
- return getTransportType(transport);
3889
+ return getTransportType(transportType);
3811
3890
  } catch (err) {
3812
3891
  throw new StorageGetErr(
3813
3892
  this.adapter.platform,
@@ -3817,10 +3896,10 @@ var Store = class extends StoreClient {
3817
3896
  }
3818
3897
  });
3819
3898
  }
3820
- setTransport(transport) {
3899
+ setTransportType(transportType) {
3821
3900
  return __async(this, null, function* () {
3822
3901
  try {
3823
- yield this.adapter.set("multichain-transport", transport);
3902
+ yield this.adapter.set("multichain-transport", transportType);
3824
3903
  } catch (err) {
3825
3904
  throw new StorageSetErr(
3826
3905
  this.adapter.platform,
@@ -3830,7 +3909,7 @@ var Store = class extends StoreClient {
3830
3909
  }
3831
3910
  });
3832
3911
  }
3833
- removeTransport() {
3912
+ removeTransportType() {
3834
3913
  return __async(this, null, function* () {
3835
3914
  try {
3836
3915
  yield this.adapter.delete("multichain-transport");
@@ -4044,7 +4123,11 @@ var BaseModalFactory = class {
4044
4123
  (_a4 = this.displayUriCallback) == null ? void 0 : _a4.call(this, newLink);
4045
4124
  return newLink;
4046
4125
  }),
4047
- onClose: this.onCloseModal.bind(this),
4126
+ onClose: (shouldTerminate) => {
4127
+ this.onCloseModal(shouldTerminate).catch((error) => {
4128
+ console.error("Failed to close modal:", error);
4129
+ });
4130
+ },
4048
4131
  startDesktopOnboarding: this.onStartDesktopOnboarding.bind(this),
4049
4132
  createConnectionRequest,
4050
4133
  onDisplayUri: this.displayUriCallback
@@ -4082,7 +4165,7 @@ function preload() {
4082
4165
  }
4083
4166
  try {
4084
4167
  const { defineCustomElements } = yield import("@metamask/multichain-ui/loader");
4085
- yield defineCustomElements();
4168
+ defineCustomElements();
4086
4169
  } catch (error) {
4087
4170
  console.error("Failed to load customElements:", error);
4088
4171
  }