@metamask/snaps-controllers 12.3.1 → 13.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 (88) hide show
  1. package/CHANGELOG.md +25 -1
  2. package/dist/cronjob/CronjobController.cjs +250 -276
  3. package/dist/cronjob/CronjobController.cjs.map +1 -1
  4. package/dist/cronjob/CronjobController.d.cts +61 -78
  5. package/dist/cronjob/CronjobController.d.cts.map +1 -1
  6. package/dist/cronjob/CronjobController.d.mts +61 -78
  7. package/dist/cronjob/CronjobController.d.mts.map +1 -1
  8. package/dist/cronjob/CronjobController.mjs +251 -277
  9. package/dist/cronjob/CronjobController.mjs.map +1 -1
  10. package/dist/cronjob/utils.cjs +79 -0
  11. package/dist/cronjob/utils.cjs.map +1 -0
  12. package/dist/cronjob/utils.d.cts +25 -0
  13. package/dist/cronjob/utils.d.cts.map +1 -0
  14. package/dist/cronjob/utils.d.mts +25 -0
  15. package/dist/cronjob/utils.d.mts.map +1 -0
  16. package/dist/cronjob/utils.mjs +75 -0
  17. package/dist/cronjob/utils.mjs.map +1 -0
  18. package/dist/insights/SnapInsightsController.cjs +199 -149
  19. package/dist/insights/SnapInsightsController.cjs.map +1 -1
  20. package/dist/insights/SnapInsightsController.mjs +198 -148
  21. package/dist/insights/SnapInsightsController.mjs.map +1 -1
  22. package/dist/interface/SnapInterfaceController.cjs +160 -101
  23. package/dist/interface/SnapInterfaceController.cjs.map +1 -1
  24. package/dist/interface/SnapInterfaceController.mjs +160 -101
  25. package/dist/interface/SnapInterfaceController.mjs.map +1 -1
  26. package/dist/multichain/MultichainRouter.cjs +117 -114
  27. package/dist/multichain/MultichainRouter.cjs.map +1 -1
  28. package/dist/multichain/MultichainRouter.mjs +117 -114
  29. package/dist/multichain/MultichainRouter.mjs.map +1 -1
  30. package/dist/services/AbstractExecutionService.cjs +131 -139
  31. package/dist/services/AbstractExecutionService.cjs.map +1 -1
  32. package/dist/services/AbstractExecutionService.mjs +131 -139
  33. package/dist/services/AbstractExecutionService.mjs.map +1 -1
  34. package/dist/services/ProxyPostMessageStream.cjs +19 -26
  35. package/dist/services/ProxyPostMessageStream.cjs.map +1 -1
  36. package/dist/services/ProxyPostMessageStream.mjs +19 -26
  37. package/dist/services/ProxyPostMessageStream.mjs.map +1 -1
  38. package/dist/services/iframe/IframeExecutionService.cjs +1 -0
  39. package/dist/services/iframe/IframeExecutionService.cjs.map +1 -1
  40. package/dist/services/iframe/IframeExecutionService.mjs +1 -0
  41. package/dist/services/iframe/IframeExecutionService.mjs.map +1 -1
  42. package/dist/services/offscreen/OffscreenExecutionService.cjs +3 -16
  43. package/dist/services/offscreen/OffscreenExecutionService.cjs.map +1 -1
  44. package/dist/services/offscreen/OffscreenExecutionService.mjs +3 -16
  45. package/dist/services/offscreen/OffscreenExecutionService.mjs.map +1 -1
  46. package/dist/services/proxy/ProxyExecutionService.cjs +4 -17
  47. package/dist/services/proxy/ProxyExecutionService.cjs.map +1 -1
  48. package/dist/services/proxy/ProxyExecutionService.mjs +4 -17
  49. package/dist/services/proxy/ProxyExecutionService.mjs.map +1 -1
  50. package/dist/services/webview/WebViewExecutionService.cjs +6 -19
  51. package/dist/services/webview/WebViewExecutionService.cjs.map +1 -1
  52. package/dist/services/webview/WebViewExecutionService.mjs +6 -19
  53. package/dist/services/webview/WebViewExecutionService.mjs.map +1 -1
  54. package/dist/services/webview/WebViewMessageStream.cjs +13 -26
  55. package/dist/services/webview/WebViewMessageStream.cjs.map +1 -1
  56. package/dist/services/webview/WebViewMessageStream.mjs +13 -26
  57. package/dist/services/webview/WebViewMessageStream.mjs.map +1 -1
  58. package/dist/snaps/SnapController.cjs +1370 -1161
  59. package/dist/snaps/SnapController.cjs.map +1 -1
  60. package/dist/snaps/SnapController.d.cts +4 -4
  61. package/dist/snaps/SnapController.d.cts.map +1 -1
  62. package/dist/snaps/SnapController.d.mts +4 -4
  63. package/dist/snaps/SnapController.d.mts.map +1 -1
  64. package/dist/snaps/SnapController.mjs +1370 -1161
  65. package/dist/snaps/SnapController.mjs.map +1 -1
  66. package/dist/snaps/Timer.cjs +4 -0
  67. package/dist/snaps/Timer.cjs.map +1 -1
  68. package/dist/snaps/Timer.mjs +4 -0
  69. package/dist/snaps/Timer.mjs.map +1 -1
  70. package/dist/snaps/location/http.cjs +20 -4
  71. package/dist/snaps/location/http.cjs.map +1 -1
  72. package/dist/snaps/location/http.mjs +20 -4
  73. package/dist/snaps/location/http.mjs.map +1 -1
  74. package/dist/snaps/location/local.cjs +4 -17
  75. package/dist/snaps/location/local.cjs.map +1 -1
  76. package/dist/snaps/location/local.mjs +4 -17
  77. package/dist/snaps/location/local.mjs.map +1 -1
  78. package/dist/snaps/location/npm.cjs +28 -48
  79. package/dist/snaps/location/npm.cjs.map +1 -1
  80. package/dist/snaps/location/npm.d.cts.map +1 -1
  81. package/dist/snaps/location/npm.d.mts.map +1 -1
  82. package/dist/snaps/location/npm.mjs +28 -48
  83. package/dist/snaps/location/npm.mjs.map +1 -1
  84. package/dist/snaps/registry/json.cjs +173 -166
  85. package/dist/snaps/registry/json.cjs.map +1 -1
  86. package/dist/snaps/registry/json.mjs +172 -165
  87. package/dist/snaps/registry/json.mjs.map +1 -1
  88. package/package.json +9 -9
@@ -1,9 +1,3 @@
1
- var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
2
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
3
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
4
- return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
5
- };
6
- var _SnapInsightsController_instances, _SnapInsightsController_hasInsight, _SnapInsightsController_getSnapsWithPermission, _SnapInsightsController_handleTransaction, _SnapInsightsController_handleSignatureStateChange, _SnapInsightsController_handleSignature, _SnapInsightsController_handleTransactionStatusUpdate, _SnapInsightsController_handleInsightCleanup, _SnapInsightsController_handleSnapRequest, _SnapInsightsController_handleSnapResponse;
7
1
  import { BaseController } from "@metamask/base-controller";
8
2
  import { getSignatureOriginCaveat, getTransactionOriginCaveat, SnapEndowments } from "@metamask/snaps-rpc-methods";
9
3
  import { HandlerType } from "@metamask/snaps-utils";
@@ -23,161 +17,217 @@ export class SnapInsightsController extends BaseController {
23
17
  name: controllerName,
24
18
  state: { insights: {}, ...state },
25
19
  });
26
- _SnapInsightsController_instances.add(this);
27
- this.messagingSystem.subscribe('TransactionController:unapprovedTransactionAdded', __classPrivateFieldGet(this, _SnapInsightsController_instances, "m", _SnapInsightsController_handleTransaction).bind(this));
28
- this.messagingSystem.subscribe('TransactionController:transactionStatusUpdated', __classPrivateFieldGet(this, _SnapInsightsController_instances, "m", _SnapInsightsController_handleTransactionStatusUpdate).bind(this));
29
- this.messagingSystem.subscribe('SignatureController:stateChange', __classPrivateFieldGet(this, _SnapInsightsController_instances, "m", _SnapInsightsController_handleSignatureStateChange).bind(this));
20
+ this.messagingSystem.subscribe('TransactionController:unapprovedTransactionAdded', this.#handleTransaction.bind(this));
21
+ this.messagingSystem.subscribe('TransactionController:transactionStatusUpdated', this.#handleTransactionStatusUpdate.bind(this));
22
+ this.messagingSystem.subscribe('SignatureController:stateChange', this.#handleSignatureStateChange.bind(this));
30
23
  }
31
- }
32
- _SnapInsightsController_instances = new WeakSet(), _SnapInsightsController_hasInsight = function _SnapInsightsController_hasInsight(id) {
33
- return hasProperty(this.state.insights, id);
34
- }, _SnapInsightsController_getSnapsWithPermission = function _SnapInsightsController_getSnapsWithPermission(permissionName) {
35
- const allSnaps = this.messagingSystem.call('SnapController:getAll');
36
- const filteredSnaps = getRunnableSnaps(allSnaps);
37
- return filteredSnaps.reduce((accumulator, snap) => {
38
- const permissions = this.messagingSystem.call('PermissionController:getPermissions', snap.id);
39
- if (permissions && hasProperty(permissions, permissionName)) {
40
- accumulator.push({
41
- snapId: snap.id,
42
- permission: permissions[permissionName],
24
+ /**
25
+ * Check if an insight already exists for a given ID.
26
+ *
27
+ * @param id - The ID.
28
+ * @returns True if the insight already exists, otherwise false.
29
+ */
30
+ #hasInsight(id) {
31
+ return hasProperty(this.state.insights, id);
32
+ }
33
+ /**
34
+ * Get a list of runnable Snaps that have a given permission.
35
+ * Also includes the permission object itself.
36
+ *
37
+ * @param permissionName - The permission name.
38
+ * @returns A list of objects containing Snap IDs and the permission object.
39
+ */
40
+ #getSnapsWithPermission(permissionName) {
41
+ const allSnaps = this.messagingSystem.call('SnapController:getAll');
42
+ const filteredSnaps = getRunnableSnaps(allSnaps);
43
+ return filteredSnaps.reduce((accumulator, snap) => {
44
+ const permissions = this.messagingSystem.call('PermissionController:getPermissions', snap.id);
45
+ if (permissions && hasProperty(permissions, permissionName)) {
46
+ accumulator.push({
47
+ snapId: snap.id,
48
+ permission: permissions[permissionName],
49
+ });
50
+ }
51
+ return accumulator;
52
+ }, []);
53
+ }
54
+ /**
55
+ * Handle a newly added unapproved transaction.
56
+ * This function fetches insights from all available Snaps
57
+ * and populates the insights state blob with the responses.
58
+ *
59
+ * @param transaction - The transaction object.
60
+ */
61
+ #handleTransaction(transaction) {
62
+ const { id, txParams, chainId, origin } = transaction;
63
+ // This assumes that the transactions are EVM-compatible for now.
64
+ const caipChainId = `eip155:${hexToBigInt(chainId).toString(10)}`;
65
+ const snaps = this.#getSnapsWithPermission(SnapEndowments.TransactionInsight);
66
+ snaps.forEach(({ snapId, permission }) => {
67
+ const hasTransactionOriginCaveat = getTransactionOriginCaveat(permission);
68
+ const transactionOrigin = hasTransactionOriginCaveat && origin ? origin : null;
69
+ this.update((state) => {
70
+ state.insights[id] ??= {};
71
+ state.insights[id][snapId] = { snapId, loading: true };
43
72
  });
44
- }
45
- return accumulator;
46
- }, []);
47
- }, _SnapInsightsController_handleTransaction = function _SnapInsightsController_handleTransaction(transaction) {
48
- const { id, txParams, chainId, origin } = transaction;
49
- // This assumes that the transactions are EVM-compatible for now.
50
- const caipChainId = `eip155:${hexToBigInt(chainId).toString(10)}`;
51
- const snaps = __classPrivateFieldGet(this, _SnapInsightsController_instances, "m", _SnapInsightsController_getSnapsWithPermission).call(this, SnapEndowments.TransactionInsight);
52
- snaps.forEach(({ snapId, permission }) => {
53
- const hasTransactionOriginCaveat = getTransactionOriginCaveat(permission);
54
- const transactionOrigin = hasTransactionOriginCaveat && origin ? origin : null;
55
- this.update((state) => {
56
- var _a;
57
- (_a = state.insights)[id] ?? (_a[id] = {});
58
- state.insights[id][snapId] = { snapId, loading: true };
73
+ this.#handleSnapRequest({
74
+ snapId,
75
+ handler: HandlerType.OnTransaction,
76
+ params: {
77
+ transaction: txParams,
78
+ chainId: caipChainId,
79
+ transactionOrigin,
80
+ },
81
+ })
82
+ .then((response) => this.#handleSnapResponse({
83
+ id,
84
+ snapId,
85
+ response: response,
86
+ }))
87
+ .catch((error) => this.#handleSnapResponse({ id, snapId, error }));
59
88
  });
60
- __classPrivateFieldGet(this, _SnapInsightsController_instances, "m", _SnapInsightsController_handleSnapRequest).call(this, {
61
- snapId,
62
- handler: HandlerType.OnTransaction,
63
- params: {
64
- transaction: txParams,
65
- chainId: caipChainId,
66
- transactionOrigin,
67
- },
68
- })
69
- .then((response) => __classPrivateFieldGet(this, _SnapInsightsController_instances, "m", _SnapInsightsController_handleSnapResponse).call(this, {
70
- id,
71
- snapId,
72
- response: response,
73
- }))
74
- .catch((error) => __classPrivateFieldGet(this, _SnapInsightsController_instances, "m", _SnapInsightsController_handleSnapResponse).call(this, { id, snapId, error }));
75
- });
76
- }, _SnapInsightsController_handleSignatureStateChange = function _SnapInsightsController_handleSignatureStateChange(state) {
77
- // If any IDs have disappeared since the last state update, the insight may be cleaned up.
78
- for (const id of Object.keys(this.state.insights)) {
79
- if (!hasProperty(state.unapprovedTypedMessages, id) &&
80
- !hasProperty(state.unapprovedPersonalMsgs, id)) {
81
- __classPrivateFieldGet(this, _SnapInsightsController_instances, "m", _SnapInsightsController_handleInsightCleanup).call(this, id);
82
- }
83
89
  }
84
- if (state.unapprovedPersonalMsgCount > 0 ||
85
- state.unapprovedTypedMessagesCount > 0) {
86
- const snaps = __classPrivateFieldGet(this, _SnapInsightsController_instances, "m", _SnapInsightsController_getSnapsWithPermission).call(this, SnapEndowments.SignatureInsight);
87
- // This isn't very efficient, but SignatureController doesn't expose a better event for us to use yet.
88
- for (const personalSignature of Object.values(state.unapprovedPersonalMsgs)) {
89
- __classPrivateFieldGet(this, _SnapInsightsController_instances, "m", _SnapInsightsController_handleSignature).call(this, snaps, personalSignature);
90
+ /**
91
+ * Handle the stateChange event emitted by the SignatureController.
92
+ * This function will remove existing insights from the state when applicable, as well as
93
+ * trigger insight fetching for newly added signatures.
94
+ *
95
+ * @param state - The SignatureController state blob.
96
+ */
97
+ #handleSignatureStateChange(state) {
98
+ // If any IDs have disappeared since the last state update, the insight may be cleaned up.
99
+ for (const id of Object.keys(this.state.insights)) {
100
+ if (!hasProperty(state.unapprovedTypedMessages, id) &&
101
+ !hasProperty(state.unapprovedPersonalMsgs, id)) {
102
+ this.#handleInsightCleanup(id);
103
+ }
90
104
  }
91
- for (const typedMessage of Object.values(state.unapprovedTypedMessages)) {
92
- __classPrivateFieldGet(this, _SnapInsightsController_instances, "m", _SnapInsightsController_handleSignature).call(this, snaps, typedMessage);
105
+ if (state.unapprovedPersonalMsgCount > 0 ||
106
+ state.unapprovedTypedMessagesCount > 0) {
107
+ const snaps = this.#getSnapsWithPermission(SnapEndowments.SignatureInsight);
108
+ // This isn't very efficient, but SignatureController doesn't expose a better event for us to use yet.
109
+ for (const personalSignature of Object.values(state.unapprovedPersonalMsgs)) {
110
+ this.#handleSignature(snaps, personalSignature);
111
+ }
112
+ for (const typedMessage of Object.values(state.unapprovedTypedMessages)) {
113
+ this.#handleSignature(snaps, typedMessage);
114
+ }
93
115
  }
94
116
  }
95
- }, _SnapInsightsController_handleSignature = function _SnapInsightsController_handleSignature(snaps, signature) {
96
- const { id, msgParams } = signature;
97
- if (__classPrivateFieldGet(this, _SnapInsightsController_instances, "m", _SnapInsightsController_hasInsight).call(this, id)) {
98
- return;
117
+ /**
118
+ * Handle a newly added unapproved signature.
119
+ * This function fetches insights from all available Snaps
120
+ * and populates the insights state blob with the responses.
121
+ *
122
+ * @param snaps - A list of Snaps to invoke.
123
+ * @param signature - The signature object.
124
+ */
125
+ #handleSignature(snaps, signature) {
126
+ const { id, msgParams } = signature;
127
+ if (this.#hasInsight(id)) {
128
+ return;
129
+ }
130
+ const { from, data, signatureMethod, origin } = msgParams;
131
+ /**
132
+ * Both eth_signTypedData_v3 and eth_signTypedData_v4 methods
133
+ * need to be parsed because their data is stringified. All other
134
+ * signature methods do not, so they are ignored.
135
+ */
136
+ const shouldParse = signatureMethod === 'eth_signTypedData_v3' ||
137
+ signatureMethod === 'eth_signTypedData_v4';
138
+ const payload = {
139
+ from,
140
+ data: shouldParse ? JSON.parse(data) : data,
141
+ signatureMethod,
142
+ };
143
+ snaps.forEach(({ snapId, permission }) => {
144
+ const hasSignatureOriginCaveat = getSignatureOriginCaveat(permission);
145
+ const signatureOrigin = origin && hasSignatureOriginCaveat ? origin : null;
146
+ this.update((state) => {
147
+ state.insights[id] ??= {};
148
+ state.insights[id][snapId] = { snapId, loading: true };
149
+ });
150
+ this.#handleSnapRequest({
151
+ snapId,
152
+ handler: HandlerType.OnSignature,
153
+ params: { signature: payload, signatureOrigin },
154
+ })
155
+ .then((response) => this.#handleSnapResponse({
156
+ id,
157
+ snapId,
158
+ response: response,
159
+ }))
160
+ .catch((error) => this.#handleSnapResponse({ id, snapId, error }));
161
+ });
99
162
  }
100
- const { from, data, signatureMethod, origin } = msgParams;
101
163
  /**
102
- * Both eth_signTypedData_v3 and eth_signTypedData_v4 methods
103
- * need to be parsed because their data is stringified. All other
104
- * signature methods do not, so they are ignored.
164
+ * Handle the transactionStatusUpdated event emitted by the TransactionController.
165
+ * This function will remove insights for the transaction in question
166
+ * once the transaction status has changed from unapproved.
167
+ *
168
+ * @param args - An options bag.
169
+ * @param args.transactionMeta - The transaction.
105
170
  */
106
- const shouldParse = signatureMethod === 'eth_signTypedData_v3' ||
107
- signatureMethod === 'eth_signTypedData_v4';
108
- const payload = {
109
- from,
110
- data: shouldParse ? JSON.parse(data) : data,
111
- signatureMethod,
112
- };
113
- snaps.forEach(({ snapId, permission }) => {
114
- const hasSignatureOriginCaveat = getSignatureOriginCaveat(permission);
115
- const signatureOrigin = origin && hasSignatureOriginCaveat ? origin : null;
171
+ #handleTransactionStatusUpdate({ transactionMeta, }) {
172
+ if (transactionMeta.status !== 'unapproved') {
173
+ this.#handleInsightCleanup(transactionMeta.id);
174
+ }
175
+ }
176
+ #handleInsightCleanup(id) {
177
+ if (!this.#hasInsight(id)) {
178
+ return;
179
+ }
180
+ // Delete interfaces from interface controller.
181
+ Object.values(this.state.insights[id])
182
+ .filter((insight) => insight.interfaceId)
183
+ .forEach((insight) => {
184
+ this.messagingSystem.call('SnapInterfaceController:deleteInterface', insight.interfaceId);
185
+ });
116
186
  this.update((state) => {
117
- var _a;
118
- (_a = state.insights)[id] ?? (_a[id] = {});
119
- state.insights[id][snapId] = { snapId, loading: true };
187
+ delete state.insights[id];
120
188
  });
121
- __classPrivateFieldGet(this, _SnapInsightsController_instances, "m", _SnapInsightsController_handleSnapRequest).call(this, {
122
- snapId,
123
- handler: HandlerType.OnSignature,
124
- params: { signature: payload, signatureOrigin },
125
- })
126
- .then((response) => __classPrivateFieldGet(this, _SnapInsightsController_instances, "m", _SnapInsightsController_handleSnapResponse).call(this, {
127
- id,
128
- snapId,
129
- response: response,
130
- }))
131
- .catch((error) => __classPrivateFieldGet(this, _SnapInsightsController_instances, "m", _SnapInsightsController_handleSnapResponse).call(this, { id, snapId, error }));
132
- });
133
- }, _SnapInsightsController_handleTransactionStatusUpdate = function _SnapInsightsController_handleTransactionStatusUpdate({ transactionMeta, }) {
134
- if (transactionMeta.status !== 'unapproved') {
135
- __classPrivateFieldGet(this, _SnapInsightsController_instances, "m", _SnapInsightsController_handleInsightCleanup).call(this, transactionMeta.id);
136
189
  }
137
- }, _SnapInsightsController_handleInsightCleanup = function _SnapInsightsController_handleInsightCleanup(id) {
138
- if (!__classPrivateFieldGet(this, _SnapInsightsController_instances, "m", _SnapInsightsController_hasInsight).call(this, id)) {
139
- return;
190
+ /**
191
+ * Handle sending a request to a given Snap with a given payload.
192
+ *
193
+ * @param args - An options bag.
194
+ * @param args.snapId - The Snap ID.
195
+ * @param args.handler - The handler to invoke.
196
+ * @param args.params - The JSON-RPC params to send.
197
+ * @returns The response from the Snap.
198
+ */
199
+ async #handleSnapRequest({ snapId, handler, params, }) {
200
+ return this.messagingSystem.call('SnapController:handleRequest', {
201
+ snapId,
202
+ origin: 'metamask',
203
+ handler,
204
+ request: {
205
+ method: '',
206
+ params,
207
+ },
208
+ });
140
209
  }
141
- // Delete interfaces from interface controller.
142
- Object.values(this.state.insights[id])
143
- .filter((insight) => insight.interfaceId)
144
- .forEach((insight) => {
145
- this.messagingSystem.call('SnapInterfaceController:deleteInterface', insight.interfaceId);
146
- });
147
- this.update((state) => {
148
- delete state.insights[id];
149
- });
150
- }, _SnapInsightsController_handleSnapRequest =
151
- /**
152
- * Handle sending a request to a given Snap with a given payload.
153
- *
154
- * @param args - An options bag.
155
- * @param args.snapId - The Snap ID.
156
- * @param args.handler - The handler to invoke.
157
- * @param args.params - The JSON-RPC params to send.
158
- * @returns The response from the Snap.
159
- */
160
- async function _SnapInsightsController_handleSnapRequest({ snapId, handler, params, }) {
161
- return this.messagingSystem.call('SnapController:handleRequest', {
162
- snapId,
163
- origin: 'metamask',
164
- handler,
165
- request: {
166
- method: '',
167
- params,
168
- },
169
- });
170
- }, _SnapInsightsController_handleSnapResponse = function _SnapInsightsController_handleSnapResponse({ id, snapId, response, error, }) {
171
- // If the insight has been cleaned up already, we can skip setting the state.
172
- // This may happen if a user accepts/rejects a transaction/signature faster than the Snap responds.
173
- if (!__classPrivateFieldGet(this, _SnapInsightsController_instances, "m", _SnapInsightsController_hasInsight).call(this, id)) {
174
- return;
210
+ /**
211
+ * Handle response from a given Snap by persisting the response or error in state.
212
+ *
213
+ * @param args - An options bag.
214
+ * @param args.id - The transaction or signature ID.
215
+ * @param args.snapId - The Snap ID.
216
+ * @param args.response - An optional response object returned by the Snap.
217
+ * @param args.error - An optional error returned by the Snap.
218
+ */
219
+ #handleSnapResponse({ id, snapId, response, error, }) {
220
+ // If the insight has been cleaned up already, we can skip setting the state.
221
+ // This may happen if a user accepts/rejects a transaction/signature faster than the Snap responds.
222
+ if (!this.#hasInsight(id)) {
223
+ return;
224
+ }
225
+ this.update((state) => {
226
+ state.insights[id][snapId].loading = false;
227
+ state.insights[id][snapId].interfaceId = response?.id;
228
+ state.insights[id][snapId].severity = response?.severity;
229
+ state.insights[id][snapId].error = error?.message;
230
+ });
175
231
  }
176
- this.update((state) => {
177
- state.insights[id][snapId].loading = false;
178
- state.insights[id][snapId].interfaceId = response?.id;
179
- state.insights[id][snapId].severity = response?.severity;
180
- state.insights[id][snapId].error = error?.message;
181
- });
182
- };
232
+ }
183
233
  //# sourceMappingURL=SnapInsightsController.mjs.map
@@ -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,K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AE,EACF,MAAM,EACN,QAAQ,EACR,KAAK,GAMN;IACC,6EAA6E;IAC7E,mGAAmG;IACnG,IAAI,CAAC,uBAAA,IAAI,6EAAY,MAAhB,IAAI,EAAa,EAAE,CAAC,EAAE,CAAC;QAC1B,OAAO;IACT,CAAC;IAED,IAAI,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE;QACpB,KAAK,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,MAAM,CAAC,CAAC,OAAO,GAAG,KAAK,CAAC;QAC3C,KAAK,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,MAAM,CAAC,CAAC,WAAW,GAAG,QAAQ,EAAE,EAAY,CAAC;QAChE,KAAK,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,MAAM,CAAC,CAAC,QAAQ,GAAG,QAAQ,EAAE,QAAkB,CAAC;QACnE,KAAK,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,MAAM,CAAC,CAAC,KAAK,GAAG,KAAK,EAAE,OAAO,CAAC;IACpD,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type {\n RestrictedMessenger,\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n} from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport type {\n Caveat,\n GetPermissions,\n ValidPermission,\n} from '@metamask/permission-controller';\nimport {\n getSignatureOriginCaveat,\n getTransactionOriginCaveat,\n SnapEndowments,\n} from '@metamask/snaps-rpc-methods';\nimport type { Json, SnapId } from '@metamask/snaps-sdk';\nimport { HandlerType } from '@metamask/snaps-utils';\nimport { hasProperty, hexToBigInt } from '@metamask/utils';\n\nimport type { DeleteInterface } from '../interface';\nimport type { GetAllSnaps, HandleSnapRequest } from '../snaps';\nimport { getRunnableSnaps } from '../snaps';\nimport type {\n TransactionControllerUnapprovedTransactionAddedEvent,\n TransactionMeta,\n SignatureStateChange,\n SignatureControllerState,\n StateSignature,\n TransactionControllerTransactionStatusUpdatedEvent,\n} from '../types';\n\nconst controllerName = 'SnapInsightsController';\n\nexport type SnapInsightsControllerAllowedActions =\n | HandleSnapRequest\n | GetAllSnaps\n | GetPermissions\n | DeleteInterface;\n\nexport type SnapInsightsControllerGetStateAction = ControllerGetStateAction<\n typeof controllerName,\n SnapInsightsControllerState\n>;\n\nexport type SnapInsightsControllerActions =\n SnapInsightsControllerGetStateAction;\n\nexport type SnapInsightControllerStateChangeEvent = ControllerStateChangeEvent<\n typeof controllerName,\n SnapInsightsControllerState\n>;\n\nexport type SnapInsightControllerEvents = SnapInsightControllerStateChangeEvent;\n\nexport type SnapInsightsControllerAllowedEvents =\n | TransactionControllerUnapprovedTransactionAddedEvent\n | TransactionControllerTransactionStatusUpdatedEvent\n | SignatureStateChange;\n\nexport type SnapInsightsControllerMessenger = RestrictedMessenger<\n typeof controllerName,\n SnapInsightsControllerActions | SnapInsightsControllerAllowedActions,\n SnapInsightControllerEvents | SnapInsightsControllerAllowedEvents,\n SnapInsightsControllerAllowedActions['type'],\n SnapInsightsControllerAllowedEvents['type']\n>;\n\nexport type SnapInsight = {\n snapId: SnapId;\n interfaceId?: string | null;\n error?: string;\n loading: boolean;\n severity?: string;\n};\n\nexport type SnapInsightsControllerState = {\n insights: Record<string, Record<SnapId, SnapInsight>>;\n};\n\nexport type SnapInsightsControllerArgs = {\n messenger: SnapInsightsControllerMessenger;\n state?: SnapInsightsControllerState;\n};\n\ntype SnapWithPermission = {\n snapId: SnapId;\n permission: ValidPermission<string, Caveat<string, Json>>;\n};\n\n/**\n * Controller for monitoring for new transactions and signatures to provide insight for.\n */\nexport class SnapInsightsController extends BaseController<\n typeof controllerName,\n SnapInsightsControllerState,\n SnapInsightsControllerMessenger\n> {\n constructor({ messenger, state }: SnapInsightsControllerArgs) {\n super({\n messenger,\n metadata: {\n insights: { persist: false, anonymous: false },\n },\n name: controllerName,\n state: { insights: {}, ...state },\n });\n\n this.messagingSystem.subscribe(\n 'TransactionController:unapprovedTransactionAdded',\n this.#handleTransaction.bind(this),\n );\n\n this.messagingSystem.subscribe(\n 'TransactionController:transactionStatusUpdated',\n this.#handleTransactionStatusUpdate.bind(this),\n );\n\n this.messagingSystem.subscribe(\n 'SignatureController:stateChange',\n this.#handleSignatureStateChange.bind(this),\n );\n }\n\n /**\n * Check if an insight already exists for a given ID.\n *\n * @param id - The ID.\n * @returns True if the insight already exists, otherwise false.\n */\n #hasInsight(id: string) {\n return hasProperty(this.state.insights, id);\n }\n\n /**\n * Get a list of runnable Snaps that have a given permission.\n * Also includes the permission object itself.\n *\n * @param permissionName - The permission name.\n * @returns A list of objects containing Snap IDs and the permission object.\n */\n #getSnapsWithPermission(permissionName: string) {\n const allSnaps = this.messagingSystem.call('SnapController:getAll');\n const filteredSnaps = getRunnableSnaps(allSnaps);\n\n return filteredSnaps.reduce<SnapWithPermission[]>((accumulator, snap) => {\n const permissions = this.messagingSystem.call(\n 'PermissionController:getPermissions',\n snap.id,\n );\n if (permissions && hasProperty(permissions, permissionName)) {\n accumulator.push({\n snapId: snap.id,\n permission: permissions[permissionName],\n });\n }\n\n return accumulator;\n }, []);\n }\n\n /**\n * Handle a newly added unapproved transaction.\n * This function fetches insights from all available Snaps\n * and populates the insights state blob with the responses.\n *\n * @param transaction - The transaction object.\n */\n #handleTransaction(transaction: TransactionMeta) {\n const { id, txParams, chainId, origin } = transaction;\n\n // This assumes that the transactions are EVM-compatible for now.\n const caipChainId = `eip155:${hexToBigInt(chainId).toString(10)}`;\n\n const snaps = this.#getSnapsWithPermission(\n SnapEndowments.TransactionInsight,\n );\n\n snaps.forEach(({ snapId, permission }) => {\n const hasTransactionOriginCaveat = getTransactionOriginCaveat(permission);\n const transactionOrigin =\n hasTransactionOriginCaveat && origin ? origin : null;\n\n this.update((state) => {\n state.insights[id] ??= {};\n state.insights[id][snapId] = { snapId, loading: true };\n });\n\n this.#handleSnapRequest({\n snapId,\n handler: HandlerType.OnTransaction,\n params: {\n transaction: txParams,\n chainId: caipChainId,\n transactionOrigin,\n },\n })\n .then((response) =>\n this.#handleSnapResponse({\n id,\n snapId,\n response: response as Record<string, Json>,\n }),\n )\n .catch((error) => this.#handleSnapResponse({ id, snapId, error }));\n });\n }\n\n /**\n * Handle the stateChange event emitted by the SignatureController.\n * This function will remove existing insights from the state when applicable, as well as\n * trigger insight fetching for newly added signatures.\n *\n * @param state - The SignatureController state blob.\n */\n #handleSignatureStateChange(state: SignatureControllerState) {\n // If any IDs have disappeared since the last state update, the insight may be cleaned up.\n for (const id of Object.keys(this.state.insights)) {\n if (\n !hasProperty(state.unapprovedTypedMessages, id) &&\n !hasProperty(state.unapprovedPersonalMsgs, id)\n ) {\n this.#handleInsightCleanup(id);\n }\n }\n\n if (\n state.unapprovedPersonalMsgCount > 0 ||\n state.unapprovedTypedMessagesCount > 0\n ) {\n const snaps = this.#getSnapsWithPermission(\n SnapEndowments.SignatureInsight,\n );\n\n // This isn't very efficient, but SignatureController doesn't expose a better event for us to use yet.\n for (const personalSignature of Object.values(\n state.unapprovedPersonalMsgs,\n )) {\n this.#handleSignature(snaps, personalSignature);\n }\n\n for (const typedMessage of Object.values(state.unapprovedTypedMessages)) {\n this.#handleSignature(snaps, typedMessage);\n }\n }\n }\n\n /**\n * Handle a newly added unapproved signature.\n * This function fetches insights from all available Snaps\n * and populates the insights state blob with the responses.\n *\n * @param snaps - A list of Snaps to invoke.\n * @param signature - The signature object.\n */\n #handleSignature(snaps: SnapWithPermission[], signature: StateSignature) {\n const { id, msgParams } = signature;\n\n if (this.#hasInsight(id)) {\n return;\n }\n\n const { from, data, signatureMethod, origin } = msgParams;\n\n /**\n * Both eth_signTypedData_v3 and eth_signTypedData_v4 methods\n * need to be parsed because their data is stringified. All other\n * signature methods do not, so they are ignored.\n */\n const shouldParse =\n signatureMethod === 'eth_signTypedData_v3' ||\n signatureMethod === 'eth_signTypedData_v4';\n\n const payload = {\n from,\n data: shouldParse ? JSON.parse(data as string) : data,\n signatureMethod,\n };\n\n snaps.forEach(({ snapId, permission }) => {\n const hasSignatureOriginCaveat = getSignatureOriginCaveat(permission);\n const signatureOrigin =\n origin && hasSignatureOriginCaveat ? origin : null;\n\n this.update((state) => {\n state.insights[id] ??= {};\n state.insights[id][snapId] = { snapId, loading: true };\n });\n\n this.#handleSnapRequest({\n snapId,\n handler: HandlerType.OnSignature,\n params: { signature: payload, signatureOrigin },\n })\n .then((response) =>\n this.#handleSnapResponse({\n id,\n snapId,\n response: response as Record<string, Json>,\n }),\n )\n .catch((error) => this.#handleSnapResponse({ id, snapId, error }));\n });\n }\n\n /**\n * Handle the transactionStatusUpdated event emitted by the TransactionController.\n * This function will remove insights for the transaction in question\n * once the transaction status has changed from unapproved.\n *\n * @param args - An options bag.\n * @param args.transactionMeta - The transaction.\n */\n #handleTransactionStatusUpdate({\n transactionMeta,\n }: {\n transactionMeta: TransactionMeta;\n }) {\n if (transactionMeta.status !== 'unapproved') {\n this.#handleInsightCleanup(transactionMeta.id);\n }\n }\n\n #handleInsightCleanup(id: string) {\n if (!this.#hasInsight(id)) {\n return;\n }\n\n // Delete interfaces from interface controller.\n Object.values(this.state.insights[id])\n .filter((insight) => insight.interfaceId)\n .forEach((insight) => {\n this.messagingSystem.call(\n 'SnapInterfaceController:deleteInterface',\n insight.interfaceId as string,\n );\n });\n\n this.update((state) => {\n delete state.insights[id];\n });\n }\n\n /**\n * Handle sending a request to a given Snap with a given payload.\n *\n * @param args - An options bag.\n * @param args.snapId - The Snap ID.\n * @param args.handler - The handler to invoke.\n * @param args.params - The JSON-RPC params to send.\n * @returns The response from the Snap.\n */\n async #handleSnapRequest({\n snapId,\n handler,\n params,\n }: {\n snapId: SnapId;\n handler: HandlerType.OnTransaction | HandlerType.OnSignature;\n params: Record<string, Json>;\n }) {\n return this.messagingSystem.call('SnapController:handleRequest', {\n snapId,\n origin: 'metamask',\n handler,\n request: {\n method: '',\n params,\n },\n });\n }\n\n /**\n * Handle response from a given Snap by persisting the response or error in state.\n *\n * @param args - An options bag.\n * @param args.id - The transaction or signature ID.\n * @param args.snapId - The Snap ID.\n * @param args.response - An optional response object returned by the Snap.\n * @param args.error - An optional error returned by the Snap.\n */\n #handleSnapResponse({\n id,\n snapId,\n response,\n error,\n }: {\n id: string;\n snapId: SnapId;\n response?: Record<string, Json>;\n error?: Error;\n }) {\n // If the insight has been cleaned up already, we can skip setting the state.\n // This may happen if a user accepts/rejects a transaction/signature faster than the Snap responds.\n if (!this.#hasInsight(id)) {\n return;\n }\n\n this.update((state) => {\n state.insights[id][snapId].loading = false;\n state.insights[id][snapId].interfaceId = response?.id as string;\n state.insights[id][snapId].severity = response?.severity as string;\n state.insights[id][snapId].error = error?.message;\n });\n }\n}\n"]}
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,eAA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AAM,CAAC,CAAC,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"]}