{"constructor_args":null,"is_partially_verified":true,"is_changed_bytecode":false,"abi":[{"inputs":[],"name":"EnforcedPause","type":"error"},{"inputs":[],"name":"ExpectedPause","type":"error"},{"inputs":[{"internalType":"uint256","name":"required","type":"uint256"},{"internalType":"uint256","name":"provided","type":"uint256"}],"name":"InsufficientBridgeFee","type":"error"},{"inputs":[],"name":"InvalidZapFee","type":"error"},{"inputs":[],"name":"InvalidZapRouter","type":"error"},{"inputs":[{"internalType":"uint256","name":"min","type":"uint256"},{"internalType":"uint256","name":"actual","type":"uint256"}],"name":"MinAssetsOutError","type":"error"},{"inputs":[],"name":"PendingLossesUnapplied","type":"error"},{"inputs":[],"name":"ReentrancyGuardReentrantCall","type":"error"},{"inputs":[{"internalType":"address","name":"token","type":"address"}],"name":"SafeERC20FailedOperation","type":"error"},{"inputs":[],"name":"SwapFailed","type":"error"},{"inputs":[{"internalType":"bytes","name":"returnData","type":"bytes"}],"name":"UnderlyingCallReverted","type":"error"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"timestamp","type":"uint256"},{"indexed":true,"internalType":"string","name":"name","type":"string"},{"indexed":false,"internalType":"address","name":"_address","type":"address"}],"name":"AddressSet","type":"event"},{"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":false,"internalType":"address","name":"account","type":"address"}],"name":"Paused","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"timestamp","type":"uint256"},{"indexed":false,"internalType":"address","name":"router","type":"address"},{"indexed":false,"internalType":"bool","name":"enabled","type":"bool"}],"name":"SetEnabledRouter","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"account","type":"address"}],"name":"Unpaused","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"timestamp","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"zapFee","type":"uint256"}],"name":"ZapFeeSet","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"timestamp","type":"uint256"},{"indexed":true,"internalType":"address","name":"user","type":"address"},{"indexed":true,"internalType":"address","name":"token","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"receiptTokens","type":"uint256"}],"name":"ZapIn","type":"event"},{"inputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"name":"addresses","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_targetChainId","type":"uint256"},{"internalType":"address","name":"_token","type":"address"},{"internalType":"uint256","name":"_amount","type":"uint256"},{"internalType":"address","name":"_recipient","type":"address"},{"internalType":"address payable","name":"_connector","type":"address"}],"name":"bridge","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_unwindingTimestamp","type":"uint256"},{"internalType":"uint32","name":"_newUnwindingEpochs","type":"uint32"}],"name":"cancelInfiWithdrawal","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_unwindingTimestamp","type":"uint256"},{"internalType":"uint32","name":"_newUnwindingEpochs","type":"uint32"}],"name":"cancelUnwinding","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"claimRedemption","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_user","type":"address"},{"internalType":"uint256","name":"_unwindingTimestamp","type":"uint256"}],"name":"completeInfiWithdrawal","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"core","outputs":[{"internalType":"contract InfiniFiCore","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_amount","type":"uint256"},{"internalType":"uint32","name":"_unwindingEpochs","type":"uint32"},{"internalType":"address","name":"_recipient","type":"address"}],"name":"createPosition","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":[{"internalType":"address","name":"","type":"address"}],"name":"enabledRouters","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"string","name":"_name","type":"string"}],"name":"getAddress","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint32","name":"_oldUnwindingEpochs","type":"uint32"},{"internalType":"uint32","name":"_newUnwindingEpochs","type":"uint32"},{"internalType":"uint256","name":"_shares","type":"uint256"}],"name":"increaseInfiWithdrawalPeriod","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint32","name":"_oldUnwindingEpochs","type":"uint32"},{"internalType":"uint32","name":"_newUnwindingEpochs","type":"uint32"},{"internalType":"uint256","name":"_shares","type":"uint256"}],"name":"increaseUnwindingEpochs","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_core","type":"address"}],"name":"init","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_amount","type":"uint256"},{"internalType":"uint32","name":"_unwindingEpochs","type":"uint32"}],"name":"lockInfi","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_farm","type":"address"},{"internalType":"address","name":"_token","type":"address"},{"internalType":"uint256","name":"_amount","type":"uint256"},{"internalType":"uint32","name":"_unwindingEpochs","type":"uint32"},{"internalType":"uint256","name":"_minIusdReceived","type":"uint256"}],"name":"migrate","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_to","type":"address"},{"internalType":"uint256","name":"_amount","type":"uint256"}],"name":"mint","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_to","type":"address"},{"internalType":"uint256","name":"_amount","type":"uint256"},{"internalType":"uint32","name":"_unwindingEpochs","type":"uint32"}],"name":"mintAndLock","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_to","type":"address"},{"internalType":"uint256","name":"_amount","type":"uint256"}],"name":"mintAndStake","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address[]","name":"_assets","type":"address[]"},{"internalType":"uint32[]","name":"_unwindingEpochs","type":"uint32[]"},{"components":[{"internalType":"address","name":"farm","type":"address"},{"internalType":"uint96","name":"weight","type":"uint96"}],"internalType":"struct AllocationVoting.AllocationVote[][]","name":"_liquidVotes","type":"tuple[][]"},{"components":[{"internalType":"address","name":"farm","type":"address"},{"internalType":"uint96","name":"weight","type":"uint96"}],"internalType":"struct AllocationVoting.AllocationVote[][]","name":"_illiquidVotes","type":"tuple[][]"}],"name":"multiVote","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":[{"internalType":"address","name":"_to","type":"address"},{"internalType":"uint256","name":"_amount","type":"uint256"},{"internalType":"uint256","name":"_minAssetsOut","type":"uint256"}],"name":"redeem","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"string","name":"_name","type":"string"},{"internalType":"address","name":"_address","type":"address"}],"name":"setAddress","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newCore","type":"address"}],"name":"setCore","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_router","type":"address"},{"internalType":"bool","name":"_enabled","type":"bool"}],"name":"setEnabledRouter","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_zapFee","type":"uint256"}],"name":"setZapFee","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_to","type":"address"},{"internalType":"uint256","name":"_receiptTokens","type":"uint256"}],"name":"stake","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_shares","type":"uint256"},{"internalType":"uint32","name":"_unwindingEpochs","type":"uint32"}],"name":"startInfiWithdrawal","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_shares","type":"uint256"},{"internalType":"uint32","name":"_unwindingEpochs","type":"uint32"}],"name":"startUnwinding","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"unpause","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_to","type":"address"},{"internalType":"uint256","name":"_stakedTokens","type":"uint256"}],"name":"unstake","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_to","type":"address"},{"internalType":"uint256","name":"_amount","type":"uint256"},{"internalType":"uint32","name":"_unwindingEpochs","type":"uint32"}],"name":"unstakeAndLock","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_asset","type":"address"},{"internalType":"uint32","name":"_unwindingEpochs","type":"uint32"},{"components":[{"internalType":"address","name":"farm","type":"address"},{"internalType":"uint96","name":"weight","type":"uint96"}],"internalType":"struct AllocationVoting.AllocationVote[]","name":"_liquidVotes","type":"tuple[]"},{"components":[{"internalType":"address","name":"farm","type":"address"},{"internalType":"uint96","name":"weight","type":"uint96"}],"internalType":"struct AllocationVoting.AllocationVote[]","name":"_illiquidVotes","type":"tuple[]"}],"name":"vote","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_unwindingTimestamp","type":"uint256"}],"name":"withdraw","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_user","type":"address"},{"internalType":"uint256","name":"_unwindingTimestamp","type":"uint256"}],"name":"withdraw","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"zapFee","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_token","type":"address"},{"internalType":"uint256","name":"_amount","type":"uint256"},{"internalType":"address","name":"_router","type":"address"},{"internalType":"bytes","name":"_routerData","type":"bytes"},{"internalType":"address","name":"_to","type":"address"}],"name":"zapIn","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"_token","type":"address"},{"internalType":"uint256","name":"_amount","type":"uint256"},{"internalType":"address","name":"_router","type":"address"},{"internalType":"bytes","name":"_routerData","type":"bytes"},{"internalType":"uint32","name":"_unwindingEpochs","type":"uint32"},{"internalType":"address","name":"_to","type":"address"}],"name":"zapInAndLock","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"_token","type":"address"},{"internalType":"uint256","name":"_amount","type":"uint256"},{"internalType":"address","name":"_router","type":"address"},{"internalType":"bytes","name":"_routerData","type":"bytes"},{"internalType":"address","name":"_to","type":"address"}],"name":"zapInAndStake","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"payable","type":"function"}],"conflicting_implementations":null,"certified":false,"additional_sources":[{"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":"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/interfaces/IInfiniFiGateway.sol","source_code":"// SPDX-License-Identifier: MIT\npragma solidity 0.8.28;\n\nimport {AllocationVoting} from \"@governance/AllocationVoting.sol\";\n\n/// @notice Interface for the InfiniFi gateway\ninterface IInfiniFiGateway {\n    function setAddress(string memory _name, address _address) external;\n\n    function getAddress(string memory _name) external view returns (address);\n\n    function setEnabledRouter(address _router, bool _enabled) external;\n\n    function setZapFee(uint256 _zapFee) external;\n\n    function addresses(bytes32 _key) external view returns (address);\n\n    function enabledRouters(address _router) external view returns (bool);\n\n    function zapFee() external view returns (uint256);\n\n    function mint(address _to, uint256 _amount) external returns (uint256);\n\n    function mintAndStake(address _to, uint256 _amount) external returns (uint256);\n\n    function stake(address _to, uint256 _receiptTokens) external returns (uint256);\n\n    function unstake(address _to, uint256 _stakedTokens) external returns (uint256);\n\n    function zapIn(address _token, uint256 _amount, address _router, bytes calldata _routerData, address _to)\n        external\n        payable\n        returns (uint256);\n\n    function zapInAndStake(address _token, uint256 _amount, address _router, bytes calldata _routerData, address _to)\n        external\n        payable\n        returns (uint256);\n\n    function zapInAndLock(\n        address _token,\n        uint256 _amount,\n        address _router,\n        bytes calldata _routerData,\n        uint32 _unwindingEpochs,\n        address _to\n    ) external payable returns (uint256);\n\n    function mintAndLock(address _to, uint256 _amount, uint32 _unwindingEpochs) external returns (uint256);\n\n    function unstakeAndLock(address _to, uint256 _amount, uint32 _unwindingEpochs) external returns (uint256);\n\n    function createPosition(uint256 _amount, uint32 _unwindingEpochs, address _recipient) external;\n\n    function startUnwinding(uint256 _shares, uint32 _unwindingEpochs) external;\n\n    function increaseUnwindingEpochs(uint32 _oldUnwindingEpochs, uint32 _newUnwindingEpochs, uint256 _shares) external;\n\n    function cancelUnwinding(uint256 _unwindingTimestamp, uint32 _newUnwindingEpochs) external;\n\n    function withdraw(uint256 _unwindingTimestamp) external;\n\n    function redeem(address _to, uint256 _amount, uint256 _minAssetsOut) external returns (uint256);\n\n    function claimRedemption() external;\n\n    function vote(\n        address _asset,\n        uint32 _unwindingEpochs,\n        AllocationVoting.AllocationVote[] calldata _liquidVotes,\n        AllocationVoting.AllocationVote[] calldata _illiquidVotes\n    ) external;\n\n    function multiVote(\n        address[] calldata _assets,\n        uint32[] calldata _unwindingEpochs,\n        AllocationVoting.AllocationVote[][] calldata _liquidVotes,\n        AllocationVoting.AllocationVote[][] calldata _illiquidVotes\n    ) external;\n\n    function migrate(address _farm, address _token, uint256 _amount, uint32 _unwindingEpochs) external returns (uint256);\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":"lib/LayerZero-v2/packages/layerzero-v2/evm/oapp/contracts/oapp/interfaces/IOAppOptionsType3.sol","source_code":"// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Struct representing enforced option parameters.\n */\nstruct EnforcedOptionParam {\n    uint32 eid; // Endpoint ID\n    uint16 msgType; // Message Type\n    bytes options; // Additional options\n}\n\n/**\n * @title IOAppOptionsType3\n * @dev Interface for the OApp with Type 3 Options, allowing the setting and combining of enforced options.\n */\ninterface IOAppOptionsType3 {\n    // Custom error message for invalid options\n    error InvalidOptions(bytes options);\n\n    // Event emitted when enforced options are set\n    event EnforcedOptionSet(EnforcedOptionParam[] _enforcedOptions);\n\n    /**\n     * @notice Sets enforced options for specific endpoint and message type combinations.\n     * @param _enforcedOptions An array of EnforcedOptionParam structures specifying enforced options.\n     */\n    function setEnforcedOptions(EnforcedOptionParam[] calldata _enforcedOptions) external;\n\n    /**\n     * @notice Combines options for a given endpoint and message type.\n     * @param _eid The endpoint ID.\n     * @param _msgType The OApp message type.\n     * @param _extraOptions Additional options passed by the caller.\n     * @return options The combination of caller specified options AND enforced options.\n     */\n    function combineOptions(\n        uint32 _eid,\n        uint16 _msgType,\n        bytes calldata _extraOptions\n    ) external view returns (bytes memory options);\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":"src/gateway/InfiniFiGatewayV1.sol","source_code":"// SPDX-License-Identifier: MIT\npragma solidity 0.8.28;\n\nimport {FixedPointMathLib} from \"@solmate/src/utils/FixedPointMathLib.sol\";\n\nimport {ERC20} from \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\nimport {SafeERC20} from \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\nimport {ReentrancyGuardTransient} from \"@openzeppelin/contracts/utils/ReentrancyGuardTransient.sol\";\n\nimport {CoreRoles} from \"@libraries/CoreRoles.sol\";\nimport {StakedToken} from \"@tokens/StakedToken.sol\";\nimport {ReceiptToken} from \"@tokens/ReceiptToken.sol\";\nimport {CoreControlled} from \"@core/CoreControlled.sol\";\nimport {MintController} from \"@funding/MintController.sol\";\nimport {RedeemController} from \"@funding/RedeemController.sol\";\nimport {AllocationVoting} from \"@governance/AllocationVoting.sol\";\nimport {LockingController} from \"@locking/LockingController.sol\";\nimport {LockedPositionToken} from \"@tokens/LockedPositionToken.sol\";\nimport {YieldSharing} from \"@finance/YieldSharing.sol\";\n\n/// @notice Gateway to interact with the InfiniFi protocol\ncontract InfiniFiGatewayV1 is CoreControlled, ReentrancyGuardTransient {\n    using SafeERC20 for ERC20;\n    using FixedPointMathLib 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 error thrown when a swap fails\n    error SwapFailed();\n    error InvalidZapFee();\n    error InvalidZapRouter();\n    error MinAssetsOutError(uint256 min, uint256 actual);\n\n    event AddressSet(uint256 timestamp, string indexed name, address _address);\n    event ZapFeeSet(uint256 timestamp, uint256 zapFee);\n    event ZapIn(uint256 timestamp, address indexed user, address indexed token, uint256 amount, uint256 receiptTokens);\n    event SetEnabledRouter(uint256 timestamp, address router, bool enabled);\n\n    /// @notice address registry of the gateway\n    mapping(bytes32 => address) public addresses;\n\n    /// @notice Mapping of routers that can be used to zap\n    mapping(address => bool) public enabledRouters;\n\n    /// @notice fee charged for zaps, as a percentage with 18 decimals\n    uint256 public zapFee;\n\n    constructor() CoreControlled(address(1)) {}\n\n    /// @notice initializer for the proxy storage\n    function init(address _core) external {\n        assert(address(core()) == address(0));\n        _setCore(_core);\n    }\n\n    /// -------------------------------------------------------------------------------------\n    /// Configuration\n    /// -------------------------------------------------------------------------------------\n\n    /// @notice set an address for a given name\n    function setAddress(string memory _name, address _address) external onlyCoreRole(CoreRoles.GOVERNOR) {\n        addresses[keccak256(abi.encode(_name))] = _address;\n        emit AddressSet(block.timestamp, _name, _address);\n    }\n\n    /// @notice get an address for a given name\n    function getAddress(string memory _name) public view returns (address) {\n        return addresses[keccak256(abi.encode(_name))];\n    }\n\n    /// @notice manage the whitelist of routers to be used by the zap functions\n    function setEnabledRouter(address _router, bool _enabled) external onlyCoreRole(CoreRoles.PROTOCOL_PARAMETERS) {\n        enabledRouters[_router] = _enabled;\n        emit SetEnabledRouter(block.timestamp, _router, _enabled);\n    }\n\n    /// @notice set the fee charged for zaps\n    function setZapFee(uint256 _zapFee) external onlyCoreRole(CoreRoles.PROTOCOL_PARAMETERS) {\n        require(_zapFee <= 0.01e18, InvalidZapFee()); // cannot set to more than 1%\n        zapFee = _zapFee;\n        emit ZapFeeSet(block.timestamp, _zapFee);\n    }\n\n    /// -------------------------------------------------------------------------------------\n    /// User interactions\n    /// -------------------------------------------------------------------------------------\n\n    function mint(address _to, uint256 _amount) external whenNotPaused nonReentrant returns (uint256) {\n        ERC20 usdc = ERC20(getAddress(\"USDC\"));\n        MintController mintController = MintController(getAddress(\"mintController\"));\n\n        usdc.safeTransferFrom(msg.sender, address(this), _amount);\n        usdc.approve(address(mintController), _amount);\n        return mintController.mint(_to, _amount);\n    }\n\n    function mintAndStake(address _to, uint256 _amount) external whenNotPaused nonReentrant returns (uint256) {\n        MintController mintController = MintController(getAddress(\"mintController\"));\n        StakedToken siusd = StakedToken(getAddress(\"stakedToken\"));\n        ReceiptToken iusd = ReceiptToken(getAddress(\"receiptToken\"));\n        ERC20 usdc = ERC20(getAddress(\"USDC\"));\n\n        usdc.safeTransferFrom(msg.sender, address(this), _amount);\n        usdc.approve(address(mintController), _amount);\n        uint256 receiptTokens = mintController.mint(address(this), _amount);\n\n        iusd.approve(address(siusd), receiptTokens);\n        siusd.deposit(receiptTokens, _to);\n        return receiptTokens;\n    }\n\n    function _zapToReceiptTokens(address _token, uint256 _amount, address _router, bytes calldata _routerData)\n        internal\n        returns (uint256, ReceiptToken)\n    {\n        require(enabledRouters[_router], InvalidZapRouter());\n\n        // pull in the tokens and approve the router if not using native ETH\n        if (_token != address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)) {\n            ERC20(_token).safeTransferFrom(msg.sender, address(this), _amount);\n            ERC20(_token).forceApprove(address(_router), _amount);\n        }\n\n        // perform swap to USDC\n        (bool swapSuccess,) = _router.call{value: msg.value}(_routerData);\n        require(swapSuccess, SwapFailed());\n\n        // read the protocol addresses from storage\n        MintController mintController = MintController(getAddress(\"mintController\"));\n        ERC20 usdc = ERC20(getAddress(\"USDC\"));\n        ReceiptToken iusd = ReceiptToken(getAddress(\"receiptToken\"));\n\n        // mint iUSD\n        uint256 usdcReceived = usdc.balanceOf(address(this));\n        usdc.approve(address(mintController), usdcReceived);\n        uint256 receiptTokens = mintController.mint(address(this), usdcReceived);\n\n        {\n            uint256 _zapFee = zapFee;\n            if (_zapFee != 0) {\n                uint256 fee = receiptTokens.mulWadDown(_zapFee);\n                receiptTokens -= fee;\n                // forge-lint: disable-next-line(erc20-unchecked-transfer)\n                iusd.transfer(getAddress(\"yieldSharing\"), fee);\n            }\n        }\n\n        emit ZapIn(block.timestamp, msg.sender, _token, _amount, receiptTokens);\n\n        return (receiptTokens, iusd);\n    }\n\n    function zapIn(address _token, uint256 _amount, address _router, bytes calldata _routerData, address _to)\n        external\n        payable\n        whenNotPaused\n        nonReentrant\n        returns (uint256)\n    {\n        (uint256 receiptTokens, ReceiptToken iusd) = _zapToReceiptTokens(_token, _amount, _router, _routerData);\n\n        // send iUSD to receiver\n        // forge-lint: disable-next-line(erc20-unchecked-transfer)\n        iusd.transfer(_to, receiptTokens);\n        return receiptTokens;\n    }\n\n    function zapInAndStake(address _token, uint256 _amount, address _router, bytes calldata _routerData, address _to)\n        external\n        payable\n        whenNotPaused\n        nonReentrant\n        returns (uint256)\n    {\n        (uint256 receiptTokens, ReceiptToken iusd) = _zapToReceiptTokens(_token, _amount, _router, _routerData);\n\n        // read the protocol addresses from storage\n        StakedToken siusd = StakedToken(getAddress(\"stakedToken\"));\n\n        // mint iUSD and stake it to siUSD\n        iusd.approve(address(siusd), receiptTokens);\n        siusd.deposit(receiptTokens, _to);\n        return receiptTokens;\n    }\n\n    function zapInAndLock(\n        address _token,\n        uint256 _amount,\n        address _router,\n        bytes calldata _routerData,\n        uint32 _unwindingEpochs,\n        address _to\n    ) external payable whenNotPaused nonReentrant returns (uint256) {\n        (uint256 receiptTokens, ReceiptToken iusd) = _zapToReceiptTokens(_token, _amount, _router, _routerData);\n\n        // read the protocol addresses from storage\n        LockingController lockingController = LockingController(getAddress(\"lockingController\"));\n\n        // lock the iUSD\n        iusd.approve(address(lockingController), receiptTokens);\n        lockingController.createPosition(receiptTokens, _unwindingEpochs, _to);\n        return receiptTokens;\n    }\n\n    function mintAndLock(address _to, uint256 _amount, uint32 _unwindingEpochs)\n        external\n        whenNotPaused\n        nonReentrant\n        returns (uint256)\n    {\n        MintController mintController = MintController(getAddress(\"mintController\"));\n        ReceiptToken iusd = ReceiptToken(getAddress(\"receiptToken\"));\n        LockingController lockingController = LockingController(getAddress(\"lockingController\"));\n        ERC20 usdc = ERC20(getAddress(\"USDC\"));\n\n        usdc.safeTransferFrom(msg.sender, address(this), _amount);\n        usdc.approve(address(mintController), _amount);\n        uint256 receiptTokens = mintController.mint(address(this), _amount);\n\n        iusd.approve(address(lockingController), receiptTokens);\n        lockingController.createPosition(receiptTokens, _unwindingEpochs, _to);\n        return receiptTokens;\n    }\n\n    function unstakeAndLock(address _to, uint256 _amount, uint32 _unwindingEpochs)\n        external\n        whenNotPaused\n        nonReentrant\n        returns (uint256)\n    {\n        ReceiptToken iusd = ReceiptToken(getAddress(\"receiptToken\"));\n        StakedToken siusd = StakedToken(getAddress(\"stakedToken\"));\n        LockingController lockingController = LockingController(getAddress(\"lockingController\"));\n\n        // forge-lint: disable-next-line(erc20-unchecked-transfer)\n        siusd.transferFrom(msg.sender, address(this), _amount);\n        uint256 receiptTokens = siusd.redeem(_amount, address(this), address(this));\n\n        iusd.approve(address(lockingController), receiptTokens);\n        lockingController.createPosition(receiptTokens, _unwindingEpochs, _to);\n        return receiptTokens;\n    }\n\n    function createPosition(uint256 _amount, uint32 _unwindingEpochs, address _recipient)\n        external\n        whenNotPaused\n        nonReentrant\n    {\n        ReceiptToken iusd = ReceiptToken(getAddress(\"receiptToken\"));\n        LockingController lockingController = LockingController(getAddress(\"lockingController\"));\n\n        // forge-lint: disable-next-line(erc20-unchecked-transfer)\n        iusd.transferFrom(msg.sender, address(this), _amount);\n        iusd.approve(address(lockingController), _amount);\n        lockingController.createPosition(_amount, _unwindingEpochs, _recipient);\n    }\n\n    function startUnwinding(uint256 _shares, uint32 _unwindingEpochs) external whenNotPaused nonReentrant {\n        LockingController lockingController = LockingController(getAddress(\"lockingController\"));\n        LockedPositionToken liusd = LockedPositionToken(lockingController.shareToken(_unwindingEpochs));\n\n        // forge-lint: disable-next-line(erc20-unchecked-transfer)\n        liusd.transferFrom(msg.sender, address(this), _shares);\n        liusd.approve(address(lockingController), _shares);\n        lockingController.startUnwinding(_shares, _unwindingEpochs, msg.sender);\n    }\n\n    function increaseUnwindingEpochs(uint32 _oldUnwindingEpochs, uint32 _newUnwindingEpochs, uint256 _shares)\n        external\n        whenNotPaused\n        nonReentrant\n    {\n        LockingController lockingController = LockingController(getAddress(\"lockingController\"));\n        LockedPositionToken liusd = LockedPositionToken(lockingController.shareToken(_oldUnwindingEpochs));\n\n        // forge-lint: disable-next-line(erc20-unchecked-transfer)\n        liusd.transferFrom(msg.sender, address(this), _shares);\n        liusd.approve(address(lockingController), _shares);\n        lockingController.increaseUnwindingEpochs(_shares, _oldUnwindingEpochs, _newUnwindingEpochs, msg.sender);\n    }\n\n    function cancelUnwinding(uint256 _unwindingTimestamp, uint32 _newUnwindingEpochs)\n        external\n        whenNotPaused\n        nonReentrant\n    {\n        LockingController(getAddress(\"lockingController\"))\n            .cancelUnwinding(msg.sender, _unwindingTimestamp, _newUnwindingEpochs);\n    }\n\n    function withdraw(uint256 _unwindingTimestamp) external whenNotPaused nonReentrant {\n        _revertIfThereAreUnaccruedLosses();\n        LockingController(getAddress(\"lockingController\")).withdraw(msg.sender, _unwindingTimestamp);\n    }\n\n    function redeem(address _to, uint256 _amount, uint256 _minAssetsOut)\n        external\n        whenNotPaused\n        nonReentrant\n        returns (uint256)\n    {\n        _revertIfThereAreUnaccruedLosses();\n        ReceiptToken iusd = ReceiptToken(getAddress(\"receiptToken\"));\n        RedeemController redeemController = RedeemController(getAddress(\"redeemController\"));\n\n        // forge-lint: disable-next-line(erc20-unchecked-transfer)\n        iusd.transferFrom(msg.sender, address(this), _amount);\n        iusd.approve(address(redeemController), _amount);\n        uint256 assetsOut = redeemController.redeem(_to, _amount);\n        require(assetsOut >= _minAssetsOut, MinAssetsOutError(_minAssetsOut, assetsOut));\n        return assetsOut;\n    }\n\n    function claimRedemption() external whenNotPaused nonReentrant {\n        RedeemController(getAddress(\"redeemController\")).claimRedemption(msg.sender);\n    }\n\n    function vote(\n        address _asset,\n        uint32 _unwindingEpochs,\n        AllocationVoting.AllocationVote[] calldata _liquidVotes,\n        AllocationVoting.AllocationVote[] calldata _illiquidVotes\n    ) external whenNotPaused nonReentrant {\n        AllocationVoting(getAddress(\"allocationVoting\"))\n            .vote(msg.sender, _asset, _unwindingEpochs, _liquidVotes, _illiquidVotes);\n    }\n\n    function multiVote(\n        address[] calldata _assets,\n        uint32[] calldata _unwindingEpochs,\n        AllocationVoting.AllocationVote[][] calldata _liquidVotes,\n        AllocationVoting.AllocationVote[][] calldata _illiquidVotes\n    ) external whenNotPaused nonReentrant {\n        AllocationVoting allocationVoting = AllocationVoting(getAddress(\"allocationVoting\"));\n\n        for (uint256 i = 0; i < _assets.length; i++) {\n            allocationVoting.vote(msg.sender, _assets[i], _unwindingEpochs[i], _liquidVotes[i], _illiquidVotes[i]);\n        }\n    }\n\n    function _revertIfThereAreUnaccruedLosses() internal view {\n        YieldSharing yieldSharing = YieldSharing(getAddress(\"yieldSharing\"));\n        require(yieldSharing.unaccruedYield() >= 0, PendingLossesUnapplied());\n    }\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/LayerZero-v2/packages/layerzero-v2/evm/oapp/contracts/oapp/libs/OAppOptionsType3.sol","source_code":"// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.20;\n\nimport { Ownable } from \"@openzeppelin/contracts/access/Ownable.sol\";\nimport { IOAppOptionsType3, EnforcedOptionParam } from \"../interfaces/IOAppOptionsType3.sol\";\n\n/**\n * @title OAppOptionsType3\n * @dev Abstract contract implementing the IOAppOptionsType3 interface with type 3 options.\n */\nabstract contract OAppOptionsType3 is IOAppOptionsType3, Ownable {\n    uint16 internal constant OPTION_TYPE_3 = 3;\n\n    // @dev The \"msgType\" should be defined in the child contract.\n    mapping(uint32 eid => mapping(uint16 msgType => bytes enforcedOption)) public enforcedOptions;\n\n    /**\n     * @dev Sets the enforced options for specific endpoint and message type combinations.\n     * @param _enforcedOptions An array of EnforcedOptionParam structures specifying enforced options.\n     *\n     * @dev Only the owner/admin of the OApp can call this function.\n     * @dev Provides a way for the OApp to enforce things like paying for PreCrime, AND/OR minimum dst lzReceive gas amounts etc.\n     * @dev These enforced options can vary as the potential options/execution on the remote may differ as per the msgType.\n     * eg. Amount of lzReceive() gas necessary to deliver a lzCompose() message adds overhead you dont want to pay\n     * if you are only making a standard LayerZero message ie. lzReceive() WITHOUT sendCompose().\n     */\n    function setEnforcedOptions(EnforcedOptionParam[] calldata _enforcedOptions) public virtual onlyOwner {\n        _setEnforcedOptions(_enforcedOptions);\n    }\n\n    /**\n     * @dev Sets the enforced options for specific endpoint and message type combinations.\n     * @param _enforcedOptions An array of EnforcedOptionParam structures specifying enforced options.\n     *\n     * @dev Provides a way for the OApp to enforce things like paying for PreCrime, AND/OR minimum dst lzReceive gas amounts etc.\n     * @dev These enforced options can vary as the potential options/execution on the remote may differ as per the msgType.\n     * eg. Amount of lzReceive() gas necessary to deliver a lzCompose() message adds overhead you dont want to pay\n     * if you are only making a standard LayerZero message ie. lzReceive() WITHOUT sendCompose().\n     */\n    function _setEnforcedOptions(EnforcedOptionParam[] memory _enforcedOptions) internal virtual {\n        for (uint256 i = 0; i < _enforcedOptions.length; i++) {\n            // @dev Enforced options are only available for optionType 3, as type 1 and 2 dont support combining.\n            _assertOptionsType3(_enforcedOptions[i].options);\n            enforcedOptions[_enforcedOptions[i].eid][_enforcedOptions[i].msgType] = _enforcedOptions[i].options;\n        }\n\n        emit EnforcedOptionSet(_enforcedOptions);\n    }\n\n    /**\n     * @notice Combines options for a given endpoint and message type.\n     * @param _eid The endpoint ID.\n     * @param _msgType The OAPP message type.\n     * @param _extraOptions Additional options passed by the caller.\n     * @return options The combination of caller specified options AND enforced options.\n     *\n     * @dev If there is an enforced lzReceive option:\n     * - {gasLimit: 200k, msg.value: 1 ether} AND a caller supplies a lzReceive option: {gasLimit: 100k, msg.value: 0.5 ether}\n     * - The resulting options will be {gasLimit: 300k, msg.value: 1.5 ether} when the message is executed on the remote lzReceive() function.\n     * @dev This presence of duplicated options is handled off-chain in the verifier/executor.\n     */\n    function combineOptions(\n        uint32 _eid,\n        uint16 _msgType,\n        bytes calldata _extraOptions\n    ) public view virtual returns (bytes memory) {\n        bytes memory enforced = enforcedOptions[_eid][_msgType];\n\n        // No enforced options, pass whatever the caller supplied, even if it's empty or legacy type 1/2 options.\n        if (enforced.length == 0) return _extraOptions;\n\n        // No caller options, return enforced\n        if (_extraOptions.length == 0) return enforced;\n\n        // @dev If caller provided _extraOptions, must be type 3 as its the ONLY type that can be combined.\n        if (_extraOptions.length >= 2) {\n            _assertOptionsType3(_extraOptions);\n            // @dev Remove the first 2 bytes containing the type from the _extraOptions and combine with enforced.\n            return bytes.concat(enforced, _extraOptions[2:]);\n        }\n\n        // No valid set of options was found.\n        revert InvalidOptions(_extraOptions);\n    }\n\n    /**\n     * @dev Internal function to assert that options are of type 3.\n     * @param _options The options to be checked.\n     */\n    function _assertOptionsType3(bytes memory _options) internal pure virtual {\n        uint16 optionsType;\n        assembly {\n            optionsType := mload(add(_options, 2))\n        }\n        if (optionsType != OPTION_TYPE_3) revert InvalidOptions(_options);\n    }\n}\n"},{"file_path":"src/funding/RedemptionPool.sol","source_code":"// SPDX-License-Identifier: MIT\npragma solidity 0.8.28;\n\nimport {RedemptionQueue} from \"@libraries/RedemptionQueue.sol\";\nimport {FixedPointMathLib} from \"@solmate/src/utils/FixedPointMathLib.sol\";\n\n/// @notice This contract is used to manage the redemption queue for a given collateral.\n/// @dev Should be inherited by the LiabilityController\n/// @dev This contract does not manage any token transfer or burn, it just manages the queue and the pending redemptions.\n/// @dev handling tokens MUST be done by the contract inheriting this one.\nabstract contract RedemptionPool {\n    using RedemptionQueue for RedemptionQueue.RedemptionRequestsQueue;\n    using FixedPointMathLib for uint256;\n\n    /// ------------------- ERRORS -------------------\n    error FundingAmountZero();\n    error EnqueueAmountZero();\n    error NoPendingClaims(address _recipient);\n    error QueueTooLong();\n    error EnqueueAmountTooLarge();\n\n    /// ------------------- EVENTS -------------------\n    event RedemptionQueued(uint256 indexed timestamp, address recipient, uint256 amount);\n    event RedemptionPartiallyFunded(uint256 indexed timestamp, address recipient, uint256 amount);\n    event RedemptionFunded(uint256 indexed timestamp, address recipient, uint256 amount);\n    event RedemptionClaimed(uint256 indexed timestamp, address recipient, uint256 amount);\n\n    /// ------------------- STATE -------------------\n    /// @notice the redemption queue\n    RedemptionQueue.RedemptionRequestsQueue public queue;\n\n    uint256 public constant MAX_QUEUE_LENGTH = 10000;\n\n    /// @notice mapping from recipient => available claim\n    mapping(address recipient => uint256 assetAmount) public userPendingClaims;\n\n    /// @notice total available redemptions\n    /// @dev this is the amount of asset (USDC, ETH) that is currently redeemable and should be held by this contract\n    uint256 public totalPendingClaims;\n\n    /// @notice total enqueued redemptions\n    /// @dev this is the amount of receipt token (iUSD, iETH) that is currently enqueued and waiting to be redeemed\n    uint256 public totalEnqueuedRedemptions;\n\n    /// @notice returns the length of the queue\n    /// aka the number of ticket waiting to be funded\n    function queueLength() public view returns (uint256) {\n        return queue.length();\n    }\n\n    /// @notice fund the redemption queue. Receipt is iToken (iUSD, iETH), asset is the collateral token (USDC, ETH)\n    /// @param _assetAmount the amount to fund, in collateral token\n    /// @param _convertReceiptToAssetRatio the ratio to convert receipt token to collateral token, with WAD precision (1e18)\n    /// @return (uint256, uint256) the first is the amount not used to fund the queue (0 if the queue fully absorbed the amount),\n    /// the second is the amount of receipt token to burn because we have funded the tickets for this amount of receiptToken\n    function _fundRedemptionQueue(uint256 _assetAmount, uint256 _convertReceiptToAssetRatio)\n        internal\n        returns (uint256, uint256)\n    {\n        require(_assetAmount > 0, FundingAmountZero());\n        uint256 totalEnqueuedRedemptionsBefore = totalEnqueuedRedemptions; // iUSD\n        // amount can be way higher than the amount being asked (total value of all tickets in the queue)\n        uint256 remainingAssets = _assetAmount; // USDC\n\n        uint256 _totalPendingClaims = totalPendingClaims;\n        uint256 _totalEnqueuedRedemptions = totalEnqueuedRedemptions;\n\n        while (remainingAssets > 0 && !queue.empty()) {\n            RedemptionQueue.RedemptionRequest memory request = queue.front();\n            // compute amount of asset to be redeemed by the amount of receipt token\n            uint256 assetRequired = uint256(request.amount).mulWadDown(_convertReceiptToAssetRatio); // USDC\n            uint256 receiptToBurn = request.amount; // iUSD\n            if (assetRequired > remainingAssets) {\n                assetRequired = remainingAssets;\n                // here 'receiptToBurn' is the amount of remaining assets converted to receipt token using the ratio\n                receiptToBurn = remainingAssets.divWadUp(_convertReceiptToAssetRatio); // iUSD\n                // forge-lint: disable-next-line(unsafe-typecast)\n                uint96 newReceiptAmount = request.amount - uint96(receiptToBurn); // iUSD\n                queue.updateFront(newReceiptAmount); // iUSD\n\n                emit RedemptionPartiallyFunded(block.timestamp, request.recipient, remainingAssets); // USDC\n            } else {\n                queue.popFront();\n                emit RedemptionFunded(block.timestamp, request.recipient, assetRequired); // USDC\n            }\n\n            userPendingClaims[request.recipient] += assetRequired; // USDC\n            remainingAssets -= assetRequired; // USDC\n            _totalPendingClaims += assetRequired; // USDC\n            _totalEnqueuedRedemptions -= receiptToBurn; // iUSD\n        }\n\n        totalPendingClaims = _totalPendingClaims; // USDC\n        totalEnqueuedRedemptions = _totalEnqueuedRedemptions; // iUSD\n\n        // the amount of receipt to burn is the difference between the total enqueued redemptions before and after the funding\n        // if before we had 100 iUSD in the enqueued redemptions and after the funding we have 75 iUSD,\n        // it means that 25 iUSD have been funded and thus 25 iUSD should be burned\n        uint256 receiptAmountToBurn = totalEnqueuedRedemptionsBefore - totalEnqueuedRedemptions; // iUSD\n        return (remainingAssets, receiptAmountToBurn); // [USDC, iUSD]\n    }\n\n    /// @notice claim the redemption for a given recipient\n    /// @param _recipient the recipient of the redemption\n    /// @return the amount of redemption claimed\n    function _claimRedemption(address _recipient) internal returns (uint256) {\n        uint256 amount = userPendingClaims[_recipient];\n        require(amount > 0, NoPendingClaims(_recipient));\n\n        userPendingClaims[_recipient] = 0;\n        totalPendingClaims -= amount;\n\n        emit RedemptionClaimed(block.timestamp, _recipient, amount);\n        return amount;\n    }\n\n    /// @notice enqueue a redemption request\n    /// @param _recipient the recipient of the redemption\n    /// @param _amount the amount of receiptToken to redeem\n    function _enqueue(address _recipient, uint256 _amount) internal {\n        // we limit the queue length to avoid possible out of gas exceptions when funding the queue\n        // mainly a risk with griefing (stuffing the queue with a lot of small redemptions)\n        // in case of griefing, the queue will be filled up to the max length, and any new enqueue will be rejected\n        // in this case, we'll just have to fund the redemption queue to empty the queue (without risking an out of gas exception)\n        // and then any new redemption request will be accepted\n        require(queue.length() < MAX_QUEUE_LENGTH, QueueTooLong());\n        require(_amount > 0, EnqueueAmountZero());\n        require(_amount <= type(uint96).max, EnqueueAmountTooLarge());\n        totalEnqueuedRedemptions += _amount;\n        // casting to 'uint96' is safe because of the require above\n        // forge-lint: disable-next-line(unsafe-typecast)\n        queue.pushBack(RedemptionQueue.RedemptionRequest({amount: uint96(_amount), recipient: _recipient}));\n        emit RedemptionQueued(block.timestamp, _recipient, _amount);\n    }\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/types/Time.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.5.0) (utils/types/Time.sol)\n\npragma solidity ^0.8.20;\n\nimport {Math} from \"../math/Math.sol\";\nimport {SafeCast} from \"../math/SafeCast.sol\";\n\n/**\n * @dev This library provides helpers for manipulating time-related objects.\n *\n * It uses the following types:\n * - `uint48` for timepoints\n * - `uint32` for durations\n *\n * While the library doesn't provide specific types for timepoints and duration, it does provide:\n * - a `Delay` type to represent duration that can be programmed to change value automatically at a given point\n * - additional helper functions\n */\nlibrary Time {\n    using Time for *;\n\n    /**\n     * @dev Get the block timestamp as a Timepoint.\n     */\n    function timestamp() internal view returns (uint48) {\n        return SafeCast.toUint48(block.timestamp);\n    }\n\n    /**\n     * @dev Get the block number as a Timepoint.\n     */\n    function blockNumber() internal view returns (uint48) {\n        return SafeCast.toUint48(block.number);\n    }\n\n    // ==================================================== Delay =====================================================\n    /**\n     * @dev A `Delay` is a uint32 duration that can be programmed to change value automatically at a given point in the\n     * future. The \"effect\" timepoint describes when the transition happens from the \"old\" value to the \"new\" value.\n     * This allows updating the delay applied to some operation while keeping some guarantees.\n     *\n     * In particular, the {update} function guarantees that if the delay is reduced, the old delay still applies for\n     * some time. For example if the delay is currently 7 days to do an upgrade, the admin should not be able to set\n     * the delay to 0 and upgrade immediately. If the admin wants to reduce the delay, the old delay (7 days) should\n     * still apply for some time.\n     *\n     *\n     * The `Delay` type is 112 bits long, and packs the following:\n     *\n     * ```\n     *   | [uint48]: effect date (timepoint)\n     *   |           | [uint32]: value before (duration)\n     *   ↓           ↓       ↓ [uint32]: value after (duration)\n     * 0xAAAAAAAAAAAABBBBBBBBCCCCCCCC\n     * ```\n     *\n     * NOTE: The {get} and {withUpdate} functions operate using timestamps. Block number based delays are not currently\n     * supported.\n     */\n    type Delay is uint112;\n\n    /**\n     * @dev Wrap a duration into a Delay to add the one-step \"update in the future\" feature\n     */\n    function toDelay(uint32 duration) internal pure returns (Delay) {\n        return Delay.wrap(duration);\n    }\n\n    /**\n     * @dev Get the value at a given timepoint plus the pending value and effect timepoint if there is a scheduled\n     * change after this timepoint. If the effect timepoint is 0, then the pending value should not be considered.\n     */\n    function _getFullAt(\n        Delay self,\n        uint48 timepoint\n    ) private pure returns (uint32 valueBefore, uint32 valueAfter, uint48 effect) {\n        (valueBefore, valueAfter, effect) = self.unpack();\n        return effect <= timepoint ? (valueAfter, 0, 0) : (valueBefore, valueAfter, effect);\n    }\n\n    /**\n     * @dev Get the current value plus the pending value and effect timepoint if there is a scheduled change. If the\n     * effect timepoint is 0, then the pending value should not be considered.\n     */\n    function getFull(Delay self) internal view returns (uint32 valueBefore, uint32 valueAfter, uint48 effect) {\n        return _getFullAt(self, timestamp());\n    }\n\n    /**\n     * @dev Get the current value.\n     */\n    function get(Delay self) internal view returns (uint32) {\n        (uint32 delay, , ) = self.getFull();\n        return delay;\n    }\n\n    /**\n     * @dev Update a Delay object so that it takes a new duration after a timepoint that is automatically computed to\n     * enforce the old delay at the moment of the update. Returns the updated Delay object and the timestamp when the\n     * new delay becomes effective.\n     */\n    function withUpdate(\n        Delay self,\n        uint32 newValue,\n        uint32 minSetback\n    ) internal view returns (Delay updatedDelay, uint48 effect) {\n        uint32 value = self.get();\n        uint32 setback = uint32(Math.max(minSetback, value > newValue ? value - newValue : 0));\n        effect = timestamp() + setback;\n        return (pack(value, newValue, effect), effect);\n    }\n\n    /**\n     * @dev Split a delay into its components: valueBefore, valueAfter and effect (transition timepoint).\n     */\n    function unpack(Delay self) internal pure returns (uint32 valueBefore, uint32 valueAfter, uint48 effect) {\n        uint112 raw = Delay.unwrap(self);\n\n        valueAfter = uint32(raw);\n        valueBefore = uint32(raw >> 32);\n        effect = uint48(raw >> 64);\n\n        return (valueBefore, valueAfter, effect);\n    }\n\n    /**\n     * @dev pack the components into a Delay object.\n     */\n    function pack(uint32 valueBefore, uint32 valueAfter, uint48 effect) internal pure returns (Delay) {\n        return Delay.wrap((uint112(effect) << 64) | (uint112(valueBefore) << 32) | uint112(valueAfter));\n    }\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/token/ERC20/extensions/ERC20Votes.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.5.0) (token/ERC20/extensions/ERC20Votes.sol)\n\npragma solidity ^0.8.24;\n\nimport {ERC20} from \"../ERC20.sol\";\nimport {Votes} from \"../../../governance/utils/Votes.sol\";\nimport {Checkpoints} from \"../../../utils/structs/Checkpoints.sol\";\n\n/**\n * @dev Extension of ERC-20 to support Compound-like voting and delegation. This version is more generic than Compound's,\n * and supports token supply up to 2^208^ - 1, while COMP is limited to 2^96^ - 1.\n *\n * NOTE: This contract does not provide interface compatibility with Compound's COMP token.\n *\n * This extension keeps a history (checkpoints) of each account's vote power. Vote power can be delegated either\n * by calling the {Votes-delegate} function directly, or by providing a signature to be used with {Votes-delegateBySig}. Voting\n * power can be queried through the public accessors {Votes-getVotes} and {Votes-getPastVotes}.\n *\n * By default, token balance does not account for voting power. This makes transfers cheaper. The downside is that it\n * requires users to delegate to themselves in order to activate checkpoints and have their voting power tracked.\n */\nabstract contract ERC20Votes is ERC20, Votes {\n    /**\n     * @dev Total supply cap has been exceeded, introducing a risk of votes overflowing.\n     */\n    error ERC20ExceededSafeSupply(uint256 increasedSupply, uint256 cap);\n\n    /**\n     * @dev Maximum token supply. Defaults to `type(uint208).max` (2^208^ - 1).\n     *\n     * This maximum is enforced in {_update}. It limits the total supply of the token, which is otherwise a uint256,\n     * so that checkpoints can be stored in the Trace208 structure used by {Votes}. Increasing this value will not\n     * remove the underlying limitation, and will cause {_update} to fail because of a math overflow in\n     * {Votes-_transferVotingUnits}. An override could be used to further restrict the total supply (to a lower value) if\n     * additional logic requires it. When resolving override conflicts on this function, the minimum should be\n     * returned.\n     */\n    function _maxSupply() internal view virtual returns (uint256) {\n        return type(uint208).max;\n    }\n\n    /**\n     * @dev Move voting power when tokens are transferred.\n     *\n     * Emits a {IVotes-DelegateVotesChanged} event.\n     */\n    function _update(address from, address to, uint256 value) internal virtual override {\n        super._update(from, to, value);\n        if (from == address(0)) {\n            uint256 supply = totalSupply();\n            uint256 cap = _maxSupply();\n            if (supply > cap) {\n                revert ERC20ExceededSafeSupply(supply, cap);\n            }\n        }\n        _transferVotingUnits(from, to, value);\n    }\n\n    /**\n     * @dev Returns the voting units of an `account`.\n     *\n     * WARNING: Overriding this function may compromise the internal vote accounting.\n     * `ERC20Votes` assumes tokens map to voting units 1:1 and this is not easy to change.\n     */\n    function _getVotingUnits(address account) internal view virtual override returns (uint256) {\n        return balanceOf(account);\n    }\n\n    /**\n     * @dev Get number of checkpoints for `account`.\n     */\n    function numCheckpoints(address account) public view virtual returns (uint32) {\n        return _numCheckpoints(account);\n    }\n\n    /**\n     * @dev Get the `pos`-th checkpoint for `account`.\n     */\n    function checkpoints(address account, uint32 pos) public view virtual returns (Checkpoints.Checkpoint208 memory) {\n        return _checkpoints(account, pos);\n    }\n}\n"},{"file_path":"src/gateway/InfiniFiGatewayV3.sol","source_code":"// SPDX-License-Identifier: MIT\npragma solidity 0.8.28;\n\nimport {ERC20} from \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\nimport {SafeERC20} from \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\n\nimport {GovernanceToken} from \"@tokens/GovernanceToken.sol\";\nimport {LockingController} from \"@locking/LockingController.sol\";\nimport {InfiniFiGatewayV2} from \"@gateway/InfiniFiGatewayV2.sol\";\nimport {MigrationController} from \"@funding/MigrationController.sol\";\n\n/// @notice Gateway to interact with the InfiniFi protocol\ncontract InfiniFiGatewayV3 is InfiniFiGatewayV2 {\n    using SafeERC20 for ERC20;\n\n    function migrate(address _farm, address _token, uint256 _amount, uint32 _unwindingEpochs, uint256 _minIusdReceived)\n        external\n        whenNotPaused\n        nonReentrant\n        returns (uint256)\n    {\n        ERC20 token = ERC20(_token);\n        MigrationController migrationController = MigrationController(getAddress(\"migrationController\"));\n\n        token.safeTransferFrom(msg.sender, address(this), _amount);\n        token.approve(address(migrationController), _amount);\n        uint256 iusdReceived = migrationController.migrate(msg.sender, _farm, _token, _amount, _unwindingEpochs);\n        require(iusdReceived >= _minIusdReceived, MinAssetsOutError(_minIusdReceived, iusdReceived));\n        return iusdReceived;\n    }\n\n    function lockInfi(uint256 _amount, uint32 _unwindingEpochs) external whenNotPaused nonReentrant {\n        GovernanceToken infi = GovernanceToken(getAddress(\"governanceToken\"));\n        LockingController locker = LockingController(getAddress(\"governanceLockingController\"));\n\n        // forge-lint: disable-next-line(erc20-unchecked-transfer)\n        infi.transferFrom(msg.sender, address(this), _amount);\n        infi.approve(address(locker), _amount);\n        locker.createPosition(_amount, _unwindingEpochs, msg.sender);\n    }\n\n    function startInfiWithdrawal(uint256 _shares, uint32 _unwindingEpochs) external whenNotPaused nonReentrant {\n        LockingController locker = LockingController(getAddress(\"governanceLockingController\"));\n        GovernanceToken linfi = GovernanceToken(locker.shareToken(_unwindingEpochs));\n\n        // forge-lint: disable-next-line(erc20-unchecked-transfer)\n        linfi.transferFrom(msg.sender, address(this), _shares);\n        linfi.approve(address(locker), _shares);\n        locker.startUnwinding(_shares, _unwindingEpochs, msg.sender);\n    }\n\n    function increaseInfiWithdrawalPeriod(uint32 _oldUnwindingEpochs, uint32 _newUnwindingEpochs, uint256 _shares)\n        external\n        whenNotPaused\n        nonReentrant\n    {\n        LockingController locker = LockingController(getAddress(\"governanceLockingController\"));\n        GovernanceToken linfi = GovernanceToken(locker.shareToken(_oldUnwindingEpochs));\n\n        // forge-lint: disable-next-line(erc20-unchecked-transfer)\n        linfi.transferFrom(msg.sender, address(this), _shares);\n        linfi.approve(address(locker), _shares);\n        locker.increaseUnwindingEpochs(_shares, _oldUnwindingEpochs, _newUnwindingEpochs, msg.sender);\n    }\n\n    function cancelInfiWithdrawal(uint256 _unwindingTimestamp, uint32 _newUnwindingEpochs)\n        external\n        whenNotPaused\n        nonReentrant\n    {\n        LockingController(getAddress(\"governanceLockingController\"))\n            .cancelUnwinding(msg.sender, _unwindingTimestamp, _newUnwindingEpochs);\n    }\n\n    function completeInfiWithdrawal(address _user, uint256 _unwindingTimestamp) external whenNotPaused nonReentrant {\n        LockingController(getAddress(\"governanceLockingController\")).withdraw(_user, _unwindingTimestamp);\n    }\n}\n"},{"file_path":"src/integrations/outland/OutlandFarm.sol","source_code":"// SPDX-License-Identifier: MIT\npragma solidity 0.8.28;\n\nimport {ERC20} from \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\nimport {SafeERC20} from \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\n\nimport {CoreRoles} from \"@libraries/CoreRoles.sol\";\nimport {OutlandVault} from \"@integrations/outland/OutlandVault.sol\";\nimport {IMaturityFarm} from \"@interfaces/IMaturityFarm.sol\";\nimport {MultiAssetFarmV2} from \"@integrations/MultiAssetFarmV2.sol\";\n\n/// @title OutlandFarm [1 week farm]\n/// @notice A farm contract that integrates with OutlandVault for cross-chain yield\ncontract OutlandFarm is MultiAssetFarmV2, IMaturityFarm {\n    using SafeERC20 for ERC20;\n\n    error VaultNotSet();\n\n    event VaultSet(address indexed vault);\n    event VaultDeposited(uint256 indexed timestamp, address _token, uint256 amount);\n    event VaultWithdrawn(uint256 indexed timestamp, address _token, uint256 amount);\n\n    /// @notice The chain ID where this farm operates\n    uint256 public immutable chainId;\n\n    /// @notice Offsets maturity to always be in future. (eg. 1 week, 2 weeks, etc)\n    uint256 public immutable maturityOffset;\n\n    /// @notice Vault contract\n    OutlandVault public vault;\n\n    /// @notice Initializes the OutlandFarm contract\n    /// @param _core Address of the Core contract for role management\n    /// @param _assetToken Address of the primary asset token for this farm\n    /// @param _chainId Chain ID where this farm operates\n    /// @param _accounting Address of the accounting module for asset tracking\n    constructor(address _core, address _assetToken, uint256 _chainId, address _accounting, uint256 _maturityOffset)\n        MultiAssetFarmV2(_core, _assetToken, _accounting)\n    {\n        chainId = _chainId;\n        maturityOffset = _maturityOffset;\n        _enableAsset(_assetToken);\n    }\n\n    /// @notice Sets the vault contract address\n    /// @dev Should be called once,\n    /// but in case of changing it be make sure to bring the old vault shares to zero\n    /// @param _vault Address of the OutlandVault contract\n    function setVault(address _vault) external onlyCoreRole(CoreRoles.PROTOCOL_PARAMETERS) {\n        vault = OutlandVault(_vault);\n        _enableAsset(_vault);\n        emit VaultSet(_vault);\n    }\n\n    /// @notice Indicates that this farm is a 1 week duration asset\n    /// @dev Returns current timestamp plus 7 days, representing the maturity date\n    /// @return The maturity timestamp (current time + 7 days)\n    function maturity() public view returns (uint256) {\n        return block.timestamp + maturityOffset;\n    }\n\n    /// @notice Deposits tokens to the OutlandVault contract\n    /// @param _token Token to deposit into vault\n    /// @param _amount Amount of vault tokens to deposit\n    function depositToVault(address _token, uint256 _amount)\n        external\n        whenNotPaused\n        onlyCoreRole(CoreRoles.OUTLAND_KEEPER)\n    {\n        require(address(vault) != address(0), VaultNotSet());\n        require(isAssetSupported(_token), InvalidAsset(_token));\n\n        ERC20(_token).forceApprove(address(vault), _amount);\n        vault.deposit(_token, _amount);\n        emit VaultDeposited(block.timestamp, _token, _amount);\n    }\n\n    /// @notice Withdraws vault shares and receives vault tokens\n    /// @param _token Token to withdraw from the vault\n    /// @param _shares Amount of vault shares to withdraw\n    function withdrawFromVault(address _token, uint256 _shares)\n        external\n        whenNotPaused\n        onlyCoreRole(CoreRoles.OUTLAND_KEEPER)\n    {\n        require(address(vault) != address(0), VaultNotSet());\n        require(isAssetSupported(_token), InvalidAsset(_token));\n\n        uint256 tokenAmount = vault.redeem(_token, _shares);\n        emit VaultWithdrawn(block.timestamp, _token, tokenAmount);\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/interfaces/IERC5805.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC5805.sol)\n\npragma solidity >=0.8.4;\n\nimport {IVotes} from \"../governance/utils/IVotes.sol\";\nimport {IERC6372} from \"./IERC6372.sol\";\n\ninterface IERC5805 is IERC6372, IVotes {}\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/FarmTypes.sol","source_code":"// SPDX-License-Identifier: MIT\npragma solidity 0.8.28;\n\nlibrary FarmTypes {\n    /// @notice indicates farm type that is not generating any yield but is capable of storing funds\n    uint256 internal constant PROTOCOL = 0;\n\n    /// @notice farm type that has instant principal withdrawals. (eg AAVE)\n    uint256 internal constant LIQUID = 1;\n\n    /// @notice (illiquid farm) has a maturity until when the principal value is locked\n    uint256 internal constant MATURITY = 2;\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":"src/interfaces/IMintController.sol","source_code":"// SPDX-License-Identifier: MIT\npragma solidity 0.8.28;\n\ninterface IAfterMintHook {\n    /// @notice event emitted when asset rebalance threshold is updated by the governance\n    event AssetRebalanceThresholdUpdated(uint256 indexed timestamp, uint256 amount);\n\n    /// @param _to the address to mint to\n    /// @param _assetsIn the amount of assets deposited\n    function afterMint(address _to, uint256 _assetsIn) external;\n}\n\n/// @notice Interface for an InfiniFi Staking Controller contract\ninterface IMintController {\n    /// @notice error emitted when the asset amount is too low\n    error AssetAmountTooLow(uint256 _amountIn, uint256 _minAssetAmount);\n\n    /// @notice event emitted when afterMintHook is changed\n    event AfterMintHookChanged(uint256 indexed timestamp, address hook);\n\n    /// @notice event emitted when minimum asset amount is updated by the governance\n    event MinAssetAmountUpdated(uint256 indexed timestamp, uint256 amount);\n\n    /// @notice event emitted upon a minting\n    event Mint(uint256 indexed timestamp, address indexed to, address asset, uint256 amountIn, uint256 amountOut);\n\n    /// @notice calculate the amount of receiptToken() out for a given `amountIn` of assetToken()\n    /// @param _assetAmount the amount of assetTokens to convert to receiptTokens\n    /// @return the amount of receiptTokens received\n    function assetToReceipt(uint256 _assetAmount) external view returns (uint256);\n\n    /// @notice mint `amountOut` receiptToken() to address `to` for `amountIn` assetToken()\n    /// @param _to the address to mint the receiptToken to\n    /// @param _assetAmountIn the amount of assetTokens to spend for minting receiptTokens\n    /// @return the amount of receiptTokens minted\n    function mint(address _to, uint256 _assetAmountIn) external returns (uint256);\n}\n"},{"file_path":"lib/LayerZero-v2/packages/layerzero-v2/evm/oapp/contracts/oapp/OAppReceiver.sol","source_code":"// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.20;\n\nimport { IOAppReceiver, Origin } from \"./interfaces/IOAppReceiver.sol\";\nimport { OAppCore } from \"./OAppCore.sol\";\n\n/**\n * @title OAppReceiver\n * @dev Abstract contract implementing the ILayerZeroReceiver interface and extending OAppCore for OApp receivers.\n */\nabstract contract OAppReceiver is IOAppReceiver, OAppCore {\n    // Custom error message for when the caller is not the registered endpoint/\n    error OnlyEndpoint(address addr);\n\n    // @dev The version of the OAppReceiver implementation.\n    // @dev Version is bumped when changes are made to this contract.\n    uint64 internal constant RECEIVER_VERSION = 2;\n\n    /**\n     * @notice Retrieves the OApp version information.\n     * @return senderVersion The version of the OAppSender.sol contract.\n     * @return receiverVersion The version of the OAppReceiver.sol contract.\n     *\n     * @dev Providing 0 as the default for OAppSender version. Indicates that the OAppSender is not implemented.\n     * ie. this is a RECEIVE only OApp.\n     * @dev If the OApp uses both OAppSender and OAppReceiver, then this needs to be override returning the correct versions.\n     */\n    function oAppVersion() public view virtual returns (uint64 senderVersion, uint64 receiverVersion) {\n        return (0, RECEIVER_VERSION);\n    }\n\n    /**\n     * @notice Indicates whether an address is an approved composeMsg sender to the Endpoint.\n     * @dev _origin The origin information containing the source endpoint and sender address.\n     *  - srcEid: The source chain endpoint ID.\n     *  - sender: The sender address on the src chain.\n     *  - nonce: The nonce of the message.\n     * @dev _message The lzReceive payload.\n     * @param _sender The sender address.\n     * @return isSender Is a valid sender.\n     *\n     * @dev Applications can optionally choose to implement separate composeMsg senders that are NOT the bridging layer.\n     * @dev The default sender IS the OAppReceiver implementer.\n     */\n    function isComposeMsgSender(\n        Origin calldata /*_origin*/,\n        bytes calldata /*_message*/,\n        address _sender\n    ) public view virtual returns (bool) {\n        return _sender == address(this);\n    }\n\n    /**\n     * @notice Checks if the path initialization is allowed based on the provided origin.\n     * @param origin The origin information containing the source endpoint and sender address.\n     * @return Whether the path has been initialized.\n     *\n     * @dev This indicates to the endpoint that the OApp has enabled msgs for this particular path to be received.\n     * @dev This defaults to assuming if a peer has been set, its initialized.\n     * Can be overridden by the OApp if there is other logic to determine this.\n     */\n    function allowInitializePath(Origin calldata origin) public view virtual returns (bool) {\n        return peers[origin.srcEid] == origin.sender;\n    }\n\n    /**\n     * @notice Retrieves the next nonce for a given source endpoint and sender address.\n     * @dev _srcEid The source endpoint ID.\n     * @dev _sender The sender address.\n     * @return nonce The next nonce.\n     *\n     * @dev The path nonce starts from 1. If 0 is returned it means that there is NO nonce ordered enforcement.\n     * @dev Is required by the off-chain executor to determine the OApp expects msg execution is ordered.\n     * @dev This is also enforced by the OApp.\n     * @dev By default this is NOT enabled. ie. nextNonce is hardcoded to return 0.\n     */\n    function nextNonce(uint32 /*_srcEid*/, bytes32 /*_sender*/) public view virtual returns (uint64 nonce) {\n        return 0;\n    }\n\n    /**\n     * @dev Entry point for receiving messages or packets from the endpoint.\n     * @param _origin The origin information containing the source endpoint and sender address.\n     *  - srcEid: The source chain endpoint ID.\n     *  - sender: The sender address on the src chain.\n     *  - nonce: The nonce of the message.\n     * @param _guid The unique identifier for the received LayerZero message.\n     * @param _message The payload of the received message.\n     * @param _executor The address of the executor for the received message.\n     * @param _extraData Additional arbitrary data provided by the corresponding executor.\n     *\n     * @dev Entry point for receiving msg/packet from the LayerZero endpoint.\n     */\n    function lzReceive(\n        Origin calldata _origin,\n        bytes32 _guid,\n        bytes calldata _message,\n        address _executor,\n        bytes calldata _extraData\n    ) public payable virtual {\n        // Ensures that only the endpoint can attempt to lzReceive() messages to this OApp.\n        if (address(endpoint) != msg.sender) revert OnlyEndpoint(msg.sender);\n\n        // Ensure that the sender matches the expected peer for the source endpoint.\n        if (_getPeerOrRevert(_origin.srcEid) != _origin.sender) revert OnlyPeer(_origin.srcEid, _origin.sender);\n\n        // Call the internal OApp implementation of lzReceive.\n        _lzReceive(_origin, _guid, _message, _executor, _extraData);\n    }\n\n    /**\n     * @dev Internal function to implement lzReceive logic without needing to copy the basic parameter validation.\n     */\n    function _lzReceive(\n        Origin calldata _origin,\n        bytes32 _guid,\n        bytes calldata _message,\n        address _executor,\n        bytes calldata _extraData\n    ) internal virtual;\n}\n"},{"file_path":"src/interfaces/IRedeemController.sol","source_code":"// SPDX-License-Identifier: MIT\npragma solidity 0.8.28;\n\ninterface IBeforeRedeemHook {\n    /// @param _to the address to redeem to\n    /// @param _receiptAmountIn the amount of receipt tokens to redeem\n    /// @param _assetAmountOut the amount of asset tokens to receive\n    function beforeRedeem(address _to, uint256 _receiptAmountIn, uint256 _assetAmountOut) external;\n}\n\n/// @notice Interface for an InfiniFi Redeem Controller contract\ninterface IRedeemController {\n    /// @notice error emitted when the redemption amount is too low\n    error RedeemAmountTooLow(uint256 _amountIn, uint256 _minRedemptionAmount);\n\n    /// @notice event emitted when before redeem hook is changed by the governance\n    event BeforeRedeemHookChanged(uint256 indexed timestamp, address hook);\n    /// @notice event emitted when minimum redemption amount is updated\n    event MinRedemptionAmountUpdated(uint256 indexed timestamp, uint256 amount);\n\n    /// @notice event emitted upon a redemption\n    event Redeem(uint256 indexed timestamp, address indexed to, address asset, uint256 amountIn, uint256 amountOut);\n\n    /// @notice calculate the amount of assetToken() out for a given `amountIn` of receiptToken()\n    /// @param _receiptAmount the amount of receiptTokens to redeem for assetTokens\n    /// @return the amount of assetTokens received\n    function receiptToAsset(uint256 _receiptAmount) external view returns (uint256);\n\n    /// @notice redeem `amountIn` receiptToken() for `amountOut` assetToken() and send to address `to`\n    /// @param _to the address to send the assetToken to\n    /// @param _receiptAmountIn the amount of receiptTokens to redeem for assetTokens\n    /// @return the amount of assetTokens received\n    function redeem(address _to, uint256 _receiptAmountIn) external returns (uint256);\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":"lib/LayerZero-v2/packages/layerzero-v2/evm/oapp/contracts/oapp/OAppCore.sol","source_code":"// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.20;\n\nimport { Ownable } from \"@openzeppelin/contracts/access/Ownable.sol\";\nimport { IOAppCore, ILayerZeroEndpointV2 } from \"./interfaces/IOAppCore.sol\";\n\n/**\n * @title OAppCore\n * @dev Abstract contract implementing the IOAppCore interface with basic OApp configurations.\n */\nabstract contract OAppCore is IOAppCore, Ownable {\n    // The LayerZero endpoint associated with the given OApp\n    ILayerZeroEndpointV2 public immutable endpoint;\n\n    // Mapping to store peers associated with corresponding endpoints\n    mapping(uint32 eid => bytes32 peer) public peers;\n\n    /**\n     * @dev Constructor to initialize the OAppCore with the provided endpoint and delegate.\n     * @param _endpoint The address of the LOCAL Layer Zero endpoint.\n     * @param _delegate The delegate capable of making OApp configurations inside of the endpoint.\n     *\n     * @dev The delegate typically should be set as the owner of the contract.\n     */\n    constructor(address _endpoint, address _delegate) {\n        endpoint = ILayerZeroEndpointV2(_endpoint);\n\n        if (_delegate == address(0)) revert InvalidDelegate();\n        endpoint.setDelegate(_delegate);\n    }\n\n    /**\n     * @notice Sets the peer address (OApp instance) for a corresponding endpoint.\n     * @param _eid The endpoint ID.\n     * @param _peer The address of the peer to be associated with the corresponding endpoint.\n     *\n     * @dev Only the owner/admin of the OApp can call this function.\n     * @dev Indicates that the peer is trusted to send LayerZero messages to this OApp.\n     * @dev Set this to bytes32(0) to remove the peer address.\n     * @dev Peer is a bytes32 to accommodate non-evm chains.\n     */\n    function setPeer(uint32 _eid, bytes32 _peer) public virtual onlyOwner {\n        _setPeer(_eid, _peer);\n    }\n\n    /**\n     * @notice Sets the peer address (OApp instance) for a corresponding endpoint.\n     * @param _eid The endpoint ID.\n     * @param _peer The address of the peer to be associated with the corresponding endpoint.\n     *\n     * @dev Indicates that the peer is trusted to send LayerZero messages to this OApp.\n     * @dev Set this to bytes32(0) to remove the peer address.\n     * @dev Peer is a bytes32 to accommodate non-evm chains.\n     */\n    function _setPeer(uint32 _eid, bytes32 _peer) internal virtual {\n        peers[_eid] = _peer;\n        emit PeerSet(_eid, _peer);\n    }\n\n    /**\n     * @notice Internal function to get the peer address associated with a specific endpoint; reverts if NOT set.\n     * ie. the peer is set to bytes32(0).\n     * @param _eid The endpoint ID.\n     * @return peer The address of the peer associated with the specified endpoint.\n     */\n    function _getPeerOrRevert(uint32 _eid) internal view virtual returns (bytes32) {\n        bytes32 peer = peers[_eid];\n        if (peer == bytes32(0)) revert NoPeer(_eid);\n        return peer;\n    }\n\n    /**\n     * @notice Sets the delegate address for the OApp.\n     * @param _delegate The address of the delegate to be set.\n     *\n     * @dev Only the owner/admin of the OApp can call this function.\n     * @dev Provides the ability for a delegate to set configs, on behalf of the OApp, directly on the Endpoint contract.\n     */\n    function setDelegate(address _delegate) public onlyOwner {\n        endpoint.setDelegate(_delegate);\n    }\n}\n"},{"file_path":"lib/LayerZero-v2/packages/layerzero-v2/evm/oapp/contracts/oft/OFTCore.sol","source_code":"// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.20;\n\nimport { OApp, Origin } from \"../oapp/OApp.sol\";\nimport { OAppOptionsType3 } from \"../oapp/libs/OAppOptionsType3.sol\";\nimport { IOAppMsgInspector } from \"../oapp/interfaces/IOAppMsgInspector.sol\";\n\nimport { OAppPreCrimeSimulator } from \"../precrime/OAppPreCrimeSimulator.sol\";\n\nimport { IOFT, SendParam, OFTLimit, OFTReceipt, OFTFeeDetail, MessagingReceipt, MessagingFee } from \"./interfaces/IOFT.sol\";\nimport { OFTMsgCodec } from \"./libs/OFTMsgCodec.sol\";\nimport { OFTComposeMsgCodec } from \"./libs/OFTComposeMsgCodec.sol\";\n\n/**\n * @title OFTCore\n * @dev Abstract contract for the OftChain (OFT) token.\n */\nabstract contract OFTCore is IOFT, OApp, OAppPreCrimeSimulator, OAppOptionsType3 {\n    using OFTMsgCodec for bytes;\n    using OFTMsgCodec for bytes32;\n\n    // @notice Provides a conversion rate when swapping between denominations of SD and LD\n    //      - shareDecimals == SD == shared Decimals\n    //      - localDecimals == LD == local decimals\n    // @dev Considers that tokens have different decimal amounts on various chains.\n    // @dev eg.\n    //  For a token\n    //      - locally with 4 decimals --> 1.2345 => uint(12345)\n    //      - remotely with 2 decimals --> 1.23 => uint(123)\n    //      - The conversion rate would be 10 ** (4 - 2) = 100\n    //  @dev If you want to send 1.2345 -> (uint 12345), you CANNOT represent that value on the remote,\n    //  you can only display 1.23 -> uint(123).\n    //  @dev To preserve the dust that would otherwise be lost on that conversion,\n    //  we need to unify a denomination that can be represented on ALL chains inside of the OFT mesh\n    uint256 public immutable decimalConversionRate;\n\n    // @notice Msg types that are used to identify the various OFT operations.\n    // @dev This can be extended in child contracts for non-default oft operations\n    // @dev These values are used in things like combineOptions() in OAppOptionsType3.sol.\n    uint16 public constant SEND = 1;\n    uint16 public constant SEND_AND_CALL = 2;\n\n    // Address of an optional contract to inspect both 'message' and 'options'\n    address public msgInspector;\n    event MsgInspectorSet(address inspector);\n\n    /**\n     * @dev Constructor.\n     * @param _localDecimals The decimals of the token on the local chain (this chain).\n     * @param _endpoint The address of the LayerZero endpoint.\n     * @param _delegate The delegate capable of making OApp configurations inside of the endpoint.\n     */\n    constructor(uint8 _localDecimals, address _endpoint, address _delegate) OApp(_endpoint, _delegate) {\n        if (_localDecimals < sharedDecimals()) revert InvalidLocalDecimals();\n        decimalConversionRate = 10 ** (_localDecimals - sharedDecimals());\n    }\n\n    /**\n     * @notice Retrieves interfaceID and the version of the OFT.\n     * @return interfaceId The interface ID.\n     * @return version The version.\n     *\n     * @dev interfaceId: This specific interface ID is '0x02e49c2c'.\n     * @dev version: Indicates a cross-chain compatible msg encoding with other OFTs.\n     * @dev If a new feature is added to the OFT cross-chain msg encoding, the version will be incremented.\n     * ie. localOFT version(x,1) CAN send messages to remoteOFT version(x,1)\n     */\n    function oftVersion() external pure virtual returns (bytes4 interfaceId, uint64 version) {\n        return (type(IOFT).interfaceId, 1);\n    }\n\n    /**\n     * @dev Retrieves the shared decimals of the OFT.\n     * @return The shared decimals of the OFT.\n     *\n     * @dev Sets an implicit cap on the amount of tokens, over uint64.max() will need some sort of outbound cap / totalSupply cap\n     * Lowest common decimal denominator between chains.\n     * Defaults to 6 decimal places to provide up to 18,446,744,073,709.551615 units (max uint64).\n     * For tokens exceeding this totalSupply(), they will need to override the sharedDecimals function with something smaller.\n     * ie. 4 sharedDecimals would be 1,844,674,407,370,955.1615\n     */\n    function sharedDecimals() public view virtual returns (uint8) {\n        return 6;\n    }\n\n    /**\n     * @dev Sets the message inspector address for the OFT.\n     * @param _msgInspector The address of the message inspector.\n     *\n     * @dev This is an optional contract that can be used to inspect both 'message' and 'options'.\n     * @dev Set it to address(0) to disable it, or set it to a contract address to enable it.\n     */\n    function setMsgInspector(address _msgInspector) public virtual onlyOwner {\n        msgInspector = _msgInspector;\n        emit MsgInspectorSet(_msgInspector);\n    }\n\n    /**\n     * @notice Provides a quote for OFT-related operations.\n     * @param _sendParam The parameters for the send operation.\n     * @return oftLimit The OFT limit information.\n     * @return oftFeeDetails The details of OFT fees.\n     * @return oftReceipt The OFT receipt information.\n     */\n    function quoteOFT(\n        SendParam calldata _sendParam\n    )\n        external\n        view\n        virtual\n        returns (OFTLimit memory oftLimit, OFTFeeDetail[] memory oftFeeDetails, OFTReceipt memory oftReceipt)\n    {\n        uint256 minAmountLD = 0; // Unused in the default implementation.\n        uint256 maxAmountLD = type(uint64).max; // Unused in the default implementation.\n        oftLimit = OFTLimit(minAmountLD, maxAmountLD);\n\n        // Unused in the default implementation; reserved for future complex fee details.\n        oftFeeDetails = new OFTFeeDetail[](0);\n\n        // @dev This is the same as the send() operation, but without the actual send.\n        // - amountSentLD is the amount in local decimals that would be sent from the sender.\n        // - amountReceivedLD is the amount in local decimals that will be credited to the recipient on the remote OFT instance.\n        // @dev The amountSentLD MIGHT not equal the amount the user actually receives. HOWEVER, the default does.\n        (uint256 amountSentLD, uint256 amountReceivedLD) = _debitView(\n            _sendParam.amountLD,\n            _sendParam.minAmountLD,\n            _sendParam.dstEid\n        );\n        oftReceipt = OFTReceipt(amountSentLD, amountReceivedLD);\n    }\n\n    /**\n     * @notice Provides a quote for the send() operation.\n     * @param _sendParam The parameters for the send() operation.\n     * @param _payInLzToken Flag indicating whether the caller is paying in the LZ token.\n     * @return msgFee The calculated LayerZero messaging fee from the send() operation.\n     *\n     * @dev MessagingFee: LayerZero msg fee\n     *  - nativeFee: The native fee.\n     *  - lzTokenFee: The lzToken fee.\n     */\n    function quoteSend(\n        SendParam calldata _sendParam,\n        bool _payInLzToken\n    ) external view virtual returns (MessagingFee memory msgFee) {\n        // @dev mock the amount to receive, this is the same operation used in the send().\n        // The quote is as similar as possible to the actual send() operation.\n        (, uint256 amountReceivedLD) = _debitView(_sendParam.amountLD, _sendParam.minAmountLD, _sendParam.dstEid);\n\n        // @dev Builds the options and OFT message to quote in the endpoint.\n        (bytes memory message, bytes memory options) = _buildMsgAndOptions(_sendParam, amountReceivedLD);\n\n        // @dev Calculates the LayerZero fee for the send() operation.\n        return _quote(_sendParam.dstEid, message, options, _payInLzToken);\n    }\n\n    /**\n     * @dev Executes the send operation.\n     * @param _sendParam The parameters for the send operation.\n     * @param _fee The calculated fee for the send() operation.\n     *      - nativeFee: The native fee.\n     *      - lzTokenFee: The lzToken fee.\n     * @param _refundAddress The address to receive any excess funds.\n     * @return msgReceipt The receipt for the send operation.\n     * @return oftReceipt The OFT receipt information.\n     *\n     * @dev MessagingReceipt: LayerZero msg receipt\n     *  - guid: The unique identifier for the sent message.\n     *  - nonce: The nonce of the sent message.\n     *  - fee: The LayerZero fee incurred for the message.\n     */\n    function send(\n        SendParam calldata _sendParam,\n        MessagingFee calldata _fee,\n        address _refundAddress\n    ) external payable virtual returns (MessagingReceipt memory msgReceipt, OFTReceipt memory oftReceipt) {\n        // @dev Applies the token transfers regarding this send() operation.\n        // - amountSentLD is the amount in local decimals that was ACTUALLY sent/debited from the sender.\n        // - amountReceivedLD is the amount in local decimals that will be received/credited to the recipient on the remote OFT instance.\n        (uint256 amountSentLD, uint256 amountReceivedLD) = _debit(\n            msg.sender,\n            _sendParam.amountLD,\n            _sendParam.minAmountLD,\n            _sendParam.dstEid\n        );\n\n        // @dev Builds the options and OFT message to quote in the endpoint.\n        (bytes memory message, bytes memory options) = _buildMsgAndOptions(_sendParam, amountReceivedLD);\n\n        // @dev Sends the message to the LayerZero endpoint and returns the LayerZero msg receipt.\n        msgReceipt = _lzSend(_sendParam.dstEid, message, options, _fee, _refundAddress);\n        // @dev Formulate the OFT receipt.\n        oftReceipt = OFTReceipt(amountSentLD, amountReceivedLD);\n\n        emit OFTSent(msgReceipt.guid, _sendParam.dstEid, msg.sender, amountSentLD, amountReceivedLD);\n    }\n\n    /**\n     * @dev Internal function to build the message and options.\n     * @param _sendParam The parameters for the send() operation.\n     * @param _amountLD The amount in local decimals.\n     * @return message The encoded message.\n     * @return options The encoded options.\n     */\n    function _buildMsgAndOptions(\n        SendParam calldata _sendParam,\n        uint256 _amountLD\n    ) internal view virtual returns (bytes memory message, bytes memory options) {\n        bool hasCompose;\n        // @dev This generated message has the msg.sender encoded into the payload so the remote knows who the caller is.\n        (message, hasCompose) = OFTMsgCodec.encode(\n            _sendParam.to,\n            _toSD(_amountLD),\n            // @dev Must be include a non empty bytes if you want to compose, EVEN if you dont need it on the remote.\n            // EVEN if you dont require an arbitrary payload to be sent... eg. '0x01'\n            _sendParam.composeMsg\n        );\n        // @dev Change the msg type depending if its composed or not.\n        uint16 msgType = hasCompose ? SEND_AND_CALL : SEND;\n        // @dev Combine the callers _extraOptions with the enforced options via the OAppOptionsType3.\n        options = combineOptions(_sendParam.dstEid, msgType, _sendParam.extraOptions);\n\n        // @dev Optionally inspect the message and options depending if the OApp owner has set a msg inspector.\n        // @dev If it fails inspection, needs to revert in the implementation. ie. does not rely on return boolean\n        if (msgInspector != address(0)) IOAppMsgInspector(msgInspector).inspect(message, options);\n    }\n\n    /**\n     * @dev Internal function to handle the receive on the LayerZero endpoint.\n     * @param _origin The origin information.\n     *  - srcEid: The source chain endpoint ID.\n     *  - sender: The sender address from the src chain.\n     *  - nonce: The nonce of the LayerZero message.\n     * @param _guid The unique identifier for the received LayerZero message.\n     * @param _message The encoded message.\n     * @dev _executor The address of the executor.\n     * @dev _extraData Additional data.\n     */\n    function _lzReceive(\n        Origin calldata _origin,\n        bytes32 _guid,\n        bytes calldata _message,\n        address /*_executor*/, // @dev unused in the default implementation.\n        bytes calldata /*_extraData*/ // @dev unused in the default implementation.\n    ) internal virtual override {\n        // @dev The src sending chain doesnt know the address length on this chain (potentially non-evm)\n        // Thus everything is bytes32() encoded in flight.\n        address toAddress = _message.sendTo().bytes32ToAddress();\n        // @dev Credit the amountLD to the recipient and return the ACTUAL amount the recipient received in local decimals\n        uint256 amountReceivedLD = _credit(toAddress, _toLD(_message.amountSD()), _origin.srcEid);\n\n        if (_message.isComposed()) {\n            // @dev Proprietary composeMsg format for the OFT.\n            bytes memory composeMsg = OFTComposeMsgCodec.encode(\n                _origin.nonce,\n                _origin.srcEid,\n                amountReceivedLD,\n                _message.composeMsg()\n            );\n\n            // @dev Stores the lzCompose payload that will be executed in a separate tx.\n            // Standardizes functionality for executing arbitrary contract invocation on some non-evm chains.\n            // @dev The off-chain executor will listen and process the msg based on the src-chain-callers compose options passed.\n            // @dev The index is used when a OApp needs to compose multiple msgs on lzReceive.\n            // For default OFT implementation there is only 1 compose msg per lzReceive, thus its always 0.\n            endpoint.sendCompose(toAddress, _guid, 0 /* the index of the composed message*/, composeMsg);\n        }\n\n        emit OFTReceived(_guid, _origin.srcEid, toAddress, amountReceivedLD);\n    }\n\n    /**\n     * @dev Internal function to handle the OAppPreCrimeSimulator simulated receive.\n     * @param _origin The origin information.\n     *  - srcEid: The source chain endpoint ID.\n     *  - sender: The sender address from the src chain.\n     *  - nonce: The nonce of the LayerZero message.\n     * @param _guid The unique identifier for the received LayerZero message.\n     * @param _message The LayerZero message.\n     * @param _executor The address of the off-chain executor.\n     * @param _extraData Arbitrary data passed by the msg executor.\n     *\n     * @dev Enables the preCrime simulator to mock sending lzReceive() messages,\n     * routes the msg down from the OAppPreCrimeSimulator, and back up to the OAppReceiver.\n     */\n    function _lzReceiveSimulate(\n        Origin calldata _origin,\n        bytes32 _guid,\n        bytes calldata _message,\n        address _executor,\n        bytes calldata _extraData\n    ) internal virtual override {\n        _lzReceive(_origin, _guid, _message, _executor, _extraData);\n    }\n\n    /**\n     * @dev Check if the peer is considered 'trusted' by the OApp.\n     * @param _eid The endpoint ID to check.\n     * @param _peer The peer to check.\n     * @return Whether the peer passed is considered 'trusted' by the OApp.\n     *\n     * @dev Enables OAppPreCrimeSimulator to check whether a potential Inbound Packet is from a trusted source.\n     */\n    function isPeer(uint32 _eid, bytes32 _peer) public view virtual override returns (bool) {\n        return peers[_eid] == _peer;\n    }\n\n    /**\n     * @dev Internal function to remove dust from the given local decimal amount.\n     * @param _amountLD The amount in local decimals.\n     * @return amountLD The amount after removing dust.\n     *\n     * @dev Prevents the loss of dust when moving amounts between chains with different decimals.\n     * @dev eg. uint(123) with a conversion rate of 100 becomes uint(100).\n     */\n    function _removeDust(uint256 _amountLD) internal view virtual returns (uint256 amountLD) {\n        return (_amountLD / decimalConversionRate) * decimalConversionRate;\n    }\n\n    /**\n     * @dev Internal function to convert an amount from shared decimals into local decimals.\n     * @param _amountSD The amount in shared decimals.\n     * @return amountLD The amount in local decimals.\n     */\n    function _toLD(uint64 _amountSD) internal view virtual returns (uint256 amountLD) {\n        return _amountSD * decimalConversionRate;\n    }\n\n    /**\n     * @dev Internal function to convert an amount from local decimals into shared decimals.\n     * @param _amountLD The amount in local decimals.\n     * @return amountSD The amount in shared decimals.\n     */\n    function _toSD(uint256 _amountLD) internal view virtual returns (uint64 amountSD) {\n        return uint64(_amountLD / decimalConversionRate);\n    }\n\n    /**\n     * @dev Internal function to mock the amount mutation from a OFT debit() operation.\n     * @param _amountLD The amount to send in local decimals.\n     * @param _minAmountLD The minimum amount to send in local decimals.\n     * @dev _dstEid The destination endpoint ID.\n     * @return amountSentLD The amount sent, in local decimals.\n     * @return amountReceivedLD The amount to be received on the remote chain, in local decimals.\n     *\n     * @dev This is where things like fees would be calculated and deducted from the amount to be received on the remote.\n     */\n    function _debitView(\n        uint256 _amountLD,\n        uint256 _minAmountLD,\n        uint32 /*_dstEid*/\n    ) internal view virtual returns (uint256 amountSentLD, uint256 amountReceivedLD) {\n        // @dev Remove the dust so nothing is lost on the conversion between chains with different decimals for the token.\n        amountSentLD = _removeDust(_amountLD);\n        // @dev The amount to send is the same as amount received in the default implementation.\n        amountReceivedLD = amountSentLD;\n\n        // @dev Check for slippage.\n        if (amountReceivedLD < _minAmountLD) {\n            revert SlippageExceeded(amountReceivedLD, _minAmountLD);\n        }\n    }\n\n    /**\n     * @dev Internal function to perform a debit operation.\n     * @param _from The address to debit.\n     * @param _amountLD The amount to send in local decimals.\n     * @param _minAmountLD The minimum amount to send in local decimals.\n     * @param _dstEid The destination endpoint ID.\n     * @return amountSentLD The amount sent in local decimals.\n     * @return amountReceivedLD The amount received in local decimals on the remote.\n     *\n     * @dev Defined here but are intended to be overriden depending on the OFT implementation.\n     * @dev Depending on OFT implementation the _amountLD could differ from the amountReceivedLD.\n     */\n    function _debit(\n        address _from,\n        uint256 _amountLD,\n        uint256 _minAmountLD,\n        uint32 _dstEid\n    ) internal virtual returns (uint256 amountSentLD, uint256 amountReceivedLD);\n\n    /**\n     * @dev Internal function to perform a credit operation.\n     * @param _to The address to credit.\n     * @param _amountLD The amount to credit in local decimals.\n     * @param _srcEid The source endpoint ID.\n     * @return amountReceivedLD The amount ACTUALLY received in local decimals.\n     *\n     * @dev Defined here but are intended to be overriden depending on the OFT implementation.\n     * @dev Depending on OFT implementation the _amountLD could differ from the amountReceivedLD.\n     */\n    function _credit(\n        address _to,\n        uint256 _amountLD,\n        uint32 _srcEid\n    ) internal virtual returns (uint256 amountReceivedLD);\n}\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/LayerZero-v2/packages/layerzero-v2/evm/protocol/contracts/interfaces/ILayerZeroEndpointV2.sol","source_code":"// SPDX-License-Identifier: MIT\n\npragma solidity >=0.8.0;\n\nimport { IMessageLibManager } from \"./IMessageLibManager.sol\";\nimport { IMessagingComposer } from \"./IMessagingComposer.sol\";\nimport { IMessagingChannel } from \"./IMessagingChannel.sol\";\nimport { IMessagingContext } from \"./IMessagingContext.sol\";\n\nstruct MessagingParams {\n    uint32 dstEid;\n    bytes32 receiver;\n    bytes message;\n    bytes options;\n    bool payInLzToken;\n}\n\nstruct MessagingReceipt {\n    bytes32 guid;\n    uint64 nonce;\n    MessagingFee fee;\n}\n\nstruct MessagingFee {\n    uint256 nativeFee;\n    uint256 lzTokenFee;\n}\n\nstruct Origin {\n    uint32 srcEid;\n    bytes32 sender;\n    uint64 nonce;\n}\n\ninterface ILayerZeroEndpointV2 is IMessageLibManager, IMessagingComposer, IMessagingChannel, IMessagingContext {\n    event PacketSent(bytes encodedPayload, bytes options, address sendLibrary);\n\n    event PacketVerified(Origin origin, address receiver, bytes32 payloadHash);\n\n    event PacketDelivered(Origin origin, address receiver);\n\n    event LzReceiveAlert(\n        address indexed receiver,\n        address indexed executor,\n        Origin origin,\n        bytes32 guid,\n        uint256 gas,\n        uint256 value,\n        bytes message,\n        bytes extraData,\n        bytes reason\n    );\n\n    event LzTokenSet(address token);\n\n    event DelegateSet(address sender, address delegate);\n\n    function quote(MessagingParams calldata _params, address _sender) external view returns (MessagingFee memory);\n\n    function send(\n        MessagingParams calldata _params,\n        address _refundAddress\n    ) external payable returns (MessagingReceipt memory);\n\n    function verify(Origin calldata _origin, address _receiver, bytes32 _payloadHash) external;\n\n    function verifiable(Origin calldata _origin, address _receiver) external view returns (bool);\n\n    function initializable(Origin calldata _origin, address _receiver) external view returns (bool);\n\n    function lzReceive(\n        Origin calldata _origin,\n        address _receiver,\n        bytes32 _guid,\n        bytes calldata _message,\n        bytes calldata _extraData\n    ) external payable;\n\n    // oapp can burn messages partially by calling this function with its own business logic if messages are verified in order\n    function clear(address _oapp, Origin calldata _origin, bytes32 _guid, bytes calldata _message) external;\n\n    function setLzToken(address _lzToken) external;\n\n    function lzToken() external view returns (address);\n\n    function nativeToken() external view returns (address);\n\n    function setDelegate(address _delegate) external;\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":"src/governance/AllocationVoting.sol","source_code":"// SPDX-License-Identifier: MIT\npragma solidity 0.8.28;\n\nimport {FixedPointMathLib} from \"@solmate/src/utils/FixedPointMathLib.sol\";\n\nimport {EpochLib} from \"@libraries/EpochLib.sol\";\nimport {CoreRoles} from \"@libraries/CoreRoles.sol\";\nimport {FarmTypes} from \"@libraries/FarmTypes.sol\";\nimport {FarmRegistry} from \"@integrations/FarmRegistry.sol\";\nimport {IMaturityFarm} from \"@interfaces/IMaturityFarm.sol\";\nimport {CoreControlled} from \"@core/CoreControlled.sol\";\nimport {LockingController} from \"@locking/LockingController.sol\";\nimport {LockedPositionToken} from \"@tokens/LockedPositionToken.sol\";\n\n/// @notice Allocation voting contract\n/// In this contract, locked users can vote for the farms where they want the protocol to allocate\n/// their assets. Liquid farm & Illiquid farm votes are treated separately: liquid votes are used\n/// to rebalance capital to the desired allocation (vote result) at every epoch, while illiquid votes\n/// are only deciding where funds are allocated on a given week (in an additive manner, there is no\n/// rebalancing between farms on the illiquid side).\n/// Votes on a given epoch are only applying on the next epoch, leaving users with a full epoch\n/// to cast their votes. Votes should be performed every week, or they will be considered outdated.\n/// This means that a farm with 0 votes on a given epoch will not persist its weight on the next\n/// epoch, its weight will become 0 on the next epoch.\ncontract AllocationVoting is CoreControlled {\n    using EpochLib for uint256;\n    using FixedPointMathLib for uint256;\n\n    error InvalidAsset(address _asset);\n    error AlreadyVoted(address _user, uint32 _unwindingEpochs);\n    error NoVotingPower(address _user, uint32 _unwindingEpochs);\n    error UnknownFarm(address farm, bool liquid);\n    error InvalidWeights(uint256 _expectedPower, uint256 _actualPower);\n    error InvalidTargetBucket(address _farm, uint256 _maturity, uint256 _userUnbondingTimestamp);\n\n    event FarmVoteRegistered(\n        uint256 indexed timestamp,\n        uint256 indexed epoch,\n        address indexed user,\n        uint32 unwindingEpochs,\n        AllocationVote[] liquidVotes,\n        AllocationVote[] illiquidVotes,\n        uint256 userWeight\n    );\n\n    struct AllocationVote {\n        address farm;\n        uint96 weight;\n    }\n\n    struct FarmWeightData {\n        // epoch of the last vote\n        uint32 epoch;\n        // weight returned if the current epoch is exactly equal to `epoch`\n        uint112 currentWeight;\n        // weight updated on votes, committed to the `currentWeight` when a vote is cast\n        // on an epoch that is later than the stored epoch.\n        uint112 nextWeight;\n    }\n\n    address public lockingController;\n    address public farmRegistry;\n\n    mapping(address farm => FarmWeightData) public farmWeightData;\n    mapping(address user => mapping(uint32 unwindingEpochs => uint32 epoch)) public lastVoteEpoch;\n\n    constructor(address _core, address _lockingController, address _farmRegistry) CoreControlled(_core) {\n        lockingController = _lockingController;\n        farmRegistry = _farmRegistry;\n    }\n\n    /// @notice Returns the weight of the farm for the given epoch\n    /// @param _farm The address of the farm\n    /// @return uint256 The weight of the farm for the given epoch\n    function getVote(address _farm) external view returns (uint256) {\n        return _getFarmWeight(farmWeightData[_farm], uint32(block.timestamp.epoch()));\n    }\n\n    /// @notice Returns the vote weights for the given farm type (liquid or illiquid)\n    /// @param _farmType Determine for which farm type subset to return votes for\n    /// @return address[] farms\n    /// @return uint256[] farms percentage\n    /// @return uint256 total power\n    function getVoteWeights(uint256 _farmType) external view returns (address[] memory, uint256[] memory, uint256) {\n        address[] memory farms = FarmRegistry(farmRegistry).getTypeFarms(_farmType);\n        (uint256[] memory weights, uint256 totalPower) = _getVoteWeights(farms);\n        return (farms, weights, totalPower);\n    }\n\n    function getAssetVoteWeights(address _asset, uint256 _farmType)\n        external\n        view\n        returns (address[] memory, uint256[] memory, uint256)\n    {\n        address[] memory farms = FarmRegistry(farmRegistry).getAssetTypeFarms(_asset, _farmType);\n        (uint256[] memory weights, uint256 totalPower) = _getVoteWeights(farms);\n        return (farms, weights, totalPower);\n    }\n\n    /// @notice Casts a vote for the given farm\n    /// @param _asset to which asset do these farms belong to\n    /// @param _unwindingEpochs The number of epochs to unwind of the user\n    /// @param _liquidVotes The liquid votes\n    /// @param _illiquidVotes The illiquid votes\n    function vote(\n        address _user,\n        address _asset,\n        uint32 _unwindingEpochs,\n        AllocationVote[] calldata _liquidVotes,\n        AllocationVote[] calldata _illiquidVotes\n    ) external whenNotPaused onlyCoreRole(CoreRoles.ENTRY_POINT) {\n        require(FarmRegistry(farmRegistry).isAssetEnabled(_asset), InvalidAsset(_asset));\n\n        uint32 epoch = uint32(block.timestamp.epoch());\n        require(lastVoteEpoch[_user][_unwindingEpochs] < epoch, AlreadyVoted(_user, _unwindingEpochs));\n        lastVoteEpoch[_user][_unwindingEpochs] = epoch;\n\n        uint256 weight = LockingController(lockingController).rewardWeightForUnwindingEpochs(_user, _unwindingEpochs);\n        require(weight > 0, NoVotingPower(_user, _unwindingEpochs));\n\n        if (_illiquidVotes.length > 0) {\n            _storeUserVotes(_asset, _unwindingEpochs, epoch, weight, _illiquidVotes, false);\n        }\n        if (_liquidVotes.length > 0) {\n            _storeUserVotes(_asset, _unwindingEpochs, epoch, weight, _liquidVotes, true);\n        }\n\n        // restrict transfer until the next epoch after voting\n        address shareToken = LockingController(lockingController).shareToken(_unwindingEpochs);\n        LockedPositionToken(shareToken).restrictTransferUntilNextEpoch(_user);\n\n        emit FarmVoteRegistered(block.timestamp, epoch, _user, _unwindingEpochs, _liquidVotes, _illiquidVotes, weight);\n    }\n\n    /// -----------------------------------------------------------------------------------------------\n    /// Internal helpers\n    /// -----------------------------------------------------------------------------------------------\n\n    /// @notice Returns the weight of the farm for the given epoch\n    /// @param _data The farm weight data\n    /// @param _epoch The epoch of the vote\n    /// @return uint256 The weight of the farm for the given epoch\n    function _getFarmWeight(FarmWeightData memory _data, uint32 _epoch) internal pure returns (uint256) {\n        // if last vote was in current epoch, return the currentWeight\n        if (_data.epoch == _epoch) {\n            return _data.currentWeight;\n        }\n        // if last vote was in previous epoch, return the nextWeight\n        if (_data.epoch == _epoch - 1) {\n            return _data.nextWeight;\n        }\n        // otherwise, return 0 (do not persist votes if they are older than 1 epoch ago)\n        return 0;\n    }\n\n    /// @notice Stores the user's votes for the given farms\n    /// @param _unwindingEpochs The number of epochs to unwind of the user\n    /// @param _epoch The epoch of the vote\n    /// @param _userWeight The weight of the user\n    /// @param _votes The votes to store\n    /// @param _liquid Whether the farms are liquid or illiquid\n    function _storeUserVotes(\n        address _asset,\n        uint32 _unwindingEpochs,\n        uint32 _epoch,\n        uint256 _userWeight,\n        AllocationVote[] calldata _votes,\n        bool _liquid\n    ) internal {\n        uint256 weightAllocated = 0;\n\n        for (uint256 i = 0; i < _votes.length; i++) {\n            address farm = _votes[i].farm;\n            if (_liquid) {\n                _validateAssetAndType(_asset, farm, FarmTypes.LIQUID);\n            } else {\n                _validateAssetAndType(_asset, farm, FarmTypes.MATURITY);\n                _validateFarmBucket(farm, _unwindingEpochs);\n            }\n\n            FarmWeightData memory data = farmWeightData[farm];\n            if (data.epoch != _epoch) {\n                // roll over pending weight votes that are in \"nextWeight\" into \"currentWeight\"\n                // when a new epoch starts and a vote is cast\n                if (data.epoch == _epoch - 1) {\n                    data = FarmWeightData({epoch: _epoch, currentWeight: data.nextWeight, nextWeight: 0});\n                } else {\n                    data = FarmWeightData({epoch: _epoch, currentWeight: 0, nextWeight: 0});\n                }\n            }\n\n            data.nextWeight += uint112(_userWeight.mulWadDown(_votes[i].weight));\n            farmWeightData[farm] = data;\n            weightAllocated += _votes[i].weight;\n        }\n\n        // user must allocate all of their voting power when casting a vote\n        // or not vote for a particular farm type at all\n        // for example, user can choose to vote only for liquid farms, or only for maturity farms\n        require(\n            weightAllocated == FixedPointMathLib.WAD || weightAllocated == 0,\n            InvalidWeights(FixedPointMathLib.WAD, weightAllocated)\n        );\n    }\n\n    function _getVoteWeights(address[] memory _farms) internal view returns (uint256[] memory, uint256) {\n        uint32 epoch = uint32(block.timestamp.epoch());\n        uint256[] memory weights = new uint256[](_farms.length);\n\n        uint256 totalPower = 0;\n\n        for (uint256 i = 0; i < _farms.length; i++) {\n            weights[i] = _getFarmWeight(farmWeightData[_farms[i]], epoch);\n            totalPower += weights[i];\n        }\n\n        return (weights, totalPower);\n    }\n\n    function _validateAssetAndType(address _asset, address _farm, uint256 _type) internal view {\n        FarmRegistry _farmRegistry = FarmRegistry(farmRegistry);\n        require(_farmRegistry.isFarmOfType(_farm, uint256(_type)), UnknownFarm(_farm, true));\n        require(_farmRegistry.isFarmOfAsset(_farm, _asset), InvalidAsset(_asset));\n    }\n\n    function _validateFarmBucket(address _farm, uint32 _unwindingEpochs) internal view {\n        uint256 maturity = IMaturityFarm(_farm).maturity();\n        uint256 userUnwindingTimestamp = (block.timestamp.nextEpoch() + _unwindingEpochs).epochToTimestamp();\n        require(maturity <= userUnwindingTimestamp, InvalidTargetBucket(_farm, maturity, userUnwindingTimestamp));\n    }\n}\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":"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/LayerZero-v2/packages/layerzero-v2/evm/oapp/contracts/precrime/libs/Packet.sol","source_code":"// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.20;\n\nimport { Origin } from \"@layerzerolabs/lz-evm-protocol-v2/contracts/interfaces/ILayerZeroEndpointV2.sol\";\nimport { PacketV1Codec } from \"@layerzerolabs/lz-evm-protocol-v2/contracts/messagelib/libs/PacketV1Codec.sol\";\n\n/**\n * @title InboundPacket\n * @dev Structure representing an inbound packet received by the contract.\n */\nstruct InboundPacket {\n    Origin origin; // Origin information of the packet.\n    uint32 dstEid; // Destination endpointId of the packet.\n    address receiver; // Receiver address for the packet.\n    bytes32 guid; // Unique identifier of the packet.\n    uint256 value; // msg.value of the packet.\n    address executor; // Executor address for the packet.\n    bytes message; // Message payload of the packet.\n    bytes extraData; // Additional arbitrary data for the packet.\n}\n\n/**\n * @title PacketDecoder\n * @dev Library for decoding LayerZero packets.\n */\nlibrary PacketDecoder {\n    using PacketV1Codec for bytes;\n\n    /**\n     * @dev Decode an inbound packet from the given packet data.\n     * @param _packet The packet data to decode.\n     * @return packet An InboundPacket struct representing the decoded packet.\n     */\n    function decode(bytes calldata _packet) internal pure returns (InboundPacket memory packet) {\n        packet.origin = Origin(_packet.srcEid(), _packet.sender(), _packet.nonce());\n        packet.dstEid = _packet.dstEid();\n        packet.receiver = _packet.receiverB20();\n        packet.guid = _packet.guid();\n        packet.message = _packet.message();\n    }\n\n    /**\n     * @dev Decode multiple inbound packets from the given packet data and associated message values.\n     * @param _packets An array of packet data to decode.\n     * @param _packetMsgValues An array of associated message values for each packet.\n     * @return packets An array of InboundPacket structs representing the decoded packets.\n     */\n    function decode(\n        bytes[] calldata _packets,\n        uint256[] memory _packetMsgValues\n    ) internal pure returns (InboundPacket[] memory packets) {\n        packets = new InboundPacket[](_packets.length);\n        for (uint256 i = 0; i < _packets.length; i++) {\n            bytes calldata packet = _packets[i];\n            packets[i] = PacketDecoder.decode(packet);\n            // @dev Allows the verifier to specify the msg.value that gets passed in lzReceive.\n            packets[i].value = _packetMsgValues[i];\n        }\n    }\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":"lib/LayerZero-v2/packages/layerzero-v2/evm/oapp/contracts/oapp/interfaces/IOAppCore.sol","source_code":"// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.20;\n\nimport { ILayerZeroEndpointV2 } from \"@layerzerolabs/lz-evm-protocol-v2/contracts/interfaces/ILayerZeroEndpointV2.sol\";\n\n/**\n * @title IOAppCore\n */\ninterface IOAppCore {\n    // Custom error messages\n    error OnlyPeer(uint32 eid, bytes32 sender);\n    error NoPeer(uint32 eid);\n    error InvalidEndpointCall();\n    error InvalidDelegate();\n\n    // Event emitted when a peer (OApp) is set for a corresponding endpoint\n    event PeerSet(uint32 eid, bytes32 peer);\n\n    /**\n     * @notice Retrieves the OApp version information.\n     * @return senderVersion The version of the OAppSender.sol contract.\n     * @return receiverVersion The version of the OAppReceiver.sol contract.\n     */\n    function oAppVersion() external view returns (uint64 senderVersion, uint64 receiverVersion);\n\n    /**\n     * @notice Retrieves the LayerZero endpoint associated with the OApp.\n     * @return iEndpoint The LayerZero endpoint as an interface.\n     */\n    function endpoint() external view returns (ILayerZeroEndpointV2 iEndpoint);\n\n    /**\n     * @notice Retrieves the peer (OApp) associated with a corresponding endpoint.\n     * @param _eid The endpoint ID.\n     * @return peer The peer address (OApp instance) associated with the corresponding endpoint.\n     */\n    function peers(uint32 _eid) external view returns (bytes32 peer);\n\n    /**\n     * @notice Sets the peer address (OApp instance) for a corresponding endpoint.\n     * @param _eid The endpoint ID.\n     * @param _peer The address of the peer to be associated with the corresponding endpoint.\n     */\n    function setPeer(uint32 _eid, bytes32 _peer) external;\n\n    /**\n     * @notice Sets the delegate address for the OApp Core.\n     * @param _delegate The address of the delegate to be set.\n     */\n    function setDelegate(address _delegate) external;\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/TransientSlot.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.3.0) (utils/TransientSlot.sol)\n// This file was procedurally generated from scripts/generate/templates/TransientSlot.js.\n\npragma solidity ^0.8.24;\n\n/**\n * @dev Library for reading and writing value-types to specific transient storage slots.\n *\n * Transient slots are often used to store temporary values that are removed after the current transaction.\n * This library helps with reading and writing to such slots without the need for inline assembly.\n *\n *  * Example reading and writing values using transient storage:\n * ```solidity\n * contract Lock {\n *     using TransientSlot for *;\n *\n *     // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.\n *     bytes32 internal constant _LOCK_SLOT = 0xf4678858b2b588224636b8522b729e7722d32fc491da849ed75b3fdf3c84f542;\n *\n *     modifier locked() {\n *         require(!_LOCK_SLOT.asBoolean().tload());\n *\n *         _LOCK_SLOT.asBoolean().tstore(true);\n *         _;\n *         _LOCK_SLOT.asBoolean().tstore(false);\n *     }\n * }\n * ```\n *\n * TIP: Consider using this library along with {SlotDerivation}.\n */\nlibrary TransientSlot {\n    /**\n     * @dev UDVT that represents a slot holding an address.\n     */\n    type AddressSlot is bytes32;\n\n    /**\n     * @dev Cast an arbitrary slot to a AddressSlot.\n     */\n    function asAddress(bytes32 slot) internal pure returns (AddressSlot) {\n        return AddressSlot.wrap(slot);\n    }\n\n    /**\n     * @dev UDVT that represents a slot holding a bool.\n     */\n    type BooleanSlot is bytes32;\n\n    /**\n     * @dev Cast an arbitrary slot to a BooleanSlot.\n     */\n    function asBoolean(bytes32 slot) internal pure returns (BooleanSlot) {\n        return BooleanSlot.wrap(slot);\n    }\n\n    /**\n     * @dev UDVT that represents a slot holding a bytes32.\n     */\n    type Bytes32Slot is bytes32;\n\n    /**\n     * @dev Cast an arbitrary slot to a Bytes32Slot.\n     */\n    function asBytes32(bytes32 slot) internal pure returns (Bytes32Slot) {\n        return Bytes32Slot.wrap(slot);\n    }\n\n    /**\n     * @dev UDVT that represents a slot holding a uint256.\n     */\n    type Uint256Slot is bytes32;\n\n    /**\n     * @dev Cast an arbitrary slot to a Uint256Slot.\n     */\n    function asUint256(bytes32 slot) internal pure returns (Uint256Slot) {\n        return Uint256Slot.wrap(slot);\n    }\n\n    /**\n     * @dev UDVT that represents a slot holding a int256.\n     */\n    type Int256Slot is bytes32;\n\n    /**\n     * @dev Cast an arbitrary slot to a Int256Slot.\n     */\n    function asInt256(bytes32 slot) internal pure returns (Int256Slot) {\n        return Int256Slot.wrap(slot);\n    }\n\n    /**\n     * @dev Load the value held at location `slot` in transient storage.\n     */\n    function tload(AddressSlot slot) internal view returns (address value) {\n        assembly (\"memory-safe\") {\n            value := tload(slot)\n        }\n    }\n\n    /**\n     * @dev Store `value` at location `slot` in transient storage.\n     */\n    function tstore(AddressSlot slot, address value) internal {\n        assembly (\"memory-safe\") {\n            tstore(slot, value)\n        }\n    }\n\n    /**\n     * @dev Load the value held at location `slot` in transient storage.\n     */\n    function tload(BooleanSlot slot) internal view returns (bool value) {\n        assembly (\"memory-safe\") {\n            value := tload(slot)\n        }\n    }\n\n    /**\n     * @dev Store `value` at location `slot` in transient storage.\n     */\n    function tstore(BooleanSlot slot, bool value) internal {\n        assembly (\"memory-safe\") {\n            tstore(slot, value)\n        }\n    }\n\n    /**\n     * @dev Load the value held at location `slot` in transient storage.\n     */\n    function tload(Bytes32Slot slot) internal view returns (bytes32 value) {\n        assembly (\"memory-safe\") {\n            value := tload(slot)\n        }\n    }\n\n    /**\n     * @dev Store `value` at location `slot` in transient storage.\n     */\n    function tstore(Bytes32Slot slot, bytes32 value) internal {\n        assembly (\"memory-safe\") {\n            tstore(slot, value)\n        }\n    }\n\n    /**\n     * @dev Load the value held at location `slot` in transient storage.\n     */\n    function tload(Uint256Slot slot) internal view returns (uint256 value) {\n        assembly (\"memory-safe\") {\n            value := tload(slot)\n        }\n    }\n\n    /**\n     * @dev Store `value` at location `slot` in transient storage.\n     */\n    function tstore(Uint256Slot slot, uint256 value) internal {\n        assembly (\"memory-safe\") {\n            tstore(slot, value)\n        }\n    }\n\n    /**\n     * @dev Load the value held at location `slot` in transient storage.\n     */\n    function tload(Int256Slot slot) internal view returns (int256 value) {\n        assembly (\"memory-safe\") {\n            value := tload(slot)\n        }\n    }\n\n    /**\n     * @dev Store `value` at location `slot` in transient storage.\n     */\n    function tstore(Int256Slot slot, int256 value) internal {\n        assembly (\"memory-safe\") {\n            tstore(slot, value)\n        }\n    }\n}\n"},{"file_path":"lib/LayerZero-v2/packages/layerzero-v2/evm/oapp/contracts/oft/libs/OFTMsgCodec.sol","source_code":"// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.20;\n\nlibrary OFTMsgCodec {\n    // Offset constants for encoding and decoding OFT messages\n    uint8 private constant SEND_TO_OFFSET = 32;\n    uint8 private constant SEND_AMOUNT_SD_OFFSET = 40;\n\n    /**\n     * @dev Encodes an OFT LayerZero message.\n     * @param _sendTo The recipient address.\n     * @param _amountShared The amount in shared decimals.\n     * @param _composeMsg The composed message.\n     * @return _msg The encoded message.\n     * @return hasCompose A boolean indicating whether the message has a composed payload.\n     */\n    function encode(\n        bytes32 _sendTo,\n        uint64 _amountShared,\n        bytes memory _composeMsg\n    ) internal view returns (bytes memory _msg, bool hasCompose) {\n        hasCompose = _composeMsg.length > 0;\n        // @dev Remote chains will want to know the composed function caller ie. msg.sender on the src.\n        _msg = hasCompose\n            ? abi.encodePacked(_sendTo, _amountShared, addressToBytes32(msg.sender), _composeMsg)\n            : abi.encodePacked(_sendTo, _amountShared);\n    }\n\n    /**\n     * @dev Checks if the OFT message is composed.\n     * @param _msg The OFT message.\n     * @return A boolean indicating whether the message is composed.\n     */\n    function isComposed(bytes calldata _msg) internal pure returns (bool) {\n        return _msg.length > SEND_AMOUNT_SD_OFFSET;\n    }\n\n    /**\n     * @dev Retrieves the recipient address from the OFT message.\n     * @param _msg The OFT message.\n     * @return The recipient address.\n     */\n    function sendTo(bytes calldata _msg) internal pure returns (bytes32) {\n        return bytes32(_msg[:SEND_TO_OFFSET]);\n    }\n\n    /**\n     * @dev Retrieves the amount in shared decimals from the OFT message.\n     * @param _msg The OFT message.\n     * @return The amount in shared decimals.\n     */\n    function amountSD(bytes calldata _msg) internal pure returns (uint64) {\n        return uint64(bytes8(_msg[SEND_TO_OFFSET:SEND_AMOUNT_SD_OFFSET]));\n    }\n\n    /**\n     * @dev Retrieves the composed message from the OFT message.\n     * @param _msg The OFT message.\n     * @return The composed message.\n     */\n    function composeMsg(bytes calldata _msg) internal pure returns (bytes memory) {\n        return _msg[SEND_AMOUNT_SD_OFFSET:];\n    }\n\n    /**\n     * @dev Converts an address to bytes32.\n     * @param _addr The address to convert.\n     * @return The bytes32 representation of the address.\n     */\n    function addressToBytes32(address _addr) internal pure returns (bytes32) {\n        return bytes32(uint256(uint160(_addr)));\n    }\n\n    /**\n     * @dev Converts bytes32 to an address.\n     * @param _b The bytes32 value to convert.\n     * @return The address representation of bytes32.\n     */\n    function bytes32ToAddress(bytes32 _b) internal pure returns (address) {\n        return address(uint160(uint256(_b)));\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/LayerZero-v2/packages/layerzero-v2/evm/oapp/contracts/oapp/OAppSender.sol","source_code":"// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.20;\n\nimport { SafeERC20, IERC20 } from \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\nimport { MessagingParams, MessagingFee, MessagingReceipt } from \"@layerzerolabs/lz-evm-protocol-v2/contracts/interfaces/ILayerZeroEndpointV2.sol\";\nimport { OAppCore } from \"./OAppCore.sol\";\n\n/**\n * @title OAppSender\n * @dev Abstract contract implementing the OAppSender functionality for sending messages to a LayerZero endpoint.\n */\nabstract contract OAppSender is OAppCore {\n    using SafeERC20 for IERC20;\n\n    // Custom error messages\n    error NotEnoughNative(uint256 msgValue);\n    error LzTokenUnavailable();\n\n    // @dev The version of the OAppSender implementation.\n    // @dev Version is bumped when changes are made to this contract.\n    uint64 internal constant SENDER_VERSION = 1;\n\n    /**\n     * @notice Retrieves the OApp version information.\n     * @return senderVersion The version of the OAppSender.sol contract.\n     * @return receiverVersion The version of the OAppReceiver.sol contract.\n     *\n     * @dev Providing 0 as the default for OAppReceiver version. Indicates that the OAppReceiver is not implemented.\n     * ie. this is a SEND only OApp.\n     * @dev If the OApp uses both OAppSender and OAppReceiver, then this needs to be override returning the correct versions\n     */\n    function oAppVersion() public view virtual returns (uint64 senderVersion, uint64 receiverVersion) {\n        return (SENDER_VERSION, 0);\n    }\n\n    /**\n     * @dev Internal function to interact with the LayerZero EndpointV2.quote() for fee calculation.\n     * @param _dstEid The destination endpoint ID.\n     * @param _message The message payload.\n     * @param _options Additional options for the message.\n     * @param _payInLzToken Flag indicating whether to pay the fee in LZ tokens.\n     * @return fee The calculated MessagingFee for the message.\n     *      - nativeFee: The native fee for the message.\n     *      - lzTokenFee: The LZ token fee for the message.\n     */\n    function _quote(\n        uint32 _dstEid,\n        bytes memory _message,\n        bytes memory _options,\n        bool _payInLzToken\n    ) internal view virtual returns (MessagingFee memory fee) {\n        return\n            endpoint.quote(\n                MessagingParams(_dstEid, _getPeerOrRevert(_dstEid), _message, _options, _payInLzToken),\n                address(this)\n            );\n    }\n\n    /**\n     * @dev Internal function to interact with the LayerZero EndpointV2.send() for sending a message.\n     * @param _dstEid The destination endpoint ID.\n     * @param _message The message payload.\n     * @param _options Additional options for the message.\n     * @param _fee The calculated LayerZero fee for the message.\n     *      - nativeFee: The native fee.\n     *      - lzTokenFee: The lzToken fee.\n     * @param _refundAddress The address to receive any excess fee values sent to the endpoint.\n     * @return receipt The receipt for the sent message.\n     *      - guid: The unique identifier for the sent message.\n     *      - nonce: The nonce of the sent message.\n     *      - fee: The LayerZero fee incurred for the message.\n     */\n    function _lzSend(\n        uint32 _dstEid,\n        bytes memory _message,\n        bytes memory _options,\n        MessagingFee memory _fee,\n        address _refundAddress\n    ) internal virtual returns (MessagingReceipt memory receipt) {\n        // @dev Push corresponding fees to the endpoint, any excess is sent back to the _refundAddress from the endpoint.\n        uint256 messageValue = _payNative(_fee.nativeFee);\n        if (_fee.lzTokenFee > 0) _payLzToken(_fee.lzTokenFee);\n\n        return\n            // solhint-disable-next-line check-send-result\n            endpoint.send{ value: messageValue }(\n                MessagingParams(_dstEid, _getPeerOrRevert(_dstEid), _message, _options, _fee.lzTokenFee > 0),\n                _refundAddress\n            );\n    }\n\n    /**\n     * @dev Internal function to pay the native fee associated with the message.\n     * @param _nativeFee The native fee to be paid.\n     * @return nativeFee The amount of native currency paid.\n     *\n     * @dev If the OApp needs to initiate MULTIPLE LayerZero messages in a single transaction,\n     * this will need to be overridden because msg.value would contain multiple lzFees.\n     * @dev Should be overridden in the event the LayerZero endpoint requires a different native currency.\n     * @dev Some EVMs use an ERC20 as a method for paying transactions/gasFees.\n     * @dev The endpoint is EITHER/OR, ie. it will NOT support both types of native payment at a time.\n     */\n    function _payNative(uint256 _nativeFee) internal virtual returns (uint256 nativeFee) {\n        if (msg.value != _nativeFee) revert NotEnoughNative(msg.value);\n        return _nativeFee;\n    }\n\n    /**\n     * @dev Internal function to pay the LZ token fee associated with the message.\n     * @param _lzTokenFee The LZ token fee to be paid.\n     *\n     * @dev If the caller is trying to pay in the specified lzToken, then the lzTokenFee is passed to the endpoint.\n     * @dev Any excess sent, is passed back to the specified _refundAddress in the _lzSend().\n     */\n    function _payLzToken(uint256 _lzTokenFee) internal virtual {\n        // @dev Cannot cache the token because it is not immutable in the endpoint.\n        address lzToken = endpoint.lzToken();\n        if (lzToken == address(0)) revert LzTokenUnavailable();\n\n        // Pay LZ token fee by sending tokens to the endpoint.\n        IERC20(lzToken).safeTransferFrom(msg.sender, address(endpoint), _lzTokenFee);\n    }\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":"src/tokens/GovernanceToken.sol","source_code":"// SPDX-License-Identifier: MIT\npragma solidity 0.8.28;\n\nimport {OFTCore} from \"@layerzerolabs/lz-evm-oapp-v2/contracts/oft/OFTCore.sol\";\nimport {Ownable} from \"@layerzerolabs/lz-evm-oapp-v2/contracts/oapp/OAppCore.sol\";\n\nimport {ERC20} from \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\nimport {EIP712} from \"@openzeppelin/contracts/utils/cryptography/EIP712.sol\";\nimport {ERC20Votes} from \"@openzeppelin/contracts/token/ERC20/extensions/ERC20Votes.sol\";\nimport {ERC20Burnable} from \"@openzeppelin/contracts/token/ERC20/extensions/ERC20Burnable.sol\";\n\nimport {CoreControlled} from \"@core/CoreControlled.sol\";\n\n/// @notice InfiniFi Governance Token.\n/// This contract is meant to be used for INFI & wINFI tokens.\n/// @dev /!\\ This contract is initially owned by the deployer, and the deployer is set as the OApp delegate,\n/// to enable easier initial configuration. Make sure to transfer the privileges before enabling it in the protocol.\n/// This can be checked by reading this.owner() and this.endpoint().delegates(this).\ncontract GovernanceToken is CoreControlled, ERC20Burnable, ERC20Votes, OFTCore {\n    bytes32 private immutable _MINTER_ROLE;\n    bytes32 private immutable _BURNER_ROLE;\n\n    struct TokenConfig {\n        string name;\n        string symbol;\n        bytes32 minterRole;\n        bytes32 burnerRole;\n    }\n\n    /// @dev Escrow of tokens that have been bridged to other chains through OFT logic.\n    /// This escrow only exists on the L1. It is meant to allow a representative totalSupply()\n    /// on the L1, and contains bridge attacks to the part of the supply that has been bridged.\n    address public immutable escrow = address(uint160(uint256(keccak256(\"escrow\"))));\n\n    constructor(address _core, TokenConfig memory _config, address _lzEndpoint)\n        CoreControlled(_core)\n        ERC20(_config.name, _config.symbol)\n        EIP712(_config.name, \"1\")\n        OFTCore(decimals(), _lzEndpoint, msg.sender)\n        Ownable(msg.sender)\n    {\n        _MINTER_ROLE = _config.minterRole;\n        _BURNER_ROLE = _config.burnerRole;\n    }\n\n    function mint(address _to, uint256 _amount) external onlyCoreRole(_MINTER_ROLE) {\n        // only allow minting on L1, the supply shall be created on L1 and then\n        // bridged to L2s through the OFT logic.\n        require(block.chainid == 1);\n        _mint(_to, _amount);\n    }\n\n    function burn(uint256 _value) public override onlyCoreRole(_BURNER_ROLE) {\n        _burn(_msgSender(), _value);\n    }\n\n    function burnFrom(address _account, uint256 _value) public override onlyCoreRole(_BURNER_ROLE) {\n        _spendAllowance(_account, _msgSender(), _value);\n        _burn(_account, _value);\n    }\n\n    function _update(address _from, address _to, uint256 _value) internal override(ERC20, ERC20Votes) {\n        return ERC20Votes._update(_from, _to, _value);\n    }\n\n    // ERC-6372 time-based checkpoints.\n    function clock() public view override returns (uint48) {\n        return uint48(block.timestamp);\n    }\n\n    // ERC-6372 time-based checkpoints.\n    function CLOCK_MODE() public pure override returns (string memory) {\n        return \"mode=timestamp\";\n    }\n\n    // OFT function\n    function token() public view returns (address) {\n        return address(this);\n    }\n\n    // OFT function\n    function approvalRequired() external pure virtual returns (bool) {\n        return false;\n    }\n\n    // OFT function: bridge out\n    function _debit(address _from, uint256 _amountLD, uint256 _minAmountLD, uint32 _dstEid)\n        internal\n        virtual\n        override\n        returns (uint256 amountSentLD, uint256 amountReceivedLD)\n    {\n        (amountSentLD, amountReceivedLD) = _debitView(_amountLD, _minAmountLD, _dstEid);\n\n        // bridging L1->L2 sends tokens to the escrow\n        // bridging L2->L1 burns the tokens on the L2\n        if (block.chainid == 1) {\n            _update(_from, escrow, amountSentLD);\n        } else {\n            _burn(_from, amountSentLD);\n        }\n    }\n\n    // OFT function: bridge in\n    function _credit(\n        address _to,\n        uint256 _amount,\n        uint32 /*_srcEid*/\n    )\n        internal\n        virtual\n        override\n        returns (uint256)\n    {\n        // can't mint to address(0)\n        if (_to == address(0x0)) _to = address(this);\n\n        // bridging L2->L1 sends tokens from escrow to the recipient\n        // bridging L1->L2 mints new tokens on the L2\n        if (block.chainid == 1) {\n            _update(escrow, _to, _amount);\n        } else {\n            _mint(_to, _amount);\n        }\n        return _amount;\n    }\n}\n"},{"file_path":"lib/LayerZero-v2/packages/layerzero-v2/evm/protocol/contracts/interfaces/IMessagingComposer.sol","source_code":"// SPDX-License-Identifier: MIT\n\npragma solidity >=0.8.0;\n\ninterface IMessagingComposer {\n    event ComposeSent(address from, address to, bytes32 guid, uint16 index, bytes message);\n    event ComposeDelivered(address from, address to, bytes32 guid, uint16 index);\n    event LzComposeAlert(\n        address indexed from,\n        address indexed to,\n        address indexed executor,\n        bytes32 guid,\n        uint16 index,\n        uint256 gas,\n        uint256 value,\n        bytes message,\n        bytes extraData,\n        bytes reason\n    );\n\n    function composeQueue(\n        address _from,\n        address _to,\n        bytes32 _guid,\n        uint16 _index\n    ) external view returns (bytes32 messageHash);\n\n    function sendCompose(address _to, bytes32 _guid, uint16 _index, bytes calldata _message) external;\n\n    function lzCompose(\n        address _from,\n        address _to,\n        bytes32 _guid,\n        uint16 _index,\n        bytes calldata _message,\n        bytes calldata _extraData\n    ) external payable;\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/interfaces/IERC6372.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC6372.sol)\n\npragma solidity >=0.4.16;\n\ninterface IERC6372 {\n    /**\n     * @dev Clock used for flagging checkpoints. Can be overridden to implement timestamp based checkpoints (and voting).\n     */\n    function clock() external view returns (uint48);\n\n    /**\n     * @dev Description of the clock\n     */\n    // solhint-disable-next-line func-name-mixedcase\n    function CLOCK_MODE() external view returns (string memory);\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":"src/libraries/GatewayLib.sol","source_code":"// SPDX-License-Identifier: MIT\npragma solidity 0.8.28;\n\nimport {FixedPointMathLib} from \"@solmate/src/utils/FixedPointMathLib.sol\";\nimport {IERC20, ERC4626, Math} from \"@openzeppelin/contracts/token/ERC20/extensions/ERC4626.sol\";\n\nimport {EpochLib} from \"@libraries/EpochLib.sol\";\nimport {YieldSharingV2} from \"@finance/YieldSharingV2.sol\";\nimport {UnwindingModule} from \"@locking/UnwindingModule.sol\";\nimport {IInfiniFiGateway} from \"@interfaces/IInfiniFiGateway.sol\";\nimport {LockingController, MintController, RedeemController} from \"@gateway/InfiniFiGatewayV1.sol\";\n\n/// RT - Receipt Token\n/// ST - Staked Token\n/// LPT - Locked Position Token\nlibrary GatewayLib {\n    using Math for uint256;\n    using FixedPointMathLib for uint256;\n\n    error NoStakedToken();\n    error NoReceiptToken();\n    error NoLockedPositionToken(uint256 _unwindingEpochs);\n\n    /// ----------------------------------------------------------------------------\n    /// Token Getters\n    /// ----------------------------------------------------------------------------\n\n    function lockedPositionToken(IInfiniFiGateway _gateway, uint256 _unwindingEpochs)\n        internal\n        view\n        returns (address lpToken)\n    {\n        lpToken = LockingController(_gateway.getAddress(\"lockingController\")).shareToken(uint32(_unwindingEpochs));\n        require(lpToken != address(0), NoLockedPositionToken(_unwindingEpochs));\n    }\n\n    function stakedToken(IInfiniFiGateway _gateway) internal view returns (address _stakedToken) {\n        _stakedToken = _gateway.getAddress(\"stakedToken\");\n        require(_stakedToken != address(0), NoStakedToken());\n    }\n\n    function receiptToken(IInfiniFiGateway _gateway) internal view returns (address _receiptToken) {\n        _receiptToken = _gateway.getAddress(\"receiptToken\");\n        require(_receiptToken != address(0), NoReceiptToken());\n    }\n\n    /// ----------------------------------------------------------------------------\n    /// Conversion methods\n    /// ----------------------------------------------------------------------------\n\n    /// @notice Converts _amountIn of receipt tokens to staked tokens\n    /// @param _gateway reference\n    /// @param _amountIn receipt token amount\n    function receiptToStaked(IInfiniFiGateway _gateway, uint256 _amountIn) internal view returns (uint256) {\n        if (_amountIn == 0) return 0;\n\n        address yieldSharing = _gateway.getAddress(\"yieldSharing\");\n        uint256 totalAssets = ERC4626(stakedToken(_gateway)).totalAssets() + YieldSharingV2(yieldSharing).vested();\n        uint256 totalSupply = ERC4626(stakedToken(_gateway)).totalSupply();\n\n        return _amountIn.mulDiv(totalSupply + 1, totalAssets + 1, Math.Rounding.Floor);\n    }\n\n    /// @notice Converts _amountIn of staked tokens to receipt tokens\n    /// @param _gateway reference\n    /// @param _amountIn staked token amount\n    function stakedToReceipt(IInfiniFiGateway _gateway, uint256 _amountIn) internal view returns (uint256) {\n        if (_amountIn == 0) return 0;\n\n        address yieldSharing = _gateway.getAddress(\"yieldSharing\");\n        uint256 totalAssets = ERC4626(stakedToken(_gateway)).totalAssets() + YieldSharingV2(yieldSharing).vested();\n        uint256 totalSupply = ERC4626(stakedToken(_gateway)).totalSupply();\n\n        return _amountIn.mulDiv(totalAssets + 1, totalSupply + 1, Math.Rounding.Floor);\n    }\n\n    /// @notice Converts _amountIn of receipt tokens to amount of locked position tokens\n    /// @param _gateway gateway reference\n    /// @param _amountIn amount of receipt tokens\n    /// @param _unwindingEpochs plain number of unwinding epochs [1,2,3,etc]\n    function receiptToLocked(IInfiniFiGateway _gateway, uint256 _amountIn, uint256 _unwindingEpochs)\n        internal\n        view\n        returns (uint256)\n    {\n        if (_amountIn == 0) return 0;\n        LockingController lockingController = LockingController(_gateway.getAddress(\"lockingController\"));\n\n        (address lptAddress, uint256 totalReceiptTokens,) = lockingController.buckets(uint32(_unwindingEpochs));\n        uint256 totalShares = IERC20(lptAddress).totalSupply();\n        if (totalShares == 0) return _amountIn;\n        return _amountIn.mulDivDown(totalShares, totalReceiptTokens);\n    }\n\n    /// @notice How many receipt tokens we get when exchanged for locked position token _amountIn\n    /// @dev It is not possible to do this conversion right away\n    /// however it is a useful reference for getting the current lpt value\n    /// @param _gateway gateway reference\n    /// @param _amountIn amount of locked position tokens\n    /// @param _unwindingEpochs plain number of unwinding epochs [1,2,3,etc]\n    function lockedToReceipt(IInfiniFiGateway _gateway, uint256 _amountIn, uint256 _unwindingEpochs)\n        internal\n        view\n        returns (uint256)\n    {\n        if (_amountIn == 0) return 0;\n        LockingController lockingController = LockingController(_gateway.getAddress(\"lockingController\"));\n        (address lptAddress, uint256 totalReceiptTokens,) = lockingController.buckets(uint32(_unwindingEpochs));\n        uint256 totalShares = IERC20(lptAddress).totalSupply();\n        if (totalShares == 0) return _amountIn;\n        return _amountIn.mulDivDown(totalReceiptTokens, totalShares);\n    }\n\n    /// @notice Converts _amountIn of asset token to receipt token\n    /// @param _gateway reference\n    /// @param _amountIn amount of asset tokens\n    function assetToReceipt(IInfiniFiGateway _gateway, uint256 _amountIn) internal view returns (uint256) {\n        if (_amountIn == 0) return 0;\n        return MintController(_gateway.getAddress(\"mintController\")).assetToReceipt(_amountIn);\n    }\n\n    /// @notice Converts _amountIn of receipt token to asset token\n    /// @param _gateway reference\n    /// @param _amountIn amount of receipt tokens\n    function receiptToAsset(IInfiniFiGateway _gateway, uint256 _amountIn) internal view returns (uint256) {\n        if (_amountIn == 0) return 0;\n        return RedeemController(_gateway.getAddress(\"redeemController\")).receiptToAsset(_amountIn);\n    }\n\n    /// ----------------------------------------------------------------------------\n    /// Unwinding data\n    /// ----------------------------------------------------------------------------\n\n    /// @notice returns useful data about user unwinding position\n    function unwindingPosition(IInfiniFiGateway _gateway, address _owner, uint256 _startTimestamp)\n        internal\n        view\n        returns (uint256 receiptTokens, bool withdrawable)\n    {\n        UnwindingModule unwindingModule = UnwindingModule(_gateway.getAddress(\"unwindingModule\"));\n\n        bytes32 unwindingKey = keccak256(abi.encode(_owner, _startTimestamp));\n        receiptTokens = unwindingModule.balanceOf(_owner, _startTimestamp);\n\n        (,, uint32 toEpoch,,) = unwindingModule.positions(unwindingKey);\n        return (receiptTokens, EpochLib.epoch(block.timestamp) >= toEpoch);\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":"lib/LayerZero-v2/packages/layerzero-v2/evm/oapp/contracts/oft/interfaces/IOFT.sol","source_code":"// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.20;\n\nimport { MessagingReceipt, MessagingFee } from \"../../oapp/OAppSender.sol\";\n\n/**\n * @dev Struct representing token parameters for the OFT send() operation.\n */\nstruct SendParam {\n    uint32 dstEid; // Destination endpoint ID.\n    bytes32 to; // Recipient address.\n    uint256 amountLD; // Amount to send in local decimals.\n    uint256 minAmountLD; // Minimum amount to send in local decimals.\n    bytes extraOptions; // Additional options supplied by the caller to be used in the LayerZero message.\n    bytes composeMsg; // The composed message for the send() operation.\n    bytes oftCmd; // The OFT command to be executed, unused in default OFT implementations.\n}\n\n/**\n * @dev Struct representing OFT limit information.\n * @dev These amounts can change dynamically and are up the the specific oft implementation.\n */\nstruct OFTLimit {\n    uint256 minAmountLD; // Minimum amount in local decimals that can be sent to the recipient.\n    uint256 maxAmountLD; // Maximum amount in local decimals that can be sent to the recipient.\n}\n\n/**\n * @dev Struct representing OFT receipt information.\n */\nstruct OFTReceipt {\n    uint256 amountSentLD; // Amount of tokens ACTUALLY debited from the sender in local decimals.\n    // @dev In non-default implementations, the amountReceivedLD COULD differ from this value.\n    uint256 amountReceivedLD; // Amount of tokens to be received on the remote side.\n}\n\n/**\n * @dev Struct representing OFT fee details.\n * @dev Future proof mechanism to provide a standardized way to communicate fees to things like a UI.\n */\nstruct OFTFeeDetail {\n    int256 feeAmountLD; // Amount of the fee in local decimals.\n    string description; // Description of the fee.\n}\n\n/**\n * @title IOFT\n * @dev Interface for the OftChain (OFT) token.\n * @dev Does not inherit ERC20 to accommodate usage by OFTAdapter as well.\n * @dev This specific interface ID is '0x02e49c2c'.\n */\ninterface IOFT {\n    // Custom error messages\n    error InvalidLocalDecimals();\n    error SlippageExceeded(uint256 amountLD, uint256 minAmountLD);\n\n    // Events\n    event OFTSent(\n        bytes32 indexed guid, // GUID of the OFT message.\n        uint32 dstEid, // Destination Endpoint ID.\n        address indexed fromAddress, // Address of the sender on the src chain.\n        uint256 amountSentLD, // Amount of tokens sent in local decimals.\n        uint256 amountReceivedLD // Amount of tokens received in local decimals.\n    );\n    event OFTReceived(\n        bytes32 indexed guid, // GUID of the OFT message.\n        uint32 srcEid, // Source Endpoint ID.\n        address indexed toAddress, // Address of the recipient on the dst chain.\n        uint256 amountReceivedLD // Amount of tokens received in local decimals.\n    );\n\n    /**\n     * @notice Retrieves interfaceID and the version of the OFT.\n     * @return interfaceId The interface ID.\n     * @return version The version.\n     *\n     * @dev interfaceId: This specific interface ID is '0x02e49c2c'.\n     * @dev version: Indicates a cross-chain compatible msg encoding with other OFTs.\n     * @dev If a new feature is added to the OFT cross-chain msg encoding, the version will be incremented.\n     * ie. localOFT version(x,1) CAN send messages to remoteOFT version(x,1)\n     */\n    function oftVersion() external view returns (bytes4 interfaceId, uint64 version);\n\n    /**\n     * @notice Retrieves the address of the token associated with the OFT.\n     * @return token The address of the ERC20 token implementation.\n     */\n    function token() external view returns (address);\n\n    /**\n     * @notice Indicates whether the OFT contract requires approval of the 'token()' to send.\n     * @return requiresApproval Needs approval of the underlying token implementation.\n     *\n     * @dev Allows things like wallet implementers to determine integration requirements,\n     * without understanding the underlying token implementation.\n     */\n    function approvalRequired() external view returns (bool);\n\n    /**\n     * @notice Retrieves the shared decimals of the OFT.\n     * @return sharedDecimals The shared decimals of the OFT.\n     */\n    function sharedDecimals() external view returns (uint8);\n\n    /**\n     * @notice Provides a quote for OFT-related operations.\n     * @param _sendParam The parameters for the send operation.\n     * @return limit The OFT limit information.\n     * @return oftFeeDetails The details of OFT fees.\n     * @return receipt The OFT receipt information.\n     */\n    function quoteOFT(\n        SendParam calldata _sendParam\n    ) external view returns (OFTLimit memory, OFTFeeDetail[] memory oftFeeDetails, OFTReceipt memory);\n\n    /**\n     * @notice Provides a quote for the send() operation.\n     * @param _sendParam The parameters for the send() operation.\n     * @param _payInLzToken Flag indicating whether the caller is paying in the LZ token.\n     * @return fee The calculated LayerZero messaging fee from the send() operation.\n     *\n     * @dev MessagingFee: LayerZero msg fee\n     *  - nativeFee: The native fee.\n     *  - lzTokenFee: The lzToken fee.\n     */\n    function quoteSend(SendParam calldata _sendParam, bool _payInLzToken) external view returns (MessagingFee memory);\n\n    /**\n     * @notice Executes the send() operation.\n     * @param _sendParam The parameters for the send operation.\n     * @param _fee The fee information supplied by the caller.\n     *      - nativeFee: The native fee.\n     *      - lzTokenFee: The lzToken fee.\n     * @param _refundAddress The address to receive any excess funds from fees etc. on the src.\n     * @return receipt The LayerZero messaging receipt from the send() operation.\n     * @return oftReceipt The OFT receipt information.\n     *\n     * @dev MessagingReceipt: LayerZero msg receipt\n     *  - guid: The unique identifier for the sent message.\n     *  - nonce: The nonce of the sent message.\n     *  - fee: The LayerZero fee incurred for the message.\n     */\n    function send(\n        SendParam calldata _sendParam,\n        MessagingFee calldata _fee,\n        address _refundAddress\n    ) external payable returns (MessagingReceipt memory, OFTReceipt memory);\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":"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/governance/utils/IVotes.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.5.0) (governance/utils/IVotes.sol)\n\npragma solidity >=0.8.4;\n\n/**\n * @dev Common interface for {ERC20Votes}, {ERC721Votes}, and other {Votes}-enabled contracts.\n */\ninterface IVotes {\n    /**\n     * @dev The signature used has expired.\n     */\n    error VotesExpiredSignature(uint256 expiry);\n\n    /**\n     * @dev Emitted when an account changes their delegate.\n     */\n    event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);\n\n    /**\n     * @dev Emitted when a token transfer or delegate change results in changes to a delegate's number of voting units.\n     */\n    event DelegateVotesChanged(address indexed delegate, uint256 previousVotes, uint256 newVotes);\n\n    /**\n     * @dev Returns the current amount of votes that `account` has.\n     */\n    function getVotes(address account) external view returns (uint256);\n\n    /**\n     * @dev Returns the amount of votes that `account` had at a specific moment in the past. If the `clock()` is\n     * configured to use block numbers, this will return the value at the end of the corresponding block.\n     */\n    function getPastVotes(address account, uint256 timepoint) external view returns (uint256);\n\n    /**\n     * @dev Returns the total supply of votes available at a specific moment in the past. If the `clock()` is\n     * configured to use block numbers, this will return the value at the end of the corresponding block.\n     *\n     * NOTE: This value is the sum of all available votes, which is not necessarily the sum of all delegated votes.\n     * Votes that have not been delegated are still part of total supply, even though they would not participate in a\n     * vote.\n     */\n    function getPastTotalSupply(uint256 timepoint) external view returns (uint256);\n\n    /**\n     * @dev Returns the delegate that `account` has chosen.\n     */\n    function delegates(address account) external view returns (address);\n\n    /**\n     * @dev Delegates votes from the sender to `delegatee`.\n     */\n    function delegate(address delegatee) external;\n\n    /**\n     * @dev Delegates votes from signer to `delegatee`.\n     */\n    function delegateBySig(address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s) external;\n}\n"},{"file_path":"src/integrations/outland/portals/PortalHub.sol","source_code":"// SPDX-License-Identifier: MIT\npragma solidity 0.8.28;\n\nimport {ERC20} from \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\nimport {SafeERC20} from \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\nimport {EnumerableMap} from \"@openzeppelin/contracts/utils/structs/EnumerableMap.sol\";\n\nimport {CoreRoles} from \"@libraries/CoreRoles.sol\";\nimport {OutlandVault} from \"@integrations/outland/OutlandVault.sol\";\n\nimport {PortalBase} from \"@integrations/outland/portals/PortalBase.sol\";\nimport {OutlandMsgCodec} from \"@integrations/outland/OutlandMsgCodec.sol\";\nimport {IOutlandConnector} from \"@interfaces/IOutlandPortal.sol\";\n\n/// @title PortalHub\n/// @notice Main hub portal contract on Ethereum mainnet for managing cross-chain vault operations\n/// @dev Manages multiple OutlandVaults for different chains and handles cross-chain token transfers and asset updates\ncontract PortalHub is PortalBase {\n    using SafeERC20 for ERC20;\n    using EnumerableMap for EnumerableMap.UintToAddressMap;\n    using EnumerableMap for EnumerableMap.AddressToAddressMap;\n\n    event VaultSet(uint256 timestamp, uint256 chainId, address indexed vault);\n    event KeyValueSent(uint256 timestamp, uint256 chainId, uint256 nonce, bytes32 key, bytes32 value, address sender);\n    event AssetMappingSet(uint256 timestamp, uint256 chainId, address indexed hubAsset, address indexed outpostAsset);\n    event AssetsUpdateReceived(\n        uint256 indexed timestamp,\n        uint256 chainId,\n        uint256 totalAssets,\n        uint256 receiptTokenTotalSupply,\n        uint256 stakedTokenTotalSupply\n    );\n\n    /// @notice Maps chainId to vault address for each supported chain\n    EnumerableMap.UintToAddressMap vaults;\n\n    /// @notice Maps chainId to asset registry (hub asset => chain asset)\n    /// @dev Helpful when token addresses are not the same over multiple chains\n    mapping(uint256 chainId => EnumerableMap.AddressToAddressMap) assetMapping;\n\n    constructor() PortalBase(address(1), 1) {}\n\n    function init(address _core, uint256 _hubChainId) external {\n        require(address(core()) == address(0), AlreadyInitialized());\n        chainId = _hubChainId;\n        _setCore(_core);\n    }\n\n    /// ============================================================\n    /// Vault Management\n    /// ============================================================\n\n    function setVault(address _vault) external onlyCoreRole(CoreRoles.PROTOCOL_PARAMETERS) {\n        require(_vault != address(0), InvalidVault(_vault));\n        uint256 chainId = OutlandVault(_vault).chainId();\n        vaults.set(chainId, _vault);\n        emit VaultSet(block.timestamp, chainId, _vault);\n    }\n\n    /// @notice Returns the vault address for a given chain\n    /// @param _chainId The chain ID to query\n    /// @return The vault address for the specified chain\n    function getVault(uint256 _chainId) public view returns (address) {\n        return vaults.get(_chainId);\n    }\n\n    /// @notice Returns all chain IDs that have registered vaults\n    /// @return Array of chain IDs with registered vaults\n    function getVaultChainIds() external view returns (uint256[] memory) {\n        return vaults.keys();\n    }\n\n    /// ============================================================\n    /// Asset Registry Management\n    /// ============================================================\n\n    /// @notice Configures mapping of assets between this chain and other chains\n    /// @dev To be used in case when token addresses are different between chains\n    /// @dev Creates bidirectional mapping: hubAsset <-> outpostAsset\n    /// @param _chainId The chain ID for which to set the asset mapping\n    /// @param _hubAsset The asset token address on the hub (mainnet)\n    /// @param _outpostAsset The asset token address on the outpost\n    function setAssetMapping(uint256 _chainId, address _hubAsset, address _outpostAsset)\n        external\n        onlyCoreRole(CoreRoles.PROTOCOL_PARAMETERS)\n    {\n        assetMapping[_chainId].set(_hubAsset, _outpostAsset);\n        assetMapping[_chainId].set(_outpostAsset, _hubAsset);\n        emit AssetMappingSet(block.timestamp, _chainId, _hubAsset, _outpostAsset);\n    }\n\n    /// @notice Returns the mapped asset address for a given chain and asset\n    /// @param _chainId The chain ID to query\n    /// @param _asset The asset token address to look up\n    /// @return The corresponding asset address on the target chain\n    function getAssetMapping(uint256 _chainId, address _asset) external view returns (address) {\n        return assetMapping[_chainId].get(_asset);\n    }\n\n    /// ============================================================\n    /// Sender side\n    /// ============================================================\n\n    /// @notice Sends tokens from the hub to an outpost chain\n    /// @dev Withdraws tokens from vault, approves connector, and initiates cross-chain transfer\n    /// @dev Can only be called by OUTLAND_KEEPER role\n    /// @param _chainId The destination chain ID\n    /// @param _token The token address to send\n    /// @param _amount The amount of tokens to send\n    /// @param _connector The authorized connector address\n    function sendTokens(uint256 _chainId, address _token, uint256 _amount, address payable _connector)\n        external\n        payable\n        whenNotPaused\n        onlyCoreRole(CoreRoles.OUTLAND_KEEPER)\n    {\n        require(_amount > 0, InvalidAmount(_amount));\n        require(vaults.contains(_chainId), ChainNotSupported(_chainId));\n        require(assetMapping[_chainId].contains(_token), InvalidAsset(_token));\n        require(isConnector(_connector), InvalidSender(_connector));\n\n        TransferPayload memory payload = TransferPayload({\n            selector: OutlandMsgCodec.TRANSFER,\n            chainId: chainId,\n            nonce: _nextOutboundNonce(_chainId),\n            assetToken: assetMapping[_chainId].get(_token),\n            amount: _amount\n        });\n\n        address vault = vaults.get(_chainId);\n        OutlandVault(vault).portalWithdraw(_token, _amount);\n\n        ERC20(_token).forceApprove(_connector, _amount);\n        IOutlandConnector(_connector).sendTokens{value: msg.value}(_chainId, _token, _amount, abi.encode(payload));\n\n        emit TokensSent(block.timestamp, _chainId, payload.nonce, _token, _amount, _connector);\n    }\n\n    /// @notice Forwards arbitrary key-value pairs to an outpost chain\n    /// @dev Used to propagate mainnet rates and configuration to L2 consumers (e.g. OutlandGatewayL2)\n    /// @dev Can only be called by OUTLAND_KEYVALUE_SENDER role\n    /// @param _chainId Destination outpost chain ID\n    /// @param _key Key identifier\n    /// @param _value Value for the key\n    /// @param _connector Authorized connector address\n    function sendKeyValue(uint256 _chainId, bytes32 _key, bytes32 _value, address payable _connector)\n        external\n        payable\n        whenNotPaused\n        onlyCoreRole(CoreRoles.OUTLAND_KEYVALUE_SENDER)\n    {\n        require(vaults.contains(_chainId), ChainNotSupported(_chainId));\n        require(isConnector(_connector), InvalidSender(_connector));\n\n        KeyValuePayload memory payload = KeyValuePayload({\n            selector: OutlandMsgCodec.KEY_VALUE,\n            chainId: chainId,\n            nonce: _nextOutboundNonce(_chainId),\n            key: _key,\n            value: _value,\n            sentAt: block.timestamp\n        });\n\n        IOutlandConnector(_connector).sendMessage{value: msg.value}(_chainId, abi.encode(payload));\n\n        emit KeyValueSent(block.timestamp, _chainId, payload.nonce, _key, _value, _connector);\n    }\n\n    // call internal _handleSendTokenBridge with _pullFromSender = true\n    function _handleSendTokenBridge(\n        uint256 _targetChainId,\n        address _token,\n        uint256 _amount,\n        address _recipient,\n        address payable _connector\n    ) internal override {\n        _handleSendTokenBridge(_targetChainId, _token, _amount, _recipient, _connector, true);\n    }\n\n    /// @dev Bridging tokens L1 -> L2\n    /// @param _chainId The destination chain ID\n    /// @param _token The L1 iUSD or siUSD token address\n    /// @param _amount The amount of tokens to bridge\n    /// @param _recipient The recipient on the destination chain\n    /// @param _connector The connector to use to relay the message\n    /// @param _pullFromSender When false, tokens are assumed to already sit in the destination vault\n    function _handleSendTokenBridge(\n        uint256 _chainId,\n        address _token,\n        uint256 _amount,\n        address _recipient,\n        address _connector,\n        bool _pullFromSender\n    ) internal {\n        require(vaults.contains(_chainId), ChainNotSupported(_chainId));\n        OutlandVault vault = OutlandVault(vaults.get(_chainId));\n        require(_token == vault.stakedToken() || _token == vault.receiptToken(), InvalidBridgedToken(_token));\n        require(assetMapping[_chainId].contains(_token), InvalidAsset(_token));\n\n        if (_pullFromSender) {\n            ERC20(_token).safeTransferFrom(msg.sender, address(vault), _amount);\n        }\n\n        TokenBridgePayload memory payload = TokenBridgePayload({\n            selector: OutlandMsgCodec.TOKEN_BRIDGE,\n            chainId: chainId,\n            nonce: _nextOutboundNonce(_chainId),\n            token: assetMapping[_chainId].get(_token),\n            amount: _amount,\n            recipient: _recipient,\n            destinationChainId: _chainId,\n            totalAssetsValue: 0,\n            receiptTokenTotalSupply: 0,\n            stakedTokenTotalSupply: 0\n        });\n        IOutlandConnector(_connector).sendMessage{value: _pullFromSender ? msg.value : 0}(_chainId, abi.encode(payload));\n\n        emit BridgedTokensSent(block.timestamp, _chainId, payload.nonce, _token, _amount, _connector);\n    }\n\n    /// ============================================================\n    /// Receiver side\n    /// ============================================================\n\n    function _validateInboundEnvelope(uint256 _chainId, bytes calldata _data) internal view override {\n        super._validateInboundEnvelope(_chainId, _data);\n        require(vaults.contains(_chainId), ChainNotSupported(_chainId));\n    }\n\n    function _executeInboundMessage(uint256 _chainId, address _connector, bytes calldata _data) internal override {\n        bytes1 messageType = OutlandMsgCodec.getMessageType(_data);\n\n        if (messageType == OutlandMsgCodec.TRANSFER) {\n            _handleReceiveTokenTransfer(_chainId, _connector, _data);\n        } else if (messageType == OutlandMsgCodec.MESSAGE) {\n            _handleReceiveAssetsUpdate(_chainId, _data);\n        } else if (messageType == OutlandMsgCodec.TOKEN_BRIDGE) {\n            _handleReceiveTokenBridge(_chainId, _connector, _data);\n        }\n    }\n\n    /// @notice Internal handler for receiving token transfers from outpost chains\n    /// @dev Pulls assets from receiver, approves vault, and deposits to the vault\n    function _handleReceiveTokenTransfer(uint256 _chainId, address _connector, bytes calldata _data) internal {\n        require(isConnector(_connector), InvalidReceiver(_connector));\n        (address senderToken, uint256 amount) = OutlandMsgCodec.getTransferPayload(_data);\n        address token = assetMapping[_chainId].get(senderToken);\n        require(token != address(0), InvalidAsset(senderToken));\n\n        OutlandVault vault = OutlandVault(vaults.get(_chainId));\n        IOutlandConnector(_connector).pullAssets(token, amount);\n\n        ERC20(token).forceApprove(address(vault), amount);\n        vault.portalDeposit(token, amount);\n        emit TokensReceived(block.timestamp, _chainId, token, amount, _connector);\n    }\n\n    /// @notice Internal handler for receiving asset updates from outpost chains\n    /// @dev Updates the vault with the latest total assets from the outpost chain\n    function _handleReceiveAssetsUpdate(uint256 _chainId, bytes calldata _data) internal {\n        (uint256 totalAssetsValue, uint256 receiptTokenTotalSupply, uint256 stakedTokenTotalSupply) =\n            OutlandMsgCodec.getAssetsUpdatePayload(_data);\n\n        OutlandVault(vaults.get(_chainId))\n            .portalUpdate(totalAssetsValue, receiptTokenTotalSupply, stakedTokenTotalSupply);\n        emit AssetsUpdateReceived(\n            block.timestamp, _chainId, totalAssetsValue, receiptTokenTotalSupply, stakedTokenTotalSupply\n        );\n    }\n\n    /// @notice Internal handler for receiving bridged iUSD / siUSD from an outpost chain\n    /// if destinationChainId == chainId, this is a L2 -> L1 bridging\n    /// else, this is a L2 -> L2 bridging and the message needs to be relayed to another outpost\n    /// @dev L2 -> L1: withdraws tokens from the source vault to the recipient\n    /// @dev L2 -> L2: moves tokens to the destination vault and relays a mint message to the target outpost\n    function _handleReceiveTokenBridge(uint256 _sourceChainId, address _connector, bytes calldata _data) internal {\n        require(isConnector(_connector), InvalidReceiver(_connector));\n\n        address token;\n        uint256 amount;\n        address recipient;\n        uint256 destinationChainId;\n        {\n            address senderToken;\n            uint256 totalAssetsValue;\n            uint256 receiptTokenTotalSupply;\n            uint256 stakedTokenTotalSupply;\n            (\n                senderToken,\n                amount,\n                recipient,\n                destinationChainId,\n                totalAssetsValue,\n                receiptTokenTotalSupply,\n                stakedTokenTotalSupply\n            ) = OutlandMsgCodec.getTokenBridgePayload(_data);\n            token = assetMapping[_sourceChainId].get(senderToken);\n            require(token != address(0), InvalidAsset(senderToken));\n\n            // Outpost-originated bridge messages carry pre-burn L2 supplies; portalUpdate runs before release.\n            OutlandVault(vaults.get(_sourceChainId))\n                .portalUpdate(totalAssetsValue, receiptTokenTotalSupply, stakedTokenTotalSupply);\n        }\n\n        // L2 -> L1 bridging\n        if (destinationChainId == chainId) {\n            // simply release the tokens from the source vault to the recipient\n            OutlandVault(vaults.get(_sourceChainId)).portalBridgeWithdraw(token, amount, recipient);\n        }\n        // L2 -> L2 bridging\n        else {\n            // we shall release the tokens from the source vault to the destination vault\n            if (!vaults.contains(destinationChainId)) {\n                // if the destination vault does not exist, do not move the tokens, and\n                // send a message back to the source outpost so the user gets their tokens back.\n                _handleSendTokenBridge(_sourceChainId, token, amount, recipient, _connector, false);\n            } else {\n                // if the destination vault exists, release the tokens from source to destination vault\n                // and send a message to the destination outpost to mint the tokens to the recipient\n                address destinationVault = vaults.get(destinationChainId);\n                OutlandVault(vaults.get(_sourceChainId)).portalBridgeWithdraw(token, amount, destinationVault);\n                _handleSendTokenBridge(destinationChainId, token, amount, recipient, _connector, false);\n            }\n        }\n\n        emit BridgedTokensReceived(block.timestamp, _sourceChainId, token, amount, recipient);\n    }\n}\n"},{"file_path":"lib/LayerZero-v2/packages/layerzero-v2/evm/protocol/contracts/interfaces/IMessageLibManager.sol","source_code":"// SPDX-License-Identifier: MIT\n\npragma solidity >=0.8.0;\n\nstruct SetConfigParam {\n    uint32 eid;\n    uint32 configType;\n    bytes config;\n}\n\ninterface IMessageLibManager {\n    struct Timeout {\n        address lib;\n        uint256 expiry;\n    }\n\n    event LibraryRegistered(address newLib);\n    event DefaultSendLibrarySet(uint32 eid, address newLib);\n    event DefaultReceiveLibrarySet(uint32 eid, address newLib);\n    event DefaultReceiveLibraryTimeoutSet(uint32 eid, address oldLib, uint256 expiry);\n    event SendLibrarySet(address sender, uint32 eid, address newLib);\n    event ReceiveLibrarySet(address receiver, uint32 eid, address newLib);\n    event ReceiveLibraryTimeoutSet(address receiver, uint32 eid, address oldLib, uint256 timeout);\n\n    function registerLibrary(address _lib) external;\n\n    function isRegisteredLibrary(address _lib) external view returns (bool);\n\n    function getRegisteredLibraries() external view returns (address[] memory);\n\n    function setDefaultSendLibrary(uint32 _eid, address _newLib) external;\n\n    function defaultSendLibrary(uint32 _eid) external view returns (address);\n\n    function setDefaultReceiveLibrary(uint32 _eid, address _newLib, uint256 _timeout) external;\n\n    function defaultReceiveLibrary(uint32 _eid) external view returns (address);\n\n    function setDefaultReceiveLibraryTimeout(uint32 _eid, address _lib, uint256 _expiry) external;\n\n    function defaultReceiveLibraryTimeout(uint32 _eid) external view returns (address lib, uint256 expiry);\n\n    function isSupportedEid(uint32 _eid) external view returns (bool);\n\n    function isValidReceiveLibrary(address _receiver, uint32 _eid, address _lib) external view returns (bool);\n\n    /// ------------------- OApp interfaces -------------------\n    function setSendLibrary(address _oapp, uint32 _eid, address _newLib) external;\n\n    function getSendLibrary(address _sender, uint32 _eid) external view returns (address lib);\n\n    function isDefaultSendLibrary(address _sender, uint32 _eid) external view returns (bool);\n\n    function setReceiveLibrary(address _oapp, uint32 _eid, address _newLib, uint256 _gracePeriod) external;\n\n    function getReceiveLibrary(address _receiver, uint32 _eid) external view returns (address lib, bool isDefault);\n\n    function setReceiveLibraryTimeout(address _oapp, uint32 _eid, address _lib, uint256 _gracePeriod) external;\n\n    function receiveLibraryTimeout(address _receiver, uint32 _eid) external view returns (address lib, uint256 expiry);\n\n    function setConfig(address _oapp, address _lib, SetConfigParam[] calldata _params) external;\n\n    function getConfig(\n        address _oapp,\n        address _lib,\n        uint32 _eid,\n        uint32 _configType\n    ) external view returns (bytes memory config);\n}\n"},{"file_path":"lib/LayerZero-v2/packages/layerzero-v2/evm/oapp/contracts/oapp/interfaces/IOAppMsgInspector.sol","source_code":"// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.20;\n\n/**\n * @title IOAppMsgInspector\n * @dev Interface for the OApp Message Inspector, allowing examination of message and options contents.\n */\ninterface IOAppMsgInspector {\n    // Custom error message for inspection failure\n    error InspectionFailed(bytes message, bytes options);\n\n    /**\n     * @notice Allows the inspector to examine LayerZero message contents and optionally throw a revert if invalid.\n     * @param _message The message payload to be inspected.\n     * @param _options Additional options or parameters for inspection.\n     * @return valid A boolean indicating whether the inspection passed (true) or failed (false).\n     *\n     * @dev Optionally done as a revert, OR use the boolean provided to handle the failure.\n     */\n    function inspect(bytes calldata _message, bytes calldata _options) external view returns (bool valid);\n}\n"},{"file_path":"src/interfaces/IMaturityFarm.sol","source_code":"// SPDX-License-Identifier: MIT\npragma solidity 0.8.28;\n\nimport {IFarm} from \"@interfaces/IFarm.sol\";\n\n/// @notice Interface for an InfiniFi Farm contract that has a maturity date\n/// @dev These farms represent illiquid farm/asset class\ninterface IMaturityFarm is IFarm {\n    /// @notice timestamp at which more funds can be made available for withdrawal\n    function maturity() external view returns (uint256);\n}\n"},{"file_path":"lib/LayerZero-v2/packages/layerzero-v2/evm/protocol/contracts/messagelib/libs/PacketV1Codec.sol","source_code":"// SPDX-License-Identifier: LZBL-1.2\n\npragma solidity ^0.8.20;\n\nimport { Packet } from \"../../interfaces/ISendLib.sol\";\nimport { AddressCast } from \"../../libs/AddressCast.sol\";\n\nlibrary PacketV1Codec {\n    using AddressCast for address;\n    using AddressCast for bytes32;\n\n    uint8 internal constant PACKET_VERSION = 1;\n\n    // header (version + nonce + path)\n    // version\n    uint256 private constant PACKET_VERSION_OFFSET = 0;\n    //    nonce\n    uint256 private constant NONCE_OFFSET = 1;\n    //    path\n    uint256 private constant SRC_EID_OFFSET = 9;\n    uint256 private constant SENDER_OFFSET = 13;\n    uint256 private constant DST_EID_OFFSET = 45;\n    uint256 private constant RECEIVER_OFFSET = 49;\n    // payload (guid + message)\n    uint256 private constant GUID_OFFSET = 81; // keccak256(nonce + path)\n    uint256 private constant MESSAGE_OFFSET = 113;\n\n    function encode(Packet memory _packet) internal pure returns (bytes memory encodedPacket) {\n        encodedPacket = abi.encodePacked(\n            PACKET_VERSION,\n            _packet.nonce,\n            _packet.srcEid,\n            _packet.sender.toBytes32(),\n            _packet.dstEid,\n            _packet.receiver,\n            _packet.guid,\n            _packet.message\n        );\n    }\n\n    function encodePacketHeader(Packet memory _packet) internal pure returns (bytes memory) {\n        return\n            abi.encodePacked(\n                PACKET_VERSION,\n                _packet.nonce,\n                _packet.srcEid,\n                _packet.sender.toBytes32(),\n                _packet.dstEid,\n                _packet.receiver\n            );\n    }\n\n    function encodePayload(Packet memory _packet) internal pure returns (bytes memory) {\n        return abi.encodePacked(_packet.guid, _packet.message);\n    }\n\n    function header(bytes calldata _packet) internal pure returns (bytes calldata) {\n        return _packet[0:GUID_OFFSET];\n    }\n\n    function version(bytes calldata _packet) internal pure returns (uint8) {\n        return uint8(bytes1(_packet[PACKET_VERSION_OFFSET:NONCE_OFFSET]));\n    }\n\n    function nonce(bytes calldata _packet) internal pure returns (uint64) {\n        return uint64(bytes8(_packet[NONCE_OFFSET:SRC_EID_OFFSET]));\n    }\n\n    function srcEid(bytes calldata _packet) internal pure returns (uint32) {\n        return uint32(bytes4(_packet[SRC_EID_OFFSET:SENDER_OFFSET]));\n    }\n\n    function sender(bytes calldata _packet) internal pure returns (bytes32) {\n        return bytes32(_packet[SENDER_OFFSET:DST_EID_OFFSET]);\n    }\n\n    function senderAddressB20(bytes calldata _packet) internal pure returns (address) {\n        return sender(_packet).toAddress();\n    }\n\n    function dstEid(bytes calldata _packet) internal pure returns (uint32) {\n        return uint32(bytes4(_packet[DST_EID_OFFSET:RECEIVER_OFFSET]));\n    }\n\n    function receiver(bytes calldata _packet) internal pure returns (bytes32) {\n        return bytes32(_packet[RECEIVER_OFFSET:GUID_OFFSET]);\n    }\n\n    function receiverB20(bytes calldata _packet) internal pure returns (address) {\n        return receiver(_packet).toAddress();\n    }\n\n    function guid(bytes calldata _packet) internal pure returns (bytes32) {\n        return bytes32(_packet[GUID_OFFSET:MESSAGE_OFFSET]);\n    }\n\n    function message(bytes calldata _packet) internal pure returns (bytes calldata) {\n        return bytes(_packet[MESSAGE_OFFSET:]);\n    }\n\n    function payload(bytes calldata _packet) internal pure returns (bytes calldata) {\n        return bytes(_packet[GUID_OFFSET:]);\n    }\n\n    function payloadHash(bytes calldata _packet) internal pure returns (bytes32) {\n        return keccak256(payload(_packet));\n    }\n}\n"},{"file_path":"src/gateway/InfiniFiGatewayV2.sol","source_code":"// SPDX-License-Identifier: MIT\npragma solidity 0.8.28;\n\nimport {FixedPointMathLib} from \"@solmate/src/utils/FixedPointMathLib.sol\";\n\nimport {ERC20} from \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\nimport {SafeERC20} from \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\nimport {ReentrancyGuardTransient} from \"@openzeppelin/contracts/utils/ReentrancyGuardTransient.sol\";\n\nimport {CoreRoles} from \"@libraries/CoreRoles.sol\";\nimport {StakedToken} from \"@tokens/StakedToken.sol\";\nimport {ReceiptToken} from \"@tokens/ReceiptToken.sol\";\nimport {CoreControlled} from \"@core/CoreControlled.sol\";\nimport {MintController} from \"@funding/MintController.sol\";\nimport {YieldSharingV2} from \"@finance/YieldSharingV2.sol\";\nimport {RedeemController} from \"@funding/RedeemController.sol\";\nimport {AllocationVoting} from \"@governance/AllocationVoting.sol\";\nimport {LockingController} from \"@locking/LockingController.sol\";\nimport {LockedPositionToken} from \"@tokens/LockedPositionToken.sol\";\n\n/// @notice Gateway to interact with the InfiniFi protocol\ncontract InfiniFiGatewayV2 is CoreControlled, ReentrancyGuardTransient {\n    using SafeERC20 for ERC20;\n    using FixedPointMathLib 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 error thrown when a swap fails\n    error SwapFailed();\n    error InvalidZapFee();\n    error InvalidZapRouter();\n    error MinAssetsOutError(uint256 min, uint256 actual);\n\n    event AddressSet(uint256 timestamp, string indexed name, address _address);\n    event ZapFeeSet(uint256 timestamp, uint256 zapFee);\n    event ZapIn(uint256 timestamp, address indexed user, address indexed token, uint256 amount, uint256 receiptTokens);\n    event SetEnabledRouter(uint256 timestamp, address router, bool enabled);\n\n    /// @notice address registry of the gateway\n    mapping(bytes32 => address) public addresses;\n\n    /// @notice Mapping of routers that can be used to zap\n    mapping(address => bool) public enabledRouters;\n\n    /// @notice fee charged for zaps, as a percentage with 18 decimals\n    uint256 public zapFee;\n\n    constructor() CoreControlled(address(1)) {}\n\n    /// @notice initializer for the proxy storage\n    function init(address _core) external {\n        assert(address(core()) == address(0));\n        _setCore(_core);\n    }\n\n    /// -------------------------------------------------------------------------------------\n    /// Configuration\n    /// -------------------------------------------------------------------------------------\n\n    /// @notice set an address for a given name\n    function setAddress(string memory _name, address _address) external onlyCoreRole(CoreRoles.GOVERNOR) {\n        addresses[keccak256(abi.encode(_name))] = _address;\n        emit AddressSet(block.timestamp, _name, _address);\n    }\n\n    /// @notice get an address for a given name\n    function getAddress(string memory _name) public view returns (address) {\n        return addresses[keccak256(abi.encode(_name))];\n    }\n\n    /// @notice manage the whitelist of routers to be used by the zap functions\n    function setEnabledRouter(address _router, bool _enabled) external onlyCoreRole(CoreRoles.PROTOCOL_PARAMETERS) {\n        enabledRouters[_router] = _enabled;\n        emit SetEnabledRouter(block.timestamp, _router, _enabled);\n    }\n\n    /// @notice set the fee charged for zaps\n    function setZapFee(uint256 _zapFee) external onlyCoreRole(CoreRoles.PROTOCOL_PARAMETERS) {\n        require(_zapFee <= 0.01e18, InvalidZapFee()); // cannot set to more than 1%\n        zapFee = _zapFee;\n        emit ZapFeeSet(block.timestamp, _zapFee);\n    }\n\n    /// -------------------------------------------------------------------------------------\n    /// User interactions\n    /// -------------------------------------------------------------------------------------\n\n    function mint(address _to, uint256 _amount) external whenNotPaused nonReentrant returns (uint256) {\n        ERC20 usdc = ERC20(getAddress(\"USDC\"));\n        MintController mintController = MintController(getAddress(\"mintController\"));\n\n        usdc.safeTransferFrom(msg.sender, address(this), _amount);\n        usdc.approve(address(mintController), _amount);\n        return mintController.mint(_to, _amount);\n    }\n\n    function mintAndStake(address _to, uint256 _amount) external whenNotPaused nonReentrant returns (uint256) {\n        MintController mintController = MintController(getAddress(\"mintController\"));\n        StakedToken siusd = StakedToken(getAddress(\"stakedToken\"));\n        ReceiptToken iusd = ReceiptToken(getAddress(\"receiptToken\"));\n        ERC20 usdc = ERC20(getAddress(\"USDC\"));\n        YieldSharingV2 yieldSharing = YieldSharingV2(getAddress(\"yieldSharing\"));\n\n        usdc.safeTransferFrom(msg.sender, address(this), _amount);\n        usdc.approve(address(mintController), _amount);\n        uint256 receiptTokens = mintController.mint(address(this), _amount);\n\n        yieldSharing.distributeInterpolationRewards();\n        yieldSharing.setCanEnterOrExitStakedToken(true);\n        iusd.approve(address(siusd), receiptTokens);\n        siusd.deposit(receiptTokens, _to);\n        yieldSharing.setCanEnterOrExitStakedToken(false);\n\n        return receiptTokens;\n    }\n\n    function stake(address _to, uint256 _receiptTokens) external whenNotPaused nonReentrant returns (uint256) {\n        StakedToken siusd = StakedToken(getAddress(\"stakedToken\"));\n        ReceiptToken iusd = ReceiptToken(getAddress(\"receiptToken\"));\n        YieldSharingV2 yieldSharing = YieldSharingV2(getAddress(\"yieldSharing\"));\n\n        // forge-lint: disable-next-line(erc20-unchecked-transfer)\n        iusd.transferFrom(msg.sender, address(this), _receiptTokens);\n        iusd.approve(address(siusd), _receiptTokens);\n        yieldSharing.distributeInterpolationRewards();\n        yieldSharing.setCanEnterOrExitStakedToken(true);\n        uint256 stakedTokens = siusd.deposit(_receiptTokens, _to);\n        yieldSharing.setCanEnterOrExitStakedToken(false);\n\n        return stakedTokens;\n    }\n\n    function unstake(address _to, uint256 _stakedTokens) external whenNotPaused nonReentrant returns (uint256) {\n        StakedToken siusd = StakedToken(getAddress(\"stakedToken\"));\n        YieldSharingV2 yieldSharing = YieldSharingV2(getAddress(\"yieldSharing\"));\n\n        // forge-lint: disable-next-line(erc20-unchecked-transfer)\n        siusd.transferFrom(msg.sender, address(this), _stakedTokens);\n        yieldSharing.distributeInterpolationRewards();\n        yieldSharing.setCanEnterOrExitStakedToken(true);\n        uint256 receiptTokens = siusd.redeem(_stakedTokens, _to, address(this));\n        yieldSharing.setCanEnterOrExitStakedToken(false);\n\n        return receiptTokens;\n    }\n\n    function _zapToReceiptTokens(address _token, uint256 _amount, address _router, bytes calldata _routerData)\n        internal\n        returns (uint256, ReceiptToken)\n    {\n        require(enabledRouters[_router], InvalidZapRouter());\n\n        // pull in the tokens and approve the router if not using native ETH\n        if (_token != address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)) {\n            ERC20(_token).safeTransferFrom(msg.sender, address(this), _amount);\n            ERC20(_token).forceApprove(address(_router), _amount);\n        }\n\n        // perform swap to USDC\n        (bool swapSuccess,) = _router.call{value: msg.value}(_routerData);\n        require(swapSuccess, SwapFailed());\n\n        // read the protocol addresses from storage\n        MintController mintController = MintController(getAddress(\"mintController\"));\n        ERC20 usdc = ERC20(getAddress(\"USDC\"));\n        ReceiptToken iusd = ReceiptToken(getAddress(\"receiptToken\"));\n\n        // mint iUSD\n        uint256 usdcReceived = usdc.balanceOf(address(this));\n        usdc.approve(address(mintController), usdcReceived);\n        uint256 receiptTokens = mintController.mint(address(this), usdcReceived);\n\n        {\n            uint256 _zapFee = zapFee;\n            if (_zapFee != 0) {\n                uint256 fee = receiptTokens.mulWadDown(_zapFee);\n                receiptTokens -= fee;\n                // forge-lint: disable-next-line(erc20-unchecked-transfer)\n                iusd.transfer(getAddress(\"yieldSharing\"), fee);\n            }\n        }\n\n        emit ZapIn(block.timestamp, msg.sender, _token, _amount, receiptTokens);\n\n        return (receiptTokens, iusd);\n    }\n\n    function zapIn(address _token, uint256 _amount, address _router, bytes calldata _routerData, address _to)\n        external\n        payable\n        whenNotPaused\n        nonReentrant\n        returns (uint256)\n    {\n        (uint256 receiptTokens, ReceiptToken iusd) = _zapToReceiptTokens(_token, _amount, _router, _routerData);\n\n        // send iUSD to receiver\n        // forge-lint: disable-next-line(erc20-unchecked-transfer)\n        iusd.transfer(_to, receiptTokens);\n        return receiptTokens;\n    }\n\n    function zapInAndStake(address _token, uint256 _amount, address _router, bytes calldata _routerData, address _to)\n        external\n        payable\n        whenNotPaused\n        nonReentrant\n        returns (uint256)\n    {\n        (uint256 receiptTokens, ReceiptToken iusd) = _zapToReceiptTokens(_token, _amount, _router, _routerData);\n\n        // read the protocol addresses from storage\n        StakedToken siusd = StakedToken(getAddress(\"stakedToken\"));\n        YieldSharingV2 yieldSharing = YieldSharingV2(getAddress(\"yieldSharing\"));\n\n        // mint iUSD and stake it to siUSD\n        yieldSharing.distributeInterpolationRewards();\n        yieldSharing.setCanEnterOrExitStakedToken(true);\n        iusd.approve(address(siusd), receiptTokens);\n        siusd.deposit(receiptTokens, _to);\n        yieldSharing.setCanEnterOrExitStakedToken(false);\n        return receiptTokens;\n    }\n\n    function zapInAndLock(\n        address _token,\n        uint256 _amount,\n        address _router,\n        bytes calldata _routerData,\n        uint32 _unwindingEpochs,\n        address _to\n    ) external payable whenNotPaused nonReentrant returns (uint256) {\n        (uint256 receiptTokens, ReceiptToken iusd) = _zapToReceiptTokens(_token, _amount, _router, _routerData);\n\n        // read the protocol addresses from storage\n        LockingController lockingController = LockingController(getAddress(\"lockingController\"));\n\n        // lock the iUSD\n        iusd.approve(address(lockingController), receiptTokens);\n        lockingController.createPosition(receiptTokens, _unwindingEpochs, _to);\n        return receiptTokens;\n    }\n\n    function mintAndLock(address _to, uint256 _amount, uint32 _unwindingEpochs)\n        external\n        whenNotPaused\n        nonReentrant\n        returns (uint256)\n    {\n        MintController mintController = MintController(getAddress(\"mintController\"));\n        ReceiptToken iusd = ReceiptToken(getAddress(\"receiptToken\"));\n        LockingController lockingController = LockingController(getAddress(\"lockingController\"));\n        ERC20 usdc = ERC20(getAddress(\"USDC\"));\n\n        usdc.safeTransferFrom(msg.sender, address(this), _amount);\n        usdc.approve(address(mintController), _amount);\n        uint256 receiptTokens = mintController.mint(address(this), _amount);\n\n        iusd.approve(address(lockingController), receiptTokens);\n        lockingController.createPosition(receiptTokens, _unwindingEpochs, _to);\n        return receiptTokens;\n    }\n\n    function unstakeAndLock(address _to, uint256 _amount, uint32 _unwindingEpochs)\n        external\n        whenNotPaused\n        nonReentrant\n        returns (uint256)\n    {\n        ReceiptToken iusd = ReceiptToken(getAddress(\"receiptToken\"));\n        StakedToken siusd = StakedToken(getAddress(\"stakedToken\"));\n        LockingController lockingController = LockingController(getAddress(\"lockingController\"));\n        YieldSharingV2 yieldSharing = YieldSharingV2(getAddress(\"yieldSharing\"));\n\n        // forge-lint: disable-next-line(erc20-unchecked-transfer)\n        siusd.transferFrom(msg.sender, address(this), _amount);\n        yieldSharing.distributeInterpolationRewards();\n        yieldSharing.setCanEnterOrExitStakedToken(true);\n        uint256 receiptTokens = siusd.redeem(_amount, address(this), address(this));\n        yieldSharing.setCanEnterOrExitStakedToken(false);\n\n        iusd.approve(address(lockingController), receiptTokens);\n        lockingController.createPosition(receiptTokens, _unwindingEpochs, _to);\n        return receiptTokens;\n    }\n\n    function createPosition(uint256 _amount, uint32 _unwindingEpochs, address _recipient)\n        external\n        whenNotPaused\n        nonReentrant\n    {\n        ReceiptToken iusd = ReceiptToken(getAddress(\"receiptToken\"));\n        LockingController lockingController = LockingController(getAddress(\"lockingController\"));\n\n        // forge-lint: disable-next-line(erc20-unchecked-transfer)\n        iusd.transferFrom(msg.sender, address(this), _amount);\n        iusd.approve(address(lockingController), _amount);\n        lockingController.createPosition(_amount, _unwindingEpochs, _recipient);\n    }\n\n    function startUnwinding(uint256 _shares, uint32 _unwindingEpochs) external whenNotPaused nonReentrant {\n        LockingController lockingController = LockingController(getAddress(\"lockingController\"));\n        LockedPositionToken liusd = LockedPositionToken(lockingController.shareToken(_unwindingEpochs));\n\n        // forge-lint: disable-next-line(erc20-unchecked-transfer)\n        liusd.transferFrom(msg.sender, address(this), _shares);\n        liusd.approve(address(lockingController), _shares);\n        lockingController.startUnwinding(_shares, _unwindingEpochs, msg.sender);\n    }\n\n    function increaseUnwindingEpochs(uint32 _oldUnwindingEpochs, uint32 _newUnwindingEpochs, uint256 _shares)\n        external\n        whenNotPaused\n        nonReentrant\n    {\n        LockingController lockingController = LockingController(getAddress(\"lockingController\"));\n        LockedPositionToken liusd = LockedPositionToken(lockingController.shareToken(_oldUnwindingEpochs));\n\n        // forge-lint: disable-next-line(erc20-unchecked-transfer)\n        liusd.transferFrom(msg.sender, address(this), _shares);\n        liusd.approve(address(lockingController), _shares);\n        lockingController.increaseUnwindingEpochs(_shares, _oldUnwindingEpochs, _newUnwindingEpochs, msg.sender);\n    }\n\n    function cancelUnwinding(uint256 _unwindingTimestamp, uint32 _newUnwindingEpochs)\n        external\n        whenNotPaused\n        nonReentrant\n    {\n        LockingController(getAddress(\"lockingController\"))\n            .cancelUnwinding(msg.sender, _unwindingTimestamp, _newUnwindingEpochs);\n    }\n\n    function withdraw(uint256 _unwindingTimestamp) external whenNotPaused nonReentrant {\n        _revertIfThereAreUnaccruedLosses();\n        LockingController(getAddress(\"lockingController\")).withdraw(msg.sender, _unwindingTimestamp);\n    }\n\n    function withdraw(address _user, uint256 _unwindingTimestamp) external whenNotPaused nonReentrant {\n        _revertIfThereAreUnaccruedLosses();\n        LockingController(getAddress(\"lockingController\")).withdraw(_user, _unwindingTimestamp);\n    }\n\n    function redeem(address _to, uint256 _amount, uint256 _minAssetsOut)\n        external\n        whenNotPaused\n        nonReentrant\n        returns (uint256)\n    {\n        _revertIfThereAreUnaccruedLosses();\n        ReceiptToken iusd = ReceiptToken(getAddress(\"receiptToken\"));\n        RedeemController redeemController = RedeemController(getAddress(\"redeemController\"));\n\n        // forge-lint: disable-next-line(erc20-unchecked-transfer)\n        iusd.transferFrom(msg.sender, address(this), _amount);\n        iusd.approve(address(redeemController), _amount);\n        uint256 assetsOut = redeemController.redeem(_to, _amount);\n        require(assetsOut >= _minAssetsOut, MinAssetsOutError(_minAssetsOut, assetsOut));\n        return assetsOut;\n    }\n\n    function claimRedemption() external whenNotPaused nonReentrant {\n        RedeemController(getAddress(\"redeemController\")).claimRedemption(msg.sender);\n    }\n\n    function vote(\n        address _asset,\n        uint32 _unwindingEpochs,\n        AllocationVoting.AllocationVote[] calldata _liquidVotes,\n        AllocationVoting.AllocationVote[] calldata _illiquidVotes\n    ) external whenNotPaused nonReentrant {\n        AllocationVoting(getAddress(\"allocationVoting\"))\n            .vote(msg.sender, _asset, _unwindingEpochs, _liquidVotes, _illiquidVotes);\n    }\n\n    function multiVote(\n        address[] calldata _assets,\n        uint32[] calldata _unwindingEpochs,\n        AllocationVoting.AllocationVote[][] calldata _liquidVotes,\n        AllocationVoting.AllocationVote[][] calldata _illiquidVotes\n    ) external whenNotPaused nonReentrant {\n        AllocationVoting allocationVoting = AllocationVoting(getAddress(\"allocationVoting\"));\n\n        for (uint256 i = 0; i < _assets.length; i++) {\n            allocationVoting.vote(msg.sender, _assets[i], _unwindingEpochs[i], _liquidVotes[i], _illiquidVotes[i]);\n        }\n    }\n\n    function _revertIfThereAreUnaccruedLosses() internal view {\n        YieldSharingV2 yieldSharing = YieldSharingV2(getAddress(\"yieldSharing\"));\n        require(yieldSharing.unaccruedYield() >= 0, PendingLossesUnapplied());\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":"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    /// @notice can initialize bridging transactions\n    bytes32 internal constant BRIDGE_INITIATOR = keccak256(\"BRIDGE_INITIATOR\");\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    /// @notice can forward key-value updates from PortalHub to outposts\n    bytes32 internal constant OUTLAND_KEYVALUE_SENDER = keccak256(\"OUTLAND_KEYVALUE_SENDER\");\n\n    /// @notice can manage OutlandGateway user allowlists\n    bytes32 internal constant WHITELIST_MANAGER = keccak256(\"WHITELIST_MANAGER\");\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":"lib/LayerZero-v2/packages/layerzero-v2/evm/protocol/contracts/interfaces/ILayerZeroReceiver.sol","source_code":"// SPDX-License-Identifier: MIT\n\npragma solidity >=0.8.0;\n\nimport { Origin } from \"./ILayerZeroEndpointV2.sol\";\n\ninterface ILayerZeroReceiver {\n    function allowInitializePath(Origin calldata _origin) external view returns (bool);\n\n    function nextNonce(uint32 _eid, bytes32 _sender) external view returns (uint64);\n\n    function lzReceive(\n        Origin calldata _origin,\n        bytes32 _guid,\n        bytes calldata _message,\n        address _executor,\n        bytes calldata _extraData\n    ) external payable;\n}\n"},{"file_path":"lib/LayerZero-v2/packages/layerzero-v2/evm/oapp/contracts/precrime/interfaces/IPreCrime.sol","source_code":"// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.20;\nstruct PreCrimePeer {\n    uint32 eid;\n    bytes32 preCrime;\n    bytes32 oApp;\n}\n\n// TODO not done yet\ninterface IPreCrime {\n    error OnlyOffChain();\n\n    // for simulate()\n    error PacketOversize(uint256 max, uint256 actual);\n    error PacketUnsorted();\n    error SimulationFailed(bytes reason);\n\n    // for preCrime()\n    error SimulationResultNotFound(uint32 eid);\n    error InvalidSimulationResult(uint32 eid, bytes reason);\n    error CrimeFound(bytes crime);\n\n    function getConfig(bytes[] calldata _packets, uint256[] calldata _packetMsgValues) external returns (bytes memory);\n\n    function simulate(\n        bytes[] calldata _packets,\n        uint256[] calldata _packetMsgValues\n    ) external payable returns (bytes memory);\n\n    function buildSimulationResult() external view returns (bytes memory);\n\n    function preCrime(\n        bytes[] calldata _packets,\n        uint256[] calldata _packetMsgValues,\n        bytes[] calldata _simulations\n    ) external;\n\n    function version() external view returns (uint64 major, uint8 minor);\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/governance/utils/Votes.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.5.0) (governance/utils/Votes.sol)\n\npragma solidity ^0.8.24;\n\nimport {IERC5805} from \"../../interfaces/IERC5805.sol\";\nimport {Context} from \"../../utils/Context.sol\";\nimport {Nonces} from \"../../utils/Nonces.sol\";\nimport {EIP712} from \"../../utils/cryptography/EIP712.sol\";\nimport {Checkpoints} from \"../../utils/structs/Checkpoints.sol\";\nimport {SafeCast} from \"../../utils/math/SafeCast.sol\";\nimport {ECDSA} from \"../../utils/cryptography/ECDSA.sol\";\nimport {Time} from \"../../utils/types/Time.sol\";\n\n/**\n * @dev This is a base abstract contract that tracks voting units, which are a measure of voting power that can be\n * transferred, and provides a system of vote delegation, where an account can delegate its voting units to a sort of\n * \"representative\" that will pool delegated voting units from different accounts and can then use it to vote in\n * decisions. In fact, voting units _must_ be delegated in order to count as actual votes, and an account has to\n * delegate those votes to itself if it wishes to participate in decisions and does not have a trusted representative.\n *\n * This contract is often combined with a token contract such that voting units correspond to token units. For an\n * example, see {ERC721Votes}.\n *\n * The full history of delegate votes is tracked on-chain so that governance protocols can consider votes as distributed\n * at a particular block number to protect against flash loans and double voting. The opt-in delegate system makes the\n * cost of this history tracking optional.\n *\n * When using this module the derived contract must implement {_getVotingUnits} (for example, make it return\n * {ERC721-balanceOf}), and can use {_transferVotingUnits} to track a change in the distribution of those units (in the\n * previous example, it would be included in {ERC721-_update}).\n */\nabstract contract Votes is Context, EIP712, Nonces, IERC5805 {\n    using Checkpoints for Checkpoints.Trace208;\n\n    bytes32 private constant DELEGATION_TYPEHASH =\n        keccak256(\"Delegation(address delegatee,uint256 nonce,uint256 expiry)\");\n\n    mapping(address account => address) private _delegatee;\n\n    mapping(address delegatee => Checkpoints.Trace208) private _delegateCheckpoints;\n\n    Checkpoints.Trace208 private _totalCheckpoints;\n\n    /**\n     * @dev The clock was incorrectly modified.\n     */\n    error ERC6372InconsistentClock();\n\n    /**\n     * @dev Lookup to future votes is not available.\n     */\n    error ERC5805FutureLookup(uint256 timepoint, uint48 clock);\n\n    /**\n     * @dev Clock used for flagging checkpoints. Can be overridden to implement timestamp based\n     * checkpoints (and voting), in which case {CLOCK_MODE} should be overridden as well to match.\n     */\n    function clock() public view virtual returns (uint48) {\n        return Time.blockNumber();\n    }\n\n    /**\n     * @dev Machine-readable description of the clock as specified in ERC-6372.\n     */\n    // solhint-disable-next-line func-name-mixedcase\n    function CLOCK_MODE() public view virtual returns (string memory) {\n        // Check that the clock was not modified\n        if (clock() != Time.blockNumber()) {\n            revert ERC6372InconsistentClock();\n        }\n        return \"mode=blocknumber&from=default\";\n    }\n\n    /**\n     * @dev Validate that a timepoint is in the past, and return it as a uint48.\n     */\n    function _validateTimepoint(uint256 timepoint) internal view returns (uint48) {\n        uint48 currentTimepoint = clock();\n        if (timepoint >= currentTimepoint) revert ERC5805FutureLookup(timepoint, currentTimepoint);\n        return SafeCast.toUint48(timepoint);\n    }\n\n    /**\n     * @dev Returns the current amount of votes that `account` has.\n     */\n    function getVotes(address account) public view virtual returns (uint256) {\n        return _delegateCheckpoints[account].latest();\n    }\n\n    /**\n     * @dev Returns the amount of votes that `account` had at a specific moment in the past. If the `clock()` is\n     * configured to use block numbers, this will return the value at the end of the corresponding block.\n     *\n     * Requirements:\n     *\n     * - `timepoint` must be in the past. If operating using block numbers, the block must be already mined.\n     */\n    function getPastVotes(address account, uint256 timepoint) public view virtual returns (uint256) {\n        return _delegateCheckpoints[account].upperLookupRecent(_validateTimepoint(timepoint));\n    }\n\n    /**\n     * @dev Returns the total supply of votes available at a specific moment in the past. If the `clock()` is\n     * configured to use block numbers, this will return the value at the end of the corresponding block.\n     *\n     * NOTE: This value is the sum of all available votes, which is not necessarily the sum of all delegated votes.\n     * Votes that have not been delegated are still part of total supply, even though they would not participate in a\n     * vote.\n     *\n     * Requirements:\n     *\n     * - `timepoint` must be in the past. If operating using block numbers, the block must be already mined.\n     */\n    function getPastTotalSupply(uint256 timepoint) public view virtual returns (uint256) {\n        return _totalCheckpoints.upperLookupRecent(_validateTimepoint(timepoint));\n    }\n\n    /**\n     * @dev Returns the current total supply of votes.\n     */\n    function _getTotalSupply() internal view virtual returns (uint256) {\n        return _totalCheckpoints.latest();\n    }\n\n    /**\n     * @dev Returns the delegate that `account` has chosen.\n     */\n    function delegates(address account) public view virtual returns (address) {\n        return _delegatee[account];\n    }\n\n    /**\n     * @dev Delegates votes from the sender to `delegatee`.\n     */\n    function delegate(address delegatee) public virtual {\n        address account = _msgSender();\n        _delegate(account, delegatee);\n    }\n\n    /**\n     * @dev Delegates votes from signer to `delegatee`.\n     */\n    function delegateBySig(\n        address delegatee,\n        uint256 nonce,\n        uint256 expiry,\n        uint8 v,\n        bytes32 r,\n        bytes32 s\n    ) public virtual {\n        if (block.timestamp > expiry) {\n            revert VotesExpiredSignature(expiry);\n        }\n        address signer = ECDSA.recover(\n            _hashTypedDataV4(keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry))),\n            v,\n            r,\n            s\n        );\n        _useCheckedNonce(signer, nonce);\n        _delegate(signer, delegatee);\n    }\n\n    /**\n     * @dev Delegate all of `account`'s voting units to `delegatee`.\n     *\n     * Emits events {IVotes-DelegateChanged} and {IVotes-DelegateVotesChanged}.\n     */\n    function _delegate(address account, address delegatee) internal virtual {\n        address oldDelegate = delegates(account);\n        _delegatee[account] = delegatee;\n\n        emit DelegateChanged(account, oldDelegate, delegatee);\n        _moveDelegateVotes(oldDelegate, delegatee, _getVotingUnits(account));\n    }\n\n    /**\n     * @dev Transfers, mints, or burns voting units. To register a mint, `from` should be zero. To register a burn, `to`\n     * should be zero. Total supply of voting units will be adjusted with mints and burns.\n     */\n    function _transferVotingUnits(address from, address to, uint256 amount) internal virtual {\n        if (from == address(0)) {\n            _push(_totalCheckpoints, _add, SafeCast.toUint208(amount));\n        }\n        if (to == address(0)) {\n            _push(_totalCheckpoints, _subtract, SafeCast.toUint208(amount));\n        }\n        _moveDelegateVotes(delegates(from), delegates(to), amount);\n    }\n\n    /**\n     * @dev Moves delegated votes from one delegate to another.\n     */\n    function _moveDelegateVotes(address from, address to, uint256 amount) internal virtual {\n        if (from != to && amount > 0) {\n            if (from != address(0)) {\n                (uint256 oldValue, uint256 newValue) = _push(\n                    _delegateCheckpoints[from],\n                    _subtract,\n                    SafeCast.toUint208(amount)\n                );\n                emit DelegateVotesChanged(from, oldValue, newValue);\n            }\n            if (to != address(0)) {\n                (uint256 oldValue, uint256 newValue) = _push(\n                    _delegateCheckpoints[to],\n                    _add,\n                    SafeCast.toUint208(amount)\n                );\n                emit DelegateVotesChanged(to, oldValue, newValue);\n            }\n        }\n    }\n\n    /**\n     * @dev Get number of checkpoints for `account`.\n     */\n    function _numCheckpoints(address account) internal view virtual returns (uint32) {\n        return SafeCast.toUint32(_delegateCheckpoints[account].length());\n    }\n\n    /**\n     * @dev Get the `pos`-th checkpoint for `account`.\n     */\n    function _checkpoints(\n        address account,\n        uint32 pos\n    ) internal view virtual returns (Checkpoints.Checkpoint208 memory) {\n        return _delegateCheckpoints[account].at(pos);\n    }\n\n    function _push(\n        Checkpoints.Trace208 storage store,\n        function(uint208, uint208) view returns (uint208) op,\n        uint208 delta\n    ) private returns (uint208 oldValue, uint208 newValue) {\n        return store.push(clock(), op(store.latest(), delta));\n    }\n\n    function _add(uint208 a, uint208 b) private pure returns (uint208) {\n        return a + b;\n    }\n\n    function _subtract(uint208 a, uint208 b) private pure returns (uint208) {\n        return a - b;\n    }\n\n    /**\n     * @dev Must return the voting units held by an account.\n     */\n    function _getVotingUnits(address) internal view virtual returns (uint256);\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/LayerZero-v2/packages/layerzero-v2/evm/oapp/contracts/oft/libs/OFTComposeMsgCodec.sol","source_code":"// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.20;\n\nlibrary OFTComposeMsgCodec {\n    // Offset constants for decoding composed messages\n    uint8 private constant NONCE_OFFSET = 8;\n    uint8 private constant SRC_EID_OFFSET = 12;\n    uint8 private constant AMOUNT_LD_OFFSET = 44;\n    uint8 private constant COMPOSE_FROM_OFFSET = 76;\n\n    /**\n     * @dev Encodes a OFT composed message.\n     * @param _nonce The nonce value.\n     * @param _srcEid The source endpoint ID.\n     * @param _amountLD The amount in local decimals.\n     * @param _composeMsg The composed message.\n     * @return _msg The encoded Composed message.\n     */\n    function encode(\n        uint64 _nonce,\n        uint32 _srcEid,\n        uint256 _amountLD,\n        bytes memory _composeMsg // 0x[composeFrom][composeMsg]\n    ) internal pure returns (bytes memory _msg) {\n        _msg = abi.encodePacked(_nonce, _srcEid, _amountLD, _composeMsg);\n    }\n\n    /**\n     * @dev Retrieves the nonce from the composed message.\n     * @param _msg The message.\n     * @return The nonce value.\n     */\n    function nonce(bytes calldata _msg) internal pure returns (uint64) {\n        return uint64(bytes8(_msg[:NONCE_OFFSET]));\n    }\n\n    /**\n     * @dev Retrieves the source endpoint ID from the composed message.\n     * @param _msg The message.\n     * @return The source endpoint ID.\n     */\n    function srcEid(bytes calldata _msg) internal pure returns (uint32) {\n        return uint32(bytes4(_msg[NONCE_OFFSET:SRC_EID_OFFSET]));\n    }\n\n    /**\n     * @dev Retrieves the amount in local decimals from the composed message.\n     * @param _msg The message.\n     * @return The amount in local decimals.\n     */\n    function amountLD(bytes calldata _msg) internal pure returns (uint256) {\n        return uint256(bytes32(_msg[SRC_EID_OFFSET:AMOUNT_LD_OFFSET]));\n    }\n\n    /**\n     * @dev Retrieves the composeFrom value from the composed message.\n     * @param _msg The message.\n     * @return The composeFrom value.\n     */\n    function composeFrom(bytes calldata _msg) internal pure returns (bytes32) {\n        return bytes32(_msg[AMOUNT_LD_OFFSET:COMPOSE_FROM_OFFSET]);\n    }\n\n    /**\n     * @dev Retrieves the composed message.\n     * @param _msg The message.\n     * @return The composed message.\n     */\n    function composeMsg(bytes calldata _msg) internal pure returns (bytes memory) {\n        return _msg[COMPOSE_FROM_OFFSET:];\n    }\n\n    /**\n     * @dev Converts an address to bytes32.\n     * @param _addr The address to convert.\n     * @return The bytes32 representation of the address.\n     */\n    function addressToBytes32(address _addr) internal pure returns (bytes32) {\n        return bytes32(uint256(uint160(_addr)));\n    }\n\n    /**\n     * @dev Converts bytes32 to an address.\n     * @param _b The bytes32 value to convert.\n     * @return The address representation of bytes32.\n     */\n    function bytes32ToAddress(bytes32 _b) internal pure returns (address) {\n        return address(uint160(uint256(_b)));\n    }\n}\n"},{"file_path":"lib/LayerZero-v2/packages/layerzero-v2/evm/oapp/contracts/precrime/OAppPreCrimeSimulator.sol","source_code":"// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.20;\n\nimport { Ownable } from \"@openzeppelin/contracts/access/Ownable.sol\";\nimport { IPreCrime } from \"./interfaces/IPreCrime.sol\";\nimport { IOAppPreCrimeSimulator, InboundPacket, Origin } from \"./interfaces/IOAppPreCrimeSimulator.sol\";\n\n/**\n * @title OAppPreCrimeSimulator\n * @dev Abstract contract serving as the base for preCrime simulation functionality in an OApp.\n */\nabstract contract OAppPreCrimeSimulator is IOAppPreCrimeSimulator, Ownable {\n    // The address of the preCrime implementation.\n    address public preCrime;\n\n    /**\n     * @dev Retrieves the address of the OApp contract.\n     * @return The address of the OApp contract.\n     *\n     * @dev The simulator contract is the base contract for the OApp by default.\n     * @dev If the simulator is a separate contract, override this function.\n     */\n    function oApp() external view virtual returns (address) {\n        return address(this);\n    }\n\n    /**\n     * @dev Sets the preCrime contract address.\n     * @param _preCrime The address of the preCrime contract.\n     */\n    function setPreCrime(address _preCrime) public virtual onlyOwner {\n        preCrime = _preCrime;\n        emit PreCrimeSet(_preCrime);\n    }\n\n    /**\n     * @dev Interface for pre-crime simulations. Always reverts at the end with the simulation results.\n     * @param _packets An array of InboundPacket objects representing received packets to be delivered.\n     *\n     * @dev WARNING: MUST revert at the end with the simulation results.\n     * @dev Gives the preCrime implementation the ability to mock sending packets to the lzReceive function,\n     * WITHOUT actually executing them.\n     */\n    function lzReceiveAndRevert(InboundPacket[] calldata _packets) public payable virtual {\n        for (uint256 i = 0; i < _packets.length; i++) {\n            InboundPacket calldata packet = _packets[i];\n\n            // Ignore packets that are not from trusted peers.\n            if (!isPeer(packet.origin.srcEid, packet.origin.sender)) continue;\n\n            // @dev Because a verifier is calling this function, it doesnt have access to executor params:\n            //  - address _executor\n            //  - bytes calldata _extraData\n            // preCrime will NOT work for OApps that rely on these two parameters inside of their _lzReceive().\n            // They are instead stubbed to default values, address(0) and bytes(\"\")\n            // @dev Calling this.lzReceiveSimulate removes ability for assembly return 0 callstack exit,\n            // which would cause the revert to be ignored.\n            this.lzReceiveSimulate{ value: packet.value }(\n                packet.origin,\n                packet.guid,\n                packet.message,\n                packet.executor,\n                packet.extraData\n            );\n        }\n\n        // @dev Revert with the simulation results. msg.sender must implement IPreCrime.buildSimulationResult().\n        revert SimulationResult(IPreCrime(msg.sender).buildSimulationResult());\n    }\n\n    /**\n     * @dev Is effectively an internal function because msg.sender must be address(this).\n     * Allows resetting the call stack for 'internal' calls.\n     * @param _origin The origin information containing the source endpoint and sender address.\n     *  - srcEid: The source chain endpoint ID.\n     *  - sender: The sender address on the src chain.\n     *  - nonce: The nonce of the message.\n     * @param _guid The unique identifier of the packet.\n     * @param _message The message payload of the packet.\n     * @param _executor The executor address for the packet.\n     * @param _extraData Additional data for the packet.\n     */\n    function lzReceiveSimulate(\n        Origin calldata _origin,\n        bytes32 _guid,\n        bytes calldata _message,\n        address _executor,\n        bytes calldata _extraData\n    ) external payable virtual {\n        // @dev Ensure ONLY can be called 'internally'.\n        if (msg.sender != address(this)) revert OnlySelf();\n        _lzReceiveSimulate(_origin, _guid, _message, _executor, _extraData);\n    }\n\n    /**\n     * @dev Internal function to handle the OAppPreCrimeSimulator simulated receive.\n     * @param _origin The origin information.\n     *  - srcEid: The source chain endpoint ID.\n     *  - sender: The sender address from the src chain.\n     *  - nonce: The nonce of the LayerZero message.\n     * @param _guid The GUID of the LayerZero message.\n     * @param _message The LayerZero message.\n     * @param _executor The address of the off-chain executor.\n     * @param _extraData Arbitrary data passed by the msg executor.\n     *\n     * @dev Enables the preCrime simulator to mock sending lzReceive() messages,\n     * routes the msg down from the OAppPreCrimeSimulator, and back up to the OAppReceiver.\n     */\n    function _lzReceiveSimulate(\n        Origin calldata _origin,\n        bytes32 _guid,\n        bytes calldata _message,\n        address _executor,\n        bytes calldata _extraData\n    ) internal virtual;\n\n    /**\n     * @dev checks if the specified peer is considered 'trusted' by the OApp.\n     * @param _eid The endpoint Id to check.\n     * @param _peer The peer to check.\n     * @return Whether the peer passed is considered 'trusted' by the OApp.\n     */\n    function isPeer(uint32 _eid, bytes32 _peer) public view virtual returns (bool);\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.BRIDGE_INITIATOR, 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.OUTLAND_KEYVALUE_SENDER, CoreRoles.GOVERNOR);\n        _setRoleAdmin(CoreRoles.WHITELIST_MANAGER, 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":"lib/LayerZero-v2/packages/layerzero-v2/evm/protocol/contracts/interfaces/ISendLib.sol","source_code":"// SPDX-License-Identifier: MIT\n\npragma solidity >=0.8.0;\n\nimport { MessagingFee } from \"./ILayerZeroEndpointV2.sol\";\nimport { IMessageLib } from \"./IMessageLib.sol\";\n\nstruct Packet {\n    uint64 nonce;\n    uint32 srcEid;\n    address sender;\n    uint32 dstEid;\n    bytes32 receiver;\n    bytes32 guid;\n    bytes message;\n}\n\ninterface ISendLib is IMessageLib {\n    function send(\n        Packet calldata _packet,\n        bytes calldata _options,\n        bool _payInLzToken\n    ) external returns (MessagingFee memory, bytes memory encodedPacket);\n\n    function quote(\n        Packet calldata _packet,\n        bytes calldata _options,\n        bool _payInLzToken\n    ) external view returns (MessagingFee memory);\n\n    function setTreasury(address _treasury) external;\n\n    function withdrawFee(address _to, uint256 _amount) external;\n\n    function withdrawLzTokenFee(address _lzToken, address _to, uint256 _amount) external;\n}\n"},{"file_path":"src/funding/RedeemController.sol","source_code":"// SPDX-License-Identifier: MIT\npragma solidity 0.8.28;\n\nimport {ERC20} from \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\nimport {SafeERC20} from \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\nimport {FixedPointMathLib} from \"@solmate/src/utils/FixedPointMathLib.sol\";\n\nimport {Farm} from \"@integrations/Farm.sol\";\nimport {CoreRoles} from \"@libraries/CoreRoles.sol\";\nimport {Accounting} from \"@finance/Accounting.sol\";\nimport {ReceiptToken} from \"@tokens/ReceiptToken.sol\";\nimport {RedemptionPool} from \"@funding/RedemptionPool.sol\";\nimport {IRedeemController, IBeforeRedeemHook} from \"@interfaces/IRedeemController.sol\";\n\n/// @notice Idle Farm that allows users to withdraw from the system.\n/// This contract acts as a Redemption Pool & a Redemption Queue, and reports\n/// assets like a Farm for standardized accounting.\ncontract RedeemController is Farm, RedemptionPool, IRedeemController {\n    using SafeERC20 for ERC20;\n    using FixedPointMathLib for uint256;\n\n    /// @notice reference to the ReceiptToken contract\n    address public immutable receiptToken;\n\n    /// @notice reference to the Accounting contract\n    address public immutable accounting;\n\n    /// @notice minimum redemption amount\n    /// @dev can be set to a different number by GOVERNOR role\n    uint256 public minRedemptionAmount = 1;\n\n    /// @notice address to call in the beforeRedeem hook\n    address public beforeRedeemHook;\n\n    constructor(address _core, address _assetToken, address _receiptToken, address _accounting)\n        Farm(_core, _assetToken)\n    {\n        receiptToken = _receiptToken;\n        accounting = _accounting;\n    }\n\n    /// @notice sets the minimum redemption amount\n    /// @dev we can set this value to a higher number if we want to prevent griefing\n    /// @dev as users could enqueue thousands of small amounts to \"stuff\" the redemption queue\n    /// @param _minRedemptionAmount the minimum redemption amount\n    function setMinRedemptionAmount(uint256 _minRedemptionAmount) external onlyCoreRole(CoreRoles.PROTOCOL_PARAMETERS) {\n        require(_minRedemptionAmount > 0, RedeemAmountTooLow(_minRedemptionAmount, 1));\n        minRedemptionAmount = _minRedemptionAmount;\n        emit MinRedemptionAmountUpdated(block.timestamp, _minRedemptionAmount);\n    }\n\n    /// @notice sets the beforeRedeemHook\n    function setBeforeRedeemHook(address _beforeRedeemHook) external onlyCoreRole(CoreRoles.GOVERNOR) {\n        beforeRedeemHook = _beforeRedeemHook;\n        emit BeforeRedeemHookChanged(block.timestamp, _beforeRedeemHook);\n    }\n\n    /// @notice calculate the amount of assetToken() out for a given `amountIn` of receiptToken()\n    function receiptToAsset(uint256 _receiptAmount) external view returns (uint256) {\n        uint256 convertRatio = _getReceiptToAssetConvertRatio();\n        return _convertReceiptToAsset(_receiptAmount, convertRatio);\n    }\n\n    /// @notice returns the total assets of the redeem controller\n    /// @dev the total assets is the sum of the assets minus the total pending claims\n    function assets() public view override returns (uint256) {\n        uint256 assetTokenBalance = ERC20(assetToken).balanceOf(address(this));\n        return assetTokenBalance - totalPendingClaims;\n    }\n\n    /// @notice returns the liquidity of the redeem controller\n    function liquidity() public view override returns (uint256) {\n        return assets();\n    }\n\n    /// @notice redeem receiptTokens out of circulation in exchange of assetTokens\n    function redeem(address _to, uint256 _receiptAmountIn)\n        external\n        whenNotPaused\n        onlyCoreRole(CoreRoles.ENTRY_POINT)\n        returns (uint256)\n    {\n        require(_receiptAmountIn >= minRedemptionAmount, RedeemAmountTooLow(_receiptAmountIn, minRedemptionAmount));\n\n        // get the convert ratio between receiptToken and assetToken\n        // to be used in both way:\n        //  - when enough liquidity available: compute how much asset tokens you get by redeeming receipt tokens\n        //  - when enqueuing: compute how much receipt tokens to burn for the amount of directly available liquidity\n        uint256 convertRatio = _getReceiptToAssetConvertRatio();\n        uint256 assetAmountOut = _convertReceiptToAsset(_receiptAmountIn, convertRatio);\n\n        // To simplify the logic, we enqueue immediately if there are some entries inside the queue already\n        // This is better than attempting to fund the entire queue and do a very big automatic movement inside the system\n        // Trying to do so would be very expensive in terms of gas and could lead to slippage losses and potential accounting issues\n        if (queueLength() > 0) {\n            uint256 _amountReceiptToQueue = _convertAssetToReceipt(assetAmountOut, convertRatio);\n            // forge-lint: disable-next-line(erc20-unchecked-transfer)\n            ReceiptToken(receiptToken).transferFrom(msg.sender, address(this), _amountReceiptToQueue);\n            _enqueue(_to, _amountReceiptToQueue);\n\n            emit Redeem(block.timestamp, _to, assetToken, _receiptAmountIn, assetAmountOut);\n            return 0;\n        }\n\n        address _beforeRedeemHook = beforeRedeemHook;\n        if (_beforeRedeemHook != address(0)) {\n            IBeforeRedeemHook(_beforeRedeemHook).beforeRedeem(_to, _receiptAmountIn, assetAmountOut);\n        }\n\n        uint256 availableAssetAmount = liquidity();\n        if (assetAmountOut <= availableAssetAmount) {\n            // if the amount to redeem is less than the available liquidity, we can send it directly,\n            // no need for the redemption queue\n            ReceiptToken(receiptToken).burnFrom(msg.sender, _receiptAmountIn);\n            ERC20(assetToken).safeTransfer(_to, assetAmountOut);\n            emit Redeem(block.timestamp, _to, assetToken, _receiptAmountIn, assetAmountOut);\n            return assetAmountOut;\n        } else {\n            // send available liquidity to the recipient\n            // (by computing how much receiptToken to burn for that amount of liquidity)\n            uint256 amountReceiptToBurn = _convertAssetToReceipt(availableAssetAmount, convertRatio);\n            ReceiptToken(receiptToken).burnFrom(msg.sender, amountReceiptToBurn);\n            ERC20(assetToken).safeTransfer(_to, availableAssetAmount);\n\n            // then enqueue the remaining amount in the redemption queue\n            uint256 remainingReceiptToQueue = _receiptAmountIn - amountReceiptToBurn;\n            // forge-lint: disable-next-line(erc20-unchecked-transfer)\n            ReceiptToken(receiptToken).transferFrom(msg.sender, address(this), remainingReceiptToQueue);\n            _enqueue(_to, remainingReceiptToQueue);\n\n            // emit the redeem event for the amount of liquidity available\n            emit Redeem(block.timestamp, _to, assetToken, amountReceiptToBurn, availableAssetAmount);\n            return availableAssetAmount;\n        }\n    }\n\n    /// @notice Claim a redemption for a given recipient\n    /// @dev can be called by anyone.\n    function claimRedemption(address _recipient) external whenNotPaused onlyCoreRole(CoreRoles.ENTRY_POINT) {\n        uint256 assetsToSend = _claimRedemption(_recipient);\n        ERC20(assetToken).safeTransfer(_recipient, assetsToSend);\n    }\n\n    /// @notice When depositing funds to the redeem controller, we fund the redemption queue\n    /// and burn the corresponding receipt tokens.\n    function _deposit(uint256 assetsToDeposit) internal override {\n        if (assetsToDeposit > 0) {\n            (, uint256 receiptAmountToBurn) = _fundRedemptionQueue(assetsToDeposit, _getReceiptToAssetConvertRatio());\n            if (receiptAmountToBurn > 0) {\n                ReceiptToken(receiptToken).burn(receiptAmountToBurn);\n            }\n        }\n    }\n\n    function deposit() external override onlyCoreRole(CoreRoles.FARM_MANAGER) whenNotPaused {\n        // override to remove checks on cap & slippage\n        _deposit(liquidity());\n    }\n\n    function _withdraw(uint256 _amount, address _to) internal override {\n        ERC20(assetToken).safeTransfer(_to, _amount);\n    }\n\n    function withdraw(uint256 amount, address to) external override onlyCoreRole(CoreRoles.FARM_MANAGER) whenNotPaused {\n        // override to remove check on slippage\n        _withdraw(amount, to);\n    }\n\n    /// @notice returns the convert ratio between receiptToken and assetToken\n    /// @dev for iUSD/USDC, 1 iUSD = 1e18, receiptToken price is for example 0.8e18, USDC token price is 1e(18 + 18 - USDC decimals) = 1e30\n    /// @dev then convert ratio is 1e18 * 0.8e18 / 1e30 = 0.8e36 / 1e30 = 0.8e6\n    /// @dev so 1e18 iUSD is worth 0.8e6 USDC\n    function _getReceiptToAssetConvertRatio() internal view returns (uint256) {\n        uint256 _assetTokenPrice = Accounting(accounting).price(assetToken);\n        uint256 _receiptTokenPrice = Accounting(accounting).price(receiptToken);\n\n        return _receiptTokenPrice.divWadDown(_assetTokenPrice);\n    }\n\n    /// @notice convert an amount of receiptToken to assetToken\n    /// @param _amountReceipt the amount of receiptToken to convert\n    /// @param _convertRatio the convert ratio between receiptToken and assetToken\n    /// @dev if the convertRatio is 0.8e18, then 1 receipt token is worth 1e18 * 0.8e18 / 1e18 = 0.8e18 asset tokens\n    function _convertReceiptToAsset(uint256 _amountReceipt, uint256 _convertRatio) internal pure returns (uint256) {\n        return _amountReceipt.mulWadDown(_convertRatio);\n    }\n\n    /// @notice convert an amount of assetToken to receiptToken\n    /// @param _amountAsset the amount of assetToken to convert\n    /// @param _convertRatio the convert ratio between receiptToken and assetToken\n    /// @dev if the convertRatio is 0.8e18, then 1 asset token is worth 1e18 * 1e18 / 0.8e18 = 1.25e18 receipt tokens\n    function _convertAssetToReceipt(uint256 _amountAsset, uint256 _convertRatio) internal pure returns (uint256) {\n        return _amountAsset.divWadUp(_convertRatio);\n    }\n}\n"},{"file_path":"src/funding/MintController.sol","source_code":"// SPDX-License-Identifier: MIT\npragma solidity 0.8.28;\n\nimport {ERC20} from \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\nimport {SafeERC20} from \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\nimport {FixedPointMathLib} from \"@solmate/src/utils/FixedPointMathLib.sol\";\n\nimport {Farm} from \"@integrations/Farm.sol\";\nimport {CoreRoles} from \"@libraries/CoreRoles.sol\";\nimport {Accounting} from \"@finance/Accounting.sol\";\nimport {ReceiptToken} from \"@tokens/ReceiptToken.sol\";\nimport {IMintController, IAfterMintHook} from \"@interfaces/IMintController.sol\";\n\n/// @notice Idle Farm that allows users to deposit new funds into the system.\n/// This contract reports assets like a Farm for standardized accounting.\ncontract MintController is Farm, IMintController {\n    using SafeERC20 for ERC20;\n    using FixedPointMathLib for uint256;\n\n    /// @notice reference to the ReceiptToken contract\n    address public immutable receiptToken;\n\n    /// @notice reference to the Accounting contract\n    address public immutable accounting;\n\n    /// @notice minimum mint amount\n    /// @dev can be set to a different number by GOVERNOR role\n    uint256 public minAssetAmount = 1;\n\n    /// @notice address to call in the afterMint hook\n    address public afterMintHook;\n\n    constructor(address _core, address _assetToken, address _receiptToken, address _accounting)\n        Farm(_core, _assetToken)\n    {\n        receiptToken = _receiptToken;\n        accounting = _accounting;\n    }\n\n    /// @notice sets the minimum mint amount\n    function setMinAssetAmount(uint256 _minAssetAmount) external onlyCoreRole(CoreRoles.PROTOCOL_PARAMETERS) {\n        require(_minAssetAmount > 0, AssetAmountTooLow(_minAssetAmount, 1));\n        minAssetAmount = _minAssetAmount;\n        emit MinAssetAmountUpdated(block.timestamp, _minAssetAmount);\n    }\n\n    /// @notice sets the afterMintHook\n    function setAfterMintHook(address _afterMintHook) external onlyCoreRole(CoreRoles.GOVERNOR) {\n        afterMintHook = _afterMintHook;\n        emit AfterMintHookChanged(block.timestamp, _afterMintHook);\n    }\n\n    /// @notice calculate the amount of receiptToken() out for a given `amountIn` of assetToken()\n    function assetToReceipt(uint256 _assetAmount) public view returns (uint256) {\n        uint256 assetTokenPrice = Accounting(accounting).price(assetToken);\n        uint256 receiptTokenPrice = Accounting(accounting).price(receiptToken);\n\n        uint256 convertRatio = receiptTokenPrice.divWadUp(assetTokenPrice);\n        return _assetAmount.divWadDown(convertRatio);\n    }\n\n    /// @notice returns the assets held by the mint controller\n    function assets() public view override returns (uint256) {\n        return ERC20(assetToken).balanceOf(address(this));\n    }\n\n    /// @notice returns the liquidity of the mint controller\n    function liquidity() public view override returns (uint256) {\n        return ERC20(assetToken).balanceOf(address(this));\n    }\n\n    /// @notice introduce new receiptTokens into circulation in exchange of assetTokens\n    function mint(address _to, uint256 _assetAmountIn)\n        external\n        whenNotPaused\n        onlyCoreRole(CoreRoles.ENTRY_POINT)\n        returns (uint256)\n    {\n        require(_assetAmountIn >= minAssetAmount, AssetAmountTooLow(_assetAmountIn, minAssetAmount));\n        uint256 receiptAmountOut = assetToReceipt(_assetAmountIn);\n\n        // pull assets & mint receipt tokens to recipient\n        // external calls to the assetToken are trusted\n        ERC20(assetToken).safeTransferFrom(msg.sender, address(this), _assetAmountIn);\n        ReceiptToken(receiptToken).mint(_to, receiptAmountOut);\n\n        // handle afterMint hook if any\n        address _afterMintHook = afterMintHook;\n        if (_afterMintHook != address(0)) {\n            IAfterMintHook(_afterMintHook).afterMint(_to, _assetAmountIn);\n        }\n\n        emit Mint(block.timestamp, _to, assetToken, _assetAmountIn, receiptAmountOut);\n        return receiptAmountOut;\n    }\n\n    function _deposit(uint256) internal override {} // noop\n\n    function deposit() external override onlyCoreRole(CoreRoles.FARM_MANAGER) whenNotPaused {\n        // override to remove checks on cap & slippage\n        _deposit(0);\n    }\n\n    function _withdraw(uint256 _amount, address _to) internal override {\n        ERC20(assetToken).safeTransfer(_to, _amount);\n    }\n\n    function withdraw(uint256 amount, address to) external override onlyCoreRole(CoreRoles.FARM_MANAGER) whenNotPaused {\n        // override to remove check on slippage\n        _withdraw(amount, to);\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":"src/integrations/outland/OutlandMsgCodec.sol","source_code":"// SPDX-License-Identifier: MIT\npragma solidity 0.8.28;\n\n/// @title OutlandMsgCodec\n/// @notice Utility library for decoding cross-chain messages and payloads in the Outland system\n/// @dev Wire layout: selector (32) | chainId (32) | nonce (32) | abi.encode(payload body)\nlibrary OutlandMsgCodec {\n    error InvalidSize(uint256 _size);\n\n    /// @notice Transport type identifier for general messages\n    bytes1 internal constant MESSAGE = hex\"00\";\n\n    /// @notice Transport type identifier for token transfers\n    bytes1 internal constant TRANSFER = hex\"01\";\n\n    /// @notice Transport type identifier for arbitrary hub-outpost key-value updates\n    bytes1 internal constant KEY_VALUE = hex\"02\";\n\n    /// @notice Transport type identifier for iUSD / siUSD bridging with an assets report\n    bytes1 internal constant TOKEN_BRIDGE = hex\"03\";\n\n    uint256 public constant HEADER_SIZE = 96;\n\n    /// @notice Gets the message type from cross-chain message data\n    function getMessageType(bytes calldata _data) internal pure returns (bytes1 messageType) {\n        require(_data.length >= HEADER_SIZE, InvalidSize(_data.length));\n        messageType = bytes1(_data[:32]);\n    }\n\n    /// @notice Gets the chain ID from cross-chain message data\n    function getChainId(bytes calldata _data) internal pure returns (uint256 chainId) {\n        require(_data.length >= HEADER_SIZE, InvalidSize(_data.length));\n        chainId = uint256(bytes32(_data[32:64]));\n    }\n\n    /// @notice Gets the outbound nonce assigned by the sender portal\n    function getNonce(bytes calldata _data) internal pure returns (uint256 nonce) {\n        require(_data.length >= HEADER_SIZE, InvalidSize(_data.length));\n        nonce = uint256(bytes32(_data[64:96]));\n    }\n\n    /// @notice Gets the transfer payload (recipient and amount) from cross-chain data\n    function getTransferPayload(bytes calldata _data) internal pure returns (address, uint256) {\n        require(_data.length >= HEADER_SIZE, InvalidSize(_data.length));\n        return abi.decode(_data[HEADER_SIZE:], (address, uint256));\n    }\n\n    /// @notice Gets the assets update payload from cross-chain data\n    function getAssetsUpdatePayload(bytes calldata _data) internal pure returns (uint256, uint256, uint256) {\n        require(_data.length >= HEADER_SIZE, InvalidSize(_data.length));\n        return abi.decode(_data[HEADER_SIZE:], (uint256, uint256, uint256));\n    }\n\n    /// @notice Gets the key-value payload from cross-chain data\n    function getKeyValuePayload(bytes calldata _data)\n        internal\n        pure\n        returns (bytes32 key, bytes32 value, uint256 sentAt)\n    {\n        require(_data.length >= HEADER_SIZE, InvalidSize(_data.length));\n        (key, value, sentAt) = abi.decode(_data[HEADER_SIZE:], (bytes32, bytes32, uint256));\n    }\n\n    /// @notice Gets the token bridge payload from cross-chain data\n    function getTokenBridgePayload(bytes calldata _data)\n        internal\n        pure\n        returns (\n            address token,\n            uint256 amount,\n            address recipient,\n            uint256 destinationChainId,\n            uint256 totalAssetsValue,\n            uint256 receiptTokenTotalSupply,\n            uint256 stakedTokenTotalSupply\n        )\n    {\n        require(_data.length >= HEADER_SIZE, InvalidSize(_data.length));\n        return abi.decode(_data[HEADER_SIZE:], (address, uint256, address, uint256, uint256, uint256, uint256));\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":"lib/openzeppelin-contracts/contracts/utils/ReentrancyGuardTransient.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.5.0) (utils/ReentrancyGuardTransient.sol)\n\npragma solidity ^0.8.24;\n\nimport {TransientSlot} from \"./TransientSlot.sol\";\n\n/**\n * @dev Variant of {ReentrancyGuard} that uses transient storage.\n *\n * NOTE: This variant only works on networks where EIP-1153 is available.\n *\n * _Available since v5.1._\n *\n * @custom:stateless\n */\nabstract contract ReentrancyGuardTransient {\n    using TransientSlot for *;\n\n    // keccak256(abi.encode(uint256(keccak256(\"openzeppelin.storage.ReentrancyGuard\")) - 1)) & ~bytes32(uint256(0xff))\n    bytes32 private constant REENTRANCY_GUARD_STORAGE =\n        0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;\n\n    /**\n     * @dev Unauthorized reentrant call.\n     */\n    error ReentrancyGuardReentrantCall();\n\n    /**\n     * @dev Prevents a contract from calling itself, directly or indirectly.\n     * Calling a `nonReentrant` function from another `nonReentrant`\n     * function is not supported. It is possible to prevent this from happening\n     * by making the `nonReentrant` function external, and making it call a\n     * `private` function that does the actual work.\n     */\n    modifier nonReentrant() {\n        _nonReentrantBefore();\n        _;\n        _nonReentrantAfter();\n    }\n\n    /**\n     * @dev A `view` only version of {nonReentrant}. Use to block view functions\n     * from being called, preventing reading from inconsistent contract state.\n     *\n     * CAUTION: This is a \"view\" modifier and does not change the reentrancy\n     * status. Use it only on view functions. For payable or non-payable functions,\n     * use the standard {nonReentrant} modifier instead.\n     */\n    modifier nonReentrantView() {\n        _nonReentrantBeforeView();\n        _;\n    }\n\n    function _nonReentrantBeforeView() private view {\n        if (_reentrancyGuardEntered()) {\n            revert ReentrancyGuardReentrantCall();\n        }\n    }\n\n    function _nonReentrantBefore() private {\n        // On the first call to nonReentrant, REENTRANCY_GUARD_STORAGE.asBoolean().tload() will be false\n        _nonReentrantBeforeView();\n\n        // Any calls to nonReentrant after this point will fail\n        _reentrancyGuardStorageSlot().asBoolean().tstore(true);\n    }\n\n    function _nonReentrantAfter() private {\n        _reentrancyGuardStorageSlot().asBoolean().tstore(false);\n    }\n\n    /**\n     * @dev Returns true if the reentrancy guard is currently set to \"entered\", which indicates there is a\n     * `nonReentrant` function in the call stack.\n     */\n    function _reentrancyGuardEntered() internal view returns (bool) {\n        return _reentrancyGuardStorageSlot().asBoolean().tload();\n    }\n\n    function _reentrancyGuardStorageSlot() internal pure virtual returns (bytes32) {\n        return REENTRANCY_GUARD_STORAGE;\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":"lib/LayerZero-v2/packages/layerzero-v2/evm/protocol/contracts/interfaces/IMessagingContext.sol","source_code":"// SPDX-License-Identifier: MIT\n\npragma solidity >=0.8.0;\n\ninterface IMessagingContext {\n    function isSendingMessage() external view returns (bool);\n\n    function getSendContext() external view returns (uint32 dstEid, address sender);\n}\n"},{"file_path":"src/funding/MigrationController.sol","source_code":"// SPDX-License-Identifier: MIT\npragma solidity 0.8.28;\n\nimport {ERC20} from \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\nimport {SafeERC20} from \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\nimport {FixedPointMathLib} from \"@solmate/src/utils/FixedPointMathLib.sol\";\n\nimport {EpochLib} from \"@libraries/EpochLib.sol\";\nimport {FarmTypes} from \"@libraries/FarmTypes.sol\";\nimport {CoreRoles} from \"@libraries/CoreRoles.sol\";\nimport {Accounting} from \"@finance/Accounting.sol\";\nimport {ReceiptToken} from \"@tokens/ReceiptToken.sol\";\nimport {FarmRegistry} from \"@integrations/FarmRegistry.sol\";\nimport {CoreControlled} from \"@core/CoreControlled.sol\";\nimport {LockingController} from \"@locking/LockingController.sol\";\nimport {IMaturityFarm, IFarm} from \"@interfaces/IMaturityFarm.sol\";\n\n/// @notice Migration Controller\n/// This contract allows users to migrate their funds from other protocols where\n/// the InfiniFi protocol is also deploying, to receive InfinFi locked receipt tokens instead.\n/// @dev this contract needs RECEIPT_TOKEN_MINTER & ENTRY_POINT roles\ncontract MigrationController is CoreControlled {\n    using EpochLib for uint256;\n    using SafeERC20 for ERC20;\n    using FixedPointMathLib for uint256;\n\n    error InvalidMaturity();\n    error HookFailed(address farm, bytes4 selector);\n    error CapExceeded(address farm, address token, uint256 cap);\n    error InvalidAmount(uint256 amount);\n    error MigrationFailed(address _farm, uint256 _amount);\n    error FarmNotRegistered(address farm);\n    error MigrationAmountTooLow(uint256 iusdAmount, uint256 minMigrationAmount);\n\n    event SetConfig(uint256 indexed timestamp, address farm, address token, MigrationConfig config);\n    event Migrated(\n        uint256 indexed timestamp, address indexed user, address farm, address token, uint256 receiptTokenAmount\n    );\n\n    /// @notice reference to the FarmRegistry contract\n    address public immutable farmRegistry;\n\n    /// @notice reference to the Accounting contract\n    address public immutable accounting;\n\n    /// @notice reference to the LockingController contract\n    address public immutable lockingController;\n\n    /// @notice reference to the ReceiptToken contract\n    address public immutable receiptToken;\n\n    struct MigrationConfig {\n        bytes4 selector; // selector of the function to call after migration\n        uint112 cap; // maximum amount of iUSD that can be minted by migrating to the farm\n        uint112 migrated; // amount of iUSD that has been minted by migrating to the farm\n        uint128 minMigrationAmount; // minimum amount of iUSD that can be migrated to the farm\n        uint128 migrationFee; // fee as a percent with 18 decimals, e.g. 0.01e18 = 1%\n    }\n\n    /// @notice mapping of farms migration cap data\n    mapping(address farm => mapping(address token => MigrationConfig data)) public config;\n\n    constructor(\n        address _core,\n        address _farmRegistry,\n        address _accounting,\n        address _lockingController,\n        address _receiptToken\n    ) CoreControlled(_core) {\n        farmRegistry = _farmRegistry;\n        accounting = _accounting;\n        lockingController = _lockingController;\n        receiptToken = _receiptToken;\n    }\n\n    /// @notice sets a farm's migration cap data\n    /// @dev note that this resets the migrated amount to 0\n    function setConfig(\n        address _farm,\n        address _token,\n        uint256 _cap,\n        bytes4 _selector,\n        uint256 _minMigrationAmount,\n        uint256 _migrationFee\n    ) external onlyCoreRole(CoreRoles.PROTOCOL_PARAMETERS) {\n        // down castings are safe because this is a configuration call that should be simulated\n        // by devs & peer reviewed before broadcasting onchain.\n        // forge-lint: disable-next-item(unsafe-typecast)\n        MigrationConfig memory _config = MigrationConfig({\n            selector: _selector,\n            cap: uint112(_cap),\n            migrated: uint112(0),\n            minMigrationAmount: uint128(_minMigrationAmount),\n            migrationFee: uint128(_migrationFee)\n        });\n\n        config[_farm][_token] = _config;\n\n        emit SetConfig(block.timestamp, _farm, _token, _config);\n    }\n\n    /// @notice Migrate assets to InfiniFi farms\n    /// @return iusdAmount Amount of iUSD locked on behalf of the recipient\n    function migrate(address _recipient, address _farm, address _token, uint256 _amount, uint32 _unwindingEpochs)\n        external\n        onlyCoreRole(CoreRoles.ENTRY_POINT)\n        returns (uint256)\n    {\n        require(_amount > 0, InvalidAmount(_amount));\n        // check farm is still in the registry\n        require(FarmRegistry(farmRegistry).isFarmOfType(_farm, FarmTypes.MATURITY), FarmNotRegistered(_farm));\n\n        // check lock duration vs farm's maturity\n        {\n            uint256 userUnwindingTimestamp = (block.timestamp.nextEpoch() + _unwindingEpochs).epochToTimestamp();\n            require(IMaturityFarm(_farm).maturity() <= userUnwindingTimestamp, InvalidMaturity());\n        }\n\n        // compute iUSD amount owed to the user\n        MigrationConfig memory _config = config[_farm][_token];\n        uint256 iusdAmount;\n        {\n            uint256 assetsBefore = IFarm(_farm).assets();\n            // airdrop tokens to farm\n            ERC20(_token).safeTransferFrom(msg.sender, _farm, _amount);\n            _callHookIfConfigured(_farm, _config.selector);\n            uint256 assetsAfter = IFarm(_farm).assets();\n            uint256 farmCap = IFarm(_farm).cap();\n            require(assetsAfter <= farmCap, CapExceeded(_farm, _token, farmCap));\n\n            uint256 assetsIncrease = assetsAfter - assetsBefore;\n            require(assetsIncrease > 0, MigrationFailed(_farm, _amount));\n            uint256 assetPrice = Accounting(accounting).price(IFarm(_farm).assetToken());\n            uint256 iusdPrice = Accounting(accounting).price(receiptToken);\n\n            iusdAmount = assetsIncrease.mulDivDown(assetPrice, iusdPrice);\n        }\n\n        // apply fee and check minimum migration amount\n        iusdAmount -= iusdAmount.mulWadDown(uint256(_config.migrationFee));\n        require(iusdAmount >= _config.minMigrationAmount, MigrationAmountTooLow(iusdAmount, _config.minMigrationAmount));\n\n        // check for farm migration cap\n        require(_config.migrated + iusdAmount <= _config.cap, CapExceeded(_farm, _token, _config.cap));\n\n        // mint iUSD, lock it, send to user\n        ReceiptToken(receiptToken).mint(address(this), iusdAmount);\n        ReceiptToken(receiptToken).approve(lockingController, iusdAmount);\n        LockingController(lockingController).createPosition(iusdAmount, _unwindingEpochs, _recipient);\n\n        // update migrated amount\n        // casting to 'uint112' is safe because of the require above\n        // forge-lint: disable-next-line(unsafe-typecast)\n        config[_farm][_token].migrated += uint112(iusdAmount);\n\n        emit Migrated(block.timestamp, _recipient, _farm, _token, iusdAmount);\n        return iusdAmount;\n    }\n\n    function _callHookIfConfigured(address _farm, bytes4 _selector) internal {\n        if (_selector != bytes4(0)) {\n            (bool success,) = _farm.call(abi.encodeWithSelector(_selector));\n            require(success, HookFailed(_farm, _selector));\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/utils/structs/Checkpoints.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.5.0) (utils/structs/Checkpoints.sol)\n// This file was procedurally generated from scripts/generate/templates/Checkpoints.js.\n\npragma solidity ^0.8.20;\n\nimport {Math} from \"../math/Math.sol\";\n\n/**\n * @dev This library defines the `Trace*` struct, for checkpointing values as they change at different points in\n * time, and later looking up past values by block number. See {Votes} as an example.\n *\n * To create a history of checkpoints define a variable type `Checkpoints.Trace*` in your contract, and store a new\n * checkpoint for the current transaction block using the {push} function.\n */\nlibrary Checkpoints {\n    /**\n     * @dev A value was attempted to be inserted on a past checkpoint.\n     */\n    error CheckpointUnorderedInsertion();\n\n    struct Trace256 {\n        Checkpoint256[] _checkpoints;\n    }\n\n    struct Checkpoint256 {\n        uint256 _key;\n        uint256 _value;\n    }\n\n    /**\n     * @dev Pushes a (`key`, `value`) pair into a Trace256 so that it is stored as the checkpoint.\n     *\n     * Returns previous value and new value.\n     *\n     * IMPORTANT: Never accept `key` as a user input, since an arbitrary `type(uint256).max` key set will disable the\n     * library.\n     */\n    function push(\n        Trace256 storage self,\n        uint256 key,\n        uint256 value\n    ) internal returns (uint256 oldValue, uint256 newValue) {\n        return _insert(self._checkpoints, key, value);\n    }\n\n    /**\n     * @dev Returns the value in the first (oldest) checkpoint with key greater or equal than the search key, or zero if\n     * there is none.\n     */\n    function lowerLookup(Trace256 storage self, uint256 key) internal view returns (uint256) {\n        uint256 len = self._checkpoints.length;\n        uint256 pos = _lowerBinaryLookup(self._checkpoints, key, 0, len);\n        return pos == len ? 0 : _unsafeAccess(self._checkpoints, pos)._value;\n    }\n\n    /**\n     * @dev Returns the value in the last (most recent) checkpoint with key lower or equal than the search key, or zero\n     * if there is none.\n     */\n    function upperLookup(Trace256 storage self, uint256 key) internal view returns (uint256) {\n        uint256 len = self._checkpoints.length;\n        uint256 pos = _upperBinaryLookup(self._checkpoints, key, 0, len);\n        return pos == 0 ? 0 : _unsafeAccess(self._checkpoints, pos - 1)._value;\n    }\n\n    /**\n     * @dev Returns the value in the last (most recent) checkpoint with key lower or equal than the search key, or zero\n     * if there is none.\n     *\n     * NOTE: This is a variant of {upperLookup} that is optimized to find \"recent\" checkpoint (checkpoints with high\n     * keys).\n     */\n    function upperLookupRecent(Trace256 storage self, uint256 key) internal view returns (uint256) {\n        uint256 len = self._checkpoints.length;\n\n        uint256 low = 0;\n        uint256 high = len;\n\n        if (len > 5) {\n            uint256 mid = len - Math.sqrt(len);\n            if (key < _unsafeAccess(self._checkpoints, mid)._key) {\n                high = mid;\n            } else {\n                low = mid + 1;\n            }\n        }\n\n        uint256 pos = _upperBinaryLookup(self._checkpoints, key, low, high);\n\n        return pos == 0 ? 0 : _unsafeAccess(self._checkpoints, pos - 1)._value;\n    }\n\n    /**\n     * @dev Returns the value in the most recent checkpoint, or zero if there are no checkpoints.\n     */\n    function latest(Trace256 storage self) internal view returns (uint256) {\n        uint256 pos = self._checkpoints.length;\n        return pos == 0 ? 0 : _unsafeAccess(self._checkpoints, pos - 1)._value;\n    }\n\n    /**\n     * @dev Returns whether there is a checkpoint in the structure (i.e. it is not empty), and if so the key and value\n     * in the most recent checkpoint.\n     */\n    function latestCheckpoint(Trace256 storage self) internal view returns (bool exists, uint256 _key, uint256 _value) {\n        uint256 pos = self._checkpoints.length;\n        if (pos == 0) {\n            return (false, 0, 0);\n        } else {\n            Checkpoint256 storage ckpt = _unsafeAccess(self._checkpoints, pos - 1);\n            return (true, ckpt._key, ckpt._value);\n        }\n    }\n\n    /**\n     * @dev Returns the number of checkpoints.\n     */\n    function length(Trace256 storage self) internal view returns (uint256) {\n        return self._checkpoints.length;\n    }\n\n    /**\n     * @dev Returns checkpoint at given position.\n     */\n    function at(Trace256 storage self, uint32 pos) internal view returns (Checkpoint256 memory) {\n        return self._checkpoints[pos];\n    }\n\n    /**\n     * @dev Pushes a (`key`, `value`) pair into an ordered list of checkpoints, either by inserting a new checkpoint,\n     * or by updating the last one.\n     */\n    function _insert(\n        Checkpoint256[] storage self,\n        uint256 key,\n        uint256 value\n    ) private returns (uint256 oldValue, uint256 newValue) {\n        uint256 pos = self.length;\n\n        if (pos > 0) {\n            Checkpoint256 storage last = _unsafeAccess(self, pos - 1);\n            uint256 lastKey = last._key;\n            uint256 lastValue = last._value;\n\n            // Checkpoint keys must be non-decreasing.\n            if (lastKey > key) {\n                revert CheckpointUnorderedInsertion();\n            }\n\n            // Update or push new checkpoint\n            if (lastKey == key) {\n                last._value = value;\n            } else {\n                self.push(Checkpoint256({_key: key, _value: value}));\n            }\n            return (lastValue, value);\n        } else {\n            self.push(Checkpoint256({_key: key, _value: value}));\n            return (0, value);\n        }\n    }\n\n    /**\n     * @dev Return the index of the first (oldest) checkpoint with key strictly bigger than the search key, or `high`\n     * if there is none. `low` and `high` define a section where to do the search, with inclusive `low` and exclusive\n     * `high`.\n     *\n     * WARNING: `high` should not be greater than the array's length.\n     */\n    function _upperBinaryLookup(\n        Checkpoint256[] storage self,\n        uint256 key,\n        uint256 low,\n        uint256 high\n    ) private view returns (uint256) {\n        while (low < high) {\n            uint256 mid = Math.average(low, high);\n            if (_unsafeAccess(self, mid)._key > key) {\n                high = mid;\n            } else {\n                low = mid + 1;\n            }\n        }\n        return high;\n    }\n\n    /**\n     * @dev Return the index of the first (oldest) checkpoint with key greater or equal than the search key, or `high`\n     * if there is none. `low` and `high` define a section where to do the search, with inclusive `low` and exclusive\n     * `high`.\n     *\n     * WARNING: `high` should not be greater than the array's length.\n     */\n    function _lowerBinaryLookup(\n        Checkpoint256[] storage self,\n        uint256 key,\n        uint256 low,\n        uint256 high\n    ) private view returns (uint256) {\n        while (low < high) {\n            uint256 mid = Math.average(low, high);\n            if (_unsafeAccess(self, mid)._key < key) {\n                low = mid + 1;\n            } else {\n                high = mid;\n            }\n        }\n        return high;\n    }\n\n    /**\n     * @dev Access an element of the array without performing bounds check. The position is assumed to be within bounds.\n     */\n    function _unsafeAccess(\n        Checkpoint256[] storage self,\n        uint256 pos\n    ) private pure returns (Checkpoint256 storage result) {\n        assembly {\n            mstore(0x00, self.slot)\n            result.slot := add(keccak256(0x00, 0x20), mul(pos, 2))\n        }\n    }\n\n    struct Trace224 {\n        Checkpoint224[] _checkpoints;\n    }\n\n    struct Checkpoint224 {\n        uint32 _key;\n        uint224 _value;\n    }\n\n    /**\n     * @dev Pushes a (`key`, `value`) pair into a Trace224 so that it is stored as the checkpoint.\n     *\n     * Returns previous value and new value.\n     *\n     * IMPORTANT: Never accept `key` as a user input, since an arbitrary `type(uint32).max` key set will disable the\n     * library.\n     */\n    function push(\n        Trace224 storage self,\n        uint32 key,\n        uint224 value\n    ) internal returns (uint224 oldValue, uint224 newValue) {\n        return _insert(self._checkpoints, key, value);\n    }\n\n    /**\n     * @dev Returns the value in the first (oldest) checkpoint with key greater or equal than the search key, or zero if\n     * there is none.\n     */\n    function lowerLookup(Trace224 storage self, uint32 key) internal view returns (uint224) {\n        uint256 len = self._checkpoints.length;\n        uint256 pos = _lowerBinaryLookup(self._checkpoints, key, 0, len);\n        return pos == len ? 0 : _unsafeAccess(self._checkpoints, pos)._value;\n    }\n\n    /**\n     * @dev Returns the value in the last (most recent) checkpoint with key lower or equal than the search key, or zero\n     * if there is none.\n     */\n    function upperLookup(Trace224 storage self, uint32 key) internal view returns (uint224) {\n        uint256 len = self._checkpoints.length;\n        uint256 pos = _upperBinaryLookup(self._checkpoints, key, 0, len);\n        return pos == 0 ? 0 : _unsafeAccess(self._checkpoints, pos - 1)._value;\n    }\n\n    /**\n     * @dev Returns the value in the last (most recent) checkpoint with key lower or equal than the search key, or zero\n     * if there is none.\n     *\n     * NOTE: This is a variant of {upperLookup} that is optimized to find \"recent\" checkpoint (checkpoints with high\n     * keys).\n     */\n    function upperLookupRecent(Trace224 storage self, uint32 key) internal view returns (uint224) {\n        uint256 len = self._checkpoints.length;\n\n        uint256 low = 0;\n        uint256 high = len;\n\n        if (len > 5) {\n            uint256 mid = len - Math.sqrt(len);\n            if (key < _unsafeAccess(self._checkpoints, mid)._key) {\n                high = mid;\n            } else {\n                low = mid + 1;\n            }\n        }\n\n        uint256 pos = _upperBinaryLookup(self._checkpoints, key, low, high);\n\n        return pos == 0 ? 0 : _unsafeAccess(self._checkpoints, pos - 1)._value;\n    }\n\n    /**\n     * @dev Returns the value in the most recent checkpoint, or zero if there are no checkpoints.\n     */\n    function latest(Trace224 storage self) internal view returns (uint224) {\n        uint256 pos = self._checkpoints.length;\n        return pos == 0 ? 0 : _unsafeAccess(self._checkpoints, pos - 1)._value;\n    }\n\n    /**\n     * @dev Returns whether there is a checkpoint in the structure (i.e. it is not empty), and if so the key and value\n     * in the most recent checkpoint.\n     */\n    function latestCheckpoint(Trace224 storage self) internal view returns (bool exists, uint32 _key, uint224 _value) {\n        uint256 pos = self._checkpoints.length;\n        if (pos == 0) {\n            return (false, 0, 0);\n        } else {\n            Checkpoint224 storage ckpt = _unsafeAccess(self._checkpoints, pos - 1);\n            return (true, ckpt._key, ckpt._value);\n        }\n    }\n\n    /**\n     * @dev Returns the number of checkpoints.\n     */\n    function length(Trace224 storage self) internal view returns (uint256) {\n        return self._checkpoints.length;\n    }\n\n    /**\n     * @dev Returns checkpoint at given position.\n     */\n    function at(Trace224 storage self, uint32 pos) internal view returns (Checkpoint224 memory) {\n        return self._checkpoints[pos];\n    }\n\n    /**\n     * @dev Pushes a (`key`, `value`) pair into an ordered list of checkpoints, either by inserting a new checkpoint,\n     * or by updating the last one.\n     */\n    function _insert(\n        Checkpoint224[] storage self,\n        uint32 key,\n        uint224 value\n    ) private returns (uint224 oldValue, uint224 newValue) {\n        uint256 pos = self.length;\n\n        if (pos > 0) {\n            Checkpoint224 storage last = _unsafeAccess(self, pos - 1);\n            uint32 lastKey = last._key;\n            uint224 lastValue = last._value;\n\n            // Checkpoint keys must be non-decreasing.\n            if (lastKey > key) {\n                revert CheckpointUnorderedInsertion();\n            }\n\n            // Update or push new checkpoint\n            if (lastKey == key) {\n                last._value = value;\n            } else {\n                self.push(Checkpoint224({_key: key, _value: value}));\n            }\n            return (lastValue, value);\n        } else {\n            self.push(Checkpoint224({_key: key, _value: value}));\n            return (0, value);\n        }\n    }\n\n    /**\n     * @dev Return the index of the first (oldest) checkpoint with key strictly bigger than the search key, or `high`\n     * if there is none. `low` and `high` define a section where to do the search, with inclusive `low` and exclusive\n     * `high`.\n     *\n     * WARNING: `high` should not be greater than the array's length.\n     */\n    function _upperBinaryLookup(\n        Checkpoint224[] storage self,\n        uint32 key,\n        uint256 low,\n        uint256 high\n    ) private view returns (uint256) {\n        while (low < high) {\n            uint256 mid = Math.average(low, high);\n            if (_unsafeAccess(self, mid)._key > key) {\n                high = mid;\n            } else {\n                low = mid + 1;\n            }\n        }\n        return high;\n    }\n\n    /**\n     * @dev Return the index of the first (oldest) checkpoint with key greater or equal than the search key, or `high`\n     * if there is none. `low` and `high` define a section where to do the search, with inclusive `low` and exclusive\n     * `high`.\n     *\n     * WARNING: `high` should not be greater than the array's length.\n     */\n    function _lowerBinaryLookup(\n        Checkpoint224[] storage self,\n        uint32 key,\n        uint256 low,\n        uint256 high\n    ) private view returns (uint256) {\n        while (low < high) {\n            uint256 mid = Math.average(low, high);\n            if (_unsafeAccess(self, mid)._key < key) {\n                low = mid + 1;\n            } else {\n                high = mid;\n            }\n        }\n        return high;\n    }\n\n    /**\n     * @dev Access an element of the array without performing bounds check. The position is assumed to be within bounds.\n     */\n    function _unsafeAccess(\n        Checkpoint224[] storage self,\n        uint256 pos\n    ) private pure returns (Checkpoint224 storage result) {\n        assembly {\n            mstore(0x00, self.slot)\n            result.slot := add(keccak256(0x00, 0x20), pos)\n        }\n    }\n\n    struct Trace208 {\n        Checkpoint208[] _checkpoints;\n    }\n\n    struct Checkpoint208 {\n        uint48 _key;\n        uint208 _value;\n    }\n\n    /**\n     * @dev Pushes a (`key`, `value`) pair into a Trace208 so that it is stored as the checkpoint.\n     *\n     * Returns previous value and new value.\n     *\n     * IMPORTANT: Never accept `key` as a user input, since an arbitrary `type(uint48).max` key set will disable the\n     * library.\n     */\n    function push(\n        Trace208 storage self,\n        uint48 key,\n        uint208 value\n    ) internal returns (uint208 oldValue, uint208 newValue) {\n        return _insert(self._checkpoints, key, value);\n    }\n\n    /**\n     * @dev Returns the value in the first (oldest) checkpoint with key greater or equal than the search key, or zero if\n     * there is none.\n     */\n    function lowerLookup(Trace208 storage self, uint48 key) internal view returns (uint208) {\n        uint256 len = self._checkpoints.length;\n        uint256 pos = _lowerBinaryLookup(self._checkpoints, key, 0, len);\n        return pos == len ? 0 : _unsafeAccess(self._checkpoints, pos)._value;\n    }\n\n    /**\n     * @dev Returns the value in the last (most recent) checkpoint with key lower or equal than the search key, or zero\n     * if there is none.\n     */\n    function upperLookup(Trace208 storage self, uint48 key) internal view returns (uint208) {\n        uint256 len = self._checkpoints.length;\n        uint256 pos = _upperBinaryLookup(self._checkpoints, key, 0, len);\n        return pos == 0 ? 0 : _unsafeAccess(self._checkpoints, pos - 1)._value;\n    }\n\n    /**\n     * @dev Returns the value in the last (most recent) checkpoint with key lower or equal than the search key, or zero\n     * if there is none.\n     *\n     * NOTE: This is a variant of {upperLookup} that is optimized to find \"recent\" checkpoint (checkpoints with high\n     * keys).\n     */\n    function upperLookupRecent(Trace208 storage self, uint48 key) internal view returns (uint208) {\n        uint256 len = self._checkpoints.length;\n\n        uint256 low = 0;\n        uint256 high = len;\n\n        if (len > 5) {\n            uint256 mid = len - Math.sqrt(len);\n            if (key < _unsafeAccess(self._checkpoints, mid)._key) {\n                high = mid;\n            } else {\n                low = mid + 1;\n            }\n        }\n\n        uint256 pos = _upperBinaryLookup(self._checkpoints, key, low, high);\n\n        return pos == 0 ? 0 : _unsafeAccess(self._checkpoints, pos - 1)._value;\n    }\n\n    /**\n     * @dev Returns the value in the most recent checkpoint, or zero if there are no checkpoints.\n     */\n    function latest(Trace208 storage self) internal view returns (uint208) {\n        uint256 pos = self._checkpoints.length;\n        return pos == 0 ? 0 : _unsafeAccess(self._checkpoints, pos - 1)._value;\n    }\n\n    /**\n     * @dev Returns whether there is a checkpoint in the structure (i.e. it is not empty), and if so the key and value\n     * in the most recent checkpoint.\n     */\n    function latestCheckpoint(Trace208 storage self) internal view returns (bool exists, uint48 _key, uint208 _value) {\n        uint256 pos = self._checkpoints.length;\n        if (pos == 0) {\n            return (false, 0, 0);\n        } else {\n            Checkpoint208 storage ckpt = _unsafeAccess(self._checkpoints, pos - 1);\n            return (true, ckpt._key, ckpt._value);\n        }\n    }\n\n    /**\n     * @dev Returns the number of checkpoints.\n     */\n    function length(Trace208 storage self) internal view returns (uint256) {\n        return self._checkpoints.length;\n    }\n\n    /**\n     * @dev Returns checkpoint at given position.\n     */\n    function at(Trace208 storage self, uint32 pos) internal view returns (Checkpoint208 memory) {\n        return self._checkpoints[pos];\n    }\n\n    /**\n     * @dev Pushes a (`key`, `value`) pair into an ordered list of checkpoints, either by inserting a new checkpoint,\n     * or by updating the last one.\n     */\n    function _insert(\n        Checkpoint208[] storage self,\n        uint48 key,\n        uint208 value\n    ) private returns (uint208 oldValue, uint208 newValue) {\n        uint256 pos = self.length;\n\n        if (pos > 0) {\n            Checkpoint208 storage last = _unsafeAccess(self, pos - 1);\n            uint48 lastKey = last._key;\n            uint208 lastValue = last._value;\n\n            // Checkpoint keys must be non-decreasing.\n            if (lastKey > key) {\n                revert CheckpointUnorderedInsertion();\n            }\n\n            // Update or push new checkpoint\n            if (lastKey == key) {\n                last._value = value;\n            } else {\n                self.push(Checkpoint208({_key: key, _value: value}));\n            }\n            return (lastValue, value);\n        } else {\n            self.push(Checkpoint208({_key: key, _value: value}));\n            return (0, value);\n        }\n    }\n\n    /**\n     * @dev Return the index of the first (oldest) checkpoint with key strictly bigger than the search key, or `high`\n     * if there is none. `low` and `high` define a section where to do the search, with inclusive `low` and exclusive\n     * `high`.\n     *\n     * WARNING: `high` should not be greater than the array's length.\n     */\n    function _upperBinaryLookup(\n        Checkpoint208[] storage self,\n        uint48 key,\n        uint256 low,\n        uint256 high\n    ) private view returns (uint256) {\n        while (low < high) {\n            uint256 mid = Math.average(low, high);\n            if (_unsafeAccess(self, mid)._key > key) {\n                high = mid;\n            } else {\n                low = mid + 1;\n            }\n        }\n        return high;\n    }\n\n    /**\n     * @dev Return the index of the first (oldest) checkpoint with key greater or equal than the search key, or `high`\n     * if there is none. `low` and `high` define a section where to do the search, with inclusive `low` and exclusive\n     * `high`.\n     *\n     * WARNING: `high` should not be greater than the array's length.\n     */\n    function _lowerBinaryLookup(\n        Checkpoint208[] storage self,\n        uint48 key,\n        uint256 low,\n        uint256 high\n    ) private view returns (uint256) {\n        while (low < high) {\n            uint256 mid = Math.average(low, high);\n            if (_unsafeAccess(self, mid)._key < key) {\n                low = mid + 1;\n            } else {\n                high = mid;\n            }\n        }\n        return high;\n    }\n\n    /**\n     * @dev Access an element of the array without performing bounds check. The position is assumed to be within bounds.\n     */\n    function _unsafeAccess(\n        Checkpoint208[] storage self,\n        uint256 pos\n    ) private pure returns (Checkpoint208 storage result) {\n        assembly {\n            mstore(0x00, self.slot)\n            result.slot := add(keccak256(0x00, 0x20), pos)\n        }\n    }\n\n    struct Trace160 {\n        Checkpoint160[] _checkpoints;\n    }\n\n    struct Checkpoint160 {\n        uint96 _key;\n        uint160 _value;\n    }\n\n    /**\n     * @dev Pushes a (`key`, `value`) pair into a Trace160 so that it is stored as the checkpoint.\n     *\n     * Returns previous value and new value.\n     *\n     * IMPORTANT: Never accept `key` as a user input, since an arbitrary `type(uint96).max` key set will disable the\n     * library.\n     */\n    function push(\n        Trace160 storage self,\n        uint96 key,\n        uint160 value\n    ) internal returns (uint160 oldValue, uint160 newValue) {\n        return _insert(self._checkpoints, key, value);\n    }\n\n    /**\n     * @dev Returns the value in the first (oldest) checkpoint with key greater or equal than the search key, or zero if\n     * there is none.\n     */\n    function lowerLookup(Trace160 storage self, uint96 key) internal view returns (uint160) {\n        uint256 len = self._checkpoints.length;\n        uint256 pos = _lowerBinaryLookup(self._checkpoints, key, 0, len);\n        return pos == len ? 0 : _unsafeAccess(self._checkpoints, pos)._value;\n    }\n\n    /**\n     * @dev Returns the value in the last (most recent) checkpoint with key lower or equal than the search key, or zero\n     * if there is none.\n     */\n    function upperLookup(Trace160 storage self, uint96 key) internal view returns (uint160) {\n        uint256 len = self._checkpoints.length;\n        uint256 pos = _upperBinaryLookup(self._checkpoints, key, 0, len);\n        return pos == 0 ? 0 : _unsafeAccess(self._checkpoints, pos - 1)._value;\n    }\n\n    /**\n     * @dev Returns the value in the last (most recent) checkpoint with key lower or equal than the search key, or zero\n     * if there is none.\n     *\n     * NOTE: This is a variant of {upperLookup} that is optimized to find \"recent\" checkpoint (checkpoints with high\n     * keys).\n     */\n    function upperLookupRecent(Trace160 storage self, uint96 key) internal view returns (uint160) {\n        uint256 len = self._checkpoints.length;\n\n        uint256 low = 0;\n        uint256 high = len;\n\n        if (len > 5) {\n            uint256 mid = len - Math.sqrt(len);\n            if (key < _unsafeAccess(self._checkpoints, mid)._key) {\n                high = mid;\n            } else {\n                low = mid + 1;\n            }\n        }\n\n        uint256 pos = _upperBinaryLookup(self._checkpoints, key, low, high);\n\n        return pos == 0 ? 0 : _unsafeAccess(self._checkpoints, pos - 1)._value;\n    }\n\n    /**\n     * @dev Returns the value in the most recent checkpoint, or zero if there are no checkpoints.\n     */\n    function latest(Trace160 storage self) internal view returns (uint160) {\n        uint256 pos = self._checkpoints.length;\n        return pos == 0 ? 0 : _unsafeAccess(self._checkpoints, pos - 1)._value;\n    }\n\n    /**\n     * @dev Returns whether there is a checkpoint in the structure (i.e. it is not empty), and if so the key and value\n     * in the most recent checkpoint.\n     */\n    function latestCheckpoint(Trace160 storage self) internal view returns (bool exists, uint96 _key, uint160 _value) {\n        uint256 pos = self._checkpoints.length;\n        if (pos == 0) {\n            return (false, 0, 0);\n        } else {\n            Checkpoint160 storage ckpt = _unsafeAccess(self._checkpoints, pos - 1);\n            return (true, ckpt._key, ckpt._value);\n        }\n    }\n\n    /**\n     * @dev Returns the number of checkpoints.\n     */\n    function length(Trace160 storage self) internal view returns (uint256) {\n        return self._checkpoints.length;\n    }\n\n    /**\n     * @dev Returns checkpoint at given position.\n     */\n    function at(Trace160 storage self, uint32 pos) internal view returns (Checkpoint160 memory) {\n        return self._checkpoints[pos];\n    }\n\n    /**\n     * @dev Pushes a (`key`, `value`) pair into an ordered list of checkpoints, either by inserting a new checkpoint,\n     * or by updating the last one.\n     */\n    function _insert(\n        Checkpoint160[] storage self,\n        uint96 key,\n        uint160 value\n    ) private returns (uint160 oldValue, uint160 newValue) {\n        uint256 pos = self.length;\n\n        if (pos > 0) {\n            Checkpoint160 storage last = _unsafeAccess(self, pos - 1);\n            uint96 lastKey = last._key;\n            uint160 lastValue = last._value;\n\n            // Checkpoint keys must be non-decreasing.\n            if (lastKey > key) {\n                revert CheckpointUnorderedInsertion();\n            }\n\n            // Update or push new checkpoint\n            if (lastKey == key) {\n                last._value = value;\n            } else {\n                self.push(Checkpoint160({_key: key, _value: value}));\n            }\n            return (lastValue, value);\n        } else {\n            self.push(Checkpoint160({_key: key, _value: value}));\n            return (0, value);\n        }\n    }\n\n    /**\n     * @dev Return the index of the first (oldest) checkpoint with key strictly bigger than the search key, or `high`\n     * if there is none. `low` and `high` define a section where to do the search, with inclusive `low` and exclusive\n     * `high`.\n     *\n     * WARNING: `high` should not be greater than the array's length.\n     */\n    function _upperBinaryLookup(\n        Checkpoint160[] storage self,\n        uint96 key,\n        uint256 low,\n        uint256 high\n    ) private view returns (uint256) {\n        while (low < high) {\n            uint256 mid = Math.average(low, high);\n            if (_unsafeAccess(self, mid)._key > key) {\n                high = mid;\n            } else {\n                low = mid + 1;\n            }\n        }\n        return high;\n    }\n\n    /**\n     * @dev Return the index of the first (oldest) checkpoint with key greater or equal than the search key, or `high`\n     * if there is none. `low` and `high` define a section where to do the search, with inclusive `low` and exclusive\n     * `high`.\n     *\n     * WARNING: `high` should not be greater than the array's length.\n     */\n    function _lowerBinaryLookup(\n        Checkpoint160[] storage self,\n        uint96 key,\n        uint256 low,\n        uint256 high\n    ) private view returns (uint256) {\n        while (low < high) {\n            uint256 mid = Math.average(low, high);\n            if (_unsafeAccess(self, mid)._key < key) {\n                low = mid + 1;\n            } else {\n                high = mid;\n            }\n        }\n        return high;\n    }\n\n    /**\n     * @dev Access an element of the array without performing bounds check. The position is assumed to be within bounds.\n     */\n    function _unsafeAccess(\n        Checkpoint160[] storage self,\n        uint256 pos\n    ) private pure returns (Checkpoint160 storage result) {\n        assembly {\n            mstore(0x00, self.slot)\n            result.slot := add(keccak256(0x00, 0x20), pos)\n        }\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/LayerZero-v2/packages/layerzero-v2/evm/protocol/contracts/interfaces/IMessagingChannel.sol","source_code":"// SPDX-License-Identifier: MIT\n\npragma solidity >=0.8.0;\n\ninterface IMessagingChannel {\n    event InboundNonceSkipped(uint32 srcEid, bytes32 sender, address receiver, uint64 nonce);\n    event PacketNilified(uint32 srcEid, bytes32 sender, address receiver, uint64 nonce, bytes32 payloadHash);\n    event PacketBurnt(uint32 srcEid, bytes32 sender, address receiver, uint64 nonce, bytes32 payloadHash);\n\n    function eid() external view returns (uint32);\n\n    // this is an emergency function if a message cannot be verified for some reasons\n    // required to provide _nextNonce to avoid race condition\n    function skip(address _oapp, uint32 _srcEid, bytes32 _sender, uint64 _nonce) external;\n\n    function nilify(address _oapp, uint32 _srcEid, bytes32 _sender, uint64 _nonce, bytes32 _payloadHash) external;\n\n    function burn(address _oapp, uint32 _srcEid, bytes32 _sender, uint64 _nonce, bytes32 _payloadHash) external;\n\n    function nextGuid(address _sender, uint32 _dstEid, bytes32 _receiver) external view returns (bytes32);\n\n    function inboundNonce(address _receiver, uint32 _srcEid, bytes32 _sender) external view returns (uint64);\n\n    function outboundNonce(address _sender, uint32 _dstEid, bytes32 _receiver) external view returns (uint64);\n\n    function inboundPayloadHash(\n        address _receiver,\n        uint32 _srcEid,\n        bytes32 _sender,\n        uint64 _nonce\n    ) external view returns (bytes32);\n\n    function lazyInboundNonce(address _receiver, uint32 _srcEid, bytes32 _sender) external view returns (uint64);\n}\n"},{"file_path":"src/integrations/outland/portals/PortalBase.sol","source_code":"// SPDX-License-Identifier: MIT\npragma solidity 0.8.28;\n\nimport {EnumerableSet} from \"@openzeppelin/contracts/utils/structs/EnumerableSet.sol\";\n\nimport {CoreRoles} from \"@libraries/CoreRoles.sol\";\nimport {CoreControlled} from \"@core/CoreControlled.sol\";\nimport {OutlandMsgCodec} from \"@integrations/outland/OutlandMsgCodec.sol\";\nimport {IOutlandPortal, IOutlandConnector} from \"@interfaces/IOutlandPortal.sol\";\n\n/// @title PortalBase\n/// @notice Base contract for portal contracts with common connector logic\n/// @dev Provides shared functionality for managing multiple connectors\nabstract contract PortalBase is CoreControlled, IOutlandPortal {\n    using EnumerableSet for EnumerableSet.AddressSet;\n\n    /// @notice The chain ID where this portal operates\n    uint256 public chainId;\n\n    /// @notice Set of authorized addresses that can send cross-chain messages\n    EnumerableSet.AddressSet internal connectors;\n\n    /// @notice Outbound nonce per destination chain, incremented on every sent message\n    mapping(uint256 targetChainId => uint256 nonce) public outboundNonce;\n\n    /// @notice Queued inbound message hashes keyed by source chain and message nonce\n    mapping(uint256 sourceChainId => mapping(uint256 nonce => bytes32 dataHash)) internal inboundHashes;\n\n    /// @notice Next inbound nonce to process per source chain (0 means the next expected nonce is 1)\n    mapping(uint256 sourceChainId => uint256 nonce) public inboundNonce;\n\n    /// @notice When true, user-initiated bridging is disabled independently of the global pause\n    bool public bridgePaused;\n\n    error AlreadyInitialized();\n    error InvalidBridgedToken(address _token);\n    error InvalidAsset(address _asset);\n    error InvalidVault(address _vault);\n    error InvalidAmount(uint256 _amount);\n    error InvalidSender(address _sender);\n    error InvalidChainId(uint256 _chainId, uint256 _decodedChainId);\n    error InvalidReceiver(address _receiver);\n    error ChainNotSupported(uint256 _chainId);\n    error InvalidNonce(uint256 _nonce);\n    error DuplicateInboundMessage(uint256 _sourceChainId, uint256 _nonce);\n    error InvalidInboundNonce(uint256 _nonce, uint256 _expectedNonce);\n    error InboundMessageNotQueued(uint256 _sourceChainId, uint256 _nonce);\n    error InvalidQueuedData();\n    error InvalidInboundNonceTarget(uint256 _newNonce);\n    error BridgeOperationsPaused();\n\n    error ZeroAddress();\n    error EntryNotFound(address _entry);\n    error DuplicateEntry(address _entry);\n\n    event TokensSent(\n        uint256 indexed timestamp, uint256 chainId, uint256 nonce, address token, uint256 amount, address sender\n    );\n    event TokensReceived(uint256 indexed timestamp, uint256 chainId, address token, uint256 amount, address receiver);\n    event BridgedTokensSent(\n        uint256 indexed timestamp, uint256 chainId, uint256 nonce, address token, uint256 amount, address sender\n    );\n    event BridgedTokensReceived(\n        uint256 indexed timestamp, uint256 chainId, address token, uint256 amount, address receiver\n    );\n\n    event ConnectorAdded(uint256 indexed timestamp, address connector);\n    event ConnectorRemoved(uint256 indexed timestamp, address connector);\n    event MessageQueued(uint256 indexed sourceChainId, uint256 indexed nonce, address indexed connector, bytes data);\n    event MessageProcessed(uint256 indexed sourceChainId, uint256 indexed nonce);\n    event InboundNonceSet(uint256 indexed sourceChainId, uint256 oldNonce, uint256 newNonce);\n    event OutboundNonceSet(uint256 indexed targetChainId, uint256 oldNonce, uint256 newNonce);\n    event BridgePaused(uint256 indexed timestamp);\n    event BridgeUnpaused(uint256 indexed timestamp);\n\n    uint256[100] private __gap;\n\n    /// @notice Initializes the PortalBase contract\n    /// @param _core Address of the Core contract for role management\n    /// @param _chainId Chain ID where this portal operates\n    constructor(address _core, uint256 _chainId) CoreControlled(_core) {\n        chainId = _chainId;\n    }\n\n    modifier whenNotBridgePaused() {\n        require(!bridgePaused, BridgeOperationsPaused());\n        _;\n    }\n\n    /// @notice Disables user-initiated bridging while leaving other portal operations available\n    function pauseBridge() external onlyCoreRole(CoreRoles.PAUSE) {\n        bridgePaused = true;\n        emit BridgePaused(block.timestamp);\n    }\n\n    /// @notice Re-enables user-initiated bridging\n    function unpauseBridge() external onlyCoreRole(CoreRoles.UNPAUSE) {\n        bridgePaused = false;\n        emit BridgeUnpaused(block.timestamp);\n    }\n\n    /// @notice Returns the queued message hash for a source chain and nonce, if any\n    function getInboundMessageHash(uint256 _sourceChainId, uint256 _nonce) external view returns (bytes32) {\n        return inboundHashes[_sourceChainId][_nonce];\n    }\n\n    /// @notice Returns the next inbound nonce expected for processing on a source chain\n    function getExpectedInboundNonce(uint256 _sourceChainId) public view returns (uint256) {\n        uint256 nextNonce = inboundNonce[_sourceChainId];\n        return nextNonce == 0 ? 1 : nextNonce;\n    }\n\n    /// @inheritdoc IOutlandPortal\n    function receiveMessage(uint256 _chainId, bytes calldata _data) external {\n        require(isConnector(msg.sender), InvalidSender(msg.sender));\n        _validateInboundEnvelope(_chainId, _data);\n\n        uint256 nonce = OutlandMsgCodec.getNonce(_data);\n        require(nonce > 0, InvalidNonce(nonce));\n        require(inboundHashes[_chainId][nonce] == bytes32(0), DuplicateInboundMessage(_chainId, nonce));\n\n        inboundHashes[_chainId][nonce] = keccak256(_data);\n        emit MessageQueued(_chainId, nonce, msg.sender, _data);\n    }\n\n    /// @inheritdoc IOutlandPortal\n    function processMessage(uint256 _chainId, bytes calldata _data, address _connector)\n        external\n        whenNotPaused\n        onlyCoreRole(CoreRoles.OUTLAND_KEEPER)\n    {\n        uint256 nonce = OutlandMsgCodec.getNonce(_data);\n        uint256 expectedNonce = getExpectedInboundNonce(_chainId);\n        require(nonce == expectedNonce, InvalidInboundNonce(nonce, expectedNonce));\n\n        bytes32 dataHash = inboundHashes[_chainId][nonce];\n        require(dataHash != bytes32(0), InboundMessageNotQueued(_chainId, nonce));\n        require(keccak256(_data) == dataHash, InvalidQueuedData());\n\n        _executeInboundMessage(_chainId, _connector, _data);\n\n        delete inboundHashes[_chainId][nonce];\n        inboundNonce[_chainId] = nonce + 1;\n        emit MessageProcessed(_chainId, nonce);\n    }\n\n    /// @notice Sets the next inbound nonce to process for a source chain\n    function setInboundNonce(uint256 _sourceChainId, uint256 _newNonce)\n        external\n        onlyCoreRole(CoreRoles.PROTOCOL_PARAMETERS)\n    {\n        require(_newNonce > 0, InvalidInboundNonceTarget(_newNonce));\n\n        uint256 oldNonce = inboundNonce[_sourceChainId];\n        inboundNonce[_sourceChainId] = _newNonce;\n        emit InboundNonceSet(_sourceChainId, oldNonce, _newNonce);\n    }\n\n    /// @notice Sets the last assigned outbound nonce for a destination chain; the next send uses `_newNonce + 1`\n    function setOutboundNonce(uint256 _targetChainId, uint256 _newNonce)\n        external\n        onlyCoreRole(CoreRoles.PROTOCOL_PARAMETERS)\n    {\n        uint256 oldNonce = outboundNonce[_targetChainId];\n        outboundNonce[_targetChainId] = _newNonce;\n        emit OutboundNonceSet(_targetChainId, oldNonce, _newNonce);\n    }\n\n    /// @dev Assigns and returns the next outbound nonce for a destination chain\n    function _nextOutboundNonce(uint256 _targetChainId) internal returns (uint256 nonce) {\n        nonce = ++outboundNonce[_targetChainId];\n    }\n\n    /// @dev Portal-specific validation of the inbound message envelope\n    function _validateInboundEnvelope(uint256 _chainId, bytes calldata _data) internal view virtual {\n        uint256 senderChainId = OutlandMsgCodec.getChainId(_data);\n        require(_chainId == senderChainId, InvalidChainId(_chainId, senderChainId));\n    }\n\n    /// @dev Portal-specific execution of a validated inbound message\n    function _executeInboundMessage(uint256 _chainId, address _connector, bytes calldata _data) internal virtual;\n\n    function getSendTokensFee(uint256 _targetChainId, address _token, uint256 _amount, address payable _connector)\n        external\n        view\n        returns (uint256)\n    {\n        TransferPayload memory payload = TransferPayload({\n            selector: OutlandMsgCodec.TRANSFER, chainId: chainId, nonce: 0, assetToken: _token, amount: _amount\n        });\n\n        return IOutlandConnector(_connector).getSendTokensFee(_targetChainId, _token, _amount, abi.encode(payload));\n    }\n\n    /// @notice Quotes the cross-chain message fee for iUSD / siUSD bridging (both directions)\n    function getBridgeMessageFee(uint256 _targetChainId, address payable _connector) external view returns (uint256) {\n        return IOutlandConnector(_connector)\n            .getMessageFee(\n                _targetChainId,\n                abi.encode(\n                    TokenBridgePayload({\n                    selector: OutlandMsgCodec.TOKEN_BRIDGE,\n                    chainId: chainId,\n                    nonce: 0,\n                    token: address(0),\n                    amount: 0,\n                    recipient: address(0),\n                    destinationChainId: _targetChainId,\n                    totalAssetsValue: 0,\n                    receiptTokenTotalSupply: 0,\n                    stakedTokenTotalSupply: 0\n                })\n                )\n            );\n    }\n\n    function getMessageFee(uint256 _targetChainId, uint256 _amount, address payable _connector)\n        external\n        view\n        returns (uint256)\n    {\n        AssetsUpdatePayload memory payload = AssetsUpdatePayload({\n            selector: OutlandMsgCodec.MESSAGE,\n            chainId: chainId,\n            nonce: 0,\n            totalAssetsValue: _amount,\n            receiptTokenTotalSupply: 0,\n            stakedTokenTotalSupply: 0\n        });\n\n        return IOutlandConnector(_connector).getMessageFee(_targetChainId, abi.encode(payload));\n    }\n\n    /// @notice Add a new authorized connector\n    /// @param _connector The address of the connector to add\n    function addConnector(address _connector) external onlyCoreRole(CoreRoles.PROTOCOL_PARAMETERS) {\n        require(_connector != address(0), ZeroAddress());\n        require(connectors.add(_connector), DuplicateEntry(_connector));\n        emit ConnectorAdded(block.timestamp, _connector);\n    }\n\n    /// @notice Remove an authorized connector\n    /// @param _connector The address of the connector to remove\n    function removeConnector(address _connector) external onlyCoreRole(CoreRoles.PROTOCOL_PARAMETERS) {\n        require(connectors.remove(_connector), EntryNotFound(_connector));\n        emit ConnectorRemoved(block.timestamp, _connector);\n    }\n\n    /// @notice Check if an address is an authorized connector\n    function isConnector(address _connector) public view returns (bool) {\n        return connectors.contains(_connector);\n    }\n\n    /// @notice Get all authorized connectors\n    function getConnectors() public view returns (address[] memory) {\n        return connectors.values();\n    }\n\n    /// @notice Get the number of authorized connectors\n    function getConnectorsCount() public view returns (uint256) {\n        return connectors.length();\n    }\n\n    /// @notice Bridges iUSD or siUSD to another chain with an assets report payload\n    function bridge(\n        uint256 _targetChainId,\n        address _token,\n        uint256 _amount,\n        address _recipient,\n        address payable _connector\n    ) external payable whenNotPaused whenNotBridgePaused onlyCoreRole(CoreRoles.BRIDGE_INITIATOR) {\n        require(_amount > 0, InvalidAmount(_amount));\n        require(_recipient != address(0), ZeroAddress());\n        require(isConnector(_connector), InvalidSender(_connector));\n\n        _handleSendTokenBridge(_targetChainId, _token, _amount, _recipient, _connector);\n    }\n\n    /// @dev Hub and outpost implementations burn local tokens, snapshot accounting, and send a bridge message\n    /// @dev must emit BridgedTokensSent event\n    function _handleSendTokenBridge(\n        uint256 _targetChainId,\n        address _token,\n        uint256 _amount,\n        address _recipient,\n        address payable _connector\n    ) internal virtual;\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":"src/interfaces/IOutlandPortal.sol","source_code":"// SPDX-License-Identifier: MIT\npragma solidity 0.8.28;\n\ninterface IOutlandPortal {\n    struct TransferPayload {\n        bytes1 selector;\n        uint256 chainId;\n        uint256 nonce;\n        address assetToken;\n        uint256 amount;\n    }\n\n    struct AssetsUpdatePayload {\n        bytes1 selector;\n        uint256 chainId;\n        uint256 nonce;\n        uint256 totalAssetsValue;\n        uint256 receiptTokenTotalSupply;\n        uint256 stakedTokenTotalSupply;\n    }\n\n    struct KeyValuePayload {\n        bytes1 selector;\n        uint256 chainId;\n        uint256 nonce;\n        bytes32 key;\n        bytes32 value;\n        uint256 sentAt;\n    }\n\n    struct TokenBridgePayload {\n        bytes1 selector;\n        uint256 chainId;\n        uint256 nonce;\n        address token;\n        uint256 amount;\n        address recipient;\n        uint256 destinationChainId;\n        uint256 totalAssetsValue;\n        uint256 receiptTokenTotalSupply;\n        uint256 stakedTokenTotalSupply;\n    }\n\n    function receiveMessage(uint256 _chainId, bytes calldata _data) external;\n\n    function processMessage(uint256 _chainId, bytes calldata _data, address _connector) external;\n}\n\ninterface IOutlandConnector {\n    event TokensSent(\n        uint256 indexed timestamp,\n        bytes32 messageId,\n        uint256 chainId,\n        address assetToken,\n        uint256 amount,\n        uint256 fee,\n        address receiver,\n        bytes messageData\n    );\n\n    event MessageSent(\n        uint256 indexed timestamp, bytes32 messageId, uint256 chainId, uint256 fee, address receiver, bytes messageData\n    );\n\n    function getMessageFee(uint256 _chainId, bytes calldata _data) external view returns (uint256);\n\n    function getSendTokensFee(uint256 _chainId, address _assetToken, uint256 _amount, bytes calldata _data)\n        external\n        view\n        returns (uint256);\n\n    function sendMessage(uint256 _chainId, bytes calldata _data) external payable;\n\n    function sendTokens(uint256 _chainId, address _assetToken, uint256 _amount, bytes calldata _data) external payable;\n\n    function pullAssets(address _assetToken, uint256 _amount) external;\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/integrations/MultiAssetFarmV2.sol","source_code":"// SPDX-License-Identifier: MIT\npragma solidity 0.8.28;\n\nimport {ERC20} from \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\nimport {SafeERC20} from \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\nimport {EnumerableSet} from \"@openzeppelin/contracts/utils/structs/EnumerableSet.sol\";\nimport {FixedPointMathLib} from \"@solmate/src/utils/FixedPointMathLib.sol\";\n\nimport {CoreRoles} from \"@libraries/CoreRoles.sol\";\nimport {Accounting} from \"@finance/Accounting.sol\";\nimport {Farm} from \"@integrations/Farm.sol\";\n\n/// @title MultiAssetFarmV2\n/// @notice InfiniFi Farm that can hold multiple asset tokens.\n/// @dev This abstract contract extends the base Farm contract to support multiple asset tokens.\n/// @dev It provides functionality to manage supported assets, convert between them using oracle prices,\n/// @dev and handle deposits/withdrawals of various asset types.\nabstract contract MultiAssetFarmV2 is Farm {\n    using SafeERC20 for ERC20;\n    using FixedPointMathLib for uint256;\n    using EnumerableSet for EnumerableSet.AddressSet;\n\n    /// @notice Emitted when a new asset is enabled for the farm\n    /// @param timestamp The block timestamp when the asset was enabled\n    /// @param asset The address of the enabled asset token\n    event AssetEnabled(uint256 indexed timestamp, address asset);\n\n    /// @notice Emitted when an asset is disabled for the farm\n    /// @param timestamp The block timestamp when the asset was disabled\n    /// @param asset The address of the disabled asset token\n    event AssetDisabled(uint256 indexed timestamp, address asset);\n\n    /// @notice Thrown when an invalid array length is provided\n    error InvalidLength();\n\n    /// @notice Thrown when an invalid farm address is provided\n    /// @param farm The invalid farm address\n    error InvalidFarm(address farm);\n\n    /// @notice Thrown when an invalid asset address is provided\n    /// @param asset The invalid asset address\n    error InvalidAsset(address asset);\n\n    /// @notice Thrown when an asset doesn't have a valid oracle\n    /// @param _asset The asset address without a valid oracle\n    error InvalidOracle(address _asset);\n\n    /// @notice Thrown when trying to disable an asset with non-zero balance\n    /// @param _asset The asset address with non-zero balance\n    /// @param _balance The current balance of the asset\n    error InvalidBalance(address _asset, uint256 _balance);\n\n    /// @notice Base amount of assets required to prevent removal without decimals\n    uint256 public constant ASSET_REMOVAL_THRESHOLD = 1;\n\n    /// @notice Reference to the accounting contract used for price oracles and asset management\n    address public immutable accounting;\n\n    /// @notice Set of supported asset tokens (excluding the primary assetToken)\n    EnumerableSet.AddressSet private _assetTokens;\n\n    /// @notice Constructor for MultiAssetFarmV2\n    /// @param _core The address of the core contract\n    /// @param _assetToken The primary asset token for this farm\n    /// @param _accounting The address of the accounting contract\n    constructor(address _core, address _assetToken, address _accounting) Farm(_core, _assetToken) {\n        accounting = _accounting;\n    }\n\n    /// @notice Returns the list of asset tokens that the farm can hold\n    /// @dev MUST include the assetToken of the farm\n    /// @dev MUST only include tokens that can be freely airdropped to the farm\n    /// while being accounted properly in the assets() function\n    /// @return Array of supported asset token addresses\n    function assetTokens() public view virtual returns (address[] memory) {\n        return _assetTokens.values();\n    }\n\n    /// @notice Checks if the farm can hold the given asset token\n    /// @param _asset The asset token address to check\n    /// @return True if the asset is supported, false otherwise\n    function isAssetSupported(address _asset) public view virtual returns (bool) {\n        return _asset == assetToken || (_assetTokens.contains(_asset) && _hasOracle(_asset));\n    }\n\n    /// @notice Returns the total value of all assets held by the farm in terms of the primary assetToken\n    /// @dev Note that there may be conversion fees between supported assets and the assetToken.\n    /// This is not reflected in the amount returned by assets()\n    /// @return Total value of all assets in terms of the primary assetToken\n    function assets() public view virtual override returns (uint256) {\n        uint256 assetTokenBalance = ERC20(assetToken).balanceOf(address(this));\n        uint256 assetTokenPrice = Accounting(accounting).price(assetToken);\n\n        address[] memory supportedAssets = assetTokens();\n        for (uint256 i = 0; i < supportedAssets.length; i++) {\n            if (supportedAssets[i] == assetToken) continue;\n            uint256 balance = ERC20(supportedAssets[i]).balanceOf(address(this));\n            if (balance == 0) continue; // do not read price if the balance is 0 to save gas\n            uint256 price = Accounting(accounting).price(supportedAssets[i]);\n            assetTokenBalance += balance.mulDivDown(price, assetTokenPrice);\n        }\n\n        return assetTokenBalance;\n    }\n\n    /// @notice Returns the current liquidity of the farm (held reference assetToken)\n    /// @return The balance of the primary assetToken held by the farm\n    function liquidity() public view override returns (uint256) {\n        return ERC20(assetToken).balanceOf(address(this));\n    }\n\n    /// @notice Converts a number of tokens to another token based on oracle rates\n    /// @param _tokenIn The input token address\n    /// @param _tokenOut The output token address\n    /// @param _amountIn The amount of input tokens to convert\n    /// @return The equivalent amount of output tokens\n    function convert(address _tokenIn, address _tokenOut, uint256 _amountIn) public view returns (uint256) {\n        if (_tokenIn == _tokenOut) return _amountIn;\n        uint256 tokenInPrice = Accounting(accounting).price(_tokenIn);\n        uint256 tokenOutPrice = Accounting(accounting).price(_tokenOut);\n        return _amountIn.mulDivDown(tokenInPrice, tokenOutPrice);\n    }\n\n    /// @notice Enables a set of assets that will be reported by this farm\n    /// @param _assetList Array of asset token addresses to enable\n    function enableAssets(address[] calldata _assetList) external onlyCoreRole(CoreRoles.PROTOCOL_PARAMETERS) {\n        require(_assetList.length > 0, InvalidLength());\n        for (uint256 i = 0; i < _assetList.length; i++) {\n            address _asset = _assetList[i];\n            require(!isAssetSupported(_asset), InvalidAsset(_asset));\n            _enableAsset(_asset);\n        }\n    }\n\n    /// @notice Disables a set of assets that are no longer required by this farm\n    /// @param _assetList Array of asset token addresses to disable\n    function disableAssets(address[] calldata _assetList) external onlyCoreRole(CoreRoles.PROTOCOL_PARAMETERS) {\n        require(_assetList.length > 0, InvalidLength());\n        for (uint256 i = 0; i < _assetList.length; i++) {\n            _disableAsset(_assetList[i]);\n        }\n    }\n\n    /// @dev Deposit does nothing, assetTokens are just held on this farm\n    /// @dev There should be other functions to do conversions between the assetTokens or deploying\n    /// the funds to a productive yield source\n    /// @param _amount The amount to deposit (unused in this implementation)\n    function _deposit(uint256 _amount) internal view virtual override {}\n\n    /// @notice Deposits assets into the farm (used for airdrops)\n    /// @dev Note that in airdrops we do not know the amount of assets before the deposit,\n    /// therefore we emit an event that contains twice the assets after the deposit\n    function deposit() external virtual override onlyCoreRole(CoreRoles.FARM_MANAGER) whenNotPaused {\n        uint256 currentAssets = assets();\n        if (currentAssets > cap) {\n            revert CapExceeded(currentAssets, cap);\n        }\n\n        _deposit(0);\n\n        /// @dev note that in airdrops we do not know the amount of assets before the deposit,\n        /// therefore we emit an event that contains twice the assets after the deposit.\n        emit AssetsUpdated(block.timestamp, currentAssets, currentAssets);\n    }\n\n    /// @dev Withdrawal can only handle the reference assetToken (i.e. the liquidity())\n    /// @dev There should be other functions to do conversions between the assetTokens or pulling\n    /// the funds out of a productive yield source\n    /// @param _amount The amount of assetToken to withdraw\n    /// @param _to The address to send the withdrawn tokens to\n    function _withdraw(uint256 _amount, address _to) internal virtual override {\n        ERC20(assetToken).safeTransfer(_to, _amount);\n    }\n\n    /// @notice Withdraws the reference assetToken from the farm\n    /// @param amount The amount of assetToken to withdraw\n    /// @param to The address to send the withdrawn tokens to\n    function withdraw(uint256 amount, address to)\n        external\n        virtual\n        override\n        onlyCoreRole(CoreRoles.FARM_MANAGER)\n        whenNotPaused\n    {\n        uint256 assetsBefore = assets();\n        _withdraw(amount, to);\n\n        emit AssetsUpdated(block.timestamp, assetsBefore, assetsBefore - amount);\n    }\n\n    /// @notice Withdraws any supported secondary asset tokens from the farm\n    /// @param _asset The address of the asset token to withdraw\n    /// @param _amount The amount of the asset to withdraw\n    /// @param _to The address to send the withdrawn tokens to\n    function withdrawSecondaryAsset(address _asset, uint256 _amount, address _to)\n        external\n        virtual\n        onlyCoreRole(CoreRoles.FARM_MANAGER)\n        whenNotPaused\n    {\n        require(isAssetSupported(_asset) && _asset != assetToken, InvalidAsset(_asset));\n\n        uint256 assetsBefore = assets();\n        ERC20(_asset).safeTransfer(_to, _amount);\n        uint256 assetsAfter = assets();\n\n        emit AssetsUpdated(block.timestamp, assetsBefore, assetsAfter);\n    }\n\n    /// @notice Internal function to enable a new asset for the farm\n    /// @param _asset The address of the asset token to enable\n    /// @dev Can add if already added but doesn't hurt as it is a set\n    function _enableAsset(address _asset) internal {\n        require(_hasOracle(_asset), InvalidOracle(_asset));\n        // Oracle has to exist in order for new assets to be added\n        _assetTokens.add(_asset);\n        emit AssetEnabled(block.timestamp, _asset);\n    }\n\n    /// @dev Internal function to disable an asset for the farm\n    /// @param _asset The address of the asset token to disable\n    function _disableAsset(address _asset) internal {\n        require(_asset != assetToken, InvalidAsset(_asset));\n        require(isAssetSupported(_asset), InvalidAsset(_asset));\n\n        // do not allow removal of nonzero balance assets\n        uint256 balance = ERC20(_asset).balanceOf(address(this));\n        uint256 decimals = ERC20(_asset).decimals();\n        require(balance <= ASSET_REMOVAL_THRESHOLD * 10 ** decimals, InvalidBalance(_asset, balance));\n\n        _assetTokens.remove(_asset);\n        emit AssetDisabled(block.timestamp, _asset);\n    }\n\n    function _hasOracle(address _asset) internal view returns (bool) {\n        try Accounting(accounting).price(_asset) returns (uint256 _price) {\n            return _price > 0;\n        } catch {\n            return false;\n        }\n    }\n}\n"},{"file_path":"lib/LayerZero-v2/packages/layerzero-v2/evm/oapp/contracts/precrime/interfaces/IOAppPreCrimeSimulator.sol","source_code":"// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.20;\n\n// @dev Import the Origin so it's exposed to OAppPreCrimeSimulator implementers.\n// solhint-disable-next-line no-unused-import\nimport { InboundPacket, Origin } from \"../libs/Packet.sol\";\n\n/**\n * @title IOAppPreCrimeSimulator Interface\n * @dev Interface for the preCrime simulation functionality in an OApp.\n */\ninterface IOAppPreCrimeSimulator {\n    // @dev simulation result used in PreCrime implementation\n    error SimulationResult(bytes result);\n    error OnlySelf();\n\n    /**\n     * @dev Emitted when the preCrime contract address is set.\n     * @param preCrimeAddress The address of the preCrime contract.\n     */\n    event PreCrimeSet(address preCrimeAddress);\n\n    /**\n     * @dev Retrieves the address of the preCrime contract implementation.\n     * @return The address of the preCrime contract.\n     */\n    function preCrime() external view returns (address);\n\n    /**\n     * @dev Retrieves the address of the OApp contract.\n     * @return The address of the OApp contract.\n     */\n    function oApp() external view returns (address);\n\n    /**\n     * @dev Sets the preCrime contract address.\n     * @param _preCrime The address of the preCrime contract.\n     */\n    function setPreCrime(address _preCrime) external;\n\n    /**\n     * @dev Mocks receiving a packet, then reverts with a series of data to infer the state/result.\n     * @param _packets An array of LayerZero InboundPacket objects representing received packets.\n     */\n    function lzReceiveAndRevert(InboundPacket[] calldata _packets) external payable;\n\n    /**\n     * @dev checks if the specified peer is considered 'trusted' by the OApp.\n     * @param _eid The endpoint Id to check.\n     * @param _peer The peer to check.\n     * @return Whether the peer passed is considered 'trusted' by the OApp.\n     */\n    function isPeer(uint32 _eid, bytes32 _peer) external view returns (bool);\n}\n"},{"file_path":"lib/openzeppelin-contracts/contracts/utils/structs/EnumerableMap.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.5.0) (utils/structs/EnumerableMap.sol)\n// This file was procedurally generated from scripts/generate/templates/EnumerableMap.js.\n\npragma solidity ^0.8.24;\n\nimport {EnumerableSet} from \"./EnumerableSet.sol\";\n\n/**\n * @dev Library for managing an enumerable variant of Solidity's\n * https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`]\n * type.\n *\n * Maps have the following properties:\n *\n * - Entries are added, removed, and checked for existence in constant time\n * (O(1)).\n * - Entries are enumerated in O(n). No guarantees are made on the ordering.\n * - Map can be cleared (all entries removed) in O(n).\n *\n * ```solidity\n * contract Example {\n *     // Add the library methods\n *     using EnumerableMap for EnumerableMap.UintToAddressMap;\n *\n *     // Declare a set state variable\n *     EnumerableMap.UintToAddressMap private myMap;\n * }\n * ```\n *\n * The following map types are supported:\n *\n * - `uint256 -> address` (`UintToAddressMap`) since v3.0.0\n * - `address -> uint256` (`AddressToUintMap`) since v4.6.0\n * - `bytes32 -> bytes32` (`Bytes32ToBytes32Map`) since v4.6.0\n * - `uint256 -> uint256` (`UintToUintMap`) since v4.7.0\n * - `bytes32 -> uint256` (`Bytes32ToUintMap`) since v4.7.0\n * - `uint256 -> bytes32` (`UintToBytes32Map`) since v5.1.0\n * - `address -> address` (`AddressToAddressMap`) since v5.1.0\n * - `address -> bytes32` (`AddressToBytes32Map`) since v5.1.0\n * - `bytes32 -> address` (`Bytes32ToAddressMap`) since v5.1.0\n * - `bytes -> bytes` (`BytesToBytesMap`) since v5.4.0\n * - `bytes4 -> address` (`Bytes4ToAddressMap`) 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 EnumerableMap, you can either remove all elements one by one or create a fresh instance using an\n * array of EnumerableMap.\n * ====\n */\nlibrary EnumerableMap {\n    using EnumerableSet for *;\n\n    // To implement this library for multiple types with as little code repetition as possible, we write it in\n    // terms of a generic Map type with bytes32 keys and values. The Map implementation uses private functions,\n    // and user-facing implementations such as `UintToAddressMap` are just wrappers around the underlying Map.\n    // This means that we can only create new EnumerableMaps for types that fit in bytes32.\n\n    /**\n     * @dev Query for a nonexistent map key.\n     */\n    error EnumerableMapNonexistentKey(bytes32 key);\n\n    struct Bytes32ToBytes32Map {\n        // Storage of keys\n        EnumerableSet.Bytes32Set _keys;\n        mapping(bytes32 key => bytes32) _values;\n    }\n\n    /**\n     * @dev Adds a key-value pair to a map, or updates the value for an existing\n     * key. O(1).\n     *\n     * Returns true if the key was added to the map, that is if it was not\n     * already present.\n     */\n    function set(Bytes32ToBytes32Map storage map, bytes32 key, bytes32 value) internal returns (bool) {\n        map._values[key] = value;\n        return map._keys.add(key);\n    }\n\n    /**\n     * @dev Removes a key-value pair from a map. O(1).\n     *\n     * Returns true if the key was removed from the map, that is if it was present.\n     */\n    function remove(Bytes32ToBytes32Map storage map, bytes32 key) internal returns (bool) {\n        delete map._values[key];\n        return map._keys.remove(key);\n    }\n\n    /**\n     * @dev Removes all the entries from a map. 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 map grows to the point where clearing it consumes too much gas to fit in a block.\n     */\n    function clear(Bytes32ToBytes32Map storage map) internal {\n        uint256 len = length(map);\n        for (uint256 i = 0; i < len; ++i) {\n            delete map._values[map._keys.at(i)];\n        }\n        map._keys.clear();\n    }\n\n    /**\n     * @dev Returns true if the key is in the map. O(1).\n     */\n    function contains(Bytes32ToBytes32Map storage map, bytes32 key) internal view returns (bool) {\n        return map._keys.contains(key);\n    }\n\n    /**\n     * @dev Returns the number of key-value pairs in the map. O(1).\n     */\n    function length(Bytes32ToBytes32Map storage map) internal view returns (uint256) {\n        return map._keys.length();\n    }\n\n    /**\n     * @dev Returns the key-value pair stored at position `index` in the map. O(1).\n     *\n     * Note that there are no guarantees on the ordering of entries inside the\n     * array, and it may change when more entries are added or removed.\n     *\n     * Requirements:\n     *\n     * - `index` must be strictly less than {length}.\n     */\n    function at(Bytes32ToBytes32Map storage map, uint256 index) internal view returns (bytes32 key, bytes32 value) {\n        bytes32 atKey = map._keys.at(index);\n        return (atKey, map._values[atKey]);\n    }\n\n    /**\n     * @dev Tries to return the value associated with `key`. O(1).\n     * Does not revert if `key` is not in the map.\n     */\n    function tryGet(Bytes32ToBytes32Map storage map, bytes32 key) internal view returns (bool exists, bytes32 value) {\n        bytes32 val = map._values[key];\n        if (val == bytes32(0)) {\n            return (contains(map, key), bytes32(0));\n        } else {\n            return (true, val);\n        }\n    }\n\n    /**\n     * @dev Returns the value associated with `key`. O(1).\n     *\n     * Requirements:\n     *\n     * - `key` must be in the map.\n     */\n    function get(Bytes32ToBytes32Map storage map, bytes32 key) internal view returns (bytes32) {\n        bytes32 value = map._values[key];\n        if (value == 0 && !contains(map, key)) {\n            revert EnumerableMapNonexistentKey(key);\n        }\n        return value;\n    }\n\n    /**\n     * @dev Returns an array containing all the keys\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 map grows to a point where copying to memory consumes too much gas to fit in a block.\n     */\n    function keys(Bytes32ToBytes32Map storage map) internal view returns (bytes32[] memory) {\n        return map._keys.values();\n    }\n\n    /**\n     * @dev Returns an array containing a slice of the keys\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 map grows to a point where copying to memory consumes too much gas to fit in a block.\n     */\n    function keys(\n        Bytes32ToBytes32Map storage map,\n        uint256 start,\n        uint256 end\n    ) internal view returns (bytes32[] memory) {\n        return map._keys.values(start, end);\n    }\n\n    // UintToUintMap\n\n    struct UintToUintMap {\n        Bytes32ToBytes32Map _inner;\n    }\n\n    /**\n     * @dev Adds a key-value pair to a map, or updates the value for an existing\n     * key. O(1).\n     *\n     * Returns true if the key was added to the map, that is if it was not\n     * already present.\n     */\n    function set(UintToUintMap storage map, uint256 key, uint256 value) internal returns (bool) {\n        return set(map._inner, bytes32(key), bytes32(value));\n    }\n\n    /**\n     * @dev Removes a value from a map. O(1).\n     *\n     * Returns true if the key was removed from the map, that is if it was present.\n     */\n    function remove(UintToUintMap storage map, uint256 key) internal returns (bool) {\n        return remove(map._inner, bytes32(key));\n    }\n\n    /**\n     * @dev Removes all the entries from a map. O(n).\n     *\n     * WARNING: This function has an unbounded cost that scales with map size. Developers should keep in mind that\n     * using it may render the function uncallable if the map grows to the point where clearing it consumes too much\n     * gas to fit in a block.\n     */\n    function clear(UintToUintMap storage map) internal {\n        clear(map._inner);\n    }\n\n    /**\n     * @dev Returns true if the key is in the map. O(1).\n     */\n    function contains(UintToUintMap storage map, uint256 key) internal view returns (bool) {\n        return contains(map._inner, bytes32(key));\n    }\n\n    /**\n     * @dev Returns the number of elements in the map. O(1).\n     */\n    function length(UintToUintMap storage map) internal view returns (uint256) {\n        return length(map._inner);\n    }\n\n    /**\n     * @dev Returns the element stored at position `index` in the map. O(1).\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(UintToUintMap storage map, uint256 index) internal view returns (uint256 key, uint256 value) {\n        (bytes32 atKey, bytes32 val) = at(map._inner, index);\n        return (uint256(atKey), uint256(val));\n    }\n\n    /**\n     * @dev Tries to return the value associated with `key`. O(1).\n     * Does not revert if `key` is not in the map.\n     */\n    function tryGet(UintToUintMap storage map, uint256 key) internal view returns (bool exists, uint256 value) {\n        (bool success, bytes32 val) = tryGet(map._inner, bytes32(key));\n        return (success, uint256(val));\n    }\n\n    /**\n     * @dev Returns the value associated with `key`. O(1).\n     *\n     * Requirements:\n     *\n     * - `key` must be in the map.\n     */\n    function get(UintToUintMap storage map, uint256 key) internal view returns (uint256) {\n        return uint256(get(map._inner, bytes32(key)));\n    }\n\n    /**\n     * @dev Returns an array containing all the keys\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 map grows to a point where copying to memory consumes too much gas to fit in a block.\n     */\n    function keys(UintToUintMap storage map) internal view returns (uint256[] memory) {\n        bytes32[] memory store = keys(map._inner);\n        uint256[] memory result;\n\n        assembly (\"memory-safe\") {\n            result := store\n        }\n\n        return result;\n    }\n\n    /**\n     * @dev Returns an array containing a slice of the keys\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 map grows to a point where copying to memory consumes too much gas to fit in a block.\n     */\n    function keys(UintToUintMap storage map, uint256 start, uint256 end) internal view returns (uint256[] memory) {\n        bytes32[] memory store = keys(map._inner, start, end);\n        uint256[] memory result;\n\n        assembly (\"memory-safe\") {\n            result := store\n        }\n\n        return result;\n    }\n\n    // UintToAddressMap\n\n    struct UintToAddressMap {\n        Bytes32ToBytes32Map _inner;\n    }\n\n    /**\n     * @dev Adds a key-value pair to a map, or updates the value for an existing\n     * key. O(1).\n     *\n     * Returns true if the key was added to the map, that is if it was not\n     * already present.\n     */\n    function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) {\n        return set(map._inner, bytes32(key), bytes32(uint256(uint160(value))));\n    }\n\n    /**\n     * @dev Removes a value from a map. O(1).\n     *\n     * Returns true if the key was removed from the map, that is if it was present.\n     */\n    function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) {\n        return remove(map._inner, bytes32(key));\n    }\n\n    /**\n     * @dev Removes all the entries from a map. O(n).\n     *\n     * WARNING: This function has an unbounded cost that scales with map size. Developers should keep in mind that\n     * using it may render the function uncallable if the map grows to the point where clearing it consumes too much\n     * gas to fit in a block.\n     */\n    function clear(UintToAddressMap storage map) internal {\n        clear(map._inner);\n    }\n\n    /**\n     * @dev Returns true if the key is in the map. O(1).\n     */\n    function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) {\n        return contains(map._inner, bytes32(key));\n    }\n\n    /**\n     * @dev Returns the number of elements in the map. O(1).\n     */\n    function length(UintToAddressMap storage map) internal view returns (uint256) {\n        return length(map._inner);\n    }\n\n    /**\n     * @dev Returns the element stored at position `index` in the map. O(1).\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(UintToAddressMap storage map, uint256 index) internal view returns (uint256 key, address value) {\n        (bytes32 atKey, bytes32 val) = at(map._inner, index);\n        return (uint256(atKey), address(uint160(uint256(val))));\n    }\n\n    /**\n     * @dev Tries to return the value associated with `key`. O(1).\n     * Does not revert if `key` is not in the map.\n     */\n    function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool exists, address value) {\n        (bool success, bytes32 val) = tryGet(map._inner, bytes32(key));\n        return (success, address(uint160(uint256(val))));\n    }\n\n    /**\n     * @dev Returns the value associated with `key`. O(1).\n     *\n     * Requirements:\n     *\n     * - `key` must be in the map.\n     */\n    function get(UintToAddressMap storage map, uint256 key) internal view returns (address) {\n        return address(uint160(uint256(get(map._inner, bytes32(key)))));\n    }\n\n    /**\n     * @dev Returns an array containing all the keys\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 map grows to a point where copying to memory consumes too much gas to fit in a block.\n     */\n    function keys(UintToAddressMap storage map) internal view returns (uint256[] memory) {\n        bytes32[] memory store = keys(map._inner);\n        uint256[] memory result;\n\n        assembly (\"memory-safe\") {\n            result := store\n        }\n\n        return result;\n    }\n\n    /**\n     * @dev Returns an array containing a slice of the keys\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 map grows to a point where copying to memory consumes too much gas to fit in a block.\n     */\n    function keys(UintToAddressMap storage map, uint256 start, uint256 end) internal view returns (uint256[] memory) {\n        bytes32[] memory store = keys(map._inner, start, end);\n        uint256[] memory result;\n\n        assembly (\"memory-safe\") {\n            result := store\n        }\n\n        return result;\n    }\n\n    // UintToBytes32Map\n\n    struct UintToBytes32Map {\n        Bytes32ToBytes32Map _inner;\n    }\n\n    /**\n     * @dev Adds a key-value pair to a map, or updates the value for an existing\n     * key. O(1).\n     *\n     * Returns true if the key was added to the map, that is if it was not\n     * already present.\n     */\n    function set(UintToBytes32Map storage map, uint256 key, bytes32 value) internal returns (bool) {\n        return set(map._inner, bytes32(key), value);\n    }\n\n    /**\n     * @dev Removes a value from a map. O(1).\n     *\n     * Returns true if the key was removed from the map, that is if it was present.\n     */\n    function remove(UintToBytes32Map storage map, uint256 key) internal returns (bool) {\n        return remove(map._inner, bytes32(key));\n    }\n\n    /**\n     * @dev Removes all the entries from a map. O(n).\n     *\n     * WARNING: This function has an unbounded cost that scales with map size. Developers should keep in mind that\n     * using it may render the function uncallable if the map grows to the point where clearing it consumes too much\n     * gas to fit in a block.\n     */\n    function clear(UintToBytes32Map storage map) internal {\n        clear(map._inner);\n    }\n\n    /**\n     * @dev Returns true if the key is in the map. O(1).\n     */\n    function contains(UintToBytes32Map storage map, uint256 key) internal view returns (bool) {\n        return contains(map._inner, bytes32(key));\n    }\n\n    /**\n     * @dev Returns the number of elements in the map. O(1).\n     */\n    function length(UintToBytes32Map storage map) internal view returns (uint256) {\n        return length(map._inner);\n    }\n\n    /**\n     * @dev Returns the element stored at position `index` in the map. O(1).\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(UintToBytes32Map storage map, uint256 index) internal view returns (uint256 key, bytes32 value) {\n        (bytes32 atKey, bytes32 val) = at(map._inner, index);\n        return (uint256(atKey), val);\n    }\n\n    /**\n     * @dev Tries to return the value associated with `key`. O(1).\n     * Does not revert if `key` is not in the map.\n     */\n    function tryGet(UintToBytes32Map storage map, uint256 key) internal view returns (bool exists, bytes32 value) {\n        (bool success, bytes32 val) = tryGet(map._inner, bytes32(key));\n        return (success, val);\n    }\n\n    /**\n     * @dev Returns the value associated with `key`. O(1).\n     *\n     * Requirements:\n     *\n     * - `key` must be in the map.\n     */\n    function get(UintToBytes32Map storage map, uint256 key) internal view returns (bytes32) {\n        return get(map._inner, bytes32(key));\n    }\n\n    /**\n     * @dev Returns an array containing all the keys\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 map grows to a point where copying to memory consumes too much gas to fit in a block.\n     */\n    function keys(UintToBytes32Map storage map) internal view returns (uint256[] memory) {\n        bytes32[] memory store = keys(map._inner);\n        uint256[] memory result;\n\n        assembly (\"memory-safe\") {\n            result := store\n        }\n\n        return result;\n    }\n\n    /**\n     * @dev Returns an array containing a slice of the keys\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 map grows to a point where copying to memory consumes too much gas to fit in a block.\n     */\n    function keys(UintToBytes32Map storage map, uint256 start, uint256 end) internal view returns (uint256[] memory) {\n        bytes32[] memory store = keys(map._inner, start, end);\n        uint256[] memory result;\n\n        assembly (\"memory-safe\") {\n            result := store\n        }\n\n        return result;\n    }\n\n    // AddressToUintMap\n\n    struct AddressToUintMap {\n        Bytes32ToBytes32Map _inner;\n    }\n\n    /**\n     * @dev Adds a key-value pair to a map, or updates the value for an existing\n     * key. O(1).\n     *\n     * Returns true if the key was added to the map, that is if it was not\n     * already present.\n     */\n    function set(AddressToUintMap storage map, address key, uint256 value) internal returns (bool) {\n        return set(map._inner, bytes32(uint256(uint160(key))), bytes32(value));\n    }\n\n    /**\n     * @dev Removes a value from a map. O(1).\n     *\n     * Returns true if the key was removed from the map, that is if it was present.\n     */\n    function remove(AddressToUintMap storage map, address key) internal returns (bool) {\n        return remove(map._inner, bytes32(uint256(uint160(key))));\n    }\n\n    /**\n     * @dev Removes all the entries from a map. O(n).\n     *\n     * WARNING: This function has an unbounded cost that scales with map size. Developers should keep in mind that\n     * using it may render the function uncallable if the map grows to the point where clearing it consumes too much\n     * gas to fit in a block.\n     */\n    function clear(AddressToUintMap storage map) internal {\n        clear(map._inner);\n    }\n\n    /**\n     * @dev Returns true if the key is in the map. O(1).\n     */\n    function contains(AddressToUintMap storage map, address key) internal view returns (bool) {\n        return contains(map._inner, bytes32(uint256(uint160(key))));\n    }\n\n    /**\n     * @dev Returns the number of elements in the map. O(1).\n     */\n    function length(AddressToUintMap storage map) internal view returns (uint256) {\n        return length(map._inner);\n    }\n\n    /**\n     * @dev Returns the element stored at position `index` in the map. O(1).\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(AddressToUintMap storage map, uint256 index) internal view returns (address key, uint256 value) {\n        (bytes32 atKey, bytes32 val) = at(map._inner, index);\n        return (address(uint160(uint256(atKey))), uint256(val));\n    }\n\n    /**\n     * @dev Tries to return the value associated with `key`. O(1).\n     * Does not revert if `key` is not in the map.\n     */\n    function tryGet(AddressToUintMap storage map, address key) internal view returns (bool exists, uint256 value) {\n        (bool success, bytes32 val) = tryGet(map._inner, bytes32(uint256(uint160(key))));\n        return (success, uint256(val));\n    }\n\n    /**\n     * @dev Returns the value associated with `key`. O(1).\n     *\n     * Requirements:\n     *\n     * - `key` must be in the map.\n     */\n    function get(AddressToUintMap storage map, address key) internal view returns (uint256) {\n        return uint256(get(map._inner, bytes32(uint256(uint160(key)))));\n    }\n\n    /**\n     * @dev Returns an array containing all the keys\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 map grows to a point where copying to memory consumes too much gas to fit in a block.\n     */\n    function keys(AddressToUintMap storage map) internal view returns (address[] memory) {\n        bytes32[] memory store = keys(map._inner);\n        address[] memory result;\n\n        assembly (\"memory-safe\") {\n            result := store\n        }\n\n        return result;\n    }\n\n    /**\n     * @dev Returns an array containing a slice of the keys\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 map grows to a point where copying to memory consumes too much gas to fit in a block.\n     */\n    function keys(AddressToUintMap storage map, uint256 start, uint256 end) internal view returns (address[] memory) {\n        bytes32[] memory store = keys(map._inner, start, end);\n        address[] memory result;\n\n        assembly (\"memory-safe\") {\n            result := store\n        }\n\n        return result;\n    }\n\n    // AddressToAddressMap\n\n    struct AddressToAddressMap {\n        Bytes32ToBytes32Map _inner;\n    }\n\n    /**\n     * @dev Adds a key-value pair to a map, or updates the value for an existing\n     * key. O(1).\n     *\n     * Returns true if the key was added to the map, that is if it was not\n     * already present.\n     */\n    function set(AddressToAddressMap storage map, address key, address value) internal returns (bool) {\n        return set(map._inner, bytes32(uint256(uint160(key))), bytes32(uint256(uint160(value))));\n    }\n\n    /**\n     * @dev Removes a value from a map. O(1).\n     *\n     * Returns true if the key was removed from the map, that is if it was present.\n     */\n    function remove(AddressToAddressMap storage map, address key) internal returns (bool) {\n        return remove(map._inner, bytes32(uint256(uint160(key))));\n    }\n\n    /**\n     * @dev Removes all the entries from a map. O(n).\n     *\n     * WARNING: This function has an unbounded cost that scales with map size. Developers should keep in mind that\n     * using it may render the function uncallable if the map grows to the point where clearing it consumes too much\n     * gas to fit in a block.\n     */\n    function clear(AddressToAddressMap storage map) internal {\n        clear(map._inner);\n    }\n\n    /**\n     * @dev Returns true if the key is in the map. O(1).\n     */\n    function contains(AddressToAddressMap storage map, address key) internal view returns (bool) {\n        return contains(map._inner, bytes32(uint256(uint160(key))));\n    }\n\n    /**\n     * @dev Returns the number of elements in the map. O(1).\n     */\n    function length(AddressToAddressMap storage map) internal view returns (uint256) {\n        return length(map._inner);\n    }\n\n    /**\n     * @dev Returns the element stored at position `index` in the map. O(1).\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(AddressToAddressMap storage map, uint256 index) internal view returns (address key, address value) {\n        (bytes32 atKey, bytes32 val) = at(map._inner, index);\n        return (address(uint160(uint256(atKey))), address(uint160(uint256(val))));\n    }\n\n    /**\n     * @dev Tries to return the value associated with `key`. O(1).\n     * Does not revert if `key` is not in the map.\n     */\n    function tryGet(AddressToAddressMap storage map, address key) internal view returns (bool exists, address value) {\n        (bool success, bytes32 val) = tryGet(map._inner, bytes32(uint256(uint160(key))));\n        return (success, address(uint160(uint256(val))));\n    }\n\n    /**\n     * @dev Returns the value associated with `key`. O(1).\n     *\n     * Requirements:\n     *\n     * - `key` must be in the map.\n     */\n    function get(AddressToAddressMap storage map, address key) internal view returns (address) {\n        return address(uint160(uint256(get(map._inner, bytes32(uint256(uint160(key)))))));\n    }\n\n    /**\n     * @dev Returns an array containing all the keys\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 map grows to a point where copying to memory consumes too much gas to fit in a block.\n     */\n    function keys(AddressToAddressMap storage map) internal view returns (address[] memory) {\n        bytes32[] memory store = keys(map._inner);\n        address[] memory result;\n\n        assembly (\"memory-safe\") {\n            result := store\n        }\n\n        return result;\n    }\n\n    /**\n     * @dev Returns an array containing a slice of the keys\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 map grows to a point where copying to memory consumes too much gas to fit in a block.\n     */\n    function keys(\n        AddressToAddressMap storage map,\n        uint256 start,\n        uint256 end\n    ) internal view returns (address[] memory) {\n        bytes32[] memory store = keys(map._inner, start, end);\n        address[] memory result;\n\n        assembly (\"memory-safe\") {\n            result := store\n        }\n\n        return result;\n    }\n\n    // AddressToBytes32Map\n\n    struct AddressToBytes32Map {\n        Bytes32ToBytes32Map _inner;\n    }\n\n    /**\n     * @dev Adds a key-value pair to a map, or updates the value for an existing\n     * key. O(1).\n     *\n     * Returns true if the key was added to the map, that is if it was not\n     * already present.\n     */\n    function set(AddressToBytes32Map storage map, address key, bytes32 value) internal returns (bool) {\n        return set(map._inner, bytes32(uint256(uint160(key))), value);\n    }\n\n    /**\n     * @dev Removes a value from a map. O(1).\n     *\n     * Returns true if the key was removed from the map, that is if it was present.\n     */\n    function remove(AddressToBytes32Map storage map, address key) internal returns (bool) {\n        return remove(map._inner, bytes32(uint256(uint160(key))));\n    }\n\n    /**\n     * @dev Removes all the entries from a map. O(n).\n     *\n     * WARNING: This function has an unbounded cost that scales with map size. Developers should keep in mind that\n     * using it may render the function uncallable if the map grows to the point where clearing it consumes too much\n     * gas to fit in a block.\n     */\n    function clear(AddressToBytes32Map storage map) internal {\n        clear(map._inner);\n    }\n\n    /**\n     * @dev Returns true if the key is in the map. O(1).\n     */\n    function contains(AddressToBytes32Map storage map, address key) internal view returns (bool) {\n        return contains(map._inner, bytes32(uint256(uint160(key))));\n    }\n\n    /**\n     * @dev Returns the number of elements in the map. O(1).\n     */\n    function length(AddressToBytes32Map storage map) internal view returns (uint256) {\n        return length(map._inner);\n    }\n\n    /**\n     * @dev Returns the element stored at position `index` in the map. O(1).\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(AddressToBytes32Map storage map, uint256 index) internal view returns (address key, bytes32 value) {\n        (bytes32 atKey, bytes32 val) = at(map._inner, index);\n        return (address(uint160(uint256(atKey))), val);\n    }\n\n    /**\n     * @dev Tries to return the value associated with `key`. O(1).\n     * Does not revert if `key` is not in the map.\n     */\n    function tryGet(AddressToBytes32Map storage map, address key) internal view returns (bool exists, bytes32 value) {\n        (bool success, bytes32 val) = tryGet(map._inner, bytes32(uint256(uint160(key))));\n        return (success, val);\n    }\n\n    /**\n     * @dev Returns the value associated with `key`. O(1).\n     *\n     * Requirements:\n     *\n     * - `key` must be in the map.\n     */\n    function get(AddressToBytes32Map storage map, address key) internal view returns (bytes32) {\n        return get(map._inner, bytes32(uint256(uint160(key))));\n    }\n\n    /**\n     * @dev Returns an array containing all the keys\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 map grows to a point where copying to memory consumes too much gas to fit in a block.\n     */\n    function keys(AddressToBytes32Map storage map) internal view returns (address[] memory) {\n        bytes32[] memory store = keys(map._inner);\n        address[] memory result;\n\n        assembly (\"memory-safe\") {\n            result := store\n        }\n\n        return result;\n    }\n\n    /**\n     * @dev Returns an array containing a slice of the keys\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 map grows to a point where copying to memory consumes too much gas to fit in a block.\n     */\n    function keys(\n        AddressToBytes32Map storage map,\n        uint256 start,\n        uint256 end\n    ) internal view returns (address[] memory) {\n        bytes32[] memory store = keys(map._inner, start, end);\n        address[] memory result;\n\n        assembly (\"memory-safe\") {\n            result := store\n        }\n\n        return result;\n    }\n\n    // Bytes32ToUintMap\n\n    struct Bytes32ToUintMap {\n        Bytes32ToBytes32Map _inner;\n    }\n\n    /**\n     * @dev Adds a key-value pair to a map, or updates the value for an existing\n     * key. O(1).\n     *\n     * Returns true if the key was added to the map, that is if it was not\n     * already present.\n     */\n    function set(Bytes32ToUintMap storage map, bytes32 key, uint256 value) internal returns (bool) {\n        return set(map._inner, key, bytes32(value));\n    }\n\n    /**\n     * @dev Removes a value from a map. O(1).\n     *\n     * Returns true if the key was removed from the map, that is if it was present.\n     */\n    function remove(Bytes32ToUintMap storage map, bytes32 key) internal returns (bool) {\n        return remove(map._inner, key);\n    }\n\n    /**\n     * @dev Removes all the entries from a map. O(n).\n     *\n     * WARNING: This function has an unbounded cost that scales with map size. Developers should keep in mind that\n     * using it may render the function uncallable if the map grows to the point where clearing it consumes too much\n     * gas to fit in a block.\n     */\n    function clear(Bytes32ToUintMap storage map) internal {\n        clear(map._inner);\n    }\n\n    /**\n     * @dev Returns true if the key is in the map. O(1).\n     */\n    function contains(Bytes32ToUintMap storage map, bytes32 key) internal view returns (bool) {\n        return contains(map._inner, key);\n    }\n\n    /**\n     * @dev Returns the number of elements in the map. O(1).\n     */\n    function length(Bytes32ToUintMap storage map) internal view returns (uint256) {\n        return length(map._inner);\n    }\n\n    /**\n     * @dev Returns the element stored at position `index` in the map. O(1).\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(Bytes32ToUintMap storage map, uint256 index) internal view returns (bytes32 key, uint256 value) {\n        (bytes32 atKey, bytes32 val) = at(map._inner, index);\n        return (atKey, uint256(val));\n    }\n\n    /**\n     * @dev Tries to return the value associated with `key`. O(1).\n     * Does not revert if `key` is not in the map.\n     */\n    function tryGet(Bytes32ToUintMap storage map, bytes32 key) internal view returns (bool exists, uint256 value) {\n        (bool success, bytes32 val) = tryGet(map._inner, key);\n        return (success, uint256(val));\n    }\n\n    /**\n     * @dev Returns the value associated with `key`. O(1).\n     *\n     * Requirements:\n     *\n     * - `key` must be in the map.\n     */\n    function get(Bytes32ToUintMap storage map, bytes32 key) internal view returns (uint256) {\n        return uint256(get(map._inner, key));\n    }\n\n    /**\n     * @dev Returns an array containing all the keys\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 map grows to a point where copying to memory consumes too much gas to fit in a block.\n     */\n    function keys(Bytes32ToUintMap storage map) internal view returns (bytes32[] memory) {\n        bytes32[] memory store = keys(map._inner);\n        bytes32[] memory result;\n\n        assembly (\"memory-safe\") {\n            result := store\n        }\n\n        return result;\n    }\n\n    /**\n     * @dev Returns an array containing a slice of the keys\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 map grows to a point where copying to memory consumes too much gas to fit in a block.\n     */\n    function keys(Bytes32ToUintMap storage map, uint256 start, uint256 end) internal view returns (bytes32[] memory) {\n        bytes32[] memory store = keys(map._inner, start, end);\n        bytes32[] memory result;\n\n        assembly (\"memory-safe\") {\n            result := store\n        }\n\n        return result;\n    }\n\n    // Bytes32ToAddressMap\n\n    struct Bytes32ToAddressMap {\n        Bytes32ToBytes32Map _inner;\n    }\n\n    /**\n     * @dev Adds a key-value pair to a map, or updates the value for an existing\n     * key. O(1).\n     *\n     * Returns true if the key was added to the map, that is if it was not\n     * already present.\n     */\n    function set(Bytes32ToAddressMap storage map, bytes32 key, address value) internal returns (bool) {\n        return set(map._inner, key, bytes32(uint256(uint160(value))));\n    }\n\n    /**\n     * @dev Removes a value from a map. O(1).\n     *\n     * Returns true if the key was removed from the map, that is if it was present.\n     */\n    function remove(Bytes32ToAddressMap storage map, bytes32 key) internal returns (bool) {\n        return remove(map._inner, key);\n    }\n\n    /**\n     * @dev Removes all the entries from a map. O(n).\n     *\n     * WARNING: This function has an unbounded cost that scales with map size. Developers should keep in mind that\n     * using it may render the function uncallable if the map grows to the point where clearing it consumes too much\n     * gas to fit in a block.\n     */\n    function clear(Bytes32ToAddressMap storage map) internal {\n        clear(map._inner);\n    }\n\n    /**\n     * @dev Returns true if the key is in the map. O(1).\n     */\n    function contains(Bytes32ToAddressMap storage map, bytes32 key) internal view returns (bool) {\n        return contains(map._inner, key);\n    }\n\n    /**\n     * @dev Returns the number of elements in the map. O(1).\n     */\n    function length(Bytes32ToAddressMap storage map) internal view returns (uint256) {\n        return length(map._inner);\n    }\n\n    /**\n     * @dev Returns the element stored at position `index` in the map. O(1).\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(Bytes32ToAddressMap storage map, uint256 index) internal view returns (bytes32 key, address value) {\n        (bytes32 atKey, bytes32 val) = at(map._inner, index);\n        return (atKey, address(uint160(uint256(val))));\n    }\n\n    /**\n     * @dev Tries to return the value associated with `key`. O(1).\n     * Does not revert if `key` is not in the map.\n     */\n    function tryGet(Bytes32ToAddressMap storage map, bytes32 key) internal view returns (bool exists, address value) {\n        (bool success, bytes32 val) = tryGet(map._inner, key);\n        return (success, address(uint160(uint256(val))));\n    }\n\n    /**\n     * @dev Returns the value associated with `key`. O(1).\n     *\n     * Requirements:\n     *\n     * - `key` must be in the map.\n     */\n    function get(Bytes32ToAddressMap storage map, bytes32 key) internal view returns (address) {\n        return address(uint160(uint256(get(map._inner, key))));\n    }\n\n    /**\n     * @dev Returns an array containing all the keys\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 map grows to a point where copying to memory consumes too much gas to fit in a block.\n     */\n    function keys(Bytes32ToAddressMap storage map) internal view returns (bytes32[] memory) {\n        bytes32[] memory store = keys(map._inner);\n        bytes32[] memory result;\n\n        assembly (\"memory-safe\") {\n            result := store\n        }\n\n        return result;\n    }\n\n    /**\n     * @dev Returns an array containing a slice of the keys\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 map grows to a point where copying to memory consumes too much gas to fit in a block.\n     */\n    function keys(\n        Bytes32ToAddressMap storage map,\n        uint256 start,\n        uint256 end\n    ) internal view returns (bytes32[] memory) {\n        bytes32[] memory store = keys(map._inner, start, end);\n        bytes32[] memory result;\n\n        assembly (\"memory-safe\") {\n            result := store\n        }\n\n        return result;\n    }\n\n    // Bytes4ToAddressMap\n\n    struct Bytes4ToAddressMap {\n        Bytes32ToBytes32Map _inner;\n    }\n\n    /**\n     * @dev Adds a key-value pair to a map, or updates the value for an existing\n     * key. O(1).\n     *\n     * Returns true if the key was added to the map, that is if it was not\n     * already present.\n     */\n    function set(Bytes4ToAddressMap storage map, bytes4 key, address value) internal returns (bool) {\n        return set(map._inner, bytes32(key), bytes32(uint256(uint160(value))));\n    }\n\n    /**\n     * @dev Removes a value from a map. O(1).\n     *\n     * Returns true if the key was removed from the map, that is if it was present.\n     */\n    function remove(Bytes4ToAddressMap storage map, bytes4 key) internal returns (bool) {\n        return remove(map._inner, bytes32(key));\n    }\n\n    /**\n     * @dev Removes all the entries from a map. O(n).\n     *\n     * WARNING: This function has an unbounded cost that scales with map size. Developers should keep in mind that\n     * using it may render the function uncallable if the map grows to the point where clearing it consumes too much\n     * gas to fit in a block.\n     */\n    function clear(Bytes4ToAddressMap storage map) internal {\n        clear(map._inner);\n    }\n\n    /**\n     * @dev Returns true if the key is in the map. O(1).\n     */\n    function contains(Bytes4ToAddressMap storage map, bytes4 key) internal view returns (bool) {\n        return contains(map._inner, bytes32(key));\n    }\n\n    /**\n     * @dev Returns the number of elements in the map. O(1).\n     */\n    function length(Bytes4ToAddressMap storage map) internal view returns (uint256) {\n        return length(map._inner);\n    }\n\n    /**\n     * @dev Returns the element stored at position `index` in the map. O(1).\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(Bytes4ToAddressMap storage map, uint256 index) internal view returns (bytes4 key, address value) {\n        (bytes32 atKey, bytes32 val) = at(map._inner, index);\n        return (bytes4(atKey), address(uint160(uint256(val))));\n    }\n\n    /**\n     * @dev Tries to return the value associated with `key`. O(1).\n     * Does not revert if `key` is not in the map.\n     */\n    function tryGet(Bytes4ToAddressMap storage map, bytes4 key) internal view returns (bool exists, address value) {\n        (bool success, bytes32 val) = tryGet(map._inner, bytes32(key));\n        return (success, address(uint160(uint256(val))));\n    }\n\n    /**\n     * @dev Returns the value associated with `key`. O(1).\n     *\n     * Requirements:\n     *\n     * - `key` must be in the map.\n     */\n    function get(Bytes4ToAddressMap storage map, bytes4 key) internal view returns (address) {\n        return address(uint160(uint256(get(map._inner, bytes32(key)))));\n    }\n\n    /**\n     * @dev Returns an array containing all the keys\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 map grows to a point where copying to memory consumes too much gas to fit in a block.\n     */\n    function keys(Bytes4ToAddressMap storage map) internal view returns (bytes4[] memory) {\n        bytes32[] memory store = keys(map._inner);\n        bytes4[] memory result;\n\n        assembly (\"memory-safe\") {\n            result := store\n        }\n\n        return result;\n    }\n\n    /**\n     * @dev Returns an array containing a slice of the keys\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 map grows to a point where copying to memory consumes too much gas to fit in a block.\n     */\n    function keys(Bytes4ToAddressMap storage map, uint256 start, uint256 end) internal view returns (bytes4[] memory) {\n        bytes32[] memory store = keys(map._inner, start, end);\n        bytes4[] memory result;\n\n        assembly (\"memory-safe\") {\n            result := store\n        }\n\n        return result;\n    }\n\n    /**\n     * @dev Query for a nonexistent map key.\n     */\n    error EnumerableMapNonexistentBytesKey(bytes key);\n\n    struct BytesToBytesMap {\n        // Storage of keys\n        EnumerableSet.BytesSet _keys;\n        mapping(bytes key => bytes) _values;\n    }\n\n    /**\n     * @dev Adds a key-value pair to a map, or updates the value for an existing\n     * key. O(1).\n     *\n     * Returns true if the key was added to the map, that is if it was not\n     * already present.\n     */\n    function set(BytesToBytesMap storage map, bytes memory key, bytes memory value) internal returns (bool) {\n        map._values[key] = value;\n        return map._keys.add(key);\n    }\n\n    /**\n     * @dev Removes a key-value pair from a map. O(1).\n     *\n     * Returns true if the key was removed from the map, that is if it was present.\n     */\n    function remove(BytesToBytesMap storage map, bytes memory key) internal returns (bool) {\n        delete map._values[key];\n        return map._keys.remove(key);\n    }\n\n    /**\n     * @dev Removes all the entries from a map. 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 map grows to the point where clearing it consumes too much gas to fit in a block.\n     */\n    function clear(BytesToBytesMap storage map) internal {\n        uint256 len = length(map);\n        for (uint256 i = 0; i < len; ++i) {\n            delete map._values[map._keys.at(i)];\n        }\n        map._keys.clear();\n    }\n\n    /**\n     * @dev Returns true if the key is in the map. O(1).\n     */\n    function contains(BytesToBytesMap storage map, bytes memory key) internal view returns (bool) {\n        return map._keys.contains(key);\n    }\n\n    /**\n     * @dev Returns the number of key-value pairs in the map. O(1).\n     */\n    function length(BytesToBytesMap storage map) internal view returns (uint256) {\n        return map._keys.length();\n    }\n\n    /**\n     * @dev Returns the key-value pair stored at position `index` in the map. O(1).\n     *\n     * Note that there are no guarantees on the ordering of entries inside the\n     * array, and it may change when more entries are added or removed.\n     *\n     * Requirements:\n     *\n     * - `index` must be strictly less than {length}.\n     */\n    function at(\n        BytesToBytesMap storage map,\n        uint256 index\n    ) internal view returns (bytes memory key, bytes memory value) {\n        key = map._keys.at(index);\n        value = map._values[key];\n    }\n\n    /**\n     * @dev Tries to return the value associated with `key`. O(1).\n     * Does not revert if `key` is not in the map.\n     */\n    function tryGet(\n        BytesToBytesMap storage map,\n        bytes memory key\n    ) internal view returns (bool exists, bytes memory value) {\n        value = map._values[key];\n        exists = bytes(value).length != 0 || contains(map, key);\n    }\n\n    /**\n     * @dev Returns the value associated with `key`. O(1).\n     *\n     * Requirements:\n     *\n     * - `key` must be in the map.\n     */\n    function get(BytesToBytesMap storage map, bytes memory key) internal view returns (bytes memory value) {\n        bool exists;\n        (exists, value) = tryGet(map, key);\n        if (!exists) {\n            revert EnumerableMapNonexistentBytesKey(key);\n        }\n    }\n\n    /**\n     * @dev Returns an array containing all the keys\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 map grows to a point where copying to memory consumes too much gas to fit in a block.\n     */\n    function keys(BytesToBytesMap storage map) internal view returns (bytes[] memory) {\n        return map._keys.values();\n    }\n\n    /**\n     * @dev Returns an array containing a slice of the keys\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 map grows to a point where copying to memory consumes too much gas to fit in a block.\n     */\n    function keys(BytesToBytesMap storage map, uint256 start, uint256 end) internal view returns (bytes[] memory) {\n        return map._keys.values(start, end);\n    }\n}\n"},{"file_path":"src/integrations/Farm.sol","source_code":"// SPDX-License-Identifier: MIT\npragma solidity 0.8.28;\n\nimport {ERC20} from \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\nimport {FixedPointMathLib} from \"@solmate/src/utils/FixedPointMathLib.sol\";\n\nimport {IFarm} from \"@interfaces/IFarm.sol\";\nimport {CoreRoles} from \"@libraries/CoreRoles.sol\";\nimport {CoreControlled} from \"@core/CoreControlled.sol\";\n\n/// @notice InfiniFi Farm base contract\nabstract contract Farm is CoreControlled, IFarm {\n    using FixedPointMathLib for uint256;\n\n    address public immutable assetToken;\n\n    /// @notice cap on the amount of assets that can be deposited into the farm\n    uint256 public cap;\n\n    /// @notice Max slippage for depositing and witdhrawing assets from the farm.\n    /// @dev Stored as a percentage with 18 decimals of precision, of the minimum\n    /// position size compared to the previous position size (so actually 1 - slippage).\n    /// @dev Set to 0 to disable slippage checks.\n    uint256 public maxSlippage;\n\n    /// @notice reference to the rewards claimer contract\n    address public rewardContract;\n\n    error CapExceeded(uint256 newAmount, uint256 cap);\n    error SlippageTooHigh(uint256 minAssetsOut, uint256 assetsReceived);\n    error ZeroAddress(address);\n    error RewardsNotEnabled();\n    error RewardsClaimFailed();\n    error RewardsClaimLostAssets();\n\n    event CapUpdated(uint256 newCap);\n    event MaxSlippageUpdated(uint256 newMaxSlippage);\n    event RewardContractUpdated(uint256 indexed timestamp, address rewardContract);\n    event Claimed(uint256 indexed timestamp, uint256 amount);\n\n    constructor(address _core, address _assetToken) CoreControlled(_core) {\n        assetToken = _assetToken;\n        cap = type(uint256).max;\n\n        // default to 99.9999%\n        // most farms should not have deposits/withdrawals fees, unless explicitly\n        // implemented, and should at worst round against depositors which should\n        // only cause some wei of losses when our farms do a deposit/withdraw.\n        maxSlippage = 0.999999e18;\n    }\n\n    /// @notice used to check slippage on vault operations\n    modifier checkSlippage() {\n        uint256 assetsBefore = assets();\n        _;\n        uint256 assetsAfter = assets();\n        uint256 minAssetsAfter = assetsBefore.mulWadDown(maxSlippage);\n        require(assetsAfter >= minAssetsAfter, SlippageTooHigh(minAssetsAfter, assetsAfter));\n    }\n\n    function setRewardContract(address _rewardContract) external onlyCoreRole(CoreRoles.PROTOCOL_PARAMETERS) {\n        require(_rewardContract != address(0), ZeroAddress(_rewardContract));\n        rewardContract = _rewardContract;\n        emit RewardContractUpdated(block.timestamp, _rewardContract);\n    }\n\n    /// @notice set the deposit cap of the farm\n    function setCap(uint256 _newCap) external onlyCoreRole(CoreRoles.PROTOCOL_PARAMETERS) {\n        cap = _newCap;\n        emit CapUpdated(_newCap);\n    }\n\n    /// @notice set the max tolerated slippage for depositing and witdhrawing assets from the farm\n    function setMaxSlippage(uint256 _maxSlippage) external onlyCoreRole(CoreRoles.PROTOCOL_PARAMETERS) {\n        maxSlippage = _maxSlippage;\n        emit MaxSlippageUpdated(_maxSlippage);\n    }\n\n    // --------------------------------------------------------------------\n    // Accounting\n    // --------------------------------------------------------------------\n\n    function assets() public view virtual returns (uint256);\n\n    // --------------------------------------------------------------------\n    // Adapter logic\n    // --------------------------------------------------------------------\n\n    function maxDeposit() external view virtual returns (uint256) {\n        uint256 currentAssets = assets();\n        if (currentAssets >= cap) {\n            return 0;\n        }\n        return cap - currentAssets;\n    }\n\n    function deposit() external virtual onlyCoreRole(CoreRoles.FARM_MANAGER) whenNotPaused {\n        uint256 assetsToDeposit = ERC20(assetToken).balanceOf(address(this));\n        uint256 assetsBefore = assets();\n\n        if (assetsBefore + assetsToDeposit > cap) {\n            revert CapExceeded(assetsBefore + assetsToDeposit, cap);\n        }\n\n        _deposit(assetsToDeposit);\n\n        uint256 assetsAfter = assets();\n        uint256 assetsReceived = assetsAfter - assetsBefore;\n\n        // check slippage\n        uint256 minAssetsOut = assetsToDeposit.mulWadDown(maxSlippage);\n        require(assetsReceived >= minAssetsOut, SlippageTooHigh(minAssetsOut, assetsReceived));\n\n        emit AssetsUpdated(block.timestamp, assetsBefore, assetsAfter);\n    }\n\n    function _deposit(uint256 assetsToDeposit) internal virtual;\n\n    function withdraw(uint256 amount, address to) external virtual onlyCoreRole(CoreRoles.FARM_MANAGER) whenNotPaused {\n        uint256 assetsBefore = assets();\n        uint256 receiverBalanceBefore = ERC20(assetToken).balanceOf(to);\n\n        _withdraw(amount, to);\n\n        uint256 assetsAfter = assets();\n        uint256 receiverBalanceAfter = ERC20(assetToken).balanceOf(to);\n\n        uint256 assetsSpent = assetsBefore - assetsAfter;\n        uint256 receiverBalanceIncrease = receiverBalanceAfter - receiverBalanceBefore;\n        assert(receiverBalanceIncrease == amount); // sanity check for _withdraw implementations, should never fail\n\n        uint256 minAssetsOut = assetsSpent.mulWadDown(maxSlippage);\n        require(amount >= minAssetsOut, SlippageTooHigh(minAssetsOut, amount));\n\n        emit AssetsUpdated(block.timestamp, assetsBefore, assetsAfter);\n    }\n\n    /// @dev MAY spend more than _amount of assets() if there is slippage or rounding errors.\n    /// @dev MUST transfer exactly _amount of assets() to _to (or withdraw will revert)\n    function _withdraw(uint256 _amount, address _to) internal virtual;\n\n    // --------------------------------------------------------------------\n    // Rewards claiming\n    // --------------------------------------------------------------------\n    function claimRewards(bytes memory _calldata) external whenNotPaused onlyCoreRole(CoreRoles.FARM_SWAP_CALLER) {\n        address _rewardContract = rewardContract;\n        require(_rewardContract != address(0), RewardsNotEnabled());\n\n        uint256 assetsBefore = assets();\n\n        (bool success,) = _rewardContract.call(_calldata);\n        require(success, RewardsClaimFailed());\n\n        uint256 assetsAfter = assets();\n        require(assetsAfter >= assetsBefore, RewardsClaimLostAssets());\n\n        emit Claimed(block.timestamp, assetsAfter - assetsBefore);\n    }\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":"src/integrations/outland/OutlandVault.sol","source_code":"// SPDX-License-Identifier: MIT\npragma solidity 0.8.28;\n\nimport {ERC20} from \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\nimport {Strings} from \"@openzeppelin/contracts/utils/Strings.sol\";\nimport {SafeERC20} from \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\nimport {FixedPointMathLib} from \"@solmate/src/utils/FixedPointMathLib.sol\";\n\nimport {CoreRoles} from \"@libraries/CoreRoles.sol\";\nimport {GatewayLib} from \"@libraries/GatewayLib.sol\";\nimport {OutlandFarm} from \"@integrations/outland/OutlandFarm.sol\";\nimport {ReceiptToken} from \"@tokens/ReceiptToken.sol\";\nimport {CoreControlled} from \"@core/CoreControlled.sol\";\nimport {IInfiniFiGateway} from \"@interfaces/IInfiniFiGateway.sol\";\n\n/// @title OutlandVault\n/// @notice A cross-chain asset vault managing deposits and withdrawals for farms with liquidity tracking\n/// @dev Simplified ERC4626-style vault with non-transferable shares and portal-controlled cross-chain operations\n/// @dev can only support assets that have similar value, for iUSD instances it would be USDC, USDe, DAI, USDT, etc\n/// @dev Requires Oracle to function, Should set price to 1e18 (1$) as it is supposed to work with stables\n/// @dev Requires RECEIPT_TOKEN_MINTER and RECEIPT_TOKEN_BURNER roles to mirror L2 token supplies via portalUpdate.\ncontract OutlandVault is ERC20, CoreControlled {\n    using SafeERC20 for ERC20;\n    using FixedPointMathLib for uint256;\n    using GatewayLib for IInfiniFiGateway;\n\n    error NotFarm(address _sender);\n    error InvalidAmount(uint256 _amount);\n    error InvalidBridgedToken(address _token);\n    error TransfersNotAllowed();\n    error InsufficientLiquidity(address _token, uint256 _requested, uint256 _available);\n\n    event Redeemed(uint256 indexed timestamp, address token, uint256 shares, uint256 amount);\n    event Deposited(uint256 indexed timestamp, address token, uint256 amount, uint256 shares);\n    event PortalUpdate(uint256 indexed timestamp, uint256 oldAssets, uint256 newAssets);\n    event PortalDeposit(uint256 indexed timestamp, address token, uint256 amount, uint256 sharesMinted);\n    event PortalWithdraw(uint256 indexed timestamp, address token, uint256 amount);\n    event PortalBridgeWithdraw(uint256 indexed timestamp, address token, uint256 amount);\n\n    /// @notice The chain ID where this vault operates\n    uint256 public immutable chainId;\n\n    /// @notice Address of the outland farm contract that can deposit/redeem from this vault\n    address public immutable outlandFarm;\n\n    /// @notice Address of the gateway contract\n    address public immutable gateway;\n\n    /// @notice Address of the receipt token contract (iUSD)\n    address public immutable receiptToken;\n\n    /// @notice Address of staked token contract (siUSD)\n    address public immutable stakedToken;\n\n    /// @notice Timestamp of last sync of L2 assets & token supplies\n    uint256 public lastPortalUpdate;\n\n    /// @notice Initializes the OutlandVault contract\n    /// @dev Sets up ERC20 token with dynamic name based on chain ID\n    /// @param _core Address of the Core contract for role management\n    /// @param _farm Address of the farm of this vault\n    /// @param _gateway Address of the gateway contract\n    constructor(address _core, address _farm, address _gateway)\n        ERC20(\n            string.concat(\"Outland - \", Strings.toString(OutlandFarm(_farm).chainId()), \" Vault\"),\n            string.concat(\"OV-\", Strings.toString(OutlandFarm(_farm).chainId()))\n        )\n        CoreControlled(_core)\n    {\n        gateway = _gateway;\n        receiptToken = IInfiniFiGateway(_gateway).getAddress(\"receiptToken\");\n        stakedToken = IInfiniFiGateway(_gateway).getAddress(\"stakedToken\");\n        outlandFarm = _farm;\n        chainId = OutlandFarm(_farm).chainId();\n    }\n\n    /// @notice Restricts function access to only registered farm\n    modifier onlyOutlandFarm() {\n        require(msg.sender == outlandFarm, NotFarm(msg.sender));\n        _;\n    }\n\n    /// @notice Returns the total amount of liquid shares in the vault\n    function liquidShares() public view returns (uint256 totalLiquidShares) {\n        address[] memory assets = OutlandFarm(outlandFarm).assetTokens();\n        for (uint256 i = 0; i < assets.length; i++) {\n            totalLiquidShares += convertToShares(assets[i], ERC20(assets[i]).balanceOf(address(this)));\n        }\n    }\n\n    /// @notice helper method which allows reading share liquidity per token\n    /// @return how many shares are instantly redeemable for a given token\n    function liquidShares(address _token) public view returns (uint256) {\n        return convertToShares(_token, ERC20(_token).balanceOf(address(this)));\n    }\n\n    /// ============================================================\n    /// Farm Operations\n    /// ============================================================\n\n    /// @notice Deposits an asset into the vault and mints shares\n    /// @dev Can only be called by the registered outland farm\n    /// @dev Converts deposited tokens to asset token equivalent and mints shares\n    /// @param _token The asset token to deposit\n    /// @param _amount The amount of asset to deposit\n    function deposit(address _token, uint256 _amount) external onlyOutlandFarm returns (uint256) {\n        require(_amount > 0, InvalidAmount(_amount));\n        _syncSharesToLiquidity();\n\n        ERC20(_token).safeTransferFrom(msg.sender, address(this), _amount);\n        uint256 shares = convertToShares(_token, _amount);\n        _mint(msg.sender, shares);\n\n        emit Deposited(block.timestamp, _token, _amount, shares);\n        return shares;\n    }\n\n    /// @notice Redeems shares from the vault and withdraws assets\n    /// @dev Can only be called by the registered outland farm\n    /// @dev Burns shares and transfers equivalent amount of tokens to the farm\n    /// @param _token The asset token to withdraw\n    /// @param _shares The amount of shares to redeem\n    function redeem(address _token, uint256 _shares) external onlyOutlandFarm returns (uint256) {\n        require(_shares > 0, InvalidAmount(_shares));\n        _syncSharesToLiquidity();\n\n        uint256 _liquidShares = liquidShares(_token);\n        require(_liquidShares >= _shares, InsufficientLiquidity(_token, _shares, _liquidShares));\n\n        uint256 tokenAmount = convertToAssets(_token, _shares);\n        ERC20(_token).safeTransfer(outlandFarm, tokenAmount);\n        _burn(msg.sender, _shares);\n\n        emit Redeemed(block.timestamp, _token, _shares, tokenAmount);\n        return tokenAmount;\n    }\n\n    /// @notice Converts token to shares of this vault\n    /// @param _tokenIn The asset token to convert from\n    /// @param _amountIn The amount of asset to convert\n    /// @return The equivalent amount in shares\n    function convertToShares(address _tokenIn, uint256 _amountIn) public view returns (uint256) {\n        return OutlandFarm(outlandFarm).convert(_tokenIn, address(this), _amountIn);\n    }\n\n    /// @notice Converts from vault shares to specific token asset\n    /// @param _tokenOut The asset token to convert to\n    /// @param _sharesIn The amount of shares to convert\n    /// @return The equivalent amount in the target token denomination\n    function convertToAssets(address _tokenOut, uint256 _sharesIn) public view returns (uint256) {\n        return OutlandFarm(outlandFarm).convert(address(this), _tokenOut, _sharesIn);\n    }\n\n    /// ============================================================\n    /// Portal Operations\n    /// ============================================================\n\n    /// @notice Updates the vault's total assets based on portal accounting\n    /// @dev Syncs the farm's share balance with the external accounting system\n    /// @dev Mints shares on profit, burns shares on loss (up to available liquidity)\n    /// @param _totalAssetsValue New total assets value reported by the external accounting\n    /// @param _receiptTokenTotalSupply New total supply of the L2 iUSD token reported by the L2 accounting\n    /// @param _stakedTokenTotalSupply New total supply of the L2 siUSD token reported by the L2 accounting\n    function portalUpdate(uint256 _totalAssetsValue, uint256 _receiptTokenTotalSupply, uint256 _stakedTokenTotalSupply)\n        external\n        onlyCoreRole(CoreRoles.OUTLAND_PORTAL)\n    {\n        _syncSharesToLiquidity();\n\n        // what is reported on other chain + what is held by this vault\n        uint256 sharesTotalAfter = _totalAssetsValue + liquidShares();\n        uint256 sharesTotalBefore = balanceOf(outlandFarm);\n\n        if (sharesTotalAfter > sharesTotalBefore) {\n            _mint(outlandFarm, sharesTotalAfter - sharesTotalBefore);\n        } else if (sharesTotalAfter < sharesTotalBefore) {\n            uint256 sharesToBurn = sharesTotalBefore - sharesTotalAfter;\n            _burn(outlandFarm, sharesToBurn);\n            _syncSharesToLiquidity();\n        }\n\n        _syncL2Supply(_receiptTokenTotalSupply, _stakedTokenTotalSupply);\n\n        lastPortalUpdate = block.timestamp;\n        emit PortalUpdate(block.timestamp, sharesTotalBefore, sharesTotalAfter);\n    }\n\n    /// @notice Deposits assets into the vault via the portal\n    /// @dev Can only be called by the registered portal contract\n    /// @dev Mints shares if the liquidity exceeds the farm's current share balance\n    /// @param _token The asset token to deposit\n    /// @param _amount The amount of asset token to deposit\n    function portalDeposit(address _token, uint256 _amount) external onlyCoreRole(CoreRoles.OUTLAND_PORTAL) {\n        require(_amount > 0, InvalidAmount(_amount));\n        ERC20(_token).safeTransferFrom(msg.sender, address(this), _amount);\n\n        uint256 sharesMinted = _syncSharesToLiquidity();\n\n        emit PortalDeposit(block.timestamp, _token, _amount, sharesMinted);\n    }\n\n    /// @notice Withdraws assets from the vault via the portal\n    /// @dev Can only be called by the registered portal contract\n    /// @dev Does not burn shares, only transfers tokens from vault to portal\n    /// @param _token The asset token to withdraw\n    /// @param _amount The amount of asset to withdraw\n    function portalWithdraw(address _token, uint256 _amount) external onlyCoreRole(CoreRoles.OUTLAND_PORTAL) {\n        uint256 tokenBalance = ERC20(_token).balanceOf(address(this));\n        require(tokenBalance >= _amount, InvalidAmount(_amount));\n\n        ERC20(_token).safeTransfer(msg.sender, _amount);\n\n        _syncSharesToLiquidity();\n        emit PortalWithdraw(block.timestamp, _token, _amount);\n    }\n\n    /// @notice Withdraws mirrored iUSD or siUSD from the vault for cross-chain bridging\n    /// @dev Can only be called by the registered portal contract\n    /// @param _to Recipient of the withdrawn tokens (portal for burns, end user for releases)\n    function portalBridgeWithdraw(address _token, uint256 _amount, address _to)\n        external\n        onlyCoreRole(CoreRoles.OUTLAND_PORTAL)\n    {\n        require(_token == receiptToken || _token == stakedToken, InvalidBridgedToken(_token));\n        require(_amount > 0, InvalidAmount(_amount));\n        require(_to != address(0), InvalidAmount(_amount));\n\n        uint256 tokenBalance = ERC20(_token).balanceOf(address(this));\n        require(tokenBalance >= _amount, InvalidAmount(_amount));\n\n        ERC20(_token).safeTransfer(_to, _amount);\n\n        emit PortalBridgeWithdraw(block.timestamp, _token, _amount);\n    }\n\n    /// @notice Returns the assets report fields mirrored on L1 for cross-chain messaging\n    /// @return totalAssetsValue L2-reported farm assets excluding local vault liquidity\n    /// @return receiptSupply iUSD balance held by the vault\n    /// @return stakedSupply siUSD balance held by the vault\n    /// @return lastPortalUpdateTimestamp Timestamp of the last portalUpdate call\n    function portalAssetsReport()\n        external\n        view\n        returns (\n            uint256 totalAssetsValue,\n            uint256 receiptSupply,\n            uint256 stakedSupply,\n            uint256 lastPortalUpdateTimestamp\n        )\n    {\n        uint256 farmShares = balanceOf(outlandFarm);\n        uint256 liquid = liquidShares();\n        totalAssetsValue = farmShares > liquid ? farmShares - liquid : 0;\n        return (\n            totalAssetsValue,\n            ERC20(receiptToken).balanceOf(address(this)),\n            ERC20(stakedToken).balanceOf(address(this)),\n            lastPortalUpdate\n        );\n    }\n\n    /// ============================================================\n    /// Internal Operations\n    /// ============================================================\n\n    /// @notice Enforces that liqudity and issued shares are in sync\n    /// @return how many new shares are minted\n    function _syncSharesToLiquidity() internal returns (uint256) {\n        uint256 sharesLiquid = liquidShares();\n        uint256 sharesInFarm = balanceOf(outlandFarm);\n\n        // nothing to reconcile\n        if (sharesInFarm >= sharesLiquid) return 0;\n\n        uint256 sharesToMint = sharesLiquid - sharesInFarm;\n        _mint(outlandFarm, sharesToMint);\n        return sharesToMint;\n    }\n\n    /// @notice Syncs the L2 token supplies to the vault\n    /// @param _receiptTokenTotalSupply New total supply of the L2 iUSD token reported by the L2 accounting\n    /// @param _stakedTokenTotalSupply New total supply of the L2 siUSD token reported by the L2 accounting\n    function _syncL2Supply(uint256 _receiptTokenTotalSupply, uint256 _stakedTokenTotalSupply) internal {\n        // reconcile iUSD supply\n        uint256 currentReceiptTokens = ReceiptToken(receiptToken).balanceOf(address(this));\n        uint256 receiptTokensToMint;\n        // if there are more on L1 than on L2, burn the extra\n        if (currentReceiptTokens > _receiptTokenTotalSupply) {\n            uint256 receiptTokensToBurn = currentReceiptTokens - _receiptTokenTotalSupply;\n            ReceiptToken(receiptToken).burn(receiptTokensToBurn);\n        }\n        // if there are less on L1 than on L2, mint the missing amount\n        else if (currentReceiptTokens < _receiptTokenTotalSupply) {\n            receiptTokensToMint = _receiptTokenTotalSupply - currentReceiptTokens;\n        }\n\n        // reconcile siUSD supply\n        uint256 currentStakedTokens = ERC20(stakedToken).balanceOf(address(this));\n        // if there are more on L1 than on L2, unstake the extra & burn the underlying iUSD\n        if (currentStakedTokens > _stakedTokenTotalSupply) {\n            uint256 stakedTokensToBurn = currentStakedTokens - _stakedTokenTotalSupply;\n            // unstake siUSD\n            ERC20(stakedToken).forceApprove(gateway, stakedTokensToBurn);\n            uint256 receiptTokens = IInfiniFiGateway(gateway).unstake(address(this), stakedTokensToBurn);\n            // burn iUSD\n            ReceiptToken(receiptToken).burn(receiptTokens);\n        }\n        // if there are less on L1 than on L2, mint and stake iUSD to mint the missing amount (round up)\n        else if (currentStakedTokens < _stakedTokenTotalSupply) {\n            uint256 stakedTokensToMint = _stakedTokenTotalSupply - currentStakedTokens;\n            // mint iUSD, add 1 wei for rounding\n            uint256 receiptTokens = IInfiniFiGateway(gateway).stakedToReceipt(stakedTokensToMint) + 1;\n            ReceiptToken(receiptToken).mint(address(this), receiptTokens);\n            // stake iUSD\n            ERC20(receiptToken).forceApprove(gateway, receiptTokens);\n            IInfiniFiGateway(gateway).stake(address(this), receiptTokens);\n        }\n\n        // Mint new loose iUSD after the siUSD reconciliation.\n        if (receiptTokensToMint > 0) {\n            ReceiptToken(receiptToken).mint(address(this), receiptTokensToMint);\n        }\n    }\n\n    /// @notice Internal hook that prevents transfers between non-zero addresses\n    /// @dev Overrides ERC20._update to make vault shares non-transferable\n    /// @dev Allows minting (from=0) and burning (to=0) but blocks regular transfers\n    /// @param _from Source address (zero for minting)\n    /// @param _to Destination address (zero for burning)\n    /// @param _value Amount of shares being transferred\n    function _update(address _from, address _to, uint256 _value) internal override {\n        if (_from != address(0) && _to != address(0)) {\n            revert TransfersNotAllowed();\n        }\n\n        super._update(_from, _to, _value);\n    }\n}\n"},{"file_path":"lib/LayerZero-v2/packages/layerzero-v2/evm/protocol/contracts/interfaces/IMessageLib.sol","source_code":"// SPDX-License-Identifier: MIT\n\npragma solidity >=0.8.0;\n\nimport { IERC165 } from \"@openzeppelin/contracts/utils/introspection/IERC165.sol\";\n\nimport { SetConfigParam } from \"./IMessageLibManager.sol\";\n\nenum MessageLibType {\n    Send,\n    Receive,\n    SendAndReceive\n}\n\ninterface IMessageLib is IERC165 {\n    function setConfig(address _oapp, SetConfigParam[] calldata _config) external;\n\n    function getConfig(uint32 _eid, address _oapp, uint32 _configType) external view returns (bytes memory config);\n\n    function isSupportedEid(uint32 _eid) external view returns (bool);\n\n    // message libs of same major version are compatible\n    function version() external view returns (uint64 major, uint8 minor, uint8 endpointVersion);\n\n    function messageLibType() external view returns (MessageLibType);\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":"lib/LayerZero-v2/packages/layerzero-v2/evm/oapp/contracts/oapp/OApp.sol","source_code":"// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.20;\n\n// @dev Import the 'MessagingFee' and 'MessagingReceipt' so it's exposed to OApp implementers\n// solhint-disable-next-line no-unused-import\nimport { OAppSender, MessagingFee, MessagingReceipt } from \"./OAppSender.sol\";\n// @dev Import the 'Origin' so it's exposed to OApp implementers\n// solhint-disable-next-line no-unused-import\nimport { OAppReceiver, Origin } from \"./OAppReceiver.sol\";\nimport { OAppCore } from \"./OAppCore.sol\";\n\n/**\n * @title OApp\n * @dev Abstract contract serving as the base for OApp implementation, combining OAppSender and OAppReceiver functionality.\n */\nabstract contract OApp is OAppSender, OAppReceiver {\n    /**\n     * @dev Constructor to initialize the OApp with the provided endpoint and owner.\n     * @param _endpoint The address of the LOCAL LayerZero endpoint.\n     * @param _delegate The delegate capable of making OApp configurations inside of the endpoint.\n     */\n    constructor(address _endpoint, address _delegate) OAppCore(_endpoint, _delegate) {}\n\n    /**\n     * @notice Retrieves the OApp version information.\n     * @return senderVersion The version of the OAppSender.sol implementation.\n     * @return receiverVersion The version of the OAppReceiver.sol implementation.\n     */\n    function oAppVersion()\n        public\n        pure\n        virtual\n        override(OAppSender, OAppReceiver)\n        returns (uint64 senderVersion, uint64 receiverVersion)\n    {\n        return (SENDER_VERSION, RECEIVER_VERSION);\n    }\n}\n"},{"file_path":"lib/LayerZero-v2/packages/layerzero-v2/evm/oapp/contracts/oapp/interfaces/IOAppReceiver.sol","source_code":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.20;\n\nimport { ILayerZeroReceiver, Origin } from \"@layerzerolabs/lz-evm-protocol-v2/contracts/interfaces/ILayerZeroReceiver.sol\";\n\ninterface IOAppReceiver is ILayerZeroReceiver {\n    /**\n     * @notice Indicates whether an address is an approved composeMsg sender to the Endpoint.\n     * @param _origin The origin information containing the source endpoint and sender address.\n     *  - srcEid: The source chain endpoint ID.\n     *  - sender: The sender address on the src chain.\n     *  - nonce: The nonce of the message.\n     * @param _message The lzReceive payload.\n     * @param _sender The sender address.\n     * @return isSender Is a valid sender.\n     *\n     * @dev Applications can optionally choose to implement a separate composeMsg sender that is NOT the bridging layer.\n     * @dev The default sender IS the OAppReceiver implementer.\n     */\n    function isComposeMsgSender(\n        Origin calldata _origin,\n        bytes calldata _message,\n        address _sender\n    ) external view returns (bool isSender);\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"},{"file_path":"src/libraries/RedemptionQueue.sol","source_code":"// SPDX-License-Identifier: MIT\npragma solidity 0.8.28;\n\n/// @notice library for the redemption queue\n/// @dev from OZ but with the least amount of features and also adding a\n/// way to update the front of the queue for partial fundings\nlibrary RedemptionQueue {\n    /// ------------------- ERRORS -------------------\n    error QueueIsFull();\n    error QueueIsEmpty();\n    error IndexOutOfBounds(uint256 _index);\n\n    /// @notice struct for a redemption request\n    /// fits in 32 bytes for storage efficiency\n    struct RedemptionRequest {\n        /// @notice the amount of receipt token (iUSD/iETH) waiting to be redeemed\n        /// @dev max value is 79.228B with 18 decimals, we assume no single redemption will be larger than this\n        uint96 amount; // 12 bytes\n        /// @notice the recipient of the redemption\n        address recipient; // 20 bytes\n    }\n\n    struct RedemptionRequestsQueue {\n        uint128 _begin;\n        uint128 _end;\n        mapping(uint128 index => RedemptionRequest) _data;\n    }\n\n    /// @notice Inserts a redemption request at the end of the queue.\n    function pushBack(RedemptionRequestsQueue storage _redemptionRequestsQueue, RedemptionRequest memory _value)\n        internal\n    {\n        unchecked {\n            uint128 backIndex = _redemptionRequestsQueue._end;\n            if (backIndex + 1 == _redemptionRequestsQueue._begin) {\n                revert QueueIsFull();\n            }\n\n            _redemptionRequestsQueue._data[backIndex] = _value;\n            _redemptionRequestsQueue._end = backIndex + 1;\n        }\n    }\n\n    /// @notice Removes the redemption request at the beginning of the queue and returns it.\n    function popFront(RedemptionRequestsQueue storage _redemptionRequestsQueue)\n        internal\n        returns (RedemptionRequest memory)\n    {\n        unchecked {\n            uint128 frontIndex = _redemptionRequestsQueue._begin;\n            if (frontIndex == _redemptionRequestsQueue._end) {\n                revert QueueIsEmpty();\n            }\n            RedemptionRequest memory value = _redemptionRequestsQueue._data[frontIndex];\n            delete _redemptionRequestsQueue._data[frontIndex];\n            _redemptionRequestsQueue._begin = frontIndex + 1;\n            return value;\n        }\n    }\n\n    /// @notice Updates the amount of the redemption request at the beginning of the queue.\n    function updateFront(RedemptionRequestsQueue storage _redemptionRequestsQueue, uint96 _newAmount) internal {\n        if (empty(_redemptionRequestsQueue)) {\n            revert QueueIsEmpty();\n        }\n\n        _redemptionRequestsQueue._data[_redemptionRequestsQueue._begin].amount = _newAmount;\n    }\n\n    /// @notice Returns the redemption request at the beginning of the queue, without removing it.\n    function front(RedemptionRequestsQueue storage _redemptionRequestsQueue)\n        internal\n        view\n        returns (RedemptionRequest memory)\n    {\n        if (empty(_redemptionRequestsQueue)) {\n            revert QueueIsEmpty();\n        }\n        return _redemptionRequestsQueue._data[_redemptionRequestsQueue._begin];\n    }\n\n    /// @notice Returns the number of items in the queue.\n    function length(RedemptionRequestsQueue storage _redemptionRequestsQueue) internal view returns (uint256) {\n        unchecked {\n            return uint256(_redemptionRequestsQueue._end - _redemptionRequestsQueue._begin);\n        }\n    }\n\n    /// @notice Return the redemption request at a position in the queue given by `index`,\n    /// with the first item at 0 and last item at `length(deque) - 1`.\n    function at(RedemptionRequestsQueue storage _redemptionRequestsQueue, uint256 _index)\n        internal\n        view\n        returns (RedemptionRequest memory)\n    {\n        if (_index >= length(_redemptionRequestsQueue)) {\n            revert IndexOutOfBounds(_index);\n        }\n        // By construction, length is a uint128, so the check above ensures that index can be safely downcast to uint128\n        unchecked {\n            // forge-lint: disable-next-line(unsafe-typecast)\n            return _redemptionRequestsQueue._data[_redemptionRequestsQueue._begin + uint128(_index)];\n        }\n    }\n\n    /// @notice returns true if the queue is empty.\n    function empty(RedemptionRequestsQueue storage _redemptionRequestsQueue) internal view returns (bool) {\n        return _redemptionRequestsQueue._end == _redemptionRequestsQueue._begin;\n    }\n}\n"},{"file_path":"lib/LayerZero-v2/packages/layerzero-v2/evm/protocol/contracts/libs/AddressCast.sol","source_code":"// SPDX-License-Identifier: LZBL-1.2\n\npragma solidity ^0.8.20;\n\nlibrary AddressCast {\n    error AddressCast_InvalidSizeForAddress();\n    error AddressCast_InvalidAddress();\n\n    function toBytes32(bytes calldata _addressBytes) internal pure returns (bytes32 result) {\n        if (_addressBytes.length > 32) revert AddressCast_InvalidAddress();\n        result = bytes32(_addressBytes);\n        unchecked {\n            uint256 offset = 32 - _addressBytes.length;\n            result = result >> (offset * 8);\n        }\n    }\n\n    function toBytes32(address _address) internal pure returns (bytes32 result) {\n        result = bytes32(uint256(uint160(_address)));\n    }\n\n    function toBytes(bytes32 _addressBytes32, uint256 _size) internal pure returns (bytes memory result) {\n        if (_size == 0 || _size > 32) revert AddressCast_InvalidSizeForAddress();\n        result = new bytes(_size);\n        unchecked {\n            uint256 offset = 256 - _size * 8;\n            assembly {\n                mstore(add(result, 32), shl(offset, _addressBytes32))\n            }\n        }\n    }\n\n    function toAddress(bytes32 _addressBytes32) internal pure returns (address result) {\n        result = address(uint160(uint256(_addressBytes32)));\n    }\n\n    function toAddress(bytes calldata _addressBytes) internal pure returns (address result) {\n        if (_addressBytes.length != 20) revert AddressCast_InvalidAddress();\n        result = address(bytes20(_addressBytes));\n    }\n}\n"}],"is_verified_via_sourcify":true,"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":"InfiniFiGatewayV4","creation_bytecode":"0x6080604052348015600e575f5ffd5b505f8054610100600160a81b031916610100179055614a57806100305f395ff3fe608060405260043610610233575f3560e01c80639b2ea4bd11610129578063c2a672e0116100a8578063ed4254ec1161006d578063ed4254ec1461066e578063f2f4eb261461068d578063f3fef3a3146106ae578063f5d954c0146106cd578063fa60e9ba146106ec575f5ffd5b8063c2a672e0146105df578063caab435f146105fe578063d59150961461061d578063d667ba301461063c578063d95ce53b1461064f575f5ffd5b8063bf0673d2116100ee578063bf0673d21461053f578063bf40fac114610554578063c00716ea14610573578063c1d9fe3e14610592578063c23544ad146105b1575f5ffd5b80639b2ea4bd146104af578063a16ba4e0146104ce578063a5a85b8d146104e2578063aa030aff14610501578063adc9772e14610520575f5ffd5b80634ec78381116101b55780637df3927e1161017a5780637df3927e1461041e5780637edd1a7e1461043e578063800096301461045d5780638456cb591461047c5780638f5cba2b14610490575f5ffd5b80634ec783811461035f5780635c975abb1461037e578063699f200f146103a05780637b4aedcf146103ec5780637b96eef1146103ff575f5ffd5b80632e1a7d4d116101fb5780632e1a7d4d146102e7578063365f1c00146103065780633f4ba83a1461031957806340c10f191461032d5780634a6bdbbe1461034c575f5ffd5b806319ab453c146102375780631a11dc4c14610258578063230ae89c1461027757806326cf8338146102a95780632b83cccd146102c8575b5f5ffd5b348015610242575f5ffd5b5061025661025136600461400f565b61070b565b005b348015610263575f5ffd5b50610256610272366004614042565b610734565b348015610282575f5ffd5b5061029661029136600461406c565b6107ec565b6040519081526020015b60405180910390f35b3480156102b4575f5ffd5b506102966102c3366004614096565b610bcd565b3480156102d3575f5ffd5b506102966102e23660046140d1565b610e88565b3480156102f2575f5ffd5b50610256610301366004614103565b6110a1565b61029661031436600461415f565b611150565b348015610324575f5ffd5b506102566113c4565b348015610338575f5ffd5b5061029661034736600461406c565b61149c565b61029661035a3660046141df565b611609565b34801561036a575f5ffd5b506102566103793660046142b2565b611756565b348015610389575f5ffd5b505f5460ff165b60405190151581526020016102a0565b3480156103ab575f5ffd5b506103d46103ba366004614103565b60016020525f90815260409020546001600160a01b031681565b6040516001600160a01b0390911681526020016102a0565b6102966103fa36600461415f565b6118b9565b34801561040a575f5ffd5b5061025661041936600461438d565b61195d565b61043161042c3660046143c4565b611a9c565b6040516102a09190614431565b348015610449575f5ffd5b50610256610458366004614042565b611d1e565b348015610468575f5ffd5b5061025661047736600461400f565b611ee8565b348015610487575f5ffd5b50610256611fc1565b34801561049b575f5ffd5b506102566104aa366004614042565b612099565b3480156104ba575f5ffd5b506102566104c9366004614533565b6120d4565b3480156104d9575f5ffd5b5061025661225a565b3480156104ed575f5ffd5b506102566104fc366004614103565b6122fb565b34801561050c575f5ffd5b5061025661051b366004614042565b612435565b34801561052b575f5ffd5b5061029661053a36600461406c565b61260a565b34801561054a575f5ffd5b5061029660035481565b34801561055f575f5ffd5b506103d461056e366004614577565b61290b565b34801561057e575f5ffd5b5061025661058d366004614042565b612954565b34801561059d575f5ffd5b506102566105ac3660046145f2565b612997565b3480156105bc575f5ffd5b506103906105cb36600461400f565b60026020525f908152604090205460ff1681565b3480156105ea575f5ffd5b506102966105f936600461406c565b612a4c565b348015610609575f5ffd5b5061025661061836600461406c565b612cb1565b348015610628575f5ffd5b50610256610637366004614684565b612d23565b61025661064a3660046146be565b612f3f565b34801561065a575f5ffd5b50610296610669366004614096565b6130d0565b348015610679575f5ffd5b50610256610688366004614719565b6133c1565b348015610698575f5ffd5b505f5461010090046001600160a01b03166103d4565b3480156106b9575f5ffd5b506102566106c836600461406c565b61355e565b3480156106d8575f5ffd5b506102966106e7366004614756565b6135a8565b3480156106f7575f5ffd5b50610256610706366004614684565b613757565b5f5461010090046001600160a01b031615610728576107286147ab565b61073181613793565b50565b61073c6137f8565b61074461381b565b610776604051806040016040528060118152602001703637b1b5b4b733a1b7b73a3937b63632b960791b81525061290b565b6040516304b92b4d60e31b81523360048201526024810184905263ffffffff831660448201526001600160a01b0391909116906325c95a68906064015b5f604051808303815f87803b1580156107ca575f5ffd5b505af11580156107dc573d5f5f3e3d5ffd5b505050506107e8613850565b5050565b5f6107f56137f8565b6107fd61381b565b5f61082d6040518060400160405280600e81526020016d36b4b73a21b7b73a3937b63632b960911b81525061290b565b90505f61085c6040518060400160405280600b81526020016a39ba30b5b2b22a37b5b2b760a91b81525061290b565b90505f61088c6040518060400160405280600c81526020016b3932b1b2b4b83a2a37b5b2b760a11b81525061290b565b90505f6108b4604051806040016040528060048152602001635553444360e01b81525061290b565b90505f6108e46040518060400160405280600c81526020016b7969656c6453686172696e6760a01b81525061290b565b90506108fb6001600160a01b03831633308a61387a565b60405163095ea7b360e01b81526001600160a01b0386811660048301526024820189905283169063095ea7b3906044016020604051808303815f875af1158015610947573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061096b91906147bf565b506040516340c10f1960e01b8152306004820152602481018890525f906001600160a01b038716906340c10f19906044016020604051808303815f875af11580156109b8573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906109dc91906147da565b9050816001600160a01b0316631d6e11f26040518163ffffffff1660e01b81526004015f604051808303815f87803b158015610a16575f5ffd5b505af1158015610a28573d5f5f3e3d5ffd5b5050604051630341728760e01b8152600160048201526001600160a01b0385169250630341728791506024015f604051808303815f87803b158015610a6b575f5ffd5b505af1158015610a7d573d5f5f3e3d5ffd5b505060405163095ea7b360e01b81526001600160a01b038881166004830152602482018590528716925063095ea7b391506044016020604051808303815f875af1158015610acd573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610af191906147bf565b50604051636e553f6560e01b8152600481018290526001600160a01b038a81166024830152861690636e553f65906044016020604051808303815f875af1158015610b3e573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610b6291906147da565b50604051630341728760e01b81525f60048201526001600160a01b038316906303417287906024015f604051808303815f87803b158015610ba1575f5ffd5b505af1158015610bb3573d5f5f3e3d5ffd5b509298505050505050505050610bc7613850565b92915050565b5f610bd66137f8565b610bde61381b565b5f610c0e6040518060400160405280600e81526020016d36b4b73a21b7b73a3937b63632b960911b81525061290b565b90505f610c3e6040518060400160405280600c81526020016b3932b1b2b4b83a2a37b5b2b760a11b81525061290b565b90505f610c73604051806040016040528060118152602001703637b1b5b4b733a1b7b73a3937b63632b960791b81525061290b565b90505f610c9b604051806040016040528060048152602001635553444360e01b81525061290b565b9050610cb26001600160a01b03821633308a61387a565b60405163095ea7b360e01b81526001600160a01b0385811660048301526024820189905282169063095ea7b3906044016020604051808303815f875af1158015610cfe573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610d2291906147bf565b506040516340c10f1960e01b8152306004820152602481018890525f906001600160a01b038616906340c10f19906044016020604051808303815f875af1158015610d6f573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610d9391906147da565b60405163095ea7b360e01b81526001600160a01b038581166004830152602482018390529192509085169063095ea7b3906044015b6020604051808303815f875af1158015610de4573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610e0891906147bf565b50604051633b50953b60e21b81526004810182905263ffffffff881660248201526001600160a01b038a8116604483015284169063ed4254ec906064015f604051808303815f87803b158015610e5c575f5ffd5b505af1158015610e6e573d5f5f3e3d5ffd5b5092975050505050505050610e81613850565b9392505050565b5f610e916137f8565b610e9961381b565b610ea16138b6565b5f610ecf6040518060400160405280600c81526020016b3932b1b2b4b83a2a37b5b2b760a11b81525061290b565b90505f610f036040518060400160405280601081526020016f3932b232b2b6a1b7b73a3937b63632b960811b81525061290b565b6040516323b872dd60e01b8152336004820152306024820152604481018790529091506001600160a01b038316906323b872dd906064016020604051808303815f875af1158015610f56573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610f7a91906147bf565b5060405163095ea7b360e01b81526001600160a01b0382811660048301526024820187905283169063095ea7b3906044016020604051808303815f875af1158015610fc7573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610feb91906147bf565b506040516301e9a69560e41b81526001600160a01b038781166004830152602482018790525f9190831690631e9a6950906044016020604051808303815f875af115801561103b573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061105f91906147da565b9050848181811015611092576040516316b4038160e21b8152600481019290925260248201526044015b60405180910390fd5b50909350505050610e81613850565b6110a96137f8565b6110b161381b565b6110b96138b6565b6110eb604051806040016040528060118152602001703637b1b5b4b733a1b7b73a3937b63632b960791b81525061290b565b60405163f3fef3a360e01b8152336004820152602481018390526001600160a01b03919091169063f3fef3a3906044015f604051808303815f87803b158015611132575f5ffd5b505af1158015611144573d5f5f3e3d5ffd5b50505050610731613850565b5f6111596137f8565b61116161381b565b5f5f6111708989898989613966565b915091505f6111a16040518060400160405280600b81526020016a39ba30b5b2b22a37b5b2b760a91b81525061290b565b90505f6111d16040518060400160405280600c81526020016b7969656c6453686172696e6760a01b81525061290b565b9050806001600160a01b0316631d6e11f26040518163ffffffff1660e01b81526004015f604051808303815f87803b15801561120b575f5ffd5b505af115801561121d573d5f5f3e3d5ffd5b5050604051630341728760e01b8152600160048201526001600160a01b0384169250630341728791506024015f604051808303815f87803b158015611260575f5ffd5b505af1158015611272573d5f5f3e3d5ffd5b505060405163095ea7b360e01b81526001600160a01b038581166004830152602482018890528616925063095ea7b391506044016020604051808303815f875af11580156112c2573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906112e691906147bf565b50604051636e553f6560e01b8152600481018590526001600160a01b038781166024830152831690636e553f65906044016020604051808303815f875af1158015611333573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061135791906147da565b50604051630341728760e01b81525f60048201526001600160a01b038216906303417287906024015f604051808303815f87803b158015611396575f5ffd5b505af11580156113a8573d5f5f3e3d5ffd5b509596505050505050506113ba613850565b9695505050505050565b5f54604051632474521560e21b81527fe7276a2a84d8de556657ec9cf93a55a7d66f096e529d0582ed08e9e2208b92b5600482018190523360248301529161010090046001600160a01b0316906391d1485490604401602060405180830381865afa158015611435573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061145991906147bf565b6114945760405162461bcd60e51b815260206004820152600c60248201526b15539055551213d49256915160a21b6044820152606401611089565b610731613d8d565b5f6114a56137f8565b6114ad61381b565b5f6114d3604051806040016040528060048152602001635553444360e01b81525061290b565b90505f6115056040518060400160405280600e81526020016d36b4b73a21b7b73a3937b63632b960911b81525061290b565b905061151c6001600160a01b03831633308761387a565b60405163095ea7b360e01b81526001600160a01b0382811660048301526024820186905283169063095ea7b3906044016020604051808303815f875af1158015611568573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061158c91906147bf565b506040516340c10f1960e01b81526001600160a01b038681166004830152602482018690528216906340c10f19906044016020604051808303815f875af11580156115d9573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906115fd91906147da565b92505050610bc7613850565b5f6116126137f8565b61161a61381b565b5f5f6116298a8a8a8a8a613966565b915091505f611660604051806040016040528060118152602001703637b1b5b4b733a1b7b73a3937b63632b960791b81525061290b565b60405163095ea7b360e01b81526001600160a01b038083166004830152602482018690529192509083169063095ea7b3906044016020604051808303815f875af11580156116b0573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906116d491906147bf565b50604051633b50953b60e21b81526004810184905263ffffffff871660248201526001600160a01b03868116604483015282169063ed4254ec906064015f604051808303815f87803b158015611728575f5ffd5b505af115801561173a573d5f5f3e3d5ffd5b50949550505050505061174b613850565b979650505050505050565b61175e6137f8565b61176661381b565b5f6117986040518060400160405280601081526020016f616c6c6f636174696f6e566f74696e6760801b81525061290b565b90505f5b888110156118a557816001600160a01b0316632610409b338c8c858181106117c6576117c66147f1565b90506020020160208101906117db919061400f565b8b8b868181106117ed576117ed6147f1565b90506020020160208101906118029190614805565b8a8a87818110611814576118146147f1565b9050602002810190611826919061481e565b8a8a89818110611838576118386147f1565b905060200281019061184a919061481e565b6040518863ffffffff1660e01b815260040161186c97969594939291906148d1565b5f604051808303815f87803b158015611883575f5ffd5b505af1158015611895573d5f5f3e3d5ffd5b50506001909201915061179c9050565b50506118af613850565b5050505050505050565b5f6118c26137f8565b6118ca61381b565b5f5f6118d98989898989613966565b60405163a9059cbb60e01b81526001600160a01b038781166004830152602482018490529294509092509082169063a9059cbb906044016020604051808303815f875af115801561192c573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061195091906147bf565b50909150506113ba613850565b5f54604051632474521560e21b81527f3947e2f542c6c46c543fa4f79cbd1e27fea37ed249bc3caf992570d19123642e600482018190523360248301529161010090046001600160a01b0316906391d1485490604401602060405180830381865afa1580156119ce573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906119f291906147bf565b611a2d5760405162461bcd60e51b815260206004820152600c60248201526b15539055551213d49256915160a21b6044820152606401611089565b6001600160a01b0383165f81815260026020908152604091829020805460ff1916861515908117909155825142815291820193909352908101919091527faf11e799c0dfe70b6ee7eeeb1e99889edf753033f557a3a5568838bdc770a08b9060600160405180910390a1505050565b5f54604051632474521560e21b81527f1a6838efa4183e08fe3607359d1259272af9d4716f65e1a7b5921f78fd5a3c6a6004820181905233602483015260609290916101009091046001600160a01b0316906391d1485490604401602060405180830381865afa158015611b12573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611b3691906147bf565b611b715760405162461bcd60e51b815260206004820152600c60248201526b15539055551213d49256915160a21b6044820152606401611089565b8267ffffffffffffffff811115611b8a57611b8a614494565b604051908082528060200260200182016040528015611bbd57816020015b6060815260200190600190039081611ba85790505b5091505f5b83811015611d16575f858583818110611bdd57611bdd6147f1565b9050602002810190611bef919061492f565b611bfd90602081019061400f565b90505f868684818110611c1257611c126147f1565b9050602002810190611c24919061492f565b602001359050365f888886818110611c3e57611c3e6147f1565b9050602002810190611c50919061492f565b611c5e90604081019061494d565b915091505f5f856001600160a01b0316858585604051611c7f929190614990565b5f6040518083038185875af1925050503d805f8114611cb9576040519150601f19603f3d011682016040523d82523d5f602084013e611cbe565b606091505b5091509150818190611ce457604051634ad176bb60e01b8152600401611089919061499f565b5080898881518110611cf857611cf86147f1565b60200260200101819052505050505050508080600101915050611bc2565b505092915050565b611d266137f8565b611d2e61381b565b5f611d5f6040518060400160405280600f81526020016e33b7bb32b93730b731b2aa37b5b2b760891b81525061290b565b90505f611d8d6040518060400160405280601b81526020015f516020614a025f395f51905f5281525061290b565b6040516323b872dd60e01b8152336004820152306024820152604481018690529091506001600160a01b038316906323b872dd906064016020604051808303815f875af1158015611de0573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611e0491906147bf565b5060405163095ea7b360e01b81526001600160a01b0382811660048301526024820186905283169063095ea7b3906044016020604051808303815f875af1158015611e51573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611e7591906147bf565b50604051633b50953b60e21b81526004810185905263ffffffff841660248201523360448201526001600160a01b0382169063ed4254ec906064015b5f604051808303815f87803b158015611ec8575f5ffd5b505af1158015611eda573d5f5f3e3d5ffd5b5050505050506107e8613850565b5f54604051632474521560e21b81527f1a6838efa4183e08fe3607359d1259272af9d4716f65e1a7b5921f78fd5a3c6a600482018190523360248301529161010090046001600160a01b0316906391d1485490604401602060405180830381865afa158015611f59573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611f7d91906147bf565b611fb85760405162461bcd60e51b815260206004820152600c60248201526b15539055551213d49256915160a21b6044820152606401611089565b6107e882613793565b5f54604051632474521560e21b81527ffcb9fcbfa83b897fb2d5cf4b58962164105c1e71489a37ef3ae0db3fdce576f6600482018190523360248301529161010090046001600160a01b0316906391d1485490604401602060405180830381865afa158015612032573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061205691906147bf565b6120915760405162461bcd60e51b815260206004820152600c60248201526b15539055551213d49256915160a21b6044820152606401611089565b610731613dde565b6120a16137f8565b6120a961381b565b6107766040518060400160405280601b81526020015f516020614a025f395f51905f5281525061290b565b5f54604051632474521560e21b81527f1a6838efa4183e08fe3607359d1259272af9d4716f65e1a7b5921f78fd5a3c6a600482018190523360248301529161010090046001600160a01b0316906391d1485490604401602060405180830381865afa158015612145573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061216991906147bf565b6121a45760405162461bcd60e51b815260206004820152600c60248201526b15539055551213d49256915160a21b6044820152606401611089565b8160015f856040516020016121b9919061499f565b6040516020818303038152906040528051906020012081526020019081526020015f205f6101000a8154816001600160a01b0302191690836001600160a01b031602179055508260405161220d91906149b1565b604080519182900382204283526001600160a01b0385166020840152917f34765092fb4826a2f48dae7ee370790341f5fe0147f013fca4108e6ea65a68ed910160405180910390a2505050565b6122626137f8565b61226a61381b565b61229b6040518060400160405280601081526020016f3932b232b2b6a1b7b73a3937b63632b960811b81525061290b565b60405163c0598b0d60e01b81523360048201526001600160a01b03919091169063c0598b0d906024015f604051808303815f87803b1580156122db575f5ffd5b505af11580156122ed573d5f5f3e3d5ffd5b505050506122f9613850565b565b5f54604051632474521560e21b81527f3947e2f542c6c46c543fa4f79cbd1e27fea37ed249bc3caf992570d19123642e600482018190523360248301529161010090046001600160a01b0316906391d1485490604401602060405180830381865afa15801561236c573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061239091906147bf565b6123cb5760405162461bcd60e51b815260206004820152600c60248201526b15539055551213d49256915160a21b6044820152606401611089565b662386f26fc100008211156123f357604051636b3ff80760e01b815260040160405180910390fd5b600382905560408051428152602081018490527f675607ea61b02df8e5abbbe4772c0b60bb371fa80782206f2efa1b31e37311eb910160405180910390a15050565b61243d6137f8565b61244561381b565b5f6124716040518060400160405280601b81526020015f516020614a025f395f51905f5281525061290b565b60405163e7dda2eb60e01b815263ffffffff841660048201529091505f906001600160a01b0383169063e7dda2eb90602401602060405180830381865afa1580156124be573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906124e291906149c7565b6040516323b872dd60e01b8152336004820152306024820152604481018690529091506001600160a01b038216906323b872dd906064016020604051808303815f875af1158015612535573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061255991906147bf565b5060405163095ea7b360e01b81526001600160a01b0383811660048301526024820186905282169063095ea7b3906044016020604051808303815f875af11580156125a6573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906125ca91906147bf565b50604051637f866a0d60e01b81526004810185905263ffffffff841660248201523360448201526001600160a01b03831690637f866a0d90606401611eb1565b5f6126136137f8565b61261b61381b565b5f6126486040518060400160405280600b81526020016a39ba30b5b2b22a37b5b2b760a91b81525061290b565b90505f6126786040518060400160405280600c81526020016b3932b1b2b4b83a2a37b5b2b760a11b81525061290b565b90505f6126a86040518060400160405280600c81526020016b7969656c6453686172696e6760a01b81525061290b565b6040516323b872dd60e01b8152336004820152306024820152604481018790529091506001600160a01b038316906323b872dd906064016020604051808303815f875af11580156126fb573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061271f91906147bf565b5060405163095ea7b360e01b81526001600160a01b0384811660048301526024820187905283169063095ea7b3906044016020604051808303815f875af115801561276c573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061279091906147bf565b50806001600160a01b0316631d6e11f26040518163ffffffff1660e01b81526004015f604051808303815f87803b1580156127c9575f5ffd5b505af11580156127db573d5f5f3e3d5ffd5b5050604051630341728760e01b8152600160048201526001600160a01b0384169250630341728791506024015f604051808303815f87803b15801561281e575f5ffd5b505af1158015612830573d5f5f3e3d5ffd5b5050604051636e553f6560e01b8152600481018890526001600160a01b0389811660248301525f935086169150636e553f65906044016020604051808303815f875af1158015612882573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906128a691906147da565b604051630341728760e01b81525f60048201529091506001600160a01b038316906303417287906024015f604051808303815f87803b1580156128e7575f5ffd5b505af11580156128f9573d5f5f3e3d5ffd5b50929650505050505050610bc7613850565b5f60015f83604051602001612920919061499f565b60408051601f198184030181529181528151602092830120835290820192909252015f20546001600160a01b031692915050565b61295c6137f8565b61296461381b565b5f612471604051806040016040528060118152602001703637b1b5b4b733a1b7b73a3937b63632b960791b81525061290b565b61299f6137f8565b6129a761381b565b6129d86040518060400160405280601081526020016f616c6c6f636174696f6e566f74696e6760801b81525061290b565b6001600160a01b0316632610409b338888888888886040518863ffffffff1660e01b8152600401612a0f97969594939291906148d1565b5f604051808303815f87803b158015612a26575f5ffd5b505af1158015612a38573d5f5f3e3d5ffd5b50505050612a44613850565b505050505050565b5f612a556137f8565b612a5d61381b565b5f612a8a6040518060400160405280600b81526020016a39ba30b5b2b22a37b5b2b760a91b81525061290b565b90505f612aba6040518060400160405280600c81526020016b7969656c6453686172696e6760a01b81525061290b565b6040516323b872dd60e01b8152336004820152306024820152604481018690529091506001600160a01b038316906323b872dd906064016020604051808303815f875af1158015612b0d573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612b3191906147bf565b50806001600160a01b0316631d6e11f26040518163ffffffff1660e01b81526004015f604051808303815f87803b158015612b6a575f5ffd5b505af1158015612b7c573d5f5f3e3d5ffd5b5050604051630341728760e01b8152600160048201526001600160a01b0384169250630341728791506024015f604051808303815f87803b158015612bbf575f5ffd5b505af1158015612bd1573d5f5f3e3d5ffd5b5050604051635d043b2960e11b8152600481018790526001600160a01b0388811660248301523060448301525f93508516915063ba087652906064016020604051808303815f875af1158015612c29573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612c4d91906147da565b604051630341728760e01b81525f60048201529091506001600160a01b038316906303417287906024015f604051808303815f87803b158015612c8e575f5ffd5b505af1158015612ca0573d5f5f3e3d5ffd5b509295505050505050610bc7613850565b612cb96137f8565b612cc161381b565b612cec6040518060400160405280601b81526020015f516020614a025f395f51905f5281525061290b565b60405163f3fef3a360e01b81526001600160a01b03848116600483015260248201849052919091169063f3fef3a3906044016107b3565b612d2b6137f8565b612d3361381b565b5f612d66604051806040016040528060118152602001703637b1b5b4b733a1b7b73a3937b63632b960791b81525061290b565b60405163e7dda2eb60e01b815263ffffffff861660048201529091505f906001600160a01b0383169063e7dda2eb90602401602060405180830381865afa158015612db3573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612dd791906149c7565b6040516323b872dd60e01b8152336004820152306024820152604481018590529091506001600160a01b038216906323b872dd906064016020604051808303815f875af1158015612e2a573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612e4e91906147bf565b5060405163095ea7b360e01b81526001600160a01b0383811660048301526024820185905282169063095ea7b3906044016020604051808303815f875af1158015612e9b573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612ebf91906147bf565b5060405163c4acfb8f60e01b81526004810184905263ffffffff8087166024830152851660448201523360648201526001600160a01b0383169063c4acfb8f906084015b5f604051808303815f87803b158015612f1a575f5ffd5b505af1158015612f2c573d5f5f3e3d5ffd5b505050505050612f3a613850565b505050565b612f476137f8565b612f4f61381b565b5f612f7a604051806040016040528060098152602001683837b93a30b6243ab160b91b81525061290b565b60405163d7014c6960e01b8152600481018890526001600160a01b0384811660248301529192505f9183169063d7014c6990604401602060405180830381865afa158015612fca573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612fee91906147da565b905080348181101561301c57604051631c83182560e01b815260048101929092526024820152604401611089565b5061303490506001600160a01b03871633308861387a565b6130486001600160a01b0387168387613e1a565b604051630d667ba360e41b8152600481018890526001600160a01b038781166024830152604482018790528581166064830152848116608483015283169063d667ba3090349060a4015f604051808303818588803b1580156130a8575f5ffd5b505af11580156130ba573d5f5f3e3d5ffd5b505050505050506130c9613850565b5050505050565b5f6130d96137f8565b6130e161381b565b5f61310f6040518060400160405280600c81526020016b3932b1b2b4b83a2a37b5b2b760a11b81525061290b565b90505f61313e6040518060400160405280600b81526020016a39ba30b5b2b22a37b5b2b760a91b81525061290b565b90505f613173604051806040016040528060118152602001703637b1b5b4b733a1b7b73a3937b63632b960791b81525061290b565b90505f6131a36040518060400160405280600c81526020016b7969656c6453686172696e6760a01b81525061290b565b6040516323b872dd60e01b8152336004820152306024820152604481018990529091506001600160a01b038416906323b872dd906064016020604051808303815f875af11580156131f6573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061321a91906147bf565b50806001600160a01b0316631d6e11f26040518163ffffffff1660e01b81526004015f604051808303815f87803b158015613253575f5ffd5b505af1158015613265573d5f5f3e3d5ffd5b5050604051630341728760e01b8152600160048201526001600160a01b0384169250630341728791506024015f604051808303815f87803b1580156132a8575f5ffd5b505af11580156132ba573d5f5f3e3d5ffd5b5050604051635d043b2960e11b8152600481018a9052306024820181905260448201525f92506001600160a01b038616915063ba087652906064016020604051808303815f875af1158015613311573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061333591906147da565b604051630341728760e01b81525f60048201529091506001600160a01b038316906303417287906024015f604051808303815f87803b158015613376575f5ffd5b505af1158015613388573d5f5f3e3d5ffd5b505060405163095ea7b360e01b81526001600160a01b038681166004830152602482018590528816925063095ea7b39150604401610dc8565b6133c96137f8565b6133d161381b565b5f6133ff6040518060400160405280600c81526020016b3932b1b2b4b83a2a37b5b2b760a11b81525061290b565b90505f613434604051806040016040528060118152602001703637b1b5b4b733a1b7b73a3937b63632b960791b81525061290b565b6040516323b872dd60e01b8152336004820152306024820152604481018790529091506001600160a01b038316906323b872dd906064016020604051808303815f875af1158015613487573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906134ab91906147bf565b5060405163095ea7b360e01b81526001600160a01b0382811660048301526024820187905283169063095ea7b3906044016020604051808303815f875af11580156134f8573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061351c91906147bf565b50604051633b50953b60e21b81526004810186905263ffffffff851660248201526001600160a01b03848116604483015282169063ed4254ec90606401612f03565b6135666137f8565b61356e61381b565b6135766138b6565b612cec604051806040016040528060118152602001703637b1b5b4b733a1b7b73a3937b63632b960791b81525061290b565b5f6135b16137f8565b6135b961381b565b5f8590505f6135fc6040518060400160405280601381526020017f6d6967726174696f6e436f6e74726f6c6c65720000000000000000000000000081525061290b565b90506136136001600160a01b03831633308961387a565b60405163095ea7b360e01b81526001600160a01b0382811660048301526024820188905283169063095ea7b3906044016020604051808303815f875af115801561365f573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061368391906147bf565b5060405163230bf88b60e11b81523360048201526001600160a01b03898116602483015288811660448301526064820188905263ffffffff871660848301525f9190831690634617f1169060a4016020604051808303815f875af11580156136ed573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061371191906147da565b905084818181101561373f576040516316b4038160e21b815260048101929092526024820152604401611089565b5090935050505061374e613850565b95945050505050565b61375f6137f8565b61376761381b565b5f612d666040518060400160405280601b81526020015f516020614a025f395f51905f5281525061290b565b5f80546001600160a01b0383811661010081810274ffffffffffffffffffffffffffffffffffffffff0019851617855560405193049190911692909183917f9209b7c8c06dcfd261686a663e7c55989337b18d59da5433c6f2835fb697092091a35050565b5f5460ff16156122f95760405163d93c066560e01b815260040160405180910390fd5b613823613e94565b6122f960017f9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f005b90613ed4565b6122f95f7f9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f0061384a565b613888848484846001613edb565b6138b057604051635274afe760e01b81526001600160a01b0385166004820152602401611089565b50505050565b5f6138e46040518060400160405280600c81526020016b7969656c6453686172696e6760a01b81525061290b565b90505f816001600160a01b031663f843336c6040518163ffffffff1660e01b8152600401602060405180830381865afa158015613923573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061394791906147da565b121561073157604051630e4a65c960e21b815260040160405180910390fd5b6001600160a01b0383165f90815260026020526040812054819060ff166139a057604051631f3eeae760e01b815260040160405180910390fd5b6001600160a01b03871673eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee146139ed576139d96001600160a01b03881633308961387a565b6139ed6001600160a01b0388168688613e1a565b5f856001600160a01b0316348686604051613a09929190614990565b5f6040518083038185875af1925050503d805f8114613a43576040519150601f19603f3d011682016040523d82523d5f602084013e613a48565b606091505b5050905080613a6a5760405163081ceff360e41b815260040160405180910390fd5b5f613a9a6040518060400160405280600e81526020016d36b4b73a21b7b73a3937b63632b960911b81525061290b565b90505f613ac2604051806040016040528060048152602001635553444360e01b81525061290b565b90505f613af26040518060400160405280600c81526020016b3932b1b2b4b83a2a37b5b2b760a11b81525061290b565b6040516370a0823160e01b81523060048201529091505f906001600160a01b038416906370a0823190602401602060405180830381865afa158015613b39573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190613b5d91906147da565b60405163095ea7b360e01b81526001600160a01b038681166004830152602482018390529192509084169063095ea7b3906044016020604051808303815f875af1158015613bad573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190613bd191906147bf565b506040516340c10f1960e01b8152306004820152602481018290525f906001600160a01b038616906340c10f19906044016020604051808303815f875af1158015613c1e573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190613c4291906147da565b6003549091508015613d2c575f613c598383613f48565b9050613c6581846149e2565b9250846001600160a01b031663a9059cbb613ca36040518060400160405280600c81526020016b7969656c6453686172696e6760a01b81525061290b565b6040517fffffffff0000000000000000000000000000000000000000000000000000000060e084901b1681526001600160a01b039091166004820152602481018490526044016020604051808303815f875af1158015613d05573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190613d2991906147bf565b50505b5060408051428152602081018e90529081018290526001600160a01b038e169033907f864d8445691e89cf27c9d9cc6155ad638a9833f28365127ad89aa779a6d3cf839060600160405180910390a39c919b50909950505050505050505050565b613d95613f5c565b5f805460ff191690557f5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa335b6040516001600160a01b03909116815260200160405180910390a1565b613de66137f8565b5f805460ff191660011790557f62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a258613dc13390565b613e268383835f613f7e565b612f3a57613e3783835f6001613f7e565b613e5f57604051635274afe760e01b81526001600160a01b0384166004820152602401611089565b613e6c8383836001613f7e565b612f3a57604051635274afe760e01b81526001600160a01b0384166004820152602401611089565b7f9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f005c156122f957604051633ee5aeb560e01b815260040160405180910390fd5b80825d5050565b6040516323b872dd60e01b5f8181526001600160a01b038781166004528616602452604485905291602083606481808c5af1925060015f51148316613f37578383151615613f2b573d5f823e3d81fd5b5f883b113d1516831692505b604052505f60605295945050505050565b5f610e818383670de0b6b3a7640000613fe0565b5f5460ff166122f957604051638dfc202b60e01b815260040160405180910390fd5b60405163095ea7b360e01b5f8181526001600160a01b038616600452602485905291602083604481808b5af1925060015f51148316613fd4578383151615613fc8573d5f823e3d81fd5b5f873b113d1516831692505b60405250949350505050565b5f825f190484118302158202613ff4575f5ffd5b5091020490565b6001600160a01b0381168114610731575f5ffd5b5f6020828403121561401f575f5ffd5b8135610e8181613ffb565b803563ffffffff8116811461403d575f5ffd5b919050565b5f5f60408385031215614053575f5ffd5b823591506140636020840161402a565b90509250929050565b5f5f6040838503121561407d575f5ffd5b823561408881613ffb565b946020939093013593505050565b5f5f5f606084860312156140a8575f5ffd5b83356140b381613ffb565b9250602084013591506140c86040850161402a565b90509250925092565b5f5f5f606084860312156140e3575f5ffd5b83356140ee81613ffb565b95602085013595506040909401359392505050565b5f60208284031215614113575f5ffd5b5035919050565b5f5f83601f84011261412a575f5ffd5b50813567ffffffffffffffff811115614141575f5ffd5b602083019150836020828501011115614158575f5ffd5b9250929050565b5f5f5f5f5f5f60a08789031215614174575f5ffd5b863561417f81613ffb565b955060208701359450604087013561419681613ffb565b9350606087013567ffffffffffffffff8111156141b1575f5ffd5b6141bd89828a0161411a565b90945092505060808701356141d181613ffb565b809150509295509295509295565b5f5f5f5f5f5f5f60c0888a0312156141f5575f5ffd5b873561420081613ffb565b965060208801359550604088013561421781613ffb565b9450606088013567ffffffffffffffff811115614232575f5ffd5b61423e8a828b0161411a565b909550935061425190506080890161402a565b915060a088013561426181613ffb565b8091505092959891949750929550565b5f5f83601f840112614281575f5ffd5b50813567ffffffffffffffff811115614298575f5ffd5b6020830191508360208260051b8501011115614158575f5ffd5b5f5f5f5f5f5f5f5f6080898b0312156142c9575f5ffd5b883567ffffffffffffffff8111156142df575f5ffd5b6142eb8b828c01614271565b909950975050602089013567ffffffffffffffff81111561430a575f5ffd5b6143168b828c01614271565b909750955050604089013567ffffffffffffffff811115614335575f5ffd5b6143418b828c01614271565b909550935050606089013567ffffffffffffffff811115614360575f5ffd5b61436c8b828c01614271565b999c989b5096995094979396929594505050565b8015158114610731575f5ffd5b5f5f6040838503121561439e575f5ffd5b82356143a981613ffb565b915060208301356143b981614380565b809150509250929050565b5f5f602083850312156143d5575f5ffd5b823567ffffffffffffffff8111156143eb575f5ffd5b6143f785828601614271565b90969095509350505050565b5f81518084528060208401602086015e5f602082860101526020601f19601f83011685010191505092915050565b5f602082016020835280845180835260408501915060408160051b8601019250602086015f5b8281101561448857603f19878603018452614473858351614403565b94506020938401939190910190600101614457565b50929695505050505050565b634e487b7160e01b5f52604160045260245ffd5b5f82601f8301126144b7575f5ffd5b813567ffffffffffffffff8111156144d1576144d1614494565b604051601f8201601f19908116603f0116810167ffffffffffffffff8111828210171561450057614500614494565b604052818152838201602001851015614517575f5ffd5b816020850160208301375f918101602001919091529392505050565b5f5f60408385031215614544575f5ffd5b823567ffffffffffffffff81111561455a575f5ffd5b614566858286016144a8565b92505060208301356143b981613ffb565b5f60208284031215614587575f5ffd5b813567ffffffffffffffff81111561459d575f5ffd5b6145a9848285016144a8565b949350505050565b5f5f83601f8401126145c1575f5ffd5b50813567ffffffffffffffff8111156145d8575f5ffd5b6020830191508360208260061b8501011115614158575f5ffd5b5f5f5f5f5f5f60808789031215614607575f5ffd5b863561461281613ffb565b95506146206020880161402a565b9450604087013567ffffffffffffffff81111561463b575f5ffd5b61464789828a016145b1565b909550935050606087013567ffffffffffffffff811115614666575f5ffd5b61467289828a016145b1565b979a9699509497509295939492505050565b5f5f5f60608486031215614696575f5ffd5b61469f8461402a565b92506146ad6020850161402a565b929592945050506040919091013590565b5f5f5f5f5f60a086880312156146d2575f5ffd5b8535945060208601356146e481613ffb565b93506040860135925060608601356146fb81613ffb565b9150608086013561470b81613ffb565b809150509295509295909350565b5f5f5f6060848603121561472b575f5ffd5b8335925061473b6020850161402a565b9150604084013561474b81613ffb565b809150509250925092565b5f5f5f5f5f60a0868803121561476a575f5ffd5b853561477581613ffb565b9450602086013561478581613ffb565b93506040860135925061479a6060870161402a565b949793965091946080013592915050565b634e487b7160e01b5f52600160045260245ffd5b5f602082840312156147cf575f5ffd5b8151610e8181614380565b5f602082840312156147ea575f5ffd5b5051919050565b634e487b7160e01b5f52603260045260245ffd5b5f60208284031215614815575f5ffd5b610e818261402a565b5f5f8335601e19843603018112614833575f5ffd5b83018035915067ffffffffffffffff82111561484d575f5ffd5b6020019150600681901b3603821315614158575f5ffd5b8183526020830192505f815f5b848110156148c757813561488481613ffb565b6001600160a01b0316865260208201356bffffffffffffffffffffffff81168082146148ae575f5ffd5b6020880152506040958601959190910190600101614871565b5093949350505050565b6001600160a01b03881681526001600160a01b038716602082015263ffffffff8616604082015260a060608201525f61490e60a083018688614864565b8281036080840152614921818587614864565b9a9950505050505050505050565b5f8235605e19833603018112614943575f5ffd5b9190910192915050565b5f5f8335601e19843603018112614962575f5ffd5b83018035915067ffffffffffffffff82111561497c575f5ffd5b602001915036819003821315614158575f5ffd5b818382375f9101908152919050565b602081525f610e816020830184614403565b5f82518060208501845e5f920191825250919050565b5f602082840312156149d7575f5ffd5b8151610e8181613ffb565b81810381811115610bc757634e487b7160e01b5f52601160045260245ffdfe676f7665726e616e63654c6f636b696e67436f6e74726f6c6c65720000000000a26469706673582212204bd4b012d283afc1b55d95ee232e1f450ed42a05a5c565b7b06fac9fa90c968564736f6c634300081c0033","external_libraries":[],"proxy_type":null,"implementations":[],"verified_at":"2026-08-04T06:59:09.025184Z","is_verified_via_verifier_alliance":false,"compiler_version":"0.8.28+commit.7893614a","decoded_constructor_args":null,"sourcify_repo_url":"https://repo.sourcify.dev/1/0x750136aC021a7149F0EE38141d0bA920Cca1fC5D","optimization_runs":400,"compiler_settings":{"evmVersion":"cancun","libraries":{},"metadata":{"bytecodeHash":"ipfs"},"optimizer":{"enabled":true,"runs":400},"remappings":[":@chainlink/=lib/chainlink-ccip/chains/evm/",":@chainlink/local/=lib/chainlink-local/",":@core/=src/core/",":@cowprotocol/=lib/cowprotocol/src/",":@deployment/=deployment/",":@finance/=src/finance/",":@forge-std/=lib/forge-std/src/",":@funding/=src/funding/",":@gateway/=src/gateway/",":@governance/=src/governance/",":@integrations/=src/integrations/",":@interfaces/=src/interfaces/",":@layerzerolabs/lz-evm-messagelib-v2/=lib/LayerZero-v2/packages/layerzero-v2/evm/messagelib/",":@layerzerolabs/lz-evm-oapp-v2/=lib/LayerZero-v2/packages/layerzero-v2/evm/oapp/",":@layerzerolabs/lz-evm-protocol-v2/=lib/LayerZero-v2/packages/layerzero-v2/evm/protocol/",":@libraries/=src/libraries/",":@locking/=src/locking/",":@openzeppelin/=lib/openzeppelin-contracts/",":@pendle/=lib/pendle-core-v2-public/contracts/",":@periphery/=src/periphery/",":@solmate/=lib/solmate/",":@test/=test/",":@tokens/=src/tokens/",":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/",":erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",":forge-std/=lib/forge-std/src/",":halmos-cheatcodes/=lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",":openzeppelin-contracts/=lib/openzeppelin-contracts/",":pendle-core-v2-public/=lib/pendle-core-v2-public/contracts/",":solidity-bytes-utils/=lib/solidity-bytes-utils/",":solmate/=lib/solmate/src/"]},"is_verified":true,"verified_twin_address_hash":null,"optimization_enabled":true,"deployed_bytecode":"0x608060405260043610610233575f3560e01c80639b2ea4bd11610129578063c2a672e0116100a8578063ed4254ec1161006d578063ed4254ec1461066e578063f2f4eb261461068d578063f3fef3a3146106ae578063f5d954c0146106cd578063fa60e9ba146106ec575f5ffd5b8063c2a672e0146105df578063caab435f146105fe578063d59150961461061d578063d667ba301461063c578063d95ce53b1461064f575f5ffd5b8063bf0673d2116100ee578063bf0673d21461053f578063bf40fac114610554578063c00716ea14610573578063c1d9fe3e14610592578063c23544ad146105b1575f5ffd5b80639b2ea4bd146104af578063a16ba4e0146104ce578063a5a85b8d146104e2578063aa030aff14610501578063adc9772e14610520575f5ffd5b80634ec78381116101b55780637df3927e1161017a5780637df3927e1461041e5780637edd1a7e1461043e578063800096301461045d5780638456cb591461047c5780638f5cba2b14610490575f5ffd5b80634ec783811461035f5780635c975abb1461037e578063699f200f146103a05780637b4aedcf146103ec5780637b96eef1146103ff575f5ffd5b80632e1a7d4d116101fb5780632e1a7d4d146102e7578063365f1c00146103065780633f4ba83a1461031957806340c10f191461032d5780634a6bdbbe1461034c575f5ffd5b806319ab453c146102375780631a11dc4c14610258578063230ae89c1461027757806326cf8338146102a95780632b83cccd146102c8575b5f5ffd5b348015610242575f5ffd5b5061025661025136600461400f565b61070b565b005b348015610263575f5ffd5b50610256610272366004614042565b610734565b348015610282575f5ffd5b5061029661029136600461406c565b6107ec565b6040519081526020015b60405180910390f35b3480156102b4575f5ffd5b506102966102c3366004614096565b610bcd565b3480156102d3575f5ffd5b506102966102e23660046140d1565b610e88565b3480156102f2575f5ffd5b50610256610301366004614103565b6110a1565b61029661031436600461415f565b611150565b348015610324575f5ffd5b506102566113c4565b348015610338575f5ffd5b5061029661034736600461406c565b61149c565b61029661035a3660046141df565b611609565b34801561036a575f5ffd5b506102566103793660046142b2565b611756565b348015610389575f5ffd5b505f5460ff165b60405190151581526020016102a0565b3480156103ab575f5ffd5b506103d46103ba366004614103565b60016020525f90815260409020546001600160a01b031681565b6040516001600160a01b0390911681526020016102a0565b6102966103fa36600461415f565b6118b9565b34801561040a575f5ffd5b5061025661041936600461438d565b61195d565b61043161042c3660046143c4565b611a9c565b6040516102a09190614431565b348015610449575f5ffd5b50610256610458366004614042565b611d1e565b348015610468575f5ffd5b5061025661047736600461400f565b611ee8565b348015610487575f5ffd5b50610256611fc1565b34801561049b575f5ffd5b506102566104aa366004614042565b612099565b3480156104ba575f5ffd5b506102566104c9366004614533565b6120d4565b3480156104d9575f5ffd5b5061025661225a565b3480156104ed575f5ffd5b506102566104fc366004614103565b6122fb565b34801561050c575f5ffd5b5061025661051b366004614042565b612435565b34801561052b575f5ffd5b5061029661053a36600461406c565b61260a565b34801561054a575f5ffd5b5061029660035481565b34801561055f575f5ffd5b506103d461056e366004614577565b61290b565b34801561057e575f5ffd5b5061025661058d366004614042565b612954565b34801561059d575f5ffd5b506102566105ac3660046145f2565b612997565b3480156105bc575f5ffd5b506103906105cb36600461400f565b60026020525f908152604090205460ff1681565b3480156105ea575f5ffd5b506102966105f936600461406c565b612a4c565b348015610609575f5ffd5b5061025661061836600461406c565b612cb1565b348015610628575f5ffd5b50610256610637366004614684565b612d23565b61025661064a3660046146be565b612f3f565b34801561065a575f5ffd5b50610296610669366004614096565b6130d0565b348015610679575f5ffd5b50610256610688366004614719565b6133c1565b348015610698575f5ffd5b505f5461010090046001600160a01b03166103d4565b3480156106b9575f5ffd5b506102566106c836600461406c565b61355e565b3480156106d8575f5ffd5b506102966106e7366004614756565b6135a8565b3480156106f7575f5ffd5b50610256610706366004614684565b613757565b5f5461010090046001600160a01b031615610728576107286147ab565b61073181613793565b50565b61073c6137f8565b61074461381b565b610776604051806040016040528060118152602001703637b1b5b4b733a1b7b73a3937b63632b960791b81525061290b565b6040516304b92b4d60e31b81523360048201526024810184905263ffffffff831660448201526001600160a01b0391909116906325c95a68906064015b5f604051808303815f87803b1580156107ca575f5ffd5b505af11580156107dc573d5f5f3e3d5ffd5b505050506107e8613850565b5050565b5f6107f56137f8565b6107fd61381b565b5f61082d6040518060400160405280600e81526020016d36b4b73a21b7b73a3937b63632b960911b81525061290b565b90505f61085c6040518060400160405280600b81526020016a39ba30b5b2b22a37b5b2b760a91b81525061290b565b90505f61088c6040518060400160405280600c81526020016b3932b1b2b4b83a2a37b5b2b760a11b81525061290b565b90505f6108b4604051806040016040528060048152602001635553444360e01b81525061290b565b90505f6108e46040518060400160405280600c81526020016b7969656c6453686172696e6760a01b81525061290b565b90506108fb6001600160a01b03831633308a61387a565b60405163095ea7b360e01b81526001600160a01b0386811660048301526024820189905283169063095ea7b3906044016020604051808303815f875af1158015610947573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061096b91906147bf565b506040516340c10f1960e01b8152306004820152602481018890525f906001600160a01b038716906340c10f19906044016020604051808303815f875af11580156109b8573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906109dc91906147da565b9050816001600160a01b0316631d6e11f26040518163ffffffff1660e01b81526004015f604051808303815f87803b158015610a16575f5ffd5b505af1158015610a28573d5f5f3e3d5ffd5b5050604051630341728760e01b8152600160048201526001600160a01b0385169250630341728791506024015f604051808303815f87803b158015610a6b575f5ffd5b505af1158015610a7d573d5f5f3e3d5ffd5b505060405163095ea7b360e01b81526001600160a01b038881166004830152602482018590528716925063095ea7b391506044016020604051808303815f875af1158015610acd573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610af191906147bf565b50604051636e553f6560e01b8152600481018290526001600160a01b038a81166024830152861690636e553f65906044016020604051808303815f875af1158015610b3e573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610b6291906147da565b50604051630341728760e01b81525f60048201526001600160a01b038316906303417287906024015f604051808303815f87803b158015610ba1575f5ffd5b505af1158015610bb3573d5f5f3e3d5ffd5b509298505050505050505050610bc7613850565b92915050565b5f610bd66137f8565b610bde61381b565b5f610c0e6040518060400160405280600e81526020016d36b4b73a21b7b73a3937b63632b960911b81525061290b565b90505f610c3e6040518060400160405280600c81526020016b3932b1b2b4b83a2a37b5b2b760a11b81525061290b565b90505f610c73604051806040016040528060118152602001703637b1b5b4b733a1b7b73a3937b63632b960791b81525061290b565b90505f610c9b604051806040016040528060048152602001635553444360e01b81525061290b565b9050610cb26001600160a01b03821633308a61387a565b60405163095ea7b360e01b81526001600160a01b0385811660048301526024820189905282169063095ea7b3906044016020604051808303815f875af1158015610cfe573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610d2291906147bf565b506040516340c10f1960e01b8152306004820152602481018890525f906001600160a01b038616906340c10f19906044016020604051808303815f875af1158015610d6f573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610d9391906147da565b60405163095ea7b360e01b81526001600160a01b038581166004830152602482018390529192509085169063095ea7b3906044015b6020604051808303815f875af1158015610de4573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610e0891906147bf565b50604051633b50953b60e21b81526004810182905263ffffffff881660248201526001600160a01b038a8116604483015284169063ed4254ec906064015f604051808303815f87803b158015610e5c575f5ffd5b505af1158015610e6e573d5f5f3e3d5ffd5b5092975050505050505050610e81613850565b9392505050565b5f610e916137f8565b610e9961381b565b610ea16138b6565b5f610ecf6040518060400160405280600c81526020016b3932b1b2b4b83a2a37b5b2b760a11b81525061290b565b90505f610f036040518060400160405280601081526020016f3932b232b2b6a1b7b73a3937b63632b960811b81525061290b565b6040516323b872dd60e01b8152336004820152306024820152604481018790529091506001600160a01b038316906323b872dd906064016020604051808303815f875af1158015610f56573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610f7a91906147bf565b5060405163095ea7b360e01b81526001600160a01b0382811660048301526024820187905283169063095ea7b3906044016020604051808303815f875af1158015610fc7573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610feb91906147bf565b506040516301e9a69560e41b81526001600160a01b038781166004830152602482018790525f9190831690631e9a6950906044016020604051808303815f875af115801561103b573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061105f91906147da565b9050848181811015611092576040516316b4038160e21b8152600481019290925260248201526044015b60405180910390fd5b50909350505050610e81613850565b6110a96137f8565b6110b161381b565b6110b96138b6565b6110eb604051806040016040528060118152602001703637b1b5b4b733a1b7b73a3937b63632b960791b81525061290b565b60405163f3fef3a360e01b8152336004820152602481018390526001600160a01b03919091169063f3fef3a3906044015f604051808303815f87803b158015611132575f5ffd5b505af1158015611144573d5f5f3e3d5ffd5b50505050610731613850565b5f6111596137f8565b61116161381b565b5f5f6111708989898989613966565b915091505f6111a16040518060400160405280600b81526020016a39ba30b5b2b22a37b5b2b760a91b81525061290b565b90505f6111d16040518060400160405280600c81526020016b7969656c6453686172696e6760a01b81525061290b565b9050806001600160a01b0316631d6e11f26040518163ffffffff1660e01b81526004015f604051808303815f87803b15801561120b575f5ffd5b505af115801561121d573d5f5f3e3d5ffd5b5050604051630341728760e01b8152600160048201526001600160a01b0384169250630341728791506024015f604051808303815f87803b158015611260575f5ffd5b505af1158015611272573d5f5f3e3d5ffd5b505060405163095ea7b360e01b81526001600160a01b038581166004830152602482018890528616925063095ea7b391506044016020604051808303815f875af11580156112c2573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906112e691906147bf565b50604051636e553f6560e01b8152600481018590526001600160a01b038781166024830152831690636e553f65906044016020604051808303815f875af1158015611333573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061135791906147da565b50604051630341728760e01b81525f60048201526001600160a01b038216906303417287906024015f604051808303815f87803b158015611396575f5ffd5b505af11580156113a8573d5f5f3e3d5ffd5b509596505050505050506113ba613850565b9695505050505050565b5f54604051632474521560e21b81527fe7276a2a84d8de556657ec9cf93a55a7d66f096e529d0582ed08e9e2208b92b5600482018190523360248301529161010090046001600160a01b0316906391d1485490604401602060405180830381865afa158015611435573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061145991906147bf565b6114945760405162461bcd60e51b815260206004820152600c60248201526b15539055551213d49256915160a21b6044820152606401611089565b610731613d8d565b5f6114a56137f8565b6114ad61381b565b5f6114d3604051806040016040528060048152602001635553444360e01b81525061290b565b90505f6115056040518060400160405280600e81526020016d36b4b73a21b7b73a3937b63632b960911b81525061290b565b905061151c6001600160a01b03831633308761387a565b60405163095ea7b360e01b81526001600160a01b0382811660048301526024820186905283169063095ea7b3906044016020604051808303815f875af1158015611568573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061158c91906147bf565b506040516340c10f1960e01b81526001600160a01b038681166004830152602482018690528216906340c10f19906044016020604051808303815f875af11580156115d9573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906115fd91906147da565b92505050610bc7613850565b5f6116126137f8565b61161a61381b565b5f5f6116298a8a8a8a8a613966565b915091505f611660604051806040016040528060118152602001703637b1b5b4b733a1b7b73a3937b63632b960791b81525061290b565b60405163095ea7b360e01b81526001600160a01b038083166004830152602482018690529192509083169063095ea7b3906044016020604051808303815f875af11580156116b0573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906116d491906147bf565b50604051633b50953b60e21b81526004810184905263ffffffff871660248201526001600160a01b03868116604483015282169063ed4254ec906064015f604051808303815f87803b158015611728575f5ffd5b505af115801561173a573d5f5f3e3d5ffd5b50949550505050505061174b613850565b979650505050505050565b61175e6137f8565b61176661381b565b5f6117986040518060400160405280601081526020016f616c6c6f636174696f6e566f74696e6760801b81525061290b565b90505f5b888110156118a557816001600160a01b0316632610409b338c8c858181106117c6576117c66147f1565b90506020020160208101906117db919061400f565b8b8b868181106117ed576117ed6147f1565b90506020020160208101906118029190614805565b8a8a87818110611814576118146147f1565b9050602002810190611826919061481e565b8a8a89818110611838576118386147f1565b905060200281019061184a919061481e565b6040518863ffffffff1660e01b815260040161186c97969594939291906148d1565b5f604051808303815f87803b158015611883575f5ffd5b505af1158015611895573d5f5f3e3d5ffd5b50506001909201915061179c9050565b50506118af613850565b5050505050505050565b5f6118c26137f8565b6118ca61381b565b5f5f6118d98989898989613966565b60405163a9059cbb60e01b81526001600160a01b038781166004830152602482018490529294509092509082169063a9059cbb906044016020604051808303815f875af115801561192c573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061195091906147bf565b50909150506113ba613850565b5f54604051632474521560e21b81527f3947e2f542c6c46c543fa4f79cbd1e27fea37ed249bc3caf992570d19123642e600482018190523360248301529161010090046001600160a01b0316906391d1485490604401602060405180830381865afa1580156119ce573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906119f291906147bf565b611a2d5760405162461bcd60e51b815260206004820152600c60248201526b15539055551213d49256915160a21b6044820152606401611089565b6001600160a01b0383165f81815260026020908152604091829020805460ff1916861515908117909155825142815291820193909352908101919091527faf11e799c0dfe70b6ee7eeeb1e99889edf753033f557a3a5568838bdc770a08b9060600160405180910390a1505050565b5f54604051632474521560e21b81527f1a6838efa4183e08fe3607359d1259272af9d4716f65e1a7b5921f78fd5a3c6a6004820181905233602483015260609290916101009091046001600160a01b0316906391d1485490604401602060405180830381865afa158015611b12573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611b3691906147bf565b611b715760405162461bcd60e51b815260206004820152600c60248201526b15539055551213d49256915160a21b6044820152606401611089565b8267ffffffffffffffff811115611b8a57611b8a614494565b604051908082528060200260200182016040528015611bbd57816020015b6060815260200190600190039081611ba85790505b5091505f5b83811015611d16575f858583818110611bdd57611bdd6147f1565b9050602002810190611bef919061492f565b611bfd90602081019061400f565b90505f868684818110611c1257611c126147f1565b9050602002810190611c24919061492f565b602001359050365f888886818110611c3e57611c3e6147f1565b9050602002810190611c50919061492f565b611c5e90604081019061494d565b915091505f5f856001600160a01b0316858585604051611c7f929190614990565b5f6040518083038185875af1925050503d805f8114611cb9576040519150601f19603f3d011682016040523d82523d5f602084013e611cbe565b606091505b5091509150818190611ce457604051634ad176bb60e01b8152600401611089919061499f565b5080898881518110611cf857611cf86147f1565b60200260200101819052505050505050508080600101915050611bc2565b505092915050565b611d266137f8565b611d2e61381b565b5f611d5f6040518060400160405280600f81526020016e33b7bb32b93730b731b2aa37b5b2b760891b81525061290b565b90505f611d8d6040518060400160405280601b81526020015f516020614a025f395f51905f5281525061290b565b6040516323b872dd60e01b8152336004820152306024820152604481018690529091506001600160a01b038316906323b872dd906064016020604051808303815f875af1158015611de0573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611e0491906147bf565b5060405163095ea7b360e01b81526001600160a01b0382811660048301526024820186905283169063095ea7b3906044016020604051808303815f875af1158015611e51573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611e7591906147bf565b50604051633b50953b60e21b81526004810185905263ffffffff841660248201523360448201526001600160a01b0382169063ed4254ec906064015b5f604051808303815f87803b158015611ec8575f5ffd5b505af1158015611eda573d5f5f3e3d5ffd5b5050505050506107e8613850565b5f54604051632474521560e21b81527f1a6838efa4183e08fe3607359d1259272af9d4716f65e1a7b5921f78fd5a3c6a600482018190523360248301529161010090046001600160a01b0316906391d1485490604401602060405180830381865afa158015611f59573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611f7d91906147bf565b611fb85760405162461bcd60e51b815260206004820152600c60248201526b15539055551213d49256915160a21b6044820152606401611089565b6107e882613793565b5f54604051632474521560e21b81527ffcb9fcbfa83b897fb2d5cf4b58962164105c1e71489a37ef3ae0db3fdce576f6600482018190523360248301529161010090046001600160a01b0316906391d1485490604401602060405180830381865afa158015612032573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061205691906147bf565b6120915760405162461bcd60e51b815260206004820152600c60248201526b15539055551213d49256915160a21b6044820152606401611089565b610731613dde565b6120a16137f8565b6120a961381b565b6107766040518060400160405280601b81526020015f516020614a025f395f51905f5281525061290b565b5f54604051632474521560e21b81527f1a6838efa4183e08fe3607359d1259272af9d4716f65e1a7b5921f78fd5a3c6a600482018190523360248301529161010090046001600160a01b0316906391d1485490604401602060405180830381865afa158015612145573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061216991906147bf565b6121a45760405162461bcd60e51b815260206004820152600c60248201526b15539055551213d49256915160a21b6044820152606401611089565b8160015f856040516020016121b9919061499f565b6040516020818303038152906040528051906020012081526020019081526020015f205f6101000a8154816001600160a01b0302191690836001600160a01b031602179055508260405161220d91906149b1565b604080519182900382204283526001600160a01b0385166020840152917f34765092fb4826a2f48dae7ee370790341f5fe0147f013fca4108e6ea65a68ed910160405180910390a2505050565b6122626137f8565b61226a61381b565b61229b6040518060400160405280601081526020016f3932b232b2b6a1b7b73a3937b63632b960811b81525061290b565b60405163c0598b0d60e01b81523360048201526001600160a01b03919091169063c0598b0d906024015f604051808303815f87803b1580156122db575f5ffd5b505af11580156122ed573d5f5f3e3d5ffd5b505050506122f9613850565b565b5f54604051632474521560e21b81527f3947e2f542c6c46c543fa4f79cbd1e27fea37ed249bc3caf992570d19123642e600482018190523360248301529161010090046001600160a01b0316906391d1485490604401602060405180830381865afa15801561236c573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061239091906147bf565b6123cb5760405162461bcd60e51b815260206004820152600c60248201526b15539055551213d49256915160a21b6044820152606401611089565b662386f26fc100008211156123f357604051636b3ff80760e01b815260040160405180910390fd5b600382905560408051428152602081018490527f675607ea61b02df8e5abbbe4772c0b60bb371fa80782206f2efa1b31e37311eb910160405180910390a15050565b61243d6137f8565b61244561381b565b5f6124716040518060400160405280601b81526020015f516020614a025f395f51905f5281525061290b565b60405163e7dda2eb60e01b815263ffffffff841660048201529091505f906001600160a01b0383169063e7dda2eb90602401602060405180830381865afa1580156124be573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906124e291906149c7565b6040516323b872dd60e01b8152336004820152306024820152604481018690529091506001600160a01b038216906323b872dd906064016020604051808303815f875af1158015612535573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061255991906147bf565b5060405163095ea7b360e01b81526001600160a01b0383811660048301526024820186905282169063095ea7b3906044016020604051808303815f875af11580156125a6573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906125ca91906147bf565b50604051637f866a0d60e01b81526004810185905263ffffffff841660248201523360448201526001600160a01b03831690637f866a0d90606401611eb1565b5f6126136137f8565b61261b61381b565b5f6126486040518060400160405280600b81526020016a39ba30b5b2b22a37b5b2b760a91b81525061290b565b90505f6126786040518060400160405280600c81526020016b3932b1b2b4b83a2a37b5b2b760a11b81525061290b565b90505f6126a86040518060400160405280600c81526020016b7969656c6453686172696e6760a01b81525061290b565b6040516323b872dd60e01b8152336004820152306024820152604481018790529091506001600160a01b038316906323b872dd906064016020604051808303815f875af11580156126fb573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061271f91906147bf565b5060405163095ea7b360e01b81526001600160a01b0384811660048301526024820187905283169063095ea7b3906044016020604051808303815f875af115801561276c573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061279091906147bf565b50806001600160a01b0316631d6e11f26040518163ffffffff1660e01b81526004015f604051808303815f87803b1580156127c9575f5ffd5b505af11580156127db573d5f5f3e3d5ffd5b5050604051630341728760e01b8152600160048201526001600160a01b0384169250630341728791506024015f604051808303815f87803b15801561281e575f5ffd5b505af1158015612830573d5f5f3e3d5ffd5b5050604051636e553f6560e01b8152600481018890526001600160a01b0389811660248301525f935086169150636e553f65906044016020604051808303815f875af1158015612882573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906128a691906147da565b604051630341728760e01b81525f60048201529091506001600160a01b038316906303417287906024015f604051808303815f87803b1580156128e7575f5ffd5b505af11580156128f9573d5f5f3e3d5ffd5b50929650505050505050610bc7613850565b5f60015f83604051602001612920919061499f565b60408051601f198184030181529181528151602092830120835290820192909252015f20546001600160a01b031692915050565b61295c6137f8565b61296461381b565b5f612471604051806040016040528060118152602001703637b1b5b4b733a1b7b73a3937b63632b960791b81525061290b565b61299f6137f8565b6129a761381b565b6129d86040518060400160405280601081526020016f616c6c6f636174696f6e566f74696e6760801b81525061290b565b6001600160a01b0316632610409b338888888888886040518863ffffffff1660e01b8152600401612a0f97969594939291906148d1565b5f604051808303815f87803b158015612a26575f5ffd5b505af1158015612a38573d5f5f3e3d5ffd5b50505050612a44613850565b505050505050565b5f612a556137f8565b612a5d61381b565b5f612a8a6040518060400160405280600b81526020016a39ba30b5b2b22a37b5b2b760a91b81525061290b565b90505f612aba6040518060400160405280600c81526020016b7969656c6453686172696e6760a01b81525061290b565b6040516323b872dd60e01b8152336004820152306024820152604481018690529091506001600160a01b038316906323b872dd906064016020604051808303815f875af1158015612b0d573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612b3191906147bf565b50806001600160a01b0316631d6e11f26040518163ffffffff1660e01b81526004015f604051808303815f87803b158015612b6a575f5ffd5b505af1158015612b7c573d5f5f3e3d5ffd5b5050604051630341728760e01b8152600160048201526001600160a01b0384169250630341728791506024015f604051808303815f87803b158015612bbf575f5ffd5b505af1158015612bd1573d5f5f3e3d5ffd5b5050604051635d043b2960e11b8152600481018790526001600160a01b0388811660248301523060448301525f93508516915063ba087652906064016020604051808303815f875af1158015612c29573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612c4d91906147da565b604051630341728760e01b81525f60048201529091506001600160a01b038316906303417287906024015f604051808303815f87803b158015612c8e575f5ffd5b505af1158015612ca0573d5f5f3e3d5ffd5b509295505050505050610bc7613850565b612cb96137f8565b612cc161381b565b612cec6040518060400160405280601b81526020015f516020614a025f395f51905f5281525061290b565b60405163f3fef3a360e01b81526001600160a01b03848116600483015260248201849052919091169063f3fef3a3906044016107b3565b612d2b6137f8565b612d3361381b565b5f612d66604051806040016040528060118152602001703637b1b5b4b733a1b7b73a3937b63632b960791b81525061290b565b60405163e7dda2eb60e01b815263ffffffff861660048201529091505f906001600160a01b0383169063e7dda2eb90602401602060405180830381865afa158015612db3573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612dd791906149c7565b6040516323b872dd60e01b8152336004820152306024820152604481018590529091506001600160a01b038216906323b872dd906064016020604051808303815f875af1158015612e2a573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612e4e91906147bf565b5060405163095ea7b360e01b81526001600160a01b0383811660048301526024820185905282169063095ea7b3906044016020604051808303815f875af1158015612e9b573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612ebf91906147bf565b5060405163c4acfb8f60e01b81526004810184905263ffffffff8087166024830152851660448201523360648201526001600160a01b0383169063c4acfb8f906084015b5f604051808303815f87803b158015612f1a575f5ffd5b505af1158015612f2c573d5f5f3e3d5ffd5b505050505050612f3a613850565b505050565b612f476137f8565b612f4f61381b565b5f612f7a604051806040016040528060098152602001683837b93a30b6243ab160b91b81525061290b565b60405163d7014c6960e01b8152600481018890526001600160a01b0384811660248301529192505f9183169063d7014c6990604401602060405180830381865afa158015612fca573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612fee91906147da565b905080348181101561301c57604051631c83182560e01b815260048101929092526024820152604401611089565b5061303490506001600160a01b03871633308861387a565b6130486001600160a01b0387168387613e1a565b604051630d667ba360e41b8152600481018890526001600160a01b038781166024830152604482018790528581166064830152848116608483015283169063d667ba3090349060a4015f604051808303818588803b1580156130a8575f5ffd5b505af11580156130ba573d5f5f3e3d5ffd5b505050505050506130c9613850565b5050505050565b5f6130d96137f8565b6130e161381b565b5f61310f6040518060400160405280600c81526020016b3932b1b2b4b83a2a37b5b2b760a11b81525061290b565b90505f61313e6040518060400160405280600b81526020016a39ba30b5b2b22a37b5b2b760a91b81525061290b565b90505f613173604051806040016040528060118152602001703637b1b5b4b733a1b7b73a3937b63632b960791b81525061290b565b90505f6131a36040518060400160405280600c81526020016b7969656c6453686172696e6760a01b81525061290b565b6040516323b872dd60e01b8152336004820152306024820152604481018990529091506001600160a01b038416906323b872dd906064016020604051808303815f875af11580156131f6573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061321a91906147bf565b50806001600160a01b0316631d6e11f26040518163ffffffff1660e01b81526004015f604051808303815f87803b158015613253575f5ffd5b505af1158015613265573d5f5f3e3d5ffd5b5050604051630341728760e01b8152600160048201526001600160a01b0384169250630341728791506024015f604051808303815f87803b1580156132a8575f5ffd5b505af11580156132ba573d5f5f3e3d5ffd5b5050604051635d043b2960e11b8152600481018a9052306024820181905260448201525f92506001600160a01b038616915063ba087652906064016020604051808303815f875af1158015613311573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061333591906147da565b604051630341728760e01b81525f60048201529091506001600160a01b038316906303417287906024015f604051808303815f87803b158015613376575f5ffd5b505af1158015613388573d5f5f3e3d5ffd5b505060405163095ea7b360e01b81526001600160a01b038681166004830152602482018590528816925063095ea7b39150604401610dc8565b6133c96137f8565b6133d161381b565b5f6133ff6040518060400160405280600c81526020016b3932b1b2b4b83a2a37b5b2b760a11b81525061290b565b90505f613434604051806040016040528060118152602001703637b1b5b4b733a1b7b73a3937b63632b960791b81525061290b565b6040516323b872dd60e01b8152336004820152306024820152604481018790529091506001600160a01b038316906323b872dd906064016020604051808303815f875af1158015613487573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906134ab91906147bf565b5060405163095ea7b360e01b81526001600160a01b0382811660048301526024820187905283169063095ea7b3906044016020604051808303815f875af11580156134f8573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061351c91906147bf565b50604051633b50953b60e21b81526004810186905263ffffffff851660248201526001600160a01b03848116604483015282169063ed4254ec90606401612f03565b6135666137f8565b61356e61381b565b6135766138b6565b612cec604051806040016040528060118152602001703637b1b5b4b733a1b7b73a3937b63632b960791b81525061290b565b5f6135b16137f8565b6135b961381b565b5f8590505f6135fc6040518060400160405280601381526020017f6d6967726174696f6e436f6e74726f6c6c65720000000000000000000000000081525061290b565b90506136136001600160a01b03831633308961387a565b60405163095ea7b360e01b81526001600160a01b0382811660048301526024820188905283169063095ea7b3906044016020604051808303815f875af115801561365f573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061368391906147bf565b5060405163230bf88b60e11b81523360048201526001600160a01b03898116602483015288811660448301526064820188905263ffffffff871660848301525f9190831690634617f1169060a4016020604051808303815f875af11580156136ed573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061371191906147da565b905084818181101561373f576040516316b4038160e21b815260048101929092526024820152604401611089565b5090935050505061374e613850565b95945050505050565b61375f6137f8565b61376761381b565b5f612d666040518060400160405280601b81526020015f516020614a025f395f51905f5281525061290b565b5f80546001600160a01b0383811661010081810274ffffffffffffffffffffffffffffffffffffffff0019851617855560405193049190911692909183917f9209b7c8c06dcfd261686a663e7c55989337b18d59da5433c6f2835fb697092091a35050565b5f5460ff16156122f95760405163d93c066560e01b815260040160405180910390fd5b613823613e94565b6122f960017f9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f005b90613ed4565b6122f95f7f9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f0061384a565b613888848484846001613edb565b6138b057604051635274afe760e01b81526001600160a01b0385166004820152602401611089565b50505050565b5f6138e46040518060400160405280600c81526020016b7969656c6453686172696e6760a01b81525061290b565b90505f816001600160a01b031663f843336c6040518163ffffffff1660e01b8152600401602060405180830381865afa158015613923573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061394791906147da565b121561073157604051630e4a65c960e21b815260040160405180910390fd5b6001600160a01b0383165f90815260026020526040812054819060ff166139a057604051631f3eeae760e01b815260040160405180910390fd5b6001600160a01b03871673eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee146139ed576139d96001600160a01b03881633308961387a565b6139ed6001600160a01b0388168688613e1a565b5f856001600160a01b0316348686604051613a09929190614990565b5f6040518083038185875af1925050503d805f8114613a43576040519150601f19603f3d011682016040523d82523d5f602084013e613a48565b606091505b5050905080613a6a5760405163081ceff360e41b815260040160405180910390fd5b5f613a9a6040518060400160405280600e81526020016d36b4b73a21b7b73a3937b63632b960911b81525061290b565b90505f613ac2604051806040016040528060048152602001635553444360e01b81525061290b565b90505f613af26040518060400160405280600c81526020016b3932b1b2b4b83a2a37b5b2b760a11b81525061290b565b6040516370a0823160e01b81523060048201529091505f906001600160a01b038416906370a0823190602401602060405180830381865afa158015613b39573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190613b5d91906147da565b60405163095ea7b360e01b81526001600160a01b038681166004830152602482018390529192509084169063095ea7b3906044016020604051808303815f875af1158015613bad573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190613bd191906147bf565b506040516340c10f1960e01b8152306004820152602481018290525f906001600160a01b038616906340c10f19906044016020604051808303815f875af1158015613c1e573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190613c4291906147da565b6003549091508015613d2c575f613c598383613f48565b9050613c6581846149e2565b9250846001600160a01b031663a9059cbb613ca36040518060400160405280600c81526020016b7969656c6453686172696e6760a01b81525061290b565b6040517fffffffff0000000000000000000000000000000000000000000000000000000060e084901b1681526001600160a01b039091166004820152602481018490526044016020604051808303815f875af1158015613d05573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190613d2991906147bf565b50505b5060408051428152602081018e90529081018290526001600160a01b038e169033907f864d8445691e89cf27c9d9cc6155ad638a9833f28365127ad89aa779a6d3cf839060600160405180910390a39c919b50909950505050505050505050565b613d95613f5c565b5f805460ff191690557f5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa335b6040516001600160a01b03909116815260200160405180910390a1565b613de66137f8565b5f805460ff191660011790557f62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a258613dc13390565b613e268383835f613f7e565b612f3a57613e3783835f6001613f7e565b613e5f57604051635274afe760e01b81526001600160a01b0384166004820152602401611089565b613e6c8383836001613f7e565b612f3a57604051635274afe760e01b81526001600160a01b0384166004820152602401611089565b7f9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f005c156122f957604051633ee5aeb560e01b815260040160405180910390fd5b80825d5050565b6040516323b872dd60e01b5f8181526001600160a01b038781166004528616602452604485905291602083606481808c5af1925060015f51148316613f37578383151615613f2b573d5f823e3d81fd5b5f883b113d1516831692505b604052505f60605295945050505050565b5f610e818383670de0b6b3a7640000613fe0565b5f5460ff166122f957604051638dfc202b60e01b815260040160405180910390fd5b60405163095ea7b360e01b5f8181526001600160a01b038616600452602485905291602083604481808b5af1925060015f51148316613fd4578383151615613fc8573d5f823e3d81fd5b5f873b113d1516831692505b60405250949350505050565b5f825f190484118302158202613ff4575f5ffd5b5091020490565b6001600160a01b0381168114610731575f5ffd5b5f6020828403121561401f575f5ffd5b8135610e8181613ffb565b803563ffffffff8116811461403d575f5ffd5b919050565b5f5f60408385031215614053575f5ffd5b823591506140636020840161402a565b90509250929050565b5f5f6040838503121561407d575f5ffd5b823561408881613ffb565b946020939093013593505050565b5f5f5f606084860312156140a8575f5ffd5b83356140b381613ffb565b9250602084013591506140c86040850161402a565b90509250925092565b5f5f5f606084860312156140e3575f5ffd5b83356140ee81613ffb565b95602085013595506040909401359392505050565b5f60208284031215614113575f5ffd5b5035919050565b5f5f83601f84011261412a575f5ffd5b50813567ffffffffffffffff811115614141575f5ffd5b602083019150836020828501011115614158575f5ffd5b9250929050565b5f5f5f5f5f5f60a08789031215614174575f5ffd5b863561417f81613ffb565b955060208701359450604087013561419681613ffb565b9350606087013567ffffffffffffffff8111156141b1575f5ffd5b6141bd89828a0161411a565b90945092505060808701356141d181613ffb565b809150509295509295509295565b5f5f5f5f5f5f5f60c0888a0312156141f5575f5ffd5b873561420081613ffb565b965060208801359550604088013561421781613ffb565b9450606088013567ffffffffffffffff811115614232575f5ffd5b61423e8a828b0161411a565b909550935061425190506080890161402a565b915060a088013561426181613ffb565b8091505092959891949750929550565b5f5f83601f840112614281575f5ffd5b50813567ffffffffffffffff811115614298575f5ffd5b6020830191508360208260051b8501011115614158575f5ffd5b5f5f5f5f5f5f5f5f6080898b0312156142c9575f5ffd5b883567ffffffffffffffff8111156142df575f5ffd5b6142eb8b828c01614271565b909950975050602089013567ffffffffffffffff81111561430a575f5ffd5b6143168b828c01614271565b909750955050604089013567ffffffffffffffff811115614335575f5ffd5b6143418b828c01614271565b909550935050606089013567ffffffffffffffff811115614360575f5ffd5b61436c8b828c01614271565b999c989b5096995094979396929594505050565b8015158114610731575f5ffd5b5f5f6040838503121561439e575f5ffd5b82356143a981613ffb565b915060208301356143b981614380565b809150509250929050565b5f5f602083850312156143d5575f5ffd5b823567ffffffffffffffff8111156143eb575f5ffd5b6143f785828601614271565b90969095509350505050565b5f81518084528060208401602086015e5f602082860101526020601f19601f83011685010191505092915050565b5f602082016020835280845180835260408501915060408160051b8601019250602086015f5b8281101561448857603f19878603018452614473858351614403565b94506020938401939190910190600101614457565b50929695505050505050565b634e487b7160e01b5f52604160045260245ffd5b5f82601f8301126144b7575f5ffd5b813567ffffffffffffffff8111156144d1576144d1614494565b604051601f8201601f19908116603f0116810167ffffffffffffffff8111828210171561450057614500614494565b604052818152838201602001851015614517575f5ffd5b816020850160208301375f918101602001919091529392505050565b5f5f60408385031215614544575f5ffd5b823567ffffffffffffffff81111561455a575f5ffd5b614566858286016144a8565b92505060208301356143b981613ffb565b5f60208284031215614587575f5ffd5b813567ffffffffffffffff81111561459d575f5ffd5b6145a9848285016144a8565b949350505050565b5f5f83601f8401126145c1575f5ffd5b50813567ffffffffffffffff8111156145d8575f5ffd5b6020830191508360208260061b8501011115614158575f5ffd5b5f5f5f5f5f5f60808789031215614607575f5ffd5b863561461281613ffb565b95506146206020880161402a565b9450604087013567ffffffffffffffff81111561463b575f5ffd5b61464789828a016145b1565b909550935050606087013567ffffffffffffffff811115614666575f5ffd5b61467289828a016145b1565b979a9699509497509295939492505050565b5f5f5f60608486031215614696575f5ffd5b61469f8461402a565b92506146ad6020850161402a565b929592945050506040919091013590565b5f5f5f5f5f60a086880312156146d2575f5ffd5b8535945060208601356146e481613ffb565b93506040860135925060608601356146fb81613ffb565b9150608086013561470b81613ffb565b809150509295509295909350565b5f5f5f6060848603121561472b575f5ffd5b8335925061473b6020850161402a565b9150604084013561474b81613ffb565b809150509250925092565b5f5f5f5f5f60a0868803121561476a575f5ffd5b853561477581613ffb565b9450602086013561478581613ffb565b93506040860135925061479a6060870161402a565b949793965091946080013592915050565b634e487b7160e01b5f52600160045260245ffd5b5f602082840312156147cf575f5ffd5b8151610e8181614380565b5f602082840312156147ea575f5ffd5b5051919050565b634e487b7160e01b5f52603260045260245ffd5b5f60208284031215614815575f5ffd5b610e818261402a565b5f5f8335601e19843603018112614833575f5ffd5b83018035915067ffffffffffffffff82111561484d575f5ffd5b6020019150600681901b3603821315614158575f5ffd5b8183526020830192505f815f5b848110156148c757813561488481613ffb565b6001600160a01b0316865260208201356bffffffffffffffffffffffff81168082146148ae575f5ffd5b6020880152506040958601959190910190600101614871565b5093949350505050565b6001600160a01b03881681526001600160a01b038716602082015263ffffffff8616604082015260a060608201525f61490e60a083018688614864565b8281036080840152614921818587614864565b9a9950505050505050505050565b5f8235605e19833603018112614943575f5ffd5b9190910192915050565b5f5f8335601e19843603018112614962575f5ffd5b83018035915067ffffffffffffffff82111561497c575f5ffd5b602001915036819003821315614158575f5ffd5b818382375f9101908152919050565b602081525f610e816020830184614403565b5f82518060208501845e5f920191825250919050565b5f602082840312156149d7575f5ffd5b8151610e8181613ffb565b81810381811115610bc757634e487b7160e01b5f52601160045260245ffdfe676f7665726e616e63654c6f636b696e67436f6e74726f6c6c65720000000000a26469706673582212204bd4b012d283afc1b55d95ee232e1f450ed42a05a5c565b7b06fac9fa90c968564736f6c634300081c0033","source_code":"// SPDX-License-Identifier: MIT\npragma solidity 0.8.28;\n\nimport {ERC20} from \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\nimport {SafeERC20} from \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\n\nimport {PortalHub} from \"@integrations/outland/portals/PortalHub.sol\";\nimport {InfiniFiGatewayV3} from \"@gateway/InfiniFiGatewayV3.sol\";\n\n/// @notice Gateway to interact with the InfiniFi protocol\n/// This version implements L1 -> L2 bridging of iUSD or siUSD to supported L2 chains.\n/// @dev Requires BRIDGE_INITIATOR role to initiate bridging transactions.\ncontract InfiniFiGatewayV4 is InfiniFiGatewayV3 {\n    using SafeERC20 for ERC20;\n\n    error InsufficientBridgeFee(uint256 required, uint256 provided);\n\n    /// @notice Bridges iUSD or siUSD to a supported L2 chain\n    /// @dev Requires BRIDGE_INITIATOR on this contract and portalHub registered in the address registry\n    /// @param _targetChainId Destination outpost chain ID\n    /// @param _token iUSD or siUSD token address on L1\n    /// @param _amount Amount of tokens to bridge\n    /// @param _recipient Recipient on the destination chain\n    /// @param _connector Authorized connector that relays the cross-chain message\n    function bridge(\n        uint256 _targetChainId,\n        address _token,\n        uint256 _amount,\n        address _recipient,\n        address payable _connector\n    ) external payable whenNotPaused nonReentrant {\n        PortalHub portalHub = PortalHub(getAddress(\"portalHub\"));\n        uint256 messageFee = portalHub.getBridgeMessageFee(_targetChainId, _connector);\n        require(msg.value >= messageFee, InsufficientBridgeFee(messageFee, msg.value));\n\n        ERC20(_token).safeTransferFrom(msg.sender, address(this), _amount);\n        ERC20(_token).forceApprove(address(portalHub), _amount);\n        portalHub.bridge{value: msg.value}(_targetChainId, _token, _amount, _recipient, _connector);\n    }\n}\n","creation_status":"success","file_path":"src/gateway/InfiniFiGatewayV4.sol"}