@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
 
@@ -1981,9 +2039,7 @@ var init_install = __esm({
1981
2039
  mount() {
1982
2040
  var _a3;
1983
2041
  const { options } = this;
1984
- const modal = document.createElement(
1985
- "mm-install-modal"
1986
- );
2042
+ const modal = document.createElement("mm-install-modal");
1987
2043
  modal.showInstallModal = options.showInstallModal;
1988
2044
  modal.addEventListener("close", (ev) => {
1989
2045
  const { detail } = ev;
@@ -2179,6 +2235,7 @@ import { analytics as analytics2 } from "@metamask/analytics";
2179
2235
  import {
2180
2236
  getMultichainClient
2181
2237
  } from "@metamask/multichain-api-client";
2238
+ import { createDeferredPromise as createDeferredPromise2 } from "@metamask/utils";
2182
2239
 
2183
2240
  // src/config/index.ts
2184
2241
  var MWP_RELAY_URL = "wss://mm-sdk-relay.api.cx.metamask.io/connection/websocket";
@@ -2302,17 +2359,93 @@ import { analytics } from "@metamask/analytics";
2302
2359
  init_domain();
2303
2360
  init_utils2();
2304
2361
  init_analytics();
2362
+
2363
+ // src/multichain/rpc/invocationError.ts
2364
+ init_domain();
2365
+ import { isValidJson } from "@metamask/utils";
2366
+ var MAX_ERROR_CAUSE_DEPTH = 5;
2367
+ function getErrorObject(value) {
2368
+ if (typeof value === "object" && value !== null) {
2369
+ return value;
2370
+ }
2371
+ return void 0;
2372
+ }
2373
+ function getNumericCode(value) {
2374
+ return typeof value === "number" ? value : void 0;
2375
+ }
2376
+ function getNonEmptyMessage(value) {
2377
+ return typeof value === "string" && value.length > 0 ? value : void 0;
2378
+ }
2379
+ function getJsonData(value) {
2380
+ return value !== void 0 && isValidJson(value) ? value : void 0;
2381
+ }
2382
+ function getFirstNonEmptyMessage(values) {
2383
+ for (const value of values) {
2384
+ const message = getNonEmptyMessage(value);
2385
+ if (message !== void 0) {
2386
+ return message;
2387
+ }
2388
+ }
2389
+ return void 0;
2390
+ }
2391
+ function getErrorObjectChain(errorObject) {
2392
+ const chain = [];
2393
+ let currentObject = errorObject;
2394
+ for (let depth = 0; currentObject !== void 0 && depth < MAX_ERROR_CAUSE_DEPTH; depth += 1) {
2395
+ chain.push(currentObject);
2396
+ currentObject = getErrorObject(currentObject.cause);
2397
+ }
2398
+ return chain;
2399
+ }
2400
+ function getCodedErrorDetails(value) {
2401
+ const code = getNumericCode(value == null ? void 0 : value.code);
2402
+ if (code === void 0) {
2403
+ return void 0;
2404
+ }
2405
+ const message = getNonEmptyMessage(value == null ? void 0 : value.message);
2406
+ const data = getJsonData(value == null ? void 0 : value.data);
2407
+ return __spreadValues(__spreadValues({
2408
+ code
2409
+ }, message === void 0 ? {} : { message }), data === void 0 ? {} : { data });
2410
+ }
2411
+ function getInvocationErrorDetails(error) {
2412
+ var _a3, _b, _c, _d;
2413
+ const errorObject = getErrorObject(error);
2414
+ const errorObjectChain = getErrorObjectChain(errorObject);
2415
+ const primitiveMessage = getNonEmptyMessage(error);
2416
+ for (const [index, currentObject] of errorObjectChain.entries()) {
2417
+ const codedDetails = getCodedErrorDetails(currentObject);
2418
+ if (codedDetails) {
2419
+ const descendantObjects = errorObjectChain.slice(index + 1);
2420
+ const ancestorObjects = errorObjectChain.slice(0, index);
2421
+ const descendantMessage = getFirstNonEmptyMessage(
2422
+ descendantObjects.map((object) => object.message)
2423
+ );
2424
+ const ancestorMessage = getFirstNonEmptyMessage([
2425
+ primitiveMessage,
2426
+ ...ancestorObjects.map((object) => object.message)
2427
+ ]);
2428
+ const reason2 = (_c = (_b = (_a3 = codedDetails.message) != null ? _a3 : descendantMessage) != null ? _b : ancestorMessage) != null ? _c : "Unknown error";
2429
+ return __spreadValues(__spreadValues({
2430
+ reason: reason2,
2431
+ rpcCode: codedDetails.code
2432
+ }, codedDetails.message === void 0 ? {} : { rpcMessage: codedDetails.message }), codedDetails.data === void 0 ? {} : { rpcData: codedDetails.data });
2433
+ }
2434
+ }
2435
+ const reason = (_d = primitiveMessage != null ? primitiveMessage : getFirstNonEmptyMessage(errorObjectChain.map((object) => object.message))) != null ? _d : "Unknown error";
2436
+ return {
2437
+ reason
2438
+ };
2439
+ }
2305
2440
  function toRPCInvokeMethodErr(error) {
2306
- var _a3;
2307
2441
  if (error instanceof RPCInvokeMethodErr) {
2308
2442
  return error;
2309
2443
  }
2310
- const castError = error;
2311
- return new RPCInvokeMethodErr(
2312
- (_a3 = castError.message) != null ? _a3 : "Unknown error",
2313
- castError.code
2314
- );
2444
+ const { reason, rpcCode, rpcMessage, rpcData } = getInvocationErrorDetails(error);
2445
+ return new RPCInvokeMethodErr(reason, rpcCode, rpcMessage, rpcData);
2315
2446
  }
2447
+
2448
+ // src/multichain/rpc/requestRouter.ts
2316
2449
  var _RequestRouter_instances, withAnalyticsTracking_fn, trackWalletActionRequested_fn, trackWalletActionSucceeded_fn, trackWalletActionFailed_fn, trackWalletActionRejected_fn;
2317
2450
  var RequestRouter = class {
2318
2451
  constructor(transport, rpcClient, config, transportType) {
@@ -2332,6 +2465,9 @@ var RequestRouter = class {
2332
2465
  invokeMethod(options) {
2333
2466
  return __async(this, null, function* () {
2334
2467
  const { method } = options.request;
2468
+ if (EIP1193_PASSTHROUGH_METHODS.has(method)) {
2469
+ return this.handleWithEip1193Passthrough(options);
2470
+ }
2335
2471
  if (RPC_HANDLED_METHODS.has(method)) {
2336
2472
  return this.handleWithRpcNode(options);
2337
2473
  }
@@ -2341,6 +2477,29 @@ var RequestRouter = class {
2341
2477
  return this.handleWithWallet(options);
2342
2478
  });
2343
2479
  }
2480
+ /**
2481
+ * Forwards EIP-1193 / legacy provider methods (e.g. `wallet_addEthereumChain`,
2482
+ * `wallet_switchEthereumChain`, `eth_accounts`) directly to the underlying
2483
+ * transport's `sendEip1193Message`, bypassing the multichain
2484
+ * `wallet_invokeMethod` envelope. These methods are wallet-side concerns the
2485
+ * Multichain API does not model, so we forward the raw `{ method, params }`
2486
+ * payload and return the wallet's full JSON-RPC response envelope unchanged.
2487
+ *
2488
+ * Analytics tracking is intentionally skipped here: ecosystem clients
2489
+ * (e.g. `connect-evm`) emit their own `wallet_action_*` events around these
2490
+ * passthrough calls, and adding router-level tracking would double-count.
2491
+ *
2492
+ * @param options
2493
+ */
2494
+ handleWithEip1193Passthrough(options) {
2495
+ return __async(this, null, function* () {
2496
+ const response = yield this.transport.sendEip1193Message({
2497
+ method: options.request.method,
2498
+ params: options.request.params
2499
+ });
2500
+ return response.result;
2501
+ });
2502
+ }
2344
2503
  /**
2345
2504
  * Forwards the request directly to the wallet via the transport.
2346
2505
  *
@@ -2373,12 +2532,7 @@ var RequestRouter = class {
2373
2532
  }
2374
2533
  const response = yield request;
2375
2534
  if (response.error) {
2376
- const { error } = response;
2377
- throw new RPCInvokeMethodErr(
2378
- `RPC Request failed with code ${error.code}: ${error.message}`,
2379
- error.code,
2380
- error.message
2381
- );
2535
+ throw toRPCInvokeMethodErr(response.error);
2382
2536
  }
2383
2537
  return response.result;
2384
2538
  }));
@@ -2432,13 +2586,15 @@ withAnalyticsTracking_fn = function(options, execute) {
2432
2586
  yield __privateMethod(this, _RequestRouter_instances, trackWalletActionSucceeded_fn).call(this, options);
2433
2587
  return result;
2434
2588
  } catch (error) {
2435
- const isRejection = isRejectionError(error);
2589
+ const normalizedError = toRPCInvokeMethodErr(error);
2590
+ const analyticsError = normalizedError.rpcCode === void 0 ? error : normalizedError;
2591
+ const isRejection = isRejectionError(analyticsError);
2436
2592
  if (isRejection) {
2437
2593
  yield __privateMethod(this, _RequestRouter_instances, trackWalletActionRejected_fn).call(this, options);
2438
2594
  } else {
2439
- yield __privateMethod(this, _RequestRouter_instances, trackWalletActionFailed_fn).call(this, options, error);
2595
+ yield __privateMethod(this, _RequestRouter_instances, trackWalletActionFailed_fn).call(this, options, analyticsError);
2440
2596
  }
2441
- throw toRPCInvokeMethodErr(error);
2597
+ throw normalizedError;
2442
2598
  }
2443
2599
  });
2444
2600
  };
@@ -2493,8 +2649,9 @@ init_utils2();
2493
2649
  import {
2494
2650
  getDefaultTransport
2495
2651
  } from "@metamask/multichain-api-client";
2652
+ import { isValidJson as isValidJson2 } from "@metamask/utils";
2496
2653
  var DEFAULT_REQUEST_TIMEOUT = 60 * 1e3;
2497
- var _notificationCallbacks, _transport, _defaultRequestOptions, _pendingRequests, _handleResponseListener, _handleNotificationListener, _DefaultTransport_instances, notifyCallbacks_fn, isMetamaskProviderEvent_fn, handleResponse_fn, handleNotification_fn, setupMessageListener_fn, init_fn;
2654
+ var _notificationCallbacks, _transport, _defaultRequestOptions, _pendingRequests, _handleResponseListener, _handleNotificationListener, _DefaultTransport_instances, notifyCallbacks_fn, parseWalletError_fn, isMetamaskProviderEvent_fn, handleResponse_fn, handleNotification_fn, setupMessageListener_fn, init_fn;
2498
2655
  var DefaultTransport = class {
2499
2656
  constructor() {
2500
2657
  __privateAdd(this, _DefaultTransport_instances);
@@ -2630,7 +2787,11 @@ var DefaultTransport = class {
2630
2787
  }
2631
2788
  request(_0) {
2632
2789
  return __async(this, arguments, function* (request, options = __privateGet(this, _defaultRequestOptions)) {
2633
- return __privateGet(this, _transport).request(request, options);
2790
+ const response = yield __privateGet(this, _transport).request(request, options);
2791
+ if (response.error) {
2792
+ throw __privateMethod(this, _DefaultTransport_instances, parseWalletError_fn).call(this, response.error);
2793
+ }
2794
+ return response;
2634
2795
  });
2635
2796
  }
2636
2797
  onNotification(callback) {
@@ -2674,6 +2835,20 @@ notifyCallbacks_fn = function(data) {
2674
2835
  }
2675
2836
  }
2676
2837
  };
2838
+ parseWalletError_fn = function(errorPayload) {
2839
+ const errorData = errorPayload;
2840
+ const error = new Error(
2841
+ typeof errorData.message === "string" ? errorData.message : "Request failed"
2842
+ );
2843
+ if (typeof errorData.code === "number") {
2844
+ error.code = errorData.code;
2845
+ }
2846
+ const { data } = errorData;
2847
+ if (isValidJson2(data)) {
2848
+ error.data = data;
2849
+ }
2850
+ return error;
2851
+ };
2677
2852
  isMetamaskProviderEvent_fn = function(event) {
2678
2853
  var _a3, _b;
2679
2854
  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
@@ -2696,13 +2871,7 @@ handleResponse_fn = function(event) {
2696
2871
  __privateGet(this, _pendingRequests).delete(responseId);
2697
2872
  const response = responseData;
2698
2873
  if ("error" in response && response.error) {
2699
- const error = new Error(
2700
- response.error.message || "Request failed"
2701
- );
2702
- if (typeof response.error.code === "number") {
2703
- error.code = response.error.code;
2704
- }
2705
- pendingRequest.reject(error);
2874
+ pendingRequest.reject(__privateMethod(this, _DefaultTransport_instances, parseWalletError_fn).call(this, response.error));
2706
2875
  } else {
2707
2876
  pendingRequest.resolve(response);
2708
2877
  }
@@ -2740,22 +2909,21 @@ init_fn = function() {
2740
2909
  // src/multichain/transports/multichainApiClientWrapper/index.ts
2741
2910
  init_utils2();
2742
2911
  import { providerErrors } from "@metamask/rpc-errors";
2743
- var _notificationCallbacks2, _MultichainApiClientWrapperTransport_instances, walletCreateSession_fn, walletGetSession_fn, walletRevokeSession_fn, walletInvokeMethod_fn;
2912
+ var _notificationCallbacks2, _getTransport, _MultichainApiClientWrapperTransport_instances, walletCreateSession_fn, walletGetSession_fn, walletRevokeSession_fn, walletInvokeMethod_fn;
2744
2913
  var MultichainApiClientWrapperTransport = class {
2745
- constructor(metamaskConnectMultichain) {
2914
+ constructor(metamaskConnectMultichain, getTransport) {
2746
2915
  this.metamaskConnectMultichain = metamaskConnectMultichain;
2747
2916
  __privateAdd(this, _MultichainApiClientWrapperTransport_instances);
2748
2917
  __privateAdd(this, _notificationCallbacks2, /* @__PURE__ */ new Set());
2918
+ __privateAdd(this, _getTransport);
2919
+ __privateSet(this, _getTransport, getTransport);
2749
2920
  }
2750
2921
  isTransportDefined() {
2751
- try {
2752
- return Boolean(this.metamaskConnectMultichain.transport);
2753
- } catch (_error) {
2754
- return false;
2755
- }
2922
+ return __privateGet(this, _getTransport).call(this) !== void 0;
2756
2923
  }
2757
2924
  isTransportConnected() {
2758
- return this.isTransportDefined() && this.metamaskConnectMultichain.transport.isConnected();
2925
+ var _a3, _b;
2926
+ return (_b = (_a3 = __privateGet(this, _getTransport).call(this)) == null ? void 0 : _a3.isConnected()) != null ? _b : false;
2759
2927
  }
2760
2928
  clearNotificationCallbacks() {
2761
2929
  __privateGet(this, _notificationCallbacks2).clear();
@@ -2771,10 +2939,11 @@ var MultichainApiClientWrapperTransport = class {
2771
2939
  this.notificationListener = void 0;
2772
2940
  }
2773
2941
  setupTransportNotificationListener() {
2774
- if (!this.isTransportDefined() || this.notificationListener) {
2942
+ const transport = __privateGet(this, _getTransport).call(this);
2943
+ if (!transport || this.notificationListener) {
2775
2944
  return;
2776
2945
  }
2777
- this.notificationListener = this.metamaskConnectMultichain.transport.onNotification(
2946
+ this.notificationListener = transport.onNotification(
2778
2947
  this.notifyCallbacks.bind(this)
2779
2948
  );
2780
2949
  }
@@ -2824,6 +2993,7 @@ var MultichainApiClientWrapperTransport = class {
2824
2993
  }
2825
2994
  };
2826
2995
  _notificationCallbacks2 = new WeakMap();
2996
+ _getTransport = new WeakMap();
2827
2997
  _MultichainApiClientWrapperTransport_instances = new WeakSet();
2828
2998
  walletCreateSession_fn = function(request) {
2829
2999
  return __async(this, null, function* () {
@@ -2847,14 +3017,19 @@ walletCreateSession_fn = function(request) {
2847
3017
  accounts,
2848
3018
  createSessionParams.sessionProperties
2849
3019
  );
2850
- return this.metamaskConnectMultichain.transport.request({
3020
+ const transport = __privateGet(this, _getTransport).call(this);
3021
+ if (!transport) {
3022
+ throw new Error("Transport not initialized after connect");
3023
+ }
3024
+ return transport.request({
2851
3025
  method: "wallet_getSession"
2852
3026
  });
2853
3027
  });
2854
3028
  };
2855
3029
  walletGetSession_fn = function(request) {
2856
3030
  return __async(this, null, function* () {
2857
- if (!this.isTransportConnected()) {
3031
+ const transport = __privateGet(this, _getTransport).call(this);
3032
+ if (!(transport == null ? void 0 : transport.isConnected())) {
2858
3033
  return {
2859
3034
  jsonrpc: "2.0",
2860
3035
  id: request.id,
@@ -2863,7 +3038,7 @@ walletGetSession_fn = function(request) {
2863
3038
  }
2864
3039
  };
2865
3040
  }
2866
- return this.metamaskConnectMultichain.transport.request({
3041
+ return transport.request({
2867
3042
  method: "wallet_getSession"
2868
3043
  });
2869
3044
  });
@@ -2941,7 +3116,7 @@ function setupAnalyticsGlobals(options, storage, setAnonId) {
2941
3116
  analytics2.enable();
2942
3117
  });
2943
3118
  }
2944
- 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;
3119
+ 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;
2945
3120
  var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends MultichainCore {
2946
3121
  constructor(options) {
2947
3122
  var _a3, _b, _c, _d;
@@ -2954,9 +3129,7 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
2954
3129
  }),
2955
3130
  analytics: normalizeAnalyticsOptions(options.analytics),
2956
3131
  versions: __spreadValues({
2957
- // typeof guard needed: Metro (React Native) bundles TS source directly,
2958
- // bypassing the tsup build that substitutes __PACKAGE_VERSION__.
2959
- "connect-multichain": false ? "unknown" : "0.15.0"
3132
+ "connect-multichain": getVersion()
2960
3133
  }, (_d = options.versions) != null ? _d : {})
2961
3134
  });
2962
3135
  super(allOptions);
@@ -2972,7 +3145,8 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
2972
3145
  __privateAdd(this, _anonId);
2973
3146
  __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}`);
2974
3147
  __privateSet(this, _providerTransportWrapper, new MultichainApiClientWrapperTransport(
2975
- this
3148
+ this,
3149
+ () => __privateGet(this, _transport2)
2976
3150
  ));
2977
3151
  __privateSet(this, _provider, getMultichainClient({
2978
3152
  transport: __privateGet(this, _providerTransportWrapper)
@@ -2991,12 +3165,6 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
2991
3165
  get provider() {
2992
3166
  return __privateGet(this, _provider);
2993
3167
  }
2994
- get transport() {
2995
- if (!__privateGet(this, _transport2)) {
2996
- throw new Error("Transport not initialized, establish connection first");
2997
- }
2998
- return __privateGet(this, _transport2);
2999
- }
3000
3168
  get dappClient() {
3001
3169
  if (!__privateGet(this, _dappClient)) {
3002
3170
  throw new Error("DappClient not initialized, establish connection first");
@@ -3010,6 +3178,9 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
3010
3178
  get storage() {
3011
3179
  return this.options.storage;
3012
3180
  }
3181
+ get version() {
3182
+ return getVersion();
3183
+ }
3013
3184
  // Creates a singleton instance of MetaMaskConnectMultichain.
3014
3185
  // If the singleton already exists, it merges the incoming options with the
3015
3186
  // existing singleton options for the following keys: `api.supportedNetworks`,
@@ -3024,6 +3195,11 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
3024
3195
  const existing = globalObject[SINGLETON_KEY];
3025
3196
  if (existing) {
3026
3197
  const instance = yield existing;
3198
+ if (instance.version !== getVersion()) {
3199
+ console.warn(
3200
+ `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.`
3201
+ );
3202
+ }
3027
3203
  instance.mergeOptions(options);
3028
3204
  if (instance instanceof _MetaMaskConnectMultichain) {
3029
3205
  yield __privateMethod(_a3 = instance, _MetaMaskConnectMultichain_instances, setupAnalytics_fn).call(_a3);
@@ -3047,12 +3223,12 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
3047
3223
  }
3048
3224
  yield __privateMethod(_a4 = instance, _MetaMaskConnectMultichain_instances, init_fn2).call(_a4);
3049
3225
  return instance;
3050
- }))();
3051
- globalObject[SINGLETON_KEY] = instancePromise;
3052
- instancePromise.catch((error) => {
3226
+ }))().catch((error) => {
3053
3227
  globalObject[SINGLETON_KEY] = void 0;
3054
3228
  console.error("Error initializing MetaMaskConnectMultichain", error);
3229
+ throw error;
3055
3230
  });
3231
+ globalObject[SINGLETON_KEY] = instancePromise;
3056
3232
  return instancePromise;
3057
3233
  });
3058
3234
  }
@@ -3112,9 +3288,9 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
3112
3288
  forceRequest
3113
3289
  }).then(() => __async(this, null, function* () {
3114
3290
  if (__privateGet(this, _transportType) === "mwp" /* MWP */) {
3115
- return this.storage.setTransport("mwp" /* MWP */);
3291
+ return this.storage.setTransportType("mwp" /* MWP */);
3116
3292
  }
3117
- return this.storage.setTransport("browser" /* Browser */);
3293
+ return this.storage.setTransportType("browser" /* Browser */);
3118
3294
  })), scopes, transportType);
3119
3295
  }
3120
3296
  if (platformType === "in-app-browser" /* MetaMaskMobileWebview */) {
@@ -3143,11 +3319,6 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
3143
3319
  return __privateMethod(this, _MetaMaskConnectMultichain_instances, handleConnection_fn).call(this, __privateMethod(this, _MetaMaskConnectMultichain_instances, showInstallModal_fn).call(this, shouldShowInstallModal, mergedScopes, mergedCaipAccountIds, nonEmptySessionProperties), scopes, transportType);
3144
3320
  });
3145
3321
  }
3146
- emit(event, args) {
3147
- var _a3, _b;
3148
- (_b = (_a3 = this.options.transport) == null ? void 0 : _a3.onNotification) == null ? void 0 : _b.call(_a3, { method: event, params: args });
3149
- super.emit(event, args);
3150
- }
3151
3322
  disconnect() {
3152
3323
  return __async(this, arguments, function* (scopes = []) {
3153
3324
  var _a3, _b, _c;
@@ -3157,7 +3328,7 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
3157
3328
  );
3158
3329
  yield (_a3 = __privateGet(this, _transport2)) == null ? void 0 : _a3.disconnect(scopes);
3159
3330
  if (remainingScopes.length === 0) {
3160
- yield this.storage.removeTransport();
3331
+ yield this.storage.removeTransportType();
3161
3332
  if (__privateGet(this, _transportType) !== "browser" /* Browser */) {
3162
3333
  yield (_b = __privateGet(this, _listener)) == null ? void 0 : _b.call(this);
3163
3334
  (_c = __privateGet(this, _beforeUnloadListener)) == null ? void 0 : _c.call(this);
@@ -3175,7 +3346,8 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
3175
3346
  invokeMethod(request) {
3176
3347
  return __async(this, null, function* () {
3177
3348
  var _a3;
3178
- const { transport, options } = this;
3349
+ const transport = __privateMethod(this, _MetaMaskConnectMultichain_instances, transportOrThrow_fn).call(this);
3350
+ const { options } = this;
3179
3351
  const rpcClient = new RpcClient(options, __privateGet(this, _sdkInfo));
3180
3352
  const requestRouter = new RequestRouter(
3181
3353
  transport,
@@ -3194,7 +3366,7 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
3194
3366
  const shouldOpenDeeplink = secure && !showInstallModal;
3195
3367
  if (shouldOpenDeeplink) {
3196
3368
  setTimeout(() => __async(this, null, function* () {
3197
- const session = yield this.transport.getActiveSession();
3369
+ const session = yield __privateMethod(this, _MetaMaskConnectMultichain_instances, transportOrThrow_fn).call(this).getActiveSession();
3198
3370
  if (!session) {
3199
3371
  throw new Error("No active session found");
3200
3372
  }
@@ -3218,10 +3390,13 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
3218
3390
  this.emit("wallet_sessionChanged", emptySession);
3219
3391
  return;
3220
3392
  }
3221
- const response = yield this.transport.request({
3393
+ const response = yield __privateGet(this, _transport2).request({
3222
3394
  method: "wallet_getSession"
3223
3395
  });
3224
- this.emit("wallet_sessionChanged", (_b = response.result) != null ? _b : emptySession);
3396
+ this.emit(
3397
+ "wallet_sessionChanged",
3398
+ (_b = response.result) != null ? _b : emptySession
3399
+ );
3225
3400
  });
3226
3401
  }
3227
3402
  };
@@ -3233,8 +3408,14 @@ _beforeUnloadListener = new WeakMap();
3233
3408
  _transportType = new WeakMap();
3234
3409
  _listener = new WeakMap();
3235
3410
  _anonId = new WeakMap();
3236
- _sdkInfo = new WeakMap();
3237
3411
  _MetaMaskConnectMultichain_instances = new WeakSet();
3412
+ transportOrThrow_fn = function() {
3413
+ if (!__privateGet(this, _transport2)) {
3414
+ throw new Error("Transport not initialized, establish connection first");
3415
+ }
3416
+ return __privateGet(this, _transport2);
3417
+ };
3418
+ _sdkInfo = new WeakMap();
3238
3419
  setupAnalytics_fn = function() {
3239
3420
  return __async(this, null, function* () {
3240
3421
  yield setupAnalyticsGlobals(this.options, this.storage, (anonId) => {
@@ -3260,7 +3441,7 @@ onTransportNotification_fn = function(payload) {
3260
3441
  };
3261
3442
  getStoredTransport_fn = function() {
3262
3443
  return __async(this, null, function* () {
3263
- const transportType = yield this.storage.getTransport();
3444
+ const transportType = yield this.storage.getTransportType();
3264
3445
  const hasExtensionInstalled = yield hasExtension();
3265
3446
  if (transportType) {
3266
3447
  if (transportType === "browser" /* Browser */) {
@@ -3288,7 +3469,7 @@ getStoredTransport_fn = function() {
3288
3469
  ));
3289
3470
  return apiTransport;
3290
3471
  }
3291
- yield this.storage.removeTransport();
3472
+ yield this.storage.removeTransportType();
3292
3473
  }
3293
3474
  return void 0;
3294
3475
  });
@@ -3298,15 +3479,15 @@ setupTransport_fn = function() {
3298
3479
  var _a3;
3299
3480
  const transport = yield __privateMethod(this, _MetaMaskConnectMultichain_instances, getStoredTransport_fn).call(this);
3300
3481
  if (transport) {
3301
- if (!this.transport.isConnected()) {
3482
+ if (!transport.isConnected()) {
3302
3483
  this.status = "connecting";
3303
- yield this.transport.connect();
3484
+ yield transport.connect();
3304
3485
  }
3305
3486
  this.status = "connected";
3306
3487
  if (__privateGet(this, _transportType) === "mwp" /* MWP */) {
3307
- yield this.storage.setTransport("mwp" /* MWP */);
3488
+ yield this.storage.setTransportType("mwp" /* MWP */);
3308
3489
  } else {
3309
- yield this.storage.setTransport("browser" /* Browser */);
3490
+ yield this.storage.setTransportType("browser" /* Browser */);
3310
3491
  }
3311
3492
  } else {
3312
3493
  this.status = "loaded";
@@ -3315,7 +3496,7 @@ setupTransport_fn = function() {
3315
3496
  if (hasExtensionInstalled && preferExtension) {
3316
3497
  yield __privateMethod(this, _MetaMaskConnectMultichain_instances, setupDefaultTransport_fn).call(this, { persist: false });
3317
3498
  try {
3318
- yield this.transport.init();
3499
+ yield __privateMethod(this, _MetaMaskConnectMultichain_instances, transportOrThrow_fn).call(this).init();
3319
3500
  } catch (error) {
3320
3501
  console.error("Passive init failed:", error);
3321
3502
  }
@@ -3339,7 +3520,7 @@ init_fn2 = function() {
3339
3520
  yield __privateMethod(this, _MetaMaskConnectMultichain_instances, setupAnalytics_fn).call(this);
3340
3521
  yield __privateMethod(this, _MetaMaskConnectMultichain_instances, setupTransport_fn).call(this);
3341
3522
  } catch (error) {
3342
- yield this.storage.removeTransport();
3523
+ yield this.storage.removeTransportType();
3343
3524
  this.status = "pending";
3344
3525
  logger2("MetaMaskSDK error during initialization", error);
3345
3526
  }
@@ -3385,17 +3566,17 @@ setupMWP_fn = function() {
3385
3566
  __privateSet(this, _transport2, apiTransport);
3386
3567
  __privateSet(this, _transportType, "mwp" /* MWP */);
3387
3568
  __privateGet(this, _providerTransportWrapper).setupTransportNotificationListener();
3388
- __privateSet(this, _listener, this.transport.onNotification(
3569
+ __privateSet(this, _listener, apiTransport.onNotification(
3389
3570
  __privateMethod(this, _MetaMaskConnectMultichain_instances, onTransportNotification_fn).bind(this)
3390
3571
  ));
3391
- yield this.storage.setTransport("mwp" /* MWP */);
3572
+ yield this.storage.setTransportType("mwp" /* MWP */);
3392
3573
  });
3393
3574
  };
3394
3575
  onBeforeUnload_fn = function() {
3395
3576
  return __async(this, null, function* () {
3396
3577
  var _a3;
3397
3578
  if ((_a3 = this.options.ui.factory.modal) == null ? void 0 : _a3.isMounted) {
3398
- yield this.storage.removeTransport();
3579
+ yield this.storage.removeTransportType();
3399
3580
  }
3400
3581
  });
3401
3582
  };
@@ -3412,70 +3593,65 @@ createBeforeUnloadListener_fn = function() {
3412
3593
  };
3413
3594
  renderInstallModalAsync_fn = function(desktopPreferred, scopes, caipAccountIds, sessionProperties) {
3414
3595
  return __async(this, null, function* () {
3415
- return new Promise((resolve, reject) => {
3416
- this.options.ui.factory.renderInstallModal(
3417
- desktopPreferred,
3418
- () => __async(this, null, function* () {
3419
- if (this.dappClient.state === "CONNECTED" || this.dappClient.state === "CONNECTING") {
3420
- yield this.dappClient.disconnect();
3421
- }
3422
- return new Promise((_resolve) => {
3423
- this.dappClient.on(
3424
- "session_request",
3425
- (sessionRequest) => {
3426
- _resolve({
3427
- sessionRequest,
3428
- metadata: __privateMethod(this, _MetaMaskConnectMultichain_instances, buildConnectionMetadata_fn).call(this)
3429
- });
3430
- }
3431
- );
3432
- (() => __async(this, null, function* () {
3433
- var _a3;
3434
- try {
3435
- yield this.transport.connect({
3436
- scopes,
3437
- caipAccountIds,
3438
- sessionProperties
3439
- });
3440
- yield this.options.ui.factory.unload();
3441
- (_a3 = this.options.ui.factory.modal) == null ? void 0 : _a3.unmount();
3442
- this.status = "connected";
3443
- yield this.storage.setTransport("mwp" /* MWP */);
3444
- } catch (error) {
3445
- const { ProtocolError, ErrorCode } = yield import("@metamask/mobile-wallet-protocol-core");
3446
- if (error instanceof ProtocolError) {
3447
- if (error.code !== ErrorCode.REQUEST_EXPIRED) {
3448
- this.status = "disconnected";
3449
- yield this.options.ui.factory.unload(error);
3450
- reject(error);
3451
- }
3452
- } else {
3453
- this.status = "disconnected";
3454
- const normalizedError = error instanceof Error ? error : new Error(String(error));
3455
- yield this.options.ui.factory.unload(normalizedError);
3456
- reject(normalizedError);
3457
- }
3458
- }
3459
- }))().catch(() => {
3460
- });
3596
+ const completion = createDeferredPromise2();
3597
+ const createConnectionRequest = () => __async(this, null, function* () {
3598
+ if (this.dappClient.state === "CONNECTED" || this.dappClient.state === "CONNECTING") {
3599
+ yield this.dappClient.disconnect();
3600
+ }
3601
+ const sessionRequestDeferred = createDeferredPromise2();
3602
+ this.dappClient.on(
3603
+ "session_request",
3604
+ (sessionRequest) => {
3605
+ sessionRequestDeferred.resolve({
3606
+ sessionRequest,
3607
+ metadata: __privateMethod(this, _MetaMaskConnectMultichain_instances, buildConnectionMetadata_fn).call(this)
3461
3608
  });
3462
- }),
3463
- (error) => __async(this, null, function* () {
3464
- if (error) {
3465
- yield this.storage.removeTransport();
3466
- reject(error);
3467
- } else {
3468
- yield this.storage.setTransport("mwp" /* MWP */);
3469
- resolve();
3609
+ }
3610
+ );
3611
+ __privateMethod(this, _MetaMaskConnectMultichain_instances, transportOrThrow_fn).call(this).connect({ scopes, caipAccountIds, sessionProperties }).then(() => __async(this, null, function* () {
3612
+ var _a3;
3613
+ yield this.options.ui.factory.unload();
3614
+ (_a3 = this.options.ui.factory.modal) == null ? void 0 : _a3.unmount();
3615
+ this.status = "connected";
3616
+ yield this.storage.setTransportType("mwp" /* MWP */);
3617
+ })).catch((error) => __async(this, null, function* () {
3618
+ const { ProtocolError, ErrorCode } = yield import("@metamask/mobile-wallet-protocol-core");
3619
+ if (error instanceof ProtocolError) {
3620
+ if (error.code !== ErrorCode.REQUEST_EXPIRED) {
3621
+ this.status = "disconnected";
3622
+ yield this.options.ui.factory.unload(error);
3623
+ completion.reject(error);
3470
3624
  }
3471
- }),
3472
- (uri) => {
3473
- this.emit("display_uri", uri);
3625
+ } else {
3626
+ this.status = "disconnected";
3627
+ const normalizedError = error instanceof Error ? error : new Error(String(error));
3628
+ yield this.options.ui.factory.unload(normalizedError);
3629
+ completion.reject(normalizedError);
3474
3630
  }
3475
- ).catch((error) => {
3476
- reject(error instanceof Error ? error : new Error(String(error)));
3477
- });
3631
+ }));
3632
+ return sessionRequestDeferred.promise;
3478
3633
  });
3634
+ this.options.ui.factory.renderInstallModal(
3635
+ desktopPreferred,
3636
+ createConnectionRequest,
3637
+ (error) => __async(this, null, function* () {
3638
+ if (error) {
3639
+ yield this.storage.removeTransportType();
3640
+ completion.reject(error);
3641
+ } else {
3642
+ yield this.storage.setTransportType("mwp" /* MWP */);
3643
+ completion.resolve();
3644
+ }
3645
+ }),
3646
+ (uri) => {
3647
+ this.emit("display_uri", uri);
3648
+ }
3649
+ ).catch((error) => {
3650
+ completion.reject(
3651
+ error instanceof Error ? error : new Error(String(error))
3652
+ );
3653
+ });
3654
+ return completion.promise;
3479
3655
  });
3480
3656
  };
3481
3657
  showInstallModal_fn = function(desktopPreferred, scopes, caipAccountIds, sessionProperties) {
@@ -3491,39 +3667,37 @@ showInstallModal_fn = function(desktopPreferred, scopes, caipAccountIds, session
3491
3667
  };
3492
3668
  headlessConnect_fn = function(scopes, caipAccountIds, sessionProperties) {
3493
3669
  return __async(this, null, function* () {
3494
- return new Promise((resolve, reject) => {
3495
- if (this.dappClient.state === "CONNECTED" || this.dappClient.state === "CONNECTING") {
3496
- this.dappClient.disconnect().catch(() => {
3497
- });
3670
+ if (this.dappClient.state === "CONNECTED" || this.dappClient.state === "CONNECTING") {
3671
+ yield this.dappClient.disconnect().catch(() => void 0);
3672
+ }
3673
+ const onSessionRequest = (sessionRequest) => {
3674
+ const connectionRequest = {
3675
+ sessionRequest,
3676
+ metadata: __privateMethod(this, _MetaMaskConnectMultichain_instances, buildConnectionMetadata_fn).call(this)
3677
+ };
3678
+ const deeplink = this.options.ui.factory.createConnectionDeeplink(connectionRequest);
3679
+ this.emit("display_uri", deeplink);
3680
+ };
3681
+ this.dappClient.on("session_request", onSessionRequest);
3682
+ try {
3683
+ yield __privateMethod(this, _MetaMaskConnectMultichain_instances, transportOrThrow_fn).call(this).connect({
3684
+ scopes,
3685
+ caipAccountIds,
3686
+ sessionProperties
3687
+ });
3688
+ this.status = "connected";
3689
+ yield this.storage.setTransportType("mwp" /* MWP */);
3690
+ } catch (error) {
3691
+ const { ProtocolError } = yield import("@metamask/mobile-wallet-protocol-core");
3692
+ this.status = "disconnected";
3693
+ yield this.storage.removeTransportType();
3694
+ if (error instanceof ProtocolError || error instanceof Error) {
3695
+ throw error;
3498
3696
  }
3499
- this.dappClient.on(
3500
- "session_request",
3501
- (sessionRequest) => {
3502
- const connectionRequest = {
3503
- sessionRequest,
3504
- metadata: __privateMethod(this, _MetaMaskConnectMultichain_instances, buildConnectionMetadata_fn).call(this)
3505
- };
3506
- const deeplink = this.options.ui.factory.createConnectionDeeplink(connectionRequest);
3507
- this.emit("display_uri", deeplink);
3508
- }
3509
- );
3510
- this.transport.connect({ scopes, caipAccountIds, sessionProperties }).then(() => __async(this, null, function* () {
3511
- this.status = "connected";
3512
- yield this.storage.setTransport("mwp" /* MWP */);
3513
- resolve();
3514
- })).catch((error) => __async(this, null, function* () {
3515
- const { ProtocolError } = yield import("@metamask/mobile-wallet-protocol-core");
3516
- if (error instanceof ProtocolError) {
3517
- this.status = "disconnected";
3518
- yield this.storage.removeTransport();
3519
- reject(error);
3520
- } else {
3521
- this.status = "disconnected";
3522
- yield this.storage.removeTransport();
3523
- reject(error instanceof Error ? error : new Error(String(error)));
3524
- }
3525
- }));
3526
- });
3697
+ throw new Error(String(error));
3698
+ } finally {
3699
+ this.dappClient.off("session_request", onSessionRequest);
3700
+ }
3527
3701
  });
3528
3702
  };
3529
3703
  setupDefaultTransport_fn = function() {
@@ -3532,7 +3706,7 @@ setupDefaultTransport_fn = function() {
3532
3706
  return __privateGet(this, _transport2);
3533
3707
  }
3534
3708
  if (options == null ? void 0 : options.persist) {
3535
- yield this.storage.setTransport("browser" /* Browser */);
3709
+ yield this.storage.setTransportType("browser" /* Browser */);
3536
3710
  }
3537
3711
  const transport = new DefaultTransport();
3538
3712
  __privateSet(this, _listener, transport.onNotification(
@@ -3565,7 +3739,7 @@ deeplinkConnect_fn = function(scopes, caipAccountIds, sessionProperties) {
3565
3739
  };
3566
3740
  this.dappClient.on("message", dappClientMessageHandler);
3567
3741
  let timeout;
3568
- if (this.transport.isConnected()) {
3742
+ if (__privateMethod(this, _MetaMaskConnectMultichain_instances, transportOrThrow_fn).call(this).isConnected()) {
3569
3743
  timeout = setTimeout(() => {
3570
3744
  this.openSimpleDeeplinkIfNeeded();
3571
3745
  }, 250);
@@ -3593,8 +3767,8 @@ deeplinkConnect_fn = function(scopes, caipAccountIds, sessionProperties) {
3593
3767
  }
3594
3768
  );
3595
3769
  }
3596
- return this.transport.connect({ scopes, caipAccountIds, sessionProperties }).then(resolve).catch((error) => __async(this, null, function* () {
3597
- yield this.storage.removeTransport();
3770
+ return __privateMethod(this, _MetaMaskConnectMultichain_instances, transportOrThrow_fn).call(this).connect({ scopes, caipAccountIds, sessionProperties }).then(resolve).catch((error) => __async(this, null, function* () {
3771
+ yield this.storage.removeTransportType();
3598
3772
  this.dappClient.off("message", dappClientMessageHandler);
3599
3773
  reject(error instanceof Error ? error : new Error(String(error)));
3600
3774
  })).finally(() => {
@@ -3660,7 +3834,7 @@ getCaipSession_fn = function() {
3660
3834
  };
3661
3835
  if ((_a3 = __privateGet(this, _transport2)) == null ? void 0 : _a3.isConnected()) {
3662
3836
  try {
3663
- const response = yield this.transport.request({
3837
+ const response = yield __privateGet(this, _transport2).request({
3664
3838
  method: "wallet_getSession"
3665
3839
  });
3666
3840
  if (response.result) {
@@ -3754,14 +3928,14 @@ var Store = class extends StoreClient {
3754
3928
  super();
3755
3929
  this.adapter = adapter;
3756
3930
  }
3757
- getTransport() {
3931
+ getTransportType() {
3758
3932
  return __async(this, null, function* () {
3759
3933
  try {
3760
- const transport = yield this.adapter.get("multichain-transport");
3761
- if (!transport) {
3934
+ const transportType = yield this.adapter.get("multichain-transport");
3935
+ if (!transportType) {
3762
3936
  return null;
3763
3937
  }
3764
- return getTransportType(transport);
3938
+ return getTransportType(transportType);
3765
3939
  } catch (err) {
3766
3940
  throw new StorageGetErr(
3767
3941
  this.adapter.platform,
@@ -3771,10 +3945,10 @@ var Store = class extends StoreClient {
3771
3945
  }
3772
3946
  });
3773
3947
  }
3774
- setTransport(transport) {
3948
+ setTransportType(transportType) {
3775
3949
  return __async(this, null, function* () {
3776
3950
  try {
3777
- yield this.adapter.set("multichain-transport", transport);
3951
+ yield this.adapter.set("multichain-transport", transportType);
3778
3952
  } catch (err) {
3779
3953
  throw new StorageSetErr(
3780
3954
  this.adapter.platform,
@@ -3784,7 +3958,7 @@ var Store = class extends StoreClient {
3784
3958
  }
3785
3959
  });
3786
3960
  }
3787
- removeTransport() {
3961
+ removeTransportType() {
3788
3962
  return __async(this, null, function* () {
3789
3963
  try {
3790
3964
  yield this.adapter.delete("multichain-transport");
@@ -3998,7 +4172,11 @@ var BaseModalFactory = class {
3998
4172
  (_a4 = this.displayUriCallback) == null ? void 0 : _a4.call(this, newLink);
3999
4173
  return newLink;
4000
4174
  }),
4001
- onClose: this.onCloseModal.bind(this),
4175
+ onClose: (shouldTerminate) => {
4176
+ this.onCloseModal(shouldTerminate).catch((error) => {
4177
+ console.error("Failed to close modal:", error);
4178
+ });
4179
+ },
4002
4180
  startDesktopOnboarding: this.onStartDesktopOnboarding.bind(this),
4003
4181
  createConnectionRequest,
4004
4182
  onDisplayUri: this.displayUriCallback
@@ -4036,7 +4214,7 @@ function preload() {
4036
4214
  }
4037
4215
  try {
4038
4216
  const { defineCustomElements } = yield import("@metamask/multichain-ui/loader");
4039
- yield defineCustomElements();
4217
+ defineCustomElements();
4040
4218
  } catch (error) {
4041
4219
  console.error("Failed to load customElements:", error);
4042
4220
  }
@@ -4074,6 +4252,7 @@ var createMultichainClient = (options) => __async(null, null, function* () {
4074
4252
  }));
4075
4253
  });
4076
4254
  export {
4255
+ EIP1193_PASSTHROUGH_METHODS,
4077
4256
  EventEmitter,
4078
4257
  Modal,
4079
4258
  MultichainCore,
@@ -4101,6 +4280,7 @@ export {
4101
4280
  isEnabled,
4102
4281
  isMetamaskExtensionInstalled,
4103
4282
  isRejectionError,
4104
- isSecure
4283
+ isSecure,
4284
+ packageVersion
4105
4285
  };
4106
4286
  //# sourceMappingURL=connect-multichain.mjs.map