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AAE,iBAAiB;4BACjC,cAAc,EAAE,iBAAiB;4BACjC,iBAAiB,EAAE,EAAE;4BACrB,kBAAkB,EAAE,KAAK;yBAC1B;qBACF;iBACF;aACF;SACF,CAAC,CAAC;QAEH,OAAO,IAAI,EAAE,CAAC;IAChB,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import type { JsonRpcMiddleware } from '@metamask/json-rpc-engine';\nimport type {\n  PermissionConstraint,\n  RequestedPermissions,\n} from '@metamask/permission-controller';\nimport { isEqual } from '@metamask/snaps-utils';\nimport {\n  type CaipAccountId,\n  type CaipChainId,\n  hasProperty,\n  type Json,\n  type JsonRpcParams,\n} from '@metamask/utils';\n\nimport { SnapEndowments } from '../endowments';\n\nexport type PreinstalledSnapsMiddlewareHooks = {\n  /**\n   * Get all available scopes with the eip155 prefix.\n   *\n   * @returns A list of all available scopes.\n   */\n  getEvmScopes: () => CaipChainId[];\n  /**\n   * Get all accounts with the eip155 scope.\n   *\n   * @returns A list of all account addresses from the eip155 scope.\n   */\n  getAllEvmAccounts: () => string[];\n  /**\n   * Get the current permissions for the requesting origin.\n   *\n   * @returns An object containing the metadata about each permission.\n   */\n  getPermissions: () => Record<string, PermissionConstraint> | undefined;\n  /**\n   * Grant the passed permissions to the origin.\n   *\n   * @param permissions\n   */\n  grantPermissions: (permissions: RequestedPermissions) => void;\n};\n\ntype ScopesObject = Record<CaipChainId, { accounts: CaipAccountId[] }>;\n\ntype AuthorizedScopeCaveat = {\n  requiredScopes: ScopesObject;\n  optionalScopes: ScopesObject;\n  sessionProperties: Record<string, Json>;\n  isMultichainOrigin: boolean;\n};\n\n/**\n * Create a scopes object for a set of scopes and accounts.\n *\n * @param scopes - The scopes.\n * @param accounts - The accounts.\n * @returns The ScopesObject\n */\nfunction createScopesObject(\n  scopes: CaipChainId[],\n  accounts: string[],\n): ScopesObject {\n  return scopes.reduce<ScopesObject>((accumulator, scope) => {\n    accumulator[scope] = {\n      accounts: accounts.map((account): CaipAccountId => `${scope}:${account}`),\n    };\n    return accumulator;\n  }, {});\n}\n\n/**\n * Create a middleware that automatically grants account permissions to preinstalled Snaps\n * that want to use the Ethereum provider endowment.\n *\n * @param hooks - The hooks used by the middleware.\n * @param hooks.getEvmScopes - Hook for retrieving all available EVM scopes.\n * @param hooks.getAllEvmAccounts - Hook for retrieving all available EVM addresses.\n * @param hooks.getPermissions - Hook for retrieving the permissions of the requesting origin.\n * @param hooks.grantPermissions - Hook for granting permissions to the requesting origin.\n * @returns The middleware.\n */\nexport function createPreinstalledSnapsMiddleware({\n  getEvmScopes,\n  getAllEvmAccounts,\n  getPermissions,\n  grantPermissions,\n}: PreinstalledSnapsMiddlewareHooks): JsonRpcMiddleware<JsonRpcParams, Json> {\n  return function methodMiddleware(request, _response, next, _end) {\n    if (request.method.startsWith('snap')) {\n      return next();\n    }\n\n    const permissions = getPermissions();\n\n    if (\n      !permissions ||\n      !hasProperty(permissions, SnapEndowments.EthereumProvider)\n    ) {\n      return next();\n    }\n\n    const existingEndowment = permissions['endowment:caip25'];\n    const existingCaveat = existingEndowment?.caveats?.find(\n      (caveat) => caveat.type === 'authorizedScopes',\n    )?.value as AuthorizedScopeCaveat | undefined;\n\n    const existingRequiredScopes = existingCaveat?.requiredScopes ?? {};\n    const existingOptionalScopes = existingCaveat?.optionalScopes ?? {};\n\n    const evmScopes = getEvmScopes();\n    const evmAccounts = getAllEvmAccounts();\n\n    const hasAllAccounts = evmScopes.every((scope) => {\n      const existingScope =\n        existingRequiredScopes[scope] ?? existingOptionalScopes[scope];\n      const existingScopedAccounts =\n        existingScope?.accounts.map((account) =>\n          account.slice(scope.length + 1),\n        ) ?? [];\n      return isEqual(evmAccounts, existingScopedAccounts);\n    });\n\n    if (hasAllAccounts) {\n      return next();\n    }\n\n    const requiredScopes = Object.keys(existingRequiredScopes) as CaipChainId[];\n    const newRequiredScopes = createScopesObject(requiredScopes, evmAccounts);\n\n    const optionalScopes = evmScopes.filter(\n      (scope) => !requiredScopes.includes(scope),\n    );\n    const newOptionalScopes = {\n      ...createScopesObject(optionalScopes, evmAccounts),\n      'wallet:eip155': { accounts: [] },\n    };\n\n    grantPermissions({\n      'endowment:caip25': {\n        caveats: [\n          {\n            type: 'authorizedScopes',\n            value: {\n              requiredScopes: newRequiredScopes,\n              optionalScopes: newOptionalScopes,\n              sessionProperties: {},\n              isMultichainOrigin: false,\n            },\n          },\n        ],\n      },\n    });\n\n    return next();\n  };\n}\n"]}