@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 _a2, _b;
591
610
  if ((_b = (_a2 = event == null ? void 0 : event.detail) == null ? void 0 : _a2.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 _a2, _b;
602
- return (_b = (_a2 = provider == null ? void 0 : provider.info) == null ? void 0 : _a2.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 _a2;
624
+ return typeof ((_a2 = provider == null ? void 0 : provider.info) == null ? void 0 : _a2.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
  }))();
@@ -1117,12 +1142,14 @@ var init_analytics = __esm({
1117
1142
 
1118
1143
  // src/domain/utils/index.ts
1119
1144
  function getVersion() {
1120
- return "0.0.0";
1145
+ return packageVersion;
1121
1146
  }
1147
+ var packageVersion;
1122
1148
  var init_utils2 = __esm({
1123
1149
  "src/domain/utils/index.ts"() {
1124
1150
  "use strict";
1125
1151
  init_analytics();
1152
+ packageVersion = false ? "unknown" : "1.1.0";
1126
1153
  }
1127
1154
  });
1128
1155
 
@@ -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 _a2, _b, _c, _d, _e, _f, _g;
1331
- try {
1332
- yield this.waitForWalletSessionIfNotCached();
1333
- const sessionRequest = yield this.request({
1334
- method: "wallet_getSession"
1335
- });
1336
- if (sessionRequest.error) {
1337
- return resumeReject(new Error(sessionRequest.error.message));
1338
- }
1339
- let walletSession = sessionRequest.result;
1340
- if (walletSession && options) {
1341
- const currentScopes = Object.keys(
1342
- (_a2 = walletSession == null ? void 0 : walletSession.sessionScopes) != null ? _a2 : {}
1343
- );
1344
- const proposedScopes = (_b = options == null ? void 0 : options.scopes) != null ? _b : [];
1345
- const proposedCaipAccountIds = (_c = options == null ? void 0 : options.caipAccountIds) != null ? _c : [];
1346
- const hasSameScopesAndAccounts = isSameScopesAndAccounts(
1347
- currentScopes,
1348
- proposedScopes,
1349
- walletSession,
1350
- proposedCaipAccountIds
1351
- );
1352
- if (options.forceRequest || !hasSameScopesAndAccounts) {
1353
- const optionalScopes = addValidAccounts(
1354
- getOptionalScopes((_d = options == null ? void 0 : options.scopes) != null ? _d : []),
1355
- getValidAccounts((_e = options == null ? void 0 : options.caipAccountIds) != null ? _e : [])
1356
- );
1357
- const sessionRequest2 = {
1358
- optionalScopes
1359
- };
1360
- const response = yield this.request({
1361
- method: "wallet_createSession",
1362
- params: sessionRequest2
1363
- });
1364
- if (response.error) {
1365
- return resumeReject(new Error(response.error.message));
1366
- }
1367
- walletSession = response.result;
1368
- }
1369
- } else if (!walletSession) {
1370
- const optionalScopes = addValidAccounts(
1371
- getOptionalScopes((_f = options == null ? void 0 : options.scopes) != null ? _f : []),
1372
- getValidAccounts((_g = options == null ? void 0 : options.caipAccountIds) != null ? _g : [])
1373
- );
1374
- const sessionRequest2 = { optionalScopes };
1375
- const response = yield this.request({
1376
- method: "wallet_createSession",
1377
- params: sessionRequest2
1378
- });
1379
- if (response.error) {
1380
- return resumeReject(new Error(response.error.message));
1381
- }
1382
- walletSession = response.result;
1383
- }
1384
- yield this.removeStoredPendingSessionRequest();
1385
- this.notifyCallbacks({
1386
- method: "wallet_sessionChanged",
1387
- params: walletSession
1388
- });
1389
- return resumeResolve();
1390
- } catch (err) {
1391
- return resumeReject(err);
1392
- }
1393
- });
1394
- }
1395
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 _a2;
1452
- if (this.dappClient.state === "CONNECTED") {
1453
- this.onResumeSuccess(resumeResolve, resumeReject, options);
1454
- } else {
1455
- this.dappClient.once("connected", () => __async(this, null, function* () {
1456
- this.onResumeSuccess(resumeResolve, resumeReject, options);
1457
- }));
1458
- dappClient.resume((_a2 = session == null ? void 0 : session.id) != null ? _a2 : "");
1459
- }
1460
- });
1461
- } else {
1462
- connection = new Promise(
1463
- (resolveConnection, rejectConnection) => {
1464
- var _a2, _b;
1465
- const optionalScopes = addValidAccounts(
1466
- getOptionalScopes((_a2 = options == null ? void 0 : options.scopes) != null ? _a2 : []),
1467
- getValidAccounts((_b = options == null ? void 0 : options.caipAccountIds) != null ? _b : [])
1468
- );
1469
- const sessionRequest = {
1470
- optionalScopes,
1471
- sessionProperties: options == null ? void 0 : options.sessionProperties
1472
- };
1473
- const request = {
1474
- jsonrpc: "2.0",
1475
- id: String(getUniqueRequestId()),
1476
- method: "wallet_createSession",
1477
- params: sessionRequest
1478
- };
1479
- initialConnectionMessageHandler = (message) => __async(this, null, function* () {
1480
- if (typeof message !== "object" || message === null) {
1481
- return;
1482
- }
1483
- if (!("data" in message)) {
1484
- return;
1485
- }
1486
- const messagePayload = message.data;
1487
- const isMatchingId = messagePayload.id === request.id;
1488
- const isMatchingMethod = messagePayload.method === "wallet_createSession" || messagePayload.method === "wallet_sessionChanged";
1489
- if (!isMatchingId && !isMatchingMethod) {
1490
- return;
1491
- }
1492
- if (messagePayload.error) {
1493
- return rejectConnection(
1494
- this.parseWalletError(messagePayload.error)
1495
- );
1496
- }
1497
- yield this.storeWalletSession(
1498
- request,
1499
- messagePayload
1500
- );
1501
- yield this.removeStoredPendingSessionRequest();
1502
- this.notifyCallbacks(messagePayload);
1503
- return resolveConnection();
1504
- });
1505
- this.dappClient.on("message", initialConnectionMessageHandler);
1506
- const platformType = getPlatformType();
1507
- const isQRCodeFlow = [
1508
- "web-desktop" /* DesktopWeb */,
1509
- "nodejs" /* NonBrowser */
1510
- ].includes(platformType);
1511
- const initialPayload = {
1512
- name: MULTICHAIN_PROVIDER_STREAM_NAME,
1513
- data: request
1514
- };
1515
- dappClient.connect({
1516
- mode: "trusted",
1517
- initialPayload: isQRCodeFlow ? void 0 : initialPayload
1518
- }).then(() => __async(this, null, function* () {
1519
- if (isQRCodeFlow) {
1520
- return dappClient.sendRequest(initialPayload);
1521
- }
1522
- return void 0;
1523
- })).catch((error) => {
1524
- if (initialConnectionMessageHandler) {
1525
- this.dappClient.off(
1526
- "message",
1527
- initialConnectionMessageHandler
1528
- );
1529
- }
1530
- rejectConnection(error);
1531
- });
1532
- }
1533
- );
1534
- }
1535
- timeout = setTimeout(
1536
- () => {
1537
- reject(new TransportTimeoutError());
1538
- },
1539
- storedSessionRequestBeforeConnectionAttempt ? this.options.resumeTimeout : this.options.connectionTimeout
1540
- );
1541
- connection.then(resolve).catch(reject);
1542
- }));
1543
- return connectionPromise.catch((error) => __async(this, null, function* () {
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 _a2, _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
+ (_a2 = walletSession == null ? void 0 : walletSession.sessionScopes) != null ? _a2 : {}
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 _a2;
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((_a2 = session.id) != null ? _a2 : "").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 _a2, _b;
1787
+ const { dappClient } = this;
1788
+ const isContinuingPriorAttempt = (yield this.getStoredPendingSessionRequest()) !== null;
1789
+ const connDeferred = createDeferredPromise();
1790
+ const optionalScopes = addValidAccounts(
1791
+ getOptionalScopes((_a2 = options == null ? void 0 : options.scopes) != null ? _a2 : []),
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
 
@@ -2118,6 +2176,7 @@ import { analytics as analytics2 } from "@metamask/analytics";
2118
2176
  import {
2119
2177
  getMultichainClient
2120
2178
  } from "@metamask/multichain-api-client";
2179
+ import { createDeferredPromise as createDeferredPromise2 } from "@metamask/utils";
2121
2180
 
2122
2181
  // src/config/index.ts
2123
2182
  var MWP_RELAY_URL = "wss://mm-sdk-relay.api.cx.metamask.io/connection/websocket";
@@ -2241,17 +2300,93 @@ import { analytics } from "@metamask/analytics";
2241
2300
  init_domain();
2242
2301
  init_utils();
2243
2302
  init_analytics();
2303
+
2304
+ // src/multichain/rpc/invocationError.ts
2305
+ init_domain();
2306
+ import { isValidJson } from "@metamask/utils";
2307
+ var MAX_ERROR_CAUSE_DEPTH = 5;
2308
+ function getErrorObject(value) {
2309
+ if (typeof value === "object" && value !== null) {
2310
+ return value;
2311
+ }
2312
+ return void 0;
2313
+ }
2314
+ function getNumericCode(value) {
2315
+ return typeof value === "number" ? value : void 0;
2316
+ }
2317
+ function getNonEmptyMessage(value) {
2318
+ return typeof value === "string" && value.length > 0 ? value : void 0;
2319
+ }
2320
+ function getJsonData(value) {
2321
+ return value !== void 0 && isValidJson(value) ? value : void 0;
2322
+ }
2323
+ function getFirstNonEmptyMessage(values) {
2324
+ for (const value of values) {
2325
+ const message = getNonEmptyMessage(value);
2326
+ if (message !== void 0) {
2327
+ return message;
2328
+ }
2329
+ }
2330
+ return void 0;
2331
+ }
2332
+ function getErrorObjectChain(errorObject) {
2333
+ const chain = [];
2334
+ let currentObject = errorObject;
2335
+ for (let depth = 0; currentObject !== void 0 && depth < MAX_ERROR_CAUSE_DEPTH; depth += 1) {
2336
+ chain.push(currentObject);
2337
+ currentObject = getErrorObject(currentObject.cause);
2338
+ }
2339
+ return chain;
2340
+ }
2341
+ function getCodedErrorDetails(value) {
2342
+ const code = getNumericCode(value == null ? void 0 : value.code);
2343
+ if (code === void 0) {
2344
+ return void 0;
2345
+ }
2346
+ const message = getNonEmptyMessage(value == null ? void 0 : value.message);
2347
+ const data = getJsonData(value == null ? void 0 : value.data);
2348
+ return __spreadValues(__spreadValues({
2349
+ code
2350
+ }, message === void 0 ? {} : { message }), data === void 0 ? {} : { data });
2351
+ }
2352
+ function getInvocationErrorDetails(error) {
2353
+ var _a2, _b, _c, _d;
2354
+ const errorObject = getErrorObject(error);
2355
+ const errorObjectChain = getErrorObjectChain(errorObject);
2356
+ const primitiveMessage = getNonEmptyMessage(error);
2357
+ for (const [index, currentObject] of errorObjectChain.entries()) {
2358
+ const codedDetails = getCodedErrorDetails(currentObject);
2359
+ if (codedDetails) {
2360
+ const descendantObjects = errorObjectChain.slice(index + 1);
2361
+ const ancestorObjects = errorObjectChain.slice(0, index);
2362
+ const descendantMessage = getFirstNonEmptyMessage(
2363
+ descendantObjects.map((object) => object.message)
2364
+ );
2365
+ const ancestorMessage = getFirstNonEmptyMessage([
2366
+ primitiveMessage,
2367
+ ...ancestorObjects.map((object) => object.message)
2368
+ ]);
2369
+ const reason2 = (_c = (_b = (_a2 = codedDetails.message) != null ? _a2 : descendantMessage) != null ? _b : ancestorMessage) != null ? _c : "Unknown error";
2370
+ return __spreadValues(__spreadValues({
2371
+ reason: reason2,
2372
+ rpcCode: codedDetails.code
2373
+ }, codedDetails.message === void 0 ? {} : { rpcMessage: codedDetails.message }), codedDetails.data === void 0 ? {} : { rpcData: codedDetails.data });
2374
+ }
2375
+ }
2376
+ const reason = (_d = primitiveMessage != null ? primitiveMessage : getFirstNonEmptyMessage(errorObjectChain.map((object) => object.message))) != null ? _d : "Unknown error";
2377
+ return {
2378
+ reason
2379
+ };
2380
+ }
2244
2381
  function toRPCInvokeMethodErr(error) {
2245
- var _a2;
2246
2382
  if (error instanceof RPCInvokeMethodErr) {
2247
2383
  return error;
2248
2384
  }
2249
- const castError = error;
2250
- return new RPCInvokeMethodErr(
2251
- (_a2 = castError.message) != null ? _a2 : "Unknown error",
2252
- castError.code
2253
- );
2385
+ const { reason, rpcCode, rpcMessage, rpcData } = getInvocationErrorDetails(error);
2386
+ return new RPCInvokeMethodErr(reason, rpcCode, rpcMessage, rpcData);
2254
2387
  }
2388
+
2389
+ // src/multichain/rpc/requestRouter.ts
2255
2390
  var _RequestRouter_instances, withAnalyticsTracking_fn, trackWalletActionRequested_fn, trackWalletActionSucceeded_fn, trackWalletActionFailed_fn, trackWalletActionRejected_fn;
2256
2391
  var RequestRouter = class {
2257
2392
  constructor(transport, rpcClient, config, transportType) {
@@ -2271,6 +2406,9 @@ var RequestRouter = class {
2271
2406
  invokeMethod(options) {
2272
2407
  return __async(this, null, function* () {
2273
2408
  const { method } = options.request;
2409
+ if (EIP1193_PASSTHROUGH_METHODS.has(method)) {
2410
+ return this.handleWithEip1193Passthrough(options);
2411
+ }
2274
2412
  if (RPC_HANDLED_METHODS.has(method)) {
2275
2413
  return this.handleWithRpcNode(options);
2276
2414
  }
@@ -2280,6 +2418,29 @@ var RequestRouter = class {
2280
2418
  return this.handleWithWallet(options);
2281
2419
  });
2282
2420
  }
2421
+ /**
2422
+ * Forwards EIP-1193 / legacy provider methods (e.g. `wallet_addEthereumChain`,
2423
+ * `wallet_switchEthereumChain`, `eth_accounts`) directly to the underlying
2424
+ * transport's `sendEip1193Message`, bypassing the multichain
2425
+ * `wallet_invokeMethod` envelope. These methods are wallet-side concerns the
2426
+ * Multichain API does not model, so we forward the raw `{ method, params }`
2427
+ * payload and return the wallet's full JSON-RPC response envelope unchanged.
2428
+ *
2429
+ * Analytics tracking is intentionally skipped here: ecosystem clients
2430
+ * (e.g. `connect-evm`) emit their own `wallet_action_*` events around these
2431
+ * passthrough calls, and adding router-level tracking would double-count.
2432
+ *
2433
+ * @param options
2434
+ */
2435
+ handleWithEip1193Passthrough(options) {
2436
+ return __async(this, null, function* () {
2437
+ const response = yield this.transport.sendEip1193Message({
2438
+ method: options.request.method,
2439
+ params: options.request.params
2440
+ });
2441
+ return response.result;
2442
+ });
2443
+ }
2283
2444
  /**
2284
2445
  * Forwards the request directly to the wallet via the transport.
2285
2446
  *
@@ -2312,12 +2473,7 @@ var RequestRouter = class {
2312
2473
  }
2313
2474
  const response = yield request;
2314
2475
  if (response.error) {
2315
- const { error } = response;
2316
- throw new RPCInvokeMethodErr(
2317
- `RPC Request failed with code ${error.code}: ${error.message}`,
2318
- error.code,
2319
- error.message
2320
- );
2476
+ throw toRPCInvokeMethodErr(response.error);
2321
2477
  }
2322
2478
  return response.result;
2323
2479
  }));
@@ -2371,13 +2527,15 @@ withAnalyticsTracking_fn = function(options, execute) {
2371
2527
  yield __privateMethod(this, _RequestRouter_instances, trackWalletActionSucceeded_fn).call(this, options);
2372
2528
  return result;
2373
2529
  } catch (error) {
2374
- const isRejection = isRejectionError(error);
2530
+ const normalizedError = toRPCInvokeMethodErr(error);
2531
+ const analyticsError = normalizedError.rpcCode === void 0 ? error : normalizedError;
2532
+ const isRejection = isRejectionError(analyticsError);
2375
2533
  if (isRejection) {
2376
2534
  yield __privateMethod(this, _RequestRouter_instances, trackWalletActionRejected_fn).call(this, options);
2377
2535
  } else {
2378
- yield __privateMethod(this, _RequestRouter_instances, trackWalletActionFailed_fn).call(this, options, error);
2536
+ yield __privateMethod(this, _RequestRouter_instances, trackWalletActionFailed_fn).call(this, options, analyticsError);
2379
2537
  }
2380
- throw toRPCInvokeMethodErr(error);
2538
+ throw normalizedError;
2381
2539
  }
2382
2540
  });
2383
2541
  };
@@ -2432,8 +2590,9 @@ init_utils();
2432
2590
  import {
2433
2591
  getDefaultTransport
2434
2592
  } from "@metamask/multichain-api-client";
2593
+ import { isValidJson as isValidJson2 } from "@metamask/utils";
2435
2594
  var DEFAULT_REQUEST_TIMEOUT = 60 * 1e3;
2436
- var _notificationCallbacks, _transport, _defaultRequestOptions, _pendingRequests, _handleResponseListener, _handleNotificationListener, _DefaultTransport_instances, notifyCallbacks_fn, isMetamaskProviderEvent_fn, handleResponse_fn, handleNotification_fn, setupMessageListener_fn, init_fn;
2595
+ var _notificationCallbacks, _transport, _defaultRequestOptions, _pendingRequests, _handleResponseListener, _handleNotificationListener, _DefaultTransport_instances, notifyCallbacks_fn, parseWalletError_fn, isMetamaskProviderEvent_fn, handleResponse_fn, handleNotification_fn, setupMessageListener_fn, init_fn;
2437
2596
  var DefaultTransport = class {
2438
2597
  constructor() {
2439
2598
  __privateAdd(this, _DefaultTransport_instances);
@@ -2569,7 +2728,11 @@ var DefaultTransport = class {
2569
2728
  }
2570
2729
  request(_0) {
2571
2730
  return __async(this, arguments, function* (request, options = __privateGet(this, _defaultRequestOptions)) {
2572
- return __privateGet(this, _transport).request(request, options);
2731
+ const response = yield __privateGet(this, _transport).request(request, options);
2732
+ if (response.error) {
2733
+ throw __privateMethod(this, _DefaultTransport_instances, parseWalletError_fn).call(this, response.error);
2734
+ }
2735
+ return response;
2573
2736
  });
2574
2737
  }
2575
2738
  onNotification(callback) {
@@ -2613,6 +2776,20 @@ notifyCallbacks_fn = function(data) {
2613
2776
  }
2614
2777
  }
2615
2778
  };
2779
+ parseWalletError_fn = function(errorPayload) {
2780
+ const errorData = errorPayload;
2781
+ const error = new Error(
2782
+ typeof errorData.message === "string" ? errorData.message : "Request failed"
2783
+ );
2784
+ if (typeof errorData.code === "number") {
2785
+ error.code = errorData.code;
2786
+ }
2787
+ const { data } = errorData;
2788
+ if (isValidJson2(data)) {
2789
+ error.data = data;
2790
+ }
2791
+ return error;
2792
+ };
2616
2793
  isMetamaskProviderEvent_fn = function(event) {
2617
2794
  var _a2, _b;
2618
2795
  return ((_b = (_a2 = event == null ? void 0 : event.data) == null ? void 0 : _a2.data) == null ? void 0 : _b.name) === "metamask-provider" && // eslint-disable-next-line no-restricted-globals
@@ -2635,13 +2812,7 @@ handleResponse_fn = function(event) {
2635
2812
  __privateGet(this, _pendingRequests).delete(responseId);
2636
2813
  const response = responseData;
2637
2814
  if ("error" in response && response.error) {
2638
- const error = new Error(
2639
- response.error.message || "Request failed"
2640
- );
2641
- if (typeof response.error.code === "number") {
2642
- error.code = response.error.code;
2643
- }
2644
- pendingRequest.reject(error);
2815
+ pendingRequest.reject(__privateMethod(this, _DefaultTransport_instances, parseWalletError_fn).call(this, response.error));
2645
2816
  } else {
2646
2817
  pendingRequest.resolve(response);
2647
2818
  }
@@ -2679,22 +2850,21 @@ init_fn = function() {
2679
2850
  // src/multichain/transports/multichainApiClientWrapper/index.ts
2680
2851
  init_utils();
2681
2852
  import { providerErrors } from "@metamask/rpc-errors";
2682
- var _notificationCallbacks2, _MultichainApiClientWrapperTransport_instances, walletCreateSession_fn, walletGetSession_fn, walletRevokeSession_fn, walletInvokeMethod_fn;
2853
+ var _notificationCallbacks2, _getTransport, _MultichainApiClientWrapperTransport_instances, walletCreateSession_fn, walletGetSession_fn, walletRevokeSession_fn, walletInvokeMethod_fn;
2683
2854
  var MultichainApiClientWrapperTransport = class {
2684
- constructor(metamaskConnectMultichain) {
2855
+ constructor(metamaskConnectMultichain, getTransport) {
2685
2856
  this.metamaskConnectMultichain = metamaskConnectMultichain;
2686
2857
  __privateAdd(this, _MultichainApiClientWrapperTransport_instances);
2687
2858
  __privateAdd(this, _notificationCallbacks2, /* @__PURE__ */ new Set());
2859
+ __privateAdd(this, _getTransport);
2860
+ __privateSet(this, _getTransport, getTransport);
2688
2861
  }
2689
2862
  isTransportDefined() {
2690
- try {
2691
- return Boolean(this.metamaskConnectMultichain.transport);
2692
- } catch (_error) {
2693
- return false;
2694
- }
2863
+ return __privateGet(this, _getTransport).call(this) !== void 0;
2695
2864
  }
2696
2865
  isTransportConnected() {
2697
- return this.isTransportDefined() && this.metamaskConnectMultichain.transport.isConnected();
2866
+ var _a2, _b;
2867
+ return (_b = (_a2 = __privateGet(this, _getTransport).call(this)) == null ? void 0 : _a2.isConnected()) != null ? _b : false;
2698
2868
  }
2699
2869
  clearNotificationCallbacks() {
2700
2870
  __privateGet(this, _notificationCallbacks2).clear();
@@ -2710,10 +2880,11 @@ var MultichainApiClientWrapperTransport = class {
2710
2880
  this.notificationListener = void 0;
2711
2881
  }
2712
2882
  setupTransportNotificationListener() {
2713
- if (!this.isTransportDefined() || this.notificationListener) {
2883
+ const transport = __privateGet(this, _getTransport).call(this);
2884
+ if (!transport || this.notificationListener) {
2714
2885
  return;
2715
2886
  }
2716
- this.notificationListener = this.metamaskConnectMultichain.transport.onNotification(
2887
+ this.notificationListener = transport.onNotification(
2717
2888
  this.notifyCallbacks.bind(this)
2718
2889
  );
2719
2890
  }
@@ -2763,6 +2934,7 @@ var MultichainApiClientWrapperTransport = class {
2763
2934
  }
2764
2935
  };
2765
2936
  _notificationCallbacks2 = new WeakMap();
2937
+ _getTransport = new WeakMap();
2766
2938
  _MultichainApiClientWrapperTransport_instances = new WeakSet();
2767
2939
  walletCreateSession_fn = function(request) {
2768
2940
  return __async(this, null, function* () {
@@ -2786,14 +2958,19 @@ walletCreateSession_fn = function(request) {
2786
2958
  accounts,
2787
2959
  createSessionParams.sessionProperties
2788
2960
  );
2789
- return this.metamaskConnectMultichain.transport.request({
2961
+ const transport = __privateGet(this, _getTransport).call(this);
2962
+ if (!transport) {
2963
+ throw new Error("Transport not initialized after connect");
2964
+ }
2965
+ return transport.request({
2790
2966
  method: "wallet_getSession"
2791
2967
  });
2792
2968
  });
2793
2969
  };
2794
2970
  walletGetSession_fn = function(request) {
2795
2971
  return __async(this, null, function* () {
2796
- if (!this.isTransportConnected()) {
2972
+ const transport = __privateGet(this, _getTransport).call(this);
2973
+ if (!(transport == null ? void 0 : transport.isConnected())) {
2797
2974
  return {
2798
2975
  jsonrpc: "2.0",
2799
2976
  id: request.id,
@@ -2802,7 +2979,7 @@ walletGetSession_fn = function(request) {
2802
2979
  }
2803
2980
  };
2804
2981
  }
2805
- return this.metamaskConnectMultichain.transport.request({
2982
+ return transport.request({
2806
2983
  method: "wallet_getSession"
2807
2984
  });
2808
2985
  });
@@ -2880,7 +3057,7 @@ function setupAnalyticsGlobals(options, storage, setAnonId) {
2880
3057
  analytics2.enable();
2881
3058
  });
2882
3059
  }
2883
- var _a, _provider, _providerTransportWrapper, _transport2, _dappClient, _beforeUnloadListener, _transportType, _listener, _anonId, _sdkInfo, _MetaMaskConnectMultichain_instances, setupAnalytics_fn, onTransportNotification_fn, getStoredTransport_fn, setupTransport_fn, buildConnectionMetadata_fn, init_fn2, createDappClient_fn, setupMWP_fn, onBeforeUnload_fn, createBeforeUnloadListener_fn, renderInstallModalAsync_fn, showInstallModal_fn, headlessConnect_fn, setupDefaultTransport_fn, deeplinkConnect_fn, handleConnection_fn, getCaipSession_fn, openConnectDeeplinkIfNeeded_fn;
3060
+ var _a, _provider, _providerTransportWrapper, _transport2, _dappClient, _beforeUnloadListener, _transportType, _listener, _anonId, _MetaMaskConnectMultichain_instances, transportOrThrow_fn, _sdkInfo, setupAnalytics_fn, onTransportNotification_fn, getStoredTransport_fn, setupTransport_fn, buildConnectionMetadata_fn, init_fn2, createDappClient_fn, setupMWP_fn, onBeforeUnload_fn, createBeforeUnloadListener_fn, renderInstallModalAsync_fn, showInstallModal_fn, headlessConnect_fn, setupDefaultTransport_fn, deeplinkConnect_fn, handleConnection_fn, getCaipSession_fn, openConnectDeeplinkIfNeeded_fn;
2884
3061
  var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends MultichainCore {
2885
3062
  constructor(options) {
2886
3063
  var _a2, _b, _c, _d;
@@ -2893,9 +3070,7 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
2893
3070
  }),
2894
3071
  analytics: normalizeAnalyticsOptions(options.analytics),
2895
3072
  versions: __spreadValues({
2896
- // typeof guard needed: Metro (React Native) bundles TS source directly,
2897
- // bypassing the tsup build that substitutes __PACKAGE_VERSION__.
2898
- "connect-multichain": false ? "unknown" : "0.15.0"
3073
+ "connect-multichain": getVersion()
2899
3074
  }, (_d = options.versions) != null ? _d : {})
2900
3075
  });
2901
3076
  super(allOptions);
@@ -2911,7 +3086,8 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
2911
3086
  __privateAdd(this, _anonId);
2912
3087
  __privateAdd(this, _sdkInfo, `Sdk/Javascript SdkVersion/${getVersion()} Platform/${getPlatformType()} dApp/${(_a = this.options.dapp.url) != null ? _a : this.options.dapp.name} dAppTitle/${this.options.dapp.name}`);
2913
3088
  __privateSet(this, _providerTransportWrapper, new MultichainApiClientWrapperTransport(
2914
- this
3089
+ this,
3090
+ () => __privateGet(this, _transport2)
2915
3091
  ));
2916
3092
  __privateSet(this, _provider, getMultichainClient({
2917
3093
  transport: __privateGet(this, _providerTransportWrapper)
@@ -2930,12 +3106,6 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
2930
3106
  get provider() {
2931
3107
  return __privateGet(this, _provider);
2932
3108
  }
2933
- get transport() {
2934
- if (!__privateGet(this, _transport2)) {
2935
- throw new Error("Transport not initialized, establish connection first");
2936
- }
2937
- return __privateGet(this, _transport2);
2938
- }
2939
3109
  get dappClient() {
2940
3110
  if (!__privateGet(this, _dappClient)) {
2941
3111
  throw new Error("DappClient not initialized, establish connection first");
@@ -2949,6 +3119,9 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
2949
3119
  get storage() {
2950
3120
  return this.options.storage;
2951
3121
  }
3122
+ get version() {
3123
+ return getVersion();
3124
+ }
2952
3125
  // Creates a singleton instance of MetaMaskConnectMultichain.
2953
3126
  // If the singleton already exists, it merges the incoming options with the
2954
3127
  // existing singleton options for the following keys: `api.supportedNetworks`,
@@ -2963,6 +3136,11 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
2963
3136
  const existing = globalObject[SINGLETON_KEY];
2964
3137
  if (existing) {
2965
3138
  const instance = yield existing;
3139
+ if (instance.version !== getVersion()) {
3140
+ console.warn(
3141
+ `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.`
3142
+ );
3143
+ }
2966
3144
  instance.mergeOptions(options);
2967
3145
  if (instance instanceof _MetaMaskConnectMultichain) {
2968
3146
  yield __privateMethod(_a2 = instance, _MetaMaskConnectMultichain_instances, setupAnalytics_fn).call(_a2);
@@ -2986,12 +3164,12 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
2986
3164
  }
2987
3165
  yield __privateMethod(_a3 = instance, _MetaMaskConnectMultichain_instances, init_fn2).call(_a3);
2988
3166
  return instance;
2989
- }))();
2990
- globalObject[SINGLETON_KEY] = instancePromise;
2991
- instancePromise.catch((error) => {
3167
+ }))().catch((error) => {
2992
3168
  globalObject[SINGLETON_KEY] = void 0;
2993
3169
  console.error("Error initializing MetaMaskConnectMultichain", error);
3170
+ throw error;
2994
3171
  });
3172
+ globalObject[SINGLETON_KEY] = instancePromise;
2995
3173
  return instancePromise;
2996
3174
  });
2997
3175
  }
@@ -3051,9 +3229,9 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
3051
3229
  forceRequest
3052
3230
  }).then(() => __async(this, null, function* () {
3053
3231
  if (__privateGet(this, _transportType) === "mwp" /* MWP */) {
3054
- return this.storage.setTransport("mwp" /* MWP */);
3232
+ return this.storage.setTransportType("mwp" /* MWP */);
3055
3233
  }
3056
- return this.storage.setTransport("browser" /* Browser */);
3234
+ return this.storage.setTransportType("browser" /* Browser */);
3057
3235
  })), scopes, transportType);
3058
3236
  }
3059
3237
  if (platformType === "in-app-browser" /* MetaMaskMobileWebview */) {
@@ -3082,11 +3260,6 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
3082
3260
  return __privateMethod(this, _MetaMaskConnectMultichain_instances, handleConnection_fn).call(this, __privateMethod(this, _MetaMaskConnectMultichain_instances, showInstallModal_fn).call(this, shouldShowInstallModal, mergedScopes, mergedCaipAccountIds, nonEmptySessionProperties), scopes, transportType);
3083
3261
  });
3084
3262
  }
3085
- emit(event, args) {
3086
- var _a2, _b;
3087
- (_b = (_a2 = this.options.transport) == null ? void 0 : _a2.onNotification) == null ? void 0 : _b.call(_a2, { method: event, params: args });
3088
- super.emit(event, args);
3089
- }
3090
3263
  disconnect() {
3091
3264
  return __async(this, arguments, function* (scopes = []) {
3092
3265
  var _a2, _b, _c;
@@ -3096,7 +3269,7 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
3096
3269
  );
3097
3270
  yield (_a2 = __privateGet(this, _transport2)) == null ? void 0 : _a2.disconnect(scopes);
3098
3271
  if (remainingScopes.length === 0) {
3099
- yield this.storage.removeTransport();
3272
+ yield this.storage.removeTransportType();
3100
3273
  if (__privateGet(this, _transportType) !== "browser" /* Browser */) {
3101
3274
  yield (_b = __privateGet(this, _listener)) == null ? void 0 : _b.call(this);
3102
3275
  (_c = __privateGet(this, _beforeUnloadListener)) == null ? void 0 : _c.call(this);
@@ -3114,7 +3287,8 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
3114
3287
  invokeMethod(request) {
3115
3288
  return __async(this, null, function* () {
3116
3289
  var _a2;
3117
- const { transport, options } = this;
3290
+ const transport = __privateMethod(this, _MetaMaskConnectMultichain_instances, transportOrThrow_fn).call(this);
3291
+ const { options } = this;
3118
3292
  const rpcClient = new RpcClient(options, __privateGet(this, _sdkInfo));
3119
3293
  const requestRouter = new RequestRouter(
3120
3294
  transport,
@@ -3133,7 +3307,7 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
3133
3307
  const shouldOpenDeeplink = secure && !showInstallModal;
3134
3308
  if (shouldOpenDeeplink) {
3135
3309
  setTimeout(() => __async(this, null, function* () {
3136
- const session = yield this.transport.getActiveSession();
3310
+ const session = yield __privateMethod(this, _MetaMaskConnectMultichain_instances, transportOrThrow_fn).call(this).getActiveSession();
3137
3311
  if (!session) {
3138
3312
  throw new Error("No active session found");
3139
3313
  }
@@ -3157,10 +3331,13 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
3157
3331
  this.emit("wallet_sessionChanged", emptySession);
3158
3332
  return;
3159
3333
  }
3160
- const response = yield this.transport.request({
3334
+ const response = yield __privateGet(this, _transport2).request({
3161
3335
  method: "wallet_getSession"
3162
3336
  });
3163
- this.emit("wallet_sessionChanged", (_b = response.result) != null ? _b : emptySession);
3337
+ this.emit(
3338
+ "wallet_sessionChanged",
3339
+ (_b = response.result) != null ? _b : emptySession
3340
+ );
3164
3341
  });
3165
3342
  }
3166
3343
  };
@@ -3172,8 +3349,14 @@ _beforeUnloadListener = new WeakMap();
3172
3349
  _transportType = new WeakMap();
3173
3350
  _listener = new WeakMap();
3174
3351
  _anonId = new WeakMap();
3175
- _sdkInfo = new WeakMap();
3176
3352
  _MetaMaskConnectMultichain_instances = new WeakSet();
3353
+ transportOrThrow_fn = function() {
3354
+ if (!__privateGet(this, _transport2)) {
3355
+ throw new Error("Transport not initialized, establish connection first");
3356
+ }
3357
+ return __privateGet(this, _transport2);
3358
+ };
3359
+ _sdkInfo = new WeakMap();
3177
3360
  setupAnalytics_fn = function() {
3178
3361
  return __async(this, null, function* () {
3179
3362
  yield setupAnalyticsGlobals(this.options, this.storage, (anonId) => {
@@ -3199,7 +3382,7 @@ onTransportNotification_fn = function(payload) {
3199
3382
  };
3200
3383
  getStoredTransport_fn = function() {
3201
3384
  return __async(this, null, function* () {
3202
- const transportType = yield this.storage.getTransport();
3385
+ const transportType = yield this.storage.getTransportType();
3203
3386
  const hasExtensionInstalled = yield hasExtension();
3204
3387
  if (transportType) {
3205
3388
  if (transportType === "browser" /* Browser */) {
@@ -3227,7 +3410,7 @@ getStoredTransport_fn = function() {
3227
3410
  ));
3228
3411
  return apiTransport;
3229
3412
  }
3230
- yield this.storage.removeTransport();
3413
+ yield this.storage.removeTransportType();
3231
3414
  }
3232
3415
  return void 0;
3233
3416
  });
@@ -3237,15 +3420,15 @@ setupTransport_fn = function() {
3237
3420
  var _a2;
3238
3421
  const transport = yield __privateMethod(this, _MetaMaskConnectMultichain_instances, getStoredTransport_fn).call(this);
3239
3422
  if (transport) {
3240
- if (!this.transport.isConnected()) {
3423
+ if (!transport.isConnected()) {
3241
3424
  this.status = "connecting";
3242
- yield this.transport.connect();
3425
+ yield transport.connect();
3243
3426
  }
3244
3427
  this.status = "connected";
3245
3428
  if (__privateGet(this, _transportType) === "mwp" /* MWP */) {
3246
- yield this.storage.setTransport("mwp" /* MWP */);
3429
+ yield this.storage.setTransportType("mwp" /* MWP */);
3247
3430
  } else {
3248
- yield this.storage.setTransport("browser" /* Browser */);
3431
+ yield this.storage.setTransportType("browser" /* Browser */);
3249
3432
  }
3250
3433
  } else {
3251
3434
  this.status = "loaded";
@@ -3254,7 +3437,7 @@ setupTransport_fn = function() {
3254
3437
  if (hasExtensionInstalled && preferExtension) {
3255
3438
  yield __privateMethod(this, _MetaMaskConnectMultichain_instances, setupDefaultTransport_fn).call(this, { persist: false });
3256
3439
  try {
3257
- yield this.transport.init();
3440
+ yield __privateMethod(this, _MetaMaskConnectMultichain_instances, transportOrThrow_fn).call(this).init();
3258
3441
  } catch (error) {
3259
3442
  console.error("Passive init failed:", error);
3260
3443
  }
@@ -3278,7 +3461,7 @@ init_fn2 = function() {
3278
3461
  yield __privateMethod(this, _MetaMaskConnectMultichain_instances, setupAnalytics_fn).call(this);
3279
3462
  yield __privateMethod(this, _MetaMaskConnectMultichain_instances, setupTransport_fn).call(this);
3280
3463
  } catch (error) {
3281
- yield this.storage.removeTransport();
3464
+ yield this.storage.removeTransportType();
3282
3465
  this.status = "pending";
3283
3466
  logger2("MetaMaskSDK error during initialization", error);
3284
3467
  }
@@ -3324,17 +3507,17 @@ setupMWP_fn = function() {
3324
3507
  __privateSet(this, _transport2, apiTransport);
3325
3508
  __privateSet(this, _transportType, "mwp" /* MWP */);
3326
3509
  __privateGet(this, _providerTransportWrapper).setupTransportNotificationListener();
3327
- __privateSet(this, _listener, this.transport.onNotification(
3510
+ __privateSet(this, _listener, apiTransport.onNotification(
3328
3511
  __privateMethod(this, _MetaMaskConnectMultichain_instances, onTransportNotification_fn).bind(this)
3329
3512
  ));
3330
- yield this.storage.setTransport("mwp" /* MWP */);
3513
+ yield this.storage.setTransportType("mwp" /* MWP */);
3331
3514
  });
3332
3515
  };
3333
3516
  onBeforeUnload_fn = function() {
3334
3517
  return __async(this, null, function* () {
3335
3518
  var _a2;
3336
3519
  if ((_a2 = this.options.ui.factory.modal) == null ? void 0 : _a2.isMounted) {
3337
- yield this.storage.removeTransport();
3520
+ yield this.storage.removeTransportType();
3338
3521
  }
3339
3522
  });
3340
3523
  };
@@ -3351,70 +3534,65 @@ createBeforeUnloadListener_fn = function() {
3351
3534
  };
3352
3535
  renderInstallModalAsync_fn = function(desktopPreferred, scopes, caipAccountIds, sessionProperties) {
3353
3536
  return __async(this, null, function* () {
3354
- return new Promise((resolve, reject) => {
3355
- this.options.ui.factory.renderInstallModal(
3356
- desktopPreferred,
3357
- () => __async(this, null, function* () {
3358
- if (this.dappClient.state === "CONNECTED" || this.dappClient.state === "CONNECTING") {
3359
- yield this.dappClient.disconnect();
3360
- }
3361
- return new Promise((_resolve) => {
3362
- this.dappClient.on(
3363
- "session_request",
3364
- (sessionRequest) => {
3365
- _resolve({
3366
- sessionRequest,
3367
- metadata: __privateMethod(this, _MetaMaskConnectMultichain_instances, buildConnectionMetadata_fn).call(this)
3368
- });
3369
- }
3370
- );
3371
- (() => __async(this, null, function* () {
3372
- var _a2;
3373
- try {
3374
- yield this.transport.connect({
3375
- scopes,
3376
- caipAccountIds,
3377
- sessionProperties
3378
- });
3379
- yield this.options.ui.factory.unload();
3380
- (_a2 = this.options.ui.factory.modal) == null ? void 0 : _a2.unmount();
3381
- this.status = "connected";
3382
- yield this.storage.setTransport("mwp" /* MWP */);
3383
- } catch (error) {
3384
- const { ProtocolError, ErrorCode } = yield import("@metamask/mobile-wallet-protocol-core");
3385
- if (error instanceof ProtocolError) {
3386
- if (error.code !== ErrorCode.REQUEST_EXPIRED) {
3387
- this.status = "disconnected";
3388
- yield this.options.ui.factory.unload(error);
3389
- reject(error);
3390
- }
3391
- } else {
3392
- this.status = "disconnected";
3393
- const normalizedError = error instanceof Error ? error : new Error(String(error));
3394
- yield this.options.ui.factory.unload(normalizedError);
3395
- reject(normalizedError);
3396
- }
3397
- }
3398
- }))().catch(() => {
3399
- });
3537
+ const completion = createDeferredPromise2();
3538
+ const createConnectionRequest = () => __async(this, null, function* () {
3539
+ if (this.dappClient.state === "CONNECTED" || this.dappClient.state === "CONNECTING") {
3540
+ yield this.dappClient.disconnect();
3541
+ }
3542
+ const sessionRequestDeferred = createDeferredPromise2();
3543
+ this.dappClient.on(
3544
+ "session_request",
3545
+ (sessionRequest) => {
3546
+ sessionRequestDeferred.resolve({
3547
+ sessionRequest,
3548
+ metadata: __privateMethod(this, _MetaMaskConnectMultichain_instances, buildConnectionMetadata_fn).call(this)
3400
3549
  });
3401
- }),
3402
- (error) => __async(this, null, function* () {
3403
- if (error) {
3404
- yield this.storage.removeTransport();
3405
- reject(error);
3406
- } else {
3407
- yield this.storage.setTransport("mwp" /* MWP */);
3408
- resolve();
3550
+ }
3551
+ );
3552
+ __privateMethod(this, _MetaMaskConnectMultichain_instances, transportOrThrow_fn).call(this).connect({ scopes, caipAccountIds, sessionProperties }).then(() => __async(this, null, function* () {
3553
+ var _a2;
3554
+ yield this.options.ui.factory.unload();
3555
+ (_a2 = this.options.ui.factory.modal) == null ? void 0 : _a2.unmount();
3556
+ this.status = "connected";
3557
+ yield this.storage.setTransportType("mwp" /* MWP */);
3558
+ })).catch((error) => __async(this, null, function* () {
3559
+ const { ProtocolError, ErrorCode } = yield import("@metamask/mobile-wallet-protocol-core");
3560
+ if (error instanceof ProtocolError) {
3561
+ if (error.code !== ErrorCode.REQUEST_EXPIRED) {
3562
+ this.status = "disconnected";
3563
+ yield this.options.ui.factory.unload(error);
3564
+ completion.reject(error);
3409
3565
  }
3410
- }),
3411
- (uri) => {
3412
- this.emit("display_uri", uri);
3566
+ } else {
3567
+ this.status = "disconnected";
3568
+ const normalizedError = error instanceof Error ? error : new Error(String(error));
3569
+ yield this.options.ui.factory.unload(normalizedError);
3570
+ completion.reject(normalizedError);
3413
3571
  }
3414
- ).catch((error) => {
3415
- reject(error instanceof Error ? error : new Error(String(error)));
3416
- });
3572
+ }));
3573
+ return sessionRequestDeferred.promise;
3417
3574
  });
3575
+ this.options.ui.factory.renderInstallModal(
3576
+ desktopPreferred,
3577
+ createConnectionRequest,
3578
+ (error) => __async(this, null, function* () {
3579
+ if (error) {
3580
+ yield this.storage.removeTransportType();
3581
+ completion.reject(error);
3582
+ } else {
3583
+ yield this.storage.setTransportType("mwp" /* MWP */);
3584
+ completion.resolve();
3585
+ }
3586
+ }),
3587
+ (uri) => {
3588
+ this.emit("display_uri", uri);
3589
+ }
3590
+ ).catch((error) => {
3591
+ completion.reject(
3592
+ error instanceof Error ? error : new Error(String(error))
3593
+ );
3594
+ });
3595
+ return completion.promise;
3418
3596
  });
3419
3597
  };
3420
3598
  showInstallModal_fn = function(desktopPreferred, scopes, caipAccountIds, sessionProperties) {
@@ -3430,39 +3608,37 @@ showInstallModal_fn = function(desktopPreferred, scopes, caipAccountIds, session
3430
3608
  };
3431
3609
  headlessConnect_fn = function(scopes, caipAccountIds, sessionProperties) {
3432
3610
  return __async(this, null, function* () {
3433
- return new Promise((resolve, reject) => {
3434
- if (this.dappClient.state === "CONNECTED" || this.dappClient.state === "CONNECTING") {
3435
- this.dappClient.disconnect().catch(() => {
3436
- });
3611
+ if (this.dappClient.state === "CONNECTED" || this.dappClient.state === "CONNECTING") {
3612
+ yield this.dappClient.disconnect().catch(() => void 0);
3613
+ }
3614
+ const onSessionRequest = (sessionRequest) => {
3615
+ const connectionRequest = {
3616
+ sessionRequest,
3617
+ metadata: __privateMethod(this, _MetaMaskConnectMultichain_instances, buildConnectionMetadata_fn).call(this)
3618
+ };
3619
+ const deeplink = this.options.ui.factory.createConnectionDeeplink(connectionRequest);
3620
+ this.emit("display_uri", deeplink);
3621
+ };
3622
+ this.dappClient.on("session_request", onSessionRequest);
3623
+ try {
3624
+ yield __privateMethod(this, _MetaMaskConnectMultichain_instances, transportOrThrow_fn).call(this).connect({
3625
+ scopes,
3626
+ caipAccountIds,
3627
+ sessionProperties
3628
+ });
3629
+ this.status = "connected";
3630
+ yield this.storage.setTransportType("mwp" /* MWP */);
3631
+ } catch (error) {
3632
+ const { ProtocolError } = yield import("@metamask/mobile-wallet-protocol-core");
3633
+ this.status = "disconnected";
3634
+ yield this.storage.removeTransportType();
3635
+ if (error instanceof ProtocolError || error instanceof Error) {
3636
+ throw error;
3437
3637
  }
3438
- this.dappClient.on(
3439
- "session_request",
3440
- (sessionRequest) => {
3441
- const connectionRequest = {
3442
- sessionRequest,
3443
- metadata: __privateMethod(this, _MetaMaskConnectMultichain_instances, buildConnectionMetadata_fn).call(this)
3444
- };
3445
- const deeplink = this.options.ui.factory.createConnectionDeeplink(connectionRequest);
3446
- this.emit("display_uri", deeplink);
3447
- }
3448
- );
3449
- this.transport.connect({ scopes, caipAccountIds, sessionProperties }).then(() => __async(this, null, function* () {
3450
- this.status = "connected";
3451
- yield this.storage.setTransport("mwp" /* MWP */);
3452
- resolve();
3453
- })).catch((error) => __async(this, null, function* () {
3454
- const { ProtocolError } = yield import("@metamask/mobile-wallet-protocol-core");
3455
- if (error instanceof ProtocolError) {
3456
- this.status = "disconnected";
3457
- yield this.storage.removeTransport();
3458
- reject(error);
3459
- } else {
3460
- this.status = "disconnected";
3461
- yield this.storage.removeTransport();
3462
- reject(error instanceof Error ? error : new Error(String(error)));
3463
- }
3464
- }));
3465
- });
3638
+ throw new Error(String(error));
3639
+ } finally {
3640
+ this.dappClient.off("session_request", onSessionRequest);
3641
+ }
3466
3642
  });
3467
3643
  };
3468
3644
  setupDefaultTransport_fn = function() {
@@ -3471,7 +3647,7 @@ setupDefaultTransport_fn = function() {
3471
3647
  return __privateGet(this, _transport2);
3472
3648
  }
3473
3649
  if (options == null ? void 0 : options.persist) {
3474
- yield this.storage.setTransport("browser" /* Browser */);
3650
+ yield this.storage.setTransportType("browser" /* Browser */);
3475
3651
  }
3476
3652
  const transport = new DefaultTransport();
3477
3653
  __privateSet(this, _listener, transport.onNotification(
@@ -3504,7 +3680,7 @@ deeplinkConnect_fn = function(scopes, caipAccountIds, sessionProperties) {
3504
3680
  };
3505
3681
  this.dappClient.on("message", dappClientMessageHandler);
3506
3682
  let timeout;
3507
- if (this.transport.isConnected()) {
3683
+ if (__privateMethod(this, _MetaMaskConnectMultichain_instances, transportOrThrow_fn).call(this).isConnected()) {
3508
3684
  timeout = setTimeout(() => {
3509
3685
  this.openSimpleDeeplinkIfNeeded();
3510
3686
  }, 250);
@@ -3532,8 +3708,8 @@ deeplinkConnect_fn = function(scopes, caipAccountIds, sessionProperties) {
3532
3708
  }
3533
3709
  );
3534
3710
  }
3535
- return this.transport.connect({ scopes, caipAccountIds, sessionProperties }).then(resolve).catch((error) => __async(this, null, function* () {
3536
- yield this.storage.removeTransport();
3711
+ return __privateMethod(this, _MetaMaskConnectMultichain_instances, transportOrThrow_fn).call(this).connect({ scopes, caipAccountIds, sessionProperties }).then(resolve).catch((error) => __async(this, null, function* () {
3712
+ yield this.storage.removeTransportType();
3537
3713
  this.dappClient.off("message", dappClientMessageHandler);
3538
3714
  reject(error instanceof Error ? error : new Error(String(error)));
3539
3715
  })).finally(() => {
@@ -3599,7 +3775,7 @@ getCaipSession_fn = function() {
3599
3775
  };
3600
3776
  if ((_a2 = __privateGet(this, _transport2)) == null ? void 0 : _a2.isConnected()) {
3601
3777
  try {
3602
- const response = yield this.transport.request({
3778
+ const response = yield __privateGet(this, _transport2).request({
3603
3779
  method: "wallet_getSession"
3604
3780
  });
3605
3781
  if (response.result) {
@@ -3693,14 +3869,14 @@ var Store = class extends StoreClient {
3693
3869
  super();
3694
3870
  this.adapter = adapter;
3695
3871
  }
3696
- getTransport() {
3872
+ getTransportType() {
3697
3873
  return __async(this, null, function* () {
3698
3874
  try {
3699
- const transport = yield this.adapter.get("multichain-transport");
3700
- if (!transport) {
3875
+ const transportType = yield this.adapter.get("multichain-transport");
3876
+ if (!transportType) {
3701
3877
  return null;
3702
3878
  }
3703
- return getTransportType(transport);
3879
+ return getTransportType(transportType);
3704
3880
  } catch (err) {
3705
3881
  throw new StorageGetErr(
3706
3882
  this.adapter.platform,
@@ -3710,10 +3886,10 @@ var Store = class extends StoreClient {
3710
3886
  }
3711
3887
  });
3712
3888
  }
3713
- setTransport(transport) {
3889
+ setTransportType(transportType) {
3714
3890
  return __async(this, null, function* () {
3715
3891
  try {
3716
- yield this.adapter.set("multichain-transport", transport);
3892
+ yield this.adapter.set("multichain-transport", transportType);
3717
3893
  } catch (err) {
3718
3894
  throw new StorageSetErr(
3719
3895
  this.adapter.platform,
@@ -3723,7 +3899,7 @@ var Store = class extends StoreClient {
3723
3899
  }
3724
3900
  });
3725
3901
  }
3726
- removeTransport() {
3902
+ removeTransportType() {
3727
3903
  return __async(this, null, function* () {
3728
3904
  try {
3729
3905
  yield this.adapter.delete("multichain-transport");
@@ -3937,7 +4113,11 @@ var BaseModalFactory = class {
3937
4113
  (_a3 = this.displayUriCallback) == null ? void 0 : _a3.call(this, newLink);
3938
4114
  return newLink;
3939
4115
  }),
3940
- onClose: this.onCloseModal.bind(this),
4116
+ onClose: (shouldTerminate) => {
4117
+ this.onCloseModal(shouldTerminate).catch((error) => {
4118
+ console.error("Failed to close modal:", error);
4119
+ });
4120
+ },
3941
4121
  startDesktopOnboarding: this.onStartDesktopOnboarding.bind(this),
3942
4122
  createConnectionRequest,
3943
4123
  onDisplayUri: this.displayUriCallback
@@ -3975,7 +4155,7 @@ function preload() {
3975
4155
  }
3976
4156
  try {
3977
4157
  const { defineCustomElements } = yield import("@metamask/multichain-ui/loader");
3978
- yield defineCustomElements();
4158
+ defineCustomElements();
3979
4159
  } catch (error) {
3980
4160
  console.error("Failed to load customElements:", error);
3981
4161
  }
@@ -4013,6 +4193,7 @@ var createMultichainClient = (options) => __async(null, null, function* () {
4013
4193
  }));
4014
4194
  });
4015
4195
  export {
4196
+ EIP1193_PASSTHROUGH_METHODS,
4016
4197
  EventEmitter,
4017
4198
  Modal,
4018
4199
  MultichainCore,
@@ -4040,6 +4221,7 @@ export {
4040
4221
  isEnabled,
4041
4222
  isMetamaskExtensionInstalled,
4042
4223
  isRejectionError,
4043
- isSecure
4224
+ isSecure,
4225
+ packageVersion
4044
4226
  };
4045
4227
  //# sourceMappingURL=connect-multichain.mjs.map