@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
@@ -112,7 +112,15 @@ var init_rpc = __esm({
112
112
  _RPCReadonlyRequestErr.code = 52;
113
113
  RPCReadonlyRequestErr = _RPCReadonlyRequestErr;
114
114
  _RPCInvokeMethodErr = class _RPCInvokeMethodErr extends BaseErr {
115
- constructor(reason, rpcCode, rpcMessage) {
115
+ /**
116
+ * @param reason - MetaMask Connect invokeMethod reason.
117
+ * @param rpcCode - Original wallet JSON-RPC / EIP-1193 error code.
118
+ * @param rpcMessage - Original provider-facing wallet message, sourced only
119
+ * from the wallet's coded error. Unset when the wallet provides no message,
120
+ * so it may differ from `reason`, which can fall back through the cause chain.
121
+ * @param rpcData - Original JSON-RPC error data, when provided by the wallet.
122
+ */
123
+ constructor(reason, rpcCode, rpcMessage, rpcData) {
116
124
  super(
117
125
  `RPCErr${_RPCInvokeMethodErr.code}: RPC Client invoke method reason (${reason})`,
118
126
  _RPCInvokeMethodErr.code
@@ -120,6 +128,7 @@ var init_rpc = __esm({
120
128
  this.reason = reason;
121
129
  this.rpcCode = rpcCode;
122
130
  this.rpcMessage = rpcMessage;
131
+ this.rpcData = rpcData;
123
132
  }
124
133
  };
125
134
  _RPCInvokeMethodErr.code = 53;
@@ -252,7 +261,7 @@ var init_logger = __esm({
252
261
  });
253
262
 
254
263
  // src/domain/multichain/api/constants.ts
255
- var infuraRpcUrls, RPC_HANDLED_METHODS, SDK_HANDLED_METHODS;
264
+ var infuraRpcUrls, RPC_HANDLED_METHODS, SDK_HANDLED_METHODS, EIP1193_PASSTHROUGH_METHODS;
256
265
  var init_constants = __esm({
257
266
  "src/domain/multichain/api/constants.ts"() {
258
267
  "use strict";
@@ -417,6 +426,11 @@ var init_constants = __esm({
417
426
  "eth_uninstallFilter"
418
427
  ]);
419
428
  SDK_HANDLED_METHODS = /* @__PURE__ */ new Set(["eth_accounts", "eth_chainId"]);
429
+ EIP1193_PASSTHROUGH_METHODS = /* @__PURE__ */ new Set([
430
+ "wallet_addEthereumChain",
431
+ "wallet_switchEthereumChain",
432
+ "eth_accounts"
433
+ ]);
420
434
  }
421
435
  });
422
436
 
@@ -567,7 +581,7 @@ function hasExtension() {
567
581
  return detectionPromise;
568
582
  });
569
583
  }
570
- var PlatformType, detectionPromise;
584
+ var PlatformType, NATIVE_METAMASK_EIP6963_RDNS, detectionPromise;
571
585
  var init_platform = __esm({
572
586
  "src/domain/platform/index.ts"() {
573
587
  "use strict";
@@ -579,6 +593,10 @@ var init_platform = __esm({
579
593
  PlatformType2["ReactNative"] = "react-native";
580
594
  return PlatformType2;
581
595
  })(PlatformType || {});
596
+ NATIVE_METAMASK_EIP6963_RDNS = /* @__PURE__ */ new Set([
597
+ "io.metamask",
598
+ "io.metamask.mobile"
599
+ ]);
582
600
  detectionPromise = (() => __async(null, null, function* () {
583
601
  const pt = getPlatformType();
584
602
  if (pt === "nodejs" /* NonBrowser */ || pt === "react-native" /* ReactNative */) {
@@ -586,23 +604,30 @@ var init_platform = __esm({
586
604
  }
587
605
  return new Promise((resolve) => {
588
606
  const providers = [];
607
+ const targetWindow = window;
589
608
  const handler = (event) => {
590
609
  var _a3, _b;
591
610
  if ((_b = (_a3 = event == null ? void 0 : event.detail) == null ? void 0 : _a3.info) == null ? void 0 : _b.rdns) {
592
611
  providers.push(event.detail);
593
612
  }
594
613
  };
595
- window.addEventListener("eip6963:announceProvider", handler);
596
- window.dispatchEvent(new Event("eip6963:requestProvider"));
614
+ targetWindow.addEventListener("eip6963:announceProvider", handler);
615
+ targetWindow.dispatchEvent(new Event("eip6963:requestProvider"));
597
616
  setTimeout(() => {
598
- window.removeEventListener("eip6963:announceProvider", handler);
599
- const hasMetaMask = providers.some(
600
- (provider) => {
601
- var _a3, _b;
602
- return (_b = (_a3 = provider == null ? void 0 : provider.info) == null ? void 0 : _a3.rdns) == null ? void 0 : _b.startsWith("io.metamask");
617
+ try {
618
+ if (typeof (targetWindow == null ? void 0 : targetWindow.removeEventListener) === "function") {
619
+ targetWindow.removeEventListener("eip6963:announceProvider", handler);
603
620
  }
604
- );
605
- resolve(hasMetaMask);
621
+ const hasMetaMask = providers.some(
622
+ (provider) => {
623
+ var _a3;
624
+ return typeof ((_a3 = provider == null ? void 0 : provider.info) == null ? void 0 : _a3.rdns) === "string" && NATIVE_METAMASK_EIP6963_RDNS.has(provider.info.rdns);
625
+ }
626
+ );
627
+ resolve(hasMetaMask);
628
+ } catch (e) {
629
+ resolve(false);
630
+ }
606
631
  }, 300);
607
632
  });
608
633
  }))();
@@ -847,12 +872,14 @@ var init_analytics = __esm({
847
872
 
848
873
  // src/domain/utils/index.ts
849
874
  function getVersion() {
850
- return "0.0.0";
875
+ return packageVersion;
851
876
  }
877
+ var packageVersion;
852
878
  var init_utils = __esm({
853
879
  "src/domain/utils/index.ts"() {
854
880
  "use strict";
855
881
  init_analytics();
882
+ packageVersion = false ? "unknown" : "1.1.0";
856
883
  }
857
884
  });
858
885
 
@@ -1159,7 +1186,8 @@ import {
1159
1186
  TransportTimeoutError
1160
1187
  } from "@metamask/multichain-api-client";
1161
1188
  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;
1189
+ import { createDeferredPromise, isValidJson as isValidJson3 } from "@metamask/utils";
1190
+ 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
1191
  var init_mwp = __esm({
1164
1192
  "src/multichain/transports/mwp/index.ts"() {
1165
1193
  "use strict";
@@ -1193,6 +1221,7 @@ var init_mwp = __esm({
1193
1221
  this.dappClient = dappClient;
1194
1222
  this.kvstore = kvstore;
1195
1223
  this.options = options;
1224
+ __privateAdd(this, _MWPTransport_instances);
1196
1225
  this.__pendingRequests = /* @__PURE__ */ new Map();
1197
1226
  this.notificationCallbacks = /* @__PURE__ */ new Set();
1198
1227
  this.dappClient.on("message", this.handleMessage.bind(this));
@@ -1264,14 +1293,33 @@ var init_mwp = __esm({
1264
1293
  const errorData = errorPayload;
1265
1294
  if (typeof errorData.code === "number" && typeof errorData.message === "string") {
1266
1295
  const { code, message: message2 } = errorData;
1296
+ const rawData = errorData.data;
1297
+ const data = isValidJson3(rawData) ? rawData : void 0;
1267
1298
  if (code >= 1e3 && code <= 4999) {
1268
- return providerErrors2.custom({ code, message: message2 });
1299
+ return providerErrors2.custom({ code, message: message2, data });
1269
1300
  }
1270
- return new JsonRpcError(code, message2);
1301
+ return new JsonRpcError(code, message2, data);
1271
1302
  }
1272
1303
  const message = errorPayload instanceof Error ? errorPayload.message : JSON.stringify(errorPayload);
1273
1304
  return rpcErrors.internal({ message });
1274
1305
  }
1306
+ getResponseError(messagePayload) {
1307
+ if ("error" in messagePayload && messagePayload.error) {
1308
+ return messagePayload.error;
1309
+ }
1310
+ const { result } = messagePayload;
1311
+ if (typeof result === "object" && result !== null && "error" in result && result.error && this.isErrorPayload(result.error)) {
1312
+ return result.error;
1313
+ }
1314
+ return void 0;
1315
+ }
1316
+ isErrorPayload(errorPayload) {
1317
+ if (errorPayload instanceof Error) {
1318
+ return true;
1319
+ }
1320
+ const errorData = errorPayload;
1321
+ return typeof (errorData == null ? void 0 : errorData.code) === "number" && typeof (errorData == null ? void 0 : errorData.message) === "string";
1322
+ }
1275
1323
  handleMessage(message) {
1276
1324
  if (typeof message === "object" && message !== null) {
1277
1325
  if ("data" in message) {
@@ -1280,9 +1328,10 @@ var init_mwp = __esm({
1280
1328
  const request = this.pendingRequests.get(messagePayload.id);
1281
1329
  if (request) {
1282
1330
  clearTimeout(request.timeout);
1283
- if ("error" in messagePayload && messagePayload.error) {
1331
+ const responseError = this.getResponseError(messagePayload);
1332
+ if (responseError) {
1284
1333
  this.pendingRequests.delete(messagePayload.id);
1285
- request.reject(this.parseWalletError(messagePayload.error));
1334
+ request.reject(this.parseWalletError(responseError));
1286
1335
  return;
1287
1336
  }
1288
1337
  const requestWithName = __spreadProps(__spreadValues({}, messagePayload), {
@@ -1325,73 +1374,6 @@ var init_mwp = __esm({
1325
1374
  }
1326
1375
  }
1327
1376
  }
1328
- onResumeSuccess(resumeResolve, resumeReject, options) {
1329
- return __async(this, null, function* () {
1330
- var _a3, _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
- (_a3 = walletSession == null ? void 0 : walletSession.sessionScopes) != null ? _a3 : {}
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
1377
  init() {
1396
1378
  return __async(this, null, function* () {
1397
1379
  });
@@ -1432,7 +1414,6 @@ var init_mwp = __esm({
1432
1414
  }
1433
1415
  connect(options) {
1434
1416
  return __async(this, null, function* () {
1435
- const { dappClient } = this;
1436
1417
  const session = yield this.getActiveSession();
1437
1418
  if (session) {
1438
1419
  logger("active session found", {
@@ -1441,116 +1422,11 @@ var init_mwp = __esm({
1441
1422
  expiresAt: session.expiresAt
1442
1423
  });
1443
1424
  }
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 _a3;
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((_a3 = session == null ? void 0 : session.id) != null ? _a3 : "");
1459
- }
1460
- });
1461
- } else {
1462
- connection = new Promise(
1463
- (resolveConnection, rejectConnection) => {
1464
- var _a3, _b;
1465
- const optionalScopes = addValidAccounts(
1466
- getOptionalScopes((_a3 = options == null ? void 0 : options.scopes) != null ? _a3 : []),
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* () {
1425
+ const connection = session ? __privateMethod(this, _MWPTransport_instances, resumeSession_fn).call(this, session, options) : __privateMethod(this, _MWPTransport_instances, startSession_fn).call(this, options);
1426
+ return connection.catch((error) => __async(this, null, function* () {
1544
1427
  yield this.dappClient.disconnect();
1545
1428
  throw error;
1546
1429
  })).finally(() => {
1547
- if (timeout) {
1548
- clearTimeout(timeout);
1549
- }
1550
- if (initialConnectionMessageHandler) {
1551
- this.dappClient.off("message", initialConnectionMessageHandler);
1552
- initialConnectionMessageHandler = void 0;
1553
- }
1554
1430
  this.removeStoredPendingSessionRequest();
1555
1431
  });
1556
1432
  });
@@ -1809,6 +1685,188 @@ var init_mwp = __esm({
1809
1685
  });
1810
1686
  }
1811
1687
  };
1688
+ _MWPTransport_instances = new WeakSet();
1689
+ onResumeHandler_fn = function(options) {
1690
+ return __async(this, null, function* () {
1691
+ var _a3, _b, _c, _d, _e, _f, _g;
1692
+ yield this.waitForWalletSessionIfNotCached();
1693
+ const sessionResponse = yield this.request({ method: "wallet_getSession" });
1694
+ if (sessionResponse.error) {
1695
+ throw new Error(sessionResponse.error.message);
1696
+ }
1697
+ let walletSession = sessionResponse.result;
1698
+ if (walletSession && options) {
1699
+ const currentScopes = Object.keys(
1700
+ (_a3 = walletSession == null ? void 0 : walletSession.sessionScopes) != null ? _a3 : {}
1701
+ );
1702
+ const proposedScopes = (_b = options == null ? void 0 : options.scopes) != null ? _b : [];
1703
+ const proposedCaipAccountIds = (_c = options == null ? void 0 : options.caipAccountIds) != null ? _c : [];
1704
+ const hasSameScopesAndAccounts = isSameScopesAndAccounts(
1705
+ currentScopes,
1706
+ proposedScopes,
1707
+ walletSession,
1708
+ proposedCaipAccountIds
1709
+ );
1710
+ if (options.forceRequest || !hasSameScopesAndAccounts) {
1711
+ const optionalScopes = addValidAccounts(
1712
+ getOptionalScopes((_d = options == null ? void 0 : options.scopes) != null ? _d : []),
1713
+ getValidAccounts((_e = options == null ? void 0 : options.caipAccountIds) != null ? _e : [])
1714
+ );
1715
+ const sessionRequest = {
1716
+ optionalScopes
1717
+ };
1718
+ const response = yield this.request({
1719
+ method: "wallet_createSession",
1720
+ params: sessionRequest
1721
+ });
1722
+ if (response.error) {
1723
+ throw new Error(response.error.message);
1724
+ }
1725
+ walletSession = response.result;
1726
+ }
1727
+ } else if (!walletSession) {
1728
+ const optionalScopes = addValidAccounts(
1729
+ getOptionalScopes((_f = options == null ? void 0 : options.scopes) != null ? _f : []),
1730
+ getValidAccounts((_g = options == null ? void 0 : options.caipAccountIds) != null ? _g : [])
1731
+ );
1732
+ const sessionRequest = {
1733
+ optionalScopes
1734
+ };
1735
+ const response = yield this.request({
1736
+ method: "wallet_createSession",
1737
+ params: sessionRequest
1738
+ });
1739
+ if (response.error) {
1740
+ throw new Error(response.error.message);
1741
+ }
1742
+ walletSession = response.result;
1743
+ }
1744
+ yield this.removeStoredPendingSessionRequest();
1745
+ this.notifyCallbacks({
1746
+ method: "wallet_sessionChanged",
1747
+ params: walletSession
1748
+ });
1749
+ });
1750
+ };
1751
+ resumeSession_fn = function(session, options) {
1752
+ return __async(this, null, function* () {
1753
+ var _a3;
1754
+ const isContinuingPriorAttempt = (yield this.getStoredPendingSessionRequest()) !== null;
1755
+ const resumeDeferred = createDeferredPromise();
1756
+ const runOnResumeHandler = () => __async(this, null, function* () {
1757
+ try {
1758
+ resumeDeferred.resolve(yield __privateMethod(this, _MWPTransport_instances, onResumeHandler_fn).call(this, options));
1759
+ } catch (err) {
1760
+ resumeDeferred.reject(err);
1761
+ }
1762
+ });
1763
+ if (this.dappClient.state === "CONNECTED") {
1764
+ runOnResumeHandler();
1765
+ } else {
1766
+ this.dappClient.once("connected", runOnResumeHandler);
1767
+ this.dappClient.resume((_a3 = session.id) != null ? _a3 : "").catch((err) => resumeDeferred.reject(err));
1768
+ }
1769
+ const timeoutDeferred = createDeferredPromise();
1770
+ const timeout = setTimeout(
1771
+ () => timeoutDeferred.reject(new TransportTimeoutError()),
1772
+ isContinuingPriorAttempt ? this.options.resumeTimeout : this.options.connectionTimeout
1773
+ );
1774
+ const cleanup = () => this.dappClient.off("connected", runOnResumeHandler);
1775
+ return Promise.race([
1776
+ resumeDeferred.promise,
1777
+ timeoutDeferred.promise
1778
+ ]).finally(() => {
1779
+ clearTimeout(timeout);
1780
+ cleanup();
1781
+ });
1782
+ });
1783
+ };
1784
+ startSession_fn = function(options) {
1785
+ return __async(this, null, function* () {
1786
+ var _a3, _b;
1787
+ const { dappClient } = this;
1788
+ const isContinuingPriorAttempt = (yield this.getStoredPendingSessionRequest()) !== null;
1789
+ const connDeferred = createDeferredPromise();
1790
+ const optionalScopes = addValidAccounts(
1791
+ getOptionalScopes((_a3 = options == null ? void 0 : options.scopes) != null ? _a3 : []),
1792
+ getValidAccounts((_b = options == null ? void 0 : options.caipAccountIds) != null ? _b : [])
1793
+ );
1794
+ const sessionRequest = {
1795
+ optionalScopes,
1796
+ sessionProperties: options == null ? void 0 : options.sessionProperties
1797
+ };
1798
+ const request = {
1799
+ jsonrpc: "2.0",
1800
+ id: String(getUniqueRequestId()),
1801
+ method: "wallet_createSession",
1802
+ params: sessionRequest
1803
+ };
1804
+ let handler;
1805
+ const removeHandler = () => {
1806
+ if (handler) {
1807
+ this.dappClient.off("message", handler);
1808
+ handler = void 0;
1809
+ }
1810
+ };
1811
+ handler = (message) => __async(this, null, function* () {
1812
+ if (typeof message !== "object" || message === null) {
1813
+ return;
1814
+ }
1815
+ if (!("data" in message)) {
1816
+ return;
1817
+ }
1818
+ const messagePayload = message.data;
1819
+ const isMatchingId = messagePayload.id === request.id;
1820
+ const isMatchingMethod = messagePayload.method === "wallet_createSession" || messagePayload.method === "wallet_sessionChanged";
1821
+ if (!isMatchingId && !isMatchingMethod) {
1822
+ return;
1823
+ }
1824
+ const responseError = this.getResponseError(messagePayload);
1825
+ if (responseError) {
1826
+ connDeferred.reject(this.parseWalletError(responseError));
1827
+ return;
1828
+ }
1829
+ yield this.storeWalletSession(
1830
+ request,
1831
+ messagePayload
1832
+ );
1833
+ yield this.removeStoredPendingSessionRequest();
1834
+ this.notifyCallbacks(messagePayload);
1835
+ connDeferred.resolve();
1836
+ });
1837
+ this.dappClient.on("message", handler);
1838
+ const platformType = getPlatformType();
1839
+ const isQRCodeFlow = [
1840
+ "web-desktop" /* DesktopWeb */,
1841
+ "nodejs" /* NonBrowser */
1842
+ ].includes(platformType);
1843
+ const initialPayload = {
1844
+ name: MULTICHAIN_PROVIDER_STREAM_NAME,
1845
+ data: request
1846
+ };
1847
+ dappClient.connect({
1848
+ mode: "trusted",
1849
+ initialPayload: isQRCodeFlow ? void 0 : initialPayload
1850
+ }).then(() => __async(this, null, function* () {
1851
+ if (isQRCodeFlow) {
1852
+ return dappClient.sendRequest(initialPayload);
1853
+ }
1854
+ return void 0;
1855
+ })).catch((error) => connDeferred.reject(error));
1856
+ const timeoutDeferred = createDeferredPromise();
1857
+ const timeout = setTimeout(
1858
+ () => timeoutDeferred.reject(new TransportTimeoutError()),
1859
+ isContinuingPriorAttempt ? this.options.resumeTimeout : this.options.connectionTimeout
1860
+ );
1861
+ return Promise.race([
1862
+ connDeferred.promise,
1863
+ timeoutDeferred.promise
1864
+ ]).finally(() => {
1865
+ clearTimeout(timeout);
1866
+ removeHandler();
1867
+ });
1868
+ });
1869
+ };
1812
1870
  }
1813
1871
  });
1814
1872
 
@@ -2088,6 +2146,7 @@ import { analytics as analytics2 } from "@metamask/analytics";
2088
2146
  import {
2089
2147
  getMultichainClient
2090
2148
  } from "@metamask/multichain-api-client";
2149
+ import { createDeferredPromise as createDeferredPromise2 } from "@metamask/utils";
2091
2150
 
2092
2151
  // src/config/index.ts
2093
2152
  var MWP_RELAY_URL = "wss://mm-sdk-relay.api.cx.metamask.io/connection/websocket";
@@ -2211,17 +2270,93 @@ import { analytics } from "@metamask/analytics";
2211
2270
  init_domain();
2212
2271
  init_utils2();
2213
2272
  init_analytics();
2273
+
2274
+ // src/multichain/rpc/invocationError.ts
2275
+ init_domain();
2276
+ import { isValidJson } from "@metamask/utils";
2277
+ var MAX_ERROR_CAUSE_DEPTH = 5;
2278
+ function getErrorObject(value) {
2279
+ if (typeof value === "object" && value !== null) {
2280
+ return value;
2281
+ }
2282
+ return void 0;
2283
+ }
2284
+ function getNumericCode(value) {
2285
+ return typeof value === "number" ? value : void 0;
2286
+ }
2287
+ function getNonEmptyMessage(value) {
2288
+ return typeof value === "string" && value.length > 0 ? value : void 0;
2289
+ }
2290
+ function getJsonData(value) {
2291
+ return value !== void 0 && isValidJson(value) ? value : void 0;
2292
+ }
2293
+ function getFirstNonEmptyMessage(values) {
2294
+ for (const value of values) {
2295
+ const message = getNonEmptyMessage(value);
2296
+ if (message !== void 0) {
2297
+ return message;
2298
+ }
2299
+ }
2300
+ return void 0;
2301
+ }
2302
+ function getErrorObjectChain(errorObject) {
2303
+ const chain = [];
2304
+ let currentObject = errorObject;
2305
+ for (let depth = 0; currentObject !== void 0 && depth < MAX_ERROR_CAUSE_DEPTH; depth += 1) {
2306
+ chain.push(currentObject);
2307
+ currentObject = getErrorObject(currentObject.cause);
2308
+ }
2309
+ return chain;
2310
+ }
2311
+ function getCodedErrorDetails(value) {
2312
+ const code = getNumericCode(value == null ? void 0 : value.code);
2313
+ if (code === void 0) {
2314
+ return void 0;
2315
+ }
2316
+ const message = getNonEmptyMessage(value == null ? void 0 : value.message);
2317
+ const data = getJsonData(value == null ? void 0 : value.data);
2318
+ return __spreadValues(__spreadValues({
2319
+ code
2320
+ }, message === void 0 ? {} : { message }), data === void 0 ? {} : { data });
2321
+ }
2322
+ function getInvocationErrorDetails(error) {
2323
+ var _a3, _b, _c, _d;
2324
+ const errorObject = getErrorObject(error);
2325
+ const errorObjectChain = getErrorObjectChain(errorObject);
2326
+ const primitiveMessage = getNonEmptyMessage(error);
2327
+ for (const [index, currentObject] of errorObjectChain.entries()) {
2328
+ const codedDetails = getCodedErrorDetails(currentObject);
2329
+ if (codedDetails) {
2330
+ const descendantObjects = errorObjectChain.slice(index + 1);
2331
+ const ancestorObjects = errorObjectChain.slice(0, index);
2332
+ const descendantMessage = getFirstNonEmptyMessage(
2333
+ descendantObjects.map((object) => object.message)
2334
+ );
2335
+ const ancestorMessage = getFirstNonEmptyMessage([
2336
+ primitiveMessage,
2337
+ ...ancestorObjects.map((object) => object.message)
2338
+ ]);
2339
+ const reason2 = (_c = (_b = (_a3 = codedDetails.message) != null ? _a3 : descendantMessage) != null ? _b : ancestorMessage) != null ? _c : "Unknown error";
2340
+ return __spreadValues(__spreadValues({
2341
+ reason: reason2,
2342
+ rpcCode: codedDetails.code
2343
+ }, codedDetails.message === void 0 ? {} : { rpcMessage: codedDetails.message }), codedDetails.data === void 0 ? {} : { rpcData: codedDetails.data });
2344
+ }
2345
+ }
2346
+ const reason = (_d = primitiveMessage != null ? primitiveMessage : getFirstNonEmptyMessage(errorObjectChain.map((object) => object.message))) != null ? _d : "Unknown error";
2347
+ return {
2348
+ reason
2349
+ };
2350
+ }
2214
2351
  function toRPCInvokeMethodErr(error) {
2215
- var _a3;
2216
2352
  if (error instanceof RPCInvokeMethodErr) {
2217
2353
  return error;
2218
2354
  }
2219
- const castError = error;
2220
- return new RPCInvokeMethodErr(
2221
- (_a3 = castError.message) != null ? _a3 : "Unknown error",
2222
- castError.code
2223
- );
2355
+ const { reason, rpcCode, rpcMessage, rpcData } = getInvocationErrorDetails(error);
2356
+ return new RPCInvokeMethodErr(reason, rpcCode, rpcMessage, rpcData);
2224
2357
  }
2358
+
2359
+ // src/multichain/rpc/requestRouter.ts
2225
2360
  var _RequestRouter_instances, withAnalyticsTracking_fn, trackWalletActionRequested_fn, trackWalletActionSucceeded_fn, trackWalletActionFailed_fn, trackWalletActionRejected_fn;
2226
2361
  var RequestRouter = class {
2227
2362
  constructor(transport, rpcClient, config, transportType) {
@@ -2241,6 +2376,9 @@ var RequestRouter = class {
2241
2376
  invokeMethod(options) {
2242
2377
  return __async(this, null, function* () {
2243
2378
  const { method } = options.request;
2379
+ if (EIP1193_PASSTHROUGH_METHODS.has(method)) {
2380
+ return this.handleWithEip1193Passthrough(options);
2381
+ }
2244
2382
  if (RPC_HANDLED_METHODS.has(method)) {
2245
2383
  return this.handleWithRpcNode(options);
2246
2384
  }
@@ -2250,6 +2388,29 @@ var RequestRouter = class {
2250
2388
  return this.handleWithWallet(options);
2251
2389
  });
2252
2390
  }
2391
+ /**
2392
+ * Forwards EIP-1193 / legacy provider methods (e.g. `wallet_addEthereumChain`,
2393
+ * `wallet_switchEthereumChain`, `eth_accounts`) directly to the underlying
2394
+ * transport's `sendEip1193Message`, bypassing the multichain
2395
+ * `wallet_invokeMethod` envelope. These methods are wallet-side concerns the
2396
+ * Multichain API does not model, so we forward the raw `{ method, params }`
2397
+ * payload and return the wallet's full JSON-RPC response envelope unchanged.
2398
+ *
2399
+ * Analytics tracking is intentionally skipped here: ecosystem clients
2400
+ * (e.g. `connect-evm`) emit their own `wallet_action_*` events around these
2401
+ * passthrough calls, and adding router-level tracking would double-count.
2402
+ *
2403
+ * @param options
2404
+ */
2405
+ handleWithEip1193Passthrough(options) {
2406
+ return __async(this, null, function* () {
2407
+ const response = yield this.transport.sendEip1193Message({
2408
+ method: options.request.method,
2409
+ params: options.request.params
2410
+ });
2411
+ return response.result;
2412
+ });
2413
+ }
2253
2414
  /**
2254
2415
  * Forwards the request directly to the wallet via the transport.
2255
2416
  *
@@ -2282,12 +2443,7 @@ var RequestRouter = class {
2282
2443
  }
2283
2444
  const response = yield request;
2284
2445
  if (response.error) {
2285
- const { error } = response;
2286
- throw new RPCInvokeMethodErr(
2287
- `RPC Request failed with code ${error.code}: ${error.message}`,
2288
- error.code,
2289
- error.message
2290
- );
2446
+ throw toRPCInvokeMethodErr(response.error);
2291
2447
  }
2292
2448
  return response.result;
2293
2449
  }));
@@ -2341,13 +2497,15 @@ withAnalyticsTracking_fn = function(options, execute) {
2341
2497
  yield __privateMethod(this, _RequestRouter_instances, trackWalletActionSucceeded_fn).call(this, options);
2342
2498
  return result;
2343
2499
  } catch (error) {
2344
- const isRejection = isRejectionError(error);
2500
+ const normalizedError = toRPCInvokeMethodErr(error);
2501
+ const analyticsError = normalizedError.rpcCode === void 0 ? error : normalizedError;
2502
+ const isRejection = isRejectionError(analyticsError);
2345
2503
  if (isRejection) {
2346
2504
  yield __privateMethod(this, _RequestRouter_instances, trackWalletActionRejected_fn).call(this, options);
2347
2505
  } else {
2348
- yield __privateMethod(this, _RequestRouter_instances, trackWalletActionFailed_fn).call(this, options, error);
2506
+ yield __privateMethod(this, _RequestRouter_instances, trackWalletActionFailed_fn).call(this, options, analyticsError);
2349
2507
  }
2350
- throw toRPCInvokeMethodErr(error);
2508
+ throw normalizedError;
2351
2509
  }
2352
2510
  });
2353
2511
  };
@@ -2402,8 +2560,9 @@ init_utils2();
2402
2560
  import {
2403
2561
  getDefaultTransport
2404
2562
  } from "@metamask/multichain-api-client";
2563
+ import { isValidJson as isValidJson2 } from "@metamask/utils";
2405
2564
  var DEFAULT_REQUEST_TIMEOUT = 60 * 1e3;
2406
- var _notificationCallbacks, _transport, _defaultRequestOptions, _pendingRequests, _handleResponseListener, _handleNotificationListener, _DefaultTransport_instances, notifyCallbacks_fn, isMetamaskProviderEvent_fn, handleResponse_fn, handleNotification_fn, setupMessageListener_fn, init_fn;
2565
+ var _notificationCallbacks, _transport, _defaultRequestOptions, _pendingRequests, _handleResponseListener, _handleNotificationListener, _DefaultTransport_instances, notifyCallbacks_fn, parseWalletError_fn, isMetamaskProviderEvent_fn, handleResponse_fn, handleNotification_fn, setupMessageListener_fn, init_fn;
2407
2566
  var DefaultTransport = class {
2408
2567
  constructor() {
2409
2568
  __privateAdd(this, _DefaultTransport_instances);
@@ -2539,7 +2698,11 @@ var DefaultTransport = class {
2539
2698
  }
2540
2699
  request(_0) {
2541
2700
  return __async(this, arguments, function* (request, options = __privateGet(this, _defaultRequestOptions)) {
2542
- return __privateGet(this, _transport).request(request, options);
2701
+ const response = yield __privateGet(this, _transport).request(request, options);
2702
+ if (response.error) {
2703
+ throw __privateMethod(this, _DefaultTransport_instances, parseWalletError_fn).call(this, response.error);
2704
+ }
2705
+ return response;
2543
2706
  });
2544
2707
  }
2545
2708
  onNotification(callback) {
@@ -2583,6 +2746,20 @@ notifyCallbacks_fn = function(data) {
2583
2746
  }
2584
2747
  }
2585
2748
  };
2749
+ parseWalletError_fn = function(errorPayload) {
2750
+ const errorData = errorPayload;
2751
+ const error = new Error(
2752
+ typeof errorData.message === "string" ? errorData.message : "Request failed"
2753
+ );
2754
+ if (typeof errorData.code === "number") {
2755
+ error.code = errorData.code;
2756
+ }
2757
+ const { data } = errorData;
2758
+ if (isValidJson2(data)) {
2759
+ error.data = data;
2760
+ }
2761
+ return error;
2762
+ };
2586
2763
  isMetamaskProviderEvent_fn = function(event) {
2587
2764
  var _a3, _b;
2588
2765
  return ((_b = (_a3 = event == null ? void 0 : event.data) == null ? void 0 : _a3.data) == null ? void 0 : _b.name) === "metamask-provider" && // eslint-disable-next-line no-restricted-globals
@@ -2605,13 +2782,7 @@ handleResponse_fn = function(event) {
2605
2782
  __privateGet(this, _pendingRequests).delete(responseId);
2606
2783
  const response = responseData;
2607
2784
  if ("error" in response && response.error) {
2608
- const error = new Error(
2609
- response.error.message || "Request failed"
2610
- );
2611
- if (typeof response.error.code === "number") {
2612
- error.code = response.error.code;
2613
- }
2614
- pendingRequest.reject(error);
2785
+ pendingRequest.reject(__privateMethod(this, _DefaultTransport_instances, parseWalletError_fn).call(this, response.error));
2615
2786
  } else {
2616
2787
  pendingRequest.resolve(response);
2617
2788
  }
@@ -2649,22 +2820,21 @@ init_fn = function() {
2649
2820
  // src/multichain/transports/multichainApiClientWrapper/index.ts
2650
2821
  init_utils2();
2651
2822
  import { providerErrors } from "@metamask/rpc-errors";
2652
- var _notificationCallbacks2, _MultichainApiClientWrapperTransport_instances, walletCreateSession_fn, walletGetSession_fn, walletRevokeSession_fn, walletInvokeMethod_fn;
2823
+ var _notificationCallbacks2, _getTransport, _MultichainApiClientWrapperTransport_instances, walletCreateSession_fn, walletGetSession_fn, walletRevokeSession_fn, walletInvokeMethod_fn;
2653
2824
  var MultichainApiClientWrapperTransport = class {
2654
- constructor(metamaskConnectMultichain) {
2825
+ constructor(metamaskConnectMultichain, getTransport) {
2655
2826
  this.metamaskConnectMultichain = metamaskConnectMultichain;
2656
2827
  __privateAdd(this, _MultichainApiClientWrapperTransport_instances);
2657
2828
  __privateAdd(this, _notificationCallbacks2, /* @__PURE__ */ new Set());
2829
+ __privateAdd(this, _getTransport);
2830
+ __privateSet(this, _getTransport, getTransport);
2658
2831
  }
2659
2832
  isTransportDefined() {
2660
- try {
2661
- return Boolean(this.metamaskConnectMultichain.transport);
2662
- } catch (_error) {
2663
- return false;
2664
- }
2833
+ return __privateGet(this, _getTransport).call(this) !== void 0;
2665
2834
  }
2666
2835
  isTransportConnected() {
2667
- return this.isTransportDefined() && this.metamaskConnectMultichain.transport.isConnected();
2836
+ var _a3, _b;
2837
+ return (_b = (_a3 = __privateGet(this, _getTransport).call(this)) == null ? void 0 : _a3.isConnected()) != null ? _b : false;
2668
2838
  }
2669
2839
  clearNotificationCallbacks() {
2670
2840
  __privateGet(this, _notificationCallbacks2).clear();
@@ -2680,10 +2850,11 @@ var MultichainApiClientWrapperTransport = class {
2680
2850
  this.notificationListener = void 0;
2681
2851
  }
2682
2852
  setupTransportNotificationListener() {
2683
- if (!this.isTransportDefined() || this.notificationListener) {
2853
+ const transport = __privateGet(this, _getTransport).call(this);
2854
+ if (!transport || this.notificationListener) {
2684
2855
  return;
2685
2856
  }
2686
- this.notificationListener = this.metamaskConnectMultichain.transport.onNotification(
2857
+ this.notificationListener = transport.onNotification(
2687
2858
  this.notifyCallbacks.bind(this)
2688
2859
  );
2689
2860
  }
@@ -2733,6 +2904,7 @@ var MultichainApiClientWrapperTransport = class {
2733
2904
  }
2734
2905
  };
2735
2906
  _notificationCallbacks2 = new WeakMap();
2907
+ _getTransport = new WeakMap();
2736
2908
  _MultichainApiClientWrapperTransport_instances = new WeakSet();
2737
2909
  walletCreateSession_fn = function(request) {
2738
2910
  return __async(this, null, function* () {
@@ -2756,14 +2928,19 @@ walletCreateSession_fn = function(request) {
2756
2928
  accounts,
2757
2929
  createSessionParams.sessionProperties
2758
2930
  );
2759
- return this.metamaskConnectMultichain.transport.request({
2931
+ const transport = __privateGet(this, _getTransport).call(this);
2932
+ if (!transport) {
2933
+ throw new Error("Transport not initialized after connect");
2934
+ }
2935
+ return transport.request({
2760
2936
  method: "wallet_getSession"
2761
2937
  });
2762
2938
  });
2763
2939
  };
2764
2940
  walletGetSession_fn = function(request) {
2765
2941
  return __async(this, null, function* () {
2766
- if (!this.isTransportConnected()) {
2942
+ const transport = __privateGet(this, _getTransport).call(this);
2943
+ if (!(transport == null ? void 0 : transport.isConnected())) {
2767
2944
  return {
2768
2945
  jsonrpc: "2.0",
2769
2946
  id: request.id,
@@ -2772,7 +2949,7 @@ walletGetSession_fn = function(request) {
2772
2949
  }
2773
2950
  };
2774
2951
  }
2775
- return this.metamaskConnectMultichain.transport.request({
2952
+ return transport.request({
2776
2953
  method: "wallet_getSession"
2777
2954
  });
2778
2955
  });
@@ -2850,7 +3027,7 @@ function setupAnalyticsGlobals(options, storage, setAnonId) {
2850
3027
  analytics2.enable();
2851
3028
  });
2852
3029
  }
2853
- var _a2, _provider, _providerTransportWrapper, _transport2, _dappClient, _beforeUnloadListener, _transportType, _listener, _anonId, _sdkInfo, _MetaMaskConnectMultichain_instances, setupAnalytics_fn, onTransportNotification_fn, getStoredTransport_fn, setupTransport_fn, buildConnectionMetadata_fn, init_fn2, createDappClient_fn, setupMWP_fn, onBeforeUnload_fn, createBeforeUnloadListener_fn, renderInstallModalAsync_fn, showInstallModal_fn, headlessConnect_fn, setupDefaultTransport_fn, deeplinkConnect_fn, handleConnection_fn, getCaipSession_fn, openConnectDeeplinkIfNeeded_fn;
3030
+ var _a2, _provider, _providerTransportWrapper, _transport2, _dappClient, _beforeUnloadListener, _transportType, _listener, _anonId, _MetaMaskConnectMultichain_instances, transportOrThrow_fn, _sdkInfo, setupAnalytics_fn, onTransportNotification_fn, getStoredTransport_fn, setupTransport_fn, buildConnectionMetadata_fn, init_fn2, createDappClient_fn, setupMWP_fn, onBeforeUnload_fn, createBeforeUnloadListener_fn, renderInstallModalAsync_fn, showInstallModal_fn, headlessConnect_fn, setupDefaultTransport_fn, deeplinkConnect_fn, handleConnection_fn, getCaipSession_fn, openConnectDeeplinkIfNeeded_fn;
2854
3031
  var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends MultichainCore {
2855
3032
  constructor(options) {
2856
3033
  var _a3, _b, _c, _d;
@@ -2863,9 +3040,7 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
2863
3040
  }),
2864
3041
  analytics: normalizeAnalyticsOptions(options.analytics),
2865
3042
  versions: __spreadValues({
2866
- // typeof guard needed: Metro (React Native) bundles TS source directly,
2867
- // bypassing the tsup build that substitutes __PACKAGE_VERSION__.
2868
- "connect-multichain": false ? "unknown" : "0.15.0"
3043
+ "connect-multichain": getVersion()
2869
3044
  }, (_d = options.versions) != null ? _d : {})
2870
3045
  });
2871
3046
  super(allOptions);
@@ -2881,7 +3056,8 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
2881
3056
  __privateAdd(this, _anonId);
2882
3057
  __privateAdd(this, _sdkInfo, `Sdk/Javascript SdkVersion/${getVersion()} Platform/${getPlatformType()} dApp/${(_a2 = this.options.dapp.url) != null ? _a2 : this.options.dapp.name} dAppTitle/${this.options.dapp.name}`);
2883
3058
  __privateSet(this, _providerTransportWrapper, new MultichainApiClientWrapperTransport(
2884
- this
3059
+ this,
3060
+ () => __privateGet(this, _transport2)
2885
3061
  ));
2886
3062
  __privateSet(this, _provider, getMultichainClient({
2887
3063
  transport: __privateGet(this, _providerTransportWrapper)
@@ -2900,12 +3076,6 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
2900
3076
  get provider() {
2901
3077
  return __privateGet(this, _provider);
2902
3078
  }
2903
- get transport() {
2904
- if (!__privateGet(this, _transport2)) {
2905
- throw new Error("Transport not initialized, establish connection first");
2906
- }
2907
- return __privateGet(this, _transport2);
2908
- }
2909
3079
  get dappClient() {
2910
3080
  if (!__privateGet(this, _dappClient)) {
2911
3081
  throw new Error("DappClient not initialized, establish connection first");
@@ -2919,6 +3089,9 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
2919
3089
  get storage() {
2920
3090
  return this.options.storage;
2921
3091
  }
3092
+ get version() {
3093
+ return getVersion();
3094
+ }
2922
3095
  // Creates a singleton instance of MetaMaskConnectMultichain.
2923
3096
  // If the singleton already exists, it merges the incoming options with the
2924
3097
  // existing singleton options for the following keys: `api.supportedNetworks`,
@@ -2933,6 +3106,11 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
2933
3106
  const existing = globalObject[SINGLETON_KEY];
2934
3107
  if (existing) {
2935
3108
  const instance = yield existing;
3109
+ if (instance.version !== getVersion()) {
3110
+ console.warn(
3111
+ `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.`
3112
+ );
3113
+ }
2936
3114
  instance.mergeOptions(options);
2937
3115
  if (instance instanceof _MetaMaskConnectMultichain) {
2938
3116
  yield __privateMethod(_a3 = instance, _MetaMaskConnectMultichain_instances, setupAnalytics_fn).call(_a3);
@@ -2956,12 +3134,12 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
2956
3134
  }
2957
3135
  yield __privateMethod(_a4 = instance, _MetaMaskConnectMultichain_instances, init_fn2).call(_a4);
2958
3136
  return instance;
2959
- }))();
2960
- globalObject[SINGLETON_KEY] = instancePromise;
2961
- instancePromise.catch((error) => {
3137
+ }))().catch((error) => {
2962
3138
  globalObject[SINGLETON_KEY] = void 0;
2963
3139
  console.error("Error initializing MetaMaskConnectMultichain", error);
3140
+ throw error;
2964
3141
  });
3142
+ globalObject[SINGLETON_KEY] = instancePromise;
2965
3143
  return instancePromise;
2966
3144
  });
2967
3145
  }
@@ -3021,9 +3199,9 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
3021
3199
  forceRequest
3022
3200
  }).then(() => __async(this, null, function* () {
3023
3201
  if (__privateGet(this, _transportType) === "mwp" /* MWP */) {
3024
- return this.storage.setTransport("mwp" /* MWP */);
3202
+ return this.storage.setTransportType("mwp" /* MWP */);
3025
3203
  }
3026
- return this.storage.setTransport("browser" /* Browser */);
3204
+ return this.storage.setTransportType("browser" /* Browser */);
3027
3205
  })), scopes, transportType);
3028
3206
  }
3029
3207
  if (platformType === "in-app-browser" /* MetaMaskMobileWebview */) {
@@ -3052,11 +3230,6 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
3052
3230
  return __privateMethod(this, _MetaMaskConnectMultichain_instances, handleConnection_fn).call(this, __privateMethod(this, _MetaMaskConnectMultichain_instances, showInstallModal_fn).call(this, shouldShowInstallModal, mergedScopes, mergedCaipAccountIds, nonEmptySessionProperties), scopes, transportType);
3053
3231
  });
3054
3232
  }
3055
- emit(event, args) {
3056
- var _a3, _b;
3057
- (_b = (_a3 = this.options.transport) == null ? void 0 : _a3.onNotification) == null ? void 0 : _b.call(_a3, { method: event, params: args });
3058
- super.emit(event, args);
3059
- }
3060
3233
  disconnect() {
3061
3234
  return __async(this, arguments, function* (scopes = []) {
3062
3235
  var _a3, _b, _c;
@@ -3066,7 +3239,7 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
3066
3239
  );
3067
3240
  yield (_a3 = __privateGet(this, _transport2)) == null ? void 0 : _a3.disconnect(scopes);
3068
3241
  if (remainingScopes.length === 0) {
3069
- yield this.storage.removeTransport();
3242
+ yield this.storage.removeTransportType();
3070
3243
  if (__privateGet(this, _transportType) !== "browser" /* Browser */) {
3071
3244
  yield (_b = __privateGet(this, _listener)) == null ? void 0 : _b.call(this);
3072
3245
  (_c = __privateGet(this, _beforeUnloadListener)) == null ? void 0 : _c.call(this);
@@ -3084,7 +3257,8 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
3084
3257
  invokeMethod(request) {
3085
3258
  return __async(this, null, function* () {
3086
3259
  var _a3;
3087
- const { transport, options } = this;
3260
+ const transport = __privateMethod(this, _MetaMaskConnectMultichain_instances, transportOrThrow_fn).call(this);
3261
+ const { options } = this;
3088
3262
  const rpcClient = new RpcClient(options, __privateGet(this, _sdkInfo));
3089
3263
  const requestRouter = new RequestRouter(
3090
3264
  transport,
@@ -3103,7 +3277,7 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
3103
3277
  const shouldOpenDeeplink = secure && !showInstallModal;
3104
3278
  if (shouldOpenDeeplink) {
3105
3279
  setTimeout(() => __async(this, null, function* () {
3106
- const session = yield this.transport.getActiveSession();
3280
+ const session = yield __privateMethod(this, _MetaMaskConnectMultichain_instances, transportOrThrow_fn).call(this).getActiveSession();
3107
3281
  if (!session) {
3108
3282
  throw new Error("No active session found");
3109
3283
  }
@@ -3127,10 +3301,13 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
3127
3301
  this.emit("wallet_sessionChanged", emptySession);
3128
3302
  return;
3129
3303
  }
3130
- const response = yield this.transport.request({
3304
+ const response = yield __privateGet(this, _transport2).request({
3131
3305
  method: "wallet_getSession"
3132
3306
  });
3133
- this.emit("wallet_sessionChanged", (_b = response.result) != null ? _b : emptySession);
3307
+ this.emit(
3308
+ "wallet_sessionChanged",
3309
+ (_b = response.result) != null ? _b : emptySession
3310
+ );
3134
3311
  });
3135
3312
  }
3136
3313
  };
@@ -3142,8 +3319,14 @@ _beforeUnloadListener = new WeakMap();
3142
3319
  _transportType = new WeakMap();
3143
3320
  _listener = new WeakMap();
3144
3321
  _anonId = new WeakMap();
3145
- _sdkInfo = new WeakMap();
3146
3322
  _MetaMaskConnectMultichain_instances = new WeakSet();
3323
+ transportOrThrow_fn = function() {
3324
+ if (!__privateGet(this, _transport2)) {
3325
+ throw new Error("Transport not initialized, establish connection first");
3326
+ }
3327
+ return __privateGet(this, _transport2);
3328
+ };
3329
+ _sdkInfo = new WeakMap();
3147
3330
  setupAnalytics_fn = function() {
3148
3331
  return __async(this, null, function* () {
3149
3332
  yield setupAnalyticsGlobals(this.options, this.storage, (anonId) => {
@@ -3169,7 +3352,7 @@ onTransportNotification_fn = function(payload) {
3169
3352
  };
3170
3353
  getStoredTransport_fn = function() {
3171
3354
  return __async(this, null, function* () {
3172
- const transportType = yield this.storage.getTransport();
3355
+ const transportType = yield this.storage.getTransportType();
3173
3356
  const hasExtensionInstalled = yield hasExtension();
3174
3357
  if (transportType) {
3175
3358
  if (transportType === "browser" /* Browser */) {
@@ -3197,7 +3380,7 @@ getStoredTransport_fn = function() {
3197
3380
  ));
3198
3381
  return apiTransport;
3199
3382
  }
3200
- yield this.storage.removeTransport();
3383
+ yield this.storage.removeTransportType();
3201
3384
  }
3202
3385
  return void 0;
3203
3386
  });
@@ -3207,15 +3390,15 @@ setupTransport_fn = function() {
3207
3390
  var _a3;
3208
3391
  const transport = yield __privateMethod(this, _MetaMaskConnectMultichain_instances, getStoredTransport_fn).call(this);
3209
3392
  if (transport) {
3210
- if (!this.transport.isConnected()) {
3393
+ if (!transport.isConnected()) {
3211
3394
  this.status = "connecting";
3212
- yield this.transport.connect();
3395
+ yield transport.connect();
3213
3396
  }
3214
3397
  this.status = "connected";
3215
3398
  if (__privateGet(this, _transportType) === "mwp" /* MWP */) {
3216
- yield this.storage.setTransport("mwp" /* MWP */);
3399
+ yield this.storage.setTransportType("mwp" /* MWP */);
3217
3400
  } else {
3218
- yield this.storage.setTransport("browser" /* Browser */);
3401
+ yield this.storage.setTransportType("browser" /* Browser */);
3219
3402
  }
3220
3403
  } else {
3221
3404
  this.status = "loaded";
@@ -3224,7 +3407,7 @@ setupTransport_fn = function() {
3224
3407
  if (hasExtensionInstalled && preferExtension) {
3225
3408
  yield __privateMethod(this, _MetaMaskConnectMultichain_instances, setupDefaultTransport_fn).call(this, { persist: false });
3226
3409
  try {
3227
- yield this.transport.init();
3410
+ yield __privateMethod(this, _MetaMaskConnectMultichain_instances, transportOrThrow_fn).call(this).init();
3228
3411
  } catch (error) {
3229
3412
  console.error("Passive init failed:", error);
3230
3413
  }
@@ -3248,7 +3431,7 @@ init_fn2 = function() {
3248
3431
  yield __privateMethod(this, _MetaMaskConnectMultichain_instances, setupAnalytics_fn).call(this);
3249
3432
  yield __privateMethod(this, _MetaMaskConnectMultichain_instances, setupTransport_fn).call(this);
3250
3433
  } catch (error) {
3251
- yield this.storage.removeTransport();
3434
+ yield this.storage.removeTransportType();
3252
3435
  this.status = "pending";
3253
3436
  logger2("MetaMaskSDK error during initialization", error);
3254
3437
  }
@@ -3294,17 +3477,17 @@ setupMWP_fn = function() {
3294
3477
  __privateSet(this, _transport2, apiTransport);
3295
3478
  __privateSet(this, _transportType, "mwp" /* MWP */);
3296
3479
  __privateGet(this, _providerTransportWrapper).setupTransportNotificationListener();
3297
- __privateSet(this, _listener, this.transport.onNotification(
3480
+ __privateSet(this, _listener, apiTransport.onNotification(
3298
3481
  __privateMethod(this, _MetaMaskConnectMultichain_instances, onTransportNotification_fn).bind(this)
3299
3482
  ));
3300
- yield this.storage.setTransport("mwp" /* MWP */);
3483
+ yield this.storage.setTransportType("mwp" /* MWP */);
3301
3484
  });
3302
3485
  };
3303
3486
  onBeforeUnload_fn = function() {
3304
3487
  return __async(this, null, function* () {
3305
3488
  var _a3;
3306
3489
  if ((_a3 = this.options.ui.factory.modal) == null ? void 0 : _a3.isMounted) {
3307
- yield this.storage.removeTransport();
3490
+ yield this.storage.removeTransportType();
3308
3491
  }
3309
3492
  });
3310
3493
  };
@@ -3321,70 +3504,65 @@ createBeforeUnloadListener_fn = function() {
3321
3504
  };
3322
3505
  renderInstallModalAsync_fn = function(desktopPreferred, scopes, caipAccountIds, sessionProperties) {
3323
3506
  return __async(this, null, function* () {
3324
- return new Promise((resolve, reject) => {
3325
- this.options.ui.factory.renderInstallModal(
3326
- desktopPreferred,
3327
- () => __async(this, null, function* () {
3328
- if (this.dappClient.state === "CONNECTED" || this.dappClient.state === "CONNECTING") {
3329
- yield this.dappClient.disconnect();
3330
- }
3331
- return new Promise((_resolve) => {
3332
- this.dappClient.on(
3333
- "session_request",
3334
- (sessionRequest) => {
3335
- _resolve({
3336
- sessionRequest,
3337
- metadata: __privateMethod(this, _MetaMaskConnectMultichain_instances, buildConnectionMetadata_fn).call(this)
3338
- });
3339
- }
3340
- );
3341
- (() => __async(this, null, function* () {
3342
- var _a3;
3343
- try {
3344
- yield this.transport.connect({
3345
- scopes,
3346
- caipAccountIds,
3347
- sessionProperties
3348
- });
3349
- yield this.options.ui.factory.unload();
3350
- (_a3 = this.options.ui.factory.modal) == null ? void 0 : _a3.unmount();
3351
- this.status = "connected";
3352
- yield this.storage.setTransport("mwp" /* MWP */);
3353
- } catch (error) {
3354
- const { ProtocolError, ErrorCode } = yield import("@metamask/mobile-wallet-protocol-core");
3355
- if (error instanceof ProtocolError) {
3356
- if (error.code !== ErrorCode.REQUEST_EXPIRED) {
3357
- this.status = "disconnected";
3358
- yield this.options.ui.factory.unload(error);
3359
- reject(error);
3360
- }
3361
- } else {
3362
- this.status = "disconnected";
3363
- const normalizedError = error instanceof Error ? error : new Error(String(error));
3364
- yield this.options.ui.factory.unload(normalizedError);
3365
- reject(normalizedError);
3366
- }
3367
- }
3368
- }))().catch(() => {
3369
- });
3507
+ const completion = createDeferredPromise2();
3508
+ const createConnectionRequest = () => __async(this, null, function* () {
3509
+ if (this.dappClient.state === "CONNECTED" || this.dappClient.state === "CONNECTING") {
3510
+ yield this.dappClient.disconnect();
3511
+ }
3512
+ const sessionRequestDeferred = createDeferredPromise2();
3513
+ this.dappClient.on(
3514
+ "session_request",
3515
+ (sessionRequest) => {
3516
+ sessionRequestDeferred.resolve({
3517
+ sessionRequest,
3518
+ metadata: __privateMethod(this, _MetaMaskConnectMultichain_instances, buildConnectionMetadata_fn).call(this)
3370
3519
  });
3371
- }),
3372
- (error) => __async(this, null, function* () {
3373
- if (error) {
3374
- yield this.storage.removeTransport();
3375
- reject(error);
3376
- } else {
3377
- yield this.storage.setTransport("mwp" /* MWP */);
3378
- resolve();
3520
+ }
3521
+ );
3522
+ __privateMethod(this, _MetaMaskConnectMultichain_instances, transportOrThrow_fn).call(this).connect({ scopes, caipAccountIds, sessionProperties }).then(() => __async(this, null, function* () {
3523
+ var _a3;
3524
+ yield this.options.ui.factory.unload();
3525
+ (_a3 = this.options.ui.factory.modal) == null ? void 0 : _a3.unmount();
3526
+ this.status = "connected";
3527
+ yield this.storage.setTransportType("mwp" /* MWP */);
3528
+ })).catch((error) => __async(this, null, function* () {
3529
+ const { ProtocolError, ErrorCode } = yield import("@metamask/mobile-wallet-protocol-core");
3530
+ if (error instanceof ProtocolError) {
3531
+ if (error.code !== ErrorCode.REQUEST_EXPIRED) {
3532
+ this.status = "disconnected";
3533
+ yield this.options.ui.factory.unload(error);
3534
+ completion.reject(error);
3379
3535
  }
3380
- }),
3381
- (uri) => {
3382
- this.emit("display_uri", uri);
3536
+ } else {
3537
+ this.status = "disconnected";
3538
+ const normalizedError = error instanceof Error ? error : new Error(String(error));
3539
+ yield this.options.ui.factory.unload(normalizedError);
3540
+ completion.reject(normalizedError);
3383
3541
  }
3384
- ).catch((error) => {
3385
- reject(error instanceof Error ? error : new Error(String(error)));
3386
- });
3542
+ }));
3543
+ return sessionRequestDeferred.promise;
3387
3544
  });
3545
+ this.options.ui.factory.renderInstallModal(
3546
+ desktopPreferred,
3547
+ createConnectionRequest,
3548
+ (error) => __async(this, null, function* () {
3549
+ if (error) {
3550
+ yield this.storage.removeTransportType();
3551
+ completion.reject(error);
3552
+ } else {
3553
+ yield this.storage.setTransportType("mwp" /* MWP */);
3554
+ completion.resolve();
3555
+ }
3556
+ }),
3557
+ (uri) => {
3558
+ this.emit("display_uri", uri);
3559
+ }
3560
+ ).catch((error) => {
3561
+ completion.reject(
3562
+ error instanceof Error ? error : new Error(String(error))
3563
+ );
3564
+ });
3565
+ return completion.promise;
3388
3566
  });
3389
3567
  };
3390
3568
  showInstallModal_fn = function(desktopPreferred, scopes, caipAccountIds, sessionProperties) {
@@ -3400,39 +3578,37 @@ showInstallModal_fn = function(desktopPreferred, scopes, caipAccountIds, session
3400
3578
  };
3401
3579
  headlessConnect_fn = function(scopes, caipAccountIds, sessionProperties) {
3402
3580
  return __async(this, null, function* () {
3403
- return new Promise((resolve, reject) => {
3404
- if (this.dappClient.state === "CONNECTED" || this.dappClient.state === "CONNECTING") {
3405
- this.dappClient.disconnect().catch(() => {
3406
- });
3581
+ if (this.dappClient.state === "CONNECTED" || this.dappClient.state === "CONNECTING") {
3582
+ yield this.dappClient.disconnect().catch(() => void 0);
3583
+ }
3584
+ const onSessionRequest = (sessionRequest) => {
3585
+ const connectionRequest = {
3586
+ sessionRequest,
3587
+ metadata: __privateMethod(this, _MetaMaskConnectMultichain_instances, buildConnectionMetadata_fn).call(this)
3588
+ };
3589
+ const deeplink = this.options.ui.factory.createConnectionDeeplink(connectionRequest);
3590
+ this.emit("display_uri", deeplink);
3591
+ };
3592
+ this.dappClient.on("session_request", onSessionRequest);
3593
+ try {
3594
+ yield __privateMethod(this, _MetaMaskConnectMultichain_instances, transportOrThrow_fn).call(this).connect({
3595
+ scopes,
3596
+ caipAccountIds,
3597
+ sessionProperties
3598
+ });
3599
+ this.status = "connected";
3600
+ yield this.storage.setTransportType("mwp" /* MWP */);
3601
+ } catch (error) {
3602
+ const { ProtocolError } = yield import("@metamask/mobile-wallet-protocol-core");
3603
+ this.status = "disconnected";
3604
+ yield this.storage.removeTransportType();
3605
+ if (error instanceof ProtocolError || error instanceof Error) {
3606
+ throw error;
3407
3607
  }
3408
- this.dappClient.on(
3409
- "session_request",
3410
- (sessionRequest) => {
3411
- const connectionRequest = {
3412
- sessionRequest,
3413
- metadata: __privateMethod(this, _MetaMaskConnectMultichain_instances, buildConnectionMetadata_fn).call(this)
3414
- };
3415
- const deeplink = this.options.ui.factory.createConnectionDeeplink(connectionRequest);
3416
- this.emit("display_uri", deeplink);
3417
- }
3418
- );
3419
- this.transport.connect({ scopes, caipAccountIds, sessionProperties }).then(() => __async(this, null, function* () {
3420
- this.status = "connected";
3421
- yield this.storage.setTransport("mwp" /* MWP */);
3422
- resolve();
3423
- })).catch((error) => __async(this, null, function* () {
3424
- const { ProtocolError } = yield import("@metamask/mobile-wallet-protocol-core");
3425
- if (error instanceof ProtocolError) {
3426
- this.status = "disconnected";
3427
- yield this.storage.removeTransport();
3428
- reject(error);
3429
- } else {
3430
- this.status = "disconnected";
3431
- yield this.storage.removeTransport();
3432
- reject(error instanceof Error ? error : new Error(String(error)));
3433
- }
3434
- }));
3435
- });
3608
+ throw new Error(String(error));
3609
+ } finally {
3610
+ this.dappClient.off("session_request", onSessionRequest);
3611
+ }
3436
3612
  });
3437
3613
  };
3438
3614
  setupDefaultTransport_fn = function() {
@@ -3441,7 +3617,7 @@ setupDefaultTransport_fn = function() {
3441
3617
  return __privateGet(this, _transport2);
3442
3618
  }
3443
3619
  if (options == null ? void 0 : options.persist) {
3444
- yield this.storage.setTransport("browser" /* Browser */);
3620
+ yield this.storage.setTransportType("browser" /* Browser */);
3445
3621
  }
3446
3622
  const transport = new DefaultTransport();
3447
3623
  __privateSet(this, _listener, transport.onNotification(
@@ -3474,7 +3650,7 @@ deeplinkConnect_fn = function(scopes, caipAccountIds, sessionProperties) {
3474
3650
  };
3475
3651
  this.dappClient.on("message", dappClientMessageHandler);
3476
3652
  let timeout;
3477
- if (this.transport.isConnected()) {
3653
+ if (__privateMethod(this, _MetaMaskConnectMultichain_instances, transportOrThrow_fn).call(this).isConnected()) {
3478
3654
  timeout = setTimeout(() => {
3479
3655
  this.openSimpleDeeplinkIfNeeded();
3480
3656
  }, 250);
@@ -3502,8 +3678,8 @@ deeplinkConnect_fn = function(scopes, caipAccountIds, sessionProperties) {
3502
3678
  }
3503
3679
  );
3504
3680
  }
3505
- return this.transport.connect({ scopes, caipAccountIds, sessionProperties }).then(resolve).catch((error) => __async(this, null, function* () {
3506
- yield this.storage.removeTransport();
3681
+ return __privateMethod(this, _MetaMaskConnectMultichain_instances, transportOrThrow_fn).call(this).connect({ scopes, caipAccountIds, sessionProperties }).then(resolve).catch((error) => __async(this, null, function* () {
3682
+ yield this.storage.removeTransportType();
3507
3683
  this.dappClient.off("message", dappClientMessageHandler);
3508
3684
  reject(error instanceof Error ? error : new Error(String(error)));
3509
3685
  })).finally(() => {
@@ -3569,7 +3745,7 @@ getCaipSession_fn = function() {
3569
3745
  };
3570
3746
  if ((_a3 = __privateGet(this, _transport2)) == null ? void 0 : _a3.isConnected()) {
3571
3747
  try {
3572
- const response = yield this.transport.request({
3748
+ const response = yield __privateGet(this, _transport2).request({
3573
3749
  method: "wallet_getSession"
3574
3750
  });
3575
3751
  if (response.result) {
@@ -3663,14 +3839,14 @@ var Store = class extends StoreClient {
3663
3839
  super();
3664
3840
  this.adapter = adapter;
3665
3841
  }
3666
- getTransport() {
3842
+ getTransportType() {
3667
3843
  return __async(this, null, function* () {
3668
3844
  try {
3669
- const transport = yield this.adapter.get("multichain-transport");
3670
- if (!transport) {
3845
+ const transportType = yield this.adapter.get("multichain-transport");
3846
+ if (!transportType) {
3671
3847
  return null;
3672
3848
  }
3673
- return getTransportType(transport);
3849
+ return getTransportType(transportType);
3674
3850
  } catch (err) {
3675
3851
  throw new StorageGetErr(
3676
3852
  this.adapter.platform,
@@ -3680,10 +3856,10 @@ var Store = class extends StoreClient {
3680
3856
  }
3681
3857
  });
3682
3858
  }
3683
- setTransport(transport) {
3859
+ setTransportType(transportType) {
3684
3860
  return __async(this, null, function* () {
3685
3861
  try {
3686
- yield this.adapter.set("multichain-transport", transport);
3862
+ yield this.adapter.set("multichain-transport", transportType);
3687
3863
  } catch (err) {
3688
3864
  throw new StorageSetErr(
3689
3865
  this.adapter.platform,
@@ -3693,7 +3869,7 @@ var Store = class extends StoreClient {
3693
3869
  }
3694
3870
  });
3695
3871
  }
3696
- removeTransport() {
3872
+ removeTransportType() {
3697
3873
  return __async(this, null, function* () {
3698
3874
  try {
3699
3875
  yield this.adapter.delete("multichain-transport");
@@ -3907,7 +4083,11 @@ var BaseModalFactory = class {
3907
4083
  (_a4 = this.displayUriCallback) == null ? void 0 : _a4.call(this, newLink);
3908
4084
  return newLink;
3909
4085
  }),
3910
- onClose: this.onCloseModal.bind(this),
4086
+ onClose: (shouldTerminate) => {
4087
+ this.onCloseModal(shouldTerminate).catch((error) => {
4088
+ console.error("Failed to close modal:", error);
4089
+ });
4090
+ },
3911
4091
  startDesktopOnboarding: this.onStartDesktopOnboarding.bind(this),
3912
4092
  createConnectionRequest,
3913
4093
  onDisplayUri: this.displayUriCallback
@@ -3978,6 +4158,7 @@ Original error: ${error instanceof Error ? error.message : error}`
3978
4158
  }));
3979
4159
  });
3980
4160
  export {
4161
+ EIP1193_PASSTHROUGH_METHODS,
3981
4162
  EventEmitter,
3982
4163
  Modal,
3983
4164
  MultichainCore,
@@ -4005,6 +4186,7 @@ export {
4005
4186
  isEnabled,
4006
4187
  isMetamaskExtensionInstalled,
4007
4188
  isRejectionError,
4008
- isSecure
4189
+ isSecure,
4190
+ packageVersion
4009
4191
  };
4010
4192
  //# sourceMappingURL=connect-multichain.mjs.map