@metamask/connect-multichain 0.12.1 → 0.13.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 (37) hide show
  1. package/CHANGELOG.md +13 -1
  2. package/dist/browser/es/connect-multichain.mjs +752 -710
  3. package/dist/browser/es/connect-multichain.mjs.map +1 -1
  4. package/dist/browser/es/metafile-esm.json +1 -1
  5. package/dist/browser/iife/connect-multichain.js +5599 -4858
  6. package/dist/browser/iife/connect-multichain.js.map +1 -1
  7. package/dist/browser/iife/metafile-iife.json +1 -1
  8. package/dist/browser/umd/connect-multichain.js +752 -705
  9. package/dist/browser/umd/connect-multichain.js.map +1 -1
  10. package/dist/browser/umd/metafile-cjs.json +1 -1
  11. package/dist/node/cjs/connect-multichain.js +752 -705
  12. package/dist/node/cjs/connect-multichain.js.map +1 -1
  13. package/dist/node/cjs/metafile-cjs.json +1 -1
  14. package/dist/node/es/connect-multichain.mjs +751 -709
  15. package/dist/node/es/connect-multichain.mjs.map +1 -1
  16. package/dist/node/es/metafile-esm.json +1 -1
  17. package/dist/react-native/es/connect-multichain.mjs +751 -709
  18. package/dist/react-native/es/connect-multichain.mjs.map +1 -1
  19. package/dist/react-native/es/metafile-esm.json +1 -1
  20. package/dist/src/domain/multichain/index.d.ts +1 -1
  21. package/dist/src/domain/multichain/index.d.ts.map +1 -1
  22. package/dist/src/multichain/index.d.ts +2 -2
  23. package/dist/src/multichain/index.d.ts.map +1 -1
  24. package/dist/src/multichain/index.js +37 -23
  25. package/dist/src/multichain/index.js.map +1 -1
  26. package/dist/src/multichain/transports/multichainApiClientWrapper/index.d.ts +1 -0
  27. package/dist/src/multichain/transports/multichainApiClientWrapper/index.d.ts.map +1 -1
  28. package/dist/src/multichain/transports/multichainApiClientWrapper/index.js +10 -10
  29. package/dist/src/multichain/transports/multichainApiClientWrapper/index.js.map +1 -1
  30. package/dist/src/multichain/transports/mwp/KeyManager.d.ts +12 -9
  31. package/dist/src/multichain/transports/mwp/KeyManager.d.ts.map +1 -1
  32. package/dist/src/multichain/transports/mwp/KeyManager.js +38 -25
  33. package/dist/src/multichain/transports/mwp/KeyManager.js.map +1 -1
  34. package/dist/src/multichain/transports/mwp/index.d.ts.map +1 -1
  35. package/dist/src/multichain/transports/mwp/index.js +1 -1
  36. package/dist/src/multichain/transports/mwp/index.js.map +1 -1
  37. package/package.json +1 -1
@@ -1042,6 +1042,706 @@ var init_domain = __esm({
1042
1042
  }
1043
1043
  });
1044
1044
 
1045
+ // src/multichain/transports/constants.ts
1046
+ var MULTICHAIN_PROVIDER_STREAM_NAME;
1047
+ var init_constants2 = __esm({
1048
+ "src/multichain/transports/constants.ts"() {
1049
+ "use strict";
1050
+ MULTICHAIN_PROVIDER_STREAM_NAME = "metamask-multichain-provider";
1051
+ }
1052
+ });
1053
+
1054
+ // src/multichain/transports/mwp/index.ts
1055
+ var mwp_exports = {};
1056
+ __export(mwp_exports, {
1057
+ MWPTransport: () => MWPTransport
1058
+ });
1059
+ 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;
1060
+ var init_mwp = __esm({
1061
+ "src/multichain/transports/mwp/index.ts"() {
1062
+ "use strict";
1063
+ import_multichain_api_client2 = require("@metamask/multichain-api-client");
1064
+ import_rpc_errors2 = require("@metamask/rpc-errors");
1065
+ init_domain();
1066
+ init_utils();
1067
+ init_constants2();
1068
+ DEFAULT_REQUEST_TIMEOUT2 = 60 * 1e3;
1069
+ CONNECTION_GRACE_PERIOD = 60 * 1e3;
1070
+ DEFAULT_CONNECTION_TIMEOUT = DEFAULT_REQUEST_TIMEOUT2 + CONNECTION_GRACE_PERIOD;
1071
+ DEFAULT_RESUME_TIMEOUT = 10 * 1e3;
1072
+ SESSION_STORE_KEY = "cache_wallet_getSession";
1073
+ ACCOUNTS_STORE_KEY = "cache_eth_accounts";
1074
+ CHAIN_STORE_KEY = "cache_eth_chainId";
1075
+ PENDING_SESSION_REQUEST_KEY = "pending_session_request";
1076
+ CACHED_METHOD_LIST = [
1077
+ "wallet_getSession",
1078
+ "wallet_createSession",
1079
+ "wallet_sessionChanged"
1080
+ ];
1081
+ CACHED_RESET_METHOD_LIST = [
1082
+ "wallet_revokeSession",
1083
+ "wallet_revokePermissions"
1084
+ ];
1085
+ logger = createLogger("metamask-sdk:transport");
1086
+ MWPTransport = class {
1087
+ constructor(dappClient, kvstore, options = {
1088
+ requestTimeout: DEFAULT_REQUEST_TIMEOUT2,
1089
+ connectionTimeout: DEFAULT_CONNECTION_TIMEOUT,
1090
+ resumeTimeout: DEFAULT_RESUME_TIMEOUT
1091
+ }) {
1092
+ this.dappClient = dappClient;
1093
+ this.kvstore = kvstore;
1094
+ this.options = options;
1095
+ this.__pendingRequests = /* @__PURE__ */ new Map();
1096
+ this.notificationCallbacks = /* @__PURE__ */ new Set();
1097
+ this.dappClient.on("message", this.handleMessage.bind(this));
1098
+ this.dappClient.on("session_request", (sessionRequest) => {
1099
+ this.currentSessionRequest = sessionRequest;
1100
+ this.kvstore.set(PENDING_SESSION_REQUEST_KEY, JSON.stringify(sessionRequest)).catch((err) => {
1101
+ logger("Failed to store pending session request", err);
1102
+ });
1103
+ });
1104
+ if (typeof window !== "undefined" && typeof window.addEventListener !== "undefined") {
1105
+ this.windowFocusHandler = this.onWindowFocus.bind(this);
1106
+ window.addEventListener("focus", this.windowFocusHandler);
1107
+ }
1108
+ }
1109
+ get pendingRequests() {
1110
+ return this.__pendingRequests;
1111
+ }
1112
+ set pendingRequests(pendingRequests) {
1113
+ this.__pendingRequests = pendingRequests;
1114
+ }
1115
+ get sessionRequest() {
1116
+ return this.currentSessionRequest;
1117
+ }
1118
+ /**
1119
+ * Returns the stored pending session request from the dappClient session_request event, if any.
1120
+ *
1121
+ * @returns The stored SessionRequest, or null if none or invalid.
1122
+ */
1123
+ getStoredPendingSessionRequest() {
1124
+ return __async(this, null, function* () {
1125
+ try {
1126
+ const raw = yield this.kvstore.get(PENDING_SESSION_REQUEST_KEY);
1127
+ if (!raw) {
1128
+ return null;
1129
+ }
1130
+ return JSON.parse(raw);
1131
+ } catch (e) {
1132
+ return null;
1133
+ }
1134
+ });
1135
+ }
1136
+ /**
1137
+ * Removes the stored pending session request from the KVStore.
1138
+ * This is necessary to ensure that ConnectMultichain is able to correctly
1139
+ * infer the MWP Transport connection attempt status.
1140
+ */
1141
+ removeStoredPendingSessionRequest() {
1142
+ return __async(this, null, function* () {
1143
+ yield this.kvstore.delete(PENDING_SESSION_REQUEST_KEY);
1144
+ });
1145
+ }
1146
+ onWindowFocus() {
1147
+ if (!this.isConnected()) {
1148
+ this.dappClient.reconnect();
1149
+ }
1150
+ }
1151
+ notifyCallbacks(data) {
1152
+ this.notificationCallbacks.forEach((callback) => callback(data));
1153
+ }
1154
+ rejectRequest(id, error = new Error("Request rejected")) {
1155
+ const request = this.pendingRequests.get(id);
1156
+ if (request) {
1157
+ this.pendingRequests.delete(id);
1158
+ clearTimeout(request.timeout);
1159
+ request.reject(error);
1160
+ }
1161
+ }
1162
+ parseWalletError(errorPayload) {
1163
+ const errorData = errorPayload;
1164
+ if (typeof errorData.code === "number" && typeof errorData.message === "string") {
1165
+ const { code, message: message2 } = errorData;
1166
+ if (code >= 1e3 && code <= 4999) {
1167
+ return import_rpc_errors2.providerErrors.custom({ code, message: message2 });
1168
+ }
1169
+ return new import_rpc_errors2.JsonRpcError(code, message2);
1170
+ }
1171
+ const message = errorPayload instanceof Error ? errorPayload.message : JSON.stringify(errorPayload);
1172
+ return import_rpc_errors2.rpcErrors.internal({ message });
1173
+ }
1174
+ handleMessage(message) {
1175
+ if (typeof message === "object" && message !== null) {
1176
+ if ("data" in message) {
1177
+ const messagePayload = message.data;
1178
+ if ("id" in messagePayload && typeof messagePayload.id === "string") {
1179
+ const request = this.pendingRequests.get(messagePayload.id);
1180
+ if (request) {
1181
+ clearTimeout(request.timeout);
1182
+ if ("error" in messagePayload && messagePayload.error) {
1183
+ this.pendingRequests.delete(messagePayload.id);
1184
+ request.reject(this.parseWalletError(messagePayload.error));
1185
+ return;
1186
+ }
1187
+ const requestWithName = __spreadProps(__spreadValues({}, messagePayload), {
1188
+ method: request.method === "wallet_getSession" || request.method === "wallet_createSession" ? "wallet_sessionChanged" : request.method
1189
+ });
1190
+ const notification = __spreadProps(__spreadValues({}, messagePayload), {
1191
+ method: request.method === "wallet_getSession" || request.method === "wallet_createSession" ? "wallet_sessionChanged" : request.method,
1192
+ params: requestWithName.result
1193
+ });
1194
+ this.notifyCallbacks(notification);
1195
+ request.resolve(requestWithName);
1196
+ this.pendingRequests.delete(messagePayload.id);
1197
+ }
1198
+ } else {
1199
+ if (message.data.method === "metamask_chainChanged") {
1200
+ this.kvstore.set(
1201
+ CHAIN_STORE_KEY,
1202
+ JSON.stringify(
1203
+ message.data.params.chainId
1204
+ )
1205
+ );
1206
+ }
1207
+ if (message.data.method === "metamask_accountsChanged") {
1208
+ this.kvstore.set(
1209
+ ACCOUNTS_STORE_KEY,
1210
+ JSON.stringify(
1211
+ message.data.params
1212
+ )
1213
+ );
1214
+ }
1215
+ if (message.data.method === "wallet_sessionChanged") {
1216
+ const notification = message.data;
1217
+ const response = {
1218
+ result: notification.params
1219
+ };
1220
+ this.kvstore.set(SESSION_STORE_KEY, JSON.stringify(response));
1221
+ }
1222
+ this.notifyCallbacks(message.data);
1223
+ }
1224
+ }
1225
+ }
1226
+ }
1227
+ onResumeSuccess(resumeResolve, resumeReject, options) {
1228
+ return __async(this, null, function* () {
1229
+ var _a2, _b, _c, _d, _e, _f, _g;
1230
+ try {
1231
+ yield this.waitForWalletSessionIfNotCached();
1232
+ const sessionRequest = yield this.request({
1233
+ method: "wallet_getSession"
1234
+ });
1235
+ if (sessionRequest.error) {
1236
+ return resumeReject(new Error(sessionRequest.error.message));
1237
+ }
1238
+ let walletSession = sessionRequest.result;
1239
+ if (walletSession && options) {
1240
+ const currentScopes = Object.keys(
1241
+ (_a2 = walletSession == null ? void 0 : walletSession.sessionScopes) != null ? _a2 : {}
1242
+ );
1243
+ const proposedScopes = (_b = options == null ? void 0 : options.scopes) != null ? _b : [];
1244
+ const proposedCaipAccountIds = (_c = options == null ? void 0 : options.caipAccountIds) != null ? _c : [];
1245
+ const hasSameScopesAndAccounts = isSameScopesAndAccounts(
1246
+ currentScopes,
1247
+ proposedScopes,
1248
+ walletSession,
1249
+ proposedCaipAccountIds
1250
+ );
1251
+ if (options.forceRequest || !hasSameScopesAndAccounts) {
1252
+ const optionalScopes = addValidAccounts(
1253
+ getOptionalScopes((_d = options == null ? void 0 : options.scopes) != null ? _d : []),
1254
+ getValidAccounts((_e = options == null ? void 0 : options.caipAccountIds) != null ? _e : [])
1255
+ );
1256
+ const sessionRequest2 = {
1257
+ optionalScopes
1258
+ };
1259
+ const response = yield this.request({
1260
+ method: "wallet_createSession",
1261
+ params: sessionRequest2
1262
+ });
1263
+ if (response.error) {
1264
+ return resumeReject(new Error(response.error.message));
1265
+ }
1266
+ walletSession = response.result;
1267
+ }
1268
+ } else if (!walletSession) {
1269
+ const optionalScopes = addValidAccounts(
1270
+ getOptionalScopes((_f = options == null ? void 0 : options.scopes) != null ? _f : []),
1271
+ getValidAccounts((_g = options == null ? void 0 : options.caipAccountIds) != null ? _g : [])
1272
+ );
1273
+ const sessionRequest2 = { optionalScopes };
1274
+ const response = yield this.request({
1275
+ method: "wallet_createSession",
1276
+ params: sessionRequest2
1277
+ });
1278
+ if (response.error) {
1279
+ return resumeReject(new Error(response.error.message));
1280
+ }
1281
+ walletSession = response.result;
1282
+ }
1283
+ yield this.removeStoredPendingSessionRequest();
1284
+ this.notifyCallbacks({
1285
+ method: "wallet_sessionChanged",
1286
+ params: walletSession
1287
+ });
1288
+ return resumeResolve();
1289
+ } catch (err) {
1290
+ return resumeReject(err);
1291
+ }
1292
+ });
1293
+ }
1294
+ init() {
1295
+ return __async(this, null, function* () {
1296
+ });
1297
+ }
1298
+ // TODO: Rename this
1299
+ sendEip1193Message(payload, options) {
1300
+ return __async(this, null, function* () {
1301
+ const request = __spreadValues({
1302
+ jsonrpc: "2.0",
1303
+ id: String(getUniqueRequestId())
1304
+ }, payload);
1305
+ const cachedWalletSession = yield this.getCachedResponse(request);
1306
+ if (cachedWalletSession) {
1307
+ this.notifyCallbacks(cachedWalletSession);
1308
+ return cachedWalletSession;
1309
+ }
1310
+ return new Promise((resolve, reject) => {
1311
+ var _a2;
1312
+ const timeout = setTimeout(() => {
1313
+ this.rejectRequest(request.id, new import_multichain_api_client2.TransportTimeoutError());
1314
+ }, (_a2 = options == null ? void 0 : options.timeout) != null ? _a2 : this.options.requestTimeout);
1315
+ this.pendingRequests.set(request.id, {
1316
+ request,
1317
+ method: request.method,
1318
+ resolve: (response) => __async(this, null, function* () {
1319
+ yield this.storeWalletSession(request, response);
1320
+ return resolve(response);
1321
+ }),
1322
+ reject,
1323
+ timeout
1324
+ });
1325
+ this.dappClient.sendRequest({
1326
+ name: "metamask-provider",
1327
+ data: request
1328
+ }).catch(reject);
1329
+ });
1330
+ });
1331
+ }
1332
+ connect(options) {
1333
+ return __async(this, null, function* () {
1334
+ const { dappClient } = this;
1335
+ const session = yield this.getActiveSession();
1336
+ if (session) {
1337
+ logger("active session found", {
1338
+ id: session.id,
1339
+ channel: session.channel,
1340
+ expiresAt: session.expiresAt
1341
+ });
1342
+ }
1343
+ const storedSessionRequestBeforeConnectionAttempt = yield this.getStoredPendingSessionRequest();
1344
+ let timeout;
1345
+ let initialConnectionMessageHandler;
1346
+ const connectionPromise = new Promise((resolve, reject) => __async(this, null, function* () {
1347
+ let connection;
1348
+ if (session) {
1349
+ connection = new Promise((resumeResolve, resumeReject) => {
1350
+ var _a2;
1351
+ if (this.dappClient.state === "CONNECTED") {
1352
+ this.onResumeSuccess(resumeResolve, resumeReject, options);
1353
+ } else {
1354
+ this.dappClient.once("connected", () => __async(this, null, function* () {
1355
+ this.onResumeSuccess(resumeResolve, resumeReject, options);
1356
+ }));
1357
+ dappClient.resume((_a2 = session == null ? void 0 : session.id) != null ? _a2 : "");
1358
+ }
1359
+ });
1360
+ } else {
1361
+ connection = new Promise(
1362
+ (resolveConnection, rejectConnection) => {
1363
+ var _a2, _b;
1364
+ const optionalScopes = addValidAccounts(
1365
+ getOptionalScopes((_a2 = options == null ? void 0 : options.scopes) != null ? _a2 : []),
1366
+ getValidAccounts((_b = options == null ? void 0 : options.caipAccountIds) != null ? _b : [])
1367
+ );
1368
+ const sessionRequest = {
1369
+ optionalScopes,
1370
+ sessionProperties: options == null ? void 0 : options.sessionProperties
1371
+ };
1372
+ const request = {
1373
+ jsonrpc: "2.0",
1374
+ id: String(getUniqueRequestId()),
1375
+ method: "wallet_createSession",
1376
+ params: sessionRequest
1377
+ };
1378
+ initialConnectionMessageHandler = (message) => __async(this, null, function* () {
1379
+ if (typeof message !== "object" || message === null) {
1380
+ return;
1381
+ }
1382
+ if (!("data" in message)) {
1383
+ return;
1384
+ }
1385
+ const messagePayload = message.data;
1386
+ const isMatchingId = messagePayload.id === request.id;
1387
+ const isMatchingMethod = messagePayload.method === "wallet_createSession" || messagePayload.method === "wallet_sessionChanged";
1388
+ if (!isMatchingId && !isMatchingMethod) {
1389
+ return;
1390
+ }
1391
+ if (messagePayload.error) {
1392
+ return rejectConnection(
1393
+ this.parseWalletError(messagePayload.error)
1394
+ );
1395
+ }
1396
+ yield this.storeWalletSession(
1397
+ request,
1398
+ messagePayload
1399
+ );
1400
+ yield this.removeStoredPendingSessionRequest();
1401
+ this.notifyCallbacks(messagePayload);
1402
+ return resolveConnection();
1403
+ });
1404
+ this.dappClient.on("message", initialConnectionMessageHandler);
1405
+ dappClient.connect({
1406
+ mode: "trusted",
1407
+ initialPayload: {
1408
+ name: MULTICHAIN_PROVIDER_STREAM_NAME,
1409
+ data: request
1410
+ }
1411
+ }).catch((error) => {
1412
+ if (initialConnectionMessageHandler) {
1413
+ this.dappClient.off(
1414
+ "message",
1415
+ initialConnectionMessageHandler
1416
+ );
1417
+ }
1418
+ rejectConnection(error);
1419
+ });
1420
+ }
1421
+ );
1422
+ }
1423
+ timeout = setTimeout(
1424
+ () => {
1425
+ reject(new import_multichain_api_client2.TransportTimeoutError());
1426
+ },
1427
+ storedSessionRequestBeforeConnectionAttempt ? this.options.resumeTimeout : this.options.connectionTimeout
1428
+ );
1429
+ connection.then(resolve).catch(reject);
1430
+ }));
1431
+ return connectionPromise.catch((error) => __async(this, null, function* () {
1432
+ yield this.dappClient.disconnect();
1433
+ throw error;
1434
+ })).finally(() => {
1435
+ if (timeout) {
1436
+ clearTimeout(timeout);
1437
+ }
1438
+ if (initialConnectionMessageHandler) {
1439
+ this.dappClient.off("message", initialConnectionMessageHandler);
1440
+ initialConnectionMessageHandler = void 0;
1441
+ }
1442
+ this.removeStoredPendingSessionRequest();
1443
+ });
1444
+ });
1445
+ }
1446
+ /**
1447
+ * Disconnects from the Mobile Wallet Protocol
1448
+ *
1449
+ * @param [scopes] - The scopes to revoke. If not provided or empty, all scopes will be revoked.
1450
+ * @returns Nothing
1451
+ */
1452
+ disconnect() {
1453
+ return __async(this, arguments, function* (scopes = []) {
1454
+ var _a2, _b;
1455
+ const cachedSession = yield this.getCachedResponse({
1456
+ jsonrpc: "2.0",
1457
+ id: "0",
1458
+ method: "wallet_getSession"
1459
+ });
1460
+ const cachedSessionScopes = (_b = (_a2 = cachedSession == null ? void 0 : cachedSession.result) == null ? void 0 : _a2.sessionScopes) != null ? _b : {};
1461
+ const remainingScopes = scopes.length === 0 ? [] : Object.keys(cachedSessionScopes).filter(
1462
+ (scope) => !scopes.includes(scope)
1463
+ );
1464
+ const newSessionScopes = Object.fromEntries(
1465
+ Object.entries(cachedSessionScopes).filter(
1466
+ ([key]) => remainingScopes.includes(key)
1467
+ )
1468
+ );
1469
+ this.request({ method: "wallet_revokeSession", params: { scopes } }).catch(
1470
+ (err) => {
1471
+ console.error("error revoking session", err);
1472
+ }
1473
+ );
1474
+ const remainingScopesIncludeEip155 = remainingScopes.some(
1475
+ (scope) => scope.includes("eip155")
1476
+ );
1477
+ if (!remainingScopesIncludeEip155) {
1478
+ this.kvstore.delete(ACCOUNTS_STORE_KEY);
1479
+ this.kvstore.delete(CHAIN_STORE_KEY);
1480
+ }
1481
+ if (remainingScopes.length > 0) {
1482
+ this.kvstore.set(
1483
+ SESSION_STORE_KEY,
1484
+ JSON.stringify({
1485
+ result: {
1486
+ sessionScopes: newSessionScopes
1487
+ }
1488
+ })
1489
+ );
1490
+ } else {
1491
+ this.kvstore.delete(SESSION_STORE_KEY);
1492
+ if (typeof window !== "undefined" && typeof window.removeEventListener !== "undefined" && this.windowFocusHandler) {
1493
+ window.removeEventListener("focus", this.windowFocusHandler);
1494
+ this.windowFocusHandler = void 0;
1495
+ }
1496
+ yield this.dappClient.disconnect();
1497
+ }
1498
+ this.notifyCallbacks({
1499
+ method: "wallet_sessionChanged",
1500
+ params: {
1501
+ sessionScopes: newSessionScopes
1502
+ }
1503
+ });
1504
+ });
1505
+ }
1506
+ /**
1507
+ * Checks if the transport is connected
1508
+ *
1509
+ * @returns True if transport is connected, false otherwise
1510
+ */
1511
+ isConnected() {
1512
+ return this.dappClient.state === "CONNECTED";
1513
+ }
1514
+ /**
1515
+ * Attempts to re-establish a connection via DappClient
1516
+ *
1517
+ * @returns Nothing
1518
+ */
1519
+ // TODO: We should re-evaluate adding this to the WebSocketTransport layer from `@metamask/mobile-wallet-protocol-core`
1520
+ // ticket: https://consensyssoftware.atlassian.net/browse/WAPI-862
1521
+ attemptResumeSession() {
1522
+ return __async(this, null, function* () {
1523
+ try {
1524
+ yield this.dappClient.reconnect();
1525
+ yield new Promise((resolve, reject) => {
1526
+ const timeout = setTimeout(() => {
1527
+ reject(new Error("Resume timeout"));
1528
+ }, 2e3);
1529
+ if (this.isConnected()) {
1530
+ clearTimeout(timeout);
1531
+ resolve();
1532
+ } else {
1533
+ this.dappClient.once("connected", () => {
1534
+ clearTimeout(timeout);
1535
+ resolve();
1536
+ });
1537
+ }
1538
+ });
1539
+ } catch (error) {
1540
+ return Promise.reject(
1541
+ new Error(`Failed to resume session: ${error.message}`)
1542
+ );
1543
+ }
1544
+ });
1545
+ }
1546
+ getCachedResponse(request) {
1547
+ return __async(this, null, function* () {
1548
+ var _a2;
1549
+ if (request.method === "wallet_getSession") {
1550
+ const walletGetSession = yield this.kvstore.get(SESSION_STORE_KEY);
1551
+ if (walletGetSession) {
1552
+ const walletSession = JSON.parse(walletGetSession);
1553
+ return {
1554
+ id: request.id,
1555
+ jsonrpc: "2.0",
1556
+ result: (_a2 = walletSession.params) != null ? _a2 : walletSession.result,
1557
+ // "what?... why walletSession.params?.."
1558
+ method: request.method
1559
+ };
1560
+ }
1561
+ } else if (request.method === "eth_accounts") {
1562
+ const ethAccounts = yield this.kvstore.get(ACCOUNTS_STORE_KEY);
1563
+ if (ethAccounts) {
1564
+ return {
1565
+ id: request.id,
1566
+ jsonrpc: "2.0",
1567
+ result: JSON.parse(ethAccounts),
1568
+ method: request.method
1569
+ };
1570
+ }
1571
+ } else if (request.method === "eth_chainId") {
1572
+ const ethChainId = yield this.kvstore.get(CHAIN_STORE_KEY);
1573
+ if (ethChainId) {
1574
+ return {
1575
+ id: request.id,
1576
+ jsonrpc: "2.0",
1577
+ result: JSON.parse(ethChainId),
1578
+ method: request.method
1579
+ };
1580
+ }
1581
+ }
1582
+ });
1583
+ }
1584
+ storeWalletSession(request, response) {
1585
+ return __async(this, null, function* () {
1586
+ if (response.error) {
1587
+ return;
1588
+ }
1589
+ if (CACHED_METHOD_LIST.includes(request.method)) {
1590
+ yield this.kvstore.set(SESSION_STORE_KEY, JSON.stringify(response));
1591
+ } else if (request.method === "eth_accounts") {
1592
+ yield this.kvstore.set(
1593
+ ACCOUNTS_STORE_KEY,
1594
+ JSON.stringify(response.result)
1595
+ );
1596
+ } else if (request.method === "eth_chainId") {
1597
+ yield this.kvstore.set(CHAIN_STORE_KEY, JSON.stringify(response.result));
1598
+ } else if (CACHED_RESET_METHOD_LIST.includes(request.method)) {
1599
+ yield this.kvstore.delete(SESSION_STORE_KEY);
1600
+ yield this.kvstore.delete(ACCOUNTS_STORE_KEY);
1601
+ yield this.kvstore.delete(CHAIN_STORE_KEY);
1602
+ }
1603
+ });
1604
+ }
1605
+ request(payload, options) {
1606
+ return __async(this, null, function* () {
1607
+ const request = __spreadValues({
1608
+ jsonrpc: "2.0",
1609
+ id: String(getUniqueRequestId())
1610
+ }, payload);
1611
+ const cachedWalletSession = yield this.getCachedResponse(request);
1612
+ if (cachedWalletSession) {
1613
+ this.notifyCallbacks(cachedWalletSession);
1614
+ return cachedWalletSession;
1615
+ }
1616
+ if (!this.isConnected()) {
1617
+ yield this.attemptResumeSession();
1618
+ }
1619
+ return new Promise((resolve, reject) => {
1620
+ var _a2;
1621
+ const timeout = setTimeout(() => {
1622
+ this.rejectRequest(request.id, new import_multichain_api_client2.TransportTimeoutError());
1623
+ }, (_a2 = options == null ? void 0 : options.timeout) != null ? _a2 : this.options.requestTimeout);
1624
+ this.pendingRequests.set(request.id, {
1625
+ request,
1626
+ method: request.method,
1627
+ resolve: (response) => __async(this, null, function* () {
1628
+ yield this.storeWalletSession(request, response);
1629
+ return resolve(response);
1630
+ }),
1631
+ reject,
1632
+ timeout
1633
+ });
1634
+ this.dappClient.sendRequest({
1635
+ name: MULTICHAIN_PROVIDER_STREAM_NAME,
1636
+ data: request
1637
+ }).catch(reject);
1638
+ });
1639
+ });
1640
+ }
1641
+ onNotification(callback) {
1642
+ this.notificationCallbacks.add(callback);
1643
+ return () => {
1644
+ this.notificationCallbacks.delete(callback);
1645
+ };
1646
+ }
1647
+ getActiveSession() {
1648
+ return __async(this, null, function* () {
1649
+ const { kvstore } = this;
1650
+ const { SessionStore } = yield import("@metamask/mobile-wallet-protocol-core");
1651
+ const sessionStore = yield SessionStore.create(kvstore);
1652
+ try {
1653
+ const [activeSession] = yield sessionStore.list();
1654
+ return activeSession;
1655
+ } catch (error) {
1656
+ logger("error getting active session", error);
1657
+ return void 0;
1658
+ }
1659
+ });
1660
+ }
1661
+ // This method checks if an existing CAIP session response is cached or waits for one
1662
+ // to be received from the wallet if not cached. This is necessary because there is an edge
1663
+ // case during the initial connection flow where after the user has accepted the permission approval
1664
+ // and returned back to the dapp from the wallet, the dapp page may have gotten unloaded and refreshed.
1665
+ // When it is unloaded and refreshed, it will try to resume the session by making a request for wallet_getSession
1666
+ // which should resolve from cache, but because a race condition makes it possible for the response from the wallet
1667
+ // for the initial wallet_createSession connection request to not have been handled and cached yet. This results
1668
+ // in the wallet_getSession request never resolving unless we wait for it explicitly as done in this method.
1669
+ waitForWalletSessionIfNotCached() {
1670
+ return __async(this, null, function* () {
1671
+ const cachedWalletGetSessionResponse = yield this.kvstore.get(SESSION_STORE_KEY);
1672
+ if (cachedWalletGetSessionResponse) {
1673
+ return;
1674
+ }
1675
+ let unsubscribe;
1676
+ const responsePromise = new Promise((resolve) => {
1677
+ unsubscribe = this.onNotification((message) => {
1678
+ if (typeof message === "object" && message !== null) {
1679
+ if ("data" in message) {
1680
+ const messagePayload = message.data;
1681
+ if (messagePayload.method === "wallet_getSession" || messagePayload.method === "wallet_sessionChanged") {
1682
+ unsubscribe();
1683
+ resolve();
1684
+ }
1685
+ }
1686
+ }
1687
+ });
1688
+ });
1689
+ const timeoutPromise = new Promise((_resolve, reject) => {
1690
+ setTimeout(() => {
1691
+ unsubscribe();
1692
+ this.removeStoredPendingSessionRequest();
1693
+ reject(new import_multichain_api_client2.TransportTimeoutError());
1694
+ }, this.options.resumeTimeout);
1695
+ });
1696
+ return Promise.race([responsePromise, timeoutPromise]);
1697
+ });
1698
+ }
1699
+ };
1700
+ }
1701
+ });
1702
+
1703
+ // src/multichain/transports/mwp/KeyManager.ts
1704
+ var KeyManager_exports = {};
1705
+ __export(KeyManager_exports, {
1706
+ createKeyManager: () => createKeyManager
1707
+ });
1708
+ function createKeyManager() {
1709
+ return __async(this, null, function* () {
1710
+ const { decrypt, encrypt, PrivateKey, PublicKey } = yield import("eciesjs");
1711
+ return {
1712
+ generateKeyPair() {
1713
+ const privateKey = new PrivateKey();
1714
+ return {
1715
+ privateKey: new Uint8Array(privateKey.secret),
1716
+ publicKey: privateKey.publicKey.toBytes(true)
1717
+ };
1718
+ },
1719
+ encrypt(plaintext, theirPublicKey) {
1720
+ return __async(this, null, function* () {
1721
+ const plaintextBuffer = Buffer.from(plaintext, "utf8");
1722
+ const encryptedBuffer = encrypt(theirPublicKey, plaintextBuffer);
1723
+ return encryptedBuffer.toString("base64");
1724
+ });
1725
+ },
1726
+ decrypt(encryptedB64, myPrivateKey) {
1727
+ return __async(this, null, function* () {
1728
+ const encryptedBuffer = Buffer.from(encryptedB64, "base64");
1729
+ const decryptedBuffer = yield decrypt(myPrivateKey, encryptedBuffer);
1730
+ return Buffer.from(decryptedBuffer).toString("utf8");
1731
+ });
1732
+ },
1733
+ validatePeerKey(key) {
1734
+ PublicKey.fromHex(Buffer.from(key).toString("hex"));
1735
+ }
1736
+ };
1737
+ });
1738
+ }
1739
+ var init_KeyManager = __esm({
1740
+ "src/multichain/transports/mwp/KeyManager.ts"() {
1741
+ "use strict";
1742
+ }
1743
+ });
1744
+
1045
1745
  // src/ui/modals/base/utils.ts
1046
1746
  function formatRemainingTime(milliseconds) {
1047
1747
  if (milliseconds <= 0) {
@@ -1334,8 +2034,6 @@ init_domain();
1334
2034
 
1335
2035
  // src/multichain/index.ts
1336
2036
  var import_analytics4 = require("@metamask/analytics");
1337
- var import_mobile_wallet_protocol_core2 = require("@metamask/mobile-wallet-protocol-core");
1338
- var import_mobile_wallet_protocol_dapp_client = require("@metamask/mobile-wallet-protocol-dapp-client");
1339
2037
  var import_multichain_api_client3 = require("@metamask/multichain-api-client");
1340
2038
 
1341
2039
  // src/config/index.ts
@@ -1898,6 +2596,9 @@ var MultichainApiClientWrapperTransport = class {
1898
2596
  return false;
1899
2597
  }
1900
2598
  }
2599
+ isTransportConnected() {
2600
+ return this.isTransportDefined() && this.metamaskConnectMultichain.transport.isConnected();
2601
+ }
1901
2602
  clearNotificationCallbacks() {
1902
2603
  __privateGet(this, _notificationCallbacks2).clear();
1903
2604
  }
@@ -1919,17 +2620,19 @@ var MultichainApiClientWrapperTransport = class {
1919
2620
  this.notifyCallbacks.bind(this)
1920
2621
  );
1921
2622
  }
2623
+ // Purposely noop, resolves successfully. Actual connection is handled by the underlying client/transport.
1922
2624
  connect() {
1923
2625
  return __async(this, null, function* () {
1924
- console.log("\u{1F4DA} connect");
1925
- yield this.metamaskConnectMultichain.emitSessionChanged();
2626
+ return Promise.resolve();
1926
2627
  });
1927
2628
  }
2629
+ // Purposely noop, resolves successfully. Actual connection is handled by the underlying client/transport.
1928
2630
  disconnect() {
1929
2631
  return __async(this, null, function* () {
1930
2632
  return Promise.resolve();
1931
2633
  });
1932
2634
  }
2635
+ // Purposely hardcoded to true. Actual connection is handled by the underlying client/transport.
1933
2636
  isConnected() {
1934
2637
  return true;
1935
2638
  }
@@ -1952,7 +2655,6 @@ var MultichainApiClientWrapperTransport = class {
1952
2655
  default:
1953
2656
  throw new Error(`Unsupported method: ${requestPayload.method}`);
1954
2657
  }
1955
- throw new Error(`Unknown method: ${requestPayload.method}`);
1956
2658
  });
1957
2659
  }
1958
2660
  onNotification(callback) {
@@ -1982,13 +2684,11 @@ walletCreateSession_fn = function(request) {
1982
2684
  }
1983
2685
  });
1984
2686
  const accounts = [...new Set(scopeAccounts)];
1985
- console.log("\u{1F4DA} SDK connect");
1986
2687
  yield this.metamaskConnectMultichain.connect(
1987
2688
  scopes,
1988
2689
  accounts,
1989
2690
  createSessionParams.sessionProperties
1990
2691
  );
1991
- console.log("\u{1F4DA} SDK connected");
1992
2692
  return this.metamaskConnectMultichain.transport.request({
1993
2693
  method: "wallet_getSession"
1994
2694
  });
@@ -1996,7 +2696,7 @@ walletCreateSession_fn = function(request) {
1996
2696
  };
1997
2697
  walletGetSession_fn = function(request) {
1998
2698
  return __async(this, null, function* () {
1999
- if (!this.isTransportDefined()) {
2699
+ if (!this.isTransportConnected()) {
2000
2700
  return {
2001
2701
  jsonrpc: "2.0",
2002
2702
  id: request.id,
@@ -2013,9 +2713,6 @@ walletGetSession_fn = function(request) {
2013
2713
  walletRevokeSession_fn = function(request) {
2014
2714
  return __async(this, null, function* () {
2015
2715
  var _a2;
2016
- if (!this.isTransportDefined()) {
2017
- return { jsonrpc: "2.0", id: request.id, result: true };
2018
- }
2019
2716
  const revokeSessionParams = request.params;
2020
2717
  const scopes = (_a2 = revokeSessionParams == null ? void 0 : revokeSessionParams.scopes) != null ? _a2 : [];
2021
2718
  try {
@@ -2028,7 +2725,7 @@ walletRevokeSession_fn = function(request) {
2028
2725
  };
2029
2726
  walletInvokeMethod_fn = function(request) {
2030
2727
  return __async(this, null, function* () {
2031
- if (!this.isTransportDefined()) {
2728
+ if (!this.isTransportConnected()) {
2032
2729
  return { error: import_rpc_errors.providerErrors.unauthorized() };
2033
2730
  }
2034
2731
  const result = this.metamaskConnectMultichain.invokeMethod(
@@ -2040,684 +2737,11 @@ walletInvokeMethod_fn = function(request) {
2040
2737
  });
2041
2738
  };
2042
2739
 
2043
- // src/multichain/transports/mwp/index.ts
2044
- var import_mobile_wallet_protocol_core = require("@metamask/mobile-wallet-protocol-core");
2045
- var import_multichain_api_client2 = require("@metamask/multichain-api-client");
2046
- var import_rpc_errors2 = require("@metamask/rpc-errors");
2047
- init_domain();
2048
- init_utils();
2049
-
2050
- // src/multichain/transports/constants.ts
2051
- var MULTICHAIN_PROVIDER_STREAM_NAME = "metamask-multichain-provider";
2052
-
2053
- // src/multichain/transports/mwp/index.ts
2054
- var DEFAULT_REQUEST_TIMEOUT2 = 60 * 1e3;
2055
- var CONNECTION_GRACE_PERIOD = 60 * 1e3;
2056
- var DEFAULT_CONNECTION_TIMEOUT = DEFAULT_REQUEST_TIMEOUT2 + CONNECTION_GRACE_PERIOD;
2057
- var DEFAULT_RESUME_TIMEOUT = 10 * 1e3;
2058
- var SESSION_STORE_KEY = "cache_wallet_getSession";
2059
- var ACCOUNTS_STORE_KEY = "cache_eth_accounts";
2060
- var CHAIN_STORE_KEY = "cache_eth_chainId";
2061
- var PENDING_SESSION_REQUEST_KEY = "pending_session_request";
2062
- var CACHED_METHOD_LIST = [
2063
- "wallet_getSession",
2064
- "wallet_createSession",
2065
- "wallet_sessionChanged"
2066
- ];
2067
- var CACHED_RESET_METHOD_LIST = [
2068
- "wallet_revokeSession",
2069
- "wallet_revokePermissions"
2070
- ];
2071
- var logger = createLogger("metamask-sdk:transport");
2072
- var MWPTransport = class {
2073
- constructor(dappClient, kvstore, options = {
2074
- requestTimeout: DEFAULT_REQUEST_TIMEOUT2,
2075
- connectionTimeout: DEFAULT_CONNECTION_TIMEOUT,
2076
- resumeTimeout: DEFAULT_RESUME_TIMEOUT
2077
- }) {
2078
- this.dappClient = dappClient;
2079
- this.kvstore = kvstore;
2080
- this.options = options;
2081
- this.__pendingRequests = /* @__PURE__ */ new Map();
2082
- this.notificationCallbacks = /* @__PURE__ */ new Set();
2083
- this.dappClient.on("message", this.handleMessage.bind(this));
2084
- this.dappClient.on("session_request", (sessionRequest) => {
2085
- this.currentSessionRequest = sessionRequest;
2086
- this.kvstore.set(PENDING_SESSION_REQUEST_KEY, JSON.stringify(sessionRequest)).catch((err) => {
2087
- logger("Failed to store pending session request", err);
2088
- });
2089
- });
2090
- if (typeof window !== "undefined" && typeof window.addEventListener !== "undefined") {
2091
- this.windowFocusHandler = this.onWindowFocus.bind(this);
2092
- window.addEventListener("focus", this.windowFocusHandler);
2093
- }
2094
- }
2095
- get pendingRequests() {
2096
- return this.__pendingRequests;
2097
- }
2098
- set pendingRequests(pendingRequests) {
2099
- this.__pendingRequests = pendingRequests;
2100
- }
2101
- get sessionRequest() {
2102
- return this.currentSessionRequest;
2103
- }
2104
- /**
2105
- * Returns the stored pending session request from the dappClient session_request event, if any.
2106
- *
2107
- * @returns The stored SessionRequest, or null if none or invalid.
2108
- */
2109
- getStoredPendingSessionRequest() {
2110
- return __async(this, null, function* () {
2111
- try {
2112
- const raw = yield this.kvstore.get(PENDING_SESSION_REQUEST_KEY);
2113
- if (!raw) {
2114
- return null;
2115
- }
2116
- return JSON.parse(raw);
2117
- } catch (e) {
2118
- return null;
2119
- }
2120
- });
2121
- }
2122
- /**
2123
- * Removes the stored pending session request from the KVStore.
2124
- * This is necessary to ensure that ConnectMultichain is able to correctly
2125
- * infer the MWP Transport connection attempt status.
2126
- */
2127
- removeStoredPendingSessionRequest() {
2128
- return __async(this, null, function* () {
2129
- yield this.kvstore.delete(PENDING_SESSION_REQUEST_KEY);
2130
- });
2131
- }
2132
- onWindowFocus() {
2133
- if (!this.isConnected()) {
2134
- this.dappClient.reconnect();
2135
- }
2136
- }
2137
- notifyCallbacks(data) {
2138
- this.notificationCallbacks.forEach((callback) => callback(data));
2139
- }
2140
- rejectRequest(id, error = new Error("Request rejected")) {
2141
- const request = this.pendingRequests.get(id);
2142
- if (request) {
2143
- this.pendingRequests.delete(id);
2144
- clearTimeout(request.timeout);
2145
- request.reject(error);
2146
- }
2147
- }
2148
- parseWalletError(errorPayload) {
2149
- const errorData = errorPayload;
2150
- if (typeof errorData.code === "number" && typeof errorData.message === "string") {
2151
- const { code, message: message2 } = errorData;
2152
- if (code >= 1e3 && code <= 4999) {
2153
- return import_rpc_errors2.providerErrors.custom({ code, message: message2 });
2154
- }
2155
- return new import_rpc_errors2.JsonRpcError(code, message2);
2156
- }
2157
- const message = errorPayload instanceof Error ? errorPayload.message : JSON.stringify(errorPayload);
2158
- return import_rpc_errors2.rpcErrors.internal({ message });
2159
- }
2160
- handleMessage(message) {
2161
- if (typeof message === "object" && message !== null) {
2162
- if ("data" in message) {
2163
- const messagePayload = message.data;
2164
- if ("id" in messagePayload && typeof messagePayload.id === "string") {
2165
- const request = this.pendingRequests.get(messagePayload.id);
2166
- if (request) {
2167
- clearTimeout(request.timeout);
2168
- if ("error" in messagePayload && messagePayload.error) {
2169
- this.pendingRequests.delete(messagePayload.id);
2170
- request.reject(this.parseWalletError(messagePayload.error));
2171
- return;
2172
- }
2173
- const requestWithName = __spreadProps(__spreadValues({}, messagePayload), {
2174
- method: request.method === "wallet_getSession" || request.method === "wallet_createSession" ? "wallet_sessionChanged" : request.method
2175
- });
2176
- const notification = __spreadProps(__spreadValues({}, messagePayload), {
2177
- method: request.method === "wallet_getSession" || request.method === "wallet_createSession" ? "wallet_sessionChanged" : request.method,
2178
- params: requestWithName.result
2179
- });
2180
- this.notifyCallbacks(notification);
2181
- request.resolve(requestWithName);
2182
- this.pendingRequests.delete(messagePayload.id);
2183
- }
2184
- } else {
2185
- if (message.data.method === "metamask_chainChanged") {
2186
- this.kvstore.set(
2187
- CHAIN_STORE_KEY,
2188
- JSON.stringify(
2189
- message.data.params.chainId
2190
- )
2191
- );
2192
- }
2193
- if (message.data.method === "metamask_accountsChanged") {
2194
- this.kvstore.set(
2195
- ACCOUNTS_STORE_KEY,
2196
- JSON.stringify(
2197
- message.data.params
2198
- )
2199
- );
2200
- }
2201
- if (message.data.method === "wallet_sessionChanged") {
2202
- const notification = message.data;
2203
- const response = {
2204
- result: notification.params
2205
- };
2206
- this.kvstore.set(SESSION_STORE_KEY, JSON.stringify(response));
2207
- }
2208
- this.notifyCallbacks(message.data);
2209
- }
2210
- }
2211
- }
2212
- }
2213
- onResumeSuccess(resumeResolve, resumeReject, options) {
2214
- return __async(this, null, function* () {
2215
- var _a2, _b, _c, _d, _e, _f, _g;
2216
- try {
2217
- yield this.waitForWalletSessionIfNotCached();
2218
- const sessionRequest = yield this.request({
2219
- method: "wallet_getSession"
2220
- });
2221
- if (sessionRequest.error) {
2222
- return resumeReject(new Error(sessionRequest.error.message));
2223
- }
2224
- let walletSession = sessionRequest.result;
2225
- if (walletSession && options) {
2226
- const currentScopes = Object.keys(
2227
- (_a2 = walletSession == null ? void 0 : walletSession.sessionScopes) != null ? _a2 : {}
2228
- );
2229
- const proposedScopes = (_b = options == null ? void 0 : options.scopes) != null ? _b : [];
2230
- const proposedCaipAccountIds = (_c = options == null ? void 0 : options.caipAccountIds) != null ? _c : [];
2231
- const hasSameScopesAndAccounts = isSameScopesAndAccounts(
2232
- currentScopes,
2233
- proposedScopes,
2234
- walletSession,
2235
- proposedCaipAccountIds
2236
- );
2237
- if (options.forceRequest || !hasSameScopesAndAccounts) {
2238
- const optionalScopes = addValidAccounts(
2239
- getOptionalScopes((_d = options == null ? void 0 : options.scopes) != null ? _d : []),
2240
- getValidAccounts((_e = options == null ? void 0 : options.caipAccountIds) != null ? _e : [])
2241
- );
2242
- const sessionRequest2 = {
2243
- optionalScopes
2244
- };
2245
- const response = yield this.request({
2246
- method: "wallet_createSession",
2247
- params: sessionRequest2
2248
- });
2249
- if (response.error) {
2250
- return resumeReject(new Error(response.error.message));
2251
- }
2252
- walletSession = response.result;
2253
- }
2254
- } else if (!walletSession) {
2255
- const optionalScopes = addValidAccounts(
2256
- getOptionalScopes((_f = options == null ? void 0 : options.scopes) != null ? _f : []),
2257
- getValidAccounts((_g = options == null ? void 0 : options.caipAccountIds) != null ? _g : [])
2258
- );
2259
- const sessionRequest2 = { optionalScopes };
2260
- const response = yield this.request({
2261
- method: "wallet_createSession",
2262
- params: sessionRequest2
2263
- });
2264
- if (response.error) {
2265
- return resumeReject(new Error(response.error.message));
2266
- }
2267
- walletSession = response.result;
2268
- }
2269
- yield this.removeStoredPendingSessionRequest();
2270
- this.notifyCallbacks({
2271
- method: "wallet_sessionChanged",
2272
- params: walletSession
2273
- });
2274
- return resumeResolve();
2275
- } catch (err) {
2276
- return resumeReject(err);
2277
- }
2278
- });
2279
- }
2280
- init() {
2281
- return __async(this, null, function* () {
2282
- });
2283
- }
2284
- // TODO: Rename this
2285
- sendEip1193Message(payload, options) {
2286
- return __async(this, null, function* () {
2287
- const request = __spreadValues({
2288
- jsonrpc: "2.0",
2289
- id: String(getUniqueRequestId())
2290
- }, payload);
2291
- const cachedWalletSession = yield this.getCachedResponse(request);
2292
- if (cachedWalletSession) {
2293
- this.notifyCallbacks(cachedWalletSession);
2294
- return cachedWalletSession;
2295
- }
2296
- return new Promise((resolve, reject) => {
2297
- var _a2;
2298
- const timeout = setTimeout(() => {
2299
- this.rejectRequest(request.id, new import_multichain_api_client2.TransportTimeoutError());
2300
- }, (_a2 = options == null ? void 0 : options.timeout) != null ? _a2 : this.options.requestTimeout);
2301
- this.pendingRequests.set(request.id, {
2302
- request,
2303
- method: request.method,
2304
- resolve: (response) => __async(this, null, function* () {
2305
- yield this.storeWalletSession(request, response);
2306
- return resolve(response);
2307
- }),
2308
- reject,
2309
- timeout
2310
- });
2311
- this.dappClient.sendRequest({
2312
- name: "metamask-provider",
2313
- data: request
2314
- }).catch(reject);
2315
- });
2316
- });
2317
- }
2318
- connect(options) {
2319
- return __async(this, null, function* () {
2320
- const { dappClient } = this;
2321
- const session = yield this.getActiveSession();
2322
- if (session) {
2323
- logger("active session found", {
2324
- id: session.id,
2325
- channel: session.channel,
2326
- expiresAt: session.expiresAt
2327
- });
2328
- }
2329
- const storedSessionRequestBeforeConnectionAttempt = yield this.getStoredPendingSessionRequest();
2330
- let timeout;
2331
- let initialConnectionMessageHandler;
2332
- const connectionPromise = new Promise((resolve, reject) => __async(this, null, function* () {
2333
- let connection;
2334
- if (session) {
2335
- connection = new Promise((resumeResolve, resumeReject) => {
2336
- var _a2;
2337
- if (this.dappClient.state === "CONNECTED") {
2338
- this.onResumeSuccess(resumeResolve, resumeReject, options);
2339
- } else {
2340
- this.dappClient.once("connected", () => __async(this, null, function* () {
2341
- this.onResumeSuccess(resumeResolve, resumeReject, options);
2342
- }));
2343
- dappClient.resume((_a2 = session == null ? void 0 : session.id) != null ? _a2 : "");
2344
- }
2345
- });
2346
- } else {
2347
- connection = new Promise(
2348
- (resolveConnection, rejectConnection) => {
2349
- var _a2, _b;
2350
- const optionalScopes = addValidAccounts(
2351
- getOptionalScopes((_a2 = options == null ? void 0 : options.scopes) != null ? _a2 : []),
2352
- getValidAccounts((_b = options == null ? void 0 : options.caipAccountIds) != null ? _b : [])
2353
- );
2354
- const sessionRequest = {
2355
- optionalScopes,
2356
- sessionProperties: options == null ? void 0 : options.sessionProperties
2357
- };
2358
- const request = {
2359
- jsonrpc: "2.0",
2360
- id: String(getUniqueRequestId()),
2361
- method: "wallet_createSession",
2362
- params: sessionRequest
2363
- };
2364
- initialConnectionMessageHandler = (message) => __async(this, null, function* () {
2365
- if (typeof message !== "object" || message === null) {
2366
- return;
2367
- }
2368
- if (!("data" in message)) {
2369
- return;
2370
- }
2371
- const messagePayload = message.data;
2372
- const isMatchingId = messagePayload.id === request.id;
2373
- const isMatchingMethod = messagePayload.method === "wallet_createSession" || messagePayload.method === "wallet_sessionChanged";
2374
- if (!isMatchingId && !isMatchingMethod) {
2375
- return;
2376
- }
2377
- if (messagePayload.error) {
2378
- return rejectConnection(
2379
- this.parseWalletError(messagePayload.error)
2380
- );
2381
- }
2382
- yield this.storeWalletSession(
2383
- request,
2384
- messagePayload
2385
- );
2386
- yield this.removeStoredPendingSessionRequest();
2387
- this.notifyCallbacks(messagePayload);
2388
- return resolveConnection();
2389
- });
2390
- this.dappClient.on("message", initialConnectionMessageHandler);
2391
- dappClient.connect({
2392
- mode: "trusted",
2393
- initialPayload: {
2394
- name: MULTICHAIN_PROVIDER_STREAM_NAME,
2395
- data: request
2396
- }
2397
- }).catch((error) => {
2398
- if (initialConnectionMessageHandler) {
2399
- this.dappClient.off(
2400
- "message",
2401
- initialConnectionMessageHandler
2402
- );
2403
- }
2404
- rejectConnection(error);
2405
- });
2406
- }
2407
- );
2408
- }
2409
- timeout = setTimeout(
2410
- () => {
2411
- reject(new import_multichain_api_client2.TransportTimeoutError());
2412
- },
2413
- storedSessionRequestBeforeConnectionAttempt ? this.options.resumeTimeout : this.options.connectionTimeout
2414
- );
2415
- connection.then(resolve).catch(reject);
2416
- }));
2417
- return connectionPromise.catch((error) => __async(this, null, function* () {
2418
- yield this.dappClient.disconnect();
2419
- throw error;
2420
- })).finally(() => {
2421
- if (timeout) {
2422
- clearTimeout(timeout);
2423
- }
2424
- if (initialConnectionMessageHandler) {
2425
- this.dappClient.off("message", initialConnectionMessageHandler);
2426
- initialConnectionMessageHandler = void 0;
2427
- }
2428
- this.removeStoredPendingSessionRequest();
2429
- });
2430
- });
2431
- }
2432
- /**
2433
- * Disconnects from the Mobile Wallet Protocol
2434
- *
2435
- * @param [scopes] - The scopes to revoke. If not provided or empty, all scopes will be revoked.
2436
- * @returns Nothing
2437
- */
2438
- disconnect() {
2439
- return __async(this, arguments, function* (scopes = []) {
2440
- var _a2, _b;
2441
- const cachedSession = yield this.getCachedResponse({
2442
- jsonrpc: "2.0",
2443
- id: "0",
2444
- method: "wallet_getSession"
2445
- });
2446
- const cachedSessionScopes = (_b = (_a2 = cachedSession == null ? void 0 : cachedSession.result) == null ? void 0 : _a2.sessionScopes) != null ? _b : {};
2447
- const remainingScopes = scopes.length === 0 ? [] : Object.keys(cachedSessionScopes).filter(
2448
- (scope) => !scopes.includes(scope)
2449
- );
2450
- const newSessionScopes = Object.fromEntries(
2451
- Object.entries(cachedSessionScopes).filter(
2452
- ([key]) => remainingScopes.includes(key)
2453
- )
2454
- );
2455
- this.request({ method: "wallet_revokeSession", params: { scopes } }).catch(
2456
- (err) => {
2457
- console.error("error revoking session", err);
2458
- }
2459
- );
2460
- const remainingScopesIncludeEip155 = remainingScopes.some(
2461
- (scope) => scope.includes("eip155")
2462
- );
2463
- if (!remainingScopesIncludeEip155) {
2464
- this.kvstore.delete(ACCOUNTS_STORE_KEY);
2465
- this.kvstore.delete(CHAIN_STORE_KEY);
2466
- }
2467
- if (remainingScopes.length > 0) {
2468
- this.kvstore.set(
2469
- SESSION_STORE_KEY,
2470
- JSON.stringify({
2471
- result: {
2472
- sessionScopes: newSessionScopes
2473
- }
2474
- })
2475
- );
2476
- } else {
2477
- this.kvstore.delete(SESSION_STORE_KEY);
2478
- if (typeof window !== "undefined" && typeof window.removeEventListener !== "undefined" && this.windowFocusHandler) {
2479
- window.removeEventListener("focus", this.windowFocusHandler);
2480
- this.windowFocusHandler = void 0;
2481
- }
2482
- yield this.dappClient.disconnect();
2483
- }
2484
- this.notifyCallbacks({
2485
- method: "wallet_sessionChanged",
2486
- params: {
2487
- sessionScopes: newSessionScopes
2488
- }
2489
- });
2490
- });
2491
- }
2492
- /**
2493
- * Checks if the transport is connected
2494
- *
2495
- * @returns True if transport is connected, false otherwise
2496
- */
2497
- isConnected() {
2498
- return this.dappClient.state === "CONNECTED";
2499
- }
2500
- /**
2501
- * Attempts to re-establish a connection via DappClient
2502
- *
2503
- * @returns Nothing
2504
- */
2505
- // TODO: We should re-evaluate adding this to the WebSocketTransport layer from `@metamask/mobile-wallet-protocol-core`
2506
- // ticket: https://consensyssoftware.atlassian.net/browse/WAPI-862
2507
- attemptResumeSession() {
2508
- return __async(this, null, function* () {
2509
- try {
2510
- yield this.dappClient.reconnect();
2511
- yield new Promise((resolve, reject) => {
2512
- const timeout = setTimeout(() => {
2513
- reject(new Error("Resume timeout"));
2514
- }, 2e3);
2515
- if (this.isConnected()) {
2516
- clearTimeout(timeout);
2517
- resolve();
2518
- } else {
2519
- this.dappClient.once("connected", () => {
2520
- clearTimeout(timeout);
2521
- resolve();
2522
- });
2523
- }
2524
- });
2525
- } catch (error) {
2526
- return Promise.reject(
2527
- new Error(`Failed to resume session: ${error.message}`)
2528
- );
2529
- }
2530
- });
2531
- }
2532
- getCachedResponse(request) {
2533
- return __async(this, null, function* () {
2534
- var _a2;
2535
- if (request.method === "wallet_getSession") {
2536
- const walletGetSession = yield this.kvstore.get(SESSION_STORE_KEY);
2537
- if (walletGetSession) {
2538
- const walletSession = JSON.parse(walletGetSession);
2539
- return {
2540
- id: request.id,
2541
- jsonrpc: "2.0",
2542
- result: (_a2 = walletSession.params) != null ? _a2 : walletSession.result,
2543
- // "what?... why walletSession.params?.."
2544
- method: request.method
2545
- };
2546
- }
2547
- } else if (request.method === "eth_accounts") {
2548
- const ethAccounts = yield this.kvstore.get(ACCOUNTS_STORE_KEY);
2549
- if (ethAccounts) {
2550
- return {
2551
- id: request.id,
2552
- jsonrpc: "2.0",
2553
- result: JSON.parse(ethAccounts),
2554
- method: request.method
2555
- };
2556
- }
2557
- } else if (request.method === "eth_chainId") {
2558
- const ethChainId = yield this.kvstore.get(CHAIN_STORE_KEY);
2559
- if (ethChainId) {
2560
- return {
2561
- id: request.id,
2562
- jsonrpc: "2.0",
2563
- result: JSON.parse(ethChainId),
2564
- method: request.method
2565
- };
2566
- }
2567
- }
2568
- });
2569
- }
2570
- storeWalletSession(request, response) {
2571
- return __async(this, null, function* () {
2572
- if (response.error) {
2573
- return;
2574
- }
2575
- if (CACHED_METHOD_LIST.includes(request.method)) {
2576
- yield this.kvstore.set(SESSION_STORE_KEY, JSON.stringify(response));
2577
- } else if (request.method === "eth_accounts") {
2578
- yield this.kvstore.set(
2579
- ACCOUNTS_STORE_KEY,
2580
- JSON.stringify(response.result)
2581
- );
2582
- } else if (request.method === "eth_chainId") {
2583
- yield this.kvstore.set(CHAIN_STORE_KEY, JSON.stringify(response.result));
2584
- } else if (CACHED_RESET_METHOD_LIST.includes(request.method)) {
2585
- yield this.kvstore.delete(SESSION_STORE_KEY);
2586
- yield this.kvstore.delete(ACCOUNTS_STORE_KEY);
2587
- yield this.kvstore.delete(CHAIN_STORE_KEY);
2588
- }
2589
- });
2590
- }
2591
- request(payload, options) {
2592
- return __async(this, null, function* () {
2593
- const request = __spreadValues({
2594
- jsonrpc: "2.0",
2595
- id: String(getUniqueRequestId())
2596
- }, payload);
2597
- const cachedWalletSession = yield this.getCachedResponse(request);
2598
- if (cachedWalletSession) {
2599
- this.notifyCallbacks(cachedWalletSession);
2600
- return cachedWalletSession;
2601
- }
2602
- if (!this.isConnected()) {
2603
- yield this.attemptResumeSession();
2604
- }
2605
- return new Promise((resolve, reject) => {
2606
- var _a2;
2607
- const timeout = setTimeout(() => {
2608
- this.rejectRequest(request.id, new import_multichain_api_client2.TransportTimeoutError());
2609
- }, (_a2 = options == null ? void 0 : options.timeout) != null ? _a2 : this.options.requestTimeout);
2610
- this.pendingRequests.set(request.id, {
2611
- request,
2612
- method: request.method,
2613
- resolve: (response) => __async(this, null, function* () {
2614
- yield this.storeWalletSession(request, response);
2615
- return resolve(response);
2616
- }),
2617
- reject,
2618
- timeout
2619
- });
2620
- this.dappClient.sendRequest({
2621
- name: MULTICHAIN_PROVIDER_STREAM_NAME,
2622
- data: request
2623
- }).catch(reject);
2624
- });
2625
- });
2626
- }
2627
- onNotification(callback) {
2628
- this.notificationCallbacks.add(callback);
2629
- return () => {
2630
- this.notificationCallbacks.delete(callback);
2631
- };
2632
- }
2633
- getActiveSession() {
2634
- return __async(this, null, function* () {
2635
- const { kvstore } = this;
2636
- const sessionStore = yield import_mobile_wallet_protocol_core.SessionStore.create(kvstore);
2637
- try {
2638
- const [activeSession] = yield sessionStore.list();
2639
- return activeSession;
2640
- } catch (error) {
2641
- logger("error getting active session", error);
2642
- return void 0;
2643
- }
2644
- });
2645
- }
2646
- // This method checks if an existing CAIP session response is cached or waits for one
2647
- // to be received from the wallet if not cached. This is necessary because there is an edge
2648
- // case during the initial connection flow where after the user has accepted the permission approval
2649
- // and returned back to the dapp from the wallet, the dapp page may have gotten unloaded and refreshed.
2650
- // When it is unloaded and refreshed, it will try to resume the session by making a request for wallet_getSession
2651
- // which should resolve from cache, but because a race condition makes it possible for the response from the wallet
2652
- // for the initial wallet_createSession connection request to not have been handled and cached yet. This results
2653
- // in the wallet_getSession request never resolving unless we wait for it explicitly as done in this method.
2654
- waitForWalletSessionIfNotCached() {
2655
- return __async(this, null, function* () {
2656
- const cachedWalletGetSessionResponse = yield this.kvstore.get(SESSION_STORE_KEY);
2657
- if (cachedWalletGetSessionResponse) {
2658
- return;
2659
- }
2660
- let unsubscribe;
2661
- const responsePromise = new Promise((resolve) => {
2662
- unsubscribe = this.onNotification((message) => {
2663
- if (typeof message === "object" && message !== null) {
2664
- if ("data" in message) {
2665
- const messagePayload = message.data;
2666
- if (messagePayload.method === "wallet_getSession" || messagePayload.method === "wallet_sessionChanged") {
2667
- unsubscribe();
2668
- resolve();
2669
- }
2670
- }
2671
- }
2672
- });
2673
- });
2674
- const timeoutPromise = new Promise((_resolve, reject) => {
2675
- setTimeout(() => {
2676
- unsubscribe();
2677
- this.removeStoredPendingSessionRequest();
2678
- reject(new import_multichain_api_client2.TransportTimeoutError());
2679
- }, this.options.resumeTimeout);
2680
- });
2681
- return Promise.race([responsePromise, timeoutPromise]);
2682
- });
2683
- }
2684
- };
2685
-
2686
- // src/multichain/transports/mwp/KeyManager.ts
2687
- var import_eciesjs = require("eciesjs");
2688
- var KeyManager = class {
2689
- generateKeyPair() {
2690
- const privateKey = new import_eciesjs.PrivateKey();
2691
- return {
2692
- privateKey: new Uint8Array(privateKey.secret),
2693
- publicKey: privateKey.publicKey.toBytes(true)
2694
- };
2695
- }
2696
- encrypt(plaintext, theirPublicKey) {
2697
- return __async(this, null, function* () {
2698
- const plaintextBuffer = Buffer.from(plaintext, "utf8");
2699
- const encryptedBuffer = (0, import_eciesjs.encrypt)(theirPublicKey, plaintextBuffer);
2700
- return encryptedBuffer.toString("base64");
2701
- });
2702
- }
2703
- decrypt(encryptedB64, myPrivateKey) {
2704
- return __async(this, null, function* () {
2705
- const encryptedBuffer = Buffer.from(encryptedB64, "base64");
2706
- const decryptedBuffer = yield (0, import_eciesjs.decrypt)(myPrivateKey, encryptedBuffer);
2707
- return Buffer.from(decryptedBuffer).toString("utf8");
2708
- });
2709
- }
2710
- validatePeerKey(key) {
2711
- import_eciesjs.PublicKey.fromHex(Buffer.from(key).toString("hex"));
2712
- }
2713
- };
2714
- var keymanager = new KeyManager();
2715
-
2716
2740
  // src/multichain/index.ts
2717
2741
  init_utils();
2718
2742
  var logger2 = createLogger("metamask-sdk:core");
2719
2743
  var SINGLETON_KEY = "__METAMASK_CONNECT_MULTICHAIN_SINGLETON__";
2720
- var _a, _provider, _providerTransportWrapper, _transport2, _dappClient, _beforeUnloadListener, _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;
2744
+ var _a, _provider, _providerTransportWrapper, _transport2, _dappClient, _beforeUnloadListener, _transportType, _listener, _anonId, _sdkInfo, _MetaMaskConnectMultichain_instances, setupAnalytics_fn, onTransportNotification_fn, getStoredTransport_fn, setupTransport_fn, buildConnectionMetadata_fn, init_fn2, createDappClient_fn, setupMWP_fn, onBeforeUnload_fn, createBeforeUnloadListener_fn, renderInstallModalAsync_fn, showInstallModal_fn, headlessConnect_fn, setupDefaultTransport_fn, deeplinkConnect_fn, handleConnection_fn, getCaipSession_fn, openConnectDeeplinkIfNeeded_fn;
2721
2745
  var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends MultichainCore {
2722
2746
  constructor(options) {
2723
2747
  var _a2, _b, _c, _d, _e, _f;
@@ -2735,7 +2759,7 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
2735
2759
  versions: __spreadValues({
2736
2760
  // typeof guard needed: Metro (React Native) bundles TS source directly,
2737
2761
  // bypassing the tsup build that substitutes __PACKAGE_VERSION__.
2738
- "connect-multichain": false ? "unknown" : "0.12.1"
2762
+ "connect-multichain": false ? "unknown" : "0.13.0"
2739
2763
  }, (_f = options.versions) != null ? _f : {})
2740
2764
  });
2741
2765
  super(allOptions);
@@ -2745,6 +2769,7 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
2745
2769
  __privateAdd(this, _transport2);
2746
2770
  __privateAdd(this, _dappClient);
2747
2771
  __privateAdd(this, _beforeUnloadListener);
2772
+ __privateAdd(this, _transportType);
2748
2773
  this._status = "pending";
2749
2774
  __privateAdd(this, _listener);
2750
2775
  __privateAdd(this, _anonId);
@@ -2781,12 +2806,13 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
2781
2806
  }
2782
2807
  return __privateGet(this, _dappClient);
2783
2808
  }
2809
+ get transportType() {
2810
+ var _a2;
2811
+ return (_a2 = __privateGet(this, _transportType)) != null ? _a2 : "unknown" /* UNKNOWN */;
2812
+ }
2784
2813
  get storage() {
2785
2814
  return this.options.storage;
2786
2815
  }
2787
- get transportType() {
2788
- return __privateGet(this, _transport2) instanceof MWPTransport ? "mwp" /* MWP */ : "browser" /* Browser */;
2789
- }
2790
2816
  // Creates a singleton instance of MetaMaskConnectMultichain.
2791
2817
  // If the singleton already exists, it merges the incoming options with the
2792
2818
  // existing singleton options for the following keys: `api.supportedNetworks`,
@@ -2840,7 +2866,7 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
2840
2866
  connect(scopes, caipAccountIds, sessionProperties, forceRequest) {
2841
2867
  return __async(this, null, function* () {
2842
2868
  var _a2;
2843
- if (this.status === "connecting" && this.transportType === "mwp" /* MWP */) {
2869
+ if (this.status === "connecting" && __privateGet(this, _transportType) === "mwp" /* MWP */) {
2844
2870
  yield __privateMethod(this, _MetaMaskConnectMultichain_instances, openConnectDeeplinkIfNeeded_fn).call(this);
2845
2871
  throw new Error(
2846
2872
  "Existing connection is pending. Please check your MetaMask Mobile app to continue."
@@ -2889,7 +2915,7 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
2889
2915
  sessionProperties: nonEmptySessionProperties,
2890
2916
  forceRequest
2891
2917
  }).then(() => __async(this, null, function* () {
2892
- if (__privateGet(this, _transport2) instanceof MWPTransport) {
2918
+ if (__privateGet(this, _transportType) === "mwp" /* MWP */) {
2893
2919
  return this.storage.setTransport("mwp" /* MWP */);
2894
2920
  }
2895
2921
  return this.storage.setTransport("browser" /* Browser */);
@@ -2936,12 +2962,13 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
2936
2962
  yield (_a2 = __privateGet(this, _transport2)) == null ? void 0 : _a2.disconnect(scopes);
2937
2963
  if (remainingScopes.length === 0) {
2938
2964
  yield this.storage.removeTransport();
2939
- if (this.transportType !== "browser" /* Browser */) {
2965
+ if (__privateGet(this, _transportType) !== "browser" /* Browser */) {
2940
2966
  yield (_b = __privateGet(this, _listener)) == null ? void 0 : _b.call(this);
2941
2967
  (_c = __privateGet(this, _beforeUnloadListener)) == null ? void 0 : _c.call(this);
2942
2968
  __privateSet(this, _listener, void 0);
2943
2969
  __privateSet(this, _beforeUnloadListener, void 0);
2944
2970
  __privateSet(this, _transport2, void 0);
2971
+ __privateSet(this, _transportType, void 0);
2945
2972
  __privateGet(this, _providerTransportWrapper).clearTransportNotificationListener();
2946
2973
  __privateSet(this, _dappClient, void 0);
2947
2974
  }
@@ -2951,13 +2978,14 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
2951
2978
  }
2952
2979
  invokeMethod(request) {
2953
2980
  return __async(this, null, function* () {
2981
+ var _a2;
2954
2982
  const { transport, options } = this;
2955
2983
  const rpcClient = new RpcClient(options, __privateGet(this, _sdkInfo));
2956
2984
  const requestRouter = new RequestRouter(
2957
2985
  transport,
2958
2986
  rpcClient,
2959
2987
  options,
2960
- this.transportType
2988
+ (_a2 = __privateGet(this, _transportType)) != null ? _a2 : "unknown" /* UNKNOWN */
2961
2989
  );
2962
2990
  return requestRouter.invokeMethod(request);
2963
2991
  });
@@ -3006,6 +3034,7 @@ _providerTransportWrapper = new WeakMap();
3006
3034
  _transport2 = new WeakMap();
3007
3035
  _dappClient = new WeakMap();
3008
3036
  _beforeUnloadListener = new WeakMap();
3037
+ _transportType = new WeakMap();
3009
3038
  _listener = new WeakMap();
3010
3039
  _anonId = new WeakMap();
3011
3040
  _sdkInfo = new WeakMap();
@@ -3063,6 +3092,7 @@ getStoredTransport_fn = function() {
3063
3092
  if (hasExtensionInstalled) {
3064
3093
  const apiTransport = new DefaultTransport();
3065
3094
  __privateSet(this, _transport2, apiTransport);
3095
+ __privateSet(this, _transportType, "browser" /* Browser */);
3066
3096
  __privateGet(this, _providerTransportWrapper).setupTransportNotificationListener();
3067
3097
  __privateSet(this, _listener, apiTransport.onNotification(
3068
3098
  __privateMethod(this, _MetaMaskConnectMultichain_instances, onTransportNotification_fn).bind(this)
@@ -3072,9 +3102,11 @@ getStoredTransport_fn = function() {
3072
3102
  } else if (transportType === "mwp" /* MWP */) {
3073
3103
  const { adapter: kvstore } = this.options.storage;
3074
3104
  const dappClient = yield __privateMethod(this, _MetaMaskConnectMultichain_instances, createDappClient_fn).call(this);
3075
- const apiTransport = new MWPTransport(dappClient, kvstore);
3105
+ const { MWPTransport: MWPTransport2 } = yield Promise.resolve().then(() => (init_mwp(), mwp_exports));
3106
+ const apiTransport = new MWPTransport2(dappClient, kvstore);
3076
3107
  __privateSet(this, _dappClient, dappClient);
3077
3108
  __privateSet(this, _transport2, apiTransport);
3109
+ __privateSet(this, _transportType, "mwp" /* MWP */);
3078
3110
  __privateGet(this, _providerTransportWrapper).setupTransportNotificationListener();
3079
3111
  __privateSet(this, _listener, apiTransport.onNotification(
3080
3112
  __privateMethod(this, _MetaMaskConnectMultichain_instances, onTransportNotification_fn).bind(this)
@@ -3096,7 +3128,7 @@ setupTransport_fn = function() {
3096
3128
  yield this.transport.connect();
3097
3129
  }
3098
3130
  this.status = "connected";
3099
- if (this.transport instanceof MWPTransport) {
3131
+ if (__privateGet(this, _transportType) === "mwp" /* MWP */) {
3100
3132
  yield this.storage.setTransport("mwp" /* MWP */);
3101
3133
  } else {
3102
3134
  yield this.storage.setTransport("browser" /* Browser */);
@@ -3140,31 +3172,43 @@ init_fn2 = function() {
3140
3172
  };
3141
3173
  createDappClient_fn = function() {
3142
3174
  return __async(this, null, function* () {
3175
+ const [mwpCore, { DappClient: DappClientClass }, { createKeyManager: createKeyManager2 }] = yield Promise.all([
3176
+ import("@metamask/mobile-wallet-protocol-core"),
3177
+ import("@metamask/mobile-wallet-protocol-dapp-client"),
3178
+ Promise.resolve().then(() => (init_KeyManager(), KeyManager_exports))
3179
+ ]);
3180
+ const keymanager = yield createKeyManager2();
3143
3181
  const { adapter: kvstore } = this.options.storage;
3144
- const sessionstore = yield import_mobile_wallet_protocol_core2.SessionStore.create(kvstore);
3182
+ const sessionstore = yield mwpCore.SessionStore.create(kvstore);
3145
3183
  const websocket = (
3146
3184
  // eslint-disable-next-line no-negated-condition
3147
3185
  typeof window !== "undefined" ? WebSocket : (yield import("ws")).WebSocket
3148
3186
  );
3149
- const transport = yield import_mobile_wallet_protocol_core2.WebSocketTransport.create({
3187
+ const transport = yield mwpCore.WebSocketTransport.create({
3150
3188
  url: MWP_RELAY_URL,
3151
3189
  kvstore,
3152
3190
  websocket
3153
3191
  });
3154
- const dappClient = new import_mobile_wallet_protocol_dapp_client.DappClient({ transport, sessionstore, keymanager });
3192
+ const dappClient = new DappClientClass({
3193
+ transport,
3194
+ sessionstore,
3195
+ keymanager
3196
+ });
3155
3197
  return dappClient;
3156
3198
  });
3157
3199
  };
3158
3200
  setupMWP_fn = function() {
3159
3201
  return __async(this, null, function* () {
3160
- if (__privateGet(this, _transport2) instanceof MWPTransport) {
3202
+ if (__privateGet(this, _transportType) === "mwp" /* MWP */) {
3161
3203
  return;
3162
3204
  }
3163
3205
  const { adapter: kvstore } = this.options.storage;
3164
3206
  const dappClient = yield __privateMethod(this, _MetaMaskConnectMultichain_instances, createDappClient_fn).call(this);
3165
3207
  __privateSet(this, _dappClient, dappClient);
3166
- const apiTransport = new MWPTransport(dappClient, kvstore);
3208
+ const { MWPTransport: MWPTransport2 } = yield Promise.resolve().then(() => (init_mwp(), mwp_exports));
3209
+ const apiTransport = new MWPTransport2(dappClient, kvstore);
3167
3210
  __privateSet(this, _transport2, apiTransport);
3211
+ __privateSet(this, _transportType, "mwp" /* MWP */);
3168
3212
  __privateGet(this, _providerTransportWrapper).setupTransportNotificationListener();
3169
3213
  __privateSet(this, _listener, this.transport.onNotification(
3170
3214
  __privateMethod(this, _MetaMaskConnectMultichain_instances, onTransportNotification_fn).bind(this)
@@ -3223,8 +3267,9 @@ renderInstallModalAsync_fn = function(desktopPreferred, scopes, caipAccountIds,
3223
3267
  this.status = "connected";
3224
3268
  yield this.storage.setTransport("mwp" /* MWP */);
3225
3269
  } catch (error) {
3226
- if (error instanceof import_mobile_wallet_protocol_core2.ProtocolError) {
3227
- if (error.code !== import_mobile_wallet_protocol_core2.ErrorCode.REQUEST_EXPIRED) {
3270
+ const { ProtocolError, ErrorCode } = yield import("@metamask/mobile-wallet-protocol-core");
3271
+ if (error instanceof ProtocolError) {
3272
+ if (error.code !== ErrorCode.REQUEST_EXPIRED) {
3228
3273
  this.status = "disconnected";
3229
3274
  yield this.options.ui.factory.unload(error);
3230
3275
  reject(error);
@@ -3292,7 +3337,8 @@ headlessConnect_fn = function(scopes, caipAccountIds, sessionProperties) {
3292
3337
  yield this.storage.setTransport("mwp" /* MWP */);
3293
3338
  resolve();
3294
3339
  })).catch((error) => __async(this, null, function* () {
3295
- if (error instanceof import_mobile_wallet_protocol_core2.ProtocolError) {
3340
+ const { ProtocolError } = yield import("@metamask/mobile-wallet-protocol-core");
3341
+ if (error instanceof ProtocolError) {
3296
3342
  this.status = "disconnected";
3297
3343
  yield this.storage.removeTransport();
3298
3344
  reject(error);
@@ -3307,7 +3353,7 @@ headlessConnect_fn = function(scopes, caipAccountIds, sessionProperties) {
3307
3353
  };
3308
3354
  setupDefaultTransport_fn = function() {
3309
3355
  return __async(this, arguments, function* (options = { persist: true }) {
3310
- if (__privateGet(this, _transport2) instanceof DefaultTransport) {
3356
+ if (__privateGet(this, _transportType) === "browser" /* Browser */) {
3311
3357
  return __privateGet(this, _transport2);
3312
3358
  }
3313
3359
  if (options == null ? void 0 : options.persist) {
@@ -3318,6 +3364,7 @@ setupDefaultTransport_fn = function() {
3318
3364
  __privateMethod(this, _MetaMaskConnectMultichain_instances, onTransportNotification_fn).bind(this)
3319
3365
  ));
3320
3366
  __privateSet(this, _transport2, transport);
3367
+ __privateSet(this, _transportType, "browser" /* Browser */);
3321
3368
  __privateGet(this, _providerTransportWrapper).setupTransportNotificationListener();
3322
3369
  return transport;
3323
3370
  });