From 25b9d1c3f84b41c956df2c124391538a140c4ace Mon Sep 17 00:00:00 2001 From: koxuan Date: Thu, 10 Aug 2023 09:54:55 +0800 Subject: [PATCH] feat: notifications on cronjob --- packages/snap/snap.manifest.json | 12 ++++++++++- packages/snap/src/index.ts | 37 +++++++++++++++++++++++++++++++- 2 files changed, 47 insertions(+), 2 deletions(-) diff --git a/packages/snap/snap.manifest.json b/packages/snap/snap.manifest.json index 3bcf5ef..2f1e0e5 100644 --- a/packages/snap/snap.manifest.json +++ b/packages/snap/snap.manifest.json @@ -7,7 +7,7 @@ "url": "https://github.com/MetaMask/template-snap-monorepo.git" }, "source": { - "shasum": "KL959iQJVvwp0xM1PUNFrSDwgcfA2qdNrhSS/eeA80Q=", + "shasum": "Kb4jQY5ygvWh4OQ+MOltTrvZ5KcoW9o7+fiANG1oiTw=", "location": { "npm": { "filePath": "dist/bundle.js", @@ -24,6 +24,16 @@ "dapps": true, "snaps": false }, + "endowment:cronjob": { + "jobs": [ + { + "expression": "* * * * *", + "request": { + "method": "execute" + } + } + ] + }, "endowment:transaction-insight": { "allowTransactionOrigin": true } diff --git a/packages/snap/src/index.ts b/packages/snap/src/index.ts index ec0ebde..b092277 100644 --- a/packages/snap/src/index.ts +++ b/packages/snap/src/index.ts @@ -1,6 +1,8 @@ import { OnRpcRequestHandler } from '@metamask/snaps-types'; -import { panel, text } from '@metamask/snaps-ui'; +import { panel, text, heading } from '@metamask/snaps-ui'; +import { rpcErrors } from '@metamask/rpc-errors'; +import type { OnCronjobHandler } from '@metamask/snaps-types'; /** * Handle incoming JSON-RPC requests, sent through `wallet_invokeSnap`. * @@ -26,3 +28,36 @@ export const onRpcRequest: OnRpcRequestHandler = ({ origin, request }) => { throw new Error('Method not found.'); } }; + + +/** + * Handle cronjob execution requests from MetaMask. This handler handles one + * method: + * + * - `execute`: The JSON-RPC method that is called by MetaMask when the cronjob + * is triggered. This method is specified in the snap manifest under the + * `endowment:cronjob` permission. If you want to support more methods (e.g., + * with different times), you can add them to the manifest there. + * + * @param params - The request parameters. + * @param params.request - The JSON-RPC request object. + * @returns The JSON-RPC response. + * @see https://docs.metamask.io/snaps/reference/exports/#oncronjob + */ + + +export const onCronjob: OnCronjobHandler = async ({ request }) => { + switch (request.method) { + case 'execute': + return snap.request({ + method: 'snap_notify', + params: { + type: 'native', + message: `Hello, world!`, + }, + }); + + default: + throw new Error('Method not found.'); + } +};