@metamask/snaps-rpc-methods
Version:
MetaMask Snaps JSON-RPC method implementations
74 lines • 2.7 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.getValidatedParams = exports.invokeSnapSugar = exports.invokeSnapSugarHandler = void 0;
const rpc_errors_1 = require("@metamask/rpc-errors");
const utils_1 = require("@metamask/utils");
/**
* `wallet_invokeSnap` attempts to invoke an RPC method of the specified Snap.
*/
exports.invokeSnapSugarHandler = {
methodNames: ['wallet_invokeSnap'],
implementation: invokeSnapSugar,
hookNames: {
invokeSnap: true,
},
};
/**
* The `wallet_invokeSnap` method implementation.
* Effectively calls `wallet_snap` under the hood.
*
* @param req - The JSON-RPC request object.
* @param res - The JSON-RPC response object.
* @param _next - The `json-rpc-engine` "next" callback.
* @param end - The `json-rpc-engine` "end" callback.
* @param hooks - The RPC method hooks.
* @param hooks.invokeSnap - A function to invoke a snap designated by its parameters,
* bound to the requesting origin.
* @returns Nothing.
* @throws If the params are invalid.
*/
async function invokeSnapSugar(req,
// `InvokeSnapResult` is an alias for `Json` (which is the default type
// argument for `PendingJsonRpcResponse`), but that may not be the case in the
// future. We use `InvokeSnapResult` here to make it clear that this is the
// expected type of the result.
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-arguments
res, _next, end, { invokeSnap }) {
try {
const params = getValidatedParams(req.params);
res.result = await invokeSnap(params);
}
catch (error) {
return end(error);
}
return end();
}
exports.invokeSnapSugar = invokeSnapSugar;
/**
* Validates the wallet_invokeSnap method `params` and returns them cast to the correct
* type. Throws if validation fails.
*
* @param params - The unvalidated params object from the method request.
* @returns The validated method parameter object.
*/
function getValidatedParams(params) {
if (!(0, utils_1.isObject)(params)) {
throw rpc_errors_1.rpcErrors.invalidParams({
message: 'Expected params to be a single object.',
});
}
const { snapId, request } = params;
if (!snapId || typeof snapId !== 'string' || snapId === '') {
throw rpc_errors_1.rpcErrors.invalidParams({
message: 'Must specify a valid snap ID.',
});
}
if (!(0, utils_1.isObject)(request)) {
throw rpc_errors_1.rpcErrors.invalidParams({
message: 'Expected request to be a single object.',
});
}
return params;
}
exports.getValidatedParams = getValidatedParams;
//# sourceMappingURL=invokeSnapSugar.cjs.map