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