@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 _a2, _b;
612
622
  if ((_b = (_a2 = event == null ? void 0 : event.detail) == null ? void 0 : _a2.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 _a2, _b;
623
- return (_b = (_a2 = provider == null ? void 0 : provider.info) == null ? void 0 : _a2.rdns) == null ? void 0 : _b.startsWith("io.metamask");
629
+ try {
630
+ if (typeof (targetWindow == null ? void 0 : targetWindow.removeEventListener) === "function") {
631
+ targetWindow.removeEventListener("eip6963:announceProvider", handler);
624
632
  }
625
- );
626
- resolve(hasMetaMask);
633
+ const hasMetaMask = providers.some(
634
+ (provider) => {
635
+ var _a2;
636
+ return typeof ((_a2 = provider == null ? void 0 : provider.info) == null ? void 0 : _a2.rdns) === "string" && NATIVE_METAMASK_EIP6963_RDNS.has(provider.info.rdns);
637
+ }
638
+ );
639
+ resolve(hasMetaMask);
640
+ } catch (e) {
641
+ resolve(false);
642
+ }
627
643
  }, 300);
628
644
  });
629
645
  }))();
@@ -1135,12 +1151,14 @@ var init_analytics = __esm({
1135
1151
 
1136
1152
  // src/domain/utils/index.ts
1137
1153
  function getVersion() {
1138
- return "0.0.0";
1154
+ return packageVersion;
1139
1155
  }
1156
+ var packageVersion;
1140
1157
  var init_utils2 = __esm({
1141
1158
  "src/domain/utils/index.ts"() {
1142
1159
  "use strict";
1143
1160
  init_analytics();
1161
+ packageVersion = false ? "unknown" : "1.0.0";
1144
1162
  }
1145
1163
  });
1146
1164
 
@@ -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_utils5, DEFAULT_REQUEST_TIMEOUT2, CONNECTION_GRACE_PERIOD, DEFAULT_CONNECTION_TIMEOUT, DEFAULT_RESUME_TIMEOUT, SESSION_STORE_KEY, ACCOUNTS_STORE_KEY, CHAIN_STORE_KEY, PENDING_SESSION_REQUEST_KEY, CACHED_METHOD_LIST, CACHED_RESET_METHOD_LIST, logger, _MWPTransport_instances, onResumeHandler_fn, resumeSession_fn, startSession_fn, MWPTransport;
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_utils5 = require("@metamask/utils");
1182
1201
  init_domain();
1183
1202
  init_utils();
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 _a2, _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
- (_a2 = walletSession == null ? void 0 : walletSession.sessionScopes) != null ? _a2 : {}
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 _a2;
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((_a2 = session == null ? void 0 : session.id) != null ? _a2 : "");
1475
- }
1476
- });
1477
- } else {
1478
- connection = new Promise(
1479
- (resolveConnection, rejectConnection) => {
1480
- var _a2, _b;
1481
- const optionalScopes = addValidAccounts(
1482
- getOptionalScopes((_a2 = options == null ? void 0 : options.scopes) != null ? _a2 : []),
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 _a2, _b, _c, _d, _e, _f, _g;
1697
+ yield this.waitForWalletSessionIfNotCached();
1698
+ const sessionResponse = yield this.request({ method: "wallet_getSession" });
1699
+ if (sessionResponse.error) {
1700
+ throw new Error(sessionResponse.error.message);
1701
+ }
1702
+ let walletSession = sessionResponse.result;
1703
+ if (walletSession && options) {
1704
+ const currentScopes = Object.keys(
1705
+ (_a2 = walletSession == null ? void 0 : walletSession.sessionScopes) != null ? _a2 : {}
1706
+ );
1707
+ const proposedScopes = (_b = options == null ? void 0 : options.scopes) != null ? _b : [];
1708
+ const proposedCaipAccountIds = (_c = options == null ? void 0 : options.caipAccountIds) != null ? _c : [];
1709
+ const hasSameScopesAndAccounts = isSameScopesAndAccounts(
1710
+ currentScopes,
1711
+ proposedScopes,
1712
+ walletSession,
1713
+ proposedCaipAccountIds
1714
+ );
1715
+ if (options.forceRequest || !hasSameScopesAndAccounts) {
1716
+ const optionalScopes = addValidAccounts(
1717
+ getOptionalScopes((_d = options == null ? void 0 : options.scopes) != null ? _d : []),
1718
+ getValidAccounts((_e = options == null ? void 0 : options.caipAccountIds) != null ? _e : [])
1719
+ );
1720
+ const sessionRequest = {
1721
+ optionalScopes
1722
+ };
1723
+ const response = yield this.request({
1724
+ method: "wallet_createSession",
1725
+ params: sessionRequest
1726
+ });
1727
+ if (response.error) {
1728
+ throw new Error(response.error.message);
1729
+ }
1730
+ walletSession = response.result;
1731
+ }
1732
+ } else if (!walletSession) {
1733
+ const optionalScopes = addValidAccounts(
1734
+ getOptionalScopes((_f = options == null ? void 0 : options.scopes) != null ? _f : []),
1735
+ getValidAccounts((_g = options == null ? void 0 : options.caipAccountIds) != null ? _g : [])
1736
+ );
1737
+ const sessionRequest = {
1738
+ optionalScopes
1739
+ };
1740
+ const response = yield this.request({
1741
+ method: "wallet_createSession",
1742
+ params: sessionRequest
1743
+ });
1744
+ if (response.error) {
1745
+ throw new Error(response.error.message);
1746
+ }
1747
+ walletSession = response.result;
1748
+ }
1749
+ yield this.removeStoredPendingSessionRequest();
1750
+ this.notifyCallbacks({
1751
+ method: "wallet_sessionChanged",
1752
+ params: walletSession
1753
+ });
1754
+ });
1755
+ };
1756
+ resumeSession_fn = function(session, options) {
1757
+ return __async(this, null, function* () {
1758
+ var _a2;
1759
+ const isContinuingPriorAttempt = (yield this.getStoredPendingSessionRequest()) !== null;
1760
+ const resumeDeferred = (0, import_utils5.createDeferredPromise)();
1761
+ const runOnResumeHandler = () => __async(this, null, function* () {
1762
+ try {
1763
+ resumeDeferred.resolve(yield __privateMethod(this, _MWPTransport_instances, onResumeHandler_fn).call(this, options));
1764
+ } catch (err) {
1765
+ resumeDeferred.reject(err);
1766
+ }
1767
+ });
1768
+ if (this.dappClient.state === "CONNECTED") {
1769
+ runOnResumeHandler();
1770
+ } else {
1771
+ this.dappClient.once("connected", runOnResumeHandler);
1772
+ this.dappClient.resume((_a2 = session.id) != null ? _a2 : "").catch((err) => resumeDeferred.reject(err));
1773
+ }
1774
+ const timeoutDeferred = (0, import_utils5.createDeferredPromise)();
1775
+ const timeout = setTimeout(
1776
+ () => timeoutDeferred.reject(new import_multichain_api_client2.TransportTimeoutError()),
1777
+ isContinuingPriorAttempt ? this.options.resumeTimeout : this.options.connectionTimeout
1778
+ );
1779
+ const cleanup = () => this.dappClient.off("connected", runOnResumeHandler);
1780
+ return Promise.race([
1781
+ resumeDeferred.promise,
1782
+ timeoutDeferred.promise
1783
+ ]).finally(() => {
1784
+ clearTimeout(timeout);
1785
+ cleanup();
1786
+ });
1787
+ });
1788
+ };
1789
+ startSession_fn = function(options) {
1790
+ return __async(this, null, function* () {
1791
+ var _a2, _b;
1792
+ const { dappClient } = this;
1793
+ const isContinuingPriorAttempt = (yield this.getStoredPendingSessionRequest()) !== null;
1794
+ const connDeferred = (0, import_utils5.createDeferredPromise)();
1795
+ const optionalScopes = addValidAccounts(
1796
+ getOptionalScopes((_a2 = options == null ? void 0 : options.scopes) != null ? _a2 : []),
1797
+ getValidAccounts((_b = options == null ? void 0 : options.caipAccountIds) != null ? _b : [])
1798
+ );
1799
+ const sessionRequest = {
1800
+ optionalScopes,
1801
+ sessionProperties: options == null ? void 0 : options.sessionProperties
1802
+ };
1803
+ const request = {
1804
+ jsonrpc: "2.0",
1805
+ id: String(getUniqueRequestId()),
1806
+ method: "wallet_createSession",
1807
+ params: sessionRequest
1808
+ };
1809
+ let handler;
1810
+ const removeHandler = () => {
1811
+ if (handler) {
1812
+ this.dappClient.off("message", handler);
1813
+ handler = void 0;
1814
+ }
1815
+ };
1816
+ handler = (message) => __async(this, null, function* () {
1817
+ if (typeof message !== "object" || message === null) {
1818
+ return;
1819
+ }
1820
+ if (!("data" in message)) {
1821
+ return;
1822
+ }
1823
+ const messagePayload = message.data;
1824
+ const isMatchingId = messagePayload.id === request.id;
1825
+ const isMatchingMethod = messagePayload.method === "wallet_createSession" || messagePayload.method === "wallet_sessionChanged";
1826
+ if (!isMatchingId && !isMatchingMethod) {
1827
+ return;
1828
+ }
1829
+ const responseError = this.getResponseError(messagePayload);
1830
+ if (responseError) {
1831
+ connDeferred.reject(this.parseWalletError(responseError));
1832
+ return;
1833
+ }
1834
+ yield this.storeWalletSession(
1835
+ request,
1836
+ messagePayload
1837
+ );
1838
+ yield this.removeStoredPendingSessionRequest();
1839
+ this.notifyCallbacks(messagePayload);
1840
+ connDeferred.resolve();
1841
+ });
1842
+ this.dappClient.on("message", handler);
1843
+ const platformType = getPlatformType();
1844
+ const isQRCodeFlow = [
1845
+ "web-desktop" /* DesktopWeb */,
1846
+ "nodejs" /* NonBrowser */
1847
+ ].includes(platformType);
1848
+ const initialPayload = {
1849
+ name: MULTICHAIN_PROVIDER_STREAM_NAME,
1850
+ data: request
1851
+ };
1852
+ dappClient.connect({
1853
+ mode: "trusted",
1854
+ initialPayload: isQRCodeFlow ? void 0 : initialPayload
1855
+ }).then(() => __async(this, null, function* () {
1856
+ if (isQRCodeFlow) {
1857
+ return dappClient.sendRequest(initialPayload);
1858
+ }
1859
+ return void 0;
1860
+ })).catch((error) => connDeferred.reject(error));
1861
+ const timeoutDeferred = (0, import_utils5.createDeferredPromise)();
1862
+ const timeout = setTimeout(
1863
+ () => timeoutDeferred.reject(new import_multichain_api_client2.TransportTimeoutError()),
1864
+ isContinuingPriorAttempt ? this.options.resumeTimeout : this.options.connectionTimeout
1865
+ );
1866
+ return Promise.race([
1867
+ connDeferred.promise,
1868
+ timeoutDeferred.promise
1869
+ ]).finally(() => {
1870
+ clearTimeout(timeout);
1871
+ removeHandler();
1872
+ });
1873
+ });
1874
+ };
1828
1875
  }
1829
1876
  });
1830
1877
 
@@ -2129,6 +2176,7 @@ var init_node2 = __esm({
2129
2176
  // src/index.node.ts
2130
2177
  var index_node_exports = {};
2131
2178
  __export(index_node_exports, {
2179
+ EIP1193_PASSTHROUGH_METHODS: () => EIP1193_PASSTHROUGH_METHODS,
2132
2180
  EventEmitter: () => EventEmitter,
2133
2181
  Modal: () => Modal,
2134
2182
  MultichainCore: () => MultichainCore,
@@ -2156,7 +2204,8 @@ __export(index_node_exports, {
2156
2204
  isEnabled: () => isEnabled,
2157
2205
  isMetamaskExtensionInstalled: () => isMetamaskExtensionInstalled,
2158
2206
  isRejectionError: () => isRejectionError,
2159
- isSecure: () => isSecure
2207
+ isSecure: () => isSecure,
2208
+ packageVersion: () => packageVersion
2160
2209
  });
2161
2210
  module.exports = __toCommonJS(index_node_exports);
2162
2211
  init_domain();
@@ -2164,6 +2213,7 @@ init_domain();
2164
2213
  // src/multichain/index.ts
2165
2214
  var import_analytics4 = require("@metamask/analytics");
2166
2215
  var import_multichain_api_client3 = require("@metamask/multichain-api-client");
2216
+ var import_utils7 = require("@metamask/utils");
2167
2217
 
2168
2218
  // src/config/index.ts
2169
2219
  var MWP_RELAY_URL = "wss://mm-sdk-relay.api.cx.metamask.io/connection/websocket";
@@ -2317,6 +2367,9 @@ var RequestRouter = class {
2317
2367
  invokeMethod(options) {
2318
2368
  return __async(this, null, function* () {
2319
2369
  const { method } = options.request;
2370
+ if (EIP1193_PASSTHROUGH_METHODS.has(method)) {
2371
+ return this.handleWithEip1193Passthrough(options);
2372
+ }
2320
2373
  if (RPC_HANDLED_METHODS.has(method)) {
2321
2374
  return this.handleWithRpcNode(options);
2322
2375
  }
@@ -2326,6 +2379,29 @@ var RequestRouter = class {
2326
2379
  return this.handleWithWallet(options);
2327
2380
  });
2328
2381
  }
2382
+ /**
2383
+ * Forwards EIP-1193 / legacy provider methods (e.g. `wallet_addEthereumChain`,
2384
+ * `wallet_switchEthereumChain`, `eth_accounts`) directly to the underlying
2385
+ * transport's `sendEip1193Message`, bypassing the multichain
2386
+ * `wallet_invokeMethod` envelope. These methods are wallet-side concerns the
2387
+ * Multichain API does not model, so we forward the raw `{ method, params }`
2388
+ * payload and return the wallet's full JSON-RPC response envelope unchanged.
2389
+ *
2390
+ * Analytics tracking is intentionally skipped here: ecosystem clients
2391
+ * (e.g. `connect-evm`) emit their own `wallet_action_*` events around these
2392
+ * passthrough calls, and adding router-level tracking would double-count.
2393
+ *
2394
+ * @param options
2395
+ */
2396
+ handleWithEip1193Passthrough(options) {
2397
+ return __async(this, null, function* () {
2398
+ const response = yield this.transport.sendEip1193Message({
2399
+ method: options.request.method,
2400
+ params: options.request.params
2401
+ });
2402
+ return response.result;
2403
+ });
2404
+ }
2329
2405
  /**
2330
2406
  * Forwards the request directly to the wallet via the transport.
2331
2407
  *
@@ -2357,14 +2433,6 @@ var RequestRouter = class {
2357
2433
  }), 10);
2358
2434
  }
2359
2435
  const response = yield request;
2360
- if (response.error) {
2361
- const { error } = response;
2362
- throw new RPCInvokeMethodErr(
2363
- `RPC Request failed with code ${error.code}: ${error.message}`,
2364
- error.code,
2365
- error.message
2366
- );
2367
- }
2368
2436
  return response.result;
2369
2437
  }));
2370
2438
  });
@@ -2477,7 +2545,7 @@ trackWalletActionRejected_fn = function(options) {
2477
2545
  var import_multichain_api_client = require("@metamask/multichain-api-client");
2478
2546
  init_utils();
2479
2547
  var DEFAULT_REQUEST_TIMEOUT = 60 * 1e3;
2480
- var _notificationCallbacks, _transport, _defaultRequestOptions, _pendingRequests, _handleResponseListener, _handleNotificationListener, _DefaultTransport_instances, notifyCallbacks_fn, isMetamaskProviderEvent_fn, handleResponse_fn, handleNotification_fn, setupMessageListener_fn, init_fn;
2548
+ var _notificationCallbacks, _transport, _defaultRequestOptions, _pendingRequests, _handleResponseListener, _handleNotificationListener, _DefaultTransport_instances, notifyCallbacks_fn, parseWalletError_fn, isMetamaskProviderEvent_fn, handleResponse_fn, handleNotification_fn, setupMessageListener_fn, init_fn;
2481
2549
  var DefaultTransport = class {
2482
2550
  constructor() {
2483
2551
  __privateAdd(this, _DefaultTransport_instances);
@@ -2613,7 +2681,11 @@ var DefaultTransport = class {
2613
2681
  }
2614
2682
  request(_0) {
2615
2683
  return __async(this, arguments, function* (request, options = __privateGet(this, _defaultRequestOptions)) {
2616
- return __privateGet(this, _transport).request(request, options);
2684
+ const response = yield __privateGet(this, _transport).request(request, options);
2685
+ if (response.error) {
2686
+ throw __privateMethod(this, _DefaultTransport_instances, parseWalletError_fn).call(this, response.error);
2687
+ }
2688
+ return response;
2617
2689
  });
2618
2690
  }
2619
2691
  onNotification(callback) {
@@ -2657,6 +2729,16 @@ notifyCallbacks_fn = function(data) {
2657
2729
  }
2658
2730
  }
2659
2731
  };
2732
+ parseWalletError_fn = function(errorPayload) {
2733
+ const errorData = errorPayload;
2734
+ const error = new Error(
2735
+ typeof errorData.message === "string" ? errorData.message : "Request failed"
2736
+ );
2737
+ if (typeof errorData.code === "number") {
2738
+ error.code = errorData.code;
2739
+ }
2740
+ return error;
2741
+ };
2660
2742
  isMetamaskProviderEvent_fn = function(event) {
2661
2743
  var _a2, _b;
2662
2744
  return ((_b = (_a2 = event == null ? void 0 : event.data) == null ? void 0 : _a2.data) == null ? void 0 : _b.name) === "metamask-provider" && // eslint-disable-next-line no-restricted-globals
@@ -2679,13 +2761,7 @@ handleResponse_fn = function(event) {
2679
2761
  __privateGet(this, _pendingRequests).delete(responseId);
2680
2762
  const response = responseData;
2681
2763
  if ("error" in response && response.error) {
2682
- const error = new Error(
2683
- response.error.message || "Request failed"
2684
- );
2685
- if (typeof response.error.code === "number") {
2686
- error.code = response.error.code;
2687
- }
2688
- pendingRequest.reject(error);
2764
+ pendingRequest.reject(__privateMethod(this, _DefaultTransport_instances, parseWalletError_fn).call(this, response.error));
2689
2765
  } else {
2690
2766
  pendingRequest.resolve(response);
2691
2767
  }
@@ -2723,22 +2799,21 @@ init_fn = function() {
2723
2799
  // src/multichain/transports/multichainApiClientWrapper/index.ts
2724
2800
  var import_rpc_errors = require("@metamask/rpc-errors");
2725
2801
  init_utils();
2726
- var _notificationCallbacks2, _MultichainApiClientWrapperTransport_instances, walletCreateSession_fn, walletGetSession_fn, walletRevokeSession_fn, walletInvokeMethod_fn;
2802
+ var _notificationCallbacks2, _getTransport, _MultichainApiClientWrapperTransport_instances, walletCreateSession_fn, walletGetSession_fn, walletRevokeSession_fn, walletInvokeMethod_fn;
2727
2803
  var MultichainApiClientWrapperTransport = class {
2728
- constructor(metamaskConnectMultichain) {
2804
+ constructor(metamaskConnectMultichain, getTransport) {
2729
2805
  this.metamaskConnectMultichain = metamaskConnectMultichain;
2730
2806
  __privateAdd(this, _MultichainApiClientWrapperTransport_instances);
2731
2807
  __privateAdd(this, _notificationCallbacks2, /* @__PURE__ */ new Set());
2808
+ __privateAdd(this, _getTransport);
2809
+ __privateSet(this, _getTransport, getTransport);
2732
2810
  }
2733
2811
  isTransportDefined() {
2734
- try {
2735
- return Boolean(this.metamaskConnectMultichain.transport);
2736
- } catch (_error) {
2737
- return false;
2738
- }
2812
+ return __privateGet(this, _getTransport).call(this) !== void 0;
2739
2813
  }
2740
2814
  isTransportConnected() {
2741
- return this.isTransportDefined() && this.metamaskConnectMultichain.transport.isConnected();
2815
+ var _a2, _b;
2816
+ return (_b = (_a2 = __privateGet(this, _getTransport).call(this)) == null ? void 0 : _a2.isConnected()) != null ? _b : false;
2742
2817
  }
2743
2818
  clearNotificationCallbacks() {
2744
2819
  __privateGet(this, _notificationCallbacks2).clear();
@@ -2754,10 +2829,11 @@ var MultichainApiClientWrapperTransport = class {
2754
2829
  this.notificationListener = void 0;
2755
2830
  }
2756
2831
  setupTransportNotificationListener() {
2757
- if (!this.isTransportDefined() || this.notificationListener) {
2832
+ const transport = __privateGet(this, _getTransport).call(this);
2833
+ if (!transport || this.notificationListener) {
2758
2834
  return;
2759
2835
  }
2760
- this.notificationListener = this.metamaskConnectMultichain.transport.onNotification(
2836
+ this.notificationListener = transport.onNotification(
2761
2837
  this.notifyCallbacks.bind(this)
2762
2838
  );
2763
2839
  }
@@ -2807,6 +2883,7 @@ var MultichainApiClientWrapperTransport = class {
2807
2883
  }
2808
2884
  };
2809
2885
  _notificationCallbacks2 = new WeakMap();
2886
+ _getTransport = new WeakMap();
2810
2887
  _MultichainApiClientWrapperTransport_instances = new WeakSet();
2811
2888
  walletCreateSession_fn = function(request) {
2812
2889
  return __async(this, null, function* () {
@@ -2830,14 +2907,19 @@ walletCreateSession_fn = function(request) {
2830
2907
  accounts,
2831
2908
  createSessionParams.sessionProperties
2832
2909
  );
2833
- return this.metamaskConnectMultichain.transport.request({
2910
+ const transport = __privateGet(this, _getTransport).call(this);
2911
+ if (!transport) {
2912
+ throw new Error("Transport not initialized after connect");
2913
+ }
2914
+ return transport.request({
2834
2915
  method: "wallet_getSession"
2835
2916
  });
2836
2917
  });
2837
2918
  };
2838
2919
  walletGetSession_fn = function(request) {
2839
2920
  return __async(this, null, function* () {
2840
- if (!this.isTransportConnected()) {
2921
+ const transport = __privateGet(this, _getTransport).call(this);
2922
+ if (!(transport == null ? void 0 : transport.isConnected())) {
2841
2923
  return {
2842
2924
  jsonrpc: "2.0",
2843
2925
  id: request.id,
@@ -2846,7 +2928,7 @@ walletGetSession_fn = function(request) {
2846
2928
  }
2847
2929
  };
2848
2930
  }
2849
- return this.metamaskConnectMultichain.transport.request({
2931
+ return transport.request({
2850
2932
  method: "wallet_getSession"
2851
2933
  });
2852
2934
  });
@@ -2924,7 +3006,7 @@ function setupAnalyticsGlobals(options, storage, setAnonId) {
2924
3006
  import_analytics4.analytics.enable();
2925
3007
  });
2926
3008
  }
2927
- var _a, _provider, _providerTransportWrapper, _transport2, _dappClient, _beforeUnloadListener, _transportType, _listener, _anonId, _sdkInfo, _MetaMaskConnectMultichain_instances, setupAnalytics_fn, onTransportNotification_fn, getStoredTransport_fn, setupTransport_fn, buildConnectionMetadata_fn, init_fn2, createDappClient_fn, setupMWP_fn, onBeforeUnload_fn, createBeforeUnloadListener_fn, renderInstallModalAsync_fn, showInstallModal_fn, headlessConnect_fn, setupDefaultTransport_fn, deeplinkConnect_fn, handleConnection_fn, getCaipSession_fn, openConnectDeeplinkIfNeeded_fn;
3009
+ var _a, _provider, _providerTransportWrapper, _transport2, _dappClient, _beforeUnloadListener, _transportType, _listener, _anonId, _MetaMaskConnectMultichain_instances, transportOrThrow_fn, _sdkInfo, setupAnalytics_fn, onTransportNotification_fn, getStoredTransport_fn, setupTransport_fn, buildConnectionMetadata_fn, init_fn2, createDappClient_fn, setupMWP_fn, onBeforeUnload_fn, createBeforeUnloadListener_fn, renderInstallModalAsync_fn, showInstallModal_fn, headlessConnect_fn, setupDefaultTransport_fn, deeplinkConnect_fn, handleConnection_fn, getCaipSession_fn, openConnectDeeplinkIfNeeded_fn;
2928
3010
  var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends MultichainCore {
2929
3011
  constructor(options) {
2930
3012
  var _a2, _b, _c, _d;
@@ -2937,9 +3019,7 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
2937
3019
  }),
2938
3020
  analytics: normalizeAnalyticsOptions(options.analytics),
2939
3021
  versions: __spreadValues({
2940
- // typeof guard needed: Metro (React Native) bundles TS source directly,
2941
- // bypassing the tsup build that substitutes __PACKAGE_VERSION__.
2942
- "connect-multichain": false ? "unknown" : "0.15.0"
3022
+ "connect-multichain": getVersion()
2943
3023
  }, (_d = options.versions) != null ? _d : {})
2944
3024
  });
2945
3025
  super(allOptions);
@@ -2955,7 +3035,8 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
2955
3035
  __privateAdd(this, _anonId);
2956
3036
  __privateAdd(this, _sdkInfo, `Sdk/Javascript SdkVersion/${getVersion()} Platform/${getPlatformType()} dApp/${(_a = this.options.dapp.url) != null ? _a : this.options.dapp.name} dAppTitle/${this.options.dapp.name}`);
2957
3037
  __privateSet(this, _providerTransportWrapper, new MultichainApiClientWrapperTransport(
2958
- this
3038
+ this,
3039
+ () => __privateGet(this, _transport2)
2959
3040
  ));
2960
3041
  __privateSet(this, _provider, (0, import_multichain_api_client3.getMultichainClient)({
2961
3042
  transport: __privateGet(this, _providerTransportWrapper)
@@ -2974,12 +3055,6 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
2974
3055
  get provider() {
2975
3056
  return __privateGet(this, _provider);
2976
3057
  }
2977
- get transport() {
2978
- if (!__privateGet(this, _transport2)) {
2979
- throw new Error("Transport not initialized, establish connection first");
2980
- }
2981
- return __privateGet(this, _transport2);
2982
- }
2983
3058
  get dappClient() {
2984
3059
  if (!__privateGet(this, _dappClient)) {
2985
3060
  throw new Error("DappClient not initialized, establish connection first");
@@ -2993,6 +3068,9 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
2993
3068
  get storage() {
2994
3069
  return this.options.storage;
2995
3070
  }
3071
+ get version() {
3072
+ return getVersion();
3073
+ }
2996
3074
  // Creates a singleton instance of MetaMaskConnectMultichain.
2997
3075
  // If the singleton already exists, it merges the incoming options with the
2998
3076
  // existing singleton options for the following keys: `api.supportedNetworks`,
@@ -3007,6 +3085,11 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
3007
3085
  const existing = globalObject[SINGLETON_KEY];
3008
3086
  if (existing) {
3009
3087
  const instance = yield existing;
3088
+ if (instance.version !== getVersion()) {
3089
+ console.warn(
3090
+ `MetaMask Connect does not support using multiple versions of @metamask/connect-multichain. Attempted to create a new instance with version ${getVersion()}, but an existing ${instance.version} singleton was already initialized. Using the existing ${instance.version} singleton. This is NOT supported and may lead to unexpected behavior. Please ensure there is only one version of @metamask/connect-multichain package resolved in your application.`
3091
+ );
3092
+ }
3010
3093
  instance.mergeOptions(options);
3011
3094
  if (instance instanceof _MetaMaskConnectMultichain) {
3012
3095
  yield __privateMethod(_a2 = instance, _MetaMaskConnectMultichain_instances, setupAnalytics_fn).call(_a2);
@@ -3030,12 +3113,12 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
3030
3113
  }
3031
3114
  yield __privateMethod(_a3 = instance, _MetaMaskConnectMultichain_instances, init_fn2).call(_a3);
3032
3115
  return instance;
3033
- }))();
3034
- globalObject[SINGLETON_KEY] = instancePromise;
3035
- instancePromise.catch((error) => {
3116
+ }))().catch((error) => {
3036
3117
  globalObject[SINGLETON_KEY] = void 0;
3037
3118
  console.error("Error initializing MetaMaskConnectMultichain", error);
3119
+ throw error;
3038
3120
  });
3121
+ globalObject[SINGLETON_KEY] = instancePromise;
3039
3122
  return instancePromise;
3040
3123
  });
3041
3124
  }
@@ -3095,9 +3178,9 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
3095
3178
  forceRequest
3096
3179
  }).then(() => __async(this, null, function* () {
3097
3180
  if (__privateGet(this, _transportType) === "mwp" /* MWP */) {
3098
- return this.storage.setTransport("mwp" /* MWP */);
3181
+ return this.storage.setTransportType("mwp" /* MWP */);
3099
3182
  }
3100
- return this.storage.setTransport("browser" /* Browser */);
3183
+ return this.storage.setTransportType("browser" /* Browser */);
3101
3184
  })), scopes, transportType);
3102
3185
  }
3103
3186
  if (platformType === "in-app-browser" /* MetaMaskMobileWebview */) {
@@ -3126,11 +3209,6 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
3126
3209
  return __privateMethod(this, _MetaMaskConnectMultichain_instances, handleConnection_fn).call(this, __privateMethod(this, _MetaMaskConnectMultichain_instances, showInstallModal_fn).call(this, shouldShowInstallModal, mergedScopes, mergedCaipAccountIds, nonEmptySessionProperties), scopes, transportType);
3127
3210
  });
3128
3211
  }
3129
- emit(event, args) {
3130
- var _a2, _b;
3131
- (_b = (_a2 = this.options.transport) == null ? void 0 : _a2.onNotification) == null ? void 0 : _b.call(_a2, { method: event, params: args });
3132
- super.emit(event, args);
3133
- }
3134
3212
  disconnect() {
3135
3213
  return __async(this, arguments, function* (scopes = []) {
3136
3214
  var _a2, _b, _c;
@@ -3140,7 +3218,7 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
3140
3218
  );
3141
3219
  yield (_a2 = __privateGet(this, _transport2)) == null ? void 0 : _a2.disconnect(scopes);
3142
3220
  if (remainingScopes.length === 0) {
3143
- yield this.storage.removeTransport();
3221
+ yield this.storage.removeTransportType();
3144
3222
  if (__privateGet(this, _transportType) !== "browser" /* Browser */) {
3145
3223
  yield (_b = __privateGet(this, _listener)) == null ? void 0 : _b.call(this);
3146
3224
  (_c = __privateGet(this, _beforeUnloadListener)) == null ? void 0 : _c.call(this);
@@ -3158,7 +3236,8 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
3158
3236
  invokeMethod(request) {
3159
3237
  return __async(this, null, function* () {
3160
3238
  var _a2;
3161
- const { transport, options } = this;
3239
+ const transport = __privateMethod(this, _MetaMaskConnectMultichain_instances, transportOrThrow_fn).call(this);
3240
+ const { options } = this;
3162
3241
  const rpcClient = new RpcClient(options, __privateGet(this, _sdkInfo));
3163
3242
  const requestRouter = new RequestRouter(
3164
3243
  transport,
@@ -3177,7 +3256,7 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
3177
3256
  const shouldOpenDeeplink = secure && !showInstallModal;
3178
3257
  if (shouldOpenDeeplink) {
3179
3258
  setTimeout(() => __async(this, null, function* () {
3180
- const session = yield this.transport.getActiveSession();
3259
+ const session = yield __privateMethod(this, _MetaMaskConnectMultichain_instances, transportOrThrow_fn).call(this).getActiveSession();
3181
3260
  if (!session) {
3182
3261
  throw new Error("No active session found");
3183
3262
  }
@@ -3201,10 +3280,13 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
3201
3280
  this.emit("wallet_sessionChanged", emptySession);
3202
3281
  return;
3203
3282
  }
3204
- const response = yield this.transport.request({
3283
+ const response = yield __privateGet(this, _transport2).request({
3205
3284
  method: "wallet_getSession"
3206
3285
  });
3207
- this.emit("wallet_sessionChanged", (_b = response.result) != null ? _b : emptySession);
3286
+ this.emit(
3287
+ "wallet_sessionChanged",
3288
+ (_b = response.result) != null ? _b : emptySession
3289
+ );
3208
3290
  });
3209
3291
  }
3210
3292
  };
@@ -3216,8 +3298,14 @@ _beforeUnloadListener = new WeakMap();
3216
3298
  _transportType = new WeakMap();
3217
3299
  _listener = new WeakMap();
3218
3300
  _anonId = new WeakMap();
3219
- _sdkInfo = new WeakMap();
3220
3301
  _MetaMaskConnectMultichain_instances = new WeakSet();
3302
+ transportOrThrow_fn = function() {
3303
+ if (!__privateGet(this, _transport2)) {
3304
+ throw new Error("Transport not initialized, establish connection first");
3305
+ }
3306
+ return __privateGet(this, _transport2);
3307
+ };
3308
+ _sdkInfo = new WeakMap();
3221
3309
  setupAnalytics_fn = function() {
3222
3310
  return __async(this, null, function* () {
3223
3311
  yield setupAnalyticsGlobals(this.options, this.storage, (anonId) => {
@@ -3243,7 +3331,7 @@ onTransportNotification_fn = function(payload) {
3243
3331
  };
3244
3332
  getStoredTransport_fn = function() {
3245
3333
  return __async(this, null, function* () {
3246
- const transportType = yield this.storage.getTransport();
3334
+ const transportType = yield this.storage.getTransportType();
3247
3335
  const hasExtensionInstalled = yield hasExtension();
3248
3336
  if (transportType) {
3249
3337
  if (transportType === "browser" /* Browser */) {
@@ -3271,7 +3359,7 @@ getStoredTransport_fn = function() {
3271
3359
  ));
3272
3360
  return apiTransport;
3273
3361
  }
3274
- yield this.storage.removeTransport();
3362
+ yield this.storage.removeTransportType();
3275
3363
  }
3276
3364
  return void 0;
3277
3365
  });
@@ -3281,15 +3369,15 @@ setupTransport_fn = function() {
3281
3369
  var _a2;
3282
3370
  const transport = yield __privateMethod(this, _MetaMaskConnectMultichain_instances, getStoredTransport_fn).call(this);
3283
3371
  if (transport) {
3284
- if (!this.transport.isConnected()) {
3372
+ if (!transport.isConnected()) {
3285
3373
  this.status = "connecting";
3286
- yield this.transport.connect();
3374
+ yield transport.connect();
3287
3375
  }
3288
3376
  this.status = "connected";
3289
3377
  if (__privateGet(this, _transportType) === "mwp" /* MWP */) {
3290
- yield this.storage.setTransport("mwp" /* MWP */);
3378
+ yield this.storage.setTransportType("mwp" /* MWP */);
3291
3379
  } else {
3292
- yield this.storage.setTransport("browser" /* Browser */);
3380
+ yield this.storage.setTransportType("browser" /* Browser */);
3293
3381
  }
3294
3382
  } else {
3295
3383
  this.status = "loaded";
@@ -3298,7 +3386,7 @@ setupTransport_fn = function() {
3298
3386
  if (hasExtensionInstalled && preferExtension) {
3299
3387
  yield __privateMethod(this, _MetaMaskConnectMultichain_instances, setupDefaultTransport_fn).call(this, { persist: false });
3300
3388
  try {
3301
- yield this.transport.init();
3389
+ yield __privateMethod(this, _MetaMaskConnectMultichain_instances, transportOrThrow_fn).call(this).init();
3302
3390
  } catch (error) {
3303
3391
  console.error("Passive init failed:", error);
3304
3392
  }
@@ -3322,7 +3410,7 @@ init_fn2 = function() {
3322
3410
  yield __privateMethod(this, _MetaMaskConnectMultichain_instances, setupAnalytics_fn).call(this);
3323
3411
  yield __privateMethod(this, _MetaMaskConnectMultichain_instances, setupTransport_fn).call(this);
3324
3412
  } catch (error) {
3325
- yield this.storage.removeTransport();
3413
+ yield this.storage.removeTransportType();
3326
3414
  this.status = "pending";
3327
3415
  logger2("MetaMaskSDK error during initialization", error);
3328
3416
  }
@@ -3368,17 +3456,17 @@ setupMWP_fn = function() {
3368
3456
  __privateSet(this, _transport2, apiTransport);
3369
3457
  __privateSet(this, _transportType, "mwp" /* MWP */);
3370
3458
  __privateGet(this, _providerTransportWrapper).setupTransportNotificationListener();
3371
- __privateSet(this, _listener, this.transport.onNotification(
3459
+ __privateSet(this, _listener, apiTransport.onNotification(
3372
3460
  __privateMethod(this, _MetaMaskConnectMultichain_instances, onTransportNotification_fn).bind(this)
3373
3461
  ));
3374
- yield this.storage.setTransport("mwp" /* MWP */);
3462
+ yield this.storage.setTransportType("mwp" /* MWP */);
3375
3463
  });
3376
3464
  };
3377
3465
  onBeforeUnload_fn = function() {
3378
3466
  return __async(this, null, function* () {
3379
3467
  var _a2;
3380
3468
  if ((_a2 = this.options.ui.factory.modal) == null ? void 0 : _a2.isMounted) {
3381
- yield this.storage.removeTransport();
3469
+ yield this.storage.removeTransportType();
3382
3470
  }
3383
3471
  });
3384
3472
  };
@@ -3395,70 +3483,65 @@ createBeforeUnloadListener_fn = function() {
3395
3483
  };
3396
3484
  renderInstallModalAsync_fn = function(desktopPreferred, scopes, caipAccountIds, sessionProperties) {
3397
3485
  return __async(this, null, function* () {
3398
- return new Promise((resolve, reject) => {
3399
- this.options.ui.factory.renderInstallModal(
3400
- desktopPreferred,
3401
- () => __async(this, null, function* () {
3402
- if (this.dappClient.state === "CONNECTED" || this.dappClient.state === "CONNECTING") {
3403
- yield this.dappClient.disconnect();
3404
- }
3405
- return new Promise((_resolve) => {
3406
- this.dappClient.on(
3407
- "session_request",
3408
- (sessionRequest) => {
3409
- _resolve({
3410
- sessionRequest,
3411
- metadata: __privateMethod(this, _MetaMaskConnectMultichain_instances, buildConnectionMetadata_fn).call(this)
3412
- });
3413
- }
3414
- );
3415
- (() => __async(this, null, function* () {
3416
- var _a2;
3417
- try {
3418
- yield this.transport.connect({
3419
- scopes,
3420
- caipAccountIds,
3421
- sessionProperties
3422
- });
3423
- yield this.options.ui.factory.unload();
3424
- (_a2 = this.options.ui.factory.modal) == null ? void 0 : _a2.unmount();
3425
- this.status = "connected";
3426
- yield this.storage.setTransport("mwp" /* MWP */);
3427
- } catch (error) {
3428
- const { ProtocolError, ErrorCode } = yield import("@metamask/mobile-wallet-protocol-core");
3429
- if (error instanceof ProtocolError) {
3430
- if (error.code !== ErrorCode.REQUEST_EXPIRED) {
3431
- this.status = "disconnected";
3432
- yield this.options.ui.factory.unload(error);
3433
- reject(error);
3434
- }
3435
- } else {
3436
- this.status = "disconnected";
3437
- const normalizedError = error instanceof Error ? error : new Error(String(error));
3438
- yield this.options.ui.factory.unload(normalizedError);
3439
- reject(normalizedError);
3440
- }
3441
- }
3442
- }))().catch(() => {
3443
- });
3486
+ const completion = (0, import_utils7.createDeferredPromise)();
3487
+ const createConnectionRequest = () => __async(this, null, function* () {
3488
+ if (this.dappClient.state === "CONNECTED" || this.dappClient.state === "CONNECTING") {
3489
+ yield this.dappClient.disconnect();
3490
+ }
3491
+ const sessionRequestDeferred = (0, import_utils7.createDeferredPromise)();
3492
+ this.dappClient.on(
3493
+ "session_request",
3494
+ (sessionRequest) => {
3495
+ sessionRequestDeferred.resolve({
3496
+ sessionRequest,
3497
+ metadata: __privateMethod(this, _MetaMaskConnectMultichain_instances, buildConnectionMetadata_fn).call(this)
3444
3498
  });
3445
- }),
3446
- (error) => __async(this, null, function* () {
3447
- if (error) {
3448
- yield this.storage.removeTransport();
3449
- reject(error);
3450
- } else {
3451
- yield this.storage.setTransport("mwp" /* MWP */);
3452
- resolve();
3499
+ }
3500
+ );
3501
+ __privateMethod(this, _MetaMaskConnectMultichain_instances, transportOrThrow_fn).call(this).connect({ scopes, caipAccountIds, sessionProperties }).then(() => __async(this, null, function* () {
3502
+ var _a2;
3503
+ yield this.options.ui.factory.unload();
3504
+ (_a2 = this.options.ui.factory.modal) == null ? void 0 : _a2.unmount();
3505
+ this.status = "connected";
3506
+ yield this.storage.setTransportType("mwp" /* MWP */);
3507
+ })).catch((error) => __async(this, null, function* () {
3508
+ const { ProtocolError, ErrorCode } = yield import("@metamask/mobile-wallet-protocol-core");
3509
+ if (error instanceof ProtocolError) {
3510
+ if (error.code !== ErrorCode.REQUEST_EXPIRED) {
3511
+ this.status = "disconnected";
3512
+ yield this.options.ui.factory.unload(error);
3513
+ completion.reject(error);
3453
3514
  }
3454
- }),
3455
- (uri) => {
3456
- this.emit("display_uri", uri);
3515
+ } else {
3516
+ this.status = "disconnected";
3517
+ const normalizedError = error instanceof Error ? error : new Error(String(error));
3518
+ yield this.options.ui.factory.unload(normalizedError);
3519
+ completion.reject(normalizedError);
3457
3520
  }
3458
- ).catch((error) => {
3459
- reject(error instanceof Error ? error : new Error(String(error)));
3460
- });
3521
+ }));
3522
+ return sessionRequestDeferred.promise;
3461
3523
  });
3524
+ this.options.ui.factory.renderInstallModal(
3525
+ desktopPreferred,
3526
+ createConnectionRequest,
3527
+ (error) => __async(this, null, function* () {
3528
+ if (error) {
3529
+ yield this.storage.removeTransportType();
3530
+ completion.reject(error);
3531
+ } else {
3532
+ yield this.storage.setTransportType("mwp" /* MWP */);
3533
+ completion.resolve();
3534
+ }
3535
+ }),
3536
+ (uri) => {
3537
+ this.emit("display_uri", uri);
3538
+ }
3539
+ ).catch((error) => {
3540
+ completion.reject(
3541
+ error instanceof Error ? error : new Error(String(error))
3542
+ );
3543
+ });
3544
+ return completion.promise;
3462
3545
  });
3463
3546
  };
3464
3547
  showInstallModal_fn = function(desktopPreferred, scopes, caipAccountIds, sessionProperties) {
@@ -3474,39 +3557,37 @@ showInstallModal_fn = function(desktopPreferred, scopes, caipAccountIds, session
3474
3557
  };
3475
3558
  headlessConnect_fn = function(scopes, caipAccountIds, sessionProperties) {
3476
3559
  return __async(this, null, function* () {
3477
- return new Promise((resolve, reject) => {
3478
- if (this.dappClient.state === "CONNECTED" || this.dappClient.state === "CONNECTING") {
3479
- this.dappClient.disconnect().catch(() => {
3480
- });
3560
+ if (this.dappClient.state === "CONNECTED" || this.dappClient.state === "CONNECTING") {
3561
+ yield this.dappClient.disconnect().catch(() => void 0);
3562
+ }
3563
+ const onSessionRequest = (sessionRequest) => {
3564
+ const connectionRequest = {
3565
+ sessionRequest,
3566
+ metadata: __privateMethod(this, _MetaMaskConnectMultichain_instances, buildConnectionMetadata_fn).call(this)
3567
+ };
3568
+ const deeplink = this.options.ui.factory.createConnectionDeeplink(connectionRequest);
3569
+ this.emit("display_uri", deeplink);
3570
+ };
3571
+ this.dappClient.on("session_request", onSessionRequest);
3572
+ try {
3573
+ yield __privateMethod(this, _MetaMaskConnectMultichain_instances, transportOrThrow_fn).call(this).connect({
3574
+ scopes,
3575
+ caipAccountIds,
3576
+ sessionProperties
3577
+ });
3578
+ this.status = "connected";
3579
+ yield this.storage.setTransportType("mwp" /* MWP */);
3580
+ } catch (error) {
3581
+ const { ProtocolError } = yield import("@metamask/mobile-wallet-protocol-core");
3582
+ this.status = "disconnected";
3583
+ yield this.storage.removeTransportType();
3584
+ if (error instanceof ProtocolError || error instanceof Error) {
3585
+ throw error;
3481
3586
  }
3482
- this.dappClient.on(
3483
- "session_request",
3484
- (sessionRequest) => {
3485
- const connectionRequest = {
3486
- sessionRequest,
3487
- metadata: __privateMethod(this, _MetaMaskConnectMultichain_instances, buildConnectionMetadata_fn).call(this)
3488
- };
3489
- const deeplink = this.options.ui.factory.createConnectionDeeplink(connectionRequest);
3490
- this.emit("display_uri", deeplink);
3491
- }
3492
- );
3493
- this.transport.connect({ scopes, caipAccountIds, sessionProperties }).then(() => __async(this, null, function* () {
3494
- this.status = "connected";
3495
- yield this.storage.setTransport("mwp" /* MWP */);
3496
- resolve();
3497
- })).catch((error) => __async(this, null, function* () {
3498
- const { ProtocolError } = yield import("@metamask/mobile-wallet-protocol-core");
3499
- if (error instanceof ProtocolError) {
3500
- this.status = "disconnected";
3501
- yield this.storage.removeTransport();
3502
- reject(error);
3503
- } else {
3504
- this.status = "disconnected";
3505
- yield this.storage.removeTransport();
3506
- reject(error instanceof Error ? error : new Error(String(error)));
3507
- }
3508
- }));
3509
- });
3587
+ throw new Error(String(error));
3588
+ } finally {
3589
+ this.dappClient.off("session_request", onSessionRequest);
3590
+ }
3510
3591
  });
3511
3592
  };
3512
3593
  setupDefaultTransport_fn = function() {
@@ -3515,7 +3596,7 @@ setupDefaultTransport_fn = function() {
3515
3596
  return __privateGet(this, _transport2);
3516
3597
  }
3517
3598
  if (options == null ? void 0 : options.persist) {
3518
- yield this.storage.setTransport("browser" /* Browser */);
3599
+ yield this.storage.setTransportType("browser" /* Browser */);
3519
3600
  }
3520
3601
  const transport = new DefaultTransport();
3521
3602
  __privateSet(this, _listener, transport.onNotification(
@@ -3548,7 +3629,7 @@ deeplinkConnect_fn = function(scopes, caipAccountIds, sessionProperties) {
3548
3629
  };
3549
3630
  this.dappClient.on("message", dappClientMessageHandler);
3550
3631
  let timeout;
3551
- if (this.transport.isConnected()) {
3632
+ if (__privateMethod(this, _MetaMaskConnectMultichain_instances, transportOrThrow_fn).call(this).isConnected()) {
3552
3633
  timeout = setTimeout(() => {
3553
3634
  this.openSimpleDeeplinkIfNeeded();
3554
3635
  }, 250);
@@ -3576,8 +3657,8 @@ deeplinkConnect_fn = function(scopes, caipAccountIds, sessionProperties) {
3576
3657
  }
3577
3658
  );
3578
3659
  }
3579
- return this.transport.connect({ scopes, caipAccountIds, sessionProperties }).then(resolve).catch((error) => __async(this, null, function* () {
3580
- yield this.storage.removeTransport();
3660
+ return __privateMethod(this, _MetaMaskConnectMultichain_instances, transportOrThrow_fn).call(this).connect({ scopes, caipAccountIds, sessionProperties }).then(resolve).catch((error) => __async(this, null, function* () {
3661
+ yield this.storage.removeTransportType();
3581
3662
  this.dappClient.off("message", dappClientMessageHandler);
3582
3663
  reject(error instanceof Error ? error : new Error(String(error)));
3583
3664
  })).finally(() => {
@@ -3643,7 +3724,7 @@ getCaipSession_fn = function() {
3643
3724
  };
3644
3725
  if ((_a2 = __privateGet(this, _transport2)) == null ? void 0 : _a2.isConnected()) {
3645
3726
  try {
3646
- const response = yield this.transport.request({
3727
+ const response = yield __privateGet(this, _transport2).request({
3647
3728
  method: "wallet_getSession"
3648
3729
  });
3649
3730
  if (response.result) {
@@ -3737,14 +3818,14 @@ var Store = class extends StoreClient {
3737
3818
  super();
3738
3819
  this.adapter = adapter;
3739
3820
  }
3740
- getTransport() {
3821
+ getTransportType() {
3741
3822
  return __async(this, null, function* () {
3742
3823
  try {
3743
- const transport = yield this.adapter.get("multichain-transport");
3744
- if (!transport) {
3824
+ const transportType = yield this.adapter.get("multichain-transport");
3825
+ if (!transportType) {
3745
3826
  return null;
3746
3827
  }
3747
- return getTransportType(transport);
3828
+ return getTransportType(transportType);
3748
3829
  } catch (err) {
3749
3830
  throw new StorageGetErr(
3750
3831
  this.adapter.platform,
@@ -3754,10 +3835,10 @@ var Store = class extends StoreClient {
3754
3835
  }
3755
3836
  });
3756
3837
  }
3757
- setTransport(transport) {
3838
+ setTransportType(transportType) {
3758
3839
  return __async(this, null, function* () {
3759
3840
  try {
3760
- yield this.adapter.set("multichain-transport", transport);
3841
+ yield this.adapter.set("multichain-transport", transportType);
3761
3842
  } catch (err) {
3762
3843
  throw new StorageSetErr(
3763
3844
  this.adapter.platform,
@@ -3767,7 +3848,7 @@ var Store = class extends StoreClient {
3767
3848
  }
3768
3849
  });
3769
3850
  }
3770
- removeTransport() {
3851
+ removeTransportType() {
3771
3852
  return __async(this, null, function* () {
3772
3853
  try {
3773
3854
  yield this.adapter.delete("multichain-transport");
@@ -3981,7 +4062,11 @@ var BaseModalFactory = class {
3981
4062
  (_a3 = this.displayUriCallback) == null ? void 0 : _a3.call(this, newLink);
3982
4063
  return newLink;
3983
4064
  }),
3984
- onClose: this.onCloseModal.bind(this),
4065
+ onClose: (shouldTerminate) => {
4066
+ this.onCloseModal(shouldTerminate).catch((error) => {
4067
+ console.error("Failed to close modal:", error);
4068
+ });
4069
+ },
3985
4070
  startDesktopOnboarding: this.onStartDesktopOnboarding.bind(this),
3986
4071
  createConnectionRequest,
3987
4072
  onDisplayUri: this.displayUriCallback
@@ -4019,7 +4104,7 @@ function preload() {
4019
4104
  }
4020
4105
  try {
4021
4106
  const { defineCustomElements } = yield import("@metamask/multichain-ui/loader");
4022
- yield defineCustomElements();
4107
+ defineCustomElements();
4023
4108
  } catch (error) {
4024
4109
  console.error("Failed to load customElements:", error);
4025
4110
  }
@@ -4058,6 +4143,7 @@ var createMultichainClient = (options) => __async(null, null, function* () {
4058
4143
  });
4059
4144
  // Annotate the CommonJS export names for ESM import in node:
4060
4145
  0 && (module.exports = {
4146
+ EIP1193_PASSTHROUGH_METHODS,
4061
4147
  EventEmitter,
4062
4148
  Modal,
4063
4149
  MultichainCore,
@@ -4085,6 +4171,7 @@ var createMultichainClient = (options) => __async(null, null, function* () {
4085
4171
  isEnabled,
4086
4172
  isMetamaskExtensionInstalled,
4087
4173
  isRejectionError,
4088
- isSecure
4174
+ isSecure,
4175
+ packageVersion
4089
4176
  });
4090
4177
  //# sourceMappingURL=connect-multichain.js.map