{"sources":{"src/sInv.sol":{"content":"// SPDX-License-Identifier: MIT License\npragma solidity ^0.8.21;\n\nimport \"lib/solmate/src/tokens/ERC4626.sol\";\n\ninterface IInvEscrow {\n    function balance() external view returns (uint);\n    function claimDBR() external;\n    function claimable() external view returns (uint);\n}\n\ninterface IMarket {\n    function deposit(uint256 amount) external;\n    function withdraw(uint256 amount) external;\n    function dbr() external returns (address);\n    function escrows(address user) external returns (address);\n}\n\ninterface IERC20 {\n    function transfer(address, uint) external returns (bool);\n    function transferFrom(address, address, uint) external returns (bool);\n    function balanceOf(address) external view returns (uint);\n}\n\n/**\n * @title sINV\n * @dev Auto-compounding ERC4626 wrapper for asset FiRM deposits utilizing xy=k auctions.\n * WARNING: While this vault is safe to be used as collateral in lending markets, it should not be allowed as a borrowable asset.\n * Any protocol in which sudden, large and atomic increases in the value of an asset may be a security risk should not integrate this vault.\n */\ncontract sINV is ERC4626{\n\n    struct RevenueData {\n        uint96 periodRevenue;\n        uint96 lastPeriodRevenue;\n        uint64 lastBuyPeriod;\n    }\n\n    struct KData {\n        uint192 targetK;\n        uint64 lastKUpdate;\n    }\n    \n    uint256 public constant MIN_ASSETS = 10**16; // 1 cent\n    uint256 public constant MIN_SHARES = 10**18;\n    uint256 public constant MAX_ASSETS = 10**32; // 100 trillion asset\n    uint256 public constant period = 7 days;\n    uint256 public depositLimit;\n    IMarket public immutable invMarket;\n    IInvEscrow public immutable invEscrow;\n    ERC20 public immutable DBR;\n    RevenueData public revenueData;\n    KData public kData;\n    address public gov;\n    address public guardian;\n    address public pendingGov;\n    uint256 public minBuffer;\n    uint256 public prevK;\n\n    function periodRevenue() external view returns(uint256){return revenueData.periodRevenue;}\n    function lastPeriodRevenue() external view returns(uint256){return revenueData.lastPeriodRevenue;}\n    function lastBuyPeriod() external view returns(uint256){return revenueData.lastBuyPeriod;}\n    function targetK() external view returns(uint256){return kData.targetK;}\n    function lastKUpdate() external view returns(uint256){return kData.lastKUpdate;}\n\n    error OnlyGov();\n    error OnlyPendingGov();\n    error OnlyGuardian();\n    error KTooLow(uint k, uint limit);\n    error BelowMinShares();\n    error AboveDepositLimit();\n    error DepositLimitMustIncrease();\n    error InsufficientAssets();\n    error Invariant();\n    error UnauthorizedTokenWithdrawal();\n\n    /**\n     * @dev Constructor for sINV contract.\n     * WARNING: MIN_SHARES will always be unwithdrawable from the vault. Deployer should deposit enough to mint MIN_SHARES to avoid causing user grief.\n     * @param _inv Address of the asset token.\n     * @param _invMarket Address of the asset FiRM market.\n     * @param _gov Address of the governance.\n     * @param _K Initial value for the K variable used in calculations.\n     */\n    constructor(\n        address _inv,\n        address _invMarket,\n        address _gov,\n        address _guardian,\n        uint256 _depositLimit,\n        uint256 _K\n    ) ERC4626(ERC20(_inv), \"Staked Inv\", \"sINV\") {\n        if(_K == 0) revert KTooLow(_K, 1);\n        IMarket(_invMarket).deposit(0); //creates an escrow on behalf of the sINV contract\n        invEscrow = IInvEscrow(IMarket(_invMarket).escrows(address(this)));\n        invMarket = IMarket(_invMarket);\n        DBR = ERC20(IMarket(_invMarket).dbr());\n        gov = _gov;\n        guardian = _guardian;\n        kData.targetK = uint192(_K);\n        depositLimit = _depositLimit;\n        prevK = _K;\n        asset.approve(address(invMarket), type(uint).max);\n    }\n\n    modifier onlyGov() {\n        if(msg.sender != gov) revert OnlyGov();\n        _;\n    }\n\n    modifier onlyPendingGov() {\n        if(msg.sender != pendingGov) revert OnlyPendingGov();\n        _;\n    }\n\n    modifier onlyGuardian() {\n        if(msg.sender != guardian) revert OnlyGuardian();\n        _;\n    }\n\n    /**\n     * @dev Hook that is called after tokens are deposited into the contract.\n     */    \n    function afterDeposit(uint256, uint256) internal override {\n        if(totalSupply < MIN_SHARES) revert BelowMinShares();\n        if(totalAssets() > depositLimit) revert AboveDepositLimit();\n        uint256 invBal = asset.balanceOf(address(this));\n        if(invBal > minBuffer){\n            invMarket.deposit(invBal - minBuffer);\n        }\n    }\n\n    /**\n     * @dev Hook that is called before tokens are withdrawn from the contract.\n     * @param assets The amount of assets to withdraw.\n     * @param shares The amount of shares to withdraw\n     */\n    function beforeWithdraw(uint256 assets, uint256 shares) internal override {\n        uint256 _totalAssets = totalAssets();\n        if(_totalAssets < assets + MIN_ASSETS) revert InsufficientAssets();\n        if(totalSupply < shares + MIN_SHARES) revert BelowMinShares();\n        uint256 invBal = asset.balanceOf(address(this));\n        if(assets > invBal) {\n            uint256 withdrawAmount = assets - invBal + minBuffer;\n            if(_totalAssets < withdrawAmount){\n                invMarket.withdraw(assets - invBal);\n            } else {\n                invMarket.withdraw(withdrawAmount);\n            }\n        }\n    }\n\n    /**\n     * @dev Calculates the total assets controlled by the contract.\n     * Period revenue is distributed linearly over the following week.\n     * @return The total assets in the contract.\n     */\n    function totalAssets() public view override returns (uint) {\n        uint256 periodsSinceLastBuy = block.timestamp / period - revenueData.lastBuyPeriod;\n        uint256 _lastPeriodRevenue = revenueData.lastPeriodRevenue;\n        uint256 _periodRevenue = revenueData.periodRevenue;\n        uint256 invBal = invEscrow.balance() + asset.balanceOf(address(this));\n        if(periodsSinceLastBuy > 1){\n            return invBal < MAX_ASSETS ? invBal : MAX_ASSETS;\n        } else if(periodsSinceLastBuy == 1) {\n            _lastPeriodRevenue = _periodRevenue;\n            _periodRevenue = 0;\n        }\n        uint256 remainingLastRevenue = _lastPeriodRevenue * (period - block.timestamp % period) / period;\n        uint256 lockedRevenue = remainingLastRevenue + _periodRevenue;\n        uint256 actualAssets;\n        if(invBal > lockedRevenue){\n            actualAssets = invBal - lockedRevenue;\n        }\n        return actualAssets < MAX_ASSETS ? actualAssets : MAX_ASSETS;\n    }\n\n    function updatePeriodRevenue(uint96 newRevenue) internal {\n        uint256 currentPeriod = block.timestamp / period;\n        uint256 periodsSinceLastBuy = currentPeriod - revenueData.lastBuyPeriod;\n        if(periodsSinceLastBuy > 1){\n            revenueData.lastPeriodRevenue = 0;\n            revenueData.periodRevenue = newRevenue;\n            revenueData.lastBuyPeriod = uint64(currentPeriod);\n        } else if(periodsSinceLastBuy == 1) {\n            revenueData.lastPeriodRevenue = revenueData.periodRevenue;\n            revenueData.periodRevenue = newRevenue;\n            revenueData.lastBuyPeriod = uint64(currentPeriod);\n        } else {\n            revenueData.periodRevenue += newRevenue;\n        }\n    }\n\n    /**\n     * @dev Returns the current value of K, which is a weighted average between prevK and kData.targetK.\n     * @return The current value of K.\n     */\n    function getK() public view returns (uint) {\n        uint256 timeElapsed = block.timestamp - kData.lastKUpdate;\n        if(timeElapsed > period) {\n            return kData.targetK;\n        }\n        uint256 prevWeight = period - timeElapsed;\n        return (prevK * prevWeight + kData.targetK * timeElapsed) / period;\n    }\n\n    /**\n     * @dev Calculates the asset reserve based on the current DBR reserve.\n     * @return The calculated asset reserve.\n     */\n    function getInvReserve() public view returns (uint) {\n        return getK() / getDbrReserve();\n    }\n\n    /**\n     * @dev Calculates the asset reserve for a given DBR reserve.\n     * @param DBRReserve The DBR reserve value.\n     * @return The calculated asset reserve.\n     */\n    function getInvReserve(uint256 DBRReserve) public view returns (uint) {\n        return getK() / DBRReserve;\n    }\n\n    /**\n     * @dev Returns the current DBR reserve as the sum of DBR balance and claimable DBR\n     * @return The current DBR reserve.\n     */\n    function getDbrReserve() public view returns (uint) {\n        return DBR.balanceOf(address(this)) + invEscrow.claimable();\n    }\n\n    /**\n     * @dev Sets a new target K value.\n     * @param _K The new target K value.\n     */\n    function setTargetK(uint256 _K) external onlyGov {\n        if(_K < getDbrReserve()) revert KTooLow(_K, getDbrReserve());\n        prevK = getK();\n        kData.targetK = uint192(_K);\n        kData.lastKUpdate = uint64(block.timestamp);\n        emit SetTargetK(_K);\n    }\n\n    /**\n     * @notice Set the min buffer\n     * @dev Min buffer is the buffer of INV held by the sINV contract, which can be withdrawn much more cheaply than if they were staked\n     * @param _minBuffer The new min buffer\n     */\n    function setMinBuffer(uint256 _minBuffer) external onlyGov {\n        minBuffer = _minBuffer;\n        emit SetMinBuffer(_minBuffer);\n    }\n\n    /**\n     * @dev Allows users to buy DBR with asset.\n     * WARNING: Never expose this directly to a UI as it's likely to cause a loss unless a transaction is executed immediately.\n     * Instead use the sINVHelper function or custom smart contract code.\n     * @param exactInvIn The exact amount of asset to spend.\n     * @param exactDbrOut The exact amount of DBR to receive.\n     * @param to The address that will receive the DBR.\n     */\n    function buyDBR(uint256 exactInvIn, uint256 exactDbrOut, address to) external {\n        require(exactInvIn <= type(uint96).max, \"EXCEED UINT96\");\n        uint256 DBRBalance = DBR.balanceOf(address(this));\n        if(exactDbrOut > DBRBalance){\n            invEscrow.claimDBR();\n            DBRBalance = DBR.balanceOf(address(this));\n        } else {\n            DBRBalance += invEscrow.claimable(); \n        }\n        uint256 k = getK();\n        uint256 DBRReserve = DBRBalance - exactDbrOut;\n        uint256 invReserve = k / DBRBalance + exactInvIn;\n        if(invReserve * DBRReserve < k) revert Invariant();\n        updatePeriodRevenue(uint96(exactInvIn));\n        asset.transferFrom(msg.sender, address(this), exactInvIn);\n        DBR.transfer(to, exactDbrOut);\n        emit Buy(msg.sender, to, exactInvIn, exactDbrOut);\n    }\n\n    /**\n     * @notice Sets a new depositLimit. Only callable by guardian.\n     * @dev Deposit limit must always increase\n     * @param _depositLimit The new deposit limit\n     */\n    function setDepositLimit(uint _depositLimit) external onlyGuardian {\n        depositLimit = _depositLimit;\n    }\n\n    /**\n     * @notice Sets the guardian that can increase the deposit limit. Only callable by governance.\n     * @param _guardian The new guardian.\n     */\n    function setGuardian(address _guardian) external onlyGov {\n        guardian = _guardian;\n    }\n\n    /**\n     * @dev Sets a new pending governance address.\n     * @param _gov The address of the new pending governance.\n     */\n    function setPendingGov(address _gov) external onlyGov {\n        pendingGov = _gov;\n    }\n\n    /**\n     * @dev Allows the pending governance to accept its role.\n     */\n    function acceptGov() external onlyPendingGov {\n        gov = pendingGov;\n        pendingGov = address(0);\n    }\n\n    /**\n     * @dev Allows governance to sweep any ERC20 token from the contract.\n     * @dev Excludes the ability to sweep DBR tokens.\n     * @param token The address of the ERC20 token to sweep.\n     * @param amount The amount of tokens to sweep.\n     * @param to The recipient address of the swept tokens.\n     */\n    function sweep(address token, uint256 amount, address to) public onlyGov {\n        if(address(DBR) == token ||\n            address(asset) == token)\n            revert UnauthorizedTokenWithdrawal();\n        IERC20(token).transfer(to, amount);\n    }\n    \n    /**\n     * @notice Allows anyone to reapprove inv spending for invMarket\n     */\n    function reapprove() external {\n        asset.approve(address(invMarket), type(uint).max);\n    }\n    \n\n    event Buy(address indexed caller, address indexed to, uint256 exactInvIn, uint256 exactDbrOut);\n    event SetTargetK(uint256 newTargetK);\n    event SetMinBuffer(uint256 newMinBuffer);\n}\n"},"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/SafeTransferLib.sol":{"content":"// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity >=0.8.0;\n\nimport {ERC20} from \"../tokens/ERC20.sol\";\n\n/// @notice Safe ETH and ERC20 transfer library that gracefully handles missing return values.\n/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/SafeTransferLib.sol)\n/// @dev Use with caution! Some functions in this library knowingly create dirty bits at the destination of the free memory pointer.\n/// @dev Note that none of the functions in this library check that a token has code at all! That responsibility is delegated to the caller.\nlibrary SafeTransferLib {\n    /*//////////////////////////////////////////////////////////////\n                             ETH OPERATIONS\n    //////////////////////////////////////////////////////////////*/\n\n    function safeTransferETH(address to, uint256 amount) internal {\n        bool success;\n\n        /// @solidity memory-safe-assembly\n        assembly {\n            // Transfer the ETH and store if it succeeded or not.\n            success := call(gas(), to, amount, 0, 0, 0, 0)\n        }\n\n        require(success, \"ETH_TRANSFER_FAILED\");\n    }\n\n    /*//////////////////////////////////////////////////////////////\n                            ERC20 OPERATIONS\n    //////////////////////////////////////////////////////////////*/\n\n    function safeTransferFrom(\n        ERC20 token,\n        address from,\n        address to,\n        uint256 amount\n    ) internal {\n        bool success;\n\n        /// @solidity memory-safe-assembly\n        assembly {\n            // Get a pointer to some free memory.\n            let freeMemoryPointer := mload(0x40)\n\n            // Write the abi-encoded calldata into memory, beginning with the function selector.\n            mstore(freeMemoryPointer, 0x23b872dd00000000000000000000000000000000000000000000000000000000)\n            mstore(add(freeMemoryPointer, 4), 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            success := and(\n                // Set success to whether the call reverted, if not we check it either\n                // returned exactly 1 (can't just be non-zero data), or had no return data.\n                or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),\n                // We use 100 because the length of our calldata totals up like so: 4 + 32 * 3.\n                // We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.\n                // Counterintuitively, this call must be positioned second to the or() call in the\n                // surrounding and() call or else returndatasize() will be zero during the computation.\n                call(gas(), token, 0, freeMemoryPointer, 100, 0, 32)\n            )\n        }\n\n        require(success, \"TRANSFER_FROM_FAILED\");\n    }\n\n    function safeTransfer(\n        ERC20 token,\n        address to,\n        uint256 amount\n    ) internal {\n        bool success;\n\n        /// @solidity memory-safe-assembly\n        assembly {\n            // Get a pointer to some free memory.\n            let freeMemoryPointer := mload(0x40)\n\n            // Write the abi-encoded calldata into memory, beginning with the function selector.\n            mstore(freeMemoryPointer, 0xa9059cbb00000000000000000000000000000000000000000000000000000000)\n            mstore(add(freeMemoryPointer, 4), 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            success := and(\n                // Set success to whether the call reverted, if not we check it either\n                // returned exactly 1 (can't just be non-zero data), or had no return data.\n                or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),\n                // We use 68 because the length of our calldata totals up like so: 4 + 32 * 2.\n                // We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.\n                // Counterintuitively, this call must be positioned second to the or() call in the\n                // surrounding and() call or else returndatasize() will be zero during the computation.\n                call(gas(), token, 0, freeMemoryPointer, 68, 0, 32)\n            )\n        }\n\n        require(success, \"TRANSFER_FAILED\");\n    }\n\n    function safeApprove(\n        ERC20 token,\n        address to,\n        uint256 amount\n    ) internal {\n        bool success;\n\n        /// @solidity memory-safe-assembly\n        assembly {\n            // Get a pointer to some free memory.\n            let freeMemoryPointer := mload(0x40)\n\n            // Write the abi-encoded calldata into memory, beginning with the function selector.\n            mstore(freeMemoryPointer, 0x095ea7b300000000000000000000000000000000000000000000000000000000)\n            mstore(add(freeMemoryPointer, 4), 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            success := and(\n                // Set success to whether the call reverted, if not we check it either\n                // returned exactly 1 (can't just be non-zero data), or had no return data.\n                or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),\n                // We use 68 because the length of our calldata totals up like so: 4 + 32 * 2.\n                // We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.\n                // Counterintuitively, this call must be positioned second to the or() call in the\n                // surrounding and() call or else returndatasize() will be zero during the computation.\n                call(gas(), token, 0, freeMemoryPointer, 68, 0, 32)\n            )\n        }\n\n        require(success, \"APPROVE_FAILED\");\n    }\n}\n"},"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"}},"matchId":"5388233","creationMatch":"exact_match","runtimeMatch":"exact_match","verifiedAt":"2024-09-18T08:16:21Z","match":"exact_match","chainId":"1","address":"0x08d23468A467d2bb86FaE0e32F247A26C7E2e994"}