UNPKG

@metamask/snaps-rpc-methods

Version:
69 lines 2.38 kB
import { rpcErrors } from "@metamask/rpc-errors"; import { isObject } from "@metamask/utils"; /** * `wallet_invokeSnap` attempts to invoke an RPC method of the specified Snap. */ export const 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. */ export 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(); } /** * 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. */ export function getValidatedParams(params) { if (!isObject(params)) { throw rpcErrors.invalidParams({ message: 'Expected params to be a single object.', }); } const { snapId, request } = params; if (!snapId || typeof snapId !== 'string' || snapId === '') { throw rpcErrors.invalidParams({ message: 'Must specify a valid snap ID.', }); } if (!isObject(request)) { throw rpcErrors.invalidParams({ message: 'Expected request to be a single object.', }); } return params; } //# sourceMappingURL=invokeSnapSugar.mjs.map