@metamask/snaps-controllers 3.3.0 → 3.4.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 +14 -1
- package/dist/cjs/cronjob/CronjobController.js.map +1 -1
- package/dist/cjs/services/ExecutionService.js.map +1 -1
- package/dist/cjs/snaps/SnapController.js +17 -11
- package/dist/cjs/snaps/SnapController.js.map +1 -1
- package/dist/cjs/snaps/registry/json.js.map +1 -1
- package/dist/cjs/snaps/registry/registry.js.map +1 -1
- package/dist/esm/cronjob/CronjobController.js.map +1 -1
- package/dist/esm/services/ExecutionService.js.map +1 -1
- package/dist/esm/snaps/SnapController.js +14 -8
- package/dist/esm/snaps/SnapController.js.map +1 -1
- package/dist/esm/snaps/registry/json.js.map +1 -1
- package/dist/esm/snaps/registry/registry.js.map +1 -1
- package/dist/types/cronjob/CronjobController.d.ts +5 -4
- package/dist/types/services/ExecutionService.d.ts +4 -4
- package/dist/types/snaps/SnapController.d.ts +36 -34
- package/dist/types/snaps/registry/registry.d.ts +3 -3
- package/package.json +6 -6
package/CHANGELOG.md
CHANGED
|
@@ -6,6 +6,18 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
6
6
|
|
|
7
7
|
## [Unreleased]
|
|
8
8
|
|
|
9
|
+
## [3.4.0]
|
|
10
|
+
### Changed
|
|
11
|
+
- Use `SubtleCrypto` for checksum calculation if available ([#1953](https://github.com/MetaMask/snaps/pull/1953))
|
|
12
|
+
- This reduces the time of the checksum calculation by up to 95% in some
|
|
13
|
+
environments.
|
|
14
|
+
- Use `@metamask/snaps-sdk` package ([#1930](https://github.com/MetaMask/snaps/pull/1930), [#1949](https://github.com/MetaMask/snaps/pull/1949))
|
|
15
|
+
- This package replaces the `@metamask/snaps-types` and
|
|
16
|
+
- `@metamask/snaps-ui` packages.
|
|
17
|
+
|
|
18
|
+
### Fixed
|
|
19
|
+
- Fix support for transaction insight Snaps returning `null` ([#1952](https://github.com/MetaMask/snaps/pull/1952))
|
|
20
|
+
|
|
9
21
|
## [3.3.0]
|
|
10
22
|
### Added
|
|
11
23
|
- Add manifest localization functionality ([#1889](https://github.com/MetaMask/snaps/pull/1889))
|
|
@@ -107,7 +119,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
107
119
|
- The version of the package no longer needs to match the version of all other
|
|
108
120
|
MetaMask Snaps packages.
|
|
109
121
|
|
|
110
|
-
[Unreleased]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-controllers@3.
|
|
122
|
+
[Unreleased]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-controllers@3.4.0...HEAD
|
|
123
|
+
[3.4.0]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-controllers@3.3.0...@metamask/snaps-controllers@3.4.0
|
|
111
124
|
[3.3.0]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-controllers@3.2.0...@metamask/snaps-controllers@3.3.0
|
|
112
125
|
[3.2.0]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-controllers@3.1.1...@metamask/snaps-controllers@3.2.0
|
|
113
126
|
[3.1.1]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-controllers@3.1.0...@metamask/snaps-controllers@3.1.1
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/cronjob/CronjobController.ts"],"sourcesContent":["import type { RestrictedControllerMessenger } from '@metamask/base-controller';\nimport { BaseControllerV2 as BaseController } from '@metamask/base-controller';\nimport type { GetPermissions } from '@metamask/permission-controller';\nimport type {\n SnapId,\n ValidatedSnapId,\n TruncatedSnap,\n CronjobSpecification,\n} from '@metamask/snaps-utils';\nimport {\n HandlerType,\n parseCronExpression,\n logError,\n} from '@metamask/snaps-utils';\nimport { Duration, inMilliseconds } from '@metamask/utils';\n\nimport type {\n GetAllSnaps,\n HandleSnapRequest,\n SnapDisabled,\n SnapEnabled,\n SnapInstalled,\n SnapRemoved,\n SnapUpdated,\n} from '..';\nimport { getRunnableSnaps, SnapEndowments } from '..';\nimport { getCronjobCaveatJobs } from '../snaps/endowments/cronjob';\nimport { Timer } from '../snaps/Timer';\n\nexport type CronjobControllerActions =\n | GetAllSnaps\n | HandleSnapRequest\n | GetPermissions;\n\nexport type CronjobControllerEvents =\n | SnapInstalled\n | SnapRemoved\n | SnapUpdated\n | SnapEnabled\n | SnapDisabled;\n\nexport type CronjobControllerMessenger = RestrictedControllerMessenger<\n 'CronjobController',\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: ValidatedSnapId;\n} & CronjobSpecification;\n\nexport type StoredJobInformation = {\n lastRun: number;\n};\n\nexport type CronjobControllerState = {\n jobs: Record<string, StoredJobInformation>;\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 #messenger: CronjobControllerMessenger;\n\n #dailyTimer!: Timer;\n\n #timers: Map<string, Timer>;\n\n // Mapping from jobId to snapId\n #snapIds: Map<string, string>;\n\n constructor({ messenger, state }: CronjobControllerArgs) {\n super({\n messenger,\n metadata: {\n jobs: { persist: true, anonymous: false },\n },\n name: controllerName,\n state: {\n jobs: {},\n ...state,\n },\n });\n this.#timers = new Map();\n this.#snapIds = new Map();\n this.#messenger = messenger;\n\n this._handleSnapRegisterEvent = this._handleSnapRegisterEvent.bind(this);\n this._handleSnapUnregisterEvent =\n this._handleSnapUnregisterEvent.bind(this);\n this._handleEventSnapUpdated = this._handleEventSnapUpdated.bind(this);\n\n // Subscribe to Snap events\n /* eslint-disable @typescript-eslint/unbound-method */\n this.messagingSystem.subscribe(\n 'SnapController:snapInstalled',\n this._handleSnapRegisterEvent,\n );\n\n this.messagingSystem.subscribe(\n 'SnapController:snapRemoved',\n this._handleSnapUnregisterEvent,\n );\n\n this.messagingSystem.subscribe(\n 'SnapController:snapEnabled',\n this._handleSnapRegisterEvent,\n );\n\n this.messagingSystem.subscribe(\n 'SnapController:snapDisabled',\n this._handleSnapUnregisterEvent,\n );\n\n this.messagingSystem.subscribe(\n 'SnapController:snapUpdated',\n this._handleEventSnapUpdated,\n );\n /* eslint-enable @typescript-eslint/unbound-method */\n\n this.dailyCheckIn().catch((error) => {\n logError(error);\n });\n }\n\n /**\n * Retrieve all cronjob specifications for all runnable snaps.\n *\n * @returns Array of Cronjob specifications.\n */\n private 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 // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion\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 private getSnapJobs(snapId: ValidatedSnapId): Cronjob[] | undefined {\n const permissions = this.#messenger.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: ValidatedSnapId) {\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 private 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 private async executeCronjob(job: Cronjob) {\n this.updateJobLastRunState(job.id, Date.now());\n await this.#messenger.call('SnapController:handleRequest', {\n snapId: job.snapId,\n origin: '',\n handler: HandlerType.OnCronjob,\n request: job.request,\n });\n }\n\n /**\n * Unregister all jobs related to the given snapId.\n *\n * @param snapId - ID of a snap.\n */\n unregister(snapId: SnapId) {\n const jobs = [...this.#snapIds.entries()].filter(\n ([_, jobSnapId]) => jobSnapId === snapId,\n );\n\n if (jobs.length) {\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 }\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 private 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 * 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:snapRemoved',\n this._handleSnapUnregisterEvent,\n );\n\n this.messagingSystem.unsubscribe(\n 'SnapController:snapEnabled',\n this._handleSnapRegisterEvent,\n );\n\n this.messagingSystem.unsubscribe(\n 'SnapController:snapDisabled',\n this._handleSnapUnregisterEvent,\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) => {\n this.unregister(snapId);\n });\n }\n\n /**\n * Handle events that should cause cronjobs to be registered.\n *\n * @param snap - Basic Snap information.\n */\n private _handleSnapRegisterEvent(snap: TruncatedSnap) {\n this.register(snap.id);\n }\n\n /**\n * Handle events that should cause cronjobs to be unregistered.\n *\n * @param snap - Basic Snap information.\n */\n private _handleSnapUnregisterEvent(snap: TruncatedSnap) {\n this.unregister(snap.id);\n }\n\n /**\n * Handle cron jobs on 'snapUpdated' event.\n *\n * @param snap - Basic Snap information.\n */\n private _handleEventSnapUpdated(snap: TruncatedSnap) {\n this.unregister(snap.id);\n this.register(snap.id);\n }\n}\n"],"names":["DAILY_TIMEOUT","CronjobController","inMilliseconds","Duration","Hour","controllerName","BaseController","getAllJobs","snaps","messagingSystem","call","filteredSnaps","getRunnableSnaps","jobs","map","snap","getSnapJobs","id","flat","filter","job","undefined","snapId","permissions","messenger","permission","SnapEndowments","Cronjob","definitions","getCronjobCaveatJobs","definition","idx","register","forEach","schedule","timers","has","parsed","parseCronExpression","expression","next","now","Date","ms","getTime","timer","Timer","start","executeCronjob","catch","error","logError","delete","state","lastRun","updateJobLastRunState","set","snapIds","origin","handler","HandlerType","OnCronjob","request","unregister","entries","_","jobSnapId","length","get","cancel","jobId","update","dailyCheckIn","hasPrev","prev","dailyTimer","destroy","unsubscribe","_handleSnapRegisterEvent","_handleSnapUnregisterEvent","_handleEventSnapUpdated","constructor","metadata","persist","anonymous","name","Map","bind","subscribe"],"mappings":";;;;;;;;;;;IAiDaA,aAAa;eAAbA;;IA8BAC,iBAAiB;eAAjBA;;;gCA9EsC;4BAY5C;uBACkC;kBAWQ;yBACZ;uBACf;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsBf,MAAMD,gBAAgBE,IAAAA,qBAAc,EAAC,IAAIC,eAAQ,CAACC,IAAI;AAwB7D,MAAMC,iBAAiB;IAWrB,0CAEA,2CAEA,uCAEA,+BAA+B;AAC/B;AAZK,MAAMJ,0BAA0BK,gCAAc;IAoEnD;;;;GAIC,GACD,AAAQC,aAAwB;QAC9B,MAAMC,QAAQ,IAAI,CAACC,eAAe,CAACC,IAAI,CAAC;QACxC,MAAMC,gBAAgBC,IAAAA,kBAAgB,EAACJ;QAEvC,MAAMK,OAAOF,cAAcG,GAAG,CAAC,CAACC,OAAS,IAAI,CAACC,WAAW,CAACD,KAAKE,EAAE;QACjE,4EAA4E;QAC5E,OAAOJ,KAAKK,IAAI,GAAGC,MAAM,CAAC,CAACC,MAAQA,QAAQC;IAC7C;IAEA;;;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AC5B,+BACA,IAAI,CAACT,0BAA0B;QAGjC,IAAI,CAACtE,eAAe,CAAC+E,SAAS,CAC5B,8BACA,IAAI,CAACR,uBAAuB;QAE9B,mDAAmD,GAEnD,IAAI,CAACR,YAAY,GAAGvB,KAAK,CAAC,CAACC;YACzBC,IAAAA,oBAAQ,EAACD;QACX;IACF;AAiPF"}
|
|
1
|
+
{"version":3,"sources":["../../../src/cronjob/CronjobController.ts"],"sourcesContent":["import type { RestrictedControllerMessenger } from '@metamask/base-controller';\nimport { BaseControllerV2 as BaseController } from '@metamask/base-controller';\nimport type { GetPermissions } from '@metamask/permission-controller';\nimport type { SnapId } from '@metamask/snaps-sdk';\nimport type {\n TruncatedSnap,\n CronjobSpecification,\n} from '@metamask/snaps-utils';\nimport {\n HandlerType,\n parseCronExpression,\n logError,\n} from '@metamask/snaps-utils';\nimport { Duration, inMilliseconds } from '@metamask/utils';\n\nimport type {\n GetAllSnaps,\n HandleSnapRequest,\n SnapDisabled,\n SnapEnabled,\n SnapInstalled,\n SnapRemoved,\n SnapUpdated,\n} from '..';\nimport { getRunnableSnaps, SnapEndowments } from '..';\nimport { getCronjobCaveatJobs } from '../snaps/endowments/cronjob';\nimport { Timer } from '../snaps/Timer';\n\nexport type CronjobControllerActions =\n | GetAllSnaps\n | HandleSnapRequest\n | GetPermissions;\n\nexport type CronjobControllerEvents =\n | SnapInstalled\n | SnapRemoved\n | SnapUpdated\n | SnapEnabled\n | SnapDisabled;\n\nexport type CronjobControllerMessenger = RestrictedControllerMessenger<\n 'CronjobController',\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};\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 #messenger: CronjobControllerMessenger;\n\n #dailyTimer!: Timer;\n\n #timers: Map<string, Timer>;\n\n // Mapping from jobId to snapId\n #snapIds: Map<string, string>;\n\n constructor({ messenger, state }: CronjobControllerArgs) {\n super({\n messenger,\n metadata: {\n jobs: { persist: true, anonymous: false },\n },\n name: controllerName,\n state: {\n jobs: {},\n ...state,\n },\n });\n this.#timers = new Map();\n this.#snapIds = new Map();\n this.#messenger = messenger;\n\n this._handleSnapRegisterEvent = this._handleSnapRegisterEvent.bind(this);\n this._handleSnapUnregisterEvent =\n this._handleSnapUnregisterEvent.bind(this);\n this._handleEventSnapUpdated = this._handleEventSnapUpdated.bind(this);\n\n // Subscribe to Snap events\n /* eslint-disable @typescript-eslint/unbound-method */\n this.messagingSystem.subscribe(\n 'SnapController:snapInstalled',\n this._handleSnapRegisterEvent,\n );\n\n this.messagingSystem.subscribe(\n 'SnapController:snapRemoved',\n this._handleSnapUnregisterEvent,\n );\n\n this.messagingSystem.subscribe(\n 'SnapController:snapEnabled',\n this._handleSnapRegisterEvent,\n );\n\n this.messagingSystem.subscribe(\n 'SnapController:snapDisabled',\n this._handleSnapUnregisterEvent,\n );\n\n this.messagingSystem.subscribe(\n 'SnapController:snapUpdated',\n this._handleEventSnapUpdated,\n );\n /* eslint-enable @typescript-eslint/unbound-method */\n\n this.dailyCheckIn().catch((error) => {\n logError(error);\n });\n }\n\n /**\n * Retrieve all cronjob specifications for all runnable snaps.\n *\n * @returns Array of Cronjob specifications.\n */\n private 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 // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion\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 private getSnapJobs(snapId: SnapId): Cronjob[] | undefined {\n const permissions = this.#messenger.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 private 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 private async executeCronjob(job: Cronjob) {\n this.updateJobLastRunState(job.id, Date.now());\n await this.#messenger.call('SnapController:handleRequest', {\n snapId: job.snapId,\n origin: '',\n handler: HandlerType.OnCronjob,\n request: job.request,\n });\n }\n\n /**\n * Unregister all jobs related to the given snapId.\n *\n * @param snapId - ID of a snap.\n */\n unregister(snapId: string) {\n const jobs = [...this.#snapIds.entries()].filter(\n ([_, jobSnapId]) => jobSnapId === snapId,\n );\n\n if (jobs.length) {\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 }\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 private 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 * 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:snapRemoved',\n this._handleSnapUnregisterEvent,\n );\n\n this.messagingSystem.unsubscribe(\n 'SnapController:snapEnabled',\n this._handleSnapRegisterEvent,\n );\n\n this.messagingSystem.unsubscribe(\n 'SnapController:snapDisabled',\n this._handleSnapUnregisterEvent,\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) => {\n this.unregister(snapId);\n });\n }\n\n /**\n * Handle events that should cause cronjobs to be registered.\n *\n * @param snap - Basic Snap information.\n */\n private _handleSnapRegisterEvent(snap: TruncatedSnap) {\n this.register(snap.id);\n }\n\n /**\n * Handle events that should cause cronjobs to be unregistered.\n *\n * @param snap - Basic Snap information.\n */\n private _handleSnapUnregisterEvent(snap: TruncatedSnap) {\n this.unregister(snap.id);\n }\n\n /**\n * Handle cron jobs on 'snapUpdated' event.\n *\n * @param snap - Basic Snap information.\n */\n private _handleEventSnapUpdated(snap: TruncatedSnap) {\n this.unregister(snap.id);\n this.register(snap.id);\n }\n}\n"],"names":["DAILY_TIMEOUT","CronjobController","inMilliseconds","Duration","Hour","controllerName","BaseController","getAllJobs","snaps","messagingSystem","call","filteredSnaps","getRunnableSnaps","jobs","map","snap","getSnapJobs","id","flat","filter","job","undefined","snapId","permissions","messenger","permission","SnapEndowments","Cronjob","definitions","getCronjobCaveatJobs","definition","idx","register","forEach","schedule","timers","has","parsed","parseCronExpression","expression","next","now","Date","ms","getTime","timer","Timer","start","executeCronjob","catch","error","logError","delete","state","lastRun","updateJobLastRunState","set","snapIds","origin","handler","HandlerType","OnCronjob","request","unregister","entries","_","jobSnapId","length","get","cancel","jobId","update","dailyCheckIn","hasPrev","prev","dailyTimer","destroy","unsubscribe","_handleSnapRegisterEvent","_handleSnapUnregisterEvent","_handleEventSnapUpdated","constructor","metadata","persist","anonymous","name","Map","bind","subscribe"],"mappings":";;;;;;;;;;;IAgDaA,aA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AA,KAAA;;QAGA,gCAAA;;mBAAA,KAAA;;uCAcQlB,SAAS,IAAImD;uCACb7B,UAAU,IAAI6B;uCACd9D,YAAYA;QAElB,IAAI,CAACsD,wBAAwB,GAAG,IAAI,CAACA,wBAAwB,CAACS,IAAI,CAAC,IAAI;QACvE,IAAI,CAACR,0BAA0B,GAC7B,IAAI,CAACA,0BAA0B,CAACQ,IAAI,CAAC,IAAI;QAC3C,IAAI,CAACP,uBAAuB,GAAG,IAAI,CAACA,uBAAuB,CAACO,IAAI,CAAC,IAAI;QAErE,2BAA2B;QAC3B,oDAAoD,GACpD,IAAI,CAAC9E,eAAe,CAAC+E,SAAS,CAC5B,gCACA,IAAI,CAACV,wBAAwB;QAG/B,IAAI,CAACrE,eAAe,CAAC+E,SAAS,CAC5B,8BACA,IAAI,CAACT,0BAA0B;QAGjC,IAAI,CAACtE,eAAe,CAAC+E,SAAS,CAC5B,8BACA,IAAI,CAACV,wBAAwB;QAG/B,IAAI,CAACrE,eAAe,CAAC+E,SAAS,CAC5B,+BACA,IAAI,CAACT,0BAA0B;QAGjC,IAAI,CAACtE,eAAe,CAAC+E,SAAS,CAC5B,8BACA,IAAI,CAACR,uBAAuB;QAE9B,mDAAmD,GAEnD,IAAI,CAACR,YAAY,GAAGvB,KAAK,CAAC,CAACC;YACzBC,IAAAA,oBAAQ,EAACD;QACX;IACF;AAiPF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/services/ExecutionService.ts"],"sourcesContent":["import type { RestrictedControllerMessenger } from '@metamask/base-controller';\nimport type {
|
|
1
|
+
{"version":3,"sources":["../../../src/services/ExecutionService.ts"],"sourcesContent":["import type { RestrictedControllerMessenger } from '@metamask/base-controller';\nimport type { SnapRpcHookArgs } from '@metamask/snaps-utils';\nimport type { Json } from '@metamask/utils';\n\ntype TerminateSnap = (snapId: string) => Promise<void>;\ntype TerminateAll = () => Promise<void>;\ntype ExecuteSnap = (snapData: SnapExecutionData) => Promise<unknown>;\n\ntype HandleRpcRequest = (\n snapId: string,\n options: SnapRpcHookArgs,\n) => Promise<unknown>;\n\nexport interface ExecutionService {\n terminateSnap: TerminateSnap;\n terminateAllSnaps: TerminateAll;\n executeSnap: ExecuteSnap;\n handleRpcRequest: HandleRpcRequest;\n}\n\nexport type SnapExecutionData = {\n snapId: string;\n sourceCode: string;\n endowments?: Json;\n};\n\nexport type SnapErrorJson = {\n message: string;\n code: number;\n data?: Json;\n};\n\nconst controllerName = 'ExecutionService';\n\nexport type ErrorMessageEvent = {\n type: 'ExecutionService:unhandledError';\n payload: [string, SnapErrorJson];\n};\n\nexport type OutboundRequest = {\n type: 'ExecutionService:outboundRequest';\n payload: [string];\n};\n\nexport type OutboundResponse = {\n type: 'ExecutionService:outboundResponse';\n payload: [string];\n};\n\nexport type ExecutionServiceEvents =\n | ErrorMessageEvent\n | OutboundRequest\n | OutboundResponse;\n\n/**\n * Handles RPC request.\n */\nexport type HandleRpcRequestAction = {\n type: `${typeof controllerName}:handleRpcRequest`;\n handler: ExecutionService['handleRpcRequest'];\n};\n\n/**\n * Executes a given snap.\n */\nexport type ExecuteSnapAction = {\n type: `${typeof controllerName}:executeSnap`;\n handler: ExecutionService['executeSnap'];\n};\n\n/**\n * Terminates a given snap.\n */\nexport type TerminateSnapAction = {\n type: `${typeof controllerName}:terminateSnap`;\n handler: ExecutionService['terminateSnap'];\n};\n\n/**\n * Terminates all snaps.\n */\nexport type TerminateAllSnapsAction = {\n type: `${typeof controllerName}:terminateAllSnaps`;\n handler: ExecutionService['terminateAllSnaps'];\n};\n\nexport type ExecutionServiceActions =\n | HandleRpcRequestAction\n | ExecuteSnapAction\n | TerminateSnapAction\n | TerminateAllSnapsAction;\n\nexport type ExecutionServiceMessenger = RestrictedControllerMessenger<\n 'ExecutionService',\n ExecutionServiceActions,\n ExecutionServiceEvents,\n ExecutionServiceActions['type'],\n ExecutionServiceEvents['type']\n>;\n"],"names":["controllerName"],"mappings":";;;;AAgCA,MAAMA,iBAAiB"}
|
|
@@ -29,7 +29,7 @@ const _basecontroller = require("@metamask/base-controller");
|
|
|
29
29
|
const _permissioncontroller = require("@metamask/permission-controller");
|
|
30
30
|
const _rpcerrors = require("@metamask/rpc-errors");
|
|
31
31
|
const _snapsrpcmethods = require("@metamask/snaps-rpc-methods");
|
|
32
|
-
const
|
|
32
|
+
const _snapssdk = require("@metamask/snaps-sdk");
|
|
33
33
|
const _snapsutils = require("@metamask/snaps-utils");
|
|
34
34
|
const _utils = require("@metamask/utils");
|
|
35
35
|
const _fsm = require("@xstate/fsm");
|
|
@@ -446,7 +446,7 @@ class SnapController extends _basecontroller.BaseControllerV2 {
|
|
|
446
446
|
* @param path - The path to the requested file.
|
|
447
447
|
* @param encoding - An optional requested file encoding.
|
|
448
448
|
* @returns The file requested in the chosen file encoding or null if the file is not found.
|
|
449
|
-
*/ getSnapFile(snapId, path, encoding =
|
|
449
|
+
*/ getSnapFile(snapId, path, encoding = _snapssdk.AuxiliaryFileEncoding.Base64) {
|
|
450
450
|
const snap = this.getExpect(snapId);
|
|
451
451
|
const normalizedPath = (0, _snapsutils.normalizeRelative)(path);
|
|
452
452
|
const value = snap.auxiliaryFiles?.find((file)=>file.path === normalizedPath)?.value;
|
|
@@ -1164,12 +1164,12 @@ class SnapController extends _basecontroller.BaseControllerV2 {
|
|
|
1164
1164
|
this.messagingSystem.subscribe('ExecutionService:outboundResponse', this._onOutboundResponse);
|
|
1165
1165
|
/* eslint-enable @typescript-eslint/unbound-method */ this.messagingSystem.subscribe('SnapController:snapInstalled', ({ id })=>{
|
|
1166
1166
|
_class_private_method_get(this, _callLifecycleHook, callLifecycleHook).call(this, id, _snapsutils.HandlerType.OnInstall).catch((error)=>{
|
|
1167
|
-
(0, _snapsutils.logError)(`Error when calling \`onInstall\` lifecycle hook for snap "${id}": ${(0,
|
|
1167
|
+
(0, _snapsutils.logError)(`Error when calling \`onInstall\` lifecycle hook for snap "${id}": ${(0, _snapssdk.getErrorMessage)(error)}`);
|
|
1168
1168
|
});
|
|
1169
1169
|
});
|
|
1170
1170
|
this.messagingSystem.subscribe('SnapController:snapUpdated', ({ id })=>{
|
|
1171
1171
|
_class_private_method_get(this, _callLifecycleHook, callLifecycleHook).call(this, id, _snapsutils.HandlerType.OnUpdate).catch((error)=>{
|
|
1172
|
-
(0, _snapsutils.logError)(`Error when calling \`onUpdate\` lifecycle hook for snap "${id}": ${(0,
|
|
1172
|
+
(0, _snapsutils.logError)(`Error when calling \`onUpdate\` lifecycle hook for snap "${id}": ${(0, _snapssdk.getErrorMessage)(error)}`);
|
|
1173
1173
|
});
|
|
1174
1174
|
});
|
|
1175
1175
|
_class_private_method_get(this, _initializeStateMachine, initializeStateMachine).call(this);
|
|
@@ -1522,13 +1522,13 @@ async function fetchSnap(snapId, location) {
|
|
|
1522
1522
|
auxiliaryFiles,
|
|
1523
1523
|
localizationFiles: validatedLocalizationFiles
|
|
1524
1524
|
};
|
|
1525
|
-
(0, _snapsutils.validateFetchedSnap)(files);
|
|
1525
|
+
await (0, _snapsutils.validateFetchedSnap)(files);
|
|
1526
1526
|
return {
|
|
1527
1527
|
files,
|
|
1528
1528
|
location
|
|
1529
1529
|
};
|
|
1530
1530
|
} catch (error) {
|
|
1531
|
-
throw new Error(`Failed to fetch snap "${snapId}": ${(0,
|
|
1531
|
+
throw new Error(`Failed to fetch snap "${snapId}": ${(0, _snapssdk.getErrorMessage)(error)}.`);
|
|
1532
1532
|
}
|
|
1533
1533
|
}
|
|
1534
1534
|
function validateSnapPermissions(processedPermissions) {
|
|
@@ -1613,14 +1613,20 @@ function checkPhishingList(origin) {
|
|
|
1613
1613
|
async function assertSnapRpcRequestResult(handlerType, result) {
|
|
1614
1614
|
switch(handlerType){
|
|
1615
1615
|
case _snapsutils.HandlerType.OnTransaction:
|
|
1616
|
-
|
|
1617
|
-
|
|
1618
|
-
|
|
1619
|
-
|
|
1616
|
+
{
|
|
1617
|
+
(0, _utils.assertStruct)(result, _snapsutils.OnTransactionResponseStruct);
|
|
1618
|
+
// Null is an allowed return value here
|
|
1619
|
+
if (result === null) {
|
|
1620
|
+
return;
|
|
1621
|
+
}
|
|
1622
|
+
await _class_private_method_get(this, _triggerPhishingListUpdate, triggerPhishingListUpdate).call(this);
|
|
1623
|
+
(0, _snapsutils.validateComponentLinks)(result.content, _class_private_method_get(this, _checkPhishingList, checkPhishingList).bind(this));
|
|
1624
|
+
break;
|
|
1625
|
+
}
|
|
1620
1626
|
case _snapsutils.HandlerType.OnHomePage:
|
|
1621
1627
|
(0, _utils.assertStruct)(result, _snapsutils.OnHomePageResponseStruct);
|
|
1622
1628
|
await _class_private_method_get(this, _triggerPhishingListUpdate, triggerPhishingListUpdate).call(this);
|
|
1623
|
-
(0,
|
|
1629
|
+
(0, _snapsutils.validateComponentLinks)(result.content, _class_private_method_get(this, _checkPhishingList, checkPhishingList).bind(this));
|
|
1624
1630
|
break;
|
|
1625
1631
|
default:
|
|
1626
1632
|
break;
|