{"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/tokens/ERC4626.sol":{"content":"// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity >=0.8.0;\n\nimport {ERC20} from \"../tokens/ERC20.sol\";\nimport {SafeTransferLib} from \"../utils/SafeTransferLib.sol\";\nimport {FixedPointMathLib} from \"../utils/FixedPointMathLib.sol\";\n\n/// @notice Minimal ERC4626 tokenized Vault implementation.\n/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC4626.sol)\nabstract contract ERC4626 is ERC20 {\n    using SafeTransferLib for ERC20;\n    using FixedPointMathLib for uint256;\n\n    /*//////////////////////////////////////////////////////////////\n                                 EVENTS\n    //////////////////////////////////////////////////////////////*/\n\n    event Deposit(address indexed caller, address indexed owner, uint256 assets, uint256 shares);\n\n    event Withdraw(\n        address indexed caller,\n        address indexed receiver,\n        address indexed owner,\n        uint256 assets,\n        uint256 shares\n    );\n\n    /*//////////////////////////////////////////////////////////////\n                               IMMUTABLES\n    //////////////////////////////////////////////////////////////*/\n\n    ERC20 public immutable asset;\n\n    constructor(\n        ERC20 _asset,\n        string memory _name,\n        string memory _symbol\n    ) ERC20(_name, _symbol, _asset.decimals()) {\n        asset = _asset;\n    }\n\n    /*//////////////////////////////////////////////////////////////\n                        DEPOSIT/WITHDRAWAL LOGIC\n    //////////////////////////////////////////////////////////////*/\n\n    function deposit(uint256 assets, address receiver) public virtual returns (uint256 shares) {\n        // Check for rounding error since we round down in previewDeposit.\n        require((shares = previewDeposit(assets)) != 0, \"ZERO_SHARES\");\n\n        // Need to transfer before minting or ERC777s could reenter.\n        asset.safeTransferFrom(msg.sender, address(this), assets);\n\n        _mint(receiver, shares);\n\n        emit Deposit(msg.sender, receiver, assets, shares);\n\n        afterDeposit(assets, shares);\n    }\n\n    function mint(uint256 shares, address receiver) public virtual returns (uint256 assets) {\n        assets = previewMint(shares); // No need to check for rounding error, previewMint rounds up.\n\n        // Need to transfer before minting or ERC777s could reenter.\n        asset.safeTransferFrom(msg.sender, address(this), assets);\n\n        _mint(receiver, shares);\n\n        emit Deposit(msg.sender, receiver, assets, shares);\n\n        afterDeposit(assets, shares);\n    }\n\n    function withdraw(\n        uint256 assets,\n        address receiver,\n        address owner\n    ) public virtual returns (uint256 shares) {\n        shares = previewWithdraw(assets); // No need to check for rounding error, previewWithdraw rounds up.\n\n        if (msg.sender != owner) {\n            uint256 allowed = allowance[owner][msg.sender]; // Saves gas for limited approvals.\n\n            if (allowed != type(uint256).max) allowance[owner][msg.sender] = allowed - shares;\n        }\n\n        beforeWithdraw(assets, shares);\n\n        _burn(owner, shares);\n\n        emit Withdraw(msg.sender, receiver, owner, assets, shares);\n\n        asset.safeTransfer(receiver, assets);\n    }\n\n    function redeem(\n        uint256 shares,\n        address receiver,\n        address owner\n    ) public virtual returns (uint256 assets) {\n        if (msg.sender != owner) {\n            uint256 allowed = allowance[owner][msg.sender]; // Saves gas for limited approvals.\n\n            if (allowed != type(uint256).max) allowance[owner][msg.sender] = allowed - shares;\n        }\n\n        // Check for rounding error since we round down in previewRedeem.\n        require((assets = previewRedeem(shares)) != 0, \"ZERO_ASSETS\");\n\n        beforeWithdraw(assets, shares);\n\n        _burn(owner, shares);\n\n        emit Withdraw(msg.sender, receiver, owner, assets, shares);\n\n        asset.safeTransfer(receiver, assets);\n    }\n\n    /*//////////////////////////////////////////////////////////////\n                            ACCOUNTING LOGIC\n    //////////////////////////////////////////////////////////////*/\n\n    function totalAssets() public view virtual returns (uint256);\n\n    function convertToShares(uint256 assets) public view virtual returns (uint256) {\n        uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.\n\n        return supply == 0 ? assets : assets.mulDivDown(supply, totalAssets());\n    }\n\n    function convertToAssets(uint256 shares) public view virtual returns (uint256) {\n        uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.\n\n        return supply == 0 ? shares : shares.mulDivDown(totalAssets(), supply);\n    }\n\n    function previewDeposit(uint256 assets) public view virtual returns (uint256) {\n        return convertToShares(assets);\n    }\n\n    function previewMint(uint256 shares) public view virtual returns (uint256) {\n        uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.\n\n        return supply == 0 ? shares : shares.mulDivUp(totalAssets(), supply);\n    }\n\n    function previewWithdraw(uint256 assets) public view virtual returns (uint256) {\n        uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.\n\n        return supply == 0 ? assets : assets.mulDivUp(supply, totalAssets());\n    }\n\n    function previewRedeem(uint256 shares) public view virtual returns (uint256) {\n        return convertToAssets(shares);\n    }\n\n    /*//////////////////////////////////////////////////////////////\n                     DEPOSIT/WITHDRAWAL LIMIT LOGIC\n    //////////////////////////////////////////////////////////////*/\n\n    function maxDeposit(address) public view virtual returns (uint256) {\n        return type(uint256).max;\n    }\n\n    function maxMint(address) public view virtual returns (uint256) {\n        return type(uint256).max;\n    }\n\n    function maxWithdraw(address owner) public view virtual returns (uint256) {\n        return convertToAssets(balanceOf[owner]);\n    }\n\n    function maxRedeem(address owner) public view virtual returns (uint256) {\n        return balanceOf[owner];\n    }\n\n    /*//////////////////////////////////////////////////////////////\n                          INTERNAL HOOKS LOGIC\n    //////////////////////////////////////////////////////////////*/\n\n    function beforeWithdraw(uint256 assets, uint256 shares) internal virtual {}\n\n    function afterDeposit(uint256 assets, uint256 shares) internal virtual {}\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.\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), and(from, 0xffffffffffffffffffffffffffffffffffffffff)) // Append and mask the \"from\" argument.\n            mstore(add(freeMemoryPointer, 36), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Append and mask the \"to\" argument.\n            mstore(add(freeMemoryPointer, 68), amount) // Append the \"amount\" argument. Masking not required as it's a full 32 byte type.\n\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            success := call(gas(), token, 0, freeMemoryPointer, 100, 0, 32)\n\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 and token has code.\n            if and(iszero(and(eq(mload(0), 1), gt(returndatasize(), 31))), success) {\n                success := iszero(or(iszero(extcodesize(token)), returndatasize())) \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), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Append and mask the \"to\" argument.\n            mstore(add(freeMemoryPointer, 36), amount) // Append the \"amount\" argument. Masking not required as it's a full 32 byte type.\n\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            success := call(gas(), token, 0, freeMemoryPointer, 68, 0, 32)\n\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 and token has code.\n            if and(iszero(and(eq(mload(0), 1), gt(returndatasize(), 31))), success) {\n                success := iszero(or(iszero(extcodesize(token)), returndatasize())) \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), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Append and mask the \"to\" argument.\n            mstore(add(freeMemoryPointer, 36), amount) // Append the \"amount\" argument. Masking not required as it's a full 32 byte type.\n\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            success := call(gas(), token, 0, freeMemoryPointer, 68, 0, 32)\n\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 and token has code.\n            if and(iszero(and(eq(mload(0), 1), gt(returndatasize(), 31))), success) {\n                success := iszero(or(iszero(extcodesize(token)), returndatasize())) \n            }\n        }\n\n        require(success, \"APPROVE_FAILED\");\n    }\n}\n"},"lib/solmate/src/utils/SignedWadMath.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity >=0.8.0;\n\n/// @notice Signed 18 decimal fixed point (wad) arithmetic library.\n/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/SignedWadMath.sol)\n/// @author Modified from Remco Bloemen (https://xn--2-umb.com/22/exp-ln/index.html)\n\n/// @dev Will not revert on overflow, only use where overflow is not possible.\nfunction toWadUnsafe(uint256 x) pure returns (int256 r) {\n    /// @solidity memory-safe-assembly\n    assembly {\n        // Multiply x by 1e18.\n        r := mul(x, 1000000000000000000)\n    }\n}\n\n/// @dev Takes an integer amount of seconds and converts it to a wad amount of days.\n/// @dev Will not revert on overflow, only use where overflow is not possible.\n/// @dev Not meant for negative second amounts, it assumes x is positive.\nfunction toDaysWadUnsafe(uint256 x) pure returns (int256 r) {\n    /// @solidity memory-safe-assembly\n    assembly {\n        // Multiply x by 1e18 and then divide it by 86400.\n        r := div(mul(x, 1000000000000000000), 86400)\n    }\n}\n\n/// @dev Takes a wad amount of days and converts it to an integer amount of seconds.\n/// @dev Will not revert on overflow, only use where overflow is not possible.\n/// @dev Not meant for negative day amounts, it assumes x is positive.\nfunction fromDaysWadUnsafe(int256 x) pure returns (uint256 r) {\n    /// @solidity memory-safe-assembly\n    assembly {\n        // Multiply x by 86400 and then divide it by 1e18.\n        r := div(mul(x, 86400), 1000000000000000000)\n    }\n}\n\n/// @dev Will not revert on overflow, only use where overflow is not possible.\nfunction unsafeWadMul(int256 x, int256 y) pure returns (int256 r) {\n    /// @solidity memory-safe-assembly\n    assembly {\n        // Multiply x by y and divide by 1e18.\n        r := sdiv(mul(x, y), 1000000000000000000)\n    }\n}\n\n/// @dev Will return 0 instead of reverting if y is zero and will\n/// not revert on overflow, only use where overflow is not possible.\nfunction unsafeWadDiv(int256 x, int256 y) pure returns (int256 r) {\n    /// @solidity memory-safe-assembly\n    assembly {\n        // Multiply x by 1e18 and divide it by y.\n        r := sdiv(mul(x, 1000000000000000000), y)\n    }\n}\n\nfunction wadMul(int256 x, int256 y) pure returns (int256 r) {\n    /// @solidity memory-safe-assembly\n    assembly {\n        // Store x * y in r for now.\n        r := mul(x, y)\n\n        // Combined overflow check (`x == 0 || (x * y) / x == y`) and edge case check\n        // where x == -1 and y == type(int256).min, for y == -1 and x == min int256,\n        // the second overflow check will catch this.\n        // See: https://secure-contracts.com/learn_evm/arithmetic-checks.html#arithmetic-checks-for-int256-multiplication\n        // Combining into 1 expression saves gas as resulting bytecode will only have 1 `JUMPI`\n        // rather than 2.\n        if iszero(\n            and(\n                or(iszero(x), eq(sdiv(r, x), y)),\n                or(lt(x, not(0)), sgt(y, 0x8000000000000000000000000000000000000000000000000000000000000000))\n            )\n        ) {\n            revert(0, 0)\n        }\n\n        // Scale the result down by 1e18.\n        r := sdiv(r, 1000000000000000000)\n    }\n}\n\nfunction wadDiv(int256 x, int256 y) pure returns (int256 r) {\n    /// @solidity memory-safe-assembly\n    assembly {\n        // Store x * 1e18 in r for now.\n        r := mul(x, 1000000000000000000)\n\n        // Equivalent to require(y != 0 && ((x * 1e18) / 1e18 == x))\n        if iszero(and(iszero(iszero(y)), eq(sdiv(r, 1000000000000000000), x))) {\n            revert(0, 0)\n        }\n\n        // Divide r by y.\n        r := sdiv(r, y)\n    }\n}\n\n/// @dev Will not work with negative bases, only use when x is positive.\nfunction wadPow(int256 x, int256 y) pure returns (int256) {\n    // Equivalent to x to the power of y because x ** y = (e ** ln(x)) ** y = e ** (ln(x) * y)\n    return wadExp((wadLn(x) * y) / 1e18); // Using ln(x) means x must be greater than 0.\n}\n\nfunction wadExp(int256 x) pure returns (int256 r) {\n    unchecked {\n        // When the result is < 0.5 we return zero. This happens when\n        // x <= floor(log(0.5e18) * 1e18) ~ -42e18\n        if (x <= -42139678854452767551) return 0;\n\n        // When the result is > (2**255 - 1) / 1e18 we can not represent it as an\n        // int. This happens when x >= floor(log((2**255 - 1) / 1e18) * 1e18) ~ 135.\n        if (x >= 135305999368893231589) revert(\"EXP_OVERFLOW\");\n\n        // x is now in the range (-42, 136) * 1e18. Convert to (-42, 136) * 2**96\n        // for more intermediate precision and a binary basis. This base conversion\n        // is a multiplication by 1e18 / 2**96 = 5**18 / 2**78.\n        x = (x << 78) / 5**18;\n\n        // Reduce range of x to (-½ ln 2, ½ ln 2) * 2**96 by factoring out powers\n        // of two such that exp(x) = exp(x') * 2**k, where k is an integer.\n        // Solving this gives k = round(x / log(2)) and x' = x - k * log(2).\n        int256 k = ((x << 96) / 54916777467707473351141471128 + 2**95) >> 96;\n        x = x - k * 54916777467707473351141471128;\n\n        // k is in the range [-61, 195].\n\n        // Evaluate using a (6, 7)-term rational approximation.\n        // p is made monic, we'll multiply by a scale factor later.\n        int256 y = x + 1346386616545796478920950773328;\n        y = ((y * x) >> 96) + 57155421227552351082224309758442;\n        int256 p = y + x - 94201549194550492254356042504812;\n        p = ((p * y) >> 96) + 28719021644029726153956944680412240;\n        p = p * x + (4385272521454847904659076985693276 << 96);\n\n        // We leave p in 2**192 basis so we don't need to scale it back up for the division.\n        int256 q = x - 2855989394907223263936484059900;\n        q = ((q * x) >> 96) + 50020603652535783019961831881945;\n        q = ((q * x) >> 96) - 533845033583426703283633433725380;\n        q = ((q * x) >> 96) + 3604857256930695427073651918091429;\n        q = ((q * x) >> 96) - 14423608567350463180887372962807573;\n        q = ((q * x) >> 96) + 26449188498355588339934803723976023;\n\n        /// @solidity memory-safe-assembly\n        assembly {\n            // Div in assembly because solidity adds a zero check despite the unchecked.\n            // The q polynomial won't have zeros in the domain as all its roots are complex.\n            // No scaling is necessary because p is already 2**96 too large.\n            r := sdiv(p, q)\n        }\n\n        // r should be in the range (0.09, 0.25) * 2**96.\n\n        // We now need to multiply r by:\n        // * the scale factor s = ~6.031367120.\n        // * the 2**k factor from the range reduction.\n        // * the 1e18 / 2**96 factor for base conversion.\n        // We do this all at once, with an intermediate result in 2**213\n        // basis, so the final right shift is always by a positive amount.\n        r = int256((uint256(r) * 3822833074963236453042738258902158003155416615667) >> uint256(195 - k));\n    }\n}\n\nfunction wadLn(int256 x) pure returns (int256 r) {\n    unchecked {\n        require(x > 0, \"UNDEFINED\");\n\n        // We want to convert x from 10**18 fixed point to 2**96 fixed point.\n        // We do this by multiplying by 2**96 / 10**18. But since\n        // ln(x * C) = ln(x) + ln(C), we can simply do nothing here\n        // and add ln(2**96 / 10**18) at the end.\n\n        /// @solidity memory-safe-assembly\n        assembly {\n            r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))\n            r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))\n            r := or(r, shl(5, lt(0xffffffff, shr(r, x))))\n            r := or(r, shl(4, lt(0xffff, shr(r, x))))\n            r := or(r, shl(3, lt(0xff, shr(r, x))))\n            r := or(r, shl(2, lt(0xf, shr(r, x))))\n            r := or(r, shl(1, lt(0x3, shr(r, x))))\n            r := or(r, lt(0x1, shr(r, x)))\n        }\n\n        // Reduce range of x to (1, 2) * 2**96\n        // ln(2^k * x) = k * ln(2) + ln(x)\n        int256 k = r - 96;\n        x <<= uint256(159 - k);\n        x = int256(uint256(x) >> 159);\n\n        // Evaluate using a (8, 8)-term rational approximation.\n        // p is made monic, we will multiply by a scale factor later.\n        int256 p = x + 3273285459638523848632254066296;\n        p = ((p * x) >> 96) + 24828157081833163892658089445524;\n        p = ((p * x) >> 96) + 43456485725739037958740375743393;\n        p = ((p * x) >> 96) - 11111509109440967052023855526967;\n        p = ((p * x) >> 96) - 45023709667254063763336534515857;\n        p = ((p * x) >> 96) - 14706773417378608786704636184526;\n        p = p * x - (795164235651350426258249787498 << 96);\n\n        // We leave p in 2**192 basis so we don't need to scale it back up for the division.\n        // q is monic by convention.\n        int256 q = x + 5573035233440673466300451813936;\n        q = ((q * x) >> 96) + 71694874799317883764090561454958;\n        q = ((q * x) >> 96) + 283447036172924575727196451306956;\n        q = ((q * x) >> 96) + 401686690394027663651624208769553;\n        q = ((q * x) >> 96) + 204048457590392012362485061816622;\n        q = ((q * x) >> 96) + 31853899698501571402653359427138;\n        q = ((q * x) >> 96) + 909429971244387300277376558375;\n        /// @solidity memory-safe-assembly\n        assembly {\n            // Div in assembly because solidity adds a zero check despite the unchecked.\n            // The q polynomial is known not to have zeros in the domain.\n            // No scaling required because p is already 2**96 too large.\n            r := sdiv(p, q)\n        }\n\n        // r is in the range (0, 0.125) * 2**96\n\n        // Finalization, we need to:\n        // * multiply by the scale factor s = 5.549…\n        // * add ln(2**96 / 10**18)\n        // * add k * ln(2)\n        // * multiply by 10**18 / 2**96 = 5**18 >> 78\n\n        // mul s * 5e18 * 2**96, base is now 5**18 * 2**192\n        r *= 1677202110996718588342820967067443963516166;\n        // add ln(2) * k * 5e18 * 2**192\n        r += 16597577552685614221487285958193947469193820559219878177908093499208371 * k;\n        // add ln(2**96 / 10**18) * 5e18 * 2**192\n        r += 600920179829731861736702779321621459595472258049074101567377883020018308;\n        // base conversion: mul 2**18 / 2**192\n        r >>= 174;\n    }\n}\n\n/// @dev Will return 0 instead of reverting if y is zero.\nfunction unsafeDiv(int256 x, int256 y) pure returns (int256 r) {\n    /// @solidity memory-safe-assembly\n    assembly {\n        // Divide x by y.\n        r := sdiv(x, y)\n    }\n}\n"},"src/Coin.sol":{"content":"// SPDX-License-Identifier: UNLICENSED\npragma solidity 0.8.24;\n\nimport \"lib/solmate/src/tokens/ERC20.sol\";\n\ncontract Coin is ERC20 {\n\n    address public immutable minter;\n\n    constructor(address _minter, string memory name, string memory symbol) ERC20(name, symbol, 18) {\n        minter = _minter;\n    }\n\n    function mint(address to, uint256 amount) external {\n        require(msg.sender == minter, \"Only minter can mint\");\n        _mint(to, amount);\n    }\n\n    function burn(uint256 amount) external {\n        _burn(msg.sender, amount);\n    }\n}"},"src/InterestModel.sol":{"content":"// SPDX-License-Identifier: UNLICENSED\npragma solidity 0.8.24;\n\nimport \"lib/solmate/src/utils/SignedWadMath.sol\";\n\n// Only one instance of this contract is deployed for use by all Lender contracts\ncontract InterestModel {\n\n    uint internal constant MIN_RATE = 5e15; // 0.5%\n\n    // The reason why this pure math is called externally by Lender contracts even though\n    // it is non-upgradeable is to allow Lender contracts try/catch the call for safety.\n    // In case of unexpected under/overflow here, Lender contracts would skip accruing interest\n    // while allowing borrowers to exit. Otherwise failure would freeze their funds.\n    // We could have also added this as an external function to Lender and called\n    // self.calculateInterest() externally, but since it's the same cost to call it here,\n    // we opt for this approach in order to reduce contract bytecode size of Lender.\n    // We also reduce Factory deployment costs by only using one instance of\n    // this contract for all Lender contracts.\n    function calculateInterest(\n        uint _totalPaidDebt,\n        uint _lastRate,\n        uint _timeElapsed,\n        uint _expRate,\n        uint _lastFreeDebtRatioBps,\n        uint _targetFreeDebtRatioStartBps,\n        uint _targetFreeDebtRatioEndBps\n    ) external pure returns (uint currBorrowRate, uint interest) {\n        // An empty market has no debt ratio signal; preserve its rate until debt or PSM backing exists.\n        if (_totalPaidDebt == 0 && _lastFreeDebtRatioBps == 0) return (_lastRate, 0);\n\n        // check _expRate * _timeElapsed overflow\n        if(uint(type(int256).max) / _expRate < _timeElapsed) _timeElapsed = uint(type(int256).max) / _expRate;\n        // we use a negative exponent in order to prevent growthDecay overflow due to large timeElapsed\n        // Results of positive exponents can exceed max uint256, negative exponents only return a value between [0, 1e18]\n        uint growthDecay = uint(wadExp(-int(_expRate * _timeElapsed)));\n        \n        if (_lastFreeDebtRatioBps < _targetFreeDebtRatioStartBps) {\n            if (growthDecay == 0) growthDecay = 1;\n            currBorrowRate = _lastRate * 1e18 / growthDecay;\n            interest = _totalPaidDebt * (currBorrowRate - _lastRate) / _expRate / 365 days;\n        } else if (_lastFreeDebtRatioBps > _targetFreeDebtRatioEndBps) {\n            currBorrowRate = _lastRate * growthDecay / 1e18;\n            if (currBorrowRate < MIN_RATE) {\n                currBorrowRate = MIN_RATE;\n                // calculate integral\n                if (_lastRate <= MIN_RATE) {\n                    // Already at min rate, just use flat rate for entire period\n                    interest = _totalPaidDebt * MIN_RATE * _timeElapsed / 365 days / 1e18;\n                } else {\n                    uint timeToMin = uint(-wadLn(int(MIN_RATE * 1e18 / _lastRate))) / _expRate;\n                    // Decaying integral up to min rate, then add flat rate portion\n                    interest = _totalPaidDebt * (_lastRate - MIN_RATE) / _expRate / 365 days +\n                              _totalPaidDebt * MIN_RATE * (_timeElapsed - timeToMin) / 365 days / 1e18;\n                }\n            } else {\n                interest = _totalPaidDebt * (_lastRate - currBorrowRate) / _expRate / 365 days;\n            }\n        } else {\n            currBorrowRate = _lastRate;\n            interest = _totalPaidDebt * _lastRate * _timeElapsed / 365 days / 1e18;\n        }\n        \n        // If interest would overflow uint120 (cast in Lender), skip accrual\n        // Also check if currBorrowRate would overflow uint88 (cast in Lender)\n        if (interest > type(uint120).max || currBorrowRate > type(uint88).max) {\n            return (_lastRate, 0);\n        }\n    }\n}\n"},"src/Lender.sol":{"content":"// SPDX-License-Identifier: UNLICENSED\npragma solidity 0.8.24;\n\nimport \"lib/solmate/src/tokens/ERC20.sol\";\nimport \"lib/solmate/src/tokens/ERC4626.sol\";\nimport \"lib/solmate/src/utils/SafeTransferLib.sol\";\nimport \"lib/solmate/src/utils/FixedPointMathLib.sol\";\nimport \"./Coin.sol\";\nimport \"./Vault.sol\";\nimport \"./InterestModel.sol\";\n\ninterface IChainlinkFeed {\n    function decimals() external view returns (uint8);\n    function latestRoundData() external view returns (\n        uint80 roundId,\n        int256 answer,\n        uint256 startedAt,\n        uint256 updatedAt,\n        uint80 answeredInRound\n    );\n}\n\ninterface IFactory {\n    function getFeeOf(address _lender) external view returns (uint256);\n    function minDebtFloor() external view returns (uint256);\n}\n\ncontract Lender {\n\n    using SafeTransferLib for ERC20;\n    using FixedPointMathLib for uint256;\n\n    // single 256-bit slot\n    uint16 public targetFreeDebtRatioStartBps; // max uint16 is 65535 bps which is outside of the range [0, 10000]\n    uint16 public targetFreeDebtRatioEndBps; // max uint16 is 65535 bps which is outside of the range [0, 10000]\n    uint16 public redeemFeeBps; // max uint16 is 65535 bps fee which is outside of the range [0, 10000]\n    uint64 public expRate; // max result is 693147180559945309 which is within uint64 range\n    uint40 public lastAccrue; // max uint40 is year 36812\n    uint88 public lastBorrowRateMantissa = uint88(2e16); // max uint88 is equivalent to 309485000% APR\n    uint16 public feeBps; // max uint16 is 65535 bps which is outside of the range [0, 10000]\n    \n\n    // single 256-bit slot\n    uint16 public cachedGlobalFeeBps;\n    uint120 public accruedLocalReserves;\n    uint120 public accruedGlobalReserves;\n\n    // Other state variables\n    address public operator;\n    address public pendingOperator;\n    uint public immutabilityDeadline; // may only be reduced by operator\n    uint public totalFreeDebt;\n    uint public totalFreeDebtShares;\n    uint public totalPaidDebt;\n    uint public totalPaidDebtShares;\n    uint public freePsmAssets;\n    uint16 public maxBorrowDeltaBps; // max acceptable rounding error in bps when borrowing (e.g., 200 = 2%)\n    \n    // Constants and immutables\n    Coin public immutable coin;\n    ERC20 public immutable collateral;\n    ERC20 public immutable psmAsset;\n    ERC4626 public immutable psmVault;\n    IChainlinkFeed public immutable feed;\n    Vault public immutable vault;\n    InterestModel public immutable interestModel;\n    IFactory public immutable factory;\n    uint public immutable collateralFactor;\n    uint public immutable minDebt;\n    uint public immutable deployTimestamp;\n    uint public immutable psmAssetDecimals;\n    uint public immutable collateralDecimals;\n    uint public immutable stalenessThreshold; \n    uint public immutable psmVaultMinTotalSupply;\n\n    uint public constant STALENESS_UNWIND_DURATION = 24 hours;\n    uint public constant MIN_LIQUIDATION_DEBT = 10_000e18; // 10,000 Coin\n    uint public constant MAX_DECIMALS = 30; // Maximum allowed token decimals\n    \n    // For accrueInterest() try-catch\n    uint256 private constant INTEREST_CALCULATION_GAS_REQUIREMENT = 40_000;\n    // For writeOff() try-catch in liquidate() \n    uint256 private constant WRITEOFF_GAS_REQUIREMENT = 120_000;\n\n    // Mappings\n    mapping(address => uint) public collateralBalances; // stored in collateral token native decimals\n    mapping(address => uint) public freeDebtShares;\n    mapping(address => uint) public paidDebtShares;\n    mapping(address => bool) public isRedeemable;\n    mapping(address => mapping(address => bool)) public delegations;\n\n    address public manager;\n\n    struct LenderParams {\n        ERC20 collateral;\n        ERC20 psmAsset; // optional\n        ERC4626 psmVault; // optional\n        IChainlinkFeed feed;\n        Coin coin;\n        Vault vault;\n        InterestModel interestModel;\n        IFactory factory;\n        address operator;\n        address manager;\n        uint collateralFactor;\n        uint minDebt;\n        uint timeUntilImmutability;\n        uint64 halfLife;\n        uint16 targetFreeDebtRatioStartBps;\n        uint16 targetFreeDebtRatioEndBps;\n        uint16 redeemFeeBps;\n        uint32 stalenessThreshold;\n        uint16 maxBorrowDeltaBps;\n        uint128 psmVaultMinTotalSupply;\n    }\n\n    constructor(LenderParams memory params) {\n        require(params.collateralFactor <= 8500, \"Invalid collateral factor\");\n        require(params.timeUntilImmutability <= 1460 days, \"Max immutability deadline is in 4 years\");\n        require(params.halfLife >= 12 hours && params.halfLife <= 30 days, \"Invalid half life\");\n        require(params.targetFreeDebtRatioStartBps >= 500 && params.targetFreeDebtRatioStartBps <= params.targetFreeDebtRatioEndBps, \"Invalid start bps\");\n        require(params.targetFreeDebtRatioEndBps <= 9500, \"Invalid end bps\");\n        require(params.redeemFeeBps <= 500, \"Invalid redeem fee bps\");\n        require(params.maxBorrowDeltaBps <= 200 && params.maxBorrowDeltaBps >= 50, \"Invalid max borrow delta bps\"); // Max 2%\n        uint minDebtFloor = IFactory(params.factory).minDebtFloor();\n        require(params.minDebt >= minDebtFloor, \"Invalid min debt\");\n        require(address(params.psmAsset) != address(params.coin), \"PSM Asset must be different than Coin\");\n       \n        if(params.psmVault != ERC4626(address(0))) {\n            require(params.psmVault.asset() == params.psmAsset, \"PSM asset mismatch\");\n            require(params.psmVaultMinTotalSupply > 0, \"Invalid PSM vault min total supply\");\n        }\n        \n        // Validate collateral decimals\n        uint256 _collateralDecimals = params.collateral.decimals();\n        require(_collateralDecimals <= MAX_DECIMALS, \"Collateral decimals exceed maximum\");\n        collateralDecimals = _collateralDecimals;\n        \n        collateral = params.collateral;\n        psmAsset = params.psmAsset;\n        psmVault = params.psmVault;\n        feed = params.feed;\n        coin = params.coin;\n        vault = params.vault;\n        interestModel = params.interestModel;\n        factory = params.factory;\n        operator = params.operator;\n        manager = params.manager;\n        collateralFactor = params.collateralFactor;\n        minDebt = params.minDebt;\n        deployTimestamp = block.timestamp;\n        immutabilityDeadline = block.timestamp + params.timeUntilImmutability;\n        lastAccrue = uint40(block.timestamp);\n        expRate = uint64(uint(wadLn(2*1e18)) / params.halfLife);\n        targetFreeDebtRatioStartBps = params.targetFreeDebtRatioStartBps;\n        targetFreeDebtRatioEndBps = params.targetFreeDebtRatioEndBps;\n        redeemFeeBps = params.redeemFeeBps;\n        maxBorrowDeltaBps = params.maxBorrowDeltaBps;\n        stalenessThreshold = params.stalenessThreshold;\n        psmVaultMinTotalSupply = params.psmVaultMinTotalSupply;\n        cachedGlobalFeeBps = uint16(factory.getFeeOf(address(this)));\n        if(psmVault != ERC4626(address(0)))\n            psmAsset.safeApprove(address(psmVault), type(uint).max);\n        uint256 _psmAssetDecimals;\n        if (psmAsset != ERC20(address(0))) {\n            _psmAssetDecimals = psmAsset.decimals();\n        } \n        psmAssetDecimals = _psmAssetDecimals;\n    }\n\n    // Modifiers\n\n    modifier onlyOperator() {\n        require(msg.sender == operator, \"Unauthorized\");\n        _;\n    }\n\n    modifier onlyOperatorOrManager() {\n        require(msg.sender == operator || msg.sender == manager, \"Unauthorized\");\n        _;\n    }\n\n    modifier beforeDeadline() {\n        require(block.timestamp < immutabilityDeadline, \"Deadline passed\");\n        _;\n    }\n\n    // Public functions\n\n    function accrueInterest() public {\n        uint timeElapsed = block.timestamp - lastAccrue;\n        if(timeElapsed == 0) return;\n\n        uint256 gasBefore = gasleft();\n\n        try interestModel.calculateInterest(\n            totalPaidDebt,\n            lastBorrowRateMantissa,\n            timeElapsed,\n            expRate,\n            getFreeDebtRatio(),\n            targetFreeDebtRatioStartBps,\n            targetFreeDebtRatioEndBps\n        ) returns (uint currBorrowRate, uint interest) {\n            uint120 localReserveFee = uint120(interest * feeBps / 10000);\n            uint120 globalReserveFee = uint120(interest * cachedGlobalFeeBps / 10000);\n            accruedLocalReserves += localReserveFee;\n            accruedGlobalReserves += globalReserveFee;\n            // we remove reserve fees from interest before calculating how much to give to stakers\n            uint interestAfterFees = interest - localReserveFee - globalReserveFee;\n            uint totalStaked = coin.balanceOf(address(vault));\n            if(totalStaked < totalPaidDebt) { // this also implies totalPaidDebt > 0 and guards the division below\n                // if total staked is less than paid debt, giving all interest to stakers would\n                // result in higher supply rate than borrow rate which is undesirable.\n                // we cap the supply rate at the borrow rate and give the rest to local reserves.\n                uint stakedInterest = interestAfterFees * totalStaked / totalPaidDebt;\n                coin.mint(address(vault), stakedInterest);\n                uint remainingInterest = interestAfterFees - stakedInterest;\n                accruedLocalReserves += uint120(remainingInterest);\n            } else {\n                // if total staked is greater than paid debt, we give all interest to stakers\n                coin.mint(address(vault), interestAfterFees);\n            }\n            totalPaidDebt += interest; // we add all interest to paid debt (NOT interestAfterFees)\n            lastAccrue = uint40(block.timestamp);\n            lastBorrowRateMantissa = uint88(currBorrowRate);\n            cachedGlobalFeeBps = uint16(factory.getFeeOf(address(this)));\n            emit InterestAccrued(interest, currBorrowRate);\n        } catch {\n            // If the call failed, check if sufficient gas was provided\n            // We need to ensure the caller provided enough gas for accrueInterest to execute\n            require(gasBefore >= INTEREST_CALCULATION_GAS_REQUIREMENT, \"Not enough gas for accrueInterest\");\n        }\n    }\n\n    function adjust(address account, int collateralDelta, int debtDelta) public {\n        accrueInterest();\n        // Handle collateral changes\n        if (collateralDelta > 0) {\n            uint256 collateralAmount = uint(collateralDelta);\n            collateralBalances[account] += collateralAmount;\n            // Transfer actual token amount\n            collateral.safeTransferFrom(msg.sender, address(this), collateralAmount);\n        } else if (collateralDelta < 0) {\n            uint256 collateralAmount = uint(-collateralDelta);\n            collateralBalances[account] -= collateralAmount;\n            collateral.safeTransfer(msg.sender, collateralAmount);\n        }\n\n        // Handle debt changes\n        int actualDebtDelta = debtDelta;\n        if (debtDelta > 0) {\n            // Borrow\n            uint amount = uint256(debtDelta);\n            increaseDebt(account, amount);\n            coin.mint(msg.sender, amount);\n        } else if (debtDelta < 0) {\n            // Repay\n            uint amount = uint256(-debtDelta);\n            uint debt = getDebtOf(account);\n            if(debt <= amount) {\n                amount = debt;\n                actualDebtDelta = -int(debt); // Use actual debt repaid for full repayment\n                decreaseDebt(account, type(uint).max);\n            } else {\n                decreaseDebt(account, amount);\n            }\n            coin.transferFrom(msg.sender, address(this), amount);\n            coin.burn(amount);\n        }\n\n        // if debtDelta is non-zero, require debt balance to either be 0 or >= minDebt\n        uint debtBalance = getDebtOf(account);\n        if(debtDelta != 0) require(debtBalance == 0 || debtBalance >= minDebt, \"Debt below minimum and larger than 0\");\n\n        // Emit event before the first early return\n        emit PositionAdjusted(account, collateralDelta, actualDebtDelta);\n\n        // Skip remaining invariants if caller does not reduce collateral AND does not increase debt\n        if(collateralDelta >= 0 && debtDelta <= 0) return;\n\n        // The caller is removing collateral and/or increasing debt. Enforce ownership beyond this point\n        require(msg.sender == account || delegations[account][msg.sender], \"Unauthorized\");\n\n        // Skip solvency checks if debt is zero\n        if(debtBalance == 0) return;\n\n        // Check solvency\n        (uint price, bool reduceOnly, ) = getCollateralPrice();\n        require(!reduceOnly, \"Reduce only\");\n        uint borrowingPower = price * collateralBalances[account] * collateralFactor / 1e18 / 10000;\n        require(debtBalance <= borrowingPower, \"Solvency check failed\");\n    }\n\n    function adjust(address account, int collateralDelta, int debtDelta, bool chooseRedeemable) external {\n        setRedemptionStatus(account, chooseRedeemable);\n        adjust(account, collateralDelta, debtDelta);\n    }\n\n    /// @notice Allows an account to delegate control of position management to another address\n    /// @dev Delegatees can call adjust(), setRedemptionStatus(), and the overloaded adjust() with redemption status.\n    /// @param delegatee The address to delegate to\n    /// @param isDelegatee True to enable delegation, false to revoke\n    function delegate(address delegatee, bool isDelegatee) external {\n        delegations[msg.sender][delegatee] = isDelegatee;\n        emit DelegationUpdated(msg.sender, delegatee, isDelegatee);\n    }\n\n    function setRedemptionStatus(address account, bool chooseRedeemable) public {\n        accrueInterest();\n        require(msg.sender == account || delegations[account][msg.sender], \"Unauthorized\");\n        if(chooseRedeemable == isRedeemable[account]) return; // no change\n        uint prevDebt = getDebtOf(account);\n        if(prevDebt > 0) {\n            decreaseDebt(account, type(uint).max);\n            isRedeemable[account] = chooseRedeemable;\n            increaseDebt(account, prevDebt);\n            uint currDebt = getDebtOf(account);\n            require(currDebt >= prevDebt, \"Debt decreased unexpectedly\");\n        } else {\n            isRedeemable[account] = chooseRedeemable;\n        }\n        emit RedemptionStatusUpdated(account, chooseRedeemable);\n    }\n\n        /// @notice Liquidates an unsafe position\n    /// @param borrower The account to be liquidated\n    /// @param repayAmount The amount of debt to repay\n    /// @param minCollateralOut The minimum amount of collateral to receive (in token decimals)\n    /// @return The amount of collateral received (in token decimals)\n    function liquidate(address borrower, uint repayAmount, uint minCollateralOut) external returns(uint) {\n        accrueInterest();\n        require(repayAmount > 0, \"Repay amount must be greater than 0\");\n        (uint price,, bool allowLiquidations) = getCollateralPrice();\n        require(allowLiquidations, \"liquidations disabled\");\n        uint debt = getDebtOf(borrower);\n        uint collateralBalance = collateralBalances[borrower]; // in collateral token decimals\n        // check liquidation condition\n        uint liquidatableDebt = getLiquidatableDebt(collateralBalance, price, debt);\n        require(liquidatableDebt > 0, \"insufficient liquidatable debt\");\n        if(repayAmount > liquidatableDebt) {\n            repayAmount = liquidatableDebt;\n        }\n\n        uint liqIncentiveBps = getLiquidationIncentiveBps(collateralBalance, price, debt);\n        uint maxRepayByCollateral = getMaxRepayByCollateral(collateralBalance, price, liqIncentiveBps);\n        if(repayAmount > maxRepayByCollateral) {\n            repayAmount = maxRepayByCollateral;\n        }\n        require(repayAmount > 0, \"insufficient collateral out\");\n\n        // apply repayment\n        decreaseDebt(borrower, repayAmount);\n\n        // calculate collateral reward (in collateral token decimals)\n        uint collateralRewardValue = repayAmount * (10000 + liqIncentiveBps) / 10000;\n        uint collateralReward = repayAmount == maxRepayByCollateral ? collateralBalance : collateralRewardValue * 1e18 / price;\n        \n        require(collateralReward >= minCollateralOut, \"insufficient collateral out\");\n\n        if(collateralReward > 0) {\n            collateralBalances[borrower] = collateralBalance - collateralReward;\n            collateral.safeTransfer(msg.sender, collateralReward);\n        }\n        coin.transferFrom(msg.sender, address(this), repayAmount);\n        coin.burn(repayAmount);\n        emit Liquidated(borrower, msg.sender, repayAmount, collateralReward);\n        \n        uint256 gasBefore = gasleft();\n        // try to write off remaining debt. Call externally and catch error to prevent liquidation failure\n        try this.writeOff(borrower, msg.sender) {} catch {\n            // If the call failed, check if sufficient gas was provided\n            // We need to ensure the caller provided enough gas for writeOff to execute\n            require(gasBefore >= WRITEOFF_GAS_REQUIREMENT, \"Not enough gas for writeOff\");\n        }\n        return collateralReward;\n    }\n\n    /// @notice Redistributes excess debt of undercollateralized accounts among other borrowers\n    /// @param borrower The account in potentiallyundercollateralized state\n    /// @return writtenOff True if the borrower was written off, false otherwise\n    /// @param to The address to send the collateral to\n    /// @dev This function is called by liquidate() when a borrower's position is undercollateralized. It should never revert to avoid liquidation failure.\n    function writeOff(address borrower, address to) external returns (bool writtenOff) {\n        accrueInterest();\n        // check for write off\n        uint debt = getDebtOf(borrower);\n        if(debt > 0) {\n            uint collateralBalance = collateralBalances[borrower]; // in collateral token decimals\n            (uint price,, bool allowLiquidations) = getCollateralPrice();\n            require(allowLiquidations, \"liquidations disabled\");\n            uint collateralValue = price * collateralBalance / 1e18;\n            // if debt is more than 100 times the collateral value, write off\n            if(debt > collateralValue * 100) {\n                // 1. delete all of the borrower's debt\n                decreaseDebt(borrower, type(uint).max);\n                // 2. redistribute excess debt among remaining borrowers\n                uint256 totalDebt = totalFreeDebt + totalPaidDebt;\n                if (totalDebt > 0) {\n                    uint256 freeDebtIncrease = debt * totalFreeDebt / totalDebt;\n                    uint256 paidDebtIncrease = debt - freeDebtIncrease;\n\n                    totalFreeDebt += freeDebtIncrease;\n                    totalPaidDebt += paidDebtIncrease;\n                }\n\n                collateralBalances[borrower] = 0;\n                \n                emit WrittenOff(borrower, to, debt, collateralBalance);\n                writtenOff = true;\n                \n                collateral.safeTransfer(to, collateralBalance);\n            }\n        }\n    }\n\n    /// @notice Redeems Coin for collateral at current market price minus a fee\n    /// @param borrower The borrower to redeem from\n    /// @param amountIn The max amount of Coin to redeem\n    /// @param minAmountOut The minimum amount of collateral to receive (in token decimals)\n    /// @return amountOut The amount of collateral received (in token decimals)\n    /// @dev Redemptions are borrower-specific and always target a single redeemable borrower\n    function redeem(address borrower, uint amountIn, uint minAmountOut) external returns (uint amountOut) {\n        accrueInterest();\n        require(isRedeemable[borrower], \"Borrower is not redeemable\");\n        require(amountIn > 0, \"amount in is zero\");\n\n        uint collateralBalance = collateralBalances[borrower];\n        require(collateralBalance > 0, \"Borrower has no collateral\");\n\n        (uint price,, bool allowLiquidations) = getCollateralPrice();\n        require(allowLiquidations, \"Redemptions disabled\");\n\n        uint borrowerDebt = getDebtOf(borrower);\n        require(borrowerDebt > 0, \"Borrower has no debt\");\n        if (amountIn > borrowerDebt) amountIn = borrowerDebt;\n\n        uint maxRedeemByCollateral = collateralBalance * price * 10000 / 1e18 / (10000 - redeemFeeBps);\n        require(maxRedeemByCollateral > 0, \"Insufficient collateral\");\n        if (amountIn > maxRedeemByCollateral) amountIn = maxRedeemByCollateral;\n\n        // Repay borrower debt and derive the exact debt amount reduced by shares arithmetic.\n        decreaseDebt(borrower, amountIn);\n        uint remainingDebt = getDebtOf(borrower);\n        amountIn = borrowerDebt - remainingDebt;\n        require(amountIn > 0, \"amount in too small\");\n        require(remainingDebt == 0 || remainingDebt >= minDebt, \"Debt below minimum and larger than 0\");\n\n        amountOut = amountIn * 1e18 * (10000 - redeemFeeBps) / price / 10000;\n        require(amountOut > 0, \"amount out is zero\");\n        require(amountOut <= collateralBalance, \"Insufficient borrower collateral\");\n\n        require(amountOut >= minAmountOut, \"insufficient amount out\");\n\n        // Seize collateral directly from borrower.\n        collateralBalances[borrower] = collateralBalance - amountOut;\n\n        coin.transferFrom(msg.sender, address(this), amountIn);\n        coin.burn(amountIn);\n\n        collateral.safeTransfer(msg.sender, amountOut);\n        emit Redeemed(msg.sender, borrower, amountIn, amountOut);\n        return amountOut;\n    }\n\n    function sell(uint coinIn, uint minAssetOut) external returns (uint assetOut) {\n        require(psmAsset != ERC20(address(0)), \"PSM asset was not set\");\n        accrueInterest();\n        assetOut = getSellAmountOut(coinIn);\n        require(assetOut >= minAssetOut, \"insufficient amount out\");\n        // get and burn coins from caller\n        coin.transferFrom(msg.sender, address(this), coinIn);\n        coin.burn(coinIn);\n        // give assets to caller\n        if(psmVault != ERC4626(address(0))) {\n            // Convert to shares out without taking into account fees, which will be paid by the seller by receiving less than assetOut\n            uint256 sharesOut = psmVault.convertToShares(assetOut);\n            uint256 actualAssetOutToSeller = psmVault.redeem(sharesOut, msg.sender, address(this));\n            freePsmAssets -= assetOut;\n            require(actualAssetOutToSeller >= minAssetOut, \"redeem failed\");\n            assetOut = actualAssetOutToSeller;\n        } else {\n            freePsmAssets -= assetOut;\n            psmAsset.safeTransfer(msg.sender, assetOut);\n        }\n        emit Sold(msg.sender, coinIn, assetOut);\n    }\n\n    function buy(uint assetIn, uint minCoinOut) external beforeDeadline returns (uint coinOut) {\n        require(psmAsset != ERC20(address(0)), \"PSM asset was not set\");\n        accrueInterest();\n        uint coinFee;\n\n        // get assets from caller\n        psmAsset.safeTransferFrom(msg.sender, address(this), assetIn);\n        if(psmVault != ERC4626(address(0))) {\n            require(psmVault.totalSupply() > psmVaultMinTotalSupply, \"PSM vault total supply below minimum\");\n            uint256 shares = psmVault.deposit(assetIn, address(this));\n            require(shares > 0, \"PSM deposit failed\");\n            uint256 redeemableFor = previewRedeemOrConvertToAssets(shares);\n            freePsmAssets += redeemableFor;\n            (coinOut, coinFee) = getBuyAmountOut(redeemableFor);\n        } else {\n            freePsmAssets += assetIn;\n            (coinOut, coinFee) = getBuyAmountOut(assetIn);\n        }\n        if(coinFee > 0) accruedLocalReserves += uint120(coinFee);\n        require(coinOut >= minCoinOut, \"insufficient amount out\");\n        // give coins to caller\n        coin.mint(msg.sender, coinOut);\n        emit Bought(msg.sender, assetIn, coinOut);\n    }\n\n    function reapprovePsmVault() external beforeDeadline {\n        if(psmVault != ERC4626(address(0))){\n            //Zero approve to support USDT. Thank you Tabboz\n            psmAsset.safeApprove(address(psmVault), 0);\n            psmAsset.safeApprove(address(psmVault), type(uint).max);\n        }\n    }\n\n    // Internal functions\n\n    function accruePsmProfit() internal {\n        if(address(psmVault) != address(0)){\n            uint assets = previewRedeemOrConvertToAssets(psmVault.balanceOf(address(this)));\n            if(assets <= freePsmAssets) return; // avoids underflow in case of loss\n            uint profit = assets - freePsmAssets;\n            accruedLocalReserves += uint120(normalizePsmAssets(profit));\n            freePsmAssets = assets;\n        } else if(psmAsset != ERC20(address(0))) {\n            // we do this in case the underlying asset may be a rebasing token that accrues profit\n            uint bal = psmAsset.balanceOf(address(this));\n            if(bal <= freePsmAssets) return; // avoids underflow in case of loss\n            uint profit = bal - freePsmAssets;\n            accruedLocalReserves += uint120(normalizePsmAssets(profit));\n            freePsmAssets = bal;\n        }\n    }\n\n    function previewRedeemOrConvertToAssets(uint shares) internal view returns (uint assets) {\n        try psmVault.previewRedeem(shares) returns (uint previewAssets) {\n            return previewAssets;\n        } catch {\n            return psmVault.convertToAssets(shares);\n        }\n    }\n\n    function increaseDebt(address account, uint256 amount) internal {\n        if (isRedeemable[account]) {\n            // Handle free debt\n            uint shares = totalFreeDebt == 0 ? \n                    amount : \n                    amount.mulDivUp(totalFreeDebtShares, totalFreeDebt);\n            \n            // Update state first\n            totalFreeDebt += amount;\n            totalFreeDebtShares += shares;\n            freeDebtShares[account] += shares;\n\n            // Calculate actual debt increase after share conversion (in the new state)\n            uint256 actualDebtIncrease = shares.mulDivUp(totalFreeDebt, totalFreeDebtShares);\n            // Enforce max-delta guard: actual debt must not exceed requested by more than maxBorrowDeltaBps\n            uint256 maxAllowedDebtIncrease = amount * (10000 + maxBorrowDeltaBps) / 10000;\n            require(actualDebtIncrease <= maxAllowedDebtIncrease, \"Borrow delta exceeds max\");\n        } else {\n            // Handle paid debt \n            uint256 shares = totalPaidDebt == 0 ? \n                amount : \n                amount.mulDivUp(totalPaidDebtShares, totalPaidDebt);\n            \n            // Update state first\n            totalPaidDebt += amount;\n            totalPaidDebtShares += shares;\n            paidDebtShares[account] += shares;\n            \n            // Calculate actual debt increase after share conversion (in the new state)\n            uint256 actualDebtIncrease = shares.mulDivUp(totalPaidDebt, totalPaidDebtShares);\n            // Enforce max-delta guard: actual debt must not exceed requested by more than maxBorrowDeltaBps\n            uint256 maxAllowedDebtIncrease = amount * (10000 + maxBorrowDeltaBps) / 10000;\n            require(actualDebtIncrease <= maxAllowedDebtIncrease, \"Borrow delta exceeds max\");\n        }\n    }\n\n    function decreaseDebt(address account, uint256 amount) internal {\n        if (isRedeemable[account]) {\n            // Handle free debt\n            uint256 shares;\n            if(amount == type(uint).max) {\n                shares = freeDebtShares[account];\n                amount = getDebtOf(account);\n            } else {\n                shares = amount.mulDivDown(totalFreeDebtShares, totalFreeDebt);\n            }\n            freeDebtShares[account] -= shares;\n            totalFreeDebtShares = totalFreeDebtShares <= shares ? 0 : totalFreeDebtShares - shares; // prevent underflow\n            totalFreeDebt = totalFreeDebt <= amount ? 0 : totalFreeDebt - amount; // prevent underflow\n        } else {\n            // Handle paid debt\n            uint256 shares;\n            if(amount == type(uint).max) {\n                shares = paidDebtShares[account];\n                amount = getDebtOf(account);\n            } else {\n                shares = amount.mulDivDown(totalPaidDebtShares, totalPaidDebt);\n            }\n            \n            paidDebtShares[account] -= shares;\n            totalPaidDebtShares = totalPaidDebtShares <= shares ? 0 : totalPaidDebtShares - shares; // prevent underflow\n            totalPaidDebt = totalPaidDebt <= amount ? 0 : totalPaidDebt - amount; // prevent underflow\n        }\n    }\n\n    function getLiquidatableDebt(uint collateralBalance, uint price, uint debt) internal view returns(uint liquidatableDebt){\n        uint borrowingPower = price * collateralBalance * collateralFactor / 1e18 / 10000;\n        if(borrowingPower >= debt) return 0;\n        // liquidate 25% of the total debt\n        liquidatableDebt = debt / 4; // 25% of the debt\n        // liquidate at least MIN_LIQUIDATION_DEBT (or the entire debt if it's less than MIN_LIQUIDATION_DEBT)\n        if(liquidatableDebt < MIN_LIQUIDATION_DEBT) liquidatableDebt = debt < MIN_LIQUIDATION_DEBT ? debt : MIN_LIQUIDATION_DEBT;\n    }\n\n    function getMaxRepayByCollateral(uint collateralBalance, uint price, uint liqIncentiveBps) internal pure returns(uint) {\n        uint collateralValue = collateralBalance * price / 1e18;\n        return collateralValue * 10000 / (10000 + liqIncentiveBps);\n    }\n\n    function getLiquidationIncentiveBps(uint collateralBalance, uint price, uint debt) internal view returns(uint) {\n        uint collateralValue = collateralBalance * price / 1e18;\n        if (collateralValue == 0) return 0; // avoid division by zero, return 0% incentive\n        uint ltvBps = debt * 10000 / collateralValue;\n        uint _collateralFactor = collateralFactor; // gas optimization\n        uint maxLtvBps = _collateralFactor + 500; // range is [_collateralFactor, _collateralFactor + 5%]\n\n        if (ltvBps <= _collateralFactor) {\n            return 0; // 0% incentive\n        } else if (ltvBps >= maxLtvBps) {\n            return 1000; // 10% incentive\n        } else {\n            // linear interpolation between 0% and 10% incentive\n            return (ltvBps - _collateralFactor) * 1000 / (maxLtvBps - _collateralFactor);\n        }\n    }\n\n    // Getters\n\n    function getFreeDebtRatio() public view returns (uint) {\n        uint _adjustedTotalFreeDebt = totalFreeDebt + normalizePsmAssets(freePsmAssets);\n        return _adjustedTotalFreeDebt == 0 ? 0 : _adjustedTotalFreeDebt * 10000 / (totalPaidDebt + _adjustedTotalFreeDebt);\n    }\n\n    function getDebtOf(address account) public view returns (uint) {\n        if(isRedeemable[account]) {\n            return totalFreeDebtShares == 0 ? 0 : freeDebtShares[account].mulDivUp(totalFreeDebt, totalFreeDebtShares);\n        } else {\n            return totalPaidDebtShares == 0 ? 0 : paidDebtShares[account].mulDivUp(totalPaidDebt, totalPaidDebtShares);\n        }\n    }\n\n    /// @notice Gets the current price of the collateral asset\n    /// @return price The price in USD normalized to (36 - collateral decimals) decimals\n    /// @return reduceOnly A boolean indicating if reduce only mode is enabled\n    /// @return allowLiquidations A boolean indicating if liquidations and write-offs are enabled\n    function getCollateralPrice() public view returns (uint price, bool reduceOnly, bool allowLiquidations) {\n        uint updatedAt;\n        allowLiquidations = true; // Default to allowing liquidations\n        \n        // call our own getFeedPrice() externally to catch all feed reverts e.g. due to inexistent feed contract, function, etc.\n        try this.getFeedPrice() returns (uint _price, uint _updatedAt) {\n            price = _price;\n            updatedAt = _updatedAt;\n            if(price == 0) {\n                reduceOnly = true;\n                allowLiquidations = false; // Disable liquidations if price is invalid\n            }\n        } catch {\n            reduceOnly = true;\n            allowLiquidations = false; // Disable liquidations only if the oracle feed is reverting\n        }\n        \n        uint currentTime = block.timestamp;\n        uint timeElapsed = currentTime >= updatedAt ? currentTime - updatedAt : 0;\n\n        if (timeElapsed > stalenessThreshold) {\n            reduceOnly = true;\n            uint stalenessDuration = timeElapsed - stalenessThreshold;\n            if (stalenessDuration < STALENESS_UNWIND_DURATION) {\n                price = price * (STALENESS_UNWIND_DURATION - stalenessDuration) / STALENESS_UNWIND_DURATION;\n            } else {\n                price = 0;\n            }\n        }\n        price = price == 0 ? 1 : price; // avoid division by zero in consumer functions\n        uint totalDebt = totalFreeDebt + totalPaidDebt;\n        uint totalCollateralValue = collateral.balanceOf(address(this)) * price / 1e18;\n        if(totalDebt > totalCollateralValue) reduceOnly = true;\n    }\n\n    function getFeedPrice() external view returns (uint price, uint updatedAt) {\n        (,int256 feedPrice,,uint feedUpdatedAt,) = feed.latestRoundData();\n        updatedAt = feedUpdatedAt;\n        if(feedPrice <= 0) return (0, updatedAt); //convert negative price to 0 to signal invalid price\n        uint8 feedDecimals = feed.decimals();\n        uint8 tokenDecimals = uint8(collateralDecimals); // collateral balances are kept in native token decimals\n        if(feedDecimals + tokenDecimals <= 36) {\n            uint8 decimals = 36 - tokenDecimals - feedDecimals;\n            price = uint(feedPrice) * (10**decimals);\n        } else {\n            uint8 decimals = feedDecimals + tokenDecimals - 36;\n            price = uint(feedPrice) / (10**decimals);\n        }\n    }\n\n    function getSellAmountOut(uint coinIn) public view returns (uint assetOut) {\n        uint8 coinDecimals = 18;\n        uint8 assetDecimals = psmAsset.decimals();\n\n        if (coinDecimals > assetDecimals) {\n            // e.g., 18 decimals -> 6 decimals: divide by 10^(18-6) = 10^12\n            assetOut = coinIn / (10 ** (coinDecimals - assetDecimals));\n        } else if (assetDecimals > coinDecimals) {\n            // e.g., 6 decimals -> 18 decimals: multiply by 10^(18-6) = 10^12\n            assetOut = coinIn * (10 ** (assetDecimals - coinDecimals));\n        } else {\n            // Same decimals: 1:1 ratio\n            assetOut = coinIn;\n        }\n    }\n\n    function getBuyFeeBps() public view returns (uint) {\n        uint startTime = deployTimestamp;\n        uint deadline = immutabilityDeadline;\n        uint current = block.timestamp;\n\n        // Calculate the halfway point of the deadline period\n        uint halfTime = startTime + ((deadline - startTime) / 2);\n\n        if (current >= deadline || current < halfTime) {\n            return 0;\n        }\n\n        // fee ramps from 0% to 1% (100 bps) over the second half of the deadline period\n        // rampDuration = deadline - halfTime = (deadline - startTime) / 2\n        // timeIntoRamp = current - halfTime\n        // feeBps = timeIntoRamp * 100 / rampDuration\n        uint rampDuration = deadline - halfTime;\n        if (rampDuration == 0) return 100; // avoids division by zero\n\n        uint timeIntoRamp = current - halfTime;\n        uint buyFeeBps = timeIntoRamp * 100 / rampDuration;\n\n        // Cap at 100 bps (1%)\n        return buyFeeBps > 100 ? 100 : buyFeeBps;\n    }\n\n    /// Provides an upperbound of assets received\n    /// @dev the amount will be precise if no vault is attached to the PSM, but may overshoot on assets received if:\n    /// 1. There is a rounding loss in the vault. This is almost guaranteed.\n    /// 2. There is a withdraw fee or other loss occuring in the vault\n    /// To get a more precise estimate, we suggest using the following code in case the contract uses a PSM:\n    /// `getBuyAmountOut(vault.previewRedeem(vault.previewDeposit(assetIn)))`\n    function getBuyAmountOut(uint assetIn) public view returns (uint coinOut, uint coinFee) {\n        uint8 coinDecimals = 18;\n        uint8 assetDecimals = psmAsset.decimals();\n\n        if (assetDecimals > coinDecimals) {\n            // e.g., 6 decimals -> 18 decimals: divide by 10^(6-18) = 10^12\n            coinOut = assetIn / (10 ** (assetDecimals - coinDecimals));\n        } else if (coinDecimals > assetDecimals) {\n            // e.g., 18 decimals -> 6 decimals: multiply by 10^(18-6) = 10^12\n            coinOut = assetIn * (10 ** (coinDecimals - assetDecimals));\n        } else {\n            // Same decimals: 1:1 ratio\n            coinOut = assetIn;\n        }\n\n        // Apply buy fee\n        uint buyFeeBps = getBuyFeeBps();\n        if(buyFeeBps > 0) {\n            coinFee = coinOut * buyFeeBps / 10000;\n            coinOut -= coinFee;\n        }\n    }\n\n    /// @notice Normalizes PSM asset amount to 18 decimals\n    /// @param assets The amount of PSM asset to normalize\n    /// @return The normalized amount with 18 decimals\n    function normalizePsmAssets(uint256 assets) internal view returns (uint256) {\n        if (psmAssetDecimals == 18) {\n            return assets;\n        } else if (psmAssetDecimals > 18) {\n            return assets / (10 ** (psmAssetDecimals - 18));\n        } else {\n            return assets * (10 ** (18 - psmAssetDecimals));\n        }\n    }\n\n    /// @notice Calculates the pending interest that would be earned by vault stakers if accrueInterest() were called\n    /// @dev This is used by the Vault to include pending yield in totalAssets() for ERC-4626 compliance\n    /// @return pendingVaultInterest The amount of interest that would be minted to the vault\n    function getPendingInterest() external view returns (uint256 pendingVaultInterest) {\n        uint timeElapsed = block.timestamp - lastAccrue;\n        if(timeElapsed == 0) return 0;\n\n        uint256 gasBefore = gasleft();\n        \n        try interestModel.calculateInterest(\n            totalPaidDebt,\n            lastBorrowRateMantissa,\n            timeElapsed,\n            expRate,\n            getFreeDebtRatio(),\n            targetFreeDebtRatioStartBps,\n            targetFreeDebtRatioEndBps\n        ) returns (uint, uint interest) {\n            uint120 localReserveFee = uint120(interest * feeBps / 10000);\n            uint120 globalReserveFee = uint120(interest * cachedGlobalFeeBps / 10000);\n            // we remove reserve fees from interest before calculating how much to give to stakers\n            uint interestAfterFees = interest - localReserveFee - globalReserveFee;\n            uint totalStaked = coin.balanceOf(address(vault));\n            if(totalStaked < totalPaidDebt) { // this also implies totalPaidDebt > 0 and guards the division below\n                // if total staked is less than paid debt, giving all interest to stakers would\n                // result in higher supply rate than borrow rate which is undesirable.\n                // we cap the supply rate at the borrow rate and give the rest to local reserves.\n                uint stakedInterest = interestAfterFees * totalStaked / totalPaidDebt;\n                return stakedInterest;\n            } else {\n                // if total staked is greater than paid debt, we give all interest to stakers\n                return interestAfterFees;\n            }\n        } catch {\n            require(gasBefore >= INTEREST_CALCULATION_GAS_REQUIREMENT, \"Not enough gas for accrueInterest\");\n        }\n    }\n\n    // Setters\n\n    function setHalfLife(uint64 halfLife) external onlyOperatorOrManager beforeDeadline {\n        accrueInterest();\n        require(halfLife >= 12 hours && halfLife <= 30 days, \"Invalid half life\");\n        expRate = uint64(uint(wadLn(2*1e18)) / halfLife);\n        emit HalfLifeUpdated(halfLife);\n    }\n\n    function setTargetFreeDebtRatio(uint16 startBps, uint16 endBps) external onlyOperatorOrManager beforeDeadline {\n        accrueInterest();\n        require(startBps >= 500 && startBps <= endBps, \"Invalid start bps\");\n        require(endBps >= startBps && endBps <= 9500, \"Invalid end bps\");\n        targetFreeDebtRatioStartBps = uint16(startBps);\n        targetFreeDebtRatioEndBps = uint16(endBps);\n        emit TargetFreeDebtRatioUpdated(startBps, endBps);\n    }\n\n    function setRedeemFeeBps(uint16 _redeemFeeBps) external onlyOperatorOrManager beforeDeadline {\n        accrueInterest();\n        require(_redeemFeeBps <= 500, \"Invalid redeem fee bps\");\n        redeemFeeBps = uint16(_redeemFeeBps);\n        emit RedeemFeeBpsUpdated(_redeemFeeBps);\n    }\n\n    function setMaxBorrowDeltaBps(uint16 _maxBorrowDeltaBps) external onlyOperatorOrManager beforeDeadline {\n        require(_maxBorrowDeltaBps <= 200 && _maxBorrowDeltaBps >= 50, \"Invalid borrow delta bps\"); // Max 2%\n        maxBorrowDeltaBps = _maxBorrowDeltaBps;\n        emit MaxBorrowDeltaBpsUpdated(_maxBorrowDeltaBps);\n    }\n\n    function setLocalReserveFeeBps(uint _feeBps) external onlyOperator {\n        accrueInterest();\n        require(_feeBps <= 5000, \"Invalid fee\");\n        feeBps = uint16(_feeBps);\n        emit LocalReserveFeeUpdated(_feeBps);\n    }\n\n    function setPendingOperator(address _pendingOperator) external onlyOperator {\n        pendingOperator = _pendingOperator;\n        emit PendingOperatorUpdated(_pendingOperator);\n    }\n\n    function acceptOperator() external {\n        require(msg.sender == pendingOperator, \"Unauthorized\");\n        operator = pendingOperator;\n        pendingOperator = address(0);\n        emit OperatorAccepted(operator);\n    }\n\n    function setManager(address _manager) external onlyOperatorOrManager {\n        manager = _manager;\n        emit ManagerUpdated(_manager);\n    }\n\n    function enableImmutabilityNow() external onlyOperator beforeDeadline {\n        immutabilityDeadline = block.timestamp;\n        emit ImmutabilityEnabled(block.timestamp);\n    }\n\n    function pullLocalReserves() external {\n        accrueInterest();\n        accruePsmProfit();\n        if (accruedLocalReserves == 0) return;\n        coin.mint(operator, accruedLocalReserves);\n        emit AccruedLocalReserves(accruedLocalReserves);\n        accruedLocalReserves = 0;\n    }\n\n    function pullGlobalReserves(address _to) external returns (uint256 amount) {\n        require(msg.sender == address(factory), \"Unauthorized\");\n        accrueInterest();\n        amount = accruedGlobalReserves;\n        coin.mint(_to, amount);\n        emit AccruedGlobalReserves(amount);\n        accruedGlobalReserves = 0;\n    }\n\n    // Events\n\n    event PositionAdjusted(address indexed account, int collateralDelta, int debtDelta);\n    event HalfLifeUpdated(uint64 halfLife);\n    event TargetFreeDebtRatioUpdated(uint16 startBps, uint16 endBps);\n    event RedeemFeeBpsUpdated(uint16 redeemFeeBps);\n    event MaxBorrowDeltaBpsUpdated(uint16 maxBorrowDeltaBps);\n    event DelegationUpdated(address indexed delegator, address indexed delegatee, bool isDelegatee);\n    event PendingOperatorUpdated(address indexed pendingOperator);\n    event OperatorAccepted(address indexed operator);\n    event ManagerUpdated(address indexed manager);\n    event LocalReserveFeeUpdated(uint256 feeBps);\n    event RedemptionStatusUpdated(address indexed account, bool isRedeemable);\n    event Liquidated(address indexed borrower, address indexed liquidator, uint repayAmount, uint collateralOut);\n    event WrittenOff(address indexed borrower, address indexed to, uint debt, uint collateral);\n    event Redeemed(address indexed account, address indexed borrower, uint amountIn, uint amountOut);\n    event Sold(address indexed account, uint coinIn, uint assetOut);\n    event Bought(address indexed account, uint assetIn, uint coinOut);\n    event ImmutabilityEnabled(uint256 timestamp);\n    event AccruedLocalReserves(uint256 amount);\n    event AccruedGlobalReserves(uint256 amount);\n    event InterestAccrued(uint256 interestAccrued, uint256 newBorrowRateMantissa);\n}\n"},"src/Vault.sol":{"content":"// SPDX-License-Identifier: UNLICENSED\npragma solidity 0.8.24;\n\nimport \"lib/solmate/src/tokens/ERC4626.sol\";\n\ninterface ILender {\n    function accrueInterest() external;\n    function coin() external view returns (ERC20);\n    function getPendingInterest() external view returns (uint256 pendingVaultInterest);\n}\n\ncontract Vault is ERC4626 {\n    using SafeTransferLib for ERC20;\n    using FixedPointMathLib for uint256;\n    \n    ILender public immutable lender;\n    uint256 constant MIN_SHARES = 1e16; // 1 cent;\n\n    /// @param _name Name of the token. Prepended with \"Staked \"\n    /// @param _symbol Symbol of the token. Prepended with \"s\"\n    /// @param _lender Address of the Lender token\n    constructor(\n        string memory _name,\n        string memory _symbol,\n        address _lender\n    ) ERC4626(\n        ILender(_lender).coin(),\n        string.concat(\"Staked \", _name),\n        string.concat(\"s\", _symbol)\n    ) {\n        lender = ILender(_lender);\n    }\n\n    modifier accrueInterest() {\n        lender.accrueInterest();\n        _;\n    }\n\n    function totalAssets() public view override returns (uint256) {\n        return asset.balanceOf(address(this)) + lender.getPendingInterest();\n    }\n\n    /// @notice Deposits assets into the vault\n    /// @param assets Amount of assets to deposit\n    /// @param receiver Address to receive the shares\n    /// @return shares Amount of shares minted\n    function deposit(uint256 assets, address receiver) public accrueInterest override returns (uint256 shares) {\n        bool isFirstDeposit = totalSupply == 0;\n       \n        // Check for rounding error since we round down in previewDeposit.\n        require((shares = convertToShares(assets)) != 0, \"ZERO_SHARES\");\n\n        // Need to transfer before minting or ERC777s could reenter.\n        asset.safeTransferFrom(msg.sender, address(this), assets);\n\n        _mint(receiver, shares);\n        \n        if(isFirstDeposit) {\n                // if this underflows, the first deposit is less than MIN_SHARES which is not allowed\n                balanceOf[receiver] -= MIN_SHARES;\n                balanceOf[address(0)] += MIN_SHARES;\n                shares -= MIN_SHARES;\n                emit Transfer(receiver, address(0), MIN_SHARES);\n        }\n\n        emit Deposit(msg.sender, receiver, assets, shares);\n    }\n\n    /// @notice Mints shares of the vault\n    /// @dev Includes MIN_SHARES deduction on first deposit, meaning it will pull more assets to burn the MIN_SHARES on first deposit\n    /// @param shares Amount of shares to mint\n    /// @param receiver Address to receive the shares\n    /// @return assets Amount of assets deposited\n    function mint(uint256 shares, address receiver) public accrueInterest override returns (uint256 assets) {\n        if (shares == 0) return 0;\n        // Get the amount of assets required including amount to burn MIN_SHARES if first deposit\n        assets = previewMint(shares); \n        // Need to transfer before minting or ERC777s could reenter.\n        asset.safeTransferFrom(msg.sender, address(this), assets);\n\n        bool isFirstDeposit = totalSupply == 0;\n        \n        if(isFirstDeposit) {\n            _mint(receiver, shares + MIN_SHARES);\n            // if this underflows, the first deposit is less than MIN_SHARES which is not allowed\n            balanceOf[receiver] -= MIN_SHARES;\n            balanceOf[address(0)] += MIN_SHARES;\n            emit Transfer(receiver, address(0), MIN_SHARES);\n        } else {\n            _mint(receiver, shares);  \n        }\n\n        emit Deposit(msg.sender, receiver, assets, shares);\n    }\n\n    /// @notice Withdraws assets from the vault\n    /// @param assets Amount of assets to withdraw\n    /// @param receiver Address to receive the assets\n    /// @param owner Owner of the shares\n    /// @return shares Amount of shares burned\n    function withdraw(\n        uint256 assets,\n        address receiver,\n        address owner\n    ) public accrueInterest override returns (uint256 shares) {\n        shares = super.withdraw(assets, receiver, owner);\n    }\n\n    /// @notice Redeems shares for assets\n    /// @param shares Amount of shares to redeem\n    /// @param receiver Address to receive the assets\n    /// @param owner Owner of the shares\n    /// @return assets Amount of assets withdrawn\n    function redeem(\n        uint256 shares,\n        address receiver,\n        address owner\n    ) public accrueInterest override returns (uint256 assets) {\n        assets = super.redeem(shares, receiver, owner);\n    }\n\n    /// @notice Preview deposit to account for MIN_SHARES deduction on first deposit\n    /// @param assets Amount of assets to deposit\n    /// @return shares Amount of shares that will be minted to the user\n    function previewDeposit(uint256 assets) public view override returns (uint256 shares) {\n        shares = convertToShares(assets);\n        if (totalSupply == 0) {\n            // Avoid reverting to conforme with ERC4626 spec\n            if (shares < MIN_SHARES) {\n                shares = 0;\n            } else shares -= MIN_SHARES;\n\n        }\n    }\n\n    /// @notice Preview mint to account for MIN_SHARES deduction on first deposit\n    /// @param shares Amount of shares to mint\n    /// @return assets Amount of assets that will be deposited (accounting for MIN_SHARES on first deposit)\n    function previewMint(uint256 shares) public view override returns (uint256 assets) {\n        if (shares == 0) return 0;\n        // If this is the first deposit, we need to mint MIN_SHARES extra\n        if (totalSupply == 0) shares += MIN_SHARES;\n        \n        uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.\n\n        return supply == 0 ? shares : shares.mulDivUp(totalAssets(), supply);\n    }\n\n    /// @notice Returns the maximum assets that `owner` can withdraw right now\n    /// @dev Caps to liquid assets currently held by the vault.\n    function maxWithdraw(address owner) public view override returns (uint256) {\n        uint256 supply = totalSupply;\n        if (supply == 0) return 0;\n\n        uint256 assetsManaged = totalAssets();\n        if (assetsManaged == 0) return 0;\n\n        uint256 ownerAssets = balanceOf[owner].mulDivDown(assetsManaged, supply);\n        return ownerAssets;\n    }\n\n    /// @notice Returns the maximum shares that `owner` can redeem right now\n    function maxRedeem(address owner) public view override returns (uint256) {\n        uint256 supply = totalSupply;\n        if (supply == 0) return 0;\n\n        uint256 assetsManaged = totalAssets();\n        if (assetsManaged == 0) return 0;\n\n        uint256 ownerShares = balanceOf[owner];\n        return ownerShares;\n    }\n}\n"}},"matchId":"56913129","creationMatch":"exact_match","runtimeMatch":"exact_match","verifiedAt":"2026-10-25T03:51:39Z","match":"exact_match","chainId":"1","address":"0x4ed5c72816aBc1b67ac31DdAbE31cff4a8c56a15"}