@metamask/snaps-rpc-methods
Version:
MetaMask Snaps JSON-RPC method implementations
72 lines • 2.67 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.openWebSocketHandler = void 0;
const rpc_errors_1 = require("@metamask/rpc-errors");
const snaps_sdk_1 = require("@metamask/snaps-sdk");
const snaps_utils_1 = require("@metamask/snaps-utils");
const superstruct_1 = require("@metamask/superstruct");
const endowments_1 = require("../endowments/index.cjs");
const hookNames = {
hasPermission: true,
openWebSocket: true,
};
const OpenWebSocketParametersStruct = (0, superstruct_1.object)({
url: (0, snaps_utils_1.uri)({ protocol: (0, snaps_sdk_1.union)([(0, snaps_sdk_1.literal)('wss:'), (0, snaps_sdk_1.literal)('ws:')]) }),
protocols: (0, superstruct_1.optional)((0, superstruct_1.array)((0, superstruct_1.string)())),
});
/**
* Handler for the `snap_openWebSocket` method.
*/
exports.openWebSocketHandler = {
methodNames: ['snap_openWebSocket'],
implementation: openWebSocketImplementation,
hookNames,
};
/**
* The `snap_openWebSocket` method implementation.
*
* @param req - The JSON-RPC request object.
* @param res - The JSON-RPC response object.
* @param _next - The `json-rpc-engine` "next" callback. Not used by this function.
* @param end - The `json-rpc-engine` "end" callback.
* @param hooks - The RPC method hooks.
* @param hooks.hasPermission - The function to check if a snap has the `endowment:network-access` permission.
* @param hooks.openWebSocket - The function to open a WebSocket.
* @returns Nothing.
*/
async function openWebSocketImplementation(req, res, _next, end, { hasPermission, openWebSocket }) {
if (!hasPermission(endowments_1.SnapEndowments.NetworkAccess)) {
return end(rpc_errors_1.providerErrors.unauthorized());
}
const { params } = req;
try {
const { url, protocols } = getValidatedParams(params);
res.result = await openWebSocket(url, protocols);
}
catch (error) {
return end(error);
}
return end();
}
/**
* Validates the parameters for the snap_openWebSocket method.
*
* @param params - Parameters to validate.
* @returns Validated parameters.
* @throws Throws RPC error if validation fails.
*/
function getValidatedParams(params) {
try {
return (0, superstruct_1.create)(params, OpenWebSocketParametersStruct);
}
catch (error) {
if (error instanceof superstruct_1.StructError) {
throw rpc_errors_1.rpcErrors.invalidParams({
message: `Invalid params: ${error.message}.`,
});
}
/* istanbul ignore next */
throw rpc_errors_1.rpcErrors.internal();
}
}
//# sourceMappingURL=openWebSocket.cjs.map