UNPKG

@metamask/snaps-rpc-methods

Version:
69 lines 2.37 kB
import { providerErrors, rpcErrors } from "@metamask/rpc-errors"; import { literal, union } from "@metamask/snaps-sdk"; import { uri } from "@metamask/snaps-utils"; import { create, object, array, string, optional, StructError } from "@metamask/superstruct"; import { SnapEndowments } from "../endowments/index.mjs"; const hookNames = { hasPermission: true, openWebSocket: true, }; const OpenWebSocketParametersStruct = object({ url: uri({ protocol: union([literal('wss:'), literal('ws:')]) }), protocols: optional(array(string())), }); /** * Handler for the `snap_openWebSocket` method. */ export const 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(SnapEndowments.NetworkAccess)) { return end(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 create(params, OpenWebSocketParametersStruct); } catch (error) { if (error instanceof StructError) { throw rpcErrors.invalidParams({ message: `Invalid params: ${error.message}.`, }); } /* istanbul ignore next */ throw rpcErrors.internal(); } } //# sourceMappingURL=openWebSocket.mjs.map