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E,CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;QACrC,MAAM,UAAU,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC;QAC3B,IAAI,cAAc,CAAC,QAAQ,CAAC,UAAU,CAAC,EAAE,CAAC;YACxC,MAAM,SAAS,CAAC,aAAa,CAC3B,oDAAoD,CACrD,CAAC;QACJ,CAAC;QAED,IAAI,QAAQ,CAAC,MAAM,CAAC,EAAE,CAAC;YACrB,IAAI,CAAC,WAAW,CAAC,MAAM,EAAE,UAAU,CAAC,EAAE,CAAC;gBACrC,OAAO,IAAI,CAAC;YACd,CAAC;YAED,MAAM,GAAG,MAAM,CAAC,UAAU,CAAC,CAAC;YAC5B,SAAS;QACX,CAAC;QAED,OAAO,IAAI,CAAC;IACd,CAAC;IAED,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import type {\n  JsonRpcEngineEndCallback,\n  MethodHandler,\n} from '@metamask/json-rpc-engine';\nimport type { Messenger } from '@metamask/messenger';\nimport type { PermissionControllerHasPermissionAction } from '@metamask/permission-controller';\nimport { providerErrors, rpcErrors } from '@metamask/rpc-errors';\nimport type { GetStateParams, GetStateResult } from '@metamask/snaps-sdk';\nimport { type InferMatching } from '@metamask/snaps-utils';\nimport {\n  boolean,\n  create,\n  object,\n  optional,\n  StructError,\n} from '@metamask/superstruct';\nimport type { PendingJsonRpcResponse, Json } from '@metamask/utils';\nimport { hasProperty, isObject } from '@metamask/utils';\n\nimport { manageStateBuilder } from '../restricted/manageState';\nimport type {\n  JsonRpcRequestWithOrigin,\n  SnapControllerGetSnapStateAction,\n} from '../types';\nimport type { MethodHooksObject } from '../utils';\nimport { FORBIDDEN_KEYS, StateKeyStruct } from '../utils';\n\nconst hookNames: MethodHooksObject<GetStateMethodHooks> = {\n  getUnlockPromise: true,\n};\n\nexport type GetStateMethodHooks = {\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\nexport type GetStateMethodActions =\n  | PermissionControllerHasPermissionAction\n  | SnapControllerGetSnapStateAction;\n\n/**\n * Get the state of the Snap, or a specific value within the state. By default,\n * the data is automatically encrypted using a Snap-specific key and\n * automatically decrypted when retrieved. You can set `encrypted` to `false` to\n * use unencrypted storage (available when the client is locked).\n *\n * @example\n * ```json name=\"Manifest\"\n * {\n *   \"initialPermissions\": {\n *     \"snap_manageState\": {}\n *   }\n * }\n * ```\n * ```ts name=\"Usage\"\n * const state = await snap.request({\n *   method: 'snap_getState',\n *   params: {\n *     key: 'some.nested.value', // Optional, defaults to entire state\n *     encrypted: true, // Optional, defaults to `true`\n *   },\n * });\n * ```\n */\nexport const getStateHandler = {\n  implementation: getStateImplementation,\n  hookNames,\n  actionNames: [\n    'PermissionController:hasPermission',\n    'SnapController:getSnapState',\n  ],\n} satisfies MethodHandler<\n  GetStateMethodHooks,\n  GetStateMethodActions,\n  GetStateParameters,\n  GetStateResult,\n  { origin: string }\n>;\n\nconst GetStateParametersStruct = object({\n  key: optional(StateKeyStruct),\n  encrypted: optional(boolean()),\n});\n\nexport type GetStateParameters = InferMatching<\n  typeof GetStateParametersStruct,\n  GetStateParams\n>;\n\n/**\n * The `snap_getState` 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.getUnlockPromise - Wait for the extension to be unlocked.\n * @param messenger - The messenger used to call controller actions.\n * @returns Nothing.\n */\nasync function getStateImplementation(\n  request: JsonRpcRequestWithOrigin<GetStateParameters>,\n  // `GetStateResult` is an alias for `Json` (which is the default type argument\n  // for `PendingJsonRpcResponse`), but that may not be the case in the future.\n  // We use `GetStateResult` here to make it clear that this is the expected\n  // type of the result.\n  // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-arguments\n  response: PendingJsonRpcResponse<GetStateResult>,\n  _next: unknown,\n  end: JsonRpcEngineEndCallback,\n  { getUnlockPromise }: GetStateMethodHooks,\n  messenger: Messenger<string, GetStateMethodActions>,\n): Promise<void> {\n  const { params, origin } = request;\n\n  if (\n    !messenger.call(\n      'PermissionController:hasPermission',\n      origin,\n      manageStateBuilder.targetName,\n    )\n  ) {\n    return end(providerErrors.unauthorized());\n  }\n\n  try {\n    const validatedParams = getValidatedParams(params);\n    const { key, encrypted = true } = validatedParams;\n\n    if (encrypted) {\n      await getUnlockPromise(true);\n    }\n\n    const state = await messenger.call(\n      'SnapController:getSnapState',\n      origin,\n      encrypted,\n    );\n    response.result = get(state, key);\n  } catch (error) {\n    return end(error);\n  }\n\n  return end();\n}\n\n/**\n * Validate the parameters of the `snap_getState` 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, GetStateParametersStruct);\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 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, `null` is returned.\n *\n * This is a simplified version of Lodash's `get` function, but Lodash doesn't\n * seem to be maintained anymore, so we're using our own implementation.\n *\n * @param value - The object to get the key from.\n * @param key - The key to get.\n * @returns The value of the key in the object, or `null` if the key does not\n * exist.\n */\nexport function get(\n  value: Record<string, Json> | null,\n  key?: string | undefined,\n): Json {\n  if (key === undefined) {\n    return value;\n  }\n\n  const keys = key.split('.');\n  let result: Json = value;\n\n  // Intentionally using a classic for loop here for performance reasons.\n  // eslint-disable-next-line @typescript-eslint/prefer-for-of\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 (isObject(result)) {\n      if (!hasProperty(result, currentKey)) {\n        return null;\n      }\n\n      result = result[currentKey];\n      continue;\n    }\n\n    return null;\n  }\n\n  return result;\n}\n"]}