@metamask/connect-multichain 0.15.0 → 1.1.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 (84) hide show
  1. package/CHANGELOG.md +36 -1
  2. package/README.md +0 -1
  3. package/dist/browser/es/connect-multichain.d.mts +18 -8
  4. package/dist/browser/es/connect-multichain.mjs +558 -378
  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 +18 -8
  8. package/dist/browser/iife/connect-multichain.js +571 -378
  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 +18 -8
  12. package/dist/browser/umd/connect-multichain.js +558 -378
  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 +18 -8
  16. package/dist/node/cjs/connect-multichain.js +560 -376
  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 +18 -8
  20. package/dist/node/es/connect-multichain.mjs +557 -375
  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 +18 -8
  24. package/dist/react-native/es/connect-multichain.mjs +556 -374
  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/errors/rpc.d.ts +11 -1
  28. package/dist/src/domain/errors/rpc.d.ts.map +1 -1
  29. package/dist/src/domain/errors/rpc.js +10 -2
  30. package/dist/src/domain/errors/rpc.js.map +1 -1
  31. package/dist/src/domain/multichain/api/constants.d.ts +1 -0
  32. package/dist/src/domain/multichain/api/constants.d.ts.map +1 -1
  33. package/dist/src/domain/multichain/api/constants.js +13 -0
  34. package/dist/src/domain/multichain/api/constants.js.map +1 -1
  35. package/dist/src/domain/multichain/index.d.ts +2 -2
  36. package/dist/src/domain/multichain/index.d.ts.map +1 -1
  37. package/dist/src/domain/multichain/index.js.map +1 -1
  38. package/dist/src/domain/multichain/types.d.ts +0 -1
  39. package/dist/src/domain/multichain/types.d.ts.map +1 -1
  40. package/dist/src/domain/platform/index.d.ts.map +1 -1
  41. package/dist/src/domain/platform/index.js +27 -5
  42. package/dist/src/domain/platform/index.js.map +1 -1
  43. package/dist/src/domain/store/client.d.ts +3 -3
  44. package/dist/src/domain/store/client.d.ts.map +1 -1
  45. package/dist/src/domain/utils/index.d.ts +1 -0
  46. package/dist/src/domain/utils/index.d.ts.map +1 -1
  47. package/dist/src/domain/utils/index.js +5 -1
  48. package/dist/src/domain/utils/index.js.map +1 -1
  49. package/dist/src/multichain/index.d.ts +2 -3
  50. package/dist/src/multichain/index.d.ts.map +1 -1
  51. package/dist/src/multichain/index.js +142 -147
  52. package/dist/src/multichain/index.js.map +1 -1
  53. package/dist/src/multichain/rpc/invocationError.d.ts +9 -0
  54. package/dist/src/multichain/rpc/invocationError.d.ts.map +1 -0
  55. package/dist/src/multichain/rpc/invocationError.js +99 -0
  56. package/dist/src/multichain/rpc/invocationError.js.map +1 -0
  57. package/dist/src/multichain/rpc/requestRouter.d.ts +15 -0
  58. package/dist/src/multichain/rpc/requestRouter.d.ts.map +1 -1
  59. package/dist/src/multichain/rpc/requestRouter.js +38 -20
  60. package/dist/src/multichain/rpc/requestRouter.js.map +1 -1
  61. package/dist/src/multichain/transports/default/index.d.ts.map +1 -1
  62. package/dist/src/multichain/transports/default/index.js +25 -10
  63. package/dist/src/multichain/transports/default/index.js.map +1 -1
  64. package/dist/src/multichain/transports/multichainApiClientWrapper/index.d.ts +2 -1
  65. package/dist/src/multichain/transports/multichainApiClientWrapper/index.d.ts.map +1 -1
  66. package/dist/src/multichain/transports/multichainApiClientWrapper/index.js +25 -17
  67. package/dist/src/multichain/transports/multichainApiClientWrapper/index.js.map +1 -1
  68. package/dist/src/multichain/transports/mwp/index.d.ts +3 -1
  69. package/dist/src/multichain/transports/mwp/index.d.ts.map +1 -1
  70. package/dist/src/multichain/transports/mwp/index.js +235 -172
  71. package/dist/src/multichain/transports/mwp/index.js.map +1 -1
  72. package/dist/src/store/index.d.ts +3 -3
  73. package/dist/src/store/index.d.ts.map +1 -1
  74. package/dist/src/store/index.js +8 -8
  75. package/dist/src/store/index.js.map +1 -1
  76. package/dist/src/ui/ModalFactory.d.ts.map +1 -1
  77. package/dist/src/ui/ModalFactory.js +5 -1
  78. package/dist/src/ui/ModalFactory.js.map +1 -1
  79. package/dist/src/ui/index.js +1 -1
  80. package/dist/src/ui/index.js.map +1 -1
  81. package/dist/src/ui/modals/web/install.d.ts.map +1 -1
  82. package/dist/src/ui/modals/web/install.js.map +1 -1
  83. package/dist/types/connect-multichain.d.ts +18 -8
  84. package/package.json +2 -2
@@ -133,7 +133,15 @@ var init_rpc = __esm({
133
133
  _RPCReadonlyRequestErr.code = 52;
134
134
  RPCReadonlyRequestErr = _RPCReadonlyRequestErr;
135
135
  _RPCInvokeMethodErr = class _RPCInvokeMethodErr extends BaseErr {
136
- constructor(reason, rpcCode, rpcMessage) {
136
+ /**
137
+ * @param reason - MetaMask Connect invokeMethod reason.
138
+ * @param rpcCode - Original wallet JSON-RPC / EIP-1193 error code.
139
+ * @param rpcMessage - Original provider-facing wallet message, sourced only
140
+ * from the wallet's coded error. Unset when the wallet provides no message,
141
+ * so it may differ from `reason`, which can fall back through the cause chain.
142
+ * @param rpcData - Original JSON-RPC error data, when provided by the wallet.
143
+ */
144
+ constructor(reason, rpcCode, rpcMessage, rpcData) {
137
145
  super(
138
146
  `RPCErr${_RPCInvokeMethodErr.code}: RPC Client invoke method reason (${reason})`,
139
147
  _RPCInvokeMethodErr.code
@@ -141,6 +149,7 @@ var init_rpc = __esm({
141
149
  this.reason = reason;
142
150
  this.rpcCode = rpcCode;
143
151
  this.rpcMessage = rpcMessage;
152
+ this.rpcData = rpcData;
144
153
  }
145
154
  };
146
155
  _RPCInvokeMethodErr.code = 53;
@@ -273,7 +282,7 @@ var init_logger = __esm({
273
282
  });
274
283
 
275
284
  // src/domain/multichain/api/constants.ts
276
- var infuraRpcUrls, RPC_HANDLED_METHODS, SDK_HANDLED_METHODS;
285
+ var infuraRpcUrls, RPC_HANDLED_METHODS, SDK_HANDLED_METHODS, EIP1193_PASSTHROUGH_METHODS;
277
286
  var init_constants = __esm({
278
287
  "src/domain/multichain/api/constants.ts"() {
279
288
  "use strict";
@@ -438,6 +447,11 @@ var init_constants = __esm({
438
447
  "eth_uninstallFilter"
439
448
  ]);
440
449
  SDK_HANDLED_METHODS = /* @__PURE__ */ new Set(["eth_accounts", "eth_chainId"]);
450
+ EIP1193_PASSTHROUGH_METHODS = /* @__PURE__ */ new Set([
451
+ "wallet_addEthereumChain",
452
+ "wallet_switchEthereumChain",
453
+ "eth_accounts"
454
+ ]);
441
455
  }
442
456
  });
443
457
 
@@ -587,7 +601,7 @@ function hasExtension() {
587
601
  return detectionPromise;
588
602
  });
589
603
  }
590
- var import_bowser, PlatformType, detectionPromise;
604
+ var import_bowser, PlatformType, NATIVE_METAMASK_EIP6963_RDNS, detectionPromise;
591
605
  var init_platform = __esm({
592
606
  "src/domain/platform/index.ts"() {
593
607
  "use strict";
@@ -600,6 +614,10 @@ var init_platform = __esm({
600
614
  PlatformType2["ReactNative"] = "react-native";
601
615
  return PlatformType2;
602
616
  })(PlatformType || {});
617
+ NATIVE_METAMASK_EIP6963_RDNS = /* @__PURE__ */ new Set([
618
+ "io.metamask",
619
+ "io.metamask.mobile"
620
+ ]);
603
621
  detectionPromise = (() => __async(null, null, function* () {
604
622
  const pt = getPlatformType();
605
623
  if (pt === "nodejs" /* NonBrowser */ || pt === "react-native" /* ReactNative */) {
@@ -607,23 +625,30 @@ var init_platform = __esm({
607
625
  }
608
626
  return new Promise((resolve) => {
609
627
  const providers = [];
628
+ const targetWindow = window;
610
629
  const handler = (event) => {
611
630
  var _a2, _b;
612
631
  if ((_b = (_a2 = event == null ? void 0 : event.detail) == null ? void 0 : _a2.info) == null ? void 0 : _b.rdns) {
613
632
  providers.push(event.detail);
614
633
  }
615
634
  };
616
- window.addEventListener("eip6963:announceProvider", handler);
617
- window.dispatchEvent(new Event("eip6963:requestProvider"));
635
+ targetWindow.addEventListener("eip6963:announceProvider", handler);
636
+ targetWindow.dispatchEvent(new Event("eip6963:requestProvider"));
618
637
  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");
638
+ try {
639
+ if (typeof (targetWindow == null ? void 0 : targetWindow.removeEventListener) === "function") {
640
+ targetWindow.removeEventListener("eip6963:announceProvider", handler);
624
641
  }
625
- );
626
- resolve(hasMetaMask);
642
+ const hasMetaMask = providers.some(
643
+ (provider) => {
644
+ var _a2;
645
+ return typeof ((_a2 = provider == null ? void 0 : provider.info) == null ? void 0 : _a2.rdns) === "string" && NATIVE_METAMASK_EIP6963_RDNS.has(provider.info.rdns);
646
+ }
647
+ );
648
+ resolve(hasMetaMask);
649
+ } catch (e) {
650
+ resolve(false);
651
+ }
627
652
  }, 300);
628
653
  });
629
654
  }))();
@@ -1135,12 +1160,14 @@ var init_analytics = __esm({
1135
1160
 
1136
1161
  // src/domain/utils/index.ts
1137
1162
  function getVersion() {
1138
- return "0.0.0";
1163
+ return packageVersion;
1139
1164
  }
1165
+ var packageVersion;
1140
1166
  var init_utils2 = __esm({
1141
1167
  "src/domain/utils/index.ts"() {
1142
1168
  "use strict";
1143
1169
  init_analytics();
1170
+ packageVersion = false ? "unknown" : "1.1.0";
1144
1171
  }
1145
1172
  });
1146
1173
 
@@ -1173,12 +1200,13 @@ var mwp_exports = {};
1173
1200
  __export(mwp_exports, {
1174
1201
  MWPTransport: () => MWPTransport
1175
1202
  });
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;
1203
+ var import_multichain_api_client2, import_rpc_errors2, import_utils7, 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
1204
  var init_mwp = __esm({
1178
1205
  "src/multichain/transports/mwp/index.ts"() {
1179
1206
  "use strict";
1180
1207
  import_multichain_api_client2 = require("@metamask/multichain-api-client");
1181
1208
  import_rpc_errors2 = require("@metamask/rpc-errors");
1209
+ import_utils7 = require("@metamask/utils");
1182
1210
  init_domain();
1183
1211
  init_utils();
1184
1212
  init_constants2();
@@ -1209,6 +1237,7 @@ var init_mwp = __esm({
1209
1237
  this.dappClient = dappClient;
1210
1238
  this.kvstore = kvstore;
1211
1239
  this.options = options;
1240
+ __privateAdd(this, _MWPTransport_instances);
1212
1241
  this.__pendingRequests = /* @__PURE__ */ new Map();
1213
1242
  this.notificationCallbacks = /* @__PURE__ */ new Set();
1214
1243
  this.dappClient.on("message", this.handleMessage.bind(this));
@@ -1280,14 +1309,33 @@ var init_mwp = __esm({
1280
1309
  const errorData = errorPayload;
1281
1310
  if (typeof errorData.code === "number" && typeof errorData.message === "string") {
1282
1311
  const { code, message: message2 } = errorData;
1312
+ const rawData = errorData.data;
1313
+ const data = (0, import_utils7.isValidJson)(rawData) ? rawData : void 0;
1283
1314
  if (code >= 1e3 && code <= 4999) {
1284
- return import_rpc_errors2.providerErrors.custom({ code, message: message2 });
1315
+ return import_rpc_errors2.providerErrors.custom({ code, message: message2, data });
1285
1316
  }
1286
- return new import_rpc_errors2.JsonRpcError(code, message2);
1317
+ return new import_rpc_errors2.JsonRpcError(code, message2, data);
1287
1318
  }
1288
1319
  const message = errorPayload instanceof Error ? errorPayload.message : JSON.stringify(errorPayload);
1289
1320
  return import_rpc_errors2.rpcErrors.internal({ message });
1290
1321
  }
1322
+ getResponseError(messagePayload) {
1323
+ if ("error" in messagePayload && messagePayload.error) {
1324
+ return messagePayload.error;
1325
+ }
1326
+ const { result } = messagePayload;
1327
+ if (typeof result === "object" && result !== null && "error" in result && result.error && this.isErrorPayload(result.error)) {
1328
+ return result.error;
1329
+ }
1330
+ return void 0;
1331
+ }
1332
+ isErrorPayload(errorPayload) {
1333
+ if (errorPayload instanceof Error) {
1334
+ return true;
1335
+ }
1336
+ const errorData = errorPayload;
1337
+ return typeof (errorData == null ? void 0 : errorData.code) === "number" && typeof (errorData == null ? void 0 : errorData.message) === "string";
1338
+ }
1291
1339
  handleMessage(message) {
1292
1340
  if (typeof message === "object" && message !== null) {
1293
1341
  if ("data" in message) {
@@ -1296,9 +1344,10 @@ var init_mwp = __esm({
1296
1344
  const request = this.pendingRequests.get(messagePayload.id);
1297
1345
  if (request) {
1298
1346
  clearTimeout(request.timeout);
1299
- if ("error" in messagePayload && messagePayload.error) {
1347
+ const responseError = this.getResponseError(messagePayload);
1348
+ if (responseError) {
1300
1349
  this.pendingRequests.delete(messagePayload.id);
1301
- request.reject(this.parseWalletError(messagePayload.error));
1350
+ request.reject(this.parseWalletError(responseError));
1302
1351
  return;
1303
1352
  }
1304
1353
  const requestWithName = __spreadProps(__spreadValues({}, messagePayload), {
@@ -1341,73 +1390,6 @@ var init_mwp = __esm({
1341
1390
  }
1342
1391
  }
1343
1392
  }
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
1393
  init() {
1412
1394
  return __async(this, null, function* () {
1413
1395
  });
@@ -1448,7 +1430,6 @@ var init_mwp = __esm({
1448
1430
  }
1449
1431
  connect(options) {
1450
1432
  return __async(this, null, function* () {
1451
- const { dappClient } = this;
1452
1433
  const session = yield this.getActiveSession();
1453
1434
  if (session) {
1454
1435
  logger("active session found", {
@@ -1457,116 +1438,11 @@ var init_mwp = __esm({
1457
1438
  expiresAt: session.expiresAt
1458
1439
  });
1459
1440
  }
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* () {
1441
+ const connection = session ? __privateMethod(this, _MWPTransport_instances, resumeSession_fn).call(this, session, options) : __privateMethod(this, _MWPTransport_instances, startSession_fn).call(this, options);
1442
+ return connection.catch((error) => __async(this, null, function* () {
1560
1443
  yield this.dappClient.disconnect();
1561
1444
  throw error;
1562
1445
  })).finally(() => {
1563
- if (timeout) {
1564
- clearTimeout(timeout);
1565
- }
1566
- if (initialConnectionMessageHandler) {
1567
- this.dappClient.off("message", initialConnectionMessageHandler);
1568
- initialConnectionMessageHandler = void 0;
1569
- }
1570
1446
  this.removeStoredPendingSessionRequest();
1571
1447
  });
1572
1448
  });
@@ -1825,6 +1701,188 @@ var init_mwp = __esm({
1825
1701
  });
1826
1702
  }
1827
1703
  };
1704
+ _MWPTransport_instances = new WeakSet();
1705
+ onResumeHandler_fn = function(options) {
1706
+ return __async(this, null, function* () {
1707
+ var _a2, _b, _c, _d, _e, _f, _g;
1708
+ yield this.waitForWalletSessionIfNotCached();
1709
+ const sessionResponse = yield this.request({ method: "wallet_getSession" });
1710
+ if (sessionResponse.error) {
1711
+ throw new Error(sessionResponse.error.message);
1712
+ }
1713
+ let walletSession = sessionResponse.result;
1714
+ if (walletSession && options) {
1715
+ const currentScopes = Object.keys(
1716
+ (_a2 = walletSession == null ? void 0 : walletSession.sessionScopes) != null ? _a2 : {}
1717
+ );
1718
+ const proposedScopes = (_b = options == null ? void 0 : options.scopes) != null ? _b : [];
1719
+ const proposedCaipAccountIds = (_c = options == null ? void 0 : options.caipAccountIds) != null ? _c : [];
1720
+ const hasSameScopesAndAccounts = isSameScopesAndAccounts(
1721
+ currentScopes,
1722
+ proposedScopes,
1723
+ walletSession,
1724
+ proposedCaipAccountIds
1725
+ );
1726
+ if (options.forceRequest || !hasSameScopesAndAccounts) {
1727
+ const optionalScopes = addValidAccounts(
1728
+ getOptionalScopes((_d = options == null ? void 0 : options.scopes) != null ? _d : []),
1729
+ getValidAccounts((_e = options == null ? void 0 : options.caipAccountIds) != null ? _e : [])
1730
+ );
1731
+ const sessionRequest = {
1732
+ optionalScopes
1733
+ };
1734
+ const response = yield this.request({
1735
+ method: "wallet_createSession",
1736
+ params: sessionRequest
1737
+ });
1738
+ if (response.error) {
1739
+ throw new Error(response.error.message);
1740
+ }
1741
+ walletSession = response.result;
1742
+ }
1743
+ } else if (!walletSession) {
1744
+ const optionalScopes = addValidAccounts(
1745
+ getOptionalScopes((_f = options == null ? void 0 : options.scopes) != null ? _f : []),
1746
+ getValidAccounts((_g = options == null ? void 0 : options.caipAccountIds) != null ? _g : [])
1747
+ );
1748
+ const sessionRequest = {
1749
+ optionalScopes
1750
+ };
1751
+ const response = yield this.request({
1752
+ method: "wallet_createSession",
1753
+ params: sessionRequest
1754
+ });
1755
+ if (response.error) {
1756
+ throw new Error(response.error.message);
1757
+ }
1758
+ walletSession = response.result;
1759
+ }
1760
+ yield this.removeStoredPendingSessionRequest();
1761
+ this.notifyCallbacks({
1762
+ method: "wallet_sessionChanged",
1763
+ params: walletSession
1764
+ });
1765
+ });
1766
+ };
1767
+ resumeSession_fn = function(session, options) {
1768
+ return __async(this, null, function* () {
1769
+ var _a2;
1770
+ const isContinuingPriorAttempt = (yield this.getStoredPendingSessionRequest()) !== null;
1771
+ const resumeDeferred = (0, import_utils7.createDeferredPromise)();
1772
+ const runOnResumeHandler = () => __async(this, null, function* () {
1773
+ try {
1774
+ resumeDeferred.resolve(yield __privateMethod(this, _MWPTransport_instances, onResumeHandler_fn).call(this, options));
1775
+ } catch (err) {
1776
+ resumeDeferred.reject(err);
1777
+ }
1778
+ });
1779
+ if (this.dappClient.state === "CONNECTED") {
1780
+ runOnResumeHandler();
1781
+ } else {
1782
+ this.dappClient.once("connected", runOnResumeHandler);
1783
+ this.dappClient.resume((_a2 = session.id) != null ? _a2 : "").catch((err) => resumeDeferred.reject(err));
1784
+ }
1785
+ const timeoutDeferred = (0, import_utils7.createDeferredPromise)();
1786
+ const timeout = setTimeout(
1787
+ () => timeoutDeferred.reject(new import_multichain_api_client2.TransportTimeoutError()),
1788
+ isContinuingPriorAttempt ? this.options.resumeTimeout : this.options.connectionTimeout
1789
+ );
1790
+ const cleanup = () => this.dappClient.off("connected", runOnResumeHandler);
1791
+ return Promise.race([
1792
+ resumeDeferred.promise,
1793
+ timeoutDeferred.promise
1794
+ ]).finally(() => {
1795
+ clearTimeout(timeout);
1796
+ cleanup();
1797
+ });
1798
+ });
1799
+ };
1800
+ startSession_fn = function(options) {
1801
+ return __async(this, null, function* () {
1802
+ var _a2, _b;
1803
+ const { dappClient } = this;
1804
+ const isContinuingPriorAttempt = (yield this.getStoredPendingSessionRequest()) !== null;
1805
+ const connDeferred = (0, import_utils7.createDeferredPromise)();
1806
+ const optionalScopes = addValidAccounts(
1807
+ getOptionalScopes((_a2 = options == null ? void 0 : options.scopes) != null ? _a2 : []),
1808
+ getValidAccounts((_b = options == null ? void 0 : options.caipAccountIds) != null ? _b : [])
1809
+ );
1810
+ const sessionRequest = {
1811
+ optionalScopes,
1812
+ sessionProperties: options == null ? void 0 : options.sessionProperties
1813
+ };
1814
+ const request = {
1815
+ jsonrpc: "2.0",
1816
+ id: String(getUniqueRequestId()),
1817
+ method: "wallet_createSession",
1818
+ params: sessionRequest
1819
+ };
1820
+ let handler;
1821
+ const removeHandler = () => {
1822
+ if (handler) {
1823
+ this.dappClient.off("message", handler);
1824
+ handler = void 0;
1825
+ }
1826
+ };
1827
+ handler = (message) => __async(this, null, function* () {
1828
+ if (typeof message !== "object" || message === null) {
1829
+ return;
1830
+ }
1831
+ if (!("data" in message)) {
1832
+ return;
1833
+ }
1834
+ const messagePayload = message.data;
1835
+ const isMatchingId = messagePayload.id === request.id;
1836
+ const isMatchingMethod = messagePayload.method === "wallet_createSession" || messagePayload.method === "wallet_sessionChanged";
1837
+ if (!isMatchingId && !isMatchingMethod) {
1838
+ return;
1839
+ }
1840
+ const responseError = this.getResponseError(messagePayload);
1841
+ if (responseError) {
1842
+ connDeferred.reject(this.parseWalletError(responseError));
1843
+ return;
1844
+ }
1845
+ yield this.storeWalletSession(
1846
+ request,
1847
+ messagePayload
1848
+ );
1849
+ yield this.removeStoredPendingSessionRequest();
1850
+ this.notifyCallbacks(messagePayload);
1851
+ connDeferred.resolve();
1852
+ });
1853
+ this.dappClient.on("message", handler);
1854
+ const platformType = getPlatformType();
1855
+ const isQRCodeFlow = [
1856
+ "web-desktop" /* DesktopWeb */,
1857
+ "nodejs" /* NonBrowser */
1858
+ ].includes(platformType);
1859
+ const initialPayload = {
1860
+ name: MULTICHAIN_PROVIDER_STREAM_NAME,
1861
+ data: request
1862
+ };
1863
+ dappClient.connect({
1864
+ mode: "trusted",
1865
+ initialPayload: isQRCodeFlow ? void 0 : initialPayload
1866
+ }).then(() => __async(this, null, function* () {
1867
+ if (isQRCodeFlow) {
1868
+ return dappClient.sendRequest(initialPayload);
1869
+ }
1870
+ return void 0;
1871
+ })).catch((error) => connDeferred.reject(error));
1872
+ const timeoutDeferred = (0, import_utils7.createDeferredPromise)();
1873
+ const timeout = setTimeout(
1874
+ () => timeoutDeferred.reject(new import_multichain_api_client2.TransportTimeoutError()),
1875
+ isContinuingPriorAttempt ? this.options.resumeTimeout : this.options.connectionTimeout
1876
+ );
1877
+ return Promise.race([
1878
+ connDeferred.promise,
1879
+ timeoutDeferred.promise
1880
+ ]).finally(() => {
1881
+ clearTimeout(timeout);
1882
+ removeHandler();
1883
+ });
1884
+ });
1885
+ };
1828
1886
  }
1829
1887
  });
1830
1888
 
@@ -2129,6 +2187,7 @@ var init_node2 = __esm({
2129
2187
  // src/index.node.ts
2130
2188
  var index_node_exports = {};
2131
2189
  __export(index_node_exports, {
2190
+ EIP1193_PASSTHROUGH_METHODS: () => EIP1193_PASSTHROUGH_METHODS,
2132
2191
  EventEmitter: () => EventEmitter,
2133
2192
  Modal: () => Modal,
2134
2193
  MultichainCore: () => MultichainCore,
@@ -2156,7 +2215,8 @@ __export(index_node_exports, {
2156
2215
  isEnabled: () => isEnabled,
2157
2216
  isMetamaskExtensionInstalled: () => isMetamaskExtensionInstalled,
2158
2217
  isRejectionError: () => isRejectionError,
2159
- isSecure: () => isSecure
2218
+ isSecure: () => isSecure,
2219
+ packageVersion: () => packageVersion
2160
2220
  });
2161
2221
  module.exports = __toCommonJS(index_node_exports);
2162
2222
  init_domain();
@@ -2164,6 +2224,7 @@ init_domain();
2164
2224
  // src/multichain/index.ts
2165
2225
  var import_analytics4 = require("@metamask/analytics");
2166
2226
  var import_multichain_api_client3 = require("@metamask/multichain-api-client");
2227
+ var import_utils9 = require("@metamask/utils");
2167
2228
 
2168
2229
  // src/config/index.ts
2169
2230
  var MWP_RELAY_URL = "wss://mm-sdk-relay.api.cx.metamask.io/connection/websocket";
@@ -2287,17 +2348,93 @@ var import_analytics2 = require("@metamask/analytics");
2287
2348
  init_domain();
2288
2349
  init_utils();
2289
2350
  init_analytics();
2351
+
2352
+ // src/multichain/rpc/invocationError.ts
2353
+ var import_utils2 = require("@metamask/utils");
2354
+ init_domain();
2355
+ var MAX_ERROR_CAUSE_DEPTH = 5;
2356
+ function getErrorObject(value) {
2357
+ if (typeof value === "object" && value !== null) {
2358
+ return value;
2359
+ }
2360
+ return void 0;
2361
+ }
2362
+ function getNumericCode(value) {
2363
+ return typeof value === "number" ? value : void 0;
2364
+ }
2365
+ function getNonEmptyMessage(value) {
2366
+ return typeof value === "string" && value.length > 0 ? value : void 0;
2367
+ }
2368
+ function getJsonData(value) {
2369
+ return value !== void 0 && (0, import_utils2.isValidJson)(value) ? value : void 0;
2370
+ }
2371
+ function getFirstNonEmptyMessage(values) {
2372
+ for (const value of values) {
2373
+ const message = getNonEmptyMessage(value);
2374
+ if (message !== void 0) {
2375
+ return message;
2376
+ }
2377
+ }
2378
+ return void 0;
2379
+ }
2380
+ function getErrorObjectChain(errorObject) {
2381
+ const chain = [];
2382
+ let currentObject = errorObject;
2383
+ for (let depth = 0; currentObject !== void 0 && depth < MAX_ERROR_CAUSE_DEPTH; depth += 1) {
2384
+ chain.push(currentObject);
2385
+ currentObject = getErrorObject(currentObject.cause);
2386
+ }
2387
+ return chain;
2388
+ }
2389
+ function getCodedErrorDetails(value) {
2390
+ const code = getNumericCode(value == null ? void 0 : value.code);
2391
+ if (code === void 0) {
2392
+ return void 0;
2393
+ }
2394
+ const message = getNonEmptyMessage(value == null ? void 0 : value.message);
2395
+ const data = getJsonData(value == null ? void 0 : value.data);
2396
+ return __spreadValues(__spreadValues({
2397
+ code
2398
+ }, message === void 0 ? {} : { message }), data === void 0 ? {} : { data });
2399
+ }
2400
+ function getInvocationErrorDetails(error) {
2401
+ var _a2, _b, _c, _d;
2402
+ const errorObject = getErrorObject(error);
2403
+ const errorObjectChain = getErrorObjectChain(errorObject);
2404
+ const primitiveMessage = getNonEmptyMessage(error);
2405
+ for (const [index, currentObject] of errorObjectChain.entries()) {
2406
+ const codedDetails = getCodedErrorDetails(currentObject);
2407
+ if (codedDetails) {
2408
+ const descendantObjects = errorObjectChain.slice(index + 1);
2409
+ const ancestorObjects = errorObjectChain.slice(0, index);
2410
+ const descendantMessage = getFirstNonEmptyMessage(
2411
+ descendantObjects.map((object) => object.message)
2412
+ );
2413
+ const ancestorMessage = getFirstNonEmptyMessage([
2414
+ primitiveMessage,
2415
+ ...ancestorObjects.map((object) => object.message)
2416
+ ]);
2417
+ const reason2 = (_c = (_b = (_a2 = codedDetails.message) != null ? _a2 : descendantMessage) != null ? _b : ancestorMessage) != null ? _c : "Unknown error";
2418
+ return __spreadValues(__spreadValues({
2419
+ reason: reason2,
2420
+ rpcCode: codedDetails.code
2421
+ }, codedDetails.message === void 0 ? {} : { rpcMessage: codedDetails.message }), codedDetails.data === void 0 ? {} : { rpcData: codedDetails.data });
2422
+ }
2423
+ }
2424
+ const reason = (_d = primitiveMessage != null ? primitiveMessage : getFirstNonEmptyMessage(errorObjectChain.map((object) => object.message))) != null ? _d : "Unknown error";
2425
+ return {
2426
+ reason
2427
+ };
2428
+ }
2290
2429
  function toRPCInvokeMethodErr(error) {
2291
- var _a2;
2292
2430
  if (error instanceof RPCInvokeMethodErr) {
2293
2431
  return error;
2294
2432
  }
2295
- const castError = error;
2296
- return new RPCInvokeMethodErr(
2297
- (_a2 = castError.message) != null ? _a2 : "Unknown error",
2298
- castError.code
2299
- );
2433
+ const { reason, rpcCode, rpcMessage, rpcData } = getInvocationErrorDetails(error);
2434
+ return new RPCInvokeMethodErr(reason, rpcCode, rpcMessage, rpcData);
2300
2435
  }
2436
+
2437
+ // src/multichain/rpc/requestRouter.ts
2301
2438
  var _RequestRouter_instances, withAnalyticsTracking_fn, trackWalletActionRequested_fn, trackWalletActionSucceeded_fn, trackWalletActionFailed_fn, trackWalletActionRejected_fn;
2302
2439
  var RequestRouter = class {
2303
2440
  constructor(transport, rpcClient, config, transportType) {
@@ -2317,6 +2454,9 @@ var RequestRouter = class {
2317
2454
  invokeMethod(options) {
2318
2455
  return __async(this, null, function* () {
2319
2456
  const { method } = options.request;
2457
+ if (EIP1193_PASSTHROUGH_METHODS.has(method)) {
2458
+ return this.handleWithEip1193Passthrough(options);
2459
+ }
2320
2460
  if (RPC_HANDLED_METHODS.has(method)) {
2321
2461
  return this.handleWithRpcNode(options);
2322
2462
  }
@@ -2326,6 +2466,29 @@ var RequestRouter = class {
2326
2466
  return this.handleWithWallet(options);
2327
2467
  });
2328
2468
  }
2469
+ /**
2470
+ * Forwards EIP-1193 / legacy provider methods (e.g. `wallet_addEthereumChain`,
2471
+ * `wallet_switchEthereumChain`, `eth_accounts`) directly to the underlying
2472
+ * transport's `sendEip1193Message`, bypassing the multichain
2473
+ * `wallet_invokeMethod` envelope. These methods are wallet-side concerns the
2474
+ * Multichain API does not model, so we forward the raw `{ method, params }`
2475
+ * payload and return the wallet's full JSON-RPC response envelope unchanged.
2476
+ *
2477
+ * Analytics tracking is intentionally skipped here: ecosystem clients
2478
+ * (e.g. `connect-evm`) emit their own `wallet_action_*` events around these
2479
+ * passthrough calls, and adding router-level tracking would double-count.
2480
+ *
2481
+ * @param options
2482
+ */
2483
+ handleWithEip1193Passthrough(options) {
2484
+ return __async(this, null, function* () {
2485
+ const response = yield this.transport.sendEip1193Message({
2486
+ method: options.request.method,
2487
+ params: options.request.params
2488
+ });
2489
+ return response.result;
2490
+ });
2491
+ }
2329
2492
  /**
2330
2493
  * Forwards the request directly to the wallet via the transport.
2331
2494
  *
@@ -2358,12 +2521,7 @@ var RequestRouter = class {
2358
2521
  }
2359
2522
  const response = yield request;
2360
2523
  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
- );
2524
+ throw toRPCInvokeMethodErr(response.error);
2367
2525
  }
2368
2526
  return response.result;
2369
2527
  }));
@@ -2417,13 +2575,15 @@ withAnalyticsTracking_fn = function(options, execute) {
2417
2575
  yield __privateMethod(this, _RequestRouter_instances, trackWalletActionSucceeded_fn).call(this, options);
2418
2576
  return result;
2419
2577
  } catch (error) {
2420
- const isRejection = isRejectionError(error);
2578
+ const normalizedError = toRPCInvokeMethodErr(error);
2579
+ const analyticsError = normalizedError.rpcCode === void 0 ? error : normalizedError;
2580
+ const isRejection = isRejectionError(analyticsError);
2421
2581
  if (isRejection) {
2422
2582
  yield __privateMethod(this, _RequestRouter_instances, trackWalletActionRejected_fn).call(this, options);
2423
2583
  } else {
2424
- yield __privateMethod(this, _RequestRouter_instances, trackWalletActionFailed_fn).call(this, options, error);
2584
+ yield __privateMethod(this, _RequestRouter_instances, trackWalletActionFailed_fn).call(this, options, analyticsError);
2425
2585
  }
2426
- throw toRPCInvokeMethodErr(error);
2586
+ throw normalizedError;
2427
2587
  }
2428
2588
  });
2429
2589
  };
@@ -2475,9 +2635,10 @@ trackWalletActionRejected_fn = function(options) {
2475
2635
 
2476
2636
  // src/multichain/transports/default/index.ts
2477
2637
  var import_multichain_api_client = require("@metamask/multichain-api-client");
2638
+ var import_utils4 = require("@metamask/utils");
2478
2639
  init_utils();
2479
2640
  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;
2641
+ var _notificationCallbacks, _transport, _defaultRequestOptions, _pendingRequests, _handleResponseListener, _handleNotificationListener, _DefaultTransport_instances, notifyCallbacks_fn, parseWalletError_fn, isMetamaskProviderEvent_fn, handleResponse_fn, handleNotification_fn, setupMessageListener_fn, init_fn;
2481
2642
  var DefaultTransport = class {
2482
2643
  constructor() {
2483
2644
  __privateAdd(this, _DefaultTransport_instances);
@@ -2613,7 +2774,11 @@ var DefaultTransport = class {
2613
2774
  }
2614
2775
  request(_0) {
2615
2776
  return __async(this, arguments, function* (request, options = __privateGet(this, _defaultRequestOptions)) {
2616
- return __privateGet(this, _transport).request(request, options);
2777
+ const response = yield __privateGet(this, _transport).request(request, options);
2778
+ if (response.error) {
2779
+ throw __privateMethod(this, _DefaultTransport_instances, parseWalletError_fn).call(this, response.error);
2780
+ }
2781
+ return response;
2617
2782
  });
2618
2783
  }
2619
2784
  onNotification(callback) {
@@ -2657,6 +2822,20 @@ notifyCallbacks_fn = function(data) {
2657
2822
  }
2658
2823
  }
2659
2824
  };
2825
+ parseWalletError_fn = function(errorPayload) {
2826
+ const errorData = errorPayload;
2827
+ const error = new Error(
2828
+ typeof errorData.message === "string" ? errorData.message : "Request failed"
2829
+ );
2830
+ if (typeof errorData.code === "number") {
2831
+ error.code = errorData.code;
2832
+ }
2833
+ const { data } = errorData;
2834
+ if ((0, import_utils4.isValidJson)(data)) {
2835
+ error.data = data;
2836
+ }
2837
+ return error;
2838
+ };
2660
2839
  isMetamaskProviderEvent_fn = function(event) {
2661
2840
  var _a2, _b;
2662
2841
  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 +2858,7 @@ handleResponse_fn = function(event) {
2679
2858
  __privateGet(this, _pendingRequests).delete(responseId);
2680
2859
  const response = responseData;
2681
2860
  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);
2861
+ pendingRequest.reject(__privateMethod(this, _DefaultTransport_instances, parseWalletError_fn).call(this, response.error));
2689
2862
  } else {
2690
2863
  pendingRequest.resolve(response);
2691
2864
  }
@@ -2723,22 +2896,21 @@ init_fn = function() {
2723
2896
  // src/multichain/transports/multichainApiClientWrapper/index.ts
2724
2897
  var import_rpc_errors = require("@metamask/rpc-errors");
2725
2898
  init_utils();
2726
- var _notificationCallbacks2, _MultichainApiClientWrapperTransport_instances, walletCreateSession_fn, walletGetSession_fn, walletRevokeSession_fn, walletInvokeMethod_fn;
2899
+ var _notificationCallbacks2, _getTransport, _MultichainApiClientWrapperTransport_instances, walletCreateSession_fn, walletGetSession_fn, walletRevokeSession_fn, walletInvokeMethod_fn;
2727
2900
  var MultichainApiClientWrapperTransport = class {
2728
- constructor(metamaskConnectMultichain) {
2901
+ constructor(metamaskConnectMultichain, getTransport) {
2729
2902
  this.metamaskConnectMultichain = metamaskConnectMultichain;
2730
2903
  __privateAdd(this, _MultichainApiClientWrapperTransport_instances);
2731
2904
  __privateAdd(this, _notificationCallbacks2, /* @__PURE__ */ new Set());
2905
+ __privateAdd(this, _getTransport);
2906
+ __privateSet(this, _getTransport, getTransport);
2732
2907
  }
2733
2908
  isTransportDefined() {
2734
- try {
2735
- return Boolean(this.metamaskConnectMultichain.transport);
2736
- } catch (_error) {
2737
- return false;
2738
- }
2909
+ return __privateGet(this, _getTransport).call(this) !== void 0;
2739
2910
  }
2740
2911
  isTransportConnected() {
2741
- return this.isTransportDefined() && this.metamaskConnectMultichain.transport.isConnected();
2912
+ var _a2, _b;
2913
+ return (_b = (_a2 = __privateGet(this, _getTransport).call(this)) == null ? void 0 : _a2.isConnected()) != null ? _b : false;
2742
2914
  }
2743
2915
  clearNotificationCallbacks() {
2744
2916
  __privateGet(this, _notificationCallbacks2).clear();
@@ -2754,10 +2926,11 @@ var MultichainApiClientWrapperTransport = class {
2754
2926
  this.notificationListener = void 0;
2755
2927
  }
2756
2928
  setupTransportNotificationListener() {
2757
- if (!this.isTransportDefined() || this.notificationListener) {
2929
+ const transport = __privateGet(this, _getTransport).call(this);
2930
+ if (!transport || this.notificationListener) {
2758
2931
  return;
2759
2932
  }
2760
- this.notificationListener = this.metamaskConnectMultichain.transport.onNotification(
2933
+ this.notificationListener = transport.onNotification(
2761
2934
  this.notifyCallbacks.bind(this)
2762
2935
  );
2763
2936
  }
@@ -2807,6 +2980,7 @@ var MultichainApiClientWrapperTransport = class {
2807
2980
  }
2808
2981
  };
2809
2982
  _notificationCallbacks2 = new WeakMap();
2983
+ _getTransport = new WeakMap();
2810
2984
  _MultichainApiClientWrapperTransport_instances = new WeakSet();
2811
2985
  walletCreateSession_fn = function(request) {
2812
2986
  return __async(this, null, function* () {
@@ -2830,14 +3004,19 @@ walletCreateSession_fn = function(request) {
2830
3004
  accounts,
2831
3005
  createSessionParams.sessionProperties
2832
3006
  );
2833
- return this.metamaskConnectMultichain.transport.request({
3007
+ const transport = __privateGet(this, _getTransport).call(this);
3008
+ if (!transport) {
3009
+ throw new Error("Transport not initialized after connect");
3010
+ }
3011
+ return transport.request({
2834
3012
  method: "wallet_getSession"
2835
3013
  });
2836
3014
  });
2837
3015
  };
2838
3016
  walletGetSession_fn = function(request) {
2839
3017
  return __async(this, null, function* () {
2840
- if (!this.isTransportConnected()) {
3018
+ const transport = __privateGet(this, _getTransport).call(this);
3019
+ if (!(transport == null ? void 0 : transport.isConnected())) {
2841
3020
  return {
2842
3021
  jsonrpc: "2.0",
2843
3022
  id: request.id,
@@ -2846,7 +3025,7 @@ walletGetSession_fn = function(request) {
2846
3025
  }
2847
3026
  };
2848
3027
  }
2849
- return this.metamaskConnectMultichain.transport.request({
3028
+ return transport.request({
2850
3029
  method: "wallet_getSession"
2851
3030
  });
2852
3031
  });
@@ -2924,7 +3103,7 @@ function setupAnalyticsGlobals(options, storage, setAnonId) {
2924
3103
  import_analytics4.analytics.enable();
2925
3104
  });
2926
3105
  }
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;
3106
+ 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
3107
  var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends MultichainCore {
2929
3108
  constructor(options) {
2930
3109
  var _a2, _b, _c, _d;
@@ -2937,9 +3116,7 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
2937
3116
  }),
2938
3117
  analytics: normalizeAnalyticsOptions(options.analytics),
2939
3118
  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"
3119
+ "connect-multichain": getVersion()
2943
3120
  }, (_d = options.versions) != null ? _d : {})
2944
3121
  });
2945
3122
  super(allOptions);
@@ -2955,7 +3132,8 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
2955
3132
  __privateAdd(this, _anonId);
2956
3133
  __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
3134
  __privateSet(this, _providerTransportWrapper, new MultichainApiClientWrapperTransport(
2958
- this
3135
+ this,
3136
+ () => __privateGet(this, _transport2)
2959
3137
  ));
2960
3138
  __privateSet(this, _provider, (0, import_multichain_api_client3.getMultichainClient)({
2961
3139
  transport: __privateGet(this, _providerTransportWrapper)
@@ -2974,12 +3152,6 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
2974
3152
  get provider() {
2975
3153
  return __privateGet(this, _provider);
2976
3154
  }
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
3155
  get dappClient() {
2984
3156
  if (!__privateGet(this, _dappClient)) {
2985
3157
  throw new Error("DappClient not initialized, establish connection first");
@@ -2993,6 +3165,9 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
2993
3165
  get storage() {
2994
3166
  return this.options.storage;
2995
3167
  }
3168
+ get version() {
3169
+ return getVersion();
3170
+ }
2996
3171
  // Creates a singleton instance of MetaMaskConnectMultichain.
2997
3172
  // If the singleton already exists, it merges the incoming options with the
2998
3173
  // existing singleton options for the following keys: `api.supportedNetworks`,
@@ -3007,6 +3182,11 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
3007
3182
  const existing = globalObject[SINGLETON_KEY];
3008
3183
  if (existing) {
3009
3184
  const instance = yield existing;
3185
+ if (instance.version !== getVersion()) {
3186
+ console.warn(
3187
+ `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.`
3188
+ );
3189
+ }
3010
3190
  instance.mergeOptions(options);
3011
3191
  if (instance instanceof _MetaMaskConnectMultichain) {
3012
3192
  yield __privateMethod(_a2 = instance, _MetaMaskConnectMultichain_instances, setupAnalytics_fn).call(_a2);
@@ -3030,12 +3210,12 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
3030
3210
  }
3031
3211
  yield __privateMethod(_a3 = instance, _MetaMaskConnectMultichain_instances, init_fn2).call(_a3);
3032
3212
  return instance;
3033
- }))();
3034
- globalObject[SINGLETON_KEY] = instancePromise;
3035
- instancePromise.catch((error) => {
3213
+ }))().catch((error) => {
3036
3214
  globalObject[SINGLETON_KEY] = void 0;
3037
3215
  console.error("Error initializing MetaMaskConnectMultichain", error);
3216
+ throw error;
3038
3217
  });
3218
+ globalObject[SINGLETON_KEY] = instancePromise;
3039
3219
  return instancePromise;
3040
3220
  });
3041
3221
  }
@@ -3095,9 +3275,9 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
3095
3275
  forceRequest
3096
3276
  }).then(() => __async(this, null, function* () {
3097
3277
  if (__privateGet(this, _transportType) === "mwp" /* MWP */) {
3098
- return this.storage.setTransport("mwp" /* MWP */);
3278
+ return this.storage.setTransportType("mwp" /* MWP */);
3099
3279
  }
3100
- return this.storage.setTransport("browser" /* Browser */);
3280
+ return this.storage.setTransportType("browser" /* Browser */);
3101
3281
  })), scopes, transportType);
3102
3282
  }
3103
3283
  if (platformType === "in-app-browser" /* MetaMaskMobileWebview */) {
@@ -3126,11 +3306,6 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
3126
3306
  return __privateMethod(this, _MetaMaskConnectMultichain_instances, handleConnection_fn).call(this, __privateMethod(this, _MetaMaskConnectMultichain_instances, showInstallModal_fn).call(this, shouldShowInstallModal, mergedScopes, mergedCaipAccountIds, nonEmptySessionProperties), scopes, transportType);
3127
3307
  });
3128
3308
  }
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
3309
  disconnect() {
3135
3310
  return __async(this, arguments, function* (scopes = []) {
3136
3311
  var _a2, _b, _c;
@@ -3140,7 +3315,7 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
3140
3315
  );
3141
3316
  yield (_a2 = __privateGet(this, _transport2)) == null ? void 0 : _a2.disconnect(scopes);
3142
3317
  if (remainingScopes.length === 0) {
3143
- yield this.storage.removeTransport();
3318
+ yield this.storage.removeTransportType();
3144
3319
  if (__privateGet(this, _transportType) !== "browser" /* Browser */) {
3145
3320
  yield (_b = __privateGet(this, _listener)) == null ? void 0 : _b.call(this);
3146
3321
  (_c = __privateGet(this, _beforeUnloadListener)) == null ? void 0 : _c.call(this);
@@ -3158,7 +3333,8 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
3158
3333
  invokeMethod(request) {
3159
3334
  return __async(this, null, function* () {
3160
3335
  var _a2;
3161
- const { transport, options } = this;
3336
+ const transport = __privateMethod(this, _MetaMaskConnectMultichain_instances, transportOrThrow_fn).call(this);
3337
+ const { options } = this;
3162
3338
  const rpcClient = new RpcClient(options, __privateGet(this, _sdkInfo));
3163
3339
  const requestRouter = new RequestRouter(
3164
3340
  transport,
@@ -3177,7 +3353,7 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
3177
3353
  const shouldOpenDeeplink = secure && !showInstallModal;
3178
3354
  if (shouldOpenDeeplink) {
3179
3355
  setTimeout(() => __async(this, null, function* () {
3180
- const session = yield this.transport.getActiveSession();
3356
+ const session = yield __privateMethod(this, _MetaMaskConnectMultichain_instances, transportOrThrow_fn).call(this).getActiveSession();
3181
3357
  if (!session) {
3182
3358
  throw new Error("No active session found");
3183
3359
  }
@@ -3201,10 +3377,13 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
3201
3377
  this.emit("wallet_sessionChanged", emptySession);
3202
3378
  return;
3203
3379
  }
3204
- const response = yield this.transport.request({
3380
+ const response = yield __privateGet(this, _transport2).request({
3205
3381
  method: "wallet_getSession"
3206
3382
  });
3207
- this.emit("wallet_sessionChanged", (_b = response.result) != null ? _b : emptySession);
3383
+ this.emit(
3384
+ "wallet_sessionChanged",
3385
+ (_b = response.result) != null ? _b : emptySession
3386
+ );
3208
3387
  });
3209
3388
  }
3210
3389
  };
@@ -3216,8 +3395,14 @@ _beforeUnloadListener = new WeakMap();
3216
3395
  _transportType = new WeakMap();
3217
3396
  _listener = new WeakMap();
3218
3397
  _anonId = new WeakMap();
3219
- _sdkInfo = new WeakMap();
3220
3398
  _MetaMaskConnectMultichain_instances = new WeakSet();
3399
+ transportOrThrow_fn = function() {
3400
+ if (!__privateGet(this, _transport2)) {
3401
+ throw new Error("Transport not initialized, establish connection first");
3402
+ }
3403
+ return __privateGet(this, _transport2);
3404
+ };
3405
+ _sdkInfo = new WeakMap();
3221
3406
  setupAnalytics_fn = function() {
3222
3407
  return __async(this, null, function* () {
3223
3408
  yield setupAnalyticsGlobals(this.options, this.storage, (anonId) => {
@@ -3243,7 +3428,7 @@ onTransportNotification_fn = function(payload) {
3243
3428
  };
3244
3429
  getStoredTransport_fn = function() {
3245
3430
  return __async(this, null, function* () {
3246
- const transportType = yield this.storage.getTransport();
3431
+ const transportType = yield this.storage.getTransportType();
3247
3432
  const hasExtensionInstalled = yield hasExtension();
3248
3433
  if (transportType) {
3249
3434
  if (transportType === "browser" /* Browser */) {
@@ -3271,7 +3456,7 @@ getStoredTransport_fn = function() {
3271
3456
  ));
3272
3457
  return apiTransport;
3273
3458
  }
3274
- yield this.storage.removeTransport();
3459
+ yield this.storage.removeTransportType();
3275
3460
  }
3276
3461
  return void 0;
3277
3462
  });
@@ -3281,15 +3466,15 @@ setupTransport_fn = function() {
3281
3466
  var _a2;
3282
3467
  const transport = yield __privateMethod(this, _MetaMaskConnectMultichain_instances, getStoredTransport_fn).call(this);
3283
3468
  if (transport) {
3284
- if (!this.transport.isConnected()) {
3469
+ if (!transport.isConnected()) {
3285
3470
  this.status = "connecting";
3286
- yield this.transport.connect();
3471
+ yield transport.connect();
3287
3472
  }
3288
3473
  this.status = "connected";
3289
3474
  if (__privateGet(this, _transportType) === "mwp" /* MWP */) {
3290
- yield this.storage.setTransport("mwp" /* MWP */);
3475
+ yield this.storage.setTransportType("mwp" /* MWP */);
3291
3476
  } else {
3292
- yield this.storage.setTransport("browser" /* Browser */);
3477
+ yield this.storage.setTransportType("browser" /* Browser */);
3293
3478
  }
3294
3479
  } else {
3295
3480
  this.status = "loaded";
@@ -3298,7 +3483,7 @@ setupTransport_fn = function() {
3298
3483
  if (hasExtensionInstalled && preferExtension) {
3299
3484
  yield __privateMethod(this, _MetaMaskConnectMultichain_instances, setupDefaultTransport_fn).call(this, { persist: false });
3300
3485
  try {
3301
- yield this.transport.init();
3486
+ yield __privateMethod(this, _MetaMaskConnectMultichain_instances, transportOrThrow_fn).call(this).init();
3302
3487
  } catch (error) {
3303
3488
  console.error("Passive init failed:", error);
3304
3489
  }
@@ -3322,7 +3507,7 @@ init_fn2 = function() {
3322
3507
  yield __privateMethod(this, _MetaMaskConnectMultichain_instances, setupAnalytics_fn).call(this);
3323
3508
  yield __privateMethod(this, _MetaMaskConnectMultichain_instances, setupTransport_fn).call(this);
3324
3509
  } catch (error) {
3325
- yield this.storage.removeTransport();
3510
+ yield this.storage.removeTransportType();
3326
3511
  this.status = "pending";
3327
3512
  logger2("MetaMaskSDK error during initialization", error);
3328
3513
  }
@@ -3368,17 +3553,17 @@ setupMWP_fn = function() {
3368
3553
  __privateSet(this, _transport2, apiTransport);
3369
3554
  __privateSet(this, _transportType, "mwp" /* MWP */);
3370
3555
  __privateGet(this, _providerTransportWrapper).setupTransportNotificationListener();
3371
- __privateSet(this, _listener, this.transport.onNotification(
3556
+ __privateSet(this, _listener, apiTransport.onNotification(
3372
3557
  __privateMethod(this, _MetaMaskConnectMultichain_instances, onTransportNotification_fn).bind(this)
3373
3558
  ));
3374
- yield this.storage.setTransport("mwp" /* MWP */);
3559
+ yield this.storage.setTransportType("mwp" /* MWP */);
3375
3560
  });
3376
3561
  };
3377
3562
  onBeforeUnload_fn = function() {
3378
3563
  return __async(this, null, function* () {
3379
3564
  var _a2;
3380
3565
  if ((_a2 = this.options.ui.factory.modal) == null ? void 0 : _a2.isMounted) {
3381
- yield this.storage.removeTransport();
3566
+ yield this.storage.removeTransportType();
3382
3567
  }
3383
3568
  });
3384
3569
  };
@@ -3395,70 +3580,65 @@ createBeforeUnloadListener_fn = function() {
3395
3580
  };
3396
3581
  renderInstallModalAsync_fn = function(desktopPreferred, scopes, caipAccountIds, sessionProperties) {
3397
3582
  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
- });
3583
+ const completion = (0, import_utils9.createDeferredPromise)();
3584
+ const createConnectionRequest = () => __async(this, null, function* () {
3585
+ if (this.dappClient.state === "CONNECTED" || this.dappClient.state === "CONNECTING") {
3586
+ yield this.dappClient.disconnect();
3587
+ }
3588
+ const sessionRequestDeferred = (0, import_utils9.createDeferredPromise)();
3589
+ this.dappClient.on(
3590
+ "session_request",
3591
+ (sessionRequest) => {
3592
+ sessionRequestDeferred.resolve({
3593
+ sessionRequest,
3594
+ metadata: __privateMethod(this, _MetaMaskConnectMultichain_instances, buildConnectionMetadata_fn).call(this)
3444
3595
  });
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();
3596
+ }
3597
+ );
3598
+ __privateMethod(this, _MetaMaskConnectMultichain_instances, transportOrThrow_fn).call(this).connect({ scopes, caipAccountIds, sessionProperties }).then(() => __async(this, null, function* () {
3599
+ var _a2;
3600
+ yield this.options.ui.factory.unload();
3601
+ (_a2 = this.options.ui.factory.modal) == null ? void 0 : _a2.unmount();
3602
+ this.status = "connected";
3603
+ yield this.storage.setTransportType("mwp" /* MWP */);
3604
+ })).catch((error) => __async(this, null, function* () {
3605
+ const { ProtocolError, ErrorCode } = yield import("@metamask/mobile-wallet-protocol-core");
3606
+ if (error instanceof ProtocolError) {
3607
+ if (error.code !== ErrorCode.REQUEST_EXPIRED) {
3608
+ this.status = "disconnected";
3609
+ yield this.options.ui.factory.unload(error);
3610
+ completion.reject(error);
3453
3611
  }
3454
- }),
3455
- (uri) => {
3456
- this.emit("display_uri", uri);
3612
+ } else {
3613
+ this.status = "disconnected";
3614
+ const normalizedError = error instanceof Error ? error : new Error(String(error));
3615
+ yield this.options.ui.factory.unload(normalizedError);
3616
+ completion.reject(normalizedError);
3457
3617
  }
3458
- ).catch((error) => {
3459
- reject(error instanceof Error ? error : new Error(String(error)));
3460
- });
3618
+ }));
3619
+ return sessionRequestDeferred.promise;
3461
3620
  });
3621
+ this.options.ui.factory.renderInstallModal(
3622
+ desktopPreferred,
3623
+ createConnectionRequest,
3624
+ (error) => __async(this, null, function* () {
3625
+ if (error) {
3626
+ yield this.storage.removeTransportType();
3627
+ completion.reject(error);
3628
+ } else {
3629
+ yield this.storage.setTransportType("mwp" /* MWP */);
3630
+ completion.resolve();
3631
+ }
3632
+ }),
3633
+ (uri) => {
3634
+ this.emit("display_uri", uri);
3635
+ }
3636
+ ).catch((error) => {
3637
+ completion.reject(
3638
+ error instanceof Error ? error : new Error(String(error))
3639
+ );
3640
+ });
3641
+ return completion.promise;
3462
3642
  });
3463
3643
  };
3464
3644
  showInstallModal_fn = function(desktopPreferred, scopes, caipAccountIds, sessionProperties) {
@@ -3474,39 +3654,37 @@ showInstallModal_fn = function(desktopPreferred, scopes, caipAccountIds, session
3474
3654
  };
3475
3655
  headlessConnect_fn = function(scopes, caipAccountIds, sessionProperties) {
3476
3656
  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
- });
3657
+ if (this.dappClient.state === "CONNECTED" || this.dappClient.state === "CONNECTING") {
3658
+ yield this.dappClient.disconnect().catch(() => void 0);
3659
+ }
3660
+ const onSessionRequest = (sessionRequest) => {
3661
+ const connectionRequest = {
3662
+ sessionRequest,
3663
+ metadata: __privateMethod(this, _MetaMaskConnectMultichain_instances, buildConnectionMetadata_fn).call(this)
3664
+ };
3665
+ const deeplink = this.options.ui.factory.createConnectionDeeplink(connectionRequest);
3666
+ this.emit("display_uri", deeplink);
3667
+ };
3668
+ this.dappClient.on("session_request", onSessionRequest);
3669
+ try {
3670
+ yield __privateMethod(this, _MetaMaskConnectMultichain_instances, transportOrThrow_fn).call(this).connect({
3671
+ scopes,
3672
+ caipAccountIds,
3673
+ sessionProperties
3674
+ });
3675
+ this.status = "connected";
3676
+ yield this.storage.setTransportType("mwp" /* MWP */);
3677
+ } catch (error) {
3678
+ const { ProtocolError } = yield import("@metamask/mobile-wallet-protocol-core");
3679
+ this.status = "disconnected";
3680
+ yield this.storage.removeTransportType();
3681
+ if (error instanceof ProtocolError || error instanceof Error) {
3682
+ throw error;
3481
3683
  }
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
- });
3684
+ throw new Error(String(error));
3685
+ } finally {
3686
+ this.dappClient.off("session_request", onSessionRequest);
3687
+ }
3510
3688
  });
3511
3689
  };
3512
3690
  setupDefaultTransport_fn = function() {
@@ -3515,7 +3693,7 @@ setupDefaultTransport_fn = function() {
3515
3693
  return __privateGet(this, _transport2);
3516
3694
  }
3517
3695
  if (options == null ? void 0 : options.persist) {
3518
- yield this.storage.setTransport("browser" /* Browser */);
3696
+ yield this.storage.setTransportType("browser" /* Browser */);
3519
3697
  }
3520
3698
  const transport = new DefaultTransport();
3521
3699
  __privateSet(this, _listener, transport.onNotification(
@@ -3548,7 +3726,7 @@ deeplinkConnect_fn = function(scopes, caipAccountIds, sessionProperties) {
3548
3726
  };
3549
3727
  this.dappClient.on("message", dappClientMessageHandler);
3550
3728
  let timeout;
3551
- if (this.transport.isConnected()) {
3729
+ if (__privateMethod(this, _MetaMaskConnectMultichain_instances, transportOrThrow_fn).call(this).isConnected()) {
3552
3730
  timeout = setTimeout(() => {
3553
3731
  this.openSimpleDeeplinkIfNeeded();
3554
3732
  }, 250);
@@ -3576,8 +3754,8 @@ deeplinkConnect_fn = function(scopes, caipAccountIds, sessionProperties) {
3576
3754
  }
3577
3755
  );
3578
3756
  }
3579
- return this.transport.connect({ scopes, caipAccountIds, sessionProperties }).then(resolve).catch((error) => __async(this, null, function* () {
3580
- yield this.storage.removeTransport();
3757
+ return __privateMethod(this, _MetaMaskConnectMultichain_instances, transportOrThrow_fn).call(this).connect({ scopes, caipAccountIds, sessionProperties }).then(resolve).catch((error) => __async(this, null, function* () {
3758
+ yield this.storage.removeTransportType();
3581
3759
  this.dappClient.off("message", dappClientMessageHandler);
3582
3760
  reject(error instanceof Error ? error : new Error(String(error)));
3583
3761
  })).finally(() => {
@@ -3643,7 +3821,7 @@ getCaipSession_fn = function() {
3643
3821
  };
3644
3822
  if ((_a2 = __privateGet(this, _transport2)) == null ? void 0 : _a2.isConnected()) {
3645
3823
  try {
3646
- const response = yield this.transport.request({
3824
+ const response = yield __privateGet(this, _transport2).request({
3647
3825
  method: "wallet_getSession"
3648
3826
  });
3649
3827
  if (response.result) {
@@ -3737,14 +3915,14 @@ var Store = class extends StoreClient {
3737
3915
  super();
3738
3916
  this.adapter = adapter;
3739
3917
  }
3740
- getTransport() {
3918
+ getTransportType() {
3741
3919
  return __async(this, null, function* () {
3742
3920
  try {
3743
- const transport = yield this.adapter.get("multichain-transport");
3744
- if (!transport) {
3921
+ const transportType = yield this.adapter.get("multichain-transport");
3922
+ if (!transportType) {
3745
3923
  return null;
3746
3924
  }
3747
- return getTransportType(transport);
3925
+ return getTransportType(transportType);
3748
3926
  } catch (err) {
3749
3927
  throw new StorageGetErr(
3750
3928
  this.adapter.platform,
@@ -3754,10 +3932,10 @@ var Store = class extends StoreClient {
3754
3932
  }
3755
3933
  });
3756
3934
  }
3757
- setTransport(transport) {
3935
+ setTransportType(transportType) {
3758
3936
  return __async(this, null, function* () {
3759
3937
  try {
3760
- yield this.adapter.set("multichain-transport", transport);
3938
+ yield this.adapter.set("multichain-transport", transportType);
3761
3939
  } catch (err) {
3762
3940
  throw new StorageSetErr(
3763
3941
  this.adapter.platform,
@@ -3767,7 +3945,7 @@ var Store = class extends StoreClient {
3767
3945
  }
3768
3946
  });
3769
3947
  }
3770
- removeTransport() {
3948
+ removeTransportType() {
3771
3949
  return __async(this, null, function* () {
3772
3950
  try {
3773
3951
  yield this.adapter.delete("multichain-transport");
@@ -3981,7 +4159,11 @@ var BaseModalFactory = class {
3981
4159
  (_a3 = this.displayUriCallback) == null ? void 0 : _a3.call(this, newLink);
3982
4160
  return newLink;
3983
4161
  }),
3984
- onClose: this.onCloseModal.bind(this),
4162
+ onClose: (shouldTerminate) => {
4163
+ this.onCloseModal(shouldTerminate).catch((error) => {
4164
+ console.error("Failed to close modal:", error);
4165
+ });
4166
+ },
3985
4167
  startDesktopOnboarding: this.onStartDesktopOnboarding.bind(this),
3986
4168
  createConnectionRequest,
3987
4169
  onDisplayUri: this.displayUriCallback
@@ -4019,7 +4201,7 @@ function preload() {
4019
4201
  }
4020
4202
  try {
4021
4203
  const { defineCustomElements } = yield import("@metamask/multichain-ui/loader");
4022
- yield defineCustomElements();
4204
+ defineCustomElements();
4023
4205
  } catch (error) {
4024
4206
  console.error("Failed to load customElements:", error);
4025
4207
  }
@@ -4058,6 +4240,7 @@ var createMultichainClient = (options) => __async(null, null, function* () {
4058
4240
  });
4059
4241
  // Annotate the CommonJS export names for ESM import in node:
4060
4242
  0 && (module.exports = {
4243
+ EIP1193_PASSTHROUGH_METHODS,
4061
4244
  EventEmitter,
4062
4245
  Modal,
4063
4246
  MultichainCore,
@@ -4085,6 +4268,7 @@ var createMultichainClient = (options) => __async(null, null, function* () {
4085
4268
  isEnabled,
4086
4269
  isMetamaskExtensionInstalled,
4087
4270
  isRejectionError,
4088
- isSecure
4271
+ isSecure,
4272
+ packageVersion
4089
4273
  });
4090
4274
  //# sourceMappingURL=connect-multichain.js.map