@metamask/snaps-rpc-methods 13.5.1 → 13.5.3

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 (58) hide show
  1. package/CHANGELOG.md +19 -1
  2. package/dist/permitted/createInterface.cjs +2 -2
  3. package/dist/permitted/createInterface.cjs.map +1 -1
  4. package/dist/permitted/createInterface.d.cts +15 -3
  5. package/dist/permitted/createInterface.d.cts.map +1 -1
  6. package/dist/permitted/createInterface.d.mts +15 -3
  7. package/dist/permitted/createInterface.d.mts.map +1 -1
  8. package/dist/permitted/createInterface.mjs +2 -2
  9. package/dist/permitted/createInterface.mjs.map +1 -1
  10. package/dist/permitted/invokeKeyring.cjs +4 -2
  11. package/dist/permitted/invokeKeyring.cjs.map +1 -1
  12. package/dist/permitted/invokeKeyring.mjs +4 -2
  13. package/dist/permitted/invokeKeyring.mjs.map +1 -1
  14. package/dist/permitted/setState.cjs +13 -6
  15. package/dist/permitted/setState.cjs.map +1 -1
  16. package/dist/permitted/setState.d.cts +7 -1
  17. package/dist/permitted/setState.d.cts.map +1 -1
  18. package/dist/permitted/setState.d.mts +7 -1
  19. package/dist/permitted/setState.d.mts.map +1 -1
  20. package/dist/permitted/setState.mjs +14 -7
  21. package/dist/permitted/setState.mjs.map +1 -1
  22. package/dist/permitted/updateInterface.cjs +2 -2
  23. package/dist/permitted/updateInterface.cjs.map +1 -1
  24. package/dist/permitted/updateInterface.d.cts +1 -1
  25. package/dist/permitted/updateInterface.d.cts.map +1 -1
  26. package/dist/permitted/updateInterface.d.mts +1 -1
  27. package/dist/permitted/updateInterface.d.mts.map +1 -1
  28. package/dist/permitted/updateInterface.mjs +2 -2
  29. package/dist/permitted/updateInterface.mjs.map +1 -1
  30. package/dist/restricted/index.d.cts +1 -0
  31. package/dist/restricted/index.d.cts.map +1 -1
  32. package/dist/restricted/index.d.mts +1 -0
  33. package/dist/restricted/index.d.mts.map +1 -1
  34. package/dist/restricted/invokeSnap.cjs +1 -8
  35. package/dist/restricted/invokeSnap.cjs.map +1 -1
  36. package/dist/restricted/invokeSnap.d.cts +2 -4
  37. package/dist/restricted/invokeSnap.d.cts.map +1 -1
  38. package/dist/restricted/invokeSnap.d.mts +2 -4
  39. package/dist/restricted/invokeSnap.d.mts.map +1 -1
  40. package/dist/restricted/invokeSnap.mjs +1 -8
  41. package/dist/restricted/invokeSnap.mjs.map +1 -1
  42. package/dist/restricted/manageAccounts.cjs +4 -1
  43. package/dist/restricted/manageAccounts.cjs.map +1 -1
  44. package/dist/restricted/manageAccounts.d.cts +9 -1
  45. package/dist/restricted/manageAccounts.d.cts.map +1 -1
  46. package/dist/restricted/manageAccounts.d.mts +9 -1
  47. package/dist/restricted/manageAccounts.d.mts.map +1 -1
  48. package/dist/restricted/manageAccounts.mjs +4 -1
  49. package/dist/restricted/manageAccounts.mjs.map +1 -1
  50. package/dist/restricted/manageState.cjs +16 -14
  51. package/dist/restricted/manageState.cjs.map +1 -1
  52. package/dist/restricted/manageState.d.cts +10 -3
  53. package/dist/restricted/manageState.d.cts.map +1 -1
  54. package/dist/restricted/manageState.d.mts +10 -3
  55. package/dist/restricted/manageState.d.mts.map +1 -1
  56. package/dist/restricted/manageState.mjs +18 -16
  57. package/dist/restricted/manageState.mjs.map +1 -1
  58. package/package.json +6 -6
package/CHANGELOG.md CHANGED
@@ -7,6 +7,22 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [13.5.3]
11
+
12
+ ### Fixed
13
+
14
+ - Wait for unlock before handling `manageAccounts` requests ([#3686](https://github.com/MetaMask/snaps/pull/3686))
15
+ - Throw if Snap not installed ([#3666](https://github.com/MetaMask/snaps/pull/3666))
16
+
17
+ ## [13.5.2]
18
+
19
+ ### Changed
20
+
21
+ - Reduce JSON validation during state updates ([#3660](https://github.com/MetaMask/snaps/pull/3660))
22
+ - As part of this change, JSON sizing limits are not longer enforced for preinstalled Snaps.
23
+ - Adjust hooks after interface actions were made synchronous ([#3361](https://github.com/MetaMask/snaps/pull/3361))
24
+ - Bump MetaMask dependencies ([#3651](https://github.com/MetaMask/snaps/pull/3651), [#3638](https://github.com/MetaMask/snaps/pull/3638), [#3648](https://github.com/MetaMask/snaps/pull/3648), [#3630](https://github.com/MetaMask/snaps/pull/3630), [#3628](https://github.com/MetaMask/snaps/pull/3628), [#3629](https://github.com/MetaMask/snaps/pull/3629), [#3607](https://github.com/MetaMask/snaps/pull/3607), [#3623](https://github.com/MetaMask/snaps/pull/3623), [#3612](https://github.com/MetaMask/snaps/pull/3612))
25
+
10
26
  ## [13.5.1]
11
27
 
12
28
  ### Fixed
@@ -500,7 +516,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
500
516
  - The version of the package no longer needs to match the version of all other
501
517
  MetaMask Snaps packages.
502
518
 
503
- [Unreleased]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-rpc-methods@13.5.1...HEAD
519
+ [Unreleased]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-rpc-methods@13.5.3...HEAD
520
+ [13.5.3]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-rpc-methods@13.5.2...@metamask/snaps-rpc-methods@13.5.3
521
+ [13.5.2]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-rpc-methods@13.5.1...@metamask/snaps-rpc-methods@13.5.2
504
522
  [13.5.1]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-rpc-methods@13.5.0...@metamask/snaps-rpc-methods@13.5.1
505
523
  [13.5.0]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-rpc-methods@13.4.0...@metamask/snaps-rpc-methods@13.5.0
506
524
  [13.4.0]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-rpc-methods@13.3.0...@metamask/snaps-rpc-methods@13.4.0
@@ -28,12 +28,12 @@ const CreateInterfaceParametersStruct = (0, superstruct_1.object)({
28
28
  * @param hooks.createInterface - The function to create the interface.
29
29
  * @returns Nothing.
30
30
  */
31
- async function getCreateInterfaceImplementation(req, res, _next, end, { createInterface }) {
31
+ function getCreateInterfaceImplementation(req, res, _next, end, { createInterface }) {
32
32
  const { params } = req;
33
33
  try {
34
34
  const validatedParams = getValidatedParams(params);
35
35
  const { ui, context } = validatedParams;
36
- res.result = await createInterface(ui, context);
36
+ res.result = createInterface(ui, context);
37
37
  }
38
38
  catch (error) {
39
39
  return end(error);
@@ -1 +1 @@
1
- {"version":3,"file":"createInterface.cjs","sourceRoot":"","sources":["../../src/permitted/createInterface.ts"],"names":[],"mappings":";;;AAEA,qDAAiD;AASjD,mDAG6B;AAE7B,uDAA8E;AAK9E,MAAM,SAAS,GAAkD;IAC/D,eAAe,EAAE,IAAI;CACtB,CAAC;AAcW,QAAA,sBAAsB,GAI/B;IACF,WAAW,EAAE,CAAC,sBAAsB,CAAC;IACrC,cAAc,EAAE,gCAAgC;IAChD,SAAS;CACV,CAAC;AAEF,MAAM,+BAA+B,GAAG,IAAA,oBAAM,EAAC;IAC7C,EAAE,EAAE,oCAAwB;IAC5B,OAAO,EAAE,IAAA,sBAAQ,EAAC,kCAAsB,CAAC;CAC1C,CAAC,CAAC;AAOH;;;;;;;;;;;GAWG;AACH,KAAK,UAAU,gCAAgC,CAC7C,GAA8C,EAC9C,GAAkD,EAClD,KAAc,EACd,GAA6B,EAC7B,EAAE,eAAe,EAA8B;IAE/C,MAAM,EAAE,MAAM,EAAE,GAAG,GAAG,CAAC;IAEvB,IAAI,CAAC;QACH,MAAM,eAAe,GAAG,kBAAkB,CAAC,MAAM,CAAC,CAAC;QAEnD,MAAM,EAAE,EAAE,EAAE,OAAO,EAAE,GAAG,eAAe,CAAC;QAExC,GAAG,CAAC,MAAM,GAAG,MAAM,eAAe,CAAC,EAAE,EAAE,OAAO,CAAC,CAAC;IAClD,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,OAAO,GAAG,CAAC,KAAK,CAAC,CAAC;IACpB,CAAC;IAED,OAAO,GAAG,EAAE,CAAC;AACf,CAAC;AAED;;;;;;GAMG;AACH,SAAS,kBAAkB,CAAC,MAAe;IACzC,IAAI,CAAC;QACH,OAAO,IAAA,oBAAM,EAAC,MAAM,EAAE,+BAA+B,CAAC,CAAC;IACzD,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,IAAI,KAAK,YAAY,yBAAW,EAAE,CAAC;YACjC,MAAM,sBAAS,CAAC,aAAa,CAAC;gBAC5B,OAAO,EAAE,mBAAmB,KAAK,CAAC,OAAO,GAAG;aAC7C,CAAC,CAAC;QACL,CAAC;QACD,0BAA0B;QAC1B,MAAM,sBAAS,CAAC,QAAQ,EAAE,CAAC;IAC7B,CAAC;AACH,CAAC","sourcesContent":["import type { JsonRpcEngineEndCallback } from '@metamask/json-rpc-engine';\nimport type { PermittedHandlerExport } from '@metamask/permission-controller';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport type {\n CreateInterfaceParams,\n CreateInterfaceResult,\n JsonRpcRequest,\n ComponentOrElement,\n InterfaceContext,\n ContentType,\n} from '@metamask/snaps-sdk';\nimport {\n ComponentOrElementStruct,\n InterfaceContextStruct,\n} from '@metamask/snaps-sdk';\nimport { type InferMatching } from '@metamask/snaps-utils';\nimport { StructError, create, object, optional } from '@metamask/superstruct';\nimport type { PendingJsonRpcResponse } from '@metamask/utils';\n\nimport type { MethodHooksObject } from '../utils';\n\nconst hookNames: MethodHooksObject<CreateInterfaceMethodHooks> = {\n createInterface: true,\n};\n\nexport type CreateInterfaceMethodHooks = {\n /**\n * @param ui - The UI components.\n * @returns The unique identifier of the interface.\n */\n createInterface: (\n ui: ComponentOrElement,\n context?: InterfaceContext,\n contentType?: ContentType,\n ) => Promise<string>;\n};\n\nexport const createInterfaceHandler: PermittedHandlerExport<\n CreateInterfaceMethodHooks,\n CreateInterfaceParameters,\n CreateInterfaceResult\n> = {\n methodNames: ['snap_createInterface'],\n implementation: getCreateInterfaceImplementation,\n hookNames,\n};\n\nconst CreateInterfaceParametersStruct = object({\n ui: ComponentOrElementStruct,\n context: optional(InterfaceContextStruct),\n});\n\nexport type CreateInterfaceParameters = InferMatching<\n typeof CreateInterfaceParametersStruct,\n CreateInterfaceParams\n>;\n\n/**\n * The `snap_createInterface` method implementation.\n *\n * @param req - The JSON-RPC request object.\n * @param res - The JSON-RPC response object.\n * @param _next - The `json-rpc-engine` \"next\" callback. Not used by this\n * function.\n * @param end - The `json-rpc-engine` \"end\" callback.\n * @param hooks - The RPC method hooks.\n * @param hooks.createInterface - The function to create the interface.\n * @returns Nothing.\n */\nasync function getCreateInterfaceImplementation(\n req: JsonRpcRequest<CreateInterfaceParameters>,\n res: PendingJsonRpcResponse<CreateInterfaceResult>,\n _next: unknown,\n end: JsonRpcEngineEndCallback,\n { createInterface }: CreateInterfaceMethodHooks,\n): Promise<void> {\n const { params } = req;\n\n try {\n const validatedParams = getValidatedParams(params);\n\n const { ui, context } = validatedParams;\n\n res.result = await createInterface(ui, context);\n } catch (error) {\n return end(error);\n }\n\n return end();\n}\n\n/**\n * Validate the createInterface method `params` and returns them cast to the correct\n * type. Throws if validation fails.\n *\n * @param params - The unvalidated params object from the method request.\n * @returns The validated createInterface method parameter object.\n */\nfunction getValidatedParams(params: unknown): CreateInterfaceParameters {\n try {\n return create(params, CreateInterfaceParametersStruct);\n } catch (error) {\n if (error instanceof StructError) {\n throw rpcErrors.invalidParams({\n message: `Invalid params: ${error.message}.`,\n });\n }\n /* istanbul ignore next */\n throw rpcErrors.internal();\n }\n}\n"]}
1
+ {"version":3,"file":"createInterface.cjs","sourceRoot":"","sources":["../../src/permitted/createInterface.ts"],"names":[],"mappings":";;;AAEA,qDAAiD;AASjD,mDAG6B;AAE7B,uDAA8E;AAK9E,MAAM,SAAS,GAAkD;IAC/D,eAAe,EAAE,IAAI;CACtB,CAAC;AAcW,QAAA,sBAAsB,GAI/B;IACF,WAAW,EAAE,CAAC,sBAAsB,CAAC;IACrC,cAAc,EAAE,gCAAgC;IAChD,SAAS;CACV,CAAC;AAEF,MAAM,+BAA+B,GAAG,IAAA,oBAAM,EAAC;IAC7C,EAAE,EAAE,oCAAwB;IAC5B,OAAO,EAAE,IAAA,sBAAQ,EAAC,kCAAsB,CAAC;CAC1C,CAAC,CAAC;AAOH;;;;;;;;;;;GAWG;AACH,SAAS,gCAAgC,CACvC,GAA8C,EAC9C,GAAkD,EAClD,KAAc,EACd,GAA6B,EAC7B,EAAE,eAAe,EAA8B;IAE/C,MAAM,EAAE,MAAM,EAAE,GAAG,GAAG,CAAC;IAEvB,IAAI,CAAC;QACH,MAAM,eAAe,GAAG,kBAAkB,CAAC,MAAM,CAAC,CAAC;QAEnD,MAAM,EAAE,EAAE,EAAE,OAAO,EAAE,GAAG,eAAe,CAAC;QAExC,GAAG,CAAC,MAAM,GAAG,eAAe,CAAC,EAAE,EAAE,OAAO,CAAC,CAAC;IAC5C,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,OAAO,GAAG,CAAC,KAAK,CAAC,CAAC;IACpB,CAAC;IAED,OAAO,GAAG,EAAE,CAAC;AACf,CAAC;AAED;;;;;;GAMG;AACH,SAAS,kBAAkB,CAAC,MAAe;IACzC,IAAI,CAAC;QACH,OAAO,IAAA,oBAAM,EAAC,MAAM,EAAE,+BAA+B,CAAC,CAAC;IACzD,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,IAAI,KAAK,YAAY,yBAAW,EAAE,CAAC;YACjC,MAAM,sBAAS,CAAC,aAAa,CAAC;gBAC5B,OAAO,EAAE,mBAAmB,KAAK,CAAC,OAAO,GAAG;aAC7C,CAAC,CAAC;QACL,CAAC;QACD,0BAA0B;QAC1B,MAAM,sBAAS,CAAC,QAAQ,EAAE,CAAC;IAC7B,CAAC;AACH,CAAC","sourcesContent":["import type { JsonRpcEngineEndCallback } from '@metamask/json-rpc-engine';\nimport type { PermittedHandlerExport } from '@metamask/permission-controller';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport type {\n CreateInterfaceParams,\n CreateInterfaceResult,\n JsonRpcRequest,\n ComponentOrElement,\n InterfaceContext,\n ContentType,\n} from '@metamask/snaps-sdk';\nimport {\n ComponentOrElementStruct,\n InterfaceContextStruct,\n} from '@metamask/snaps-sdk';\nimport { type InferMatching } from '@metamask/snaps-utils';\nimport { StructError, create, object, optional } from '@metamask/superstruct';\nimport type { PendingJsonRpcResponse } from '@metamask/utils';\n\nimport type { MethodHooksObject } from '../utils';\n\nconst hookNames: MethodHooksObject<CreateInterfaceMethodHooks> = {\n createInterface: true,\n};\n\nexport type CreateInterfaceMethodHooks = {\n /**\n * @param ui - The UI components.\n * @returns The unique identifier of the interface.\n */\n createInterface: (\n ui: ComponentOrElement,\n context?: InterfaceContext,\n contentType?: ContentType,\n ) => string;\n};\n\nexport const createInterfaceHandler: PermittedHandlerExport<\n CreateInterfaceMethodHooks,\n CreateInterfaceParameters,\n CreateInterfaceResult\n> = {\n methodNames: ['snap_createInterface'],\n implementation: getCreateInterfaceImplementation,\n hookNames,\n};\n\nconst CreateInterfaceParametersStruct = object({\n ui: ComponentOrElementStruct,\n context: optional(InterfaceContextStruct),\n});\n\nexport type CreateInterfaceParameters = InferMatching<\n typeof CreateInterfaceParametersStruct,\n CreateInterfaceParams\n>;\n\n/**\n * The `snap_createInterface` method implementation.\n *\n * @param req - The JSON-RPC request object.\n * @param res - The JSON-RPC response object.\n * @param _next - The `json-rpc-engine` \"next\" callback. Not used by this\n * function.\n * @param end - The `json-rpc-engine` \"end\" callback.\n * @param hooks - The RPC method hooks.\n * @param hooks.createInterface - The function to create the interface.\n * @returns Nothing.\n */\nfunction getCreateInterfaceImplementation(\n req: JsonRpcRequest<CreateInterfaceParameters>,\n res: PendingJsonRpcResponse<CreateInterfaceResult>,\n _next: unknown,\n end: JsonRpcEngineEndCallback,\n { createInterface }: CreateInterfaceMethodHooks,\n): void {\n const { params } = req;\n\n try {\n const validatedParams = getValidatedParams(params);\n\n const { ui, context } = validatedParams;\n\n res.result = createInterface(ui, context);\n } catch (error) {\n return end(error);\n }\n\n return end();\n}\n\n/**\n * Validate the createInterface method `params` and returns them cast to the correct\n * type. Throws if validation fails.\n *\n * @param params - The unvalidated params object from the method request.\n * @returns The validated createInterface method parameter object.\n */\nfunction getValidatedParams(params: unknown): CreateInterfaceParameters {\n try {\n return create(params, CreateInterfaceParametersStruct);\n } catch (error) {\n if (error instanceof StructError) {\n throw rpcErrors.invalidParams({\n message: `Invalid params: ${error.message}.`,\n });\n }\n /* istanbul ignore next */\n throw rpcErrors.internal();\n }\n}\n"]}
@@ -6,7 +6,7 @@ export type CreateInterfaceMethodHooks = {
6
6
  * @param ui - The UI components.
7
7
  * @returns The unique identifier of the interface.
8
8
  */
9
- createInterface: (ui: ComponentOrElement, context?: InterfaceContext, contentType?: ContentType) => Promise<string>;
9
+ createInterface: (ui: ComponentOrElement, context?: InterfaceContext, contentType?: ContentType) => string;
10
10
  };
11
11
  export declare const createInterfaceHandler: PermittedHandlerExport<CreateInterfaceMethodHooks, CreateInterfaceParameters, CreateInterfaceResult>;
12
12
  declare const CreateInterfaceParametersStruct: import("@metamask/superstruct").Struct<{
@@ -21,7 +21,13 @@ declare const CreateInterfaceParametersStruct: import("@metamask/superstruct").S
21
21
  type: import("@metamask/snaps-sdk").NodeType.Heading;
22
22
  } | {
23
23
  value: string;
24
- type: import("@metamask/snaps-sdk").NodeType.Image;
24
+ type: import("@metamask/snaps-sdk").NodeType.Image; /**
25
+ * Validate the createInterface method `params` and returns them cast to the correct
26
+ * type. Throws if validation fails.
27
+ *
28
+ * @param params - The unvalidated params object from the method request.
29
+ * @returns The validated createInterface method parameter object.
30
+ */
25
31
  } | {
26
32
  type: import("@metamask/snaps-sdk").NodeType.Spinner;
27
33
  } | {
@@ -108,7 +114,13 @@ declare const CreateInterfaceParametersStruct: import("@metamask/superstruct").S
108
114
  type: import("@metamask/snaps-sdk").NodeType.Heading;
109
115
  } | {
110
116
  value: string;
111
- type: import("@metamask/snaps-sdk").NodeType.Image;
117
+ type: import("@metamask/snaps-sdk").NodeType.Image; /**
118
+ * Validate the createInterface method `params` and returns them cast to the correct
119
+ * type. Throws if validation fails.
120
+ *
121
+ * @param params - The unvalidated params object from the method request.
122
+ * @returns The validated createInterface method parameter object.
123
+ */
112
124
  } | {
113
125
  type: import("@metamask/snaps-sdk").NodeType.Spinner;
114
126
  } | {
@@ -1 +1 @@
1
- {"version":3,"file":"createInterface.d.cts","sourceRoot":"","sources":["../../src/permitted/createInterface.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,sBAAsB,EAAE,wCAAwC;AAE9E,OAAO,KAAK,EACV,qBAAqB,EACrB,qBAAqB,EAErB,kBAAkB,EAClB,gBAAgB,EAChB,WAAW,EACZ,4BAA4B;AAK7B,OAAO,EAAE,KAAK,aAAa,EAAE,8BAA8B;AAU3D,MAAM,MAAM,0BAA0B,GAAG;IACvC;;;OAGG;IACH,eAAe,EAAE,CACf,EAAE,EAAE,kBAAkB,EACtB,OAAO,CAAC,EAAE,gBAAgB,EAC1B,WAAW,CAAC,EAAE,WAAW,KACtB,OAAO,CAAC,MAAM,CAAC,CAAC;CACtB,CAAC;AAEF,eAAO,MAAM,sBAAsB,EAAE,sBAAsB,CACzD,0BAA0B,EAC1B,yBAAyB,EACzB,qBAAqB,CAKtB,CAAC;AAEF,QAAA,MAAM,+BAA+B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAGnC,CAAC;AAEH,MAAM,MAAM,yBAAyB,GAAG,aAAa,CACnD,OAAO,+BAA+B,EACtC,qBAAqB,CACtB,CAAC"}
1
+ {"version":3,"file":"createInterface.d.cts","sourceRoot":"","sources":["../../src/permitted/createInterface.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,sBAAsB,EAAE,wCAAwC;AAE9E,OAAO,KAAK,EACV,qBAAqB,EACrB,qBAAqB,EAErB,kBAAkB,EAClB,gBAAgB,EAChB,WAAW,EACZ,4BAA4B;AAK7B,OAAO,EAAE,KAAK,aAAa,EAAE,8BAA8B;AAU3D,MAAM,MAAM,0BAA0B,GAAG;IACvC;;;OAGG;IACH,eAAe,EAAE,CACf,EAAE,EAAE,kBAAkB,EACtB,OAAO,CAAC,EAAE,gBAAgB,EAC1B,WAAW,CAAC,EAAE,WAAW,KACtB,MAAM,CAAC;CACb,CAAC;AAEF,eAAO,MAAM,sBAAsB,EAAE,sBAAsB,CACzD,0BAA0B,EAC1B,yBAAyB,EACzB,qBAAqB,CAKtB,CAAC;AAEF,QAAA,MAAM,+BAA+B;;;;;;;;;;;;4DA4CrC;;;;;;WAMG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;4DANH;;;;;;WAMG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EA/CD,CAAC;AAEH,MAAM,MAAM,yBAAyB,GAAG,aAAa,CACnD,OAAO,+BAA+B,EACtC,qBAAqB,CACtB,CAAC"}
@@ -6,7 +6,7 @@ export type CreateInterfaceMethodHooks = {
6
6
  * @param ui - The UI components.
7
7
  * @returns The unique identifier of the interface.
8
8
  */
9
- createInterface: (ui: ComponentOrElement, context?: InterfaceContext, contentType?: ContentType) => Promise<string>;
9
+ createInterface: (ui: ComponentOrElement, context?: InterfaceContext, contentType?: ContentType) => string;
10
10
  };
11
11
  export declare const createInterfaceHandler: PermittedHandlerExport<CreateInterfaceMethodHooks, CreateInterfaceParameters, CreateInterfaceResult>;
12
12
  declare const CreateInterfaceParametersStruct: import("@metamask/superstruct").Struct<{
@@ -21,7 +21,13 @@ declare const CreateInterfaceParametersStruct: import("@metamask/superstruct").S
21
21
  type: import("@metamask/snaps-sdk").NodeType.Heading;
22
22
  } | {
23
23
  value: string;
24
- type: import("@metamask/snaps-sdk").NodeType.Image;
24
+ type: import("@metamask/snaps-sdk").NodeType.Image; /**
25
+ * Validate the createInterface method `params` and returns them cast to the correct
26
+ * type. Throws if validation fails.
27
+ *
28
+ * @param params - The unvalidated params object from the method request.
29
+ * @returns The validated createInterface method parameter object.
30
+ */
25
31
  } | {
26
32
  type: import("@metamask/snaps-sdk").NodeType.Spinner;
27
33
  } | {
@@ -108,7 +114,13 @@ declare const CreateInterfaceParametersStruct: import("@metamask/superstruct").S
108
114
  type: import("@metamask/snaps-sdk").NodeType.Heading;
109
115
  } | {
110
116
  value: string;
111
- type: import("@metamask/snaps-sdk").NodeType.Image;
117
+ type: import("@metamask/snaps-sdk").NodeType.Image; /**
118
+ * Validate the createInterface method `params` and returns them cast to the correct
119
+ * type. Throws if validation fails.
120
+ *
121
+ * @param params - The unvalidated params object from the method request.
122
+ * @returns The validated createInterface method parameter object.
123
+ */
112
124
  } | {
113
125
  type: import("@metamask/snaps-sdk").NodeType.Spinner;
114
126
  } | {
@@ -1 +1 @@
1
- {"version":3,"file":"createInterface.d.mts","sourceRoot":"","sources":["../../src/permitted/createInterface.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,sBAAsB,EAAE,wCAAwC;AAE9E,OAAO,KAAK,EACV,qBAAqB,EACrB,qBAAqB,EAErB,kBAAkB,EAClB,gBAAgB,EAChB,WAAW,EACZ,4BAA4B;AAK7B,OAAO,EAAE,KAAK,aAAa,EAAE,8BAA8B;AAU3D,MAAM,MAAM,0BAA0B,GAAG;IACvC;;;OAGG;IACH,eAAe,EAAE,CACf,EAAE,EAAE,kBAAkB,EACtB,OAAO,CAAC,EAAE,gBAAgB,EAC1B,WAAW,CAAC,EAAE,WAAW,KACtB,OAAO,CAAC,MAAM,CAAC,CAAC;CACtB,CAAC;AAEF,eAAO,MAAM,sBAAsB,EAAE,sBAAsB,CACzD,0BAA0B,EAC1B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AAyB,GAAG,aAAa,CACnD,OAAO,+BAA+B,EACtC,qBAAqB,CACtB,CAAC"}
@@ -25,12 +25,12 @@ const CreateInterfaceParametersStruct = object({
25
25
  * @param hooks.createInterface - The function to create the interface.
26
26
  * @returns Nothing.
27
27
  */
28
- async function getCreateInterfaceImplementation(req, res, _next, end, { createInterface }) {
28
+ function getCreateInterfaceImplementation(req, res, _next, end, { createInterface }) {
29
29
  const { params } = req;
30
30
  try {
31
31
  const validatedParams = getValidatedParams(params);
32
32
  const { ui, context } = validatedParams;
33
- res.result = await createInterface(ui, context);
33
+ res.result = createInterface(ui, context);
34
34
  }
35
35
  catch (error) {
36
36
  return end(error);
@@ -1 +1 @@
1
- {"version":3,"file":"createInterface.mjs","sourceRoot":"","sources":["../../src/permitted/createInterface.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,SAAS,EAAE,6BAA6B;AASjD,OAAO,EACL,wBAAwB,EACxB,sBAAsB,EACvB,4BAA4B;AAE7B,OAAO,EAAE,WAAW,EAAE,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,8BAA8B;AAK9E,MAAM,SAAS,GAAkD;IAC/D,eAAe,EAAE,IAAI;CACtB,CAAC;AAcF,MAAM,CAAC,MAAM,sBAAsB,GAI/B;IACF,WAAW,EAAE,CAAC,sBAAsB,CAAC;IACrC,cAAc,EAAE,gCAAgC;IAChD,SAAS;CACV,CAAC;AAEF,MAAM,+BAA+B,GAAG,MAAM,CAAC;IAC7C,EAAE,EAAE,wBAAwB;IAC5B,OAAO,EAAE,QAAQ,CAAC,sBAAsB,CAAC;CAC1C,CAAC,CAAC;AAOH;;;;;;;;;;;GAWG;AACH,KAAK,UAAU,gCAAgC,CAC7C,GAA8C,EAC9C,GAAkD,EAClD,KAAc,EACd,GAA6B,EAC7B,EAAE,eAAe,EAA8B;IAE/C,MAAM,EAAE,MAAM,EAAE,GAAG,GAAG,CAAC;IAEvB,IAAI,CAAC;QACH,MAAM,eAAe,GAAG,kBAAkB,CAAC,MAAM,CAAC,CAAC;QAEnD,MAAM,EAAE,EAAE,EAAE,OAAO,EAAE,GAAG,eAAe,CAAC;QAExC,GAAG,CAAC,MAAM,GAAG,MAAM,eAAe,CAAC,EAAE,EAAE,OAAO,CAAC,CAAC;IAClD,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,OAAO,GAAG,CAAC,KAAK,CAAC,CAAC;IACpB,CAAC;IAED,OAAO,GAAG,EAAE,CAAC;AACf,CAAC;AAED;;;;;;GAMG;AACH,SAAS,kBAAkB,CAAC,MAAe;IACzC,IAAI,CAAC;QACH,OAAO,MAAM,CAAC,MAAM,EAAE,+BAA+B,CAAC,CAAC;IACzD,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,IAAI,KAAK,YAAY,WAAW,EAAE,CAAC;YACjC,MAAM,SAAS,CAAC,aAAa,CAAC;gBAC5B,OAAO,EAAE,mBAAmB,KAAK,CAAC,OAAO,GAAG;aAC7C,CAAC,CAAC;QACL,CAAC;QACD,0BAA0B;QAC1B,MAAM,SAAS,CAAC,QAAQ,EAAE,CAAC;IAC7B,CAAC;AACH,CAAC","sourcesContent":["import type { JsonRpcEngineEndCallback } from '@metamask/json-rpc-engine';\nimport type { PermittedHandlerExport } from '@metamask/permission-controller';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport type {\n CreateInterfaceParams,\n CreateInterfaceResult,\n JsonRpcRequest,\n ComponentOrElement,\n InterfaceContext,\n ContentType,\n} from '@metamask/snaps-sdk';\nimport {\n ComponentOrElementStruct,\n InterfaceContextStruct,\n} from '@metamask/snaps-sdk';\nimport { type InferMatching } from '@metamask/snaps-utils';\nimport { StructError, create, object, optional } from '@metamask/superstruct';\nimport type { PendingJsonRpcResponse } from '@metamask/utils';\n\nimport type { MethodHooksObject } from '../utils';\n\nconst hookNames: MethodHooksObject<CreateInterfaceMethodHooks> = {\n createInterface: true,\n};\n\nexport type CreateInterfaceMethodHooks = {\n /**\n * @param ui - The UI components.\n * @returns The unique identifier of the interface.\n */\n createInterface: (\n ui: ComponentOrElement,\n context?: InterfaceContext,\n contentType?: ContentType,\n ) => Promise<string>;\n};\n\nexport const createInterfaceHandler: PermittedHandlerExport<\n CreateInterfaceMethodHooks,\n CreateInterfaceParameters,\n CreateInterfaceResult\n> = {\n methodNames: ['snap_createInterface'],\n implementation: getCreateInterfaceImplementation,\n hookNames,\n};\n\nconst CreateInterfaceParametersStruct = object({\n ui: ComponentOrElementStruct,\n context: optional(InterfaceContextStruct),\n});\n\nexport type CreateInterfaceParameters = InferMatching<\n typeof CreateInterfaceParametersStruct,\n CreateInterfaceParams\n>;\n\n/**\n * The `snap_createInterface` method implementation.\n *\n * @param req - The JSON-RPC request object.\n * @param res - The JSON-RPC response object.\n * @param _next - The `json-rpc-engine` \"next\" callback. Not used by this\n * function.\n * @param end - The `json-rpc-engine` \"end\" callback.\n * @param hooks - The RPC method hooks.\n * @param hooks.createInterface - The function to create the interface.\n * @returns Nothing.\n */\nasync function getCreateInterfaceImplementation(\n req: JsonRpcRequest<CreateInterfaceParameters>,\n res: PendingJsonRpcResponse<CreateInterfaceResult>,\n _next: unknown,\n end: JsonRpcEngineEndCallback,\n { createInterface }: CreateInterfaceMethodHooks,\n): Promise<void> {\n const { params } = req;\n\n try {\n const validatedParams = getValidatedParams(params);\n\n const { ui, context } = validatedParams;\n\n res.result = await createInterface(ui, context);\n } catch (error) {\n return end(error);\n }\n\n return end();\n}\n\n/**\n * Validate the createInterface method `params` and returns them cast to the correct\n * type. Throws if validation fails.\n *\n * @param params - The unvalidated params object from the method request.\n * @returns The validated createInterface method parameter object.\n */\nfunction getValidatedParams(params: unknown): CreateInterfaceParameters {\n try {\n return create(params, CreateInterfaceParametersStruct);\n } catch (error) {\n if (error instanceof StructError) {\n throw rpcErrors.invalidParams({\n message: `Invalid params: ${error.message}.`,\n });\n }\n /* istanbul ignore next */\n throw rpcErrors.internal();\n }\n}\n"]}
1
+ {"version":3,"file":"createInterface.mjs","sourceRoot":"","sources":["../../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AAE,CAAC;YACjC,MAAM,SAAS,CAAC,aAAa,CAAC;gBAC5B,OAAO,EAAE,mBAAmB,KAAK,CAAC,OAAO,GAAG;aAC7C,CAAC,CAAC;QACL,CAAC;QACD,0BAA0B;QAC1B,MAAM,SAAS,CAAC,QAAQ,EAAE,CAAC;IAC7B,CAAC;AACH,CAAC","sourcesContent":["import type { JsonRpcEngineEndCallback } from '@metamask/json-rpc-engine';\nimport type { PermittedHandlerExport } from '@metamask/permission-controller';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport type {\n CreateInterfaceParams,\n CreateInterfaceResult,\n JsonRpcRequest,\n ComponentOrElement,\n InterfaceContext,\n ContentType,\n} from '@metamask/snaps-sdk';\nimport {\n ComponentOrElementStruct,\n InterfaceContextStruct,\n} from '@metamask/snaps-sdk';\nimport { type InferMatching } from '@metamask/snaps-utils';\nimport { StructError, create, object, optional } from '@metamask/superstruct';\nimport type { PendingJsonRpcResponse } from '@metamask/utils';\n\nimport type { MethodHooksObject } from '../utils';\n\nconst hookNames: MethodHooksObject<CreateInterfaceMethodHooks> = {\n createInterface: true,\n};\n\nexport type CreateInterfaceMethodHooks = {\n /**\n * @param ui - The UI components.\n * @returns The unique identifier of the interface.\n */\n createInterface: (\n ui: ComponentOrElement,\n context?: InterfaceContext,\n contentType?: ContentType,\n ) => string;\n};\n\nexport const createInterfaceHandler: PermittedHandlerExport<\n CreateInterfaceMethodHooks,\n CreateInterfaceParameters,\n CreateInterfaceResult\n> = {\n methodNames: ['snap_createInterface'],\n implementation: getCreateInterfaceImplementation,\n hookNames,\n};\n\nconst CreateInterfaceParametersStruct = object({\n ui: ComponentOrElementStruct,\n context: optional(InterfaceContextStruct),\n});\n\nexport type CreateInterfaceParameters = InferMatching<\n typeof CreateInterfaceParametersStruct,\n CreateInterfaceParams\n>;\n\n/**\n * The `snap_createInterface` method implementation.\n *\n * @param req - The JSON-RPC request object.\n * @param res - The JSON-RPC response object.\n * @param _next - The `json-rpc-engine` \"next\" callback. Not used by this\n * function.\n * @param end - The `json-rpc-engine` \"end\" callback.\n * @param hooks - The RPC method hooks.\n * @param hooks.createInterface - The function to create the interface.\n * @returns Nothing.\n */\nfunction getCreateInterfaceImplementation(\n req: JsonRpcRequest<CreateInterfaceParameters>,\n res: PendingJsonRpcResponse<CreateInterfaceResult>,\n _next: unknown,\n end: JsonRpcEngineEndCallback,\n { createInterface }: CreateInterfaceMethodHooks,\n): void {\n const { params } = req;\n\n try {\n const validatedParams = getValidatedParams(params);\n\n const { ui, context } = validatedParams;\n\n res.result = createInterface(ui, context);\n } catch (error) {\n return end(error);\n }\n\n return end();\n}\n\n/**\n * Validate the createInterface method `params` and returns them cast to the correct\n * type. Throws if validation fails.\n *\n * @param params - The unvalidated params object from the method request.\n * @returns The validated createInterface method parameter object.\n */\nfunction getValidatedParams(params: unknown): CreateInterfaceParameters {\n try {\n return create(params, CreateInterfaceParametersStruct);\n } catch (error) {\n if (error instanceof StructError) {\n throw rpcErrors.invalidParams({\n message: `Invalid params: ${error.message}.`,\n });\n }\n /* istanbul ignore next */\n throw rpcErrors.internal();\n }\n}\n"]}
@@ -59,8 +59,10 @@ res, _next, end, { handleSnapRpcRequest, hasPermission, getSnap, getAllowedKeyri
59
59
  }));
60
60
  }
61
61
  if (!getSnap(snapId)) {
62
- return end(rpc_errors_1.rpcErrors.invalidRequest({
63
- message: `The snap "${snapId}" is not installed. Please install it first, before invoking the snap.`,
62
+ return end(
63
+ // Mirror error message from SnapController.
64
+ rpc_errors_1.rpcErrors.invalidRequest({
65
+ message: `The Snap "${snapId}" is not installed. Please install it before invoking it.`,
64
66
  }));
65
67
  }
66
68
  if (!(0, utils_1.hasProperty)(request, 'method') || typeof request.method !== 'string') {
@@ -1 +1 @@
1
- {"version":3,"file":"invokeKeyring.cjs","sourceRoot":"","sources":["../../src/permitted/invokeKeyring.ts"],"names":[],"mappings":";;;AAEA,qDAAiD;AAOjD,uDAAgF;AAMhF,2CAA8C;AAE9C,2DAAuD;AAGvD,MAAM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AI,CAAC,IAAA,mBAAW,EAAC,OAAO,EAAE,QAAQ,CAAC,IAAI,OAAO,OAAO,CAAC,MAAM,KAAK,QAAQ,EAAE,CAAC;QAC1E,OAAO,GAAG,CACR,sBAAS,CAAC,cAAc,CAAC;YACvB,OAAO,EAAE,iCAAiC;SAC3C,CAAC,CACH,CAAC;IACJ,CAAC;IAED,MAAM,cAAc,GAAG,wBAAwB,EAAE,CAAC;IAClD,IAAI,CAAC,cAAc,CAAC,QAAQ,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE,CAAC;QAC7C,OAAO,GAAG,CACR,sBAAS,CAAC,cAAc,CAAC;YACvB,OAAO,EAAE,eAAe,MAAM,0CAA0C,OAAO,CAAC,MAAM,IAAI;SAC3F,CAAC,CACH,CAAC;IACJ,CAAC;IAED,IAAI,CAAC;QACH,GAAG,CAAC,MAAM,GAAG,CAAC,MAAM,oBAAoB,CAAC;YACvC,MAAM;YACN,OAAO;YACP,OAAO,EAAE,yBAAW,CAAC,gBAAgB;SACtC,CAAC,CAAS,CAAC;IACd,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,OAAO,GAAG,CAAC,KAAK,CAAC,CAAC;IACpB,CAAC;IAED,OAAO,GAAG,EAAE,CAAC;AACf,CAAC","sourcesContent":["import type { JsonRpcEngineEndCallback } from '@metamask/json-rpc-engine';\nimport type { PermittedHandlerExport } from '@metamask/permission-controller';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport type {\n InvokeKeyringParams,\n InvokeKeyringResult,\n InvokeSnapParams,\n} from '@metamask/snaps-sdk';\nimport type { Snap, SnapRpcHookArgs } from '@metamask/snaps-utils';\nimport { HandlerType, WALLET_SNAP_PERMISSION_KEY } from '@metamask/snaps-utils';\nimport type {\n PendingJsonRpcResponse,\n Json,\n JsonRpcRequest,\n} from '@metamask/utils';\nimport { hasProperty } from '@metamask/utils';\n\nimport { getValidatedParams } from './invokeSnapSugar';\nimport type { MethodHooksObject } from '../utils';\n\nconst hookNames: MethodHooksObject<InvokeKeyringHooks> = {\n hasPermission: true,\n handleSnapRpcRequest: true,\n getSnap: true,\n getAllowedKeyringMethods: true,\n};\n\n/**\n * `wallet_invokeKeyring` gets the requester's permitted and installed Snaps.\n */\nexport const invokeKeyringHandler: PermittedHandlerExport<\n InvokeKeyringHooks,\n InvokeSnapParams,\n InvokeKeyringResult\n> = {\n methodNames: ['wallet_invokeKeyring'],\n implementation: invokeKeyringImplementation,\n hookNames,\n};\n\nexport type InvokeKeyringHooks = {\n hasPermission: (permissionName: string) => boolean;\n\n handleSnapRpcRequest: ({\n snapId,\n handler,\n request,\n }: Omit<SnapRpcHookArgs, 'origin'> & { snapId: string }) => Promise<unknown>;\n\n getSnap: (snapId: string) => Snap | undefined;\n\n getAllowedKeyringMethods: () => string[];\n};\n\n/**\n * The `wallet_invokeKeyring` method implementation.\n * Invokes onKeyringRequest if the snap requested is installed and connected to the dapp.\n *\n * @param req - The JSON-RPC request object.\n * @param res - The JSON-RPC response object.\n * @param _next - The `json-rpc-engine` \"next\" callback. Not used by this\n * function.\n * @param end - The `json-rpc-engine` \"end\" callback.\n * @param hooks - The RPC method hooks.\n * @param hooks.handleSnapRpcRequest - Invokes a snap with a given RPC request.\n * @param hooks.hasPermission - Checks whether a given origin has a given permission.\n * @param hooks.getSnap - Gets information about a given snap.\n * @param hooks.getAllowedKeyringMethods - Get the list of allowed Keyring\n * methods for a given origin.\n * @returns Nothing.\n */\nasync function invokeKeyringImplementation(\n req: JsonRpcRequest<InvokeKeyringParams>,\n // `InvokeKeyringResult` is an alias for `Json` (which is the default type\n // argument for `PendingJsonRpcResponse`), but that may not be the case in the\n // future. We use `InvokeKeyringResult` here to make it clear that this is the\n // expected type of the result.\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-arguments\n res: PendingJsonRpcResponse<InvokeKeyringResult>,\n _next: unknown,\n end: JsonRpcEngineEndCallback,\n {\n handleSnapRpcRequest,\n hasPermission,\n getSnap,\n getAllowedKeyringMethods,\n }: InvokeKeyringHooks,\n): Promise<void> {\n let params: InvokeSnapParams;\n try {\n params = getValidatedParams(req.params);\n } catch (error) {\n return end(error);\n }\n\n // We expect the MM middleware stack to always add the origin to requests\n const { origin } = req as JsonRpcRequest & { origin: string };\n const { snapId, request } = params;\n\n if (!origin || !hasPermission(WALLET_SNAP_PERMISSION_KEY)) {\n return end(\n rpcErrors.invalidRequest({\n message: `The snap \"${snapId}\" is not connected to \"${origin}\". Please connect before invoking the snap.`,\n }),\n );\n }\n\n if (!getSnap(snapId)) {\n return end(\n rpcErrors.invalidRequest({\n message: `The snap \"${snapId}\" is not installed. Please install it first, before invoking the snap.`,\n }),\n );\n }\n\n if (!hasProperty(request, 'method') || typeof request.method !== 'string') {\n return end(\n rpcErrors.invalidRequest({\n message: 'The request must have a method.',\n }),\n );\n }\n\n const allowedMethods = getAllowedKeyringMethods();\n if (!allowedMethods.includes(request.method)) {\n return end(\n rpcErrors.invalidRequest({\n message: `The origin \"${origin}\" is not allowed to invoke the method \"${request.method}\".`,\n }),\n );\n }\n\n try {\n res.result = (await handleSnapRpcRequest({\n snapId,\n request,\n handler: HandlerType.OnKeyringRequest,\n })) as Json;\n } catch (error) {\n return end(error);\n }\n\n return end();\n}\n"]}
1
+ {"version":3,"file":"invokeKeyring.cjs","sourceRoot":"","sources":["../../src/permitted/invokeKeyring.ts"],"names":[],"mappings":";;;AAEA,qDAAiD;AAOjD,uDAAgF;AAMhF,2CAA8C;AAE9C,2DAAuD;AAGvD,MAAM,SAAS,GAA0C;IACvD,aAAa,EAAE,IAAI;IACnB,oBAAoB,EAAE,IAAI;IAC1B,OAAO,EAAE,IAAI;IACb,wBAAwB,EAAE,IAAI;CAC/B,CAAC;AAEF;;GAEG;AACU,QAAA,oBAAoB,GAI7B;IACF,WAAW,EAAE,CAAC,sBAAsB,CAAC;IACrC,cAAc,EAAE,2BAA2B;IAC3C,SAAS;CACV,CAAC;AAgBF;;;;;;;;;;;;;;;;GAgBG;AACH,KAAK,UAAU,2B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C,QAAQ,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE,CAAC;QAC7C,OAAO,GAAG,CACR,sBAAS,CAAC,cAAc,CAAC;YACvB,OAAO,EAAE,eAAe,MAAM,0CAA0C,OAAO,CAAC,MAAM,IAAI;SAC3F,CAAC,CACH,CAAC;IACJ,CAAC;IAED,IAAI,CAAC;QACH,GAAG,CAAC,MAAM,GAAG,CAAC,MAAM,oBAAoB,CAAC;YACvC,MAAM;YACN,OAAO;YACP,OAAO,EAAE,yBAAW,CAAC,gBAAgB;SACtC,CAAC,CAAS,CAAC;IACd,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,OAAO,GAAG,CAAC,KAAK,CAAC,CAAC;IACpB,CAAC;IAED,OAAO,GAAG,EAAE,CAAC;AACf,CAAC","sourcesContent":["import type { JsonRpcEngineEndCallback } from '@metamask/json-rpc-engine';\nimport type { PermittedHandlerExport } from '@metamask/permission-controller';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport type {\n InvokeKeyringParams,\n InvokeKeyringResult,\n InvokeSnapParams,\n} from '@metamask/snaps-sdk';\nimport type { Snap, SnapRpcHookArgs } from '@metamask/snaps-utils';\nimport { HandlerType, WALLET_SNAP_PERMISSION_KEY } from '@metamask/snaps-utils';\nimport type {\n PendingJsonRpcResponse,\n Json,\n JsonRpcRequest,\n} from '@metamask/utils';\nimport { hasProperty } from '@metamask/utils';\n\nimport { getValidatedParams } from './invokeSnapSugar';\nimport type { MethodHooksObject } from '../utils';\n\nconst hookNames: MethodHooksObject<InvokeKeyringHooks> = {\n hasPermission: true,\n handleSnapRpcRequest: true,\n getSnap: true,\n getAllowedKeyringMethods: true,\n};\n\n/**\n * `wallet_invokeKeyring` gets the requester's permitted and installed Snaps.\n */\nexport const invokeKeyringHandler: PermittedHandlerExport<\n InvokeKeyringHooks,\n InvokeSnapParams,\n InvokeKeyringResult\n> = {\n methodNames: ['wallet_invokeKeyring'],\n implementation: invokeKeyringImplementation,\n hookNames,\n};\n\nexport type InvokeKeyringHooks = {\n hasPermission: (permissionName: string) => boolean;\n\n handleSnapRpcRequest: ({\n snapId,\n handler,\n request,\n }: Omit<SnapRpcHookArgs, 'origin'> & { snapId: string }) => Promise<unknown>;\n\n getSnap: (snapId: string) => Snap | undefined;\n\n getAllowedKeyringMethods: () => string[];\n};\n\n/**\n * The `wallet_invokeKeyring` method implementation.\n * Invokes onKeyringRequest if the snap requested is installed and connected to the dapp.\n *\n * @param req - The JSON-RPC request object.\n * @param res - The JSON-RPC response object.\n * @param _next - The `json-rpc-engine` \"next\" callback. Not used by this\n * function.\n * @param end - The `json-rpc-engine` \"end\" callback.\n * @param hooks - The RPC method hooks.\n * @param hooks.handleSnapRpcRequest - Invokes a snap with a given RPC request.\n * @param hooks.hasPermission - Checks whether a given origin has a given permission.\n * @param hooks.getSnap - Gets information about a given snap.\n * @param hooks.getAllowedKeyringMethods - Get the list of allowed Keyring\n * methods for a given origin.\n * @returns Nothing.\n */\nasync function invokeKeyringImplementation(\n req: JsonRpcRequest<InvokeKeyringParams>,\n // `InvokeKeyringResult` is an alias for `Json` (which is the default type\n // argument for `PendingJsonRpcResponse`), but that may not be the case in the\n // future. We use `InvokeKeyringResult` here to make it clear that this is the\n // expected type of the result.\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-arguments\n res: PendingJsonRpcResponse<InvokeKeyringResult>,\n _next: unknown,\n end: JsonRpcEngineEndCallback,\n {\n handleSnapRpcRequest,\n hasPermission,\n getSnap,\n getAllowedKeyringMethods,\n }: InvokeKeyringHooks,\n): Promise<void> {\n let params: InvokeSnapParams;\n try {\n params = getValidatedParams(req.params);\n } catch (error) {\n return end(error);\n }\n\n // We expect the MM middleware stack to always add the origin to requests\n const { origin } = req as JsonRpcRequest & { origin: string };\n const { snapId, request } = params;\n\n if (!origin || !hasPermission(WALLET_SNAP_PERMISSION_KEY)) {\n return end(\n rpcErrors.invalidRequest({\n message: `The snap \"${snapId}\" is not connected to \"${origin}\". Please connect before invoking the snap.`,\n }),\n );\n }\n\n if (!getSnap(snapId)) {\n return end(\n // Mirror error message from SnapController.\n rpcErrors.invalidRequest({\n message: `The Snap \"${snapId}\" is not installed. Please install it before invoking it.`,\n }),\n );\n }\n\n if (!hasProperty(request, 'method') || typeof request.method !== 'string') {\n return end(\n rpcErrors.invalidRequest({\n message: 'The request must have a method.',\n }),\n );\n }\n\n const allowedMethods = getAllowedKeyringMethods();\n if (!allowedMethods.includes(request.method)) {\n return end(\n rpcErrors.invalidRequest({\n message: `The origin \"${origin}\" is not allowed to invoke the method \"${request.method}\".`,\n }),\n );\n }\n\n try {\n res.result = (await handleSnapRpcRequest({\n snapId,\n request,\n handler: HandlerType.OnKeyringRequest,\n })) as Json;\n } catch (error) {\n return end(error);\n }\n\n return end();\n}\n"]}
@@ -56,8 +56,10 @@ res, _next, end, { handleSnapRpcRequest, hasPermission, getSnap, getAllowedKeyri
56
56
  }));
57
57
  }
58
58
  if (!getSnap(snapId)) {
59
- return end(rpcErrors.invalidRequest({
60
- message: `The snap "${snapId}" is not installed. Please install it first, before invoking the snap.`,
59
+ return end(
60
+ // Mirror error message from SnapController.
61
+ rpcErrors.invalidRequest({
62
+ message: `The Snap "${snapId}" is not installed. Please install it before invoking it.`,
61
63
  }));
62
64
  }
63
65
  if (!hasProperty(request, 'method') || typeof request.method !== 'string') {
@@ -1 +1 @@
1
- {"version":3,"file":"invokeKeyring.mjs","sourceRoot":"","sources":["../../src/permitted/invokeKeyring.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,SAAS,EAAE,6BAA6B;AAOjD,OAAO,EAAE,WAAW,EAAE,0BAA0B,EAAE,8BAA8B;AAMhF,OAAO,EAAE,WAAW,EAAE,wBAAwB;AAE9C,OAAO,EAAE,kBAAkB,EAAE,8BAA0B;AAGvD,MAAM,SAAS,GAA0C;IACvD,aAAa,EAAE,IAAI;IACnB,oBAAoB,EAAE,IAAI;IAC1B,OAAO,EAAE,IAAI;IACb,wBAAwB,EAAE,IAAI;CAC/B,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G,CACR,SAAS,CAAC,cAAc,CAAC;YACvB,OAAO,EAAE,iCAAiC;SAC3C,CAAC,CACH,CAAC;IACJ,CAAC;IAED,MAAM,cAAc,GAAG,wBAAwB,EAAE,CAAC;IAClD,IAAI,CAAC,cAAc,CAAC,QAAQ,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE,CAAC;QAC7C,OAAO,GAAG,CACR,SAAS,CAAC,cAAc,CAAC;YACvB,OAAO,EAAE,eAAe,MAAM,0CAA0C,OAAO,CAAC,MAAM,IAAI;SAC3F,CAAC,CACH,CAAC;IACJ,CAAC;IAED,IAAI,CAAC;QACH,GAAG,CAAC,MAAM,GAAG,CAAC,MAAM,oBAAoB,CAAC;YACvC,MAAM;YACN,OAAO;YACP,OAAO,EAAE,WAAW,CAAC,gBAAgB;SACtC,CAAC,CAAS,CAAC;IACd,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,OAAO,GAAG,CAAC,KAAK,CAAC,CAAC;IACpB,CAAC;IAED,OAAO,GAAG,EAAE,CAAC;AACf,CAAC","sourcesContent":["import type { JsonRpcEngineEndCallback } from '@metamask/json-rpc-engine';\nimport type { PermittedHandlerExport } from '@metamask/permission-controller';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport type {\n InvokeKeyringParams,\n InvokeKeyringResult,\n InvokeSnapParams,\n} from '@metamask/snaps-sdk';\nimport type { Snap, SnapRpcHookArgs } from '@metamask/snaps-utils';\nimport { HandlerType, WALLET_SNAP_PERMISSION_KEY } from '@metamask/snaps-utils';\nimport type {\n PendingJsonRpcResponse,\n Json,\n JsonRpcRequest,\n} from '@metamask/utils';\nimport { hasProperty } from '@metamask/utils';\n\nimport { getValidatedParams } from './invokeSnapSugar';\nimport type { MethodHooksObject } from '../utils';\n\nconst hookNames: MethodHooksObject<InvokeKeyringHooks> = {\n hasPermission: true,\n handleSnapRpcRequest: true,\n getSnap: true,\n getAllowedKeyringMethods: true,\n};\n\n/**\n * `wallet_invokeKeyring` gets the requester's permitted and installed Snaps.\n */\nexport const invokeKeyringHandler: PermittedHandlerExport<\n InvokeKeyringHooks,\n InvokeSnapParams,\n InvokeKeyringResult\n> = {\n methodNames: ['wallet_invokeKeyring'],\n implementation: invokeKeyringImplementation,\n hookNames,\n};\n\nexport type InvokeKeyringHooks = {\n hasPermission: (permissionName: string) => boolean;\n\n handleSnapRpcRequest: ({\n snapId,\n handler,\n request,\n }: Omit<SnapRpcHookArgs, 'origin'> & { snapId: string }) => Promise<unknown>;\n\n getSnap: (snapId: string) => Snap | undefined;\n\n getAllowedKeyringMethods: () => string[];\n};\n\n/**\n * The `wallet_invokeKeyring` method implementation.\n * Invokes onKeyringRequest if the snap requested is installed and connected to the dapp.\n *\n * @param req - The JSON-RPC request object.\n * @param res - The JSON-RPC response object.\n * @param _next - The `json-rpc-engine` \"next\" callback. Not used by this\n * function.\n * @param end - The `json-rpc-engine` \"end\" callback.\n * @param hooks - The RPC method hooks.\n * @param hooks.handleSnapRpcRequest - Invokes a snap with a given RPC request.\n * @param hooks.hasPermission - Checks whether a given origin has a given permission.\n * @param hooks.getSnap - Gets information about a given snap.\n * @param hooks.getAllowedKeyringMethods - Get the list of allowed Keyring\n * methods for a given origin.\n * @returns Nothing.\n */\nasync function invokeKeyringImplementation(\n req: JsonRpcRequest<InvokeKeyringParams>,\n // `InvokeKeyringResult` is an alias for `Json` (which is the default type\n // argument for `PendingJsonRpcResponse`), but that may not be the case in the\n // future. We use `InvokeKeyringResult` here to make it clear that this is the\n // expected type of the result.\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-arguments\n res: PendingJsonRpcResponse<InvokeKeyringResult>,\n _next: unknown,\n end: JsonRpcEngineEndCallback,\n {\n handleSnapRpcRequest,\n hasPermission,\n getSnap,\n getAllowedKeyringMethods,\n }: InvokeKeyringHooks,\n): Promise<void> {\n let params: InvokeSnapParams;\n try {\n params = getValidatedParams(req.params);\n } catch (error) {\n return end(error);\n }\n\n // We expect the MM middleware stack to always add the origin to requests\n const { origin } = req as JsonRpcRequest & { origin: string };\n const { snapId, request } = params;\n\n if (!origin || !hasPermission(WALLET_SNAP_PERMISSION_KEY)) {\n return end(\n rpcErrors.invalidRequest({\n message: `The snap \"${snapId}\" is not connected to \"${origin}\". Please connect before invoking the snap.`,\n }),\n );\n }\n\n if (!getSnap(snapId)) {\n return end(\n rpcErrors.invalidRequest({\n message: `The snap \"${snapId}\" is not installed. Please install it first, before invoking the snap.`,\n }),\n );\n }\n\n if (!hasProperty(request, 'method') || typeof request.method !== 'string') {\n return end(\n rpcErrors.invalidRequest({\n message: 'The request must have a method.',\n }),\n );\n }\n\n const allowedMethods = getAllowedKeyringMethods();\n if (!allowedMethods.includes(request.method)) {\n return end(\n rpcErrors.invalidRequest({\n message: `The origin \"${origin}\" is not allowed to invoke the method \"${request.method}\".`,\n }),\n );\n }\n\n try {\n res.result = (await handleSnapRpcRequest({\n snapId,\n request,\n handler: HandlerType.OnKeyringRequest,\n })) as Json;\n } catch (error) {\n return end(error);\n }\n\n return end();\n}\n"]}
1
+ {"version":3,"file":"invokeKeyring.mjs","sourceRoot":"","sources":["../../src/permitted/invokeKeyring.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,SAAS,EAAE,6BAA6B;AAOjD,OAAO,EAAE,WAAW,EAAE,0BAA0B,EAAE,8BAA8B;AAMhF,OAAO,EAAE,WAAW,EAAE,wBAAwB;AAE9C,OAAO,EAAE,kBAAkB,EAAE,8BAA0B;AAGvD,MAAM,SAAS,GAA0C;IACvD,aAAa,EAAE,IAAI;IACnB,oBAAoB,EAAE,IAAI;IAC1B,OAAO,EAAE,IAAI;IACb,wBAAwB,EAAE,IAAI;CAC/B,CAAC;AAEF;;GAEG;AACH,MAAM,CAAC,MAAM,oBAAoB,GAI7B;IACF,WAAW,EAAE,CAAC,sBAAsB,CAAC;IACrC,cAAc,EAAE,2BAA2B;IAC3C,SAAS;CACV,CAAC;AAgBF;;;;;;;;;;;;;;;;GAgBG;AACH,KAAK,UAAU,2BAA2B,C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AC,MAAM,CAAC,EAAE,CAAC;QAC7C,OAAO,GAAG,CACR,SAAS,CAAC,cAAc,CAAC;YACvB,OAAO,EAAE,eAAe,MAAM,0CAA0C,OAAO,CAAC,MAAM,IAAI;SAC3F,CAAC,CACH,CAAC;IACJ,CAAC;IAED,IAAI,CAAC;QACH,GAAG,CAAC,MAAM,GAAG,CAAC,MAAM,oBAAoB,CAAC;YACvC,MAAM;YACN,OAAO;YACP,OAAO,EAAE,WAAW,CAAC,gBAAgB;SACtC,CAAC,CAAS,CAAC;IACd,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,OAAO,GAAG,CAAC,KAAK,CAAC,CAAC;IACpB,CAAC;IAED,OAAO,GAAG,EAAE,CAAC;AACf,CAAC","sourcesContent":["import type { JsonRpcEngineEndCallback } from '@metamask/json-rpc-engine';\nimport type { PermittedHandlerExport } from '@metamask/permission-controller';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport type {\n InvokeKeyringParams,\n InvokeKeyringResult,\n InvokeSnapParams,\n} from '@metamask/snaps-sdk';\nimport type { Snap, SnapRpcHookArgs } from '@metamask/snaps-utils';\nimport { HandlerType, WALLET_SNAP_PERMISSION_KEY } from '@metamask/snaps-utils';\nimport type {\n PendingJsonRpcResponse,\n Json,\n JsonRpcRequest,\n} from '@metamask/utils';\nimport { hasProperty } from '@metamask/utils';\n\nimport { getValidatedParams } from './invokeSnapSugar';\nimport type { MethodHooksObject } from '../utils';\n\nconst hookNames: MethodHooksObject<InvokeKeyringHooks> = {\n hasPermission: true,\n handleSnapRpcRequest: true,\n getSnap: true,\n getAllowedKeyringMethods: true,\n};\n\n/**\n * `wallet_invokeKeyring` gets the requester's permitted and installed Snaps.\n */\nexport const invokeKeyringHandler: PermittedHandlerExport<\n InvokeKeyringHooks,\n InvokeSnapParams,\n InvokeKeyringResult\n> = {\n methodNames: ['wallet_invokeKeyring'],\n implementation: invokeKeyringImplementation,\n hookNames,\n};\n\nexport type InvokeKeyringHooks = {\n hasPermission: (permissionName: string) => boolean;\n\n handleSnapRpcRequest: ({\n snapId,\n handler,\n request,\n }: Omit<SnapRpcHookArgs, 'origin'> & { snapId: string }) => Promise<unknown>;\n\n getSnap: (snapId: string) => Snap | undefined;\n\n getAllowedKeyringMethods: () => string[];\n};\n\n/**\n * The `wallet_invokeKeyring` method implementation.\n * Invokes onKeyringRequest if the snap requested is installed and connected to the dapp.\n *\n * @param req - The JSON-RPC request object.\n * @param res - The JSON-RPC response object.\n * @param _next - The `json-rpc-engine` \"next\" callback. Not used by this\n * function.\n * @param end - The `json-rpc-engine` \"end\" callback.\n * @param hooks - The RPC method hooks.\n * @param hooks.handleSnapRpcRequest - Invokes a snap with a given RPC request.\n * @param hooks.hasPermission - Checks whether a given origin has a given permission.\n * @param hooks.getSnap - Gets information about a given snap.\n * @param hooks.getAllowedKeyringMethods - Get the list of allowed Keyring\n * methods for a given origin.\n * @returns Nothing.\n */\nasync function invokeKeyringImplementation(\n req: JsonRpcRequest<InvokeKeyringParams>,\n // `InvokeKeyringResult` is an alias for `Json` (which is the default type\n // argument for `PendingJsonRpcResponse`), but that may not be the case in the\n // future. We use `InvokeKeyringResult` here to make it clear that this is the\n // expected type of the result.\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-arguments\n res: PendingJsonRpcResponse<InvokeKeyringResult>,\n _next: unknown,\n end: JsonRpcEngineEndCallback,\n {\n handleSnapRpcRequest,\n hasPermission,\n getSnap,\n getAllowedKeyringMethods,\n }: InvokeKeyringHooks,\n): Promise<void> {\n let params: InvokeSnapParams;\n try {\n params = getValidatedParams(req.params);\n } catch (error) {\n return end(error);\n }\n\n // We expect the MM middleware stack to always add the origin to requests\n const { origin } = req as JsonRpcRequest & { origin: string };\n const { snapId, request } = params;\n\n if (!origin || !hasPermission(WALLET_SNAP_PERMISSION_KEY)) {\n return end(\n rpcErrors.invalidRequest({\n message: `The snap \"${snapId}\" is not connected to \"${origin}\". Please connect before invoking the snap.`,\n }),\n );\n }\n\n if (!getSnap(snapId)) {\n return end(\n // Mirror error message from SnapController.\n rpcErrors.invalidRequest({\n message: `The Snap \"${snapId}\" is not installed. Please install it before invoking it.`,\n }),\n );\n }\n\n if (!hasProperty(request, 'method') || typeof request.method !== 'string') {\n return end(\n rpcErrors.invalidRequest({\n message: 'The request must have a method.',\n }),\n );\n }\n\n const allowedMethods = getAllowedKeyringMethods();\n if (!allowedMethods.includes(request.method)) {\n return end(\n rpcErrors.invalidRequest({\n message: `The origin \"${origin}\" is not allowed to invoke the method \"${request.method}\".`,\n }),\n );\n }\n\n try {\n res.result = (await handleSnapRpcRequest({\n snapId,\n request,\n handler: HandlerType.OnKeyringRequest,\n })) as Json;\n } catch (error) {\n return end(error);\n }\n\n return end();\n}\n"]}
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.set = exports.setStateHandler = void 0;
4
4
  const rpc_errors_1 = require("@metamask/rpc-errors");
5
+ const snaps_utils_1 = require("@metamask/snaps-utils");
5
6
  const superstruct_1 = require("@metamask/superstruct");
6
7
  const utils_1 = require("@metamask/utils");
7
8
  const manageState_1 = require("../restricted/manageState.cjs");
@@ -11,6 +12,7 @@ const hookNames = {
11
12
  getSnapState: true,
12
13
  getUnlockPromise: true,
13
14
  updateSnapState: true,
15
+ getSnap: true,
14
16
  };
15
17
  /**
16
18
  * `snap_setState` sets the state of the Snap.
@@ -39,9 +41,10 @@ const SetStateParametersStruct = (0, superstruct_1.object)({
39
41
  * @param hooks.getSnapState - Get the state of the requesting Snap.
40
42
  * @param hooks.getUnlockPromise - Wait for the extension to be unlocked.
41
43
  * @param hooks.updateSnapState - Update the state of the requesting Snap.
44
+ * @param hooks.getSnap - The hook function to get Snap metadata.
42
45
  * @returns Nothing.
43
46
  */
44
- async function setStateImplementation(request, response, _next, end, { hasPermission, getSnapState, getUnlockPromise, updateSnapState, }) {
47
+ async function setStateImplementation(request, response, _next, end, { hasPermission, getSnapState, getUnlockPromise, updateSnapState, getSnap, }) {
45
48
  const { params } = request;
46
49
  if (!hasPermission(manageState_1.manageStateBuilder.targetName)) {
47
50
  return end(rpc_errors_1.providerErrors.unauthorized());
@@ -56,11 +59,15 @@ async function setStateImplementation(request, response, _next, end, { hasPermis
56
59
  await getUnlockPromise(true);
57
60
  }
58
61
  const newState = await getNewState(key, value, encrypted, getSnapState);
59
- const size = (0, utils_1.getJsonSize)(newState);
60
- if (size > manageState_1.STORAGE_SIZE_LIMIT) {
61
- throw rpc_errors_1.rpcErrors.invalidParams({
62
- message: `Invalid params: The new state must not exceed ${manageState_1.STORAGE_SIZE_LIMIT / 1000000} MB in size.`,
63
- });
62
+ const snap = getSnap(request.origin);
63
+ if (!snap?.preinstalled) {
64
+ // We know that the state is valid JSON as per previous validation.
65
+ const size = (0, snaps_utils_1.getJsonSizeUnsafe)(newState, true);
66
+ if (size > manageState_1.STORAGE_SIZE_LIMIT) {
67
+ throw rpc_errors_1.rpcErrors.invalidParams({
68
+ message: `Invalid params: The new state must not exceed ${manageState_1.STORAGE_SIZE_LIMIT / 1000000} MB in size.`,
69
+ });
70
+ }
64
71
  }
65
72
  await updateSnapState(newState, encrypted);
66
73
  response.result = null;
@@ -1 +1 @@
1
- {"version":3,"file":"setState.cjs","sourceRoot":"","sources":["../../src/permitted/setState.ts"],"names":[],"mappings":";;;AAEA,qDAAiE;AAIjE,uDAM+B;AAM/B,2CAMyB;AAEzB,+DAGmC;AAEnC,wCAA0D;AAE1D,MAAM,SAAS,GAAqC;IAClD,aAAa,EAAE,IAAI;IACnB,YAAY,EAAE,IAAI;IAClB,gBAAgB,EAAE,IAAI;IACtB,eAAe,EAAE,IAAI;CACtB,CAAC;AAEF;;GAEG;AACU,QAAA,eAAe,GAIxB;IACF,WAAW,EAAE,CAAC,eAAe,CAAC;IAC9B,cAAc,EAAE,sBAAsB;IACtC,SAAS;CACV,CAAC;AAsCF,MAAM,wBAAwB,GAAG,IAAA,oBAAY,EAAC;IAC5C,GAAG,EAAE,IAAA,sBAAQ,EAA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AI,aAAa,GAAyB,cAAc,CAAC;IAEzD,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;QACrC,MAAM,UAAU,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC;QAC3B,IAAI,sBAAc,CAAC,QAAQ,CAAC,UAAU,CAAC,EAAE,CAAC;YACxC,MAAM,sBAAS,CAAC,aAAa,CAC3B,oDAAoD,CACrD,CAAC;QACJ,CAAC;QAED,IAAI,CAAC,KAAK,IAAI,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YAC1B,aAAa,CAAC,UAAU,CAAC,GAAG,KAAK,CAAC;YAClC,OAAO,cAAc,CAAC;QACxB,CAAC;QAED,IACE,CAAC,IAAA,mBAAW,EAAC,aAAa,EAAE,UAAU,CAAC;YACvC,aAAa,CAAC,UAAU,CAAC,KAAK,IAAI,EAClC,CAAC;YACD,aAAa,CAAC,UAAU,CAAC,GAAG,EAAE,CAAC;QACjC,CAAC;aAAM,IAAI,CAAC,IAAA,gBAAQ,EAAC,aAAa,CAAC,UAAU,CAAC,CAAC,EAAE,CAAC;YAChD,MAAM,sBAAS,CAAC,aAAa,CAC3B,oDAAoD,CACrD,CAAC;QACJ,CAAC;QAED,aAAa,GAAG,aAAa,CAAC,UAAU,CAAyB,CAAC;IACpE,CAAC;IAED,gCAAgC;IAChC,0BAA0B;IAC1B,MAAM,IAAI,KAAK,CAAC,2CAA2C,CAAC,CAAC;AAC/D,CAAC;AAvCD,kBAuCC","sourcesContent":["import type { JsonRpcEngineEndCallback } from '@metamask/json-rpc-engine';\nimport type { PermittedHandlerExport } from '@metamask/permission-controller';\nimport { providerErrors, rpcErrors } from '@metamask/rpc-errors';\nimport type { SetStateParams, SetStateResult } from '@metamask/snaps-sdk';\nimport type { JsonObject } from '@metamask/snaps-sdk/jsx';\nimport { type InferMatching } from '@metamask/snaps-utils';\nimport {\n boolean,\n create,\n object as objectStruct,\n optional,\n StructError,\n} from '@metamask/superstruct';\nimport type {\n PendingJsonRpcResponse,\n Json,\n JsonRpcRequest,\n} from '@metamask/utils';\nimport {\n getJsonSize,\n hasProperty,\n isObject,\n assert,\n JsonStruct,\n} from '@metamask/utils';\n\nimport {\n manageStateBuilder,\n STORAGE_SIZE_LIMIT,\n} from '../restricted/manageState';\nimport type { MethodHooksObject } from '../utils';\nimport { FORBIDDEN_KEYS, StateKeyStruct } from '../utils';\n\nconst hookNames: MethodHooksObject<SetStateHooks> = {\n hasPermission: true,\n getSnapState: true,\n getUnlockPromise: true,\n updateSnapState: true,\n};\n\n/**\n * `snap_setState` sets the state of the Snap.\n */\nexport const setStateHandler: PermittedHandlerExport<\n SetStateHooks,\n SetStateParameters,\n SetStateResult\n> = {\n methodNames: ['snap_setState'],\n implementation: setStateImplementation,\n hookNames,\n};\n\nexport type SetStateHooks = {\n /**\n * Check if 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 * Get the state of the requesting Snap.\n *\n * @param encrypted - Whether the state is encrypted.\n * @returns The current state of the Snap.\n */\n getSnapState: (encrypted: boolean) => Promise<Record<string, Json>>;\n\n /**\n * Wait for the extension to be unlocked.\n *\n * @returns A promise that resolves once the extension is unlocked.\n */\n getUnlockPromise: (shouldShowUnlockRequest: boolean) => Promise<void>;\n\n /**\n * Update the state of the requesting Snap.\n *\n * @param newState - The new state of the Snap.\n * @param encrypted - Whether the state should be encrypted.\n */\n updateSnapState: (\n newState: Record<string, Json>,\n encrypted: boolean,\n ) => Promise<void>;\n};\n\nconst SetStateParametersStruct = objectStruct({\n key: optional(StateKeyStruct),\n value: JsonStruct,\n encrypted: optional(boolean()),\n});\n\nexport type SetStateParameters = InferMatching<\n typeof SetStateParametersStruct,\n SetStateParams\n>;\n\n/**\n * The `snap_setState` method implementation.\n *\n * @param request - The JSON-RPC request object.\n * @param response - The JSON-RPC response object.\n * @param _next - The `json-rpc-engine` \"next\" callback. Not used by this\n * function.\n * @param end - The `json-rpc-engine` \"end\" callback.\n * @param hooks - The RPC method hooks.\n * @param hooks.hasPermission - Check whether a given origin has a given\n * permission.\n * @param hooks.getSnapState - Get the state of the requesting Snap.\n * @param hooks.getUnlockPromise - Wait for the extension to be unlocked.\n * @param hooks.updateSnapState - Update the state of the requesting Snap.\n * @returns Nothing.\n */\nasync function setStateImplementation(\n request: JsonRpcRequest<SetStateParameters>,\n response: PendingJsonRpcResponse<SetStateResult>,\n _next: unknown,\n end: JsonRpcEngineEndCallback,\n {\n hasPermission,\n getSnapState,\n getUnlockPromise,\n updateSnapState,\n }: SetStateHooks,\n): Promise<void> {\n const { params } = request;\n\n if (!hasPermission(manageStateBuilder.targetName)) {\n return end(providerErrors.unauthorized());\n }\n\n try {\n const validatedParams = getValidatedParams(params);\n const { key, value, encrypted = true } = validatedParams;\n\n if (key === undefined && !isObject(value)) {\n return end(\n rpcErrors.invalidParams(\n 'Invalid params: Value must be an object if key is not provided.',\n ),\n );\n }\n\n if (encrypted) {\n await getUnlockPromise(true);\n }\n\n const newState = await getNewState(key, value, encrypted, getSnapState);\n\n const size = getJsonSize(newState);\n if (size > STORAGE_SIZE_LIMIT) {\n throw rpcErrors.invalidParams({\n message: `Invalid params: The new state must not exceed ${\n STORAGE_SIZE_LIMIT / 1_000_000\n } MB in size.`,\n });\n }\n\n await updateSnapState(newState, encrypted);\n response.result = null;\n } catch (error) {\n return end(error);\n }\n\n return end();\n}\n\n/**\n * Validate the parameters of the `snap_setState` method.\n *\n * @param params - The parameters to validate.\n * @returns The validated parameters.\n */\nfunction getValidatedParams(params?: unknown) {\n try {\n return create(params, SetStateParametersStruct);\n } catch (error) {\n if (error instanceof StructError) {\n throw rpcErrors.invalidParams({\n message: `Invalid params: ${error.message}.`,\n });\n }\n\n /* istanbul ignore next */\n throw rpcErrors.internal();\n }\n}\n\n/**\n * Get the new state of the Snap.\n *\n * If the key is `undefined`, the value is expected to be an object. In this\n * case, the value is returned as the new state.\n *\n * If the key is not `undefined`, the value is set in the state at the key. If\n * the key does not exist, it is created (and any missing intermediate keys are\n * created as well).\n *\n * @param key - The key to set.\n * @param value - The value to set the key to.\n * @param encrypted - Whether the state is encrypted.\n * @param getSnapState - The `getSnapState` hook.\n * @returns The new state of the Snap.\n */\nasync function getNewState(\n key: string | undefined,\n value: Json,\n encrypted: boolean,\n getSnapState: SetStateHooks['getSnapState'],\n) {\n if (key === undefined) {\n assert(isObject(value));\n return value;\n }\n\n const state = await getSnapState(encrypted);\n return set(state, key, value);\n}\n\n/**\n * Set the value of a key in an object. The key may contain Lodash-style path\n * syntax, e.g., `a.b.c` (with the exception of array syntax). If the key does\n * not exist, it is created (and any missing intermediate keys are created as\n * well).\n *\n * This is a simplified version of Lodash's `set` function, but Lodash doesn't\n * seem to be maintained anymore, so we're using our own implementation.\n *\n * @param object - The object to get the key from.\n * @param key - The key to set.\n * @param value - The value to set the key to.\n * @returns The new object with the key set to the value.\n */\nexport function set(\n object: Record<string, Json> | null,\n key: string,\n value: Json,\n): JsonObject {\n const keys = key.split('.');\n const requiredObject = object ?? {};\n let currentObject: Record<string, Json> = requiredObject;\n\n for (let i = 0; i < keys.length; i++) {\n const currentKey = keys[i];\n if (FORBIDDEN_KEYS.includes(currentKey)) {\n throw rpcErrors.invalidParams(\n 'Invalid params: Key contains forbidden characters.',\n );\n }\n\n if (i === keys.length - 1) {\n currentObject[currentKey] = value;\n return requiredObject;\n }\n\n if (\n !hasProperty(currentObject, currentKey) ||\n currentObject[currentKey] === null\n ) {\n currentObject[currentKey] = {};\n } else if (!isObject(currentObject[currentKey])) {\n throw rpcErrors.invalidParams(\n 'Invalid params: Cannot overwrite non-object value.',\n );\n }\n\n currentObject = currentObject[currentKey] as Record<string, Json>;\n }\n\n // This should never be reached.\n /* istanbul ignore next */\n throw new Error('Unexpected error while setting the state.');\n}\n"]}
1
+ {"version":3,"file":"setState.cjs","sourceRoot":"","sources":["../../src/permitted/set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CAAC;YACD,aAAa,CAAC,UAAU,CAAC,GAAG,EAAE,CAAC;QACjC,CAAC;aAAM,IAAI,CAAC,IAAA,gBAAQ,EAAC,aAAa,CAAC,UAAU,CAAC,CAAC,EAAE,CAAC;YAChD,MAAM,sBAAS,CAAC,aAAa,CAC3B,oDAAoD,CACrD,CAAC;QACJ,CAAC;QAED,aAAa,GAAG,aAAa,CAAC,UAAU,CAAyB,CAAC;IACpE,CAAC;IAED,gCAAgC;IAChC,0BAA0B;IAC1B,MAAM,IAAI,KAAK,CAAC,2CAA2C,CAAC,CAAC;AAC/D,CAAC;AAvCD,kBAuCC","sourcesContent":["import type { JsonRpcEngineEndCallback } from '@metamask/json-rpc-engine';\nimport type { PermittedHandlerExport } from '@metamask/permission-controller';\nimport { providerErrors, rpcErrors } from '@metamask/rpc-errors';\nimport type { SetStateParams, SetStateResult } from '@metamask/snaps-sdk';\nimport type { JsonObject } from '@metamask/snaps-sdk/jsx';\nimport {\n getJsonSizeUnsafe,\n type InferMatching,\n type Snap,\n} from '@metamask/snaps-utils';\nimport {\n boolean,\n create,\n object as objectStruct,\n optional,\n StructError,\n} from '@metamask/superstruct';\nimport type {\n PendingJsonRpcResponse,\n Json,\n JsonRpcRequest,\n} from '@metamask/utils';\nimport { hasProperty, isObject, assert, JsonStruct } from '@metamask/utils';\n\nimport {\n manageStateBuilder,\n STORAGE_SIZE_LIMIT,\n} from '../restricted/manageState';\nimport type { MethodHooksObject } from '../utils';\nimport { FORBIDDEN_KEYS, StateKeyStruct } from '../utils';\n\nconst hookNames: MethodHooksObject<SetStateHooks> = {\n hasPermission: true,\n getSnapState: true,\n getUnlockPromise: true,\n updateSnapState: true,\n getSnap: true,\n};\n\n/**\n * `snap_setState` sets the state of the Snap.\n */\nexport const setStateHandler: PermittedHandlerExport<\n SetStateHooks,\n SetStateParameters,\n SetStateResult\n> = {\n methodNames: ['snap_setState'],\n implementation: setStateImplementation,\n hookNames,\n};\n\nexport type SetStateHooks = {\n /**\n * Check if 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 * Get the state of the requesting Snap.\n *\n * @param encrypted - Whether the state is encrypted.\n * @returns The current state of the Snap.\n */\n getSnapState: (encrypted: boolean) => Promise<Record<string, Json>>;\n\n /**\n * Wait for the extension to be unlocked.\n *\n * @returns A promise that resolves once the extension is unlocked.\n */\n getUnlockPromise: (shouldShowUnlockRequest: boolean) => Promise<void>;\n\n /**\n * Update the state of the requesting Snap.\n *\n * @param newState - The new state of the Snap.\n * @param encrypted - Whether the state should be encrypted.\n */\n updateSnapState: (\n newState: Record<string, Json>,\n encrypted: boolean,\n ) => Promise<void>;\n\n /**\n * Get Snap metadata.\n *\n * @param snapId - The ID of a Snap.\n */\n getSnap: (snapId: string) => Snap | undefined;\n};\n\nconst SetStateParametersStruct = objectStruct({\n key: optional(StateKeyStruct),\n value: JsonStruct,\n encrypted: optional(boolean()),\n});\n\nexport type SetStateParameters = InferMatching<\n typeof SetStateParametersStruct,\n SetStateParams\n>;\n\n/**\n * The `snap_setState` method implementation.\n *\n * @param request - The JSON-RPC request object.\n * @param response - The JSON-RPC response object.\n * @param _next - The `json-rpc-engine` \"next\" callback. Not used by this\n * function.\n * @param end - The `json-rpc-engine` \"end\" callback.\n * @param hooks - The RPC method hooks.\n * @param hooks.hasPermission - Check whether a given origin has a given\n * permission.\n * @param hooks.getSnapState - Get the state of the requesting Snap.\n * @param hooks.getUnlockPromise - Wait for the extension to be unlocked.\n * @param hooks.updateSnapState - Update the state of the requesting Snap.\n * @param hooks.getSnap - The hook function to get Snap metadata.\n * @returns Nothing.\n */\nasync function setStateImplementation(\n request: JsonRpcRequest<SetStateParameters>,\n response: PendingJsonRpcResponse<SetStateResult>,\n _next: unknown,\n end: JsonRpcEngineEndCallback,\n {\n hasPermission,\n getSnapState,\n getUnlockPromise,\n updateSnapState,\n getSnap,\n }: SetStateHooks,\n): Promise<void> {\n const { params } = request;\n\n if (!hasPermission(manageStateBuilder.targetName)) {\n return end(providerErrors.unauthorized());\n }\n\n try {\n const validatedParams = getValidatedParams(params);\n const { key, value, encrypted = true } = validatedParams;\n\n if (key === undefined && !isObject(value)) {\n return end(\n rpcErrors.invalidParams(\n 'Invalid params: Value must be an object if key is not provided.',\n ),\n );\n }\n\n if (encrypted) {\n await getUnlockPromise(true);\n }\n\n const newState = await getNewState(key, value, encrypted, getSnapState);\n\n const snap = getSnap(\n (request as JsonRpcRequest<SetStateParams> & { origin: string }).origin,\n );\n\n if (!snap?.preinstalled) {\n // We know that the state is valid JSON as per previous validation.\n const size = getJsonSizeUnsafe(newState, true);\n if (size > STORAGE_SIZE_LIMIT) {\n throw rpcErrors.invalidParams({\n message: `Invalid params: The new state must not exceed ${\n STORAGE_SIZE_LIMIT / 1_000_000\n } MB in size.`,\n });\n }\n }\n\n await updateSnapState(newState, encrypted);\n response.result = null;\n } catch (error) {\n return end(error);\n }\n\n return end();\n}\n\n/**\n * Validate the parameters of the `snap_setState` method.\n *\n * @param params - The parameters to validate.\n * @returns The validated parameters.\n */\nfunction getValidatedParams(params?: unknown) {\n try {\n return create(params, SetStateParametersStruct);\n } catch (error) {\n if (error instanceof StructError) {\n throw rpcErrors.invalidParams({\n message: `Invalid params: ${error.message}.`,\n });\n }\n\n /* istanbul ignore next */\n throw rpcErrors.internal();\n }\n}\n\n/**\n * Get the new state of the Snap.\n *\n * If the key is `undefined`, the value is expected to be an object. In this\n * case, the value is returned as the new state.\n *\n * If the key is not `undefined`, the value is set in the state at the key. If\n * the key does not exist, it is created (and any missing intermediate keys are\n * created as well).\n *\n * @param key - The key to set.\n * @param value - The value to set the key to.\n * @param encrypted - Whether the state is encrypted.\n * @param getSnapState - The `getSnapState` hook.\n * @returns The new state of the Snap.\n */\nasync function getNewState(\n key: string | undefined,\n value: Json,\n encrypted: boolean,\n getSnapState: SetStateHooks['getSnapState'],\n) {\n if (key === undefined) {\n assert(isObject(value));\n return value;\n }\n\n const state = await getSnapState(encrypted);\n return set(state, key, value);\n}\n\n/**\n * Set the value of a key in an object. The key may contain Lodash-style path\n * syntax, e.g., `a.b.c` (with the exception of array syntax). If the key does\n * not exist, it is created (and any missing intermediate keys are created as\n * well).\n *\n * This is a simplified version of Lodash's `set` function, but Lodash doesn't\n * seem to be maintained anymore, so we're using our own implementation.\n *\n * @param object - The object to get the key from.\n * @param key - The key to set.\n * @param value - The value to set the key to.\n * @returns The new object with the key set to the value.\n */\nexport function set(\n object: Record<string, Json> | null,\n key: string,\n value: Json,\n): JsonObject {\n const keys = key.split('.');\n const requiredObject = object ?? {};\n let currentObject: Record<string, Json> = requiredObject;\n\n for (let i = 0; i < keys.length; i++) {\n const currentKey = keys[i];\n if (FORBIDDEN_KEYS.includes(currentKey)) {\n throw rpcErrors.invalidParams(\n 'Invalid params: Key contains forbidden characters.',\n );\n }\n\n if (i === keys.length - 1) {\n currentObject[currentKey] = value;\n return requiredObject;\n }\n\n if (\n !hasProperty(currentObject, currentKey) ||\n currentObject[currentKey] === null\n ) {\n currentObject[currentKey] = {};\n } else if (!isObject(currentObject[currentKey])) {\n throw rpcErrors.invalidParams(\n 'Invalid params: Cannot overwrite non-object value.',\n );\n }\n\n currentObject = currentObject[currentKey] as Record<string, Json>;\n }\n\n // This should never be reached.\n /* istanbul ignore next */\n throw new Error('Unexpected error while setting the state.');\n}\n"]}
@@ -1,7 +1,7 @@
1
1
  import type { PermittedHandlerExport } from "@metamask/permission-controller";
2
2
  import type { SetStateParams, SetStateResult } from "@metamask/snaps-sdk";
3
3
  import type { JsonObject } from "@metamask/snaps-sdk/jsx";
4
- import { type InferMatching } from "@metamask/snaps-utils";
4
+ import { type InferMatching, type Snap } from "@metamask/snaps-utils";
5
5
  import type { Json } from "@metamask/utils";
6
6
  /**
7
7
  * `snap_setState` sets the state of the Snap.
@@ -35,6 +35,12 @@ export type SetStateHooks = {
35
35
  * @param encrypted - Whether the state should be encrypted.
36
36
  */
37
37
  updateSnapState: (newState: Record<string, Json>, encrypted: boolean) => Promise<void>;
38
+ /**
39
+ * Get Snap metadata.
40
+ *
41
+ * @param snapId - The ID of a Snap.
42
+ */
43
+ getSnap: (snapId: string) => Snap | undefined;
38
44
  };
39
45
  declare const SetStateParametersStruct: import("@metamask/superstruct").Struct<{
40
46
  value: Json;
@@ -1 +1 @@
1
- {"version":3,"file":"setState.d.cts","sourceRoot":"","sources":["../../src/permitted/setState.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,sBAAsB,EAAE,wCAAwC;AAE9E,OAAO,KAAK,EAAE,cAAc,EAAE,cAAc,EAAE,4BAA4B;AAC1E,OAAO,KAAK,EAAE,UAAU,EAAE,gCAAgC;AAC1D,OAAO,EAAE,KAAK,aAAa,EAAE,8BAA8B;AAQ3D,OAAO,KAAK,EAEV,IAAI,EAEL,wBAAwB;AAuBzB;;GAEG;AACH,eAAO,MAAM,eAAe,EAAE,sBAAsB,CAClD,aAAa,EACb,kBAAkB,EAClB,cAAc,CAKf,CAAC;AAEF,MAAM,MAAM,aAAa,GAAG;IAC1B;;;;;OAKG;IACH,aAAa,EAAE,CAAC,cAAc,EAAE,MAAM,KAAK,OAAO,CAAC;IAEnD;;;;;OAKG;IACH,YAAY,EAAE,CAAC,SAAS,EAAE,OAAO,KAAK,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC,CAAC;IAEpE;;;;OAIG;IACH,gBAAgB,EAAE,CAAC,uBAAuB,EAAE,OAAO,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IAEtE;;;;;OAKG;IACH,eAAe,EAAE,CACf,QAAQ,EAAE,MAAM,CAAC,MAAM,EAAE,IAAI,CAAC,EAC9B,SAAS,EAAE,OAAO,KACf,OAAO,CAAC,IAAI,CAAC,CAAC;CACpB,CAAC;AAEF,QAAA,MAAM,wBAAwB;;;;;;;;EAI5B,CAAC;AAEH,MAAM,MAAM,kBAAkB,GAAG,aAAa,CAC5C,OAAO,wBAAwB,EAC/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M,wBAAwB;;;;;;;;EAI5B,CAAC;AAEH,MAAM,MAAM,kBAAkB,GAAG,aAAa,CAC5C,OAAO,wBAAwB,EAC/B,cAAc,CACf,CAAC;AAqIF;;;;;;;;;;;;;GAaG;AACH,wBAAgB,GAAG,CACjB,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,IAAI,CAAC,GAAG,IAAI,EACnC,GAAG,EAAE,MAAM,EACX,KAAK,EAAE,IAAI,GACV,UAAU,CAmCZ"}
@@ -1,7 +1,7 @@
1
1
  import type { PermittedHandlerExport } from "@metamask/permission-controller";
2
2
  import type { SetStateParams, SetStateResult } from "@metamask/snaps-sdk";
3
3
  import type { JsonObject } from "@metamask/snaps-sdk/jsx";
4
- import { type InferMatching } from "@metamask/snaps-utils";
4
+ import { type InferMatching, type Snap } from "@metamask/snaps-utils";
5
5
  import type { Json } from "@metamask/utils";
6
6
  /**
7
7
  * `snap_setState` sets the state of the Snap.
@@ -35,6 +35,12 @@ export type SetStateHooks = {
35
35
  * @param encrypted - Whether the state should be encrypted.
36
36
  */
37
37
  updateSnapState: (newState: Record<string, Json>, encrypted: boolean) => Promise<void>;
38
+ /**
39
+ * Get Snap metadata.
40
+ *
41
+ * @param snapId - The ID of a Snap.
42
+ */
43
+ getSnap: (snapId: string) => Snap | undefined;
38
44
  };
39
45
  declare const SetStateParametersStruct: import("@metamask/superstruct").Struct<{
40
46
  value: Json;
@@ -1 +1 @@
1
- {"version":3,"file":"setState.d.mts","sourceRoot":"","sources":["../../src/permitted/setState.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,sBAAsB,EAAE,wCAAwC;AAE9E,OAAO,KAAK,EAAE,cAAc,EAAE,cAAc,EAAE,4BAA4B;AAC1E,OAAO,KAAK,EAAE,UAAU,EAAE,gCAAgC;AAC1D,OAAO,EAAE,KAAK,aAAa,EAAE,8BAA8B;AAQ3D,OAAO,KAAK,EAEV,IAAI,EAEL,wBAAwB;AAuBzB;;GAEG;AACH,eAAO,MAAM,e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,MAAM,eAAe,EAAE,sBAAsB,CAClD,aAAa,EACb,kBAAkB,EAClB,cAAc,CAKf,CAAC;AAEF,MAAM,MAAM,aAAa,GAAG;IAC1B;;;;;OAKG;IACH,aAAa,EAAE,CAAC,cAAc,EAAE,MAAM,KAAK,OAAO,CAAC;IAEnD;;;;;OAKG;IACH,YAAY,EAAE,CAAC,SAAS,EAAE,OAAO,KAAK,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC,CAAC;IAEpE;;;;OAIG;IACH,gBAAgB,EAAE,CAAC,uBAAuB,EAAE,OAAO,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IAEtE;;;;;OAKG;IACH,eAAe,EAAE,CACf,QAAQ,EAAE,MAAM,CAAC,MAAM,EAAE,IAAI,CAAC,EAC9B,SAAS,EAAE,OAAO,KACf,OAAO,CAAC,IAAI,CAAC,CAAC;IAEnB;;;;OAIG;IACH,OAAO,EAAE,CAAC,MAAM,EAAE,MAAM,KAAK,IAAI,GAAG,SAAS,CAAC;CAC/C,CAAC;AAEF,QAAA,MAAM,wBAAwB;;;;;;;;EAI5B,CAAC;AAEH,MAAM,MAAM,kBAAkB,GAAG,aAAa,CAC5C,OAAO,wBAAwB,EAC/B,cAAc,CACf,CAAC;AAqIF;;;;;;;;;;;;;GAaG;AACH,wBAAgB,GAAG,CACjB,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,IAAI,CAAC,GAAG,IAAI,EACnC,GAAG,EAAE,MAAM,EACX,KAAK,EAAE,IAAI,GACV,UAAU,CAmCZ"}
@@ -1,6 +1,7 @@
1
1
  import { providerErrors, rpcErrors } from "@metamask/rpc-errors";
2
+ import { getJsonSizeUnsafe } from "@metamask/snaps-utils";
2
3
  import { boolean, create, object as objectStruct, optional, StructError } from "@metamask/superstruct";
3
- import { getJsonSize, hasProperty, isObject, assert, JsonStruct } from "@metamask/utils";
4
+ import { hasProperty, isObject, assert, JsonStruct } from "@metamask/utils";
4
5
  import { manageStateBuilder, STORAGE_SIZE_LIMIT } from "../restricted/manageState.mjs";
5
6
  import { FORBIDDEN_KEYS, StateKeyStruct } from "../utils.mjs";
6
7
  const hookNames = {
@@ -8,6 +9,7 @@ const hookNames = {
8
9
  getSnapState: true,
9
10
  getUnlockPromise: true,
10
11
  updateSnapState: true,
12
+ getSnap: true,
11
13
  };
12
14
  /**
13
15
  * `snap_setState` sets the state of the Snap.
@@ -36,9 +38,10 @@ const SetStateParametersStruct = objectStruct({
36
38
  * @param hooks.getSnapState - Get the state of the requesting Snap.
37
39
  * @param hooks.getUnlockPromise - Wait for the extension to be unlocked.
38
40
  * @param hooks.updateSnapState - Update the state of the requesting Snap.
41
+ * @param hooks.getSnap - The hook function to get Snap metadata.
39
42
  * @returns Nothing.
40
43
  */
41
- async function setStateImplementation(request, response, _next, end, { hasPermission, getSnapState, getUnlockPromise, updateSnapState, }) {
44
+ async function setStateImplementation(request, response, _next, end, { hasPermission, getSnapState, getUnlockPromise, updateSnapState, getSnap, }) {
42
45
  const { params } = request;
43
46
  if (!hasPermission(manageStateBuilder.targetName)) {
44
47
  return end(providerErrors.unauthorized());
@@ -53,11 +56,15 @@ async function setStateImplementation(request, response, _next, end, { hasPermis
53
56
  await getUnlockPromise(true);
54
57
  }
55
58
  const newState = await getNewState(key, value, encrypted, getSnapState);
56
- const size = getJsonSize(newState);
57
- if (size > STORAGE_SIZE_LIMIT) {
58
- throw rpcErrors.invalidParams({
59
- message: `Invalid params: The new state must not exceed ${STORAGE_SIZE_LIMIT / 1000000} MB in size.`,
60
- });
59
+ const snap = getSnap(request.origin);
60
+ if (!snap?.preinstalled) {
61
+ // We know that the state is valid JSON as per previous validation.
62
+ const size = getJsonSizeUnsafe(newState, true);
63
+ if (size > STORAGE_SIZE_LIMIT) {
64
+ throw rpcErrors.invalidParams({
65
+ message: `Invalid params: The new state must not exceed ${STORAGE_SIZE_LIMIT / 1000000} MB in size.`,
66
+ });
67
+ }
61
68
  }
62
69
  await updateSnapState(newState, encrypted);
63
70
  response.result = null;
@@ -1 +1 @@
1
- {"version":3,"file":"setState.mjs","sourceRoot":"","sources":["../../src/permitted/setState.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,cAAc,EAAE,SAAS,EAAE,6BAA6B;AAIjE,OAAO,EACL,OAAO,EACP,MAAM,EACN,MAAM,IAAI,YAAY,EACtB,QAAQ,EACR,WAAW,EACZ,8BAA8B;AAM/B,OAAO,EACL,WAAW,EACX,WAAW,EACX,QAAQ,EACR,MAAM,EACN,UAAU,EACX,wBAAwB;AAEzB,OAAO,EACL,kBAAkB,EAClB,kBAAkB,EACnB,sCAAkC;AAEnC,OAAO,EAAE,cAAc,EAAE,cAAc,EAAE,qBAAiB;AAE1D,MAAM,SAAS,GAAqC;IAClD,aAAa,EAAE,IAAI;IACnB,YAAY,EAAE,IAAI;IAClB,gBAAgB,EAAE,IAAI;IACtB,eAAe,EAAE,IAAI;CACtB,CAAC;AAEF;;GAEG;AACH,MAAM,CAAC,MAAM,eAAe,GAIxB;IACF,WAAW,EAAE,CAAC,eAAe,CAAC;IAC9B,cAAc,EAAE,sBAAsB;IACtC,SAAS;CACV,CAAC;AAsCF,MAAM,wBAAwB,GAAG,YAAY,CAAC;IAC5C,GAAG,EAAE,QAAQ,CAAC,cAAc,CAAC;IAC7B,KAAK,EAAE,UAAU;IACjB,SAAS,EAAE,QAAQ,CAAC,OAAO,EAAE,CAAC;CAC/B,CAAC,CAAC;AAOH;;;;;;;;;;;;;;;GAeG;AACH,KAAK,UAAU,sBAAsB,CACnC,OAA2C,EAC3C,QAAgD,EAChD,KAAc,EACd,GAA6B,EAC7B,EACE,aAAa,EACb,YAAY,EACZ,gBAAgB,EAChB,eAAe,GACD;IAEhB,MAAM,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC;IAE3B,IAAI,CAAC,aAAa,CAAC,kBAAkB,CAAC,UAAU,CAAC,EAAE,CAAC;QAClD,OAAO,GAAG,CAAC,cAAc,CAAC,YAAY,EAAE,CAAC,CA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AAE,UAAU,CAAC;YACvC,aAAa,CAAC,UAAU,CAAC,KAAK,IAAI,EAClC,CAAC;YACD,aAAa,CAAC,UAAU,CAAC,GAAG,EAAE,CAAC;QACjC,CAAC;aAAM,IAAI,CAAC,QAAQ,CAAC,aAAa,CAAC,UAAU,CAAC,CAAC,EAAE,CAAC;YAChD,MAAM,SAAS,CAAC,aAAa,CAC3B,oDAAoD,CACrD,CAAC;QACJ,CAAC;QAED,aAAa,GAAG,aAAa,CAAC,UAAU,CAAyB,CAAC;IACpE,CAAC;IAED,gCAAgC;IAChC,0BAA0B;IAC1B,MAAM,IAAI,KAAK,CAAC,2CAA2C,CAAC,CAAC;AAC/D,CAAC","sourcesContent":["import type { JsonRpcEngineEndCallback } from '@metamask/json-rpc-engine';\nimport type { PermittedHandlerExport } from '@metamask/permission-controller';\nimport { providerErrors, rpcErrors } from '@metamask/rpc-errors';\nimport type { SetStateParams, SetStateResult } from '@metamask/snaps-sdk';\nimport type { JsonObject } from '@metamask/snaps-sdk/jsx';\nimport { type InferMatching } from '@metamask/snaps-utils';\nimport {\n boolean,\n create,\n object as objectStruct,\n optional,\n StructError,\n} from '@metamask/superstruct';\nimport type {\n PendingJsonRpcResponse,\n Json,\n JsonRpcRequest,\n} from '@metamask/utils';\nimport {\n getJsonSize,\n hasProperty,\n isObject,\n assert,\n JsonStruct,\n} from '@metamask/utils';\n\nimport {\n manageStateBuilder,\n STORAGE_SIZE_LIMIT,\n} from '../restricted/manageState';\nimport type { MethodHooksObject } from '../utils';\nimport { FORBIDDEN_KEYS, StateKeyStruct } from '../utils';\n\nconst hookNames: MethodHooksObject<SetStateHooks> = {\n hasPermission: true,\n getSnapState: true,\n getUnlockPromise: true,\n updateSnapState: true,\n};\n\n/**\n * `snap_setState` sets the state of the Snap.\n */\nexport const setStateHandler: PermittedHandlerExport<\n SetStateHooks,\n SetStateParameters,\n SetStateResult\n> = {\n methodNames: ['snap_setState'],\n implementation: setStateImplementation,\n hookNames,\n};\n\nexport type SetStateHooks = {\n /**\n * Check if 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 * Get the state of the requesting Snap.\n *\n * @param encrypted - Whether the state is encrypted.\n * @returns The current state of the Snap.\n */\n getSnapState: (encrypted: boolean) => Promise<Record<string, Json>>;\n\n /**\n * Wait for the extension to be unlocked.\n *\n * @returns A promise that resolves once the extension is unlocked.\n */\n getUnlockPromise: (shouldShowUnlockRequest: boolean) => Promise<void>;\n\n /**\n * Update the state of the requesting Snap.\n *\n * @param newState - The new state of the Snap.\n * @param encrypted - Whether the state should be encrypted.\n */\n updateSnapState: (\n newState: Record<string, Json>,\n encrypted: boolean,\n ) => Promise<void>;\n};\n\nconst SetStateParametersStruct = objectStruct({\n key: optional(StateKeyStruct),\n value: JsonStruct,\n encrypted: optional(boolean()),\n});\n\nexport type SetStateParameters = InferMatching<\n typeof SetStateParametersStruct,\n SetStateParams\n>;\n\n/**\n * The `snap_setState` method implementation.\n *\n * @param request - The JSON-RPC request object.\n * @param response - The JSON-RPC response object.\n * @param _next - The `json-rpc-engine` \"next\" callback. Not used by this\n * function.\n * @param end - The `json-rpc-engine` \"end\" callback.\n * @param hooks - The RPC method hooks.\n * @param hooks.hasPermission - Check whether a given origin has a given\n * permission.\n * @param hooks.getSnapState - Get the state of the requesting Snap.\n * @param hooks.getUnlockPromise - Wait for the extension to be unlocked.\n * @param hooks.updateSnapState - Update the state of the requesting Snap.\n * @returns Nothing.\n */\nasync function setStateImplementation(\n request: JsonRpcRequest<SetStateParameters>,\n response: PendingJsonRpcResponse<SetStateResult>,\n _next: unknown,\n end: JsonRpcEngineEndCallback,\n {\n hasPermission,\n getSnapState,\n getUnlockPromise,\n updateSnapState,\n }: SetStateHooks,\n): Promise<void> {\n const { params } = request;\n\n if (!hasPermission(manageStateBuilder.targetName)) {\n return end(providerErrors.unauthorized());\n }\n\n try {\n const validatedParams = getValidatedParams(params);\n const { key, value, encrypted = true } = validatedParams;\n\n if (key === undefined && !isObject(value)) {\n return end(\n rpcErrors.invalidParams(\n 'Invalid params: Value must be an object if key is not provided.',\n ),\n );\n }\n\n if (encrypted) {\n await getUnlockPromise(true);\n }\n\n const newState = await getNewState(key, value, encrypted, getSnapState);\n\n const size = getJsonSize(newState);\n if (size > STORAGE_SIZE_LIMIT) {\n throw rpcErrors.invalidParams({\n message: `Invalid params: The new state must not exceed ${\n STORAGE_SIZE_LIMIT / 1_000_000\n } MB in size.`,\n });\n }\n\n await updateSnapState(newState, encrypted);\n response.result = null;\n } catch (error) {\n return end(error);\n }\n\n return end();\n}\n\n/**\n * Validate the parameters of the `snap_setState` method.\n *\n * @param params - The parameters to validate.\n * @returns The validated parameters.\n */\nfunction getValidatedParams(params?: unknown) {\n try {\n return create(params, SetStateParametersStruct);\n } catch (error) {\n if (error instanceof StructError) {\n throw rpcErrors.invalidParams({\n message: `Invalid params: ${error.message}.`,\n });\n }\n\n /* istanbul ignore next */\n throw rpcErrors.internal();\n }\n}\n\n/**\n * Get the new state of the Snap.\n *\n * If the key is `undefined`, the value is expected to be an object. In this\n * case, the value is returned as the new state.\n *\n * If the key is not `undefined`, the value is set in the state at the key. If\n * the key does not exist, it is created (and any missing intermediate keys are\n * created as well).\n *\n * @param key - The key to set.\n * @param value - The value to set the key to.\n * @param encrypted - Whether the state is encrypted.\n * @param getSnapState - The `getSnapState` hook.\n * @returns The new state of the Snap.\n */\nasync function getNewState(\n key: string | undefined,\n value: Json,\n encrypted: boolean,\n getSnapState: SetStateHooks['getSnapState'],\n) {\n if (key === undefined) {\n assert(isObject(value));\n return value;\n }\n\n const state = await getSnapState(encrypted);\n return set(state, key, value);\n}\n\n/**\n * Set the value of a key in an object. The key may contain Lodash-style path\n * syntax, e.g., `a.b.c` (with the exception of array syntax). If the key does\n * not exist, it is created (and any missing intermediate keys are created as\n * well).\n *\n * This is a simplified version of Lodash's `set` function, but Lodash doesn't\n * seem to be maintained anymore, so we're using our own implementation.\n *\n * @param object - The object to get the key from.\n * @param key - The key to set.\n * @param value - The value to set the key to.\n * @returns The new object with the key set to the value.\n */\nexport function set(\n object: Record<string, Json> | null,\n key: string,\n value: Json,\n): JsonObject {\n const keys = key.split('.');\n const requiredObject = object ?? {};\n let currentObject: Record<string, Json> = requiredObject;\n\n for (let i = 0; i < keys.length; i++) {\n const currentKey = keys[i];\n if (FORBIDDEN_KEYS.includes(currentKey)) {\n throw rpcErrors.invalidParams(\n 'Invalid params: Key contains forbidden characters.',\n );\n }\n\n if (i === keys.length - 1) {\n currentObject[currentKey] = value;\n return requiredObject;\n }\n\n if (\n !hasProperty(currentObject, currentKey) ||\n currentObject[currentKey] === null\n ) {\n currentObject[currentKey] = {};\n } else if (!isObject(currentObject[currentKey])) {\n throw rpcErrors.invalidParams(\n 'Invalid params: Cannot overwrite non-object value.',\n );\n }\n\n currentObject = currentObject[currentKey] as Record<string, Json>;\n }\n\n // This should never be reached.\n /* istanbul ignore next */\n throw new Error('Unexpected error while setting the state.');\n}\n"]}
1
+ {"version":3,"file":"setState.mjs","sourceRoot":"","sources":["../../src/permitted/setState.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,cAAc,EAAE,SAAS,EAAE,6BAA6B;AAGjE,OAAO,EACL,iBAAiB,EAGlB,8BAA8B;AAC/B,OAAO,EACL,OAAO,EACP,MAAM,EACN,MAAM,IAAI,YAAY,EACtB,QAAQ,EACR,WAAW,EACZ,8BAA8B;AAM/B,OAAO,EAAE,WAAW,EAAE,QAAQ,EAAE,MAAM,EAAE,UAAU,EAAE,wBAAwB;AAE5E,OAAO,EACL,kBAAkB,EAClB,kBAAkB,EACnB,sCAAkC;AAEnC,OAAO,EAAE,cAAc,EAAE,cAAc,EAAE,qBAAiB;AAE1D,MAAM,SAAS,GAAqC;IAClD,aAAa,EAAE,IAAI;IACnB,YAAY,EAAE,IAAI;IAClB,gBAAgB,EAAE,IAAI;IACtB,eAAe,EAAE,IAAI;IACrB,OAAO,EAAE,I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C,2CAA2C,CAAC,CAAC;AAC/D,CAAC","sourcesContent":["import type { JsonRpcEngineEndCallback } from '@metamask/json-rpc-engine';\nimport type { PermittedHandlerExport } from '@metamask/permission-controller';\nimport { providerErrors, rpcErrors } from '@metamask/rpc-errors';\nimport type { SetStateParams, SetStateResult } from '@metamask/snaps-sdk';\nimport type { JsonObject } from '@metamask/snaps-sdk/jsx';\nimport {\n getJsonSizeUnsafe,\n type InferMatching,\n type Snap,\n} from '@metamask/snaps-utils';\nimport {\n boolean,\n create,\n object as objectStruct,\n optional,\n StructError,\n} from '@metamask/superstruct';\nimport type {\n PendingJsonRpcResponse,\n Json,\n JsonRpcRequest,\n} from '@metamask/utils';\nimport { hasProperty, isObject, assert, JsonStruct } from '@metamask/utils';\n\nimport {\n manageStateBuilder,\n STORAGE_SIZE_LIMIT,\n} from '../restricted/manageState';\nimport type { MethodHooksObject } from '../utils';\nimport { FORBIDDEN_KEYS, StateKeyStruct } from '../utils';\n\nconst hookNames: MethodHooksObject<SetStateHooks> = {\n hasPermission: true,\n getSnapState: true,\n getUnlockPromise: true,\n updateSnapState: true,\n getSnap: true,\n};\n\n/**\n * `snap_setState` sets the state of the Snap.\n */\nexport const setStateHandler: PermittedHandlerExport<\n SetStateHooks,\n SetStateParameters,\n SetStateResult\n> = {\n methodNames: ['snap_setState'],\n implementation: setStateImplementation,\n hookNames,\n};\n\nexport type SetStateHooks = {\n /**\n * Check if 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 * Get the state of the requesting Snap.\n *\n * @param encrypted - Whether the state is encrypted.\n * @returns The current state of the Snap.\n */\n getSnapState: (encrypted: boolean) => Promise<Record<string, Json>>;\n\n /**\n * Wait for the extension to be unlocked.\n *\n * @returns A promise that resolves once the extension is unlocked.\n */\n getUnlockPromise: (shouldShowUnlockRequest: boolean) => Promise<void>;\n\n /**\n * Update the state of the requesting Snap.\n *\n * @param newState - The new state of the Snap.\n * @param encrypted - Whether the state should be encrypted.\n */\n updateSnapState: (\n newState: Record<string, Json>,\n encrypted: boolean,\n ) => Promise<void>;\n\n /**\n * Get Snap metadata.\n *\n * @param snapId - The ID of a Snap.\n */\n getSnap: (snapId: string) => Snap | undefined;\n};\n\nconst SetStateParametersStruct = objectStruct({\n key: optional(StateKeyStruct),\n value: JsonStruct,\n encrypted: optional(boolean()),\n});\n\nexport type SetStateParameters = InferMatching<\n typeof SetStateParametersStruct,\n SetStateParams\n>;\n\n/**\n * The `snap_setState` method implementation.\n *\n * @param request - The JSON-RPC request object.\n * @param response - The JSON-RPC response object.\n * @param _next - The `json-rpc-engine` \"next\" callback. Not used by this\n * function.\n * @param end - The `json-rpc-engine` \"end\" callback.\n * @param hooks - The RPC method hooks.\n * @param hooks.hasPermission - Check whether a given origin has a given\n * permission.\n * @param hooks.getSnapState - Get the state of the requesting Snap.\n * @param hooks.getUnlockPromise - Wait for the extension to be unlocked.\n * @param hooks.updateSnapState - Update the state of the requesting Snap.\n * @param hooks.getSnap - The hook function to get Snap metadata.\n * @returns Nothing.\n */\nasync function setStateImplementation(\n request: JsonRpcRequest<SetStateParameters>,\n response: PendingJsonRpcResponse<SetStateResult>,\n _next: unknown,\n end: JsonRpcEngineEndCallback,\n {\n hasPermission,\n getSnapState,\n getUnlockPromise,\n updateSnapState,\n getSnap,\n }: SetStateHooks,\n): Promise<void> {\n const { params } = request;\n\n if (!hasPermission(manageStateBuilder.targetName)) {\n return end(providerErrors.unauthorized());\n }\n\n try {\n const validatedParams = getValidatedParams(params);\n const { key, value, encrypted = true } = validatedParams;\n\n if (key === undefined && !isObject(value)) {\n return end(\n rpcErrors.invalidParams(\n 'Invalid params: Value must be an object if key is not provided.',\n ),\n );\n }\n\n if (encrypted) {\n await getUnlockPromise(true);\n }\n\n const newState = await getNewState(key, value, encrypted, getSnapState);\n\n const snap = getSnap(\n (request as JsonRpcRequest<SetStateParams> & { origin: string }).origin,\n );\n\n if (!snap?.preinstalled) {\n // We know that the state is valid JSON as per previous validation.\n const size = getJsonSizeUnsafe(newState, true);\n if (size > STORAGE_SIZE_LIMIT) {\n throw rpcErrors.invalidParams({\n message: `Invalid params: The new state must not exceed ${\n STORAGE_SIZE_LIMIT / 1_000_000\n } MB in size.`,\n });\n }\n }\n\n await updateSnapState(newState, encrypted);\n response.result = null;\n } catch (error) {\n return end(error);\n }\n\n return end();\n}\n\n/**\n * Validate the parameters of the `snap_setState` method.\n *\n * @param params - The parameters to validate.\n * @returns The validated parameters.\n */\nfunction getValidatedParams(params?: unknown) {\n try {\n return create(params, SetStateParametersStruct);\n } catch (error) {\n if (error instanceof StructError) {\n throw rpcErrors.invalidParams({\n message: `Invalid params: ${error.message}.`,\n });\n }\n\n /* istanbul ignore next */\n throw rpcErrors.internal();\n }\n}\n\n/**\n * Get the new state of the Snap.\n *\n * If the key is `undefined`, the value is expected to be an object. In this\n * case, the value is returned as the new state.\n *\n * If the key is not `undefined`, the value is set in the state at the key. If\n * the key does not exist, it is created (and any missing intermediate keys are\n * created as well).\n *\n * @param key - The key to set.\n * @param value - The value to set the key to.\n * @param encrypted - Whether the state is encrypted.\n * @param getSnapState - The `getSnapState` hook.\n * @returns The new state of the Snap.\n */\nasync function getNewState(\n key: string | undefined,\n value: Json,\n encrypted: boolean,\n getSnapState: SetStateHooks['getSnapState'],\n) {\n if (key === undefined) {\n assert(isObject(value));\n return value;\n }\n\n const state = await getSnapState(encrypted);\n return set(state, key, value);\n}\n\n/**\n * Set the value of a key in an object. The key may contain Lodash-style path\n * syntax, e.g., `a.b.c` (with the exception of array syntax). If the key does\n * not exist, it is created (and any missing intermediate keys are created as\n * well).\n *\n * This is a simplified version of Lodash's `set` function, but Lodash doesn't\n * seem to be maintained anymore, so we're using our own implementation.\n *\n * @param object - The object to get the key from.\n * @param key - The key to set.\n * @param value - The value to set the key to.\n * @returns The new object with the key set to the value.\n */\nexport function set(\n object: Record<string, Json> | null,\n key: string,\n value: Json,\n): JsonObject {\n const keys = key.split('.');\n const requiredObject = object ?? {};\n let currentObject: Record<string, Json> = requiredObject;\n\n for (let i = 0; i < keys.length; i++) {\n const currentKey = keys[i];\n if (FORBIDDEN_KEYS.includes(currentKey)) {\n throw rpcErrors.invalidParams(\n 'Invalid params: Key contains forbidden characters.',\n );\n }\n\n if (i === keys.length - 1) {\n currentObject[currentKey] = value;\n return requiredObject;\n }\n\n if (\n !hasProperty(currentObject, currentKey) ||\n currentObject[currentKey] === null\n ) {\n currentObject[currentKey] = {};\n } else if (!isObject(currentObject[currentKey])) {\n throw rpcErrors.invalidParams(\n 'Invalid params: Cannot overwrite non-object value.',\n );\n }\n\n currentObject = currentObject[currentKey] as Record<string, Json>;\n }\n\n // This should never be reached.\n /* istanbul ignore next */\n throw new Error('Unexpected error while setting the state.');\n}\n"]}