@metamask/snaps-jest 6.0.2 → 7.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 (138) hide show
  1. package/CHANGELOG.md +12 -1
  2. package/README.md +100 -7
  3. package/dist/{chunk-6RXFM4YC.js → chunk-2JAGD4N6.js} +3 -3
  4. package/dist/{chunk-7YD4IW43.mjs → chunk-3M4GRUMH.mjs} +3 -6
  5. package/dist/chunk-3M4GRUMH.mjs.map +1 -0
  6. package/dist/{chunk-7BFTEFLS.mjs → chunk-5U5WB3SM.mjs} +5 -3
  7. package/dist/chunk-5U5WB3SM.mjs.map +1 -0
  8. package/dist/chunk-6POKT4OO.js +127 -0
  9. package/dist/chunk-6POKT4OO.js.map +1 -0
  10. package/dist/{chunk-7VILST6M.mjs → chunk-BVGI3E45.mjs} +2 -2
  11. package/dist/chunk-CKRORVDW.js +1 -0
  12. package/dist/{chunk-6HW5NGCB.js → chunk-DTDYOBCI.js} +3 -3
  13. package/dist/{chunk-WIFOID2P.mjs → chunk-EDEJD326.mjs} +20 -10
  14. package/dist/chunk-EDEJD326.mjs.map +1 -0
  15. package/dist/{chunk-B4QZXXQY.js → chunk-FIZAYEHV.js} +4 -4
  16. package/dist/chunk-I5P52IMF.mjs +223 -0
  17. package/dist/chunk-I5P52IMF.mjs.map +1 -0
  18. package/dist/{chunk-T2BE4O5H.js → chunk-IDGD7TZ7.js} +33 -23
  19. package/dist/chunk-IDGD7TZ7.js.map +1 -0
  20. package/dist/{chunk-BS24WMRW.mjs → chunk-LG3VKXGH.mjs} +2 -2
  21. package/dist/{chunk-C2ONPIIB.js → chunk-MCYTJUDG.js} +10 -15
  22. package/dist/chunk-MCYTJUDG.js.map +1 -0
  23. package/dist/chunk-PVMIH6OB.mjs +127 -0
  24. package/dist/chunk-PVMIH6OB.mjs.map +1 -0
  25. package/dist/chunk-S2HLITUN.js +1 -0
  26. package/dist/{chunk-ISWZ7XZ5.js → chunk-SB5EPHE3.js} +5 -3
  27. package/dist/chunk-SB5EPHE3.js.map +1 -0
  28. package/dist/{chunk-HBLJOACO.mjs → chunk-TAIJXTLU.mjs} +2 -10
  29. package/dist/chunk-TAIJXTLU.mjs.map +1 -0
  30. package/dist/chunk-TGZ7WOTJ.mjs +1 -0
  31. package/dist/chunk-UDOXICJK.mjs +1 -0
  32. package/dist/{chunk-3HU56QS3.mjs → chunk-VSUNWJMQ.mjs} +8 -13
  33. package/dist/chunk-VSUNWJMQ.mjs.map +1 -0
  34. package/dist/{chunk-TO46ICOZ.js → chunk-WMLSD6B5.js} +3 -6
  35. package/dist/chunk-WMLSD6B5.js.map +1 -0
  36. package/dist/{chunk-3SNZ4SPY.mjs → chunk-X5IPMTHO.mjs} +2 -2
  37. package/dist/chunk-Y4DKEF7Y.js +223 -0
  38. package/dist/chunk-Y4DKEF7Y.js.map +1 -0
  39. package/dist/{chunk-7J34R6YW.mjs → chunk-YEVKBYKO.mjs} +35 -25
  40. package/dist/chunk-YEVKBYKO.mjs.map +1 -0
  41. package/dist/{chunk-5PLDD7ZC.js → chunk-Z35PCKFD.js} +24 -14
  42. package/dist/chunk-Z35PCKFD.js.map +1 -0
  43. package/dist/{chunk-LXSNRZV4.js → chunk-ZWN4SO2V.js} +5 -13
  44. package/dist/chunk-ZWN4SO2V.js.map +1 -0
  45. package/dist/environment.js +13 -14
  46. package/dist/environment.mjs +12 -13
  47. package/dist/global.js +2 -0
  48. package/dist/global.js.map +1 -0
  49. package/dist/global.mjs +2 -0
  50. package/dist/global.mjs.map +1 -0
  51. package/dist/helpers.js +13 -14
  52. package/dist/helpers.mjs +12 -13
  53. package/dist/index.js +16 -16
  54. package/dist/index.mjs +15 -15
  55. package/dist/internals/index.js +27 -14
  56. package/dist/internals/index.mjs +30 -17
  57. package/dist/internals/request.js +12 -11
  58. package/dist/internals/request.mjs +13 -12
  59. package/dist/internals/simulation/controllers.js +6 -7
  60. package/dist/internals/simulation/controllers.mjs +5 -6
  61. package/dist/internals/simulation/index.js +17 -10
  62. package/dist/internals/simulation/index.mjs +17 -10
  63. package/dist/internals/simulation/interface.js +11 -3
  64. package/dist/internals/simulation/interface.mjs +12 -4
  65. package/dist/internals/simulation/methods/hooks/index.js +4 -10
  66. package/dist/internals/simulation/methods/hooks/index.mjs +3 -9
  67. package/dist/internals/simulation/methods/hooks/notifications.js +1 -1
  68. package/dist/internals/simulation/methods/hooks/notifications.mjs +1 -1
  69. package/dist/internals/simulation/methods/hooks/show-dialog.js +1 -1
  70. package/dist/internals/simulation/methods/hooks/show-dialog.mjs +1 -1
  71. package/dist/internals/simulation/methods/hooks/state.js +3 -3
  72. package/dist/internals/simulation/methods/hooks/state.mjs +2 -2
  73. package/dist/internals/simulation/methods/index.js +5 -6
  74. package/dist/internals/simulation/methods/index.mjs +4 -5
  75. package/dist/internals/simulation/methods/specifications.js +5 -6
  76. package/dist/internals/simulation/methods/specifications.mjs +4 -5
  77. package/dist/internals/simulation/simulation.js +8 -9
  78. package/dist/internals/simulation/simulation.mjs +7 -8
  79. package/dist/internals/simulation/store/index.js +2 -2
  80. package/dist/internals/simulation/store/index.mjs +1 -1
  81. package/dist/internals/simulation/store/store.js +2 -2
  82. package/dist/internals/simulation/store/store.mjs +1 -1
  83. package/dist/internals/structs.js +6 -2
  84. package/dist/internals/structs.mjs +5 -1
  85. package/dist/matchers.js +13 -14
  86. package/dist/matchers.mjs +12 -13
  87. package/dist/setup.js +12 -13
  88. package/dist/setup.mjs +12 -13
  89. package/dist/tsconfig.build.tsbuildinfo +1 -1
  90. package/dist/types/global.d.ts +69 -0
  91. package/dist/types/index.d.ts +1 -0
  92. package/dist/types/internals/request.d.ts +13 -4
  93. package/dist/types/internals/simulation/interface.d.ts +47 -4
  94. package/dist/types/internals/simulation/methods/hooks/index.d.ts +0 -1
  95. package/dist/types/internals/simulation/methods/hooks/state.d.ts +2 -1
  96. package/dist/types/internals/simulation/store/store.d.ts +1 -2
  97. package/dist/types/internals/structs.d.ts +79 -156
  98. package/dist/types/types.d.ts +42 -21
  99. package/package.json +6 -6
  100. package/dist/chunk-2X23DUDP.mjs +0 -22
  101. package/dist/chunk-2X23DUDP.mjs.map +0 -1
  102. package/dist/chunk-3HU56QS3.mjs.map +0 -1
  103. package/dist/chunk-5PLDD7ZC.js.map +0 -1
  104. package/dist/chunk-6MVV44M5.mjs +0 -76
  105. package/dist/chunk-6MVV44M5.mjs.map +0 -1
  106. package/dist/chunk-7BFTEFLS.mjs.map +0 -1
  107. package/dist/chunk-7J34R6YW.mjs.map +0 -1
  108. package/dist/chunk-7YD4IW43.mjs.map +0 -1
  109. package/dist/chunk-C2ONPIIB.js.map +0 -1
  110. package/dist/chunk-HBLJOACO.mjs.map +0 -1
  111. package/dist/chunk-HNH5UAKZ.js +0 -80
  112. package/dist/chunk-HNH5UAKZ.js.map +0 -1
  113. package/dist/chunk-ISWZ7XZ5.js.map +0 -1
  114. package/dist/chunk-LXSNRZV4.js.map +0 -1
  115. package/dist/chunk-LYK6EGZU.mjs +0 -80
  116. package/dist/chunk-LYK6EGZU.mjs.map +0 -1
  117. package/dist/chunk-RD7GQCPL.js +0 -22
  118. package/dist/chunk-RD7GQCPL.js.map +0 -1
  119. package/dist/chunk-T2BE4O5H.js.map +0 -1
  120. package/dist/chunk-TO46ICOZ.js.map +0 -1
  121. package/dist/chunk-U5BLLHIU.js +0 -1
  122. package/dist/chunk-V6LFAN3U.mjs +0 -1
  123. package/dist/chunk-WIFOID2P.mjs.map +0 -1
  124. package/dist/chunk-ZAQZRYPW.js +0 -76
  125. package/dist/chunk-ZAQZRYPW.js.map +0 -1
  126. package/dist/internals/simulation/methods/hooks/encryption.js +0 -10
  127. package/dist/internals/simulation/methods/hooks/encryption.mjs +0 -10
  128. package/dist/types/internals/simulation/methods/hooks/encryption.d.ts +0 -29
  129. /package/dist/{chunk-6RXFM4YC.js.map → chunk-2JAGD4N6.js.map} +0 -0
  130. /package/dist/{chunk-7VILST6M.mjs.map → chunk-BVGI3E45.mjs.map} +0 -0
  131. /package/dist/{chunk-U5BLLHIU.js.map → chunk-CKRORVDW.js.map} +0 -0
  132. /package/dist/{chunk-6HW5NGCB.js.map → chunk-DTDYOBCI.js.map} +0 -0
  133. /package/dist/{chunk-B4QZXXQY.js.map → chunk-FIZAYEHV.js.map} +0 -0
  134. /package/dist/{chunk-BS24WMRW.mjs.map → chunk-LG3VKXGH.mjs.map} +0 -0
  135. /package/dist/{internals/simulation/methods/hooks/encryption.js.map → chunk-S2HLITUN.js.map} +0 -0
  136. /package/dist/{chunk-V6LFAN3U.mjs.map → chunk-TGZ7WOTJ.mjs.map} +0 -0
  137. /package/dist/{internals/simulation/methods/hooks/encryption.mjs.map → chunk-UDOXICJK.mjs.map} +0 -0
  138. /package/dist/{chunk-3SNZ4SPY.mjs.map → chunk-X5IPMTHO.mjs.map} +0 -0
@@ -0,0 +1,223 @@
1
+ import {
2
+ getCurrentInterface,
3
+ resolveInterface,
4
+ setInterface
5
+ } from "./chunk-74TIKA2T.mjs";
6
+
7
+ // src/internals/simulation/interface.ts
8
+ import {
9
+ ButtonType,
10
+ DialogType,
11
+ NodeType,
12
+ UserInputEventType,
13
+ assert
14
+ } from "@metamask/snaps-sdk";
15
+ import { HandlerType, hasChildren } from "@metamask/snaps-utils";
16
+ import { call, put, select, take } from "redux-saga/effects";
17
+ function getInterfaceResponse(runSaga, type, content, interfaceActions) {
18
+ switch (type) {
19
+ case DialogType.Alert:
20
+ return {
21
+ ...interfaceActions,
22
+ type,
23
+ content,
24
+ ok: resolveWith(runSaga, null)
25
+ };
26
+ case DialogType.Confirmation:
27
+ return {
28
+ ...interfaceActions,
29
+ type,
30
+ content,
31
+ ok: resolveWith(runSaga, true),
32
+ cancel: resolveWith(runSaga, false)
33
+ };
34
+ case DialogType.Prompt:
35
+ return {
36
+ ...interfaceActions,
37
+ type,
38
+ content,
39
+ ok: resolveWithInput(runSaga),
40
+ cancel: resolveWith(runSaga, null)
41
+ };
42
+ default:
43
+ throw new Error(`Unknown or unsupported dialog type: "${String(type)}".`);
44
+ }
45
+ }
46
+ function resolveWith(runSaga, value) {
47
+ function* resolveWithSaga() {
48
+ yield put(resolveInterface(value));
49
+ }
50
+ return async () => {
51
+ await runSaga(resolveWithSaga).toPromise();
52
+ };
53
+ }
54
+ function resolveWithInput(runSaga) {
55
+ function* resolveWithSaga(value) {
56
+ yield put(resolveInterface(value));
57
+ }
58
+ return async (value = "") => {
59
+ await runSaga(resolveWithSaga, value).toPromise();
60
+ };
61
+ }
62
+ function* getStoredInterface(controllerMessenger, snapId) {
63
+ const currentInterface = yield select(getCurrentInterface);
64
+ if (currentInterface) {
65
+ const { content: content2 } = controllerMessenger.call(
66
+ "SnapInterfaceController:getInterface",
67
+ snapId,
68
+ currentInterface.id
69
+ );
70
+ return { ...currentInterface, content: content2 };
71
+ }
72
+ const { payload } = yield take(setInterface.type);
73
+ const { content } = controllerMessenger.call(
74
+ "SnapInterfaceController:getInterface",
75
+ snapId,
76
+ payload.id
77
+ );
78
+ return { ...payload, content };
79
+ }
80
+ function getElement(content, name) {
81
+ const { type } = content;
82
+ if ((type === NodeType.Button || type === NodeType.Input) && content.name === name) {
83
+ return { element: content };
84
+ }
85
+ if (hasChildren(content)) {
86
+ for (const element of content.children) {
87
+ const result = getElement(element, name);
88
+ const form = type === NodeType.Form ? content.name : result?.form;
89
+ if (result) {
90
+ return { element: result.element, form };
91
+ }
92
+ }
93
+ }
94
+ return void 0;
95
+ }
96
+ async function clickElement(controllerMessenger, id, content, snapId, name) {
97
+ const result = getElement(content, name);
98
+ assert(
99
+ result !== void 0 && result.element.type === NodeType.Button,
100
+ "No button found in the interface."
101
+ );
102
+ if (result.form && result.element.buttonType === ButtonType.Submit) {
103
+ const { state } = controllerMessenger.call(
104
+ "SnapInterfaceController:getInterface",
105
+ snapId,
106
+ id
107
+ );
108
+ await controllerMessenger.call(
109
+ "ExecutionService:handleRpcRequest",
110
+ snapId,
111
+ {
112
+ origin: "",
113
+ handler: HandlerType.OnUserInput,
114
+ request: {
115
+ jsonrpc: "2.0",
116
+ method: " ",
117
+ params: {
118
+ event: {
119
+ type: UserInputEventType.FormSubmitEvent,
120
+ name: result.form,
121
+ value: state[result.form]
122
+ },
123
+ id
124
+ }
125
+ }
126
+ }
127
+ );
128
+ return;
129
+ }
130
+ if (result.element.buttonType !== ButtonType.Submit) {
131
+ await controllerMessenger.call(
132
+ "ExecutionService:handleRpcRequest",
133
+ snapId,
134
+ {
135
+ origin: "",
136
+ handler: HandlerType.OnUserInput,
137
+ request: {
138
+ jsonrpc: "2.0",
139
+ method: " ",
140
+ params: {
141
+ event: {
142
+ type: UserInputEventType.ButtonClickEvent,
143
+ name: result.element.name
144
+ },
145
+ id
146
+ }
147
+ }
148
+ }
149
+ );
150
+ }
151
+ }
152
+ function mergeValue(state, name, value, form) {
153
+ if (form) {
154
+ return {
155
+ ...state,
156
+ [form]: {
157
+ ...state[form],
158
+ [name]: value
159
+ }
160
+ };
161
+ }
162
+ return { ...state, [name]: value };
163
+ }
164
+ async function typeInField(controllerMessenger, id, content, snapId, name, value) {
165
+ const result = getElement(content, name);
166
+ assert(
167
+ result !== void 0 && result.element.type === NodeType.Input,
168
+ "No input found in the interface."
169
+ );
170
+ const { state } = controllerMessenger.call(
171
+ "SnapInterfaceController:getInterface",
172
+ snapId,
173
+ id
174
+ );
175
+ const newState = mergeValue(state, name, value, result.form);
176
+ controllerMessenger.call(
177
+ "SnapInterfaceController:updateInterfaceState",
178
+ id,
179
+ newState
180
+ );
181
+ await controllerMessenger.call("ExecutionService:handleRpcRequest", snapId, {
182
+ origin: "",
183
+ handler: HandlerType.OnUserInput,
184
+ request: {
185
+ jsonrpc: "2.0",
186
+ method: " ",
187
+ params: {
188
+ event: {
189
+ type: UserInputEventType.InputChangeEvent,
190
+ name: result.element.name,
191
+ value
192
+ },
193
+ id
194
+ }
195
+ }
196
+ });
197
+ }
198
+ function* getInterface(runSaga, snapId, controllerMessenger) {
199
+ const { type, id, content } = yield call(
200
+ getStoredInterface,
201
+ controllerMessenger,
202
+ snapId
203
+ );
204
+ const interfaceActions = {
205
+ clickElement: async (name) => {
206
+ await clickElement(controllerMessenger, id, content, snapId, name);
207
+ },
208
+ typeInField: async (name, value) => {
209
+ await typeInField(controllerMessenger, id, content, snapId, name, value);
210
+ }
211
+ };
212
+ return getInterfaceResponse(runSaga, type, content, interfaceActions);
213
+ }
214
+
215
+ export {
216
+ getInterfaceResponse,
217
+ getElement,
218
+ clickElement,
219
+ mergeValue,
220
+ typeInField,
221
+ getInterface
222
+ };
223
+ //# sourceMappingURL=chunk-I5P52IMF.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/internals/simulation/interface.ts"],"sourcesContent":["import type {\n Button,\n Component,\n FormState,\n Input,\n InterfaceState,\n SnapId,\n} from '@metamask/snaps-sdk';\nimport {\n ButtonType,\n DialogType,\n NodeType,\n UserInputEventType,\n assert,\n} from '@metamask/snaps-sdk';\nimport { HandlerType, hasChildren } from '@metamask/snaps-utils';\nimport type { PayloadAction } from '@reduxjs/toolkit';\nimport { type SagaIterator } from 'redux-saga';\nimport { call, put, select, take } from 'redux-saga/effects';\n\nimport type { SnapInterface, SnapInterfaceActions } from '../../types';\nimport type { RootControllerMessenger } from './controllers';\nimport type { Interface, RunSagaFunction } from './store';\nimport { getCurrentInterface, resolveInterface, setInterface } from './store';\n\n/**\n * Get a user interface object from a type and content object.\n *\n * @param runSaga - A function to run a saga outside the usual Redux flow.\n * @param type - The type of the interface.\n * @param content - The content to show in the interface.\n * @param interfaceActions - The actions to interact with the interface.\n * @returns The user interface object.\n */\nexport function getInterfaceResponse(\n runSaga: RunSagaFunction,\n type: DialogType,\n content: Component,\n interfaceActions: SnapInterfaceActions,\n): SnapInterface {\n switch (type) {\n case DialogType.Alert:\n return {\n ...interfaceActions,\n type,\n content,\n ok: resolveWith(runSaga, null),\n };\n\n case DialogType.Confirmation:\n return {\n ...interfaceActions,\n type,\n content,\n\n ok: resolveWith(runSaga, true),\n cancel: resolveWith(runSaga, false),\n };\n\n case DialogType.Prompt:\n return {\n ...interfaceActions,\n type,\n content,\n\n ok: resolveWithInput(runSaga),\n cancel: resolveWith(runSaga, null),\n };\n\n default:\n throw new Error(`Unknown or unsupported dialog type: \"${String(type)}\".`);\n }\n}\n\n/**\n * Resolve the current user interface with the given value. This returns a\n * function that can be used to resolve the user interface.\n *\n * @param runSaga - A function to run a saga outside the usual Redux flow.\n * @param value - The value to resolve the user interface with.\n * @returns A function that can be used to resolve the user interface.\n */\nfunction resolveWith(runSaga: RunSagaFunction, value: unknown) {\n /**\n * Resolve the current user interface with the given value.\n *\n * @yields Puts the resolve user interface action.\n */\n function* resolveWithSaga(): SagaIterator {\n yield put(resolveInterface(value));\n }\n\n return async () => {\n await runSaga(resolveWithSaga).toPromise();\n };\n}\n\n/**\n * Resolve the current user interface with the provided input. This returns a\n * function that can be used to resolve the user interface.\n *\n * @param runSaga - A function to run a saga outside the usual Redux flow.\n * @returns A function that can be used to resolve the user interface.\n */\nfunction resolveWithInput(runSaga: RunSagaFunction) {\n /**\n * Resolve the current user interface with the given value.\n *\n * @param value - The value to resolve the user interface with.\n * @yields Puts the resolve user interface action.\n */\n function* resolveWithSaga(value: string): SagaIterator {\n yield put(resolveInterface(value));\n }\n\n return async (value = '') => {\n await runSaga(resolveWithSaga, value).toPromise();\n };\n}\n\n/**\n * Get the stored user interface from the store.\n *\n * @param controllerMessenger - The controller messenger used to call actions.\n * @param snapId - The Snap ID.\n * @yields Takes the set interface action.\n * @returns The user interface object.\n */\nfunction* getStoredInterface(\n controllerMessenger: RootControllerMessenger,\n snapId: SnapId,\n): SagaIterator<Interface & { content: Component }> {\n const currentInterface: Interface | null = yield select(getCurrentInterface);\n\n if (currentInterface) {\n const { content } = controllerMessenger.call(\n 'SnapInterfaceController:getInterface',\n snapId,\n currentInterface.id,\n );\n\n return { ...currentInterface, content };\n }\n\n const { payload }: PayloadAction<Interface> = yield take(setInterface.type);\n\n const { content } = controllerMessenger.call(\n 'SnapInterfaceController:getInterface',\n snapId,\n payload.id,\n );\n\n return { ...payload, content };\n}\n\n/**\n * Get a Button or an Input from an interface.\n *\n * @param content - The interface content.\n * @param name - The element name.\n * @returns An object containing the element and the form name if it's contained in a form, otherwise undefined.\n */\nexport function getElement(\n content: Component,\n name: string,\n):\n | {\n element: Button | Input;\n form?: string;\n }\n | undefined {\n const { type } = content;\n\n if (\n (type === NodeType.Button || type === NodeType.Input) &&\n content.name === name\n ) {\n return { element: content };\n }\n\n if (hasChildren(content)) {\n for (const element of content.children) {\n const result = getElement(element, name);\n const form = type === NodeType.Form ? content.name : result?.form;\n\n if (result) {\n return { element: result.element, form };\n }\n }\n }\n\n return undefined;\n}\n\n/**\n * Click on an element of the Snap interface.\n *\n * @param controllerMessenger - The controller messenger used to call actions.\n * @param id - The interface ID.\n * @param content - The interface content.\n * @param snapId - The Snap ID.\n * @param name - The element name.\n */\nexport async function clickElement(\n controllerMessenger: RootControllerMessenger,\n id: string,\n content: Component,\n snapId: SnapId,\n name: string,\n): Promise<void> {\n const result = getElement(content, name);\n assert(\n result !== undefined && result.element.type === NodeType.Button,\n 'No button found in the interface.',\n );\n\n if (result.form && result.element.buttonType === ButtonType.Submit) {\n const { state } = controllerMessenger.call(\n 'SnapInterfaceController:getInterface',\n snapId,\n id,\n );\n\n await controllerMessenger.call(\n 'ExecutionService:handleRpcRequest',\n snapId,\n {\n origin: '',\n handler: HandlerType.OnUserInput,\n request: {\n jsonrpc: '2.0',\n method: ' ',\n params: {\n event: {\n type: UserInputEventType.FormSubmitEvent,\n name: result.form,\n value: state[result.form],\n },\n id,\n },\n },\n },\n );\n\n return;\n }\n\n if (result.element.buttonType !== ButtonType.Submit) {\n await controllerMessenger.call(\n 'ExecutionService:handleRpcRequest',\n snapId,\n {\n origin: '',\n handler: HandlerType.OnUserInput,\n request: {\n jsonrpc: '2.0',\n method: ' ',\n params: {\n event: {\n type: UserInputEventType.ButtonClickEvent,\n name: result.element.name,\n },\n id,\n },\n },\n },\n );\n }\n}\n\n/**\n * Merge a value in the interface state.\n *\n * @param state - The actual interface state.\n * @param name - The component name that changed value.\n * @param value - The new value.\n * @param form - The form name if the element is in one.\n * @returns The state with the merged value.\n */\nexport function mergeValue(\n state: InterfaceState,\n name: string,\n value: string | null,\n form?: string,\n): InterfaceState {\n if (form) {\n return {\n ...state,\n [form]: {\n ...(state[form] as FormState),\n [name]: value,\n },\n };\n }\n\n return { ...state, [name]: value };\n}\n\n/**\n * Type a value in an interface element.\n *\n * @param controllerMessenger - The controller messenger used to call actions.\n * @param id - The interface ID.\n * @param content - The interface Components.\n * @param snapId - The Snap ID.\n * @param name - The element name.\n * @param value - The value to type in the element.\n */\nexport async function typeInField(\n controllerMessenger: RootControllerMessenger,\n id: string,\n content: Component,\n snapId: SnapId,\n name: string,\n value: string,\n) {\n const result = getElement(content, name);\n\n assert(\n result !== undefined && result.element.type === NodeType.Input,\n 'No input found in the interface.',\n );\n\n const { state } = controllerMessenger.call(\n 'SnapInterfaceController:getInterface',\n snapId,\n id,\n );\n\n const newState = mergeValue(state, name, value, result.form);\n\n controllerMessenger.call(\n 'SnapInterfaceController:updateInterfaceState',\n id,\n newState,\n );\n\n await controllerMessenger.call('ExecutionService:handleRpcRequest', snapId, {\n origin: '',\n handler: HandlerType.OnUserInput,\n request: {\n jsonrpc: '2.0',\n method: ' ',\n params: {\n event: {\n type: UserInputEventType.InputChangeEvent,\n name: result.element.name,\n value,\n },\n id,\n },\n },\n });\n}\n\n/**\n * Get a user interface object from a Snap.\n *\n * @param runSaga - A function to run a saga outside the usual Redux flow.\n * @param snapId - The Snap ID.\n * @param controllerMessenger - The controller messenger used to call actions.\n * @yields Takes the set interface action.\n * @returns The user interface object.\n */\nexport function* getInterface(\n runSaga: RunSagaFunction,\n snapId: SnapId,\n controllerMessenger: RootControllerMessenger,\n): SagaIterator<SnapInterface> {\n const { type, id, content } = yield call(\n getStoredInterface,\n controllerMessenger,\n snapId,\n );\n\n const interfaceActions = {\n clickElement: async (name: string) => {\n await clickElement(controllerMessenger, id, content, snapId, name);\n },\n typeInField: async (name: string, value: string) => {\n await typeInField(controllerMessenger, id, content, snapId, name, value);\n },\n };\n\n return getInterfaceResponse(runSaga, type, content, interfaceActions);\n}\n"],"mappings":";;;;;;;AAQA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,aAAa,mBAAmB;AAGzC,SAAS,MAAM,KAAK,QAAQ,YAAY;AAgBjC,SAAS,qBACd,SACA,MACA,SACA,kBACe;AACf,UAAQ,MAAM;AAAA,IACZ,KAAK,WAAW;AACd,aAAO;AAAA,QACL,GAAG;AAAA,QACH;AAAA,QACA;AAAA,QACA,IAAI,YAAY,SAAS,IAAI;AAAA,MAC/B;AAAA,IAEF,KAAK,WAAW;AACd,aAAO;AAAA,QACL,GAAG;AAAA,QACH;AAAA,QACA;AAAA,QAEA,IAAI,YAAY,SAAS,IAAI;AAAA,QAC7B,QAAQ,YAAY,SAAS,KAAK;AAAA,MACpC;AAAA,IAEF,KAAK,WAAW;AACd,aAAO;AAAA,QACL,GAAG;AAAA,QACH;AAAA,QACA;AAAA,QAEA,IAAI,iBAAiB,OAAO;AAAA,QAC5B,QAAQ,YAAY,SAAS,IAAI;AAAA,MACnC;AAAA,IAEF;AACE,YAAM,IAAI,MAAM,wCAAwC,OAAO,IAAI,CAAC,IAAI;AAAA,EAC5E;AACF;AAUA,SAAS,YAAY,SAA0B,OAAgB;AAM7D,YAAU,kBAAgC;AACxC,UAAM,IAAI,iBAAiB,KAAK,CAAC;AAAA,EACnC;AAEA,SAAO,YAAY;AACjB,UAAM,QAAQ,eAAe,EAAE,UAAU;AAAA,EAC3C;AACF;AASA,SAAS,iBAAiB,SAA0B;AAOlD,YAAU,gBAAgB,OAA6B;AACrD,UAAM,IAAI,iBAAiB,KAAK,CAAC;AAAA,EACnC;AAEA,SAAO,OAAO,QAAQ,OAAO;AAC3B,UAAM,QAAQ,iBAAiB,KAAK,EAAE,UAAU;AAA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IAAI;AAE3D,sBAAoB;AAAA,IAClB;AAAA,IACA;AAAA,IACA;AAAA,EACF;AAEA,QAAM,oBAAoB,KAAK,qCAAqC,QAAQ;AAAA,IAC1E,QAAQ;AAAA,IACR,SAAS,YAAY;AAAA,IACrB,SAAS;AAAA,MACP,SAAS;AAAA,MACT,QAAQ;AAAA,MACR,QAAQ;AAAA,QACN,OAAO;AAAA,UACL,MAAM,mBAAmB;AAAA,UACzB,MAAM,OAAO,QAAQ;AAAA,UACrB;AAAA,QACF;AAAA,QACA;AAAA,MACF;AAAA,IACF;AAAA,EACF,CAAC;AACH;AAWO,UAAU,aACf,SACA,QACA,qBAC6B;AAC7B,QAAM,EAAE,MAAM,IAAI,QAAQ,IAAI,MAAM;AAAA,IAClC;AAAA,IACA;AAAA,IACA;AAAA,EACF;AAEA,QAAM,mBAAmB;AAAA,IACvB,cAAc,OAAO,SAAiB;AACpC,YAAM,aAAa,qBAAqB,IAAI,SAAS,QAAQ,IAAI;AAAA,IACnE;AAAA,IACA,aAAa,OAAO,MAAc,UAAkB;AAClD,YAAM,YAAY,qBAAqB,IAAI,SAAS,QAAQ,MAAM,KAAK;AAAA,IACzE;AAAA,EACF;AAEA,SAAO,qBAAqB,SAAS,MAAM,SAAS,gBAAgB;AACtE;","names":["content"]}
@@ -27,6 +27,7 @@ var _crypto = require('crypto');
27
27
 
28
28
 
29
29
 
30
+
30
31
  var _superstruct = require('superstruct');
31
32
  var BytesLikeStruct = _superstruct.union.call(void 0, [
32
33
  _superstruct.bigint.call(void 0, ),
@@ -197,30 +198,39 @@ var JsonRpcMockOptionsStruct = _superstruct.object.call(void 0, {
197
198
  var InterfaceStruct = _superstruct.type.call(void 0, {
198
199
  content: _superstruct.optional.call(void 0, _snapssdk.ComponentStruct)
199
200
  });
200
- var SnapResponseStruct = _superstruct.assign.call(void 0,
201
- InterfaceStruct,
201
+ var SnapResponseWithoutInterfaceStruct = _superstruct.object.call(void 0, {
202
+ id: _superstruct.string.call(void 0, ),
203
+ response: _superstruct.union.call(void 0, [
204
+ _superstruct.object.call(void 0, {
205
+ result: _utils.JsonStruct
206
+ }),
207
+ _superstruct.object.call(void 0, {
208
+ error: _utils.JsonStruct
209
+ })
210
+ ]),
211
+ notifications: _superstruct.array.call(void 0,
212
+ _superstruct.object.call(void 0, {
213
+ id: _superstruct.string.call(void 0, ),
214
+ message: _superstruct.string.call(void 0, ),
215
+ type: _superstruct.union.call(void 0, [
216
+ _snapssdk.enumValue.call(void 0, _snapssdk.NotificationType.InApp),
217
+ _snapssdk.enumValue.call(void 0, _snapssdk.NotificationType.Native)
218
+ ])
219
+ })
220
+ )
221
+ });
222
+ var SnapResponseWithInterfaceStruct = _superstruct.assign.call(void 0,
223
+ SnapResponseWithoutInterfaceStruct,
202
224
  _superstruct.object.call(void 0, {
203
- id: _superstruct.string.call(void 0, ),
204
- response: _superstruct.union.call(void 0, [
205
- _superstruct.object.call(void 0, {
206
- result: _utils.JsonStruct
207
- }),
208
- _superstruct.object.call(void 0, {
209
- error: _utils.JsonStruct
210
- })
211
- ]),
212
- notifications: _superstruct.array.call(void 0,
213
- _superstruct.object.call(void 0, {
214
- id: _superstruct.string.call(void 0, ),
215
- message: _superstruct.string.call(void 0, ),
216
- type: _superstruct.union.call(void 0, [
217
- _snapssdk.enumValue.call(void 0, _snapssdk.NotificationType.InApp),
218
- _snapssdk.enumValue.call(void 0, _snapssdk.NotificationType.Native)
219
- ])
220
- })
221
- )
225
+ getInterface: _superstruct.func.call(void 0, )
222
226
  })
223
227
  );
228
+ var SnapResponseStruct = _superstruct.union.call(void 0, [
229
+ SnapResponseWithoutInterfaceStruct,
230
+ SnapResponseWithInterfaceStruct
231
+ ]);
232
+
233
+
224
234
 
225
235
 
226
236
 
@@ -229,5 +239,5 @@ var SnapResponseStruct = _superstruct.assign.call(void 0,
229
239
 
230
240
 
231
241
 
232
- exports.TransactionOptionsStruct = TransactionOptionsStruct; exports.SignatureOptionsStruct = SignatureOptionsStruct; exports.SnapOptionsStruct = SnapOptionsStruct; exports.JsonRpcMockOptionsStruct = JsonRpcMockOptionsStruct; exports.InterfaceStruct = InterfaceStruct; exports.SnapResponseStruct = SnapResponseStruct;
233
- //# sourceMappingURL=chunk-T2BE4O5H.js.map
242
+ exports.TransactionOptionsStruct = TransactionOptionsStruct; exports.SignatureOptionsStruct = SignatureOptionsStruct; exports.SnapOptionsStruct = SnapOptionsStruct; exports.JsonRpcMockOptionsStruct = JsonRpcMockOptionsStruct; exports.InterfaceStruct = InterfaceStruct; exports.SnapResponseWithoutInterfaceStruct = SnapResponseWithoutInterfaceStruct; exports.SnapResponseWithInterfaceStruct = SnapResponseWithInterfaceStruct; exports.SnapResponseStruct = SnapResponseStruct;
243
+ //# sourceMappingURL=chunk-IDGD7TZ7.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/internals/structs.ts"],"names":[],"mappings":";AAAA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,mBAAmB;AAC5B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAGP,IAAM,kBAAkB,MAAM;AAAA,EAC5B,OAAO;AAAA,EACP,OAAO;AAAA,EACP,OAAO;AAAA,EACP,SAAS,UAAU;AACrB,CAAC;AAEM,IAAM,2BAA2B,OAAO;AAAA;AAAA;AAAA;AAAA,EAI7C,SAAS,UAAU,OAAO,GAAG,UAAU;AAAA;AAAA;AAAA;AAAA,EAKvC,QAAQ,UAAU,OAAO,GAAG,aAAa;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOzC,MAAM,OAAO,iBAAiB,SAAS,eAAe,GAAG,CAAC,UAAU;AAClE,QAAI,OA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AAM,qCAAqC,OAAO;AAAA,EACvD,IAAI,OAAO;AAAA,EAEX,UAAU,MAAM;AAAA,IACd,OAAO;AAAA,MACL,QAAQ;AAAA,IACV,CAAC;AAAA,IACD,OAAO;AAAA,MACL,OAAO;AAAA,IACT,CAAC;AAAA,EACH,CAAC;AAAA,EAED,eAAe;AAAA,IACb,OAAO;AAAA,MACL,IAAI,OAAO;AAAA,MACX,SAAS,OAAO;AAAA,MAChB,MAAM,MAAM;AAAA,QACV,UAAU,iBAAiB,KAAK;AAAA,QAChC,UAAU,iBAAiB,MAAM;AAAA,MACnC,CAAC;AAAA,IACH,CAAC;AAAA,EACH;AACF,CAAC;AAEM,IAAM,kCAAkC;AAAA,EAC7C;AAAA,EACA,OAAO;AAAA,IACL,cAAc,KAAK;AAAA,EACrB,CAAC;AACH;AAEO,IAAM,qBAAqB,MAAM;AAAA,EACtC;AAAA,EACA;AACF,CAAC","sourcesContent":["import {\n ComponentStruct,\n NotificationType,\n enumValue,\n} from '@metamask/snaps-sdk';\nimport {\n bytesToHex,\n JsonStruct,\n StrictHexStruct,\n valueToBytes,\n} from '@metamask/utils';\nimport { randomBytes } from 'crypto';\nimport {\n array,\n assign,\n bigint,\n coerce,\n defaulted,\n instance,\n literal,\n number,\n object,\n optional,\n string,\n union,\n record,\n any,\n func,\n type,\n} from 'superstruct';\n\n// TODO: Export this from `@metamask/utils` instead.\nconst BytesLikeStruct = union([\n bigint(),\n number(),\n string(),\n instance(Uint8Array),\n]);\n\nexport const TransactionOptionsStruct = object({\n /**\n * The CAIP-2 chain ID to send the transaction on. Defaults to `eip155:1`.\n */\n chainId: defaulted(string(), 'eip155:1'),\n\n /**\n * The origin to send the transaction from. Defaults to `metamask.io`.\n */\n origin: defaulted(string(), 'metamask.io'),\n\n /**\n * The address to send the transaction from. Defaults to a randomly generated\n * address.\n */\n // TODO: Move this coercer to `@metamask/utils`.\n from: coerce(StrictHexStruct, optional(BytesLikeStruct), (value) => {\n if (value) {\n return bytesToHex(valueToBytes(value));\n }\n\n return bytesToHex(randomBytes(20));\n }),\n\n /**\n * The address to send the transaction to. Defaults to a randomly generated\n * address.\n */\n // TODO: Move this coercer to `@metamask/utils`.\n to: coerce(StrictHexStruct, optional(BytesLikeStruct), (value) => {\n if (value) {\n return bytesToHex(valueToBytes(value));\n }\n\n return bytesToHex(randomBytes(20));\n }),\n\n /**\n * The value to send with the transaction. The value may be specified as a\n * `number`, `bigint`, `string`, or `Uint8Array`. Defaults to `0`.\n */\n value: defaulted(\n coerce(StrictHexStruct, BytesLikeStruct, (value) =>\n bytesToHex(valueToBytes(value)),\n ),\n '0x0',\n ),\n\n /**\n * The gas limit to use for the transaction. The gas limit may be specified\n * as a `number`, `bigint`, `string`, or `Uint8Array`. Defaults to `21_000`.\n */\n gasLimit: defaulted(\n coerce(StrictHexStruct, BytesLikeStruct, (value) =>\n bytesToHex(valueToBytes(value)),\n ),\n valueToBytes(21_000),\n ),\n\n /**\n * The max fee per gas (in Wei) to use for the transaction. The max fee per\n * gas may be specified as a `number`, `bigint`, `string`, or `Uint8Array`.\n * Defaults to `1`.\n */\n maxFeePerGas: defaulted(\n coerce(StrictHexStruct, BytesLikeStruct, (value) =>\n bytesToHex(valueToBytes(value)),\n ),\n valueToBytes(1),\n ),\n\n /**\n * The max priority fee per gas (in Wei) to use for the transaction. The max\n * priority fee per gas may be specified as a `number`, `bigint`, `string`,\n * or `Uint8Array`. Defaults to `1`.\n */\n maxPriorityFeePerGas: defaulted(\n coerce(StrictHexStruct, BytesLikeStruct, (value) =>\n bytesToHex(valueToBytes(value)),\n ),\n valueToBytes(1),\n ),\n\n /**\n * The nonce to use for the transaction. The nonce may be specified as a\n * `number`, `bigint`, `string`, or `Uint8Array`. Defaults to `0`.\n */\n nonce: defaulted(\n coerce(StrictHexStruct, BytesLikeStruct, (value) =>\n bytesToHex(valueToBytes(value)),\n ),\n valueToBytes(0),\n ),\n\n /**\n * The data to send with the transaction. The data may be specified as a\n * `number`, `bigint`, `string`, or `Uint8Array`. Defaults to `0x`.\n */\n data: defaulted(\n coerce(union([StrictHexStruct, literal('0x')]), BytesLikeStruct, (value) =>\n bytesToHex(valueToBytes(value)),\n ),\n '0x',\n ),\n});\n\nexport const SignatureOptionsStruct = object({\n /**\n * The origin making the signature request.\n */\n origin: defaulted(string(), 'metamask.io'),\n\n /**\n * The address signing the signature request. Defaults to a randomly generated\n * address.\n */\n from: coerce(StrictHexStruct, optional(BytesLikeStruct), (value) => {\n if (value) {\n return bytesToHex(valueToBytes(value));\n }\n\n return bytesToHex(randomBytes(20));\n }),\n\n /**\n * The data to send with the transaction. The data may be specified as a\n * `string`, an object, or an array of objects. This covers the data types\n * for the supported signature methods. Defaults to `0x`.\n */\n data: defaulted(\n union([\n StrictHexStruct,\n literal('0x'),\n record(string(), any()),\n array(record(string(), any())),\n ]),\n '0x',\n ),\n\n /**\n * The signature method being used.\n */\n signatureMethod: defaulted(\n union([\n literal('eth_sign'),\n literal('personal_sign'),\n literal('eth_signTypedData'),\n literal('eth_signTypedData_v3'),\n literal('eth_signTypedData_v4'),\n ]),\n 'personal_sign',\n ),\n});\n\nexport const SnapOptionsStruct = object({\n /**\n * The timeout in milliseconds to use for requests to the snap. Defaults to\n * `1000`.\n */\n timeout: defaulted(optional(number()), 1000),\n});\n\nexport const JsonRpcMockOptionsStruct = object({\n method: string(),\n result: JsonStruct,\n});\n\nexport const InterfaceStruct = type({\n content: optional(ComponentStruct),\n});\n\nexport const SnapResponseWithoutInterfaceStruct = object({\n id: string(),\n\n response: union([\n object({\n result: JsonStruct,\n }),\n object({\n error: JsonStruct,\n }),\n ]),\n\n notifications: array(\n object({\n id: string(),\n message: string(),\n type: union([\n enumValue(NotificationType.InApp),\n enumValue(NotificationType.Native),\n ]),\n }),\n ),\n});\n\nexport const SnapResponseWithInterfaceStruct = assign(\n SnapResponseWithoutInterfaceStruct,\n object({\n getInterface: func(),\n }),\n);\n\nexport const SnapResponseStruct = union([\n SnapResponseWithoutInterfaceStruct,\n SnapResponseWithInterfaceStruct,\n]);\n"]}
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  getPermissionSpecifications
3
- } from "./chunk-HBLJOACO.mjs";
3
+ } from "./chunk-TAIJXTLU.mjs";
4
4
  import {
5
5
  UNRESTRICTED_METHODS
6
6
  } from "./chunk-57SGDM5B.mjs";
@@ -92,4 +92,4 @@ export {
92
92
  getControllers,
93
93
  registerSnap
94
94
  };
95
- //# sourceMappingURL=chunk-BS24WMRW.mjs.map
95
+ //# sourceMappingURL=chunk-LG3VKXGH.mjs.map
@@ -3,20 +3,20 @@
3
3
  var _chunkXWGECIXIjs = require('./chunk-XWGECIXI.js');
4
4
 
5
5
 
6
- var _chunkVXPCUDBIjs = require('./chunk-VXPCUDBI.js');
6
+ var _chunkTVD4SWH7js = require('./chunk-TVD4SWH7.js');
7
7
 
8
8
 
9
+ var _chunkVXPCUDBIjs = require('./chunk-VXPCUDBI.js');
9
10
 
10
- var _chunk6HW5NGCBjs = require('./chunk-6HW5NGCB.js');
11
11
 
12
12
 
13
- var _chunkLXSNRZV4js = require('./chunk-LXSNRZV4.js');
13
+ var _chunkDTDYOBCIjs = require('./chunk-DTDYOBCI.js');
14
14
 
15
15
 
16
- var _chunkTO46ICOZjs = require('./chunk-TO46ICOZ.js');
16
+ var _chunkZWN4SO2Vjs = require('./chunk-ZWN4SO2V.js');
17
17
 
18
18
 
19
- var _chunkTVD4SWH7js = require('./chunk-TVD4SWH7.js');
19
+ var _chunkWMLSD6B5js = require('./chunk-WMLSD6B5.js');
20
20
 
21
21
  // src/internals/simulation/simulation.ts
22
22
  var _basecontroller = require('@metamask/base-controller');
@@ -28,7 +28,6 @@ var _keytree = require('@metamask/key-tree');
28
28
 
29
29
 
30
30
  var _node = require('@metamask/snaps-controllers/node');
31
- var _snapsrpcmethods = require('@metamask/snaps-rpc-methods');
32
31
  var _snapsutils = require('@metamask/snaps-utils');
33
32
  var _readablestream = require('readable-stream');
34
33
  async function handleInstallSnap(snapId, {
@@ -41,15 +40,11 @@ async function handleInstallSnap(snapId, {
41
40
  allowLocal: true
42
41
  });
43
42
  const snapFiles = await _node.fetchSnap.call(void 0, snapId, location);
44
- const password = await _snapsrpcmethods.getEncryptionKey.call(void 0, {
45
- mnemonicPhrase: _keytree.mnemonicPhraseToBytes.call(void 0, options.secretRecoveryPhrase),
46
- snapId
47
- });
48
- const { store, runSaga } = _chunkTO46ICOZjs.createStore.call(void 0, password, options);
43
+ const { store, runSaga } = _chunkWMLSD6B5js.createStore.call(void 0, options);
49
44
  const controllerMessenger = new (0, _basecontroller.ControllerMessenger)();
50
45
  registerActions(controllerMessenger);
51
46
  const hooks = getHooks(options, snapFiles, snapId, controllerMessenger);
52
- const { subjectMetadataController, permissionController } = _chunk6HW5NGCBjs.getControllers.call(void 0, {
47
+ const { subjectMetadataController, permissionController } = _chunkDTDYOBCIjs.getControllers.call(void 0, {
53
48
  controllerMessenger,
54
49
  hooks,
55
50
  runSaga,
@@ -81,14 +76,14 @@ async function handleInstallSnap(snapId, {
81
76
  });
82
77
  }
83
78
  });
84
- await _chunk6HW5NGCBjs.registerSnap.call(void 0, snapId, snapFiles.manifest.result, {
79
+ await _chunkDTDYOBCIjs.registerSnap.call(void 0, snapId, snapFiles.manifest.result, {
85
80
  permissionController,
86
81
  subjectMetadataController
87
82
  });
88
83
  await service.executeSnap({
89
84
  snapId,
90
85
  sourceCode: snapFiles.sourceCode.toString("utf8"),
91
- endowments: await _chunkLXSNRZV4js.getEndowments.call(void 0, permissionController, snapId)
86
+ endowments: await _chunkZWN4SO2Vjs.getEndowments.call(void 0, permissionController, snapId)
92
87
  });
93
88
  return {
94
89
  snapId,
@@ -136,4 +131,4 @@ function registerActions(controllerMessenger) {
136
131
 
137
132
 
138
133
  exports.handleInstallSnap = handleInstallSnap; exports.getHooks = getHooks; exports.registerActions = registerActions;
139
- //# sourceMappingURL=chunk-C2ONPIIB.js.map
134
+ //# sourceMappingURL=chunk-MCYTJUDG.js.map
@@ -0,0 +1 @@
1
+ {"version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} from '@metamask/base-controller';\nimport { ControllerMessenger } from '@metamask/base-controller';\nimport { createEngineStream } from '@metamask/json-rpc-middleware-stream';\nimport { mnemonicPhraseToBytes } from '@metamask/key-tree';\nimport type { AbstractExecutionService } from '@metamask/snaps-controllers';\nimport {\n fetchSnap,\n detectSnapLocation,\n NodeThreadExecutionService,\n setupMultiplex,\n} from '@metamask/snaps-controllers/node';\nimport type {\n SnapId,\n AuxiliaryFileEncoding,\n Component,\n InterfaceState,\n} from '@metamask/snaps-sdk';\nimport type { FetchedSnapFiles } from '@metamask/snaps-utils';\nimport { logError } from '@metamask/snaps-utils';\nimport type { Duplex } from 'readable-stream';\nimport { pipeline } from 'readable-stream';\n\nimport type { RootControllerMessenger } from './controllers';\nimport { getControllers, registerSnap } from './controllers';\nimport { getSnapFile } from './files';\nimport { getEndowments } from './methods';\nimport { createJsonRpcEngine } from './middleware';\nimport type { SimulationOptions, SimulationUserOptions } from './options';\nimport { getOptions } from './options';\nimport type { RunSagaFunction, Store } from './store';\nimport { createStore } from './store';\n\n/**\n * Options for the execution service, without the options that are shared\n * between all execution services.\n *\n * @template Service - The type of the execution service, i.e., the class that\n * creates the execution service.\n */\nexport type ExecutionServiceOptions<\n Service extends new (...args: any[]) => any,\n> = Omit<\n ConstructorParameters<Service>[0],\n keyof ConstructorParameters<typeof AbstractExecutionService<unknown>>[0]\n>;\n\n/**\n * The options for running a Snap in a simulated environment.\n *\n * @property executionService - The execution service to use.\n * @property executionServiceOptions - The options to use when creating the\n * execution service, if any. This should only include options specific to the\n * provided execution service.\n * @property options - The simulation options.\n * @template Service - The type of the execution service.\n */\nexport type InstallSnapOptions<\n Service extends new (...args: any[]) => InstanceType<\n typeof AbstractExecutionService<unknown>\n >,\n> = ExecutionServiceOptions<Service> extends Record<string, never>\n ? {\n executionService: Service;\n executionServiceOptions?: ExecutionServiceOptions<Service>;\n options?: SimulationUserOptions;\n }\n : {\n executionService: Service;\n executionServiceOptions: ExecutionServiceOptions<Service>;\n options?: SimulationUserOptions;\n };\n\nexport type InstalledSnap = {\n snapId: SnapId;\n store: Store;\n executionService: InstanceType<typeof AbstractExecutionService>;\n controllerMessenger: ControllerMessenger<ActionConstraint, EventConstraint>;\n runSaga: RunSagaFunction;\n};\n\nexport type MiddlewareHooks = {\n /**\n * A hook that returns the user's secret recovery phrase.\n *\n * @returns The user's secret recovery phrase.\n */\n getMnemonic: () => Promise<Uint8Array>;\n\n /**\n * A hook that returns the Snap's auxiliary file for the given path.\n *\n * @param path - The path of the auxiliary file to get.\n * @param encoding - The encoding to use when returning the file.\n * @returns The Snap's auxiliary file for the given path.\n */\n getSnapFile: (\n path: string,\n encoding: AuxiliaryFileEncoding,\n ) => Promise<string | null>;\n\n /**\n * A hook that returns whether the client is locked or not.\n *\n * @returns A boolean flag signaling whether the client is locked.\n */\n getIsLocked: () => boolean;\n createInterface: (content: Component) => Promise<string>;\n updateInterface: (id: string, content: Component) => Promise<void>;\n getInterfaceState: (id: string) => InterfaceState;\n};\n\n/**\n * Install a Snap in a simulated environment. This will fetch the Snap files,\n * create a Redux store, set up the controllers and JSON-RPC stack, register the\n * Snap, and run the Snap code in the execution service.\n *\n * @param snapId - The ID of the Snap to install.\n * @param options - The options to use when installing the Snap.\n * @param options.executionService - The execution service to use.\n * @param options.executionServiceOptions - The options to use when creating the\n * execution service, if any. This should only include options specific to the\n * provided execution service.\n * @param options.options - The simulation options.\n * @template Service - The type of the execution service.\n */\nexport async function handleInstallSnap<\n Service extends new (...args: any[]) => InstanceType<\n typeof AbstractExecutionService\n >,\n>(\n snapId: SnapId,\n {\n executionService,\n executionServiceOptions,\n options: rawOptions = {},\n }: Partial<InstallSnapOptions<Service>> = {},\n): Promise<InstalledSnap> {\n const options = getOptions(rawOptions);\n\n // Fetch Snap files.\n const location = detectSnapLocation(snapId, {\n allowLocal: true,\n });\n\n const snapFiles = await fetchSnap(snapId, location);\n\n // Create Redux store.\n const { store, runSaga } = createStore(options);\n\n const controllerMessenger = new ControllerMessenger<any, any>();\n\n registerActions(controllerMessenger);\n\n // Set up controllers and JSON-RPC stack.\n const hooks = getHooks(options, snapFiles, snapId, controllerMessenger);\n\n const { subjectMetadataController, permissionController } = getControllers({\n controllerMessenger,\n hooks,\n runSaga,\n options,\n });\n\n const engine = createJsonRpcEngine({\n store,\n hooks,\n permissionMiddleware: permissionController.createPermissionMiddleware({\n origin: snapId,\n }),\n });\n\n // Create execution service.\n const ExecutionService = executionService ?? NodeThreadExecutionService;\n const service = new ExecutionService({\n ...executionServiceOptions,\n messenger: controllerMessenger.getRestricted({\n name: 'ExecutionService',\n allowedActions: [],\n allowedEvents: [],\n }),\n setupSnapProvider: (_snapId: string, rpcStream: Duplex) => {\n const mux = setupMultiplex(rpcStream, 'snapStream');\n const stream = mux.createStream('metamask-provider');\n const providerStream = createEngineStream({ engine });\n\n // Error function is difficult to test, so we ignore it.\n /* istanbul ignore next 2 */\n pipeline(stream, providerStream, stream, (error: unknown) => {\n if (error) {\n logError(`Provider stream failure.`, error);\n }\n });\n },\n });\n\n // Register the Snap. This sets up the Snap's permissions and subject\n // metadata.\n await registerSnap(snapId, snapFiles.manifest.result, {\n permissionController,\n subjectMetadataController,\n });\n\n // Run the Snap code in the execution service.\n await service.executeSnap({\n snapId,\n sourceCode: snapFiles.sourceCode.toString('utf8'),\n endowments: await getEndowments(permissionController, snapId),\n });\n\n return {\n snapId,\n store,\n executionService: service,\n controllerMessenger,\n runSaga,\n };\n}\n\n/**\n * Get the hooks for the simulation.\n *\n * @param options - The simulation options.\n * @param snapFiles - The Snap files.\n * @param snapId - The Snap ID.\n * @param controllerMessenger - The controller messenger.\n * @returns The hooks for the simulation.\n */\nexport function getHooks(\n options: SimulationOptions,\n snapFiles: FetchedSnapFiles,\n snapId: SnapId,\n controllerMessenger: RootControllerMessenger,\n): MiddlewareHooks {\n return {\n getMnemonic: async () =>\n Promise.resolve(mnemonicPhraseToBytes(options.secretRecoveryPhrase)),\n getSnapFile: async (path: string, encoding: AuxiliaryFileEncoding) =>\n await getSnapFile(snapFiles.auxiliaryFiles, path, encoding),\n getIsLocked: () => false,\n createInterface: async (...args) =>\n controllerMessenger.call(\n 'SnapInterfaceController:createInterface',\n snapId,\n ...args,\n ),\n updateInterface: async (...args) =>\n controllerMessenger.call(\n 'SnapInterfaceController:updateInterface',\n snapId,\n ...args,\n ),\n getInterfaceState: (...args) =>\n controllerMessenger.call(\n 'SnapInterfaceController:getInterface',\n snapId,\n ...args,\n ).state,\n };\n}\n\n/**\n * Register mocked action handlers.\n *\n * @param controllerMessenger - The controller messenger.\n */\nexport function registerActions(controllerMessenger: RootControllerMessenger) {\n controllerMessenger.registerActionHandler(\n 'PhishingController:maybeUpdateState',\n async () => Promise.resolve(),\n );\n\n controllerMessenger.registerActionHandler(\n 'PhishingController:testOrigin',\n () => ({ result: false, type: 'all' }),\n );\n}\n"]}
@@ -0,0 +1,127 @@
1
+ import {
2
+ clickElement,
3
+ getInterface,
4
+ typeInField
5
+ } from "./chunk-I5P52IMF.mjs";
6
+ import {
7
+ clearNotifications,
8
+ getNotifications
9
+ } from "./chunk-LB4R3BUA.mjs";
10
+
11
+ // src/internals/request.ts
12
+ import { unwrapError } from "@metamask/snaps-utils";
13
+ import { getSafeJson, hasProperty, isPlainObject } from "@metamask/utils";
14
+ import { nanoid } from "@reduxjs/toolkit";
15
+ function handleRequest({
16
+ snapId,
17
+ store,
18
+ executionService,
19
+ handler,
20
+ controllerMessenger,
21
+ runSaga,
22
+ request: { id = nanoid(), origin = "https://metamask.io", ...options }
23
+ }) {
24
+ const promise = executionService.handleRpcRequest(snapId, {
25
+ origin,
26
+ handler,
27
+ request: {
28
+ jsonrpc: "2.0",
29
+ id: 1,
30
+ ...options
31
+ }
32
+ }).then(async (result) => {
33
+ const notifications = getNotifications(store.getState());
34
+ store.dispatch(clearNotifications());
35
+ const getInterfaceFn = await getInterfaceApi(
36
+ result,
37
+ snapId,
38
+ controllerMessenger
39
+ );
40
+ return {
41
+ id: String(id),
42
+ response: {
43
+ result: getSafeJson(result)
44
+ },
45
+ notifications,
46
+ ...getInterfaceFn ? { getInterface: getInterfaceFn } : {}
47
+ };
48
+ }).catch((error) => {
49
+ const [unwrappedError] = unwrapError(error);
50
+ return {
51
+ id: String(id),
52
+ response: {
53
+ error: unwrappedError.serialize()
54
+ },
55
+ notifications: []
56
+ };
57
+ });
58
+ promise.getInterface = async () => {
59
+ return await runSaga(
60
+ getInterface,
61
+ runSaga,
62
+ snapId,
63
+ controllerMessenger
64
+ ).toPromise();
65
+ };
66
+ return promise;
67
+ }
68
+ async function getInterfaceFromResult(result, snapId, controllerMessenger) {
69
+ if (isPlainObject(result) && hasProperty(result, "id")) {
70
+ return result.id;
71
+ }
72
+ if (isPlainObject(result) && hasProperty(result, "content")) {
73
+ const id = await controllerMessenger.call(
74
+ "SnapInterfaceController:createInterface",
75
+ snapId,
76
+ result.content
77
+ );
78
+ return id;
79
+ }
80
+ return void 0;
81
+ }
82
+ async function getInterfaceApi(result, snapId, controllerMessenger) {
83
+ const interfaceId = await getInterfaceFromResult(
84
+ result,
85
+ snapId,
86
+ controllerMessenger
87
+ );
88
+ if (interfaceId) {
89
+ return () => {
90
+ const { content } = controllerMessenger.call(
91
+ "SnapInterfaceController:getInterface",
92
+ snapId,
93
+ interfaceId
94
+ );
95
+ return {
96
+ content,
97
+ clickElement: async (name) => {
98
+ await clickElement(
99
+ controllerMessenger,
100
+ interfaceId,
101
+ content,
102
+ snapId,
103
+ name
104
+ );
105
+ },
106
+ typeInField: async (name, value) => {
107
+ await typeInField(
108
+ controllerMessenger,
109
+ interfaceId,
110
+ content,
111
+ snapId,
112
+ name,
113
+ value
114
+ );
115
+ }
116
+ };
117
+ };
118
+ }
119
+ return void 0;
120
+ }
121
+
122
+ export {
123
+ handleRequest,
124
+ getInterfaceFromResult,
125
+ getInterfaceApi
126
+ };
127
+ //# sourceMappingURL=chunk-PVMIH6OB.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/internals/request.ts"],"sourcesContent":["import type { AbstractExecutionService } from '@metamask/snaps-controllers';\nimport type { SnapId, Component } from '@metamask/snaps-sdk';\nimport type { HandlerType } from '@metamask/snaps-utils';\nimport { unwrapError } from '@metamask/snaps-utils';\nimport { getSafeJson, hasProperty, isPlainObject } from '@metamask/utils';\nimport { nanoid } from '@reduxjs/toolkit';\n\nimport type {\n RequestOptions,\n SnapHandlerInterface,\n SnapRequest,\n} from '../types';\nimport {\n clearNotifications,\n clickElement,\n getInterface,\n getNotifications,\n typeInField,\n} from './simulation';\nimport type { RunSagaFunction, Store } from './simulation';\nimport type { RootControllerMessenger } from './simulation/controllers';\n\nexport type HandleRequestOptions = {\n snapId: SnapId;\n store: Store;\n executionService: AbstractExecutionService<unknown>;\n handler: HandlerType;\n controllerMessenger: RootControllerMessenger;\n runSaga: RunSagaFunction;\n request: RequestOptions;\n};\n\n/**\n * Send a JSON-RPC request to the Snap, and wrap the response in a\n * {@link SnapResponse} object.\n *\n * @param options - The request options.\n * @param options.snapId - The ID of the Snap to send the request to.\n * @param options.store - The Redux store.\n * @param options.executionService - The execution service to use to send the\n * request.\n * @param options.handler - The handler to use to send the request.\n * @param options.controllerMessenger - The controller messenger used to call actions.\n * @param options.runSaga - A function to run a saga outside the usual Redux\n * flow.\n * @param options.request - The request to send.\n * @param options.request.id - The ID of the request. If not provided, a random\n * ID will be generated.\n * @param options.request.origin - The origin of the request. Defaults to\n * `https://metamask.io`.\n * @returns The response, wrapped in a {@link SnapResponse} object.\n */\nexport function handleRequest({\n snapId,\n store,\n executionService,\n handler,\n controllerMessenger,\n runSaga,\n request: { id = nanoid(), origin = 'https://metamask.io', ...options },\n}: HandleRequestOptions): SnapRequest {\n const promise = executionService\n .handleRpcRequest(snapId, {\n origin,\n handler,\n request: {\n jsonrpc: '2.0',\n id: 1,\n ...options,\n },\n })\n .then(async (result) => {\n const notifications = getNotifications(store.getState());\n store.dispatch(clearNotifications());\n\n const getInterfaceFn = await getInterfaceApi(\n result,\n snapId,\n controllerMessenger,\n );\n\n return {\n id: String(id),\n response: {\n result: getSafeJson(result),\n },\n notifications,\n ...(getInterfaceFn ? { getInterface: getInterfaceFn } : {}),\n };\n })\n .catch((error) => {\n const [unwrappedError] = unwrapError(error);\n\n return {\n id: String(id),\n response: {\n error: unwrappedError.serialize(),\n },\n notifications: [],\n };\n }) as unknown as SnapRequest;\n\n promise.getInterface = async () => {\n return await runSaga(\n getInterface,\n runSaga,\n snapId,\n controllerMessenger,\n ).toPromise();\n };\n\n return promise;\n}\n\n/**\n * Get the interface ID from the result if it's available or create a new interface if the result contains static components.\n *\n * @param result - The handler result object.\n * @param snapId - The Snap ID.\n * @param controllerMessenger - The controller messenger.\n * @returns The interface ID or undefined if the result doesn't include content.\n */\nexport async function getInterfaceFromResult(\n result: unknown,\n snapId: SnapId,\n controllerMessenger: RootControllerMessenger,\n) {\n if (isPlainObject(result) && hasProperty(result, 'id')) {\n return result.id as string;\n }\n\n if (isPlainObject(result) && hasProperty(result, 'content')) {\n const id = await controllerMessenger.call(\n 'SnapInterfaceController:createInterface',\n snapId,\n result.content as Component,\n );\n\n return id;\n }\n\n return undefined;\n}\n\n/**\n * Get the response content from the SnapInterfaceController and include the interaction methods.\n *\n * @param result - The handler result object.\n * @param snapId - The Snap ID.\n * @param controllerMessenger - The controller messenger.\n * @returns The content components if any.\n */\nexport async function getInterfaceApi(\n result: unknown,\n snapId: SnapId,\n controllerMessenger: RootControllerMessenger,\n): Promise<(() => SnapHandlerInterface) | undefined> {\n const interfaceId = await getInterfaceFromResult(\n result,\n snapId,\n controllerMessenger,\n );\n\n if (interfaceId) {\n return () => {\n const { content } = controllerMessenger.call(\n 'SnapInterfaceController:getInterface',\n snapId,\n interfaceId,\n );\n\n return {\n content,\n clickElement: async (name) => {\n await clickElement(\n controllerMessenger,\n interfaceId,\n content,\n snapId,\n name,\n );\n },\n typeInField: async (name, value) => {\n await typeInField(\n controllerMessenger,\n interfaceId,\n content,\n snapId,\n name,\n value,\n );\n },\n };\n };\n }\n\n return undefined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,IAAI,GAAG;AACtD,WAAO,OAAO;AAAA,EAChB;AAEA,MAAI,cAAc,MAAM,KAAK,YAAY,QAAQ,SAAS,GAAG;AAC3D,UAAM,KAAK,MAAM,oBAAoB;AAAA,MACnC;AAAA,MACA;AAAA,MACA,OAAO;AAAA,IACT;AAEA,WAAO;AAAA,EACT;AAEA,SAAO;AACT;AAUA,eAAsB,gBACpB,QACA,QACA,qBACmD;AACnD,QAAM,cAAc,MAAM;AAAA,IACxB;AAAA,IACA;AAAA,IACA;AAAA,EACF;AAEA,MAAI,aAAa;AACf,WAAO,MAAM;AACX,YAAM,EAAE,QAAQ,IAAI,oBAAoB;AAAA,QACtC;AAAA,QACA;AAAA,QACA;AAAA,MACF;AAEA,aAAO;AAAA,QACL;AAAA,QACA,cAAc,OAAO,SAAS;AAC5B,gBAAM;AAAA,YACJ;AAAA,YACA;AAAA,YACA;AAAA,YACA;AAAA,YACA;AAAA,UACF;AAAA,QACF;AAAA,QACA,aAAa,OAAO,MAAM,UAAU;AAClC,gBAAM;AAAA,YACJ;AAAA,YACA;AAAA,YACA;AAAA,YACA;AAAA,YACA;AAAA,YACA;AAAA,UACF;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAEA,SAAO;AACT;","names":[]}
@@ -0,0 +1 @@
1
+ "use strict";//# sourceMappingURL=chunk-S2HLITUN.js.map
@@ -5,9 +5,11 @@
5
5
  var _chunkLBC2OGSNjs = require('./chunk-LBC2OGSN.js');
6
6
 
7
7
  // src/internals/simulation/methods/hooks/state.ts
8
+ var _snapsutils = require('@metamask/snaps-utils');
8
9
  var _effects = require('redux-saga/effects');
9
10
  function* getSnapStateImplementation(_snapId, encrypted = true) {
10
- return yield _effects.select.call(void 0, _chunkLBC2OGSNjs.getState.call(void 0, encrypted));
11
+ const state = yield _effects.select.call(void 0, _chunkLBC2OGSNjs.getState.call(void 0, encrypted));
12
+ return _snapsutils.parseJson.call(void 0, state);
11
13
  }
12
14
  function getGetSnapStateMethodImplementation(runSaga) {
13
15
  return (...args) => {
@@ -15,7 +17,7 @@ function getGetSnapStateMethodImplementation(runSaga) {
15
17
  };
16
18
  }
17
19
  function* updateSnapStateImplementation(_snapId, newState, encrypted = true) {
18
- yield _effects.put.call(void 0, _chunkLBC2OGSNjs.setState.call(void 0, { state: newState, encrypted }));
20
+ yield _effects.put.call(void 0, _chunkLBC2OGSNjs.setState.call(void 0, { state: JSON.stringify(newState), encrypted }));
19
21
  }
20
22
  function getUpdateSnapStateMethodImplementation(runSaga) {
21
23
  return (...args) => {
@@ -36,4 +38,4 @@ function getClearSnapStateMethodImplementation(runSaga) {
36
38
 
37
39
 
38
40
  exports.getGetSnapStateMethodImplementation = getGetSnapStateMethodImplementation; exports.getUpdateSnapStateMethodImplementation = getUpdateSnapStateMethodImplementation; exports.getClearSnapStateMethodImplementation = getClearSnapStateMethodImplementation;
39
- //# sourceMappingURL=chunk-ISWZ7XZ5.js.map
41
+ //# sourceMappingURL=chunk-SB5EPHE3.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/internals/simulation/methods/hooks/state.ts"],"names":[],"mappings":";;;;;;;AAAA,SAAS,iBAAiB;AAG1B,SAAS,KAAK,cAAc;AAe5B,UAAU,2BACR,SACA,YAAY,MACU;AACtB,QAAM,QAAQ,MAAM,OAAO,SAAS,SAAS,CAAC;AAE9C,SAAO,UAAU,KAAK;AACxB;AAQO,SAAS,oCAAoC,SAA0B;AAC5E,SAAO,IAAI,SAAwD;AACjE,WAAO,QAAQ,4BAA4B,GAAG,IAAI,EAAE,OAAO;AAAA,EAC7D;AACF;AAYA,UAAU,8BACR,SACA,UACA,YAAY,MACQ;AAEpB,QAAM,IAAI,SAAS,EAAE,OAAO,KAAK,UAAU,QAAQ,GAAG,UAAU,CAAC,CAAC;AACpE;AAQO,SAAS,uCACd,SACA;AACA,SAAO,IAAI,SAA2D;AACpE,YAAQ,+BAA+B,GAAG,IAAI,EAAE,OAAO;AAAA,EACzD;AACF;AAWA,UAAU,6BACR,SACA,YAAY,MACQ;AACpB,QAAM,IAAI,WAAW,EAAE,UAAU,CAAC,CAAC;AACrC;AAQO,SAAS,sCACd,SACA;AACA,SAAO,UAAU,SAA0D;AACzE,YAAQ,8BAA8B,GAAG,IAAI,EAAE,OAAO;AAAA,EACxD;AACF","sourcesContent":["import { parseJson } from '@metamask/snaps-utils';\nimport type { Json } from '@metamask/utils';\nimport type { SagaIterator } from 'redux-saga';\nimport { put, select } from 'redux-saga/effects';\n\nimport type { RunSagaFunction } from '../../store';\nimport { clearState, getState, setState } from '../../store';\n\n/**\n * Get the Snap state from the store.\n *\n * @param _snapId - The ID of the Snap to get the state for. This is ignored\n * because the simulator only supports one Snap.\n * @param encrypted - Whether to get the encrypted or unencrypted state.\n * Defaults to encrypted state.\n * @returns The state of the Snap.\n * @yields Selects the state from the store.\n */\nfunction* getSnapStateImplementation(\n _snapId: string,\n encrypted = true,\n): SagaIterator<string> {\n const state = yield select(getState(encrypted));\n // TODO: Use actual decryption implementation\n return parseJson(state);\n}\n\n/**\n * Get the implementation of the `getSnapState` hook.\n *\n * @param runSaga - The function to run a saga outside the usual Redux flow.\n * @returns The implementation of the `getSnapState` hook.\n */\nexport function getGetSnapStateMethodImplementation(runSaga: RunSagaFunction) {\n return (...args: Parameters<typeof getSnapStateImplementation>) => {\n return runSaga(getSnapStateImplementation, ...args).result();\n };\n}\n\n/**\n * Update the Snap state in the store.\n *\n * @param _snapId - The ID of the Snap to update the state for. This is ignored\n * because the simulator only supports one Snap.\n * @param newState - The new state.\n * @param encrypted - Whether to update the encrypted or unencrypted state.\n * Defaults to encrypted state.\n * @yields Puts the new state in the store.\n */\nfunction* updateSnapStateImplementation(\n _snapId: string,\n newState: Record<string, Json>,\n encrypted = true,\n): SagaIterator<void> {\n // TODO: Use actual encryption implementation\n yield put(setState({ state: JSON.stringify(newState), encrypted }));\n}\n\n/**\n * Get the implementation of the `updateSnapState` hook.\n *\n * @param runSaga - The function to run a saga outside the usual Redux flow.\n * @returns The implementation of the `updateSnapState` hook.\n */\nexport function getUpdateSnapStateMethodImplementation(\n runSaga: RunSagaFunction,\n) {\n return (...args: Parameters<typeof updateSnapStateImplementation>) => {\n runSaga(updateSnapStateImplementation, ...args).result();\n };\n}\n\n/**\n * Clear the Snap state in the store.\n *\n * @param _snapId - The ID of the Snap to clear the state for. This is ignored\n * because the simulator only supports one Snap.\n * @param encrypted - Whether to clear the encrypted or unencrypted state.\n * Defaults to encrypted state.\n * @yields Puts the new state in the store.\n */\nfunction* clearSnapStateImplementation(\n _snapId: string,\n encrypted = true,\n): SagaIterator<void> {\n yield put(clearState({ encrypted }));\n}\n\n/**\n * Get the implementation of the `clearSnapState` hook.\n *\n * @param runSaga - The function to run a saga outside the usual Redux flow.\n * @returns The implementation of the `clearSnapState` hook.\n */\nexport function getClearSnapStateMethodImplementation(\n runSaga: RunSagaFunction,\n) {\n return async (...args: Parameters<typeof clearSnapStateImplementation>) => {\n runSaga(clearSnapStateImplementation, ...args).result();\n };\n}\n"]}