@metamask/snaps-simulation 4.1.3 → 4.1.4

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 (66) hide show
  1. package/CHANGELOG.md +13 -2
  2. package/dist/methods/hooks/index.cjs +0 -2
  3. package/dist/methods/hooks/index.cjs.map +1 -1
  4. package/dist/methods/hooks/index.d.cts +0 -2
  5. package/dist/methods/hooks/index.d.cts.map +1 -1
  6. package/dist/methods/hooks/index.d.mts +0 -2
  7. package/dist/methods/hooks/index.d.mts.map +1 -1
  8. package/dist/methods/hooks/index.mjs +0 -2
  9. package/dist/methods/hooks/index.mjs.map +1 -1
  10. package/dist/methods/hooks/state.cjs +1 -1
  11. package/dist/methods/hooks/state.cjs.map +1 -1
  12. package/dist/methods/hooks/state.d.cts +1 -1
  13. package/dist/methods/hooks/state.d.cts.map +1 -1
  14. package/dist/methods/hooks/state.d.mts +1 -1
  15. package/dist/methods/hooks/state.d.mts.map +1 -1
  16. package/dist/methods/hooks/state.mjs +1 -1
  17. package/dist/methods/hooks/state.mjs.map +1 -1
  18. package/dist/methods/specifications.cjs +5 -14
  19. package/dist/methods/specifications.cjs.map +1 -1
  20. package/dist/methods/specifications.d.cts +7 -17
  21. package/dist/methods/specifications.d.cts.map +1 -1
  22. package/dist/methods/specifications.d.mts +7 -17
  23. package/dist/methods/specifications.d.mts.map +1 -1
  24. package/dist/methods/specifications.mjs +6 -15
  25. package/dist/methods/specifications.mjs.map +1 -1
  26. package/dist/middleware/engine.cjs +8 -4
  27. package/dist/middleware/engine.cjs.map +1 -1
  28. package/dist/middleware/engine.d.cts +7 -6
  29. package/dist/middleware/engine.d.cts.map +1 -1
  30. package/dist/middleware/engine.d.mts +7 -6
  31. package/dist/middleware/engine.d.mts.map +1 -1
  32. package/dist/middleware/engine.mjs +9 -5
  33. package/dist/middleware/engine.mjs.map +1 -1
  34. package/dist/simulation.cjs +82 -27
  35. package/dist/simulation.cjs.map +1 -1
  36. package/dist/simulation.d.cts +18 -114
  37. package/dist/simulation.d.cts.map +1 -1
  38. package/dist/simulation.d.mts +18 -114
  39. package/dist/simulation.d.mts.map +1 -1
  40. package/dist/simulation.mjs +83 -28
  41. package/dist/simulation.mjs.map +1 -1
  42. package/package.json +12 -12
  43. package/dist/methods/hooks/get-entropy-sources.cjs +0 -30
  44. package/dist/methods/hooks/get-entropy-sources.cjs.map +0 -1
  45. package/dist/methods/hooks/get-entropy-sources.d.cts +0 -14
  46. package/dist/methods/hooks/get-entropy-sources.d.cts.map +0 -1
  47. package/dist/methods/hooks/get-entropy-sources.d.mts +0 -14
  48. package/dist/methods/hooks/get-entropy-sources.d.mts.map +0 -1
  49. package/dist/methods/hooks/get-entropy-sources.mjs +0 -26
  50. package/dist/methods/hooks/get-entropy-sources.mjs.map +0 -1
  51. package/dist/methods/hooks/get-mnemonic-seed.cjs +0 -29
  52. package/dist/methods/hooks/get-mnemonic-seed.cjs.map +0 -1
  53. package/dist/methods/hooks/get-mnemonic-seed.d.cts +0 -9
  54. package/dist/methods/hooks/get-mnemonic-seed.d.cts.map +0 -1
  55. package/dist/methods/hooks/get-mnemonic-seed.d.mts +0 -9
  56. package/dist/methods/hooks/get-mnemonic-seed.d.mts.map +0 -1
  57. package/dist/methods/hooks/get-mnemonic-seed.mjs +0 -25
  58. package/dist/methods/hooks/get-mnemonic-seed.mjs.map +0 -1
  59. package/dist/methods/hooks/interface.cjs +0 -34
  60. package/dist/methods/hooks/interface.cjs.map +0 -1
  61. package/dist/methods/hooks/interface.d.cts +0 -24
  62. package/dist/methods/hooks/interface.d.cts.map +0 -1
  63. package/dist/methods/hooks/interface.d.mts +0 -24
  64. package/dist/methods/hooks/interface.d.mts.map +0 -1
  65. package/dist/methods/hooks/interface.mjs +0 -28
  66. package/dist/methods/hooks/interface.mjs.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"engine.d.cts","sourceRoot":"","sources":["../../src/middleware/engine.ts"],"names":[],"mappings":"AAAA,OAAO,K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AC;IAC3C,cAAc,EAAE,wBAAwB,CAAC;IACzC,eAAe,EAAE,yBAAyB,CAAC;IAC3C,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,YAAY,EAAE,OAAO,CAAC;CACvB,CAAC;AAEF;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,mBAAmB,CAAC,EAClC,MAAM,EACN,SAAS,EACT,KAAK,EACL,eAAe,EACf,cAAc,EACd,eAAe,EACf,YAAY,GACb,EAAE,0BAA0B,iBAoB5B"}
@@ -1,15 +1,15 @@
1
- import type { JsonRpcMiddleware } from "@metamask/json-rpc-engine";
2
1
  import { JsonRpcEngine } from "@metamask/json-rpc-engine";
3
- import type { RestrictedMethodParameters } from "@metamask/permission-controller";
4
- import type { Json } from "@metamask/utils";
2
+ import type { SnapId } from "@metamask/snaps-sdk";
3
+ import type { RootControllerMessenger } from "../controllers.mjs";
5
4
  import type { MultichainMiddlewareHooks, PermittedMiddlewareHooks, RestrictedMiddlewareHooks } from "../simulation.mjs";
6
5
  import type { Store } from "../store/index.mjs";
7
6
  export type CreateJsonRpcEngineOptions = {
7
+ snapId: SnapId;
8
+ messenger: RootControllerMessenger;
8
9
  store: Store;
9
10
  restrictedHooks: RestrictedMiddlewareHooks;
10
11
  permittedHooks: PermittedMiddlewareHooks;
11
12
  multichainHooks: MultichainMiddlewareHooks;
12
- permissionMiddleware: JsonRpcMiddleware<RestrictedMethodParameters, Json>;
13
13
  endpoint?: string;
14
14
  isMultichain: boolean;
15
15
  };
@@ -20,13 +20,14 @@ export type CreateJsonRpcEngineOptions = {
20
20
  * well as Snap-specific requests.
21
21
  *
22
22
  * @param options - The options to use when creating the engine.
23
+ * @param options.snapId - The Snap ID.
24
+ * @param options.messenger - The messenger.
23
25
  * @param options.store - The Redux store to use.
24
26
  * @param options.restrictedHooks - Any hooks used by the middleware handlers.
25
27
  * @param options.permittedHooks - Any hooks used by the middleware handlers.
26
- * @param options.permissionMiddleware - The permission middleware to use.
27
28
  * @param options.multichainHooks - Hooks used by the multichain middleware.
28
29
  * @param options.isMultichain - Whether the engine is used for multichain.
29
30
  * @returns A JSON-RPC engine.
30
31
  */
31
- export declare function createJsonRpcEngine({ store, restrictedHooks, permittedHooks, permissionMiddleware, multichainHooks, isMultichain, }: CreateJsonRpcEngineOptions): JsonRpcEngine;
32
+ export declare function createJsonRpcEngine({ snapId, messenger, store, restrictedHooks, permittedHooks, multichainHooks, isMultichain, }: CreateJsonRpcEngineOptions): JsonRpcEngine;
32
33
  //# sourceMappingURL=engine.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"engine.d.mts","sourceRoot":"","sources":["../../src/middleware/engine.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,iBAAiB,EAAE,kCAAkC;AACnE,OAAO,EAAE,aAAa,EAAE,kCAAkC;AAC1D,OAAO,KAAK,EAAE,0BAA0B,EAAE,wCAAwC;AAElF,OAAO,KAAK,EAAE,IAAI,EAAE,wBAAwB;AAM5C,OAAO,KAAK,EACV,yBAAyB,EACzB,wBAAwB,EACxB,yBAAyB,EAC1B,0BAAsB;AACvB,OAAO,KAAK,EAAE,KAAK,EAAE,2BAAiB;AAEtC,MAAM,MAAM,0BAA0B,GAAG;IACvC,KAAK,EAAE,KAAK,CAAC;IACb,eAAe,EAAE,yBAAyB,CAAC;IAC3C,cAAc,EAAE,wBAAwB,CAAC;IACzC,eAAe,EAAE,yBAAyB,CAAC;IAC3C,oBAAoB,EAAE,iBAAiB,CAAC,0BAA0B,EAAE,IAAI,CAAC,CAAC;IAC1E,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,YAAY,EAAE,OAAO,CAAC;CACvB,CAAC;AAEF;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,mBAAmB,CAAC,EAClC,KAAK,EACL,eAAe,EACf,cAAc,EACd,oBAAoB,EACpB,eAAe,EACf,YAAY,GACb,EAAE,0BAA0B,iBAgB5B"}
1
+ {"version":3,"file":"engine.d.mts","sourceRoot":"","sources":["../../src/middleware/engine.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,aAAa,EAEd,kCAAkC;AAGnC,OAAO,KAAK,EAAE,MAAM,EAAE,4BAA4B;AAMlD,OAAO,KAAK,EAAE,uBAAuB,EAAE,2BAAuB;AAC9D,OAAO,KAAK,EACV,yBAAyB,EACzB,wBAAwB,EACxB,yBAAyB,EAC1B,0BAAsB;AACvB,OAAO,KAAK,EAAE,KAAK,EAAE,2BAAiB;AAEtC,MAAM,MAAM,0BAA0B,GAAG;IACvC,MAAM,EAAE,MAAM,CAAC;IACf,SAAS,EAAE,uBAAuB,CAAC;IACnC,KAAK,EAAE,KAAK,CAAC;IACb,eAAe,EAAE,yBAAyB,CAAC;IAC3C,cAAc,EAAE,wBAAwB,CAAC;IACzC,eAAe,EAAE,yBAAyB,CAAC;IAC3C,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,YAAY,EAAE,OAAO,CAAC;CACvB,CAAC;AAEF;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,mBAAmB,CAAC,EAClC,MAAM,EACN,SAAS,EACT,KAAK,EACL,eAAe,EACf,cAAc,EACd,eAAe,EACf,YAAY,GACb,EAAE,0BAA0B,iBAoB5B"}
@@ -1,4 +1,5 @@
1
- import { JsonRpcEngine } from "@metamask/json-rpc-engine";
1
+ import { JsonRpcEngine, createOriginMiddleware } from "@metamask/json-rpc-engine";
2
+ import { createPermissionMiddleware } from "@metamask/permission-controller";
2
3
  import { createSnapsMethodMiddleware } from "@metamask/snaps-rpc-methods";
3
4
  import { createInternalMethodsMiddleware } from "./internal-methods/index.mjs";
4
5
  import { createMockMiddleware } from "./mock.mjs";
@@ -11,23 +12,26 @@ import { createProviderMiddleware } from "./provider.mjs";
11
12
  * well as Snap-specific requests.
12
13
  *
13
14
  * @param options - The options to use when creating the engine.
15
+ * @param options.snapId - The Snap ID.
16
+ * @param options.messenger - The messenger.
14
17
  * @param options.store - The Redux store to use.
15
18
  * @param options.restrictedHooks - Any hooks used by the middleware handlers.
16
19
  * @param options.permittedHooks - Any hooks used by the middleware handlers.
17
- * @param options.permissionMiddleware - The permission middleware to use.
18
20
  * @param options.multichainHooks - Hooks used by the multichain middleware.
19
21
  * @param options.isMultichain - Whether the engine is used for multichain.
20
22
  * @returns A JSON-RPC engine.
21
23
  */
22
- export function createJsonRpcEngine({ store, restrictedHooks, permittedHooks, permissionMiddleware, multichainHooks, isMultichain, }) {
24
+ export function createJsonRpcEngine({ snapId, messenger, store, restrictedHooks, permittedHooks, multichainHooks, isMultichain, }) {
23
25
  const engine = new JsonRpcEngine();
26
+ engine.push(createOriginMiddleware(snapId));
24
27
  engine.push(createMultichainMiddleware(isMultichain, multichainHooks));
25
28
  engine.push(createMockMiddleware(store));
26
29
  // The hooks here do not match the hooks used by the clients, so this
27
30
  // middleware should not be used outside of the simulation environment.
28
31
  engine.push(createInternalMethodsMiddleware(restrictedHooks));
29
- engine.push(createSnapsMethodMiddleware(true, permittedHooks));
30
- engine.push(permissionMiddleware);
32
+ // @ts-expect-error Hooks type mismatch.
33
+ engine.push(createSnapsMethodMiddleware(true, permittedHooks, messenger));
34
+ engine.push(createPermissionMiddleware({ messenger, origin: snapId }));
31
35
  engine.push(createProviderMiddleware(store));
32
36
  return engine;
33
37
  }
@@ -1 +1 @@
1
- {"version":3,"file":"engine.mjs","sourceRoot":"","sources":["../../src/middleware/engine.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,aAAa,EAAE,kCAAkC;AAE1D,OAAO,EAAE,2BAA2B,EAAE,oCAAoC;AAG1E,OAAO,EAAE,+BAA+B,EAAE,qCAA2B;AACrE,OAAO,EAAE,oBAAoB,EAAE,mBAAe;AAC9C,OAAO,EAAE,0BAA0B,EAAE,+BAAqB;AAC1D,OAAO,EAAE,wBAAwB,EAAE,uBAAmB;AAkBtD;;;;;;;;;;;;;;GAcG;AACH,MAAM,UAAU,mBAAmB,CAAC,EAClC,KAAK,EACL,eAAe,EACf,cAAc,EACd,oBAAoB,EACpB,eAAe,EACf,YAAY,GACe;IAC3B,MAAM,MAAM,GAAG,IAAI,aAAa,EAAE,CAAC;IAEnC,MAAM,CAAC,IAAI,CAAC,0BAA0B,CAAC,YAAY,EAAE,eAAe,CAAC,CAAC,CAAC;IAEvE,MAAM,CAAC,IAAI,CAAC,oBAAoB,CAAC,KAAK,CAAC,CAAC,CAAC;IAEzC,qEAAqE;IACrE,uEAAuE;IACvE,MAAM,CAAC,IAAI,CAAC,+BAA+B,CAAC,eAAe,CAAC,CAAC,CAAC;IAC9D,MAAM,CAAC,IAAI,CAAC,2BAA2B,CAAC,IAAI,EAAE,cAAc,CAAC,CAAC,CAAC;IAE/D,MAAM,CAAC,IAAI,CAAC,oBAAoB,CAAC,CAAC;IAClC,MAAM,CAAC,IAAI,CAAC,wBAAwB,CAAC,KAAK,CAAC,CAAC,CAAC;IAE7C,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import type { JsonRpcMiddleware } from '@metamask/json-rpc-engine';\nimport { JsonRpcEngine } from '@metamask/json-rpc-engine';\nimport type { RestrictedMethodParameters } from '@metamask/permission-controller';\nimport { createSnapsMethodMiddleware } from '@metamask/snaps-rpc-methods';\nimport type { Json } from '@metamask/utils';\n\nimport { createInternalMethodsMiddleware } from './internal-methods';\nimport { createMockMiddleware } from './mock';\nimport { createMultichainMiddleware } from './multichain';\nimport { createProviderMiddleware } from './provider';\nimport type {\n MultichainMiddlewareHooks,\n PermittedMiddlewareHooks,\n RestrictedMiddlewareHooks,\n} from '../simulation';\nimport type { Store } from '../store';\n\nexport type CreateJsonRpcEngineOptions = {\n store: Store;\n restrictedHooks: RestrictedMiddlewareHooks;\n permittedHooks: PermittedMiddlewareHooks;\n multichainHooks: MultichainMiddlewareHooks;\n permissionMiddleware: JsonRpcMiddleware<RestrictedMethodParameters, Json>;\n endpoint?: string;\n isMultichain: boolean;\n};\n\n/**\n * Create a JSON-RPC engine for use in a simulated environment. This engine\n * should be used to handle all JSON-RPC requests. It is set up to handle\n * requests that would normally be handled internally by the MetaMask client, as\n * well as Snap-specific requests.\n *\n * @param options - The options to use when creating the engine.\n * @param options.store - The Redux store to use.\n * @param options.restrictedHooks - Any hooks used by the middleware handlers.\n * @param options.permittedHooks - Any hooks used by the middleware handlers.\n * @param options.permissionMiddleware - The permission middleware to use.\n * @param options.multichainHooks - Hooks used by the multichain middleware.\n * @param options.isMultichain - Whether the engine is used for multichain.\n * @returns A JSON-RPC engine.\n */\nexport function createJsonRpcEngine({\n store,\n restrictedHooks,\n permittedHooks,\n permissionMiddleware,\n multichainHooks,\n isMultichain,\n}: CreateJsonRpcEngineOptions) {\n const engine = new JsonRpcEngine();\n\n engine.push(createMultichainMiddleware(isMultichain, multichainHooks));\n\n engine.push(createMockMiddleware(store));\n\n // The hooks here do not match the hooks used by the clients, so this\n // middleware should not be used outside of the simulation environment.\n engine.push(createInternalMethodsMiddleware(restrictedHooks));\n engine.push(createSnapsMethodMiddleware(true, permittedHooks));\n\n engine.push(permissionMiddleware);\n engine.push(createProviderMiddleware(store));\n\n return engine;\n}\n"]}
1
+ {"version":3,"file":"engine.mjs","sourceRoot":"","sources":["../../src/middleware/engine.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,aAAa,EACb,sBAAsB,EACvB,kCAAkC;AACnC,OAAO,EAAE,0BAA0B,EAAE,wCAAwC;AAC7E,OAAO,EAAE,2BAA2B,EAAE,oCAAoC;AAG1E,OAAO,EAAE,+BAA+B,EAAE,qCAA2B;AACrE,OAAO,EAAE,oBAAoB,EAAE,mBAAe;AAC9C,OAAO,EAAE,0BAA0B,EAAE,+BAAqB;AAC1D,OAAO,EAAE,wBAAwB,EAAE,uBAAmB;AAoBtD;;;;;;;;;;;;;;;GAeG;AACH,MAAM,UAAU,mBAAmB,CAAC,EAClC,MAAM,EACN,SAAS,EACT,KAAK,EACL,eAAe,EACf,cAAc,EACd,eAAe,EACf,YAAY,GACe;IAC3B,MAAM,MAAM,GAAG,IAAI,aAAa,EAAE,CAAC;IAEnC,MAAM,CAAC,IAAI,CAAC,sBAAsB,CAAC,MAAM,CAAC,CAAC,CAAC;IAE5C,MAAM,CAAC,IAAI,CAAC,0BAA0B,CAAC,YAAY,EAAE,eAAe,CAAC,CAAC,CAAC;IAEvE,MAAM,CAAC,IAAI,CAAC,oBAAoB,CAAC,KAAK,CAAC,CAAC,CAAC;IAEzC,qEAAqE;IACrE,uEAAuE;IACvE,MAAM,CAAC,IAAI,CAAC,+BAA+B,CAAC,eAAe,CAAC,CAAC,CAAC;IAE9D,wCAAwC;IACxC,MAAM,CAAC,IAAI,CAAC,2BAA2B,CAAC,IAAI,EAAE,cAAc,EAAE,SAAS,CAAC,CAAC,CAAC;IAE1E,MAAM,CAAC,IAAI,CAAC,0BAA0B,CAAC,EAAE,SAAS,EAAE,MAAM,EAAE,MAAM,EAAE,CAAC,CAAC,CAAC;IACvE,MAAM,CAAC,IAAI,CAAC,wBAAwB,CAAC,KAAK,CAAC,CAAC,CAAC;IAE7C,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import {\n JsonRpcEngine,\n createOriginMiddleware,\n} from '@metamask/json-rpc-engine';\nimport { createPermissionMiddleware } from '@metamask/permission-controller';\nimport { createSnapsMethodMiddleware } from '@metamask/snaps-rpc-methods';\nimport type { SnapId } from '@metamask/snaps-sdk';\n\nimport { createInternalMethodsMiddleware } from './internal-methods';\nimport { createMockMiddleware } from './mock';\nimport { createMultichainMiddleware } from './multichain';\nimport { createProviderMiddleware } from './provider';\nimport type { RootControllerMessenger } from '../controllers';\nimport type {\n MultichainMiddlewareHooks,\n PermittedMiddlewareHooks,\n RestrictedMiddlewareHooks,\n} from '../simulation';\nimport type { Store } from '../store';\n\nexport type CreateJsonRpcEngineOptions = {\n snapId: SnapId;\n messenger: RootControllerMessenger;\n store: Store;\n restrictedHooks: RestrictedMiddlewareHooks;\n permittedHooks: PermittedMiddlewareHooks;\n multichainHooks: MultichainMiddlewareHooks;\n endpoint?: string;\n isMultichain: boolean;\n};\n\n/**\n * Create a JSON-RPC engine for use in a simulated environment. This engine\n * should be used to handle all JSON-RPC requests. It is set up to handle\n * requests that would normally be handled internally by the MetaMask client, as\n * well as Snap-specific requests.\n *\n * @param options - The options to use when creating the engine.\n * @param options.snapId - The Snap ID.\n * @param options.messenger - The messenger.\n * @param options.store - The Redux store to use.\n * @param options.restrictedHooks - Any hooks used by the middleware handlers.\n * @param options.permittedHooks - Any hooks used by the middleware handlers.\n * @param options.multichainHooks - Hooks used by the multichain middleware.\n * @param options.isMultichain - Whether the engine is used for multichain.\n * @returns A JSON-RPC engine.\n */\nexport function createJsonRpcEngine({\n snapId,\n messenger,\n store,\n restrictedHooks,\n permittedHooks,\n multichainHooks,\n isMultichain,\n}: CreateJsonRpcEngineOptions) {\n const engine = new JsonRpcEngine();\n\n engine.push(createOriginMiddleware(snapId));\n\n engine.push(createMultichainMiddleware(isMultichain, multichainHooks));\n\n engine.push(createMockMiddleware(store));\n\n // The hooks here do not match the hooks used by the clients, so this\n // middleware should not be used outside of the simulation environment.\n engine.push(createInternalMethodsMiddleware(restrictedHooks));\n\n // @ts-expect-error Hooks type mismatch.\n engine.push(createSnapsMethodMiddleware(true, permittedHooks, messenger));\n\n engine.push(createPermissionMiddleware({ messenger, origin: snapId }));\n engine.push(createProviderMiddleware(store));\n\n return engine;\n}\n"]}
@@ -2,11 +2,13 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.registerActions = exports.getMultichainHooks = exports.getPermittedHooks = exports.getRestrictedHooks = exports.installSnap = void 0;
4
4
  const json_rpc_middleware_stream_1 = require("@metamask/json-rpc-middleware-stream");
5
+ const key_tree_1 = require("@metamask/key-tree");
5
6
  const messenger_1 = require("@metamask/messenger");
6
7
  const permission_controller_1 = require("@metamask/permission-controller");
7
8
  const node_1 = require("@metamask/snaps-controllers/node");
8
9
  const snaps_rpc_methods_1 = require("@metamask/snaps-rpc-methods");
9
10
  const snaps_utils_1 = require("@metamask/snaps-utils");
11
+ const utils_1 = require("@metamask/utils");
10
12
  const readable_stream_1 = require("readable-stream");
11
13
  const effects_1 = require("redux-saga/effects");
12
14
  const controllers_1 = require("./controllers.cjs");
@@ -15,7 +17,6 @@ const helpers_1 = require("./helpers.cjs");
15
17
  const interface_1 = require("./interface.cjs");
16
18
  const methods_1 = require("./methods/index.cjs");
17
19
  const hooks_1 = require("./methods/hooks/index.cjs");
18
- const get_mnemonic_seed_1 = require("./methods/hooks/get-mnemonic-seed.cjs");
19
20
  const middleware_1 = require("./middleware/index.cjs");
20
21
  const options_1 = require("./options.cjs");
21
22
  const store_1 = require("./store/index.cjs");
@@ -47,10 +48,10 @@ async function installSnap(snapId, { executionService, executionServiceOptions,
47
48
  const controllerMessenger = new messenger_1.Messenger({
48
49
  namespace: messenger_1.MOCK_ANY_NAMESPACE,
49
50
  });
50
- registerActions(controllerMessenger, runSaga, options, snapId);
51
+ registerActions(controllerMessenger, runSaga, options, snapId, snapFiles.auxiliaryFiles);
51
52
  // Set up controllers and JSON-RPC stack.
52
53
  const restrictedHooks = getRestrictedHooks(options, store, runSaga);
53
- const permittedHooks = getPermittedHooks(snapId, snapFiles, controllerMessenger, runSaga);
54
+ const permittedHooks = getPermittedHooks(runSaga);
54
55
  const multichainHooks = getMultichainHooks(snapId, options, controllerMessenger);
55
56
  const { subjectMetadataController, permissionController } = (0, controllers_1.getControllers)({
56
57
  controllerMessenger,
@@ -58,22 +59,21 @@ async function installSnap(snapId, { executionService, executionServiceOptions,
58
59
  runSaga,
59
60
  options,
60
61
  });
61
- const permissionMiddleware = permissionController.createPermissionMiddleware({
62
- origin: snapId,
63
- });
64
62
  const engine = (0, middleware_1.createJsonRpcEngine)({
63
+ snapId,
64
+ messenger: controllerMessenger,
65
65
  store,
66
66
  restrictedHooks,
67
67
  permittedHooks,
68
- permissionMiddleware,
69
68
  multichainHooks,
70
69
  isMultichain: false,
71
70
  });
72
71
  const multichainEngine = (0, middleware_1.createJsonRpcEngine)({
72
+ snapId,
73
+ messenger: controllerMessenger,
73
74
  store,
74
75
  restrictedHooks,
75
76
  permittedHooks,
76
- permissionMiddleware,
77
77
  multichainHooks,
78
78
  isMultichain: true,
79
79
  });
@@ -149,7 +149,6 @@ exports.installSnap = installSnap;
149
149
  function getRestrictedHooks(options, store, runSaga) {
150
150
  return {
151
151
  getMnemonic: (0, hooks_1.getGetMnemonicImplementation)(options.secretRecoveryPhrase),
152
- getMnemonicSeed: (0, get_mnemonic_seed_1.getGetMnemonicSeedImplementation)(options.secretRecoveryPhrase),
153
152
  getIsLocked: () => false,
154
153
  getClientCryptography: () => ({}),
155
154
  getSnap: (0, hooks_1.getGetSnapImplementation)(true),
@@ -161,30 +160,15 @@ exports.getRestrictedHooks = getRestrictedHooks;
161
160
  /**
162
161
  * Get the permitted hooks for the simulation.
163
162
  *
164
- * @param snapId - The ID of the Snap.
165
- * @param snapFiles - The fetched Snap files.
166
- * @param controllerMessenger - The controller messenger.
167
163
  * @param runSaga - The run saga function.
168
164
  * @returns The permitted hooks for the simulation.
169
165
  */
170
- function getPermittedHooks(snapId, snapFiles, controllerMessenger, runSaga) {
166
+ function getPermittedHooks(runSaga) {
171
167
  return {
172
- hasPermission: () => true,
173
168
  getUnlockPromise: (0, methods_1.asyncResolve)(),
174
- getIsLocked: () => false,
175
169
  getIsActive: () => true,
176
170
  getVersion: () => '13.6.0-flask.0',
177
- getSnapFile: async (path, encoding) => await (0, files_1.getSnapFile)(snapFiles.auxiliaryFiles, path, encoding),
178
- createInterface: (...args) => controllerMessenger.call('SnapInterfaceController:createInterface', snapId, ...args),
179
- updateInterface: (...args) => controllerMessenger.call('SnapInterfaceController:updateInterface', snapId, ...args),
180
- getInterfaceState: (...args) => controllerMessenger.call('SnapInterfaceController:getInterfaceState', snapId, ...args),
181
- getInterfaceContext: (...args) => controllerMessenger.call('SnapInterfaceController:getInterface', snapId, ...args).context,
182
- resolveInterface: async (...args) => controllerMessenger.call('SnapInterfaceController:resolveInterface', snapId, ...args),
183
- getEntropySources: (0, hooks_1.getGetEntropySourcesImplementation)(),
184
- getSnapState: (0, hooks_1.getPermittedGetSnapStateMethodImplementation)(runSaga),
185
- updateSnapState: (0, hooks_1.getPermittedUpdateSnapStateMethodImplementation)(runSaga),
186
- clearSnapState: (0, hooks_1.getPermittedClearSnapStateMethodImplementation)(runSaga),
187
- getSnap: (0, hooks_1.getGetSnapImplementation)(true),
171
+ getAllowedKeyringMethods: () => [],
188
172
  trackError: (0, hooks_1.getTrackErrorImplementation)(runSaga),
189
173
  trackEvent: (0, hooks_1.getTrackEventImplementation)(runSaga),
190
174
  startTrace: (0, hooks_1.getStartTraceImplementation)(runSaga),
@@ -238,6 +222,12 @@ function getMultichainHooks(snapId, options, controllerMessenger) {
238
222
  };
239
223
  }
240
224
  exports.getMultichainHooks = getMultichainHooks;
225
+ /**
226
+ * Get the mock mnemonic for a given source ID.
227
+ *
228
+ * @param options - The simulation options.
229
+ * @returns The mnemonic.
230
+ */
241
231
  /**
242
232
  * Register mocked action handlers.
243
233
  *
@@ -245,8 +235,9 @@ exports.getMultichainHooks = getMultichainHooks;
245
235
  * @param runSaga - The run saga function.
246
236
  * @param options - The simulation options.
247
237
  * @param snapId - The ID of the Snap.
238
+ * @param auxiliaryFiles - Auxiliary files from the fetched Snap.
248
239
  */
249
- function registerActions(controllerMessenger, runSaga, options, snapId) {
240
+ function registerActions(controllerMessenger, runSaga, options, snapId, auxiliaryFiles) {
250
241
  controllerMessenger.registerActionHandler('PhishingController:testOrigin', () => ({ result: false, type: 'all' }));
251
242
  controllerMessenger.registerActionHandler('AccountsController:getAccountByAddress',
252
243
  // @ts-expect-error - This is a partial account with only the necessary
@@ -300,6 +291,70 @@ function registerActions(controllerMessenger, runSaga, options, snapId) {
300
291
  await runSaga(interface_1.resolveWithSaga, value).toPromise();
301
292
  return { value };
302
293
  });
294
+ controllerMessenger.registerActionHandler('ApprovalController:addRequest',
295
+ // @ts-expect-error Types of property 'requestData' are incompatible.
296
+ (0, hooks_1.getRequestUserApprovalImplementation)(runSaga));
297
+ controllerMessenger.registerActionHandler('SnapController:getSnap', (0, hooks_1.getGetSnapImplementation)(true));
298
+ controllerMessenger.registerActionHandler('SnapController:getSnapState', (0, hooks_1.getGetSnapStateMethodImplementation)(runSaga));
299
+ controllerMessenger.registerActionHandler('SnapController:updateSnapState', (0, hooks_1.getUpdateSnapStateMethodImplementation)(runSaga));
300
+ controllerMessenger.registerActionHandler('SnapController:clearSnapState', (0, hooks_1.getClearSnapStateMethodImplementation)(runSaga));
301
+ controllerMessenger.registerActionHandler('SnapController:getSnapFile', async (_snapId, path, encoding) => (0, files_1.getSnapFile)(auxiliaryFiles, path, encoding));
302
+ const showNativeNotification = (0, hooks_1.getShowNativeNotificationImplementation)(runSaga);
303
+ const showInAppNotification = (0, hooks_1.getShowInAppNotificationImplementation)(runSaga);
304
+ controllerMessenger.registerActionHandler(
305
+ // @ts-expect-error - `RateLimitController` is not part of the simulation messenger types.
306
+ 'RateLimitController:call', async (_origin, type, ...args) => {
307
+ switch (type) {
308
+ case 'showNativeNotification':
309
+ return await showNativeNotification(args[0], {
310
+ type: 'native',
311
+ message: args[1],
312
+ });
313
+ case 'showInAppNotification':
314
+ return await showInAppNotification(args[0], args[1]);
315
+ /* istanbul ignore next */
316
+ default:
317
+ return (0, utils_1.assertExhaustive)(type);
318
+ }
319
+ });
320
+ const getMnemonic = (0, hooks_1.getGetMnemonicImplementation)(options.secretRecoveryPhrase);
321
+ controllerMessenger.registerActionHandler(
322
+ // @ts-expect-error - `KeyringController` is not part of the simulation messenger types.
323
+ 'KeyringController:getState', () => ({
324
+ isUnlocked: true,
325
+ keyrings: [
326
+ {
327
+ type: 'HD Key Tree',
328
+ metadata: {
329
+ id: 'default',
330
+ name: 'Default Secret Recovery Phrase',
331
+ },
332
+ },
333
+ {
334
+ type: 'HD Key Tree',
335
+ metadata: {
336
+ id: 'alternative',
337
+ name: 'Alternative Secret Recovery Phrase',
338
+ },
339
+ },
340
+ ],
341
+ }));
342
+ controllerMessenger.registerActionHandler(
343
+ // @ts-expect-error - `KeyringController` is not part of the simulation messenger types.
344
+ 'KeyringController:withKeyring', async (selector, operation) => {
345
+ const source = (0, utils_1.hasProperty)(selector, 'id')
346
+ ? selector.id
347
+ : undefined;
348
+ const mnemonic = await getMnemonic(source);
349
+ const seed = await (0, key_tree_1.mnemonicToSeed)(mnemonic);
350
+ return await operation({
351
+ keyring: {
352
+ type: 'HD Key Tree',
353
+ mnemonic,
354
+ seed,
355
+ },
356
+ });
357
+ });
303
358
  }
304
359
  exports.registerActions = registerActions;
305
360
  //# sourceMappingURL=simulation.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"simulation.cjs","sourceRoot":"","sources":["../src/simulation.ts"],"names":[],"mappings":";;;AAAA,qFAA0E;AAQ1E,mDAAoE;AACpE,2EAIyC;AAEzC,2DAK0C;AAC1C,mEAAoE;AAcpE,uDAAiD;AAGjD,qDAA2C;AAE3C,gDAA4C;AAG5C,mDAA6D;AAC7D,uCAAsC;AAEtC,2CAAuC;AACvC,+CAA8C;AAC9C,iDAAwD;AACxD,qDAYyB;AACzB,6EAAqF;AACrF,uDAAmD;AAMnD,2CAAuC;AAOvC,6CAA2D;AAC3D,iDAA2D;AAyT3D;;;;;;;;;;;;;;GAcG;AACI,KAAK,UAAU,WAAW,CAG/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;IAEh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CAAC,qBAAqB,CACvC,qCAAqC,EACrC,GAAG,EAAE,CAAC,CAAC;QACL,4DAA4D;QAC5D,mDAAmD;QACnD,cAAc,EAAE,OAAO,CAAC,MAAM;QAC9B,cAAc,EAAE,OAAO,CAAC,QAAQ,CAAC,MAAM,CACrC,CAAC,GAAG,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 { createEngineStream } from '@metamask/json-rpc-middleware-stream';\nimport type { CryptographicFunctions } from '@metamask/key-tree';\nimport type {\n ActionConstraint,\n EventConstraint,\n MockAnyNamespace,\n NamespacedName,\n} from '@metamask/messenger';\nimport { MOCK_ANY_NAMESPACE, Messenger } from '@metamask/messenger';\nimport {\n PermissionDoesNotExistError,\n type Caveat,\n type RequestedPermissions,\n} from '@metamask/permission-controller';\nimport type { ExecutionService } 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, Hex, 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 getSetCurrentChainImplementation,\n} from './methods/hooks';\nimport { getGetMnemonicSeedImplementation } from './methods/hooks/get-mnemonic-seed';\nimport { createJsonRpcEngine } from './middleware';\nimport type {\n SimulationAccount,\n SimulationOptions,\n SimulationUserOptions,\n} from './options';\nimport { getOptions } from './options';\nimport type {\n ApplicationState,\n Interface,\n RunSagaFunction,\n Store,\n} 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 ExecutionService>[0]\n>;\n\n/**\n * The options for running a Snap in a simulated environment.\n *\n * @property executionService - The execution service to use.\n * @property executionServiceOptions - The options to use when creating the\n * execution service, if any. This should only include options specific to the\n * provided execution service.\n * @property options - The simulation options.\n * @template Service - The type of the execution service.\n */\nexport type InstallSnapOptions<\n Service extends new (...args: any[]) => InstanceType<typeof ExecutionService>,\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 ExecutionService>;\n controllerMessenger: Messenger<\n NamespacedName,\n ActionConstraint,\n EventConstraint\n >;\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 /**\n * A hook that returns metadata about a given Snap.\n *\n * @param snapId - The ID of a Snap.\n * @returns The metadata for the given Snap.\n */\n getSnap: (snapId: string) => Snap;\n\n /**\n * A hook that sets the current chain ID.\n *\n * @param chainId - The chain ID.\n */\n setCurrentChain: (chainId: Hex) => null;\n\n /**\n * A hook that gets the current simulation state.\n *\n * @returns The simulation state.\n */\n getSimulationState: () => ApplicationState;\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 client version.\n *\n * @returns A string that corresponds to the client version.\n */\n getVersion: () => string;\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: (content: Component, context?: InterfaceContext) => 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) => 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\nexport type MultichainMiddlewareHooks = {\n /**\n * A hook that returns the simulated accounts.\n *\n * @returns The simulated accounts.\n */\n getAccounts: () => SimulationAccount[];\n\n /**\n * A hook that retrieves a caveat for a given permission.\n *\n * @param permission - The permission name.\n * @param caveatType - The caveat type.\n * @returns The caveat, if it exists.\n */\n getCaveat: (\n permission: string,\n caveatType: string,\n ) => Caveat<string, Json> | undefined;\n\n /**\n * A hook that grants permissions to the origin.\n *\n * @param permissions - The permissions.\n */\n grantPermissions: (permissions: RequestedPermissions) => void;\n\n /**\n * A hook that revokes a permission for the origin.\n *\n * @param permission - The permission name.\n */\n revokePermission: (permission: string) => 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 (...args: any[]) => InstanceType<typeof ExecutionService>,\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<MockAnyNamespace, any, any>({\n namespace: MOCK_ANY_NAMESPACE,\n });\n\n registerActions(controllerMessenger, runSaga, options, snapId);\n\n // Set up controllers and JSON-RPC stack.\n const restrictedHooks = getRestrictedHooks(options, store, runSaga);\n\n const permittedHooks = getPermittedHooks(\n snapId,\n snapFiles,\n controllerMessenger,\n runSaga,\n );\n\n const multichainHooks = getMultichainHooks(\n snapId,\n options,\n controllerMessenger,\n );\n\n const { subjectMetadataController, permissionController } = getControllers({\n controllerMessenger,\n hooks: restrictedHooks,\n runSaga,\n options,\n });\n\n const permissionMiddleware = permissionController.createPermissionMiddleware({\n origin: snapId,\n });\n\n const engine = createJsonRpcEngine({\n store,\n restrictedHooks,\n permittedHooks,\n permissionMiddleware,\n multichainHooks,\n isMultichain: false,\n });\n\n const multichainEngine = createJsonRpcEngine({\n store,\n restrictedHooks,\n permittedHooks,\n permissionMiddleware,\n multichainHooks,\n isMultichain: true,\n });\n\n // Create execution service.\n const ActualService = executionService ?? NodeThreadExecutionService;\n const service = new ActualService({\n ...executionServiceOptions,\n messenger: new Messenger({\n namespace: 'ExecutionService',\n parent: controllerMessenger,\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 const multichainStream = mux.createStream('metamask-multichain-provider');\n const multichainProviderStream = createEngineStream({\n engine: multichainEngine,\n });\n\n /* istanbul ignore next 2 */\n pipeline(\n multichainStream,\n multichainProviderStream,\n multichainStream,\n (error) => {\n if (error && !error.message?.match('Premature close')) {\n logError(`Provider stream failure.`, error);\n }\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 * @param store - The Redux store.\n * @param runSaga - The run saga function.\n * @returns The hooks for the simulation.\n */\nexport function getRestrictedHooks(\n options: SimulationOptions,\n store: Store,\n runSaga: RunSagaFunction,\n): RestrictedMiddlewareHooks {\n return {\n getMnemonic: getGetMnemonicImplementation(options.secretRecoveryPhrase),\n getMnemonicSeed: getGetMnemonicSeedImplementation(\n options.secretRecoveryPhrase,\n ),\n getIsLocked: () => false,\n getClientCryptography: () => ({}),\n getSnap: getGetSnapImplementation(true),\n setCurrentChain: getSetCurrentChainImplementation(runSaga),\n getSimulationState: store.getState.bind(store),\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 getVersion: () => '13.6.0-flask.0',\n\n getSnapFile: async (path: string, encoding: AuxiliaryFileEncoding) =>\n await getSnapFile(snapFiles.auxiliaryFiles, path, encoding),\n\n createInterface: (...args) =>\n controllerMessenger.call(\n 'SnapInterfaceController:createInterface',\n snapId,\n ...args,\n ),\n updateInterface: (...args) =>\n controllerMessenger.call(\n 'SnapInterfaceController:updateInterface',\n snapId,\n ...args,\n ),\n getInterfaceState: (...args) =>\n controllerMessenger.call(\n 'SnapInterfaceController:getInterfaceState',\n snapId,\n ...args,\n ),\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 * Get the hooks for the multichain middleware simulation.\n *\n * @param snapId - The Snap ID.\n * @param options - The simulation options.\n * @param controllerMessenger - The controller messenger.\n * @returns The hooks for the middleware.\n */\nexport function getMultichainHooks(\n snapId: SnapId,\n options: SimulationOptions,\n controllerMessenger: RootControllerMessenger,\n): MultichainMiddlewareHooks {\n return {\n getAccounts: () => options.accounts,\n getCaveat: (permission: string, caveatType: string) => {\n try {\n return controllerMessenger.call(\n 'PermissionController:getCaveat',\n snapId,\n permission,\n caveatType,\n );\n } catch (error) {\n if (error instanceof PermissionDoesNotExistError) {\n return undefined;\n }\n /* istanbul ignore next */\n throw error;\n }\n },\n grantPermissions: (approvedPermissions: RequestedPermissions) => {\n controllerMessenger.call('PermissionController:grantPermissions', {\n subject: { origin: snapId },\n approvedPermissions,\n });\n },\n revokePermission: (permission: string) => {\n try {\n controllerMessenger.call('PermissionController:revokePermissions', {\n [snapId]: [permission],\n });\n } catch (error) {\n if (error instanceof PermissionDoesNotExistError) {\n return;\n }\n /* istanbul ignore next */\n throw error;\n }\n },\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: '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":";;;AAAA,qFAA0E;AAE1E,iDAAoD;AAOpD,mDAAoE;AACpE,2EAIyC;AAEzC,2DAK0C;AAC1C,mEAAoE;AASpE,uDAAiD;AACjD,2CAAgE;AAGhE,qDAA2C;AAE3C,gDAA4C;AAG5C,mDAA6D;AAC7D,uCAAsC;AAEtC,2CAAuC;AACvC,+CAA8C;AAC9C,iDAAwD;AACxD,qDAcyB;AACzB,uDAAmD;AAMnD,2CAAuC;AAOvC,6CAA2D;AAC3D,iDAA2D;AAkM3D;;;;;;;;;;;;;;GAcG;AACI,KAAK,UAAU,WAAW,CAG/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,qBAAS,CAA6B;QACpE,SAAS,EAAE,8BAAkB;KAC9B,CAAC,CAAC;IAEH,eAAe,CACb,mBAAmB,EACnB,OAAO,EACP,OAAO,EACP,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AU,EAAE,IAAI;QAChB,QAAQ,EAAE;YACR;gBACE,IAAI,EAAE,aAAa;gBACnB,QAAQ,EAAE;oBACR,EAAE,EAAE,SAAS;oBACb,IAAI,EAAE,gCAAgC;iBACvC;aACF;YACD;gBACE,IAAI,EAAE,aAAa;gBACnB,QAAQ,EAAE;oBACR,EAAE,EAAE,aAAa;oBACjB,IAAI,EAAE,oCAAoC;iBAC3C;aACF;SACF;KACF,CAAC,CACH,CAAC;IAEF,mBAAmB,CAAC,qBAAqB;IACvC,wFAAwF;IACxF,+BAA+B,EAC/B,KAAK,EACH,QAA2D,EAC3D,SAEsB,EACtB,EAAE;QACF,MAAM,MAAM,GAAG,IAAA,mBAAW,EAAC,QAAQ,EAAE,IAAI,CAAC;YACxC,CAAC,CAAE,QAAQ,CAAC,EAAa;YACzB,CAAC,CAAC,SAAS,CAAC;QAEd,MAAM,QAAQ,GAAG,MAAM,WAAW,CAAC,MAAM,CAAC,CAAC;QAC3C,MAAM,IAAI,GAAG,MAAM,IAAA,yBAAc,EAAC,QAAQ,CAAC,CAAC;QAE5C,OAAO,MAAM,SAAS,CAAC;YACrB,OAAO,EAAE;gBACP,IAAI,EAAE,aAAa;gBACnB,QAAQ;gBACR,IAAI;aACL;SACF,CAAC,CAAC;IACL,CAAC,CACF,CAAC;AACJ,CAAC;AA7ND,0CA6NC","sourcesContent":["import { createEngineStream } from '@metamask/json-rpc-middleware-stream';\nimport type { CryptographicFunctions } from '@metamask/key-tree';\nimport { mnemonicToSeed } from '@metamask/key-tree';\nimport type {\n ActionConstraint,\n EventConstraint,\n MockAnyNamespace,\n NamespacedName,\n} from '@metamask/messenger';\nimport { MOCK_ANY_NAMESPACE, Messenger } from '@metamask/messenger';\nimport {\n PermissionDoesNotExistError,\n type Caveat,\n type RequestedPermissions,\n} from '@metamask/permission-controller';\nimport type { ExecutionService } 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 SnapId,\n TraceRequest,\n EndTraceRequest,\n TraceContext,\n} from '@metamask/snaps-sdk';\nimport type { Snap, VirtualFile } from '@metamask/snaps-utils';\nimport { logError } from '@metamask/snaps-utils';\nimport { assertExhaustive, hasProperty } from '@metamask/utils';\nimport type { CaipAssetType, Hex, 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 getGetMnemonicImplementation,\n getGetSnapImplementation,\n getTrackEventImplementation,\n getTrackErrorImplementation,\n getEndTraceImplementation,\n getStartTraceImplementation,\n getSetCurrentChainImplementation,\n getClearSnapStateMethodImplementation,\n getGetSnapStateMethodImplementation,\n getUpdateSnapStateMethodImplementation,\n getRequestUserApprovalImplementation,\n getShowInAppNotificationImplementation,\n getShowNativeNotificationImplementation,\n} from './methods/hooks';\nimport { createJsonRpcEngine } from './middleware';\nimport type {\n SimulationAccount,\n SimulationOptions,\n SimulationUserOptions,\n} from './options';\nimport { getOptions } from './options';\nimport type {\n ApplicationState,\n Interface,\n RunSagaFunction,\n Store,\n} 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 ExecutionService>[0]\n>;\n\n/**\n * The options for running a Snap in a simulated environment.\n *\n * @property executionService - The execution service to use.\n * @property executionServiceOptions - The options to use when creating the\n * execution service, if any. This should only include options specific to the\n * provided execution service.\n * @property options - The simulation options.\n * @template Service - The type of the execution service.\n */\nexport type InstallSnapOptions<\n Service extends new (...args: any[]) => InstanceType<typeof ExecutionService>,\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 ExecutionService>;\n controllerMessenger: Messenger<\n NamespacedName,\n ActionConstraint,\n EventConstraint\n >;\n runSaga: RunSagaFunction;\n};\n\nexport type RestrictedMiddlewareHooks = {\n /**\n * A hook that returns the user's secret recovery phrase.\n *\n * @returns The user's secret recovery phrase.\n */\n getMnemonic: () => Promise<Uint8Array>;\n\n /**\n * A hook that returns 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 /**\n * A hook that returns metadata about a given Snap.\n *\n * @param snapId - The ID of a Snap.\n * @returns The metadata for the given Snap.\n */\n getSnap: (snapId: string) => Snap;\n\n /**\n * A hook that sets the current chain ID.\n *\n * @param chainId - The chain ID.\n */\n setCurrentChain: (chainId: Hex) => null;\n\n /**\n * A hook that gets the current simulation state.\n *\n * @returns The simulation state.\n */\n getSimulationState: () => ApplicationState;\n};\n\nexport type PermittedMiddlewareHooks = {\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 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 client version.\n *\n * @returns A string that corresponds to the client version.\n */\n getVersion: () => string;\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 * A hook that returns the allowed keyring methods.\n *\n * @returns The keyring methods.\n */\n getAllowedKeyringMethods(): string[];\n};\n\nexport type MultichainMiddlewareHooks = {\n /**\n * A hook that returns the simulated accounts.\n *\n * @returns The simulated accounts.\n */\n getAccounts: () => SimulationAccount[];\n\n /**\n * A hook that retrieves a caveat for a given permission.\n *\n * @param permission - The permission name.\n * @param caveatType - The caveat type.\n * @returns The caveat, if it exists.\n */\n getCaveat: (\n permission: string,\n caveatType: string,\n ) => Caveat<string, Json> | undefined;\n\n /**\n * A hook that grants permissions to the origin.\n *\n * @param permissions - The permissions.\n */\n grantPermissions: (permissions: RequestedPermissions) => void;\n\n /**\n * A hook that revokes a permission for the origin.\n *\n * @param permission - The permission name.\n */\n revokePermission: (permission: string) => 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 (...args: any[]) => InstanceType<typeof ExecutionService>,\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<MockAnyNamespace, any, any>({\n namespace: MOCK_ANY_NAMESPACE,\n });\n\n registerActions(\n controllerMessenger,\n runSaga,\n options,\n snapId,\n snapFiles.auxiliaryFiles,\n );\n\n // Set up controllers and JSON-RPC stack.\n const restrictedHooks = getRestrictedHooks(options, store, runSaga);\n\n const permittedHooks = getPermittedHooks(runSaga);\n\n const multichainHooks = getMultichainHooks(\n snapId,\n options,\n controllerMessenger,\n );\n\n const { subjectMetadataController, permissionController } = getControllers({\n controllerMessenger,\n hooks: restrictedHooks,\n runSaga,\n options,\n });\n\n const engine = createJsonRpcEngine({\n snapId,\n messenger: controllerMessenger,\n store,\n restrictedHooks,\n permittedHooks,\n multichainHooks,\n isMultichain: false,\n });\n\n const multichainEngine = createJsonRpcEngine({\n snapId,\n messenger: controllerMessenger,\n store,\n restrictedHooks,\n permittedHooks,\n multichainHooks,\n isMultichain: true,\n });\n\n // Create execution service.\n const ActualService = executionService ?? NodeThreadExecutionService;\n const service = new ActualService({\n ...executionServiceOptions,\n messenger: new Messenger({\n namespace: 'ExecutionService',\n parent: controllerMessenger,\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 const multichainStream = mux.createStream('metamask-multichain-provider');\n const multichainProviderStream = createEngineStream({\n engine: multichainEngine,\n });\n\n /* istanbul ignore next 2 */\n pipeline(\n multichainStream,\n multichainProviderStream,\n multichainStream,\n (error) => {\n if (error && !error.message?.match('Premature close')) {\n logError(`Provider stream failure.`, error);\n }\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 * @param store - The Redux store.\n * @param runSaga - The run saga function.\n * @returns The hooks for the simulation.\n */\nexport function getRestrictedHooks(\n options: SimulationOptions,\n store: Store,\n runSaga: RunSagaFunction,\n): RestrictedMiddlewareHooks {\n return {\n getMnemonic: getGetMnemonicImplementation(options.secretRecoveryPhrase),\n getIsLocked: () => false,\n getClientCryptography: () => ({}),\n getSnap: getGetSnapImplementation(true),\n setCurrentChain: getSetCurrentChainImplementation(runSaga),\n getSimulationState: store.getState.bind(store),\n };\n}\n\n/**\n * Get the permitted hooks for the simulation.\n *\n * @param runSaga - The run saga function.\n * @returns The permitted hooks for the simulation.\n */\nexport function getPermittedHooks(\n runSaga: RunSagaFunction,\n): PermittedMiddlewareHooks {\n return {\n getUnlockPromise: asyncResolve(),\n getIsActive: () => true,\n getVersion: () => '13.6.0-flask.0',\n\n getAllowedKeyringMethods: () => [],\n\n trackError: getTrackErrorImplementation(runSaga),\n trackEvent: getTrackEventImplementation(runSaga),\n startTrace: getStartTraceImplementation(runSaga),\n endTrace: getEndTraceImplementation(runSaga),\n };\n}\n\n/**\n * Get the hooks for the multichain middleware simulation.\n *\n * @param snapId - The Snap ID.\n * @param options - The simulation options.\n * @param controllerMessenger - The controller messenger.\n * @returns The hooks for the middleware.\n */\nexport function getMultichainHooks(\n snapId: SnapId,\n options: SimulationOptions,\n controllerMessenger: RootControllerMessenger,\n): MultichainMiddlewareHooks {\n return {\n getAccounts: () => options.accounts,\n getCaveat: (permission: string, caveatType: string) => {\n try {\n return controllerMessenger.call(\n 'PermissionController:getCaveat',\n snapId,\n permission,\n caveatType,\n );\n } catch (error) {\n if (error instanceof PermissionDoesNotExistError) {\n return undefined;\n }\n /* istanbul ignore next */\n throw error;\n }\n },\n grantPermissions: (approvedPermissions: RequestedPermissions) => {\n controllerMessenger.call('PermissionController:grantPermissions', {\n subject: { origin: snapId },\n approvedPermissions,\n });\n },\n revokePermission: (permission: string) => {\n try {\n controllerMessenger.call('PermissionController:revokePermissions', {\n [snapId]: [permission],\n });\n } catch (error) {\n if (error instanceof PermissionDoesNotExistError) {\n return;\n }\n /* istanbul ignore next */\n throw error;\n }\n },\n };\n}\n\n/**\n * Get the mock mnemonic for a given source ID.\n *\n * @param options - The simulation options.\n * @returns The mnemonic.\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 * @param auxiliaryFiles - Auxiliary files from the fetched Snap.\n */\nexport function registerActions(\n controllerMessenger: RootControllerMessenger,\n runSaga: RunSagaFunction,\n options: SimulationOptions,\n snapId: SnapId,\n auxiliaryFiles: VirtualFile[],\n) {\n controllerMessenger.registerActionHandler(\n 'PhishingController:testOrigin',\n () => ({ result: false, type: '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 controllerMessenger.registerActionHandler(\n 'ApprovalController:addRequest',\n // @ts-expect-error Types of property 'requestData' are incompatible.\n getRequestUserApprovalImplementation(runSaga),\n );\n\n controllerMessenger.registerActionHandler(\n 'SnapController:getSnap',\n getGetSnapImplementation(true),\n );\n\n controllerMessenger.registerActionHandler(\n 'SnapController:getSnapState',\n getGetSnapStateMethodImplementation(runSaga),\n );\n\n controllerMessenger.registerActionHandler(\n 'SnapController:updateSnapState',\n getUpdateSnapStateMethodImplementation(runSaga),\n );\n\n controllerMessenger.registerActionHandler(\n 'SnapController:clearSnapState',\n getClearSnapStateMethodImplementation(runSaga),\n );\n\n controllerMessenger.registerActionHandler(\n 'SnapController:getSnapFile',\n async (_snapId, path, encoding) =>\n getSnapFile(auxiliaryFiles, path, encoding),\n );\n\n const showNativeNotification =\n getShowNativeNotificationImplementation(runSaga);\n const showInAppNotification = getShowInAppNotificationImplementation(runSaga);\n\n controllerMessenger.registerActionHandler(\n // @ts-expect-error - `RateLimitController` is not part of the simulation messenger types.\n 'RateLimitController:call',\n async (\n _origin: string,\n type: 'showNativeNotification' | 'showInAppNotification',\n ...args: unknown[]\n ) => {\n switch (type) {\n case 'showNativeNotification':\n return await showNativeNotification(args[0] as string, {\n type: 'native',\n message: args[1] as string,\n });\n case 'showInAppNotification':\n return await showInAppNotification(\n args[0] as string,\n args[1] as Parameters<typeof showInAppNotification>[1],\n );\n /* istanbul ignore next */\n default:\n return assertExhaustive(type);\n }\n },\n );\n\n const getMnemonic = getGetMnemonicImplementation(\n options.secretRecoveryPhrase,\n );\n\n controllerMessenger.registerActionHandler(\n // @ts-expect-error - `KeyringController` is not part of the simulation messenger types.\n 'KeyringController:getState',\n () => ({\n isUnlocked: true,\n keyrings: [\n {\n type: 'HD Key Tree',\n metadata: {\n id: 'default',\n name: 'Default Secret Recovery Phrase',\n },\n },\n {\n type: 'HD Key Tree',\n metadata: {\n id: 'alternative',\n name: 'Alternative Secret Recovery Phrase',\n },\n },\n ],\n }),\n );\n\n controllerMessenger.registerActionHandler(\n // @ts-expect-error - `KeyringController` is not part of the simulation messenger types.\n 'KeyringController:withKeyring',\n async (\n selector: { type: string; index?: number } | { id: string },\n operation: (args: {\n keyring: { type: string; mnemonic: Uint8Array; seed: Uint8Array };\n }) => Promise<unknown>,\n ) => {\n const source = hasProperty(selector, 'id')\n ? (selector.id as string)\n : undefined;\n\n const mnemonic = await getMnemonic(source);\n const seed = await mnemonicToSeed(mnemonic);\n\n return await operation({\n keyring: {\n type: 'HD Key Tree',\n mnemonic,\n seed,\n },\n });\n },\n );\n}\n"]}