@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) {
@@ -1255,13 +1957,6 @@ init_domain();
1255
1957
 
1256
1958
  // src/multichain/index.ts
1257
1959
  import { analytics as analytics2 } from "@metamask/analytics";
1258
- import {
1259
- ErrorCode,
1260
- ProtocolError,
1261
- SessionStore as SessionStore2,
1262
- WebSocketTransport
1263
- } from "@metamask/mobile-wallet-protocol-core";
1264
- import { DappClient } from "@metamask/mobile-wallet-protocol-dapp-client";
1265
1960
  import {
1266
1961
  getMultichainClient
1267
1962
  } from "@metamask/multichain-api-client";
@@ -1828,6 +2523,9 @@ var MultichainApiClientWrapperTransport = class {
1828
2523
  return false;
1829
2524
  }
1830
2525
  }
2526
+ isTransportConnected() {
2527
+ return this.isTransportDefined() && this.metamaskConnectMultichain.transport.isConnected();
2528
+ }
1831
2529
  clearNotificationCallbacks() {
1832
2530
  __privateGet(this, _notificationCallbacks2).clear();
1833
2531
  }
@@ -1849,17 +2547,19 @@ var MultichainApiClientWrapperTransport = class {
1849
2547
  this.notifyCallbacks.bind(this)
1850
2548
  );
1851
2549
  }
2550
+ // Purposely noop, resolves successfully. Actual connection is handled by the underlying client/transport.
1852
2551
  connect() {
1853
2552
  return __async(this, null, function* () {
1854
- console.log("\u{1F4DA} connect");
1855
- yield this.metamaskConnectMultichain.emitSessionChanged();
2553
+ return Promise.resolve();
1856
2554
  });
1857
2555
  }
2556
+ // Purposely noop, resolves successfully. Actual connection is handled by the underlying client/transport.
1858
2557
  disconnect() {
1859
2558
  return __async(this, null, function* () {
1860
2559
  return Promise.resolve();
1861
2560
  });
1862
2561
  }
2562
+ // Purposely hardcoded to true. Actual connection is handled by the underlying client/transport.
1863
2563
  isConnected() {
1864
2564
  return true;
1865
2565
  }
@@ -1882,7 +2582,6 @@ var MultichainApiClientWrapperTransport = class {
1882
2582
  default:
1883
2583
  throw new Error(`Unsupported method: ${requestPayload.method}`);
1884
2584
  }
1885
- throw new Error(`Unknown method: ${requestPayload.method}`);
1886
2585
  });
1887
2586
  }
1888
2587
  onNotification(callback) {
@@ -1912,13 +2611,11 @@ walletCreateSession_fn = function(request) {
1912
2611
  }
1913
2612
  });
1914
2613
  const accounts = [...new Set(scopeAccounts)];
1915
- console.log("\u{1F4DA} SDK connect");
1916
2614
  yield this.metamaskConnectMultichain.connect(
1917
2615
  scopes,
1918
2616
  accounts,
1919
2617
  createSessionParams.sessionProperties
1920
2618
  );
1921
- console.log("\u{1F4DA} SDK connected");
1922
2619
  return this.metamaskConnectMultichain.transport.request({
1923
2620
  method: "wallet_getSession"
1924
2621
  });
@@ -1926,7 +2623,7 @@ walletCreateSession_fn = function(request) {
1926
2623
  };
1927
2624
  walletGetSession_fn = function(request) {
1928
2625
  return __async(this, null, function* () {
1929
- if (!this.isTransportDefined()) {
2626
+ if (!this.isTransportConnected()) {
1930
2627
  return {
1931
2628
  jsonrpc: "2.0",
1932
2629
  id: request.id,
@@ -1943,9 +2640,6 @@ walletGetSession_fn = function(request) {
1943
2640
  walletRevokeSession_fn = function(request) {
1944
2641
  return __async(this, null, function* () {
1945
2642
  var _a3;
1946
- if (!this.isTransportDefined()) {
1947
- return { jsonrpc: "2.0", id: request.id, result: true };
1948
- }
1949
2643
  const revokeSessionParams = request.params;
1950
2644
  const scopes = (_a3 = revokeSessionParams == null ? void 0 : revokeSessionParams.scopes) != null ? _a3 : [];
1951
2645
  try {
@@ -1958,7 +2652,7 @@ walletRevokeSession_fn = function(request) {
1958
2652
  };
1959
2653
  walletInvokeMethod_fn = function(request) {
1960
2654
  return __async(this, null, function* () {
1961
- if (!this.isTransportDefined()) {
2655
+ if (!this.isTransportConnected()) {
1962
2656
  return { error: providerErrors.unauthorized() };
1963
2657
  }
1964
2658
  const result = this.metamaskConnectMultichain.invokeMethod(
@@ -1970,686 +2664,11 @@ walletInvokeMethod_fn = function(request) {
1970
2664
  });
1971
2665
  };
1972
2666
 
1973
- // src/multichain/transports/mwp/index.ts
1974
- init_domain();
1975
- init_utils2();
1976
- import { SessionStore } from "@metamask/mobile-wallet-protocol-core";
1977
- import {
1978
- TransportTimeoutError
1979
- } from "@metamask/multichain-api-client";
1980
- import { JsonRpcError, providerErrors as providerErrors2, rpcErrors } from "@metamask/rpc-errors";
1981
-
1982
- // src/multichain/transports/constants.ts
1983
- var MULTICHAIN_PROVIDER_STREAM_NAME = "metamask-multichain-provider";
1984
-
1985
- // src/multichain/transports/mwp/index.ts
1986
- var DEFAULT_REQUEST_TIMEOUT2 = 60 * 1e3;
1987
- var CONNECTION_GRACE_PERIOD = 60 * 1e3;
1988
- var DEFAULT_CONNECTION_TIMEOUT = DEFAULT_REQUEST_TIMEOUT2 + CONNECTION_GRACE_PERIOD;
1989
- var DEFAULT_RESUME_TIMEOUT = 10 * 1e3;
1990
- var SESSION_STORE_KEY = "cache_wallet_getSession";
1991
- var ACCOUNTS_STORE_KEY = "cache_eth_accounts";
1992
- var CHAIN_STORE_KEY = "cache_eth_chainId";
1993
- var PENDING_SESSION_REQUEST_KEY = "pending_session_request";
1994
- var CACHED_METHOD_LIST = [
1995
- "wallet_getSession",
1996
- "wallet_createSession",
1997
- "wallet_sessionChanged"
1998
- ];
1999
- var CACHED_RESET_METHOD_LIST = [
2000
- "wallet_revokeSession",
2001
- "wallet_revokePermissions"
2002
- ];
2003
- var logger = createLogger("metamask-sdk:transport");
2004
- var MWPTransport = class {
2005
- constructor(dappClient, kvstore, options = {
2006
- requestTimeout: DEFAULT_REQUEST_TIMEOUT2,
2007
- connectionTimeout: DEFAULT_CONNECTION_TIMEOUT,
2008
- resumeTimeout: DEFAULT_RESUME_TIMEOUT
2009
- }) {
2010
- this.dappClient = dappClient;
2011
- this.kvstore = kvstore;
2012
- this.options = options;
2013
- this.__pendingRequests = /* @__PURE__ */ new Map();
2014
- this.notificationCallbacks = /* @__PURE__ */ new Set();
2015
- this.dappClient.on("message", this.handleMessage.bind(this));
2016
- this.dappClient.on("session_request", (sessionRequest) => {
2017
- this.currentSessionRequest = sessionRequest;
2018
- this.kvstore.set(PENDING_SESSION_REQUEST_KEY, JSON.stringify(sessionRequest)).catch((err) => {
2019
- logger("Failed to store pending session request", err);
2020
- });
2021
- });
2022
- if (typeof window !== "undefined" && typeof window.addEventListener !== "undefined") {
2023
- this.windowFocusHandler = this.onWindowFocus.bind(this);
2024
- window.addEventListener("focus", this.windowFocusHandler);
2025
- }
2026
- }
2027
- get pendingRequests() {
2028
- return this.__pendingRequests;
2029
- }
2030
- set pendingRequests(pendingRequests) {
2031
- this.__pendingRequests = pendingRequests;
2032
- }
2033
- get sessionRequest() {
2034
- return this.currentSessionRequest;
2035
- }
2036
- /**
2037
- * Returns the stored pending session request from the dappClient session_request event, if any.
2038
- *
2039
- * @returns The stored SessionRequest, or null if none or invalid.
2040
- */
2041
- getStoredPendingSessionRequest() {
2042
- return __async(this, null, function* () {
2043
- try {
2044
- const raw = yield this.kvstore.get(PENDING_SESSION_REQUEST_KEY);
2045
- if (!raw) {
2046
- return null;
2047
- }
2048
- return JSON.parse(raw);
2049
- } catch (e) {
2050
- return null;
2051
- }
2052
- });
2053
- }
2054
- /**
2055
- * Removes the stored pending session request from the KVStore.
2056
- * This is necessary to ensure that ConnectMultichain is able to correctly
2057
- * infer the MWP Transport connection attempt status.
2058
- */
2059
- removeStoredPendingSessionRequest() {
2060
- return __async(this, null, function* () {
2061
- yield this.kvstore.delete(PENDING_SESSION_REQUEST_KEY);
2062
- });
2063
- }
2064
- onWindowFocus() {
2065
- if (!this.isConnected()) {
2066
- this.dappClient.reconnect();
2067
- }
2068
- }
2069
- notifyCallbacks(data) {
2070
- this.notificationCallbacks.forEach((callback) => callback(data));
2071
- }
2072
- rejectRequest(id, error = new Error("Request rejected")) {
2073
- const request = this.pendingRequests.get(id);
2074
- if (request) {
2075
- this.pendingRequests.delete(id);
2076
- clearTimeout(request.timeout);
2077
- request.reject(error);
2078
- }
2079
- }
2080
- parseWalletError(errorPayload) {
2081
- const errorData = errorPayload;
2082
- if (typeof errorData.code === "number" && typeof errorData.message === "string") {
2083
- const { code, message: message2 } = errorData;
2084
- if (code >= 1e3 && code <= 4999) {
2085
- return providerErrors2.custom({ code, message: message2 });
2086
- }
2087
- return new JsonRpcError(code, message2);
2088
- }
2089
- const message = errorPayload instanceof Error ? errorPayload.message : JSON.stringify(errorPayload);
2090
- return rpcErrors.internal({ message });
2091
- }
2092
- handleMessage(message) {
2093
- if (typeof message === "object" && message !== null) {
2094
- if ("data" in message) {
2095
- const messagePayload = message.data;
2096
- if ("id" in messagePayload && typeof messagePayload.id === "string") {
2097
- const request = this.pendingRequests.get(messagePayload.id);
2098
- if (request) {
2099
- clearTimeout(request.timeout);
2100
- if ("error" in messagePayload && messagePayload.error) {
2101
- this.pendingRequests.delete(messagePayload.id);
2102
- request.reject(this.parseWalletError(messagePayload.error));
2103
- return;
2104
- }
2105
- const requestWithName = __spreadProps(__spreadValues({}, messagePayload), {
2106
- method: request.method === "wallet_getSession" || request.method === "wallet_createSession" ? "wallet_sessionChanged" : request.method
2107
- });
2108
- const notification = __spreadProps(__spreadValues({}, messagePayload), {
2109
- method: request.method === "wallet_getSession" || request.method === "wallet_createSession" ? "wallet_sessionChanged" : request.method,
2110
- params: requestWithName.result
2111
- });
2112
- this.notifyCallbacks(notification);
2113
- request.resolve(requestWithName);
2114
- this.pendingRequests.delete(messagePayload.id);
2115
- }
2116
- } else {
2117
- if (message.data.method === "metamask_chainChanged") {
2118
- this.kvstore.set(
2119
- CHAIN_STORE_KEY,
2120
- JSON.stringify(
2121
- message.data.params.chainId
2122
- )
2123
- );
2124
- }
2125
- if (message.data.method === "metamask_accountsChanged") {
2126
- this.kvstore.set(
2127
- ACCOUNTS_STORE_KEY,
2128
- JSON.stringify(
2129
- message.data.params
2130
- )
2131
- );
2132
- }
2133
- if (message.data.method === "wallet_sessionChanged") {
2134
- const notification = message.data;
2135
- const response = {
2136
- result: notification.params
2137
- };
2138
- this.kvstore.set(SESSION_STORE_KEY, JSON.stringify(response));
2139
- }
2140
- this.notifyCallbacks(message.data);
2141
- }
2142
- }
2143
- }
2144
- }
2145
- onResumeSuccess(resumeResolve, resumeReject, options) {
2146
- return __async(this, null, function* () {
2147
- var _a3, _b, _c, _d, _e, _f, _g;
2148
- try {
2149
- yield this.waitForWalletSessionIfNotCached();
2150
- const sessionRequest = yield this.request({
2151
- method: "wallet_getSession"
2152
- });
2153
- if (sessionRequest.error) {
2154
- return resumeReject(new Error(sessionRequest.error.message));
2155
- }
2156
- let walletSession = sessionRequest.result;
2157
- if (walletSession && options) {
2158
- const currentScopes = Object.keys(
2159
- (_a3 = walletSession == null ? void 0 : walletSession.sessionScopes) != null ? _a3 : {}
2160
- );
2161
- const proposedScopes = (_b = options == null ? void 0 : options.scopes) != null ? _b : [];
2162
- const proposedCaipAccountIds = (_c = options == null ? void 0 : options.caipAccountIds) != null ? _c : [];
2163
- const hasSameScopesAndAccounts = isSameScopesAndAccounts(
2164
- currentScopes,
2165
- proposedScopes,
2166
- walletSession,
2167
- proposedCaipAccountIds
2168
- );
2169
- if (options.forceRequest || !hasSameScopesAndAccounts) {
2170
- const optionalScopes = addValidAccounts(
2171
- getOptionalScopes((_d = options == null ? void 0 : options.scopes) != null ? _d : []),
2172
- getValidAccounts((_e = options == null ? void 0 : options.caipAccountIds) != null ? _e : [])
2173
- );
2174
- const sessionRequest2 = {
2175
- optionalScopes
2176
- };
2177
- const response = yield this.request({
2178
- method: "wallet_createSession",
2179
- params: sessionRequest2
2180
- });
2181
- if (response.error) {
2182
- return resumeReject(new Error(response.error.message));
2183
- }
2184
- walletSession = response.result;
2185
- }
2186
- } else if (!walletSession) {
2187
- const optionalScopes = addValidAccounts(
2188
- getOptionalScopes((_f = options == null ? void 0 : options.scopes) != null ? _f : []),
2189
- getValidAccounts((_g = options == null ? void 0 : options.caipAccountIds) != null ? _g : [])
2190
- );
2191
- const sessionRequest2 = { optionalScopes };
2192
- const response = yield this.request({
2193
- method: "wallet_createSession",
2194
- params: sessionRequest2
2195
- });
2196
- if (response.error) {
2197
- return resumeReject(new Error(response.error.message));
2198
- }
2199
- walletSession = response.result;
2200
- }
2201
- yield this.removeStoredPendingSessionRequest();
2202
- this.notifyCallbacks({
2203
- method: "wallet_sessionChanged",
2204
- params: walletSession
2205
- });
2206
- return resumeResolve();
2207
- } catch (err) {
2208
- return resumeReject(err);
2209
- }
2210
- });
2211
- }
2212
- init() {
2213
- return __async(this, null, function* () {
2214
- });
2215
- }
2216
- // TODO: Rename this
2217
- sendEip1193Message(payload, options) {
2218
- return __async(this, null, function* () {
2219
- const request = __spreadValues({
2220
- jsonrpc: "2.0",
2221
- id: String(getUniqueRequestId())
2222
- }, payload);
2223
- const cachedWalletSession = yield this.getCachedResponse(request);
2224
- if (cachedWalletSession) {
2225
- this.notifyCallbacks(cachedWalletSession);
2226
- return cachedWalletSession;
2227
- }
2228
- return new Promise((resolve, reject) => {
2229
- var _a3;
2230
- const timeout = setTimeout(() => {
2231
- this.rejectRequest(request.id, new TransportTimeoutError());
2232
- }, (_a3 = options == null ? void 0 : options.timeout) != null ? _a3 : this.options.requestTimeout);
2233
- this.pendingRequests.set(request.id, {
2234
- request,
2235
- method: request.method,
2236
- resolve: (response) => __async(this, null, function* () {
2237
- yield this.storeWalletSession(request, response);
2238
- return resolve(response);
2239
- }),
2240
- reject,
2241
- timeout
2242
- });
2243
- this.dappClient.sendRequest({
2244
- name: "metamask-provider",
2245
- data: request
2246
- }).catch(reject);
2247
- });
2248
- });
2249
- }
2250
- connect(options) {
2251
- return __async(this, null, function* () {
2252
- const { dappClient } = this;
2253
- const session = yield this.getActiveSession();
2254
- if (session) {
2255
- logger("active session found", {
2256
- id: session.id,
2257
- channel: session.channel,
2258
- expiresAt: session.expiresAt
2259
- });
2260
- }
2261
- const storedSessionRequestBeforeConnectionAttempt = yield this.getStoredPendingSessionRequest();
2262
- let timeout;
2263
- let initialConnectionMessageHandler;
2264
- const connectionPromise = new Promise((resolve, reject) => __async(this, null, function* () {
2265
- let connection;
2266
- if (session) {
2267
- connection = new Promise((resumeResolve, resumeReject) => {
2268
- var _a3;
2269
- if (this.dappClient.state === "CONNECTED") {
2270
- this.onResumeSuccess(resumeResolve, resumeReject, options);
2271
- } else {
2272
- this.dappClient.once("connected", () => __async(this, null, function* () {
2273
- this.onResumeSuccess(resumeResolve, resumeReject, options);
2274
- }));
2275
- dappClient.resume((_a3 = session == null ? void 0 : session.id) != null ? _a3 : "");
2276
- }
2277
- });
2278
- } else {
2279
- connection = new Promise(
2280
- (resolveConnection, rejectConnection) => {
2281
- var _a3, _b;
2282
- const optionalScopes = addValidAccounts(
2283
- getOptionalScopes((_a3 = options == null ? void 0 : options.scopes) != null ? _a3 : []),
2284
- getValidAccounts((_b = options == null ? void 0 : options.caipAccountIds) != null ? _b : [])
2285
- );
2286
- const sessionRequest = {
2287
- optionalScopes,
2288
- sessionProperties: options == null ? void 0 : options.sessionProperties
2289
- };
2290
- const request = {
2291
- jsonrpc: "2.0",
2292
- id: String(getUniqueRequestId()),
2293
- method: "wallet_createSession",
2294
- params: sessionRequest
2295
- };
2296
- initialConnectionMessageHandler = (message) => __async(this, null, function* () {
2297
- if (typeof message !== "object" || message === null) {
2298
- return;
2299
- }
2300
- if (!("data" in message)) {
2301
- return;
2302
- }
2303
- const messagePayload = message.data;
2304
- const isMatchingId = messagePayload.id === request.id;
2305
- const isMatchingMethod = messagePayload.method === "wallet_createSession" || messagePayload.method === "wallet_sessionChanged";
2306
- if (!isMatchingId && !isMatchingMethod) {
2307
- return;
2308
- }
2309
- if (messagePayload.error) {
2310
- return rejectConnection(
2311
- this.parseWalletError(messagePayload.error)
2312
- );
2313
- }
2314
- yield this.storeWalletSession(
2315
- request,
2316
- messagePayload
2317
- );
2318
- yield this.removeStoredPendingSessionRequest();
2319
- this.notifyCallbacks(messagePayload);
2320
- return resolveConnection();
2321
- });
2322
- this.dappClient.on("message", initialConnectionMessageHandler);
2323
- dappClient.connect({
2324
- mode: "trusted",
2325
- initialPayload: {
2326
- name: MULTICHAIN_PROVIDER_STREAM_NAME,
2327
- data: request
2328
- }
2329
- }).catch((error) => {
2330
- if (initialConnectionMessageHandler) {
2331
- this.dappClient.off(
2332
- "message",
2333
- initialConnectionMessageHandler
2334
- );
2335
- }
2336
- rejectConnection(error);
2337
- });
2338
- }
2339
- );
2340
- }
2341
- timeout = setTimeout(
2342
- () => {
2343
- reject(new TransportTimeoutError());
2344
- },
2345
- storedSessionRequestBeforeConnectionAttempt ? this.options.resumeTimeout : this.options.connectionTimeout
2346
- );
2347
- connection.then(resolve).catch(reject);
2348
- }));
2349
- return connectionPromise.catch((error) => __async(this, null, function* () {
2350
- yield this.dappClient.disconnect();
2351
- throw error;
2352
- })).finally(() => {
2353
- if (timeout) {
2354
- clearTimeout(timeout);
2355
- }
2356
- if (initialConnectionMessageHandler) {
2357
- this.dappClient.off("message", initialConnectionMessageHandler);
2358
- initialConnectionMessageHandler = void 0;
2359
- }
2360
- this.removeStoredPendingSessionRequest();
2361
- });
2362
- });
2363
- }
2364
- /**
2365
- * Disconnects from the Mobile Wallet Protocol
2366
- *
2367
- * @param [scopes] - The scopes to revoke. If not provided or empty, all scopes will be revoked.
2368
- * @returns Nothing
2369
- */
2370
- disconnect() {
2371
- return __async(this, arguments, function* (scopes = []) {
2372
- var _a3, _b;
2373
- const cachedSession = yield this.getCachedResponse({
2374
- jsonrpc: "2.0",
2375
- id: "0",
2376
- method: "wallet_getSession"
2377
- });
2378
- const cachedSessionScopes = (_b = (_a3 = cachedSession == null ? void 0 : cachedSession.result) == null ? void 0 : _a3.sessionScopes) != null ? _b : {};
2379
- const remainingScopes = scopes.length === 0 ? [] : Object.keys(cachedSessionScopes).filter(
2380
- (scope) => !scopes.includes(scope)
2381
- );
2382
- const newSessionScopes = Object.fromEntries(
2383
- Object.entries(cachedSessionScopes).filter(
2384
- ([key]) => remainingScopes.includes(key)
2385
- )
2386
- );
2387
- this.request({ method: "wallet_revokeSession", params: { scopes } }).catch(
2388
- (err) => {
2389
- console.error("error revoking session", err);
2390
- }
2391
- );
2392
- const remainingScopesIncludeEip155 = remainingScopes.some(
2393
- (scope) => scope.includes("eip155")
2394
- );
2395
- if (!remainingScopesIncludeEip155) {
2396
- this.kvstore.delete(ACCOUNTS_STORE_KEY);
2397
- this.kvstore.delete(CHAIN_STORE_KEY);
2398
- }
2399
- if (remainingScopes.length > 0) {
2400
- this.kvstore.set(
2401
- SESSION_STORE_KEY,
2402
- JSON.stringify({
2403
- result: {
2404
- sessionScopes: newSessionScopes
2405
- }
2406
- })
2407
- );
2408
- } else {
2409
- this.kvstore.delete(SESSION_STORE_KEY);
2410
- if (typeof window !== "undefined" && typeof window.removeEventListener !== "undefined" && this.windowFocusHandler) {
2411
- window.removeEventListener("focus", this.windowFocusHandler);
2412
- this.windowFocusHandler = void 0;
2413
- }
2414
- yield this.dappClient.disconnect();
2415
- }
2416
- this.notifyCallbacks({
2417
- method: "wallet_sessionChanged",
2418
- params: {
2419
- sessionScopes: newSessionScopes
2420
- }
2421
- });
2422
- });
2423
- }
2424
- /**
2425
- * Checks if the transport is connected
2426
- *
2427
- * @returns True if transport is connected, false otherwise
2428
- */
2429
- isConnected() {
2430
- return this.dappClient.state === "CONNECTED";
2431
- }
2432
- /**
2433
- * Attempts to re-establish a connection via DappClient
2434
- *
2435
- * @returns Nothing
2436
- */
2437
- // TODO: We should re-evaluate adding this to the WebSocketTransport layer from `@metamask/mobile-wallet-protocol-core`
2438
- // ticket: https://consensyssoftware.atlassian.net/browse/WAPI-862
2439
- attemptResumeSession() {
2440
- return __async(this, null, function* () {
2441
- try {
2442
- yield this.dappClient.reconnect();
2443
- yield new Promise((resolve, reject) => {
2444
- const timeout = setTimeout(() => {
2445
- reject(new Error("Resume timeout"));
2446
- }, 2e3);
2447
- if (this.isConnected()) {
2448
- clearTimeout(timeout);
2449
- resolve();
2450
- } else {
2451
- this.dappClient.once("connected", () => {
2452
- clearTimeout(timeout);
2453
- resolve();
2454
- });
2455
- }
2456
- });
2457
- } catch (error) {
2458
- return Promise.reject(
2459
- new Error(`Failed to resume session: ${error.message}`)
2460
- );
2461
- }
2462
- });
2463
- }
2464
- getCachedResponse(request) {
2465
- return __async(this, null, function* () {
2466
- var _a3;
2467
- if (request.method === "wallet_getSession") {
2468
- const walletGetSession = yield this.kvstore.get(SESSION_STORE_KEY);
2469
- if (walletGetSession) {
2470
- const walletSession = JSON.parse(walletGetSession);
2471
- return {
2472
- id: request.id,
2473
- jsonrpc: "2.0",
2474
- result: (_a3 = walletSession.params) != null ? _a3 : walletSession.result,
2475
- // "what?... why walletSession.params?.."
2476
- method: request.method
2477
- };
2478
- }
2479
- } else if (request.method === "eth_accounts") {
2480
- const ethAccounts = yield this.kvstore.get(ACCOUNTS_STORE_KEY);
2481
- if (ethAccounts) {
2482
- return {
2483
- id: request.id,
2484
- jsonrpc: "2.0",
2485
- result: JSON.parse(ethAccounts),
2486
- method: request.method
2487
- };
2488
- }
2489
- } else if (request.method === "eth_chainId") {
2490
- const ethChainId = yield this.kvstore.get(CHAIN_STORE_KEY);
2491
- if (ethChainId) {
2492
- return {
2493
- id: request.id,
2494
- jsonrpc: "2.0",
2495
- result: JSON.parse(ethChainId),
2496
- method: request.method
2497
- };
2498
- }
2499
- }
2500
- });
2501
- }
2502
- storeWalletSession(request, response) {
2503
- return __async(this, null, function* () {
2504
- if (response.error) {
2505
- return;
2506
- }
2507
- if (CACHED_METHOD_LIST.includes(request.method)) {
2508
- yield this.kvstore.set(SESSION_STORE_KEY, JSON.stringify(response));
2509
- } else if (request.method === "eth_accounts") {
2510
- yield this.kvstore.set(
2511
- ACCOUNTS_STORE_KEY,
2512
- JSON.stringify(response.result)
2513
- );
2514
- } else if (request.method === "eth_chainId") {
2515
- yield this.kvstore.set(CHAIN_STORE_KEY, JSON.stringify(response.result));
2516
- } else if (CACHED_RESET_METHOD_LIST.includes(request.method)) {
2517
- yield this.kvstore.delete(SESSION_STORE_KEY);
2518
- yield this.kvstore.delete(ACCOUNTS_STORE_KEY);
2519
- yield this.kvstore.delete(CHAIN_STORE_KEY);
2520
- }
2521
- });
2522
- }
2523
- request(payload, options) {
2524
- return __async(this, null, function* () {
2525
- const request = __spreadValues({
2526
- jsonrpc: "2.0",
2527
- id: String(getUniqueRequestId())
2528
- }, payload);
2529
- const cachedWalletSession = yield this.getCachedResponse(request);
2530
- if (cachedWalletSession) {
2531
- this.notifyCallbacks(cachedWalletSession);
2532
- return cachedWalletSession;
2533
- }
2534
- if (!this.isConnected()) {
2535
- yield this.attemptResumeSession();
2536
- }
2537
- return new Promise((resolve, reject) => {
2538
- var _a3;
2539
- const timeout = setTimeout(() => {
2540
- this.rejectRequest(request.id, new TransportTimeoutError());
2541
- }, (_a3 = options == null ? void 0 : options.timeout) != null ? _a3 : this.options.requestTimeout);
2542
- this.pendingRequests.set(request.id, {
2543
- request,
2544
- method: request.method,
2545
- resolve: (response) => __async(this, null, function* () {
2546
- yield this.storeWalletSession(request, response);
2547
- return resolve(response);
2548
- }),
2549
- reject,
2550
- timeout
2551
- });
2552
- this.dappClient.sendRequest({
2553
- name: MULTICHAIN_PROVIDER_STREAM_NAME,
2554
- data: request
2555
- }).catch(reject);
2556
- });
2557
- });
2558
- }
2559
- onNotification(callback) {
2560
- this.notificationCallbacks.add(callback);
2561
- return () => {
2562
- this.notificationCallbacks.delete(callback);
2563
- };
2564
- }
2565
- getActiveSession() {
2566
- return __async(this, null, function* () {
2567
- const { kvstore } = this;
2568
- const sessionStore = yield SessionStore.create(kvstore);
2569
- try {
2570
- const [activeSession] = yield sessionStore.list();
2571
- return activeSession;
2572
- } catch (error) {
2573
- logger("error getting active session", error);
2574
- return void 0;
2575
- }
2576
- });
2577
- }
2578
- // This method checks if an existing CAIP session response is cached or waits for one
2579
- // to be received from the wallet if not cached. This is necessary because there is an edge
2580
- // case during the initial connection flow where after the user has accepted the permission approval
2581
- // and returned back to the dapp from the wallet, the dapp page may have gotten unloaded and refreshed.
2582
- // When it is unloaded and refreshed, it will try to resume the session by making a request for wallet_getSession
2583
- // which should resolve from cache, but because a race condition makes it possible for the response from the wallet
2584
- // for the initial wallet_createSession connection request to not have been handled and cached yet. This results
2585
- // in the wallet_getSession request never resolving unless we wait for it explicitly as done in this method.
2586
- waitForWalletSessionIfNotCached() {
2587
- return __async(this, null, function* () {
2588
- const cachedWalletGetSessionResponse = yield this.kvstore.get(SESSION_STORE_KEY);
2589
- if (cachedWalletGetSessionResponse) {
2590
- return;
2591
- }
2592
- let unsubscribe;
2593
- const responsePromise = new Promise((resolve) => {
2594
- unsubscribe = this.onNotification((message) => {
2595
- if (typeof message === "object" && message !== null) {
2596
- if ("data" in message) {
2597
- const messagePayload = message.data;
2598
- if (messagePayload.method === "wallet_getSession" || messagePayload.method === "wallet_sessionChanged") {
2599
- unsubscribe();
2600
- resolve();
2601
- }
2602
- }
2603
- }
2604
- });
2605
- });
2606
- const timeoutPromise = new Promise((_resolve, reject) => {
2607
- setTimeout(() => {
2608
- unsubscribe();
2609
- this.removeStoredPendingSessionRequest();
2610
- reject(new TransportTimeoutError());
2611
- }, this.options.resumeTimeout);
2612
- });
2613
- return Promise.race([responsePromise, timeoutPromise]);
2614
- });
2615
- }
2616
- };
2617
-
2618
- // src/multichain/transports/mwp/KeyManager.ts
2619
- import { decrypt, encrypt, PrivateKey, PublicKey } from "eciesjs";
2620
- var KeyManager = class {
2621
- generateKeyPair() {
2622
- const privateKey = new PrivateKey();
2623
- return {
2624
- privateKey: new Uint8Array(privateKey.secret),
2625
- publicKey: privateKey.publicKey.toBytes(true)
2626
- };
2627
- }
2628
- encrypt(plaintext, theirPublicKey) {
2629
- return __async(this, null, function* () {
2630
- const plaintextBuffer = Buffer.from(plaintext, "utf8");
2631
- const encryptedBuffer = encrypt(theirPublicKey, plaintextBuffer);
2632
- return encryptedBuffer.toString("base64");
2633
- });
2634
- }
2635
- decrypt(encryptedB64, myPrivateKey) {
2636
- return __async(this, null, function* () {
2637
- const encryptedBuffer = Buffer.from(encryptedB64, "base64");
2638
- const decryptedBuffer = yield decrypt(myPrivateKey, encryptedBuffer);
2639
- return Buffer.from(decryptedBuffer).toString("utf8");
2640
- });
2641
- }
2642
- validatePeerKey(key) {
2643
- PublicKey.fromHex(Buffer.from(key).toString("hex"));
2644
- }
2645
- };
2646
- var keymanager = new KeyManager();
2647
-
2648
2667
  // src/multichain/index.ts
2649
2668
  init_utils2();
2650
2669
  var logger2 = createLogger("metamask-sdk:core");
2651
2670
  var SINGLETON_KEY = "__METAMASK_CONNECT_MULTICHAIN_SINGLETON__";
2652
- 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;
2671
+ 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;
2653
2672
  var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends MultichainCore {
2654
2673
  constructor(options) {
2655
2674
  var _a3, _b, _c, _d, _e, _f;
@@ -2667,7 +2686,7 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
2667
2686
  versions: __spreadValues({
2668
2687
  // typeof guard needed: Metro (React Native) bundles TS source directly,
2669
2688
  // bypassing the tsup build that substitutes __PACKAGE_VERSION__.
2670
- "connect-multichain": false ? "unknown" : "0.12.1"
2689
+ "connect-multichain": false ? "unknown" : "0.13.0"
2671
2690
  }, (_f = options.versions) != null ? _f : {})
2672
2691
  });
2673
2692
  super(allOptions);
@@ -2677,6 +2696,7 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
2677
2696
  __privateAdd(this, _transport2);
2678
2697
  __privateAdd(this, _dappClient);
2679
2698
  __privateAdd(this, _beforeUnloadListener);
2699
+ __privateAdd(this, _transportType);
2680
2700
  this._status = "pending";
2681
2701
  __privateAdd(this, _listener);
2682
2702
  __privateAdd(this, _anonId);
@@ -2713,12 +2733,13 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
2713
2733
  }
2714
2734
  return __privateGet(this, _dappClient);
2715
2735
  }
2736
+ get transportType() {
2737
+ var _a3;
2738
+ return (_a3 = __privateGet(this, _transportType)) != null ? _a3 : "unknown" /* UNKNOWN */;
2739
+ }
2716
2740
  get storage() {
2717
2741
  return this.options.storage;
2718
2742
  }
2719
- get transportType() {
2720
- return __privateGet(this, _transport2) instanceof MWPTransport ? "mwp" /* MWP */ : "browser" /* Browser */;
2721
- }
2722
2743
  // Creates a singleton instance of MetaMaskConnectMultichain.
2723
2744
  // If the singleton already exists, it merges the incoming options with the
2724
2745
  // existing singleton options for the following keys: `api.supportedNetworks`,
@@ -2772,7 +2793,7 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
2772
2793
  connect(scopes, caipAccountIds, sessionProperties, forceRequest) {
2773
2794
  return __async(this, null, function* () {
2774
2795
  var _a3;
2775
- if (this.status === "connecting" && this.transportType === "mwp" /* MWP */) {
2796
+ if (this.status === "connecting" && __privateGet(this, _transportType) === "mwp" /* MWP */) {
2776
2797
  yield __privateMethod(this, _MetaMaskConnectMultichain_instances, openConnectDeeplinkIfNeeded_fn).call(this);
2777
2798
  throw new Error(
2778
2799
  "Existing connection is pending. Please check your MetaMask Mobile app to continue."
@@ -2821,7 +2842,7 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
2821
2842
  sessionProperties: nonEmptySessionProperties,
2822
2843
  forceRequest
2823
2844
  }).then(() => __async(this, null, function* () {
2824
- if (__privateGet(this, _transport2) instanceof MWPTransport) {
2845
+ if (__privateGet(this, _transportType) === "mwp" /* MWP */) {
2825
2846
  return this.storage.setTransport("mwp" /* MWP */);
2826
2847
  }
2827
2848
  return this.storage.setTransport("browser" /* Browser */);
@@ -2868,12 +2889,13 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
2868
2889
  yield (_a3 = __privateGet(this, _transport2)) == null ? void 0 : _a3.disconnect(scopes);
2869
2890
  if (remainingScopes.length === 0) {
2870
2891
  yield this.storage.removeTransport();
2871
- if (this.transportType !== "browser" /* Browser */) {
2892
+ if (__privateGet(this, _transportType) !== "browser" /* Browser */) {
2872
2893
  yield (_b = __privateGet(this, _listener)) == null ? void 0 : _b.call(this);
2873
2894
  (_c = __privateGet(this, _beforeUnloadListener)) == null ? void 0 : _c.call(this);
2874
2895
  __privateSet(this, _listener, void 0);
2875
2896
  __privateSet(this, _beforeUnloadListener, void 0);
2876
2897
  __privateSet(this, _transport2, void 0);
2898
+ __privateSet(this, _transportType, void 0);
2877
2899
  __privateGet(this, _providerTransportWrapper).clearTransportNotificationListener();
2878
2900
  __privateSet(this, _dappClient, void 0);
2879
2901
  }
@@ -2883,13 +2905,14 @@ var _MetaMaskConnectMultichain = class _MetaMaskConnectMultichain extends Multic
2883
2905
  }
2884
2906
  invokeMethod(request) {
2885
2907
  return __async(this, null, function* () {
2908
+ var _a3;
2886
2909
  const { transport, options } = this;
2887
2910
  const rpcClient = new RpcClient(options, __privateGet(this, _sdkInfo));
2888
2911
  const requestRouter = new RequestRouter(
2889
2912
  transport,
2890
2913
  rpcClient,
2891
2914
  options,
2892
- this.transportType
2915
+ (_a3 = __privateGet(this, _transportType)) != null ? _a3 : "unknown" /* UNKNOWN */
2893
2916
  );
2894
2917
  return requestRouter.invokeMethod(request);
2895
2918
  });
@@ -2938,6 +2961,7 @@ _providerTransportWrapper = new WeakMap();
2938
2961
  _transport2 = new WeakMap();
2939
2962
  _dappClient = new WeakMap();
2940
2963
  _beforeUnloadListener = new WeakMap();
2964
+ _transportType = new WeakMap();
2941
2965
  _listener = new WeakMap();
2942
2966
  _anonId = new WeakMap();
2943
2967
  _sdkInfo = new WeakMap();
@@ -2995,6 +3019,7 @@ getStoredTransport_fn = function() {
2995
3019
  if (hasExtensionInstalled) {
2996
3020
  const apiTransport = new DefaultTransport();
2997
3021
  __privateSet(this, _transport2, apiTransport);
3022
+ __privateSet(this, _transportType, "browser" /* Browser */);
2998
3023
  __privateGet(this, _providerTransportWrapper).setupTransportNotificationListener();
2999
3024
  __privateSet(this, _listener, apiTransport.onNotification(
3000
3025
  __privateMethod(this, _MetaMaskConnectMultichain_instances, onTransportNotification_fn).bind(this)
@@ -3004,9 +3029,11 @@ getStoredTransport_fn = function() {
3004
3029
  } else if (transportType === "mwp" /* MWP */) {
3005
3030
  const { adapter: kvstore } = this.options.storage;
3006
3031
  const dappClient = yield __privateMethod(this, _MetaMaskConnectMultichain_instances, createDappClient_fn).call(this);
3007
- const apiTransport = new MWPTransport(dappClient, kvstore);
3032
+ const { MWPTransport: MWPTransport2 } = yield Promise.resolve().then(() => (init_mwp(), mwp_exports));
3033
+ const apiTransport = new MWPTransport2(dappClient, kvstore);
3008
3034
  __privateSet(this, _dappClient, dappClient);
3009
3035
  __privateSet(this, _transport2, apiTransport);
3036
+ __privateSet(this, _transportType, "mwp" /* MWP */);
3010
3037
  __privateGet(this, _providerTransportWrapper).setupTransportNotificationListener();
3011
3038
  __privateSet(this, _listener, apiTransport.onNotification(
3012
3039
  __privateMethod(this, _MetaMaskConnectMultichain_instances, onTransportNotification_fn).bind(this)
@@ -3028,7 +3055,7 @@ setupTransport_fn = function() {
3028
3055
  yield this.transport.connect();
3029
3056
  }
3030
3057
  this.status = "connected";
3031
- if (this.transport instanceof MWPTransport) {
3058
+ if (__privateGet(this, _transportType) === "mwp" /* MWP */) {
3032
3059
  yield this.storage.setTransport("mwp" /* MWP */);
3033
3060
  } else {
3034
3061
  yield this.storage.setTransport("browser" /* Browser */);
@@ -3072,31 +3099,43 @@ init_fn2 = function() {
3072
3099
  };
3073
3100
  createDappClient_fn = function() {
3074
3101
  return __async(this, null, function* () {
3102
+ const [mwpCore, { DappClient: DappClientClass }, { createKeyManager: createKeyManager2 }] = yield Promise.all([
3103
+ import("@metamask/mobile-wallet-protocol-core"),
3104
+ import("@metamask/mobile-wallet-protocol-dapp-client"),
3105
+ Promise.resolve().then(() => (init_KeyManager(), KeyManager_exports))
3106
+ ]);
3107
+ const keymanager = yield createKeyManager2();
3075
3108
  const { adapter: kvstore } = this.options.storage;
3076
- const sessionstore = yield SessionStore2.create(kvstore);
3109
+ const sessionstore = yield mwpCore.SessionStore.create(kvstore);
3077
3110
  const websocket = (
3078
3111
  // eslint-disable-next-line no-negated-condition
3079
3112
  typeof window !== "undefined" ? WebSocket : (yield import("ws")).WebSocket
3080
3113
  );
3081
- const transport = yield WebSocketTransport.create({
3114
+ const transport = yield mwpCore.WebSocketTransport.create({
3082
3115
  url: MWP_RELAY_URL,
3083
3116
  kvstore,
3084
3117
  websocket
3085
3118
  });
3086
- const dappClient = new DappClient({ transport, sessionstore, keymanager });
3119
+ const dappClient = new DappClientClass({
3120
+ transport,
3121
+ sessionstore,
3122
+ keymanager
3123
+ });
3087
3124
  return dappClient;
3088
3125
  });
3089
3126
  };
3090
3127
  setupMWP_fn = function() {
3091
3128
  return __async(this, null, function* () {
3092
- if (__privateGet(this, _transport2) instanceof MWPTransport) {
3129
+ if (__privateGet(this, _transportType) === "mwp" /* MWP */) {
3093
3130
  return;
3094
3131
  }
3095
3132
  const { adapter: kvstore } = this.options.storage;
3096
3133
  const dappClient = yield __privateMethod(this, _MetaMaskConnectMultichain_instances, createDappClient_fn).call(this);
3097
3134
  __privateSet(this, _dappClient, dappClient);
3098
- const apiTransport = new MWPTransport(dappClient, kvstore);
3135
+ const { MWPTransport: MWPTransport2 } = yield Promise.resolve().then(() => (init_mwp(), mwp_exports));
3136
+ const apiTransport = new MWPTransport2(dappClient, kvstore);
3099
3137
  __privateSet(this, _transport2, apiTransport);
3138
+ __privateSet(this, _transportType, "mwp" /* MWP */);
3100
3139
  __privateGet(this, _providerTransportWrapper).setupTransportNotificationListener();
3101
3140
  __privateSet(this, _listener, this.transport.onNotification(
3102
3141
  __privateMethod(this, _MetaMaskConnectMultichain_instances, onTransportNotification_fn).bind(this)
@@ -3155,6 +3194,7 @@ renderInstallModalAsync_fn = function(desktopPreferred, scopes, caipAccountIds,
3155
3194
  this.status = "connected";
3156
3195
  yield this.storage.setTransport("mwp" /* MWP */);
3157
3196
  } catch (error) {
3197
+ const { ProtocolError, ErrorCode } = yield import("@metamask/mobile-wallet-protocol-core");
3158
3198
  if (error instanceof ProtocolError) {
3159
3199
  if (error.code !== ErrorCode.REQUEST_EXPIRED) {
3160
3200
  this.status = "disconnected";
@@ -3224,6 +3264,7 @@ headlessConnect_fn = function(scopes, caipAccountIds, sessionProperties) {
3224
3264
  yield this.storage.setTransport("mwp" /* MWP */);
3225
3265
  resolve();
3226
3266
  })).catch((error) => __async(this, null, function* () {
3267
+ const { ProtocolError } = yield import("@metamask/mobile-wallet-protocol-core");
3227
3268
  if (error instanceof ProtocolError) {
3228
3269
  this.status = "disconnected";
3229
3270
  yield this.storage.removeTransport();
@@ -3239,7 +3280,7 @@ headlessConnect_fn = function(scopes, caipAccountIds, sessionProperties) {
3239
3280
  };
3240
3281
  setupDefaultTransport_fn = function() {
3241
3282
  return __async(this, arguments, function* (options = { persist: true }) {
3242
- if (__privateGet(this, _transport2) instanceof DefaultTransport) {
3283
+ if (__privateGet(this, _transportType) === "browser" /* Browser */) {
3243
3284
  return __privateGet(this, _transport2);
3244
3285
  }
3245
3286
  if (options == null ? void 0 : options.persist) {
@@ -3250,6 +3291,7 @@ setupDefaultTransport_fn = function() {
3250
3291
  __privateMethod(this, _MetaMaskConnectMultichain_instances, onTransportNotification_fn).bind(this)
3251
3292
  ));
3252
3293
  __privateSet(this, _transport2, transport);
3294
+ __privateSet(this, _transportType, "browser" /* Browser */);
3253
3295
  __privateGet(this, _providerTransportWrapper).setupTransportNotificationListener();
3254
3296
  return transport;
3255
3297
  });