UNPKG

@metamask/snaps-rpc-methods

Version:
1 lines 8.22 kB
{"version":3,"file":"getState.cjs","sourceRoot":"","sources":["../../src/permitted/getState.ts"],"names":[],"mappings":";;;AAEA,qDAAiE;AAGjE,uDAM+B;AAM/B,2CAAwD;AAExD,+DAA+D;AAE/D,wCAA0D;AAE1D,MAAM,SAAS,GAAqC;IAClD,aAAa,EAAE,IAAI;IACnB,YAAY,EAAE,IAAI;IAClB,gBAAgB,EAAE,IAAI;CACvB,CAAC;AAEF;;GAEG;AACU,QAAA,eAAe,GAIxB;IACF,WAAW,EAAE,CAAC,eAAe,CAAC;IAC9B,cAAc,EAAE,sBAAsB;IACtC,SAAS;CACV,CAAC;AA0BF,MAAM,wBAAwB,GAAG,IAAA,oBAAM,EAAC;IACtC,GAAG,EAAE,IAAA,sBAAQ,EAAC,sBAAc,CAAC;IAC7B,SAAS,EAAE,IAAA,sBAAQ,EAAC,IAAA,qBAAO,GAAE,CAAC;CAC/B,CAAC,CAAC;AAOH;;;;;;;;;;;;;;GAcG;AACH,KAAK,UAAU,sBAAsB,CACnC,OAA2C;AAC3C,8EAA8E;AAC9E,6EAA6E;AAC7E,0EAA0E;AAC1E,sBAAsB;AACtB,4EAA4E;AAC5E,QAAgD,EAChD,KAAc,EACd,GAA6B,EAC7B,EAAE,aAAa,EAAE,YAAY,EAAE,gBAAgB,EAAiB;IAEhE,MAAM,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC;IAE3B,IAAI,CAAC,aAAa,CAAC,gCAAkB,CAAC,UAAU,CAAC,EAAE,CAAC;QAClD,OAAO,GAAG,CAAC,2BAAc,CAAC,YAAY,EAAE,CAAC,CAAC;IAC5C,CAAC;IAED,IAAI,CAAC;QACH,MAAM,eAAe,GAAG,kBAAkB,CAAC,MAAM,CAAC,CAAC;QACnD,MAAM,EAAE,GAAG,EAAE,SAAS,GAAG,IAAI,EAAE,GAAG,eAAe,CAAC;QAElD,IAAI,SAAS,EAAE,CAAC;YACd,MAAM,gBAAgB,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M,sBAAS,CAAC,aAAa,CAC3B,oDAAoD,CACrD,CAAC;QACJ,CAAC;QAED,IAAI,IAAA,gBAAQ,EAAC,MAAM,CAAC,EAAE,CAAC;YACrB,IAAI,CAAC,IAAA,mBAAW,EAAC,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;AAlCD,kBAkCC","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 { 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 {\n PendingJsonRpcResponse,\n Json,\n JsonRpcRequest,\n} from '@metamask/utils';\nimport { hasProperty, isObject } from '@metamask/utils';\n\nimport { manageStateBuilder } from '../restricted/manageState';\nimport type { MethodHooksObject } from '../utils';\nimport { FORBIDDEN_KEYS, StateKeyStruct } from '../utils';\n\nconst hookNames: MethodHooksObject<GetStateHooks> = {\n hasPermission: true,\n getSnapState: true,\n getUnlockPromise: true,\n};\n\n/**\n * `snap_getState` gets the state of the Snap.\n */\nexport const getStateHandler: PermittedHandlerExport<\n GetStateHooks,\n GetStateParameters,\n GetStateResult\n> = {\n methodNames: ['snap_getState'],\n implementation: getStateImplementation,\n hookNames,\n};\n\nexport type GetStateHooks = {\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 * @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\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.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 * @returns Nothing.\n */\nasync function getStateImplementation(\n request: JsonRpcRequest<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 { hasPermission, getSnapState, getUnlockPromise }: GetStateHooks,\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, encrypted = true } = validatedParams;\n\n if (encrypted) {\n await getUnlockPromise(true);\n }\n\n const state = await getSnapState(encrypted);\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"]}