{"constructor_args":null,"is_partially_verified":true,"is_changed_bytecode":false,"abi":[{"inputs":[],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"EnforcedPause","type":"error"},{"inputs":[],"name":"ExpectedPause","type":"error"},{"inputs":[{"internalType":"address","name":"_recipient","type":"address"}],"name":"PerformanceFeeRecipientIsZeroAddress","type":"error"},{"inputs":[{"internalType":"uint256","name":"_percent","type":"uint256"}],"name":"PerformanceFeeTooHigh","type":"error"},{"inputs":[],"name":"StakedTokenNotAvailable","type":"error"},{"inputs":[{"internalType":"uint256","name":"_ratio","type":"uint256"}],"name":"TargetIlliquidRatioTooHigh","type":"error"},{"inputs":[{"internalType":"bytes","name":"returnData","type":"bytes"}],"name":"UnderlyingCallReverted","type":"error"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"oldCore","type":"address"},{"indexed":true,"internalType":"address","name":"newCore","type":"address"}],"name":"CoreUpdate","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"timestamp","type":"uint256"},{"indexed":false,"internalType":"address","name":"recipient","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"ExcessSafetyBufferFlushed","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"timestamp","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"duration","type":"uint256"}],"name":"InterpolationDurationUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"timestamp","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"multiplier","type":"uint256"}],"name":"LiquidMultiplierUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"account","type":"address"}],"name":"Paused","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"timestamp","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"percentage","type":"uint256"},{"indexed":false,"internalType":"address","name":"recipient","type":"address"}],"name":"PerformanceFeeSettingsUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"timestamp","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"}],"name":"SafetyBufferSizeUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"timestamp","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"multiplier","type":"uint256"}],"name":"TargetIlliquidRatioUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"account","type":"address"}],"name":"Unpaused","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"timestamp","type":"uint256"},{"indexed":false,"internalType":"int256","name":"yield","type":"int256"}],"name":"YieldAccrued","type":"event"},{"inputs":[],"name":"MAX_PERFORMANCE_FEE","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"accounting","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"accrue","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"canEnterOrExitStakedToken","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"core","outputs":[{"internalType":"contract InfiniFiCore","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"distributeInterpolationRewards","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"address","name":"target","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"},{"internalType":"bytes","name":"callData","type":"bytes"}],"internalType":"struct CoreControlled.Call[]","name":"calls","type":"tuple[]"}],"name":"emergencyAction","outputs":[{"internalType":"bytes[]","name":"returnData","type":"bytes[]"}],"stateMutability":"payable","type":"function"},{"inputs":[],"name":"escrow","outputs":[{"internalType":"contract YieldVestingEscrow","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_recipient","type":"address"},{"internalType":"uint256","name":"_maxFlushAmount","type":"uint256"}],"name":"flushExcessSafetyBuffer","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"getCachedStakedReceiptTokens","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_core","type":"address"},{"internalType":"address","name":"_accounting","type":"address"},{"internalType":"address","name":"_receiptToken","type":"address"},{"internalType":"address","name":"_stakedToken","type":"address"},{"internalType":"address","name":"_lockingModule","type":"address"},{"internalType":"address","name":"_escrow","type":"address"}],"name":"initialize","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"interpolationDuration","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"liquidReturnMultiplier","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"lockingModule","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_source","type":"address"}],"name":"migrateSafetyBuffer","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"pause","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"paused","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"performanceFee","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"performanceFeeRecipient","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"point","outputs":[{"internalType":"uint32","name":"lastAccrued","type":"uint32"},{"internalType":"uint32","name":"lastClaimed","type":"uint32"},{"internalType":"uint208","name":"rate","type":"uint208"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"receiptToken","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"safetyBufferSize","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bool","name":"_value","type":"bool"}],"name":"setCanEnterOrExitStakedToken","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newCore","type":"address"}],"name":"setCore","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_duration","type":"uint256"}],"name":"setInterpolationDuration","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_multiplier","type":"uint256"}],"name":"setLiquidReturnMultiplier","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_percent","type":"uint256"},{"internalType":"address","name":"_recipient","type":"address"}],"name":"setPerformanceFeeAndRecipient","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_safetyBufferSize","type":"uint256"}],"name":"setSafetyBufferSize","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_ratio","type":"uint256"}],"name":"setTargetIlliquidRatio","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"stakedReceiptTokenCache","outputs":[{"internalType":"uint48","name":"blockTimestamp","type":"uint48"},{"internalType":"uint208","name":"amount","type":"uint208"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"stakedToken","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"targetIlliquidRatio","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"unaccruedYield","outputs":[{"internalType":"int256","name":"","type":"int256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"unpause","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"vested","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"vesting","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"}],"conflicting_implementations":null,"certified":false,"additional_sources":[{"file_path":"src/core/CoreControlled.sol","source_code":"// SPDX-License-Identifier: MIT\npragma solidity 0.8.28;\n\nimport {Pausable} from \"@openzeppelin/contracts/utils/Pausable.sol\";\nimport {CoreRoles} from \"@libraries/CoreRoles.sol\";\nimport {InfiniFiCore} from \"@core/InfiniFiCore.sol\";\n\n/// @notice Defines some modifiers and utilities around interacting with Core\nabstract contract CoreControlled is Pausable {\n    error UnderlyingCallReverted(bytes returnData);\n\n    /// @notice emitted when the reference to core is updated\n    event CoreUpdate(address indexed oldCore, address indexed newCore);\n\n    /// @notice reference to Core\n    InfiniFiCore private _core;\n\n    constructor(address coreAddress) {\n        _core = InfiniFiCore(coreAddress);\n    }\n\n    /// @notice named onlyCoreRole to prevent collision with OZ onlyRole modifier\n    modifier onlyCoreRole(bytes32 role) {\n        require(_core.hasRole(role, msg.sender), \"UNAUTHORIZED\");\n        _;\n    }\n\n    /// @notice address of the Core contract referenced\n    function core() public view returns (InfiniFiCore) {\n        return _core;\n    }\n\n    /// @notice WARNING CALLING THIS FUNCTION CAN POTENTIALLY\n    /// BRICK A CONTRACT IF CORE IS SET INCORRECTLY\n    /// @notice set new reference to core\n    /// only callable by governor\n    /// @param newCore to reference\n    function setCore(address newCore) external onlyCoreRole(CoreRoles.GOVERNOR) {\n        _setCore(newCore);\n    }\n\n    /// @notice WARNING CALLING THIS FUNCTION CAN POTENTIALLY\n    /// BRICK A CONTRACT IF CORE IS SET INCORRECTLY\n    /// @notice set new reference to core\n    /// @param newCore to reference\n    function _setCore(address newCore) internal {\n        address oldCore = address(_core);\n        _core = InfiniFiCore(newCore);\n\n        emit CoreUpdate(oldCore, newCore);\n    }\n\n    /// @notice set pausable methods to paused\n    function pause() public onlyCoreRole(CoreRoles.PAUSE) {\n        _pause();\n    }\n\n    /// @notice set pausable methods to unpaused\n    function unpause() public onlyCoreRole(CoreRoles.UNPAUSE) {\n        _unpause();\n    }\n\n    /// ------------------------------------------\n    /// ------------ Emergency Action ------------\n    /// ------------------------------------------\n\n    /// inspired by MakerDAO Multicall:\n    /// https://github.com/makerdao/multicall/blob/master/src/Multicall.sol\n\n    /// @notice struct to pack calldata and targets for an emergency action\n    struct Call {\n        /// @notice target address to call\n        address target;\n        /// @notice amount of eth to send with the call\n        uint256 value;\n        /// @notice payload to send to target\n        bytes callData;\n    }\n\n    /// @notice due to inflexibility of current smart contracts,\n    /// add this ability to be able to execute arbitrary calldata\n    /// against arbitrary addresses.\n    /// callable only by governor\n    function emergencyAction(Call[] calldata calls)\n        external\n        payable\n        virtual\n        onlyCoreRole(CoreRoles.GOVERNOR)\n        returns (bytes[] memory returnData)\n    {\n        returnData = new bytes[](calls.length);\n        for (uint256 i = 0; i < calls.length; i++) {\n            address payable target = payable(calls[i].target);\n            uint256 value = calls[i].value;\n            bytes calldata callData = calls[i].callData;\n\n            (bool success, bytes memory returned) = target.call{value: value}(callData);\n            require(success, UnderlyingCallReverted(returned));\n            returnData[i] = returned;\n        }\n    }\n}\n"},{"file_path":"src/tokens/ReceiptToken.sol","source_code":"// SPDX-License-Identifier: MIT\npragma solidity 0.8.28;\n\nimport {ERC20} from \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\nimport {CoreRoles} from \"@libraries/CoreRoles.sol\";\nimport {ERC20Permit} from \"@openzeppelin/contracts/token/ERC20/extensions/ERC20Permit.sol\";\nimport {ERC20Burnable} from \"@openzeppelin/contracts/token/ERC20/extensions/ERC20Burnable.sol\";\nimport {CoreControlled} from \"@core/CoreControlled.sol\";\n\n/// @notice InfiniFi Receipt Token.\ncontract ReceiptToken is CoreControlled, ERC20Permit, ERC20Burnable {\n    constructor(address _core, string memory _name, string memory _symbol)\n        CoreControlled(_core)\n        ERC20(_name, _symbol)\n        ERC20Permit(_name)\n    {}\n\n    /// ---------------------------------------------------------------------------\n    /// Supply management\n    /// ---------------------------------------------------------------------------\n\n    function mint(address _to, uint256 _amount) external onlyCoreRole(CoreRoles.RECEIPT_TOKEN_MINTER) {\n        _mint(_to, _amount);\n    }\n\n    function burn(uint256 _value) public override onlyCoreRole(CoreRoles.RECEIPT_TOKEN_BURNER) {\n        _burn(_msgSender(), _value);\n    }\n\n    function burnFrom(address _account, uint256 _value) public override onlyCoreRole(CoreRoles.RECEIPT_TOKEN_BURNER) {\n        _spendAllowance(_account, _msgSender(), _value);\n        _burn(_account, _value);\n    }\n}\n"},{"file_path":"lib/openzeppelin-contracts/contracts/access/extensions/AccessControlEnumerable.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.5.0) (access/extensions/AccessControlEnumerable.sol)\n\npragma solidity ^0.8.24;\n\nimport {IAccessControlEnumerable} from \"./IAccessControlEnumerable.sol\";\nimport {AccessControl} from \"../AccessControl.sol\";\nimport {EnumerableSet} from \"../../utils/structs/EnumerableSet.sol\";\nimport {IERC165} from \"../../utils/introspection/ERC165.sol\";\n\n/**\n * @dev Extension of {AccessControl} that allows enumerating the members of each role.\n */\nabstract contract AccessControlEnumerable is IAccessControlEnumerable, AccessControl {\n    using EnumerableSet for EnumerableSet.AddressSet;\n\n    mapping(bytes32 role => EnumerableSet.AddressSet) private _roleMembers;\n\n    /// @inheritdoc IERC165\n    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n        return interfaceId == type(IAccessControlEnumerable).interfaceId || super.supportsInterface(interfaceId);\n    }\n\n    /**\n     * @dev Returns one of the accounts that have `role`. `index` must be a\n     * value between 0 and {getRoleMemberCount}, non-inclusive.\n     *\n     * Role bearers are not sorted in any particular way, and their ordering may\n     * change at any point.\n     *\n     * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure\n     * you perform all queries on the same block. See the following\n     * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]\n     * for more information.\n     */\n    function getRoleMember(bytes32 role, uint256 index) public view virtual returns (address) {\n        return _roleMembers[role].at(index);\n    }\n\n    /**\n     * @dev Returns the number of accounts that have `role`. Can be used\n     * together with {getRoleMember} to enumerate all bearers of a role.\n     */\n    function getRoleMemberCount(bytes32 role) public view virtual returns (uint256) {\n        return _roleMembers[role].length();\n    }\n\n    /**\n     * @dev Return all accounts that have `role`\n     *\n     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\n     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\n     * this function has an unbounded cost, and using it as part of a state-changing function may render the function\n     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\n     */\n    function getRoleMembers(bytes32 role) public view virtual returns (address[] memory) {\n        return _roleMembers[role].values();\n    }\n\n    /**\n     * @dev Overload {AccessControl-_grantRole} to track enumerable memberships\n     */\n    function _grantRole(bytes32 role, address account) internal virtual override returns (bool) {\n        bool granted = super._grantRole(role, account);\n        if (granted) {\n            _roleMembers[role].add(account);\n        }\n        return granted;\n    }\n\n    /**\n     * @dev Overload {AccessControl-_revokeRole} to track enumerable memberships\n     */\n    function _revokeRole(bytes32 role, address account) internal virtual override returns (bool) {\n        bool revoked = super._revokeRole(role, account);\n        if (revoked) {\n            _roleMembers[role].remove(account);\n        }\n        return revoked;\n    }\n}\n"},{"file_path":"src/interfaces/IOracle.sol","source_code":"// SPDX-License-Identifier: MIT\npragma solidity 0.8.28;\n\ninterface IOracle {\n    /// @notice price of a token expressed in a reference token.\n    /// @dev be mindful of the decimals here, because if quote token\n    /// doesn't have 18 decimals, value is used to scale the decimals.\n    /// For example, for USDC quote (6 decimals) expressed in\n    /// DAI reference (18 decimals), value should be around ~1e30,\n    /// so that price is:\n    /// 1e6 * 1e30 / WAD (1e18)\n    /// ~= WAD (1e18)\n    /// ~= 1:1\n    function price() external view returns (uint256);\n}\n"},{"file_path":"lib/openzeppelin-contracts/contracts/interfaces/IERC4626.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.5.0) (interfaces/IERC4626.sol)\n\npragma solidity >=0.6.2;\n\nimport {IERC20} from \"../token/ERC20/IERC20.sol\";\nimport {IERC20Metadata} from \"../token/ERC20/extensions/IERC20Metadata.sol\";\n\n/**\n * @dev Interface of the ERC-4626 \"Tokenized Vault Standard\", as defined in\n * https://eips.ethereum.org/EIPS/eip-4626[ERC-4626].\n */\ninterface IERC4626 is IERC20, IERC20Metadata {\n    event Deposit(address indexed sender, address indexed owner, uint256 assets, uint256 shares);\n\n    event Withdraw(\n        address indexed sender,\n        address indexed receiver,\n        address indexed owner,\n        uint256 assets,\n        uint256 shares\n    );\n\n    /**\n     * @dev Returns the address of the underlying token used for the Vault for accounting, depositing, and withdrawing.\n     *\n     * - MUST be an ERC-20 token contract.\n     * - MUST NOT revert.\n     */\n    function asset() external view returns (address assetTokenAddress);\n\n    /**\n     * @dev Returns the total amount of the underlying asset that is “managed” by Vault.\n     *\n     * - SHOULD include any compounding that occurs from yield.\n     * - MUST be inclusive of any fees that are charged against assets in the Vault.\n     * - MUST NOT revert.\n     */\n    function totalAssets() external view returns (uint256 totalManagedAssets);\n\n    /**\n     * @dev Returns the amount of shares that the Vault would exchange for the amount of assets provided, in an ideal\n     * scenario where all the conditions are met.\n     *\n     * - MUST NOT be inclusive of any fees that are charged against assets in the Vault.\n     * - MUST NOT show any variations depending on the caller.\n     * - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.\n     * - MUST NOT revert.\n     *\n     * NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the\n     * “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and\n     * from.\n     */\n    function convertToShares(uint256 assets) external view returns (uint256 shares);\n\n    /**\n     * @dev Returns the amount of assets that the Vault would exchange for the amount of shares provided, in an ideal\n     * scenario where all the conditions are met.\n     *\n     * - MUST NOT be inclusive of any fees that are charged against assets in the Vault.\n     * - MUST NOT show any variations depending on the caller.\n     * - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.\n     * - MUST NOT revert.\n     *\n     * NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the\n     * “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and\n     * from.\n     */\n    function convertToAssets(uint256 shares) external view returns (uint256 assets);\n\n    /**\n     * @dev Returns the maximum amount of the underlying asset that can be deposited into the Vault for the receiver,\n     * through a deposit call.\n     *\n     * - MUST return a limited value if receiver is subject to some deposit limit.\n     * - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of assets that may be deposited.\n     * - MUST NOT revert.\n     */\n    function maxDeposit(address receiver) external view returns (uint256 maxAssets);\n\n    /**\n     * @dev Allows an on-chain or off-chain user to simulate the effects of their deposit at the current block, given\n     * current on-chain conditions.\n     *\n     * - MUST return as close to and no more than the exact amount of Vault shares that would be minted in a deposit\n     *   call in the same transaction. I.e. deposit should return the same or more shares as previewDeposit if called\n     *   in the same transaction.\n     * - MUST NOT account for deposit limits like those returned from maxDeposit and should always act as though the\n     *   deposit would be accepted, regardless if the user has enough tokens approved, etc.\n     * - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.\n     * - MUST NOT revert.\n     *\n     * NOTE: any unfavorable discrepancy between convertToShares and previewDeposit SHOULD be considered slippage in\n     * share price or some other type of condition, meaning the depositor will lose assets by depositing.\n     */\n    function previewDeposit(uint256 assets) external view returns (uint256 shares);\n\n    /**\n     * @dev Deposit `assets` underlying tokens and send the corresponding number of vault shares (`shares`) to `receiver`.\n     *\n     * - MUST emit the Deposit event.\n     * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the\n     *   deposit execution, and are accounted for during deposit.\n     * - MUST revert if all of assets cannot be deposited (due to deposit limit being reached, slippage, the user not\n     *   approving enough underlying tokens to the Vault contract, etc).\n     *\n     * NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.\n     */\n    function deposit(uint256 assets, address receiver) external returns (uint256 shares);\n\n    /**\n     * @dev Returns the maximum amount of the Vault shares that can be minted for the receiver, through a mint call.\n     * - MUST return a limited value if receiver is subject to some mint limit.\n     * - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of shares that may be minted.\n     * - MUST NOT revert.\n     */\n    function maxMint(address receiver) external view returns (uint256 maxShares);\n\n    /**\n     * @dev Allows an on-chain or off-chain user to simulate the effects of their mint at the current block, given\n     * current on-chain conditions.\n     *\n     * - MUST return as close to and no fewer than the exact amount of assets that would be deposited in a mint call\n     *   in the same transaction. I.e. mint should return the same or fewer assets as previewMint if called in the\n     *   same transaction.\n     * - MUST NOT account for mint limits like those returned from maxMint and should always act as though the mint\n     *   would be accepted, regardless if the user has enough tokens approved, etc.\n     * - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.\n     * - MUST NOT revert.\n     *\n     * NOTE: any unfavorable discrepancy between convertToAssets and previewMint SHOULD be considered slippage in\n     * share price or some other type of condition, meaning the depositor will lose assets by minting.\n     */\n    function previewMint(uint256 shares) external view returns (uint256 assets);\n\n    /**\n     * @dev Mints exactly `shares` vault shares to `receiver` in exchange for `assets` underlying tokens.\n     *\n     * - MUST emit the Deposit event.\n     * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the mint\n     *   execution, and are accounted for during mint.\n     * - MUST revert if all of shares cannot be minted (due to deposit limit being reached, slippage, the user not\n     *   approving enough underlying tokens to the Vault contract, etc).\n     *\n     * NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.\n     */\n    function mint(uint256 shares, address receiver) external returns (uint256 assets);\n\n    /**\n     * @dev Returns the maximum amount of the underlying asset that can be withdrawn from the owner balance in the\n     * Vault, through a withdraw call.\n     *\n     * - MUST return a limited value if owner is subject to some withdrawal limit or timelock.\n     * - MUST NOT revert.\n     */\n    function maxWithdraw(address owner) external view returns (uint256 maxAssets);\n\n    /**\n     * @dev Allows an on-chain or off-chain user to simulate the effects of their withdrawal at the current block,\n     * given current on-chain conditions.\n     *\n     * - MUST return as close to and no fewer than the exact amount of Vault shares that would be burned in a withdraw\n     *   call in the same transaction. I.e. withdraw should return the same or fewer shares as previewWithdraw if\n     *   called\n     *   in the same transaction.\n     * - MUST NOT account for withdrawal limits like those returned from maxWithdraw and should always act as though\n     *   the withdrawal would be accepted, regardless if the user has enough shares, etc.\n     * - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.\n     * - MUST NOT revert.\n     *\n     * NOTE: any unfavorable discrepancy between convertToShares and previewWithdraw SHOULD be considered slippage in\n     * share price or some other type of condition, meaning the depositor will lose assets by depositing.\n     */\n    function previewWithdraw(uint256 assets) external view returns (uint256 shares);\n\n    /**\n     * @dev Burns shares from owner and sends exactly assets of underlying tokens to receiver.\n     *\n     * - MUST emit the Withdraw event.\n     * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the\n     *   withdraw execution, and are accounted for during withdraw.\n     * - MUST revert if all of assets cannot be withdrawn (due to withdrawal limit being reached, slippage, the owner\n     *   not having enough shares, etc).\n     *\n     * Note that some implementations will require pre-requesting to the Vault before a withdrawal may be performed.\n     * Those methods should be performed separately.\n     */\n    function withdraw(uint256 assets, address receiver, address owner) external returns (uint256 shares);\n\n    /**\n     * @dev Returns the maximum amount of Vault shares that can be redeemed from the owner balance in the Vault,\n     * through a redeem call.\n     *\n     * - MUST return a limited value if owner is subject to some withdrawal limit or timelock.\n     * - MUST return balanceOf(owner) if owner is not subject to any withdrawal limit or timelock.\n     * - MUST NOT revert.\n     */\n    function maxRedeem(address owner) external view returns (uint256 maxShares);\n\n    /**\n     * @dev Allows an on-chain or off-chain user to simulate the effects of their redemption at the current block,\n     * given current on-chain conditions.\n     *\n     * - MUST return as close to and no more than the exact amount of assets that would be withdrawn in a redeem call\n     *   in the same transaction. I.e. redeem should return the same or more assets as previewRedeem if called in the\n     *   same transaction.\n     * - MUST NOT account for redemption limits like those returned from maxRedeem and should always act as though the\n     *   redemption would be accepted, regardless if the user has enough shares, etc.\n     * - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.\n     * - MUST NOT revert.\n     *\n     * NOTE: any unfavorable discrepancy between convertToAssets and previewRedeem SHOULD be considered slippage in\n     * share price or some other type of condition, meaning the depositor will lose assets by redeeming.\n     */\n    function previewRedeem(uint256 shares) external view returns (uint256 assets);\n\n    /**\n     * @dev Burns exactly shares from owner and sends assets of underlying tokens to receiver.\n     *\n     * - MUST emit the Withdraw event.\n     * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the\n     *   redeem execution, and are accounted for during redeem.\n     * - MUST revert if all of shares cannot be redeemed (due to withdrawal limit being reached, slippage, the owner\n     *   not having enough shares, etc).\n     *\n     * NOTE: some implementations will require pre-requesting to the Vault before a withdrawal may be performed.\n     * Those methods should be performed separately.\n     */\n    function redeem(uint256 shares, address receiver, address owner) external returns (uint256 assets);\n}\n"},{"file_path":"lib/openzeppelin-contracts/contracts/utils/math/Math.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.5.0) (utils/math/Math.sol)\n\npragma solidity ^0.8.20;\n\nimport {Panic} from \"../Panic.sol\";\nimport {SafeCast} from \"./SafeCast.sol\";\n\n/**\n * @dev Standard math utilities missing in the Solidity language.\n */\nlibrary Math {\n    enum Rounding {\n        Floor, // Toward negative infinity\n        Ceil, // Toward positive infinity\n        Trunc, // Toward zero\n        Expand // Away from zero\n    }\n\n    /**\n     * @dev Return the 512-bit addition of two uint256.\n     *\n     * The result is stored in two 256 variables such that sum = high * 2²⁵⁶ + low.\n     */\n    function add512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {\n        assembly (\"memory-safe\") {\n            low := add(a, b)\n            high := lt(low, a)\n        }\n    }\n\n    /**\n     * @dev Return the 512-bit multiplication of two uint256.\n     *\n     * The result is stored in two 256 variables such that product = high * 2²⁵⁶ + low.\n     */\n    function mul512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {\n        // 512-bit multiply [high low] = x * y. Compute the product mod 2²⁵⁶ and mod 2²⁵⁶ - 1, then use\n        // the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256\n        // variables such that product = high * 2²⁵⁶ + low.\n        assembly (\"memory-safe\") {\n            let mm := mulmod(a, b, not(0))\n            low := mul(a, b)\n            high := sub(sub(mm, low), lt(mm, low))\n        }\n    }\n\n    /**\n     * @dev Returns the addition of two unsigned integers, with a success flag (no overflow).\n     */\n    function tryAdd(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {\n        unchecked {\n            uint256 c = a + b;\n            success = c >= a;\n            result = c * SafeCast.toUint(success);\n        }\n    }\n\n    /**\n     * @dev Returns the subtraction of two unsigned integers, with a success flag (no overflow).\n     */\n    function trySub(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {\n        unchecked {\n            uint256 c = a - b;\n            success = c <= a;\n            result = c * SafeCast.toUint(success);\n        }\n    }\n\n    /**\n     * @dev Returns the multiplication of two unsigned integers, with a success flag (no overflow).\n     */\n    function tryMul(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {\n        unchecked {\n            uint256 c = a * b;\n            assembly (\"memory-safe\") {\n                // Only true when the multiplication doesn't overflow\n                // (c / a == b) || (a == 0)\n                success := or(eq(div(c, a), b), iszero(a))\n            }\n            // equivalent to: success ? c : 0\n            result = c * SafeCast.toUint(success);\n        }\n    }\n\n    /**\n     * @dev Returns the division of two unsigned integers, with a success flag (no division by zero).\n     */\n    function tryDiv(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {\n        unchecked {\n            success = b > 0;\n            assembly (\"memory-safe\") {\n                // The `DIV` opcode returns zero when the denominator is 0.\n                result := div(a, b)\n            }\n        }\n    }\n\n    /**\n     * @dev Returns the remainder of dividing two unsigned integers, with a success flag (no division by zero).\n     */\n    function tryMod(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {\n        unchecked {\n            success = b > 0;\n            assembly (\"memory-safe\") {\n                // The `MOD` opcode returns zero when the denominator is 0.\n                result := mod(a, b)\n            }\n        }\n    }\n\n    /**\n     * @dev Unsigned saturating addition, bounds to `2²⁵⁶ - 1` instead of overflowing.\n     */\n    function saturatingAdd(uint256 a, uint256 b) internal pure returns (uint256) {\n        (bool success, uint256 result) = tryAdd(a, b);\n        return ternary(success, result, type(uint256).max);\n    }\n\n    /**\n     * @dev Unsigned saturating subtraction, bounds to zero instead of overflowing.\n     */\n    function saturatingSub(uint256 a, uint256 b) internal pure returns (uint256) {\n        (, uint256 result) = trySub(a, b);\n        return result;\n    }\n\n    /**\n     * @dev Unsigned saturating multiplication, bounds to `2²⁵⁶ - 1` instead of overflowing.\n     */\n    function saturatingMul(uint256 a, uint256 b) internal pure returns (uint256) {\n        (bool success, uint256 result) = tryMul(a, b);\n        return ternary(success, result, type(uint256).max);\n    }\n\n    /**\n     * @dev Branchless ternary evaluation for `condition ? a : b`. Gas costs are constant.\n     *\n     * IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.\n     * However, the compiler may optimize Solidity ternary operations (i.e. `condition ? a : b`) to only compute\n     * one branch when needed, making this function more expensive.\n     */\n    function ternary(bool condition, uint256 a, uint256 b) internal pure returns (uint256) {\n        unchecked {\n            // branchless ternary works because:\n            // b ^ (a ^ b) == a\n            // b ^ 0 == b\n            return b ^ ((a ^ b) * SafeCast.toUint(condition));\n        }\n    }\n\n    /**\n     * @dev Returns the largest of two numbers.\n     */\n    function max(uint256 a, uint256 b) internal pure returns (uint256) {\n        return ternary(a > b, a, b);\n    }\n\n    /**\n     * @dev Returns the smallest of two numbers.\n     */\n    function min(uint256 a, uint256 b) internal pure returns (uint256) {\n        return ternary(a < b, a, b);\n    }\n\n    /**\n     * @dev Returns the average of two numbers. The result is rounded towards\n     * zero.\n     */\n    function average(uint256 a, uint256 b) internal pure returns (uint256) {\n        unchecked {\n            // (a + b) / 2 can overflow.\n            return (a & b) + (a ^ b) / 2;\n        }\n    }\n\n    /**\n     * @dev Returns the ceiling of the division of two numbers.\n     *\n     * This differs from standard division with `/` in that it rounds towards infinity instead\n     * of rounding towards zero.\n     */\n    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {\n        if (b == 0) {\n            // Guarantee the same behavior as in a regular Solidity division.\n            Panic.panic(Panic.DIVISION_BY_ZERO);\n        }\n\n        // The following calculation ensures accurate ceiling division without overflow.\n        // Since a is non-zero, (a - 1) / b will not overflow.\n        // The largest possible result occurs when (a - 1) / b is type(uint256).max,\n        // but the largest value we can obtain is type(uint256).max - 1, which happens\n        // when a = type(uint256).max and b = 1.\n        unchecked {\n            return SafeCast.toUint(a > 0) * ((a - 1) / b + 1);\n        }\n    }\n\n    /**\n     * @dev Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or\n     * denominator == 0.\n     *\n     * Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by\n     * Uniswap Labs also under MIT license.\n     */\n    function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {\n        unchecked {\n            (uint256 high, uint256 low) = mul512(x, y);\n\n            // Handle non-overflow cases, 256 by 256 division.\n            if (high == 0) {\n                // Solidity will revert if denominator == 0, unlike the div opcode on its own.\n                // The surrounding unchecked block does not change this fact.\n                // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.\n                return low / denominator;\n            }\n\n            // Make sure the result is less than 2²⁵⁶. Also prevents denominator == 0.\n            if (denominator <= high) {\n                Panic.panic(ternary(denominator == 0, Panic.DIVISION_BY_ZERO, Panic.UNDER_OVERFLOW));\n            }\n\n            ///////////////////////////////////////////////\n            // 512 by 256 division.\n            ///////////////////////////////////////////////\n\n            // Make division exact by subtracting the remainder from [high low].\n            uint256 remainder;\n            assembly (\"memory-safe\") {\n                // Compute remainder using mulmod.\n                remainder := mulmod(x, y, denominator)\n\n                // Subtract 256 bit number from 512 bit number.\n                high := sub(high, gt(remainder, low))\n                low := sub(low, remainder)\n            }\n\n            // Factor powers of two out of denominator and compute largest power of two divisor of denominator.\n            // Always >= 1. See https://cs.stackexchange.com/q/138556/92363.\n\n            uint256 twos = denominator & (0 - denominator);\n            assembly (\"memory-safe\") {\n                // Divide denominator by twos.\n                denominator := div(denominator, twos)\n\n                // Divide [high low] by twos.\n                low := div(low, twos)\n\n                // Flip twos such that it is 2²⁵⁶ / twos. If twos is zero, then it becomes one.\n                twos := add(div(sub(0, twos), twos), 1)\n            }\n\n            // Shift in bits from high into low.\n            low |= high * twos;\n\n            // Invert denominator mod 2²⁵⁶. Now that denominator is an odd number, it has an inverse modulo 2²⁵⁶ such\n            // that denominator * inv ≡ 1 mod 2²⁵⁶. Compute the inverse by starting with a seed that is correct for\n            // four bits. That is, denominator * inv ≡ 1 mod 2⁴.\n            uint256 inverse = (3 * denominator) ^ 2;\n\n            // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also\n            // works in modular arithmetic, doubling the correct bits in each step.\n            inverse *= 2 - denominator * inverse; // inverse mod 2⁸\n            inverse *= 2 - denominator * inverse; // inverse mod 2¹⁶\n            inverse *= 2 - denominator * inverse; // inverse mod 2³²\n            inverse *= 2 - denominator * inverse; // inverse mod 2⁶⁴\n            inverse *= 2 - denominator * inverse; // inverse mod 2¹²⁸\n            inverse *= 2 - denominator * inverse; // inverse mod 2²⁵⁶\n\n            // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.\n            // This will give us the correct result modulo 2²⁵⁶. Since the preconditions guarantee that the outcome is\n            // less than 2²⁵⁶, this is the final result. We don't need to compute the high bits of the result and high\n            // is no longer required.\n            result = low * inverse;\n            return result;\n        }\n    }\n\n    /**\n     * @dev Calculates x * y / denominator with full precision, following the selected rounding direction.\n     */\n    function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {\n        return mulDiv(x, y, denominator) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0);\n    }\n\n    /**\n     * @dev Calculates floor(x * y >> n) with full precision. Throws if result overflows a uint256.\n     */\n    function mulShr(uint256 x, uint256 y, uint8 n) internal pure returns (uint256 result) {\n        unchecked {\n            (uint256 high, uint256 low) = mul512(x, y);\n            if (high >= 1 << n) {\n                Panic.panic(Panic.UNDER_OVERFLOW);\n            }\n            return (high << (256 - n)) | (low >> n);\n        }\n    }\n\n    /**\n     * @dev Calculates x * y >> n with full precision, following the selected rounding direction.\n     */\n    function mulShr(uint256 x, uint256 y, uint8 n, Rounding rounding) internal pure returns (uint256) {\n        return mulShr(x, y, n) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, 1 << n) > 0);\n    }\n\n    /**\n     * @dev Calculate the modular multiplicative inverse of a number in Z/nZ.\n     *\n     * If n is a prime, then Z/nZ is a field. In that case all elements are inversible, except 0.\n     * If n is not a prime, then Z/nZ is not a field, and some elements might not be inversible.\n     *\n     * If the input value is not inversible, 0 is returned.\n     *\n     * NOTE: If you know for sure that n is (big) a prime, it may be cheaper to use Fermat's little theorem and get the\n     * inverse using `Math.modExp(a, n - 2, n)`. See {invModPrime}.\n     */\n    function invMod(uint256 a, uint256 n) internal pure returns (uint256) {\n        unchecked {\n            if (n == 0) return 0;\n\n            // The inverse modulo is calculated using the Extended Euclidean Algorithm (iterative version)\n            // Used to compute integers x and y such that: ax + ny = gcd(a, n).\n            // When the gcd is 1, then the inverse of a modulo n exists and it's x.\n            // ax + ny = 1\n            // ax = 1 + (-y)n\n            // ax ≡ 1 (mod n) # x is the inverse of a modulo n\n\n            // If the remainder is 0 the gcd is n right away.\n            uint256 remainder = a % n;\n            uint256 gcd = n;\n\n            // Therefore the initial coefficients are:\n            // ax + ny = gcd(a, n) = n\n            // 0a + 1n = n\n            int256 x = 0;\n            int256 y = 1;\n\n            while (remainder != 0) {\n                uint256 quotient = gcd / remainder;\n\n                (gcd, remainder) = (\n                    // The old remainder is the next gcd to try.\n                    remainder,\n                    // Compute the next remainder.\n                    // Can't overflow given that (a % gcd) * (gcd // (a % gcd)) <= gcd\n                    // where gcd is at most n (capped to type(uint256).max)\n                    gcd - remainder * quotient\n                );\n\n                (x, y) = (\n                    // Increment the coefficient of a.\n                    y,\n                    // Decrement the coefficient of n.\n                    // Can overflow, but the result is casted to uint256 so that the\n                    // next value of y is \"wrapped around\" to a value between 0 and n - 1.\n                    x - y * int256(quotient)\n                );\n            }\n\n            if (gcd != 1) return 0; // No inverse exists.\n            return ternary(x < 0, n - uint256(-x), uint256(x)); // Wrap the result if it's negative.\n        }\n    }\n\n    /**\n     * @dev Variant of {invMod}. More efficient, but only works if `p` is known to be a prime greater than `2`.\n     *\n     * From https://en.wikipedia.org/wiki/Fermat%27s_little_theorem[Fermat's little theorem], we know that if p is\n     * prime, then `a**(p-1) ≡ 1 mod p`. As a consequence, we have `a * a**(p-2) ≡ 1 mod p`, which means that\n     * `a**(p-2)` is the modular multiplicative inverse of a in Fp.\n     *\n     * NOTE: this function does NOT check that `p` is a prime greater than `2`.\n     */\n    function invModPrime(uint256 a, uint256 p) internal view returns (uint256) {\n        unchecked {\n            return Math.modExp(a, p - 2, p);\n        }\n    }\n\n    /**\n     * @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m)\n     *\n     * Requirements:\n     * - modulus can't be zero\n     * - underlying staticcall to precompile must succeed\n     *\n     * IMPORTANT: The result is only valid if the underlying call succeeds. When using this function, make\n     * sure the chain you're using it on supports the precompiled contract for modular exponentiation\n     * at address 0x05 as specified in https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise,\n     * the underlying function will succeed given the lack of a revert, but the result may be incorrectly\n     * interpreted as 0.\n     */\n    function modExp(uint256 b, uint256 e, uint256 m) internal view returns (uint256) {\n        (bool success, uint256 result) = tryModExp(b, e, m);\n        if (!success) {\n            Panic.panic(Panic.DIVISION_BY_ZERO);\n        }\n        return result;\n    }\n\n    /**\n     * @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m).\n     * It includes a success flag indicating if the operation succeeded. Operation will be marked as failed if trying\n     * to operate modulo 0 or if the underlying precompile reverted.\n     *\n     * IMPORTANT: The result is only valid if the success flag is true. When using this function, make sure the chain\n     * you're using it on supports the precompiled contract for modular exponentiation at address 0x05 as specified in\n     * https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise, the underlying function will succeed given the lack\n     * of a revert, but the result may be incorrectly interpreted as 0.\n     */\n    function tryModExp(uint256 b, uint256 e, uint256 m) internal view returns (bool success, uint256 result) {\n        if (m == 0) return (false, 0);\n        assembly (\"memory-safe\") {\n            let ptr := mload(0x40)\n            // | Offset    | Content    | Content (Hex)                                                      |\n            // |-----------|------------|--------------------------------------------------------------------|\n            // | 0x00:0x1f | size of b  | 0x0000000000000000000000000000000000000000000000000000000000000020 |\n            // | 0x20:0x3f | size of e  | 0x0000000000000000000000000000000000000000000000000000000000000020 |\n            // | 0x40:0x5f | size of m  | 0x0000000000000000000000000000000000000000000000000000000000000020 |\n            // | 0x60:0x7f | value of b | 0x<.............................................................b> |\n            // | 0x80:0x9f | value of e | 0x<.............................................................e> |\n            // | 0xa0:0xbf | value of m | 0x<.............................................................m> |\n            mstore(ptr, 0x20)\n            mstore(add(ptr, 0x20), 0x20)\n            mstore(add(ptr, 0x40), 0x20)\n            mstore(add(ptr, 0x60), b)\n            mstore(add(ptr, 0x80), e)\n            mstore(add(ptr, 0xa0), m)\n\n            // Given the result < m, it's guaranteed to fit in 32 bytes,\n            // so we can use the memory scratch space located at offset 0.\n            success := staticcall(gas(), 0x05, ptr, 0xc0, 0x00, 0x20)\n            result := mload(0x00)\n        }\n    }\n\n    /**\n     * @dev Variant of {modExp} that supports inputs of arbitrary length.\n     */\n    function modExp(bytes memory b, bytes memory e, bytes memory m) internal view returns (bytes memory) {\n        (bool success, bytes memory result) = tryModExp(b, e, m);\n        if (!success) {\n            Panic.panic(Panic.DIVISION_BY_ZERO);\n        }\n        return result;\n    }\n\n    /**\n     * @dev Variant of {tryModExp} that supports inputs of arbitrary length.\n     */\n    function tryModExp(\n        bytes memory b,\n        bytes memory e,\n        bytes memory m\n    ) internal view returns (bool success, bytes memory result) {\n        if (_zeroBytes(m)) return (false, new bytes(0));\n\n        uint256 mLen = m.length;\n\n        // Encode call args in result and move the free memory pointer\n        result = abi.encodePacked(b.length, e.length, mLen, b, e, m);\n\n        assembly (\"memory-safe\") {\n            let dataPtr := add(result, 0x20)\n            // Write result on top of args to avoid allocating extra memory.\n            success := staticcall(gas(), 0x05, dataPtr, mload(result), dataPtr, mLen)\n            // Overwrite the length.\n            // result.length > returndatasize() is guaranteed because returndatasize() == m.length\n            mstore(result, mLen)\n            // Set the memory pointer after the returned data.\n            mstore(0x40, add(dataPtr, mLen))\n        }\n    }\n\n    /**\n     * @dev Returns whether the provided byte array is zero.\n     */\n    function _zeroBytes(bytes memory buffer) private pure returns (bool) {\n        uint256 chunk;\n        for (uint256 i = 0; i < buffer.length; i += 0x20) {\n            // See _unsafeReadBytesOffset from utils/Bytes.sol\n            assembly (\"memory-safe\") {\n                chunk := mload(add(add(buffer, 0x20), i))\n            }\n            if (chunk >> (8 * saturatingSub(i + 0x20, buffer.length)) != 0) {\n                return false;\n            }\n        }\n        return true;\n    }\n\n    /**\n     * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded\n     * towards zero.\n     *\n     * This method is based on Newton's method for computing square roots; the algorithm is restricted to only\n     * using integer operations.\n     */\n    function sqrt(uint256 a) internal pure returns (uint256) {\n        unchecked {\n            // Take care of easy edge cases when a == 0 or a == 1\n            if (a <= 1) {\n                return a;\n            }\n\n            // In this function, we use Newton's method to get a root of `f(x) := x² - a`. It involves building a\n            // sequence x_n that converges toward sqrt(a). For each iteration x_n, we also define the error between\n            // the current value as `ε_n = | x_n - sqrt(a) |`.\n            //\n            // For our first estimation, we consider `e` the smallest power of 2 which is bigger than the square root\n            // of the target. (i.e. `2**(e-1) ≤ sqrt(a) < 2**e`). We know that `e ≤ 128` because `(2¹²⁸)² = 2²⁵⁶` is\n            // bigger than any uint256.\n            //\n            // By noticing that\n            // `2**(e-1) ≤ sqrt(a) < 2**e → (2**(e-1))² ≤ a < (2**e)² → 2**(2*e-2) ≤ a < 2**(2*e)`\n            // we can deduce that `e - 1` is `log2(a) / 2`. We can thus compute `x_n = 2**(e-1)` using a method similar\n            // to the msb function.\n            uint256 aa = a;\n            uint256 xn = 1;\n\n            if (aa >= (1 << 128)) {\n                aa >>= 128;\n                xn <<= 64;\n            }\n            if (aa >= (1 << 64)) {\n                aa >>= 64;\n                xn <<= 32;\n            }\n            if (aa >= (1 << 32)) {\n                aa >>= 32;\n                xn <<= 16;\n            }\n            if (aa >= (1 << 16)) {\n                aa >>= 16;\n                xn <<= 8;\n            }\n            if (aa >= (1 << 8)) {\n                aa >>= 8;\n                xn <<= 4;\n            }\n            if (aa >= (1 << 4)) {\n                aa >>= 4;\n                xn <<= 2;\n            }\n            if (aa >= (1 << 2)) {\n                xn <<= 1;\n            }\n\n            // We now have x_n such that `x_n = 2**(e-1) ≤ sqrt(a) < 2**e = 2 * x_n`. This implies ε_n ≤ 2**(e-1).\n            //\n            // We can refine our estimation by noticing that the middle of that interval minimizes the error.\n            // If we move x_n to equal 2**(e-1) + 2**(e-2), then we reduce the error to ε_n ≤ 2**(e-2).\n            // This is going to be our x_0 (and ε_0)\n            xn = (3 * xn) >> 1; // ε_0 := | x_0 - sqrt(a) | ≤ 2**(e-2)\n\n            // From here, Newton's method give us:\n            // x_{n+1} = (x_n + a / x_n) / 2\n            //\n            // One should note that:\n            // x_{n+1}² - a = ((x_n + a / x_n) / 2)² - a\n            //              = ((x_n² + a) / (2 * x_n))² - a\n            //              = (x_n⁴ + 2 * a * x_n² + a²) / (4 * x_n²) - a\n            //              = (x_n⁴ + 2 * a * x_n² + a² - 4 * a * x_n²) / (4 * x_n²)\n            //              = (x_n⁴ - 2 * a * x_n² + a²) / (4 * x_n²)\n            //              = (x_n² - a)² / (2 * x_n)²\n            //              = ((x_n² - a) / (2 * x_n))²\n            //              ≥ 0\n            // Which proves that for all n ≥ 1, sqrt(a) ≤ x_n\n            //\n            // This gives us the proof of quadratic convergence of the sequence:\n            // ε_{n+1} = | x_{n+1} - sqrt(a) |\n            //         = | (x_n + a / x_n) / 2 - sqrt(a) |\n            //         = | (x_n² + a - 2*x_n*sqrt(a)) / (2 * x_n) |\n            //         = | (x_n - sqrt(a))² / (2 * x_n) |\n            //         = | ε_n² / (2 * x_n) |\n            //         = ε_n² / | (2 * x_n) |\n            //\n            // For the first iteration, we have a special case where x_0 is known:\n            // ε_1 = ε_0² / | (2 * x_0) |\n            //     ≤ (2**(e-2))² / (2 * (2**(e-1) + 2**(e-2)))\n            //     ≤ 2**(2*e-4) / (3 * 2**(e-1))\n            //     ≤ 2**(e-3) / 3\n            //     ≤ 2**(e-3-log2(3))\n            //     ≤ 2**(e-4.5)\n            //\n            // For the following iterations, we use the fact that, 2**(e-1) ≤ sqrt(a) ≤ x_n:\n            // ε_{n+1} = ε_n² / | (2 * x_n) |\n            //         ≤ (2**(e-k))² / (2 * 2**(e-1))\n            //         ≤ 2**(2*e-2*k) / 2**e\n            //         ≤ 2**(e-2*k)\n            xn = (xn + a / xn) >> 1; // ε_1 := | x_1 - sqrt(a) | ≤ 2**(e-4.5)  -- special case, see above\n            xn = (xn + a / xn) >> 1; // ε_2 := | x_2 - sqrt(a) | ≤ 2**(e-9)    -- general case with k = 4.5\n            xn = (xn + a / xn) >> 1; // ε_3 := | x_3 - sqrt(a) | ≤ 2**(e-18)   -- general case with k = 9\n            xn = (xn + a / xn) >> 1; // ε_4 := | x_4 - sqrt(a) | ≤ 2**(e-36)   -- general case with k = 18\n            xn = (xn + a / xn) >> 1; // ε_5 := | x_5 - sqrt(a) | ≤ 2**(e-72)   -- general case with k = 36\n            xn = (xn + a / xn) >> 1; // ε_6 := | x_6 - sqrt(a) | ≤ 2**(e-144)  -- general case with k = 72\n\n            // Because e ≤ 128 (as discussed during the first estimation phase), we know have reached a precision\n            // ε_6 ≤ 2**(e-144) < 1. Given we're operating on integers, then we can ensure that xn is now either\n            // sqrt(a) or sqrt(a) + 1.\n            return xn - SafeCast.toUint(xn > a / xn);\n        }\n    }\n\n    /**\n     * @dev Calculates sqrt(a), following the selected rounding direction.\n     */\n    function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {\n        unchecked {\n            uint256 result = sqrt(a);\n            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && result * result < a);\n        }\n    }\n\n    /**\n     * @dev Return the log in base 2 of a positive value rounded towards zero.\n     * Returns 0 if given 0.\n     */\n    function log2(uint256 x) internal pure returns (uint256 r) {\n        // If value has upper 128 bits set, log2 result is at least 128\n        r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;\n        // If upper 64 bits of 128-bit half set, add 64 to result\n        r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;\n        // If upper 32 bits of 64-bit half set, add 32 to result\n        r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;\n        // If upper 16 bits of 32-bit half set, add 16 to result\n        r |= SafeCast.toUint((x >> r) > 0xffff) << 4;\n        // If upper 8 bits of 16-bit half set, add 8 to result\n        r |= SafeCast.toUint((x >> r) > 0xff) << 3;\n        // If upper 4 bits of 8-bit half set, add 4 to result\n        r |= SafeCast.toUint((x >> r) > 0xf) << 2;\n\n        // Shifts value right by the current result and use it as an index into this lookup table:\n        //\n        // | x (4 bits) |  index  | table[index] = MSB position |\n        // |------------|---------|-----------------------------|\n        // |    0000    |    0    |        table[0] = 0         |\n        // |    0001    |    1    |        table[1] = 0         |\n        // |    0010    |    2    |        table[2] = 1         |\n        // |    0011    |    3    |        table[3] = 1         |\n        // |    0100    |    4    |        table[4] = 2         |\n        // |    0101    |    5    |        table[5] = 2         |\n        // |    0110    |    6    |        table[6] = 2         |\n        // |    0111    |    7    |        table[7] = 2         |\n        // |    1000    |    8    |        table[8] = 3         |\n        // |    1001    |    9    |        table[9] = 3         |\n        // |    1010    |   10    |        table[10] = 3        |\n        // |    1011    |   11    |        table[11] = 3        |\n        // |    1100    |   12    |        table[12] = 3        |\n        // |    1101    |   13    |        table[13] = 3        |\n        // |    1110    |   14    |        table[14] = 3        |\n        // |    1111    |   15    |        table[15] = 3        |\n        //\n        // The lookup table is represented as a 32-byte value with the MSB positions for 0-15 in the first 16 bytes (most significant half).\n        assembly (\"memory-safe\") {\n            r := or(r, byte(shr(r, x), 0x0000010102020202030303030303030300000000000000000000000000000000))\n        }\n    }\n\n    /**\n     * @dev Return the log in base 2, following the selected rounding direction, of a positive value.\n     * Returns 0 if given 0.\n     */\n    function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {\n        unchecked {\n            uint256 result = log2(value);\n            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << result < value);\n        }\n    }\n\n    /**\n     * @dev Return the log in base 10 of a positive value rounded towards zero.\n     * Returns 0 if given 0.\n     */\n    function log10(uint256 value) internal pure returns (uint256) {\n        uint256 result = 0;\n        unchecked {\n            if (value >= 10 ** 64) {\n                value /= 10 ** 64;\n                result += 64;\n            }\n            if (value >= 10 ** 32) {\n                value /= 10 ** 32;\n                result += 32;\n            }\n            if (value >= 10 ** 16) {\n                value /= 10 ** 16;\n                result += 16;\n            }\n            if (value >= 10 ** 8) {\n                value /= 10 ** 8;\n                result += 8;\n            }\n            if (value >= 10 ** 4) {\n                value /= 10 ** 4;\n                result += 4;\n            }\n            if (value >= 10 ** 2) {\n                value /= 10 ** 2;\n                result += 2;\n            }\n            if (value >= 10 ** 1) {\n                result += 1;\n            }\n        }\n        return result;\n    }\n\n    /**\n     * @dev Return the log in base 10, following the selected rounding direction, of a positive value.\n     * Returns 0 if given 0.\n     */\n    function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {\n        unchecked {\n            uint256 result = log10(value);\n            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 10 ** result < value);\n        }\n    }\n\n    /**\n     * @dev Return the log in base 256 of a positive value rounded towards zero.\n     * Returns 0 if given 0.\n     *\n     * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.\n     */\n    function log256(uint256 x) internal pure returns (uint256 r) {\n        // If value has upper 128 bits set, log2 result is at least 128\n        r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;\n        // If upper 64 bits of 128-bit half set, add 64 to result\n        r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;\n        // If upper 32 bits of 64-bit half set, add 32 to result\n        r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;\n        // If upper 16 bits of 32-bit half set, add 16 to result\n        r |= SafeCast.toUint((x >> r) > 0xffff) << 4;\n        // Add 1 if upper 8 bits of 16-bit half set, and divide accumulated result by 8\n        return (r >> 3) | SafeCast.toUint((x >> r) > 0xff);\n    }\n\n    /**\n     * @dev Return the log in base 256, following the selected rounding direction, of a positive value.\n     * Returns 0 if given 0.\n     */\n    function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {\n        unchecked {\n            uint256 result = log256(value);\n            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << (result << 3) < value);\n        }\n    }\n\n    /**\n     * @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.\n     */\n    function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {\n        return uint8(rounding) % 2 == 1;\n    }\n\n    /**\n     * @dev Counts the number of leading zero bits in a uint256.\n     */\n    function clz(uint256 x) internal pure returns (uint256) {\n        return ternary(x == 0, 256, 255 - log2(x));\n    }\n}\n"},{"file_path":"lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.5.0) (token/ERC20/utils/SafeERC20.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC20} from \"../IERC20.sol\";\nimport {IERC1363} from \"../../../interfaces/IERC1363.sol\";\n\n/**\n * @title SafeERC20\n * @dev Wrappers around ERC-20 operations that throw on failure (when the token\n * contract returns false). Tokens that return no value (and instead revert or\n * throw on failure) are also supported, non-reverting calls are assumed to be\n * successful.\n * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,\n * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.\n */\nlibrary SafeERC20 {\n    /**\n     * @dev An operation with an ERC-20 token failed.\n     */\n    error SafeERC20FailedOperation(address token);\n\n    /**\n     * @dev Indicates a failed `decreaseAllowance` request.\n     */\n    error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);\n\n    /**\n     * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,\n     * non-reverting calls are assumed to be successful.\n     */\n    function safeTransfer(IERC20 token, address to, uint256 value) internal {\n        if (!_safeTransfer(token, to, value, true)) {\n            revert SafeERC20FailedOperation(address(token));\n        }\n    }\n\n    /**\n     * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the\n     * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.\n     */\n    function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {\n        if (!_safeTransferFrom(token, from, to, value, true)) {\n            revert SafeERC20FailedOperation(address(token));\n        }\n    }\n\n    /**\n     * @dev Variant of {safeTransfer} that returns a bool instead of reverting if the operation is not successful.\n     */\n    function trySafeTransfer(IERC20 token, address to, uint256 value) internal returns (bool) {\n        return _safeTransfer(token, to, value, false);\n    }\n\n    /**\n     * @dev Variant of {safeTransferFrom} that returns a bool instead of reverting if the operation is not successful.\n     */\n    function trySafeTransferFrom(IERC20 token, address from, address to, uint256 value) internal returns (bool) {\n        return _safeTransferFrom(token, from, to, value, false);\n    }\n\n    /**\n     * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,\n     * non-reverting calls are assumed to be successful.\n     *\n     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the \"client\"\n     * smart contract uses ERC-7674 to set temporary allowances, then the \"client\" smart contract should avoid using\n     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract\n     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.\n     */\n    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {\n        uint256 oldAllowance = token.allowance(address(this), spender);\n        forceApprove(token, spender, oldAllowance + value);\n    }\n\n    /**\n     * @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no\n     * value, non-reverting calls are assumed to be successful.\n     *\n     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the \"client\"\n     * smart contract uses ERC-7674 to set temporary allowances, then the \"client\" smart contract should avoid using\n     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract\n     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.\n     */\n    function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {\n        unchecked {\n            uint256 currentAllowance = token.allowance(address(this), spender);\n            if (currentAllowance < requestedDecrease) {\n                revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);\n            }\n            forceApprove(token, spender, currentAllowance - requestedDecrease);\n        }\n    }\n\n    /**\n     * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,\n     * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval\n     * to be set to zero before setting it to a non-zero value, such as USDT.\n     *\n     * NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function\n     * only sets the \"standard\" allowance. Any temporary allowance will remain active, in addition to the value being\n     * set here.\n     */\n    function forceApprove(IERC20 token, address spender, uint256 value) internal {\n        if (!_safeApprove(token, spender, value, false)) {\n            if (!_safeApprove(token, spender, 0, true)) revert SafeERC20FailedOperation(address(token));\n            if (!_safeApprove(token, spender, value, true)) revert SafeERC20FailedOperation(address(token));\n        }\n    }\n\n    /**\n     * @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no\n     * code. This can be used to implement an {ERC721}-like safe transfer that relies on {ERC1363} checks when\n     * targeting contracts.\n     *\n     * Reverts if the returned value is other than `true`.\n     */\n    function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {\n        if (to.code.length == 0) {\n            safeTransfer(token, to, value);\n        } else if (!token.transferAndCall(to, value, data)) {\n            revert SafeERC20FailedOperation(address(token));\n        }\n    }\n\n    /**\n     * @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target\n     * has no code. This can be used to implement an {ERC721}-like safe transfer that relies on {ERC1363} checks when\n     * targeting contracts.\n     *\n     * Reverts if the returned value is other than `true`.\n     */\n    function transferFromAndCallRelaxed(\n        IERC1363 token,\n        address from,\n        address to,\n        uint256 value,\n        bytes memory data\n    ) internal {\n        if (to.code.length == 0) {\n            safeTransferFrom(token, from, to, value);\n        } else if (!token.transferFromAndCall(from, to, value, data)) {\n            revert SafeERC20FailedOperation(address(token));\n        }\n    }\n\n    /**\n     * @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no\n     * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when\n     * targeting contracts.\n     *\n     * NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.\n     * Oppositely, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}\n     * once without retrying, and relies on the returned value to be true.\n     *\n     * Reverts if the returned value is other than `true`.\n     */\n    function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {\n        if (to.code.length == 0) {\n            forceApprove(token, to, value);\n        } else if (!token.approveAndCall(to, value, data)) {\n            revert SafeERC20FailedOperation(address(token));\n        }\n    }\n\n    /**\n     * @dev Imitates a Solidity `token.transfer(to, value)` call, relaxing the requirement on the return value: the\n     * return value is optional (but if data is returned, it must not be false).\n     *\n     * @param token The token targeted by the call.\n     * @param to The recipient of the tokens\n     * @param value The amount of token to transfer\n     * @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.\n     */\n    function _safeTransfer(IERC20 token, address to, uint256 value, bool bubble) private returns (bool success) {\n        bytes4 selector = IERC20.transfer.selector;\n\n        assembly (\"memory-safe\") {\n            let fmp := mload(0x40)\n            mstore(0x00, selector)\n            mstore(0x04, and(to, shr(96, not(0))))\n            mstore(0x24, value)\n            success := call(gas(), token, 0, 0x00, 0x44, 0x00, 0x20)\n            // if call success and return is true, all is good.\n            // otherwise (not success or return is not true), we need to perform further checks\n            if iszero(and(success, eq(mload(0x00), 1))) {\n                // if the call was a failure and bubble is enabled, bubble the error\n                if and(iszero(success), bubble) {\n                    returndatacopy(fmp, 0x00, returndatasize())\n                    revert(fmp, returndatasize())\n                }\n                // if the return value is not true, then the call is only successful if:\n                // - the token address has code\n                // - the returndata is empty\n                success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))\n            }\n            mstore(0x40, fmp)\n        }\n    }\n\n    /**\n     * @dev Imitates a Solidity `token.transferFrom(from, to, value)` call, relaxing the requirement on the return\n     * value: the return value is optional (but if data is returned, it must not be false).\n     *\n     * @param token The token targeted by the call.\n     * @param from The sender of the tokens\n     * @param to The recipient of the tokens\n     * @param value The amount of token to transfer\n     * @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.\n     */\n    function _safeTransferFrom(\n        IERC20 token,\n        address from,\n        address to,\n        uint256 value,\n        bool bubble\n    ) private returns (bool success) {\n        bytes4 selector = IERC20.transferFrom.selector;\n\n        assembly (\"memory-safe\") {\n            let fmp := mload(0x40)\n            mstore(0x00, selector)\n            mstore(0x04, and(from, shr(96, not(0))))\n            mstore(0x24, and(to, shr(96, not(0))))\n            mstore(0x44, value)\n            success := call(gas(), token, 0, 0x00, 0x64, 0x00, 0x20)\n            // if call success and return is true, all is good.\n            // otherwise (not success or return is not true), we need to perform further checks\n            if iszero(and(success, eq(mload(0x00), 1))) {\n                // if the call was a failure and bubble is enabled, bubble the error\n                if and(iszero(success), bubble) {\n                    returndatacopy(fmp, 0x00, returndatasize())\n                    revert(fmp, returndatasize())\n                }\n                // if the return value is not true, then the call is only successful if:\n                // - the token address has code\n                // - the returndata is empty\n                success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))\n            }\n            mstore(0x40, fmp)\n            mstore(0x60, 0)\n        }\n    }\n\n    /**\n     * @dev Imitates a Solidity `token.approve(spender, value)` call, relaxing the requirement on the return value:\n     * the return value is optional (but if data is returned, it must not be false).\n     *\n     * @param token The token targeted by the call.\n     * @param spender The spender of the tokens\n     * @param value The amount of token to transfer\n     * @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.\n     */\n    function _safeApprove(IERC20 token, address spender, uint256 value, bool bubble) private returns (bool success) {\n        bytes4 selector = IERC20.approve.selector;\n\n        assembly (\"memory-safe\") {\n            let fmp := mload(0x40)\n            mstore(0x00, selector)\n            mstore(0x04, and(spender, shr(96, not(0))))\n            mstore(0x24, value)\n            success := call(gas(), token, 0, 0x00, 0x44, 0x00, 0x20)\n            // if call success and return is true, all is good.\n            // otherwise (not success or return is not true), we need to perform further checks\n            if iszero(and(success, eq(mload(0x00), 1))) {\n                // if the call was a failure and bubble is enabled, bubble the error\n                if and(iszero(success), bubble) {\n                    returndatacopy(fmp, 0x00, returndatasize())\n                    revert(fmp, returndatasize())\n                }\n                // if the return value is not true, then the call is only successful if:\n                // - the token address has code\n                // - the returndata is empty\n                success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))\n            }\n            mstore(0x40, fmp)\n        }\n    }\n}\n"},{"file_path":"lib/openzeppelin-contracts/contracts/access/IAccessControl.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.4.0) (access/IAccessControl.sol)\n\npragma solidity >=0.8.4;\n\n/**\n * @dev External interface of AccessControl declared to support ERC-165 detection.\n */\ninterface IAccessControl {\n    /**\n     * @dev The `account` is missing a role.\n     */\n    error AccessControlUnauthorizedAccount(address account, bytes32 neededRole);\n\n    /**\n     * @dev The caller of a function is not the expected one.\n     *\n     * NOTE: Don't confuse with {AccessControlUnauthorizedAccount}.\n     */\n    error AccessControlBadConfirmation();\n\n    /**\n     * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`\n     *\n     * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite\n     * {RoleAdminChanged} not being emitted to signal this.\n     */\n    event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);\n\n    /**\n     * @dev Emitted when `account` is granted `role`.\n     *\n     * `sender` is the account that originated the contract call. This account bears the admin role (for the granted role).\n     * Expected in cases where the role was granted using the internal {AccessControl-_grantRole}.\n     */\n    event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);\n\n    /**\n     * @dev Emitted when `account` is revoked `role`.\n     *\n     * `sender` is the account that originated the contract call:\n     *   - if using `revokeRole`, it is the admin role bearer\n     *   - if using `renounceRole`, it is the role bearer (i.e. `account`)\n     */\n    event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);\n\n    /**\n     * @dev Returns `true` if `account` has been granted `role`.\n     */\n    function hasRole(bytes32 role, address account) external view returns (bool);\n\n    /**\n     * @dev Returns the admin role that controls `role`. See {grantRole} and\n     * {revokeRole}.\n     *\n     * To change a role's admin, use {AccessControl-_setRoleAdmin}.\n     */\n    function getRoleAdmin(bytes32 role) external view returns (bytes32);\n\n    /**\n     * @dev Grants `role` to `account`.\n     *\n     * If `account` had not been already granted `role`, emits a {RoleGranted}\n     * event.\n     *\n     * Requirements:\n     *\n     * - the caller must have ``role``'s admin role.\n     */\n    function grantRole(bytes32 role, address account) external;\n\n    /**\n     * @dev Revokes `role` from `account`.\n     *\n     * If `account` had been granted `role`, emits a {RoleRevoked} event.\n     *\n     * Requirements:\n     *\n     * - the caller must have ``role``'s admin role.\n     */\n    function revokeRole(bytes32 role, address account) external;\n\n    /**\n     * @dev Revokes `role` from the calling account.\n     *\n     * Roles are often managed via {grantRole} and {revokeRole}: this function's\n     * purpose is to provide a mechanism for accounts to lose their privileges\n     * if they are compromised (such as when a trusted device is misplaced).\n     *\n     * If the calling account had been granted `role`, emits a {RoleRevoked}\n     * event.\n     *\n     * Requirements:\n     *\n     * - the caller must be `callerConfirmation`.\n     */\n    function renounceRole(bytes32 role, address callerConfirmation) external;\n}\n"},{"file_path":"lib/openzeppelin-contracts/contracts/utils/cryptography/ECDSA.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.5.0) (utils/cryptography/ECDSA.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.\n *\n * These functions can be used to verify that a message was signed by the holder\n * of the private keys of a given address.\n */\nlibrary ECDSA {\n    enum RecoverError {\n        NoError,\n        InvalidSignature,\n        InvalidSignatureLength,\n        InvalidSignatureS\n    }\n\n    /**\n     * @dev The signature is invalid.\n     */\n    error ECDSAInvalidSignature();\n\n    /**\n     * @dev The signature has an invalid length.\n     */\n    error ECDSAInvalidSignatureLength(uint256 length);\n\n    /**\n     * @dev The signature has an S value that is in the upper half order.\n     */\n    error ECDSAInvalidSignatureS(bytes32 s);\n\n    /**\n     * @dev Returns the address that signed a hashed message (`hash`) with `signature` or an error. This will not\n     * return address(0) without also returning an error description. Errors are documented using an enum (error type)\n     * and a bytes32 providing additional information about the error.\n     *\n     * If no error is returned, then the address can be used for verification purposes.\n     *\n     * The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:\n     * this function rejects them by requiring the `s` value to be in the lower\n     * half order, and the `v` value to be either 27 or 28.\n     *\n     * NOTE: This function only supports 65-byte signatures. ERC-2098 short signatures are rejected. This restriction\n     * is DEPRECATED and will be removed in v6.0. Developers SHOULD NOT use signatures as unique identifiers; use hash\n     * invalidation or nonces for replay protection.\n     *\n     * IMPORTANT: `hash` _must_ be the result of a hash operation for the\n     * verification to be secure: it is possible to craft signatures that\n     * recover to arbitrary addresses for non-hashed data. A safe way to ensure\n     * this is by receiving a hash of the original message (which may otherwise\n     * be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.\n     *\n     * Documentation for signature generation:\n     *\n     * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]\n     * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]\n     */\n    function tryRecover(\n        bytes32 hash,\n        bytes memory signature\n    ) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {\n        if (signature.length == 65) {\n            bytes32 r;\n            bytes32 s;\n            uint8 v;\n            // ecrecover takes the signature parameters, and the only way to get them\n            // currently is to use assembly.\n            assembly (\"memory-safe\") {\n                r := mload(add(signature, 0x20))\n                s := mload(add(signature, 0x40))\n                v := byte(0, mload(add(signature, 0x60)))\n            }\n            return tryRecover(hash, v, r, s);\n        } else {\n            return (address(0), RecoverError.InvalidSignatureLength, bytes32(signature.length));\n        }\n    }\n\n    /**\n     * @dev Variant of {tryRecover} that takes a signature in calldata\n     */\n    function tryRecoverCalldata(\n        bytes32 hash,\n        bytes calldata signature\n    ) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {\n        if (signature.length == 65) {\n            bytes32 r;\n            bytes32 s;\n            uint8 v;\n            // ecrecover takes the signature parameters, calldata slices would work here, but are\n            // significantly more expensive (length check) than using calldataload in assembly.\n            assembly (\"memory-safe\") {\n                r := calldataload(signature.offset)\n                s := calldataload(add(signature.offset, 0x20))\n                v := byte(0, calldataload(add(signature.offset, 0x40)))\n            }\n            return tryRecover(hash, v, r, s);\n        } else {\n            return (address(0), RecoverError.InvalidSignatureLength, bytes32(signature.length));\n        }\n    }\n\n    /**\n     * @dev Returns the address that signed a hashed message (`hash`) with\n     * `signature`. This address can then be used for verification purposes.\n     *\n     * The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:\n     * this function rejects them by requiring the `s` value to be in the lower\n     * half order, and the `v` value to be either 27 or 28.\n     *\n     * NOTE: This function only supports 65-byte signatures. ERC-2098 short signatures are rejected. This restriction\n     * is DEPRECATED and will be removed in v6.0. Developers SHOULD NOT use signatures as unique identifiers; use hash\n     * invalidation or nonces for replay protection.\n     *\n     * IMPORTANT: `hash` _must_ be the result of a hash operation for the\n     * verification to be secure: it is possible to craft signatures that\n     * recover to arbitrary addresses for non-hashed data. A safe way to ensure\n     * this is by receiving a hash of the original message (which may otherwise\n     * be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.\n     */\n    function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {\n        (address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, signature);\n        _throwError(error, errorArg);\n        return recovered;\n    }\n\n    /**\n     * @dev Variant of {recover} that takes a signature in calldata\n     */\n    function recoverCalldata(bytes32 hash, bytes calldata signature) internal pure returns (address) {\n        (address recovered, RecoverError error, bytes32 errorArg) = tryRecoverCalldata(hash, signature);\n        _throwError(error, errorArg);\n        return recovered;\n    }\n\n    /**\n     * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.\n     *\n     * See https://eips.ethereum.org/EIPS/eip-2098[ERC-2098 short signatures]\n     */\n    function tryRecover(\n        bytes32 hash,\n        bytes32 r,\n        bytes32 vs\n    ) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {\n        unchecked {\n            bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);\n            // We do not check for an overflow here since the shift operation results in 0 or 1.\n            uint8 v = uint8((uint256(vs) >> 255) + 27);\n            return tryRecover(hash, v, r, s);\n        }\n    }\n\n    /**\n     * @dev Overload of {ECDSA-recover} that receives the `r` and `vs` short-signature fields separately.\n     */\n    function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address) {\n        (address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, r, vs);\n        _throwError(error, errorArg);\n        return recovered;\n    }\n\n    /**\n     * @dev Overload of {ECDSA-tryRecover} that receives the `v`,\n     * `r` and `s` signature fields separately.\n     */\n    function tryRecover(\n        bytes32 hash,\n        uint8 v,\n        bytes32 r,\n        bytes32 s\n    ) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {\n        // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature\n        // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines\n        // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most\n        // signatures from current libraries generate a unique signature with an s-value in the lower half order.\n        //\n        // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value\n        // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or\n        // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept\n        // these malleable signatures as well.\n        if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {\n            return (address(0), RecoverError.InvalidSignatureS, s);\n        }\n\n        // If the signature is valid (and not malleable), return the signer address\n        address signer = ecrecover(hash, v, r, s);\n        if (signer == address(0)) {\n            return (address(0), RecoverError.InvalidSignature, bytes32(0));\n        }\n\n        return (signer, RecoverError.NoError, bytes32(0));\n    }\n\n    /**\n     * @dev Overload of {ECDSA-recover} that receives the `v`,\n     * `r` and `s` signature fields separately.\n     */\n    function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {\n        (address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, v, r, s);\n        _throwError(error, errorArg);\n        return recovered;\n    }\n\n    /**\n     * @dev Parse a signature into its `v`, `r` and `s` components. Supports 65-byte and 64-byte (ERC-2098)\n     * formats. Returns (0,0,0) for invalid signatures.\n     *\n     * For 64-byte signatures, `v` is automatically normalized to 27 or 28.\n     * For 65-byte signatures, `v` is returned as-is and MUST already be 27 or 28 for use with ecrecover.\n     *\n     * Consider validating the result before use, or use {tryRecover}/{recover} which perform full validation.\n     */\n    function parse(bytes memory signature) internal pure returns (uint8 v, bytes32 r, bytes32 s) {\n        assembly (\"memory-safe\") {\n            // Check the signature length\n            switch mload(signature)\n            // - case 65: r,s,v signature (standard)\n            case 65 {\n                r := mload(add(signature, 0x20))\n                s := mload(add(signature, 0x40))\n                v := byte(0, mload(add(signature, 0x60)))\n            }\n            // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098)\n            case 64 {\n                let vs := mload(add(signature, 0x40))\n                r := mload(add(signature, 0x20))\n                s := and(vs, shr(1, not(0)))\n                v := add(shr(255, vs), 27)\n            }\n            default {\n                r := 0\n                s := 0\n                v := 0\n            }\n        }\n    }\n\n    /**\n     * @dev Variant of {parse} that takes a signature in calldata\n     */\n    function parseCalldata(bytes calldata signature) internal pure returns (uint8 v, bytes32 r, bytes32 s) {\n        assembly (\"memory-safe\") {\n            // Check the signature length\n            switch signature.length\n            // - case 65: r,s,v signature (standard)\n            case 65 {\n                r := calldataload(signature.offset)\n                s := calldataload(add(signature.offset, 0x20))\n                v := byte(0, calldataload(add(signature.offset, 0x40)))\n            }\n            // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098)\n            case 64 {\n                let vs := calldataload(add(signature.offset, 0x20))\n                r := calldataload(signature.offset)\n                s := and(vs, shr(1, not(0)))\n                v := add(shr(255, vs), 27)\n            }\n            default {\n                r := 0\n                s := 0\n                v := 0\n            }\n        }\n    }\n\n    /**\n     * @dev Optionally reverts with the corresponding custom error according to the `error` argument provided.\n     */\n    function _throwError(RecoverError error, bytes32 errorArg) private pure {\n        if (error == RecoverError.NoError) {\n            return; // no error: do nothing\n        } else if (error == RecoverError.InvalidSignature) {\n            revert ECDSAInvalidSignature();\n        } else if (error == RecoverError.InvalidSignatureLength) {\n            revert ECDSAInvalidSignatureLength(uint256(errorArg));\n        } else if (error == RecoverError.InvalidSignatureS) {\n            revert ECDSAInvalidSignatureS(errorArg);\n        }\n    }\n}\n"},{"file_path":"lib/openzeppelin-contracts/contracts/utils/Panic.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (utils/Panic.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Helper library for emitting standardized panic codes.\n *\n * ```solidity\n * contract Example {\n *      using Panic for uint256;\n *\n *      // Use any of the declared internal constants\n *      function foo() { Panic.GENERIC.panic(); }\n *\n *      // Alternatively\n *      function foo() { Panic.panic(Panic.GENERIC); }\n * }\n * ```\n *\n * Follows the list from https://github.com/ethereum/solidity/blob/v0.8.24/libsolutil/ErrorCodes.h[libsolutil].\n *\n * _Available since v5.1._\n */\n// slither-disable-next-line unused-state\nlibrary Panic {\n    /// @dev generic / unspecified error\n    uint256 internal constant GENERIC = 0x00;\n    /// @dev used by the assert() builtin\n    uint256 internal constant ASSERT = 0x01;\n    /// @dev arithmetic underflow or overflow\n    uint256 internal constant UNDER_OVERFLOW = 0x11;\n    /// @dev division or modulo by zero\n    uint256 internal constant DIVISION_BY_ZERO = 0x12;\n    /// @dev enum conversion error\n    uint256 internal constant ENUM_CONVERSION_ERROR = 0x21;\n    /// @dev invalid encoding in storage\n    uint256 internal constant STORAGE_ENCODING_ERROR = 0x22;\n    /// @dev empty array pop\n    uint256 internal constant EMPTY_ARRAY_POP = 0x31;\n    /// @dev array out of bounds access\n    uint256 internal constant ARRAY_OUT_OF_BOUNDS = 0x32;\n    /// @dev resource error (too large allocation or too large array)\n    uint256 internal constant RESOURCE_ERROR = 0x41;\n    /// @dev calling invalid internal function\n    uint256 internal constant INVALID_INTERNAL_FUNCTION = 0x51;\n\n    /// @dev Reverts with a panic code. Recommended to use with\n    /// the internal constants with predefined codes.\n    function panic(uint256 code) internal pure {\n        assembly (\"memory-safe\") {\n            mstore(0x00, 0x4e487b71)\n            mstore(0x20, code)\n            revert(0x1c, 0x24)\n        }\n    }\n}\n"},{"file_path":"lib/openzeppelin-contracts/contracts/access/extensions/IAccessControlEnumerable.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.4.0) (access/extensions/IAccessControlEnumerable.sol)\n\npragma solidity >=0.8.4;\n\nimport {IAccessControl} from \"../IAccessControl.sol\";\n\n/**\n * @dev External interface of AccessControlEnumerable declared to support ERC-165 detection.\n */\ninterface IAccessControlEnumerable is IAccessControl {\n    /**\n     * @dev Returns one of the accounts that have `role`. `index` must be a\n     * value between 0 and {getRoleMemberCount}, non-inclusive.\n     *\n     * Role bearers are not sorted in any particular way, and their ordering may\n     * change at any point.\n     *\n     * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure\n     * you perform all queries on the same block. See the following\n     * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]\n     * for more information.\n     */\n    function getRoleMember(bytes32 role, uint256 index) external view returns (address);\n\n    /**\n     * @dev Returns the number of accounts that have `role`. Can be used\n     * together with {getRoleMember} to enumerate all bearers of a role.\n     */\n    function getRoleMemberCount(bytes32 role) external view returns (uint256);\n}\n"},{"file_path":"lib/openzeppelin-contracts/contracts/utils/structs/EnumerableSet.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.5.0) (utils/structs/EnumerableSet.sol)\n// This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.\n\npragma solidity ^0.8.24;\n\nimport {Arrays} from \"../Arrays.sol\";\nimport {Math} from \"../math/Math.sol\";\n\n/**\n * @dev Library for managing\n * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive\n * types.\n *\n * Sets have the following properties:\n *\n * - Elements are added, removed, and checked for existence in constant time\n * (O(1)).\n * - Elements are enumerated in O(n). No guarantees are made on the ordering.\n * - Set can be cleared (all elements removed) in O(n).\n *\n * ```solidity\n * contract Example {\n *     // Add the library methods\n *     using EnumerableSet for EnumerableSet.AddressSet;\n *\n *     // Declare a set state variable\n *     EnumerableSet.AddressSet private mySet;\n * }\n * ```\n *\n * The following types are supported:\n *\n * - `bytes32` (`Bytes32Set`) since v3.3.0\n * - `address` (`AddressSet`) since v3.3.0\n * - `uint256` (`UintSet`) since v3.3.0\n * - `string` (`StringSet`) since v5.4.0\n * - `bytes` (`BytesSet`) since v5.4.0\n * - `bytes4` (`Bytes4Set`) since v5.6.0\n *\n * [WARNING]\n * ====\n * Trying to delete such a structure from storage will likely result in data corruption, rendering the structure\n * unusable.\n * See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.\n *\n * In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an\n * array of EnumerableSet.\n * ====\n */\nlibrary EnumerableSet {\n    // To implement this library for multiple types with as little code\n    // repetition as possible, we write it in terms of a generic Set type with\n    // bytes32 values.\n    // The Set implementation uses private functions, and user-facing\n    // implementations (such as AddressSet) are just wrappers around the\n    // underlying Set.\n    // This means that we can only create new EnumerableSets for types that fit\n    // in bytes32.\n\n    struct Set {\n        // Storage of set values\n        bytes32[] _values;\n        // Position is the index of the value in the `values` array plus 1.\n        // Position 0 is used to mean a value is not in the set.\n        mapping(bytes32 value => uint256) _positions;\n    }\n\n    /**\n     * @dev Add a value to a set. O(1).\n     *\n     * Returns true if the value was added to the set, that is if it was not\n     * already present.\n     */\n    function _add(Set storage set, bytes32 value) private returns (bool) {\n        if (!_contains(set, value)) {\n            set._values.push(value);\n            // The value is stored at length-1, but we add 1 to all indexes\n            // and use 0 as a sentinel value\n            set._positions[value] = set._values.length;\n            return true;\n        } else {\n            return false;\n        }\n    }\n\n    /**\n     * @dev Removes a value from a set. O(1).\n     *\n     * Returns true if the value was removed from the set, that is if it was\n     * present.\n     */\n    function _remove(Set storage set, bytes32 value) private returns (bool) {\n        // We cache the value's position to prevent multiple reads from the same storage slot\n        uint256 position = set._positions[value];\n\n        if (position != 0) {\n            // Equivalent to contains(set, value)\n            // To delete an element from the _values array in O(1), we swap the element to delete with the last one in\n            // the array, and then remove the last element (sometimes called as 'swap and pop').\n            // This modifies the order of the array, as noted in {at}.\n\n            uint256 valueIndex = position - 1;\n            uint256 lastIndex = set._values.length - 1;\n\n            if (valueIndex != lastIndex) {\n                bytes32 lastValue = set._values[lastIndex];\n\n                // Move the lastValue to the index where the value to delete is\n                set._values[valueIndex] = lastValue;\n                // Update the tracked position of the lastValue (that was just moved)\n                set._positions[lastValue] = position;\n            }\n\n            // Delete the slot where the moved value was stored\n            set._values.pop();\n\n            // Delete the tracked position for the deleted slot\n            delete set._positions[value];\n\n            return true;\n        } else {\n            return false;\n        }\n    }\n\n    /**\n     * @dev Removes all the values from a set. O(n).\n     *\n     * WARNING: This function has an unbounded cost that scales with set size. Developers should keep in mind that\n     * using it may render the function uncallable if the set grows to the point where clearing it consumes too much\n     * gas to fit in a block.\n     */\n    function _clear(Set storage set) private {\n        uint256 len = _length(set);\n        for (uint256 i = 0; i < len; ++i) {\n            delete set._positions[set._values[i]];\n        }\n        Arrays.unsafeSetLength(set._values, 0);\n    }\n\n    /**\n     * @dev Returns true if the value is in the set. O(1).\n     */\n    function _contains(Set storage set, bytes32 value) private view returns (bool) {\n        return set._positions[value] != 0;\n    }\n\n    /**\n     * @dev Returns the number of values on the set. O(1).\n     */\n    function _length(Set storage set) private view returns (uint256) {\n        return set._values.length;\n    }\n\n    /**\n     * @dev Returns the value stored at position `index` in the set. O(1).\n     *\n     * Note that there are no guarantees on the ordering of values inside the\n     * array, and it may change when more values are added or removed.\n     *\n     * Requirements:\n     *\n     * - `index` must be strictly less than {length}.\n     */\n    function _at(Set storage set, uint256 index) private view returns (bytes32) {\n        return set._values[index];\n    }\n\n    /**\n     * @dev Return the entire set in an array\n     *\n     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\n     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\n     * this function has an unbounded cost, and using it as part of a state-changing function may render the function\n     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\n     */\n    function _values(Set storage set) private view returns (bytes32[] memory) {\n        return set._values;\n    }\n\n    /**\n     * @dev Return a slice of the set in an array\n     *\n     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\n     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\n     * this function has an unbounded cost, and using it as part of a state-changing function may render the function\n     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\n     */\n    function _values(Set storage set, uint256 start, uint256 end) private view returns (bytes32[] memory) {\n        unchecked {\n            end = Math.min(end, _length(set));\n            start = Math.min(start, end);\n\n            uint256 len = end - start;\n            bytes32[] memory result = new bytes32[](len);\n            for (uint256 i = 0; i < len; ++i) {\n                result[i] = Arrays.unsafeAccess(set._values, start + i).value;\n            }\n            return result;\n        }\n    }\n\n    // Bytes32Set\n\n    struct Bytes32Set {\n        Set _inner;\n    }\n\n    /**\n     * @dev Add a value to a set. O(1).\n     *\n     * Returns true if the value was added to the set, that is if it was not\n     * already present.\n     */\n    function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {\n        return _add(set._inner, value);\n    }\n\n    /**\n     * @dev Removes a value from a set. O(1).\n     *\n     * Returns true if the value was removed from the set, that is if it was\n     * present.\n     */\n    function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {\n        return _remove(set._inner, value);\n    }\n\n    /**\n     * @dev Removes all the values from a set. O(n).\n     *\n     * WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the\n     * function uncallable if the set grows to the point where clearing it consumes too much gas to fit in a block.\n     */\n    function clear(Bytes32Set storage set) internal {\n        _clear(set._inner);\n    }\n\n    /**\n     * @dev Returns true if the value is in the set. O(1).\n     */\n    function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {\n        return _contains(set._inner, value);\n    }\n\n    /**\n     * @dev Returns the number of values in the set. O(1).\n     */\n    function length(Bytes32Set storage set) internal view returns (uint256) {\n        return _length(set._inner);\n    }\n\n    /**\n     * @dev Returns the value stored at position `index` in the set. O(1).\n     *\n     * Note that there are no guarantees on the ordering of values inside the\n     * array, and it may change when more values are added or removed.\n     *\n     * Requirements:\n     *\n     * - `index` must be strictly less than {length}.\n     */\n    function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {\n        return _at(set._inner, index);\n    }\n\n    /**\n     * @dev Return the entire set in an array\n     *\n     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\n     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\n     * this function has an unbounded cost, and using it as part of a state-changing function may render the function\n     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\n     */\n    function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {\n        bytes32[] memory store = _values(set._inner);\n        bytes32[] memory result;\n\n        assembly (\"memory-safe\") {\n            result := store\n        }\n\n        return result;\n    }\n\n    /**\n     * @dev Return a slice of the set in an array\n     *\n     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\n     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\n     * this function has an unbounded cost, and using it as part of a state-changing function may render the function\n     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\n     */\n    function values(Bytes32Set storage set, uint256 start, uint256 end) internal view returns (bytes32[] memory) {\n        bytes32[] memory store = _values(set._inner, start, end);\n        bytes32[] memory result;\n\n        assembly (\"memory-safe\") {\n            result := store\n        }\n\n        return result;\n    }\n\n    // Bytes4Set\n\n    struct Bytes4Set {\n        Set _inner;\n    }\n\n    /**\n     * @dev Add a value to a set. O(1).\n     *\n     * Returns true if the value was added to the set, that is if it was not\n     * already present.\n     */\n    function add(Bytes4Set storage set, bytes4 value) internal returns (bool) {\n        return _add(set._inner, bytes32(value));\n    }\n\n    /**\n     * @dev Removes a value from a set. O(1).\n     *\n     * Returns true if the value was removed from the set, that is if it was\n     * present.\n     */\n    function remove(Bytes4Set storage set, bytes4 value) internal returns (bool) {\n        return _remove(set._inner, bytes32(value));\n    }\n\n    /**\n     * @dev Removes all the values from a set. O(n).\n     *\n     * WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the\n     * function uncallable if the set grows to the point where clearing it consumes too much gas to fit in a block.\n     */\n    function clear(Bytes4Set storage set) internal {\n        _clear(set._inner);\n    }\n\n    /**\n     * @dev Returns true if the value is in the set. O(1).\n     */\n    function contains(Bytes4Set storage set, bytes4 value) internal view returns (bool) {\n        return _contains(set._inner, bytes32(value));\n    }\n\n    /**\n     * @dev Returns the number of values in the set. O(1).\n     */\n    function length(Bytes4Set storage set) internal view returns (uint256) {\n        return _length(set._inner);\n    }\n\n    /**\n     * @dev Returns the value stored at position `index` in the set. O(1).\n     *\n     * Note that there are no guarantees on the ordering of values inside the\n     * array, and it may change when more values are added or removed.\n     *\n     * Requirements:\n     *\n     * - `index` must be strictly less than {length}.\n     */\n    function at(Bytes4Set storage set, uint256 index) internal view returns (bytes4) {\n        return bytes4(_at(set._inner, index));\n    }\n\n    /**\n     * @dev Return the entire set in an array\n     *\n     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\n     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\n     * this function has an unbounded cost, and using it as part of a state-changing function may render the function\n     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\n     */\n    function values(Bytes4Set storage set) internal view returns (bytes4[] memory) {\n        bytes32[] memory store = _values(set._inner);\n        bytes4[] memory result;\n\n        assembly (\"memory-safe\") {\n            result := store\n        }\n\n        return result;\n    }\n\n    /**\n     * @dev Return a slice of the set in an array\n     *\n     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\n     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\n     * this function has an unbounded cost, and using it as part of a state-changing function may render the function\n     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\n     */\n    function values(Bytes4Set storage set, uint256 start, uint256 end) internal view returns (bytes4[] memory) {\n        bytes32[] memory store = _values(set._inner, start, end);\n        bytes4[] memory result;\n\n        assembly (\"memory-safe\") {\n            result := store\n        }\n\n        return result;\n    }\n\n    // AddressSet\n\n    struct AddressSet {\n        Set _inner;\n    }\n\n    /**\n     * @dev Add a value to a set. O(1).\n     *\n     * Returns true if the value was added to the set, that is if it was not\n     * already present.\n     */\n    function add(AddressSet storage set, address value) internal returns (bool) {\n        return _add(set._inner, bytes32(uint256(uint160(value))));\n    }\n\n    /**\n     * @dev Removes a value from a set. O(1).\n     *\n     * Returns true if the value was removed from the set, that is if it was\n     * present.\n     */\n    function remove(AddressSet storage set, address value) internal returns (bool) {\n        return _remove(set._inner, bytes32(uint256(uint160(value))));\n    }\n\n    /**\n     * @dev Removes all the values from a set. O(n).\n     *\n     * WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the\n     * function uncallable if the set grows to the point where clearing it consumes too much gas to fit in a block.\n     */\n    function clear(AddressSet storage set) internal {\n        _clear(set._inner);\n    }\n\n    /**\n     * @dev Returns true if the value is in the set. O(1).\n     */\n    function contains(AddressSet storage set, address value) internal view returns (bool) {\n        return _contains(set._inner, bytes32(uint256(uint160(value))));\n    }\n\n    /**\n     * @dev Returns the number of values in the set. O(1).\n     */\n    function length(AddressSet storage set) internal view returns (uint256) {\n        return _length(set._inner);\n    }\n\n    /**\n     * @dev Returns the value stored at position `index` in the set. O(1).\n     *\n     * Note that there are no guarantees on the ordering of values inside the\n     * array, and it may change when more values are added or removed.\n     *\n     * Requirements:\n     *\n     * - `index` must be strictly less than {length}.\n     */\n    function at(AddressSet storage set, uint256 index) internal view returns (address) {\n        return address(uint160(uint256(_at(set._inner, index))));\n    }\n\n    /**\n     * @dev Return the entire set in an array\n     *\n     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\n     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\n     * this function has an unbounded cost, and using it as part of a state-changing function may render the function\n     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\n     */\n    function values(AddressSet storage set) internal view returns (address[] memory) {\n        bytes32[] memory store = _values(set._inner);\n        address[] memory result;\n\n        assembly (\"memory-safe\") {\n            result := store\n        }\n\n        return result;\n    }\n\n    /**\n     * @dev Return a slice of the set in an array\n     *\n     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\n     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\n     * this function has an unbounded cost, and using it as part of a state-changing function may render the function\n     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\n     */\n    function values(AddressSet storage set, uint256 start, uint256 end) internal view returns (address[] memory) {\n        bytes32[] memory store = _values(set._inner, start, end);\n        address[] memory result;\n\n        assembly (\"memory-safe\") {\n            result := store\n        }\n\n        return result;\n    }\n\n    // UintSet\n\n    struct UintSet {\n        Set _inner;\n    }\n\n    /**\n     * @dev Add a value to a set. O(1).\n     *\n     * Returns true if the value was added to the set, that is if it was not\n     * already present.\n     */\n    function add(UintSet storage set, uint256 value) internal returns (bool) {\n        return _add(set._inner, bytes32(value));\n    }\n\n    /**\n     * @dev Removes a value from a set. O(1).\n     *\n     * Returns true if the value was removed from the set, that is if it was\n     * present.\n     */\n    function remove(UintSet storage set, uint256 value) internal returns (bool) {\n        return _remove(set._inner, bytes32(value));\n    }\n\n    /**\n     * @dev Removes all the values from a set. O(n).\n     *\n     * WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the\n     * function uncallable if the set grows to the point where clearing it consumes too much gas to fit in a block.\n     */\n    function clear(UintSet storage set) internal {\n        _clear(set._inner);\n    }\n\n    /**\n     * @dev Returns true if the value is in the set. O(1).\n     */\n    function contains(UintSet storage set, uint256 value) internal view returns (bool) {\n        return _contains(set._inner, bytes32(value));\n    }\n\n    /**\n     * @dev Returns the number of values in the set. O(1).\n     */\n    function length(UintSet storage set) internal view returns (uint256) {\n        return _length(set._inner);\n    }\n\n    /**\n     * @dev Returns the value stored at position `index` in the set. O(1).\n     *\n     * Note that there are no guarantees on the ordering of values inside the\n     * array, and it may change when more values are added or removed.\n     *\n     * Requirements:\n     *\n     * - `index` must be strictly less than {length}.\n     */\n    function at(UintSet storage set, uint256 index) internal view returns (uint256) {\n        return uint256(_at(set._inner, index));\n    }\n\n    /**\n     * @dev Return the entire set in an array\n     *\n     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\n     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\n     * this function has an unbounded cost, and using it as part of a state-changing function may render the function\n     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\n     */\n    function values(UintSet storage set) internal view returns (uint256[] memory) {\n        bytes32[] memory store = _values(set._inner);\n        uint256[] memory result;\n\n        assembly (\"memory-safe\") {\n            result := store\n        }\n\n        return result;\n    }\n\n    /**\n     * @dev Return a slice of the set in an array\n     *\n     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\n     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\n     * this function has an unbounded cost, and using it as part of a state-changing function may render the function\n     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\n     */\n    function values(UintSet storage set, uint256 start, uint256 end) internal view returns (uint256[] memory) {\n        bytes32[] memory store = _values(set._inner, start, end);\n        uint256[] memory result;\n\n        assembly (\"memory-safe\") {\n            result := store\n        }\n\n        return result;\n    }\n\n    struct StringSet {\n        // Storage of set values\n        string[] _values;\n        // Position is the index of the value in the `values` array plus 1.\n        // Position 0 is used to mean a value is not in the set.\n        mapping(string value => uint256) _positions;\n    }\n\n    /**\n     * @dev Add a value to a set. O(1).\n     *\n     * Returns true if the value was added to the set, that is if it was not\n     * already present.\n     */\n    function add(StringSet storage set, string memory value) internal returns (bool) {\n        if (!contains(set, value)) {\n            set._values.push(value);\n            // The value is stored at length-1, but we add 1 to all indexes\n            // and use 0 as a sentinel value\n            set._positions[value] = set._values.length;\n            return true;\n        } else {\n            return false;\n        }\n    }\n\n    /**\n     * @dev Removes a value from a set. O(1).\n     *\n     * Returns true if the value was removed from the set, that is if it was\n     * present.\n     */\n    function remove(StringSet storage set, string memory value) internal returns (bool) {\n        // We cache the value's position to prevent multiple reads from the same storage slot\n        uint256 position = set._positions[value];\n\n        if (position != 0) {\n            // Equivalent to contains(set, value)\n            // To delete an element from the _values array in O(1), we swap the element to delete with the last one in\n            // the array, and then remove the last element (sometimes called as 'swap and pop').\n            // This modifies the order of the array, as noted in {at}.\n\n            uint256 valueIndex = position - 1;\n            uint256 lastIndex = set._values.length - 1;\n\n            if (valueIndex != lastIndex) {\n                string memory lastValue = set._values[lastIndex];\n\n                // Move the lastValue to the index where the value to delete is\n                set._values[valueIndex] = lastValue;\n                // Update the tracked position of the lastValue (that was just moved)\n                set._positions[lastValue] = position;\n            }\n\n            // Delete the slot where the moved value was stored\n            set._values.pop();\n\n            // Delete the tracked position for the deleted slot\n            delete set._positions[value];\n\n            return true;\n        } else {\n            return false;\n        }\n    }\n\n    /**\n     * @dev Removes all the values from a set. O(n).\n     *\n     * WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the\n     * function uncallable if the set grows to the point where clearing it consumes too much gas to fit in a block.\n     */\n    function clear(StringSet storage set) internal {\n        uint256 len = length(set);\n        for (uint256 i = 0; i < len; ++i) {\n            delete set._positions[set._values[i]];\n        }\n        Arrays.unsafeSetLength(set._values, 0);\n    }\n\n    /**\n     * @dev Returns true if the value is in the set. O(1).\n     */\n    function contains(StringSet storage set, string memory value) internal view returns (bool) {\n        return set._positions[value] != 0;\n    }\n\n    /**\n     * @dev Returns the number of values on the set. O(1).\n     */\n    function length(StringSet storage set) internal view returns (uint256) {\n        return set._values.length;\n    }\n\n    /**\n     * @dev Returns the value stored at position `index` in the set. O(1).\n     *\n     * Note that there are no guarantees on the ordering of values inside the\n     * array, and it may change when more values are added or removed.\n     *\n     * Requirements:\n     *\n     * - `index` must be strictly less than {length}.\n     */\n    function at(StringSet storage set, uint256 index) internal view returns (string memory) {\n        return set._values[index];\n    }\n\n    /**\n     * @dev Return the entire set in an array\n     *\n     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\n     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\n     * this function has an unbounded cost, and using it as part of a state-changing function may render the function\n     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\n     */\n    function values(StringSet storage set) internal view returns (string[] memory) {\n        return set._values;\n    }\n\n    /**\n     * @dev Return a slice of the set in an array\n     *\n     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\n     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\n     * this function has an unbounded cost, and using it as part of a state-changing function may render the function\n     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\n     */\n    function values(StringSet storage set, uint256 start, uint256 end) internal view returns (string[] memory) {\n        unchecked {\n            end = Math.min(end, length(set));\n            start = Math.min(start, end);\n\n            uint256 len = end - start;\n            string[] memory result = new string[](len);\n            for (uint256 i = 0; i < len; ++i) {\n                result[i] = Arrays.unsafeAccess(set._values, start + i).value;\n            }\n            return result;\n        }\n    }\n\n    struct BytesSet {\n        // Storage of set values\n        bytes[] _values;\n        // Position is the index of the value in the `values` array plus 1.\n        // Position 0 is used to mean a value is not in the set.\n        mapping(bytes value => uint256) _positions;\n    }\n\n    /**\n     * @dev Add a value to a set. O(1).\n     *\n     * Returns true if the value was added to the set, that is if it was not\n     * already present.\n     */\n    function add(BytesSet storage set, bytes memory value) internal returns (bool) {\n        if (!contains(set, value)) {\n            set._values.push(value);\n            // The value is stored at length-1, but we add 1 to all indexes\n            // and use 0 as a sentinel value\n            set._positions[value] = set._values.length;\n            return true;\n        } else {\n            return false;\n        }\n    }\n\n    /**\n     * @dev Removes a value from a set. O(1).\n     *\n     * Returns true if the value was removed from the set, that is if it was\n     * present.\n     */\n    function remove(BytesSet storage set, bytes memory value) internal returns (bool) {\n        // We cache the value's position to prevent multiple reads from the same storage slot\n        uint256 position = set._positions[value];\n\n        if (position != 0) {\n            // Equivalent to contains(set, value)\n            // To delete an element from the _values array in O(1), we swap the element to delete with the last one in\n            // the array, and then remove the last element (sometimes called as 'swap and pop').\n            // This modifies the order of the array, as noted in {at}.\n\n            uint256 valueIndex = position - 1;\n            uint256 lastIndex = set._values.length - 1;\n\n            if (valueIndex != lastIndex) {\n                bytes memory lastValue = set._values[lastIndex];\n\n                // Move the lastValue to the index where the value to delete is\n                set._values[valueIndex] = lastValue;\n                // Update the tracked position of the lastValue (that was just moved)\n                set._positions[lastValue] = position;\n            }\n\n            // Delete the slot where the moved value was stored\n            set._values.pop();\n\n            // Delete the tracked position for the deleted slot\n            delete set._positions[value];\n\n            return true;\n        } else {\n            return false;\n        }\n    }\n\n    /**\n     * @dev Removes all the values from a set. O(n).\n     *\n     * WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the\n     * function uncallable if the set grows to the point where clearing it consumes too much gas to fit in a block.\n     */\n    function clear(BytesSet storage set) internal {\n        uint256 len = length(set);\n        for (uint256 i = 0; i < len; ++i) {\n            delete set._positions[set._values[i]];\n        }\n        Arrays.unsafeSetLength(set._values, 0);\n    }\n\n    /**\n     * @dev Returns true if the value is in the set. O(1).\n     */\n    function contains(BytesSet storage set, bytes memory value) internal view returns (bool) {\n        return set._positions[value] != 0;\n    }\n\n    /**\n     * @dev Returns the number of values on the set. O(1).\n     */\n    function length(BytesSet storage set) internal view returns (uint256) {\n        return set._values.length;\n    }\n\n    /**\n     * @dev Returns the value stored at position `index` in the set. O(1).\n     *\n     * Note that there are no guarantees on the ordering of values inside the\n     * array, and it may change when more values are added or removed.\n     *\n     * Requirements:\n     *\n     * - `index` must be strictly less than {length}.\n     */\n    function at(BytesSet storage set, uint256 index) internal view returns (bytes memory) {\n        return set._values[index];\n    }\n\n    /**\n     * @dev Return the entire set in an array\n     *\n     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\n     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\n     * this function has an unbounded cost, and using it as part of a state-changing function may render the function\n     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\n     */\n    function values(BytesSet storage set) internal view returns (bytes[] memory) {\n        return set._values;\n    }\n\n    /**\n     * @dev Return a slice of the set in an array\n     *\n     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\n     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\n     * this function has an unbounded cost, and using it as part of a state-changing function may render the function\n     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\n     */\n    function values(BytesSet storage set, uint256 start, uint256 end) internal view returns (bytes[] memory) {\n        unchecked {\n            end = Math.min(end, length(set));\n            start = Math.min(start, end);\n\n            uint256 len = end - start;\n            bytes[] memory result = new bytes[](len);\n            for (uint256 i = 0; i < len; ++i) {\n                result[i] = Arrays.unsafeAccess(set._values, start + i).value;\n            }\n            return result;\n        }\n    }\n}\n"},{"file_path":"src/interfaces/IFarm.sol","source_code":"// SPDX-License-Identifier: MIT\npragma solidity 0.8.28;\n\n/// @notice Interface for an InfiniFi Farm contract\ninterface IFarm {\n    /// @notice emitted when there is a deposit of withdrawal from the farm\n    event AssetsUpdated(uint256 timestamp, uint256 assetsBefore, uint256 assetsAfter);\n\n    // --------------------------------------------------------------------\n    // Accounting\n    // --------------------------------------------------------------------\n\n    /// @notice the cap of the farm\n    function cap() external view returns (uint256);\n\n    /// @notice the asset used by deposits and withdrawals in the farm\n    function assetToken() external view returns (address);\n\n    /// @notice the total assets in the farm, reported as a balance of asset()\n    function assets() external view returns (uint256);\n\n    // --------------------------------------------------------------------\n    // Adapter logic\n    // --------------------------------------------------------------------\n    /// @notice deposit all asset() held by the contract into the farm\n    function deposit() external;\n\n    /// @notice Returns the max deposit amount for the underlying protocol\n    function maxDeposit() external view returns (uint256);\n\n    /// @notice withdraw an amount of the asset() from the farm\n    /// @param amount Amount of assets to withdraw\n    /// @param to Address to receive the withdrawn assets\n    function withdraw(uint256 amount, address to) external;\n\n    /// @notice available number of assetToken() withdrawable instantly from the farm\n    function liquidity() external view returns (uint256);\n}\n"},{"file_path":"src/libraries/EpochLib.sol","source_code":"// SPDX-License-Identifier: MIT\npragma solidity 0.8.28;\n\nlibrary EpochLib {\n    uint256 internal constant EPOCH = 1 weeks;\n    uint256 internal constant EPOCH_OFFSET = 3 days;\n\n    /// @notice epoch start (start of the epoch) for a given timestamp\n    function epoch(uint256 _timestamp) internal pure returns (uint256) {\n        return (_timestamp - EPOCH_OFFSET) / EPOCH;\n    }\n\n    /// @notice epoch end (end of the epoch) for a given timestamp\n    function nextEpoch(uint256 _timestamp) internal pure returns (uint256) {\n        return epoch(_timestamp) + 1;\n    }\n\n    /// @notice Convert epoch to timestamp taking into account the epoch offset\n    function epochToTimestamp(uint256 _epoch) internal pure returns (uint256) {\n        return _epoch * EPOCH + EPOCH_OFFSET;\n    }\n}\n"},{"file_path":"lib/openzeppelin-contracts/contracts/utils/ShortStrings.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.5.0) (utils/ShortStrings.sol)\n\npragma solidity ^0.8.20;\n\nimport {StorageSlot} from \"./StorageSlot.sol\";\n\n// | string  | 0xAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA   |\n// | length  | 0x                                                              BB |\ntype ShortString is bytes32;\n\n/**\n * @dev This library provides functions to convert short memory strings\n * into a `ShortString` type that can be used as an immutable variable.\n *\n * Strings of arbitrary length can be optimized using this library if\n * they are short enough (up to 31 bytes) by packing them with their\n * length (1 byte) in a single EVM word (32 bytes). Additionally, a\n * fallback mechanism can be used for every other case.\n *\n * Usage example:\n *\n * ```solidity\n * contract Named {\n *     using ShortStrings for *;\n *\n *     ShortString private immutable _name;\n *     string private _nameFallback;\n *\n *     constructor(string memory contractName) {\n *         _name = contractName.toShortStringWithFallback(_nameFallback);\n *     }\n *\n *     function name() external view returns (string memory) {\n *         return _name.toStringWithFallback(_nameFallback);\n *     }\n * }\n * ```\n */\nlibrary ShortStrings {\n    // Used as an identifier for strings longer than 31 bytes.\n    bytes32 private constant FALLBACK_SENTINEL = 0x00000000000000000000000000000000000000000000000000000000000000FF;\n\n    error StringTooLong(string str);\n    error InvalidShortString();\n\n    /**\n     * @dev Encode a string of at most 31 chars into a `ShortString`.\n     *\n     * This will trigger a `StringTooLong` error is the input string is too long.\n     */\n    function toShortString(string memory str) internal pure returns (ShortString) {\n        bytes memory bstr = bytes(str);\n        if (bstr.length > 0x1f) {\n            revert StringTooLong(str);\n        }\n        return ShortString.wrap(bytes32(uint256(bytes32(bstr)) | bstr.length));\n    }\n\n    /**\n     * @dev Decode a `ShortString` back to a \"normal\" string.\n     */\n    function toString(ShortString sstr) internal pure returns (string memory) {\n        uint256 len = byteLength(sstr);\n        // using `new string(len)` would work locally but is not memory safe.\n        string memory str = new string(0x20);\n        assembly (\"memory-safe\") {\n            mstore(str, len)\n            mstore(add(str, 0x20), sstr)\n        }\n        return str;\n    }\n\n    /**\n     * @dev Return the length of a `ShortString`.\n     */\n    function byteLength(ShortString sstr) internal pure returns (uint256) {\n        uint256 result = uint256(ShortString.unwrap(sstr)) & 0xFF;\n        if (result > 0x1f) {\n            revert InvalidShortString();\n        }\n        return result;\n    }\n\n    /**\n     * @dev Encode a string into a `ShortString`, or write it to storage if it is too long.\n     */\n    function toShortStringWithFallback(string memory value, string storage store) internal returns (ShortString) {\n        if (bytes(value).length < 0x20) {\n            return toShortString(value);\n        } else {\n            StorageSlot.getStringSlot(store).value = value;\n            return ShortString.wrap(FALLBACK_SENTINEL);\n        }\n    }\n\n    /**\n     * @dev Decode a string that was encoded to `ShortString` or written to storage using {toShortStringWithFallback}.\n     */\n    function toStringWithFallback(ShortString value, string storage store) internal pure returns (string memory) {\n        if (ShortString.unwrap(value) != FALLBACK_SENTINEL) {\n            return toString(value);\n        } else {\n            return store;\n        }\n    }\n\n    /**\n     * @dev Return the length of a string that was encoded to `ShortString` or written to storage using\n     * {toShortStringWithFallback}.\n     *\n     * WARNING: This will return the \"byte length\" of the string. This may not reflect the actual length in terms of\n     * actual characters as the UTF-8 encoding of a single character can span over multiple bytes.\n     */\n    function byteLengthWithFallback(ShortString value, string storage store) internal view returns (uint256) {\n        if (ShortString.unwrap(value) != FALLBACK_SENTINEL) {\n            return byteLength(value);\n        } else {\n            return bytes(store).length;\n        }\n    }\n}\n"},{"file_path":"lib/openzeppelin-contracts/contracts/interfaces/IERC20.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC20.sol)\n\npragma solidity >=0.4.16;\n\nimport {IERC20} from \"../token/ERC20/IERC20.sol\";\n"},{"file_path":"src/tokens/LockedPositionToken.sol","source_code":"// SPDX-License-Identifier: MIT\npragma solidity 0.8.28;\n\nimport {ERC20} from \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\nimport {ERC20Permit} from \"@openzeppelin/contracts/token/ERC20/extensions/ERC20Permit.sol\";\nimport {ERC20Burnable} from \"@openzeppelin/contracts/token/ERC20/extensions/ERC20Burnable.sol\";\n\nimport {EpochLib} from \"@libraries/EpochLib.sol\";\nimport {CoreRoles} from \"@libraries/CoreRoles.sol\";\nimport {CoreControlled} from \"@core/CoreControlled.sol\";\n\n/// @notice InfiniFi Locked Position Token.\ncontract LockedPositionToken is CoreControlled, ERC20Permit, ERC20Burnable {\n    /// @notice thrown when a user with transfer restrictions tries to transfer\n    error TransferRestrictedUntil(address user, uint256 timestamp);\n\n    /// @notice mapping of transfer restrictions: from address to timestamp after which transfers/redemptions are allowed\n    mapping(address => uint256) public transferRestrictions;\n\n    constructor(address _core, string memory _name, string memory _symbol)\n        CoreControlled(_core)\n        ERC20(_name, _symbol)\n        ERC20Permit(_name)\n    {}\n\n    function mint(address _to, uint256 _amount) external onlyCoreRole(CoreRoles.LOCKED_TOKEN_MANAGER) {\n        _mint(_to, _amount);\n    }\n\n    function burn(uint256 _value) public override onlyCoreRole(CoreRoles.LOCKED_TOKEN_MANAGER) {\n        _burn(_msgSender(), _value);\n    }\n\n    function burnFrom(address _account, uint256 _value) public override onlyCoreRole(CoreRoles.LOCKED_TOKEN_MANAGER) {\n        _spendAllowance(_account, _msgSender(), _value);\n        _burn(_account, _value);\n    }\n\n    /// @notice restricts transfers until the next epoch\n    function restrictTransferUntilNextEpoch(address _user) external onlyCoreRole(CoreRoles.TRANSFER_RESTRICTOR) {\n        transferRestrictions[_user] = EpochLib.epochToTimestamp(EpochLib.nextEpoch(block.timestamp));\n    }\n\n    /// ---------------------------------------------------------------------------\n    /// Transfer restrictions\n    /// ---------------------------------------------------------------------------\n\n    function _update(address _from, address _to, uint256 _value) internal override {\n        uint256 restriction = transferRestrictions[_from];\n        // if it's 0, storage is unset so user has no transfer restriction\n        if (restriction > 0) {\n            require(block.timestamp >= restriction, TransferRestrictedUntil(_from, restriction));\n        }\n\n        return ERC20._update(_from, _to, _value);\n    }\n}\n"},{"file_path":"lib/openzeppelin-contracts/contracts/interfaces/IERC165.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC165.sol)\n\npragma solidity >=0.4.16;\n\nimport {IERC165} from \"../utils/introspection/IERC165.sol\";\n"},{"file_path":"lib/openzeppelin-contracts/contracts/utils/Arrays.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.5.0) (utils/Arrays.sol)\n// This file was procedurally generated from scripts/generate/templates/Arrays.js.\n\npragma solidity ^0.8.24;\n\nimport {Comparators} from \"./Comparators.sol\";\nimport {SlotDerivation} from \"./SlotDerivation.sol\";\nimport {StorageSlot} from \"./StorageSlot.sol\";\nimport {Math} from \"./math/Math.sol\";\n\n/**\n * @dev Collection of functions related to array types.\n */\nlibrary Arrays {\n    using SlotDerivation for bytes32;\n    using StorageSlot for bytes32;\n\n    /**\n     * @dev Sort an array of uint256 (in memory) following the provided comparator function.\n     *\n     * This function does the sorting \"in place\", meaning that it overrides the input. The object is returned for\n     * convenience, but that returned value can be discarded safely if the caller has a memory pointer to the array.\n     *\n     * NOTE: this function's cost is `O(n · log(n))` in average and `O(n²)` in the worst case, with n the length of the\n     * array. Using it in view functions that are executed through `eth_call` is safe, but one should be very careful\n     * when executing this as part of a transaction. If the array being sorted is too large, the sort operation may\n     * consume more gas than is available in a block, leading to potential DoS.\n     *\n     * IMPORTANT: Consider memory side-effects when using custom comparator functions that access memory in an unsafe way.\n     */\n    function sort(\n        uint256[] memory array,\n        function(uint256, uint256) pure returns (bool) comp\n    ) internal pure returns (uint256[] memory) {\n        _quickSort(_begin(array), _end(array), comp);\n        return array;\n    }\n\n    /**\n     * @dev Variant of {sort} that sorts an array of uint256 in increasing order.\n     */\n    function sort(uint256[] memory array) internal pure returns (uint256[] memory) {\n        sort(array, Comparators.lt);\n        return array;\n    }\n\n    /**\n     * @dev Sort an array of address (in memory) following the provided comparator function.\n     *\n     * This function does the sorting \"in place\", meaning that it overrides the input. The object is returned for\n     * convenience, but that returned value can be discarded safely if the caller has a memory pointer to the array.\n     *\n     * NOTE: this function's cost is `O(n · log(n))` in average and `O(n²)` in the worst case, with n the length of the\n     * array. Using it in view functions that are executed through `eth_call` is safe, but one should be very careful\n     * when executing this as part of a transaction. If the array being sorted is too large, the sort operation may\n     * consume more gas than is available in a block, leading to potential DoS.\n     *\n     * IMPORTANT: Consider memory side-effects when using custom comparator functions that access memory in an unsafe way.\n     */\n    function sort(\n        address[] memory array,\n        function(address, address) pure returns (bool) comp\n    ) internal pure returns (address[] memory) {\n        sort(_castToUint256Array(array), _castToUint256Comp(comp));\n        return array;\n    }\n\n    /**\n     * @dev Variant of {sort} that sorts an array of address in increasing order.\n     */\n    function sort(address[] memory array) internal pure returns (address[] memory) {\n        sort(_castToUint256Array(array), Comparators.lt);\n        return array;\n    }\n\n    /**\n     * @dev Sort an array of bytes32 (in memory) following the provided comparator function.\n     *\n     * This function does the sorting \"in place\", meaning that it overrides the input. The object is returned for\n     * convenience, but that returned value can be discarded safely if the caller has a memory pointer to the array.\n     *\n     * NOTE: this function's cost is `O(n · log(n))` in average and `O(n²)` in the worst case, with n the length of the\n     * array. Using it in view functions that are executed through `eth_call` is safe, but one should be very careful\n     * when executing this as part of a transaction. If the array being sorted is too large, the sort operation may\n     * consume more gas than is available in a block, leading to potential DoS.\n     *\n     * IMPORTANT: Consider memory side-effects when using custom comparator functions that access memory in an unsafe way.\n     */\n    function sort(\n        bytes32[] memory array,\n        function(bytes32, bytes32) pure returns (bool) comp\n    ) internal pure returns (bytes32[] memory) {\n        sort(_castToUint256Array(array), _castToUint256Comp(comp));\n        return array;\n    }\n\n    /**\n     * @dev Variant of {sort} that sorts an array of bytes32 in increasing order.\n     */\n    function sort(bytes32[] memory array) internal pure returns (bytes32[] memory) {\n        sort(_castToUint256Array(array), Comparators.lt);\n        return array;\n    }\n\n    /**\n     * @dev Performs a quick sort of a segment of memory. The segment sorted starts at `begin` (inclusive), and stops\n     * at end (exclusive). Sorting follows the `comp` comparator.\n     *\n     * Invariant: `begin <= end`. This is the case when initially called by {sort} and is preserved in subcalls.\n     *\n     * IMPORTANT: Memory locations between `begin` and `end` are not validated/zeroed. This function should\n     * be used only if the limits are within a memory array.\n     */\n    function _quickSort(uint256 begin, uint256 end, function(uint256, uint256) pure returns (bool) comp) private pure {\n        unchecked {\n            if (end - begin < 0x40) return;\n\n            // Use first element as pivot\n            uint256 pivot = _mload(begin);\n            // Position where the pivot should be at the end of the loop\n            uint256 pos = begin;\n\n            for (uint256 it = begin + 0x20; it < end; it += 0x20) {\n                if (comp(_mload(it), pivot)) {\n                    // If the value stored at the iterator's position comes before the pivot, we increment the\n                    // position of the pivot and move the value there.\n                    pos += 0x20;\n                    _swap(pos, it);\n                }\n            }\n\n            _swap(begin, pos); // Swap pivot into place\n            _quickSort(begin, pos, comp); // Sort the left side of the pivot\n            _quickSort(pos + 0x20, end, comp); // Sort the right side of the pivot\n        }\n    }\n\n    /**\n     * @dev Pointer to the memory location of the first element of `array`.\n     */\n    function _begin(uint256[] memory array) private pure returns (uint256 ptr) {\n        assembly (\"memory-safe\") {\n            ptr := add(array, 0x20)\n        }\n    }\n\n    /**\n     * @dev Pointer to the memory location of the first memory word (32bytes) after `array`. This is the memory word\n     * that comes just after the last element of the array.\n     */\n    function _end(uint256[] memory array) private pure returns (uint256 ptr) {\n        unchecked {\n            return _begin(array) + array.length * 0x20;\n        }\n    }\n\n    /**\n     * @dev Load memory word (as a uint256) at location `ptr`.\n     */\n    function _mload(uint256 ptr) private pure returns (uint256 value) {\n        assembly {\n            value := mload(ptr)\n        }\n    }\n\n    /**\n     * @dev Swaps the elements memory location `ptr1` and `ptr2`.\n     */\n    function _swap(uint256 ptr1, uint256 ptr2) private pure {\n        assembly {\n            let value1 := mload(ptr1)\n            let value2 := mload(ptr2)\n            mstore(ptr1, value2)\n            mstore(ptr2, value1)\n        }\n    }\n\n    /// @dev Helper: low level cast address memory array to uint256 memory array\n    function _castToUint256Array(address[] memory input) private pure returns (uint256[] memory output) {\n        assembly {\n            output := input\n        }\n    }\n\n    /// @dev Helper: low level cast bytes32 memory array to uint256 memory array\n    function _castToUint256Array(bytes32[] memory input) private pure returns (uint256[] memory output) {\n        assembly {\n            output := input\n        }\n    }\n\n    /// @dev Helper: low level cast address comp function to uint256 comp function\n    function _castToUint256Comp(\n        function(address, address) pure returns (bool) input\n    ) private pure returns (function(uint256, uint256) pure returns (bool) output) {\n        assembly {\n            output := input\n        }\n    }\n\n    /// @dev Helper: low level cast bytes32 comp function to uint256 comp function\n    function _castToUint256Comp(\n        function(bytes32, bytes32) pure returns (bool) input\n    ) private pure returns (function(uint256, uint256) pure returns (bool) output) {\n        assembly {\n            output := input\n        }\n    }\n\n    /**\n     * @dev Searches a sorted `array` and returns the first index that contains\n     * a value greater or equal to `element`. If no such index exists (i.e. all\n     * values in the array are strictly less than `element`), the array length is\n     * returned. Time complexity O(log n).\n     *\n     * NOTE: The `array` is expected to be sorted in ascending order, and to\n     * contain no repeated elements.\n     *\n     * IMPORTANT: Deprecated. This implementation behaves as {lowerBound} but lacks\n     * support for repeated elements in the array. The {lowerBound} function should\n     * be used instead.\n     */\n    function findUpperBound(uint256[] storage array, uint256 element) internal view returns (uint256) {\n        uint256 low = 0;\n        uint256 high = array.length;\n\n        if (high == 0) {\n            return 0;\n        }\n\n        while (low < high) {\n            uint256 mid = Math.average(low, high);\n\n            // Note that mid will always be strictly less than high (i.e. it will be a valid array index)\n            // because Math.average rounds towards zero (it does integer division with truncation).\n            if (unsafeAccess(array, mid).value > element) {\n                high = mid;\n            } else {\n                low = mid + 1;\n            }\n        }\n\n        // At this point `low` is the exclusive upper bound. We will return the inclusive upper bound.\n        if (low > 0 && unsafeAccess(array, low - 1).value == element) {\n            return low - 1;\n        } else {\n            return low;\n        }\n    }\n\n    /**\n     * @dev Searches an `array` sorted in ascending order and returns the first\n     * index that contains a value greater or equal than `element`. If no such index\n     * exists (i.e. all values in the array are strictly less than `element`), the array\n     * length is returned. Time complexity O(log n).\n     *\n     * See C++'s https://en.cppreference.com/w/cpp/algorithm/lower_bound[lower_bound].\n     */\n    function lowerBound(uint256[] storage array, uint256 element) internal view returns (uint256) {\n        uint256 low = 0;\n        uint256 high = array.length;\n\n        if (high == 0) {\n            return 0;\n        }\n\n        while (low < high) {\n            uint256 mid = Math.average(low, high);\n\n            // Note that mid will always be strictly less than high (i.e. it will be a valid array index)\n            // because Math.average rounds towards zero (it does integer division with truncation).\n            if (unsafeAccess(array, mid).value < element) {\n                // this cannot overflow because mid < high\n                unchecked {\n                    low = mid + 1;\n                }\n            } else {\n                high = mid;\n            }\n        }\n\n        return low;\n    }\n\n    /**\n     * @dev Searches an `array` sorted in ascending order and returns the first\n     * index that contains a value strictly greater than `element`. If no such index\n     * exists (i.e. all values in the array are strictly less than `element`), the array\n     * length is returned. Time complexity O(log n).\n     *\n     * See C++'s https://en.cppreference.com/w/cpp/algorithm/upper_bound[upper_bound].\n     */\n    function upperBound(uint256[] storage array, uint256 element) internal view returns (uint256) {\n        uint256 low = 0;\n        uint256 high = array.length;\n\n        if (high == 0) {\n            return 0;\n        }\n\n        while (low < high) {\n            uint256 mid = Math.average(low, high);\n\n            // Note that mid will always be strictly less than high (i.e. it will be a valid array index)\n            // because Math.average rounds towards zero (it does integer division with truncation).\n            if (unsafeAccess(array, mid).value > element) {\n                high = mid;\n            } else {\n                // this cannot overflow because mid < high\n                unchecked {\n                    low = mid + 1;\n                }\n            }\n        }\n\n        return low;\n    }\n\n    /**\n     * @dev Same as {lowerBound}, but with an array in memory.\n     */\n    function lowerBoundMemory(uint256[] memory array, uint256 element) internal pure returns (uint256) {\n        uint256 low = 0;\n        uint256 high = array.length;\n\n        if (high == 0) {\n            return 0;\n        }\n\n        while (low < high) {\n            uint256 mid = Math.average(low, high);\n\n            // Note that mid will always be strictly less than high (i.e. it will be a valid array index)\n            // because Math.average rounds towards zero (it does integer division with truncation).\n            if (unsafeMemoryAccess(array, mid) < element) {\n                // this cannot overflow because mid < high\n                unchecked {\n                    low = mid + 1;\n                }\n            } else {\n                high = mid;\n            }\n        }\n\n        return low;\n    }\n\n    /**\n     * @dev Same as {upperBound}, but with an array in memory.\n     */\n    function upperBoundMemory(uint256[] memory array, uint256 element) internal pure returns (uint256) {\n        uint256 low = 0;\n        uint256 high = array.length;\n\n        if (high == 0) {\n            return 0;\n        }\n\n        while (low < high) {\n            uint256 mid = Math.average(low, high);\n\n            // Note that mid will always be strictly less than high (i.e. it will be a valid array index)\n            // because Math.average rounds towards zero (it does integer division with truncation).\n            if (unsafeMemoryAccess(array, mid) > element) {\n                high = mid;\n            } else {\n                // this cannot overflow because mid < high\n                unchecked {\n                    low = mid + 1;\n                }\n            }\n        }\n\n        return low;\n    }\n\n    /**\n     * @dev Copies the content of `array`, from `start` (included) to the end of `array` into a new address array in\n     * memory.\n     *\n     * NOTE: replicates the behavior of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice[Javascript's `Array.slice`]\n     */\n    function slice(address[] memory array, uint256 start) internal pure returns (address[] memory) {\n        return slice(array, start, array.length);\n    }\n\n    /**\n     * @dev Copies the content of `array`, from `start` (included) to `end` (excluded) into a new address array in\n     * memory. The `end` argument is truncated to the length of the `array`.\n     *\n     * NOTE: replicates the behavior of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice[Javascript's `Array.slice`]\n     */\n    function slice(address[] memory array, uint256 start, uint256 end) internal pure returns (address[] memory) {\n        // sanitize\n        end = Math.min(end, array.length);\n        start = Math.min(start, end);\n\n        // allocate and copy\n        address[] memory result = new address[](end - start);\n        assembly (\"memory-safe\") {\n            mcopy(add(result, 0x20), add(add(array, 0x20), mul(start, 0x20)), mul(sub(end, start), 0x20))\n        }\n\n        return result;\n    }\n\n    /**\n     * @dev Copies the content of `array`, from `start` (included) to the end of `array` into a new bytes32 array in\n     * memory.\n     *\n     * NOTE: replicates the behavior of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice[Javascript's `Array.slice`]\n     */\n    function slice(bytes32[] memory array, uint256 start) internal pure returns (bytes32[] memory) {\n        return slice(array, start, array.length);\n    }\n\n    /**\n     * @dev Copies the content of `array`, from `start` (included) to `end` (excluded) into a new bytes32 array in\n     * memory. The `end` argument is truncated to the length of the `array`.\n     *\n     * NOTE: replicates the behavior of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice[Javascript's `Array.slice`]\n     */\n    function slice(bytes32[] memory array, uint256 start, uint256 end) internal pure returns (bytes32[] memory) {\n        // sanitize\n        end = Math.min(end, array.length);\n        start = Math.min(start, end);\n\n        // allocate and copy\n        bytes32[] memory result = new bytes32[](end - start);\n        assembly (\"memory-safe\") {\n            mcopy(add(result, 0x20), add(add(array, 0x20), mul(start, 0x20)), mul(sub(end, start), 0x20))\n        }\n\n        return result;\n    }\n\n    /**\n     * @dev Copies the content of `array`, from `start` (included) to the end of `array` into a new uint256 array in\n     * memory.\n     *\n     * NOTE: replicates the behavior of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice[Javascript's `Array.slice`]\n     */\n    function slice(uint256[] memory array, uint256 start) internal pure returns (uint256[] memory) {\n        return slice(array, start, array.length);\n    }\n\n    /**\n     * @dev Copies the content of `array`, from `start` (included) to `end` (excluded) into a new uint256 array in\n     * memory. The `end` argument is truncated to the length of the `array`.\n     *\n     * NOTE: replicates the behavior of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice[Javascript's `Array.slice`]\n     */\n    function slice(uint256[] memory array, uint256 start, uint256 end) internal pure returns (uint256[] memory) {\n        // sanitize\n        end = Math.min(end, array.length);\n        start = Math.min(start, end);\n\n        // allocate and copy\n        uint256[] memory result = new uint256[](end - start);\n        assembly (\"memory-safe\") {\n            mcopy(add(result, 0x20), add(add(array, 0x20), mul(start, 0x20)), mul(sub(end, start), 0x20))\n        }\n\n        return result;\n    }\n\n    /**\n     * @dev Moves the content of `array`, from `start` (included) to the end of `array` to the start of that array.\n     *\n     * NOTE: This function modifies the provided array in place. If you need to preserve the original array, use {slice} instead.\n     * NOTE: replicates the behavior of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice[Javascript's `Array.splice`]\n     */\n    function splice(address[] memory array, uint256 start) internal pure returns (address[] memory) {\n        return splice(array, start, array.length);\n    }\n\n    /**\n     * @dev Moves the content of `array`, from `start` (included) to `end` (excluded) to the start of that array. The\n     * `end` argument is truncated to the length of the `array`.\n     *\n     * NOTE: This function modifies the provided array in place. If you need to preserve the original array, use {slice} instead.\n     * NOTE: replicates the behavior of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice[Javascript's `Array.splice`]\n     */\n    function splice(address[] memory array, uint256 start, uint256 end) internal pure returns (address[] memory) {\n        // sanitize\n        end = Math.min(end, array.length);\n        start = Math.min(start, end);\n\n        // move and resize\n        assembly (\"memory-safe\") {\n            mcopy(add(array, 0x20), add(add(array, 0x20), mul(start, 0x20)), mul(sub(end, start), 0x20))\n            mstore(array, sub(end, start))\n        }\n\n        return array;\n    }\n\n    /**\n     * @dev Replaces elements in `array` starting at `pos` with all elements from `replacement`.\n     *\n     * Parameters are clamped to valid ranges (i.e. `pos` is clamped to `[0, array.length]`).\n     * If `pos >= array.length`, no replacement occurs and the array is returned unchanged.\n     *\n     * NOTE: This function modifies the provided array in place.\n     */\n    function replace(\n        address[] memory array,\n        uint256 pos,\n        address[] memory replacement\n    ) internal pure returns (address[] memory) {\n        return replace(array, pos, replacement, 0, replacement.length);\n    }\n\n    /**\n     * @dev Replaces elements in `array` starting at `pos` with elements from `replacement` starting at `offset`.\n     * Copies at most `length` elements from `replacement` to `array`.\n     *\n     * Parameters are clamped to valid ranges (i.e. `pos` is clamped to `[0, array.length]`, `offset` is\n     * clamped to `[0, replacement.length]`, and `length` is clamped to `min(length, replacement.length - offset,\n     * array.length - pos)`). If `pos >= array.length` or `offset >= replacement.length`, no replacement occurs\n     * and the array is returned unchanged.\n     *\n     * NOTE: This function modifies the provided array in place.\n     */\n    function replace(\n        address[] memory array,\n        uint256 pos,\n        address[] memory replacement,\n        uint256 offset,\n        uint256 length\n    ) internal pure returns (address[] memory) {\n        // sanitize\n        pos = Math.min(pos, array.length);\n        offset = Math.min(offset, replacement.length);\n        length = Math.min(length, Math.min(replacement.length - offset, array.length - pos));\n\n        // allocate and copy\n        assembly (\"memory-safe\") {\n            mcopy(\n                add(add(array, 0x20), mul(pos, 0x20)),\n                add(add(replacement, 0x20), mul(offset, 0x20)),\n                mul(length, 0x20)\n            )\n        }\n\n        return array;\n    }\n\n    /**\n     * @dev Moves the content of `array`, from `start` (included) to the end of `array` to the start of that array.\n     *\n     * NOTE: This function modifies the provided array in place. If you need to preserve the original array, use {slice} instead.\n     * NOTE: replicates the behavior of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice[Javascript's `Array.splice`]\n     */\n    function splice(bytes32[] memory array, uint256 start) internal pure returns (bytes32[] memory) {\n        return splice(array, start, array.length);\n    }\n\n    /**\n     * @dev Moves the content of `array`, from `start` (included) to `end` (excluded) to the start of that array. The\n     * `end` argument is truncated to the length of the `array`.\n     *\n     * NOTE: This function modifies the provided array in place. If you need to preserve the original array, use {slice} instead.\n     * NOTE: replicates the behavior of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice[Javascript's `Array.splice`]\n     */\n    function splice(bytes32[] memory array, uint256 start, uint256 end) internal pure returns (bytes32[] memory) {\n        // sanitize\n        end = Math.min(end, array.length);\n        start = Math.min(start, end);\n\n        // move and resize\n        assembly (\"memory-safe\") {\n            mcopy(add(array, 0x20), add(add(array, 0x20), mul(start, 0x20)), mul(sub(end, start), 0x20))\n            mstore(array, sub(end, start))\n        }\n\n        return array;\n    }\n\n    /**\n     * @dev Replaces elements in `array` starting at `pos` with all elements from `replacement`.\n     *\n     * Parameters are clamped to valid ranges (i.e. `pos` is clamped to `[0, array.length]`).\n     * If `pos >= array.length`, no replacement occurs and the array is returned unchanged.\n     *\n     * NOTE: This function modifies the provided array in place.\n     */\n    function replace(\n        bytes32[] memory array,\n        uint256 pos,\n        bytes32[] memory replacement\n    ) internal pure returns (bytes32[] memory) {\n        return replace(array, pos, replacement, 0, replacement.length);\n    }\n\n    /**\n     * @dev Replaces elements in `array` starting at `pos` with elements from `replacement` starting at `offset`.\n     * Copies at most `length` elements from `replacement` to `array`.\n     *\n     * Parameters are clamped to valid ranges (i.e. `pos` is clamped to `[0, array.length]`, `offset` is\n     * clamped to `[0, replacement.length]`, and `length` is clamped to `min(length, replacement.length - offset,\n     * array.length - pos)`). If `pos >= array.length` or `offset >= replacement.length`, no replacement occurs\n     * and the array is returned unchanged.\n     *\n     * NOTE: This function modifies the provided array in place.\n     */\n    function replace(\n        bytes32[] memory array,\n        uint256 pos,\n        bytes32[] memory replacement,\n        uint256 offset,\n        uint256 length\n    ) internal pure returns (bytes32[] memory) {\n        // sanitize\n        pos = Math.min(pos, array.length);\n        offset = Math.min(offset, replacement.length);\n        length = Math.min(length, Math.min(replacement.length - offset, array.length - pos));\n\n        // allocate and copy\n        assembly (\"memory-safe\") {\n            mcopy(\n                add(add(array, 0x20), mul(pos, 0x20)),\n                add(add(replacement, 0x20), mul(offset, 0x20)),\n                mul(length, 0x20)\n            )\n        }\n\n        return array;\n    }\n\n    /**\n     * @dev Moves the content of `array`, from `start` (included) to the end of `array` to the start of that array.\n     *\n     * NOTE: This function modifies the provided array in place. If you need to preserve the original array, use {slice} instead.\n     * NOTE: replicates the behavior of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice[Javascript's `Array.splice`]\n     */\n    function splice(uint256[] memory array, uint256 start) internal pure returns (uint256[] memory) {\n        return splice(array, start, array.length);\n    }\n\n    /**\n     * @dev Moves the content of `array`, from `start` (included) to `end` (excluded) to the start of that array. The\n     * `end` argument is truncated to the length of the `array`.\n     *\n     * NOTE: This function modifies the provided array in place. If you need to preserve the original array, use {slice} instead.\n     * NOTE: replicates the behavior of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice[Javascript's `Array.splice`]\n     */\n    function splice(uint256[] memory array, uint256 start, uint256 end) internal pure returns (uint256[] memory) {\n        // sanitize\n        end = Math.min(end, array.length);\n        start = Math.min(start, end);\n\n        // move and resize\n        assembly (\"memory-safe\") {\n            mcopy(add(array, 0x20), add(add(array, 0x20), mul(start, 0x20)), mul(sub(end, start), 0x20))\n            mstore(array, sub(end, start))\n        }\n\n        return array;\n    }\n\n    /**\n     * @dev Replaces elements in `array` starting at `pos` with all elements from `replacement`.\n     *\n     * Parameters are clamped to valid ranges (i.e. `pos` is clamped to `[0, array.length]`).\n     * If `pos >= array.length`, no replacement occurs and the array is returned unchanged.\n     *\n     * NOTE: This function modifies the provided array in place.\n     */\n    function replace(\n        uint256[] memory array,\n        uint256 pos,\n        uint256[] memory replacement\n    ) internal pure returns (uint256[] memory) {\n        return replace(array, pos, replacement, 0, replacement.length);\n    }\n\n    /**\n     * @dev Replaces elements in `array` starting at `pos` with elements from `replacement` starting at `offset`.\n     * Copies at most `length` elements from `replacement` to `array`.\n     *\n     * Parameters are clamped to valid ranges (i.e. `pos` is clamped to `[0, array.length]`, `offset` is\n     * clamped to `[0, replacement.length]`, and `length` is clamped to `min(length, replacement.length - offset,\n     * array.length - pos)`). If `pos >= array.length` or `offset >= replacement.length`, no replacement occurs\n     * and the array is returned unchanged.\n     *\n     * NOTE: This function modifies the provided array in place.\n     */\n    function replace(\n        uint256[] memory array,\n        uint256 pos,\n        uint256[] memory replacement,\n        uint256 offset,\n        uint256 length\n    ) internal pure returns (uint256[] memory) {\n        // sanitize\n        pos = Math.min(pos, array.length);\n        offset = Math.min(offset, replacement.length);\n        length = Math.min(length, Math.min(replacement.length - offset, array.length - pos));\n\n        // allocate and copy\n        assembly (\"memory-safe\") {\n            mcopy(\n                add(add(array, 0x20), mul(pos, 0x20)),\n                add(add(replacement, 0x20), mul(offset, 0x20)),\n                mul(length, 0x20)\n            )\n        }\n\n        return array;\n    }\n\n    /**\n     * @dev Access an array in an \"unsafe\" way. Skips solidity \"index-out-of-range\" check.\n     *\n     * WARNING: Only use if you are certain `pos` is lower than the array length.\n     */\n    function unsafeAccess(address[] storage arr, uint256 pos) internal pure returns (StorageSlot.AddressSlot storage) {\n        bytes32 slot;\n        assembly (\"memory-safe\") {\n            slot := arr.slot\n        }\n        return slot.deriveArray().offset(pos).getAddressSlot();\n    }\n\n    /**\n     * @dev Access an array in an \"unsafe\" way. Skips solidity \"index-out-of-range\" check.\n     *\n     * WARNING: Only use if you are certain `pos` is lower than the array length.\n     */\n    function unsafeAccess(bytes32[] storage arr, uint256 pos) internal pure returns (StorageSlot.Bytes32Slot storage) {\n        bytes32 slot;\n        assembly (\"memory-safe\") {\n            slot := arr.slot\n        }\n        return slot.deriveArray().offset(pos).getBytes32Slot();\n    }\n\n    /**\n     * @dev Access an array in an \"unsafe\" way. Skips solidity \"index-out-of-range\" check.\n     *\n     * WARNING: Only use if you are certain `pos` is lower than the array length.\n     */\n    function unsafeAccess(uint256[] storage arr, uint256 pos) internal pure returns (StorageSlot.Uint256Slot storage) {\n        bytes32 slot;\n        assembly (\"memory-safe\") {\n            slot := arr.slot\n        }\n        return slot.deriveArray().offset(pos).getUint256Slot();\n    }\n\n    /**\n     * @dev Access an array in an \"unsafe\" way. Skips solidity \"index-out-of-range\" check.\n     *\n     * WARNING: Only use if you are certain `pos` is lower than the array length.\n     */\n    function unsafeAccess(bytes[] storage arr, uint256 pos) internal pure returns (StorageSlot.BytesSlot storage) {\n        bytes32 slot;\n        assembly (\"memory-safe\") {\n            slot := arr.slot\n        }\n        return slot.deriveArray().offset(pos).getBytesSlot();\n    }\n\n    /**\n     * @dev Access an array in an \"unsafe\" way. Skips solidity \"index-out-of-range\" check.\n     *\n     * WARNING: Only use if you are certain `pos` is lower than the array length.\n     */\n    function unsafeAccess(string[] storage arr, uint256 pos) internal pure returns (StorageSlot.StringSlot storage) {\n        bytes32 slot;\n        assembly (\"memory-safe\") {\n            slot := arr.slot\n        }\n        return slot.deriveArray().offset(pos).getStringSlot();\n    }\n\n    /**\n     * @dev Access an array in an \"unsafe\" way. Skips solidity \"index-out-of-range\" check.\n     *\n     * WARNING: Only use if you are certain `pos` is lower than the array length.\n     */\n    function unsafeMemoryAccess(address[] memory arr, uint256 pos) internal pure returns (address res) {\n        assembly {\n            res := mload(add(add(arr, 0x20), mul(pos, 0x20)))\n        }\n    }\n\n    /**\n     * @dev Access an array in an \"unsafe\" way. Skips solidity \"index-out-of-range\" check.\n     *\n     * WARNING: Only use if you are certain `pos` is lower than the array length.\n     */\n    function unsafeMemoryAccess(bytes32[] memory arr, uint256 pos) internal pure returns (bytes32 res) {\n        assembly {\n            res := mload(add(add(arr, 0x20), mul(pos, 0x20)))\n        }\n    }\n\n    /**\n     * @dev Access an array in an \"unsafe\" way. Skips solidity \"index-out-of-range\" check.\n     *\n     * WARNING: Only use if you are certain `pos` is lower than the array length.\n     */\n    function unsafeMemoryAccess(uint256[] memory arr, uint256 pos) internal pure returns (uint256 res) {\n        assembly {\n            res := mload(add(add(arr, 0x20), mul(pos, 0x20)))\n        }\n    }\n\n    /**\n     * @dev Access an array in an \"unsafe\" way. Skips solidity \"index-out-of-range\" check.\n     *\n     * WARNING: Only use if you are certain `pos` is lower than the array length.\n     */\n    function unsafeMemoryAccess(bytes[] memory arr, uint256 pos) internal pure returns (bytes memory res) {\n        assembly {\n            res := mload(add(add(arr, 0x20), mul(pos, 0x20)))\n        }\n    }\n\n    /**\n     * @dev Access an array in an \"unsafe\" way. Skips solidity \"index-out-of-range\" check.\n     *\n     * WARNING: Only use if you are certain `pos` is lower than the array length.\n     */\n    function unsafeMemoryAccess(string[] memory arr, uint256 pos) internal pure returns (string memory res) {\n        assembly {\n            res := mload(add(add(arr, 0x20), mul(pos, 0x20)))\n        }\n    }\n\n    /**\n     * @dev Helper to set the length of a dynamic array. Directly writing to `.length` is forbidden.\n     *\n     * WARNING: this does not clear elements if length is reduced, or initialize elements if length is increased.\n     */\n    function unsafeSetLength(address[] storage array, uint256 len) internal {\n        assembly (\"memory-safe\") {\n            sstore(array.slot, len)\n        }\n    }\n\n    /**\n     * @dev Helper to set the length of a dynamic array. Directly writing to `.length` is forbidden.\n     *\n     * WARNING: this does not clear elements if length is reduced, or initialize elements if length is increased.\n     */\n    function unsafeSetLength(bytes32[] storage array, uint256 len) internal {\n        assembly (\"memory-safe\") {\n            sstore(array.slot, len)\n        }\n    }\n\n    /**\n     * @dev Helper to set the length of a dynamic array. Directly writing to `.length` is forbidden.\n     *\n     * WARNING: this does not clear elements if length is reduced, or initialize elements if length is increased.\n     */\n    function unsafeSetLength(uint256[] storage array, uint256 len) internal {\n        assembly (\"memory-safe\") {\n            sstore(array.slot, len)\n        }\n    }\n\n    /**\n     * @dev Helper to set the length of a dynamic array. Directly writing to `.length` is forbidden.\n     *\n     * WARNING: this does not clear elements if length is reduced, or initialize elements if length is increased.\n     */\n    function unsafeSetLength(bytes[] storage array, uint256 len) internal {\n        assembly (\"memory-safe\") {\n            sstore(array.slot, len)\n        }\n    }\n\n    /**\n     * @dev Helper to set the length of a dynamic array. Directly writing to `.length` is forbidden.\n     *\n     * WARNING: this does not clear elements if length is reduced, or initialize elements if length is increased.\n     */\n    function unsafeSetLength(string[] storage array, uint256 len) internal {\n        assembly (\"memory-safe\") {\n            sstore(array.slot, len)\n        }\n    }\n}\n"},{"file_path":"lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/IERC165.sol)\n\npragma solidity >=0.4.16;\n\n/**\n * @dev Interface of the ERC-165 standard, as defined in the\n * https://eips.ethereum.org/EIPS/eip-165[ERC].\n *\n * Implementers can declare support of contract interfaces, which can then be\n * queried by others ({ERC165Checker}).\n *\n * For an implementation, see {ERC165}.\n */\ninterface IERC165 {\n    /**\n     * @dev Returns true if this contract implements the interface defined by\n     * `interfaceId`. See the corresponding\n     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]\n     * to learn more about how these ids are created.\n     *\n     * This function call must use less than 30 000 gas.\n     */\n    function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n"},{"file_path":"lib/openzeppelin-contracts/contracts/utils/Strings.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.5.0) (utils/Strings.sol)\n\npragma solidity ^0.8.24;\n\nimport {Math} from \"./math/Math.sol\";\nimport {SafeCast} from \"./math/SafeCast.sol\";\nimport {SignedMath} from \"./math/SignedMath.sol\";\nimport {Bytes} from \"./Bytes.sol\";\n\n/**\n * @dev String operations.\n */\nlibrary Strings {\n    using SafeCast for *;\n\n    bytes16 private constant HEX_DIGITS = \"0123456789abcdef\";\n    uint8 private constant ADDRESS_LENGTH = 20;\n    uint256 private constant SPECIAL_CHARS_LOOKUP =\n        (1 << 0x08) | // backspace\n            (1 << 0x09) | // tab\n            (1 << 0x0a) | // newline\n            (1 << 0x0c) | // form feed\n            (1 << 0x0d) | // carriage return\n            (1 << 0x22) | // double quote\n            (1 << 0x5c); // backslash\n\n    /**\n     * @dev The `value` string doesn't fit in the specified `length`.\n     */\n    error StringsInsufficientHexLength(uint256 value, uint256 length);\n\n    /**\n     * @dev The string being parsed contains characters that are not in scope of the given base.\n     */\n    error StringsInvalidChar();\n\n    /**\n     * @dev The string being parsed is not a properly formatted address.\n     */\n    error StringsInvalidAddressFormat();\n\n    /**\n     * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n     */\n    function toString(uint256 value) internal pure returns (string memory) {\n        unchecked {\n            uint256 length = Math.log10(value) + 1;\n            string memory buffer = new string(length);\n            uint256 ptr;\n            assembly (\"memory-safe\") {\n                ptr := add(add(buffer, 0x20), length)\n            }\n            while (true) {\n                ptr--;\n                assembly (\"memory-safe\") {\n                    mstore8(ptr, byte(mod(value, 10), HEX_DIGITS))\n                }\n                value /= 10;\n                if (value == 0) break;\n            }\n            return buffer;\n        }\n    }\n\n    /**\n     * @dev Converts a `int256` to its ASCII `string` decimal representation.\n     */\n    function toStringSigned(int256 value) internal pure returns (string memory) {\n        return string.concat(value < 0 ? \"-\" : \"\", toString(SignedMath.abs(value)));\n    }\n\n    /**\n     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.\n     */\n    function toHexString(uint256 value) internal pure returns (string memory) {\n        unchecked {\n            return toHexString(value, Math.log256(value) + 1);\n        }\n    }\n\n    /**\n     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.\n     */\n    function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {\n        uint256 localValue = value;\n        bytes memory buffer = new bytes(2 * length + 2);\n        buffer[0] = \"0\";\n        buffer[1] = \"x\";\n        for (uint256 i = 2 * length + 1; i > 1; --i) {\n            buffer[i] = HEX_DIGITS[localValue & 0xf];\n            localValue >>= 4;\n        }\n        if (localValue != 0) {\n            revert StringsInsufficientHexLength(value, length);\n        }\n        return string(buffer);\n    }\n\n    /**\n     * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal\n     * representation.\n     */\n    function toHexString(address addr) internal pure returns (string memory) {\n        return toHexString(uint256(uint160(addr)), ADDRESS_LENGTH);\n    }\n\n    /**\n     * @dev Converts an `address` with fixed length of 20 bytes to its checksummed ASCII `string` hexadecimal\n     * representation, according to EIP-55.\n     */\n    function toChecksumHexString(address addr) internal pure returns (string memory) {\n        bytes memory buffer = bytes(toHexString(addr));\n\n        // hash the hex part of buffer (skip length + 2 bytes, length 40)\n        uint256 hashValue;\n        assembly (\"memory-safe\") {\n            hashValue := shr(96, keccak256(add(buffer, 0x22), 40))\n        }\n\n        for (uint256 i = 41; i > 1; --i) {\n            // possible values for buffer[i] are 48 (0) to 57 (9) and 97 (a) to 102 (f)\n            if (hashValue & 0xf > 7 && uint8(buffer[i]) > 96) {\n                // case shift by xoring with 0x20\n                buffer[i] ^= 0x20;\n            }\n            hashValue >>= 4;\n        }\n        return string(buffer);\n    }\n\n    /**\n     * @dev Converts a `bytes` buffer to its ASCII `string` hexadecimal representation.\n     */\n    function toHexString(bytes memory input) internal pure returns (string memory) {\n        unchecked {\n            bytes memory buffer = new bytes(2 * input.length + 2);\n            buffer[0] = \"0\";\n            buffer[1] = \"x\";\n            for (uint256 i = 0; i < input.length; ++i) {\n                uint8 v = uint8(input[i]);\n                buffer[2 * i + 2] = HEX_DIGITS[v >> 4];\n                buffer[2 * i + 3] = HEX_DIGITS[v & 0xf];\n            }\n            return string(buffer);\n        }\n    }\n\n    /**\n     * @dev Returns true if the two strings are equal.\n     */\n    function equal(string memory a, string memory b) internal pure returns (bool) {\n        return Bytes.equal(bytes(a), bytes(b));\n    }\n\n    /**\n     * @dev Parse a decimal string and returns the value as a `uint256`.\n     *\n     * Requirements:\n     * - The string must be formatted as `[0-9]*`\n     * - The result must fit into an `uint256` type\n     */\n    function parseUint(string memory input) internal pure returns (uint256) {\n        return parseUint(input, 0, bytes(input).length);\n    }\n\n    /**\n     * @dev Variant of {parseUint-string} that parses a substring of `input` located between position `begin` (included) and\n     * `end` (excluded).\n     *\n     * Requirements:\n     * - The substring must be formatted as `[0-9]*`\n     * - The result must fit into an `uint256` type\n     */\n    function parseUint(string memory input, uint256 begin, uint256 end) internal pure returns (uint256) {\n        (bool success, uint256 value) = tryParseUint(input, begin, end);\n        if (!success) revert StringsInvalidChar();\n        return value;\n    }\n\n    /**\n     * @dev Variant of {parseUint-string} that returns false if the parsing fails because of an invalid character.\n     *\n     * NOTE: This function will revert if the result does not fit in a `uint256`.\n     */\n    function tryParseUint(string memory input) internal pure returns (bool success, uint256 value) {\n        return _tryParseUintUncheckedBounds(input, 0, bytes(input).length);\n    }\n\n    /**\n     * @dev Variant of {parseUint-string-uint256-uint256} that returns false if the parsing fails because of an invalid\n     * character.\n     *\n     * NOTE: This function will revert if the result does not fit in a `uint256`.\n     */\n    function tryParseUint(\n        string memory input,\n        uint256 begin,\n        uint256 end\n    ) internal pure returns (bool success, uint256 value) {\n        if (end > bytes(input).length || begin > end) return (false, 0);\n        return _tryParseUintUncheckedBounds(input, begin, end);\n    }\n\n    /**\n     * @dev Implementation of {tryParseUint-string-uint256-uint256} that does not check bounds. Caller should make sure that\n     * `begin <= end <= input.length`. Other inputs would result in undefined behavior.\n     */\n    function _tryParseUintUncheckedBounds(\n        string memory input,\n        uint256 begin,\n        uint256 end\n    ) private pure returns (bool success, uint256 value) {\n        bytes memory buffer = bytes(input);\n\n        uint256 result = 0;\n        for (uint256 i = begin; i < end; ++i) {\n            uint8 chr = _tryParseChr(bytes1(_unsafeReadBytesOffset(buffer, i)));\n            if (chr > 9) return (false, 0);\n            result *= 10;\n            result += chr;\n        }\n        return (true, result);\n    }\n\n    /**\n     * @dev Parse a decimal string and returns the value as a `int256`.\n     *\n     * Requirements:\n     * - The string must be formatted as `[-+]?[0-9]*`\n     * - The result must fit in an `int256` type.\n     */\n    function parseInt(string memory input) internal pure returns (int256) {\n        return parseInt(input, 0, bytes(input).length);\n    }\n\n    /**\n     * @dev Variant of {parseInt-string} that parses a substring of `input` located between position `begin` (included) and\n     * `end` (excluded).\n     *\n     * Requirements:\n     * - The substring must be formatted as `[-+]?[0-9]*`\n     * - The result must fit in an `int256` type.\n     */\n    function parseInt(string memory input, uint256 begin, uint256 end) internal pure returns (int256) {\n        (bool success, int256 value) = tryParseInt(input, begin, end);\n        if (!success) revert StringsInvalidChar();\n        return value;\n    }\n\n    /**\n     * @dev Variant of {parseInt-string} that returns false if the parsing fails because of an invalid character or if\n     * the result does not fit in a `int256`.\n     *\n     * NOTE: This function will revert if the absolute value of the result does not fit in a `uint256`.\n     */\n    function tryParseInt(string memory input) internal pure returns (bool success, int256 value) {\n        return _tryParseIntUncheckedBounds(input, 0, bytes(input).length);\n    }\n\n    uint256 private constant ABS_MIN_INT256 = 2 ** 255;\n\n    /**\n     * @dev Variant of {parseInt-string-uint256-uint256} that returns false if the parsing fails because of an invalid\n     * character or if the result does not fit in a `int256`.\n     *\n     * NOTE: This function will revert if the absolute value of the result does not fit in a `uint256`.\n     */\n    function tryParseInt(\n        string memory input,\n        uint256 begin,\n        uint256 end\n    ) internal pure returns (bool success, int256 value) {\n        if (end > bytes(input).length || begin > end) return (false, 0);\n        return _tryParseIntUncheckedBounds(input, begin, end);\n    }\n\n    /**\n     * @dev Implementation of {tryParseInt-string-uint256-uint256} that does not check bounds. Caller should make sure that\n     * `begin <= end <= input.length`. Other inputs would result in undefined behavior.\n     */\n    function _tryParseIntUncheckedBounds(\n        string memory input,\n        uint256 begin,\n        uint256 end\n    ) private pure returns (bool success, int256 value) {\n        bytes memory buffer = bytes(input);\n\n        // Check presence of a negative sign.\n        bytes1 sign = begin == end ? bytes1(0) : bytes1(_unsafeReadBytesOffset(buffer, begin)); // don't do out-of-bound (possibly unsafe) read if sub-string is empty\n        bool positiveSign = sign == bytes1(\"+\");\n        bool negativeSign = sign == bytes1(\"-\");\n        uint256 offset = (positiveSign || negativeSign).toUint();\n\n        (bool absSuccess, uint256 absValue) = tryParseUint(input, begin + offset, end);\n\n        if (absSuccess && absValue < ABS_MIN_INT256) {\n            return (true, negativeSign ? -int256(absValue) : int256(absValue));\n        } else if (absSuccess && negativeSign && absValue == ABS_MIN_INT256) {\n            return (true, type(int256).min);\n        } else return (false, 0);\n    }\n\n    /**\n     * @dev Parse a hexadecimal string (with or without \"0x\" prefix), and returns the value as a `uint256`.\n     *\n     * Requirements:\n     * - The string must be formatted as `(0x)?[0-9a-fA-F]*`\n     * - The result must fit in an `uint256` type.\n     */\n    function parseHexUint(string memory input) internal pure returns (uint256) {\n        return parseHexUint(input, 0, bytes(input).length);\n    }\n\n    /**\n     * @dev Variant of {parseHexUint-string} that parses a substring of `input` located between position `begin` (included) and\n     * `end` (excluded).\n     *\n     * Requirements:\n     * - The substring must be formatted as `(0x)?[0-9a-fA-F]*`\n     * - The result must fit in an `uint256` type.\n     */\n    function parseHexUint(string memory input, uint256 begin, uint256 end) internal pure returns (uint256) {\n        (bool success, uint256 value) = tryParseHexUint(input, begin, end);\n        if (!success) revert StringsInvalidChar();\n        return value;\n    }\n\n    /**\n     * @dev Variant of {parseHexUint-string} that returns false if the parsing fails because of an invalid character.\n     *\n     * NOTE: This function will revert if the result does not fit in a `uint256`.\n     */\n    function tryParseHexUint(string memory input) internal pure returns (bool success, uint256 value) {\n        return _tryParseHexUintUncheckedBounds(input, 0, bytes(input).length);\n    }\n\n    /**\n     * @dev Variant of {parseHexUint-string-uint256-uint256} that returns false if the parsing fails because of an\n     * invalid character.\n     *\n     * NOTE: This function will revert if the result does not fit in a `uint256`.\n     */\n    function tryParseHexUint(\n        string memory input,\n        uint256 begin,\n        uint256 end\n    ) internal pure returns (bool success, uint256 value) {\n        if (end > bytes(input).length || begin > end) return (false, 0);\n        return _tryParseHexUintUncheckedBounds(input, begin, end);\n    }\n\n    /**\n     * @dev Implementation of {tryParseHexUint-string-uint256-uint256} that does not check bounds. Caller should make sure that\n     * `begin <= end <= input.length`. Other inputs would result in undefined behavior.\n     */\n    function _tryParseHexUintUncheckedBounds(\n        string memory input,\n        uint256 begin,\n        uint256 end\n    ) private pure returns (bool success, uint256 value) {\n        bytes memory buffer = bytes(input);\n\n        // skip 0x prefix if present\n        bool hasPrefix = (end > begin + 1) && bytes2(_unsafeReadBytesOffset(buffer, begin)) == bytes2(\"0x\"); // don't do out-of-bound (possibly unsafe) read if sub-string is empty\n        uint256 offset = hasPrefix.toUint() * 2;\n\n        uint256 result = 0;\n        for (uint256 i = begin + offset; i < end; ++i) {\n            uint8 chr = _tryParseChr(bytes1(_unsafeReadBytesOffset(buffer, i)));\n            if (chr > 15) return (false, 0);\n            result *= 16;\n            unchecked {\n                // Multiplying by 16 is equivalent to a shift of 4 bits (with additional overflow check).\n                // This guarantees that adding a value < 16 will not cause an overflow, hence the unchecked.\n                result += chr;\n            }\n        }\n        return (true, result);\n    }\n\n    /**\n     * @dev Parse a hexadecimal string (with or without \"0x\" prefix), and returns the value as an `address`.\n     *\n     * Requirements:\n     * - The string must be formatted as `(0x)?[0-9a-fA-F]{40}`\n     */\n    function parseAddress(string memory input) internal pure returns (address) {\n        return parseAddress(input, 0, bytes(input).length);\n    }\n\n    /**\n     * @dev Variant of {parseAddress-string} that parses a substring of `input` located between position `begin` (included) and\n     * `end` (excluded).\n     *\n     * Requirements:\n     * - The substring must be formatted as `(0x)?[0-9a-fA-F]{40}`\n     */\n    function parseAddress(string memory input, uint256 begin, uint256 end) internal pure returns (address) {\n        (bool success, address value) = tryParseAddress(input, begin, end);\n        if (!success) revert StringsInvalidAddressFormat();\n        return value;\n    }\n\n    /**\n     * @dev Variant of {parseAddress-string} that returns false if the parsing fails because the input is not a properly\n     * formatted address. See {parseAddress-string} requirements.\n     */\n    function tryParseAddress(string memory input) internal pure returns (bool success, address value) {\n        return tryParseAddress(input, 0, bytes(input).length);\n    }\n\n    /**\n     * @dev Variant of {parseAddress-string-uint256-uint256} that returns false if the parsing fails because input is not a properly\n     * formatted address. See {parseAddress-string-uint256-uint256} requirements.\n     */\n    function tryParseAddress(\n        string memory input,\n        uint256 begin,\n        uint256 end\n    ) internal pure returns (bool success, address value) {\n        if (end > bytes(input).length || begin > end) return (false, address(0));\n\n        bool hasPrefix = (end > begin + 1) && bytes2(_unsafeReadBytesOffset(bytes(input), begin)) == bytes2(\"0x\"); // don't do out-of-bound (possibly unsafe) read if sub-string is empty\n        uint256 expectedLength = 40 + hasPrefix.toUint() * 2;\n\n        // check that input is the correct length\n        if (end - begin == expectedLength) {\n            // length guarantees that this does not overflow, and value is at most type(uint160).max\n            (bool s, uint256 v) = _tryParseHexUintUncheckedBounds(input, begin, end);\n            return (s, address(uint160(v)));\n        } else {\n            return (false, address(0));\n        }\n    }\n\n    function _tryParseChr(bytes1 chr) private pure returns (uint8) {\n        uint8 value = uint8(chr);\n\n        // Try to parse `chr`:\n        // - Case 1: [0-9]\n        // - Case 2: [a-f]\n        // - Case 3: [A-F]\n        // - otherwise not supported\n        unchecked {\n            if (value > 47 && value < 58) value -= 48;\n            else if (value > 96 && value < 103) value -= 87;\n            else if (value > 64 && value < 71) value -= 55;\n            else return type(uint8).max;\n        }\n\n        return value;\n    }\n\n    /**\n     * @dev Escape special characters in JSON strings. This can be useful to prevent JSON injection in NFT metadata.\n     *\n     * WARNING: This function should only be used in double quoted JSON strings. Single quotes are not escaped.\n     *\n     * NOTE: This function escapes all unicode characters, and not just the ones in ranges defined in section 2.5 of\n     * RFC-4627 (U+0000 to U+001F, U+0022 and U+005C). ECMAScript's `JSON.parse` does recover escaped unicode\n     * characters that are not in this range, but other tooling may provide different results.\n     */\n    function escapeJSON(string memory input) internal pure returns (string memory) {\n        bytes memory buffer = bytes(input);\n        bytes memory output = new bytes(2 * buffer.length); // worst case scenario\n        uint256 outputLength = 0;\n\n        for (uint256 i = 0; i < buffer.length; ++i) {\n            bytes1 char = bytes1(_unsafeReadBytesOffset(buffer, i));\n            if (((SPECIAL_CHARS_LOOKUP & (1 << uint8(char))) != 0)) {\n                output[outputLength++] = \"\\\\\";\n                if (char == 0x08) output[outputLength++] = \"b\";\n                else if (char == 0x09) output[outputLength++] = \"t\";\n                else if (char == 0x0a) output[outputLength++] = \"n\";\n                else if (char == 0x0c) output[outputLength++] = \"f\";\n                else if (char == 0x0d) output[outputLength++] = \"r\";\n                else if (char == 0x5c) output[outputLength++] = \"\\\\\";\n                else if (char == 0x22) {\n                    // solhint-disable-next-line quotes\n                    output[outputLength++] = '\"';\n                }\n            } else {\n                output[outputLength++] = char;\n            }\n        }\n        // write the actual length and deallocate unused memory\n        assembly (\"memory-safe\") {\n            mstore(output, outputLength)\n            mstore(0x40, add(output, shl(5, shr(5, add(outputLength, 63)))))\n        }\n\n        return string(output);\n    }\n\n    /**\n     * @dev Reads a bytes32 from a bytes array without bounds checking.\n     *\n     * NOTE: making this function internal would mean it could be used with memory unsafe offset, and marking the\n     * assembly block as such would prevent some optimizations.\n     */\n    function _unsafeReadBytesOffset(bytes memory buffer, uint256 offset) private pure returns (bytes32 value) {\n        // This is not memory safe in the general case, but all calls to this private function are within bounds.\n        assembly (\"memory-safe\") {\n            value := mload(add(add(buffer, 0x20), offset))\n        }\n    }\n}\n"},{"file_path":"lib/openzeppelin-contracts/contracts/token/ERC20/ERC20.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.5.0) (token/ERC20/ERC20.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC20} from \"./IERC20.sol\";\nimport {IERC20Metadata} from \"./extensions/IERC20Metadata.sol\";\nimport {Context} from \"../../utils/Context.sol\";\nimport {IERC20Errors} from \"../../interfaces/draft-IERC6093.sol\";\n\n/**\n * @dev Implementation of the {IERC20} interface.\n *\n * This implementation is agnostic to the way tokens are created. This means\n * that a supply mechanism has to be added in a derived contract using {_mint}.\n *\n * TIP: For a detailed writeup see our guide\n * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How\n * to implement supply mechanisms].\n *\n * The default value of {decimals} is 18. To change this, you should override\n * this function so it returns a different value.\n *\n * We have followed general OpenZeppelin Contracts guidelines: functions revert\n * instead returning `false` on failure. This behavior is nonetheless\n * conventional and does not conflict with the expectations of ERC-20\n * applications.\n */\nabstract contract ERC20 is Context, IERC20, IERC20Metadata, IERC20Errors {\n    mapping(address account => uint256) private _balances;\n\n    mapping(address account => mapping(address spender => uint256)) private _allowances;\n\n    uint256 private _totalSupply;\n\n    string private _name;\n    string private _symbol;\n\n    /**\n     * @dev Sets the values for {name} and {symbol}.\n     *\n     * Both values are immutable: they can only be set once during construction.\n     */\n    constructor(string memory name_, string memory symbol_) {\n        _name = name_;\n        _symbol = symbol_;\n    }\n\n    /**\n     * @dev Returns the name of the token.\n     */\n    function name() public view virtual returns (string memory) {\n        return _name;\n    }\n\n    /**\n     * @dev Returns the symbol of the token, usually a shorter version of the\n     * name.\n     */\n    function symbol() public view virtual returns (string memory) {\n        return _symbol;\n    }\n\n    /**\n     * @dev Returns the number of decimals used to get its user representation.\n     * For example, if `decimals` equals `2`, a balance of `505` tokens should\n     * be displayed to a user as `5.05` (`505 / 10 ** 2`).\n     *\n     * Tokens usually opt for a value of 18, imitating the relationship between\n     * Ether and Wei. This is the default value returned by this function, unless\n     * it's overridden.\n     *\n     * NOTE: This information is only used for _display_ purposes: it in\n     * no way affects any of the arithmetic of the contract, including\n     * {IERC20-balanceOf} and {IERC20-transfer}.\n     */\n    function decimals() public view virtual returns (uint8) {\n        return 18;\n    }\n\n    /// @inheritdoc IERC20\n    function totalSupply() public view virtual returns (uint256) {\n        return _totalSupply;\n    }\n\n    /// @inheritdoc IERC20\n    function balanceOf(address account) public view virtual returns (uint256) {\n        return _balances[account];\n    }\n\n    /**\n     * @dev See {IERC20-transfer}.\n     *\n     * Requirements:\n     *\n     * - `to` cannot be the zero address.\n     * - the caller must have a balance of at least `value`.\n     */\n    function transfer(address to, uint256 value) public virtual returns (bool) {\n        address owner = _msgSender();\n        _transfer(owner, to, value);\n        return true;\n    }\n\n    /// @inheritdoc IERC20\n    function allowance(address owner, address spender) public view virtual returns (uint256) {\n        return _allowances[owner][spender];\n    }\n\n    /**\n     * @dev See {IERC20-approve}.\n     *\n     * NOTE: If `value` is the maximum `uint256`, the allowance is not updated on\n     * `transferFrom`. This is semantically equivalent to an infinite approval.\n     *\n     * Requirements:\n     *\n     * - `spender` cannot be the zero address.\n     */\n    function approve(address spender, uint256 value) public virtual returns (bool) {\n        address owner = _msgSender();\n        _approve(owner, spender, value);\n        return true;\n    }\n\n    /**\n     * @dev See {IERC20-transferFrom}.\n     *\n     * Skips emitting an {Approval} event indicating an allowance update. This is not\n     * required by the ERC. See {xref-ERC20-_approve-address-address-uint256-bool-}[_approve].\n     *\n     * NOTE: Does not update the allowance if the current allowance\n     * is the maximum `uint256`.\n     *\n     * Requirements:\n     *\n     * - `from` and `to` cannot be the zero address.\n     * - `from` must have a balance of at least `value`.\n     * - the caller must have allowance for ``from``'s tokens of at least\n     * `value`.\n     */\n    function transferFrom(address from, address to, uint256 value) public virtual returns (bool) {\n        address spender = _msgSender();\n        _spendAllowance(from, spender, value);\n        _transfer(from, to, value);\n        return true;\n    }\n\n    /**\n     * @dev Moves a `value` amount of tokens from `from` to `to`.\n     *\n     * This internal function is equivalent to {transfer}, and can be used to\n     * e.g. implement automatic token fees, slashing mechanisms, etc.\n     *\n     * Emits a {Transfer} event.\n     *\n     * NOTE: This function is not virtual, {_update} should be overridden instead.\n     */\n    function _transfer(address from, address to, uint256 value) internal {\n        if (from == address(0)) {\n            revert ERC20InvalidSender(address(0));\n        }\n        if (to == address(0)) {\n            revert ERC20InvalidReceiver(address(0));\n        }\n        _update(from, to, value);\n    }\n\n    /**\n     * @dev Transfers a `value` amount of tokens from `from` to `to`, or alternatively mints (or burns) if `from`\n     * (or `to`) is the zero address. All customizations to transfers, mints, and burns should be done by overriding\n     * this function.\n     *\n     * Emits a {Transfer} event.\n     */\n    function _update(address from, address to, uint256 value) internal virtual {\n        if (from == address(0)) {\n            // Overflow check required: The rest of the code assumes that totalSupply never overflows\n            _totalSupply += value;\n        } else {\n            uint256 fromBalance = _balances[from];\n            if (fromBalance < value) {\n                revert ERC20InsufficientBalance(from, fromBalance, value);\n            }\n            unchecked {\n                // Overflow not possible: value <= fromBalance <= totalSupply.\n                _balances[from] = fromBalance - value;\n            }\n        }\n\n        if (to == address(0)) {\n            unchecked {\n                // Overflow not possible: value <= totalSupply or value <= fromBalance <= totalSupply.\n                _totalSupply -= value;\n            }\n        } else {\n            unchecked {\n                // Overflow not possible: balance + value is at most totalSupply, which we know fits into a uint256.\n                _balances[to] += value;\n            }\n        }\n\n        emit Transfer(from, to, value);\n    }\n\n    /**\n     * @dev Creates a `value` amount of tokens and assigns them to `account`, by transferring it from address(0).\n     * Relies on the `_update` mechanism\n     *\n     * Emits a {Transfer} event with `from` set to the zero address.\n     *\n     * NOTE: This function is not virtual, {_update} should be overridden instead.\n     */\n    function _mint(address account, uint256 value) internal {\n        if (account == address(0)) {\n            revert ERC20InvalidReceiver(address(0));\n        }\n        _update(address(0), account, value);\n    }\n\n    /**\n     * @dev Destroys a `value` amount of tokens from `account`, lowering the total supply.\n     * Relies on the `_update` mechanism.\n     *\n     * Emits a {Transfer} event with `to` set to the zero address.\n     *\n     * NOTE: This function is not virtual, {_update} should be overridden instead\n     */\n    function _burn(address account, uint256 value) internal {\n        if (account == address(0)) {\n            revert ERC20InvalidSender(address(0));\n        }\n        _update(account, address(0), value);\n    }\n\n    /**\n     * @dev Sets `value` as the allowance of `spender` over the `owner`'s tokens.\n     *\n     * This internal function is equivalent to `approve`, and can be used to\n     * e.g. set automatic allowances for certain subsystems, etc.\n     *\n     * Emits an {Approval} event.\n     *\n     * Requirements:\n     *\n     * - `owner` cannot be the zero address.\n     * - `spender` cannot be the zero address.\n     *\n     * Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.\n     */\n    function _approve(address owner, address spender, uint256 value) internal {\n        _approve(owner, spender, value, true);\n    }\n\n    /**\n     * @dev Variant of {_approve} with an optional flag to enable or disable the {Approval} event.\n     *\n     * By default (when calling {_approve}) the flag is set to true. On the other hand, approval changes made by\n     * `_spendAllowance` during the `transferFrom` operation sets the flag to false. This saves gas by not emitting any\n     * `Approval` event during `transferFrom` operations.\n     *\n     * Anyone who wishes to continue emitting `Approval` events on the `transferFrom` operation can force the flag to\n     * true using the following override:\n     *\n     * ```solidity\n     * function _approve(address owner, address spender, uint256 value, bool) internal virtual override {\n     *     super._approve(owner, spender, value, true);\n     * }\n     * ```\n     *\n     * Requirements are the same as {_approve}.\n     */\n    function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual {\n        if (owner == address(0)) {\n            revert ERC20InvalidApprover(address(0));\n        }\n        if (spender == address(0)) {\n            revert ERC20InvalidSpender(address(0));\n        }\n        _allowances[owner][spender] = value;\n        if (emitEvent) {\n            emit Approval(owner, spender, value);\n        }\n    }\n\n    /**\n     * @dev Updates `owner`'s allowance for `spender` based on spent `value`.\n     *\n     * Does not update the allowance value in case of infinite allowance.\n     * Revert if not enough allowance is available.\n     *\n     * Does not emit an {Approval} event.\n     */\n    function _spendAllowance(address owner, address spender, uint256 value) internal virtual {\n        uint256 currentAllowance = allowance(owner, spender);\n        if (currentAllowance < type(uint256).max) {\n            if (currentAllowance < value) {\n                revert ERC20InsufficientAllowance(spender, currentAllowance, value);\n            }\n            unchecked {\n                _approve(owner, spender, currentAllowance - value, false);\n            }\n        }\n    }\n}\n"},{"file_path":"lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/IERC20.sol)\n\npragma solidity >=0.4.16;\n\n/**\n * @dev Interface of the ERC-20 standard as defined in the ERC.\n */\ninterface IERC20 {\n    /**\n     * @dev Emitted when `value` tokens are moved from one account (`from`) to\n     * another (`to`).\n     *\n     * Note that `value` may be zero.\n     */\n    event Transfer(address indexed from, address indexed to, uint256 value);\n\n    /**\n     * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n     * a call to {approve}. `value` is the new allowance.\n     */\n    event Approval(address indexed owner, address indexed spender, uint256 value);\n\n    /**\n     * @dev Returns the value of tokens in existence.\n     */\n    function totalSupply() external view returns (uint256);\n\n    /**\n     * @dev Returns the value of tokens owned by `account`.\n     */\n    function balanceOf(address account) external view returns (uint256);\n\n    /**\n     * @dev Moves a `value` amount of tokens from the caller's account to `to`.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * Emits a {Transfer} event.\n     */\n    function transfer(address to, uint256 value) external returns (bool);\n\n    /**\n     * @dev Returns the remaining number of tokens that `spender` will be\n     * allowed to spend on behalf of `owner` through {transferFrom}. This is\n     * zero by default.\n     *\n     * This value changes when {approve} or {transferFrom} are called.\n     */\n    function allowance(address owner, address spender) external view returns (uint256);\n\n    /**\n     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the\n     * caller's tokens.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * IMPORTANT: Beware that changing an allowance with this method brings the risk\n     * that someone may use both the old and the new allowance by unfortunate\n     * transaction ordering. One possible solution to mitigate this race\n     * condition is to first reduce the spender's allowance to 0 and set the\n     * desired value afterwards:\n     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n     *\n     * Emits an {Approval} event.\n     */\n    function approve(address spender, uint256 value) external returns (bool);\n\n    /**\n     * @dev Moves a `value` amount of tokens from `from` to `to` using the\n     * allowance mechanism. `value` is then deducted from the caller's\n     * allowance.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * Emits a {Transfer} event.\n     */\n    function transferFrom(address from, address to, uint256 value) external returns (bool);\n}\n"},{"file_path":"lib/openzeppelin-contracts/contracts/utils/Pausable.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.3.0) (utils/Pausable.sol)\n\npragma solidity ^0.8.20;\n\nimport {Context} from \"../utils/Context.sol\";\n\n/**\n * @dev Contract module which allows children to implement an emergency stop\n * mechanism that can be triggered by an authorized account.\n *\n * This module is used through inheritance. It will make available the\n * modifiers `whenNotPaused` and `whenPaused`, which can be applied to\n * the functions of your contract. Note that they will not be pausable by\n * simply including this module, only once the modifiers are put in place.\n */\nabstract contract Pausable is Context {\n    bool private _paused;\n\n    /**\n     * @dev Emitted when the pause is triggered by `account`.\n     */\n    event Paused(address account);\n\n    /**\n     * @dev Emitted when the pause is lifted by `account`.\n     */\n    event Unpaused(address account);\n\n    /**\n     * @dev The operation failed because the contract is paused.\n     */\n    error EnforcedPause();\n\n    /**\n     * @dev The operation failed because the contract is not paused.\n     */\n    error ExpectedPause();\n\n    /**\n     * @dev Modifier to make a function callable only when the contract is not paused.\n     *\n     * Requirements:\n     *\n     * - The contract must not be paused.\n     */\n    modifier whenNotPaused() {\n        _requireNotPaused();\n        _;\n    }\n\n    /**\n     * @dev Modifier to make a function callable only when the contract is paused.\n     *\n     * Requirements:\n     *\n     * - The contract must be paused.\n     */\n    modifier whenPaused() {\n        _requirePaused();\n        _;\n    }\n\n    /**\n     * @dev Returns true if the contract is paused, and false otherwise.\n     */\n    function paused() public view virtual returns (bool) {\n        return _paused;\n    }\n\n    /**\n     * @dev Throws if the contract is paused.\n     */\n    function _requireNotPaused() internal view virtual {\n        if (paused()) {\n            revert EnforcedPause();\n        }\n    }\n\n    /**\n     * @dev Throws if the contract is not paused.\n     */\n    function _requirePaused() internal view virtual {\n        if (!paused()) {\n            revert ExpectedPause();\n        }\n    }\n\n    /**\n     * @dev Triggers stopped state.\n     *\n     * Requirements:\n     *\n     * - The contract must not be paused.\n     */\n    function _pause() internal virtual whenNotPaused {\n        _paused = true;\n        emit Paused(_msgSender());\n    }\n\n    /**\n     * @dev Returns to normal state.\n     *\n     * Requirements:\n     *\n     * - The contract must be paused.\n     */\n    function _unpause() internal virtual whenPaused {\n        _paused = false;\n        emit Unpaused(_msgSender());\n    }\n}\n"},{"file_path":"lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/extensions/IERC20Metadata.sol)\n\npragma solidity >=0.6.2;\n\nimport {IERC20} from \"../IERC20.sol\";\n\n/**\n * @dev Interface for the optional metadata functions from the ERC-20 standard.\n */\ninterface IERC20Metadata is IERC20 {\n    /**\n     * @dev Returns the name of the token.\n     */\n    function name() external view returns (string memory);\n\n    /**\n     * @dev Returns the symbol of the token.\n     */\n    function symbol() external view returns (string memory);\n\n    /**\n     * @dev Returns the decimals places of the token.\n     */\n    function decimals() external view returns (uint8);\n}\n"},{"file_path":"lib/openzeppelin-contracts/contracts/interfaces/IERC1363.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC1363.sol)\n\npragma solidity >=0.6.2;\n\nimport {IERC20} from \"./IERC20.sol\";\nimport {IERC165} from \"./IERC165.sol\";\n\n/**\n * @title IERC1363\n * @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].\n *\n * Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract\n * after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.\n */\ninterface IERC1363 is IERC20, IERC165 {\n    /*\n     * Note: the ERC-165 identifier for this interface is 0xb0202a11.\n     * 0xb0202a11 ===\n     *   bytes4(keccak256('transferAndCall(address,uint256)')) ^\n     *   bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^\n     *   bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^\n     *   bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^\n     *   bytes4(keccak256('approveAndCall(address,uint256)')) ^\n     *   bytes4(keccak256('approveAndCall(address,uint256,bytes)'))\n     */\n\n    /**\n     * @dev Moves a `value` amount of tokens from the caller's account to `to`\n     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.\n     * @param to The address which you want to transfer to.\n     * @param value The amount of tokens to be transferred.\n     * @return A boolean value indicating whether the operation succeeded unless throwing.\n     */\n    function transferAndCall(address to, uint256 value) external returns (bool);\n\n    /**\n     * @dev Moves a `value` amount of tokens from the caller's account to `to`\n     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.\n     * @param to The address which you want to transfer to.\n     * @param value The amount of tokens to be transferred.\n     * @param data Additional data with no specified format, sent in call to `to`.\n     * @return A boolean value indicating whether the operation succeeded unless throwing.\n     */\n    function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);\n\n    /**\n     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism\n     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.\n     * @param from The address which you want to send tokens from.\n     * @param to The address which you want to transfer to.\n     * @param value The amount of tokens to be transferred.\n     * @return A boolean value indicating whether the operation succeeded unless throwing.\n     */\n    function transferFromAndCall(address from, address to, uint256 value) external returns (bool);\n\n    /**\n     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism\n     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.\n     * @param from The address which you want to send tokens from.\n     * @param to The address which you want to transfer to.\n     * @param value The amount of tokens to be transferred.\n     * @param data Additional data with no specified format, sent in call to `to`.\n     * @return A boolean value indicating whether the operation succeeded unless throwing.\n     */\n    function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);\n\n    /**\n     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the\n     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.\n     * @param spender The address which will spend the funds.\n     * @param value The amount of tokens to be spent.\n     * @return A boolean value indicating whether the operation succeeded unless throwing.\n     */\n    function approveAndCall(address spender, uint256 value) external returns (bool);\n\n    /**\n     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the\n     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.\n     * @param spender The address which will spend the funds.\n     * @param value The amount of tokens to be spent.\n     * @param data Additional data with no specified format, sent in call to `spender`.\n     * @return A boolean value indicating whether the operation succeeded unless throwing.\n     */\n    function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);\n}\n"},{"file_path":"lib/openzeppelin-contracts/contracts/utils/Nonces.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/Nonces.sol)\npragma solidity ^0.8.20;\n\n/**\n * @dev Provides tracking nonces for addresses. Nonces will only increment.\n */\nabstract contract Nonces {\n    /**\n     * @dev The nonce used for an `account` is not the expected current nonce.\n     */\n    error InvalidAccountNonce(address account, uint256 currentNonce);\n\n    mapping(address account => uint256) private _nonces;\n\n    /**\n     * @dev Returns the next unused nonce for an address.\n     */\n    function nonces(address owner) public view virtual returns (uint256) {\n        return _nonces[owner];\n    }\n\n    /**\n     * @dev Consumes a nonce.\n     *\n     * Returns the current value and increments nonce.\n     */\n    function _useNonce(address owner) internal virtual returns (uint256) {\n        // For each account, the nonce has an initial value of 0, can only be incremented by one, and cannot be\n        // decremented or reset. This guarantees that the nonce never overflows.\n        unchecked {\n            // It is important to do x++ and not ++x here.\n            return _nonces[owner]++;\n        }\n    }\n\n    /**\n     * @dev Same as {_useNonce} but checking that `nonce` is the next valid for `owner`.\n     */\n    function _useCheckedNonce(address owner, uint256 nonce) internal virtual {\n        uint256 current = _useNonce(owner);\n        if (nonce != current) {\n            revert InvalidAccountNonce(owner, current);\n        }\n    }\n}\n"},{"file_path":"lib/openzeppelin-contracts/contracts/token/ERC20/extensions/ERC20Burnable.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/ERC20Burnable.sol)\n\npragma solidity ^0.8.20;\n\nimport {ERC20} from \"../ERC20.sol\";\nimport {Context} from \"../../../utils/Context.sol\";\n\n/**\n * @dev Extension of {ERC20} that allows token holders to destroy both their own\n * tokens and those that they have an allowance for, in a way that can be\n * recognized off-chain (via event analysis).\n */\nabstract contract ERC20Burnable is Context, ERC20 {\n    /**\n     * @dev Destroys a `value` amount of tokens from the caller.\n     *\n     * See {ERC20-_burn}.\n     */\n    function burn(uint256 value) public virtual {\n        _burn(_msgSender(), value);\n    }\n\n    /**\n     * @dev Destroys a `value` amount of tokens from `account`, deducting from\n     * the caller's allowance.\n     *\n     * See {ERC20-_burn} and {ERC20-allowance}.\n     *\n     * Requirements:\n     *\n     * - the caller must have allowance for ``accounts``'s tokens of at least\n     * `value`.\n     */\n    function burnFrom(address account, uint256 value) public virtual {\n        _spendAllowance(account, _msgSender(), value);\n        _burn(account, value);\n    }\n}\n"},{"file_path":"lib/openzeppelin-contracts/contracts/token/ERC20/extensions/ERC4626.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.5.0) (token/ERC20/extensions/ERC4626.sol)\n\npragma solidity ^0.8.24;\n\nimport {IERC20, IERC20Metadata, ERC20} from \"../ERC20.sol\";\nimport {SafeERC20} from \"../utils/SafeERC20.sol\";\nimport {IERC4626} from \"../../../interfaces/IERC4626.sol\";\nimport {LowLevelCall} from \"../../../utils/LowLevelCall.sol\";\nimport {Memory} from \"../../../utils/Memory.sol\";\nimport {Math} from \"../../../utils/math/Math.sol\";\n\n/**\n * @dev Implementation of the ERC-4626 \"Tokenized Vault Standard\" as defined in\n * https://eips.ethereum.org/EIPS/eip-4626[ERC-4626].\n *\n * This extension allows the minting and burning of \"shares\" (represented using the ERC-20 inheritance) in exchange for\n * underlying \"assets\" through standardized {deposit}, {mint}, {redeem} and {burn} workflows. This contract extends\n * the ERC-20 standard. Any additional extensions included along it would affect the \"shares\" token represented by this\n * contract and not the \"assets\" token which is an independent contract.\n *\n * [CAUTION]\n * ====\n * In empty (or nearly empty) ERC-4626 vaults, deposits are at high risk of being stolen through frontrunning\n * with a \"donation\" to the vault that inflates the price of a share. This is variously known as a donation or inflation\n * attack and is essentially a problem of slippage. Vault deployers can protect against this attack by making an initial\n * deposit of a non-trivial amount of the asset, such that price manipulation becomes infeasible. Withdrawals may\n * similarly be affected by slippage. Users can protect against this attack as well as unexpected slippage in general by\n * verifying the amount received is as expected, using a wrapper that performs these checks such as\n * https://github.com/fei-protocol/ERC4626#erc4626router-and-base[ERC4626Router].\n *\n * Since v4.9, this implementation introduces configurable virtual assets and shares to help developers mitigate that risk.\n * The `_decimalsOffset()` corresponds to an offset in the decimal representation between the underlying asset's decimals\n * and the vault decimals. This offset also determines the rate of virtual shares to virtual assets in the vault, which\n * itself determines the initial exchange rate. While not fully preventing the attack, analysis shows that the default\n * offset (0) makes it non-profitable even if an attacker is able to capture value from multiple user deposits, as a result\n * of the value being captured by the virtual shares (out of the attacker's donation) matching the attacker's expected gains.\n * With a larger offset, the attack becomes orders of magnitude more expensive than it is profitable. More details about the\n * underlying math can be found xref:ROOT:erc4626.adoc#inflation-attack[here].\n *\n * The drawback of this approach is that the virtual shares do capture (a very small) part of the value being accrued\n * to the vault. Also, if the vault experiences losses, the users try to exit the vault, the virtual shares and assets\n * will cause the first user to exit to experience reduced losses in detriment to the last users that will experience\n * bigger losses. Developers willing to revert back to the pre-v4.9 behavior just need to override the\n * `_convertToShares` and `_convertToAssets` functions.\n *\n * To learn more, check out our xref:ROOT:erc4626.adoc[ERC-4626 guide].\n * ====\n *\n * [NOTE]\n * ====\n * When overriding this contract, some elements must be considered:\n *\n * * When overriding the behavior of the deposit or withdraw mechanisms, it is recommended to override the internal\n * functions. Overriding {_deposit} automatically affects both {deposit} and {mint}. Similarly, overriding {_withdraw}\n * automatically affects both {withdraw} and {redeem}. Overall it is not recommended to override the public facing\n * functions since that could lead to inconsistent behaviors between the {deposit} and {mint} or between {withdraw} and\n * {redeem}, which is documented to have led to loss of funds.\n *\n * * Overrides to the deposit or withdraw mechanism must be reflected in the preview functions as well.\n *\n * * {maxWithdraw} depends on {maxRedeem}. Therefore, overriding {maxRedeem} only is enough. On the other hand,\n * overriding {maxWithdraw} only would have no effect on {maxRedeem}, and could create an inconsistency between the two\n * functions.\n *\n * * If {previewRedeem} is overridden to revert, {maxWithdraw} must be overridden as necessary to ensure it\n * always return successfully.\n * ====\n */\nabstract contract ERC4626 is ERC20, IERC4626 {\n    using Math for uint256;\n\n    IERC20 private immutable _asset;\n    uint8 private immutable _underlyingDecimals;\n\n    /**\n     * @dev Attempted to deposit more assets than the max amount for `receiver`.\n     */\n    error ERC4626ExceededMaxDeposit(address receiver, uint256 assets, uint256 max);\n\n    /**\n     * @dev Attempted to mint more shares than the max amount for `receiver`.\n     */\n    error ERC4626ExceededMaxMint(address receiver, uint256 shares, uint256 max);\n\n    /**\n     * @dev Attempted to withdraw more assets than the max amount for `owner`.\n     */\n    error ERC4626ExceededMaxWithdraw(address owner, uint256 assets, uint256 max);\n\n    /**\n     * @dev Attempted to redeem more shares than the max amount for `owner`.\n     */\n    error ERC4626ExceededMaxRedeem(address owner, uint256 shares, uint256 max);\n\n    /**\n     * @dev Set the underlying asset contract. This must be an ERC20-compatible contract (ERC-20 or ERC-777).\n     */\n    constructor(IERC20 asset_) {\n        (bool success, uint8 assetDecimals) = _tryGetAssetDecimals(asset_);\n        _underlyingDecimals = success ? assetDecimals : 18;\n        _asset = asset_;\n    }\n\n    /**\n     * @dev Attempts to fetch the asset decimals. A return value of false indicates that the attempt failed in some way.\n     */\n    function _tryGetAssetDecimals(IERC20 asset_) private view returns (bool ok, uint8 assetDecimals) {\n        Memory.Pointer ptr = Memory.getFreeMemoryPointer();\n        (bool success, bytes32 returnedDecimals, ) = LowLevelCall.staticcallReturn64Bytes(\n            address(asset_),\n            abi.encodeCall(IERC20Metadata.decimals, ())\n        );\n        Memory.setFreeMemoryPointer(ptr);\n\n        return\n            (success && LowLevelCall.returnDataSize() >= 32 && uint256(returnedDecimals) <= type(uint8).max)\n                ? (true, uint8(uint256(returnedDecimals)))\n                : (false, 0);\n    }\n\n    /**\n     * @dev Decimals are computed by adding the decimal offset on top of the underlying asset's decimals. This\n     * \"original\" value is cached during construction of the vault contract. If this read operation fails (e.g., the\n     * asset has not been created yet), a default of 18 is used to represent the underlying asset's decimals.\n     *\n     * See {IERC20Metadata-decimals}.\n     */\n    function decimals() public view virtual override(IERC20Metadata, ERC20) returns (uint8) {\n        return _underlyingDecimals + _decimalsOffset();\n    }\n\n    /// @inheritdoc IERC4626\n    function asset() public view virtual returns (address) {\n        return address(_asset);\n    }\n\n    /// @inheritdoc IERC4626\n    function totalAssets() public view virtual returns (uint256) {\n        return IERC20(asset()).balanceOf(address(this));\n    }\n\n    /// @inheritdoc IERC4626\n    function convertToShares(uint256 assets) public view virtual returns (uint256) {\n        return _convertToShares(assets, Math.Rounding.Floor);\n    }\n\n    /// @inheritdoc IERC4626\n    function convertToAssets(uint256 shares) public view virtual returns (uint256) {\n        return _convertToAssets(shares, Math.Rounding.Floor);\n    }\n\n    /// @inheritdoc IERC4626\n    function maxDeposit(address) public view virtual returns (uint256) {\n        return type(uint256).max;\n    }\n\n    /// @inheritdoc IERC4626\n    function maxMint(address) public view virtual returns (uint256) {\n        return type(uint256).max;\n    }\n\n    /// @inheritdoc IERC4626\n    function maxWithdraw(address owner) public view virtual returns (uint256) {\n        return previewRedeem(maxRedeem(owner));\n    }\n\n    /// @inheritdoc IERC4626\n    function maxRedeem(address owner) public view virtual returns (uint256) {\n        return balanceOf(owner);\n    }\n\n    /// @inheritdoc IERC4626\n    function previewDeposit(uint256 assets) public view virtual returns (uint256) {\n        return _convertToShares(assets, Math.Rounding.Floor);\n    }\n\n    /// @inheritdoc IERC4626\n    function previewMint(uint256 shares) public view virtual returns (uint256) {\n        return _convertToAssets(shares, Math.Rounding.Ceil);\n    }\n\n    /// @inheritdoc IERC4626\n    function previewWithdraw(uint256 assets) public view virtual returns (uint256) {\n        return _convertToShares(assets, Math.Rounding.Ceil);\n    }\n\n    /// @inheritdoc IERC4626\n    function previewRedeem(uint256 shares) public view virtual returns (uint256) {\n        return _convertToAssets(shares, Math.Rounding.Floor);\n    }\n\n    /// @inheritdoc IERC4626\n    function deposit(uint256 assets, address receiver) public virtual returns (uint256) {\n        uint256 maxAssets = maxDeposit(receiver);\n        if (assets > maxAssets) {\n            revert ERC4626ExceededMaxDeposit(receiver, assets, maxAssets);\n        }\n\n        uint256 shares = previewDeposit(assets);\n        _deposit(_msgSender(), receiver, assets, shares);\n\n        return shares;\n    }\n\n    /// @inheritdoc IERC4626\n    function mint(uint256 shares, address receiver) public virtual returns (uint256) {\n        uint256 maxShares = maxMint(receiver);\n        if (shares > maxShares) {\n            revert ERC4626ExceededMaxMint(receiver, shares, maxShares);\n        }\n\n        uint256 assets = previewMint(shares);\n        _deposit(_msgSender(), receiver, assets, shares);\n\n        return assets;\n    }\n\n    /// @inheritdoc IERC4626\n    function withdraw(uint256 assets, address receiver, address owner) public virtual returns (uint256) {\n        uint256 maxAssets = maxWithdraw(owner);\n        if (assets > maxAssets) {\n            revert ERC4626ExceededMaxWithdraw(owner, assets, maxAssets);\n        }\n\n        uint256 shares = previewWithdraw(assets);\n        _withdraw(_msgSender(), receiver, owner, assets, shares);\n\n        return shares;\n    }\n\n    /// @inheritdoc IERC4626\n    function redeem(uint256 shares, address receiver, address owner) public virtual returns (uint256) {\n        uint256 maxShares = maxRedeem(owner);\n        if (shares > maxShares) {\n            revert ERC4626ExceededMaxRedeem(owner, shares, maxShares);\n        }\n\n        uint256 assets = previewRedeem(shares);\n        _withdraw(_msgSender(), receiver, owner, assets, shares);\n\n        return assets;\n    }\n\n    /**\n     * @dev Internal conversion function (from assets to shares) with support for rounding direction.\n     */\n    function _convertToShares(uint256 assets, Math.Rounding rounding) internal view virtual returns (uint256) {\n        return assets.mulDiv(totalSupply() + 10 ** _decimalsOffset(), totalAssets() + 1, rounding);\n    }\n\n    /**\n     * @dev Internal conversion function (from shares to assets) with support for rounding direction.\n     */\n    function _convertToAssets(uint256 shares, Math.Rounding rounding) internal view virtual returns (uint256) {\n        return shares.mulDiv(totalAssets() + 1, totalSupply() + 10 ** _decimalsOffset(), rounding);\n    }\n\n    /**\n     * @dev Deposit/mint common workflow.\n     */\n    function _deposit(address caller, address receiver, uint256 assets, uint256 shares) internal virtual {\n        // If asset() is ERC-777, `transferFrom` can trigger a reentrancy BEFORE the transfer happens through the\n        // `tokensToSend` hook. On the other hand, the `tokenReceived` hook, that is triggered after the transfer,\n        // calls the vault, which is assumed not malicious.\n        //\n        // Conclusion: we need to do the transfer before we mint so that any reentrancy would happen before the\n        // assets are transferred and before the shares are minted, which is a valid state.\n        // slither-disable-next-line reentrancy-no-eth\n        _transferIn(caller, assets);\n        _mint(receiver, shares);\n\n        emit Deposit(caller, receiver, assets, shares);\n    }\n\n    /**\n     * @dev Withdraw/redeem common workflow.\n     */\n    function _withdraw(\n        address caller,\n        address receiver,\n        address owner,\n        uint256 assets,\n        uint256 shares\n    ) internal virtual {\n        if (caller != owner) {\n            _spendAllowance(owner, caller, shares);\n        }\n\n        // If asset() is ERC-777, `transfer` can trigger a reentrancy AFTER the transfer happens through the\n        // `tokensReceived` hook. On the other hand, the `tokensToSend` hook, that is triggered before the transfer,\n        // calls the vault, which is assumed not malicious.\n        //\n        // Conclusion: we need to do the transfer after the burn so that any reentrancy would happen after the\n        // shares are burned and after the assets are transferred, which is a valid state.\n        _burn(owner, shares);\n        _transferOut(receiver, assets);\n\n        emit Withdraw(caller, receiver, owner, assets, shares);\n    }\n\n    /// @dev Performs a transfer in of underlying assets. The default implementation uses `SafeERC20`. Used by {_deposit}.\n    function _transferIn(address from, uint256 assets) internal virtual {\n        SafeERC20.safeTransferFrom(IERC20(asset()), from, address(this), assets);\n    }\n\n    /// @dev Performs a transfer out of underlying assets. The default implementation uses `SafeERC20`. Used by {_withdraw}.\n    function _transferOut(address to, uint256 assets) internal virtual {\n        SafeERC20.safeTransfer(IERC20(asset()), to, assets);\n    }\n\n    function _decimalsOffset() internal view virtual returns (uint8) {\n        return 0;\n    }\n}\n"},{"file_path":"src/locking/LockingController.sol","source_code":"// SPDX-License-Identifier: MIT\npragma solidity 0.8.28;\n\nimport {IERC20} from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport {ERC20Burnable} from \"@openzeppelin/contracts/token/ERC20/extensions/ERC20Burnable.sol\";\nimport {FixedPointMathLib} from \"@solmate/src/utils/FixedPointMathLib.sol\";\n\nimport {CoreRoles} from \"@libraries/CoreRoles.sol\";\nimport {CoreControlled} from \"@core/CoreControlled.sol\";\nimport {UnwindingModule} from \"@locking/UnwindingModule.sol\";\nimport {LockedPositionToken} from \"@tokens/LockedPositionToken.sol\";\n\ncontract LockingController is CoreControlled {\n    using FixedPointMathLib for uint256;\n\n    /// @notice address of the locked token\n    address public immutable receiptToken;\n\n    /// @notice address of the unwinding module\n    address public immutable unwindingModule;\n\n    /// ----------------------------------------------------------------------------\n    /// STRUCTS, ERRORS, AND EVENTS\n    /// ----------------------------------------------------------------------------\n\n    struct BucketData {\n        address shareToken;\n        uint256 totalReceiptTokens;\n        uint256 multiplier;\n    }\n\n    error TransferFailed();\n    error InvalidBucket(uint32 unwindingEpochs);\n    error InvalidUnwindingEpochs(uint32 unwindingEpochs);\n    error BucketMustBeLongerDuration(uint32 oldValue, uint32 newValue);\n    error UnwindingInProgress();\n    error InvalidMaxLossPercentage(uint256 maxLossPercentage);\n\n    event PositionCreated(\n        uint256 indexed timestamp, address indexed user, uint256 amount, uint32 indexed unwindingEpochs\n    );\n    event PositionRemoved(\n        uint256 indexed timestamp, address indexed user, uint256 amount, uint32 indexed unwindingEpochs\n    );\n    event RewardsDeposited(uint256 indexed timestamp, uint256 amount);\n    event LossesApplied(uint256 indexed timestamp, uint256 amount);\n    event BucketEnabled(uint256 indexed timestamp, uint256 bucket, address shareToken, uint256 multiplier);\n    event BucketMultiplierUpdated(uint256 indexed timestamp, uint256 bucket, uint256 multiplier);\n    event MaxLossPercentageUpdated(uint256 indexed timestamp, uint256 maxLossPercentage);\n    /// ----------------------------------------------------------------------------\n    /// STATE\n    /// ----------------------------------------------------------------------------\n\n    /// @notice array of all enabled unwinding epochs\n    /// @dev example, this array will contain [2, 4, 6] if users are allowed to\n    /// lock for 2, 4 and 6 weeks respectively\n    uint32[] public enabledBuckets;\n\n    /// @notice mapping of unwinding epochs data\n    mapping(uint32 _unwindingEpochs => BucketData data) public buckets;\n\n    uint256 public globalReceiptToken;\n    uint256 public globalRewardWeight;\n\n    /// @notice maximum loss percentage for the locking module in WAD (18 decimals)\n    uint256 public maxLossPercentage = 0.999999e18;\n\n    /// ----------------------------------------------------------------------------\n    /// CONSTRUCTOR\n    /// ----------------------------------------------------------------------------\n\n    constructor(address _core, address _receiptToken, address _unwindingModule) CoreControlled(_core) {\n        receiptToken = _receiptToken;\n        unwindingModule = _unwindingModule;\n    }\n\n    /// ----------------------------------------------------------------------------\n    /// ADMINISTRATION METHODS\n    /// ----------------------------------------------------------------------------\n\n    /// @notice enable a new unwinding epochs duration\n    function enableBucket(uint32 _unwindingEpochs, address _shareToken, uint256 _multiplier)\n        external\n        onlyCoreRole(CoreRoles.GOVERNOR)\n    {\n        require(buckets[_unwindingEpochs].shareToken == address(0), InvalidBucket(_unwindingEpochs));\n        require(_unwindingEpochs > 0, InvalidUnwindingEpochs(_unwindingEpochs));\n        require(_unwindingEpochs <= 100, InvalidUnwindingEpochs(_unwindingEpochs));\n\n        buckets[_unwindingEpochs].shareToken = _shareToken;\n        buckets[_unwindingEpochs].multiplier = _multiplier;\n        enabledBuckets.push(_unwindingEpochs);\n        emit BucketEnabled(block.timestamp, _unwindingEpochs, _shareToken, _multiplier);\n    }\n\n    /// @notice update the multiplier of a given bucket\n    /// @dev note that this won't affect the unwinding users, unless they cancel their unwinding\n    function setBucketMultiplier(uint32 _unwindingEpochs, uint256 _multiplier)\n        external\n        onlyCoreRole(CoreRoles.PROTOCOL_PARAMETERS)\n    {\n        BucketData memory data = buckets[_unwindingEpochs];\n        require(data.shareToken != address(0), InvalidBucket(_unwindingEpochs));\n\n        uint256 oldRewardWeight = data.totalReceiptTokens.mulWadDown(data.multiplier);\n        uint256 newRewardWeight = data.totalReceiptTokens.mulWadDown(_multiplier);\n        globalRewardWeight = globalRewardWeight + newRewardWeight - oldRewardWeight;\n        buckets[_unwindingEpochs].multiplier = _multiplier;\n        emit BucketMultiplierUpdated(block.timestamp, _unwindingEpochs, _multiplier);\n    }\n\n    function setMaxLossPercentage(uint256 _maxLossPercentage) external onlyCoreRole(CoreRoles.GOVERNOR) {\n        require(_maxLossPercentage <= FixedPointMathLib.WAD, InvalidMaxLossPercentage(_maxLossPercentage));\n        maxLossPercentage = _maxLossPercentage;\n        emit MaxLossPercentageUpdated(block.timestamp, _maxLossPercentage);\n    }\n\n    /// ----------------------------------------------------------------------------\n    /// READ METHODS\n    /// ----------------------------------------------------------------------------\n\n    /// @notice get the enabled unwinding epochs\n    function getEnabledBuckets() external view returns (uint32[] memory) {\n        return enabledBuckets;\n    }\n\n    /// @notice get the balance of a user by looping through all the enabled unwinding epochs\n    /// and looking at how many share tokens the user has, then multiplying for each of them\n    /// by the current share price.\n    /// @dev Balance is expressed in receipt tokens.\n    function balanceOf(address _user) external view returns (uint256) {\n        return _userSumAcrossUnwindingEpochs(_user, _totalReceiptTokensGetter);\n    }\n\n    /// @notice get the reward weight of a user by looping through all the enabled unwinding epochs\n    /// and looking at how many share tokens the user has, then multiplying for each of them\n    /// by the current reward weight of these shares.\n    /// @dev Reward weight is expressed in \"virtual receipt tokens\" and is used to compute the\n    /// rewards earned during yield distribution.\n    function rewardWeight(address _user) external view returns (uint256) {\n        return _userSumAcrossUnwindingEpochs(_user, _bucketRewardWeightGetter);\n    }\n\n    /// @notice get the reward weight of a user\n    function rewardWeightForUnwindingEpochs(address _user, uint32 _unwindingEpochs) external view returns (uint256) {\n        BucketData memory data = buckets[_unwindingEpochs];\n\n        uint256 userShares = IERC20(data.shareToken).balanceOf(_user);\n        uint256 totalShares = IERC20(data.shareToken).totalSupply();\n        if (totalShares == 0) return 0;\n        uint256 bucketRewardWeight = data.totalReceiptTokens.mulWadDown(data.multiplier);\n        return userShares.mulDivDown(bucketRewardWeight, totalShares);\n    }\n\n    /// @notice get the shares of a user for a given unwindingEpochs\n    function shares(address _user, uint32 _unwindingEpochs) external view returns (uint256) {\n        BucketData memory data = buckets[_unwindingEpochs];\n        if (data.shareToken == address(0)) return 0;\n        return IERC20(data.shareToken).balanceOf(_user);\n    }\n\n    /// @notice get the shares token of a given unwindingEpochs, 0 if not enabled\n    function shareToken(uint32 _unwindingEpochs) external view returns (address) {\n        return buckets[_unwindingEpochs].shareToken;\n    }\n\n    /// @notice get the current exchange rate between the receiptToken and a given shareToken.\n    /// This function is here for convenience, to help share token holders estimate the value of their tokens.\n    /// @dev returns 0 if the _unwindingEpochs is not valid or if there are no locks for this duration\n    function exchangeRate(uint32 _unwindingEpochs) external view returns (uint256) {\n        BucketData memory data = buckets[_unwindingEpochs];\n        if (data.shareToken == address(0)) return 0;\n        uint256 totalShares = IERC20(data.shareToken).totalSupply();\n        if (totalShares == 0) return 0;\n        return data.totalReceiptTokens.divWadDown(totalShares);\n    }\n\n    /// @notice returns true if the given unwinding epochs is enabled for locking\n    function unwindingEpochsEnabled(uint32 _unwindingEpochs) external view returns (bool) {\n        return buckets[_unwindingEpochs].shareToken != address(0);\n    }\n\n    /// @notice total balance of receipt tokens in the module\n    /// @dev note that due to rounding down in the protocol's favor, this might be slightly\n    /// above the sum of the balanceOf() of all users.\n    function totalBalance() public view returns (uint256) {\n        return globalReceiptToken + UnwindingModule(unwindingModule).totalReceiptTokens();\n    }\n\n    /// @notice multiplier to apply to totalBalance() for computing rewards in profit distribution,\n    /// Expressed as a WAD (18 decimals). Should be between [1.0e18, 2.0e18] realistically.\n    function rewardMultiplier() external view returns (uint256) {\n        uint256 totalWeight = globalRewardWeight + UnwindingModule(unwindingModule).totalRewardWeight();\n        if (totalWeight == 0) return FixedPointMathLib.WAD; // defaults to 1.0\n        return totalWeight.divWadDown(totalBalance());\n    }\n\n    /// ----------------------------------------------------------------------------\n    /// POSITION MANAGEMENT WRITE METHODS\n    /// ----------------------------------------------------------------------------\n\n    /// @notice Enter a locked position\n    function createPosition(uint256 _amount, uint32 _unwindingEpochs, address _recipient) external whenNotPaused {\n        if (msg.sender != unwindingModule) {\n            // special case for access control here, the unwindingModule can reenter createPosition()\n            // after being called by this contract's cancelUnwinding() function.\n            // this exception is preferable to granting ENTRY_POINT role to the unwindingModule.\n            require(core().hasRole(CoreRoles.ENTRY_POINT, msg.sender), \"UNAUTHORIZED\");\n        }\n\n        BucketData memory data = buckets[_unwindingEpochs];\n        require(data.shareToken != address(0), InvalidBucket(_unwindingEpochs));\n        require(IERC20(receiptToken).transferFrom(msg.sender, address(this), _amount), TransferFailed());\n\n        uint256 totalShares = IERC20(data.shareToken).totalSupply();\n        uint256 newShares = totalShares == 0 ? _amount : _amount.mulDivDown(totalShares, data.totalReceiptTokens);\n        uint256 bucketRewardWeightBefore = data.totalReceiptTokens.mulWadDown(data.multiplier);\n        data.totalReceiptTokens += _amount;\n        globalReceiptToken += _amount;\n        buckets[_unwindingEpochs] = data;\n        uint256 bucketRewardWeightAfter = data.totalReceiptTokens.mulWadDown(data.multiplier);\n        globalRewardWeight += bucketRewardWeightAfter - bucketRewardWeightBefore;\n\n        LockedPositionToken(data.shareToken).mint(_recipient, newShares);\n        emit PositionCreated(block.timestamp, _recipient, _amount, _unwindingEpochs);\n    }\n\n    /// @notice Start unwinding a locked position\n    function startUnwinding(uint256 _shares, uint32 _unwindingEpochs, address _recipient)\n        external\n        whenNotPaused\n        onlyCoreRole(CoreRoles.ENTRY_POINT)\n    {\n        BucketData memory data = buckets[_unwindingEpochs];\n        require(data.shareToken != address(0), InvalidBucket(_unwindingEpochs));\n\n        uint256 totalShares = IERC20(data.shareToken).totalSupply();\n        uint256 userReceiptToken = _shares.mulDivDown(data.totalReceiptTokens, totalShares);\n\n        require(IERC20(data.shareToken).transferFrom(msg.sender, address(this), _shares), TransferFailed());\n        LockedPositionToken(data.shareToken).burn(_shares);\n\n        UnwindingModule(unwindingModule)\n            .startUnwinding(\n                _recipient, userReceiptToken, _unwindingEpochs, userReceiptToken.mulWadDown(data.multiplier)\n            );\n        // forge-lint: disable-next-line(erc20-unchecked-transfer)\n        IERC20(receiptToken).transfer(unwindingModule, userReceiptToken);\n\n        buckets[_unwindingEpochs].totalReceiptTokens = data.totalReceiptTokens - userReceiptToken;\n        uint256 bucketRewardWeightBefore = data.totalReceiptTokens.mulWadDown(data.multiplier);\n        uint256 bucketRewardWeightAfter = (data.totalReceiptTokens - userReceiptToken).mulWadDown(data.multiplier);\n        uint256 rewardWeightDecrease = bucketRewardWeightBefore - bucketRewardWeightAfter;\n        globalRewardWeight -= rewardWeightDecrease;\n        globalReceiptToken -= userReceiptToken;\n\n        emit PositionRemoved(block.timestamp, _recipient, userReceiptToken, _unwindingEpochs);\n    }\n\n    /// @notice Increase the unwinding period of a position\n    function increaseUnwindingEpochs(\n        uint256 _shares,\n        uint32 _oldUnwindingEpochs,\n        uint32 _newUnwindingEpochs,\n        address _recipient\n    ) external whenNotPaused onlyCoreRole(CoreRoles.ENTRY_POINT) {\n        require(\n            _newUnwindingEpochs > _oldUnwindingEpochs,\n            BucketMustBeLongerDuration(_oldUnwindingEpochs, _newUnwindingEpochs)\n        );\n\n        BucketData memory oldData = buckets[_oldUnwindingEpochs];\n        BucketData memory newData = buckets[_newUnwindingEpochs];\n\n        require(newData.shareToken != address(0), InvalidBucket(_newUnwindingEpochs));\n\n        // burn position in old share tokens\n        if (_shares == 0) return;\n        uint256 oldTotalSupply = IERC20(oldData.shareToken).totalSupply();\n        uint256 receiptTokens = _shares.mulDivDown(oldData.totalReceiptTokens, oldTotalSupply);\n        if (receiptTokens == 0) return;\n\n        // compute global reward weight change\n        {\n            uint256 oldBucketRewardWeightBefore = oldData.totalReceiptTokens.mulWadDown(oldData.multiplier);\n            uint256 oldBucketRewardWeightAfter =\n                (oldData.totalReceiptTokens - receiptTokens).mulWadDown(oldData.multiplier);\n            uint256 newBucketRewardWeightBefore = newData.totalReceiptTokens.mulWadDown(newData.multiplier);\n            uint256 newBucketRewardWeightAfter =\n                (newData.totalReceiptTokens + receiptTokens).mulWadDown(newData.multiplier);\n\n            uint256 _globalRewardWeight = globalRewardWeight;\n            _globalRewardWeight = _globalRewardWeight - oldBucketRewardWeightBefore + oldBucketRewardWeightAfter;\n            _globalRewardWeight = _globalRewardWeight - newBucketRewardWeightBefore + newBucketRewardWeightAfter;\n            globalRewardWeight = _globalRewardWeight;\n        }\n\n        ERC20Burnable(oldData.shareToken).burnFrom(msg.sender, _shares);\n        oldData.totalReceiptTokens -= receiptTokens;\n        buckets[_oldUnwindingEpochs] = oldData;\n\n        // mint position in new share tokens\n        uint256 newTotalSupply = IERC20(newData.shareToken).totalSupply();\n        uint256 newShares =\n            newTotalSupply == 0 ? receiptTokens : receiptTokens.mulDivDown(newTotalSupply, newData.totalReceiptTokens);\n        LockedPositionToken(newData.shareToken).mint(_recipient, newShares);\n        newData.totalReceiptTokens += receiptTokens;\n        buckets[_newUnwindingEpochs] = newData;\n\n        emit PositionRemoved(block.timestamp, _recipient, receiptTokens, _oldUnwindingEpochs);\n        emit PositionCreated(block.timestamp, _recipient, receiptTokens, _newUnwindingEpochs);\n    }\n\n    /// @notice Cancel an ongoing unwinding. All checks are performed by the Unwinding module.\n    function cancelUnwinding(address _user, uint256 _unwindingTimestamp, uint32 _newUnwindingEpochs)\n        external\n        whenNotPaused\n        onlyCoreRole(CoreRoles.ENTRY_POINT)\n    {\n        UnwindingModule(unwindingModule).cancelUnwinding(_user, _unwindingTimestamp, _newUnwindingEpochs);\n    }\n\n    /// @notice Withdraw after an unwinding period has completed\n    function withdraw(address _user, uint256 _unwindingTimestamp)\n        external\n        whenNotPaused\n        onlyCoreRole(CoreRoles.ENTRY_POINT)\n    {\n        UnwindingModule(unwindingModule).withdraw(_unwindingTimestamp, _user);\n    }\n\n    /// ----------------------------------------------------------------------------\n    /// INTERNAL UTILS\n    /// ----------------------------------------------------------------------------\n\n    function _userSumAcrossUnwindingEpochs(address _user, function(BucketData memory) view returns (uint256) _getter)\n        internal\n        view\n        returns (uint256)\n    {\n        uint256 weight;\n        uint256 nBuckets = enabledBuckets.length;\n        for (uint256 i = 0; i < nBuckets; i++) {\n            uint32 unwindingEpochs = enabledBuckets[i];\n            BucketData memory data = buckets[unwindingEpochs];\n\n            uint256 userShares = IERC20(data.shareToken).balanceOf(_user);\n            if (userShares == 0) continue;\n            uint256 totalShares = IERC20(data.shareToken).totalSupply();\n            if (totalShares == 0) continue;\n            weight += userShares.mulDivDown(_getter(data), totalShares);\n        }\n        return weight;\n    }\n\n    function _bucketRewardWeightGetter(BucketData memory data) internal pure returns (uint256) {\n        return data.totalReceiptTokens.mulWadDown(data.multiplier);\n    }\n\n    function _totalReceiptTokensGetter(BucketData memory data) internal pure returns (uint256) {\n        return data.totalReceiptTokens;\n    }\n\n    function _min(uint256 a, uint256 b) internal pure returns (uint256) {\n        return a < b ? a : b;\n    }\n\n    /// ----------------------------------------------------------------------------\n    /// REWARDS MANAGEMENT WRITE METHODS\n    /// ----------------------------------------------------------------------------\n\n    /// @notice Deposit rewards into the locking module\n    function depositRewards(uint256 _amount) external onlyCoreRole(CoreRoles.FINANCE_MANAGER) {\n        if (_amount == 0) return;\n\n        emit RewardsDeposited(block.timestamp, _amount);\n\n        require(IERC20(receiptToken).transferFrom(msg.sender, address(this), _amount), TransferFailed());\n\n        // compute split between locking users & unwinding users\n        uint256 _globalRewardWeight = globalRewardWeight;\n        uint256 unwindingRewardWeight = UnwindingModule(unwindingModule).totalRewardWeight();\n        uint256 unwindingRewards =\n            _amount.mulDivDown(unwindingRewardWeight, _globalRewardWeight + unwindingRewardWeight);\n        if (unwindingRewards > 0) {\n            UnwindingModule(unwindingModule).depositRewards(unwindingRewards);\n            require(IERC20(receiptToken).transfer(unwindingModule, unwindingRewards), TransferFailed());\n            _amount -= unwindingRewards;\n\n            // if there are no rewards to distribute, do nothing\n            if (_amount == 0) return;\n        }\n\n        // if there are no recipients, receiptTokens are pulled to this contract\n        // but won't be claimable by anyone\n        // this happens only if the ProfitManager sends rewards to the locking module\n        // even though no one is locked, which should never happen.\n        if (_globalRewardWeight == 0) return;\n\n        uint256 _newGlobalRewardWeight = 0;\n        uint256 _receiptTokensIncrement = 0;\n        uint256 nBuckets = enabledBuckets.length;\n        for (uint256 i = 0; i < nBuckets; i++) {\n            BucketData storage data = buckets[enabledBuckets[i]];\n\n            // increase total locked tokens\n            uint256 epochTotalReceiptToken = data.totalReceiptTokens;\n            uint256 bucketRewardWeight = epochTotalReceiptToken.mulWadDown(data.multiplier);\n            uint256 allocation = _amount.mulDivDown(bucketRewardWeight, _globalRewardWeight);\n\n            data.totalReceiptTokens = epochTotalReceiptToken + allocation;\n            _receiptTokensIncrement += allocation;\n\n            _newGlobalRewardWeight += (epochTotalReceiptToken + allocation).mulWadDown(data.multiplier);\n        }\n\n        globalReceiptToken += _receiptTokensIncrement;\n        globalRewardWeight = _newGlobalRewardWeight;\n    }\n\n    /// @notice Apply losses to the locking module\n    function applyLosses(uint256 _amount) external onlyCoreRole(CoreRoles.FINANCE_MANAGER) {\n        if (_amount == 0) return;\n\n        emit LossesApplied(block.timestamp, _amount);\n\n        // compute split between locking users & unwinding users\n        uint256 unwindingBalance = UnwindingModule(unwindingModule).totalReceiptTokens();\n        uint256 _globalReceiptToken = globalReceiptToken;\n        uint256 _totalBalance = _globalReceiptToken + unwindingBalance;\n\n        // if the amount to apply is greater than the maximum allowed loss,\n        // we need to apply all the losses and pause the contract\n        {\n            uint256 maximumAllowedLoss = _totalBalance.mulDivDown(maxLossPercentage, 1e18);\n            if (_amount > maximumAllowedLoss) {\n                UnwindingModule(unwindingModule).applyLosses(unwindingBalance);\n                ERC20Burnable(receiptToken).burn(_globalReceiptToken);\n                globalReceiptToken = 0;\n                globalRewardWeight = 0;\n                for (uint256 i = 0; i < enabledBuckets.length; i++) {\n                    buckets[enabledBuckets[i]].totalReceiptTokens = 0;\n                }\n                _pause();\n                return;\n            }\n        }\n\n        // apply losses to the unwinding module\n        uint256 amountToUnwinding = _amount.mulDivUp(unwindingBalance, _totalBalance);\n        amountToUnwinding = _min(amountToUnwinding, unwindingBalance);\n        UnwindingModule(unwindingModule).applyLosses(amountToUnwinding);\n        _amount -= amountToUnwinding;\n\n        // No more losses to apply, and the UnwindingModule is not slashed\n        // So we can safely exit the function\n        if (_amount == 0) return;\n\n        _amount = _min(_amount, _globalReceiptToken);\n\n        ERC20Burnable(receiptToken).burn(_amount);\n\n        uint256 nBuckets = enabledBuckets.length;\n        uint256 newGlobalRewardWeight = 0;\n        uint256 globalReceiptTokenDecrement = 0;\n        for (uint256 i = 0; i < nBuckets; i++) {\n            BucketData storage data = buckets[enabledBuckets[i]];\n\n            // slash principal\n            uint256 epochTotalReceiptToken = data.totalReceiptTokens;\n            if (epochTotalReceiptToken == 0) continue;\n            uint256 allocation = epochTotalReceiptToken.mulDivUp(_amount, _globalReceiptToken);\n            allocation = _min(allocation, epochTotalReceiptToken); // up rounding could cause underflows\n            data.totalReceiptTokens = epochTotalReceiptToken - allocation;\n            globalReceiptTokenDecrement += allocation;\n\n            newGlobalRewardWeight += (epochTotalReceiptToken - allocation).mulWadDown(data.multiplier);\n        }\n\n        globalReceiptToken = _globalReceiptToken - globalReceiptTokenDecrement;\n        globalRewardWeight = newGlobalRewardWeight;\n\n        {\n            // if a full slashing occurred either in UnwindingModule due to rounding errors,\n            // pause the contract to prevent any further operations.\n            // Resolving the situation will require a protocol upgrade,\n            // as the slashIndex in the UnwindingModule is now 0.\n            uint256 slashIndex = UnwindingModule(unwindingModule).slashIndex();\n            bool unwindingWipedOut = amountToUnwinding > 0 && slashIndex == 0;\n            if (unwindingWipedOut) _pause();\n        }\n    }\n}\n"},{"file_path":"src/libraries/CoreRoles.sol","source_code":"// SPDX-License-Identifier: MIT\npragma solidity 0.8.28;\n\n/// @notice Holds a complete list of all roles which can be held by contracts inside the InfiniFi protocol.\nlibrary CoreRoles {\n    /// ----------- Core roles for access control --------------\n    /// @notice the all-powerful role. Controls all other roles and protocol functionality.\n    bytes32 internal constant GOVERNOR = keccak256(\"GOVERNOR\");\n\n    /// @notice Can pause contracts in an emergency.\n    bytes32 internal constant PAUSE = keccak256(\"PAUSE\");\n\n    /// @notice Can unpause contracts after an emergency.\n    bytes32 internal constant UNPAUSE = keccak256(\"UNPAUSE\");\n\n    /// @notice can tweak protocol parameters\n    bytes32 internal constant PROTOCOL_PARAMETERS = keccak256(\"PROTOCOL_PARAMETERS\");\n\n    /// @notice can manage minor roles\n    bytes32 internal constant MINOR_ROLES_MANAGER = keccak256(\"MINOR_ROLES_MANAGER\");\n\n    /// ----------- User Flow Management -----------------------\n\n    /// @notice Granted to the user entry point of the system\n    bytes32 internal constant ENTRY_POINT = keccak256(\"ENTRY_POINT\");\n\n    /// ----------- Token Management ---------------------------\n\n    /// @notice can mint ReceiptToken arbitrarily\n    bytes32 internal constant RECEIPT_TOKEN_MINTER = keccak256(\"RECEIPT_TOKEN_MINTER\");\n\n    /// @notice can burn ReceiptToken tokens\n    bytes32 internal constant RECEIPT_TOKEN_BURNER = keccak256(\"RECEIPT_TOKEN_BURNER\");\n\n    /// @notice can mint GovernanceToken arbitrarily\n    bytes32 internal constant GOVERNANCE_TOKEN_MINTER = keccak256(\"GOVERNANCE_TOKEN_MINTER\");\n\n    /// @notice can burn GovernanceToken tokens\n    bytes32 internal constant GOVERNANCE_TOKEN_BURNER = keccak256(\"GOVERNANCE_TOKEN_BURNER\");\n\n    /// @notice can mint arbitrarily & burn held LockedPositionToken\n    bytes32 internal constant LOCKED_TOKEN_MANAGER = keccak256(\"LOCKED_TOKEN_MANAGER\");\n\n    /// @notice can prevent transfers of LockedPositionToken\n    bytes32 internal constant TRANSFER_RESTRICTOR = keccak256(\"TRANSFER_RESTRICTOR\");\n\n    /// ----------- Funds Management & Accounting --------------\n\n    /// @notice contract that can allocate funds between farms\n    bytes32 internal constant FARM_MANAGER = keccak256(\"FARM_MANAGER\");\n\n    /// @notice addresses who can use the manual rebalancer\n    bytes32 internal constant MANUAL_REBALANCER = keccak256(\"MANUAL_REBALANCER\");\n\n    /// @notice addresses who can use the periodic rebalancer\n    bytes32 internal constant PERIODIC_REBALANCER = keccak256(\"PERIODIC_REBALANCER\");\n\n    /// @notice addresses who can move funds from farms to a safe address\n    bytes32 internal constant EMERGENCY_WITHDRAWAL = keccak256(\"EMERGENCY_WITHDRAWAL\");\n\n    /// @notice addresses who can trigger swaps in Farms\n    bytes32 internal constant FARM_SWAP_CALLER = keccak256(\"FARM_SWAP_CALLER\");\n\n    /// @notice can set oracles references within the system\n    bytes32 internal constant ORACLE_MANAGER = keccak256(\"ORACLE_MANAGER\");\n\n    /// @notice trusted to report profit and losses in the system.\n    /// This role can be used to slash depositors in case of losses, and\n    /// can also deposit profits for distribution to end users.\n    bytes32 internal constant FINANCE_MANAGER = keccak256(\"FINANCE_MANAGER\");\n\n    /// @notice can accrue pending yield in the system\n    bytes32 internal constant ACCRUE_YIELD = keccak256(\"ACCRUE_YIELD\");\n\n    /// ----------- Timelock management ------------------------\n    /// The hashes are the same as OpenZeppelins's roles in TimelockController\n\n    /// @notice can propose new actions in timelocks\n    bytes32 internal constant PROPOSER_ROLE = keccak256(\"PROPOSER_ROLE\");\n\n    /// @notice can execute actions in timelocks after their delay\n    bytes32 internal constant EXECUTOR_ROLE = keccak256(\"EXECUTOR_ROLE\");\n\n    /// @notice can cancel actions in timelocks\n    bytes32 internal constant CANCELLER_ROLE = keccak256(\"CANCELLER_ROLE\");\n\n    /// ----------- Crosschain ------------------------\n\n    /// @notice controls bridging and messaging process\n    bytes32 internal constant OUTLAND_PORTAL = keccak256(\"OUTLAND_PORTAL\");\n\n    /// @notice can execute operations required by offchain keeper\n    /// example is submitting burn proofs to circle gateway\n    /// portal should have keeper role as well\n    bytes32 internal constant OUTLAND_KEEPER = keccak256(\"OUTLAND_KEEPER\");\n}\n"},{"file_path":"lib/openzeppelin-contracts/contracts/token/ERC20/extensions/ERC20Permit.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.5.0) (token/ERC20/extensions/ERC20Permit.sol)\n\npragma solidity ^0.8.24;\n\nimport {IERC20Permit} from \"./IERC20Permit.sol\";\nimport {ERC20} from \"../ERC20.sol\";\nimport {ECDSA} from \"../../../utils/cryptography/ECDSA.sol\";\nimport {EIP712} from \"../../../utils/cryptography/EIP712.sol\";\nimport {Nonces} from \"../../../utils/Nonces.sol\";\n\n/**\n * @dev Implementation of the ERC-20 Permit extension allowing approvals to be made via signatures, as defined in\n * https://eips.ethereum.org/EIPS/eip-2612[ERC-2612].\n *\n * Adds the {permit} method, which can be used to change an account's ERC-20 allowance (see {IERC20-allowance}) by\n * presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't\n * need to send a transaction, and thus is not required to hold Ether at all.\n */\nabstract contract ERC20Permit is ERC20, IERC20Permit, EIP712, Nonces {\n    bytes32 private constant PERMIT_TYPEHASH =\n        keccak256(\"Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)\");\n\n    /**\n     * @dev Permit deadline has expired.\n     */\n    error ERC2612ExpiredSignature(uint256 deadline);\n\n    /**\n     * @dev Mismatched signature.\n     */\n    error ERC2612InvalidSigner(address signer, address owner);\n\n    /**\n     * @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `\"1\"`.\n     *\n     * It's a good idea to use the same `name` that is defined as the ERC-20 token name.\n     */\n    constructor(string memory name) EIP712(name, \"1\") {}\n\n    /// @inheritdoc IERC20Permit\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        if (block.timestamp > deadline) {\n            revert ERC2612ExpiredSignature(deadline);\n        }\n\n        bytes32 structHash = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline));\n\n        bytes32 hash = _hashTypedDataV4(structHash);\n\n        address signer = ECDSA.recover(hash, v, r, s);\n        if (signer != owner) {\n            revert ERC2612InvalidSigner(signer, owner);\n        }\n\n        _approve(owner, spender, value);\n    }\n\n    /// @inheritdoc IERC20Permit\n    function nonces(address owner) public view virtual override(IERC20Permit, Nonces) returns (uint256) {\n        return super.nonces(owner);\n    }\n\n    /// @inheritdoc IERC20Permit\n    // solhint-disable-next-line func-name-mixedcase\n    function DOMAIN_SEPARATOR() external view returns (bytes32) {\n        return _domainSeparatorV4();\n    }\n}\n"},{"file_path":"lib/openzeppelin-contracts/contracts/access/AccessControl.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.4.0) (access/AccessControl.sol)\n\npragma solidity ^0.8.20;\n\nimport {IAccessControl} from \"./IAccessControl.sol\";\nimport {Context} from \"../utils/Context.sol\";\nimport {ERC165} from \"../utils/introspection/ERC165.sol\";\n\n/**\n * @dev Contract module that allows children to implement role-based access\n * control mechanisms. This is a lightweight version that doesn't allow enumerating role\n * members except through off-chain means by accessing the contract event logs. Some\n * applications may benefit from on-chain enumerability, for those cases see\n * {AccessControlEnumerable}.\n *\n * Roles are referred to by their `bytes32` identifier. These should be exposed\n * in the external API and be unique. The best way to achieve this is by\n * using `public constant` hash digests:\n *\n * ```solidity\n * bytes32 public constant MY_ROLE = keccak256(\"MY_ROLE\");\n * ```\n *\n * Roles can be used to represent a set of permissions. To restrict access to a\n * function call, use {hasRole}:\n *\n * ```solidity\n * function foo() public {\n *     require(hasRole(MY_ROLE, msg.sender));\n *     ...\n * }\n * ```\n *\n * Roles can be granted and revoked dynamically via the {grantRole} and\n * {revokeRole} functions. Each role has an associated admin role, and only\n * accounts that have a role's admin role can call {grantRole} and {revokeRole}.\n *\n * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means\n * that only accounts with this role will be able to grant or revoke other\n * roles. More complex role relationships can be created by using\n * {_setRoleAdmin}.\n *\n * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to\n * grant and revoke this role. Extra precautions should be taken to secure\n * accounts that have been granted it. We recommend using {AccessControlDefaultAdminRules}\n * to enforce additional security measures for this role.\n */\nabstract contract AccessControl is Context, IAccessControl, ERC165 {\n    struct RoleData {\n        mapping(address account => bool) hasRole;\n        bytes32 adminRole;\n    }\n\n    mapping(bytes32 role => RoleData) private _roles;\n\n    bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;\n\n    /**\n     * @dev Modifier that checks that an account has a specific role. Reverts\n     * with an {AccessControlUnauthorizedAccount} error including the required role.\n     */\n    modifier onlyRole(bytes32 role) {\n        _checkRole(role);\n        _;\n    }\n\n    /// @inheritdoc ERC165\n    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n        return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);\n    }\n\n    /**\n     * @dev Returns `true` if `account` has been granted `role`.\n     */\n    function hasRole(bytes32 role, address account) public view virtual returns (bool) {\n        return _roles[role].hasRole[account];\n    }\n\n    /**\n     * @dev Reverts with an {AccessControlUnauthorizedAccount} error if `_msgSender()`\n     * is missing `role`. Overriding this function changes the behavior of the {onlyRole} modifier.\n     */\n    function _checkRole(bytes32 role) internal view virtual {\n        _checkRole(role, _msgSender());\n    }\n\n    /**\n     * @dev Reverts with an {AccessControlUnauthorizedAccount} error if `account`\n     * is missing `role`.\n     */\n    function _checkRole(bytes32 role, address account) internal view virtual {\n        if (!hasRole(role, account)) {\n            revert AccessControlUnauthorizedAccount(account, role);\n        }\n    }\n\n    /**\n     * @dev Returns the admin role that controls `role`. See {grantRole} and\n     * {revokeRole}.\n     *\n     * To change a role's admin, use {_setRoleAdmin}.\n     */\n    function getRoleAdmin(bytes32 role) public view virtual returns (bytes32) {\n        return _roles[role].adminRole;\n    }\n\n    /**\n     * @dev Grants `role` to `account`.\n     *\n     * If `account` had not been already granted `role`, emits a {RoleGranted}\n     * event.\n     *\n     * Requirements:\n     *\n     * - the caller must have ``role``'s admin role.\n     *\n     * May emit a {RoleGranted} event.\n     */\n    function grantRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {\n        _grantRole(role, account);\n    }\n\n    /**\n     * @dev Revokes `role` from `account`.\n     *\n     * If `account` had been granted `role`, emits a {RoleRevoked} event.\n     *\n     * Requirements:\n     *\n     * - the caller must have ``role``'s admin role.\n     *\n     * May emit a {RoleRevoked} event.\n     */\n    function revokeRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {\n        _revokeRole(role, account);\n    }\n\n    /**\n     * @dev Revokes `role` from the calling account.\n     *\n     * Roles are often managed via {grantRole} and {revokeRole}: this function's\n     * purpose is to provide a mechanism for accounts to lose their privileges\n     * if they are compromised (such as when a trusted device is misplaced).\n     *\n     * If the calling account had been revoked `role`, emits a {RoleRevoked}\n     * event.\n     *\n     * Requirements:\n     *\n     * - the caller must be `callerConfirmation`.\n     *\n     * May emit a {RoleRevoked} event.\n     */\n    function renounceRole(bytes32 role, address callerConfirmation) public virtual {\n        if (callerConfirmation != _msgSender()) {\n            revert AccessControlBadConfirmation();\n        }\n\n        _revokeRole(role, callerConfirmation);\n    }\n\n    /**\n     * @dev Sets `adminRole` as ``role``'s admin role.\n     *\n     * Emits a {RoleAdminChanged} event.\n     */\n    function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {\n        bytes32 previousAdminRole = getRoleAdmin(role);\n        _roles[role].adminRole = adminRole;\n        emit RoleAdminChanged(role, previousAdminRole, adminRole);\n    }\n\n    /**\n     * @dev Attempts to grant `role` to `account` and returns a boolean indicating if `role` was granted.\n     *\n     * Internal function without access restriction.\n     *\n     * May emit a {RoleGranted} event.\n     */\n    function _grantRole(bytes32 role, address account) internal virtual returns (bool) {\n        if (!hasRole(role, account)) {\n            _roles[role].hasRole[account] = true;\n            emit RoleGranted(role, account, _msgSender());\n            return true;\n        } else {\n            return false;\n        }\n    }\n\n    /**\n     * @dev Attempts to revoke `role` from `account` and returns a boolean indicating if `role` was revoked.\n     *\n     * Internal function without access restriction.\n     *\n     * May emit a {RoleRevoked} event.\n     */\n    function _revokeRole(bytes32 role, address account) internal virtual returns (bool) {\n        if (hasRole(role, account)) {\n            _roles[role].hasRole[account] = false;\n            emit RoleRevoked(role, account, _msgSender());\n            return true;\n        } else {\n            return false;\n        }\n    }\n}\n"},{"file_path":"src/finance/YieldSharing.sol","source_code":"// SPDX-License-Identifier: MIT\npragma solidity 0.8.28;\n\nimport {FixedPointMathLib} from \"@solmate/src/utils/FixedPointMathLib.sol\";\n\nimport {CoreRoles} from \"@libraries/CoreRoles.sol\";\nimport {Accounting} from \"@finance/Accounting.sol\";\nimport {StakedToken} from \"@tokens/StakedToken.sol\";\nimport {ReceiptToken} from \"@tokens/ReceiptToken.sol\";\nimport {CoreControlled} from \"@core/CoreControlled.sol\";\nimport {LockingController} from \"@locking/LockingController.sol\";\nimport {FixedPriceOracle} from \"@finance/oracles/FixedPriceOracle.sol\";\n\n/// @notice InfiniFi YieldSharing contract\n/// @dev This contract is used to distribute yield between iUSD locking users and siUSD holders.\n/// @dev It also holds idle iUSD that can be used to slash losses or distribute profits.\ncontract YieldSharing is CoreControlled {\n    using FixedPointMathLib for uint256;\n\n    error PerformanceFeeTooHigh(uint256 _percent);\n    error PerformanceFeeRecipientIsZeroAddress(address _recipient);\n    error TargetIlliquidRatioTooHigh(uint256 _ratio);\n\n    /// @notice Fired when yield is accrued from frarms\n    /// @param timestamp block timestamp of the accrual\n    /// @param yield profit or loss in farms since last accrual\n    event YieldAccrued(uint256 indexed timestamp, int256 yield);\n    event TargetIlliquidRatioUpdated(uint256 indexed timestamp, uint256 multiplier);\n    event SafetyBufferSizeUpdated(uint256 indexed timestamp, uint256 value);\n    event LiquidMultiplierUpdated(uint256 indexed timestamp, uint256 multiplier);\n    event PerformanceFeeSettingsUpdated(uint256 indexed timestamp, uint256 percentage, address recipient);\n\n    uint256 public constant MAX_PERFORMANCE_FEE = 0.2e18; // 20%\n\n    /// @notice reference to farm accounting contract\n    address public immutable accounting;\n\n    /// @notice reference to receipt token\n    address public immutable receiptToken;\n\n    /// @notice reference to staked token\n    address public immutable stakedToken;\n\n    /// @notice reference to locking module\n    address public immutable lockingModule;\n\n    /// @notice safety buffer amount.\n    /// This amount of iUSD is held on the contract and consumed first in case of losses smaller\n    /// than the safety buffer. It is also replenished first in case of profit, up to the buffer size.\n    /// The buffer held could exceed safetyBufferSize if there are donations to this contract, or if\n    /// the buffer size has been reduced since last profit distribution, or if there are no other\n    /// users to distribute to.\n    /// The safety buffer is meant to absorb small losses such as slippage or fees when\n    /// deploying capital to productive farms.\n    /// safety buffer can be emptied by governance through the use of emergencyAction().\n    uint256 public safetyBufferSize;\n\n    /// @notice optional performance fee, expressed as a percentage with 18 decimals.\n    uint256 public performanceFee; // default to 0%\n\n    /// @notice optional performance fee recipient\n    address public performanceFeeRecipient;\n\n    /// @notice multiplier for the liquid return, expressed as a percentage with 18 decimals.\n    uint256 public liquidReturnMultiplier = FixedPointMathLib.WAD; // default to 1.0\n\n    /// @notice target illiquid ratio, expressed as a percentage with 18 decimals.\n    /// This ratio is the minimum percent of illiquid holdings the protocol is targetting, and\n    /// if there is a percentage of illiquid users lower than the targetIlliquidRatio, the protocol\n    /// wil distribute additional rewards to the illiquid users until targetIlliquidRatio is reached.\n    uint256 public targetIlliquidRatio; // default to 0\n\n    struct StakedReceiptTokenCache {\n        uint48 blockTimestamp;\n        uint208 amount;\n    }\n\n    StakedReceiptTokenCache public stakedReceiptTokenCache;\n\n    constructor(address _core, address _accounting, address _receiptToken, address _stakedToken, address _lockingModule)\n        CoreControlled(_core)\n    {\n        accounting = _accounting;\n        receiptToken = _receiptToken;\n        stakedToken = _stakedToken;\n        lockingModule = _lockingModule;\n\n        ReceiptToken(receiptToken).approve(_stakedToken, type(uint256).max);\n        ReceiptToken(receiptToken).approve(_lockingModule, type(uint256).max);\n    }\n\n    /// @notice set the safety buffer size\n    /// @param _safetyBufferSize the new safety buffer size\n    function setSafetyBufferSize(uint256 _safetyBufferSize) external onlyCoreRole(CoreRoles.PROTOCOL_PARAMETERS) {\n        safetyBufferSize = _safetyBufferSize;\n        emit SafetyBufferSizeUpdated(block.timestamp, _safetyBufferSize);\n    }\n\n    /// @notice set the performance fee and recipient\n    function setPerformanceFeeAndRecipient(uint256 _percent, address _recipient)\n        external\n        onlyCoreRole(CoreRoles.PROTOCOL_PARAMETERS)\n    {\n        require(_percent <= MAX_PERFORMANCE_FEE, PerformanceFeeTooHigh(_percent));\n        if (_percent > 0) {\n            require(_recipient != address(0), PerformanceFeeRecipientIsZeroAddress(_recipient));\n        }\n\n        performanceFee = _percent;\n        performanceFeeRecipient = _recipient;\n        emit PerformanceFeeSettingsUpdated(block.timestamp, _percent, _recipient);\n    }\n\n    /// @notice set the liquid return multiplier\n    function setLiquidReturnMultiplier(uint256 _multiplier) external onlyCoreRole(CoreRoles.PROTOCOL_PARAMETERS) {\n        liquidReturnMultiplier = _multiplier;\n        emit LiquidMultiplierUpdated(block.timestamp, _multiplier);\n    }\n\n    /// @notice set the target illiquid ratio\n    function setTargetIlliquidRatio(uint256 _ratio) external onlyCoreRole(CoreRoles.PROTOCOL_PARAMETERS) {\n        require(_ratio <= FixedPointMathLib.WAD, TargetIlliquidRatioTooHigh(_ratio));\n        targetIlliquidRatio = _ratio;\n        emit TargetIlliquidRatioUpdated(block.timestamp, _ratio);\n    }\n\n    /// @notice returns the yield earned by the protocol since the last accrue() call.\n    /// @return yield as an amount of receiptTokens.\n    /// @dev Note that yield can be negative if the protocol farms have lost value, or if the\n    /// oracle price of assets held in the protocol has decreased since last accrue() call,\n    /// or if more ReceiptTokens entered circulation than assets entered the protocol.\n    function unaccruedYield() public view returns (int256) {\n        uint256 receiptTokenPrice = Accounting(accounting).price(receiptToken);\n        uint256 assets = Accounting(accounting).totalAssetsValue(); // returns assets in USD\n\n        uint256 assetsInReceiptTokens = assets.divWadDown(receiptTokenPrice);\n\n        // casting to 'int256' is safe because type(int256).max is a very large amount of receiptTokens\n        // forge-lint: disable-next-line(unsafe-typecast)\n        return int256(assetsInReceiptTokens) - int256(ReceiptToken(receiptToken).totalSupply());\n    }\n\n    /// @notice accrue yield and handle profits & losses\n    /// This function should bring back unaccruedYield() to 0 by minting receiptTokens into circulation (profit distribution)\n    /// or burning receipt tokens (slashing) or updating the oracle price of the receiptToken if there\n    /// are not enough first-loss capital stakers to slash.\n    function accrue() external whenNotPaused {\n        int256 yield = unaccruedYield();\n        // casting to 'uint256' is safe because of 'if'\n        // forge-lint: disable-next-line(unsafe-typecast)\n        if (yield > 0) _handlePositiveYield(uint256(yield));\n        // casting to 'uint256' is safe because of 'else'\n        // forge-lint: disable-next-line(unsafe-typecast)\n        else if (yield < 0) _handleNegativeYield(uint256(-yield));\n\n        emit YieldAccrued(block.timestamp, yield);\n    }\n\n    function getCachedStakedReceiptTokens() public returns (uint256) {\n        StakedReceiptTokenCache memory data = stakedReceiptTokenCache;\n        if (uint256(data.blockTimestamp) == block.timestamp) {\n            return uint256(data.amount);\n        }\n        uint256 amount = ReceiptToken(receiptToken).balanceOf(stakedToken);\n        assert(amount <= type(uint208).max);\n\n        // casting to 'uint48' is safe because type(uint48).max timestamp is very far in the future\n        // forge-lint: disable-next-line(unsafe-typecast)\n        stakedReceiptTokenCache.blockTimestamp = uint48(block.timestamp);\n        // casting to 'uint208' is safe because of the assert above\n        // forge-lint: disable-next-line(unsafe-typecast)\n        stakedReceiptTokenCache.amount = uint208(amount);\n\n        return amount;\n    }\n\n    /// @notice Yield sharing: split between iUSD lockin users & siUSD holders.\n    /// If no users are locking or saving, the profit is minted on this contract and\n    /// held idle so that the accrue() expected behavior of restoring protocol equity to 0\n    /// is maintained. Funds minted on this contract in such a way can be unstuck by governance\n    /// through the use of emergencyAction().\n    function _handlePositiveYield(uint256 _positiveYield) internal {\n        uint256 stakedReceiptTokens = getCachedStakedReceiptTokens().mulWadDown(liquidReturnMultiplier);\n        uint256 receiptTokenTotalSupply = ReceiptToken(receiptToken).totalSupply();\n        uint256 targetIlliquidMinimum = receiptTokenTotalSupply.mulWadDown(targetIlliquidRatio);\n        uint256 lockingReceiptTokens = LockingController(lockingModule).totalBalance();\n        if (lockingReceiptTokens < targetIlliquidMinimum) {\n            lockingReceiptTokens = targetIlliquidMinimum;\n        }\n        uint256 bondingMultiplier = LockingController(lockingModule).rewardMultiplier();\n        lockingReceiptTokens = lockingReceiptTokens.mulWadDown(bondingMultiplier);\n        uint256 totalReceiptTokens = stakedReceiptTokens + lockingReceiptTokens;\n\n        // mint yield\n        ReceiptToken(receiptToken).mint(address(this), _positiveYield);\n\n        // fill safety buffer first\n        uint256 _safetyBufferSize = safetyBufferSize;\n        if (_safetyBufferSize > 0) {\n            uint256 safetyBuffer = ReceiptToken(receiptToken).balanceOf(address(this)) - _positiveYield;\n            if (safetyBuffer < _safetyBufferSize) {\n                if (safetyBuffer + _positiveYield > _safetyBufferSize) {\n                    // there will be a leftover profit after filling the safety buffer, so we\n                    // deduct the safety buffer contribution from the profits and continue\n                    _positiveYield -= _safetyBufferSize - safetyBuffer;\n                } else {\n                    // do not do any further distribution and only replenish the safety buffer\n                    return;\n                }\n            }\n        }\n\n        // performance fee\n        uint256 _performanceFee = performanceFee;\n        if (_performanceFee > 0) {\n            uint256 fee = _positiveYield.mulWadDown(_performanceFee);\n            if (fee > 0) {\n                // forge-lint: disable-next-line(erc20-unchecked-transfer)\n                ReceiptToken(receiptToken).transfer(performanceFeeRecipient, fee);\n                _positiveYield -= fee;\n            }\n        }\n\n        // compute splits\n        if (totalReceiptTokens == 0) {\n            // nobody to distribute to, do nothing and hold the tokens\n            return;\n        }\n\n        // yield split to staked users\n        uint256 stakingProfit = _positiveYield.mulDivDown(stakedReceiptTokens, totalReceiptTokens);\n        if (stakingProfit > 0) {\n            StakedToken(stakedToken).depositRewards(stakingProfit);\n        }\n\n        // yield split to locking users\n        uint256 lockingProfit = _positiveYield - stakingProfit;\n        if (lockingProfit > 0) {\n            LockingController(lockingModule).depositRewards(lockingProfit);\n        }\n    }\n\n    /// @notice Loss propagation: iUSD locking users -> siUSD holders -> iUSD holders\n    function _handleNegativeYield(uint256 _negativeYield) internal {\n        // if there is a safety buffer, and the loss is smaller than the safety buffer,\n        // consume it and do not apply any losses to users.\n        uint256 safetyBuffer = ReceiptToken(receiptToken).balanceOf(address(this));\n        if (safetyBuffer >= _negativeYield) {\n            ReceiptToken(receiptToken).burn(_negativeYield);\n            return;\n        }\n\n        // first, apply losses to locking users\n        uint256 lockingReceiptTokens = LockingController(lockingModule).totalBalance();\n        if (_negativeYield <= lockingReceiptTokens) {\n            LockingController(lockingModule).applyLosses(_negativeYield);\n            return;\n        }\n        LockingController(lockingModule).applyLosses(lockingReceiptTokens);\n        _negativeYield -= lockingReceiptTokens;\n\n        // second, apply negativeYield to siUSD holders\n        uint256 stakedReceiptTokens = ReceiptToken(receiptToken).balanceOf(stakedToken);\n        if (_negativeYield <= stakedReceiptTokens) {\n            StakedToken(stakedToken).applyLosses(_negativeYield);\n            return;\n        }\n        StakedToken(stakedToken).applyLosses(stakedReceiptTokens);\n        _negativeYield -= stakedReceiptTokens;\n\n        // lastly, apply losses to all iUSD in circulation\n        uint256 totalSupply = ReceiptToken(receiptToken).totalSupply();\n        address oracle = Accounting(accounting).oracle(receiptToken);\n        uint256 price = FixedPriceOracle(oracle).price();\n        uint256 newPrice = price.mulDivDown(totalSupply - _negativeYield, totalSupply);\n        FixedPriceOracle(oracle).setPrice(newPrice);\n    }\n}\n"},{"file_path":"lib/solmate/src/utils/FixedPointMathLib.sol","source_code":"// 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"},{"file_path":"lib/openzeppelin-contracts/contracts/utils/math/SignedMath.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/SignedMath.sol)\n\npragma solidity ^0.8.20;\n\nimport {SafeCast} from \"./SafeCast.sol\";\n\n/**\n * @dev Standard signed math utilities missing in the Solidity language.\n */\nlibrary SignedMath {\n    /**\n     * @dev Branchless ternary evaluation for `a ? b : c`. Gas costs are constant.\n     *\n     * IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.\n     * However, the compiler may optimize Solidity ternary operations (i.e. `a ? b : c`) to only compute\n     * one branch when needed, making this function more expensive.\n     */\n    function ternary(bool condition, int256 a, int256 b) internal pure returns (int256) {\n        unchecked {\n            // branchless ternary works because:\n            // b ^ (a ^ b) == a\n            // b ^ 0 == b\n            return b ^ ((a ^ b) * int256(SafeCast.toUint(condition)));\n        }\n    }\n\n    /**\n     * @dev Returns the largest of two signed numbers.\n     */\n    function max(int256 a, int256 b) internal pure returns (int256) {\n        return ternary(a > b, a, b);\n    }\n\n    /**\n     * @dev Returns the smallest of two signed numbers.\n     */\n    function min(int256 a, int256 b) internal pure returns (int256) {\n        return ternary(a < b, a, b);\n    }\n\n    /**\n     * @dev Returns the average of two signed numbers without overflow.\n     * The result is rounded towards zero.\n     */\n    function average(int256 a, int256 b) internal pure returns (int256) {\n        // Formula from the book \"Hacker's Delight\"\n        int256 x = (a & b) + ((a ^ b) >> 1);\n        return x + (int256(uint256(x) >> 255) & (a ^ b));\n    }\n\n    /**\n     * @dev Returns the absolute unsigned value of a signed value.\n     */\n    function abs(int256 n) internal pure returns (uint256) {\n        unchecked {\n            // Formula from the \"Bit Twiddling Hacks\" by Sean Eron Anderson.\n            // Since `n` is a signed integer, the generated bytecode will use the SAR opcode to perform the right shift,\n            // taking advantage of the most significant (or \"sign\" bit) in two's complement representation.\n            // This opcode adds new most significant bits set to the value of the previous most significant bit. As a result,\n            // the mask will either be `bytes32(0)` (if n is positive) or `~bytes32(0)` (if n is negative).\n            int256 mask = n >> 255;\n\n            // A `bytes32(0)` mask leaves the input unchanged, while a `~bytes32(0)` mask complements it.\n            return uint256((n + mask) ^ mask);\n        }\n    }\n}\n"},{"file_path":"lib/openzeppelin-contracts/contracts/utils/Memory.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.5.0) (utils/Memory.sol)\n\npragma solidity ^0.8.24;\n\nimport {Panic} from \"./Panic.sol\";\nimport {Math} from \"./math/Math.sol\";\n\n/**\n * @dev Utilities to manipulate memory.\n *\n * Memory is a contiguous and dynamic byte array in which Solidity stores non-primitive types.\n * This library provides functions to manipulate pointers to this dynamic array and work with slices of it.\n *\n * Slices provide a view into a portion of memory without copying data, enabling efficient substring operations.\n *\n * WARNING: When manipulating memory pointers or slices, make sure to follow the Solidity documentation\n * guidelines for https://docs.soliditylang.org/en/v0.8.20/assembly.html#memory-safety[Memory Safety].\n */\nlibrary Memory {\n    type Pointer is bytes32;\n\n    /// @dev Returns a `Pointer` to the current free `Pointer`.\n    function getFreeMemoryPointer() internal pure returns (Pointer ptr) {\n        assembly (\"memory-safe\") {\n            ptr := mload(0x40)\n        }\n    }\n\n    /**\n     * @dev Sets the free `Pointer` to a specific value.\n     *\n     * WARNING: Everything after the pointer may be overwritten.\n     **/\n    function setFreeMemoryPointer(Pointer ptr) internal pure {\n        assembly (\"memory-safe\") {\n            mstore(0x40, ptr)\n        }\n    }\n\n    /// @dev `Pointer` to `bytes32`. Expects a pointer to a properly ABI-encoded `bytes` object.\n    function asBytes32(Pointer ptr) internal pure returns (bytes32) {\n        return Pointer.unwrap(ptr);\n    }\n\n    /// @dev `bytes32` to `Pointer`. Expects a pointer to a properly ABI-encoded `bytes` object.\n    function asPointer(bytes32 value) internal pure returns (Pointer) {\n        return Pointer.wrap(value);\n    }\n\n    /// @dev Move a pointer forward by a given offset.\n    function forward(Pointer ptr, uint256 offset) internal pure returns (Pointer) {\n        return Pointer.wrap(bytes32(uint256(Pointer.unwrap(ptr)) + offset));\n    }\n\n    /// @dev Equality comparator for memory pointers.\n    function equal(Pointer ptr1, Pointer ptr2) internal pure returns (bool) {\n        return Pointer.unwrap(ptr1) == Pointer.unwrap(ptr2);\n    }\n\n    type Slice is bytes32;\n\n    /// @dev Get a slice representation of a bytes object in memory\n    function asSlice(bytes memory self) internal pure returns (Slice result) {\n        assembly (\"memory-safe\") {\n            result := or(shl(128, mload(self)), add(self, 0x20))\n        }\n    }\n\n    /// @dev Returns the length of a given slice (equiv to self.length for calldata slices)\n    function length(Slice self) internal pure returns (uint256 result) {\n        assembly (\"memory-safe\") {\n            result := shr(128, self)\n        }\n    }\n\n    /// @dev Offset a memory slice (equivalent to self[start:] for calldata slices)\n    function slice(Slice self, uint256 offset) internal pure returns (Slice) {\n        if (offset > length(self)) Panic.panic(Panic.ARRAY_OUT_OF_BOUNDS);\n        return _asSlice(length(self) - offset, forward(_pointer(self), offset));\n    }\n\n    /// @dev Offset and cut a Slice (equivalent to self[start:start+length] for calldata slices)\n    function slice(Slice self, uint256 offset, uint256 len) internal pure returns (Slice) {\n        if (offset + len > length(self)) Panic.panic(Panic.ARRAY_OUT_OF_BOUNDS);\n        return _asSlice(len, forward(_pointer(self), offset));\n    }\n\n    /**\n     * @dev Read a bytes32 buffer from a given Slice at a specific offset\n     *\n     * NOTE: If offset > length(slice) - 0x20, part of the return value will be out of bound of the slice. These bytes are zeroed.\n     */\n    function load(Slice self, uint256 offset) internal pure returns (bytes32 value) {\n        uint256 outOfBoundBytes = Math.saturatingSub(0x20 + offset, length(self));\n        if (outOfBoundBytes > 0x1f) Panic.panic(Panic.ARRAY_OUT_OF_BOUNDS);\n\n        assembly (\"memory-safe\") {\n            value := and(mload(add(and(self, shr(128, not(0))), offset)), shl(mul(8, outOfBoundBytes), not(0)))\n        }\n    }\n\n    /// @dev Extract the data corresponding to a Slice (allocate new memory)\n    function toBytes(Slice self) internal pure returns (bytes memory result) {\n        uint256 len = length(self);\n        Memory.Pointer ptr = _pointer(self);\n        assembly (\"memory-safe\") {\n            result := mload(0x40)\n            mstore(result, len)\n            mcopy(add(result, 0x20), ptr, len)\n            mstore(0x40, add(add(result, len), 0x20))\n        }\n    }\n\n    /// @dev Returns true if the two slices contain the same data.\n    function equal(Slice a, Slice b) internal pure returns (bool result) {\n        Memory.Pointer ptrA = _pointer(a);\n        Memory.Pointer ptrB = _pointer(b);\n        uint256 lenA = length(a);\n        uint256 lenB = length(b);\n        assembly (\"memory-safe\") {\n            result := eq(keccak256(ptrA, lenA), keccak256(ptrB, lenB))\n        }\n    }\n\n    /**\n     * @dev Private helper: create a slice from raw values (length and pointer)\n     *\n     * NOTE: this function MUST NOT be called with `len` or `ptr` that exceed `2**128-1`. This should never be\n     * the case of slices produced by `asSlice(bytes)`, and function that reduce the scope of slices\n     * (`slice(Slice,uint256)` and `slice(Slice,uint256, uint256)`) should not cause this issue if the parent slice is\n     * correct.\n     */\n    function _asSlice(uint256 len, Memory.Pointer ptr) private pure returns (Slice result) {\n        assembly (\"memory-safe\") {\n            result := or(shl(128, len), ptr)\n        }\n    }\n\n    /// @dev Returns the memory location of a given slice (equiv to self.offset for calldata slices)\n    function _pointer(Slice self) private pure returns (Memory.Pointer result) {\n        assembly (\"memory-safe\") {\n            result := and(self, shr(128, not(0)))\n        }\n    }\n}\n"},{"file_path":"lib/openzeppelin-contracts/contracts/utils/Context.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract Context {\n    function _msgSender() internal view virtual returns (address) {\n        return msg.sender;\n    }\n\n    function _msgData() internal view virtual returns (bytes calldata) {\n        return msg.data;\n    }\n\n    function _contextSuffixLength() internal view virtual returns (uint256) {\n        return 0;\n    }\n}\n"},{"file_path":"lib/openzeppelin-contracts/contracts/utils/Bytes.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.5.0) (utils/Bytes.sol)\n\npragma solidity ^0.8.24;\n\nimport {Math} from \"./math/Math.sol\";\n\n/**\n * @dev Bytes operations.\n */\nlibrary Bytes {\n    /**\n     * @dev Forward search for `s` in `buffer`\n     * * If `s` is present in the buffer, returns the index of the first instance\n     * * If `s` is not present in the buffer, returns type(uint256).max\n     *\n     * NOTE: replicates the behavior of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf[Javascript's `Array.indexOf`]\n     */\n    function indexOf(bytes memory buffer, bytes1 s) internal pure returns (uint256) {\n        return indexOf(buffer, s, 0);\n    }\n\n    /**\n     * @dev Forward search for `s` in `buffer` starting at position `pos`\n     * * If `s` is present in the buffer (at or after `pos`), returns the index of the next instance\n     * * If `s` is not present in the buffer (at or after `pos`), returns type(uint256).max\n     *\n     * NOTE: replicates the behavior of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf[Javascript's `Array.indexOf`]\n     */\n    function indexOf(bytes memory buffer, bytes1 s, uint256 pos) internal pure returns (uint256) {\n        uint256 length = buffer.length;\n        for (uint256 i = pos; i < length; ++i) {\n            if (bytes1(_unsafeReadBytesOffset(buffer, i)) == s) {\n                return i;\n            }\n        }\n        return type(uint256).max;\n    }\n\n    /**\n     * @dev Backward search for `s` in `buffer`\n     * * If `s` is present in the buffer, returns the index of the last instance\n     * * If `s` is not present in the buffer, returns type(uint256).max\n     *\n     * NOTE: replicates the behavior of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/lastIndexOf[Javascript's `Array.lastIndexOf`]\n     */\n    function lastIndexOf(bytes memory buffer, bytes1 s) internal pure returns (uint256) {\n        return lastIndexOf(buffer, s, type(uint256).max);\n    }\n\n    /**\n     * @dev Backward search for `s` in `buffer` starting at position `pos`\n     * * If `s` is present in the buffer (at or before `pos`), returns the index of the previous instance\n     * * If `s` is not present in the buffer (at or before `pos`), returns type(uint256).max\n     *\n     * NOTE: replicates the behavior of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/lastIndexOf[Javascript's `Array.lastIndexOf`]\n     */\n    function lastIndexOf(bytes memory buffer, bytes1 s, uint256 pos) internal pure returns (uint256) {\n        unchecked {\n            uint256 length = buffer.length;\n            for (uint256 i = Math.min(Math.saturatingAdd(pos, 1), length); i > 0; --i) {\n                if (bytes1(_unsafeReadBytesOffset(buffer, i - 1)) == s) {\n                    return i - 1;\n                }\n            }\n            return type(uint256).max;\n        }\n    }\n\n    /**\n     * @dev Copies the content of `buffer`, from `start` (included) to the end of `buffer` into a new bytes object in\n     * memory.\n     *\n     * NOTE: replicates the behavior of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice[Javascript's `Array.slice`]\n     */\n    function slice(bytes memory buffer, uint256 start) internal pure returns (bytes memory) {\n        return slice(buffer, start, buffer.length);\n    }\n\n    /**\n     * @dev Copies the content of `buffer`, from `start` (included) to `end` (excluded) into a new bytes object in\n     * memory. The `end` argument is truncated to the length of the `buffer`.\n     *\n     * NOTE: replicates the behavior of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice[Javascript's `Array.slice`]\n     */\n    function slice(bytes memory buffer, uint256 start, uint256 end) internal pure returns (bytes memory) {\n        // sanitize\n        end = Math.min(end, buffer.length);\n        start = Math.min(start, end);\n\n        // allocate and copy\n        bytes memory result = new bytes(end - start);\n        assembly (\"memory-safe\") {\n            mcopy(add(result, 0x20), add(add(buffer, 0x20), start), sub(end, start))\n        }\n\n        return result;\n    }\n\n    /**\n     * @dev Moves the content of `buffer`, from `start` (included) to the end of `buffer` to the start of that buffer.\n     *\n     * NOTE: This function modifies the provided buffer in place. If you need to preserve the original buffer, use {slice} instead\n     * NOTE: replicates the behavior of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice[Javascript's `Array.splice`]\n     */\n    function splice(bytes memory buffer, uint256 start) internal pure returns (bytes memory) {\n        return splice(buffer, start, buffer.length);\n    }\n\n    /**\n     * @dev Moves the content of `buffer`, from `start` (included) to end (excluded) to the start of that buffer. The\n     * `end` argument is truncated to the length of the `buffer`.\n     *\n     * NOTE: This function modifies the provided buffer in place. If you need to preserve the original buffer, use {slice} instead\n     * NOTE: replicates the behavior of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice[Javascript's `Array.splice`]\n     */\n    function splice(bytes memory buffer, uint256 start, uint256 end) internal pure returns (bytes memory) {\n        // sanitize\n        end = Math.min(end, buffer.length);\n        start = Math.min(start, end);\n\n        // allocate and copy\n        assembly (\"memory-safe\") {\n            mcopy(add(buffer, 0x20), add(add(buffer, 0x20), start), sub(end, start))\n            mstore(buffer, sub(end, start))\n        }\n\n        return buffer;\n    }\n\n    /**\n     * @dev Replaces bytes in `buffer` starting at `pos` with all bytes from `replacement`.\n     *\n     * Parameters are clamped to valid ranges (i.e. `pos` is clamped to `[0, buffer.length]`).\n     * If `pos >= buffer.length`, no replacement occurs and the buffer is returned unchanged.\n     *\n     * NOTE: This function modifies the provided buffer in place.\n     */\n    function replace(bytes memory buffer, uint256 pos, bytes memory replacement) internal pure returns (bytes memory) {\n        return replace(buffer, pos, replacement, 0, replacement.length);\n    }\n\n    /**\n     * @dev Replaces bytes in `buffer` starting at `pos` with bytes from `replacement` starting at `offset`.\n     * Copies at most `length` bytes from `replacement` to `buffer`.\n     *\n     * Parameters are clamped to valid ranges (i.e. `pos` is clamped to `[0, buffer.length]`, `offset` is\n     * clamped to `[0, replacement.length]`, and `length` is clamped to `min(length, replacement.length - offset,\n     * buffer.length - pos))`. If `pos >= buffer.length` or `offset >= replacement.length`, no replacement occurs\n     * and the buffer is returned unchanged.\n     *\n     * NOTE: This function modifies the provided buffer in place.\n     */\n    function replace(\n        bytes memory buffer,\n        uint256 pos,\n        bytes memory replacement,\n        uint256 offset,\n        uint256 length\n    ) internal pure returns (bytes memory) {\n        // sanitize\n        pos = Math.min(pos, buffer.length);\n        offset = Math.min(offset, replacement.length);\n        length = Math.min(length, Math.min(replacement.length - offset, buffer.length - pos));\n\n        // allocate and copy\n        assembly (\"memory-safe\") {\n            mcopy(add(add(buffer, 0x20), pos), add(add(replacement, 0x20), offset), length)\n        }\n\n        return buffer;\n    }\n\n    /**\n     * @dev Concatenate an array of bytes into a single bytes object.\n     *\n     * For fixed bytes types, we recommend using the solidity built-in `bytes.concat` or (equivalent)\n     * `abi.encodePacked`.\n     *\n     * NOTE: this could be done in assembly with a single loop that expands starting at the FMP, but that would be\n     * significantly less readable. It might be worth benchmarking the savings of the full-assembly approach.\n     */\n    function concat(bytes[] memory buffers) internal pure returns (bytes memory) {\n        uint256 length = 0;\n        for (uint256 i = 0; i < buffers.length; ++i) {\n            length += buffers[i].length;\n        }\n\n        bytes memory result = new bytes(length);\n\n        uint256 offset = 0x20;\n        for (uint256 i = 0; i < buffers.length; ++i) {\n            bytes memory input = buffers[i];\n            assembly (\"memory-safe\") {\n                mcopy(add(result, offset), add(input, 0x20), mload(input))\n            }\n            unchecked {\n                offset += input.length;\n            }\n        }\n\n        return result;\n    }\n\n    /**\n     * @dev Split each byte in `input` into two nibbles (4 bits each)\n     *\n     * Example: hex\"01234567\" → hex\"0001020304050607\"\n     */\n    function toNibbles(bytes memory input) internal pure returns (bytes memory output) {\n        assembly (\"memory-safe\") {\n            let length := mload(input)\n            output := mload(0x40)\n            mstore(0x40, add(add(output, 0x20), mul(length, 2)))\n            mstore(output, mul(length, 2))\n            for {\n                let i := 0\n            } lt(i, length) {\n                i := add(i, 0x10)\n            } {\n                let chunk := shr(128, mload(add(add(input, 0x20), i)))\n                chunk := and(\n                    0x0000000000000000ffffffffffffffff0000000000000000ffffffffffffffff,\n                    or(shl(64, chunk), chunk)\n                )\n                chunk := and(\n                    0x00000000ffffffff00000000ffffffff00000000ffffffff00000000ffffffff,\n                    or(shl(32, chunk), chunk)\n                )\n                chunk := and(\n                    0x0000ffff0000ffff0000ffff0000ffff0000ffff0000ffff0000ffff0000ffff,\n                    or(shl(16, chunk), chunk)\n                )\n                chunk := and(\n                    0x00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff,\n                    or(shl(8, chunk), chunk)\n                )\n                chunk := and(\n                    0x0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f,\n                    or(shl(4, chunk), chunk)\n                )\n                mstore(add(add(output, 0x20), mul(i, 2)), chunk)\n            }\n        }\n    }\n\n    /**\n     * @dev Returns true if the two byte buffers are equal.\n     */\n    function equal(bytes memory a, bytes memory b) internal pure returns (bool) {\n        return a.length == b.length && keccak256(a) == keccak256(b);\n    }\n\n    /**\n     * @dev Reverses the byte order of a bytes32 value, converting between little-endian and big-endian.\n     * Inspired by https://graphics.stanford.edu/~seander/bithacks.html#ReverseParallel[Reverse Parallel]\n     */\n    function reverseBytes32(bytes32 value) internal pure returns (bytes32) {\n        value = // swap bytes\n            ((value >> 8) & 0x00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF) |\n            ((value & 0x00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF) << 8);\n        value = // swap 2-byte long pairs\n            ((value >> 16) & 0x0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF) |\n            ((value & 0x0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF) << 16);\n        value = // swap 4-byte long pairs\n            ((value >> 32) & 0x00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF) |\n            ((value & 0x00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF) << 32);\n        value = // swap 8-byte long pairs\n            ((value >> 64) & 0x0000000000000000FFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF) |\n            ((value & 0x0000000000000000FFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF) << 64);\n        return (value >> 128) | (value << 128); // swap 16-byte long pairs\n    }\n\n    /// @dev Same as {reverseBytes32} but optimized for 128-bit values.\n    function reverseBytes16(bytes16 value) internal pure returns (bytes16) {\n        value = // swap bytes\n            ((value & 0xFF00FF00FF00FF00FF00FF00FF00FF00) >> 8) |\n            ((value & 0x00FF00FF00FF00FF00FF00FF00FF00FF) << 8);\n        value = // swap 2-byte long pairs\n            ((value & 0xFFFF0000FFFF0000FFFF0000FFFF0000) >> 16) |\n            ((value & 0x0000FFFF0000FFFF0000FFFF0000FFFF) << 16);\n        value = // swap 4-byte long pairs\n            ((value & 0xFFFFFFFF00000000FFFFFFFF00000000) >> 32) |\n            ((value & 0x00000000FFFFFFFF00000000FFFFFFFF) << 32);\n        return (value >> 64) | (value << 64); // swap 8-byte long pairs\n    }\n\n    /// @dev Same as {reverseBytes32} but optimized for 64-bit values.\n    function reverseBytes8(bytes8 value) internal pure returns (bytes8) {\n        value = ((value & 0xFF00FF00FF00FF00) >> 8) | ((value & 0x00FF00FF00FF00FF) << 8); // swap bytes\n        value = ((value & 0xFFFF0000FFFF0000) >> 16) | ((value & 0x0000FFFF0000FFFF) << 16); // swap 2-byte long pairs\n        return (value >> 32) | (value << 32); // swap 4-byte long pairs\n    }\n\n    /// @dev Same as {reverseBytes32} but optimized for 32-bit values.\n    function reverseBytes4(bytes4 value) internal pure returns (bytes4) {\n        value = ((value & 0xFF00FF00) >> 8) | ((value & 0x00FF00FF) << 8); // swap bytes\n        return (value >> 16) | (value << 16); // swap 2-byte long pairs\n    }\n\n    /// @dev Same as {reverseBytes32} but optimized for 16-bit values.\n    function reverseBytes2(bytes2 value) internal pure returns (bytes2) {\n        return (value >> 8) | (value << 8);\n    }\n\n    /**\n     * @dev Counts the number of leading zero bits a bytes array. Returns `8 * buffer.length`\n     * if the buffer is all zeros.\n     */\n    function clz(bytes memory buffer) internal pure returns (uint256) {\n        for (uint256 i = 0; i < buffer.length; i += 0x20) {\n            bytes32 chunk = _unsafeReadBytesOffset(buffer, i);\n            if (chunk != bytes32(0)) {\n                return Math.min(8 * i + Math.clz(uint256(chunk)), 8 * buffer.length);\n            }\n        }\n        return 8 * buffer.length;\n    }\n\n    /**\n     * @dev Reads a bytes32 from a bytes array without bounds checking.\n     *\n     * NOTE: making this function internal would mean it could be used with memory unsafe offset, and marking the\n     * assembly block as such would prevent some optimizations.\n     */\n    function _unsafeReadBytesOffset(bytes memory buffer, uint256 offset) private pure returns (bytes32 value) {\n        // This is not memory safe in the general case, but all calls to this private function are within bounds.\n        assembly (\"memory-safe\") {\n            value := mload(add(add(buffer, 0x20), offset))\n        }\n    }\n}\n"},{"file_path":"lib/openzeppelin-contracts/contracts/utils/Comparators.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (utils/Comparators.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Provides a set of functions to compare values.\n *\n * _Available since v5.1._\n */\nlibrary Comparators {\n    function lt(uint256 a, uint256 b) internal pure returns (bool) {\n        return a < b;\n    }\n\n    function gt(uint256 a, uint256 b) internal pure returns (bool) {\n        return a > b;\n    }\n}\n"},{"file_path":"src/core/InfiniFiCore.sol","source_code":"// SPDX-License-Identifier: MIT\npragma solidity 0.8.28;\n\nimport {CoreRoles} from \"@libraries/CoreRoles.sol\";\nimport {AccessControlEnumerable} from \"@openzeppelin/contracts/access/extensions/AccessControlEnumerable.sol\";\n\n/// @notice Maintains roles and access control\ncontract InfiniFiCore is AccessControlEnumerable {\n    error RoleAlreadyExists(bytes32 role);\n    error RoleDoesNotExist(bytes32 role);\n    error LengthMismatch(uint256 expected, uint256 actual);\n\n    /// @notice construct Core\n    constructor() {\n        // For initial setup before going live, deployer can then call\n        // renounceRole(bytes32 role, address account)\n        _grantRole(CoreRoles.GOVERNOR, msg.sender);\n\n        // Initial roles setup: direct hierarchy, everything under governor\n        _setRoleAdmin(CoreRoles.GOVERNOR, CoreRoles.GOVERNOR);\n        _setRoleAdmin(CoreRoles.PAUSE, CoreRoles.GOVERNOR);\n        _setRoleAdmin(CoreRoles.UNPAUSE, CoreRoles.GOVERNOR);\n        _setRoleAdmin(CoreRoles.PROTOCOL_PARAMETERS, CoreRoles.GOVERNOR);\n        _setRoleAdmin(CoreRoles.MINOR_ROLES_MANAGER, CoreRoles.GOVERNOR);\n        _setRoleAdmin(CoreRoles.ENTRY_POINT, CoreRoles.GOVERNOR);\n        _setRoleAdmin(CoreRoles.RECEIPT_TOKEN_MINTER, CoreRoles.GOVERNOR);\n        _setRoleAdmin(CoreRoles.RECEIPT_TOKEN_BURNER, CoreRoles.GOVERNOR);\n        _setRoleAdmin(CoreRoles.GOVERNANCE_TOKEN_MINTER, CoreRoles.GOVERNOR);\n        _setRoleAdmin(CoreRoles.GOVERNANCE_TOKEN_BURNER, CoreRoles.GOVERNOR);\n        _setRoleAdmin(CoreRoles.LOCKED_TOKEN_MANAGER, CoreRoles.GOVERNOR);\n        _setRoleAdmin(CoreRoles.TRANSFER_RESTRICTOR, CoreRoles.GOVERNOR);\n        _setRoleAdmin(CoreRoles.FARM_MANAGER, CoreRoles.GOVERNOR);\n        _setRoleAdmin(CoreRoles.MANUAL_REBALANCER, CoreRoles.GOVERNOR);\n        _setRoleAdmin(CoreRoles.PERIODIC_REBALANCER, CoreRoles.GOVERNOR);\n        _setRoleAdmin(CoreRoles.EMERGENCY_WITHDRAWAL, CoreRoles.GOVERNOR);\n        _setRoleAdmin(CoreRoles.FARM_SWAP_CALLER, CoreRoles.GOVERNOR);\n        _setRoleAdmin(CoreRoles.ORACLE_MANAGER, CoreRoles.GOVERNOR);\n        _setRoleAdmin(CoreRoles.FINANCE_MANAGER, CoreRoles.GOVERNOR);\n        _setRoleAdmin(CoreRoles.PROPOSER_ROLE, CoreRoles.GOVERNOR);\n        _setRoleAdmin(CoreRoles.EXECUTOR_ROLE, CoreRoles.GOVERNOR);\n        _setRoleAdmin(CoreRoles.CANCELLER_ROLE, CoreRoles.GOVERNOR);\n        _setRoleAdmin(CoreRoles.OUTLAND_PORTAL, CoreRoles.GOVERNOR);\n        _setRoleAdmin(CoreRoles.OUTLAND_KEEPER, CoreRoles.GOVERNOR);\n        _setRoleAdmin(CoreRoles.ACCRUE_YIELD, CoreRoles.GOVERNOR);\n    }\n\n    /// @notice creates a new role to be maintained\n    /// @param role the new role id\n    /// @param adminRole the admin role id for `role`\n    function createRole(bytes32 role, bytes32 adminRole) external onlyRole(CoreRoles.GOVERNOR) {\n        require(getRoleAdmin(role) == bytes32(0), RoleAlreadyExists(role));\n        _setRoleAdmin(role, adminRole);\n    }\n\n    /// @notice override admin role of an existing role\n    /// @param role the role id\n    /// @param adminRole the admin role id\n    function setRoleAdmin(bytes32 role, bytes32 adminRole) external onlyRole(CoreRoles.GOVERNOR) {\n        require(getRoleAdmin(role) != bytes32(0), RoleDoesNotExist(role));\n        _setRoleAdmin(role, adminRole);\n    }\n\n    /// @notice batch granting of roles to various addresses\n    /// @dev if msg.sender does not have admin role needed to grant any of the\n    /// granted roles, the whole transaction reverts.\n    function grantRoles(bytes32[] calldata roles, address[] calldata accounts) external {\n        require(roles.length == accounts.length, LengthMismatch(roles.length, accounts.length));\n        for (uint256 i = 0; i < roles.length; i++) {\n            _checkRole(getRoleAdmin(roles[i]));\n            _grantRole(roles[i], accounts[i]);\n        }\n    }\n}\n"},{"file_path":"lib/openzeppelin-contracts/contracts/interfaces/IERC5267.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC5267.sol)\n\npragma solidity >=0.4.16;\n\ninterface IERC5267 {\n    /**\n     * @dev MAY be emitted to signal that the domain could have changed.\n     */\n    event EIP712DomainChanged();\n\n    /**\n     * @dev returns the fields and values that describe the domain separator used by this contract for EIP-712\n     * signature.\n     */\n    function eip712Domain()\n        external\n        view\n        returns (\n            bytes1 fields,\n            string memory name,\n            string memory version,\n            uint256 chainId,\n            address verifyingContract,\n            bytes32 salt,\n            uint256[] memory extensions\n        );\n}\n"},{"file_path":"src/tokens/StakedToken.sol","source_code":"// SPDX-License-Identifier: MIT\npragma solidity 0.8.28;\n\nimport {EpochLib} from \"@libraries/EpochLib.sol\";\nimport {CoreRoles} from \"@libraries/CoreRoles.sol\";\nimport {ReceiptToken} from \"@tokens/ReceiptToken.sol\";\nimport {YieldSharing} from \"@finance/YieldSharing.sol\";\nimport {CoreControlled} from \"@core/CoreControlled.sol\";\nimport {ERC20, IERC20, ERC4626} from \"@openzeppelin/contracts/token/ERC20/extensions/ERC4626.sol\";\n\n/// @notice InfiniFi Staked Token.\n/// @dev be carefull, as this contract is an ERC4626, the \"assets\" keyword is used to refer to the underlying token\n/// in this case, it's the ReceiptToken. It's a bit confusing because \"asset\" is the word we use to refer to the backing token (USDC)\n/// everywhere else in the code\ncontract StakedToken is ERC4626, CoreControlled {\n    using EpochLib for uint256;\n\n    /// @notice error thrown when there are pending losses unapplied\n    /// if you observe this error as a user, call YieldSharing.accrue() before\n    /// attempting a withdrawal from the vault.\n    error PendingLossesUnapplied();\n\n    /// @notice emitted when a loss is applied to the vault\n    /// @dev epoch could be 0 if the principal of the vault has to be slashed\n    event VaultLoss(uint256 indexed timestamp, uint256 epoch, uint256 assets);\n    /// @notice emitted when a profit is applied to the vault\n    event VaultProfit(uint256 indexed timestamp, uint256 epoch, uint256 assets);\n\n    /// @notice reference to the YieldSharing contract\n    address public yieldSharing;\n\n    /// @notice rewards to distribute per epoch\n    /// @dev epochRewards can only contain future rewards in the next epoch,\n    /// and not further in the future - see `depositRewards()`.\n    mapping(uint256 epoch => uint256 rewards) public epochRewards;\n\n    constructor(address _core, address _receiptToken)\n        CoreControlled(_core)\n        ERC20(string.concat(\"Staked \", ERC20(_receiptToken).name()), string.concat(\"s\", ERC20(_receiptToken).symbol()))\n        ERC4626(IERC20(_receiptToken))\n    {}\n\n    /// @notice allows governor to update the yieldSharing reference\n    function setYieldSharing(address _yieldSharing) external onlyCoreRole(CoreRoles.GOVERNOR) {\n        yieldSharing = _yieldSharing;\n    }\n\n    /// ---------------------------------------------------------------------------\n    /// Overrides\n    /// ---------------------------------------------------------------------------\n\n    function maxMint(address _receiver) public view override returns (uint256) {\n        if (paused()) {\n            return 0;\n        }\n        return super.maxMint(_receiver);\n    }\n\n    function maxDeposit(address _receiver) public view override returns (uint256) {\n        if (paused()) {\n            return 0;\n        }\n        return super.maxDeposit(_receiver);\n    }\n\n    function maxRedeem(address _receiver) public view override returns (uint256) {\n        if (paused() || YieldSharing(yieldSharing).unaccruedYield() < 0) {\n            return 0;\n        }\n        return super.maxRedeem(_receiver);\n    }\n\n    function maxWithdraw(address _receiver) public view override returns (uint256) {\n        if (paused() || YieldSharing(yieldSharing).unaccruedYield() < 0) {\n            return 0;\n        }\n        return super.maxWithdraw(_receiver);\n    }\n\n    // override vault deposits & withdrawals to hook into yieldSharing, so\n    // that yieldSharing can cache the number of receiptTokens staked in StakedToken\n    // and avoid intra-block manipulations during yield distribution.\n    function _deposit(address caller, address receiver, uint256 assets, uint256 shares) internal override {\n        YieldSharing(yieldSharing).getCachedStakedReceiptTokens();\n        super._deposit(caller, receiver, assets, shares);\n    }\n\n    function _withdraw(address caller, address receiver, address owner, uint256 assets, uint256 shares)\n        internal\n        override\n    {\n        YieldSharing(yieldSharing).getCachedStakedReceiptTokens();\n        super._withdraw(caller, receiver, owner, assets, shares);\n    }\n\n    /// ---------------------------------------------------------------------------\n    /// Loss Management\n    /// ---------------------------------------------------------------------------\n\n    /// @notice Slash losses in future epoch rewards, current epoch rewards, and principal.\n    /// @dev note that this function might behave slightly differently than expected, for the sake\n    /// of simplicity in the slashing logic.\n    /// Take the following example:\n    /// - 1500 assets in \"vault principal\"\n    /// - 300 in current epoch rewards (150 already available, 150 still vesting)\n    /// - 50 in next epoch rewards\n    /// -> totalAssets() = 1650.\n    /// If a loss of 250 occurs, you might expect the slashing to remove :\n    /// - 50 tokens in next epoch rewards (200 loss still remaining)\n    /// - 150 tokens in current epoch vesting rewards (50 loss still remaining)\n    /// - 50 tokens in principal (0 loss remaining)\n    /// -> resulting in a totalAssets() of 1500 - 50 (principal slash)\n    ///    + 150 (vested current epoch rewards) = 1600.\n    ///    and no remaining rewards towards the end of the epoch.\n    /// However, the actual behavior will be:\n    /// - 50 tokens in next epoch rewards (200 loss still remaining)\n    /// - 200 tokens in current epoch vesting rewards (0 loss remaining)\n    ///   current epoch rewards updated to 300 - 200 = 100\n    /// -> resulting in a totalAssets() of 1500 + 50 (vested current epoch rewards) = 1550.\n    ///    and a remaining rewards interpolation of 50 until the end of the epoch, resulting\n    ///    in a totalAssets() at the end of the epoch of 1600.\n    /// This is a slight inconsistency between how losses are applied and how rewards are\n    /// interpolated/reported in totalAssets(). Operationally, the interpolating rewards should be\n    /// small compared to the vault's TVL, and slashing events should be rare, so this simplified\n    /// logic is acceptable.\n    function applyLosses(uint256 _amount) external onlyCoreRole(CoreRoles.FINANCE_MANAGER) {\n        // any future rewards are slashed first\n        // first, slash next epoch rewards\n        _amount = _slashEpochRewards(block.timestamp.nextEpoch(), _amount);\n        if (_amount == 0) return;\n        // second, slash current epoch rewards\n        _amount = _slashEpochRewards(block.timestamp.epoch(), _amount);\n        if (_amount == 0) return;\n        // lastly, slash the principal of the vault\n        ReceiptToken(asset()).burn(_amount);\n        emit VaultLoss(block.timestamp, 0, _amount);\n    }\n\n    /// @notice Slash rewards for a given epoch\n    function _slashEpochRewards(uint256 _epoch, uint256 _amount) internal returns (uint256) {\n        uint256 _epochRewards = epochRewards[_epoch];\n        if (_epochRewards >= _amount) {\n            epochRewards[_epoch] = _epochRewards - _amount;\n            ReceiptToken(asset()).burn(_amount);\n            emit VaultLoss(block.timestamp, _epoch, _amount);\n            _amount = 0;\n        } else {\n            epochRewards[_epoch] = 0;\n            ReceiptToken(asset()).burn(_epochRewards);\n            emit VaultLoss(block.timestamp, _epoch, _epochRewards);\n            _amount -= _epochRewards;\n        }\n        return _amount;\n    }\n\n    /// ---------------------------------------------------------------------------\n    /// Profit Smoothing\n    /// ---------------------------------------------------------------------------\n\n    function depositRewards(uint256 _amount) external onlyCoreRole(CoreRoles.FINANCE_MANAGER) {\n        // forge-lint: disable-next-line(erc20-unchecked-transfer)\n        ERC20(asset()).transferFrom(msg.sender, address(this), _amount);\n        uint256 epoch = block.timestamp.nextEpoch();\n        epochRewards[epoch] += _amount;\n        emit VaultProfit(block.timestamp, epoch, _amount);\n    }\n\n    /// @notice returns the amount of rewards for the current epoch minus the rewards that are already available\n    function _unavailableCurrentEpochRewards() internal view returns (uint256) {\n        uint256 currentEpoch = block.timestamp.epoch();\n        uint256 currentEpochRewards = epochRewards[currentEpoch]; // safe upcast\n        uint256 elapsed = block.timestamp - currentEpoch.epochToTimestamp();\n        uint256 availableEpochRewards = (currentEpochRewards * elapsed) / EpochLib.EPOCH;\n        return currentEpochRewards - availableEpochRewards;\n    }\n\n    /// @notice returns the total assets, excluding the rewards that are not available yet\n    function totalAssets() public view override returns (uint256) {\n        return super.totalAssets() - epochRewards[block.timestamp.nextEpoch()] - _unavailableCurrentEpochRewards();\n    }\n}\n"},{"file_path":"src/finance/oracles/FixedPriceOracle.sol","source_code":"// SPDX-License-Identifier: MIT\npragma solidity 0.8.28;\n\nimport {IOracle} from \"@interfaces/IOracle.sol\";\nimport {CoreControlled, CoreRoles} from \"@core/CoreControlled.sol\";\n\ncontract FixedPriceOracle is IOracle, CoreControlled {\n    uint256 public price;\n\n    event PriceSet(uint256 indexed timestamp, uint256 price);\n\n    constructor(address _core, uint256 _price) CoreControlled(_core) {\n        price = _price;\n    }\n\n    function setPrice(uint256 _price) external onlyCoreRole(CoreRoles.ORACLE_MANAGER) {\n        price = _price;\n        emit PriceSet(block.timestamp, _price);\n    }\n}\n"},{"file_path":"lib/openzeppelin-contracts/contracts/utils/math/SafeCast.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/SafeCast.sol)\n// This file was procedurally generated from scripts/generate/templates/SafeCast.js.\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Wrappers over Solidity's uintXX/intXX/bool casting operators with added overflow\n * checks.\n *\n * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can\n * easily result in undesired exploitation or bugs, since developers usually\n * assume that overflows raise errors. `SafeCast` restores this intuition by\n * reverting the transaction when such an operation overflows.\n *\n * Using this library instead of the unchecked operations eliminates an entire\n * class of bugs, so it's recommended to use it always.\n */\nlibrary SafeCast {\n    /**\n     * @dev Value doesn't fit in a uint of `bits` size.\n     */\n    error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value);\n\n    /**\n     * @dev An int value doesn't fit in a uint of `bits` size.\n     */\n    error SafeCastOverflowedIntToUint(int256 value);\n\n    /**\n     * @dev Value doesn't fit in an int of `bits` size.\n     */\n    error SafeCastOverflowedIntDowncast(uint8 bits, int256 value);\n\n    /**\n     * @dev A uint value doesn't fit in an int of `bits` size.\n     */\n    error SafeCastOverflowedUintToInt(uint256 value);\n\n    /**\n     * @dev Returns the downcasted uint248 from uint256, reverting on\n     * overflow (when the input is greater than largest uint248).\n     *\n     * Counterpart to Solidity's `uint248` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 248 bits\n     */\n    function toUint248(uint256 value) internal pure returns (uint248) {\n        if (value > type(uint248).max) {\n            revert SafeCastOverflowedUintDowncast(248, value);\n        }\n        return uint248(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint240 from uint256, reverting on\n     * overflow (when the input is greater than largest uint240).\n     *\n     * Counterpart to Solidity's `uint240` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 240 bits\n     */\n    function toUint240(uint256 value) internal pure returns (uint240) {\n        if (value > type(uint240).max) {\n            revert SafeCastOverflowedUintDowncast(240, value);\n        }\n        return uint240(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint232 from uint256, reverting on\n     * overflow (when the input is greater than largest uint232).\n     *\n     * Counterpart to Solidity's `uint232` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 232 bits\n     */\n    function toUint232(uint256 value) internal pure returns (uint232) {\n        if (value > type(uint232).max) {\n            revert SafeCastOverflowedUintDowncast(232, value);\n        }\n        return uint232(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint224 from uint256, reverting on\n     * overflow (when the input is greater than largest uint224).\n     *\n     * Counterpart to Solidity's `uint224` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 224 bits\n     */\n    function toUint224(uint256 value) internal pure returns (uint224) {\n        if (value > type(uint224).max) {\n            revert SafeCastOverflowedUintDowncast(224, value);\n        }\n        return uint224(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint216 from uint256, reverting on\n     * overflow (when the input is greater than largest uint216).\n     *\n     * Counterpart to Solidity's `uint216` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 216 bits\n     */\n    function toUint216(uint256 value) internal pure returns (uint216) {\n        if (value > type(uint216).max) {\n            revert SafeCastOverflowedUintDowncast(216, value);\n        }\n        return uint216(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint208 from uint256, reverting on\n     * overflow (when the input is greater than largest uint208).\n     *\n     * Counterpart to Solidity's `uint208` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 208 bits\n     */\n    function toUint208(uint256 value) internal pure returns (uint208) {\n        if (value > type(uint208).max) {\n            revert SafeCastOverflowedUintDowncast(208, value);\n        }\n        return uint208(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint200 from uint256, reverting on\n     * overflow (when the input is greater than largest uint200).\n     *\n     * Counterpart to Solidity's `uint200` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 200 bits\n     */\n    function toUint200(uint256 value) internal pure returns (uint200) {\n        if (value > type(uint200).max) {\n            revert SafeCastOverflowedUintDowncast(200, value);\n        }\n        return uint200(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint192 from uint256, reverting on\n     * overflow (when the input is greater than largest uint192).\n     *\n     * Counterpart to Solidity's `uint192` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 192 bits\n     */\n    function toUint192(uint256 value) internal pure returns (uint192) {\n        if (value > type(uint192).max) {\n            revert SafeCastOverflowedUintDowncast(192, value);\n        }\n        return uint192(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint184 from uint256, reverting on\n     * overflow (when the input is greater than largest uint184).\n     *\n     * Counterpart to Solidity's `uint184` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 184 bits\n     */\n    function toUint184(uint256 value) internal pure returns (uint184) {\n        if (value > type(uint184).max) {\n            revert SafeCastOverflowedUintDowncast(184, value);\n        }\n        return uint184(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint176 from uint256, reverting on\n     * overflow (when the input is greater than largest uint176).\n     *\n     * Counterpart to Solidity's `uint176` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 176 bits\n     */\n    function toUint176(uint256 value) internal pure returns (uint176) {\n        if (value > type(uint176).max) {\n            revert SafeCastOverflowedUintDowncast(176, value);\n        }\n        return uint176(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint168 from uint256, reverting on\n     * overflow (when the input is greater than largest uint168).\n     *\n     * Counterpart to Solidity's `uint168` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 168 bits\n     */\n    function toUint168(uint256 value) internal pure returns (uint168) {\n        if (value > type(uint168).max) {\n            revert SafeCastOverflowedUintDowncast(168, value);\n        }\n        return uint168(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint160 from uint256, reverting on\n     * overflow (when the input is greater than largest uint160).\n     *\n     * Counterpart to Solidity's `uint160` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 160 bits\n     */\n    function toUint160(uint256 value) internal pure returns (uint160) {\n        if (value > type(uint160).max) {\n            revert SafeCastOverflowedUintDowncast(160, value);\n        }\n        return uint160(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint152 from uint256, reverting on\n     * overflow (when the input is greater than largest uint152).\n     *\n     * Counterpart to Solidity's `uint152` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 152 bits\n     */\n    function toUint152(uint256 value) internal pure returns (uint152) {\n        if (value > type(uint152).max) {\n            revert SafeCastOverflowedUintDowncast(152, value);\n        }\n        return uint152(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint144 from uint256, reverting on\n     * overflow (when the input is greater than largest uint144).\n     *\n     * Counterpart to Solidity's `uint144` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 144 bits\n     */\n    function toUint144(uint256 value) internal pure returns (uint144) {\n        if (value > type(uint144).max) {\n            revert SafeCastOverflowedUintDowncast(144, value);\n        }\n        return uint144(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint136 from uint256, reverting on\n     * overflow (when the input is greater than largest uint136).\n     *\n     * Counterpart to Solidity's `uint136` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 136 bits\n     */\n    function toUint136(uint256 value) internal pure returns (uint136) {\n        if (value > type(uint136).max) {\n            revert SafeCastOverflowedUintDowncast(136, value);\n        }\n        return uint136(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint128 from uint256, reverting on\n     * overflow (when the input is greater than largest uint128).\n     *\n     * Counterpart to Solidity's `uint128` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 128 bits\n     */\n    function toUint128(uint256 value) internal pure returns (uint128) {\n        if (value > type(uint128).max) {\n            revert SafeCastOverflowedUintDowncast(128, value);\n        }\n        return uint128(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint120 from uint256, reverting on\n     * overflow (when the input is greater than largest uint120).\n     *\n     * Counterpart to Solidity's `uint120` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 120 bits\n     */\n    function toUint120(uint256 value) internal pure returns (uint120) {\n        if (value > type(uint120).max) {\n            revert SafeCastOverflowedUintDowncast(120, value);\n        }\n        return uint120(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint112 from uint256, reverting on\n     * overflow (when the input is greater than largest uint112).\n     *\n     * Counterpart to Solidity's `uint112` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 112 bits\n     */\n    function toUint112(uint256 value) internal pure returns (uint112) {\n        if (value > type(uint112).max) {\n            revert SafeCastOverflowedUintDowncast(112, value);\n        }\n        return uint112(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint104 from uint256, reverting on\n     * overflow (when the input is greater than largest uint104).\n     *\n     * Counterpart to Solidity's `uint104` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 104 bits\n     */\n    function toUint104(uint256 value) internal pure returns (uint104) {\n        if (value > type(uint104).max) {\n            revert SafeCastOverflowedUintDowncast(104, value);\n        }\n        return uint104(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint96 from uint256, reverting on\n     * overflow (when the input is greater than largest uint96).\n     *\n     * Counterpart to Solidity's `uint96` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 96 bits\n     */\n    function toUint96(uint256 value) internal pure returns (uint96) {\n        if (value > type(uint96).max) {\n            revert SafeCastOverflowedUintDowncast(96, value);\n        }\n        return uint96(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint88 from uint256, reverting on\n     * overflow (when the input is greater than largest uint88).\n     *\n     * Counterpart to Solidity's `uint88` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 88 bits\n     */\n    function toUint88(uint256 value) internal pure returns (uint88) {\n        if (value > type(uint88).max) {\n            revert SafeCastOverflowedUintDowncast(88, value);\n        }\n        return uint88(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint80 from uint256, reverting on\n     * overflow (when the input is greater than largest uint80).\n     *\n     * Counterpart to Solidity's `uint80` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 80 bits\n     */\n    function toUint80(uint256 value) internal pure returns (uint80) {\n        if (value > type(uint80).max) {\n            revert SafeCastOverflowedUintDowncast(80, value);\n        }\n        return uint80(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint72 from uint256, reverting on\n     * overflow (when the input is greater than largest uint72).\n     *\n     * Counterpart to Solidity's `uint72` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 72 bits\n     */\n    function toUint72(uint256 value) internal pure returns (uint72) {\n        if (value > type(uint72).max) {\n            revert SafeCastOverflowedUintDowncast(72, value);\n        }\n        return uint72(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint64 from uint256, reverting on\n     * overflow (when the input is greater than largest uint64).\n     *\n     * Counterpart to Solidity's `uint64` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 64 bits\n     */\n    function toUint64(uint256 value) internal pure returns (uint64) {\n        if (value > type(uint64).max) {\n            revert SafeCastOverflowedUintDowncast(64, value);\n        }\n        return uint64(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint56 from uint256, reverting on\n     * overflow (when the input is greater than largest uint56).\n     *\n     * Counterpart to Solidity's `uint56` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 56 bits\n     */\n    function toUint56(uint256 value) internal pure returns (uint56) {\n        if (value > type(uint56).max) {\n            revert SafeCastOverflowedUintDowncast(56, value);\n        }\n        return uint56(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint48 from uint256, reverting on\n     * overflow (when the input is greater than largest uint48).\n     *\n     * Counterpart to Solidity's `uint48` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 48 bits\n     */\n    function toUint48(uint256 value) internal pure returns (uint48) {\n        if (value > type(uint48).max) {\n            revert SafeCastOverflowedUintDowncast(48, value);\n        }\n        return uint48(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint40 from uint256, reverting on\n     * overflow (when the input is greater than largest uint40).\n     *\n     * Counterpart to Solidity's `uint40` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 40 bits\n     */\n    function toUint40(uint256 value) internal pure returns (uint40) {\n        if (value > type(uint40).max) {\n            revert SafeCastOverflowedUintDowncast(40, value);\n        }\n        return uint40(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint32 from uint256, reverting on\n     * overflow (when the input is greater than largest uint32).\n     *\n     * Counterpart to Solidity's `uint32` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 32 bits\n     */\n    function toUint32(uint256 value) internal pure returns (uint32) {\n        if (value > type(uint32).max) {\n            revert SafeCastOverflowedUintDowncast(32, value);\n        }\n        return uint32(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint24 from uint256, reverting on\n     * overflow (when the input is greater than largest uint24).\n     *\n     * Counterpart to Solidity's `uint24` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 24 bits\n     */\n    function toUint24(uint256 value) internal pure returns (uint24) {\n        if (value > type(uint24).max) {\n            revert SafeCastOverflowedUintDowncast(24, value);\n        }\n        return uint24(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint16 from uint256, reverting on\n     * overflow (when the input is greater than largest uint16).\n     *\n     * Counterpart to Solidity's `uint16` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 16 bits\n     */\n    function toUint16(uint256 value) internal pure returns (uint16) {\n        if (value > type(uint16).max) {\n            revert SafeCastOverflowedUintDowncast(16, value);\n        }\n        return uint16(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint8 from uint256, reverting on\n     * overflow (when the input is greater than largest uint8).\n     *\n     * Counterpart to Solidity's `uint8` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 8 bits\n     */\n    function toUint8(uint256 value) internal pure returns (uint8) {\n        if (value > type(uint8).max) {\n            revert SafeCastOverflowedUintDowncast(8, value);\n        }\n        return uint8(value);\n    }\n\n    /**\n     * @dev Converts a signed int256 into an unsigned uint256.\n     *\n     * Requirements:\n     *\n     * - input must be greater than or equal to 0.\n     */\n    function toUint256(int256 value) internal pure returns (uint256) {\n        if (value < 0) {\n            revert SafeCastOverflowedIntToUint(value);\n        }\n        return uint256(value);\n    }\n\n    /**\n     * @dev Returns the downcasted int248 from int256, reverting on\n     * overflow (when the input is less than smallest int248 or\n     * greater than largest int248).\n     *\n     * Counterpart to Solidity's `int248` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 248 bits\n     */\n    function toInt248(int256 value) internal pure returns (int248 downcasted) {\n        downcasted = int248(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(248, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int240 from int256, reverting on\n     * overflow (when the input is less than smallest int240 or\n     * greater than largest int240).\n     *\n     * Counterpart to Solidity's `int240` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 240 bits\n     */\n    function toInt240(int256 value) internal pure returns (int240 downcasted) {\n        downcasted = int240(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(240, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int232 from int256, reverting on\n     * overflow (when the input is less than smallest int232 or\n     * greater than largest int232).\n     *\n     * Counterpart to Solidity's `int232` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 232 bits\n     */\n    function toInt232(int256 value) internal pure returns (int232 downcasted) {\n        downcasted = int232(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(232, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int224 from int256, reverting on\n     * overflow (when the input is less than smallest int224 or\n     * greater than largest int224).\n     *\n     * Counterpart to Solidity's `int224` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 224 bits\n     */\n    function toInt224(int256 value) internal pure returns (int224 downcasted) {\n        downcasted = int224(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(224, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int216 from int256, reverting on\n     * overflow (when the input is less than smallest int216 or\n     * greater than largest int216).\n     *\n     * Counterpart to Solidity's `int216` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 216 bits\n     */\n    function toInt216(int256 value) internal pure returns (int216 downcasted) {\n        downcasted = int216(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(216, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int208 from int256, reverting on\n     * overflow (when the input is less than smallest int208 or\n     * greater than largest int208).\n     *\n     * Counterpart to Solidity's `int208` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 208 bits\n     */\n    function toInt208(int256 value) internal pure returns (int208 downcasted) {\n        downcasted = int208(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(208, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int200 from int256, reverting on\n     * overflow (when the input is less than smallest int200 or\n     * greater than largest int200).\n     *\n     * Counterpart to Solidity's `int200` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 200 bits\n     */\n    function toInt200(int256 value) internal pure returns (int200 downcasted) {\n        downcasted = int200(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(200, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int192 from int256, reverting on\n     * overflow (when the input is less than smallest int192 or\n     * greater than largest int192).\n     *\n     * Counterpart to Solidity's `int192` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 192 bits\n     */\n    function toInt192(int256 value) internal pure returns (int192 downcasted) {\n        downcasted = int192(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(192, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int184 from int256, reverting on\n     * overflow (when the input is less than smallest int184 or\n     * greater than largest int184).\n     *\n     * Counterpart to Solidity's `int184` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 184 bits\n     */\n    function toInt184(int256 value) internal pure returns (int184 downcasted) {\n        downcasted = int184(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(184, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int176 from int256, reverting on\n     * overflow (when the input is less than smallest int176 or\n     * greater than largest int176).\n     *\n     * Counterpart to Solidity's `int176` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 176 bits\n     */\n    function toInt176(int256 value) internal pure returns (int176 downcasted) {\n        downcasted = int176(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(176, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int168 from int256, reverting on\n     * overflow (when the input is less than smallest int168 or\n     * greater than largest int168).\n     *\n     * Counterpart to Solidity's `int168` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 168 bits\n     */\n    function toInt168(int256 value) internal pure returns (int168 downcasted) {\n        downcasted = int168(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(168, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int160 from int256, reverting on\n     * overflow (when the input is less than smallest int160 or\n     * greater than largest int160).\n     *\n     * Counterpart to Solidity's `int160` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 160 bits\n     */\n    function toInt160(int256 value) internal pure returns (int160 downcasted) {\n        downcasted = int160(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(160, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int152 from int256, reverting on\n     * overflow (when the input is less than smallest int152 or\n     * greater than largest int152).\n     *\n     * Counterpart to Solidity's `int152` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 152 bits\n     */\n    function toInt152(int256 value) internal pure returns (int152 downcasted) {\n        downcasted = int152(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(152, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int144 from int256, reverting on\n     * overflow (when the input is less than smallest int144 or\n     * greater than largest int144).\n     *\n     * Counterpart to Solidity's `int144` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 144 bits\n     */\n    function toInt144(int256 value) internal pure returns (int144 downcasted) {\n        downcasted = int144(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(144, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int136 from int256, reverting on\n     * overflow (when the input is less than smallest int136 or\n     * greater than largest int136).\n     *\n     * Counterpart to Solidity's `int136` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 136 bits\n     */\n    function toInt136(int256 value) internal pure returns (int136 downcasted) {\n        downcasted = int136(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(136, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int128 from int256, reverting on\n     * overflow (when the input is less than smallest int128 or\n     * greater than largest int128).\n     *\n     * Counterpart to Solidity's `int128` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 128 bits\n     */\n    function toInt128(int256 value) internal pure returns (int128 downcasted) {\n        downcasted = int128(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(128, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int120 from int256, reverting on\n     * overflow (when the input is less than smallest int120 or\n     * greater than largest int120).\n     *\n     * Counterpart to Solidity's `int120` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 120 bits\n     */\n    function toInt120(int256 value) internal pure returns (int120 downcasted) {\n        downcasted = int120(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(120, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int112 from int256, reverting on\n     * overflow (when the input is less than smallest int112 or\n     * greater than largest int112).\n     *\n     * Counterpart to Solidity's `int112` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 112 bits\n     */\n    function toInt112(int256 value) internal pure returns (int112 downcasted) {\n        downcasted = int112(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(112, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int104 from int256, reverting on\n     * overflow (when the input is less than smallest int104 or\n     * greater than largest int104).\n     *\n     * Counterpart to Solidity's `int104` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 104 bits\n     */\n    function toInt104(int256 value) internal pure returns (int104 downcasted) {\n        downcasted = int104(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(104, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int96 from int256, reverting on\n     * overflow (when the input is less than smallest int96 or\n     * greater than largest int96).\n     *\n     * Counterpart to Solidity's `int96` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 96 bits\n     */\n    function toInt96(int256 value) internal pure returns (int96 downcasted) {\n        downcasted = int96(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(96, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int88 from int256, reverting on\n     * overflow (when the input is less than smallest int88 or\n     * greater than largest int88).\n     *\n     * Counterpart to Solidity's `int88` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 88 bits\n     */\n    function toInt88(int256 value) internal pure returns (int88 downcasted) {\n        downcasted = int88(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(88, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int80 from int256, reverting on\n     * overflow (when the input is less than smallest int80 or\n     * greater than largest int80).\n     *\n     * Counterpart to Solidity's `int80` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 80 bits\n     */\n    function toInt80(int256 value) internal pure returns (int80 downcasted) {\n        downcasted = int80(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(80, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int72 from int256, reverting on\n     * overflow (when the input is less than smallest int72 or\n     * greater than largest int72).\n     *\n     * Counterpart to Solidity's `int72` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 72 bits\n     */\n    function toInt72(int256 value) internal pure returns (int72 downcasted) {\n        downcasted = int72(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(72, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int64 from int256, reverting on\n     * overflow (when the input is less than smallest int64 or\n     * greater than largest int64).\n     *\n     * Counterpart to Solidity's `int64` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 64 bits\n     */\n    function toInt64(int256 value) internal pure returns (int64 downcasted) {\n        downcasted = int64(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(64, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int56 from int256, reverting on\n     * overflow (when the input is less than smallest int56 or\n     * greater than largest int56).\n     *\n     * Counterpart to Solidity's `int56` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 56 bits\n     */\n    function toInt56(int256 value) internal pure returns (int56 downcasted) {\n        downcasted = int56(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(56, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int48 from int256, reverting on\n     * overflow (when the input is less than smallest int48 or\n     * greater than largest int48).\n     *\n     * Counterpart to Solidity's `int48` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 48 bits\n     */\n    function toInt48(int256 value) internal pure returns (int48 downcasted) {\n        downcasted = int48(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(48, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int40 from int256, reverting on\n     * overflow (when the input is less than smallest int40 or\n     * greater than largest int40).\n     *\n     * Counterpart to Solidity's `int40` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 40 bits\n     */\n    function toInt40(int256 value) internal pure returns (int40 downcasted) {\n        downcasted = int40(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(40, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int32 from int256, reverting on\n     * overflow (when the input is less than smallest int32 or\n     * greater than largest int32).\n     *\n     * Counterpart to Solidity's `int32` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 32 bits\n     */\n    function toInt32(int256 value) internal pure returns (int32 downcasted) {\n        downcasted = int32(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(32, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int24 from int256, reverting on\n     * overflow (when the input is less than smallest int24 or\n     * greater than largest int24).\n     *\n     * Counterpart to Solidity's `int24` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 24 bits\n     */\n    function toInt24(int256 value) internal pure returns (int24 downcasted) {\n        downcasted = int24(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(24, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int16 from int256, reverting on\n     * overflow (when the input is less than smallest int16 or\n     * greater than largest int16).\n     *\n     * Counterpart to Solidity's `int16` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 16 bits\n     */\n    function toInt16(int256 value) internal pure returns (int16 downcasted) {\n        downcasted = int16(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(16, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int8 from int256, reverting on\n     * overflow (when the input is less than smallest int8 or\n     * greater than largest int8).\n     *\n     * Counterpart to Solidity's `int8` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 8 bits\n     */\n    function toInt8(int256 value) internal pure returns (int8 downcasted) {\n        downcasted = int8(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(8, value);\n        }\n    }\n\n    /**\n     * @dev Converts an unsigned uint256 into a signed int256.\n     *\n     * Requirements:\n     *\n     * - input must be less than or equal to maxInt256.\n     */\n    function toInt256(uint256 value) internal pure returns (int256) {\n        // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive\n        if (value > uint256(type(int256).max)) {\n            revert SafeCastOverflowedUintToInt(value);\n        }\n        return int256(value);\n    }\n\n    /**\n     * @dev Cast a boolean (false or true) to a uint256 (0 or 1) with no jump.\n     */\n    function toUint(bool b) internal pure returns (uint256 u) {\n        assembly (\"memory-safe\") {\n            u := iszero(iszero(b))\n        }\n    }\n}\n"},{"file_path":"src/finance/Accounting.sol","source_code":"// SPDX-License-Identifier: MIT\npragma solidity 0.8.28;\n\nimport {FixedPointMathLib} from \"@solmate/src/utils/FixedPointMathLib.sol\";\n\nimport {IFarm} from \"@interfaces/IFarm.sol\";\nimport {IOracle} from \"@interfaces/IOracle.sol\";\nimport {CoreRoles} from \"@libraries/CoreRoles.sol\";\nimport {FarmRegistry} from \"@integrations/FarmRegistry.sol\";\nimport {CoreControlled} from \"@core/CoreControlled.sol\";\n\n/// @notice InfiniFi Accounting contract\ncontract Accounting is CoreControlled {\n    using FixedPointMathLib for uint256;\n\n    event PriceSet(uint256 indexed timestamp, address indexed asset, uint256 price);\n    event OracleSet(uint256 indexed timestamp, address indexed asset, address oracle);\n\n    /// @notice reference to the farm registry\n    address public immutable farmRegistry;\n\n    constructor(address _core, address _farmRegistry) CoreControlled(_core) {\n        farmRegistry = _farmRegistry;\n    }\n\n    /// @notice mapping from asset to oracle\n    mapping(address => address) public oracle;\n\n    /// @notice returns the price of an asset\n    function price(address _asset) external view returns (uint256) {\n        return IOracle(oracle[_asset]).price();\n    }\n\n    /// @notice set the oracle for an asset\n    function setOracle(address _asset, address _oracle) external onlyCoreRole(CoreRoles.ORACLE_MANAGER) {\n        oracle[_asset] = _oracle;\n        emit OracleSet(block.timestamp, _asset, _oracle);\n    }\n\n    /// -------------------------------------------------------------------------------------------\n    /// Reference token getters (e.g. USD for iUSD, ETH for iETH, ...)\n    /// @dev note that the \"USD\" token does not exist, it is just an abstract unit of account\n    /// used in the protocol to represent stablecoins pegged to USD, that allows to uniformly\n    /// account for a diverse reserve composed of USDC, DAI, FRAX, etc.\n    /// -------------------------------------------------------------------------------------------\n\n    /// @notice returns the sum of the value of all assets held on protocol contracts listed in the farm registry.\n    function totalAssetsValue() external view returns (uint256 _totalValue) {\n        address[] memory assets = FarmRegistry(farmRegistry).getEnabledAssets();\n        for (uint256 i = 0; i < assets.length; i++) {\n            uint256 assetPrice = IOracle(oracle[assets[i]]).price();\n            uint256 _assets = _calculateTotalAssets(FarmRegistry(farmRegistry).getAssetFarms(assets[i]));\n            _totalValue += _assets.mulWadDown(assetPrice);\n        }\n    }\n\n    /// @notice returns the sum of the value of all liquid assets held on protocol contracts listed in the farm registry.\n    /// @dev see totalAssetsValue()\n    function totalAssetsValueOf(uint256 _type) external view returns (uint256 _totalValue) {\n        address[] memory assets = FarmRegistry(farmRegistry).getEnabledAssets();\n        for (uint256 i = 0; i < assets.length; i++) {\n            uint256 assetPrice = IOracle(oracle[assets[i]]).price();\n            address[] memory assetFarms = FarmRegistry(farmRegistry).getAssetTypeFarms(assets[i], uint256(_type));\n            uint256 _assets = _calculateTotalAssets(assetFarms);\n            _totalValue += _assets.mulWadDown(assetPrice);\n        }\n    }\n\n    /// -------------------------------------------------------------------------------------------\n    /// Specific asset getters (e.g. USDC, DAI, ...)\n    /// -------------------------------------------------------------------------------------------\n\n    /// @notice returns the sum of the balance of all farms of a given asset.\n    function totalAssets(address _asset) external view returns (uint256) {\n        return _calculateTotalAssets(FarmRegistry(farmRegistry).getAssetFarms(_asset));\n    }\n\n    function totalAssetsOf(address _asset, uint256 _type) external view returns (uint256) {\n        return _calculateTotalAssets(FarmRegistry(farmRegistry).getAssetTypeFarms(_asset, uint256(_type)));\n    }\n\n    /// -------------------------------------------------------------------------------------------\n    /// Internal helpers\n    /// -------------------------------------------------------------------------------------------\n\n    function _calculateTotalAssets(address[] memory _farms) internal view returns (uint256 _totalAssets) {\n        uint256 length = _farms.length;\n        for (uint256 index = 0; index < length; index++) {\n            _totalAssets += IFarm(_farms[index]).assets();\n        }\n    }\n}\n"},{"file_path":"src/finance/YieldSharingV2.sol","source_code":"// SPDX-License-Identifier: MIT\npragma solidity 0.8.28;\n\nimport {Math} from \"@openzeppelin/contracts/utils/math/Math.sol\";\nimport {Ownable} from \"@openzeppelin/contracts/access/Ownable.sol\";\nimport {FixedPointMathLib} from \"@solmate/src/utils/FixedPointMathLib.sol\";\n\nimport {CoreRoles} from \"@libraries/CoreRoles.sol\";\nimport {Accounting} from \"@finance/Accounting.sol\";\nimport {StakedToken} from \"@tokens/StakedToken.sol\";\nimport {ReceiptToken} from \"@tokens/ReceiptToken.sol\";\nimport {CoreControlled} from \"@core/CoreControlled.sol\";\nimport {LockingController} from \"@locking/LockingController.sol\";\nimport {FixedPriceOracle} from \"@finance/oracles/FixedPriceOracle.sol\";\n\n/// @dev Escrow of interpolating rewards, owned by the YieldSharing contract.\n/// the iUSD interpolated need to sit on another address (hence the escrow), because\n/// all iUSD held by the YieldSharing contract are considered to be part of the safety buffer.\ncontract YieldVestingEscrow is Ownable {\n    constructor() Ownable(msg.sender) {}\n\n    function send(address _token, address _to, uint256 _amount) external onlyOwner {\n        // forge-lint: disable-next-line(erc20-unchecked-transfer)\n        ReceiptToken(_token).transfer(_to, _amount);\n    }\n}\n\n/// @notice InfiniFi YieldSharing contract\n/// @dev This contract is used to distribute yield between iUSD locking users and siUSD holders.\n/// @dev It also holds idle iUSD that can be used to slash losses or distribute profits.\n/// @dev This V2 interpolates yield over a configurable duration for the staked token, and airdrops iUSD to the vault\n/// instead of calling depositRewards(). This allows for interpolation of yield for liquid depositors over a configurable\n/// duration instead of a full epoch (7 days), which is more robust when the protocol's TVL is growing steadily and dilutes\n/// less the rewards of liquid depositors.\ncontract YieldSharingV2 is CoreControlled {\n    using FixedPointMathLib for uint256;\n\n    error PerformanceFeeTooHigh(uint256 _percent);\n    error PerformanceFeeRecipientIsZeroAddress(address _recipient);\n    error TargetIlliquidRatioTooHigh(uint256 _ratio);\n    error StakedTokenNotAvailable();\n\n    /// @notice Fired when yield is accrued from frarms\n    /// @param timestamp block timestamp of the accrual\n    /// @param yield profit or loss in farms since last accrual\n    event YieldAccrued(uint256 indexed timestamp, int256 yield);\n    event InterpolationDurationUpdated(uint256 indexed timestamp, uint256 duration);\n    event TargetIlliquidRatioUpdated(uint256 indexed timestamp, uint256 multiplier);\n    event SafetyBufferSizeUpdated(uint256 indexed timestamp, uint256 value);\n    event LiquidMultiplierUpdated(uint256 indexed timestamp, uint256 multiplier);\n    event PerformanceFeeSettingsUpdated(uint256 indexed timestamp, uint256 percentage, address recipient);\n\n    uint256 public constant MAX_PERFORMANCE_FEE = 0.2e18; // 20%\n\n    /// @notice reference to farm accounting contract\n    address public immutable accounting;\n\n    /// @notice reference to receipt token\n    address public immutable receiptToken;\n\n    /// @notice reference to staked token\n    address public immutable stakedToken;\n\n    /// @notice reference to locking module\n    address public immutable lockingModule;\n\n    /// @notice safety buffer amount.\n    /// This amount of iUSD is held on the contract and consumed first in case of losses smaller\n    /// than the safety buffer. It is also replenished first in case of profit, up to the buffer size.\n    /// The buffer held could exceed safetyBufferSize if there are donations to this contract, or if\n    /// the buffer size has been reduced since last profit distribution, or if there are no other\n    /// users to distribute to.\n    /// The safety buffer is meant to absorb small losses such as slippage or fees when\n    /// deploying capital to productive farms.\n    /// safety buffer can be emptied by governance through the use of emergencyAction().\n    uint256 public safetyBufferSize;\n\n    /// @notice optional performance fee, expressed as a percentage with 18 decimals.\n    uint256 public performanceFee; // default to 0%\n\n    /// @notice optional performance fee recipient\n    address public performanceFeeRecipient;\n\n    /// @notice multiplier for the liquid return, expressed as a percentage with 18 decimals.\n    uint256 public liquidReturnMultiplier = FixedPointMathLib.WAD; // default to 1.0\n\n    /// @notice target illiquid ratio, expressed as a percentage with 18 decimals.\n    /// This ratio is the minimum percent of illiquid holdings the protocol is targetting, and\n    /// if there is a percentage of illiquid users lower than the targetIlliquidRatio, the protocol\n    /// wil distribute additional rewards to the illiquid users until targetIlliquidRatio is reached.\n    uint256 public targetIlliquidRatio; // default to 0\n\n    struct StakedReceiptTokenCache {\n        uint48 blockTimestamp;\n        uint208 amount;\n    }\n\n    StakedReceiptTokenCache public stakedReceiptTokenCache;\n\n    /// @notice escrow of rewards to staked users\n    YieldVestingEscrow public immutable escrow;\n\n    /// @notice interpolation duration of rewards to staked users\n    uint256 public interpolationDuration = 8 hours;\n\n    struct Point {\n        uint32 lastAccrued;\n        uint32 lastClaimed;\n        uint208 rate;\n    }\n\n    /// @notice point used for interpolating rewards of the staked users\n    Point public point = Point({lastAccrued: uint32(block.timestamp), lastClaimed: uint32(block.timestamp), rate: 0});\n\n    /// @notice Make deposits and withdrawals in the staked token revert unless set to true.\n    bool public transient canEnterOrExitStakedToken;\n\n    constructor(address _core, address _accounting, address _receiptToken, address _stakedToken, address _lockingModule)\n        CoreControlled(_core)\n    {\n        accounting = _accounting;\n        receiptToken = _receiptToken;\n        stakedToken = _stakedToken;\n        lockingModule = _lockingModule;\n\n        escrow = new YieldVestingEscrow();\n        ReceiptToken(receiptToken).approve(_lockingModule, type(uint256).max);\n    }\n\n    /// @notice set the safety buffer size\n    /// @param _safetyBufferSize the new safety buffer size\n    function setSafetyBufferSize(uint256 _safetyBufferSize) external onlyCoreRole(CoreRoles.PROTOCOL_PARAMETERS) {\n        safetyBufferSize = _safetyBufferSize;\n        emit SafetyBufferSizeUpdated(block.timestamp, _safetyBufferSize);\n    }\n\n    /// @notice set the performance fee and recipient\n    function setPerformanceFeeAndRecipient(uint256 _percent, address _recipient)\n        external\n        onlyCoreRole(CoreRoles.PROTOCOL_PARAMETERS)\n    {\n        require(_percent <= MAX_PERFORMANCE_FEE, PerformanceFeeTooHigh(_percent));\n        if (_percent > 0) {\n            require(_recipient != address(0), PerformanceFeeRecipientIsZeroAddress(_recipient));\n        }\n\n        performanceFee = _percent;\n        performanceFeeRecipient = _recipient;\n        emit PerformanceFeeSettingsUpdated(block.timestamp, _percent, _recipient);\n    }\n\n    /// @notice set the liquid return multiplier\n    function setLiquidReturnMultiplier(uint256 _multiplier) external onlyCoreRole(CoreRoles.PROTOCOL_PARAMETERS) {\n        liquidReturnMultiplier = _multiplier;\n        emit LiquidMultiplierUpdated(block.timestamp, _multiplier);\n    }\n\n    /// @notice set the target illiquid ratio\n    function setTargetIlliquidRatio(uint256 _ratio) external onlyCoreRole(CoreRoles.PROTOCOL_PARAMETERS) {\n        require(_ratio <= FixedPointMathLib.WAD, TargetIlliquidRatioTooHigh(_ratio));\n        targetIlliquidRatio = _ratio;\n        emit TargetIlliquidRatioUpdated(block.timestamp, _ratio);\n    }\n\n    /// @notice set the interpolation duration of StakedToken rewards\n    /// @dev Note that the rate of distribution will only change after the next accrue() call\n    /// that is distributing a non-zero amount of rewards to the staked users.\n    function setInterpolationDuration(uint256 _duration) external onlyCoreRole(CoreRoles.PROTOCOL_PARAMETERS) {\n        interpolationDuration = _duration;\n        emit InterpolationDurationUpdated(block.timestamp, _duration);\n    }\n\n    /// @notice returns the yield earned by the protocol since the last accrue() call.\n    /// @return yield as an amount of receiptTokens.\n    /// @dev Note that yield can be negative if the protocol farms have lost value, or if the\n    /// oracle price of assets held in the protocol has decreased since last accrue() call,\n    /// or if more ReceiptTokens entered circulation than assets entered the protocol.\n    function unaccruedYield() public view returns (int256) {\n        uint256 receiptTokenPrice = Accounting(accounting).price(receiptToken);\n        uint256 assets = Accounting(accounting).totalAssetsValue(); // returns assets in USD\n\n        uint256 assetsInReceiptTokens = assets.divWadDown(receiptTokenPrice);\n\n        // casting to 'int256' is safe because type(int256).max is an irrealistically large amount of receiptTokens\n        // forge-lint: disable-next-line(unsafe-typecast)\n        return int256(assetsInReceiptTokens) - int256(ReceiptToken(receiptToken).totalSupply());\n    }\n\n    /// @notice accrue yield and handle profits & losses\n    /// This function should bring back unaccruedYield() to 0 by minting receiptTokens into circulation (profit distribution)\n    /// or burning receipt tokens (slashing) or updating the oracle price of the receiptToken if there\n    /// are not enough first-loss capital stakers to slash.\n    function accrue() external whenNotPaused {\n        distributeInterpolationRewards();\n\n        int256 yield = unaccruedYield();\n        // casting to 'uint256' is safe because of 'if'\n        // forge-lint: disable-next-line(unsafe-typecast)\n        if (yield > 0) _handlePositiveYield(uint256(yield));\n        // casting to 'uint256' is safe because of 'else'\n        // forge-lint: disable-next-line(unsafe-typecast)\n        else if (yield < 0) _handleNegativeYield(uint256(-yield));\n\n        emit YieldAccrued(block.timestamp, yield);\n    }\n\n    function _getCachedStakedReceiptTokens() internal returns (uint256) {\n        StakedReceiptTokenCache memory data = stakedReceiptTokenCache;\n        if (uint256(data.blockTimestamp) == block.timestamp) {\n            return uint256(data.amount);\n        }\n        uint256 amount = ReceiptToken(receiptToken).balanceOf(stakedToken);\n        assert(amount <= type(uint208).max);\n\n        // casting to 'uint48' is safe because type(uint48).max timestamp is very far in the future\n        // forge-lint: disable-next-line(unsafe-typecast)\n        stakedReceiptTokenCache.blockTimestamp = uint48(block.timestamp);\n        // casting to 'uint208' is safe because of the assert above\n        // forge-lint: disable-next-line(unsafe-typecast)\n        stakedReceiptTokenCache.amount = uint208(amount);\n\n        return amount;\n    }\n\n    // hook called by any deposits and withdrawals in siUSD vault, we revert if the\n    // flag is not set to true. this will break 4626 compatibility of the vault for\n    // deposits and withdrawals, but the gateway can set the flag and perform entry/\n    // exits on behalf of the users.\n    function getCachedStakedReceiptTokens() public returns (uint256) {\n        require(canEnterOrExitStakedToken, StakedTokenNotAvailable());\n        return _getCachedStakedReceiptTokens();\n    }\n\n    // gateway can set the flag to allow deposits and withdrawals in the siUSD vault\n    function setCanEnterOrExitStakedToken(bool _value) external onlyCoreRole(CoreRoles.ENTRY_POINT) {\n        canEnterOrExitStakedToken = _value;\n    }\n\n    /// @notice Number of rewards interpolating to staked users\n    function vesting() public view returns (uint256) {\n        return ReceiptToken(receiptToken).balanceOf(address(escrow));\n    }\n\n    /// @notice Number of rewards vested to staked users\n    function vested() public view returns (uint256) {\n        uint256 _vesting = vesting();\n        if (_vesting == 0) return 0;\n\n        uint256 maxTs = Math.max(point.lastAccrued, point.lastClaimed);\n        return Math.min(_vesting, uint256(point.rate) * (block.timestamp - maxTs));\n    }\n\n    // send the vested rewards to the siUSD vault\n    // called by the gateway before stake & unstake,\n    // and here in the yieldSharing before accrue()\n    function distributeInterpolationRewards() public {\n        uint256 _vested = vested();\n        point.lastClaimed = uint32(block.timestamp);\n        if (_vested != 0) {\n            escrow.send(receiptToken, stakedToken, _vested);\n        }\n    }\n\n    /// @notice Yield sharing: split between iUSD lockin users & siUSD holders.\n    /// If no users are locking or saving, the profit is minted on this contract and\n    /// held idle so that the accrue() expected behavior of restoring protocol equity to 0\n    /// is maintained. Funds minted on this contract in such a way can be unstuck by governance\n    /// through the use of emergencyAction().\n    function _handlePositiveYield(uint256 _positiveYield) internal {\n        uint256 stakedReceiptTokens = _getCachedStakedReceiptTokens().mulWadDown(liquidReturnMultiplier);\n        uint256 receiptTokenTotalSupply = ReceiptToken(receiptToken).totalSupply();\n        uint256 targetIlliquidMinimum = receiptTokenTotalSupply.mulWadDown(targetIlliquidRatio);\n        uint256 lockingReceiptTokens = LockingController(lockingModule).totalBalance();\n        if (lockingReceiptTokens < targetIlliquidMinimum) {\n            lockingReceiptTokens = targetIlliquidMinimum;\n        }\n        uint256 bondingMultiplier = LockingController(lockingModule).rewardMultiplier();\n        lockingReceiptTokens = lockingReceiptTokens.mulWadDown(bondingMultiplier);\n        uint256 totalReceiptTokens = stakedReceiptTokens + lockingReceiptTokens;\n\n        // mint yield\n        ReceiptToken(receiptToken).mint(address(this), _positiveYield);\n\n        // fill safety buffer first\n        uint256 _safetyBufferSize = safetyBufferSize;\n        if (_safetyBufferSize > 0) {\n            uint256 safetyBuffer = ReceiptToken(receiptToken).balanceOf(address(this)) - _positiveYield;\n            if (safetyBuffer < _safetyBufferSize) {\n                if (safetyBuffer + _positiveYield > _safetyBufferSize) {\n                    // there will be a leftover profit after filling the safety buffer, so we\n                    // deduct the safety buffer contribution from the profits and continue\n                    _positiveYield -= _safetyBufferSize - safetyBuffer;\n                } else {\n                    // do not do any further distribution and only replenish the safety buffer\n                    return;\n                }\n            }\n        }\n\n        // performance fee\n        uint256 _performanceFee = performanceFee;\n        if (_performanceFee > 0) {\n            uint256 fee = _positiveYield.mulWadDown(_performanceFee);\n            if (fee > 0) {\n                // forge-lint: disable-next-line(erc20-unchecked-transfer)\n                ReceiptToken(receiptToken).transfer(performanceFeeRecipient, fee);\n                _positiveYield -= fee;\n            }\n        }\n\n        // compute splits\n        if (totalReceiptTokens == 0) {\n            // nobody to distribute to, do nothing and hold the tokens\n            return;\n        }\n\n        // yield split to staked users\n        uint256 stakingProfit = _positiveYield.mulDivDown(stakedReceiptTokens, totalReceiptTokens);\n        if (stakingProfit > 0) {\n            // forge-lint: disable-next-line(erc20-unchecked-transfer)\n            ReceiptToken(receiptToken).transfer(address(escrow), stakingProfit);\n            // casting to 'uint208' is safe because type(uint208).max would be an outrageously large rate per second\n            // forge-lint: disable-next-line(unsafe-typecast)\n            point.rate = uint208(vesting() / interpolationDuration);\n            point.lastAccrued = uint32(block.timestamp);\n        }\n\n        // yield split to locking users\n        uint256 lockingProfit = _positiveYield - stakingProfit;\n        if (lockingProfit > 0) {\n            LockingController(lockingModule).depositRewards(lockingProfit);\n        }\n    }\n\n    /// @notice Loss propagation: iUSD locking users -> siUSD holders -> iUSD holders\n    function _handleNegativeYield(uint256 _negativeYield) internal {\n        // if there is a safety buffer, and the loss is smaller than the safety buffer,\n        // consume it and do not apply any losses to users.\n        uint256 safetyBuffer = ReceiptToken(receiptToken).balanceOf(address(this));\n        if (safetyBuffer >= _negativeYield) {\n            ReceiptToken(receiptToken).burn(_negativeYield);\n            return;\n        }\n\n        // first, apply losses to locking users\n        uint256 lockingReceiptTokens = LockingController(lockingModule).totalBalance();\n        if (_negativeYield <= lockingReceiptTokens) {\n            LockingController(lockingModule).applyLosses(_negativeYield);\n            return;\n        }\n        LockingController(lockingModule).applyLosses(lockingReceiptTokens);\n        _negativeYield -= lockingReceiptTokens;\n\n        // second, apply negativeYield to siUSD holders\n        uint256 stakedReceiptTokens = ReceiptToken(receiptToken).balanceOf(stakedToken);\n        if (_negativeYield <= stakedReceiptTokens) {\n            StakedToken(stakedToken).applyLosses(_negativeYield);\n            return;\n        }\n        StakedToken(stakedToken).applyLosses(stakedReceiptTokens);\n        _negativeYield -= stakedReceiptTokens;\n\n        // lastly, apply losses to all iUSD in circulation\n        uint256 totalSupply = ReceiptToken(receiptToken).totalSupply();\n        address oracle = Accounting(accounting).oracle(receiptToken);\n        uint256 price = FixedPriceOracle(oracle).price();\n        uint256 newPrice = price.mulDivDown(totalSupply - _negativeYield, totalSupply);\n        FixedPriceOracle(oracle).setPrice(newPrice);\n    }\n\n    function migrateSafetyBuffer(address _source) external onlyCoreRole(CoreRoles.GOVERNOR) {\n        uint256 sourceBalance = ReceiptToken(receiptToken).balanceOf(_source);\n        uint256 sourceAllowance = ReceiptToken(receiptToken).allowance(_source, address(this));\n        uint256 amount = sourceAllowance < sourceBalance ? sourceAllowance : sourceBalance;\n        if (amount > 0) {\n            // forge-lint: disable-next-line(erc20-unchecked-transfer)\n            ReceiptToken(receiptToken).transferFrom(_source, address(this), amount);\n        }\n    }\n}\n"},{"file_path":"src/integrations/FarmRegistry.sol","source_code":"// SPDX-License-Identifier: MIT\npragma solidity 0.8.28;\n\nimport {IFarm} from \"@interfaces/IFarm.sol\";\nimport {CoreRoles} from \"@libraries/CoreRoles.sol\";\nimport {EnumerableSet} from \"@openzeppelin/contracts/utils/structs/EnumerableSet.sol\";\nimport {CoreControlled} from \"@core/CoreControlled.sol\";\n\n/// @notice InfiniFi Farm registry\ncontract FarmRegistry is CoreControlled {\n    error FarmAlreadyAdded(address farm);\n    error FarmNotFound(address farm);\n    error AssetNotEnabled(address farm, address asset);\n    error AssetAlreadyEnabled(address asset);\n    error AssetNotFound(address asset);\n\n    event AssetEnabled(uint256 indexed timestamp, address asset);\n    event AssetDisabled(uint256 indexed timestamp, address asset);\n    event FarmsAdded(uint256 indexed timestamp, uint256 farmType, address[] indexed farms);\n    event FarmsRemoved(uint256 indexed timestamp, uint256 farmType, address[] indexed farms);\n\n    using EnumerableSet for EnumerableSet.AddressSet;\n\n    EnumerableSet.AddressSet private assets;\n    EnumerableSet.AddressSet private farms;\n    mapping(uint256 _type => EnumerableSet.AddressSet _farms) private typeFarms;\n    mapping(address _asset => EnumerableSet.AddressSet _farms) private assetFarms;\n    mapping(address _asset => mapping(uint256 _type => EnumerableSet.AddressSet _farms)) private assetTypeFarms;\n\n    constructor(address _core) CoreControlled(_core) {}\n\n    /// ----------------------------------------------------------------------------\n    /// READ METHODS\n    /// ----------------------------------------------------------------------------\n\n    function getEnabledAssets() external view returns (address[] memory) {\n        return assets.values();\n    }\n\n    function isAssetEnabled(address _asset) external view returns (bool) {\n        return assets.contains(_asset);\n    }\n\n    function getFarms() external view returns (address[] memory) {\n        return farms.values();\n    }\n\n    function getTypeFarms(uint256 _type) external view returns (address[] memory) {\n        return typeFarms[_type].values();\n    }\n\n    function getAssetFarms(address _asset) external view returns (address[] memory) {\n        return assetFarms[_asset].values();\n    }\n\n    function getAssetTypeFarms(address _asset, uint256 _type) external view returns (address[] memory) {\n        return assetTypeFarms[_asset][_type].values();\n    }\n\n    function isFarm(address _farm) external view returns (bool) {\n        return farms.contains(_farm);\n    }\n\n    function isFarmOfAsset(address _farm, address _asset) external view returns (bool) {\n        return assetFarms[_asset].contains(_farm);\n    }\n\n    function isFarmOfType(address _farm, uint256 _type) external view returns (bool) {\n        return typeFarms[_type].contains(_farm);\n    }\n\n    /// ----------------------------------------------------------------------------\n    /// WRITE METHODS\n    /// ----------------------------------------------------------------------------\n\n    function enableAsset(address _asset) external onlyCoreRole(CoreRoles.GOVERNOR) {\n        require(assets.add(_asset), AssetAlreadyEnabled(_asset));\n        emit AssetEnabled(block.timestamp, _asset);\n    }\n\n    function disableAsset(address _asset) external onlyCoreRole(CoreRoles.GOVERNOR) {\n        require(assets.remove(_asset), AssetNotFound(_asset));\n        emit AssetDisabled(block.timestamp, _asset);\n    }\n\n    function addFarms(uint256 _type, address[] calldata _list) external onlyCoreRole(CoreRoles.PROTOCOL_PARAMETERS) {\n        _addFarms(_type, _list);\n        emit FarmsAdded(block.timestamp, _type, _list);\n    }\n\n    function removeFarms(uint256 _type, address[] calldata _list) external onlyCoreRole(CoreRoles.PROTOCOL_PARAMETERS) {\n        _removeFarms(_type, _list);\n        emit FarmsRemoved(block.timestamp, _type, _list);\n    }\n\n    /// ----------------------------------------------------------------------------\n    /// INTERNAL METHODS\n    /// ----------------------------------------------------------------------------\n\n    function _addFarms(uint256 _type, address[] calldata _list) internal {\n        for (uint256 i = 0; i < _list.length; i++) {\n            address farmAsset = IFarm(_list[i]).assetToken();\n            require(assets.contains(farmAsset), AssetNotEnabled(_list[i], farmAsset));\n            require(farms.add(_list[i]), FarmAlreadyAdded(_list[i]));\n            require(typeFarms[_type].add(_list[i]), FarmAlreadyAdded(_list[i]));\n            require(assetFarms[farmAsset].add(_list[i]), FarmAlreadyAdded(_list[i]));\n            require(assetTypeFarms[farmAsset][_type].add(_list[i]), FarmAlreadyAdded(_list[i]));\n        }\n    }\n\n    function _removeFarms(uint256 _type, address[] calldata _list) internal {\n        for (uint256 i = 0; i < _list.length; i++) {\n            address farmAsset = IFarm(_list[i]).assetToken();\n            require(farms.remove(_list[i]), FarmNotFound(_list[i]));\n            require(typeFarms[_type].remove(_list[i]), FarmNotFound(_list[i]));\n            require(assetFarms[farmAsset].remove(_list[i]), FarmNotFound(_list[i]));\n            require(assetTypeFarms[farmAsset][_type].remove(_list[i]), FarmNotFound(_list[i]));\n        }\n    }\n}\n"},{"file_path":"lib/openzeppelin-contracts/contracts/access/Ownable.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)\n\npragma solidity ^0.8.20;\n\nimport {Context} from \"../utils/Context.sol\";\n\n/**\n * @dev Contract module which provides a basic access control mechanism, where\n * there is an account (an owner) that can be granted exclusive access to\n * specific functions.\n *\n * The initial owner is set to the address provided by the deployer. This can\n * later be changed with {transferOwnership}.\n *\n * This module is used through inheritance. It will make available the modifier\n * `onlyOwner`, which can be applied to your functions to restrict their use to\n * the owner.\n */\nabstract contract Ownable is Context {\n    address private _owner;\n\n    /**\n     * @dev The caller account is not authorized to perform an operation.\n     */\n    error OwnableUnauthorizedAccount(address account);\n\n    /**\n     * @dev The owner is not a valid owner account. (eg. `address(0)`)\n     */\n    error OwnableInvalidOwner(address owner);\n\n    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);\n\n    /**\n     * @dev Initializes the contract setting the address provided by the deployer as the initial owner.\n     */\n    constructor(address initialOwner) {\n        if (initialOwner == address(0)) {\n            revert OwnableInvalidOwner(address(0));\n        }\n        _transferOwnership(initialOwner);\n    }\n\n    /**\n     * @dev Throws if called by any account other than the owner.\n     */\n    modifier onlyOwner() {\n        _checkOwner();\n        _;\n    }\n\n    /**\n     * @dev Returns the address of the current owner.\n     */\n    function owner() public view virtual returns (address) {\n        return _owner;\n    }\n\n    /**\n     * @dev Throws if the sender is not the owner.\n     */\n    function _checkOwner() internal view virtual {\n        if (owner() != _msgSender()) {\n            revert OwnableUnauthorizedAccount(_msgSender());\n        }\n    }\n\n    /**\n     * @dev Leaves the contract without owner. It will not be possible to call\n     * `onlyOwner` functions. Can only be called by the current owner.\n     *\n     * NOTE: Renouncing ownership will leave the contract without an owner,\n     * thereby disabling any functionality that is only available to the owner.\n     */\n    function renounceOwnership() public virtual onlyOwner {\n        _transferOwnership(address(0));\n    }\n\n    /**\n     * @dev Transfers ownership of the contract to a new account (`newOwner`).\n     * Can only be called by the current owner.\n     */\n    function transferOwnership(address newOwner) public virtual onlyOwner {\n        if (newOwner == address(0)) {\n            revert OwnableInvalidOwner(address(0));\n        }\n        _transferOwnership(newOwner);\n    }\n\n    /**\n     * @dev Transfers ownership of the contract to a new account (`newOwner`).\n     * Internal function without access restriction.\n     */\n    function _transferOwnership(address newOwner) internal virtual {\n        address oldOwner = _owner;\n        _owner = newOwner;\n        emit OwnershipTransferred(oldOwner, newOwner);\n    }\n}\n"},{"file_path":"lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Permit.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.5.0) (token/ERC20/extensions/IERC20Permit.sol)\n\npragma solidity >=0.4.16;\n\n/**\n * @dev Interface of the ERC-20 Permit extension allowing approvals to be made via signatures, as defined in\n * https://eips.ethereum.org/EIPS/eip-2612[ERC-2612].\n *\n * Adds the {permit} method, which can be used to change an account's ERC-20 allowance (see {IERC20-allowance}) by\n * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't\n * need to send a transaction, and thus is not required to hold Ether at all.\n *\n * ==== Security Considerations\n *\n * There are two important considerations concerning the use of `permit`. The first is that a valid permit signature\n * expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be\n * considered as an intention to spend the allowance in any specific way. The second is that because permits have\n * built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should\n * take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be\n * generally recommended is:\n *\n * ```solidity\n * function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {\n *     try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}\n *     doThing(..., value);\n * }\n *\n * function doThing(..., uint256 value) public {\n *     token.safeTransferFrom(msg.sender, address(this), value);\n *     ...\n * }\n * ```\n *\n * Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of\n * `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also\n * {SafeERC20-safeTransferFrom}).\n *\n * Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so\n * contracts should have entry points that don't rely on permit.\n */\ninterface IERC20Permit {\n    /**\n     * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,\n     * given ``owner``'s signed approval.\n     *\n     * IMPORTANT: The same issues {IERC20-approve} has related to transaction\n     * ordering also applies here.\n     *\n     * Emits an {Approval} event.\n     *\n     * Requirements:\n     *\n     * - `spender` cannot be the zero address.\n     * - `deadline` must be a timestamp in the future.\n     * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`\n     * over the EIP712-formatted function arguments.\n     * - the signature must use ``owner``'s current nonce (see {nonces}).\n     *\n     * For more information on the signature format, see the\n     * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP\n     * section].\n     *\n     * CAUTION: See Security Considerations above.\n     */\n    function permit(\n        address owner,\n        address spender,\n        uint256 value,\n        uint256 deadline,\n        uint8 v,\n        bytes32 r,\n        bytes32 s\n    ) external;\n\n    /**\n     * @dev Returns the current nonce for `owner`. This value must be\n     * included whenever a signature is generated for {permit}.\n     *\n     * Every successful call to {permit} increases ``owner``'s nonce by one. This\n     * prevents a signature from being used multiple times.\n     */\n    function nonces(address owner) external view returns (uint256);\n\n    /**\n     * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.\n     */\n    // solhint-disable-next-line func-name-mixedcase\n    function DOMAIN_SEPARATOR() external view returns (bytes32);\n}\n"},{"file_path":"lib/openzeppelin-contracts/contracts/utils/StorageSlot.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (utils/StorageSlot.sol)\n// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Library for reading and writing primitive types to specific storage slots.\n *\n * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.\n * This library helps with reading and writing to such slots without the need for inline assembly.\n *\n * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.\n *\n * Example usage to set ERC-1967 implementation slot:\n * ```solidity\n * contract ERC1967 {\n *     // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.\n *     bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;\n *\n *     function _getImplementation() internal view returns (address) {\n *         return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;\n *     }\n *\n *     function _setImplementation(address newImplementation) internal {\n *         require(newImplementation.code.length > 0);\n *         StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;\n *     }\n * }\n * ```\n *\n * TIP: Consider using this library along with {SlotDerivation}.\n */\nlibrary StorageSlot {\n    struct AddressSlot {\n        address value;\n    }\n\n    struct BooleanSlot {\n        bool value;\n    }\n\n    struct Bytes32Slot {\n        bytes32 value;\n    }\n\n    struct Uint256Slot {\n        uint256 value;\n    }\n\n    struct Int256Slot {\n        int256 value;\n    }\n\n    struct StringSlot {\n        string value;\n    }\n\n    struct BytesSlot {\n        bytes value;\n    }\n\n    /**\n     * @dev Returns an `AddressSlot` with member `value` located at `slot`.\n     */\n    function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {\n        assembly (\"memory-safe\") {\n            r.slot := slot\n        }\n    }\n\n    /**\n     * @dev Returns a `BooleanSlot` with member `value` located at `slot`.\n     */\n    function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {\n        assembly (\"memory-safe\") {\n            r.slot := slot\n        }\n    }\n\n    /**\n     * @dev Returns a `Bytes32Slot` with member `value` located at `slot`.\n     */\n    function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {\n        assembly (\"memory-safe\") {\n            r.slot := slot\n        }\n    }\n\n    /**\n     * @dev Returns a `Uint256Slot` with member `value` located at `slot`.\n     */\n    function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {\n        assembly (\"memory-safe\") {\n            r.slot := slot\n        }\n    }\n\n    /**\n     * @dev Returns a `Int256Slot` with member `value` located at `slot`.\n     */\n    function getInt256Slot(bytes32 slot) internal pure returns (Int256Slot storage r) {\n        assembly (\"memory-safe\") {\n            r.slot := slot\n        }\n    }\n\n    /**\n     * @dev Returns a `StringSlot` with member `value` located at `slot`.\n     */\n    function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {\n        assembly (\"memory-safe\") {\n            r.slot := slot\n        }\n    }\n\n    /**\n     * @dev Returns an `StringSlot` representation of the string storage pointer `store`.\n     */\n    function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {\n        assembly (\"memory-safe\") {\n            r.slot := store.slot\n        }\n    }\n\n    /**\n     * @dev Returns a `BytesSlot` with member `value` located at `slot`.\n     */\n    function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {\n        assembly (\"memory-safe\") {\n            r.slot := slot\n        }\n    }\n\n    /**\n     * @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.\n     */\n    function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {\n        assembly (\"memory-safe\") {\n            r.slot := store.slot\n        }\n    }\n}\n"},{"file_path":"lib/openzeppelin-contracts/contracts/utils/SlotDerivation.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.5.0) (utils/SlotDerivation.sol)\n// This file was procedurally generated from scripts/generate/templates/SlotDerivation.js.\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Library for computing storage (and transient storage) locations from namespaces and deriving slots\n * corresponding to standard patterns. The derivation method for array and mapping matches the storage layout used by\n * the solidity language / compiler.\n *\n * See https://docs.soliditylang.org/en/v0.8.20/internals/layout_in_storage.html#mappings-and-dynamic-arrays[Solidity docs for mappings and dynamic arrays.].\n *\n * Example usage:\n * ```solidity\n * contract Example {\n *     // Add the library methods\n *     using StorageSlot for bytes32;\n *     using SlotDerivation for *;\n *\n *     // Declare a namespace\n *     string private constant _NAMESPACE = \"<namespace>\"; // eg. OpenZeppelin.Slot\n *\n *     function setValueInNamespace(uint256 key, address newValue) internal {\n *         _NAMESPACE.erc7201Slot().deriveMapping(key).getAddressSlot().value = newValue;\n *     }\n *\n *     function getValueInNamespace(uint256 key) internal view returns (address) {\n *         return _NAMESPACE.erc7201Slot().deriveMapping(key).getAddressSlot().value;\n *     }\n * }\n * ```\n *\n * TIP: Consider using this library along with {StorageSlot}.\n *\n * NOTE: This library provides a way to manipulate storage locations in a non-standard way. Tooling for checking\n * upgrade safety will ignore the slots accessed through this library.\n *\n * _Available since v5.1._\n */\nlibrary SlotDerivation {\n    /**\n     * @dev Derive an ERC-7201 slot from a string (namespace).\n     */\n    function erc7201Slot(string memory namespace) internal pure returns (bytes32 slot) {\n        assembly (\"memory-safe\") {\n            mstore(0x00, sub(keccak256(add(namespace, 0x20), mload(namespace)), 1))\n            slot := and(keccak256(0x00, 0x20), not(0xff))\n        }\n    }\n\n    /**\n     * @dev Add an offset to a slot to get the n-th element of a structure or an array.\n     */\n    function offset(bytes32 slot, uint256 pos) internal pure returns (bytes32 result) {\n        unchecked {\n            return bytes32(uint256(slot) + pos);\n        }\n    }\n\n    /**\n     * @dev Derive the location of the first element in an array from the slot where the length is stored.\n     */\n    function deriveArray(bytes32 slot) internal pure returns (bytes32 result) {\n        assembly (\"memory-safe\") {\n            mstore(0x00, slot)\n            result := keccak256(0x00, 0x20)\n        }\n    }\n\n    /**\n     * @dev Derive the location of a mapping element from the key.\n     */\n    function deriveMapping(bytes32 slot, address key) internal pure returns (bytes32 result) {\n        assembly (\"memory-safe\") {\n            mstore(0x00, and(key, shr(96, not(0))))\n            mstore(0x20, slot)\n            result := keccak256(0x00, 0x40)\n        }\n    }\n\n    /**\n     * @dev Derive the location of a mapping element from the key.\n     */\n    function deriveMapping(bytes32 slot, bool key) internal pure returns (bytes32 result) {\n        assembly (\"memory-safe\") {\n            mstore(0x00, iszero(iszero(key)))\n            mstore(0x20, slot)\n            result := keccak256(0x00, 0x40)\n        }\n    }\n\n    /**\n     * @dev Derive the location of a mapping element from the key.\n     */\n    function deriveMapping(bytes32 slot, bytes32 key) internal pure returns (bytes32 result) {\n        assembly (\"memory-safe\") {\n            mstore(0x00, key)\n            mstore(0x20, slot)\n            result := keccak256(0x00, 0x40)\n        }\n    }\n\n    /**\n     * @dev Derive the location of a mapping element from the key.\n     */\n    function deriveMapping(bytes32 slot, uint256 key) internal pure returns (bytes32 result) {\n        assembly (\"memory-safe\") {\n            mstore(0x00, key)\n            mstore(0x20, slot)\n            result := keccak256(0x00, 0x40)\n        }\n    }\n\n    /**\n     * @dev Derive the location of a mapping element from the key.\n     */\n    function deriveMapping(bytes32 slot, int256 key) internal pure returns (bytes32 result) {\n        assembly (\"memory-safe\") {\n            mstore(0x00, key)\n            mstore(0x20, slot)\n            result := keccak256(0x00, 0x40)\n        }\n    }\n\n    /**\n     * @dev Derive the location of a mapping element from the key.\n     */\n    function deriveMapping(bytes32 slot, string memory key) internal pure returns (bytes32 result) {\n        assembly (\"memory-safe\") {\n            let length := mload(key)\n            let begin := add(key, 0x20)\n            let end := add(begin, length)\n            let cache := mload(end)\n            mstore(end, slot)\n            result := keccak256(begin, add(length, 0x20))\n            mstore(end, cache)\n        }\n    }\n\n    /**\n     * @dev Derive the location of a mapping element from the key.\n     */\n    function deriveMapping(bytes32 slot, bytes memory key) internal pure returns (bytes32 result) {\n        assembly (\"memory-safe\") {\n            let length := mload(key)\n            let begin := add(key, 0x20)\n            let end := add(begin, length)\n            let cache := mload(end)\n            mstore(end, slot)\n            result := keccak256(begin, add(length, 0x20))\n            mstore(end, cache)\n        }\n    }\n}\n"},{"file_path":"lib/openzeppelin-contracts/contracts/utils/cryptography/EIP712.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.5.0) (utils/cryptography/EIP712.sol)\n\npragma solidity ^0.8.24;\n\nimport {MessageHashUtils} from \"./MessageHashUtils.sol\";\nimport {ShortStrings, ShortString} from \"../ShortStrings.sol\";\nimport {IERC5267} from \"../../interfaces/IERC5267.sol\";\n\n/**\n * @dev https://eips.ethereum.org/EIPS/eip-712[EIP-712] is a standard for hashing and signing of typed structured data.\n *\n * The encoding scheme specified in the EIP requires a domain separator and a hash of the typed structured data, whose\n * encoding is very generic and therefore its implementation in Solidity is not feasible, thus this contract\n * does not implement the encoding itself. Protocols need to implement the type-specific encoding they need in order to\n * produce the hash of their typed data using a combination of `abi.encode` and `keccak256`.\n *\n * This contract implements the EIP-712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding\n * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA\n * ({_hashTypedDataV4}).\n *\n * The implementation of the domain separator was designed to be as efficient as possible while still properly updating\n * the chain id to protect against replay attacks on an eventual fork of the chain.\n *\n * NOTE: This contract implements the version of the encoding known as \"v4\", as implemented by the JSON RPC method\n * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].\n *\n * NOTE: In the upgradeable version of this contract, the cached values will correspond to the address, and the domain\n * separator of the implementation contract. This will cause the {_domainSeparatorV4} function to always rebuild the\n * separator from the immutable values, which is cheaper than accessing a cached version in cold storage.\n *\n * @custom:oz-upgrades-unsafe-allow state-variable-immutable\n */\nabstract contract EIP712 is IERC5267 {\n    using ShortStrings for *;\n\n    bytes32 private constant TYPE_HASH =\n        keccak256(\"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)\");\n\n    // Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to\n    // invalidate the cached domain separator if the chain id changes.\n    bytes32 private immutable _cachedDomainSeparator;\n    uint256 private immutable _cachedChainId;\n    address private immutable _cachedThis;\n\n    bytes32 private immutable _hashedName;\n    bytes32 private immutable _hashedVersion;\n\n    ShortString private immutable _name;\n    ShortString private immutable _version;\n    // slither-disable-next-line constable-states\n    string private _nameFallback;\n    // slither-disable-next-line constable-states\n    string private _versionFallback;\n\n    /**\n     * @dev Initializes the domain separator and parameter caches.\n     *\n     * The meaning of `name` and `version` is specified in\n     * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP-712]:\n     *\n     * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.\n     * - `version`: the current major version of the signing domain.\n     *\n     * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart\n     * contract upgrade].\n     */\n    constructor(string memory name, string memory version) {\n        _name = name.toShortStringWithFallback(_nameFallback);\n        _version = version.toShortStringWithFallback(_versionFallback);\n        _hashedName = keccak256(bytes(name));\n        _hashedVersion = keccak256(bytes(version));\n\n        _cachedChainId = block.chainid;\n        _cachedDomainSeparator = _buildDomainSeparator();\n        _cachedThis = address(this);\n    }\n\n    /**\n     * @dev Returns the domain separator for the current chain.\n     */\n    function _domainSeparatorV4() internal view returns (bytes32) {\n        if (address(this) == _cachedThis && block.chainid == _cachedChainId) {\n            return _cachedDomainSeparator;\n        } else {\n            return _buildDomainSeparator();\n        }\n    }\n\n    function _buildDomainSeparator() private view returns (bytes32) {\n        return keccak256(abi.encode(TYPE_HASH, _hashedName, _hashedVersion, block.chainid, address(this)));\n    }\n\n    /**\n     * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this\n     * function returns the hash of the fully encoded EIP712 message for this domain.\n     *\n     * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:\n     *\n     * ```solidity\n     * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(\n     *     keccak256(\"Mail(address to,string contents)\"),\n     *     mailTo,\n     *     keccak256(bytes(mailContents))\n     * )));\n     * address signer = ECDSA.recover(digest, signature);\n     * ```\n     */\n    function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {\n        return MessageHashUtils.toTypedDataHash(_domainSeparatorV4(), structHash);\n    }\n\n    /// @inheritdoc IERC5267\n    function eip712Domain()\n        public\n        view\n        virtual\n        returns (\n            bytes1 fields,\n            string memory name,\n            string memory version,\n            uint256 chainId,\n            address verifyingContract,\n            bytes32 salt,\n            uint256[] memory extensions\n        )\n    {\n        return (\n            hex\"0f\", // 01111\n            _EIP712Name(),\n            _EIP712Version(),\n            block.chainid,\n            address(this),\n            bytes32(0),\n            new uint256[](0)\n        );\n    }\n\n    /**\n     * @dev The name parameter for the EIP712 domain.\n     *\n     * NOTE: By default this function reads _name which is an immutable value.\n     * It only reads from storage if necessary (in case the value is too large to fit in a ShortString).\n     */\n    // solhint-disable-next-line func-name-mixedcase\n    function _EIP712Name() internal view returns (string memory) {\n        return _name.toStringWithFallback(_nameFallback);\n    }\n\n    /**\n     * @dev The version parameter for the EIP712 domain.\n     *\n     * NOTE: By default this function reads _version which is an immutable value.\n     * It only reads from storage if necessary (in case the value is too large to fit in a ShortString).\n     */\n    // solhint-disable-next-line func-name-mixedcase\n    function _EIP712Version() internal view returns (string memory) {\n        return _version.toStringWithFallback(_versionFallback);\n    }\n}\n"},{"file_path":"lib/openzeppelin-contracts/contracts/utils/introspection/ERC165.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/ERC165.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC165} from \"./IERC165.sol\";\n\n/**\n * @dev Implementation of the {IERC165} interface.\n *\n * Contracts that want to implement ERC-165 should inherit from this contract and override {supportsInterface} to check\n * for the additional interface id that will be supported. For example:\n *\n * ```solidity\n * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n *     return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);\n * }\n * ```\n */\nabstract contract ERC165 is IERC165 {\n    /// @inheritdoc IERC165\n    function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {\n        return interfaceId == type(IERC165).interfaceId;\n    }\n}\n"},{"file_path":"lib/openzeppelin-contracts/contracts/interfaces/draft-IERC6093.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.5.0) (interfaces/draft-IERC6093.sol)\n\npragma solidity >=0.8.4;\n\n/**\n * @dev Standard ERC-20 Errors\n * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-20 tokens.\n */\ninterface IERC20Errors {\n    /**\n     * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.\n     * @param sender Address whose tokens are being transferred.\n     * @param balance Current balance for the interacting account.\n     * @param needed Minimum amount required to perform a transfer.\n     */\n    error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);\n\n    /**\n     * @dev Indicates a failure with the token `sender`. Used in transfers.\n     * @param sender Address whose tokens are being transferred.\n     */\n    error ERC20InvalidSender(address sender);\n\n    /**\n     * @dev Indicates a failure with the token `receiver`. Used in transfers.\n     * @param receiver Address to which tokens are being transferred.\n     */\n    error ERC20InvalidReceiver(address receiver);\n\n    /**\n     * @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers.\n     * @param spender Address that may be allowed to operate on tokens without being their owner.\n     * @param allowance Amount of tokens a `spender` is allowed to operate with.\n     * @param needed Minimum amount required to perform a transfer.\n     */\n    error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed);\n\n    /**\n     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.\n     * @param approver Address initiating an approval operation.\n     */\n    error ERC20InvalidApprover(address approver);\n\n    /**\n     * @dev Indicates a failure with the `spender` to be approved. Used in approvals.\n     * @param spender Address that may be allowed to operate on tokens without being their owner.\n     */\n    error ERC20InvalidSpender(address spender);\n}\n\n/**\n * @dev Standard ERC-721 Errors\n * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-721 tokens.\n */\ninterface IERC721Errors {\n    /**\n     * @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in ERC-721.\n     * Used in balance queries.\n     * @param owner Address of the current owner of a token.\n     */\n    error ERC721InvalidOwner(address owner);\n\n    /**\n     * @dev Indicates a `tokenId` whose `owner` is the zero address.\n     * @param tokenId Identifier number of a token.\n     */\n    error ERC721NonexistentToken(uint256 tokenId);\n\n    /**\n     * @dev Indicates an error related to the ownership over a particular token. Used in transfers.\n     * @param sender Address whose tokens are being transferred.\n     * @param tokenId Identifier number of a token.\n     * @param owner Address of the current owner of a token.\n     */\n    error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner);\n\n    /**\n     * @dev Indicates a failure with the token `sender`. Used in transfers.\n     * @param sender Address whose tokens are being transferred.\n     */\n    error ERC721InvalidSender(address sender);\n\n    /**\n     * @dev Indicates a failure with the token `receiver`. Used in transfers.\n     * @param receiver Address to which tokens are being transferred.\n     */\n    error ERC721InvalidReceiver(address receiver);\n\n    /**\n     * @dev Indicates a failure with the `operator`’s approval. Used in transfers.\n     * @param operator Address that may be allowed to operate on tokens without being their owner.\n     * @param tokenId Identifier number of a token.\n     */\n    error ERC721InsufficientApproval(address operator, uint256 tokenId);\n\n    /**\n     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.\n     * @param approver Address initiating an approval operation.\n     */\n    error ERC721InvalidApprover(address approver);\n\n    /**\n     * @dev Indicates a failure with the `operator` to be approved. Used in approvals.\n     * @param operator Address that may be allowed to operate on tokens without being their owner.\n     */\n    error ERC721InvalidOperator(address operator);\n}\n\n/**\n * @dev Standard ERC-1155 Errors\n * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-1155 tokens.\n */\ninterface IERC1155Errors {\n    /**\n     * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.\n     * @param sender Address whose tokens are being transferred.\n     * @param balance Current balance for the interacting account.\n     * @param needed Minimum amount required to perform a transfer.\n     * @param tokenId Identifier number of a token.\n     */\n    error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId);\n\n    /**\n     * @dev Indicates a failure with the token `sender`. Used in transfers.\n     * @param sender Address whose tokens are being transferred.\n     */\n    error ERC1155InvalidSender(address sender);\n\n    /**\n     * @dev Indicates a failure with the token `receiver`. Used in transfers.\n     * @param receiver Address to which tokens are being transferred.\n     */\n    error ERC1155InvalidReceiver(address receiver);\n\n    /**\n     * @dev Indicates a failure with the `operator`’s approval. Used in transfers.\n     * @param operator Address that may be allowed to operate on tokens without being their owner.\n     * @param owner Address of the current owner of a token.\n     */\n    error ERC1155MissingApprovalForAll(address operator, address owner);\n\n    /**\n     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.\n     * @param approver Address initiating an approval operation.\n     */\n    error ERC1155InvalidApprover(address approver);\n\n    /**\n     * @dev Indicates a failure with the `operator` to be approved. Used in approvals.\n     * @param operator Address that may be allowed to operate on tokens without being their owner.\n     */\n    error ERC1155InvalidOperator(address operator);\n\n    /**\n     * @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation.\n     * Used in batch transfers.\n     * @param idsLength Length of the array of token identifiers\n     * @param valuesLength Length of the array of token amounts\n     */\n    error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength);\n}\n"},{"file_path":"lib/openzeppelin-contracts/contracts/utils/LowLevelCall.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.5.0) (utils/LowLevelCall.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Library of low level call functions that implement different calling strategies to deal with the return data.\n *\n * WARNING: Using this library requires an advanced understanding of Solidity and how the EVM works. It is recommended\n * to use the {Address} library instead.\n */\nlibrary LowLevelCall {\n    /// @dev Performs a Solidity function call using a low level `call` and ignoring the return data.\n    function callNoReturn(address target, bytes memory data) internal returns (bool success) {\n        return callNoReturn(target, 0, data);\n    }\n\n    /// @dev Same as {callNoReturn-address-bytes}, but allows specifying the value to be sent in the call.\n    function callNoReturn(address target, uint256 value, bytes memory data) internal returns (bool success) {\n        assembly (\"memory-safe\") {\n            success := call(gas(), target, value, add(data, 0x20), mload(data), 0x00, 0x00)\n        }\n    }\n\n    /// @dev Performs a Solidity function call using a low level `call` and returns the first 64 bytes of the result\n    /// in the scratch space of memory. Useful for functions that return a tuple of single-word values.\n    ///\n    /// WARNING: Do not assume that the results are zero if `success` is false. Memory can be already allocated\n    /// and this function doesn't zero it out.\n    function callReturn64Bytes(\n        address target,\n        bytes memory data\n    ) internal returns (bool success, bytes32 result1, bytes32 result2) {\n        return callReturn64Bytes(target, 0, data);\n    }\n\n    /// @dev Same as {callReturn64Bytes-address-bytes}, but allows specifying the value to be sent in the call.\n    function callReturn64Bytes(\n        address target,\n        uint256 value,\n        bytes memory data\n    ) internal returns (bool success, bytes32 result1, bytes32 result2) {\n        assembly (\"memory-safe\") {\n            success := call(gas(), target, value, add(data, 0x20), mload(data), 0x00, 0x40)\n            result1 := mload(0x00)\n            result2 := mload(0x20)\n        }\n    }\n\n    /// @dev Performs a Solidity function call using a low level `staticcall` and ignoring the return data.\n    function staticcallNoReturn(address target, bytes memory data) internal view returns (bool success) {\n        assembly (\"memory-safe\") {\n            success := staticcall(gas(), target, add(data, 0x20), mload(data), 0x00, 0x00)\n        }\n    }\n\n    /// @dev Performs a Solidity function call using a low level `staticcall` and returns the first 64 bytes of the result\n    /// in the scratch space of memory. Useful for functions that return a tuple of single-word values.\n    ///\n    /// WARNING: Do not assume that the results are zero if `success` is false. Memory can be already allocated\n    /// and this function doesn't zero it out.\n    function staticcallReturn64Bytes(\n        address target,\n        bytes memory data\n    ) internal view returns (bool success, bytes32 result1, bytes32 result2) {\n        assembly (\"memory-safe\") {\n            success := staticcall(gas(), target, add(data, 0x20), mload(data), 0x00, 0x40)\n            result1 := mload(0x00)\n            result2 := mload(0x20)\n        }\n    }\n\n    /// @dev Performs a Solidity function call using a low level `delegatecall` and ignoring the return data.\n    function delegatecallNoReturn(address target, bytes memory data) internal returns (bool success) {\n        assembly (\"memory-safe\") {\n            success := delegatecall(gas(), target, add(data, 0x20), mload(data), 0x00, 0x00)\n        }\n    }\n\n    /// @dev Performs a Solidity function call using a low level `delegatecall` and returns the first 64 bytes of the result\n    /// in the scratch space of memory. Useful for functions that return a tuple of single-word values.\n    ///\n    /// WARNING: Do not assume that the results are zero if `success` is false. Memory can be already allocated\n    /// and this function doesn't zero it out.\n    function delegatecallReturn64Bytes(\n        address target,\n        bytes memory data\n    ) internal returns (bool success, bytes32 result1, bytes32 result2) {\n        assembly (\"memory-safe\") {\n            success := delegatecall(gas(), target, add(data, 0x20), mload(data), 0x00, 0x40)\n            result1 := mload(0x00)\n            result2 := mload(0x20)\n        }\n    }\n\n    /// @dev Returns the size of the return data buffer.\n    function returnDataSize() internal pure returns (uint256 size) {\n        assembly (\"memory-safe\") {\n            size := returndatasize()\n        }\n    }\n\n    /// @dev Returns a buffer containing the return data from the last call.\n    function returnData() internal pure returns (bytes memory result) {\n        assembly (\"memory-safe\") {\n            result := mload(0x40)\n            mstore(result, returndatasize())\n            returndatacopy(add(result, 0x20), 0x00, returndatasize())\n            mstore(0x40, add(result, add(0x20, returndatasize())))\n        }\n    }\n\n    /// @dev Revert with the return data from the last call.\n    function bubbleRevert() internal pure {\n        assembly (\"memory-safe\") {\n            let fmp := mload(0x40)\n            returndatacopy(fmp, 0x00, returndatasize())\n            revert(fmp, returndatasize())\n        }\n    }\n\n    function bubbleRevert(bytes memory returndata) internal pure {\n        assembly (\"memory-safe\") {\n            revert(add(returndata, 0x20), mload(returndata))\n        }\n    }\n}\n"},{"file_path":"lib/openzeppelin-contracts/contracts/utils/cryptography/MessageHashUtils.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.5.0) (utils/cryptography/MessageHashUtils.sol)\n\npragma solidity ^0.8.24;\n\nimport {Strings} from \"../Strings.sol\";\n\n/**\n * @dev Signature message hash utilities for producing digests to be consumed by {ECDSA} recovery or signing.\n *\n * The library provides methods for generating a hash of a message that conforms to the\n * https://eips.ethereum.org/EIPS/eip-191[ERC-191] and https://eips.ethereum.org/EIPS/eip-712[EIP 712]\n * specifications.\n */\nlibrary MessageHashUtils {\n    error ERC5267ExtensionsNotSupported();\n\n    /**\n     * @dev Returns the keccak256 digest of an ERC-191 signed data with version\n     * `0x45` (`personal_sign` messages).\n     *\n     * The digest is calculated by prefixing a bytes32 `messageHash` with\n     * `\"\\x19Ethereum Signed Message:\\n32\"` and hashing the result. It corresponds with the\n     * hash signed when using the https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_sign[`eth_sign`] JSON-RPC method.\n     *\n     * NOTE: The `messageHash` parameter is intended to be the result of hashing a raw message with\n     * keccak256, although any bytes32 value can be safely used because the final digest will\n     * be re-hashed.\n     *\n     * See {ECDSA-recover}.\n     */\n    function toEthSignedMessageHash(bytes32 messageHash) internal pure returns (bytes32 digest) {\n        assembly (\"memory-safe\") {\n            mstore(0x00, \"\\x19Ethereum Signed Message:\\n32\") // 32 is the bytes-length of messageHash\n            mstore(0x1c, messageHash) // 0x1c (28) is the length of the prefix\n            digest := keccak256(0x00, 0x3c) // 0x3c is the length of the prefix (0x1c) + messageHash (0x20)\n        }\n    }\n\n    /**\n     * @dev Returns the keccak256 digest of an ERC-191 signed data with version\n     * `0x45` (`personal_sign` messages).\n     *\n     * The digest is calculated by prefixing an arbitrary `message` with\n     * `\"\\x19Ethereum Signed Message:\\n\" + len(message)` and hashing the result. It corresponds with the\n     * hash signed when using the https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_sign[`eth_sign`] JSON-RPC method.\n     *\n     * See {ECDSA-recover}.\n     */\n    function toEthSignedMessageHash(bytes memory message) internal pure returns (bytes32) {\n        return\n            keccak256(bytes.concat(\"\\x19Ethereum Signed Message:\\n\", bytes(Strings.toString(message.length)), message));\n    }\n\n    /**\n     * @dev Returns the keccak256 digest of an ERC-191 signed data with version\n     * `0x00` (data with intended validator).\n     *\n     * The digest is calculated by prefixing an arbitrary `data` with `\"\\x19\\x00\"` and the intended\n     * `validator` address. Then hashing the result.\n     *\n     * See {ECDSA-recover}.\n     */\n    function toDataWithIntendedValidatorHash(address validator, bytes memory data) internal pure returns (bytes32) {\n        return keccak256(abi.encodePacked(hex\"19_00\", validator, data));\n    }\n\n    /**\n     * @dev Variant of {toDataWithIntendedValidatorHash-address-bytes} optimized for cases where `data` is a bytes32.\n     */\n    function toDataWithIntendedValidatorHash(\n        address validator,\n        bytes32 messageHash\n    ) internal pure returns (bytes32 digest) {\n        assembly (\"memory-safe\") {\n            mstore(0x00, hex\"19_00\")\n            mstore(0x02, shl(96, validator))\n            mstore(0x16, messageHash)\n            digest := keccak256(0x00, 0x36)\n        }\n    }\n\n    /**\n     * @dev Returns the keccak256 digest of an EIP-712 typed data (ERC-191 version `0x01`).\n     *\n     * The digest is calculated from a `domainSeparator` and a `structHash`, by prefixing them with\n     * `\\x19\\x01` and hashing the result. It corresponds to the hash signed by the\n     * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] JSON-RPC method as part of EIP-712.\n     *\n     * See {ECDSA-recover}.\n     */\n    function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32 digest) {\n        assembly (\"memory-safe\") {\n            let ptr := mload(0x40)\n            mstore(ptr, hex\"19_01\")\n            mstore(add(ptr, 0x02), domainSeparator)\n            mstore(add(ptr, 0x22), structHash)\n            digest := keccak256(ptr, 0x42)\n        }\n    }\n\n    /**\n     * @dev Returns the EIP-712 domain separator constructed from an `eip712Domain`. See {IERC5267-eip712Domain}\n     *\n     * This function dynamically constructs the domain separator based on which fields are present in the\n     * `fields` parameter. It contains flags that indicate which domain fields are present:\n     *\n     * * Bit 0 (0x01): name\n     * * Bit 1 (0x02): version\n     * * Bit 2 (0x04): chainId\n     * * Bit 3 (0x08): verifyingContract\n     * * Bit 4 (0x10): salt\n     *\n     * Arguments that correspond to fields which are not present in `fields` are ignored. For example, if `fields` is\n     * `0x0f` (`0b01111`), then the `salt` parameter is ignored.\n     */\n    function toDomainSeparator(\n        bytes1 fields,\n        string memory name,\n        string memory version,\n        uint256 chainId,\n        address verifyingContract,\n        bytes32 salt\n    ) internal pure returns (bytes32 hash) {\n        return\n            toDomainSeparator(\n                fields,\n                keccak256(bytes(name)),\n                keccak256(bytes(version)),\n                chainId,\n                verifyingContract,\n                salt\n            );\n    }\n\n    /// @dev Variant of {toDomainSeparator-bytes1-string-string-uint256-address-bytes32} that uses hashed name and version.\n    function toDomainSeparator(\n        bytes1 fields,\n        bytes32 nameHash,\n        bytes32 versionHash,\n        uint256 chainId,\n        address verifyingContract,\n        bytes32 salt\n    ) internal pure returns (bytes32 hash) {\n        bytes32 domainTypeHash = toDomainTypeHash(fields);\n\n        assembly (\"memory-safe\") {\n            // align fields to the right for easy processing\n            fields := shr(248, fields)\n\n            // FMP used as scratch space\n            let fmp := mload(0x40)\n            mstore(fmp, domainTypeHash)\n\n            let ptr := add(fmp, 0x20)\n            if and(fields, 0x01) {\n                mstore(ptr, nameHash)\n                ptr := add(ptr, 0x20)\n            }\n            if and(fields, 0x02) {\n                mstore(ptr, versionHash)\n                ptr := add(ptr, 0x20)\n            }\n            if and(fields, 0x04) {\n                mstore(ptr, chainId)\n                ptr := add(ptr, 0x20)\n            }\n            if and(fields, 0x08) {\n                mstore(ptr, verifyingContract)\n                ptr := add(ptr, 0x20)\n            }\n            if and(fields, 0x10) {\n                mstore(ptr, salt)\n                ptr := add(ptr, 0x20)\n            }\n\n            hash := keccak256(fmp, sub(ptr, fmp))\n        }\n    }\n\n    /// @dev Builds an EIP-712 domain type hash depending on the `fields` provided, following https://eips.ethereum.org/EIPS/eip-5267[ERC-5267]\n    function toDomainTypeHash(bytes1 fields) internal pure returns (bytes32 hash) {\n        if (fields & 0x20 == 0x20) revert ERC5267ExtensionsNotSupported();\n\n        assembly (\"memory-safe\") {\n            // align fields to the right for easy processing\n            fields := shr(248, fields)\n\n            // FMP used as scratch space\n            let fmp := mload(0x40)\n            mstore(fmp, \"EIP712Domain(\")\n\n            let ptr := add(fmp, 0x0d)\n            // name field\n            if and(fields, 0x01) {\n                mstore(ptr, \"string name,\")\n                ptr := add(ptr, 0x0c)\n            }\n            // version field\n            if and(fields, 0x02) {\n                mstore(ptr, \"string version,\")\n                ptr := add(ptr, 0x0f)\n            }\n            // chainId field\n            if and(fields, 0x04) {\n                mstore(ptr, \"uint256 chainId,\")\n                ptr := add(ptr, 0x10)\n            }\n            // verifyingContract field\n            if and(fields, 0x08) {\n                mstore(ptr, \"address verifyingContract,\")\n                ptr := add(ptr, 0x1a)\n            }\n            // salt field\n            if and(fields, 0x10) {\n                mstore(ptr, \"bytes32 salt,\")\n                ptr := add(ptr, 0x0d)\n            }\n            // if any field is enabled, remove the trailing comma\n            ptr := sub(ptr, iszero(iszero(and(fields, 0x1f))))\n            // add the closing brace\n            mstore8(ptr, 0x29) // add closing brace\n            ptr := add(ptr, 1)\n\n            hash := keccak256(fmp, sub(ptr, fmp))\n        }\n    }\n}\n"},{"file_path":"src/locking/UnwindingModule.sol","source_code":"// SPDX-License-Identifier: MIT\npragma solidity 0.8.28;\n\nimport {IERC20} from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport {ERC20Burnable} from \"@openzeppelin/contracts/token/ERC20/extensions/ERC20Burnable.sol\";\nimport {FixedPointMathLib} from \"@solmate/src/utils/FixedPointMathLib.sol\";\n\nimport {EpochLib} from \"@libraries/EpochLib.sol\";\nimport {CoreRoles} from \"@libraries/CoreRoles.sol\";\nimport {CoreControlled} from \"@core/CoreControlled.sol\";\nimport {LockingController} from \"@locking/LockingController.sol\";\n\nstruct UnwindingPosition {\n    uint256 shares; // shares of receiptTokens of the position\n    uint32 fromEpoch; // epoch when the position started unwinding\n    uint32 toEpoch; // epoch when the position will end unwinding\n    uint256 fromRewardWeight; // reward weight at the start of the unwinding\n    uint256 rewardWeightDecrease; // reward weight decrease per epoch between fromEpoch and toEpoch\n}\n\nstruct GlobalPoint {\n    uint32 epoch; // epoch of the global point\n    uint256 totalRewardWeight; // total reward weight in the contract\n    uint256 totalRewardWeightDecrease; // total reward weight decrease per epoch\n    uint256 rewardShares; // number of receiptTokens rewards distributed on the epoch (stored as shares)\n}\n\ncontract UnwindingModule is CoreControlled {\n    using EpochLib for uint256;\n    using FixedPointMathLib for uint256;\n\n    error TransferFailed();\n    error UserNotUnwinding();\n    error UserUnwindingNotStarted();\n    error UserUnwindingInprogress();\n    error InvalidUnwindingEpochs(uint32 value);\n\n    event UnwindingStarted(\n        uint256 indexed timestamp, address user, uint256 receiptTokens, uint32 unwindingEpochs, uint256 rewardWeight\n    );\n    event UnwindingCanceled(\n        uint256 indexed timestamp, address user, uint256 startUnwindingTimestamp, uint32 newUnwindingEpochs\n    );\n    event Withdrawal(uint256 indexed timestamp, uint256 startUnwindingTimestamp, address user);\n    event GlobalPointUpdated(uint256 indexed timestamp, GlobalPoint);\n    event CriticalLoss(uint256 indexed timestamp, uint256 amount);\n\n    /// @notice address of the receipt token\n    address public immutable receiptToken;\n\n    /// ----------------------------------------------------------------------------\n    /// STATE\n    /// ----------------------------------------------------------------------------\n\n    /// @notice total shares of locked tokens in the contract\n    uint256 public totalShares;\n\n    /// @notice total amount of receipt tokens in the contract, excluding donations\n    uint256 public totalReceiptTokens;\n\n    /// @notice slashing index, starts at 1e18 and decreases every time there is a slash\n    uint256 public slashIndex = FixedPointMathLib.WAD;\n\n    /// @notice mapping of unwinding positions\n    mapping(bytes32 id => UnwindingPosition position) public positions;\n\n    /// @notice last global point's epoch for direct access\n    uint32 public lastGlobalPointEpoch;\n\n    /// @notice mapping of epoch to global point\n    mapping(uint32 epoch => GlobalPoint point) public globalPoints;\n\n    /// @notice mapping of epoch to positive bias changes\n    mapping(uint32 epoch => uint256 increase) public rewardWeightBiasIncreases;\n\n    /// @notice mapping of epoch to positive slope changes\n    mapping(uint32 epoch => uint256 increase) public rewardWeightIncreases;\n\n    /// @notice mapping of epoch to negative slope changes\n    mapping(uint32 epoch => uint256 decrease) public rewardWeightDecreases;\n\n    /// ----------------------------------------------------------------------------\n    /// CONSTRUCTOR\n    /// ----------------------------------------------------------------------------\n\n    constructor(address _core, address _receiptToken) CoreControlled(_core) {\n        receiptToken = _receiptToken;\n\n        uint32 currentEpoch = uint32(block.timestamp.epoch());\n        lastGlobalPointEpoch = currentEpoch;\n        globalPoints[currentEpoch] =\n            GlobalPoint({epoch: currentEpoch, totalRewardWeight: 0, totalRewardWeightDecrease: 0, rewardShares: 0});\n    }\n\n    /// ----------------------------------------------------------------------------\n    /// READ METHODS\n    /// ----------------------------------------------------------------------------\n\n    /// @notice returns the current reward weight\n    function totalRewardWeight() external view returns (uint256) {\n        GlobalPoint memory point = _getLastGlobalPoint();\n        return point.totalRewardWeight.mulWadUp(slashIndex);\n    }\n\n    /// @notice returns the balance of a user\n    function balanceOf(address _user, uint256 _startUnwindingTimestamp) external view returns (uint256) {\n        return _sharesToAmount(_userShares(_user, _startUnwindingTimestamp));\n    }\n\n    /// @notice returns number of share of a user\n    function _userShares(address _user, uint256 _startUnwindingTimestamp) internal view returns (uint256) {\n        UnwindingPosition memory position = positions[_unwindingId(_user, _startUnwindingTimestamp)];\n        if (position.fromEpoch == 0) return 0;\n\n        // apply rewards\n        GlobalPoint memory globalPoint;\n        uint256 userRewardWeight = position.fromRewardWeight;\n        uint256 userShares = position.shares;\n        uint256 currentEpoch = block.timestamp.epoch();\n        for (uint32 epoch = position.fromEpoch - 1; epoch <= currentEpoch; epoch++) {\n            // if a real global point exists, use it\n            // there is always a real global point for the position.fromEpoch,\n            // because a global point is saved to storage when a position starts unwinding.\n            GlobalPoint memory epochGlobalPoint = globalPoints[epoch];\n            if (epochGlobalPoint.epoch != 0) globalPoint = epochGlobalPoint;\n\n            // add shares to the user for their earned rewards\n            // note that the userRewardWeight is not increased proportionally to the rewards\n            // received, which means that rewards are not compounding during unwinding.\n            if (epoch >= position.fromEpoch) {\n                // do not distribute rewards at the epoch where the user started unwinding,\n                // because the global reward weight is not updated yet and the user should not\n                // earn rewards before the start of their unwinding period (and the start of their\n                // unwinding is the next epoch after they called startUnwinding).\n                userShares += globalPoint.rewardShares.mulDivDown(userRewardWeight, globalPoint.totalRewardWeight);\n            }\n\n            // prepare a virtual global point for the next iteration\n            // slope changes\n            globalPoint.totalRewardWeightDecrease -= rewardWeightIncreases[epoch];\n            globalPoint.totalRewardWeightDecrease += rewardWeightDecreases[epoch];\n            // bias changes\n            globalPoint.totalRewardWeight += rewardWeightBiasIncreases[epoch];\n            // apply slope changes\n            globalPoint.totalRewardWeight -= globalPoint.totalRewardWeightDecrease;\n            // update epoch\n            globalPoint.epoch = epoch + 1;\n            // reset rewards\n            globalPoint.rewardShares = 0;\n\n            // if during the position's unwinding period, the reward weight should decrease\n            if (epoch >= position.fromEpoch && epoch < position.toEpoch) {\n                userRewardWeight -= position.rewardWeightDecrease;\n            }\n        }\n\n        return userShares;\n    }\n\n    /// @notice returns the reward weight of a user\n    function rewardWeight(address _user, uint256 _startUnwindingTimestamp) public view returns (uint256) {\n        UnwindingPosition memory position = positions[_unwindingId(_user, _startUnwindingTimestamp)];\n        if (position.fromEpoch == 0) return 0;\n\n        uint256 userRewardWeight = position.fromRewardWeight;\n        uint256 currentEpoch = block.timestamp.epoch();\n        if (currentEpoch < position.fromEpoch) return 0;\n        for (uint32 epoch = position.fromEpoch + 1; epoch <= currentEpoch && epoch <= position.toEpoch; epoch++) {\n            userRewardWeight -= position.rewardWeightDecrease;\n        }\n\n        return userRewardWeight.mulWadDown(slashIndex);\n    }\n\n    /// ----------------------------------------------------------------------------\n    /// WRITE METHODS\n    /// ----------------------------------------------------------------------------\n\n    /// @notice Start unwinding a locked position\n    function startUnwinding(address _user, uint256 _receiptTokens, uint32 _unwindingEpochs, uint256 _rewardWeight)\n        external\n        onlyCoreRole(CoreRoles.LOCKED_TOKEN_MANAGER)\n    {\n        bytes32 id = _unwindingId(_user, block.timestamp);\n        require(positions[id].fromEpoch == 0, UserUnwindingInprogress());\n\n        uint256 userRewardWeight = _rewardWeight.divWadDown(slashIndex);\n        uint256 targetRewardWeight = _receiptTokens.divWadDown(slashIndex);\n        uint256 totalDecrease = userRewardWeight - targetRewardWeight;\n        uint256 rewardWeightDecrease = totalDecrease / uint256(_unwindingEpochs);\n        uint256 roundingLoss = totalDecrease - (rewardWeightDecrease * uint256(_unwindingEpochs));\n        userRewardWeight -= roundingLoss;\n\n        uint32 nextEpoch = uint32(block.timestamp.nextEpoch());\n        uint32 endEpoch = nextEpoch + _unwindingEpochs;\n        {\n            uint256 newShares = _amountToShares(_receiptTokens);\n            positions[id] = UnwindingPosition({\n                shares: newShares,\n                fromEpoch: nextEpoch,\n                toEpoch: endEpoch,\n                fromRewardWeight: userRewardWeight,\n                rewardWeightDecrease: rewardWeightDecrease\n            });\n            totalShares += newShares;\n        }\n        totalReceiptTokens += _receiptTokens;\n\n        GlobalPoint memory point = _getLastGlobalPoint();\n        _updateGlobalPoint(point);\n        rewardWeightBiasIncreases[uint32(block.timestamp.epoch())] += userRewardWeight;\n        rewardWeightDecreases[nextEpoch] += rewardWeightDecrease;\n        rewardWeightIncreases[endEpoch] += rewardWeightDecrease;\n        emit UnwindingStarted(block.timestamp, _user, _receiptTokens, _unwindingEpochs, userRewardWeight);\n    }\n\n    /// @notice Cancel an ongoing unwinding\n    function cancelUnwinding(address _user, uint256 _startUnwindingTimestamp, uint32 _newUnwindingEpochs)\n        external\n        onlyCoreRole(CoreRoles.LOCKED_TOKEN_MANAGER)\n    {\n        uint32 currentEpoch = uint32(block.timestamp.epoch());\n        bytes32 id = _unwindingId(_user, _startUnwindingTimestamp);\n        UnwindingPosition memory position = positions[id];\n        require(position.toEpoch > 0 && currentEpoch < position.toEpoch, UserNotUnwinding());\n        require(currentEpoch >= position.fromEpoch, UserUnwindingNotStarted());\n\n        uint256 userShares = _userShares(_user, _startUnwindingTimestamp);\n        uint256 userBalance = _sharesToAmount(userShares);\n        uint256 elapsedEpochs = currentEpoch - position.fromEpoch;\n        uint256 userRewardWeight = position.fromRewardWeight - elapsedEpochs * position.rewardWeightDecrease;\n\n        {\n            // scope some state writing to avoid stack too deep\n            GlobalPoint memory point = _getLastGlobalPoint();\n            if (currentEpoch == position.fromEpoch) {\n                // if cancelling unwinding on the first epoch, the reward weight has not started\n                // decreasing yet, so we do not need to update the global point's slope\n                // instead, we cancel the slope change that will happen in the next epoch\n                rewardWeightDecreases[currentEpoch] -= position.rewardWeightDecrease;\n            } else {\n                // if cancelling unwinding after the first epoch, we correct the global point's slope\n                point.totalRewardWeightDecrease -= position.rewardWeightDecrease;\n            }\n            uint256 rewardSharesToDecrement = point.rewardShares.mulDivDown(userRewardWeight, point.totalRewardWeight);\n            point.rewardShares -= rewardSharesToDecrement;\n            point.totalRewardWeight -= userRewardWeight;\n            _updateGlobalPoint(point);\n            // cancel slope change that would have happened at the end of unwinding\n            rewardWeightIncreases[position.toEpoch] -= position.rewardWeightDecrease;\n\n            delete positions[id];\n\n            totalShares -= userShares;\n            totalReceiptTokens -= userBalance;\n        }\n\n        uint32 remainingEpochs = position.toEpoch - currentEpoch;\n        require(_newUnwindingEpochs >= remainingEpochs, InvalidUnwindingEpochs(_newUnwindingEpochs));\n        IERC20(receiptToken).approve(msg.sender, userBalance);\n        LockingController(msg.sender).createPosition(userBalance, _newUnwindingEpochs, _user);\n        emit UnwindingCanceled(block.timestamp, _user, _startUnwindingTimestamp, _newUnwindingEpochs);\n    }\n\n    /// @notice Withdraw after an unwinding period has completed\n    function withdraw(uint256 _startUnwindingTimestamp, address _owner)\n        external\n        onlyCoreRole(CoreRoles.LOCKED_TOKEN_MANAGER)\n    {\n        uint32 currentEpoch = uint32(block.timestamp.epoch());\n        bytes32 id = _unwindingId(_owner, _startUnwindingTimestamp);\n        UnwindingPosition memory position = positions[id];\n        require(position.toEpoch > 0, UserNotUnwinding());\n        require(currentEpoch >= position.toEpoch, UserUnwindingInprogress());\n\n        uint256 userShares = _userShares(_owner, _startUnwindingTimestamp);\n        uint256 userBalance = _sharesToAmount(userShares);\n        uint256 userRewardWeight =\n            position.fromRewardWeight - (position.toEpoch - position.fromEpoch) * position.rewardWeightDecrease;\n        delete positions[id];\n\n        GlobalPoint memory point = _getLastGlobalPoint();\n        uint256 rewardSharesToDecrement = point.rewardShares.mulDivDown(userRewardWeight, point.totalRewardWeight);\n        point.rewardShares -= rewardSharesToDecrement;\n        point.totalRewardWeight -= userRewardWeight;\n        _updateGlobalPoint(point);\n\n        totalShares -= userShares;\n        totalReceiptTokens -= userBalance;\n\n        require(IERC20(receiptToken).transfer(_owner, userBalance), TransferFailed());\n        emit Withdrawal(block.timestamp, _startUnwindingTimestamp, _owner);\n    }\n\n    /// ----------------------------------------------------------------------------\n    /// INTERNAL UTILS\n    /// ----------------------------------------------------------------------------\n\n    function _unwindingId(address _user, uint256 _blockTimestamp) internal pure returns (bytes32) {\n        return keccak256(abi.encode(_user, _blockTimestamp));\n    }\n\n    function _amountToShares(uint256 _amount) internal view returns (uint256) {\n        uint256 _totalReceiptTokens = totalReceiptTokens;\n        return _totalReceiptTokens == 0 ? _amount : _amount.mulDivDown(totalShares, _totalReceiptTokens);\n    }\n\n    function _sharesToAmount(uint256 _shares) internal view returns (uint256) {\n        if (_shares == 0) return 0;\n        return _shares.mulDivDown(totalReceiptTokens, totalShares);\n    }\n\n    function _getLastGlobalPoint() internal view returns (GlobalPoint memory) {\n        GlobalPoint memory point = globalPoints[lastGlobalPointEpoch];\n        uint32 currentEpoch = uint32(block.timestamp.epoch());\n\n        // apply slope & bias changes if the current point\n        // must be extrapolated from a past global point\n        for (uint32 epoch = point.epoch; epoch < currentEpoch; epoch++) {\n            point.totalRewardWeightDecrease -= rewardWeightIncreases[epoch];\n            point.totalRewardWeightDecrease += rewardWeightDecreases[epoch];\n            point.totalRewardWeight += rewardWeightBiasIncreases[epoch];\n            point.totalRewardWeight -= point.totalRewardWeightDecrease;\n            point.epoch = epoch + 1;\n            point.rewardShares = 0;\n        }\n        return point;\n    }\n\n    function _updateGlobalPoint(GlobalPoint memory point) internal {\n        globalPoints[point.epoch] = point;\n        lastGlobalPointEpoch = point.epoch;\n        emit GlobalPointUpdated(block.timestamp, point);\n    }\n\n    /// ----------------------------------------------------------------------------\n    /// REWARDS MANAGEMENT WRITE METHODS\n    /// ----------------------------------------------------------------------------\n\n    function depositRewards(uint256 _amount) external onlyCoreRole(CoreRoles.LOCKED_TOKEN_MANAGER) {\n        if (_amount == 0) return;\n\n        GlobalPoint memory point = _getLastGlobalPoint();\n        uint256 rewardShares = _amountToShares(_amount);\n        point.rewardShares += rewardShares;\n        _updateGlobalPoint(point);\n\n        totalShares += rewardShares;\n        totalReceiptTokens += _amount;\n    }\n\n    function applyLosses(uint256 _amount) external onlyCoreRole(CoreRoles.LOCKED_TOKEN_MANAGER) {\n        if (_amount == 0) return;\n\n        // protect against underflow\n        if (_amount > totalReceiptTokens) {\n            _amount = totalReceiptTokens;\n            emit CriticalLoss(block.timestamp, _amount);\n        }\n\n        uint256 _totalReceiptTokens = totalReceiptTokens;\n\n        ERC20Burnable(receiptToken).burn(_amount);\n\n        slashIndex = slashIndex.mulDivDown(_totalReceiptTokens - _amount, _totalReceiptTokens);\n\n        totalReceiptTokens = _totalReceiptTokens - _amount;\n    }\n}\n"}],"is_verified_via_sourcify":false,"can_be_visualized_via_sol2uml":true,"evm_version":"cancun","language":"solidity","is_verified_via_eth_bytecode_db":true,"is_fully_verified":false,"license_type":"none","is_blueprint":false,"name":"YieldSharingV3","creation_bytecode":"0x60e06040524263ffffffff16608081905260a08190525f60c052600d80546001600160401b0319168217640100000000909202919091179055600e80546001600160d01b03191690553480156052575f5ffd5b505f8054610100600160a81b031916610100179055612f09806100745f395ff3fe608060405260043610610207575f3560e01c806385e3e8de11610113578063ec78e8321161009d578063f6339d891161006d578063f6339d89146105cd578063f843336c14610626578063f8ba4cff1461063a578063fea5657c1461064e578063ffaeac0014610662575f5ffd5b8063ec78e83214610559578063ed27f7c914610578578063efa72e9d14610597578063f2f4eb26146105ac575f5ffd5b8063bdca9165116100e3578063bdca9165146104ca578063be6972ac146104e5578063cc2a9a5b146104fc578063cc7a262e1461051b578063e2fdcc171461053a575f5ffd5b806385e3e8de1461045857806387788782146104775780639624e83e1461048c578063aee459dd146104ab575f5ffd5b80632f1183d8116101945780635c975abb116101645780635c975abb146103c45780637df3927e146103e657806380009630146104065780638456cb5914610425578063845ce76814610439575f5ffd5b80632f1183d81461035e5780633eb901a61461037d5780633f4ba83a1461039c57806344c63eec146103b0575f5ffd5b80631d6e11f2116101da5780631d6e11f2146102a95780631f91fa03146102bd57806325fc3ebe146102d25780632ba9fcd5146102e75780632e6cfc9314610349575f5ffd5b8063034172871461020b578063047050e81461022c57806312d9bdab1461025357806314ffc7931461028a575b5f5ffd5b348015610216575f5ffd5b5061022a610225366004612ab1565b610681565b005b348015610237575f5ffd5b50610240610769565b6040519081526020015b60405180910390f35b34801561025e575f5ffd5b50600454610272906001600160a01b031681565b6040516001600160a01b03909116815260200161024a565b348015610295575f5ffd5b5061022a6102a4366004612ae7565b610799565b3480156102b4575f5ffd5b5061022a6109e9565b3480156102c8575f5ffd5b5061024060055481565b3480156102dd575f5ffd5b5061024060095481565b3480156102f2575f5ffd5b50600d54600e5461031d9163ffffffff8082169264010000000090920416906001600160d01b031683565b6040805163ffffffff94851681529390921660208401526001600160d01b03169082015260600161024a565b348015610354575f5ffd5b5061024060085481565b348015610369575f5ffd5b5061022a610378366004612b02565b610a87565b348015610388575f5ffd5b5061022a610397366004612b02565b610bb1565b3480156103a7575f5ffd5b5061022a610ca5565b3480156103bb575f5ffd5b50610240610d7d565b3480156103cf575f5ffd5b505f5460ff165b604051901515815260200161024a565b6103f96103f4366004612b19565b610def565b60405161024a9190612bb8565b348015610411575f5ffd5b5061022a610420366004612ae7565b611071565b348015610430575f5ffd5b5061022a61114e565b348015610444575f5ffd5b5061022a610453366004612c1b565b611226565b348015610463575f5ffd5b5061022a610472366004612b02565b6113b1565b348015610482575f5ffd5b5061024060065481565b348015610497575f5ffd5b50600154610272906001600160a01b031681565b3480156104b6575f5ffd5b5061022a6104c5366004612b02565b6114a5565b3480156104d5575f5ffd5b506102406702c68af0bb14000081565b3480156104f0575f5ffd5b506103d660ff5f5c1681565b348015610507575f5ffd5b5061022a610516366004612c49565b611599565b348015610526575f5ffd5b50600354610272906001600160a01b031681565b348015610545575f5ffd5b50600b54610272906001600160a01b031681565b348015610564575f5ffd5b50600254610272906001600160a01b031681565b348015610583575f5ffd5b50600754610272906001600160a01b031681565b3480156105a2575f5ffd5b50610240600c5481565b3480156105b7575f5ffd5b505f5461010090046001600160a01b0316610272565b3480156105d8575f5ffd5b50600a546106009065ffffffffffff811690660100000000000090046001600160d01b031682565b6040805165ffffffffffff90931683526001600160d01b0390911660208301520161024a565b348015610631575f5ffd5b50610240611704565b348015610645575f5ffd5b5061022a611881565b348015610659575f5ffd5b50610240611961565b34801561066d575f5ffd5b5061022a61067c366004612cc7565b6119cd565b5f54604051632474521560e21b81527f276ea66e969b021a947c47a128f4d53c55387336443ef7a5391a75f0d2e48d25600482018190523360248301529161010090046001600160a01b0316906391d1485490604401602060405180830381865afa1580156106f2573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906107169190612cf1565b6107565760405162461bcd60e51b815260206004820152600c60248201526b15539055551213d49256915160a21b60448201526064015b60405180910390fd5b815f805c60ff191682151517905d505050565b5f60ff815c1661078c57604051633400dad560e11b815260040160405180910390fd5b610794611d7f565b905090565b5f54604051632474521560e21b81527f1a6838efa4183e08fe3607359d1259272af9d4716f65e1a7b5921f78fd5a3c6a600482018190523360248301529161010090046001600160a01b0316906391d1485490604401602060405180830381865afa15801561080a573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061082e9190612cf1565b6108695760405162461bcd60e51b815260206004820152600c60248201526b15539055551213d49256915160a21b604482015260640161074d565b6002546040516370a0823160e01b81526001600160a01b0384811660048301525f9216906370a0823190602401602060405180830381865afa1580156108b1573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906108d59190612d0c565b600254604051636eb1769f60e11b81526001600160a01b0386811660048301523060248301529293505f929091169063dd62ed3e90604401602060405180830381865afa158015610928573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061094c9190612d0c565b90505f82821061095c578261095e565b815b905080156109e2576002546040516323b872dd60e01b81526001600160a01b03878116600483015230602483015260448201849052909116906323b872dd906064016020604051808303815f875af11580156109bc573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906109e09190612cf1565b505b5050505050565b5f6109f2611961565b600d805467ffffffff0000000019166401000000004263ffffffff160217905590508015610a8457600b546002546003546040516303bcd7f360e11b81526001600160a01b039283166004820152908216602482015260448101849052911690630779afe6906064015f604051808303815f87803b158015610a72575f5ffd5b505af11580156109e2573d5f5f3e3d5ffd5b50565b5f54604051632474521560e21b81525f516020612eb45f395f51905f52600482018190523360248301529161010090046001600160a01b0316906391d1485490604401602060405180830381865afa158015610ae5573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610b099190612cf1565b610b445760405162461bcd60e51b815260206004820152600c60248201526b15539055551213d49256915160a21b604482015260640161074d565b81670de0b6b3a7640000811115610b715760405163e299400d60e01b815260040161074d91815260200190565b50600982905560405182815242907f02a6bcd1ae1882a47f8d6d3393d0540786d609fb8ef48ee6f069ef93777a6ebc906020015b60405180910390a25050565b5f54604051632474521560e21b81525f516020612eb45f395f51905f52600482018190523360248301529161010090046001600160a01b0316906391d1485490604401602060405180830381865afa158015610c0f573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610c339190612cf1565b610c6e5760405162461bcd60e51b815260206004820152600c60248201526b15539055551213d49256915160a21b604482015260640161074d565b600c82905560405182815242907fc2af70983f5a9782f3c9b120a93935d68085856aa4e255fb95f00e66159d2ad090602001610ba5565b5f54604051632474521560e21b81527fe7276a2a84d8de556657ec9cf93a55a7d66f096e529d0582ed08e9e2208b92b5600482018190523360248301529161010090046001600160a01b0316906391d1485490604401602060405180830381865afa158015610d16573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610d3a9190612cf1565b610d755760405162461bcd60e51b815260206004820152600c60248201526b15539055551213d49256915160a21b604482015260640161074d565b610a84611e7e565b600254600b546040516370a0823160e01b81526001600160a01b0391821660048201525f9291909116906370a0823190602401602060405180830381865afa158015610dcb573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906107949190612d0c565b5f54604051632474521560e21b81527f1a6838efa4183e08fe3607359d1259272af9d4716f65e1a7b5921f78fd5a3c6a6004820181905233602483015260609290916101009091046001600160a01b0316906391d1485490604401602060405180830381865afa158015610e65573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610e899190612cf1565b610ec45760405162461bcd60e51b815260206004820152600c60248201526b15539055551213d49256915160a21b604482015260640161074d565b8267ffffffffffffffff811115610edd57610edd612d23565b604051908082528060200260200182016040528015610f1057816020015b6060815260200190600190039081610efb5790505b5091505f5b83811015611069575f858583818110610f3057610f30612d37565b9050602002810190610f429190612d4b565b610f50906020810190612ae7565b90505f868684818110610f6557610f65612d37565b9050602002810190610f779190612d4b565b602001359050365f888886818110610f9157610f91612d37565b9050602002810190610fa39190612d4b565b610fb1906040810190612d69565b915091505f5f856001600160a01b0316858585604051610fd2929190612db3565b5f6040518083038185875af1925050503d805f811461100c576040519150601f19603f3d011682016040523d82523d5f602084013e611011565b606091505b509150915081819061103757604051634ad176bb60e01b815260040161074d9190612dc2565b508089888151811061104b5761104b612d37565b60200260200101819052505050505050508080600101915050610f15565b505092915050565b5f54604051632474521560e21b81527f1a6838efa4183e08fe3607359d1259272af9d4716f65e1a7b5921f78fd5a3c6a600482018190523360248301529161010090046001600160a01b0316906391d1485490604401602060405180830381865afa1580156110e2573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906111069190612cf1565b6111415760405162461bcd60e51b815260206004820152600c60248201526b15539055551213d49256915160a21b604482015260640161074d565b61114a82611ecf565b5050565b5f54604051632474521560e21b81527ffcb9fcbfa83b897fb2d5cf4b58962164105c1e71489a37ef3ae0db3fdce576f6600482018190523360248301529161010090046001600160a01b0316906391d1485490604401602060405180830381865afa1580156111bf573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906111e39190612cf1565b61121e5760405162461bcd60e51b815260206004820152600c60248201526b15539055551213d49256915160a21b604482015260640161074d565b610a84611f34565b5f54604051632474521560e21b81525f516020612eb45f395f51905f52600482018190523360248301529161010090046001600160a01b0316906391d1485490604401602060405180830381865afa158015611284573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906112a89190612cf1565b6112e35760405162461bcd60e51b815260206004820152600c60248201526b15539055551213d49256915160a21b604482015260640161074d565b826702c68af0bb1400008111156113105760405163b4ea6d5760e01b815260040161074d91815260200190565b50821561134d57816001600160a01b03811661134b5760405163048f87e560e31b81526001600160a01b03909116600482015260240161074d565b505b6006839055600780546001600160a01b0319166001600160a01b03841690811790915560408051858152602081019290925242917fc60b1772d13a32078285a149ad1f03b32a1f6df54245b584a8531d6f87f9e9f4910160405180910390a2505050565b5f54604051632474521560e21b81525f516020612eb45f395f51905f52600482018190523360248301529161010090046001600160a01b0316906391d1485490604401602060405180830381865afa15801561140f573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906114339190612cf1565b61146e5760405162461bcd60e51b815260206004820152600c60248201526b15539055551213d49256915160a21b604482015260640161074d565b600882905560405182815242907f0e55cc3e5c112dfa7651f177a66f846bd9975bd44fb3a7db47ba0346ffafb6c890602001610ba5565b5f54604051632474521560e21b81525f516020612eb45f395f51905f52600482018190523360248301529161010090046001600160a01b0316906391d1485490604401602060405180830381865afa158015611503573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906115279190612cf1565b6115625760405162461bcd60e51b815260206004820152600c60248201526b15539055551213d49256915160a21b604482015260640161074d565b600582905560405182815242907fb7ab3434f2f51870b4678303479d0d5e9d514f29711a30a1af70d696890dc66090602001610ba5565b5f5461010090046001600160a01b0316156115b2575f5ffd5b6115bb86611ecf565b600180546001600160a01b038781166001600160a01b031992831617909255600280548784169083168117909155600380548785169084161790556004805486851690841681178255600b8054958716959094169490941790925560405163095ea7b360e01b8152918201929092525f19602482015263095ea7b3906044016020604051808303815f875af1158015611656573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061167a9190612cf1565b50617080600c81905560405190815242907fc2af70983f5a9782f3c9b120a93935d68085856aa4e255fb95f00e66159d2ad09060200160405180910390a2670de0b6b3a7640000600881905560405190815242907f0e55cc3e5c112dfa7651f177a66f846bd9975bd44fb3a7db47ba0346ffafb6c8906020015b60405180910390a2505050505050565b6001546002546040516315d5220f60e31b81526001600160a01b0391821660048201525f928392169063aea9107890602401602060405180830381865afa158015611751573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906117759190612d0c565b90505f60015f9054906101000a90046001600160a01b03166001600160a01b031663d2c0dc146040518163ffffffff1660e01b8152600401602060405180830381865afa1580156117c8573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906117ec9190612d0c565b90505f6117f98284611f70565b905060025f9054906101000a90046001600160a01b03166001600160a01b03166318160ddd6040518163ffffffff1660e01b8152600401602060405180830381865afa15801561184b573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061186f9190612d0c565b6118799082612de8565b935050505090565b611889611f8d565b5f54604051632474521560e21b81527f8d206b40e8cca1a29acde55045d77950eb6fa9c9c87fb916b4d028ffc6ba3bcd600482018190523360248301529161010090046001600160a01b0316906391d1485490604401602060405180830381865afa1580156118fa573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061191e9190612cf1565b6119595760405162461bcd60e51b815260206004820152600c60248201526b15539055551213d49256915160a21b604482015260640161074d565b610a84611fb2565b5f5f61196b610d7d565b9050805f0361197b575f91505090565b600d545f9061199b9063ffffffff80821691640100000000900416612034565b90506119c6826119ab8342612e0e565b600e546119c191906001600160d01b0316612e21565b612043565b9250505090565b6119d5611f8d565b5f54604051632474521560e21b81527f8d206b40e8cca1a29acde55045d77950eb6fa9c9c87fb916b4d028ffc6ba3bcd600482018190523360248301529161010090046001600160a01b0316906391d1485490604401602060405180830381865afa158015611a46573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611a6a9190612cf1565b611aa55760405162461bcd60e51b815260206004820152600c60248201526b15539055551213d49256915160a21b604482015260640161074d565b611aad611fb2565b6002546040516370a0823160e01b81523060048201525f916001600160a01b0316906370a0823190602401602060405180830381865afa158015611af3573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611b179190612d0c565b6005549091505f818311611b2b575f611b35565b611b358284612e0e565b9050805f03611b4657505050505050565b5f85118015611b5457508481115b15611b5c5750835b6001600160a01b038616611b7a57611b75815f5f612052565b611d3e565b6003546001600160a01b0390811690871603611c5657600254600b5460405163a9059cbb60e01b81526001600160a01b0391821660048201526024810184905291169063a9059cbb906044016020604051808303815f875af1158015611be2573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611c069190612cf1565b50600c54611c12610d7d565b611c1c9190612e38565b600e80546001600160d01b0319166001600160d01b0392909216919091179055600d805463ffffffff19164263ffffffff16179055611d3e565b6004546001600160a01b0390811690871603611cc857600480546040516345efb3f960e11b81529182018390526001600160a01b031690638bdf67f2906024015f604051808303815f87803b158015611cad575f5ffd5b505af1158015611cbf573d5f5f3e3d5ffd5b50505050611d3e565b60025460405163a9059cbb60e01b81526001600160a01b038881166004830152602482018490529091169063a9059cbb906044016020604051808303815f875af1158015611d18573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611d3c9190612cf1565b505b604080516001600160a01b03881681526020810183905242917f2eb35b04d54ff7312f7402d6dee8b7f7b70bfaa62f43225066819e774a00e2cf91016116f4565b60408051808201909152600a5465ffffffffffff811680835266010000000000009091046001600160d01b031660208301525f9190429003611dcd57602001516001600160d01b0316919050565b6002546003546040516370a0823160e01b81526001600160a01b0391821660048201525f9291909116906370a0823190602401602060405180830381865afa158015611e1b573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611e3f9190612d0c565b90506001600160d01b03811115611e5857611e58612e57565b6001600160d01b03811666010000000000000265ffffffffffff421617600a5592915050565b611e86612547565b5f805460ff191690557f5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa335b6040516001600160a01b03909116815260200160405180910390a1565b5f80546001600160a01b0383811661010081810274ffffffffffffffffffffffffffffffffffffffff0019851617855560405193049190911692909183917f9209b7c8c06dcfd261686a663e7c55989337b18d59da5433c6f2835fb697092091a35050565b611f3c611f8d565b5f805460ff191660011790557f62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a258611eb23390565b5f611f8483670de0b6b3a764000084612569565b90505b92915050565b5f5460ff1615611fb05760405163d93c066560e01b815260040160405180910390fd5b565b611fba6109e9565b5f611fc3611704565b90505f811315611fde57611fd981600180612052565b611ff7565b5f811215611ff757611ff7611ff282612e6b565b612584565b427f662151f741be4ee85874103ff68a554d84943b85246bcb342d1c9642e22d159e8260405161202991815260200190565b60405180910390a250565b5f828218828411028218611f84565b5f828218828410028218611f84565b5f612067600854612061611d7f565b90612a90565b90505f60025f9054906101000a90046001600160a01b03166001600160a01b03166318160ddd6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156120ba573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906120de9190612d0c565b90505f6120f660095483612a9090919063ffffffff16565b90505f60045f9054906101000a90046001600160a01b03166001600160a01b031663ad7a672f6040518163ffffffff1660e01b8152600401602060405180830381865afa158015612149573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061216d9190612d0c565b90508181101561217a5750805b5f60045f9054906101000a90046001600160a01b03166001600160a01b0316636f2c590a6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156121cb573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906121ef9190612d0c565b90506121fb8282612a90565b91505f6122088387612e85565b90508715612270576002546040516340c10f1960e01b8152306004820152602481018b90526001600160a01b03909116906340c10f19906044015f604051808303815f87803b158015612259575f5ffd5b505af115801561226b573d5f5f3e3d5ffd5b505050505b6005548015612336576002546040516370a0823160e01b81523060048201525f918c916001600160a01b03909116906370a0823190602401602060405180830381865afa1580156122c3573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906122e79190612d0c565b6122f19190612e0e565b90508181101561233457816123068c83612e85565b1115612327576123168183612e0e565b612320908c612e0e565b9a50612334565b5050505050505050505050565b505b60065480158015906123455750885b156123e3575f6123558c83612a90565b905080156123e15760025460075460405163a9059cbb60e01b81526001600160a01b0391821660048201526024810184905291169063a9059cbb906044016020604051808303815f875af11580156123af573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906123d39190612cf1565b506123de818d612e0e565b9b505b505b825f036123f7575050505050505050505050565b5f6124038c8a86612569565b905080156124cd57600254600b5460405163a9059cbb60e01b81526001600160a01b0391821660048201526024810184905291169063a9059cbb906044016020604051808303815f875af115801561245d573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906124819190612cf1565b50600c5461248d610d7d565b6124979190612e38565b600e80546001600160d01b0319166001600160d01b0392909216919091179055600d805463ffffffff19164263ffffffff161790555b5f6124d8828e612e0e565b9050801561253857600480546040516345efb3f960e11b81529182018390526001600160a01b031690638bdf67f2906024015f604051808303815f87803b158015612521575f5ffd5b505af1158015612533573d5f5f3e3d5ffd5b505050505b50505050505050505050505050565b5f5460ff16611fb057604051638dfc202b60e01b815260040160405180910390fd5b5f825f19048411830215820261257d575f5ffd5b5091020490565b6002546040516370a0823160e01b81523060048201525f916001600160a01b0316906370a0823190602401602060405180830381865afa1580156125ca573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906125ee9190612d0c565b905081811061264c57600254604051630852cd8d60e31b8152600481018490526001600160a01b03909116906342966c68906024015f604051808303815f87803b15801561263a575f5ffd5b505af11580156109e0573d5f5f3e3d5ffd5b5f60045f9054906101000a90046001600160a01b03166001600160a01b031663ad7a672f6040518163ffffffff1660e01b8152600401602060405180830381865afa15801561269d573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906126c19190612d0c565b90508083116127265760048054604051632652277760e01b81529182018590526001600160a01b0316906326522777906024015f604051808303815f87803b15801561270b575f5ffd5b505af115801561271d573d5f5f3e3d5ffd5b50505050505050565b60048054604051632652277760e01b81529182018390526001600160a01b0316906326522777906024015f604051808303815f87803b158015612767575f5ffd5b505af1158015612779573d5f5f3e3d5ffd5b5050505080836127899190612e0e565b6002546003546040516370a0823160e01b81526001600160a01b0391821660048201529295505f929116906370a0823190602401602060405180830381865afa1580156127d8573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906127fc9190612d0c565b905080841161286457600354604051632652277760e01b8152600481018690526001600160a01b03909116906326522777906024015f604051808303815f87803b158015612848575f5ffd5b505af115801561285a573d5f5f3e3d5ffd5b5050505050505050565b600354604051632652277760e01b8152600481018390526001600160a01b03909116906326522777906024015f604051808303815f87803b1580156128a7575f5ffd5b505af11580156128b9573d5f5f3e3d5ffd5b5050505080846128c99190612e0e565b93505f60025f9054906101000a90046001600160a01b03166001600160a01b03166318160ddd6040518163ffffffff1660e01b8152600401602060405180830381865afa15801561291c573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906129409190612d0c565b60015460025460405163eb37d34960e01b81526001600160a01b0391821660048201529293505f9291169063eb37d34990602401602060405180830381865afa15801561298f573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906129b39190612e98565b90505f816001600160a01b031663a035b1fe6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156129f2573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612a169190612d0c565b90505f612a2e612a268986612e0e565b839086612569565b6040516391b7f5ed60e01b8152600481018290529091506001600160a01b038416906391b7f5ed906024015f604051808303815f87803b158015612a70575f5ffd5b505af1158015612a82573d5f5f3e3d5ffd5b505050505050505050505050565b5f611f848383670de0b6b3a7640000612569565b8015158114610a84575f5ffd5b5f60208284031215612ac1575f5ffd5b8135612acc81612aa4565b9392505050565b6001600160a01b0381168114610a84575f5ffd5b5f60208284031215612af7575f5ffd5b8135612acc81612ad3565b5f60208284031215612b12575f5ffd5b5035919050565b5f5f60208385031215612b2a575f5ffd5b823567ffffffffffffffff811115612b40575f5ffd5b8301601f81018513612b50575f5ffd5b803567ffffffffffffffff811115612b66575f5ffd5b8560208260051b8401011115612b7a575f5ffd5b6020919091019590945092505050565b5f81518084528060208401602086015e5f602082860101526020601f19601f83011685010191505092915050565b5f602082016020835280845180835260408501915060408160051b8601019250602086015f5b82811015612c0f57603f19878603018452612bfa858351612b8a565b94506020938401939190910190600101612bde565b50929695505050505050565b5f5f60408385031215612c2c575f5ffd5b823591506020830135612c3e81612ad3565b809150509250929050565b5f5f5f5f5f5f60c08789031215612c5e575f5ffd5b8635612c6981612ad3565b95506020870135612c7981612ad3565b94506040870135612c8981612ad3565b93506060870135612c9981612ad3565b92506080870135612ca981612ad3565b915060a0870135612cb981612ad3565b809150509295509295509295565b5f5f60408385031215612cd8575f5ffd5b8235612ce381612ad3565b946020939093013593505050565b5f60208284031215612d01575f5ffd5b8151612acc81612aa4565b5f60208284031215612d1c575f5ffd5b5051919050565b634e487b7160e01b5f52604160045260245ffd5b634e487b7160e01b5f52603260045260245ffd5b5f8235605e19833603018112612d5f575f5ffd5b9190910192915050565b5f5f8335601e19843603018112612d7e575f5ffd5b83018035915067ffffffffffffffff821115612d98575f5ffd5b602001915036819003821315612dac575f5ffd5b9250929050565b818382375f9101908152919050565b602081525f611f846020830184612b8a565b634e487b7160e01b5f52601160045260245ffd5b8181035f831280158383131683831282161715612e0757612e07612dd4565b5092915050565b81810381811115611f8757611f87612dd4565b8082028115828204841417611f8757611f87612dd4565b5f82612e5257634e487b7160e01b5f52601260045260245ffd5b500490565b634e487b7160e01b5f52600160045260245ffd5b5f600160ff1b8201612e7f57612e7f612dd4565b505f0390565b80820180821115611f8757611f87612dd4565b5f60208284031215612ea8575f5ffd5b8151612acc81612ad356fe3947e2f542c6c46c543fa4f79cbd1e27fea37ed249bc3caf992570d19123642ea2646970667358221220d4ebd9f4a619d8ee896b267acc6c62d89fdb45d96537a9d29e723fd5d606686f64736f6c634300081c0033","external_libraries":[],"proxy_type":null,"implementations":[],"verified_at":"2026-04-21T08:20:46.750667Z","is_verified_via_verifier_alliance":true,"compiler_version":"0.8.28+commit.7893614a","decoded_constructor_args":null,"sourcify_repo_url":null,"optimization_runs":400,"compiler_settings":{"evmVersion":"cancun","metadata":{"appendCBOR":true,"bytecodeHash":"ipfs","useLiteralContent":false},"optimizer":{"enabled":true,"runs":400},"remappings":["@openzeppelin/=lib/openzeppelin-contracts/","@forge-std/=lib/forge-std/src/","@solmate/=lib/solmate/","@cowprotocol/=lib/cowprotocol/src/","@core/=src/core/","@tokens/=src/tokens/","@locking/=src/locking/","@funding/=src/funding/","@gateway/=src/gateway/","@finance/=src/finance/","@periphery/=src/periphery/","@libraries/=src/libraries/","@interfaces/=src/interfaces/","@governance/=src/governance/","@integrations/=src/integrations/","@test/=test/","@deployment/=deployment/","@pendle/=lib/pendle-core-v2-public/contracts/","@chainlink/=lib/chainlink-ccip/chains/evm/","@chainlink/local/=lib/chainlink-local/","@layerzerolabs/lz-evm-protocol-v2/=lib/LayerZero-v2/packages/layerzero-v2/evm/protocol/","@layerzerolabs/lz-evm-oapp-v2/=lib/LayerZero-v2/packages/layerzero-v2/evm/oapp/","@layerzerolabs/lz-evm-messagelib-v2/=lib/LayerZero-v2/packages/layerzero-v2/evm/messagelib/","solidity-bytes-utils/=lib/solidity-bytes-utils/","LayerZero-devtools/=lib/LayerZero-devtools/","LayerZero-v2/=lib/LayerZero-v2/","chainlink-ccip/=lib/chainlink-ccip/chains/evm/contracts/vendor/optimism/interop-lib/v0/src/","cowprotocol/=lib/cowprotocol/src/","ds-test/=lib/solmate/lib/ds-test/src/","forge-std/=lib/forge-std/src/","openzeppelin-contracts/=lib/openzeppelin-contracts/","pendle-core-v2-public/=lib/pendle-core-v2-public/contracts/","solmate/=lib/solmate/src/"],"viaIR":false},"is_verified":true,"verified_twin_address_hash":null,"optimization_enabled":true,"deployed_bytecode":"0x608060405260043610610207575f3560e01c806385e3e8de11610113578063ec78e8321161009d578063f6339d891161006d578063f6339d89146105cd578063f843336c14610626578063f8ba4cff1461063a578063fea5657c1461064e578063ffaeac0014610662575f5ffd5b8063ec78e83214610559578063ed27f7c914610578578063efa72e9d14610597578063f2f4eb26146105ac575f5ffd5b8063bdca9165116100e3578063bdca9165146104ca578063be6972ac146104e5578063cc2a9a5b146104fc578063cc7a262e1461051b578063e2fdcc171461053a575f5ffd5b806385e3e8de1461045857806387788782146104775780639624e83e1461048c578063aee459dd146104ab575f5ffd5b80632f1183d8116101945780635c975abb116101645780635c975abb146103c45780637df3927e146103e657806380009630146104065780638456cb5914610425578063845ce76814610439575f5ffd5b80632f1183d81461035e5780633eb901a61461037d5780633f4ba83a1461039c57806344c63eec146103b0575f5ffd5b80631d6e11f2116101da5780631d6e11f2146102a95780631f91fa03146102bd57806325fc3ebe146102d25780632ba9fcd5146102e75780632e6cfc9314610349575f5ffd5b8063034172871461020b578063047050e81461022c57806312d9bdab1461025357806314ffc7931461028a575b5f5ffd5b348015610216575f5ffd5b5061022a610225366004612ab1565b610681565b005b348015610237575f5ffd5b50610240610769565b6040519081526020015b60405180910390f35b34801561025e575f5ffd5b50600454610272906001600160a01b031681565b6040516001600160a01b03909116815260200161024a565b348015610295575f5ffd5b5061022a6102a4366004612ae7565b610799565b3480156102b4575f5ffd5b5061022a6109e9565b3480156102c8575f5ffd5b5061024060055481565b3480156102dd575f5ffd5b5061024060095481565b3480156102f2575f5ffd5b50600d54600e5461031d9163ffffffff8082169264010000000090920416906001600160d01b031683565b6040805163ffffffff94851681529390921660208401526001600160d01b03169082015260600161024a565b348015610354575f5ffd5b5061024060085481565b348015610369575f5ffd5b5061022a610378366004612b02565b610a87565b348015610388575f5ffd5b5061022a610397366004612b02565b610bb1565b3480156103a7575f5ffd5b5061022a610ca5565b3480156103bb575f5ffd5b50610240610d7d565b3480156103cf575f5ffd5b505f5460ff165b604051901515815260200161024a565b6103f96103f4366004612b19565b610def565b60405161024a9190612bb8565b348015610411575f5ffd5b5061022a610420366004612ae7565b611071565b348015610430575f5ffd5b5061022a61114e565b348015610444575f5ffd5b5061022a610453366004612c1b565b611226565b348015610463575f5ffd5b5061022a610472366004612b02565b6113b1565b348015610482575f5ffd5b5061024060065481565b348015610497575f5ffd5b50600154610272906001600160a01b031681565b3480156104b6575f5ffd5b5061022a6104c5366004612b02565b6114a5565b3480156104d5575f5ffd5b506102406702c68af0bb14000081565b3480156104f0575f5ffd5b506103d660ff5f5c1681565b348015610507575f5ffd5b5061022a610516366004612c49565b611599565b348015610526575f5ffd5b50600354610272906001600160a01b031681565b348015610545575f5ffd5b50600b54610272906001600160a01b031681565b348015610564575f5ffd5b50600254610272906001600160a01b031681565b348015610583575f5ffd5b50600754610272906001600160a01b031681565b3480156105a2575f5ffd5b50610240600c5481565b3480156105b7575f5ffd5b505f5461010090046001600160a01b0316610272565b3480156105d8575f5ffd5b50600a546106009065ffffffffffff811690660100000000000090046001600160d01b031682565b6040805165ffffffffffff90931683526001600160d01b0390911660208301520161024a565b348015610631575f5ffd5b50610240611704565b348015610645575f5ffd5b5061022a611881565b348015610659575f5ffd5b50610240611961565b34801561066d575f5ffd5b5061022a61067c366004612cc7565b6119cd565b5f54604051632474521560e21b81527f276ea66e969b021a947c47a128f4d53c55387336443ef7a5391a75f0d2e48d25600482018190523360248301529161010090046001600160a01b0316906391d1485490604401602060405180830381865afa1580156106f2573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906107169190612cf1565b6107565760405162461bcd60e51b815260206004820152600c60248201526b15539055551213d49256915160a21b60448201526064015b60405180910390fd5b815f805c60ff191682151517905d505050565b5f60ff815c1661078c57604051633400dad560e11b815260040160405180910390fd5b610794611d7f565b905090565b5f54604051632474521560e21b81527f1a6838efa4183e08fe3607359d1259272af9d4716f65e1a7b5921f78fd5a3c6a600482018190523360248301529161010090046001600160a01b0316906391d1485490604401602060405180830381865afa15801561080a573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061082e9190612cf1565b6108695760405162461bcd60e51b815260206004820152600c60248201526b15539055551213d49256915160a21b604482015260640161074d565b6002546040516370a0823160e01b81526001600160a01b0384811660048301525f9216906370a0823190602401602060405180830381865afa1580156108b1573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906108d59190612d0c565b600254604051636eb1769f60e11b81526001600160a01b0386811660048301523060248301529293505f929091169063dd62ed3e90604401602060405180830381865afa158015610928573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061094c9190612d0c565b90505f82821061095c578261095e565b815b905080156109e2576002546040516323b872dd60e01b81526001600160a01b03878116600483015230602483015260448201849052909116906323b872dd906064016020604051808303815f875af11580156109bc573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906109e09190612cf1565b505b5050505050565b5f6109f2611961565b600d805467ffffffff0000000019166401000000004263ffffffff160217905590508015610a8457600b546002546003546040516303bcd7f360e11b81526001600160a01b039283166004820152908216602482015260448101849052911690630779afe6906064015f604051808303815f87803b158015610a72575f5ffd5b505af11580156109e2573d5f5f3e3d5ffd5b50565b5f54604051632474521560e21b81525f516020612eb45f395f51905f52600482018190523360248301529161010090046001600160a01b0316906391d1485490604401602060405180830381865afa158015610ae5573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610b099190612cf1565b610b445760405162461bcd60e51b815260206004820152600c60248201526b15539055551213d49256915160a21b604482015260640161074d565b81670de0b6b3a7640000811115610b715760405163e299400d60e01b815260040161074d91815260200190565b50600982905560405182815242907f02a6bcd1ae1882a47f8d6d3393d0540786d609fb8ef48ee6f069ef93777a6ebc906020015b60405180910390a25050565b5f54604051632474521560e21b81525f516020612eb45f395f51905f52600482018190523360248301529161010090046001600160a01b0316906391d1485490604401602060405180830381865afa158015610c0f573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610c339190612cf1565b610c6e5760405162461bcd60e51b815260206004820152600c60248201526b15539055551213d49256915160a21b604482015260640161074d565b600c82905560405182815242907fc2af70983f5a9782f3c9b120a93935d68085856aa4e255fb95f00e66159d2ad090602001610ba5565b5f54604051632474521560e21b81527fe7276a2a84d8de556657ec9cf93a55a7d66f096e529d0582ed08e9e2208b92b5600482018190523360248301529161010090046001600160a01b0316906391d1485490604401602060405180830381865afa158015610d16573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610d3a9190612cf1565b610d755760405162461bcd60e51b815260206004820152600c60248201526b15539055551213d49256915160a21b604482015260640161074d565b610a84611e7e565b600254600b546040516370a0823160e01b81526001600160a01b0391821660048201525f9291909116906370a0823190602401602060405180830381865afa158015610dcb573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906107949190612d0c565b5f54604051632474521560e21b81527f1a6838efa4183e08fe3607359d1259272af9d4716f65e1a7b5921f78fd5a3c6a6004820181905233602483015260609290916101009091046001600160a01b0316906391d1485490604401602060405180830381865afa158015610e65573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610e899190612cf1565b610ec45760405162461bcd60e51b815260206004820152600c60248201526b15539055551213d49256915160a21b604482015260640161074d565b8267ffffffffffffffff811115610edd57610edd612d23565b604051908082528060200260200182016040528015610f1057816020015b6060815260200190600190039081610efb5790505b5091505f5b83811015611069575f858583818110610f3057610f30612d37565b9050602002810190610f429190612d4b565b610f50906020810190612ae7565b90505f868684818110610f6557610f65612d37565b9050602002810190610f779190612d4b565b602001359050365f888886818110610f9157610f91612d37565b9050602002810190610fa39190612d4b565b610fb1906040810190612d69565b915091505f5f856001600160a01b0316858585604051610fd2929190612db3565b5f6040518083038185875af1925050503d805f811461100c576040519150601f19603f3d011682016040523d82523d5f602084013e611011565b606091505b509150915081819061103757604051634ad176bb60e01b815260040161074d9190612dc2565b508089888151811061104b5761104b612d37565b60200260200101819052505050505050508080600101915050610f15565b505092915050565b5f54604051632474521560e21b81527f1a6838efa4183e08fe3607359d1259272af9d4716f65e1a7b5921f78fd5a3c6a600482018190523360248301529161010090046001600160a01b0316906391d1485490604401602060405180830381865afa1580156110e2573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906111069190612cf1565b6111415760405162461bcd60e51b815260206004820152600c60248201526b15539055551213d49256915160a21b604482015260640161074d565b61114a82611ecf565b5050565b5f54604051632474521560e21b81527ffcb9fcbfa83b897fb2d5cf4b58962164105c1e71489a37ef3ae0db3fdce576f6600482018190523360248301529161010090046001600160a01b0316906391d1485490604401602060405180830381865afa1580156111bf573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906111e39190612cf1565b61121e5760405162461bcd60e51b815260206004820152600c60248201526b15539055551213d49256915160a21b604482015260640161074d565b610a84611f34565b5f54604051632474521560e21b81525f516020612eb45f395f51905f52600482018190523360248301529161010090046001600160a01b0316906391d1485490604401602060405180830381865afa158015611284573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906112a89190612cf1565b6112e35760405162461bcd60e51b815260206004820152600c60248201526b15539055551213d49256915160a21b604482015260640161074d565b826702c68af0bb1400008111156113105760405163b4ea6d5760e01b815260040161074d91815260200190565b50821561134d57816001600160a01b03811661134b5760405163048f87e560e31b81526001600160a01b03909116600482015260240161074d565b505b6006839055600780546001600160a01b0319166001600160a01b03841690811790915560408051858152602081019290925242917fc60b1772d13a32078285a149ad1f03b32a1f6df54245b584a8531d6f87f9e9f4910160405180910390a2505050565b5f54604051632474521560e21b81525f516020612eb45f395f51905f52600482018190523360248301529161010090046001600160a01b0316906391d1485490604401602060405180830381865afa15801561140f573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906114339190612cf1565b61146e5760405162461bcd60e51b815260206004820152600c60248201526b15539055551213d49256915160a21b604482015260640161074d565b600882905560405182815242907f0e55cc3e5c112dfa7651f177a66f846bd9975bd44fb3a7db47ba0346ffafb6c890602001610ba5565b5f54604051632474521560e21b81525f516020612eb45f395f51905f52600482018190523360248301529161010090046001600160a01b0316906391d1485490604401602060405180830381865afa158015611503573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906115279190612cf1565b6115625760405162461bcd60e51b815260206004820152600c60248201526b15539055551213d49256915160a21b604482015260640161074d565b600582905560405182815242907fb7ab3434f2f51870b4678303479d0d5e9d514f29711a30a1af70d696890dc66090602001610ba5565b5f5461010090046001600160a01b0316156115b2575f5ffd5b6115bb86611ecf565b600180546001600160a01b038781166001600160a01b031992831617909255600280548784169083168117909155600380548785169084161790556004805486851690841681178255600b8054958716959094169490941790925560405163095ea7b360e01b8152918201929092525f19602482015263095ea7b3906044016020604051808303815f875af1158015611656573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061167a9190612cf1565b50617080600c81905560405190815242907fc2af70983f5a9782f3c9b120a93935d68085856aa4e255fb95f00e66159d2ad09060200160405180910390a2670de0b6b3a7640000600881905560405190815242907f0e55cc3e5c112dfa7651f177a66f846bd9975bd44fb3a7db47ba0346ffafb6c8906020015b60405180910390a2505050505050565b6001546002546040516315d5220f60e31b81526001600160a01b0391821660048201525f928392169063aea9107890602401602060405180830381865afa158015611751573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906117759190612d0c565b90505f60015f9054906101000a90046001600160a01b03166001600160a01b031663d2c0dc146040518163ffffffff1660e01b8152600401602060405180830381865afa1580156117c8573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906117ec9190612d0c565b90505f6117f98284611f70565b905060025f9054906101000a90046001600160a01b03166001600160a01b03166318160ddd6040518163ffffffff1660e01b8152600401602060405180830381865afa15801561184b573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061186f9190612d0c565b6118799082612de8565b935050505090565b611889611f8d565b5f54604051632474521560e21b81527f8d206b40e8cca1a29acde55045d77950eb6fa9c9c87fb916b4d028ffc6ba3bcd600482018190523360248301529161010090046001600160a01b0316906391d1485490604401602060405180830381865afa1580156118fa573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061191e9190612cf1565b6119595760405162461bcd60e51b815260206004820152600c60248201526b15539055551213d49256915160a21b604482015260640161074d565b610a84611fb2565b5f5f61196b610d7d565b9050805f0361197b575f91505090565b600d545f9061199b9063ffffffff80821691640100000000900416612034565b90506119c6826119ab8342612e0e565b600e546119c191906001600160d01b0316612e21565b612043565b9250505090565b6119d5611f8d565b5f54604051632474521560e21b81527f8d206b40e8cca1a29acde55045d77950eb6fa9c9c87fb916b4d028ffc6ba3bcd600482018190523360248301529161010090046001600160a01b0316906391d1485490604401602060405180830381865afa158015611a46573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611a6a9190612cf1565b611aa55760405162461bcd60e51b815260206004820152600c60248201526b15539055551213d49256915160a21b604482015260640161074d565b611aad611fb2565b6002546040516370a0823160e01b81523060048201525f916001600160a01b0316906370a0823190602401602060405180830381865afa158015611af3573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611b179190612d0c565b6005549091505f818311611b2b575f611b35565b611b358284612e0e565b9050805f03611b4657505050505050565b5f85118015611b5457508481115b15611b5c5750835b6001600160a01b038616611b7a57611b75815f5f612052565b611d3e565b6003546001600160a01b0390811690871603611c5657600254600b5460405163a9059cbb60e01b81526001600160a01b0391821660048201526024810184905291169063a9059cbb906044016020604051808303815f875af1158015611be2573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611c069190612cf1565b50600c54611c12610d7d565b611c1c9190612e38565b600e80546001600160d01b0319166001600160d01b0392909216919091179055600d805463ffffffff19164263ffffffff16179055611d3e565b6004546001600160a01b0390811690871603611cc857600480546040516345efb3f960e11b81529182018390526001600160a01b031690638bdf67f2906024015f604051808303815f87803b158015611cad575f5ffd5b505af1158015611cbf573d5f5f3e3d5ffd5b50505050611d3e565b60025460405163a9059cbb60e01b81526001600160a01b038881166004830152602482018490529091169063a9059cbb906044016020604051808303815f875af1158015611d18573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611d3c9190612cf1565b505b604080516001600160a01b03881681526020810183905242917f2eb35b04d54ff7312f7402d6dee8b7f7b70bfaa62f43225066819e774a00e2cf91016116f4565b60408051808201909152600a5465ffffffffffff811680835266010000000000009091046001600160d01b031660208301525f9190429003611dcd57602001516001600160d01b0316919050565b6002546003546040516370a0823160e01b81526001600160a01b0391821660048201525f9291909116906370a0823190602401602060405180830381865afa158015611e1b573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611e3f9190612d0c565b90506001600160d01b03811115611e5857611e58612e57565b6001600160d01b03811666010000000000000265ffffffffffff421617600a5592915050565b611e86612547565b5f805460ff191690557f5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa335b6040516001600160a01b03909116815260200160405180910390a1565b5f80546001600160a01b0383811661010081810274ffffffffffffffffffffffffffffffffffffffff0019851617855560405193049190911692909183917f9209b7c8c06dcfd261686a663e7c55989337b18d59da5433c6f2835fb697092091a35050565b611f3c611f8d565b5f805460ff191660011790557f62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a258611eb23390565b5f611f8483670de0b6b3a764000084612569565b90505b92915050565b5f5460ff1615611fb05760405163d93c066560e01b815260040160405180910390fd5b565b611fba6109e9565b5f611fc3611704565b90505f811315611fde57611fd981600180612052565b611ff7565b5f811215611ff757611ff7611ff282612e6b565b612584565b427f662151f741be4ee85874103ff68a554d84943b85246bcb342d1c9642e22d159e8260405161202991815260200190565b60405180910390a250565b5f828218828411028218611f84565b5f828218828410028218611f84565b5f612067600854612061611d7f565b90612a90565b90505f60025f9054906101000a90046001600160a01b03166001600160a01b03166318160ddd6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156120ba573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906120de9190612d0c565b90505f6120f660095483612a9090919063ffffffff16565b90505f60045f9054906101000a90046001600160a01b03166001600160a01b031663ad7a672f6040518163ffffffff1660e01b8152600401602060405180830381865afa158015612149573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061216d9190612d0c565b90508181101561217a5750805b5f60045f9054906101000a90046001600160a01b03166001600160a01b0316636f2c590a6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156121cb573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906121ef9190612d0c565b90506121fb8282612a90565b91505f6122088387612e85565b90508715612270576002546040516340c10f1960e01b8152306004820152602481018b90526001600160a01b03909116906340c10f19906044015f604051808303815f87803b158015612259575f5ffd5b505af115801561226b573d5f5f3e3d5ffd5b505050505b6005548015612336576002546040516370a0823160e01b81523060048201525f918c916001600160a01b03909116906370a0823190602401602060405180830381865afa1580156122c3573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906122e79190612d0c565b6122f19190612e0e565b90508181101561233457816123068c83612e85565b1115612327576123168183612e0e565b612320908c612e0e565b9a50612334565b5050505050505050505050565b505b60065480158015906123455750885b156123e3575f6123558c83612a90565b905080156123e15760025460075460405163a9059cbb60e01b81526001600160a01b0391821660048201526024810184905291169063a9059cbb906044016020604051808303815f875af11580156123af573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906123d39190612cf1565b506123de818d612e0e565b9b505b505b825f036123f7575050505050505050505050565b5f6124038c8a86612569565b905080156124cd57600254600b5460405163a9059cbb60e01b81526001600160a01b0391821660048201526024810184905291169063a9059cbb906044016020604051808303815f875af115801561245d573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906124819190612cf1565b50600c5461248d610d7d565b6124979190612e38565b600e80546001600160d01b0319166001600160d01b0392909216919091179055600d805463ffffffff19164263ffffffff161790555b5f6124d8828e612e0e565b9050801561253857600480546040516345efb3f960e11b81529182018390526001600160a01b031690638bdf67f2906024015f604051808303815f87803b158015612521575f5ffd5b505af1158015612533573d5f5f3e3d5ffd5b505050505b50505050505050505050505050565b5f5460ff16611fb057604051638dfc202b60e01b815260040160405180910390fd5b5f825f19048411830215820261257d575f5ffd5b5091020490565b6002546040516370a0823160e01b81523060048201525f916001600160a01b0316906370a0823190602401602060405180830381865afa1580156125ca573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906125ee9190612d0c565b905081811061264c57600254604051630852cd8d60e31b8152600481018490526001600160a01b03909116906342966c68906024015f604051808303815f87803b15801561263a575f5ffd5b505af11580156109e0573d5f5f3e3d5ffd5b5f60045f9054906101000a90046001600160a01b03166001600160a01b031663ad7a672f6040518163ffffffff1660e01b8152600401602060405180830381865afa15801561269d573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906126c19190612d0c565b90508083116127265760048054604051632652277760e01b81529182018590526001600160a01b0316906326522777906024015f604051808303815f87803b15801561270b575f5ffd5b505af115801561271d573d5f5f3e3d5ffd5b50505050505050565b60048054604051632652277760e01b81529182018390526001600160a01b0316906326522777906024015f604051808303815f87803b158015612767575f5ffd5b505af1158015612779573d5f5f3e3d5ffd5b5050505080836127899190612e0e565b6002546003546040516370a0823160e01b81526001600160a01b0391821660048201529295505f929116906370a0823190602401602060405180830381865afa1580156127d8573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906127fc9190612d0c565b905080841161286457600354604051632652277760e01b8152600481018690526001600160a01b03909116906326522777906024015f604051808303815f87803b158015612848575f5ffd5b505af115801561285a573d5f5f3e3d5ffd5b5050505050505050565b600354604051632652277760e01b8152600481018390526001600160a01b03909116906326522777906024015f604051808303815f87803b1580156128a7575f5ffd5b505af11580156128b9573d5f5f3e3d5ffd5b5050505080846128c99190612e0e565b93505f60025f9054906101000a90046001600160a01b03166001600160a01b03166318160ddd6040518163ffffffff1660e01b8152600401602060405180830381865afa15801561291c573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906129409190612d0c565b60015460025460405163eb37d34960e01b81526001600160a01b0391821660048201529293505f9291169063eb37d34990602401602060405180830381865afa15801561298f573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906129b39190612e98565b90505f816001600160a01b031663a035b1fe6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156129f2573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612a169190612d0c565b90505f612a2e612a268986612e0e565b839086612569565b6040516391b7f5ed60e01b8152600481018290529091506001600160a01b038416906391b7f5ed906024015f604051808303815f87803b158015612a70575f5ffd5b505af1158015612a82573d5f5f3e3d5ffd5b505050505050505050505050565b5f611f848383670de0b6b3a7640000612569565b8015158114610a84575f5ffd5b5f60208284031215612ac1575f5ffd5b8135612acc81612aa4565b9392505050565b6001600160a01b0381168114610a84575f5ffd5b5f60208284031215612af7575f5ffd5b8135612acc81612ad3565b5f60208284031215612b12575f5ffd5b5035919050565b5f5f60208385031215612b2a575f5ffd5b823567ffffffffffffffff811115612b40575f5ffd5b8301601f81018513612b50575f5ffd5b803567ffffffffffffffff811115612b66575f5ffd5b8560208260051b8401011115612b7a575f5ffd5b6020919091019590945092505050565b5f81518084528060208401602086015e5f602082860101526020601f19601f83011685010191505092915050565b5f602082016020835280845180835260408501915060408160051b8601019250602086015f5b82811015612c0f57603f19878603018452612bfa858351612b8a565b94506020938401939190910190600101612bde565b50929695505050505050565b5f5f60408385031215612c2c575f5ffd5b823591506020830135612c3e81612ad3565b809150509250929050565b5f5f5f5f5f5f60c08789031215612c5e575f5ffd5b8635612c6981612ad3565b95506020870135612c7981612ad3565b94506040870135612c8981612ad3565b93506060870135612c9981612ad3565b92506080870135612ca981612ad3565b915060a0870135612cb981612ad3565b809150509295509295509295565b5f5f60408385031215612cd8575f5ffd5b8235612ce381612ad3565b946020939093013593505050565b5f60208284031215612d01575f5ffd5b8151612acc81612aa4565b5f60208284031215612d1c575f5ffd5b5051919050565b634e487b7160e01b5f52604160045260245ffd5b634e487b7160e01b5f52603260045260245ffd5b5f8235605e19833603018112612d5f575f5ffd5b9190910192915050565b5f5f8335601e19843603018112612d7e575f5ffd5b83018035915067ffffffffffffffff821115612d98575f5ffd5b602001915036819003821315612dac575f5ffd5b9250929050565b818382375f9101908152919050565b602081525f611f846020830184612b8a565b634e487b7160e01b5f52601160045260245ffd5b8181035f831280158383131683831282161715612e0757612e07612dd4565b5092915050565b81810381811115611f8757611f87612dd4565b8082028115828204841417611f8757611f87612dd4565b5f82612e5257634e487b7160e01b5f52601260045260245ffd5b500490565b634e487b7160e01b5f52600160045260245ffd5b5f600160ff1b8201612e7f57612e7f612dd4565b505f0390565b80820180821115611f8757611f87612dd4565b5f60208284031215612ea8575f5ffd5b8151612acc81612ad356fe3947e2f542c6c46c543fa4f79cbd1e27fea37ed249bc3caf992570d19123642ea2646970667358221220d4ebd9f4a619d8ee896b267acc6c62d89fdb45d96537a9d29e723fd5d606686f64736f6c634300081c0033","source_code":"// SPDX-License-Identifier: MIT\npragma solidity 0.8.28;\n\nimport {Math} from \"@openzeppelin/contracts/utils/math/Math.sol\";\nimport {FixedPointMathLib} from \"@solmate/src/utils/FixedPointMathLib.sol\";\n\nimport {CoreRoles} from \"@libraries/CoreRoles.sol\";\nimport {Accounting} from \"@finance/Accounting.sol\";\nimport {StakedToken} from \"@tokens/StakedToken.sol\";\nimport {ReceiptToken} from \"@tokens/ReceiptToken.sol\";\nimport {CoreControlled} from \"@core/CoreControlled.sol\";\nimport {FixedPriceOracle} from \"@finance/oracles/FixedPriceOracle.sol\";\nimport {LockingController} from \"@locking/LockingController.sol\";\nimport {YieldVestingEscrow} from \"@finance/YieldSharingV2.sol\";\n\n/// @notice InfiniFi YieldSharing contract V3\n/// this V3 allows the reuse of an existing escrow, adds access control to the accrue() function,\n/// and adds a function to flush the excess safety buffer.\ncontract YieldSharingV3 is CoreControlled {\n    using FixedPointMathLib for uint256;\n\n    error PerformanceFeeTooHigh(uint256 _percent);\n    error PerformanceFeeRecipientIsZeroAddress(address _recipient);\n    error TargetIlliquidRatioTooHigh(uint256 _ratio);\n    error StakedTokenNotAvailable();\n\n    /// @notice Fired when yield is accrued from frarms\n    /// @param timestamp block timestamp of the accrual\n    /// @param yield profit or loss in farms since last accrual\n    event YieldAccrued(uint256 indexed timestamp, int256 yield);\n    event InterpolationDurationUpdated(uint256 indexed timestamp, uint256 duration);\n    event TargetIlliquidRatioUpdated(uint256 indexed timestamp, uint256 multiplier);\n    event SafetyBufferSizeUpdated(uint256 indexed timestamp, uint256 value);\n    event LiquidMultiplierUpdated(uint256 indexed timestamp, uint256 multiplier);\n    event PerformanceFeeSettingsUpdated(uint256 indexed timestamp, uint256 percentage, address recipient);\n    event ExcessSafetyBufferFlushed(uint256 indexed timestamp, address recipient, uint256 amount);\n\n    uint256 public constant MAX_PERFORMANCE_FEE = 0.2e18; // 20%\n\n    /// @notice reference to farm accounting contract\n    address public accounting;\n\n    /// @notice reference to receipt token\n    address public receiptToken;\n\n    /// @notice reference to staked token\n    address public stakedToken;\n\n    /// @notice reference to locking module\n    address public lockingModule;\n\n    /// @notice safety buffer amount.\n    /// This amount of iUSD is held on the contract and consumed first in case of losses smaller\n    /// than the safety buffer. It is also replenished first in case of profit, up to the buffer size.\n    /// The buffer held could exceed safetyBufferSize if there are donations to this contract, or if\n    /// the buffer size has been reduced since last profit distribution, or if there are no other\n    /// users to distribute to.\n    /// The safety buffer is meant to absorb small losses such as slippage or fees when\n    /// deploying capital to productive farms.\n    /// safety buffer can be emptied by governance through the use of emergencyAction().\n    uint256 public safetyBufferSize;\n\n    /// @notice optional performance fee, expressed as a percentage with 18 decimals.\n    uint256 public performanceFee; // default to 0%\n\n    /// @notice optional performance fee recipient\n    address public performanceFeeRecipient;\n\n    /// @notice multiplier for the liquid return, expressed as a percentage with 18 decimals.\n    uint256 public liquidReturnMultiplier;\n\n    /// @notice target illiquid ratio, expressed as a percentage with 18 decimals.\n    /// This ratio is the minimum percent of illiquid holdings the protocol is targetting, and\n    /// if there is a percentage of illiquid users lower than the targetIlliquidRatio, the protocol\n    /// wil distribute additional rewards to the illiquid users until targetIlliquidRatio is reached.\n    uint256 public targetIlliquidRatio; // default to 0\n\n    struct StakedReceiptTokenCache {\n        uint48 blockTimestamp;\n        uint208 amount;\n    }\n\n    StakedReceiptTokenCache public stakedReceiptTokenCache;\n\n    /// @notice escrow of rewards to staked users\n    YieldVestingEscrow public escrow;\n\n    /// @notice interpolation duration of rewards to staked users\n    uint256 public interpolationDuration;\n\n    struct Point {\n        uint32 lastAccrued;\n        uint32 lastClaimed;\n        uint208 rate;\n    }\n\n    /// @notice point used for interpolating rewards of the staked users\n    Point public point = Point({lastAccrued: uint32(block.timestamp), lastClaimed: uint32(block.timestamp), rate: 0});\n\n    /// @notice Make deposits and withdrawals in the staked token revert unless set to true.\n    bool public transient canEnterOrExitStakedToken;\n\n    constructor() CoreControlled(address(1)) {}\n\n    /// @notice initializer for deployment behind a proxy\n    function initialize(\n        address _core,\n        address _accounting,\n        address _receiptToken,\n        address _stakedToken,\n        address _lockingModule,\n        address _escrow\n    ) external {\n        require(address(core()) == address(0));\n\n        _setCore(_core);\n        accounting = _accounting;\n        receiptToken = _receiptToken;\n        stakedToken = _stakedToken;\n        lockingModule = _lockingModule;\n        escrow = YieldVestingEscrow(_escrow);\n        ReceiptToken(receiptToken).approve(_lockingModule, type(uint256).max);\n\n        interpolationDuration = 8 hours;\n        emit InterpolationDurationUpdated(block.timestamp, interpolationDuration);\n        liquidReturnMultiplier = FixedPointMathLib.WAD;\n        emit LiquidMultiplierUpdated(block.timestamp, liquidReturnMultiplier);\n    }\n\n    /// @notice set the safety buffer size\n    /// @param _safetyBufferSize the new safety buffer size\n    function setSafetyBufferSize(uint256 _safetyBufferSize) external onlyCoreRole(CoreRoles.PROTOCOL_PARAMETERS) {\n        safetyBufferSize = _safetyBufferSize;\n        emit SafetyBufferSizeUpdated(block.timestamp, _safetyBufferSize);\n    }\n\n    /// @notice set the performance fee and recipient\n    function setPerformanceFeeAndRecipient(uint256 _percent, address _recipient)\n        external\n        onlyCoreRole(CoreRoles.PROTOCOL_PARAMETERS)\n    {\n        require(_percent <= MAX_PERFORMANCE_FEE, PerformanceFeeTooHigh(_percent));\n        if (_percent > 0) {\n            require(_recipient != address(0), PerformanceFeeRecipientIsZeroAddress(_recipient));\n        }\n\n        performanceFee = _percent;\n        performanceFeeRecipient = _recipient;\n        emit PerformanceFeeSettingsUpdated(block.timestamp, _percent, _recipient);\n    }\n\n    /// @notice set the liquid return multiplier\n    function setLiquidReturnMultiplier(uint256 _multiplier) external onlyCoreRole(CoreRoles.PROTOCOL_PARAMETERS) {\n        liquidReturnMultiplier = _multiplier;\n        emit LiquidMultiplierUpdated(block.timestamp, _multiplier);\n    }\n\n    /// @notice set the target illiquid ratio\n    function setTargetIlliquidRatio(uint256 _ratio) external onlyCoreRole(CoreRoles.PROTOCOL_PARAMETERS) {\n        require(_ratio <= FixedPointMathLib.WAD, TargetIlliquidRatioTooHigh(_ratio));\n        targetIlliquidRatio = _ratio;\n        emit TargetIlliquidRatioUpdated(block.timestamp, _ratio);\n    }\n\n    /// @notice set the interpolation duration of StakedToken rewards\n    /// @dev Note that the rate of distribution will only change after the next accrue() call\n    /// that is distributing a non-zero amount of rewards to the staked users.\n    function setInterpolationDuration(uint256 _duration) external onlyCoreRole(CoreRoles.PROTOCOL_PARAMETERS) {\n        interpolationDuration = _duration;\n        emit InterpolationDurationUpdated(block.timestamp, _duration);\n    }\n\n    /// @notice returns the yield earned by the protocol since the last accrue() call.\n    /// @return yield as an amount of receiptTokens.\n    /// @dev Note that yield can be negative if the protocol farms have lost value, or if the\n    /// oracle price of assets held in the protocol has decreased since last accrue() call,\n    /// or if more ReceiptTokens entered circulation than assets entered the protocol.\n    function unaccruedYield() public view returns (int256) {\n        uint256 receiptTokenPrice = Accounting(accounting).price(receiptToken);\n        uint256 assets = Accounting(accounting).totalAssetsValue(); // returns assets in USD\n\n        uint256 assetsInReceiptTokens = assets.divWadDown(receiptTokenPrice);\n\n        // casting to 'int256' is safe because type(int256).max is an irrealistically large amount of receiptTokens\n        // forge-lint: disable-next-line(unsafe-typecast)\n        return int256(assetsInReceiptTokens) - int256(ReceiptToken(receiptToken).totalSupply());\n    }\n\n    /// @notice accrue yield and handle profits & losses\n    /// This function should bring back unaccruedYield() to 0 by minting receiptTokens into circulation (profit distribution)\n    /// or burning receipt tokens (slashing) or updating the oracle price of the receiptToken if there\n    /// are not enough first-loss capital stakers to slash.\n    function _accrue() internal {\n        distributeInterpolationRewards();\n\n        int256 yield = unaccruedYield();\n        // casting to 'uint256' is safe because of 'if'\n        // forge-lint: disable-next-line(unsafe-typecast)\n        if (yield > 0) _handlePositiveYield(uint256(yield), true, true);\n        // casting to 'uint256' is safe because of 'else'\n        // forge-lint: disable-next-line(unsafe-typecast)\n        else if (yield < 0) _handleNegativeYield(uint256(-yield));\n\n        emit YieldAccrued(block.timestamp, yield);\n    }\n\n    function accrue() external whenNotPaused onlyCoreRole(CoreRoles.ACCRUE_YIELD) {\n        _accrue();\n    }\n\n    function _getCachedStakedReceiptTokens() internal returns (uint256) {\n        StakedReceiptTokenCache memory data = stakedReceiptTokenCache;\n        if (uint256(data.blockTimestamp) == block.timestamp) {\n            return uint256(data.amount);\n        }\n        uint256 amount = ReceiptToken(receiptToken).balanceOf(stakedToken);\n        assert(amount <= type(uint208).max);\n\n        // casting to 'uint48' is safe because type(uint48).max timestamp is very far in the future\n        // forge-lint: disable-next-line(unsafe-typecast)\n        stakedReceiptTokenCache.blockTimestamp = uint48(block.timestamp);\n        // casting to 'uint208' is safe because of the assert above\n        // forge-lint: disable-next-line(unsafe-typecast)\n        stakedReceiptTokenCache.amount = uint208(amount);\n\n        return amount;\n    }\n\n    // hook called by any deposits and withdrawals in siUSD vault, we revert if the\n    // flag is not set to true. this will break 4626 compatibility of the vault for\n    // deposits and withdrawals, but the gateway can set the flag and perform entry/\n    // exits on behalf of the users.\n    function getCachedStakedReceiptTokens() public returns (uint256) {\n        require(canEnterOrExitStakedToken, StakedTokenNotAvailable());\n        return _getCachedStakedReceiptTokens();\n    }\n\n    // gateway can set the flag to allow deposits and withdrawals in the siUSD vault\n    function setCanEnterOrExitStakedToken(bool _value) external onlyCoreRole(CoreRoles.ENTRY_POINT) {\n        canEnterOrExitStakedToken = _value;\n    }\n\n    /// @notice Number of rewards interpolating to staked users\n    function vesting() public view returns (uint256) {\n        return ReceiptToken(receiptToken).balanceOf(address(escrow));\n    }\n\n    /// @notice Number of rewards vested to staked users\n    function vested() public view returns (uint256) {\n        uint256 _vesting = vesting();\n        if (_vesting == 0) return 0;\n\n        uint256 maxTs = Math.max(point.lastAccrued, point.lastClaimed);\n        return Math.min(_vesting, uint256(point.rate) * (block.timestamp - maxTs));\n    }\n\n    // send the vested rewards to the siUSD vault\n    // called by the gateway before stake & unstake,\n    // and here in the yieldSharing before accrue()\n    function distributeInterpolationRewards() public {\n        uint256 _vested = vested();\n        point.lastClaimed = uint32(block.timestamp);\n        if (_vested != 0) {\n            escrow.send(receiptToken, stakedToken, _vested);\n        }\n    }\n\n    /// @notice Yield sharing: split between iUSD lockin users & siUSD holders.\n    /// If no users are locking or saving, the profit is minted on this contract and\n    /// held idle so that the accrue() expected behavior of restoring protocol equity to 0\n    /// is maintained. Funds minted on this contract in such a way can be unstuck by governance\n    /// through the use of emergencyAction().\n    /// @param _positiveYield the amount of profit to distribute\n    /// @param _doMint whether to self-mint the profit before distribution\n    /// @param _applyPerfFee whether to apply the performance fee\n    function _handlePositiveYield(uint256 _positiveYield, bool _doMint, bool _applyPerfFee) internal {\n        uint256 stakedReceiptTokens = _getCachedStakedReceiptTokens().mulWadDown(liquidReturnMultiplier);\n        uint256 receiptTokenTotalSupply = ReceiptToken(receiptToken).totalSupply();\n        uint256 targetIlliquidMinimum = receiptTokenTotalSupply.mulWadDown(targetIlliquidRatio);\n        uint256 lockingReceiptTokens = LockingController(lockingModule).totalBalance();\n        if (lockingReceiptTokens < targetIlliquidMinimum) {\n            lockingReceiptTokens = targetIlliquidMinimum;\n        }\n        uint256 bondingMultiplier = LockingController(lockingModule).rewardMultiplier();\n        lockingReceiptTokens = lockingReceiptTokens.mulWadDown(bondingMultiplier);\n        uint256 totalReceiptTokens = stakedReceiptTokens + lockingReceiptTokens;\n\n        // mint yield\n        if (_doMint) ReceiptToken(receiptToken).mint(address(this), _positiveYield);\n\n        // fill safety buffer first\n        uint256 _safetyBufferSize = safetyBufferSize;\n        if (_safetyBufferSize > 0) {\n            uint256 safetyBuffer = ReceiptToken(receiptToken).balanceOf(address(this)) - _positiveYield;\n            if (safetyBuffer < _safetyBufferSize) {\n                if (safetyBuffer + _positiveYield > _safetyBufferSize) {\n                    // there will be a leftover profit after filling the safety buffer, so we\n                    // deduct the safety buffer contribution from the profits and continue\n                    _positiveYield -= _safetyBufferSize - safetyBuffer;\n                } else {\n                    // do not do any further distribution and only replenish the safety buffer\n                    return;\n                }\n            }\n        }\n\n        // performance fee\n        uint256 _performanceFee = performanceFee;\n        if (_performanceFee > 0 && _applyPerfFee) {\n            uint256 fee = _positiveYield.mulWadDown(_performanceFee);\n            if (fee > 0) {\n                // forge-lint: disable-next-line(erc20-unchecked-transfer)\n                ReceiptToken(receiptToken).transfer(performanceFeeRecipient, fee);\n                _positiveYield -= fee;\n            }\n        }\n\n        // compute splits\n        if (totalReceiptTokens == 0) {\n            // nobody to distribute to, do nothing and hold the tokens\n            return;\n        }\n\n        // yield split to staked users\n        uint256 stakingProfit = _positiveYield.mulDivDown(stakedReceiptTokens, totalReceiptTokens);\n        if (stakingProfit > 0) {\n            // forge-lint: disable-next-line(erc20-unchecked-transfer)\n            ReceiptToken(receiptToken).transfer(address(escrow), stakingProfit);\n            // casting to 'uint208' is safe because type(uint208).max would be an outrageously large rate per second\n            // forge-lint: disable-next-line(unsafe-typecast)\n            point.rate = uint208(vesting() / interpolationDuration);\n            point.lastAccrued = uint32(block.timestamp);\n        }\n\n        // yield split to locking users\n        uint256 lockingProfit = _positiveYield - stakingProfit;\n        if (lockingProfit > 0) {\n            LockingController(lockingModule).depositRewards(lockingProfit);\n        }\n    }\n\n    /// @notice Loss propagation: iUSD locking users -> siUSD holders -> iUSD holders\n    function _handleNegativeYield(uint256 _negativeYield) internal {\n        // if there is a safety buffer, and the loss is smaller than the safety buffer,\n        // consume it and do not apply any losses to users.\n        uint256 safetyBuffer = ReceiptToken(receiptToken).balanceOf(address(this));\n        if (safetyBuffer >= _negativeYield) {\n            ReceiptToken(receiptToken).burn(_negativeYield);\n            return;\n        }\n\n        // first, apply losses to locking users\n        uint256 lockingReceiptTokens = LockingController(lockingModule).totalBalance();\n        if (_negativeYield <= lockingReceiptTokens) {\n            LockingController(lockingModule).applyLosses(_negativeYield);\n            return;\n        }\n        LockingController(lockingModule).applyLosses(lockingReceiptTokens);\n        _negativeYield -= lockingReceiptTokens;\n\n        // second, apply negativeYield to siUSD holders\n        uint256 stakedReceiptTokens = ReceiptToken(receiptToken).balanceOf(stakedToken);\n        if (_negativeYield <= stakedReceiptTokens) {\n            StakedToken(stakedToken).applyLosses(_negativeYield);\n            return;\n        }\n        StakedToken(stakedToken).applyLosses(stakedReceiptTokens);\n        _negativeYield -= stakedReceiptTokens;\n\n        // lastly, apply losses to all iUSD in circulation\n        uint256 totalSupply = ReceiptToken(receiptToken).totalSupply();\n        address oracle = Accounting(accounting).oracle(receiptToken);\n        uint256 price = FixedPriceOracle(oracle).price();\n        uint256 newPrice = price.mulDivDown(totalSupply - _negativeYield, totalSupply);\n        FixedPriceOracle(oracle).setPrice(newPrice);\n    }\n\n    function migrateSafetyBuffer(address _source) external onlyCoreRole(CoreRoles.GOVERNOR) {\n        uint256 sourceBalance = ReceiptToken(receiptToken).balanceOf(_source);\n        uint256 sourceAllowance = ReceiptToken(receiptToken).allowance(_source, address(this));\n        uint256 amount = sourceAllowance < sourceBalance ? sourceAllowance : sourceBalance;\n        if (amount > 0) {\n            // forge-lint: disable-next-line(erc20-unchecked-transfer)\n            ReceiptToken(receiptToken).transferFrom(_source, address(this), amount);\n        }\n    }\n\n    /// @notice flush the excess safety buffer\n    /// @param _recipient The recipient of the excess safety buffer\n    /// @dev the recipient can be:\n    /// - address(0) to distribute the excess as yield normally,\n    /// - stakedToken to distribute the excess as yield to siUSD holders,\n    /// - lockingModule to distribute the excess as yield to liUSD holders,\n    /// - or any other address to send the excess to.\n    /// @dev note that yield distributed through this function is ignoring the performance fee\n    function flushExcessSafetyBuffer(address _recipient, uint256 _maxFlushAmount)\n        external\n        whenNotPaused\n        onlyCoreRole(CoreRoles.ACCRUE_YIELD)\n    {\n        _accrue();\n\n        uint256 balance = ReceiptToken(receiptToken).balanceOf(address(this));\n        uint256 _safetyBufferSize = safetyBufferSize;\n        uint256 excess = balance > _safetyBufferSize ? balance - _safetyBufferSize : 0;\n        if (excess == 0) return;\n\n        if (_maxFlushAmount > 0 && excess > _maxFlushAmount) excess = _maxFlushAmount;\n\n        // case 1: recipient is address(0): distribute excess as yield normally\n        if (_recipient == address(0)) {\n            _handlePositiveYield(excess, false, false);\n        }\n        // case 1: recipient is siUSD: distribute excess as yield to siUSD holders\n        else if (_recipient == stakedToken) {\n            // forge-lint: disable-next-line(erc20-unchecked-transfer)\n            ReceiptToken(receiptToken).transfer(address(escrow), excess);\n            // casting to 'uint208' is safe because type(uint208).max would be\n            // an outrageously large rate per second\n            // forge-lint: disable-next-line(unsafe-typecast)\n            point.rate = uint208(vesting() / interpolationDuration);\n            point.lastAccrued = uint32(block.timestamp);\n        }\n        // case 2: recipient is lockingModule: distribute excess as yield to liUSD holders\n        else if (_recipient == lockingModule) {\n            LockingController(lockingModule).depositRewards(excess);\n        }\n        // case 3: recipient is other: send excess to recipient\n        else {\n            // receipt token always returns true or revert\n            // forge-lint: disable-next-line(erc20-unchecked-transfer)\n            ReceiptToken(receiptToken).transfer(_recipient, excess);\n        }\n\n        emit ExcessSafetyBufferFlushed(block.timestamp, _recipient, excess);\n    }\n}\n","creation_status":"success","file_path":"src/finance/YieldSharingV3.sol"}