@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_domain = __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_utils();
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 _a2, _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
+ (_a2 = walletSession == null ? void 0 : walletSession.sessionScopes) != null ? _a2 : {}
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 _a2;
1296
+ const timeout = setTimeout(() => {
1297
+ this.rejectRequest(request.id, new TransportTimeoutError());
1298
+ }, (_a2 = options == null ? void 0 : options.timeout) != null ? _a2 : 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 _a2;
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((_a2 = session == null ? void 0 : session.id) != null ? _a2 : "");
1342
+ }
1343
+ });
1344
+ } else {
1345
+ connection = new Promise(
1346
+ (resolveConnection, rejectConnection) => {
1347
+ var _a2, _b;
1348
+ const optionalScopes = addValidAccounts(
1349
+ getOptionalScopes((_a2 = options == null ? void 0 : options.scopes) != null ? _a2 : []),
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 _a2, _b;
1439
+ const cachedSession = yield this.getCachedResponse({
1440
+ jsonrpc: "2.0",
1441
+ id: "0",
1442
+ method: "wallet_getSession"
1443
+ });
1444
+ const cachedSessionScopes = (_b = (_a2 = cachedSession == null ? void 0 : cachedSession.result) == null ? void 0 : _a2.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 _a2;
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: (_a2 = walletSession.params) != null ? _a2 : 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 _a2;
1605
+ const timeout = setTimeout(() => {
1606
+ this.rejectRequest(request.id, new TransportTimeoutError());
1607
+ }, (_a2 = options == null ? void 0 : options.timeout) != null ? _a2 : 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) {
@@ -1285,13 +1987,6 @@ init_domain();
1285
1987
 
1286
1988
  // src/multichain/index.ts
1287
1989
  import { analytics as analytics2 } from "@metamask/analytics";
1288
- import {
1289
- ErrorCode,
1290
- ProtocolError,
1291
- SessionStore as SessionStore2,
1292
- WebSocketTransport
1293
- } from "@metamask/mobile-wallet-protocol-core";
1294
- import { DappClient } from "@metamask/mobile-wallet-protocol-dapp-client";
1295
1990
  import {
1296
1991
  getMultichainClient
1297
1992
  } from "@metamask/multichain-api-client";
@@ -1858,6 +2553,9 @@ var MultichainApiClientWrapperTransport = class {
1858
2553
  return false;
1859
2554
  }
1860
2555
  }
2556
+ isTransportConnected() {
2557
+ return this.isTransportDefined() && this.metamaskConnectMultichain.transport.isConnected();
2558
+ }
1861
2559
  clearNotificationCallbacks() {
1862
2560
  __privateGet(this, _notificationCallbacks2).clear();
1863
2561
  }
@@ -1879,17 +2577,19 @@ var MultichainApiClientWrapperTransport = class {
1879
2577
  this.notifyCallbacks.bind(this)
1880
2578
  );
1881
2579
  }
2580
+ // Purposely noop, resolves successfully. Actual connection is handled by the underlying client/transport.
1882
2581
  connect() {
1883
2582
  return __async(this, null, function* () {
1884
- console.log("\u{1F4DA} connect");
1885
- yield this.metamaskConnectMultichain.emitSessionChanged();
2583
+ return Promise.resolve();
1886
2584
  });
1887
2585
  }
2586
+ // Purposely noop, resolves successfully. Actual connection is handled by the underlying client/transport.
1888
2587
  disconnect() {
1889
2588
  return __async(this, null, function* () {
1890
2589
  return Promise.resolve();
1891
2590
  });
1892
2591
  }
2592
+ // Purposely hardcoded to true. Actual connection is handled by the underlying client/transport.
1893
2593
  isConnected() {
1894
2594
  return true;
1895
2595
  }
@@ -1912,7 +2612,6 @@ var MultichainApiClientWrapperTransport = class {
1912
2612
  default:
1913
2613
  throw new Error(`Unsupported method: ${requestPayload.method}`);
1914
2614
  }
1915
- throw new Error(`Unknown method: ${requestPayload.method}`);
1916
2615
  });
1917
2616
  }
1918
2617
  onNotification(callback) {
@@ -1942,13 +2641,11 @@ walletCreateSession_fn = function(request) {
1942
2641
  }
1943
2642
  });
1944
2643
  const accounts = [...new Set(scopeAccounts)];
1945
- console.log("\u{1F4DA} SDK connect");
1946
2644
  yield this.metamaskConnectMultichain.connect(
1947
2645
  scopes,
1948
2646
  accounts,
1949
2647
  createSessionParams.sessionProperties
1950
2648
  );
1951
- console.log("\u{1F4DA} SDK connected");
1952
2649
  return this.metamaskConnectMultichain.transport.request({
1953
2650
  method: "wallet_getSession"
1954
2651
  });
@@ -1956,7 +2653,7 @@ walletCreateSession_fn = function(request) {
1956
2653
  };
1957
2654
  walletGetSession_fn = function(request) {
1958
2655
  return __async(this, null, function* () {
1959
- if (!this.isTransportDefined()) {
2656
+ if (!this.isTransportConnected()) {
1960
2657
  return {
1961
2658
  jsonrpc: "2.0",
1962
2659
  id: request.id,
@@ -1973,9 +2670,6 @@ walletGetSession_fn = function(request) {
1973
2670
  walletRevokeSession_fn = function(request) {
1974
2671
  return __async(this, null, function* () {
1975
2672
  var _a2;
1976
- if (!this.isTransportDefined()) {
1977
- return { jsonrpc: "2.0", id: request.id, result: true };
1978
- }
1979
2673
  const revokeSessionParams = request.params;
1980
2674
  const scopes = (_a2 = revokeSessionParams == null ? void 0 : revokeSessionParams.scopes) != null ? _a2 : [];
1981
2675
  try {
@@ -1988,7 +2682,7 @@ walletRevokeSession_fn = function(request) {
1988
2682
  };
1989
2683
  walletInvokeMethod_fn = function(request) {
1990
2684
  return __async(this, null, function* () {
1991
- if (!this.isTransportDefined()) {
2685
+ if (!this.isTransportConnected()) {
1992
2686
  return { error: providerErrors.unauthorized() };
1993
2687
  }
1994
2688
  const result = this.metamaskConnectMultichain.invokeMethod(
@@ -2000,686 +2694,11 @@ walletInvokeMethod_fn = function(request) {
2000
2694
  });
2001
2695
  };
2002
2696
 
2003
- // src/multichain/transports/mwp/index.ts
2004
- init_domain();
2005
- init_utils();
2006
- import { SessionStore } from "@metamask/mobile-wallet-protocol-core";
2007
- import {
2008
- TransportTimeoutError
2009
- } from "@metamask/multichain-api-client";
2010
- import { JsonRpcError, providerErrors as providerErrors2, rpcErrors } from "@metamask/rpc-errors";
2011
-
2012
- // src/multichain/transports/constants.ts
2013
- var MULTICHAIN_PROVIDER_STREAM_NAME = "metamask-multichain-provider";
2014
-
2015
- // src/multichain/transports/mwp/index.ts
2016
- var DEFAULT_REQUEST_TIMEOUT2 = 60 * 1e3;
2017
- var CONNECTION_GRACE_PERIOD = 60 * 1e3;
2018
- var DEFAULT_CONNECTION_TIMEOUT = DEFAULT_REQUEST_TIMEOUT2 + CONNECTION_GRACE_PERIOD;
2019
- var DEFAULT_RESUME_TIMEOUT = 10 * 1e3;
2020
- var SESSION_STORE_KEY = "cache_wallet_getSession";
2021
- var ACCOUNTS_STORE_KEY = "cache_eth_accounts";
2022
- var CHAIN_STORE_KEY = "cache_eth_chainId";
2023
- var PENDING_SESSION_REQUEST_KEY = "pending_session_request";
2024
- var CACHED_METHOD_LIST = [
2025
- "wallet_getSession",
2026
- "wallet_createSession",
2027
- "wallet_sessionChanged"
2028
- ];
2029
- var CACHED_RESET_METHOD_LIST = [
2030
- "wallet_revokeSession",
2031
- "wallet_revokePermissions"
2032
- ];
2033
- var logger = createLogger("metamask-sdk:transport");
2034
- var MWPTransport = class {
2035
- constructor(dappClient, kvstore, options = {
2036
- requestTimeout: DEFAULT_REQUEST_TIMEOUT2,
2037
- connectionTimeout: DEFAULT_CONNECTION_TIMEOUT,
2038
- resumeTimeout: DEFAULT_RESUME_TIMEOUT
2039
- }) {
2040
- this.dappClient = dappClient;
2041
- this.kvstore = kvstore;
2042
- this.options = options;
2043
- this.__pendingRequests = /* @__PURE__ */ new Map();
2044
- this.notificationCallbacks = /* @__PURE__ */ new Set();
2045
- this.dappClient.on("message", this.handleMessage.bind(this));
2046
- this.dappClient.on("session_request", (sessionRequest) => {
2047
- this.currentSessionRequest = sessionRequest;
2048
- this.kvstore.set(PENDING_SESSION_REQUEST_KEY, JSON.stringify(sessionRequest)).catch((err) => {
2049
- logger("Failed to store pending session request", err);
2050
- });
2051
- });
2052
- if (typeof window !== "undefined" && typeof window.addEventListener !== "undefined") {
2053
- this.windowFocusHandler = this.onWindowFocus.bind(this);
2054
- window.addEventListener("focus", this.windowFocusHandler);
2055
- }
2056
- }
2057
- get pendingRequests() {
2058
- return this.__pendingRequests;
2059
- }
2060
- set pendingRequests(pendingRequests) {
2061
- this.__pendingRequests = pendingRequests;
2062
- }
2063
- get sessionRequest() {
2064
- return this.currentSessionRequest;
2065
- }
2066
- /**
2067
- * Returns the stored pending session request from the dappClient session_request event, if any.
2068
- *
2069
- * @returns The stored SessionRequest, or null if none or invalid.
2070
- */
2071
- getStoredPendingSessionRequest() {
2072
- return __async(this, null, function* () {
2073
- try {
2074
- const raw = yield this.kvstore.get(PENDING_SESSION_REQUEST_KEY);
2075
- if (!raw) {
2076
- return null;
2077
- }
2078
- return JSON.parse(raw);
2079
- } catch (e) {
2080
- return null;
2081
- }
2082
- });
2083
- }
2084
- /**
2085
- * Removes the stored pending session request from the KVStore.
2086
- * This is necessary to ensure that ConnectMultichain is able to correctly
2087
- * infer the MWP Transport connection attempt status.
2088
- */
2089
- removeStoredPendingSessionRequest() {
2090
- return __async(this, null, function* () {
2091
- yield this.kvstore.delete(PENDING_SESSION_REQUEST_KEY);
2092
- });
2093
- }
2094
- onWindowFocus() {
2095
- if (!this.isConnected()) {
2096
- this.dappClient.reconnect();
2097
- }
2098
- }
2099
- notifyCallbacks(data) {
2100
- this.notificationCallbacks.forEach((callback) => callback(data));
2101
- }
2102
- rejectRequest(id, error = new Error("Request rejected")) {
2103
- const request = this.pendingRequests.get(id);
2104
- if (request) {
2105
- this.pendingRequests.delete(id);
2106
- clearTimeout(request.timeout);
2107
- request.reject(error);
2108
- }
2109
- }
2110
- parseWalletError(errorPayload) {
2111
- const errorData = errorPayload;
2112
- if (typeof errorData.code === "number" && typeof errorData.message === "string") {
2113
- const { code, message: message2 } = errorData;
2114
- if (code >= 1e3 && code <= 4999) {
2115
- return providerErrors2.custom({ code, message: message2 });
2116
- }
2117
- return new JsonRpcError(code, message2);
2118
- }
2119
- const message = errorPayload instanceof Error ? errorPayload.message : JSON.stringify(errorPayload);
2120
- return rpcErrors.internal({ message });
2121
- }
2122
- handleMessage(message) {
2123
- if (typeof message === "object" && message !== null) {
2124
- if ("data" in message) {
2125
- const messagePayload = message.data;
2126
- if ("id" in messagePayload && typeof messagePayload.id === "string") {
2127
- const request = this.pendingRequests.get(messagePayload.id);
2128
- if (request) {
2129
- clearTimeout(request.timeout);
2130
- if ("error" in messagePayload && messagePayload.error) {
2131
- this.pendingRequests.delete(messagePayload.id);
2132
- request.reject(this.parseWalletError(messagePayload.error));
2133
- return;
2134
- }
2135
- const requestWithName = __spreadProps(__spreadValues({}, messagePayload), {
2136
- method: request.method === "wallet_getSession" || request.method === "wallet_createSession" ? "wallet_sessionChanged" : request.method
2137
- });
2138
- const notification = __spreadProps(__spreadValues({}, messagePayload), {
2139
- method: request.method === "wallet_getSession" || request.method === "wallet_createSession" ? "wallet_sessionChanged" : request.method,
2140
- params: requestWithName.result
2141
- });
2142
- this.notifyCallbacks(notification);
2143
- request.resolve(requestWithName);
2144
- this.pendingRequests.delete(messagePayload.id);
2145
- }
2146
- } else {
2147
- if (message.data.method === "metamask_chainChanged") {
2148
- this.kvstore.set(
2149
- CHAIN_STORE_KEY,
2150
- JSON.stringify(
2151
- message.data.params.chainId
2152
- )
2153
- );
2154
- }
2155
- if (message.data.method === "metamask_accountsChanged") {
2156
- this.kvstore.set(
2157
- ACCOUNTS_STORE_KEY,
2158
- JSON.stringify(
2159
- message.data.params
2160
- )
2161
- );
2162
- }
2163
- if (message.data.method === "wallet_sessionChanged") {
2164
- const notification = message.data;
2165
- const response = {
2166
- result: notification.params
2167
- };
2168
- this.kvstore.set(SESSION_STORE_KEY, JSON.stringify(response));
2169
- }
2170
- this.notifyCallbacks(message.data);
2171
- }
2172
- }
2173
- }
2174
- }
2175
- onResumeSuccess(resumeResolve, resumeReject, options) {
2176
- return __async(this, null, function* () {
2177
- var _a2, _b, _c, _d, _e, _f, _g;
2178
- try {
2179
- yield this.waitForWalletSessionIfNotCached();
2180
- const sessionRequest = yield this.request({
2181
- method: "wallet_getSession"
2182
- });
2183
- if (sessionRequest.error) {
2184
- return resumeReject(new Error(sessionRequest.error.message));
2185
- }
2186
- let walletSession = sessionRequest.result;
2187
- if (walletSession && options) {
2188
- const currentScopes = Object.keys(
2189
- (_a2 = walletSession == null ? void 0 : walletSession.sessionScopes) != null ? _a2 : {}
2190
- );
2191
- const proposedScopes = (_b = options == null ? void 0 : options.scopes) != null ? _b : [];
2192
- const proposedCaipAccountIds = (_c = options == null ? void 0 : options.caipAccountIds) != null ? _c : [];
2193
- const hasSameScopesAndAccounts = isSameScopesAndAccounts(
2194
- currentScopes,
2195
- proposedScopes,
2196
- walletSession,
2197
- proposedCaipAccountIds
2198
- );
2199
- if (options.forceRequest || !hasSameScopesAndAccounts) {
2200
- const optionalScopes = addValidAccounts(
2201
- getOptionalScopes((_d = options == null ? void 0 : options.scopes) != null ? _d : []),
2202
- getValidAccounts((_e = options == null ? void 0 : options.caipAccountIds) != null ? _e : [])
2203
- );
2204
- const sessionRequest2 = {
2205
- optionalScopes
2206
- };
2207
- const response = yield this.request({
2208
- method: "wallet_createSession",
2209
- params: sessionRequest2
2210
- });
2211
- if (response.error) {
2212
- return resumeReject(new Error(response.error.message));
2213
- }
2214
- walletSession = response.result;
2215
- }
2216
- } else if (!walletSession) {
2217
- const optionalScopes = addValidAccounts(
2218
- getOptionalScopes((_f = options == null ? void 0 : options.scopes) != null ? _f : []),
2219
- getValidAccounts((_g = options == null ? void 0 : options.caipAccountIds) != null ? _g : [])
2220
- );
2221
- const sessionRequest2 = { optionalScopes };
2222
- const response = yield this.request({
2223
- method: "wallet_createSession",
2224
- params: sessionRequest2
2225
- });
2226
- if (response.error) {
2227
- return resumeReject(new Error(response.error.message));
2228
- }
2229
- walletSession = response.result;
2230
- }
2231
- yield this.removeStoredPendingSessionRequest();
2232
- this.notifyCallbacks({
2233
- method: "wallet_sessionChanged",
2234
- params: walletSession
2235
- });
2236
- return resumeResolve();
2237
- } catch (err) {
2238
- return resumeReject(err);
2239
- }
2240
- });
2241
- }
2242
- init() {
2243
- return __async(this, null, function* () {
2244
- });
2245
- }
2246
- // TODO: Rename this
2247
- sendEip1193Message(payload, options) {
2248
- return __async(this, null, function* () {
2249
- const request = __spreadValues({
2250
- jsonrpc: "2.0",
2251
- id: String(getUniqueRequestId())
2252
- }, payload);
2253
- const cachedWalletSession = yield this.getCachedResponse(request);
2254
- if (cachedWalletSession) {
2255
- this.notifyCallbacks(cachedWalletSession);
2256
- return cachedWalletSession;
2257
- }
2258
- return new Promise((resolve, reject) => {
2259
- var _a2;
2260
- const timeout = setTimeout(() => {
2261
- this.rejectRequest(request.id, new TransportTimeoutError());
2262
- }, (_a2 = options == null ? void 0 : options.timeout) != null ? _a2 : this.options.requestTimeout);
2263
- this.pendingRequests.set(request.id, {
2264
- request,
2265
- method: request.method,
2266
- resolve: (response) => __async(this, null, function* () {
2267
- yield this.storeWalletSession(request, response);
2268
- return resolve(response);
2269
- }),
2270
- reject,
2271
- timeout
2272
- });
2273
- this.dappClient.sendRequest({
2274
- name: "metamask-provider",
2275
- data: request
2276
- }).catch(reject);
2277
- });
2278
- });
2279
- }
2280
- connect(options) {
2281
- return __async(this, null, function* () {
2282
- const { dappClient } = this;
2283
- const session = yield this.getActiveSession();
2284
- if (session) {
2285
- logger("active session found", {
2286
- id: session.id,
2287
- channel: session.channel,
2288
- expiresAt: session.expiresAt
2289
- });
2290
- }
2291
- const storedSessionRequestBeforeConnectionAttempt = yield this.getStoredPendingSessionRequest();
2292
- let timeout;
2293
- let initialConnectionMessageHandler;
2294
- const connectionPromise = new Promise((resolve, reject) => __async(this, null, function* () {
2295
- let connection;
2296
- if (session) {
2297
- connection = new Promise((resumeResolve, resumeReject) => {
2298
- var _a2;
2299
- if (this.dappClient.state === "CONNECTED") {
2300
- this.onResumeSuccess(resumeResolve, resumeReject, options);
2301
- } else {
2302
- this.dappClient.once("connected", () => __async(this, null, function* () {
2303
- this.onResumeSuccess(resumeResolve, resumeReject, options);
2304
- }));
2305
- dappClient.resume((_a2 = session == null ? void 0 : session.id) != null ? _a2 : "");
2306
- }
2307
- });
2308
- } else {
2309
- connection = new Promise(
2310
- (resolveConnection, rejectConnection) => {
2311
- var _a2, _b;
2312
- const optionalScopes = addValidAccounts(
2313
- getOptionalScopes((_a2 = options == null ? void 0 : options.scopes) != null ? _a2 : []),
2314
- getValidAccounts((_b = options == null ? void 0 : options.caipAccountIds) != null ? _b : [])
2315
- );
2316
- const sessionRequest = {
2317
- optionalScopes,
2318
- sessionProperties: options == null ? void 0 : options.sessionProperties
2319
- };
2320
- const request = {
2321
- jsonrpc: "2.0",
2322
- id: String(getUniqueRequestId()),
2323
- method: "wallet_createSession",
2324
- params: sessionRequest
2325
- };
2326
- initialConnectionMessageHandler = (message) => __async(this, null, function* () {
2327
- if (typeof message !== "object" || message === null) {
2328
- return;
2329
- }
2330
- if (!("data" in message)) {
2331
- return;
2332
- }
2333
- const messagePayload = message.data;
2334
- const isMatchingId = messagePayload.id === request.id;
2335
- const isMatchingMethod = messagePayload.method === "wallet_createSession" || messagePayload.method === "wallet_sessionChanged";
2336
- if (!isMatchingId && !isMatchingMethod) {
2337
- return;
2338
- }
2339
- if (messagePayload.error) {
2340
- return rejectConnection(
2341
- this.parseWalletError(messagePayload.error)
2342
- );
2343
- }
2344
- yield this.storeWalletSession(
2345
- request,
2346
- messagePayload
2347
- );
2348
- yield this.removeStoredPendingSessionRequest();
2349
- this.notifyCallbacks(messagePayload);
2350
- return resolveConnection();
2351
- });
2352
- this.dappClient.on("message", initialConnectionMessageHandler);
2353
- dappClient.connect({
2354
- mode: "trusted",
2355
- initialPayload: {
2356
- name: MULTICHAIN_PROVIDER_STREAM_NAME,
2357
- data: request
2358
- }
2359
- }).catch((error) => {
2360
- if (initialConnectionMessageHandler) {
2361
- this.dappClient.off(
2362
- "message",
2363
- initialConnectionMessageHandler
2364
- );
2365
- }
2366
- rejectConnection(error);
2367
- });
2368
- }
2369
- );
2370
- }
2371
- timeout = setTimeout(
2372
- () => {
2373
- reject(new TransportTimeoutError());
2374
- },
2375
- storedSessionRequestBeforeConnectionAttempt ? this.options.resumeTimeout : this.options.connectionTimeout
2376
- );
2377
- connection.then(resolve).catch(reject);
2378
- }));
2379
- return connectionPromise.catch((error) => __async(this, null, function* () {
2380
- yield this.dappClient.disconnect();
2381
- throw error;
2382
- })).finally(() => {
2383
- if (timeout) {
2384
- clearTimeout(timeout);
2385
- }
2386
- if (initialConnectionMessageHandler) {
2387
- this.dappClient.off("message", initialConnectionMessageHandler);
2388
- initialConnectionMessageHandler = void 0;
2389
- }
2390
- this.removeStoredPendingSessionRequest();
2391
- });
2392
- });
2393
- }
2394
- /**
2395
- * Disconnects from the Mobile Wallet Protocol
2396
- *
2397
- * @param [scopes] - The scopes to revoke. If not provided or empty, all scopes will be revoked.
2398
- * @returns Nothing
2399
- */
2400
- disconnect() {
2401
- return __async(this, arguments, function* (scopes = []) {
2402
- var _a2, _b;
2403
- const cachedSession = yield this.getCachedResponse({
2404
- jsonrpc: "2.0",
2405
- id: "0",
2406
- method: "wallet_getSession"
2407
- });
2408
- const cachedSessionScopes = (_b = (_a2 = cachedSession == null ? void 0 : cachedSession.result) == null ? void 0 : _a2.sessionScopes) != null ? _b : {};
2409
- const remainingScopes = scopes.length === 0 ? [] : Object.keys(cachedSessionScopes).filter(
2410
- (scope) => !scopes.includes(scope)
2411
- );
2412
- const newSessionScopes = Object.fromEntries(
2413
- Object.entries(cachedSessionScopes).filter(
2414
- ([key]) => remainingScopes.includes(key)
2415
- )
2416
- );
2417
- this.request({ method: "wallet_revokeSession", params: { scopes } }).catch(
2418
- (err) => {
2419
- console.error("error revoking session", err);
2420
- }
2421
- );
2422
- const remainingScopesIncludeEip155 = remainingScopes.some(
2423
- (scope) => scope.includes("eip155")
2424
- );
2425
- if (!remainingScopesIncludeEip155) {
2426
- this.kvstore.delete(ACCOUNTS_STORE_KEY);
2427
- this.kvstore.delete(CHAIN_STORE_KEY);
2428
- }
2429
- if (remainingScopes.length > 0) {
2430
- this.kvstore.set(
2431
- SESSION_STORE_KEY,
2432
- JSON.stringify({
2433
- result: {
2434
- sessionScopes: newSessionScopes
2435
- }
2436
- })
2437
- );
2438
- } else {
2439
- this.kvstore.delete(SESSION_STORE_KEY);
2440
- if (typeof window !== "undefined" && typeof window.removeEventListener !== "undefined" && this.windowFocusHandler) {
2441
- window.removeEventListener("focus", this.windowFocusHandler);
2442
- this.windowFocusHandler = void 0;
2443
- }
2444
- yield this.dappClient.disconnect();
2445
- }
2446
- this.notifyCallbacks({
2447
- method: "wallet_sessionChanged",
2448
- params: {
2449
- sessionScopes: newSessionScopes
2450
- }
2451
- });
2452
- });
2453
- }
2454
- /**
2455
- * Checks if the transport is connected
2456
- *
2457
- * @returns True if transport is connected, false otherwise
2458
- */
2459
- isConnected() {
2460
- return this.dappClient.state === "CONNECTED";
2461
- }
2462
- /**
2463
- * Attempts to re-establish a connection via DappClient
2464
- *
2465
- * @returns Nothing
2466
- */
2467
- // TODO: We should re-evaluate adding this to the WebSocketTransport layer from `@metamask/mobile-wallet-protocol-core`
2468
- // ticket: https://consensyssoftware.atlassian.net/browse/WAPI-862
2469
- attemptResumeSession() {
2470
- return __async(this, null, function* () {
2471
- try {
2472
- yield this.dappClient.reconnect();
2473
- yield new Promise((resolve, reject) => {
2474
- const timeout = setTimeout(() => {
2475
- reject(new Error("Resume timeout"));
2476
- }, 2e3);
2477
- if (this.isConnected()) {
2478
- clearTimeout(timeout);
2479
- resolve();
2480
- } else {
2481
- this.dappClient.once("connected", () => {
2482
- clearTimeout(timeout);
2483
- resolve();
2484
- });
2485
- }
2486
- });
2487
- } catch (error) {
2488
- return Promise.reject(
2489
- new Error(`Failed to resume session: ${error.message}`)
2490
- );
2491
- }
2492
- });
2493
- }
2494
- getCachedResponse(request) {
2495
- return __async(this, null, function* () {
2496
- var _a2;
2497
- if (request.method === "wallet_getSession") {
2498
- const walletGetSession = yield this.kvstore.get(SESSION_STORE_KEY);
2499
- if (walletGetSession) {
2500
- const walletSession = JSON.parse(walletGetSession);
2501
- return {
2502
- id: request.id,
2503
- jsonrpc: "2.0",
2504
- result: (_a2 = walletSession.params) != null ? _a2 : walletSession.result,
2505
- // "what?... why walletSession.params?.."
2506
- method: request.method
2507
- };
2508
- }
2509
- } else if (request.method === "eth_accounts") {
2510
- const ethAccounts = yield this.kvstore.get(ACCOUNTS_STORE_KEY);
2511
- if (ethAccounts) {
2512
- return {
2513
- id: request.id,
2514
- jsonrpc: "2.0",
2515
- result: JSON.parse(ethAccounts),
2516
- method: request.method
2517
- };
2518
- }
2519
- } else if (request.method === "eth_chainId") {
2520
- const ethChainId = yield this.kvstore.get(CHAIN_STORE_KEY);
2521
- if (ethChainId) {
2522
- return {
2523
- id: request.id,
2524
- jsonrpc: "2.0",
2525
- result: JSON.parse(ethChainId),
2526
- method: request.method
2527
- };
2528
- }
2529
- }
2530
- });
2531
- }
2532
- storeWalletSession(request, response) {
2533
- return __async(this, null, function* () {
2534
- if (response.error) {
2535
- return;
2536
- }
2537
- if (CACHED_METHOD_LIST.includes(request.method)) {
2538
- yield this.kvstore.set(SESSION_STORE_KEY, JSON.stringify(response));
2539
- } else if (request.method === "eth_accounts") {
2540
- yield this.kvstore.set(
2541
- ACCOUNTS_STORE_KEY,
2542
- JSON.stringify(response.result)
2543
- );
2544
- } else if (request.method === "eth_chainId") {
2545
- yield this.kvstore.set(CHAIN_STORE_KEY, JSON.stringify(response.result));
2546
- } else if (CACHED_RESET_METHOD_LIST.includes(request.method)) {
2547
- yield this.kvstore.delete(SESSION_STORE_KEY);
2548
- yield this.kvstore.delete(ACCOUNTS_STORE_KEY);
2549
- yield this.kvstore.delete(CHAIN_STORE_KEY);
2550
- }
2551
- });
2552
- }
2553
- request(payload, options) {
2554
- return __async(this, null, function* () {
2555
- const request = __spreadValues({
2556
- jsonrpc: "2.0",
2557
- id: String(getUniqueRequestId())
2558
- }, payload);
2559
- const cachedWalletSession = yield this.getCachedResponse(request);
2560
- if (cachedWalletSession) {
2561
- this.notifyCallbacks(cachedWalletSession);
2562
- return cachedWalletSession;
2563
- }
2564
- if (!this.isConnected()) {
2565
- yield this.attemptResumeSession();
2566
- }
2567
- return new Promise((resolve, reject) => {
2568
- var _a2;
2569
- const timeout = setTimeout(() => {
2570
- this.rejectRequest(request.id, new TransportTimeoutError());
2571
- }, (_a2 = options == null ? void 0 : options.timeout) != null ? _a2 : this.options.requestTimeout);
2572
- this.pendingRequests.set(request.id, {
2573
- request,
2574
- method: request.method,
2575
- resolve: (response) => __async(this, null, function* () {
2576
- yield this.storeWalletSession(request, response);
2577
- return resolve(response);
2578
- }),
2579
- reject,
2580
- timeout
2581
- });
2582
- this.dappClient.sendRequest({
2583
- name: MULTICHAIN_PROVIDER_STREAM_NAME,
2584
- data: request
2585
- }).catch(reject);
2586
- });
2587
- });
2588
- }
2589
- onNotification(callback) {
2590
- this.notificationCallbacks.add(callback);
2591
- return () => {
2592
- this.notificationCallbacks.delete(callback);
2593
- };
2594
- }
2595
- getActiveSession() {
2596
- return __async(this, null, function* () {
2597
- const { kvstore } = this;
2598
- const sessionStore = yield SessionStore.create(kvstore);
2599
- try {
2600
- const [activeSession] = yield sessionStore.list();
2601
- return activeSession;
2602
- } catch (error) {
2603
- logger("error getting active session", error);
2604
- return void 0;
2605
- }
2606
- });
2607
- }
2608
- // This method checks if an existing CAIP session response is cached or waits for one
2609
- // to be received from the wallet if not cached. This is necessary because there is an edge
2610
- // case during the initial connection flow where after the user has accepted the permission approval
2611
- // and returned back to the dapp from the wallet, the dapp page may have gotten unloaded and refreshed.
2612
- // When it is unloaded and refreshed, it will try to resume the session by making a request for wallet_getSession
2613
- // which should resolve from cache, but because a race condition makes it possible for the response from the wallet
2614
- // for the initial wallet_createSession connection request to not have been handled and cached yet. This results
2615
- // in the wallet_getSession request never resolving unless we wait for it explicitly as done in this method.
2616
- waitForWalletSessionIfNotCached() {
2617
- return __async(this, null, function* () {
2618
- const cachedWalletGetSessionResponse = yield this.kvstore.get(SESSION_STORE_KEY);
2619
- if (cachedWalletGetSessionResponse) {
2620
- return;
2621
- }
2622
- let unsubscribe;
2623
- const responsePromise = new Promise((resolve) => {
2624
- unsubscribe = this.onNotification((message) => {
2625
- if (typeof message === "object" && message !== null) {
2626
- if ("data" in message) {
2627
- const messagePayload = message.data;
2628
- if (messagePayload.method === "wallet_getSession" || messagePayload.method === "wallet_sessionChanged") {
2629
- unsubscribe();
2630
- resolve();
2631
- }
2632
- }
2633
- }
2634
- });
2635
- });
2636
- const timeoutPromise = new Promise((_resolve, reject) => {
2637
- setTimeout(() => {
2638
- unsubscribe();
2639
- this.removeStoredPendingSessionRequest();
2640
- reject(new TransportTimeoutError());
2641
- }, this.options.resumeTimeout);
2642
- });
2643
- return Promise.race([responsePromise, timeoutPromise]);
2644
- });
2645
- }
2646
- };
2647
-
2648
- // src/multichain/transports/mwp/KeyManager.ts
2649
- import { decrypt, encrypt, PrivateKey, PublicKey } from "eciesjs";
2650
- var KeyManager = class {
2651
- generateKeyPair() {
2652
- const privateKey = new PrivateKey();
2653
- return {
2654
- privateKey: new Uint8Array(privateKey.secret),
2655
- publicKey: privateKey.publicKey.toBytes(true)
2656
- };
2657
- }
2658
- encrypt(plaintext, theirPublicKey) {
2659
- return __async(this, null, function* () {
2660
- const plaintextBuffer = Buffer.from(plaintext, "utf8");
2661
- const encryptedBuffer = encrypt(theirPublicKey, plaintextBuffer);
2662
- return encryptedBuffer.toString("base64");
2663
- });
2664
- }
2665
- decrypt(encryptedB64, myPrivateKey) {
2666
- return __async(this, null, function* () {
2667
- const encryptedBuffer = Buffer.from(encryptedB64, "base64");
2668
- const decryptedBuffer = yield decrypt(myPrivateKey, encryptedBuffer);
2669
- return Buffer.from(decryptedBuffer).toString("utf8");
2670
- });
2671
- }
2672
- validatePeerKey(key) {
2673
- PublicKey.fromHex(Buffer.from(key).toString("hex"));
2674
- }
2675
- };
2676
- var keymanager = new KeyManager();
2677
-
2678
2697
  // src/multichain/index.ts
2679
2698
  init_utils();
2680
2699
  var logger2 = createLogger("metamask-sdk:core");
2681
2700
  var SINGLETON_KEY = "__METAMASK_CONNECT_MULTICHAIN_SINGLETON__";
2682
- 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;
2701
+ 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;
2683
2702
  var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends MultichainCore {
2684
2703
  constructor(options) {
2685
2704
  var _a2, _b, _c, _d, _e, _f;
@@ -2697,7 +2716,7 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
2697
2716
  versions: __spreadValues({
2698
2717
  // typeof guard needed: Metro (React Native) bundles TS source directly,
2699
2718
  // bypassing the tsup build that substitutes __PACKAGE_VERSION__.
2700
- "connect-multichain": false ? "unknown" : "0.12.1"
2719
+ "connect-multichain": false ? "unknown" : "0.13.0"
2701
2720
  }, (_f = options.versions) != null ? _f : {})
2702
2721
  });
2703
2722
  super(allOptions);
@@ -2707,6 +2726,7 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
2707
2726
  __privateAdd(this, _transport2);
2708
2727
  __privateAdd(this, _dappClient);
2709
2728
  __privateAdd(this, _beforeUnloadListener);
2729
+ __privateAdd(this, _transportType);
2710
2730
  this._status = "pending";
2711
2731
  __privateAdd(this, _listener);
2712
2732
  __privateAdd(this, _anonId);
@@ -2743,12 +2763,13 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
2743
2763
  }
2744
2764
  return __privateGet(this, _dappClient);
2745
2765
  }
2766
+ get transportType() {
2767
+ var _a2;
2768
+ return (_a2 = __privateGet(this, _transportType)) != null ? _a2 : "unknown" /* UNKNOWN */;
2769
+ }
2746
2770
  get storage() {
2747
2771
  return this.options.storage;
2748
2772
  }
2749
- get transportType() {
2750
- return __privateGet(this, _transport2) instanceof MWPTransport ? "mwp" /* MWP */ : "browser" /* Browser */;
2751
- }
2752
2773
  // Creates a singleton instance of MetaMaskConnectMultichain.
2753
2774
  // If the singleton already exists, it merges the incoming options with the
2754
2775
  // existing singleton options for the following keys: `api.supportedNetworks`,
@@ -2802,7 +2823,7 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
2802
2823
  connect(scopes, caipAccountIds, sessionProperties, forceRequest) {
2803
2824
  return __async(this, null, function* () {
2804
2825
  var _a2;
2805
- if (this.status === "connecting" && this.transportType === "mwp" /* MWP */) {
2826
+ if (this.status === "connecting" && __privateGet(this, _transportType) === "mwp" /* MWP */) {
2806
2827
  yield __privateMethod(this, _MetaMaskConnectMultichain_instances, openConnectDeeplinkIfNeeded_fn).call(this);
2807
2828
  throw new Error(
2808
2829
  "Existing connection is pending. Please check your MetaMask Mobile app to continue."
@@ -2851,7 +2872,7 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
2851
2872
  sessionProperties: nonEmptySessionProperties,
2852
2873
  forceRequest
2853
2874
  }).then(() => __async(this, null, function* () {
2854
- if (__privateGet(this, _transport2) instanceof MWPTransport) {
2875
+ if (__privateGet(this, _transportType) === "mwp" /* MWP */) {
2855
2876
  return this.storage.setTransport("mwp" /* MWP */);
2856
2877
  }
2857
2878
  return this.storage.setTransport("browser" /* Browser */);
@@ -2898,12 +2919,13 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
2898
2919
  yield (_a2 = __privateGet(this, _transport2)) == null ? void 0 : _a2.disconnect(scopes);
2899
2920
  if (remainingScopes.length === 0) {
2900
2921
  yield this.storage.removeTransport();
2901
- if (this.transportType !== "browser" /* Browser */) {
2922
+ if (__privateGet(this, _transportType) !== "browser" /* Browser */) {
2902
2923
  yield (_b = __privateGet(this, _listener)) == null ? void 0 : _b.call(this);
2903
2924
  (_c = __privateGet(this, _beforeUnloadListener)) == null ? void 0 : _c.call(this);
2904
2925
  __privateSet(this, _listener, void 0);
2905
2926
  __privateSet(this, _beforeUnloadListener, void 0);
2906
2927
  __privateSet(this, _transport2, void 0);
2928
+ __privateSet(this, _transportType, void 0);
2907
2929
  __privateGet(this, _providerTransportWrapper).clearTransportNotificationListener();
2908
2930
  __privateSet(this, _dappClient, void 0);
2909
2931
  }
@@ -2913,13 +2935,14 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
2913
2935
  }
2914
2936
  invokeMethod(request) {
2915
2937
  return __async(this, null, function* () {
2938
+ var _a2;
2916
2939
  const { transport, options } = this;
2917
2940
  const rpcClient = new RpcClient(options, __privateGet(this, _sdkInfo));
2918
2941
  const requestRouter = new RequestRouter(
2919
2942
  transport,
2920
2943
  rpcClient,
2921
2944
  options,
2922
- this.transportType
2945
+ (_a2 = __privateGet(this, _transportType)) != null ? _a2 : "unknown" /* UNKNOWN */
2923
2946
  );
2924
2947
  return requestRouter.invokeMethod(request);
2925
2948
  });
@@ -2968,6 +2991,7 @@ _providerTransportWrapper = new WeakMap();
2968
2991
  _transport2 = new WeakMap();
2969
2992
  _dappClient = new WeakMap();
2970
2993
  _beforeUnloadListener = new WeakMap();
2994
+ _transportType = new WeakMap();
2971
2995
  _listener = new WeakMap();
2972
2996
  _anonId = new WeakMap();
2973
2997
  _sdkInfo = new WeakMap();
@@ -3025,6 +3049,7 @@ getStoredTransport_fn = function() {
3025
3049
  if (hasExtensionInstalled) {
3026
3050
  const apiTransport = new DefaultTransport();
3027
3051
  __privateSet(this, _transport2, apiTransport);
3052
+ __privateSet(this, _transportType, "browser" /* Browser */);
3028
3053
  __privateGet(this, _providerTransportWrapper).setupTransportNotificationListener();
3029
3054
  __privateSet(this, _listener, apiTransport.onNotification(
3030
3055
  __privateMethod(this, _MetaMaskConnectMultichain_instances, onTransportNotification_fn).bind(this)
@@ -3034,9 +3059,11 @@ getStoredTransport_fn = function() {
3034
3059
  } else if (transportType === "mwp" /* MWP */) {
3035
3060
  const { adapter: kvstore } = this.options.storage;
3036
3061
  const dappClient = yield __privateMethod(this, _MetaMaskConnectMultichain_instances, createDappClient_fn).call(this);
3037
- const apiTransport = new MWPTransport(dappClient, kvstore);
3062
+ const { MWPTransport: MWPTransport2 } = yield Promise.resolve().then(() => (init_mwp(), mwp_exports));
3063
+ const apiTransport = new MWPTransport2(dappClient, kvstore);
3038
3064
  __privateSet(this, _dappClient, dappClient);
3039
3065
  __privateSet(this, _transport2, apiTransport);
3066
+ __privateSet(this, _transportType, "mwp" /* MWP */);
3040
3067
  __privateGet(this, _providerTransportWrapper).setupTransportNotificationListener();
3041
3068
  __privateSet(this, _listener, apiTransport.onNotification(
3042
3069
  __privateMethod(this, _MetaMaskConnectMultichain_instances, onTransportNotification_fn).bind(this)
@@ -3058,7 +3085,7 @@ setupTransport_fn = function() {
3058
3085
  yield this.transport.connect();
3059
3086
  }
3060
3087
  this.status = "connected";
3061
- if (this.transport instanceof MWPTransport) {
3088
+ if (__privateGet(this, _transportType) === "mwp" /* MWP */) {
3062
3089
  yield this.storage.setTransport("mwp" /* MWP */);
3063
3090
  } else {
3064
3091
  yield this.storage.setTransport("browser" /* Browser */);
@@ -3102,31 +3129,43 @@ init_fn2 = function() {
3102
3129
  };
3103
3130
  createDappClient_fn = function() {
3104
3131
  return __async(this, null, function* () {
3132
+ const [mwpCore, { DappClient: DappClientClass }, { createKeyManager: createKeyManager2 }] = yield Promise.all([
3133
+ import("@metamask/mobile-wallet-protocol-core"),
3134
+ import("@metamask/mobile-wallet-protocol-dapp-client"),
3135
+ Promise.resolve().then(() => (init_KeyManager(), KeyManager_exports))
3136
+ ]);
3137
+ const keymanager = yield createKeyManager2();
3105
3138
  const { adapter: kvstore } = this.options.storage;
3106
- const sessionstore = yield SessionStore2.create(kvstore);
3139
+ const sessionstore = yield mwpCore.SessionStore.create(kvstore);
3107
3140
  const websocket = (
3108
3141
  // eslint-disable-next-line no-negated-condition
3109
3142
  typeof window !== "undefined" ? WebSocket : (yield import("ws")).WebSocket
3110
3143
  );
3111
- const transport = yield WebSocketTransport.create({
3144
+ const transport = yield mwpCore.WebSocketTransport.create({
3112
3145
  url: MWP_RELAY_URL,
3113
3146
  kvstore,
3114
3147
  websocket
3115
3148
  });
3116
- const dappClient = new DappClient({ transport, sessionstore, keymanager });
3149
+ const dappClient = new DappClientClass({
3150
+ transport,
3151
+ sessionstore,
3152
+ keymanager
3153
+ });
3117
3154
  return dappClient;
3118
3155
  });
3119
3156
  };
3120
3157
  setupMWP_fn = function() {
3121
3158
  return __async(this, null, function* () {
3122
- if (__privateGet(this, _transport2) instanceof MWPTransport) {
3159
+ if (__privateGet(this, _transportType) === "mwp" /* MWP */) {
3123
3160
  return;
3124
3161
  }
3125
3162
  const { adapter: kvstore } = this.options.storage;
3126
3163
  const dappClient = yield __privateMethod(this, _MetaMaskConnectMultichain_instances, createDappClient_fn).call(this);
3127
3164
  __privateSet(this, _dappClient, dappClient);
3128
- const apiTransport = new MWPTransport(dappClient, kvstore);
3165
+ const { MWPTransport: MWPTransport2 } = yield Promise.resolve().then(() => (init_mwp(), mwp_exports));
3166
+ const apiTransport = new MWPTransport2(dappClient, kvstore);
3129
3167
  __privateSet(this, _transport2, apiTransport);
3168
+ __privateSet(this, _transportType, "mwp" /* MWP */);
3130
3169
  __privateGet(this, _providerTransportWrapper).setupTransportNotificationListener();
3131
3170
  __privateSet(this, _listener, this.transport.onNotification(
3132
3171
  __privateMethod(this, _MetaMaskConnectMultichain_instances, onTransportNotification_fn).bind(this)
@@ -3185,6 +3224,7 @@ renderInstallModalAsync_fn = function(desktopPreferred, scopes, caipAccountIds,
3185
3224
  this.status = "connected";
3186
3225
  yield this.storage.setTransport("mwp" /* MWP */);
3187
3226
  } catch (error) {
3227
+ const { ProtocolError, ErrorCode } = yield import("@metamask/mobile-wallet-protocol-core");
3188
3228
  if (error instanceof ProtocolError) {
3189
3229
  if (error.code !== ErrorCode.REQUEST_EXPIRED) {
3190
3230
  this.status = "disconnected";
@@ -3254,6 +3294,7 @@ headlessConnect_fn = function(scopes, caipAccountIds, sessionProperties) {
3254
3294
  yield this.storage.setTransport("mwp" /* MWP */);
3255
3295
  resolve();
3256
3296
  })).catch((error) => __async(this, null, function* () {
3297
+ const { ProtocolError } = yield import("@metamask/mobile-wallet-protocol-core");
3257
3298
  if (error instanceof ProtocolError) {
3258
3299
  this.status = "disconnected";
3259
3300
  yield this.storage.removeTransport();
@@ -3269,7 +3310,7 @@ headlessConnect_fn = function(scopes, caipAccountIds, sessionProperties) {
3269
3310
  };
3270
3311
  setupDefaultTransport_fn = function() {
3271
3312
  return __async(this, arguments, function* (options = { persist: true }) {
3272
- if (__privateGet(this, _transport2) instanceof DefaultTransport) {
3313
+ if (__privateGet(this, _transportType) === "browser" /* Browser */) {
3273
3314
  return __privateGet(this, _transport2);
3274
3315
  }
3275
3316
  if (options == null ? void 0 : options.persist) {
@@ -3280,6 +3321,7 @@ setupDefaultTransport_fn = function() {
3280
3321
  __privateMethod(this, _MetaMaskConnectMultichain_instances, onTransportNotification_fn).bind(this)
3281
3322
  ));
3282
3323
  __privateSet(this, _transport2, transport);
3324
+ __privateSet(this, _transportType, "browser" /* Browser */);
3283
3325
  __privateGet(this, _providerTransportWrapper).setupTransportNotificationListener();
3284
3326
  return transport;
3285
3327
  });