@metamask/connect-multichain 0.15.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/CHANGELOG.md +36 -1
  2. package/README.md +0 -1
  3. package/dist/browser/es/connect-multichain.d.mts +18 -8
  4. package/dist/browser/es/connect-multichain.mjs +558 -378
  5. package/dist/browser/es/connect-multichain.mjs.map +1 -1
  6. package/dist/browser/es/metafile-esm.json +1 -1
  7. package/dist/browser/iife/connect-multichain.d.ts +18 -8
  8. package/dist/browser/iife/connect-multichain.js +571 -378
  9. package/dist/browser/iife/connect-multichain.js.map +1 -1
  10. package/dist/browser/iife/metafile-iife.json +1 -1
  11. package/dist/browser/umd/connect-multichain.d.ts +18 -8
  12. package/dist/browser/umd/connect-multichain.js +558 -378
  13. package/dist/browser/umd/connect-multichain.js.map +1 -1
  14. package/dist/browser/umd/metafile-cjs.json +1 -1
  15. package/dist/node/cjs/connect-multichain.d.ts +18 -8
  16. package/dist/node/cjs/connect-multichain.js +560 -376
  17. package/dist/node/cjs/connect-multichain.js.map +1 -1
  18. package/dist/node/cjs/metafile-cjs.json +1 -1
  19. package/dist/node/es/connect-multichain.d.mts +18 -8
  20. package/dist/node/es/connect-multichain.mjs +557 -375
  21. package/dist/node/es/connect-multichain.mjs.map +1 -1
  22. package/dist/node/es/metafile-esm.json +1 -1
  23. package/dist/react-native/es/connect-multichain.d.mts +18 -8
  24. package/dist/react-native/es/connect-multichain.mjs +556 -374
  25. package/dist/react-native/es/connect-multichain.mjs.map +1 -1
  26. package/dist/react-native/es/metafile-esm.json +1 -1
  27. package/dist/src/domain/errors/rpc.d.ts +11 -1
  28. package/dist/src/domain/errors/rpc.d.ts.map +1 -1
  29. package/dist/src/domain/errors/rpc.js +10 -2
  30. package/dist/src/domain/errors/rpc.js.map +1 -1
  31. package/dist/src/domain/multichain/api/constants.d.ts +1 -0
  32. package/dist/src/domain/multichain/api/constants.d.ts.map +1 -1
  33. package/dist/src/domain/multichain/api/constants.js +13 -0
  34. package/dist/src/domain/multichain/api/constants.js.map +1 -1
  35. package/dist/src/domain/multichain/index.d.ts +2 -2
  36. package/dist/src/domain/multichain/index.d.ts.map +1 -1
  37. package/dist/src/domain/multichain/index.js.map +1 -1
  38. package/dist/src/domain/multichain/types.d.ts +0 -1
  39. package/dist/src/domain/multichain/types.d.ts.map +1 -1
  40. package/dist/src/domain/platform/index.d.ts.map +1 -1
  41. package/dist/src/domain/platform/index.js +27 -5
  42. package/dist/src/domain/platform/index.js.map +1 -1
  43. package/dist/src/domain/store/client.d.ts +3 -3
  44. package/dist/src/domain/store/client.d.ts.map +1 -1
  45. package/dist/src/domain/utils/index.d.ts +1 -0
  46. package/dist/src/domain/utils/index.d.ts.map +1 -1
  47. package/dist/src/domain/utils/index.js +5 -1
  48. package/dist/src/domain/utils/index.js.map +1 -1
  49. package/dist/src/multichain/index.d.ts +2 -3
  50. package/dist/src/multichain/index.d.ts.map +1 -1
  51. package/dist/src/multichain/index.js +142 -147
  52. package/dist/src/multichain/index.js.map +1 -1
  53. package/dist/src/multichain/rpc/invocationError.d.ts +9 -0
  54. package/dist/src/multichain/rpc/invocationError.d.ts.map +1 -0
  55. package/dist/src/multichain/rpc/invocationError.js +99 -0
  56. package/dist/src/multichain/rpc/invocationError.js.map +1 -0
  57. package/dist/src/multichain/rpc/requestRouter.d.ts +15 -0
  58. package/dist/src/multichain/rpc/requestRouter.d.ts.map +1 -1
  59. package/dist/src/multichain/rpc/requestRouter.js +38 -20
  60. package/dist/src/multichain/rpc/requestRouter.js.map +1 -1
  61. package/dist/src/multichain/transports/default/index.d.ts.map +1 -1
  62. package/dist/src/multichain/transports/default/index.js +25 -10
  63. package/dist/src/multichain/transports/default/index.js.map +1 -1
  64. package/dist/src/multichain/transports/multichainApiClientWrapper/index.d.ts +2 -1
  65. package/dist/src/multichain/transports/multichainApiClientWrapper/index.d.ts.map +1 -1
  66. package/dist/src/multichain/transports/multichainApiClientWrapper/index.js +25 -17
  67. package/dist/src/multichain/transports/multichainApiClientWrapper/index.js.map +1 -1
  68. package/dist/src/multichain/transports/mwp/index.d.ts +3 -1
  69. package/dist/src/multichain/transports/mwp/index.d.ts.map +1 -1
  70. package/dist/src/multichain/transports/mwp/index.js +235 -172
  71. package/dist/src/multichain/transports/mwp/index.js.map +1 -1
  72. package/dist/src/store/index.d.ts +3 -3
  73. package/dist/src/store/index.d.ts.map +1 -1
  74. package/dist/src/store/index.js +8 -8
  75. package/dist/src/store/index.js.map +1 -1
  76. package/dist/src/ui/ModalFactory.d.ts.map +1 -1
  77. package/dist/src/ui/ModalFactory.js +5 -1
  78. package/dist/src/ui/ModalFactory.js.map +1 -1
  79. package/dist/src/ui/index.js +1 -1
  80. package/dist/src/ui/index.js.map +1 -1
  81. package/dist/src/ui/modals/web/install.d.ts.map +1 -1
  82. package/dist/src/ui/modals/web/install.js.map +1 -1
  83. package/dist/types/connect-multichain.d.ts +18 -8
  84. package/package.json +2 -2
@@ -133,7 +133,15 @@ var init_rpc = __esm({
133
133
  _RPCReadonlyRequestErr.code = 52;
134
134
  RPCReadonlyRequestErr = _RPCReadonlyRequestErr;
135
135
  _RPCInvokeMethodErr = class _RPCInvokeMethodErr extends BaseErr {
136
- constructor(reason, rpcCode, rpcMessage) {
136
+ /**
137
+ * @param reason - MetaMask Connect invokeMethod reason.
138
+ * @param rpcCode - Original wallet JSON-RPC / EIP-1193 error code.
139
+ * @param rpcMessage - Original provider-facing wallet message, sourced only
140
+ * from the wallet's coded error. Unset when the wallet provides no message,
141
+ * so it may differ from `reason`, which can fall back through the cause chain.
142
+ * @param rpcData - Original JSON-RPC error data, when provided by the wallet.
143
+ */
144
+ constructor(reason, rpcCode, rpcMessage, rpcData) {
137
145
  super(
138
146
  `RPCErr${_RPCInvokeMethodErr.code}: RPC Client invoke method reason (${reason})`,
139
147
  _RPCInvokeMethodErr.code
@@ -141,6 +149,7 @@ var init_rpc = __esm({
141
149
  this.reason = reason;
142
150
  this.rpcCode = rpcCode;
143
151
  this.rpcMessage = rpcMessage;
152
+ this.rpcData = rpcData;
144
153
  }
145
154
  };
146
155
  _RPCInvokeMethodErr.code = 53;
@@ -273,7 +282,7 @@ var init_logger = __esm({
273
282
  });
274
283
 
275
284
  // src/domain/multichain/api/constants.ts
276
- var infuraRpcUrls, RPC_HANDLED_METHODS, SDK_HANDLED_METHODS;
285
+ var infuraRpcUrls, RPC_HANDLED_METHODS, SDK_HANDLED_METHODS, EIP1193_PASSTHROUGH_METHODS;
277
286
  var init_constants = __esm({
278
287
  "src/domain/multichain/api/constants.ts"() {
279
288
  "use strict";
@@ -438,6 +447,11 @@ var init_constants = __esm({
438
447
  "eth_uninstallFilter"
439
448
  ]);
440
449
  SDK_HANDLED_METHODS = /* @__PURE__ */ new Set(["eth_accounts", "eth_chainId"]);
450
+ EIP1193_PASSTHROUGH_METHODS = /* @__PURE__ */ new Set([
451
+ "wallet_addEthereumChain",
452
+ "wallet_switchEthereumChain",
453
+ "eth_accounts"
454
+ ]);
441
455
  }
442
456
  });
443
457
 
@@ -587,7 +601,7 @@ function hasExtension() {
587
601
  return detectionPromise;
588
602
  });
589
603
  }
590
- var import_bowser, PlatformType, detectionPromise;
604
+ var import_bowser, PlatformType, NATIVE_METAMASK_EIP6963_RDNS, detectionPromise;
591
605
  var init_platform = __esm({
592
606
  "src/domain/platform/index.ts"() {
593
607
  "use strict";
@@ -600,6 +614,10 @@ var init_platform = __esm({
600
614
  PlatformType2["ReactNative"] = "react-native";
601
615
  return PlatformType2;
602
616
  })(PlatformType || {});
617
+ NATIVE_METAMASK_EIP6963_RDNS = /* @__PURE__ */ new Set([
618
+ "io.metamask",
619
+ "io.metamask.mobile"
620
+ ]);
603
621
  detectionPromise = (() => __async(null, null, function* () {
604
622
  const pt = getPlatformType();
605
623
  if (pt === "nodejs" /* NonBrowser */ || pt === "react-native" /* ReactNative */) {
@@ -607,23 +625,30 @@ var init_platform = __esm({
607
625
  }
608
626
  return new Promise((resolve) => {
609
627
  const providers = [];
628
+ const targetWindow = window;
610
629
  const handler = (event) => {
611
630
  var _a3, _b;
612
631
  if ((_b = (_a3 = event == null ? void 0 : event.detail) == null ? void 0 : _a3.info) == null ? void 0 : _b.rdns) {
613
632
  providers.push(event.detail);
614
633
  }
615
634
  };
616
- window.addEventListener("eip6963:announceProvider", handler);
617
- window.dispatchEvent(new Event("eip6963:requestProvider"));
635
+ targetWindow.addEventListener("eip6963:announceProvider", handler);
636
+ targetWindow.dispatchEvent(new Event("eip6963:requestProvider"));
618
637
  setTimeout(() => {
619
- window.removeEventListener("eip6963:announceProvider", handler);
620
- const hasMetaMask = providers.some(
621
- (provider) => {
622
- var _a3, _b;
623
- return (_b = (_a3 = provider == null ? void 0 : provider.info) == null ? void 0 : _a3.rdns) == null ? void 0 : _b.startsWith("io.metamask");
638
+ try {
639
+ if (typeof (targetWindow == null ? void 0 : targetWindow.removeEventListener) === "function") {
640
+ targetWindow.removeEventListener("eip6963:announceProvider", handler);
624
641
  }
625
- );
626
- resolve(hasMetaMask);
642
+ const hasMetaMask = providers.some(
643
+ (provider) => {
644
+ var _a3;
645
+ return typeof ((_a3 = provider == null ? void 0 : provider.info) == null ? void 0 : _a3.rdns) === "string" && NATIVE_METAMASK_EIP6963_RDNS.has(provider.info.rdns);
646
+ }
647
+ );
648
+ resolve(hasMetaMask);
649
+ } catch (e) {
650
+ resolve(false);
651
+ }
627
652
  }, 300);
628
653
  });
629
654
  }))();
@@ -868,12 +893,14 @@ var init_analytics = __esm({
868
893
 
869
894
  // src/domain/utils/index.ts
870
895
  function getVersion() {
871
- return "0.0.0";
896
+ return packageVersion;
872
897
  }
898
+ var packageVersion;
873
899
  var init_utils = __esm({
874
900
  "src/domain/utils/index.ts"() {
875
901
  "use strict";
876
902
  init_analytics();
903
+ packageVersion = false ? "unknown" : "1.1.0";
877
904
  }
878
905
  });
879
906
 
@@ -1173,12 +1200,13 @@ var mwp_exports = {};
1173
1200
  __export(mwp_exports, {
1174
1201
  MWPTransport: () => MWPTransport
1175
1202
  });
1176
- var import_multichain_api_client2, import_rpc_errors2, DEFAULT_REQUEST_TIMEOUT2, CONNECTION_GRACE_PERIOD, DEFAULT_CONNECTION_TIMEOUT, DEFAULT_RESUME_TIMEOUT, SESSION_STORE_KEY, ACCOUNTS_STORE_KEY, CHAIN_STORE_KEY, PENDING_SESSION_REQUEST_KEY, CACHED_METHOD_LIST, CACHED_RESET_METHOD_LIST, logger, MWPTransport;
1203
+ var import_multichain_api_client2, import_rpc_errors2, import_utils8, DEFAULT_REQUEST_TIMEOUT2, CONNECTION_GRACE_PERIOD, DEFAULT_CONNECTION_TIMEOUT, DEFAULT_RESUME_TIMEOUT, SESSION_STORE_KEY, ACCOUNTS_STORE_KEY, CHAIN_STORE_KEY, PENDING_SESSION_REQUEST_KEY, CACHED_METHOD_LIST, CACHED_RESET_METHOD_LIST, logger, _MWPTransport_instances, onResumeHandler_fn, resumeSession_fn, startSession_fn, MWPTransport;
1177
1204
  var init_mwp = __esm({
1178
1205
  "src/multichain/transports/mwp/index.ts"() {
1179
1206
  "use strict";
1180
1207
  import_multichain_api_client2 = require("@metamask/multichain-api-client");
1181
1208
  import_rpc_errors2 = require("@metamask/rpc-errors");
1209
+ import_utils8 = require("@metamask/utils");
1182
1210
  init_domain();
1183
1211
  init_utils2();
1184
1212
  init_constants2();
@@ -1209,6 +1237,7 @@ var init_mwp = __esm({
1209
1237
  this.dappClient = dappClient;
1210
1238
  this.kvstore = kvstore;
1211
1239
  this.options = options;
1240
+ __privateAdd(this, _MWPTransport_instances);
1212
1241
  this.__pendingRequests = /* @__PURE__ */ new Map();
1213
1242
  this.notificationCallbacks = /* @__PURE__ */ new Set();
1214
1243
  this.dappClient.on("message", this.handleMessage.bind(this));
@@ -1280,14 +1309,33 @@ var init_mwp = __esm({
1280
1309
  const errorData = errorPayload;
1281
1310
  if (typeof errorData.code === "number" && typeof errorData.message === "string") {
1282
1311
  const { code, message: message2 } = errorData;
1312
+ const rawData = errorData.data;
1313
+ const data = (0, import_utils8.isValidJson)(rawData) ? rawData : void 0;
1283
1314
  if (code >= 1e3 && code <= 4999) {
1284
- return import_rpc_errors2.providerErrors.custom({ code, message: message2 });
1315
+ return import_rpc_errors2.providerErrors.custom({ code, message: message2, data });
1285
1316
  }
1286
- return new import_rpc_errors2.JsonRpcError(code, message2);
1317
+ return new import_rpc_errors2.JsonRpcError(code, message2, data);
1287
1318
  }
1288
1319
  const message = errorPayload instanceof Error ? errorPayload.message : JSON.stringify(errorPayload);
1289
1320
  return import_rpc_errors2.rpcErrors.internal({ message });
1290
1321
  }
1322
+ getResponseError(messagePayload) {
1323
+ if ("error" in messagePayload && messagePayload.error) {
1324
+ return messagePayload.error;
1325
+ }
1326
+ const { result } = messagePayload;
1327
+ if (typeof result === "object" && result !== null && "error" in result && result.error && this.isErrorPayload(result.error)) {
1328
+ return result.error;
1329
+ }
1330
+ return void 0;
1331
+ }
1332
+ isErrorPayload(errorPayload) {
1333
+ if (errorPayload instanceof Error) {
1334
+ return true;
1335
+ }
1336
+ const errorData = errorPayload;
1337
+ return typeof (errorData == null ? void 0 : errorData.code) === "number" && typeof (errorData == null ? void 0 : errorData.message) === "string";
1338
+ }
1291
1339
  handleMessage(message) {
1292
1340
  if (typeof message === "object" && message !== null) {
1293
1341
  if ("data" in message) {
@@ -1296,9 +1344,10 @@ var init_mwp = __esm({
1296
1344
  const request = this.pendingRequests.get(messagePayload.id);
1297
1345
  if (request) {
1298
1346
  clearTimeout(request.timeout);
1299
- if ("error" in messagePayload && messagePayload.error) {
1347
+ const responseError = this.getResponseError(messagePayload);
1348
+ if (responseError) {
1300
1349
  this.pendingRequests.delete(messagePayload.id);
1301
- request.reject(this.parseWalletError(messagePayload.error));
1350
+ request.reject(this.parseWalletError(responseError));
1302
1351
  return;
1303
1352
  }
1304
1353
  const requestWithName = __spreadProps(__spreadValues({}, messagePayload), {
@@ -1341,73 +1390,6 @@ var init_mwp = __esm({
1341
1390
  }
1342
1391
  }
1343
1392
  }
1344
- onResumeSuccess(resumeResolve, resumeReject, options) {
1345
- return __async(this, null, function* () {
1346
- var _a3, _b, _c, _d, _e, _f, _g;
1347
- try {
1348
- yield this.waitForWalletSessionIfNotCached();
1349
- const sessionRequest = yield this.request({
1350
- method: "wallet_getSession"
1351
- });
1352
- if (sessionRequest.error) {
1353
- return resumeReject(new Error(sessionRequest.error.message));
1354
- }
1355
- let walletSession = sessionRequest.result;
1356
- if (walletSession && options) {
1357
- const currentScopes = Object.keys(
1358
- (_a3 = walletSession == null ? void 0 : walletSession.sessionScopes) != null ? _a3 : {}
1359
- );
1360
- const proposedScopes = (_b = options == null ? void 0 : options.scopes) != null ? _b : [];
1361
- const proposedCaipAccountIds = (_c = options == null ? void 0 : options.caipAccountIds) != null ? _c : [];
1362
- const hasSameScopesAndAccounts = isSameScopesAndAccounts(
1363
- currentScopes,
1364
- proposedScopes,
1365
- walletSession,
1366
- proposedCaipAccountIds
1367
- );
1368
- if (options.forceRequest || !hasSameScopesAndAccounts) {
1369
- const optionalScopes = addValidAccounts(
1370
- getOptionalScopes((_d = options == null ? void 0 : options.scopes) != null ? _d : []),
1371
- getValidAccounts((_e = options == null ? void 0 : options.caipAccountIds) != null ? _e : [])
1372
- );
1373
- const sessionRequest2 = {
1374
- optionalScopes
1375
- };
1376
- const response = yield this.request({
1377
- method: "wallet_createSession",
1378
- params: sessionRequest2
1379
- });
1380
- if (response.error) {
1381
- return resumeReject(new Error(response.error.message));
1382
- }
1383
- walletSession = response.result;
1384
- }
1385
- } else if (!walletSession) {
1386
- const optionalScopes = addValidAccounts(
1387
- getOptionalScopes((_f = options == null ? void 0 : options.scopes) != null ? _f : []),
1388
- getValidAccounts((_g = options == null ? void 0 : options.caipAccountIds) != null ? _g : [])
1389
- );
1390
- const sessionRequest2 = { optionalScopes };
1391
- const response = yield this.request({
1392
- method: "wallet_createSession",
1393
- params: sessionRequest2
1394
- });
1395
- if (response.error) {
1396
- return resumeReject(new Error(response.error.message));
1397
- }
1398
- walletSession = response.result;
1399
- }
1400
- yield this.removeStoredPendingSessionRequest();
1401
- this.notifyCallbacks({
1402
- method: "wallet_sessionChanged",
1403
- params: walletSession
1404
- });
1405
- return resumeResolve();
1406
- } catch (err) {
1407
- return resumeReject(err);
1408
- }
1409
- });
1410
- }
1411
1393
  init() {
1412
1394
  return __async(this, null, function* () {
1413
1395
  });
@@ -1448,7 +1430,6 @@ var init_mwp = __esm({
1448
1430
  }
1449
1431
  connect(options) {
1450
1432
  return __async(this, null, function* () {
1451
- const { dappClient } = this;
1452
1433
  const session = yield this.getActiveSession();
1453
1434
  if (session) {
1454
1435
  logger("active session found", {
@@ -1457,116 +1438,11 @@ var init_mwp = __esm({
1457
1438
  expiresAt: session.expiresAt
1458
1439
  });
1459
1440
  }
1460
- const storedSessionRequestBeforeConnectionAttempt = yield this.getStoredPendingSessionRequest();
1461
- let timeout;
1462
- let initialConnectionMessageHandler;
1463
- const connectionPromise = new Promise((resolve, reject) => __async(this, null, function* () {
1464
- let connection;
1465
- if (session) {
1466
- connection = new Promise((resumeResolve, resumeReject) => {
1467
- var _a3;
1468
- if (this.dappClient.state === "CONNECTED") {
1469
- this.onResumeSuccess(resumeResolve, resumeReject, options);
1470
- } else {
1471
- this.dappClient.once("connected", () => __async(this, null, function* () {
1472
- this.onResumeSuccess(resumeResolve, resumeReject, options);
1473
- }));
1474
- dappClient.resume((_a3 = session == null ? void 0 : session.id) != null ? _a3 : "");
1475
- }
1476
- });
1477
- } else {
1478
- connection = new Promise(
1479
- (resolveConnection, rejectConnection) => {
1480
- var _a3, _b;
1481
- const optionalScopes = addValidAccounts(
1482
- getOptionalScopes((_a3 = options == null ? void 0 : options.scopes) != null ? _a3 : []),
1483
- getValidAccounts((_b = options == null ? void 0 : options.caipAccountIds) != null ? _b : [])
1484
- );
1485
- const sessionRequest = {
1486
- optionalScopes,
1487
- sessionProperties: options == null ? void 0 : options.sessionProperties
1488
- };
1489
- const request = {
1490
- jsonrpc: "2.0",
1491
- id: String(getUniqueRequestId()),
1492
- method: "wallet_createSession",
1493
- params: sessionRequest
1494
- };
1495
- initialConnectionMessageHandler = (message) => __async(this, null, function* () {
1496
- if (typeof message !== "object" || message === null) {
1497
- return;
1498
- }
1499
- if (!("data" in message)) {
1500
- return;
1501
- }
1502
- const messagePayload = message.data;
1503
- const isMatchingId = messagePayload.id === request.id;
1504
- const isMatchingMethod = messagePayload.method === "wallet_createSession" || messagePayload.method === "wallet_sessionChanged";
1505
- if (!isMatchingId && !isMatchingMethod) {
1506
- return;
1507
- }
1508
- if (messagePayload.error) {
1509
- return rejectConnection(
1510
- this.parseWalletError(messagePayload.error)
1511
- );
1512
- }
1513
- yield this.storeWalletSession(
1514
- request,
1515
- messagePayload
1516
- );
1517
- yield this.removeStoredPendingSessionRequest();
1518
- this.notifyCallbacks(messagePayload);
1519
- return resolveConnection();
1520
- });
1521
- this.dappClient.on("message", initialConnectionMessageHandler);
1522
- const platformType = getPlatformType();
1523
- const isQRCodeFlow = [
1524
- "web-desktop" /* DesktopWeb */,
1525
- "nodejs" /* NonBrowser */
1526
- ].includes(platformType);
1527
- const initialPayload = {
1528
- name: MULTICHAIN_PROVIDER_STREAM_NAME,
1529
- data: request
1530
- };
1531
- dappClient.connect({
1532
- mode: "trusted",
1533
- initialPayload: isQRCodeFlow ? void 0 : initialPayload
1534
- }).then(() => __async(this, null, function* () {
1535
- if (isQRCodeFlow) {
1536
- return dappClient.sendRequest(initialPayload);
1537
- }
1538
- return void 0;
1539
- })).catch((error) => {
1540
- if (initialConnectionMessageHandler) {
1541
- this.dappClient.off(
1542
- "message",
1543
- initialConnectionMessageHandler
1544
- );
1545
- }
1546
- rejectConnection(error);
1547
- });
1548
- }
1549
- );
1550
- }
1551
- timeout = setTimeout(
1552
- () => {
1553
- reject(new import_multichain_api_client2.TransportTimeoutError());
1554
- },
1555
- storedSessionRequestBeforeConnectionAttempt ? this.options.resumeTimeout : this.options.connectionTimeout
1556
- );
1557
- connection.then(resolve).catch(reject);
1558
- }));
1559
- return connectionPromise.catch((error) => __async(this, null, function* () {
1441
+ const connection = session ? __privateMethod(this, _MWPTransport_instances, resumeSession_fn).call(this, session, options) : __privateMethod(this, _MWPTransport_instances, startSession_fn).call(this, options);
1442
+ return connection.catch((error) => __async(this, null, function* () {
1560
1443
  yield this.dappClient.disconnect();
1561
1444
  throw error;
1562
1445
  })).finally(() => {
1563
- if (timeout) {
1564
- clearTimeout(timeout);
1565
- }
1566
- if (initialConnectionMessageHandler) {
1567
- this.dappClient.off("message", initialConnectionMessageHandler);
1568
- initialConnectionMessageHandler = void 0;
1569
- }
1570
1446
  this.removeStoredPendingSessionRequest();
1571
1447
  });
1572
1448
  });
@@ -1825,6 +1701,188 @@ var init_mwp = __esm({
1825
1701
  });
1826
1702
  }
1827
1703
  };
1704
+ _MWPTransport_instances = new WeakSet();
1705
+ onResumeHandler_fn = function(options) {
1706
+ return __async(this, null, function* () {
1707
+ var _a3, _b, _c, _d, _e, _f, _g;
1708
+ yield this.waitForWalletSessionIfNotCached();
1709
+ const sessionResponse = yield this.request({ method: "wallet_getSession" });
1710
+ if (sessionResponse.error) {
1711
+ throw new Error(sessionResponse.error.message);
1712
+ }
1713
+ let walletSession = sessionResponse.result;
1714
+ if (walletSession && options) {
1715
+ const currentScopes = Object.keys(
1716
+ (_a3 = walletSession == null ? void 0 : walletSession.sessionScopes) != null ? _a3 : {}
1717
+ );
1718
+ const proposedScopes = (_b = options == null ? void 0 : options.scopes) != null ? _b : [];
1719
+ const proposedCaipAccountIds = (_c = options == null ? void 0 : options.caipAccountIds) != null ? _c : [];
1720
+ const hasSameScopesAndAccounts = isSameScopesAndAccounts(
1721
+ currentScopes,
1722
+ proposedScopes,
1723
+ walletSession,
1724
+ proposedCaipAccountIds
1725
+ );
1726
+ if (options.forceRequest || !hasSameScopesAndAccounts) {
1727
+ const optionalScopes = addValidAccounts(
1728
+ getOptionalScopes((_d = options == null ? void 0 : options.scopes) != null ? _d : []),
1729
+ getValidAccounts((_e = options == null ? void 0 : options.caipAccountIds) != null ? _e : [])
1730
+ );
1731
+ const sessionRequest = {
1732
+ optionalScopes
1733
+ };
1734
+ const response = yield this.request({
1735
+ method: "wallet_createSession",
1736
+ params: sessionRequest
1737
+ });
1738
+ if (response.error) {
1739
+ throw new Error(response.error.message);
1740
+ }
1741
+ walletSession = response.result;
1742
+ }
1743
+ } else if (!walletSession) {
1744
+ const optionalScopes = addValidAccounts(
1745
+ getOptionalScopes((_f = options == null ? void 0 : options.scopes) != null ? _f : []),
1746
+ getValidAccounts((_g = options == null ? void 0 : options.caipAccountIds) != null ? _g : [])
1747
+ );
1748
+ const sessionRequest = {
1749
+ optionalScopes
1750
+ };
1751
+ const response = yield this.request({
1752
+ method: "wallet_createSession",
1753
+ params: sessionRequest
1754
+ });
1755
+ if (response.error) {
1756
+ throw new Error(response.error.message);
1757
+ }
1758
+ walletSession = response.result;
1759
+ }
1760
+ yield this.removeStoredPendingSessionRequest();
1761
+ this.notifyCallbacks({
1762
+ method: "wallet_sessionChanged",
1763
+ params: walletSession
1764
+ });
1765
+ });
1766
+ };
1767
+ resumeSession_fn = function(session, options) {
1768
+ return __async(this, null, function* () {
1769
+ var _a3;
1770
+ const isContinuingPriorAttempt = (yield this.getStoredPendingSessionRequest()) !== null;
1771
+ const resumeDeferred = (0, import_utils8.createDeferredPromise)();
1772
+ const runOnResumeHandler = () => __async(this, null, function* () {
1773
+ try {
1774
+ resumeDeferred.resolve(yield __privateMethod(this, _MWPTransport_instances, onResumeHandler_fn).call(this, options));
1775
+ } catch (err) {
1776
+ resumeDeferred.reject(err);
1777
+ }
1778
+ });
1779
+ if (this.dappClient.state === "CONNECTED") {
1780
+ runOnResumeHandler();
1781
+ } else {
1782
+ this.dappClient.once("connected", runOnResumeHandler);
1783
+ this.dappClient.resume((_a3 = session.id) != null ? _a3 : "").catch((err) => resumeDeferred.reject(err));
1784
+ }
1785
+ const timeoutDeferred = (0, import_utils8.createDeferredPromise)();
1786
+ const timeout = setTimeout(
1787
+ () => timeoutDeferred.reject(new import_multichain_api_client2.TransportTimeoutError()),
1788
+ isContinuingPriorAttempt ? this.options.resumeTimeout : this.options.connectionTimeout
1789
+ );
1790
+ const cleanup = () => this.dappClient.off("connected", runOnResumeHandler);
1791
+ return Promise.race([
1792
+ resumeDeferred.promise,
1793
+ timeoutDeferred.promise
1794
+ ]).finally(() => {
1795
+ clearTimeout(timeout);
1796
+ cleanup();
1797
+ });
1798
+ });
1799
+ };
1800
+ startSession_fn = function(options) {
1801
+ return __async(this, null, function* () {
1802
+ var _a3, _b;
1803
+ const { dappClient } = this;
1804
+ const isContinuingPriorAttempt = (yield this.getStoredPendingSessionRequest()) !== null;
1805
+ const connDeferred = (0, import_utils8.createDeferredPromise)();
1806
+ const optionalScopes = addValidAccounts(
1807
+ getOptionalScopes((_a3 = options == null ? void 0 : options.scopes) != null ? _a3 : []),
1808
+ getValidAccounts((_b = options == null ? void 0 : options.caipAccountIds) != null ? _b : [])
1809
+ );
1810
+ const sessionRequest = {
1811
+ optionalScopes,
1812
+ sessionProperties: options == null ? void 0 : options.sessionProperties
1813
+ };
1814
+ const request = {
1815
+ jsonrpc: "2.0",
1816
+ id: String(getUniqueRequestId()),
1817
+ method: "wallet_createSession",
1818
+ params: sessionRequest
1819
+ };
1820
+ let handler;
1821
+ const removeHandler = () => {
1822
+ if (handler) {
1823
+ this.dappClient.off("message", handler);
1824
+ handler = void 0;
1825
+ }
1826
+ };
1827
+ handler = (message) => __async(this, null, function* () {
1828
+ if (typeof message !== "object" || message === null) {
1829
+ return;
1830
+ }
1831
+ if (!("data" in message)) {
1832
+ return;
1833
+ }
1834
+ const messagePayload = message.data;
1835
+ const isMatchingId = messagePayload.id === request.id;
1836
+ const isMatchingMethod = messagePayload.method === "wallet_createSession" || messagePayload.method === "wallet_sessionChanged";
1837
+ if (!isMatchingId && !isMatchingMethod) {
1838
+ return;
1839
+ }
1840
+ const responseError = this.getResponseError(messagePayload);
1841
+ if (responseError) {
1842
+ connDeferred.reject(this.parseWalletError(responseError));
1843
+ return;
1844
+ }
1845
+ yield this.storeWalletSession(
1846
+ request,
1847
+ messagePayload
1848
+ );
1849
+ yield this.removeStoredPendingSessionRequest();
1850
+ this.notifyCallbacks(messagePayload);
1851
+ connDeferred.resolve();
1852
+ });
1853
+ this.dappClient.on("message", handler);
1854
+ const platformType = getPlatformType();
1855
+ const isQRCodeFlow = [
1856
+ "web-desktop" /* DesktopWeb */,
1857
+ "nodejs" /* NonBrowser */
1858
+ ].includes(platformType);
1859
+ const initialPayload = {
1860
+ name: MULTICHAIN_PROVIDER_STREAM_NAME,
1861
+ data: request
1862
+ };
1863
+ dappClient.connect({
1864
+ mode: "trusted",
1865
+ initialPayload: isQRCodeFlow ? void 0 : initialPayload
1866
+ }).then(() => __async(this, null, function* () {
1867
+ if (isQRCodeFlow) {
1868
+ return dappClient.sendRequest(initialPayload);
1869
+ }
1870
+ return void 0;
1871
+ })).catch((error) => connDeferred.reject(error));
1872
+ const timeoutDeferred = (0, import_utils8.createDeferredPromise)();
1873
+ const timeout = setTimeout(
1874
+ () => timeoutDeferred.reject(new import_multichain_api_client2.TransportTimeoutError()),
1875
+ isContinuingPriorAttempt ? this.options.resumeTimeout : this.options.connectionTimeout
1876
+ );
1877
+ return Promise.race([
1878
+ connDeferred.promise,
1879
+ timeoutDeferred.promise
1880
+ ]).finally(() => {
1881
+ clearTimeout(timeout);
1882
+ removeHandler();
1883
+ });
1884
+ });
1885
+ };
1828
1886
  }
1829
1887
  });
1830
1888
 
@@ -1997,9 +2055,7 @@ var init_install = __esm({
1997
2055
  mount() {
1998
2056
  var _a3;
1999
2057
  const { options } = this;
2000
- const modal = document.createElement(
2001
- "mm-install-modal"
2002
- );
2058
+ const modal = document.createElement("mm-install-modal");
2003
2059
  modal.showInstallModal = options.showInstallModal;
2004
2060
  modal.addEventListener("close", (ev) => {
2005
2061
  const { detail } = ev;
@@ -2183,6 +2239,7 @@ var init_web2 = __esm({
2183
2239
  // src/index.browser.ts
2184
2240
  var index_browser_exports = {};
2185
2241
  __export(index_browser_exports, {
2242
+ EIP1193_PASSTHROUGH_METHODS: () => EIP1193_PASSTHROUGH_METHODS,
2186
2243
  EventEmitter: () => EventEmitter,
2187
2244
  Modal: () => Modal,
2188
2245
  MultichainCore: () => MultichainCore,
@@ -2210,7 +2267,8 @@ __export(index_browser_exports, {
2210
2267
  isEnabled: () => isEnabled,
2211
2268
  isMetamaskExtensionInstalled: () => isMetamaskExtensionInstalled,
2212
2269
  isRejectionError: () => isRejectionError,
2213
- isSecure: () => isSecure
2270
+ isSecure: () => isSecure,
2271
+ packageVersion: () => packageVersion
2214
2272
  });
2215
2273
  module.exports = __toCommonJS(index_browser_exports);
2216
2274
 
@@ -2227,6 +2285,7 @@ init_domain();
2227
2285
  // src/multichain/index.ts
2228
2286
  var import_analytics4 = require("@metamask/analytics");
2229
2287
  var import_multichain_api_client3 = require("@metamask/multichain-api-client");
2288
+ var import_utils10 = require("@metamask/utils");
2230
2289
 
2231
2290
  // src/config/index.ts
2232
2291
  var MWP_RELAY_URL = "wss://mm-sdk-relay.api.cx.metamask.io/connection/websocket";
@@ -2350,17 +2409,93 @@ var import_analytics2 = require("@metamask/analytics");
2350
2409
  init_domain();
2351
2410
  init_utils2();
2352
2411
  init_analytics();
2412
+
2413
+ // src/multichain/rpc/invocationError.ts
2414
+ var import_utils3 = require("@metamask/utils");
2415
+ init_domain();
2416
+ var MAX_ERROR_CAUSE_DEPTH = 5;
2417
+ function getErrorObject(value) {
2418
+ if (typeof value === "object" && value !== null) {
2419
+ return value;
2420
+ }
2421
+ return void 0;
2422
+ }
2423
+ function getNumericCode(value) {
2424
+ return typeof value === "number" ? value : void 0;
2425
+ }
2426
+ function getNonEmptyMessage(value) {
2427
+ return typeof value === "string" && value.length > 0 ? value : void 0;
2428
+ }
2429
+ function getJsonData(value) {
2430
+ return value !== void 0 && (0, import_utils3.isValidJson)(value) ? value : void 0;
2431
+ }
2432
+ function getFirstNonEmptyMessage(values) {
2433
+ for (const value of values) {
2434
+ const message = getNonEmptyMessage(value);
2435
+ if (message !== void 0) {
2436
+ return message;
2437
+ }
2438
+ }
2439
+ return void 0;
2440
+ }
2441
+ function getErrorObjectChain(errorObject) {
2442
+ const chain = [];
2443
+ let currentObject = errorObject;
2444
+ for (let depth = 0; currentObject !== void 0 && depth < MAX_ERROR_CAUSE_DEPTH; depth += 1) {
2445
+ chain.push(currentObject);
2446
+ currentObject = getErrorObject(currentObject.cause);
2447
+ }
2448
+ return chain;
2449
+ }
2450
+ function getCodedErrorDetails(value) {
2451
+ const code = getNumericCode(value == null ? void 0 : value.code);
2452
+ if (code === void 0) {
2453
+ return void 0;
2454
+ }
2455
+ const message = getNonEmptyMessage(value == null ? void 0 : value.message);
2456
+ const data = getJsonData(value == null ? void 0 : value.data);
2457
+ return __spreadValues(__spreadValues({
2458
+ code
2459
+ }, message === void 0 ? {} : { message }), data === void 0 ? {} : { data });
2460
+ }
2461
+ function getInvocationErrorDetails(error) {
2462
+ var _a3, _b, _c, _d;
2463
+ const errorObject = getErrorObject(error);
2464
+ const errorObjectChain = getErrorObjectChain(errorObject);
2465
+ const primitiveMessage = getNonEmptyMessage(error);
2466
+ for (const [index, currentObject] of errorObjectChain.entries()) {
2467
+ const codedDetails = getCodedErrorDetails(currentObject);
2468
+ if (codedDetails) {
2469
+ const descendantObjects = errorObjectChain.slice(index + 1);
2470
+ const ancestorObjects = errorObjectChain.slice(0, index);
2471
+ const descendantMessage = getFirstNonEmptyMessage(
2472
+ descendantObjects.map((object) => object.message)
2473
+ );
2474
+ const ancestorMessage = getFirstNonEmptyMessage([
2475
+ primitiveMessage,
2476
+ ...ancestorObjects.map((object) => object.message)
2477
+ ]);
2478
+ const reason2 = (_c = (_b = (_a3 = codedDetails.message) != null ? _a3 : descendantMessage) != null ? _b : ancestorMessage) != null ? _c : "Unknown error";
2479
+ return __spreadValues(__spreadValues({
2480
+ reason: reason2,
2481
+ rpcCode: codedDetails.code
2482
+ }, codedDetails.message === void 0 ? {} : { rpcMessage: codedDetails.message }), codedDetails.data === void 0 ? {} : { rpcData: codedDetails.data });
2483
+ }
2484
+ }
2485
+ const reason = (_d = primitiveMessage != null ? primitiveMessage : getFirstNonEmptyMessage(errorObjectChain.map((object) => object.message))) != null ? _d : "Unknown error";
2486
+ return {
2487
+ reason
2488
+ };
2489
+ }
2353
2490
  function toRPCInvokeMethodErr(error) {
2354
- var _a3;
2355
2491
  if (error instanceof RPCInvokeMethodErr) {
2356
2492
  return error;
2357
2493
  }
2358
- const castError = error;
2359
- return new RPCInvokeMethodErr(
2360
- (_a3 = castError.message) != null ? _a3 : "Unknown error",
2361
- castError.code
2362
- );
2494
+ const { reason, rpcCode, rpcMessage, rpcData } = getInvocationErrorDetails(error);
2495
+ return new RPCInvokeMethodErr(reason, rpcCode, rpcMessage, rpcData);
2363
2496
  }
2497
+
2498
+ // src/multichain/rpc/requestRouter.ts
2364
2499
  var _RequestRouter_instances, withAnalyticsTracking_fn, trackWalletActionRequested_fn, trackWalletActionSucceeded_fn, trackWalletActionFailed_fn, trackWalletActionRejected_fn;
2365
2500
  var RequestRouter = class {
2366
2501
  constructor(transport, rpcClient, config, transportType) {
@@ -2380,6 +2515,9 @@ var RequestRouter = class {
2380
2515
  invokeMethod(options) {
2381
2516
  return __async(this, null, function* () {
2382
2517
  const { method } = options.request;
2518
+ if (EIP1193_PASSTHROUGH_METHODS.has(method)) {
2519
+ return this.handleWithEip1193Passthrough(options);
2520
+ }
2383
2521
  if (RPC_HANDLED_METHODS.has(method)) {
2384
2522
  return this.handleWithRpcNode(options);
2385
2523
  }
@@ -2389,6 +2527,29 @@ var RequestRouter = class {
2389
2527
  return this.handleWithWallet(options);
2390
2528
  });
2391
2529
  }
2530
+ /**
2531
+ * Forwards EIP-1193 / legacy provider methods (e.g. `wallet_addEthereumChain`,
2532
+ * `wallet_switchEthereumChain`, `eth_accounts`) directly to the underlying
2533
+ * transport's `sendEip1193Message`, bypassing the multichain
2534
+ * `wallet_invokeMethod` envelope. These methods are wallet-side concerns the
2535
+ * Multichain API does not model, so we forward the raw `{ method, params }`
2536
+ * payload and return the wallet's full JSON-RPC response envelope unchanged.
2537
+ *
2538
+ * Analytics tracking is intentionally skipped here: ecosystem clients
2539
+ * (e.g. `connect-evm`) emit their own `wallet_action_*` events around these
2540
+ * passthrough calls, and adding router-level tracking would double-count.
2541
+ *
2542
+ * @param options
2543
+ */
2544
+ handleWithEip1193Passthrough(options) {
2545
+ return __async(this, null, function* () {
2546
+ const response = yield this.transport.sendEip1193Message({
2547
+ method: options.request.method,
2548
+ params: options.request.params
2549
+ });
2550
+ return response.result;
2551
+ });
2552
+ }
2392
2553
  /**
2393
2554
  * Forwards the request directly to the wallet via the transport.
2394
2555
  *
@@ -2421,12 +2582,7 @@ var RequestRouter = class {
2421
2582
  }
2422
2583
  const response = yield request;
2423
2584
  if (response.error) {
2424
- const { error } = response;
2425
- throw new RPCInvokeMethodErr(
2426
- `RPC Request failed with code ${error.code}: ${error.message}`,
2427
- error.code,
2428
- error.message
2429
- );
2585
+ throw toRPCInvokeMethodErr(response.error);
2430
2586
  }
2431
2587
  return response.result;
2432
2588
  }));
@@ -2480,13 +2636,15 @@ withAnalyticsTracking_fn = function(options, execute) {
2480
2636
  yield __privateMethod(this, _RequestRouter_instances, trackWalletActionSucceeded_fn).call(this, options);
2481
2637
  return result;
2482
2638
  } catch (error) {
2483
- const isRejection = isRejectionError(error);
2639
+ const normalizedError = toRPCInvokeMethodErr(error);
2640
+ const analyticsError = normalizedError.rpcCode === void 0 ? error : normalizedError;
2641
+ const isRejection = isRejectionError(analyticsError);
2484
2642
  if (isRejection) {
2485
2643
  yield __privateMethod(this, _RequestRouter_instances, trackWalletActionRejected_fn).call(this, options);
2486
2644
  } else {
2487
- yield __privateMethod(this, _RequestRouter_instances, trackWalletActionFailed_fn).call(this, options, error);
2645
+ yield __privateMethod(this, _RequestRouter_instances, trackWalletActionFailed_fn).call(this, options, analyticsError);
2488
2646
  }
2489
- throw toRPCInvokeMethodErr(error);
2647
+ throw normalizedError;
2490
2648
  }
2491
2649
  });
2492
2650
  };
@@ -2538,9 +2696,10 @@ trackWalletActionRejected_fn = function(options) {
2538
2696
 
2539
2697
  // src/multichain/transports/default/index.ts
2540
2698
  var import_multichain_api_client = require("@metamask/multichain-api-client");
2699
+ var import_utils5 = require("@metamask/utils");
2541
2700
  init_utils2();
2542
2701
  var DEFAULT_REQUEST_TIMEOUT = 60 * 1e3;
2543
- var _notificationCallbacks, _transport, _defaultRequestOptions, _pendingRequests, _handleResponseListener, _handleNotificationListener, _DefaultTransport_instances, notifyCallbacks_fn, isMetamaskProviderEvent_fn, handleResponse_fn, handleNotification_fn, setupMessageListener_fn, init_fn;
2702
+ var _notificationCallbacks, _transport, _defaultRequestOptions, _pendingRequests, _handleResponseListener, _handleNotificationListener, _DefaultTransport_instances, notifyCallbacks_fn, parseWalletError_fn, isMetamaskProviderEvent_fn, handleResponse_fn, handleNotification_fn, setupMessageListener_fn, init_fn;
2544
2703
  var DefaultTransport = class {
2545
2704
  constructor() {
2546
2705
  __privateAdd(this, _DefaultTransport_instances);
@@ -2676,7 +2835,11 @@ var DefaultTransport = class {
2676
2835
  }
2677
2836
  request(_0) {
2678
2837
  return __async(this, arguments, function* (request, options = __privateGet(this, _defaultRequestOptions)) {
2679
- return __privateGet(this, _transport).request(request, options);
2838
+ const response = yield __privateGet(this, _transport).request(request, options);
2839
+ if (response.error) {
2840
+ throw __privateMethod(this, _DefaultTransport_instances, parseWalletError_fn).call(this, response.error);
2841
+ }
2842
+ return response;
2680
2843
  });
2681
2844
  }
2682
2845
  onNotification(callback) {
@@ -2720,6 +2883,20 @@ notifyCallbacks_fn = function(data) {
2720
2883
  }
2721
2884
  }
2722
2885
  };
2886
+ parseWalletError_fn = function(errorPayload) {
2887
+ const errorData = errorPayload;
2888
+ const error = new Error(
2889
+ typeof errorData.message === "string" ? errorData.message : "Request failed"
2890
+ );
2891
+ if (typeof errorData.code === "number") {
2892
+ error.code = errorData.code;
2893
+ }
2894
+ const { data } = errorData;
2895
+ if ((0, import_utils5.isValidJson)(data)) {
2896
+ error.data = data;
2897
+ }
2898
+ return error;
2899
+ };
2723
2900
  isMetamaskProviderEvent_fn = function(event) {
2724
2901
  var _a3, _b;
2725
2902
  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
@@ -2742,13 +2919,7 @@ handleResponse_fn = function(event) {
2742
2919
  __privateGet(this, _pendingRequests).delete(responseId);
2743
2920
  const response = responseData;
2744
2921
  if ("error" in response && response.error) {
2745
- const error = new Error(
2746
- response.error.message || "Request failed"
2747
- );
2748
- if (typeof response.error.code === "number") {
2749
- error.code = response.error.code;
2750
- }
2751
- pendingRequest.reject(error);
2922
+ pendingRequest.reject(__privateMethod(this, _DefaultTransport_instances, parseWalletError_fn).call(this, response.error));
2752
2923
  } else {
2753
2924
  pendingRequest.resolve(response);
2754
2925
  }
@@ -2786,22 +2957,21 @@ init_fn = function() {
2786
2957
  // src/multichain/transports/multichainApiClientWrapper/index.ts
2787
2958
  var import_rpc_errors = require("@metamask/rpc-errors");
2788
2959
  init_utils2();
2789
- var _notificationCallbacks2, _MultichainApiClientWrapperTransport_instances, walletCreateSession_fn, walletGetSession_fn, walletRevokeSession_fn, walletInvokeMethod_fn;
2960
+ var _notificationCallbacks2, _getTransport, _MultichainApiClientWrapperTransport_instances, walletCreateSession_fn, walletGetSession_fn, walletRevokeSession_fn, walletInvokeMethod_fn;
2790
2961
  var MultichainApiClientWrapperTransport = class {
2791
- constructor(metamaskConnectMultichain) {
2962
+ constructor(metamaskConnectMultichain, getTransport) {
2792
2963
  this.metamaskConnectMultichain = metamaskConnectMultichain;
2793
2964
  __privateAdd(this, _MultichainApiClientWrapperTransport_instances);
2794
2965
  __privateAdd(this, _notificationCallbacks2, /* @__PURE__ */ new Set());
2966
+ __privateAdd(this, _getTransport);
2967
+ __privateSet(this, _getTransport, getTransport);
2795
2968
  }
2796
2969
  isTransportDefined() {
2797
- try {
2798
- return Boolean(this.metamaskConnectMultichain.transport);
2799
- } catch (_error) {
2800
- return false;
2801
- }
2970
+ return __privateGet(this, _getTransport).call(this) !== void 0;
2802
2971
  }
2803
2972
  isTransportConnected() {
2804
- return this.isTransportDefined() && this.metamaskConnectMultichain.transport.isConnected();
2973
+ var _a3, _b;
2974
+ return (_b = (_a3 = __privateGet(this, _getTransport).call(this)) == null ? void 0 : _a3.isConnected()) != null ? _b : false;
2805
2975
  }
2806
2976
  clearNotificationCallbacks() {
2807
2977
  __privateGet(this, _notificationCallbacks2).clear();
@@ -2817,10 +2987,11 @@ var MultichainApiClientWrapperTransport = class {
2817
2987
  this.notificationListener = void 0;
2818
2988
  }
2819
2989
  setupTransportNotificationListener() {
2820
- if (!this.isTransportDefined() || this.notificationListener) {
2990
+ const transport = __privateGet(this, _getTransport).call(this);
2991
+ if (!transport || this.notificationListener) {
2821
2992
  return;
2822
2993
  }
2823
- this.notificationListener = this.metamaskConnectMultichain.transport.onNotification(
2994
+ this.notificationListener = transport.onNotification(
2824
2995
  this.notifyCallbacks.bind(this)
2825
2996
  );
2826
2997
  }
@@ -2870,6 +3041,7 @@ var MultichainApiClientWrapperTransport = class {
2870
3041
  }
2871
3042
  };
2872
3043
  _notificationCallbacks2 = new WeakMap();
3044
+ _getTransport = new WeakMap();
2873
3045
  _MultichainApiClientWrapperTransport_instances = new WeakSet();
2874
3046
  walletCreateSession_fn = function(request) {
2875
3047
  return __async(this, null, function* () {
@@ -2893,14 +3065,19 @@ walletCreateSession_fn = function(request) {
2893
3065
  accounts,
2894
3066
  createSessionParams.sessionProperties
2895
3067
  );
2896
- return this.metamaskConnectMultichain.transport.request({
3068
+ const transport = __privateGet(this, _getTransport).call(this);
3069
+ if (!transport) {
3070
+ throw new Error("Transport not initialized after connect");
3071
+ }
3072
+ return transport.request({
2897
3073
  method: "wallet_getSession"
2898
3074
  });
2899
3075
  });
2900
3076
  };
2901
3077
  walletGetSession_fn = function(request) {
2902
3078
  return __async(this, null, function* () {
2903
- if (!this.isTransportConnected()) {
3079
+ const transport = __privateGet(this, _getTransport).call(this);
3080
+ if (!(transport == null ? void 0 : transport.isConnected())) {
2904
3081
  return {
2905
3082
  jsonrpc: "2.0",
2906
3083
  id: request.id,
@@ -2909,7 +3086,7 @@ walletGetSession_fn = function(request) {
2909
3086
  }
2910
3087
  };
2911
3088
  }
2912
- return this.metamaskConnectMultichain.transport.request({
3089
+ return transport.request({
2913
3090
  method: "wallet_getSession"
2914
3091
  });
2915
3092
  });
@@ -2987,7 +3164,7 @@ function setupAnalyticsGlobals(options, storage, setAnonId) {
2987
3164
  import_analytics4.analytics.enable();
2988
3165
  });
2989
3166
  }
2990
- 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;
3167
+ 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;
2991
3168
  var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends MultichainCore {
2992
3169
  constructor(options) {
2993
3170
  var _a3, _b, _c, _d;
@@ -3000,9 +3177,7 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
3000
3177
  }),
3001
3178
  analytics: normalizeAnalyticsOptions(options.analytics),
3002
3179
  versions: __spreadValues({
3003
- // typeof guard needed: Metro (React Native) bundles TS source directly,
3004
- // bypassing the tsup build that substitutes __PACKAGE_VERSION__.
3005
- "connect-multichain": false ? "unknown" : "0.15.0"
3180
+ "connect-multichain": getVersion()
3006
3181
  }, (_d = options.versions) != null ? _d : {})
3007
3182
  });
3008
3183
  super(allOptions);
@@ -3018,7 +3193,8 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
3018
3193
  __privateAdd(this, _anonId);
3019
3194
  __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}`);
3020
3195
  __privateSet(this, _providerTransportWrapper, new MultichainApiClientWrapperTransport(
3021
- this
3196
+ this,
3197
+ () => __privateGet(this, _transport2)
3022
3198
  ));
3023
3199
  __privateSet(this, _provider, (0, import_multichain_api_client3.getMultichainClient)({
3024
3200
  transport: __privateGet(this, _providerTransportWrapper)
@@ -3037,12 +3213,6 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
3037
3213
  get provider() {
3038
3214
  return __privateGet(this, _provider);
3039
3215
  }
3040
- get transport() {
3041
- if (!__privateGet(this, _transport2)) {
3042
- throw new Error("Transport not initialized, establish connection first");
3043
- }
3044
- return __privateGet(this, _transport2);
3045
- }
3046
3216
  get dappClient() {
3047
3217
  if (!__privateGet(this, _dappClient)) {
3048
3218
  throw new Error("DappClient not initialized, establish connection first");
@@ -3056,6 +3226,9 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
3056
3226
  get storage() {
3057
3227
  return this.options.storage;
3058
3228
  }
3229
+ get version() {
3230
+ return getVersion();
3231
+ }
3059
3232
  // Creates a singleton instance of MetaMaskConnectMultichain.
3060
3233
  // If the singleton already exists, it merges the incoming options with the
3061
3234
  // existing singleton options for the following keys: `api.supportedNetworks`,
@@ -3070,6 +3243,11 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
3070
3243
  const existing = globalObject[SINGLETON_KEY];
3071
3244
  if (existing) {
3072
3245
  const instance = yield existing;
3246
+ if (instance.version !== getVersion()) {
3247
+ console.warn(
3248
+ `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.`
3249
+ );
3250
+ }
3073
3251
  instance.mergeOptions(options);
3074
3252
  if (instance instanceof _MetaMaskConnectMultichain) {
3075
3253
  yield __privateMethod(_a3 = instance, _MetaMaskConnectMultichain_instances, setupAnalytics_fn).call(_a3);
@@ -3093,12 +3271,12 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
3093
3271
  }
3094
3272
  yield __privateMethod(_a4 = instance, _MetaMaskConnectMultichain_instances, init_fn2).call(_a4);
3095
3273
  return instance;
3096
- }))();
3097
- globalObject[SINGLETON_KEY] = instancePromise;
3098
- instancePromise.catch((error) => {
3274
+ }))().catch((error) => {
3099
3275
  globalObject[SINGLETON_KEY] = void 0;
3100
3276
  console.error("Error initializing MetaMaskConnectMultichain", error);
3277
+ throw error;
3101
3278
  });
3279
+ globalObject[SINGLETON_KEY] = instancePromise;
3102
3280
  return instancePromise;
3103
3281
  });
3104
3282
  }
@@ -3158,9 +3336,9 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
3158
3336
  forceRequest
3159
3337
  }).then(() => __async(this, null, function* () {
3160
3338
  if (__privateGet(this, _transportType) === "mwp" /* MWP */) {
3161
- return this.storage.setTransport("mwp" /* MWP */);
3339
+ return this.storage.setTransportType("mwp" /* MWP */);
3162
3340
  }
3163
- return this.storage.setTransport("browser" /* Browser */);
3341
+ return this.storage.setTransportType("browser" /* Browser */);
3164
3342
  })), scopes, transportType);
3165
3343
  }
3166
3344
  if (platformType === "in-app-browser" /* MetaMaskMobileWebview */) {
@@ -3189,11 +3367,6 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
3189
3367
  return __privateMethod(this, _MetaMaskConnectMultichain_instances, handleConnection_fn).call(this, __privateMethod(this, _MetaMaskConnectMultichain_instances, showInstallModal_fn).call(this, shouldShowInstallModal, mergedScopes, mergedCaipAccountIds, nonEmptySessionProperties), scopes, transportType);
3190
3368
  });
3191
3369
  }
3192
- emit(event, args) {
3193
- var _a3, _b;
3194
- (_b = (_a3 = this.options.transport) == null ? void 0 : _a3.onNotification) == null ? void 0 : _b.call(_a3, { method: event, params: args });
3195
- super.emit(event, args);
3196
- }
3197
3370
  disconnect() {
3198
3371
  return __async(this, arguments, function* (scopes = []) {
3199
3372
  var _a3, _b, _c;
@@ -3203,7 +3376,7 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
3203
3376
  );
3204
3377
  yield (_a3 = __privateGet(this, _transport2)) == null ? void 0 : _a3.disconnect(scopes);
3205
3378
  if (remainingScopes.length === 0) {
3206
- yield this.storage.removeTransport();
3379
+ yield this.storage.removeTransportType();
3207
3380
  if (__privateGet(this, _transportType) !== "browser" /* Browser */) {
3208
3381
  yield (_b = __privateGet(this, _listener)) == null ? void 0 : _b.call(this);
3209
3382
  (_c = __privateGet(this, _beforeUnloadListener)) == null ? void 0 : _c.call(this);
@@ -3221,7 +3394,8 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
3221
3394
  invokeMethod(request) {
3222
3395
  return __async(this, null, function* () {
3223
3396
  var _a3;
3224
- const { transport, options } = this;
3397
+ const transport = __privateMethod(this, _MetaMaskConnectMultichain_instances, transportOrThrow_fn).call(this);
3398
+ const { options } = this;
3225
3399
  const rpcClient = new RpcClient(options, __privateGet(this, _sdkInfo));
3226
3400
  const requestRouter = new RequestRouter(
3227
3401
  transport,
@@ -3240,7 +3414,7 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
3240
3414
  const shouldOpenDeeplink = secure && !showInstallModal;
3241
3415
  if (shouldOpenDeeplink) {
3242
3416
  setTimeout(() => __async(this, null, function* () {
3243
- const session = yield this.transport.getActiveSession();
3417
+ const session = yield __privateMethod(this, _MetaMaskConnectMultichain_instances, transportOrThrow_fn).call(this).getActiveSession();
3244
3418
  if (!session) {
3245
3419
  throw new Error("No active session found");
3246
3420
  }
@@ -3264,10 +3438,13 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
3264
3438
  this.emit("wallet_sessionChanged", emptySession);
3265
3439
  return;
3266
3440
  }
3267
- const response = yield this.transport.request({
3441
+ const response = yield __privateGet(this, _transport2).request({
3268
3442
  method: "wallet_getSession"
3269
3443
  });
3270
- this.emit("wallet_sessionChanged", (_b = response.result) != null ? _b : emptySession);
3444
+ this.emit(
3445
+ "wallet_sessionChanged",
3446
+ (_b = response.result) != null ? _b : emptySession
3447
+ );
3271
3448
  });
3272
3449
  }
3273
3450
  };
@@ -3279,8 +3456,14 @@ _beforeUnloadListener = new WeakMap();
3279
3456
  _transportType = new WeakMap();
3280
3457
  _listener = new WeakMap();
3281
3458
  _anonId = new WeakMap();
3282
- _sdkInfo = new WeakMap();
3283
3459
  _MetaMaskConnectMultichain_instances = new WeakSet();
3460
+ transportOrThrow_fn = function() {
3461
+ if (!__privateGet(this, _transport2)) {
3462
+ throw new Error("Transport not initialized, establish connection first");
3463
+ }
3464
+ return __privateGet(this, _transport2);
3465
+ };
3466
+ _sdkInfo = new WeakMap();
3284
3467
  setupAnalytics_fn = function() {
3285
3468
  return __async(this, null, function* () {
3286
3469
  yield setupAnalyticsGlobals(this.options, this.storage, (anonId) => {
@@ -3306,7 +3489,7 @@ onTransportNotification_fn = function(payload) {
3306
3489
  };
3307
3490
  getStoredTransport_fn = function() {
3308
3491
  return __async(this, null, function* () {
3309
- const transportType = yield this.storage.getTransport();
3492
+ const transportType = yield this.storage.getTransportType();
3310
3493
  const hasExtensionInstalled = yield hasExtension();
3311
3494
  if (transportType) {
3312
3495
  if (transportType === "browser" /* Browser */) {
@@ -3334,7 +3517,7 @@ getStoredTransport_fn = function() {
3334
3517
  ));
3335
3518
  return apiTransport;
3336
3519
  }
3337
- yield this.storage.removeTransport();
3520
+ yield this.storage.removeTransportType();
3338
3521
  }
3339
3522
  return void 0;
3340
3523
  });
@@ -3344,15 +3527,15 @@ setupTransport_fn = function() {
3344
3527
  var _a3;
3345
3528
  const transport = yield __privateMethod(this, _MetaMaskConnectMultichain_instances, getStoredTransport_fn).call(this);
3346
3529
  if (transport) {
3347
- if (!this.transport.isConnected()) {
3530
+ if (!transport.isConnected()) {
3348
3531
  this.status = "connecting";
3349
- yield this.transport.connect();
3532
+ yield transport.connect();
3350
3533
  }
3351
3534
  this.status = "connected";
3352
3535
  if (__privateGet(this, _transportType) === "mwp" /* MWP */) {
3353
- yield this.storage.setTransport("mwp" /* MWP */);
3536
+ yield this.storage.setTransportType("mwp" /* MWP */);
3354
3537
  } else {
3355
- yield this.storage.setTransport("browser" /* Browser */);
3538
+ yield this.storage.setTransportType("browser" /* Browser */);
3356
3539
  }
3357
3540
  } else {
3358
3541
  this.status = "loaded";
@@ -3361,7 +3544,7 @@ setupTransport_fn = function() {
3361
3544
  if (hasExtensionInstalled && preferExtension) {
3362
3545
  yield __privateMethod(this, _MetaMaskConnectMultichain_instances, setupDefaultTransport_fn).call(this, { persist: false });
3363
3546
  try {
3364
- yield this.transport.init();
3547
+ yield __privateMethod(this, _MetaMaskConnectMultichain_instances, transportOrThrow_fn).call(this).init();
3365
3548
  } catch (error) {
3366
3549
  console.error("Passive init failed:", error);
3367
3550
  }
@@ -3385,7 +3568,7 @@ init_fn2 = function() {
3385
3568
  yield __privateMethod(this, _MetaMaskConnectMultichain_instances, setupAnalytics_fn).call(this);
3386
3569
  yield __privateMethod(this, _MetaMaskConnectMultichain_instances, setupTransport_fn).call(this);
3387
3570
  } catch (error) {
3388
- yield this.storage.removeTransport();
3571
+ yield this.storage.removeTransportType();
3389
3572
  this.status = "pending";
3390
3573
  logger2("MetaMaskSDK error during initialization", error);
3391
3574
  }
@@ -3431,17 +3614,17 @@ setupMWP_fn = function() {
3431
3614
  __privateSet(this, _transport2, apiTransport);
3432
3615
  __privateSet(this, _transportType, "mwp" /* MWP */);
3433
3616
  __privateGet(this, _providerTransportWrapper).setupTransportNotificationListener();
3434
- __privateSet(this, _listener, this.transport.onNotification(
3617
+ __privateSet(this, _listener, apiTransport.onNotification(
3435
3618
  __privateMethod(this, _MetaMaskConnectMultichain_instances, onTransportNotification_fn).bind(this)
3436
3619
  ));
3437
- yield this.storage.setTransport("mwp" /* MWP */);
3620
+ yield this.storage.setTransportType("mwp" /* MWP */);
3438
3621
  });
3439
3622
  };
3440
3623
  onBeforeUnload_fn = function() {
3441
3624
  return __async(this, null, function* () {
3442
3625
  var _a3;
3443
3626
  if ((_a3 = this.options.ui.factory.modal) == null ? void 0 : _a3.isMounted) {
3444
- yield this.storage.removeTransport();
3627
+ yield this.storage.removeTransportType();
3445
3628
  }
3446
3629
  });
3447
3630
  };
@@ -3458,70 +3641,65 @@ createBeforeUnloadListener_fn = function() {
3458
3641
  };
3459
3642
  renderInstallModalAsync_fn = function(desktopPreferred, scopes, caipAccountIds, sessionProperties) {
3460
3643
  return __async(this, null, function* () {
3461
- return new Promise((resolve, reject) => {
3462
- this.options.ui.factory.renderInstallModal(
3463
- desktopPreferred,
3464
- () => __async(this, null, function* () {
3465
- if (this.dappClient.state === "CONNECTED" || this.dappClient.state === "CONNECTING") {
3466
- yield this.dappClient.disconnect();
3467
- }
3468
- return new Promise((_resolve) => {
3469
- this.dappClient.on(
3470
- "session_request",
3471
- (sessionRequest) => {
3472
- _resolve({
3473
- sessionRequest,
3474
- metadata: __privateMethod(this, _MetaMaskConnectMultichain_instances, buildConnectionMetadata_fn).call(this)
3475
- });
3476
- }
3477
- );
3478
- (() => __async(this, null, function* () {
3479
- var _a3;
3480
- try {
3481
- yield this.transport.connect({
3482
- scopes,
3483
- caipAccountIds,
3484
- sessionProperties
3485
- });
3486
- yield this.options.ui.factory.unload();
3487
- (_a3 = this.options.ui.factory.modal) == null ? void 0 : _a3.unmount();
3488
- this.status = "connected";
3489
- yield this.storage.setTransport("mwp" /* MWP */);
3490
- } catch (error) {
3491
- const { ProtocolError, ErrorCode } = yield import("@metamask/mobile-wallet-protocol-core");
3492
- if (error instanceof ProtocolError) {
3493
- if (error.code !== ErrorCode.REQUEST_EXPIRED) {
3494
- this.status = "disconnected";
3495
- yield this.options.ui.factory.unload(error);
3496
- reject(error);
3497
- }
3498
- } else {
3499
- this.status = "disconnected";
3500
- const normalizedError = error instanceof Error ? error : new Error(String(error));
3501
- yield this.options.ui.factory.unload(normalizedError);
3502
- reject(normalizedError);
3503
- }
3504
- }
3505
- }))().catch(() => {
3506
- });
3644
+ const completion = (0, import_utils10.createDeferredPromise)();
3645
+ const createConnectionRequest = () => __async(this, null, function* () {
3646
+ if (this.dappClient.state === "CONNECTED" || this.dappClient.state === "CONNECTING") {
3647
+ yield this.dappClient.disconnect();
3648
+ }
3649
+ const sessionRequestDeferred = (0, import_utils10.createDeferredPromise)();
3650
+ this.dappClient.on(
3651
+ "session_request",
3652
+ (sessionRequest) => {
3653
+ sessionRequestDeferred.resolve({
3654
+ sessionRequest,
3655
+ metadata: __privateMethod(this, _MetaMaskConnectMultichain_instances, buildConnectionMetadata_fn).call(this)
3507
3656
  });
3508
- }),
3509
- (error) => __async(this, null, function* () {
3510
- if (error) {
3511
- yield this.storage.removeTransport();
3512
- reject(error);
3513
- } else {
3514
- yield this.storage.setTransport("mwp" /* MWP */);
3515
- resolve();
3657
+ }
3658
+ );
3659
+ __privateMethod(this, _MetaMaskConnectMultichain_instances, transportOrThrow_fn).call(this).connect({ scopes, caipAccountIds, sessionProperties }).then(() => __async(this, null, function* () {
3660
+ var _a3;
3661
+ yield this.options.ui.factory.unload();
3662
+ (_a3 = this.options.ui.factory.modal) == null ? void 0 : _a3.unmount();
3663
+ this.status = "connected";
3664
+ yield this.storage.setTransportType("mwp" /* MWP */);
3665
+ })).catch((error) => __async(this, null, function* () {
3666
+ const { ProtocolError, ErrorCode } = yield import("@metamask/mobile-wallet-protocol-core");
3667
+ if (error instanceof ProtocolError) {
3668
+ if (error.code !== ErrorCode.REQUEST_EXPIRED) {
3669
+ this.status = "disconnected";
3670
+ yield this.options.ui.factory.unload(error);
3671
+ completion.reject(error);
3516
3672
  }
3517
- }),
3518
- (uri) => {
3519
- this.emit("display_uri", uri);
3673
+ } else {
3674
+ this.status = "disconnected";
3675
+ const normalizedError = error instanceof Error ? error : new Error(String(error));
3676
+ yield this.options.ui.factory.unload(normalizedError);
3677
+ completion.reject(normalizedError);
3520
3678
  }
3521
- ).catch((error) => {
3522
- reject(error instanceof Error ? error : new Error(String(error)));
3523
- });
3679
+ }));
3680
+ return sessionRequestDeferred.promise;
3524
3681
  });
3682
+ this.options.ui.factory.renderInstallModal(
3683
+ desktopPreferred,
3684
+ createConnectionRequest,
3685
+ (error) => __async(this, null, function* () {
3686
+ if (error) {
3687
+ yield this.storage.removeTransportType();
3688
+ completion.reject(error);
3689
+ } else {
3690
+ yield this.storage.setTransportType("mwp" /* MWP */);
3691
+ completion.resolve();
3692
+ }
3693
+ }),
3694
+ (uri) => {
3695
+ this.emit("display_uri", uri);
3696
+ }
3697
+ ).catch((error) => {
3698
+ completion.reject(
3699
+ error instanceof Error ? error : new Error(String(error))
3700
+ );
3701
+ });
3702
+ return completion.promise;
3525
3703
  });
3526
3704
  };
3527
3705
  showInstallModal_fn = function(desktopPreferred, scopes, caipAccountIds, sessionProperties) {
@@ -3537,39 +3715,37 @@ showInstallModal_fn = function(desktopPreferred, scopes, caipAccountIds, session
3537
3715
  };
3538
3716
  headlessConnect_fn = function(scopes, caipAccountIds, sessionProperties) {
3539
3717
  return __async(this, null, function* () {
3540
- return new Promise((resolve, reject) => {
3541
- if (this.dappClient.state === "CONNECTED" || this.dappClient.state === "CONNECTING") {
3542
- this.dappClient.disconnect().catch(() => {
3543
- });
3718
+ if (this.dappClient.state === "CONNECTED" || this.dappClient.state === "CONNECTING") {
3719
+ yield this.dappClient.disconnect().catch(() => void 0);
3720
+ }
3721
+ const onSessionRequest = (sessionRequest) => {
3722
+ const connectionRequest = {
3723
+ sessionRequest,
3724
+ metadata: __privateMethod(this, _MetaMaskConnectMultichain_instances, buildConnectionMetadata_fn).call(this)
3725
+ };
3726
+ const deeplink = this.options.ui.factory.createConnectionDeeplink(connectionRequest);
3727
+ this.emit("display_uri", deeplink);
3728
+ };
3729
+ this.dappClient.on("session_request", onSessionRequest);
3730
+ try {
3731
+ yield __privateMethod(this, _MetaMaskConnectMultichain_instances, transportOrThrow_fn).call(this).connect({
3732
+ scopes,
3733
+ caipAccountIds,
3734
+ sessionProperties
3735
+ });
3736
+ this.status = "connected";
3737
+ yield this.storage.setTransportType("mwp" /* MWP */);
3738
+ } catch (error) {
3739
+ const { ProtocolError } = yield import("@metamask/mobile-wallet-protocol-core");
3740
+ this.status = "disconnected";
3741
+ yield this.storage.removeTransportType();
3742
+ if (error instanceof ProtocolError || error instanceof Error) {
3743
+ throw error;
3544
3744
  }
3545
- this.dappClient.on(
3546
- "session_request",
3547
- (sessionRequest) => {
3548
- const connectionRequest = {
3549
- sessionRequest,
3550
- metadata: __privateMethod(this, _MetaMaskConnectMultichain_instances, buildConnectionMetadata_fn).call(this)
3551
- };
3552
- const deeplink = this.options.ui.factory.createConnectionDeeplink(connectionRequest);
3553
- this.emit("display_uri", deeplink);
3554
- }
3555
- );
3556
- this.transport.connect({ scopes, caipAccountIds, sessionProperties }).then(() => __async(this, null, function* () {
3557
- this.status = "connected";
3558
- yield this.storage.setTransport("mwp" /* MWP */);
3559
- resolve();
3560
- })).catch((error) => __async(this, null, function* () {
3561
- const { ProtocolError } = yield import("@metamask/mobile-wallet-protocol-core");
3562
- if (error instanceof ProtocolError) {
3563
- this.status = "disconnected";
3564
- yield this.storage.removeTransport();
3565
- reject(error);
3566
- } else {
3567
- this.status = "disconnected";
3568
- yield this.storage.removeTransport();
3569
- reject(error instanceof Error ? error : new Error(String(error)));
3570
- }
3571
- }));
3572
- });
3745
+ throw new Error(String(error));
3746
+ } finally {
3747
+ this.dappClient.off("session_request", onSessionRequest);
3748
+ }
3573
3749
  });
3574
3750
  };
3575
3751
  setupDefaultTransport_fn = function() {
@@ -3578,7 +3754,7 @@ setupDefaultTransport_fn = function() {
3578
3754
  return __privateGet(this, _transport2);
3579
3755
  }
3580
3756
  if (options == null ? void 0 : options.persist) {
3581
- yield this.storage.setTransport("browser" /* Browser */);
3757
+ yield this.storage.setTransportType("browser" /* Browser */);
3582
3758
  }
3583
3759
  const transport = new DefaultTransport();
3584
3760
  __privateSet(this, _listener, transport.onNotification(
@@ -3611,7 +3787,7 @@ deeplinkConnect_fn = function(scopes, caipAccountIds, sessionProperties) {
3611
3787
  };
3612
3788
  this.dappClient.on("message", dappClientMessageHandler);
3613
3789
  let timeout;
3614
- if (this.transport.isConnected()) {
3790
+ if (__privateMethod(this, _MetaMaskConnectMultichain_instances, transportOrThrow_fn).call(this).isConnected()) {
3615
3791
  timeout = setTimeout(() => {
3616
3792
  this.openSimpleDeeplinkIfNeeded();
3617
3793
  }, 250);
@@ -3639,8 +3815,8 @@ deeplinkConnect_fn = function(scopes, caipAccountIds, sessionProperties) {
3639
3815
  }
3640
3816
  );
3641
3817
  }
3642
- return this.transport.connect({ scopes, caipAccountIds, sessionProperties }).then(resolve).catch((error) => __async(this, null, function* () {
3643
- yield this.storage.removeTransport();
3818
+ return __privateMethod(this, _MetaMaskConnectMultichain_instances, transportOrThrow_fn).call(this).connect({ scopes, caipAccountIds, sessionProperties }).then(resolve).catch((error) => __async(this, null, function* () {
3819
+ yield this.storage.removeTransportType();
3644
3820
  this.dappClient.off("message", dappClientMessageHandler);
3645
3821
  reject(error instanceof Error ? error : new Error(String(error)));
3646
3822
  })).finally(() => {
@@ -3706,7 +3882,7 @@ getCaipSession_fn = function() {
3706
3882
  };
3707
3883
  if ((_a3 = __privateGet(this, _transport2)) == null ? void 0 : _a3.isConnected()) {
3708
3884
  try {
3709
- const response = yield this.transport.request({
3885
+ const response = yield __privateGet(this, _transport2).request({
3710
3886
  method: "wallet_getSession"
3711
3887
  });
3712
3888
  if (response.result) {
@@ -3800,14 +3976,14 @@ var Store = class extends StoreClient {
3800
3976
  super();
3801
3977
  this.adapter = adapter;
3802
3978
  }
3803
- getTransport() {
3979
+ getTransportType() {
3804
3980
  return __async(this, null, function* () {
3805
3981
  try {
3806
- const transport = yield this.adapter.get("multichain-transport");
3807
- if (!transport) {
3982
+ const transportType = yield this.adapter.get("multichain-transport");
3983
+ if (!transportType) {
3808
3984
  return null;
3809
3985
  }
3810
- return getTransportType(transport);
3986
+ return getTransportType(transportType);
3811
3987
  } catch (err) {
3812
3988
  throw new StorageGetErr(
3813
3989
  this.adapter.platform,
@@ -3817,10 +3993,10 @@ var Store = class extends StoreClient {
3817
3993
  }
3818
3994
  });
3819
3995
  }
3820
- setTransport(transport) {
3996
+ setTransportType(transportType) {
3821
3997
  return __async(this, null, function* () {
3822
3998
  try {
3823
- yield this.adapter.set("multichain-transport", transport);
3999
+ yield this.adapter.set("multichain-transport", transportType);
3824
4000
  } catch (err) {
3825
4001
  throw new StorageSetErr(
3826
4002
  this.adapter.platform,
@@ -3830,7 +4006,7 @@ var Store = class extends StoreClient {
3830
4006
  }
3831
4007
  });
3832
4008
  }
3833
- removeTransport() {
4009
+ removeTransportType() {
3834
4010
  return __async(this, null, function* () {
3835
4011
  try {
3836
4012
  yield this.adapter.delete("multichain-transport");
@@ -4044,7 +4220,11 @@ var BaseModalFactory = class {
4044
4220
  (_a4 = this.displayUriCallback) == null ? void 0 : _a4.call(this, newLink);
4045
4221
  return newLink;
4046
4222
  }),
4047
- onClose: this.onCloseModal.bind(this),
4223
+ onClose: (shouldTerminate) => {
4224
+ this.onCloseModal(shouldTerminate).catch((error) => {
4225
+ console.error("Failed to close modal:", error);
4226
+ });
4227
+ },
4048
4228
  startDesktopOnboarding: this.onStartDesktopOnboarding.bind(this),
4049
4229
  createConnectionRequest,
4050
4230
  onDisplayUri: this.displayUriCallback
@@ -4082,7 +4262,7 @@ function preload() {
4082
4262
  }
4083
4263
  try {
4084
4264
  const { defineCustomElements } = yield import("@metamask/multichain-ui/loader");
4085
- yield defineCustomElements();
4265
+ defineCustomElements();
4086
4266
  } catch (error) {
4087
4267
  console.error("Failed to load customElements:", error);
4088
4268
  }