creation_sourcecode: {{
    "sources": {
      "lib/aave-collector-unification/src/interfaces/ICollector.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {IERC20} from 'solidity-utils/contracts/oz-common/interfaces/IERC20.sol';\n\ninterface ICollector {\n  struct Stream {\n    uint256 deposit;\n    uint256 ratePerSecond;\n    uint256 remainingBalance;\n    uint256 startTime;\n    uint256 stopTime;\n    address recipient;\n    address sender;\n    address tokenAddress;\n    bool isEntity;\n  }\n\n  /** @notice Emitted when the funds admin changes\n   * @param fundsAdmin The new funds admin.\n   **/\n  event NewFundsAdmin(address indexed fundsAdmin);\n\n  /** @notice Emitted when the new stream is created\n   * @param streamId The identifier of the stream.\n   * @param sender The address of the collector.\n   * @param recipient The address towards which the money is streamed.\n   * @param deposit The amount of money to be streamed.\n   * @param tokenAddress The ERC20 token to use as streaming currency.\n   * @param startTime The unix timestamp for when the stream starts.\n   * @param stopTime The unix timestamp for when the stream stops.\n   **/\n  event CreateStream(\n    uint256 indexed streamId,\n    address indexed sender,\n    address indexed recipient,\n    uint256 deposit,\n    address tokenAddress,\n    uint256 startTime,\n    uint256 stopTime\n  );\n\n  /**\n   * @notice Emmitted when withdraw happens from the contract to the recipient's account.\n   * @param streamId The id of the stream to withdraw tokens from.\n   * @param recipient The address towards which the money is streamed.\n   * @param amount The amount of tokens to withdraw.\n   */\n  event WithdrawFromStream(uint256 indexed streamId, address indexed recipient, uint256 amount);\n\n  /**\n   * @notice Emmitted when the stream is canceled.\n   * @param streamId The id of the stream to withdraw tokens from.\n   * @param sender The address of the collector.\n   * @param recipient The address towards which the money is streamed.\n   * @param senderBalance The sender's balance at the moment of cancelling.\n   * @param recipientBalance The recipient's balance at the moment of cancelling.\n   */\n  event CancelStream(\n    uint256 indexed streamId,\n    address indexed sender,\n    address indexed recipient,\n    uint256 senderBalance,\n    uint256 recipientBalance\n  );\n\n  /** @notice Returns the mock ETH reference address\n   * @return address The address\n   **/\n  function ETH_MOCK_ADDRESS() external pure returns (address);\n\n  /** @notice Initializes the contracts\n   * @param fundsAdmin Funds admin address\n   * @param nextStreamId StreamId to set, applied if greater than 0\n   **/\n  function initialize(address fundsAdmin, uint256 nextStreamId) external;\n\n  /**\n   * @notice Return the funds admin, only entity to be able to interact with this contract (controller of reserve)\n   * @return address The address of the funds admin\n   **/\n  function getFundsAdmin() external view returns (address);\n\n  /**\n   * @notice Returns the available funds for the given stream id and address.\n   * @param streamId The id of the stream for which to query the balance.\n   * @param who The address for which to query the balance.\n   * @notice Returns the total funds allocated to `who` as uint256.\n   */\n  function balanceOf(uint256 streamId, address who) external view returns (uint256 balance);\n\n  /**\n   * @dev Function for the funds admin to give ERC20 allowance to other parties\n   * @param token The address of the token to give allowance from\n   * @param recipient Allowance's recipient\n   * @param amount Allowance to approve\n   **/\n  function approve(IERC20 token, address recipient, uint256 amount) external;\n\n  /**\n   * @notice Function for the funds admin to transfer ERC20 tokens to other parties\n   * @param token The address of the token to transfer\n   * @param recipient Transfer's recipient\n   * @param amount Amount to transfer\n   **/\n  function transfer(IERC20 token, address recipient, uint256 amount) external;\n\n  /**\n   * @dev Transfer the ownership of the funds administrator role.\n          This function should only be callable by the current funds administrator.\n   * @param admin The address of the new funds administrator\n   */\n  function setFundsAdmin(address admin) external;\n\n  /**\n   * @notice Creates a new stream funded by this contracts itself and paid towards `recipient`.\n   * @param recipient The address towards which the money is streamed.\n   * @param deposit The amount of money to be streamed.\n   * @param tokenAddress The ERC20 token to use as streaming currency.\n   * @param startTime The unix timestamp for when the stream starts.\n   * @param stopTime The unix timestamp for when the stream stops.\n   * @return streamId the uint256 id of the newly created stream.\n   */\n  function createStream(\n    address recipient,\n    uint256 deposit,\n    address tokenAddress,\n    uint256 startTime,\n    uint256 stopTime\n  ) external returns (uint256 streamId);\n\n  /**\n   * @notice Returns the stream with all its properties.\n   * @dev Throws if the id does not point to a valid stream.\n   * @param streamId The id of the stream to query.\n   * @notice Returns the stream object.\n   */\n  function getStream(\n    uint256 streamId\n  )\n    external\n    view\n    returns (\n      address sender,\n      address recipient,\n      uint256 deposit,\n      address tokenAddress,\n      uint256 startTime,\n      uint256 stopTime,\n      uint256 remainingBalance,\n      uint256 ratePerSecond\n    );\n\n  /**\n   * @notice Withdraws from the contract to the recipient's account.\n   * @param streamId The id of the stream to withdraw tokens from.\n   * @param amount The amount of tokens to withdraw.\n   * @return bool Returns true if successful.\n   */\n  function withdrawFromStream(uint256 streamId, uint256 amount) external returns (bool);\n\n  /**\n   * @notice Cancels the stream and transfers the tokens back on a pro rata basis.\n   * @param streamId The id of the stream to cancel.\n   * @return bool Returns true if successful.\n   */\n  function cancelStream(uint256 streamId) external returns (bool);\n\n  /**\n   * @notice Returns the next available stream id\n   * @return nextStreamId Returns the stream id.\n   */\n  function getNextStreamId() external view returns (uint256);\n}\n"
      },
      "lib/forge-std/src/StdUtils.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.6.2 <0.9.0;\n\npragma experimental ABIEncoderV2;\n\nimport {IMulticall3} from \"./interfaces/IMulticall3.sol\";\nimport {VmSafe} from \"./Vm.sol\";\n\nabstract contract StdUtils {\n    /*//////////////////////////////////////////////////////////////////////////\n                                     CONSTANTS\n    //////////////////////////////////////////////////////////////////////////*/\n\n    IMulticall3 private constant multicall = IMulticall3(0xcA11bde05977b3631167028862bE2a173976CA11);\n    VmSafe private constant vm = VmSafe(address(uint160(uint256(keccak256(\"hevm cheat code\")))));\n    address private constant CONSOLE2_ADDRESS = 0x000000000000000000636F6e736F6c652e6c6f67;\n    uint256 private constant INT256_MIN_ABS =\n        57896044618658097711785492504343953926634992332820282019728792003956564819968;\n    uint256 private constant SECP256K1_ORDER =\n        115792089237316195423570985008687907852837564279074904382605163141518161494337;\n    uint256 private constant UINT256_MAX =\n        115792089237316195423570985008687907853269984665640564039457584007913129639935;\n\n    // Used by default when deploying with create2, https://github.com/Arachnid/deterministic-deployment-proxy.\n    address private constant CREATE2_FACTORY = 0x4e59b44847b379578588920cA78FbF26c0B4956C;\n\n    /*//////////////////////////////////////////////////////////////////////////\n                                 INTERNAL FUNCTIONS\n    //////////////////////////////////////////////////////////////////////////*/\n\n    function _bound(uint256 x, uint256 min, uint256 max) internal pure virtual returns (uint256 result) {\n        require(min <= max, \"StdUtils bound(uint256,uint256,uint256): Max is less than min.\");\n        // If x is between min and max, return x directly. This is to ensure that dictionary values\n        // do not get shifted if the min is nonzero. More info: https://github.com/foundry-rs/forge-std/issues/188\n        if (x >= min && x <= max) return x;\n\n        uint256 size = max - min + 1;\n\n        // If the value is 0, 1, 2, 3, wrap that to min, min+1, min+2, min+3. Similarly for the UINT256_MAX side.\n        // This helps ensure coverage of the min/max values.\n        if (x <= 3 && size > x) return min + x;\n        if (x >= UINT256_MAX - 3 && size > UINT256_MAX - x) return max - (UINT256_MAX - x);\n\n        // Otherwise, wrap x into the range [min, max], i.e. the range is inclusive.\n        if (x > max) {\n            uint256 diff = x - max;\n            uint256 rem = diff % size;\n            if (rem == 0) return max;\n            result = min + rem - 1;\n        } else if (x < min) {\n            uint256 diff = min - x;\n            uint256 rem = diff % size;\n            if (rem == 0) return min;\n            result = max - rem + 1;\n        }\n    }\n\n    function bound(uint256 x, uint256 min, uint256 max) internal view virtual returns (uint256 result) {\n        result = _bound(x, min, max);\n        console2_log(\"Bound Result\", result);\n    }\n\n    function _bound(int256 x, int256 min, int256 max) internal pure virtual returns (int256 result) {\n        require(min <= max, \"StdUtils bound(int256,int256,int256): Max is less than min.\");\n\n        // Shifting all int256 values to uint256 to use _bound function. The range of two types are:\n        // int256 : -(2**255) ~ (2**255 - 1)\n        // uint256:     0     ~ (2**256 - 1)\n        // So, add 2**255, INT256_MIN_ABS to the integer values.\n        //\n        // If the given integer value is -2**255, we cannot use `-uint256(-x)` because of the overflow.\n        // So, use `~uint256(x) + 1` instead.\n        uint256 _x = x < 0 ? (INT256_MIN_ABS - ~uint256(x) - 1) : (uint256(x) + INT256_MIN_ABS);\n        uint256 _min = min < 0 ? (INT256_MIN_ABS - ~uint256(min) - 1) : (uint256(min) + INT256_MIN_ABS);\n        uint256 _max = max < 0 ? (INT256_MIN_ABS - ~uint256(max) - 1) : (uint256(max) + INT256_MIN_ABS);\n\n        uint256 y = _bound(_x, _min, _max);\n\n        // To move it back to int256 value, subtract INT256_MIN_ABS at here.\n        result = y < INT256_MIN_ABS ? int256(~(INT256_MIN_ABS - y) + 1) : int256(y - INT256_MIN_ABS);\n    }\n\n    function bound(int256 x, int256 min, int256 max) internal view virtual returns (int256 result) {\n        result = _bound(x, min, max);\n        console2_log(\"Bound result\", vm.toString(result));\n    }\n\n    function boundPrivateKey(uint256 privateKey) internal view virtual returns (uint256 result) {\n        result = _bound(privateKey, 1, SECP256K1_ORDER - 1);\n    }\n\n    function bytesToUint(bytes memory b) internal pure virtual returns (uint256) {\n        require(b.length <= 32, \"StdUtils bytesToUint(bytes): Bytes length exceeds 32.\");\n        return abi.decode(abi.encodePacked(new bytes(32 - b.length), b), (uint256));\n    }\n\n    /// @dev Compute the address a contract will be deployed at for a given deployer address and nonce\n    /// @notice adapted from Solmate implementation (https://github.com/Rari-Capital/solmate/blob/main/src/utils/LibRLP.sol)\n    function computeCreateAddress(address deployer, uint256 nonce) internal pure virtual returns (address) {\n        // forgefmt: disable-start\n        // The integer zero is treated as an empty byte string, and as a result it only has a length prefix, 0x80, computed via 0x80 + 0.\n        // A one byte integer uses its own value as its length prefix, there is no additional \"0x80 + length\" prefix that comes before it.\n        if (nonce == 0x00)      return addressFromLast20Bytes(keccak256(abi.encodePacked(bytes1(0xd6), bytes1(0x94), deployer, bytes1(0x80))));\n        if (nonce <= 0x7f)      return addressFromLast20Bytes(keccak256(abi.encodePacked(bytes1(0xd6), bytes1(0x94), deployer, uint8(nonce))));\n\n        // Nonces greater than 1 byte all follow a consistent encoding scheme, where each value is preceded by a prefix of 0x80 + length.\n        if (nonce <= 2**8 - 1)  return addressFromLast20Bytes(keccak256(abi.encodePacked(bytes1(0xd7), bytes1(0x94), deployer, bytes1(0x81), uint8(nonce))));\n        if (nonce <= 2**16 - 1) return addressFromLast20Bytes(keccak256(abi.encodePacked(bytes1(0xd8), bytes1(0x94), deployer, bytes1(0x82), uint16(nonce))));\n        if (nonce <= 2**24 - 1) return addressFromLast20Bytes(keccak256(abi.encodePacked(bytes1(0xd9), bytes1(0x94), deployer, bytes1(0x83), uint24(nonce))));\n        // forgefmt: disable-end\n\n        // More details about RLP encoding can be found here: https://eth.wiki/fundamentals/rlp\n        // 0xda = 0xc0 (short RLP prefix) + 0x16 (length of: 0x94 ++ proxy ++ 0x84 ++ nonce)\n        // 0x94 = 0x80 + 0x14 (0x14 = the length of an address, 20 bytes, in hex)\n        // 0x84 = 0x80 + 0x04 (0x04 = the bytes length of the nonce, 4 bytes, in hex)\n        // We assume nobody can have a nonce large enough to require more than 32 bytes.\n        return addressFromLast20Bytes(\n            keccak256(abi.encodePacked(bytes1(0xda), bytes1(0x94), deployer, bytes1(0x84), uint32(nonce)))\n        );\n    }\n\n    function computeCreate2Address(bytes32 salt, bytes32 initcodeHash, address deployer)\n        internal\n        pure\n        virtual\n        returns (address)\n    {\n        return addressFromLast20Bytes(keccak256(abi.encodePacked(bytes1(0xff), deployer, salt, initcodeHash)));\n    }\n\n    /// @dev returns the address of a contract created with CREATE2 using the default CREATE2 deployer\n    function computeCreate2Address(bytes32 salt, bytes32 initCodeHash) internal pure returns (address) {\n        return computeCreate2Address(salt, initCodeHash, CREATE2_FACTORY);\n    }\n\n    /// @dev returns the hash of the init code (creation code + no args) used in CREATE2 with no constructor arguments\n    /// @param creationCode the creation code of a contract C, as returned by type(C).creationCode\n    function hashInitCode(bytes memory creationCode) internal pure returns (bytes32) {\n        return hashInitCode(creationCode, \"\");\n    }\n\n    /// @dev returns the hash of the init code (creation code + ABI-encoded args) used in CREATE2\n    /// @param creationCode the creation code of a contract C, as returned by type(C).creationCode\n    /// @param args the ABI-encoded arguments to the constructor of C\n    function hashInitCode(bytes memory creationCode, bytes memory args) internal pure returns (bytes32) {\n        return keccak256(abi.encodePacked(creationCode, args));\n    }\n\n    // Performs a single call with Multicall3 to query the ERC-20 token balances of the given addresses.\n    function getTokenBalances(address token, address[] memory addresses)\n        internal\n        virtual\n        returns (uint256[] memory balances)\n    {\n        uint256 tokenCodeSize;\n        assembly {\n            tokenCodeSize := extcodesize(token)\n        }\n        require(tokenCodeSize > 0, \"StdUtils getTokenBalances(address,address[]): Token address is not a contract.\");\n\n        // ABI encode the aggregate call to Multicall3.\n        uint256 length = addresses.length;\n        IMulticall3.Call[] memory calls = new IMulticall3.Call[](length);\n        for (uint256 i = 0; i < length; ++i) {\n            // 0x70a08231 = bytes4(\"balanceOf(address)\"))\n            calls[i] = IMulticall3.Call({target: token, callData: abi.encodeWithSelector(0x70a08231, (addresses[i]))});\n        }\n\n        // Make the aggregate call.\n        (, bytes[] memory returnData) = multicall.aggregate(calls);\n\n        // ABI decode the return data and return the balances.\n        balances = new uint256[](length);\n        for (uint256 i = 0; i < length; ++i) {\n            balances[i] = abi.decode(returnData[i], (uint256));\n        }\n    }\n\n    /*//////////////////////////////////////////////////////////////////////////\n                                 PRIVATE FUNCTIONS\n    //////////////////////////////////////////////////////////////////////////*/\n\n    function addressFromLast20Bytes(bytes32 bytesValue) private pure returns (address) {\n        return address(uint160(uint256(bytesValue)));\n    }\n\n    // Used to prevent the compilation of console, which shortens the compilation time when console is not used elsewhere.\n\n    function console2_log(string memory p0, uint256 p1) private view {\n        (bool status,) = address(CONSOLE2_ADDRESS).staticcall(abi.encodeWithSignature(\"log(string,uint256)\", p0, p1));\n        status;\n    }\n\n    function console2_log(string memory p0, string memory p1) private view {\n        (bool status,) = address(CONSOLE2_ADDRESS).staticcall(abi.encodeWithSignature(\"log(string,string)\", p0, p1));\n        status;\n    }\n}\n"
      },
      "lib/forge-std/src/Vm.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.6.2 <0.9.0;\n\npragma experimental ABIEncoderV2;\n\n// Cheatcodes are marked as view/pure/none using the following rules:\n// 0. A call's observable behaviour includes its return value, logs, reverts and state writes,\n// 1. If you can influence a later call's observable behaviour, you're neither `view` nor `pure (you are modifying some state be it the EVM, interpreter, filesystem, etc),\n// 2. Otherwise if you can be influenced by an earlier call, or if reading some state, you're `view`,\n// 3. Otherwise you're `pure`.\n\ninterface VmSafe {\n    enum CallerMode {\n        None,\n        Broadcast,\n        RecurrentBroadcast,\n        Prank,\n        RecurrentPrank\n    }\n\n    struct Log {\n        bytes32[] topics;\n        bytes data;\n        address emitter;\n    }\n\n    struct Rpc {\n        string key;\n        string url;\n    }\n\n    struct DirEntry {\n        string errorMessage;\n        string path;\n        uint64 depth;\n        bool isDir;\n        bool isSymlink;\n    }\n\n    struct FsMetadata {\n        bool isDir;\n        bool isSymlink;\n        uint256 length;\n        bool readOnly;\n        uint256 modified;\n        uint256 accessed;\n        uint256 created;\n    }\n\n    // Loads a storage slot from an address\n    function load(address target, bytes32 slot) external view returns (bytes32 data);\n    // Signs data\n    function sign(uint256 privateKey, bytes32 digest) external pure returns (uint8 v, bytes32 r, bytes32 s);\n    // Gets the address for a given private key\n    function addr(uint256 privateKey) external pure returns (address keyAddr);\n    // Gets the nonce of an account\n    function getNonce(address account) external view returns (uint64 nonce);\n    // Performs a foreign function call via the terminal\n    function ffi(string[] calldata commandInput) external returns (bytes memory result);\n    // Sets environment variables\n    function setEnv(string calldata name, string calldata value) external;\n    // Reads environment variables, (name) => (value)\n    function envBool(string calldata name) external view returns (bool value);\n    function envUint(string calldata name) external view returns (uint256 value);\n    function envInt(string calldata name) external view returns (int256 value);\n    function envAddress(string calldata name) external view returns (address value);\n    function envBytes32(string calldata name) external view returns (bytes32 value);\n    function envString(string calldata name) external view returns (string memory value);\n    function envBytes(string calldata name) external view returns (bytes memory value);\n    // Reads environment variables as arrays\n    function envBool(string calldata name, string calldata delim) external view returns (bool[] memory value);\n    function envUint(string calldata name, string calldata delim) external view returns (uint256[] memory value);\n    function envInt(string calldata name, string calldata delim) external view returns (int256[] memory value);\n    function envAddress(string calldata name, string calldata delim) external view returns (address[] memory value);\n    function envBytes32(string calldata name, string calldata delim) external view returns (bytes32[] memory value);\n    function envString(string calldata name, string calldata delim) external view returns (string[] memory value);\n    function envBytes(string calldata name, string calldata delim) external view returns (bytes[] memory value);\n    // Read environment variables with default value\n    function envOr(string calldata name, bool defaultValue) external returns (bool value);\n    function envOr(string calldata name, uint256 defaultValue) external returns (uint256 value);\n    function envOr(string calldata name, int256 defaultValue) external returns (int256 value);\n    function envOr(string calldata name, address defaultValue) external returns (address value);\n    function envOr(string calldata name, bytes32 defaultValue) external returns (bytes32 value);\n    function envOr(string calldata name, string calldata defaultValue) external returns (string memory value);\n    function envOr(string calldata name, bytes calldata defaultValue) external returns (bytes memory value);\n    // Read environment variables as arrays with default value\n    function envOr(string calldata name, string calldata delim, bool[] calldata defaultValue)\n        external\n        returns (bool[] memory value);\n    function envOr(string calldata name, string calldata delim, uint256[] calldata defaultValue)\n        external\n        returns (uint256[] memory value);\n    function envOr(string calldata name, string calldata delim, int256[] calldata defaultValue)\n        external\n        returns (int256[] memory value);\n    function envOr(string calldata name, string calldata delim, address[] calldata defaultValue)\n        external\n        returns (address[] memory value);\n    function envOr(string calldata name, string calldata delim, bytes32[] calldata defaultValue)\n        external\n        returns (bytes32[] memory value);\n    function envOr(string calldata name, string calldata delim, string[] calldata defaultValue)\n        external\n        returns (string[] memory value);\n    function envOr(string calldata name, string calldata delim, bytes[] calldata defaultValue)\n        external\n        returns (bytes[] memory value);\n    // Records all storage reads and writes\n    function record() external;\n    // Gets all accessed reads and write slot from a recording session, for a given address\n    function accesses(address target) external returns (bytes32[] memory readSlots, bytes32[] memory writeSlots);\n    // Gets the _creation_ bytecode from an artifact file. Takes in the relative path to the json file\n    function getCode(string calldata artifactPath) external view returns (bytes memory creationBytecode);\n    // Gets the _deployed_ bytecode from an artifact file. Takes in the relative path to the json file\n    function getDeployedCode(string calldata artifactPath) external view returns (bytes memory runtimeBytecode);\n    // Labels an address in call traces\n    function label(address account, string calldata newLabel) external;\n    // Gets the label for the specified address\n    function getLabel(address account) external returns (string memory label);\n    // Using the address that calls the test contract, has the next call (at this call depth only) create a transaction that can later be signed and sent onchain\n    function broadcast() external;\n    // Has the next call (at this call depth only) create a transaction with the address provided as the sender that can later be signed and sent onchain\n    function broadcast(address signer) external;\n    // Has the next call (at this call depth only) create a transaction with the private key provided as the sender that can later be signed and sent onchain\n    function broadcast(uint256 privateKey) external;\n    // Using the address that calls the test contract, has all subsequent calls (at this call depth only) create transactions that can later be signed and sent onchain\n    function startBroadcast() external;\n    // Has all subsequent calls (at this call depth only) create transactions with the address provided that can later be signed and sent onchain\n    function startBroadcast(address signer) external;\n    // Has all subsequent calls (at this call depth only) create transactions with the private key provided that can later be signed and sent onchain\n    function startBroadcast(uint256 privateKey) external;\n    // Stops collecting onchain transactions\n    function stopBroadcast() external;\n\n    // Get the path of the current project root.\n    function projectRoot() external view returns (string memory path);\n    // Reads the entire content of file to string. `path` is relative to the project root.\n    function readFile(string calldata path) external view returns (string memory data);\n    // Reads the entire content of file as binary. `path` is relative to the project root.\n    function readFileBinary(string calldata path) external view returns (bytes memory data);\n    // Reads next line of file to string.\n    function readLine(string calldata path) external view returns (string memory line);\n    // Writes data to file, creating a file if it does not exist, and entirely replacing its contents if it does.\n    // `path` is relative to the project root.\n    function writeFile(string calldata path, string calldata data) external;\n    // Writes binary data to a file, creating a file if it does not exist, and entirely replacing its contents if it does.\n    // `path` is relative to the project root.\n    function writeFileBinary(string calldata path, bytes calldata data) external;\n    // Writes line to file, creating a file if it does not exist.\n    // `path` is relative to the project root.\n    function writeLine(string calldata path, string calldata data) external;\n    // Closes file for reading, resetting the offset and allowing to read it from beginning with readLine.\n    // `path` is relative to the project root.\n    function closeFile(string calldata path) external;\n    // Removes a file from the filesystem.\n    // This cheatcode will revert in the following situations, but is not limited to just these cases:\n    // - `path` points to a directory.\n    // - The file doesn't exist.\n    // - The user lacks permissions to remove the file.\n    // `path` is relative to the project root.\n    function removeFile(string calldata path) external;\n    // Creates a new, empty directory at the provided path.\n    // This cheatcode will revert in the following situations, but is not limited to just these cases:\n    // - User lacks permissions to modify `path`.\n    // - A parent of the given path doesn't exist and `recursive` is false.\n    // - `path` already exists and `recursive` is false.\n    // `path` is relative to the project root.\n    function createDir(string calldata path, bool recursive) external;\n    // Removes a directory at the provided path.\n    // This cheatcode will revert in the following situations, but is not limited to just these cases:\n    // - `path` doesn't exist.\n    // - `path` isn't a directory.\n    // - User lacks permissions to modify `path`.\n    // - The directory is not empty and `recursive` is false.\n    // `path` is relative to the project root.\n    function removeDir(string calldata path, bool recursive) external;\n    // Reads the directory at the given path recursively, up to `max_depth`.\n    // `max_depth` defaults to 1, meaning only the direct children of the given directory will be returned.\n    // Follows symbolic links if `follow_links` is true.\n    function readDir(string calldata path) external view returns (DirEntry[] memory entries);\n    function readDir(string calldata path, uint64 maxDepth) external view returns (DirEntry[] memory entries);\n    function readDir(string calldata path, uint64 maxDepth, bool followLinks)\n        external\n        view\n        returns (DirEntry[] memory entries);\n    // Reads a symbolic link, returning the path that the link points to.\n    // This cheatcode will revert in the following situations, but is not limited to just these cases:\n    // - `path` is not a symbolic link.\n    // - `path` does not exist.\n    function readLink(string calldata linkPath) external view returns (string memory targetPath);\n    // Given a path, query the file system to get information about a file, directory, etc.\n    function fsMetadata(string calldata path) external view returns (FsMetadata memory metadata);\n\n    // Convert values to a string\n    function toString(address value) external pure returns (string memory stringifiedValue);\n    function toString(bytes calldata value) external pure returns (string memory stringifiedValue);\n    function toString(bytes32 value) external pure returns (string memory stringifiedValue);\n    function toString(bool value) external pure returns (string memory stringifiedValue);\n    function toString(uint256 value) external pure returns (string memory stringifiedValue);\n    function toString(int256 value) external pure returns (string memory stringifiedValue);\n    // Convert values from a string\n    function parseBytes(string calldata stringifiedValue) external pure returns (bytes memory parsedValue);\n    function parseAddress(string calldata stringifiedValue) external pure returns (address parsedValue);\n    function parseUint(string calldata stringifiedValue) external pure returns (uint256 parsedValue);\n    function parseInt(string calldata stringifiedValue) external pure returns (int256 parsedValue);\n    function parseBytes32(string calldata stringifiedValue) external pure returns (bytes32 parsedValue);\n    function parseBool(string calldata stringifiedValue) external pure returns (bool parsedValue);\n    // Record all the transaction logs\n    function recordLogs() external;\n    // Gets all the recorded logs\n    function getRecordedLogs() external returns (Log[] memory logs);\n    // Derive a private key from a provided mnenomic string (or mnenomic file path) at the derivation path m/44'/60'/0'/0/{index}\n    function deriveKey(string calldata mnemonic, uint32 index) external pure returns (uint256 privateKey);\n    // Derive a private key from a provided mnenomic string (or mnenomic file path) at {derivationPath}{index}\n    function deriveKey(string calldata mnemonic, string calldata derivationPath, uint32 index)\n        external\n        pure\n        returns (uint256 privateKey);\n    // Adds a private key to the local forge wallet and returns the address\n    function rememberKey(uint256 privateKey) external returns (address keyAddr);\n    //\n    // parseJson\n    //\n    // ----\n    // In case the returned value is a JSON object, it's encoded as a ABI-encoded tuple. As JSON objects\n    // don't have the notion of ordered, but tuples do, they JSON object is encoded with it's fields ordered in\n    // ALPHABETICAL order. That means that in order to successfully decode the tuple, we need to define a tuple that\n    // encodes the fields in the same order, which is alphabetical. In the case of Solidity structs, they are encoded\n    // as tuples, with the attributes in the order in which they are defined.\n    // For example: json = { 'a': 1, 'b': 0xa4tb......3xs}\n    // a: uint256\n    // b: address\n    // To decode that json, we need to define a struct or a tuple as follows:\n    // struct json = { uint256 a; address b; }\n    // If we defined a json struct with the opposite order, meaning placing the address b first, it would try to\n    // decode the tuple in that order, and thus fail.\n    // ----\n    // Given a string of JSON, return it as ABI-encoded\n    function parseJson(string calldata json, string calldata key) external pure returns (bytes memory abiEncodedData);\n    function parseJson(string calldata json) external pure returns (bytes memory abiEncodedData);\n\n    // The following parseJson cheatcodes will do type coercion, for the type that they indicate.\n    // For example, parseJsonUint will coerce all values to a uint256. That includes stringified numbers '12'\n    // and hex numbers '0xEF'.\n    // Type coercion works ONLY for discrete values or arrays. That means that the key must return a value or array, not\n    // a JSON object.\n    function parseJsonUint(string calldata, string calldata) external returns (uint256);\n    function parseJsonUintArray(string calldata, string calldata) external returns (uint256[] memory);\n    function parseJsonInt(string calldata, string calldata) external returns (int256);\n    function parseJsonIntArray(string calldata, string calldata) external returns (int256[] memory);\n    function parseJsonBool(string calldata, string calldata) external returns (bool);\n    function parseJsonBoolArray(string calldata, string calldata) external returns (bool[] memory);\n    function parseJsonAddress(string calldata, string calldata) external returns (address);\n    function parseJsonAddressArray(string calldata, string calldata) external returns (address[] memory);\n    function parseJsonString(string calldata, string calldata) external returns (string memory);\n    function parseJsonStringArray(string calldata, string calldata) external returns (string[] memory);\n    function parseJsonBytes(string calldata, string calldata) external returns (bytes memory);\n    function parseJsonBytesArray(string calldata, string calldata) external returns (bytes[] memory);\n    function parseJsonBytes32(string calldata, string calldata) external returns (bytes32);\n    function parseJsonBytes32Array(string calldata, string calldata) external returns (bytes32[] memory);\n\n    // Serialize a key and value to a JSON object stored in-memory that can be later written to a file\n    // It returns the stringified version of the specific JSON file up to that moment.\n    function serializeBool(string calldata objectKey, string calldata valueKey, bool value)\n        external\n        returns (string memory json);\n    function serializeUint(string calldata objectKey, string calldata valueKey, uint256 value)\n        external\n        returns (string memory json);\n    function serializeInt(string calldata objectKey, string calldata valueKey, int256 value)\n        external\n        returns (string memory json);\n    function serializeAddress(string calldata objectKey, string calldata valueKey, address value)\n        external\n        returns (string memory json);\n    function serializeBytes32(string calldata objectKey, string calldata valueKey, bytes32 value)\n        external\n        returns (string memory json);\n    function serializeString(string calldata objectKey, string calldata valueKey, string calldata value)\n        external\n        returns (string memory json);\n    function serializeBytes(string calldata objectKey, string calldata valueKey, bytes calldata value)\n        external\n        returns (string memory json);\n\n    function serializeBool(string calldata objectKey, string calldata valueKey, bool[] calldata values)\n        external\n        returns (string memory json);\n    function serializeUint(string calldata objectKey, string calldata valueKey, uint256[] calldata values)\n        external\n        returns (string memory json);\n    function serializeInt(string calldata objectKey, string calldata valueKey, int256[] calldata values)\n        external\n        returns (string memory json);\n    function serializeAddress(string calldata objectKey, string calldata valueKey, address[] calldata values)\n        external\n        returns (string memory json);\n    function serializeBytes32(string calldata objectKey, string calldata valueKey, bytes32[] calldata values)\n        external\n        returns (string memory json);\n    function serializeString(string calldata objectKey, string calldata valueKey, string[] calldata values)\n        external\n        returns (string memory json);\n    function serializeBytes(string calldata objectKey, string calldata valueKey, bytes[] calldata values)\n        external\n        returns (string memory json);\n\n    //\n    // writeJson\n    //\n    // ----\n    // Write a serialized JSON object to a file. If the file exists, it will be overwritten.\n    // Let's assume we want to write the following JSON to a file:\n    //\n    // { \"boolean\": true, \"number\": 342, \"object\": { \"title\": \"finally json serialization\" } }\n    //\n    // ```\n    //  string memory json1 = \"some key\";\n    //  vm.serializeBool(json1, \"boolean\", true);\n    //  vm.serializeBool(json1, \"number\", uint256(342));\n    //  json2 = \"some other key\";\n    //  string memory output = vm.serializeString(json2, \"title\", \"finally json serialization\");\n    //  string memory finalJson = vm.serialize(json1, \"object\", output);\n    //  vm.writeJson(finalJson, \"./output/example.json\");\n    // ```\n    // The critical insight is that every invocation of serialization will return the stringified version of the JSON\n    // up to that point. That means we can construct arbitrary JSON objects and then use the return stringified version\n    // to serialize them as values to another JSON object.\n    //\n    // json1 and json2 are simply keys used by the backend to keep track of the objects. So vm.serializeJson(json1,..)\n    // will find the object in-memory that is keyed by \"some key\".\n    function writeJson(string calldata json, string calldata path) external;\n    // Write a serialized JSON object to an **existing** JSON file, replacing a value with key = <value_key>\n    // This is useful to replace a specific value of a JSON file, without having to parse the entire thing\n    function writeJson(string calldata json, string calldata path, string calldata valueKey) external;\n    // Returns the RPC url for the given alias\n    function rpcUrl(string calldata rpcAlias) external view returns (string memory json);\n    // Returns all rpc urls and their aliases `[alias, url][]`\n    function rpcUrls() external view returns (string[2][] memory urls);\n    // Returns all rpc urls and their aliases as structs.\n    function rpcUrlStructs() external view returns (Rpc[] memory urls);\n    // If the condition is false, discard this run's fuzz inputs and generate new ones.\n    function assume(bool condition) external pure;\n    // Pauses gas metering (i.e. gas usage is not counted). Noop if already paused.\n    function pauseGasMetering() external;\n    // Resumes gas metering (i.e. gas usage is counted again). Noop if already on.\n    function resumeGasMetering() external;\n    // Writes a breakpoint to jump to in the debugger\n    function breakpoint(string calldata char) external;\n    // Writes a conditional breakpoint to jump to in the debugger\n    function breakpoint(string calldata char, bool value) external;\n}\n\ninterface Vm is VmSafe {\n    // Sets block.timestamp\n    function warp(uint256 newTimestamp) external;\n    // Sets block.height\n    function roll(uint256 newHeight) external;\n    // Sets block.basefee\n    function fee(uint256 newBasefee) external;\n    // Sets block.difficulty\n    // Not available on EVM versions from Paris onwards. Use `prevrandao` instead.\n    // If used on unsupported EVM versions it will revert.\n    function difficulty(uint256 newDifficulty) external;\n    // Sets block.prevrandao\n    // Not available on EVM versions before Paris. Use `difficulty` instead.\n    // If used on unsupported EVM versions it will revert.\n    function prevrandao(bytes32 newPrevrandao) external;\n    // Sets block.chainid\n    function chainId(uint256 newChainId) external;\n    // Sets tx.gasprice\n    function txGasPrice(uint256 newGasPrice) external;\n    // Stores a value to an address' storage slot.\n    function store(address target, bytes32 slot, bytes32 value) external;\n    // Sets the nonce of an account; must be higher than the current nonce of the account\n    function setNonce(address account, uint64 newNonce) external;\n    // Sets the nonce of an account to an arbitrary value\n    function setNonceUnsafe(address account, uint64 newNonce) external;\n    // Resets the nonce of an account to 0 for EOAs and 1 for contract accounts\n    function resetNonce(address account) external;\n    // Sets the *next* call's msg.sender to be the input address\n    function prank(address msgSender) external;\n    // Sets all subsequent calls' msg.sender to be the input address until `stopPrank` is called\n    function startPrank(address msgSender) external;\n    // Sets the *next* call's msg.sender to be the input address, and the tx.origin to be the second input\n    function prank(address msgSender, address txOrigin) external;\n    // Sets all subsequent calls' msg.sender to be the input address until `stopPrank` is called, and the tx.origin to be the second input\n    function startPrank(address msgSender, address txOrigin) external;\n    // Resets subsequent calls' msg.sender to be `address(this)`\n    function stopPrank() external;\n    // Reads the current `msg.sender` and `tx.origin` from state and reports if there is any active caller modification\n    function readCallers() external returns (CallerMode callerMode, address msgSender, address txOrigin);\n    // Sets an address' balance\n    function deal(address account, uint256 newBalance) external;\n    // Sets an address' code\n    function etch(address target, bytes calldata newRuntimeBytecode) external;\n    // Expects an error on next call\n    function expectRevert(bytes calldata revertData) external;\n    function expectRevert(bytes4 revertData) external;\n    function expectRevert() external;\n\n    // Prepare an expected log with all four checks enabled.\n    // Call this function, then emit an event, then call a function. Internally after the call, we check if\n    // logs were emitted in the expected order with the expected topics and data.\n    // Second form also checks supplied address against emitting contract.\n    function expectEmit() external;\n    function expectEmit(address emitter) external;\n\n    // Prepare an expected log with (bool checkTopic1, bool checkTopic2, bool checkTopic3, bool checkData).\n    // Call this function, then emit an event, then call a function. Internally after the call, we check if\n    // logs were emitted in the expected order with the expected topics and data (as specified by the booleans).\n    // Second form also checks supplied address against emitting contract.\n    function expectEmit(bool checkTopic1, bool checkTopic2, bool checkTopic3, bool checkData) external;\n    function expectEmit(bool checkTopic1, bool checkTopic2, bool checkTopic3, bool checkData, address emitter)\n        external;\n\n    // Mocks a call to an address, returning specified data.\n    // Calldata can either be strict or a partial match, e.g. if you only\n    // pass a Solidity selector to the expected calldata, then the entire Solidity\n    // function will be mocked.\n    function mockCall(address callee, bytes calldata data, bytes calldata returnData) external;\n    // Mocks a call to an address with a specific msg.value, returning specified data.\n    // Calldata match takes precedence over msg.value in case of ambiguity.\n    function mockCall(address callee, uint256 msgValue, bytes calldata data, bytes calldata returnData) external;\n    // Reverts a call to an address with specified revert data.\n    function mockCallRevert(address callee, bytes calldata data, bytes calldata revertData) external;\n    // Reverts a call to an address with a specific msg.value, with specified revert data.\n    function mockCallRevert(address callee, uint256 msgValue, bytes calldata data, bytes calldata revertData)\n        external;\n    // Clears all mocked calls\n    function clearMockedCalls() external;\n    // Expects a call to an address with the specified calldata.\n    // Calldata can either be a strict or a partial match\n    function expectCall(address callee, bytes calldata data) external;\n    // Expects given number of calls to an address with the specified calldata.\n    function expectCall(address callee, bytes calldata data, uint64 count) external;\n    // Expects a call to an address with the specified msg.value and calldata\n    function expectCall(address callee, uint256 msgValue, bytes calldata data) external;\n    // Expects given number of calls to an address with the specified msg.value and calldata\n    function expectCall(address callee, uint256 msgValue, bytes calldata data, uint64 count) external;\n    // Expect a call to an address with the specified msg.value, gas, and calldata.\n    function expectCall(address callee, uint256 msgValue, uint64 gas, bytes calldata data) external;\n    // Expects given number of calls to an address with the specified msg.value, gas, and calldata.\n    function expectCall(address callee, uint256 msgValue, uint64 gas, bytes calldata data, uint64 count) external;\n    // Expect a call to an address with the specified msg.value and calldata, and a *minimum* amount of gas.\n    function expectCallMinGas(address callee, uint256 msgValue, uint64 minGas, bytes calldata data) external;\n    // Expect given number of calls to an address with the specified msg.value and calldata, and a *minimum* amount of gas.\n    function expectCallMinGas(address callee, uint256 msgValue, uint64 minGas, bytes calldata data, uint64 count)\n        external;\n    // Only allows memory writes to offsets [0x00, 0x60) ∪ [min, max) in the current subcontext. If any other\n    // memory is written to, the test will fail. Can be called multiple times to add more ranges to the set.\n    function expectSafeMemory(uint64 min, uint64 max) external;\n    // Only allows memory writes to offsets [0x00, 0x60) ∪ [min, max) in the next created subcontext.\n    // If any other memory is written to, the test will fail. Can be called multiple times to add more ranges\n    // to the set.\n    function expectSafeMemoryCall(uint64 min, uint64 max) external;\n    // Sets block.coinbase\n    function coinbase(address newCoinbase) external;\n    // Snapshot the current state of the evm.\n    // Returns the id of the snapshot that was created.\n    // To revert a snapshot use `revertTo`\n    function snapshot() external returns (uint256 snapshotId);\n    // Revert the state of the EVM to a previous snapshot\n    // Takes the snapshot id to revert to.\n    // This deletes the snapshot and all snapshots taken after the given snapshot id.\n    function revertTo(uint256 snapshotId) external returns (bool success);\n    // Creates a new fork with the given endpoint and block and returns the identifier of the fork\n    function createFork(string calldata urlOrAlias, uint256 blockNumber) external returns (uint256 forkId);\n    // Creates a new fork with the given endpoint and the _latest_ block and returns the identifier of the fork\n    function createFork(string calldata urlOrAlias) external returns (uint256 forkId);\n    // Creates a new fork with the given endpoint and at the block the given transaction was mined in, replays all transaction mined in the block before the transaction,\n    // and returns the identifier of the fork\n    function createFork(string calldata urlOrAlias, bytes32 txHash) external returns (uint256 forkId);\n    // Creates _and_ also selects a new fork with the given endpoint and block and returns the identifier of the fork\n    function createSelectFork(string calldata urlOrAlias, uint256 blockNumber) external returns (uint256 forkId);\n    // Creates _and_ also selects new fork with the given endpoint and at the block the given transaction was mined in, replays all transaction mined in the block before\n    // the transaction, returns the identifier of the fork\n    function createSelectFork(string calldata urlOrAlias, bytes32 txHash) external returns (uint256 forkId);\n    // Creates _and_ also selects a new fork with the given endpoint and the latest block and returns the identifier of the fork\n    function createSelectFork(string calldata urlOrAlias) external returns (uint256 forkId);\n    // Takes a fork identifier created by `createFork` and sets the corresponding forked state as active.\n    function selectFork(uint256 forkId) external;\n    /// Returns the identifier of the currently active fork. Reverts if no fork is currently active.\n    function activeFork() external view returns (uint256 forkId);\n    // Updates the currently active fork to given block number\n    // This is similar to `roll` but for the currently active fork\n    function rollFork(uint256 blockNumber) external;\n    // Updates the currently active fork to given transaction\n    // this will `rollFork` with the number of the block the transaction was mined in and replays all transaction mined before it in the block\n    function rollFork(bytes32 txHash) external;\n    // Updates the given fork to given block number\n    function rollFork(uint256 forkId, uint256 blockNumber) external;\n    // Updates the given fork to block number of the given transaction and replays all transaction mined before it in the block\n    function rollFork(uint256 forkId, bytes32 txHash) external;\n    // Marks that the account(s) should use persistent storage across fork swaps in a multifork setup\n    // Meaning, changes made to the state of this account will be kept when switching forks\n    function makePersistent(address account) external;\n    function makePersistent(address account0, address account1) external;\n    function makePersistent(address account0, address account1, address account2) external;\n    function makePersistent(address[] calldata accounts) external;\n    // Revokes persistent status from the address, previously added via `makePersistent`\n    function revokePersistent(address account) external;\n    function revokePersistent(address[] calldata accounts) external;\n    // Returns true if the account is marked as persistent\n    function isPersistent(address account) external view returns (bool persistent);\n    // In forking mode, explicitly grant the given address cheatcode access\n    function allowCheatcodes(address account) external;\n    // Fetches the given transaction from the active fork and executes it on the current state\n    function transact(bytes32 txHash) external;\n    // Fetches the given transaction from the given fork and executes it on the current state\n    function transact(uint256 forkId, bytes32 txHash) external;\n}\n"
      },
      "lib/forge-std/src/interfaces/IMulticall3.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.6.2 <0.9.0;\n\npragma experimental ABIEncoderV2;\n\ninterface IMulticall3 {\n    struct Call {\n        address target;\n        bytes callData;\n    }\n\n    struct Call3 {\n        address target;\n        bool allowFailure;\n        bytes callData;\n    }\n\n    struct Call3Value {\n        address target;\n        bool allowFailure;\n        uint256 value;\n        bytes callData;\n    }\n\n    struct Result {\n        bool success;\n        bytes returnData;\n    }\n\n    function aggregate(Call[] calldata calls)\n        external\n        payable\n        returns (uint256 blockNumber, bytes[] memory returnData);\n\n    function aggregate3(Call3[] calldata calls) external payable returns (Result[] memory returnData);\n\n    function aggregate3Value(Call3Value[] calldata calls) external payable returns (Result[] memory returnData);\n\n    function blockAndAggregate(Call[] calldata calls)\n        external\n        payable\n        returns (uint256 blockNumber, bytes32 blockHash, Result[] memory returnData);\n\n    function getBasefee() external view returns (uint256 basefee);\n\n    function getBlockHash(uint256 blockNumber) external view returns (bytes32 blockHash);\n\n    function getBlockNumber() external view returns (uint256 blockNumber);\n\n    function getChainId() external view returns (uint256 chainid);\n\n    function getCurrentBlockCoinbase() external view returns (address coinbase);\n\n    function getCurrentBlockDifficulty() external view returns (uint256 difficulty);\n\n    function getCurrentBlockGasLimit() external view returns (uint256 gaslimit);\n\n    function getCurrentBlockTimestamp() external view returns (uint256 timestamp);\n\n    function getEthBalance(address addr) external view returns (uint256 balance);\n\n    function getLastBlockHash() external view returns (bytes32 blockHash);\n\n    function tryAggregate(bool requireSuccess, Call[] calldata calls)\n        external\n        payable\n        returns (Result[] memory returnData);\n\n    function tryBlockAndAggregate(bool requireSuccess, Call[] calldata calls)\n        external\n        payable\n        returns (uint256 blockNumber, bytes32 blockHash, Result[] memory returnData);\n}\n"
      },
      "lib/solidity-utils/src/contracts/oz-common/Address.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Address.sol)\n// From commit https://github.com/OpenZeppelin/openzeppelin-contracts/commit/8b778fa20d6d76340c5fac1ed66c80273f05b95a\n\npragma solidity ^0.8.1;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n  /**\n   * @dev Returns true if `account` is a contract.\n   *\n   * [IMPORTANT]\n   * ====\n   * It is unsafe to assume that an address for which this function returns\n   * false is an externally-owned account (EOA) and not a contract.\n   *\n   * Among others, `isContract` will return false for the following\n   * types of addresses:\n   *\n   *  - an externally-owned account\n   *  - a contract in construction\n   *  - an address where a contract will be created\n   *  - an address where a contract lived, but was destroyed\n   * ====\n   *\n   * [IMPORTANT]\n   * ====\n   * You shouldn't rely on `isContract` to protect against flash loan attacks!\n   *\n   * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets\n   * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract\n   * constructor.\n   * ====\n   */\n  function isContract(address account) internal view returns (bool) {\n    // This method relies on extcodesize/address.code.length, which returns 0\n    // for contracts in construction, since the code is only stored at the end\n    // of the constructor execution.\n\n    return account.code.length > 0;\n  }\n\n  /**\n   * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n   * `recipient`, forwarding all available gas and reverting on errors.\n   *\n   * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n   * of certain opcodes, possibly making contracts go over the 2300 gas limit\n   * imposed by `transfer`, making them unable to receive funds via\n   * `transfer`. {sendValue} removes this limitation.\n   *\n   * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n   *\n   * IMPORTANT: because control is transferred to `recipient`, care must be\n   * taken to not create reentrancy vulnerabilities. Consider using\n   * {ReentrancyGuard} or the\n   * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n   */\n  function sendValue(address payable recipient, uint256 amount) internal {\n    require(address(this).balance >= amount, 'Address: insufficient balance');\n\n    (bool success, ) = recipient.call{value: amount}('');\n    require(success, 'Address: unable to send value, recipient may have reverted');\n  }\n\n  /**\n   * @dev Performs a Solidity function call using a low level `call`. A\n   * plain `call` is an unsafe replacement for a function call: use this\n   * function instead.\n   *\n   * If `target` reverts with a revert reason, it is bubbled up by this\n   * function (like regular Solidity function calls).\n   *\n   * Returns the raw returned data. To convert to the expected return value,\n   * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n   *\n   * Requirements:\n   *\n   * - `target` must be a contract.\n   * - calling `target` with `data` must not revert.\n   *\n   * _Available since v3.1._\n   */\n  function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n    return functionCallWithValue(target, data, 0, 'Address: low-level call failed');\n  }\n\n  /**\n   * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n   * `errorMessage` as a fallback revert reason when `target` reverts.\n   *\n   * _Available since v3.1._\n   */\n  function functionCall(\n    address target,\n    bytes memory data,\n    string memory errorMessage\n  ) internal returns (bytes memory) {\n    return functionCallWithValue(target, data, 0, errorMessage);\n  }\n\n  /**\n   * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n   * but also transferring `value` wei to `target`.\n   *\n   * Requirements:\n   *\n   * - the calling contract must have an ETH balance of at least `value`.\n   * - the called Solidity function must be `payable`.\n   *\n   * _Available since v3.1._\n   */\n  function functionCallWithValue(\n    address target,\n    bytes memory data,\n    uint256 value\n  ) internal returns (bytes memory) {\n    return functionCallWithValue(target, data, value, 'Address: low-level call with value failed');\n  }\n\n  /**\n   * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n   * with `errorMessage` as a fallback revert reason when `target` reverts.\n   *\n   * _Available since v3.1._\n   */\n  function functionCallWithValue(\n    address target,\n    bytes memory data,\n    uint256 value,\n    string memory errorMessage\n  ) internal returns (bytes memory) {\n    require(address(this).balance >= value, 'Address: insufficient balance for call');\n    (bool success, bytes memory returndata) = target.call{value: value}(data);\n    return verifyCallResultFromTarget(target, success, returndata, errorMessage);\n  }\n\n  /**\n   * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n   * but performing a static call.\n   *\n   * _Available since v3.3._\n   */\n  function functionStaticCall(address target, bytes memory data)\n    internal\n    view\n    returns (bytes memory)\n  {\n    return functionStaticCall(target, data, 'Address: low-level static call failed');\n  }\n\n  /**\n   * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n   * but performing a static call.\n   *\n   * _Available since v3.3._\n   */\n  function functionStaticCall(\n    address target,\n    bytes memory data,\n    string memory errorMessage\n  ) internal view returns (bytes memory) {\n    (bool success, bytes memory returndata) = target.staticcall(data);\n    return verifyCallResultFromTarget(target, success, returndata, errorMessage);\n  }\n\n  /**\n   * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n   * but performing a delegate call.\n   *\n   * _Available since v3.4._\n   */\n  function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n    return functionDelegateCall(target, data, 'Address: low-level delegate call failed');\n  }\n\n  /**\n   * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n   * but performing a delegate call.\n   *\n   * _Available since v3.4._\n   */\n  function functionDelegateCall(\n    address target,\n    bytes memory data,\n    string memory errorMessage\n  ) internal returns (bytes memory) {\n    (bool success, bytes memory returndata) = target.delegatecall(data);\n    return verifyCallResultFromTarget(target, success, returndata, errorMessage);\n  }\n\n  /**\n   * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling\n   * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.\n   *\n   * _Available since v4.8._\n   */\n  function verifyCallResultFromTarget(\n    address target,\n    bool success,\n    bytes memory returndata,\n    string memory errorMessage\n  ) internal view returns (bytes memory) {\n    if (success) {\n      if (returndata.length == 0) {\n        // only check isContract if the call was successful and the return data is empty\n        // otherwise we already know that it was a contract\n        require(isContract(target), 'Address: call to non-contract');\n      }\n      return returndata;\n    } else {\n      _revert(returndata, errorMessage);\n    }\n  }\n\n  /**\n   * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the\n   * revert reason or using the provided one.\n   *\n   * _Available since v4.3._\n   */\n  function verifyCallResult(\n    bool success,\n    bytes memory returndata,\n    string memory errorMessage\n  ) internal pure returns (bytes memory) {\n    if (success) {\n      return returndata;\n    } else {\n      _revert(returndata, errorMessage);\n    }\n  }\n\n  function _revert(bytes memory returndata, string memory errorMessage) private pure {\n    // Look for revert reason and bubble it up if present\n    if (returndata.length > 0) {\n      // The easiest way to bubble the revert reason is using memory via assembly\n      /// @solidity memory-safe-assembly\n      assembly {\n        let returndata_size := mload(returndata)\n        revert(add(32, returndata), returndata_size)\n      }\n    } else {\n      revert(errorMessage);\n    }\n  }\n}\n"
      },
      "lib/solidity-utils/src/contracts/oz-common/Context.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)\n// From commit https://github.com/OpenZeppelin/openzeppelin-contracts/commit/8b778fa20d6d76340c5fac1ed66c80273f05b95a\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract Context {\n  function _msgSender() internal view virtual returns (address) {\n    return msg.sender;\n  }\n\n  function _msgData() internal view virtual returns (bytes calldata) {\n    return msg.data;\n  }\n}\n"
      },
      "lib/solidity-utils/src/contracts/oz-common/Ownable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (access/Ownable.sol)\n// From commit https://github.com/OpenZeppelin/openzeppelin-contracts/commit/8b778fa20d6d76340c5fac1ed66c80273f05b95a\n\npragma solidity ^0.8.0;\n\nimport './Context.sol';\n\n/**\n * @dev Contract module which provides a basic access control mechanism, where\n * there is an account (an owner) that can be granted exclusive access to\n * specific functions.\n *\n * By default, the owner account will be the one that deploys the contract. This\n * can later be changed with {transferOwnership}.\n *\n * This module is used through inheritance. It will make available the modifier\n * `onlyOwner`, which can be applied to your functions to restrict their use to\n * the owner.\n */\nabstract contract Ownable is Context {\n  address private _owner;\n\n  event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);\n\n  /**\n   * @dev Initializes the contract setting the deployer as the initial owner.\n   */\n  constructor() {\n    _transferOwnership(_msgSender());\n  }\n\n  /**\n   * @dev Throws if called by any account other than the owner.\n   */\n  modifier onlyOwner() {\n    _checkOwner();\n    _;\n  }\n\n  /**\n   * @dev Returns the address of the current owner.\n   */\n  function owner() public view virtual returns (address) {\n    return _owner;\n  }\n\n  /**\n   * @dev Throws if the sender is not the owner.\n   */\n  function _checkOwner() internal view virtual {\n    require(owner() == _msgSender(), 'Ownable: caller is not the owner');\n  }\n\n  /**\n   * @dev Leaves the contract without owner. It will not be possible to call\n   * `onlyOwner` functions anymore. Can only be called by the current owner.\n   *\n   * NOTE: Renouncing ownership will leave the contract without an owner,\n   * thereby removing any functionality that is only available to the owner.\n   */\n  function renounceOwnership() public virtual onlyOwner {\n    _transferOwnership(address(0));\n  }\n\n  /**\n   * @dev Transfers ownership of the contract to a new account (`newOwner`).\n   * Can only be called by the current owner.\n   */\n  function transferOwnership(address newOwner) public virtual onlyOwner {\n    require(newOwner != address(0), 'Ownable: new owner is the zero address');\n    _transferOwnership(newOwner);\n  }\n\n  /**\n   * @dev Transfers ownership of the contract to a new account (`newOwner`).\n   * Internal function without access restriction.\n   */\n  function _transferOwnership(address newOwner) internal virtual {\n    address oldOwner = _owner;\n    _owner = newOwner;\n    emit OwnershipTransferred(oldOwner, newOwner);\n  }\n}\n"
      },
      "lib/solidity-utils/src/contracts/oz-common/StorageSlot.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/StorageSlot.sol)\n// From commit https://github.com/OpenZeppelin/openzeppelin-contracts/commit/8b778fa20d6d76340c5fac1ed66c80273f05b95a\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Library for reading and writing primitive types to specific storage slots.\n *\n * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.\n * This library helps with reading and writing to such slots without the need for inline assembly.\n *\n * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.\n *\n * Example usage to set ERC1967 implementation slot:\n * ```\n * contract ERC1967 {\n *     bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;\n *\n *     function _getImplementation() internal view returns (address) {\n *         return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;\n *     }\n *\n *     function _setImplementation(address newImplementation) internal {\n *         require(Address.isContract(newImplementation), \"ERC1967: new implementation is not a contract\");\n *         StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;\n *     }\n * }\n * ```\n *\n * _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._\n */\nlibrary StorageSlot {\n  struct AddressSlot {\n    address value;\n  }\n\n  struct BooleanSlot {\n    bool value;\n  }\n\n  struct Bytes32Slot {\n    bytes32 value;\n  }\n\n  struct Uint256Slot {\n    uint256 value;\n  }\n\n  /**\n   * @dev Returns an `AddressSlot` with member `value` located at `slot`.\n   */\n  function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {\n    /// @solidity memory-safe-assembly\n    assembly {\n      r.slot := slot\n    }\n  }\n\n  /**\n   * @dev Returns an `BooleanSlot` with member `value` located at `slot`.\n   */\n  function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {\n    /// @solidity memory-safe-assembly\n    assembly {\n      r.slot := slot\n    }\n  }\n\n  /**\n   * @dev Returns an `Bytes32Slot` with member `value` located at `slot`.\n   */\n  function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {\n    /// @solidity memory-safe-assembly\n    assembly {\n      r.slot := slot\n    }\n  }\n\n  /**\n   * @dev Returns an `Uint256Slot` with member `value` located at `slot`.\n   */\n  function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {\n    /// @solidity memory-safe-assembly\n    assembly {\n      r.slot := slot\n    }\n  }\n}\n"
      },
      "lib/solidity-utils/src/contracts/oz-common/interfaces/IERC20.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)\n// From commit https://github.com/OpenZeppelin/openzeppelin-contracts/commit/a035b235b4f2c9af4ba88edc4447f02e37f8d124\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20 {\n    /**\n     * @dev Emitted when `value` tokens are moved from one account (`from`) to\n     * another (`to`).\n     *\n     * Note that `value` may be zero.\n     */\n    event Transfer(address indexed from, address indexed to, uint256 value);\n\n    /**\n     * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n     * a call to {approve}. `value` is the new allowance.\n     */\n    event Approval(address indexed owner, address indexed spender, uint256 value);\n\n    /**\n     * @dev Returns the amount of tokens in existence.\n     */\n    function totalSupply() external view returns (uint256);\n\n    /**\n     * @dev Returns the amount of tokens owned by `account`.\n     */\n    function balanceOf(address account) external view returns (uint256);\n\n    /**\n     * @dev Moves `amount` tokens from the caller's account to `to`.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * Emits a {Transfer} event.\n     */\n    function transfer(address to, uint256 amount) external returns (bool);\n\n    /**\n     * @dev Returns the remaining number of tokens that `spender` will be\n     * allowed to spend on behalf of `owner` through {transferFrom}. This is\n     * zero by default.\n     *\n     * This value changes when {approve} or {transferFrom} are called.\n     */\n    function allowance(address owner, address spender) external view returns (uint256);\n\n    /**\n     * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * IMPORTANT: Beware that changing an allowance with this method brings the risk\n     * that someone may use both the old and the new allowance by unfortunate\n     * transaction ordering. One possible solution to mitigate this race\n     * condition is to first reduce the spender's allowance to 0 and set the\n     * desired value afterwards:\n     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n     *\n     * Emits an {Approval} event.\n     */\n    function approve(address spender, uint256 amount) external returns (bool);\n\n    /**\n     * @dev Moves `amount` tokens from `from` to `to` using the\n     * allowance mechanism. `amount` is then deducted from the caller's\n     * allowance.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * Emits a {Transfer} event.\n     */\n    function transferFrom(\n        address from,\n        address to,\n        uint256 amount\n    ) external returns (bool);\n}"
      },
      "lib/solidity-utils/src/contracts/transparent-proxy/ERC1967Proxy.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\n/** @dev OpenZeppelin Contracts (last updated v4.7.0) (proxy/ERC1967/ERC1967Proxy.sol)\n * From https://github.com/OpenZeppelin/openzeppelin-contracts/tree/8b778fa20d6d76340c5fac1ed66c80273f05b95a\n *\n * BGD Labs adaptations:\n * - Same exact version as OZ, only linting changes\n */\n\npragma solidity ^0.8.0;\n\nimport './Proxy.sol';\nimport './ERC1967Upgrade.sol';\n\n/**\n * @dev This contract implements an upgradeable proxy. It is upgradeable because calls are delegated to an\n * implementation address that can be changed. This address is stored in storage in the location specified by\n * https://eips.ethereum.org/EIPS/eip-1967[EIP1967], so that it doesn't conflict with the storage layout of the\n * implementation behind the proxy.\n */\ncontract ERC1967Proxy is Proxy, ERC1967Upgrade {\n  /**\n   * @dev Initializes the upgradeable proxy with an initial implementation specified by `_logic`.\n   *\n   * If `_data` is nonempty, it's used as data in a delegate call to `_logic`. This will typically be an encoded\n   * function call, and allows initializing the storage of the proxy like a Solidity constructor.\n   */\n  constructor(address _logic, bytes memory _data) payable {\n    _upgradeToAndCall(_logic, _data, false);\n  }\n\n  /**\n   * @dev Returns the current implementation address.\n   */\n  function _implementation() internal view virtual override returns (address impl) {\n    return ERC1967Upgrade._getImplementation();\n  }\n}\n"
      },
      "lib/solidity-utils/src/contracts/transparent-proxy/ERC1967Upgrade.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\n/** @dev OpenZeppelin Contracts (last updated v4.5.0) (proxy/ERC1967/ERC1967Upgrade.sol)\n * From https://github.com/OpenZeppelin/openzeppelin-contracts/tree/8b778fa20d6d76340c5fac1ed66c80273f05b95a\n *\n * BGD Labs adaptations:\n * - This is an opinionated version, to be used on \"classic\" transparent upgradeable proxies (non UUPS/Beacon)\n * - For the sake of simplification and gas savings on deployment, the functions/constants related with UUPS/Beacon have been removed\n * - Moved declaration of `_ADMIN_SLOT` constant and `AdminChanged` event to the top\n * - Linting\n * - Removed imports not used anymore due to not have UUPS/Beacon logic\n */\n\npragma solidity ^0.8.2;\n\nimport '../oz-common/Address.sol';\nimport '../oz-common/StorageSlot.sol';\n\n/**\n * @dev This abstract contract provides getters and event emitting update functions for\n * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.\n *\n * _Available since v4.1._\n *\n * @custom:oz-upgrades-unsafe-allow delegatecall\n */\nabstract contract ERC1967Upgrade {\n  /**\n   * @dev Storage slot with the address of the current implementation.\n   * This is the keccak-256 hash of \"eip1967.proxy.implementation\" subtracted by 1, and is\n   * validated in the constructor.\n   */\n  bytes32 internal constant _IMPLEMENTATION_SLOT =\n    0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;\n\n  /**\n   * @dev Storage slot with the admin of the contract.\n   * This is the keccak-256 hash of \"eip1967.proxy.admin\" subtracted by 1, and is\n   * validated in the constructor.\n   */\n  bytes32 internal constant _ADMIN_SLOT =\n    0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;\n\n  /**\n   * @dev Emitted when the implementation is upgraded.\n   */\n  event Upgraded(address indexed implementation);\n\n  /**\n   * @dev Emitted when the admin account has changed.\n   */\n  event AdminChanged(address previousAdmin, address newAdmin);\n\n  /**\n   * @dev Returns the current implementation address.\n   */\n  function _getImplementation() internal view returns (address) {\n    return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;\n  }\n\n  /**\n   * @dev Stores a new address in the EIP1967 implementation slot.\n   */\n  function _setImplementation(address newImplementation) private {\n    require(Address.isContract(newImplementation), 'ERC1967: new implementation is not a contract');\n    StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;\n  }\n\n  /**\n   * @dev Perform implementation upgrade\n   *\n   * Emits an {Upgraded} event.\n   */\n  function _upgradeTo(address newImplementation) internal {\n    _setImplementation(newImplementation);\n    emit Upgraded(newImplementation);\n  }\n\n  /**\n   * @dev Perform implementation upgrade with additional setup call.\n   *\n   * Emits an {Upgraded} event.\n   */\n  function _upgradeToAndCall(\n    address newImplementation,\n    bytes memory data,\n    bool forceCall\n  ) internal {\n    _upgradeTo(newImplementation);\n    if (data.length > 0 || forceCall) {\n      Address.functionDelegateCall(newImplementation, data);\n    }\n  }\n\n  /**\n   * @dev Returns the current admin.\n   */\n  function _getAdmin() internal view returns (address) {\n    return StorageSlot.getAddressSlot(_ADMIN_SLOT).value;\n  }\n\n  /**\n   * @dev Stores a new address in the EIP1967 admin slot.\n   */\n  function _setAdmin(address newAdmin) private {\n    require(newAdmin != address(0), 'ERC1967: new admin is the zero address');\n    StorageSlot.getAddressSlot(_ADMIN_SLOT).value = newAdmin;\n  }\n\n  /**\n   * @dev Changes the admin of the proxy.\n   *\n   * Emits an {AdminChanged} event.\n   */\n  function _changeAdmin(address newAdmin) internal {\n    emit AdminChanged(_getAdmin(), newAdmin);\n    _setAdmin(newAdmin);\n  }\n}\n"
      },
      "lib/solidity-utils/src/contracts/transparent-proxy/Proxy.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\n/**\n * @dev OpenZeppelin Contracts (last updated v4.6.0) (proxy/Proxy.sol)\n * From https://github.com/OpenZeppelin/openzeppelin-contracts/tree/8b778fa20d6d76340c5fac1ed66c80273f05b95a\n *\n * BGD Labs adaptations:\n * - Linting\n */\npragma solidity ^0.8.0;\n\n/**\n * @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM\n * instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to\n * be specified by overriding the virtual {_implementation} function.\n *\n * Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a\n * different contract through the {_delegate} function.\n *\n * The success and return data of the delegated call will be returned back to the caller of the proxy.\n */\nabstract contract Proxy {\n  /**\n   * @dev Delegates the current call to `implementation`.\n   *\n   * This function does not return to its internal call site, it will return directly to the external caller.\n   */\n  function _delegate(address implementation) internal virtual {\n    assembly {\n      // Copy msg.data. We take full control of memory in this inline assembly\n      // block because it will not return to Solidity code. We overwrite the\n      // Solidity scratch pad at memory position 0.\n      calldatacopy(0, 0, calldatasize())\n\n      // Call the implementation.\n      // out and outsize are 0 because we don't know the size yet.\n      let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)\n\n      // Copy the returned data.\n      returndatacopy(0, 0, returndatasize())\n\n      switch result\n      // delegatecall returns 0 on error.\n      case 0 {\n        revert(0, returndatasize())\n      }\n      default {\n        return(0, returndatasize())\n      }\n    }\n  }\n\n  /**\n   * @dev This is a virtual function that should be overridden so it returns the address to which the fallback function\n   * and {_fallback} should delegate.\n   */\n  function _implementation() internal view virtual returns (address);\n\n  /**\n   * @dev Delegates the current call to the address returned by `_implementation()`.\n   *\n   * This function does not return to its internal call site, it will return directly to the external caller.\n   */\n  function _fallback() internal virtual {\n    _beforeFallback();\n    _delegate(_implementation());\n  }\n\n  /**\n   * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other\n   * function in the contract matches the call data.\n   */\n  fallback() external payable virtual {\n    _fallback();\n  }\n\n  /**\n   * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data\n   * is empty.\n   */\n  receive() external payable virtual {\n    _fallback();\n  }\n\n  /**\n   * @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback`\n   * call, or as part of the Solidity `fallback` or `receive` functions.\n   *\n   * If overridden should call `super._beforeFallback()`.\n   */\n  function _beforeFallback() internal virtual {}\n}\n"
      },
      "lib/solidity-utils/src/contracts/transparent-proxy/ProxyAdmin.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\n/**\n * @dev OpenZeppelin Contracts v4.4.1 (proxy/transparent/ProxyAdmin.sol)\n * From https://github.com/OpenZeppelin/openzeppelin-contracts/tree/8b778fa20d6d76340c5fac1ed66c80273f05b95a\n *\n * BGD Labs adaptations:\n * - Linting\n */\n\npragma solidity ^0.8.0;\n\nimport './TransparentUpgradeableProxy.sol';\nimport '../oz-common/Ownable.sol';\n\n/**\n * @dev This is an auxiliary contract meant to be assigned as the admin of a {TransparentUpgradeableProxy}. For an\n * explanation of why you would want to use this see the documentation for {TransparentUpgradeableProxy}.\n */\ncontract ProxyAdmin is Ownable {\n  /**\n   * @dev Returns the current implementation of `proxy`.\n   *\n   * Requirements:\n   *\n   * - This contract must be the admin of `proxy`.\n   */\n  function getProxyImplementation(TransparentUpgradeableProxy proxy)\n    public\n    view\n    virtual\n    returns (address)\n  {\n    // We need to manually run the static call since the getter cannot be flagged as view\n    // bytes4(keccak256(\"implementation()\")) == 0x5c60da1b\n    (bool success, bytes memory returndata) = address(proxy).staticcall(hex'5c60da1b');\n    require(success);\n    return abi.decode(returndata, (address));\n  }\n\n  /**\n   * @dev Returns the current admin of `proxy`.\n   *\n   * Requirements:\n   *\n   * - This contract must be the admin of `proxy`.\n   */\n  function getProxyAdmin(TransparentUpgradeableProxy proxy) public view virtual returns (address) {\n    // We need to manually run the static call since the getter cannot be flagged as view\n    // bytes4(keccak256(\"admin()\")) == 0xf851a440\n    (bool success, bytes memory returndata) = address(proxy).staticcall(hex'f851a440');\n    require(success);\n    return abi.decode(returndata, (address));\n  }\n\n  /**\n   * @dev Changes the admin of `proxy` to `newAdmin`.\n   *\n   * Requirements:\n   *\n   * - This contract must be the current admin of `proxy`.\n   */\n  function changeProxyAdmin(TransparentUpgradeableProxy proxy, address newAdmin)\n    public\n    virtual\n    onlyOwner\n  {\n    proxy.changeAdmin(newAdmin);\n  }\n\n  /**\n   * @dev Upgrades `proxy` to `implementation`. See {TransparentUpgradeableProxy-upgradeTo}.\n   *\n   * Requirements:\n   *\n   * - This contract must be the admin of `proxy`.\n   */\n  function upgrade(TransparentUpgradeableProxy proxy, address implementation)\n    public\n    virtual\n    onlyOwner\n  {\n    proxy.upgradeTo(implementation);\n  }\n\n  /**\n   * @dev Upgrades `proxy` to `implementation` and calls a function on the new implementation. See\n   * {TransparentUpgradeableProxy-upgradeToAndCall}.\n   *\n   * Requirements:\n   *\n   * - This contract must be the admin of `proxy`.\n   */\n  function upgradeAndCall(\n    TransparentUpgradeableProxy proxy,\n    address implementation,\n    bytes memory data\n  ) public payable virtual onlyOwner {\n    proxy.upgradeToAndCall{value: msg.value}(implementation, data);\n  }\n}\n"
      },
      "lib/solidity-utils/src/contracts/transparent-proxy/TransparentUpgradeableProxy.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\n/**\n * @dev OpenZeppelin Contracts (last updated v4.7.0) (proxy/utils/Initializable.sol)\n * From https://github.com/OpenZeppelin/openzeppelin-contracts/tree/8b778fa20d6d76340c5fac1ed66c80273f05b95a\n *\n * BGD Labs adaptations:\n * - Linting\n */\n\npragma solidity ^0.8.0;\n\nimport './ERC1967Proxy.sol';\n\n/**\n * @dev This contract implements a proxy that is upgradeable by an admin.\n *\n * To avoid https://medium.com/nomic-labs-blog/malicious-backdoors-in-ethereum-proxies-62629adf3357[proxy selector\n * clashing], which can potentially be used in an attack, this contract uses the\n * https://blog.openzeppelin.com/the-transparent-proxy-pattern/[transparent proxy pattern]. This pattern implies two\n * things that go hand in hand:\n *\n * 1. If any account other than the admin calls the proxy, the call will be forwarded to the implementation, even if\n * that call matches one of the admin functions exposed by the proxy itself.\n * 2. If the admin calls the proxy, it can access the admin functions, but its calls will never be forwarded to the\n * implementation. If the admin tries to call a function on the implementation it will fail with an error that says\n * \"admin cannot fallback to proxy target\".\n *\n * These properties mean that the admin account can only be used for admin actions like upgrading the proxy or changing\n * the admin, so it's best if it's a dedicated account that is not used for anything else. This will avoid headaches due\n * to sudden errors when trying to call a function from the proxy implementation.\n *\n * Our recommendation is for the dedicated account to be an instance of the {ProxyAdmin} contract. If set up this way,\n * you should think of the `ProxyAdmin` instance as the real administrative interface of your proxy.\n */\ncontract TransparentUpgradeableProxy is ERC1967Proxy {\n  /**\n   * @dev Initializes an upgradeable proxy managed by `_admin`, backed by the implementation at `_logic`, and\n   * optionally initialized with `_data` as explained in {ERC1967Proxy-constructor}.\n   */\n  constructor(\n    address _logic,\n    address admin_,\n    bytes memory _data\n  ) payable ERC1967Proxy(_logic, _data) {\n    _changeAdmin(admin_);\n  }\n\n  /**\n   * @dev Modifier used internally that will delegate the call to the implementation unless the sender is the admin.\n   */\n  modifier ifAdmin() {\n    if (msg.sender == _getAdmin()) {\n      _;\n    } else {\n      _fallback();\n    }\n  }\n\n  /**\n   * @dev Returns the current admin.\n   *\n   * NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyAdmin}.\n   *\n   * TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the\n   * https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.\n   * `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`\n   */\n  function admin() external ifAdmin returns (address admin_) {\n    admin_ = _getAdmin();\n  }\n\n  /**\n   * @dev Returns the current implementation.\n   *\n   * NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyImplementation}.\n   *\n   * TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the\n   * https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.\n   * `0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc`\n   */\n  function implementation() external ifAdmin returns (address implementation_) {\n    implementation_ = _implementation();\n  }\n\n  /**\n   * @dev Changes the admin of the proxy.\n   *\n   * Emits an {AdminChanged} event.\n   *\n   * NOTE: Only the admin can call this function. See {ProxyAdmin-changeProxyAdmin}.\n   */\n  function changeAdmin(address newAdmin) external virtual ifAdmin {\n    _changeAdmin(newAdmin);\n  }\n\n  /**\n   * @dev Upgrade the implementation of the proxy.\n   *\n   * NOTE: Only the admin can call this function. See {ProxyAdmin-upgrade}.\n   */\n  function upgradeTo(address newImplementation) external ifAdmin {\n    _upgradeToAndCall(newImplementation, bytes(''), false);\n  }\n\n  /**\n   * @dev Upgrade the implementation of the proxy, and then call a function from the new implementation as specified\n   * by `data`, which should be an encoded function call. This is useful to initialize new storage variables in the\n   * proxied contract.\n   *\n   * NOTE: Only the admin can call this function. See {ProxyAdmin-upgradeAndCall}.\n   */\n  function upgradeToAndCall(address newImplementation, bytes calldata data)\n    external\n    payable\n    ifAdmin\n  {\n    _upgradeToAndCall(newImplementation, data, true);\n  }\n\n  /**\n   * @dev Returns the current admin.\n   */\n  function _admin() internal view virtual returns (address) {\n    return _getAdmin();\n  }\n\n  /**\n   * @dev Makes sure the admin cannot access the fallback function. See {Proxy-_beforeFallback}.\n   */\n  function _beforeFallback() internal virtual override {\n    require(\n      msg.sender != _getAdmin(),\n      'TransparentUpgradeableProxy: admin cannot fallback to proxy target'\n    );\n    super._beforeFallback();\n  }\n}\n"
      },
      "src/core/contracts/dependencies/gnosis/contracts/GPv2SafeERC20.sol": {
        "content": "// SPDX-License-Identifier: LGPL-3.0-or-later\npragma solidity ^0.8.10;\n\nimport {IERC20} from '../../openzeppelin/contracts/IERC20.sol';\n\n/// @title Gnosis Protocol v2 Safe ERC20 Transfer Library\n/// @author Gnosis Developers\n/// @dev Gas-efficient version of Openzeppelin's SafeERC20 contract.\nlibrary GPv2SafeERC20 {\n  /// @dev Wrapper around a call to the ERC20 function `transfer` that reverts\n  /// also when the token returns `false`.\n  function safeTransfer(IERC20 token, address to, uint256 value) internal {\n    bytes4 selector_ = token.transfer.selector;\n\n    // solhint-disable-next-line no-inline-assembly\n    assembly {\n      let freeMemoryPointer := mload(0x40)\n      mstore(freeMemoryPointer, selector_)\n      mstore(add(freeMemoryPointer, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff))\n      mstore(add(freeMemoryPointer, 36), value)\n\n      if iszero(call(gas(), token, 0, freeMemoryPointer, 68, 0, 0)) {\n        returndatacopy(0, 0, returndatasize())\n        revert(0, returndatasize())\n      }\n    }\n\n    require(getLastTransferResult(token), 'GPv2: failed transfer');\n  }\n\n  /// @dev Wrapper around a call to the ERC20 function `transferFrom` that\n  /// reverts also when the token returns `false`.\n  function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {\n    bytes4 selector_ = token.transferFrom.selector;\n\n    // solhint-disable-next-line no-inline-assembly\n    assembly {\n      let freeMemoryPointer := mload(0x40)\n      mstore(freeMemoryPointer, selector_)\n      mstore(add(freeMemoryPointer, 4), and(from, 0xffffffffffffffffffffffffffffffffffffffff))\n      mstore(add(freeMemoryPointer, 36), and(to, 0xffffffffffffffffffffffffffffffffffffffff))\n      mstore(add(freeMemoryPointer, 68), value)\n\n      if iszero(call(gas(), token, 0, freeMemoryPointer, 100, 0, 0)) {\n        returndatacopy(0, 0, returndatasize())\n        revert(0, returndatasize())\n      }\n    }\n\n    require(getLastTransferResult(token), 'GPv2: failed transferFrom');\n  }\n\n  /// @dev Verifies that the last return was a successful `transfer*` call.\n  /// This is done by checking that the return data is either empty, or\n  /// is a valid ABI encoded boolean.\n  function getLastTransferResult(IERC20 token) private view returns (bool success) {\n    // NOTE: Inspecting previous return data requires assembly. Note that\n    // we write the return data to memory 0 in the case where the return\n    // data size is 32, this is OK since the first 64 bytes of memory are\n    // reserved by Solidy as a scratch space that can be used within\n    // assembly blocks.\n    // <https://docs.soliditylang.org/en/v0.7.6/internals/layout_in_memory.html>\n    // solhint-disable-next-line no-inline-assembly\n    assembly {\n      /// @dev Revert with an ABI encoded Solidity error with a message\n      /// that fits into 32-bytes.\n      ///\n      /// An ABI encoded Solidity error has the following memory layout:\n      ///\n      /// ------------+----------------------------------\n      ///  byte range | value\n      /// ------------+----------------------------------\n      ///  0x00..0x04 |        selector(\"Error(string)\")\n      ///  0x04..0x24 |      string offset (always 0x20)\n      ///  0x24..0x44 |                    string length\n      ///  0x44..0x64 | string value, padded to 32-bytes\n      function revertWithMessage(length, message) {\n        mstore(0x00, '\\x08\\xc3\\x79\\xa0')\n        mstore(0x04, 0x20)\n        mstore(0x24, length)\n        mstore(0x44, message)\n        revert(0x00, 0x64)\n      }\n\n      switch returndatasize()\n      // Non-standard ERC20 transfer without return.\n      case 0 {\n        // NOTE: When the return data size is 0, verify that there\n        // is code at the address. This is done in order to maintain\n        // compatibility with Solidity calling conventions.\n        // <https://docs.soliditylang.org/en/v0.7.6/control-structures.html#external-function-calls>\n        if iszero(extcodesize(token)) {\n          revertWithMessage(20, 'GPv2: not a contract')\n        }\n\n        success := 1\n      }\n      // Standard ERC20 transfer returning boolean success value.\n      case 32 {\n        returndatacopy(0, 0, returndatasize())\n\n        // NOTE: For ABI encoding v1, any non-zero value is accepted\n        // as `true` for a boolean. In order to stay compatible with\n        // OpenZeppelin's `SafeERC20` library which is known to work\n        // with the existing ERC20 implementation we care about,\n        // make sure we return success for any non-zero return value\n        // from the `transfer*` call.\n        success := iszero(iszero(mload(0)))\n      }\n      default {\n        revertWithMessage(31, 'GPv2: malformed transfer result')\n      }\n    }\n  }\n}\n"
      },
      "src/core/contracts/dependencies/openzeppelin/contracts/Address.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n  /**\n   * @dev Returns true if `account` is a contract.\n   *\n   * [IMPORTANT]\n   * ====\n   * It is unsafe to assume that an address for which this function returns\n   * false is an externally-owned account (EOA) and not a contract.\n   *\n   * Among others, `isContract` will return false for the following\n   * types of addresses:\n   *\n   *  - an externally-owned account\n   *  - a contract in construction\n   *  - an address where a contract will be created\n   *  - an address where a contract lived, but was destroyed\n   * ====\n   */\n  function isContract(address account) internal view returns (bool) {\n    // This method relies on extcodesize, which returns 0 for contracts in\n    // construction, since the code is only stored at the end of the\n    // constructor execution.\n\n    uint256 size;\n    assembly {\n      size := extcodesize(account)\n    }\n    return size > 0;\n  }\n\n  /**\n   * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n   * `recipient`, forwarding all available gas and reverting on errors.\n   *\n   * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n   * of certain opcodes, possibly making contracts go over the 2300 gas limit\n   * imposed by `transfer`, making them unable to receive funds via\n   * `transfer`. {sendValue} removes this limitation.\n   *\n   * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n   *\n   * IMPORTANT: because control is transferred to `recipient`, care must be\n   * taken to not create reentrancy vulnerabilities. Consider using\n   * {ReentrancyGuard} or the\n   * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n   */\n  function sendValue(address payable recipient, uint256 amount) internal {\n    require(address(this).balance >= amount, 'Address: insufficient balance');\n\n    (bool success, ) = recipient.call{value: amount}('');\n    require(success, 'Address: unable to send value, recipient may have reverted');\n  }\n\n  /**\n   * @dev Performs a Solidity function call using a low level `call`. A\n   * plain `call` is an unsafe replacement for a function call: use this\n   * function instead.\n   *\n   * If `target` reverts with a revert reason, it is bubbled up by this\n   * function (like regular Solidity function calls).\n   *\n   * Returns the raw returned data. To convert to the expected return value,\n   * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n   *\n   * Requirements:\n   *\n   * - `target` must be a contract.\n   * - calling `target` with `data` must not revert.\n   *\n   * _Available since v3.1._\n   */\n  function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n    return functionCall(target, data, 'Address: low-level call failed');\n  }\n\n  /**\n   * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n   * `errorMessage` as a fallback revert reason when `target` reverts.\n   *\n   * _Available since v3.1._\n   */\n  function functionCall(\n    address target,\n    bytes memory data,\n    string memory errorMessage\n  ) internal returns (bytes memory) {\n    return functionCallWithValue(target, data, 0, errorMessage);\n  }\n\n  /**\n   * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n   * but also transferring `value` wei to `target`.\n   *\n   * Requirements:\n   *\n   * - the calling contract must have an ETH balance of at least `value`.\n   * - the called Solidity function must be `payable`.\n   *\n   * _Available since v3.1._\n   */\n  function functionCallWithValue(\n    address target,\n    bytes memory data,\n    uint256 value\n  ) internal returns (bytes memory) {\n    return functionCallWithValue(target, data, value, 'Address: low-level call with value failed');\n  }\n\n  /**\n   * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n   * with `errorMessage` as a fallback revert reason when `target` reverts.\n   *\n   * _Available since v3.1._\n   */\n  function functionCallWithValue(\n    address target,\n    bytes memory data,\n    uint256 value,\n    string memory errorMessage\n  ) internal returns (bytes memory) {\n    require(address(this).balance >= value, 'Address: insufficient balance for call');\n    require(isContract(target), 'Address: call to non-contract');\n\n    (bool success, bytes memory returndata) = target.call{value: value}(data);\n    return verifyCallResult(success, returndata, errorMessage);\n  }\n\n  /**\n   * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n   * but performing a static call.\n   *\n   * _Available since v3.3._\n   */\n  function functionStaticCall(\n    address target,\n    bytes memory data\n  ) internal view returns (bytes memory) {\n    return functionStaticCall(target, data, 'Address: low-level static call failed');\n  }\n\n  /**\n   * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n   * but performing a static call.\n   *\n   * _Available since v3.3._\n   */\n  function functionStaticCall(\n    address target,\n    bytes memory data,\n    string memory errorMessage\n  ) internal view returns (bytes memory) {\n    require(isContract(target), 'Address: static call to non-contract');\n\n    (bool success, bytes memory returndata) = target.staticcall(data);\n    return verifyCallResult(success, returndata, errorMessage);\n  }\n\n  /**\n   * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n   * but performing a delegate call.\n   *\n   * _Available since v3.4._\n   */\n  function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n    return functionDelegateCall(target, data, 'Address: low-level delegate call failed');\n  }\n\n  /**\n   * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n   * but performing a delegate call.\n   *\n   * _Available since v3.4._\n   */\n  function functionDelegateCall(\n    address target,\n    bytes memory data,\n    string memory errorMessage\n  ) internal returns (bytes memory) {\n    require(isContract(target), 'Address: delegate call to non-contract');\n\n    (bool success, bytes memory returndata) = target.delegatecall(data);\n    return verifyCallResult(success, returndata, errorMessage);\n  }\n\n  /**\n   * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the\n   * revert reason using the provided one.\n   *\n   * _Available since v4.3._\n   */\n  function verifyCallResult(\n    bool success,\n    bytes memory returndata,\n    string memory errorMessage\n  ) internal pure returns (bytes memory) {\n    if (success) {\n      return returndata;\n    } else {\n      // Look for revert reason and bubble it up if present\n      if (returndata.length > 0) {\n        // The easiest way to bubble the revert reason is using memory via assembly\n\n        assembly {\n          let returndata_size := mload(returndata)\n          revert(add(32, returndata), returndata_size)\n        }\n      } else {\n        revert(errorMessage);\n      }\n    }\n  }\n}\n"
      },
      "src/core/contracts/dependencies/openzeppelin/contracts/Context.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n/*\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with GSN meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract Context {\n  function _msgSender() internal view virtual returns (address payable) {\n    return payable(msg.sender);\n  }\n\n  function _msgData() internal view virtual returns (bytes memory) {\n    this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691\n    return msg.data;\n  }\n}\n"
      },
      "src/core/contracts/dependencies/openzeppelin/contracts/IAccessControl.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.10;\n\n/**\n * @dev External interface of AccessControl declared to support ERC165 detection.\n */\ninterface IAccessControl {\n  /**\n   * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`\n   *\n   * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite\n   * {RoleAdminChanged} not being emitted signaling this.\n   *\n   * _Available since v3.1._\n   */\n  event RoleAdminChanged(\n    bytes32 indexed role,\n    bytes32 indexed previousAdminRole,\n    bytes32 indexed newAdminRole\n  );\n\n  /**\n   * @dev Emitted when `account` is granted `role`.\n   *\n   * `sender` is the account that originated the contract call, an admin role\n   * bearer except when using {AccessControl-_setupRole}.\n   */\n  event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);\n\n  /**\n   * @dev Emitted when `account` is revoked `role`.\n   *\n   * `sender` is the account that originated the contract call:\n   *   - if using `revokeRole`, it is the admin role bearer\n   *   - if using `renounceRole`, it is the role bearer (i.e. `account`)\n   */\n  event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);\n\n  /**\n   * @dev Returns `true` if `account` has been granted `role`.\n   */\n  function hasRole(bytes32 role, address account) external view returns (bool);\n\n  /**\n   * @dev Returns the admin role that controls `role`. See {grantRole} and\n   * {revokeRole}.\n   *\n   * To change a role's admin, use {AccessControl-_setRoleAdmin}.\n   */\n  function getRoleAdmin(bytes32 role) external view returns (bytes32);\n\n  /**\n   * @dev Grants `role` to `account`.\n   *\n   * If `account` had not been already granted `role`, emits a {RoleGranted}\n   * event.\n   *\n   * Requirements:\n   *\n   * - the caller must have ``role``'s admin role.\n   */\n  function grantRole(bytes32 role, address account) external;\n\n  /**\n   * @dev Revokes `role` from `account`.\n   *\n   * If `account` had been granted `role`, emits a {RoleRevoked} event.\n   *\n   * Requirements:\n   *\n   * - the caller must have ``role``'s admin role.\n   */\n  function revokeRole(bytes32 role, address account) external;\n\n  /**\n   * @dev Revokes `role` from the calling account.\n   *\n   * Roles are often managed via {grantRole} and {revokeRole}: this function's\n   * purpose is to provide a mechanism for accounts to lose their privileges\n   * if they are compromised (such as when a trusted device is misplaced).\n   *\n   * If the calling account had been granted `role`, emits a {RoleRevoked}\n   * event.\n   *\n   * Requirements:\n   *\n   * - the caller must be `account`.\n   */\n  function renounceRole(bytes32 role, address account) external;\n}\n"
      },
      "src/core/contracts/dependencies/openzeppelin/contracts/IERC20.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20 {\n  /**\n   * @dev Returns the amount of tokens in existence.\n   */\n  function totalSupply() external view returns (uint256);\n\n  /**\n   * @dev Returns the amount of tokens owned by `account`.\n   */\n  function balanceOf(address account) external view returns (uint256);\n\n  /**\n   * @dev Moves `amount` tokens from the caller's account to `recipient`.\n   *\n   * Returns a boolean value indicating whether the operation succeeded.\n   *\n   * Emits a {Transfer} event.\n   */\n  function transfer(address recipient, uint256 amount) external returns (bool);\n\n  /**\n   * @dev Returns the remaining number of tokens that `spender` will be\n   * allowed to spend on behalf of `owner` through {transferFrom}. This is\n   * zero by default.\n   *\n   * This value changes when {approve} or {transferFrom} are called.\n   */\n  function allowance(address owner, address spender) external view returns (uint256);\n\n  /**\n   * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.\n   *\n   * Returns a boolean value indicating whether the operation succeeded.\n   *\n   * IMPORTANT: Beware that changing an allowance with this method brings the risk\n   * that someone may use both the old and the new allowance by unfortunate\n   * transaction ordering. One possible solution to mitigate this race\n   * condition is to first reduce the spender's allowance to 0 and set the\n   * desired value afterwards:\n   * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n   *\n   * Emits an {Approval} event.\n   */\n  function approve(address spender, uint256 amount) external returns (bool);\n\n  /**\n   * @dev Moves `amount` tokens from `sender` to `recipient` using the\n   * allowance mechanism. `amount` is then deducted from the caller's\n   * allowance.\n   *\n   * Returns a boolean value indicating whether the operation succeeded.\n   *\n   * Emits a {Transfer} event.\n   */\n  function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);\n\n  /**\n   * @dev Emitted when `value` tokens are moved from one account (`from`) to\n   * another (`to`).\n   *\n   * Note that `value` may be zero.\n   */\n  event Transfer(address indexed from, address indexed to, uint256 value);\n\n  /**\n   * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n   * a call to {approve}. `value` is the new allowance.\n   */\n  event Approval(address indexed owner, address indexed spender, uint256 value);\n}\n"
      },
      "src/core/contracts/dependencies/openzeppelin/contracts/IERC20Detailed.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport {IERC20} from './IERC20.sol';\n\ninterface IERC20Detailed is IERC20 {\n  function name() external view returns (string memory);\n\n  function symbol() external view returns (string memory);\n\n  function decimals() external view returns (uint8);\n}\n"
      },
      "src/core/contracts/dependencies/openzeppelin/contracts/Ownable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.10;\n\nimport './Context.sol';\n\n/**\n * @dev Contract module which provides a basic access control mechanism, where\n * there is an account (an owner) that can be granted exclusive access to\n * specific functions.\n *\n * By default, the owner account will be the one that deploys the contract. This\n * can later be changed with {transferOwnership}.\n *\n * This module is used through inheritance. It will make available the modifier\n * `onlyOwner`, which can be applied to your functions to restrict their use to\n * the owner.\n */\ncontract Ownable is Context {\n  address private _owner;\n\n  event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);\n\n  /**\n   * @dev Initializes the contract setting the deployer as the initial owner.\n   */\n  constructor() {\n    address msgSender = _msgSender();\n    _owner = msgSender;\n    emit OwnershipTransferred(address(0), msgSender);\n  }\n\n  /**\n   * @dev Returns the address of the current owner.\n   */\n  function owner() public view returns (address) {\n    return _owner;\n  }\n\n  /**\n   * @dev Throws if called by any account other than the owner.\n   */\n  modifier onlyOwner() {\n    require(_owner == _msgSender(), 'Ownable: caller is not the owner');\n    _;\n  }\n\n  /**\n   * @dev Leaves the contract without owner. It will not be possible to call\n   * `onlyOwner` functions anymore. Can only be called by the current owner.\n   *\n   * NOTE: Renouncing ownership will leave the contract without an owner,\n   * thereby removing any functionality that is only available to the owner.\n   */\n  function renounceOwnership() public virtual onlyOwner {\n    emit OwnershipTransferred(_owner, address(0));\n    _owner = address(0);\n  }\n\n  /**\n   * @dev Transfers ownership of the contract to a new account (`newOwner`).\n   * Can only be called by the current owner.\n   */\n  function transferOwnership(address newOwner) public virtual onlyOwner {\n    require(newOwner != address(0), 'Ownable: new owner is the zero address');\n    emit OwnershipTransferred(_owner, newOwner);\n    _owner = newOwner;\n  }\n}\n"
      },
      "src/core/contracts/dependencies/openzeppelin/contracts/SafeCast.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/math/SafeCast.sol)\npragma solidity ^0.8.10;\n\n/**\n * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow\n * checks.\n *\n * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can\n * easily result in undesired exploitation or bugs, since developers usually\n * assume that overflows raise errors. `SafeCast` restores this intuition by\n * reverting the transaction when such an operation overflows.\n *\n * Using this library instead of the unchecked operations eliminates an entire\n * class of bugs, so it's recommended to use it always.\n *\n * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing\n * all math on `uint256` and `int256` and then downcasting.\n */\nlibrary SafeCast {\n  /**\n   * @dev Returns the downcasted uint224 from uint256, reverting on\n   * overflow (when the input is greater than largest uint224).\n   *\n   * Counterpart to Solidity's `uint224` operator.\n   *\n   * Requirements:\n   *\n   * - input must fit into 224 bits\n   */\n  function toUint224(uint256 value) internal pure returns (uint224) {\n    require(value <= type(uint224).max, \"SafeCast: value doesn't fit in 224 bits\");\n    return uint224(value);\n  }\n\n  /**\n   * @dev Returns the downcasted uint128 from uint256, reverting on\n   * overflow (when the input is greater than largest uint128).\n   *\n   * Counterpart to Solidity's `uint128` operator.\n   *\n   * Requirements:\n   *\n   * - input must fit into 128 bits\n   */\n  function toUint128(uint256 value) internal pure returns (uint128) {\n    require(value <= type(uint128).max, \"SafeCast: value doesn't fit in 128 bits\");\n    return uint128(value);\n  }\n\n  /**\n   * @dev Returns the downcasted uint96 from uint256, reverting on\n   * overflow (when the input is greater than largest uint96).\n   *\n   * Counterpart to Solidity's `uint96` operator.\n   *\n   * Requirements:\n   *\n   * - input must fit into 96 bits\n   */\n  function toUint96(uint256 value) internal pure returns (uint96) {\n    require(value <= type(uint96).max, \"SafeCast: value doesn't fit in 96 bits\");\n    return uint96(value);\n  }\n\n  /**\n   * @dev Returns the downcasted uint64 from uint256, reverting on\n   * overflow (when the input is greater than largest uint64).\n   *\n   * Counterpart to Solidity's `uint64` operator.\n   *\n   * Requirements:\n   *\n   * - input must fit into 64 bits\n   */\n  function toUint64(uint256 value) internal pure returns (uint64) {\n    require(value <= type(uint64).max, \"SafeCast: value doesn't fit in 64 bits\");\n    return uint64(value);\n  }\n\n  /**\n   * @dev Returns the downcasted uint32 from uint256, reverting on\n   * overflow (when the input is greater than largest uint32).\n   *\n   * Counterpart to Solidity's `uint32` operator.\n   *\n   * Requirements:\n   *\n   * - input must fit into 32 bits\n   */\n  function toUint32(uint256 value) internal pure returns (uint32) {\n    require(value <= type(uint32).max, \"SafeCast: value doesn't fit in 32 bits\");\n    return uint32(value);\n  }\n\n  /**\n   * @dev Returns the downcasted uint16 from uint256, reverting on\n   * overflow (when the input is greater than largest uint16).\n   *\n   * Counterpart to Solidity's `uint16` operator.\n   *\n   * Requirements:\n   *\n   * - input must fit into 16 bits\n   */\n  function toUint16(uint256 value) internal pure returns (uint16) {\n    require(value <= type(uint16).max, \"SafeCast: value doesn't fit in 16 bits\");\n    return uint16(value);\n  }\n\n  /**\n   * @dev Returns the downcasted uint8 from uint256, reverting on\n   * overflow (when the input is greater than largest uint8).\n   *\n   * Counterpart to Solidity's `uint8` operator.\n   *\n   * Requirements:\n   *\n   * - input must fit into 8 bits.\n   */\n  function toUint8(uint256 value) internal pure returns (uint8) {\n    require(value <= type(uint8).max, \"SafeCast: value doesn't fit in 8 bits\");\n    return uint8(value);\n  }\n\n  /**\n   * @dev Converts a signed int256 into an unsigned uint256.\n   *\n   * Requirements:\n   *\n   * - input must be greater than or equal to 0.\n   */\n  function toUint256(int256 value) internal pure returns (uint256) {\n    require(value >= 0, 'SafeCast: value must be positive');\n    return uint256(value);\n  }\n\n  /**\n   * @dev Returns the downcasted int128 from int256, reverting on\n   * overflow (when the input is less than smallest int128 or\n   * greater than largest int128).\n   *\n   * Counterpart to Solidity's `int128` operator.\n   *\n   * Requirements:\n   *\n   * - input must fit into 128 bits\n   *\n   * _Available since v3.1._\n   */\n  function toInt128(int256 value) internal pure returns (int128) {\n    require(\n      value >= type(int128).min && value <= type(int128).max,\n      \"SafeCast: value doesn't fit in 128 bits\"\n    );\n    return int128(value);\n  }\n\n  /**\n   * @dev Returns the downcasted int64 from int256, reverting on\n   * overflow (when the input is less than smallest int64 or\n   * greater than largest int64).\n   *\n   * Counterpart to Solidity's `int64` operator.\n   *\n   * Requirements:\n   *\n   * - input must fit into 64 bits\n   *\n   * _Available since v3.1._\n   */\n  function toInt64(int256 value) internal pure returns (int64) {\n    require(\n      value >= type(int64).min && value <= type(int64).max,\n      \"SafeCast: value doesn't fit in 64 bits\"\n    );\n    return int64(value);\n  }\n\n  /**\n   * @dev Returns the downcasted int32 from int256, reverting on\n   * overflow (when the input is less than smallest int32 or\n   * greater than largest int32).\n   *\n   * Counterpart to Solidity's `int32` operator.\n   *\n   * Requirements:\n   *\n   * - input must fit into 32 bits\n   *\n   * _Available since v3.1._\n   */\n  function toInt32(int256 value) internal pure returns (int32) {\n    require(\n      value >= type(int32).min && value <= type(int32).max,\n      \"SafeCast: value doesn't fit in 32 bits\"\n    );\n    return int32(value);\n  }\n\n  /**\n   * @dev Returns the downcasted int16 from int256, reverting on\n   * overflow (when the input is less than smallest int16 or\n   * greater than largest int16).\n   *\n   * Counterpart to Solidity's `int16` operator.\n   *\n   * Requirements:\n   *\n   * - input must fit into 16 bits\n   *\n   * _Available since v3.1._\n   */\n  function toInt16(int256 value) internal pure returns (int16) {\n    require(\n      value >= type(int16).min && value <= type(int16).max,\n      \"SafeCast: value doesn't fit in 16 bits\"\n    );\n    return int16(value);\n  }\n\n  /**\n   * @dev Returns the downcasted int8 from int256, reverting on\n   * overflow (when the input is less than smallest int8 or\n   * greater than largest int8).\n   *\n   * Counterpart to Solidity's `int8` operator.\n   *\n   * Requirements:\n   *\n   * - input must fit into 8 bits.\n   *\n   * _Available since v3.1._\n   */\n  function toInt8(int256 value) internal pure returns (int8) {\n    require(\n      value >= type(int8).min && value <= type(int8).max,\n      \"SafeCast: value doesn't fit in 8 bits\"\n    );\n    return int8(value);\n  }\n\n  /**\n   * @dev Converts an unsigned uint256 into a signed int256.\n   *\n   * Requirements:\n   *\n   * - input must be less than or equal to maxInt256.\n   */\n  function toInt256(uint256 value) internal pure returns (int256) {\n    // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive\n    require(value <= uint256(type(int256).max), \"SafeCast: value doesn't fit in an int256\");\n    return int256(value);\n  }\n}\n"
      },
      "src/core/contracts/dependencies/openzeppelin/contracts/SafeERC20.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol)\n\npragma solidity ^0.8.0;\n\nimport './IERC20.sol';\nimport './Address.sol';\n\n/**\n * @title SafeERC20\n * @dev Wrappers around ERC20 operations that throw on failure (when the token\n * contract returns false). Tokens that return no value (and instead revert or\n * throw on failure) are also supported, non-reverting calls are assumed to be\n * successful.\n * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,\n * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.\n */\nlibrary SafeERC20 {\n  using Address for address;\n\n  function safeTransfer(IERC20 token, address to, uint256 value) internal {\n    _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));\n  }\n\n  function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {\n    _callOptionalReturn(\n      token,\n      abi.encodeWithSelector(token.transferFrom.selector, from, to, value)\n    );\n  }\n\n  /**\n   * @dev Deprecated. This function has issues similar to the ones found in\n   * {IERC20-approve}, and its usage is discouraged.\n   *\n   * Whenever possible, use {safeIncreaseAllowance} and\n   * {safeDecreaseAllowance} instead.\n   */\n  function safeApprove(IERC20 token, address spender, uint256 value) internal {\n    // safeApprove should only be called when setting an initial allowance,\n    // or when resetting it to zero. To increase and decrease it, use\n    // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'\n    require(\n      (value == 0) || (token.allowance(address(this), spender) == 0),\n      'SafeERC20: approve from non-zero to non-zero allowance'\n    );\n    _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));\n  }\n\n  function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {\n    uint256 newAllowance = token.allowance(address(this), spender) + value;\n    _callOptionalReturn(\n      token,\n      abi.encodeWithSelector(token.approve.selector, spender, newAllowance)\n    );\n  }\n\n  function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {\n    unchecked {\n      uint256 oldAllowance = token.allowance(address(this), spender);\n      require(oldAllowance >= value, 'SafeERC20: decreased allowance below zero');\n      uint256 newAllowance = oldAllowance - value;\n      _callOptionalReturn(\n        token,\n        abi.encodeWithSelector(token.approve.selector, spender, newAllowance)\n      );\n    }\n  }\n\n  /**\n   * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\n   * on the return value: the return value is optional (but if data is returned, it must not be false).\n   * @param token The token targeted by the call.\n   * @param data The call data (encoded using abi.encode or one of its variants).\n   */\n  function _callOptionalReturn(IERC20 token, bytes memory data) private {\n    // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since\n    // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that\n    // the target address contains contract code and also asserts for success in the low-level call.\n\n    bytes memory returndata = address(token).functionCall(data, 'SafeERC20: low-level call failed');\n    if (returndata.length > 0) {\n      // Return data is optional\n      require(abi.decode(returndata, (bool)), 'SafeERC20: ERC20 operation did not succeed');\n    }\n  }\n}\n"
      },
      "src/core/contracts/dependencies/openzeppelin/contracts/SafeMath.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n/// @title Optimized overflow and underflow safe math operations\n/// @notice Contains methods for doing math operations that revert on overflow or underflow for minimal gas cost\nlibrary SafeMath {\n  /// @notice Returns x + y, reverts if sum overflows uint256\n  /// @param x The augend\n  /// @param y The addend\n  /// @return z The sum of x and y\n  function add(uint256 x, uint256 y) internal pure returns (uint256 z) {\n    unchecked {\n      require((z = x + y) >= x);\n    }\n  }\n\n  /// @notice Returns x - y, reverts if underflows\n  /// @param x The minuend\n  /// @param y The subtrahend\n  /// @return z The difference of x and y\n  function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {\n    unchecked {\n      require((z = x - y) <= x);\n    }\n  }\n\n  /// @notice Returns x - y, reverts if underflows\n  /// @param x The minuend\n  /// @param y The subtrahend\n  /// @param message The error msg\n  /// @return z The difference of x and y\n  function sub(uint256 x, uint256 y, string memory message) internal pure returns (uint256 z) {\n    unchecked {\n      require((z = x - y) <= x, message);\n    }\n  }\n\n  /// @notice Returns x * y, reverts if overflows\n  /// @param x The multiplicand\n  /// @param y The multiplier\n  /// @return z The product of x and y\n  function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {\n    unchecked {\n      require(x == 0 || (z = x * y) / x == y);\n    }\n  }\n\n  /// @notice Returns x / y, reverts if overflows - no specific check, solidity reverts on division by 0\n  /// @param x The numerator\n  /// @param y The denominator\n  /// @return z The product of x and y\n  function div(uint256 x, uint256 y) internal pure returns (uint256 z) {\n    return x / y;\n  }\n}\n"
      },
      "src/core/contracts/dependencies/openzeppelin/upgradeability/BaseUpgradeabilityProxy.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport './Proxy.sol';\nimport '../contracts/Address.sol';\n\n/**\n * @title BaseUpgradeabilityProxy\n * @dev This contract implements a proxy that allows to change the\n * implementation address to which it will delegate.\n * Such a change is called an implementation upgrade.\n */\ncontract BaseUpgradeabilityProxy is Proxy {\n  /**\n   * @dev Emitted when the implementation is upgraded.\n   * @param implementation Address of the new implementation.\n   */\n  event Upgraded(address indexed implementation);\n\n  /**\n   * @dev Storage slot with the address of the current implementation.\n   * This is the keccak-256 hash of \"eip1967.proxy.implementation\" subtracted by 1, and is\n   * validated in the constructor.\n   */\n  bytes32 internal constant IMPLEMENTATION_SLOT =\n    0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;\n\n  /**\n   * @dev Returns the current implementation.\n   * @return impl Address of the current implementation\n   */\n  function _implementation() internal view override returns (address impl) {\n    bytes32 slot = IMPLEMENTATION_SLOT;\n    //solium-disable-next-line\n    assembly {\n      impl := sload(slot)\n    }\n  }\n\n  /**\n   * @dev Upgrades the proxy to a new implementation.\n   * @param newImplementation Address of the new implementation.\n   */\n  function _upgradeTo(address newImplementation) internal {\n    _setImplementation(newImplementation);\n    emit Upgraded(newImplementation);\n  }\n\n  /**\n   * @dev Sets the implementation address of the proxy.\n   * @param newImplementation Address of the new implementation.\n   */\n  function _setImplementation(address newImplementation) internal {\n    require(\n      Address.isContract(newImplementation),\n      'Cannot set a proxy implementation to a non-contract address'\n    );\n\n    bytes32 slot = IMPLEMENTATION_SLOT;\n\n    //solium-disable-next-line\n    assembly {\n      sstore(slot, newImplementation)\n    }\n  }\n}\n"
      },
      "src/core/contracts/dependencies/openzeppelin/upgradeability/InitializableUpgradeabilityProxy.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport './BaseUpgradeabilityProxy.sol';\n\n/**\n * @title InitializableUpgradeabilityProxy\n * @dev Extends BaseUpgradeabilityProxy with an initializer for initializing\n * implementation and init data.\n */\ncontract InitializableUpgradeabilityProxy is BaseUpgradeabilityProxy {\n  /**\n   * @dev Contract initializer.\n   * @param _logic Address of the initial implementation.\n   * @param _data Data to send as msg.data to the implementation to initialize the proxied contract.\n   * It should include the signature and the parameters of the function to be called, as described in\n   * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.\n   * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped.\n   */\n  function initialize(address _logic, bytes memory _data) public payable {\n    require(_implementation() == address(0));\n    assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1));\n    _setImplementation(_logic);\n    if (_data.length > 0) {\n      (bool success, ) = _logic.delegatecall(_data);\n      require(success);\n    }\n  }\n}\n"
      },
      "src/core/contracts/dependencies/openzeppelin/upgradeability/Proxy.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n/**\n * @title Proxy\n * @dev Implements delegation of calls to other contracts, with proper\n * forwarding of return values and bubbling of failures.\n * It defines a fallback function that delegates all calls to the address\n * returned by the abstract _implementation() internal function.\n */\nabstract contract Proxy {\n  /**\n   * @dev Fallback function.\n   * Will run if no other function in the contract matches the call data.\n   * Implemented entirely in `_fallback`.\n   */\n  fallback() external payable {\n    _fallback();\n  }\n\n  /**\n   * @return The Address of the implementation.\n   */\n  function _implementation() internal view virtual returns (address);\n\n  /**\n   * @dev Delegates execution to an implementation contract.\n   * This is a low level function that doesn't return to its internal call site.\n   * It will return to the external caller whatever the implementation returns.\n   * @param implementation Address to delegate.\n   */\n  function _delegate(address implementation) internal {\n    //solium-disable-next-line\n    assembly {\n      // Copy msg.data. We take full control of memory in this inline assembly\n      // block because it will not return to Solidity code. We overwrite the\n      // Solidity scratch pad at memory position 0.\n      calldatacopy(0, 0, calldatasize())\n\n      // Call the implementation.\n      // out and outsize are 0 because we don't know the size yet.\n      let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)\n\n      // Copy the returned data.\n      returndatacopy(0, 0, returndatasize())\n\n      switch result\n      // delegatecall returns 0 on error.\n      case 0 {\n        revert(0, returndatasize())\n      }\n      default {\n        return(0, returndatasize())\n      }\n    }\n  }\n\n  /**\n   * @dev Function that is run as the first thing in the fallback function.\n   * Can be redefined in derived contracts to add functionality.\n   * Redefinitions must call super._willFallback().\n   */\n  function _willFallback() internal virtual {}\n\n  /**\n   * @dev fallback implementation.\n   * Extracted to enable manual triggering.\n   */\n  function _fallback() internal {\n    _willFallback();\n    _delegate(_implementation());\n  }\n}\n"
      },
      "src/core/contracts/flashloan/base/FlashLoanSimpleReceiverBase.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport {IFlashLoanSimpleReceiver} from '../interfaces/IFlashLoanSimpleReceiver.sol';\nimport {IPoolAddressesProvider} from '../../interfaces/IPoolAddressesProvider.sol';\nimport {IPool} from '../../interfaces/IPool.sol';\n\n/**\n * @title FlashLoanSimpleReceiverBase\n * @author Aave\n * @notice Base contract to develop a flashloan-receiver contract.\n */\nabstract contract FlashLoanSimpleReceiverBase is IFlashLoanSimpleReceiver {\n  IPoolAddressesProvider public immutable override ADDRESSES_PROVIDER;\n  IPool public immutable override POOL;\n\n  constructor(IPoolAddressesProvider provider) {\n    ADDRESSES_PROVIDER = provider;\n    POOL = IPool(provider.getPool());\n  }\n}\n"
      },
      "src/core/contracts/flashloan/interfaces/IFlashLoanSimpleReceiver.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {IPoolAddressesProvider} from '../../interfaces/IPoolAddressesProvider.sol';\nimport {IPool} from '../../interfaces/IPool.sol';\n\n/**\n * @title IFlashLoanSimpleReceiver\n * @author Aave\n * @notice Defines the basic interface of a flashloan-receiver contract.\n * @dev Implement this interface to develop a flashloan-compatible flashLoanReceiver contract\n */\ninterface IFlashLoanSimpleReceiver {\n  /**\n   * @notice Executes an operation after receiving the flash-borrowed asset\n   * @dev Ensure that the contract can return the debt + premium, e.g., has\n   *      enough funds to repay and has approved the Pool to pull the total amount\n   * @param asset The address of the flash-borrowed asset\n   * @param amount The amount of the flash-borrowed asset\n   * @param premium The fee of the flash-borrowed asset\n   * @param initiator The address of the flashloan initiator\n   * @param params The byte-encoded params passed when initiating the flashloan\n   * @return True if the execution of the operation succeeds, false otherwise\n   */\n  function executeOperation(\n    address asset,\n    uint256 amount,\n    uint256 premium,\n    address initiator,\n    bytes calldata params\n  ) external returns (bool);\n\n  function ADDRESSES_PROVIDER() external view returns (IPoolAddressesProvider);\n\n  function POOL() external view returns (IPool);\n}\n"
      },
      "src/core/contracts/interfaces/IACLManager.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {IPoolAddressesProvider} from './IPoolAddressesProvider.sol';\n\n/**\n * @title IACLManager\n * @author Aave\n * @notice Defines the basic interface for the ACL Manager\n */\ninterface IACLManager {\n  /**\n   * @notice Returns the contract address of the PoolAddressesProvider\n   * @return The address of the PoolAddressesProvider\n   */\n  function ADDRESSES_PROVIDER() external view returns (IPoolAddressesProvider);\n\n  /**\n   * @notice Returns the identifier of the PoolAdmin role\n   * @return The id of the PoolAdmin role\n   */\n  function POOL_ADMIN_ROLE() external view returns (bytes32);\n\n  /**\n   * @notice Returns the identifier of the EmergencyAdmin role\n   * @return The id of the EmergencyAdmin role\n   */\n  function EMERGENCY_ADMIN_ROLE() external view returns (bytes32);\n\n  /**\n   * @notice Returns the identifier of the RiskAdmin role\n   * @return The id of the RiskAdmin role\n   */\n  function RISK_ADMIN_ROLE() external view returns (bytes32);\n\n  /**\n   * @notice Returns the identifier of the FlashBorrower role\n   * @return The id of the FlashBorrower role\n   */\n  function FLASH_BORROWER_ROLE() external view returns (bytes32);\n\n  /**\n   * @notice Returns the identifier of the Bridge role\n   * @return The id of the Bridge role\n   */\n  function BRIDGE_ROLE() external view returns (bytes32);\n\n  /**\n   * @notice Returns the identifier of the AssetListingAdmin role\n   * @return The id of the AssetListingAdmin role\n   */\n  function ASSET_LISTING_ADMIN_ROLE() external view returns (bytes32);\n\n  /**\n   * @notice Set the role as admin of a specific role.\n   * @dev By default the admin role for all roles is `DEFAULT_ADMIN_ROLE`.\n   * @param role The role to be managed by the admin role\n   * @param adminRole The admin role\n   */\n  function setRoleAdmin(bytes32 role, bytes32 adminRole) external;\n\n  /**\n   * @notice Adds a new admin as PoolAdmin\n   * @param admin The address of the new admin\n   */\n  function addPoolAdmin(address admin) external;\n\n  /**\n   * @notice Removes an admin as PoolAdmin\n   * @param admin The address of the admin to remove\n   */\n  function removePoolAdmin(address admin) external;\n\n  /**\n   * @notice Returns true if the address is PoolAdmin, false otherwise\n   * @param admin The address to check\n   * @return True if the given address is PoolAdmin, false otherwise\n   */\n  function isPoolAdmin(address admin) external view returns (bool);\n\n  /**\n   * @notice Adds a new admin as EmergencyAdmin\n   * @param admin The address of the new admin\n   */\n  function addEmergencyAdmin(address admin) external;\n\n  /**\n   * @notice Removes an admin as EmergencyAdmin\n   * @param admin The address of the admin to remove\n   */\n  function removeEmergencyAdmin(address admin) external;\n\n  /**\n   * @notice Returns true if the address is EmergencyAdmin, false otherwise\n   * @param admin The address to check\n   * @return True if the given address is EmergencyAdmin, false otherwise\n   */\n  function isEmergencyAdmin(address admin) external view returns (bool);\n\n  /**\n   * @notice Adds a new admin as RiskAdmin\n   * @param admin The address of the new admin\n   */\n  function addRiskAdmin(address admin) external;\n\n  /**\n   * @notice Removes an admin as RiskAdmin\n   * @param admin The address of the admin to remove\n   */\n  function removeRiskAdmin(address admin) external;\n\n  /**\n   * @notice Returns true if the address is RiskAdmin, false otherwise\n   * @param admin The address to check\n   * @return True if the given address is RiskAdmin, false otherwise\n   */\n  function isRiskAdmin(address admin) external view returns (bool);\n\n  /**\n   * @notice Adds a new address as FlashBorrower\n   * @param borrower The address of the new FlashBorrower\n   */\n  function addFlashBorrower(address borrower) external;\n\n  /**\n   * @notice Removes an address as FlashBorrower\n   * @param borrower The address of the FlashBorrower to remove\n   */\n  function removeFlashBorrower(address borrower) external;\n\n  /**\n   * @notice Returns true if the address is FlashBorrower, false otherwise\n   * @param borrower The address to check\n   * @return True if the given address is FlashBorrower, false otherwise\n   */\n  function isFlashBorrower(address borrower) external view returns (bool);\n\n  /**\n   * @notice Adds a new address as Bridge\n   * @param bridge The address of the new Bridge\n   */\n  function addBridge(address bridge) external;\n\n  /**\n   * @notice Removes an address as Bridge\n   * @param bridge The address of the bridge to remove\n   */\n  function removeBridge(address bridge) external;\n\n  /**\n   * @notice Returns true if the address is Bridge, false otherwise\n   * @param bridge The address to check\n   * @return True if the given address is Bridge, false otherwise\n   */\n  function isBridge(address bridge) external view returns (bool);\n\n  /**\n   * @notice Adds a new admin as AssetListingAdmin\n   * @param admin The address of the new admin\n   */\n  function addAssetListingAdmin(address admin) external;\n\n  /**\n   * @notice Removes an admin as AssetListingAdmin\n   * @param admin The address of the admin to remove\n   */\n  function removeAssetListingAdmin(address admin) external;\n\n  /**\n   * @notice Returns true if the address is AssetListingAdmin, false otherwise\n   * @param admin The address to check\n   * @return True if the given address is AssetListingAdmin, false otherwise\n   */\n  function isAssetListingAdmin(address admin) external view returns (bool);\n}\n"
      },
      "src/core/contracts/interfaces/IAToken.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {IERC20} from '../dependencies/openzeppelin/contracts/IERC20.sol';\nimport {IScaledBalanceToken} from './IScaledBalanceToken.sol';\nimport {IInitializableAToken} from './IInitializableAToken.sol';\n\n/**\n * @title IAToken\n * @author Aave\n * @notice Defines the basic interface for an AToken.\n */\ninterface IAToken is IERC20, IScaledBalanceToken, IInitializableAToken {\n  /**\n   * @dev Emitted during the transfer action\n   * @param from The user whose tokens are being transferred\n   * @param to The recipient\n   * @param value The scaled amount being transferred\n   * @param index The next liquidity index of the reserve\n   */\n  event BalanceTransfer(address indexed from, address indexed to, uint256 value, uint256 index);\n\n  /**\n   * @notice Mints `amount` aTokens to `user`\n   * @param caller The address performing the mint\n   * @param onBehalfOf The address of the user that will receive the minted aTokens\n   * @param amount The amount of tokens getting minted\n   * @param index The next liquidity index of the reserve\n   * @return `true` if the the previous balance of the user was 0\n   */\n  function mint(\n    address caller,\n    address onBehalfOf,\n    uint256 amount,\n    uint256 index\n  ) external returns (bool);\n\n  /**\n   * @notice Burns aTokens from `user` and sends the equivalent amount of underlying to `receiverOfUnderlying`\n   * @dev In some instances, the mint event could be emitted from a burn transaction\n   * if the amount to burn is less than the interest that the user accrued\n   * @param from The address from which the aTokens will be burned\n   * @param receiverOfUnderlying The address that will receive the underlying\n   * @param amount The amount being burned\n   * @param index The next liquidity index of the reserve\n   */\n  function burn(address from, address receiverOfUnderlying, uint256 amount, uint256 index) external;\n\n  /**\n   * @notice Mints aTokens to the reserve treasury\n   * @param amount The amount of tokens getting minted\n   * @param index The next liquidity index of the reserve\n   */\n  function mintToTreasury(uint256 amount, uint256 index) external;\n\n  /**\n   * @notice Transfers aTokens in the event of a borrow being liquidated, in case the liquidators reclaims the aToken\n   * @param from The address getting liquidated, current owner of the aTokens\n   * @param to The recipient\n   * @param value The amount of tokens getting transferred\n   */\n  function transferOnLiquidation(address from, address to, uint256 value) external;\n\n  /**\n   * @notice Transfers the underlying asset to `target`.\n   * @dev Used by the Pool to transfer assets in borrow(), withdraw() and flashLoan()\n   * @param target The recipient of the underlying\n   * @param amount The amount getting transferred\n   */\n  function transferUnderlyingTo(address target, uint256 amount) external;\n\n  /**\n   * @notice Handles the underlying received by the aToken after the transfer has been completed.\n   * @dev The default implementation is empty as with standard ERC20 tokens, nothing needs to be done after the\n   * transfer is concluded. However in the future there may be aTokens that allow for example to stake the underlying\n   * to receive LM rewards. In that case, `handleRepayment()` would perform the staking of the underlying asset.\n   * @param user The user executing the repayment\n   * @param onBehalfOf The address of the user who will get his debt reduced/removed\n   * @param amount The amount getting repaid\n   */\n  function handleRepayment(address user, address onBehalfOf, uint256 amount) external;\n\n  /**\n   * @notice Allow passing a signed message to approve spending\n   * @dev implements the permit function as for\n   * https://github.com/ethereum/EIPs/blob/8a34d644aacf0f9f8f00815307fd7dd5da07655f/EIPS/eip-2612.md\n   * @param owner The owner of the funds\n   * @param spender The spender\n   * @param value The amount\n   * @param deadline The deadline timestamp, type(uint256).max for max deadline\n   * @param v Signature param\n   * @param s Signature param\n   * @param r Signature param\n   */\n  function permit(\n    address owner,\n    address spender,\n    uint256 value,\n    uint256 deadline,\n    uint8 v,\n    bytes32 r,\n    bytes32 s\n  ) external;\n\n  /**\n   * @notice Returns the address of the underlying asset of this aToken (E.g. WETH for aWETH)\n   * @return The address of the underlying asset\n   */\n  function UNDERLYING_ASSET_ADDRESS() external view returns (address);\n\n  /**\n   * @notice Returns the address of the Aave treasury, receiving the fees on this aToken.\n   * @return Address of the Aave treasury\n   */\n  function RESERVE_TREASURY_ADDRESS() external view returns (address);\n\n  /**\n   * @notice Get the domain separator for the token\n   * @dev Return cached value if chainId matches cache, otherwise recomputes separator\n   * @return The domain separator of the token at current chain\n   */\n  function DOMAIN_SEPARATOR() external view returns (bytes32);\n\n  /**\n   * @notice Returns the nonce for owner.\n   * @param owner The address of the owner\n   * @return The nonce of the owner\n   */\n  function nonces(address owner) external view returns (uint256);\n\n  /**\n   * @notice Rescue and transfer tokens locked in this contract\n   * @param token The address of the token\n   * @param to The address of the recipient\n   * @param amount The amount of token to transfer\n   */\n  function rescueTokens(address token, address to, uint256 amount) external;\n}\n"
      },
      "src/core/contracts/interfaces/IAaveIncentivesController.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n/**\n * @title IAaveIncentivesController\n * @author Aave\n * @notice Defines the basic interface for an Aave Incentives Controller.\n * @dev It only contains one single function, needed as a hook on aToken and debtToken transfers.\n */\ninterface IAaveIncentivesController {\n  /**\n   * @dev Called by the corresponding asset on transfer hook in order to update the rewards distribution.\n   * @dev The units of `totalSupply` and `userBalance` should be the same.\n   * @param user The address of the user whose asset balance has changed\n   * @param totalSupply The total supply of the asset prior to user balance change\n   * @param userBalance The previous user balance prior to balance change\n   */\n  function handleAction(address user, uint256 totalSupply, uint256 userBalance) external;\n}\n"
      },
      "src/core/contracts/interfaces/IAaveOracle.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {IPriceOracleGetter} from './IPriceOracleGetter.sol';\nimport {IPoolAddressesProvider} from './IPoolAddressesProvider.sol';\n\n/**\n * @title IAaveOracle\n * @author Aave\n * @notice Defines the basic interface for the Aave Oracle\n */\ninterface IAaveOracle is IPriceOracleGetter {\n  /**\n   * @dev Emitted after the base currency is set\n   * @param baseCurrency The base currency of used for price quotes\n   * @param baseCurrencyUnit The unit of the base currency\n   */\n  event BaseCurrencySet(address indexed baseCurrency, uint256 baseCurrencyUnit);\n\n  /**\n   * @dev Emitted after the price source of an asset is updated\n   * @param asset The address of the asset\n   * @param source The price source of the asset\n   */\n  event AssetSourceUpdated(address indexed asset, address indexed source);\n\n  /**\n   * @dev Emitted after the address of fallback oracle is updated\n   * @param fallbackOracle The address of the fallback oracle\n   */\n  event FallbackOracleUpdated(address indexed fallbackOracle);\n\n  /**\n   * @notice Returns the PoolAddressesProvider\n   * @return The address of the PoolAddressesProvider contract\n   */\n  function ADDRESSES_PROVIDER() external view returns (IPoolAddressesProvider);\n\n  /**\n   * @notice Sets or replaces price sources of assets\n   * @param assets The addresses of the assets\n   * @param sources The addresses of the price sources\n   */\n  function setAssetSources(address[] calldata assets, address[] calldata sources) external;\n\n  /**\n   * @notice Sets the fallback oracle\n   * @param fallbackOracle The address of the fallback oracle\n   */\n  function setFallbackOracle(address fallbackOracle) external;\n\n  /**\n   * @notice Returns a list of prices from a list of assets addresses\n   * @param assets The list of assets addresses\n   * @return The prices of the given assets\n   */\n  function getAssetsPrices(address[] calldata assets) external view returns (uint256[] memory);\n\n  /**\n   * @notice Returns the address of the source for an asset address\n   * @param asset The address of the asset\n   * @return The address of the source\n   */\n  function getSourceOfAsset(address asset) external view returns (address);\n\n  /**\n   * @notice Returns the address of the fallback oracle\n   * @return The address of the fallback oracle\n   */\n  function getFallbackOracle() external view returns (address);\n}\n"
      },
      "src/core/contracts/interfaces/IDefaultInterestRateStrategy.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {IReserveInterestRateStrategy} from './IReserveInterestRateStrategy.sol';\nimport {IPoolAddressesProvider} from './IPoolAddressesProvider.sol';\n\n/**\n * @title IDefaultInterestRateStrategy\n * @author Aave\n * @notice Defines the basic interface of the DefaultReserveInterestRateStrategy\n */\ninterface IDefaultInterestRateStrategy is IReserveInterestRateStrategy {\n  /**\n   * @notice Returns the usage ratio at which the pool aims to obtain most competitive borrow rates.\n   * @return The optimal usage ratio, expressed in ray.\n   */\n  function OPTIMAL_USAGE_RATIO() external view returns (uint256);\n\n  /**\n   * @notice Returns the optimal stable to total debt ratio of the reserve.\n   * @return The optimal stable to total debt ratio, expressed in ray.\n   */\n  function OPTIMAL_STABLE_TO_TOTAL_DEBT_RATIO() external view returns (uint256);\n\n  /**\n   * @notice Returns the excess usage ratio above the optimal.\n   * @dev It's always equal to 1-optimal usage ratio (added as constant for gas optimizations)\n   * @return The max excess usage ratio, expressed in ray.\n   */\n  function MAX_EXCESS_USAGE_RATIO() external view returns (uint256);\n\n  /**\n   * @notice Returns the excess stable debt ratio above the optimal.\n   * @dev It's always equal to 1-optimal stable to total debt ratio (added as constant for gas optimizations)\n   * @return The max excess stable to total debt ratio, expressed in ray.\n   */\n  function MAX_EXCESS_STABLE_TO_TOTAL_DEBT_RATIO() external view returns (uint256);\n\n  /**\n   * @notice Returns the address of the PoolAddressesProvider\n   * @return The address of the PoolAddressesProvider contract\n   */\n  function ADDRESSES_PROVIDER() external view returns (IPoolAddressesProvider);\n\n  /**\n   * @notice Returns the variable rate slope below optimal usage ratio\n   * @dev It's the variable rate when usage ratio > 0 and <= OPTIMAL_USAGE_RATIO\n   * @return The variable rate slope, expressed in ray\n   */\n  function getVariableRateSlope1() external view returns (uint256);\n\n  /**\n   * @notice Returns the variable rate slope above optimal usage ratio\n   * @dev It's the variable rate when usage ratio > OPTIMAL_USAGE_RATIO\n   * @return The variable rate slope, expressed in ray\n   */\n  function getVariableRateSlope2() external view returns (uint256);\n\n  /**\n   * @notice Returns the stable rate slope below optimal usage ratio\n   * @dev It's the stable rate when usage ratio > 0 and <= OPTIMAL_USAGE_RATIO\n   * @return The stable rate slope, expressed in ray\n   */\n  function getStableRateSlope1() external view returns (uint256);\n\n  /**\n   * @notice Returns the stable rate slope above optimal usage ratio\n   * @dev It's the variable rate when usage ratio > OPTIMAL_USAGE_RATIO\n   * @return The stable rate slope, expressed in ray\n   */\n  function getStableRateSlope2() external view returns (uint256);\n\n  /**\n   * @notice Returns the stable rate excess offset\n   * @dev It's an additional premium applied to the stable when stable debt > OPTIMAL_STABLE_TO_TOTAL_DEBT_RATIO\n   * @return The stable rate excess offset, expressed in ray\n   */\n  function getStableRateExcessOffset() external view returns (uint256);\n\n  /**\n   * @notice Returns the base stable borrow rate\n   * @return The base stable borrow rate, expressed in ray\n   */\n  function getBaseStableBorrowRate() external view returns (uint256);\n\n  /**\n   * @notice Returns the base variable borrow rate\n   * @return The base variable borrow rate, expressed in ray\n   */\n  function getBaseVariableBorrowRate() external view returns (uint256);\n\n  /**\n   * @notice Returns the maximum variable borrow rate\n   * @return The maximum variable borrow rate, expressed in ray\n   */\n  function getMaxVariableBorrowRate() external view returns (uint256);\n}\n"
      },
      "src/core/contracts/interfaces/IERC20WithPermit.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {IERC20} from '../dependencies/openzeppelin/contracts/IERC20.sol';\n\n/**\n * @title IERC20WithPermit\n * @author Aave\n * @notice Interface for the permit function (EIP-2612)\n */\ninterface IERC20WithPermit is IERC20 {\n  /**\n   * @notice Allow passing a signed message to approve spending\n   * @dev implements the permit function as for\n   * https://github.com/ethereum/EIPs/blob/8a34d644aacf0f9f8f00815307fd7dd5da07655f/EIPS/eip-2612.md\n   * @param owner The owner of the funds\n   * @param spender The spender\n   * @param value The amount\n   * @param deadline The deadline timestamp, type(uint256).max for max deadline\n   * @param v Signature param\n   * @param s Signature param\n   * @param r Signature param\n   */\n  function permit(\n    address owner,\n    address spender,\n    uint256 value,\n    uint256 deadline,\n    uint8 v,\n    bytes32 r,\n    bytes32 s\n  ) external;\n}\n"
      },
      "src/core/contracts/interfaces/IInitializableAToken.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {IAaveIncentivesController} from './IAaveIncentivesController.sol';\nimport {IPool} from './IPool.sol';\n\n/**\n * @title IInitializableAToken\n * @author Aave\n * @notice Interface for the initialize function on AToken\n */\ninterface IInitializableAToken {\n  /**\n   * @dev Emitted when an aToken is initialized\n   * @param underlyingAsset The address of the underlying asset\n   * @param pool The address of the associated pool\n   * @param treasury The address of the treasury\n   * @param incentivesController The address of the incentives controller for this aToken\n   * @param aTokenDecimals The decimals of the underlying\n   * @param aTokenName The name of the aToken\n   * @param aTokenSymbol The symbol of the aToken\n   * @param params A set of encoded parameters for additional initialization\n   */\n  event Initialized(\n    address indexed underlyingAsset,\n    address indexed pool,\n    address treasury,\n    address incentivesController,\n    uint8 aTokenDecimals,\n    string aTokenName,\n    string aTokenSymbol,\n    bytes params\n  );\n\n  /**\n   * @notice Initializes the aToken\n   * @param pool The pool contract that is initializing this contract\n   * @param treasury The address of the Aave treasury, receiving the fees on this aToken\n   * @param underlyingAsset The address of the underlying asset of this aToken (E.g. WETH for aWETH)\n   * @param incentivesController The smart contract managing potential incentives distribution\n   * @param aTokenDecimals The decimals of the aToken, same as the underlying asset's\n   * @param aTokenName The name of the aToken\n   * @param aTokenSymbol The symbol of the aToken\n   * @param params A set of encoded parameters for additional initialization\n   */\n  function initialize(\n    IPool pool,\n    address treasury,\n    address underlyingAsset,\n    IAaveIncentivesController incentivesController,\n    uint8 aTokenDecimals,\n    string calldata aTokenName,\n    string calldata aTokenSymbol,\n    bytes calldata params\n  ) external;\n}\n"
      },
      "src/core/contracts/interfaces/IInitializableDebtToken.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {IAaveIncentivesController} from './IAaveIncentivesController.sol';\nimport {IPool} from './IPool.sol';\n\n/**\n * @title IInitializableDebtToken\n * @author Aave\n * @notice Interface for the initialize function common between debt tokens\n */\ninterface IInitializableDebtToken {\n  /**\n   * @dev Emitted when a debt token is initialized\n   * @param underlyingAsset The address of the underlying asset\n   * @param pool The address of the associated pool\n   * @param incentivesController The address of the incentives controller for this aToken\n   * @param debtTokenDecimals The decimals of the debt token\n   * @param debtTokenName The name of the debt token\n   * @param debtTokenSymbol The symbol of the debt token\n   * @param params A set of encoded parameters for additional initialization\n   */\n  event Initialized(\n    address indexed underlyingAsset,\n    address indexed pool,\n    address incentivesController,\n    uint8 debtTokenDecimals,\n    string debtTokenName,\n    string debtTokenSymbol,\n    bytes params\n  );\n\n  /**\n   * @notice Initializes the debt token.\n   * @param pool The pool contract that is initializing this contract\n   * @param underlyingAsset The address of the underlying asset of this aToken (E.g. WETH for aWETH)\n   * @param incentivesController The smart contract managing potential incentives distribution\n   * @param debtTokenDecimals The decimals of the debtToken, same as the underlying asset's\n   * @param debtTokenName The name of the token\n   * @param debtTokenSymbol The symbol of the token\n   * @param params A set of encoded parameters for additional initialization\n   */\n  function initialize(\n    IPool pool,\n    address underlyingAsset,\n    IAaveIncentivesController incentivesController,\n    uint8 debtTokenDecimals,\n    string memory debtTokenName,\n    string memory debtTokenSymbol,\n    bytes calldata params\n  ) external;\n}\n"
      },
      "src/core/contracts/interfaces/IPool.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {IPoolAddressesProvider} from './IPoolAddressesProvider.sol';\nimport {DataTypes} from '../protocol/libraries/types/DataTypes.sol';\n\n/**\n * @title IPool\n * @author Aave\n * @notice Defines the basic interface for an Aave Pool.\n */\ninterface IPool {\n  /**\n   * @dev Emitted on mintUnbacked()\n   * @param reserve The address of the underlying asset of the reserve\n   * @param user The address initiating the supply\n   * @param onBehalfOf The beneficiary of the supplied assets, receiving the aTokens\n   * @param amount The amount of supplied assets\n   * @param referralCode The referral code used\n   */\n  event MintUnbacked(\n    address indexed reserve,\n    address user,\n    address indexed onBehalfOf,\n    uint256 amount,\n    uint16 indexed referralCode\n  );\n\n  /**\n   * @dev Emitted on backUnbacked()\n   * @param reserve The address of the underlying asset of the reserve\n   * @param backer The address paying for the backing\n   * @param amount The amount added as backing\n   * @param fee The amount paid in fees\n   */\n  event BackUnbacked(address indexed reserve, address indexed backer, uint256 amount, uint256 fee);\n\n  /**\n   * @dev Emitted on supply()\n   * @param reserve The address of the underlying asset of the reserve\n   * @param user The address initiating the supply\n   * @param onBehalfOf The beneficiary of the supply, receiving the aTokens\n   * @param amount The amount supplied\n   * @param referralCode The referral code used\n   */\n  event Supply(\n    address indexed reserve,\n    address user,\n    address indexed onBehalfOf,\n    uint256 amount,\n    uint16 indexed referralCode\n  );\n\n  /**\n   * @dev Emitted on withdraw()\n   * @param reserve The address of the underlying asset being withdrawn\n   * @param user The address initiating the withdrawal, owner of aTokens\n   * @param to The address that will receive the underlying\n   * @param amount The amount to be withdrawn\n   */\n  event Withdraw(address indexed reserve, address indexed user, address indexed to, uint256 amount);\n\n  /**\n   * @dev Emitted on borrow() and flashLoan() when debt needs to be opened\n   * @param reserve The address of the underlying asset being borrowed\n   * @param user The address of the user initiating the borrow(), receiving the funds on borrow() or just\n   * initiator of the transaction on flashLoan()\n   * @param onBehalfOf The address that will be getting the debt\n   * @param amount The amount borrowed out\n   * @param interestRateMode The rate mode: 1 for Stable, 2 for Variable\n   * @param borrowRate The numeric rate at which the user has borrowed, expressed in ray\n   * @param referralCode The referral code used\n   */\n  event Borrow(\n    address indexed reserve,\n    address user,\n    address indexed onBehalfOf,\n    uint256 amount,\n    DataTypes.InterestRateMode interestRateMode,\n    uint256 borrowRate,\n    uint16 indexed referralCode\n  );\n\n  /**\n   * @dev Emitted on repay()\n   * @param reserve The address of the underlying asset of the reserve\n   * @param user The beneficiary of the repayment, getting his debt reduced\n   * @param repayer The address of the user initiating the repay(), providing the funds\n   * @param amount The amount repaid\n   * @param useATokens True if the repayment is done using aTokens, `false` if done with underlying asset directly\n   */\n  event Repay(\n    address indexed reserve,\n    address indexed user,\n    address indexed repayer,\n    uint256 amount,\n    bool useATokens\n  );\n\n  /**\n   * @dev Emitted on swapBorrowRateMode()\n   * @param reserve The address of the underlying asset of the reserve\n   * @param user The address of the user swapping his rate mode\n   * @param interestRateMode The current interest rate mode of the position being swapped: 1 for Stable, 2 for Variable\n   */\n  event SwapBorrowRateMode(\n    address indexed reserve,\n    address indexed user,\n    DataTypes.InterestRateMode interestRateMode\n  );\n\n  /**\n   * @dev Emitted on borrow(), repay() and liquidationCall() when using isolated assets\n   * @param asset The address of the underlying asset of the reserve\n   * @param totalDebt The total isolation mode debt for the reserve\n   */\n  event IsolationModeTotalDebtUpdated(address indexed asset, uint256 totalDebt);\n\n  /**\n   * @dev Emitted when the user selects a certain asset category for eMode\n   * @param user The address of the user\n   * @param categoryId The category id\n   */\n  event UserEModeSet(address indexed user, uint8 categoryId);\n\n  /**\n   * @dev Emitted on setUserUseReserveAsCollateral()\n   * @param reserve The address of the underlying asset of the reserve\n   * @param user The address of the user enabling the usage as collateral\n   */\n  event ReserveUsedAsCollateralEnabled(address indexed reserve, address indexed user);\n\n  /**\n   * @dev Emitted on setUserUseReserveAsCollateral()\n   * @param reserve The address of the underlying asset of the reserve\n   * @param user The address of the user enabling the usage as collateral\n   */\n  event ReserveUsedAsCollateralDisabled(address indexed reserve, address indexed user);\n\n  /**\n   * @dev Emitted on rebalanceStableBorrowRate()\n   * @param reserve The address of the underlying asset of the reserve\n   * @param user The address of the user for which the rebalance has been executed\n   */\n  event RebalanceStableBorrowRate(address indexed reserve, address indexed user);\n\n  /**\n   * @dev Emitted on flashLoan()\n   * @param target The address of the flash loan receiver contract\n   * @param initiator The address initiating the flash loan\n   * @param asset The address of the asset being flash borrowed\n   * @param amount The amount flash borrowed\n   * @param interestRateMode The flashloan mode: 0 for regular flashloan, 1 for Stable debt, 2 for Variable debt\n   * @param premium The fee flash borrowed\n   * @param referralCode The referral code used\n   */\n  event FlashLoan(\n    address indexed target,\n    address initiator,\n    address indexed asset,\n    uint256 amount,\n    DataTypes.InterestRateMode interestRateMode,\n    uint256 premium,\n    uint16 indexed referralCode\n  );\n\n  /**\n   * @dev Emitted when a borrower is liquidated.\n   * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation\n   * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation\n   * @param user The address of the borrower getting liquidated\n   * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover\n   * @param liquidatedCollateralAmount The amount of collateral received by the liquidator\n   * @param liquidator The address of the liquidator\n   * @param receiveAToken True if the liquidators wants to receive the collateral aTokens, `false` if he wants\n   * to receive the underlying collateral asset directly\n   */\n  event LiquidationCall(\n    address indexed collateralAsset,\n    address indexed debtAsset,\n    address indexed user,\n    uint256 debtToCover,\n    uint256 liquidatedCollateralAmount,\n    address liquidator,\n    bool receiveAToken\n  );\n\n  /**\n   * @dev Emitted when the state of a reserve is updated.\n   * @param reserve The address of the underlying asset of the reserve\n   * @param liquidityRate The next liquidity rate\n   * @param stableBorrowRate The next stable borrow rate\n   * @param variableBorrowRate The next variable borrow rate\n   * @param liquidityIndex The next liquidity index\n   * @param variableBorrowIndex The next variable borrow index\n   */\n  event ReserveDataUpdated(\n    address indexed reserve,\n    uint256 liquidityRate,\n    uint256 stableBorrowRate,\n    uint256 variableBorrowRate,\n    uint256 liquidityIndex,\n    uint256 variableBorrowIndex\n  );\n\n  /**\n   * @dev Emitted when the protocol treasury receives minted aTokens from the accrued interest.\n   * @param reserve The address of the reserve\n   * @param amountMinted The amount minted to the treasury\n   */\n  event MintedToTreasury(address indexed reserve, uint256 amountMinted);\n\n  /**\n   * @notice Mints an `amount` of aTokens to the `onBehalfOf`\n   * @param asset The address of the underlying asset to mint\n   * @param amount The amount to mint\n   * @param onBehalfOf The address that will receive the aTokens\n   * @param referralCode Code used to register the integrator originating the operation, for potential rewards.\n   *   0 if the action is executed directly by the user, without any middle-man\n   */\n  function mintUnbacked(\n    address asset,\n    uint256 amount,\n    address onBehalfOf,\n    uint16 referralCode\n  ) external;\n\n  /**\n   * @notice Back the current unbacked underlying with `amount` and pay `fee`.\n   * @param asset The address of the underlying asset to back\n   * @param amount The amount to back\n   * @param fee The amount paid in fees\n   * @return The backed amount\n   */\n  function backUnbacked(address asset, uint256 amount, uint256 fee) external returns (uint256);\n\n  /**\n   * @notice Supplies an `amount` of underlying asset into the reserve, receiving in return overlying aTokens.\n   * - E.g. User supplies 100 USDC and gets in return 100 aUSDC\n   * @param asset The address of the underlying asset to supply\n   * @param amount The amount to be supplied\n   * @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user\n   *   wants to receive them on his own wallet, or a different address if the beneficiary of aTokens\n   *   is a different wallet\n   * @param referralCode Code used to register the integrator originating the operation, for potential rewards.\n   *   0 if the action is executed directly by the user, without any middle-man\n   */\n  function supply(address asset, uint256 amount, address onBehalfOf, uint16 referralCode) external;\n\n  /**\n   * @notice Supply with transfer approval of asset to be supplied done via permit function\n   * see: https://eips.ethereum.org/EIPS/eip-2612 and https://eips.ethereum.org/EIPS/eip-713\n   * @param asset The address of the underlying asset to supply\n   * @param amount The amount to be supplied\n   * @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user\n   *   wants to receive them on his own wallet, or a different address if the beneficiary of aTokens\n   *   is a different wallet\n   * @param deadline The deadline timestamp that the permit is valid\n   * @param referralCode Code used to register the integrator originating the operation, for potential rewards.\n   *   0 if the action is executed directly by the user, without any middle-man\n   * @param permitV The V parameter of ERC712 permit sig\n   * @param permitR The R parameter of ERC712 permit sig\n   * @param permitS The S parameter of ERC712 permit sig\n   */\n  function supplyWithPermit(\n    address asset,\n    uint256 amount,\n    address onBehalfOf,\n    uint16 referralCode,\n    uint256 deadline,\n    uint8 permitV,\n    bytes32 permitR,\n    bytes32 permitS\n  ) external;\n\n  /**\n   * @notice Withdraws an `amount` of underlying asset from the reserve, burning the equivalent aTokens owned\n   * E.g. User has 100 aUSDC, calls withdraw() and receives 100 USDC, burning the 100 aUSDC\n   * @param asset The address of the underlying asset to withdraw\n   * @param amount The underlying amount to be withdrawn\n   *   - Send the value type(uint256).max in order to withdraw the whole aToken balance\n   * @param to The address that will receive the underlying, same as msg.sender if the user\n   *   wants to receive it on his own wallet, or a different address if the beneficiary is a\n   *   different wallet\n   * @return The final amount withdrawn\n   */\n  function withdraw(address asset, uint256 amount, address to) external returns (uint256);\n\n  /**\n   * @notice Allows users to borrow a specific `amount` of the reserve underlying asset, provided that the borrower\n   * already supplied enough collateral, or he was given enough allowance by a credit delegator on the\n   * corresponding debt token (StableDebtToken or VariableDebtToken)\n   * - E.g. User borrows 100 USDC passing as `onBehalfOf` his own address, receiving the 100 USDC in his wallet\n   *   and 100 stable/variable debt tokens, depending on the `interestRateMode`\n   * @param asset The address of the underlying asset to borrow\n   * @param amount The amount to be borrowed\n   * @param interestRateMode The interest rate mode at which the user wants to borrow: 1 for Stable, 2 for Variable\n   * @param referralCode The code used to register the integrator originating the operation, for potential rewards.\n   *   0 if the action is executed directly by the user, without any middle-man\n   * @param onBehalfOf The address of the user who will receive the debt. Should be the address of the borrower itself\n   * calling the function if he wants to borrow against his own collateral, or the address of the credit delegator\n   * if he has been given credit delegation allowance\n   */\n  function borrow(\n    address asset,\n    uint256 amount,\n    uint256 interestRateMode,\n    uint16 referralCode,\n    address onBehalfOf\n  ) external;\n\n  /**\n   * @notice Repays a borrowed `amount` on a specific reserve, burning the equivalent debt tokens owned\n   * - E.g. User repays 100 USDC, burning 100 variable/stable debt tokens of the `onBehalfOf` address\n   * @param asset The address of the borrowed underlying asset previously borrowed\n   * @param amount The amount to repay\n   * - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode`\n   * @param interestRateMode The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable\n   * @param onBehalfOf The address of the user who will get his debt reduced/removed. Should be the address of the\n   * user calling the function if he wants to reduce/remove his own debt, or the address of any other\n   * other borrower whose debt should be removed\n   * @return The final amount repaid\n   */\n  function repay(\n    address asset,\n    uint256 amount,\n    uint256 interestRateMode,\n    address onBehalfOf\n  ) external returns (uint256);\n\n  /**\n   * @notice Repay with transfer approval of asset to be repaid done via permit function\n   * see: https://eips.ethereum.org/EIPS/eip-2612 and https://eips.ethereum.org/EIPS/eip-713\n   * @param asset The address of the borrowed underlying asset previously borrowed\n   * @param amount The amount to repay\n   * - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode`\n   * @param interestRateMode The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable\n   * @param onBehalfOf Address of the user who will get his debt reduced/removed. Should be the address of the\n   * user calling the function if he wants to reduce/remove his own debt, or the address of any other\n   * other borrower whose debt should be removed\n   * @param deadline The deadline timestamp that the permit is valid\n   * @param permitV The V parameter of ERC712 permit sig\n   * @param permitR The R parameter of ERC712 permit sig\n   * @param permitS The S parameter of ERC712 permit sig\n   * @return The final amount repaid\n   */\n  function repayWithPermit(\n    address asset,\n    uint256 amount,\n    uint256 interestRateMode,\n    address onBehalfOf,\n    uint256 deadline,\n    uint8 permitV,\n    bytes32 permitR,\n    bytes32 permitS\n  ) external returns (uint256);\n\n  /**\n   * @notice Repays a borrowed `amount` on a specific reserve using the reserve aTokens, burning the\n   * equivalent debt tokens\n   * - E.g. User repays 100 USDC using 100 aUSDC, burning 100 variable/stable debt tokens\n   * @dev  Passing uint256.max as amount will clean up any residual aToken dust balance, if the user aToken\n   * balance is not enough to cover the whole debt\n   * @param asset The address of the borrowed underlying asset previously borrowed\n   * @param amount The amount to repay\n   * - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode`\n   * @param interestRateMode The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable\n   * @return The final amount repaid\n   */\n  function repayWithATokens(\n    address asset,\n    uint256 amount,\n    uint256 interestRateMode\n  ) external returns (uint256);\n\n  /**\n   * @notice Allows a borrower to swap his debt between stable and variable mode, or vice versa\n   * @param asset The address of the underlying asset borrowed\n   * @param interestRateMode The current interest rate mode of the position being swapped: 1 for Stable, 2 for Variable\n   */\n  function swapBorrowRateMode(address asset, uint256 interestRateMode) external;\n\n  /**\n   * @notice Rebalances the stable interest rate of a user to the current stable rate defined on the reserve.\n   * - Users can be rebalanced if the following conditions are satisfied:\n   *     1. Usage ratio is above 95%\n   *     2. the current supply APY is below REBALANCE_UP_THRESHOLD * maxVariableBorrowRate, which means that too\n   *        much has been borrowed at a stable rate and suppliers are not earning enough\n   * @param asset The address of the underlying asset borrowed\n   * @param user The address of the user to be rebalanced\n   */\n  function rebalanceStableBorrowRate(address asset, address user) external;\n\n  /**\n   * @notice Allows suppliers to enable/disable a specific supplied asset as collateral\n   * @param asset The address of the underlying asset supplied\n   * @param useAsCollateral True if the user wants to use the supply as collateral, false otherwise\n   */\n  function setUserUseReserveAsCollateral(address asset, bool useAsCollateral) external;\n\n  /**\n   * @notice Function to liquidate a non-healthy position collateral-wise, with Health Factor below 1\n   * - The caller (liquidator) covers `debtToCover` amount of debt of the user getting liquidated, and receives\n   *   a proportionally amount of the `collateralAsset` plus a bonus to cover market risk\n   * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation\n   * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation\n   * @param user The address of the borrower getting liquidated\n   * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover\n   * @param receiveAToken True if the liquidators wants to receive the collateral aTokens, `false` if he wants\n   * to receive the underlying collateral asset directly\n   */\n  function liquidationCall(\n    address collateralAsset,\n    address debtAsset,\n    address user,\n    uint256 debtToCover,\n    bool receiveAToken\n  ) external;\n\n  /**\n   * @notice Allows smartcontracts to access the liquidity of the pool within one transaction,\n   * as long as the amount taken plus a fee is returned.\n   * @dev IMPORTANT There are security concerns for developers of flashloan receiver contracts that must be kept\n   * into consideration. For further details please visit https://docs.aave.com/developers/\n   * @param receiverAddress The address of the contract receiving the funds, implementing IFlashLoanReceiver interface\n   * @param assets The addresses of the assets being flash-borrowed\n   * @param amounts The amounts of the assets being flash-borrowed\n   * @param interestRateModes Types of the debt to open if the flash loan is not returned:\n   *   0 -> Don't open any debt, just revert if funds can't be transferred from the receiver\n   *   1 -> Open debt at stable rate for the value of the amount flash-borrowed to the `onBehalfOf` address\n   *   2 -> Open debt at variable rate for the value of the amount flash-borrowed to the `onBehalfOf` address\n   * @param onBehalfOf The address  that will receive the debt in the case of using on `modes` 1 or 2\n   * @param params Variadic packed params to pass to the receiver as extra information\n   * @param referralCode The code used to register the integrator originating the operation, for potential rewards.\n   *   0 if the action is executed directly by the user, without any middle-man\n   */\n  function flashLoan(\n    address receiverAddress,\n    address[] calldata assets,\n    uint256[] calldata amounts,\n    uint256[] calldata interestRateModes,\n    address onBehalfOf,\n    bytes calldata params,\n    uint16 referralCode\n  ) external;\n\n  /**\n   * @notice Allows smartcontracts to access the liquidity of the pool within one transaction,\n   * as long as the amount taken plus a fee is returned.\n   * @dev IMPORTANT There are security concerns for developers of flashloan receiver contracts that must be kept\n   * into consideration. For further details please visit https://docs.aave.com/developers/\n   * @param receiverAddress The address of the contract receiving the funds, implementing IFlashLoanSimpleReceiver interface\n   * @param asset The address of the asset being flash-borrowed\n   * @param amount The amount of the asset being flash-borrowed\n   * @param params Variadic packed params to pass to the receiver as extra information\n   * @param referralCode The code used to register the integrator originating the operation, for potential rewards.\n   *   0 if the action is executed directly by the user, without any middle-man\n   */\n  function flashLoanSimple(\n    address receiverAddress,\n    address asset,\n    uint256 amount,\n    bytes calldata params,\n    uint16 referralCode\n  ) external;\n\n  /**\n   * @notice Returns the user account data across all the reserves\n   * @param user The address of the user\n   * @return totalCollateralBase The total collateral of the user in the base currency used by the price feed\n   * @return totalDebtBase The total debt of the user in the base currency used by the price feed\n   * @return availableBorrowsBase The borrowing power left of the user in the base currency used by the price feed\n   * @return currentLiquidationThreshold The liquidation threshold of the user\n   * @return ltv The loan to value of The user\n   * @return healthFactor The current health factor of the user\n   */\n  function getUserAccountData(\n    address user\n  )\n    external\n    view\n    returns (\n      uint256 totalCollateralBase,\n      uint256 totalDebtBase,\n      uint256 availableBorrowsBase,\n      uint256 currentLiquidationThreshold,\n      uint256 ltv,\n      uint256 healthFactor\n    );\n\n  /**\n   * @notice Initializes a reserve, activating it, assigning an aToken and debt tokens and an\n   * interest rate strategy\n   * @dev Only callable by the PoolConfigurator contract\n   * @param asset The address of the underlying asset of the reserve\n   * @param aTokenAddress The address of the aToken that will be assigned to the reserve\n   * @param stableDebtAddress The address of the StableDebtToken that will be assigned to the reserve\n   * @param variableDebtAddress The address of the VariableDebtToken that will be assigned to the reserve\n   * @param interestRateStrategyAddress The address of the interest rate strategy contract\n   */\n  function initReserve(\n    address asset,\n    address aTokenAddress,\n    address stableDebtAddress,\n    address variableDebtAddress,\n    address interestRateStrategyAddress\n  ) external;\n\n  /**\n   * @notice Drop a reserve\n   * @dev Only callable by the PoolConfigurator contract\n   * @param asset The address of the underlying asset of the reserve\n   */\n  function dropReserve(address asset) external;\n\n  /**\n   * @notice Updates the address of the interest rate strategy contract\n   * @dev Only callable by the PoolConfigurator contract\n   * @param asset The address of the underlying asset of the reserve\n   * @param rateStrategyAddress The address of the interest rate strategy contract\n   */\n  function setReserveInterestRateStrategyAddress(\n    address asset,\n    address rateStrategyAddress\n  ) external;\n\n  /**\n   * @notice Sets the configuration bitmap of the reserve as a whole\n   * @dev Only callable by the PoolConfigurator contract\n   * @param asset The address of the underlying asset of the reserve\n   * @param configuration The new configuration bitmap\n   */\n  function setConfiguration(\n    address asset,\n    DataTypes.ReserveConfigurationMap calldata configuration\n  ) external;\n\n  /**\n   * @notice Returns the configuration of the reserve\n   * @param asset The address of the underlying asset of the reserve\n   * @return The configuration of the reserve\n   */\n  function getConfiguration(\n    address asset\n  ) external view returns (DataTypes.ReserveConfigurationMap memory);\n\n  /**\n   * @notice Returns the configuration of the user across all the reserves\n   * @param user The user address\n   * @return The configuration of the user\n   */\n  function getUserConfiguration(\n    address user\n  ) external view returns (DataTypes.UserConfigurationMap memory);\n\n  /**\n   * @notice Returns the normalized income of the reserve\n   * @param asset The address of the underlying asset of the reserve\n   * @return The reserve's normalized income\n   */\n  function getReserveNormalizedIncome(address asset) external view returns (uint256);\n\n  /**\n   * @notice Returns the normalized variable debt per unit of asset\n   * @dev WARNING: This function is intended to be used primarily by the protocol itself to get a\n   * \"dynamic\" variable index based on time, current stored index and virtual rate at the current\n   * moment (approx. a borrower would get if opening a position). This means that is always used in\n   * combination with variable debt supply/balances.\n   * If using this function externally, consider that is possible to have an increasing normalized\n   * variable debt that is not equivalent to how the variable debt index would be updated in storage\n   * (e.g. only updates with non-zero variable debt supply)\n   * @param asset The address of the underlying asset of the reserve\n   * @return The reserve normalized variable debt\n   */\n  function getReserveNormalizedVariableDebt(address asset) external view returns (uint256);\n\n  /**\n   * @notice Returns the state and configuration of the reserve\n   * @param asset The address of the underlying asset of the reserve\n   * @return The state and configuration data of the reserve\n   */\n  function getReserveData(address asset) external view returns (DataTypes.ReserveData memory);\n\n  /**\n   * @notice Validates and finalizes an aToken transfer\n   * @dev Only callable by the overlying aToken of the `asset`\n   * @param asset The address of the underlying asset of the aToken\n   * @param from The user from which the aTokens are transferred\n   * @param to The user receiving the aTokens\n   * @param amount The amount being transferred/withdrawn\n   * @param balanceFromBefore The aToken balance of the `from` user before the transfer\n   * @param balanceToBefore The aToken balance of the `to` user before the transfer\n   */\n  function finalizeTransfer(\n    address asset,\n    address from,\n    address to,\n    uint256 amount,\n    uint256 balanceFromBefore,\n    uint256 balanceToBefore\n  ) external;\n\n  /**\n   * @notice Returns the list of the underlying assets of all the initialized reserves\n   * @dev It does not include dropped reserves\n   * @return The addresses of the underlying assets of the initialized reserves\n   */\n  function getReservesList() external view returns (address[] memory);\n\n  /**\n   * @notice Returns the address of the underlying asset of a reserve by the reserve id as stored in the DataTypes.ReserveData struct\n   * @param id The id of the reserve as stored in the DataTypes.ReserveData struct\n   * @return The address of the reserve associated with id\n   */\n  function getReserveAddressById(uint16 id) external view returns (address);\n\n  /**\n   * @notice Returns the PoolAddressesProvider connected to this contract\n   * @return The address of the PoolAddressesProvider\n   */\n  function ADDRESSES_PROVIDER() external view returns (IPoolAddressesProvider);\n\n  /**\n   * @notice Updates the protocol fee on the bridging\n   * @param bridgeProtocolFee The part of the premium sent to the protocol treasury\n   */\n  function updateBridgeProtocolFee(uint256 bridgeProtocolFee) external;\n\n  /**\n   * @notice Updates flash loan premiums. Flash loan premium consists of two parts:\n   * - A part is sent to aToken holders as extra, one time accumulated interest\n   * - A part is collected by the protocol treasury\n   * @dev The total premium is calculated on the total borrowed amount\n   * @dev The premium to protocol is calculated on the total premium, being a percentage of `flashLoanPremiumTotal`\n   * @dev Only callable by the PoolConfigurator contract\n   * @param flashLoanPremiumTotal The total premium, expressed in bps\n   * @param flashLoanPremiumToProtocol The part of the premium sent to the protocol treasury, expressed in bps\n   */\n  function updateFlashloanPremiums(\n    uint128 flashLoanPremiumTotal,\n    uint128 flashLoanPremiumToProtocol\n  ) external;\n\n  /**\n   * @notice Configures a new category for the eMode.\n   * @dev In eMode, the protocol allows very high borrowing power to borrow assets of the same category.\n   * The category 0 is reserved as it's the default for volatile assets\n   * @param id The id of the category\n   * @param config The configuration of the category\n   */\n  function configureEModeCategory(uint8 id, DataTypes.EModeCategory memory config) external;\n\n  /**\n   * @notice Returns the data of an eMode category\n   * @param id The id of the category\n   * @return The configuration data of the category\n   */\n  function getEModeCategoryData(uint8 id) external view returns (DataTypes.EModeCategory memory);\n\n  /**\n   * @notice Allows a user to use the protocol in eMode\n   * @param categoryId The id of the category\n   */\n  function setUserEMode(uint8 categoryId) external;\n\n  /**\n   * @notice Returns the eMode the user is using\n   * @param user The address of the user\n   * @return The eMode id\n   */\n  function getUserEMode(address user) external view returns (uint256);\n\n  /**\n   * @notice Resets the isolation mode total debt of the given asset to zero\n   * @dev It requires the given asset has zero debt ceiling\n   * @param asset The address of the underlying asset to reset the isolationModeTotalDebt\n   */\n  function resetIsolationModeTotalDebt(address asset) external;\n\n  /**\n   * @notice Returns the percentage of available liquidity that can be borrowed at once at stable rate\n   * @return The percentage of available liquidity to borrow, expressed in bps\n   */\n  function MAX_STABLE_RATE_BORROW_SIZE_PERCENT() external view returns (uint256);\n\n  /**\n   * @notice Returns the total fee on flash loans\n   * @return The total fee on flashloans\n   */\n  function FLASHLOAN_PREMIUM_TOTAL() external view returns (uint128);\n\n  /**\n   * @notice Returns the part of the bridge fees sent to protocol\n   * @return The bridge fee sent to the protocol treasury\n   */\n  function BRIDGE_PROTOCOL_FEE() external view returns (uint256);\n\n  /**\n   * @notice Returns the part of the flashloan fees sent to protocol\n   * @return The flashloan fee sent to the protocol treasury\n   */\n  function FLASHLOAN_PREMIUM_TO_PROTOCOL() external view returns (uint128);\n\n  /**\n   * @notice Returns the maximum number of reserves supported to be listed in this Pool\n   * @return The maximum number of reserves supported\n   */\n  function MAX_NUMBER_RESERVES() external view returns (uint16);\n\n  /**\n   * @notice Mints the assets accrued through the reserve factor to the treasury in the form of aTokens\n   * @param assets The list of reserves for which the minting needs to be executed\n   */\n  function mintToTreasury(address[] calldata assets) external;\n\n  /**\n   * @notice Rescue and transfer tokens locked in this contract\n   * @param token The address of the token\n   * @param to The address of the recipient\n   * @param amount The amount of token to transfer\n   */\n  function rescueTokens(address token, address to, uint256 amount) external;\n\n  /**\n   * @notice Supplies an `amount` of underlying asset into the reserve, receiving in return overlying aTokens.\n   * - E.g. User supplies 100 USDC and gets in return 100 aUSDC\n   * @dev Deprecated: Use the `supply` function instead\n   * @param asset The address of the underlying asset to supply\n   * @param amount The amount to be supplied\n   * @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user\n   *   wants to receive them on his own wallet, or a different address if the beneficiary of aTokens\n   *   is a different wallet\n   * @param referralCode Code used to register the integrator originating the operation, for potential rewards.\n   *   0 if the action is executed directly by the user, without any middle-man\n   */\n  function deposit(address asset, uint256 amount, address onBehalfOf, uint16 referralCode) external;\n}\n"
      },
      "src/core/contracts/interfaces/IPoolAddressesProvider.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n/**\n * @title IPoolAddressesProvider\n * @author Aave\n * @notice Defines the basic interface for a Pool Addresses Provider.\n */\ninterface IPoolAddressesProvider {\n  /**\n   * @dev Emitted when the market identifier is updated.\n   * @param oldMarketId The old id of the market\n   * @param newMarketId The new id of the market\n   */\n  event MarketIdSet(string indexed oldMarketId, string indexed newMarketId);\n\n  /**\n   * @dev Emitted when the pool is updated.\n   * @param oldAddress The old address of the Pool\n   * @param newAddress The new address of the Pool\n   */\n  event PoolUpdated(address indexed oldAddress, address indexed newAddress);\n\n  /**\n   * @dev Emitted when the pool configurator is updated.\n   * @param oldAddress The old address of the PoolConfigurator\n   * @param newAddress The new address of the PoolConfigurator\n   */\n  event PoolConfiguratorUpdated(address indexed oldAddress, address indexed newAddress);\n\n  /**\n   * @dev Emitted when the price oracle is updated.\n   * @param oldAddress The old address of the PriceOracle\n   * @param newAddress The new address of the PriceOracle\n   */\n  event PriceOracleUpdated(address indexed oldAddress, address indexed newAddress);\n\n  /**\n   * @dev Emitted when the ACL manager is updated.\n   * @param oldAddress The old address of the ACLManager\n   * @param newAddress The new address of the ACLManager\n   */\n  event ACLManagerUpdated(address indexed oldAddress, address indexed newAddress);\n\n  /**\n   * @dev Emitted when the ACL admin is updated.\n   * @param oldAddress The old address of the ACLAdmin\n   * @param newAddress The new address of the ACLAdmin\n   */\n  event ACLAdminUpdated(address indexed oldAddress, address indexed newAddress);\n\n  /**\n   * @dev Emitted when the price oracle sentinel is updated.\n   * @param oldAddress The old address of the PriceOracleSentinel\n   * @param newAddress The new address of the PriceOracleSentinel\n   */\n  event PriceOracleSentinelUpdated(address indexed oldAddress, address indexed newAddress);\n\n  /**\n   * @dev Emitted when the pool data provider is updated.\n   * @param oldAddress The old address of the PoolDataProvider\n   * @param newAddress The new address of the PoolDataProvider\n   */\n  event PoolDataProviderUpdated(address indexed oldAddress, address indexed newAddress);\n\n  /**\n   * @dev Emitted when a new proxy is created.\n   * @param id The identifier of the proxy\n   * @param proxyAddress The address of the created proxy contract\n   * @param implementationAddress The address of the implementation contract\n   */\n  event ProxyCreated(\n    bytes32 indexed id,\n    address indexed proxyAddress,\n    address indexed implementationAddress\n  );\n\n  /**\n   * @dev Emitted when a new non-proxied contract address is registered.\n   * @param id The identifier of the contract\n   * @param oldAddress The address of the old contract\n   * @param newAddress The address of the new contract\n   */\n  event AddressSet(bytes32 indexed id, address indexed oldAddress, address indexed newAddress);\n\n  /**\n   * @dev Emitted when the implementation of the proxy registered with id is updated\n   * @param id The identifier of the contract\n   * @param proxyAddress The address of the proxy contract\n   * @param oldImplementationAddress The address of the old implementation contract\n   * @param newImplementationAddress The address of the new implementation contract\n   */\n  event AddressSetAsProxy(\n    bytes32 indexed id,\n    address indexed proxyAddress,\n    address oldImplementationAddress,\n    address indexed newImplementationAddress\n  );\n\n  /**\n   * @notice Returns the id of the Aave market to which this contract points to.\n   * @return The market id\n   */\n  function getMarketId() external view returns (string memory);\n\n  /**\n   * @notice Associates an id with a specific PoolAddressesProvider.\n   * @dev This can be used to create an onchain registry of PoolAddressesProviders to\n   * identify and validate multiple Aave markets.\n   * @param newMarketId The market id\n   */\n  function setMarketId(string calldata newMarketId) external;\n\n  /**\n   * @notice Returns an address by its identifier.\n   * @dev The returned address might be an EOA or a contract, potentially proxied\n   * @dev It returns ZERO if there is no registered address with the given id\n   * @param id The id\n   * @return The address of the registered for the specified id\n   */\n  function getAddress(bytes32 id) external view returns (address);\n\n  /**\n   * @notice General function to update the implementation of a proxy registered with\n   * certain `id`. If there is no proxy registered, it will instantiate one and\n   * set as implementation the `newImplementationAddress`.\n   * @dev IMPORTANT Use this function carefully, only for ids that don't have an explicit\n   * setter function, in order to avoid unexpected consequences\n   * @param id The id\n   * @param newImplementationAddress The address of the new implementation\n   */\n  function setAddressAsProxy(bytes32 id, address newImplementationAddress) external;\n\n  /**\n   * @notice Sets an address for an id replacing the address saved in the addresses map.\n   * @dev IMPORTANT Use this function carefully, as it will do a hard replacement\n   * @param id The id\n   * @param newAddress The address to set\n   */\n  function setAddress(bytes32 id, address newAddress) external;\n\n  /**\n   * @notice Returns the address of the Pool proxy.\n   * @return The Pool proxy address\n   */\n  function getPool() external view returns (address);\n\n  /**\n   * @notice Updates the implementation of the Pool, or creates a proxy\n   * setting the new `pool` implementation when the function is called for the first time.\n   * @param newPoolImpl The new Pool implementation\n   */\n  function setPoolImpl(address newPoolImpl) external;\n\n  /**\n   * @notice Returns the address of the PoolConfigurator proxy.\n   * @return The PoolConfigurator proxy address\n   */\n  function getPoolConfigurator() external view returns (address);\n\n  /**\n   * @notice Updates the implementation of the PoolConfigurator, or creates a proxy\n   * setting the new `PoolConfigurator` implementation when the function is called for the first time.\n   * @param newPoolConfiguratorImpl The new PoolConfigurator implementation\n   */\n  function setPoolConfiguratorImpl(address newPoolConfiguratorImpl) external;\n\n  /**\n   * @notice Returns the address of the price oracle.\n   * @return The address of the PriceOracle\n   */\n  function getPriceOracle() external view returns (address);\n\n  /**\n   * @notice Updates the address of the price oracle.\n   * @param newPriceOracle The address of the new PriceOracle\n   */\n  function setPriceOracle(address newPriceOracle) external;\n\n  /**\n   * @notice Returns the address of the ACL manager.\n   * @return The address of the ACLManager\n   */\n  function getACLManager() external view returns (address);\n\n  /**\n   * @notice Updates the address of the ACL manager.\n   * @param newAclManager The address of the new ACLManager\n   */\n  function setACLManager(address newAclManager) external;\n\n  /**\n   * @notice Returns the address of the ACL admin.\n   * @return The address of the ACL admin\n   */\n  function getACLAdmin() external view returns (address);\n\n  /**\n   * @notice Updates the address of the ACL admin.\n   * @param newAclAdmin The address of the new ACL admin\n   */\n  function setACLAdmin(address newAclAdmin) external;\n\n  /**\n   * @notice Returns the address of the price oracle sentinel.\n   * @return The address of the PriceOracleSentinel\n   */\n  function getPriceOracleSentinel() external view returns (address);\n\n  /**\n   * @notice Updates the address of the price oracle sentinel.\n   * @param newPriceOracleSentinel The address of the new PriceOracleSentinel\n   */\n  function setPriceOracleSentinel(address newPriceOracleSentinel) external;\n\n  /**\n   * @notice Returns the address of the data provider.\n   * @return The address of the DataProvider\n   */\n  function getPoolDataProvider() external view returns (address);\n\n  /**\n   * @notice Updates the address of the data provider.\n   * @param newDataProvider The address of the new DataProvider\n   */\n  function setPoolDataProvider(address newDataProvider) external;\n}\n"
      },
      "src/core/contracts/interfaces/IPoolAddressesProviderRegistry.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n/**\n * @title IPoolAddressesProviderRegistry\n * @author Aave\n * @notice Defines the basic interface for an Aave Pool Addresses Provider Registry.\n */\ninterface IPoolAddressesProviderRegistry {\n  /**\n   * @dev Emitted when a new AddressesProvider is registered.\n   * @param addressesProvider The address of the registered PoolAddressesProvider\n   * @param id The id of the registered PoolAddressesProvider\n   */\n  event AddressesProviderRegistered(address indexed addressesProvider, uint256 indexed id);\n\n  /**\n   * @dev Emitted when an AddressesProvider is unregistered.\n   * @param addressesProvider The address of the unregistered PoolAddressesProvider\n   * @param id The id of the unregistered PoolAddressesProvider\n   */\n  event AddressesProviderUnregistered(address indexed addressesProvider, uint256 indexed id);\n\n  /**\n   * @notice Returns the list of registered addresses providers\n   * @return The list of addresses providers\n   */\n  function getAddressesProvidersList() external view returns (address[] memory);\n\n  /**\n   * @notice Returns the id of a registered PoolAddressesProvider\n   * @param addressesProvider The address of the PoolAddressesProvider\n   * @return The id of the PoolAddressesProvider or 0 if is not registered\n   */\n  function getAddressesProviderIdByAddress(\n    address addressesProvider\n  ) external view returns (uint256);\n\n  /**\n   * @notice Returns the address of a registered PoolAddressesProvider\n   * @param id The id of the market\n   * @return The address of the PoolAddressesProvider with the given id or zero address if it is not registered\n   */\n  function getAddressesProviderAddressById(uint256 id) external view returns (address);\n\n  /**\n   * @notice Registers an addresses provider\n   * @dev The PoolAddressesProvider must not already be registered in the registry\n   * @dev The id must not be used by an already registered PoolAddressesProvider\n   * @param provider The address of the new PoolAddressesProvider\n   * @param id The id for the new PoolAddressesProvider, referring to the market it belongs to\n   */\n  function registerAddressesProvider(address provider, uint256 id) external;\n\n  /**\n   * @notice Removes an addresses provider from the list of registered addresses providers\n   * @param provider The PoolAddressesProvider address\n   */\n  function unregisterAddressesProvider(address provider) external;\n}\n"
      },
      "src/core/contracts/interfaces/IPoolConfigurator.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {ConfiguratorInputTypes} from '../protocol/libraries/types/ConfiguratorInputTypes.sol';\n\n/**\n * @title IPoolConfigurator\n * @author Aave\n * @notice Defines the basic interface for a Pool configurator.\n */\ninterface IPoolConfigurator {\n  /**\n   * @dev Emitted when a reserve is initialized.\n   * @param asset The address of the underlying asset of the reserve\n   * @param aToken The address of the associated aToken contract\n   * @param stableDebtToken The address of the associated stable rate debt token\n   * @param variableDebtToken The address of the associated variable rate debt token\n   * @param interestRateStrategyAddress The address of the interest rate strategy for the reserve\n   */\n  event ReserveInitialized(\n    address indexed asset,\n    address indexed aToken,\n    address stableDebtToken,\n    address variableDebtToken,\n    address interestRateStrategyAddress\n  );\n\n  /**\n   * @dev Emitted when borrowing is enabled or disabled on a reserve.\n   * @param asset The address of the underlying asset of the reserve\n   * @param enabled True if borrowing is enabled, false otherwise\n   */\n  event ReserveBorrowing(address indexed asset, bool enabled);\n\n  /**\n   * @dev Emitted when flashloans are enabled or disabled on a reserve.\n   * @param asset The address of the underlying asset of the reserve\n   * @param enabled True if flashloans are enabled, false otherwise\n   */\n  event ReserveFlashLoaning(address indexed asset, bool enabled);\n\n  /**\n   * @dev Emitted when the collateralization risk parameters for the specified asset are updated.\n   * @param asset The address of the underlying asset of the reserve\n   * @param ltv The loan to value of the asset when used as collateral\n   * @param liquidationThreshold The threshold at which loans using this asset as collateral will be considered undercollateralized\n   * @param liquidationBonus The bonus liquidators receive to liquidate this asset\n   */\n  event CollateralConfigurationChanged(\n    address indexed asset,\n    uint256 ltv,\n    uint256 liquidationThreshold,\n    uint256 liquidationBonus\n  );\n\n  /**\n   * @dev Emitted when stable rate borrowing is enabled or disabled on a reserve\n   * @param asset The address of the underlying asset of the reserve\n   * @param enabled True if stable rate borrowing is enabled, false otherwise\n   */\n  event ReserveStableRateBorrowing(address indexed asset, bool enabled);\n\n  /**\n   * @dev Emitted when a reserve is activated or deactivated\n   * @param asset The address of the underlying asset of the reserve\n   * @param active True if reserve is active, false otherwise\n   */\n  event ReserveActive(address indexed asset, bool active);\n\n  /**\n   * @dev Emitted when a reserve is frozen or unfrozen\n   * @param asset The address of the underlying asset of the reserve\n   * @param frozen True if reserve is frozen, false otherwise\n   */\n  event ReserveFrozen(address indexed asset, bool frozen);\n\n  /**\n   * @dev Emitted when a reserve is paused or unpaused\n   * @param asset The address of the underlying asset of the reserve\n   * @param paused True if reserve is paused, false otherwise\n   */\n  event ReservePaused(address indexed asset, bool paused);\n\n  /**\n   * @dev Emitted when a reserve is dropped.\n   * @param asset The address of the underlying asset of the reserve\n   */\n  event ReserveDropped(address indexed asset);\n\n  /**\n   * @dev Emitted when a reserve factor is updated.\n   * @param asset The address of the underlying asset of the reserve\n   * @param oldReserveFactor The old reserve factor, expressed in bps\n   * @param newReserveFactor The new reserve factor, expressed in bps\n   */\n  event ReserveFactorChanged(\n    address indexed asset,\n    uint256 oldReserveFactor,\n    uint256 newReserveFactor\n  );\n\n  /**\n   * @dev Emitted when the borrow cap of a reserve is updated.\n   * @param asset The address of the underlying asset of the reserve\n   * @param oldBorrowCap The old borrow cap\n   * @param newBorrowCap The new borrow cap\n   */\n  event BorrowCapChanged(address indexed asset, uint256 oldBorrowCap, uint256 newBorrowCap);\n\n  /**\n   * @dev Emitted when the supply cap of a reserve is updated.\n   * @param asset The address of the underlying asset of the reserve\n   * @param oldSupplyCap The old supply cap\n   * @param newSupplyCap The new supply cap\n   */\n  event SupplyCapChanged(address indexed asset, uint256 oldSupplyCap, uint256 newSupplyCap);\n\n  /**\n   * @dev Emitted when the liquidation protocol fee of a reserve is updated.\n   * @param asset The address of the underlying asset of the reserve\n   * @param oldFee The old liquidation protocol fee, expressed in bps\n   * @param newFee The new liquidation protocol fee, expressed in bps\n   */\n  event LiquidationProtocolFeeChanged(address indexed asset, uint256 oldFee, uint256 newFee);\n\n  /**\n   * @dev Emitted when the unbacked mint cap of a reserve is updated.\n   * @param asset The address of the underlying asset of the reserve\n   * @param oldUnbackedMintCap The old unbacked mint cap\n   * @param newUnbackedMintCap The new unbacked mint cap\n   */\n  event UnbackedMintCapChanged(\n    address indexed asset,\n    uint256 oldUnbackedMintCap,\n    uint256 newUnbackedMintCap\n  );\n\n  /**\n   * @dev Emitted when the category of an asset in eMode is changed.\n   * @param asset The address of the underlying asset of the reserve\n   * @param oldCategoryId The old eMode asset category\n   * @param newCategoryId The new eMode asset category\n   */\n  event EModeAssetCategoryChanged(address indexed asset, uint8 oldCategoryId, uint8 newCategoryId);\n\n  /**\n   * @dev Emitted when a new eMode category is added.\n   * @param categoryId The new eMode category id\n   * @param ltv The ltv for the asset category in eMode\n   * @param liquidationThreshold The liquidationThreshold for the asset category in eMode\n   * @param liquidationBonus The liquidationBonus for the asset category in eMode\n   * @param oracle The optional address of the price oracle specific for this category\n   * @param label A human readable identifier for the category\n   */\n  event EModeCategoryAdded(\n    uint8 indexed categoryId,\n    uint256 ltv,\n    uint256 liquidationThreshold,\n    uint256 liquidationBonus,\n    address oracle,\n    string label\n  );\n\n  /**\n   * @dev Emitted when a reserve interest strategy contract is updated.\n   * @param asset The address of the underlying asset of the reserve\n   * @param oldStrategy The address of the old interest strategy contract\n   * @param newStrategy The address of the new interest strategy contract\n   */\n  event ReserveInterestRateStrategyChanged(\n    address indexed asset,\n    address oldStrategy,\n    address newStrategy\n  );\n\n  /**\n   * @dev Emitted when an aToken implementation is upgraded.\n   * @param asset The address of the underlying asset of the reserve\n   * @param proxy The aToken proxy address\n   * @param implementation The new aToken implementation\n   */\n  event ATokenUpgraded(\n    address indexed asset,\n    address indexed proxy,\n    address indexed implementation\n  );\n\n  /**\n   * @dev Emitted when the implementation of a stable debt token is upgraded.\n   * @param asset The address of the underlying asset of the reserve\n   * @param proxy The stable debt token proxy address\n   * @param implementation The new aToken implementation\n   */\n  event StableDebtTokenUpgraded(\n    address indexed asset,\n    address indexed proxy,\n    address indexed implementation\n  );\n\n  /**\n   * @dev Emitted when the implementation of a variable debt token is upgraded.\n   * @param asset The address of the underlying asset of the reserve\n   * @param proxy The variable debt token proxy address\n   * @param implementation The new aToken implementation\n   */\n  event VariableDebtTokenUpgraded(\n    address indexed asset,\n    address indexed proxy,\n    address indexed implementation\n  );\n\n  /**\n   * @dev Emitted when the debt ceiling of an asset is set.\n   * @param asset The address of the underlying asset of the reserve\n   * @param oldDebtCeiling The old debt ceiling\n   * @param newDebtCeiling The new debt ceiling\n   */\n  event DebtCeilingChanged(address indexed asset, uint256 oldDebtCeiling, uint256 newDebtCeiling);\n\n  /**\n   * @dev Emitted when the the siloed borrowing state for an asset is changed.\n   * @param asset The address of the underlying asset of the reserve\n   * @param oldState The old siloed borrowing state\n   * @param newState The new siloed borrowing state\n   */\n  event SiloedBorrowingChanged(address indexed asset, bool oldState, bool newState);\n\n  /**\n   * @dev Emitted when the bridge protocol fee is updated.\n   * @param oldBridgeProtocolFee The old protocol fee, expressed in bps\n   * @param newBridgeProtocolFee The new protocol fee, expressed in bps\n   */\n  event BridgeProtocolFeeUpdated(uint256 oldBridgeProtocolFee, uint256 newBridgeProtocolFee);\n\n  /**\n   * @dev Emitted when the total premium on flashloans is updated.\n   * @param oldFlashloanPremiumTotal The old premium, expressed in bps\n   * @param newFlashloanPremiumTotal The new premium, expressed in bps\n   */\n  event FlashloanPremiumTotalUpdated(\n    uint128 oldFlashloanPremiumTotal,\n    uint128 newFlashloanPremiumTotal\n  );\n\n  /**\n   * @dev Emitted when the part of the premium that goes to protocol is updated.\n   * @param oldFlashloanPremiumToProtocol The old premium, expressed in bps\n   * @param newFlashloanPremiumToProtocol The new premium, expressed in bps\n   */\n  event FlashloanPremiumToProtocolUpdated(\n    uint128 oldFlashloanPremiumToProtocol,\n    uint128 newFlashloanPremiumToProtocol\n  );\n\n  /**\n   * @dev Emitted when the reserve is set as borrowable/non borrowable in isolation mode.\n   * @param asset The address of the underlying asset of the reserve\n   * @param borrowable True if the reserve is borrowable in isolation, false otherwise\n   */\n  event BorrowableInIsolationChanged(address asset, bool borrowable);\n\n  /**\n   * @notice Initializes multiple reserves.\n   * @param input The array of initialization parameters\n   */\n  function initReserves(ConfiguratorInputTypes.InitReserveInput[] calldata input) external;\n\n  /**\n   * @dev Updates the aToken implementation for the reserve.\n   * @param input The aToken update parameters\n   */\n  function updateAToken(ConfiguratorInputTypes.UpdateATokenInput calldata input) external;\n\n  /**\n   * @notice Updates the stable debt token implementation for the reserve.\n   * @param input The stableDebtToken update parameters\n   */\n  function updateStableDebtToken(\n    ConfiguratorInputTypes.UpdateDebtTokenInput calldata input\n  ) external;\n\n  /**\n   * @notice Updates the variable debt token implementation for the asset.\n   * @param input The variableDebtToken update parameters\n   */\n  function updateVariableDebtToken(\n    ConfiguratorInputTypes.UpdateDebtTokenInput calldata input\n  ) external;\n\n  /**\n   * @notice Configures borrowing on a reserve.\n   * @dev Can only be disabled (set to false) if stable borrowing is disabled\n   * @param asset The address of the underlying asset of the reserve\n   * @param enabled True if borrowing needs to be enabled, false otherwise\n   */\n  function setReserveBorrowing(address asset, bool enabled) external;\n\n  /**\n   * @notice Configures the reserve collateralization parameters.\n   * @dev All the values are expressed in bps. A value of 10000, results in 100.00%\n   * @dev The `liquidationBonus` is always above 100%. A value of 105% means the liquidator will receive a 5% bonus\n   * @param asset The address of the underlying asset of the reserve\n   * @param ltv The loan to value of the asset when used as collateral\n   * @param liquidationThreshold The threshold at which loans using this asset as collateral will be considered undercollateralized\n   * @param liquidationBonus The bonus liquidators receive to liquidate this asset\n   */\n  function configureReserveAsCollateral(\n    address asset,\n    uint256 ltv,\n    uint256 liquidationThreshold,\n    uint256 liquidationBonus\n  ) external;\n\n  /**\n   * @notice Enable or disable stable rate borrowing on a reserve.\n   * @dev Can only be enabled (set to true) if borrowing is enabled\n   * @param asset The address of the underlying asset of the reserve\n   * @param enabled True if stable rate borrowing needs to be enabled, false otherwise\n   */\n  function setReserveStableRateBorrowing(address asset, bool enabled) external;\n\n  /**\n   * @notice Enable or disable flashloans on a reserve\n   * @param asset The address of the underlying asset of the reserve\n   * @param enabled True if flashloans need to be enabled, false otherwise\n   */\n  function setReserveFlashLoaning(address asset, bool enabled) external;\n\n  /**\n   * @notice Activate or deactivate a reserve\n   * @param asset The address of the underlying asset of the reserve\n   * @param active True if the reserve needs to be active, false otherwise\n   */\n  function setReserveActive(address asset, bool active) external;\n\n  /**\n   * @notice Freeze or unfreeze a reserve. A frozen reserve doesn't allow any new supply, borrow\n   * or rate swap but allows repayments, liquidations, rate rebalances and withdrawals.\n   * @param asset The address of the underlying asset of the reserve\n   * @param freeze True if the reserve needs to be frozen, false otherwise\n   */\n  function setReserveFreeze(address asset, bool freeze) external;\n\n  /**\n   * @notice Sets the borrowable in isolation flag for the reserve.\n   * @dev When this flag is set to true, the asset will be borrowable against isolated collaterals and the\n   * borrowed amount will be accumulated in the isolated collateral's total debt exposure\n   * @dev Only assets of the same family (e.g. USD stablecoins) should be borrowable in isolation mode to keep\n   * consistency in the debt ceiling calculations\n   * @param asset The address of the underlying asset of the reserve\n   * @param borrowable True if the asset should be borrowable in isolation, false otherwise\n   */\n  function setBorrowableInIsolation(address asset, bool borrowable) external;\n\n  /**\n   * @notice Pauses a reserve. A paused reserve does not allow any interaction (supply, borrow, repay,\n   * swap interest rate, liquidate, atoken transfers).\n   * @param asset The address of the underlying asset of the reserve\n   * @param paused True if pausing the reserve, false if unpausing\n   */\n  function setReservePause(address asset, bool paused) external;\n\n  /**\n   * @notice Updates the reserve factor of a reserve.\n   * @param asset The address of the underlying asset of the reserve\n   * @param newReserveFactor The new reserve factor of the reserve\n   */\n  function setReserveFactor(address asset, uint256 newReserveFactor) external;\n\n  /**\n   * @notice Sets the interest rate strategy of a reserve.\n   * @param asset The address of the underlying asset of the reserve\n   * @param newRateStrategyAddress The address of the new interest strategy contract\n   */\n  function setReserveInterestRateStrategyAddress(\n    address asset,\n    address newRateStrategyAddress\n  ) external;\n\n  /**\n   * @notice Pauses or unpauses all the protocol reserves. In the paused state all the protocol interactions\n   * are suspended.\n   * @param paused True if protocol needs to be paused, false otherwise\n   */\n  function setPoolPause(bool paused) external;\n\n  /**\n   * @notice Updates the borrow cap of a reserve.\n   * @param asset The address of the underlying asset of the reserve\n   * @param newBorrowCap The new borrow cap of the reserve\n   */\n  function setBorrowCap(address asset, uint256 newBorrowCap) external;\n\n  /**\n   * @notice Updates the supply cap of a reserve.\n   * @param asset The address of the underlying asset of the reserve\n   * @param newSupplyCap The new supply cap of the reserve\n   */\n  function setSupplyCap(address asset, uint256 newSupplyCap) external;\n\n  /**\n   * @notice Updates the liquidation protocol fee of reserve.\n   * @param asset The address of the underlying asset of the reserve\n   * @param newFee The new liquidation protocol fee of the reserve, expressed in bps\n   */\n  function setLiquidationProtocolFee(address asset, uint256 newFee) external;\n\n  /**\n   * @notice Updates the unbacked mint cap of reserve.\n   * @param asset The address of the underlying asset of the reserve\n   * @param newUnbackedMintCap The new unbacked mint cap of the reserve\n   */\n  function setUnbackedMintCap(address asset, uint256 newUnbackedMintCap) external;\n\n  /**\n   * @notice Assign an efficiency mode (eMode) category to asset.\n   * @param asset The address of the underlying asset of the reserve\n   * @param newCategoryId The new category id of the asset\n   */\n  function setAssetEModeCategory(address asset, uint8 newCategoryId) external;\n\n  /**\n   * @notice Adds a new efficiency mode (eMode) category.\n   * @dev If zero is provided as oracle address, the default asset oracles will be used to compute the overall debt and\n   * overcollateralization of the users using this category.\n   * @dev The new ltv and liquidation threshold must be greater than the base\n   * ltvs and liquidation thresholds of all assets within the eMode category\n   * @param categoryId The id of the category to be configured\n   * @param ltv The ltv associated with the category\n   * @param liquidationThreshold The liquidation threshold associated with the category\n   * @param liquidationBonus The liquidation bonus associated with the category\n   * @param oracle The oracle associated with the category\n   * @param label A label identifying the category\n   */\n  function setEModeCategory(\n    uint8 categoryId,\n    uint16 ltv,\n    uint16 liquidationThreshold,\n    uint16 liquidationBonus,\n    address oracle,\n    string calldata label\n  ) external;\n\n  /**\n   * @notice Drops a reserve entirely.\n   * @param asset The address of the reserve to drop\n   */\n  function dropReserve(address asset) external;\n\n  /**\n   * @notice Updates the bridge fee collected by the protocol reserves.\n   * @param newBridgeProtocolFee The part of the fee sent to the protocol treasury, expressed in bps\n   */\n  function updateBridgeProtocolFee(uint256 newBridgeProtocolFee) external;\n\n  /**\n   * @notice Updates the total flash loan premium.\n   * Total flash loan premium consists of two parts:\n   * - A part is sent to aToken holders as extra balance\n   * - A part is collected by the protocol reserves\n   * @dev Expressed in bps\n   * @dev The premium is calculated on the total amount borrowed\n   * @param newFlashloanPremiumTotal The total flashloan premium\n   */\n  function updateFlashloanPremiumTotal(uint128 newFlashloanPremiumTotal) external;\n\n  /**\n   * @notice Updates the flash loan premium collected by protocol reserves\n   * @dev Expressed in bps\n   * @dev The premium to protocol is calculated on the total flashloan premium\n   * @param newFlashloanPremiumToProtocol The part of the flashloan premium sent to the protocol treasury\n   */\n  function updateFlashloanPremiumToProtocol(uint128 newFlashloanPremiumToProtocol) external;\n\n  /**\n   * @notice Sets the debt ceiling for an asset.\n   * @param newDebtCeiling The new debt ceiling\n   */\n  function setDebtCeiling(address asset, uint256 newDebtCeiling) external;\n\n  /**\n   * @notice Sets siloed borrowing for an asset\n   * @param siloed The new siloed borrowing state\n   */\n  function setSiloedBorrowing(address asset, bool siloed) external;\n}\n"
      },
      "src/core/contracts/interfaces/IPoolDataProvider.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {IPoolAddressesProvider} from './IPoolAddressesProvider.sol';\n\n/**\n * @title IPoolDataProvider\n * @author Aave\n * @notice Defines the basic interface of a PoolDataProvider\n */\ninterface IPoolDataProvider {\n  struct TokenData {\n    string symbol;\n    address tokenAddress;\n  }\n\n  /**\n   * @notice Returns the address for the PoolAddressesProvider contract.\n   * @return The address for the PoolAddressesProvider contract\n   */\n  function ADDRESSES_PROVIDER() external view returns (IPoolAddressesProvider);\n\n  /**\n   * @notice Returns the list of the existing reserves in the pool.\n   * @dev Handling MKR and ETH in a different way since they do not have standard `symbol` functions.\n   * @return The list of reserves, pairs of symbols and addresses\n   */\n  function getAllReservesTokens() external view returns (TokenData[] memory);\n\n  /**\n   * @notice Returns the list of the existing ATokens in the pool.\n   * @return The list of ATokens, pairs of symbols and addresses\n   */\n  function getAllATokens() external view returns (TokenData[] memory);\n\n  /**\n   * @notice Returns the configuration data of the reserve\n   * @dev Not returning borrow and supply caps for compatibility, nor pause flag\n   * @param asset The address of the underlying asset of the reserve\n   * @return decimals The number of decimals of the reserve\n   * @return ltv The ltv of the reserve\n   * @return liquidationThreshold The liquidationThreshold of the reserve\n   * @return liquidationBonus The liquidationBonus of the reserve\n   * @return reserveFactor The reserveFactor of the reserve\n   * @return usageAsCollateralEnabled True if the usage as collateral is enabled, false otherwise\n   * @return borrowingEnabled True if borrowing is enabled, false otherwise\n   * @return stableBorrowRateEnabled True if stable rate borrowing is enabled, false otherwise\n   * @return isActive True if it is active, false otherwise\n   * @return isFrozen True if it is frozen, false otherwise\n   */\n  function getReserveConfigurationData(\n    address asset\n  )\n    external\n    view\n    returns (\n      uint256 decimals,\n      uint256 ltv,\n      uint256 liquidationThreshold,\n      uint256 liquidationBonus,\n      uint256 reserveFactor,\n      bool usageAsCollateralEnabled,\n      bool borrowingEnabled,\n      bool stableBorrowRateEnabled,\n      bool isActive,\n      bool isFrozen\n    );\n\n  /**\n   * @notice Returns the efficiency mode category of the reserve\n   * @param asset The address of the underlying asset of the reserve\n   * @return The eMode id of the reserve\n   */\n  function getReserveEModeCategory(address asset) external view returns (uint256);\n\n  /**\n   * @notice Returns the caps parameters of the reserve\n   * @param asset The address of the underlying asset of the reserve\n   * @return borrowCap The borrow cap of the reserve\n   * @return supplyCap The supply cap of the reserve\n   */\n  function getReserveCaps(\n    address asset\n  ) external view returns (uint256 borrowCap, uint256 supplyCap);\n\n  /**\n   * @notice Returns if the pool is paused\n   * @param asset The address of the underlying asset of the reserve\n   * @return isPaused True if the pool is paused, false otherwise\n   */\n  function getPaused(address asset) external view returns (bool isPaused);\n\n  /**\n   * @notice Returns the siloed borrowing flag\n   * @param asset The address of the underlying asset of the reserve\n   * @return True if the asset is siloed for borrowing\n   */\n  function getSiloedBorrowing(address asset) external view returns (bool);\n\n  /**\n   * @notice Returns the protocol fee on the liquidation bonus\n   * @param asset The address of the underlying asset of the reserve\n   * @return The protocol fee on liquidation\n   */\n  function getLiquidationProtocolFee(address asset) external view returns (uint256);\n\n  /**\n   * @notice Returns the unbacked mint cap of the reserve\n   * @param asset The address of the underlying asset of the reserve\n   * @return The unbacked mint cap of the reserve\n   */\n  function getUnbackedMintCap(address asset) external view returns (uint256);\n\n  /**\n   * @notice Returns the debt ceiling of the reserve\n   * @param asset The address of the underlying asset of the reserve\n   * @return The debt ceiling of the reserve\n   */\n  function getDebtCeiling(address asset) external view returns (uint256);\n\n  /**\n   * @notice Returns the debt ceiling decimals\n   * @return The debt ceiling decimals\n   */\n  function getDebtCeilingDecimals() external pure returns (uint256);\n\n  /**\n   * @notice Returns the reserve data\n   * @param asset The address of the underlying asset of the reserve\n   * @return unbacked The amount of unbacked tokens\n   * @return accruedToTreasuryScaled The scaled amount of tokens accrued to treasury that is to be minted\n   * @return totalAToken The total supply of the aToken\n   * @return totalStableDebt The total stable debt of the reserve\n   * @return totalVariableDebt The total variable debt of the reserve\n   * @return liquidityRate The liquidity rate of the reserve\n   * @return variableBorrowRate The variable borrow rate of the reserve\n   * @return stableBorrowRate The stable borrow rate of the reserve\n   * @return averageStableBorrowRate The average stable borrow rate of the reserve\n   * @return liquidityIndex The liquidity index of the reserve\n   * @return variableBorrowIndex The variable borrow index of the reserve\n   * @return lastUpdateTimestamp The timestamp of the last update of the reserve\n   */\n  function getReserveData(\n    address asset\n  )\n    external\n    view\n    returns (\n      uint256 unbacked,\n      uint256 accruedToTreasuryScaled,\n      uint256 totalAToken,\n      uint256 totalStableDebt,\n      uint256 totalVariableDebt,\n      uint256 liquidityRate,\n      uint256 variableBorrowRate,\n      uint256 stableBorrowRate,\n      uint256 averageStableBorrowRate,\n      uint256 liquidityIndex,\n      uint256 variableBorrowIndex,\n      uint40 lastUpdateTimestamp\n    );\n\n  /**\n   * @notice Returns the total supply of aTokens for a given asset\n   * @param asset The address of the underlying asset of the reserve\n   * @return The total supply of the aToken\n   */\n  function getATokenTotalSupply(address asset) external view returns (uint256);\n\n  /**\n   * @notice Returns the total debt for a given asset\n   * @param asset The address of the underlying asset of the reserve\n   * @return The total debt for asset\n   */\n  function getTotalDebt(address asset) external view returns (uint256);\n\n  /**\n   * @notice Returns the user data in a reserve\n   * @param asset The address of the underlying asset of the reserve\n   * @param user The address of the user\n   * @return currentATokenBalance The current AToken balance of the user\n   * @return currentStableDebt The current stable debt of the user\n   * @return currentVariableDebt The current variable debt of the user\n   * @return principalStableDebt The principal stable debt of the user\n   * @return scaledVariableDebt The scaled variable debt of the user\n   * @return stableBorrowRate The stable borrow rate of the user\n   * @return liquidityRate The liquidity rate of the reserve\n   * @return stableRateLastUpdated The timestamp of the last update of the user stable rate\n   * @return usageAsCollateralEnabled True if the user is using the asset as collateral, false\n   *         otherwise\n   */\n  function getUserReserveData(\n    address asset,\n    address user\n  )\n    external\n    view\n    returns (\n      uint256 currentATokenBalance,\n      uint256 currentStableDebt,\n      uint256 currentVariableDebt,\n      uint256 principalStableDebt,\n      uint256 scaledVariableDebt,\n      uint256 stableBorrowRate,\n      uint256 liquidityRate,\n      uint40 stableRateLastUpdated,\n      bool usageAsCollateralEnabled\n    );\n\n  /**\n   * @notice Returns the token addresses of the reserve\n   * @param asset The address of the underlying asset of the reserve\n   * @return aTokenAddress The AToken address of the reserve\n   * @return stableDebtTokenAddress The StableDebtToken address of the reserve\n   * @return variableDebtTokenAddress The VariableDebtToken address of the reserve\n   */\n  function getReserveTokensAddresses(\n    address asset\n  )\n    external\n    view\n    returns (\n      address aTokenAddress,\n      address stableDebtTokenAddress,\n      address variableDebtTokenAddress\n    );\n\n  /**\n   * @notice Returns the address of the Interest Rate strategy\n   * @param asset The address of the underlying asset of the reserve\n   * @return irStrategyAddress The address of the Interest Rate strategy\n   */\n  function getInterestRateStrategyAddress(\n    address asset\n  ) external view returns (address irStrategyAddress);\n\n  /**\n   * @notice Returns whether the reserve has FlashLoans enabled or disabled\n   * @param asset The address of the underlying asset of the reserve\n   * @return True if FlashLoans are enabled, false otherwise\n   */\n  function getFlashLoanEnabled(address asset) external view returns (bool);\n}\n"
      },
      "src/core/contracts/interfaces/IPriceOracleGetter.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n/**\n * @title IPriceOracleGetter\n * @author Aave\n * @notice Interface for the Aave price oracle.\n */\ninterface IPriceOracleGetter {\n  /**\n   * @notice Returns the base currency address\n   * @dev Address 0x0 is reserved for USD as base currency.\n   * @return Returns the base currency address.\n   */\n  function BASE_CURRENCY() external view returns (address);\n\n  /**\n   * @notice Returns the base currency unit\n   * @dev 1 ether for ETH, 1e8 for USD.\n   * @return Returns the base currency unit.\n   */\n  function BASE_CURRENCY_UNIT() external view returns (uint256);\n\n  /**\n   * @notice Returns the asset price in the base currency\n   * @param asset The address of the asset\n   * @return The price of the asset\n   */\n  function getAssetPrice(address asset) external view returns (uint256);\n}\n"
      },
      "src/core/contracts/interfaces/IPriceOracleSentinel.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {IPoolAddressesProvider} from './IPoolAddressesProvider.sol';\n\n/**\n * @title IPriceOracleSentinel\n * @author Aave\n * @notice Defines the basic interface for the PriceOracleSentinel\n */\ninterface IPriceOracleSentinel {\n  /**\n   * @dev Emitted after the sequencer oracle is updated\n   * @param newSequencerOracle The new sequencer oracle\n   */\n  event SequencerOracleUpdated(address newSequencerOracle);\n\n  /**\n   * @dev Emitted after the grace period is updated\n   * @param newGracePeriod The new grace period value\n   */\n  event GracePeriodUpdated(uint256 newGracePeriod);\n\n  /**\n   * @notice Returns the PoolAddressesProvider\n   * @return The address of the PoolAddressesProvider contract\n   */\n  function ADDRESSES_PROVIDER() external view returns (IPoolAddressesProvider);\n\n  /**\n   * @notice Returns true if the `borrow` operation is allowed.\n   * @dev Operation not allowed when PriceOracle is down or grace period not passed.\n   * @return True if the `borrow` operation is allowed, false otherwise.\n   */\n  function isBorrowAllowed() external view returns (bool);\n\n  /**\n   * @notice Returns true if the `liquidation` operation is allowed.\n   * @dev Operation not allowed when PriceOracle is down or grace period not passed.\n   * @return True if the `liquidation` operation is allowed, false otherwise.\n   */\n  function isLiquidationAllowed() external view returns (bool);\n\n  /**\n   * @notice Updates the address of the sequencer oracle\n   * @param newSequencerOracle The address of the new Sequencer Oracle to use\n   */\n  function setSequencerOracle(address newSequencerOracle) external;\n\n  /**\n   * @notice Updates the duration of the grace period\n   * @param newGracePeriod The value of the new grace period duration\n   */\n  function setGracePeriod(uint256 newGracePeriod) external;\n\n  /**\n   * @notice Returns the SequencerOracle\n   * @return The address of the sequencer oracle contract\n   */\n  function getSequencerOracle() external view returns (address);\n\n  /**\n   * @notice Returns the grace period\n   * @return The duration of the grace period\n   */\n  function getGracePeriod() external view returns (uint256);\n}\n"
      },
      "src/core/contracts/interfaces/IReserveInterestRateStrategy.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {DataTypes} from '../protocol/libraries/types/DataTypes.sol';\n\n/**\n * @title IReserveInterestRateStrategy\n * @author Aave\n * @notice Interface for the calculation of the interest rates\n */\ninterface IReserveInterestRateStrategy {\n  /**\n   * @notice Calculates the interest rates depending on the reserve's state and configurations\n   * @param params The parameters needed to calculate interest rates\n   * @return liquidityRate The liquidity rate expressed in rays\n   * @return stableBorrowRate The stable borrow rate expressed in rays\n   * @return variableBorrowRate The variable borrow rate expressed in rays\n   */\n  function calculateInterestRates(\n    DataTypes.CalculateInterestRatesParams memory params\n  ) external view returns (uint256, uint256, uint256);\n}\n"
      },
      "src/core/contracts/interfaces/IScaledBalanceToken.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n/**\n * @title IScaledBalanceToken\n * @author Aave\n * @notice Defines the basic interface for a scaled-balance token.\n */\ninterface IScaledBalanceToken {\n  /**\n   * @dev Emitted after the mint action\n   * @param caller The address performing the mint\n   * @param onBehalfOf The address of the user that will receive the minted tokens\n   * @param value The scaled-up amount being minted (based on user entered amount and balance increase from interest)\n   * @param balanceIncrease The increase in scaled-up balance since the last action of 'onBehalfOf'\n   * @param index The next liquidity index of the reserve\n   */\n  event Mint(\n    address indexed caller,\n    address indexed onBehalfOf,\n    uint256 value,\n    uint256 balanceIncrease,\n    uint256 index\n  );\n\n  /**\n   * @dev Emitted after the burn action\n   * @dev If the burn function does not involve a transfer of the underlying asset, the target defaults to zero address\n   * @param from The address from which the tokens will be burned\n   * @param target The address that will receive the underlying, if any\n   * @param value The scaled-up amount being burned (user entered amount - balance increase from interest)\n   * @param balanceIncrease The increase in scaled-up balance since the last action of 'from'\n   * @param index The next liquidity index of the reserve\n   */\n  event Burn(\n    address indexed from,\n    address indexed target,\n    uint256 value,\n    uint256 balanceIncrease,\n    uint256 index\n  );\n\n  /**\n   * @notice Returns the scaled balance of the user.\n   * @dev The scaled balance is the sum of all the updated stored balance divided by the reserve's liquidity index\n   * at the moment of the update\n   * @param user The user whose balance is calculated\n   * @return The scaled balance of the user\n   */\n  function scaledBalanceOf(address user) external view returns (uint256);\n\n  /**\n   * @notice Returns the scaled balance of the user and the scaled total supply.\n   * @param user The address of the user\n   * @return The scaled balance of the user\n   * @return The scaled total supply\n   */\n  function getScaledUserBalanceAndSupply(address user) external view returns (uint256, uint256);\n\n  /**\n   * @notice Returns the scaled total supply of the scaled balance token. Represents sum(debt/index)\n   * @return The scaled total supply\n   */\n  function scaledTotalSupply() external view returns (uint256);\n\n  /**\n   * @notice Returns last index interest was accrued to the user's balance\n   * @param user The address of the user\n   * @return The last index interest was accrued to the user's balance, expressed in ray\n   */\n  function getPreviousIndex(address user) external view returns (uint256);\n}\n"
      },
      "src/core/contracts/interfaces/IStableDebtToken.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {IInitializableDebtToken} from './IInitializableDebtToken.sol';\n\n/**\n * @title IStableDebtToken\n * @author Aave\n * @notice Defines the interface for the stable debt token\n * @dev It does not inherit from IERC20 to save in code size\n */\ninterface IStableDebtToken is IInitializableDebtToken {\n  /**\n   * @dev Emitted when new stable debt is minted\n   * @param user The address of the user who triggered the minting\n   * @param onBehalfOf The recipient of stable debt tokens\n   * @param amount The amount minted (user entered amount + balance increase from interest)\n   * @param currentBalance The balance of the user based on the previous balance and balance increase from interest\n   * @param balanceIncrease The increase in balance since the last action of the user 'onBehalfOf'\n   * @param newRate The rate of the debt after the minting\n   * @param avgStableRate The next average stable rate after the minting\n   * @param newTotalSupply The next total supply of the stable debt token after the action\n   */\n  event Mint(\n    address indexed user,\n    address indexed onBehalfOf,\n    uint256 amount,\n    uint256 currentBalance,\n    uint256 balanceIncrease,\n    uint256 newRate,\n    uint256 avgStableRate,\n    uint256 newTotalSupply\n  );\n\n  /**\n   * @dev Emitted when new stable debt is burned\n   * @param from The address from which the debt will be burned\n   * @param amount The amount being burned (user entered amount - balance increase from interest)\n   * @param currentBalance The balance of the user based on the previous balance and balance increase from interest\n   * @param balanceIncrease The increase in balance since the last action of 'from'\n   * @param avgStableRate The next average stable rate after the burning\n   * @param newTotalSupply The next total supply of the stable debt token after the action\n   */\n  event Burn(\n    address indexed from,\n    uint256 amount,\n    uint256 currentBalance,\n    uint256 balanceIncrease,\n    uint256 avgStableRate,\n    uint256 newTotalSupply\n  );\n\n  /**\n   * @notice Mints debt token to the `onBehalfOf` address.\n   * @dev The resulting rate is the weighted average between the rate of the new debt\n   * and the rate of the previous debt\n   * @param user The address receiving the borrowed underlying, being the delegatee in case\n   * of credit delegate, or same as `onBehalfOf` otherwise\n   * @param onBehalfOf The address receiving the debt tokens\n   * @param amount The amount of debt tokens to mint\n   * @param rate The rate of the debt being minted\n   * @return True if it is the first borrow, false otherwise\n   * @return The total stable debt\n   * @return The average stable borrow rate\n   */\n  function mint(\n    address user,\n    address onBehalfOf,\n    uint256 amount,\n    uint256 rate\n  ) external returns (bool, uint256, uint256);\n\n  /**\n   * @notice Burns debt of `user`\n   * @dev The resulting rate is the weighted average between the rate of the new debt\n   * and the rate of the previous debt\n   * @dev In some instances, a burn transaction will emit a mint event\n   * if the amount to burn is less than the interest the user earned\n   * @param from The address from which the debt will be burned\n   * @param amount The amount of debt tokens getting burned\n   * @return The total stable debt\n   * @return The average stable borrow rate\n   */\n  function burn(address from, uint256 amount) external returns (uint256, uint256);\n\n  /**\n   * @notice Returns the average rate of all the stable rate loans.\n   * @return The average stable rate\n   */\n  function getAverageStableRate() external view returns (uint256);\n\n  /**\n   * @notice Returns the stable rate of the user debt\n   * @param user The address of the user\n   * @return The stable rate of the user\n   */\n  function getUserStableRate(address user) external view returns (uint256);\n\n  /**\n   * @notice Returns the timestamp of the last update of the user\n   * @param user The address of the user\n   * @return The timestamp\n   */\n  function getUserLastUpdated(address user) external view returns (uint40);\n\n  /**\n   * @notice Returns the principal, the total supply, the average stable rate and the timestamp for the last update\n   * @return The principal\n   * @return The total supply\n   * @return The average stable rate\n   * @return The timestamp of the last update\n   */\n  function getSupplyData() external view returns (uint256, uint256, uint256, uint40);\n\n  /**\n   * @notice Returns the timestamp of the last update of the total supply\n   * @return The timestamp\n   */\n  function getTotalSupplyLastUpdated() external view returns (uint40);\n\n  /**\n   * @notice Returns the total supply and the average stable rate\n   * @return The total supply\n   * @return The average rate\n   */\n  function getTotalSupplyAndAvgRate() external view returns (uint256, uint256);\n\n  /**\n   * @notice Returns the principal debt balance of the user\n   * @return The debt balance of the user since the last burn/mint action\n   */\n  function principalBalanceOf(address user) external view returns (uint256);\n\n  /**\n   * @notice Returns the address of the underlying asset of this stableDebtToken (E.g. WETH for stableDebtWETH)\n   * @return The address of the underlying asset\n   */\n  function UNDERLYING_ASSET_ADDRESS() external view returns (address);\n}\n"
      },
      "src/core/contracts/interfaces/IVariableDebtToken.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {IScaledBalanceToken} from './IScaledBalanceToken.sol';\nimport {IInitializableDebtToken} from './IInitializableDebtToken.sol';\n\n/**\n * @title IVariableDebtToken\n * @author Aave\n * @notice Defines the basic interface for a variable debt token.\n */\ninterface IVariableDebtToken is IScaledBalanceToken, IInitializableDebtToken {\n  /**\n   * @notice Mints debt token to the `onBehalfOf` address\n   * @param user The address receiving the borrowed underlying, being the delegatee in case\n   * of credit delegate, or same as `onBehalfOf` otherwise\n   * @param onBehalfOf The address receiving the debt tokens\n   * @param amount The amount of debt being minted\n   * @param index The variable debt index of the reserve\n   * @return True if the previous balance of the user is 0, false otherwise\n   * @return The scaled total debt of the reserve\n   */\n  function mint(\n    address user,\n    address onBehalfOf,\n    uint256 amount,\n    uint256 index\n  ) external returns (bool, uint256);\n\n  /**\n   * @notice Burns user variable debt\n   * @dev In some instances, a burn transaction will emit a mint event\n   * if the amount to burn is less than the interest that the user accrued\n   * @param from The address from which the debt will be burned\n   * @param amount The amount getting burned\n   * @param index The variable debt index of the reserve\n   * @return The scaled total debt of the reserve\n   */\n  function burn(address from, uint256 amount, uint256 index) external returns (uint256);\n\n  /**\n   * @notice Returns the address of the underlying asset of this debtToken (E.g. WETH for variableDebtWETH)\n   * @return The address of the underlying asset\n   */\n  function UNDERLYING_ASSET_ADDRESS() external view returns (address);\n}\n"
      },
      "src/core/contracts/misc/AaveProtocolDataProvider.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport {IERC20Detailed} from '../dependencies/openzeppelin/contracts/IERC20Detailed.sol';\nimport {ReserveConfiguration} from '../protocol/libraries/configuration/ReserveConfiguration.sol';\nimport {UserConfiguration} from '../protocol/libraries/configuration/UserConfiguration.sol';\nimport {DataTypes} from '../protocol/libraries/types/DataTypes.sol';\nimport {WadRayMath} from '../protocol/libraries/math/WadRayMath.sol';\nimport {IPoolAddressesProvider} from '../interfaces/IPoolAddressesProvider.sol';\nimport {IStableDebtToken} from '../interfaces/IStableDebtToken.sol';\nimport {IVariableDebtToken} from '../interfaces/IVariableDebtToken.sol';\nimport {IPool} from '../interfaces/IPool.sol';\nimport {IPoolDataProvider} from '../interfaces/IPoolDataProvider.sol';\n\n/**\n * @title AaveProtocolDataProvider\n * @author Aave\n * @notice Peripheral contract to collect and pre-process information from the Pool.\n */\ncontract AaveProtocolDataProvider is IPoolDataProvider {\n  using ReserveConfiguration for DataTypes.ReserveConfigurationMap;\n  using UserConfiguration for DataTypes.UserConfigurationMap;\n  using WadRayMath for uint256;\n\n  address constant MKR = 0x9f8F72aA9304c8B593d555F12eF6589cC3A579A2;\n  address constant ETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;\n\n  /// @inheritdoc IPoolDataProvider\n  IPoolAddressesProvider public immutable ADDRESSES_PROVIDER;\n\n  /**\n   * @notice Constructor\n   * @param addressesProvider The address of the PoolAddressesProvider contract\n   */\n  constructor(IPoolAddressesProvider addressesProvider) {\n    ADDRESSES_PROVIDER = addressesProvider;\n  }\n\n  /// @inheritdoc IPoolDataProvider\n  function getAllReservesTokens() external view override returns (TokenData[] memory) {\n    IPool pool = IPool(ADDRESSES_PROVIDER.getPool());\n    address[] memory reserves = pool.getReservesList();\n    TokenData[] memory reservesTokens = new TokenData[](reserves.length);\n    for (uint256 i = 0; i < reserves.length; i++) {\n      if (reserves[i] == MKR) {\n        reservesTokens[i] = TokenData({symbol: 'MKR', tokenAddress: reserves[i]});\n        continue;\n      }\n      if (reserves[i] == ETH) {\n        reservesTokens[i] = TokenData({symbol: 'ETH', tokenAddress: reserves[i]});\n        continue;\n      }\n      reservesTokens[i] = TokenData({\n        symbol: IERC20Detailed(reserves[i]).symbol(),\n        tokenAddress: reserves[i]\n      });\n    }\n    return reservesTokens;\n  }\n\n  /// @inheritdoc IPoolDataProvider\n  function getAllATokens() external view override returns (TokenData[] memory) {\n    IPool pool = IPool(ADDRESSES_PROVIDER.getPool());\n    address[] memory reserves = pool.getReservesList();\n    TokenData[] memory aTokens = new TokenData[](reserves.length);\n    for (uint256 i = 0; i < reserves.length; i++) {\n      DataTypes.ReserveData memory reserveData = pool.getReserveData(reserves[i]);\n      aTokens[i] = TokenData({\n        symbol: IERC20Detailed(reserveData.aTokenAddress).symbol(),\n        tokenAddress: reserveData.aTokenAddress\n      });\n    }\n    return aTokens;\n  }\n\n  /// @inheritdoc IPoolDataProvider\n  function getReserveConfigurationData(\n    address asset\n  )\n    external\n    view\n    override\n    returns (\n      uint256 decimals,\n      uint256 ltv,\n      uint256 liquidationThreshold,\n      uint256 liquidationBonus,\n      uint256 reserveFactor,\n      bool usageAsCollateralEnabled,\n      bool borrowingEnabled,\n      bool stableBorrowRateEnabled,\n      bool isActive,\n      bool isFrozen\n    )\n  {\n    DataTypes.ReserveConfigurationMap memory configuration = IPool(ADDRESSES_PROVIDER.getPool())\n      .getConfiguration(asset);\n\n    (ltv, liquidationThreshold, liquidationBonus, decimals, reserveFactor, ) = configuration\n      .getParams();\n\n    (isActive, isFrozen, borrowingEnabled, stableBorrowRateEnabled, ) = configuration.getFlags();\n\n    usageAsCollateralEnabled = liquidationThreshold != 0;\n  }\n\n  /// @inheritdoc IPoolDataProvider\n  function getReserveEModeCategory(address asset) external view override returns (uint256) {\n    DataTypes.ReserveConfigurationMap memory configuration = IPool(ADDRESSES_PROVIDER.getPool())\n      .getConfiguration(asset);\n    return configuration.getEModeCategory();\n  }\n\n  /// @inheritdoc IPoolDataProvider\n  function getReserveCaps(\n    address asset\n  ) external view override returns (uint256 borrowCap, uint256 supplyCap) {\n    (borrowCap, supplyCap) = IPool(ADDRESSES_PROVIDER.getPool()).getConfiguration(asset).getCaps();\n  }\n\n  /// @inheritdoc IPoolDataProvider\n  function getPaused(address asset) external view override returns (bool isPaused) {\n    (, , , , isPaused) = IPool(ADDRESSES_PROVIDER.getPool()).getConfiguration(asset).getFlags();\n  }\n\n  /// @inheritdoc IPoolDataProvider\n  function getSiloedBorrowing(address asset) external view override returns (bool) {\n    return IPool(ADDRESSES_PROVIDER.getPool()).getConfiguration(asset).getSiloedBorrowing();\n  }\n\n  /// @inheritdoc IPoolDataProvider\n  function getLiquidationProtocolFee(address asset) external view override returns (uint256) {\n    return IPool(ADDRESSES_PROVIDER.getPool()).getConfiguration(asset).getLiquidationProtocolFee();\n  }\n\n  /// @inheritdoc IPoolDataProvider\n  function getUnbackedMintCap(address asset) external view override returns (uint256) {\n    return IPool(ADDRESSES_PROVIDER.getPool()).getConfiguration(asset).getUnbackedMintCap();\n  }\n\n  /// @inheritdoc IPoolDataProvider\n  function getDebtCeiling(address asset) external view override returns (uint256) {\n    return IPool(ADDRESSES_PROVIDER.getPool()).getConfiguration(asset).getDebtCeiling();\n  }\n\n  /// @inheritdoc IPoolDataProvider\n  function getDebtCeilingDecimals() external pure override returns (uint256) {\n    return ReserveConfiguration.DEBT_CEILING_DECIMALS;\n  }\n\n  /// @inheritdoc IPoolDataProvider\n  function getReserveData(\n    address asset\n  )\n    external\n    view\n    override\n    returns (\n      uint256 unbacked,\n      uint256 accruedToTreasuryScaled,\n      uint256 totalAToken,\n      uint256 totalStableDebt,\n      uint256 totalVariableDebt,\n      uint256 liquidityRate,\n      uint256 variableBorrowRate,\n      uint256 stableBorrowRate,\n      uint256 averageStableBorrowRate,\n      uint256 liquidityIndex,\n      uint256 variableBorrowIndex,\n      uint40 lastUpdateTimestamp\n    )\n  {\n    DataTypes.ReserveData memory reserve = IPool(ADDRESSES_PROVIDER.getPool()).getReserveData(\n      asset\n    );\n\n    return (\n      reserve.unbacked,\n      reserve.accruedToTreasury,\n      IERC20Detailed(reserve.aTokenAddress).totalSupply(),\n      IERC20Detailed(reserve.stableDebtTokenAddress).totalSupply(),\n      IERC20Detailed(reserve.variableDebtTokenAddress).totalSupply(),\n      reserve.currentLiquidityRate,\n      reserve.currentVariableBorrowRate,\n      reserve.currentStableBorrowRate,\n      IStableDebtToken(reserve.stableDebtTokenAddress).getAverageStableRate(),\n      reserve.liquidityIndex,\n      reserve.variableBorrowIndex,\n      reserve.lastUpdateTimestamp\n    );\n  }\n\n  /// @inheritdoc IPoolDataProvider\n  function getATokenTotalSupply(address asset) external view override returns (uint256) {\n    DataTypes.ReserveData memory reserve = IPool(ADDRESSES_PROVIDER.getPool()).getReserveData(\n      asset\n    );\n    return IERC20Detailed(reserve.aTokenAddress).totalSupply();\n  }\n\n  /// @inheritdoc IPoolDataProvider\n  function getTotalDebt(address asset) external view override returns (uint256) {\n    DataTypes.ReserveData memory reserve = IPool(ADDRESSES_PROVIDER.getPool()).getReserveData(\n      asset\n    );\n    return\n      IERC20Detailed(reserve.stableDebtTokenAddress).totalSupply() +\n      IERC20Detailed(reserve.variableDebtTokenAddress).totalSupply();\n  }\n\n  /// @inheritdoc IPoolDataProvider\n  function getUserReserveData(\n    address asset,\n    address user\n  )\n    external\n    view\n    override\n    returns (\n      uint256 currentATokenBalance,\n      uint256 currentStableDebt,\n      uint256 currentVariableDebt,\n      uint256 principalStableDebt,\n      uint256 scaledVariableDebt,\n      uint256 stableBorrowRate,\n      uint256 liquidityRate,\n      uint40 stableRateLastUpdated,\n      bool usageAsCollateralEnabled\n    )\n  {\n    DataTypes.ReserveData memory reserve = IPool(ADDRESSES_PROVIDER.getPool()).getReserveData(\n      asset\n    );\n\n    DataTypes.UserConfigurationMap memory userConfig = IPool(ADDRESSES_PROVIDER.getPool())\n      .getUserConfiguration(user);\n\n    currentATokenBalance = IERC20Detailed(reserve.aTokenAddress).balanceOf(user);\n    currentVariableDebt = IERC20Detailed(reserve.variableDebtTokenAddress).balanceOf(user);\n    currentStableDebt = IERC20Detailed(reserve.stableDebtTokenAddress).balanceOf(user);\n    principalStableDebt = IStableDebtToken(reserve.stableDebtTokenAddress).principalBalanceOf(user);\n    scaledVariableDebt = IVariableDebtToken(reserve.variableDebtTokenAddress).scaledBalanceOf(user);\n    liquidityRate = reserve.currentLiquidityRate;\n    stableBorrowRate = IStableDebtToken(reserve.stableDebtTokenAddress).getUserStableRate(user);\n    stableRateLastUpdated = IStableDebtToken(reserve.stableDebtTokenAddress).getUserLastUpdated(\n      user\n    );\n    usageAsCollateralEnabled = userConfig.isUsingAsCollateral(reserve.id);\n  }\n\n  /// @inheritdoc IPoolDataProvider\n  function getReserveTokensAddresses(\n    address asset\n  )\n    external\n    view\n    override\n    returns (\n      address aTokenAddress,\n      address stableDebtTokenAddress,\n      address variableDebtTokenAddress\n    )\n  {\n    DataTypes.ReserveData memory reserve = IPool(ADDRESSES_PROVIDER.getPool()).getReserveData(\n      asset\n    );\n\n    return (\n      reserve.aTokenAddress,\n      reserve.stableDebtTokenAddress,\n      reserve.variableDebtTokenAddress\n    );\n  }\n\n  /// @inheritdoc IPoolDataProvider\n  function getInterestRateStrategyAddress(\n    address asset\n  ) external view override returns (address irStrategyAddress) {\n    DataTypes.ReserveData memory reserve = IPool(ADDRESSES_PROVIDER.getPool()).getReserveData(\n      asset\n    );\n\n    return (reserve.interestRateStrategyAddress);\n  }\n\n  /// @inheritdoc IPoolDataProvider\n  function getFlashLoanEnabled(address asset) external view override returns (bool) {\n    DataTypes.ReserveConfigurationMap memory configuration = IPool(ADDRESSES_PROVIDER.getPool())\n      .getConfiguration(asset);\n\n    return configuration.getFlashLoanEnabled();\n  }\n}\n"
      },
      "src/core/contracts/misc/L2Encoder.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport {SafeCast} from '../dependencies/openzeppelin/contracts/SafeCast.sol';\nimport {IPool} from '../interfaces/IPool.sol';\nimport {DataTypes} from '../protocol/libraries/types/DataTypes.sol';\n\n/**\n * @title L2Encoder\n * @author Aave\n * @notice Helper contract to encode calldata, used to optimize calldata size in L2Pool for transaction cost reduction\n * only indented to help generate calldata for uses/frontends.\n */\ncontract L2Encoder {\n  using SafeCast for uint256;\n  IPool public immutable POOL;\n\n  /**\n   * @dev Constructor.\n   * @param pool The address of the Pool contract\n   */\n  constructor(IPool pool) {\n    POOL = pool;\n  }\n\n  /**\n   * @notice Encodes supply parameters from standard input to compact representation of 1 bytes32\n   * @dev Without an onBehalfOf parameter as the compact calls to L2Pool will use msg.sender as onBehalfOf\n   * @param asset The address of the underlying asset to supply\n   * @param amount The amount to be supplied\n   * @param referralCode referralCode Code used to register the integrator originating the operation, for potential rewards.\n   *   0 if the action is executed directly by the user, without any middle-man\n   * @return compact representation of supply parameters\n   */\n  function encodeSupplyParams(\n    address asset,\n    uint256 amount,\n    uint16 referralCode\n  ) external view returns (bytes32) {\n    DataTypes.ReserveData memory data = POOL.getReserveData(asset);\n\n    uint16 assetId = data.id;\n    uint128 shortenedAmount = amount.toUint128();\n    bytes32 res;\n\n    assembly {\n      res := add(assetId, add(shl(16, shortenedAmount), shl(144, referralCode)))\n    }\n    return res;\n  }\n\n  /**\n   * @notice Encodes supplyWithPermit parameters from standard input to compact representation of 3 bytes32\n   * @dev Without an onBehalfOf parameter as the compact calls to L2Pool will use msg.sender as onBehalfOf\n   * @param asset The address of the underlying asset to supply\n   * @param amount The amount to be supplied\n   * @param referralCode referralCode Code used to register the integrator originating the operation, for potential rewards.\n   *   0 if the action is executed directly by the user, without any middle-man\n   * @param deadline The deadline timestamp that the permit is valid\n   * @param permitV The V parameter of ERC712 permit sig\n   * @param permitR The R parameter of ERC712 permit sig\n   * @param permitS The S parameter of ERC712 permit sig\n   * @return compact representation of supplyWithPermit parameters\n   * @return The R parameter of ERC712 permit sig\n   * @return The S parameter of ERC712 permit sig\n   */\n  function encodeSupplyWithPermitParams(\n    address asset,\n    uint256 amount,\n    uint16 referralCode,\n    uint256 deadline,\n    uint8 permitV,\n    bytes32 permitR,\n    bytes32 permitS\n  ) external view returns (bytes32, bytes32, bytes32) {\n    DataTypes.ReserveData memory data = POOL.getReserveData(asset);\n\n    uint16 assetId = data.id;\n    uint128 shortenedAmount = amount.toUint128();\n    uint32 shortenedDeadline = deadline.toUint32();\n\n    bytes32 res;\n    assembly {\n      res := add(\n        assetId,\n        add(\n          shl(16, shortenedAmount),\n          add(shl(144, referralCode), add(shl(160, shortenedDeadline), shl(192, permitV)))\n        )\n      )\n    }\n\n    return (res, permitR, permitS);\n  }\n\n  /**\n   * @notice Encodes withdraw parameters from standard input to compact representation of 1 bytes32\n   * @dev Without a to parameter as the compact calls to L2Pool will use msg.sender as to\n   * @param asset The address of the underlying asset to withdraw\n   * @param amount The underlying amount to be withdrawn\n   * @return compact representation of withdraw parameters\n   */\n  function encodeWithdrawParams(address asset, uint256 amount) external view returns (bytes32) {\n    DataTypes.ReserveData memory data = POOL.getReserveData(asset);\n\n    uint16 assetId = data.id;\n    uint128 shortenedAmount = amount == type(uint256).max ? type(uint128).max : amount.toUint128();\n\n    bytes32 res;\n    assembly {\n      res := add(assetId, shl(16, shortenedAmount))\n    }\n    return res;\n  }\n\n  /**\n   * @notice Encodes borrow parameters from standard input to compact representation of 1 bytes32\n   * @dev Without an onBehalfOf parameter as the compact calls to L2Pool will use msg.sender as onBehalfOf\n   * @param asset The address of the underlying asset to borrow\n   * @param amount The amount to be borrowed\n   * @param interestRateMode The interest rate mode at which the user wants to borrow: 1 for Stable, 2 for Variable\n   * @param referralCode The code used to register the integrator originating the operation, for potential rewards.\n   *   0 if the action is executed directly by the user, without any middle-man\n   * @return compact representation of withdraw parameters\n   */\n  function encodeBorrowParams(\n    address asset,\n    uint256 amount,\n    uint256 interestRateMode,\n    uint16 referralCode\n  ) external view returns (bytes32) {\n    DataTypes.ReserveData memory data = POOL.getReserveData(asset);\n\n    uint16 assetId = data.id;\n    uint128 shortenedAmount = amount.toUint128();\n    uint8 shortenedInterestRateMode = interestRateMode.toUint8();\n    bytes32 res;\n    assembly {\n      res := add(\n        assetId,\n        add(\n          shl(16, shortenedAmount),\n          add(shl(144, shortenedInterestRateMode), shl(152, referralCode))\n        )\n      )\n    }\n    return res;\n  }\n\n  /**\n   * @notice Encodes repay parameters from standard input to compact representation of 1 bytes32\n   * @dev Without an onBehalfOf parameter as the compact calls to L2Pool will use msg.sender as onBehalfOf\n   * @param asset The address of the borrowed underlying asset previously borrowed\n   * @param amount The amount to repay\n   * - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `interestRateMode`\n   * @param interestRateMode The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable\n   * @return compact representation of repay parameters\n   */\n  function encodeRepayParams(\n    address asset,\n    uint256 amount,\n    uint256 interestRateMode\n  ) public view returns (bytes32) {\n    DataTypes.ReserveData memory data = POOL.getReserveData(asset);\n\n    uint16 assetId = data.id;\n    uint128 shortenedAmount = amount == type(uint256).max ? type(uint128).max : amount.toUint128();\n    uint8 shortenedInterestRateMode = interestRateMode.toUint8();\n\n    bytes32 res;\n    assembly {\n      res := add(assetId, add(shl(16, shortenedAmount), shl(144, shortenedInterestRateMode)))\n    }\n    return res;\n  }\n\n  /**\n   * @notice Encodes repayWithPermit parameters from standard input to compact representation of 3 bytes32\n   * @dev Without an onBehalfOf parameter as the compact calls to L2Pool will use msg.sender as onBehalfOf\n   * @param asset The address of the borrowed underlying asset previously borrowed\n   * @param amount The amount to repay\n   * - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode`\n   * @param interestRateMode The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable\n   * @param deadline The deadline timestamp that the permit is valid\n   * @param permitV The V parameter of ERC712 permit sig\n   * @param permitR The R parameter of ERC712 permit sig\n   * @param permitS The S parameter of ERC712 permit sig\n   * @return compact representation of repayWithPermit parameters\n   * @return The R parameter of ERC712 permit sig\n   * @return The S parameter of ERC712 permit sig\n   */\n  function encodeRepayWithPermitParams(\n    address asset,\n    uint256 amount,\n    uint256 interestRateMode,\n    uint256 deadline,\n    uint8 permitV,\n    bytes32 permitR,\n    bytes32 permitS\n  ) external view returns (bytes32, bytes32, bytes32) {\n    DataTypes.ReserveData memory data = POOL.getReserveData(asset);\n\n    uint16 assetId = data.id;\n    uint128 shortenedAmount = amount == type(uint256).max ? type(uint128).max : amount.toUint128();\n    uint8 shortenedInterestRateMode = interestRateMode.toUint8();\n    uint32 shortenedDeadline = deadline.toUint32();\n\n    bytes32 res;\n    assembly {\n      res := add(\n        assetId,\n        add(\n          shl(16, shortenedAmount),\n          add(\n            shl(144, shortenedInterestRateMode),\n            add(shl(152, shortenedDeadline), shl(184, permitV))\n          )\n        )\n      )\n    }\n    return (res, permitR, permitS);\n  }\n\n  /**\n   * @notice Encodes repay with aToken parameters from standard input to compact representation of 1 bytes32\n   * @param asset The address of the borrowed underlying asset previously borrowed\n   * @param amount The amount to repay\n   * - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode`\n   * @param interestRateMode The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable\n   * @return compact representation of repay with aToken parameters\n   */\n  function encodeRepayWithATokensParams(\n    address asset,\n    uint256 amount,\n    uint256 interestRateMode\n  ) external view returns (bytes32) {\n    return encodeRepayParams(asset, amount, interestRateMode);\n  }\n\n  /**\n   * @notice Encodes swap borrow rate mode parameters from standard input to compact representation of 1 bytes32\n   * @param asset The address of the underlying asset borrowed\n   * @param interestRateMode The current interest rate mode of the position being swapped: 1 for Stable, 2 for Variable\n   * @return compact representation of swap borrow rate mode parameters\n   */\n  function encodeSwapBorrowRateMode(\n    address asset,\n    uint256 interestRateMode\n  ) external view returns (bytes32) {\n    DataTypes.ReserveData memory data = POOL.getReserveData(asset);\n    uint16 assetId = data.id;\n    uint8 shortenedInterestRateMode = interestRateMode.toUint8();\n    bytes32 res;\n    assembly {\n      res := add(assetId, shl(16, shortenedInterestRateMode))\n    }\n    return res;\n  }\n\n  /**\n   * @notice Encodes rebalance stable borrow rate parameters from standard input to compact representation of 1 bytes32\n   * @param asset The address of the underlying asset borrowed\n   * @param user The address of the user to be rebalanced\n   * @return compact representation of rebalance stable borrow rate parameters\n   */\n  function encodeRebalanceStableBorrowRate(\n    address asset,\n    address user\n  ) external view returns (bytes32) {\n    DataTypes.ReserveData memory data = POOL.getReserveData(asset);\n    uint16 assetId = data.id;\n\n    bytes32 res;\n    assembly {\n      res := add(assetId, shl(16, user))\n    }\n    return res;\n  }\n\n  /**\n   * @notice Encodes set user use reserve as collateral parameters from standard input to compact representation of 1 bytes32\n   * @param asset The address of the underlying asset borrowed\n   * @param useAsCollateral True if the user wants to use the supply as collateral, false otherwise\n   * @return compact representation of set user use reserve as collateral parameters\n   */\n  function encodeSetUserUseReserveAsCollateral(\n    address asset,\n    bool useAsCollateral\n  ) external view returns (bytes32) {\n    DataTypes.ReserveData memory data = POOL.getReserveData(asset);\n    uint16 assetId = data.id;\n    bytes32 res;\n    assembly {\n      res := add(assetId, shl(16, useAsCollateral))\n    }\n    return res;\n  }\n\n  /**\n   * @notice Encodes liquidation call parameters from standard input to compact representation of 2 bytes32\n   * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation\n   * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation\n   * @param user The address of the borrower getting liquidated\n   * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover\n   * @param receiveAToken True if the liquidators wants to receive the collateral aTokens, `false` if he wants\n   * to receive the underlying collateral asset directly\n   * @return First half ot compact representation of liquidation call parameters\n   * @return Second half ot compact representation of liquidation call parameters\n   */\n  function encodeLiquidationCall(\n    address collateralAsset,\n    address debtAsset,\n    address user,\n    uint256 debtToCover,\n    bool receiveAToken\n  ) external view returns (bytes32, bytes32) {\n    DataTypes.ReserveData memory collateralData = POOL.getReserveData(collateralAsset);\n    uint16 collateralAssetId = collateralData.id;\n\n    DataTypes.ReserveData memory debtData = POOL.getReserveData(debtAsset);\n    uint16 debtAssetId = debtData.id;\n\n    uint128 shortenedDebtToCover = debtToCover == type(uint256).max\n      ? type(uint128).max\n      : debtToCover.toUint128();\n\n    bytes32 res1;\n    bytes32 res2;\n\n    assembly {\n      res1 := add(add(collateralAssetId, shl(16, debtAssetId)), shl(32, user))\n      res2 := add(shortenedDebtToCover, shl(128, receiveAToken))\n    }\n    return (res1, res2);\n  }\n}\n"
      },
      "src/core/contracts/protocol/libraries/aave-upgradeability/BaseImmutableAdminUpgradeabilityProxy.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport {BaseUpgradeabilityProxy} from '../../../dependencies/openzeppelin/upgradeability/BaseUpgradeabilityProxy.sol';\n\n/**\n * @title BaseImmutableAdminUpgradeabilityProxy\n * @author Aave, inspired by the OpenZeppelin upgradeability proxy pattern\n * @notice This contract combines an upgradeability proxy with an authorization\n * mechanism for administrative tasks.\n * @dev The admin role is stored in an immutable, which helps saving transactions costs\n * All external functions in this contract must be guarded by the\n * `ifAdmin` modifier. See ethereum/solidity#3864 for a Solidity\n * feature proposal that would enable this to be done automatically.\n */\ncontract BaseImmutableAdminUpgradeabilityProxy is BaseUpgradeabilityProxy {\n  address internal immutable _admin;\n\n  /**\n   * @dev Constructor.\n   * @param admin The address of the admin\n   */\n  constructor(address admin) {\n    _admin = admin;\n  }\n\n  modifier ifAdmin() {\n    if (msg.sender == _admin) {\n      _;\n    } else {\n      _fallback();\n    }\n  }\n\n  /**\n   * @notice Return the admin address\n   * @return The address of the proxy admin.\n   */\n  function admin() external ifAdmin returns (address) {\n    return _admin;\n  }\n\n  /**\n   * @notice Return the implementation address\n   * @return The address of the implementation.\n   */\n  function implementation() external ifAdmin returns (address) {\n    return _implementation();\n  }\n\n  /**\n   * @notice Upgrade the backing implementation of the proxy.\n   * @dev Only the admin can call this function.\n   * @param newImplementation The address of the new implementation.\n   */\n  function upgradeTo(address newImplementation) external ifAdmin {\n    _upgradeTo(newImplementation);\n  }\n\n  /**\n   * @notice Upgrade the backing implementation of the proxy and call a function\n   * on the new implementation.\n   * @dev This is useful to initialize the proxied contract.\n   * @param newImplementation The address of the new implementation.\n   * @param data Data to send as msg.data in the low level call.\n   * It should include the signature and the parameters of the function to be called, as described in\n   * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.\n   */\n  function upgradeToAndCall(\n    address newImplementation,\n    bytes calldata data\n  ) external payable ifAdmin {\n    _upgradeTo(newImplementation);\n    (bool success, ) = newImplementation.delegatecall(data);\n    require(success);\n  }\n\n  /**\n   * @notice Only fall back when the sender is not the admin.\n   */\n  function _willFallback() internal virtual override {\n    require(msg.sender != _admin, 'Cannot call fallback function from the proxy admin');\n    super._willFallback();\n  }\n}\n"
      },
      "src/core/contracts/protocol/libraries/aave-upgradeability/InitializableImmutableAdminUpgradeabilityProxy.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport {InitializableUpgradeabilityProxy} from '../../../dependencies/openzeppelin/upgradeability/InitializableUpgradeabilityProxy.sol';\nimport {Proxy} from '../../../dependencies/openzeppelin/upgradeability/Proxy.sol';\nimport {BaseImmutableAdminUpgradeabilityProxy} from './BaseImmutableAdminUpgradeabilityProxy.sol';\n\n/**\n * @title InitializableAdminUpgradeabilityProxy\n * @author Aave\n * @dev Extends BaseAdminUpgradeabilityProxy with an initializer function\n */\ncontract InitializableImmutableAdminUpgradeabilityProxy is\n  BaseImmutableAdminUpgradeabilityProxy,\n  InitializableUpgradeabilityProxy\n{\n  /**\n   * @dev Constructor.\n   * @param admin The address of the admin\n   */\n  constructor(address admin) BaseImmutableAdminUpgradeabilityProxy(admin) {\n    // Intentionally left blank\n  }\n\n  /// @inheritdoc BaseImmutableAdminUpgradeabilityProxy\n  function _willFallback() internal override(BaseImmutableAdminUpgradeabilityProxy, Proxy) {\n    BaseImmutableAdminUpgradeabilityProxy._willFallback();\n  }\n}\n"
      },
      "src/core/contracts/protocol/libraries/configuration/ReserveConfiguration.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {Errors} from '../helpers/Errors.sol';\nimport {DataTypes} from '../types/DataTypes.sol';\n\n/**\n * @title ReserveConfiguration library\n * @author Aave\n * @notice Implements the bitmap logic to handle the reserve configuration\n */\nlibrary ReserveConfiguration {\n  uint256 internal constant LTV_MASK =                       0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000; // prettier-ignore\n  uint256 internal constant LIQUIDATION_THRESHOLD_MASK =     0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000FFFF; // prettier-ignore\n  uint256 internal constant LIQUIDATION_BONUS_MASK =         0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000FFFFFFFF; // prettier-ignore\n  uint256 internal constant DECIMALS_MASK =                  0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00FFFFFFFFFFFF; // prettier-ignore\n  uint256 internal constant ACTIVE_MASK =                    0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFF; // prettier-ignore\n  uint256 internal constant FROZEN_MASK =                    0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFDFFFFFFFFFFFFFF; // prettier-ignore\n  uint256 internal constant BORROWING_MASK =                 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFBFFFFFFFFFFFFFF; // prettier-ignore\n  uint256 internal constant STABLE_BORROWING_MASK =          0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFFFFFFFFF; // prettier-ignore\n  uint256 internal constant PAUSED_MASK =                    0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFF; // prettier-ignore\n  uint256 internal constant BORROWABLE_IN_ISOLATION_MASK =   0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFDFFFFFFFFFFFFFFF; // prettier-ignore\n  uint256 internal constant SILOED_BORROWING_MASK =          0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFBFFFFFFFFFFFFFFF; // prettier-ignore\n  uint256 internal constant FLASHLOAN_ENABLED_MASK =         0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFFFFFFFFFF; // prettier-ignore\n  uint256 internal constant RESERVE_FACTOR_MASK =            0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000FFFFFFFFFFFFFFFF; // prettier-ignore\n  uint256 internal constant BORROW_CAP_MASK =                0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF000000000FFFFFFFFFFFFFFFFFFFF; // prettier-ignore\n  uint256 internal constant SUPPLY_CAP_MASK =                0xFFFFFFFFFFFFFFFFFFFFFFFFFF000000000FFFFFFFFFFFFFFFFFFFFFFFFFFFFF; // prettier-ignore\n  uint256 internal constant LIQUIDATION_PROTOCOL_FEE_MASK =  0xFFFFFFFFFFFFFFFFFFFFFF0000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; // prettier-ignore\n  uint256 internal constant EMODE_CATEGORY_MASK =            0xFFFFFFFFFFFFFFFFFFFF00FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; // prettier-ignore\n  uint256 internal constant UNBACKED_MINT_CAP_MASK =         0xFFFFFFFFFFF000000000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; // prettier-ignore\n  uint256 internal constant DEBT_CEILING_MASK =              0xF0000000000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; // prettier-ignore\n\n  /// @dev For the LTV, the start bit is 0 (up to 15), hence no bitshifting is needed\n  uint256 internal constant LIQUIDATION_THRESHOLD_START_BIT_POSITION = 16;\n  uint256 internal constant LIQUIDATION_BONUS_START_BIT_POSITION = 32;\n  uint256 internal constant RESERVE_DECIMALS_START_BIT_POSITION = 48;\n  uint256 internal constant IS_ACTIVE_START_BIT_POSITION = 56;\n  uint256 internal constant IS_FROZEN_START_BIT_POSITION = 57;\n  uint256 internal constant BORROWING_ENABLED_START_BIT_POSITION = 58;\n  uint256 internal constant STABLE_BORROWING_ENABLED_START_BIT_POSITION = 59;\n  uint256 internal constant IS_PAUSED_START_BIT_POSITION = 60;\n  uint256 internal constant BORROWABLE_IN_ISOLATION_START_BIT_POSITION = 61;\n  uint256 internal constant SILOED_BORROWING_START_BIT_POSITION = 62;\n  uint256 internal constant FLASHLOAN_ENABLED_START_BIT_POSITION = 63;\n  uint256 internal constant RESERVE_FACTOR_START_BIT_POSITION = 64;\n  uint256 internal constant BORROW_CAP_START_BIT_POSITION = 80;\n  uint256 internal constant SUPPLY_CAP_START_BIT_POSITION = 116;\n  uint256 internal constant LIQUIDATION_PROTOCOL_FEE_START_BIT_POSITION = 152;\n  uint256 internal constant EMODE_CATEGORY_START_BIT_POSITION = 168;\n  uint256 internal constant UNBACKED_MINT_CAP_START_BIT_POSITION = 176;\n  uint256 internal constant DEBT_CEILING_START_BIT_POSITION = 212;\n\n  uint256 internal constant MAX_VALID_LTV = 65535;\n  uint256 internal constant MAX_VALID_LIQUIDATION_THRESHOLD = 65535;\n  uint256 internal constant MAX_VALID_LIQUIDATION_BONUS = 65535;\n  uint256 internal constant MAX_VALID_DECIMALS = 255;\n  uint256 internal constant MAX_VALID_RESERVE_FACTOR = 65535;\n  uint256 internal constant MAX_VALID_BORROW_CAP = 68719476735;\n  uint256 internal constant MAX_VALID_SUPPLY_CAP = 68719476735;\n  uint256 internal constant MAX_VALID_LIQUIDATION_PROTOCOL_FEE = 65535;\n  uint256 internal constant MAX_VALID_EMODE_CATEGORY = 255;\n  uint256 internal constant MAX_VALID_UNBACKED_MINT_CAP = 68719476735;\n  uint256 internal constant MAX_VALID_DEBT_CEILING = 1099511627775;\n\n  uint256 public constant DEBT_CEILING_DECIMALS = 2;\n  uint16 public constant MAX_RESERVES_COUNT = 128;\n\n  /**\n   * @notice Sets the Loan to Value of the reserve\n   * @param self The reserve configuration\n   * @param ltv The new ltv\n   */\n  function setLtv(DataTypes.ReserveConfigurationMap memory self, uint256 ltv) internal pure {\n    require(ltv <= MAX_VALID_LTV, Errors.INVALID_LTV);\n\n    self.data = (self.data & LTV_MASK) | ltv;\n  }\n\n  /**\n   * @notice Gets the Loan to Value of the reserve\n   * @param self The reserve configuration\n   * @return The loan to value\n   */\n  function getLtv(DataTypes.ReserveConfigurationMap memory self) internal pure returns (uint256) {\n    return self.data & ~LTV_MASK;\n  }\n\n  /**\n   * @notice Sets the liquidation threshold of the reserve\n   * @param self The reserve configuration\n   * @param threshold The new liquidation threshold\n   */\n  function setLiquidationThreshold(\n    DataTypes.ReserveConfigurationMap memory self,\n    uint256 threshold\n  ) internal pure {\n    require(threshold <= MAX_VALID_LIQUIDATION_THRESHOLD, Errors.INVALID_LIQ_THRESHOLD);\n\n    self.data =\n      (self.data & LIQUIDATION_THRESHOLD_MASK) |\n      (threshold << LIQUIDATION_THRESHOLD_START_BIT_POSITION);\n  }\n\n  /**\n   * @notice Gets the liquidation threshold of the reserve\n   * @param self The reserve configuration\n   * @return The liquidation threshold\n   */\n  function getLiquidationThreshold(\n    DataTypes.ReserveConfigurationMap memory self\n  ) internal pure returns (uint256) {\n    return (self.data & ~LIQUIDATION_THRESHOLD_MASK) >> LIQUIDATION_THRESHOLD_START_BIT_POSITION;\n  }\n\n  /**\n   * @notice Sets the liquidation bonus of the reserve\n   * @param self The reserve configuration\n   * @param bonus The new liquidation bonus\n   */\n  function setLiquidationBonus(\n    DataTypes.ReserveConfigurationMap memory self,\n    uint256 bonus\n  ) internal pure {\n    require(bonus <= MAX_VALID_LIQUIDATION_BONUS, Errors.INVALID_LIQ_BONUS);\n\n    self.data =\n      (self.data & LIQUIDATION_BONUS_MASK) |\n      (bonus << LIQUIDATION_BONUS_START_BIT_POSITION);\n  }\n\n  /**\n   * @notice Gets the liquidation bonus of the reserve\n   * @param self The reserve configuration\n   * @return The liquidation bonus\n   */\n  function getLiquidationBonus(\n    DataTypes.ReserveConfigurationMap memory self\n  ) internal pure returns (uint256) {\n    return (self.data & ~LIQUIDATION_BONUS_MASK) >> LIQUIDATION_BONUS_START_BIT_POSITION;\n  }\n\n  /**\n   * @notice Sets the decimals of the underlying asset of the reserve\n   * @param self The reserve configuration\n   * @param decimals The decimals\n   */\n  function setDecimals(\n    DataTypes.ReserveConfigurationMap memory self,\n    uint256 decimals\n  ) internal pure {\n    require(decimals <= MAX_VALID_DECIMALS, Errors.INVALID_DECIMALS);\n\n    self.data = (self.data & DECIMALS_MASK) | (decimals << RESERVE_DECIMALS_START_BIT_POSITION);\n  }\n\n  /**\n   * @notice Gets the decimals of the underlying asset of the reserve\n   * @param self The reserve configuration\n   * @return The decimals of the asset\n   */\n  function getDecimals(\n    DataTypes.ReserveConfigurationMap memory self\n  ) internal pure returns (uint256) {\n    return (self.data & ~DECIMALS_MASK) >> RESERVE_DECIMALS_START_BIT_POSITION;\n  }\n\n  /**\n   * @notice Sets the active state of the reserve\n   * @param self The reserve configuration\n   * @param active The active state\n   */\n  function setActive(DataTypes.ReserveConfigurationMap memory self, bool active) internal pure {\n    self.data =\n      (self.data & ACTIVE_MASK) |\n      (uint256(active ? 1 : 0) << IS_ACTIVE_START_BIT_POSITION);\n  }\n\n  /**\n   * @notice Gets the active state of the reserve\n   * @param self The reserve configuration\n   * @return The active state\n   */\n  function getActive(DataTypes.ReserveConfigurationMap memory self) internal pure returns (bool) {\n    return (self.data & ~ACTIVE_MASK) != 0;\n  }\n\n  /**\n   * @notice Sets the frozen state of the reserve\n   * @param self The reserve configuration\n   * @param frozen The frozen state\n   */\n  function setFrozen(DataTypes.ReserveConfigurationMap memory self, bool frozen) internal pure {\n    self.data =\n      (self.data & FROZEN_MASK) |\n      (uint256(frozen ? 1 : 0) << IS_FROZEN_START_BIT_POSITION);\n  }\n\n  /**\n   * @notice Gets the frozen state of the reserve\n   * @param self The reserve configuration\n   * @return The frozen state\n   */\n  function getFrozen(DataTypes.ReserveConfigurationMap memory self) internal pure returns (bool) {\n    return (self.data & ~FROZEN_MASK) != 0;\n  }\n\n  /**\n   * @notice Sets the paused state of the reserve\n   * @param self The reserve configuration\n   * @param paused The paused state\n   */\n  function setPaused(DataTypes.ReserveConfigurationMap memory self, bool paused) internal pure {\n    self.data =\n      (self.data & PAUSED_MASK) |\n      (uint256(paused ? 1 : 0) << IS_PAUSED_START_BIT_POSITION);\n  }\n\n  /**\n   * @notice Gets the paused state of the reserve\n   * @param self The reserve configuration\n   * @return The paused state\n   */\n  function getPaused(DataTypes.ReserveConfigurationMap memory self) internal pure returns (bool) {\n    return (self.data & ~PAUSED_MASK) != 0;\n  }\n\n  /**\n   * @notice Sets the borrowable in isolation flag for the reserve.\n   * @dev When this flag is set to true, the asset will be borrowable against isolated collaterals and the borrowed\n   * amount will be accumulated in the isolated collateral's total debt exposure.\n   * @dev Only assets of the same family (eg USD stablecoins) should be borrowable in isolation mode to keep\n   * consistency in the debt ceiling calculations.\n   * @param self The reserve configuration\n   * @param borrowable True if the asset is borrowable\n   */\n  function setBorrowableInIsolation(\n    DataTypes.ReserveConfigurationMap memory self,\n    bool borrowable\n  ) internal pure {\n    self.data =\n      (self.data & BORROWABLE_IN_ISOLATION_MASK) |\n      (uint256(borrowable ? 1 : 0) << BORROWABLE_IN_ISOLATION_START_BIT_POSITION);\n  }\n\n  /**\n   * @notice Gets the borrowable in isolation flag for the reserve.\n   * @dev If the returned flag is true, the asset is borrowable against isolated collateral. Assets borrowed with\n   * isolated collateral is accounted for in the isolated collateral's total debt exposure.\n   * @dev Only assets of the same family (eg USD stablecoins) should be borrowable in isolation mode to keep\n   * consistency in the debt ceiling calculations.\n   * @param self The reserve configuration\n   * @return The borrowable in isolation flag\n   */\n  function getBorrowableInIsolation(\n    DataTypes.ReserveConfigurationMap memory self\n  ) internal pure returns (bool) {\n    return (self.data & ~BORROWABLE_IN_ISOLATION_MASK) != 0;\n  }\n\n  /**\n   * @notice Sets the siloed borrowing flag for the reserve.\n   * @dev When this flag is set to true, users borrowing this asset will not be allowed to borrow any other asset.\n   * @param self The reserve configuration\n   * @param siloed True if the asset is siloed\n   */\n  function setSiloedBorrowing(\n    DataTypes.ReserveConfigurationMap memory self,\n    bool siloed\n  ) internal pure {\n    self.data =\n      (self.data & SILOED_BORROWING_MASK) |\n      (uint256(siloed ? 1 : 0) << SILOED_BORROWING_START_BIT_POSITION);\n  }\n\n  /**\n   * @notice Gets the siloed borrowing flag for the reserve.\n   * @dev When this flag is set to true, users borrowing this asset will not be allowed to borrow any other asset.\n   * @param self The reserve configuration\n   * @return The siloed borrowing flag\n   */\n  function getSiloedBorrowing(\n    DataTypes.ReserveConfigurationMap memory self\n  ) internal pure returns (bool) {\n    return (self.data & ~SILOED_BORROWING_MASK) != 0;\n  }\n\n  /**\n   * @notice Enables or disables borrowing on the reserve\n   * @param self The reserve configuration\n   * @param enabled True if the borrowing needs to be enabled, false otherwise\n   */\n  function setBorrowingEnabled(\n    DataTypes.ReserveConfigurationMap memory self,\n    bool enabled\n  ) internal pure {\n    self.data =\n      (self.data & BORROWING_MASK) |\n      (uint256(enabled ? 1 : 0) << BORROWING_ENABLED_START_BIT_POSITION);\n  }\n\n  /**\n   * @notice Gets the borrowing state of the reserve\n   * @param self The reserve configuration\n   * @return The borrowing state\n   */\n  function getBorrowingEnabled(\n    DataTypes.ReserveConfigurationMap memory self\n  ) internal pure returns (bool) {\n    return (self.data & ~BORROWING_MASK) != 0;\n  }\n\n  /**\n   * @notice Enables or disables stable rate borrowing on the reserve\n   * @param self The reserve configuration\n   * @param enabled True if the stable rate borrowing needs to be enabled, false otherwise\n   */\n  function setStableRateBorrowingEnabled(\n    DataTypes.ReserveConfigurationMap memory self,\n    bool enabled\n  ) internal pure {\n    self.data =\n      (self.data & STABLE_BORROWING_MASK) |\n      (uint256(enabled ? 1 : 0) << STABLE_BORROWING_ENABLED_START_BIT_POSITION);\n  }\n\n  /**\n   * @notice Gets the stable rate borrowing state of the reserve\n   * @param self The reserve configuration\n   * @return The stable rate borrowing state\n   */\n  function getStableRateBorrowingEnabled(\n    DataTypes.ReserveConfigurationMap memory self\n  ) internal pure returns (bool) {\n    return (self.data & ~STABLE_BORROWING_MASK) != 0;\n  }\n\n  /**\n   * @notice Sets the reserve factor of the reserve\n   * @param self The reserve configuration\n   * @param reserveFactor The reserve factor\n   */\n  function setReserveFactor(\n    DataTypes.ReserveConfigurationMap memory self,\n    uint256 reserveFactor\n  ) internal pure {\n    require(reserveFactor <= MAX_VALID_RESERVE_FACTOR, Errors.INVALID_RESERVE_FACTOR);\n\n    self.data =\n      (self.data & RESERVE_FACTOR_MASK) |\n      (reserveFactor << RESERVE_FACTOR_START_BIT_POSITION);\n  }\n\n  /**\n   * @notice Gets the reserve factor of the reserve\n   * @param self The reserve configuration\n   * @return The reserve factor\n   */\n  function getReserveFactor(\n    DataTypes.ReserveConfigurationMap memory self\n  ) internal pure returns (uint256) {\n    return (self.data & ~RESERVE_FACTOR_MASK) >> RESERVE_FACTOR_START_BIT_POSITION;\n  }\n\n  /**\n   * @notice Sets the borrow cap of the reserve\n   * @param self The reserve configuration\n   * @param borrowCap The borrow cap\n   */\n  function setBorrowCap(\n    DataTypes.ReserveConfigurationMap memory self,\n    uint256 borrowCap\n  ) internal pure {\n    require(borrowCap <= MAX_VALID_BORROW_CAP, Errors.INVALID_BORROW_CAP);\n\n    self.data = (self.data & BORROW_CAP_MASK) | (borrowCap << BORROW_CAP_START_BIT_POSITION);\n  }\n\n  /**\n   * @notice Gets the borrow cap of the reserve\n   * @param self The reserve configuration\n   * @return The borrow cap\n   */\n  function getBorrowCap(\n    DataTypes.ReserveConfigurationMap memory self\n  ) internal pure returns (uint256) {\n    return (self.data & ~BORROW_CAP_MASK) >> BORROW_CAP_START_BIT_POSITION;\n  }\n\n  /**\n   * @notice Sets the supply cap of the reserve\n   * @param self The reserve configuration\n   * @param supplyCap The supply cap\n   */\n  function setSupplyCap(\n    DataTypes.ReserveConfigurationMap memory self,\n    uint256 supplyCap\n  ) internal pure {\n    require(supplyCap <= MAX_VALID_SUPPLY_CAP, Errors.INVALID_SUPPLY_CAP);\n\n    self.data = (self.data & SUPPLY_CAP_MASK) | (supplyCap << SUPPLY_CAP_START_BIT_POSITION);\n  }\n\n  /**\n   * @notice Gets the supply cap of the reserve\n   * @param self The reserve configuration\n   * @return The supply cap\n   */\n  function getSupplyCap(\n    DataTypes.ReserveConfigurationMap memory self\n  ) internal pure returns (uint256) {\n    return (self.data & ~SUPPLY_CAP_MASK) >> SUPPLY_CAP_START_BIT_POSITION;\n  }\n\n  /**\n   * @notice Sets the debt ceiling in isolation mode for the asset\n   * @param self The reserve configuration\n   * @param ceiling The maximum debt ceiling for the asset\n   */\n  function setDebtCeiling(\n    DataTypes.ReserveConfigurationMap memory self,\n    uint256 ceiling\n  ) internal pure {\n    require(ceiling <= MAX_VALID_DEBT_CEILING, Errors.INVALID_DEBT_CEILING);\n\n    self.data = (self.data & DEBT_CEILING_MASK) | (ceiling << DEBT_CEILING_START_BIT_POSITION);\n  }\n\n  /**\n   * @notice Gets the debt ceiling for the asset if the asset is in isolation mode\n   * @param self The reserve configuration\n   * @return The debt ceiling (0 = isolation mode disabled)\n   */\n  function getDebtCeiling(\n    DataTypes.ReserveConfigurationMap memory self\n  ) internal pure returns (uint256) {\n    return (self.data & ~DEBT_CEILING_MASK) >> DEBT_CEILING_START_BIT_POSITION;\n  }\n\n  /**\n   * @notice Sets the liquidation protocol fee of the reserve\n   * @param self The reserve configuration\n   * @param liquidationProtocolFee The liquidation protocol fee\n   */\n  function setLiquidationProtocolFee(\n    DataTypes.ReserveConfigurationMap memory self,\n    uint256 liquidationProtocolFee\n  ) internal pure {\n    require(\n      liquidationProtocolFee <= MAX_VALID_LIQUIDATION_PROTOCOL_FEE,\n      Errors.INVALID_LIQUIDATION_PROTOCOL_FEE\n    );\n\n    self.data =\n      (self.data & LIQUIDATION_PROTOCOL_FEE_MASK) |\n      (liquidationProtocolFee << LIQUIDATION_PROTOCOL_FEE_START_BIT_POSITION);\n  }\n\n  /**\n   * @dev Gets the liquidation protocol fee\n   * @param self The reserve configuration\n   * @return The liquidation protocol fee\n   */\n  function getLiquidationProtocolFee(\n    DataTypes.ReserveConfigurationMap memory self\n  ) internal pure returns (uint256) {\n    return\n      (self.data & ~LIQUIDATION_PROTOCOL_FEE_MASK) >> LIQUIDATION_PROTOCOL_FEE_START_BIT_POSITION;\n  }\n\n  /**\n   * @notice Sets the unbacked mint cap of the reserve\n   * @param self The reserve configuration\n   * @param unbackedMintCap The unbacked mint cap\n   */\n  function setUnbackedMintCap(\n    DataTypes.ReserveConfigurationMap memory self,\n    uint256 unbackedMintCap\n  ) internal pure {\n    require(unbackedMintCap <= MAX_VALID_UNBACKED_MINT_CAP, Errors.INVALID_UNBACKED_MINT_CAP);\n\n    self.data =\n      (self.data & UNBACKED_MINT_CAP_MASK) |\n      (unbackedMintCap << UNBACKED_MINT_CAP_START_BIT_POSITION);\n  }\n\n  /**\n   * @dev Gets the unbacked mint cap of the reserve\n   * @param self The reserve configuration\n   * @return The unbacked mint cap\n   */\n  function getUnbackedMintCap(\n    DataTypes.ReserveConfigurationMap memory self\n  ) internal pure returns (uint256) {\n    return (self.data & ~UNBACKED_MINT_CAP_MASK) >> UNBACKED_MINT_CAP_START_BIT_POSITION;\n  }\n\n  /**\n   * @notice Sets the eMode asset category\n   * @param self The reserve configuration\n   * @param category The asset category when the user selects the eMode\n   */\n  function setEModeCategory(\n    DataTypes.ReserveConfigurationMap memory self,\n    uint256 category\n  ) internal pure {\n    require(category <= MAX_VALID_EMODE_CATEGORY, Errors.INVALID_EMODE_CATEGORY);\n\n    self.data = (self.data & EMODE_CATEGORY_MASK) | (category << EMODE_CATEGORY_START_BIT_POSITION);\n  }\n\n  /**\n   * @dev Gets the eMode asset category\n   * @param self The reserve configuration\n   * @return The eMode category for the asset\n   */\n  function getEModeCategory(\n    DataTypes.ReserveConfigurationMap memory self\n  ) internal pure returns (uint256) {\n    return (self.data & ~EMODE_CATEGORY_MASK) >> EMODE_CATEGORY_START_BIT_POSITION;\n  }\n\n  /**\n   * @notice Sets the flashloanable flag for the reserve\n   * @param self The reserve configuration\n   * @param flashLoanEnabled True if the asset is flashloanable, false otherwise\n   */\n  function setFlashLoanEnabled(\n    DataTypes.ReserveConfigurationMap memory self,\n    bool flashLoanEnabled\n  ) internal pure {\n    self.data =\n      (self.data & FLASHLOAN_ENABLED_MASK) |\n      (uint256(flashLoanEnabled ? 1 : 0) << FLASHLOAN_ENABLED_START_BIT_POSITION);\n  }\n\n  /**\n   * @notice Gets the flashloanable flag for the reserve\n   * @param self The reserve configuration\n   * @return The flashloanable flag\n   */\n  function getFlashLoanEnabled(\n    DataTypes.ReserveConfigurationMap memory self\n  ) internal pure returns (bool) {\n    return (self.data & ~FLASHLOAN_ENABLED_MASK) != 0;\n  }\n\n  /**\n   * @notice Gets the configuration flags of the reserve\n   * @param self The reserve configuration\n   * @return The state flag representing active\n   * @return The state flag representing frozen\n   * @return The state flag representing borrowing enabled\n   * @return The state flag representing stableRateBorrowing enabled\n   * @return The state flag representing paused\n   */\n  function getFlags(\n    DataTypes.ReserveConfigurationMap memory self\n  ) internal pure returns (bool, bool, bool, bool, bool) {\n    uint256 dataLocal = self.data;\n\n    return (\n      (dataLocal & ~ACTIVE_MASK) != 0,\n      (dataLocal & ~FROZEN_MASK) != 0,\n      (dataLocal & ~BORROWING_MASK) != 0,\n      (dataLocal & ~STABLE_BORROWING_MASK) != 0,\n      (dataLocal & ~PAUSED_MASK) != 0\n    );\n  }\n\n  /**\n   * @notice Gets the configuration parameters of the reserve from storage\n   * @param self The reserve configuration\n   * @return The state param representing ltv\n   * @return The state param representing liquidation threshold\n   * @return The state param representing liquidation bonus\n   * @return The state param representing reserve decimals\n   * @return The state param representing reserve factor\n   * @return The state param representing eMode category\n   */\n  function getParams(\n    DataTypes.ReserveConfigurationMap memory self\n  ) internal pure returns (uint256, uint256, uint256, uint256, uint256, uint256) {\n    uint256 dataLocal = self.data;\n\n    return (\n      dataLocal & ~LTV_MASK,\n      (dataLocal & ~LIQUIDATION_THRESHOLD_MASK) >> LIQUIDATION_THRESHOLD_START_BIT_POSITION,\n      (dataLocal & ~LIQUIDATION_BONUS_MASK) >> LIQUIDATION_BONUS_START_BIT_POSITION,\n      (dataLocal & ~DECIMALS_MASK) >> RESERVE_DECIMALS_START_BIT_POSITION,\n      (dataLocal & ~RESERVE_FACTOR_MASK) >> RESERVE_FACTOR_START_BIT_POSITION,\n      (dataLocal & ~EMODE_CATEGORY_MASK) >> EMODE_CATEGORY_START_BIT_POSITION\n    );\n  }\n\n  /**\n   * @notice Gets the caps parameters of the reserve from storage\n   * @param self The reserve configuration\n   * @return The state param representing borrow cap\n   * @return The state param representing supply cap.\n   */\n  function getCaps(\n    DataTypes.ReserveConfigurationMap memory self\n  ) internal pure returns (uint256, uint256) {\n    uint256 dataLocal = self.data;\n\n    return (\n      (dataLocal & ~BORROW_CAP_MASK) >> BORROW_CAP_START_BIT_POSITION,\n      (dataLocal & ~SUPPLY_CAP_MASK) >> SUPPLY_CAP_START_BIT_POSITION\n    );\n  }\n}\n"
      },
      "src/core/contracts/protocol/libraries/configuration/UserConfiguration.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {Errors} from '../helpers/Errors.sol';\nimport {DataTypes} from '../types/DataTypes.sol';\nimport {ReserveConfiguration} from './ReserveConfiguration.sol';\n\n/**\n * @title UserConfiguration library\n * @author Aave\n * @notice Implements the bitmap logic to handle the user configuration\n */\nlibrary UserConfiguration {\n  using ReserveConfiguration for DataTypes.ReserveConfigurationMap;\n\n  uint256 internal constant BORROWING_MASK =\n    0x5555555555555555555555555555555555555555555555555555555555555555;\n  uint256 internal constant COLLATERAL_MASK =\n    0xAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA;\n\n  /**\n   * @notice Sets if the user is borrowing the reserve identified by reserveIndex\n   * @param self The configuration object\n   * @param reserveIndex The index of the reserve in the bitmap\n   * @param borrowing True if the user is borrowing the reserve, false otherwise\n   */\n  function setBorrowing(\n    DataTypes.UserConfigurationMap storage self,\n    uint256 reserveIndex,\n    bool borrowing\n  ) internal {\n    unchecked {\n      require(reserveIndex < ReserveConfiguration.MAX_RESERVES_COUNT, Errors.INVALID_RESERVE_INDEX);\n      uint256 bit = 1 << (reserveIndex << 1);\n      if (borrowing) {\n        self.data |= bit;\n      } else {\n        self.data &= ~bit;\n      }\n    }\n  }\n\n  /**\n   * @notice Sets if the user is using as collateral the reserve identified by reserveIndex\n   * @param self The configuration object\n   * @param reserveIndex The index of the reserve in the bitmap\n   * @param usingAsCollateral True if the user is using the reserve as collateral, false otherwise\n   */\n  function setUsingAsCollateral(\n    DataTypes.UserConfigurationMap storage self,\n    uint256 reserveIndex,\n    bool usingAsCollateral\n  ) internal {\n    unchecked {\n      require(reserveIndex < ReserveConfiguration.MAX_RESERVES_COUNT, Errors.INVALID_RESERVE_INDEX);\n      uint256 bit = 1 << ((reserveIndex << 1) + 1);\n      if (usingAsCollateral) {\n        self.data |= bit;\n      } else {\n        self.data &= ~bit;\n      }\n    }\n  }\n\n  /**\n   * @notice Returns if a user has been using the reserve for borrowing or as collateral\n   * @param self The configuration object\n   * @param reserveIndex The index of the reserve in the bitmap\n   * @return True if the user has been using a reserve for borrowing or as collateral, false otherwise\n   */\n  function isUsingAsCollateralOrBorrowing(\n    DataTypes.UserConfigurationMap memory self,\n    uint256 reserveIndex\n  ) internal pure returns (bool) {\n    unchecked {\n      require(reserveIndex < ReserveConfiguration.MAX_RESERVES_COUNT, Errors.INVALID_RESERVE_INDEX);\n      return (self.data >> (reserveIndex << 1)) & 3 != 0;\n    }\n  }\n\n  /**\n   * @notice Validate a user has been using the reserve for borrowing\n   * @param self The configuration object\n   * @param reserveIndex The index of the reserve in the bitmap\n   * @return True if the user has been using a reserve for borrowing, false otherwise\n   */\n  function isBorrowing(\n    DataTypes.UserConfigurationMap memory self,\n    uint256 reserveIndex\n  ) internal pure returns (bool) {\n    unchecked {\n      require(reserveIndex < ReserveConfiguration.MAX_RESERVES_COUNT, Errors.INVALID_RESERVE_INDEX);\n      return (self.data >> (reserveIndex << 1)) & 1 != 0;\n    }\n  }\n\n  /**\n   * @notice Validate a user has been using the reserve as collateral\n   * @param self The configuration object\n   * @param reserveIndex The index of the reserve in the bitmap\n   * @return True if the user has been using a reserve as collateral, false otherwise\n   */\n  function isUsingAsCollateral(\n    DataTypes.UserConfigurationMap memory self,\n    uint256 reserveIndex\n  ) internal pure returns (bool) {\n    unchecked {\n      require(reserveIndex < ReserveConfiguration.MAX_RESERVES_COUNT, Errors.INVALID_RESERVE_INDEX);\n      return (self.data >> ((reserveIndex << 1) + 1)) & 1 != 0;\n    }\n  }\n\n  /**\n   * @notice Checks if a user has been supplying only one reserve as collateral\n   * @dev this uses a simple trick - if a number is a power of two (only one bit set) then n & (n - 1) == 0\n   * @param self The configuration object\n   * @return True if the user has been supplying as collateral one reserve, false otherwise\n   */\n  function isUsingAsCollateralOne(\n    DataTypes.UserConfigurationMap memory self\n  ) internal pure returns (bool) {\n    uint256 collateralData = self.data & COLLATERAL_MASK;\n    return collateralData != 0 && (collateralData & (collateralData - 1) == 0);\n  }\n\n  /**\n   * @notice Checks if a user has been supplying any reserve as collateral\n   * @param self The configuration object\n   * @return True if the user has been supplying as collateral any reserve, false otherwise\n   */\n  function isUsingAsCollateralAny(\n    DataTypes.UserConfigurationMap memory self\n  ) internal pure returns (bool) {\n    return self.data & COLLATERAL_MASK != 0;\n  }\n\n  /**\n   * @notice Checks if a user has been borrowing only one asset\n   * @dev this uses a simple trick - if a number is a power of two (only one bit set) then n & (n - 1) == 0\n   * @param self The configuration object\n   * @return True if the user has been supplying as collateral one reserve, false otherwise\n   */\n  function isBorrowingOne(DataTypes.UserConfigurationMap memory self) internal pure returns (bool) {\n    uint256 borrowingData = self.data & BORROWING_MASK;\n    return borrowingData != 0 && (borrowingData & (borrowingData - 1) == 0);\n  }\n\n  /**\n   * @notice Checks if a user has been borrowing from any reserve\n   * @param self The configuration object\n   * @return True if the user has been borrowing any reserve, false otherwise\n   */\n  function isBorrowingAny(DataTypes.UserConfigurationMap memory self) internal pure returns (bool) {\n    return self.data & BORROWING_MASK != 0;\n  }\n\n  /**\n   * @notice Checks if a user has not been using any reserve for borrowing or supply\n   * @param self The configuration object\n   * @return True if the user has not been borrowing or supplying any reserve, false otherwise\n   */\n  function isEmpty(DataTypes.UserConfigurationMap memory self) internal pure returns (bool) {\n    return self.data == 0;\n  }\n\n  /**\n   * @notice Returns the Isolation Mode state of the user\n   * @param self The configuration object\n   * @param reservesData The state of all the reserves\n   * @param reservesList The addresses of all the active reserves\n   * @return True if the user is in isolation mode, false otherwise\n   * @return The address of the only asset used as collateral\n   * @return The debt ceiling of the reserve\n   */\n  function getIsolationModeState(\n    DataTypes.UserConfigurationMap memory self,\n    mapping(address => DataTypes.ReserveData) storage reservesData,\n    mapping(uint256 => address) storage reservesList\n  ) internal view returns (bool, address, uint256) {\n    if (isUsingAsCollateralOne(self)) {\n      uint256 assetId = _getFirstAssetIdByMask(self, COLLATERAL_MASK);\n\n      address assetAddress = reservesList[assetId];\n      uint256 ceiling = reservesData[assetAddress].configuration.getDebtCeiling();\n      if (ceiling != 0) {\n        return (true, assetAddress, ceiling);\n      }\n    }\n    return (false, address(0), 0);\n  }\n\n  /**\n   * @notice Returns the siloed borrowing state for the user\n   * @param self The configuration object\n   * @param reservesData The data of all the reserves\n   * @param reservesList The reserve list\n   * @return True if the user has borrowed a siloed asset, false otherwise\n   * @return The address of the only borrowed asset\n   */\n  function getSiloedBorrowingState(\n    DataTypes.UserConfigurationMap memory self,\n    mapping(address => DataTypes.ReserveData) storage reservesData,\n    mapping(uint256 => address) storage reservesList\n  ) internal view returns (bool, address) {\n    if (isBorrowingOne(self)) {\n      uint256 assetId = _getFirstAssetIdByMask(self, BORROWING_MASK);\n      address assetAddress = reservesList[assetId];\n      if (reservesData[assetAddress].configuration.getSiloedBorrowing()) {\n        return (true, assetAddress);\n      }\n    }\n\n    return (false, address(0));\n  }\n\n  /**\n   * @notice Returns the address of the first asset flagged in the bitmap given the corresponding bitmask\n   * @param self The configuration object\n   * @return The index of the first asset flagged in the bitmap once the corresponding mask is applied\n   */\n  function _getFirstAssetIdByMask(\n    DataTypes.UserConfigurationMap memory self,\n    uint256 mask\n  ) internal pure returns (uint256) {\n    unchecked {\n      uint256 bitmapData = self.data & mask;\n      uint256 firstAssetPosition = bitmapData & ~(bitmapData - 1);\n      uint256 id;\n\n      while ((firstAssetPosition >>= 2) != 0) {\n        id += 1;\n      }\n      return id;\n    }\n  }\n}\n"
      },
      "src/core/contracts/protocol/libraries/helpers/Errors.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n/**\n * @title Errors library\n * @author Aave\n * @notice Defines the error messages emitted by the different contracts of the Aave protocol\n */\nlibrary Errors {\n  string public constant CALLER_NOT_POOL_ADMIN = '1'; // 'The caller of the function is not a pool admin'\n  string public constant CALLER_NOT_EMERGENCY_ADMIN = '2'; // 'The caller of the function is not an emergency admin'\n  string public constant CALLER_NOT_POOL_OR_EMERGENCY_ADMIN = '3'; // 'The caller of the function is not a pool or emergency admin'\n  string public constant CALLER_NOT_RISK_OR_POOL_ADMIN = '4'; // 'The caller of the function is not a risk or pool admin'\n  string public constant CALLER_NOT_ASSET_LISTING_OR_POOL_ADMIN = '5'; // 'The caller of the function is not an asset listing or pool admin'\n  string public constant CALLER_NOT_BRIDGE = '6'; // 'The caller of the function is not a bridge'\n  string public constant ADDRESSES_PROVIDER_NOT_REGISTERED = '7'; // 'Pool addresses provider is not registered'\n  string public constant INVALID_ADDRESSES_PROVIDER_ID = '8'; // 'Invalid id for the pool addresses provider'\n  string public constant NOT_CONTRACT = '9'; // 'Address is not a contract'\n  string public constant CALLER_NOT_POOL_CONFIGURATOR = '10'; // 'The caller of the function is not the pool configurator'\n  string public constant CALLER_NOT_ATOKEN = '11'; // 'The caller of the function is not an AToken'\n  string public constant INVALID_ADDRESSES_PROVIDER = '12'; // 'The address of the pool addresses provider is invalid'\n  string public constant INVALID_FLASHLOAN_EXECUTOR_RETURN = '13'; // 'Invalid return value of the flashloan executor function'\n  string public constant RESERVE_ALREADY_ADDED = '14'; // 'Reserve has already been added to reserve list'\n  string public constant NO_MORE_RESERVES_ALLOWED = '15'; // 'Maximum amount of reserves in the pool reached'\n  string public constant EMODE_CATEGORY_RESERVED = '16'; // 'Zero eMode category is reserved for volatile heterogeneous assets'\n  string public constant INVALID_EMODE_CATEGORY_ASSIGNMENT = '17'; // 'Invalid eMode category assignment to asset'\n  string public constant RESERVE_LIQUIDITY_NOT_ZERO = '18'; // 'The liquidity of the reserve needs to be 0'\n  string public constant FLASHLOAN_PREMIUM_INVALID = '19'; // 'Invalid flashloan premium'\n  string public constant INVALID_RESERVE_PARAMS = '20'; // 'Invalid risk parameters for the reserve'\n  string public constant INVALID_EMODE_CATEGORY_PARAMS = '21'; // 'Invalid risk parameters for the eMode category'\n  string public constant BRIDGE_PROTOCOL_FEE_INVALID = '22'; // 'Invalid bridge protocol fee'\n  string public constant CALLER_MUST_BE_POOL = '23'; // 'The caller of this function must be a pool'\n  string public constant INVALID_MINT_AMOUNT = '24'; // 'Invalid amount to mint'\n  string public constant INVALID_BURN_AMOUNT = '25'; // 'Invalid amount to burn'\n  string public constant INVALID_AMOUNT = '26'; // 'Amount must be greater than 0'\n  string public constant RESERVE_INACTIVE = '27'; // 'Action requires an active reserve'\n  string public constant RESERVE_FROZEN = '28'; // 'Action cannot be performed because the reserve is frozen'\n  string public constant RESERVE_PAUSED = '29'; // 'Action cannot be performed because the reserve is paused'\n  string public constant BORROWING_NOT_ENABLED = '30'; // 'Borrowing is not enabled'\n  string public constant STABLE_BORROWING_NOT_ENABLED = '31'; // 'Stable borrowing is not enabled'\n  string public constant NOT_ENOUGH_AVAILABLE_USER_BALANCE = '32'; // 'User cannot withdraw more than the available balance'\n  string public constant INVALID_INTEREST_RATE_MODE_SELECTED = '33'; // 'Invalid interest rate mode selected'\n  string public constant COLLATERAL_BALANCE_IS_ZERO = '34'; // 'The collateral balance is 0'\n  string public constant HEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD = '35'; // 'Health factor is lesser than the liquidation threshold'\n  string public constant COLLATERAL_CANNOT_COVER_NEW_BORROW = '36'; // 'There is not enough collateral to cover a new borrow'\n  string public constant COLLATERAL_SAME_AS_BORROWING_CURRENCY = '37'; // 'Collateral is (mostly) the same currency that is being borrowed'\n  string public constant AMOUNT_BIGGER_THAN_MAX_LOAN_SIZE_STABLE = '38'; // 'The requested amount is greater than the max loan size in stable rate mode'\n  string public constant NO_DEBT_OF_SELECTED_TYPE = '39'; // 'For repayment of a specific type of debt, the user needs to have debt that type'\n  string public constant NO_EXPLICIT_AMOUNT_TO_REPAY_ON_BEHALF = '40'; // 'To repay on behalf of a user an explicit amount to repay is needed'\n  string public constant NO_OUTSTANDING_STABLE_DEBT = '41'; // 'User does not have outstanding stable rate debt on this reserve'\n  string public constant NO_OUTSTANDING_VARIABLE_DEBT = '42'; // 'User does not have outstanding variable rate debt on this reserve'\n  string public constant UNDERLYING_BALANCE_ZERO = '43'; // 'The underlying balance needs to be greater than 0'\n  string public constant INTEREST_RATE_REBALANCE_CONDITIONS_NOT_MET = '44'; // 'Interest rate rebalance conditions were not met'\n  string public constant HEALTH_FACTOR_NOT_BELOW_THRESHOLD = '45'; // 'Health factor is not below the threshold'\n  string public constant COLLATERAL_CANNOT_BE_LIQUIDATED = '46'; // 'The collateral chosen cannot be liquidated'\n  string public constant SPECIFIED_CURRENCY_NOT_BORROWED_BY_USER = '47'; // 'User did not borrow the specified currency'\n  string public constant INCONSISTENT_FLASHLOAN_PARAMS = '49'; // 'Inconsistent flashloan parameters'\n  string public constant BORROW_CAP_EXCEEDED = '50'; // 'Borrow cap is exceeded'\n  string public constant SUPPLY_CAP_EXCEEDED = '51'; // 'Supply cap is exceeded'\n  string public constant UNBACKED_MINT_CAP_EXCEEDED = '52'; // 'Unbacked mint cap is exceeded'\n  string public constant DEBT_CEILING_EXCEEDED = '53'; // 'Debt ceiling is exceeded'\n  string public constant UNDERLYING_CLAIMABLE_RIGHTS_NOT_ZERO = '54'; // 'Claimable rights over underlying not zero (aToken supply or accruedToTreasury)'\n  string public constant STABLE_DEBT_NOT_ZERO = '55'; // 'Stable debt supply is not zero'\n  string public constant VARIABLE_DEBT_SUPPLY_NOT_ZERO = '56'; // 'Variable debt supply is not zero'\n  string public constant LTV_VALIDATION_FAILED = '57'; // 'Ltv validation failed'\n  string public constant INCONSISTENT_EMODE_CATEGORY = '58'; // 'Inconsistent eMode category'\n  string public constant PRICE_ORACLE_SENTINEL_CHECK_FAILED = '59'; // 'Price oracle sentinel validation failed'\n  string public constant ASSET_NOT_BORROWABLE_IN_ISOLATION = '60'; // 'Asset is not borrowable in isolation mode'\n  string public constant RESERVE_ALREADY_INITIALIZED = '61'; // 'Reserve has already been initialized'\n  string public constant USER_IN_ISOLATION_MODE_OR_LTV_ZERO = '62'; // 'User is in isolation mode or ltv is zero'\n  string public constant INVALID_LTV = '63'; // 'Invalid ltv parameter for the reserve'\n  string public constant INVALID_LIQ_THRESHOLD = '64'; // 'Invalid liquidity threshold parameter for the reserve'\n  string public constant INVALID_LIQ_BONUS = '65'; // 'Invalid liquidity bonus parameter for the reserve'\n  string public constant INVALID_DECIMALS = '66'; // 'Invalid decimals parameter of the underlying asset of the reserve'\n  string public constant INVALID_RESERVE_FACTOR = '67'; // 'Invalid reserve factor parameter for the reserve'\n  string public constant INVALID_BORROW_CAP = '68'; // 'Invalid borrow cap for the reserve'\n  string public constant INVALID_SUPPLY_CAP = '69'; // 'Invalid supply cap for the reserve'\n  string public constant INVALID_LIQUIDATION_PROTOCOL_FEE = '70'; // 'Invalid liquidation protocol fee for the reserve'\n  string public constant INVALID_EMODE_CATEGORY = '71'; // 'Invalid eMode category for the reserve'\n  string public constant INVALID_UNBACKED_MINT_CAP = '72'; // 'Invalid unbacked mint cap for the reserve'\n  string public constant INVALID_DEBT_CEILING = '73'; // 'Invalid debt ceiling for the reserve\n  string public constant INVALID_RESERVE_INDEX = '74'; // 'Invalid reserve index'\n  string public constant ACL_ADMIN_CANNOT_BE_ZERO = '75'; // 'ACL admin cannot be set to the zero address'\n  string public constant INCONSISTENT_PARAMS_LENGTH = '76'; // 'Array parameters that should be equal length are not'\n  string public constant ZERO_ADDRESS_NOT_VALID = '77'; // 'Zero address not valid'\n  string public constant INVALID_EXPIRATION = '78'; // 'Invalid expiration'\n  string public constant INVALID_SIGNATURE = '79'; // 'Invalid signature'\n  string public constant OPERATION_NOT_SUPPORTED = '80'; // 'Operation not supported'\n  string public constant DEBT_CEILING_NOT_ZERO = '81'; // 'Debt ceiling is not zero'\n  string public constant ASSET_NOT_LISTED = '82'; // 'Asset is not listed'\n  string public constant INVALID_OPTIMAL_USAGE_RATIO = '83'; // 'Invalid optimal usage ratio'\n  string public constant INVALID_OPTIMAL_STABLE_TO_TOTAL_DEBT_RATIO = '84'; // 'Invalid optimal stable to total debt ratio'\n  string public constant UNDERLYING_CANNOT_BE_RESCUED = '85'; // 'The underlying asset cannot be rescued'\n  string public constant ADDRESSES_PROVIDER_ALREADY_ADDED = '86'; // 'Reserve has already been added to reserve list'\n  string public constant POOL_ADDRESSES_DO_NOT_MATCH = '87'; // 'The token implementation pool address and the pool address provided by the initializing pool do not match'\n  string public constant STABLE_BORROWING_ENABLED = '88'; // 'Stable borrowing is enabled'\n  string public constant SILOED_BORROWING_VIOLATION = '89'; // 'User is trying to borrow multiple assets including a siloed one'\n  string public constant RESERVE_DEBT_NOT_ZERO = '90'; // the total debt of the reserve needs to be 0\n  string public constant FLASHLOAN_DISABLED = '91'; // FlashLoaning for this asset is disabled\n}\n"
      },
      "src/core/contracts/protocol/libraries/helpers/Helpers.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {IERC20} from '../../../dependencies/openzeppelin/contracts/IERC20.sol';\nimport {DataTypes} from '../types/DataTypes.sol';\n\n/**\n * @title Helpers library\n * @author Aave\n */\nlibrary Helpers {\n  /**\n   * @notice Fetches the user current stable and variable debt balances\n   * @param user The user address\n   * @param reserveCache The reserve cache data object\n   * @return The stable debt balance\n   * @return The variable debt balance\n   */\n  function getUserCurrentDebt(\n    address user,\n    DataTypes.ReserveCache memory reserveCache\n  ) internal view returns (uint256, uint256) {\n    return (\n      IERC20(reserveCache.stableDebtTokenAddress).balanceOf(user),\n      IERC20(reserveCache.variableDebtTokenAddress).balanceOf(user)\n    );\n  }\n}\n"
      },
      "src/core/contracts/protocol/libraries/logic/BorrowLogic.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport {GPv2SafeERC20} from '../../../dependencies/gnosis/contracts/GPv2SafeERC20.sol';\nimport {SafeCast} from '../../../dependencies/openzeppelin/contracts/SafeCast.sol';\nimport {IERC20} from '../../../dependencies/openzeppelin/contracts/IERC20.sol';\nimport {IStableDebtToken} from '../../../interfaces/IStableDebtToken.sol';\nimport {IVariableDebtToken} from '../../../interfaces/IVariableDebtToken.sol';\nimport {IAToken} from '../../../interfaces/IAToken.sol';\nimport {UserConfiguration} from '../configuration/UserConfiguration.sol';\nimport {ReserveConfiguration} from '../configuration/ReserveConfiguration.sol';\nimport {Helpers} from '../helpers/Helpers.sol';\nimport {DataTypes} from '../types/DataTypes.sol';\nimport {ValidationLogic} from './ValidationLogic.sol';\nimport {ReserveLogic} from './ReserveLogic.sol';\nimport {IsolationModeLogic} from './IsolationModeLogic.sol';\n\n/**\n * @title BorrowLogic library\n * @author Aave\n * @notice Implements the base logic for all the actions related to borrowing\n */\nlibrary BorrowLogic {\n  using ReserveLogic for DataTypes.ReserveCache;\n  using ReserveLogic for DataTypes.ReserveData;\n  using GPv2SafeERC20 for IERC20;\n  using UserConfiguration for DataTypes.UserConfigurationMap;\n  using ReserveConfiguration for DataTypes.ReserveConfigurationMap;\n  using SafeCast for uint256;\n\n  // See `IPool` for descriptions\n  event Borrow(\n    address indexed reserve,\n    address user,\n    address indexed onBehalfOf,\n    uint256 amount,\n    DataTypes.InterestRateMode interestRateMode,\n    uint256 borrowRate,\n    uint16 indexed referralCode\n  );\n  event Repay(\n    address indexed reserve,\n    address indexed user,\n    address indexed repayer,\n    uint256 amount,\n    bool useATokens\n  );\n  event RebalanceStableBorrowRate(address indexed reserve, address indexed user);\n  event SwapBorrowRateMode(\n    address indexed reserve,\n    address indexed user,\n    DataTypes.InterestRateMode interestRateMode\n  );\n  event IsolationModeTotalDebtUpdated(address indexed asset, uint256 totalDebt);\n\n  /**\n   * @notice Implements the borrow feature. Borrowing allows users that provided collateral to draw liquidity from the\n   * Aave protocol proportionally to their collateralization power. For isolated positions, it also increases the\n   * isolated debt.\n   * @dev  Emits the `Borrow()` event\n   * @param reservesData The state of all the reserves\n   * @param reservesList The addresses of all the active reserves\n   * @param eModeCategories The configuration of all the efficiency mode categories\n   * @param userConfig The user configuration mapping that tracks the supplied/borrowed assets\n   * @param params The additional parameters needed to execute the borrow function\n   */\n  function executeBorrow(\n    mapping(address => DataTypes.ReserveData) storage reservesData,\n    mapping(uint256 => address) storage reservesList,\n    mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories,\n    DataTypes.UserConfigurationMap storage userConfig,\n    DataTypes.ExecuteBorrowParams memory params\n  ) public {\n    DataTypes.ReserveData storage reserve = reservesData[params.asset];\n    DataTypes.ReserveCache memory reserveCache = reserve.cache();\n\n    reserve.updateState(reserveCache);\n\n    (\n      bool isolationModeActive,\n      address isolationModeCollateralAddress,\n      uint256 isolationModeDebtCeiling\n    ) = userConfig.getIsolationModeState(reservesData, reservesList);\n\n    ValidationLogic.validateBorrow(\n      reservesData,\n      reservesList,\n      eModeCategories,\n      DataTypes.ValidateBorrowParams({\n        reserveCache: reserveCache,\n        userConfig: userConfig,\n        asset: params.asset,\n        userAddress: params.onBehalfOf,\n        amount: params.amount,\n        interestRateMode: params.interestRateMode,\n        maxStableLoanPercent: params.maxStableRateBorrowSizePercent,\n        reservesCount: params.reservesCount,\n        oracle: params.oracle,\n        userEModeCategory: params.userEModeCategory,\n        priceOracleSentinel: params.priceOracleSentinel,\n        isolationModeActive: isolationModeActive,\n        isolationModeCollateralAddress: isolationModeCollateralAddress,\n        isolationModeDebtCeiling: isolationModeDebtCeiling\n      })\n    );\n\n    uint256 currentStableRate = 0;\n    bool isFirstBorrowing = false;\n\n    if (params.interestRateMode == DataTypes.InterestRateMode.STABLE) {\n      currentStableRate = reserve.currentStableBorrowRate;\n\n      (\n        isFirstBorrowing,\n        reserveCache.nextTotalStableDebt,\n        reserveCache.nextAvgStableBorrowRate\n      ) = IStableDebtToken(reserveCache.stableDebtTokenAddress).mint(\n        params.user,\n        params.onBehalfOf,\n        params.amount,\n        currentStableRate\n      );\n    } else {\n      (isFirstBorrowing, reserveCache.nextScaledVariableDebt) = IVariableDebtToken(\n        reserveCache.variableDebtTokenAddress\n      ).mint(params.user, params.onBehalfOf, params.amount, reserveCache.nextVariableBorrowIndex);\n    }\n\n    if (isFirstBorrowing) {\n      userConfig.setBorrowing(reserve.id, true);\n    }\n\n    if (isolationModeActive) {\n      uint256 nextIsolationModeTotalDebt = reservesData[isolationModeCollateralAddress]\n        .isolationModeTotalDebt += (params.amount /\n        10 **\n          (reserveCache.reserveConfiguration.getDecimals() -\n            ReserveConfiguration.DEBT_CEILING_DECIMALS)).toUint128();\n      emit IsolationModeTotalDebtUpdated(\n        isolationModeCollateralAddress,\n        nextIsolationModeTotalDebt\n      );\n    }\n\n    reserve.updateInterestRates(\n      reserveCache,\n      params.asset,\n      0,\n      params.releaseUnderlying ? params.amount : 0\n    );\n\n    if (params.releaseUnderlying) {\n      IAToken(reserveCache.aTokenAddress).transferUnderlyingTo(params.user, params.amount);\n    }\n\n    emit Borrow(\n      params.asset,\n      params.user,\n      params.onBehalfOf,\n      params.amount,\n      params.interestRateMode,\n      params.interestRateMode == DataTypes.InterestRateMode.STABLE\n        ? currentStableRate\n        : reserve.currentVariableBorrowRate,\n      params.referralCode\n    );\n  }\n\n  /**\n   * @notice Implements the repay feature. Repaying transfers the underlying back to the aToken and clears the\n   * equivalent amount of debt for the user by burning the corresponding debt token. For isolated positions, it also\n   * reduces the isolated debt.\n   * @dev  Emits the `Repay()` event\n   * @param reservesData The state of all the reserves\n   * @param reservesList The addresses of all the active reserves\n   * @param userConfig The user configuration mapping that tracks the supplied/borrowed assets\n   * @param params The additional parameters needed to execute the repay function\n   * @return The actual amount being repaid\n   */\n  function executeRepay(\n    mapping(address => DataTypes.ReserveData) storage reservesData,\n    mapping(uint256 => address) storage reservesList,\n    DataTypes.UserConfigurationMap storage userConfig,\n    DataTypes.ExecuteRepayParams memory params\n  ) external returns (uint256) {\n    DataTypes.ReserveData storage reserve = reservesData[params.asset];\n    DataTypes.ReserveCache memory reserveCache = reserve.cache();\n    reserve.updateState(reserveCache);\n\n    (uint256 stableDebt, uint256 variableDebt) = Helpers.getUserCurrentDebt(\n      params.onBehalfOf,\n      reserveCache\n    );\n\n    ValidationLogic.validateRepay(\n      reserveCache,\n      params.amount,\n      params.interestRateMode,\n      params.onBehalfOf,\n      stableDebt,\n      variableDebt\n    );\n\n    uint256 paybackAmount = params.interestRateMode == DataTypes.InterestRateMode.STABLE\n      ? stableDebt\n      : variableDebt;\n\n    // Allows a user to repay with aTokens without leaving dust from interest.\n    if (params.useATokens && params.amount == type(uint256).max) {\n      params.amount = IAToken(reserveCache.aTokenAddress).balanceOf(msg.sender);\n    }\n\n    if (params.amount < paybackAmount) {\n      paybackAmount = params.amount;\n    }\n\n    if (params.interestRateMode == DataTypes.InterestRateMode.STABLE) {\n      (reserveCache.nextTotalStableDebt, reserveCache.nextAvgStableBorrowRate) = IStableDebtToken(\n        reserveCache.stableDebtTokenAddress\n      ).burn(params.onBehalfOf, paybackAmount);\n    } else {\n      reserveCache.nextScaledVariableDebt = IVariableDebtToken(\n        reserveCache.variableDebtTokenAddress\n      ).burn(params.onBehalfOf, paybackAmount, reserveCache.nextVariableBorrowIndex);\n    }\n\n    reserve.updateInterestRates(\n      reserveCache,\n      params.asset,\n      params.useATokens ? 0 : paybackAmount,\n      0\n    );\n\n    if (stableDebt + variableDebt - paybackAmount == 0) {\n      userConfig.setBorrowing(reserve.id, false);\n    }\n\n    IsolationModeLogic.updateIsolatedDebtIfIsolated(\n      reservesData,\n      reservesList,\n      userConfig,\n      reserveCache,\n      paybackAmount\n    );\n\n    if (params.useATokens) {\n      IAToken(reserveCache.aTokenAddress).burn(\n        msg.sender,\n        reserveCache.aTokenAddress,\n        paybackAmount,\n        reserveCache.nextLiquidityIndex\n      );\n    } else {\n      IERC20(params.asset).safeTransferFrom(msg.sender, reserveCache.aTokenAddress, paybackAmount);\n      IAToken(reserveCache.aTokenAddress).handleRepayment(\n        msg.sender,\n        params.onBehalfOf,\n        paybackAmount\n      );\n    }\n\n    emit Repay(params.asset, params.onBehalfOf, msg.sender, paybackAmount, params.useATokens);\n\n    return paybackAmount;\n  }\n\n  /**\n   * @notice Implements the rebalance stable borrow rate feature. In case of liquidity crunches on the protocol, stable\n   * rate borrows might need to be rebalanced to bring back equilibrium between the borrow and supply APYs.\n   * @dev The rules that define if a position can be rebalanced are implemented in `ValidationLogic.validateRebalanceStableBorrowRate()`\n   * @dev Emits the `RebalanceStableBorrowRate()` event\n   * @param reserve The state of the reserve of the asset being repaid\n   * @param asset The asset of the position being rebalanced\n   * @param user The user being rebalanced\n   */\n  function executeRebalanceStableBorrowRate(\n    DataTypes.ReserveData storage reserve,\n    address asset,\n    address user\n  ) external {\n    DataTypes.ReserveCache memory reserveCache = reserve.cache();\n    reserve.updateState(reserveCache);\n\n    ValidationLogic.validateRebalanceStableBorrowRate(reserve, reserveCache, asset);\n\n    IStableDebtToken stableDebtToken = IStableDebtToken(reserveCache.stableDebtTokenAddress);\n    uint256 stableDebt = IERC20(address(stableDebtToken)).balanceOf(user);\n\n    stableDebtToken.burn(user, stableDebt);\n\n    (, reserveCache.nextTotalStableDebt, reserveCache.nextAvgStableBorrowRate) = stableDebtToken\n      .mint(user, user, stableDebt, reserve.currentStableBorrowRate);\n\n    reserve.updateInterestRates(reserveCache, asset, 0, 0);\n\n    emit RebalanceStableBorrowRate(asset, user);\n  }\n\n  /**\n   * @notice Implements the swap borrow rate feature. Borrowers can swap from variable to stable positions at any time.\n   * @dev Emits the `Swap()` event\n   * @param reserve The of the reserve of the asset being repaid\n   * @param userConfig The user configuration mapping that tracks the supplied/borrowed assets\n   * @param asset The asset of the position being swapped\n   * @param interestRateMode The current interest rate mode of the position being swapped\n   */\n  function executeSwapBorrowRateMode(\n    DataTypes.ReserveData storage reserve,\n    DataTypes.UserConfigurationMap storage userConfig,\n    address asset,\n    DataTypes.InterestRateMode interestRateMode\n  ) external {\n    DataTypes.ReserveCache memory reserveCache = reserve.cache();\n\n    reserve.updateState(reserveCache);\n\n    (uint256 stableDebt, uint256 variableDebt) = Helpers.getUserCurrentDebt(\n      msg.sender,\n      reserveCache\n    );\n\n    ValidationLogic.validateSwapRateMode(\n      reserve,\n      reserveCache,\n      userConfig,\n      stableDebt,\n      variableDebt,\n      interestRateMode\n    );\n\n    if (interestRateMode == DataTypes.InterestRateMode.STABLE) {\n      (reserveCache.nextTotalStableDebt, reserveCache.nextAvgStableBorrowRate) = IStableDebtToken(\n        reserveCache.stableDebtTokenAddress\n      ).burn(msg.sender, stableDebt);\n\n      (, reserveCache.nextScaledVariableDebt) = IVariableDebtToken(\n        reserveCache.variableDebtTokenAddress\n      ).mint(msg.sender, msg.sender, stableDebt, reserveCache.nextVariableBorrowIndex);\n    } else {\n      reserveCache.nextScaledVariableDebt = IVariableDebtToken(\n        reserveCache.variableDebtTokenAddress\n      ).burn(msg.sender, variableDebt, reserveCache.nextVariableBorrowIndex);\n\n      (, reserveCache.nextTotalStableDebt, reserveCache.nextAvgStableBorrowRate) = IStableDebtToken(\n        reserveCache.stableDebtTokenAddress\n      ).mint(msg.sender, msg.sender, variableDebt, reserve.currentStableBorrowRate);\n    }\n\n    reserve.updateInterestRates(reserveCache, asset, 0, 0);\n\n    emit SwapBorrowRateMode(asset, msg.sender, interestRateMode);\n  }\n}\n"
      },
      "src/core/contracts/protocol/libraries/logic/BridgeLogic.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport {IERC20} from '../../../dependencies/openzeppelin/contracts/IERC20.sol';\nimport {GPv2SafeERC20} from '../../../dependencies/gnosis/contracts/GPv2SafeERC20.sol';\nimport {SafeCast} from '../../../dependencies/openzeppelin/contracts/SafeCast.sol';\nimport {IAToken} from '../../../interfaces/IAToken.sol';\nimport {DataTypes} from '../types/DataTypes.sol';\nimport {UserConfiguration} from '../configuration/UserConfiguration.sol';\nimport {ReserveConfiguration} from '../configuration/ReserveConfiguration.sol';\nimport {WadRayMath} from '../math/WadRayMath.sol';\nimport {PercentageMath} from '../math/PercentageMath.sol';\nimport {Errors} from '../helpers/Errors.sol';\nimport {ValidationLogic} from './ValidationLogic.sol';\nimport {ReserveLogic} from './ReserveLogic.sol';\n\nlibrary BridgeLogic {\n  using ReserveLogic for DataTypes.ReserveCache;\n  using ReserveLogic for DataTypes.ReserveData;\n  using UserConfiguration for DataTypes.UserConfigurationMap;\n  using ReserveConfiguration for DataTypes.ReserveConfigurationMap;\n  using WadRayMath for uint256;\n  using PercentageMath for uint256;\n  using SafeCast for uint256;\n  using GPv2SafeERC20 for IERC20;\n\n  // See `IPool` for descriptions\n  event ReserveUsedAsCollateralEnabled(address indexed reserve, address indexed user);\n  event MintUnbacked(\n    address indexed reserve,\n    address user,\n    address indexed onBehalfOf,\n    uint256 amount,\n    uint16 indexed referralCode\n  );\n  event BackUnbacked(address indexed reserve, address indexed backer, uint256 amount, uint256 fee);\n\n  /**\n   * @notice Mint unbacked aTokens to a user and updates the unbacked for the reserve.\n   * @dev Essentially a supply without transferring the underlying.\n   * @dev Emits the `MintUnbacked` event\n   * @dev Emits the `ReserveUsedAsCollateralEnabled` if asset is set as collateral\n   * @param reservesData The state of all the reserves\n   * @param reservesList The addresses of all the active reserves\n   * @param userConfig The user configuration mapping that tracks the supplied/borrowed assets\n   * @param asset The address of the underlying asset to mint aTokens of\n   * @param amount The amount to mint\n   * @param onBehalfOf The address that will receive the aTokens\n   * @param referralCode Code used to register the integrator originating the operation, for potential rewards.\n   *   0 if the action is executed directly by the user, without any middle-man\n   */\n  function executeMintUnbacked(\n    mapping(address => DataTypes.ReserveData) storage reservesData,\n    mapping(uint256 => address) storage reservesList,\n    DataTypes.UserConfigurationMap storage userConfig,\n    address asset,\n    uint256 amount,\n    address onBehalfOf,\n    uint16 referralCode\n  ) external {\n    DataTypes.ReserveData storage reserve = reservesData[asset];\n    DataTypes.ReserveCache memory reserveCache = reserve.cache();\n\n    reserve.updateState(reserveCache);\n\n    ValidationLogic.validateSupply(reserveCache, reserve, amount);\n\n    uint256 unbackedMintCap = reserveCache.reserveConfiguration.getUnbackedMintCap();\n    uint256 reserveDecimals = reserveCache.reserveConfiguration.getDecimals();\n\n    uint256 unbacked = reserve.unbacked += amount.toUint128();\n\n    require(\n      unbacked <= unbackedMintCap * (10 ** reserveDecimals),\n      Errors.UNBACKED_MINT_CAP_EXCEEDED\n    );\n\n    reserve.updateInterestRates(reserveCache, asset, 0, 0);\n\n    bool isFirstSupply = IAToken(reserveCache.aTokenAddress).mint(\n      msg.sender,\n      onBehalfOf,\n      amount,\n      reserveCache.nextLiquidityIndex\n    );\n\n    if (isFirstSupply) {\n      if (\n        ValidationLogic.validateAutomaticUseAsCollateral(\n          reservesData,\n          reservesList,\n          userConfig,\n          reserveCache.reserveConfiguration,\n          reserveCache.aTokenAddress\n        )\n      ) {\n        userConfig.setUsingAsCollateral(reserve.id, true);\n        emit ReserveUsedAsCollateralEnabled(asset, onBehalfOf);\n      }\n    }\n\n    emit MintUnbacked(asset, msg.sender, onBehalfOf, amount, referralCode);\n  }\n\n  /**\n   * @notice Back the current unbacked with `amount` and pay `fee`.\n   * @dev It is not possible to back more than the existing unbacked amount of the reserve\n   * @dev Emits the `BackUnbacked` event\n   * @param reserve The reserve to back unbacked for\n   * @param asset The address of the underlying asset to repay\n   * @param amount The amount to back\n   * @param fee The amount paid in fees\n   * @param protocolFeeBps The fraction of fees in basis points paid to the protocol\n   * @return The backed amount\n   */\n  function executeBackUnbacked(\n    DataTypes.ReserveData storage reserve,\n    address asset,\n    uint256 amount,\n    uint256 fee,\n    uint256 protocolFeeBps\n  ) external returns (uint256) {\n    DataTypes.ReserveCache memory reserveCache = reserve.cache();\n\n    reserve.updateState(reserveCache);\n\n    uint256 backingAmount = (amount < reserve.unbacked) ? amount : reserve.unbacked;\n\n    uint256 feeToProtocol = fee.percentMul(protocolFeeBps);\n    uint256 feeToLP = fee - feeToProtocol;\n    uint256 added = backingAmount + fee;\n\n    reserveCache.nextLiquidityIndex = reserve.cumulateToLiquidityIndex(\n      IERC20(reserveCache.aTokenAddress).totalSupply() +\n        uint256(reserve.accruedToTreasury).rayMul(reserveCache.nextLiquidityIndex),\n      feeToLP\n    );\n\n    reserve.accruedToTreasury += feeToProtocol.rayDiv(reserveCache.nextLiquidityIndex).toUint128();\n\n    reserve.unbacked -= backingAmount.toUint128();\n    reserve.updateInterestRates(reserveCache, asset, added, 0);\n\n    IERC20(asset).safeTransferFrom(msg.sender, reserveCache.aTokenAddress, added);\n\n    emit BackUnbacked(asset, msg.sender, backingAmount, fee);\n\n    return backingAmount;\n  }\n}\n"
      },
      "src/core/contracts/protocol/libraries/logic/ConfiguratorLogic.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport {IPool} from '../../../interfaces/IPool.sol';\nimport {IInitializableAToken} from '../../../interfaces/IInitializableAToken.sol';\nimport {IInitializableDebtToken} from '../../../interfaces/IInitializableDebtToken.sol';\nimport {InitializableImmutableAdminUpgradeabilityProxy} from '../aave-upgradeability/InitializableImmutableAdminUpgradeabilityProxy.sol';\nimport {ReserveConfiguration} from '../configuration/ReserveConfiguration.sol';\nimport {DataTypes} from '../types/DataTypes.sol';\nimport {ConfiguratorInputTypes} from '../types/ConfiguratorInputTypes.sol';\n\n/**\n * @title ConfiguratorLogic library\n * @author Aave\n * @notice Implements the functions to initialize reserves and update aTokens and debtTokens\n */\nlibrary ConfiguratorLogic {\n  using ReserveConfiguration for DataTypes.ReserveConfigurationMap;\n\n  // See `IPoolConfigurator` for descriptions\n  event ReserveInitialized(\n    address indexed asset,\n    address indexed aToken,\n    address stableDebtToken,\n    address variableDebtToken,\n    address interestRateStrategyAddress\n  );\n  event ATokenUpgraded(\n    address indexed asset,\n    address indexed proxy,\n    address indexed implementation\n  );\n  event StableDebtTokenUpgraded(\n    address indexed asset,\n    address indexed proxy,\n    address indexed implementation\n  );\n  event VariableDebtTokenUpgraded(\n    address indexed asset,\n    address indexed proxy,\n    address indexed implementation\n  );\n\n  /**\n   * @notice Initialize a reserve by creating and initializing aToken, stable debt token and variable debt token\n   * @dev Emits the `ReserveInitialized` event\n   * @param pool The Pool in which the reserve will be initialized\n   * @param input The needed parameters for the initialization\n   */\n  function executeInitReserve(\n    IPool pool,\n    ConfiguratorInputTypes.InitReserveInput calldata input\n  ) public {\n    address aTokenProxyAddress = _initTokenWithProxy(\n      input.aTokenImpl,\n      abi.encodeWithSelector(\n        IInitializableAToken.initialize.selector,\n        pool,\n        input.treasury,\n        input.underlyingAsset,\n        input.incentivesController,\n        input.underlyingAssetDecimals,\n        input.aTokenName,\n        input.aTokenSymbol,\n        input.params\n      )\n    );\n\n    address stableDebtTokenProxyAddress = _initTokenWithProxy(\n      input.stableDebtTokenImpl,\n      abi.encodeWithSelector(\n        IInitializableDebtToken.initialize.selector,\n        pool,\n        input.underlyingAsset,\n        input.incentivesController,\n        input.underlyingAssetDecimals,\n        input.stableDebtTokenName,\n        input.stableDebtTokenSymbol,\n        input.params\n      )\n    );\n\n    address variableDebtTokenProxyAddress = _initTokenWithProxy(\n      input.variableDebtTokenImpl,\n      abi.encodeWithSelector(\n        IInitializableDebtToken.initialize.selector,\n        pool,\n        input.underlyingAsset,\n        input.incentivesController,\n        input.underlyingAssetDecimals,\n        input.variableDebtTokenName,\n        input.variableDebtTokenSymbol,\n        input.params\n      )\n    );\n\n    pool.initReserve(\n      input.underlyingAsset,\n      aTokenProxyAddress,\n      stableDebtTokenProxyAddress,\n      variableDebtTokenProxyAddress,\n      input.interestRateStrategyAddress\n    );\n\n    DataTypes.ReserveConfigurationMap memory currentConfig = DataTypes.ReserveConfigurationMap(0);\n\n    currentConfig.setDecimals(input.underlyingAssetDecimals);\n\n    currentConfig.setActive(true);\n    currentConfig.setPaused(false);\n    currentConfig.setFrozen(false);\n\n    pool.setConfiguration(input.underlyingAsset, currentConfig);\n\n    emit ReserveInitialized(\n      input.underlyingAsset,\n      aTokenProxyAddress,\n      stableDebtTokenProxyAddress,\n      variableDebtTokenProxyAddress,\n      input.interestRateStrategyAddress\n    );\n  }\n\n  /**\n   * @notice Updates the aToken implementation and initializes it\n   * @dev Emits the `ATokenUpgraded` event\n   * @param cachedPool The Pool containing the reserve with the aToken\n   * @param input The parameters needed for the initialize call\n   */\n  function executeUpdateAToken(\n    IPool cachedPool,\n    ConfiguratorInputTypes.UpdateATokenInput calldata input\n  ) public {\n    DataTypes.ReserveData memory reserveData = cachedPool.getReserveData(input.asset);\n\n    (, , , uint256 decimals, , ) = cachedPool.getConfiguration(input.asset).getParams();\n\n    bytes memory encodedCall = abi.encodeWithSelector(\n      IInitializableAToken.initialize.selector,\n      cachedPool,\n      input.treasury,\n      input.asset,\n      input.incentivesController,\n      decimals,\n      input.name,\n      input.symbol,\n      input.params\n    );\n\n    _upgradeTokenImplementation(reserveData.aTokenAddress, input.implementation, encodedCall);\n\n    emit ATokenUpgraded(input.asset, reserveData.aTokenAddress, input.implementation);\n  }\n\n  /**\n   * @notice Updates the stable debt token implementation and initializes it\n   * @dev Emits the `StableDebtTokenUpgraded` event\n   * @param cachedPool The Pool containing the reserve with the stable debt token\n   * @param input The parameters needed for the initialize call\n   */\n  function executeUpdateStableDebtToken(\n    IPool cachedPool,\n    ConfiguratorInputTypes.UpdateDebtTokenInput calldata input\n  ) public {\n    DataTypes.ReserveData memory reserveData = cachedPool.getReserveData(input.asset);\n\n    (, , , uint256 decimals, , ) = cachedPool.getConfiguration(input.asset).getParams();\n\n    bytes memory encodedCall = abi.encodeWithSelector(\n      IInitializableDebtToken.initialize.selector,\n      cachedPool,\n      input.asset,\n      input.incentivesController,\n      decimals,\n      input.name,\n      input.symbol,\n      input.params\n    );\n\n    _upgradeTokenImplementation(\n      reserveData.stableDebtTokenAddress,\n      input.implementation,\n      encodedCall\n    );\n\n    emit StableDebtTokenUpgraded(\n      input.asset,\n      reserveData.stableDebtTokenAddress,\n      input.implementation\n    );\n  }\n\n  /**\n   * @notice Updates the variable debt token implementation and initializes it\n   * @dev Emits the `VariableDebtTokenUpgraded` event\n   * @param cachedPool The Pool containing the reserve with the variable debt token\n   * @param input The parameters needed for the initialize call\n   */\n  function executeUpdateVariableDebtToken(\n    IPool cachedPool,\n    ConfiguratorInputTypes.UpdateDebtTokenInput calldata input\n  ) public {\n    DataTypes.ReserveData memory reserveData = cachedPool.getReserveData(input.asset);\n\n    (, , , uint256 decimals, , ) = cachedPool.getConfiguration(input.asset).getParams();\n\n    bytes memory encodedCall = abi.encodeWithSelector(\n      IInitializableDebtToken.initialize.selector,\n      cachedPool,\n      input.asset,\n      input.incentivesController,\n      decimals,\n      input.name,\n      input.symbol,\n      input.params\n    );\n\n    _upgradeTokenImplementation(\n      reserveData.variableDebtTokenAddress,\n      input.implementation,\n      encodedCall\n    );\n\n    emit VariableDebtTokenUpgraded(\n      input.asset,\n      reserveData.variableDebtTokenAddress,\n      input.implementation\n    );\n  }\n\n  /**\n   * @notice Creates a new proxy and initializes the implementation\n   * @param implementation The address of the implementation\n   * @param initParams The parameters that is passed to the implementation to initialize\n   * @return The address of initialized proxy\n   */\n  function _initTokenWithProxy(\n    address implementation,\n    bytes memory initParams\n  ) internal returns (address) {\n    InitializableImmutableAdminUpgradeabilityProxy proxy = new InitializableImmutableAdminUpgradeabilityProxy(\n        address(this)\n      );\n\n    proxy.initialize(implementation, initParams);\n\n    return address(proxy);\n  }\n\n  /**\n   * @notice Upgrades the implementation and makes call to the proxy\n   * @dev The call is used to initialize the new implementation.\n   * @param proxyAddress The address of the proxy\n   * @param implementation The address of the new implementation\n   * @param  initParams The parameters to the call after the upgrade\n   */\n  function _upgradeTokenImplementation(\n    address proxyAddress,\n    address implementation,\n    bytes memory initParams\n  ) internal {\n    InitializableImmutableAdminUpgradeabilityProxy proxy = InitializableImmutableAdminUpgradeabilityProxy(\n        payable(proxyAddress)\n      );\n\n    proxy.upgradeToAndCall(implementation, initParams);\n  }\n}\n"
      },
      "src/core/contracts/protocol/libraries/logic/EModeLogic.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport {GPv2SafeERC20} from '../../../dependencies/gnosis/contracts/GPv2SafeERC20.sol';\nimport {IERC20} from '../../../dependencies/openzeppelin/contracts/IERC20.sol';\nimport {IPriceOracleGetter} from '../../../interfaces/IPriceOracleGetter.sol';\nimport {UserConfiguration} from '../configuration/UserConfiguration.sol';\nimport {Errors} from '../helpers/Errors.sol';\nimport {WadRayMath} from '../math/WadRayMath.sol';\nimport {PercentageMath} from '../math/PercentageMath.sol';\nimport {DataTypes} from '../types/DataTypes.sol';\nimport {ValidationLogic} from './ValidationLogic.sol';\nimport {ReserveLogic} from './ReserveLogic.sol';\n\n/**\n * @title EModeLogic library\n * @author Aave\n * @notice Implements the base logic for all the actions related to the eMode\n */\nlibrary EModeLogic {\n  using ReserveLogic for DataTypes.ReserveCache;\n  using ReserveLogic for DataTypes.ReserveData;\n  using GPv2SafeERC20 for IERC20;\n  using UserConfiguration for DataTypes.UserConfigurationMap;\n  using WadRayMath for uint256;\n  using PercentageMath for uint256;\n\n  // See `IPool` for descriptions\n  event UserEModeSet(address indexed user, uint8 categoryId);\n\n  /**\n   * @notice Updates the user efficiency mode category\n   * @dev Will revert if user is borrowing non-compatible asset or change will drop HF < HEALTH_FACTOR_LIQUIDATION_THRESHOLD\n   * @dev Emits the `UserEModeSet` event\n   * @param reservesData The state of all the reserves\n   * @param reservesList The addresses of all the active reserves\n   * @param eModeCategories The configuration of all the efficiency mode categories\n   * @param usersEModeCategory The state of all users efficiency mode category\n   * @param userConfig The user configuration mapping that tracks the supplied/borrowed assets\n   * @param params The additional parameters needed to execute the setUserEMode function\n   */\n  function executeSetUserEMode(\n    mapping(address => DataTypes.ReserveData) storage reservesData,\n    mapping(uint256 => address) storage reservesList,\n    mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories,\n    mapping(address => uint8) storage usersEModeCategory,\n    DataTypes.UserConfigurationMap storage userConfig,\n    DataTypes.ExecuteSetUserEModeParams memory params\n  ) external {\n    ValidationLogic.validateSetUserEMode(\n      reservesData,\n      reservesList,\n      eModeCategories,\n      userConfig,\n      params.reservesCount,\n      params.categoryId\n    );\n\n    uint8 prevCategoryId = usersEModeCategory[msg.sender];\n    usersEModeCategory[msg.sender] = params.categoryId;\n\n    if (prevCategoryId != 0) {\n      ValidationLogic.validateHealthFactor(\n        reservesData,\n        reservesList,\n        eModeCategories,\n        userConfig,\n        msg.sender,\n        params.categoryId,\n        params.reservesCount,\n        params.oracle\n      );\n    }\n    emit UserEModeSet(msg.sender, params.categoryId);\n  }\n\n  /**\n   * @notice Gets the eMode configuration and calculates the eMode asset price if a custom oracle is configured\n   * @dev The eMode asset price returned is 0 if no oracle is specified\n   * @param category The user eMode category\n   * @param oracle The price oracle\n   * @return The eMode ltv\n   * @return The eMode liquidation threshold\n   * @return The eMode asset price\n   */\n  function getEModeConfiguration(\n    DataTypes.EModeCategory storage category,\n    IPriceOracleGetter oracle\n  ) internal view returns (uint256, uint256, uint256) {\n    uint256 eModeAssetPrice = 0;\n    address eModePriceSource = category.priceSource;\n\n    if (eModePriceSource != address(0)) {\n      eModeAssetPrice = oracle.getAssetPrice(eModePriceSource);\n    }\n\n    return (category.ltv, category.liquidationThreshold, eModeAssetPrice);\n  }\n\n  /**\n   * @notice Checks if eMode is active for a user and if yes, if the asset belongs to the eMode category chosen\n   * @param eModeUserCategory The user eMode category\n   * @param eModeAssetCategory The asset eMode category\n   * @return True if eMode is active and the asset belongs to the eMode category chosen by the user, false otherwise\n   */\n  function isInEModeCategory(\n    uint256 eModeUserCategory,\n    uint256 eModeAssetCategory\n  ) internal pure returns (bool) {\n    return (eModeUserCategory != 0 && eModeAssetCategory == eModeUserCategory);\n  }\n}\n"
      },
      "src/core/contracts/protocol/libraries/logic/GenericLogic.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport {IERC20} from '../../../dependencies/openzeppelin/contracts/IERC20.sol';\nimport {IScaledBalanceToken} from '../../../interfaces/IScaledBalanceToken.sol';\nimport {IPriceOracleGetter} from '../../../interfaces/IPriceOracleGetter.sol';\nimport {ReserveConfiguration} from '../configuration/ReserveConfiguration.sol';\nimport {UserConfiguration} from '../configuration/UserConfiguration.sol';\nimport {PercentageMath} from '../math/PercentageMath.sol';\nimport {WadRayMath} from '../math/WadRayMath.sol';\nimport {DataTypes} from '../types/DataTypes.sol';\nimport {ReserveLogic} from './ReserveLogic.sol';\nimport {EModeLogic} from './EModeLogic.sol';\n\n/**\n * @title GenericLogic library\n * @author Aave\n * @notice Implements protocol-level logic to calculate and validate the state of a user\n */\nlibrary GenericLogic {\n  using ReserveLogic for DataTypes.ReserveData;\n  using WadRayMath for uint256;\n  using PercentageMath for uint256;\n  using ReserveConfiguration for DataTypes.ReserveConfigurationMap;\n  using UserConfiguration for DataTypes.UserConfigurationMap;\n\n  struct CalculateUserAccountDataVars {\n    uint256 assetPrice;\n    uint256 assetUnit;\n    uint256 userBalanceInBaseCurrency;\n    uint256 decimals;\n    uint256 ltv;\n    uint256 liquidationThreshold;\n    uint256 i;\n    uint256 healthFactor;\n    uint256 totalCollateralInBaseCurrency;\n    uint256 totalDebtInBaseCurrency;\n    uint256 avgLtv;\n    uint256 avgLiquidationThreshold;\n    uint256 eModeAssetPrice;\n    uint256 eModeLtv;\n    uint256 eModeLiqThreshold;\n    uint256 eModeAssetCategory;\n    address currentReserveAddress;\n    bool hasZeroLtvCollateral;\n    bool isInEModeCategory;\n  }\n\n  /**\n   * @notice Calculates the user data across the reserves.\n   * @dev It includes the total liquidity/collateral/borrow balances in the base currency used by the price feed,\n   * the average Loan To Value, the average Liquidation Ratio, and the Health factor.\n   * @param reservesData The state of all the reserves\n   * @param reservesList The addresses of all the active reserves\n   * @param eModeCategories The configuration of all the efficiency mode categories\n   * @param params Additional parameters needed for the calculation\n   * @return The total collateral of the user in the base currency used by the price feed\n   * @return The total debt of the user in the base currency used by the price feed\n   * @return The average ltv of the user\n   * @return The average liquidation threshold of the user\n   * @return The health factor of the user\n   * @return True if the ltv is zero, false otherwise\n   */\n  function calculateUserAccountData(\n    mapping(address => DataTypes.ReserveData) storage reservesData,\n    mapping(uint256 => address) storage reservesList,\n    mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories,\n    DataTypes.CalculateUserAccountDataParams memory params\n  ) internal view returns (uint256, uint256, uint256, uint256, uint256, bool) {\n    if (params.userConfig.isEmpty()) {\n      return (0, 0, 0, 0, type(uint256).max, false);\n    }\n\n    CalculateUserAccountDataVars memory vars;\n\n    if (params.userEModeCategory != 0) {\n      (vars.eModeLtv, vars.eModeLiqThreshold, vars.eModeAssetPrice) = EModeLogic\n        .getEModeConfiguration(\n          eModeCategories[params.userEModeCategory],\n          IPriceOracleGetter(params.oracle)\n        );\n    }\n\n    while (vars.i < params.reservesCount) {\n      if (!params.userConfig.isUsingAsCollateralOrBorrowing(vars.i)) {\n        unchecked {\n          ++vars.i;\n        }\n        continue;\n      }\n\n      vars.currentReserveAddress = reservesList[vars.i];\n\n      if (vars.currentReserveAddress == address(0)) {\n        unchecked {\n          ++vars.i;\n        }\n        continue;\n      }\n\n      DataTypes.ReserveData storage currentReserve = reservesData[vars.currentReserveAddress];\n\n      (\n        vars.ltv,\n        vars.liquidationThreshold,\n        ,\n        vars.decimals,\n        ,\n        vars.eModeAssetCategory\n      ) = currentReserve.configuration.getParams();\n\n      unchecked {\n        vars.assetUnit = 10 ** vars.decimals;\n      }\n\n      vars.assetPrice = vars.eModeAssetPrice != 0 &&\n        params.userEModeCategory == vars.eModeAssetCategory\n        ? vars.eModeAssetPrice\n        : IPriceOracleGetter(params.oracle).getAssetPrice(vars.currentReserveAddress);\n\n      if (vars.liquidationThreshold != 0 && params.userConfig.isUsingAsCollateral(vars.i)) {\n        vars.userBalanceInBaseCurrency = _getUserBalanceInBaseCurrency(\n          params.user,\n          currentReserve,\n          vars.assetPrice,\n          vars.assetUnit\n        );\n\n        vars.totalCollateralInBaseCurrency += vars.userBalanceInBaseCurrency;\n\n        vars.isInEModeCategory = EModeLogic.isInEModeCategory(\n          params.userEModeCategory,\n          vars.eModeAssetCategory\n        );\n\n        if (vars.ltv != 0) {\n          vars.avgLtv +=\n            vars.userBalanceInBaseCurrency *\n            (vars.isInEModeCategory ? vars.eModeLtv : vars.ltv);\n        } else {\n          vars.hasZeroLtvCollateral = true;\n        }\n\n        vars.avgLiquidationThreshold +=\n          vars.userBalanceInBaseCurrency *\n          (vars.isInEModeCategory ? vars.eModeLiqThreshold : vars.liquidationThreshold);\n      }\n\n      if (params.userConfig.isBorrowing(vars.i)) {\n        vars.totalDebtInBaseCurrency += _getUserDebtInBaseCurrency(\n          params.user,\n          currentReserve,\n          vars.assetPrice,\n          vars.assetUnit\n        );\n      }\n\n      unchecked {\n        ++vars.i;\n      }\n    }\n\n    unchecked {\n      vars.avgLtv = vars.totalCollateralInBaseCurrency != 0\n        ? vars.avgLtv / vars.totalCollateralInBaseCurrency\n        : 0;\n      vars.avgLiquidationThreshold = vars.totalCollateralInBaseCurrency != 0\n        ? vars.avgLiquidationThreshold / vars.totalCollateralInBaseCurrency\n        : 0;\n    }\n\n    vars.healthFactor = (vars.totalDebtInBaseCurrency == 0)\n      ? type(uint256).max\n      : (vars.totalCollateralInBaseCurrency.percentMul(vars.avgLiquidationThreshold)).wadDiv(\n        vars.totalDebtInBaseCurrency\n      );\n    return (\n      vars.totalCollateralInBaseCurrency,\n      vars.totalDebtInBaseCurrency,\n      vars.avgLtv,\n      vars.avgLiquidationThreshold,\n      vars.healthFactor,\n      vars.hasZeroLtvCollateral\n    );\n  }\n\n  /**\n   * @notice Calculates the maximum amount that can be borrowed depending on the available collateral, the total debt\n   * and the average Loan To Value\n   * @param totalCollateralInBaseCurrency The total collateral in the base currency used by the price feed\n   * @param totalDebtInBaseCurrency The total borrow balance in the base currency used by the price feed\n   * @param ltv The average loan to value\n   * @return The amount available to borrow in the base currency of the used by the price feed\n   */\n  function calculateAvailableBorrows(\n    uint256 totalCollateralInBaseCurrency,\n    uint256 totalDebtInBaseCurrency,\n    uint256 ltv\n  ) internal pure returns (uint256) {\n    uint256 availableBorrowsInBaseCurrency = totalCollateralInBaseCurrency.percentMul(ltv);\n\n    if (availableBorrowsInBaseCurrency < totalDebtInBaseCurrency) {\n      return 0;\n    }\n\n    availableBorrowsInBaseCurrency = availableBorrowsInBaseCurrency - totalDebtInBaseCurrency;\n    return availableBorrowsInBaseCurrency;\n  }\n\n  /**\n   * @notice Calculates total debt of the user in the based currency used to normalize the values of the assets\n   * @dev This fetches the `balanceOf` of the stable and variable debt tokens for the user. For gas reasons, the\n   * variable debt balance is calculated by fetching `scaledBalancesOf` normalized debt, which is cheaper than\n   * fetching `balanceOf`\n   * @param user The address of the user\n   * @param reserve The data of the reserve for which the total debt of the user is being calculated\n   * @param assetPrice The price of the asset for which the total debt of the user is being calculated\n   * @param assetUnit The value representing one full unit of the asset (10^decimals)\n   * @return The total debt of the user normalized to the base currency\n   */\n  function _getUserDebtInBaseCurrency(\n    address user,\n    DataTypes.ReserveData storage reserve,\n    uint256 assetPrice,\n    uint256 assetUnit\n  ) private view returns (uint256) {\n    // fetching variable debt\n    uint256 userTotalDebt = IScaledBalanceToken(reserve.variableDebtTokenAddress).scaledBalanceOf(\n      user\n    );\n    if (userTotalDebt != 0) {\n      userTotalDebt = userTotalDebt.rayMul(reserve.getNormalizedDebt());\n    }\n\n    userTotalDebt = userTotalDebt + IERC20(reserve.stableDebtTokenAddress).balanceOf(user);\n\n    userTotalDebt = assetPrice * userTotalDebt;\n\n    unchecked {\n      return userTotalDebt / assetUnit;\n    }\n  }\n\n  /**\n   * @notice Calculates total aToken balance of the user in the based currency used by the price oracle\n   * @dev For gas reasons, the aToken balance is calculated by fetching `scaledBalancesOf` normalized debt, which\n   * is cheaper than fetching `balanceOf`\n   * @param user The address of the user\n   * @param reserve The data of the reserve for which the total aToken balance of the user is being calculated\n   * @param assetPrice The price of the asset for which the total aToken balance of the user is being calculated\n   * @param assetUnit The value representing one full unit of the asset (10^decimals)\n   * @return The total aToken balance of the user normalized to the base currency of the price oracle\n   */\n  function _getUserBalanceInBaseCurrency(\n    address user,\n    DataTypes.ReserveData storage reserve,\n    uint256 assetPrice,\n    uint256 assetUnit\n  ) private view returns (uint256) {\n    uint256 normalizedIncome = reserve.getNormalizedIncome();\n    uint256 balance = (\n      IScaledBalanceToken(reserve.aTokenAddress).scaledBalanceOf(user).rayMul(normalizedIncome)\n    ) * assetPrice;\n\n    unchecked {\n      return balance / assetUnit;\n    }\n  }\n}\n"
      },
      "src/core/contracts/protocol/libraries/logic/IsolationModeLogic.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport {DataTypes} from '../types/DataTypes.sol';\nimport {ReserveConfiguration} from '../configuration/ReserveConfiguration.sol';\nimport {UserConfiguration} from '../configuration/UserConfiguration.sol';\nimport {SafeCast} from '../../../dependencies/openzeppelin/contracts/SafeCast.sol';\n\n/**\n * @title IsolationModeLogic library\n * @author Aave\n * @notice Implements the base logic for handling repayments for assets borrowed in isolation mode\n */\nlibrary IsolationModeLogic {\n  using ReserveConfiguration for DataTypes.ReserveConfigurationMap;\n  using UserConfiguration for DataTypes.UserConfigurationMap;\n  using SafeCast for uint256;\n\n  // See `IPool` for descriptions\n  event IsolationModeTotalDebtUpdated(address indexed asset, uint256 totalDebt);\n\n  /**\n   * @notice updated the isolated debt whenever a position collateralized by an isolated asset is repaid or liquidated\n   * @param reservesData The state of all the reserves\n   * @param reservesList The addresses of all the active reserves\n   * @param userConfig The user configuration mapping\n   * @param reserveCache The cached data of the reserve\n   * @param repayAmount The amount being repaid\n   */\n  function updateIsolatedDebtIfIsolated(\n    mapping(address => DataTypes.ReserveData) storage reservesData,\n    mapping(uint256 => address) storage reservesList,\n    DataTypes.UserConfigurationMap storage userConfig,\n    DataTypes.ReserveCache memory reserveCache,\n    uint256 repayAmount\n  ) internal {\n    (bool isolationModeActive, address isolationModeCollateralAddress, ) = userConfig\n      .getIsolationModeState(reservesData, reservesList);\n\n    if (isolationModeActive) {\n      uint128 isolationModeTotalDebt = reservesData[isolationModeCollateralAddress]\n        .isolationModeTotalDebt;\n\n      uint128 isolatedDebtRepaid = (repayAmount /\n        10 **\n          (reserveCache.reserveConfiguration.getDecimals() -\n            ReserveConfiguration.DEBT_CEILING_DECIMALS)).toUint128();\n\n      // since the debt ceiling does not take into account the interest accrued, it might happen that amount\n      // repaid > debt in isolation mode\n      if (isolationModeTotalDebt <= isolatedDebtRepaid) {\n        reservesData[isolationModeCollateralAddress].isolationModeTotalDebt = 0;\n        emit IsolationModeTotalDebtUpdated(isolationModeCollateralAddress, 0);\n      } else {\n        uint256 nextIsolationModeTotalDebt = reservesData[isolationModeCollateralAddress]\n          .isolationModeTotalDebt = isolationModeTotalDebt - isolatedDebtRepaid;\n        emit IsolationModeTotalDebtUpdated(\n          isolationModeCollateralAddress,\n          nextIsolationModeTotalDebt\n        );\n      }\n    }\n  }\n}\n"
      },
      "src/core/contracts/protocol/libraries/logic/ReserveLogic.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport {IERC20} from '../../../dependencies/openzeppelin/contracts/IERC20.sol';\nimport {GPv2SafeERC20} from '../../../dependencies/gnosis/contracts/GPv2SafeERC20.sol';\nimport {IStableDebtToken} from '../../../interfaces/IStableDebtToken.sol';\nimport {IVariableDebtToken} from '../../../interfaces/IVariableDebtToken.sol';\nimport {IReserveInterestRateStrategy} from '../../../interfaces/IReserveInterestRateStrategy.sol';\nimport {ReserveConfiguration} from '../configuration/ReserveConfiguration.sol';\nimport {MathUtils} from '../math/MathUtils.sol';\nimport {WadRayMath} from '../math/WadRayMath.sol';\nimport {PercentageMath} from '../math/PercentageMath.sol';\nimport {Errors} from '../helpers/Errors.sol';\nimport {DataTypes} from '../types/DataTypes.sol';\nimport {SafeCast} from '../../../dependencies/openzeppelin/contracts/SafeCast.sol';\n\n/**\n * @title ReserveLogic library\n * @author Aave\n * @notice Implements the logic to update the reserves state\n */\nlibrary ReserveLogic {\n  using WadRayMath for uint256;\n  using PercentageMath for uint256;\n  using SafeCast for uint256;\n  using GPv2SafeERC20 for IERC20;\n  using ReserveLogic for DataTypes.ReserveData;\n  using ReserveConfiguration for DataTypes.ReserveConfigurationMap;\n\n  // See `IPool` for descriptions\n  event ReserveDataUpdated(\n    address indexed reserve,\n    uint256 liquidityRate,\n    uint256 stableBorrowRate,\n    uint256 variableBorrowRate,\n    uint256 liquidityIndex,\n    uint256 variableBorrowIndex\n  );\n\n  /**\n   * @notice Returns the ongoing normalized income for the reserve.\n   * @dev A value of 1e27 means there is no income. As time passes, the income is accrued\n   * @dev A value of 2*1e27 means for each unit of asset one unit of income has been accrued\n   * @param reserve The reserve object\n   * @return The normalized income, expressed in ray\n   */\n  function getNormalizedIncome(\n    DataTypes.ReserveData storage reserve\n  ) internal view returns (uint256) {\n    uint40 timestamp = reserve.lastUpdateTimestamp;\n\n    //solium-disable-next-line\n    if (timestamp == block.timestamp) {\n      //if the index was updated in the same block, no need to perform any calculation\n      return reserve.liquidityIndex;\n    } else {\n      return\n        MathUtils.calculateLinearInterest(reserve.currentLiquidityRate, timestamp).rayMul(\n          reserve.liquidityIndex\n        );\n    }\n  }\n\n  /**\n   * @notice Returns the ongoing normalized variable debt for the reserve.\n   * @dev A value of 1e27 means there is no debt. As time passes, the debt is accrued\n   * @dev A value of 2*1e27 means that for each unit of debt, one unit worth of interest has been accumulated\n   * @param reserve The reserve object\n   * @return The normalized variable debt, expressed in ray\n   */\n  function getNormalizedDebt(\n    DataTypes.ReserveData storage reserve\n  ) internal view returns (uint256) {\n    uint40 timestamp = reserve.lastUpdateTimestamp;\n\n    //solium-disable-next-line\n    if (timestamp == block.timestamp) {\n      //if the index was updated in the same block, no need to perform any calculation\n      return reserve.variableBorrowIndex;\n    } else {\n      return\n        MathUtils.calculateCompoundedInterest(reserve.currentVariableBorrowRate, timestamp).rayMul(\n          reserve.variableBorrowIndex\n        );\n    }\n  }\n\n  /**\n   * @notice Updates the liquidity cumulative index and the variable borrow index.\n   * @param reserve The reserve object\n   * @param reserveCache The caching layer for the reserve data\n   */\n  function updateState(\n    DataTypes.ReserveData storage reserve,\n    DataTypes.ReserveCache memory reserveCache\n  ) internal {\n    // If time didn't pass since last stored timestamp, skip state update\n    //solium-disable-next-line\n    if (reserve.lastUpdateTimestamp == uint40(block.timestamp)) {\n      return;\n    }\n\n    _updateIndexes(reserve, reserveCache);\n    _accrueToTreasury(reserve, reserveCache);\n\n    //solium-disable-next-line\n    reserve.lastUpdateTimestamp = uint40(block.timestamp);\n  }\n\n  /**\n   * @notice Accumulates a predefined amount of asset to the reserve as a fixed, instantaneous income. Used for example\n   * to accumulate the flashloan fee to the reserve, and spread it between all the suppliers.\n   * @param reserve The reserve object\n   * @param totalLiquidity The total liquidity available in the reserve\n   * @param amount The amount to accumulate\n   * @return The next liquidity index of the reserve\n   */\n  function cumulateToLiquidityIndex(\n    DataTypes.ReserveData storage reserve,\n    uint256 totalLiquidity,\n    uint256 amount\n  ) internal returns (uint256) {\n    //next liquidity index is calculated this way: `((amount / totalLiquidity) + 1) * liquidityIndex`\n    //division `amount / totalLiquidity` done in ray for precision\n    uint256 result = (amount.wadToRay().rayDiv(totalLiquidity.wadToRay()) + WadRayMath.RAY).rayMul(\n      reserve.liquidityIndex\n    );\n    reserve.liquidityIndex = result.toUint128();\n    return result;\n  }\n\n  /**\n   * @notice Initializes a reserve.\n   * @param reserve The reserve object\n   * @param aTokenAddress The address of the overlying atoken contract\n   * @param stableDebtTokenAddress The address of the overlying stable debt token contract\n   * @param variableDebtTokenAddress The address of the overlying variable debt token contract\n   * @param interestRateStrategyAddress The address of the interest rate strategy contract\n   */\n  function init(\n    DataTypes.ReserveData storage reserve,\n    address aTokenAddress,\n    address stableDebtTokenAddress,\n    address variableDebtTokenAddress,\n    address interestRateStrategyAddress\n  ) internal {\n    require(reserve.aTokenAddress == address(0), Errors.RESERVE_ALREADY_INITIALIZED);\n\n    reserve.liquidityIndex = uint128(WadRayMath.RAY);\n    reserve.variableBorrowIndex = uint128(WadRayMath.RAY);\n    reserve.aTokenAddress = aTokenAddress;\n    reserve.stableDebtTokenAddress = stableDebtTokenAddress;\n    reserve.variableDebtTokenAddress = variableDebtTokenAddress;\n    reserve.interestRateStrategyAddress = interestRateStrategyAddress;\n  }\n\n  struct UpdateInterestRatesLocalVars {\n    uint256 nextLiquidityRate;\n    uint256 nextStableRate;\n    uint256 nextVariableRate;\n    uint256 totalVariableDebt;\n  }\n\n  /**\n   * @notice Updates the reserve current stable borrow rate, the current variable borrow rate and the current liquidity rate.\n   * @param reserve The reserve reserve to be updated\n   * @param reserveCache The caching layer for the reserve data\n   * @param reserveAddress The address of the reserve to be updated\n   * @param liquidityAdded The amount of liquidity added to the protocol (supply or repay) in the previous action\n   * @param liquidityTaken The amount of liquidity taken from the protocol (redeem or borrow)\n   */\n  function updateInterestRates(\n    DataTypes.ReserveData storage reserve,\n    DataTypes.ReserveCache memory reserveCache,\n    address reserveAddress,\n    uint256 liquidityAdded,\n    uint256 liquidityTaken\n  ) internal {\n    UpdateInterestRatesLocalVars memory vars;\n\n    vars.totalVariableDebt = reserveCache.nextScaledVariableDebt.rayMul(\n      reserveCache.nextVariableBorrowIndex\n    );\n\n    (\n      vars.nextLiquidityRate,\n      vars.nextStableRate,\n      vars.nextVariableRate\n    ) = IReserveInterestRateStrategy(reserve.interestRateStrategyAddress).calculateInterestRates(\n      DataTypes.CalculateInterestRatesParams({\n        unbacked: reserve.unbacked,\n        liquidityAdded: liquidityAdded,\n        liquidityTaken: liquidityTaken,\n        totalStableDebt: reserveCache.nextTotalStableDebt,\n        totalVariableDebt: vars.totalVariableDebt,\n        averageStableBorrowRate: reserveCache.nextAvgStableBorrowRate,\n        reserveFactor: reserveCache.reserveFactor,\n        reserve: reserveAddress,\n        aToken: reserveCache.aTokenAddress\n      })\n    );\n\n    reserve.currentLiquidityRate = vars.nextLiquidityRate.toUint128();\n    reserve.currentStableBorrowRate = vars.nextStableRate.toUint128();\n    reserve.currentVariableBorrowRate = vars.nextVariableRate.toUint128();\n\n    emit ReserveDataUpdated(\n      reserveAddress,\n      vars.nextLiquidityRate,\n      vars.nextStableRate,\n      vars.nextVariableRate,\n      reserveCache.nextLiquidityIndex,\n      reserveCache.nextVariableBorrowIndex\n    );\n  }\n\n  struct AccrueToTreasuryLocalVars {\n    uint256 prevTotalStableDebt;\n    uint256 prevTotalVariableDebt;\n    uint256 currTotalVariableDebt;\n    uint256 cumulatedStableInterest;\n    uint256 totalDebtAccrued;\n    uint256 amountToMint;\n  }\n\n  /**\n   * @notice Mints part of the repaid interest to the reserve treasury as a function of the reserve factor for the\n   * specific asset.\n   * @param reserve The reserve to be updated\n   * @param reserveCache The caching layer for the reserve data\n   */\n  function _accrueToTreasury(\n    DataTypes.ReserveData storage reserve,\n    DataTypes.ReserveCache memory reserveCache\n  ) internal {\n    AccrueToTreasuryLocalVars memory vars;\n\n    if (reserveCache.reserveFactor == 0) {\n      return;\n    }\n\n    //calculate the total variable debt at moment of the last interaction\n    vars.prevTotalVariableDebt = reserveCache.currScaledVariableDebt.rayMul(\n      reserveCache.currVariableBorrowIndex\n    );\n\n    //calculate the new total variable debt after accumulation of the interest on the index\n    vars.currTotalVariableDebt = reserveCache.currScaledVariableDebt.rayMul(\n      reserveCache.nextVariableBorrowIndex\n    );\n\n    //calculate the stable debt until the last timestamp update\n    vars.cumulatedStableInterest = MathUtils.calculateCompoundedInterest(\n      reserveCache.currAvgStableBorrowRate,\n      reserveCache.stableDebtLastUpdateTimestamp,\n      reserveCache.reserveLastUpdateTimestamp\n    );\n\n    vars.prevTotalStableDebt = reserveCache.currPrincipalStableDebt.rayMul(\n      vars.cumulatedStableInterest\n    );\n\n    //debt accrued is the sum of the current debt minus the sum of the debt at the last update\n    vars.totalDebtAccrued =\n      vars.currTotalVariableDebt +\n      reserveCache.currTotalStableDebt -\n      vars.prevTotalVariableDebt -\n      vars.prevTotalStableDebt;\n\n    vars.amountToMint = vars.totalDebtAccrued.percentMul(reserveCache.reserveFactor);\n\n    if (vars.amountToMint != 0) {\n      reserve.accruedToTreasury += vars\n        .amountToMint\n        .rayDiv(reserveCache.nextLiquidityIndex)\n        .toUint128();\n    }\n  }\n\n  /**\n   * @notice Updates the reserve indexes and the timestamp of the update.\n   * @param reserve The reserve reserve to be updated\n   * @param reserveCache The cache layer holding the cached protocol data\n   */\n  function _updateIndexes(\n    DataTypes.ReserveData storage reserve,\n    DataTypes.ReserveCache memory reserveCache\n  ) internal {\n    // Only cumulating on the supply side if there is any income being produced\n    // The case of Reserve Factor 100% is not a problem (currentLiquidityRate == 0),\n    // as liquidity index should not be updated\n    if (reserveCache.currLiquidityRate != 0) {\n      uint256 cumulatedLiquidityInterest = MathUtils.calculateLinearInterest(\n        reserveCache.currLiquidityRate,\n        reserveCache.reserveLastUpdateTimestamp\n      );\n      reserveCache.nextLiquidityIndex = cumulatedLiquidityInterest.rayMul(\n        reserveCache.currLiquidityIndex\n      );\n      reserve.liquidityIndex = reserveCache.nextLiquidityIndex.toUint128();\n    }\n\n    // Variable borrow index only gets updated if there is any variable debt.\n    // reserveCache.currVariableBorrowRate != 0 is not a correct validation,\n    // because a positive base variable rate can be stored on\n    // reserveCache.currVariableBorrowRate, but the index should not increase\n    if (reserveCache.currScaledVariableDebt != 0) {\n      uint256 cumulatedVariableBorrowInterest = MathUtils.calculateCompoundedInterest(\n        reserveCache.currVariableBorrowRate,\n        reserveCache.reserveLastUpdateTimestamp\n      );\n      reserveCache.nextVariableBorrowIndex = cumulatedVariableBorrowInterest.rayMul(\n        reserveCache.currVariableBorrowIndex\n      );\n      reserve.variableBorrowIndex = reserveCache.nextVariableBorrowIndex.toUint128();\n    }\n  }\n\n  /**\n   * @notice Creates a cache object to avoid repeated storage reads and external contract calls when updating state and\n   * interest rates.\n   * @param reserve The reserve object for which the cache will be filled\n   * @return The cache object\n   */\n  function cache(\n    DataTypes.ReserveData storage reserve\n  ) internal view returns (DataTypes.ReserveCache memory) {\n    DataTypes.ReserveCache memory reserveCache;\n\n    reserveCache.reserveConfiguration = reserve.configuration;\n    reserveCache.reserveFactor = reserveCache.reserveConfiguration.getReserveFactor();\n    reserveCache.currLiquidityIndex = reserveCache.nextLiquidityIndex = reserve.liquidityIndex;\n    reserveCache.currVariableBorrowIndex = reserveCache.nextVariableBorrowIndex = reserve\n      .variableBorrowIndex;\n    reserveCache.currLiquidityRate = reserve.currentLiquidityRate;\n    reserveCache.currVariableBorrowRate = reserve.currentVariableBorrowRate;\n\n    reserveCache.aTokenAddress = reserve.aTokenAddress;\n    reserveCache.stableDebtTokenAddress = reserve.stableDebtTokenAddress;\n    reserveCache.variableDebtTokenAddress = reserve.variableDebtTokenAddress;\n\n    reserveCache.reserveLastUpdateTimestamp = reserve.lastUpdateTimestamp;\n\n    reserveCache.currScaledVariableDebt = reserveCache.nextScaledVariableDebt = IVariableDebtToken(\n      reserveCache.variableDebtTokenAddress\n    ).scaledTotalSupply();\n\n    (\n      reserveCache.currPrincipalStableDebt,\n      reserveCache.currTotalStableDebt,\n      reserveCache.currAvgStableBorrowRate,\n      reserveCache.stableDebtLastUpdateTimestamp\n    ) = IStableDebtToken(reserveCache.stableDebtTokenAddress).getSupplyData();\n\n    // by default the actions are considered as not affecting the debt balances.\n    // if the action involves mint/burn of debt, the cache needs to be updated\n    reserveCache.nextTotalStableDebt = reserveCache.currTotalStableDebt;\n    reserveCache.nextAvgStableBorrowRate = reserveCache.currAvgStableBorrowRate;\n\n    return reserveCache;\n  }\n}\n"
      },
      "src/core/contracts/protocol/libraries/logic/ValidationLogic.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport {IERC20} from '../../../dependencies/openzeppelin/contracts/IERC20.sol';\nimport {Address} from '../../../dependencies/openzeppelin/contracts/Address.sol';\nimport {GPv2SafeERC20} from '../../../dependencies/gnosis/contracts/GPv2SafeERC20.sol';\nimport {IReserveInterestRateStrategy} from '../../../interfaces/IReserveInterestRateStrategy.sol';\nimport {IStableDebtToken} from '../../../interfaces/IStableDebtToken.sol';\nimport {IScaledBalanceToken} from '../../../interfaces/IScaledBalanceToken.sol';\nimport {IPriceOracleGetter} from '../../../interfaces/IPriceOracleGetter.sol';\nimport {IAToken} from '../../../interfaces/IAToken.sol';\nimport {IPriceOracleSentinel} from '../../../interfaces/IPriceOracleSentinel.sol';\nimport {IPoolAddressesProvider} from '../../../interfaces/IPoolAddressesProvider.sol';\nimport {IAccessControl} from '../../../dependencies/openzeppelin/contracts/IAccessControl.sol';\nimport {ReserveConfiguration} from '../configuration/ReserveConfiguration.sol';\nimport {UserConfiguration} from '../configuration/UserConfiguration.sol';\nimport {Errors} from '../helpers/Errors.sol';\nimport {WadRayMath} from '../math/WadRayMath.sol';\nimport {PercentageMath} from '../math/PercentageMath.sol';\nimport {DataTypes} from '../types/DataTypes.sol';\nimport {ReserveLogic} from './ReserveLogic.sol';\nimport {GenericLogic} from './GenericLogic.sol';\nimport {SafeCast} from '../../../dependencies/openzeppelin/contracts/SafeCast.sol';\nimport {IncentivizedERC20} from '../../tokenization/base/IncentivizedERC20.sol';\n\n/**\n * @title ReserveLogic library\n * @author Aave\n * @notice Implements functions to validate the different actions of the protocol\n */\nlibrary ValidationLogic {\n  using ReserveLogic for DataTypes.ReserveData;\n  using WadRayMath for uint256;\n  using PercentageMath for uint256;\n  using SafeCast for uint256;\n  using GPv2SafeERC20 for IERC20;\n  using ReserveConfiguration for DataTypes.ReserveConfigurationMap;\n  using UserConfiguration for DataTypes.UserConfigurationMap;\n  using Address for address;\n\n  // Factor to apply to \"only-variable-debt\" liquidity rate to get threshold for rebalancing, expressed in bps\n  // A value of 0.9e4 results in 90%\n  uint256 public constant REBALANCE_UP_LIQUIDITY_RATE_THRESHOLD = 0.9e4;\n\n  // Minimum health factor allowed under any circumstance\n  // A value of 0.95e18 results in 0.95\n  uint256 public constant MINIMUM_HEALTH_FACTOR_LIQUIDATION_THRESHOLD = 0.95e18;\n\n  /**\n   * @dev Minimum health factor to consider a user position healthy\n   * A value of 1e18 results in 1\n   */\n  uint256 public constant HEALTH_FACTOR_LIQUIDATION_THRESHOLD = 1e18;\n\n  /**\n   * @dev Role identifier for the role allowed to supply isolated reserves as collateral\n   */\n  bytes32 public constant ISOLATED_COLLATERAL_SUPPLIER_ROLE =\n    keccak256('ISOLATED_COLLATERAL_SUPPLIER');\n\n  /**\n   * @notice Validates a supply action.\n   * @param reserveCache The cached data of the reserve\n   * @param amount The amount to be supplied\n   */\n  function validateSupply(\n    DataTypes.ReserveCache memory reserveCache,\n    DataTypes.ReserveData storage reserve,\n    uint256 amount\n  ) internal view {\n    require(amount != 0, Errors.INVALID_AMOUNT);\n\n    (bool isActive, bool isFrozen, , , bool isPaused) = reserveCache\n      .reserveConfiguration\n      .getFlags();\n    require(isActive, Errors.RESERVE_INACTIVE);\n    require(!isPaused, Errors.RESERVE_PAUSED);\n    require(!isFrozen, Errors.RESERVE_FROZEN);\n\n    uint256 supplyCap = reserveCache.reserveConfiguration.getSupplyCap();\n    require(\n      supplyCap == 0 ||\n        ((IAToken(reserveCache.aTokenAddress).scaledTotalSupply() +\n          uint256(reserve.accruedToTreasury)).rayMul(reserveCache.nextLiquidityIndex) + amount) <=\n        supplyCap * (10 ** reserveCache.reserveConfiguration.getDecimals()),\n      Errors.SUPPLY_CAP_EXCEEDED\n    );\n  }\n\n  /**\n   * @notice Validates a withdraw action.\n   * @param reserveCache The cached data of the reserve\n   * @param amount The amount to be withdrawn\n   * @param userBalance The balance of the user\n   */\n  function validateWithdraw(\n    DataTypes.ReserveCache memory reserveCache,\n    uint256 amount,\n    uint256 userBalance\n  ) internal pure {\n    require(amount != 0, Errors.INVALID_AMOUNT);\n    require(amount <= userBalance, Errors.NOT_ENOUGH_AVAILABLE_USER_BALANCE);\n\n    (bool isActive, , , , bool isPaused) = reserveCache.reserveConfiguration.getFlags();\n    require(isActive, Errors.RESERVE_INACTIVE);\n    require(!isPaused, Errors.RESERVE_PAUSED);\n  }\n\n  struct ValidateBorrowLocalVars {\n    uint256 currentLtv;\n    uint256 collateralNeededInBaseCurrency;\n    uint256 userCollateralInBaseCurrency;\n    uint256 userDebtInBaseCurrency;\n    uint256 availableLiquidity;\n    uint256 healthFactor;\n    uint256 totalDebt;\n    uint256 totalSupplyVariableDebt;\n    uint256 reserveDecimals;\n    uint256 borrowCap;\n    uint256 amountInBaseCurrency;\n    uint256 assetUnit;\n    address eModePriceSource;\n    address siloedBorrowingAddress;\n    bool isActive;\n    bool isFrozen;\n    bool isPaused;\n    bool borrowingEnabled;\n    bool stableRateBorrowingEnabled;\n    bool siloedBorrowingEnabled;\n  }\n\n  /**\n   * @notice Validates a borrow action.\n   * @param reservesData The state of all the reserves\n   * @param reservesList The addresses of all the active reserves\n   * @param eModeCategories The configuration of all the efficiency mode categories\n   * @param params Additional params needed for the validation\n   */\n  function validateBorrow(\n    mapping(address => DataTypes.ReserveData) storage reservesData,\n    mapping(uint256 => address) storage reservesList,\n    mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories,\n    DataTypes.ValidateBorrowParams memory params\n  ) internal view {\n    require(params.amount != 0, Errors.INVALID_AMOUNT);\n\n    ValidateBorrowLocalVars memory vars;\n\n    (\n      vars.isActive,\n      vars.isFrozen,\n      vars.borrowingEnabled,\n      vars.stableRateBorrowingEnabled,\n      vars.isPaused\n    ) = params.reserveCache.reserveConfiguration.getFlags();\n\n    require(vars.isActive, Errors.RESERVE_INACTIVE);\n    require(!vars.isPaused, Errors.RESERVE_PAUSED);\n    require(!vars.isFrozen, Errors.RESERVE_FROZEN);\n    require(vars.borrowingEnabled, Errors.BORROWING_NOT_ENABLED);\n\n    require(\n      params.priceOracleSentinel == address(0) ||\n        IPriceOracleSentinel(params.priceOracleSentinel).isBorrowAllowed(),\n      Errors.PRICE_ORACLE_SENTINEL_CHECK_FAILED\n    );\n\n    //validate interest rate mode\n    require(\n      params.interestRateMode == DataTypes.InterestRateMode.VARIABLE ||\n        params.interestRateMode == DataTypes.InterestRateMode.STABLE,\n      Errors.INVALID_INTEREST_RATE_MODE_SELECTED\n    );\n\n    vars.reserveDecimals = params.reserveCache.reserveConfiguration.getDecimals();\n    vars.borrowCap = params.reserveCache.reserveConfiguration.getBorrowCap();\n    unchecked {\n      vars.assetUnit = 10 ** vars.reserveDecimals;\n    }\n\n    if (vars.borrowCap != 0) {\n      vars.totalSupplyVariableDebt = params.reserveCache.currScaledVariableDebt.rayMul(\n        params.reserveCache.nextVariableBorrowIndex\n      );\n\n      vars.totalDebt =\n        params.reserveCache.currTotalStableDebt +\n        vars.totalSupplyVariableDebt +\n        params.amount;\n\n      unchecked {\n        require(vars.totalDebt <= vars.borrowCap * vars.assetUnit, Errors.BORROW_CAP_EXCEEDED);\n      }\n    }\n\n    if (params.isolationModeActive) {\n      // check that the asset being borrowed is borrowable in isolation mode AND\n      // the total exposure is no bigger than the collateral debt ceiling\n      require(\n        params.reserveCache.reserveConfiguration.getBorrowableInIsolation(),\n        Errors.ASSET_NOT_BORROWABLE_IN_ISOLATION\n      );\n\n      require(\n        reservesData[params.isolationModeCollateralAddress].isolationModeTotalDebt +\n          (params.amount /\n            10 ** (vars.reserveDecimals - ReserveConfiguration.DEBT_CEILING_DECIMALS))\n            .toUint128() <=\n          params.isolationModeDebtCeiling,\n        Errors.DEBT_CEILING_EXCEEDED\n      );\n    }\n\n    if (params.userEModeCategory != 0) {\n      require(\n        params.reserveCache.reserveConfiguration.getEModeCategory() == params.userEModeCategory,\n        Errors.INCONSISTENT_EMODE_CATEGORY\n      );\n      vars.eModePriceSource = eModeCategories[params.userEModeCategory].priceSource;\n    }\n\n    (\n      vars.userCollateralInBaseCurrency,\n      vars.userDebtInBaseCurrency,\n      vars.currentLtv,\n      ,\n      vars.healthFactor,\n\n    ) = GenericLogic.calculateUserAccountData(\n      reservesData,\n      reservesList,\n      eModeCategories,\n      DataTypes.CalculateUserAccountDataParams({\n        userConfig: params.userConfig,\n        reservesCount: params.reservesCount,\n        user: params.userAddress,\n        oracle: params.oracle,\n        userEModeCategory: params.userEModeCategory\n      })\n    );\n\n    require(vars.userCollateralInBaseCurrency != 0, Errors.COLLATERAL_BALANCE_IS_ZERO);\n    require(vars.currentLtv != 0, Errors.LTV_VALIDATION_FAILED);\n\n    require(\n      vars.healthFactor > HEALTH_FACTOR_LIQUIDATION_THRESHOLD,\n      Errors.HEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD\n    );\n\n    vars.amountInBaseCurrency =\n      IPriceOracleGetter(params.oracle).getAssetPrice(\n        vars.eModePriceSource != address(0) ? vars.eModePriceSource : params.asset\n      ) *\n      params.amount;\n    unchecked {\n      vars.amountInBaseCurrency /= vars.assetUnit;\n    }\n\n    //add the current already borrowed amount to the amount requested to calculate the total collateral needed.\n    vars.collateralNeededInBaseCurrency = (vars.userDebtInBaseCurrency + vars.amountInBaseCurrency)\n      .percentDiv(vars.currentLtv); //LTV is calculated in percentage\n\n    require(\n      vars.collateralNeededInBaseCurrency <= vars.userCollateralInBaseCurrency,\n      Errors.COLLATERAL_CANNOT_COVER_NEW_BORROW\n    );\n\n    /**\n     * Following conditions need to be met if the user is borrowing at a stable rate:\n     * 1. Reserve must be enabled for stable rate borrowing\n     * 2. Users cannot borrow from the reserve if their collateral is (mostly) the same currency\n     *    they are borrowing, to prevent abuses.\n     * 3. Users will be able to borrow only a portion of the total available liquidity\n     */\n\n    if (params.interestRateMode == DataTypes.InterestRateMode.STABLE) {\n      //check if the borrow mode is stable and if stable rate borrowing is enabled on this reserve\n\n      require(vars.stableRateBorrowingEnabled, Errors.STABLE_BORROWING_NOT_ENABLED);\n\n      require(\n        !params.userConfig.isUsingAsCollateral(reservesData[params.asset].id) ||\n          params.reserveCache.reserveConfiguration.getLtv() == 0 ||\n          params.amount > IERC20(params.reserveCache.aTokenAddress).balanceOf(params.userAddress),\n        Errors.COLLATERAL_SAME_AS_BORROWING_CURRENCY\n      );\n\n      vars.availableLiquidity = IERC20(params.asset).balanceOf(params.reserveCache.aTokenAddress);\n\n      //calculate the max available loan size in stable rate mode as a percentage of the\n      //available liquidity\n      uint256 maxLoanSizeStable = vars.availableLiquidity.percentMul(params.maxStableLoanPercent);\n\n      require(params.amount <= maxLoanSizeStable, Errors.AMOUNT_BIGGER_THAN_MAX_LOAN_SIZE_STABLE);\n    }\n\n    if (params.userConfig.isBorrowingAny()) {\n      (vars.siloedBorrowingEnabled, vars.siloedBorrowingAddress) = params\n        .userConfig\n        .getSiloedBorrowingState(reservesData, reservesList);\n\n      if (vars.siloedBorrowingEnabled) {\n        require(vars.siloedBorrowingAddress == params.asset, Errors.SILOED_BORROWING_VIOLATION);\n      } else {\n        require(\n          !params.reserveCache.reserveConfiguration.getSiloedBorrowing(),\n          Errors.SILOED_BORROWING_VIOLATION\n        );\n      }\n    }\n  }\n\n  /**\n   * @notice Validates a repay action.\n   * @param reserveCache The cached data of the reserve\n   * @param amountSent The amount sent for the repayment. Can be an actual value or uint(-1)\n   * @param interestRateMode The interest rate mode of the debt being repaid\n   * @param onBehalfOf The address of the user msg.sender is repaying for\n   * @param stableDebt The borrow balance of the user\n   * @param variableDebt The borrow balance of the user\n   */\n  function validateRepay(\n    DataTypes.ReserveCache memory reserveCache,\n    uint256 amountSent,\n    DataTypes.InterestRateMode interestRateMode,\n    address onBehalfOf,\n    uint256 stableDebt,\n    uint256 variableDebt\n  ) internal view {\n    require(amountSent != 0, Errors.INVALID_AMOUNT);\n    require(\n      amountSent != type(uint256).max || msg.sender == onBehalfOf,\n      Errors.NO_EXPLICIT_AMOUNT_TO_REPAY_ON_BEHALF\n    );\n\n    (bool isActive, , , , bool isPaused) = reserveCache.reserveConfiguration.getFlags();\n    require(isActive, Errors.RESERVE_INACTIVE);\n    require(!isPaused, Errors.RESERVE_PAUSED);\n\n    require(\n      (stableDebt != 0 && interestRateMode == DataTypes.InterestRateMode.STABLE) ||\n        (variableDebt != 0 && interestRateMode == DataTypes.InterestRateMode.VARIABLE),\n      Errors.NO_DEBT_OF_SELECTED_TYPE\n    );\n  }\n\n  /**\n   * @notice Validates a swap of borrow rate mode.\n   * @param reserve The reserve state on which the user is swapping the rate\n   * @param reserveCache The cached data of the reserve\n   * @param userConfig The user reserves configuration\n   * @param stableDebt The stable debt of the user\n   * @param variableDebt The variable debt of the user\n   * @param currentRateMode The rate mode of the debt being swapped\n   */\n  function validateSwapRateMode(\n    DataTypes.ReserveData storage reserve,\n    DataTypes.ReserveCache memory reserveCache,\n    DataTypes.UserConfigurationMap storage userConfig,\n    uint256 stableDebt,\n    uint256 variableDebt,\n    DataTypes.InterestRateMode currentRateMode\n  ) internal view {\n    (bool isActive, bool isFrozen, , bool stableRateEnabled, bool isPaused) = reserveCache\n      .reserveConfiguration\n      .getFlags();\n    require(isActive, Errors.RESERVE_INACTIVE);\n    require(!isPaused, Errors.RESERVE_PAUSED);\n    require(!isFrozen, Errors.RESERVE_FROZEN);\n\n    if (currentRateMode == DataTypes.InterestRateMode.STABLE) {\n      require(stableDebt != 0, Errors.NO_OUTSTANDING_STABLE_DEBT);\n    } else if (currentRateMode == DataTypes.InterestRateMode.VARIABLE) {\n      require(variableDebt != 0, Errors.NO_OUTSTANDING_VARIABLE_DEBT);\n      /**\n       * user wants to swap to stable, before swapping we need to ensure that\n       * 1. stable borrow rate is enabled on the reserve\n       * 2. user is not trying to abuse the reserve by supplying\n       * more collateral than he is borrowing, artificially lowering\n       * the interest rate, borrowing at variable, and switching to stable\n       */\n      require(stableRateEnabled, Errors.STABLE_BORROWING_NOT_ENABLED);\n\n      require(\n        !userConfig.isUsingAsCollateral(reserve.id) ||\n          reserveCache.reserveConfiguration.getLtv() == 0 ||\n          stableDebt + variableDebt > IERC20(reserveCache.aTokenAddress).balanceOf(msg.sender),\n        Errors.COLLATERAL_SAME_AS_BORROWING_CURRENCY\n      );\n    } else {\n      revert(Errors.INVALID_INTEREST_RATE_MODE_SELECTED);\n    }\n  }\n\n  /**\n   * @notice Validates a stable borrow rate rebalance action.\n   * @dev Rebalancing is accepted when depositors are earning <= 90% of their earnings in pure supply/demand market (variable rate only)\n   * For this to be the case, there has to be quite large stable debt with an interest rate below the current variable rate.\n   * @param reserve The reserve state on which the user is getting rebalanced\n   * @param reserveCache The cached state of the reserve\n   * @param reserveAddress The address of the reserve\n   */\n  function validateRebalanceStableBorrowRate(\n    DataTypes.ReserveData storage reserve,\n    DataTypes.ReserveCache memory reserveCache,\n    address reserveAddress\n  ) internal view {\n    (bool isActive, , , , bool isPaused) = reserveCache.reserveConfiguration.getFlags();\n    require(isActive, Errors.RESERVE_INACTIVE);\n    require(!isPaused, Errors.RESERVE_PAUSED);\n\n    uint256 totalDebt = IERC20(reserveCache.stableDebtTokenAddress).totalSupply() +\n      IERC20(reserveCache.variableDebtTokenAddress).totalSupply();\n\n    (uint256 liquidityRateVariableDebtOnly, , ) = IReserveInterestRateStrategy(\n      reserve.interestRateStrategyAddress\n    ).calculateInterestRates(\n        DataTypes.CalculateInterestRatesParams({\n          unbacked: reserve.unbacked,\n          liquidityAdded: 0,\n          liquidityTaken: 0,\n          totalStableDebt: 0,\n          totalVariableDebt: totalDebt,\n          averageStableBorrowRate: 0,\n          reserveFactor: reserveCache.reserveFactor,\n          reserve: reserveAddress,\n          aToken: reserveCache.aTokenAddress\n        })\n      );\n\n    require(\n      reserveCache.currLiquidityRate <=\n        liquidityRateVariableDebtOnly.percentMul(REBALANCE_UP_LIQUIDITY_RATE_THRESHOLD),\n      Errors.INTEREST_RATE_REBALANCE_CONDITIONS_NOT_MET\n    );\n  }\n\n  /**\n   * @notice Validates the action of setting an asset as collateral.\n   * @param reserveCache The cached data of the reserve\n   * @param userBalance The balance of the user\n   */\n  function validateSetUseReserveAsCollateral(\n    DataTypes.ReserveCache memory reserveCache,\n    uint256 userBalance\n  ) internal pure {\n    require(userBalance != 0, Errors.UNDERLYING_BALANCE_ZERO);\n\n    (bool isActive, , , , bool isPaused) = reserveCache.reserveConfiguration.getFlags();\n    require(isActive, Errors.RESERVE_INACTIVE);\n    require(!isPaused, Errors.RESERVE_PAUSED);\n  }\n\n  /**\n   * @notice Validates a flashloan action.\n   * @param reservesData The state of all the reserves\n   * @param assets The assets being flash-borrowed\n   * @param amounts The amounts for each asset being borrowed\n   */\n  function validateFlashloan(\n    mapping(address => DataTypes.ReserveData) storage reservesData,\n    address[] memory assets,\n    uint256[] memory amounts\n  ) internal view {\n    require(assets.length == amounts.length, Errors.INCONSISTENT_FLASHLOAN_PARAMS);\n    for (uint256 i = 0; i < assets.length; i++) {\n      validateFlashloanSimple(reservesData[assets[i]]);\n    }\n  }\n\n  /**\n   * @notice Validates a flashloan action.\n   * @param reserve The state of the reserve\n   */\n  function validateFlashloanSimple(DataTypes.ReserveData storage reserve) internal view {\n    DataTypes.ReserveConfigurationMap memory configuration = reserve.configuration;\n    require(!configuration.getPaused(), Errors.RESERVE_PAUSED);\n    require(configuration.getActive(), Errors.RESERVE_INACTIVE);\n    require(configuration.getFlashLoanEnabled(), Errors.FLASHLOAN_DISABLED);\n  }\n\n  struct ValidateLiquidationCallLocalVars {\n    bool collateralReserveActive;\n    bool collateralReservePaused;\n    bool principalReserveActive;\n    bool principalReservePaused;\n    bool isCollateralEnabled;\n  }\n\n  /**\n   * @notice Validates the liquidation action.\n   * @param userConfig The user configuration mapping\n   * @param collateralReserve The reserve data of the collateral\n   * @param params Additional parameters needed for the validation\n   */\n  function validateLiquidationCall(\n    DataTypes.UserConfigurationMap storage userConfig,\n    DataTypes.ReserveData storage collateralReserve,\n    DataTypes.ValidateLiquidationCallParams memory params\n  ) internal view {\n    ValidateLiquidationCallLocalVars memory vars;\n\n    (vars.collateralReserveActive, , , , vars.collateralReservePaused) = collateralReserve\n      .configuration\n      .getFlags();\n\n    (vars.principalReserveActive, , , , vars.principalReservePaused) = params\n      .debtReserveCache\n      .reserveConfiguration\n      .getFlags();\n\n    require(vars.collateralReserveActive && vars.principalReserveActive, Errors.RESERVE_INACTIVE);\n    require(!vars.collateralReservePaused && !vars.principalReservePaused, Errors.RESERVE_PAUSED);\n\n    require(\n      params.priceOracleSentinel == address(0) ||\n        params.healthFactor < MINIMUM_HEALTH_FACTOR_LIQUIDATION_THRESHOLD ||\n        IPriceOracleSentinel(params.priceOracleSentinel).isLiquidationAllowed(),\n      Errors.PRICE_ORACLE_SENTINEL_CHECK_FAILED\n    );\n\n    require(\n      params.healthFactor < HEALTH_FACTOR_LIQUIDATION_THRESHOLD,\n      Errors.HEALTH_FACTOR_NOT_BELOW_THRESHOLD\n    );\n\n    vars.isCollateralEnabled =\n      collateralReserve.configuration.getLiquidationThreshold() != 0 &&\n      userConfig.isUsingAsCollateral(collateralReserve.id);\n\n    //if collateral isn't enabled as collateral by user, it cannot be liquidated\n    require(vars.isCollateralEnabled, Errors.COLLATERAL_CANNOT_BE_LIQUIDATED);\n    require(params.totalDebt != 0, Errors.SPECIFIED_CURRENCY_NOT_BORROWED_BY_USER);\n  }\n\n  /**\n   * @notice Validates the health factor of a user.\n   * @param reservesData The state of all the reserves\n   * @param reservesList The addresses of all the active reserves\n   * @param eModeCategories The configuration of all the efficiency mode categories\n   * @param userConfig The state of the user for the specific reserve\n   * @param user The user to validate health factor of\n   * @param userEModeCategory The users active efficiency mode category\n   * @param reservesCount The number of available reserves\n   * @param oracle The price oracle\n   */\n  function validateHealthFactor(\n    mapping(address => DataTypes.ReserveData) storage reservesData,\n    mapping(uint256 => address) storage reservesList,\n    mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories,\n    DataTypes.UserConfigurationMap memory userConfig,\n    address user,\n    uint8 userEModeCategory,\n    uint256 reservesCount,\n    address oracle\n  ) internal view returns (uint256, bool) {\n    (, , , , uint256 healthFactor, bool hasZeroLtvCollateral) = GenericLogic\n      .calculateUserAccountData(\n        reservesData,\n        reservesList,\n        eModeCategories,\n        DataTypes.CalculateUserAccountDataParams({\n          userConfig: userConfig,\n          reservesCount: reservesCount,\n          user: user,\n          oracle: oracle,\n          userEModeCategory: userEModeCategory\n        })\n      );\n\n    require(\n      healthFactor >= HEALTH_FACTOR_LIQUIDATION_THRESHOLD,\n      Errors.HEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD\n    );\n\n    return (healthFactor, hasZeroLtvCollateral);\n  }\n\n  /**\n   * @notice Validates the health factor of a user and the ltv of the asset being withdrawn.\n   * @param reservesData The state of all the reserves\n   * @param reservesList The addresses of all the active reserves\n   * @param eModeCategories The configuration of all the efficiency mode categories\n   * @param userConfig The state of the user for the specific reserve\n   * @param asset The asset for which the ltv will be validated\n   * @param from The user from which the aTokens are being transferred\n   * @param reservesCount The number of available reserves\n   * @param oracle The price oracle\n   * @param userEModeCategory The users active efficiency mode category\n   */\n  function validateHFAndLtv(\n    mapping(address => DataTypes.ReserveData) storage reservesData,\n    mapping(uint256 => address) storage reservesList,\n    mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories,\n    DataTypes.UserConfigurationMap memory userConfig,\n    address asset,\n    address from,\n    uint256 reservesCount,\n    address oracle,\n    uint8 userEModeCategory\n  ) internal view {\n    DataTypes.ReserveData memory reserve = reservesData[asset];\n\n    (, bool hasZeroLtvCollateral) = validateHealthFactor(\n      reservesData,\n      reservesList,\n      eModeCategories,\n      userConfig,\n      from,\n      userEModeCategory,\n      reservesCount,\n      oracle\n    );\n\n    require(\n      !hasZeroLtvCollateral || reserve.configuration.getLtv() == 0,\n      Errors.LTV_VALIDATION_FAILED\n    );\n  }\n\n  /**\n   * @notice Validates a transfer action.\n   * @param reserve The reserve object\n   */\n  function validateTransfer(DataTypes.ReserveData storage reserve) internal view {\n    require(!reserve.configuration.getPaused(), Errors.RESERVE_PAUSED);\n  }\n\n  /**\n   * @notice Validates a drop reserve action.\n   * @param reservesList The addresses of all the active reserves\n   * @param reserve The reserve object\n   * @param asset The address of the reserve's underlying asset\n   */\n  function validateDropReserve(\n    mapping(uint256 => address) storage reservesList,\n    DataTypes.ReserveData storage reserve,\n    address asset\n  ) internal view {\n    require(asset != address(0), Errors.ZERO_ADDRESS_NOT_VALID);\n    require(reserve.id != 0 || reservesList[0] == asset, Errors.ASSET_NOT_LISTED);\n    require(IERC20(reserve.stableDebtTokenAddress).totalSupply() == 0, Errors.STABLE_DEBT_NOT_ZERO);\n    require(\n      IERC20(reserve.variableDebtTokenAddress).totalSupply() == 0,\n      Errors.VARIABLE_DEBT_SUPPLY_NOT_ZERO\n    );\n    require(\n      IERC20(reserve.aTokenAddress).totalSupply() == 0 && reserve.accruedToTreasury == 0,\n      Errors.UNDERLYING_CLAIMABLE_RIGHTS_NOT_ZERO\n    );\n  }\n\n  /**\n   * @notice Validates the action of setting efficiency mode.\n   * @param reservesData The state of all the reserves\n   * @param reservesList The addresses of all the active reserves\n   * @param eModeCategories a mapping storing configurations for all efficiency mode categories\n   * @param userConfig the user configuration\n   * @param reservesCount The total number of valid reserves\n   * @param categoryId The id of the category\n   */\n  function validateSetUserEMode(\n    mapping(address => DataTypes.ReserveData) storage reservesData,\n    mapping(uint256 => address) storage reservesList,\n    mapping(uint8 => DataTypes.EModeCategory) storage eModeCategories,\n    DataTypes.UserConfigurationMap memory userConfig,\n    uint256 reservesCount,\n    uint8 categoryId\n  ) internal view {\n    // category is invalid if the liq threshold is not set\n    require(\n      categoryId == 0 || eModeCategories[categoryId].liquidationThreshold != 0,\n      Errors.INCONSISTENT_EMODE_CATEGORY\n    );\n\n    // eMode can always be enabled if the user hasn't supplied anything\n    if (userConfig.isEmpty()) {\n      return;\n    }\n\n    // if user is trying to set another category than default we require that\n    // either the user is not borrowing, or it's borrowing assets of categoryId\n    if (categoryId != 0) {\n      unchecked {\n        for (uint256 i = 0; i < reservesCount; i++) {\n          if (userConfig.isBorrowing(i)) {\n            DataTypes.ReserveConfigurationMap memory configuration = reservesData[reservesList[i]]\n              .configuration;\n            require(\n              configuration.getEModeCategory() == categoryId,\n              Errors.INCONSISTENT_EMODE_CATEGORY\n            );\n          }\n        }\n      }\n    }\n  }\n\n  /**\n   * @notice Validates the action of activating the asset as collateral.\n   * @dev Only possible if the asset has non-zero LTV and the user is not in isolation mode\n   * @param reservesData The state of all the reserves\n   * @param reservesList The addresses of all the active reserves\n   * @param userConfig the user configuration\n   * @param reserveConfig The reserve configuration\n   * @return True if the asset can be activated as collateral, false otherwise\n   */\n  function validateUseAsCollateral(\n    mapping(address => DataTypes.ReserveData) storage reservesData,\n    mapping(uint256 => address) storage reservesList,\n    DataTypes.UserConfigurationMap storage userConfig,\n    DataTypes.ReserveConfigurationMap memory reserveConfig\n  ) internal view returns (bool) {\n    if (reserveConfig.getLtv() == 0) {\n      return false;\n    }\n    if (!userConfig.isUsingAsCollateralAny()) {\n      return true;\n    }\n    (bool isolationModeActive, , ) = userConfig.getIsolationModeState(reservesData, reservesList);\n\n    return (!isolationModeActive && reserveConfig.getDebtCeiling() == 0);\n  }\n\n  /**\n   * @notice Validates if an asset should be automatically activated as collateral in the following actions: supply,\n   * transfer, mint unbacked, and liquidate\n   * @dev This is used to ensure that isolated assets are not enabled as collateral automatically\n   * @param reservesData The state of all the reserves\n   * @param reservesList The addresses of all the active reserves\n   * @param userConfig the user configuration\n   * @param reserveConfig The reserve configuration\n   * @return True if the asset can be activated as collateral, false otherwise\n   */\n  function validateAutomaticUseAsCollateral(\n    mapping(address => DataTypes.ReserveData) storage reservesData,\n    mapping(uint256 => address) storage reservesList,\n    DataTypes.UserConfigurationMap storage userConfig,\n    DataTypes.ReserveConfigurationMap memory reserveConfig,\n    address aTokenAddress\n  ) internal view returns (bool) {\n    if (reserveConfig.getDebtCeiling() != 0) {\n      // ensures only the ISOLATED_COLLATERAL_SUPPLIER_ROLE can enable collateral as side-effect of an action\n      IPoolAddressesProvider addressesProvider = IncentivizedERC20(aTokenAddress)\n        .POOL()\n        .ADDRESSES_PROVIDER();\n      if (\n        !IAccessControl(addressesProvider.getACLManager()).hasRole(\n          ISOLATED_COLLATERAL_SUPPLIER_ROLE,\n          msg.sender\n        )\n      ) return false;\n    }\n    return validateUseAsCollateral(reservesData, reservesList, userConfig, reserveConfig);\n  }\n}\n"
      },
      "src/core/contracts/protocol/libraries/math/MathUtils.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {WadRayMath} from './WadRayMath.sol';\n\n/**\n * @title MathUtils library\n * @author Aave\n * @notice Provides functions to perform linear and compounded interest calculations\n */\nlibrary MathUtils {\n  using WadRayMath for uint256;\n\n  /// @dev Ignoring leap years\n  uint256 internal constant SECONDS_PER_YEAR = 365 days;\n\n  /**\n   * @dev Function to calculate the interest accumulated using a linear interest rate formula\n   * @param rate The interest rate, in ray\n   * @param lastUpdateTimestamp The timestamp of the last update of the interest\n   * @return The interest rate linearly accumulated during the timeDelta, in ray\n   */\n  function calculateLinearInterest(\n    uint256 rate,\n    uint40 lastUpdateTimestamp\n  ) internal view returns (uint256) {\n    //solium-disable-next-line\n    uint256 result = rate * (block.timestamp - uint256(lastUpdateTimestamp));\n    unchecked {\n      result = result / SECONDS_PER_YEAR;\n    }\n\n    return WadRayMath.RAY + result;\n  }\n\n  /**\n   * @dev Function to calculate the interest using a compounded interest rate formula\n   * To avoid expensive exponentiation, the calculation is performed using a binomial approximation:\n   *\n   *  (1+x)^n = 1+n*x+[n/2*(n-1)]*x^2+[n/6*(n-1)*(n-2)*x^3...\n   *\n   * The approximation slightly underpays liquidity providers and undercharges borrowers, with the advantage of great\n   * gas cost reductions. The whitepaper contains reference to the approximation and a table showing the margin of\n   * error per different time periods\n   *\n   * @param rate The interest rate, in ray\n   * @param lastUpdateTimestamp The timestamp of the last update of the interest\n   * @return The interest rate compounded during the timeDelta, in ray\n   */\n  function calculateCompoundedInterest(\n    uint256 rate,\n    uint40 lastUpdateTimestamp,\n    uint256 currentTimestamp\n  ) internal pure returns (uint256) {\n    //solium-disable-next-line\n    uint256 exp = currentTimestamp - uint256(lastUpdateTimestamp);\n\n    if (exp == 0) {\n      return WadRayMath.RAY;\n    }\n\n    uint256 expMinusOne;\n    uint256 expMinusTwo;\n    uint256 basePowerTwo;\n    uint256 basePowerThree;\n    unchecked {\n      expMinusOne = exp - 1;\n\n      expMinusTwo = exp > 2 ? exp - 2 : 0;\n\n      basePowerTwo = rate.rayMul(rate) / (SECONDS_PER_YEAR * SECONDS_PER_YEAR);\n      basePowerThree = basePowerTwo.rayMul(rate) / SECONDS_PER_YEAR;\n    }\n\n    uint256 secondTerm = exp * expMinusOne * basePowerTwo;\n    unchecked {\n      secondTerm /= 2;\n    }\n    uint256 thirdTerm = exp * expMinusOne * expMinusTwo * basePowerThree;\n    unchecked {\n      thirdTerm /= 6;\n    }\n\n    return WadRayMath.RAY + (rate * exp) / SECONDS_PER_YEAR + secondTerm + thirdTerm;\n  }\n\n  /**\n   * @dev Calculates the compounded interest between the timestamp of the last update and the current block timestamp\n   * @param rate The interest rate (in ray)\n   * @param lastUpdateTimestamp The timestamp from which the interest accumulation needs to be calculated\n   * @return The interest rate compounded between lastUpdateTimestamp and current block timestamp, in ray\n   */\n  function calculateCompoundedInterest(\n    uint256 rate,\n    uint40 lastUpdateTimestamp\n  ) internal view returns (uint256) {\n    return calculateCompoundedInterest(rate, lastUpdateTimestamp, block.timestamp);\n  }\n}\n"
      },
      "src/core/contracts/protocol/libraries/math/PercentageMath.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n/**\n * @title PercentageMath library\n * @author Aave\n * @notice Provides functions to perform percentage calculations\n * @dev Percentages are defined by default with 2 decimals of precision (100.00). The precision is indicated by PERCENTAGE_FACTOR\n * @dev Operations are rounded. If a value is >=.5, will be rounded up, otherwise rounded down.\n */\nlibrary PercentageMath {\n  // Maximum percentage factor (100.00%)\n  uint256 internal constant PERCENTAGE_FACTOR = 1e4;\n\n  // Half percentage factor (50.00%)\n  uint256 internal constant HALF_PERCENTAGE_FACTOR = 0.5e4;\n\n  /**\n   * @notice Executes a percentage multiplication\n   * @dev assembly optimized for improved gas savings, see https://twitter.com/transmissions11/status/1451131036377571328\n   * @param value The value of which the percentage needs to be calculated\n   * @param percentage The percentage of the value to be calculated\n   * @return result value percentmul percentage\n   */\n  function percentMul(uint256 value, uint256 percentage) internal pure returns (uint256 result) {\n    // to avoid overflow, value <= (type(uint256).max - HALF_PERCENTAGE_FACTOR) / percentage\n    assembly {\n      if iszero(\n        or(\n          iszero(percentage),\n          iszero(gt(value, div(sub(not(0), HALF_PERCENTAGE_FACTOR), percentage)))\n        )\n      ) {\n        revert(0, 0)\n      }\n\n      result := div(add(mul(value, percentage), HALF_PERCENTAGE_FACTOR), PERCENTAGE_FACTOR)\n    }\n  }\n\n  /**\n   * @notice Executes a percentage division\n   * @dev assembly optimized for improved gas savings, see https://twitter.com/transmissions11/status/1451131036377571328\n   * @param value The value of which the percentage needs to be calculated\n   * @param percentage The percentage of the value to be calculated\n   * @return result value percentdiv percentage\n   */\n  function percentDiv(uint256 value, uint256 percentage) internal pure returns (uint256 result) {\n    // to avoid overflow, value <= (type(uint256).max - halfPercentage) / PERCENTAGE_FACTOR\n    assembly {\n      if or(\n        iszero(percentage),\n        iszero(iszero(gt(value, div(sub(not(0), div(percentage, 2)), PERCENTAGE_FACTOR))))\n      ) {\n        revert(0, 0)\n      }\n\n      result := div(add(mul(value, PERCENTAGE_FACTOR), div(percentage, 2)), percentage)\n    }\n  }\n}\n"
      },
      "src/core/contracts/protocol/libraries/math/WadRayMath.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n/**\n * @title WadRayMath library\n * @author Aave\n * @notice Provides functions to perform calculations with Wad and Ray units\n * @dev Provides mul and div function for wads (decimal numbers with 18 digits of precision) and rays (decimal numbers\n * with 27 digits of precision)\n * @dev Operations are rounded. If a value is >=.5, will be rounded up, otherwise rounded down.\n */\nlibrary WadRayMath {\n  // HALF_WAD and HALF_RAY expressed with extended notation as constant with operations are not supported in Yul assembly\n  uint256 internal constant WAD = 1e18;\n  uint256 internal constant HALF_WAD = 0.5e18;\n\n  uint256 internal constant RAY = 1e27;\n  uint256 internal constant HALF_RAY = 0.5e27;\n\n  uint256 internal constant WAD_RAY_RATIO = 1e9;\n\n  /**\n   * @dev Multiplies two wad, rounding half up to the nearest wad\n   * @dev assembly optimized for improved gas savings, see https://twitter.com/transmissions11/status/1451131036377571328\n   * @param a Wad\n   * @param b Wad\n   * @return c = a*b, in wad\n   */\n  function wadMul(uint256 a, uint256 b) internal pure returns (uint256 c) {\n    // to avoid overflow, a <= (type(uint256).max - HALF_WAD) / b\n    assembly {\n      if iszero(or(iszero(b), iszero(gt(a, div(sub(not(0), HALF_WAD), b))))) {\n        revert(0, 0)\n      }\n\n      c := div(add(mul(a, b), HALF_WAD), WAD)\n    }\n  }\n\n  /**\n   * @dev Divides two wad, rounding half up to the nearest wad\n   * @dev assembly optimized for improved gas savings, see https://twitter.com/transmissions11/status/1451131036377571328\n   * @param a Wad\n   * @param b Wad\n   * @return c = a/b, in wad\n   */\n  function wadDiv(uint256 a, uint256 b) internal pure returns (uint256 c) {\n    // to avoid overflow, a <= (type(uint256).max - halfB) / WAD\n    assembly {\n      if or(iszero(b), iszero(iszero(gt(a, div(sub(not(0), div(b, 2)), WAD))))) {\n        revert(0, 0)\n      }\n\n      c := div(add(mul(a, WAD), div(b, 2)), b)\n    }\n  }\n\n  /**\n   * @notice Multiplies two ray, rounding half up to the nearest ray\n   * @dev assembly optimized for improved gas savings, see https://twitter.com/transmissions11/status/1451131036377571328\n   * @param a Ray\n   * @param b Ray\n   * @return c = a raymul b\n   */\n  function rayMul(uint256 a, uint256 b) internal pure returns (uint256 c) {\n    // to avoid overflow, a <= (type(uint256).max - HALF_RAY) / b\n    assembly {\n      if iszero(or(iszero(b), iszero(gt(a, div(sub(not(0), HALF_RAY), b))))) {\n        revert(0, 0)\n      }\n\n      c := div(add(mul(a, b), HALF_RAY), RAY)\n    }\n  }\n\n  /**\n   * @notice Divides two ray, rounding half up to the nearest ray\n   * @dev assembly optimized for improved gas savings, see https://twitter.com/transmissions11/status/1451131036377571328\n   * @param a Ray\n   * @param b Ray\n   * @return c = a raydiv b\n   */\n  function rayDiv(uint256 a, uint256 b) internal pure returns (uint256 c) {\n    // to avoid overflow, a <= (type(uint256).max - halfB) / RAY\n    assembly {\n      if or(iszero(b), iszero(iszero(gt(a, div(sub(not(0), div(b, 2)), RAY))))) {\n        revert(0, 0)\n      }\n\n      c := div(add(mul(a, RAY), div(b, 2)), b)\n    }\n  }\n\n  /**\n   * @dev Casts ray down to wad\n   * @dev assembly optimized for improved gas savings, see https://twitter.com/transmissions11/status/1451131036377571328\n   * @param a Ray\n   * @return b = a converted to wad, rounded half up to the nearest wad\n   */\n  function rayToWad(uint256 a) internal pure returns (uint256 b) {\n    assembly {\n      b := div(a, WAD_RAY_RATIO)\n      let remainder := mod(a, WAD_RAY_RATIO)\n      if iszero(lt(remainder, div(WAD_RAY_RATIO, 2))) {\n        b := add(b, 1)\n      }\n    }\n  }\n\n  /**\n   * @dev Converts wad up to ray\n   * @dev assembly optimized for improved gas savings, see https://twitter.com/transmissions11/status/1451131036377571328\n   * @param a Wad\n   * @return b = a converted in ray\n   */\n  function wadToRay(uint256 a) internal pure returns (uint256 b) {\n    // to avoid overflow, b/WAD_RAY_RATIO == a\n    assembly {\n      b := mul(a, WAD_RAY_RATIO)\n\n      if iszero(eq(div(b, WAD_RAY_RATIO), a)) {\n        revert(0, 0)\n      }\n    }\n  }\n}\n"
      },
      "src/core/contracts/protocol/libraries/types/ConfiguratorInputTypes.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nlibrary ConfiguratorInputTypes {\n  struct InitReserveInput {\n    address aTokenImpl;\n    address stableDebtTokenImpl;\n    address variableDebtTokenImpl;\n    uint8 underlyingAssetDecimals;\n    address interestRateStrategyAddress;\n    address underlyingAsset;\n    address treasury;\n    address incentivesController;\n    string aTokenName;\n    string aTokenSymbol;\n    string variableDebtTokenName;\n    string variableDebtTokenSymbol;\n    string stableDebtTokenName;\n    string stableDebtTokenSymbol;\n    bytes params;\n  }\n\n  struct UpdateATokenInput {\n    address asset;\n    address treasury;\n    address incentivesController;\n    string name;\n    string symbol;\n    address implementation;\n    bytes params;\n  }\n\n  struct UpdateDebtTokenInput {\n    address asset;\n    address incentivesController;\n    string name;\n    string symbol;\n    address implementation;\n    bytes params;\n  }\n}\n"
      },
      "src/core/contracts/protocol/libraries/types/DataTypes.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nlibrary DataTypes {\n  struct ReserveData {\n    //stores the reserve configuration\n    ReserveConfigurationMap configuration;\n    //the liquidity index. Expressed in ray\n    uint128 liquidityIndex;\n    //the current supply rate. Expressed in ray\n    uint128 currentLiquidityRate;\n    //variable borrow index. Expressed in ray\n    uint128 variableBorrowIndex;\n    //the current variable borrow rate. Expressed in ray\n    uint128 currentVariableBorrowRate;\n    //the current stable borrow rate. Expressed in ray\n    uint128 currentStableBorrowRate;\n    //timestamp of last update\n    uint40 lastUpdateTimestamp;\n    //the id of the reserve. Represents the position in the list of the active reserves\n    uint16 id;\n    //aToken address\n    address aTokenAddress;\n    //stableDebtToken address\n    address stableDebtTokenAddress;\n    //variableDebtToken address\n    address variableDebtTokenAddress;\n    //address of the interest rate strategy\n    address interestRateStrategyAddress;\n    //the current treasury balance, scaled\n    uint128 accruedToTreasury;\n    //the outstanding unbacked aTokens minted through the bridging feature\n    uint128 unbacked;\n    //the outstanding debt borrowed against this asset in isolation mode\n    uint128 isolationModeTotalDebt;\n  }\n\n  struct ReserveConfigurationMap {\n    //bit 0-15: LTV\n    //bit 16-31: Liq. threshold\n    //bit 32-47: Liq. bonus\n    //bit 48-55: Decimals\n    //bit 56: reserve is active\n    //bit 57: reserve is frozen\n    //bit 58: borrowing is enabled\n    //bit 59: stable rate borrowing enabled\n    //bit 60: asset is paused\n    //bit 61: borrowing in isolation mode is enabled\n    //bit 62: siloed borrowing enabled\n    //bit 63: flashloaning enabled\n    //bit 64-79: reserve factor\n    //bit 80-115 borrow cap in whole tokens, borrowCap == 0 => no cap\n    //bit 116-151 supply cap in whole tokens, supplyCap == 0 => no cap\n    //bit 152-167 liquidation protocol fee\n    //bit 168-175 eMode category\n    //bit 176-211 unbacked mint cap in whole tokens, unbackedMintCap == 0 => minting disabled\n    //bit 212-251 debt ceiling for isolation mode with (ReserveConfiguration::DEBT_CEILING_DECIMALS) decimals\n    //bit 252-255 unused\n\n    uint256 data;\n  }\n\n  struct UserConfigurationMap {\n    /**\n     * @dev Bitmap of the users collaterals and borrows. It is divided in pairs of bits, one pair per asset.\n     * The first bit indicates if an asset is used as collateral by the user, the second whether an\n     * asset is borrowed by the user.\n     */\n    uint256 data;\n  }\n\n  struct EModeCategory {\n    // each eMode category has a custom ltv and liquidation threshold\n    uint16 ltv;\n    uint16 liquidationThreshold;\n    uint16 liquidationBonus;\n    // each eMode category may or may not have a custom oracle to override the individual assets price oracles\n    address priceSource;\n    string label;\n  }\n\n  enum InterestRateMode {\n    NONE,\n    STABLE,\n    VARIABLE\n  }\n\n  struct ReserveCache {\n    uint256 currScaledVariableDebt;\n    uint256 nextScaledVariableDebt;\n    uint256 currPrincipalStableDebt;\n    uint256 currAvgStableBorrowRate;\n    uint256 currTotalStableDebt;\n    uint256 nextAvgStableBorrowRate;\n    uint256 nextTotalStableDebt;\n    uint256 currLiquidityIndex;\n    uint256 nextLiquidityIndex;\n    uint256 currVariableBorrowIndex;\n    uint256 nextVariableBorrowIndex;\n    uint256 currLiquidityRate;\n    uint256 currVariableBorrowRate;\n    uint256 reserveFactor;\n    ReserveConfigurationMap reserveConfiguration;\n    address aTokenAddress;\n    address stableDebtTokenAddress;\n    address variableDebtTokenAddress;\n    uint40 reserveLastUpdateTimestamp;\n    uint40 stableDebtLastUpdateTimestamp;\n  }\n\n  struct ExecuteLiquidationCallParams {\n    uint256 reservesCount;\n    uint256 debtToCover;\n    address collateralAsset;\n    address debtAsset;\n    address user;\n    bool receiveAToken;\n    address priceOracle;\n    uint8 userEModeCategory;\n    address priceOracleSentinel;\n  }\n\n  struct ExecuteSupplyParams {\n    address asset;\n    uint256 amount;\n    address onBehalfOf;\n    uint16 referralCode;\n  }\n\n  struct ExecuteBorrowParams {\n    address asset;\n    address user;\n    address onBehalfOf;\n    uint256 amount;\n    InterestRateMode interestRateMode;\n    uint16 referralCode;\n    bool releaseUnderlying;\n    uint256 maxStableRateBorrowSizePercent;\n    uint256 reservesCount;\n    address oracle;\n    uint8 userEModeCategory;\n    address priceOracleSentinel;\n  }\n\n  struct ExecuteRepayParams {\n    address asset;\n    uint256 amount;\n    InterestRateMode interestRateMode;\n    address onBehalfOf;\n    bool useATokens;\n  }\n\n  struct ExecuteWithdrawParams {\n    address asset;\n    uint256 amount;\n    address to;\n    uint256 reservesCount;\n    address oracle;\n    uint8 userEModeCategory;\n  }\n\n  struct ExecuteSetUserEModeParams {\n    uint256 reservesCount;\n    address oracle;\n    uint8 categoryId;\n  }\n\n  struct FinalizeTransferParams {\n    address asset;\n    address from;\n    address to;\n    uint256 amount;\n    uint256 balanceFromBefore;\n    uint256 balanceToBefore;\n    uint256 reservesCount;\n    address oracle;\n    uint8 fromEModeCategory;\n  }\n\n  struct FlashloanParams {\n    address receiverAddress;\n    address[] assets;\n    uint256[] amounts;\n    uint256[] interestRateModes;\n    address onBehalfOf;\n    bytes params;\n    uint16 referralCode;\n    uint256 flashLoanPremiumToProtocol;\n    uint256 flashLoanPremiumTotal;\n    uint256 maxStableRateBorrowSizePercent;\n    uint256 reservesCount;\n    address addressesProvider;\n    uint8 userEModeCategory;\n    bool isAuthorizedFlashBorrower;\n  }\n\n  struct FlashloanSimpleParams {\n    address receiverAddress;\n    address asset;\n    uint256 amount;\n    bytes params;\n    uint16 referralCode;\n    uint256 flashLoanPremiumToProtocol;\n    uint256 flashLoanPremiumTotal;\n  }\n\n  struct FlashLoanRepaymentParams {\n    uint256 amount;\n    uint256 totalPremium;\n    uint256 flashLoanPremiumToProtocol;\n    address asset;\n    address receiverAddress;\n    uint16 referralCode;\n  }\n\n  struct CalculateUserAccountDataParams {\n    UserConfigurationMap userConfig;\n    uint256 reservesCount;\n    address user;\n    address oracle;\n    uint8 userEModeCategory;\n  }\n\n  struct ValidateBorrowParams {\n    ReserveCache reserveCache;\n    UserConfigurationMap userConfig;\n    address asset;\n    address userAddress;\n    uint256 amount;\n    InterestRateMode interestRateMode;\n    uint256 maxStableLoanPercent;\n    uint256 reservesCount;\n    address oracle;\n    uint8 userEModeCategory;\n    address priceOracleSentinel;\n    bool isolationModeActive;\n    address isolationModeCollateralAddress;\n    uint256 isolationModeDebtCeiling;\n  }\n\n  struct ValidateLiquidationCallParams {\n    ReserveCache debtReserveCache;\n    uint256 totalDebt;\n    uint256 healthFactor;\n    address priceOracleSentinel;\n  }\n\n  struct CalculateInterestRatesParams {\n    uint256 unbacked;\n    uint256 liquidityAdded;\n    uint256 liquidityTaken;\n    uint256 totalStableDebt;\n    uint256 totalVariableDebt;\n    uint256 averageStableBorrowRate;\n    uint256 reserveFactor;\n    address reserve;\n    address aToken;\n  }\n\n  struct InitReserveParams {\n    address asset;\n    address aTokenAddress;\n    address stableDebtAddress;\n    address variableDebtAddress;\n    address interestRateStrategyAddress;\n    uint16 reservesCount;\n    uint16 maxNumberReserves;\n  }\n}\n"
      },
      "src/core/contracts/protocol/pool/DefaultReserveInterestRateStrategy.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {IERC20} from '../../dependencies/openzeppelin/contracts/IERC20.sol';\nimport {WadRayMath} from '../libraries/math/WadRayMath.sol';\nimport {PercentageMath} from '../libraries/math/PercentageMath.sol';\nimport {DataTypes} from '../libraries/types/DataTypes.sol';\nimport {Errors} from '../libraries/helpers/Errors.sol';\nimport {IDefaultInterestRateStrategy} from '../../interfaces/IDefaultInterestRateStrategy.sol';\nimport {IReserveInterestRateStrategy} from '../../interfaces/IReserveInterestRateStrategy.sol';\nimport {IPoolAddressesProvider} from '../../interfaces/IPoolAddressesProvider.sol';\n\n/**\n * @title DefaultReserveInterestRateStrategy contract\n * @author Aave\n * @notice Implements the calculation of the interest rates depending on the reserve state\n * @dev The model of interest rate is based on 2 slopes, one before the `OPTIMAL_USAGE_RATIO`\n * point of usage and another from that one to 100%.\n * - An instance of this same contract, can't be used across different Aave markets, due to the caching\n *   of the PoolAddressesProvider\n */\ncontract DefaultReserveInterestRateStrategy is IDefaultInterestRateStrategy {\n  using WadRayMath for uint256;\n  using PercentageMath for uint256;\n\n  /// @inheritdoc IDefaultInterestRateStrategy\n  uint256 public immutable OPTIMAL_USAGE_RATIO;\n\n  /// @inheritdoc IDefaultInterestRateStrategy\n  uint256 public immutable OPTIMAL_STABLE_TO_TOTAL_DEBT_RATIO;\n\n  /// @inheritdoc IDefaultInterestRateStrategy\n  uint256 public immutable MAX_EXCESS_USAGE_RATIO;\n\n  /// @inheritdoc IDefaultInterestRateStrategy\n  uint256 public immutable MAX_EXCESS_STABLE_TO_TOTAL_DEBT_RATIO;\n\n  IPoolAddressesProvider public immutable ADDRESSES_PROVIDER;\n\n  // Base variable borrow rate when usage rate = 0. Expressed in ray\n  uint256 internal immutable _baseVariableBorrowRate;\n\n  // Slope of the variable interest curve when usage ratio > 0 and <= OPTIMAL_USAGE_RATIO. Expressed in ray\n  uint256 internal immutable _variableRateSlope1;\n\n  // Slope of the variable interest curve when usage ratio > OPTIMAL_USAGE_RATIO. Expressed in ray\n  uint256 internal immutable _variableRateSlope2;\n\n  // Slope of the stable interest curve when usage ratio > 0 and <= OPTIMAL_USAGE_RATIO. Expressed in ray\n  uint256 internal immutable _stableRateSlope1;\n\n  // Slope of the stable interest curve when usage ratio > OPTIMAL_USAGE_RATIO. Expressed in ray\n  uint256 internal immutable _stableRateSlope2;\n\n  // Premium on top of `_variableRateSlope1` for base stable borrowing rate\n  uint256 internal immutable _baseStableRateOffset;\n\n  // Additional premium applied to stable rate when stable debt surpass `OPTIMAL_STABLE_TO_TOTAL_DEBT_RATIO`\n  uint256 internal immutable _stableRateExcessOffset;\n\n  /**\n   * @dev Constructor.\n   * @param provider The address of the PoolAddressesProvider contract\n   * @param optimalUsageRatio The optimal usage ratio\n   * @param baseVariableBorrowRate The base variable borrow rate\n   * @param variableRateSlope1 The variable rate slope below optimal usage ratio\n   * @param variableRateSlope2 The variable rate slope above optimal usage ratio\n   * @param stableRateSlope1 The stable rate slope below optimal usage ratio\n   * @param stableRateSlope2 The stable rate slope above optimal usage ratio\n   * @param baseStableRateOffset The premium on top of variable rate for base stable borrowing rate\n   * @param stableRateExcessOffset The premium on top of stable rate when there stable debt surpass the threshold\n   * @param optimalStableToTotalDebtRatio The optimal stable debt to total debt ratio of the reserve\n   */\n  constructor(\n    IPoolAddressesProvider provider,\n    uint256 optimalUsageRatio,\n    uint256 baseVariableBorrowRate,\n    uint256 variableRateSlope1,\n    uint256 variableRateSlope2,\n    uint256 stableRateSlope1,\n    uint256 stableRateSlope2,\n    uint256 baseStableRateOffset,\n    uint256 stableRateExcessOffset,\n    uint256 optimalStableToTotalDebtRatio\n  ) {\n    require(WadRayMath.RAY >= optimalUsageRatio, Errors.INVALID_OPTIMAL_USAGE_RATIO);\n    require(\n      WadRayMath.RAY >= optimalStableToTotalDebtRatio,\n      Errors.INVALID_OPTIMAL_STABLE_TO_TOTAL_DEBT_RATIO\n    );\n    OPTIMAL_USAGE_RATIO = optimalUsageRatio;\n    MAX_EXCESS_USAGE_RATIO = WadRayMath.RAY - optimalUsageRatio;\n    OPTIMAL_STABLE_TO_TOTAL_DEBT_RATIO = optimalStableToTotalDebtRatio;\n    MAX_EXCESS_STABLE_TO_TOTAL_DEBT_RATIO = WadRayMath.RAY - optimalStableToTotalDebtRatio;\n    ADDRESSES_PROVIDER = provider;\n    _baseVariableBorrowRate = baseVariableBorrowRate;\n    _variableRateSlope1 = variableRateSlope1;\n    _variableRateSlope2 = variableRateSlope2;\n    _stableRateSlope1 = stableRateSlope1;\n    _stableRateSlope2 = stableRateSlope2;\n    _baseStableRateOffset = baseStableRateOffset;\n    _stableRateExcessOffset = stableRateExcessOffset;\n  }\n\n  /// @inheritdoc IDefaultInterestRateStrategy\n  function getVariableRateSlope1() external view returns (uint256) {\n    return _variableRateSlope1;\n  }\n\n  /// @inheritdoc IDefaultInterestRateStrategy\n  function getVariableRateSlope2() external view returns (uint256) {\n    return _variableRateSlope2;\n  }\n\n  /// @inheritdoc IDefaultInterestRateStrategy\n  function getStableRateSlope1() external view returns (uint256) {\n    return _stableRateSlope1;\n  }\n\n  /// @inheritdoc IDefaultInterestRateStrategy\n  function getStableRateSlope2() external view returns (uint256) {\n    return _stableRateSlope2;\n  }\n\n  /// @inheritdoc IDefaultInterestRateStrategy\n  function getStableRateExcessOffset() external view returns (uint256) {\n    return _stableRateExcessOffset;\n  }\n\n  /// @inheritdoc IDefaultInterestRateStrategy\n  function getBaseStableBorrowRate() public view returns (uint256) {\n    return _variableRateSlope1 + _baseStableRateOffset;\n  }\n\n  /// @inheritdoc IDefaultInterestRateStrategy\n  function getBaseVariableBorrowRate() external view override returns (uint256) {\n    return _baseVariableBorrowRate;\n  }\n\n  /// @inheritdoc IDefaultInterestRateStrategy\n  function getMaxVariableBorrowRate() external view override returns (uint256) {\n    return _baseVariableBorrowRate + _variableRateSlope1 + _variableRateSlope2;\n  }\n\n  struct CalcInterestRatesLocalVars {\n    uint256 availableLiquidity;\n    uint256 totalDebt;\n    uint256 currentVariableBorrowRate;\n    uint256 currentStableBorrowRate;\n    uint256 currentLiquidityRate;\n    uint256 borrowUsageRatio;\n    uint256 supplyUsageRatio;\n    uint256 stableToTotalDebtRatio;\n    uint256 availableLiquidityPlusDebt;\n  }\n\n  /// @inheritdoc IReserveInterestRateStrategy\n  function calculateInterestRates(\n    DataTypes.CalculateInterestRatesParams memory params\n  ) public view override returns (uint256, uint256, uint256) {\n    CalcInterestRatesLocalVars memory vars;\n\n    vars.totalDebt = params.totalStableDebt + params.totalVariableDebt;\n\n    vars.currentLiquidityRate = 0;\n    vars.currentVariableBorrowRate = _baseVariableBorrowRate;\n    vars.currentStableBorrowRate = getBaseStableBorrowRate();\n\n    if (vars.totalDebt != 0) {\n      vars.stableToTotalDebtRatio = params.totalStableDebt.rayDiv(vars.totalDebt);\n      vars.availableLiquidity =\n        IERC20(params.reserve).balanceOf(params.aToken) +\n        params.liquidityAdded -\n        params.liquidityTaken;\n\n      vars.availableLiquidityPlusDebt = vars.availableLiquidity + vars.totalDebt;\n      vars.borrowUsageRatio = vars.totalDebt.rayDiv(vars.availableLiquidityPlusDebt);\n      vars.supplyUsageRatio = vars.totalDebt.rayDiv(\n        vars.availableLiquidityPlusDebt + params.unbacked\n      );\n    }\n\n    if (vars.borrowUsageRatio > OPTIMAL_USAGE_RATIO) {\n      uint256 excessBorrowUsageRatio = (vars.borrowUsageRatio - OPTIMAL_USAGE_RATIO).rayDiv(\n        MAX_EXCESS_USAGE_RATIO\n      );\n\n      vars.currentStableBorrowRate +=\n        _stableRateSlope1 +\n        _stableRateSlope2.rayMul(excessBorrowUsageRatio);\n\n      vars.currentVariableBorrowRate +=\n        _variableRateSlope1 +\n        _variableRateSlope2.rayMul(excessBorrowUsageRatio);\n    } else {\n      vars.currentStableBorrowRate += _stableRateSlope1.rayMul(vars.borrowUsageRatio).rayDiv(\n        OPTIMAL_USAGE_RATIO\n      );\n\n      vars.currentVariableBorrowRate += _variableRateSlope1.rayMul(vars.borrowUsageRatio).rayDiv(\n        OPTIMAL_USAGE_RATIO\n      );\n    }\n\n    if (vars.stableToTotalDebtRatio > OPTIMAL_STABLE_TO_TOTAL_DEBT_RATIO) {\n      uint256 excessStableDebtRatio = (vars.stableToTotalDebtRatio -\n        OPTIMAL_STABLE_TO_TOTAL_DEBT_RATIO).rayDiv(MAX_EXCESS_STABLE_TO_TOTAL_DEBT_RATIO);\n      vars.currentStableBorrowRate += _stableRateExcessOffset.rayMul(excessStableDebtRatio);\n    }\n\n    vars.currentLiquidityRate = _getOverallBorrowRate(\n      params.totalStableDebt,\n      params.totalVariableDebt,\n      vars.currentVariableBorrowRate,\n      params.averageStableBorrowRate\n    ).rayMul(vars.supplyUsageRatio).percentMul(\n        PercentageMath.PERCENTAGE_FACTOR - params.reserveFactor\n      );\n\n    return (\n      vars.currentLiquidityRate,\n      vars.currentStableBorrowRate,\n      vars.currentVariableBorrowRate\n    );\n  }\n\n  /**\n   * @dev Calculates the overall borrow rate as the weighted average between the total variable debt and total stable\n   * debt\n   * @param totalStableDebt The total borrowed from the reserve at a stable rate\n   * @param totalVariableDebt The total borrowed from the reserve at a variable rate\n   * @param currentVariableBorrowRate The current variable borrow rate of the reserve\n   * @param currentAverageStableBorrowRate The current weighted average of all the stable rate loans\n   * @return The weighted averaged borrow rate\n   */\n  function _getOverallBorrowRate(\n    uint256 totalStableDebt,\n    uint256 totalVariableDebt,\n    uint256 currentVariableBorrowRate,\n    uint256 currentAverageStableBorrowRate\n  ) internal pure returns (uint256) {\n    uint256 totalDebt = totalStableDebt + totalVariableDebt;\n\n    if (totalDebt == 0) return 0;\n\n    uint256 weightedVariableRate = totalVariableDebt.wadToRay().rayMul(currentVariableBorrowRate);\n\n    uint256 weightedStableRate = totalStableDebt.wadToRay().rayMul(currentAverageStableBorrowRate);\n\n    uint256 overallBorrowRate = (weightedVariableRate + weightedStableRate).rayDiv(\n      totalDebt.wadToRay()\n    );\n\n    return overallBorrowRate;\n  }\n}\n"
      },
      "src/core/contracts/protocol/tokenization/base/IncentivizedERC20.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport {Context} from '../../../dependencies/openzeppelin/contracts/Context.sol';\nimport {IERC20} from '../../../dependencies/openzeppelin/contracts/IERC20.sol';\nimport {IERC20Detailed} from '../../../dependencies/openzeppelin/contracts/IERC20Detailed.sol';\nimport {SafeCast} from '../../../dependencies/openzeppelin/contracts/SafeCast.sol';\nimport {WadRayMath} from '../../libraries/math/WadRayMath.sol';\nimport {Errors} from '../../libraries/helpers/Errors.sol';\nimport {IAaveIncentivesController} from '../../../interfaces/IAaveIncentivesController.sol';\nimport {IPoolAddressesProvider} from '../../../interfaces/IPoolAddressesProvider.sol';\nimport {IPool} from '../../../interfaces/IPool.sol';\nimport {IACLManager} from '../../../interfaces/IACLManager.sol';\n\n/**\n * @title IncentivizedERC20\n * @author Aave, inspired by the Openzeppelin ERC20 implementation\n * @notice Basic ERC20 implementation\n */\nabstract contract IncentivizedERC20 is Context, IERC20Detailed {\n  using WadRayMath for uint256;\n  using SafeCast for uint256;\n\n  /**\n   * @dev Only pool admin can call functions marked by this modifier.\n   */\n  modifier onlyPoolAdmin() {\n    IACLManager aclManager = IACLManager(_addressesProvider.getACLManager());\n    require(aclManager.isPoolAdmin(msg.sender), Errors.CALLER_NOT_POOL_ADMIN);\n    _;\n  }\n\n  /**\n   * @dev Only pool can call functions marked by this modifier.\n   */\n  modifier onlyPool() {\n    require(_msgSender() == address(POOL), Errors.CALLER_MUST_BE_POOL);\n    _;\n  }\n\n  /**\n   * @dev UserState - additionalData is a flexible field.\n   * ATokens and VariableDebtTokens use this field store the index of the\n   * user's last supply/withdrawal/borrow/repayment. StableDebtTokens use\n   * this field to store the user's stable rate.\n   */\n  struct UserState {\n    uint128 balance;\n    uint128 additionalData;\n  }\n  // Map of users address and their state data (userAddress => userStateData)\n  mapping(address => UserState) internal _userState;\n\n  // Map of allowances (delegator => delegatee => allowanceAmount)\n  mapping(address => mapping(address => uint256)) private _allowances;\n\n  uint256 internal _totalSupply;\n  string private _name;\n  string private _symbol;\n  uint8 private _decimals;\n  IAaveIncentivesController internal _incentivesController;\n  IPoolAddressesProvider internal immutable _addressesProvider;\n  IPool public immutable POOL;\n\n  /**\n   * @dev Constructor.\n   * @param pool The reference to the main Pool contract\n   * @param name The name of the token\n   * @param symbol The symbol of the token\n   * @param decimals The number of decimals of the token\n   */\n  constructor(IPool pool, string memory name, string memory symbol, uint8 decimals) {\n    _addressesProvider = pool.ADDRESSES_PROVIDER();\n    _name = name;\n    _symbol = symbol;\n    _decimals = decimals;\n    POOL = pool;\n  }\n\n  /// @inheritdoc IERC20Detailed\n  function name() public view override returns (string memory) {\n    return _name;\n  }\n\n  /// @inheritdoc IERC20Detailed\n  function symbol() external view override returns (string memory) {\n    return _symbol;\n  }\n\n  /// @inheritdoc IERC20Detailed\n  function decimals() external view override returns (uint8) {\n    return _decimals;\n  }\n\n  /// @inheritdoc IERC20\n  function totalSupply() public view virtual override returns (uint256) {\n    return _totalSupply;\n  }\n\n  /// @inheritdoc IERC20\n  function balanceOf(address account) public view virtual override returns (uint256) {\n    return _userState[account].balance;\n  }\n\n  /**\n   * @notice Returns the address of the Incentives Controller contract\n   * @return The address of the Incentives Controller\n   */\n  function getIncentivesController() external view virtual returns (IAaveIncentivesController) {\n    return _incentivesController;\n  }\n\n  /**\n   * @notice Sets a new Incentives Controller\n   * @param controller the new Incentives controller\n   */\n  function setIncentivesController(IAaveIncentivesController controller) external onlyPoolAdmin {\n    _incentivesController = controller;\n  }\n\n  /// @inheritdoc IERC20\n  function transfer(address recipient, uint256 amount) external virtual override returns (bool) {\n    uint128 castAmount = amount.toUint128();\n    _transfer(_msgSender(), recipient, castAmount);\n    return true;\n  }\n\n  /// @inheritdoc IERC20\n  function allowance(\n    address owner,\n    address spender\n  ) external view virtual override returns (uint256) {\n    return _allowances[owner][spender];\n  }\n\n  /// @inheritdoc IERC20\n  function approve(address spender, uint256 amount) external virtual override returns (bool) {\n    _approve(_msgSender(), spender, amount);\n    return true;\n  }\n\n  /// @inheritdoc IERC20\n  function transferFrom(\n    address sender,\n    address recipient,\n    uint256 amount\n  ) external virtual override returns (bool) {\n    uint128 castAmount = amount.toUint128();\n    _approve(sender, _msgSender(), _allowances[sender][_msgSender()] - castAmount);\n    _transfer(sender, recipient, castAmount);\n    return true;\n  }\n\n  /**\n   * @notice Increases the allowance of spender to spend _msgSender() tokens\n   * @param spender The user allowed to spend on behalf of _msgSender()\n   * @param addedValue The amount being added to the allowance\n   * @return `true`\n   */\n  function increaseAllowance(address spender, uint256 addedValue) external virtual returns (bool) {\n    _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);\n    return true;\n  }\n\n  /**\n   * @notice Decreases the allowance of spender to spend _msgSender() tokens\n   * @param spender The user allowed to spend on behalf of _msgSender()\n   * @param subtractedValue The amount being subtracted to the allowance\n   * @return `true`\n   */\n  function decreaseAllowance(\n    address spender,\n    uint256 subtractedValue\n  ) external virtual returns (bool) {\n    _approve(_msgSender(), spender, _allowances[_msgSender()][spender] - subtractedValue);\n    return true;\n  }\n\n  /**\n   * @notice Transfers tokens between two users and apply incentives if defined.\n   * @param sender The source address\n   * @param recipient The destination address\n   * @param amount The amount getting transferred\n   */\n  function _transfer(address sender, address recipient, uint128 amount) internal virtual {\n    uint128 oldSenderBalance = _userState[sender].balance;\n    _userState[sender].balance = oldSenderBalance - amount;\n    uint128 oldRecipientBalance = _userState[recipient].balance;\n    _userState[recipient].balance = oldRecipientBalance + amount;\n\n    IAaveIncentivesController incentivesControllerLocal = _incentivesController;\n    if (address(incentivesControllerLocal) != address(0)) {\n      uint256 currentTotalSupply = _totalSupply;\n      incentivesControllerLocal.handleAction(sender, currentTotalSupply, oldSenderBalance);\n      if (sender != recipient) {\n        incentivesControllerLocal.handleAction(recipient, currentTotalSupply, oldRecipientBalance);\n      }\n    }\n  }\n\n  /**\n   * @notice Approve `spender` to use `amount` of `owner`s balance\n   * @param owner The address owning the tokens\n   * @param spender The address approved for spending\n   * @param amount The amount of tokens to approve spending of\n   */\n  function _approve(address owner, address spender, uint256 amount) internal virtual {\n    _allowances[owner][spender] = amount;\n    emit Approval(owner, spender, amount);\n  }\n\n  /**\n   * @notice Update the name of the token\n   * @param newName The new name for the token\n   */\n  function _setName(string memory newName) internal {\n    _name = newName;\n  }\n\n  /**\n   * @notice Update the symbol for the token\n   * @param newSymbol The new symbol for the token\n   */\n  function _setSymbol(string memory newSymbol) internal {\n    _symbol = newSymbol;\n  }\n\n  /**\n   * @notice Update the number of decimals for the token\n   * @param newDecimals The new number of decimals for the token\n   */\n  function _setDecimals(uint8 newDecimals) internal {\n    _decimals = newDecimals;\n  }\n}\n"
      },
      "src/deployments/contracts/LibraryReportStorage.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport '../interfaces/ILibraryReportStorage.sol';\n\nabstract contract LibraryReportStorage is ILibraryReportStorage {\n  LibrariesReport internal _librariesReport;\n\n  function getLibrariesReport() public view returns (LibrariesReport memory) {\n    return _librariesReport;\n  }\n}\n"
      },
      "src/deployments/contracts/utilities/Create2Utils.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {StdUtils} from 'forge-std/StdUtils.sol';\n\nabstract contract Create2Utils is StdUtils {\n  address private constant CREATE2_FACTORY = 0x4e59b44847b379578588920cA78FbF26c0B4956C;\n\n  function _create2Deploy(bytes32 salt, bytes memory bytecode) internal returns (address) {\n    if (isContractDeployed(CREATE2_FACTORY) == false) {\n      revert('MISSING CREATE2_FACTORY');\n    }\n    address computed = computeCreate2Address(salt, hashInitCode(bytecode));\n\n    if (isContractDeployed(computed)) {\n      return computed;\n    } else {\n      bytes memory creationBytecode = abi.encodePacked(salt, bytecode);\n      bytes memory returnData;\n      (, returnData) = CREATE2_FACTORY.call(creationBytecode);\n      address deployedAt = address(uint160(bytes20(returnData)));\n      require(deployedAt == computed, 'failure at create2 address derivation');\n      return deployedAt;\n    }\n  }\n\n  function isContractDeployed(address _addr) internal view returns (bool isContract) {\n    return (_addr.code.length > 0);\n  }\n}\n"
      },
      "src/deployments/interfaces/ILibraryReportStorage.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport './IMarketReportTypes.sol';\n\ninterface ILibraryReportStorage {\n  function getLibrariesReport() external view returns (LibrariesReport memory);\n}\n"
      },
      "src/deployments/interfaces/IMarketReportTypes.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\nimport 'aave-v3-core/contracts/interfaces/IPoolAddressesProvider.sol';\nimport 'aave-v3-core/contracts/interfaces/IPoolAddressesProviderRegistry.sol';\nimport 'aave-v3-core/contracts/interfaces/IPool.sol';\nimport 'aave-v3-core/contracts/interfaces/IPoolConfigurator.sol';\nimport 'aave-v3-core/contracts/interfaces/IAaveOracle.sol';\nimport 'aave-v3-core/contracts/interfaces/IAToken.sol';\nimport 'aave-v3-core/contracts/interfaces/IVariableDebtToken.sol';\nimport 'aave-v3-core/contracts/interfaces/IStableDebtToken.sol';\nimport 'aave-v3-core/contracts/interfaces/IACLManager.sol';\nimport 'aave-v3-core/contracts/misc/AaveProtocolDataProvider.sol';\nimport 'aave-v3-periphery/contracts/misc/UiPoolDataProviderV3.sol';\nimport 'aave-v3-periphery/contracts/misc/UiIncentiveDataProviderV3.sol';\nimport 'aave-v3-periphery/contracts/rewards/interfaces/IEmissionManager.sol';\nimport 'aave-v3-periphery/contracts/rewards/interfaces/IRewardsController.sol';\nimport 'aave-v3-periphery/contracts/misc/WalletBalanceProvider.sol';\nimport 'aave-v3-periphery/contracts/adapters/paraswap/ParaSwapLiquiditySwapAdapter.sol';\nimport 'aave-v3-periphery/contracts/adapters/paraswap/ParaSwapRepayAdapter.sol';\nimport 'aave-v3-periphery/contracts/adapters/paraswap/ParaSwapWithdrawSwapAdapter.sol';\nimport 'aave-v3-periphery/contracts/misc/interfaces/IWrappedTokenGatewayV3.sol';\nimport 'aave-v3-core/contracts/misc/L2Encoder.sol';\nimport {ICollector} from 'aave-collector-unification/src/interfaces/ICollector.sol';\nimport {ProxyAdmin} from 'solidity-utils/contracts/transparent-proxy/ProxyAdmin.sol';\n\nstruct ContractsReport {\n  IPoolAddressesProviderRegistry poolAddressesProviderRegistry;\n  IPoolAddressesProvider poolAddressesProvider;\n  IPool poolProxy;\n  IPool poolImplementation;\n  IPoolConfigurator poolConfiguratorProxy;\n  IPoolConfigurator poolConfiguratorImplementation;\n  AaveProtocolDataProvider protocolDataProvider;\n  IAaveOracle aaveOracle;\n  IACLManager aclManager;\n  ICollector treasury;\n  ProxyAdmin proxyAdmin;\n  ICollector treasuryImplementation;\n  IWrappedTokenGatewayV3 wrappedTokenGateway;\n  WalletBalanceProvider walletBalanceProvider;\n  UiIncentiveDataProviderV3 uiIncentiveDataProvider;\n  UiPoolDataProviderV3 uiPoolDataProvider;\n  ParaSwapLiquiditySwapAdapter paraSwapLiquiditySwapAdapter;\n  ParaSwapRepayAdapter paraSwapRepayAdapter;\n  ParaSwapWithdrawSwapAdapter paraSwapWithdrawSwapAdapter;\n  L2Encoder l2Encoder;\n  IAToken aToken;\n  IVariableDebtToken variableDebtToken;\n  IStableDebtToken stableDebtToken;\n  IEmissionManager emissionManager;\n  IRewardsController rewardsControllerImplementation;\n  IRewardsController rewardsControllerProxy;\n}\n\nstruct MarketReport {\n  address poolAddressesProviderRegistry;\n  address poolAddressesProvider;\n  address poolProxy;\n  address poolImplementation;\n  address poolConfiguratorProxy;\n  address poolConfiguratorImplementation;\n  address protocolDataProvider;\n  address aaveOracle;\n  address aclManager;\n  address treasury;\n  address proxyAdmin;\n  address treasuryImplementation;\n  address wrappedTokenGateway;\n  address walletBalanceProvider;\n  address uiIncentiveDataProvider;\n  address uiPoolDataProvider;\n  address paraSwapLiquiditySwapAdapter;\n  address paraSwapRepayAdapter;\n  address paraSwapWithdrawSwapAdapter;\n  address l2Encoder;\n  address aToken;\n  address variableDebtToken;\n  address stableDebtToken;\n  address emissionManager;\n  address rewardsControllerImplementation;\n  address rewardsControllerProxy;\n}\n\nstruct LibrariesReport {\n  address borrowLogic;\n  address bridgeLogic;\n  address configuratorLogic;\n  address eModeLogic;\n  address flashLoanLogic;\n  address liquidationLogic;\n  address poolLogic;\n  address supplyLogic;\n}\n\nstruct Roles {\n  address marketOwner;\n  address poolAdmin;\n  address emergencyAdmin;\n}\n\nstruct MarketConfig {\n  address networkBaseTokenPriceInUsdProxyAggregator;\n  address marketReferenceCurrencyPriceInUsdProxyAggregator;\n  string marketId;\n  uint8 oracleDecimals;\n  address paraswapAugustusRegistry;\n  uint256 providerId;\n  bytes32 salt;\n  address wrappedNativeToken;\n  address proxyAdmin;\n  uint128 flashLoanPremiumTotal;\n  uint128 flashLoanPremiumToProtocol;\n}\n\nstruct DeployFlags {\n  bool l2;\n}\n\nstruct PoolReport {\n  address poolImplementation;\n  address poolConfiguratorImplementation;\n}\n\nstruct InitialReport {\n  address poolAddressesProvider;\n  address poolAddressesProviderRegistry;\n}\n\nstruct SetupReport {\n  address poolProxy;\n  address poolConfiguratorProxy;\n  address rewardsControllerProxy;\n  address aclManager;\n}\n\nstruct PeripheryReport {\n  address aaveOracle;\n  address proxyAdmin;\n  address treasury;\n  address treasuryImplementation;\n  address emissionManager;\n  address rewardsControllerImplementation;\n}\n\nstruct ParaswapReport {\n  address paraSwapLiquiditySwapAdapter;\n  address paraSwapRepayAdapter;\n  address paraSwapWithdrawSwapAdapter;\n}\n"
      },
      "src/deployments/projects/aave-v3-libraries/AaveV3LibrariesBatch1.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport '../../contracts/LibraryReportStorage.sol';\nimport {Create2Utils} from '../../contracts/utilities/Create2Utils.sol';\nimport {BorrowLogic} from 'aave-v3-core/contracts/protocol/libraries/logic/BorrowLogic.sol';\nimport {BridgeLogic} from 'aave-v3-core/contracts/protocol/libraries/logic/BridgeLogic.sol';\nimport {ConfiguratorLogic} from 'aave-v3-core/contracts/protocol/libraries/logic/ConfiguratorLogic.sol';\nimport {EModeLogic} from 'aave-v3-core/contracts/protocol/libraries/logic/EModeLogic.sol';\n\ncontract AaveV3LibrariesBatch1 is LibraryReportStorage, Create2Utils {\n  constructor() {\n    _librariesReport = _deployAaveV3Libraries();\n  }\n\n  function _deployAaveV3Libraries() internal returns (LibrariesReport memory libReport) {\n    bytes32 salt = keccak256('AAVE_V3_LIBRARIES_BATCH');\n\n    libReport.borrowLogic = _create2Deploy(salt, type(BorrowLogic).creationCode);\n    libReport.bridgeLogic = _create2Deploy(salt, type(BridgeLogic).creationCode);\n    libReport.configuratorLogic = _create2Deploy(salt, type(ConfiguratorLogic).creationCode);\n    libReport.eModeLogic = _create2Deploy(salt, type(EModeLogic).creationCode);\n    return libReport;\n  }\n}\n"
      },
      "src/periphery/contracts/adapters/paraswap/BaseParaSwapAdapter.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport {DataTypes} from 'aave-v3-core/contracts/protocol/libraries/types/DataTypes.sol';\nimport {FlashLoanSimpleReceiverBase} from 'aave-v3-core/contracts/flashloan/base/FlashLoanSimpleReceiverBase.sol';\nimport {GPv2SafeERC20} from 'aave-v3-core/contracts/dependencies/gnosis/contracts/GPv2SafeERC20.sol';\nimport {IERC20} from 'aave-v3-core/contracts/dependencies/openzeppelin/contracts/IERC20.sol';\nimport {IERC20Detailed} from 'aave-v3-core/contracts/dependencies/openzeppelin/contracts/IERC20Detailed.sol';\nimport {IERC20WithPermit} from 'aave-v3-core/contracts/interfaces/IERC20WithPermit.sol';\nimport {IPoolAddressesProvider} from 'aave-v3-core/contracts/interfaces/IPoolAddressesProvider.sol';\nimport {IPriceOracleGetter} from 'aave-v3-core/contracts/interfaces/IPriceOracleGetter.sol';\nimport {SafeMath} from 'aave-v3-core/contracts/dependencies/openzeppelin/contracts/SafeMath.sol';\nimport {Ownable} from 'aave-v3-core/contracts/dependencies/openzeppelin/contracts/Ownable.sol';\n\n/**\n * @title BaseParaSwapAdapter\n * @notice Utility functions for adapters using ParaSwap\n * @author Jason Raymond Bell\n */\nabstract contract BaseParaSwapAdapter is FlashLoanSimpleReceiverBase, Ownable {\n  using SafeMath for uint256;\n  using GPv2SafeERC20 for IERC20;\n  using GPv2SafeERC20 for IERC20Detailed;\n  using GPv2SafeERC20 for IERC20WithPermit;\n\n  struct PermitSignature {\n    uint256 amount;\n    uint256 deadline;\n    uint8 v;\n    bytes32 r;\n    bytes32 s;\n  }\n\n  // Max slippage percent allowed\n  uint256 public constant MAX_SLIPPAGE_PERCENT = 3000; // 30%\n\n  IPriceOracleGetter public immutable ORACLE;\n\n  event Swapped(\n    address indexed fromAsset,\n    address indexed toAsset,\n    uint256 fromAmount,\n    uint256 receivedAmount\n  );\n  event Bought(\n    address indexed fromAsset,\n    address indexed toAsset,\n    uint256 amountSold,\n    uint256 receivedAmount\n  );\n\n  constructor(\n    IPoolAddressesProvider addressesProvider\n  ) FlashLoanSimpleReceiverBase(addressesProvider) {\n    ORACLE = IPriceOracleGetter(addressesProvider.getPriceOracle());\n  }\n\n  /**\n   * @dev Get the price of the asset from the oracle denominated in eth\n   * @param asset address\n   * @return eth price for the asset\n   */\n  function _getPrice(address asset) internal view returns (uint256) {\n    return ORACLE.getAssetPrice(asset);\n  }\n\n  /**\n   * @dev Get the decimals of an asset\n   * @return number of decimals of the asset\n   */\n  function _getDecimals(IERC20Detailed asset) internal view returns (uint8) {\n    uint8 decimals = asset.decimals();\n    // Ensure 10**decimals won't overflow a uint256\n    require(decimals <= 77, 'TOO_MANY_DECIMALS_ON_TOKEN');\n    return decimals;\n  }\n\n  /**\n   * @dev Get the aToken associated to the asset\n   * @return address of the aToken\n   */\n  function _getReserveData(address asset) internal view returns (DataTypes.ReserveData memory) {\n    return POOL.getReserveData(asset);\n  }\n\n  function _pullATokenAndWithdraw(\n    address reserve,\n    address user,\n    uint256 amount,\n    PermitSignature memory permitSignature\n  ) internal {\n    IERC20WithPermit reserveAToken = IERC20WithPermit(\n      _getReserveData(address(reserve)).aTokenAddress\n    );\n    _pullATokenAndWithdraw(reserve, reserveAToken, user, amount, permitSignature);\n  }\n\n  /**\n   * @dev Pull the ATokens from the user\n   * @param reserve address of the asset\n   * @param reserveAToken address of the aToken of the reserve\n   * @param user address\n   * @param amount of tokens to be transferred to the contract\n   * @param permitSignature struct containing the permit signature\n   */\n  function _pullATokenAndWithdraw(\n    address reserve,\n    IERC20WithPermit reserveAToken,\n    address user,\n    uint256 amount,\n    PermitSignature memory permitSignature\n  ) internal {\n    // If deadline is set to zero, assume there is no signature for permit\n    if (permitSignature.deadline != 0) {\n      reserveAToken.permit(\n        user,\n        address(this),\n        permitSignature.amount,\n        permitSignature.deadline,\n        permitSignature.v,\n        permitSignature.r,\n        permitSignature.s\n      );\n    }\n\n    // transfer from user to adapter\n    reserveAToken.safeTransferFrom(user, address(this), amount);\n\n    // withdraw reserve\n    require(POOL.withdraw(reserve, amount, address(this)) == amount, 'UNEXPECTED_AMOUNT_WITHDRAWN');\n  }\n\n  /**\n   * @dev Emergency rescue for token stucked on this contract, as failsafe mechanism\n   * - Funds should never remain in this contract more time than during transactions\n   * - Only callable by the owner\n   */\n  function rescueTokens(IERC20 token) external onlyOwner {\n    token.safeTransfer(owner(), token.balanceOf(address(this)));\n  }\n}\n"
      },
      "src/periphery/contracts/adapters/paraswap/BaseParaSwapBuyAdapter.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport {SafeERC20} from 'aave-v3-core/contracts/dependencies/openzeppelin/contracts/SafeERC20.sol';\nimport {SafeMath} from 'aave-v3-core/contracts/dependencies/openzeppelin/contracts/SafeMath.sol';\nimport {PercentageMath} from 'aave-v3-core/contracts/protocol/libraries/math/PercentageMath.sol';\nimport {IPoolAddressesProvider} from 'aave-v3-core/contracts/interfaces/IPoolAddressesProvider.sol';\nimport {IERC20Detailed} from 'aave-v3-core/contracts/dependencies/openzeppelin/contracts/IERC20Detailed.sol';\nimport {IParaSwapAugustus} from './interfaces/IParaSwapAugustus.sol';\nimport {IParaSwapAugustusRegistry} from './interfaces/IParaSwapAugustusRegistry.sol';\nimport {BaseParaSwapAdapter} from './BaseParaSwapAdapter.sol';\n\n/**\n * @title BaseParaSwapBuyAdapter\n * @notice Implements the logic for buying tokens on ParaSwap\n */\nabstract contract BaseParaSwapBuyAdapter is BaseParaSwapAdapter {\n  using PercentageMath for uint256;\n  using SafeMath for uint256;\n  using SafeERC20 for IERC20Detailed;\n\n  IParaSwapAugustusRegistry public immutable AUGUSTUS_REGISTRY;\n\n  constructor(\n    IPoolAddressesProvider addressesProvider,\n    IParaSwapAugustusRegistry augustusRegistry\n  ) BaseParaSwapAdapter(addressesProvider) {\n    // Do something on Augustus registry to check the right contract was passed\n    require(!augustusRegistry.isValidAugustus(address(0)), 'Not a valid Augustus address');\n    AUGUSTUS_REGISTRY = augustusRegistry;\n  }\n\n  /**\n   * @dev Swaps a token for another using ParaSwap\n   * @param toAmountOffset Offset of toAmount in Augustus calldata if it should be overwritten, otherwise 0\n   * @param paraswapData Data for Paraswap Adapter\n   * @param assetToSwapFrom Address of the asset to be swapped from\n   * @param assetToSwapTo Address of the asset to be swapped to\n   * @param maxAmountToSwap Max amount to be swapped\n   * @param amountToReceive Amount to be received from the swap\n   * @return amountSold The amount sold during the swap\n   */\n  function _buyOnParaSwap(\n    uint256 toAmountOffset,\n    bytes memory paraswapData,\n    IERC20Detailed assetToSwapFrom,\n    IERC20Detailed assetToSwapTo,\n    uint256 maxAmountToSwap,\n    uint256 amountToReceive\n  ) internal returns (uint256 amountSold) {\n    (bytes memory buyCalldata, IParaSwapAugustus augustus) = abi.decode(\n      paraswapData,\n      (bytes, IParaSwapAugustus)\n    );\n\n    require(AUGUSTUS_REGISTRY.isValidAugustus(address(augustus)), 'INVALID_AUGUSTUS');\n\n    {\n      uint256 fromAssetDecimals = _getDecimals(assetToSwapFrom);\n      uint256 toAssetDecimals = _getDecimals(assetToSwapTo);\n\n      uint256 fromAssetPrice = _getPrice(address(assetToSwapFrom));\n      uint256 toAssetPrice = _getPrice(address(assetToSwapTo));\n\n      uint256 expectedMaxAmountToSwap = amountToReceive\n        .mul(toAssetPrice.mul(10 ** fromAssetDecimals))\n        .div(fromAssetPrice.mul(10 ** toAssetDecimals))\n        .percentMul(PercentageMath.PERCENTAGE_FACTOR.add(MAX_SLIPPAGE_PERCENT));\n\n      require(maxAmountToSwap <= expectedMaxAmountToSwap, 'maxAmountToSwap exceed max slippage');\n    }\n\n    uint256 balanceBeforeAssetFrom = assetToSwapFrom.balanceOf(address(this));\n    require(balanceBeforeAssetFrom >= maxAmountToSwap, 'INSUFFICIENT_BALANCE_BEFORE_SWAP');\n    uint256 balanceBeforeAssetTo = assetToSwapTo.balanceOf(address(this));\n\n    address tokenTransferProxy = augustus.getTokenTransferProxy();\n    assetToSwapFrom.safeApprove(tokenTransferProxy, 0);\n    assetToSwapFrom.safeApprove(tokenTransferProxy, maxAmountToSwap);\n\n    if (toAmountOffset != 0) {\n      // Ensure 256 bit (32 bytes) toAmountOffset value is within bounds of the\n      // calldata, not overlapping with the first 4 bytes (function selector).\n      require(\n        toAmountOffset >= 4 && toAmountOffset <= buyCalldata.length.sub(32),\n        'TO_AMOUNT_OFFSET_OUT_OF_RANGE'\n      );\n      // Overwrite the toAmount with the correct amount for the buy.\n      // In memory, buyCalldata consists of a 256 bit length field, followed by\n      // the actual bytes data, that is why 32 is added to the byte offset.\n      assembly {\n        mstore(add(buyCalldata, add(toAmountOffset, 32)), amountToReceive)\n      }\n    }\n    (bool success, ) = address(augustus).call(buyCalldata);\n    if (!success) {\n      // Copy revert reason from call\n      assembly {\n        returndatacopy(0, 0, returndatasize())\n        revert(0, returndatasize())\n      }\n    }\n\n    uint256 balanceAfterAssetFrom = assetToSwapFrom.balanceOf(address(this));\n    amountSold = balanceBeforeAssetFrom - balanceAfterAssetFrom;\n    require(amountSold <= maxAmountToSwap, 'WRONG_BALANCE_AFTER_SWAP');\n    uint256 amountReceived = assetToSwapTo.balanceOf(address(this)).sub(balanceBeforeAssetTo);\n    require(amountReceived >= amountToReceive, 'INSUFFICIENT_AMOUNT_RECEIVED');\n\n    emit Bought(address(assetToSwapFrom), address(assetToSwapTo), amountSold, amountReceived);\n  }\n}\n"
      },
      "src/periphery/contracts/adapters/paraswap/BaseParaSwapSellAdapter.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport {SafeERC20} from 'aave-v3-core/contracts/dependencies/openzeppelin/contracts/SafeERC20.sol';\nimport {SafeMath} from 'aave-v3-core/contracts/dependencies/openzeppelin/contracts/SafeMath.sol';\nimport {PercentageMath} from 'aave-v3-core/contracts/protocol/libraries/math/PercentageMath.sol';\nimport {IPoolAddressesProvider} from 'aave-v3-core/contracts/interfaces/IPoolAddressesProvider.sol';\nimport {IERC20Detailed} from 'aave-v3-core/contracts/dependencies/openzeppelin/contracts/IERC20Detailed.sol';\nimport {IParaSwapAugustus} from './interfaces/IParaSwapAugustus.sol';\nimport {IParaSwapAugustusRegistry} from './interfaces/IParaSwapAugustusRegistry.sol';\nimport {BaseParaSwapAdapter} from './BaseParaSwapAdapter.sol';\n\n/**\n * @title BaseParaSwapSellAdapter\n * @notice Implements the logic for selling tokens on ParaSwap\n * @author Jason Raymond Bell\n */\nabstract contract BaseParaSwapSellAdapter is BaseParaSwapAdapter {\n  using PercentageMath for uint256;\n  using SafeMath for uint256;\n  using SafeERC20 for IERC20Detailed;\n\n  IParaSwapAugustusRegistry public immutable AUGUSTUS_REGISTRY;\n\n  constructor(\n    IPoolAddressesProvider addressesProvider,\n    IParaSwapAugustusRegistry augustusRegistry\n  ) BaseParaSwapAdapter(addressesProvider) {\n    // Do something on Augustus registry to check the right contract was passed\n    require(!augustusRegistry.isValidAugustus(address(0)));\n    AUGUSTUS_REGISTRY = augustusRegistry;\n  }\n\n  /**\n   * @dev Swaps a token for another using ParaSwap\n   * @param fromAmountOffset Offset of fromAmount in Augustus calldata if it should be overwritten, otherwise 0\n   * @param swapCalldata Calldata for ParaSwap's AugustusSwapper contract\n   * @param augustus Address of ParaSwap's AugustusSwapper contract\n   * @param assetToSwapFrom Address of the asset to be swapped from\n   * @param assetToSwapTo Address of the asset to be swapped to\n   * @param amountToSwap Amount to be swapped\n   * @param minAmountToReceive Minimum amount to be received from the swap\n   * @return amountReceived The amount received from the swap\n   */\n  function _sellOnParaSwap(\n    uint256 fromAmountOffset,\n    bytes memory swapCalldata,\n    IParaSwapAugustus augustus,\n    IERC20Detailed assetToSwapFrom,\n    IERC20Detailed assetToSwapTo,\n    uint256 amountToSwap,\n    uint256 minAmountToReceive\n  ) internal returns (uint256 amountReceived) {\n    require(AUGUSTUS_REGISTRY.isValidAugustus(address(augustus)), 'INVALID_AUGUSTUS');\n\n    {\n      uint256 fromAssetDecimals = _getDecimals(assetToSwapFrom);\n      uint256 toAssetDecimals = _getDecimals(assetToSwapTo);\n\n      uint256 fromAssetPrice = _getPrice(address(assetToSwapFrom));\n      uint256 toAssetPrice = _getPrice(address(assetToSwapTo));\n\n      uint256 expectedMinAmountOut = amountToSwap\n        .mul(fromAssetPrice.mul(10 ** toAssetDecimals))\n        .div(toAssetPrice.mul(10 ** fromAssetDecimals))\n        .percentMul(PercentageMath.PERCENTAGE_FACTOR - MAX_SLIPPAGE_PERCENT);\n\n      require(expectedMinAmountOut <= minAmountToReceive, 'MIN_AMOUNT_EXCEEDS_MAX_SLIPPAGE');\n    }\n\n    uint256 balanceBeforeAssetFrom = assetToSwapFrom.balanceOf(address(this));\n    require(balanceBeforeAssetFrom >= amountToSwap, 'INSUFFICIENT_BALANCE_BEFORE_SWAP');\n    uint256 balanceBeforeAssetTo = assetToSwapTo.balanceOf(address(this));\n\n    address tokenTransferProxy = augustus.getTokenTransferProxy();\n    assetToSwapFrom.safeApprove(tokenTransferProxy, 0);\n    assetToSwapFrom.safeApprove(tokenTransferProxy, amountToSwap);\n\n    if (fromAmountOffset != 0) {\n      // Ensure 256 bit (32 bytes) fromAmount value is within bounds of the\n      // calldata, not overlapping with the first 4 bytes (function selector).\n      require(\n        fromAmountOffset >= 4 && fromAmountOffset <= swapCalldata.length.sub(32),\n        'FROM_AMOUNT_OFFSET_OUT_OF_RANGE'\n      );\n      // Overwrite the fromAmount with the correct amount for the swap.\n      // In memory, swapCalldata consists of a 256 bit length field, followed by\n      // the actual bytes data, that is why 32 is added to the byte offset.\n      assembly {\n        mstore(add(swapCalldata, add(fromAmountOffset, 32)), amountToSwap)\n      }\n    }\n    (bool success, ) = address(augustus).call(swapCalldata);\n    if (!success) {\n      // Copy revert reason from call\n      assembly {\n        returndatacopy(0, 0, returndatasize())\n        revert(0, returndatasize())\n      }\n    }\n    require(\n      assetToSwapFrom.balanceOf(address(this)) == balanceBeforeAssetFrom - amountToSwap,\n      'WRONG_BALANCE_AFTER_SWAP'\n    );\n    amountReceived = assetToSwapTo.balanceOf(address(this)).sub(balanceBeforeAssetTo);\n    require(amountReceived >= minAmountToReceive, 'INSUFFICIENT_AMOUNT_RECEIVED');\n\n    emit Swapped(address(assetToSwapFrom), address(assetToSwapTo), amountToSwap, amountReceived);\n  }\n}\n"
      },
      "src/periphery/contracts/adapters/paraswap/ParaSwapLiquiditySwapAdapter.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport {IERC20Detailed} from 'aave-v3-core/contracts/dependencies/openzeppelin/contracts/IERC20Detailed.sol';\nimport {IERC20WithPermit} from 'aave-v3-core/contracts/interfaces/IERC20WithPermit.sol';\nimport {IPoolAddressesProvider} from 'aave-v3-core/contracts/interfaces/IPoolAddressesProvider.sol';\nimport {SafeERC20} from 'aave-v3-core/contracts/dependencies/openzeppelin/contracts/SafeERC20.sol';\nimport {SafeMath} from 'aave-v3-core/contracts/dependencies/openzeppelin/contracts/SafeMath.sol';\nimport {BaseParaSwapSellAdapter} from './BaseParaSwapSellAdapter.sol';\nimport {IParaSwapAugustusRegistry} from './interfaces/IParaSwapAugustusRegistry.sol';\nimport {IParaSwapAugustus} from './interfaces/IParaSwapAugustus.sol';\nimport {ReentrancyGuard} from '../../dependencies/openzeppelin/ReentrancyGuard.sol';\n\n/**\n * @title ParaSwapLiquiditySwapAdapter\n * @notice Adapter to swap liquidity using ParaSwap.\n * @author Jason Raymond Bell\n */\ncontract ParaSwapLiquiditySwapAdapter is BaseParaSwapSellAdapter, ReentrancyGuard {\n  using SafeMath for uint256;\n  using SafeERC20 for IERC20Detailed;\n\n  constructor(\n    IPoolAddressesProvider addressesProvider,\n    IParaSwapAugustusRegistry augustusRegistry,\n    address owner\n  ) BaseParaSwapSellAdapter(addressesProvider, augustusRegistry) {\n    transferOwnership(owner);\n  }\n\n  /**\n   * @dev Swaps the received reserve amount from the flash loan into the asset specified in the params.\n   * The received funds from the swap are then deposited into the protocol on behalf of the user.\n   * The user should give this contract allowance to pull the ATokens in order to withdraw the underlying asset and repay the flash loan.\n   * @param asset The address of the flash-borrowed asset\n   * @param amount The amount of the flash-borrowed asset\n   * @param premium The fee of the flash-borrowed asset\n   * @param initiator The address of the flashloan initiator\n   * @param params The byte-encoded params passed when initiating the flashloan\n   * @return True if the execution of the operation succeeds, false otherwise\n   *   address assetToSwapTo Address of the underlying asset to be swapped to and deposited\n   *   uint256 minAmountToReceive Min amount to be received from the swap\n   *   uint256 swapAllBalanceOffset Set to offset of fromAmount in Augustus calldata if wanting to swap all balance, otherwise 0\n   *   bytes swapCalldata Calldata for ParaSwap's AugustusSwapper contract\n   *   address augustus Address of ParaSwap's AugustusSwapper contract\n   *   PermitSignature permitParams Struct containing the permit signatures, set to all zeroes if not used\n   */\n  function executeOperation(\n    address asset,\n    uint256 amount,\n    uint256 premium,\n    address initiator,\n    bytes calldata params\n  ) external override nonReentrant returns (bool) {\n    require(msg.sender == address(POOL), 'CALLER_MUST_BE_POOL');\n\n    uint256 flashLoanAmount = amount;\n    uint256 premiumLocal = premium;\n    address initiatorLocal = initiator;\n    IERC20Detailed assetToSwapFrom = IERC20Detailed(asset);\n    (\n      IERC20Detailed assetToSwapTo,\n      uint256 minAmountToReceive,\n      uint256 swapAllBalanceOffset,\n      bytes memory swapCalldata,\n      IParaSwapAugustus augustus,\n      PermitSignature memory permitParams\n    ) = abi.decode(\n        params,\n        (IERC20Detailed, uint256, uint256, bytes, IParaSwapAugustus, PermitSignature)\n      );\n\n    _swapLiquidity(\n      swapAllBalanceOffset,\n      swapCalldata,\n      augustus,\n      permitParams,\n      flashLoanAmount,\n      premiumLocal,\n      initiatorLocal,\n      assetToSwapFrom,\n      assetToSwapTo,\n      minAmountToReceive\n    );\n\n    return true;\n  }\n\n  /**\n   * @dev Swaps an amount of an asset to another and deposits the new asset amount on behalf of the user without using a flash loan.\n   * This method can be used when the temporary transfer of the collateral asset to this contract does not affect the user position.\n   * The user should give this contract allowance to pull the ATokens in order to withdraw the underlying asset and perform the swap.\n   * @param assetToSwapFrom Address of the underlying asset to be swapped from\n   * @param assetToSwapTo Address of the underlying asset to be swapped to and deposited\n   * @param amountToSwap Amount to be swapped, or maximum amount when swapping all balance\n   * @param minAmountToReceive Minimum amount to be received from the swap\n   * @param swapAllBalanceOffset Set to offset of fromAmount in Augustus calldata if wanting to swap all balance, otherwise 0\n   * @param swapCalldata Calldata for ParaSwap's AugustusSwapper contract\n   * @param augustus Address of ParaSwap's AugustusSwapper contract\n   * @param permitParams Struct containing the permit signatures, set to all zeroes if not used\n   */\n  function swapAndDeposit(\n    IERC20Detailed assetToSwapFrom,\n    IERC20Detailed assetToSwapTo,\n    uint256 amountToSwap,\n    uint256 minAmountToReceive,\n    uint256 swapAllBalanceOffset,\n    bytes calldata swapCalldata,\n    IParaSwapAugustus augustus,\n    PermitSignature calldata permitParams\n  ) external nonReentrant {\n    IERC20WithPermit aToken = IERC20WithPermit(\n      _getReserveData(address(assetToSwapFrom)).aTokenAddress\n    );\n\n    if (swapAllBalanceOffset != 0) {\n      uint256 balance = aToken.balanceOf(msg.sender);\n      require(balance <= amountToSwap, 'INSUFFICIENT_AMOUNT_TO_SWAP');\n      amountToSwap = balance;\n    }\n\n    _pullATokenAndWithdraw(\n      address(assetToSwapFrom),\n      aToken,\n      msg.sender,\n      amountToSwap,\n      permitParams\n    );\n\n    uint256 amountReceived = _sellOnParaSwap(\n      swapAllBalanceOffset,\n      swapCalldata,\n      augustus,\n      assetToSwapFrom,\n      assetToSwapTo,\n      amountToSwap,\n      minAmountToReceive\n    );\n\n    assetToSwapTo.safeApprove(address(POOL), 0);\n    assetToSwapTo.safeApprove(address(POOL), amountReceived);\n    POOL.deposit(address(assetToSwapTo), amountReceived, msg.sender, 0);\n  }\n\n  /**\n   * @dev Swaps an amount of an asset to another and deposits the funds on behalf of the initiator.\n   * @param swapAllBalanceOffset Set to offset of fromAmount in Augustus calldata if wanting to swap all balance, otherwise 0\n   * @param swapCalldata Calldata for ParaSwap's AugustusSwapper contract\n   * @param augustus Address of ParaSwap's AugustusSwapper contract\n   * @param permitParams Struct containing the permit signatures, set to all zeroes if not used\n   * @param flashLoanAmount Amount of the flash loan i.e. maximum amount to swap\n   * @param premium Fee of the flash loan\n   * @param initiator Account that initiated the flash loan\n   * @param assetToSwapFrom Address of the underyling asset to be swapped from\n   * @param assetToSwapTo Address of the underlying asset to be swapped to and deposited\n   * @param minAmountToReceive Min amount to be received from the swap\n   */\n  function _swapLiquidity(\n    uint256 swapAllBalanceOffset,\n    bytes memory swapCalldata,\n    IParaSwapAugustus augustus,\n    PermitSignature memory permitParams,\n    uint256 flashLoanAmount,\n    uint256 premium,\n    address initiator,\n    IERC20Detailed assetToSwapFrom,\n    IERC20Detailed assetToSwapTo,\n    uint256 minAmountToReceive\n  ) internal {\n    IERC20WithPermit aToken = IERC20WithPermit(\n      _getReserveData(address(assetToSwapFrom)).aTokenAddress\n    );\n    uint256 amountToSwap = flashLoanAmount;\n\n    uint256 balance = aToken.balanceOf(initiator);\n    if (swapAllBalanceOffset != 0) {\n      uint256 balanceToSwap = balance.sub(premium);\n      require(balanceToSwap <= amountToSwap, 'INSUFFICIENT_AMOUNT_TO_SWAP');\n      amountToSwap = balanceToSwap;\n    } else {\n      require(balance >= amountToSwap.add(premium), 'INSUFFICIENT_ATOKEN_BALANCE');\n    }\n\n    uint256 amountReceived = _sellOnParaSwap(\n      swapAllBalanceOffset,\n      swapCalldata,\n      augustus,\n      assetToSwapFrom,\n      assetToSwapTo,\n      amountToSwap,\n      minAmountToReceive\n    );\n\n    assetToSwapTo.safeApprove(address(POOL), 0);\n    assetToSwapTo.safeApprove(address(POOL), amountReceived);\n    POOL.deposit(address(assetToSwapTo), amountReceived, initiator, 0);\n\n    _pullATokenAndWithdraw(\n      address(assetToSwapFrom),\n      aToken,\n      initiator,\n      amountToSwap.add(premium),\n      permitParams\n    );\n\n    // Repay flash loan\n    assetToSwapFrom.safeApprove(address(POOL), 0);\n    assetToSwapFrom.safeApprove(address(POOL), flashLoanAmount.add(premium));\n  }\n}\n"
      },
      "src/periphery/contracts/adapters/paraswap/ParaSwapRepayAdapter.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport {DataTypes} from 'aave-v3-core/contracts/protocol/libraries/types/DataTypes.sol';\nimport {IERC20Detailed} from 'aave-v3-core/contracts/dependencies/openzeppelin/contracts/IERC20Detailed.sol';\nimport {IERC20} from 'aave-v3-core/contracts/dependencies/openzeppelin/contracts/IERC20.sol';\nimport {IERC20WithPermit} from 'aave-v3-core/contracts/interfaces/IERC20WithPermit.sol';\nimport {IPoolAddressesProvider} from 'aave-v3-core/contracts/interfaces/IPoolAddressesProvider.sol';\nimport {SafeERC20} from 'aave-v3-core/contracts/dependencies/openzeppelin/contracts/SafeERC20.sol';\nimport {SafeMath} from 'aave-v3-core/contracts/dependencies/openzeppelin/contracts/SafeMath.sol';\nimport {BaseParaSwapBuyAdapter} from './BaseParaSwapBuyAdapter.sol';\nimport {IParaSwapAugustusRegistry} from './interfaces/IParaSwapAugustusRegistry.sol';\nimport {IParaSwapAugustus} from './interfaces/IParaSwapAugustus.sol';\nimport {ReentrancyGuard} from '../../dependencies/openzeppelin/ReentrancyGuard.sol';\n\n/**\n * @title ParaSwapRepayAdapter\n * @notice ParaSwap Adapter to perform a repay of a debt with collateral.\n * @author Aave\n **/\ncontract ParaSwapRepayAdapter is BaseParaSwapBuyAdapter, ReentrancyGuard {\n  using SafeMath for uint256;\n  using SafeERC20 for IERC20;\n\n  struct RepayParams {\n    address collateralAsset;\n    uint256 collateralAmount;\n    uint256 rateMode;\n    PermitSignature permitSignature;\n    bool useEthPath;\n  }\n\n  constructor(\n    IPoolAddressesProvider addressesProvider,\n    IParaSwapAugustusRegistry augustusRegistry,\n    address owner\n  ) BaseParaSwapBuyAdapter(addressesProvider, augustusRegistry) {\n    transferOwnership(owner);\n  }\n\n  /**\n   * @dev Uses the received funds from the flash loan to repay a debt on the protocol on behalf of the user. Then pulls\n   * the collateral from the user and swaps it to the debt asset to repay the flash loan.\n   * The user should give this contract allowance to pull the ATokens in order to withdraw the underlying asset, swap it\n   * and repay the flash loan.\n   * Supports only one asset on the flash loan.\n   * @param asset The address of the flash-borrowed asset\n   * @param amount The amount of the flash-borrowed asset\n   * @param premium The fee of the flash-borrowed asset\n   * @param initiator The address of the flashloan initiator\n   * @param params The byte-encoded params passed when initiating the flashloan\n   * @return True if the execution of the operation succeeds, false otherwise\n   *   IERC20Detailed debtAsset Address of the debt asset\n   *   uint256 debtAmount Amount of debt to be repaid\n   *   uint256 rateMode Rate modes of the debt to be repaid\n   *   uint256 deadline Deadline for the permit signature\n   *   uint256 debtRateMode Rate mode of the debt to be repaid\n   *   bytes paraswapData Paraswap Data\n   *                    * bytes buyCallData Call data for augustus\n   *                    * IParaSwapAugustus augustus Address of Augustus Swapper\n   *   PermitSignature permitParams Struct containing the permit signatures, set to all zeroes if not used\n   */\n  function executeOperation(\n    address asset,\n    uint256 amount,\n    uint256 premium,\n    address initiator,\n    bytes calldata params\n  ) external override nonReentrant returns (bool) {\n    require(msg.sender == address(POOL), 'CALLER_MUST_BE_POOL');\n\n    uint256 collateralAmount = amount;\n    address initiatorLocal = initiator;\n\n    IERC20Detailed collateralAsset = IERC20Detailed(asset);\n\n    _swapAndRepay(params, premium, initiatorLocal, collateralAsset, collateralAmount);\n\n    return true;\n  }\n\n  /**\n   * @dev Swaps the user collateral for the debt asset and then repay the debt on the protocol on behalf of the user\n   * without using flash loans. This method can be used when the temporary transfer of the collateral asset to this\n   * contract does not affect the user position.\n   * The user should give this contract allowance to pull the ATokens in order to withdraw the underlying asset\n   * @param collateralAsset Address of asset to be swapped\n   * @param debtAsset Address of debt asset\n   * @param collateralAmount max Amount of the collateral to be swapped\n   * @param debtRepayAmount Amount of the debt to be repaid, or maximum amount when repaying entire debt\n   * @param debtRateMode Rate mode of the debt to be repaid\n   * @param buyAllBalanceOffset Set to offset of toAmount in Augustus calldata if wanting to pay entire debt, otherwise 0\n   * @param paraswapData Data for Paraswap Adapter\n   * @param permitSignature struct containing the permit signature\n   */\n  function swapAndRepay(\n    IERC20Detailed collateralAsset,\n    IERC20Detailed debtAsset,\n    uint256 collateralAmount,\n    uint256 debtRepayAmount,\n    uint256 debtRateMode,\n    uint256 buyAllBalanceOffset,\n    bytes calldata paraswapData,\n    PermitSignature calldata permitSignature\n  ) external nonReentrant {\n    debtRepayAmount = getDebtRepayAmount(\n      debtAsset,\n      debtRateMode,\n      buyAllBalanceOffset,\n      debtRepayAmount,\n      msg.sender\n    );\n\n    // Pull aTokens from user\n    _pullATokenAndWithdraw(address(collateralAsset), msg.sender, collateralAmount, permitSignature);\n    //buy debt asset using collateral asset\n    uint256 amountSold = _buyOnParaSwap(\n      buyAllBalanceOffset,\n      paraswapData,\n      collateralAsset,\n      debtAsset,\n      collateralAmount,\n      debtRepayAmount\n    );\n\n    uint256 collateralBalanceLeft = collateralAmount - amountSold;\n\n    //deposit collateral back in the pool, if left after the swap(buy)\n    if (collateralBalanceLeft > 0) {\n      IERC20(collateralAsset).safeApprove(address(POOL), 0);\n      IERC20(collateralAsset).safeApprove(address(POOL), collateralBalanceLeft);\n      POOL.deposit(address(collateralAsset), collateralBalanceLeft, msg.sender, 0);\n    }\n\n    // Repay debt. Approves 0 first to comply with tokens that implement the anti frontrunning approval fix\n    IERC20(debtAsset).safeApprove(address(POOL), 0);\n    IERC20(debtAsset).safeApprove(address(POOL), debtRepayAmount);\n    POOL.repay(address(debtAsset), debtRepayAmount, debtRateMode, msg.sender);\n  }\n\n  /**\n   * @dev Perform the repay of the debt, pulls the initiator collateral and swaps to repay the flash loan\n   * @param premium Fee of the flash loan\n   * @param initiator Address of the user\n   * @param collateralAsset Address of token to be swapped\n   * @param collateralAmount Amount of the reserve to be swapped(flash loan amount)\n   */\n\n  function _swapAndRepay(\n    bytes calldata params,\n    uint256 premium,\n    address initiator,\n    IERC20Detailed collateralAsset,\n    uint256 collateralAmount\n  ) private {\n    (\n      IERC20Detailed debtAsset,\n      uint256 debtRepayAmount,\n      uint256 buyAllBalanceOffset,\n      uint256 rateMode,\n      bytes memory paraswapData,\n      PermitSignature memory permitSignature\n    ) = abi.decode(params, (IERC20Detailed, uint256, uint256, uint256, bytes, PermitSignature));\n\n    debtRepayAmount = getDebtRepayAmount(\n      debtAsset,\n      rateMode,\n      buyAllBalanceOffset,\n      debtRepayAmount,\n      initiator\n    );\n\n    uint256 amountSold = _buyOnParaSwap(\n      buyAllBalanceOffset,\n      paraswapData,\n      collateralAsset,\n      debtAsset,\n      collateralAmount,\n      debtRepayAmount\n    );\n\n    // Repay debt. Approves for 0 first to comply with tokens that implement the anti frontrunning approval fix.\n    IERC20(debtAsset).safeApprove(address(POOL), 0);\n    IERC20(debtAsset).safeApprove(address(POOL), debtRepayAmount);\n    POOL.repay(address(debtAsset), debtRepayAmount, rateMode, initiator);\n\n    uint256 neededForFlashLoanRepay = amountSold.add(premium);\n\n    // Pull aTokens from user\n    _pullATokenAndWithdraw(\n      address(collateralAsset),\n      initiator,\n      neededForFlashLoanRepay,\n      permitSignature\n    );\n\n    // Repay flashloan. Approves for 0 first to comply with tokens that implement the anti frontrunning approval fix.\n    IERC20(collateralAsset).safeApprove(address(POOL), 0);\n    IERC20(collateralAsset).safeApprove(address(POOL), collateralAmount.add(premium));\n  }\n\n  function getDebtRepayAmount(\n    IERC20Detailed debtAsset,\n    uint256 rateMode,\n    uint256 buyAllBalanceOffset,\n    uint256 debtRepayAmount,\n    address initiator\n  ) private view returns (uint256) {\n    DataTypes.ReserveData memory debtReserveData = _getReserveData(address(debtAsset));\n\n    address debtToken = DataTypes.InterestRateMode(rateMode) == DataTypes.InterestRateMode.STABLE\n      ? debtReserveData.stableDebtTokenAddress\n      : debtReserveData.variableDebtTokenAddress;\n\n    uint256 currentDebt = IERC20(debtToken).balanceOf(initiator);\n\n    if (buyAllBalanceOffset != 0) {\n      require(currentDebt <= debtRepayAmount, 'INSUFFICIENT_AMOUNT_TO_REPAY');\n      debtRepayAmount = currentDebt;\n    } else {\n      require(debtRepayAmount <= currentDebt, 'INVALID_DEBT_REPAY_AMOUNT');\n    }\n\n    return debtRepayAmount;\n  }\n}\n"
      },
      "src/periphery/contracts/adapters/paraswap/ParaSwapWithdrawSwapAdapter.sol": {
        "content": "// SPDX-License-Identifier: AGPL-3.0\npragma solidity ^0.8.10;\n\nimport {IERC20Detailed} from 'aave-v3-core/contracts/dependencies/openzeppelin/contracts/IERC20Detailed.sol';\nimport {IERC20WithPermit} from 'aave-v3-core/contracts/interfaces/IERC20WithPermit.sol';\nimport {IPoolAddressesProvider} from 'aave-v3-core/contracts/interfaces/IPoolAddressesProvider.sol';\nimport {BaseParaSwapSellAdapter} from './BaseParaSwapSellAdapter.sol';\nimport {IParaSwapAugustusRegistry} from './interfaces/IParaSwapAugustusRegistry.sol';\nimport {SafeERC20} from 'aave-v3-core/contracts/dependencies/openzeppelin/contracts/SafeERC20.sol';\nimport {IParaSwapAugustus} from './interfaces/IParaSwapAugustus.sol';\nimport {ReentrancyGuard} from '../../dependencies/openzeppelin/ReentrancyGuard.sol';\n\ncontract ParaSwapWithdrawSwapAdapter is BaseParaSwapSellAdapter, ReentrancyGuard {\n  using SafeERC20 for IERC20Detailed;\n\n  constructor(\n    IPoolAddressesProvider addressesProvider,\n    IParaSwapAugustusRegistry augustusRegistry,\n    address owner\n  ) BaseParaSwapSellAdapter(addressesProvider, augustusRegistry) {\n    transferOwnership(owner);\n  }\n\n  function executeOperation(\n    address,\n    uint256,\n    uint256,\n    address,\n    bytes calldata\n  ) external override nonReentrant returns (bool) {\n    revert('NOT_SUPPORTED');\n  }\n\n  /**\n   * @dev Swaps an amount of an asset to another after a withdraw and transfers the new asset to the user.\n   * The user should give this contract allowance to pull the ATokens in order to withdraw the underlying asset and perform the swap.\n   * @param assetToSwapFrom Address of the underlying asset to be swapped from\n   * @param assetToSwapTo Address of the underlying asset to be swapped to\n   * @param amountToSwap Amount to be swapped, or maximum amount when swapping all balance\n   * @param minAmountToReceive Minimum amount to be received from the swap\n   * @param swapAllBalanceOffset Set to offset of fromAmount in Augustus calldata if wanting to swap all balance, otherwise 0\n   * @param swapCalldata Calldata for ParaSwap's AugustusSwapper contract\n   * @param augustus Address of ParaSwap's AugustusSwapper contract\n   * @param permitParams Struct containing the permit signatures, set to all zeroes if not used\n   */\n  function withdrawAndSwap(\n    IERC20Detailed assetToSwapFrom,\n    IERC20Detailed assetToSwapTo,\n    uint256 amountToSwap,\n    uint256 minAmountToReceive,\n    uint256 swapAllBalanceOffset,\n    bytes calldata swapCalldata,\n    IParaSwapAugustus augustus,\n    PermitSignature calldata permitParams\n  ) external nonReentrant {\n    IERC20WithPermit aToken = IERC20WithPermit(\n      _getReserveData(address(assetToSwapFrom)).aTokenAddress\n    );\n\n    if (swapAllBalanceOffset != 0) {\n      uint256 balance = aToken.balanceOf(msg.sender);\n      require(balance <= amountToSwap, 'INSUFFICIENT_AMOUNT_TO_SWAP');\n      amountToSwap = balance;\n    }\n\n    _pullATokenAndWithdraw(\n      address(assetToSwapFrom),\n      aToken,\n      msg.sender,\n      amountToSwap,\n      permitParams\n    );\n\n    uint256 amountReceived = _sellOnParaSwap(\n      swapAllBalanceOffset,\n      swapCalldata,\n      augustus,\n      assetToSwapFrom,\n      assetToSwapTo,\n      amountToSwap,\n      minAmountToReceive\n    );\n\n    assetToSwapTo.safeTransfer(msg.sender, amountReceived);\n  }\n}\n"
      },
      "src/periphery/contracts/adapters/paraswap/interfaces/IParaSwapAugustus.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IParaSwapAugustus {\n  function getTokenTransferProxy() external view returns (address);\n}\n"
      },
      "src/periphery/contracts/adapters/paraswap/interfaces/IParaSwapAugustusRegistry.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IParaSwapAugustusRegistry {\n  function isValidAugustus(address augustus) external view returns (bool);\n}\n"
      },
      "src/periphery/contracts/dependencies/openzeppelin/ReentrancyGuard.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.10;\n\n/**\n * @dev Contract module that helps prevent reentrant calls to a function.\n *\n * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier\n * available, which can be applied to functions to make sure there are no nested\n * (reentrant) calls to them.\n *\n * Note that because there is a single `nonReentrant` guard, functions marked as\n * `nonReentrant` may not call one another. This can be worked around by making\n * those functions `private`, and then adding `external` `nonReentrant` entry\n * points to them.\n *\n * TIP: If you would like to learn more about reentrancy and alternative ways\n * to protect against it, check out our blog post\n * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].\n */\nabstract contract ReentrancyGuard {\n  // Booleans are more expensive than uint256 or any type that takes up a full\n  // word because each write operation emits an extra SLOAD to first read the\n  // slot's contents, replace the bits taken up by the boolean, and then write\n  // back. This is the compiler's defense against contract upgrades and\n  // pointer aliasing, and it cannot be disabled.\n\n  // The values being non-zero value makes deployment a bit more expensive,\n  // but in exchange the refund on every call to nonReentrant will be lower in\n  // amount. Since refunds are capped to a percentage of the total\n  // transaction's gas, it is best to keep them low in cases like this one, to\n  // increase the likelihood of the full refund coming into effect.\n  uint256 private constant _NOT_ENTERED = 1;\n  uint256 private constant _ENTERED = 2;\n\n  uint256 private _status;\n\n  constructor() {\n    _status = _NOT_ENTERED;\n  }\n\n  /**\n   * @dev Prevents a contract from calling itself, directly or indirectly.\n   * Calling a `nonReentrant` function from another `nonReentrant`\n   * function is not supported. It is possible to prevent this from happening\n   * by making the `nonReentrant` function external, and make it call a\n   * `private` function that does the actual work.\n   */\n  modifier nonReentrant() {\n    // On the first call to nonReentrant, _notEntered will be true\n    require(_status != _ENTERED, 'ReentrancyGuard: reentrant call');\n\n    // Any calls to nonReentrant after this point will fail\n    _status = _ENTERED;\n\n    _;\n\n    // By storing the original value once again, a refund is triggered (see\n    // https://eips.ethereum.org/EIPS/eip-2200)\n    _status = _NOT_ENTERED;\n  }\n}\n"
      },
      "src/periphery/contracts/misc/UiIncentiveDataProviderV3.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport {IERC20Detailed} from 'aave-v3-core/contracts/dependencies/openzeppelin/contracts/IERC20Detailed.sol';\nimport {IPoolAddressesProvider} from 'aave-v3-core/contracts/interfaces/IPoolAddressesProvider.sol';\nimport {IPool} from 'aave-v3-core/contracts/interfaces/IPool.sol';\nimport {IncentivizedERC20} from 'aave-v3-core/contracts/protocol/tokenization/base/IncentivizedERC20.sol';\nimport {UserConfiguration} from 'aave-v3-core/contracts/protocol/libraries/configuration/UserConfiguration.sol';\nimport {DataTypes} from 'aave-v3-core/contracts/protocol/libraries/types/DataTypes.sol';\nimport {IRewardsController} from '../rewards/interfaces/IRewardsController.sol';\nimport {IEACAggregatorProxy} from './interfaces/IEACAggregatorProxy.sol';\nimport {IUiIncentiveDataProviderV3} from './interfaces/IUiIncentiveDataProviderV3.sol';\n\ncontract UiIncentiveDataProviderV3 is IUiIncentiveDataProviderV3 {\n  using UserConfiguration for DataTypes.UserConfigurationMap;\n\n  function getFullReservesIncentiveData(\n    IPoolAddressesProvider provider,\n    address user\n  )\n    external\n    view\n    override\n    returns (AggregatedReserveIncentiveData[] memory, UserReserveIncentiveData[] memory)\n  {\n    return (_getReservesIncentivesData(provider), _getUserReservesIncentivesData(provider, user));\n  }\n\n  function getReservesIncentivesData(\n    IPoolAddressesProvider provider\n  ) external view override returns (AggregatedReserveIncentiveData[] memory) {\n    return _getReservesIncentivesData(provider);\n  }\n\n  function _getReservesIncentivesData(\n    IPoolAddressesProvider provider\n  ) private view returns (AggregatedReserveIncentiveData[] memory) {\n    IPool pool = IPool(provider.getPool());\n    address[] memory reserves = pool.getReservesList();\n    AggregatedReserveIncentiveData[]\n      memory reservesIncentiveData = new AggregatedReserveIncentiveData[](reserves.length);\n    // Iterate through the reserves to get all the information from the (a/s/v) Tokens\n    for (uint256 i = 0; i < reserves.length; i++) {\n      AggregatedReserveIncentiveData memory reserveIncentiveData = reservesIncentiveData[i];\n      reserveIncentiveData.underlyingAsset = reserves[i];\n\n      DataTypes.ReserveData memory baseData = pool.getReserveData(reserves[i]);\n\n      // Get aTokens rewards information\n      // TODO: check that this is deployed correctly on contract and remove casting\n      IRewardsController aTokenIncentiveController = IRewardsController(\n        address(IncentivizedERC20(baseData.aTokenAddress).getIncentivesController())\n      );\n      RewardInfo[] memory aRewardsInformation;\n      if (address(aTokenIncentiveController) != address(0)) {\n        address[] memory aTokenRewardAddresses = aTokenIncentiveController.getRewardsByAsset(\n          baseData.aTokenAddress\n        );\n\n        aRewardsInformation = new RewardInfo[](aTokenRewardAddresses.length);\n        for (uint256 j = 0; j < aTokenRewardAddresses.length; ++j) {\n          RewardInfo memory rewardInformation;\n          rewardInformation.rewardTokenAddress = aTokenRewardAddresses[j];\n\n          (\n            rewardInformation.tokenIncentivesIndex,\n            rewardInformation.emissionPerSecond,\n            rewardInformation.incentivesLastUpdateTimestamp,\n            rewardInformation.emissionEndTimestamp\n          ) = aTokenIncentiveController.getRewardsData(\n            baseData.aTokenAddress,\n            rewardInformation.rewardTokenAddress\n          );\n\n          rewardInformation.precision = aTokenIncentiveController.getAssetDecimals(\n            baseData.aTokenAddress\n          );\n          rewardInformation.rewardTokenDecimals = IERC20Detailed(\n            rewardInformation.rewardTokenAddress\n          ).decimals();\n          rewardInformation.rewardTokenSymbol = IERC20Detailed(rewardInformation.rewardTokenAddress)\n            .symbol();\n\n          // Get price of reward token from Chainlink Proxy Oracle\n          rewardInformation.rewardOracleAddress = aTokenIncentiveController.getRewardOracle(\n            rewardInformation.rewardTokenAddress\n          );\n          rewardInformation.priceFeedDecimals = IEACAggregatorProxy(\n            rewardInformation.rewardOracleAddress\n          ).decimals();\n          rewardInformation.rewardPriceFeed = IEACAggregatorProxy(\n            rewardInformation.rewardOracleAddress\n          ).latestAnswer();\n\n          aRewardsInformation[j] = rewardInformation;\n        }\n      }\n\n      reserveIncentiveData.aIncentiveData = IncentiveData(\n        baseData.aTokenAddress,\n        address(aTokenIncentiveController),\n        aRewardsInformation\n      );\n\n      // Get vTokens rewards information\n      IRewardsController vTokenIncentiveController = IRewardsController(\n        address(IncentivizedERC20(baseData.variableDebtTokenAddress).getIncentivesController())\n      );\n      RewardInfo[] memory vRewardsInformation;\n      if (address(vTokenIncentiveController) != address(0)) {\n        address[] memory vTokenRewardAddresses = vTokenIncentiveController.getRewardsByAsset(\n          baseData.variableDebtTokenAddress\n        );\n        vRewardsInformation = new RewardInfo[](vTokenRewardAddresses.length);\n        for (uint256 j = 0; j < vTokenRewardAddresses.length; ++j) {\n          RewardInfo memory rewardInformation;\n          rewardInformation.rewardTokenAddress = vTokenRewardAddresses[j];\n\n          (\n            rewardInformation.tokenIncentivesIndex,\n            rewardInformation.emissionPerSecond,\n            rewardInformation.incentivesLastUpdateTimestamp,\n            rewardInformation.emissionEndTimestamp\n          ) = vTokenIncentiveController.getRewardsData(\n            baseData.variableDebtTokenAddress,\n            rewardInformation.rewardTokenAddress\n          );\n\n          rewardInformation.precision = vTokenIncentiveController.getAssetDecimals(\n            baseData.variableDebtTokenAddress\n          );\n          rewardInformation.rewardTokenDecimals = IERC20Detailed(\n            rewardInformation.rewardTokenAddress\n          ).decimals();\n          rewardInformation.rewardTokenSymbol = IERC20Detailed(rewardInformation.rewardTokenAddress)\n            .symbol();\n\n          // Get price of reward token from Chainlink Proxy Oracle\n          rewardInformation.rewardOracleAddress = vTokenIncentiveController.getRewardOracle(\n            rewardInformation.rewardTokenAddress\n          );\n          rewardInformation.priceFeedDecimals = IEACAggregatorProxy(\n            rewardInformation.rewardOracleAddress\n          ).decimals();\n          rewardInformation.rewardPriceFeed = IEACAggregatorProxy(\n            rewardInformation.rewardOracleAddress\n          ).latestAnswer();\n\n          vRewardsInformation[j] = rewardInformation;\n        }\n      }\n\n      reserveIncentiveData.vIncentiveData = IncentiveData(\n        baseData.variableDebtTokenAddress,\n        address(vTokenIncentiveController),\n        vRewardsInformation\n      );\n\n      // Get sTokens rewards information\n      IRewardsController sTokenIncentiveController = IRewardsController(\n        address(IncentivizedERC20(baseData.stableDebtTokenAddress).getIncentivesController())\n      );\n      RewardInfo[] memory sRewardsInformation;\n      if (address(sTokenIncentiveController) != address(0)) {\n        address[] memory sTokenRewardAddresses = sTokenIncentiveController.getRewardsByAsset(\n          baseData.stableDebtTokenAddress\n        );\n        sRewardsInformation = new RewardInfo[](sTokenRewardAddresses.length);\n        for (uint256 j = 0; j < sTokenRewardAddresses.length; ++j) {\n          RewardInfo memory rewardInformation;\n          rewardInformation.rewardTokenAddress = sTokenRewardAddresses[j];\n\n          (\n            rewardInformation.tokenIncentivesIndex,\n            rewardInformation.emissionPerSecond,\n            rewardInformation.incentivesLastUpdateTimestamp,\n            rewardInformation.emissionEndTimestamp\n          ) = sTokenIncentiveController.getRewardsData(\n            baseData.stableDebtTokenAddress,\n            rewardInformation.rewardTokenAddress\n          );\n\n          rewardInformation.precision = sTokenIncentiveController.getAssetDecimals(\n            baseData.stableDebtTokenAddress\n          );\n          rewardInformation.rewardTokenDecimals = IERC20Detailed(\n            rewardInformation.rewardTokenAddress\n          ).decimals();\n          rewardInformation.rewardTokenSymbol = IERC20Detailed(rewardInformation.rewardTokenAddress)\n            .symbol();\n\n          // Get price of reward token from Chainlink Proxy Oracle\n          rewardInformation.rewardOracleAddress = sTokenIncentiveController.getRewardOracle(\n            rewardInformation.rewardTokenAddress\n          );\n          rewardInformation.priceFeedDecimals = IEACAggregatorProxy(\n            rewardInformation.rewardOracleAddress\n          ).decimals();\n          rewardInformation.rewardPriceFeed = IEACAggregatorProxy(\n            rewardInformation.rewardOracleAddress\n          ).latestAnswer();\n\n          sRewardsInformation[j] = rewardInformation;\n        }\n      }\n\n      reserveIncentiveData.sIncentiveData = IncentiveData(\n        baseData.stableDebtTokenAddress,\n        address(sTokenIncentiveController),\n        sRewardsInformation\n      );\n    }\n\n    return (reservesIncentiveData);\n  }\n\n  function getUserReservesIncentivesData(\n    IPoolAddressesProvider provider,\n    address user\n  ) external view override returns (UserReserveIncentiveData[] memory) {\n    return _getUserReservesIncentivesData(provider, user);\n  }\n\n  function _getUserReservesIncentivesData(\n    IPoolAddressesProvider provider,\n    address user\n  ) private view returns (UserReserveIncentiveData[] memory) {\n    IPool pool = IPool(provider.getPool());\n    address[] memory reserves = pool.getReservesList();\n\n    UserReserveIncentiveData[] memory userReservesIncentivesData = new UserReserveIncentiveData[](\n      user != address(0) ? reserves.length : 0\n    );\n\n    for (uint256 i = 0; i < reserves.length; i++) {\n      DataTypes.ReserveData memory baseData = pool.getReserveData(reserves[i]);\n\n      // user reserve data\n      userReservesIncentivesData[i].underlyingAsset = reserves[i];\n\n      IRewardsController aTokenIncentiveController = IRewardsController(\n        address(IncentivizedERC20(baseData.aTokenAddress).getIncentivesController())\n      );\n      if (address(aTokenIncentiveController) != address(0)) {\n        // get all rewards information from the asset\n        address[] memory aTokenRewardAddresses = aTokenIncentiveController.getRewardsByAsset(\n          baseData.aTokenAddress\n        );\n        UserRewardInfo[] memory aUserRewardsInformation = new UserRewardInfo[](\n          aTokenRewardAddresses.length\n        );\n        for (uint256 j = 0; j < aTokenRewardAddresses.length; ++j) {\n          UserRewardInfo memory userRewardInformation;\n          userRewardInformation.rewardTokenAddress = aTokenRewardAddresses[j];\n\n          userRewardInformation.tokenIncentivesUserIndex = aTokenIncentiveController\n            .getUserAssetIndex(\n              user,\n              baseData.aTokenAddress,\n              userRewardInformation.rewardTokenAddress\n            );\n\n          userRewardInformation.userUnclaimedRewards = aTokenIncentiveController\n            .getUserAccruedRewards(user, userRewardInformation.rewardTokenAddress);\n          userRewardInformation.rewardTokenDecimals = IERC20Detailed(\n            userRewardInformation.rewardTokenAddress\n          ).decimals();\n          userRewardInformation.rewardTokenSymbol = IERC20Detailed(\n            userRewardInformation.rewardTokenAddress\n          ).symbol();\n\n          // Get price of reward token from Chainlink Proxy Oracle\n          userRewardInformation.rewardOracleAddress = aTokenIncentiveController.getRewardOracle(\n            userRewardInformation.rewardTokenAddress\n          );\n          userRewardInformation.priceFeedDecimals = IEACAggregatorProxy(\n            userRewardInformation.rewardOracleAddress\n          ).decimals();\n          userRewardInformation.rewardPriceFeed = IEACAggregatorProxy(\n            userRewardInformation.rewardOracleAddress\n          ).latestAnswer();\n\n          aUserRewardsInformation[j] = userRewardInformation;\n        }\n\n        userReservesIncentivesData[i].aTokenIncentivesUserData = UserIncentiveData(\n          baseData.aTokenAddress,\n          address(aTokenIncentiveController),\n          aUserRewardsInformation\n        );\n      }\n\n      // variable debt token\n      IRewardsController vTokenIncentiveController = IRewardsController(\n        address(IncentivizedERC20(baseData.variableDebtTokenAddress).getIncentivesController())\n      );\n      if (address(vTokenIncentiveController) != address(0)) {\n        // get all rewards information from the asset\n        address[] memory vTokenRewardAddresses = vTokenIncentiveController.getRewardsByAsset(\n          baseData.variableDebtTokenAddress\n        );\n        UserRewardInfo[] memory vUserRewardsInformation = new UserRewardInfo[](\n          vTokenRewardAddresses.length\n        );\n        for (uint256 j = 0; j < vTokenRewardAddresses.length; ++j) {\n          UserRewardInfo memory userRewardInformation;\n          userRewardInformation.rewardTokenAddress = vTokenRewardAddresses[j];\n\n          userRewardInformation.tokenIncentivesUserIndex = vTokenIncentiveController\n            .getUserAssetIndex(\n              user,\n              baseData.variableDebtTokenAddress,\n              userRewardInformation.rewardTokenAddress\n            );\n\n          userRewardInformation.userUnclaimedRewards = vTokenIncentiveController\n            .getUserAccruedRewards(user, userRewardInformation.rewardTokenAddress);\n          userRewardInformation.rewardTokenDecimals = IERC20Detailed(\n            userRewardInformation.rewardTokenAddress\n          ).decimals();\n          userRewardInformation.rewardTokenSymbol = IERC20Detailed(\n            userRewardInformation.rewardTokenAddress\n          ).symbol();\n\n          // Get price of reward token from Chainlink Proxy Oracle\n          userRewardInformation.rewardOracleAddress = vTokenIncentiveController.getRewardOracle(\n            userRewardInformation.rewardTokenAddress\n          );\n          userRewardInformation.priceFeedDecimals = IEACAggregatorProxy(\n            userRewardInformation.rewardOracleAddress\n          ).decimals();\n          userRewardInformation.rewardPriceFeed = IEACAggregatorProxy(\n            userRewardInformation.rewardOracleAddress\n          ).latestAnswer();\n\n          vUserRewardsInformation[j] = userRewardInformation;\n        }\n\n        userReservesIncentivesData[i].vTokenIncentivesUserData = UserIncentiveData(\n          baseData.variableDebtTokenAddress,\n          address(aTokenIncentiveController),\n          vUserRewardsInformation\n        );\n      }\n\n      // stable debt token\n      IRewardsController sTokenIncentiveController = IRewardsController(\n        address(IncentivizedERC20(baseData.stableDebtTokenAddress).getIncentivesController())\n      );\n      if (address(sTokenIncentiveController) != address(0)) {\n        // get all rewards information from the asset\n        address[] memory sTokenRewardAddresses = sTokenIncentiveController.getRewardsByAsset(\n          baseData.stableDebtTokenAddress\n        );\n        UserRewardInfo[] memory sUserRewardsInformation = new UserRewardInfo[](\n          sTokenRewardAddresses.length\n        );\n        for (uint256 j = 0; j < sTokenRewardAddresses.length; ++j) {\n          UserRewardInfo memory userRewardInformation;\n          userRewardInformation.rewardTokenAddress = sTokenRewardAddresses[j];\n\n          userRewardInformation.tokenIncentivesUserIndex = sTokenIncentiveController\n            .getUserAssetIndex(\n              user,\n              baseData.stableDebtTokenAddress,\n              userRewardInformation.rewardTokenAddress\n            );\n\n          userRewardInformation.userUnclaimedRewards = sTokenIncentiveController\n            .getUserAccruedRewards(user, userRewardInformation.rewardTokenAddress);\n          userRewardInformation.rewardTokenDecimals = IERC20Detailed(\n            userRewardInformation.rewardTokenAddress\n          ).decimals();\n          userRewardInformation.rewardTokenSymbol = IERC20Detailed(\n            userRewardInformation.rewardTokenAddress\n          ).symbol();\n\n          // Get price of reward token from Chainlink Proxy Oracle\n          userRewardInformation.rewardOracleAddress = sTokenIncentiveController.getRewardOracle(\n            userRewardInformation.rewardTokenAddress\n          );\n          userRewardInformation.priceFeedDecimals = IEACAggregatorProxy(\n            userRewardInformation.rewardOracleAddress\n          ).decimals();\n          userRewardInformation.rewardPriceFeed = IEACAggregatorProxy(\n            userRewardInformation.rewardOracleAddress\n          ).latestAnswer();\n\n          sUserRewardsInformation[j] = userRewardInformation;\n        }\n\n        userReservesIncentivesData[i].sTokenIncentivesUserData = UserIncentiveData(\n          baseData.stableDebtTokenAddress,\n          address(aTokenIncentiveController),\n          sUserRewardsInformation\n        );\n      }\n    }\n\n    return (userReservesIncentivesData);\n  }\n}\n"
      },
      "src/periphery/contracts/misc/UiPoolDataProviderV3.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport {IERC20Detailed} from 'aave-v3-core/contracts/dependencies/openzeppelin/contracts/IERC20Detailed.sol';\nimport {IPoolAddressesProvider} from 'aave-v3-core/contracts/interfaces/IPoolAddressesProvider.sol';\nimport {IPool} from 'aave-v3-core/contracts/interfaces/IPool.sol';\nimport {IAaveOracle} from 'aave-v3-core/contracts/interfaces/IAaveOracle.sol';\nimport {IAToken} from 'aave-v3-core/contracts/interfaces/IAToken.sol';\nimport {IVariableDebtToken} from 'aave-v3-core/contracts/interfaces/IVariableDebtToken.sol';\nimport {IStableDebtToken} from 'aave-v3-core/contracts/interfaces/IStableDebtToken.sol';\nimport {DefaultReserveInterestRateStrategy} from 'aave-v3-core/contracts/protocol/pool/DefaultReserveInterestRateStrategy.sol';\nimport {AaveProtocolDataProvider} from 'aave-v3-core/contracts/misc/AaveProtocolDataProvider.sol';\nimport {WadRayMath} from 'aave-v3-core/contracts/protocol/libraries/math/WadRayMath.sol';\nimport {ReserveConfiguration} from 'aave-v3-core/contracts/protocol/libraries/configuration/ReserveConfiguration.sol';\nimport {UserConfiguration} from 'aave-v3-core/contracts/protocol/libraries/configuration/UserConfiguration.sol';\nimport {DataTypes} from 'aave-v3-core/contracts/protocol/libraries/types/DataTypes.sol';\nimport {IEACAggregatorProxy} from './interfaces/IEACAggregatorProxy.sol';\nimport {IERC20DetailedBytes} from './interfaces/IERC20DetailedBytes.sol';\nimport {IUiPoolDataProviderV3} from './interfaces/IUiPoolDataProviderV3.sol';\n\ncontract UiPoolDataProviderV3 is IUiPoolDataProviderV3 {\n  using WadRayMath for uint256;\n  using ReserveConfiguration for DataTypes.ReserveConfigurationMap;\n  using UserConfiguration for DataTypes.UserConfigurationMap;\n\n  IEACAggregatorProxy public immutable networkBaseTokenPriceInUsdProxyAggregator;\n  IEACAggregatorProxy public immutable marketReferenceCurrencyPriceInUsdProxyAggregator;\n  uint256 public constant ETH_CURRENCY_UNIT = 1 ether;\n  address public constant MKR_ADDRESS = 0x9f8F72aA9304c8B593d555F12eF6589cC3A579A2;\n\n  constructor(\n    IEACAggregatorProxy _networkBaseTokenPriceInUsdProxyAggregator,\n    IEACAggregatorProxy _marketReferenceCurrencyPriceInUsdProxyAggregator\n  ) {\n    networkBaseTokenPriceInUsdProxyAggregator = _networkBaseTokenPriceInUsdProxyAggregator;\n    marketReferenceCurrencyPriceInUsdProxyAggregator = _marketReferenceCurrencyPriceInUsdProxyAggregator;\n  }\n\n  function getReservesList(\n    IPoolAddressesProvider provider\n  ) public view override returns (address[] memory) {\n    IPool pool = IPool(provider.getPool());\n    return pool.getReservesList();\n  }\n\n  function getReservesData(\n    IPoolAddressesProvider provider\n  ) public view override returns (AggregatedReserveData[] memory, BaseCurrencyInfo memory) {\n    IAaveOracle oracle = IAaveOracle(provider.getPriceOracle());\n    IPool pool = IPool(provider.getPool());\n    AaveProtocolDataProvider poolDataProvider = AaveProtocolDataProvider(\n      provider.getPoolDataProvider()\n    );\n\n    address[] memory reserves = pool.getReservesList();\n    AggregatedReserveData[] memory reservesData = new AggregatedReserveData[](reserves.length);\n\n    for (uint256 i = 0; i < reserves.length; i++) {\n      AggregatedReserveData memory reserveData = reservesData[i];\n      reserveData.underlyingAsset = reserves[i];\n\n      // reserve current state\n      DataTypes.ReserveData memory baseData = pool.getReserveData(reserveData.underlyingAsset);\n      //the liquidity index. Expressed in ray\n      reserveData.liquidityIndex = baseData.liquidityIndex;\n      //variable borrow index. Expressed in ray\n      reserveData.variableBorrowIndex = baseData.variableBorrowIndex;\n      //the current supply rate. Expressed in ray\n      reserveData.liquidityRate = baseData.currentLiquidityRate;\n      //the current variable borrow rate. Expressed in ray\n      reserveData.variableBorrowRate = baseData.currentVariableBorrowRate;\n      //the current stable borrow rate. Expressed in ray\n      reserveData.stableBorrowRate = baseData.currentStableBorrowRate;\n      reserveData.lastUpdateTimestamp = baseData.lastUpdateTimestamp;\n      reserveData.aTokenAddress = baseData.aTokenAddress;\n      reserveData.stableDebtTokenAddress = baseData.stableDebtTokenAddress;\n      reserveData.variableDebtTokenAddress = baseData.variableDebtTokenAddress;\n      //address of the interest rate strategy\n      reserveData.interestRateStrategyAddress = baseData.interestRateStrategyAddress;\n      reserveData.priceInMarketReferenceCurrency = oracle.getAssetPrice(\n        reserveData.underlyingAsset\n      );\n      reserveData.priceOracle = oracle.getSourceOfAsset(reserveData.underlyingAsset);\n      reserveData.availableLiquidity = IERC20Detailed(reserveData.underlyingAsset).balanceOf(\n        reserveData.aTokenAddress\n      );\n      (\n        reserveData.totalPrincipalStableDebt,\n        ,\n        reserveData.averageStableRate,\n        reserveData.stableDebtLastUpdateTimestamp\n      ) = IStableDebtToken(reserveData.stableDebtTokenAddress).getSupplyData();\n      reserveData.totalScaledVariableDebt = IVariableDebtToken(reserveData.variableDebtTokenAddress)\n        .scaledTotalSupply();\n\n      // Due we take the symbol from underlying token we need a special case for $MKR as symbol() returns bytes32\n      if (address(reserveData.underlyingAsset) == address(MKR_ADDRESS)) {\n        bytes32 symbol = IERC20DetailedBytes(reserveData.underlyingAsset).symbol();\n        bytes32 name = IERC20DetailedBytes(reserveData.underlyingAsset).name();\n        reserveData.symbol = bytes32ToString(symbol);\n        reserveData.name = bytes32ToString(name);\n      } else {\n        reserveData.symbol = IERC20Detailed(reserveData.underlyingAsset).symbol();\n        reserveData.name = IERC20Detailed(reserveData.underlyingAsset).name();\n      }\n\n      //stores the reserve configuration\n      DataTypes.ReserveConfigurationMap memory reserveConfigurationMap = baseData.configuration;\n      uint256 eModeCategoryId;\n      (\n        reserveData.baseLTVasCollateral,\n        reserveData.reserveLiquidationThreshold,\n        reserveData.reserveLiquidationBonus,\n        reserveData.decimals,\n        reserveData.reserveFactor,\n        eModeCategoryId\n      ) = reserveConfigurationMap.getParams();\n      reserveData.usageAsCollateralEnabled = reserveData.baseLTVasCollateral != 0;\n\n      (\n        reserveData.isActive,\n        reserveData.isFrozen,\n        reserveData.borrowingEnabled,\n        reserveData.stableBorrowRateEnabled,\n        reserveData.isPaused\n      ) = reserveConfigurationMap.getFlags();\n\n      // interest rates\n      try\n        DefaultReserveInterestRateStrategy(reserveData.interestRateStrategyAddress)\n          .getVariableRateSlope1()\n      returns (uint256 res) {\n        reserveData.variableRateSlope1 = res;\n      } catch {}\n      try\n        DefaultReserveInterestRateStrategy(reserveData.interestRateStrategyAddress)\n          .getVariableRateSlope2()\n      returns (uint256 res) {\n        reserveData.variableRateSlope2 = res;\n      } catch {}\n      try\n        DefaultReserveInterestRateStrategy(reserveData.interestRateStrategyAddress)\n          .getStableRateSlope1()\n      returns (uint256 res) {\n        reserveData.stableRateSlope1 = res;\n      } catch {}\n      try\n        DefaultReserveInterestRateStrategy(reserveData.interestRateStrategyAddress)\n          .getStableRateSlope2()\n      returns (uint256 res) {\n        reserveData.stableRateSlope2 = res;\n      } catch {}\n      try\n        DefaultReserveInterestRateStrategy(reserveData.interestRateStrategyAddress)\n          .getBaseStableBorrowRate()\n      returns (uint256 res) {\n        reserveData.baseStableBorrowRate = res;\n      } catch {}\n      try\n        DefaultReserveInterestRateStrategy(reserveData.interestRateStrategyAddress)\n          .getBaseVariableBorrowRate()\n      returns (uint256 res) {\n        reserveData.baseVariableBorrowRate = res;\n      } catch {}\n      try\n        DefaultReserveInterestRateStrategy(reserveData.interestRateStrategyAddress)\n          .OPTIMAL_USAGE_RATIO()\n      returns (uint256 res) {\n        reserveData.optimalUsageRatio = res;\n      } catch {}\n\n      // v3 only\n      reserveData.eModeCategoryId = uint8(eModeCategoryId);\n      reserveData.debtCeiling = reserveConfigurationMap.getDebtCeiling();\n      reserveData.debtCeilingDecimals = poolDataProvider.getDebtCeilingDecimals();\n      (reserveData.borrowCap, reserveData.supplyCap) = reserveConfigurationMap.getCaps();\n\n      try poolDataProvider.getFlashLoanEnabled(reserveData.underlyingAsset) returns (\n        bool flashLoanEnabled\n      ) {\n        reserveData.flashLoanEnabled = flashLoanEnabled;\n      } catch (bytes memory) {\n        reserveData.flashLoanEnabled = true;\n      }\n\n      reserveData.isSiloedBorrowing = reserveConfigurationMap.getSiloedBorrowing();\n      reserveData.unbacked = baseData.unbacked;\n      reserveData.isolationModeTotalDebt = baseData.isolationModeTotalDebt;\n      reserveData.accruedToTreasury = baseData.accruedToTreasury;\n\n      DataTypes.EModeCategory memory categoryData = pool.getEModeCategoryData(\n        reserveData.eModeCategoryId\n      );\n      reserveData.eModeLtv = categoryData.ltv;\n      reserveData.eModeLiquidationThreshold = categoryData.liquidationThreshold;\n      reserveData.eModeLiquidationBonus = categoryData.liquidationBonus;\n      // each eMode category may or may not have a custom oracle to override the individual assets price oracles\n      reserveData.eModePriceSource = categoryData.priceSource;\n      reserveData.eModeLabel = categoryData.label;\n\n      reserveData.borrowableInIsolation = reserveConfigurationMap.getBorrowableInIsolation();\n    }\n\n    BaseCurrencyInfo memory baseCurrencyInfo;\n    baseCurrencyInfo.networkBaseTokenPriceInUsd = networkBaseTokenPriceInUsdProxyAggregator\n      .latestAnswer();\n    baseCurrencyInfo.networkBaseTokenPriceDecimals = networkBaseTokenPriceInUsdProxyAggregator\n      .decimals();\n\n    try oracle.BASE_CURRENCY_UNIT() returns (uint256 baseCurrencyUnit) {\n      baseCurrencyInfo.marketReferenceCurrencyUnit = baseCurrencyUnit;\n      baseCurrencyInfo.marketReferenceCurrencyPriceInUsd = int256(baseCurrencyUnit);\n    } catch (bytes memory /*lowLevelData*/) {\n      baseCurrencyInfo.marketReferenceCurrencyUnit = ETH_CURRENCY_UNIT;\n      baseCurrencyInfo\n        .marketReferenceCurrencyPriceInUsd = marketReferenceCurrencyPriceInUsdProxyAggregator\n        .latestAnswer();\n    }\n\n    return (reservesData, baseCurrencyInfo);\n  }\n\n  function getUserReservesData(\n    IPoolAddressesProvider provider,\n    address user\n  ) external view override returns (UserReserveData[] memory, uint8) {\n    IPool pool = IPool(provider.getPool());\n    address[] memory reserves = pool.getReservesList();\n    DataTypes.UserConfigurationMap memory userConfig = pool.getUserConfiguration(user);\n\n    uint8 userEmodeCategoryId = uint8(pool.getUserEMode(user));\n\n    UserReserveData[] memory userReservesData = new UserReserveData[](\n      user != address(0) ? reserves.length : 0\n    );\n\n    for (uint256 i = 0; i < reserves.length; i++) {\n      DataTypes.ReserveData memory baseData = pool.getReserveData(reserves[i]);\n\n      // user reserve data\n      userReservesData[i].underlyingAsset = reserves[i];\n      userReservesData[i].scaledATokenBalance = IAToken(baseData.aTokenAddress).scaledBalanceOf(\n        user\n      );\n      userReservesData[i].usageAsCollateralEnabledOnUser = userConfig.isUsingAsCollateral(i);\n\n      if (userConfig.isBorrowing(i)) {\n        userReservesData[i].scaledVariableDebt = IVariableDebtToken(\n          baseData.variableDebtTokenAddress\n        ).scaledBalanceOf(user);\n        userReservesData[i].principalStableDebt = IStableDebtToken(baseData.stableDebtTokenAddress)\n          .principalBalanceOf(user);\n        if (userReservesData[i].principalStableDebt != 0) {\n          userReservesData[i].stableBorrowRate = IStableDebtToken(baseData.stableDebtTokenAddress)\n            .getUserStableRate(user);\n          userReservesData[i].stableBorrowLastUpdateTimestamp = IStableDebtToken(\n            baseData.stableDebtTokenAddress\n          ).getUserLastUpdated(user);\n        }\n      }\n    }\n\n    return (userReservesData, userEmodeCategoryId);\n  }\n\n  function bytes32ToString(bytes32 _bytes32) public pure returns (string memory) {\n    uint8 i = 0;\n    while (i < 32 && _bytes32[i] != 0) {\n      i++;\n    }\n    bytes memory bytesArray = new bytes(i);\n    for (i = 0; i < 32 && _bytes32[i] != 0; i++) {\n      bytesArray[i] = _bytes32[i];\n    }\n    return string(bytesArray);\n  }\n}\n"
      },
      "src/periphery/contracts/misc/WalletBalanceProvider.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport {Address} from 'aave-v3-core/contracts/dependencies/openzeppelin/contracts/Address.sol';\nimport {IERC20} from 'aave-v3-core/contracts/dependencies/openzeppelin/contracts/IERC20.sol';\n\nimport {IPoolAddressesProvider} from 'aave-v3-core/contracts/interfaces/IPoolAddressesProvider.sol';\nimport {IPool} from 'aave-v3-core/contracts/interfaces/IPool.sol';\nimport {GPv2SafeERC20} from 'aave-v3-core/contracts/dependencies/gnosis/contracts/GPv2SafeERC20.sol';\nimport {ReserveConfiguration} from 'aave-v3-core/contracts/protocol/libraries/configuration/ReserveConfiguration.sol';\nimport {DataTypes} from 'aave-v3-core/contracts/protocol/libraries/types/DataTypes.sol';\n\n/**\n * @title WalletBalanceProvider contract\n * @author Aave, influenced by https://github.com/wbobeirne/eth-balance-checker/blob/master/contracts/BalanceChecker.sol\n * @notice Implements a logic of getting multiple tokens balance for one user address\n * @dev NOTE: THIS CONTRACT IS NOT USED WITHIN THE AAVE PROTOCOL. It's an accessory contract used to reduce the number of calls\n * towards the blockchain from the Aave backend.\n **/\ncontract WalletBalanceProvider {\n  using Address for address payable;\n  using Address for address;\n  using GPv2SafeERC20 for IERC20;\n  using ReserveConfiguration for DataTypes.ReserveConfigurationMap;\n\n  address constant MOCK_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;\n\n  /**\n    @dev Fallback function, don't accept any ETH\n    **/\n  receive() external payable {\n    //only contracts can send ETH to the core\n    require(msg.sender.isContract(), '22');\n  }\n\n  /**\n    @dev Check the token balance of a wallet in a token contract\n\n    Returns the balance of the token for user. Avoids possible errors:\n      - return 0 on non-contract address\n    **/\n  function balanceOf(address user, address token) public view returns (uint256) {\n    if (token == MOCK_ETH_ADDRESS) {\n      return user.balance; // ETH balance\n      // check if token is actually a contract\n    } else if (token.isContract()) {\n      return IERC20(token).balanceOf(user);\n    }\n    revert('INVALID_TOKEN');\n  }\n\n  /**\n   * @notice Fetches, for a list of _users and _tokens (ETH included with mock address), the balances\n   * @param users The list of users\n   * @param tokens The list of tokens\n   * @return And array with the concatenation of, for each user, his/her balances\n   **/\n  function batchBalanceOf(\n    address[] calldata users,\n    address[] calldata tokens\n  ) external view returns (uint256[] memory) {\n    uint256[] memory balances = new uint256[](users.length * tokens.length);\n\n    for (uint256 i = 0; i < users.length; i++) {\n      for (uint256 j = 0; j < tokens.length; j++) {\n        balances[i * tokens.length + j] = balanceOf(users[i], tokens[j]);\n      }\n    }\n\n    return balances;\n  }\n\n  /**\n    @dev provides balances of user wallet for all reserves available on the pool\n    */\n  function getUserWalletBalances(\n    address provider,\n    address user\n  ) external view returns (address[] memory, uint256[] memory) {\n    IPool pool = IPool(IPoolAddressesProvider(provider).getPool());\n\n    address[] memory reserves = pool.getReservesList();\n    address[] memory reservesWithEth = new address[](reserves.length + 1);\n    for (uint256 i = 0; i < reserves.length; i++) {\n      reservesWithEth[i] = reserves[i];\n    }\n    reservesWithEth[reserves.length] = MOCK_ETH_ADDRESS;\n\n    uint256[] memory balances = new uint256[](reservesWithEth.length);\n\n    for (uint256 j = 0; j < reserves.length; j++) {\n      DataTypes.ReserveConfigurationMap memory configuration = pool.getConfiguration(\n        reservesWithEth[j]\n      );\n\n      (bool isActive, , , , ) = configuration.getFlags();\n\n      if (!isActive) {\n        balances[j] = 0;\n        continue;\n      }\n      balances[j] = balanceOf(user, reservesWithEth[j]);\n    }\n    balances[reserves.length] = balanceOf(user, MOCK_ETH_ADDRESS);\n\n    return (reservesWithEth, balances);\n  }\n}\n"
      },
      "src/periphery/contracts/misc/interfaces/IEACAggregatorProxy.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IEACAggregatorProxy {\n  function decimals() external view returns (uint8);\n\n  function latestAnswer() external view returns (int256);\n\n  function latestTimestamp() external view returns (uint256);\n\n  function latestRound() external view returns (uint256);\n\n  function getAnswer(uint256 roundId) external view returns (int256);\n\n  function getTimestamp(uint256 roundId) external view returns (uint256);\n\n  event AnswerUpdated(int256 indexed current, uint256 indexed roundId, uint256 timestamp);\n  event NewRound(uint256 indexed roundId, address indexed startedBy);\n}\n"
      },
      "src/periphery/contracts/misc/interfaces/IERC20DetailedBytes.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport {IERC20} from 'aave-v3-core/contracts/dependencies/openzeppelin/contracts/IERC20.sol';\n\ninterface IERC20DetailedBytes is IERC20 {\n  function name() external view returns (bytes32);\n\n  function symbol() external view returns (bytes32);\n\n  function decimals() external view returns (uint8);\n}\n"
      },
      "src/periphery/contracts/misc/interfaces/IUiIncentiveDataProviderV3.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport {IPoolAddressesProvider} from 'aave-v3-core/contracts/interfaces/IPoolAddressesProvider.sol';\n\ninterface IUiIncentiveDataProviderV3 {\n  struct AggregatedReserveIncentiveData {\n    address underlyingAsset;\n    IncentiveData aIncentiveData;\n    IncentiveData vIncentiveData;\n    IncentiveData sIncentiveData;\n  }\n\n  struct IncentiveData {\n    address tokenAddress;\n    address incentiveControllerAddress;\n    RewardInfo[] rewardsTokenInformation;\n  }\n\n  struct RewardInfo {\n    string rewardTokenSymbol;\n    address rewardTokenAddress;\n    address rewardOracleAddress;\n    uint256 emissionPerSecond;\n    uint256 incentivesLastUpdateTimestamp;\n    uint256 tokenIncentivesIndex;\n    uint256 emissionEndTimestamp;\n    int256 rewardPriceFeed;\n    uint8 rewardTokenDecimals;\n    uint8 precision;\n    uint8 priceFeedDecimals;\n  }\n\n  struct UserReserveIncentiveData {\n    address underlyingAsset;\n    UserIncentiveData aTokenIncentivesUserData;\n    UserIncentiveData vTokenIncentivesUserData;\n    UserIncentiveData sTokenIncentivesUserData;\n  }\n\n  struct UserIncentiveData {\n    address tokenAddress;\n    address incentiveControllerAddress;\n    UserRewardInfo[] userRewardsInformation;\n  }\n\n  struct UserRewardInfo {\n    string rewardTokenSymbol;\n    address rewardOracleAddress;\n    address rewardTokenAddress;\n    uint256 userUnclaimedRewards;\n    uint256 tokenIncentivesUserIndex;\n    int256 rewardPriceFeed;\n    uint8 priceFeedDecimals;\n    uint8 rewardTokenDecimals;\n  }\n\n  function getReservesIncentivesData(\n    IPoolAddressesProvider provider\n  ) external view returns (AggregatedReserveIncentiveData[] memory);\n\n  function getUserReservesIncentivesData(\n    IPoolAddressesProvider provider,\n    address user\n  ) external view returns (UserReserveIncentiveData[] memory);\n\n  // generic method with full data\n  function getFullReservesIncentiveData(\n    IPoolAddressesProvider provider,\n    address user\n  )\n    external\n    view\n    returns (AggregatedReserveIncentiveData[] memory, UserReserveIncentiveData[] memory);\n}\n"
      },
      "src/periphery/contracts/misc/interfaces/IUiPoolDataProviderV3.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport {IPoolAddressesProvider} from 'aave-v3-core/contracts/interfaces/IPoolAddressesProvider.sol';\n\ninterface IUiPoolDataProviderV3 {\n  struct InterestRates {\n    uint256 variableRateSlope1;\n    uint256 variableRateSlope2;\n    uint256 stableRateSlope1;\n    uint256 stableRateSlope2;\n    uint256 baseStableBorrowRate;\n    uint256 baseVariableBorrowRate;\n    uint256 optimalUsageRatio;\n  }\n\n  struct AggregatedReserveData {\n    address underlyingAsset;\n    string name;\n    string symbol;\n    uint256 decimals;\n    uint256 baseLTVasCollateral;\n    uint256 reserveLiquidationThreshold;\n    uint256 reserveLiquidationBonus;\n    uint256 reserveFactor;\n    bool usageAsCollateralEnabled;\n    bool borrowingEnabled;\n    bool stableBorrowRateEnabled;\n    bool isActive;\n    bool isFrozen;\n    // base data\n    uint128 liquidityIndex;\n    uint128 variableBorrowIndex;\n    uint128 liquidityRate;\n    uint128 variableBorrowRate;\n    uint128 stableBorrowRate;\n    uint40 lastUpdateTimestamp;\n    address aTokenAddress;\n    address stableDebtTokenAddress;\n    address variableDebtTokenAddress;\n    address interestRateStrategyAddress;\n    //\n    uint256 availableLiquidity;\n    uint256 totalPrincipalStableDebt;\n    uint256 averageStableRate;\n    uint256 stableDebtLastUpdateTimestamp;\n    uint256 totalScaledVariableDebt;\n    uint256 priceInMarketReferenceCurrency;\n    address priceOracle;\n    uint256 variableRateSlope1;\n    uint256 variableRateSlope2;\n    uint256 stableRateSlope1;\n    uint256 stableRateSlope2;\n    uint256 baseStableBorrowRate;\n    uint256 baseVariableBorrowRate;\n    uint256 optimalUsageRatio;\n    // v3 only\n    bool isPaused;\n    bool isSiloedBorrowing;\n    uint128 accruedToTreasury;\n    uint128 unbacked;\n    uint128 isolationModeTotalDebt;\n    bool flashLoanEnabled;\n    //\n    uint256 debtCeiling;\n    uint256 debtCeilingDecimals;\n    uint8 eModeCategoryId;\n    uint256 borrowCap;\n    uint256 supplyCap;\n    // eMode\n    uint16 eModeLtv;\n    uint16 eModeLiquidationThreshold;\n    uint16 eModeLiquidationBonus;\n    address eModePriceSource;\n    string eModeLabel;\n    bool borrowableInIsolation;\n  }\n\n  struct UserReserveData {\n    address underlyingAsset;\n    uint256 scaledATokenBalance;\n    bool usageAsCollateralEnabledOnUser;\n    uint256 stableBorrowRate;\n    uint256 scaledVariableDebt;\n    uint256 principalStableDebt;\n    uint256 stableBorrowLastUpdateTimestamp;\n  }\n\n  struct BaseCurrencyInfo {\n    uint256 marketReferenceCurrencyUnit;\n    int256 marketReferenceCurrencyPriceInUsd;\n    int256 networkBaseTokenPriceInUsd;\n    uint8 networkBaseTokenPriceDecimals;\n  }\n\n  function getReservesList(\n    IPoolAddressesProvider provider\n  ) external view returns (address[] memory);\n\n  function getReservesData(\n    IPoolAddressesProvider provider\n  ) external view returns (AggregatedReserveData[] memory, BaseCurrencyInfo memory);\n\n  function getUserReservesData(\n    IPoolAddressesProvider provider,\n    address user\n  ) external view returns (UserReserveData[] memory, uint8);\n}\n"
      },
      "src/periphery/contracts/misc/interfaces/IWrappedTokenGatewayV3.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IWrappedTokenGatewayV3 {\n  function depositETH(address pool, address onBehalfOf, uint16 referralCode) external payable;\n\n  function withdrawETH(address pool, uint256 amount, address onBehalfOf) external;\n\n  function repayETH(\n    address pool,\n    uint256 amount,\n    uint256 rateMode,\n    address onBehalfOf\n  ) external payable;\n\n  function borrowETH(\n    address pool,\n    uint256 amount,\n    uint256 interestRateMode,\n    uint16 referralCode\n  ) external;\n\n  function withdrawETHWithPermit(\n    address pool,\n    uint256 amount,\n    address to,\n    uint256 deadline,\n    uint8 permitV,\n    bytes32 permitR,\n    bytes32 permitS\n  ) external;\n}\n"
      },
      "src/periphery/contracts/rewards/interfaces/IEmissionManager.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport {IEACAggregatorProxy} from '../../misc/interfaces/IEACAggregatorProxy.sol';\nimport {RewardsDataTypes} from '../libraries/RewardsDataTypes.sol';\nimport {ITransferStrategyBase} from './ITransferStrategyBase.sol';\nimport {IRewardsController} from './IRewardsController.sol';\n\n/**\n * @title IEmissionManager\n * @author Aave\n * @notice Defines the basic interface for the Emission Manager\n */\ninterface IEmissionManager {\n  /**\n   * @dev Emitted when the admin of a reward emission is updated.\n   * @param reward The address of the rewarding token\n   * @param oldAdmin The address of the old emission admin\n   * @param newAdmin The address of the new emission admin\n   */\n  event EmissionAdminUpdated(\n    address indexed reward,\n    address indexed oldAdmin,\n    address indexed newAdmin\n  );\n\n  /**\n   * @dev Configure assets to incentivize with an emission of rewards per second until the end of distribution.\n   * @dev Only callable by the emission admin of the given rewards\n   * @param config The assets configuration input, the list of structs contains the following fields:\n   *   uint104 emissionPerSecond: The emission per second following rewards unit decimals.\n   *   uint256 totalSupply: The total supply of the asset to incentivize\n   *   uint40 distributionEnd: The end of the distribution of the incentives for an asset\n   *   address asset: The asset address to incentivize\n   *   address reward: The reward token address\n   *   ITransferStrategy transferStrategy: The TransferStrategy address with the install hook and claim logic.\n   *   IEACAggregatorProxy rewardOracle: The Price Oracle of a reward to visualize the incentives at the UI Frontend.\n   *                                     Must follow Chainlink Aggregator IEACAggregatorProxy interface to be compatible.\n   */\n  function configureAssets(RewardsDataTypes.RewardsConfigInput[] memory config) external;\n\n  /**\n   * @dev Sets a TransferStrategy logic contract that determines the logic of the rewards transfer\n   * @dev Only callable by the emission admin of the given reward\n   * @param reward The address of the reward token\n   * @param transferStrategy The address of the TransferStrategy logic contract\n   */\n  function setTransferStrategy(address reward, ITransferStrategyBase transferStrategy) external;\n\n  /**\n   * @dev Sets an Aave Oracle contract to enforce rewards with a source of value.\n   * @dev Only callable by the emission admin of the given reward\n   * @notice At the moment of reward configuration, the Incentives Controller performs\n   * a check to see if the reward asset oracle is compatible with IEACAggregator proxy.\n   * This check is enforced for integrators to be able to show incentives at\n   * the current Aave UI without the need to setup an external price registry\n   * @param reward The address of the reward to set the price aggregator\n   * @param rewardOracle The address of price aggregator that follows IEACAggregatorProxy interface\n   */\n  function setRewardOracle(address reward, IEACAggregatorProxy rewardOracle) external;\n\n  /**\n   * @dev Sets the end date for the distribution\n   * @dev Only callable by the emission admin of the given reward\n   * @param asset The asset to incentivize\n   * @param reward The reward token that incentives the asset\n   * @param newDistributionEnd The end date of the incentivization, in unix time format\n   **/\n  function setDistributionEnd(address asset, address reward, uint32 newDistributionEnd) external;\n\n  /**\n   * @dev Sets the emission per second of a set of reward distributions\n   * @param asset The asset is being incentivized\n   * @param rewards List of reward addresses are being distributed\n   * @param newEmissionsPerSecond List of new reward emissions per second\n   */\n  function setEmissionPerSecond(\n    address asset,\n    address[] calldata rewards,\n    uint88[] calldata newEmissionsPerSecond\n  ) external;\n\n  /**\n   * @dev Whitelists an address to claim the rewards on behalf of another address\n   * @dev Only callable by the owner of the EmissionManager\n   * @param user The address of the user\n   * @param claimer The address of the claimer\n   */\n  function setClaimer(address user, address claimer) external;\n\n  /**\n   * @dev Updates the admin of the reward emission\n   * @dev Only callable by the owner of the EmissionManager\n   * @param reward The address of the reward token\n   * @param admin The address of the new admin of the emission\n   */\n  function setEmissionAdmin(address reward, address admin) external;\n\n  /**\n   * @dev Updates the address of the rewards controller\n   * @dev Only callable by the owner of the EmissionManager\n   * @param controller the address of the RewardsController contract\n   */\n  function setRewardsController(address controller) external;\n\n  /**\n   * @dev Returns the rewards controller address\n   * @return The address of the RewardsController contract\n   */\n  function getRewardsController() external view returns (IRewardsController);\n\n  /**\n   * @dev Returns the admin of the given reward emission\n   * @param reward The address of the reward token\n   * @return The address of the emission admin\n   */\n  function getEmissionAdmin(address reward) external view returns (address);\n}\n"
      },
      "src/periphery/contracts/rewards/interfaces/IRewardsController.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport {IRewardsDistributor} from './IRewardsDistributor.sol';\nimport {ITransferStrategyBase} from './ITransferStrategyBase.sol';\nimport {IEACAggregatorProxy} from '../../misc/interfaces/IEACAggregatorProxy.sol';\nimport {RewardsDataTypes} from '../libraries/RewardsDataTypes.sol';\n\n/**\n * @title IRewardsController\n * @author Aave\n * @notice Defines the basic interface for a Rewards Controller.\n */\ninterface IRewardsController is IRewardsDistributor {\n  /**\n   * @dev Emitted when a new address is whitelisted as claimer of rewards on behalf of a user\n   * @param user The address of the user\n   * @param claimer The address of the claimer\n   */\n  event ClaimerSet(address indexed user, address indexed claimer);\n\n  /**\n   * @dev Emitted when rewards are claimed\n   * @param user The address of the user rewards has been claimed on behalf of\n   * @param reward The address of the token reward is claimed\n   * @param to The address of the receiver of the rewards\n   * @param claimer The address of the claimer\n   * @param amount The amount of rewards claimed\n   */\n  event RewardsClaimed(\n    address indexed user,\n    address indexed reward,\n    address indexed to,\n    address claimer,\n    uint256 amount\n  );\n\n  /**\n   * @dev Emitted when a transfer strategy is installed for the reward distribution\n   * @param reward The address of the token reward\n   * @param transferStrategy The address of TransferStrategy contract\n   */\n  event TransferStrategyInstalled(address indexed reward, address indexed transferStrategy);\n\n  /**\n   * @dev Emitted when the reward oracle is updated\n   * @param reward The address of the token reward\n   * @param rewardOracle The address of oracle\n   */\n  event RewardOracleUpdated(address indexed reward, address indexed rewardOracle);\n\n  /**\n   * @dev Whitelists an address to claim the rewards on behalf of another address\n   * @param user The address of the user\n   * @param claimer The address of the claimer\n   */\n  function setClaimer(address user, address claimer) external;\n\n  /**\n   * @dev Sets a TransferStrategy logic contract that determines the logic of the rewards transfer\n   * @param reward The address of the reward token\n   * @param transferStrategy The address of the TransferStrategy logic contract\n   */\n  function setTransferStrategy(address reward, ITransferStrategyBase transferStrategy) external;\n\n  /**\n   * @dev Sets an Aave Oracle contract to enforce rewards with a source of value.\n   * @notice At the moment of reward configuration, the Incentives Controller performs\n   * a check to see if the reward asset oracle is compatible with IEACAggregator proxy.\n   * This check is enforced for integrators to be able to show incentives at\n   * the current Aave UI without the need to setup an external price registry\n   * @param reward The address of the reward to set the price aggregator\n   * @param rewardOracle The address of price aggregator that follows IEACAggregatorProxy interface\n   */\n  function setRewardOracle(address reward, IEACAggregatorProxy rewardOracle) external;\n\n  /**\n   * @dev Get the price aggregator oracle address\n   * @param reward The address of the reward\n   * @return The price oracle of the reward\n   */\n  function getRewardOracle(address reward) external view returns (address);\n\n  /**\n   * @dev Returns the whitelisted claimer for a certain address (0x0 if not set)\n   * @param user The address of the user\n   * @return The claimer address\n   */\n  function getClaimer(address user) external view returns (address);\n\n  /**\n   * @dev Returns the Transfer Strategy implementation contract address being used for a reward address\n   * @param reward The address of the reward\n   * @return The address of the TransferStrategy contract\n   */\n  function getTransferStrategy(address reward) external view returns (address);\n\n  /**\n   * @dev Configure assets to incentivize with an emission of rewards per second until the end of distribution.\n   * @param config The assets configuration input, the list of structs contains the following fields:\n   *   uint104 emissionPerSecond: The emission per second following rewards unit decimals.\n   *   uint256 totalSupply: The total supply of the asset to incentivize\n   *   uint40 distributionEnd: The end of the distribution of the incentives for an asset\n   *   address asset: The asset address to incentivize\n   *   address reward: The reward token address\n   *   ITransferStrategy transferStrategy: The TransferStrategy address with the install hook and claim logic.\n   *   IEACAggregatorProxy rewardOracle: The Price Oracle of a reward to visualize the incentives at the UI Frontend.\n   *                                     Must follow Chainlink Aggregator IEACAggregatorProxy interface to be compatible.\n   */\n  function configureAssets(RewardsDataTypes.RewardsConfigInput[] memory config) external;\n\n  /**\n   * @dev Called by the corresponding asset on transfer hook in order to update the rewards distribution.\n   * @dev The units of `totalSupply` and `userBalance` should be the same.\n   * @param user The address of the user whose asset balance has changed\n   * @param totalSupply The total supply of the asset prior to user balance change\n   * @param userBalance The previous user balance prior to balance change\n   **/\n  function handleAction(address user, uint256 totalSupply, uint256 userBalance) external;\n\n  /**\n   * @dev Claims reward for a user to the desired address, on all the assets of the pool, accumulating the pending rewards\n   * @param assets List of assets to check eligible distributions before claiming rewards\n   * @param amount The amount of rewards to claim\n   * @param to The address that will be receiving the rewards\n   * @param reward The address of the reward token\n   * @return The amount of rewards claimed\n   **/\n  function claimRewards(\n    address[] calldata assets,\n    uint256 amount,\n    address to,\n    address reward\n  ) external returns (uint256);\n\n  /**\n   * @dev Claims reward for a user on behalf, on all the assets of the pool, accumulating the pending rewards. The\n   * caller must be whitelisted via \"allowClaimOnBehalf\" function by the RewardsAdmin role manager\n   * @param assets The list of assets to check eligible distributions before claiming rewards\n   * @param amount The amount of rewards to claim\n   * @param user The address to check and claim rewards\n   * @param to The address that will be receiving the rewards\n   * @param reward The address of the reward token\n   * @return The amount of rewards claimed\n   **/\n  function claimRewardsOnBehalf(\n    address[] calldata assets,\n    uint256 amount,\n    address user,\n    address to,\n    address reward\n  ) external returns (uint256);\n\n  /**\n   * @dev Claims reward for msg.sender, on all the assets of the pool, accumulating the pending rewards\n   * @param assets The list of assets to check eligible distributions before claiming rewards\n   * @param amount The amount of rewards to claim\n   * @param reward The address of the reward token\n   * @return The amount of rewards claimed\n   **/\n  function claimRewardsToSelf(\n    address[] calldata assets,\n    uint256 amount,\n    address reward\n  ) external returns (uint256);\n\n  /**\n   * @dev Claims all rewards for a user to the desired address, on all the assets of the pool, accumulating the pending rewards\n   * @param assets The list of assets to check eligible distributions before claiming rewards\n   * @param to The address that will be receiving the rewards\n   * @return rewardsList List of addresses of the reward tokens\n   * @return claimedAmounts List that contains the claimed amount per reward, following same order as \"rewardList\"\n   **/\n  function claimAllRewards(\n    address[] calldata assets,\n    address to\n  ) external returns (address[] memory rewardsList, uint256[] memory claimedAmounts);\n\n  /**\n   * @dev Claims all rewards for a user on behalf, on all the assets of the pool, accumulating the pending rewards. The caller must\n   * be whitelisted via \"allowClaimOnBehalf\" function by the RewardsAdmin role manager\n   * @param assets The list of assets to check eligible distributions before claiming rewards\n   * @param user The address to check and claim rewards\n   * @param to The address that will be receiving the rewards\n   * @return rewardsList List of addresses of the reward tokens\n   * @return claimedAmounts List that contains the claimed amount per reward, following same order as \"rewardsList\"\n   **/\n  function claimAllRewardsOnBehalf(\n    address[] calldata assets,\n    address user,\n    address to\n  ) external returns (address[] memory rewardsList, uint256[] memory claimedAmounts);\n\n  /**\n   * @dev Claims all reward for msg.sender, on all the assets of the pool, accumulating the pending rewards\n   * @param assets The list of assets to check eligible distributions before claiming rewards\n   * @return rewardsList List of addresses of the reward tokens\n   * @return claimedAmounts List that contains the claimed amount per reward, following same order as \"rewardsList\"\n   **/\n  function claimAllRewardsToSelf(\n    address[] calldata assets\n  ) external returns (address[] memory rewardsList, uint256[] memory claimedAmounts);\n}\n"
      },
      "src/periphery/contracts/rewards/interfaces/IRewardsDistributor.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n/**\n * @title IRewardsDistributor\n * @author Aave\n * @notice Defines the basic interface for a Rewards Distributor.\n */\ninterface IRewardsDistributor {\n  /**\n   * @dev Emitted when the configuration of the rewards of an asset is updated.\n   * @param asset The address of the incentivized asset\n   * @param reward The address of the reward token\n   * @param oldEmission The old emissions per second value of the reward distribution\n   * @param newEmission The new emissions per second value of the reward distribution\n   * @param oldDistributionEnd The old end timestamp of the reward distribution\n   * @param newDistributionEnd The new end timestamp of the reward distribution\n   * @param assetIndex The index of the asset distribution\n   */\n  event AssetConfigUpdated(\n    address indexed asset,\n    address indexed reward,\n    uint256 oldEmission,\n    uint256 newEmission,\n    uint256 oldDistributionEnd,\n    uint256 newDistributionEnd,\n    uint256 assetIndex\n  );\n\n  /**\n   * @dev Emitted when rewards of an asset are accrued on behalf of a user.\n   * @param asset The address of the incentivized asset\n   * @param reward The address of the reward token\n   * @param user The address of the user that rewards are accrued on behalf of\n   * @param assetIndex The index of the asset distribution\n   * @param userIndex The index of the asset distribution on behalf of the user\n   * @param rewardsAccrued The amount of rewards accrued\n   */\n  event Accrued(\n    address indexed asset,\n    address indexed reward,\n    address indexed user,\n    uint256 assetIndex,\n    uint256 userIndex,\n    uint256 rewardsAccrued\n  );\n\n  /**\n   * @dev Sets the end date for the distribution\n   * @param asset The asset to incentivize\n   * @param reward The reward token that incentives the asset\n   * @param newDistributionEnd The end date of the incentivization, in unix time format\n   **/\n  function setDistributionEnd(address asset, address reward, uint32 newDistributionEnd) external;\n\n  /**\n   * @dev Sets the emission per second of a set of reward distributions\n   * @param asset The asset is being incentivized\n   * @param rewards List of reward addresses are being distributed\n   * @param newEmissionsPerSecond List of new reward emissions per second\n   */\n  function setEmissionPerSecond(\n    address asset,\n    address[] calldata rewards,\n    uint88[] calldata newEmissionsPerSecond\n  ) external;\n\n  /**\n   * @dev Gets the end date for the distribution\n   * @param asset The incentivized asset\n   * @param reward The reward token of the incentivized asset\n   * @return The timestamp with the end of the distribution, in unix time format\n   **/\n  function getDistributionEnd(address asset, address reward) external view returns (uint256);\n\n  /**\n   * @dev Returns the index of a user on a reward distribution\n   * @param user Address of the user\n   * @param asset The incentivized asset\n   * @param reward The reward token of the incentivized asset\n   * @return The current user asset index, not including new distributions\n   **/\n  function getUserAssetIndex(\n    address user,\n    address asset,\n    address reward\n  ) external view returns (uint256);\n\n  /**\n   * @dev Returns the configuration of the distribution reward for a certain asset\n   * @param asset The incentivized asset\n   * @param reward The reward token of the incentivized asset\n   * @return The index of the asset distribution\n   * @return The emission per second of the reward distribution\n   * @return The timestamp of the last update of the index\n   * @return The timestamp of the distribution end\n   **/\n  function getRewardsData(\n    address asset,\n    address reward\n  ) external view returns (uint256, uint256, uint256, uint256);\n\n  /**\n   * @dev Calculates the next value of an specific distribution index, with validations.\n   * @param asset The incentivized asset\n   * @param reward The reward token of the incentivized asset\n   * @return The old index of the asset distribution\n   * @return The new index of the asset distribution\n   **/\n  function getAssetIndex(address asset, address reward) external view returns (uint256, uint256);\n\n  /**\n   * @dev Returns the list of available reward token addresses of an incentivized asset\n   * @param asset The incentivized asset\n   * @return List of rewards addresses of the input asset\n   **/\n  function getRewardsByAsset(address asset) external view returns (address[] memory);\n\n  /**\n   * @dev Returns the list of available reward addresses\n   * @return List of rewards supported in this contract\n   **/\n  function getRewardsList() external view returns (address[] memory);\n\n  /**\n   * @dev Returns the accrued rewards balance of a user, not including virtually accrued rewards since last distribution.\n   * @param user The address of the user\n   * @param reward The address of the reward token\n   * @return Unclaimed rewards, not including new distributions\n   **/\n  function getUserAccruedRewards(address user, address reward) external view returns (uint256);\n\n  /**\n   * @dev Returns a single rewards balance of a user, including virtually accrued and unrealized claimable rewards.\n   * @param assets List of incentivized assets to check eligible distributions\n   * @param user The address of the user\n   * @param reward The address of the reward token\n   * @return The rewards amount\n   **/\n  function getUserRewards(\n    address[] calldata assets,\n    address user,\n    address reward\n  ) external view returns (uint256);\n\n  /**\n   * @dev Returns a list all rewards of a user, including already accrued and unrealized claimable rewards\n   * @param assets List of incentivized assets to check eligible distributions\n   * @param user The address of the user\n   * @return The list of reward addresses\n   * @return The list of unclaimed amount of rewards\n   **/\n  function getAllUserRewards(\n    address[] calldata assets,\n    address user\n  ) external view returns (address[] memory, uint256[] memory);\n\n  /**\n   * @dev Returns the decimals of an asset to calculate the distribution delta\n   * @param asset The address to retrieve decimals\n   * @return The decimals of an underlying asset\n   */\n  function getAssetDecimals(address asset) external view returns (uint8);\n\n  /**\n   * @dev Returns the address of the emission manager\n   * @return The address of the EmissionManager\n   */\n  function EMISSION_MANAGER() external view returns (address);\n\n  /**\n   * @dev Returns the address of the emission manager.\n   * Deprecated: This getter is maintained for compatibility purposes. Use the `EMISSION_MANAGER()` function instead.\n   * @return The address of the EmissionManager\n   */\n  function getEmissionManager() external view returns (address);\n}\n"
      },
      "src/periphery/contracts/rewards/interfaces/ITransferStrategyBase.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface ITransferStrategyBase {\n  event EmergencyWithdrawal(\n    address indexed caller,\n    address indexed token,\n    address indexed to,\n    uint256 amount\n  );\n\n  /**\n   * @dev Perform custom transfer logic via delegate call from source contract to a TransferStrategy implementation\n   * @param to Account to transfer rewards\n   * @param reward Address of the reward token\n   * @param amount Amount to transfer to the \"to\" address parameter\n   * @return Returns true bool if transfer logic succeeds\n   */\n  function performTransfer(address to, address reward, uint256 amount) external returns (bool);\n\n  /**\n   * @return Returns the address of the Incentives Controller\n   */\n  function getIncentivesController() external view returns (address);\n\n  /**\n   * @return Returns the address of the Rewards admin\n   */\n  function getRewardsAdmin() external view returns (address);\n\n  /**\n   * @dev Perform an emergency token withdrawal only callable by the Rewards admin\n   * @param token Address of the token to withdraw funds from this contract\n   * @param to Address of the recipient of the withdrawal\n   * @param amount Amount of the withdrawal\n   */\n  function emergencyWithdrawal(address token, address to, uint256 amount) external;\n}\n"
      },
      "src/periphery/contracts/rewards/libraries/RewardsDataTypes.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport {ITransferStrategyBase} from '../interfaces/ITransferStrategyBase.sol';\nimport {IEACAggregatorProxy} from '../../misc/interfaces/IEACAggregatorProxy.sol';\n\nlibrary RewardsDataTypes {\n  struct RewardsConfigInput {\n    uint88 emissionPerSecond;\n    uint256 totalSupply;\n    uint32 distributionEnd;\n    address asset;\n    address reward;\n    ITransferStrategyBase transferStrategy;\n    IEACAggregatorProxy rewardOracle;\n  }\n\n  struct UserAssetBalance {\n    address asset;\n    uint256 userBalance;\n    uint256 totalSupply;\n  }\n\n  struct UserData {\n    // Liquidity index of the reward distribution for the user\n    uint104 index;\n    // Amount of accrued rewards for the user since last user index update\n    uint128 accrued;\n  }\n\n  struct RewardData {\n    // Liquidity index of the reward distribution\n    uint104 index;\n    // Amount of reward tokens distributed per second\n    uint88 emissionPerSecond;\n    // Timestamp of the last reward index update\n    uint32 lastUpdateTimestamp;\n    // The end of the distribution of rewards (in seconds)\n    uint32 distributionEnd;\n    // Map of user addresses and their rewards data (userAddress => userData)\n    mapping(address => UserData) usersData;\n  }\n\n  struct AssetData {\n    // Map of reward token addresses and their data (rewardTokenAddress => rewardData)\n    mapping(address => RewardData) rewards;\n    // List of reward token addresses for the asset\n    mapping(uint128 => address) availableRewards;\n    // Count of reward tokens for the asset\n    uint128 availableRewardsCount;\n    // Number of decimals of the asset\n    uint8 decimals;\n  }\n}\n"
      }
    },
    "settings": {
      "remappings": [
        "aave-v3-core/=src/core/",
        "aave-v3-periphery/=src/periphery/",
        "aave-collector-unification/=lib/aave-collector-unification/",
        "solidity-utils/=lib/solidity-utils/src/",
        "aave-helpers/=lib/aave-helpers/src/",
        "aave-address-book/=lib/aave-address-book/src/",
        "forge-std/=lib/forge-std/src/",
        "ds-test/=lib/forge-std/lib/ds-test/src/",
        "@aave/core-v2/=lib/aave-collector-unification/lib/protocol-v2/",
        "@aave/core-v3/=lib/aave-address-book/lib/aave-v3-core/",
        "@aave/periphery-v3/=lib/aave-address-book/lib/aave-v3-periphery/",
        "governance-crosschain-bridges/=lib/aave-helpers/lib/governance-crosschain-bridges/",
        "protocol-v2/=lib/aave-collector-unification/lib/protocol-v2/"
      ],
      "optimizer": {
        "enabled": true,
        "runs": 200
      },
      "metadata": {
        "useLiteralContent": false,
        "bytecodeHash": "none",
        "appendCBOR": true
      },
      "outputSelection": {
        "*": {
          "*": [
            "evm.bytecode",
            "evm.deployedBytecode",
            "devdoc",
            "userdoc",
            "metadata",
            "abi"
          ]
        }
      },
      "evmVersion": "paris",
      "libraries": {}
    },
    "language": "Solidity"
  }}