@metamask/snaps-simulation 3.3.0 → 3.4.1

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 (118) hide show
  1. package/CHANGELOG.md +17 -1
  2. package/dist/methods/hooks/end-trace.cjs +29 -0
  3. package/dist/methods/hooks/end-trace.cjs.map +1 -0
  4. package/dist/methods/hooks/end-trace.d.cts +9 -0
  5. package/dist/methods/hooks/end-trace.d.cts.map +1 -0
  6. package/dist/methods/hooks/end-trace.d.mts +9 -0
  7. package/dist/methods/hooks/end-trace.d.mts.map +1 -0
  8. package/dist/methods/hooks/end-trace.mjs +25 -0
  9. package/dist/methods/hooks/end-trace.mjs.map +1 -0
  10. package/dist/methods/hooks/get-snap.cjs +52 -0
  11. package/dist/methods/hooks/get-snap.cjs.map +1 -0
  12. package/dist/methods/hooks/get-snap.d.cts +11 -0
  13. package/dist/methods/hooks/get-snap.d.cts.map +1 -0
  14. package/dist/methods/hooks/get-snap.d.mts +11 -0
  15. package/dist/methods/hooks/get-snap.d.mts.map +1 -0
  16. package/dist/methods/hooks/get-snap.mjs +48 -0
  17. package/dist/methods/hooks/get-snap.mjs.map +1 -0
  18. package/dist/methods/hooks/index.cjs +5 -0
  19. package/dist/methods/hooks/index.cjs.map +1 -1
  20. package/dist/methods/hooks/index.d.cts +5 -0
  21. package/dist/methods/hooks/index.d.cts.map +1 -1
  22. package/dist/methods/hooks/index.d.mts +5 -0
  23. package/dist/methods/hooks/index.d.mts.map +1 -1
  24. package/dist/methods/hooks/index.mjs +5 -0
  25. package/dist/methods/hooks/index.mjs.map +1 -1
  26. package/dist/methods/hooks/start-trace.cjs +34 -0
  27. package/dist/methods/hooks/start-trace.cjs.map +1 -0
  28. package/dist/methods/hooks/start-trace.d.cts +9 -0
  29. package/dist/methods/hooks/start-trace.d.cts.map +1 -0
  30. package/dist/methods/hooks/start-trace.d.mts +9 -0
  31. package/dist/methods/hooks/start-trace.d.mts.map +1 -0
  32. package/dist/methods/hooks/start-trace.mjs +30 -0
  33. package/dist/methods/hooks/start-trace.mjs.map +1 -0
  34. package/dist/methods/hooks/track-error.cjs +31 -0
  35. package/dist/methods/hooks/track-error.cjs.map +1 -0
  36. package/dist/methods/hooks/track-error.d.cts +9 -0
  37. package/dist/methods/hooks/track-error.d.cts.map +1 -0
  38. package/dist/methods/hooks/track-error.d.mts +9 -0
  39. package/dist/methods/hooks/track-error.d.mts.map +1 -0
  40. package/dist/methods/hooks/track-error.mjs +27 -0
  41. package/dist/methods/hooks/track-error.mjs.map +1 -0
  42. package/dist/methods/hooks/track-event.cjs +29 -0
  43. package/dist/methods/hooks/track-event.cjs.map +1 -0
  44. package/dist/methods/hooks/track-event.d.cts +13 -0
  45. package/dist/methods/hooks/track-event.d.cts.map +1 -0
  46. package/dist/methods/hooks/track-event.d.mts +13 -0
  47. package/dist/methods/hooks/track-event.d.mts.map +1 -0
  48. package/dist/methods/hooks/track-event.mjs +25 -0
  49. package/dist/methods/hooks/track-event.mjs.map +1 -0
  50. package/dist/request.cjs +21 -1
  51. package/dist/request.cjs.map +1 -1
  52. package/dist/request.d.cts.map +1 -1
  53. package/dist/request.d.mts.map +1 -1
  54. package/dist/request.mjs +22 -2
  55. package/dist/request.mjs.map +1 -1
  56. package/dist/simulation.cjs +6 -1
  57. package/dist/simulation.cjs.map +1 -1
  58. package/dist/simulation.d.cts +34 -2
  59. package/dist/simulation.d.cts.map +1 -1
  60. package/dist/simulation.d.mts +34 -2
  61. package/dist/simulation.d.mts.map +1 -1
  62. package/dist/simulation.mjs +7 -2
  63. package/dist/simulation.mjs.map +1 -1
  64. package/dist/store/index.cjs +1 -0
  65. package/dist/store/index.cjs.map +1 -1
  66. package/dist/store/index.d.cts +1 -0
  67. package/dist/store/index.d.cts.map +1 -1
  68. package/dist/store/index.d.mts +1 -0
  69. package/dist/store/index.d.mts.map +1 -1
  70. package/dist/store/index.mjs +1 -0
  71. package/dist/store/index.mjs.map +1 -1
  72. package/dist/store/mocks.d.cts +1 -0
  73. package/dist/store/mocks.d.cts.map +1 -1
  74. package/dist/store/mocks.d.mts +1 -0
  75. package/dist/store/mocks.d.mts.map +1 -1
  76. package/dist/store/notifications.d.cts +1 -0
  77. package/dist/store/notifications.d.cts.map +1 -1
  78. package/dist/store/notifications.d.mts +1 -0
  79. package/dist/store/notifications.d.mts.map +1 -1
  80. package/dist/store/state.d.cts +2 -0
  81. package/dist/store/state.d.cts.map +1 -1
  82. package/dist/store/state.d.mts +2 -0
  83. package/dist/store/state.d.mts.map +1 -1
  84. package/dist/store/store.cjs +2 -0
  85. package/dist/store/store.cjs.map +1 -1
  86. package/dist/store/store.d.cts +1 -0
  87. package/dist/store/store.d.cts.map +1 -1
  88. package/dist/store/store.d.mts +1 -0
  89. package/dist/store/store.d.mts.map +1 -1
  90. package/dist/store/store.mjs +2 -0
  91. package/dist/store/store.mjs.map +1 -1
  92. package/dist/store/trackables.cjs +70 -0
  93. package/dist/store/trackables.cjs.map +1 -0
  94. package/dist/store/trackables.d.cts +98 -0
  95. package/dist/store/trackables.d.cts.map +1 -0
  96. package/dist/store/trackables.d.mts +98 -0
  97. package/dist/store/trackables.d.mts.map +1 -0
  98. package/dist/store/trackables.mjs +67 -0
  99. package/dist/store/trackables.mjs.map +1 -0
  100. package/dist/store/ui.d.cts +1 -0
  101. package/dist/store/ui.d.cts.map +1 -1
  102. package/dist/store/ui.d.mts +1 -0
  103. package/dist/store/ui.d.mts.map +1 -1
  104. package/dist/structs.cjs +17 -0
  105. package/dist/structs.cjs.map +1 -1
  106. package/dist/structs.d.cts +182 -12
  107. package/dist/structs.d.cts.map +1 -1
  108. package/dist/structs.d.mts +182 -12
  109. package/dist/structs.d.mts.map +1 -1
  110. package/dist/structs.mjs +18 -1
  111. package/dist/structs.mjs.map +1 -1
  112. package/dist/types.cjs.map +1 -1
  113. package/dist/types.d.cts +11 -1
  114. package/dist/types.d.cts.map +1 -1
  115. package/dist/types.d.mts +11 -1
  116. package/dist/types.d.mts.map +1 -1
  117. package/dist/types.mjs.map +1 -1
  118. package/package.json +8 -7
@@ -0,0 +1,13 @@
1
+ import type { RunSagaFunction } from "../../store/index.cjs";
2
+ /**
3
+ * Get a method that can be used to track an event.
4
+ *
5
+ * @param runSaga - A function to run a saga outside the usual Redux flow.
6
+ * @returns A method that can be used to track an event.
7
+ */
8
+ export declare function getTrackEventImplementation(runSaga: RunSagaFunction): (event: {
9
+ event: string;
10
+ properties?: Record<string, import("@metamask/snaps-sdk").Json> | undefined;
11
+ sensitiveProperties?: Record<string, import("@metamask/snaps-sdk").Json> | undefined;
12
+ }) => any;
13
+ //# sourceMappingURL=track-event.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"track-event.d.cts","sourceRoot":"","sources":["../../../src/methods/hooks/track-event.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,eAAe,EAAE,8BAAoB;AAiBnD;;;;;GAKG;AACH,wBAAgB,2BAA2B,CAAC,OAAO,EAAE,eAAe;;;;UAInE"}
@@ -0,0 +1,13 @@
1
+ import type { RunSagaFunction } from "../../store/index.mjs";
2
+ /**
3
+ * Get a method that can be used to track an event.
4
+ *
5
+ * @param runSaga - A function to run a saga outside the usual Redux flow.
6
+ * @returns A method that can be used to track an event.
7
+ */
8
+ export declare function getTrackEventImplementation(runSaga: RunSagaFunction): (event: {
9
+ event: string;
10
+ properties?: Record<string, import("@metamask/snaps-sdk").Json> | undefined;
11
+ sensitiveProperties?: Record<string, import("@metamask/snaps-sdk").Json> | undefined;
12
+ }) => any;
13
+ //# sourceMappingURL=track-event.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"track-event.d.mts","sourceRoot":"","sources":["../../../src/methods/hooks/track-event.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,eAAe,EAAE,8BAAoB;AAiBnD;;;;;GAKG;AACH,wBAAgB,2BAA2B,CAAC,OAAO,EAAE,eAAe;;;;UAInE"}
@@ -0,0 +1,25 @@
1
+ import { put } from "redux-saga/effects";
2
+ import { trackEvent } from "../../store/index.mjs";
3
+ /**
4
+ * Track an event.
5
+ *
6
+ * @param event - The event to track.
7
+ * @returns `null`.
8
+ * @yields Adds the event to the store.
9
+ */
10
+ function* trackEventImplementation(event) {
11
+ yield put(trackEvent(event));
12
+ return null;
13
+ }
14
+ /**
15
+ * Get a method that can be used to track an event.
16
+ *
17
+ * @param runSaga - A function to run a saga outside the usual Redux flow.
18
+ * @returns A method that can be used to track an event.
19
+ */
20
+ export function getTrackEventImplementation(runSaga) {
21
+ return (...args) => {
22
+ return runSaga(trackEventImplementation, ...args).result();
23
+ };
24
+ }
25
+ //# sourceMappingURL=track-event.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"track-event.mjs","sourceRoot":"","sources":["../../../src/methods/hooks/track-event.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,GAAG,EAAE,2BAA2B;AAGzC,OAAO,EAAE,UAAU,EAAE,8BAAoB;AAEzC;;;;;;GAMG;AACH,QAAQ,CAAC,CAAC,wBAAwB,CAChC,KAAgC;IAEhC,MAAM,GAAG,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC,CAAC;IAC7B,OAAO,IAAI,CAAC;AACd,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,2BAA2B,CAAC,OAAwB;IAClE,OAAO,CAAC,GAAG,IAAiD,EAAE,EAAE;QAC9D,OAAO,OAAO,CAAC,wBAAwB,EAAE,GAAG,IAAI,CAAC,CAAC,MAAM,EAAE,CAAC;IAC7D,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import type { TrackEventParams } from '@metamask/snaps-sdk';\nimport type { SagaIterator } from 'redux-saga';\nimport { put } from 'redux-saga/effects';\n\nimport type { RunSagaFunction } from '../../store';\nimport { trackEvent } from '../../store';\n\n/**\n * Track an event.\n *\n * @param event - The event to track.\n * @returns `null`.\n * @yields Adds the event to the store.\n */\nfunction* trackEventImplementation(\n event: TrackEventParams['event'],\n): SagaIterator {\n yield put(trackEvent(event));\n return null;\n}\n\n/**\n * Get a method that can be used to track an event.\n *\n * @param runSaga - A function to run a saga outside the usual Redux flow.\n * @returns A method that can be used to track an event.\n */\nexport function getTrackEventImplementation(runSaga: RunSagaFunction) {\n return (...args: Parameters<typeof trackEventImplementation>) => {\n return runSaga(trackEventImplementation, ...args).result();\n };\n}\n"]}
package/dist/request.cjs CHANGED
@@ -45,9 +45,14 @@ function handleRequest({ snapId, store, executionService, handler, controllerMes
45
45
  },
46
46
  })
47
47
  .then(async (result) => {
48
- const notifications = (0, store_1.getNotifications)(store.getState());
48
+ const state = store.getState();
49
+ const notifications = (0, store_1.getNotifications)(state);
50
+ const errors = (0, store_1.getErrors)(state);
51
+ const events = (0, store_1.getEvents)(state);
52
+ const traces = (0, store_1.getTraces)(state);
49
53
  const interfaceId = notifications[0]?.content;
50
54
  store.dispatch((0, store_1.clearNotifications)());
55
+ store.dispatch((0, store_1.clearTrackables)());
51
56
  try {
52
57
  const getInterfaceFn = await getInterfaceApi(result, snapId, controllerMessenger, simulationOptions, interfaceId);
53
58
  return {
@@ -56,6 +61,11 @@ function handleRequest({ snapId, store, executionService, handler, controllerMes
56
61
  result: (0, utils_1.getSafeJson)(result),
57
62
  },
58
63
  notifications,
64
+ tracked: {
65
+ errors,
66
+ events,
67
+ traces,
68
+ },
59
69
  ...(getInterfaceFn ? { getInterface: getInterfaceFn } : {}),
60
70
  };
61
71
  }
@@ -67,6 +77,11 @@ function handleRequest({ snapId, store, executionService, handler, controllerMes
67
77
  error: unwrappedError.serialize(),
68
78
  },
69
79
  notifications: [],
80
+ tracked: {
81
+ errors: [],
82
+ events: [],
83
+ traces: [],
84
+ },
70
85
  getInterface: getInterfaceError,
71
86
  };
72
87
  }
@@ -79,6 +94,11 @@ function handleRequest({ snapId, store, executionService, handler, controllerMes
79
94
  error: unwrappedError.serialize(),
80
95
  },
81
96
  notifications: [],
97
+ tracked: {
98
+ errors: [],
99
+ events: [],
100
+ traces: [],
101
+ },
82
102
  getInterface: getInterfaceError,
83
103
  };
84
104
  });
@@ -1 +1 @@
1
- {"version":3,"file":"request.cjs","sourceRoot":"","sources":["../src/request.ts"],"names":[],"mappings":";;;AACA,mDAK6B;AAE7B,uDAAoD;AACpD,uDAA2C;AAC3C,2CAKyB;AACzB,8CAA0C;AAG1C,+CAAgE;AAEhE,6CAA+D;AAE/D,2CAA+C;AAkB/C;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,SAAgB,aAAa,CAAC,EAC5B,MAAM,EACN,KAAK,EACL,gBAAgB,EAChB,OAAO,EACP,mBAAmB,EACnB,iBAAiB,EACjB,OAAO,EACP,OAAO,EAAE,EAAE,EAAE,GAAG,IAAA,gBAAM,GAAE,EAAE,MAAM,GAAG,qBAAqB,EAAE,GAAG,OAAO,EAAE,GACjD;IACrB,MAAM,iBAAiB,GAAG,GAAG,EAAE;QAC7B,MAAM,IAAI,KAAK,CACb,4EAA4E,CAC7E,CAAC;IACJ,CAAC,CAAC;IAEF,MAAM,OAAO,GAAG,gBAAgB;SAC7B,gBAAgB,CAAC,MAAM,EAAE;QACxB,MAAM;QACN,OAAO;QACP,OAAO,EAAE;YACP,OAAO,EAAE,KAAK;YACd,EAAE,EAAE,CAAC;YACL,GAAG,OAAO;SACX;KACF,CAAC;SACD,IAAI,CAAC,KAAK,EAAE,MAAM,EAAE,EAAE;QACrB,MAAM,aAAa,GAAG,IAAA,wBAAgB,EAAC,KAAK,CAAC,QAAQ,EAAE,CAAC,CAAC;QACzD,MAAM,WAAW,GAAG,aAAa,CAAC,CAAC,CAAC,EAAE,OAAO,CAAC;QAC9C,KAAK,CAAC,QAAQ,CAAC,IAAA,0BAAkB,GAAE,CAAC,CAAC;QAErC,IAAI,CAAC;YACH,MAAM,cAAc,GAAG,MAAM,eAAe,CAC1C,MAAM,EACN,MAAM,EACN,mBAAmB,EACnB,iBAAiB,EACjB,WAAW,CACZ,CAAC;YAEF,OAAO;gBACL,EAAE,EAAE,MAAM,CAAC,EAAE,CAAC;gBACd,Q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E,GAAG,mBAAmB,CAAC,IAAI,CAC1C,sCAAsC,EACtC,MAAM,EACN,EAAE,CACH,CAAC;YAEF,MAAM,OAAO,GAAG,IAAA,+BAAmB,EACjC,MAAM,EACN,mBAAmB,EACnB,OAAO,EACP;gBACE,EAAE;gBACF,OAAO;aACR,CACF,CAAC;YAEF,OAAO;gBACL,OAAO;gBACP,GAAG,OAAO;aACX,CAAC;QACJ,CAAC,CAAC;IACJ,CAAC;IAED,OAAO,SAAS,CAAC;AACnB,CAAC;AAzCD,0CAyCC","sourcesContent":["import type { AbstractExecutionService } from '@metamask/snaps-controllers';\nimport {\n type ComponentOrElement,\n ComponentOrElementStruct,\n type JsonRpcError,\n type SnapId,\n} from '@metamask/snaps-sdk';\nimport type { HandlerType } from '@metamask/snaps-utils';\nimport { unwrapError } from '@metamask/snaps-utils';\nimport { is } from '@metamask/superstruct';\nimport {\n assert,\n getSafeJson,\n hasProperty,\n isPlainObject,\n} from '@metamask/utils';\nimport { nanoid } from '@reduxjs/toolkit';\n\nimport type { RootControllerMessenger } from './controllers';\nimport { getInterface, getInterfaceActions } from './interface';\nimport type { SimulationOptions } from './options';\nimport { clearNotifications, getNotifications } from './store';\nimport type { RunSagaFunction, Store } from './store';\nimport { SnapResponseStruct } from './structs';\nimport type {\n RequestOptions,\n SnapHandlerInterface,\n SnapRequest,\n} from './types';\n\nexport type HandleRequestOptions = {\n snapId: SnapId;\n store: Store;\n executionService: AbstractExecutionService<unknown>;\n handler: HandlerType;\n controllerMessenger: RootControllerMessenger;\n simulationOptions: SimulationOptions;\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.simulationOptions - The simulation options.\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 simulationOptions,\n runSaga,\n request: { id = nanoid(), origin = 'https://metamask.io', ...options },\n}: HandleRequestOptions): SnapRequest {\n const getInterfaceError = () => {\n throw new Error(\n 'Unable to get the interface from the Snap: The request to the Snap failed.',\n );\n };\n\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 const interfaceId = notifications[0]?.content;\n store.dispatch(clearNotifications());\n\n try {\n const getInterfaceFn = await getInterfaceApi(\n result,\n snapId,\n controllerMessenger,\n simulationOptions,\n interfaceId,\n );\n\n return {\n id: String(id),\n response: {\n result: getSafeJson(result),\n },\n notifications,\n ...(getInterfaceFn ? { getInterface: getInterfaceFn } : {}),\n };\n } catch (error) {\n const [unwrappedError] = unwrapError(error);\n return {\n id: String(id),\n response: {\n error: unwrappedError.serialize(),\n },\n notifications: [],\n getInterface: getInterfaceError,\n };\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 getInterface: getInterfaceError,\n };\n }) as unknown as SnapRequest;\n\n promise.getInterface = async () => {\n const sagaPromise = runSaga(\n getInterface,\n runSaga,\n snapId,\n controllerMessenger,\n simulationOptions,\n ).toPromise();\n const result = await Promise.race([promise, sagaPromise]);\n\n // If the request promise has resolved to an error, we should throw\n // instead of waiting for an interface that likely will never be displayed\n if (\n is(result, SnapResponseStruct) &&\n hasProperty(result.response, 'error')\n ) {\n throw new Error(\n `Unable to get the interface from the Snap: The returned interface may be invalid. The error message received was: ${\n (result.response.error as JsonRpcError).message\n }`,\n );\n }\n\n return await sagaPromise;\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 assert(\n is(result.content, ComponentOrElementStruct),\n 'The Snap returned an invalid interface.',\n );\n\n const id = await controllerMessenger.call(\n 'SnapInterfaceController:createInterface',\n snapId,\n result.content as ComponentOrElement,\n );\n\n return id;\n }\n\n return undefined;\n}\n\n/**\n * Get the response content from the `SnapInterfaceController` and include the\n * interaction methods.\n *\n * @param result - The handler result object.\n * @param snapId - The Snap ID.\n * @param controllerMessenger - The controller messenger.\n * @param options - The simulation options.\n * @param contentId - The id of the interface if it exists outside of the result.\n * @returns The content components if any.\n */\nexport async function getInterfaceApi(\n result: unknown,\n snapId: SnapId,\n controllerMessenger: RootControllerMessenger,\n options: SimulationOptions,\n contentId?: string,\n): Promise<(() => SnapHandlerInterface) | undefined> {\n const interfaceId = await getInterfaceFromResult(\n result,\n snapId,\n controllerMessenger,\n );\n\n const id = interfaceId ?? contentId;\n\n if (id) {\n return () => {\n const { content } = controllerMessenger.call(\n 'SnapInterfaceController:getInterface',\n snapId,\n id,\n );\n\n const actions = getInterfaceActions(\n snapId,\n controllerMessenger,\n options,\n {\n id,\n content,\n },\n );\n\n return {\n content,\n ...actions,\n };\n };\n }\n\n return undefined;\n}\n"]}
1
+ {"version":3,"file":"request.cjs","sourceRoot":"","sources":["../src/request.ts"],"names":[],"mappings":";;;AACA,mDAK6B;AAE7B,uDAAoD;AACpD,uDAA2C;AAC3C,2CAK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,OAAO,SAAS,CAAC;AACnB,CAAC;AAzBD,wDAyBC;AAED;;;;;;;;;;GAUG;AACI,KAAK,UAAU,eAAe,CACnC,MAAe,EACf,MAAc,EACd,mBAA4C,EAC5C,OAA0B,EAC1B,SAAkB;IAElB,MAAM,WAAW,GAAG,MAAM,sBAAsB,CAC9C,MAAM,EACN,MAAM,EACN,mBAAmB,CACpB,CAAC;IAEF,MAAM,EAAE,GAAG,WAAW,IAAI,SAAS,CAAC;IAEpC,IAAI,EAAE,EAAE,CAAC;QACP,OAAO,GAAG,EAAE;YACV,MAAM,EAAE,OAAO,EAAE,GAAG,mBAAmB,CAAC,IAAI,CAC1C,sCAAsC,EACtC,MAAM,EACN,EAAE,CACH,CAAC;YAEF,MAAM,OAAO,GAAG,IAAA,+BAAmB,EACjC,MAAM,EACN,mBAAmB,EACnB,OAAO,EACP;gBACE,EAAE;gBACF,OAAO;aACR,CACF,CAAC;YAEF,OAAO;gBACL,OAAO;gBACP,GAAG,OAAO;aACX,CAAC;QACJ,CAAC,CAAC;IACJ,CAAC;IAED,OAAO,SAAS,CAAC;AACnB,CAAC;AAzCD,0CAyCC","sourcesContent":["import type { AbstractExecutionService } from '@metamask/snaps-controllers';\nimport {\n type ComponentOrElement,\n ComponentOrElementStruct,\n type JsonRpcError,\n type SnapId,\n} from '@metamask/snaps-sdk';\nimport type { HandlerType } from '@metamask/snaps-utils';\nimport { unwrapError } from '@metamask/snaps-utils';\nimport { is } from '@metamask/superstruct';\nimport {\n assert,\n getSafeJson,\n hasProperty,\n isPlainObject,\n} from '@metamask/utils';\nimport { nanoid } from '@reduxjs/toolkit';\n\nimport type { RootControllerMessenger } from './controllers';\nimport { getInterface, getInterfaceActions } from './interface';\nimport type { SimulationOptions } from './options';\nimport type { RunSagaFunction, Store } from './store';\nimport {\n getTraces,\n getErrors,\n clearNotifications,\n getNotifications,\n getEvents,\n clearTrackables,\n} from './store';\nimport { SnapResponseStruct } from './structs';\nimport type {\n RequestOptions,\n SnapHandlerInterface,\n SnapRequest,\n} from './types';\n\nexport type HandleRequestOptions = {\n snapId: SnapId;\n store: Store;\n executionService: AbstractExecutionService<unknown>;\n handler: HandlerType;\n controllerMessenger: RootControllerMessenger;\n simulationOptions: SimulationOptions;\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.simulationOptions - The simulation options.\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 simulationOptions,\n runSaga,\n request: { id = nanoid(), origin = 'https://metamask.io', ...options },\n}: HandleRequestOptions): SnapRequest {\n const getInterfaceError = () => {\n throw new Error(\n 'Unable to get the interface from the Snap: The request to the Snap failed.',\n );\n };\n\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 state = store.getState();\n const notifications = getNotifications(state);\n const errors = getErrors(state);\n const events = getEvents(state);\n const traces = getTraces(state);\n const interfaceId = notifications[0]?.content;\n\n store.dispatch(clearNotifications());\n store.dispatch(clearTrackables());\n\n try {\n const getInterfaceFn = await getInterfaceApi(\n result,\n snapId,\n controllerMessenger,\n simulationOptions,\n interfaceId,\n );\n\n return {\n id: String(id),\n response: {\n result: getSafeJson(result),\n },\n notifications,\n tracked: {\n errors,\n events,\n traces,\n },\n ...(getInterfaceFn ? { getInterface: getInterfaceFn } : {}),\n };\n } catch (error) {\n const [unwrappedError] = unwrapError(error);\n return {\n id: String(id),\n response: {\n error: unwrappedError.serialize(),\n },\n notifications: [],\n tracked: {\n errors: [],\n events: [],\n traces: [],\n },\n getInterface: getInterfaceError,\n };\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 tracked: {\n errors: [],\n events: [],\n traces: [],\n },\n getInterface: getInterfaceError,\n };\n }) as unknown as SnapRequest;\n\n promise.getInterface = async () => {\n const sagaPromise = runSaga(\n getInterface,\n runSaga,\n snapId,\n controllerMessenger,\n simulationOptions,\n ).toPromise();\n const result = await Promise.race([promise, sagaPromise]);\n\n // If the request promise has resolved to an error, we should throw\n // instead of waiting for an interface that likely will never be displayed\n if (\n is(result, SnapResponseStruct) &&\n hasProperty(result.response, 'error')\n ) {\n throw new Error(\n `Unable to get the interface from the Snap: The returned interface may be invalid. The error message received was: ${\n (result.response.error as JsonRpcError).message\n }`,\n );\n }\n\n return await sagaPromise;\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 assert(\n is(result.content, ComponentOrElementStruct),\n 'The Snap returned an invalid interface.',\n );\n\n const id = await controllerMessenger.call(\n 'SnapInterfaceController:createInterface',\n snapId,\n result.content as ComponentOrElement,\n );\n\n return id;\n }\n\n return undefined;\n}\n\n/**\n * Get the response content from the `SnapInterfaceController` and include the\n * interaction methods.\n *\n * @param result - The handler result object.\n * @param snapId - The Snap ID.\n * @param controllerMessenger - The controller messenger.\n * @param options - The simulation options.\n * @param contentId - The id of the interface if it exists outside of the result.\n * @returns The content components if any.\n */\nexport async function getInterfaceApi(\n result: unknown,\n snapId: SnapId,\n controllerMessenger: RootControllerMessenger,\n options: SimulationOptions,\n contentId?: string,\n): Promise<(() => SnapHandlerInterface) | undefined> {\n const interfaceId = await getInterfaceFromResult(\n result,\n snapId,\n controllerMessenger,\n );\n\n const id = interfaceId ?? contentId;\n\n if (id) {\n return () => {\n const { content } = controllerMessenger.call(\n 'SnapInterfaceController:getInterface',\n snapId,\n id,\n );\n\n const actions = getInterfaceActions(\n snapId,\n controllerMessenger,\n options,\n {\n id,\n content,\n },\n );\n\n return {\n content,\n ...actions,\n };\n };\n }\n\n return undefined;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"request.d.cts","sourceRoot":"","sources":["../src/request.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,wBAAwB,EAAE,oCAAoC;AAC5E,OAAO,EAIL,KAAK,MAAM,EACZ,4BAA4B;AAC7B,OAAO,KAAK,EAAE,WAAW,EAAE,8BAA8B;AAWzD,OAAO,KAAK,EAAE,uBAAuB,EAAE,0BAAsB;AAE7D,OAAO,KAAK,EAAE,iBAAiB,EAAE,sBAAkB;AAEnD,OAAO,KAAK,EAAE,eAAe,EAAE,KAAK,EAAE,0BAAgB;AAEtD,OAAO,KAAK,EACV,cAAc,EACd,oBAAoB,EACpB,WAAW,EACZ,oBAAgB;AAEjB,MAAM,MAAM,oBAAoB,GAAG;IACjC,MAAM,EAAE,MAAM,CAAC;IACf,KAAK,EAAE,KAAK,CAAC;IACb,gBAAgB,EAAE,wBAAwB,CAAC,OAAO,CAAC,CAAC;IACpD,OAAO,EAAE,WAAW,CAAC;IACrB,mBAAmB,EAAE,uBAAuB,CAAC;IAC7C,iBAAiB,EAAE,iBAAiB,CAAC;IACrC,OAAO,EAAE,eAAe,CAAC;IACzB,OAAO,EAAE,cAAc,CAAC;CACzB,CAAC;A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,OAAO,KAAK,EAAE,eAAe,EAAE,KAAK,EAAE,0BAAgB;AAUtD,OAAO,KAAK,EACV,cAAc,EACd,oBAAoB,EACpB,WAAW,EACZ,oBAAgB;AAEjB,MAAM,MAAM,oBAAoB,GAAG;IACjC,MAAM,EAAE,MAAM,CAAC;IACf,KAAK,EAAE,KAAK,CAAC;IACb,gBAAgB,EAAE,wBAAwB,CAAC,OAAO,CAAC,CAAC;IACpD,OAAO,EAAE,WAAW,CAAC;IACrB,mBAAmB,EAAE,uBAAuB,CAAC;IAC7C,iBAAiB,EAAE,iBAAiB,CAAC;IACrC,OAAO,EAAE,eAAe,CAAC;IACzB,OAAO,EAAE,cAAc,CAAC;CACzB,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,wBAAgB,aAAa,CAAC,EAC5B,MAAM,EACN,KAAK,EACL,gBAAgB,EAChB,OAAO,EACP,mBAAmB,EACnB,iBAAiB,EACjB,OAAO,EACP,OAAO,EAAE,EAAE,EAAa,EAAE,MAA8B,EAAE,GAAG,OAAO,EAAE,GACvE,EAAE,oBAAoB,GAAG,WAAW,CAgHpC;AAED;;;;;;;GAOG;AACH,wBAAsB,sBAAsB,CAC1C,MAAM,EAAE,OAAO,EACf,MAAM,EAAE,MAAM,EACd,mBAAmB,EAAE,uBAAuB,+BAsB7C;AAED;;;;;;;;;;GAUG;AACH,wBAAsB,eAAe,CACnC,MAAM,EAAE,OAAO,EACf,MAAM,EAAE,MAAM,EACd,mBAAmB,EAAE,uBAAuB,EAC5C,OAAO,EAAE,iBAAiB,EAC1B,SAAS,CAAC,EAAE,MAAM,GACjB,OAAO,CAAC,CAAC,MAAM,oBAAoB,CAAC,GAAG,SAAS,CAAC,CAmCnD"}
package/dist/request.mjs CHANGED
@@ -5,7 +5,7 @@ import { assert, getSafeJson, hasProperty, isPlainObject } from "@metamask/utils
5
5
  import $reduxjstoolkit from "@reduxjs/toolkit";
6
6
  const { nanoid } = $reduxjstoolkit;
7
7
  import { getInterface, getInterfaceActions } from "./interface.mjs";
8
- import { clearNotifications, getNotifications } from "./store/index.mjs";
8
+ import { getTraces, getErrors, clearNotifications, getNotifications, getEvents, clearTrackables } from "./store/index.mjs";
9
9
  import { SnapResponseStruct } from "./structs.mjs";
10
10
  /**
11
11
  * Send a JSON-RPC request to the Snap, and wrap the response in a
@@ -43,9 +43,14 @@ export function handleRequest({ snapId, store, executionService, handler, contro
43
43
  },
44
44
  })
45
45
  .then(async (result) => {
46
- const notifications = getNotifications(store.getState());
46
+ const state = store.getState();
47
+ const notifications = getNotifications(state);
48
+ const errors = getErrors(state);
49
+ const events = getEvents(state);
50
+ const traces = getTraces(state);
47
51
  const interfaceId = notifications[0]?.content;
48
52
  store.dispatch(clearNotifications());
53
+ store.dispatch(clearTrackables());
49
54
  try {
50
55
  const getInterfaceFn = await getInterfaceApi(result, snapId, controllerMessenger, simulationOptions, interfaceId);
51
56
  return {
@@ -54,6 +59,11 @@ export function handleRequest({ snapId, store, executionService, handler, contro
54
59
  result: getSafeJson(result),
55
60
  },
56
61
  notifications,
62
+ tracked: {
63
+ errors,
64
+ events,
65
+ traces,
66
+ },
57
67
  ...(getInterfaceFn ? { getInterface: getInterfaceFn } : {}),
58
68
  };
59
69
  }
@@ -65,6 +75,11 @@ export function handleRequest({ snapId, store, executionService, handler, contro
65
75
  error: unwrappedError.serialize(),
66
76
  },
67
77
  notifications: [],
78
+ tracked: {
79
+ errors: [],
80
+ events: [],
81
+ traces: [],
82
+ },
68
83
  getInterface: getInterfaceError,
69
84
  };
70
85
  }
@@ -77,6 +92,11 @@ export function handleRequest({ snapId, store, executionService, handler, contro
77
92
  error: unwrappedError.serialize(),
78
93
  },
79
94
  notifications: [],
95
+ tracked: {
96
+ errors: [],
97
+ events: [],
98
+ traces: [],
99
+ },
80
100
  getInterface: getInterfaceError,
81
101
  };
82
102
  });
@@ -1 +1 @@
1
- {"version":3,"file":"request.mjs","sourceRoot":"","sources":["../src/request.ts"],"names":[],"mappings":"AACA,OAAO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AO,EAAE,GAAG,mBAAmB,CAAC,IAAI,CAC1C,sCAAsC,EACtC,MAAM,EACN,EAAE,CACH,CAAC;YAEF,MAAM,OAAO,GAAG,mBAAmB,CACjC,MAAM,EACN,mBAAmB,EACnB,OAAO,EACP;gBACE,EAAE;gBACF,OAAO;aACR,CACF,CAAC;YAEF,OAAO;gBACL,OAAO;gBACP,GAAG,OAAO;aACX,CAAC;QACJ,CAAC,CAAC;IACJ,CAAC;IAED,OAAO,SAAS,CAAC;AACnB,CAAC","sourcesContent":["import type { AbstractExecutionService } from '@metamask/snaps-controllers';\nimport {\n type ComponentOrElement,\n ComponentOrElementStruct,\n type JsonRpcError,\n type SnapId,\n} from '@metamask/snaps-sdk';\nimport type { HandlerType } from '@metamask/snaps-utils';\nimport { unwrapError } from '@metamask/snaps-utils';\nimport { is } from '@metamask/superstruct';\nimport {\n assert,\n getSafeJson,\n hasProperty,\n isPlainObject,\n} from '@metamask/utils';\nimport { nanoid } from '@reduxjs/toolkit';\n\nimport type { RootControllerMessenger } from './controllers';\nimport { getInterface, getInterfaceActions } from './interface';\nimport type { SimulationOptions } from './options';\nimport { clearNotifications, getNotifications } from './store';\nimport type { RunSagaFunction, Store } from './store';\nimport { SnapResponseStruct } from './structs';\nimport type {\n RequestOptions,\n SnapHandlerInterface,\n SnapRequest,\n} from './types';\n\nexport type HandleRequestOptions = {\n snapId: SnapId;\n store: Store;\n executionService: AbstractExecutionService<unknown>;\n handler: HandlerType;\n controllerMessenger: RootControllerMessenger;\n simulationOptions: SimulationOptions;\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.simulationOptions - The simulation options.\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 simulationOptions,\n runSaga,\n request: { id = nanoid(), origin = 'https://metamask.io', ...options },\n}: HandleRequestOptions): SnapRequest {\n const getInterfaceError = () => {\n throw new Error(\n 'Unable to get the interface from the Snap: The request to the Snap failed.',\n );\n };\n\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 const interfaceId = notifications[0]?.content;\n store.dispatch(clearNotifications());\n\n try {\n const getInterfaceFn = await getInterfaceApi(\n result,\n snapId,\n controllerMessenger,\n simulationOptions,\n interfaceId,\n );\n\n return {\n id: String(id),\n response: {\n result: getSafeJson(result),\n },\n notifications,\n ...(getInterfaceFn ? { getInterface: getInterfaceFn } : {}),\n };\n } catch (error) {\n const [unwrappedError] = unwrapError(error);\n return {\n id: String(id),\n response: {\n error: unwrappedError.serialize(),\n },\n notifications: [],\n getInterface: getInterfaceError,\n };\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 getInterface: getInterfaceError,\n };\n }) as unknown as SnapRequest;\n\n promise.getInterface = async () => {\n const sagaPromise = runSaga(\n getInterface,\n runSaga,\n snapId,\n controllerMessenger,\n simulationOptions,\n ).toPromise();\n const result = await Promise.race([promise, sagaPromise]);\n\n // If the request promise has resolved to an error, we should throw\n // instead of waiting for an interface that likely will never be displayed\n if (\n is(result, SnapResponseStruct) &&\n hasProperty(result.response, 'error')\n ) {\n throw new Error(\n `Unable to get the interface from the Snap: The returned interface may be invalid. The error message received was: ${\n (result.response.error as JsonRpcError).message\n }`,\n );\n }\n\n return await sagaPromise;\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 assert(\n is(result.content, ComponentOrElementStruct),\n 'The Snap returned an invalid interface.',\n );\n\n const id = await controllerMessenger.call(\n 'SnapInterfaceController:createInterface',\n snapId,\n result.content as ComponentOrElement,\n );\n\n return id;\n }\n\n return undefined;\n}\n\n/**\n * Get the response content from the `SnapInterfaceController` and include the\n * interaction methods.\n *\n * @param result - The handler result object.\n * @param snapId - The Snap ID.\n * @param controllerMessenger - The controller messenger.\n * @param options - The simulation options.\n * @param contentId - The id of the interface if it exists outside of the result.\n * @returns The content components if any.\n */\nexport async function getInterfaceApi(\n result: unknown,\n snapId: SnapId,\n controllerMessenger: RootControllerMessenger,\n options: SimulationOptions,\n contentId?: string,\n): Promise<(() => SnapHandlerInterface) | undefined> {\n const interfaceId = await getInterfaceFromResult(\n result,\n snapId,\n controllerMessenger,\n );\n\n const id = interfaceId ?? contentId;\n\n if (id) {\n return () => {\n const { content } = controllerMessenger.call(\n 'SnapInterfaceController:getInterface',\n snapId,\n id,\n );\n\n const actions = getInterfaceActions(\n snapId,\n controllerMessenger,\n options,\n {\n id,\n content,\n },\n );\n\n return {\n content,\n ...actions,\n };\n };\n }\n\n return undefined;\n}\n"]}
1
+ {"version":3,"file":"request.mjs","sourceRoot":"","sources":["../src/request.ts"],"names":[],"mappings":"AACA,OAAO,EAEL,wBAAwB,EAGzB,4BAA4B;AAE7B,OAAO,EAAE,WAAW,EAAE,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,mBAAmB,CAAC,IAAI,CACvC,yCAAyC,EACzC,MAAM,EACN,MAAM,CAAC,OAA6B,CACrC,CAAC;QAEF,OAAO,EAAE,CAAC;IACZ,CAAC;IAED,OAAO,SAAS,CAAC;AACnB,CAAC;AAED;;;;;;;;;;GAUG;AACH,MAAM,CAAC,KAAK,UAAU,eAAe,CACnC,MAAe,EACf,MAAc,EACd,mBAA4C,EAC5C,OAA0B,EAC1B,SAAkB;IAElB,MAAM,WAAW,GAAG,MAAM,sBAAsB,CAC9C,MAAM,EACN,MAAM,EACN,mBAAmB,CACpB,CAAC;IAEF,MAAM,EAAE,GAAG,WAAW,IAAI,SAAS,CAAC;IAEpC,IAAI,EAAE,EAAE,CAAC;QACP,OAAO,GAAG,EAAE;YACV,MAAM,EAAE,OAAO,EAAE,GAAG,mBAAmB,CAAC,IAAI,CAC1C,sCAAsC,EACtC,MAAM,EACN,EAAE,CACH,CAAC;YAEF,MAAM,OAAO,GAAG,mBAAmB,CACjC,MAAM,EACN,mBAAmB,EACnB,OAAO,EACP;gBACE,EAAE;gBACF,OAAO;aACR,CACF,CAAC;YAEF,OAAO;gBACL,OAAO;gBACP,GAAG,OAAO;aACX,CAAC;QACJ,CAAC,CAAC;IACJ,CAAC;IAED,OAAO,SAAS,CAAC;AACnB,CAAC","sourcesContent":["import type { AbstractExecutionService } from '@metamask/snaps-controllers';\nimport {\n type ComponentOrElement,\n ComponentOrElementStruct,\n type JsonRpcError,\n type SnapId,\n} from '@metamask/snaps-sdk';\nimport type { HandlerType } from '@metamask/snaps-utils';\nimport { unwrapError } from '@metamask/snaps-utils';\nimport { is } from '@metamask/superstruct';\nimport {\n assert,\n getSafeJson,\n hasProperty,\n isPlainObject,\n} from '@metamask/utils';\nimport { nanoid } from '@reduxjs/toolkit';\n\nimport type { RootControllerMessenger } from './controllers';\nimport { getInterface, getInterfaceActions } from './interface';\nimport type { SimulationOptions } from './options';\nimport type { RunSagaFunction, Store } from './store';\nimport {\n getTraces,\n getErrors,\n clearNotifications,\n getNotifications,\n getEvents,\n clearTrackables,\n} from './store';\nimport { SnapResponseStruct } from './structs';\nimport type {\n RequestOptions,\n SnapHandlerInterface,\n SnapRequest,\n} from './types';\n\nexport type HandleRequestOptions = {\n snapId: SnapId;\n store: Store;\n executionService: AbstractExecutionService<unknown>;\n handler: HandlerType;\n controllerMessenger: RootControllerMessenger;\n simulationOptions: SimulationOptions;\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.simulationOptions - The simulation options.\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 simulationOptions,\n runSaga,\n request: { id = nanoid(), origin = 'https://metamask.io', ...options },\n}: HandleRequestOptions): SnapRequest {\n const getInterfaceError = () => {\n throw new Error(\n 'Unable to get the interface from the Snap: The request to the Snap failed.',\n );\n };\n\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 state = store.getState();\n const notifications = getNotifications(state);\n const errors = getErrors(state);\n const events = getEvents(state);\n const traces = getTraces(state);\n const interfaceId = notifications[0]?.content;\n\n store.dispatch(clearNotifications());\n store.dispatch(clearTrackables());\n\n try {\n const getInterfaceFn = await getInterfaceApi(\n result,\n snapId,\n controllerMessenger,\n simulationOptions,\n interfaceId,\n );\n\n return {\n id: String(id),\n response: {\n result: getSafeJson(result),\n },\n notifications,\n tracked: {\n errors,\n events,\n traces,\n },\n ...(getInterfaceFn ? { getInterface: getInterfaceFn } : {}),\n };\n } catch (error) {\n const [unwrappedError] = unwrapError(error);\n return {\n id: String(id),\n response: {\n error: unwrappedError.serialize(),\n },\n notifications: [],\n tracked: {\n errors: [],\n events: [],\n traces: [],\n },\n getInterface: getInterfaceError,\n };\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 tracked: {\n errors: [],\n events: [],\n traces: [],\n },\n getInterface: getInterfaceError,\n };\n }) as unknown as SnapRequest;\n\n promise.getInterface = async () => {\n const sagaPromise = runSaga(\n getInterface,\n runSaga,\n snapId,\n controllerMessenger,\n simulationOptions,\n ).toPromise();\n const result = await Promise.race([promise, sagaPromise]);\n\n // If the request promise has resolved to an error, we should throw\n // instead of waiting for an interface that likely will never be displayed\n if (\n is(result, SnapResponseStruct) &&\n hasProperty(result.response, 'error')\n ) {\n throw new Error(\n `Unable to get the interface from the Snap: The returned interface may be invalid. The error message received was: ${\n (result.response.error as JsonRpcError).message\n }`,\n );\n }\n\n return await sagaPromise;\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 assert(\n is(result.content, ComponentOrElementStruct),\n 'The Snap returned an invalid interface.',\n );\n\n const id = await controllerMessenger.call(\n 'SnapInterfaceController:createInterface',\n snapId,\n result.content as ComponentOrElement,\n );\n\n return id;\n }\n\n return undefined;\n}\n\n/**\n * Get the response content from the `SnapInterfaceController` and include the\n * interaction methods.\n *\n * @param result - The handler result object.\n * @param snapId - The Snap ID.\n * @param controllerMessenger - The controller messenger.\n * @param options - The simulation options.\n * @param contentId - The id of the interface if it exists outside of the result.\n * @returns The content components if any.\n */\nexport async function getInterfaceApi(\n result: unknown,\n snapId: SnapId,\n controllerMessenger: RootControllerMessenger,\n options: SimulationOptions,\n contentId?: string,\n): Promise<(() => SnapHandlerInterface) | undefined> {\n const interfaceId = await getInterfaceFromResult(\n result,\n snapId,\n controllerMessenger,\n );\n\n const id = interfaceId ?? contentId;\n\n if (id) {\n return () => {\n const { content } = controllerMessenger.call(\n 'SnapInterfaceController:getInterface',\n snapId,\n id,\n );\n\n const actions = getInterfaceActions(\n snapId,\n controllerMessenger,\n options,\n {\n id,\n content,\n },\n );\n\n return {\n content,\n ...actions,\n };\n };\n }\n\n return undefined;\n}\n"]}
@@ -79,7 +79,7 @@ async function installSnap(snapId, { executionService, executionServiceOptions,
79
79
  // Error function is difficult to test, so we ignore it.
80
80
  /* istanbul ignore next 2 */
81
81
  (0, readable_stream_1.pipeline)(stream, providerStream, stream, (error) => {
82
- if (error) {
82
+ if (error && !error.message?.match('Premature close')) {
83
83
  (0, snaps_utils_1.logError)(`Provider stream failure.`, error);
84
84
  }
85
85
  });
@@ -155,6 +155,11 @@ function getPermittedHooks(snapId, snapFiles, controllerMessenger, runSaga) {
155
155
  getSnapState: (0, hooks_1.getPermittedGetSnapStateMethodImplementation)(runSaga),
156
156
  updateSnapState: (0, hooks_1.getPermittedUpdateSnapStateMethodImplementation)(runSaga),
157
157
  clearSnapState: (0, hooks_1.getPermittedClearSnapStateMethodImplementation)(runSaga),
158
+ getSnap: (0, hooks_1.getGetSnapImplementation)(true),
159
+ trackError: (0, hooks_1.getTrackErrorImplementation)(runSaga),
160
+ trackEvent: (0, hooks_1.getTrackEventImplementation)(runSaga),
161
+ startTrace: (0, hooks_1.getStartTraceImplementation)(runSaga),
162
+ endTrace: (0, hooks_1.getEndTraceImplementation)(runSaga),
158
163
  };
159
164
  }
160
165
  exports.getPermittedHooks = getPermittedHooks;
@@ -1 +1 @@
1
- {"version":3,"file":"simulation.cjs","sourceRoot":"","sources":["../src/simulation.ts"],"names":[],"mappings":";;;AAIA,+DAAsD;AACtD,qFAA0E;AAE1E,uEAA2E;AAE3E,2DAK0C;AAC1C,mEAAoE;AAUpE,uDAAiD;AAGjD,qDAA2C;AAE3C,gDAA4C;AAG5C,mDAA6D;AAC7D,uCAAsC;AAEtC,2CAAuC;AACvC,+CAA8C;AAC9C,iDAAwD;AACxD,qDAMyB;AACzB,6EAAqF;AACrF,uDAAmD;AAEnD,2CAAuC;AAEvC,6CAA2D;AAC3D,iDAA2D;AAqN3D;;;;;;;;;;;;;;GAcG;AACI,KAAK,UAAU,WAAW,CAK/B,MAAc,EACd,EACE,gBAAgB,EAChB,uBAAuB,EACvB,OAAO,EAAE,UAAU,GAAG,EAAE,MACgB,EAAE;IAE5C,MAAM,OAAO,GAAG,IAAA,oBAAU,EAAC,UAAU,CAAC,CAAC;IAEvC,oBAAoB;IACpB,MAAM,QAAQ,GAAG,IAAA,yBAAkB,EAAC,MAAM,EAAE;QAC1C,UAAU,EAAE,IAAI;KACjB,CAAC,CAAC;IAEH,MAAM,SAAS,GAAG,MAAM,IAAA,gBAAS,EAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;IAEpD,sBAAsB;IACtB,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,GAAG,IAAA,mBAAW,EAAC,OAAO,CAAC,CAAC;IAEhD,MAAM,mBAAmB,GAAG,IAAI,2BAAS,EAAY,CAAC;IAEtD,eAAe,CAAC,mBAAmB,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,CAAC,CAAC;IAE/D,yCAAyC;IACzC,MAAM,eAAe,GAAG,kBAAkB,CAAC,OAAO,CAAC,CAAC;IACpD,MAAM,cAAc,GAAG,iBAAiB,CACtC,MAAM,EACN,SAAS,EACT,m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,EAAE,OAAO,EAAE,EAAE;YACf,GAAG,CAAC,OAAO,CAAC,EAAE,CAAC,GAAG,OAAO,CAAC,MAAM,IAAI,EAAE,CAAC;YACvC,OAAO,GAAG,CAAC;QACb,CAAC,EACD,EAAE,CACH;KACF,CAAC,CACH,CAAC;IAEF,mBAAmB,CAAC,qBAAqB,CACvC,+BAA+B,EAC/B,CAAC,IAAI,EAAE,EAAE;QACP;;;;;WAKG;QACH,QAAQ,CAAC,CAAC,uBAAuB;YAC/B,MAAM,gBAAgB,GAAc,MAAM,IAAA,gBAAM,EAAC,2BAAmB,CAAC,CAAC;YACtE,OAAO,gBAAgB,CAAC;QAC1B,CAAC;QAED,MAAM,gBAAgB,GAA0B,OAAO,CACrD,uBAAuB,CACxB,CAAC,MAAM,EAAE,CAAC;QACX,OAAO,CACL,gBAAgB,EAAE,IAAI,KAAK,yCAAqB,CAAC,OAAO;YACxD,gBAAgB,EAAE,EAAE,KAAK,IAAI,EAAE,EAAE,CAClC,CAAC;IACJ,CAAC,CACF,CAAC;IAEF,mBAAmB,CAAC,qBAAqB,CACvC,kCAAkC,EAClC,KAAK,EAAE,GAAW,EAAE,KAAc,EAAE,EAAE;QACpC,MAAM,OAAO,CAAC,2BAAe,EAAE,KAAK,CAAC,CAAC,SAAS,EAAE,CAAC;QAElD,OAAO,EAAE,KAAK,EAAE,CAAC;IACnB,CAAC,CACF,CAAC;AACJ,CAAC;AAxGD,0CAwGC","sourcesContent":["import type {\n ActionConstraint,\n EventConstraint,\n} from '@metamask/base-controller';\nimport { Messenger } from '@metamask/base-controller';\nimport { createEngineStream } from '@metamask/json-rpc-middleware-stream';\nimport type { CryptographicFunctions } from '@metamask/key-tree';\nimport { PhishingDetectorResultType } from '@metamask/phishing-controller';\nimport type { AbstractExecutionService } from '@metamask/snaps-controllers';\nimport {\n detectSnapLocation,\n fetchSnap,\n NodeThreadExecutionService,\n setupMultiplex,\n} from '@metamask/snaps-controllers/node';\nimport { DIALOG_APPROVAL_TYPES } from '@metamask/snaps-rpc-methods';\nimport {\n type AuxiliaryFileEncoding,\n type Component,\n type InterfaceState,\n type InterfaceContext,\n type SnapId,\n type EntropySource,\n} from '@metamask/snaps-sdk';\nimport type { FetchedSnapFiles } from '@metamask/snaps-utils';\nimport { logError } from '@metamask/snaps-utils';\nimport type { CaipAssetType, Json } from '@metamask/utils';\nimport type { Duplex } from 'readable-stream';\nimport { pipeline } from 'readable-stream';\nimport type { SagaIterator } from 'redux-saga';\nimport { select } from 'redux-saga/effects';\n\nimport type { RootControllerMessenger } from './controllers';\nimport { getControllers, registerSnap } from './controllers';\nimport { getSnapFile } from './files';\nimport type { SnapHelpers } from './helpers';\nimport { getHelpers } from './helpers';\nimport { resolveWithSaga } from './interface';\nimport { asyncResolve, getEndowments } from './methods';\nimport {\n getPermittedClearSnapStateMethodImplementation,\n getPermittedGetSnapStateMethodImplementation,\n getPermittedUpdateSnapStateMethodImplementation,\n getGetEntropySourcesImplementation,\n getGetMnemonicImplementation,\n} from './methods/hooks';\nimport { getGetMnemonicSeedImplementation } from './methods/hooks/get-mnemonic-seed';\nimport { createJsonRpcEngine } from './middleware';\nimport type { SimulationOptions, SimulationUserOptions } from './options';\nimport { getOptions } from './options';\nimport type { Interface, RunSagaFunction, Store } from './store';\nimport { createStore, getCurrentInterface } from './store';\nimport { addSnapMetadataToAccount } from './utils/account';\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 (\n ...args: any[]\n ) => InstanceType<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: Messenger<ActionConstraint, EventConstraint>;\n runSaga: RunSagaFunction;\n};\n\nexport type RestrictedMiddlewareHooks = {\n /**\n * A hook that returns the user's secret recovery phrase.\n *\n * @param source - The entropy source to get the mnemonic from.\n * @returns The user's secret recovery phrase.\n */\n getMnemonic: (source?: string | undefined) => Promise<Uint8Array>;\n\n /**\n * A hook that returns the seed derived from the user's secret recovery phrase.\n *\n * @param source - The entropy source to get the seed from.\n * @returns The seed.\n */\n getMnemonicSeed: (source?: string | undefined) => Promise<Uint8Array>;\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\n /**\n * Get the cryptographic functions to use for the client. This may return an\n * empty object to fall back to the default cryptographic functions.\n *\n * @returns The cryptographic functions to use for the client.\n */\n getClientCryptography: () => CryptographicFunctions;\n};\n\nexport type PermittedMiddlewareHooks = {\n /**\n * A hook that gets whether the requesting origin has a given permission.\n *\n * @param permissionName - The name of the permission to check.\n * @returns Whether the origin has the permission.\n */\n hasPermission: (permissionName: string) => boolean;\n\n /**\n * A hook that returns the entropy sources available to the Snap.\n *\n * @returns The entropy sources available to the Snap.\n */\n getEntropySources: () => EntropySource[];\n\n /**\n * A hook that returns a promise that resolves once the extension is unlocked.\n *\n * @param shouldShowUnlockRequest - Whether to show the unlock request.\n * @returns A promise that resolves once the extension is unlocked.\n */\n getUnlockPromise: (shouldShowUnlockRequest: boolean) => Promise<void>;\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\n /**\n * A hook that returns whether the client is active or not.\n *\n * @returns A boolean flag signaling whether the client is opened.\n */\n getIsActive: () => boolean;\n\n /**\n * A hook that returns the Snap's auxiliary file for the given path. This hook\n * is bound to the Snap ID.\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 gets the state of the Snap. This hook is bound to the Snap ID.\n *\n * @param encrypted - Whether to get the encrypted or unencrypted state.\n * @returns The current state of the Snap.\n */\n getSnapState: (encrypted: boolean) => Promise<Record<string, Json>>;\n\n /**\n * A hook that updates the state of the Snap. This hook is bound to the Snap\n * ID.\n *\n * @param newState - The new state.\n * @param encrypted - Whether to update the encrypted or unencrypted state.\n */\n updateSnapState: (\n newState: Record<string, Json>,\n encrypted: boolean,\n ) => Promise<void>;\n\n /**\n * A hook that clears the state of the Snap. This hook is bound to the Snap\n * ID.\n *\n * @param encrypted - Whether to clear the encrypted or unencrypted state.\n */\n clearSnapState: (encrypted: boolean) => Promise<void>;\n\n /**\n * A hook that creates an interface for the Snap. This hook is bound to the\n * Snap ID.\n *\n * @param content - The content of the interface.\n * @param context - The context of the interface.\n * @returns The ID of the created interface.\n */\n createInterface: (\n content: Component,\n context?: InterfaceContext,\n ) => Promise<string>;\n\n /**\n * A hook that updates an interface for the Snap. This hook is bound to the\n * Snap ID.\n *\n * @param id - The ID of the interface to update.\n * @param content - The content of the interface.\n */\n updateInterface: (id: string, content: Component) => Promise<void>;\n\n /**\n * A hook that gets the state of an interface for the Snap. This hook is bound\n * to the Snap ID.\n *\n * @param id - The ID of the interface to get.\n * @returns The state of the interface.\n */\n getInterfaceState: (id: string) => InterfaceState;\n\n /**\n * A hook that gets the context of an interface for the Snap. This hook is\n * bound to the Snap ID.\n *\n * @param id - The ID of the interface to get.\n * @returns The context of the interface.\n */\n getInterfaceContext: (id: string) => InterfaceContext | null;\n\n /**\n * A hook that resolves an interface for the Snap. This hook is bound to the\n * Snap ID.\n *\n * @param id - The ID of the interface to resolve.\n * @param value - The value to resolve the interface with.\n */\n resolveInterface: (id: string, value: Json) => Promise<void>;\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 * @returns The installed Snap object.\n * @template Service - The type of the execution service.\n */\nexport async function installSnap<\n Service extends new (\n ...args: any[]\n ) => InstanceType<typeof AbstractExecutionService>,\n>(\n snapId: SnapId,\n {\n executionService,\n executionServiceOptions,\n options: rawOptions = {},\n }: Partial<InstallSnapOptions<Service>> = {},\n): Promise<InstalledSnap & SnapHelpers> {\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 Messenger<any, any>();\n\n registerActions(controllerMessenger, runSaga, options, snapId);\n\n // Set up controllers and JSON-RPC stack.\n const restrictedHooks = getRestrictedHooks(options);\n const permittedHooks = getPermittedHooks(\n snapId,\n snapFiles,\n controllerMessenger,\n runSaga,\n );\n\n const { subjectMetadataController, permissionController } = getControllers({\n controllerMessenger,\n hooks: restrictedHooks,\n runSaga,\n options,\n });\n\n const engine = createJsonRpcEngine({\n store,\n restrictedHooks,\n permittedHooks,\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 const helpers = getHelpers({\n snapId,\n store,\n controllerMessenger,\n runSaga,\n executionService: service,\n options,\n });\n\n return {\n snapId,\n store,\n executionService: service,\n controllerMessenger,\n runSaga,\n ...helpers,\n };\n}\n\n/**\n * Get the hooks for the simulation.\n *\n * @param options - The simulation options.\n * @returns The hooks for the simulation.\n */\nexport function getRestrictedHooks(\n options: SimulationOptions,\n): RestrictedMiddlewareHooks {\n return {\n getMnemonic: getGetMnemonicImplementation(options.secretRecoveryPhrase),\n getMnemonicSeed: getGetMnemonicSeedImplementation(\n options.secretRecoveryPhrase,\n ),\n getIsLocked: () => false,\n getClientCryptography: () => ({}),\n };\n}\n\n/**\n * Get the permitted hooks for the simulation.\n *\n * @param snapId - The ID of the Snap.\n * @param snapFiles - The fetched Snap files.\n * @param controllerMessenger - The controller messenger.\n * @param runSaga - The run saga function.\n * @returns The permitted hooks for the simulation.\n */\nexport function getPermittedHooks(\n snapId: SnapId,\n snapFiles: FetchedSnapFiles,\n controllerMessenger: RootControllerMessenger,\n runSaga: RunSagaFunction,\n): PermittedMiddlewareHooks {\n return {\n hasPermission: () => true,\n getUnlockPromise: asyncResolve(),\n getIsLocked: () => false,\n getIsActive: () => true,\n\n getSnapFile: async (path: string, encoding: AuxiliaryFileEncoding) =>\n await getSnapFile(snapFiles.auxiliaryFiles, path, encoding),\n\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 getInterfaceContext: (...args) =>\n controllerMessenger.call(\n 'SnapInterfaceController:getInterface',\n snapId,\n ...args,\n ).context,\n resolveInterface: async (...args) =>\n controllerMessenger.call(\n 'SnapInterfaceController:resolveInterface',\n snapId,\n ...args,\n ),\n\n getEntropySources: getGetEntropySourcesImplementation(),\n getSnapState: getPermittedGetSnapStateMethodImplementation(runSaga),\n updateSnapState: getPermittedUpdateSnapStateMethodImplementation(runSaga),\n clearSnapState: getPermittedClearSnapStateMethodImplementation(runSaga),\n };\n}\n\n/**\n * Register mocked action handlers.\n *\n * @param controllerMessenger - The controller messenger.\n * @param runSaga - The run saga function.\n * @param options - The simulation options.\n * @param snapId - The ID of the Snap.\n */\nexport function registerActions(\n controllerMessenger: RootControllerMessenger,\n runSaga: RunSagaFunction,\n options: SimulationOptions,\n snapId: SnapId,\n) {\n controllerMessenger.registerActionHandler(\n 'PhishingController:testOrigin',\n () => ({ result: false, type: PhishingDetectorResultType.All }),\n );\n\n controllerMessenger.registerActionHandler(\n 'AccountsController:getAccountByAddress',\n // @ts-expect-error - This is a partial account with only the necessary\n // data used by the interface controller.\n (address) => {\n const matchingAccount = options.accounts.find(\n (account) => address === account.address,\n );\n\n if (!matchingAccount) {\n return undefined;\n }\n\n return addSnapMetadataToAccount(matchingAccount, snapId);\n },\n );\n\n controllerMessenger.registerActionHandler(\n 'AccountsController:getSelectedMultichainAccount',\n // @ts-expect-error - This is a partial account with only the necessary\n // data used by the interface controller.\n () => {\n const selectedAccount = options.accounts.find(\n (account) => account.selected,\n );\n\n if (!selectedAccount) {\n return undefined;\n }\n\n return addSnapMetadataToAccount(selectedAccount, snapId);\n },\n );\n\n controllerMessenger.registerActionHandler(\n 'AccountsController:listMultichainAccounts',\n\n () =>\n // @ts-expect-error - These are partial accounts with only the necessary\n // data used by the interface controller.\n options.accounts.map((account) =>\n addSnapMetadataToAccount(account, snapId),\n ),\n );\n\n controllerMessenger.registerActionHandler(\n 'MultichainAssetsController:getState',\n () => ({\n // @ts-expect-error - These are partial assets with only the\n // necessary data used by the interface controller.\n assetsMetadata: options.assets,\n accountsAssets: options.accounts.reduce<Record<string, CaipAssetType[]>>(\n (acc, account) => {\n acc[account.id] = account.assets ?? [];\n return acc;\n },\n {},\n ),\n }),\n );\n\n controllerMessenger.registerActionHandler(\n 'ApprovalController:hasRequest',\n (opts) => {\n /**\n * Get the current interface from the store.\n *\n * @yields Selects the current interface from the store.\n * @returns The current interface.\n */\n function* getCurrentInterfaceSaga(): SagaIterator {\n const currentInterface: Interface = yield select(getCurrentInterface);\n return currentInterface;\n }\n\n const currentInterface: Interface | undefined = runSaga(\n getCurrentInterfaceSaga,\n ).result();\n return (\n currentInterface?.type === DIALOG_APPROVAL_TYPES.default &&\n currentInterface?.id === opts?.id\n );\n },\n );\n\n controllerMessenger.registerActionHandler(\n 'ApprovalController:acceptRequest',\n async (_id: string, value: unknown) => {\n await runSaga(resolveWithSaga, value).toPromise();\n\n return { value };\n },\n );\n}\n"]}
1
+ {"version":3,"file":"simulation.cjs","sourceRoot":"","sources":["../src/simulation.ts"],"names":[],"mappings":";;;AAIA,+DAAsD;AACtD,qFAA0E;AAE1E,uEAA2E;AAE3E,2DAK0C;AAC1C,mEAAoE;AAcpE,uDAAiD;AAGjD,qDAA2C;AAE3C,gDAA4C;AAG5C,mDAA6D;AAC7D,uCAAsC;AAEtC,2CAAuC;AACvC,+CAA8C;AAC9C,iDAAwD;AAC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AAE,CAAC,GAAG,OAAO,CAAC,MAAM,IAAI,EAAE,CAAC;YACvC,OAAO,GAAG,CAAC;QACb,CAAC,EACD,EAAE,CACH;KACF,CAAC,CACH,CAAC;IAEF,mBAAmB,CAAC,qBAAqB,CACvC,+BAA+B,EAC/B,CAAC,IAAI,EAAE,EAAE;QACP;;;;;WAKG;QACH,QAAQ,CAAC,CAAC,uBAAuB;YAC/B,MAAM,gBAAgB,GAAc,MAAM,IAAA,gBAAM,EAAC,2BAAmB,CAAC,CAAC;YACtE,OAAO,gBAAgB,CAAC;QAC1B,CAAC;QAED,MAAM,gBAAgB,GAA0B,OAAO,CACrD,uBAAuB,CACxB,CAAC,MAAM,EAAE,CAAC;QACX,OAAO,CACL,gBAAgB,EAAE,IAAI,KAAK,yCAAqB,CAAC,OAAO;YACxD,gBAAgB,EAAE,EAAE,KAAK,IAAI,EAAE,EAAE,CAClC,CAAC;IACJ,CAAC,CACF,CAAC;IAEF,mBAAmB,CAAC,qBAAqB,CACvC,kCAAkC,EAClC,KAAK,EAAE,GAAW,EAAE,KAAc,EAAE,EAAE;QACpC,MAAM,OAAO,CAAC,2BAAe,EAAE,KAAK,CAAC,CAAC,SAAS,EAAE,CAAC;QAElD,OAAO,EAAE,KAAK,EAAE,CAAC;IACnB,CAAC,CACF,CAAC;AACJ,CAAC;AAxGD,0CAwGC","sourcesContent":["import type {\n ActionConstraint,\n EventConstraint,\n} from '@metamask/base-controller';\nimport { Messenger } from '@metamask/base-controller';\nimport { createEngineStream } from '@metamask/json-rpc-middleware-stream';\nimport type { CryptographicFunctions } from '@metamask/key-tree';\nimport { PhishingDetectorResultType } from '@metamask/phishing-controller';\nimport type { AbstractExecutionService } from '@metamask/snaps-controllers';\nimport {\n detectSnapLocation,\n fetchSnap,\n NodeThreadExecutionService,\n setupMultiplex,\n} from '@metamask/snaps-controllers/node';\nimport { DIALOG_APPROVAL_TYPES } from '@metamask/snaps-rpc-methods';\nimport type {\n TrackEventParams,\n AuxiliaryFileEncoding,\n Component,\n InterfaceState,\n InterfaceContext,\n SnapId,\n EntropySource,\n TraceRequest,\n EndTraceRequest,\n TraceContext,\n} from '@metamask/snaps-sdk';\nimport type { FetchedSnapFiles, Snap } from '@metamask/snaps-utils';\nimport { logError } from '@metamask/snaps-utils';\nimport type { CaipAssetType, Json } from '@metamask/utils';\nimport type { Duplex } from 'readable-stream';\nimport { pipeline } from 'readable-stream';\nimport type { SagaIterator } from 'redux-saga';\nimport { select } from 'redux-saga/effects';\n\nimport type { RootControllerMessenger } from './controllers';\nimport { getControllers, registerSnap } from './controllers';\nimport { getSnapFile } from './files';\nimport type { SnapHelpers } from './helpers';\nimport { getHelpers } from './helpers';\nimport { resolveWithSaga } from './interface';\nimport { asyncResolve, getEndowments } from './methods';\nimport {\n getPermittedClearSnapStateMethodImplementation,\n getPermittedGetSnapStateMethodImplementation,\n getPermittedUpdateSnapStateMethodImplementation,\n getGetEntropySourcesImplementation,\n getGetMnemonicImplementation,\n getGetSnapImplementation,\n getTrackEventImplementation,\n getTrackErrorImplementation,\n getEndTraceImplementation,\n getStartTraceImplementation,\n} from './methods/hooks';\nimport { getGetMnemonicSeedImplementation } from './methods/hooks/get-mnemonic-seed';\nimport { createJsonRpcEngine } from './middleware';\nimport type { SimulationOptions, SimulationUserOptions } from './options';\nimport { getOptions } from './options';\nimport type { Interface, RunSagaFunction, Store } from './store';\nimport { createStore, getCurrentInterface } from './store';\nimport { addSnapMetadataToAccount } from './utils/account';\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 (\n ...args: any[]\n ) => InstanceType<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: Messenger<ActionConstraint, EventConstraint>;\n runSaga: RunSagaFunction;\n};\n\nexport type RestrictedMiddlewareHooks = {\n /**\n * A hook that returns the user's secret recovery phrase.\n *\n * @param source - The entropy source to get the mnemonic from.\n * @returns The user's secret recovery phrase.\n */\n getMnemonic: (source?: string | undefined) => Promise<Uint8Array>;\n\n /**\n * A hook that returns the seed derived from the user's secret recovery phrase.\n *\n * @param source - The entropy source to get the seed from.\n * @returns The seed.\n */\n getMnemonicSeed: (source?: string | undefined) => Promise<Uint8Array>;\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\n /**\n * Get the cryptographic functions to use for the client. This may return an\n * empty object to fall back to the default cryptographic functions.\n *\n * @returns The cryptographic functions to use for the client.\n */\n getClientCryptography: () => CryptographicFunctions;\n};\n\nexport type PermittedMiddlewareHooks = {\n /**\n * A hook that gets whether the requesting origin has a given permission.\n *\n * @param permissionName - The name of the permission to check.\n * @returns Whether the origin has the permission.\n */\n hasPermission: (permissionName: string) => boolean;\n\n /**\n * A hook that returns the entropy sources available to the Snap.\n *\n * @returns The entropy sources available to the Snap.\n */\n getEntropySources: () => EntropySource[];\n\n /**\n * A hook that returns a promise that resolves once the extension is unlocked.\n *\n * @param shouldShowUnlockRequest - Whether to show the unlock request.\n * @returns A promise that resolves once the extension is unlocked.\n */\n getUnlockPromise: (shouldShowUnlockRequest: boolean) => Promise<void>;\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\n /**\n * A hook that returns whether the client is active or not.\n *\n * @returns A boolean flag signaling whether the client is opened.\n */\n getIsActive: () => boolean;\n\n /**\n * A hook that returns the Snap's auxiliary file for the given path. This hook\n * is bound to the Snap ID.\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 gets the state of the Snap. This hook is bound to the Snap ID.\n *\n * @param encrypted - Whether to get the encrypted or unencrypted state.\n * @returns The current state of the Snap.\n */\n getSnapState: (encrypted: boolean) => Promise<Record<string, Json>>;\n\n /**\n * A hook that updates the state of the Snap. This hook is bound to the Snap\n * ID.\n *\n * @param newState - The new state.\n * @param encrypted - Whether to update the encrypted or unencrypted state.\n */\n updateSnapState: (\n newState: Record<string, Json>,\n encrypted: boolean,\n ) => Promise<void>;\n\n /**\n * A hook that clears the state of the Snap. This hook is bound to the Snap\n * ID.\n *\n * @param encrypted - Whether to clear the encrypted or unencrypted state.\n */\n clearSnapState: (encrypted: boolean) => Promise<void>;\n\n /**\n * A hook that creates an interface for the Snap. This hook is bound to the\n * Snap ID.\n *\n * @param content - The content of the interface.\n * @param context - The context of the interface.\n * @returns The ID of the created interface.\n */\n createInterface: (\n content: Component,\n context?: InterfaceContext,\n ) => Promise<string>;\n\n /**\n * A hook that updates an interface for the Snap. This hook is bound to the\n * Snap ID.\n *\n * @param id - The ID of the interface to update.\n * @param content - The content of the interface.\n */\n updateInterface: (id: string, content: Component) => Promise<void>;\n\n /**\n * A hook that gets the state of an interface for the Snap. This hook is bound\n * to the Snap ID.\n *\n * @param id - The ID of the interface to get.\n * @returns The state of the interface.\n */\n getInterfaceState: (id: string) => InterfaceState;\n\n /**\n * A hook that gets the context of an interface for the Snap. This hook is\n * bound to the Snap ID.\n *\n * @param id - The ID of the interface to get.\n * @returns The context of the interface.\n */\n getInterfaceContext: (id: string) => InterfaceContext | null;\n\n /**\n * A hook that resolves an interface for the Snap. This hook is bound to the\n * Snap ID.\n *\n * @param id - The ID of the interface to resolve.\n * @param value - The value to resolve the interface with.\n */\n resolveInterface: (id: string, value: Json) => Promise<void>;\n\n /**\n * A hook that gets the Snap's metadata.\n *\n * @param snapId - The ID of the Snap to get.\n * @returns The Snap's metadata.\n */\n getSnap(snapId: string): Snap;\n\n /**\n * A hook that tracks an error.\n *\n * @param error - The error object containing error details and properties.\n */\n trackError(error: Error): void;\n\n /**\n * A hook that tracks an event.\n *\n * @param event - The event object containing event details and properties.\n */\n trackEvent(event: TrackEventParams['event']): void;\n\n /**\n * A hook that starts a performance trace.\n *\n * @param request - The trace request object containing trace details.\n */\n startTrace(request: TraceRequest): TraceContext;\n\n /**\n * A hook that ends a performance trace.\n *\n * @param request - The trace request object containing trace details.\n * @returns The trace data.\n */\n endTrace(request: EndTraceRequest): void;\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 * @returns The installed Snap object.\n * @template Service - The type of the execution service.\n */\nexport async function installSnap<\n Service extends new (\n ...args: any[]\n ) => InstanceType<typeof AbstractExecutionService>,\n>(\n snapId: SnapId,\n {\n executionService,\n executionServiceOptions,\n options: rawOptions = {},\n }: Partial<InstallSnapOptions<Service>> = {},\n): Promise<InstalledSnap & SnapHelpers> {\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 Messenger<any, any>();\n\n registerActions(controllerMessenger, runSaga, options, snapId);\n\n // Set up controllers and JSON-RPC stack.\n const restrictedHooks = getRestrictedHooks(options);\n const permittedHooks = getPermittedHooks(\n snapId,\n snapFiles,\n controllerMessenger,\n runSaga,\n );\n\n const { subjectMetadataController, permissionController } = getControllers({\n controllerMessenger,\n hooks: restrictedHooks,\n runSaga,\n options,\n });\n\n const engine = createJsonRpcEngine({\n store,\n restrictedHooks,\n permittedHooks,\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) => {\n if (error && !error.message?.match('Premature close')) {\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 const helpers = getHelpers({\n snapId,\n store,\n controllerMessenger,\n runSaga,\n executionService: service,\n options,\n });\n\n return {\n snapId,\n store,\n executionService: service,\n controllerMessenger,\n runSaga,\n ...helpers,\n };\n}\n\n/**\n * Get the hooks for the simulation.\n *\n * @param options - The simulation options.\n * @returns The hooks for the simulation.\n */\nexport function getRestrictedHooks(\n options: SimulationOptions,\n): RestrictedMiddlewareHooks {\n return {\n getMnemonic: getGetMnemonicImplementation(options.secretRecoveryPhrase),\n getMnemonicSeed: getGetMnemonicSeedImplementation(\n options.secretRecoveryPhrase,\n ),\n getIsLocked: () => false,\n getClientCryptography: () => ({}),\n };\n}\n\n/**\n * Get the permitted hooks for the simulation.\n *\n * @param snapId - The ID of the Snap.\n * @param snapFiles - The fetched Snap files.\n * @param controllerMessenger - The controller messenger.\n * @param runSaga - The run saga function.\n * @returns The permitted hooks for the simulation.\n */\nexport function getPermittedHooks(\n snapId: SnapId,\n snapFiles: FetchedSnapFiles,\n controllerMessenger: RootControllerMessenger,\n runSaga: RunSagaFunction,\n): PermittedMiddlewareHooks {\n return {\n hasPermission: () => true,\n getUnlockPromise: asyncResolve(),\n getIsLocked: () => false,\n getIsActive: () => true,\n\n getSnapFile: async (path: string, encoding: AuxiliaryFileEncoding) =>\n await getSnapFile(snapFiles.auxiliaryFiles, path, encoding),\n\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 getInterfaceContext: (...args) =>\n controllerMessenger.call(\n 'SnapInterfaceController:getInterface',\n snapId,\n ...args,\n ).context,\n resolveInterface: async (...args) =>\n controllerMessenger.call(\n 'SnapInterfaceController:resolveInterface',\n snapId,\n ...args,\n ),\n\n getEntropySources: getGetEntropySourcesImplementation(),\n getSnapState: getPermittedGetSnapStateMethodImplementation(runSaga),\n updateSnapState: getPermittedUpdateSnapStateMethodImplementation(runSaga),\n clearSnapState: getPermittedClearSnapStateMethodImplementation(runSaga),\n\n getSnap: getGetSnapImplementation(true),\n trackError: getTrackErrorImplementation(runSaga),\n trackEvent: getTrackEventImplementation(runSaga),\n startTrace: getStartTraceImplementation(runSaga),\n endTrace: getEndTraceImplementation(runSaga),\n };\n}\n\n/**\n * Register mocked action handlers.\n *\n * @param controllerMessenger - The controller messenger.\n * @param runSaga - The run saga function.\n * @param options - The simulation options.\n * @param snapId - The ID of the Snap.\n */\nexport function registerActions(\n controllerMessenger: RootControllerMessenger,\n runSaga: RunSagaFunction,\n options: SimulationOptions,\n snapId: SnapId,\n) {\n controllerMessenger.registerActionHandler(\n 'PhishingController:testOrigin',\n () => ({ result: false, type: PhishingDetectorResultType.All }),\n );\n\n controllerMessenger.registerActionHandler(\n 'AccountsController:getAccountByAddress',\n // @ts-expect-error - This is a partial account with only the necessary\n // data used by the interface controller.\n (address) => {\n const matchingAccount = options.accounts.find(\n (account) => address === account.address,\n );\n\n if (!matchingAccount) {\n return undefined;\n }\n\n return addSnapMetadataToAccount(matchingAccount, snapId);\n },\n );\n\n controllerMessenger.registerActionHandler(\n 'AccountsController:getSelectedMultichainAccount',\n // @ts-expect-error - This is a partial account with only the necessary\n // data used by the interface controller.\n () => {\n const selectedAccount = options.accounts.find(\n (account) => account.selected,\n );\n\n if (!selectedAccount) {\n return undefined;\n }\n\n return addSnapMetadataToAccount(selectedAccount, snapId);\n },\n );\n\n controllerMessenger.registerActionHandler(\n 'AccountsController:listMultichainAccounts',\n\n () =>\n // @ts-expect-error - These are partial accounts with only the necessary\n // data used by the interface controller.\n options.accounts.map((account) =>\n addSnapMetadataToAccount(account, snapId),\n ),\n );\n\n controllerMessenger.registerActionHandler(\n 'MultichainAssetsController:getState',\n () => ({\n // @ts-expect-error - These are partial assets with only the\n // necessary data used by the interface controller.\n assetsMetadata: options.assets,\n accountsAssets: options.accounts.reduce<Record<string, CaipAssetType[]>>(\n (acc, account) => {\n acc[account.id] = account.assets ?? [];\n return acc;\n },\n {},\n ),\n }),\n );\n\n controllerMessenger.registerActionHandler(\n 'ApprovalController:hasRequest',\n (opts) => {\n /**\n * Get the current interface from the store.\n *\n * @yields Selects the current interface from the store.\n * @returns The current interface.\n */\n function* getCurrentInterfaceSaga(): SagaIterator {\n const currentInterface: Interface = yield select(getCurrentInterface);\n return currentInterface;\n }\n\n const currentInterface: Interface | undefined = runSaga(\n getCurrentInterfaceSaga,\n ).result();\n return (\n currentInterface?.type === DIALOG_APPROVAL_TYPES.default &&\n currentInterface?.id === opts?.id\n );\n },\n );\n\n controllerMessenger.registerActionHandler(\n 'ApprovalController:acceptRequest',\n async (_id: string, value: unknown) => {\n await runSaga(resolveWithSaga, value).toPromise();\n\n return { value };\n },\n );\n}\n"]}
@@ -2,8 +2,8 @@ import type { ActionConstraint, EventConstraint } from "@metamask/base-controlle
2
2
  import { Messenger } from "@metamask/base-controller";
3
3
  import type { CryptographicFunctions } from "@metamask/key-tree";
4
4
  import type { AbstractExecutionService } from "@metamask/snaps-controllers";
5
- import { type AuxiliaryFileEncoding, type Component, type InterfaceState, type InterfaceContext, type SnapId, type EntropySource } from "@metamask/snaps-sdk";
6
- import type { FetchedSnapFiles } from "@metamask/snaps-utils";
5
+ import type { TrackEventParams, AuxiliaryFileEncoding, Component, InterfaceState, InterfaceContext, SnapId, EntropySource, TraceRequest, EndTraceRequest, TraceContext } from "@metamask/snaps-sdk";
6
+ import type { FetchedSnapFiles, Snap } from "@metamask/snaps-utils";
7
7
  import type { Json } from "@metamask/utils";
8
8
  import type { RootControllerMessenger } from "./controllers.cjs";
9
9
  import type { SnapHelpers } from "./helpers.cjs";
@@ -177,6 +177,38 @@ export type PermittedMiddlewareHooks = {
177
177
  * @param value - The value to resolve the interface with.
178
178
  */
179
179
  resolveInterface: (id: string, value: Json) => Promise<void>;
180
+ /**
181
+ * A hook that gets the Snap's metadata.
182
+ *
183
+ * @param snapId - The ID of the Snap to get.
184
+ * @returns The Snap's metadata.
185
+ */
186
+ getSnap(snapId: string): Snap;
187
+ /**
188
+ * A hook that tracks an error.
189
+ *
190
+ * @param error - The error object containing error details and properties.
191
+ */
192
+ trackError(error: Error): void;
193
+ /**
194
+ * A hook that tracks an event.
195
+ *
196
+ * @param event - The event object containing event details and properties.
197
+ */
198
+ trackEvent(event: TrackEventParams['event']): void;
199
+ /**
200
+ * A hook that starts a performance trace.
201
+ *
202
+ * @param request - The trace request object containing trace details.
203
+ */
204
+ startTrace(request: TraceRequest): TraceContext;
205
+ /**
206
+ * A hook that ends a performance trace.
207
+ *
208
+ * @param request - The trace request object containing trace details.
209
+ * @returns The trace data.
210
+ */
211
+ endTrace(request: EndTraceRequest): void;
180
212
  };
181
213
  /**
182
214
  * Install a Snap in a simulated environment. This will fetch the Snap files,
@@ -1 +1 @@
1
- {"version":3,"file":"simulation.d.cts","sourceRoot":"","sources":["../src/simulation.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,gBAAgB,EAChB,eAAe,EAChB,kCAAkC;AACnC,OAAO,EAAE,SAAS,EAAE,kCAAkC;AAEtD,OAAO,KAAK,EAAE,sBAAsB,EAAE,2BAA2B;AAEjE,OAAO,KAAK,EAAE,wBAAwB,EAAE,oCAAoC;AAQ5E,OAAO,EACL,KAAK,qBAAqB,EAC1B,KAAK,SAAS,EACd,KAAK,cAAc,EACnB,KAAK,gBAAgB,EACrB,KAAK,MAAM,EACX,KAAK,aAAa,EACnB,4BAA4B;AAC7B,OAAO,KAAK,EAAE,gBAAgB,EAAE,8BAA8B;AAE9D,OAAO,KAAK,EAAiB,IAAI,EAAE,wBAAwB;AAM3D,OAAO,KAAK,EAAE,uBAAuB,EAAE,0BAAsB;AAG7D,OAAO,KAAK,EAAE,WAAW,EAAE,sBAAkB;AAa7C,OAAO,KAAK,EAAE,iBAAiB,EAAE,qBAAqB,EAAE,sBAAkB;AAE1E,OAAO,KAAK,EAAa,eAAe,EAAE,KAAK,EAAE,0BAAgB;AAIjE;;;;;;GAMG;AACH,MAAM,MAAM,uBAAuB,CACjC,OAAO,SAAS,KAAK,GAAG,IAAI,EAAE,GAAG,EAAE,KAAK,GAAG,IACzC,IAAI,CACN,qBAAqB,CAAC,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AAI,CAAC;CAC1C,CAAC;AAEF;;;;;;;;;;;;;;GAcG;AACH,wBAAsB,WAAW,CAC/B,OAAO,SAAS,KACd,GAAG,IAAI,EAAE,GAAG,EAAE,KACX,YAAY,CAAC,OAAO,wBAAwB,CAAC,EAElD,MAAM,EAAE,MAAM,EACd,EACE,gBAAgB,EAChB,uBAAuB,EACvB,OAAO,EAAE,UAAe,GACzB,GAAE,OAAO,CAAC,kBAAkB,CAAC,OAAO,CAAC,CAAM,GAC3C,OAAO,CAAC,aAAa,GAAG,WAAW,CAAC,CAiGtC;AAED;;;;;GAKG;AACH,wBAAgB,kBAAkB,CAChC,OAAO,EAAE,iBAAiB,GACzB,yBAAyB,CAS3B;AAED;;;;;;;;GAQG;AACH,wBAAgB,iBAAiB,CAC/B,MAAM,EAAE,MAAM,EACd,SAAS,EAAE,gBAAgB,EAC3B,mBAAmB,EAAE,uBAAuB,EAC5C,OAAO,EAAE,eAAe,GACvB,wBAAwB,CAoD1B;AAED;;;;;;;GAOG;AACH,wBAAgB,eAAe,CAC7B,mBAAmB,EAAE,uBAAuB,EAC5C,OAAO,EAAE,eAAe,EACxB,OAAO,EAAE,iBAAiB,EAC1B,MAAM,EAAE,MAAM,QAoGf"}
@@ -2,8 +2,8 @@ import type { ActionConstraint, EventConstraint } from "@metamask/base-controlle
2
2
  import { Messenger } from "@metamask/base-controller";
3
3
  import type { CryptographicFunctions } from "@metamask/key-tree";
4
4
  import type { AbstractExecutionService } from "@metamask/snaps-controllers";
5
- import { type AuxiliaryFileEncoding, type Component, type InterfaceState, type InterfaceContext, type SnapId, type EntropySource } from "@metamask/snaps-sdk";
6
- import type { FetchedSnapFiles } from "@metamask/snaps-utils";
5
+ import type { TrackEventParams, AuxiliaryFileEncoding, Component, InterfaceState, InterfaceContext, SnapId, EntropySource, TraceRequest, EndTraceRequest, TraceContext } from "@metamask/snaps-sdk";
6
+ import type { FetchedSnapFiles, Snap } from "@metamask/snaps-utils";
7
7
  import type { Json } from "@metamask/utils";
8
8
  import type { RootControllerMessenger } from "./controllers.mjs";
9
9
  import type { SnapHelpers } from "./helpers.mjs";
@@ -177,6 +177,38 @@ export type PermittedMiddlewareHooks = {
177
177
  * @param value - The value to resolve the interface with.
178
178
  */
179
179
  resolveInterface: (id: string, value: Json) => Promise<void>;
180
+ /**
181
+ * A hook that gets the Snap's metadata.
182
+ *
183
+ * @param snapId - The ID of the Snap to get.
184
+ * @returns The Snap's metadata.
185
+ */
186
+ getSnap(snapId: string): Snap;
187
+ /**
188
+ * A hook that tracks an error.
189
+ *
190
+ * @param error - The error object containing error details and properties.
191
+ */
192
+ trackError(error: Error): void;
193
+ /**
194
+ * A hook that tracks an event.
195
+ *
196
+ * @param event - The event object containing event details and properties.
197
+ */
198
+ trackEvent(event: TrackEventParams['event']): void;
199
+ /**
200
+ * A hook that starts a performance trace.
201
+ *
202
+ * @param request - The trace request object containing trace details.
203
+ */
204
+ startTrace(request: TraceRequest): TraceContext;
205
+ /**
206
+ * A hook that ends a performance trace.
207
+ *
208
+ * @param request - The trace request object containing trace details.
209
+ * @returns The trace data.
210
+ */
211
+ endTrace(request: EndTraceRequest): void;
180
212
  };
181
213
  /**
182
214
  * Install a Snap in a simulated environment. This will fetch the Snap files,
@@ -1 +1 @@
1
- {"version":3,"file":"simulation.d.mts","sourceRoot":"","sources":["../src/simulation.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,gBAAgB,EAChB,eAAe,EAChB,kCAAkC;AACnC,OAAO,EAAE,SAAS,EAAE,kCAAkC;AAEtD,OAAO,KAAK,EAAE,sBAAsB,EAAE,2BAA2B;AAEjE,OAAO,KAAK,EAAE,wBAAwB,EAAE,oCAAoC;AAQ5E,OAAO,EACL,KAAK,qBAAqB,EAC1B,KAAK,SAAS,EACd,KAAK,cAAc,EACnB,KAAK,gBAAgB,EACrB,KAAK,MAAM,EACX,KAAK,aAAa,EACnB,4BAA4B;AAC7B,OAAO,KAAK,EAAE,gBAAgB,EAAE,8BAA8B;AAE9D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