@metamask/snaps-controllers 0.24.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.
Files changed (111) hide show
  1. package/LICENSE +18 -0
  2. package/README.md +3 -0
  3. package/dist/cronjob/CronjobController.d.ts +115 -0
  4. package/dist/cronjob/CronjobController.js +231 -0
  5. package/dist/cronjob/CronjobController.js.map +1 -0
  6. package/dist/cronjob/index.d.ts +1 -0
  7. package/dist/cronjob/index.js +18 -0
  8. package/dist/cronjob/index.js.map +1 -0
  9. package/dist/fsm.d.ts +24 -0
  10. package/dist/fsm.js +75 -0
  11. package/dist/fsm.js.map +1 -0
  12. package/dist/index.d.ts +6 -0
  13. package/dist/index.js +22 -0
  14. package/dist/index.js.map +1 -0
  15. package/dist/multichain/MultiChainController.d.ts +135 -0
  16. package/dist/multichain/MultiChainController.js +348 -0
  17. package/dist/multichain/MultiChainController.js.map +1 -0
  18. package/dist/multichain/index.d.ts +3 -0
  19. package/dist/multichain/index.js +20 -0
  20. package/dist/multichain/index.js.map +1 -0
  21. package/dist/multichain/matching.d.ts +9 -0
  22. package/dist/multichain/matching.js +58 -0
  23. package/dist/multichain/matching.js.map +1 -0
  24. package/dist/multichain/middleware.d.ts +14 -0
  25. package/dist/multichain/middleware.js +42 -0
  26. package/dist/multichain/middleware.js.map +1 -0
  27. package/dist/services/AbstractExecutionService.d.ts +124 -0
  28. package/dist/services/AbstractExecutionService.js +316 -0
  29. package/dist/services/AbstractExecutionService.js.map +1 -0
  30. package/dist/services/ExecutionService.d.ts +68 -0
  31. package/dist/services/ExecutionService.js +4 -0
  32. package/dist/services/ExecutionService.js.map +1 -0
  33. package/dist/services/browser.d.ts +3 -0
  34. package/dist/services/browser.js +21 -0
  35. package/dist/services/browser.js.map +1 -0
  36. package/dist/services/iframe/IframeExecutionService.d.ts +25 -0
  37. package/dist/services/iframe/IframeExecutionService.js +82 -0
  38. package/dist/services/iframe/IframeExecutionService.js.map +1 -0
  39. package/dist/services/iframe/index.d.ts +1 -0
  40. package/dist/services/iframe/index.js +18 -0
  41. package/dist/services/iframe/index.js.map +1 -0
  42. package/dist/services/iframe/test/fixJSDOMPostMessageEventSource.d.ts +3 -0
  43. package/dist/services/iframe/test/fixJSDOMPostMessageEventSource.js +74 -0
  44. package/dist/services/iframe/test/fixJSDOMPostMessageEventSource.js.map +1 -0
  45. package/dist/services/iframe/test/server.d.ts +11 -0
  46. package/dist/services/iframe/test/server.js +71 -0
  47. package/dist/services/iframe/test/server.js.map +1 -0
  48. package/dist/services/index.d.ts +4 -0
  49. package/dist/services/index.js +21 -0
  50. package/dist/services/index.js.map +1 -0
  51. package/dist/services/node/NodeProcessExecutionService.d.ts +11 -0
  52. package/dist/services/node/NodeProcessExecutionService.js +18 -0
  53. package/dist/services/node/NodeProcessExecutionService.js.map +1 -0
  54. package/dist/services/node/NodeThreadExecutionService.d.ts +11 -0
  55. package/dist/services/node/NodeThreadExecutionService.js +18 -0
  56. package/dist/services/node/NodeThreadExecutionService.js.map +1 -0
  57. package/dist/services/node/index.d.ts +2 -0
  58. package/dist/services/node/index.js +19 -0
  59. package/dist/services/node/index.js.map +1 -0
  60. package/dist/snaps/RequestQueue.d.ts +24 -0
  61. package/dist/snaps/RequestQueue.js +47 -0
  62. package/dist/snaps/RequestQueue.js.map +1 -0
  63. package/dist/snaps/SnapController.d.ts +600 -0
  64. package/dist/snaps/SnapController.js +1314 -0
  65. package/dist/snaps/SnapController.js.map +1 -0
  66. package/dist/snaps/Timer.d.ts +39 -0
  67. package/dist/snaps/Timer.js +86 -0
  68. package/dist/snaps/Timer.js.map +1 -0
  69. package/dist/snaps/endowments/cronjob.d.ts +49 -0
  70. package/dist/snaps/endowments/cronjob.js +105 -0
  71. package/dist/snaps/endowments/cronjob.js.map +1 -0
  72. package/dist/snaps/endowments/enum.d.ts +8 -0
  73. package/dist/snaps/endowments/enum.js +13 -0
  74. package/dist/snaps/endowments/enum.js.map +1 -0
  75. package/dist/snaps/endowments/ethereum-provider.d.ts +13 -0
  76. package/dist/snaps/endowments/ethereum-provider.js +31 -0
  77. package/dist/snaps/endowments/ethereum-provider.js.map +1 -0
  78. package/dist/snaps/endowments/index.d.ts +67 -0
  79. package/dist/snaps/endowments/index.js +39 -0
  80. package/dist/snaps/endowments/index.js.map +1 -0
  81. package/dist/snaps/endowments/keyring.d.ts +39 -0
  82. package/dist/snaps/endowments/keyring.js +103 -0
  83. package/dist/snaps/endowments/keyring.js.map +1 -0
  84. package/dist/snaps/endowments/long-running.d.ts +13 -0
  85. package/dist/snaps/endowments/long-running.js +28 -0
  86. package/dist/snaps/endowments/long-running.js.map +1 -0
  87. package/dist/snaps/endowments/network-access.d.ts +13 -0
  88. package/dist/snaps/endowments/network-access.js +29 -0
  89. package/dist/snaps/endowments/network-access.js.map +1 -0
  90. package/dist/snaps/endowments/transaction-insight.d.ts +38 -0
  91. package/dist/snaps/endowments/transaction-insight.js +106 -0
  92. package/dist/snaps/endowments/transaction-insight.js.map +1 -0
  93. package/dist/snaps/index.d.ts +4 -0
  94. package/dist/snaps/index.js +21 -0
  95. package/dist/snaps/index.js.map +1 -0
  96. package/dist/snaps/selectors.d.ts +2 -0
  97. package/dist/snaps/selectors.js +6 -0
  98. package/dist/snaps/selectors.js.map +1 -0
  99. package/dist/snaps/utils/index.d.ts +2 -0
  100. package/dist/snaps/utils/index.js +19 -0
  101. package/dist/snaps/utils/index.js.map +1 -0
  102. package/dist/snaps/utils/npm.d.ts +14 -0
  103. package/dist/snaps/utils/npm.js +81 -0
  104. package/dist/snaps/utils/npm.js.map +1 -0
  105. package/dist/snaps/utils/stream.d.ts +30 -0
  106. package/dist/snaps/utils/stream.js +124 -0
  107. package/dist/snaps/utils/stream.js.map +1 -0
  108. package/dist/utils.d.ts +128 -0
  109. package/dist/utils.js +92 -0
  110. package/dist/utils.js.map +1 -0
  111. package/package.json +99 -0
@@ -0,0 +1 @@
1
+ {"version":3,"file":"SnapController.js","sourceRoot":"","sources":["../../src/snaps/S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CAAC,MAAM,IAAI,CAAC,eAAe,CAAC,IAAI,CAC9B,qCAAqC,EACrC,MAAM,CACP,CAAC,mCAAI,EAAE,CAAC;IAEX,MAAM,cAAc,GAAG,IAAA,eAAO,EAAC,qBAAqB,EAAE,cAAc,CAAC,CAAC;IACtE,qFAAqF;IACrF,oDAAoD;IACpD,MAAM,iBAAiB,GAAG,IAAA,eAAO,EAAC,cAAc,EAAE,qBAAqB,CAAC,CAAC;IAEzE,sEAAsE;IACtE,qGAAqG;IACrG,MAAM,mBAAmB,GAAG,IAAA,eAAO,EAAC,cAAc,EAAE,iBAAiB,CAAC,CAAC;IAEvE,OAAO,EAAE,cAAc,EAAE,iBAAiB,EAAE,mBAAmB,EAAE,CAAC;AACpE,CAAC","sourcesContent":["import passworder from '@metamask/browser-passworder';\nimport {\n AddApprovalRequest,\n BaseControllerV2 as BaseController,\n Caveat,\n GetEndowments,\n GetPermissions,\n GrantPermissions,\n HasPermission,\n HasPermissions,\n PermissionConstraint,\n PermissionsRequest,\n RestrictedControllerMessenger,\n RevokeAllPermissions,\n RevokePermissionForAllSubjects,\n RevokePermissions,\n SubjectPermissions,\n ValidPermission,\n} from '@metamask/controllers';\nimport {\n assertIsSnapManifest,\n BlockedSnapInfo,\n DEFAULT_ENDOWMENTS,\n DEFAULT_REQUESTED_SNAP_VERSION,\n fromEntries,\n getSnapPermissionName,\n getSnapPrefix,\n gtVersion,\n InstallSnapsResult,\n isValidSnapVersionRange,\n LOCALHOST_HOSTNAMES,\n NpmSnapFileNames,\n PersistedSnap,\n ProcessSnapResult,\n RequestedSnapPermissions,\n resolveVersion,\n satisfiesVersionRange,\n Snap,\n SnapId,\n SnapIdPrefixes,\n SnapManifest,\n SnapPermissions,\n SnapRpcHook,\n SnapRpcHookArgs,\n SnapStatus,\n SnapStatusEvents,\n SNAP_PREFIX,\n SNAP_PREFIX_REGEX,\n StatusContext,\n StatusEvents,\n StatusStates,\n TruncatedSnap,\n TruncatedSnapFields,\n ValidatedSnapId,\n validateSnapId,\n validateSnapShasum,\n} from '@metamask/snaps-utils';\nimport {\n assert,\n assertExhaustive,\n Duration,\n hasProperty,\n inMilliseconds,\n isNonEmptyArray,\n Json,\n timeSince,\n} from '@metamask/utils';\nimport { createMachine, interpret, StateMachine } from '@xstate/fsm';\nimport { ethErrors, serializeError } from 'eth-rpc-errors';\n\nimport type { Patch } from 'immer';\nimport { nanoid } from 'nanoid';\n\nimport { caveatMappers } from '@metamask/rpc-methods';\nimport { forceStrict, validateMachine } from '../fsm';\nimport {\n ExecuteSnapAction,\n ExecutionServiceEvents,\n HandleRpcRequestAction,\n SnapErrorJson,\n TerminateAllSnapsAction,\n TerminateSnapAction,\n} from '../services/ExecutionService';\nimport { hasTimedOut, setDiff, withTimeout } from '../utils';\nimport { endowmentCaveatMappers, SnapEndowments } from './endowments';\nimport { RequestQueue } from './RequestQueue';\nimport { fetchNpmSnap } from './utils';\n\nimport { Timer } from './Timer';\n\nexport const controllerName = 'SnapController';\n\n// TODO: Figure out how to name these\nexport const SNAP_APPROVAL_INSTALL = 'wallet_installSnap';\nexport const SNAP_APPROVAL_UPDATE = 'wallet_updateSnap';\n\nconst TRUNCATED_SNAP_PROPERTIES = new Set<TruncatedSnapFields>([\n 'initialPermissions',\n 'id',\n 'permissionName',\n 'version',\n 'enabled',\n 'blocked',\n]);\n\nexport type PendingRequest = {\n requestId: unknown;\n timer: Timer;\n};\n\n/**\n * A wrapper type for any data stored during runtime of Snaps.\n * It is not persisted in state as it contains non-serializable data and is only relevant for the\n * current session.\n */\nexport interface SnapRuntimeData {\n /**\n * A promise that resolves when the Snap has finished installing\n */\n installPromise: null | Promise<PersistedSnap>;\n\n /**\n * A Unix timestamp for the last time the Snap received an RPC request\n */\n lastRequest: null | number;\n\n /**\n * The current number of active references where this Snap is being used\n */\n activeReferences: number;\n\n /**\n * The current pending inbound requests, meaning requests that are processed by snaps.\n */\n pendingInboundRequests: PendingRequest[];\n\n /**\n * The current pending outbound requests, meaning requests made from snaps towards the MetaMask\n * extension.\n */\n pendingOutboundRequests: number;\n\n /**\n * RPC handler designated for the Snap\n */\n rpcHandler: null | SnapRpcHook;\n\n /**\n * The finite state machine interpreter for possible states that the Snap can be in such as\n * stopped, running, blocked\n *\n * @see {@link SnapController:constructor}\n */\n interpreter: StateMachine.Service<StatusContext, StatusEvents, StatusStates>;\n\n /**\n * The snap source code\n */\n sourceCode: null | string;\n\n /**\n * The snap state (encrypted)\n */\n state: null | string;\n}\n\nexport type SnapError = {\n message: string;\n code: number;\n data?: Json;\n};\n\n/**\n * The return type of {@link SnapController.fetchSnap} and its sibling methods.\n */\ntype FetchSnapResult = {\n /**\n * The manifest of the fetched Snap.\n */\n manifest: SnapManifest;\n\n /**\n * The source code of the fetched Snap.\n */\n sourceCode: string;\n\n /**\n * The raw XML content of the Snap's SVG icon, if any.\n */\n svgIcon?: string;\n};\n\n// Types that probably should be defined elsewhere in prod\ntype CloseAllConnectionsFunction = (origin: string) => void;\ntype StoredSnaps = Record<SnapId, Snap>;\n\nexport type SnapControllerState = {\n snaps: StoredSnaps;\n // This type needs to be defined but is always empty in practice.\n // eslint-disable-next-line @typescript-eslint/ban-types\n snapStates: {};\n snapErrors: {\n [internalID: string]: SnapError & { internalID: string };\n };\n};\n\nexport type PersistedSnapControllerState = SnapControllerState & {\n snaps: Record<SnapId, PersistedSnap>;\n snapStates: Record<SnapId, string>;\n};\n\n// Controller Messenger Actions\n\n/**\n * Gets the specified Snap from state.\n */\nexport type GetSnap = {\n type: `${typeof controllerName}:get`;\n handler: SnapController['get'];\n};\n\n/**\n * Handles sending an inbound request to a snap and returns its result.\n */\nexport type HandleSnapRequest = {\n type: `${typeof controllerName}:handleRequest`;\n handler: SnapController['handleRequest'];\n};\n\n/**\n * Gets the specified Snap's persisted state.\n */\nexport type GetSnapState = {\n type: `${typeof controllerName}:getSnapState`;\n handler: SnapController['getSnapState'];\n};\n\n/**\n * Checks if the specified snap exists in state.\n */\nexport type HasSnap = {\n type: `${typeof controllerName}:has`;\n handler: SnapController['has'];\n};\n\n/**\n * Updates the specified Snap's persisted state.\n */\nexport type UpdateSnapState = {\n type: `${typeof controllerName}:updateSnapState`;\n handler: SnapController['updateSnapState'];\n};\n\n/**\n * Clears the specified Snap's persisted state.\n */\nexport type ClearSnapState = {\n type: `${typeof controllerName}:clearSnapState`;\n handler: SnapController['clearSnapState'];\n};\n\n/**\n * Checks all installed snaps against the blocklist.\n */\nexport type UpdateBlockedSnaps = {\n type: `${typeof controllerName}:updateBlockedSnaps`;\n handler: SnapController['updateBlockedSnaps'];\n};\n\nexport type EnableSnap = {\n type: `${typeof controllerName}:enable`;\n handler: SnapController['enableSnap'];\n};\n\nexport type DisableSnap = {\n type: `${typeof controllerName}:disable`;\n handler: SnapController['disableSnap'];\n};\n\nexport type RemoveSnap = {\n type: `${typeof controllerName}:remove`;\n handler: SnapController['removeSnap'];\n};\n\nexport type GetPermittedSnaps = {\n type: `${typeof controllerName}:getPermitted`;\n handler: SnapController['getPermittedSnaps'];\n};\n\nexport type GetAllSnaps = {\n type: `${typeof controllerName}:getAll`;\n handler: SnapController['getAllSnaps'];\n};\n\nexport type IncrementActiveReferences = {\n type: `${typeof controllerName}:incrementActiveReferences`;\n handler: SnapController['incrementActiveReferences'];\n};\n\nexport type DecrementActiveReferences = {\n type: `${typeof controllerName}:decrementActiveReferences`;\n handler: SnapController['decrementActiveReferences'];\n};\n\nexport type InstallSnaps = {\n type: `${typeof controllerName}:install`;\n handler: SnapController['installSnaps'];\n};\n\nexport type RemoveSnapError = {\n type: `${typeof controllerName}:removeSnapError`;\n handler: SnapController['removeSnapError'];\n};\n\nexport type SnapControllerActions =\n | ClearSnapState\n | GetSnap\n | GetSnapState\n | HandleSnapRequest\n | HasSnap\n | UpdateBlockedSnaps\n | UpdateSnapState\n | EnableSnap\n | DisableSnap\n | RemoveSnap\n | GetPermittedSnaps\n | InstallSnaps\n | RemoveSnapError\n | GetAllSnaps\n | IncrementActiveReferences\n | DecrementActiveReferences;\n\n// Controller Messenger Events\n\nexport type SnapStateChange = {\n type: `${typeof controllerName}:stateChange`;\n payload: [SnapControllerState, Patch[]];\n};\n\n/**\n * Emitted when a Snap has been added to state during installation.\n */\nexport type SnapAdded = {\n type: `${typeof controllerName}:snapAdded`;\n payload: [snap: Snap, svgIcon: string | undefined];\n};\n\n/**\n * Emitted when an installed snap has been blocked.\n */\nexport type SnapBlocked = {\n type: `${typeof controllerName}:snapBlocked`;\n payload: [snapId: string, blockedSnapInfo: BlockedSnapInfo];\n};\n\n/**\n * Emitted when a snap has been started after being added and authorized during\n * installation.\n */\nexport type SnapInstalled = {\n type: `${typeof controllerName}:snapInstalled`;\n payload: [snap: TruncatedSnap];\n};\n\n/**\n * Emitted when a snap is removed.\n */\nexport type SnapRemoved = {\n type: `${typeof controllerName}:snapRemoved`;\n payload: [snap: TruncatedSnap];\n};\n\n/**\n * Emitted when an installed snap has been unblocked.\n */\nexport type SnapUnblocked = {\n type: `${typeof controllerName}:snapUnblocked`;\n payload: [snapId: string];\n};\n\n/**\n * Emitted when a snap is updated.\n */\nexport type SnapUpdated = {\n type: `${typeof controllerName}:snapUpdated`;\n payload: [snap: TruncatedSnap, oldVersion: string];\n};\n\n/**\n * Emitted when a Snap is terminated. This is different from the snap being\n * stopped as it can also be triggered when a snap fails initialization.\n */\nexport type SnapTerminated = {\n type: `${typeof controllerName}:snapTerminated`;\n payload: [snap: TruncatedSnap];\n};\n\nexport type SnapControllerEvents =\n | SnapAdded\n | SnapBlocked\n | SnapInstalled\n | SnapRemoved\n | SnapStateChange\n | SnapUnblocked\n | SnapUpdated\n | SnapTerminated;\n\nexport type AllowedActions =\n | GetEndowments\n | GetPermissions\n | HasPermission\n | HasPermissions\n | RevokePermissions\n | RevokeAllPermissions\n | RevokePermissionForAllSubjects\n | GrantPermissions\n | AddApprovalRequest\n | HandleRpcRequestAction\n | ExecuteSnapAction\n | TerminateAllSnapsAction\n | TerminateSnapAction;\n\nexport type AllowedEvents = ExecutionServiceEvents;\n\ntype SnapControllerMessenger = RestrictedControllerMessenger<\n typeof controllerName,\n SnapControllerActions | AllowedActions,\n SnapControllerEvents | AllowedEvents,\n AllowedActions['type'],\n AllowedEvents['type']\n>;\n\nexport enum AppKeyType {\n stateEncryption = 'stateEncryption',\n}\n\ntype GetAppKey = (subject: string, appKeyType: AppKeyType) => Promise<string>;\n\ntype FeatureFlags = {\n /**\n * We still need to implement new UI approval page in metamask-extension before we can allow\n * DApps to update Snaps. After it's added, this flag can be removed.\n *\n * @see {SNAP_APPROVAL_UPDATE}\n * @see {SnapController.processRequestedSnap}\n */\n dappsCanUpdateSnaps?: true;\n};\n\ntype SemVerVersion = string;\ntype SnapInfo = { version: SemVerVersion; shasum: string };\nexport type CheckSnapBlockListArg = Record<SnapId, SnapInfo>;\n\nexport type CheckSnapBlockListResult = Record<\n SnapId,\n | {\n blocked: true;\n reason?: string;\n infoUrl?: string;\n }\n | { blocked: false }\n>;\n\n/**\n * Checks whether a version of a snap is blocked.\n */\nexport type CheckSnapBlockList = (\n snapsToCheck: CheckSnapBlockListArg,\n) => Promise<CheckSnapBlockListResult>;\n\ntype SnapControllerArgs = {\n /**\n * A teardown function that allows the host to clean up its instrumentation\n * for a running snap.\n */\n closeAllConnections: CloseAllConnectionsFunction;\n\n /**\n * The names of endowment permissions whose values are the names of JavaScript\n * APIs that will be added to the snap execution environment at runtime.\n */\n environmentEndowmentPermissions: string[];\n\n /**\n * The function that will be used by the controller fo make network requests.\n * Should be compatible with {@link fetch}.\n */\n fetchFunction?: typeof fetch;\n\n /**\n * Flags that enable or disable features in the controller.\n * See {@link FeatureFlags}.\n */\n featureFlags: FeatureFlags;\n\n /**\n * A function to get an \"app key\" for a specific subject.\n */\n getAppKey: GetAppKey;\n\n /**\n * How frequently to check whether a snap is idle.\n */\n idleTimeCheckInterval?: number;\n\n /**\n * A function that checks whether the specified snap and version is blocked.\n */\n checkBlockList: CheckSnapBlockList;\n\n /**\n * The maximum amount of time that a snap may be idle.\n */\n maxIdleTime?: number;\n\n /**\n * The controller messenger.\n */\n messenger: SnapControllerMessenger;\n\n /**\n * The maximum amount of time a snap may take to process an RPC request,\n * unless it is permitted to take longer.\n */\n maxRequestTime?: number;\n\n /**\n * The npm registry URL that will be used to fetch published snaps.\n */\n npmRegistryUrl?: string;\n\n /**\n * Persisted state that will be used for rehydration.\n */\n state?: PersistedSnapControllerState;\n};\n\ntype AddSnapArgsBase = {\n id: SnapId;\n origin: string;\n versionRange?: string;\n};\n\n// A snap can either be added directly, with manifest and source code, or it\n// can be fetched and then added.\ntype AddSnapArgs =\n | AddSnapArgsBase\n | (AddSnapArgsBase & {\n manifest: SnapManifest;\n sourceCode: string;\n });\n\n// When we set a snap, we need all required properties to be present and\n// validated.\ntype SetSnapArgs = Omit<AddSnapArgs, 'id'> & {\n id: ValidatedSnapId;\n manifest: SnapManifest;\n sourceCode: string;\n svgIcon?: string;\n};\n\nconst defaultState: SnapControllerState = {\n snapErrors: {},\n snaps: {},\n snapStates: {},\n};\n\n/**\n * Truncates the properties of a snap to only ones that are easily serializable.\n *\n * @param snap - The snap to truncate.\n * @returns Object with serializable snap properties.\n */\nfunction truncateSnap(snap: Snap): TruncatedSnap {\n return Object.keys(snap).reduce((serialized, key) => {\n if (TRUNCATED_SNAP_PROPERTIES.has(key as any)) {\n serialized[key as keyof TruncatedSnap] = snap[\n key as keyof TruncatedSnap\n ] as any;\n }\n\n return serialized;\n }, {} as Partial<TruncatedSnap>) as TruncatedSnap;\n}\n\nconst name = 'SnapController';\n\n/*\n * A snap is initialized in three phases:\n * - Add: Loads the snap from a remote source and parses it.\n * - Authorize: Requests the snap's required permissions from the user.\n * - Start: Initializes the snap in its SES realm with the authorized permissions.\n */\n\nexport class SnapController extends BaseController<\n string,\n SnapControllerState,\n SnapControllerMessenger\n> {\n #closeAllConnections: CloseAllConnectionsFunction;\n\n #environmentEndowmentPermissions: string[];\n\n #featureFlags: FeatureFlags;\n\n #fetchFunction: typeof fetch;\n\n #idleTimeCheckInterval: number;\n\n #checkSnapBlockList: CheckSnapBlockList;\n\n #maxIdleTime: number;\n\n // This property cannot be hash private yet because of tests.\n private maxRequestTime: number;\n\n #npmRegistryUrl?: string;\n\n // This property cannot be hash private yet because of tests.\n private snapsRuntimeData: Map<SnapId, SnapRuntimeData>;\n\n #getAppKey: GetAppKey;\n\n #timeoutForLastRequestStatus?: number;\n\n #statusMachine!: StateMachine.Machine<\n StatusContext,\n StatusEvents,\n StatusStates\n >;\n\n constructor({\n closeAllConnections,\n messenger,\n state,\n getAppKey,\n environmentEndowmentPermissions = [],\n npmRegistryUrl,\n idleTimeCheckInterval = inMilliseconds(5, Duration.Second),\n checkBlockList,\n maxIdleTime = inMilliseconds(30, Duration.Second),\n maxRequestTime = inMilliseconds(60, Duration.Second),\n fetchFunction = globalThis.fetch.bind(globalThis),\n featureFlags = {},\n }: SnapControllerArgs) {\n super({\n messenger,\n metadata: {\n snapErrors: {\n persist: false,\n anonymous: false,\n },\n snapStates: {\n persist: () => {\n return Object.keys(this.state.snaps).reduce<\n Record<string, string | null>\n >((acc, cur) => {\n acc[cur] = this.#getRuntimeExpect(cur).state;\n return acc;\n }, {});\n },\n anonymous: false,\n },\n snaps: {\n persist: (snaps) => {\n return Object.values(snaps)\n .map((snap) => {\n return {\n ...snap,\n sourceCode: this.#getRuntimeExpect(snap.id).sourceCode,\n // At the time state is rehydrated, no snap will be running.\n status: SnapStatus.Stopped,\n };\n })\n .reduce((memo: Record<string, Snap>, snap) => {\n memo[snap.id] = snap;\n return memo;\n }, {});\n },\n anonymous: false,\n },\n },\n name,\n state: {\n ...defaultState,\n ...{\n ...state,\n snaps: Object.values(state?.snaps ?? {}).reduce(\n (memo: Record<string, Snap>, snap) => {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const { sourceCode, ...rest } = snap;\n memo[snap.id] = rest;\n return memo;\n },\n {},\n ),\n },\n },\n });\n\n this.#closeAllConnections = closeAllConnections;\n this.#environmentEndowmentPermissions = environmentEndowmentPermissions;\n this.#featureFlags = featureFlags;\n this.#fetchFunction = fetchFunction;\n this.#getAppKey = getAppKey;\n this.#idleTimeCheckInterval = idleTimeCheckInterval;\n this.#checkSnapBlockList = checkBlockList;\n this.#maxIdleTime = maxIdleTime;\n this.maxRequestTime = maxRequestTime;\n this.#npmRegistryUrl = npmRegistryUrl;\n this._onUnhandledSnapError = this._onUnhandledSnapError.bind(this);\n this._onOutboundRequest = this._onOutboundRequest.bind(this);\n this._onOutboundResponse = this._onOutboundResponse.bind(this);\n this.snapsRuntimeData = new Map();\n\n this.#pollForLastRequestStatus();\n\n this.messagingSystem.subscribe(\n 'ExecutionService:unhandledError',\n this._onUnhandledSnapError,\n );\n\n this.messagingSystem.subscribe(\n 'ExecutionService:outboundRequest',\n this._onOutboundRequest,\n );\n\n this.messagingSystem.subscribe(\n 'ExecutionService:outboundResponse',\n this._onOutboundResponse,\n );\n\n this.#initializeStateMachine();\n this.#registerMessageHandlers();\n\n Object.values(state?.snaps ?? {}).forEach((snap) =>\n this.#setupRuntime(snap.id, {\n sourceCode: snap.sourceCode,\n state: state?.snapStates?.[snap.id] ?? null,\n }),\n );\n }\n\n /**\n * We track status of a Snap using a finite-state-machine.\n * It keeps track of whether the snap is started / stopped / etc.\n *\n * @see {@link SnapController.transition} for interacting with the machine.\n */\n // We initialize the machine in the instance because the status is currently tightly coupled\n // with the SnapController - the guard checks for enabled status inside the SnapController state.\n // In the future, side-effects could be added to the machine during transitions.\n #initializeStateMachine() {\n const disableGuard = ({ snapId }: StatusContext) => {\n return this.getExpect(snapId).enabled;\n };\n\n const statusConfig: StateMachine.Config<\n StatusContext,\n StatusEvents,\n StatusStates\n > = {\n initial: SnapStatus.Installing,\n states: {\n [SnapStatus.Installing]: {\n on: {\n [SnapStatusEvents.Start]: {\n target: SnapStatus.Running,\n cond: disableGuard,\n },\n },\n },\n [SnapStatus.Updating]: {\n on: {\n [SnapStatusEvents.Start]: {\n target: SnapStatus.Running,\n cond: disableGuard,\n },\n },\n },\n [SnapStatus.Running]: {\n on: {\n [SnapStatusEvents.Stop]: SnapStatus.Stopped,\n [SnapStatusEvents.Crash]: SnapStatus.Crashed,\n },\n },\n [SnapStatus.Stopped]: {\n on: {\n [SnapStatusEvents.Start]: {\n target: SnapStatus.Running,\n cond: disableGuard,\n },\n [SnapStatusEvents.Update]: SnapStatus.Updating,\n },\n },\n [SnapStatus.Crashed]: {\n on: {\n [SnapStatusEvents.Start]: {\n target: SnapStatus.Running,\n cond: disableGuard,\n },\n },\n },\n },\n };\n this.#statusMachine = createMachine(statusConfig);\n validateMachine(this.#statusMachine);\n }\n\n /**\n * Constructor helper for registering the controller's messaging system\n * actions.\n */\n #registerMessageHandlers(): void {\n this.messagingSystem.registerActionHandler(\n `${controllerName}:clearSnapState`,\n (...args) => this.clearSnapState(...args),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:get`,\n (...args) => this.get(...args),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:getSnapState`,\n (...args) => this.getSnapState(...args),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:handleRequest`,\n (...args) => this.handleRequest(...args),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:has`,\n (...args) => this.has(...args),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:updateBlockedSnaps`,\n () => this.updateBlockedSnaps(),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:updateSnapState`,\n (...args) => this.updateSnapState(...args),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:enable`,\n (...args) => this.enableSnap(...args),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:disable`,\n (...args) => this.disableSnap(...args),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:remove`,\n (...args) => this.removeSnap(...args),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:getPermitted`,\n (...args) => this.getPermittedSnaps(...args),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:install`,\n (...args) => this.installSnaps(...args),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:removeSnapError`,\n (...args) => this.removeSnapError(...args),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:getAll`,\n (...args) => this.getAllSnaps(...args),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:incrementActiveReferences`,\n (...args) => this.incrementActiveReferences(...args),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:decrementActiveReferences`,\n (...args) => this.decrementActiveReferences(...args),\n );\n }\n\n #pollForLastRequestStatus() {\n this.#timeoutForLastRequestStatus = setTimeout(async () => {\n await this.#stopSnapsLastRequestPastMax();\n this.#pollForLastRequestStatus();\n }, this.#idleTimeCheckInterval) as unknown as number;\n }\n\n /**\n * Checks all installed snaps against the block list and\n * blocks/unblocks snaps as appropriate. See {@link SnapController.blockSnap}\n * for more information.\n */\n async updateBlockedSnaps(): Promise<void> {\n const blockedSnaps = await this.#checkSnapBlockList(\n Object.values(this.state.snaps).reduce<CheckSnapBlockListArg>(\n (blockListArg, snap) => {\n blockListArg[snap.id] = {\n version: snap.version,\n shasum: snap.manifest.source.shasum,\n };\n return blockListArg;\n },\n {},\n ),\n );\n\n await Promise.all(\n Object.entries(blockedSnaps).map(\n ([snapId, { blocked, ...blockData }]) => {\n if (blocked) {\n return this.#blockSnap(snapId, blockData);\n }\n\n return this.#unblockSnap(snapId);\n },\n ),\n );\n }\n\n /**\n * Blocks an installed snap and prevents it from being started again. Emits\n * {@link SnapBlocked}. Does nothing if the snap is not installed.\n *\n * @param snapId - The snap to block.\n * @param blockedSnapInfo - Information detailing why the snap is blocked.\n */\n async #blockSnap(\n snapId: SnapId,\n blockedSnapInfo: BlockedSnapInfo,\n ): Promise<void> {\n if (!this.has(snapId)) {\n return;\n }\n\n try {\n this.update((state: any) => {\n state.snaps[snapId].blocked = true;\n state.snaps[snapId].blockInformation = blockedSnapInfo;\n });\n\n await this.disableSnap(snapId);\n } catch (error) {\n console.error(\n `Encountered error when stopping blocked snap \"${snapId}\".`,\n error,\n );\n }\n\n this.messagingSystem.publish(\n `${controllerName}:snapBlocked`,\n snapId,\n blockedSnapInfo,\n );\n }\n\n /**\n * Unblocks a snap so that it can be enabled and started again. Emits\n * {@link SnapUnblocked}. Does nothing if the snap is not installed or already\n * unblocked.\n *\n * @param snapId - The id of the snap to unblock.\n */\n async #unblockSnap(snapId: SnapId): Promise<void> {\n if (!this.has(snapId) || !this.state.snaps[snapId].blocked) {\n return;\n }\n\n this.update((state: any) => {\n state.snaps[snapId].blocked = false;\n delete state.snaps[snapId].blockInformation;\n });\n\n this.messagingSystem.publish(`${controllerName}:snapUnblocked`, snapId);\n }\n\n /**\n * Checks the block list to determine whether a version of a snap is blocked.\n *\n * @param snapId - The snap id to check.\n * @param snapInfo - Snap information containing version and shasum.\n * @returns Whether the version of the snap is blocked or not.\n */\n async isBlocked(\n snapId: ValidatedSnapId,\n snapInfo: SnapInfo,\n ): Promise<boolean> {\n const result = await this.#checkSnapBlockList({\n [snapId]: snapInfo,\n });\n return result[snapId].blocked;\n }\n\n /**\n * Asserts that a version of a snap is not blocked. Succeeds automatically\n * if {@link SnapController._checkSnapBlockList} is undefined.\n *\n * @param snapId - The id of the snap to check.\n * @param snapInfo - Snap information containing version and shasum.\n */\n async #assertIsUnblocked(snapId: ValidatedSnapId, snapInfo: SnapInfo) {\n if (await this.isBlocked(snapId, snapInfo)) {\n throw new Error(\n `Cannot install version \"${snapInfo.version}\" of snap \"${snapId}\": the version is blocked.`,\n );\n }\n }\n\n async #stopSnapsLastRequestPastMax() {\n const entries = [...this.snapsRuntimeData.entries()];\n return Promise.all(\n entries\n .filter(\n ([_snapId, runtime]) =>\n runtime.activeReferences === 0 &&\n runtime.pendingInboundRequests.length === 0 &&\n // lastRequest should always be set here but TypeScript wants this check\n runtime.lastRequest &&\n this.#maxIdleTime &&\n timeSince(runtime.lastRequest) > this.#maxIdleTime,\n )\n .map(([snapId]) => this.stopSnap(snapId, SnapStatusEvents.Stop)),\n );\n }\n\n async _onUnhandledSnapError(snapId: SnapId, error: SnapErrorJson) {\n await this.stopSnap(snapId, SnapStatusEvents.Crash);\n this.addSnapError(error);\n }\n\n async _onOutboundRequest(snapId: SnapId) {\n const runtime = this.#getRuntimeExpect(snapId);\n // Ideally we would only pause the pending request that is making the outbound request\n // but right now we don't have a way to know which request initiated the outbound request\n runtime.pendingInboundRequests\n .filter((pendingRequest) => pendingRequest.timer.status === 'running')\n .forEach((pendingRequest) => pendingRequest.timer.pause());\n runtime.pendingOutboundRequests += 1;\n }\n\n async _onOutboundResponse(snapId: SnapId) {\n const runtime = this.#getRuntimeExpect(snapId);\n runtime.pendingOutboundRequests -= 1;\n if (runtime.pendingOutboundRequests === 0) {\n runtime.pendingInboundRequests\n .filter((pendingRequest) => pendingRequest.timer.status === 'paused')\n .forEach((pendingRequest) => pendingRequest.timer.resume());\n }\n }\n\n /**\n * Transitions between states using `snapStatusStateMachineConfig` as the template to figure out\n * the next state. This transition function uses a very minimal subset of XState conventions:\n * - supports initial state\n * - .on supports raw event target string\n * - .on supports {target, cond} object\n * - the arguments for `cond` is the `SerializedSnap` instead of Xstate convention of `(event,\n * context) => boolean`\n *\n * @param snapId - The id of the snap to transition.\n * @param event - The event enum to use to transition.\n */\n #transition(snapId: SnapId, event: StatusEvents | StatusEvents['type']) {\n const { interpreter } = this.#getRuntimeExpect(snapId);\n interpreter.send(event);\n this.update((state: any) => {\n state.snaps[snapId].status = interpreter.state.value;\n });\n }\n\n /**\n * Starts the given snap. Throws an error if no such snap exists\n * or if it is already running.\n *\n * @param snapId - The id of the Snap to start.\n */\n async startSnap(snapId: SnapId): Promise<void> {\n const runtime = this.#getRuntimeExpect(snapId);\n\n if (this.state.snaps[snapId].enabled === false) {\n throw new Error(`Snap \"${snapId}\" is disabled.`);\n }\n\n assert(runtime.sourceCode);\n\n await this.#startSnap({\n snapId,\n sourceCode: runtime.sourceCode,\n });\n }\n\n /**\n * Enables the given snap. A snap can only be started if it is enabled. A snap\n * can only be enabled if it isn't blocked.\n *\n * @param snapId - The id of the Snap to enable.\n */\n enableSnap(snapId: SnapId): void {\n this.getExpect(snapId);\n\n if (this.state.snaps[snapId].blocked) {\n throw new Error(`Snap \"${snapId}\" is blocked and cannot be enabled.`);\n }\n\n this.update((state: any) => {\n state.snaps[snapId].enabled = true;\n });\n }\n\n /**\n * Disables the given snap. A snap can only be started if it is enabled.\n *\n * @param snapId - The id of the Snap to disable.\n * @returns A promise that resolves once the snap has been disabled.\n */\n disableSnap(snapId: SnapId): Promise<void> {\n if (!this.has(snapId)) {\n throw new Error(`Snap \"${snapId}\" not found.`);\n }\n\n this.update((state: any) => {\n state.snaps[snapId].enabled = false;\n });\n\n if (this.isRunning(snapId)) {\n return this.stopSnap(snapId, SnapStatusEvents.Stop);\n }\n\n return Promise.resolve();\n }\n\n /**\n * Stops the given snap, removes all hooks, closes all connections, and\n * terminates its worker.\n *\n * @param snapId - The id of the Snap to stop.\n * @param statusEvent - The Snap status event that caused the snap to be\n * stopped.\n */\n public async stopSnap(\n snapId: SnapId,\n statusEvent:\n | SnapStatusEvents.Stop\n | SnapStatusEvents.Crash = SnapStatusEvents.Stop,\n ): Promise<void> {\n const runtime = this.#getRuntime(snapId);\n if (!runtime) {\n throw new Error(`The snap \"${snapId}\" is not running.`);\n }\n\n // Reset request tracking\n runtime.lastRequest = null;\n runtime.pendingInboundRequests = [];\n runtime.pendingOutboundRequests = 0;\n try {\n if (this.isRunning(snapId)) {\n this.#closeAllConnections(snapId);\n await this.#terminateSnap(snapId);\n }\n } finally {\n if (this.isRunning(snapId)) {\n this.#transition(snapId, statusEvent);\n }\n }\n }\n\n /**\n * Terminates the specified snap and emits the `snapTerminated` event.\n *\n * @param snapId - The snap to terminate.\n */\n async #terminateSnap(snapId: SnapId) {\n await this.messagingSystem.call('ExecutionService:terminateSnap', snapId);\n this.messagingSystem.publish(\n 'SnapController:snapTerminated',\n this.getTruncatedExpect(snapId),\n );\n }\n\n /**\n * Returns whether the given snap is running.\n * Throws an error if the snap doesn't exist.\n *\n * @param snapId - The id of the Snap to check.\n * @returns `true` if the snap is running, otherwise `false`.\n */\n isRunning(snapId: SnapId): boolean {\n return this.getExpect(snapId).status === 'running';\n }\n\n /**\n * Returns whether the given snap has been added to state.\n *\n * @param snapId - The id of the Snap to check for.\n * @returns `true` if the snap exists in the controller state, otherwise `false`.\n */\n has(snapId: SnapId): boolean {\n return Boolean(this.get(snapId));\n }\n\n /**\n * Gets the snap with the given id if it exists, including all data.\n * This should not be used if the snap is to be serializable, as e.g.\n * the snap sourceCode may be quite large.\n *\n * @param snapId - The id of the Snap to get.\n * @returns The entire snap object from the controller state.\n */\n get(snapId: SnapId): Snap | undefined {\n return this.state.snaps[snapId];\n }\n\n /**\n * Gets the snap with the given id, throws if doesn't.\n * This should not be used if the snap is to be serializable, as e.g.\n * the snap sourceCode may be quite large.\n *\n * @see {@link SnapController.get}\n * @throws {@link Error}. If the snap doesn't exist\n * @param snapId - The id of the snap to get.\n * @returns The entire snap object.\n */\n getExpect(snapId: SnapId): Snap {\n const snap = this.get(snapId);\n assert(snap !== undefined, new Error(`Snap \"${snapId}\" not found.`));\n return snap;\n }\n\n /**\n * Gets the snap with the given id if it exists, excluding any\n * non-serializable or expensive-to-serialize data.\n *\n * @param snapId - The id of the Snap to get.\n * @returns A truncated version of the snap state, that is less expensive to serialize.\n */\n // TODO(ritave): this.get returns undefined, this.getTruncated returns null\n getTruncated(snapId: SnapId): TruncatedSnap | null {\n const snap = this.get(snapId);\n\n return snap ? truncateSnap(snap) : null;\n }\n\n /**\n * Gets the snap with the given id, throw if it doesn't exist.\n *\n * @throws {@link Error}. If snap doesn't exist\n * @param snapId - The id of the snap to get.\n * @returns A truncated version of the snap state, that is less expensive to serialize.\n */\n getTruncatedExpect(snapId: SnapId): TruncatedSnap {\n return truncateSnap(this.getExpect(snapId));\n }\n\n /**\n * Updates the own state of the snap with the given id.\n * This is distinct from the state MetaMask uses to manage snaps.\n *\n * @param snapId - The id of the Snap whose state should be updated.\n * @param newSnapState - The new state of the snap.\n */\n async updateSnapState(snapId: SnapId, newSnapState: Json): Promise<void> {\n const encrypted = await this.#encryptSnapState(snapId, newSnapState);\n const runtime = this.#getRuntimeExpect(snapId);\n runtime.state = encrypted;\n }\n\n /**\n * Clears the state of the snap with the given id.\n * This is distinct from the state MetaMask uses to manage snaps.\n *\n * @param snapId - The id of the Snap whose state should be cleared.\n */\n async clearSnapState(snapId: SnapId): Promise<void> {\n const runtime = this.#getRuntimeExpect(snapId);\n runtime.state = null;\n }\n\n /**\n * Adds error from a snap to the SnapController state.\n *\n * @param snapError - The error to store on the SnapController.\n */\n addSnapError(snapError: SnapError): void {\n this.update((state: any) => {\n const id = nanoid();\n state.snapErrors[id] = {\n ...snapError,\n internalID: id,\n };\n });\n }\n\n /**\n * Removes an error by internalID from a the SnapControllers state.\n *\n * @param internalID - The internal error ID to remove on the SnapController.\n */\n async removeSnapError(internalID: string) {\n this.update((state: any) => {\n delete state.snapErrors[internalID];\n });\n }\n\n /**\n * Clears all errors from the SnapControllers state.\n *\n */\n async clearSnapErrors() {\n this.update((state: any) => {\n state.snapErrors = {};\n });\n }\n\n /**\n * Gets the own state of the snap with the given id.\n * This is distinct from the state MetaMask uses to manage snaps.\n *\n * @param snapId - The id of the Snap whose state to get.\n * @returns A promise that resolves with the decrypted snap state or null if no state exists.\n * @throws If the snap state decryption fails.\n */\n async getSnapState(snapId: SnapId): Promise<Json> {\n const { state } = this.#getRuntimeExpect(snapId);\n return state ? this.#decryptSnapState(snapId, state) : null;\n }\n\n async #getEncryptionKey(snapId: SnapId): Promise<string> {\n return this.#getAppKey(snapId, AppKeyType.stateEncryption);\n }\n\n async #encryptSnapState(snapId: SnapId, state: Json): Promise<string> {\n const appKey = await this.#getEncryptionKey(snapId);\n return passworder.encrypt(appKey, state);\n }\n\n async #decryptSnapState(snapId: SnapId, encrypted: string): Promise<Json> {\n const appKey = await this.#getEncryptionKey(snapId);\n try {\n return await passworder.decrypt(appKey, encrypted);\n } catch (err) {\n throw new Error(\n 'Failed to decrypt snap state, the state must be corrupted.',\n );\n }\n }\n\n /**\n * Completely clear the controller's state: delete all associated data,\n * handlers, event listeners, and permissions; tear down all snap providers.\n */\n clearState() {\n const snapIds = Object.keys(this.state.snaps);\n snapIds.forEach((snapId) => {\n this.#closeAllConnections(snapId);\n });\n this.messagingSystem.call('ExecutionService:terminateAllSnaps');\n snapIds.forEach(this.revokeAllSnapPermissions);\n\n this.update((state: any) => {\n state.snaps = {};\n state.snapStates = {};\n });\n }\n\n /**\n * Removes the given snap from state, and clears all associated handlers\n * and listeners.\n *\n * @param snapId - The id of the Snap.\n * @returns A promise that resolves once the snap has been removed.\n */\n async removeSnap(snapId: SnapId): Promise<void> {\n return this.removeSnaps([snapId]);\n }\n\n /**\n * Stops the given snaps, removes them from state, and clears all associated\n * permissions, handlers, and listeners.\n *\n * @param snapIds - The ids of the Snaps.\n */\n async removeSnaps(snapIds: string[]): Promise<void> {\n if (!Array.isArray(snapIds)) {\n throw new Error('Expected array of snap ids.');\n }\n\n await Promise.all(\n snapIds.map(async (snapId) => {\n const truncated = this.getTruncatedExpect(snapId);\n // Disable the snap and revoke all of its permissions before deleting\n // it. This ensures that the snap will not be restarted or otherwise\n // affect the host environment while we are deleting it.\n await this.disableSnap(snapId);\n this.revokeAllSnapPermissions(snapId);\n\n const permissionName = getSnapPermissionName(snapId);\n // Revoke all subjects access to the snap\n this.messagingSystem.call(\n 'PermissionController:revokePermissionForAllSubjects',\n permissionName,\n );\n\n this.snapsRuntimeData.delete(snapId);\n\n this.update((state: any) => {\n delete state.snaps[snapId];\n delete state.snapStates[snapId];\n });\n\n this.messagingSystem.publish(`SnapController:snapRemoved`, truncated);\n }),\n );\n }\n\n /**\n * Safely revokes all permissions granted to a Snap.\n *\n * @param snapId - The snap ID.\n */\n private async revokeAllSnapPermissions(snapId: string): Promise<void> {\n if (\n await this.messagingSystem.call(\n 'PermissionController:hasPermissions',\n snapId,\n )\n ) {\n this.messagingSystem.call(\n 'PermissionController:revokeAllPermissions',\n snapId,\n );\n }\n }\n\n /**\n * Handles incrementing the activeReferences counter.\n *\n * @param snapId - The snap id of the snap that was referenced.\n */\n incrementActiveReferences(snapId: SnapId) {\n const runtime = this.#getRuntimeExpect(snapId);\n runtime.activeReferences += 1;\n }\n\n /**\n * Handles decrement the activeReferences counter.\n *\n * @param snapId - The snap id of the snap that was referenced..\n */\n decrementActiveReferences(snapId: SnapId) {\n const runtime = this.#getRuntimeExpect(snapId);\n assert(\n runtime.activeReferences > 0,\n 'SnapController reference management is in an invalid state.',\n );\n runtime.activeReferences -= 1;\n }\n\n /**\n * Gets all snaps in their truncated format.\n *\n * @returns All installed snaps in their truncated format.\n */\n getAllSnaps(): TruncatedSnap[] {\n return Object.values(this.state.snaps).map(truncateSnap);\n }\n\n /**\n * Gets the serialized permitted snaps of the given origin, if any.\n *\n * @param origin - The origin whose permitted snaps to retrieve.\n * @returns The serialized permitted snaps for the origin.\n */\n async getPermittedSnaps(origin: string): Promise<InstallSnapsResult> {\n return Object.values(\n (await this.messagingSystem.call(\n 'PermissionController:getPermissions',\n origin,\n )) ?? {},\n ).reduce((permittedSnaps, perm) => {\n if (perm.parentCapability.startsWith(SNAP_PREFIX)) {\n const snapId = perm.parentCapability.replace(SNAP_PREFIX_REGEX, '');\n const snap = this.get(snapId);\n const truncatedSnap = this.getTruncated(snapId);\n\n if (truncatedSnap && snap?.status !== SnapStatus.Installing) {\n permittedSnaps[snapId] = truncatedSnap;\n }\n }\n return permittedSnaps;\n }, {} as InstallSnapsResult);\n }\n\n /**\n * Installs the snaps requested by the given origin, returning the snap\n * object if the origin is permitted to install it, and an authorization error\n * otherwise.\n *\n * @param origin - The origin that requested to install the snaps.\n * @param requestedSnaps - The snaps to install.\n * @returns An object of snap ids and snap objects, or errors if a\n * snap couldn't be installed.\n */\n async installSnaps(\n origin: string,\n requestedSnaps: RequestedSnapPermissions,\n ): Promise<InstallSnapsResult> {\n const result: InstallSnapsResult = {};\n\n await Promise.all(\n Object.entries(requestedSnaps).map(\n async ([snapId, { version: rawVersion }]) => {\n const version = resolveVersion(rawVersion);\n const permissionName = getSnapPermissionName(snapId);\n\n if (!isValidSnapVersionRange(version)) {\n result[snapId] = {\n error: ethErrors.rpc.invalidParams(\n `The \"version\" field must be a valid SemVer version range if specified. Received: \"${version}\".`,\n ),\n };\n return;\n }\n\n if (\n await this.messagingSystem.call(\n 'PermissionController:hasPermission',\n origin,\n permissionName,\n )\n ) {\n // Attempt to install and run the snap, storing any errors that\n // occur during the process.\n result[snapId] = {\n ...(await this.processRequestedSnap(origin, snapId, version)),\n };\n } else {\n // only allow the installation of permitted snaps\n result[snapId] = {\n error: ethErrors.provider.unauthorized(\n `Not authorized to install snap \"${snapId}\". Request the permission for the snap before attempting to install it.`,\n ),\n };\n }\n },\n ),\n );\n return result;\n }\n\n /**\n * Adds, authorizes, and runs the given snap with a snap provider.\n * Results from this method should be efficiently serializable.\n *\n * @param origin - The origin requesting the snap.\n * @param snapId - The id of the snap.\n * @param versionRange - The semver range of the snap to install.\n * @returns The resulting snap object, or an error if something went wrong.\n */\n private async processRequestedSnap(\n origin: string,\n snapId: SnapId,\n versionRange: string,\n ): Promise<ProcessSnapResult> {\n try {\n validateSnapId(snapId);\n } catch (err) {\n return {\n error: ethErrors.rpc.invalidParams(\n `\"${snapId}\" is not a valid snap id.`,\n ),\n };\n }\n\n const existingSnap = this.getTruncated(snapId);\n // For devX we always re-install local snaps.\n if (existingSnap && getSnapPrefix(snapId) !== SnapIdPrefixes.local) {\n if (satisfiesVersionRange(existingSnap.version, versionRange)) {\n return existingSnap;\n }\n\n if (this.#featureFlags.dappsCanUpdateSnaps === true) {\n try {\n const updateResult = await this.updateSnap(\n origin,\n snapId,\n versionRange,\n );\n if (updateResult === null) {\n return {\n error: ethErrors.rpc.invalidParams(\n `Snap \"${snapId}@${existingSnap.version}\" is already installed, couldn't update to a version inside requested \"${versionRange}\" range.`,\n ),\n };\n }\n return updateResult;\n } catch (err) {\n return { error: serializeError(err) };\n }\n } else {\n return {\n error: ethErrors.rpc.invalidParams(\n `Version mismatch with already installed snap. ${snapId}@${existingSnap.version} doesn't satisfy requested version ${versionRange}`,\n ),\n };\n }\n }\n\n // Existing snaps must be stopped before overwriting\n if (existingSnap && this.isRunning(snapId)) {\n await this.stopSnap(snapId, SnapStatusEvents.Stop);\n }\n\n try {\n const { sourceCode } = await this.#add({\n origin,\n id: snapId,\n versionRange,\n });\n\n await this.authorize(origin, snapId);\n\n await this.#startSnap({\n snapId,\n sourceCode,\n });\n\n const truncated = this.getTruncatedExpect(snapId);\n\n this.messagingSystem.publish(`SnapController:snapInstalled`, truncated);\n return truncated;\n } catch (err) {\n console.error(`Error when adding snap.`, err);\n if (this.has(snapId)) {\n this.removeSnap(snapId);\n }\n\n return { error: serializeError(err) };\n }\n }\n\n /**\n * Updates an installed snap. The flow is similar to\n * {@link SnapController.installSnaps}. The user will be asked if they want\n * to update, then approve any permission changes, and finally the snap will\n * be restarted.\n *\n * The update will fail if the user rejects any prompt or if the new version\n * of the snap is blocked.\n *\n * If the original version of the snap was blocked and the update succeeded,\n * the snap will be unblocked and enabled before it is restarted.\n *\n * @param origin - The origin requesting the snap update.\n * @param snapId - The id of the Snap to be updated.\n * @param newVersionRange - A semver version range in which the maximum version will be chosen.\n * @returns The snap metadata if updated, `null` otherwise.\n */\n async updateSnap(\n origin: string,\n snapId: ValidatedSnapId,\n newVersionRange: string = DEFAULT_REQUESTED_SNAP_VERSION,\n ): Promise<TruncatedSnap | null> {\n const snap = this.getExpect(snapId);\n\n if (!isValidSnapVersionRange(newVersionRange)) {\n throw new Error(\n `Received invalid snap version range: \"${newVersionRange}\".`,\n );\n }\n\n const newSnap = await this.fetchSnap(snapId, newVersionRange);\n const newVersion = newSnap.manifest.version;\n if (!gtVersion(newVersion, snap.version)) {\n console.warn(\n `Tried updating snap \"${snapId}\" within \"${newVersionRange}\" version range, but newer version \"${snap.version}\" is already installed`,\n );\n return null;\n }\n\n await this.#assertIsUnblocked(snapId, {\n version: newVersion,\n shasum: newSnap.manifest.source.shasum,\n });\n\n const processedPermissions = this.#processSnapPermissions(\n newSnap.manifest.initialPermissions,\n );\n\n const { newPermissions, unusedPermissions, approvedPermissions } =\n await this.#calculatePermissionsChange(snapId, processedPermissions);\n\n const id = nanoid();\n const { permissions: approvedNewPermissions, ...requestData } =\n (await this.messagingSystem.call(\n 'ApprovalController:addRequest',\n {\n origin,\n id,\n type: SNAP_APPROVAL_UPDATE,\n requestData: {\n // First two keys mirror installation params\n metadata: { id, origin: snapId, dappOrigin: origin },\n permissions: newPermissions,\n snapId,\n newVersion: newSnap.manifest.version,\n newPermissions,\n approvedPermissions,\n unusedPermissions,\n },\n },\n true,\n )) as PermissionsRequest;\n\n if (this.isRunning(snapId)) {\n await this.stopSnap(snapId, SnapStatusEvents.Stop);\n }\n\n this.#transition(snapId, SnapStatusEvents.Update);\n\n this.#set({\n origin,\n id: snapId,\n manifest: newSnap.manifest,\n sourceCode: newSnap.sourceCode,\n versionRange: newVersionRange,\n });\n\n const unusedPermissionsKeys = Object.keys(unusedPermissions);\n if (isNonEmptyArray(unusedPermissionsKeys)) {\n await this.messagingSystem.call(\n 'PermissionController:revokePermissions',\n {\n [snapId]: unusedPermissionsKeys,\n },\n );\n }\n\n if (isNonEmptyArray(Object.keys(approvedNewPermissions))) {\n await this.messagingSystem.call('PermissionController:grantPermissions', {\n approvedPermissions: approvedNewPermissions,\n subject: { origin: snapId },\n requestData,\n });\n }\n\n await this.#startSnap({ snapId, sourceCode: newSnap.sourceCode });\n\n const truncatedSnap = this.getTruncatedExpect(snapId);\n\n this.messagingSystem.publish(\n 'SnapController:snapUpdated',\n truncatedSnap,\n snap.version,\n );\n return truncatedSnap;\n }\n\n /**\n * Returns a promise representing the complete installation of the requested snap.\n * If the snap is already being installed, the previously pending promise will be returned.\n *\n * @param args - Object containing the snap id and either the URL of the snap's manifest,\n * or the snap's manifest and source code. The object may also optionally contain a target\n * version.\n * @returns The resulting snap object.\n */\n async #add(args: AddSnapArgs): Promise<PersistedSnap> {\n const { id: snapId } = args;\n validateSnapId(snapId);\n\n if (\n !args ||\n !('origin' in args) ||\n !('id' in args) ||\n (!('manifest' in args) && 'sourceCode' in args) ||\n ('manifest' in args && !('sourceCode' in args))\n ) {\n throw new Error(`Invalid add snap args for snap \"${snapId}\".`);\n }\n this.#setupRuntime(snapId, { sourceCode: null, state: null });\n const runtime = this.#getRuntimeExpect(snapId);\n if (!runtime.installPromise) {\n console.info(`Adding snap: ${snapId}`);\n\n // If fetching and setting the snap succeeds, this property will be set\n // to null in the authorize() method.\n runtime.installPromise = (async () => {\n if ('manifest' in args && 'sourceCode' in args) {\n return this.#set({ ...args, id: snapId });\n }\n\n const fetchedSnap = await this.fetchSnap(snapId, args.versionRange);\n await this.#assertIsUnblocked(snapId, {\n version: fetchedSnap.manifest.version,\n shasum: fetchedSnap.manifest.source.shasum,\n });\n\n return this.#set({\n ...args,\n ...fetchedSnap,\n id: snapId,\n });\n })();\n }\n\n try {\n return await runtime.installPromise;\n } catch (error) {\n // Reset promise so users can retry installation in case the problem is\n // temporary.\n runtime.installPromise = null;\n throw error;\n }\n }\n\n async #startSnap(snapData: { snapId: string; sourceCode: string }) {\n const { snapId } = snapData;\n if (this.isRunning(snapId)) {\n throw new Error(`Snap \"${snapId}\" is already started.`);\n }\n\n try {\n const result = await this.#executeWithTimeout(\n snapId,\n this.messagingSystem.call('ExecutionService:executeSnap', {\n ...snapData,\n endowments: await this.#getEndowments(snapId),\n }),\n );\n this.#transition(snapId, SnapStatusEvents.Start);\n return result;\n } catch (err) {\n await this.#terminateSnap(snapId);\n throw err;\n }\n }\n\n /**\n * Gets the names of all endowments that will be added to the Snap's\n * Compartment when it executes. These should be the names of global\n * JavaScript APIs accessible in the root realm of the execution environment.\n *\n * Throws an error if the endowment getter for a permission returns a truthy\n * value that is not an array of strings.\n *\n * @param snapId - The id of the snap whose SES endowments to get.\n * @returns An array of the names of the endowments.\n */\n async #getEndowments(snapId: string): Promise<string[]> {\n let allEndowments: string[] = [];\n\n for (const permissionName of this.#environmentEndowmentPermissions) {\n if (\n await this.messagingSystem.call(\n 'PermissionController:hasPermission',\n snapId,\n permissionName,\n )\n ) {\n const endowments = await this.messagingSystem.call(\n 'PermissionController:getEndowments',\n snapId,\n permissionName,\n );\n\n if (endowments) {\n // We don't have any guarantees about the type of the endowments\n // value, so we have to guard at runtime.\n if (\n !Array.isArray(endowments) ||\n endowments.some((value) => typeof value !== 'string')\n ) {\n throw new Error('Expected an array of string endowment names.');\n }\n\n allEndowments = allEndowments.concat(endowments as string[]);\n }\n }\n }\n\n const dedupedEndowments = [\n ...new Set([...DEFAULT_ENDOWMENTS, ...allEndowments]),\n ];\n\n if (\n dedupedEndowments.length <\n DEFAULT_ENDOWMENTS.length + allEndowments.length\n ) {\n console.error(\n 'Duplicate endowments found. Default endowments should not be requested.',\n allEndowments,\n );\n }\n return dedupedEndowments;\n }\n\n /**\n * Sets a snap in state. Called when a snap is installed or updated. Performs\n * various validation checks on the received arguments, and will throw if\n * validation fails.\n *\n * The snap will be enabled and unblocked by the time this method returns,\n * regardless of its previous state.\n *\n * See {@link SnapController.add} and {@link SnapController.updateSnap} for\n * usage.\n *\n * @param args - The add snap args.\n * @returns The resulting snap object.\n */\n #set(args: SetSnapArgs): PersistedSnap {\n const {\n id: snapId,\n origin,\n manifest,\n sourceCode,\n svgIcon,\n versionRange = DEFAULT_REQUESTED_SNAP_VERSION,\n } = args;\n\n assertIsSnapManifest(manifest);\n const { version } = manifest;\n\n if (!satisfiesVersionRange(version, versionRange)) {\n throw new Error(\n `Version mismatch. Manifest for \"${snapId}\" specifies version \"${version}\" which doesn't satisfy requested version range \"${versionRange}\"`,\n );\n }\n\n if (typeof sourceCode !== 'string' || sourceCode.length === 0) {\n throw new Error(`Invalid source code for snap \"${snapId}\".`);\n }\n\n const initialPermissions = manifest?.initialPermissions;\n if (\n !initialPermissions ||\n typeof initialPermissions !== 'object' ||\n Array.isArray(initialPermissions)\n ) {\n throw new Error(`Invalid initial permissions for snap \"${snapId}\".`);\n }\n\n const snapsState = this.state.snaps;\n\n const existingSnap = snapsState[snapId];\n\n const previousVersionHistory = existingSnap?.versionHistory ?? [];\n const versionHistory = [\n ...previousVersionHistory,\n {\n version,\n date: Date.now(),\n origin,\n },\n ];\n\n const snap: Snap = {\n // Restore relevant snap state if it exists\n ...existingSnap,\n\n // Note that the snap will be unblocked and enabled, regardless of its\n // previous state.\n blocked: false,\n enabled: true,\n\n // So we can easily correlate the snap with its permission\n permissionName: getSnapPermissionName(snapId),\n\n id: snapId,\n initialPermissions,\n manifest,\n status: this.#statusMachine.config.initial as StatusStates['value'],\n version,\n versionHistory,\n };\n // If the snap was blocked, it isn't any longer\n delete snap.blockInformation;\n\n // store the snap back in state\n this.update((state: any) => {\n state.snaps[snapId] = snap;\n });\n\n const runtime = this.#getRuntimeExpect(snapId);\n runtime.sourceCode = sourceCode;\n\n this.messagingSystem.publish(`SnapController:snapAdded`, snap, svgIcon);\n return { ...snap, sourceCode };\n }\n\n /**\n * Fetches the manifest and source code of a snap.\n *\n * This function is not hash private yet because of tests.\n *\n * @param snapId - The id of the Snap.\n * @param versionRange - The SemVer version of the Snap to fetch.\n * @returns A tuple of the Snap manifest object and the Snap source code.\n */\n async fetchSnap(\n snapId: ValidatedSnapId,\n versionRange: string = DEFAULT_REQUESTED_SNAP_VERSION,\n ): Promise<FetchSnapResult> {\n try {\n const snapPrefix = getSnapPrefix(snapId);\n switch (snapPrefix) {\n case SnapIdPrefixes.local:\n return this.#fetchLocalSnap(snapId.replace(SnapIdPrefixes.local, ''));\n case SnapIdPrefixes.npm:\n return this.#fetchNpmSnap(\n snapId.replace(SnapIdPrefixes.npm, ''),\n versionRange,\n );\n /* istanbul ignore next */\n default:\n // This whill fail to compile if the above switch is not fully exhaustive\n return assertExhaustive(snapPrefix);\n }\n } catch (error) {\n throw new Error(\n `Failed to fetch Snap \"${snapId}\": ${(error as Error).message}`,\n );\n }\n }\n\n async #fetchNpmSnap(\n packageName: string,\n versionRange: string,\n ): Promise<FetchSnapResult> {\n if (!isValidSnapVersionRange(versionRange)) {\n throw new Error(\n `Received invalid Snap version range: \"${versionRange}\".`,\n );\n }\n\n const { manifest, sourceCode, svgIcon } = await fetchNpmSnap(\n packageName,\n versionRange,\n this.#npmRegistryUrl,\n this.#fetchFunction,\n );\n return { manifest, sourceCode, svgIcon };\n }\n\n /**\n * Fetches the manifest and source code of a local snap.\n *\n * @param localhostUrl - The localhost URL to download from.\n * @returns The validated manifest and the source code.\n */\n async #fetchLocalSnap(localhostUrl: string): Promise<FetchSnapResult> {\n // Local snaps are mostly used for development purposes. Fetches were cached in the browser and were not requested\n // afterwards which lead to confusing development where old versions of snaps were installed.\n // Thus we disable caching\n const fetchOptions: RequestInit = { cache: 'no-cache' };\n const manifestUrl = new URL(NpmSnapFileNames.Manifest, localhostUrl);\n if (!LOCALHOST_HOSTNAMES.has(manifestUrl.hostname)) {\n throw new Error(\n `Invalid URL: Locally hosted Snaps must be hosted on localhost. Received URL: \"${manifestUrl.toString()}\"`,\n );\n }\n\n const manifest = await (\n await this.#fetchFunction(manifestUrl.toString(), fetchOptions)\n ).json();\n assertIsSnapManifest(manifest);\n\n const {\n source: {\n location: {\n npm: { filePath, iconPath },\n },\n },\n } = manifest;\n\n const [sourceCode, svgIcon] = await Promise.all([\n (\n await this.#fetchFunction(\n new URL(filePath, localhostUrl).toString(),\n fetchOptions,\n )\n ).text(),\n iconPath\n ? (\n await this.#fetchFunction(\n new URL(iconPath, localhostUrl).toString(),\n fetchOptions,\n )\n ).text()\n : undefined,\n ]);\n\n validateSnapShasum(manifest, sourceCode);\n return { manifest, sourceCode, svgIcon };\n }\n\n /**\n * Map initial permissions as defined in a Snap manifest to something that can\n * be processed by the PermissionsController. Each caveat mapping function\n * should return a valid permission caveat value.\n *\n * This function does not validate the caveat values, since that is done by\n * the PermissionsController itself, upon requesting the permissions.\n *\n * @param initialPermissions - The initial permissions to process.\n * @returns The processed permissions.\n * @private\n */\n #processSnapPermissions(\n initialPermissions: SnapPermissions,\n ): Record<\n string,\n Pick<PermissionConstraint, 'caveats'> | Record<string, never>\n > {\n return fromEntries(\n Object.entries(initialPermissions).map(([initialPermission, value]) => {\n if (hasProperty(caveatMappers, initialPermission)) {\n return [initialPermission, caveatMappers[initialPermission](value)];\n } else if (hasProperty(endowmentCaveatMappers, initialPermission)) {\n return [\n initialPermission,\n endowmentCaveatMappers[initialPermission](value),\n ];\n }\n\n assert(Object.keys(value).length === 0);\n return [initialPermission, {}];\n }),\n );\n }\n\n /**\n * Initiates a request for the given snap's initial permissions.\n * Must be called in order. See processRequestedSnap.\n *\n * This function is not hash private yet because of tests.\n *\n * @param origin - The origin of the install request.\n * @param snapId - The id of the Snap.\n * @returns The snap's approvedPermissions.\n */\n private async authorize(origin: string, snapId: SnapId): Promise<void> {\n console.info(`Authorizing snap: ${snapId}`);\n const snapsState = this.state.snaps;\n const snap = snapsState[snapId];\n const { initialPermissions } = snap;\n\n try {\n const processedPermissions =\n this.#processSnapPermissions(initialPermissions);\n const id = nanoid();\n const { permissions: approvedPermissions, ...requestData } =\n (await this.messagingSystem.call(\n 'ApprovalController:addRequest',\n {\n origin,\n id,\n type: SNAP_APPROVAL_INSTALL,\n requestData: {\n // Mirror previous installation metadata\n metadata: { id, origin: snapId, dappOrigin: origin },\n permissions: processedPermissions,\n snapId,\n },\n },\n true,\n )) as PermissionsRequest;\n\n if (isNonEmptyArray(Object.keys(approvedPermissions))) {\n await this.messagingSystem.call(\n 'PermissionController:grantPermissions',\n {\n approvedPermissions,\n subject: { origin: snapId },\n requestData,\n },\n );\n }\n } finally {\n const runtime = this.#getRuntimeExpect(snapId);\n runtime.installPromise = null;\n }\n }\n\n destroy() {\n super.destroy();\n\n if (this.#timeoutForLastRequestStatus) {\n clearTimeout(this.#timeoutForLastRequestStatus);\n }\n\n this.messagingSystem.unsubscribe(\n 'ExecutionService:unhandledError',\n this._onUnhandledSnapError,\n );\n\n this.messagingSystem.unsubscribe(\n 'ExecutionService:outboundRequest',\n this._onOutboundRequest,\n );\n\n this.messagingSystem.unsubscribe(\n 'ExecutionService:outboundResponse',\n this._onOutboundResponse,\n );\n }\n\n /**\n * Passes a JSON-RPC request object to the RPC handler function of a snap.\n *\n * @param options - A bag of options.\n * @param options.snapId - The ID of the recipient snap.\n * @param options.origin - The origin of the RPC request.\n * @param options.handler - The handler to trigger on the snap for the request.\n * @param options.request - The JSON-RPC request object.\n * @returns The result of the JSON-RPC request.\n */\n async handleRequest({\n snapId,\n origin,\n handler: handlerType,\n request,\n }: SnapRpcHookArgs & { snapId: SnapId }): Promise<unknown> {\n const handler = await this.#getRpcRequestHandler(snapId);\n if (!handler) {\n throw new Error(\n `Snap RPC message handler not found for snap \"${snapId}\".`,\n );\n }\n return handler({ origin, handler: handlerType, request });\n }\n\n /**\n * Gets the RPC message handler for the given snap.\n *\n * @param snapId - The id of the Snap whose message handler to get.\n * @returns The RPC handler for the given snap.\n */\n async #getRpcRequestHandler(snapId: SnapId): Promise<SnapRpcHook> {\n const runtime = this.#getRuntimeExpect(snapId);\n const existingHandler = runtime.rpcHandler;\n if (existingHandler) {\n return existingHandler;\n }\n\n const requestQueue = new RequestQueue(5);\n // We need to set up this promise map to map snapIds to their respective startPromises,\n // because otherwise we would lose context on the correct startPromise.\n const startPromises = new Map<string, Promise<void>>();\n\n const rpcHandler = async ({\n origin,\n handler: handlerType,\n request,\n }: SnapRpcHookArgs) => {\n if (this.state.snaps[snapId].enabled === false) {\n throw new Error(`Snap \"${snapId}\" is disabled.`);\n }\n\n if (this.state.snaps[snapId].status === SnapStatus.Installing) {\n throw new Error(\n `Snap \"${snapId}\" is currently being installed. Please try again later.`,\n );\n }\n\n if (this.isRunning(snapId) === false) {\n let localStartPromise = startPromises.get(snapId);\n if (!localStartPromise) {\n localStartPromise = this.startSnap(snapId);\n startPromises.set(snapId, localStartPromise);\n } else if (requestQueue.get(origin) >= requestQueue.maxQueueSize) {\n throw new Error(\n 'Exceeds maximum number of requests waiting to be resolved, please try again.',\n );\n }\n\n requestQueue.increment(origin);\n try {\n await localStartPromise;\n } finally {\n requestQueue.decrement(origin);\n // Only delete startPromise for a snap if its value hasn't changed\n if (startPromises.get(snapId) === localStartPromise) {\n startPromises.delete(snapId);\n }\n }\n }\n\n let _request = request;\n if (!hasProperty(request, 'jsonrpc')) {\n _request = { ...request, jsonrpc: '2.0' };\n } else if (request.jsonrpc !== '2.0') {\n throw ethErrors.rpc.invalidRequest({\n message: 'Invalid \"jsonrpc\" property. Must be \"2.0\" if provided.',\n data: request.jsonrpc,\n });\n }\n\n const timer = new Timer(this.maxRequestTime);\n this.#recordSnapRpcRequestStart(snapId, request.id, timer);\n\n const handleRpcRequestPromise = this.messagingSystem.call(\n 'ExecutionService:handleRpcRequest',\n snapId,\n { origin, handler: handlerType, request: _request },\n );\n\n // This will either get the result or reject due to the timeout.\n try {\n const result = await this.#executeWithTimeout(\n snapId,\n handleRpcRequestPromise,\n timer,\n );\n this.#recordSnapRpcRequestFinish(snapId, request.id);\n return result;\n } catch (err) {\n await this.stopSnap(snapId, SnapStatusEvents.Crash);\n throw err;\n }\n };\n\n runtime.rpcHandler = rpcHandler;\n return rpcHandler;\n }\n\n /**\n * Awaits the specified promise and rejects if the promise doesn't resolve\n * before the timeout.\n *\n * @param snapId - The snap id.\n * @param promise - The promise to await.\n * @param timer - An optional timer object to control the timeout.\n * @returns The result of the promise or rejects if the promise times out.\n * @template PromiseValue - The value of the Promise.\n */\n async #executeWithTimeout<PromiseValue>(\n snapId: SnapId,\n promise: Promise<PromiseValue>,\n timer?: Timer,\n ): Promise<PromiseValue> {\n const isLongRunning = await this.messagingSystem.call(\n 'PermissionController:hasPermission',\n snapId,\n SnapEndowments.LongRunning,\n );\n\n // Long running snaps have timeouts disabled\n if (isLongRunning) {\n return promise;\n }\n\n const result = await withTimeout(promise, timer ?? this.maxRequestTime);\n if (result === hasTimedOut) {\n throw new Error('The request timed out.');\n }\n return result;\n }\n\n #recordSnapRpcRequestStart(snapId: SnapId, requestId: unknown, timer: Timer) {\n const runtime = this.#getRuntimeExpect(snapId);\n runtime.pendingInboundRequests.push({ requestId, timer });\n runtime.lastRequest = null;\n }\n\n #recordSnapRpcRequestFinish(snapId: SnapId, requestId: unknown) {\n const runtime = this.#getRuntimeExpect(snapId);\n runtime.pendingInboundRequests = runtime.pendingInboundRequests.filter(\n (r) => r.requestId !== requestId,\n );\n\n if (runtime.pendingInboundRequests.length === 0) {\n runtime.lastRequest = Date.now();\n }\n }\n\n #getRuntime(snapId: SnapId): SnapRuntimeData | undefined {\n return this.snapsRuntimeData.get(snapId);\n }\n\n #getRuntimeExpect(snapId: SnapId): SnapRuntimeData {\n const runtime = this.#getRuntime(snapId);\n assert(\n runtime !== undefined,\n new Error(`Snap \"${snapId}\" runtime data not found`),\n );\n return runtime;\n }\n\n #setupRuntime(\n snapId: SnapId,\n data: { sourceCode: string | null; state: string | null },\n ) {\n if (this.snapsRuntimeData.has(snapId)) {\n return;\n }\n\n const snap = this.get(snapId);\n const interpreter = interpret(this.#statusMachine);\n interpreter.start({\n context: { snapId },\n value:\n snap?.status ??\n (this.#statusMachine.config.initial as StatusStates['value']),\n });\n\n forceStrict(interpreter);\n\n this.snapsRuntimeData.set(snapId, {\n lastRequest: null,\n rpcHandler: null,\n installPromise: null,\n activeReferences: 0,\n pendingInboundRequests: [],\n pendingOutboundRequests: 0,\n interpreter,\n ...data,\n });\n }\n\n async #calculatePermissionsChange(\n snapId: SnapId,\n desiredPermissionsSet: RequestedSnapPermissions,\n ): Promise<{\n newPermissions: RequestedSnapPermissions;\n unusedPermissions: SubjectPermissions<\n ValidPermission<string, Caveat<string, any>>\n >;\n approvedPermissions: SubjectPermissions<\n ValidPermission<string, Caveat<string, any>>\n >;\n }> {\n const oldPermissions =\n (await this.messagingSystem.call(\n 'PermissionController:getPermissions',\n snapId,\n )) ?? {};\n\n const newPermissions = setDiff(desiredPermissionsSet, oldPermissions);\n // TODO(ritave): The assumption that these are unused only holds so long as we do not\n // permit dynamic permission requests.\n const unusedPermissions = setDiff(oldPermissions, desiredPermissionsSet);\n\n // It's a Set Intersection of oldPermissions and desiredPermissionsSet\n // oldPermissions ∖ (oldPermissions ∖ desiredPermissionsSet) ⟺ oldPermissions ∩ desiredPermissionsSet\n const approvedPermissions = setDiff(oldPermissions, unusedPermissions);\n\n return { newPermissions, unusedPermissions, approvedPermissions };\n }\n}\n"]}
@@ -0,0 +1,39 @@
1
+ export declare type TimerStatus = 'stopped' | 'paused' | 'running' | 'finished';
2
+ export declare class Timer {
3
+ private state;
4
+ /**
5
+ * If `ms` is smaller or equal to zero (including -Infinity), the callback is added to the event loop and executed async immediately
6
+ * If `ms` is +Infinity the timer never finishes.
7
+ *
8
+ * @throws {@link TypeError}. If `ms` is NaN or negative.
9
+ * @param ms - The number of milliseconds before the callback is called after started.
10
+ */
11
+ constructor(ms: number);
12
+ get status(): TimerStatus;
13
+ /**
14
+ * Cancels the currently running timer and marks it finished.
15
+ *
16
+ * @throws {@link Error}. If it wasn't running or paused.
17
+ */
18
+ cancel(): void;
19
+ /**
20
+ * Pauses a currently running timer, allowing it to resume later.
21
+ *
22
+ * @throws {@link Error}. If it wasn't running.
23
+ */
24
+ pause(): void;
25
+ /**
26
+ * Starts the timer.
27
+ *
28
+ * @param callback - The function that will be called after the timer finishes.
29
+ * @throws {@link Error}. If it was already started.
30
+ */
31
+ start(callback: () => void): void;
32
+ /**
33
+ * Resumes a currently paused timer.
34
+ *
35
+ * @throws {@link Error}. If it wasn't paused.
36
+ */
37
+ resume(): void;
38
+ private onFinish;
39
+ }
@@ -0,0 +1,86 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Timer = void 0;
4
+ const utils_1 = require("@metamask/utils");
5
+ class Timer {
6
+ /**
7
+ * If `ms` is smaller or equal to zero (including -Infinity), the callback is added to the event loop and executed async immediately
8
+ * If `ms` is +Infinity the timer never finishes.
9
+ *
10
+ * @throws {@link TypeError}. If `ms` is NaN or negative.
11
+ * @param ms - The number of milliseconds before the callback is called after started.
12
+ */
13
+ constructor(ms) {
14
+ (0, utils_1.assert)(!Number.isNaN(ms), new TypeError("Can't start a timer with NaN time"));
15
+ (0, utils_1.assert)(ms >= 0, new TypeError("Can't start a timer with negative time"));
16
+ this.state = { value: 'stopped', remaining: ms };
17
+ }
18
+ get status() {
19
+ return this.state.value;
20
+ }
21
+ /**
22
+ * Cancels the currently running timer and marks it finished.
23
+ *
24
+ * @throws {@link Error}. If it wasn't running or paused.
25
+ */
26
+ cancel() {
27
+ (0, utils_1.assert)(this.status === 'paused' || this.status === 'running', new Error('Tried to cancel a not running Timer'));
28
+ this.onFinish(false);
29
+ }
30
+ /**
31
+ * Pauses a currently running timer, allowing it to resume later.
32
+ *
33
+ * @throws {@link Error}. If it wasn't running.
34
+ */
35
+ pause() {
36
+ (0, utils_1.assert)(this.state.value === 'running', new Error('Tried to pause a not running Timer'));
37
+ const { callback, start, timeout, remaining } = this.state;
38
+ timeout !== undefined && clearTimeout(timeout);
39
+ this.state = {
40
+ value: 'paused',
41
+ callback,
42
+ remaining: remaining - (Date.now() - start),
43
+ };
44
+ }
45
+ /**
46
+ * Starts the timer.
47
+ *
48
+ * @param callback - The function that will be called after the timer finishes.
49
+ * @throws {@link Error}. If it was already started.
50
+ */
51
+ start(callback) {
52
+ (0, utils_1.assert)(this.state.value === 'stopped', new Error('Tried to start an already running Timer'));
53
+ const { remaining } = this.state;
54
+ this.state = { value: 'paused', remaining, callback };
55
+ this.resume();
56
+ }
57
+ /**
58
+ * Resumes a currently paused timer.
59
+ *
60
+ * @throws {@link Error}. If it wasn't paused.
61
+ */
62
+ resume() {
63
+ (0, utils_1.assert)(this.state.value === 'paused', new Error('Tried to resume not paused Timer'));
64
+ const { remaining, callback } = this.state;
65
+ const start = Date.now();
66
+ let timeout;
67
+ // setTimeout returns immediately on +Infinity which we use
68
+ if (remaining !== Number.POSITIVE_INFINITY) {
69
+ timeout = setTimeout(() => this.onFinish(true), remaining);
70
+ }
71
+ this.state = { value: 'running', callback, remaining, start, timeout };
72
+ }
73
+ onFinish(shouldCall) {
74
+ (0, utils_1.assert)(this.state.value === 'running' || this.state.value === 'paused');
75
+ if (this.state.value === 'running' && this.state.timeout !== undefined) {
76
+ clearTimeout(this.state.timeout);
77
+ }
78
+ const { callback } = this.state;
79
+ this.state = { value: 'finished' };
80
+ if (shouldCall) {
81
+ callback();
82
+ }
83
+ }
84
+ }
85
+ exports.Timer = Timer;
86
+ //# sourceMappingURL=Timer.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Timer.js","sourceRoot":"","sources":["../../src/snaps/Timer.ts"],"names":[],"mappings":";;;AAAA,2CAAyC;AAIzC,MAAa,KAAK;IAiBhB;;;;;;OAMG;IACH,YAAY,EAAU;QACpB,IAAA,cAAM,EACJ,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC,EACjB,IAAI,SAAS,CAAC,mCAAmC,CAAC,CACnD,CAAC;QACF,IAAA,cAAM,EAAC,EAAE,IAAI,CAAC,EAAE,IAAI,SAAS,CAAC,wCAAwC,CAAC,CAAC,CAAC;QACzE,IAAI,CAAC,KAAK,GAAG,EAAE,KAAK,EAAE,SAAS,EAAE,SAAS,EAAE,EAAE,EAAE,CAAC;IACnD,CAAC;IAED,IAAI,MAAM;QACR,OAAO,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC;IAC1B,CAAC;IAED;;;;OAIG;IACH,MAAM;QACJ,IAAA,cAAM,EACJ,IAAI,CAAC,MAAM,KAAK,QAAQ,IAAI,IAAI,CAAC,MAAM,KAAK,SAAS,EACrD,IAAI,KAAK,CAAC,qCAAqC,CAAC,CACjD,CAAC;QACF,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;IACvB,CAAC;IAED;;;;OAIG;IACH,KAAK;QACH,IAAA,cAAM,EACJ,IAAI,CAAC,KAAK,CAAC,KAAK,KAAK,SAAS,EAC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C,KAAK,GAAG,EAAE,KAAK,EAAE,SAAS,EAAE,QAAQ,EAAE,SAAS,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC;IACzE,CAAC;IAEO,QAAQ,CAAC,UAAmB;QAClC,IAAA,cAAM,EAAC,IAAI,CAAC,KAAK,CAAC,KAAK,KAAK,SAAS,IAAI,IAAI,CAAC,KAAK,CAAC,KAAK,KAAK,QAAQ,CAAC,CAAC;QAExE,IAAI,IAAI,CAAC,KAAK,CAAC,KAAK,KAAK,SAAS,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,KAAK,SAAS,EAAE;YACtE,YAAY,CAAC,IAAI,CAAC,KAAK,CAAC,OAAc,CAAC,CAAC;SACzC;QAED,MAAM,EAAE,QAAQ,EAAE,GAAG,IAAI,CAAC,KAAK,CAAC;QAChC,IAAI,CAAC,KAAK,GAAG,EAAE,KAAK,EAAE,UAAU,EAAE,CAAC;QAEnC,IAAI,UAAU,EAAE;YACd,QAAQ,EAAE,CAAC;SACZ;IACH,CAAC;CACF;AA5HD,sBA4HC","sourcesContent":["import { assert } from '@metamask/utils';\n\nexport type TimerStatus = 'stopped' | 'paused' | 'running' | 'finished';\n\nexport class Timer {\n private state:\n | { value: 'stopped'; remaining: number }\n | {\n value: 'paused';\n remaining: number;\n callback: () => void;\n }\n | {\n value: 'running';\n remaining: number;\n callback: () => void;\n start: number;\n timeout?: unknown;\n }\n | { value: 'finished' };\n\n /**\n * If `ms` is smaller or equal to zero (including -Infinity), the callback is added to the event loop and executed async immediately\n * If `ms` is +Infinity the timer never finishes.\n *\n * @throws {@link TypeError}. If `ms` is NaN or negative.\n * @param ms - The number of milliseconds before the callback is called after started.\n */\n constructor(ms: number) {\n assert(\n !Number.isNaN(ms),\n new TypeError(\"Can't start a timer with NaN time\"),\n );\n assert(ms >= 0, new TypeError(\"Can't start a timer with negative time\"));\n this.state = { value: 'stopped', remaining: ms };\n }\n\n get status(): TimerStatus {\n return this.state.value;\n }\n\n /**\n * Cancels the currently running timer and marks it finished.\n *\n * @throws {@link Error}. If it wasn't running or paused.\n */\n cancel() {\n assert(\n this.status === 'paused' || this.status === 'running',\n new Error('Tried to cancel a not running Timer'),\n );\n this.onFinish(false);\n }\n\n /**\n * Pauses a currently running timer, allowing it to resume later.\n *\n * @throws {@link Error}. If it wasn't running.\n */\n pause() {\n assert(\n this.state.value === 'running',\n new Error('Tried to pause a not running Timer'),\n );\n\n const { callback, start, timeout, remaining } = this.state;\n\n timeout !== undefined && clearTimeout(timeout as any);\n this.state = {\n value: 'paused',\n callback,\n remaining: remaining - (Date.now() - start),\n };\n }\n\n /**\n * Starts the timer.\n *\n * @param callback - The function that will be called after the timer finishes.\n * @throws {@link Error}. If it was already started.\n */\n start(callback: () => void) {\n assert(\n this.state.value === 'stopped',\n new Error('Tried to start an already running Timer'),\n );\n\n const { remaining } = this.state;\n this.state = { value: 'paused', remaining, callback };\n this.resume();\n }\n\n /**\n * Resumes a currently paused timer.\n *\n * @throws {@link Error}. If it wasn't paused.\n */\n resume() {\n assert(\n this.state.value === 'paused',\n new Error('Tried to resume not paused Timer'),\n );\n const { remaining, callback } = this.state;\n const start = Date.now();\n\n let timeout: unknown;\n // setTimeout returns immediately on +Infinity which we use\n if (remaining !== Number.POSITIVE_INFINITY) {\n timeout = setTimeout(() => this.onFinish(true), remaining);\n }\n\n this.state = { value: 'running', callback, remaining, start, timeout };\n }\n\n private onFinish(shouldCall: boolean) {\n assert(this.state.value === 'running' || this.state.value === 'paused');\n\n if (this.state.value === 'running' && this.state.timeout !== undefined) {\n clearTimeout(this.state.timeout as any);\n }\n\n const { callback } = this.state;\n this.state = { value: 'finished' };\n\n if (shouldCall) {\n callback();\n }\n }\n}\n"]}
@@ -0,0 +1,49 @@
1
+ import { PermissionSpecificationBuilder, PermissionType, PermissionConstraint, Caveat, CaveatSpecificationConstraint } from '@metamask/controllers';
2
+ import { Json, NonEmptyArray } from '@metamask/utils';
3
+ import { SnapCaveatType, CronjobSpecification } from '@metamask/snaps-utils';
4
+ import { SnapEndowments } from './enum';
5
+ declare const permissionName = SnapEndowments.Cronjob;
6
+ export declare const cronjobEndowmentBuilder: Readonly<{
7
+ readonly targetKey: SnapEndowments.Cronjob;
8
+ readonly specificationBuilder: PermissionSpecificationBuilder<PermissionType.Endowment, any, {
9
+ permissionType: PermissionType.Endowment;
10
+ targetKey: typeof permissionName;
11
+ endowmentGetter: (_options?: any) => undefined;
12
+ allowedCaveats: Readonly<NonEmptyArray<string>> | null;
13
+ }>;
14
+ }>;
15
+ /**
16
+ * Map a raw value from the `initialPermissions` to a caveat specification.
17
+ * Note that this function does not do any validation, that's handled by the
18
+ * PermissionsController when the permission is requested.
19
+ *
20
+ * @param value - The raw value from the `initialPermissions`.
21
+ * @returns The caveat specification.
22
+ */
23
+ export declare function getCronjobCaveatMapper(value: Json): Pick<PermissionConstraint, 'caveats'>;
24
+ /**
25
+ * Getter function to get the cronjobs from a permission.
26
+ *
27
+ * This does basic validation of the caveat, but does not validate the type or
28
+ * value of the namespaces object itself, as this is handled by the
29
+ * `PermissionsController` when the permission is requested.
30
+ *
31
+ * @param permission - The permission to get the keyring namespaces from.
32
+ * @returns The cronjobs, or `null` if the permission does not have a
33
+ * cronjob caveat.
34
+ */
35
+ export declare function getCronjobCaveatJobs(permission?: PermissionConstraint): CronjobSpecification[] | null;
36
+ /**
37
+ * Validate the cronjob specification values associated with a caveat.
38
+ * This validates that the value is a non-empty array with valid
39
+ * cronjob expression and request object.
40
+ *
41
+ * @param caveat - The caveat to validate.
42
+ * @throws If the value is invalid.
43
+ */
44
+ export declare function validateCronjobCaveat(caveat: Caveat<string, any>): void;
45
+ /**
46
+ * Caveat specification for the Cronjob.
47
+ */
48
+ export declare const cronjobCaveatSpecifications: Record<SnapCaveatType.SnapCronjob, CaveatSpecificationConstraint>;
49
+ export {};
@@ -0,0 +1,105 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.cronjobCaveatSpecifications = exports.validateCronjobCaveat = exports.getCronjobCaveatJobs = exports.getCronjobCaveatMapper = exports.cronjobEndowmentBuilder = void 0;
4
+ const controllers_1 = require("@metamask/controllers");
5
+ const utils_1 = require("@metamask/utils");
6
+ const snaps_utils_1 = require("@metamask/snaps-utils");
7
+ const eth_rpc_errors_1 = require("eth-rpc-errors");
8
+ const enum_1 = require("./enum");
9
+ const permissionName = enum_1.SnapEndowments.Cronjob;
10
+ /**
11
+ * `endowment:cronjob` returns nothing; it is intended to be used as a flag to determine whether the snap wants to run cronjobs.
12
+ *
13
+ * @param _builderOptions - Optional specification builder options.
14
+ * @returns The specification for the cronjob endowment.
15
+ */
16
+ const specificationBuilder = (_builderOptions) => {
17
+ return {
18
+ permissionType: controllers_1.PermissionType.Endowment,
19
+ targetKey: permissionName,
20
+ allowedCaveats: [snaps_utils_1.SnapCaveatType.SnapCronjob],
21
+ endowmentGetter: (_getterOptions) => undefined,
22
+ };
23
+ };
24
+ exports.cronjobEndowmentBuilder = Object.freeze({
25
+ targetKey: permissionName,
26
+ specificationBuilder,
27
+ });
28
+ /**
29
+ * Map a raw value from the `initialPermissions` to a caveat specification.
30
+ * Note that this function does not do any validation, that's handled by the
31
+ * PermissionsController when the permission is requested.
32
+ *
33
+ * @param value - The raw value from the `initialPermissions`.
34
+ * @returns The caveat specification.
35
+ */
36
+ function getCronjobCaveatMapper(value) {
37
+ return {
38
+ caveats: [
39
+ {
40
+ type: snaps_utils_1.SnapCaveatType.SnapCronjob,
41
+ value,
42
+ },
43
+ ],
44
+ };
45
+ }
46
+ exports.getCronjobCaveatMapper = getCronjobCaveatMapper;
47
+ /**
48
+ * Getter function to get the cronjobs from a permission.
49
+ *
50
+ * This does basic validation of the caveat, but does not validate the type or
51
+ * value of the namespaces object itself, as this is handled by the
52
+ * `PermissionsController` when the permission is requested.
53
+ *
54
+ * @param permission - The permission to get the keyring namespaces from.
55
+ * @returns The cronjobs, or `null` if the permission does not have a
56
+ * cronjob caveat.
57
+ */
58
+ function getCronjobCaveatJobs(permission) {
59
+ var _a, _b;
60
+ if (!(permission === null || permission === void 0 ? void 0 : permission.caveats)) {
61
+ return null;
62
+ }
63
+ (0, utils_1.assert)(permission.caveats.length === 1);
64
+ (0, utils_1.assert)(permission.caveats[0].type === snaps_utils_1.SnapCaveatType.SnapCronjob);
65
+ const caveat = permission.caveats[0];
66
+ return (_b = (_a = caveat.value) === null || _a === void 0 ? void 0 : _a.jobs) !== null && _b !== void 0 ? _b : null;
67
+ }
68
+ exports.getCronjobCaveatJobs = getCronjobCaveatJobs;
69
+ /**
70
+ * Validate the cronjob specification values associated with a caveat.
71
+ * This validates that the value is a non-empty array with valid
72
+ * cronjob expression and request object.
73
+ *
74
+ * @param caveat - The caveat to validate.
75
+ * @throws If the value is invalid.
76
+ */
77
+ function validateCronjobCaveat(caveat) {
78
+ if (!(0, utils_1.hasProperty)(caveat, 'value') || !(0, utils_1.isPlainObject)(caveat.value)) {
79
+ throw eth_rpc_errors_1.ethErrors.rpc.invalidParams({
80
+ message: 'Expected a plain object.',
81
+ });
82
+ }
83
+ const { value } = caveat;
84
+ if (!(0, utils_1.hasProperty)(value, 'jobs') || !(0, utils_1.isPlainObject)(value)) {
85
+ throw eth_rpc_errors_1.ethErrors.rpc.invalidParams({
86
+ message: 'Expected a plain object.',
87
+ });
88
+ }
89
+ if (!(0, snaps_utils_1.isCronjobSpecificationArray)(value.jobs)) {
90
+ throw eth_rpc_errors_1.ethErrors.rpc.invalidParams({
91
+ message: 'Expected a valid cronjob specification array.',
92
+ });
93
+ }
94
+ }
95
+ exports.validateCronjobCaveat = validateCronjobCaveat;
96
+ /**
97
+ * Caveat specification for the Cronjob.
98
+ */
99
+ exports.cronjobCaveatSpecifications = {
100
+ [snaps_utils_1.SnapCaveatType.SnapCronjob]: Object.freeze({
101
+ type: snaps_utils_1.SnapCaveatType.SnapCronjob,
102
+ validator: (caveat) => validateCronjobCaveat(caveat),
103
+ }),
104
+ };
105
+ //# sourceMappingURL=cronjob.js.map
@@ -0,0 +1 @@
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C,KAAK,0CAAE,IAA+B,mCAAI,IAAI,CAAC;AAChE,CAAC;AAbD,oDAaC;AAED;;;;;;;GAOG;AACH,SAAgB,qBAAqB,CAAC,MAA2B;IAC/D,IAAI,CAAC,IAAA,mBAAW,EAAC,MAAM,EAAE,OAAO,CAAC,IAAI,CAAC,IAAA,qBAAa,EAAC,MAAM,CAAC,KAAK,CAAC,EAAE;QACjE,MAAM,0BAAS,CAAC,GAAG,CAAC,aAAa,CAAC;YAChC,OAAO,EAAE,0BAA0B;SACpC,CAAC,CAAC;KACJ;IAED,MAAM,EAAE,KAAK,EAAE,GAAG,MAAM,CAAC;IAEzB,IAAI,CAAC,IAAA,mBAAW,EAAC,KAAK,EAAE,MAAM,CAAC,IAAI,CAAC,IAAA,qBAAa,EAAC,KAAK,CAAC,EAAE;QACxD,MAAM,0BAAS,CAAC,GAAG,CAAC,aAAa,CAAC;YAChC,OAAO,EAAE,0BAA0B;SACpC,CAAC,CAAC;KACJ;IAED,IAAI,CAAC,IAAA,yCAA2B,EAAC,KAAK,CAAC,IAAI,CAAC,EAAE;QAC5C,MAAM,0BAAS,CAAC,GAAG,CAAC,aAAa,CAAC;YAChC,OAAO,EAAE,+CAA+C;SACzD,CAAC,CAAC;KACJ;AACH,CAAC;AApBD,sDAoBC;AAED;;GAEG;AACU,QAAA,2BAA2B,GAGpC;IACF,CAAC,4BAAc,CAAC,WAAW,CAAC,EAAE,MAAM,CAAC,MAAM,CAAC;QAC1C,IAAI,EAAE,4BAAc,CAAC,WAAW;QAChC,SAAS,EAAE,CAAC,MAAM,EAAE,EAAE,CAAC,qBAAqB,CAAC,MAAM,CAAC;KACrD,CAAC;CACH,CAAC","sourcesContent":["import {\n PermissionSpecificationBuilder,\n PermissionType,\n EndowmentGetterParams,\n ValidPermissionSpecification,\n PermissionConstraint,\n Caveat,\n CaveatSpecificationConstraint,\n} from '@metamask/controllers';\nimport {\n assert,\n hasProperty,\n isPlainObject,\n Json,\n NonEmptyArray,\n} from '@metamask/utils';\nimport {\n SnapCaveatType,\n CronjobSpecification,\n isCronjobSpecificationArray,\n} from '@metamask/snaps-utils';\nimport { ethErrors } from 'eth-rpc-errors';\nimport { SnapEndowments } from './enum';\n\nconst permissionName = SnapEndowments.Cronjob;\n\ntype CronjobEndowmentSpecification = ValidPermissionSpecification<{\n permissionType: PermissionType.Endowment;\n targetKey: typeof permissionName;\n endowmentGetter: (_options?: any) => undefined;\n allowedCaveats: Readonly<NonEmptyArray<string>> | null;\n}>;\n\n/**\n * `endowment:cronjob` returns nothing; it is intended to be used as a flag to determine whether the snap wants to run cronjobs.\n *\n * @param _builderOptions - Optional specification builder options.\n * @returns The specification for the cronjob endowment.\n */\nconst specificationBuilder: PermissionSpecificationBuilder<\n PermissionType.Endowment,\n any,\n CronjobEndowmentSpecification\n> = (_builderOptions?: any) => {\n return {\n permissionType: PermissionType.Endowment,\n targetKey: permissionName,\n allowedCaveats: [SnapCaveatType.SnapCronjob],\n endowmentGetter: (_getterOptions?: EndowmentGetterParams) => undefined,\n };\n};\n\nexport const cronjobEndowmentBuilder = Object.freeze({\n targetKey: permissionName,\n specificationBuilder,\n} as const);\n\n/**\n * Map a raw value from the `initialPermissions` to a caveat specification.\n * Note that this function does not do any validation, that's handled by the\n * PermissionsController when the permission is requested.\n *\n * @param value - The raw value from the `initialPermissions`.\n * @returns The caveat specification.\n */\nexport function getCronjobCaveatMapper(\n value: Json,\n): Pick<PermissionConstraint, 'caveats'> {\n return {\n caveats: [\n {\n type: SnapCaveatType.SnapCronjob,\n value,\n },\n ],\n };\n}\n\n/**\n * Getter function to get the cronjobs from a permission.\n *\n * This does basic validation of the caveat, but does not validate the type or\n * value of the namespaces object itself, as this is handled by the\n * `PermissionsController` when the permission is requested.\n *\n * @param permission - The permission to get the keyring namespaces from.\n * @returns The cronjobs, or `null` if the permission does not have a\n * cronjob caveat.\n */\nexport function getCronjobCaveatJobs(\n permission?: PermissionConstraint,\n): CronjobSpecification[] | null {\n if (!permission?.caveats) {\n return null;\n }\n\n assert(permission.caveats.length === 1);\n assert(permission.caveats[0].type === SnapCaveatType.SnapCronjob);\n\n const caveat = permission.caveats[0] as Caveat<string, { jobs: Json[] }>;\n\n return (caveat.value?.jobs as CronjobSpecification[]) ?? null;\n}\n\n/**\n * Validate the cronjob specification values associated with a caveat.\n * This validates that the value is a non-empty array with valid\n * cronjob expression and request object.\n *\n * @param caveat - The caveat to validate.\n * @throws If the value is invalid.\n */\nexport function validateCronjobCaveat(caveat: Caveat<string, any>) {\n if (!hasProperty(caveat, 'value') || !isPlainObject(caveat.value)) {\n throw ethErrors.rpc.invalidParams({\n message: 'Expected a plain object.',\n });\n }\n\n const { value } = caveat;\n\n if (!hasProperty(value, 'jobs') || !isPlainObject(value)) {\n throw ethErrors.rpc.invalidParams({\n message: 'Expected a plain object.',\n });\n }\n\n if (!isCronjobSpecificationArray(value.jobs)) {\n throw ethErrors.rpc.invalidParams({\n message: 'Expected a valid cronjob specification array.',\n });\n }\n}\n\n/**\n * Caveat specification for the Cronjob.\n */\nexport const cronjobCaveatSpecifications: Record<\n SnapCaveatType.SnapCronjob,\n CaveatSpecificationConstraint\n> = {\n [SnapCaveatType.SnapCronjob]: Object.freeze({\n type: SnapCaveatType.SnapCronjob,\n validator: (caveat) => validateCronjobCaveat(caveat),\n }),\n};\n"]}
@@ -0,0 +1,8 @@
1
+ export declare enum SnapEndowments {
2
+ NetworkAccess = "endowment:network-access",
3
+ LongRunning = "endowment:long-running",
4
+ TransactionInsight = "endowment:transaction-insight",
5
+ Keyring = "endowment:keyring",
6
+ Cronjob = "endowment:cronjob",
7
+ EthereumProvider = "endowment:ethereum-provider"
8
+ }
@@ -0,0 +1,13 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SnapEndowments = void 0;
4
+ var SnapEndowments;
5
+ (function (SnapEndowments) {
6
+ SnapEndowments["NetworkAccess"] = "endowment:network-access";
7
+ SnapEndowments["LongRunning"] = "endowment:long-running";
8
+ SnapEndowments["TransactionInsight"] = "endowment:transaction-insight";
9
+ SnapEndowments["Keyring"] = "endowment:keyring";
10
+ SnapEndowments["Cronjob"] = "endowment:cronjob";
11
+ SnapEndowments["EthereumProvider"] = "endowment:ethereum-provider";
12
+ })(SnapEndowments = exports.SnapEndowments || (exports.SnapEndowments = {}));
13
+ //# sourceMappingURL=enum.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"enum.js","sourceRoot":"","sources":["../../../src/snaps/endowments/enum.ts"],"names":[],"mappings":";;;AAAA,IAAY,cAOX;AAPD,WAAY,cAAc;IACxB,4DAA0C,CAAA;IAC1C,wDAAsC,CAAA;IACtC,sEAAoD,CAAA;IACpD,+CAA6B,CAAA;IAC7B,+CAA6B,CAAA;IAC7B,kEAAgD,CAAA;AAClD,CAAC,EAPW,cAAc,GAAd,sBAAc,KAAd,sBAAc,QAOzB","sourcesContent":["export enum SnapEndowments {\n NetworkAccess = 'endowment:network-access',\n LongRunning = 'endowment:long-running',\n TransactionInsight = 'endowment:transaction-insight',\n Keyring = 'endowment:keyring',\n Cronjob = 'endowment:cronjob',\n EthereumProvider = 'endowment:ethereum-provider',\n}\n"]}
@@ -0,0 +1,13 @@
1
+ import { PermissionSpecificationBuilder, PermissionType } from '@metamask/controllers';
2
+ import { SnapEndowments } from './enum';
3
+ declare const permissionName = SnapEndowments.EthereumProvider;
4
+ export declare const ethereumProviderEndowmentBuilder: Readonly<{
5
+ readonly targetKey: SnapEndowments.EthereumProvider;
6
+ readonly specificationBuilder: PermissionSpecificationBuilder<PermissionType.Endowment, any, {
7
+ permissionType: PermissionType.Endowment;
8
+ targetKey: typeof permissionName;
9
+ endowmentGetter: (_options?: any) => ['ethereum'];
10
+ allowedCaveats: null;
11
+ }>;
12
+ }>;
13
+ export {};