@metamask/snaps-rpc-methods
Version:
MetaMask Snaps JSON-RPC method implementations
40 lines • 1.82 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.createSnapsMethodMiddleware = void 0;
const rpc_errors_1 = require("@metamask/rpc-errors");
const snaps_utils_1 = require("@metamask/snaps-utils");
const handlers_1 = require("./handlers.cjs");
const utils_1 = require("../utils.cjs");
/**
* Creates a middleware that handles permitted snap RPC methods.
*
* @param isSnap - A flag that should indicate whether the requesting origin is a snap or not.
* @param hooks - An object containing the hooks made available to the permitted RPC methods.
* @returns The middleware.
*/
function createSnapsMethodMiddleware(isSnap, hooks) {
// This is not actually a misused promise, the type is just wrong
// eslint-disable-next-line @typescript-eslint/no-misused-promises
return async function methodMiddleware(request, response, next, end) {
const handler = handlers_1.methodHandlers[request.method];
if (handler) {
if (String.prototype.startsWith.call(request.method, 'snap_') &&
!isSnap) {
return end(rpc_errors_1.rpcErrors.methodNotFound());
}
// TODO: Once json-rpc-engine types are up to date, we should type this correctly
const { implementation, hookNames } = handler;
try {
// Implementations may or may not be async, so we must await them.
return await implementation(request, response, next, end, (0, utils_1.selectHooks)(hooks, hookNames));
}
catch (error) {
(0, snaps_utils_1.logError)(error);
return end(error);
}
}
return next();
};
}
exports.createSnapsMethodMiddleware = createSnapsMethodMiddleware;
//# sourceMappingURL=middleware.cjs.map