@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
@@ -252,7 +252,7 @@ var init_logger = __esm({
252
252
  });
253
253
 
254
254
  // src/domain/multichain/api/constants.ts
255
- var infuraRpcUrls, RPC_HANDLED_METHODS, SDK_HANDLED_METHODS;
255
+ var infuraRpcUrls, RPC_HANDLED_METHODS, SDK_HANDLED_METHODS, EIP1193_PASSTHROUGH_METHODS;
256
256
  var init_constants = __esm({
257
257
  "src/domain/multichain/api/constants.ts"() {
258
258
  "use strict";
@@ -417,6 +417,11 @@ var init_constants = __esm({
417
417
  "eth_uninstallFilter"
418
418
  ]);
419
419
  SDK_HANDLED_METHODS = /* @__PURE__ */ new Set(["eth_accounts", "eth_chainId"]);
420
+ EIP1193_PASSTHROUGH_METHODS = /* @__PURE__ */ new Set([
421
+ "wallet_addEthereumChain",
422
+ "wallet_switchEthereumChain",
423
+ "eth_accounts"
424
+ ]);
420
425
  }
421
426
  });
422
427
 
@@ -567,7 +572,7 @@ function hasExtension() {
567
572
  return detectionPromise;
568
573
  });
569
574
  }
570
- var PlatformType, detectionPromise;
575
+ var PlatformType, NATIVE_METAMASK_EIP6963_RDNS, detectionPromise;
571
576
  var init_platform = __esm({
572
577
  "src/domain/platform/index.ts"() {
573
578
  "use strict";
@@ -579,6 +584,10 @@ var init_platform = __esm({
579
584
  PlatformType2["ReactNative"] = "react-native";
580
585
  return PlatformType2;
581
586
  })(PlatformType || {});
587
+ NATIVE_METAMASK_EIP6963_RDNS = /* @__PURE__ */ new Set([
588
+ "io.metamask",
589
+ "io.metamask.mobile"
590
+ ]);
582
591
  detectionPromise = (() => __async(null, null, function* () {
583
592
  const pt = getPlatformType();
584
593
  if (pt === "nodejs" /* NonBrowser */ || pt === "react-native" /* ReactNative */) {
@@ -586,23 +595,30 @@ var init_platform = __esm({
586
595
  }
587
596
  return new Promise((resolve) => {
588
597
  const providers = [];
598
+ const targetWindow = window;
589
599
  const handler = (event) => {
590
600
  var _a2, _b;
591
601
  if ((_b = (_a2 = event == null ? void 0 : event.detail) == null ? void 0 : _a2.info) == null ? void 0 : _b.rdns) {
592
602
  providers.push(event.detail);
593
603
  }
594
604
  };
595
- window.addEventListener("eip6963:announceProvider", handler);
596
- window.dispatchEvent(new Event("eip6963:requestProvider"));
605
+ targetWindow.addEventListener("eip6963:announceProvider", handler);
606
+ targetWindow.dispatchEvent(new Event("eip6963:requestProvider"));
597
607
  setTimeout(() => {
598
- window.removeEventListener("eip6963:announceProvider", handler);
599
- const hasMetaMask = providers.some(
600
- (provider) => {
601
- var _a2, _b;
602
- return (_b = (_a2 = provider == null ? void 0 : provider.info) == null ? void 0 : _a2.rdns) == null ? void 0 : _b.startsWith("io.metamask");
608
+ try {
609
+ if (typeof (targetWindow == null ? void 0 : targetWindow.removeEventListener) === "function") {
610
+ targetWindow.removeEventListener("eip6963:announceProvider", handler);
603
611
  }
604
- );
605
- resolve(hasMetaMask);
612
+ const hasMetaMask = providers.some(
613
+ (provider) => {
614
+ var _a2;
615
+ return typeof ((_a2 = provider == null ? void 0 : provider.info) == null ? void 0 : _a2.rdns) === "string" && NATIVE_METAMASK_EIP6963_RDNS.has(provider.info.rdns);
616
+ }
617
+ );
618
+ resolve(hasMetaMask);
619
+ } catch (e) {
620
+ resolve(false);
621
+ }
606
622
  }, 300);
607
623
  });
608
624
  }))();
@@ -1117,12 +1133,14 @@ var init_analytics = __esm({
1117
1133
 
1118
1134
  // src/domain/utils/index.ts
1119
1135
  function getVersion() {
1120
- return "0.0.0";
1136
+ return packageVersion;
1121
1137
  }
1138
+ var packageVersion;
1122
1139
  var init_utils2 = __esm({
1123
1140
  "src/domain/utils/index.ts"() {
1124
1141
  "use strict";
1125
1142
  init_analytics();
1143
+ packageVersion = false ? "unknown" : "1.0.0";
1126
1144
  }
1127
1145
  });
1128
1146
 
@@ -1159,7 +1177,8 @@ import {
1159
1177
  TransportTimeoutError
1160
1178
  } from "@metamask/multichain-api-client";
1161
1179
  import { JsonRpcError, providerErrors as providerErrors2, rpcErrors } from "@metamask/rpc-errors";
1162
- var DEFAULT_REQUEST_TIMEOUT2, CONNECTION_GRACE_PERIOD, DEFAULT_CONNECTION_TIMEOUT, DEFAULT_RESUME_TIMEOUT, SESSION_STORE_KEY, ACCOUNTS_STORE_KEY, CHAIN_STORE_KEY, PENDING_SESSION_REQUEST_KEY, CACHED_METHOD_LIST, CACHED_RESET_METHOD_LIST, logger, MWPTransport;
1180
+ import { createDeferredPromise } from "@metamask/utils";
1181
+ var DEFAULT_REQUEST_TIMEOUT2, CONNECTION_GRACE_PERIOD, DEFAULT_CONNECTION_TIMEOUT, DEFAULT_RESUME_TIMEOUT, SESSION_STORE_KEY, ACCOUNTS_STORE_KEY, CHAIN_STORE_KEY, PENDING_SESSION_REQUEST_KEY, CACHED_METHOD_LIST, CACHED_RESET_METHOD_LIST, logger, _MWPTransport_instances, onResumeHandler_fn, resumeSession_fn, startSession_fn, MWPTransport;
1163
1182
  var init_mwp = __esm({
1164
1183
  "src/multichain/transports/mwp/index.ts"() {
1165
1184
  "use strict";
@@ -1193,6 +1212,7 @@ var init_mwp = __esm({
1193
1212
  this.dappClient = dappClient;
1194
1213
  this.kvstore = kvstore;
1195
1214
  this.options = options;
1215
+ __privateAdd(this, _MWPTransport_instances);
1196
1216
  this.__pendingRequests = /* @__PURE__ */ new Map();
1197
1217
  this.notificationCallbacks = /* @__PURE__ */ new Set();
1198
1218
  this.dappClient.on("message", this.handleMessage.bind(this));
@@ -1272,6 +1292,23 @@ var init_mwp = __esm({
1272
1292
  const message = errorPayload instanceof Error ? errorPayload.message : JSON.stringify(errorPayload);
1273
1293
  return rpcErrors.internal({ message });
1274
1294
  }
1295
+ getResponseError(messagePayload) {
1296
+ if ("error" in messagePayload && messagePayload.error) {
1297
+ return messagePayload.error;
1298
+ }
1299
+ const { result } = messagePayload;
1300
+ if (typeof result === "object" && result !== null && "error" in result && result.error && this.isErrorPayload(result.error)) {
1301
+ return result.error;
1302
+ }
1303
+ return void 0;
1304
+ }
1305
+ isErrorPayload(errorPayload) {
1306
+ if (errorPayload instanceof Error) {
1307
+ return true;
1308
+ }
1309
+ const errorData = errorPayload;
1310
+ return typeof (errorData == null ? void 0 : errorData.code) === "number" && typeof (errorData == null ? void 0 : errorData.message) === "string";
1311
+ }
1275
1312
  handleMessage(message) {
1276
1313
  if (typeof message === "object" && message !== null) {
1277
1314
  if ("data" in message) {
@@ -1280,9 +1317,10 @@ var init_mwp = __esm({
1280
1317
  const request = this.pendingRequests.get(messagePayload.id);
1281
1318
  if (request) {
1282
1319
  clearTimeout(request.timeout);
1283
- if ("error" in messagePayload && messagePayload.error) {
1320
+ const responseError = this.getResponseError(messagePayload);
1321
+ if (responseError) {
1284
1322
  this.pendingRequests.delete(messagePayload.id);
1285
- request.reject(this.parseWalletError(messagePayload.error));
1323
+ request.reject(this.parseWalletError(responseError));
1286
1324
  return;
1287
1325
  }
1288
1326
  const requestWithName = __spreadProps(__spreadValues({}, messagePayload), {
@@ -1325,73 +1363,6 @@ var init_mwp = __esm({
1325
1363
  }
1326
1364
  }
1327
1365
  }
1328
- onResumeSuccess(resumeResolve, resumeReject, options) {
1329
- return __async(this, null, function* () {
1330
- var _a2, _b, _c, _d, _e, _f, _g;
1331
- try {
1332
- yield this.waitForWalletSessionIfNotCached();
1333
- const sessionRequest = yield this.request({
1334
- method: "wallet_getSession"
1335
- });
1336
- if (sessionRequest.error) {
1337
- return resumeReject(new Error(sessionRequest.error.message));
1338
- }
1339
- let walletSession = sessionRequest.result;
1340
- if (walletSession && options) {
1341
- const currentScopes = Object.keys(
1342
- (_a2 = walletSession == null ? void 0 : walletSession.sessionScopes) != null ? _a2 : {}
1343
- );
1344
- const proposedScopes = (_b = options == null ? void 0 : options.scopes) != null ? _b : [];
1345
- const proposedCaipAccountIds = (_c = options == null ? void 0 : options.caipAccountIds) != null ? _c : [];
1346
- const hasSameScopesAndAccounts = isSameScopesAndAccounts(
1347
- currentScopes,
1348
- proposedScopes,
1349
- walletSession,
1350
- proposedCaipAccountIds
1351
- );
1352
- if (options.forceRequest || !hasSameScopesAndAccounts) {
1353
- const optionalScopes = addValidAccounts(
1354
- getOptionalScopes((_d = options == null ? void 0 : options.scopes) != null ? _d : []),
1355
- getValidAccounts((_e = options == null ? void 0 : options.caipAccountIds) != null ? _e : [])
1356
- );
1357
- const sessionRequest2 = {
1358
- optionalScopes
1359
- };
1360
- const response = yield this.request({
1361
- method: "wallet_createSession",
1362
- params: sessionRequest2
1363
- });
1364
- if (response.error) {
1365
- return resumeReject(new Error(response.error.message));
1366
- }
1367
- walletSession = response.result;
1368
- }
1369
- } else if (!walletSession) {
1370
- const optionalScopes = addValidAccounts(
1371
- getOptionalScopes((_f = options == null ? void 0 : options.scopes) != null ? _f : []),
1372
- getValidAccounts((_g = options == null ? void 0 : options.caipAccountIds) != null ? _g : [])
1373
- );
1374
- const sessionRequest2 = { optionalScopes };
1375
- const response = yield this.request({
1376
- method: "wallet_createSession",
1377
- params: sessionRequest2
1378
- });
1379
- if (response.error) {
1380
- return resumeReject(new Error(response.error.message));
1381
- }
1382
- walletSession = response.result;
1383
- }
1384
- yield this.removeStoredPendingSessionRequest();
1385
- this.notifyCallbacks({
1386
- method: "wallet_sessionChanged",
1387
- params: walletSession
1388
- });
1389
- return resumeResolve();
1390
- } catch (err) {
1391
- return resumeReject(err);
1392
- }
1393
- });
1394
- }
1395
1366
  init() {
1396
1367
  return __async(this, null, function* () {
1397
1368
  });
@@ -1432,7 +1403,6 @@ var init_mwp = __esm({
1432
1403
  }
1433
1404
  connect(options) {
1434
1405
  return __async(this, null, function* () {
1435
- const { dappClient } = this;
1436
1406
  const session = yield this.getActiveSession();
1437
1407
  if (session) {
1438
1408
  logger("active session found", {
@@ -1441,116 +1411,11 @@ var init_mwp = __esm({
1441
1411
  expiresAt: session.expiresAt
1442
1412
  });
1443
1413
  }
1444
- const storedSessionRequestBeforeConnectionAttempt = yield this.getStoredPendingSessionRequest();
1445
- let timeout;
1446
- let initialConnectionMessageHandler;
1447
- const connectionPromise = new Promise((resolve, reject) => __async(this, null, function* () {
1448
- let connection;
1449
- if (session) {
1450
- connection = new Promise((resumeResolve, resumeReject) => {
1451
- var _a2;
1452
- if (this.dappClient.state === "CONNECTED") {
1453
- this.onResumeSuccess(resumeResolve, resumeReject, options);
1454
- } else {
1455
- this.dappClient.once("connected", () => __async(this, null, function* () {
1456
- this.onResumeSuccess(resumeResolve, resumeReject, options);
1457
- }));
1458
- dappClient.resume((_a2 = session == null ? void 0 : session.id) != null ? _a2 : "");
1459
- }
1460
- });
1461
- } else {
1462
- connection = new Promise(
1463
- (resolveConnection, rejectConnection) => {
1464
- var _a2, _b;
1465
- const optionalScopes = addValidAccounts(
1466
- getOptionalScopes((_a2 = options == null ? void 0 : options.scopes) != null ? _a2 : []),
1467
- getValidAccounts((_b = options == null ? void 0 : options.caipAccountIds) != null ? _b : [])
1468
- );
1469
- const sessionRequest = {
1470
- optionalScopes,
1471
- sessionProperties: options == null ? void 0 : options.sessionProperties
1472
- };
1473
- const request = {
1474
- jsonrpc: "2.0",
1475
- id: String(getUniqueRequestId()),
1476
- method: "wallet_createSession",
1477
- params: sessionRequest
1478
- };
1479
- initialConnectionMessageHandler = (message) => __async(this, null, function* () {
1480
- if (typeof message !== "object" || message === null) {
1481
- return;
1482
- }
1483
- if (!("data" in message)) {
1484
- return;
1485
- }
1486
- const messagePayload = message.data;
1487
- const isMatchingId = messagePayload.id === request.id;
1488
- const isMatchingMethod = messagePayload.method === "wallet_createSession" || messagePayload.method === "wallet_sessionChanged";
1489
- if (!isMatchingId && !isMatchingMethod) {
1490
- return;
1491
- }
1492
- if (messagePayload.error) {
1493
- return rejectConnection(
1494
- this.parseWalletError(messagePayload.error)
1495
- );
1496
- }
1497
- yield this.storeWalletSession(
1498
- request,
1499
- messagePayload
1500
- );
1501
- yield this.removeStoredPendingSessionRequest();
1502
- this.notifyCallbacks(messagePayload);
1503
- return resolveConnection();
1504
- });
1505
- this.dappClient.on("message", initialConnectionMessageHandler);
1506
- const platformType = getPlatformType();
1507
- const isQRCodeFlow = [
1508
- "web-desktop" /* DesktopWeb */,
1509
- "nodejs" /* NonBrowser */
1510
- ].includes(platformType);
1511
- const initialPayload = {
1512
- name: MULTICHAIN_PROVIDER_STREAM_NAME,
1513
- data: request
1514
- };
1515
- dappClient.connect({
1516
- mode: "trusted",
1517
- initialPayload: isQRCodeFlow ? void 0 : initialPayload
1518
- }).then(() => __async(this, null, function* () {
1519
- if (isQRCodeFlow) {
1520
- return dappClient.sendRequest(initialPayload);
1521
- }
1522
- return void 0;
1523
- })).catch((error) => {
1524
- if (initialConnectionMessageHandler) {
1525
- this.dappClient.off(
1526
- "message",
1527
- initialConnectionMessageHandler
1528
- );
1529
- }
1530
- rejectConnection(error);
1531
- });
1532
- }
1533
- );
1534
- }
1535
- timeout = setTimeout(
1536
- () => {
1537
- reject(new TransportTimeoutError());
1538
- },
1539
- storedSessionRequestBeforeConnectionAttempt ? this.options.resumeTimeout : this.options.connectionTimeout
1540
- );
1541
- connection.then(resolve).catch(reject);
1542
- }));
1543
- return connectionPromise.catch((error) => __async(this, null, function* () {
1414
+ const connection = session ? __privateMethod(this, _MWPTransport_instances, resumeSession_fn).call(this, session, options) : __privateMethod(this, _MWPTransport_instances, startSession_fn).call(this, options);
1415
+ return connection.catch((error) => __async(this, null, function* () {
1544
1416
  yield this.dappClient.disconnect();
1545
1417
  throw error;
1546
1418
  })).finally(() => {
1547
- if (timeout) {
1548
- clearTimeout(timeout);
1549
- }
1550
- if (initialConnectionMessageHandler) {
1551
- this.dappClient.off("message", initialConnectionMessageHandler);
1552
- initialConnectionMessageHandler = void 0;
1553
- }
1554
1419
  this.removeStoredPendingSessionRequest();
1555
1420
  });
1556
1421
  });
@@ -1809,6 +1674,188 @@ var init_mwp = __esm({
1809
1674
  });
1810
1675
  }
1811
1676
  };
1677
+ _MWPTransport_instances = new WeakSet();
1678
+ onResumeHandler_fn = function(options) {
1679
+ return __async(this, null, function* () {
1680
+ var _a2, _b, _c, _d, _e, _f, _g;
1681
+ yield this.waitForWalletSessionIfNotCached();
1682
+ const sessionResponse = yield this.request({ method: "wallet_getSession" });
1683
+ if (sessionResponse.error) {
1684
+ throw new Error(sessionResponse.error.message);
1685
+ }
1686
+ let walletSession = sessionResponse.result;
1687
+ if (walletSession && options) {
1688
+ const currentScopes = Object.keys(
1689
+ (_a2 = walletSession == null ? void 0 : walletSession.sessionScopes) != null ? _a2 : {}
1690
+ );
1691
+ const proposedScopes = (_b = options == null ? void 0 : options.scopes) != null ? _b : [];
1692
+ const proposedCaipAccountIds = (_c = options == null ? void 0 : options.caipAccountIds) != null ? _c : [];
1693
+ const hasSameScopesAndAccounts = isSameScopesAndAccounts(
1694
+ currentScopes,
1695
+ proposedScopes,
1696
+ walletSession,
1697
+ proposedCaipAccountIds
1698
+ );
1699
+ if (options.forceRequest || !hasSameScopesAndAccounts) {
1700
+ const optionalScopes = addValidAccounts(
1701
+ getOptionalScopes((_d = options == null ? void 0 : options.scopes) != null ? _d : []),
1702
+ getValidAccounts((_e = options == null ? void 0 : options.caipAccountIds) != null ? _e : [])
1703
+ );
1704
+ const sessionRequest = {
1705
+ optionalScopes
1706
+ };
1707
+ const response = yield this.request({
1708
+ method: "wallet_createSession",
1709
+ params: sessionRequest
1710
+ });
1711
+ if (response.error) {
1712
+ throw new Error(response.error.message);
1713
+ }
1714
+ walletSession = response.result;
1715
+ }
1716
+ } else if (!walletSession) {
1717
+ const optionalScopes = addValidAccounts(
1718
+ getOptionalScopes((_f = options == null ? void 0 : options.scopes) != null ? _f : []),
1719
+ getValidAccounts((_g = options == null ? void 0 : options.caipAccountIds) != null ? _g : [])
1720
+ );
1721
+ const sessionRequest = {
1722
+ optionalScopes
1723
+ };
1724
+ const response = yield this.request({
1725
+ method: "wallet_createSession",
1726
+ params: sessionRequest
1727
+ });
1728
+ if (response.error) {
1729
+ throw new Error(response.error.message);
1730
+ }
1731
+ walletSession = response.result;
1732
+ }
1733
+ yield this.removeStoredPendingSessionRequest();
1734
+ this.notifyCallbacks({
1735
+ method: "wallet_sessionChanged",
1736
+ params: walletSession
1737
+ });
1738
+ });
1739
+ };
1740
+ resumeSession_fn = function(session, options) {
1741
+ return __async(this, null, function* () {
1742
+ var _a2;
1743
+ const isContinuingPriorAttempt = (yield this.getStoredPendingSessionRequest()) !== null;
1744
+ const resumeDeferred = createDeferredPromise();
1745
+ const runOnResumeHandler = () => __async(this, null, function* () {
1746
+ try {
1747
+ resumeDeferred.resolve(yield __privateMethod(this, _MWPTransport_instances, onResumeHandler_fn).call(this, options));
1748
+ } catch (err) {
1749
+ resumeDeferred.reject(err);
1750
+ }
1751
+ });
1752
+ if (this.dappClient.state === "CONNECTED") {
1753
+ runOnResumeHandler();
1754
+ } else {
1755
+ this.dappClient.once("connected", runOnResumeHandler);
1756
+ this.dappClient.resume((_a2 = session.id) != null ? _a2 : "").catch((err) => resumeDeferred.reject(err));
1757
+ }
1758
+ const timeoutDeferred = createDeferredPromise();
1759
+ const timeout = setTimeout(
1760
+ () => timeoutDeferred.reject(new TransportTimeoutError()),
1761
+ isContinuingPriorAttempt ? this.options.resumeTimeout : this.options.connectionTimeout
1762
+ );
1763
+ const cleanup = () => this.dappClient.off("connected", runOnResumeHandler);
1764
+ return Promise.race([
1765
+ resumeDeferred.promise,
1766
+ timeoutDeferred.promise
1767
+ ]).finally(() => {
1768
+ clearTimeout(timeout);
1769
+ cleanup();
1770
+ });
1771
+ });
1772
+ };
1773
+ startSession_fn = function(options) {
1774
+ return __async(this, null, function* () {
1775
+ var _a2, _b;
1776
+ const { dappClient } = this;
1777
+ const isContinuingPriorAttempt = (yield this.getStoredPendingSessionRequest()) !== null;
1778
+ const connDeferred = createDeferredPromise();
1779
+ const optionalScopes = addValidAccounts(
1780
+ getOptionalScopes((_a2 = options == null ? void 0 : options.scopes) != null ? _a2 : []),
1781
+ getValidAccounts((_b = options == null ? void 0 : options.caipAccountIds) != null ? _b : [])
1782
+ );
1783
+ const sessionRequest = {
1784
+ optionalScopes,
1785
+ sessionProperties: options == null ? void 0 : options.sessionProperties
1786
+ };
1787
+ const request = {
1788
+ jsonrpc: "2.0",
1789
+ id: String(getUniqueRequestId()),
1790
+ method: "wallet_createSession",
1791
+ params: sessionRequest
1792
+ };
1793
+ let handler;
1794
+ const removeHandler = () => {
1795
+ if (handler) {
1796
+ this.dappClient.off("message", handler);
1797
+ handler = void 0;
1798
+ }
1799
+ };
1800
+ handler = (message) => __async(this, null, function* () {
1801
+ if (typeof message !== "object" || message === null) {
1802
+ return;
1803
+ }
1804
+ if (!("data" in message)) {
1805
+ return;
1806
+ }
1807
+ const messagePayload = message.data;
1808
+ const isMatchingId = messagePayload.id === request.id;
1809
+ const isMatchingMethod = messagePayload.method === "wallet_createSession" || messagePayload.method === "wallet_sessionChanged";
1810
+ if (!isMatchingId && !isMatchingMethod) {
1811
+ return;
1812
+ }
1813
+ const responseError = this.getResponseError(messagePayload);
1814
+ if (responseError) {
1815
+ connDeferred.reject(this.parseWalletError(responseError));
1816
+ return;
1817
+ }
1818
+ yield this.storeWalletSession(
1819
+ request,
1820
+ messagePayload
1821
+ );
1822
+ yield this.removeStoredPendingSessionRequest();
1823
+ this.notifyCallbacks(messagePayload);
1824
+ connDeferred.resolve();
1825
+ });
1826
+ this.dappClient.on("message", handler);
1827
+ const platformType = getPlatformType();
1828
+ const isQRCodeFlow = [
1829
+ "web-desktop" /* DesktopWeb */,
1830
+ "nodejs" /* NonBrowser */
1831
+ ].includes(platformType);
1832
+ const initialPayload = {
1833
+ name: MULTICHAIN_PROVIDER_STREAM_NAME,
1834
+ data: request
1835
+ };
1836
+ dappClient.connect({
1837
+ mode: "trusted",
1838
+ initialPayload: isQRCodeFlow ? void 0 : initialPayload
1839
+ }).then(() => __async(this, null, function* () {
1840
+ if (isQRCodeFlow) {
1841
+ return dappClient.sendRequest(initialPayload);
1842
+ }
1843
+ return void 0;
1844
+ })).catch((error) => connDeferred.reject(error));
1845
+ const timeoutDeferred = createDeferredPromise();
1846
+ const timeout = setTimeout(
1847
+ () => timeoutDeferred.reject(new TransportTimeoutError()),
1848
+ isContinuingPriorAttempt ? this.options.resumeTimeout : this.options.connectionTimeout
1849
+ );
1850
+ return Promise.race([
1851
+ connDeferred.promise,
1852
+ timeoutDeferred.promise
1853
+ ]).finally(() => {
1854
+ clearTimeout(timeout);
1855
+ removeHandler();
1856
+ });
1857
+ });
1858
+ };
1812
1859
  }
1813
1860
  });
1814
1861
 
@@ -2118,6 +2165,7 @@ import { analytics as analytics2 } from "@metamask/analytics";
2118
2165
  import {
2119
2166
  getMultichainClient
2120
2167
  } from "@metamask/multichain-api-client";
2168
+ import { createDeferredPromise as createDeferredPromise2 } from "@metamask/utils";
2121
2169
 
2122
2170
  // src/config/index.ts
2123
2171
  var MWP_RELAY_URL = "wss://mm-sdk-relay.api.cx.metamask.io/connection/websocket";
@@ -2271,6 +2319,9 @@ var RequestRouter = class {
2271
2319
  invokeMethod(options) {
2272
2320
  return __async(this, null, function* () {
2273
2321
  const { method } = options.request;
2322
+ if (EIP1193_PASSTHROUGH_METHODS.has(method)) {
2323
+ return this.handleWithEip1193Passthrough(options);
2324
+ }
2274
2325
  if (RPC_HANDLED_METHODS.has(method)) {
2275
2326
  return this.handleWithRpcNode(options);
2276
2327
  }
@@ -2280,6 +2331,29 @@ var RequestRouter = class {
2280
2331
  return this.handleWithWallet(options);
2281
2332
  });
2282
2333
  }
2334
+ /**
2335
+ * Forwards EIP-1193 / legacy provider methods (e.g. `wallet_addEthereumChain`,
2336
+ * `wallet_switchEthereumChain`, `eth_accounts`) directly to the underlying
2337
+ * transport's `sendEip1193Message`, bypassing the multichain
2338
+ * `wallet_invokeMethod` envelope. These methods are wallet-side concerns the
2339
+ * Multichain API does not model, so we forward the raw `{ method, params }`
2340
+ * payload and return the wallet's full JSON-RPC response envelope unchanged.
2341
+ *
2342
+ * Analytics tracking is intentionally skipped here: ecosystem clients
2343
+ * (e.g. `connect-evm`) emit their own `wallet_action_*` events around these
2344
+ * passthrough calls, and adding router-level tracking would double-count.
2345
+ *
2346
+ * @param options
2347
+ */
2348
+ handleWithEip1193Passthrough(options) {
2349
+ return __async(this, null, function* () {
2350
+ const response = yield this.transport.sendEip1193Message({
2351
+ method: options.request.method,
2352
+ params: options.request.params
2353
+ });
2354
+ return response.result;
2355
+ });
2356
+ }
2283
2357
  /**
2284
2358
  * Forwards the request directly to the wallet via the transport.
2285
2359
  *
@@ -2311,14 +2385,6 @@ var RequestRouter = class {
2311
2385
  }), 10);
2312
2386
  }
2313
2387
  const response = yield request;
2314
- if (response.error) {
2315
- const { error } = response;
2316
- throw new RPCInvokeMethodErr(
2317
- `RPC Request failed with code ${error.code}: ${error.message}`,
2318
- error.code,
2319
- error.message
2320
- );
2321
- }
2322
2388
  return response.result;
2323
2389
  }));
2324
2390
  });
@@ -2433,7 +2499,7 @@ import {
2433
2499
  getDefaultTransport
2434
2500
  } from "@metamask/multichain-api-client";
2435
2501
  var DEFAULT_REQUEST_TIMEOUT = 60 * 1e3;
2436
- var _notificationCallbacks, _transport, _defaultRequestOptions, _pendingRequests, _handleResponseListener, _handleNotificationListener, _DefaultTransport_instances, notifyCallbacks_fn, isMetamaskProviderEvent_fn, handleResponse_fn, handleNotification_fn, setupMessageListener_fn, init_fn;
2502
+ var _notificationCallbacks, _transport, _defaultRequestOptions, _pendingRequests, _handleResponseListener, _handleNotificationListener, _DefaultTransport_instances, notifyCallbacks_fn, parseWalletError_fn, isMetamaskProviderEvent_fn, handleResponse_fn, handleNotification_fn, setupMessageListener_fn, init_fn;
2437
2503
  var DefaultTransport = class {
2438
2504
  constructor() {
2439
2505
  __privateAdd(this, _DefaultTransport_instances);
@@ -2569,7 +2635,11 @@ var DefaultTransport = class {
2569
2635
  }
2570
2636
  request(_0) {
2571
2637
  return __async(this, arguments, function* (request, options = __privateGet(this, _defaultRequestOptions)) {
2572
- return __privateGet(this, _transport).request(request, options);
2638
+ const response = yield __privateGet(this, _transport).request(request, options);
2639
+ if (response.error) {
2640
+ throw __privateMethod(this, _DefaultTransport_instances, parseWalletError_fn).call(this, response.error);
2641
+ }
2642
+ return response;
2573
2643
  });
2574
2644
  }
2575
2645
  onNotification(callback) {
@@ -2613,6 +2683,16 @@ notifyCallbacks_fn = function(data) {
2613
2683
  }
2614
2684
  }
2615
2685
  };
2686
+ parseWalletError_fn = function(errorPayload) {
2687
+ const errorData = errorPayload;
2688
+ const error = new Error(
2689
+ typeof errorData.message === "string" ? errorData.message : "Request failed"
2690
+ );
2691
+ if (typeof errorData.code === "number") {
2692
+ error.code = errorData.code;
2693
+ }
2694
+ return error;
2695
+ };
2616
2696
  isMetamaskProviderEvent_fn = function(event) {
2617
2697
  var _a2, _b;
2618
2698
  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
@@ -2635,13 +2715,7 @@ handleResponse_fn = function(event) {
2635
2715
  __privateGet(this, _pendingRequests).delete(responseId);
2636
2716
  const response = responseData;
2637
2717
  if ("error" in response && response.error) {
2638
- const error = new Error(
2639
- response.error.message || "Request failed"
2640
- );
2641
- if (typeof response.error.code === "number") {
2642
- error.code = response.error.code;
2643
- }
2644
- pendingRequest.reject(error);
2718
+ pendingRequest.reject(__privateMethod(this, _DefaultTransport_instances, parseWalletError_fn).call(this, response.error));
2645
2719
  } else {
2646
2720
  pendingRequest.resolve(response);
2647
2721
  }
@@ -2679,22 +2753,21 @@ init_fn = function() {
2679
2753
  // src/multichain/transports/multichainApiClientWrapper/index.ts
2680
2754
  init_utils();
2681
2755
  import { providerErrors } from "@metamask/rpc-errors";
2682
- var _notificationCallbacks2, _MultichainApiClientWrapperTransport_instances, walletCreateSession_fn, walletGetSession_fn, walletRevokeSession_fn, walletInvokeMethod_fn;
2756
+ var _notificationCallbacks2, _getTransport, _MultichainApiClientWrapperTransport_instances, walletCreateSession_fn, walletGetSession_fn, walletRevokeSession_fn, walletInvokeMethod_fn;
2683
2757
  var MultichainApiClientWrapperTransport = class {
2684
- constructor(metamaskConnectMultichain) {
2758
+ constructor(metamaskConnectMultichain, getTransport) {
2685
2759
  this.metamaskConnectMultichain = metamaskConnectMultichain;
2686
2760
  __privateAdd(this, _MultichainApiClientWrapperTransport_instances);
2687
2761
  __privateAdd(this, _notificationCallbacks2, /* @__PURE__ */ new Set());
2762
+ __privateAdd(this, _getTransport);
2763
+ __privateSet(this, _getTransport, getTransport);
2688
2764
  }
2689
2765
  isTransportDefined() {
2690
- try {
2691
- return Boolean(this.metamaskConnectMultichain.transport);
2692
- } catch (_error) {
2693
- return false;
2694
- }
2766
+ return __privateGet(this, _getTransport).call(this) !== void 0;
2695
2767
  }
2696
2768
  isTransportConnected() {
2697
- return this.isTransportDefined() && this.metamaskConnectMultichain.transport.isConnected();
2769
+ var _a2, _b;
2770
+ return (_b = (_a2 = __privateGet(this, _getTransport).call(this)) == null ? void 0 : _a2.isConnected()) != null ? _b : false;
2698
2771
  }
2699
2772
  clearNotificationCallbacks() {
2700
2773
  __privateGet(this, _notificationCallbacks2).clear();
@@ -2710,10 +2783,11 @@ var MultichainApiClientWrapperTransport = class {
2710
2783
  this.notificationListener = void 0;
2711
2784
  }
2712
2785
  setupTransportNotificationListener() {
2713
- if (!this.isTransportDefined() || this.notificationListener) {
2786
+ const transport = __privateGet(this, _getTransport).call(this);
2787
+ if (!transport || this.notificationListener) {
2714
2788
  return;
2715
2789
  }
2716
- this.notificationListener = this.metamaskConnectMultichain.transport.onNotification(
2790
+ this.notificationListener = transport.onNotification(
2717
2791
  this.notifyCallbacks.bind(this)
2718
2792
  );
2719
2793
  }
@@ -2763,6 +2837,7 @@ var MultichainApiClientWrapperTransport = class {
2763
2837
  }
2764
2838
  };
2765
2839
  _notificationCallbacks2 = new WeakMap();
2840
+ _getTransport = new WeakMap();
2766
2841
  _MultichainApiClientWrapperTransport_instances = new WeakSet();
2767
2842
  walletCreateSession_fn = function(request) {
2768
2843
  return __async(this, null, function* () {
@@ -2786,14 +2861,19 @@ walletCreateSession_fn = function(request) {
2786
2861
  accounts,
2787
2862
  createSessionParams.sessionProperties
2788
2863
  );
2789
- return this.metamaskConnectMultichain.transport.request({
2864
+ const transport = __privateGet(this, _getTransport).call(this);
2865
+ if (!transport) {
2866
+ throw new Error("Transport not initialized after connect");
2867
+ }
2868
+ return transport.request({
2790
2869
  method: "wallet_getSession"
2791
2870
  });
2792
2871
  });
2793
2872
  };
2794
2873
  walletGetSession_fn = function(request) {
2795
2874
  return __async(this, null, function* () {
2796
- if (!this.isTransportConnected()) {
2875
+ const transport = __privateGet(this, _getTransport).call(this);
2876
+ if (!(transport == null ? void 0 : transport.isConnected())) {
2797
2877
  return {
2798
2878
  jsonrpc: "2.0",
2799
2879
  id: request.id,
@@ -2802,7 +2882,7 @@ walletGetSession_fn = function(request) {
2802
2882
  }
2803
2883
  };
2804
2884
  }
2805
- return this.metamaskConnectMultichain.transport.request({
2885
+ return transport.request({
2806
2886
  method: "wallet_getSession"
2807
2887
  });
2808
2888
  });
@@ -2880,7 +2960,7 @@ function setupAnalyticsGlobals(options, storage, setAnonId) {
2880
2960
  analytics2.enable();
2881
2961
  });
2882
2962
  }
2883
- 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;
2963
+ 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;
2884
2964
  var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends MultichainCore {
2885
2965
  constructor(options) {
2886
2966
  var _a2, _b, _c, _d;
@@ -2893,9 +2973,7 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
2893
2973
  }),
2894
2974
  analytics: normalizeAnalyticsOptions(options.analytics),
2895
2975
  versions: __spreadValues({
2896
- // typeof guard needed: Metro (React Native) bundles TS source directly,
2897
- // bypassing the tsup build that substitutes __PACKAGE_VERSION__.
2898
- "connect-multichain": false ? "unknown" : "0.15.0"
2976
+ "connect-multichain": getVersion()
2899
2977
  }, (_d = options.versions) != null ? _d : {})
2900
2978
  });
2901
2979
  super(allOptions);
@@ -2911,7 +2989,8 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
2911
2989
  __privateAdd(this, _anonId);
2912
2990
  __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}`);
2913
2991
  __privateSet(this, _providerTransportWrapper, new MultichainApiClientWrapperTransport(
2914
- this
2992
+ this,
2993
+ () => __privateGet(this, _transport2)
2915
2994
  ));
2916
2995
  __privateSet(this, _provider, getMultichainClient({
2917
2996
  transport: __privateGet(this, _providerTransportWrapper)
@@ -2930,12 +3009,6 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
2930
3009
  get provider() {
2931
3010
  return __privateGet(this, _provider);
2932
3011
  }
2933
- get transport() {
2934
- if (!__privateGet(this, _transport2)) {
2935
- throw new Error("Transport not initialized, establish connection first");
2936
- }
2937
- return __privateGet(this, _transport2);
2938
- }
2939
3012
  get dappClient() {
2940
3013
  if (!__privateGet(this, _dappClient)) {
2941
3014
  throw new Error("DappClient not initialized, establish connection first");
@@ -2949,6 +3022,9 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
2949
3022
  get storage() {
2950
3023
  return this.options.storage;
2951
3024
  }
3025
+ get version() {
3026
+ return getVersion();
3027
+ }
2952
3028
  // Creates a singleton instance of MetaMaskConnectMultichain.
2953
3029
  // If the singleton already exists, it merges the incoming options with the
2954
3030
  // existing singleton options for the following keys: `api.supportedNetworks`,
@@ -2963,6 +3039,11 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
2963
3039
  const existing = globalObject[SINGLETON_KEY];
2964
3040
  if (existing) {
2965
3041
  const instance = yield existing;
3042
+ if (instance.version !== getVersion()) {
3043
+ console.warn(
3044
+ `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.`
3045
+ );
3046
+ }
2966
3047
  instance.mergeOptions(options);
2967
3048
  if (instance instanceof _MetaMaskConnectMultichain) {
2968
3049
  yield __privateMethod(_a2 = instance, _MetaMaskConnectMultichain_instances, setupAnalytics_fn).call(_a2);
@@ -2986,12 +3067,12 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
2986
3067
  }
2987
3068
  yield __privateMethod(_a3 = instance, _MetaMaskConnectMultichain_instances, init_fn2).call(_a3);
2988
3069
  return instance;
2989
- }))();
2990
- globalObject[SINGLETON_KEY] = instancePromise;
2991
- instancePromise.catch((error) => {
3070
+ }))().catch((error) => {
2992
3071
  globalObject[SINGLETON_KEY] = void 0;
2993
3072
  console.error("Error initializing MetaMaskConnectMultichain", error);
3073
+ throw error;
2994
3074
  });
3075
+ globalObject[SINGLETON_KEY] = instancePromise;
2995
3076
  return instancePromise;
2996
3077
  });
2997
3078
  }
@@ -3051,9 +3132,9 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
3051
3132
  forceRequest
3052
3133
  }).then(() => __async(this, null, function* () {
3053
3134
  if (__privateGet(this, _transportType) === "mwp" /* MWP */) {
3054
- return this.storage.setTransport("mwp" /* MWP */);
3135
+ return this.storage.setTransportType("mwp" /* MWP */);
3055
3136
  }
3056
- return this.storage.setTransport("browser" /* Browser */);
3137
+ return this.storage.setTransportType("browser" /* Browser */);
3057
3138
  })), scopes, transportType);
3058
3139
  }
3059
3140
  if (platformType === "in-app-browser" /* MetaMaskMobileWebview */) {
@@ -3082,11 +3163,6 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
3082
3163
  return __privateMethod(this, _MetaMaskConnectMultichain_instances, handleConnection_fn).call(this, __privateMethod(this, _MetaMaskConnectMultichain_instances, showInstallModal_fn).call(this, shouldShowInstallModal, mergedScopes, mergedCaipAccountIds, nonEmptySessionProperties), scopes, transportType);
3083
3164
  });
3084
3165
  }
3085
- emit(event, args) {
3086
- var _a2, _b;
3087
- (_b = (_a2 = this.options.transport) == null ? void 0 : _a2.onNotification) == null ? void 0 : _b.call(_a2, { method: event, params: args });
3088
- super.emit(event, args);
3089
- }
3090
3166
  disconnect() {
3091
3167
  return __async(this, arguments, function* (scopes = []) {
3092
3168
  var _a2, _b, _c;
@@ -3096,7 +3172,7 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
3096
3172
  );
3097
3173
  yield (_a2 = __privateGet(this, _transport2)) == null ? void 0 : _a2.disconnect(scopes);
3098
3174
  if (remainingScopes.length === 0) {
3099
- yield this.storage.removeTransport();
3175
+ yield this.storage.removeTransportType();
3100
3176
  if (__privateGet(this, _transportType) !== "browser" /* Browser */) {
3101
3177
  yield (_b = __privateGet(this, _listener)) == null ? void 0 : _b.call(this);
3102
3178
  (_c = __privateGet(this, _beforeUnloadListener)) == null ? void 0 : _c.call(this);
@@ -3114,7 +3190,8 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
3114
3190
  invokeMethod(request) {
3115
3191
  return __async(this, null, function* () {
3116
3192
  var _a2;
3117
- const { transport, options } = this;
3193
+ const transport = __privateMethod(this, _MetaMaskConnectMultichain_instances, transportOrThrow_fn).call(this);
3194
+ const { options } = this;
3118
3195
  const rpcClient = new RpcClient(options, __privateGet(this, _sdkInfo));
3119
3196
  const requestRouter = new RequestRouter(
3120
3197
  transport,
@@ -3133,7 +3210,7 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
3133
3210
  const shouldOpenDeeplink = secure && !showInstallModal;
3134
3211
  if (shouldOpenDeeplink) {
3135
3212
  setTimeout(() => __async(this, null, function* () {
3136
- const session = yield this.transport.getActiveSession();
3213
+ const session = yield __privateMethod(this, _MetaMaskConnectMultichain_instances, transportOrThrow_fn).call(this).getActiveSession();
3137
3214
  if (!session) {
3138
3215
  throw new Error("No active session found");
3139
3216
  }
@@ -3157,10 +3234,13 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
3157
3234
  this.emit("wallet_sessionChanged", emptySession);
3158
3235
  return;
3159
3236
  }
3160
- const response = yield this.transport.request({
3237
+ const response = yield __privateGet(this, _transport2).request({
3161
3238
  method: "wallet_getSession"
3162
3239
  });
3163
- this.emit("wallet_sessionChanged", (_b = response.result) != null ? _b : emptySession);
3240
+ this.emit(
3241
+ "wallet_sessionChanged",
3242
+ (_b = response.result) != null ? _b : emptySession
3243
+ );
3164
3244
  });
3165
3245
  }
3166
3246
  };
@@ -3172,8 +3252,14 @@ _beforeUnloadListener = new WeakMap();
3172
3252
  _transportType = new WeakMap();
3173
3253
  _listener = new WeakMap();
3174
3254
  _anonId = new WeakMap();
3175
- _sdkInfo = new WeakMap();
3176
3255
  _MetaMaskConnectMultichain_instances = new WeakSet();
3256
+ transportOrThrow_fn = function() {
3257
+ if (!__privateGet(this, _transport2)) {
3258
+ throw new Error("Transport not initialized, establish connection first");
3259
+ }
3260
+ return __privateGet(this, _transport2);
3261
+ };
3262
+ _sdkInfo = new WeakMap();
3177
3263
  setupAnalytics_fn = function() {
3178
3264
  return __async(this, null, function* () {
3179
3265
  yield setupAnalyticsGlobals(this.options, this.storage, (anonId) => {
@@ -3199,7 +3285,7 @@ onTransportNotification_fn = function(payload) {
3199
3285
  };
3200
3286
  getStoredTransport_fn = function() {
3201
3287
  return __async(this, null, function* () {
3202
- const transportType = yield this.storage.getTransport();
3288
+ const transportType = yield this.storage.getTransportType();
3203
3289
  const hasExtensionInstalled = yield hasExtension();
3204
3290
  if (transportType) {
3205
3291
  if (transportType === "browser" /* Browser */) {
@@ -3227,7 +3313,7 @@ getStoredTransport_fn = function() {
3227
3313
  ));
3228
3314
  return apiTransport;
3229
3315
  }
3230
- yield this.storage.removeTransport();
3316
+ yield this.storage.removeTransportType();
3231
3317
  }
3232
3318
  return void 0;
3233
3319
  });
@@ -3237,15 +3323,15 @@ setupTransport_fn = function() {
3237
3323
  var _a2;
3238
3324
  const transport = yield __privateMethod(this, _MetaMaskConnectMultichain_instances, getStoredTransport_fn).call(this);
3239
3325
  if (transport) {
3240
- if (!this.transport.isConnected()) {
3326
+ if (!transport.isConnected()) {
3241
3327
  this.status = "connecting";
3242
- yield this.transport.connect();
3328
+ yield transport.connect();
3243
3329
  }
3244
3330
  this.status = "connected";
3245
3331
  if (__privateGet(this, _transportType) === "mwp" /* MWP */) {
3246
- yield this.storage.setTransport("mwp" /* MWP */);
3332
+ yield this.storage.setTransportType("mwp" /* MWP */);
3247
3333
  } else {
3248
- yield this.storage.setTransport("browser" /* Browser */);
3334
+ yield this.storage.setTransportType("browser" /* Browser */);
3249
3335
  }
3250
3336
  } else {
3251
3337
  this.status = "loaded";
@@ -3254,7 +3340,7 @@ setupTransport_fn = function() {
3254
3340
  if (hasExtensionInstalled && preferExtension) {
3255
3341
  yield __privateMethod(this, _MetaMaskConnectMultichain_instances, setupDefaultTransport_fn).call(this, { persist: false });
3256
3342
  try {
3257
- yield this.transport.init();
3343
+ yield __privateMethod(this, _MetaMaskConnectMultichain_instances, transportOrThrow_fn).call(this).init();
3258
3344
  } catch (error) {
3259
3345
  console.error("Passive init failed:", error);
3260
3346
  }
@@ -3278,7 +3364,7 @@ init_fn2 = function() {
3278
3364
  yield __privateMethod(this, _MetaMaskConnectMultichain_instances, setupAnalytics_fn).call(this);
3279
3365
  yield __privateMethod(this, _MetaMaskConnectMultichain_instances, setupTransport_fn).call(this);
3280
3366
  } catch (error) {
3281
- yield this.storage.removeTransport();
3367
+ yield this.storage.removeTransportType();
3282
3368
  this.status = "pending";
3283
3369
  logger2("MetaMaskSDK error during initialization", error);
3284
3370
  }
@@ -3324,17 +3410,17 @@ setupMWP_fn = function() {
3324
3410
  __privateSet(this, _transport2, apiTransport);
3325
3411
  __privateSet(this, _transportType, "mwp" /* MWP */);
3326
3412
  __privateGet(this, _providerTransportWrapper).setupTransportNotificationListener();
3327
- __privateSet(this, _listener, this.transport.onNotification(
3413
+ __privateSet(this, _listener, apiTransport.onNotification(
3328
3414
  __privateMethod(this, _MetaMaskConnectMultichain_instances, onTransportNotification_fn).bind(this)
3329
3415
  ));
3330
- yield this.storage.setTransport("mwp" /* MWP */);
3416
+ yield this.storage.setTransportType("mwp" /* MWP */);
3331
3417
  });
3332
3418
  };
3333
3419
  onBeforeUnload_fn = function() {
3334
3420
  return __async(this, null, function* () {
3335
3421
  var _a2;
3336
3422
  if ((_a2 = this.options.ui.factory.modal) == null ? void 0 : _a2.isMounted) {
3337
- yield this.storage.removeTransport();
3423
+ yield this.storage.removeTransportType();
3338
3424
  }
3339
3425
  });
3340
3426
  };
@@ -3351,70 +3437,65 @@ createBeforeUnloadListener_fn = function() {
3351
3437
  };
3352
3438
  renderInstallModalAsync_fn = function(desktopPreferred, scopes, caipAccountIds, sessionProperties) {
3353
3439
  return __async(this, null, function* () {
3354
- return new Promise((resolve, reject) => {
3355
- this.options.ui.factory.renderInstallModal(
3356
- desktopPreferred,
3357
- () => __async(this, null, function* () {
3358
- if (this.dappClient.state === "CONNECTED" || this.dappClient.state === "CONNECTING") {
3359
- yield this.dappClient.disconnect();
3360
- }
3361
- return new Promise((_resolve) => {
3362
- this.dappClient.on(
3363
- "session_request",
3364
- (sessionRequest) => {
3365
- _resolve({
3366
- sessionRequest,
3367
- metadata: __privateMethod(this, _MetaMaskConnectMultichain_instances, buildConnectionMetadata_fn).call(this)
3368
- });
3369
- }
3370
- );
3371
- (() => __async(this, null, function* () {
3372
- var _a2;
3373
- try {
3374
- yield this.transport.connect({
3375
- scopes,
3376
- caipAccountIds,
3377
- sessionProperties
3378
- });
3379
- yield this.options.ui.factory.unload();
3380
- (_a2 = this.options.ui.factory.modal) == null ? void 0 : _a2.unmount();
3381
- this.status = "connected";
3382
- yield this.storage.setTransport("mwp" /* MWP */);
3383
- } catch (error) {
3384
- const { ProtocolError, ErrorCode } = yield import("@metamask/mobile-wallet-protocol-core");
3385
- if (error instanceof ProtocolError) {
3386
- if (error.code !== ErrorCode.REQUEST_EXPIRED) {
3387
- this.status = "disconnected";
3388
- yield this.options.ui.factory.unload(error);
3389
- reject(error);
3390
- }
3391
- } else {
3392
- this.status = "disconnected";
3393
- const normalizedError = error instanceof Error ? error : new Error(String(error));
3394
- yield this.options.ui.factory.unload(normalizedError);
3395
- reject(normalizedError);
3396
- }
3397
- }
3398
- }))().catch(() => {
3399
- });
3440
+ const completion = createDeferredPromise2();
3441
+ const createConnectionRequest = () => __async(this, null, function* () {
3442
+ if (this.dappClient.state === "CONNECTED" || this.dappClient.state === "CONNECTING") {
3443
+ yield this.dappClient.disconnect();
3444
+ }
3445
+ const sessionRequestDeferred = createDeferredPromise2();
3446
+ this.dappClient.on(
3447
+ "session_request",
3448
+ (sessionRequest) => {
3449
+ sessionRequestDeferred.resolve({
3450
+ sessionRequest,
3451
+ metadata: __privateMethod(this, _MetaMaskConnectMultichain_instances, buildConnectionMetadata_fn).call(this)
3400
3452
  });
3401
- }),
3402
- (error) => __async(this, null, function* () {
3403
- if (error) {
3404
- yield this.storage.removeTransport();
3405
- reject(error);
3406
- } else {
3407
- yield this.storage.setTransport("mwp" /* MWP */);
3408
- resolve();
3453
+ }
3454
+ );
3455
+ __privateMethod(this, _MetaMaskConnectMultichain_instances, transportOrThrow_fn).call(this).connect({ scopes, caipAccountIds, sessionProperties }).then(() => __async(this, null, function* () {
3456
+ var _a2;
3457
+ yield this.options.ui.factory.unload();
3458
+ (_a2 = this.options.ui.factory.modal) == null ? void 0 : _a2.unmount();
3459
+ this.status = "connected";
3460
+ yield this.storage.setTransportType("mwp" /* MWP */);
3461
+ })).catch((error) => __async(this, null, function* () {
3462
+ const { ProtocolError, ErrorCode } = yield import("@metamask/mobile-wallet-protocol-core");
3463
+ if (error instanceof ProtocolError) {
3464
+ if (error.code !== ErrorCode.REQUEST_EXPIRED) {
3465
+ this.status = "disconnected";
3466
+ yield this.options.ui.factory.unload(error);
3467
+ completion.reject(error);
3409
3468
  }
3410
- }),
3411
- (uri) => {
3412
- this.emit("display_uri", uri);
3469
+ } else {
3470
+ this.status = "disconnected";
3471
+ const normalizedError = error instanceof Error ? error : new Error(String(error));
3472
+ yield this.options.ui.factory.unload(normalizedError);
3473
+ completion.reject(normalizedError);
3413
3474
  }
3414
- ).catch((error) => {
3415
- reject(error instanceof Error ? error : new Error(String(error)));
3416
- });
3475
+ }));
3476
+ return sessionRequestDeferred.promise;
3417
3477
  });
3478
+ this.options.ui.factory.renderInstallModal(
3479
+ desktopPreferred,
3480
+ createConnectionRequest,
3481
+ (error) => __async(this, null, function* () {
3482
+ if (error) {
3483
+ yield this.storage.removeTransportType();
3484
+ completion.reject(error);
3485
+ } else {
3486
+ yield this.storage.setTransportType("mwp" /* MWP */);
3487
+ completion.resolve();
3488
+ }
3489
+ }),
3490
+ (uri) => {
3491
+ this.emit("display_uri", uri);
3492
+ }
3493
+ ).catch((error) => {
3494
+ completion.reject(
3495
+ error instanceof Error ? error : new Error(String(error))
3496
+ );
3497
+ });
3498
+ return completion.promise;
3418
3499
  });
3419
3500
  };
3420
3501
  showInstallModal_fn = function(desktopPreferred, scopes, caipAccountIds, sessionProperties) {
@@ -3430,39 +3511,37 @@ showInstallModal_fn = function(desktopPreferred, scopes, caipAccountIds, session
3430
3511
  };
3431
3512
  headlessConnect_fn = function(scopes, caipAccountIds, sessionProperties) {
3432
3513
  return __async(this, null, function* () {
3433
- return new Promise((resolve, reject) => {
3434
- if (this.dappClient.state === "CONNECTED" || this.dappClient.state === "CONNECTING") {
3435
- this.dappClient.disconnect().catch(() => {
3436
- });
3514
+ if (this.dappClient.state === "CONNECTED" || this.dappClient.state === "CONNECTING") {
3515
+ yield this.dappClient.disconnect().catch(() => void 0);
3516
+ }
3517
+ const onSessionRequest = (sessionRequest) => {
3518
+ const connectionRequest = {
3519
+ sessionRequest,
3520
+ metadata: __privateMethod(this, _MetaMaskConnectMultichain_instances, buildConnectionMetadata_fn).call(this)
3521
+ };
3522
+ const deeplink = this.options.ui.factory.createConnectionDeeplink(connectionRequest);
3523
+ this.emit("display_uri", deeplink);
3524
+ };
3525
+ this.dappClient.on("session_request", onSessionRequest);
3526
+ try {
3527
+ yield __privateMethod(this, _MetaMaskConnectMultichain_instances, transportOrThrow_fn).call(this).connect({
3528
+ scopes,
3529
+ caipAccountIds,
3530
+ sessionProperties
3531
+ });
3532
+ this.status = "connected";
3533
+ yield this.storage.setTransportType("mwp" /* MWP */);
3534
+ } catch (error) {
3535
+ const { ProtocolError } = yield import("@metamask/mobile-wallet-protocol-core");
3536
+ this.status = "disconnected";
3537
+ yield this.storage.removeTransportType();
3538
+ if (error instanceof ProtocolError || error instanceof Error) {
3539
+ throw error;
3437
3540
  }
3438
- this.dappClient.on(
3439
- "session_request",
3440
- (sessionRequest) => {
3441
- const connectionRequest = {
3442
- sessionRequest,
3443
- metadata: __privateMethod(this, _MetaMaskConnectMultichain_instances, buildConnectionMetadata_fn).call(this)
3444
- };
3445
- const deeplink = this.options.ui.factory.createConnectionDeeplink(connectionRequest);
3446
- this.emit("display_uri", deeplink);
3447
- }
3448
- );
3449
- this.transport.connect({ scopes, caipAccountIds, sessionProperties }).then(() => __async(this, null, function* () {
3450
- this.status = "connected";
3451
- yield this.storage.setTransport("mwp" /* MWP */);
3452
- resolve();
3453
- })).catch((error) => __async(this, null, function* () {
3454
- const { ProtocolError } = yield import("@metamask/mobile-wallet-protocol-core");
3455
- if (error instanceof ProtocolError) {
3456
- this.status = "disconnected";
3457
- yield this.storage.removeTransport();
3458
- reject(error);
3459
- } else {
3460
- this.status = "disconnected";
3461
- yield this.storage.removeTransport();
3462
- reject(error instanceof Error ? error : new Error(String(error)));
3463
- }
3464
- }));
3465
- });
3541
+ throw new Error(String(error));
3542
+ } finally {
3543
+ this.dappClient.off("session_request", onSessionRequest);
3544
+ }
3466
3545
  });
3467
3546
  };
3468
3547
  setupDefaultTransport_fn = function() {
@@ -3471,7 +3550,7 @@ setupDefaultTransport_fn = function() {
3471
3550
  return __privateGet(this, _transport2);
3472
3551
  }
3473
3552
  if (options == null ? void 0 : options.persist) {
3474
- yield this.storage.setTransport("browser" /* Browser */);
3553
+ yield this.storage.setTransportType("browser" /* Browser */);
3475
3554
  }
3476
3555
  const transport = new DefaultTransport();
3477
3556
  __privateSet(this, _listener, transport.onNotification(
@@ -3504,7 +3583,7 @@ deeplinkConnect_fn = function(scopes, caipAccountIds, sessionProperties) {
3504
3583
  };
3505
3584
  this.dappClient.on("message", dappClientMessageHandler);
3506
3585
  let timeout;
3507
- if (this.transport.isConnected()) {
3586
+ if (__privateMethod(this, _MetaMaskConnectMultichain_instances, transportOrThrow_fn).call(this).isConnected()) {
3508
3587
  timeout = setTimeout(() => {
3509
3588
  this.openSimpleDeeplinkIfNeeded();
3510
3589
  }, 250);
@@ -3532,8 +3611,8 @@ deeplinkConnect_fn = function(scopes, caipAccountIds, sessionProperties) {
3532
3611
  }
3533
3612
  );
3534
3613
  }
3535
- return this.transport.connect({ scopes, caipAccountIds, sessionProperties }).then(resolve).catch((error) => __async(this, null, function* () {
3536
- yield this.storage.removeTransport();
3614
+ return __privateMethod(this, _MetaMaskConnectMultichain_instances, transportOrThrow_fn).call(this).connect({ scopes, caipAccountIds, sessionProperties }).then(resolve).catch((error) => __async(this, null, function* () {
3615
+ yield this.storage.removeTransportType();
3537
3616
  this.dappClient.off("message", dappClientMessageHandler);
3538
3617
  reject(error instanceof Error ? error : new Error(String(error)));
3539
3618
  })).finally(() => {
@@ -3599,7 +3678,7 @@ getCaipSession_fn = function() {
3599
3678
  };
3600
3679
  if ((_a2 = __privateGet(this, _transport2)) == null ? void 0 : _a2.isConnected()) {
3601
3680
  try {
3602
- const response = yield this.transport.request({
3681
+ const response = yield __privateGet(this, _transport2).request({
3603
3682
  method: "wallet_getSession"
3604
3683
  });
3605
3684
  if (response.result) {
@@ -3693,14 +3772,14 @@ var Store = class extends StoreClient {
3693
3772
  super();
3694
3773
  this.adapter = adapter;
3695
3774
  }
3696
- getTransport() {
3775
+ getTransportType() {
3697
3776
  return __async(this, null, function* () {
3698
3777
  try {
3699
- const transport = yield this.adapter.get("multichain-transport");
3700
- if (!transport) {
3778
+ const transportType = yield this.adapter.get("multichain-transport");
3779
+ if (!transportType) {
3701
3780
  return null;
3702
3781
  }
3703
- return getTransportType(transport);
3782
+ return getTransportType(transportType);
3704
3783
  } catch (err) {
3705
3784
  throw new StorageGetErr(
3706
3785
  this.adapter.platform,
@@ -3710,10 +3789,10 @@ var Store = class extends StoreClient {
3710
3789
  }
3711
3790
  });
3712
3791
  }
3713
- setTransport(transport) {
3792
+ setTransportType(transportType) {
3714
3793
  return __async(this, null, function* () {
3715
3794
  try {
3716
- yield this.adapter.set("multichain-transport", transport);
3795
+ yield this.adapter.set("multichain-transport", transportType);
3717
3796
  } catch (err) {
3718
3797
  throw new StorageSetErr(
3719
3798
  this.adapter.platform,
@@ -3723,7 +3802,7 @@ var Store = class extends StoreClient {
3723
3802
  }
3724
3803
  });
3725
3804
  }
3726
- removeTransport() {
3805
+ removeTransportType() {
3727
3806
  return __async(this, null, function* () {
3728
3807
  try {
3729
3808
  yield this.adapter.delete("multichain-transport");
@@ -3937,7 +4016,11 @@ var BaseModalFactory = class {
3937
4016
  (_a3 = this.displayUriCallback) == null ? void 0 : _a3.call(this, newLink);
3938
4017
  return newLink;
3939
4018
  }),
3940
- onClose: this.onCloseModal.bind(this),
4019
+ onClose: (shouldTerminate) => {
4020
+ this.onCloseModal(shouldTerminate).catch((error) => {
4021
+ console.error("Failed to close modal:", error);
4022
+ });
4023
+ },
3941
4024
  startDesktopOnboarding: this.onStartDesktopOnboarding.bind(this),
3942
4025
  createConnectionRequest,
3943
4026
  onDisplayUri: this.displayUriCallback
@@ -3975,7 +4058,7 @@ function preload() {
3975
4058
  }
3976
4059
  try {
3977
4060
  const { defineCustomElements } = yield import("@metamask/multichain-ui/loader");
3978
- yield defineCustomElements();
4061
+ defineCustomElements();
3979
4062
  } catch (error) {
3980
4063
  console.error("Failed to load customElements:", error);
3981
4064
  }
@@ -4013,6 +4096,7 @@ var createMultichainClient = (options) => __async(null, null, function* () {
4013
4096
  }));
4014
4097
  });
4015
4098
  export {
4099
+ EIP1193_PASSTHROUGH_METHODS,
4016
4100
  EventEmitter,
4017
4101
  Modal,
4018
4102
  MultichainCore,
@@ -4040,6 +4124,7 @@ export {
4040
4124
  isEnabled,
4041
4125
  isMetamaskExtensionInstalled,
4042
4126
  isRejectionError,
4043
- isSecure
4127
+ isSecure,
4128
+ packageVersion
4044
4129
  };
4045
4130
  //# sourceMappingURL=connect-multichain.mjs.map