File size: 52,945 Bytes
f998fcd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
{
  "language": "Solidity",
  "sources": {
    "lib/solmate/src/tokens/ERC20.sol": {
      "content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity >=0.8.0;\n\n/// @notice Modern and gas efficient ERC20 + EIP-2612 implementation.\n/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC20.sol)\n/// @author Modified from Uniswap (https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2ERC20.sol)\n/// @dev Do not manually set balances without updating totalSupply, as the sum of all user balances must not exceed it.\nabstract contract ERC20 {\n    /*//////////////////////////////////////////////////////////////\n                                 EVENTS\n    //////////////////////////////////////////////////////////////*/\n\n    event Transfer(address indexed from, address indexed to, uint256 amount);\n\n    event Approval(address indexed owner, address indexed spender, uint256 amount);\n\n    /*//////////////////////////////////////////////////////////////\n                            METADATA STORAGE\n    //////////////////////////////////////////////////////////////*/\n\n    string public name;\n\n    string public symbol;\n\n    uint8 public immutable decimals;\n\n    /*//////////////////////////////////////////////////////////////\n                              ERC20 STORAGE\n    //////////////////////////////////////////////////////////////*/\n\n    uint256 public totalSupply;\n\n    mapping(address => uint256) public balanceOf;\n\n    mapping(address => mapping(address => uint256)) public allowance;\n\n    /*//////////////////////////////////////////////////////////////\n                            EIP-2612 STORAGE\n    //////////////////////////////////////////////////////////////*/\n\n    uint256 internal immutable INITIAL_CHAIN_ID;\n\n    bytes32 internal immutable INITIAL_DOMAIN_SEPARATOR;\n\n    mapping(address => uint256) public nonces;\n\n    /*//////////////////////////////////////////////////////////////\n                               CONSTRUCTOR\n    //////////////////////////////////////////////////////////////*/\n\n    constructor(\n        string memory _name,\n        string memory _symbol,\n        uint8 _decimals\n    ) {\n        name = _name;\n        symbol = _symbol;\n        decimals = _decimals;\n\n        INITIAL_CHAIN_ID = block.chainid;\n        INITIAL_DOMAIN_SEPARATOR = computeDomainSeparator();\n    }\n\n    /*//////////////////////////////////////////////////////////////\n                               ERC20 LOGIC\n    //////////////////////////////////////////////////////////////*/\n\n    function approve(address spender, uint256 amount) public virtual returns (bool) {\n        allowance[msg.sender][spender] = amount;\n\n        emit Approval(msg.sender, spender, amount);\n\n        return true;\n    }\n\n    function transfer(address to, uint256 amount) public virtual returns (bool) {\n        balanceOf[msg.sender] -= amount;\n\n        // Cannot overflow because the sum of all user\n        // balances can't exceed the max uint256 value.\n        unchecked {\n            balanceOf[to] += amount;\n        }\n\n        emit Transfer(msg.sender, to, amount);\n\n        return true;\n    }\n\n    function transferFrom(\n        address from,\n        address to,\n        uint256 amount\n    ) public virtual returns (bool) {\n        uint256 allowed = allowance[from][msg.sender]; // Saves gas for limited approvals.\n\n        if (allowed != type(uint256).max) allowance[from][msg.sender] = allowed - amount;\n\n        balanceOf[from] -= amount;\n\n        // Cannot overflow because the sum of all user\n        // balances can't exceed the max uint256 value.\n        unchecked {\n            balanceOf[to] += amount;\n        }\n\n        emit Transfer(from, to, amount);\n\n        return true;\n    }\n\n    /*//////////////////////////////////////////////////////////////\n                             EIP-2612 LOGIC\n    //////////////////////////////////////////////////////////////*/\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    ) public virtual {\n        require(deadline >= block.timestamp, \"PERMIT_DEADLINE_EXPIRED\");\n\n        // Unchecked because the only math done is incrementing\n        // the owner's nonce which cannot realistically overflow.\n        unchecked {\n            address recoveredAddress = ecrecover(\n                keccak256(\n                    abi.encodePacked(\n                        \"\\x19\\x01\",\n                        DOMAIN_SEPARATOR(),\n                        keccak256(\n                            abi.encode(\n                                keccak256(\n                                    \"Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)\"\n                                ),\n                                owner,\n                                spender,\n                                value,\n                                nonces[owner]++,\n                                deadline\n                            )\n                        )\n                    )\n                ),\n                v,\n                r,\n                s\n            );\n\n            require(recoveredAddress != address(0) && recoveredAddress == owner, \"INVALID_SIGNER\");\n\n            allowance[recoveredAddress][spender] = value;\n        }\n\n        emit Approval(owner, spender, value);\n    }\n\n    function DOMAIN_SEPARATOR() public view virtual returns (bytes32) {\n        return block.chainid == INITIAL_CHAIN_ID ? INITIAL_DOMAIN_SEPARATOR : computeDomainSeparator();\n    }\n\n    function computeDomainSeparator() internal view virtual returns (bytes32) {\n        return\n            keccak256(\n                abi.encode(\n                    keccak256(\"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)\"),\n                    keccak256(bytes(name)),\n                    keccak256(\"1\"),\n                    block.chainid,\n                    address(this)\n                )\n            );\n    }\n\n    /*//////////////////////////////////////////////////////////////\n                        INTERNAL MINT/BURN LOGIC\n    //////////////////////////////////////////////////////////////*/\n\n    function _mint(address to, uint256 amount) internal virtual {\n        totalSupply += amount;\n\n        // Cannot overflow because the sum of all user\n        // balances can't exceed the max uint256 value.\n        unchecked {\n            balanceOf[to] += amount;\n        }\n\n        emit Transfer(address(0), to, amount);\n    }\n\n    function _burn(address from, uint256 amount) internal virtual {\n        balanceOf[from] -= amount;\n\n        // Cannot underflow because a user's balance\n        // will never be larger than the total supply.\n        unchecked {\n            totalSupply -= amount;\n        }\n\n        emit Transfer(from, address(0), amount);\n    }\n}\n"
    },
    "lib/solmate/src/utils/FixedPointMathLib.sol": {
      "content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity >=0.8.0;\n\n/// @notice Arithmetic library with operations for fixed-point numbers.\n/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/FixedPointMathLib.sol)\n/// @author Inspired by USM (https://github.com/usmfum/USM/blob/master/contracts/WadMath.sol)\nlibrary FixedPointMathLib {\n    /*//////////////////////////////////////////////////////////////\n                    SIMPLIFIED FIXED POINT OPERATIONS\n    //////////////////////////////////////////////////////////////*/\n\n    uint256 internal constant MAX_UINT256 = 2**256 - 1;\n\n    uint256 internal constant WAD = 1e18; // The scalar of ETH and most ERC20s.\n\n    function mulWadDown(uint256 x, uint256 y) internal pure returns (uint256) {\n        return mulDivDown(x, y, WAD); // Equivalent to (x * y) / WAD rounded down.\n    }\n\n    function mulWadUp(uint256 x, uint256 y) internal pure returns (uint256) {\n        return mulDivUp(x, y, WAD); // Equivalent to (x * y) / WAD rounded up.\n    }\n\n    function divWadDown(uint256 x, uint256 y) internal pure returns (uint256) {\n        return mulDivDown(x, WAD, y); // Equivalent to (x * WAD) / y rounded down.\n    }\n\n    function divWadUp(uint256 x, uint256 y) internal pure returns (uint256) {\n        return mulDivUp(x, WAD, y); // Equivalent to (x * WAD) / y rounded up.\n    }\n\n    /*//////////////////////////////////////////////////////////////\n                    LOW LEVEL FIXED POINT OPERATIONS\n    //////////////////////////////////////////////////////////////*/\n\n    function mulDivDown(\n        uint256 x,\n        uint256 y,\n        uint256 denominator\n    ) internal pure returns (uint256 z) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            // Equivalent to require(denominator != 0 && (y == 0 || x <= type(uint256).max / y))\n            if iszero(mul(denominator, iszero(mul(y, gt(x, div(MAX_UINT256, y)))))) {\n                revert(0, 0)\n            }\n\n            // Divide x * y by the denominator.\n            z := div(mul(x, y), denominator)\n        }\n    }\n\n    function mulDivUp(\n        uint256 x,\n        uint256 y,\n        uint256 denominator\n    ) internal pure returns (uint256 z) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            // Equivalent to require(denominator != 0 && (y == 0 || x <= type(uint256).max / y))\n            if iszero(mul(denominator, iszero(mul(y, gt(x, div(MAX_UINT256, y)))))) {\n                revert(0, 0)\n            }\n\n            // If x * y modulo the denominator is strictly greater than 0,\n            // 1 is added to round up the division of x * y by the denominator.\n            z := add(gt(mod(mul(x, y), denominator), 0), div(mul(x, y), denominator))\n        }\n    }\n\n    function rpow(\n        uint256 x,\n        uint256 n,\n        uint256 scalar\n    ) internal pure returns (uint256 z) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            switch x\n            case 0 {\n                switch n\n                case 0 {\n                    // 0 ** 0 = 1\n                    z := scalar\n                }\n                default {\n                    // 0 ** n = 0\n                    z := 0\n                }\n            }\n            default {\n                switch mod(n, 2)\n                case 0 {\n                    // If n is even, store scalar in z for now.\n                    z := scalar\n                }\n                default {\n                    // If n is odd, store x in z for now.\n                    z := x\n                }\n\n                // Shifting right by 1 is like dividing by 2.\n                let half := shr(1, scalar)\n\n                for {\n                    // Shift n right by 1 before looping to halve it.\n                    n := shr(1, n)\n                } n {\n                    // Shift n right by 1 each iteration to halve it.\n                    n := shr(1, n)\n                } {\n                    // Revert immediately if x ** 2 would overflow.\n                    // Equivalent to iszero(eq(div(xx, x), x)) here.\n                    if shr(128, x) {\n                        revert(0, 0)\n                    }\n\n                    // Store x squared.\n                    let xx := mul(x, x)\n\n                    // Round to the nearest number.\n                    let xxRound := add(xx, half)\n\n                    // Revert if xx + half overflowed.\n                    if lt(xxRound, xx) {\n                        revert(0, 0)\n                    }\n\n                    // Set x to scaled xxRound.\n                    x := div(xxRound, scalar)\n\n                    // If n is even:\n                    if mod(n, 2) {\n                        // Compute z * x.\n                        let zx := mul(z, x)\n\n                        // If z * x overflowed:\n                        if iszero(eq(div(zx, x), z)) {\n                            // Revert if x is non-zero.\n                            if iszero(iszero(x)) {\n                                revert(0, 0)\n                            }\n                        }\n\n                        // Round to the nearest number.\n                        let zxRound := add(zx, half)\n\n                        // Revert if zx + half overflowed.\n                        if lt(zxRound, zx) {\n                            revert(0, 0)\n                        }\n\n                        // Return properly scaled zxRound.\n                        z := div(zxRound, scalar)\n                    }\n                }\n            }\n        }\n    }\n\n    /*//////////////////////////////////////////////////////////////\n                        GENERAL NUMBER UTILITIES\n    //////////////////////////////////////////////////////////////*/\n\n    function sqrt(uint256 x) internal pure returns (uint256 z) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            let y := x // We start y at x, which will help us make our initial estimate.\n\n            z := 181 // The \"correct\" value is 1, but this saves a multiplication later.\n\n            // This segment is to get a reasonable initial estimate for the Babylonian method. With a bad\n            // start, the correct # of bits increases ~linearly each iteration instead of ~quadratically.\n\n            // We check y >= 2^(k + 8) but shift right by k bits\n            // each branch to ensure that if x >= 256, then y >= 256.\n            if iszero(lt(y, 0x10000000000000000000000000000000000)) {\n                y := shr(128, y)\n                z := shl(64, z)\n            }\n            if iszero(lt(y, 0x1000000000000000000)) {\n                y := shr(64, y)\n                z := shl(32, z)\n            }\n            if iszero(lt(y, 0x10000000000)) {\n                y := shr(32, y)\n                z := shl(16, z)\n            }\n            if iszero(lt(y, 0x1000000)) {\n                y := shr(16, y)\n                z := shl(8, z)\n            }\n\n            // Goal was to get z*z*y within a small factor of x. More iterations could\n            // get y in a tighter range. Currently, we will have y in [256, 256*2^16).\n            // We ensured y >= 256 so that the relative difference between y and y+1 is small.\n            // That's not possible if x < 256 but we can just verify those cases exhaustively.\n\n            // Now, z*z*y <= x < z*z*(y+1), and y <= 2^(16+8), and either y >= 256, or x < 256.\n            // Correctness can be checked exhaustively for x < 256, so we assume y >= 256.\n            // Then z*sqrt(y) is within sqrt(257)/sqrt(256) of sqrt(x), or about 20bps.\n\n            // For s in the range [1/256, 256], the estimate f(s) = (181/1024) * (s+1) is in the range\n            // (1/2.84 * sqrt(s), 2.84 * sqrt(s)), with largest error when s = 1 and when s = 256 or 1/256.\n\n            // Since y is in [256, 256*2^16), let a = y/65536, so that a is in [1/256, 256). Then we can estimate\n            // sqrt(y) using sqrt(65536) * 181/1024 * (a + 1) = 181/4 * (y + 65536)/65536 = 181 * (y + 65536)/2^18.\n\n            // There is no overflow risk here since y < 2^136 after the first branch above.\n            z := shr(18, mul(z, add(y, 65536))) // A mul() is saved from starting z at 181.\n\n            // Given the worst case multiplicative error of 2.84 above, 7 iterations should be enough.\n            z := shr(1, add(z, div(x, z)))\n            z := shr(1, add(z, div(x, z)))\n            z := shr(1, add(z, div(x, z)))\n            z := shr(1, add(z, div(x, z)))\n            z := shr(1, add(z, div(x, z)))\n            z := shr(1, add(z, div(x, z)))\n            z := shr(1, add(z, div(x, z)))\n\n            // If x+1 is a perfect square, the Babylonian method cycles between\n            // floor(sqrt(x)) and ceil(sqrt(x)). This statement ensures we return floor.\n            // See: https://en.wikipedia.org/wiki/Integer_square_root#Using_only_integer_division\n            // Since the ceil is rare, we save gas on the assignment and repeat division in the rare case.\n            // If you don't care whether the floor or ceil square root is returned, you can remove this statement.\n            z := sub(z, lt(div(x, z), z))\n        }\n    }\n\n    function unsafeMod(uint256 x, uint256 y) internal pure returns (uint256 z) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            // Mod x by y. Note this will return\n            // 0 instead of reverting if y is zero.\n            z := mod(x, y)\n        }\n    }\n\n    function unsafeDiv(uint256 x, uint256 y) internal pure returns (uint256 r) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            // Divide x by y. Note this will return\n            // 0 instead of reverting if y is zero.\n            r := div(x, y)\n        }\n    }\n\n    function unsafeDivUp(uint256 x, uint256 y) internal pure returns (uint256 z) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            // Add 1 to x * y if x % y > 0. Note this will\n            // return 0 instead of reverting if y is zero.\n            z := add(gt(mod(x, y), 0), div(x, y))\n        }\n    }\n}\n"
    },
    "lib/solmate/src/utils/SafeTransferLib.sol": {
      "content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity >=0.8.0;\n\nimport {ERC20} from \"../tokens/ERC20.sol\";\n\n/// @notice Safe ETH and ERC20 transfer library that gracefully handles missing return values.\n/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/SafeTransferLib.sol)\n/// @dev Use with caution! Some functions in this library knowingly create dirty bits at the destination of the free memory pointer.\n/// @dev Note that none of the functions in this library check that a token has code at all! That responsibility is delegated to the caller.\nlibrary SafeTransferLib {\n    /*//////////////////////////////////////////////////////////////\n                             ETH OPERATIONS\n    //////////////////////////////////////////////////////////////*/\n\n    function safeTransferETH(address to, uint256 amount) internal {\n        bool success;\n\n        /// @solidity memory-safe-assembly\n        assembly {\n            // Transfer the ETH and store if it succeeded or not.\n            success := call(gas(), to, amount, 0, 0, 0, 0)\n        }\n\n        require(success, \"ETH_TRANSFER_FAILED\");\n    }\n\n    /*//////////////////////////////////////////////////////////////\n                            ERC20 OPERATIONS\n    //////////////////////////////////////////////////////////////*/\n\n    function safeTransferFrom(\n        ERC20 token,\n        address from,\n        address to,\n        uint256 amount\n    ) internal {\n        bool success;\n\n        /// @solidity memory-safe-assembly\n        assembly {\n            // Get a pointer to some free memory.\n            let freeMemoryPointer := mload(0x40)\n\n            // Write the abi-encoded calldata into memory, beginning with the function selector.\n            mstore(freeMemoryPointer, 0x23b872dd00000000000000000000000000000000000000000000000000000000)\n            mstore(add(freeMemoryPointer, 4), from) // Append the \"from\" argument.\n            mstore(add(freeMemoryPointer, 36), to) // Append the \"to\" argument.\n            mstore(add(freeMemoryPointer, 68), amount) // Append the \"amount\" argument.\n\n            success := and(\n                // Set success to whether the call reverted, if not we check it either\n                // returned exactly 1 (can't just be non-zero data), or had no return data.\n                or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),\n                // We use 100 because the length of our calldata totals up like so: 4 + 32 * 3.\n                // We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.\n                // Counterintuitively, this call must be positioned second to the or() call in the\n                // surrounding and() call or else returndatasize() will be zero during the computation.\n                call(gas(), token, 0, freeMemoryPointer, 100, 0, 32)\n            )\n        }\n\n        require(success, \"TRANSFER_FROM_FAILED\");\n    }\n\n    function safeTransfer(\n        ERC20 token,\n        address to,\n        uint256 amount\n    ) internal {\n        bool success;\n\n        /// @solidity memory-safe-assembly\n        assembly {\n            // Get a pointer to some free memory.\n            let freeMemoryPointer := mload(0x40)\n\n            // Write the abi-encoded calldata into memory, beginning with the function selector.\n            mstore(freeMemoryPointer, 0xa9059cbb00000000000000000000000000000000000000000000000000000000)\n            mstore(add(freeMemoryPointer, 4), to) // Append the \"to\" argument.\n            mstore(add(freeMemoryPointer, 36), amount) // Append the \"amount\" argument.\n\n            success := and(\n                // Set success to whether the call reverted, if not we check it either\n                // returned exactly 1 (can't just be non-zero data), or had no return data.\n                or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),\n                // We use 68 because the length of our calldata totals up like so: 4 + 32 * 2.\n                // We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.\n                // Counterintuitively, this call must be positioned second to the or() call in the\n                // surrounding and() call or else returndatasize() will be zero during the computation.\n                call(gas(), token, 0, freeMemoryPointer, 68, 0, 32)\n            )\n        }\n\n        require(success, \"TRANSFER_FAILED\");\n    }\n\n    function safeApprove(\n        ERC20 token,\n        address to,\n        uint256 amount\n    ) internal {\n        bool success;\n\n        /// @solidity memory-safe-assembly\n        assembly {\n            // Get a pointer to some free memory.\n            let freeMemoryPointer := mload(0x40)\n\n            // Write the abi-encoded calldata into memory, beginning with the function selector.\n            mstore(freeMemoryPointer, 0x095ea7b300000000000000000000000000000000000000000000000000000000)\n            mstore(add(freeMemoryPointer, 4), to) // Append the \"to\" argument.\n            mstore(add(freeMemoryPointer, 36), amount) // Append the \"amount\" argument.\n\n            success := and(\n                // Set success to whether the call reverted, if not we check it either\n                // returned exactly 1 (can't just be non-zero data), or had no return data.\n                or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),\n                // We use 68 because the length of our calldata totals up like so: 4 + 32 * 2.\n                // We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.\n                // Counterintuitively, this call must be positioned second to the or() call in the\n                // surrounding and() call or else returndatasize() will be zero during the computation.\n                call(gas(), token, 0, freeMemoryPointer, 68, 0, 32)\n            )\n        }\n\n        require(success, \"APPROVE_FAILED\");\n    }\n}\n"
    },
    "src/Strategy.sol": {
      "content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity 0.8.9;\n\nimport './Vault.sol';\n\n/** @dev\n * Strategies have to implement the following virtual functions:\n *\n * totalAssets()\n * _withdraw(uint256, address)\n * _harvest()\n * _invest()\n */\nabstract contract Strategy is Ownership {\n\tusing FixedPointMathLib for uint256;\n\n\tVault public immutable vault;\n\tERC20 public immutable asset;\n\n\t/// @notice address which performance fees are sent to\n\taddress public treasury;\n\t/// @notice performance fee sent to treasury / FEE_BASIS of 10_000\n\tuint16 public fee = 1_000;\n\tuint16 internal constant MAX_FEE = 1_000;\n\tuint16 internal constant FEE_BASIS = 10_000;\n\n\t/// @notice used to calculate slippage / SLIP_BASIS of 10_000\n\t/// @dev default to 99% (or 1%)\n\tuint16 public slip = 9_900;\n\tuint16 internal constant SLIP_BASIS = 10_000;\n\n\t/*//////////////////\n\t/      Events      /\n\t//////////////////*/\n\n\tevent FeeChanged(uint16 newFee);\n\tevent SlipChanged(uint16 newSlip);\n\tevent TreasuryChanged(address indexed newTreasury);\n\n\t/*//////////////////\n\t/      Errors      /\n\t//////////////////*/\n\n\terror Zero();\n\terror NotVault();\n\terror InvalidValue();\n\terror AlreadyValue();\n\n\tconstructor(\n\t\tVault _vault,\n\t\taddress _treasury,\n\t\taddress[] memory _authorized\n\t) Ownership(_authorized) {\n\t\tvault = _vault;\n\t\tasset = vault.asset();\n\t\ttreasury = _treasury;\n\t}\n\n\t/*//////////////////////////\n\t/      Public Virtual      /\n\t//////////////////////////*/\n\n\t/// @notice amount of 'asset' currently managed by strategy\n\tfunction totalAssets() public view virtual returns (uint256);\n\n\t/*///////////////////////////////////////////\n\t/      Restricted Functions: onlyVault      /\n\t///////////////////////////////////////////*/\n\n\tfunction withdraw(uint256 _assets, address _receiver)\n\t\texternal\n\t\tonlyVault\n\t\treturns (uint256 received, uint256 slippage)\n\t{\n\t\treceived = _withdraw(_assets, _receiver);\n\t\treceived = received > _assets ? _assets : received; // received cannot > _assets for vault calculations\n\n\t\tunchecked {\n\t\t\tslippage = _assets - received;\n\t\t}\n\t}\n\n\t/*//////////////////////////////////////////////////\n\t/      Restricted Functions: onlyAdminOrVault      /\n\t//////////////////////////////////////////////////*/\n\n\tfunction harvest() external onlyAdminOrVault returns (uint256 assets) {\n\t\treturn _harvest();\n\t}\n\n\tfunction invest() external onlyAdminOrVault {\n\t\t_invest();\n\t}\n\n\t/*///////////////////////////////////////////\n\t/      Restricted Functions: onlyOwner      /\n\t///////////////////////////////////////////*/\n\n\tfunction setFee(uint16 _fee) external onlyOwner {\n\t\tif (_fee > MAX_FEE) revert InvalidValue();\n\t\tif (_fee == fee) revert AlreadyValue();\n\t\tfee = _fee;\n\t\temit FeeChanged(_fee);\n\t}\n\n\tfunction setTreasury(address _treasury) external onlyOwner {\n\t\tif (_treasury == treasury) revert AlreadyValue();\n\t\ttreasury = _treasury;\n\t\temit TreasuryChanged(_treasury);\n\t}\n\n\t/*////////////////////////////////////////////\n\t/      Restricted Functions: onlyAdmins      /\n\t////////////////////////////////////////////*/\n\n\tfunction setSlip(uint16 _slip) external onlyAdmins {\n\t\tif (_slip > SLIP_BASIS) revert InvalidValue();\n\t\tif (_slip == slip) revert AlreadyValue();\n\t\tslip = _slip;\n\t\temit SlipChanged(_slip);\n\t}\n\n\t/*////////////////////////////\n\t/      Internal Virtual      /\n\t////////////////////////////*/\n\n\t/// @dev this must handle overflow, i.e. vault trying to withdraw more than what strategy has\n\tfunction _withdraw(uint256 _assets, address _receiver) internal virtual returns (uint256 received);\n\n\t/// @dev return harvested assets\n\tfunction _harvest() internal virtual returns (uint256 received);\n\n\tfunction _invest() internal virtual;\n\n\t/*//////////////////////////////\n\t/      Internal Functions      /\n\t//////////////////////////////*/\n\n\tfunction _calculateSlippage(uint256 _amount) internal view returns (uint256) {\n\t\treturn _amount.mulDivDown(slip, SLIP_BASIS);\n\t}\n\n\tfunction _calculateFee(uint256 _amount) internal view returns (uint256) {\n\t\treturn _amount.mulDivDown(fee, FEE_BASIS);\n\t}\n\n\tmodifier onlyVault() {\n\t\tif (msg.sender != address(vault)) revert NotVault();\n\t\t_;\n\t}\n\n\t/*//////////////////////////////\n\t/      Internal Functions      /\n\t//////////////////////////////*/\n\n\tmodifier onlyAdminOrVault() {\n\t\tif (msg.sender != owner && msg.sender != admin && msg.sender != address(vault)) revert Unauthorized();\n\t\t_;\n\t}\n}\n"
    },
    "src/Vault.sol": {
      "content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.9;\n\nimport 'solmate/tokens/ERC20.sol';\nimport 'solmate/utils/SafeTransferLib.sol';\nimport 'solmate/utils/FixedPointMathLib.sol';\n\nimport './libraries/Ownership.sol';\nimport './libraries/BlockDelay.sol';\nimport './interfaces/IERC4626.sol';\nimport './Strategy.sol';\n\ncontract Vault is ERC20, IERC4626, Ownership, BlockDelay {\n\tusing SafeTransferLib for ERC20;\n\tusing FixedPointMathLib for uint256;\n\n\t/// @notice token which the vault uses and accumulates\n\tERC20 public immutable asset;\n\n\t/// @notice whether deposits and withdrawals are paused\n\tbool public paused;\n\n\tuint256 private _lockedProfit;\n\t/// @notice timestamp of last report, used for locked profit calculations\n\tuint256 public lastReport;\n\t/// @notice period over which profits are gradually unlocked, defense against sandwich attacks\n\tuint256 public lockedProfitDuration = 6 hours;\n\tuint256 internal constant MAX_LOCKED_PROFIT_DURATION = 3 days;\n\n\t/// @dev maximum user can deposit in a single tx\n\tuint256 private _maxDeposit = type(uint256).max;\n\n\tstruct StrategyParams {\n\t\tbool added;\n\t\tuint256 debt;\n\t\tuint256 debtRatio;\n\t}\n\n\tStrategy[] private _queue;\n\tmapping(Strategy => StrategyParams) public strategies;\n\n\tuint8 internal constant MAX_QUEUE_LENGTH = 20;\n\n\tuint256 public totalDebt;\n\tuint256 public totalDebtRatio;\n\tuint256 internal constant MAX_TOTAL_DEBT_RATIO = 1_000;\n\n\t/*//////////////////\n\t/      Events      /\n\t//////////////////*/\n\n\tevent Report(Strategy indexed strategy, uint256 harvested, uint256 gain, uint256 loss);\n\tevent Lend(Strategy indexed strategy, uint256 assets, uint256 slippage);\n\tevent Collect(Strategy indexed strategy, uint256 received, uint256 slippage);\n\n\tevent StrategyAdded(Strategy indexed strategy, uint256 debtRatio);\n\tevent StrategyDebtRatioChanged(Strategy indexed strategy, uint256 newDebtRatio);\n\tevent StrategyRemoved(Strategy indexed strategy);\n\tevent StrategyQueuePositionsSwapped(uint8 i, uint8 j, Strategy indexed newI, Strategy indexed newJ);\n\n\tevent LockedProfitDurationChanged(uint256 newDuration);\n\tevent MaxDepositChanged(uint256 newMaxDeposit);\n\n\t/*//////////////////\n\t/      Errors      /\n\t//////////////////*/\n\n\terror Zero();\n\terror BelowMinimum(uint256);\n\terror AboveMaximum(uint256);\n\n\terror AboveMaxDeposit();\n\n\terror AlreadyStrategy();\n\terror NotStrategy();\n\terror StrategyDoesNotBelongToQueue();\n\terror StrategyQueueFull();\n\n\terror AlreadyValue();\n\n\terror Paused();\n\n\t/// @dev e.g. USDC becomes 'Unagii USD Coin Vault v3' and 'uUSDCv3'\n\tconstructor(\n\t\tERC20 _asset,\n\t\taddress[] memory _authorized,\n\t\tuint8 _blockDelay\n\t)\n\t\tERC20(\n\t\t\tstring(abi.encodePacked('Unagii ', _asset.name(), ' Vault v3')),\n\t\t\tstring(abi.encodePacked('u', _asset.symbol(), 'v3')),\n\t\t\t_asset.decimals()\n\t\t)\n\t\tOwnership(_authorized)\n\t\tBlockDelay(_blockDelay)\n\t{\n\t\tasset = _asset;\n\t}\n\n\t/*///////////////////////\n\t/      Public View      /\n\t///////////////////////*/\n\n\tfunction queue() external view returns (Strategy[] memory) {\n\t\treturn _queue;\n\t}\n\n\tfunction totalAssets() public view returns (uint256 assets) {\n\t\treturn asset.balanceOf(address(this)) + totalDebt;\n\t}\n\n\tfunction lockedProfit() public view returns (uint256 lockedAssets) {\n\t\tuint256 last = lastReport;\n\t\tuint256 duration = lockedProfitDuration;\n\n\t\tunchecked {\n\t\t\t// won't overflow since time is nowhere near uint256.max\n\t\t\tif (block.timestamp >= last + duration) return 0;\n\t\t\t// can overflow if _lockedProfit * difference > uint256.max but in practice should never happen\n\t\t\treturn _lockedProfit - _lockedProfit.mulDivDown(block.timestamp - last, duration);\n\t\t}\n\t}\n\n\tfunction freeAssets() public view returns (uint256 assets) {\n\t\treturn totalAssets() - lockedProfit();\n\t}\n\n\tfunction convertToShares(uint256 _assets) public view returns (uint256 shares) {\n\t\tuint256 supply = totalSupply;\n\t\treturn supply == 0 ? _assets : _assets.mulDivDown(supply, totalAssets());\n\t}\n\n\tfunction convertToAssets(uint256 _shares) public view returns (uint256 assets) {\n\t\tuint256 supply = totalSupply;\n\t\treturn supply == 0 ? _shares : _shares.mulDivDown(totalAssets(), supply);\n\t}\n\n\tfunction maxDeposit(address) external view returns (uint256 assets) {\n\t\treturn _maxDeposit;\n\t}\n\n\tfunction previewDeposit(uint256 _assets) public view returns (uint256 shares) {\n\t\treturn convertToShares(_assets);\n\t}\n\n\tfunction maxMint(address) external view returns (uint256 shares) {\n\t\treturn convertToShares(_maxDeposit);\n\t}\n\n\tfunction previewMint(uint256 shares) public view returns (uint256 assets) {\n\t\tuint256 supply = totalSupply;\n\t\treturn supply == 0 ? shares : shares.mulDivUp(totalAssets(), supply);\n\t}\n\n\tfunction maxWithdraw(address owner) external view returns (uint256 assets) {\n\t\treturn convertToAssets(balanceOf[owner]);\n\t}\n\n\tfunction previewWithdraw(uint256 assets) public view returns (uint256 shares) {\n\t\tuint256 supply = totalSupply;\n\n\t\treturn supply == 0 ? assets : assets.mulDivUp(supply, freeAssets());\n\t}\n\n\tfunction maxRedeem(address _owner) external view returns (uint256 shares) {\n\t\treturn balanceOf[_owner];\n\t}\n\n\tfunction previewRedeem(uint256 shares) public view returns (uint256 assets) {\n\t\tuint256 supply = totalSupply;\n\t\treturn supply == 0 ? shares : shares.mulDivDown(freeAssets(), supply);\n\t}\n\n\t/*////////////////////////////\n\t/      Public Functions      /\n\t////////////////////////////*/\n\n\tfunction safeDeposit(\n\t\tuint256 _assets,\n\t\taddress _receiver,\n\t\tuint256 _minShares\n\t) external returns (uint256 shares) {\n\t\tshares = deposit(_assets, _receiver);\n\t\tif (shares < _minShares) revert BelowMinimum(shares);\n\t}\n\n\tfunction safeMint(\n\t\tuint256 _shares,\n\t\taddress _receiver,\n\t\tuint256 _maxAssets\n\t) external returns (uint256 assets) {\n\t\tassets = mint(_shares, _receiver);\n\t\tif (assets > _maxAssets) revert AboveMaximum(assets);\n\t}\n\n\tfunction safeWithdraw(\n\t\tuint256 _assets,\n\t\taddress _receiver,\n\t\taddress _owner,\n\t\tuint256 _maxShares\n\t) external returns (uint256 shares) {\n\t\tshares = withdraw(_assets, _receiver, _owner);\n\t\tif (shares > _maxShares) revert AboveMaximum(shares);\n\t}\n\n\tfunction safeRedeem(\n\t\tuint256 _shares,\n\t\taddress _receiver,\n\t\taddress _owner,\n\t\tuint256 _minAssets\n\t) external returns (uint256 assets) {\n\t\tassets = redeem(_shares, _receiver, _owner);\n\t\tif (assets < _minAssets) revert BelowMinimum(assets);\n\t}\n\n\t/*////////////////////////////////////\n\t/      ERC4626 Public Functions      /\n\t////////////////////////////////////*/\n\n\tfunction deposit(uint256 _assets, address _receiver) public whenNotPaused returns (uint256 shares) {\n\t\tif ((shares = previewDeposit(_assets)) == 0) revert Zero();\n\n\t\t_deposit(_assets, shares, _receiver);\n\t}\n\n\tfunction mint(uint256 _shares, address _receiver) public whenNotPaused returns (uint256 assets) {\n\t\tif (_shares == 0) revert Zero();\n\t\tassets = previewMint(_shares);\n\n\t\t_deposit(assets, _shares, _receiver);\n\t}\n\n\tfunction withdraw(\n\t\tuint256 _assets,\n\t\taddress _receiver,\n\t\taddress _owner\n\t) public returns (uint256 shares) {\n\t\tif (_assets == 0) revert Zero();\n\t\tshares = previewWithdraw(_assets);\n\n\t\t_withdraw(_assets, shares, _owner, _receiver);\n\t}\n\n\tfunction redeem(\n\t\tuint256 _shares,\n\t\taddress _receiver,\n\t\taddress _owner\n\t) public returns (uint256 assets) {\n\t\tif ((assets = previewRedeem(_shares)) == 0) revert Zero();\n\n\t\treturn _withdraw(assets, _shares, _owner, _receiver);\n\t}\n\n\t/*///////////////////////////////////////////\n\t/      Restricted Functions: onlyOwner      /\n\t///////////////////////////////////////////*/\n\n\tfunction addStrategy(Strategy _strategy, uint256 _debtRatio) external onlyOwner {\n\t\tif (_strategy.vault() != this) revert StrategyDoesNotBelongToQueue();\n\t\tif (strategies[_strategy].added) revert AlreadyStrategy();\n\t\tif (_queue.length >= MAX_QUEUE_LENGTH) revert StrategyQueueFull();\n\n\t\ttotalDebtRatio += _debtRatio;\n\t\tif (totalDebtRatio > MAX_TOTAL_DEBT_RATIO) revert AboveMaximum(totalDebtRatio);\n\n\t\tstrategies[_strategy] = StrategyParams({added: true, debt: 0, debtRatio: _debtRatio});\n\t\t_queue.push(_strategy);\n\n\t\temit StrategyAdded(_strategy, _debtRatio);\n\t}\n\n\t/*////////////////////////////////////////////\n\t/      Restricted Functions: onlyAdmins      /\n\t////////////////////////////////////////////*/\n\n\tfunction removeStrategy(Strategy _strategy, uint256 _minReceived) external onlyAdmins {\n\t\tif (!strategies[_strategy].added) revert NotStrategy();\n\t\ttotalDebtRatio -= strategies[_strategy].debtRatio;\n\n\t\tif (strategies[_strategy].debt > 0) {\n\t\t\t(uint256 received, ) = _collect(_strategy, type(uint256).max, address(this));\n\t\t\tif (received < _minReceived) revert BelowMinimum(received);\n\n\t\t\t// forgive all remaining debt when removing a strategy\n\t\t\tuint256 remainingDebt = strategies[_strategy].debt;\n\t\t\tif (remainingDebt > 0) totalDebt -= remainingDebt;\n\t\t}\n\n\t\t// reorganize queue, filling in the empty strategy\n\t\tStrategy[] memory newQueue = new Strategy[](_queue.length - 1);\n\n\t\tbool found;\n\t\tuint8 length = uint8(newQueue.length);\n\t\tfor (uint8 i = 0; i < length; ++i) {\n\t\t\tif (_queue[i] == _strategy) found = true;\n\n\t\t\tif (found) newQueue[i] = _queue[i + 1];\n\t\t\telse newQueue[i] = _queue[i];\n\t\t}\n\n\t\tdelete strategies[_strategy];\n\t\t_queue = newQueue;\n\n\t\temit StrategyRemoved(_strategy);\n\t}\n\n\tfunction swapQueuePositions(uint8 _i, uint8 _j) external onlyAdmins {\n\t\tStrategy s1 = _queue[_i];\n\t\tStrategy s2 = _queue[_j];\n\n\t\t_queue[_i] = s2;\n\t\t_queue[_j] = s1;\n\n\t\temit StrategyQueuePositionsSwapped(_i, _j, s2, s1);\n\t}\n\n\tfunction setDebtRatio(Strategy _strategy, uint256 _newDebtRatio) external onlyAdmins {\n\t\tif (!strategies[_strategy].added) revert NotStrategy();\n\t\t_setDebtRatio(_strategy, _newDebtRatio);\n\t}\n\n\t/// @dev locked profit duration can be 0\n\tfunction setLockedProfitDuration(uint256 _newDuration) external onlyAdmins {\n\t\tif (_newDuration > MAX_LOCKED_PROFIT_DURATION) revert AboveMaximum(_newDuration);\n\t\tif (_newDuration == lockedProfitDuration) revert AlreadyValue();\n\t\tlockedProfitDuration = _newDuration;\n\t\temit LockedProfitDurationChanged(_newDuration);\n\t}\n\n\tfunction setBlockDelay(uint8 _newDelay) external onlyAdmins {\n\t\t_setBlockDelay(_newDelay);\n\t}\n\n\t/*///////////////////////////////////////////////\n\t/      Restricted Functions: onlyAuthorized     /\n\t///////////////////////////////////////////////*/\n\n\tfunction suspendStrategy(Strategy _strategy) external onlyAuthorized {\n\t\tif (!strategies[_strategy].added) revert NotStrategy();\n\t\t_setDebtRatio(_strategy, 0);\n\t}\n\n\tfunction collectFromStrategy(\n\t\tStrategy _strategy,\n\t\tuint256 _assets,\n\t\tuint256 _minReceived\n\t) external onlyAuthorized returns (uint256 received) {\n\t\tif (!strategies[_strategy].added) revert NotStrategy();\n\t\t(received, ) = _collect(_strategy, _assets, address(this));\n\t\tif (received < _minReceived) revert BelowMinimum(received);\n\t}\n\n\tfunction pause() external onlyAuthorized {\n\t\tif (paused) revert AlreadyValue();\n\t\tpaused = true;\n\t}\n\n\tfunction unpause() external onlyAuthorized {\n\t\tif (!paused) revert AlreadyValue();\n\t\tpaused = false;\n\t}\n\n\tfunction setMaxDeposit(uint256 _newMaxDeposit) external onlyAuthorized {\n\t\tif (_maxDeposit == _newMaxDeposit) revert AlreadyValue();\n\t\t_maxDeposit = _newMaxDeposit;\n\t\temit MaxDepositChanged(_newMaxDeposit);\n\t}\n\n\t/// @dev costs less gas than multiple harvests if active strategies > 1\n\tfunction harvestAll() external onlyAuthorized updateLastReport {\n\t\tuint8 length = uint8(_queue.length);\n\t\tfor (uint8 i = 0; i < length; ++i) {\n\t\t\t_harvest(_queue[i]);\n\t\t}\n\t}\n\n\t/// @dev costs less gas than multiple reports if active strategies > 1\n\tfunction reportAll() external onlyAuthorized updateLastReport {\n\t\tuint8 length = uint8(_queue.length);\n\t\tfor (uint8 i = 0; i < length; ++i) {\n\t\t\t_report(_queue[i], 0);\n\t\t}\n\t}\n\n\tfunction harvest(Strategy _strategy) external onlyAuthorized updateLastReport {\n\t\tif (!strategies[_strategy].added) revert NotStrategy();\n\n\t\t_harvest(_strategy);\n\t}\n\n\tfunction report(Strategy _strategy) external onlyAuthorized updateLastReport {\n\t\tif (!strategies[_strategy].added) revert NotStrategy();\n\n\t\t_report(_strategy, 0);\n\t}\n\n\t/*///////////////////////////////////////////\n\t/      Internal Override: useBlockDelay     /\n\t///////////////////////////////////////////*/\n\n\t/// @dev address cannot mint/burn/send/receive share tokens on same block, defense against flash loan exploits\n\tfunction _mint(address _to, uint256 _amount) internal override useBlockDelay(_to) {\n\t\tif (_to == address(0)) revert Zero();\n\t\tERC20._mint(_to, _amount);\n\t}\n\n\t/// @dev address cannot mint/burn/send/receive share tokens on same block, defense against flash loan exploits\n\tfunction _burn(address _from, uint256 _amount) internal override useBlockDelay(_from) {\n\t\tERC20._burn(_from, _amount);\n\t}\n\n\t/// @dev address cannot mint/burn/send/receive share tokens on same block, defense against flash loan exploits\n\tfunction transfer(address _to, uint256 _amount)\n\t\tpublic\n\t\toverride\n\t\tuseBlockDelay(msg.sender)\n\t\tuseBlockDelay(_to)\n\t\treturns (bool)\n\t{\n\t\treturn ERC20.transfer(_to, _amount);\n\t}\n\n\t/// @dev address cannot mint/burn/send/receive share tokens on same block, defense against flash loan exploits\n\tfunction transferFrom(\n\t\taddress _from,\n\t\taddress _to,\n\t\tuint256 _amount\n\t) public override useBlockDelay(_from) useBlockDelay(_to) returns (bool) {\n\t\treturn ERC20.transferFrom(_from, _to, _amount);\n\t}\n\n\t/*//////////////////////////////\n\t/      Internal Functions      /\n\t//////////////////////////////*/\n\n\tfunction _deposit(\n\t\tuint256 _assets,\n\t\tuint256 _shares,\n\t\taddress _receiver\n\t) internal {\n\t\tif (_assets > _maxDeposit) revert AboveMaxDeposit();\n\n\t\tasset.safeTransferFrom(msg.sender, address(this), _assets);\n\t\t_mint(_receiver, _shares);\n\t\temit Deposit(msg.sender, _receiver, _assets, _shares);\n\t}\n\n\tfunction _withdraw(\n\t\tuint256 _assets,\n\t\tuint256 _shares,\n\t\taddress _owner,\n\t\taddress _receiver\n\t) internal returns (uint256 received) {\n\t\tif (msg.sender != _owner) {\n\t\t\tuint256 allowed = allowance[_owner][msg.sender];\n\t\t\tif (allowed != type(uint256).max) allowance[_owner][msg.sender] = allowed - _shares;\n\t\t}\n\n\t\t_burn(_owner, _shares);\n\n\t\temit Withdraw(msg.sender, _receiver, _owner, _assets, _shares);\n\n\t\t// first, withdraw from balance\n\t\tuint256 balance = asset.balanceOf(address(this));\n\n\t\tif (balance > 0) {\n\t\t\tuint256 amount = _assets > balance ? balance : _assets;\n\t\t\tasset.safeTransfer(_receiver, amount);\n\t\t\t_assets -= amount;\n\t\t\treceived += amount;\n\t\t}\n\n\t\t// next, withdraw from strategies\n\t\tuint8 length = uint8(_queue.length);\n\t\tfor (uint8 i = 0; i < length; ++i) {\n\t\t\tif (_assets == 0) break;\n\t\t\t(uint256 receivedFromStrategy, uint256 slippage) = _collect(_queue[i], _assets, _receiver);\n\t\t\t_assets -= receivedFromStrategy + slippage; // user pays for slippage, if any\n\t\t\treceived += receivedFromStrategy;\n\t\t}\n\t}\n\n\tfunction _lend(Strategy _strategy, uint256 _assets) internal {\n\t\tuint256 balance = asset.balanceOf(address(this));\n\t\tuint256 amount = _assets > balance ? balance : _assets;\n\n\t\tasset.safeTransfer(address(_strategy), amount);\n\t\t_strategy.invest();\n\n\t\tuint256 debtBefore = strategies[_strategy].debt;\n\t\tuint256 debtAfter = _strategy.totalAssets();\n\t\tstrategies[_strategy].debt = debtAfter;\n\n\t\tuint256 slippage = debtBefore > debtAfter ? debtBefore - debtAfter : 0;\n\n\t\ttotalDebt += amount - slippage;\n\n\t\temit Lend(_strategy, amount, slippage);\n\t}\n\n\t/// @dev overflow is handled by strategy\n\tfunction _collect(\n\t\tStrategy _strategy,\n\t\tuint256 _assets,\n\t\taddress _receiver\n\t) internal returns (uint256 received, uint256 slippage) {\n\t\t(received, slippage) = _strategy.withdraw(_assets, _receiver);\n\n\t\tuint256 total = received + slippage;\n\n\t\tuint256 debt = strategies[_strategy].debt;\n\n\t\tuint256 amount = debt > total ? received : total;\n\n\t\tstrategies[_strategy].debt -= amount;\n\t\ttotalDebt -= amount;\n\n\t\tif (_receiver == address(this)) emit Collect(_strategy, received, slippage);\n\t}\n\n\tfunction _harvest(Strategy _strategy) internal {\n\t\t_report(_strategy, _strategy.harvest());\n\t}\n\n\tfunction _report(Strategy _strategy, uint256 _harvested) internal {\n\t\tuint256 assets = _strategy.totalAssets();\n\t\tuint256 debt = strategies[_strategy].debt;\n\n\t\tstrategies[_strategy].debt = assets; // update debt\n\n\t\tuint256 gain;\n\t\tuint256 loss;\n\n\t\tuint256 lockedProfitBefore = lockedProfit();\n\n\t\tif (assets > debt) {\n\t\t\tunchecked {\n\t\t\t\tgain = assets - debt;\n\t\t\t}\n\t\t\ttotalDebt += gain;\n\n\t\t\t_lockedProfit = lockedProfitBefore + gain + _harvested;\n\t\t} else if (debt > assets) {\n\t\t\tunchecked {\n\t\t\t\tloss = debt - assets;\n\t\t\t\ttotalDebt -= loss;\n\n\t\t\t\t_lockedProfit = lockedProfitBefore + _harvested > loss ? lockedProfitBefore + _harvested - loss : 0;\n\t\t\t}\n\t\t}\n\n\t\tuint256 possibleDebt = totalDebtRatio == 0\n\t\t\t? 0\n\t\t\t: totalAssets().mulDivDown(strategies[_strategy].debtRatio, totalDebtRatio);\n\n\t\tif (possibleDebt > assets) _lend(_strategy, possibleDebt - assets);\n\t\telse if (assets > possibleDebt) _collect(_strategy, assets - possibleDebt, address(this));\n\n\t\temit Report(_strategy, _harvested, gain, loss);\n\t}\n\n\tfunction _setDebtRatio(Strategy _strategy, uint256 _newDebtRatio) internal {\n\t\tuint256 currentDebtRatio = strategies[_strategy].debtRatio;\n\t\tif (_newDebtRatio == currentDebtRatio) revert AlreadyValue();\n\n\t\tuint256 newTotalDebtRatio = totalDebtRatio + _newDebtRatio - currentDebtRatio;\n\t\tif (newTotalDebtRatio > MAX_TOTAL_DEBT_RATIO) revert AboveMaximum(newTotalDebtRatio);\n\n\t\tstrategies[_strategy].debtRatio = _newDebtRatio;\n\t\ttotalDebtRatio = newTotalDebtRatio;\n\n\t\temit StrategyDebtRatioChanged(_strategy, _newDebtRatio);\n\t}\n\n\t/*/////////////////////\n\t/      Modifiers      /\n\t/////////////////////*/\n\n\tmodifier updateLastReport() {\n\t\t_;\n\t\tlastReport = block.timestamp;\n\t}\n\n\tmodifier whenNotPaused() {\n\t\tif (paused) revert Paused();\n\t\t_;\n\t}\n}\n"
    },
    "src/interfaces/IERC4626.sol": {
      "content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.9;\n\nimport 'solmate/tokens/ERC20.sol';\n\n/// @notice https://eips.ethereum.org/EIPS/eip-4626\ninterface IERC4626 {\n\tevent Deposit(address indexed caller, address indexed owner, uint256 assets, uint256 shares);\n\n\tevent Withdraw(\n\t\taddress indexed caller,\n\t\taddress indexed receiver,\n\t\taddress indexed owner,\n\t\tuint256 assets,\n\t\tuint256 shares\n\t);\n\n\tfunction asset() external view returns (ERC20);\n\n\tfunction totalAssets() external view returns (uint256 assets);\n\n\tfunction convertToShares(uint256 assets) external view returns (uint256 shares);\n\n\tfunction convertToAssets(uint256 shares) external view returns (uint256 assets);\n\n\tfunction maxDeposit(address receiver) external view returns (uint256 assets);\n\n\tfunction previewDeposit(uint256 assets) external view returns (uint256 shares);\n\n\tfunction deposit(uint256 assets, address receiver) external returns (uint256 shares);\n\n\tfunction maxMint(address receiver) external view returns (uint256 shares);\n\n\tfunction previewMint(uint256 shares) external view returns (uint256 assets);\n\n\tfunction mint(uint256 shares, address receiver) external returns (uint256 assets);\n\n\tfunction maxWithdraw(address owner) external view returns (uint256 assets);\n\n\tfunction previewWithdraw(uint256 assets) external view returns (uint256 shares);\n\n\tfunction withdraw(\n\t\tuint256 assets,\n\t\taddress receiver,\n\t\taddress owner\n\t) external returns (uint256 shares);\n\n\tfunction maxRedeem(address owner) external view returns (uint256 shares);\n\n\tfunction previewRedeem(uint256 shares) external view returns (uint256 assets);\n\n\tfunction redeem(\n\t\tuint256 shares,\n\t\taddress receiver,\n\t\taddress owner\n\t) external returns (uint256 assets);\n}\n"
    },
    "src/libraries/BlockDelay.sol": {
      "content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.9;\n\nabstract contract BlockDelay {\n\t/// @notice delay before functions with 'useBlockDelay' can be called by the same address\n\t/// @dev 0 means no delay\n\tuint256 public blockDelay;\n\tuint256 internal constant MAX_BLOCK_DELAY = 10;\n\n\tmapping(address => uint256) public lastBlock;\n\n\terror AboveMaxBlockDelay();\n\terror BeforeBlockDelay();\n\n\tconstructor(uint8 _delay) {\n\t\t_setBlockDelay(_delay);\n\t}\n\n\tfunction _setBlockDelay(uint8 _newDelay) internal {\n\t\tif (_newDelay > MAX_BLOCK_DELAY) revert AboveMaxBlockDelay();\n\t\tblockDelay = _newDelay;\n\t}\n\n\tmodifier useBlockDelay(address _address) {\n\t\tif (block.number < lastBlock[_address] + blockDelay) revert BeforeBlockDelay();\n\t\tlastBlock[_address] = block.number;\n\t\t_;\n\t}\n}\n"
    },
    "src/libraries/Ownership.sol": {
      "content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.9;\n\nabstract contract Ownership {\n\taddress public owner;\n\taddress public nominatedOwner;\n\n\taddress public admin;\n\n\tmapping(address => bool) public authorized;\n\n\tevent OwnerChanged(address indexed previousOwner, address indexed newOwner);\n\tevent AuthAdded(address indexed newAuth);\n\tevent AuthRemoved(address indexed oldAuth);\n\n\terror Unauthorized();\n\terror AlreadyRole();\n\terror NotRole();\n\n\t/// @param _authorized maximum of 256 addresses in constructor\n\tconstructor(address[] memory _authorized) {\n\t\towner = msg.sender;\n\t\tadmin = msg.sender;\n\t\tfor (uint8 i = 0; i < _authorized.length; ++i) {\n\t\t\tauthorized[_authorized[i]] = true;\n\t\t\temit AuthAdded(_authorized[i]);\n\t\t}\n\t}\n\n\t// Public Functions\n\n\tfunction acceptOwnership() external {\n\t\tif (msg.sender != nominatedOwner) revert Unauthorized();\n\t\temit OwnerChanged(owner, msg.sender);\n\t\towner = msg.sender;\n\t\tnominatedOwner = address(0);\n\t}\n\n\t// Restricted Functions: onlyOwner\n\n\t/// @dev nominating zero address revokes a pending nomination\n\tfunction nominateOwnership(address _newOwner) external onlyOwner {\n\t\tnominatedOwner = _newOwner;\n\t}\n\n\tfunction setAdmin(address _newAdmin) external onlyOwner {\n\t\tif (admin == _newAdmin) revert AlreadyRole();\n\t\tadmin = _newAdmin;\n\t}\n\n\t// Restricted Functions: onlyAdmins\n\n\tfunction addAuthorized(address _authorized) external onlyAdmins {\n\t\tif (authorized[_authorized]) revert AlreadyRole();\n\t\tauthorized[_authorized] = true;\n\t\temit AuthAdded(_authorized);\n\t}\n\n\tfunction removeAuthorized(address _authorized) external onlyAdmins {\n\t\tif (!authorized[_authorized]) revert NotRole();\n\t\tauthorized[_authorized] = false;\n\t\temit AuthRemoved(_authorized);\n\t}\n\n\t// Modifiers\n\n\tmodifier onlyOwner() {\n\t\tif (msg.sender != owner) revert Unauthorized();\n\t\t_;\n\t}\n\n\tmodifier onlyAdmins() {\n\t\tif (msg.sender != owner && msg.sender != admin) revert Unauthorized();\n\t\t_;\n\t}\n\n\tmodifier onlyAuthorized() {\n\t\tif (msg.sender != owner && msg.sender != admin && !authorized[msg.sender]) revert Unauthorized();\n\t\t_;\n\t}\n}\n"
    }
  },
  "settings": {
    "remappings": [
      "ds-test/=lib/solmate/lib/ds-test/src/",
      "forge-std/=lib/forge-std/src/",
      "solmate/=lib/solmate/src/"
    ],
    "optimizer": {
      "enabled": true,
      "runs": 10000
    },
    "metadata": {
      "bytecodeHash": "ipfs"
    },
    "outputSelection": {
      "*": {
        "*": [
          "evm.bytecode",
          "evm.deployedBytecode",
          "devdoc",
          "userdoc",
          "metadata",
          "abi"
        ]
      }
    },
    "evmVersion": "london",
    "libraries": {}
  }
}