UNPKG

@metamask/snaps-rpc-methods

Version:
67 lines 2.15 kB
import { providerErrors, rpcErrors } from "@metamask/rpc-errors"; import { create, object, string, StructError } from "@metamask/superstruct"; import { SnapEndowments } from "../endowments/index.mjs"; const hookNames = { hasPermission: true, closeWebSocket: true, }; const CloseWebSocketParametersStruct = object({ id: string(), }); /** * Handler for the `snap_closeWebSocket` method. */ export const closeWebSocketHandler = { methodNames: ['snap_closeWebSocket'], implementation: closeWebSocketImplementation, hookNames, }; /** * The `snap_closeWebSocket` 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.closeWebSocket - The function to close a WebSocket. * @returns Nothing. */ function closeWebSocketImplementation(req, res, _next, end, { hasPermission, closeWebSocket }) { if (!hasPermission(SnapEndowments.NetworkAccess)) { return end(providerErrors.unauthorized()); } const { params } = req; try { const { id } = getValidatedParams(params); closeWebSocket(id); res.result = null; } catch (error) { return end(error); } return end(); } /** * Validates the parameters for the snap_closeWebSocket method. * * @param params - Parameters to validate. * @returns Validated parameters. * @throws Throws RPC error if validation fails. */ function getValidatedParams(params) { try { return create(params, CloseWebSocketParametersStruct); } catch (error) { if (error instanceof StructError) { throw rpcErrors.invalidParams({ message: `Invalid params: ${error.message}.`, }); } /* istanbul ignore next */ throw rpcErrors.internal(); } } //# sourceMappingURL=closeWebSocket.mjs.map