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