@metamask/snaps-controllers 11.0.1 → 11.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +36 -1
- package/dist/cronjob/CronjobController.cjs +2 -2
- package/dist/cronjob/CronjobController.cjs.map +1 -1
- package/dist/cronjob/CronjobController.mjs +2 -2
- package/dist/cronjob/CronjobController.mjs.map +1 -1
- package/dist/insights/SnapInsightsController.cjs +1 -1
- package/dist/insights/SnapInsightsController.cjs.map +1 -1
- package/dist/insights/SnapInsightsController.mjs +1 -1
- package/dist/insights/SnapInsightsController.mjs.map +1 -1
- package/dist/interface/SnapInterfaceController.cjs +21 -11
- package/dist/interface/SnapInterfaceController.cjs.map +1 -1
- package/dist/interface/SnapInterfaceController.d.cts +17 -4
- package/dist/interface/SnapInterfaceController.d.cts.map +1 -1
- package/dist/interface/SnapInterfaceController.d.mts +17 -4
- package/dist/interface/SnapInterfaceController.d.mts.map +1 -1
- package/dist/interface/SnapInterfaceController.mjs +23 -13
- package/dist/interface/SnapInterfaceController.mjs.map +1 -1
- package/dist/interface/utils.cjs +124 -23
- package/dist/interface/utils.cjs.map +1 -1
- package/dist/interface/utils.d.cts +82 -2
- package/dist/interface/utils.d.cts.map +1 -1
- package/dist/interface/utils.d.mts +82 -2
- package/dist/interface/utils.d.mts.map +1 -1
- package/dist/interface/utils.mjs +120 -22
- package/dist/interface/utils.mjs.map +1 -1
- package/dist/multichain/MultichainRouter.cjs +3 -2
- package/dist/multichain/MultichainRouter.cjs.map +1 -1
- package/dist/multichain/MultichainRouter.d.cts +1 -15
- package/dist/multichain/MultichainRouter.d.cts.map +1 -1
- package/dist/multichain/MultichainRouter.d.mts +1 -15
- package/dist/multichain/MultichainRouter.d.mts.map +1 -1
- package/dist/multichain/MultichainRouter.mjs +3 -2
- package/dist/multichain/MultichainRouter.mjs.map +1 -1
- package/dist/snaps/SnapController.cjs +93 -74
- package/dist/snaps/SnapController.cjs.map +1 -1
- package/dist/snaps/SnapController.d.cts +6 -1
- package/dist/snaps/SnapController.d.cts.map +1 -1
- package/dist/snaps/SnapController.d.mts +6 -1
- package/dist/snaps/SnapController.d.mts.map +1 -1
- package/dist/snaps/SnapController.mjs +96 -77
- package/dist/snaps/SnapController.mjs.map +1 -1
- package/dist/snaps/constants.cjs +5 -1
- package/dist/snaps/constants.cjs.map +1 -1
- package/dist/snaps/constants.d.cts +4 -0
- package/dist/snaps/constants.d.cts.map +1 -1
- package/dist/snaps/constants.d.mts +4 -0
- package/dist/snaps/constants.d.mts.map +1 -1
- package/dist/snaps/constants.mjs +4 -0
- package/dist/snaps/constants.mjs.map +1 -1
- package/dist/utils.cjs +29 -1
- package/dist/utils.cjs.map +1 -1
- package/dist/utils.d.cts +20 -4
- package/dist/utils.d.cts.map +1 -1
- package/dist/utils.d.mts +20 -4
- package/dist/utils.d.mts.map +1 -1
- package/dist/utils.mjs +27 -0
- package/dist/utils.mjs.map +1 -1
- package/package.json +15 -25
package/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,39 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
+
## [11.2.0]
|
|
11
|
+
|
|
12
|
+
### Added
|
|
13
|
+
|
|
14
|
+
- Add support for market data to `onAssetsConversion` handler ([#3299](https://github.com/MetaMask/snaps/pull/3299))
|
|
15
|
+
- Add support for `onAssetHistoricalPrice` handler ([#3282](https://github.com/MetaMask/snaps/pull/3282))
|
|
16
|
+
|
|
17
|
+
### Changed
|
|
18
|
+
|
|
19
|
+
- Debounce persistence of state updates ([#3258](https://github.com/MetaMask/snaps/pull/3258))
|
|
20
|
+
|
|
21
|
+
### Fixed
|
|
22
|
+
|
|
23
|
+
- Inject `context` into `onUserInput` request ([#3298](https://github.com/MetaMask/snaps/pull/3298))
|
|
24
|
+
- Consider protocol Snaps when determining `isSupportedScope` ([#3284](https://github.com/MetaMask/snaps/pull/3284))
|
|
25
|
+
- Validate origin in `handleRequest` ([#3292](https://github.com/MetaMask/snaps/pull/3292))
|
|
26
|
+
- Update `name` and `symbol` to be optional in a fungible asset type ([#3300](https://github.com/MetaMask/snaps/pull/3300))
|
|
27
|
+
- Stop refreshing phishing list when updating interfaces ([#3272](https://github.com/MetaMask/snaps/pull/3272))
|
|
28
|
+
|
|
29
|
+
## [11.1.0]
|
|
30
|
+
|
|
31
|
+
### Added
|
|
32
|
+
|
|
33
|
+
- Add support for the `AddressInput` component ([#3129](https://github.com/MetaMask/snaps/pull/3129))
|
|
34
|
+
- Add support for the `AssetSelector` component ([#3166](https://github.com/MetaMask/snaps/pull/3166))
|
|
35
|
+
- Add mutex to `getSnapState` to prevent concurrent decryption ([#3234](https://github.com/MetaMask/snaps/pull/3234))
|
|
36
|
+
|
|
37
|
+
### Changed
|
|
38
|
+
|
|
39
|
+
- Increase Snap interface context size limit slightly ([#3246](https://github.com/MetaMask/snaps/pull/3246))
|
|
40
|
+
- Bump `@metamask/key-tree` from `10.1.0` to `10.1.1` ([#3254](https://github.com/MetaMask/snaps/pull/3254))
|
|
41
|
+
- Bump `nanoid` from `3.1.31` to `3.3.10` ([#3228](https://github.com/MetaMask/snaps/pull/3228), [#3255](https://github.com/MetaMask/snaps/pull/3255))
|
|
42
|
+
|
|
10
43
|
## [11.0.1]
|
|
11
44
|
|
|
12
45
|
### Fixed
|
|
@@ -670,7 +703,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
670
703
|
- The version of the package no longer needs to match the version of all other
|
|
671
704
|
MetaMask Snaps packages.
|
|
672
705
|
|
|
673
|
-
[Unreleased]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-controllers@11.0
|
|
706
|
+
[Unreleased]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-controllers@11.2.0...HEAD
|
|
707
|
+
[11.2.0]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-controllers@11.1.0...@metamask/snaps-controllers@11.2.0
|
|
708
|
+
[11.1.0]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-controllers@11.0.1...@metamask/snaps-controllers@11.1.0
|
|
674
709
|
[11.0.1]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-controllers@11.0.0...@metamask/snaps-controllers@11.0.1
|
|
675
710
|
[11.0.0]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-controllers@10.0.1...@metamask/snaps-controllers@11.0.0
|
|
676
711
|
[10.0.1]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-controllers@10.0.0...@metamask/snaps-controllers@10.0.1
|
|
@@ -315,7 +315,7 @@ async function _CronjobController_executeCronjob(job) {
|
|
|
315
315
|
__classPrivateFieldGet(this, _CronjobController_instances, "m", _CronjobController_updateJobLastRunState).call(this, job.id, Date.now());
|
|
316
316
|
await this.messagingSystem.call('SnapController:handleRequest', {
|
|
317
317
|
snapId: job.snapId,
|
|
318
|
-
origin: '',
|
|
318
|
+
origin: 'metamask',
|
|
319
319
|
handler: snaps_utils_1.HandlerType.OnCronjob,
|
|
320
320
|
request: job.request,
|
|
321
321
|
});
|
|
@@ -331,7 +331,7 @@ async function _CronjobController_executeCronjob(job) {
|
|
|
331
331
|
this.messagingSystem
|
|
332
332
|
.call('SnapController:handleRequest', {
|
|
333
333
|
snapId: event.snapId,
|
|
334
|
-
origin: '',
|
|
334
|
+
origin: 'metamask',
|
|
335
335
|
handler: snaps_utils_1.HandlerType.OnCronjob,
|
|
336
336
|
request: event.request,
|
|
337
337
|
})
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"CronjobController.cjs","sourceRoot":"","sources":["../../src/cronjob/CronjobController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAKA,+DAA2D;AAE3D,mEAGqC;AAMrC,uDAK+B;AAC/B,2CAAmE;AACnE,iCAAkC;AAClC,iCAAiC;AACjC,mCAAgC;AAWhC,oCAAsC;AACtC,8CAAuC;AAmD1B,QAAA,aAAa,GAA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vB,MAAM,IAAI,GAAG,IAAI,IAAI,CAAC,IAAI,CAAC,CAAC;QAC5B,IAAI,IAAI,CAAC,OAAO,EAAE,GAAG,GAAG,CAAC,OAAO,EAAE,EAAE,CAAC;YACnC,mCAAmC;YACnC,IAAI,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE;gBACpB,OAAO,KAAK,CAAC,MAAM,CAAC,SAAS,CAAC,EAAE,CAAC,CAAC;YACpC,CAAC,CAAC,CAAC;YAEH,IAAA,wBAAU,EACR,6BAA6B,SAAS,CAAC,EAAE,0CAA0C,CACpF,CAAC;QACJ,CAAC;aAAM,CAAC;YACN,uBAAA,IAAI,6EAAsB,MAA1B,IAAI,EAAuB,SAAS,CAAC,CAAC;QACxC,CAAC;IACH,CAAC;AACH,CAAC","sourcesContent":["import type {\n RestrictedMessenger,\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n} from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport type { GetPermissions } from '@metamask/permission-controller';\nimport {\n getCronjobCaveatJobs,\n SnapEndowments,\n} from '@metamask/snaps-rpc-methods';\nimport type { BackgroundEvent, SnapId } from '@metamask/snaps-sdk';\nimport type {\n TruncatedSnap,\n CronjobSpecification,\n} from '@metamask/snaps-utils';\nimport {\n HandlerType,\n parseCronExpression,\n logError,\n logWarning,\n} from '@metamask/snaps-utils';\nimport { assert, Duration, inMilliseconds } from '@metamask/utils';\nimport { castDraft } from 'immer';\nimport { DateTime } from 'luxon';\nimport { nanoid } from 'nanoid';\n\nimport type {\n GetAllSnaps,\n HandleSnapRequest,\n SnapDisabled,\n SnapEnabled,\n SnapInstalled,\n SnapUninstalled,\n SnapUpdated,\n} from '..';\nimport { getRunnableSnaps } from '..';\nimport { Timer } from '../snaps/Timer';\n\nexport type CronjobControllerGetStateAction = ControllerGetStateAction<\n typeof controllerName,\n CronjobControllerState\n>;\nexport type CronjobControllerStateChangeEvent = ControllerStateChangeEvent<\n typeof controllerName,\n CronjobControllerState\n>;\n\nexport type ScheduleBackgroundEvent = {\n type: `${typeof controllerName}:scheduleBackgroundEvent`;\n handler: CronjobController['scheduleBackgroundEvent'];\n};\n\nexport type CancelBackgroundEvent = {\n type: `${typeof controllerName}:cancelBackgroundEvent`;\n handler: CronjobController['cancelBackgroundEvent'];\n};\n\nexport type GetBackgroundEvents = {\n type: `${typeof controllerName}:getBackgroundEvents`;\n handler: CronjobController['getBackgroundEvents'];\n};\n\nexport type CronjobControllerActions =\n | GetAllSnaps\n | HandleSnapRequest\n | GetPermissions\n | CronjobControllerGetStateAction\n | ScheduleBackgroundEvent\n | CancelBackgroundEvent\n | GetBackgroundEvents;\n\nexport type CronjobControllerEvents =\n | SnapInstalled\n | SnapUninstalled\n | SnapUpdated\n | SnapEnabled\n | SnapDisabled\n | CronjobControllerStateChangeEvent;\n\nexport type CronjobControllerMessenger = RestrictedMessenger<\n typeof controllerName,\n CronjobControllerActions,\n CronjobControllerEvents,\n CronjobControllerActions['type'],\n CronjobControllerEvents['type']\n>;\n\nexport const DAILY_TIMEOUT = inMilliseconds(24, Duration.Hour);\n\nexport type CronjobControllerArgs = {\n messenger: CronjobControllerMessenger;\n /**\n * Persisted state that will be used for rehydration.\n */\n state?: CronjobControllerState;\n};\n\nexport type Cronjob = {\n timer?: Timer;\n id: string;\n snapId: SnapId;\n} & CronjobSpecification;\n\nexport type StoredJobInformation = {\n lastRun: number;\n};\n\nexport type CronjobControllerState = {\n jobs: Record<string, StoredJobInformation>;\n events: Record<string, BackgroundEvent>;\n};\n\nconst controllerName = 'CronjobController';\n\n/**\n * Use this controller to register and schedule periodically executed jobs\n * using RPC method hooks.\n */\nexport class CronjobController extends BaseController<\n typeof controllerName,\n CronjobControllerState,\n CronjobControllerMessenger\n> {\n #dailyTimer!: Timer;\n\n readonly #timers: Map<string, Timer>;\n\n // Mapping from jobId to snapId\n readonly #snapIds: Map<string, SnapId>;\n\n constructor({ messenger, state }: CronjobControllerArgs) {\n super({\n messenger,\n metadata: {\n jobs: { persist: true, anonymous: false },\n events: { persist: true, anonymous: false },\n },\n name: controllerName,\n state: {\n jobs: {},\n events: {},\n ...state,\n },\n });\n this.#timers = new Map();\n this.#snapIds = new Map();\n\n this._handleSnapRegisterEvent = this._handleSnapRegisterEvent.bind(this);\n this._handleSnapUnregisterEvent =\n this._handleSnapUnregisterEvent.bind(this);\n this._handleEventSnapUpdated = this._handleEventSnapUpdated.bind(this);\n this._handleSnapDisabledEvent = this._handleSnapDisabledEvent.bind(this);\n this._handleSnapEnabledEvent = this._handleSnapEnabledEvent.bind(this);\n // Subscribe to Snap events\n /* eslint-disable @typescript-eslint/unbound-method */\n\n this.messagingSystem.subscribe(\n 'SnapController:snapInstalled',\n this._handleSnapRegisterEvent,\n );\n\n this.messagingSystem.subscribe(\n 'SnapController:snapUninstalled',\n this._handleSnapUnregisterEvent,\n );\n\n this.messagingSystem.subscribe(\n 'SnapController:snapEnabled',\n this._handleSnapEnabledEvent,\n );\n\n this.messagingSystem.subscribe(\n 'SnapController:snapDisabled',\n this._handleSnapDisabledEvent,\n );\n\n this.messagingSystem.subscribe(\n 'SnapController:snapUpdated',\n this._handleEventSnapUpdated,\n );\n /* eslint-enable @typescript-eslint/unbound-method */\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:scheduleBackgroundEvent`,\n (...args) => this.scheduleBackgroundEvent(...args),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:cancelBackgroundEvent`,\n (...args) => this.cancelBackgroundEvent(...args),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:getBackgroundEvents`,\n (...args) => this.getBackgroundEvents(...args),\n );\n\n this.dailyCheckIn().catch((error) => {\n logError(error);\n });\n\n this.#rescheduleBackgroundEvents(Object.values(this.state.events));\n }\n\n /**\n * Retrieve all cronjob specifications for all runnable snaps.\n *\n * @returns Array of Cronjob specifications.\n */\n #getAllJobs(): Cronjob[] {\n const snaps = this.messagingSystem.call('SnapController:getAll');\n const filteredSnaps = getRunnableSnaps(snaps);\n\n const jobs = filteredSnaps.map((snap) => this.#getSnapJobs(snap.id));\n return jobs.flat().filter((job) => job !== undefined) as Cronjob[];\n }\n\n /**\n * Retrieve all Cronjob specifications for a Snap.\n *\n * @param snapId - ID of a Snap.\n * @returns Array of Cronjob specifications.\n */\n #getSnapJobs(snapId: SnapId): Cronjob[] | undefined {\n const permissions = this.messagingSystem.call(\n 'PermissionController:getPermissions',\n snapId,\n );\n\n const permission = permissions?.[SnapEndowments.Cronjob];\n const definitions = getCronjobCaveatJobs(permission);\n\n return definitions?.map((definition, idx) => {\n return { ...definition, id: `${snapId}-${idx}`, snapId };\n });\n }\n\n /**\n * Register cron jobs for a given snap by getting specification from a permission caveats.\n * Once registered, each job will be scheduled.\n *\n * @param snapId - ID of a snap.\n */\n register(snapId: SnapId) {\n const jobs = this.#getSnapJobs(snapId);\n jobs?.forEach((job) => this.#schedule(job));\n }\n\n /**\n * Schedule a new job.\n * This will interpret the cron expression and tell the timer to execute the job\n * at the next suitable point in time.\n * Job last run state will be initialized afterwards.\n *\n * Note: Schedule will be skipped if the job's execution time is too far in the future and\n * will be revisited on a daily check.\n *\n * @param job - Cronjob specification.\n */\n #schedule(job: Cronjob) {\n if (this.#timers.has(job.id)) {\n return;\n }\n\n const parsed = parseCronExpression(job.expression);\n const next = parsed.next();\n const now = new Date();\n const ms = next.getTime() - now.getTime();\n\n // Don't schedule this job yet as it is too far in the future\n if (ms > DAILY_TIMEOUT) {\n return;\n }\n\n const timer = new Timer(ms);\n timer.start(() => {\n this.#executeCronjob(job).catch((error) => {\n // TODO: Decide how to handle errors.\n logError(error);\n });\n\n this.#timers.delete(job.id);\n this.#schedule(job);\n });\n\n if (!this.state.jobs[job.id]?.lastRun) {\n this.#updateJobLastRunState(job.id, 0); // 0 for init, never ran actually\n }\n\n this.#timers.set(job.id, timer);\n this.#snapIds.set(job.id, job.snapId);\n }\n\n /**\n * Execute job.\n *\n * @param job - Cronjob specification.\n */\n async #executeCronjob(job: Cronjob) {\n this.#updateJobLastRunState(job.id, Date.now());\n await this.messagingSystem.call('SnapController:handleRequest', {\n snapId: job.snapId,\n origin: '',\n handler: HandlerType.OnCronjob,\n request: job.request,\n });\n }\n\n /**\n * Schedule a background event.\n *\n * @param backgroundEventWithoutId - Background event.\n * @returns An id representing the background event.\n */\n scheduleBackgroundEvent(\n backgroundEventWithoutId: Omit<BackgroundEvent, 'id' | 'scheduledAt'>,\n ) {\n // Remove millisecond precision and convert to UTC.\n const scheduledAt = DateTime.fromJSDate(new Date())\n .toUTC()\n .startOf('second')\n .toISO({\n suppressMilliseconds: true,\n });\n\n assert(scheduledAt);\n\n const event = {\n ...backgroundEventWithoutId,\n id: nanoid(),\n scheduledAt,\n };\n\n this.#setUpBackgroundEvent(event);\n this.update((state) => {\n state.events[event.id] = castDraft(event);\n });\n\n return event.id;\n }\n\n /**\n * Cancel a background event.\n *\n * @param origin - The origin making the cancel call.\n * @param id - The id of the background event to cancel.\n * @throws If the event does not exist.\n */\n cancelBackgroundEvent(origin: string, id: string) {\n assert(\n this.state.events[id],\n `A background event with the id of \"${id}\" does not exist.`,\n );\n\n assert(\n this.state.events[id].snapId === origin,\n 'Only the origin that scheduled this event can cancel it.',\n );\n\n const timer = this.#timers.get(id);\n timer?.cancel();\n this.#timers.delete(id);\n this.#snapIds.delete(id);\n this.update((state) => {\n delete state.events[id];\n });\n }\n\n /**\n * A helper function to handle setup of the background event.\n *\n * @param event - A background event.\n */\n #setUpBackgroundEvent(event: BackgroundEvent) {\n const date = new Date(event.date);\n const now = new Date();\n const ms = date.getTime() - now.getTime();\n\n if (ms <= 0) {\n throw new Error('Cannot schedule an event in the past.');\n }\n\n const timer = new Timer(ms);\n timer.start(() => {\n this.messagingSystem\n .call('SnapController:handleRequest', {\n snapId: event.snapId,\n origin: '',\n handler: HandlerType.OnCronjob,\n request: event.request,\n })\n .catch((error) => {\n logError(error);\n });\n\n this.#timers.delete(event.id);\n this.#snapIds.delete(event.id);\n this.update((state) => {\n delete state.events[event.id];\n });\n });\n\n this.#timers.set(event.id, timer);\n this.#snapIds.set(event.id, event.snapId);\n }\n\n /**\n * Get a list of a Snap's background events.\n *\n * @param snapId - The id of the Snap to fetch background events for.\n * @returns An array of background events.\n */\n getBackgroundEvents(snapId: SnapId): BackgroundEvent[] {\n return Object.values(this.state.events).filter(\n (snapEvent) => snapEvent.snapId === snapId,\n );\n }\n\n /**\n * Unregister all jobs and background events related to the given snapId.\n *\n * @param snapId - ID of a snap.\n * @param skipEvents - Whether the unregistration process should skip scheduled background events.\n */\n unregister(snapId: SnapId, skipEvents = false) {\n const jobs = [...this.#snapIds.entries()].filter(\n ([_, jobSnapId]) => jobSnapId === snapId,\n );\n\n if (jobs.length) {\n const eventIds: string[] = [];\n jobs.forEach(([id]) => {\n const timer = this.#timers.get(id);\n if (timer) {\n timer.cancel();\n this.#timers.delete(id);\n this.#snapIds.delete(id);\n if (!skipEvents && this.state.events[id]) {\n eventIds.push(id);\n }\n }\n });\n\n if (eventIds.length > 0) {\n this.update((state) => {\n eventIds.forEach((id) => {\n delete state.events[id];\n });\n });\n }\n }\n }\n\n /**\n * Update time of a last run for the Cronjob specified by ID.\n *\n * @param jobId - ID of a cron job.\n * @param lastRun - Unix timestamp when the job was last ran.\n */\n #updateJobLastRunState(jobId: string, lastRun: number) {\n this.update((state) => {\n state.jobs[jobId] = {\n lastRun,\n };\n });\n }\n\n /**\n * Runs every 24 hours to check if new jobs need to be scheduled.\n *\n * This is necessary for longer running jobs that execute with more than 24 hours between them.\n */\n async dailyCheckIn() {\n const jobs = this.#getAllJobs();\n\n for (const job of jobs) {\n const parsed = parseCronExpression(job.expression);\n const lastRun = this.state.jobs[job.id]?.lastRun;\n // If a job was supposed to run while we were shut down but wasn't we run it now\n if (\n lastRun !== undefined &&\n parsed.hasPrev() &&\n parsed.prev().getTime() > lastRun\n ) {\n await this.#executeCronjob(job);\n }\n\n // Try scheduling, will fail if an existing scheduled job is found\n this.#schedule(job);\n }\n\n this.#dailyTimer = new Timer(DAILY_TIMEOUT);\n this.#dailyTimer.start(() => {\n this.dailyCheckIn().catch((error) => {\n // TODO: Decide how to handle errors.\n logError(error);\n });\n });\n }\n\n /**\n * Reschedule background events.\n *\n * @param backgroundEvents - A list of background events to reschdule.\n */\n #rescheduleBackgroundEvents(backgroundEvents: BackgroundEvent[]) {\n for (const snapEvent of backgroundEvents) {\n const { date } = snapEvent;\n const now = new Date();\n const then = new Date(date);\n if (then.getTime() < now.getTime()) {\n // Remove expired events from state\n this.update((state) => {\n delete state.events[snapEvent.id];\n });\n\n logWarning(\n `Background event with id \"${snapEvent.id}\" not scheduled as its date has expired.`,\n );\n } else {\n this.#setUpBackgroundEvent(snapEvent);\n }\n }\n }\n\n /**\n * Run controller teardown process and unsubscribe from Snap events.\n */\n destroy() {\n super.destroy();\n\n /* eslint-disable @typescript-eslint/unbound-method */\n this.messagingSystem.unsubscribe(\n 'SnapController:snapInstalled',\n this._handleSnapRegisterEvent,\n );\n\n this.messagingSystem.unsubscribe(\n 'SnapController:snapUninstalled',\n this._handleSnapUnregisterEvent,\n );\n\n this.messagingSystem.unsubscribe(\n 'SnapController:snapEnabled',\n this._handleSnapEnabledEvent,\n );\n\n this.messagingSystem.unsubscribe(\n 'SnapController:snapDisabled',\n this._handleSnapDisabledEvent,\n );\n\n this.messagingSystem.unsubscribe(\n 'SnapController:snapUpdated',\n this._handleEventSnapUpdated,\n );\n /* eslint-enable @typescript-eslint/unbound-method */\n\n this.#snapIds.forEach((snapId) => this.unregister(snapId));\n }\n\n /**\n * Handle events that should cause cronjobs to be registered.\n *\n * @param snap - Basic Snap information.\n */\n // TODO: Either fix this lint violation or explain why it's necessary to\n // ignore.\n // eslint-disable-next-line no-restricted-syntax\n private _handleSnapRegisterEvent(snap: TruncatedSnap) {\n this.register(snap.id);\n }\n\n /**\n * Handle events that could cause cronjobs to be registered\n * and for background events to be rescheduled.\n *\n * @param snap - Basic Snap information.\n */\n // TODO: Either fix this lint violation or explain why it's necessary to\n // ignore.\n // eslint-disable-next-line no-restricted-syntax\n private _handleSnapEnabledEvent(snap: TruncatedSnap) {\n const events = this.getBackgroundEvents(snap.id);\n this.#rescheduleBackgroundEvents(events);\n this.register(snap.id);\n }\n\n /**\n * Handle events that should cause cronjobs and background events to be unregistered.\n *\n * @param snap - Basic Snap information.\n */\n // TODO: Either fix this lint violation or explain why it's necessary to\n // ignore.\n // eslint-disable-next-line no-restricted-syntax\n private _handleSnapUnregisterEvent(snap: TruncatedSnap) {\n this.unregister(snap.id);\n }\n\n /**\n * Handle events that should cause cronjobs and background events to be unregistered.\n *\n * @param snap - Basic Snap information.\n */\n // TODO: Either fix this lint violation or explain why it's necessary to\n // ignore.\n // eslint-disable-next-line no-restricted-syntax\n private _handleSnapDisabledEvent(snap: TruncatedSnap) {\n this.unregister(snap.id, true);\n }\n\n /**\n * Handle cron jobs on 'snapUpdated' event.\n *\n * @param snap - Basic Snap information.\n */\n // TODO: Either fix this lint violation or explain why it's necessary to\n // ignore.\n // eslint-disable-next-line no-restricted-syntax\n private _handleEventSnapUpdated(snap: TruncatedSnap) {\n this.unregister(snap.id);\n this.register(snap.id);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"CronjobController.cjs","sourceRoot":"","sources":["../../src/cronjob/CronjobController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAKA,+DAA2D;AAE3D,mEAGqC;AAMrC,uDAK+B;AAC/B,2CAAmE;AACnE,iCAAkC;AAClC,iCAAiC;AACjC,mCAAgC;AAWhC,oCAAsC;AACtC,8CAAuC;AAmD1B,QAAA,aAAa,GAAG,IAAA,sBAAc,EAAC,EAAE,EAAE,gBAAQ,CAAC,IAAI,CAAC,CAAC;AAyB/D,MAAM,cAAc,GAAG,mBAAmB,CAAC;AAE3C;;;GAGG;AACH,MAAa,iBAAkB,SAAQ,gCAItC;IAQC,YAAY,EAAE,SAAS,EAAE,KAAK,EAAyB;QACrD,KAAK,CAAC;YACJ,SAAS;YACT,QAAQ,EAAE;gBACR,IAAI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AAE,CAAC,CAAC;YACpC,CAAC,CAAC,CAAC;YAEH,IAAA,wBAAU,EACR,6BAA6B,SAAS,CAAC,EAAE,0CAA0C,CACpF,CAAC;QACJ,CAAC;aAAM,CAAC;YACN,uBAAA,IAAI,6EAAsB,MAA1B,IAAI,EAAuB,SAAS,CAAC,CAAC;QACxC,CAAC;IACH,CAAC;AACH,CAAC","sourcesContent":["import type {\n RestrictedMessenger,\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n} from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport type { GetPermissions } from '@metamask/permission-controller';\nimport {\n getCronjobCaveatJobs,\n SnapEndowments,\n} from '@metamask/snaps-rpc-methods';\nimport type { BackgroundEvent, SnapId } from '@metamask/snaps-sdk';\nimport type {\n TruncatedSnap,\n CronjobSpecification,\n} from '@metamask/snaps-utils';\nimport {\n HandlerType,\n parseCronExpression,\n logError,\n logWarning,\n} from '@metamask/snaps-utils';\nimport { assert, Duration, inMilliseconds } from '@metamask/utils';\nimport { castDraft } from 'immer';\nimport { DateTime } from 'luxon';\nimport { nanoid } from 'nanoid';\n\nimport type {\n GetAllSnaps,\n HandleSnapRequest,\n SnapDisabled,\n SnapEnabled,\n SnapInstalled,\n SnapUninstalled,\n SnapUpdated,\n} from '..';\nimport { getRunnableSnaps } from '..';\nimport { Timer } from '../snaps/Timer';\n\nexport type CronjobControllerGetStateAction = ControllerGetStateAction<\n typeof controllerName,\n CronjobControllerState\n>;\nexport type CronjobControllerStateChangeEvent = ControllerStateChangeEvent<\n typeof controllerName,\n CronjobControllerState\n>;\n\nexport type ScheduleBackgroundEvent = {\n type: `${typeof controllerName}:scheduleBackgroundEvent`;\n handler: CronjobController['scheduleBackgroundEvent'];\n};\n\nexport type CancelBackgroundEvent = {\n type: `${typeof controllerName}:cancelBackgroundEvent`;\n handler: CronjobController['cancelBackgroundEvent'];\n};\n\nexport type GetBackgroundEvents = {\n type: `${typeof controllerName}:getBackgroundEvents`;\n handler: CronjobController['getBackgroundEvents'];\n};\n\nexport type CronjobControllerActions =\n | GetAllSnaps\n | HandleSnapRequest\n | GetPermissions\n | CronjobControllerGetStateAction\n | ScheduleBackgroundEvent\n | CancelBackgroundEvent\n | GetBackgroundEvents;\n\nexport type CronjobControllerEvents =\n | SnapInstalled\n | SnapUninstalled\n | SnapUpdated\n | SnapEnabled\n | SnapDisabled\n | CronjobControllerStateChangeEvent;\n\nexport type CronjobControllerMessenger = RestrictedMessenger<\n typeof controllerName,\n CronjobControllerActions,\n CronjobControllerEvents,\n CronjobControllerActions['type'],\n CronjobControllerEvents['type']\n>;\n\nexport const DAILY_TIMEOUT = inMilliseconds(24, Duration.Hour);\n\nexport type CronjobControllerArgs = {\n messenger: CronjobControllerMessenger;\n /**\n * Persisted state that will be used for rehydration.\n */\n state?: CronjobControllerState;\n};\n\nexport type Cronjob = {\n timer?: Timer;\n id: string;\n snapId: SnapId;\n} & CronjobSpecification;\n\nexport type StoredJobInformation = {\n lastRun: number;\n};\n\nexport type CronjobControllerState = {\n jobs: Record<string, StoredJobInformation>;\n events: Record<string, BackgroundEvent>;\n};\n\nconst controllerName = 'CronjobController';\n\n/**\n * Use this controller to register and schedule periodically executed jobs\n * using RPC method hooks.\n */\nexport class CronjobController extends BaseController<\n typeof controllerName,\n CronjobControllerState,\n CronjobControllerMessenger\n> {\n #dailyTimer!: Timer;\n\n readonly #timers: Map<string, Timer>;\n\n // Mapping from jobId to snapId\n readonly #snapIds: Map<string, SnapId>;\n\n constructor({ messenger, state }: CronjobControllerArgs) {\n super({\n messenger,\n metadata: {\n jobs: { persist: true, anonymous: false },\n events: { persist: true, anonymous: false },\n },\n name: controllerName,\n state: {\n jobs: {},\n events: {},\n ...state,\n },\n });\n this.#timers = new Map();\n this.#snapIds = new Map();\n\n this._handleSnapRegisterEvent = this._handleSnapRegisterEvent.bind(this);\n this._handleSnapUnregisterEvent =\n this._handleSnapUnregisterEvent.bind(this);\n this._handleEventSnapUpdated = this._handleEventSnapUpdated.bind(this);\n this._handleSnapDisabledEvent = this._handleSnapDisabledEvent.bind(this);\n this._handleSnapEnabledEvent = this._handleSnapEnabledEvent.bind(this);\n // Subscribe to Snap events\n /* eslint-disable @typescript-eslint/unbound-method */\n\n this.messagingSystem.subscribe(\n 'SnapController:snapInstalled',\n this._handleSnapRegisterEvent,\n );\n\n this.messagingSystem.subscribe(\n 'SnapController:snapUninstalled',\n this._handleSnapUnregisterEvent,\n );\n\n this.messagingSystem.subscribe(\n 'SnapController:snapEnabled',\n this._handleSnapEnabledEvent,\n );\n\n this.messagingSystem.subscribe(\n 'SnapController:snapDisabled',\n this._handleSnapDisabledEvent,\n );\n\n this.messagingSystem.subscribe(\n 'SnapController:snapUpdated',\n this._handleEventSnapUpdated,\n );\n /* eslint-enable @typescript-eslint/unbound-method */\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:scheduleBackgroundEvent`,\n (...args) => this.scheduleBackgroundEvent(...args),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:cancelBackgroundEvent`,\n (...args) => this.cancelBackgroundEvent(...args),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:getBackgroundEvents`,\n (...args) => this.getBackgroundEvents(...args),\n );\n\n this.dailyCheckIn().catch((error) => {\n logError(error);\n });\n\n this.#rescheduleBackgroundEvents(Object.values(this.state.events));\n }\n\n /**\n * Retrieve all cronjob specifications for all runnable snaps.\n *\n * @returns Array of Cronjob specifications.\n */\n #getAllJobs(): Cronjob[] {\n const snaps = this.messagingSystem.call('SnapController:getAll');\n const filteredSnaps = getRunnableSnaps(snaps);\n\n const jobs = filteredSnaps.map((snap) => this.#getSnapJobs(snap.id));\n return jobs.flat().filter((job) => job !== undefined) as Cronjob[];\n }\n\n /**\n * Retrieve all Cronjob specifications for a Snap.\n *\n * @param snapId - ID of a Snap.\n * @returns Array of Cronjob specifications.\n */\n #getSnapJobs(snapId: SnapId): Cronjob[] | undefined {\n const permissions = this.messagingSystem.call(\n 'PermissionController:getPermissions',\n snapId,\n );\n\n const permission = permissions?.[SnapEndowments.Cronjob];\n const definitions = getCronjobCaveatJobs(permission);\n\n return definitions?.map((definition, idx) => {\n return { ...definition, id: `${snapId}-${idx}`, snapId };\n });\n }\n\n /**\n * Register cron jobs for a given snap by getting specification from a permission caveats.\n * Once registered, each job will be scheduled.\n *\n * @param snapId - ID of a snap.\n */\n register(snapId: SnapId) {\n const jobs = this.#getSnapJobs(snapId);\n jobs?.forEach((job) => this.#schedule(job));\n }\n\n /**\n * Schedule a new job.\n * This will interpret the cron expression and tell the timer to execute the job\n * at the next suitable point in time.\n * Job last run state will be initialized afterwards.\n *\n * Note: Schedule will be skipped if the job's execution time is too far in the future and\n * will be revisited on a daily check.\n *\n * @param job - Cronjob specification.\n */\n #schedule(job: Cronjob) {\n if (this.#timers.has(job.id)) {\n return;\n }\n\n const parsed = parseCronExpression(job.expression);\n const next = parsed.next();\n const now = new Date();\n const ms = next.getTime() - now.getTime();\n\n // Don't schedule this job yet as it is too far in the future\n if (ms > DAILY_TIMEOUT) {\n return;\n }\n\n const timer = new Timer(ms);\n timer.start(() => {\n this.#executeCronjob(job).catch((error) => {\n // TODO: Decide how to handle errors.\n logError(error);\n });\n\n this.#timers.delete(job.id);\n this.#schedule(job);\n });\n\n if (!this.state.jobs[job.id]?.lastRun) {\n this.#updateJobLastRunState(job.id, 0); // 0 for init, never ran actually\n }\n\n this.#timers.set(job.id, timer);\n this.#snapIds.set(job.id, job.snapId);\n }\n\n /**\n * Execute job.\n *\n * @param job - Cronjob specification.\n */\n async #executeCronjob(job: Cronjob) {\n this.#updateJobLastRunState(job.id, Date.now());\n await this.messagingSystem.call('SnapController:handleRequest', {\n snapId: job.snapId,\n origin: 'metamask',\n handler: HandlerType.OnCronjob,\n request: job.request,\n });\n }\n\n /**\n * Schedule a background event.\n *\n * @param backgroundEventWithoutId - Background event.\n * @returns An id representing the background event.\n */\n scheduleBackgroundEvent(\n backgroundEventWithoutId: Omit<BackgroundEvent, 'id' | 'scheduledAt'>,\n ) {\n // Remove millisecond precision and convert to UTC.\n const scheduledAt = DateTime.fromJSDate(new Date())\n .toUTC()\n .startOf('second')\n .toISO({\n suppressMilliseconds: true,\n });\n\n assert(scheduledAt);\n\n const event = {\n ...backgroundEventWithoutId,\n id: nanoid(),\n scheduledAt,\n };\n\n this.#setUpBackgroundEvent(event);\n this.update((state) => {\n state.events[event.id] = castDraft(event);\n });\n\n return event.id;\n }\n\n /**\n * Cancel a background event.\n *\n * @param origin - The origin making the cancel call.\n * @param id - The id of the background event to cancel.\n * @throws If the event does not exist.\n */\n cancelBackgroundEvent(origin: string, id: string) {\n assert(\n this.state.events[id],\n `A background event with the id of \"${id}\" does not exist.`,\n );\n\n assert(\n this.state.events[id].snapId === origin,\n 'Only the origin that scheduled this event can cancel it.',\n );\n\n const timer = this.#timers.get(id);\n timer?.cancel();\n this.#timers.delete(id);\n this.#snapIds.delete(id);\n this.update((state) => {\n delete state.events[id];\n });\n }\n\n /**\n * A helper function to handle setup of the background event.\n *\n * @param event - A background event.\n */\n #setUpBackgroundEvent(event: BackgroundEvent) {\n const date = new Date(event.date);\n const now = new Date();\n const ms = date.getTime() - now.getTime();\n\n if (ms <= 0) {\n throw new Error('Cannot schedule an event in the past.');\n }\n\n const timer = new Timer(ms);\n timer.start(() => {\n this.messagingSystem\n .call('SnapController:handleRequest', {\n snapId: event.snapId,\n origin: 'metamask',\n handler: HandlerType.OnCronjob,\n request: event.request,\n })\n .catch((error) => {\n logError(error);\n });\n\n this.#timers.delete(event.id);\n this.#snapIds.delete(event.id);\n this.update((state) => {\n delete state.events[event.id];\n });\n });\n\n this.#timers.set(event.id, timer);\n this.#snapIds.set(event.id, event.snapId);\n }\n\n /**\n * Get a list of a Snap's background events.\n *\n * @param snapId - The id of the Snap to fetch background events for.\n * @returns An array of background events.\n */\n getBackgroundEvents(snapId: SnapId): BackgroundEvent[] {\n return Object.values(this.state.events).filter(\n (snapEvent) => snapEvent.snapId === snapId,\n );\n }\n\n /**\n * Unregister all jobs and background events related to the given snapId.\n *\n * @param snapId - ID of a snap.\n * @param skipEvents - Whether the unregistration process should skip scheduled background events.\n */\n unregister(snapId: SnapId, skipEvents = false) {\n const jobs = [...this.#snapIds.entries()].filter(\n ([_, jobSnapId]) => jobSnapId === snapId,\n );\n\n if (jobs.length) {\n const eventIds: string[] = [];\n jobs.forEach(([id]) => {\n const timer = this.#timers.get(id);\n if (timer) {\n timer.cancel();\n this.#timers.delete(id);\n this.#snapIds.delete(id);\n if (!skipEvents && this.state.events[id]) {\n eventIds.push(id);\n }\n }\n });\n\n if (eventIds.length > 0) {\n this.update((state) => {\n eventIds.forEach((id) => {\n delete state.events[id];\n });\n });\n }\n }\n }\n\n /**\n * Update time of a last run for the Cronjob specified by ID.\n *\n * @param jobId - ID of a cron job.\n * @param lastRun - Unix timestamp when the job was last ran.\n */\n #updateJobLastRunState(jobId: string, lastRun: number) {\n this.update((state) => {\n state.jobs[jobId] = {\n lastRun,\n };\n });\n }\n\n /**\n * Runs every 24 hours to check if new jobs need to be scheduled.\n *\n * This is necessary for longer running jobs that execute with more than 24 hours between them.\n */\n async dailyCheckIn() {\n const jobs = this.#getAllJobs();\n\n for (const job of jobs) {\n const parsed = parseCronExpression(job.expression);\n const lastRun = this.state.jobs[job.id]?.lastRun;\n // If a job was supposed to run while we were shut down but wasn't we run it now\n if (\n lastRun !== undefined &&\n parsed.hasPrev() &&\n parsed.prev().getTime() > lastRun\n ) {\n await this.#executeCronjob(job);\n }\n\n // Try scheduling, will fail if an existing scheduled job is found\n this.#schedule(job);\n }\n\n this.#dailyTimer = new Timer(DAILY_TIMEOUT);\n this.#dailyTimer.start(() => {\n this.dailyCheckIn().catch((error) => {\n // TODO: Decide how to handle errors.\n logError(error);\n });\n });\n }\n\n /**\n * Reschedule background events.\n *\n * @param backgroundEvents - A list of background events to reschdule.\n */\n #rescheduleBackgroundEvents(backgroundEvents: BackgroundEvent[]) {\n for (const snapEvent of backgroundEvents) {\n const { date } = snapEvent;\n const now = new Date();\n const then = new Date(date);\n if (then.getTime() < now.getTime()) {\n // Remove expired events from state\n this.update((state) => {\n delete state.events[snapEvent.id];\n });\n\n logWarning(\n `Background event with id \"${snapEvent.id}\" not scheduled as its date has expired.`,\n );\n } else {\n this.#setUpBackgroundEvent(snapEvent);\n }\n }\n }\n\n /**\n * Run controller teardown process and unsubscribe from Snap events.\n */\n destroy() {\n super.destroy();\n\n /* eslint-disable @typescript-eslint/unbound-method */\n this.messagingSystem.unsubscribe(\n 'SnapController:snapInstalled',\n this._handleSnapRegisterEvent,\n );\n\n this.messagingSystem.unsubscribe(\n 'SnapController:snapUninstalled',\n this._handleSnapUnregisterEvent,\n );\n\n this.messagingSystem.unsubscribe(\n 'SnapController:snapEnabled',\n this._handleSnapEnabledEvent,\n );\n\n this.messagingSystem.unsubscribe(\n 'SnapController:snapDisabled',\n this._handleSnapDisabledEvent,\n );\n\n this.messagingSystem.unsubscribe(\n 'SnapController:snapUpdated',\n this._handleEventSnapUpdated,\n );\n /* eslint-enable @typescript-eslint/unbound-method */\n\n this.#snapIds.forEach((snapId) => this.unregister(snapId));\n }\n\n /**\n * Handle events that should cause cronjobs to be registered.\n *\n * @param snap - Basic Snap information.\n */\n // TODO: Either fix this lint violation or explain why it's necessary to\n // ignore.\n // eslint-disable-next-line no-restricted-syntax\n private _handleSnapRegisterEvent(snap: TruncatedSnap) {\n this.register(snap.id);\n }\n\n /**\n * Handle events that could cause cronjobs to be registered\n * and for background events to be rescheduled.\n *\n * @param snap - Basic Snap information.\n */\n // TODO: Either fix this lint violation or explain why it's necessary to\n // ignore.\n // eslint-disable-next-line no-restricted-syntax\n private _handleSnapEnabledEvent(snap: TruncatedSnap) {\n const events = this.getBackgroundEvents(snap.id);\n this.#rescheduleBackgroundEvents(events);\n this.register(snap.id);\n }\n\n /**\n * Handle events that should cause cronjobs and background events to be unregistered.\n *\n * @param snap - Basic Snap information.\n */\n // TODO: Either fix this lint violation or explain why it's necessary to\n // ignore.\n // eslint-disable-next-line no-restricted-syntax\n private _handleSnapUnregisterEvent(snap: TruncatedSnap) {\n this.unregister(snap.id);\n }\n\n /**\n * Handle events that should cause cronjobs and background events to be unregistered.\n *\n * @param snap - Basic Snap information.\n */\n // TODO: Either fix this lint violation or explain why it's necessary to\n // ignore.\n // eslint-disable-next-line no-restricted-syntax\n private _handleSnapDisabledEvent(snap: TruncatedSnap) {\n this.unregister(snap.id, true);\n }\n\n /**\n * Handle cron jobs on 'snapUpdated' event.\n *\n * @param snap - Basic Snap information.\n */\n // TODO: Either fix this lint violation or explain why it's necessary to\n // ignore.\n // eslint-disable-next-line no-restricted-syntax\n private _handleEventSnapUpdated(snap: TruncatedSnap) {\n this.unregister(snap.id);\n this.register(snap.id);\n }\n}\n"]}
|
|
@@ -311,7 +311,7 @@ async function _CronjobController_executeCronjob(job) {
|
|
|
311
311
|
__classPrivateFieldGet(this, _CronjobController_instances, "m", _CronjobController_updateJobLastRunState).call(this, job.id, Date.now());
|
|
312
312
|
await this.messagingSystem.call('SnapController:handleRequest', {
|
|
313
313
|
snapId: job.snapId,
|
|
314
|
-
origin: '',
|
|
314
|
+
origin: 'metamask',
|
|
315
315
|
handler: HandlerType.OnCronjob,
|
|
316
316
|
request: job.request,
|
|
317
317
|
});
|
|
@@ -327,7 +327,7 @@ async function _CronjobController_executeCronjob(job) {
|
|
|
327
327
|
this.messagingSystem
|
|
328
328
|
.call('SnapController:handleRequest', {
|
|
329
329
|
snapId: event.snapId,
|
|
330
|
-
origin: '',
|
|
330
|
+
origin: 'metamask',
|
|
331
331
|
handler: HandlerType.OnCronjob,
|
|
332
332
|
request: event.request,
|
|
333
333
|
})
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"CronjobController.mjs","sourceRoot":"","sources":["../../src/cronjob/CronjobController.ts"],"names":[],"mappings":";;;;;;;;;;;;AAKA,OAAO,EAAE,cAAc,EAAE,kCAAkC;AAE3D,OAAO,EACL,oBAAoB,EACpB,cAAc,EACf,oCAAoC;AAMr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AC,KAAK,CAAC,GAAG;YAClB,OAAO;SACR,CAAC;IACJ,CAAC,CAAC,CAAC;AACL,CAAC,yGAwC2B,gBAAmC;IAC7D,KAAK,MAAM,SAAS,IAAI,gBAAgB,EAAE,CAAC;QACzC,MAAM,EAAE,IAAI,EAAE,GAAG,SAAS,CAAC;QAC3B,MAAM,GAAG,GAAG,IAAI,IAAI,EAAE,CAAC;QACvB,MAAM,IAAI,GAAG,IAAI,IAAI,CAAC,IAAI,CAAC,CAAC;QAC5B,IAAI,IAAI,CAAC,OAAO,EAAE,GAAG,GAAG,CAAC,OAAO,EAAE,EAAE,CAAC;YACnC,mCAAmC;YACnC,IAAI,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE;gBACpB,OAAO,KAAK,CAAC,MAAM,CAAC,SAAS,CAAC,EAAE,CAAC,CAAC;YACpC,CAAC,CAAC,CAAC;YAEH,UAAU,CACR,6BAA6B,SAAS,CAAC,EAAE,0CAA0C,CACpF,CAAC;QACJ,CAAC;aAAM,CAAC;YACN,uBAAA,IAAI,6EAAsB,MAA1B,IAAI,EAAuB,SAAS,CAAC,CAAC;QACxC,CAAC;IACH,CAAC;AACH,CAAC","sourcesContent":["import type {\n RestrictedMessenger,\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n} from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport type { GetPermissions } from '@metamask/permission-controller';\nimport {\n getCronjobCaveatJobs,\n SnapEndowments,\n} from '@metamask/snaps-rpc-methods';\nimport type { BackgroundEvent, SnapId } from '@metamask/snaps-sdk';\nimport type {\n TruncatedSnap,\n CronjobSpecification,\n} from '@metamask/snaps-utils';\nimport {\n HandlerType,\n parseCronExpression,\n logError,\n logWarning,\n} from '@metamask/snaps-utils';\nimport { assert, Duration, inMilliseconds } from '@metamask/utils';\nimport { castDraft } from 'immer';\nimport { DateTime } from 'luxon';\nimport { nanoid } from 'nanoid';\n\nimport type {\n GetAllSnaps,\n HandleSnapRequest,\n SnapDisabled,\n SnapEnabled,\n SnapInstalled,\n SnapUninstalled,\n SnapUpdated,\n} from '..';\nimport { getRunnableSnaps } from '..';\nimport { Timer } from '../snaps/Timer';\n\nexport type CronjobControllerGetStateAction = ControllerGetStateAction<\n typeof controllerName,\n CronjobControllerState\n>;\nexport type CronjobControllerStateChangeEvent = ControllerStateChangeEvent<\n typeof controllerName,\n CronjobControllerState\n>;\n\nexport type ScheduleBackgroundEvent = {\n type: `${typeof controllerName}:scheduleBackgroundEvent`;\n handler: CronjobController['scheduleBackgroundEvent'];\n};\n\nexport type CancelBackgroundEvent = {\n type: `${typeof controllerName}:cancelBackgroundEvent`;\n handler: CronjobController['cancelBackgroundEvent'];\n};\n\nexport type GetBackgroundEvents = {\n type: `${typeof controllerName}:getBackgroundEvents`;\n handler: CronjobController['getBackgroundEvents'];\n};\n\nexport type CronjobControllerActions =\n | GetAllSnaps\n | HandleSnapRequest\n | GetPermissions\n | CronjobControllerGetStateAction\n | ScheduleBackgroundEvent\n | CancelBackgroundEvent\n | GetBackgroundEvents;\n\nexport type CronjobControllerEvents =\n | SnapInstalled\n | SnapUninstalled\n | SnapUpdated\n | SnapEnabled\n | SnapDisabled\n | CronjobControllerStateChangeEvent;\n\nexport type CronjobControllerMessenger = RestrictedMessenger<\n typeof controllerName,\n CronjobControllerActions,\n CronjobControllerEvents,\n CronjobControllerActions['type'],\n CronjobControllerEvents['type']\n>;\n\nexport const DAILY_TIMEOUT = inMilliseconds(24, Duration.Hour);\n\nexport type CronjobControllerArgs = {\n messenger: CronjobControllerMessenger;\n /**\n * Persisted state that will be used for rehydration.\n */\n state?: CronjobControllerState;\n};\n\nexport type Cronjob = {\n timer?: Timer;\n id: string;\n snapId: SnapId;\n} & CronjobSpecification;\n\nexport type StoredJobInformation = {\n lastRun: number;\n};\n\nexport type CronjobControllerState = {\n jobs: Record<string, StoredJobInformation>;\n events: Record<string, BackgroundEvent>;\n};\n\nconst controllerName = 'CronjobController';\n\n/**\n * Use this controller to register and schedule periodically executed jobs\n * using RPC method hooks.\n */\nexport class CronjobController extends BaseController<\n typeof controllerName,\n CronjobControllerState,\n CronjobControllerMessenger\n> {\n #dailyTimer!: Timer;\n\n readonly #timers: Map<string, Timer>;\n\n // Mapping from jobId to snapId\n readonly #snapIds: Map<string, SnapId>;\n\n constructor({ messenger, state }: CronjobControllerArgs) {\n super({\n messenger,\n metadata: {\n jobs: { persist: true, anonymous: false },\n events: { persist: true, anonymous: false },\n },\n name: controllerName,\n state: {\n jobs: {},\n events: {},\n ...state,\n },\n });\n this.#timers = new Map();\n this.#snapIds = new Map();\n\n this._handleSnapRegisterEvent = this._handleSnapRegisterEvent.bind(this);\n this._handleSnapUnregisterEvent =\n this._handleSnapUnregisterEvent.bind(this);\n this._handleEventSnapUpdated = this._handleEventSnapUpdated.bind(this);\n this._handleSnapDisabledEvent = this._handleSnapDisabledEvent.bind(this);\n this._handleSnapEnabledEvent = this._handleSnapEnabledEvent.bind(this);\n // Subscribe to Snap events\n /* eslint-disable @typescript-eslint/unbound-method */\n\n this.messagingSystem.subscribe(\n 'SnapController:snapInstalled',\n this._handleSnapRegisterEvent,\n );\n\n this.messagingSystem.subscribe(\n 'SnapController:snapUninstalled',\n this._handleSnapUnregisterEvent,\n );\n\n this.messagingSystem.subscribe(\n 'SnapController:snapEnabled',\n this._handleSnapEnabledEvent,\n );\n\n this.messagingSystem.subscribe(\n 'SnapController:snapDisabled',\n this._handleSnapDisabledEvent,\n );\n\n this.messagingSystem.subscribe(\n 'SnapController:snapUpdated',\n this._handleEventSnapUpdated,\n );\n /* eslint-enable @typescript-eslint/unbound-method */\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:scheduleBackgroundEvent`,\n (...args) => this.scheduleBackgroundEvent(...args),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:cancelBackgroundEvent`,\n (...args) => this.cancelBackgroundEvent(...args),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:getBackgroundEvents`,\n (...args) => this.getBackgroundEvents(...args),\n );\n\n this.dailyCheckIn().catch((error) => {\n logError(error);\n });\n\n this.#rescheduleBackgroundEvents(Object.values(this.state.events));\n }\n\n /**\n * Retrieve all cronjob specifications for all runnable snaps.\n *\n * @returns Array of Cronjob specifications.\n */\n #getAllJobs(): Cronjob[] {\n const snaps = this.messagingSystem.call('SnapController:getAll');\n const filteredSnaps = getRunnableSnaps(snaps);\n\n const jobs = filteredSnaps.map((snap) => this.#getSnapJobs(snap.id));\n return jobs.flat().filter((job) => job !== undefined) as Cronjob[];\n }\n\n /**\n * Retrieve all Cronjob specifications for a Snap.\n *\n * @param snapId - ID of a Snap.\n * @returns Array of Cronjob specifications.\n */\n #getSnapJobs(snapId: SnapId): Cronjob[] | undefined {\n const permissions = this.messagingSystem.call(\n 'PermissionController:getPermissions',\n snapId,\n );\n\n const permission = permissions?.[SnapEndowments.Cronjob];\n const definitions = getCronjobCaveatJobs(permission);\n\n return definitions?.map((definition, idx) => {\n return { ...definition, id: `${snapId}-${idx}`, snapId };\n });\n }\n\n /**\n * Register cron jobs for a given snap by getting specification from a permission caveats.\n * Once registered, each job will be scheduled.\n *\n * @param snapId - ID of a snap.\n */\n register(snapId: SnapId) {\n const jobs = this.#getSnapJobs(snapId);\n jobs?.forEach((job) => this.#schedule(job));\n }\n\n /**\n * Schedule a new job.\n * This will interpret the cron expression and tell the timer to execute the job\n * at the next suitable point in time.\n * Job last run state will be initialized afterwards.\n *\n * Note: Schedule will be skipped if the job's execution time is too far in the future and\n * will be revisited on a daily check.\n *\n * @param job - Cronjob specification.\n */\n #schedule(job: Cronjob) {\n if (this.#timers.has(job.id)) {\n return;\n }\n\n const parsed = parseCronExpression(job.expression);\n const next = parsed.next();\n const now = new Date();\n const ms = next.getTime() - now.getTime();\n\n // Don't schedule this job yet as it is too far in the future\n if (ms > DAILY_TIMEOUT) {\n return;\n }\n\n const timer = new Timer(ms);\n timer.start(() => {\n this.#executeCronjob(job).catch((error) => {\n // TODO: Decide how to handle errors.\n logError(error);\n });\n\n this.#timers.delete(job.id);\n this.#schedule(job);\n });\n\n if (!this.state.jobs[job.id]?.lastRun) {\n this.#updateJobLastRunState(job.id, 0); // 0 for init, never ran actually\n }\n\n this.#timers.set(job.id, timer);\n this.#snapIds.set(job.id, job.snapId);\n }\n\n /**\n * Execute job.\n *\n * @param job - Cronjob specification.\n */\n async #executeCronjob(job: Cronjob) {\n this.#updateJobLastRunState(job.id, Date.now());\n await this.messagingSystem.call('SnapController:handleRequest', {\n snapId: job.snapId,\n origin: '',\n handler: HandlerType.OnCronjob,\n request: job.request,\n });\n }\n\n /**\n * Schedule a background event.\n *\n * @param backgroundEventWithoutId - Background event.\n * @returns An id representing the background event.\n */\n scheduleBackgroundEvent(\n backgroundEventWithoutId: Omit<BackgroundEvent, 'id' | 'scheduledAt'>,\n ) {\n // Remove millisecond precision and convert to UTC.\n const scheduledAt = DateTime.fromJSDate(new Date())\n .toUTC()\n .startOf('second')\n .toISO({\n suppressMilliseconds: true,\n });\n\n assert(scheduledAt);\n\n const event = {\n ...backgroundEventWithoutId,\n id: nanoid(),\n scheduledAt,\n };\n\n this.#setUpBackgroundEvent(event);\n this.update((state) => {\n state.events[event.id] = castDraft(event);\n });\n\n return event.id;\n }\n\n /**\n * Cancel a background event.\n *\n * @param origin - The origin making the cancel call.\n * @param id - The id of the background event to cancel.\n * @throws If the event does not exist.\n */\n cancelBackgroundEvent(origin: string, id: string) {\n assert(\n this.state.events[id],\n `A background event with the id of \"${id}\" does not exist.`,\n );\n\n assert(\n this.state.events[id].snapId === origin,\n 'Only the origin that scheduled this event can cancel it.',\n );\n\n const timer = this.#timers.get(id);\n timer?.cancel();\n this.#timers.delete(id);\n this.#snapIds.delete(id);\n this.update((state) => {\n delete state.events[id];\n });\n }\n\n /**\n * A helper function to handle setup of the background event.\n *\n * @param event - A background event.\n */\n #setUpBackgroundEvent(event: BackgroundEvent) {\n const date = new Date(event.date);\n const now = new Date();\n const ms = date.getTime() - now.getTime();\n\n if (ms <= 0) {\n throw new Error('Cannot schedule an event in the past.');\n }\n\n const timer = new Timer(ms);\n timer.start(() => {\n this.messagingSystem\n .call('SnapController:handleRequest', {\n snapId: event.snapId,\n origin: '',\n handler: HandlerType.OnCronjob,\n request: event.request,\n })\n .catch((error) => {\n logError(error);\n });\n\n this.#timers.delete(event.id);\n this.#snapIds.delete(event.id);\n this.update((state) => {\n delete state.events[event.id];\n });\n });\n\n this.#timers.set(event.id, timer);\n this.#snapIds.set(event.id, event.snapId);\n }\n\n /**\n * Get a list of a Snap's background events.\n *\n * @param snapId - The id of the Snap to fetch background events for.\n * @returns An array of background events.\n */\n getBackgroundEvents(snapId: SnapId): BackgroundEvent[] {\n return Object.values(this.state.events).filter(\n (snapEvent) => snapEvent.snapId === snapId,\n );\n }\n\n /**\n * Unregister all jobs and background events related to the given snapId.\n *\n * @param snapId - ID of a snap.\n * @param skipEvents - Whether the unregistration process should skip scheduled background events.\n */\n unregister(snapId: SnapId, skipEvents = false) {\n const jobs = [...this.#snapIds.entries()].filter(\n ([_, jobSnapId]) => jobSnapId === snapId,\n );\n\n if (jobs.length) {\n const eventIds: string[] = [];\n jobs.forEach(([id]) => {\n const timer = this.#timers.get(id);\n if (timer) {\n timer.cancel();\n this.#timers.delete(id);\n this.#snapIds.delete(id);\n if (!skipEvents && this.state.events[id]) {\n eventIds.push(id);\n }\n }\n });\n\n if (eventIds.length > 0) {\n this.update((state) => {\n eventIds.forEach((id) => {\n delete state.events[id];\n });\n });\n }\n }\n }\n\n /**\n * Update time of a last run for the Cronjob specified by ID.\n *\n * @param jobId - ID of a cron job.\n * @param lastRun - Unix timestamp when the job was last ran.\n */\n #updateJobLastRunState(jobId: string, lastRun: number) {\n this.update((state) => {\n state.jobs[jobId] = {\n lastRun,\n };\n });\n }\n\n /**\n * Runs every 24 hours to check if new jobs need to be scheduled.\n *\n * This is necessary for longer running jobs that execute with more than 24 hours between them.\n */\n async dailyCheckIn() {\n const jobs = this.#getAllJobs();\n\n for (const job of jobs) {\n const parsed = parseCronExpression(job.expression);\n const lastRun = this.state.jobs[job.id]?.lastRun;\n // If a job was supposed to run while we were shut down but wasn't we run it now\n if (\n lastRun !== undefined &&\n parsed.hasPrev() &&\n parsed.prev().getTime() > lastRun\n ) {\n await this.#executeCronjob(job);\n }\n\n // Try scheduling, will fail if an existing scheduled job is found\n this.#schedule(job);\n }\n\n this.#dailyTimer = new Timer(DAILY_TIMEOUT);\n this.#dailyTimer.start(() => {\n this.dailyCheckIn().catch((error) => {\n // TODO: Decide how to handle errors.\n logError(error);\n });\n });\n }\n\n /**\n * Reschedule background events.\n *\n * @param backgroundEvents - A list of background events to reschdule.\n */\n #rescheduleBackgroundEvents(backgroundEvents: BackgroundEvent[]) {\n for (const snapEvent of backgroundEvents) {\n const { date } = snapEvent;\n const now = new Date();\n const then = new Date(date);\n if (then.getTime() < now.getTime()) {\n // Remove expired events from state\n this.update((state) => {\n delete state.events[snapEvent.id];\n });\n\n logWarning(\n `Background event with id \"${snapEvent.id}\" not scheduled as its date has expired.`,\n );\n } else {\n this.#setUpBackgroundEvent(snapEvent);\n }\n }\n }\n\n /**\n * Run controller teardown process and unsubscribe from Snap events.\n */\n destroy() {\n super.destroy();\n\n /* eslint-disable @typescript-eslint/unbound-method */\n this.messagingSystem.unsubscribe(\n 'SnapController:snapInstalled',\n this._handleSnapRegisterEvent,\n );\n\n this.messagingSystem.unsubscribe(\n 'SnapController:snapUninstalled',\n this._handleSnapUnregisterEvent,\n );\n\n this.messagingSystem.unsubscribe(\n 'SnapController:snapEnabled',\n this._handleSnapEnabledEvent,\n );\n\n this.messagingSystem.unsubscribe(\n 'SnapController:snapDisabled',\n this._handleSnapDisabledEvent,\n );\n\n this.messagingSystem.unsubscribe(\n 'SnapController:snapUpdated',\n this._handleEventSnapUpdated,\n );\n /* eslint-enable @typescript-eslint/unbound-method */\n\n this.#snapIds.forEach((snapId) => this.unregister(snapId));\n }\n\n /**\n * Handle events that should cause cronjobs to be registered.\n *\n * @param snap - Basic Snap information.\n */\n // TODO: Either fix this lint violation or explain why it's necessary to\n // ignore.\n // eslint-disable-next-line no-restricted-syntax\n private _handleSnapRegisterEvent(snap: TruncatedSnap) {\n this.register(snap.id);\n }\n\n /**\n * Handle events that could cause cronjobs to be registered\n * and for background events to be rescheduled.\n *\n * @param snap - Basic Snap information.\n */\n // TODO: Either fix this lint violation or explain why it's necessary to\n // ignore.\n // eslint-disable-next-line no-restricted-syntax\n private _handleSnapEnabledEvent(snap: TruncatedSnap) {\n const events = this.getBackgroundEvents(snap.id);\n this.#rescheduleBackgroundEvents(events);\n this.register(snap.id);\n }\n\n /**\n * Handle events that should cause cronjobs and background events to be unregistered.\n *\n * @param snap - Basic Snap information.\n */\n // TODO: Either fix this lint violation or explain why it's necessary to\n // ignore.\n // eslint-disable-next-line no-restricted-syntax\n private _handleSnapUnregisterEvent(snap: TruncatedSnap) {\n this.unregister(snap.id);\n }\n\n /**\n * Handle events that should cause cronjobs and background events to be unregistered.\n *\n * @param snap - Basic Snap information.\n */\n // TODO: Either fix this lint violation or explain why it's necessary to\n // ignore.\n // eslint-disable-next-line no-restricted-syntax\n private _handleSnapDisabledEvent(snap: TruncatedSnap) {\n this.unregister(snap.id, true);\n }\n\n /**\n * Handle cron jobs on 'snapUpdated' event.\n *\n * @param snap - Basic Snap information.\n */\n // TODO: Either fix this lint violation or explain why it's necessary to\n // ignore.\n // eslint-disable-next-line no-restricted-syntax\n private _handleEventSnapUpdated(snap: TruncatedSnap) {\n this.unregister(snap.id);\n this.register(snap.id);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"CronjobController.mjs","sourceRoot":"","sources":["../../src/cronjob/CronjobController.ts"],"names":[],"mappings":";;;;;;;;;;;;AAKA,OAAO,EAAE,cAAc,EAAE,kCAAkC;AAE3D,OAAO,EACL,oBAAoB,EACpB,cAAc,EACf,oCAAoC;AAMrC,OAAO,EACL,WAAW,EACX,mBAAmB,EACnB,QAAQ,EACR,UAAU,EACX,8BAA8B;AAC/B,OAAO,E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AwC2B,gBAAmC;IAC7D,KAAK,MAAM,SAAS,IAAI,gBAAgB,EAAE,CAAC;QACzC,MAAM,EAAE,IAAI,EAAE,GAAG,SAAS,CAAC;QAC3B,MAAM,GAAG,GAAG,IAAI,IAAI,EAAE,CAAC;QACvB,MAAM,IAAI,GAAG,IAAI,IAAI,CAAC,IAAI,CAAC,CAAC;QAC5B,IAAI,IAAI,CAAC,OAAO,EAAE,GAAG,GAAG,CAAC,OAAO,EAAE,EAAE,CAAC;YACnC,mCAAmC;YACnC,IAAI,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE;gBACpB,OAAO,KAAK,CAAC,MAAM,CAAC,SAAS,CAAC,EAAE,CAAC,CAAC;YACpC,CAAC,CAAC,CAAC;YAEH,UAAU,CACR,6BAA6B,SAAS,CAAC,EAAE,0CAA0C,CACpF,CAAC;QACJ,CAAC;aAAM,CAAC;YACN,uBAAA,IAAI,6EAAsB,MAA1B,IAAI,EAAuB,SAAS,CAAC,CAAC;QACxC,CAAC;IACH,CAAC;AACH,CAAC","sourcesContent":["import type {\n RestrictedMessenger,\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n} from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport type { GetPermissions } from '@metamask/permission-controller';\nimport {\n getCronjobCaveatJobs,\n SnapEndowments,\n} from '@metamask/snaps-rpc-methods';\nimport type { BackgroundEvent, SnapId } from '@metamask/snaps-sdk';\nimport type {\n TruncatedSnap,\n CronjobSpecification,\n} from '@metamask/snaps-utils';\nimport {\n HandlerType,\n parseCronExpression,\n logError,\n logWarning,\n} from '@metamask/snaps-utils';\nimport { assert, Duration, inMilliseconds } from '@metamask/utils';\nimport { castDraft } from 'immer';\nimport { DateTime } from 'luxon';\nimport { nanoid } from 'nanoid';\n\nimport type {\n GetAllSnaps,\n HandleSnapRequest,\n SnapDisabled,\n SnapEnabled,\n SnapInstalled,\n SnapUninstalled,\n SnapUpdated,\n} from '..';\nimport { getRunnableSnaps } from '..';\nimport { Timer } from '../snaps/Timer';\n\nexport type CronjobControllerGetStateAction = ControllerGetStateAction<\n typeof controllerName,\n CronjobControllerState\n>;\nexport type CronjobControllerStateChangeEvent = ControllerStateChangeEvent<\n typeof controllerName,\n CronjobControllerState\n>;\n\nexport type ScheduleBackgroundEvent = {\n type: `${typeof controllerName}:scheduleBackgroundEvent`;\n handler: CronjobController['scheduleBackgroundEvent'];\n};\n\nexport type CancelBackgroundEvent = {\n type: `${typeof controllerName}:cancelBackgroundEvent`;\n handler: CronjobController['cancelBackgroundEvent'];\n};\n\nexport type GetBackgroundEvents = {\n type: `${typeof controllerName}:getBackgroundEvents`;\n handler: CronjobController['getBackgroundEvents'];\n};\n\nexport type CronjobControllerActions =\n | GetAllSnaps\n | HandleSnapRequest\n | GetPermissions\n | CronjobControllerGetStateAction\n | ScheduleBackgroundEvent\n | CancelBackgroundEvent\n | GetBackgroundEvents;\n\nexport type CronjobControllerEvents =\n | SnapInstalled\n | SnapUninstalled\n | SnapUpdated\n | SnapEnabled\n | SnapDisabled\n | CronjobControllerStateChangeEvent;\n\nexport type CronjobControllerMessenger = RestrictedMessenger<\n typeof controllerName,\n CronjobControllerActions,\n CronjobControllerEvents,\n CronjobControllerActions['type'],\n CronjobControllerEvents['type']\n>;\n\nexport const DAILY_TIMEOUT = inMilliseconds(24, Duration.Hour);\n\nexport type CronjobControllerArgs = {\n messenger: CronjobControllerMessenger;\n /**\n * Persisted state that will be used for rehydration.\n */\n state?: CronjobControllerState;\n};\n\nexport type Cronjob = {\n timer?: Timer;\n id: string;\n snapId: SnapId;\n} & CronjobSpecification;\n\nexport type StoredJobInformation = {\n lastRun: number;\n};\n\nexport type CronjobControllerState = {\n jobs: Record<string, StoredJobInformation>;\n events: Record<string, BackgroundEvent>;\n};\n\nconst controllerName = 'CronjobController';\n\n/**\n * Use this controller to register and schedule periodically executed jobs\n * using RPC method hooks.\n */\nexport class CronjobController extends BaseController<\n typeof controllerName,\n CronjobControllerState,\n CronjobControllerMessenger\n> {\n #dailyTimer!: Timer;\n\n readonly #timers: Map<string, Timer>;\n\n // Mapping from jobId to snapId\n readonly #snapIds: Map<string, SnapId>;\n\n constructor({ messenger, state }: CronjobControllerArgs) {\n super({\n messenger,\n metadata: {\n jobs: { persist: true, anonymous: false },\n events: { persist: true, anonymous: false },\n },\n name: controllerName,\n state: {\n jobs: {},\n events: {},\n ...state,\n },\n });\n this.#timers = new Map();\n this.#snapIds = new Map();\n\n this._handleSnapRegisterEvent = this._handleSnapRegisterEvent.bind(this);\n this._handleSnapUnregisterEvent =\n this._handleSnapUnregisterEvent.bind(this);\n this._handleEventSnapUpdated = this._handleEventSnapUpdated.bind(this);\n this._handleSnapDisabledEvent = this._handleSnapDisabledEvent.bind(this);\n this._handleSnapEnabledEvent = this._handleSnapEnabledEvent.bind(this);\n // Subscribe to Snap events\n /* eslint-disable @typescript-eslint/unbound-method */\n\n this.messagingSystem.subscribe(\n 'SnapController:snapInstalled',\n this._handleSnapRegisterEvent,\n );\n\n this.messagingSystem.subscribe(\n 'SnapController:snapUninstalled',\n this._handleSnapUnregisterEvent,\n );\n\n this.messagingSystem.subscribe(\n 'SnapController:snapEnabled',\n this._handleSnapEnabledEvent,\n );\n\n this.messagingSystem.subscribe(\n 'SnapController:snapDisabled',\n this._handleSnapDisabledEvent,\n );\n\n this.messagingSystem.subscribe(\n 'SnapController:snapUpdated',\n this._handleEventSnapUpdated,\n );\n /* eslint-enable @typescript-eslint/unbound-method */\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:scheduleBackgroundEvent`,\n (...args) => this.scheduleBackgroundEvent(...args),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:cancelBackgroundEvent`,\n (...args) => this.cancelBackgroundEvent(...args),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:getBackgroundEvents`,\n (...args) => this.getBackgroundEvents(...args),\n );\n\n this.dailyCheckIn().catch((error) => {\n logError(error);\n });\n\n this.#rescheduleBackgroundEvents(Object.values(this.state.events));\n }\n\n /**\n * Retrieve all cronjob specifications for all runnable snaps.\n *\n * @returns Array of Cronjob specifications.\n */\n #getAllJobs(): Cronjob[] {\n const snaps = this.messagingSystem.call('SnapController:getAll');\n const filteredSnaps = getRunnableSnaps(snaps);\n\n const jobs = filteredSnaps.map((snap) => this.#getSnapJobs(snap.id));\n return jobs.flat().filter((job) => job !== undefined) as Cronjob[];\n }\n\n /**\n * Retrieve all Cronjob specifications for a Snap.\n *\n * @param snapId - ID of a Snap.\n * @returns Array of Cronjob specifications.\n */\n #getSnapJobs(snapId: SnapId): Cronjob[] | undefined {\n const permissions = this.messagingSystem.call(\n 'PermissionController:getPermissions',\n snapId,\n );\n\n const permission = permissions?.[SnapEndowments.Cronjob];\n const definitions = getCronjobCaveatJobs(permission);\n\n return definitions?.map((definition, idx) => {\n return { ...definition, id: `${snapId}-${idx}`, snapId };\n });\n }\n\n /**\n * Register cron jobs for a given snap by getting specification from a permission caveats.\n * Once registered, each job will be scheduled.\n *\n * @param snapId - ID of a snap.\n */\n register(snapId: SnapId) {\n const jobs = this.#getSnapJobs(snapId);\n jobs?.forEach((job) => this.#schedule(job));\n }\n\n /**\n * Schedule a new job.\n * This will interpret the cron expression and tell the timer to execute the job\n * at the next suitable point in time.\n * Job last run state will be initialized afterwards.\n *\n * Note: Schedule will be skipped if the job's execution time is too far in the future and\n * will be revisited on a daily check.\n *\n * @param job - Cronjob specification.\n */\n #schedule(job: Cronjob) {\n if (this.#timers.has(job.id)) {\n return;\n }\n\n const parsed = parseCronExpression(job.expression);\n const next = parsed.next();\n const now = new Date();\n const ms = next.getTime() - now.getTime();\n\n // Don't schedule this job yet as it is too far in the future\n if (ms > DAILY_TIMEOUT) {\n return;\n }\n\n const timer = new Timer(ms);\n timer.start(() => {\n this.#executeCronjob(job).catch((error) => {\n // TODO: Decide how to handle errors.\n logError(error);\n });\n\n this.#timers.delete(job.id);\n this.#schedule(job);\n });\n\n if (!this.state.jobs[job.id]?.lastRun) {\n this.#updateJobLastRunState(job.id, 0); // 0 for init, never ran actually\n }\n\n this.#timers.set(job.id, timer);\n this.#snapIds.set(job.id, job.snapId);\n }\n\n /**\n * Execute job.\n *\n * @param job - Cronjob specification.\n */\n async #executeCronjob(job: Cronjob) {\n this.#updateJobLastRunState(job.id, Date.now());\n await this.messagingSystem.call('SnapController:handleRequest', {\n snapId: job.snapId,\n origin: 'metamask',\n handler: HandlerType.OnCronjob,\n request: job.request,\n });\n }\n\n /**\n * Schedule a background event.\n *\n * @param backgroundEventWithoutId - Background event.\n * @returns An id representing the background event.\n */\n scheduleBackgroundEvent(\n backgroundEventWithoutId: Omit<BackgroundEvent, 'id' | 'scheduledAt'>,\n ) {\n // Remove millisecond precision and convert to UTC.\n const scheduledAt = DateTime.fromJSDate(new Date())\n .toUTC()\n .startOf('second')\n .toISO({\n suppressMilliseconds: true,\n });\n\n assert(scheduledAt);\n\n const event = {\n ...backgroundEventWithoutId,\n id: nanoid(),\n scheduledAt,\n };\n\n this.#setUpBackgroundEvent(event);\n this.update((state) => {\n state.events[event.id] = castDraft(event);\n });\n\n return event.id;\n }\n\n /**\n * Cancel a background event.\n *\n * @param origin - The origin making the cancel call.\n * @param id - The id of the background event to cancel.\n * @throws If the event does not exist.\n */\n cancelBackgroundEvent(origin: string, id: string) {\n assert(\n this.state.events[id],\n `A background event with the id of \"${id}\" does not exist.`,\n );\n\n assert(\n this.state.events[id].snapId === origin,\n 'Only the origin that scheduled this event can cancel it.',\n );\n\n const timer = this.#timers.get(id);\n timer?.cancel();\n this.#timers.delete(id);\n this.#snapIds.delete(id);\n this.update((state) => {\n delete state.events[id];\n });\n }\n\n /**\n * A helper function to handle setup of the background event.\n *\n * @param event - A background event.\n */\n #setUpBackgroundEvent(event: BackgroundEvent) {\n const date = new Date(event.date);\n const now = new Date();\n const ms = date.getTime() - now.getTime();\n\n if (ms <= 0) {\n throw new Error('Cannot schedule an event in the past.');\n }\n\n const timer = new Timer(ms);\n timer.start(() => {\n this.messagingSystem\n .call('SnapController:handleRequest', {\n snapId: event.snapId,\n origin: 'metamask',\n handler: HandlerType.OnCronjob,\n request: event.request,\n })\n .catch((error) => {\n logError(error);\n });\n\n this.#timers.delete(event.id);\n this.#snapIds.delete(event.id);\n this.update((state) => {\n delete state.events[event.id];\n });\n });\n\n this.#timers.set(event.id, timer);\n this.#snapIds.set(event.id, event.snapId);\n }\n\n /**\n * Get a list of a Snap's background events.\n *\n * @param snapId - The id of the Snap to fetch background events for.\n * @returns An array of background events.\n */\n getBackgroundEvents(snapId: SnapId): BackgroundEvent[] {\n return Object.values(this.state.events).filter(\n (snapEvent) => snapEvent.snapId === snapId,\n );\n }\n\n /**\n * Unregister all jobs and background events related to the given snapId.\n *\n * @param snapId - ID of a snap.\n * @param skipEvents - Whether the unregistration process should skip scheduled background events.\n */\n unregister(snapId: SnapId, skipEvents = false) {\n const jobs = [...this.#snapIds.entries()].filter(\n ([_, jobSnapId]) => jobSnapId === snapId,\n );\n\n if (jobs.length) {\n const eventIds: string[] = [];\n jobs.forEach(([id]) => {\n const timer = this.#timers.get(id);\n if (timer) {\n timer.cancel();\n this.#timers.delete(id);\n this.#snapIds.delete(id);\n if (!skipEvents && this.state.events[id]) {\n eventIds.push(id);\n }\n }\n });\n\n if (eventIds.length > 0) {\n this.update((state) => {\n eventIds.forEach((id) => {\n delete state.events[id];\n });\n });\n }\n }\n }\n\n /**\n * Update time of a last run for the Cronjob specified by ID.\n *\n * @param jobId - ID of a cron job.\n * @param lastRun - Unix timestamp when the job was last ran.\n */\n #updateJobLastRunState(jobId: string, lastRun: number) {\n this.update((state) => {\n state.jobs[jobId] = {\n lastRun,\n };\n });\n }\n\n /**\n * Runs every 24 hours to check if new jobs need to be scheduled.\n *\n * This is necessary for longer running jobs that execute with more than 24 hours between them.\n */\n async dailyCheckIn() {\n const jobs = this.#getAllJobs();\n\n for (const job of jobs) {\n const parsed = parseCronExpression(job.expression);\n const lastRun = this.state.jobs[job.id]?.lastRun;\n // If a job was supposed to run while we were shut down but wasn't we run it now\n if (\n lastRun !== undefined &&\n parsed.hasPrev() &&\n parsed.prev().getTime() > lastRun\n ) {\n await this.#executeCronjob(job);\n }\n\n // Try scheduling, will fail if an existing scheduled job is found\n this.#schedule(job);\n }\n\n this.#dailyTimer = new Timer(DAILY_TIMEOUT);\n this.#dailyTimer.start(() => {\n this.dailyCheckIn().catch((error) => {\n // TODO: Decide how to handle errors.\n logError(error);\n });\n });\n }\n\n /**\n * Reschedule background events.\n *\n * @param backgroundEvents - A list of background events to reschdule.\n */\n #rescheduleBackgroundEvents(backgroundEvents: BackgroundEvent[]) {\n for (const snapEvent of backgroundEvents) {\n const { date } = snapEvent;\n const now = new Date();\n const then = new Date(date);\n if (then.getTime() < now.getTime()) {\n // Remove expired events from state\n this.update((state) => {\n delete state.events[snapEvent.id];\n });\n\n logWarning(\n `Background event with id \"${snapEvent.id}\" not scheduled as its date has expired.`,\n );\n } else {\n this.#setUpBackgroundEvent(snapEvent);\n }\n }\n }\n\n /**\n * Run controller teardown process and unsubscribe from Snap events.\n */\n destroy() {\n super.destroy();\n\n /* eslint-disable @typescript-eslint/unbound-method */\n this.messagingSystem.unsubscribe(\n 'SnapController:snapInstalled',\n this._handleSnapRegisterEvent,\n );\n\n this.messagingSystem.unsubscribe(\n 'SnapController:snapUninstalled',\n this._handleSnapUnregisterEvent,\n );\n\n this.messagingSystem.unsubscribe(\n 'SnapController:snapEnabled',\n this._handleSnapEnabledEvent,\n );\n\n this.messagingSystem.unsubscribe(\n 'SnapController:snapDisabled',\n this._handleSnapDisabledEvent,\n );\n\n this.messagingSystem.unsubscribe(\n 'SnapController:snapUpdated',\n this._handleEventSnapUpdated,\n );\n /* eslint-enable @typescript-eslint/unbound-method */\n\n this.#snapIds.forEach((snapId) => this.unregister(snapId));\n }\n\n /**\n * Handle events that should cause cronjobs to be registered.\n *\n * @param snap - Basic Snap information.\n */\n // TODO: Either fix this lint violation or explain why it's necessary to\n // ignore.\n // eslint-disable-next-line no-restricted-syntax\n private _handleSnapRegisterEvent(snap: TruncatedSnap) {\n this.register(snap.id);\n }\n\n /**\n * Handle events that could cause cronjobs to be registered\n * and for background events to be rescheduled.\n *\n * @param snap - Basic Snap information.\n */\n // TODO: Either fix this lint violation or explain why it's necessary to\n // ignore.\n // eslint-disable-next-line no-restricted-syntax\n private _handleSnapEnabledEvent(snap: TruncatedSnap) {\n const events = this.getBackgroundEvents(snap.id);\n this.#rescheduleBackgroundEvents(events);\n this.register(snap.id);\n }\n\n /**\n * Handle events that should cause cronjobs and background events to be unregistered.\n *\n * @param snap - Basic Snap information.\n */\n // TODO: Either fix this lint violation or explain why it's necessary to\n // ignore.\n // eslint-disable-next-line no-restricted-syntax\n private _handleSnapUnregisterEvent(snap: TruncatedSnap) {\n this.unregister(snap.id);\n }\n\n /**\n * Handle events that should cause cronjobs and background events to be unregistered.\n *\n * @param snap - Basic Snap information.\n */\n // TODO: Either fix this lint violation or explain why it's necessary to\n // ignore.\n // eslint-disable-next-line no-restricted-syntax\n private _handleSnapDisabledEvent(snap: TruncatedSnap) {\n this.unregister(snap.id, true);\n }\n\n /**\n * Handle cron jobs on 'snapUpdated' event.\n *\n * @param snap - Basic Snap information.\n */\n // TODO: Either fix this lint violation or explain why it's necessary to\n // ignore.\n // eslint-disable-next-line no-restricted-syntax\n private _handleEventSnapUpdated(snap: TruncatedSnap) {\n this.unregister(snap.id);\n this.register(snap.id);\n }\n}\n"]}
|
|
@@ -164,7 +164,7 @@ _SnapInsightsController_instances = new WeakSet(), _SnapInsightsController_hasIn
|
|
|
164
164
|
async function _SnapInsightsController_handleSnapRequest({ snapId, handler, params, }) {
|
|
165
165
|
return this.messagingSystem.call('SnapController:handleRequest', {
|
|
166
166
|
snapId,
|
|
167
|
-
origin: '',
|
|
167
|
+
origin: 'metamask',
|
|
168
168
|
handler,
|
|
169
169
|
request: {
|
|
170
170
|
method: '',
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"SnapInsightsController.cjs","sourceRoot":"","s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AAC,CAAC;IAEL,IAAI,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE;QACpB,OAAO,KAAK,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC;IAC5B,CAAC,CAAC,CAAC;AACL,CAAC;AAED;;;;;;;;GAQG;AACH,KAAK,oDAAoB,EACvB,MAAM,EACN,OAAO,EACP,MAAM,GAKP;IACC,OAAO,IAAI,CAAC,eAAe,CAAC,IAAI,CAAC,8BAA8B,EAAE;QAC/D,MAAM;QACN,MAAM,EAAE,EAAE;QACV,OAAO;QACP,OAAO,EAAE;YACP,MAAM,EAAE,EAAE;YACV,MAAM;SACP;KACF,CAAC,CAAC;AACL,CAAC,mGAWmB,EAClB,EAAE,EACF,MAAM,EACN,QAAQ,EACR,KAAK,GAMN;IACC,6EAA6E;IAC7E,mGAAmG;IACnG,IAAI,CAAC,uBAAA,IAAI,6EAAY,MAAhB,IAAI,EAAa,EAAE,CAAC,EAAE,CAAC;QAC1B,OAAO;IACT,CAAC;IAED,IAAI,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE;QACpB,KAAK,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,MAAM,CAAC,CAAC,OAAO,GAAG,KAAK,CAAC;QAC3C,KAAK,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,MAAM,CAAC,CAAC,WAAW,GAAG,QAAQ,EAAE,EAAY,CAAC;QAChE,KAAK,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,MAAM,CAAC,CAAC,QAAQ,GAAG,QAAQ,EAAE,QAAkB,CAAC;QACnE,KAAK,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,MAAM,CAAC,CAAC,KAAK,GAAG,KAAK,EAAE,OAAO,CAAC;IACpD,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type {\n RestrictedMessenger,\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n} from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport type {\n Caveat,\n GetPermissions,\n ValidPermission,\n} from '@metamask/permission-controller';\nimport {\n getSignatureOriginCaveat,\n getTransactionOriginCaveat,\n SnapEndowments,\n} from '@metamask/snaps-rpc-methods';\nimport type { Json, SnapId } from '@metamask/snaps-sdk';\nimport { HandlerType } from '@metamask/snaps-utils';\nimport { hasProperty, hexToBigInt } from '@metamask/utils';\n\nimport type { DeleteInterface } from '../interface';\nimport type { GetAllSnaps, HandleSnapRequest } from '../snaps';\nimport { getRunnableSnaps } from '../snaps';\nimport type {\n TransactionControllerUnapprovedTransactionAddedEvent,\n TransactionMeta,\n SignatureStateChange,\n SignatureControllerState,\n StateSignature,\n TransactionControllerTransactionStatusUpdatedEvent,\n} from '../types';\n\nconst controllerName = 'SnapInsightsController';\n\nexport type SnapInsightsControllerAllowedActions =\n | HandleSnapRequest\n | GetAllSnaps\n | GetPermissions\n | DeleteInterface;\n\nexport type SnapInsightsControllerGetStateAction = ControllerGetStateAction<\n typeof controllerName,\n SnapInsightsControllerState\n>;\n\nexport type SnapInsightsControllerActions =\n SnapInsightsControllerGetStateAction;\n\nexport type SnapInsightControllerStateChangeEvent = ControllerStateChangeEvent<\n typeof controllerName,\n SnapInsightsControllerState\n>;\n\nexport type SnapInsightControllerEvents = SnapInsightControllerStateChangeEvent;\n\nexport type SnapInsightsControllerAllowedEvents =\n | TransactionControllerUnapprovedTransactionAddedEvent\n | TransactionControllerTransactionStatusUpdatedEvent\n | SignatureStateChange;\n\nexport type SnapInsightsControllerMessenger = RestrictedMessenger<\n typeof controllerName,\n SnapInsightsControllerActions | SnapInsightsControllerAllowedActions,\n SnapInsightControllerEvents | SnapInsightsControllerAllowedEvents,\n SnapInsightsControllerAllowedActions['type'],\n SnapInsightsControllerAllowedEvents['type']\n>;\n\nexport type SnapInsight = {\n snapId: SnapId;\n interfaceId?: string | null;\n error?: string;\n loading: boolean;\n severity?: string;\n};\n\nexport type SnapInsightsControllerState = {\n insights: Record<string, Record<SnapId, SnapInsight>>;\n};\n\nexport type SnapInsightsControllerArgs = {\n messenger: SnapInsightsControllerMessenger;\n state?: SnapInsightsControllerState;\n};\n\ntype SnapWithPermission = {\n snapId: SnapId;\n permission: ValidPermission<string, Caveat<string, Json>>;\n};\n\n/**\n * Controller for monitoring for new transactions and signatures to provide insight for.\n */\nexport class SnapInsightsController extends BaseController<\n typeof controllerName,\n SnapInsightsControllerState,\n SnapInsightsControllerMessenger\n> {\n constructor({ messenger, state }: SnapInsightsControllerArgs) {\n super({\n messenger,\n metadata: {\n insights: { persist: false, anonymous: false },\n },\n name: controllerName,\n state: { insights: {}, ...state },\n });\n\n this.messagingSystem.subscribe(\n 'TransactionController:unapprovedTransactionAdded',\n this.#handleTransaction.bind(this),\n );\n\n this.messagingSystem.subscribe(\n 'TransactionController:transactionStatusUpdated',\n this.#handleTransactionStatusUpdate.bind(this),\n );\n\n this.messagingSystem.subscribe(\n 'SignatureController:stateChange',\n this.#handleSignatureStateChange.bind(this),\n );\n }\n\n /**\n * Check if an insight already exists for a given ID.\n *\n * @param id - The ID.\n * @returns True if the insight already exists, otherwise false.\n */\n #hasInsight(id: string) {\n return hasProperty(this.state.insights, id);\n }\n\n /**\n * Get a list of runnable Snaps that have a given permission.\n * Also includes the permission object itself.\n *\n * @param permissionName - The permission name.\n * @returns A list of objects containing Snap IDs and the permission object.\n */\n #getSnapsWithPermission(permissionName: string) {\n const allSnaps = this.messagingSystem.call('SnapController:getAll');\n const filteredSnaps = getRunnableSnaps(allSnaps);\n\n return filteredSnaps.reduce<SnapWithPermission[]>((accumulator, snap) => {\n const permissions = this.messagingSystem.call(\n 'PermissionController:getPermissions',\n snap.id,\n );\n if (permissions && hasProperty(permissions, permissionName)) {\n accumulator.push({\n snapId: snap.id,\n permission: permissions[permissionName],\n });\n }\n\n return accumulator;\n }, []);\n }\n\n /**\n * Handle a newly added unapproved transaction.\n * This function fetches insights from all available Snaps\n * and populates the insights state blob with the responses.\n *\n * @param transaction - The transaction object.\n */\n #handleTransaction(transaction: TransactionMeta) {\n const { id, txParams, chainId, origin } = transaction;\n\n // This assumes that the transactions are EVM-compatible for now.\n const caipChainId = `eip155:${hexToBigInt(chainId).toString(10)}`;\n\n const snaps = this.#getSnapsWithPermission(\n SnapEndowments.TransactionInsight,\n );\n\n snaps.forEach(({ snapId, permission }) => {\n const hasTransactionOriginCaveat = getTransactionOriginCaveat(permission);\n const transactionOrigin =\n hasTransactionOriginCaveat && origin ? origin : null;\n\n this.update((state) => {\n state.insights[id] ??= {};\n state.insights[id][snapId] = { snapId, loading: true };\n });\n\n this.#handleSnapRequest({\n snapId,\n handler: HandlerType.OnTransaction,\n params: {\n transaction: txParams,\n chainId: caipChainId,\n transactionOrigin,\n },\n })\n .then((response) =>\n this.#handleSnapResponse({\n id,\n snapId,\n response: response as Record<string, Json>,\n }),\n )\n .catch((error) => this.#handleSnapResponse({ id, snapId, error }));\n });\n }\n\n /**\n * Handle the stateChange event emitted by the SignatureController.\n * This function will remove existing insights from the state when applicable, as well as\n * trigger insight fetching for newly added signatures.\n *\n * @param state - The SignatureController state blob.\n */\n #handleSignatureStateChange(state: SignatureControllerState) {\n // If any IDs have disappeared since the last state update, the insight may be cleaned up.\n for (const id of Object.keys(this.state.insights)) {\n if (\n !hasProperty(state.unapprovedTypedMessages, id) &&\n !hasProperty(state.unapprovedPersonalMsgs, id)\n ) {\n this.#handleInsightCleanup(id);\n }\n }\n\n if (\n state.unapprovedPersonalMsgCount > 0 ||\n state.unapprovedTypedMessagesCount > 0\n ) {\n const snaps = this.#getSnapsWithPermission(\n SnapEndowments.SignatureInsight,\n );\n\n // This isn't very efficient, but SignatureController doesn't expose a better event for us to use yet.\n for (const personalSignature of Object.values(\n state.unapprovedPersonalMsgs,\n )) {\n this.#handleSignature(snaps, personalSignature);\n }\n\n for (const typedMessage of Object.values(state.unapprovedTypedMessages)) {\n this.#handleSignature(snaps, typedMessage);\n }\n }\n }\n\n /**\n * Handle a newly added unapproved signature.\n * This function fetches insights from all available Snaps\n * and populates the insights state blob with the responses.\n *\n * @param snaps - A list of Snaps to invoke.\n * @param signature - The signature object.\n */\n #handleSignature(snaps: SnapWithPermission[], signature: StateSignature) {\n const { id, msgParams } = signature;\n\n if (this.#hasInsight(id)) {\n return;\n }\n\n const { from, data, signatureMethod, origin } = msgParams;\n\n /**\n * Both eth_signTypedData_v3 and eth_signTypedData_v4 methods\n * need to be parsed because their data is stringified. All other\n * signature methods do not, so they are ignored.\n */\n const shouldParse =\n signatureMethod === 'eth_signTypedData_v3' ||\n signatureMethod === 'eth_signTypedData_v4';\n\n const payload = {\n from,\n data: shouldParse ? JSON.parse(data as string) : data,\n signatureMethod,\n };\n\n snaps.forEach(({ snapId, permission }) => {\n const hasSignatureOriginCaveat = getSignatureOriginCaveat(permission);\n const signatureOrigin =\n origin && hasSignatureOriginCaveat ? origin : null;\n\n this.update((state) => {\n state.insights[id] ??= {};\n state.insights[id][snapId] = { snapId, loading: true };\n });\n\n this.#handleSnapRequest({\n snapId,\n handler: HandlerType.OnSignature,\n params: { signature: payload, signatureOrigin },\n })\n .then((response) =>\n this.#handleSnapResponse({\n id,\n snapId,\n response: response as Record<string, Json>,\n }),\n )\n .catch((error) => this.#handleSnapResponse({ id, snapId, error }));\n });\n }\n\n /**\n * Handle the transactionStatusUpdated event emitted by the TransactionController.\n * This function will remove insights for the transaction in question\n * once the transaction status has changed from unapproved.\n *\n * @param args - An options bag.\n * @param args.transactionMeta - The transaction.\n */\n #handleTransactionStatusUpdate({\n transactionMeta,\n }: {\n transactionMeta: TransactionMeta;\n }) {\n if (transactionMeta.status !== 'unapproved') {\n this.#handleInsightCleanup(transactionMeta.id);\n }\n }\n\n #handleInsightCleanup(id: string) {\n if (!this.#hasInsight(id)) {\n return;\n }\n\n // Delete interfaces from interface controller.\n Object.values(this.state.insights[id])\n .filter((insight) => insight.interfaceId)\n .forEach((insight) => {\n this.messagingSystem.call(\n 'SnapInterfaceController:deleteInterface',\n insight.interfaceId as string,\n );\n });\n\n this.update((state) => {\n delete state.insights[id];\n });\n }\n\n /**\n * Handle sending a request to a given Snap with a given payload.\n *\n * @param args - An options bag.\n * @param args.snapId - The Snap ID.\n * @param args.handler - The handler to invoke.\n * @param args.params - The JSON-RPC params to send.\n * @returns The response from the Snap.\n */\n async #handleSnapRequest({\n snapId,\n handler,\n params,\n }: {\n snapId: SnapId;\n handler: HandlerType.OnTransaction | HandlerType.OnSignature;\n params: Record<string, Json>;\n }) {\n return this.messagingSystem.call('SnapController:handleRequest', {\n snapId,\n origin: '',\n handler,\n request: {\n method: '',\n params,\n },\n });\n }\n\n /**\n * Handle response from a given Snap by persisting the response or error in state.\n *\n * @param args - An options bag.\n * @param args.id - The transaction or signature ID.\n * @param args.snapId - The Snap ID.\n * @param args.response - An optional response object returned by the Snap.\n * @param args.error - An optional error returned by the Snap.\n */\n #handleSnapResponse({\n id,\n snapId,\n response,\n error,\n }: {\n id: string;\n snapId: SnapId;\n response?: Record<string, Json>;\n error?: Error;\n }) {\n // If the insight has been cleaned up already, we can skip setting the state.\n // This may happen if a user accepts/rejects a transaction/signature faster than the Snap responds.\n if (!this.#hasInsight(id)) {\n return;\n }\n\n this.update((state) => {\n state.insights[id][snapId].loading = false;\n state.insights[id][snapId].interfaceId = response?.id as string;\n state.insights[id][snapId].severity = response?.severity as string;\n state.insights[id][snapId].error = error?.message;\n });\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"SnapInsightsController.cjs","sourceRoot":"","sources":["../../src/insights/SnapInsightsController.ts"],"names":[],"mappings":";;;;;;;;;AAKA,+DAA2D;AAM3D,mEAIqC;AAErC,uDAAoD;AACpD,2CAA2D;AAI3D,8CAA4C;AAU5C,MAAM,cAAc,GAAG,wBAAwB,CAAC;AA0DhD;;GAEG;AACH,MAAa,sBAAuB,SAAQ,gCAI3C;IACC,YAAY,EAAE,SAAS,EAAE,KAAK,EAA8B;QAC1D,KAAK,CAAC;YACJ,SAAS;YACT,QAAQ,EAAE;gBACR,QAAQ,EAAE,EAAE,OAAO,EAAE,KAAK,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AAO,EAAE;YACP,MAAM,EAAE,EAAE;YACV,MAAM;SACP;KACF,CAAC,CAAC;AACL,CAAC,mGAWmB,EAClB,EAAE,EACF,MAAM,EACN,QAAQ,EACR,KAAK,GAMN;IACC,6EAA6E;IAC7E,mGAAmG;IACnG,IAAI,CAAC,uBAAA,IAAI,6EAAY,MAAhB,IAAI,EAAa,EAAE,CAAC,EAAE,CAAC;QAC1B,OAAO;IACT,CAAC;IAED,IAAI,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE;QACpB,KAAK,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,MAAM,CAAC,CAAC,OAAO,GAAG,KAAK,CAAC;QAC3C,KAAK,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,MAAM,CAAC,CAAC,WAAW,GAAG,QAAQ,EAAE,EAAY,CAAC;QAChE,KAAK,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,MAAM,CAAC,CAAC,QAAQ,GAAG,QAAQ,EAAE,QAAkB,CAAC;QACnE,KAAK,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,MAAM,CAAC,CAAC,KAAK,GAAG,KAAK,EAAE,OAAO,CAAC;IACpD,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type {\n RestrictedMessenger,\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n} from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport type {\n Caveat,\n GetPermissions,\n ValidPermission,\n} from '@metamask/permission-controller';\nimport {\n getSignatureOriginCaveat,\n getTransactionOriginCaveat,\n SnapEndowments,\n} from '@metamask/snaps-rpc-methods';\nimport type { Json, SnapId } from '@metamask/snaps-sdk';\nimport { HandlerType } from '@metamask/snaps-utils';\nimport { hasProperty, hexToBigInt } from '@metamask/utils';\n\nimport type { DeleteInterface } from '../interface';\nimport type { GetAllSnaps, HandleSnapRequest } from '../snaps';\nimport { getRunnableSnaps } from '../snaps';\nimport type {\n TransactionControllerUnapprovedTransactionAddedEvent,\n TransactionMeta,\n SignatureStateChange,\n SignatureControllerState,\n StateSignature,\n TransactionControllerTransactionStatusUpdatedEvent,\n} from '../types';\n\nconst controllerName = 'SnapInsightsController';\n\nexport type SnapInsightsControllerAllowedActions =\n | HandleSnapRequest\n | GetAllSnaps\n | GetPermissions\n | DeleteInterface;\n\nexport type SnapInsightsControllerGetStateAction = ControllerGetStateAction<\n typeof controllerName,\n SnapInsightsControllerState\n>;\n\nexport type SnapInsightsControllerActions =\n SnapInsightsControllerGetStateAction;\n\nexport type SnapInsightControllerStateChangeEvent = ControllerStateChangeEvent<\n typeof controllerName,\n SnapInsightsControllerState\n>;\n\nexport type SnapInsightControllerEvents = SnapInsightControllerStateChangeEvent;\n\nexport type SnapInsightsControllerAllowedEvents =\n | TransactionControllerUnapprovedTransactionAddedEvent\n | TransactionControllerTransactionStatusUpdatedEvent\n | SignatureStateChange;\n\nexport type SnapInsightsControllerMessenger = RestrictedMessenger<\n typeof controllerName,\n SnapInsightsControllerActions | SnapInsightsControllerAllowedActions,\n SnapInsightControllerEvents | SnapInsightsControllerAllowedEvents,\n SnapInsightsControllerAllowedActions['type'],\n SnapInsightsControllerAllowedEvents['type']\n>;\n\nexport type SnapInsight = {\n snapId: SnapId;\n interfaceId?: string | null;\n error?: string;\n loading: boolean;\n severity?: string;\n};\n\nexport type SnapInsightsControllerState = {\n insights: Record<string, Record<SnapId, SnapInsight>>;\n};\n\nexport type SnapInsightsControllerArgs = {\n messenger: SnapInsightsControllerMessenger;\n state?: SnapInsightsControllerState;\n};\n\ntype SnapWithPermission = {\n snapId: SnapId;\n permission: ValidPermission<string, Caveat<string, Json>>;\n};\n\n/**\n * Controller for monitoring for new transactions and signatures to provide insight for.\n */\nexport class SnapInsightsController extends BaseController<\n typeof controllerName,\n SnapInsightsControllerState,\n SnapInsightsControllerMessenger\n> {\n constructor({ messenger, state }: SnapInsightsControllerArgs) {\n super({\n messenger,\n metadata: {\n insights: { persist: false, anonymous: false },\n },\n name: controllerName,\n state: { insights: {}, ...state },\n });\n\n this.messagingSystem.subscribe(\n 'TransactionController:unapprovedTransactionAdded',\n this.#handleTransaction.bind(this),\n );\n\n this.messagingSystem.subscribe(\n 'TransactionController:transactionStatusUpdated',\n this.#handleTransactionStatusUpdate.bind(this),\n );\n\n this.messagingSystem.subscribe(\n 'SignatureController:stateChange',\n this.#handleSignatureStateChange.bind(this),\n );\n }\n\n /**\n * Check if an insight already exists for a given ID.\n *\n * @param id - The ID.\n * @returns True if the insight already exists, otherwise false.\n */\n #hasInsight(id: string) {\n return hasProperty(this.state.insights, id);\n }\n\n /**\n * Get a list of runnable Snaps that have a given permission.\n * Also includes the permission object itself.\n *\n * @param permissionName - The permission name.\n * @returns A list of objects containing Snap IDs and the permission object.\n */\n #getSnapsWithPermission(permissionName: string) {\n const allSnaps = this.messagingSystem.call('SnapController:getAll');\n const filteredSnaps = getRunnableSnaps(allSnaps);\n\n return filteredSnaps.reduce<SnapWithPermission[]>((accumulator, snap) => {\n const permissions = this.messagingSystem.call(\n 'PermissionController:getPermissions',\n snap.id,\n );\n if (permissions && hasProperty(permissions, permissionName)) {\n accumulator.push({\n snapId: snap.id,\n permission: permissions[permissionName],\n });\n }\n\n return accumulator;\n }, []);\n }\n\n /**\n * Handle a newly added unapproved transaction.\n * This function fetches insights from all available Snaps\n * and populates the insights state blob with the responses.\n *\n * @param transaction - The transaction object.\n */\n #handleTransaction(transaction: TransactionMeta) {\n const { id, txParams, chainId, origin } = transaction;\n\n // This assumes that the transactions are EVM-compatible for now.\n const caipChainId = `eip155:${hexToBigInt(chainId).toString(10)}`;\n\n const snaps = this.#getSnapsWithPermission(\n SnapEndowments.TransactionInsight,\n );\n\n snaps.forEach(({ snapId, permission }) => {\n const hasTransactionOriginCaveat = getTransactionOriginCaveat(permission);\n const transactionOrigin =\n hasTransactionOriginCaveat && origin ? origin : null;\n\n this.update((state) => {\n state.insights[id] ??= {};\n state.insights[id][snapId] = { snapId, loading: true };\n });\n\n this.#handleSnapRequest({\n snapId,\n handler: HandlerType.OnTransaction,\n params: {\n transaction: txParams,\n chainId: caipChainId,\n transactionOrigin,\n },\n })\n .then((response) =>\n this.#handleSnapResponse({\n id,\n snapId,\n response: response as Record<string, Json>,\n }),\n )\n .catch((error) => this.#handleSnapResponse({ id, snapId, error }));\n });\n }\n\n /**\n * Handle the stateChange event emitted by the SignatureController.\n * This function will remove existing insights from the state when applicable, as well as\n * trigger insight fetching for newly added signatures.\n *\n * @param state - The SignatureController state blob.\n */\n #handleSignatureStateChange(state: SignatureControllerState) {\n // If any IDs have disappeared since the last state update, the insight may be cleaned up.\n for (const id of Object.keys(this.state.insights)) {\n if (\n !hasProperty(state.unapprovedTypedMessages, id) &&\n !hasProperty(state.unapprovedPersonalMsgs, id)\n ) {\n this.#handleInsightCleanup(id);\n }\n }\n\n if (\n state.unapprovedPersonalMsgCount > 0 ||\n state.unapprovedTypedMessagesCount > 0\n ) {\n const snaps = this.#getSnapsWithPermission(\n SnapEndowments.SignatureInsight,\n );\n\n // This isn't very efficient, but SignatureController doesn't expose a better event for us to use yet.\n for (const personalSignature of Object.values(\n state.unapprovedPersonalMsgs,\n )) {\n this.#handleSignature(snaps, personalSignature);\n }\n\n for (const typedMessage of Object.values(state.unapprovedTypedMessages)) {\n this.#handleSignature(snaps, typedMessage);\n }\n }\n }\n\n /**\n * Handle a newly added unapproved signature.\n * This function fetches insights from all available Snaps\n * and populates the insights state blob with the responses.\n *\n * @param snaps - A list of Snaps to invoke.\n * @param signature - The signature object.\n */\n #handleSignature(snaps: SnapWithPermission[], signature: StateSignature) {\n const { id, msgParams } = signature;\n\n if (this.#hasInsight(id)) {\n return;\n }\n\n const { from, data, signatureMethod, origin } = msgParams;\n\n /**\n * Both eth_signTypedData_v3 and eth_signTypedData_v4 methods\n * need to be parsed because their data is stringified. All other\n * signature methods do not, so they are ignored.\n */\n const shouldParse =\n signatureMethod === 'eth_signTypedData_v3' ||\n signatureMethod === 'eth_signTypedData_v4';\n\n const payload = {\n from,\n data: shouldParse ? JSON.parse(data as string) : data,\n signatureMethod,\n };\n\n snaps.forEach(({ snapId, permission }) => {\n const hasSignatureOriginCaveat = getSignatureOriginCaveat(permission);\n const signatureOrigin =\n origin && hasSignatureOriginCaveat ? origin : null;\n\n this.update((state) => {\n state.insights[id] ??= {};\n state.insights[id][snapId] = { snapId, loading: true };\n });\n\n this.#handleSnapRequest({\n snapId,\n handler: HandlerType.OnSignature,\n params: { signature: payload, signatureOrigin },\n })\n .then((response) =>\n this.#handleSnapResponse({\n id,\n snapId,\n response: response as Record<string, Json>,\n }),\n )\n .catch((error) => this.#handleSnapResponse({ id, snapId, error }));\n });\n }\n\n /**\n * Handle the transactionStatusUpdated event emitted by the TransactionController.\n * This function will remove insights for the transaction in question\n * once the transaction status has changed from unapproved.\n *\n * @param args - An options bag.\n * @param args.transactionMeta - The transaction.\n */\n #handleTransactionStatusUpdate({\n transactionMeta,\n }: {\n transactionMeta: TransactionMeta;\n }) {\n if (transactionMeta.status !== 'unapproved') {\n this.#handleInsightCleanup(transactionMeta.id);\n }\n }\n\n #handleInsightCleanup(id: string) {\n if (!this.#hasInsight(id)) {\n return;\n }\n\n // Delete interfaces from interface controller.\n Object.values(this.state.insights[id])\n .filter((insight) => insight.interfaceId)\n .forEach((insight) => {\n this.messagingSystem.call(\n 'SnapInterfaceController:deleteInterface',\n insight.interfaceId as string,\n );\n });\n\n this.update((state) => {\n delete state.insights[id];\n });\n }\n\n /**\n * Handle sending a request to a given Snap with a given payload.\n *\n * @param args - An options bag.\n * @param args.snapId - The Snap ID.\n * @param args.handler - The handler to invoke.\n * @param args.params - The JSON-RPC params to send.\n * @returns The response from the Snap.\n */\n async #handleSnapRequest({\n snapId,\n handler,\n params,\n }: {\n snapId: SnapId;\n handler: HandlerType.OnTransaction | HandlerType.OnSignature;\n params: Record<string, Json>;\n }) {\n return this.messagingSystem.call('SnapController:handleRequest', {\n snapId,\n origin: 'metamask',\n handler,\n request: {\n method: '',\n params,\n },\n });\n }\n\n /**\n * Handle response from a given Snap by persisting the response or error in state.\n *\n * @param args - An options bag.\n * @param args.id - The transaction or signature ID.\n * @param args.snapId - The Snap ID.\n * @param args.response - An optional response object returned by the Snap.\n * @param args.error - An optional error returned by the Snap.\n */\n #handleSnapResponse({\n id,\n snapId,\n response,\n error,\n }: {\n id: string;\n snapId: SnapId;\n response?: Record<string, Json>;\n error?: Error;\n }) {\n // If the insight has been cleaned up already, we can skip setting the state.\n // This may happen if a user accepts/rejects a transaction/signature faster than the Snap responds.\n if (!this.#hasInsight(id)) {\n return;\n }\n\n this.update((state) => {\n state.insights[id][snapId].loading = false;\n state.insights[id][snapId].interfaceId = response?.id as string;\n state.insights[id][snapId].severity = response?.severity as string;\n state.insights[id][snapId].error = error?.message;\n });\n }\n}\n"]}
|
|
@@ -160,7 +160,7 @@ _SnapInsightsController_instances = new WeakSet(), _SnapInsightsController_hasIn
|
|
|
160
160
|
async function _SnapInsightsController_handleSnapRequest({ snapId, handler, params, }) {
|
|
161
161
|
return this.messagingSystem.call('SnapController:handleRequest', {
|
|
162
162
|
snapId,
|
|
163
|
-
origin: '',
|
|
163
|
+
origin: 'metamask',
|
|
164
164
|
handler,
|
|
165
165
|
request: {
|
|
166
166
|
method: '',
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"SnapInsightsController.mjs","sourceRoot":"","sources":["../../src/insights/SnapInsightsController.ts"],"names":[],"mappings":";;;;;;AAKA,OAAO,EAAE,cAAc,EAAE,kCAAkC;AAM3D,OAAO,EACL,wBAAwB,EACxB,0BAA0B,EAC1B,cAAc,EACf,oCAAoC;AAErC,OAAO,EAAE,WAAW,EAAE,8BAA8B;AACpD,OAAO,EAAE,WAAW,EAAE,WAAW,EAAE,wBAAwB;AAI3D,OAAO,EAAE,gBAAgB,EAAE,2BAAiB;AAU5C,MAAM,cAAc,GAAG,wBAAwB,CAAC;AA0DhD;;GAEG;AACH,MAAM,OAAO,sBAAuB,SAAQ,cAI3C;IACC,YAAY,EAA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AAM;QACN,MAAM,EAAE,EAAE;QACV,OAAO;QACP,OAAO,EAAE;YACP,MAAM,EAAE,EAAE;YACV,MAAM;SACP;KACF,CAAC,CAAC;AACL,CAAC,mGAWmB,EAClB,EAAE,EACF,MAAM,EACN,QAAQ,EACR,KAAK,GAMN;IACC,6EAA6E;IAC7E,mGAAmG;IACnG,IAAI,CAAC,uBAAA,IAAI,6EAAY,MAAhB,IAAI,EAAa,EAAE,CAAC,EAAE,CAAC;QAC1B,OAAO;IACT,CAAC;IAED,IAAI,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE;QACpB,KAAK,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,MAAM,CAAC,CAAC,OAAO,GAAG,KAAK,CAAC;QAC3C,KAAK,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,MAAM,CAAC,CAAC,WAAW,GAAG,QAAQ,EAAE,EAAY,CAAC;QAChE,KAAK,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,MAAM,CAAC,CAAC,QAAQ,GAAG,QAAQ,EAAE,QAAkB,CAAC;QACnE,KAAK,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,MAAM,CAAC,CAAC,KAAK,GAAG,KAAK,EAAE,OAAO,CAAC;IACpD,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type {\n RestrictedMessenger,\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n} from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport type {\n Caveat,\n GetPermissions,\n ValidPermission,\n} from '@metamask/permission-controller';\nimport {\n getSignatureOriginCaveat,\n getTransactionOriginCaveat,\n SnapEndowments,\n} from '@metamask/snaps-rpc-methods';\nimport type { Json, SnapId } from '@metamask/snaps-sdk';\nimport { HandlerType } from '@metamask/snaps-utils';\nimport { hasProperty, hexToBigInt } from '@metamask/utils';\n\nimport type { DeleteInterface } from '../interface';\nimport type { GetAllSnaps, HandleSnapRequest } from '../snaps';\nimport { getRunnableSnaps } from '../snaps';\nimport type {\n TransactionControllerUnapprovedTransactionAddedEvent,\n TransactionMeta,\n SignatureStateChange,\n SignatureControllerState,\n StateSignature,\n TransactionControllerTransactionStatusUpdatedEvent,\n} from '../types';\n\nconst controllerName = 'SnapInsightsController';\n\nexport type SnapInsightsControllerAllowedActions =\n | HandleSnapRequest\n | GetAllSnaps\n | GetPermissions\n | DeleteInterface;\n\nexport type SnapInsightsControllerGetStateAction = ControllerGetStateAction<\n typeof controllerName,\n SnapInsightsControllerState\n>;\n\nexport type SnapInsightsControllerActions =\n SnapInsightsControllerGetStateAction;\n\nexport type SnapInsightControllerStateChangeEvent = ControllerStateChangeEvent<\n typeof controllerName,\n SnapInsightsControllerState\n>;\n\nexport type SnapInsightControllerEvents = SnapInsightControllerStateChangeEvent;\n\nexport type SnapInsightsControllerAllowedEvents =\n | TransactionControllerUnapprovedTransactionAddedEvent\n | TransactionControllerTransactionStatusUpdatedEvent\n | SignatureStateChange;\n\nexport type SnapInsightsControllerMessenger = RestrictedMessenger<\n typeof controllerName,\n SnapInsightsControllerActions | SnapInsightsControllerAllowedActions,\n SnapInsightControllerEvents | SnapInsightsControllerAllowedEvents,\n SnapInsightsControllerAllowedActions['type'],\n SnapInsightsControllerAllowedEvents['type']\n>;\n\nexport type SnapInsight = {\n snapId: SnapId;\n interfaceId?: string | null;\n error?: string;\n loading: boolean;\n severity?: string;\n};\n\nexport type SnapInsightsControllerState = {\n insights: Record<string, Record<SnapId, SnapInsight>>;\n};\n\nexport type SnapInsightsControllerArgs = {\n messenger: SnapInsightsControllerMessenger;\n state?: SnapInsightsControllerState;\n};\n\ntype SnapWithPermission = {\n snapId: SnapId;\n permission: ValidPermission<string, Caveat<string, Json>>;\n};\n\n/**\n * Controller for monitoring for new transactions and signatures to provide insight for.\n */\nexport class SnapInsightsController extends BaseController<\n typeof controllerName,\n SnapInsightsControllerState,\n SnapInsightsControllerMessenger\n> {\n constructor({ messenger, state }: SnapInsightsControllerArgs) {\n super({\n messenger,\n metadata: {\n insights: { persist: false, anonymous: false },\n },\n name: controllerName,\n state: { insights: {}, ...state },\n });\n\n this.messagingSystem.subscribe(\n 'TransactionController:unapprovedTransactionAdded',\n this.#handleTransaction.bind(this),\n );\n\n this.messagingSystem.subscribe(\n 'TransactionController:transactionStatusUpdated',\n this.#handleTransactionStatusUpdate.bind(this),\n );\n\n this.messagingSystem.subscribe(\n 'SignatureController:stateChange',\n this.#handleSignatureStateChange.bind(this),\n );\n }\n\n /**\n * Check if an insight already exists for a given ID.\n *\n * @param id - The ID.\n * @returns True if the insight already exists, otherwise false.\n */\n #hasInsight(id: string) {\n return hasProperty(this.state.insights, id);\n }\n\n /**\n * Get a list of runnable Snaps that have a given permission.\n * Also includes the permission object itself.\n *\n * @param permissionName - The permission name.\n * @returns A list of objects containing Snap IDs and the permission object.\n */\n #getSnapsWithPermission(permissionName: string) {\n const allSnaps = this.messagingSystem.call('SnapController:getAll');\n const filteredSnaps = getRunnableSnaps(allSnaps);\n\n return filteredSnaps.reduce<SnapWithPermission[]>((accumulator, snap) => {\n const permissions = this.messagingSystem.call(\n 'PermissionController:getPermissions',\n snap.id,\n );\n if (permissions && hasProperty(permissions, permissionName)) {\n accumulator.push({\n snapId: snap.id,\n permission: permissions[permissionName],\n });\n }\n\n return accumulator;\n }, []);\n }\n\n /**\n * Handle a newly added unapproved transaction.\n * This function fetches insights from all available Snaps\n * and populates the insights state blob with the responses.\n *\n * @param transaction - The transaction object.\n */\n #handleTransaction(transaction: TransactionMeta) {\n const { id, txParams, chainId, origin } = transaction;\n\n // This assumes that the transactions are EVM-compatible for now.\n const caipChainId = `eip155:${hexToBigInt(chainId).toString(10)}`;\n\n const snaps = this.#getSnapsWithPermission(\n SnapEndowments.TransactionInsight,\n );\n\n snaps.forEach(({ snapId, permission }) => {\n const hasTransactionOriginCaveat = getTransactionOriginCaveat(permission);\n const transactionOrigin =\n hasTransactionOriginCaveat && origin ? origin : null;\n\n this.update((state) => {\n state.insights[id] ??= {};\n state.insights[id][snapId] = { snapId, loading: true };\n });\n\n this.#handleSnapRequest({\n snapId,\n handler: HandlerType.OnTransaction,\n params: {\n transaction: txParams,\n chainId: caipChainId,\n transactionOrigin,\n },\n })\n .then((response) =>\n this.#handleSnapResponse({\n id,\n snapId,\n response: response as Record<string, Json>,\n }),\n )\n .catch((error) => this.#handleSnapResponse({ id, snapId, error }));\n });\n }\n\n /**\n * Handle the stateChange event emitted by the SignatureController.\n * This function will remove existing insights from the state when applicable, as well as\n * trigger insight fetching for newly added signatures.\n *\n * @param state - The SignatureController state blob.\n */\n #handleSignatureStateChange(state: SignatureControllerState) {\n // If any IDs have disappeared since the last state update, the insight may be cleaned up.\n for (const id of Object.keys(this.state.insights)) {\n if (\n !hasProperty(state.unapprovedTypedMessages, id) &&\n !hasProperty(state.unapprovedPersonalMsgs, id)\n ) {\n this.#handleInsightCleanup(id);\n }\n }\n\n if (\n state.unapprovedPersonalMsgCount > 0 ||\n state.unapprovedTypedMessagesCount > 0\n ) {\n const snaps = this.#getSnapsWithPermission(\n SnapEndowments.SignatureInsight,\n );\n\n // This isn't very efficient, but SignatureController doesn't expose a better event for us to use yet.\n for (const personalSignature of Object.values(\n state.unapprovedPersonalMsgs,\n )) {\n this.#handleSignature(snaps, personalSignature);\n }\n\n for (const typedMessage of Object.values(state.unapprovedTypedMessages)) {\n this.#handleSignature(snaps, typedMessage);\n }\n }\n }\n\n /**\n * Handle a newly added unapproved signature.\n * This function fetches insights from all available Snaps\n * and populates the insights state blob with the responses.\n *\n * @param snaps - A list of Snaps to invoke.\n * @param signature - The signature object.\n */\n #handleSignature(snaps: SnapWithPermission[], signature: StateSignature) {\n const { id, msgParams } = signature;\n\n if (this.#hasInsight(id)) {\n return;\n }\n\n const { from, data, signatureMethod, origin } = msgParams;\n\n /**\n * Both eth_signTypedData_v3 and eth_signTypedData_v4 methods\n * need to be parsed because their data is stringified. All other\n * signature methods do not, so they are ignored.\n */\n const shouldParse =\n signatureMethod === 'eth_signTypedData_v3' ||\n signatureMethod === 'eth_signTypedData_v4';\n\n const payload = {\n from,\n data: shouldParse ? JSON.parse(data as string) : data,\n signatureMethod,\n };\n\n snaps.forEach(({ snapId, permission }) => {\n const hasSignatureOriginCaveat = getSignatureOriginCaveat(permission);\n const signatureOrigin =\n origin && hasSignatureOriginCaveat ? origin : null;\n\n this.update((state) => {\n state.insights[id] ??= {};\n state.insights[id][snapId] = { snapId, loading: true };\n });\n\n this.#handleSnapRequest({\n snapId,\n handler: HandlerType.OnSignature,\n params: { signature: payload, signatureOrigin },\n })\n .then((response) =>\n this.#handleSnapResponse({\n id,\n snapId,\n response: response as Record<string, Json>,\n }),\n )\n .catch((error) => this.#handleSnapResponse({ id, snapId, error }));\n });\n }\n\n /**\n * Handle the transactionStatusUpdated event emitted by the TransactionController.\n * This function will remove insights for the transaction in question\n * once the transaction status has changed from unapproved.\n *\n * @param args - An options bag.\n * @param args.transactionMeta - The transaction.\n */\n #handleTransactionStatusUpdate({\n transactionMeta,\n }: {\n transactionMeta: TransactionMeta;\n }) {\n if (transactionMeta.status !== 'unapproved') {\n this.#handleInsightCleanup(transactionMeta.id);\n }\n }\n\n #handleInsightCleanup(id: string) {\n if (!this.#hasInsight(id)) {\n return;\n }\n\n // Delete interfaces from interface controller.\n Object.values(this.state.insights[id])\n .filter((insight) => insight.interfaceId)\n .forEach((insight) => {\n this.messagingSystem.call(\n 'SnapInterfaceController:deleteInterface',\n insight.interfaceId as string,\n );\n });\n\n this.update((state) => {\n delete state.insights[id];\n });\n }\n\n /**\n * Handle sending a request to a given Snap with a given payload.\n *\n * @param args - An options bag.\n * @param args.snapId - The Snap ID.\n * @param args.handler - The handler to invoke.\n * @param args.params - The JSON-RPC params to send.\n * @returns The response from the Snap.\n */\n async #handleSnapRequest({\n snapId,\n handler,\n params,\n }: {\n snapId: SnapId;\n handler: HandlerType.OnTransaction | HandlerType.OnSignature;\n params: Record<string, Json>;\n }) {\n return this.messagingSystem.call('SnapController:handleRequest', {\n snapId,\n origin: '',\n handler,\n request: {\n method: '',\n params,\n },\n });\n }\n\n /**\n * Handle response from a given Snap by persisting the response or error in state.\n *\n * @param args - An options bag.\n * @param args.id - The transaction or signature ID.\n * @param args.snapId - The Snap ID.\n * @param args.response - An optional response object returned by the Snap.\n * @param args.error - An optional error returned by the Snap.\n */\n #handleSnapResponse({\n id,\n snapId,\n response,\n error,\n }: {\n id: string;\n snapId: SnapId;\n response?: Record<string, Json>;\n error?: Error;\n }) {\n // If the insight has been cleaned up already, we can skip setting the state.\n // This may happen if a user accepts/rejects a transaction/signature faster than the Snap responds.\n if (!this.#hasInsight(id)) {\n return;\n }\n\n this.update((state) => {\n state.insights[id][snapId].loading = false;\n state.insights[id][snapId].interfaceId = response?.id as string;\n state.insights[id][snapId].severity = response?.severity as string;\n state.insights[id][snapId].error = error?.message;\n });\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"SnapInsightsController.mjs","sourceRoot":"","sources":["../../src/insights/SnapInsightsController.ts"],"names":[],"mappings":";;;;;;AAKA,OAAO,EAAE,cAAc,EAAE,kCAAkC;AAM3D,OAAO,EACL,wBAAwB,EACxB,0BAA0B,EAC1B,cAAc,EACf,oCAAoC;AAErC,OAAO,EAAE,WAAW,EAAE,8BAA8B;AACpD,OAAO,EAAE,WAAW,EAAE,WAAW,EAAE,wBAAwB;AAI3D,OAAO,EAAE,gBAAgB,EAAE,2BAAiB;AAU5C,MAAM,cAAc,GAAG,wBAAwB,CAAC;AA0DhD;;GAEG;AACH,MAAM,OAAO,sBAAuB,SAAQ,cAI3C;IACC,YAAY,EAAE,SAAS,EAAE,KAAK,EAA8B;QAC1D,KAAK,CAAC;YACJ,SAAS;YACT,QAAQ,EAAE;gBACR,QAAQ,EAAE,EAAE,OAAO,EAAE,KAAK,EAAE,SAAS,EAAE,KAAK,EAAE;aAC/C;YACD,IAAI,EAAE,cAAc;YACpB,KAAK,EAAE,EAAE,QAAQ,EAAE,EAAE,EAAE,GAAG,KAAK,EAAE;SAClC,CAAC,C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I,EAAa,EAAE,CAAC,EAAE,CAAC;QAC1B,OAAO;IACT,CAAC;IAED,IAAI,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE;QACpB,KAAK,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,MAAM,CAAC,CAAC,OAAO,GAAG,KAAK,CAAC;QAC3C,KAAK,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,MAAM,CAAC,CAAC,WAAW,GAAG,QAAQ,EAAE,EAAY,CAAC;QAChE,KAAK,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,MAAM,CAAC,CAAC,QAAQ,GAAG,QAAQ,EAAE,QAAkB,CAAC;QACnE,KAAK,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,MAAM,CAAC,CAAC,KAAK,GAAG,KAAK,EAAE,OAAO,CAAC;IACpD,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type {\n RestrictedMessenger,\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n} from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport type {\n Caveat,\n GetPermissions,\n ValidPermission,\n} from '@metamask/permission-controller';\nimport {\n getSignatureOriginCaveat,\n getTransactionOriginCaveat,\n SnapEndowments,\n} from '@metamask/snaps-rpc-methods';\nimport type { Json, SnapId } from '@metamask/snaps-sdk';\nimport { HandlerType } from '@metamask/snaps-utils';\nimport { hasProperty, hexToBigInt } from '@metamask/utils';\n\nimport type { DeleteInterface } from '../interface';\nimport type { GetAllSnaps, HandleSnapRequest } from '../snaps';\nimport { getRunnableSnaps } from '../snaps';\nimport type {\n TransactionControllerUnapprovedTransactionAddedEvent,\n TransactionMeta,\n SignatureStateChange,\n SignatureControllerState,\n StateSignature,\n TransactionControllerTransactionStatusUpdatedEvent,\n} from '../types';\n\nconst controllerName = 'SnapInsightsController';\n\nexport type SnapInsightsControllerAllowedActions =\n | HandleSnapRequest\n | GetAllSnaps\n | GetPermissions\n | DeleteInterface;\n\nexport type SnapInsightsControllerGetStateAction = ControllerGetStateAction<\n typeof controllerName,\n SnapInsightsControllerState\n>;\n\nexport type SnapInsightsControllerActions =\n SnapInsightsControllerGetStateAction;\n\nexport type SnapInsightControllerStateChangeEvent = ControllerStateChangeEvent<\n typeof controllerName,\n SnapInsightsControllerState\n>;\n\nexport type SnapInsightControllerEvents = SnapInsightControllerStateChangeEvent;\n\nexport type SnapInsightsControllerAllowedEvents =\n | TransactionControllerUnapprovedTransactionAddedEvent\n | TransactionControllerTransactionStatusUpdatedEvent\n | SignatureStateChange;\n\nexport type SnapInsightsControllerMessenger = RestrictedMessenger<\n typeof controllerName,\n SnapInsightsControllerActions | SnapInsightsControllerAllowedActions,\n SnapInsightControllerEvents | SnapInsightsControllerAllowedEvents,\n SnapInsightsControllerAllowedActions['type'],\n SnapInsightsControllerAllowedEvents['type']\n>;\n\nexport type SnapInsight = {\n snapId: SnapId;\n interfaceId?: string | null;\n error?: string;\n loading: boolean;\n severity?: string;\n};\n\nexport type SnapInsightsControllerState = {\n insights: Record<string, Record<SnapId, SnapInsight>>;\n};\n\nexport type SnapInsightsControllerArgs = {\n messenger: SnapInsightsControllerMessenger;\n state?: SnapInsightsControllerState;\n};\n\ntype SnapWithPermission = {\n snapId: SnapId;\n permission: ValidPermission<string, Caveat<string, Json>>;\n};\n\n/**\n * Controller for monitoring for new transactions and signatures to provide insight for.\n */\nexport class SnapInsightsController extends BaseController<\n typeof controllerName,\n SnapInsightsControllerState,\n SnapInsightsControllerMessenger\n> {\n constructor({ messenger, state }: SnapInsightsControllerArgs) {\n super({\n messenger,\n metadata: {\n insights: { persist: false, anonymous: false },\n },\n name: controllerName,\n state: { insights: {}, ...state },\n });\n\n this.messagingSystem.subscribe(\n 'TransactionController:unapprovedTransactionAdded',\n this.#handleTransaction.bind(this),\n );\n\n this.messagingSystem.subscribe(\n 'TransactionController:transactionStatusUpdated',\n this.#handleTransactionStatusUpdate.bind(this),\n );\n\n this.messagingSystem.subscribe(\n 'SignatureController:stateChange',\n this.#handleSignatureStateChange.bind(this),\n );\n }\n\n /**\n * Check if an insight already exists for a given ID.\n *\n * @param id - The ID.\n * @returns True if the insight already exists, otherwise false.\n */\n #hasInsight(id: string) {\n return hasProperty(this.state.insights, id);\n }\n\n /**\n * Get a list of runnable Snaps that have a given permission.\n * Also includes the permission object itself.\n *\n * @param permissionName - The permission name.\n * @returns A list of objects containing Snap IDs and the permission object.\n */\n #getSnapsWithPermission(permissionName: string) {\n const allSnaps = this.messagingSystem.call('SnapController:getAll');\n const filteredSnaps = getRunnableSnaps(allSnaps);\n\n return filteredSnaps.reduce<SnapWithPermission[]>((accumulator, snap) => {\n const permissions = this.messagingSystem.call(\n 'PermissionController:getPermissions',\n snap.id,\n );\n if (permissions && hasProperty(permissions, permissionName)) {\n accumulator.push({\n snapId: snap.id,\n permission: permissions[permissionName],\n });\n }\n\n return accumulator;\n }, []);\n }\n\n /**\n * Handle a newly added unapproved transaction.\n * This function fetches insights from all available Snaps\n * and populates the insights state blob with the responses.\n *\n * @param transaction - The transaction object.\n */\n #handleTransaction(transaction: TransactionMeta) {\n const { id, txParams, chainId, origin } = transaction;\n\n // This assumes that the transactions are EVM-compatible for now.\n const caipChainId = `eip155:${hexToBigInt(chainId).toString(10)}`;\n\n const snaps = this.#getSnapsWithPermission(\n SnapEndowments.TransactionInsight,\n );\n\n snaps.forEach(({ snapId, permission }) => {\n const hasTransactionOriginCaveat = getTransactionOriginCaveat(permission);\n const transactionOrigin =\n hasTransactionOriginCaveat && origin ? origin : null;\n\n this.update((state) => {\n state.insights[id] ??= {};\n state.insights[id][snapId] = { snapId, loading: true };\n });\n\n this.#handleSnapRequest({\n snapId,\n handler: HandlerType.OnTransaction,\n params: {\n transaction: txParams,\n chainId: caipChainId,\n transactionOrigin,\n },\n })\n .then((response) =>\n this.#handleSnapResponse({\n id,\n snapId,\n response: response as Record<string, Json>,\n }),\n )\n .catch((error) => this.#handleSnapResponse({ id, snapId, error }));\n });\n }\n\n /**\n * Handle the stateChange event emitted by the SignatureController.\n * This function will remove existing insights from the state when applicable, as well as\n * trigger insight fetching for newly added signatures.\n *\n * @param state - The SignatureController state blob.\n */\n #handleSignatureStateChange(state: SignatureControllerState) {\n // If any IDs have disappeared since the last state update, the insight may be cleaned up.\n for (const id of Object.keys(this.state.insights)) {\n if (\n !hasProperty(state.unapprovedTypedMessages, id) &&\n !hasProperty(state.unapprovedPersonalMsgs, id)\n ) {\n this.#handleInsightCleanup(id);\n }\n }\n\n if (\n state.unapprovedPersonalMsgCount > 0 ||\n state.unapprovedTypedMessagesCount > 0\n ) {\n const snaps = this.#getSnapsWithPermission(\n SnapEndowments.SignatureInsight,\n );\n\n // This isn't very efficient, but SignatureController doesn't expose a better event for us to use yet.\n for (const personalSignature of Object.values(\n state.unapprovedPersonalMsgs,\n )) {\n this.#handleSignature(snaps, personalSignature);\n }\n\n for (const typedMessage of Object.values(state.unapprovedTypedMessages)) {\n this.#handleSignature(snaps, typedMessage);\n }\n }\n }\n\n /**\n * Handle a newly added unapproved signature.\n * This function fetches insights from all available Snaps\n * and populates the insights state blob with the responses.\n *\n * @param snaps - A list of Snaps to invoke.\n * @param signature - The signature object.\n */\n #handleSignature(snaps: SnapWithPermission[], signature: StateSignature) {\n const { id, msgParams } = signature;\n\n if (this.#hasInsight(id)) {\n return;\n }\n\n const { from, data, signatureMethod, origin } = msgParams;\n\n /**\n * Both eth_signTypedData_v3 and eth_signTypedData_v4 methods\n * need to be parsed because their data is stringified. All other\n * signature methods do not, so they are ignored.\n */\n const shouldParse =\n signatureMethod === 'eth_signTypedData_v3' ||\n signatureMethod === 'eth_signTypedData_v4';\n\n const payload = {\n from,\n data: shouldParse ? JSON.parse(data as string) : data,\n signatureMethod,\n };\n\n snaps.forEach(({ snapId, permission }) => {\n const hasSignatureOriginCaveat = getSignatureOriginCaveat(permission);\n const signatureOrigin =\n origin && hasSignatureOriginCaveat ? origin : null;\n\n this.update((state) => {\n state.insights[id] ??= {};\n state.insights[id][snapId] = { snapId, loading: true };\n });\n\n this.#handleSnapRequest({\n snapId,\n handler: HandlerType.OnSignature,\n params: { signature: payload, signatureOrigin },\n })\n .then((response) =>\n this.#handleSnapResponse({\n id,\n snapId,\n response: response as Record<string, Json>,\n }),\n )\n .catch((error) => this.#handleSnapResponse({ id, snapId, error }));\n });\n }\n\n /**\n * Handle the transactionStatusUpdated event emitted by the TransactionController.\n * This function will remove insights for the transaction in question\n * once the transaction status has changed from unapproved.\n *\n * @param args - An options bag.\n * @param args.transactionMeta - The transaction.\n */\n #handleTransactionStatusUpdate({\n transactionMeta,\n }: {\n transactionMeta: TransactionMeta;\n }) {\n if (transactionMeta.status !== 'unapproved') {\n this.#handleInsightCleanup(transactionMeta.id);\n }\n }\n\n #handleInsightCleanup(id: string) {\n if (!this.#hasInsight(id)) {\n return;\n }\n\n // Delete interfaces from interface controller.\n Object.values(this.state.insights[id])\n .filter((insight) => insight.interfaceId)\n .forEach((insight) => {\n this.messagingSystem.call(\n 'SnapInterfaceController:deleteInterface',\n insight.interfaceId as string,\n );\n });\n\n this.update((state) => {\n delete state.insights[id];\n });\n }\n\n /**\n * Handle sending a request to a given Snap with a given payload.\n *\n * @param args - An options bag.\n * @param args.snapId - The Snap ID.\n * @param args.handler - The handler to invoke.\n * @param args.params - The JSON-RPC params to send.\n * @returns The response from the Snap.\n */\n async #handleSnapRequest({\n snapId,\n handler,\n params,\n }: {\n snapId: SnapId;\n handler: HandlerType.OnTransaction | HandlerType.OnSignature;\n params: Record<string, Json>;\n }) {\n return this.messagingSystem.call('SnapController:handleRequest', {\n snapId,\n origin: 'metamask',\n handler,\n request: {\n method: '',\n params,\n },\n });\n }\n\n /**\n * Handle response from a given Snap by persisting the response or error in state.\n *\n * @param args - An options bag.\n * @param args.id - The transaction or signature ID.\n * @param args.snapId - The Snap ID.\n * @param args.response - An optional response object returned by the Snap.\n * @param args.error - An optional error returned by the Snap.\n */\n #handleSnapResponse({\n id,\n snapId,\n response,\n error,\n }: {\n id: string;\n snapId: SnapId;\n response?: Record<string, Json>;\n error?: Error;\n }) {\n // If the insight has been cleaned up already, we can skip setting the state.\n // This may happen if a user accepts/rejects a transaction/signature faster than the Snap responds.\n if (!this.#hasInsight(id)) {\n return;\n }\n\n this.update((state) => {\n state.insights[id][snapId].loading = false;\n state.insights[id][snapId].interfaceId = response?.id as string;\n state.insights[id][snapId].severity = response?.severity as string;\n state.insights[id][snapId].error = error?.message;\n });\n }\n}\n"]}
|