@metamask/snaps-controllers 14.2.2 → 15.0.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 (42) hide show
  1. package/CHANGELOG.md +25 -1
  2. package/dist/cronjob/CronjobController.cjs +6 -1
  3. package/dist/cronjob/CronjobController.cjs.map +1 -1
  4. package/dist/cronjob/CronjobController.d.cts.map +1 -1
  5. package/dist/cronjob/CronjobController.d.mts.map +1 -1
  6. package/dist/cronjob/CronjobController.mjs +6 -1
  7. package/dist/cronjob/CronjobController.mjs.map +1 -1
  8. package/dist/insights/SnapInsightsController.cjs +6 -1
  9. package/dist/insights/SnapInsightsController.cjs.map +1 -1
  10. package/dist/insights/SnapInsightsController.d.cts.map +1 -1
  11. package/dist/insights/SnapInsightsController.d.mts.map +1 -1
  12. package/dist/insights/SnapInsightsController.mjs +6 -1
  13. package/dist/insights/SnapInsightsController.mjs.map +1 -1
  14. package/dist/interface/SnapInterfaceController.cjs +7 -5
  15. package/dist/interface/SnapInterfaceController.cjs.map +1 -1
  16. package/dist/interface/SnapInterfaceController.d.cts +2 -2
  17. package/dist/interface/SnapInterfaceController.d.cts.map +1 -1
  18. package/dist/interface/SnapInterfaceController.d.mts +2 -2
  19. package/dist/interface/SnapInterfaceController.d.mts.map +1 -1
  20. package/dist/interface/SnapInterfaceController.mjs +7 -5
  21. package/dist/interface/SnapInterfaceController.mjs.map +1 -1
  22. package/dist/services/AbstractExecutionService.cjs +22 -8
  23. package/dist/services/AbstractExecutionService.cjs.map +1 -1
  24. package/dist/services/AbstractExecutionService.d.cts.map +1 -1
  25. package/dist/services/AbstractExecutionService.d.mts.map +1 -1
  26. package/dist/services/AbstractExecutionService.mjs +24 -10
  27. package/dist/services/AbstractExecutionService.mjs.map +1 -1
  28. package/dist/snaps/SnapController.cjs +129 -71
  29. package/dist/snaps/SnapController.cjs.map +1 -1
  30. package/dist/snaps/SnapController.d.cts +13 -50
  31. package/dist/snaps/SnapController.d.cts.map +1 -1
  32. package/dist/snaps/SnapController.d.mts +13 -50
  33. package/dist/snaps/SnapController.d.mts.map +1 -1
  34. package/dist/snaps/SnapController.mjs +131 -73
  35. package/dist/snaps/SnapController.mjs.map +1 -1
  36. package/dist/snaps/registry/json.cjs +18 -3
  37. package/dist/snaps/registry/json.cjs.map +1 -1
  38. package/dist/snaps/registry/json.d.cts.map +1 -1
  39. package/dist/snaps/registry/json.d.mts.map +1 -1
  40. package/dist/snaps/registry/json.mjs +18 -3
  41. package/dist/snaps/registry/json.mjs.map +1 -1
  42. package/package.json +11 -9
@@ -1 +1 @@
1
- {"version":3,"file":"SnapInsightsController.mjs","sourceRoot":"","sources":["../../src/insights/SnapInsightsController.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,cAAc,EAAE,kCAAkC;AAM3D,OAAO,EACL,wBAAwB,EACxB,0BAA0B,EAC1B,cAAc,EACf,oCAAoC;AAErC,OAAO,EAAE,WAAW,EAAE,8BAA8B;AACpD,OAAO,EAAE,WAAW,EAAE,WAAW,EAAE,wBAAwB;AAI3D,OAAO,EAAE,gBAAgB,EAAE,2BAAiB;AAU5C,MAAM,cAAc,GAAG,wBAAwB,CAAC;AA0DhD;;GAEG;AACH,MAAM,OAAO,sBAAuB,SAAQ,cAI3C;IACC,YAAY,EAAE,SAAS,EAAE,KAAK,EAA8B;QAC1D,KAAK,CAAC;YACJ,SAAS;YACT,QAAQ,EAAE;gBACR,QAAQ,EAAE,EAAE,OAAO,EAAE,KAAK,EAAE,SAAS,EAAE,KAAK,EAAE;aAC/C;YACD,IAAI,EAAE,cAAc;YACpB,KAAK,EAAE,EAAE,QAAQ,EAAE,EAAE,EAAE,GAAG,KAAK,EAAE;SAClC,CAAC,CAAC;QAEH,IAAI,CAAC,eAAe,CAAC,SAAS,CAC5B,kDAAkD,EAClD,IAAI,CAAC,kBAAkB,CAAC,IAAI,CAAC,IAAI,CAAC,CACnC,CAAC;QAEF,IAAI,CAAC,eAAe,CAAC,SAAS,CA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OAAO,GAAG,KAAK,CAAC;YAC3C,KAAK,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,MAAM,CAAC,CAAC,WAAW,GAAG,QAAQ,EAAE,EAAY,CAAC;YAChE,KAAK,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,MAAM,CAAC,CAAC,QAAQ,GAAG,QAAQ,EAAE,QAAkB,CAAC;YACnE,KAAK,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,MAAM,CAAC,CAAC,KAAK,GAAG,KAAK,EAAE,OAAO,CAAC;QACpD,CAAC,CAAC,CAAC;IACL,CAAC;CACF","sourcesContent":["import type {\n RestrictedMessenger,\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n} from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport type {\n Caveat,\n GetPermissions,\n ValidPermission,\n} from '@metamask/permission-controller';\nimport {\n getSignatureOriginCaveat,\n getTransactionOriginCaveat,\n SnapEndowments,\n} from '@metamask/snaps-rpc-methods';\nimport type { Json, SnapId } from '@metamask/snaps-sdk';\nimport { HandlerType } from '@metamask/snaps-utils';\nimport { hasProperty, hexToBigInt } from '@metamask/utils';\n\nimport type { DeleteInterface } from '../interface';\nimport type { GetAllSnaps, HandleSnapRequest } from '../snaps';\nimport { getRunnableSnaps } from '../snaps';\nimport type {\n TransactionControllerUnapprovedTransactionAddedEvent,\n TransactionMeta,\n SignatureStateChange,\n SignatureControllerState,\n StateSignature,\n TransactionControllerTransactionStatusUpdatedEvent,\n} from '../types';\n\nconst controllerName = 'SnapInsightsController';\n\nexport type SnapInsightsControllerAllowedActions =\n | HandleSnapRequest\n | GetAllSnaps\n | GetPermissions\n | DeleteInterface;\n\nexport type SnapInsightsControllerGetStateAction = ControllerGetStateAction<\n typeof controllerName,\n SnapInsightsControllerState\n>;\n\nexport type SnapInsightsControllerActions =\n SnapInsightsControllerGetStateAction;\n\nexport type SnapInsightControllerStateChangeEvent = ControllerStateChangeEvent<\n typeof controllerName,\n SnapInsightsControllerState\n>;\n\nexport type SnapInsightControllerEvents = SnapInsightControllerStateChangeEvent;\n\nexport type SnapInsightsControllerAllowedEvents =\n | TransactionControllerUnapprovedTransactionAddedEvent\n | TransactionControllerTransactionStatusUpdatedEvent\n | SignatureStateChange;\n\nexport type SnapInsightsControllerMessenger = RestrictedMessenger<\n typeof controllerName,\n SnapInsightsControllerActions | SnapInsightsControllerAllowedActions,\n SnapInsightControllerEvents | SnapInsightsControllerAllowedEvents,\n SnapInsightsControllerAllowedActions['type'],\n SnapInsightsControllerAllowedEvents['type']\n>;\n\nexport type SnapInsight = {\n snapId: SnapId;\n interfaceId?: string | null;\n error?: string;\n loading: boolean;\n severity?: string;\n};\n\nexport type SnapInsightsControllerState = {\n insights: Record<string, Record<SnapId, SnapInsight>>;\n};\n\nexport type SnapInsightsControllerArgs = {\n messenger: SnapInsightsControllerMessenger;\n state?: SnapInsightsControllerState;\n};\n\ntype SnapWithPermission = {\n snapId: SnapId;\n permission: ValidPermission<string, Caveat<string, Json>>;\n};\n\n/**\n * Controller for monitoring for new transactions and signatures to provide insight for.\n */\nexport class SnapInsightsController extends BaseController<\n typeof controllerName,\n SnapInsightsControllerState,\n SnapInsightsControllerMessenger\n> {\n constructor({ messenger, state }: SnapInsightsControllerArgs) {\n super({\n messenger,\n metadata: {\n insights: { persist: false, anonymous: false },\n },\n name: controllerName,\n state: { insights: {}, ...state },\n });\n\n this.messagingSystem.subscribe(\n 'TransactionController:unapprovedTransactionAdded',\n this.#handleTransaction.bind(this),\n );\n\n this.messagingSystem.subscribe(\n 'TransactionController:transactionStatusUpdated',\n this.#handleTransactionStatusUpdate.bind(this),\n );\n\n this.messagingSystem.subscribe(\n 'SignatureController:stateChange',\n this.#handleSignatureStateChange.bind(this),\n );\n }\n\n /**\n * Check if an insight already exists for a given ID.\n *\n * @param id - The ID.\n * @returns True if the insight already exists, otherwise false.\n */\n #hasInsight(id: string) {\n return hasProperty(this.state.insights, id);\n }\n\n /**\n * Get a list of runnable Snaps that have a given permission.\n * Also includes the permission object itself.\n *\n * @param permissionName - The permission name.\n * @returns A list of objects containing Snap IDs and the permission object.\n */\n #getSnapsWithPermission(permissionName: string) {\n const allSnaps = this.messagingSystem.call('SnapController:getAll');\n const filteredSnaps = getRunnableSnaps(allSnaps);\n\n return filteredSnaps.reduce<SnapWithPermission[]>((accumulator, snap) => {\n const permissions = this.messagingSystem.call(\n 'PermissionController:getPermissions',\n snap.id,\n );\n if (permissions && hasProperty(permissions, permissionName)) {\n accumulator.push({\n snapId: snap.id,\n permission: permissions[permissionName],\n });\n }\n\n return accumulator;\n }, []);\n }\n\n /**\n * Handle a newly added unapproved transaction.\n * This function fetches insights from all available Snaps\n * and populates the insights state blob with the responses.\n *\n * @param transaction - The transaction object.\n */\n #handleTransaction(transaction: TransactionMeta) {\n const { id, txParams, chainId, origin } = transaction;\n\n // This assumes that the transactions are EVM-compatible for now.\n const caipChainId = `eip155:${hexToBigInt(chainId).toString(10)}`;\n\n const snaps = this.#getSnapsWithPermission(\n SnapEndowments.TransactionInsight,\n );\n\n snaps.forEach(({ snapId, permission }) => {\n const hasTransactionOriginCaveat = getTransactionOriginCaveat(permission);\n const transactionOrigin =\n hasTransactionOriginCaveat && origin ? origin : null;\n\n this.update((state) => {\n state.insights[id] ??= {};\n state.insights[id][snapId] = { snapId, loading: true };\n });\n\n this.#handleSnapRequest({\n snapId,\n handler: HandlerType.OnTransaction,\n params: {\n transaction: txParams,\n chainId: caipChainId,\n transactionOrigin,\n },\n })\n .then((response) =>\n this.#handleSnapResponse({\n id,\n snapId,\n response: response as Record<string, Json>,\n }),\n )\n .catch((error) => this.#handleSnapResponse({ id, snapId, error }));\n });\n }\n\n /**\n * Handle the stateChange event emitted by the SignatureController.\n * This function will remove existing insights from the state when applicable, as well as\n * trigger insight fetching for newly added signatures.\n *\n * @param state - The SignatureController state blob.\n */\n #handleSignatureStateChange(state: SignatureControllerState) {\n // If any IDs have disappeared since the last state update, the insight may be cleaned up.\n for (const id of Object.keys(this.state.insights)) {\n if (\n !hasProperty(state.unapprovedTypedMessages, id) &&\n !hasProperty(state.unapprovedPersonalMsgs, id)\n ) {\n this.#handleInsightCleanup(id);\n }\n }\n\n if (\n state.unapprovedPersonalMsgCount > 0 ||\n state.unapprovedTypedMessagesCount > 0\n ) {\n const snaps = this.#getSnapsWithPermission(\n SnapEndowments.SignatureInsight,\n );\n\n // This isn't very efficient, but SignatureController doesn't expose a better event for us to use yet.\n for (const personalSignature of Object.values(\n state.unapprovedPersonalMsgs,\n )) {\n this.#handleSignature(snaps, personalSignature);\n }\n\n for (const typedMessage of Object.values(state.unapprovedTypedMessages)) {\n this.#handleSignature(snaps, typedMessage);\n }\n }\n }\n\n /**\n * Handle a newly added unapproved signature.\n * This function fetches insights from all available Snaps\n * and populates the insights state blob with the responses.\n *\n * @param snaps - A list of Snaps to invoke.\n * @param signature - The signature object.\n */\n #handleSignature(snaps: SnapWithPermission[], signature: StateSignature) {\n const { id, msgParams } = signature;\n\n if (this.#hasInsight(id)) {\n return;\n }\n\n const { from, data, signatureMethod, origin } = msgParams;\n\n /**\n * Both eth_signTypedData_v3 and eth_signTypedData_v4 methods\n * need to be parsed because their data is stringified. All other\n * signature methods do not, so they are ignored.\n */\n const shouldParse =\n signatureMethod === 'eth_signTypedData_v3' ||\n signatureMethod === 'eth_signTypedData_v4';\n\n const payload = {\n from,\n data: shouldParse ? JSON.parse(data as string) : data,\n signatureMethod,\n };\n\n snaps.forEach(({ snapId, permission }) => {\n const hasSignatureOriginCaveat = getSignatureOriginCaveat(permission);\n const signatureOrigin =\n origin && hasSignatureOriginCaveat ? origin : null;\n\n this.update((state) => {\n state.insights[id] ??= {};\n state.insights[id][snapId] = { snapId, loading: true };\n });\n\n this.#handleSnapRequest({\n snapId,\n handler: HandlerType.OnSignature,\n params: { signature: payload, signatureOrigin },\n })\n .then((response) =>\n this.#handleSnapResponse({\n id,\n snapId,\n response: response as Record<string, Json>,\n }),\n )\n .catch((error) => this.#handleSnapResponse({ id, snapId, error }));\n });\n }\n\n /**\n * Handle the transactionStatusUpdated event emitted by the TransactionController.\n * This function will remove insights for the transaction in question\n * once the transaction status has changed from unapproved.\n *\n * @param args - An options bag.\n * @param args.transactionMeta - The transaction.\n */\n #handleTransactionStatusUpdate({\n transactionMeta,\n }: {\n transactionMeta: TransactionMeta;\n }) {\n if (transactionMeta.status !== 'unapproved') {\n this.#handleInsightCleanup(transactionMeta.id);\n }\n }\n\n #handleInsightCleanup(id: string) {\n if (!this.#hasInsight(id)) {\n return;\n }\n\n // Delete interfaces from interface controller.\n Object.values(this.state.insights[id])\n .filter((insight) => insight.interfaceId)\n .forEach((insight) => {\n this.messagingSystem.call(\n 'SnapInterfaceController:deleteInterface',\n insight.interfaceId as string,\n );\n });\n\n this.update((state) => {\n delete state.insights[id];\n });\n }\n\n /**\n * Handle sending a request to a given Snap with a given payload.\n *\n * @param args - An options bag.\n * @param args.snapId - The Snap ID.\n * @param args.handler - The handler to invoke.\n * @param args.params - The JSON-RPC params to send.\n * @returns The response from the Snap.\n */\n async #handleSnapRequest({\n snapId,\n handler,\n params,\n }: {\n snapId: SnapId;\n handler: HandlerType.OnTransaction | HandlerType.OnSignature;\n params: Record<string, Json>;\n }) {\n return this.messagingSystem.call('SnapController:handleRequest', {\n snapId,\n origin: 'metamask',\n handler,\n request: {\n method: '',\n params,\n },\n });\n }\n\n /**\n * Handle response from a given Snap by persisting the response or error in state.\n *\n * @param args - An options bag.\n * @param args.id - The transaction or signature ID.\n * @param args.snapId - The Snap ID.\n * @param args.response - An optional response object returned by the Snap.\n * @param args.error - An optional error returned by the Snap.\n */\n #handleSnapResponse({\n id,\n snapId,\n response,\n error,\n }: {\n id: string;\n snapId: SnapId;\n response?: Record<string, Json>;\n error?: Error;\n }) {\n // If the insight has been cleaned up already, we can skip setting the state.\n // This may happen if a user accepts/rejects a transaction/signature faster than the Snap responds.\n if (!this.#hasInsight(id)) {\n return;\n }\n\n this.update((state) => {\n state.insights[id][snapId].loading = false;\n state.insights[id][snapId].interfaceId = response?.id as string;\n state.insights[id][snapId].severity = response?.severity as string;\n state.insights[id][snapId].error = error?.message;\n });\n }\n}\n"]}
1
+ {"version":3,"file":"SnapInsightsController.mjs","sourceRoot":"","sources":["../../src/insights/SnapInsightsController.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,cAAc,EAAE,kCAAkC;AAM3D,OAAO,EACL,wBAAwB,EACxB,0BAA0B,EAC1B,cAAc,EACf,oCAAoC;AAErC,OAAO,EAAE,WAAW,EAAE,8BAA8B;AACpD,OAAO,EAAE,WAAW,EAAE,WAAW,EAAE,wBAAwB;AAI3D,OAAO,EAAE,gBAAgB,EAAE,2BAAiB;AAU5C,MAAM,cAAc,GAAG,wBAAwB,CAAC;AA0DhD;;GAEG;AACH,MAAM,OAAO,sBAAuB,SAAQ,cAI3C;IACC,YAAY,EAAE,SAAS,EAAE,KAAK,EAA8B;QAC1D,KAAK,CAAC;YACJ,SAAS;YACT,QAAQ,EAAE;gBACR,QAAQ,EAAE;oBACR,kBAAkB,EAAE,IAAI;oBACxB,OAAO,EAAE,KAAK;oBACd,SAAS,EAAE,KAAK;oBAChB,QAAQ,EAAE,IAAI;iBACf;aACF;YACD,IAAI,EAAE,cAAc;YACpB,KAAK,EAAE,EAAE,QAAQ,EAAE,EAAE,EAAE,GAAG,KAAK,EAAE;SAClC,CAAC,CAAC;QAEH,IAAI,CAAC,eAAe,CAAC,SAAS,CAC5B,kDAAkD,EAClD,IAAI,CAAC,kBAAkB,CAAC,IAAI,CAAC,IAAI,CAAC,CACnC,CAAC;QAEF,IAAI,CAAC,eAAe,CAAC,SAAS,CAC5B,gDAAgD,EAChD,IAAI,CAAC,8BAA8B,CAAC,IAAI,CAAC,IAAI,CAAC,CAC/C,CAAC;QAEF,IAAI,CAAC,eAAe,CAAC,SAAS,CAC5B,iCAAiC,EACjC,IAAI,CAAC,2BAA2B,CAAC,IAAI,CAAC,IAAI,CAAC,CAC5C,CAAC;IACJ,CAAC;IAED;;;;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AAkB,CAAC;YACnE,KAAK,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,MAAM,CAAC,CAAC,KAAK,GAAG,KAAK,EAAE,OAAO,CAAC;QACpD,CAAC,CAAC,CAAC;IACL,CAAC;CACF","sourcesContent":["import type {\n RestrictedMessenger,\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n} from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport type {\n Caveat,\n GetPermissions,\n ValidPermission,\n} from '@metamask/permission-controller';\nimport {\n getSignatureOriginCaveat,\n getTransactionOriginCaveat,\n SnapEndowments,\n} from '@metamask/snaps-rpc-methods';\nimport type { Json, SnapId } from '@metamask/snaps-sdk';\nimport { HandlerType } from '@metamask/snaps-utils';\nimport { hasProperty, hexToBigInt } from '@metamask/utils';\n\nimport type { DeleteInterface } from '../interface';\nimport type { GetAllSnaps, HandleSnapRequest } from '../snaps';\nimport { getRunnableSnaps } from '../snaps';\nimport type {\n TransactionControllerUnapprovedTransactionAddedEvent,\n TransactionMeta,\n SignatureStateChange,\n SignatureControllerState,\n StateSignature,\n TransactionControllerTransactionStatusUpdatedEvent,\n} from '../types';\n\nconst controllerName = 'SnapInsightsController';\n\nexport type SnapInsightsControllerAllowedActions =\n | HandleSnapRequest\n | GetAllSnaps\n | GetPermissions\n | DeleteInterface;\n\nexport type SnapInsightsControllerGetStateAction = ControllerGetStateAction<\n typeof controllerName,\n SnapInsightsControllerState\n>;\n\nexport type SnapInsightsControllerActions =\n SnapInsightsControllerGetStateAction;\n\nexport type SnapInsightControllerStateChangeEvent = ControllerStateChangeEvent<\n typeof controllerName,\n SnapInsightsControllerState\n>;\n\nexport type SnapInsightControllerEvents = SnapInsightControllerStateChangeEvent;\n\nexport type SnapInsightsControllerAllowedEvents =\n | TransactionControllerUnapprovedTransactionAddedEvent\n | TransactionControllerTransactionStatusUpdatedEvent\n | SignatureStateChange;\n\nexport type SnapInsightsControllerMessenger = RestrictedMessenger<\n typeof controllerName,\n SnapInsightsControllerActions | SnapInsightsControllerAllowedActions,\n SnapInsightControllerEvents | SnapInsightsControllerAllowedEvents,\n SnapInsightsControllerAllowedActions['type'],\n SnapInsightsControllerAllowedEvents['type']\n>;\n\nexport type SnapInsight = {\n snapId: SnapId;\n interfaceId?: string | null;\n error?: string;\n loading: boolean;\n severity?: string;\n};\n\nexport type SnapInsightsControllerState = {\n insights: Record<string, Record<SnapId, SnapInsight>>;\n};\n\nexport type SnapInsightsControllerArgs = {\n messenger: SnapInsightsControllerMessenger;\n state?: SnapInsightsControllerState;\n};\n\ntype SnapWithPermission = {\n snapId: SnapId;\n permission: ValidPermission<string, Caveat<string, Json>>;\n};\n\n/**\n * Controller for monitoring for new transactions and signatures to provide insight for.\n */\nexport class SnapInsightsController extends BaseController<\n typeof controllerName,\n SnapInsightsControllerState,\n SnapInsightsControllerMessenger\n> {\n constructor({ messenger, state }: SnapInsightsControllerArgs) {\n super({\n messenger,\n metadata: {\n insights: {\n includeInStateLogs: true,\n persist: false,\n anonymous: false,\n usedInUi: true,\n },\n },\n name: controllerName,\n state: { insights: {}, ...state },\n });\n\n this.messagingSystem.subscribe(\n 'TransactionController:unapprovedTransactionAdded',\n this.#handleTransaction.bind(this),\n );\n\n this.messagingSystem.subscribe(\n 'TransactionController:transactionStatusUpdated',\n this.#handleTransactionStatusUpdate.bind(this),\n );\n\n this.messagingSystem.subscribe(\n 'SignatureController:stateChange',\n this.#handleSignatureStateChange.bind(this),\n );\n }\n\n /**\n * Check if an insight already exists for a given ID.\n *\n * @param id - The ID.\n * @returns True if the insight already exists, otherwise false.\n */\n #hasInsight(id: string) {\n return hasProperty(this.state.insights, id);\n }\n\n /**\n * Get a list of runnable Snaps that have a given permission.\n * Also includes the permission object itself.\n *\n * @param permissionName - The permission name.\n * @returns A list of objects containing Snap IDs and the permission object.\n */\n #getSnapsWithPermission(permissionName: string) {\n const allSnaps = this.messagingSystem.call('SnapController:getAll');\n const filteredSnaps = getRunnableSnaps(allSnaps);\n\n return filteredSnaps.reduce<SnapWithPermission[]>((accumulator, snap) => {\n const permissions = this.messagingSystem.call(\n 'PermissionController:getPermissions',\n snap.id,\n );\n if (permissions && hasProperty(permissions, permissionName)) {\n accumulator.push({\n snapId: snap.id,\n permission: permissions[permissionName],\n });\n }\n\n return accumulator;\n }, []);\n }\n\n /**\n * Handle a newly added unapproved transaction.\n * This function fetches insights from all available Snaps\n * and populates the insights state blob with the responses.\n *\n * @param transaction - The transaction object.\n */\n #handleTransaction(transaction: TransactionMeta) {\n const { id, txParams, chainId, origin } = transaction;\n\n // This assumes that the transactions are EVM-compatible for now.\n const caipChainId = `eip155:${hexToBigInt(chainId).toString(10)}`;\n\n const snaps = this.#getSnapsWithPermission(\n SnapEndowments.TransactionInsight,\n );\n\n snaps.forEach(({ snapId, permission }) => {\n const hasTransactionOriginCaveat = getTransactionOriginCaveat(permission);\n const transactionOrigin =\n hasTransactionOriginCaveat && origin ? origin : null;\n\n this.update((state) => {\n state.insights[id] ??= {};\n state.insights[id][snapId] = { snapId, loading: true };\n });\n\n this.#handleSnapRequest({\n snapId,\n handler: HandlerType.OnTransaction,\n params: {\n transaction: txParams,\n chainId: caipChainId,\n transactionOrigin,\n },\n })\n .then((response) =>\n this.#handleSnapResponse({\n id,\n snapId,\n response: response as Record<string, Json>,\n }),\n )\n .catch((error) => this.#handleSnapResponse({ id, snapId, error }));\n });\n }\n\n /**\n * Handle the stateChange event emitted by the SignatureController.\n * This function will remove existing insights from the state when applicable, as well as\n * trigger insight fetching for newly added signatures.\n *\n * @param state - The SignatureController state blob.\n */\n #handleSignatureStateChange(state: SignatureControllerState) {\n // If any IDs have disappeared since the last state update, the insight may be cleaned up.\n for (const id of Object.keys(this.state.insights)) {\n if (\n !hasProperty(state.unapprovedTypedMessages, id) &&\n !hasProperty(state.unapprovedPersonalMsgs, id)\n ) {\n this.#handleInsightCleanup(id);\n }\n }\n\n if (\n state.unapprovedPersonalMsgCount > 0 ||\n state.unapprovedTypedMessagesCount > 0\n ) {\n const snaps = this.#getSnapsWithPermission(\n SnapEndowments.SignatureInsight,\n );\n\n // This isn't very efficient, but SignatureController doesn't expose a better event for us to use yet.\n for (const personalSignature of Object.values(\n state.unapprovedPersonalMsgs,\n )) {\n this.#handleSignature(snaps, personalSignature);\n }\n\n for (const typedMessage of Object.values(state.unapprovedTypedMessages)) {\n this.#handleSignature(snaps, typedMessage);\n }\n }\n }\n\n /**\n * Handle a newly added unapproved signature.\n * This function fetches insights from all available Snaps\n * and populates the insights state blob with the responses.\n *\n * @param snaps - A list of Snaps to invoke.\n * @param signature - The signature object.\n */\n #handleSignature(snaps: SnapWithPermission[], signature: StateSignature) {\n const { id, msgParams } = signature;\n\n if (this.#hasInsight(id)) {\n return;\n }\n\n const { from, data, signatureMethod, origin } = msgParams;\n\n /**\n * Both eth_signTypedData_v3 and eth_signTypedData_v4 methods\n * need to be parsed because their data is stringified. All other\n * signature methods do not, so they are ignored.\n */\n const shouldParse =\n signatureMethod === 'eth_signTypedData_v3' ||\n signatureMethod === 'eth_signTypedData_v4';\n\n const payload = {\n from,\n data: shouldParse ? JSON.parse(data as string) : data,\n signatureMethod,\n };\n\n snaps.forEach(({ snapId, permission }) => {\n const hasSignatureOriginCaveat = getSignatureOriginCaveat(permission);\n const signatureOrigin =\n origin && hasSignatureOriginCaveat ? origin : null;\n\n this.update((state) => {\n state.insights[id] ??= {};\n state.insights[id][snapId] = { snapId, loading: true };\n });\n\n this.#handleSnapRequest({\n snapId,\n handler: HandlerType.OnSignature,\n params: { signature: payload, signatureOrigin },\n })\n .then((response) =>\n this.#handleSnapResponse({\n id,\n snapId,\n response: response as Record<string, Json>,\n }),\n )\n .catch((error) => this.#handleSnapResponse({ id, snapId, error }));\n });\n }\n\n /**\n * Handle the transactionStatusUpdated event emitted by the TransactionController.\n * This function will remove insights for the transaction in question\n * once the transaction status has changed from unapproved.\n *\n * @param args - An options bag.\n * @param args.transactionMeta - The transaction.\n */\n #handleTransactionStatusUpdate({\n transactionMeta,\n }: {\n transactionMeta: TransactionMeta;\n }) {\n if (transactionMeta.status !== 'unapproved') {\n this.#handleInsightCleanup(transactionMeta.id);\n }\n }\n\n #handleInsightCleanup(id: string) {\n if (!this.#hasInsight(id)) {\n return;\n }\n\n // Delete interfaces from interface controller.\n Object.values(this.state.insights[id])\n .filter((insight) => insight.interfaceId)\n .forEach((insight) => {\n this.messagingSystem.call(\n 'SnapInterfaceController:deleteInterface',\n insight.interfaceId as string,\n );\n });\n\n this.update((state) => {\n delete state.insights[id];\n });\n }\n\n /**\n * Handle sending a request to a given Snap with a given payload.\n *\n * @param args - An options bag.\n * @param args.snapId - The Snap ID.\n * @param args.handler - The handler to invoke.\n * @param args.params - The JSON-RPC params to send.\n * @returns The response from the Snap.\n */\n async #handleSnapRequest({\n snapId,\n handler,\n params,\n }: {\n snapId: SnapId;\n handler: HandlerType.OnTransaction | HandlerType.OnSignature;\n params: Record<string, Json>;\n }) {\n return this.messagingSystem.call('SnapController:handleRequest', {\n snapId,\n origin: 'metamask',\n handler,\n request: {\n method: '',\n params,\n },\n });\n }\n\n /**\n * Handle response from a given Snap by persisting the response or error in state.\n *\n * @param args - An options bag.\n * @param args.id - The transaction or signature ID.\n * @param args.snapId - The Snap ID.\n * @param args.response - An optional response object returned by the Snap.\n * @param args.error - An optional error returned by the Snap.\n */\n #handleSnapResponse({\n id,\n snapId,\n response,\n error,\n }: {\n id: string;\n snapId: SnapId;\n response?: Record<string, Json>;\n error?: Error;\n }) {\n // If the insight has been cleaned up already, we can skip setting the state.\n // This may happen if a user accepts/rejects a transaction/signature faster than the Snap responds.\n if (!this.#hasInsight(id)) {\n return;\n }\n\n this.update((state) => {\n state.insights[id][snapId].loading = false;\n state.insights[id][snapId].interfaceId = response?.id as string;\n state.insights[id][snapId].severity = response?.severity as string;\n state.insights[id][snapId].error = error?.message;\n });\n }\n}\n"]}
@@ -19,6 +19,7 @@ class SnapInterfaceController extends base_controller_1.BaseController {
19
19
  messenger,
20
20
  metadata: {
21
21
  interfaces: {
22
+ includeInStateLogs: true,
22
23
  persist: (interfaces) => {
23
24
  return Object.entries(interfaces).reduce((persistedInterfaces, [id, snapInterface]) => {
24
25
  switch (snapInterface.contentType) {
@@ -31,6 +32,7 @@ class SnapInterfaceController extends base_controller_1.BaseController {
31
32
  }, {});
32
33
  },
33
34
  anonymous: false,
35
+ usedInUi: true,
34
36
  },
35
37
  },
36
38
  name: controllerName,
@@ -60,9 +62,9 @@ class SnapInterfaceController extends base_controller_1.BaseController {
60
62
  * @param contentType - The type of content.
61
63
  * @returns The newly interface id.
62
64
  */
63
- async createInterface(snapId, content, context, contentType) {
65
+ createInterface(snapId, content, context, contentType) {
64
66
  const element = (0, utils_2.getJsxInterface)(content);
65
- await this.#validateContent(element);
67
+ this.#validateContent(element);
66
68
  (0, utils_2.validateInterfaceContext)(context);
67
69
  const id = (0, nanoid_1.nanoid)();
68
70
  const componentState = (0, utils_2.constructState)({}, element, {
@@ -104,10 +106,10 @@ class SnapInterfaceController extends base_controller_1.BaseController {
104
106
  * @param content - The new content.
105
107
  * @param context - An optional interface context object.
106
108
  */
107
- async updateInterface(snapId, id, content, context) {
109
+ updateInterface(snapId, id, content, context) {
108
110
  this.#validateArgs(snapId, id);
109
111
  const element = (0, utils_2.getJsxInterface)(content);
110
- await this.#validateContent(element);
112
+ this.#validateContent(element);
111
113
  (0, utils_2.validateInterfaceContext)(context);
112
114
  const oldState = this.state.interfaces[id].state;
113
115
  const newState = (0, utils_2.constructState)(oldState, element, {
@@ -264,7 +266,7 @@ class SnapInterfaceController extends base_controller_1.BaseController {
264
266
  *
265
267
  * @param element - The JSX element to verify.
266
268
  */
267
- async #validateContent(element) {
269
+ #validateContent(element) {
268
270
  // We assume the validity of this JSON to be validated by the caller.
269
271
  // E.g., in the RPC method implementation.
270
272
  const size = (0, snaps_utils_1.getJsonSizeUnsafe)(element);
@@ -1 +1 @@
1
- {"version":3,"file":"SnapInterfaceController.cjs","sourceRoot":"","sources":["../../src/interface/SnapInterfaceController.ts"],"names":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nimport type {\n RestrictedMessenger,\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n} from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport type { TestOrigin } from '@metamask/phishing-controller';\nimport type {\n InterfaceState,\n SnapId,\n ComponentOrElement,\n InterfaceContext,\n FungibleAssetMetadata,\n} from '@metamask/snaps-sdk';\nimport { ContentType } from '@metamask/snaps-sdk';\nimport type { JSXElement } from '@metamask/snaps-sdk/jsx';\nimport type { InternalAccount } from '@metamask/snaps-utils';\nimport {\n getJsonSizeUnsafe,\n snapOwnsAccount,\n validateJsxElements,\n} from '@metamask/snaps-utils';\nimport type {\n CaipAccountId,\n CaipAssetType,\n CaipChainId,\n Json,\n} from '@metamask/utils';\nimport { assert, hasProperty, parseCaipAccountId } from '@metamask/utils';\nimport { castDraft } from 'immer';\nimport { nanoid } from 'nanoid';\n\nimport {\n constructState,\n getJsxInterface,\n isMatchingChainId,\n validateInterfaceContext,\n} from './utils';\nimport type { GetSnap } from '../snaps';\n\nconst MAX_UI_CONTENT_SIZE = 10_000_000; // 10 mb\n\nconst controllerName = 'SnapInterfaceController';\n\nexport type CreateInterface = {\n type: `${typeof controllerName}:createInterface`;\n handler: SnapInterfaceController['createInterface'];\n};\n\nexport type GetInterface = {\n type: `${typeof controllerName}:getInterface`;\n handler: SnapInterfaceController['getInterface'];\n};\n\nexport type UpdateInterface = {\n type: `${typeof controllerName}:updateInterface`;\n handler: SnapInterfaceController['updateInterface'];\n};\n\nexport type DeleteInterface = {\n type: `${typeof controllerName}:deleteInterface`;\n handler: SnapInterfaceController['deleteInterface'];\n};\n\nexport type UpdateInterfaceState = {\n type: `${typeof controllerName}:updateInterfaceState`;\n handler: SnapInterfaceController['updateInterfaceState'];\n};\n\nexport type ResolveInterface = {\n type: `${typeof controllerName}:resolveInterface`;\n handler: SnapInterfaceController['resolveInterface'];\n};\n\ntype AccountsControllerGetAccountByAddressAction = {\n type: `AccountsController:getAccountByAddress`;\n handler: (address: string) => InternalAccount | undefined;\n};\n\ntype AccountsControllerGetSelectedMultichainAccountAction = {\n type: `AccountsController:getSelectedMultichainAccount`;\n handler: () => InternalAccount;\n};\n\ntype AccountsControllerListMultichainAccountsAction = {\n type: `AccountsController:listMultichainAccounts`;\n handler: (chainId?: CaipChainId) => InternalAccount[];\n};\n\nexport type SnapInterfaceControllerGetStateAction = ControllerGetStateAction<\n typeof controllerName,\n SnapInterfaceControllerState\n>;\n\ntype MultichainAssetsControllerGetStateAction = ControllerGetStateAction<\n 'MultichainAssetsController',\n {\n assetsMetadata: {\n [asset: CaipAssetType]: FungibleAssetMetadata;\n };\n accountsAssets: { [account: string]: CaipAssetType[] };\n }\n>;\n\nexport type SnapInterfaceControllerAllowedActions =\n | TestOrigin\n | HasApprovalRequest\n | AcceptRequest\n | GetSnap\n | MultichainAssetsControllerGetStateAction\n | AccountsControllerGetSelectedMultichainAccountAction\n | AccountsControllerGetAccountByAddressAction\n | AccountsControllerListMultichainAccountsAction;\n\nexport type SnapInterfaceControllerActions =\n | CreateInterface\n | GetInterface\n | UpdateInterface\n | DeleteInterface\n | UpdateInterfaceState\n | ResolveInterface\n | SnapInterfaceControllerGetStateAction;\n\nexport type SnapInterfaceControllerStateChangeEvent =\n ControllerStateChangeEvent<\n typeof controllerName,\n SnapInterfaceControllerState\n >;\n\ntype OtherNotification = { type: string; [key: string]: unknown };\n\nexport type ExpandedView = {\n title: string;\n interfaceId: string;\n footerLink?: { href: string; text: string };\n};\n\ntype NormalSnapNotificationData = { message: string; origin: string };\n\ntype ExpandedSnapNotificationData = {\n message: string;\n origin: string;\n detailedView: ExpandedView;\n};\n\ntype SnapNotification = {\n type: 'snap';\n data: NormalSnapNotificationData | ExpandedSnapNotificationData;\n readDate: string | null;\n};\n\ntype Notification = OtherNotification | SnapNotification;\n\ntype NotificationListUpdatedEvent = {\n type: 'NotificationServicesController:notificationsListUpdated';\n payload: [Notification[]];\n};\n\nexport type SnapInterfaceControllerEvents =\n | SnapInterfaceControllerStateChangeEvent\n | NotificationListUpdatedEvent;\n\nexport type SnapInterfaceControllerMessenger = RestrictedMessenger<\n typeof controllerName,\n SnapInterfaceControllerActions | SnapInterfaceControllerAllowedActions,\n SnapInterfaceControllerEvents,\n SnapInterfaceControllerAllowedActions['type'],\n SnapInterfaceControllerEvents['type']\n>;\n\nexport type StoredInterface = {\n snapId: SnapId;\n content: JSXElement;\n state: InterfaceState;\n context: InterfaceContext | null;\n contentType: ContentType | null;\n};\n\nexport type SnapInterfaceControllerState = {\n interfaces: Record<string, StoredInterface>;\n};\n\nexport type SnapInterfaceControllerArgs = {\n messenger: SnapInterfaceControllerMessenger;\n state?: SnapInterfaceControllerState;\n};\n\n/**\n * Use this controller to manage snaps UI interfaces using RPC method hooks.\n */\nexport class SnapInterfaceController extends BaseController<\n typeof controllerName,\n SnapInterfaceControllerState,\n SnapInterfaceControllerMessenger\n> {\n constructor({ messenger, state }: SnapInterfaceControllerArgs) {\n super({\n messenger,\n metadata: {\n interfaces: {\n persist: (interfaces: Record<string, StoredInterface>) => {\n return Object.entries(interfaces).reduce<\n Record<string, StoredInterface>\n >((persistedInterfaces, [id, snapInterface]) => {\n switch (snapInterface.contentType) {\n case ContentType.Notification:\n persistedInterfaces[id] = snapInterface;\n return persistedInterfaces;\n default:\n return persistedInterfaces;\n }\n }, {});\n },\n anonymous: false,\n },\n },\n name: controllerName,\n state: { interfaces: {}, ...state },\n });\n\n this.messagingSystem.subscribe(\n 'NotificationServicesController:notificationsListUpdated',\n this.#onNotificationsListUpdated.bind(this),\n );\n\n this.#registerMessageHandlers();\n }\n\n /**\n * Constructor helper for registering this controller's messaging system\n * actions.\n */\n #registerMessageHandlers() {\n this.messagingSystem.registerActionHandler(\n `${controllerName}:createInterface`,\n this.createInterface.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:getInterface`,\n this.getInterface.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:updateInterface`,\n this.updateInterface.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:deleteInterface`,\n this.deleteInterface.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:updateInterfaceState`,\n this.updateInterfaceState.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:resolveInterface`,\n this.resolveInterface.bind(this),\n );\n }\n\n /**\n * Create an interface in the controller state with the associated data.\n *\n * @param snapId - The snap id that created the interface.\n * @param content - The interface content.\n * @param context - An optional interface context object.\n * @param contentType - The type of content.\n * @returns The newly interface id.\n */\n async createInterface(\n snapId: SnapId,\n content: ComponentOrElement,\n context?: InterfaceContext,\n contentType?: ContentType,\n ) {\n const element = getJsxInterface(content);\n await this.#validateContent(element);\n validateInterfaceContext(context);\n\n const id = nanoid();\n const componentState = constructState({}, element, {\n getAssetsState: this.#getAssetsState.bind(this),\n getAccountByAddress: this.#getAccountByAddress.bind(this),\n getSelectedAccount: this.#getSelectedAccount.bind(this),\n listAccounts: this.#listAccounts.bind(this),\n snapOwnsAccount: (account: InternalAccount) =>\n snapOwnsAccount(snapId, account),\n });\n\n this.update((draftState) => {\n // @ts-expect-error - TS2589: Type instantiation is excessively deep and\n // possibly infinite.\n draftState.interfaces[id] = {\n snapId,\n content: castDraft(element),\n state: componentState,\n context: context ?? null,\n contentType: contentType ?? null,\n };\n });\n\n return id;\n }\n\n /**\n * Get the data of a given interface id.\n *\n * @param snapId - The snap id requesting the interface data.\n * @param id - The interface id.\n * @returns The interface state.\n */\n getInterface(snapId: SnapId, id: string) {\n this.#validateArgs(snapId, id);\n\n return this.state.interfaces[id];\n }\n\n /**\n * Update the interface with the given content.\n *\n * @param snapId - The snap id requesting the update.\n * @param id - The interface id.\n * @param content - The new content.\n * @param context - An optional interface context object.\n */\n async updateInterface(\n snapId: SnapId,\n id: string,\n content: ComponentOrElement,\n context?: InterfaceContext,\n ) {\n this.#validateArgs(snapId, id);\n const element = getJsxInterface(content);\n await this.#validateContent(element);\n validateInterfaceContext(context);\n\n const oldState = this.state.interfaces[id].state;\n const newState = constructState(oldState, element, {\n getAssetsState: this.#getAssetsState.bind(this),\n getAccountByAddress: this.#getAccountByAddress.bind(this),\n getSelectedAccount: this.#getSelectedAccount.bind(this),\n listAccounts: this.#listAccounts.bind(this),\n snapOwnsAccount: (account: InternalAccount) =>\n snapOwnsAccount(snapId, account),\n });\n\n this.update((draftState) => {\n draftState.interfaces[id].state = newState;\n draftState.interfaces[id].content = castDraft(element);\n if (context) {\n draftState.interfaces[id].context = context;\n }\n });\n }\n\n /**\n * Delete an interface from state.\n *\n * @param id - The interface id.\n */\n deleteInterface(id: string) {\n this.update((draftState) => {\n delete draftState.interfaces[id];\n });\n }\n\n /**\n * Update the interface state.\n *\n * @param id - The interface id.\n * @param state - The new state.\n */\n updateInterfaceState(id: string, state: InterfaceState) {\n this.update((draftState) => {\n draftState.interfaces[id].state = state;\n });\n }\n\n /**\n * Resolve the promise of a given interface approval request.\n * The approval needs to have the same ID as the interface.\n *\n * @param snapId - The snap id.\n * @param id - The interface id.\n * @param value - The value to resolve the promise with.\n */\n async resolveInterface(snapId: SnapId, id: string, value: Json) {\n this.#validateArgs(snapId, id);\n this.#validateApproval(id);\n\n await this.#acceptApprovalRequest(id, value);\n\n this.deleteInterface(id);\n }\n\n /**\n * Utility function to validate the args passed to the other methods.\n *\n * @param snapId - The snap id.\n * @param id - The interface id.\n */\n #validateArgs(snapId: SnapId, id: string) {\n const existingInterface = this.state.interfaces[id];\n\n assert(\n existingInterface !== undefined,\n `Interface with id '${id}' not found.`,\n );\n assert(\n existingInterface.snapId === snapId,\n `Interface not created by ${snapId}.`,\n );\n }\n\n /**\n * Utility function to validate that the approval request exists.\n *\n * @param id - The interface id.\n */\n #validateApproval(id: string) {\n assert(\n this.#hasApprovalRequest(id),\n `Approval request with id '${id}' not found.`,\n );\n }\n\n /**\n * Check an origin against the phishing list.\n *\n * @param origin - The origin to check.\n * @returns True if the origin is on the phishing list, otherwise false.\n */\n #checkPhishingList(origin: string) {\n return this.messagingSystem.call('PhishingController:testOrigin', origin)\n .result;\n }\n\n /**\n * Check if an approval request exists for a given interface by looking up\n * if the ApprovalController has a request with the given interface ID.\n *\n * @param id - The interface id.\n * @returns True if an approval request exists, otherwise false.\n */\n #hasApprovalRequest(id: string) {\n return this.messagingSystem.call('ApprovalController:hasRequest', {\n id,\n });\n }\n\n /**\n * Accept an approval request for a given interface.\n *\n * @param id - The interface id.\n * @param value - The value to resolve the promise with.\n */\n async #acceptApprovalRequest(id: string, value: Json) {\n await this.messagingSystem.call(\n 'ApprovalController:acceptRequest',\n id,\n value,\n );\n }\n\n /**\n * Get the selected account in the client.\n *\n * @returns The selected account.\n */\n #getSelectedAccount() {\n return this.messagingSystem.call(\n 'AccountsController:getSelectedMultichainAccount',\n );\n }\n\n /**\n * Get a list of accounts for the given chain IDs.\n *\n * @param chainIds - The chain IDs to get the accounts for.\n * @returns The list of accounts.\n */\n #listAccounts(chainIds?: CaipChainId[]) {\n const accounts = this.messagingSystem.call(\n 'AccountsController:listMultichainAccounts',\n );\n\n if (!chainIds || chainIds.length === 0) {\n return accounts;\n }\n\n return accounts.filter((account) =>\n account.scopes.some((scope) => isMatchingChainId(scope, chainIds)),\n );\n }\n\n /**\n * Get an account by its address.\n *\n * @param address - The account address.\n * @returns The account or undefined if not found.\n */\n #getAccountByAddress(address: CaipAccountId) {\n const { address: parsedAddress } = parseCaipAccountId(address);\n\n return this.messagingSystem.call(\n 'AccountsController:getAccountByAddress',\n parsedAddress,\n );\n }\n\n /**\n * Get the MultichainAssetsController state.\n *\n * @returns The MultichainAssetsController state.\n */\n #getAssetsState() {\n return this.messagingSystem.call('MultichainAssetsController:getState');\n }\n\n /**\n * Get a snap by its id.\n *\n * @param id - The snap id.\n * @returns The snap.\n */\n #getSnap(id: string) {\n return this.messagingSystem.call('SnapController:get', id);\n }\n\n /**\n * Utility function to validate the components of an interface.\n * Throws if something is invalid.\n *\n * @param element - The JSX element to verify.\n */\n async #validateContent(element: JSXElement) {\n // We assume the validity of this JSON to be validated by the caller.\n // E.g., in the RPC method implementation.\n const size = getJsonSizeUnsafe(element);\n assert(\n size <= MAX_UI_CONTENT_SIZE,\n `A Snap UI may not be larger than ${MAX_UI_CONTENT_SIZE / 1000000} MB.`,\n );\n\n validateJsxElements(element, {\n isOnPhishingList: this.#checkPhishingList.bind(this),\n getSnap: this.#getSnap.bind(this),\n getAccountByAddress: this.#getAccountByAddress.bind(this),\n });\n }\n\n #onNotificationsListUpdated(notificationsList: Notification[]) {\n const snapNotificationsWithInterface = notificationsList.filter(\n (notification) => {\n return (\n notification.type === 'snap' &&\n hasProperty((notification as SnapNotification).data, 'detailedView')\n );\n },\n );\n\n const interfaceIdSet = new Set(\n snapNotificationsWithInterface.map(\n (notification) =>\n (\n (notification as SnapNotification)\n .data as ExpandedSnapNotificationData\n ).detailedView.interfaceId,\n ),\n );\n\n this.update((state) => {\n Object.entries(state.interfaces).forEach(([id, snapInterface]) => {\n if (\n snapInterface.contentType === ContentType.Notification &&\n !interfaceIdSet.has(id)\n ) {\n delete state.interfaces[id];\n }\n });\n });\n }\n}\n"]}
1
+ {"version":3,"file":"SnapInterfaceController.cjs","sourceRoot":"","sources":["../../src/interface/SnapInterfaceController.ts"],"names":[],"mappings":";;;AASA,+DAA2D;AAS3D,mDAAkD;AAGlD,uDAI+B;AAO/B,2CAA0E;AAC1E,iCAAkC;AAClC,mCAAgC;AAEhC,uCAKiB;AAGjB,MAAM,mBAAmB,GAAG,QAAU,CAAC,CAAC,QAAQ;AAEhD,MAAM,cAAc,GAAG,yBAAyB,CAAC;AAiJjD;;GAEG;AACH,MAAa,uBAAwB,SAAQ,gCAI5C;IACC,YAAY,EAAE,SAAS,EAAE,KAAK,EAA+B;QAC3D,KAAK,CAAC;YACJ,SAAS;YACT,QAAQ,EAAE;gBACR,UAAU,EAAE;oBACV,kBAAkB,EAAE,IAAI;oBACxB,OAAO,EAAE,CAAC,UAA2C,EAAE,EAAE;wBACvD,OAAO,MAAM,CAAC,O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,MAAM;gBAC5B,IAAA,mBAAW,EAAE,YAAiC,CAAC,IAAI,EAAE,cAAc,CAAC,CACrE,CAAC;QACJ,CAAC,CACF,CAAC;QAEF,MAAM,cAAc,GAAG,IAAI,GAAG,CAC5B,8BAA8B,CAAC,GAAG,CAChC,CAAC,YAAY,EAAE,EAAE,CAEZ,YAAiC;aAC/B,IACJ,CAAC,YAAY,CAAC,WAAW,CAC7B,CACF,CAAC;QAEF,IAAI,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE;YACpB,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,EAAE,aAAa,CAAC,EAAE,EAAE;gBAC/D,IACE,aAAa,CAAC,WAAW,KAAK,uBAAW,CAAC,YAAY;oBACtD,CAAC,cAAc,CAAC,GAAG,CAAC,EAAE,CAAC,EACvB,CAAC;oBACD,OAAO,KAAK,CAAC,UAAU,CAAC,EAAE,CAAC,CAAC;gBAC9B,CAAC;YACH,CAAC,CAAC,CAAC;QACL,CAAC,CAAC,CAAC;IACL,CAAC;CACF;AA9YD,0DA8YC","sourcesContent":["import type {\n AcceptRequest,\n HasApprovalRequest,\n} from '@metamask/approval-controller';\nimport type {\n RestrictedMessenger,\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n} from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport type { TestOrigin } from '@metamask/phishing-controller';\nimport type {\n InterfaceState,\n SnapId,\n ComponentOrElement,\n InterfaceContext,\n FungibleAssetMetadata,\n} from '@metamask/snaps-sdk';\nimport { ContentType } from '@metamask/snaps-sdk';\nimport type { JSXElement } from '@metamask/snaps-sdk/jsx';\nimport type { InternalAccount } from '@metamask/snaps-utils';\nimport {\n getJsonSizeUnsafe,\n snapOwnsAccount,\n validateJsxElements,\n} from '@metamask/snaps-utils';\nimport type {\n CaipAccountId,\n CaipAssetType,\n CaipChainId,\n Json,\n} from '@metamask/utils';\nimport { assert, hasProperty, parseCaipAccountId } from '@metamask/utils';\nimport { castDraft } from 'immer';\nimport { nanoid } from 'nanoid';\n\nimport {\n constructState,\n getJsxInterface,\n isMatchingChainId,\n validateInterfaceContext,\n} from './utils';\nimport type { GetSnap } from '../snaps';\n\nconst MAX_UI_CONTENT_SIZE = 10_000_000; // 10 mb\n\nconst controllerName = 'SnapInterfaceController';\n\nexport type CreateInterface = {\n type: `${typeof controllerName}:createInterface`;\n handler: SnapInterfaceController['createInterface'];\n};\n\nexport type GetInterface = {\n type: `${typeof controllerName}:getInterface`;\n handler: SnapInterfaceController['getInterface'];\n};\n\nexport type UpdateInterface = {\n type: `${typeof controllerName}:updateInterface`;\n handler: SnapInterfaceController['updateInterface'];\n};\n\nexport type DeleteInterface = {\n type: `${typeof controllerName}:deleteInterface`;\n handler: SnapInterfaceController['deleteInterface'];\n};\n\nexport type UpdateInterfaceState = {\n type: `${typeof controllerName}:updateInterfaceState`;\n handler: SnapInterfaceController['updateInterfaceState'];\n};\n\nexport type ResolveInterface = {\n type: `${typeof controllerName}:resolveInterface`;\n handler: SnapInterfaceController['resolveInterface'];\n};\n\ntype AccountsControllerGetAccountByAddressAction = {\n type: `AccountsController:getAccountByAddress`;\n handler: (address: string) => InternalAccount | undefined;\n};\n\ntype AccountsControllerGetSelectedMultichainAccountAction = {\n type: `AccountsController:getSelectedMultichainAccount`;\n handler: () => InternalAccount;\n};\n\ntype AccountsControllerListMultichainAccountsAction = {\n type: `AccountsController:listMultichainAccounts`;\n handler: (chainId?: CaipChainId) => InternalAccount[];\n};\n\nexport type SnapInterfaceControllerGetStateAction = ControllerGetStateAction<\n typeof controllerName,\n SnapInterfaceControllerState\n>;\n\ntype MultichainAssetsControllerGetStateAction = ControllerGetStateAction<\n 'MultichainAssetsController',\n {\n assetsMetadata: {\n [asset: CaipAssetType]: FungibleAssetMetadata;\n };\n accountsAssets: { [account: string]: CaipAssetType[] };\n }\n>;\n\nexport type SnapInterfaceControllerAllowedActions =\n | TestOrigin\n | HasApprovalRequest\n | AcceptRequest\n | GetSnap\n | MultichainAssetsControllerGetStateAction\n | AccountsControllerGetSelectedMultichainAccountAction\n | AccountsControllerGetAccountByAddressAction\n | AccountsControllerListMultichainAccountsAction;\n\nexport type SnapInterfaceControllerActions =\n | CreateInterface\n | GetInterface\n | UpdateInterface\n | DeleteInterface\n | UpdateInterfaceState\n | ResolveInterface\n | SnapInterfaceControllerGetStateAction;\n\nexport type SnapInterfaceControllerStateChangeEvent =\n ControllerStateChangeEvent<\n typeof controllerName,\n SnapInterfaceControllerState\n >;\n\ntype OtherNotification = { type: string; [key: string]: unknown };\n\nexport type ExpandedView = {\n title: string;\n interfaceId: string;\n footerLink?: { href: string; text: string };\n};\n\ntype NormalSnapNotificationData = { message: string; origin: string };\n\ntype ExpandedSnapNotificationData = {\n message: string;\n origin: string;\n detailedView: ExpandedView;\n};\n\ntype SnapNotification = {\n type: 'snap';\n data: NormalSnapNotificationData | ExpandedSnapNotificationData;\n readDate: string | null;\n};\n\ntype Notification = OtherNotification | SnapNotification;\n\ntype NotificationListUpdatedEvent = {\n type: 'NotificationServicesController:notificationsListUpdated';\n payload: [Notification[]];\n};\n\nexport type SnapInterfaceControllerEvents =\n | SnapInterfaceControllerStateChangeEvent\n | NotificationListUpdatedEvent;\n\nexport type SnapInterfaceControllerMessenger = RestrictedMessenger<\n typeof controllerName,\n SnapInterfaceControllerActions | SnapInterfaceControllerAllowedActions,\n SnapInterfaceControllerEvents,\n SnapInterfaceControllerAllowedActions['type'],\n SnapInterfaceControllerEvents['type']\n>;\n\nexport type StoredInterface = {\n snapId: SnapId;\n content: JSXElement;\n state: InterfaceState;\n context: InterfaceContext | null;\n contentType: ContentType | null;\n};\n\nexport type SnapInterfaceControllerState = {\n interfaces: Record<string, StoredInterface>;\n};\n\nexport type SnapInterfaceControllerArgs = {\n messenger: SnapInterfaceControllerMessenger;\n state?: SnapInterfaceControllerState;\n};\n\n/**\n * Use this controller to manage snaps UI interfaces using RPC method hooks.\n */\nexport class SnapInterfaceController extends BaseController<\n typeof controllerName,\n SnapInterfaceControllerState,\n SnapInterfaceControllerMessenger\n> {\n constructor({ messenger, state }: SnapInterfaceControllerArgs) {\n super({\n messenger,\n metadata: {\n interfaces: {\n includeInStateLogs: true,\n persist: (interfaces: Record<string, StoredInterface>) => {\n return Object.entries(interfaces).reduce<\n Record<string, StoredInterface>\n >((persistedInterfaces, [id, snapInterface]) => {\n switch (snapInterface.contentType) {\n case ContentType.Notification:\n persistedInterfaces[id] = snapInterface;\n return persistedInterfaces;\n default:\n return persistedInterfaces;\n }\n }, {});\n },\n anonymous: false,\n usedInUi: true,\n },\n },\n name: controllerName,\n state: { interfaces: {}, ...state },\n });\n\n this.messagingSystem.subscribe(\n 'NotificationServicesController:notificationsListUpdated',\n this.#onNotificationsListUpdated.bind(this),\n );\n\n this.#registerMessageHandlers();\n }\n\n /**\n * Constructor helper for registering this controller's messaging system\n * actions.\n */\n #registerMessageHandlers() {\n this.messagingSystem.registerActionHandler(\n `${controllerName}:createInterface`,\n this.createInterface.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:getInterface`,\n this.getInterface.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:updateInterface`,\n this.updateInterface.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:deleteInterface`,\n this.deleteInterface.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:updateInterfaceState`,\n this.updateInterfaceState.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:resolveInterface`,\n this.resolveInterface.bind(this),\n );\n }\n\n /**\n * Create an interface in the controller state with the associated data.\n *\n * @param snapId - The snap id that created the interface.\n * @param content - The interface content.\n * @param context - An optional interface context object.\n * @param contentType - The type of content.\n * @returns The newly interface id.\n */\n createInterface(\n snapId: SnapId,\n content: ComponentOrElement,\n context?: InterfaceContext,\n contentType?: ContentType,\n ) {\n const element = getJsxInterface(content);\n this.#validateContent(element);\n validateInterfaceContext(context);\n\n const id = nanoid();\n const componentState = constructState({}, element, {\n getAssetsState: this.#getAssetsState.bind(this),\n getAccountByAddress: this.#getAccountByAddress.bind(this),\n getSelectedAccount: this.#getSelectedAccount.bind(this),\n listAccounts: this.#listAccounts.bind(this),\n snapOwnsAccount: (account: InternalAccount) =>\n snapOwnsAccount(snapId, account),\n });\n\n this.update((draftState) => {\n // @ts-expect-error - TS2589: Type instantiation is excessively deep and\n // possibly infinite.\n draftState.interfaces[id] = {\n snapId,\n content: castDraft(element),\n state: componentState,\n context: context ?? null,\n contentType: contentType ?? null,\n };\n });\n\n return id;\n }\n\n /**\n * Get the data of a given interface id.\n *\n * @param snapId - The snap id requesting the interface data.\n * @param id - The interface id.\n * @returns The interface state.\n */\n getInterface(snapId: SnapId, id: string) {\n this.#validateArgs(snapId, id);\n\n return this.state.interfaces[id];\n }\n\n /**\n * Update the interface with the given content.\n *\n * @param snapId - The snap id requesting the update.\n * @param id - The interface id.\n * @param content - The new content.\n * @param context - An optional interface context object.\n */\n updateInterface(\n snapId: SnapId,\n id: string,\n content: ComponentOrElement,\n context?: InterfaceContext,\n ) {\n this.#validateArgs(snapId, id);\n const element = getJsxInterface(content);\n this.#validateContent(element);\n validateInterfaceContext(context);\n\n const oldState = this.state.interfaces[id].state;\n const newState = constructState(oldState, element, {\n getAssetsState: this.#getAssetsState.bind(this),\n getAccountByAddress: this.#getAccountByAddress.bind(this),\n getSelectedAccount: this.#getSelectedAccount.bind(this),\n listAccounts: this.#listAccounts.bind(this),\n snapOwnsAccount: (account: InternalAccount) =>\n snapOwnsAccount(snapId, account),\n });\n\n this.update((draftState) => {\n draftState.interfaces[id].state = newState;\n draftState.interfaces[id].content = castDraft(element);\n if (context) {\n draftState.interfaces[id].context = context;\n }\n });\n }\n\n /**\n * Delete an interface from state.\n *\n * @param id - The interface id.\n */\n deleteInterface(id: string) {\n this.update((draftState) => {\n delete draftState.interfaces[id];\n });\n }\n\n /**\n * Update the interface state.\n *\n * @param id - The interface id.\n * @param state - The new state.\n */\n updateInterfaceState(id: string, state: InterfaceState) {\n this.update((draftState) => {\n draftState.interfaces[id].state = state;\n });\n }\n\n /**\n * Resolve the promise of a given interface approval request.\n * The approval needs to have the same ID as the interface.\n *\n * @param snapId - The snap id.\n * @param id - The interface id.\n * @param value - The value to resolve the promise with.\n */\n async resolveInterface(snapId: SnapId, id: string, value: Json) {\n this.#validateArgs(snapId, id);\n this.#validateApproval(id);\n\n await this.#acceptApprovalRequest(id, value);\n\n this.deleteInterface(id);\n }\n\n /**\n * Utility function to validate the args passed to the other methods.\n *\n * @param snapId - The snap id.\n * @param id - The interface id.\n */\n #validateArgs(snapId: SnapId, id: string) {\n const existingInterface = this.state.interfaces[id];\n\n assert(\n existingInterface !== undefined,\n `Interface with id '${id}' not found.`,\n );\n assert(\n existingInterface.snapId === snapId,\n `Interface not created by ${snapId}.`,\n );\n }\n\n /**\n * Utility function to validate that the approval request exists.\n *\n * @param id - The interface id.\n */\n #validateApproval(id: string) {\n assert(\n this.#hasApprovalRequest(id),\n `Approval request with id '${id}' not found.`,\n );\n }\n\n /**\n * Check an origin against the phishing list.\n *\n * @param origin - The origin to check.\n * @returns True if the origin is on the phishing list, otherwise false.\n */\n #checkPhishingList(origin: string) {\n return this.messagingSystem.call('PhishingController:testOrigin', origin)\n .result;\n }\n\n /**\n * Check if an approval request exists for a given interface by looking up\n * if the ApprovalController has a request with the given interface ID.\n *\n * @param id - The interface id.\n * @returns True if an approval request exists, otherwise false.\n */\n #hasApprovalRequest(id: string) {\n return this.messagingSystem.call('ApprovalController:hasRequest', {\n id,\n });\n }\n\n /**\n * Accept an approval request for a given interface.\n *\n * @param id - The interface id.\n * @param value - The value to resolve the promise with.\n */\n async #acceptApprovalRequest(id: string, value: Json) {\n await this.messagingSystem.call(\n 'ApprovalController:acceptRequest',\n id,\n value,\n );\n }\n\n /**\n * Get the selected account in the client.\n *\n * @returns The selected account.\n */\n #getSelectedAccount() {\n return this.messagingSystem.call(\n 'AccountsController:getSelectedMultichainAccount',\n );\n }\n\n /**\n * Get a list of accounts for the given chain IDs.\n *\n * @param chainIds - The chain IDs to get the accounts for.\n * @returns The list of accounts.\n */\n #listAccounts(chainIds?: CaipChainId[]) {\n const accounts = this.messagingSystem.call(\n 'AccountsController:listMultichainAccounts',\n );\n\n if (!chainIds || chainIds.length === 0) {\n return accounts;\n }\n\n return accounts.filter((account) =>\n account.scopes.some((scope) => isMatchingChainId(scope, chainIds)),\n );\n }\n\n /**\n * Get an account by its address.\n *\n * @param address - The account address.\n * @returns The account or undefined if not found.\n */\n #getAccountByAddress(address: CaipAccountId) {\n const { address: parsedAddress } = parseCaipAccountId(address);\n\n return this.messagingSystem.call(\n 'AccountsController:getAccountByAddress',\n parsedAddress,\n );\n }\n\n /**\n * Get the MultichainAssetsController state.\n *\n * @returns The MultichainAssetsController state.\n */\n #getAssetsState() {\n return this.messagingSystem.call('MultichainAssetsController:getState');\n }\n\n /**\n * Get a snap by its id.\n *\n * @param id - The snap id.\n * @returns The snap.\n */\n #getSnap(id: string) {\n return this.messagingSystem.call('SnapController:get', id);\n }\n\n /**\n * Utility function to validate the components of an interface.\n * Throws if something is invalid.\n *\n * @param element - The JSX element to verify.\n */\n #validateContent(element: JSXElement) {\n // We assume the validity of this JSON to be validated by the caller.\n // E.g., in the RPC method implementation.\n const size = getJsonSizeUnsafe(element);\n assert(\n size <= MAX_UI_CONTENT_SIZE,\n `A Snap UI may not be larger than ${MAX_UI_CONTENT_SIZE / 1000000} MB.`,\n );\n\n validateJsxElements(element, {\n isOnPhishingList: this.#checkPhishingList.bind(this),\n getSnap: this.#getSnap.bind(this),\n getAccountByAddress: this.#getAccountByAddress.bind(this),\n });\n }\n\n #onNotificationsListUpdated(notificationsList: Notification[]) {\n const snapNotificationsWithInterface = notificationsList.filter(\n (notification) => {\n return (\n notification.type === 'snap' &&\n hasProperty((notification as SnapNotification).data, 'detailedView')\n );\n },\n );\n\n const interfaceIdSet = new Set(\n snapNotificationsWithInterface.map(\n (notification) =>\n (\n (notification as SnapNotification)\n .data as ExpandedSnapNotificationData\n ).detailedView.interfaceId,\n ),\n );\n\n this.update((state) => {\n Object.entries(state.interfaces).forEach(([id, snapInterface]) => {\n if (\n snapInterface.contentType === ContentType.Notification &&\n !interfaceIdSet.has(id)\n ) {\n delete state.interfaces[id];\n }\n });\n });\n }\n}\n"]}
@@ -119,7 +119,7 @@ export declare class SnapInterfaceController extends BaseController<typeof contr
119
119
  * @param contentType - The type of content.
120
120
  * @returns The newly interface id.
121
121
  */
122
- createInterface(snapId: SnapId, content: ComponentOrElement, context?: InterfaceContext, contentType?: ContentType): Promise<string>;
122
+ createInterface(snapId: SnapId, content: ComponentOrElement, context?: InterfaceContext, contentType?: ContentType): string;
123
123
  /**
124
124
  * Get the data of a given interface id.
125
125
  *
@@ -136,7 +136,7 @@ export declare class SnapInterfaceController extends BaseController<typeof contr
136
136
  * @param content - The new content.
137
137
  * @param context - An optional interface context object.
138
138
  */
139
- updateInterface(snapId: SnapId, id: string, content: ComponentOrElement, context?: InterfaceContext): Promise<void>;
139
+ updateInterface(snapId: SnapId, id: string, content: ComponentOrElement, context?: InterfaceContext): void;
140
140
  /**
141
141
  * Delete an interface from state.
142
142
  *
@@ -1 +1 @@
1
- {"version":3,"file":"SnapInterfaceController.d.cts","sourceRoot":"","sources":["../../src/interface/SnapInterfaceController.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,aAAa,EACb,kBAAkB,EACnB,sCAAsC;AACvC,OAAO,KAAK,EACV,mBAAmB,EACnB,wBAAwB,EACxB,0BAA0B,EAC3B,kCAAkC;AACnC,OAAO,EAAE,cAAc,EAAE,kCAAkC;AAC3D,OAAO,KAAK,EAAE,UAAU,EAAE,sCAAsC;AAChE,OAAO,KAAK,EACV,cAAc,EACd,MAAM,EACN,kBAAkB,EAClB,gBAAgB,EAChB,qBAAqB,EACtB,4BAA4B;AAC7B,OAAO,EAAE,WAAW,EAAE,4BAA4B;AA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CAAC;IAC5C,KAAK,CAAC,EAAE,4BAA4B,CAAC;CACtC,CAAC;AAEF;;GAEG;AACH,qBAAa,uBAAwB,SAAQ,cAAc,CACzD,OAAO,cAAc,EACrB,4BAA4B,EAC5B,gCAAgC,CACjC;;gBACa,EAAE,SAAS,EAAE,KAAK,EAAE,EAAE,2BAA2B;IAqE7D;;;;;;;;OAQG;IACG,eAAe,CACnB,MAAM,EAAE,MAAM,EACd,OAAO,EAAE,kBAAkB,EAC3B,OAAO,CAAC,EAAE,gBAAgB,EAC1B,WAAW,CAAC,EAAE,WAAW;IA+B3B;;;;;;OAMG;IACH,YAAY,CAAC,MAAM,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM;IAMvC;;;;;;;OAOG;IACG,eAAe,CACnB,MAAM,EAAE,MAAM,EACd,EAAE,EAAE,MAAM,EACV,OAAO,EAAE,kBAAkB,EAC3B,OAAO,CAAC,EAAE,gBAAgB;IA0B5B;;;;OAIG;IACH,eAAe,CAAC,EAAE,EAAE,MAAM;IAM1B;;;;;OAKG;IACH,oBAAoB,CAAC,EAAE,EAAE,MAAM,EAAE,KAAK,EAAE,cAAc;IAMtD;;;;;;;OAOG;IACG,gBAAgB,CAAC,MAAM,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,KAAK,EAAE,IAAI;CAoM/D"}
1
+ {"version":3,"file":"SnapInterfaceController.d.cts","sourceRoot":"","sources":["../../src/interface/SnapInterfaceController.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,aAAa,EACb,kBAAkB,EACnB,sCAAsC;AACvC,OAAO,KAAK,EACV,mBAAmB,EACnB,wBAAwB,EACxB,0BAA0B,EAC3B,kCAAkC;AACnC,OAAO,EAAE,cAAc,EAAE,kCAAkC;AAC3D,OAAO,KAAK,EAAE,UAAU,EAAE,sCAAsC;AAChE,OAAO,KAAK,EACV,cAAc,EACd,MAAM,EACN,kBAAkB,EAClB,gBAAgB,EAChB,qBAAqB,EACtB,4BAA4B;AAC7B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2B,GAAG;IACxC,SAAS,EAAE,gCAAgC,CAAC;IAC5C,KAAK,CAAC,EAAE,4BAA4B,CAAC;CACtC,CAAC;AAEF;;GAEG;AACH,qBAAa,uBAAwB,SAAQ,cAAc,CACzD,OAAO,cAAc,EACrB,4BAA4B,EAC5B,gCAAgC,CACjC;;gBACa,EAAE,SAAS,EAAE,KAAK,EAAE,EAAE,2BAA2B;IAuE7D;;;;;;;;OAQG;IACH,eAAe,CACb,MAAM,EAAE,MAAM,EACd,OAAO,EAAE,kBAAkB,EAC3B,OAAO,CAAC,EAAE,gBAAgB,EAC1B,WAAW,CAAC,EAAE,WAAW;IA+B3B;;;;;;OAMG;IACH,YAAY,CAAC,MAAM,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM;IAMvC;;;;;;;OAOG;IACH,eAAe,CACb,MAAM,EAAE,MAAM,EACd,EAAE,EAAE,MAAM,EACV,OAAO,EAAE,kBAAkB,EAC3B,OAAO,CAAC,EAAE,gBAAgB;IA0B5B;;;;OAIG;IACH,eAAe,CAAC,EAAE,EAAE,MAAM;IAM1B;;;;;OAKG;IACH,oBAAoB,CAAC,EAAE,EAAE,MAAM,EAAE,KAAK,EAAE,cAAc;IAMtD;;;;;;;OAOG;IACG,gBAAgB,CAAC,MAAM,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,KAAK,EAAE,IAAI;CAoM/D"}
@@ -119,7 +119,7 @@ export declare class SnapInterfaceController extends BaseController<typeof contr
119
119
  * @param contentType - The type of content.
120
120
  * @returns The newly interface id.
121
121
  */
122
- createInterface(snapId: SnapId, content: ComponentOrElement, context?: InterfaceContext, contentType?: ContentType): Promise<string>;
122
+ createInterface(snapId: SnapId, content: ComponentOrElement, context?: InterfaceContext, contentType?: ContentType): string;
123
123
  /**
124
124
  * Get the data of a given interface id.
125
125
  *
@@ -136,7 +136,7 @@ export declare class SnapInterfaceController extends BaseController<typeof contr
136
136
  * @param content - The new content.
137
137
  * @param context - An optional interface context object.
138
138
  */
139
- updateInterface(snapId: SnapId, id: string, content: ComponentOrElement, context?: InterfaceContext): Promise<void>;
139
+ updateInterface(snapId: SnapId, id: string, content: ComponentOrElement, context?: InterfaceContext): void;
140
140
  /**
141
141
  * Delete an interface from state.
142
142
  *
@@ -1 +1 @@
1
- {"version":3,"file":"SnapInterfaceController.d.mts","sourceRoot":"","sources":["../../src/interface/SnapInterfaceController.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,aAAa,EACb,kBAAkB,EACnB,sCAAsC;AACvC,OAAO,KAAK,EACV,mBAAmB,EACnB,wBAAwB,EACxB,0BAA0B,EAC3B,kCAAkC;AACnC,OAAO,EAAE,cAAc,EAAE,kCAAkC;AAC3D,OAAO,KAAK,EAAE,UAAU,EAAE,sCAAsC;AAChE,OAAO,KAAK,EACV,cAAc,EACd,MAAM,EACN,kBAAkB,EAClB,gBAAgB,EAChB,qBAAqB,EACtB,4BAA4B;AAC7B,OAAO,EAAE,WAAW,EAAE,4BAA4B;AAClD,OAAO,KAAK,EAAE,UAAU,EAAE,gCAAgC;AAC1D,OAAO,KAAK,EAAE,eAAe,EAAE,8BAA8B;AAM7D,OAAO,KAAK,EAEV,aAAa,EACb,WAAW,EACX,IAAI,EACL,wBAAwB;AAWzB,OAAO,KAAK,EAAE,OAAO,EAAE,2BAAiB;AAIxC,QAAA,MAAM,cAAc,4BAA4B,CAAC;AAEjD,MAAM,MAAM,eAAe,GAAG;IAC5B,IAAI,EAAE,GAAG,OAAO,cAAc,kBAAkB,CAAC;IACjD,OAAO,EAAE,uBAAuB,CAAC,iBAAiB,CAAC,CAAC;CACrD,CAAC;AAEF,MAAM,MAAM,YAAY,GAAG;IACzB,IAAI,EAAE,GAAG,OAAO,cAAc,eAAe,CAAC;IAC9C,OAAO,EAAE,uBAAuB,CAAC,cAAc,CAAC,CAAC;CAClD,CAAC;AAEF,MAAM,MAAM,eAAe,GAAG;IAC5B,IAAI,EAAE,GAAG,OAAO,cAAc,kBAAkB,CAAC;IACjD,O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AE,MAAM;IAM1B;;;;;OAKG;IACH,oBAAoB,CAAC,EAAE,EAAE,MAAM,EAAE,KAAK,EAAE,cAAc;IAMtD;;;;;;;OAOG;IACG,gBAAgB,CAAC,MAAM,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,KAAK,EAAE,IAAI;CAoM/D"}
1
+ {"version":3,"file":"SnapInterfaceController.d.mts","sourceRoot":"","sources":["../../src/interface/SnapInterfaceController.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,aAAa,EACb,kBAAkB,EACnB,sCAAsC;AACvC,OAAO,KAAK,EACV,mBAAmB,EACnB,wBAAwB,EACxB,0BAA0B,EAC3B,kCAAkC;AACnC,OAAO,EAAE,cAAc,EAAE,kCAAkC;AAC3D,OAAO,KAAK,EAAE,UAAU,EAAE,sCAAsC;AAChE,OAAO,KAAK,EACV,cAAc,EACd,MAAM,EACN,kBAAkB,EAClB,gBAAgB,EAChB,qBAAqB,EACtB,4BAA4B;AAC7B,OAAO,EAAE,WAAW,EAAE,4BAA4B;AAClD,OAAO,KAAK,EAAE,UAAU,EAAE,gCAAgC;AAC1D,OAAO,KAAK,EAAE,eAAe,EAAE,8BAA8B;AAM7D,OAAO,KAAK,EAEV,aAAa,EACb,WAAW,EACX,IAAI,EACL,wBAAwB;AAWzB,OAAO,KAAK,EAAE,OAAO,EAAE,2BAAiB;AAIxC,QAAA,MAAM,cAAc,4BAA4B,CAAC;AAEjD,MAAM,MAAM,eAAe,GAAG;IAC5B,IAAI,EAAE,GAAG,OAAO,cAAc,kBAAkB,CAAC;IACjD,OAAO,EAAE,uBAAuB,CAAC,iBAAiB,CAAC,CAAC;CACrD,CAAC;AAEF,MAAM,MAAM,YAAY,GAAG;IACzB,IAAI,EAAE,GAAG,OAAO,cAAc,eAAe,CAAC;IAC9C,OAAO,EAAE,uBAAuB,CAAC,cAAc,CAAC,CAAC;CAClD,CAAC;AAEF,MAAM,MAAM,eAAe,GAAG;IAC5B,IAAI,EAAE,GAA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;;OAIG;IACH,eAAe,CAAC,EAAE,EAAE,MAAM;IAM1B;;;;;OAKG;IACH,oBAAoB,CAAC,EAAE,EAAE,MAAM,EAAE,KAAK,EAAE,cAAc;IAMtD;;;;;;;OAOG;IACG,gBAAgB,CAAC,MAAM,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,KAAK,EAAE,IAAI;CAoM/D"}
@@ -16,6 +16,7 @@ export class SnapInterfaceController extends BaseController {
16
16
  messenger,
17
17
  metadata: {
18
18
  interfaces: {
19
+ includeInStateLogs: true,
19
20
  persist: (interfaces) => {
20
21
  return Object.entries(interfaces).reduce((persistedInterfaces, [id, snapInterface]) => {
21
22
  switch (snapInterface.contentType) {
@@ -28,6 +29,7 @@ export class SnapInterfaceController extends BaseController {
28
29
  }, {});
29
30
  },
30
31
  anonymous: false,
32
+ usedInUi: true,
31
33
  },
32
34
  },
33
35
  name: controllerName,
@@ -57,9 +59,9 @@ export class SnapInterfaceController extends BaseController {
57
59
  * @param contentType - The type of content.
58
60
  * @returns The newly interface id.
59
61
  */
60
- async createInterface(snapId, content, context, contentType) {
62
+ createInterface(snapId, content, context, contentType) {
61
63
  const element = getJsxInterface(content);
62
- await this.#validateContent(element);
64
+ this.#validateContent(element);
63
65
  validateInterfaceContext(context);
64
66
  const id = nanoid();
65
67
  const componentState = constructState({}, element, {
@@ -101,10 +103,10 @@ export class SnapInterfaceController extends BaseController {
101
103
  * @param content - The new content.
102
104
  * @param context - An optional interface context object.
103
105
  */
104
- async updateInterface(snapId, id, content, context) {
106
+ updateInterface(snapId, id, content, context) {
105
107
  this.#validateArgs(snapId, id);
106
108
  const element = getJsxInterface(content);
107
- await this.#validateContent(element);
109
+ this.#validateContent(element);
108
110
  validateInterfaceContext(context);
109
111
  const oldState = this.state.interfaces[id].state;
110
112
  const newState = constructState(oldState, element, {
@@ -261,7 +263,7 @@ export class SnapInterfaceController extends BaseController {
261
263
  *
262
264
  * @param element - The JSX element to verify.
263
265
  */
264
- async #validateContent(element) {
266
+ #validateContent(element) {
265
267
  // We assume the validity of this JSON to be validated by the caller.
266
268
  // E.g., in the RPC method implementation.
267
269
  const size = getJsonSizeUnsafe(element);
@@ -1 +1 @@
1
- {"version":3,"file":"SnapInterfaceController.mjs","sourceRoot":"","sources":["../../src/interface/SnapInterfaceController.ts"],"names":[],"mappings":"AASA,OAAO,EAAE,cAAc,EAAE,kCAAkC;AAS3D,OAAO,EAAE,WAAW,EAAE,4BAA4B;AAGlD,OAAO,EACL,iBAAiB,EACjB,eAAe,EACf,mBAAmB,EACpB,8BAA8B;AAO/B,OAAO,EAAE,MAAM,EAAE,WAAW,EAAE,kBAAkB,EAAE,wBAAwB;AAC1E,OAAO,EAAE,SAAS,EAAE,cAAc;AAClC,OAAO,EAAE,MAAM,EAAE,eAAe;AAEhC,OAAO,EACL,cAAc,EACd,eAAe,EACf,iBAAiB,EACjB,wBAAwB,EACzB,oBAAgB;AAGjB,MAAM,mBAAmB,GAAG,QAAU,CAAC,CAAC,QAAQ;AAEhD,MAAM,cAAc,GAAG,yBAAyB,CAAC;AAiJjD;;GAEG;AACH,MAAM,OAAO,uBAAwB,SAAQ,cAI5C;IACC,YAAY,EAAE,SAAS,EAAE,KAAK,EAA+B;QAC3D,KAAK,CAAC;YACJ,SAAS;YACT,QAAQ,EAAE;gBACR,UAAU,EAAE;oBACV,OAAO,EAAE,CAAC,UAA2C,EAAE,EAAE;wBACvD,OAAO,MAAM,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC,MAAM,CAEtC,CAAC,mBAAmB,EAAE,CAAC,EAAE,EAAE,aAAa,CAAC,EAAE,EAAE;4BAC7C,QAAQ,aAAa,CAAC,WAAW,EAAE,CAAC;gCAClC,KAAK,WAAW,CAAC,YAAY;oCAC3B,mBAAmB,CAAC,EAAE,CAAC,GAAG,aAAa,CAAC;oCACxC,OAAO,mBAAmB,CAAC;gCAC7B;oCACE,OAAO,mBAAmB,CAAC;4BAC/B,CAAC;wBACH,CAAC,EAAE,EAAE,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gBAC/D,IACE,aAAa,CAAC,WAAW,KAAK,WAAW,CAAC,YAAY;oBACtD,CAAC,cAAc,CAAC,GAAG,CAAC,EAAE,CAAC,EACvB,CAAC;oBACD,OAAO,KAAK,CAAC,UAAU,CAAC,EAAE,CAAC,CAAC;gBAC9B,CAAC;YACH,CAAC,CAAC,CAAC;QACL,CAAC,CAAC,CAAC;IACL,CAAC;CACF","sourcesContent":["import type {\n AcceptRequest,\n HasApprovalRequest,\n} from '@metamask/approval-controller';\nimport type {\n RestrictedMessenger,\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n} from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport type { TestOrigin } from '@metamask/phishing-controller';\nimport type {\n InterfaceState,\n SnapId,\n ComponentOrElement,\n InterfaceContext,\n FungibleAssetMetadata,\n} from '@metamask/snaps-sdk';\nimport { ContentType } from '@metamask/snaps-sdk';\nimport type { JSXElement } from '@metamask/snaps-sdk/jsx';\nimport type { InternalAccount } from '@metamask/snaps-utils';\nimport {\n getJsonSizeUnsafe,\n snapOwnsAccount,\n validateJsxElements,\n} from '@metamask/snaps-utils';\nimport type {\n CaipAccountId,\n CaipAssetType,\n CaipChainId,\n Json,\n} from '@metamask/utils';\nimport { assert, hasProperty, parseCaipAccountId } from '@metamask/utils';\nimport { castDraft } from 'immer';\nimport { nanoid } from 'nanoid';\n\nimport {\n constructState,\n getJsxInterface,\n isMatchingChainId,\n validateInterfaceContext,\n} from './utils';\nimport type { GetSnap } from '../snaps';\n\nconst MAX_UI_CONTENT_SIZE = 10_000_000; // 10 mb\n\nconst controllerName = 'SnapInterfaceController';\n\nexport type CreateInterface = {\n type: `${typeof controllerName}:createInterface`;\n handler: SnapInterfaceController['createInterface'];\n};\n\nexport type GetInterface = {\n type: `${typeof controllerName}:getInterface`;\n handler: SnapInterfaceController['getInterface'];\n};\n\nexport type UpdateInterface = {\n type: `${typeof controllerName}:updateInterface`;\n handler: SnapInterfaceController['updateInterface'];\n};\n\nexport type DeleteInterface = {\n type: `${typeof controllerName}:deleteInterface`;\n handler: SnapInterfaceController['deleteInterface'];\n};\n\nexport type UpdateInterfaceState = {\n type: `${typeof controllerName}:updateInterfaceState`;\n handler: SnapInterfaceController['updateInterfaceState'];\n};\n\nexport type ResolveInterface = {\n type: `${typeof controllerName}:resolveInterface`;\n handler: SnapInterfaceController['resolveInterface'];\n};\n\ntype AccountsControllerGetAccountByAddressAction = {\n type: `AccountsController:getAccountByAddress`;\n handler: (address: string) => InternalAccount | undefined;\n};\n\ntype AccountsControllerGetSelectedMultichainAccountAction = {\n type: `AccountsController:getSelectedMultichainAccount`;\n handler: () => InternalAccount;\n};\n\ntype AccountsControllerListMultichainAccountsAction = {\n type: `AccountsController:listMultichainAccounts`;\n handler: (chainId?: CaipChainId) => InternalAccount[];\n};\n\nexport type SnapInterfaceControllerGetStateAction = ControllerGetStateAction<\n typeof controllerName,\n SnapInterfaceControllerState\n>;\n\ntype MultichainAssetsControllerGetStateAction = ControllerGetStateAction<\n 'MultichainAssetsController',\n {\n assetsMetadata: {\n [asset: CaipAssetType]: FungibleAssetMetadata;\n };\n accountsAssets: { [account: string]: CaipAssetType[] };\n }\n>;\n\nexport type SnapInterfaceControllerAllowedActions =\n | TestOrigin\n | HasApprovalRequest\n | AcceptRequest\n | GetSnap\n | MultichainAssetsControllerGetStateAction\n | AccountsControllerGetSelectedMultichainAccountAction\n | AccountsControllerGetAccountByAddressAction\n | AccountsControllerListMultichainAccountsAction;\n\nexport type SnapInterfaceControllerActions =\n | CreateInterface\n | GetInterface\n | UpdateInterface\n | DeleteInterface\n | UpdateInterfaceState\n | ResolveInterface\n | SnapInterfaceControllerGetStateAction;\n\nexport type SnapInterfaceControllerStateChangeEvent =\n ControllerStateChangeEvent<\n typeof controllerName,\n SnapInterfaceControllerState\n >;\n\ntype OtherNotification = { type: string; [key: string]: unknown };\n\nexport type ExpandedView = {\n title: string;\n interfaceId: string;\n footerLink?: { href: string; text: string };\n};\n\ntype NormalSnapNotificationData = { message: string; origin: string };\n\ntype ExpandedSnapNotificationData = {\n message: string;\n origin: string;\n detailedView: ExpandedView;\n};\n\ntype SnapNotification = {\n type: 'snap';\n data: NormalSnapNotificationData | ExpandedSnapNotificationData;\n readDate: string | null;\n};\n\ntype Notification = OtherNotification | SnapNotification;\n\ntype NotificationListUpdatedEvent = {\n type: 'NotificationServicesController:notificationsListUpdated';\n payload: [Notification[]];\n};\n\nexport type SnapInterfaceControllerEvents =\n | SnapInterfaceControllerStateChangeEvent\n | NotificationListUpdatedEvent;\n\nexport type SnapInterfaceControllerMessenger = RestrictedMessenger<\n typeof controllerName,\n SnapInterfaceControllerActions | SnapInterfaceControllerAllowedActions,\n SnapInterfaceControllerEvents,\n SnapInterfaceControllerAllowedActions['type'],\n SnapInterfaceControllerEvents['type']\n>;\n\nexport type StoredInterface = {\n snapId: SnapId;\n content: JSXElement;\n state: InterfaceState;\n context: InterfaceContext | null;\n contentType: ContentType | null;\n};\n\nexport type SnapInterfaceControllerState = {\n interfaces: Record<string, StoredInterface>;\n};\n\nexport type SnapInterfaceControllerArgs = {\n messenger: SnapInterfaceControllerMessenger;\n state?: SnapInterfaceControllerState;\n};\n\n/**\n * Use this controller to manage snaps UI interfaces using RPC method hooks.\n */\nexport class SnapInterfaceController extends BaseController<\n typeof controllerName,\n SnapInterfaceControllerState,\n SnapInterfaceControllerMessenger\n> {\n constructor({ messenger, state }: SnapInterfaceControllerArgs) {\n super({\n messenger,\n metadata: {\n interfaces: {\n persist: (interfaces: Record<string, StoredInterface>) => {\n return Object.entries(interfaces).reduce<\n Record<string, StoredInterface>\n >((persistedInterfaces, [id, snapInterface]) => {\n switch (snapInterface.contentType) {\n case ContentType.Notification:\n persistedInterfaces[id] = snapInterface;\n return persistedInterfaces;\n default:\n return persistedInterfaces;\n }\n }, {});\n },\n anonymous: false,\n },\n },\n name: controllerName,\n state: { interfaces: {}, ...state },\n });\n\n this.messagingSystem.subscribe(\n 'NotificationServicesController:notificationsListUpdated',\n this.#onNotificationsListUpdated.bind(this),\n );\n\n this.#registerMessageHandlers();\n }\n\n /**\n * Constructor helper for registering this controller's messaging system\n * actions.\n */\n #registerMessageHandlers() {\n this.messagingSystem.registerActionHandler(\n `${controllerName}:createInterface`,\n this.createInterface.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:getInterface`,\n this.getInterface.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:updateInterface`,\n this.updateInterface.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:deleteInterface`,\n this.deleteInterface.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:updateInterfaceState`,\n this.updateInterfaceState.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:resolveInterface`,\n this.resolveInterface.bind(this),\n );\n }\n\n /**\n * Create an interface in the controller state with the associated data.\n *\n * @param snapId - The snap id that created the interface.\n * @param content - The interface content.\n * @param context - An optional interface context object.\n * @param contentType - The type of content.\n * @returns The newly interface id.\n */\n async createInterface(\n snapId: SnapId,\n content: ComponentOrElement,\n context?: InterfaceContext,\n contentType?: ContentType,\n ) {\n const element = getJsxInterface(content);\n await this.#validateContent(element);\n validateInterfaceContext(context);\n\n const id = nanoid();\n const componentState = constructState({}, element, {\n getAssetsState: this.#getAssetsState.bind(this),\n getAccountByAddress: this.#getAccountByAddress.bind(this),\n getSelectedAccount: this.#getSelectedAccount.bind(this),\n listAccounts: this.#listAccounts.bind(this),\n snapOwnsAccount: (account: InternalAccount) =>\n snapOwnsAccount(snapId, account),\n });\n\n this.update((draftState) => {\n // @ts-expect-error - TS2589: Type instantiation is excessively deep and\n // possibly infinite.\n draftState.interfaces[id] = {\n snapId,\n content: castDraft(element),\n state: componentState,\n context: context ?? null,\n contentType: contentType ?? null,\n };\n });\n\n return id;\n }\n\n /**\n * Get the data of a given interface id.\n *\n * @param snapId - The snap id requesting the interface data.\n * @param id - The interface id.\n * @returns The interface state.\n */\n getInterface(snapId: SnapId, id: string) {\n this.#validateArgs(snapId, id);\n\n return this.state.interfaces[id];\n }\n\n /**\n * Update the interface with the given content.\n *\n * @param snapId - The snap id requesting the update.\n * @param id - The interface id.\n * @param content - The new content.\n * @param context - An optional interface context object.\n */\n async updateInterface(\n snapId: SnapId,\n id: string,\n content: ComponentOrElement,\n context?: InterfaceContext,\n ) {\n this.#validateArgs(snapId, id);\n const element = getJsxInterface(content);\n await this.#validateContent(element);\n validateInterfaceContext(context);\n\n const oldState = this.state.interfaces[id].state;\n const newState = constructState(oldState, element, {\n getAssetsState: this.#getAssetsState.bind(this),\n getAccountByAddress: this.#getAccountByAddress.bind(this),\n getSelectedAccount: this.#getSelectedAccount.bind(this),\n listAccounts: this.#listAccounts.bind(this),\n snapOwnsAccount: (account: InternalAccount) =>\n snapOwnsAccount(snapId, account),\n });\n\n this.update((draftState) => {\n draftState.interfaces[id].state = newState;\n draftState.interfaces[id].content = castDraft(element);\n if (context) {\n draftState.interfaces[id].context = context;\n }\n });\n }\n\n /**\n * Delete an interface from state.\n *\n * @param id - The interface id.\n */\n deleteInterface(id: string) {\n this.update((draftState) => {\n delete draftState.interfaces[id];\n });\n }\n\n /**\n * Update the interface state.\n *\n * @param id - The interface id.\n * @param state - The new state.\n */\n updateInterfaceState(id: string, state: InterfaceState) {\n this.update((draftState) => {\n draftState.interfaces[id].state = state;\n });\n }\n\n /**\n * Resolve the promise of a given interface approval request.\n * The approval needs to have the same ID as the interface.\n *\n * @param snapId - The snap id.\n * @param id - The interface id.\n * @param value - The value to resolve the promise with.\n */\n async resolveInterface(snapId: SnapId, id: string, value: Json) {\n this.#validateArgs(snapId, id);\n this.#validateApproval(id);\n\n await this.#acceptApprovalRequest(id, value);\n\n this.deleteInterface(id);\n }\n\n /**\n * Utility function to validate the args passed to the other methods.\n *\n * @param snapId - The snap id.\n * @param id - The interface id.\n */\n #validateArgs(snapId: SnapId, id: string) {\n const existingInterface = this.state.interfaces[id];\n\n assert(\n existingInterface !== undefined,\n `Interface with id '${id}' not found.`,\n );\n assert(\n existingInterface.snapId === snapId,\n `Interface not created by ${snapId}.`,\n );\n }\n\n /**\n * Utility function to validate that the approval request exists.\n *\n * @param id - The interface id.\n */\n #validateApproval(id: string) {\n assert(\n this.#hasApprovalRequest(id),\n `Approval request with id '${id}' not found.`,\n );\n }\n\n /**\n * Check an origin against the phishing list.\n *\n * @param origin - The origin to check.\n * @returns True if the origin is on the phishing list, otherwise false.\n */\n #checkPhishingList(origin: string) {\n return this.messagingSystem.call('PhishingController:testOrigin', origin)\n .result;\n }\n\n /**\n * Check if an approval request exists for a given interface by looking up\n * if the ApprovalController has a request with the given interface ID.\n *\n * @param id - The interface id.\n * @returns True if an approval request exists, otherwise false.\n */\n #hasApprovalRequest(id: string) {\n return this.messagingSystem.call('ApprovalController:hasRequest', {\n id,\n });\n }\n\n /**\n * Accept an approval request for a given interface.\n *\n * @param id - The interface id.\n * @param value - The value to resolve the promise with.\n */\n async #acceptApprovalRequest(id: string, value: Json) {\n await this.messagingSystem.call(\n 'ApprovalController:acceptRequest',\n id,\n value,\n );\n }\n\n /**\n * Get the selected account in the client.\n *\n * @returns The selected account.\n */\n #getSelectedAccount() {\n return this.messagingSystem.call(\n 'AccountsController:getSelectedMultichainAccount',\n );\n }\n\n /**\n * Get a list of accounts for the given chain IDs.\n *\n * @param chainIds - The chain IDs to get the accounts for.\n * @returns The list of accounts.\n */\n #listAccounts(chainIds?: CaipChainId[]) {\n const accounts = this.messagingSystem.call(\n 'AccountsController:listMultichainAccounts',\n );\n\n if (!chainIds || chainIds.length === 0) {\n return accounts;\n }\n\n return accounts.filter((account) =>\n account.scopes.some((scope) => isMatchingChainId(scope, chainIds)),\n );\n }\n\n /**\n * Get an account by its address.\n *\n * @param address - The account address.\n * @returns The account or undefined if not found.\n */\n #getAccountByAddress(address: CaipAccountId) {\n const { address: parsedAddress } = parseCaipAccountId(address);\n\n return this.messagingSystem.call(\n 'AccountsController:getAccountByAddress',\n parsedAddress,\n );\n }\n\n /**\n * Get the MultichainAssetsController state.\n *\n * @returns The MultichainAssetsController state.\n */\n #getAssetsState() {\n return this.messagingSystem.call('MultichainAssetsController:getState');\n }\n\n /**\n * Get a snap by its id.\n *\n * @param id - The snap id.\n * @returns The snap.\n */\n #getSnap(id: string) {\n return this.messagingSystem.call('SnapController:get', id);\n }\n\n /**\n * Utility function to validate the components of an interface.\n * Throws if something is invalid.\n *\n * @param element - The JSX element to verify.\n */\n async #validateContent(element: JSXElement) {\n // We assume the validity of this JSON to be validated by the caller.\n // E.g., in the RPC method implementation.\n const size = getJsonSizeUnsafe(element);\n assert(\n size <= MAX_UI_CONTENT_SIZE,\n `A Snap UI may not be larger than ${MAX_UI_CONTENT_SIZE / 1000000} MB.`,\n );\n\n validateJsxElements(element, {\n isOnPhishingList: this.#checkPhishingList.bind(this),\n getSnap: this.#getSnap.bind(this),\n getAccountByAddress: this.#getAccountByAddress.bind(this),\n });\n }\n\n #onNotificationsListUpdated(notificationsList: Notification[]) {\n const snapNotificationsWithInterface = notificationsList.filter(\n (notification) => {\n return (\n notification.type === 'snap' &&\n hasProperty((notification as SnapNotification).data, 'detailedView')\n );\n },\n );\n\n const interfaceIdSet = new Set(\n snapNotificationsWithInterface.map(\n (notification) =>\n (\n (notification as SnapNotification)\n .data as ExpandedSnapNotificationData\n ).detailedView.interfaceId,\n ),\n );\n\n this.update((state) => {\n Object.entries(state.interfaces).forEach(([id, snapInterface]) => {\n if (\n snapInterface.contentType === ContentType.Notification &&\n !interfaceIdSet.has(id)\n ) {\n delete state.interfaces[id];\n }\n });\n });\n }\n}\n"]}
1
+ {"version":3,"file":"SnapInterfaceController.mjs","sourceRoot":"","sources":["../../src/interface/SnapInterfaceController.ts"],"names":[],"mappings":"AASA,OAAO,EAAE,cAAc,EAAE,kCAAkC;AAS3D,OAAO,EAAE,WAAW,EAAE,4BAA4B;AAGlD,OAAO,EACL,iBAAiB,EACjB,eAAe,EACf,mBAAmB,EACpB,8BAA8B;AAO/B,O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,MAAM,CACxE,CAAC;QAEF,mBAAmB,CAAC,OAAO,EAAE;YAC3B,gBAAgB,EAAE,IAAI,CAAC,kBAAkB,CAAC,IAAI,CAAC,IAAI,CAAC;YACpD,OAAO,EAAE,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC;YACjC,mBAAmB,EAAE,IAAI,CAAC,oBAAoB,CAAC,IAAI,CAAC,IAAI,CAAC;SAC1D,CAAC,CAAC;IACL,CAAC;IAED,2BAA2B,CAAC,iBAAiC;QAC3D,MAAM,8BAA8B,GAAG,iBAAiB,CAAC,MAAM,CAC7D,CAAC,YAAY,EAAE,EAAE;YACf,OAAO,CACL,YAAY,CAAC,IAAI,KAAK,MAAM;gBAC5B,WAAW,CAAE,YAAiC,CAAC,IAAI,EAAE,cAAc,CAAC,CACrE,CAAC;QACJ,CAAC,CACF,CAAC;QAEF,MAAM,cAAc,GAAG,IAAI,GAAG,CAC5B,8BAA8B,CAAC,GAAG,CAChC,CAAC,YAAY,EAAE,EAAE,CAEZ,YAAiC;aAC/B,IACJ,CAAC,YAAY,CAAC,WAAW,CAC7B,CACF,CAAC;QAEF,IAAI,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE;YACpB,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,EAAE,aAAa,CAAC,EAAE,EAAE;gBAC/D,IACE,aAAa,CAAC,WAAW,KAAK,WAAW,CAAC,YAAY;oBACtD,CAAC,cAAc,CAAC,GAAG,CAAC,EAAE,CAAC,EACvB,CAAC;oBACD,OAAO,KAAK,CAAC,UAAU,CAAC,EAAE,CAAC,CAAC;gBAC9B,CAAC;YACH,CAAC,CAAC,CAAC;QACL,CAAC,CAAC,CAAC;IACL,CAAC;CACF","sourcesContent":["import type {\n AcceptRequest,\n HasApprovalRequest,\n} from '@metamask/approval-controller';\nimport type {\n RestrictedMessenger,\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n} from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport type { TestOrigin } from '@metamask/phishing-controller';\nimport type {\n InterfaceState,\n SnapId,\n ComponentOrElement,\n InterfaceContext,\n FungibleAssetMetadata,\n} from '@metamask/snaps-sdk';\nimport { ContentType } from '@metamask/snaps-sdk';\nimport type { JSXElement } from '@metamask/snaps-sdk/jsx';\nimport type { InternalAccount } from '@metamask/snaps-utils';\nimport {\n getJsonSizeUnsafe,\n snapOwnsAccount,\n validateJsxElements,\n} from '@metamask/snaps-utils';\nimport type {\n CaipAccountId,\n CaipAssetType,\n CaipChainId,\n Json,\n} from '@metamask/utils';\nimport { assert, hasProperty, parseCaipAccountId } from '@metamask/utils';\nimport { castDraft } from 'immer';\nimport { nanoid } from 'nanoid';\n\nimport {\n constructState,\n getJsxInterface,\n isMatchingChainId,\n validateInterfaceContext,\n} from './utils';\nimport type { GetSnap } from '../snaps';\n\nconst MAX_UI_CONTENT_SIZE = 10_000_000; // 10 mb\n\nconst controllerName = 'SnapInterfaceController';\n\nexport type CreateInterface = {\n type: `${typeof controllerName}:createInterface`;\n handler: SnapInterfaceController['createInterface'];\n};\n\nexport type GetInterface = {\n type: `${typeof controllerName}:getInterface`;\n handler: SnapInterfaceController['getInterface'];\n};\n\nexport type UpdateInterface = {\n type: `${typeof controllerName}:updateInterface`;\n handler: SnapInterfaceController['updateInterface'];\n};\n\nexport type DeleteInterface = {\n type: `${typeof controllerName}:deleteInterface`;\n handler: SnapInterfaceController['deleteInterface'];\n};\n\nexport type UpdateInterfaceState = {\n type: `${typeof controllerName}:updateInterfaceState`;\n handler: SnapInterfaceController['updateInterfaceState'];\n};\n\nexport type ResolveInterface = {\n type: `${typeof controllerName}:resolveInterface`;\n handler: SnapInterfaceController['resolveInterface'];\n};\n\ntype AccountsControllerGetAccountByAddressAction = {\n type: `AccountsController:getAccountByAddress`;\n handler: (address: string) => InternalAccount | undefined;\n};\n\ntype AccountsControllerGetSelectedMultichainAccountAction = {\n type: `AccountsController:getSelectedMultichainAccount`;\n handler: () => InternalAccount;\n};\n\ntype AccountsControllerListMultichainAccountsAction = {\n type: `AccountsController:listMultichainAccounts`;\n handler: (chainId?: CaipChainId) => InternalAccount[];\n};\n\nexport type SnapInterfaceControllerGetStateAction = ControllerGetStateAction<\n typeof controllerName,\n SnapInterfaceControllerState\n>;\n\ntype MultichainAssetsControllerGetStateAction = ControllerGetStateAction<\n 'MultichainAssetsController',\n {\n assetsMetadata: {\n [asset: CaipAssetType]: FungibleAssetMetadata;\n };\n accountsAssets: { [account: string]: CaipAssetType[] };\n }\n>;\n\nexport type SnapInterfaceControllerAllowedActions =\n | TestOrigin\n | HasApprovalRequest\n | AcceptRequest\n | GetSnap\n | MultichainAssetsControllerGetStateAction\n | AccountsControllerGetSelectedMultichainAccountAction\n | AccountsControllerGetAccountByAddressAction\n | AccountsControllerListMultichainAccountsAction;\n\nexport type SnapInterfaceControllerActions =\n | CreateInterface\n | GetInterface\n | UpdateInterface\n | DeleteInterface\n | UpdateInterfaceState\n | ResolveInterface\n | SnapInterfaceControllerGetStateAction;\n\nexport type SnapInterfaceControllerStateChangeEvent =\n ControllerStateChangeEvent<\n typeof controllerName,\n SnapInterfaceControllerState\n >;\n\ntype OtherNotification = { type: string; [key: string]: unknown };\n\nexport type ExpandedView = {\n title: string;\n interfaceId: string;\n footerLink?: { href: string; text: string };\n};\n\ntype NormalSnapNotificationData = { message: string; origin: string };\n\ntype ExpandedSnapNotificationData = {\n message: string;\n origin: string;\n detailedView: ExpandedView;\n};\n\ntype SnapNotification = {\n type: 'snap';\n data: NormalSnapNotificationData | ExpandedSnapNotificationData;\n readDate: string | null;\n};\n\ntype Notification = OtherNotification | SnapNotification;\n\ntype NotificationListUpdatedEvent = {\n type: 'NotificationServicesController:notificationsListUpdated';\n payload: [Notification[]];\n};\n\nexport type SnapInterfaceControllerEvents =\n | SnapInterfaceControllerStateChangeEvent\n | NotificationListUpdatedEvent;\n\nexport type SnapInterfaceControllerMessenger = RestrictedMessenger<\n typeof controllerName,\n SnapInterfaceControllerActions | SnapInterfaceControllerAllowedActions,\n SnapInterfaceControllerEvents,\n SnapInterfaceControllerAllowedActions['type'],\n SnapInterfaceControllerEvents['type']\n>;\n\nexport type StoredInterface = {\n snapId: SnapId;\n content: JSXElement;\n state: InterfaceState;\n context: InterfaceContext | null;\n contentType: ContentType | null;\n};\n\nexport type SnapInterfaceControllerState = {\n interfaces: Record<string, StoredInterface>;\n};\n\nexport type SnapInterfaceControllerArgs = {\n messenger: SnapInterfaceControllerMessenger;\n state?: SnapInterfaceControllerState;\n};\n\n/**\n * Use this controller to manage snaps UI interfaces using RPC method hooks.\n */\nexport class SnapInterfaceController extends BaseController<\n typeof controllerName,\n SnapInterfaceControllerState,\n SnapInterfaceControllerMessenger\n> {\n constructor({ messenger, state }: SnapInterfaceControllerArgs) {\n super({\n messenger,\n metadata: {\n interfaces: {\n includeInStateLogs: true,\n persist: (interfaces: Record<string, StoredInterface>) => {\n return Object.entries(interfaces).reduce<\n Record<string, StoredInterface>\n >((persistedInterfaces, [id, snapInterface]) => {\n switch (snapInterface.contentType) {\n case ContentType.Notification:\n persistedInterfaces[id] = snapInterface;\n return persistedInterfaces;\n default:\n return persistedInterfaces;\n }\n }, {});\n },\n anonymous: false,\n usedInUi: true,\n },\n },\n name: controllerName,\n state: { interfaces: {}, ...state },\n });\n\n this.messagingSystem.subscribe(\n 'NotificationServicesController:notificationsListUpdated',\n this.#onNotificationsListUpdated.bind(this),\n );\n\n this.#registerMessageHandlers();\n }\n\n /**\n * Constructor helper for registering this controller's messaging system\n * actions.\n */\n #registerMessageHandlers() {\n this.messagingSystem.registerActionHandler(\n `${controllerName}:createInterface`,\n this.createInterface.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:getInterface`,\n this.getInterface.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:updateInterface`,\n this.updateInterface.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:deleteInterface`,\n this.deleteInterface.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:updateInterfaceState`,\n this.updateInterfaceState.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:resolveInterface`,\n this.resolveInterface.bind(this),\n );\n }\n\n /**\n * Create an interface in the controller state with the associated data.\n *\n * @param snapId - The snap id that created the interface.\n * @param content - The interface content.\n * @param context - An optional interface context object.\n * @param contentType - The type of content.\n * @returns The newly interface id.\n */\n createInterface(\n snapId: SnapId,\n content: ComponentOrElement,\n context?: InterfaceContext,\n contentType?: ContentType,\n ) {\n const element = getJsxInterface(content);\n this.#validateContent(element);\n validateInterfaceContext(context);\n\n const id = nanoid();\n const componentState = constructState({}, element, {\n getAssetsState: this.#getAssetsState.bind(this),\n getAccountByAddress: this.#getAccountByAddress.bind(this),\n getSelectedAccount: this.#getSelectedAccount.bind(this),\n listAccounts: this.#listAccounts.bind(this),\n snapOwnsAccount: (account: InternalAccount) =>\n snapOwnsAccount(snapId, account),\n });\n\n this.update((draftState) => {\n // @ts-expect-error - TS2589: Type instantiation is excessively deep and\n // possibly infinite.\n draftState.interfaces[id] = {\n snapId,\n content: castDraft(element),\n state: componentState,\n context: context ?? null,\n contentType: contentType ?? null,\n };\n });\n\n return id;\n }\n\n /**\n * Get the data of a given interface id.\n *\n * @param snapId - The snap id requesting the interface data.\n * @param id - The interface id.\n * @returns The interface state.\n */\n getInterface(snapId: SnapId, id: string) {\n this.#validateArgs(snapId, id);\n\n return this.state.interfaces[id];\n }\n\n /**\n * Update the interface with the given content.\n *\n * @param snapId - The snap id requesting the update.\n * @param id - The interface id.\n * @param content - The new content.\n * @param context - An optional interface context object.\n */\n updateInterface(\n snapId: SnapId,\n id: string,\n content: ComponentOrElement,\n context?: InterfaceContext,\n ) {\n this.#validateArgs(snapId, id);\n const element = getJsxInterface(content);\n this.#validateContent(element);\n validateInterfaceContext(context);\n\n const oldState = this.state.interfaces[id].state;\n const newState = constructState(oldState, element, {\n getAssetsState: this.#getAssetsState.bind(this),\n getAccountByAddress: this.#getAccountByAddress.bind(this),\n getSelectedAccount: this.#getSelectedAccount.bind(this),\n listAccounts: this.#listAccounts.bind(this),\n snapOwnsAccount: (account: InternalAccount) =>\n snapOwnsAccount(snapId, account),\n });\n\n this.update((draftState) => {\n draftState.interfaces[id].state = newState;\n draftState.interfaces[id].content = castDraft(element);\n if (context) {\n draftState.interfaces[id].context = context;\n }\n });\n }\n\n /**\n * Delete an interface from state.\n *\n * @param id - The interface id.\n */\n deleteInterface(id: string) {\n this.update((draftState) => {\n delete draftState.interfaces[id];\n });\n }\n\n /**\n * Update the interface state.\n *\n * @param id - The interface id.\n * @param state - The new state.\n */\n updateInterfaceState(id: string, state: InterfaceState) {\n this.update((draftState) => {\n draftState.interfaces[id].state = state;\n });\n }\n\n /**\n * Resolve the promise of a given interface approval request.\n * The approval needs to have the same ID as the interface.\n *\n * @param snapId - The snap id.\n * @param id - The interface id.\n * @param value - The value to resolve the promise with.\n */\n async resolveInterface(snapId: SnapId, id: string, value: Json) {\n this.#validateArgs(snapId, id);\n this.#validateApproval(id);\n\n await this.#acceptApprovalRequest(id, value);\n\n this.deleteInterface(id);\n }\n\n /**\n * Utility function to validate the args passed to the other methods.\n *\n * @param snapId - The snap id.\n * @param id - The interface id.\n */\n #validateArgs(snapId: SnapId, id: string) {\n const existingInterface = this.state.interfaces[id];\n\n assert(\n existingInterface !== undefined,\n `Interface with id '${id}' not found.`,\n );\n assert(\n existingInterface.snapId === snapId,\n `Interface not created by ${snapId}.`,\n );\n }\n\n /**\n * Utility function to validate that the approval request exists.\n *\n * @param id - The interface id.\n */\n #validateApproval(id: string) {\n assert(\n this.#hasApprovalRequest(id),\n `Approval request with id '${id}' not found.`,\n );\n }\n\n /**\n * Check an origin against the phishing list.\n *\n * @param origin - The origin to check.\n * @returns True if the origin is on the phishing list, otherwise false.\n */\n #checkPhishingList(origin: string) {\n return this.messagingSystem.call('PhishingController:testOrigin', origin)\n .result;\n }\n\n /**\n * Check if an approval request exists for a given interface by looking up\n * if the ApprovalController has a request with the given interface ID.\n *\n * @param id - The interface id.\n * @returns True if an approval request exists, otherwise false.\n */\n #hasApprovalRequest(id: string) {\n return this.messagingSystem.call('ApprovalController:hasRequest', {\n id,\n });\n }\n\n /**\n * Accept an approval request for a given interface.\n *\n * @param id - The interface id.\n * @param value - The value to resolve the promise with.\n */\n async #acceptApprovalRequest(id: string, value: Json) {\n await this.messagingSystem.call(\n 'ApprovalController:acceptRequest',\n id,\n value,\n );\n }\n\n /**\n * Get the selected account in the client.\n *\n * @returns The selected account.\n */\n #getSelectedAccount() {\n return this.messagingSystem.call(\n 'AccountsController:getSelectedMultichainAccount',\n );\n }\n\n /**\n * Get a list of accounts for the given chain IDs.\n *\n * @param chainIds - The chain IDs to get the accounts for.\n * @returns The list of accounts.\n */\n #listAccounts(chainIds?: CaipChainId[]) {\n const accounts = this.messagingSystem.call(\n 'AccountsController:listMultichainAccounts',\n );\n\n if (!chainIds || chainIds.length === 0) {\n return accounts;\n }\n\n return accounts.filter((account) =>\n account.scopes.some((scope) => isMatchingChainId(scope, chainIds)),\n );\n }\n\n /**\n * Get an account by its address.\n *\n * @param address - The account address.\n * @returns The account or undefined if not found.\n */\n #getAccountByAddress(address: CaipAccountId) {\n const { address: parsedAddress } = parseCaipAccountId(address);\n\n return this.messagingSystem.call(\n 'AccountsController:getAccountByAddress',\n parsedAddress,\n );\n }\n\n /**\n * Get the MultichainAssetsController state.\n *\n * @returns The MultichainAssetsController state.\n */\n #getAssetsState() {\n return this.messagingSystem.call('MultichainAssetsController:getState');\n }\n\n /**\n * Get a snap by its id.\n *\n * @param id - The snap id.\n * @returns The snap.\n */\n #getSnap(id: string) {\n return this.messagingSystem.call('SnapController:get', id);\n }\n\n /**\n * Utility function to validate the components of an interface.\n * Throws if something is invalid.\n *\n * @param element - The JSX element to verify.\n */\n #validateContent(element: JSXElement) {\n // We assume the validity of this JSON to be validated by the caller.\n // E.g., in the RPC method implementation.\n const size = getJsonSizeUnsafe(element);\n assert(\n size <= MAX_UI_CONTENT_SIZE,\n `A Snap UI may not be larger than ${MAX_UI_CONTENT_SIZE / 1000000} MB.`,\n );\n\n validateJsxElements(element, {\n isOnPhishingList: this.#checkPhishingList.bind(this),\n getSnap: this.#getSnap.bind(this),\n getAccountByAddress: this.#getAccountByAddress.bind(this),\n });\n }\n\n #onNotificationsListUpdated(notificationsList: Notification[]) {\n const snapNotificationsWithInterface = notificationsList.filter(\n (notification) => {\n return (\n notification.type === 'snap' &&\n hasProperty((notification as SnapNotification).data, 'detailedView')\n );\n },\n );\n\n const interfaceIdSet = new Set(\n snapNotificationsWithInterface.map(\n (notification) =>\n (\n (notification as SnapNotification)\n .data as ExpandedSnapNotificationData\n ).detailedView.interfaceId,\n ),\n );\n\n this.update((state) => {\n Object.entries(state.interfaces).forEach(([id, snapInterface]) => {\n if (\n snapInterface.contentType === ContentType.Notification &&\n !interfaceIdSet.has(id)\n ) {\n delete state.interfaces[id];\n }\n });\n });\n }\n}\n"]}
@@ -69,12 +69,7 @@ class AbstractExecutionService {
69
69
  id: (0, nanoid_1.nanoid)(),
70
70
  }), this.#terminationTimeout);
71
71
  if (result === utils_2.hasTimedOut || result !== 'OK') {
72
- // We tried to shutdown gracefully but failed. This probably means the Snap is in infinite loop and
73
- // hogging down the whole JS process.
74
- // TODO(ritave): It might be doing weird things such as posting a lot of setTimeouts. Add a test to ensure that this behaviour
75
- // doesn't leak into other workers. Especially important in IframeExecutionEnvironment since they all share the same
76
- // JS process.
77
- (0, snaps_utils_1.logError)(`Snap "${snapId}" failed to terminate gracefully.`, result);
72
+ (0, snaps_utils_1.logWarning)(`Snap "${snapId}" failed to terminate gracefully.`);
78
73
  }
79
74
  }
80
75
  catch {
@@ -167,6 +162,23 @@ class AbstractExecutionService {
167
162
  };
168
163
  commandStream.on('data', notificationHandler);
169
164
  const rpcStream = mux.createStream(snaps_utils_1.SNAP_STREAM_NAMES.JSON_RPC);
165
+ rpcStream.on('data', (chunk) => {
166
+ if (chunk?.data && (0, utils_1.hasProperty)(chunk?.data, 'id')) {
167
+ this.#messenger.publish('ExecutionService:outboundRequest', snapId);
168
+ }
169
+ });
170
+ const originalWrite = rpcStream.write.bind(rpcStream);
171
+ // @ts-expect-error Hack to inspect the messages being written to the stream.
172
+ rpcStream.write = (chunk, encoding, callback) => {
173
+ // Ignore chain switching notifications as it doesn't matter for the SnapProvider.
174
+ if (chunk?.data?.method === 'metamask_chainChanged') {
175
+ return true;
176
+ }
177
+ if (chunk?.data && (0, utils_1.hasProperty)(chunk?.data, 'id')) {
178
+ this.#messenger.publish('ExecutionService:outboundResponse', snapId);
179
+ }
180
+ return originalWrite(chunk, encoding, callback);
181
+ };
170
182
  // Typecast: stream type mismatch
171
183
  return {
172
184
  streams: {
@@ -250,8 +262,10 @@ class AbstractExecutionService {
250
262
  }
251
263
  (0, logging_1.log)('Parent: Sending Command', message);
252
264
  const response = await job.rpcEngine.handle(message);
253
- if ((0, utils_1.isJsonRpcFailure)(response)) {
254
- throw new rpc_errors_1.JsonRpcError(response.error.code, response.error.message, response.error.data);
265
+ // We don't need full validation of the response here because we control it.
266
+ if ((0, utils_1.hasProperty)(response, 'error')) {
267
+ const error = response.error;
268
+ throw new rpc_errors_1.JsonRpcError(error.code, error.message, error.data);
255
269
  }
256
270
  return response.result;
257
271
  }