@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
@@ -35,6 +35,7 @@ const methodHooks = {
35
35
  clearSnapState: true,
36
36
  getSnapState: true,
37
37
  updateSnapState: true,
38
+ getSnap: true,
38
39
  };
39
40
  exports.manageStateBuilder = Object.freeze({
40
41
  targetName: methodName,
@@ -80,14 +81,25 @@ exports.getEncryptionEntropy = getEncryptionEntropy;
80
81
  * @param hooks.getUnlockPromise - A function that resolves once the MetaMask
81
82
  * extension is unlocked and prompts the user to unlock their MetaMask if it is
82
83
  * locked.
84
+ * @param hooks.getSnap - The hook function to get Snap metadata.
83
85
  * @returns The method implementation which either returns `null` for a
84
86
  * successful state update/deletion or returns the decrypted state.
85
87
  * @throws If the params are invalid.
86
88
  */
87
- function getManageStateImplementation({ getUnlockPromise, clearSnapState, getSnapState, updateSnapState, }) {
89
+ function getManageStateImplementation({ getUnlockPromise, clearSnapState, getSnapState, updateSnapState, getSnap, }) {
88
90
  return async function manageState(options) {
89
91
  const { params = {}, method, context: { origin }, } = options;
90
92
  const validatedParams = getValidatedParams(params, method);
93
+ const snap = getSnap(origin);
94
+ if (!snap?.preinstalled &&
95
+ validatedParams.operation === snaps_sdk_1.ManageStateOperation.UpdateState) {
96
+ const size = (0, snaps_utils_1.getJsonSizeUnsafe)(validatedParams.newState, true);
97
+ if (size > exports.STORAGE_SIZE_LIMIT) {
98
+ throw rpc_errors_1.rpcErrors.invalidParams({
99
+ message: `Invalid ${method} "newState" parameter: The new state must not exceed ${exports.STORAGE_SIZE_LIMIT / 1000000} MB in size.`,
100
+ });
101
+ }
102
+ }
91
103
  // If the encrypted param is undefined or null we default to true.
92
104
  const shouldEncrypt = validatedParams.encrypted ?? true;
93
105
  // We only need to prompt the user when the mnemonic is needed
@@ -107,6 +119,7 @@ function getManageStateImplementation({ getUnlockPromise, clearSnapState, getSna
107
119
  await updateSnapState(origin, validatedParams.newState, shouldEncrypt);
108
120
  return null;
109
121
  }
122
+ /* istanbul ignore next */
110
123
  default:
111
124
  throw rpc_errors_1.rpcErrors.invalidParams(`Invalid ${method} operation: "${validatedParams.operation}"`);
112
125
  }
@@ -119,10 +132,9 @@ exports.getManageStateImplementation = getManageStateImplementation;
119
132
  *
120
133
  * @param params - The unvalidated params object from the method request.
121
134
  * @param method - RPC method name used for debugging errors.
122
- * @param storageSizeLimit - Maximum allowed size (in bytes) of a new state object.
123
135
  * @returns The validated method parameter object.
124
136
  */
125
- function getValidatedParams(params, method, storageSizeLimit = exports.STORAGE_SIZE_LIMIT) {
137
+ function getValidatedParams(params, method) {
126
138
  if (!(0, utils_1.isObject)(params)) {
127
139
  throw rpc_errors_1.rpcErrors.invalidParams({
128
140
  message: 'Expected params to be a single object.',
@@ -147,21 +159,11 @@ function getValidatedParams(params, method, storageSizeLimit = exports.STORAGE_S
147
159
  message: `Invalid ${method} "newState" parameter: The new state must be a plain object.`,
148
160
  });
149
161
  }
150
- let size;
151
- try {
152
- // `getJsonSize` will throw if the state is not JSON serializable.
153
- size = (0, utils_1.getJsonSize)(newState);
154
- }
155
- catch {
162
+ if (!(0, utils_1.isValidJson)(newState)) {
156
163
  throw rpc_errors_1.rpcErrors.invalidParams({
157
164
  message: `Invalid ${method} "newState" parameter: The new state must be JSON serializable.`,
158
165
  });
159
166
  }
160
- if (size > storageSizeLimit) {
161
- throw rpc_errors_1.rpcErrors.invalidParams({
162
- message: `Invalid ${method} "newState" parameter: The new state must not exceed ${storageSizeLimit / 1000000} MB in size.`,
163
- });
164
- }
165
167
  }
166
168
  return params;
167
169
  }
@@ -1 +1 @@
1
- {"version":3,"file":"manageState.cjs","sourceRoot":"","sources":["../../src/restricted/manageState.ts"],"names":[],"mappings":";;;AAMA,2EAA8E;AAC9E,qDAAiD;AAEjD,mDAA2D;AAC3D,uDAAqE;AAErE,2CAAwD;AAGxD,wCAAiD;AAEjD,oDAAoD;AACvC,QAAA,qBAAqB,GAAG,6BAA6B,CAAC;AAEnE,MAAM,UAAU,GAAG,kBAAkB,CAAC;AAiDtC;;;;;;;;;GASG;AACI,MAAM,oBAAoB,GAI7B,CAAC,EACH,cAAc,GAAG,IAAI,EACrB,WAAW,GAC4B,EAAE,EAAE;IAC3C,OAAO;QACL,cAAc,EAAE,sCAAc,CAAC,gBAAgB;QAC/C,UAAU,EAAE,UAAU;QACtB,cAAc;QACd,oBAAoB,EAAE,4BAA4B,CAAC,WAAW,CAAC;QAC/D,YAAY,EAAE,CAAC,mCAAW,CAAC,IAAI,CAAC;KACjC,CAAC;AACJ,CAAC,CAAC;AAfW,QAAA,oBAAoB,wBAe/B;AAEF,MAAM,WAAW,GAA8C;IAC7D,gBAAgB,EAAE,IAAI;IACtB,cAAc,EAAE,IAAI;IACpB,YAAY,EAAE,IAAI;IAClB,eAAe,EAA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AAA,gBAAQ,EAAC,QAAQ,CAAC,EAAE,CAAC;YACxB,MAAM,sBAAS,CAAC,aAAa,CAAC;gBAC5B,OAAO,EAAE,WAAW,MAAM,8DAA8D;aACzF,CAAC,CAAC;QACL,CAAC;QAED,IAAI,IAAI,CAAC;QACT,IAAI,CAAC;YACH,kEAAkE;YAClE,IAAI,GAAG,IAAA,mBAAW,EAAC,QAAQ,CAAC,CAAC;QAC/B,CAAC;QAAC,MAAM,CAAC;YACP,MAAM,sBAAS,CAAC,aAAa,CAAC;gBAC5B,OAAO,EAAE,WAAW,MAAM,iEAAiE;aAC5F,CAAC,CAAC;QACL,CAAC;QAED,IAAI,IAAI,GAAG,gBAAgB,EAAE,CAAC;YAC5B,MAAM,sBAAS,CAAC,aAAa,CAAC;gBAC5B,OAAO,EAAE,WAAW,MAAM,wDACxB,gBAAgB,GAAG,OACrB,cAAc;aACf,CAAC,CAAC;QACL,CAAC;IACH,CAAC;IAED,OAAO,MAA2B,CAAC;AACrC,CAAC;AA1DD,gDA0DC","sourcesContent":["import type { CryptographicFunctions } from '@metamask/key-tree';\nimport type {\n PermissionSpecificationBuilder,\n RestrictedMethodOptions,\n ValidPermissionSpecification,\n} from '@metamask/permission-controller';\nimport { PermissionType, SubjectType } from '@metamask/permission-controller';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport type { ManageStateParams, ManageStateResult } from '@metamask/snaps-sdk';\nimport { ManageStateOperation } from '@metamask/snaps-sdk';\nimport { STATE_ENCRYPTION_MAGIC_VALUE } from '@metamask/snaps-utils';\nimport type { Json, NonEmptyArray } from '@metamask/utils';\nimport { isObject, getJsonSize } from '@metamask/utils';\n\nimport type { MethodHooksObject } from '../utils';\nimport { deriveEntropyFromSeed } from '../utils';\n\n// The salt used for SIP-6-based entropy derivation.\nexport const STATE_ENCRYPTION_SALT = 'snap_manageState encryption';\n\nconst methodName = 'snap_manageState';\n\nexport type ManageStateMethodHooks = {\n /**\n * Waits 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 * A function that clears the state of the requesting Snap.\n */\n clearSnapState: (snapId: string, encrypted: boolean) => void;\n\n /**\n * A function that gets the encrypted state of the requesting Snap.\n *\n * @returns The current state of the Snap.\n */\n getSnapState: (\n snapId: string,\n encrypted: boolean,\n ) => Promise<Record<string, Json>>;\n\n /**\n * A function that updates the state of the requesting Snap.\n *\n * @param newState - The new state of the Snap.\n */\n updateSnapState: (\n snapId: string,\n newState: Record<string, Json>,\n encrypted: boolean,\n ) => Promise<void>;\n};\n\ntype ManageStateSpecificationBuilderOptions = {\n allowedCaveats?: Readonly<NonEmptyArray<string>> | null;\n methodHooks: ManageStateMethodHooks;\n};\n\ntype ManageStateSpecification = ValidPermissionSpecification<{\n permissionType: PermissionType.RestrictedMethod;\n targetName: typeof methodName;\n methodImplementation: ReturnType<typeof getManageStateImplementation>;\n allowedCaveats: Readonly<NonEmptyArray<string>> | null;\n}>;\n\n/**\n * The specification builder for the `snap_manageState` permission.\n * `snap_manageState` lets the Snap store and manage some of its state on\n * your device.\n *\n * @param options - The specification builder options.\n * @param options.allowedCaveats - The optional allowed caveats for the permission.\n * @param options.methodHooks - The RPC method hooks needed by the method implementation.\n * @returns The specification for the `snap_manageState` permission.\n */\nexport const specificationBuilder: PermissionSpecificationBuilder<\n PermissionType.RestrictedMethod,\n ManageStateSpecificationBuilderOptions,\n ManageStateSpecification\n> = ({\n allowedCaveats = null,\n methodHooks,\n}: ManageStateSpecificationBuilderOptions) => {\n return {\n permissionType: PermissionType.RestrictedMethod,\n targetName: methodName,\n allowedCaveats,\n methodImplementation: getManageStateImplementation(methodHooks),\n subjectTypes: [SubjectType.Snap],\n };\n};\n\nconst methodHooks: MethodHooksObject<ManageStateMethodHooks> = {\n getUnlockPromise: true,\n clearSnapState: true,\n getSnapState: true,\n updateSnapState: true,\n};\n\nexport const manageStateBuilder = Object.freeze({\n targetName: methodName,\n specificationBuilder,\n methodHooks,\n} as const);\n\nexport const STORAGE_SIZE_LIMIT = 64_000_000; // In bytes (64 MB)\n\ntype GetEncryptionKeyArgs = {\n snapId: string;\n seed: Uint8Array;\n cryptographicFunctions?: CryptographicFunctions | undefined;\n};\n\n/**\n * Get a deterministic encryption key to use for encrypting and decrypting the\n * state.\n *\n * This key should only be used for state encryption using `snap_manageState`.\n * To get other encryption keys, a different salt can be used.\n *\n * @param args - The encryption key args.\n * @param args.snapId - The ID of the snap to get the encryption key for.\n * @param args.seed - The mnemonic seed to derive the encryption key\n * from.\n * @param args.cryptographicFunctions - The cryptographic functions to use for\n * the client.\n * @returns The state encryption key.\n */\nexport async function getEncryptionEntropy({\n seed,\n snapId,\n cryptographicFunctions,\n}: GetEncryptionKeyArgs) {\n return await deriveEntropyFromSeed({\n seed,\n input: snapId,\n salt: STATE_ENCRYPTION_SALT,\n magic: STATE_ENCRYPTION_MAGIC_VALUE,\n cryptographicFunctions,\n });\n}\n\n/**\n * Builds the method implementation for `snap_manageState`.\n *\n * @param hooks - The RPC method hooks.\n * @param hooks.clearSnapState - A function that clears the state stored for a\n * snap.\n * @param hooks.getSnapState - A function that fetches the persisted decrypted\n * state for a snap.\n * @param hooks.updateSnapState - A function that updates the state stored for a\n * snap.\n * @param hooks.getUnlockPromise - A function that resolves once the MetaMask\n * extension is unlocked and prompts the user to unlock their MetaMask if it is\n * locked.\n * @returns The method implementation which either returns `null` for a\n * successful state update/deletion or returns the decrypted state.\n * @throws If the params are invalid.\n */\nexport function getManageStateImplementation({\n getUnlockPromise,\n clearSnapState,\n getSnapState,\n updateSnapState,\n}: ManageStateMethodHooks) {\n return async function manageState(\n options: RestrictedMethodOptions<ManageStateParams>,\n ): Promise<ManageStateResult> {\n const {\n params = {},\n method,\n context: { origin },\n } = options;\n const validatedParams = getValidatedParams(params, method);\n\n // If the encrypted param is undefined or null we default to true.\n const shouldEncrypt = validatedParams.encrypted ?? true;\n\n // We only need to prompt the user when the mnemonic is needed\n // which it isn't for the clear operation or unencrypted storage.\n if (\n shouldEncrypt &&\n validatedParams.operation !== ManageStateOperation.ClearState\n ) {\n await getUnlockPromise(true);\n }\n\n switch (validatedParams.operation) {\n case ManageStateOperation.ClearState:\n clearSnapState(origin, shouldEncrypt);\n return null;\n\n case ManageStateOperation.GetState: {\n return await getSnapState(origin, shouldEncrypt);\n }\n\n case ManageStateOperation.UpdateState: {\n await updateSnapState(origin, validatedParams.newState, shouldEncrypt);\n return null;\n }\n\n default:\n throw rpcErrors.invalidParams(\n `Invalid ${method} operation: \"${\n validatedParams.operation as string\n }\"`,\n );\n }\n };\n}\n\n/**\n * Validates the manageState 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 * @param method - RPC method name used for debugging errors.\n * @param storageSizeLimit - Maximum allowed size (in bytes) of a new state object.\n * @returns The validated method parameter object.\n */\nexport function getValidatedParams(\n params: unknown,\n method: string,\n storageSizeLimit = STORAGE_SIZE_LIMIT,\n): ManageStateParams {\n if (!isObject(params)) {\n throw rpcErrors.invalidParams({\n message: 'Expected params to be a single object.',\n });\n }\n\n const { operation, newState, encrypted } = params;\n\n if (\n !operation ||\n typeof operation !== 'string' ||\n !Object.values(ManageStateOperation).includes(\n operation as ManageStateOperation,\n )\n ) {\n throw rpcErrors.invalidParams({\n message: 'Must specify a valid manage state \"operation\".',\n });\n }\n\n if (encrypted !== undefined && typeof encrypted !== 'boolean') {\n throw rpcErrors.invalidParams({\n message: '\"encrypted\" parameter must be a boolean if specified.',\n });\n }\n\n if (operation === ManageStateOperation.UpdateState) {\n if (!isObject(newState)) {\n throw rpcErrors.invalidParams({\n message: `Invalid ${method} \"newState\" parameter: The new state must be a plain object.`,\n });\n }\n\n let size;\n try {\n // `getJsonSize` will throw if the state is not JSON serializable.\n size = getJsonSize(newState);\n } catch {\n throw rpcErrors.invalidParams({\n message: `Invalid ${method} \"newState\" parameter: The new state must be JSON serializable.`,\n });\n }\n\n if (size > storageSizeLimit) {\n throw rpcErrors.invalidParams({\n message: `Invalid ${method} \"newState\" parameter: The new state must not exceed ${\n storageSizeLimit / 1_000_000\n } MB in size.`,\n });\n }\n }\n\n return params as ManageStateParams;\n}\n"]}
1
+ {"version":3,"file":"manageState.cjs","sourceRoot":"","sources":["../../src/restricted/manageState.ts"],"names":[],"mappings":";;;AAMA,2EAA8E;AAC9E,qDAAiD;AAEjD,mDAA2D;AAE3D,uDAG+B;AAE/B,2CAAwD;AAGxD,wCAAiD;AAEjD,oDAAoD;AACvC,QAAA,qBAAqB,GAAG,6BAA6B,CAAC;AAEnE,MAAM,UAAU,GAAG,kBAAkB,CAAC;AAwDtC;;;;;;;;;GASG;AACI,MAAM,oBAAoB,GAI7B,CAAC,EACH,cAAc,GAAG,IAAI,EACrB,WAAW,GAC4B,EAAE,EAAE;IAC3C,OAAO;QACL,cAAc,EAAE,sCAAc,CAAC,gBAAgB;QAC/C,UAAU,EAAE,UAAU;QACtB,cAAc;QACd,oBAAoB,EAAE,4BAA4B,CAAC,WAAW,CAAC;QAC/D,YAAY,EAAE,CAAC,mCAAW,CAAC,IAAI,CAAC;KACjC,CAAC;AACJ,CAAC,CAAC;AAfW,QAAA,oBAAoB,wBAe/B;AAEF,MAAM,WAAW,GAA8C;IAC7D,gBAAgB,EAAE,IAAI;IACtB,cAAc,EAAE,IAAI;IACpB,YAAY,EAAE,IAAI;IAClB,eAAe,EAAE,IAAI;IACrB,OAAO,EAAE,IAAI;CACd,CAAC;AAEW,QAAA,kBAAkB,GAAG,MAAM,CAAC,MAAM,CAAC;IAC9C,UAAU,EAAE,UAAU;IACtB,oBAAoB,EAApB,4BAAoB;IACpB,WAAW;CACH,CAAC,CAAC;AAEC,QAAA,kBAAkB,GAAG,QAAU,CAAC,CAAC,mBAAmB;AAQjE;;;;;;;;;;;;;;GAcG;AACI,KAAK,UAAU,oBAAoB,CAAC,EACzC,IAAI,EACJ,MAAM,EACN,sBAAsB,GACD;IACrB,OAAO,MAAM,IAAA,6BAAqB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;IACL,CAAC;IAED,IAAI,SAAS,KAAK,gCAAoB,CAAC,WAAW,EAAE,CAAC;QACnD,IAAI,CAAC,IAAA,gBAAQ,EAAC,QAAQ,CAAC,EAAE,CAAC;YACxB,MAAM,sBAAS,CAAC,aAAa,CAAC;gBAC5B,OAAO,EAAE,WAAW,MAAM,8DAA8D;aACzF,CAAC,CAAC;QACL,CAAC;QAED,IAAI,CAAC,IAAA,mBAAW,EAAC,QAAQ,CAAC,EAAE,CAAC;YAC3B,MAAM,sBAAS,CAAC,aAAa,CAAC;gBAC5B,OAAO,EAAE,WAAW,MAAM,iEAAiE;aAC5F,CAAC,CAAC;QACL,CAAC;IACH,CAAC;IAED,OAAO,MAA2B,CAAC;AACrC,CAAC;AA7CD,gDA6CC","sourcesContent":["import type { CryptographicFunctions } from '@metamask/key-tree';\nimport type {\n PermissionSpecificationBuilder,\n RestrictedMethodOptions,\n ValidPermissionSpecification,\n} from '@metamask/permission-controller';\nimport { PermissionType, SubjectType } from '@metamask/permission-controller';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport type { ManageStateParams, ManageStateResult } from '@metamask/snaps-sdk';\nimport { ManageStateOperation } from '@metamask/snaps-sdk';\nimport type { Snap } from '@metamask/snaps-utils';\nimport {\n getJsonSizeUnsafe,\n STATE_ENCRYPTION_MAGIC_VALUE,\n} from '@metamask/snaps-utils';\nimport type { Json, NonEmptyArray } from '@metamask/utils';\nimport { isObject, isValidJson } from '@metamask/utils';\n\nimport type { MethodHooksObject } from '../utils';\nimport { deriveEntropyFromSeed } from '../utils';\n\n// The salt used for SIP-6-based entropy derivation.\nexport const STATE_ENCRYPTION_SALT = 'snap_manageState encryption';\n\nconst methodName = 'snap_manageState';\n\nexport type ManageStateMethodHooks = {\n /**\n * Waits 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 * A function that clears the state of the requesting Snap.\n */\n clearSnapState: (snapId: string, encrypted: boolean) => void;\n\n /**\n * A function that gets the encrypted state of the requesting Snap.\n *\n * @returns The current state of the Snap.\n */\n getSnapState: (\n snapId: string,\n encrypted: boolean,\n ) => Promise<Record<string, Json>>;\n\n /**\n * A function that updates the state of the requesting Snap.\n *\n * @param newState - The new state of the Snap.\n */\n updateSnapState: (\n snapId: string,\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\ntype ManageStateSpecificationBuilderOptions = {\n allowedCaveats?: Readonly<NonEmptyArray<string>> | null;\n methodHooks: ManageStateMethodHooks;\n};\n\ntype ManageStateSpecification = ValidPermissionSpecification<{\n permissionType: PermissionType.RestrictedMethod;\n targetName: typeof methodName;\n methodImplementation: ReturnType<typeof getManageStateImplementation>;\n allowedCaveats: Readonly<NonEmptyArray<string>> | null;\n}>;\n\n/**\n * The specification builder for the `snap_manageState` permission.\n * `snap_manageState` lets the Snap store and manage some of its state on\n * your device.\n *\n * @param options - The specification builder options.\n * @param options.allowedCaveats - The optional allowed caveats for the permission.\n * @param options.methodHooks - The RPC method hooks needed by the method implementation.\n * @returns The specification for the `snap_manageState` permission.\n */\nexport const specificationBuilder: PermissionSpecificationBuilder<\n PermissionType.RestrictedMethod,\n ManageStateSpecificationBuilderOptions,\n ManageStateSpecification\n> = ({\n allowedCaveats = null,\n methodHooks,\n}: ManageStateSpecificationBuilderOptions) => {\n return {\n permissionType: PermissionType.RestrictedMethod,\n targetName: methodName,\n allowedCaveats,\n methodImplementation: getManageStateImplementation(methodHooks),\n subjectTypes: [SubjectType.Snap],\n };\n};\n\nconst methodHooks: MethodHooksObject<ManageStateMethodHooks> = {\n getUnlockPromise: true,\n clearSnapState: true,\n getSnapState: true,\n updateSnapState: true,\n getSnap: true,\n};\n\nexport const manageStateBuilder = Object.freeze({\n targetName: methodName,\n specificationBuilder,\n methodHooks,\n} as const);\n\nexport const STORAGE_SIZE_LIMIT = 64_000_000; // In bytes (64 MB)\n\ntype GetEncryptionKeyArgs = {\n snapId: string;\n seed: Uint8Array;\n cryptographicFunctions?: CryptographicFunctions | undefined;\n};\n\n/**\n * Get a deterministic encryption key to use for encrypting and decrypting the\n * state.\n *\n * This key should only be used for state encryption using `snap_manageState`.\n * To get other encryption keys, a different salt can be used.\n *\n * @param args - The encryption key args.\n * @param args.snapId - The ID of the snap to get the encryption key for.\n * @param args.seed - The mnemonic seed to derive the encryption key\n * from.\n * @param args.cryptographicFunctions - The cryptographic functions to use for\n * the client.\n * @returns The state encryption key.\n */\nexport async function getEncryptionEntropy({\n seed,\n snapId,\n cryptographicFunctions,\n}: GetEncryptionKeyArgs) {\n return await deriveEntropyFromSeed({\n seed,\n input: snapId,\n salt: STATE_ENCRYPTION_SALT,\n magic: STATE_ENCRYPTION_MAGIC_VALUE,\n cryptographicFunctions,\n });\n}\n\n/**\n * Builds the method implementation for `snap_manageState`.\n *\n * @param hooks - The RPC method hooks.\n * @param hooks.clearSnapState - A function that clears the state stored for a\n * snap.\n * @param hooks.getSnapState - A function that fetches the persisted decrypted\n * state for a snap.\n * @param hooks.updateSnapState - A function that updates the state stored for a\n * snap.\n * @param hooks.getUnlockPromise - A function that resolves once the MetaMask\n * extension is unlocked and prompts the user to unlock their MetaMask if it is\n * locked.\n * @param hooks.getSnap - The hook function to get Snap metadata.\n * @returns The method implementation which either returns `null` for a\n * successful state update/deletion or returns the decrypted state.\n * @throws If the params are invalid.\n */\nexport function getManageStateImplementation({\n getUnlockPromise,\n clearSnapState,\n getSnapState,\n updateSnapState,\n getSnap,\n}: ManageStateMethodHooks) {\n return async function manageState(\n options: RestrictedMethodOptions<ManageStateParams>,\n ): Promise<ManageStateResult> {\n const {\n params = {},\n method,\n context: { origin },\n } = options;\n const validatedParams = getValidatedParams(params, method);\n\n const snap = getSnap(origin);\n\n if (\n !snap?.preinstalled &&\n validatedParams.operation === ManageStateOperation.UpdateState\n ) {\n const size = getJsonSizeUnsafe(validatedParams.newState, true);\n\n if (size > STORAGE_SIZE_LIMIT) {\n throw rpcErrors.invalidParams({\n message: `Invalid ${method} \"newState\" parameter: The new state must not exceed ${\n STORAGE_SIZE_LIMIT / 1_000_000\n } MB in size.`,\n });\n }\n }\n\n // If the encrypted param is undefined or null we default to true.\n const shouldEncrypt = validatedParams.encrypted ?? true;\n\n // We only need to prompt the user when the mnemonic is needed\n // which it isn't for the clear operation or unencrypted storage.\n if (\n shouldEncrypt &&\n validatedParams.operation !== ManageStateOperation.ClearState\n ) {\n await getUnlockPromise(true);\n }\n\n switch (validatedParams.operation) {\n case ManageStateOperation.ClearState:\n clearSnapState(origin, shouldEncrypt);\n return null;\n\n case ManageStateOperation.GetState: {\n return await getSnapState(origin, shouldEncrypt);\n }\n\n case ManageStateOperation.UpdateState: {\n await updateSnapState(origin, validatedParams.newState, shouldEncrypt);\n return null;\n }\n\n /* istanbul ignore next */\n default:\n throw rpcErrors.invalidParams(\n `Invalid ${method} operation: \"${\n validatedParams.operation as string\n }\"`,\n );\n }\n };\n}\n\n/**\n * Validates the manageState 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 * @param method - RPC method name used for debugging errors.\n * @returns The validated method parameter object.\n */\nexport function getValidatedParams(\n params: unknown,\n method: string,\n): ManageStateParams {\n if (!isObject(params)) {\n throw rpcErrors.invalidParams({\n message: 'Expected params to be a single object.',\n });\n }\n\n const { operation, newState, encrypted } = params;\n\n if (\n !operation ||\n typeof operation !== 'string' ||\n !Object.values(ManageStateOperation).includes(\n operation as ManageStateOperation,\n )\n ) {\n throw rpcErrors.invalidParams({\n message: 'Must specify a valid manage state \"operation\".',\n });\n }\n\n if (encrypted !== undefined && typeof encrypted !== 'boolean') {\n throw rpcErrors.invalidParams({\n message: '\"encrypted\" parameter must be a boolean if specified.',\n });\n }\n\n if (operation === ManageStateOperation.UpdateState) {\n if (!isObject(newState)) {\n throw rpcErrors.invalidParams({\n message: `Invalid ${method} \"newState\" parameter: The new state must be a plain object.`,\n });\n }\n\n if (!isValidJson(newState)) {\n throw rpcErrors.invalidParams({\n message: `Invalid ${method} \"newState\" parameter: The new state must be JSON serializable.`,\n });\n }\n }\n\n return params as ManageStateParams;\n}\n"]}
@@ -2,6 +2,7 @@ import type { CryptographicFunctions } from "@metamask/key-tree";
2
2
  import type { PermissionSpecificationBuilder, RestrictedMethodOptions, ValidPermissionSpecification } from "@metamask/permission-controller";
3
3
  import { PermissionType } from "@metamask/permission-controller";
4
4
  import type { ManageStateParams, ManageStateResult } from "@metamask/snaps-sdk";
5
+ import type { Snap } from "@metamask/snaps-utils";
5
6
  import type { Json, NonEmptyArray } from "@metamask/utils";
6
7
  import type { MethodHooksObject } from "../utils.cjs";
7
8
  export declare const STATE_ENCRYPTION_SALT = "snap_manageState encryption";
@@ -29,6 +30,12 @@ export type ManageStateMethodHooks = {
29
30
  * @param newState - The new state of the Snap.
30
31
  */
31
32
  updateSnapState: (snapId: string, newState: Record<string, Json>, encrypted: boolean) => Promise<void>;
33
+ /**
34
+ * Get Snap metadata.
35
+ *
36
+ * @param snapId - The ID of a Snap.
37
+ */
38
+ getSnap: (snapId: string) => Snap | undefined;
32
39
  };
33
40
  type ManageStateSpecificationBuilderOptions = {
34
41
  allowedCaveats?: Readonly<NonEmptyArray<string>> | null;
@@ -96,20 +103,20 @@ export declare function getEncryptionEntropy({ seed, snapId, cryptographicFuncti
96
103
  * @param hooks.getUnlockPromise - A function that resolves once the MetaMask
97
104
  * extension is unlocked and prompts the user to unlock their MetaMask if it is
98
105
  * locked.
106
+ * @param hooks.getSnap - The hook function to get Snap metadata.
99
107
  * @returns The method implementation which either returns `null` for a
100
108
  * successful state update/deletion or returns the decrypted state.
101
109
  * @throws If the params are invalid.
102
110
  */
103
- export declare function getManageStateImplementation({ getUnlockPromise, clearSnapState, getSnapState, updateSnapState, }: ManageStateMethodHooks): (options: RestrictedMethodOptions<ManageStateParams>) => Promise<ManageStateResult>;
111
+ export declare function getManageStateImplementation({ getUnlockPromise, clearSnapState, getSnapState, updateSnapState, getSnap, }: ManageStateMethodHooks): (options: RestrictedMethodOptions<ManageStateParams>) => Promise<ManageStateResult>;
104
112
  /**
105
113
  * Validates the manageState method `params` and returns them cast to the correct
106
114
  * type. Throws if validation fails.
107
115
  *
108
116
  * @param params - The unvalidated params object from the method request.
109
117
  * @param method - RPC method name used for debugging errors.
110
- * @param storageSizeLimit - Maximum allowed size (in bytes) of a new state object.
111
118
  * @returns The validated method parameter object.
112
119
  */
113
- export declare function getValidatedParams(params: unknown, method: string, storageSizeLimit?: number): ManageStateParams;
120
+ export declare function getValidatedParams(params: unknown, method: string): ManageStateParams;
114
121
  export {};
115
122
  //# sourceMappingURL=manageState.d.cts.map
@@ -1 +1 @@
1
- {"version":3,"file":"manageState.d.cts","sourceRoot":"","sources":["../../src/restricted/manageState.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,sBAAsB,EAAE,2BAA2B;AACjE,OAAO,KAAK,EACV,8BAA8B,EAC9B,uBAAuB,EACvB,4BAA4B,EAC7B,wCAAwC;AACzC,OAAO,EAAE,cAAc,EAAe,wCAAwC;AAE9E,OAAO,KAAK,EAAE,iBAAiB,EAAE,iBAAiB,EAAE,4BAA4B;AAGhF,OAAO,KAAK,EAAE,IAAI,EAAE,aAAa,EAAE,wBAAwB;AAG3D,OAAO,KAAK,EAAE,iBAAiB,EAAE,qBAAiB;AAIlD,eAAO,MAAM,qBAAqB,gCAAgC,CAAC;AAEnE,QAAA,MAAM,UAAU,qBAAqB,CAAC;AAEtC,MAAM,MAAM,sBAAsB,GAAG;IACnC;;;;OAIG;IACH,gBAAgB,EAAE,CAAC,uBAAuB,EAAE,OAAO,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IAEtE;;OAEG;IACH,cAAc,EAAE,CAAC,MAAM,EAAE,MAAM,EAAE,SAAS,EAAE,OAAO,KAAK,IAAI,CAAC;IAE7D;;;;OAIG;IACH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I,EAAE,UAAU,CAAC;IACjB,sBAAsB,CAAC,EAAE,sBAAsB,GAAG,SAAS,CAAC;CAC7D,CAAC;AAEF;;;;;;;;;;;;;;GAcG;AACH,wBAAsB,oBAAoB,CAAC,EACzC,IAAI,EACJ,MAAM,EACN,sBAAsB,GACvB,EAAE,oBAAoB,0BAQtB;AAED;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAgB,4BAA4B,CAAC,EAC3C,gBAAgB,EAChB,cAAc,EACd,YAAY,EACZ,eAAe,EACf,OAAO,GACR,EAAE,sBAAsB,aAEZ,wBAAwB,iBAAiB,CAAC,KAClD,QAAQ,iBAAiB,CAAC,CA4D9B;AAED;;;;;;;GAOG;AACH,wBAAgB,kBAAkB,CAChC,MAAM,EAAE,OAAO,EACf,MAAM,EAAE,MAAM,GACb,iBAAiB,CA0CnB"}
@@ -2,6 +2,7 @@ import type { CryptographicFunctions } from "@metamask/key-tree";
2
2
  import type { PermissionSpecificationBuilder, RestrictedMethodOptions, ValidPermissionSpecification } from "@metamask/permission-controller";
3
3
  import { PermissionType } from "@metamask/permission-controller";
4
4
  import type { ManageStateParams, ManageStateResult } from "@metamask/snaps-sdk";
5
+ import type { Snap } from "@metamask/snaps-utils";
5
6
  import type { Json, NonEmptyArray } from "@metamask/utils";
6
7
  import type { MethodHooksObject } from "../utils.mjs";
7
8
  export declare const STATE_ENCRYPTION_SALT = "snap_manageState encryption";
@@ -29,6 +30,12 @@ export type ManageStateMethodHooks = {
29
30
  * @param newState - The new state of the Snap.
30
31
  */
31
32
  updateSnapState: (snapId: string, newState: Record<string, Json>, encrypted: boolean) => Promise<void>;
33
+ /**
34
+ * Get Snap metadata.
35
+ *
36
+ * @param snapId - The ID of a Snap.
37
+ */
38
+ getSnap: (snapId: string) => Snap | undefined;
32
39
  };
33
40
  type ManageStateSpecificationBuilderOptions = {
34
41
  allowedCaveats?: Readonly<NonEmptyArray<string>> | null;
@@ -96,20 +103,20 @@ export declare function getEncryptionEntropy({ seed, snapId, cryptographicFuncti
96
103
  * @param hooks.getUnlockPromise - A function that resolves once the MetaMask
97
104
  * extension is unlocked and prompts the user to unlock their MetaMask if it is
98
105
  * locked.
106
+ * @param hooks.getSnap - The hook function to get Snap metadata.
99
107
  * @returns The method implementation which either returns `null` for a
100
108
  * successful state update/deletion or returns the decrypted state.
101
109
  * @throws If the params are invalid.
102
110
  */
103
- export declare function getManageStateImplementation({ getUnlockPromise, clearSnapState, getSnapState, updateSnapState, }: ManageStateMethodHooks): (options: RestrictedMethodOptions<ManageStateParams>) => Promise<ManageStateResult>;
111
+ export declare function getManageStateImplementation({ getUnlockPromise, clearSnapState, getSnapState, updateSnapState, getSnap, }: ManageStateMethodHooks): (options: RestrictedMethodOptions<ManageStateParams>) => Promise<ManageStateResult>;
104
112
  /**
105
113
  * Validates the manageState method `params` and returns them cast to the correct
106
114
  * type. Throws if validation fails.
107
115
  *
108
116
  * @param params - The unvalidated params object from the method request.
109
117
  * @param method - RPC method name used for debugging errors.
110
- * @param storageSizeLimit - Maximum allowed size (in bytes) of a new state object.
111
118
  * @returns The validated method parameter object.
112
119
  */
113
- export declare function getValidatedParams(params: unknown, method: string, storageSizeLimit?: number): ManageStateParams;
120
+ export declare function getValidatedParams(params: unknown, method: string): ManageStateParams;
114
121
  export {};
115
122
  //# sourceMappingURL=manageState.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"manageState.d.mts","sourceRoot":"","sources":["../../src/restricted/manageState.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,sBAAsB,EAAE,2BAA2B;AACjE,OAAO,KAAK,EACV,8BAA8B,EAC9B,uBAAuB,EACvB,4BAA4B,EAC7B,wCAAwC;AACzC,OAAO,EAAE,cAAc,EAAe,wCAAwC;AAE9E,OAAO,KAAK,EAAE,iBAAiB,EAAE,iBAAiB,EAAE,4BAA4B;AAGhF,OAAO,KAAK,EAAE,IAAI,EAAE,aAAa,EAAE,wBAAwB;AAG3D,OAAO,KAAK,EAAE,iBAAiB,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BAA8B,CAC/D,cAAc,CAAC,gBAAgB,EAC/B,sCAAsC,EACtC,wBAAwB,CAYzB,CAAC;AAUF,eAAO,MAAM,kBAAkB;;;wBAzCb,eAAe,gBAAgB;oBACnC,iBAAiB;8BACP,WAAW,mCAAmC,CAAC;wBACrD,SAAS,cAAc,MAAM,CAAC,CAAC,GAAG,IAAI;;;EA0C7C,CAAC;AAEZ,eAAO,MAAM,kBAAkB,WAAa,CAAC;AAE7C,KAAK,oBAAoB,GAAG;IAC1B,MAAM,EAAE,MAAM,CAAC;IACf,IAAI,EAAE,UAAU,CAAC;IACjB,sBAAsB,CAAC,EAAE,sBAAsB,GAAG,SAAS,CAAC;CAC7D,CAAC;AAEF;;;;;;;;;;;;;;GAcG;AACH,wBAAsB,oBAAoB,CAAC,EACzC,IAAI,EACJ,MAAM,EACN,sBAAsB,GACvB,EAAE,oBAAoB,0BAQtB;AAED;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAgB,4BAA4B,CAAC,EAC3C,gBAAgB,EAChB,cAAc,EACd,YAAY,EACZ,eAAe,EACf,OAAO,GACR,EAAE,sBAAsB,aAEZ,wBAAwB,iBAAiB,CAAC,KAClD,QAAQ,iBAAiB,CAAC,CA4D9B;AAED;;;;;;;GAOG;AACH,wBAAgB,kBAAkB,CAChC,MAAM,EAAE,OAAO,EACf,MAAM,EAAE,MAAM,GACb,iBAAiB,CA0CnB"}
@@ -1,8 +1,8 @@
1
1
  import { PermissionType, SubjectType } from "@metamask/permission-controller";
2
2
  import { rpcErrors } from "@metamask/rpc-errors";
3
3
  import { ManageStateOperation } from "@metamask/snaps-sdk";
4
- import { STATE_ENCRYPTION_MAGIC_VALUE } from "@metamask/snaps-utils";
5
- import { isObject, getJsonSize } from "@metamask/utils";
4
+ import { getJsonSizeUnsafe, STATE_ENCRYPTION_MAGIC_VALUE } from "@metamask/snaps-utils";
5
+ import { isObject, isValidJson } from "@metamask/utils";
6
6
  import { deriveEntropyFromSeed } from "../utils.mjs";
7
7
  // The salt used for SIP-6-based entropy derivation.
8
8
  export const STATE_ENCRYPTION_SALT = 'snap_manageState encryption';
@@ -31,6 +31,7 @@ const methodHooks = {
31
31
  clearSnapState: true,
32
32
  getSnapState: true,
33
33
  updateSnapState: true,
34
+ getSnap: true,
34
35
  };
35
36
  export const manageStateBuilder = Object.freeze({
36
37
  targetName: methodName,
@@ -75,14 +76,25 @@ export async function getEncryptionEntropy({ seed, snapId, cryptographicFunction
75
76
  * @param hooks.getUnlockPromise - A function that resolves once the MetaMask
76
77
  * extension is unlocked and prompts the user to unlock their MetaMask if it is
77
78
  * locked.
79
+ * @param hooks.getSnap - The hook function to get Snap metadata.
78
80
  * @returns The method implementation which either returns `null` for a
79
81
  * successful state update/deletion or returns the decrypted state.
80
82
  * @throws If the params are invalid.
81
83
  */
82
- export function getManageStateImplementation({ getUnlockPromise, clearSnapState, getSnapState, updateSnapState, }) {
84
+ export function getManageStateImplementation({ getUnlockPromise, clearSnapState, getSnapState, updateSnapState, getSnap, }) {
83
85
  return async function manageState(options) {
84
86
  const { params = {}, method, context: { origin }, } = options;
85
87
  const validatedParams = getValidatedParams(params, method);
88
+ const snap = getSnap(origin);
89
+ if (!snap?.preinstalled &&
90
+ validatedParams.operation === ManageStateOperation.UpdateState) {
91
+ const size = getJsonSizeUnsafe(validatedParams.newState, true);
92
+ if (size > STORAGE_SIZE_LIMIT) {
93
+ throw rpcErrors.invalidParams({
94
+ message: `Invalid ${method} "newState" parameter: The new state must not exceed ${STORAGE_SIZE_LIMIT / 1000000} MB in size.`,
95
+ });
96
+ }
97
+ }
86
98
  // If the encrypted param is undefined or null we default to true.
87
99
  const shouldEncrypt = validatedParams.encrypted ?? true;
88
100
  // We only need to prompt the user when the mnemonic is needed
@@ -102,6 +114,7 @@ export function getManageStateImplementation({ getUnlockPromise, clearSnapState,
102
114
  await updateSnapState(origin, validatedParams.newState, shouldEncrypt);
103
115
  return null;
104
116
  }
117
+ /* istanbul ignore next */
105
118
  default:
106
119
  throw rpcErrors.invalidParams(`Invalid ${method} operation: "${validatedParams.operation}"`);
107
120
  }
@@ -113,10 +126,9 @@ export function getManageStateImplementation({ getUnlockPromise, clearSnapState,
113
126
  *
114
127
  * @param params - The unvalidated params object from the method request.
115
128
  * @param method - RPC method name used for debugging errors.
116
- * @param storageSizeLimit - Maximum allowed size (in bytes) of a new state object.
117
129
  * @returns The validated method parameter object.
118
130
  */
119
- export function getValidatedParams(params, method, storageSizeLimit = STORAGE_SIZE_LIMIT) {
131
+ export function getValidatedParams(params, method) {
120
132
  if (!isObject(params)) {
121
133
  throw rpcErrors.invalidParams({
122
134
  message: 'Expected params to be a single object.',
@@ -141,21 +153,11 @@ export function getValidatedParams(params, method, storageSizeLimit = STORAGE_SI
141
153
  message: `Invalid ${method} "newState" parameter: The new state must be a plain object.`,
142
154
  });
143
155
  }
144
- let size;
145
- try {
146
- // `getJsonSize` will throw if the state is not JSON serializable.
147
- size = getJsonSize(newState);
148
- }
149
- catch {
156
+ if (!isValidJson(newState)) {
150
157
  throw rpcErrors.invalidParams({
151
158
  message: `Invalid ${method} "newState" parameter: The new state must be JSON serializable.`,
152
159
  });
153
160
  }
154
- if (size > storageSizeLimit) {
155
- throw rpcErrors.invalidParams({
156
- message: `Invalid ${method} "newState" parameter: The new state must not exceed ${storageSizeLimit / 1000000} MB in size.`,
157
- });
158
- }
159
161
  }
160
162
  return params;
161
163
  }
@@ -1 +1 @@
1
- {"version":3,"file":"manageState.mjs","sourceRoot":"","sources":["../../src/restricted/manageState.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,cAAc,EAAE,WAAW,EAAE,wCAAwC;AAC9E,OAAO,EAAE,SAAS,EAAE,6BAA6B;AAEjD,OAAO,EAAE,oBAAoB,EAAE,4BAA4B;AAC3D,OAAO,EAAE,4BAA4B,EAAE,8BAA8B;AAErE,OAAO,EAAE,QAAQ,EAAE,WAAW,EAAE,wBAAwB;AAGxD,OAAO,EAAE,qBAAqB,EAAE,qBAAiB;AAEjD,oDAAoD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EAAE,QAAQ,EAAE,SAAS,EAAE,GAAG,MAAM,CAAC;IAElD,IACE,CAAC,SAAS;QACV,OAAO,SAAS,KAAK,QAAQ;QAC7B,CAAC,MAAM,CAAC,MAAM,CAAC,oBAAoB,CAAC,CAAC,QAAQ,CAC3C,SAAiC,CAClC,EACD,CAAC;QACD,MAAM,SAAS,CAAC,aAAa,CAAC;YAC5B,OAAO,EAAE,gDAAgD;SAC1D,CAAC,CAAC;IACL,CAAC;IAED,IAAI,SAAS,KAAK,SAAS,IAAI,OAAO,SAAS,KAAK,SAAS,EAAE,CAAC;QAC9D,MAAM,SAAS,CAAC,aAAa,CAAC;YAC5B,OAAO,EAAE,uDAAuD;SACjE,CAAC,CAAC;IACL,CAAC;IAED,IAAI,SAAS,KAAK,oBAAoB,CAAC,WAAW,EAAE,CAAC;QACnD,IAAI,CAAC,QAAQ,CAAC,QAAQ,CAAC,EAAE,CAAC;YACxB,MAAM,SAAS,CAAC,aAAa,CAAC;gBAC5B,OAAO,EAAE,WAAW,MAAM,8DAA8D;aACzF,CAAC,CAAC;QACL,CAAC;QAED,IAAI,IAAI,CAAC;QACT,IAAI,CAAC;YACH,kEAAkE;YAClE,IAAI,GAAG,WAAW,CAAC,QAAQ,CAAC,CAAC;QAC/B,CAAC;QAAC,MAAM,CAAC;YACP,MAAM,SAAS,CAAC,aAAa,CAAC;gBAC5B,OAAO,EAAE,WAAW,MAAM,iEAAiE;aAC5F,CAAC,CAAC;QACL,CAAC;QAED,IAAI,IAAI,GAAG,gBAAgB,EAAE,CAAC;YAC5B,MAAM,SAAS,CAAC,aAAa,CAAC;gBAC5B,OAAO,EAAE,WAAW,MAAM,wDACxB,gBAAgB,GAAG,OACrB,cAAc;aACf,CAAC,CAAC;QACL,CAAC;IACH,CAAC;IAED,OAAO,MAA2B,CAAC;AACrC,CAAC","sourcesContent":["import type { CryptographicFunctions } from '@metamask/key-tree';\nimport type {\n PermissionSpecificationBuilder,\n RestrictedMethodOptions,\n ValidPermissionSpecification,\n} from '@metamask/permission-controller';\nimport { PermissionType, SubjectType } from '@metamask/permission-controller';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport type { ManageStateParams, ManageStateResult } from '@metamask/snaps-sdk';\nimport { ManageStateOperation } from '@metamask/snaps-sdk';\nimport { STATE_ENCRYPTION_MAGIC_VALUE } from '@metamask/snaps-utils';\nimport type { Json, NonEmptyArray } from '@metamask/utils';\nimport { isObject, getJsonSize } from '@metamask/utils';\n\nimport type { MethodHooksObject } from '../utils';\nimport { deriveEntropyFromSeed } from '../utils';\n\n// The salt used for SIP-6-based entropy derivation.\nexport const STATE_ENCRYPTION_SALT = 'snap_manageState encryption';\n\nconst methodName = 'snap_manageState';\n\nexport type ManageStateMethodHooks = {\n /**\n * Waits 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 * A function that clears the state of the requesting Snap.\n */\n clearSnapState: (snapId: string, encrypted: boolean) => void;\n\n /**\n * A function that gets the encrypted state of the requesting Snap.\n *\n * @returns The current state of the Snap.\n */\n getSnapState: (\n snapId: string,\n encrypted: boolean,\n ) => Promise<Record<string, Json>>;\n\n /**\n * A function that updates the state of the requesting Snap.\n *\n * @param newState - The new state of the Snap.\n */\n updateSnapState: (\n snapId: string,\n newState: Record<string, Json>,\n encrypted: boolean,\n ) => Promise<void>;\n};\n\ntype ManageStateSpecificationBuilderOptions = {\n allowedCaveats?: Readonly<NonEmptyArray<string>> | null;\n methodHooks: ManageStateMethodHooks;\n};\n\ntype ManageStateSpecification = ValidPermissionSpecification<{\n permissionType: PermissionType.RestrictedMethod;\n targetName: typeof methodName;\n methodImplementation: ReturnType<typeof getManageStateImplementation>;\n allowedCaveats: Readonly<NonEmptyArray<string>> | null;\n}>;\n\n/**\n * The specification builder for the `snap_manageState` permission.\n * `snap_manageState` lets the Snap store and manage some of its state on\n * your device.\n *\n * @param options - The specification builder options.\n * @param options.allowedCaveats - The optional allowed caveats for the permission.\n * @param options.methodHooks - The RPC method hooks needed by the method implementation.\n * @returns The specification for the `snap_manageState` permission.\n */\nexport const specificationBuilder: PermissionSpecificationBuilder<\n PermissionType.RestrictedMethod,\n ManageStateSpecificationBuilderOptions,\n ManageStateSpecification\n> = ({\n allowedCaveats = null,\n methodHooks,\n}: ManageStateSpecificationBuilderOptions) => {\n return {\n permissionType: PermissionType.RestrictedMethod,\n targetName: methodName,\n allowedCaveats,\n methodImplementation: getManageStateImplementation(methodHooks),\n subjectTypes: [SubjectType.Snap],\n };\n};\n\nconst methodHooks: MethodHooksObject<ManageStateMethodHooks> = {\n getUnlockPromise: true,\n clearSnapState: true,\n getSnapState: true,\n updateSnapState: true,\n};\n\nexport const manageStateBuilder = Object.freeze({\n targetName: methodName,\n specificationBuilder,\n methodHooks,\n} as const);\n\nexport const STORAGE_SIZE_LIMIT = 64_000_000; // In bytes (64 MB)\n\ntype GetEncryptionKeyArgs = {\n snapId: string;\n seed: Uint8Array;\n cryptographicFunctions?: CryptographicFunctions | undefined;\n};\n\n/**\n * Get a deterministic encryption key to use for encrypting and decrypting the\n * state.\n *\n * This key should only be used for state encryption using `snap_manageState`.\n * To get other encryption keys, a different salt can be used.\n *\n * @param args - The encryption key args.\n * @param args.snapId - The ID of the snap to get the encryption key for.\n * @param args.seed - The mnemonic seed to derive the encryption key\n * from.\n * @param args.cryptographicFunctions - The cryptographic functions to use for\n * the client.\n * @returns The state encryption key.\n */\nexport async function getEncryptionEntropy({\n seed,\n snapId,\n cryptographicFunctions,\n}: GetEncryptionKeyArgs) {\n return await deriveEntropyFromSeed({\n seed,\n input: snapId,\n salt: STATE_ENCRYPTION_SALT,\n magic: STATE_ENCRYPTION_MAGIC_VALUE,\n cryptographicFunctions,\n });\n}\n\n/**\n * Builds the method implementation for `snap_manageState`.\n *\n * @param hooks - The RPC method hooks.\n * @param hooks.clearSnapState - A function that clears the state stored for a\n * snap.\n * @param hooks.getSnapState - A function that fetches the persisted decrypted\n * state for a snap.\n * @param hooks.updateSnapState - A function that updates the state stored for a\n * snap.\n * @param hooks.getUnlockPromise - A function that resolves once the MetaMask\n * extension is unlocked and prompts the user to unlock their MetaMask if it is\n * locked.\n * @returns The method implementation which either returns `null` for a\n * successful state update/deletion or returns the decrypted state.\n * @throws If the params are invalid.\n */\nexport function getManageStateImplementation({\n getUnlockPromise,\n clearSnapState,\n getSnapState,\n updateSnapState,\n}: ManageStateMethodHooks) {\n return async function manageState(\n options: RestrictedMethodOptions<ManageStateParams>,\n ): Promise<ManageStateResult> {\n const {\n params = {},\n method,\n context: { origin },\n } = options;\n const validatedParams = getValidatedParams(params, method);\n\n // If the encrypted param is undefined or null we default to true.\n const shouldEncrypt = validatedParams.encrypted ?? true;\n\n // We only need to prompt the user when the mnemonic is needed\n // which it isn't for the clear operation or unencrypted storage.\n if (\n shouldEncrypt &&\n validatedParams.operation !== ManageStateOperation.ClearState\n ) {\n await getUnlockPromise(true);\n }\n\n switch (validatedParams.operation) {\n case ManageStateOperation.ClearState:\n clearSnapState(origin, shouldEncrypt);\n return null;\n\n case ManageStateOperation.GetState: {\n return await getSnapState(origin, shouldEncrypt);\n }\n\n case ManageStateOperation.UpdateState: {\n await updateSnapState(origin, validatedParams.newState, shouldEncrypt);\n return null;\n }\n\n default:\n throw rpcErrors.invalidParams(\n `Invalid ${method} operation: \"${\n validatedParams.operation as string\n }\"`,\n );\n }\n };\n}\n\n/**\n * Validates the manageState 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 * @param method - RPC method name used for debugging errors.\n * @param storageSizeLimit - Maximum allowed size (in bytes) of a new state object.\n * @returns The validated method parameter object.\n */\nexport function getValidatedParams(\n params: unknown,\n method: string,\n storageSizeLimit = STORAGE_SIZE_LIMIT,\n): ManageStateParams {\n if (!isObject(params)) {\n throw rpcErrors.invalidParams({\n message: 'Expected params to be a single object.',\n });\n }\n\n const { operation, newState, encrypted } = params;\n\n if (\n !operation ||\n typeof operation !== 'string' ||\n !Object.values(ManageStateOperation).includes(\n operation as ManageStateOperation,\n )\n ) {\n throw rpcErrors.invalidParams({\n message: 'Must specify a valid manage state \"operation\".',\n });\n }\n\n if (encrypted !== undefined && typeof encrypted !== 'boolean') {\n throw rpcErrors.invalidParams({\n message: '\"encrypted\" parameter must be a boolean if specified.',\n });\n }\n\n if (operation === ManageStateOperation.UpdateState) {\n if (!isObject(newState)) {\n throw rpcErrors.invalidParams({\n message: `Invalid ${method} \"newState\" parameter: The new state must be a plain object.`,\n });\n }\n\n let size;\n try {\n // `getJsonSize` will throw if the state is not JSON serializable.\n size = getJsonSize(newState);\n } catch {\n throw rpcErrors.invalidParams({\n message: `Invalid ${method} \"newState\" parameter: The new state must be JSON serializable.`,\n });\n }\n\n if (size > storageSizeLimit) {\n throw rpcErrors.invalidParams({\n message: `Invalid ${method} \"newState\" parameter: The new state must not exceed ${\n storageSizeLimit / 1_000_000\n } MB in size.`,\n });\n }\n }\n\n return params as ManageStateParams;\n}\n"]}
1
+ {"version":3,"file":"manageState.mjs","sourceRoot":"","sources":["../../src/restricted/manageState.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,cAAc,EAAE,WAAW,EAAE,wCAAwC;AAC9E,OAAO,EAAE,SAAS,EAAE,6BAA6B;AAEjD,OAAO,EAAE,oBAAoB,EAAE,4BAA4B;AAE3D,OAAO,EACL,iBAAiB,EACjB,4BAA4B,EAC7B,8BAA8B;AAE/B,OAAO,EAAE,QAAQ,EAAE,WAAW,EAAE,wBAAwB;AAGxD,OAAO,EAAE,qBAAqB,EAAE,qBAAiB;AAEjD,oDAAoD;AACpD,MAAM,CAAC,MAAM,qBAAqB,GAAG,6BAA6B,CAAC;AAEnE,MAAM,UAAU,GAAG,kBAAkB,CAAC;AAwDtC;;;;;;;;;GASG;AACH,MAAM,CAAC,MAAM,oBAAoB,GAI7B,CAAC,EACH,cAAc,GAAG,IAAI,EACrB,WAAW,GAC4B,EAAE,EAAE;IAC3C,OAAO;Q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,MAAM,UAAU,kBAAkB,CAChC,MAAe,EACf,MAAc;IAEd,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,EAAE,CAAC;QACtB,MAAM,SAAS,CAAC,aAAa,CAAC;YAC5B,OAAO,EAAE,wCAAwC;SAClD,CAAC,CAAC;IACL,CAAC;IAED,MAAM,EAAE,SAAS,EAAE,QAAQ,EAAE,SAAS,EAAE,GAAG,MAAM,CAAC;IAElD,IACE,CAAC,SAAS;QACV,OAAO,SAAS,KAAK,QAAQ;QAC7B,CAAC,MAAM,CAAC,MAAM,CAAC,oBAAoB,CAAC,CAAC,QAAQ,CAC3C,SAAiC,CAClC,EACD,CAAC;QACD,MAAM,SAAS,CAAC,aAAa,CAAC;YAC5B,OAAO,EAAE,gDAAgD;SAC1D,CAAC,CAAC;IACL,CAAC;IAED,IAAI,SAAS,KAAK,SAAS,IAAI,OAAO,SAAS,KAAK,SAAS,EAAE,CAAC;QAC9D,MAAM,SAAS,CAAC,aAAa,CAAC;YAC5B,OAAO,EAAE,uDAAuD;SACjE,CAAC,CAAC;IACL,CAAC;IAED,IAAI,SAAS,KAAK,oBAAoB,CAAC,WAAW,EAAE,CAAC;QACnD,IAAI,CAAC,QAAQ,CAAC,QAAQ,CAAC,EAAE,CAAC;YACxB,MAAM,SAAS,CAAC,aAAa,CAAC;gBAC5B,OAAO,EAAE,WAAW,MAAM,8DAA8D;aACzF,CAAC,CAAC;QACL,CAAC;QAED,IAAI,CAAC,WAAW,CAAC,QAAQ,CAAC,EAAE,CAAC;YAC3B,MAAM,SAAS,CAAC,aAAa,CAAC;gBAC5B,OAAO,EAAE,WAAW,MAAM,iEAAiE;aAC5F,CAAC,CAAC;QACL,CAAC;IACH,CAAC;IAED,OAAO,MAA2B,CAAC;AACrC,CAAC","sourcesContent":["import type { CryptographicFunctions } from '@metamask/key-tree';\nimport type {\n PermissionSpecificationBuilder,\n RestrictedMethodOptions,\n ValidPermissionSpecification,\n} from '@metamask/permission-controller';\nimport { PermissionType, SubjectType } from '@metamask/permission-controller';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport type { ManageStateParams, ManageStateResult } from '@metamask/snaps-sdk';\nimport { ManageStateOperation } from '@metamask/snaps-sdk';\nimport type { Snap } from '@metamask/snaps-utils';\nimport {\n getJsonSizeUnsafe,\n STATE_ENCRYPTION_MAGIC_VALUE,\n} from '@metamask/snaps-utils';\nimport type { Json, NonEmptyArray } from '@metamask/utils';\nimport { isObject, isValidJson } from '@metamask/utils';\n\nimport type { MethodHooksObject } from '../utils';\nimport { deriveEntropyFromSeed } from '../utils';\n\n// The salt used for SIP-6-based entropy derivation.\nexport const STATE_ENCRYPTION_SALT = 'snap_manageState encryption';\n\nconst methodName = 'snap_manageState';\n\nexport type ManageStateMethodHooks = {\n /**\n * Waits 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 * A function that clears the state of the requesting Snap.\n */\n clearSnapState: (snapId: string, encrypted: boolean) => void;\n\n /**\n * A function that gets the encrypted state of the requesting Snap.\n *\n * @returns The current state of the Snap.\n */\n getSnapState: (\n snapId: string,\n encrypted: boolean,\n ) => Promise<Record<string, Json>>;\n\n /**\n * A function that updates the state of the requesting Snap.\n *\n * @param newState - The new state of the Snap.\n */\n updateSnapState: (\n snapId: string,\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\ntype ManageStateSpecificationBuilderOptions = {\n allowedCaveats?: Readonly<NonEmptyArray<string>> | null;\n methodHooks: ManageStateMethodHooks;\n};\n\ntype ManageStateSpecification = ValidPermissionSpecification<{\n permissionType: PermissionType.RestrictedMethod;\n targetName: typeof methodName;\n methodImplementation: ReturnType<typeof getManageStateImplementation>;\n allowedCaveats: Readonly<NonEmptyArray<string>> | null;\n}>;\n\n/**\n * The specification builder for the `snap_manageState` permission.\n * `snap_manageState` lets the Snap store and manage some of its state on\n * your device.\n *\n * @param options - The specification builder options.\n * @param options.allowedCaveats - The optional allowed caveats for the permission.\n * @param options.methodHooks - The RPC method hooks needed by the method implementation.\n * @returns The specification for the `snap_manageState` permission.\n */\nexport const specificationBuilder: PermissionSpecificationBuilder<\n PermissionType.RestrictedMethod,\n ManageStateSpecificationBuilderOptions,\n ManageStateSpecification\n> = ({\n allowedCaveats = null,\n methodHooks,\n}: ManageStateSpecificationBuilderOptions) => {\n return {\n permissionType: PermissionType.RestrictedMethod,\n targetName: methodName,\n allowedCaveats,\n methodImplementation: getManageStateImplementation(methodHooks),\n subjectTypes: [SubjectType.Snap],\n };\n};\n\nconst methodHooks: MethodHooksObject<ManageStateMethodHooks> = {\n getUnlockPromise: true,\n clearSnapState: true,\n getSnapState: true,\n updateSnapState: true,\n getSnap: true,\n};\n\nexport const manageStateBuilder = Object.freeze({\n targetName: methodName,\n specificationBuilder,\n methodHooks,\n} as const);\n\nexport const STORAGE_SIZE_LIMIT = 64_000_000; // In bytes (64 MB)\n\ntype GetEncryptionKeyArgs = {\n snapId: string;\n seed: Uint8Array;\n cryptographicFunctions?: CryptographicFunctions | undefined;\n};\n\n/**\n * Get a deterministic encryption key to use for encrypting and decrypting the\n * state.\n *\n * This key should only be used for state encryption using `snap_manageState`.\n * To get other encryption keys, a different salt can be used.\n *\n * @param args - The encryption key args.\n * @param args.snapId - The ID of the snap to get the encryption key for.\n * @param args.seed - The mnemonic seed to derive the encryption key\n * from.\n * @param args.cryptographicFunctions - The cryptographic functions to use for\n * the client.\n * @returns The state encryption key.\n */\nexport async function getEncryptionEntropy({\n seed,\n snapId,\n cryptographicFunctions,\n}: GetEncryptionKeyArgs) {\n return await deriveEntropyFromSeed({\n seed,\n input: snapId,\n salt: STATE_ENCRYPTION_SALT,\n magic: STATE_ENCRYPTION_MAGIC_VALUE,\n cryptographicFunctions,\n });\n}\n\n/**\n * Builds the method implementation for `snap_manageState`.\n *\n * @param hooks - The RPC method hooks.\n * @param hooks.clearSnapState - A function that clears the state stored for a\n * snap.\n * @param hooks.getSnapState - A function that fetches the persisted decrypted\n * state for a snap.\n * @param hooks.updateSnapState - A function that updates the state stored for a\n * snap.\n * @param hooks.getUnlockPromise - A function that resolves once the MetaMask\n * extension is unlocked and prompts the user to unlock their MetaMask if it is\n * locked.\n * @param hooks.getSnap - The hook function to get Snap metadata.\n * @returns The method implementation which either returns `null` for a\n * successful state update/deletion or returns the decrypted state.\n * @throws If the params are invalid.\n */\nexport function getManageStateImplementation({\n getUnlockPromise,\n clearSnapState,\n getSnapState,\n updateSnapState,\n getSnap,\n}: ManageStateMethodHooks) {\n return async function manageState(\n options: RestrictedMethodOptions<ManageStateParams>,\n ): Promise<ManageStateResult> {\n const {\n params = {},\n method,\n context: { origin },\n } = options;\n const validatedParams = getValidatedParams(params, method);\n\n const snap = getSnap(origin);\n\n if (\n !snap?.preinstalled &&\n validatedParams.operation === ManageStateOperation.UpdateState\n ) {\n const size = getJsonSizeUnsafe(validatedParams.newState, true);\n\n if (size > STORAGE_SIZE_LIMIT) {\n throw rpcErrors.invalidParams({\n message: `Invalid ${method} \"newState\" parameter: The new state must not exceed ${\n STORAGE_SIZE_LIMIT / 1_000_000\n } MB in size.`,\n });\n }\n }\n\n // If the encrypted param is undefined or null we default to true.\n const shouldEncrypt = validatedParams.encrypted ?? true;\n\n // We only need to prompt the user when the mnemonic is needed\n // which it isn't for the clear operation or unencrypted storage.\n if (\n shouldEncrypt &&\n validatedParams.operation !== ManageStateOperation.ClearState\n ) {\n await getUnlockPromise(true);\n }\n\n switch (validatedParams.operation) {\n case ManageStateOperation.ClearState:\n clearSnapState(origin, shouldEncrypt);\n return null;\n\n case ManageStateOperation.GetState: {\n return await getSnapState(origin, shouldEncrypt);\n }\n\n case ManageStateOperation.UpdateState: {\n await updateSnapState(origin, validatedParams.newState, shouldEncrypt);\n return null;\n }\n\n /* istanbul ignore next */\n default:\n throw rpcErrors.invalidParams(\n `Invalid ${method} operation: \"${\n validatedParams.operation as string\n }\"`,\n );\n }\n };\n}\n\n/**\n * Validates the manageState 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 * @param method - RPC method name used for debugging errors.\n * @returns The validated method parameter object.\n */\nexport function getValidatedParams(\n params: unknown,\n method: string,\n): ManageStateParams {\n if (!isObject(params)) {\n throw rpcErrors.invalidParams({\n message: 'Expected params to be a single object.',\n });\n }\n\n const { operation, newState, encrypted } = params;\n\n if (\n !operation ||\n typeof operation !== 'string' ||\n !Object.values(ManageStateOperation).includes(\n operation as ManageStateOperation,\n )\n ) {\n throw rpcErrors.invalidParams({\n message: 'Must specify a valid manage state \"operation\".',\n });\n }\n\n if (encrypted !== undefined && typeof encrypted !== 'boolean') {\n throw rpcErrors.invalidParams({\n message: '\"encrypted\" parameter must be a boolean if specified.',\n });\n }\n\n if (operation === ManageStateOperation.UpdateState) {\n if (!isObject(newState)) {\n throw rpcErrors.invalidParams({\n message: `Invalid ${method} \"newState\" parameter: The new state must be a plain object.`,\n });\n }\n\n if (!isValidJson(newState)) {\n throw rpcErrors.invalidParams({\n message: `Invalid ${method} \"newState\" parameter: The new state must be JSON serializable.`,\n });\n }\n }\n\n return params as ManageStateParams;\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@metamask/snaps-rpc-methods",
3
- "version": "13.5.1",
3
+ "version": "13.5.3",
4
4
  "description": "MetaMask Snaps JSON-RPC method implementations",
5
5
  "keywords": [
6
6
  "MetaMask",
@@ -58,16 +58,16 @@
58
58
  "@metamask/key-tree": "^10.1.1",
59
59
  "@metamask/permission-controller": "^11.0.6",
60
60
  "@metamask/rpc-errors": "^7.0.3",
61
- "@metamask/snaps-sdk": "^9.3.0",
62
- "@metamask/snaps-utils": "^11.5.0",
61
+ "@metamask/snaps-sdk": "^10.0.0",
62
+ "@metamask/snaps-utils": "^11.6.0",
63
63
  "@metamask/superstruct": "^3.2.1",
64
- "@metamask/utils": "^11.4.2",
64
+ "@metamask/utils": "^11.8.1",
65
65
  "@noble/hashes": "^1.7.1"
66
66
  },
67
67
  "devDependencies": {
68
- "@lavamoat/allow-scripts": "^3.3.4",
68
+ "@lavamoat/allow-scripts": "^3.4.0",
69
69
  "@metamask/auto-changelog": "^5.0.2",
70
- "@metamask/json-rpc-engine": "^10.0.2",
70
+ "@metamask/json-rpc-engine": "^10.1.0",
71
71
  "@swc/core": "1.11.31",
72
72
  "@swc/jest": "^0.2.38",
73
73
  "@ts-bridge/cli": "^0.6.1",