@metamask/snaps-rpc-methods
Version:
MetaMask Snaps JSON-RPC method implementations
85 lines • 2.93 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.cancelBackgroundEventHandler = void 0;
const rpc_errors_1 = require("@metamask/rpc-errors");
const superstruct_1 = require("@metamask/superstruct");
const endowments_1 = require("../endowments/index.cjs");
/**
* Cancel a background event created by
* [`snap_scheduleBackgroundEvent`](https://docs.metamask.io/snaps/reference/snaps-api/snap_schedulebackgroundevent).
*
* @example
* ```ts
* const id = await snap.request({
* method: 'snap_scheduleBackgroundEvent',
* params: {
* // ...
* },
* });
*
* // Later, when you want to cancel the background event:
* snap.request({
* method: 'snap_cancelBackgroundEvent',
* params: { id },
* });
* ```
*/
exports.cancelBackgroundEventHandler = {
implementation: getCancelBackgroundEventImplementation,
actionNames: [
'PermissionController:hasPermission',
'CronjobController:cancel',
],
};
const CancelBackgroundEventsParametersStruct = (0, superstruct_1.object)({
id: (0, superstruct_1.string)(),
});
/**
* The `snap_cancelBackgroundEvent` 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. Not used by this function.
* @param messenger - The messenger used to call controller actions.
* @returns Nothing.
*/
async function getCancelBackgroundEventImplementation(req, res, _next, end, _hooks, messenger) {
const { params, origin } = req;
if (!messenger.call('PermissionController:hasPermission', origin, endowments_1.SnapEndowments.Cronjob)) {
return end(rpc_errors_1.providerErrors.unauthorized());
}
try {
const validatedParams = getValidatedParams(params);
const { id } = validatedParams;
messenger.call('CronjobController:cancel', origin, id);
res.result = null;
}
catch (error) {
return end(error);
}
return end();
}
/**
* Validate the cancelBackgroundEvent 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 resolveInterface method parameter object.
*/
function getValidatedParams(params) {
try {
return (0, superstruct_1.create)(params, CancelBackgroundEventsParametersStruct);
}
catch (error) {
if (error instanceof superstruct_1.StructError) {
throw rpc_errors_1.rpcErrors.invalidParams({
message: `Invalid params: ${error.message}.`,
});
}
/* istanbul ignore next */
throw rpc_errors_1.rpcErrors.internal();
}
}
//# sourceMappingURL=cancelBackgroundEvent.cjs.map