creation_sourcecode: {{
    "language": "Solidity",
    "sources": {
      "src/tokenomics/LiquidityGauge.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.8.16;\n\nimport {IERC20} from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport {IERC20Metadata} from \"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol\";\nimport {SafeERC20} from \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\nimport {ECDSA} from \"@openzeppelin/contracts/utils/cryptography/ECDSA.sol\";\nimport {MessageHashUtils} from \"@openzeppelin/contracts/utils/cryptography/MessageHashUtils.sol\";\nimport {ReentrancyGuard} from \"@openzeppelin/contracts/utils/ReentrancyGuard.sol\";\nimport {IVoteLocker} from \"src/interfaces/IVoteLocker.sol\";\nimport {IGaugeController} from \"src/interfaces/Gauge/IGaugeController.sol\";\nimport {IMinter} from \"src/interfaces/Minter/IMinter.sol\";\nimport {IMinterEscrow} from \"src/interfaces/Minter/IMinterEscrow.sol\";\n\nimport {IRegistryContract} from \"src/interfaces/Registry/IRegistryContract.sol\";\n\nimport {IRegistryAccess} from \"src/interfaces/Registry/IRegistryAccess.sol\";\nimport {RewardManager} from \"src/RewardManager.sol\";\nimport {\n    CONTRACT_REGISTRY_ACCESS,\n    WEEK,\n    CONTRACT_GAUGE_CONTROLLER,\n    ROLE_OPAL_TEAM\n} from \"src/utils/constants.sol\";\n\ncontract LiquidityGauge is ReentrancyGuard {\n    using SafeERC20 for IERC20;\n\n    // Constants\n\n    uint256 public constant TOKENLESS_PRODUCTION = 40;\n\n    uint256 public constant MAX_RELATIVE_WEIGHT_CAP = 10 ** 18;\n\n    bytes32 public constant ERC1271_MAGIC_VAL =\n        0x1626ba7e00000000000000000000000000000000000000000000000000000000;\n    bytes32 public constant EIP712_TYPEHASH = keccak256(\n        \"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)\"\n    );\n    bytes32 public constant PERMIT_TYPEHASH = keccak256(\n        \"Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)\"\n    );\n    string public constant VERSION = \"v1.0.0\";\n\n    uint256 constant MAX_UINT256 = type(uint256).max;\n\n    // Storage\n\n    address public immutable MINTER;\n    address public immutable MINTER_ESCROW;\n    address public immutable VL_TOKEN;\n    address public immutable GAUGE_CONTROLLER;\n\n    IRegistryContract public immutable registryContract;\n    IRegistryAccess public immutable registryAccess;\n\n    mapping(address => uint256) public nonces;\n\n    address public lpToken;\n    uint256 public futureEpochTime;\n\n    mapping(address => uint256) public balanceOf;\n    uint256 public totalSupply;\n    mapping(address => mapping(address => uint256)) allowance;\n\n    string public name;\n    string public symbol;\n\n    mapping(address => uint256) public workingBalances;\n    uint256 public workingSupply;\n\n    // The goal is to be able to calculate ∫(rate * balance / totalSupply dt) from 0 till checkpoint\n    // All values are kept in units of being multiplied by 1e18\n    uint256 public period;\n    uint256[] public periodTimestamp;\n\n    // 1e18 * ∫(rate(t) / totalSupply(t) dt) from 0 till checkpoint\n    uint256[] public integrateInvSupply; // bump epoch when rate() changes\n    uint256[] public integrateInvSupplyBoosted; // bump epoch when rate() changes\n\n    // 1e18 * ∫(rate(t) / totalSupply(t) dt) from (last_action) till checkpoint\n    mapping(address => uint256) public integrateInvSupplyOf;\n    mapping(address => uint256) public integrateCheckpointOf;\n    mapping(address => uint256) public integrateBoostedInvSupplyOf;\n    mapping(address => uint256) public integrateBoostedCheckpointOf;\n\n    // ∫(balance * rate(t) / totalSupply(t) dt) from 0 till checkpoint\n    // Units: rate * t = already number of coins per address to issue\n    mapping(address => uint256) public integrateFraction;\n    mapping(address => uint256) public integrateFractionBoosted;\n\n    uint256 public inflationRate;\n    uint256 public inflationRateBoosted;\n\n    bool public isKilled;\n    address public factory;\n\n    RewardManager public rewardManager;\n\n    // Events\n\n    event Deposit(address indexed provider, uint256 value);\n\n    event Withdraw(address indexed provider, uint256 value);\n\n    event UpdateLiquidityLimit(\n        address indexed user,\n        uint256 original_balance,\n        uint256 original_supply,\n        uint256 working_balance,\n        uint256 working_supply\n    );\n\n    event Transfer(address indexed from, address indexed to, uint256 value);\n\n    event Approval(address indexed owner, address indexed spender, uint256 value);\n\n    event RewardManagerSet(address indexed rewardManager);\n\n    // Errors\n\n    error CannotInitialize();\n    error CallerNotAllowed();\n    error NotAllowed();\n    error AddressZero();\n    error SignatureExpired();\n    error SignatureInvalid();\n    error NoRewardManager();\n\n    modifier onlyOpalTeam() {\n        if (!registryAccess.checkRole(ROLE_OPAL_TEAM, msg.sender)) revert NotAllowed();\n        _;\n    }\n\n    // Constructor\n\n    constructor(\n        address _minter,\n        address _minterEscrow,\n        address _vlToken,\n        address _registryContract\n    ) {\n        MINTER = _minter;\n        MINTER_ESCROW = _minterEscrow;\n        VL_TOKEN = _vlToken;\n        registryContract = IRegistryContract(_registryContract);\n        registryAccess = IRegistryAccess(registryContract.getContract(CONTRACT_REGISTRY_ACCESS));\n\n        GAUGE_CONTROLLER = registryContract.getContract(CONTRACT_GAUGE_CONTROLLER);\n\n        lpToken = address(0x000000000000000000000000000000000000dEaD);\n    }\n\n    /**\n     * @notice  Initialize the contract\n     * @param   _lpToken  The address of the LP token\n     */\n    function initialize(address _lpToken) external {\n        if (lpToken != address(0)) revert CannotInitialize();\n\n        lpToken = _lpToken;\n        factory = msg.sender;\n\n        string memory _symbol = IERC20Metadata(_lpToken).symbol();\n        string memory _name = string.concat(\"Opal \", _symbol, \" Gauge Deposit\");\n        name = _name;\n        symbol = string.concat(_symbol, \"-Gauge\");\n\n        integrateInvSupply.push(0);\n        integrateInvSupplyBoosted.push(0);\n        periodTimestamp.push(block.timestamp);\n        inflationRate = IMinter(MINTER).rate();\n        inflationRateBoosted = IMinterEscrow(MINTER_ESCROW).rate();\n        futureEpochTime = IMinter(MINTER).futureEpochTimeWrite();\n    }\n\n    function setRewardManager(address _rewardManager) external onlyOpalTeam {\n        rewardManager = RewardManager(_rewardManager);\n        emit RewardManagerSet(_rewardManager);\n    }\n\n    // View functions\n\n    /**\n     * @notice  Get the decimals of the token\n     * @return  uint256\n     */\n    function decimals() external pure returns (uint256) {\n        return 18;\n    }\n\n    // solhint-disable-next-line func-name-mixedcase\n    function DOMAIN_SEPARATOR() external view virtual returns (bytes32) {\n        return _domainSeparator();\n    }\n\n    /**\n     * @notice  Integrate checkpoint\n     * @return  uint256  .\n     */\n    function integrateCheckpoint() external view returns (uint256) {\n        return periodTimestamp[period];\n    }\n\n    // State-changing functions\n\n    /**\n     * @notice  Checkpoint user\n     * @param   user  The address of the user\n     * @return  bool  .\n     */\n    function userCheckpoint(address user) external returns (bool) {\n        if (msg.sender != user && msg.sender != MINTER && msg.sender != MINTER_ESCROW) {\n            revert CallerNotAllowed();\n        }\n        _checkpoint(user);\n        _updateLiquidityLimit(user, balanceOf[user], totalSupply);\n        return true;\n    }\n\n    /**\n     * @notice  Claimable tokens\n     * @param   user  The address of the user\n     * @return  uint256  .\n     */\n    function claimableTokens(address user) external returns (uint256) {\n        _checkpoint(user);\n        return integrateFraction[user] - IMinter(MINTER).minted(user, address(this));\n    }\n\n    /**\n     * @notice  Claimable escrow tokens\n     * @param   user  The address of the user\n     * @return  uint256  .\n     */\n    function claimableEscrowTokens(address user) external returns (uint256) {\n        _checkpoint(user);\n        return integrateFractionBoosted[user]\n            - IMinterEscrow(MINTER_ESCROW).minted(user, address(this));\n    }\n\n    /**\n     * @notice  All claimable tokens (bormal and escrowed) for the user\n     * @param   user  The address of the user\n     * @return  basicAmount  amount of basic tokens\n     * @return  escrowAmount  amount of escrowed tokens\n     */\n    function claimable(address user) external returns (uint256 basicAmount, uint256 escrowAmount) {\n        _checkpoint(user);\n        basicAmount = integrateFraction[user] - IMinter(MINTER).minted(user, address(this));\n        escrowAmount = integrateFractionBoosted[user]\n            - IMinterEscrow(MINTER_ESCROW).minted(user, address(this));\n    }\n\n    /**\n     * @notice  Kick function\n     * @param   user  The address of the user\n     */\n    function kick(address user) external {\n        uint256 lastTime = integrateCheckpointOf[user];\n        (,,, IVoteLocker.LockedBalance[] memory userLocks) =\n            IVoteLocker(VL_TOKEN).lockedBalances(user);\n        uint256 vlTime = userLocks[userLocks.length - 1].unlockTime;\n        uint256 userBalance = balanceOf[user];\n\n        if (IVoteLocker(VL_TOKEN).balanceOf(user) > 0 && vlTime < lastTime) return;\n        if (workingBalances[user] <= (userBalance * TOKENLESS_PRODUCTION / 100)) return;\n\n        _checkpoint(user);\n        _updateLiquidityLimit(user, balanceOf[user], totalSupply);\n    }\n\n    /**\n     * @notice  Deposit function\n     * @param   value  The amount of tokens to deposit\n     */\n    function deposit(uint256 value) external nonReentrant {\n        _deposit(value, msg.sender);\n    }\n\n    /**\n     * @notice  Deposit function\n     * @param   value  The amount of tokens to deposit\n     * @param   user  The address of the user\n     */\n    function deposit(uint256 value, address user) external nonReentrant {\n        _deposit(value, user);\n    }\n\n    /**\n     * @notice  Withdraw function\n     * @param   value  The amount of tokens to withdraw\n     */\n    function withdraw(uint256 value) external nonReentrant {\n        _withdraw(value);\n    }\n\n    /**\n     * @notice  Withdraw function\n     * @param   to  The address of the user\n     * @param   value  The amount of tokens to withdraw\n     * @return  bool  .\n     */\n    function transfer(address to, uint256 value) external nonReentrant returns (bool) {\n        _transfer(msg.sender, to, value);\n        return true;\n    }\n\n    /**\n     * @notice  TransferFrom function\n     * @param   from  The address of the user\n     * @param   to  The address of the user\n     * @param   value  The amount of tokens to transfer\n     * @return  bool  .\n     */\n    function transferFrom(address from, address to, uint256 value)\n        external\n        nonReentrant\n        returns (bool)\n    {\n        uint256 _allowance = allowance[from][msg.sender];\n        if (_allowance != MAX_UINT256) {\n            allowance[from][msg.sender] = _allowance - value;\n        }\n\n        _transfer(from, to, value);\n        return true;\n    }\n\n    /**\n     * @notice  Approve function\n     * @param   spender  The address of the spender\n     * @param   value  The amount of tokens to approve\n     * @return  bool  .\n     */\n    function approve(address spender, uint256 value) external nonReentrant returns (bool) {\n        allowance[msg.sender][spender] = value;\n        emit Approval(msg.sender, spender, value);\n        return true;\n    }\n\n    /**\n     * @notice  Permit function\n     * @param   owner  address of the owner\n     * @param   spender  address of the spender\n     * @param   value  amount of tokens\n     * @param   deadline  timestamp where signature not valid\n     */\n    function permit(\n        address owner,\n        address spender,\n        uint256 value,\n        uint256 deadline,\n        uint8 v,\n        bytes32 r,\n        bytes32 s\n    ) public virtual {\n        if (owner == address(0)) revert AddressZero();\n        if (block.timestamp > deadline) revert SignatureExpired();\n\n        uint256 userNonce = nonces[owner];\n        bytes32 structHash =\n            keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, userNonce, deadline));\n\n        bytes32 _hash = MessageHashUtils.toTypedDataHash(_domainSeparator(), structHash);\n\n        address signer = ECDSA.recover(_hash, v, r, s);\n        if (signer != owner) revert SignatureInvalid();\n\n        allowance[owner][spender] = value;\n        nonces[owner]++;\n    }\n\n    // Internal functions\n\n    /**\n     * @notice  Deposit function\n     * @param   value  The amount of tokens to deposit\n     * @param   user  The address of the user\n     */\n    function _deposit(uint256 value, address user) internal {\n        _checkpoint(user);\n\n        if (value > 0) {\n            uint256 _totalSupply = totalSupply;\n            _totalSupply += value;\n            uint256 newUserBalance = balanceOf[user] + value;\n            balanceOf[user] = newUserBalance;\n            totalSupply = _totalSupply;\n\n            _updateLiquidityLimit(user, newUserBalance, _totalSupply);\n\n            IERC20(lpToken).safeTransferFrom(msg.sender, address(this), value);\n        }\n\n        emit Deposit(user, value);\n        emit Transfer(address(0), user, value);\n    }\n\n    /**\n     * @notice  Withdraw function\n     * @param   value  The amount of tokens to withdraw\n     */\n    function _withdraw(uint256 value) internal {\n        _checkpoint(msg.sender);\n\n        if (value > 0) {\n            uint256 _totalSupply = totalSupply;\n            _totalSupply -= value;\n            uint256 newUserBalance = balanceOf[msg.sender] - value;\n            balanceOf[msg.sender] = newUserBalance;\n            totalSupply = _totalSupply;\n\n            _updateLiquidityLimit(msg.sender, newUserBalance, _totalSupply);\n\n            IERC20(lpToken).safeTransfer(msg.sender, value);\n        }\n\n        emit Withdraw(msg.sender, value);\n        emit Transfer(msg.sender, address(0), value);\n    }\n\n    /**\n     * @notice  Transfer function\n     * @param   from  address of the sender\n     * @param   to  address of the receiver\n     * @param   value  amount of tokens\n     */\n    function _transfer(address from, address to, uint256 value) internal {\n        _checkpoint(from);\n        _checkpoint(to);\n\n        if (value > 0) {\n            uint256 _totalSupply = totalSupply;\n\n            uint256 newFromBalance = balanceOf[from] - value;\n            balanceOf[from] = newFromBalance;\n            _updateLiquidityLimit(from, newFromBalance, _totalSupply);\n\n            uint256 newToBalance = balanceOf[to] + value;\n            balanceOf[to] = newToBalance;\n            _updateLiquidityLimit(to, newToBalance, _totalSupply);\n        }\n\n        emit Transfer(from, to, value);\n    }\n\n    /**\n     * @notice  Update liquidity limit\n     * @param   user  The address of the user\n     * @param   l  limit of the user\n     * @param   L  total limit\n     */\n    function _updateLiquidityLimit(address user, uint256 l, uint256 L) internal {\n        uint256 userBalance = IVoteLocker(VL_TOKEN).balanceOf(user);\n        uint256 totalLockedSupply = IVoteLocker(VL_TOKEN).totalSupply();\n        uint256 lim = (l * TOKENLESS_PRODUCTION) / 100;\n        if (totalLockedSupply > 0) {\n            lim += L * userBalance / totalLockedSupply * (100 - TOKENLESS_PRODUCTION) / 100;\n        }\n        if (lim > l) lim = l;\n\n        uint256 oldBalance = workingBalances[user];\n        workingBalances[user] = lim;\n        uint256 _workingSupply = workingSupply - oldBalance + lim;\n        workingSupply = _workingSupply;\n\n        emit UpdateLiquidityLimit(user, l, L, lim, _workingSupply);\n    }\n\n    /**\n     * @notice  Checkpoint function\n     * @param   user  The address of the user\n     */\n    function _checkpoint(address user) internal {\n        uint256 _period = period;\n        uint256 periodTime = periodTimestamp[_period];\n\n        uint256 _integrateInvSupply = integrateInvSupply[_period];\n        uint256 _integrateInvSupplyBoosted = integrateInvSupplyBoosted[_period];\n\n        uint256 rate = inflationRate;\n        uint256 newRate = rate;\n        uint256 prevFutureEpoch = futureEpochTime;\n        if (prevFutureEpoch >= periodTime) {\n            futureEpochTime = IMinter(MINTER).futureEpochTimeWrite();\n            newRate = IMinter(MINTER).rate();\n            inflationRate = newRate;\n        }\n        uint256 rateBoosted = inflationRateBoosted;\n        uint256 newRateBoosted = IMinterEscrow(MINTER_ESCROW).rate();\n        uint256 endTimestamp;\n        if (newRateBoosted != rateBoosted) {\n            endTimestamp = IMinterEscrow(MINTER_ESCROW).distributionEnd();\n            inflationRateBoosted = newRateBoosted;\n        }\n\n        if (isKilled) {\n            rate = 0;\n        }\n\n        if (block.timestamp > periodTime) {\n            uint256 _workingSupply = workingSupply;\n            uint256 _totalSupply = totalSupply;\n\n            IGaugeController(GAUGE_CONTROLLER).checkpointGauge(address(this));\n\n            uint256 prevWeekTime = periodTime;\n            uint256 weekTime = (periodTime + WEEK) / WEEK * WEEK;\n            if (weekTime > block.timestamp) weekTime = block.timestamp;\n\n            for (uint256 i; i < 500; i++) {\n                uint256 dt = weekTime - prevWeekTime;\n                uint256 w = IGaugeController(GAUGE_CONTROLLER).gaugeRelativeWeight(\n                    address(this), prevWeekTime / WEEK * WEEK\n                );\n                if (_totalSupply > 0) {\n                    if (prevFutureEpoch >= prevWeekTime && prevFutureEpoch < weekTime) {\n                        _integrateInvSupply +=\n                            rate * w * (prevFutureEpoch - prevWeekTime) / _totalSupply;\n                        rate = newRate;\n                        _integrateInvSupply +=\n                            rate * w * (weekTime - prevFutureEpoch) / _totalSupply;\n                    } else {\n                        _integrateInvSupply += rate * w * dt / _totalSupply;\n                    }\n                }\n\n                if (_workingSupply > 0 && rateBoosted > 0) {\n                    if (\n                        endTimestamp >= prevWeekTime && endTimestamp < weekTime && endTimestamp != 0\n                    ) {\n                        _integrateInvSupplyBoosted +=\n                            rateBoosted * w * (endTimestamp - prevWeekTime) / _workingSupply;\n                        rateBoosted = newRate;\n                    } else {\n                        _integrateInvSupplyBoosted += rateBoosted * w * dt / _workingSupply;\n                    }\n                }\n\n                if (weekTime == block.timestamp) break;\n\n                prevWeekTime = weekTime;\n                weekTime = weekTime + WEEK > block.timestamp ? block.timestamp : weekTime + WEEK;\n            }\n        }\n\n        _period++;\n        period = _period;\n        periodTimestamp.push(block.timestamp);\n        integrateInvSupply.push(_integrateInvSupply);\n        integrateInvSupplyBoosted.push(_integrateInvSupplyBoosted);\n\n        uint256 _userBalance = balanceOf[user];\n        integrateFraction[user] +=\n            _userBalance * (_integrateInvSupply - integrateInvSupplyOf[user]) / 10 ** 18;\n        integrateInvSupplyOf[user] = _integrateInvSupply;\n        integrateCheckpointOf[user] = block.timestamp;\n\n        uint256 _workingBalance = workingBalances[user];\n        integrateFractionBoosted[user] += _workingBalance\n            * (_integrateInvSupplyBoosted - integrateBoostedInvSupplyOf[user]) / 10 ** 18;\n        integrateBoostedInvSupplyOf[user] = _integrateInvSupplyBoosted;\n        integrateBoostedCheckpointOf[user] = block.timestamp;\n\n        if (address(rewardManager) != address(0)) {\n            rewardManager.updateUserState(user);\n        }\n    }\n\n    function _domainSeparator() internal view returns (bytes32) {\n        return keccak256(abi.encode(EIP712_TYPEHASH, name, VERSION, block.chainid, address(this)));\n    }\n\n    // Admin functions\n\n    /**\n     * @notice  Kill the contract\n     * @param   _isKilled  .\n     */\n    function setKilled(bool _isKilled) external onlyOpalTeam {\n        isKilled = _isKilled;\n    }\n}\n"
      },
      "lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/IERC20.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\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"
      },
      "lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Metadata.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC20} from \"../IERC20.sol\";\n\n/**\n * @dev Interface for the optional metadata functions from the ERC20 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"
      },
      "lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/utils/SafeERC20.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC20} from \"../IERC20.sol\";\nimport {IERC20Permit} from \"../extensions/IERC20Permit.sol\";\nimport {Address} from \"../../../utils/Address.sol\";\n\n/**\n * @title SafeERC20\n * @dev Wrappers around ERC20 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    using Address for address;\n\n    /**\n     * @dev An operation with an ERC20 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        _callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));\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        _callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));\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    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    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    function forceApprove(IERC20 token, address spender, uint256 value) internal {\n        bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));\n\n        if (!_callOptionalReturnBool(token, approvalCall)) {\n            _callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));\n            _callOptionalReturn(token, approvalCall);\n        }\n    }\n\n    /**\n     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\n     * on the return value: the return value is optional (but if data is returned, it must not be false).\n     * @param token The token targeted by the call.\n     * @param data The call data (encoded using abi.encode or one of its variants).\n     */\n    function _callOptionalReturn(IERC20 token, bytes memory data) private {\n        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since\n        // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that\n        // the target address contains contract code and also asserts for success in the low-level call.\n\n        bytes memory returndata = address(token).functionCall(data);\n        if (returndata.length != 0 && !abi.decode(returndata, (bool))) {\n            revert SafeERC20FailedOperation(address(token));\n        }\n    }\n\n    /**\n     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\n     * on the return value: the return value is optional (but if data is returned, it must not be false).\n     * @param token The token targeted by the call.\n     * @param data The call data (encoded using abi.encode or one of its variants).\n     *\n     * This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.\n     */\n    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {\n        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since\n        // we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false\n        // and not revert is the subcall reverts.\n\n        (bool success, bytes memory returndata) = address(token).call(data);\n        return success && (returndata.length == 0 || abi.decode(returndata, (bool))) && address(token).code.length > 0;\n    }\n}\n"
      },
      "lib/openzeppelin-contracts/contracts/utils/cryptography/ECDSA.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.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 derives the `address(0)`.\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     * 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     * - 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(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError, bytes32) {\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            /// @solidity memory-safe-assembly\n            assembly {\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 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     * 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 Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.\n     *\n     * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]\n     */\n    function tryRecover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address, RecoverError, bytes32) {\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, RecoverError, bytes32) {\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 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"
      },
      "lib/openzeppelin-contracts/contracts/utils/cryptography/MessageHashUtils.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/cryptography/MessageHashUtils.sol)\n\npragma solidity ^0.8.20;\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[EIP 191] and https://eips.ethereum.org/EIPS/eip-712[EIP 712]\n * specifications.\n */\nlibrary MessageHashUtils {\n    /**\n     * @dev Returns the keccak256 digest of an EIP-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://eth.wiki/json-rpc/API#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        /// @solidity memory-safe-assembly\n        assembly {\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 EIP-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://eth.wiki/json-rpc/API#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 EIP-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 Returns the keccak256 digest of an EIP-712 typed data (EIP-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        /// @solidity memory-safe-assembly\n        assembly {\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"
      },
      "lib/openzeppelin-contracts/contracts/utils/ReentrancyGuard.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/ReentrancyGuard.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Contract module that helps prevent reentrant calls to a function.\n *\n * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier\n * available, which can be applied to functions to make sure there are no nested\n * (reentrant) calls to them.\n *\n * Note that because there is a single `nonReentrant` guard, functions marked as\n * `nonReentrant` may not call one another. This can be worked around by making\n * those functions `private`, and then adding `external` `nonReentrant` entry\n * points to them.\n *\n * TIP: If you would like to learn more about reentrancy and alternative ways\n * to protect against it, check out our blog post\n * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].\n */\nabstract contract ReentrancyGuard {\n    // Booleans are more expensive than uint256 or any type that takes up a full\n    // word because each write operation emits an extra SLOAD to first read the\n    // slot's contents, replace the bits taken up by the boolean, and then write\n    // back. This is the compiler's defense against contract upgrades and\n    // pointer aliasing, and it cannot be disabled.\n\n    // The values being non-zero value makes deployment a bit more expensive,\n    // but in exchange the refund on every call to nonReentrant will be lower in\n    // amount. Since refunds are capped to a percentage of the total\n    // transaction's gas, it is best to keep them low in cases like this one, to\n    // increase the likelihood of the full refund coming into effect.\n    uint256 private constant NOT_ENTERED = 1;\n    uint256 private constant ENTERED = 2;\n\n    uint256 private _status;\n\n    /**\n     * @dev Unauthorized reentrant call.\n     */\n    error ReentrancyGuardReentrantCall();\n\n    constructor() {\n        _status = NOT_ENTERED;\n    }\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    function _nonReentrantBefore() private {\n        // On the first call to nonReentrant, _status will be NOT_ENTERED\n        if (_status == ENTERED) {\n            revert ReentrancyGuardReentrantCall();\n        }\n\n        // Any calls to nonReentrant after this point will fail\n        _status = ENTERED;\n    }\n\n    function _nonReentrantAfter() private {\n        // By storing the original value once again, a refund is triggered (see\n        // https://eips.ethereum.org/EIPS/eip-2200)\n        _status = NOT_ENTERED;\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 _status == ENTERED;\n    }\n}\n"
      },
      "src/interfaces/IVoteLocker.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.20;\n\ninterface IVoteLocker {\n    struct LockedBalance {\n        uint208 amount;\n        uint48 unlockTime;\n    }\n\n    struct Epoch {\n        uint208 supply; //epoch boosted supply\n        uint48 date; //epoch start date\n    }\n\n    function balanceOf(address _account) external view returns (uint256 amount);\n\n    function totalSupply() external view returns (uint256 amount);\n\n    function lockedBalances(address _user)\n        external\n        view\n        returns (uint256 total, uint256 unlockable, uint256 locked, LockedBalance[] memory lockData);\n\n    function lock(address _account, uint256 _amount) external;\n\n    function checkpointEpoch() external;\n\n    function epochCount() external view returns (uint256);\n\n    function epochs(uint256 i) external view returns (Epoch memory);\n\n    function balanceAtEpochOf(uint256 _epoch, address _user)\n        external\n        view\n        returns (uint256 amount);\n\n    function totalSupplyAtEpoch(uint256 _epoch) external view returns (uint256 supply);\n\n    function queueNewRewards(address _rewardsToken, uint256 reward) external;\n\n    function getReward(address _account, bool _stake) external;\n\n    function getReward(address _account) external;\n}\n"
      },
      "src/interfaces/Gauge/IGaugeController.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.20;\n\ninterface IGaugeController {\n    function getGaugeType(address gauge) external view returns (uint256);\n    function checkpointGauge(address gauge) external;\n    function gaugeRelativeWeight(address gauge, uint256 timestamp)\n        external\n        view\n        returns (uint256);\n}\n"
      },
      "src/interfaces/Minter/IMinter.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.20;\n\ninterface IMinter {\n    function token() external view returns (address);\n    function controller() external view returns (address);\n\n    function rate() external view returns (uint256);\n\n    function futureEpochTimeWrite() external returns (uint256);\n\n    function minted(address user, address gauge) external view returns (uint256);\n}\n"
      },
      "src/interfaces/Minter/IMinterEscrow.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.20;\n\ninterface IMinterEscrow {\n    function token() external view returns (address);\n    function controller() external view returns (address);\n\n    function rate() external view returns (uint256);\n    function distributionEnd() external view returns (uint256);\n\n    function minted(address user, address gauge) external view returns (uint256);\n}\n"
      },
      "src/interfaces/Registry/IRegistryContract.sol": {
        "content": "// SPDX-License-Identifier: Apache-2.0\npragma solidity 0.8.20;\n\ninterface IRegistryContract {\n    function getContract(bytes32 name) external view returns (address);\n}\n"
      },
      "src/interfaces/Registry/IRegistryAccess.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.8.20;\n\ninterface IRegistryAccess {\n    function getOwner() external view returns (address);\n\n    function checkRole(bytes32 role, address user) external view returns (bool);\n}\n"
      },
      "src/RewardManager.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.20;\n\nimport {Initializable} from \"@openzeppelin-upgradeable-contracts/proxy/utils/Initializable.sol\";\nimport {UUPSUpgradeable} from \"@openzeppelin-upgradeable-contracts/proxy/utils/UUPSUpgradeable.sol\";\nimport {IERC20} from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport {SafeERC20} from \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\nimport {IAuraPool} from \"src/interfaces/Aura/IAuraPool.sol\";\nimport {IOmnipool} from \"src/interfaces/Omnipool/IOmnipool.sol\";\nimport {IRewardManager} from \"src/interfaces/Reward/IRewardManager.sol\";\nimport {IRegistryContract} from \"src/interfaces/Registry/IRegistryContract.sol\";\nimport {IRegistryAccess} from \"src/interfaces/Registry/IRegistryAccess.sol\";\nimport {\n    REWARD_FEES,\n    SCALED_ONE,\n    ROLE_OPAL_TEAM,\n    CONTRACT_BAL_TOKEN,\n    CONTRACT_AURA_TOKEN,\n    CONTRACT_GEM_TOKEN,\n    CONTRACT_OPAL_TREASURY,\n    CONTRACT_VOTE_LOCKER\n} from \"src/utils/constants.sol\";\nimport {LiquidityGauge} from \"src/tokenomics/LiquidityGauge.sol\";\n\ninterface IRewardToken {\n    function rewardToken() external view returns (address);\n}\n\ninterface IBaseToken {\n    function baseToken() external view returns (address);\n}\n\n/**\n * @title RewardManager\n */\ncontract RewardManager is IRewardManager, Initializable, UUPSUpgradeable {\n    using SafeERC20 for IERC20;\n\n    // --------------------------- STRUCTS ---------------------------\n    struct RewardMeta {\n        uint256 earnedIntegral;\n        uint256 lastEarned;\n        mapping(address => uint256) accountIntegral;\n        mapping(address => uint256) accountShare;\n    }\n\n    // --------------------------- CONSTANTS ---------------------------\n    uint256 public constant REWARD_TOKENS_LENGTH = 3;\n\n    // --------------------------- IMMUTABLES --------------------------\n    address public BAL;\n    address public AURA;\n    address public GEM;\n\n    IERC20 public BALToken;\n    IERC20 public AURAToken;\n    IERC20 public GEMToken;\n\n    IRegistryAccess public registryAccess;\n    IRegistryContract public registryContract;\n\n    // --------------------------- VARIABLES ---------------------------\n    IOmnipool public omnipool;\n\n    RewardMeta public BALMeta;\n    RewardMeta public AURAMeta;\n    mapping(address => RewardMeta) public extraRewardMeta;\n\n    LiquidityGauge public liquidityGauge;\n\n    uint256 public protocolFeesBALBalance = 0;\n    uint256 public protocolFeesAURABalance = 0;\n\n    uint256 public lastBALBalance;\n    uint256 public lastAURABalance;\n    uint256[] public lastExtraRewardBalances;\n\n    uint256 private _extraRewardTokensLength;\n    address[] private _extraRewardTokens;\n    mapping(address => bool) private _extraRewardTokensMap;\n\n    // --------------------------- ERROR ---------------------------\n    error OutOfBounds();\n    error NotAuthorized();\n    error InvalidArrayLength();\n    error SwapForGemFailed(address rewardToken);\n    error NoLiquidtyGauge();\n\n    // --------------------------- CONSTRUCTOR ---------------------------\n    constructor() {\n        _disableInitializers();\n    }\n\n    function initialize(address _omnipool, address _registryAccess, address _registryContract)\n        public\n        initializer\n    {\n        __UUPSUpgradeable_init();\n\n        omnipool = IOmnipool(_omnipool);\n        registryContract = IRegistryContract(_registryContract);\n        registryAccess = IRegistryAccess(_registryAccess);\n\n        BAL = registryContract.getContract(CONTRACT_BAL_TOKEN);\n        AURA = registryContract.getContract(CONTRACT_AURA_TOKEN);\n        GEM = registryContract.getContract(CONTRACT_GEM_TOKEN);\n\n        BALToken = IERC20(BAL);\n        AURAToken = IERC20(AURA);\n        GEMToken = IERC20(GEM);\n    }\n\n    function _authorizeUpgrade(address newImplementation) internal override onlyOpalUpgrade {}\n\n    // --------------------------- EVENTS ---------------------------\n    /// @notice Emitted when the omnipool rewards are updated\n    event RewardUpdated(uint256 bal, uint256 aura, uint256[] extraRewards);\n    /// @notice Emitted when a user claim his rewards\n    event RewardClaimed(address indexed user, uint256 bal, uint256 aura, uint256 gem);\n    /// @notice Emitted when a token is swapped for another SCALED_ONE\n    event RewardSwapped(\n        address indexed tokenIn, uint256 amountIn, address indexed tokenOut, uint256 amountOut\n    );\n    /// @notice Emitted when underlying pool reward tokens are claimed\n    event UnderlyingPoolRewardClaimed(\n        address indexed underlyingPool, address indexed rewardToken, uint256 amount\n    );\n    event LiquidityGaugeSet(address indexed liquidityGauge);\n    event RewardUpdated(\n        address indexed user,\n        uint256 balIntegral,\n        uint256 auraIntegral,\n        uint256[] extraRewardIntegrals\n    );\n\n    // --------------------------- MODIFIERS ---------------------------\n    modifier onlyOpalTeam() {\n        if (!registryAccess.checkRole(ROLE_OPAL_TEAM, msg.sender)) {\n            revert NotAuthorized();\n        }\n        _;\n    }\n\n    modifier hasLiquidtyGauge() {\n        if (address(liquidityGauge) == address(0)) {\n            revert NoLiquidtyGauge();\n        }\n        _;\n    }\n\n    modifier onlyOpalUpgrade() {\n        if (!registryAccess.checkRole(ROLE_OPAL_TEAM, msg.sender)) {\n            revert NotAuthorized();\n        }\n        _;\n    }\n\n    // --------------------------- PUBLIC FUNCTIONS ---------------------------\n\n    // --------------------------- EXTERNAL FUNCTIONS ---------------------------\n    // ------------- VIEW FUNCTIONS -------------\n    /**\n     * @notice Return an extra reward tokens by index\n     * @return (address) : The address of the extra reward token\n     */\n    function getExtraRewardToken(uint256 index) external view returns (address) {\n        if (index >= _extraRewardTokensLength) revert OutOfBounds();\n        return _extraRewardTokens[index];\n    }\n\n    /**\n     * @notice Return the length of the extra reward tokens array\n     * @return (uint256) : The length of the extra reward tokens array\n     */\n    function getExtraRewardTokensLength() external view returns (uint256) {\n        return _extraRewardTokensLength;\n    }\n\n    /**\n     * @notice Return the reward token address by index\n     * @return (address) : The address of the reward token\n     */\n    function getRewardToken(uint256 index) external view returns (address) {\n        if (index == 0) return BAL;\n        else if (index == 1) return AURA;\n        else if (index == 2) return GEM;\n        else revert OutOfBounds();\n    }\n\n    // ------------- FUNCTIONS -------------\n    /**\n     * @notice Claim the rewards of the user\n     * @dev This function is called by the user to claim his rewards, it updates the state of the omnipool and claim the pending rewards of the underlying pools\n     * @return bool : true if the claim is successful\n     */\n    function claimEarnings(\n        bool claimExtraRewards,\n        int256[][] memory rewardSwapSlippages,\n        uint256 deadline\n    ) external returns (bool) {\n        if (rewardSwapSlippages.length != _extraRewardTokensLength) revert InvalidArrayLength();\n\n        updateUserState(msg.sender);\n\n        // Get the share amounts\n        uint256 balAmount = BALMeta.accountShare[msg.sender];\n        uint256 auraAmount = AURAMeta.accountShare[msg.sender];\n\n        // Set the share balances to 0\n        BALMeta.accountShare[msg.sender] = 0;\n        AURAMeta.accountShare[msg.sender] = 0;\n\n        // Allowance\n        // Transfer the rewards to the user\n        if (balAmount > 0) {\n            omnipool.approveForRewardManager(BAL, balAmount);\n            BALToken.safeTransferFrom(address(omnipool), msg.sender, balAmount);\n            lastBALBalance = IERC20(BAL).balanceOf(address(omnipool));\n        }\n        if (auraAmount > 0) {\n            omnipool.approveForRewardManager(AURA, auraAmount);\n            AURAToken.safeTransferFrom(address(omnipool), msg.sender, auraAmount);\n            lastAURABalance = IERC20(AURA).balanceOf(address(omnipool));\n        }\n\n        uint256 gemAmountDelta;\n        if (claimExtraRewards) {\n            uint256 gemAmount = IERC20(GEM).balanceOf(address(omnipool));\n\n            for (uint256 i = 0; i < _extraRewardTokensLength;) {\n                address extraRewardToken = _extraRewardTokens[i];\n                RewardMeta storage extraRewardMeta_ = extraRewardMeta[extraRewardToken];\n                uint256 extraRewardAmount = extraRewardMeta_.accountShare[msg.sender];\n                extraRewardMeta_.accountShare[msg.sender] = 0;\n\n                if (extraRewardAmount > 0) {\n                    // Swap for gems\n                    _swapExtraReward(\n                        extraRewardToken, extraRewardAmount, rewardSwapSlippages[i], deadline\n                    );\n                    lastExtraRewardBalances[i] =\n                        IERC20(extraRewardToken).balanceOf(address(omnipool));\n                }\n\n                unchecked {\n                    ++i;\n                }\n            }\n\n            gemAmountDelta = IERC20(GEM).balanceOf(address(omnipool)) - gemAmount;\n            if (gemAmountDelta > 0) {\n                omnipool.approveForRewardManager(GEM, gemAmountDelta);\n                GEMToken.safeTransferFrom(address(omnipool), msg.sender, gemAmountDelta);\n            }\n        }\n\n        // Emit the event\n        emit RewardClaimed(msg.sender, balAmount, auraAmount, gemAmountDelta);\n\n        return true;\n    }\n\n    function setLiquidtyGauge(address _liquidityGauge) external onlyOpalTeam {\n        liquidityGauge = LiquidityGauge(_liquidityGauge);\n        emit LiquidityGaugeSet(_liquidityGauge);\n    }\n\n    /**\n     * @notice Extract the reward tokens informations from the underlying pools\n     * @dev This function iterates over the underlying pools and extract the reward tokens informations, it also updates the rewardTokens array, we should call this function each time the omnipool is updated\n     * @custom:conditions : /!\\ For this method we suppose that BAL token is always the underlying pool reward token AND BAL token is not in the extra rewards tokens\n     */\n    function setExtraRewardTokens() external returns (uint256) {\n        if (_extraRewardTokensLength == 0) {\n            _extraRewardTokens = new address[](0);\n            lastExtraRewardBalances = new uint256[](0);\n        }\n\n        uint8 underlyingPoolLength = omnipool.getUnderlyingPoolsLength();\n        for (uint8 i = 0; i < underlyingPoolLength;) {\n            address underlyingPool = omnipool.getUnderlyingPool(i);\n            IAuraPool auraPool = IAuraPool(underlyingPool);\n            // For each extra reward token, we add it to the rewardTokens array\n            uint256 extraRewardsLength = auraPool.extraRewardsLength();\n            for (uint256 j = 0; j < extraRewardsLength;) {\n                address extraReward = auraPool.extraRewards(j);\n                address extraRewardToken = _virtualBalanceRewardAddrToTokenAddr(extraReward);\n\n                // Check if the token is SCALED_ONE of the reward tokens\n                if (\n                    extraRewardToken != BAL && extraRewardToken != AURA && extraRewardToken != GEM\n                        && !_extraRewardTokensMap[extraRewardToken]\n                ) {\n                    // Add the reward token to the end of the list, it's a new SCALED_ONE\n                    _extraRewardTokensMap[extraRewardToken] = true;\n                    _extraRewardTokens.push(extraRewardToken);\n                    lastExtraRewardBalances.push(0);\n                    unchecked {\n                        ++_extraRewardTokensLength;\n                    }\n                }\n                unchecked {\n                    ++j;\n                }\n            }\n            unchecked {\n                ++i;\n            }\n        }\n\n        return _extraRewardTokensLength;\n    }\n\n    // --------------------------- INTERNAL FUNCTIONS ---------------------------\n    // ------------- VIEW FUNCTIONS -------------\n    /**\n     * @dev This function extract from an Aura.Finance contract the ERC20 token address\n     * @param rewardAddr (address) : The address of the reward contract\n     * @return (address) : An ERC20 token address\n     */\n    function _virtualBalanceRewardAddrToTokenAddr(address rewardAddr)\n        internal\n        view\n        returns (address)\n    {\n        return IBaseToken(IRewardToken(rewardAddr).rewardToken()).baseToken();\n    }\n\n    // ------------- FUNCTIONS -------------\n    /**\n     * @return balDelta Amount of BAL earned by the RM.\n     * @return auraDelta Amount of AURA earned by the RM.\n     * @return extraRewardTokensDelta Amounts of extra reward tokens earned by the RM in an array.\n     * return the amount of BAL, AURA and an array of all reward tokens earned by the RM\n     */\n    function _incrementRewardBalances(\n        uint256 initialBALBalance,\n        uint256 initialAURABalance,\n        uint256[] memory initialExtraRewardBalances\n    )\n        internal\n        view\n        returns (uint256 balDelta, uint256 auraDelta, uint256[] memory extraRewardTokensDelta)\n    {\n        uint256 balBalance = IERC20(BAL).balanceOf(address(omnipool));\n        uint256 auraBalance = IERC20(AURA).balanceOf(address(omnipool));\n\n        balDelta = balBalance - initialBALBalance;\n        auraDelta = auraBalance - initialAURABalance;\n\n        extraRewardTokensDelta = new uint256[](_extraRewardTokensLength);\n        for (uint256 i = 0; i < _extraRewardTokensLength;) {\n            uint256 extraRewardBalance = IERC20(_extraRewardTokens[i]).balanceOf(address(omnipool));\n            extraRewardTokensDelta[i] = extraRewardBalance - initialExtraRewardBalances[i];\n            unchecked {\n                ++i;\n            }\n        }\n    }\n\n    /**\n     * @notice Update the state of the pool and the rewards of the user\n     */\n    function updateUserState(address _account) public hasLiquidtyGauge {\n        // Get the user LP balance\n        uint256 deposited = liquidityGauge.balanceOf(_account);\n\n        // Update the pool state, claim the rewards and transfer them to the RewardManager\n        _updateOmnipoolState();\n\n        // Update the user's rewards\n        _updateRewards(_account, deposited);\n    }\n\n    /**\n     * @notice Update the rewards of the user\n     * @dev This function updates the rewards of the user, it updates the earnedIntegral and lastEarned of the RewardMeta for each reward token\n     */\n    function _updateRewards(address account, uint256 balance) internal {\n        uint256 BALIntegralDelta = BALMeta.earnedIntegral - BALMeta.accountIntegral[account];\n\n        uint256 balShare = (balance * BALIntegralDelta) / SCALED_ONE;\n        BALMeta.accountShare[account] += balShare;\n        BALMeta.accountIntegral[account] = BALMeta.earnedIntegral;\n\n        uint256 AURAIntegralDelta = AURAMeta.earnedIntegral - AURAMeta.accountIntegral[account];\n        uint256 auraShare = (balance * AURAIntegralDelta) / SCALED_ONE;\n        AURAMeta.accountShare[account] += auraShare;\n        AURAMeta.accountIntegral[account] = AURAMeta.earnedIntegral;\n\n        uint256[] memory extraRewardIntegrals = new uint256[](_extraRewardTokensLength);\n        for (uint256 i = 0; i < _extraRewardTokensLength;) {\n            RewardMeta storage extraRewardMeta_ = extraRewardMeta[_extraRewardTokens[i]];\n            uint256 extraRewardIntegralDelta =\n                extraRewardMeta_.earnedIntegral - extraRewardMeta_.accountIntegral[account];\n            uint256 extraRewardShare = (balance * extraRewardIntegralDelta) / SCALED_ONE;\n            extraRewardMeta_.accountShare[account] += extraRewardShare;\n            extraRewardMeta_.accountIntegral[account] = extraRewardMeta_.earnedIntegral;\n            extraRewardIntegrals[i] = extraRewardIntegralDelta;\n            unchecked {\n                ++i;\n            }\n        }\n\n        emit RewardUpdated(account, BALIntegralDelta, AURAIntegralDelta, extraRewardIntegrals);\n    }\n\n    /**\n     * @notice Update the state of the omnipool\n     * @dev This function updates the state of the omnipool, it claims the rewards and swap the other tokens for GEM tokens, it also updates the earnedIntegral and lastEarned of the RewardMeta\n     */\n    function _updateOmnipoolState() internal {\n        (uint256 earnedBAL, uint256 earnedAURA, uint256[] memory earnedExtraRewardTokens) =\n            _claimOmnipoolRewards();\n\n        // Apply fees\n        uint256 protocolFeesBAL = earnedBAL * REWARD_FEES / SCALED_ONE;\n        uint256 protocolFeesAURA = earnedAURA * REWARD_FEES / SCALED_ONE;\n\n        protocolFeesBALBalance += protocolFeesBAL;\n        protocolFeesAURABalance += protocolFeesAURA;\n\n        earnedBAL -= protocolFeesBAL;\n        earnedAURA -= protocolFeesAURA;\n\n        uint256 totalDeposited = liquidityGauge.totalSupply();\n\n        if (totalDeposited > 0) {\n            BALMeta.earnedIntegral += (earnedBAL * SCALED_ONE) / totalDeposited;\n            BALMeta.lastEarned += earnedBAL;\n\n            AURAMeta.earnedIntegral += (earnedAURA * SCALED_ONE) / totalDeposited;\n            AURAMeta.lastEarned += earnedAURA;\n\n            for (uint256 i = 0; i < _extraRewardTokensLength;) {\n                uint256 extraRewardEarned = earnedExtraRewardTokens[i];\n                address extraRewardToken = _extraRewardTokens[i];\n                uint256 extraRewardIntegral = extraRewardEarned * SCALED_ONE / totalDeposited;\n                RewardMeta storage extraRewardMeta_ = extraRewardMeta[_extraRewardTokens[i]];\n\n                extraRewardMeta_.earnedIntegral += extraRewardIntegral;\n                extraRewardMeta_.lastEarned += extraRewardEarned;\n                lastExtraRewardBalances[i] = IERC20(extraRewardToken).balanceOf(address(omnipool));\n                unchecked {\n                    ++i;\n                }\n            }\n        }\n\n        _claimProtocolFees();\n\n        lastBALBalance = IERC20(BAL).balanceOf(address(omnipool));\n        lastAURABalance = IERC20(AURA).balanceOf(address(omnipool));\n\n        // Emit the event\n        emit RewardUpdated(earnedBAL, earnedAURA, earnedExtraRewardTokens);\n    }\n\n    /**\n     * @notice Claim the protocol fees\n     */\n    function _claimProtocolFees() internal {\n        uint256 balToClaim = protocolFeesBALBalance;\n        uint256 auraToClaim = protocolFeesAURABalance;\n\n        protocolFeesBALBalance = 0;\n        protocolFeesAURABalance = 0;\n\n        address omnipoolAddr = address(omnipool);\n\n        omnipool.approveForRewardManager(BAL, balToClaim);\n        omnipool.approveForRewardManager(AURA, auraToClaim);\n\n        uint256 balTreasuryPart = balToClaim / 2;\n        uint256 auraTreasuryPart = auraToClaim / 2;\n\n        address opalTreasury = registryContract.getContract(CONTRACT_OPAL_TREASURY);\n        address voteLocker = registryContract.getContract(CONTRACT_VOTE_LOCKER);\n\n        BALToken.safeTransferFrom(omnipoolAddr, opalTreasury, balTreasuryPart);\n        AURAToken.safeTransferFrom(omnipoolAddr, opalTreasury, auraTreasuryPart);\n\n        BALToken.safeTransferFrom(omnipoolAddr, voteLocker, balToClaim - balTreasuryPart);\n        AURAToken.safeTransferFrom(omnipoolAddr, voteLocker, auraToClaim - auraTreasuryPart);\n    }\n\n    /**\n     * @notice Claim the rewards of the omnipool\n     * @dev This function iterates over the underlying pools and claim the rewards, it also swap the other tokens for GEM tokens\n     * @return (uint256, uint256, uint256[]) : the amount of BAL, AURA and an array of all extra reward tokens earned (initial balance - final balance)\n     */\n    function _claimOmnipoolRewards() internal returns (uint256, uint256, uint256[] memory) {\n        uint8 underlyingPoolLength = omnipool.getUnderlyingPoolsLength();\n\n        (\n            uint256 initialBALBalance,\n            uint256 initialAURABalance,\n            uint256[] memory initialExtraRewardBalances\n        ) = (lastBALBalance, lastAURABalance, lastExtraRewardBalances);\n        // Claim the rewards from the underlying pools and swap the other tokens for GEM tokens\n        for (uint8 i = 0; i < underlyingPoolLength;) {\n            _claimUnderlyingPoolRewards(i);\n            unchecked {\n                ++i;\n            }\n        }\n\n        return _incrementRewardBalances(\n            initialBALBalance, initialAURABalance, initialExtraRewardBalances\n        );\n    }\n\n    function _claimUnderlyingPoolRewards(uint8 _poolIndex) internal {\n        // Claim the rewards from the underlying pool\n        bool success =\n            IAuraPool(omnipool.getUnderlyingPool(_poolIndex)).getReward(address(omnipool), true);\n\n        if (success) {\n            emit UnderlyingPoolRewardClaimed(\n                omnipool.getUnderlyingPool(_poolIndex),\n                BAL,\n                IERC20(BAL).balanceOf(address(omnipool))\n            );\n        }\n    }\n\n    /**\n     * @notice Swap all extra rewards into GEM\n     * @dev This function swap the extra rewards for GEM tokens, it calls the omnipool to perform the swap\n     */\n    function _swapExtraReward(\n        address extraRewardToken,\n        uint256 extraRewardBalance,\n        int256[] memory _swapSlippages,\n        uint256 _deadline\n    ) internal {\n        // ExtraRewardToken is not necessary up to date if the underlying pool reward token changed and the RM hasn't been updated with setExtraRewardTokens\n        bool success =\n            omnipool.swapForGem(extraRewardToken, extraRewardBalance, _swapSlippages, _deadline);\n        if (success) {\n            emit RewardSwapped(\n                extraRewardToken, extraRewardBalance, GEM, IERC20(GEM).balanceOf(address(omnipool))\n            );\n        } else {\n            revert SwapForGemFailed(extraRewardToken);\n        }\n    }\n}\n"
      },
      "src/utils/constants.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.20;\n\n/* Role */\nbytes32 constant ROLE_ADMIN = keccak256(\"ROLE_ADMIN\");\nbytes32 constant ROLE_OPAL_TEAM = keccak256(\"ROLE_OPAL_TEAM\");\nbytes32 constant ROLE_OMNIPOOL = keccak256(\"ROLE_OMNIPOOL\");\nbytes32 constant ROLE_OMNIPOOL_CONTROLLER = keccak256(\"ROLE_OMNIPOOL_CONTROLLER\");\nbytes32 constant ROLE_REWARD_MANAGER = keccak256(\"ROLE_REWARD_MANAGER\");\nbytes32 constant ROLE_MINT_LP_TOKEN = keccak256(\"ROLE_MINT_LP_TOKEN\");\nbytes32 constant ROLE_BURN_LP_TOKEN = keccak256(\"ROLE_BURN_LP_TOKEN\");\nbytes32 constant ROLE_MINT_ESCROW_TOKEN = keccak256(\"ROLE_MINT_ESCROW_TOKEN\");\nbytes32 constant ROLE_MINTER_ESCROW = keccak256(\"ROLE_MINTER_ESCROW\");\nbytes32 constant ROLE_DAO = keccak256(\"ROLE_DAO\");\nbytes32 constant ROLE_GEM_MINTER = keccak256(\"ROLE_MINTER_ESCROW\");\n\n/* Contracts */\n\nbytes32 constant CONTRACT_GEM_TOKEN = keccak256(\"CONTRACT_GEM_TOKEN\");\nbytes32 constant CONTRACT_BAL_TOKEN = keccak256(\"CONTRACT_BAL_TOKEN\");\nbytes32 constant CONTRACT_AURA_TOKEN = keccak256(\"CONTRACT_AURA_TOKEN\");\nbytes32 constant CONTRACT_ORACLE = keccak256(\"CONTRACT_ORACLE\");\nbytes32 constant CONTRACT_REGISTRY_ACCESS = keccak256(\"CONTRACT_REGISTRY_ACCESS\");\nbytes32 constant CONTRACT_GAUGE_CONTROLLER = keccak256(\"CONTRACT_GAUGE_CONTROLLER\");\nbytes32 constant CONTRACT_OMNIPOOL = keccak256(\"CONTRACT_OMNIPOOL\");\nbytes32 constant CONTRACT_OMNIPOOL_CONTROLLER = keccak256(\"CONTRACT_OMNIPOOL_CONTROLLER\");\nbytes32 constant CONTRACT_LP_STAKER = keccak256(\"CONTRACT_LP_STAKER\");\nbytes32 constant CONTRACT_BALANCER_VAULT = keccak256(\"CONTRACT_BALANCER_VAULT\");\nbytes32 constant CONTRACT_AURA_DEPOSIT_WRAPPER = keccak256(\"CONTRACT_AURA_DEPOSIT_WRAPPER\");\nbytes32 constant CONTRACT_OPAL_TREASURY = keccak256(\"CONTRACT_OPAL_TREASURY\");\nbytes32 constant CONTRACT_VOTE_LOCKER = keccak256(\"CONTRACT_VOTE_LOCKER\");\nbytes32 constant CONTRACT_GEM_MINTER_REBALANCING_REWARD =\n    keccak256(\"CONTRACT_GEM_MINTER_REBALANCING_REWARD\");\nbytes32 constant CONTRACT_WETH = keccak256(\"CONTRACT_WETH\");\nbytes32 constant CONTRACT_INCENTIVES_MS = keccak256(\"CONTRACT_INCENTIVES_MS\");\n\n/* Constants */\n\nuint256 constant SCALED_ONE = 1e18;\n\nuint256 constant GEM_TOTAL_SUPPLY = 50_000_000 * SCALED_ONE;\nuint256 constant LPB_SUPPLY = 5_000_000 * SCALED_ONE; // 10% of total supply\nuint256 constant SEED_SUPPLY = 2_500_000 * SCALED_ONE; // 5% of total supply\nuint256 constant LIQUIDITY_MINING_SUPPLY = 8_100_000 * SCALED_ONE; // 16.2% of total supply\nuint256 constant VLGEM_BOOST_SUPPLY = 9_400_000 * SCALED_ONE; // 18.8% of total supply\nuint256 constant TREASURY_SUPPLY = 3_000_000 * SCALED_ONE; // 6% of total supply\nuint256 constant TEAM_SUPPLY = 7_500_000 * SCALED_ONE; // 15% of total supply\nuint256 constant AIRDROP_SUPPLY = 5_000_000 * SCALED_ONE; // 10% of total supply\nuint256 constant REBALANCING_SUPPLY = 9_500_000 * SCALED_ONE; // 19% of total supply\n\nuint256 constant WEEK = 604_800;\n\n/* Minter */\nuint256 constant INITIAL_MINTER_RATE = (2_250_000 * SCALED_ONE) / uint256(52 weeks);\nuint256 constant RATE_REDUCTION_TIME = 365 days;\nuint256 constant RATE_REDUCTION_COEFFICIENT = 0.75 * 1e18; // 25% reduction\n\n/* Minter Escrow */\nuint256 constant MINTER_ESCROW_RATE = (9_400_000 * SCALED_ONE) / uint256(104 weeks);\nuint256 constant RATE_END_TIMESTAMP = 2 * 365 days;\nuint256 constant INFLATION_DELAY = 1 days;\n\n/* Reward Manager */\nuint256 constant REWARD_FEES = 900 * SCALED_ONE / 10_000; // 9%\n\n/* Omnipool */\nuint256 constant WITHDRAW_FEES = 50 * SCALED_ONE / 10_000; // 0.5%\n\n/* Oracle */\naddress constant CURVE_SFRXETH_ORACLE = 0xa1F8A6807c402E4A15ef4EBa36528A3FED24E577;\n\n/* TOKEN */\naddress constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;\naddress constant SFRXETH = 0xac3E018457B222d93114458476f3E3416Abbe38F;\naddress constant WSTETH = 0x7f39C581F595B53c5cb19bD0b3f8dA6c935E2Ca0;\naddress constant RETH = 0xae78736Cd615f374D3085123A210448E74Fc6393;\n\n/* Enum */\nenum PoolType {\n    WEIGHTED,\n    STABLE,\n    COMPOSABLE\n}\n"
      },
      "lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Permit.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Permit.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in\n * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].\n *\n * Adds the {permit} method, which can be used to change an account's ERC20 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 apply 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"
      },
      "lib/openzeppelin-contracts/contracts/utils/Address.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/Address.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n    /**\n     * @dev The ETH balance of the account is not enough to perform the operation.\n     */\n    error AddressInsufficientBalance(address account);\n\n    /**\n     * @dev There's no code at `target` (it is not a contract).\n     */\n    error AddressEmptyCode(address target);\n\n    /**\n     * @dev A call to an address target failed. The target may have reverted.\n     */\n    error FailedInnerCall();\n\n    /**\n     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n     * `recipient`, forwarding all available gas and reverting on errors.\n     *\n     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n     * of certain opcodes, possibly making contracts go over the 2300 gas limit\n     * imposed by `transfer`, making them unable to receive funds via\n     * `transfer`. {sendValue} removes this limitation.\n     *\n     * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n     *\n     * IMPORTANT: because control is transferred to `recipient`, care must be\n     * taken to not create reentrancy vulnerabilities. Consider using\n     * {ReentrancyGuard} or the\n     * https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n     */\n    function sendValue(address payable recipient, uint256 amount) internal {\n        if (address(this).balance < amount) {\n            revert AddressInsufficientBalance(address(this));\n        }\n\n        (bool success, ) = recipient.call{value: amount}(\"\");\n        if (!success) {\n            revert FailedInnerCall();\n        }\n    }\n\n    /**\n     * @dev Performs a Solidity function call using a low level `call`. A\n     * plain `call` is an unsafe replacement for a function call: use this\n     * function instead.\n     *\n     * If `target` reverts with a revert reason or custom error, it is bubbled\n     * up by this function (like regular Solidity function calls). However, if\n     * the call reverted with no returned reason, this function reverts with a\n     * {FailedInnerCall} error.\n     *\n     * Returns the raw returned data. To convert to the expected return value,\n     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n     *\n     * Requirements:\n     *\n     * - `target` must be a contract.\n     * - calling `target` with `data` must not revert.\n     */\n    function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n        return functionCallWithValue(target, data, 0);\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but also transferring `value` wei to `target`.\n     *\n     * Requirements:\n     *\n     * - the calling contract must have an ETH balance of at least `value`.\n     * - the called Solidity function must be `payable`.\n     */\n    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {\n        if (address(this).balance < value) {\n            revert AddressInsufficientBalance(address(this));\n        }\n        (bool success, bytes memory returndata) = target.call{value: value}(data);\n        return verifyCallResultFromTarget(target, success, returndata);\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but performing a static call.\n     */\n    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n        (bool success, bytes memory returndata) = target.staticcall(data);\n        return verifyCallResultFromTarget(target, success, returndata);\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but performing a delegate call.\n     */\n    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n        (bool success, bytes memory returndata) = target.delegatecall(data);\n        return verifyCallResultFromTarget(target, success, returndata);\n    }\n\n    /**\n     * @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target\n     * was not a contract or bubbling up the revert reason (falling back to {FailedInnerCall}) in case of an\n     * unsuccessful call.\n     */\n    function verifyCallResultFromTarget(\n        address target,\n        bool success,\n        bytes memory returndata\n    ) internal view returns (bytes memory) {\n        if (!success) {\n            _revert(returndata);\n        } else {\n            // only check if target is a contract if the call was successful and the return data is empty\n            // otherwise we already know that it was a contract\n            if (returndata.length == 0 && target.code.length == 0) {\n                revert AddressEmptyCode(target);\n            }\n            return returndata;\n        }\n    }\n\n    /**\n     * @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the\n     * revert reason or with a default {FailedInnerCall} error.\n     */\n    function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {\n        if (!success) {\n            _revert(returndata);\n        } else {\n            return returndata;\n        }\n    }\n\n    /**\n     * @dev Reverts with returndata if present. Otherwise reverts with {FailedInnerCall}.\n     */\n    function _revert(bytes memory returndata) private pure {\n        // Look for revert reason and bubble it up if present\n        if (returndata.length > 0) {\n            // The easiest way to bubble the revert reason is using memory via assembly\n            /// @solidity memory-safe-assembly\n            assembly {\n                let returndata_size := mload(returndata)\n                revert(add(32, returndata), returndata_size)\n            }\n        } else {\n            revert FailedInnerCall();\n        }\n    }\n}\n"
      },
      "lib/openzeppelin-contracts/contracts/utils/Strings.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/Strings.sol)\n\npragma solidity ^0.8.20;\n\nimport {Math} from \"./math/Math.sol\";\nimport {SignedMath} from \"./math/SignedMath.sol\";\n\n/**\n * @dev String operations.\n */\nlibrary Strings {\n    bytes16 private constant HEX_DIGITS = \"0123456789abcdef\";\n    uint8 private constant ADDRESS_LENGTH = 20;\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 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            /// @solidity memory-safe-assembly\n            assembly {\n                ptr := add(buffer, add(32, length))\n            }\n            while (true) {\n                ptr--;\n                /// @solidity memory-safe-assembly\n                assembly {\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 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(a).length == bytes(b).length && keccak256(bytes(a)) == keccak256(bytes(b));\n    }\n}\n"
      },
      "lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/Initializable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (proxy/utils/Initializable.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed\n * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an\n * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer\n * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.\n *\n * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be\n * reused. This mechanism prevents re-execution of each \"step\" but allows the creation of new initialization steps in\n * case an upgrade adds a module that needs to be initialized.\n *\n * For example:\n *\n * [.hljs-theme-light.nopadding]\n * ```solidity\n * contract MyToken is ERC20Upgradeable {\n *     function initialize() initializer public {\n *         __ERC20_init(\"MyToken\", \"MTK\");\n *     }\n * }\n *\n * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {\n *     function initializeV2() reinitializer(2) public {\n *         __ERC20Permit_init(\"MyToken\");\n *     }\n * }\n * ```\n *\n * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as\n * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.\n *\n * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure\n * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.\n *\n * [CAUTION]\n * ====\n * Avoid leaving a contract uninitialized.\n *\n * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation\n * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke\n * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:\n *\n * [.hljs-theme-light.nopadding]\n * ```\n * /// @custom:oz-upgrades-unsafe-allow constructor\n * constructor() {\n *     _disableInitializers();\n * }\n * ```\n * ====\n */\nabstract contract Initializable {\n    /**\n     * @dev Storage of the initializable contract.\n     *\n     * It's implemented on a custom ERC-7201 namespace to reduce the risk of storage collisions\n     * when using with upgradeable contracts.\n     *\n     * @custom:storage-location erc7201:openzeppelin.storage.Initializable\n     */\n    struct InitializableStorage {\n        /**\n         * @dev Indicates that the contract has been initialized.\n         */\n        uint64 _initialized;\n        /**\n         * @dev Indicates that the contract is in the process of being initialized.\n         */\n        bool _initializing;\n    }\n\n    // keccak256(abi.encode(uint256(keccak256(\"openzeppelin.storage.Initializable\")) - 1)) & ~bytes32(uint256(0xff))\n    bytes32 private constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00;\n\n    /**\n     * @dev The contract is already initialized.\n     */\n    error InvalidInitialization();\n\n    /**\n     * @dev The contract is not initializing.\n     */\n    error NotInitializing();\n\n    /**\n     * @dev Triggered when the contract has been initialized or reinitialized.\n     */\n    event Initialized(uint64 version);\n\n    /**\n     * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,\n     * `onlyInitializing` functions can be used to initialize parent contracts.\n     *\n     * Similar to `reinitializer(1)`, except that in the context of a constructor an `initializer` may be invoked any\n     * number of times. This behavior in the constructor can be useful during testing and is not expected to be used in\n     * production.\n     *\n     * Emits an {Initialized} event.\n     */\n    modifier initializer() {\n        // solhint-disable-next-line var-name-mixedcase\n        InitializableStorage storage $ = _getInitializableStorage();\n\n        // Cache values to avoid duplicated sloads\n        bool isTopLevelCall = !$._initializing;\n        uint64 initialized = $._initialized;\n\n        // Allowed calls:\n        // - initialSetup: the contract is not in the initializing state and no previous version was\n        //                 initialized\n        // - construction: the contract is initialized at version 1 (no reininitialization) and the\n        //                 current contract is just being deployed\n        bool initialSetup = initialized == 0 && isTopLevelCall;\n        bool construction = initialized == 1 && address(this).code.length == 0;\n\n        if (!initialSetup && !construction) {\n            revert InvalidInitialization();\n        }\n        $._initialized = 1;\n        if (isTopLevelCall) {\n            $._initializing = true;\n        }\n        _;\n        if (isTopLevelCall) {\n            $._initializing = false;\n            emit Initialized(1);\n        }\n    }\n\n    /**\n     * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the\n     * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be\n     * used to initialize parent contracts.\n     *\n     * A reinitializer may be used after the original initialization step. This is essential to configure modules that\n     * are added through upgrades and that require initialization.\n     *\n     * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`\n     * cannot be nested. If one is invoked in the context of another, execution will revert.\n     *\n     * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in\n     * a contract, executing them in the right order is up to the developer or operator.\n     *\n     * WARNING: Setting the version to 2**64 - 1 will prevent any future reinitialization.\n     *\n     * Emits an {Initialized} event.\n     */\n    modifier reinitializer(uint64 version) {\n        // solhint-disable-next-line var-name-mixedcase\n        InitializableStorage storage $ = _getInitializableStorage();\n\n        if ($._initializing || $._initialized >= version) {\n            revert InvalidInitialization();\n        }\n        $._initialized = version;\n        $._initializing = true;\n        _;\n        $._initializing = false;\n        emit Initialized(version);\n    }\n\n    /**\n     * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the\n     * {initializer} and {reinitializer} modifiers, directly or indirectly.\n     */\n    modifier onlyInitializing() {\n        _checkInitializing();\n        _;\n    }\n\n    /**\n     * @dev Reverts if the contract is not in an initializing state. See {onlyInitializing}.\n     */\n    function _checkInitializing() internal view virtual {\n        if (!_isInitializing()) {\n            revert NotInitializing();\n        }\n    }\n\n    /**\n     * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.\n     * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized\n     * to any version. It is recommended to use this to lock implementation contracts that are designed to be called\n     * through proxies.\n     *\n     * Emits an {Initialized} event the first time it is successfully executed.\n     */\n    function _disableInitializers() internal virtual {\n        // solhint-disable-next-line var-name-mixedcase\n        InitializableStorage storage $ = _getInitializableStorage();\n\n        if ($._initializing) {\n            revert InvalidInitialization();\n        }\n        if ($._initialized != type(uint64).max) {\n            $._initialized = type(uint64).max;\n            emit Initialized(type(uint64).max);\n        }\n    }\n\n    /**\n     * @dev Returns the highest version that has been initialized. See {reinitializer}.\n     */\n    function _getInitializedVersion() internal view returns (uint64) {\n        return _getInitializableStorage()._initialized;\n    }\n\n    /**\n     * @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.\n     */\n    function _isInitializing() internal view returns (bool) {\n        return _getInitializableStorage()._initializing;\n    }\n\n    /**\n     * @dev Returns a pointer to the storage namespace.\n     */\n    // solhint-disable-next-line var-name-mixedcase\n    function _getInitializableStorage() private pure returns (InitializableStorage storage $) {\n        assembly {\n            $.slot := INITIALIZABLE_STORAGE\n        }\n    }\n}\n"
      },
      "lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/UUPSUpgradeable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (proxy/utils/UUPSUpgradeable.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC1822Proxiable} from \"@openzeppelin/contracts/interfaces/draft-IERC1822.sol\";\nimport {ERC1967Utils} from \"@openzeppelin/contracts/proxy/ERC1967/ERC1967Utils.sol\";\nimport {Initializable} from \"./Initializable.sol\";\n\n/**\n * @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an\n * {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy.\n *\n * A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is\n * reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing\n * `UUPSUpgradeable` with a custom implementation of upgrades.\n *\n * The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism.\n */\nabstract contract UUPSUpgradeable is Initializable, IERC1822Proxiable {\n    /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n    address private immutable __self = address(this);\n\n    /**\n     * @dev The version of the upgrade interface of the contract. If this getter is missing, both `upgradeTo(address)`\n     * and `upgradeToAndCall(address,bytes)` are present, and `upgradeTo` must be used if no function should be called,\n     * while `upgradeToAndCall` will invoke the `receive` function if the second argument is the empty byte string.\n     * If the getter returns `\"5.0.0\"`, only `upgradeToAndCall(address,bytes)` is present, and the second argument must\n     * be the empty byte string if no function should be called, making it impossible to invoke the `receive` function\n     * during an upgrade.\n     */\n    string public constant UPGRADE_INTERFACE_VERSION = \"5.0.0\";\n\n    /**\n     * @dev The call is from an unauthorized context.\n     */\n    error UUPSUnauthorizedCallContext();\n\n    /**\n     * @dev The storage `slot` is unsupported as a UUID.\n     */\n    error UUPSUnsupportedProxiableUUID(bytes32 slot);\n\n    /**\n     * @dev Check that the execution is being performed through a delegatecall call and that the execution context is\n     * a proxy contract with an implementation (as defined in ERC1967) pointing to self. This should only be the case\n     * for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a\n     * function through ERC1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to\n     * fail.\n     */\n    modifier onlyProxy() {\n        _checkProxy();\n        _;\n    }\n\n    /**\n     * @dev Check that the execution is not being performed through a delegate call. This allows a function to be\n     * callable on the implementing contract but not through proxies.\n     */\n    modifier notDelegated() {\n        _checkNotDelegated();\n        _;\n    }\n\n    function __UUPSUpgradeable_init() internal onlyInitializing {\n    }\n\n    function __UUPSUpgradeable_init_unchained() internal onlyInitializing {\n    }\n    /**\n     * @dev Implementation of the ERC1822 {proxiableUUID} function. This returns the storage slot used by the\n     * implementation. It is used to validate the implementation's compatibility when performing an upgrade.\n     *\n     * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks\n     * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this\n     * function revert if invoked through a proxy. This is guaranteed by the `notDelegated` modifier.\n     */\n    function proxiableUUID() external view virtual notDelegated returns (bytes32) {\n        return ERC1967Utils.IMPLEMENTATION_SLOT;\n    }\n\n    /**\n     * @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call\n     * encoded in `data`.\n     *\n     * Calls {_authorizeUpgrade}.\n     *\n     * Emits an {Upgraded} event.\n     *\n     * @custom:oz-upgrades-unsafe-allow-reachable delegatecall\n     */\n    function upgradeToAndCall(address newImplementation, bytes memory data) public payable virtual onlyProxy {\n        _authorizeUpgrade(newImplementation);\n        _upgradeToAndCallUUPS(newImplementation, data);\n    }\n\n    /**\n     * @dev Reverts if the execution is not performed via delegatecall or the execution\n     * context is not of a proxy with an ERC1967-compliant implementation pointing to self.\n     * See {_onlyProxy}.\n     */\n    function _checkProxy() internal view virtual {\n        if (\n            address(this) == __self || // Must be called through delegatecall\n            ERC1967Utils.getImplementation() != __self // Must be called through an active proxy\n        ) {\n            revert UUPSUnauthorizedCallContext();\n        }\n    }\n\n    /**\n     * @dev Reverts if the execution is performed via delegatecall.\n     * See {notDelegated}.\n     */\n    function _checkNotDelegated() internal view virtual {\n        if (address(this) != __self) {\n            // Must not be called through delegatecall\n            revert UUPSUnauthorizedCallContext();\n        }\n    }\n\n    /**\n     * @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by\n     * {upgradeToAndCall}.\n     *\n     * Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}.\n     *\n     * ```solidity\n     * function _authorizeUpgrade(address) internal onlyOwner {}\n     * ```\n     */\n    function _authorizeUpgrade(address newImplementation) internal virtual;\n\n    /**\n     * @dev Performs an implementation upgrade with a security check for UUPS proxies, and additional setup call.\n     *\n     * As a security check, {proxiableUUID} is invoked in the new implementation, and the return value\n     * is expected to be the implementation slot in ERC1967.\n     *\n     * Emits an {IERC1967-Upgraded} event.\n     */\n    function _upgradeToAndCallUUPS(address newImplementation, bytes memory data) private {\n        try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) {\n            if (slot != ERC1967Utils.IMPLEMENTATION_SLOT) {\n                revert UUPSUnsupportedProxiableUUID(slot);\n            }\n            ERC1967Utils.upgradeToAndCall(newImplementation, data);\n        } catch {\n            // The implementation is not UUPS\n            revert ERC1967Utils.ERC1967InvalidImplementation(newImplementation);\n        }\n    }\n}\n"
      },
      "src/interfaces/Aura/IAuraPool.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.20;\n\n//sample convex reward contracts interface\ninterface IAuraPool {\n    //get balance of an address\n    function balanceOf(address _account) external returns (uint256);\n    //withdraw to a convex tokenized deposit\n    function withdraw(uint256 _amount, bool _claim) external returns (bool);\n    //withdraw directly to curve LP token\n    function withdrawAndUnwrap(uint256 _amount, bool _claim) external returns (bool);\n    //claim rewards\n    function getReward() external returns (bool);\n    //stake a convex tokenized deposit\n    function stake(uint256 _amount) external returns (bool);\n    //stake a convex tokenized deposit for another address(transfering ownership)\n    function stakeFor(address _account, uint256 _amount) external returns (bool);\n\n    // Custom\n    function getReward(address _account, bool _claimExtras) external returns (bool);\n    function rewardToken() external returns (address);\n    function extraRewardsLength() external returns (uint256);\n    function extraRewards(uint256 input) external returns (address);\n\n    function periodFinish() external returns (uint256);\n\n    function processIdleRewards() external;\n}\n"
      },
      "src/interfaces/Omnipool/IOmnipool.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.20;\n\nimport \"src/interfaces/Balancer/IBalancerPool.sol\";\nimport \"src/interfaces/Omnipool/IOmnipoolController.sol\";\nimport \"src/interfaces/Balancer/IBalancerVault.sol\";\nimport {PoolType} from \"src/pools/Oracle.sol\";\nimport {IERC20Metadata} from \"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol\";\n\ninterface IOmnipool {\n    // --------------------------- STRUCTS ---------------------------\n    struct UnderlyingPool {\n        address poolAddress; // aura pool address\n        bytes32 poolId; // balancer pool id\n        IAsset[] assets; // list of input tokens of the pool\n        uint256 targetWeight; // target pool weight\n        PoolType poolType;\n        uint8 assetIndex;\n        uint8 bptIndex;\n    }\n\n    function changeUnderlyingPool(\n        uint8 id,\n        address _poolAddress,\n        bytes32 _poolId,\n        uint256 _weight,\n        PoolType _poolType\n    ) external;\n\n    struct PoolWithAmount {\n        address poolAddress;\n        uint256 amount;\n    }\n\n    struct PoolWeight {\n        address poolAddress;\n        uint256 weight;\n    }\n\n    function depositFor(uint256 _amountIn, address _depositFor, uint256 _minLpReceived) external;\n\n    function deposit(uint256 _amountIn, uint256 _minLpReceived) external;\n\n    function withdraw(uint256 _amountOut, uint256 _minUnderlyingReceived) external;\n\n    function updateWeights(IOmnipoolController.WeightUpdate[] calldata poolWeights) external;\n\n    function togglePool() external returns (bool);\n\n    /* PUBLIC VIEW */\n\n    function getTotalDeposited() external view returns (uint256);\n\n    function getUserTotalDeposit(address user) external view returns (uint256);\n\n    function getUnderlyingBalance(uint8 poolId, uint256 _amount, uint256 _underlyingPrice)\n        external\n        view\n        returns (uint256);\n\n    function approveForRewardManager(address token, uint256 amount) external;\n\n    function swapForGem(\n        address _token,\n        uint256 _amountIn,\n        int256[] memory _amountsOutMin,\n        uint256 _deadline\n    ) external returns (bool);\n\n    function getUnderlyingPool(uint8 index) external view returns (address);\n\n    function setGemPoolId(bytes32 _poolId) external;\n\n    function setExtraRewardPool(address _token, bytes32 _poolId) external;\n\n    function getUnderlyingToken() external view returns (IERC20Metadata);\n\n    function getTotalDeviationAfterUpdate() external view returns (uint256);\n\n    function getUnderlyingPoolsLength() external view returns (uint8);\n\n    function getLpToken() external view returns (IERC20Metadata);\n\n    function totalUnderlying() external view returns (uint256);\n\n    function getTotalAndPerPoolUnderlying()\n        external\n        view\n        returns (uint256 totalUnderlying_, uint256[] memory perPoolUnderlying_);\n}\n"
      },
      "src/interfaces/Reward/IRewardManager.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.20;\n\ninterface IRewardManager {\n    function getRewardToken(uint256 index) external view returns (address);\n\n    function getExtraRewardToken(uint256 index) external view returns (address);\n\n    function setExtraRewardTokens() external returns (uint256);\n}\n"
      },
      "lib/openzeppelin-contracts/contracts/utils/math/Math.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/math/Math.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Standard math utilities missing in the Solidity language.\n */\nlibrary Math {\n    /**\n     * @dev Muldiv operation overflow.\n     */\n    error MathOverflowedMulDiv();\n\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 Returns the addition of two unsigned integers, with an overflow flag.\n     */\n    function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n        unchecked {\n            uint256 c = a + b;\n            if (c < a) return (false, 0);\n            return (true, c);\n        }\n    }\n\n    /**\n     * @dev Returns the subtraction of two unsigned integers, with an overflow flag.\n     */\n    function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n        unchecked {\n            if (b > a) return (false, 0);\n            return (true, a - b);\n        }\n    }\n\n    /**\n     * @dev Returns the multiplication of two unsigned integers, with an overflow flag.\n     */\n    function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n        unchecked {\n            // Gas optimization: this is cheaper than requiring 'a' not being zero, but the\n            // benefit is lost if 'b' is also tested.\n            // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522\n            if (a == 0) return (true, 0);\n            uint256 c = a * b;\n            if (c / a != b) return (false, 0);\n            return (true, c);\n        }\n    }\n\n    /**\n     * @dev Returns the division of two unsigned integers, with a division by zero flag.\n     */\n    function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n        unchecked {\n            if (b == 0) return (false, 0);\n            return (true, a / b);\n        }\n    }\n\n    /**\n     * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.\n     */\n    function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n        unchecked {\n            if (b == 0) return (false, 0);\n            return (true, a % b);\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 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 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        // (a + b) / 2 can overflow.\n        return (a & b) + (a ^ b) / 2;\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            return a / b;\n        }\n\n        // (a + b - 1) / b can overflow on addition, so we distribute.\n        return a == 0 ? 0 : (a - 1) / b + 1;\n    }\n\n    /**\n     * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or\n     * denominator == 0.\n     * @dev 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            // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use\n            // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256\n            // variables such that product = prod1 * 2^256 + prod0.\n            uint256 prod0 = x * y; // Least significant 256 bits of the product\n            uint256 prod1; // Most significant 256 bits of the product\n            assembly {\n                let mm := mulmod(x, y, not(0))\n                prod1 := sub(sub(mm, prod0), lt(mm, prod0))\n            }\n\n            // Handle non-overflow cases, 256 by 256 division.\n            if (prod1 == 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 prod0 / denominator;\n            }\n\n            // Make sure the result is less than 2^256. Also prevents denominator == 0.\n            if (denominator <= prod1) {\n                revert MathOverflowedMulDiv();\n            }\n\n            ///////////////////////////////////////////////\n            // 512 by 256 division.\n            ///////////////////////////////////////////////\n\n            // Make division exact by subtracting the remainder from [prod1 prod0].\n            uint256 remainder;\n            assembly {\n                // Compute remainder using mulmod.\n                remainder := mulmod(x, y, denominator)\n\n                // Subtract 256 bit number from 512 bit number.\n                prod1 := sub(prod1, gt(remainder, prod0))\n                prod0 := sub(prod0, 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 {\n                // Divide denominator by twos.\n                denominator := div(denominator, twos)\n\n                // Divide [prod1 prod0] by twos.\n                prod0 := div(prod0, twos)\n\n                // Flip twos such that it is 2^256 / 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 prod1 into prod0.\n            prod0 |= prod1 * twos;\n\n            // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such\n            // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for\n            // four bits. That is, denominator * inv = 1 mod 2^4.\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^8\n            inverse *= 2 - denominator * inverse; // inverse mod 2^16\n            inverse *= 2 - denominator * inverse; // inverse mod 2^32\n            inverse *= 2 - denominator * inverse; // inverse mod 2^64\n            inverse *= 2 - denominator * inverse; // inverse mod 2^128\n            inverse *= 2 - denominator * inverse; // inverse mod 2^256\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^256. Since the preconditions guarantee that the outcome is\n            // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1\n            // is no longer required.\n            result = prod0 * inverse;\n            return result;\n        }\n    }\n\n    /**\n     * @notice 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        uint256 result = mulDiv(x, y, denominator);\n        if (unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0) {\n            result += 1;\n        }\n        return result;\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     * Inspired by Henry S. Warren, Jr.'s \"Hacker's Delight\" (Chapter 11).\n     */\n    function sqrt(uint256 a) internal pure returns (uint256) {\n        if (a == 0) {\n            return 0;\n        }\n\n        // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.\n        //\n        // We know that the \"msb\" (most significant bit) of our target number `a` is a power of 2 such that we have\n        // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.\n        //\n        // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`\n        // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`\n        // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`\n        //\n        // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.\n        uint256 result = 1 << (log2(a) >> 1);\n\n        // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,\n        // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at\n        // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision\n        // into the expected uint128 result.\n        unchecked {\n            result = (result + a / result) >> 1;\n            result = (result + a / result) >> 1;\n            result = (result + a / result) >> 1;\n            result = (result + a / result) >> 1;\n            result = (result + a / result) >> 1;\n            result = (result + a / result) >> 1;\n            result = (result + a / result) >> 1;\n            return min(result, a / result);\n        }\n    }\n\n    /**\n     * @notice 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 + (unsignedRoundsUp(rounding) && result * result < a ? 1 : 0);\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 value) internal pure returns (uint256) {\n        uint256 result = 0;\n        unchecked {\n            if (value >> 128 > 0) {\n                value >>= 128;\n                result += 128;\n            }\n            if (value >> 64 > 0) {\n                value >>= 64;\n                result += 64;\n            }\n            if (value >> 32 > 0) {\n                value >>= 32;\n                result += 32;\n            }\n            if (value >> 16 > 0) {\n                value >>= 16;\n                result += 16;\n            }\n            if (value >> 8 > 0) {\n                value >>= 8;\n                result += 8;\n            }\n            if (value >> 4 > 0) {\n                value >>= 4;\n                result += 4;\n            }\n            if (value >> 2 > 0) {\n                value >>= 2;\n                result += 2;\n            }\n            if (value >> 1 > 0) {\n                result += 1;\n            }\n        }\n        return result;\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 + (unsignedRoundsUp(rounding) && 1 << result < value ? 1 : 0);\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 + (unsignedRoundsUp(rounding) && 10 ** result < value ? 1 : 0);\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 value) internal pure returns (uint256) {\n        uint256 result = 0;\n        unchecked {\n            if (value >> 128 > 0) {\n                value >>= 128;\n                result += 16;\n            }\n            if (value >> 64 > 0) {\n                value >>= 64;\n                result += 8;\n            }\n            if (value >> 32 > 0) {\n                value >>= 32;\n                result += 4;\n            }\n            if (value >> 16 > 0) {\n                value >>= 16;\n                result += 2;\n            }\n            if (value >> 8 > 0) {\n                result += 1;\n            }\n        }\n        return result;\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 + (unsignedRoundsUp(rounding) && 1 << (result << 3) < value ? 1 : 0);\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"
      },
      "lib/openzeppelin-contracts/contracts/utils/math/SignedMath.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/math/SignedMath.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Standard signed math utilities missing in the Solidity language.\n */\nlibrary SignedMath {\n    /**\n     * @dev Returns the largest of two signed numbers.\n     */\n    function max(int256 a, int256 b) internal pure returns (int256) {\n        return 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 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            // must be unchecked in order to support `n = type(int256).min`\n            return uint256(n >= 0 ? n : -n);\n        }\n    }\n}\n"
      },
      "lib/openzeppelin-contracts/contracts/interfaces/draft-IERC1822.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/draft-IERC1822.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev ERC1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified\n * proxy whose upgrades are fully controlled by the current implementation.\n */\ninterface IERC1822Proxiable {\n    /**\n     * @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation\n     * address.\n     *\n     * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks\n     * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this\n     * function revert if invoked through a proxy.\n     */\n    function proxiableUUID() external view returns (bytes32);\n}\n"
      },
      "lib/openzeppelin-contracts/contracts/proxy/ERC1967/ERC1967Utils.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (proxy/ERC1967/ERC1967Utils.sol)\n\npragma solidity ^0.8.20;\n\nimport {IBeacon} from \"../beacon/IBeacon.sol\";\nimport {Address} from \"../../utils/Address.sol\";\nimport {StorageSlot} from \"../../utils/StorageSlot.sol\";\n\n/**\n * @dev This abstract contract provides getters and event emitting update functions for\n * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.\n */\nlibrary ERC1967Utils {\n    // We re-declare ERC-1967 events here because they can't be used directly from IERC1967.\n    // This will be fixed in Solidity 0.8.21. At that point we should remove these events.\n    /**\n     * @dev Emitted when the implementation is upgraded.\n     */\n    event Upgraded(address indexed implementation);\n\n    /**\n     * @dev Emitted when the admin account has changed.\n     */\n    event AdminChanged(address previousAdmin, address newAdmin);\n\n    /**\n     * @dev Emitted when the beacon is changed.\n     */\n    event BeaconUpgraded(address indexed beacon);\n\n    /**\n     * @dev Storage slot with the address of the current implementation.\n     * This is the keccak-256 hash of \"eip1967.proxy.implementation\" subtracted by 1.\n     */\n    // solhint-disable-next-line private-vars-leading-underscore\n    bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;\n\n    /**\n     * @dev The `implementation` of the proxy is invalid.\n     */\n    error ERC1967InvalidImplementation(address implementation);\n\n    /**\n     * @dev The `admin` of the proxy is invalid.\n     */\n    error ERC1967InvalidAdmin(address admin);\n\n    /**\n     * @dev The `beacon` of the proxy is invalid.\n     */\n    error ERC1967InvalidBeacon(address beacon);\n\n    /**\n     * @dev An upgrade function sees `msg.value > 0` that may be lost.\n     */\n    error ERC1967NonPayable();\n\n    /**\n     * @dev Returns the current implementation address.\n     */\n    function getImplementation() internal view returns (address) {\n        return StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value;\n    }\n\n    /**\n     * @dev Stores a new address in the EIP1967 implementation slot.\n     */\n    function _setImplementation(address newImplementation) private {\n        if (newImplementation.code.length == 0) {\n            revert ERC1967InvalidImplementation(newImplementation);\n        }\n        StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value = newImplementation;\n    }\n\n    /**\n     * @dev Performs implementation upgrade with additional setup call if data is nonempty.\n     * This function is payable only if the setup call is performed, otherwise `msg.value` is rejected\n     * to avoid stuck value in the contract.\n     *\n     * Emits an {IERC1967-Upgraded} event.\n     */\n    function upgradeToAndCall(address newImplementation, bytes memory data) internal {\n        _setImplementation(newImplementation);\n        emit Upgraded(newImplementation);\n\n        if (data.length > 0) {\n            Address.functionDelegateCall(newImplementation, data);\n        } else {\n            _checkNonPayable();\n        }\n    }\n\n    /**\n     * @dev Storage slot with the admin of the contract.\n     * This is the keccak-256 hash of \"eip1967.proxy.admin\" subtracted by 1.\n     */\n    // solhint-disable-next-line private-vars-leading-underscore\n    bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;\n\n    /**\n     * @dev Returns the current admin.\n     *\n     * TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using\n     * the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.\n     * `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`\n     */\n    function getAdmin() internal view returns (address) {\n        return StorageSlot.getAddressSlot(ADMIN_SLOT).value;\n    }\n\n    /**\n     * @dev Stores a new address in the EIP1967 admin slot.\n     */\n    function _setAdmin(address newAdmin) private {\n        if (newAdmin == address(0)) {\n            revert ERC1967InvalidAdmin(address(0));\n        }\n        StorageSlot.getAddressSlot(ADMIN_SLOT).value = newAdmin;\n    }\n\n    /**\n     * @dev Changes the admin of the proxy.\n     *\n     * Emits an {IERC1967-AdminChanged} event.\n     */\n    function changeAdmin(address newAdmin) internal {\n        emit AdminChanged(getAdmin(), newAdmin);\n        _setAdmin(newAdmin);\n    }\n\n    /**\n     * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.\n     * This is the keccak-256 hash of \"eip1967.proxy.beacon\" subtracted by 1.\n     */\n    // solhint-disable-next-line private-vars-leading-underscore\n    bytes32 internal constant BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;\n\n    /**\n     * @dev Returns the current beacon.\n     */\n    function getBeacon() internal view returns (address) {\n        return StorageSlot.getAddressSlot(BEACON_SLOT).value;\n    }\n\n    /**\n     * @dev Stores a new beacon in the EIP1967 beacon slot.\n     */\n    function _setBeacon(address newBeacon) private {\n        if (newBeacon.code.length == 0) {\n            revert ERC1967InvalidBeacon(newBeacon);\n        }\n\n        StorageSlot.getAddressSlot(BEACON_SLOT).value = newBeacon;\n\n        address beaconImplementation = IBeacon(newBeacon).implementation();\n        if (beaconImplementation.code.length == 0) {\n            revert ERC1967InvalidImplementation(beaconImplementation);\n        }\n    }\n\n    /**\n     * @dev Change the beacon and trigger a setup call if data is nonempty.\n     * This function is payable only if the setup call is performed, otherwise `msg.value` is rejected\n     * to avoid stuck value in the contract.\n     *\n     * Emits an {IERC1967-BeaconUpgraded} event.\n     *\n     * CAUTION: Invoking this function has no effect on an instance of {BeaconProxy} since v5, since\n     * it uses an immutable beacon without looking at the value of the ERC-1967 beacon slot for\n     * efficiency.\n     */\n    function upgradeBeaconToAndCall(address newBeacon, bytes memory data) internal {\n        _setBeacon(newBeacon);\n        emit BeaconUpgraded(newBeacon);\n\n        if (data.length > 0) {\n            Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);\n        } else {\n            _checkNonPayable();\n        }\n    }\n\n    /**\n     * @dev Reverts if `msg.value` is not zero. It can be used to avoid `msg.value` stuck in the contract\n     * if an upgrade doesn't perform an initialization call.\n     */\n    function _checkNonPayable() private {\n        if (msg.value > 0) {\n            revert ERC1967NonPayable();\n        }\n    }\n}\n"
      },
      "src/interfaces/Balancer/IBalancerPool.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\nimport {IERC20} from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\n\npragma solidity ^0.8.20;\n\ninterface IBalancerPool {\n    function decimals() external view returns (uint256);\n    function getPoolId() external view returns (bytes32);\n\n    function getActualSupply() external view returns (uint256);\n\n    function getRate() external view returns (uint256);\n\n    function getTokenRate(IERC20 token) external view returns (uint256);\n\n    function getInvariant() external view returns (uint256 invariant_);\n\n    function getNormalizedWeights() external view returns (uint256[] memory);\n\n    function getSwapEnabled() external view returns (bool);\n\n    function getOwner() external view returns (address);\n\n    function totalSupply() external view returns (uint256);\n\n    function balanceOf(address account) external view returns (uint256);\n\n    function getBptIndex() external view returns (uint256);\n\n    function withdrawAndUnwrap(uint256 amount, bool claim) external returns (bool);\n}\n"
      },
      "src/interfaces/Omnipool/IOmnipoolController.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.20;\n\nimport \"src/interfaces/Omnipool/IOmnipool.sol\";\n\ninterface IOmnipoolController {\n    struct WeightUpdate {\n        address poolAddress;\n        uint256 newWeight;\n    }\n\n    function handleRebalancingRewards(\n        address account,\n        uint256 deviationBefore,\n        uint256 deviationAfter\n    ) external;\n\n    function computePoolWeights()\n        external\n        view\n        returns (address[] memory pools, uint256[] memory poolWeights, uint256 totalUSDValue);\n\n    function computePoolWeight(address pool)\n        external\n        view\n        returns (uint256 poolWeight, uint256 totalUSDValue);\n\n    function getLastWeightUpdate(address pool) external view returns (uint256);\n\n    function isPool(address poolAddress) external view returns (bool);\n\n    function setMinimumTaintedTransferAmount(address token, uint256 amount) external;\n\n    function isAllowedMultipleDepositsWithdraws(address poolAddress) external view returns (bool);\n\n    function getMinimumTaintedTransferAmount(address token) external view returns (uint256);\n}\n"
      },
      "src/interfaces/Balancer/IBalancerVault.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.8.20;\n\nimport \"balancer-v2-monorepo/pkg/interfaces/contracts/vault/IAsset.sol\";\n\ninterface IBalancerVault {\n    enum PoolSpecialization {\n        GENERAL,\n        MINIMAL_SWAP_INFO,\n        TWO_TOKEN\n    }\n    enum JoinKind {\n        INIT,\n        EXACT_TOKENS_IN_FOR_BPT_OUT,\n        TOKEN_IN_FOR_EXACT_BPT_OUT,\n        ALL_TOKENS_IN_FOR_EXACT_BPT_OUT\n    }\n\n    enum SwapKind {\n        GIVEN_IN,\n        GIVEN_OUT\n    }\n\n    struct BatchSwapStep {\n        bytes32 poolId;\n        uint256 assetInIndex;\n        uint256 assetOutIndex;\n        uint256 amount;\n        bytes userData;\n    }\n\n    function batchSwap(\n        SwapKind kind,\n        BatchSwapStep[] memory swaps,\n        IAsset[] memory assets,\n        FundManagement memory funds,\n        int256[] memory limits,\n        uint256 deadline\n    ) external payable returns (int256[] memory);\n\n    struct SingleSwap {\n        bytes32 poolId;\n        SwapKind kind;\n        IAsset assetIn;\n        IAsset assetOut;\n        uint256 amount;\n        bytes userData;\n    }\n\n    struct FundManagement {\n        address sender;\n        bool fromInternalBalance;\n        address payable recipient;\n        bool toInternalBalance;\n    }\n\n    struct JoinPoolRequest {\n        IAsset[] assets;\n        uint256[] maxAmountsIn;\n        bytes userData;\n        bool fromInternalBalance;\n    }\n\n    function getPool(bytes32 poolId) external view returns (address, PoolSpecialization);\n\n    function getPoolTokens(bytes32 poolId)\n        external\n        view\n        returns (address[] memory tokens, uint256[] memory balances, uint256 lastChangeBlock);\n\n    function joinPool(\n        bytes32 poolId,\n        address sender,\n        address recipient,\n        JoinPoolRequest memory request\n    ) external payable;\n\n    function swap(\n        SingleSwap memory singleSwap,\n        FundManagement memory funds,\n        uint256 limit,\n        uint256 deadline\n    ) external returns (uint256 amountCalculated);\n\n    function exitPool(\n        bytes32 poolId,\n        address sender,\n        address payable recipient,\n        ExitPoolRequest memory request\n    ) external;\n\n    function getInternalBalance(address user, address[] memory tokens)\n        external\n        view\n        returns (uint256[] memory);\n\n    function queryBatchSwap(\n        SwapKind kind,\n        BatchSwapStep[] memory swaps,\n        IAsset[] memory assets,\n        FundManagement memory funds\n    ) external returns (int256[] memory assetDeltas);\n\n    struct ExitPoolRequest {\n        IAsset[] assets;\n        uint256[] minAmountsOut;\n        bytes userData;\n        bool toInternalBalance;\n    }\n\n    enum ExitKind {\n        EXACT_BPT_IN_FOR_ONE_TOKEN_OUT,\n        EXACT_BPT_IN_FOR_TOKENS_OUT,\n        BPT_IN_FOR_EXACT_TOKENS_OUT,\n        MANAGEMENT_FEE_TOKENS_OUT // for ManagedPool\n\n    }\n}\n"
      },
      "src/pools/Oracle.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.20;\n\nimport {IERC20} from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport {Initializable} from \"@openzeppelin-upgradeable-contracts/proxy/utils/Initializable.sol\";\nimport {UUPSUpgradeable} from \"@openzeppelin-upgradeable-contracts/proxy/utils/UUPSUpgradeable.sol\";\nimport {SafeERC20} from \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\nimport {IERC20Metadata} from \"@openzeppelin/contracts/interfaces/IERC20Metadata.sol\";\nimport {IRateProvider} from\n    \"balancer-v2-monorepo/pkg/interfaces/contracts/pool-utils/IRateProvider.sol\";\nimport {IRateProviderPool} from\n    \"balancer-v2-monorepo/pkg/interfaces/contracts/pool-utils/IRateProviderPool.sol\";\nimport {IManagedPool} from\n    \"balancer-v2-monorepo/pkg/interfaces/contracts/pool-utils/IManagedPool.sol\";\nimport {IExternalWeightedMath} from\n    \"balancer-v2-monorepo/pkg/interfaces/contracts/pool-weighted/IExternalWeightedMath.sol\";\nimport {IBalancerPool} from \"src/interfaces/Balancer/IBalancerPool.sol\";\nimport {IBalancerVault} from \"src/interfaces/Balancer/IBalancerVault.sol\";\nimport {IOracle} from \"src/interfaces/IOracle.sol\";\nimport {IChainlinkOracle} from \"src/interfaces/Oracle/IChainlinkOracle.sol\";\nimport {ICurveOracle} from \"src/interfaces/Oracle/ICurveOracle.sol\";\nimport {IFraxOracle} from \"src/interfaces/Oracle/IFraxOracle.sol\";\nimport {IWstEth} from \"src/interfaces/Oracle/IWstEth.sol\";\nimport {VaultReentrancyLib} from \"src/utils/VaultReentrancyLib.sol\";\nimport {IVault} from \"balancer-v2-monorepo/pkg/interfaces/contracts/vault/IVault.sol\";\nimport {PRBMathSD59x18} from \"src/utils/PRBMathSD59x18.sol\";\nimport {PRBMathUD60x18} from \"src/utils/PRBMathUD60x18.sol\";\nimport {PoolType} from \"src/utils/constants.sol\";\n\nimport {IRegistryAccess} from \"src/interfaces/Registry/IRegistryAccess.sol\";\nimport {IRegistryContract} from \"src/interfaces/Registry/IRegistryContract.sol\";\nimport {\n    CONTRACT_ORACLE,\n    CONTRACT_REGISTRY_ACCESS,\n    ROLE_OPAL_TEAM,\n    CONTRACT_BALANCER_VAULT,\n    WETH,\n    SFRXETH,\n    CURVE_SFRXETH_ORACLE,\n    WSTETH\n} from \"src/utils/constants.sol\";\n\n/**\n * @title Oracle\n * @author Opal Team\n * @dev A smart contract for providing price information for Balancer pools in various types.\n */\ncontract Oracle is IOracle, Initializable, UUPSUpgradeable {\n    using PRBMathUD60x18 for uint256;\n\n    /**\n     *  @custom:library PRBMathSD59x18 Smart contract library for advanced fixed-point math that works with int256\n     */\n    using PRBMathSD59x18 for int256;\n\n    address public priceFeedAddress;\n\n    IRegistryAccess public registryAccess;\n    IRegistryContract public registryContract;\n    IBalancerVault internal balancerVault;\n\n    mapping(address => uint256) public tokenHeartbeat;\n    mapping(address => IChainlinkOracle) private _priceFeedMapping;\n    mapping(IChainlinkOracle => bool) private _isSupportedPriceFeed;\n    mapping(address => bool) public isEthLstPriceFeed;\n\n    uint256 constant MAX_UINT256 = type(uint256).max;\n\n    error NullAddress();\n    error PriceFeedNotFound();\n    error NotAuthorized();\n    error HeartbeatNotSet();\n    error StalePrice();\n    error InvalidPrice();\n    error InvalidPoolType();\n    error DecimalNotFetch();\n    error AlreadySupported();\n    error FailedToGetSharePrice();\n\n    event SetTokenHeartbeat(address token, uint256 heartbeat);\n    event AddNewPriceFeedAsset(address asset, address priceFeed);\n    event SupportLst(address token);\n    event RemoveLst(address token);\n\n    modifier onlyOpalTeam() {\n        if (!registryAccess.checkRole(ROLE_OPAL_TEAM, msg.sender)) revert NotAuthorized();\n        _;\n    }\n\n    function initialize(address registryContract_) public initializer {\n        if (registryContract_ == address(0)) revert NullAddress();\n        __UUPSUpgradeable_init();\n        registryContract = IRegistryContract(registryContract_);\n        registryAccess = IRegistryAccess(registryContract.getContract(CONTRACT_REGISTRY_ACCESS));\n        balancerVault = IBalancerVault(registryContract.getContract(CONTRACT_BALANCER_VAULT));\n    }\n\n    function _authorizeUpgrade(address newImplementation) internal override onlyOpalTeam {}\n\n    function addLst(address token) external onlyOpalTeam {\n        if (isEthLstPriceFeed[token]) revert AlreadySupported();\n        isEthLstPriceFeed[token] = true;\n        emit SupportLst(token);\n    }\n\n    function removeLst(address token) external onlyOpalTeam {\n        if (!isEthLstPriceFeed[token]) revert AlreadySupported();\n        isEthLstPriceFeed[token] = false;\n        emit RemoveLst(token);\n    }\n\n    /**\n     * @notice Add a new price feed for a specific asset\n     * @param asset The address of the asset\n     * @param priceFeed The address of the price feed contract (IChainlinkOracle)\n     */\n    function addPriceFeed(address asset, address priceFeed) public onlyOpalTeam {\n        _priceFeedMapping[asset] = IChainlinkOracle(priceFeed);\n        _isSupportedPriceFeed[IChainlinkOracle(priceFeed)] = true;\n        emit AddNewPriceFeedAsset(asset, priceFeed);\n    }\n\n    function updatePriceFeed(address asset, address priceFeed) public onlyOpalTeam {\n        if (!_isSupportedPriceFeed[_priceFeedMapping[asset]]) revert PriceFeedNotFound();\n        _priceFeedMapping[asset] = IChainlinkOracle(priceFeed);\n    }\n\n    function removePriceFeed(address asset) public onlyOpalTeam {\n        if (!_isSupportedPriceFeed[_priceFeedMapping[asset]]) revert PriceFeedNotFound();\n        delete _priceFeedMapping[asset];\n        _isSupportedPriceFeed[_priceFeedMapping[asset]] = false;\n    }\n\n    /**\n     * @notice  .\n     * @dev     .\n     * @param   token  address of the token.\n     * @param   heartbeat  the heartbeat of the token\n     */\n    function setHeartbeat(address token, uint256 heartbeat) external onlyOpalTeam {\n        tokenHeartbeat[token] = heartbeat;\n        emit SetTokenHeartbeat(token, heartbeat);\n    }\n\n    /**\n     * @dev Get the USD price for a stable pool identified by its poolId.\n     * @param poolId The poolId of the stable pool.\n     * @return The USD price for the stable pool.\n     */\n    function BptPriceStablePool(bytes32 poolId) public view returns (uint256) {\n        VaultReentrancyLib.ensureNotInVaultContext(IVault(address(balancerVault)));\n        (address[] memory tokens,,) = balancerVault.getPoolTokens(poolId);\n\n        (address poolAddress,) = balancerVault.getPool(poolId);\n        uint256 min = MAX_UINT256;\n        address token;\n        uint256 length = tokens.length;\n        for (uint256 i; i < length;) {\n            token = address(tokens[i]);\n\n            if (token == poolAddress) {\n                unchecked {\n                    ++i;\n                }\n                continue;\n            }\n\n            IBalancerPool pool = IBalancerPool(poolAddress);\n            uint256 value = getUSDPrice(token);\n            try pool.getTokenRate(IERC20(token)) returns (uint256 rate) {\n                value = value * 1e18 / rate;\n            } catch {}\n            if (value < min) {\n                min = value;\n            }\n\n            unchecked {\n                ++i;\n            }\n        }\n        return (min * IRateProvider(poolAddress).getRate()) / 1e18;\n    }\n\n    /**\n     * @dev Get the USD price for a weighted pool identified by its poolId.\n     * @dev https://hackmd.io/@re73/SJHmQaCFq\n     * @param poolId The poolId of the weighted pool.\n     * @return The USD price for the weighted pool.\n     */\n    function BptPriceWeightPool(bytes32 poolId) public view returns (uint256) {\n        VaultReentrancyLib.ensureNotInVaultContext(IVault(address(balancerVault)));\n        (address[] memory tokens,,) = balancerVault.getPoolTokens(poolId);\n\n        (address poolAddress,) = balancerVault.getPool(poolId);\n\n        // 1. weight = balance * price / invariant\n        uint256[] memory weights = IManagedPool(poolAddress).getNormalizedWeights();\n\n        uint256 length = tokens.length;\n\n        int256 invariant = int256(IBalancerPool(poolAddress).getInvariant());\n\n        int256 totalPi = PRBMathSD59x18.fromInt(1e18);\n\n        for (uint256 i = 0; i < length;) {\n            // Get token price\n            uint256 assetPrice = getUSDPrice(address(tokens[i]));\n\n            uint256 weight = weights[i];\n            if (weight == 0) {\n                unchecked {\n                    ++i;\n                }\n                continue;\n            }\n\n            int256 actualPrice = int256(assetPrice.mul(1e18).div(weight));\n\n            int256 uniquePi = actualPrice.pow(int256(weight));\n\n            totalPi = totalPi.mul(uniquePi);\n\n            unchecked {\n                ++i;\n            }\n        }\n\n        // Pool TVL in USD\n        int256 numerator = totalPi.mul(invariant);\n\n        // 4. Total Supply of BPT tokens for this pool.\n        // Try using actualSupply on compatible pools, or fallback to totalSupply.\n        int256 totalSupply;\n        try IManagedPool(poolAddress).getActualSupply() returns (uint256 supply) {\n            totalSupply = int256(supply);\n        } catch {\n            totalSupply = int256(IBalancerPool(poolAddress).totalSupply());\n        }\n\n        // 5. BPT Price (USD) = TVL / totalSupply\n        uint256 bptPrice = uint256((numerator.toInt().div(totalSupply)));\n        return bptPrice;\n    }\n\n    /**\n     * @dev Get the USD price for a composable pool identified by its poolId.\n     * @param poolId The poolId of the composable pool.\n     * @return The USD price for the composable pool.\n     */\n    function BptPriceComposablePool(bytes32 poolId) public view returns (uint256) {\n        VaultReentrancyLib.ensureNotInVaultContext(IVault(address(balancerVault)));\n        (address[] memory tokens,,) = balancerVault.getPoolTokens(poolId);\n\n        (address pool,) = balancerVault.getPool(poolId);\n\n        uint256 length = tokens.length;\n\n        uint256 minPrice = MAX_UINT256;\n        IRateProvider[] memory rateProviders = IRateProviderPool(pool).getRateProviders();\n\n        for (uint256 i; i < length;) {\n            if (address(tokens[i]) == pool) {\n                unchecked {\n                    ++i;\n                }\n                continue;\n            }\n            uint256 tokenRate =\n                address(rateProviders[i]) == address(0) ? 1e18 : rateProviders[i].getRate();\n\n            // Get token price\n            uint256 marketPrice = getUSDPrice(address(tokens[i]));\n            uint256 normalizedPrice = marketPrice * 1e18 / tokenRate;\n            minPrice = minPrice < normalizedPrice ? minPrice : normalizedPrice;\n\n            unchecked {\n                ++i;\n            }\n        }\n\n        uint256 priceResult = minPrice * IRateProvider(pool).getRate();\n\n        return priceResult / 1e18;\n    }\n\n    /**\n     * @dev Get the USD valuation for a Balancer pool based on its poolId and type.\n     * @param poolId The poolId of the Balancer pool.\n     * @param poolType The type of the Balancer pool.\n     * @return The USD valuation for the Balancer pool.\n     */\n    function getPoolValuation(bytes32 poolId, PoolType poolType) external view returns (uint256) {\n        if (poolType == PoolType.WEIGHTED) {\n            return BptPriceWeightPool(poolId);\n        } else if (poolType == PoolType.STABLE) {\n            return BptPriceStablePool(poolId);\n        } else if (poolType == PoolType.COMPOSABLE) {\n            return BptPriceComposablePool(poolId);\n        }\n        revert InvalidPoolType();\n    }\n\n    /**\n     * @dev call the oracle to get the price in USD with 18 decimals\n     * @param token the token address\n     * @return priceInUSD the amount in USD with token decimals\n     */\n    function getUSDPrice(address token) public view returns (uint256 priceInUSD) {\n        if (token == SFRXETH) {\n            return _getSfrxETHPrice();\n        } else if (token == WSTETH) {\n            return _getWstEthPrice();\n        } else if (isEthLstPriceFeed[token]) {\n            return _getLstPriceFromEth(token);\n        }\n        return _getUSDPrice(token);\n    }\n\n    /**\n     * @dev call the oracle to get the price in USD with 18 decimals\n     * @param token the token address\n     * @return priceInUSD the amount in USD with token decimals\n     */\n    function _getUSDPrice(address token) public view returns (uint256 priceInUSD) {\n        uint256 heartbeat = tokenHeartbeat[token];\n        if (heartbeat == 0) {\n            revert HeartbeatNotSet();\n        }\n\n        IChainlinkOracle priceFeed = _priceFeedMapping[token];\n\n        if (address(priceFeed) == address(0)) revert PriceFeedNotFound();\n        (, int256 priceInUSDInt,, uint256 updatedAt,) = priceFeed.latestRoundData();\n        if (priceInUSDInt <= 0) revert InvalidPrice();\n        if (updatedAt + tokenHeartbeat[token] < block.timestamp) revert StalePrice();\n        if (priceInUSDInt < 0) revert StalePrice();\n        // Oracle answer are normalized to 8 decimals\n        try priceFeed.decimals() returns (uint8) {\n            uint256 newPrice = _normalizeAmount(uint256(priceInUSDInt), priceFeed.decimals());\n            return newPrice;\n        } catch {\n            revert DecimalNotFetch();\n        }\n    }\n\n    /**\n     * @dev call the oracle to get the price in USD with 18 decimals\n     * @param token the token address\n     * @return priceInUSD the amount in USD with token decimals\n     */\n    function _getLstPriceFromEth(address token) public view returns (uint256 priceInUSD) {\n        uint256 ethPrice = _getUSDPrice(WETH);\n        uint256 tokenPrice = _getUSDPrice(token);\n        return tokenPrice * ethPrice / 1e18;\n    }\n\n    function _getSfrxETHPrice() public view returns (uint256 price) {\n        uint256 pricePerShare = IFraxOracle(SFRXETH).pricePerShare();\n        ICurveOracle oracle = ICurveOracle(CURVE_SFRXETH_ORACLE);\n        uint256 ethPrice = _getUSDPrice(WETH);\n        return (pricePerShare * oracle.price_oracle() / 1e18) * ethPrice / 1e18;\n    }\n\n    function _getWstEthPrice() public view returns (uint256 price) {\n        uint256 pricePerShare = IWstEth(WSTETH).stEthPerToken();\n        uint256 ethPrice = _getUSDPrice(WETH);\n        return pricePerShare * ethPrice / 1e18;\n    }\n\n    function _normalizeAmount(uint256 _price, uint256 _answerDigits)\n        public\n        pure\n        returns (uint256 price)\n    {\n        uint256 targetDigits = 18;\n        if (_answerDigits >= targetDigits) {\n            // Scale the returned price value down to target precision\n            price = _price / (10 ** (_answerDigits - targetDigits));\n        } else if (_answerDigits < targetDigits) {\n            // Scale the returned price value up to target precision\n            price = _price * (10 ** (targetDigits - _answerDigits));\n        }\n        return price;\n    }\n}\n"
      },
      "lib/openzeppelin-contracts/contracts/proxy/beacon/IBeacon.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (proxy/beacon/IBeacon.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev This is the interface that {BeaconProxy} expects of its beacon.\n */\ninterface IBeacon {\n    /**\n     * @dev Must return an address that can be used as a delegate call target.\n     *\n     * {UpgradeableBeacon} will check that this address is a contract.\n     */\n    function implementation() external view returns (address);\n}\n"
      },
      "lib/openzeppelin-contracts/contracts/utils/StorageSlot.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.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 ERC1967 implementation slot:\n * ```solidity\n * contract ERC1967 {\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 */\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 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        /// @solidity memory-safe-assembly\n        assembly {\n            r.slot := slot\n        }\n    }\n\n    /**\n     * @dev Returns an `BooleanSlot` with member `value` located at `slot`.\n     */\n    function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            r.slot := slot\n        }\n    }\n\n    /**\n     * @dev Returns an `Bytes32Slot` with member `value` located at `slot`.\n     */\n    function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            r.slot := slot\n        }\n    }\n\n    /**\n     * @dev Returns an `Uint256Slot` with member `value` located at `slot`.\n     */\n    function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            r.slot := slot\n        }\n    }\n\n    /**\n     * @dev Returns an `StringSlot` with member `value` located at `slot`.\n     */\n    function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {\n        /// @solidity memory-safe-assembly\n        assembly {\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        /// @solidity memory-safe-assembly\n        assembly {\n            r.slot := store.slot\n        }\n    }\n\n    /**\n     * @dev Returns an `BytesSlot` with member `value` located at `slot`.\n     */\n    function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {\n        /// @solidity memory-safe-assembly\n        assembly {\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        /// @solidity memory-safe-assembly\n        assembly {\n            r.slot := store.slot\n        }\n    }\n}\n"
      },
      "lib/balancer-v2-monorepo/pkg/interfaces/contracts/vault/IAsset.sol": {
        "content": "// SPDX-License-Identifier: GPL-3.0-or-later\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n// GNU General Public License for more details.\n\n// You should have received a copy of the GNU General Public License\n// along with this program.  If not, see <http://www.gnu.org/licenses/>.\n\npragma solidity >=0.7.0 <0.9.0;\n\n/**\n * @dev This is an empty interface used to represent either ERC20-conforming token contracts or ETH (using the zero\n * address sentinel value). We're just relying on the fact that `interface` can be used to declare new address-like\n * types.\n *\n * This concept is unrelated to a Pool's Asset Managers.\n */\ninterface IAsset {\n    // solhint-disable-previous-line no-empty-blocks\n}\n"
      },
      "lib/openzeppelin-contracts/contracts/interfaces/IERC20Metadata.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC20Metadata.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC20Metadata} from \"../token/ERC20/extensions/IERC20Metadata.sol\";\n"
      },
      "lib/balancer-v2-monorepo/pkg/interfaces/contracts/pool-utils/IRateProvider.sol": {
        "content": "// SPDX-License-Identifier: GPL-3.0-or-later\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n// GNU General Public License for more details.\n\n// You should have received a copy of the GNU General Public License\n// along with this program.  If not, see <http://www.gnu.org/licenses/>.\n\npragma solidity >=0.7.0 <0.9.0;\n\ninterface IRateProvider {\n    /**\n     * @dev Returns an 18 decimal fixed point number that is the exchange rate of the token to some other underlying\n     * token. The meaning of this rate depends on the context.\n     */\n    function getRate() external view returns (uint256);\n}\n"
      },
      "lib/balancer-v2-monorepo/pkg/interfaces/contracts/pool-utils/IRateProviderPool.sol": {
        "content": "// SPDX-License-Identifier: GPL-3.0-or-later\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n// GNU General Public License for more details.\n\n// You should have received a copy of the GNU General Public License\n// along with this program.  If not, see <http://www.gnu.org/licenses/>.\n\npragma solidity >=0.7.0 <0.9.0;\n\nimport \"./IRateProvider.sol\";\n\n/**\n * @dev Interface for Pools that assign rate providers to their tokens.\n */\ninterface IRateProviderPool {\n    /**\n     * @dev Returns the rate provider for each of the Pool's tokens. A zero-address entry means there's no rate provider\n     * for that token.\n     */\n    function getRateProviders() external view returns (IRateProvider[] memory);\n}\n"
      },
      "lib/balancer-v2-monorepo/pkg/interfaces/contracts/pool-utils/IManagedPool.sol": {
        "content": "// SPDX-License-Identifier: GPL-3.0-or-later\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n// GNU General Public License for more details.\n\n// You should have received a copy of the GNU General Public License\n// along with this program.  If not, see <http://www.gnu.org/licenses/>.\n\npragma solidity >=0.7.0 <0.9.0;\n\nimport \"../solidity-utils/openzeppelin/IERC20.sol\";\nimport \"../vault/IBasePool.sol\";\n\ninterface IManagedPool is IBasePool {\n    event GradualSwapFeeUpdateScheduled(\n        uint256 startTime,\n        uint256 endTime,\n        uint256 startSwapFeePercentage,\n        uint256 endSwapFeePercentage\n    );\n    event GradualWeightUpdateScheduled(\n        uint256 startTime,\n        uint256 endTime,\n        uint256[] startWeights,\n        uint256[] endWeights\n    );\n    event SwapEnabledSet(bool swapEnabled);\n    event JoinExitEnabledSet(bool joinExitEnabled);\n    event MustAllowlistLPsSet(bool mustAllowlistLPs);\n    event AllowlistAddressAdded(address indexed member);\n    event AllowlistAddressRemoved(address indexed member);\n    event ManagementAumFeePercentageChanged(uint256 managementAumFeePercentage);\n    event ManagementAumFeeCollected(uint256 bptAmount);\n    event CircuitBreakerSet(\n        IERC20 indexed token,\n        uint256 bptPrice,\n        uint256 lowerBoundPercentage,\n        uint256 upperBoundPercentage\n    );\n    event TokenAdded(IERC20 indexed token, uint256 normalizedWeight);\n    event TokenRemoved(IERC20 indexed token);\n\n    /**\n     * @notice Returns the effective BPT supply.\n     *\n     * @dev The Pool owes debt to the Protocol and the Pool's owner in the form of unminted BPT, which will be minted\n     * immediately before the next join or exit. We need to take these into account since, even if they don't yet exist,\n     * they will effectively be included in any Pool operation that involves BPT.\n     *\n     * In the vast majority of cases, this function should be used instead of `totalSupply()`.\n     *\n     * WARNING: since this function reads balances directly from the Vault, it is potentially subject to manipulation\n     * via reentrancy. See https://forum.balancer.fi/t/reentrancy-vulnerability-scope-expanded/4345 for reference.\n     *\n     * To call this function safely, attempt to trigger the reentrancy guard in the Vault by calling a non-reentrant\n     * function before calling `getActualSupply`. That will make the transaction revert in an unsafe context.\n     * (See `whenNotInVaultContext` in `ManagedPoolSettings`).\n     */\n    function getActualSupply() external view returns (uint256);\n\n    // Swap fee percentage\n\n    /**\n     * @notice Schedule a gradual swap fee update.\n     * @dev The swap fee will change from the given starting value (which may or may not be the current\n     * value) to the given ending fee percentage, over startTime to endTime.\n     *\n     * Note that calling this with a starting swap fee different from the current value will immediately change the\n     * current swap fee to `startSwapFeePercentage`, before commencing the gradual change at `startTime`.\n     * Emits the GradualSwapFeeUpdateScheduled event.\n     * This is a permissioned function.\n     *\n     * @param startTime - The timestamp when the swap fee change will begin.\n     * @param endTime - The timestamp when the swap fee change will end (must be >= startTime).\n     * @param startSwapFeePercentage - The starting value for the swap fee change.\n     * @param endSwapFeePercentage - The ending value for the swap fee change. If the current timestamp >= endTime,\n     * `getSwapFeePercentage()` will return this value.\n     */\n    function updateSwapFeeGradually(\n        uint256 startTime,\n        uint256 endTime,\n        uint256 startSwapFeePercentage,\n        uint256 endSwapFeePercentage\n    ) external;\n\n    /**\n     * @notice Returns the current gradual swap fee update parameters.\n     * @dev The current swap fee can be retrieved via `getSwapFeePercentage()`.\n     * @return startTime - The timestamp when the swap fee update will begin.\n     * @return endTime - The timestamp when the swap fee update will end.\n     * @return startSwapFeePercentage - The starting swap fee percentage (could be different from the current value).\n     * @return endSwapFeePercentage - The final swap fee percentage, when the current timestamp >= endTime.\n     */\n    function getGradualSwapFeeUpdateParams()\n        external\n        view\n        returns (\n            uint256 startTime,\n            uint256 endTime,\n            uint256 startSwapFeePercentage,\n            uint256 endSwapFeePercentage\n        );\n\n    // Token weights\n\n    /**\n     * @notice Schedule a gradual weight change.\n     * @dev The weights will change from their current values to the given endWeights, over startTime to endTime.\n     * This is a permissioned function.\n     *\n     * Since, unlike with swap fee updates, we generally do not want to allow instantaneous weight changes,\n     * the weights always start from their current values. This also guarantees a smooth transition when\n     * updateWeightsGradually is called during an ongoing weight change.\n     * @param startTime - The timestamp when the weight change will begin.\n     * @param endTime - The timestamp when the weight change will end (can be >= startTime).\n     * @param tokens - The tokens associated with the target weights (must match the current pool tokens).\n     * @param endWeights - The target weights. If the current timestamp >= endTime, `getNormalizedWeights()`\n     * will return these values.\n     */\n    function updateWeightsGradually(\n        uint256 startTime,\n        uint256 endTime,\n        IERC20[] memory tokens,\n        uint256[] memory endWeights\n    ) external;\n\n    /**\n     * @notice Returns all normalized weights, in the same order as the Pool's tokens.\n     */\n    function getNormalizedWeights() external view returns (uint256[] memory);\n\n    /**\n     * @notice Returns the current gradual weight change update parameters.\n     * @dev The current weights can be retrieved via `getNormalizedWeights()`.\n     * @return startTime - The timestamp when the weight update will begin.\n     * @return endTime - The timestamp when the weight update will end.\n     * @return startWeights - The starting weights, when the weight change was initiated.\n     * @return endWeights - The final weights, when the current timestamp >= endTime.\n     */\n    function getGradualWeightUpdateParams()\n        external\n        view\n        returns (\n            uint256 startTime,\n            uint256 endTime,\n            uint256[] memory startWeights,\n            uint256[] memory endWeights\n        );\n\n    // Join and Exit enable/disable\n\n    /**\n     * @notice Enable or disable joins and exits. Note that this does not affect Recovery Mode exits.\n     * @dev Emits the JoinExitEnabledSet event. This is a permissioned function.\n     * @param joinExitEnabled - The new value of the join/exit enabled flag.\n     */\n    function setJoinExitEnabled(bool joinExitEnabled) external;\n\n    /**\n     * @notice Returns whether joins and exits are enabled.\n     */\n    function getJoinExitEnabled() external view returns (bool);\n\n    // Swap enable/disable\n\n    /**\n     * @notice Enable or disable trading.\n     * @dev Emits the SwapEnabledSet event. This is a permissioned function.\n     * @param swapEnabled - The new value of the swap enabled flag.\n     */\n    function setSwapEnabled(bool swapEnabled) external;\n\n    /**\n     * @notice Returns whether swaps are enabled.\n     */\n    function getSwapEnabled() external view returns (bool);\n\n    // LP Allowlist\n\n    /**\n     * @notice Enable or disable the LP allowlist.\n     * @dev Note that any addresses added to the allowlist will be retained if the allowlist is toggled off and\n     * back on again, because this action does not affect the list of LP addresses.\n     * Emits the MustAllowlistLPsSet event. This is a permissioned function.\n     * @param mustAllowlistLPs - The new value of the mustAllowlistLPs flag.\n     */\n    function setMustAllowlistLPs(bool mustAllowlistLPs) external;\n\n    /**\n     * @notice Adds an address to the LP allowlist.\n     * @dev Will fail if the address is already allowlisted.\n     * Emits the AllowlistAddressAdded event. This is a permissioned function.\n     * @param member - The address to be added to the allowlist.\n     */\n    function addAllowedAddress(address member) external;\n\n    /**\n     * @notice Removes an address from the LP allowlist.\n     * @dev Will fail if the address was not previously allowlisted.\n     * Emits the AllowlistAddressRemoved event. This is a permissioned function.\n     * @param member - The address to be removed from the allowlist.\n     */\n    function removeAllowedAddress(address member) external;\n\n    /**\n     * @notice Returns whether the allowlist for LPs is enabled.\n     */\n    function getMustAllowlistLPs() external view returns (bool);\n\n    /**\n     * @notice Check whether an LP address is on the allowlist.\n     * @dev This simply checks the list, regardless of whether the allowlist feature is enabled.\n     * @param member - The address to check against the allowlist.\n     * @return true if the given address is on the allowlist.\n     */\n    function isAddressOnAllowlist(address member) external view returns (bool);\n\n    // Management fees\n\n    /**\n     * @notice Collect any accrued AUM fees and send them to the pool manager.\n     * @dev This can be called by anyone to collect accrued AUM fees - and will be called automatically\n     * whenever the supply changes (e.g., joins and exits, add and remove token), and before the fee\n     * percentage is changed by the manager, to prevent fees from being applied retroactively.\n     *\n     * Correct behavior depends on the current supply, which is potentially manipulable if the pool\n     * is reentered during execution of a Vault hook. This is protected where overridden in ManagedPoolSettings,\n     * and so is safe to call on ManagedPool.\n     *\n     * See https://forum.balancer.fi/t/reentrancy-vulnerability-scope-expanded/4345 for reference.\n     *\n     * @return The amount of BPT minted to the manager.\n     */\n    function collectAumManagementFees() external returns (uint256);\n\n    /**\n     * @notice Setter for the yearly percentage AUM management fee, which is payable to the pool manager.\n     * @dev Attempting to collect AUM fees in excess of the maximum permitted percentage will revert.\n     * To avoid retroactive fee increases, we force collection at the current fee percentage before processing\n     * the update. Emits the ManagementAumFeePercentageChanged event. This is a permissioned function.\n     *\n     * To prevent changing management fees retroactively, this triggers payment of protocol fees before applying\n     * the change. Correct behavior depends on the current supply, which is potentially manipulable if the pool\n     * is reentered during execution of a Vault hook. This is protected where overridden in ManagedPoolSettings,\n     * and so is safe to call on ManagedPool.\n     *\n     * See https://forum.balancer.fi/t/reentrancy-vulnerability-scope-expanded/4345 for reference.\n     *\n     * @param managementAumFeePercentage - The new management AUM fee percentage.\n     * @return amount - The amount of BPT minted to the manager before the update, if any.\n     */\n    function setManagementAumFeePercentage(uint256 managementAumFeePercentage) external returns (uint256);\n\n    /**\n     * @notice Returns the management AUM fee percentage as an 18-decimal fixed point number and the timestamp of the\n     * last collection of AUM fees.\n     */\n    function getManagementAumFeeParams()\n        external\n        view\n        returns (uint256 aumFeePercentage, uint256 lastCollectionTimestamp);\n\n    // Circuit Breakers\n\n    /**\n     * @notice Set a circuit breaker for one or more tokens.\n     * @dev This is a permissioned function. The lower and upper bounds are percentages, corresponding to a\n     * relative change in the token's spot price: e.g., a lower bound of 0.8 means the breaker should prevent\n     * trades that result in the value of the token dropping 20% or more relative to the rest of the pool.\n     */\n    function setCircuitBreakers(\n        IERC20[] memory tokens,\n        uint256[] memory bptPrices,\n        uint256[] memory lowerBoundPercentages,\n        uint256[] memory upperBoundPercentages\n    ) external;\n\n    /**\n     * @notice Return the full circuit breaker state for the given token.\n     * @dev These are the reference values (BPT price and reference weight) passed in when the breaker was set,\n     * along with the percentage bounds. It also returns the current BPT price bounds, needed to check whether\n     * the circuit breaker should trip.\n     */\n    function getCircuitBreakerState(IERC20 token)\n        external\n        view\n        returns (\n            uint256 bptPrice,\n            uint256 referenceWeight,\n            uint256 lowerBound,\n            uint256 upperBound,\n            uint256 lowerBptPriceBound,\n            uint256 upperBptPriceBound\n        );\n\n    // Add/remove tokens\n\n    /**\n     * @notice Adds a token to the Pool's list of tradeable tokens. This is a permissioned function.\n     *\n     * @dev By adding a token to the Pool's composition, the weights of all other tokens will be decreased. The new\n     * token will have no balance - it is up to the owner to provide some immediately after calling this function.\n     * Note however that regular join functions will not work while the new token has no balance: the only way to\n     * deposit an initial amount is by using an Asset Manager.\n     *\n     * Token addition is forbidden during a weight change, or if one is scheduled to happen in the future.\n     *\n     * The caller may additionally pass a non-zero `mintAmount` to have some BPT be minted for them, which might be\n     * useful in some scenarios to account for the fact that the Pool will have more tokens.\n     *\n     * Emits the TokenAdded event. This is a permissioned function.\n     *\n     * Correct behavior depends on the token balances from the Vault, which may be out of sync with the state of\n     * the pool during execution of a Vault hook. This is protected where overridden in ManagedPoolSettings,\n     * and so is safe to call on ManagedPool.\n     *\n     * See https://forum.balancer.fi/t/reentrancy-vulnerability-scope-expanded/4345 for reference.\n     *\n     * @param tokenToAdd - The ERC20 token to be added to the Pool.\n     * @param assetManager - The Asset Manager for the token.\n     * @param tokenToAddNormalizedWeight - The normalized weight of `token` relative to the other tokens in the Pool.\n     * @param mintAmount - The amount of BPT to be minted as a result of adding `token` to the Pool.\n     * @param recipient - The address to receive the BPT minted by the Pool.\n     */\n    function addToken(\n        IERC20 tokenToAdd,\n        address assetManager,\n        uint256 tokenToAddNormalizedWeight,\n        uint256 mintAmount,\n        address recipient\n    ) external;\n\n    /**\n     * @notice Removes a token from the Pool's list of tradeable tokens.\n     * @dev Tokens can only be removed if the Pool has more than 2 tokens, as it can never have fewer than 2 (not\n     * including BPT). Token removal is also forbidden during a weight change, or if one is scheduled to happen in\n     * the future.\n     *\n     * Emits the TokenRemoved event. This is a permissioned function.\n     * Correct behavior depends on the token balances from the Vault, which may be out of sync with the state of\n     * the pool during execution of a Vault hook. This is protected where overridden in ManagedPoolSettings,\n     * and so is safe to call on ManagedPool.\n     *\n     * See https://forum.balancer.fi/t/reentrancy-vulnerability-scope-expanded/4345 for reference.\n     *\n     * The caller may additionally pass a non-zero `burnAmount` to burn some of their BPT, which might be useful\n     * in some scenarios to account for the fact that the Pool now has fewer tokens. This is a permissioned function.\n     * @param tokenToRemove - The ERC20 token to be removed from the Pool.\n     * @param burnAmount - The amount of BPT to be burned after removing `token` from the Pool.\n     * @param sender - The address to burn BPT from.\n     */\n    function removeToken(\n        IERC20 tokenToRemove,\n        uint256 burnAmount,\n        address sender\n    ) external;\n}\n"
      },
      "lib/balancer-v2-monorepo/pkg/interfaces/contracts/pool-weighted/IExternalWeightedMath.sol": {
        "content": "// SPDX-License-Identifier: GPL-3.0-or-later\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n// GNU General Public License for more details.\n\n// You should have received a copy of the GNU General Public License\n// along with this program.  If not, see <http://www.gnu.org/licenses/>.\n\npragma solidity >=0.7.0 <0.9.0;\n\n/**\n * @notice Interface for ExternalWeightedMath, a contract-wrapper for Weighted Math, Joins and Exits.\n */\ninterface IExternalWeightedMath {\n    /**\n     * @dev See `WeightedMath._calculateInvariant`.\n     */\n    function calculateInvariant(uint256[] memory normalizedWeights, uint256[] memory balances)\n        external\n        pure\n        returns (uint256);\n\n    /**\n     * @dev See `WeightedMath._calcOutGivenIn`.\n     */\n    function calcOutGivenIn(\n        uint256 balanceIn,\n        uint256 weightIn,\n        uint256 balanceOut,\n        uint256 weightOut,\n        uint256 amountIn\n    ) external pure returns (uint256);\n\n    /**\n     * @dev See `WeightedMath._calcInGivenOut`.\n     */\n    function calcInGivenOut(\n        uint256 balanceIn,\n        uint256 weightIn,\n        uint256 balanceOut,\n        uint256 weightOut,\n        uint256 amountOut\n    ) external pure returns (uint256);\n\n    /**\n     * @dev See `WeightedMath._calcBptOutGivenExactTokensIn`.\n     */\n    function calcBptOutGivenExactTokensIn(\n        uint256[] memory balances,\n        uint256[] memory normalizedWeights,\n        uint256[] memory amountsIn,\n        uint256 bptTotalSupply,\n        uint256 swapFeePercentage\n    ) external pure returns (uint256);\n\n    /**\n     * @dev See `WeightedMath._calcBptOutGivenExactTokenIn`.\n     */\n    function calcBptOutGivenExactTokenIn(\n        uint256 balance,\n        uint256 normalizedWeight,\n        uint256 amountIn,\n        uint256 bptTotalSupply,\n        uint256 swapFeePercentage\n    ) external pure returns (uint256);\n\n    /**\n     * @dev See `WeightedMath._calcTokenInGivenExactBptOut`.\n     */\n    function calcTokenInGivenExactBptOut(\n        uint256 balance,\n        uint256 normalizedWeight,\n        uint256 bptAmountOut,\n        uint256 bptTotalSupply,\n        uint256 swapFeePercentage\n    ) external pure returns (uint256);\n\n    /**\n     * @dev See `WeightedMath._calcAllTokensInGivenExactBptOut`.\n     */\n    function calcAllTokensInGivenExactBptOut(\n        uint256[] memory balances,\n        uint256 bptAmountOut,\n        uint256 totalBPT\n    ) external pure returns (uint256[] memory);\n\n    /**\n     * @dev See `WeightedMath._calcBptInGivenExactTokensOut`.\n     */\n    function calcBptInGivenExactTokensOut(\n        uint256[] memory balances,\n        uint256[] memory normalizedWeights,\n        uint256[] memory amountsOut,\n        uint256 bptTotalSupply,\n        uint256 swapFeePercentage\n    ) external pure returns (uint256);\n\n    /**\n     * @dev See `WeightedMath._calcBptInGivenExactTokenOut`.\n     */\n    function calcBptInGivenExactTokenOut(\n        uint256 balance,\n        uint256 normalizedWeight,\n        uint256 amountOut,\n        uint256 bptTotalSupply,\n        uint256 swapFeePercentage\n    ) external pure returns (uint256);\n\n    /**\n     * @dev See `WeightedMath._calcTokenOutGivenExactBptIn`.\n     */\n    function calcTokenOutGivenExactBptIn(\n        uint256 balance,\n        uint256 normalizedWeight,\n        uint256 bptAmountIn,\n        uint256 bptTotalSupply,\n        uint256 swapFeePercentage\n    ) external pure returns (uint256);\n\n    /**\n     * @dev See `WeightedMath._calcTokensOutGivenExactBptIn`.\n     */\n    function calcTokensOutGivenExactBptIn(\n        uint256[] memory balances,\n        uint256 bptAmountIn,\n        uint256 totalBPT\n    ) external pure returns (uint256[] memory);\n\n    /**\n     * @dev See `WeightedMath._calcBptOutAddToken`.\n     */\n    function calcBptOutAddToken(uint256 totalSupply, uint256 normalizedWeight) external pure returns (uint256);\n\n    /**\n     * @dev See `WeightedJoinsLib.joinExactTokensInForBPTOut`.\n     */\n    function joinExactTokensInForBPTOut(\n        uint256[] memory balances,\n        uint256[] memory normalizedWeights,\n        uint256[] memory scalingFactors,\n        uint256 totalSupply,\n        uint256 swapFeePercentage,\n        bytes memory userData\n    ) external pure returns (uint256, uint256[] memory);\n\n    /**\n     * @dev See `WeightedJoinsLib.joinTokenInForExactBPTOut`.\n     */\n    function joinTokenInForExactBPTOut(\n        uint256[] memory balances,\n        uint256[] memory normalizedWeights,\n        uint256 totalSupply,\n        uint256 swapFeePercentage,\n        bytes memory userData\n    ) external pure returns (uint256, uint256[] memory);\n\n    /**\n     * @dev See `WeightedJoinsLib.joinAllTokensInForExactBPTOut`.\n     */\n    function joinAllTokensInForExactBPTOut(\n        uint256[] memory balances,\n        uint256 totalSupply,\n        bytes memory userData\n    ) external pure returns (uint256 bptAmountOut, uint256[] memory amountsIn);\n\n    /**\n     * @dev See `WeightedExitsLib.exitExactBPTInForTokenOut`.\n     */\n    function exitExactBPTInForTokenOut(\n        uint256[] memory balances,\n        uint256[] memory normalizedWeights,\n        uint256 totalSupply,\n        uint256 swapFeePercentage,\n        bytes memory userData\n    ) external pure returns (uint256, uint256[] memory);\n\n    /**\n     * @dev See `WeightedExitsLib.exitExactBPTInForTokensOut`.\n     */\n    function exitExactBPTInForTokensOut(\n        uint256[] memory balances,\n        uint256 totalSupply,\n        bytes memory userData\n    ) external pure returns (uint256 bptAmountIn, uint256[] memory amountsOut);\n\n    /**\n     * @dev See `WeightedExitsLib.exitBPTInForExactTokensOut`.\n     */\n    function exitBPTInForExactTokensOut(\n        uint256[] memory balances,\n        uint256[] memory normalizedWeights,\n        uint256[] memory scalingFactors,\n        uint256 totalSupply,\n        uint256 swapFeePercentage,\n        bytes memory userData\n    ) external pure returns (uint256, uint256[] memory);\n}\n"
      },
      "src/interfaces/IOracle.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.20;\n\nimport {PoolType} from \"src/utils/constants.sol\";\n\ninterface IOracle {\n    function getUSDPrice(address token) external view returns (uint256);\n\n    function getPoolValuation(bytes32 poolId, PoolType poolType) external view returns (uint256);\n}\n"
      },
      "src/interfaces/Oracle/IChainlinkOracle.sol": {
        "content": "// SPDX-License-Identifier: Apache-2.0\npragma solidity 0.8.20;\n\ninterface IChainlinkOracle {\n    function decimals() external view returns (uint8);\n    function description() external view returns (string memory);\n    function version() external view returns (uint256);\n\n    function getRoundData(uint80 _roundId)\n        external\n        view\n        returns (\n            uint80 roundId,\n            int256 answer,\n            uint256 startedAt,\n            uint256 updatedAt,\n            uint80 answeredInRound\n        );\n\n    function latestRoundData()\n        external\n        view\n        returns (\n            uint80 roundId,\n            int256 answer,\n            uint256 startedAt,\n            uint256 updatedAt,\n            uint80 answeredInRound\n        );\n}\n"
      },
      "src/interfaces/Oracle/ICurveOracle.sol": {
        "content": "// SPDX-License-Identifier: Apache-2.0\npragma solidity 0.8.20;\n\ninterface ICurveOracle {\n    // How much WETH is 1E18 frxETH worth. Price is in ETH not USD\n    function price_oracle() external view returns (uint256 value);\n}\n"
      },
      "src/interfaces/Oracle/IFraxOracle.sol": {
        "content": "// SPDX-License-Identifier: Apache-2.0\npragma solidity 0.8.20;\n\ninterface IFraxOracle {\n    // How much frxETH is 1E18 sfrxETH worth. Price is in ETH, not USD\n    function pricePerShare() external view returns (uint256 value);\n}\n"
      },
      "src/interfaces/Oracle/IWstEth.sol": {
        "content": "// SPDX-License-Identifier: Apache-2.0\npragma solidity 0.8.20;\n\ninterface IWstEth {\n    // Get amount of stETH for a one wstETH\n    function stEthPerToken() external view returns (uint256);\n}\n"
      },
      "src/utils/VaultReentrancyLib.sol": {
        "content": "// SPDX-License-Identifier: GPL-3.0-or-later\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n// GNU General Public License for more details.\n\n// You should have received a copy of the GNU General Public License\n// along with this program.  If not, see <http://www.gnu.org/licenses/>.\n\npragma solidity >=0.7.0 <0.9.0;\n\nimport \"balancer-v2-monorepo/pkg/interfaces/contracts/solidity-utils/helpers/BalancerErrors.sol\";\nimport \"balancer-v2-monorepo/pkg/interfaces/contracts/vault/IVault.sol\";\n\nlibrary VaultReentrancyLib {\n    /**\n     * @dev Ensure we are not in a Vault context when this function is called, by attempting a no-op internal\n     * balance operation. If we are already in a Vault transaction (e.g., a swap, join, or exit), the Vault's\n     * reentrancy protection will cause this function to revert.\n     *\n     * The exact function call doesn't really matter: we're just trying to trigger the Vault reentrancy check\n     * (and not hurt anything in case it works). An empty operation array with no specific operation at all works\n     * for that purpose, and is also the least expensive in terms of gas and bytecode size.\n     *\n     * Call this at the top of any function that can cause a state change in a pool and is either public itself,\n     * or called by a public function *outside* a Vault operation (e.g., join, exit, or swap).\n     *\n     * If this is *not* called in functions that are vulnerable to the read-only reentrancy issue described\n     * here (https://forum.balancer.fi/t/reentrancy-vulnerability-scope-expanded/4345), those functions are unsafe,\n     * and subject to manipulation that may result in loss of funds.\n     */\n    function ensureNotInVaultContext(IVault vault) internal view {\n        // Perform the following operation to trigger the Vault's reentrancy guard:\n        //\n        // IVault.UserBalanceOp[] memory noop = new IVault.UserBalanceOp[](0);\n        // _vault.manageUserBalance(noop);\n        //\n        // However, use a static call so that it can be a view function (even though the function is non-view).\n        // This allows the library to be used more widely, as some functions that need to be protected might be\n        // view.\n        //\n        // This staticcall always reverts, but we need to make sure it doesn't fail due to a re-entrancy attack.\n        // Staticcalls consume all gas forwarded to them on a revert caused by storage modification.\n        // By default, almost the entire available gas is forwarded to the staticcall,\n        // causing the entire call to revert with an 'out of gas' error.\n        //\n        // We set the gas limit to 10k for the staticcall to\n        // avoid wasting gas when it reverts due to storage modification.\n        // `manageUserBalance` is a non-reentrant function in the Vault, so calling it invokes `_enterNonReentrant`\n        // in the `ReentrancyGuard` contract, reproduced here:\n        //\n        //    function _enterNonReentrant() private {\n        //        // If the Vault is actually being reentered, it will revert in the first line, at the `_require` that\n        //        // checks the reentrancy flag, with \"BAL#400\" (corresponding to Errors.REENTRANCY) in the revertData.\n        //        // The full revertData will be: `abi.encodeWithSignature(\"Error(string)\", \"BAL#400\")`.\n        //        _require(_status != _ENTERED, Errors.REENTRANCY);\n        //\n        //        // If the Vault is not being reentered, the check above will pass: but it will *still* revert,\n        //        // because the next line attempts to modify storage during a staticcall. However, this type of\n        //        // failure results in empty revertData.\n        //        _status = _ENTERED;\n        //    }\n        //\n        // So based on this analysis, there are only two possible revertData values: empty, or abi.encoded BAL#400.\n        //\n        // It is of course much more bytecode and gas efficient to check for zero-length revertData than to compare it\n        // to the encoded REENTRANCY revertData.\n        //\n        // While it should be impossible for the call to fail in any other way (especially since it reverts before\n        // `manageUserBalance` even gets called), any other error would generate non-zero revertData, so checking for\n        // empty data guards against this case too.\n\n        (, bytes memory revertData) = address(vault).staticcall{gas: 10_000}(\n            abi.encodeWithSelector(vault.manageUserBalance.selector, 0)\n        );\n\n        _require(revertData.length == 0, Errors.REENTRANCY);\n    }\n}\n"
      },
      "lib/balancer-v2-monorepo/pkg/interfaces/contracts/vault/IVault.sol": {
        "content": "// SPDX-License-Identifier: GPL-3.0-or-later\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n// GNU General Public License for more details.\n\n// You should have received a copy of the GNU General Public License\n// along with this program.  If not, see <http://www.gnu.org/licenses/>.\n\npragma experimental ABIEncoderV2;\n\nimport \"../solidity-utils/openzeppelin/IERC20.sol\";\nimport \"../solidity-utils/helpers/IAuthentication.sol\";\nimport \"../solidity-utils/helpers/ISignaturesValidator.sol\";\nimport \"../solidity-utils/helpers/ITemporarilyPausable.sol\";\nimport \"../solidity-utils/misc/IWETH.sol\";\n\nimport \"./IAsset.sol\";\nimport \"./IAuthorizer.sol\";\nimport \"./IFlashLoanRecipient.sol\";\nimport \"./IProtocolFeesCollector.sol\";\n\npragma solidity >=0.7.0 <0.9.0;\n\n/**\n * @dev Full external interface for the Vault core contract - no external or public methods exist in the contract that\n * don't override one of these declarations.\n */\ninterface IVault is ISignaturesValidator, ITemporarilyPausable, IAuthentication {\n    // Generalities about the Vault:\n    //\n    // - Whenever documentation refers to 'tokens', it strictly refers to ERC20-compliant token contracts. Tokens are\n    // transferred out of the Vault by calling the `IERC20.transfer` function, and transferred in by calling\n    // `IERC20.transferFrom`. In these cases, the sender must have previously allowed the Vault to use their tokens by\n    // calling `IERC20.approve`. The only deviation from the ERC20 standard that is supported is functions not returning\n    // a boolean value: in these scenarios, a non-reverting call is assumed to be successful.\n    //\n    // - All non-view functions in the Vault are non-reentrant: calling them while another one is mid-execution (e.g.\n    // while execution control is transferred to a token contract during a swap) will result in a revert. View\n    // functions can be called in a re-reentrant way, but doing so might cause them to return inconsistent results.\n    // Contracts calling view functions in the Vault must make sure the Vault has not already been entered.\n    //\n    // - View functions revert if referring to either unregistered Pools, or unregistered tokens for registered Pools.\n\n    // Authorizer\n    //\n    // Some system actions are permissioned, like setting and collecting protocol fees. This permissioning system exists\n    // outside of the Vault in the Authorizer contract: the Vault simply calls the Authorizer to check if the caller\n    // can perform a given action.\n\n    /**\n     * @dev Returns the Vault's Authorizer.\n     */\n    function getAuthorizer() external view returns (IAuthorizer);\n\n    /**\n     * @dev Sets a new Authorizer for the Vault. The caller must be allowed by the current Authorizer to do this.\n     *\n     * Emits an `AuthorizerChanged` event.\n     */\n    function setAuthorizer(IAuthorizer newAuthorizer) external;\n\n    /**\n     * @dev Emitted when a new authorizer is set by `setAuthorizer`.\n     */\n    event AuthorizerChanged(IAuthorizer indexed newAuthorizer);\n\n    // Relayers\n    //\n    // Additionally, it is possible for an account to perform certain actions on behalf of another one, using their\n    // Vault ERC20 allowance and Internal Balance. These accounts are said to be 'relayers' for these Vault functions,\n    // and are expected to be smart contracts with sound authentication mechanisms. For an account to be able to wield\n    // this power, two things must occur:\n    //  - The Authorizer must grant the account the permission to be a relayer for the relevant Vault function. This\n    //    means that Balancer governance must approve each individual contract to act as a relayer for the intended\n    //    functions.\n    //  - Each user must approve the relayer to act on their behalf.\n    // This double protection means users cannot be tricked into approving malicious relayers (because they will not\n    // have been allowed by the Authorizer via governance), nor can malicious relayers approved by a compromised\n    // Authorizer or governance drain user funds, since they would also need to be approved by each individual user.\n\n    /**\n     * @dev Returns true if `user` has approved `relayer` to act as a relayer for them.\n     */\n    function hasApprovedRelayer(address user, address relayer) external view returns (bool);\n\n    /**\n     * @dev Allows `relayer` to act as a relayer for `sender` if `approved` is true, and disallows it otherwise.\n     *\n     * Emits a `RelayerApprovalChanged` event.\n     */\n    function setRelayerApproval(\n        address sender,\n        address relayer,\n        bool approved\n    ) external;\n\n    /**\n     * @dev Emitted every time a relayer is approved or disapproved by `setRelayerApproval`.\n     */\n    event RelayerApprovalChanged(address indexed relayer, address indexed sender, bool approved);\n\n    // Internal Balance\n    //\n    // Users can deposit tokens into the Vault, where they are allocated to their Internal Balance, and later\n    // transferred or withdrawn. It can also be used as a source of tokens when joining Pools, as a destination\n    // when exiting them, and as either when performing swaps. This usage of Internal Balance results in greatly reduced\n    // gas costs when compared to relying on plain ERC20 transfers, leading to large savings for frequent users.\n    //\n    // Internal Balance management features batching, which means a single contract call can be used to perform multiple\n    // operations of different kinds, with different senders and recipients, at once.\n\n    /**\n     * @dev Returns `user`'s Internal Balance for a set of tokens.\n     */\n    function getInternalBalance(address user, IERC20[] memory tokens) external view returns (uint256[] memory);\n\n    /**\n     * @dev Performs a set of user balance operations, which involve Internal Balance (deposit, withdraw or transfer)\n     * and plain ERC20 transfers using the Vault's allowance. This last feature is particularly useful for relayers, as\n     * it lets integrators reuse a user's Vault allowance.\n     *\n     * For each operation, if the caller is not `sender`, it must be an authorized relayer for them.\n     */\n    function manageUserBalance(UserBalanceOp[] memory ops) external payable;\n\n    /**\n     * @dev Data for `manageUserBalance` operations, which include the possibility for ETH to be sent and received\n     without manual WETH wrapping or unwrapping.\n     */\n    struct UserBalanceOp {\n        UserBalanceOpKind kind;\n        IAsset asset;\n        uint256 amount;\n        address sender;\n        address payable recipient;\n    }\n\n    // There are four possible operations in `manageUserBalance`:\n    //\n    // - DEPOSIT_INTERNAL\n    // Increases the Internal Balance of the `recipient` account by transferring tokens from the corresponding\n    // `sender`. The sender must have allowed the Vault to use their tokens via `IERC20.approve()`.\n    //\n    // ETH can be used by passing the ETH sentinel value as the asset and forwarding ETH in the call: it will be wrapped\n    // and deposited as WETH. Any ETH amount remaining will be sent back to the caller (not the sender, which is\n    // relevant for relayers).\n    //\n    // Emits an `InternalBalanceChanged` event.\n    //\n    //\n    // - WITHDRAW_INTERNAL\n    // Decreases the Internal Balance of the `sender` account by transferring tokens to the `recipient`.\n    //\n    // ETH can be used by passing the ETH sentinel value as the asset. This will deduct WETH instead, unwrap it and send\n    // it to the recipient as ETH.\n    //\n    // Emits an `InternalBalanceChanged` event.\n    //\n    //\n    // - TRANSFER_INTERNAL\n    // Transfers tokens from the Internal Balance of the `sender` account to the Internal Balance of `recipient`.\n    //\n    // Reverts if the ETH sentinel value is passed.\n    //\n    // Emits an `InternalBalanceChanged` event.\n    //\n    //\n    // - TRANSFER_EXTERNAL\n    // Transfers tokens from `sender` to `recipient`, using the Vault's ERC20 allowance. This is typically used by\n    // relayers, as it lets them reuse a user's Vault allowance.\n    //\n    // Reverts if the ETH sentinel value is passed.\n    //\n    // Emits an `ExternalBalanceTransfer` event.\n\n    enum UserBalanceOpKind { DEPOSIT_INTERNAL, WITHDRAW_INTERNAL, TRANSFER_INTERNAL, TRANSFER_EXTERNAL }\n\n    /**\n     * @dev Emitted when a user's Internal Balance changes, either from calls to `manageUserBalance`, or through\n     * interacting with Pools using Internal Balance.\n     *\n     * Because Internal Balance works exclusively with ERC20 tokens, ETH deposits and withdrawals will use the WETH\n     * address.\n     */\n    event InternalBalanceChanged(address indexed user, IERC20 indexed token, int256 delta);\n\n    /**\n     * @dev Emitted when a user's Vault ERC20 allowance is used by the Vault to transfer tokens to an external account.\n     */\n    event ExternalBalanceTransfer(IERC20 indexed token, address indexed sender, address recipient, uint256 amount);\n\n    // Pools\n    //\n    // There are three specialization settings for Pools, which allow for cheaper swaps at the cost of reduced\n    // functionality:\n    //\n    //  - General: no specialization, suited for all Pools. IGeneralPool is used for swap request callbacks, passing the\n    // balance of all tokens in the Pool. These Pools have the largest swap costs (because of the extra storage reads),\n    // which increase with the number of registered tokens.\n    //\n    //  - Minimal Swap Info: IMinimalSwapInfoPool is used instead of IGeneralPool, which saves gas by only passing the\n    // balance of the two tokens involved in the swap. This is suitable for some pricing algorithms, like the weighted\n    // constant product one popularized by Balancer V1. Swap costs are smaller compared to general Pools, and are\n    // independent of the number of registered tokens.\n    //\n    //  - Two Token: only allows two tokens to be registered. This achieves the lowest possible swap gas cost. Like\n    // minimal swap info Pools, these are called via IMinimalSwapInfoPool.\n\n    enum PoolSpecialization { GENERAL, MINIMAL_SWAP_INFO, TWO_TOKEN }\n\n    /**\n     * @dev Registers the caller account as a Pool with a given specialization setting. Returns the Pool's ID, which\n     * is used in all Pool-related functions. Pools cannot be deregistered, nor can the Pool's specialization be\n     * changed.\n     *\n     * The caller is expected to be a smart contract that implements either `IGeneralPool` or `IMinimalSwapInfoPool`,\n     * depending on the chosen specialization setting. This contract is known as the Pool's contract.\n     *\n     * Note that the same contract may register itself as multiple Pools with unique Pool IDs, or in other words,\n     * multiple Pools may share the same contract.\n     *\n     * Emits a `PoolRegistered` event.\n     */\n    function registerPool(PoolSpecialization specialization) external returns (bytes32);\n\n    /**\n     * @dev Emitted when a Pool is registered by calling `registerPool`.\n     */\n    event PoolRegistered(bytes32 indexed poolId, address indexed poolAddress, PoolSpecialization specialization);\n\n    /**\n     * @dev Returns a Pool's contract address and specialization setting.\n     */\n    function getPool(bytes32 poolId) external view returns (address, PoolSpecialization);\n\n    /**\n     * @dev Registers `tokens` for the `poolId` Pool. Must be called by the Pool's contract.\n     *\n     * Pools can only interact with tokens they have registered. Users join a Pool by transferring registered tokens,\n     * exit by receiving registered tokens, and can only swap registered tokens.\n     *\n     * Each token can only be registered once. For Pools with the Two Token specialization, `tokens` must have a length\n     * of two, that is, both tokens must be registered in the same `registerTokens` call, and they must be sorted in\n     * ascending order.\n     *\n     * The `tokens` and `assetManagers` arrays must have the same length, and each entry in these indicates the Asset\n     * Manager for the corresponding token. Asset Managers can manage a Pool's tokens via `managePoolBalance`,\n     * depositing and withdrawing them directly, and can even set their balance to arbitrary amounts. They are therefore\n     * expected to be highly secured smart contracts with sound design principles, and the decision to register an\n     * Asset Manager should not be made lightly.\n     *\n     * Pools can choose not to assign an Asset Manager to a given token by passing in the zero address. Once an Asset\n     * Manager is set, it cannot be changed except by deregistering the associated token and registering again with a\n     * different Asset Manager.\n     *\n     * Emits a `TokensRegistered` event.\n     */\n    function registerTokens(\n        bytes32 poolId,\n        IERC20[] memory tokens,\n        address[] memory assetManagers\n    ) external;\n\n    /**\n     * @dev Emitted when a Pool registers tokens by calling `registerTokens`.\n     */\n    event TokensRegistered(bytes32 indexed poolId, IERC20[] tokens, address[] assetManagers);\n\n    /**\n     * @dev Deregisters `tokens` for the `poolId` Pool. Must be called by the Pool's contract.\n     *\n     * Only registered tokens (via `registerTokens`) can be deregistered. Additionally, they must have zero total\n     * balance. For Pools with the Two Token specialization, `tokens` must have a length of two, that is, both tokens\n     * must be deregistered in the same `deregisterTokens` call.\n     *\n     * A deregistered token can be re-registered later on, possibly with a different Asset Manager.\n     *\n     * Emits a `TokensDeregistered` event.\n     */\n    function deregisterTokens(bytes32 poolId, IERC20[] memory tokens) external;\n\n    /**\n     * @dev Emitted when a Pool deregisters tokens by calling `deregisterTokens`.\n     */\n    event TokensDeregistered(bytes32 indexed poolId, IERC20[] tokens);\n\n    /**\n     * @dev Returns detailed information for a Pool's registered token.\n     *\n     * `cash` is the number of tokens the Vault currently holds for the Pool. `managed` is the number of tokens\n     * withdrawn and held outside the Vault by the Pool's token Asset Manager. The Pool's total balance for `token`\n     * equals the sum of `cash` and `managed`.\n     *\n     * Internally, `cash` and `managed` are stored using 112 bits. No action can ever cause a Pool's token `cash`,\n     * `managed` or `total` balance to be greater than 2^112 - 1.\n     *\n     * `lastChangeBlock` is the number of the block in which `token`'s total balance was last modified (via either a\n     * join, exit, swap, or Asset Manager update). This value is useful to avoid so-called 'sandwich attacks', for\n     * example when developing price oracles. A change of zero (e.g. caused by a swap with amount zero) is considered a\n     * change for this purpose, and will update `lastChangeBlock`.\n     *\n     * `assetManager` is the Pool's token Asset Manager.\n     */\n    function getPoolTokenInfo(bytes32 poolId, IERC20 token)\n        external\n        view\n        returns (\n            uint256 cash,\n            uint256 managed,\n            uint256 lastChangeBlock,\n            address assetManager\n        );\n\n    /**\n     * @dev Returns a Pool's registered tokens, the total balance for each, and the latest block when *any* of\n     * the tokens' `balances` changed.\n     *\n     * The order of the `tokens` array is the same order that will be used in `joinPool`, `exitPool`, as well as in all\n     * Pool hooks (where applicable). Calls to `registerTokens` and `deregisterTokens` may change this order.\n     *\n     * If a Pool only registers tokens once, and these are sorted in ascending order, they will be stored in the same\n     * order as passed to `registerTokens`.\n     *\n     * Total balances include both tokens held by the Vault and those withdrawn by the Pool's Asset Managers. These are\n     * the amounts used by joins, exits and swaps. For a detailed breakdown of token balances, use `getPoolTokenInfo`\n     * instead.\n     */\n    function getPoolTokens(bytes32 poolId)\n        external\n        view\n        returns (\n            IERC20[] memory tokens,\n            uint256[] memory balances,\n            uint256 lastChangeBlock\n        );\n\n    /**\n     * @dev Called by users to join a Pool, which transfers tokens from `sender` into the Pool's balance. This will\n     * trigger custom Pool behavior, which will typically grant something in return to `recipient` - often tokenized\n     * Pool shares.\n     *\n     * If the caller is not `sender`, it must be an authorized relayer for them.\n     *\n     * The `assets` and `maxAmountsIn` arrays must have the same length, and each entry indicates the maximum amount\n     * to send for each asset. The amounts to send are decided by the Pool and not the Vault: it just enforces\n     * these maximums.\n     *\n     * If joining a Pool that holds WETH, it is possible to send ETH directly: the Vault will do the wrapping. To enable\n     * this mechanism, the IAsset sentinel value (the zero address) must be passed in the `assets` array instead of the\n     * WETH address. Note that it is not possible to combine ETH and WETH in the same join. Any excess ETH will be sent\n     * back to the caller (not the sender, which is important for relayers).\n     *\n     * `assets` must have the same length and order as the array returned by `getPoolTokens`. This prevents issues when\n     * interacting with Pools that register and deregister tokens frequently. If sending ETH however, the array must be\n     * sorted *before* replacing the WETH address with the ETH sentinel value (the zero address), which means the final\n     * `assets` array might not be sorted. Pools with no registered tokens cannot be joined.\n     *\n     * If `fromInternalBalance` is true, the caller's Internal Balance will be preferred: ERC20 transfers will only\n     * be made for the difference between the requested amount and Internal Balance (if any). Note that ETH cannot be\n     * withdrawn from Internal Balance: attempting to do so will trigger a revert.\n     *\n     * This causes the Vault to call the `IBasePool.onJoinPool` hook on the Pool's contract, where Pools implement\n     * their own custom logic. This typically requires additional information from the user (such as the expected number\n     * of Pool shares). This can be encoded in the `userData` argument, which is ignored by the Vault and passed\n     * directly to the Pool's contract, as is `recipient`.\n     *\n     * Emits a `PoolBalanceChanged` event.\n     */\n    function joinPool(\n        bytes32 poolId,\n        address sender,\n        address recipient,\n        JoinPoolRequest memory request\n    ) external payable;\n\n    struct JoinPoolRequest {\n        IAsset[] assets;\n        uint256[] maxAmountsIn;\n        bytes userData;\n        bool fromInternalBalance;\n    }\n\n    /**\n     * @dev Called by users to exit a Pool, which transfers tokens from the Pool's balance to `recipient`. This will\n     * trigger custom Pool behavior, which will typically ask for something in return from `sender` - often tokenized\n     * Pool shares. The amount of tokens that can be withdrawn is limited by the Pool's `cash` balance (see\n     * `getPoolTokenInfo`).\n     *\n     * If the caller is not `sender`, it must be an authorized relayer for them.\n     *\n     * The `tokens` and `minAmountsOut` arrays must have the same length, and each entry in these indicates the minimum\n     * token amount to receive for each token contract. The amounts to send are decided by the Pool and not the Vault:\n     * it just enforces these minimums.\n     *\n     * If exiting a Pool that holds WETH, it is possible to receive ETH directly: the Vault will do the unwrapping. To\n     * enable this mechanism, the IAsset sentinel value (the zero address) must be passed in the `assets` array instead\n     * of the WETH address. Note that it is not possible to combine ETH and WETH in the same exit.\n     *\n     * `assets` must have the same length and order as the array returned by `getPoolTokens`. This prevents issues when\n     * interacting with Pools that register and deregister tokens frequently. If receiving ETH however, the array must\n     * be sorted *before* replacing the WETH address with the ETH sentinel value (the zero address), which means the\n     * final `assets` array might not be sorted. Pools with no registered tokens cannot be exited.\n     *\n     * If `toInternalBalance` is true, the tokens will be deposited to `recipient`'s Internal Balance. Otherwise,\n     * an ERC20 transfer will be performed. Note that ETH cannot be deposited to Internal Balance: attempting to\n     * do so will trigger a revert.\n     *\n     * `minAmountsOut` is the minimum amount of tokens the user expects to get out of the Pool, for each token in the\n     * `tokens` array. This array must match the Pool's registered tokens.\n     *\n     * This causes the Vault to call the `IBasePool.onExitPool` hook on the Pool's contract, where Pools implement\n     * their own custom logic. This typically requires additional information from the user (such as the expected number\n     * of Pool shares to return). This can be encoded in the `userData` argument, which is ignored by the Vault and\n     * passed directly to the Pool's contract.\n     *\n     * Emits a `PoolBalanceChanged` event.\n     */\n    function exitPool(\n        bytes32 poolId,\n        address sender,\n        address payable recipient,\n        ExitPoolRequest memory request\n    ) external;\n\n    struct ExitPoolRequest {\n        IAsset[] assets;\n        uint256[] minAmountsOut;\n        bytes userData;\n        bool toInternalBalance;\n    }\n\n    /**\n     * @dev Emitted when a user joins or exits a Pool by calling `joinPool` or `exitPool`, respectively.\n     */\n    event PoolBalanceChanged(\n        bytes32 indexed poolId,\n        address indexed liquidityProvider,\n        IERC20[] tokens,\n        int256[] deltas,\n        uint256[] protocolFeeAmounts\n    );\n\n    enum PoolBalanceChangeKind { JOIN, EXIT }\n\n    // Swaps\n    //\n    // Users can swap tokens with Pools by calling the `swap` and `batchSwap` functions. To do this,\n    // they need not trust Pool contracts in any way: all security checks are made by the Vault. They must however be\n    // aware of the Pools' pricing algorithms in order to estimate the prices Pools will quote.\n    //\n    // The `swap` function executes a single swap, while `batchSwap` can perform multiple swaps in sequence.\n    // In each individual swap, tokens of one kind are sent from the sender to the Pool (this is the 'token in'),\n    // and tokens of another kind are sent from the Pool to the recipient in exchange (this is the 'token out').\n    // More complex swaps, such as one token in to multiple tokens out can be achieved by batching together\n    // individual swaps.\n    //\n    // There are two swap kinds:\n    //  - 'given in' swaps, where the amount of tokens in (sent to the Pool) is known, and the Pool determines (via the\n    // `onSwap` hook) the amount of tokens out (to send to the recipient).\n    //  - 'given out' swaps, where the amount of tokens out (received from the Pool) is known, and the Pool determines\n    // (via the `onSwap` hook) the amount of tokens in (to receive from the sender).\n    //\n    // Additionally, it is possible to chain swaps using a placeholder input amount, which the Vault replaces with\n    // the calculated output of the previous swap. If the previous swap was 'given in', this will be the calculated\n    // tokenOut amount. If the previous swap was 'given out', it will use the calculated tokenIn amount. These extended\n    // swaps are known as 'multihop' swaps, since they 'hop' through a number of intermediate tokens before arriving at\n    // the final intended token.\n    //\n    // In all cases, tokens are only transferred in and out of the Vault (or withdrawn from and deposited into Internal\n    // Balance) after all individual swaps have been completed, and the net token balance change computed. This makes\n    // certain swap patterns, such as multihops, or swaps that interact with the same token pair in multiple Pools, cost\n    // much less gas than they would otherwise.\n    //\n    // It also means that under certain conditions it is possible to perform arbitrage by swapping with multiple\n    // Pools in a way that results in net token movement out of the Vault (profit), with no tokens being sent in (only\n    // updating the Pool's internal accounting).\n    //\n    // To protect users from front-running or the market changing rapidly, they supply a list of 'limits' for each token\n    // involved in the swap, where either the maximum number of tokens to send (by passing a positive value) or the\n    // minimum amount of tokens to receive (by passing a negative value) is specified.\n    //\n    // Additionally, a 'deadline' timestamp can also be provided, forcing the swap to fail if it occurs after\n    // this point in time (e.g. if the transaction failed to be included in a block promptly).\n    //\n    // If interacting with Pools that hold WETH, it is possible to both send and receive ETH directly: the Vault will do\n    // the wrapping and unwrapping. To enable this mechanism, the IAsset sentinel value (the zero address) must be\n    // passed in the `assets` array instead of the WETH address. Note that it is possible to combine ETH and WETH in the\n    // same swap. Any excess ETH will be sent back to the caller (not the sender, which is relevant for relayers).\n    //\n    // Finally, Internal Balance can be used when either sending or receiving tokens.\n\n    enum SwapKind { GIVEN_IN, GIVEN_OUT }\n\n    /**\n     * @dev Performs a swap with a single Pool.\n     *\n     * If the swap is 'given in' (the number of tokens to send to the Pool is known), it returns the amount of tokens\n     * taken from the Pool, which must be greater than or equal to `limit`.\n     *\n     * If the swap is 'given out' (the number of tokens to take from the Pool is known), it returns the amount of tokens\n     * sent to the Pool, which must be less than or equal to `limit`.\n     *\n     * Internal Balance usage and the recipient are determined by the `funds` struct.\n     *\n     * Emits a `Swap` event.\n     */\n    function swap(\n        SingleSwap memory singleSwap,\n        FundManagement memory funds,\n        uint256 limit,\n        uint256 deadline\n    ) external payable returns (uint256);\n\n    /**\n     * @dev Data for a single swap executed by `swap`. `amount` is either `amountIn` or `amountOut` depending on\n     * the `kind` value.\n     *\n     * `assetIn` and `assetOut` are either token addresses, or the IAsset sentinel value for ETH (the zero address).\n     * Note that Pools never interact with ETH directly: it will be wrapped to or unwrapped from WETH by the Vault.\n     *\n     * The `userData` field is ignored by the Vault, but forwarded to the Pool in the `onSwap` hook, and may be\n     * used to extend swap behavior.\n     */\n    struct SingleSwap {\n        bytes32 poolId;\n        SwapKind kind;\n        IAsset assetIn;\n        IAsset assetOut;\n        uint256 amount;\n        bytes userData;\n    }\n\n    /**\n     * @dev Performs a series of swaps with one or multiple Pools. In each individual swap, the caller determines either\n     * the amount of tokens sent to or received from the Pool, depending on the `kind` value.\n     *\n     * Returns an array with the net Vault asset balance deltas. Positive amounts represent tokens (or ETH) sent to the\n     * Vault, and negative amounts represent tokens (or ETH) sent by the Vault. Each delta corresponds to the asset at\n     * the same index in the `assets` array.\n     *\n     * Swaps are executed sequentially, in the order specified by the `swaps` array. Each array element describes a\n     * Pool, the token to be sent to this Pool, the token to receive from it, and an amount that is either `amountIn` or\n     * `amountOut` depending on the swap kind.\n     *\n     * Multihop swaps can be executed by passing an `amount` value of zero for a swap. This will cause the amount in/out\n     * of the previous swap to be used as the amount in for the current one. In a 'given in' swap, 'tokenIn' must equal\n     * the previous swap's `tokenOut`. For a 'given out' swap, `tokenOut` must equal the previous swap's `tokenIn`.\n     *\n     * The `assets` array contains the addresses of all assets involved in the swaps. These are either token addresses,\n     * or the IAsset sentinel value for ETH (the zero address). Each entry in the `swaps` array specifies tokens in and\n     * out by referencing an index in `assets`. Note that Pools never interact with ETH directly: it will be wrapped to\n     * or unwrapped from WETH by the Vault.\n     *\n     * Internal Balance usage, sender, and recipient are determined by the `funds` struct. The `limits` array specifies\n     * the minimum or maximum amount of each token the vault is allowed to transfer.\n     *\n     * `batchSwap` can be used to make a single swap, like `swap` does, but doing so requires more gas than the\n     * equivalent `swap` call.\n     *\n     * Emits `Swap` events.\n     */\n    function batchSwap(\n        SwapKind kind,\n        BatchSwapStep[] memory swaps,\n        IAsset[] memory assets,\n        FundManagement memory funds,\n        int256[] memory limits,\n        uint256 deadline\n    ) external payable returns (int256[] memory);\n\n    /**\n     * @dev Data for each individual swap executed by `batchSwap`. The asset in and out fields are indexes into the\n     * `assets` array passed to that function, and ETH assets are converted to WETH.\n     *\n     * If `amount` is zero, the multihop mechanism is used to determine the actual amount based on the amount in/out\n     * from the previous swap, depending on the swap kind.\n     *\n     * The `userData` field is ignored by the Vault, but forwarded to the Pool in the `onSwap` hook, and may be\n     * used to extend swap behavior.\n     */\n    struct BatchSwapStep {\n        bytes32 poolId;\n        uint256 assetInIndex;\n        uint256 assetOutIndex;\n        uint256 amount;\n        bytes userData;\n    }\n\n    /**\n     * @dev Emitted for each individual swap performed by `swap` or `batchSwap`.\n     */\n    event Swap(\n        bytes32 indexed poolId,\n        IERC20 indexed tokenIn,\n        IERC20 indexed tokenOut,\n        uint256 amountIn,\n        uint256 amountOut\n    );\n\n    /**\n     * @dev All tokens in a swap are either sent from the `sender` account to the Vault, or from the Vault to the\n     * `recipient` account.\n     *\n     * If the caller is not `sender`, it must be an authorized relayer for them.\n     *\n     * If `fromInternalBalance` is true, the `sender`'s Internal Balance will be preferred, performing an ERC20\n     * transfer for the difference between the requested amount and the User's Internal Balance (if any). The `sender`\n     * must have allowed the Vault to use their tokens via `IERC20.approve()`. This matches the behavior of\n     * `joinPool`.\n     *\n     * If `toInternalBalance` is true, tokens will be deposited to `recipient`'s internal balance instead of\n     * transferred. This matches the behavior of `exitPool`.\n     *\n     * Note that ETH cannot be deposited to or withdrawn from Internal Balance: attempting to do so will trigger a\n     * revert.\n     */\n    struct FundManagement {\n        address sender;\n        bool fromInternalBalance;\n        address payable recipient;\n        bool toInternalBalance;\n    }\n\n    /**\n     * @dev Simulates a call to `batchSwap`, returning an array of Vault asset deltas. Calls to `swap` cannot be\n     * simulated directly, but an equivalent `batchSwap` call can and will yield the exact same result.\n     *\n     * Each element in the array corresponds to the asset at the same index, and indicates the number of tokens (or ETH)\n     * the Vault would take from the sender (if positive) or send to the recipient (if negative). The arguments it\n     * receives are the same that an equivalent `batchSwap` call would receive.\n     *\n     * Unlike `batchSwap`, this function performs no checks on the sender or recipient field in the `funds` struct.\n     * This makes it suitable to be called by off-chain applications via eth_call without needing to hold tokens,\n     * approve them for the Vault, or even know a user's address.\n     *\n     * Note that this function is not 'view' (due to implementation details): the client code must explicitly execute\n     * eth_call instead of eth_sendTransaction.\n     */\n    function queryBatchSwap(\n        SwapKind kind,\n        BatchSwapStep[] memory swaps,\n        IAsset[] memory assets,\n        FundManagement memory funds\n    ) external returns (int256[] memory assetDeltas);\n\n    // Flash Loans\n\n    /**\n     * @dev Performs a 'flash loan', sending tokens to `recipient`, executing the `receiveFlashLoan` hook on it,\n     * and then reverting unless the tokens plus a proportional protocol fee have been returned.\n     *\n     * The `tokens` and `amounts` arrays must have the same length, and each entry in these indicates the loan amount\n     * for each token contract. `tokens` must be sorted in ascending order.\n     *\n     * The 'userData' field is ignored by the Vault, and forwarded as-is to `recipient` as part of the\n     * `receiveFlashLoan` call.\n     *\n     * Emits `FlashLoan` events.\n     */\n    function flashLoan(\n        IFlashLoanRecipient recipient,\n        IERC20[] memory tokens,\n        uint256[] memory amounts,\n        bytes memory userData\n    ) external;\n\n    /**\n     * @dev Emitted for each individual flash loan performed by `flashLoan`.\n     */\n    event FlashLoan(IFlashLoanRecipient indexed recipient, IERC20 indexed token, uint256 amount, uint256 feeAmount);\n\n    // Asset Management\n    //\n    // Each token registered for a Pool can be assigned an Asset Manager, which is able to freely withdraw the Pool's\n    // tokens from the Vault, deposit them, or assign arbitrary values to its `managed` balance (see\n    // `getPoolTokenInfo`). This makes them extremely powerful and dangerous. Even if an Asset Manager only directly\n    // controls one of the tokens in a Pool, a malicious manager could set that token's balance to manipulate the\n    // prices of the other tokens, and then drain the Pool with swaps. The risk of using Asset Managers is therefore\n    // not constrained to the tokens they are managing, but extends to the entire Pool's holdings.\n    //\n    // However, a properly designed Asset Manager smart contract can be safely used for the Pool's benefit,\n    // for example by lending unused tokens out for interest, or using them to participate in voting protocols.\n    //\n    // This concept is unrelated to the IAsset interface.\n\n    /**\n     * @dev Performs a set of Pool balance operations, which may be either withdrawals, deposits or updates.\n     *\n     * Pool Balance management features batching, which means a single contract call can be used to perform multiple\n     * operations of different kinds, with different Pools and tokens, at once.\n     *\n     * For each operation, the caller must be registered as the Asset Manager for `token` in `poolId`.\n     */\n    function managePoolBalance(PoolBalanceOp[] memory ops) external;\n\n    struct PoolBalanceOp {\n        PoolBalanceOpKind kind;\n        bytes32 poolId;\n        IERC20 token;\n        uint256 amount;\n    }\n\n    /**\n     * Withdrawals decrease the Pool's cash, but increase its managed balance, leaving the total balance unchanged.\n     *\n     * Deposits increase the Pool's cash, but decrease its managed balance, leaving the total balance unchanged.\n     *\n     * Updates don't affect the Pool's cash balance, but because the managed balance changes, it does alter the total.\n     * The external amount can be either increased or decreased by this call (i.e., reporting a gain or a loss).\n     */\n    enum PoolBalanceOpKind { WITHDRAW, DEPOSIT, UPDATE }\n\n    /**\n     * @dev Emitted when a Pool's token Asset Manager alters its balance via `managePoolBalance`.\n     */\n    event PoolBalanceManaged(\n        bytes32 indexed poolId,\n        address indexed assetManager,\n        IERC20 indexed token,\n        int256 cashDelta,\n        int256 managedDelta\n    );\n\n    // Protocol Fees\n    //\n    // Some operations cause the Vault to collect tokens in the form of protocol fees, which can then be withdrawn by\n    // permissioned accounts.\n    //\n    // There are two kinds of protocol fees:\n    //\n    //  - flash loan fees: charged on all flash loans, as a percentage of the amounts lent.\n    //\n    //  - swap fees: a percentage of the fees charged by Pools when performing swaps. For a number of reasons, including\n    // swap gas costs and interface simplicity, protocol swap fees are not charged on each individual swap. Rather,\n    // Pools are expected to keep track of how much they have charged in swap fees, and pay any outstanding debts to the\n    // Vault when they are joined or exited. This prevents users from joining a Pool with unpaid debt, as well as\n    // exiting a Pool in debt without first paying their share.\n\n    /**\n     * @dev Returns the current protocol fee module.\n     */\n    function getProtocolFeesCollector() external view returns (IProtocolFeesCollector);\n\n    /**\n     * @dev Safety mechanism to pause most Vault operations in the event of an emergency - typically detection of an\n     * error in some part of the system.\n     *\n     * The Vault can only be paused during an initial time period, after which pausing is forever disabled.\n     *\n     * While the contract is paused, the following features are disabled:\n     * - depositing and transferring internal balance\n     * - transferring external balance (using the Vault's allowance)\n     * - swaps\n     * - joining Pools\n     * - Asset Manager interactions\n     *\n     * Internal Balance can still be withdrawn, and Pools exited.\n     */\n    function setPaused(bool paused) external;\n\n    /**\n     * @dev Returns the Vault's WETH instance.\n     */\n    function WETH() external view returns (IWETH);\n    // solhint-disable-previous-line func-name-mixedcase\n}\n"
      },
      "src/utils/PRBMathSD59x18.sol": {
        "content": "// SPDX-License-Identifier: WTFPL\npragma solidity >=0.8.4;\n\nimport \"./PRBMath.sol\";\n\n/// @title PRBMathSD59x18\n/// @author Paul Razvan Berg\n/// @notice Smart contract library for advanced fixed-point math that works with int256 numbers considered to have 18\n/// trailing decimals. We call this number representation signed 59.18-decimal fixed-point, since the numbers can have\n/// a sign and there can be up to 59 digits in the integer part and up to 18 decimals in the fractional part. The numbers\n/// are bound by the minimum and the maximum values permitted by the Solidity type int256.\nlibrary PRBMathSD59x18 {\n    /// @dev log2(e) as a signed 59.18-decimal fixed-point number.\n    int256 internal constant LOG2_E = 1_442_695_040_888_963_407;\n\n    /// @dev Half the SCALE number.\n    int256 internal constant HALF_SCALE = 5e17;\n\n    /// @dev The maximum value a signed 59.18-decimal fixed-point number can have.\n    int256 internal constant MAX_SD59x18 =\n        57_896_044_618_658_097_711_785_492_504_343_953_926_634_992_332_820_282_019_728_792_003_956_564_819_967;\n\n    /// @dev The maximum whole value a signed 59.18-decimal fixed-point number can have.\n    int256 internal constant MAX_WHOLE_SD59x18 =\n        57_896_044_618_658_097_711_785_492_504_343_953_926_634_992_332_820_282_019_728_000_000_000_000_000_000;\n\n    /// @dev The minimum value a signed 59.18-decimal fixed-point number can have.\n    int256 internal constant MIN_SD59x18 = -57_896_044_618_658_097_711_785_492_504_343_953_926_634_992_332_820_282_019_728_792_003_956_564_819_968;\n\n    /// @dev The minimum whole value a signed 59.18-decimal fixed-point number can have.\n    int256 internal constant MIN_WHOLE_SD59x18 = -57_896_044_618_658_097_711_785_492_504_343_953_926_634_992_332_820_282_019_728_000_000_000_000_000_000;\n\n    /// @dev How many trailing decimals can be represented.\n    int256 internal constant SCALE = 1e18;\n\n    /// INTERNAL FUNCTIONS ///\n\n    /// @notice Calculate the absolute value of x.\n    ///\n    /// @dev Requirements:\n    /// - x must be greater than MIN_SD59x18.\n    ///\n    /// @param x The number to calculate the absolute value for.\n    /// @param result The absolute value of x.\n    function abs(int256 x) internal pure returns (int256 result) {\n        unchecked {\n            require(x > MIN_SD59x18);\n            result = x < 0 ? -x : x;\n        }\n    }\n\n    /// @notice Calculates arithmetic average of x and y, rounding down.\n    /// @param x The first operand as a signed 59.18-decimal fixed-point number.\n    /// @param y The second operand as a signed 59.18-decimal fixed-point number.\n    /// @return result The arithmetic average as a signed 59.18-decimal fixed-point number.\n    function avg(int256 x, int256 y) internal pure returns (int256 result) {\n        // The operations can never overflow.\n        unchecked {\n            // The last operand checks if both x and y are odd and if that is the case, we add 1 to the result. We need\n            // to do this because if both numbers are odd, the 0.5 remainder gets truncated twice.\n            result = (x >> 1) + (y >> 1) + (x & y & 1);\n        }\n    }\n\n    /// @notice Yields the least greatest signed 59.18 decimal fixed-point number greater than or equal to x.\n    ///\n    /// @dev Optimised for fractional value inputs, because for every whole value there are (1e18 - 1) fractional counterparts.\n    /// See https://en.wikipedia.org/wiki/Floor_and_ceiling_functions.\n    ///\n    /// Requirements:\n    /// - x must be less than or equal to MAX_WHOLE_SD59x18.\n    ///\n    /// @param x The signed 59.18-decimal fixed-point number to ceil.\n    /// @param result The least integer greater than or equal to x, as a signed 58.18-decimal fixed-point number.\n    function ceil(int256 x) internal pure returns (int256 result) {\n        require(x <= MAX_WHOLE_SD59x18);\n        unchecked {\n            int256 remainder = x % SCALE;\n            if (remainder == 0) {\n                result = x;\n            } else {\n                // Solidity uses C fmod style, which returns a modulus with the same sign as x.\n                result = x - remainder;\n                if (x > 0) {\n                    result += SCALE;\n                }\n            }\n        }\n    }\n\n    /// @notice Divides two signed 59.18-decimal fixed-point numbers, returning a new signed 59.18-decimal fixed-point number.\n    ///\n    /// @dev Variant of \"mulDiv\" that works with signed numbers. Works by computing the signs and the absolute values separately.\n    ///\n    /// Requirements:\n    /// - All from \"PRBMath.mulDiv\".\n    /// - None of the inputs can be type(int256).min.\n    /// - y cannot be zero.\n    /// - The result must fit within int256.\n    ///\n    /// Caveats:\n    /// - All from \"PRBMath.mulDiv\".\n    ///\n    /// @param x The numerator as a signed 59.18-decimal fixed-point number.\n    /// @param y The denominator as a signed 59.18-decimal fixed-point number.\n    /// @param result The quotient as a signed 59.18-decimal fixed-point number.\n    function div(int256 x, int256 y) internal pure returns (int256 result) {\n        require(x > type(int256).min);\n        require(y > type(int256).min);\n\n        // Get hold of the absolute values of x and y.\n        uint256 ax;\n        uint256 ay;\n        unchecked {\n            ax = x < 0 ? uint256(-x) : uint256(x);\n            ay = y < 0 ? uint256(-y) : uint256(y);\n        }\n\n        // Compute the absolute value of (x*SCALE)÷y. The result must fit within int256.\n        uint256 rUnsigned = PRBMath.mulDiv(ax, uint256(SCALE), ay);\n        require(rUnsigned <= uint256(type(int256).max));\n\n        // Get the signs of x and y.\n        uint256 sx;\n        uint256 sy;\n        assembly {\n            sx := sgt(x, sub(0, 1))\n            sy := sgt(y, sub(0, 1))\n        }\n\n        // XOR over sx and sy. This is basically checking whether the inputs have the same sign. If yes, the result\n        // should be positive. Otherwise, it should be negative.\n        result = sx ^ sy == 1 ? -int256(rUnsigned) : int256(rUnsigned);\n    }\n\n    /// @notice Returns Euler's number as a signed 59.18-decimal fixed-point number.\n    /// @dev See https://en.wikipedia.org/wiki/E_(mathematical_constant).\n    function e() internal pure returns (int256 result) {\n        result = 2_718_281_828_459_045_235;\n    }\n\n    /// @notice Calculates the natural exponent of x.\n    ///\n    /// @dev Based on the insight that e^x = 2^(x * log2(e)).\n    ///\n    /// Requirements:\n    /// - All from \"log2\".\n    /// - x must be less than 133.084258667509499441.\n    ///\n    /// Caveats:\n    /// - All from \"exp2\".\n    /// - For any x less than -41.446531673892822322, the result is zero.\n    ///\n    /// @param x The exponent as a signed 59.18-decimal fixed-point number.\n    /// @return result The result as a signed 59.18-decimal fixed-point number.\n    function exp(int256 x) internal pure returns (int256 result) {\n        // Without this check, the value passed to \"exp2\" would be less than -59.794705707972522261.\n        if (x < -41_446_531_673_892_822_322) {\n            return 0;\n        }\n\n        // Without this check, the value passed to \"exp2\" would be greater than 192.\n        require(x < 133_084_258_667_509_499_441);\n\n        // Do the fixed-point multiplication inline to save gas.\n        unchecked {\n            int256 doubleScaleProduct = x * LOG2_E;\n            result = exp2((doubleScaleProduct + HALF_SCALE) / SCALE);\n        }\n    }\n\n    /// @notice Calculates the binary exponent of x using the binary fraction method.\n    ///\n    /// @dev See https://ethereum.stackexchange.com/q/79903/24693.\n    ///\n    /// Requirements:\n    /// - x must be 192 or less.\n    /// - The result must fit within MAX_SD59x18.\n    ///\n    /// Caveats:\n    /// - For any x less than -59.794705707972522261, the result is zero.\n    ///\n    /// @param x The exponent as a signed 59.18-decimal fixed-point number.\n    /// @return result The result as a signed 59.18-decimal fixed-point number.\n    function exp2(int256 x) internal pure returns (int256 result) {\n        // This works because 2^(-x) = 1/2^x.\n        if (x < 0) {\n            // 2^59.794705707972522262 is the maximum number whose inverse does not truncate down to zero.\n            if (x < -59_794_705_707_972_522_261) {\n                return 0;\n            }\n\n            // Do the fixed-point inversion inline to save gas. The numerator is SCALE * SCALE.\n            unchecked {\n                result = 1e36 / exp2(-x);\n            }\n        } else {\n            // 2^192 doesn't fit within the 192.64-bit fixed-point representation.\n            require(x < 192e18);\n\n            unchecked {\n                // Convert x to the 192.64-bit fixed-point format.\n                uint256 x192x64 = (uint256(x) << 64) / uint256(SCALE);\n\n                // Safe to convert the result to int256 directly because the maximum input allowed is 192.\n                result = int256(PRBMath.exp2(x192x64));\n            }\n        }\n    }\n\n    /// @notice Yields the greatest signed 59.18 decimal fixed-point number less than or equal to x.\n    ///\n    /// @dev Optimised for fractional value inputs, because for every whole value there are (1e18 - 1) fractional counterparts.\n    /// See https://en.wikipedia.org/wiki/Floor_and_ceiling_functions.\n    ///\n    /// Requirements:\n    /// - x must be greater than or equal to MIN_WHOLE_SD59x18.\n    ///\n    /// @param x The signed 59.18-decimal fixed-point number to floor.\n    /// @param result The greatest integer less than or equal to x, as a signed 58.18-decimal fixed-point number.\n    function floor(int256 x) internal pure returns (int256 result) {\n        require(x >= MIN_WHOLE_SD59x18);\n        unchecked {\n            int256 remainder = x % SCALE;\n            if (remainder == 0) {\n                result = x;\n            } else {\n                // Solidity uses C fmod style, which returns a modulus with the same sign as x.\n                result = x - remainder;\n                if (x < 0) {\n                    result -= SCALE;\n                }\n            }\n        }\n    }\n\n    /// @notice Yields the excess beyond the floor of x for positive numbers and the part of the number to the right\n    /// of the radix point for negative numbers.\n    /// @dev Based on the odd function definition. https://en.wikipedia.org/wiki/Fractional_part\n    /// @param x The signed 59.18-decimal fixed-point number to get the fractional part of.\n    /// @param result The fractional part of x as a signed 59.18-decimal fixed-point number.\n    function frac(int256 x) internal pure returns (int256 result) {\n        unchecked {\n            result = x % SCALE;\n        }\n    }\n\n    /// @notice Converts a number from basic integer form to signed 59.18-decimal fixed-point representation.\n    ///\n    /// @dev Requirements:\n    /// - x must be greater than or equal to MIN_SD59x18 divided by SCALE.\n    /// - x must be less than or equal to MAX_SD59x18 divided by SCALE.\n    ///\n    /// @param x The basic integer to convert.\n    /// @param result The same number in signed 59.18-decimal fixed-point representation.\n    function fromInt(int256 x) internal pure returns (int256 result) {\n        unchecked {\n            require(x >= MIN_SD59x18 / SCALE && x <= MAX_SD59x18 / SCALE);\n            result = x * SCALE;\n        }\n    }\n\n    /// @notice Calculates geometric mean of x and y, i.e. sqrt(x * y), rounding down.\n    ///\n    /// @dev Requirements:\n    /// - x * y must fit within MAX_SD59x18, lest it overflows.\n    /// - x * y cannot be negative.\n    ///\n    /// @param x The first operand as a signed 59.18-decimal fixed-point number.\n    /// @param y The second operand as a signed 59.18-decimal fixed-point number.\n    /// @return result The result as a signed 59.18-decimal fixed-point number.\n    function gm(int256 x, int256 y) internal pure returns (int256 result) {\n        if (x == 0) {\n            return 0;\n        }\n\n        unchecked {\n            // Checking for overflow this way is faster than letting Solidity do it.\n            int256 xy = x * y;\n            require(xy / x == y);\n\n            // The product cannot be negative.\n            require(xy >= 0);\n\n            // We don't need to multiply by the SCALE here because the x*y product had already picked up a factor of SCALE\n            // during multiplication. See the comments within the \"sqrt\" function.\n            result = int256(PRBMath.sqrt(uint256(xy)));\n        }\n    }\n\n    /// @notice Calculates 1 / x, rounding towards zero.\n    ///\n    /// @dev Requirements:\n    /// - x cannot be zero.\n    ///\n    /// @param x The signed 59.18-decimal fixed-point number for which to calculate the inverse.\n    /// @return result The inverse as a signed 59.18-decimal fixed-point number.\n    function inv(int256 x) internal pure returns (int256 result) {\n        unchecked {\n            // 1e36 is SCALE * SCALE.\n            result = 1e36 / x;\n        }\n    }\n\n    /// @notice Calculates the natural logarithm of x.\n    ///\n    /// @dev Based on the insight that ln(x) = log2(x) / log2(e).\n    ///\n    /// Requirements:\n    /// - All from \"log2\".\n    ///\n    /// Caveats:\n    /// - All from \"log2\".\n    /// - This doesn't return exactly 1 for 2718281828459045235, for that we would need more fine-grained precision.\n    ///\n    /// @param x The signed 59.18-decimal fixed-point number for which to calculate the natural logarithm.\n    /// @return result The natural logarithm as a signed 59.18-decimal fixed-point number.\n    function ln(int256 x) internal pure returns (int256 result) {\n        // Do the fixed-point multiplication inline to save gas. This is overflow-safe because the maximum value that log2(x)\n        // can return is 195205294292027477728.\n        unchecked {\n            result = (log2(x) * SCALE) / LOG2_E;\n        }\n    }\n\n    /// @notice Calculates the common logarithm of x.\n    ///\n    /// @dev First checks if x is an exact power of ten and it stops if yes. If it's not, calculates the common\n    /// logarithm based on the insight that log10(x) = log2(x) / log2(10).\n    ///\n    /// Requirements:\n    /// - All from \"log2\".\n    ///\n    /// Caveats:\n    /// - All from \"log2\".\n    ///\n    /// @param x The signed 59.18-decimal fixed-point number for which to calculate the common logarithm.\n    /// @return result The common logarithm as a signed 59.18-decimal fixed-point number.\n    function log10(int256 x) internal pure returns (int256 result) {\n        require(x > 0);\n\n        // Note that the \"mul\" in this block is the assembly mul operation, not the \"mul\" function defined in this contract.\n        // prettier-ignore\n        assembly {\n            switch x\n            case 1 { result := mul(SCALE, sub(0, 18)) }\n            case 10 { result := mul(SCALE, sub(1, 18)) }\n            case 100 { result := mul(SCALE, sub(2, 18)) }\n            case 1000 { result := mul(SCALE, sub(3, 18)) }\n            case 10000 { result := mul(SCALE, sub(4, 18)) }\n            case 100000 { result := mul(SCALE, sub(5, 18)) }\n            case 1000000 { result := mul(SCALE, sub(6, 18)) }\n            case 10000000 { result := mul(SCALE, sub(7, 18)) }\n            case 100000000 { result := mul(SCALE, sub(8, 18)) }\n            case 1000000000 { result := mul(SCALE, sub(9, 18)) }\n            case 10000000000 { result := mul(SCALE, sub(10, 18)) }\n            case 100000000000 { result := mul(SCALE, sub(11, 18)) }\n            case 1000000000000 { result := mul(SCALE, sub(12, 18)) }\n            case 10000000000000 { result := mul(SCALE, sub(13, 18)) }\n            case 100000000000000 { result := mul(SCALE, sub(14, 18)) }\n            case 1000000000000000 { result := mul(SCALE, sub(15, 18)) }\n            case 10000000000000000 { result := mul(SCALE, sub(16, 18)) }\n            case 100000000000000000 { result := mul(SCALE, sub(17, 18)) }\n            case 1000000000000000000 { result := 0 }\n            case 10000000000000000000 { result := SCALE }\n            case 100000000000000000000 { result := mul(SCALE, 2) }\n            case 1000000000000000000000 { result := mul(SCALE, 3) }\n            case 10000000000000000000000 { result := mul(SCALE, 4) }\n            case 100000000000000000000000 { result := mul(SCALE, 5) }\n            case 1000000000000000000000000 { result := mul(SCALE, 6) }\n            case 10000000000000000000000000 { result := mul(SCALE, 7) }\n            case 100000000000000000000000000 { result := mul(SCALE, 8) }\n            case 1000000000000000000000000000 { result := mul(SCALE, 9) }\n            case 10000000000000000000000000000 { result := mul(SCALE, 10) }\n            case 100000000000000000000000000000 { result := mul(SCALE, 11) }\n            case 1000000000000000000000000000000 { result := mul(SCALE, 12) }\n            case 10000000000000000000000000000000 { result := mul(SCALE, 13) }\n            case 100000000000000000000000000000000 { result := mul(SCALE, 14) }\n            case 1000000000000000000000000000000000 { result := mul(SCALE, 15) }\n            case 10000000000000000000000000000000000 { result := mul(SCALE, 16) }\n            case 100000000000000000000000000000000000 { result := mul(SCALE, 17) }\n            case 1000000000000000000000000000000000000 { result := mul(SCALE, 18) }\n            case 10000000000000000000000000000000000000 { result := mul(SCALE, 19) }\n            case 100000000000000000000000000000000000000 { result := mul(SCALE, 20) }\n            case 1000000000000000000000000000000000000000 { result := mul(SCALE, 21) }\n            case 10000000000000000000000000000000000000000 { result := mul(SCALE, 22) }\n            case 100000000000000000000000000000000000000000 { result := mul(SCALE, 23) }\n            case 1000000000000000000000000000000000000000000 { result := mul(SCALE, 24) }\n            case 10000000000000000000000000000000000000000000 { result := mul(SCALE, 25) }\n            case 100000000000000000000000000000000000000000000 { result := mul(SCALE, 26) }\n            case 1000000000000000000000000000000000000000000000 { result := mul(SCALE, 27) }\n            case 10000000000000000000000000000000000000000000000 { result := mul(SCALE, 28) }\n            case 100000000000000000000000000000000000000000000000 { result := mul(SCALE, 29) }\n            case 1000000000000000000000000000000000000000000000000 { result := mul(SCALE, 30) }\n            case 10000000000000000000000000000000000000000000000000 { result := mul(SCALE, 31) }\n            case 100000000000000000000000000000000000000000000000000 { result := mul(SCALE, 32) }\n            case 1000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 33) }\n            case 10000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 34) }\n            case 100000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 35) }\n            case 1000000000000000000000000000000000000000000000000000000 {\n                result := mul(SCALE, 36)\n            }\n            case 10000000000000000000000000000000000000000000000000000000 {\n                result := mul(SCALE, 37)\n            }\n            case 100000000000000000000000000000000000000000000000000000000 {\n                result := mul(SCALE, 38)\n            }\n            case 1000000000000000000000000000000000000000000000000000000000 {\n                result := mul(SCALE, 39)\n            }\n            case 10000000000000000000000000000000000000000000000000000000000 {\n                result := mul(SCALE, 40)\n            }\n            case 100000000000000000000000000000000000000000000000000000000000 {\n                result := mul(SCALE, 41)\n            }\n            case 1000000000000000000000000000000000000000000000000000000000000 {\n                result := mul(SCALE, 42)\n            }\n            case 10000000000000000000000000000000000000000000000000000000000000 {\n                result := mul(SCALE, 43)\n            }\n            case 100000000000000000000000000000000000000000000000000000000000000 {\n                result := mul(SCALE, 44)\n            }\n            case 1000000000000000000000000000000000000000000000000000000000000000 {\n                result := mul(SCALE, 45)\n            }\n            case 10000000000000000000000000000000000000000000000000000000000000000 {\n                result := mul(SCALE, 46)\n            }\n            case 100000000000000000000000000000000000000000000000000000000000000000 {\n                result := mul(SCALE, 47)\n            }\n            case 1000000000000000000000000000000000000000000000000000000000000000000 {\n                result := mul(SCALE, 48)\n            }\n            case 10000000000000000000000000000000000000000000000000000000000000000000 {\n                result := mul(SCALE, 49)\n            }\n            case 100000000000000000000000000000000000000000000000000000000000000000000 {\n                result := mul(SCALE, 50)\n            }\n            case 1000000000000000000000000000000000000000000000000000000000000000000000 {\n                result := mul(SCALE, 51)\n            }\n            case 10000000000000000000000000000000000000000000000000000000000000000000000 {\n                result := mul(SCALE, 52)\n            }\n            case 100000000000000000000000000000000000000000000000000000000000000000000000 {\n                result := mul(SCALE, 53)\n            }\n            case 1000000000000000000000000000000000000000000000000000000000000000000000000 {\n                result := mul(SCALE, 54)\n            }\n            case 10000000000000000000000000000000000000000000000000000000000000000000000000 {\n                result := mul(SCALE, 55)\n            }\n            case 100000000000000000000000000000000000000000000000000000000000000000000000000 {\n                result := mul(SCALE, 56)\n            }\n            case 1000000000000000000000000000000000000000000000000000000000000000000000000000 {\n                result := mul(SCALE, 57)\n            }\n            case 10000000000000000000000000000000000000000000000000000000000000000000000000000 {\n                result := mul(SCALE, 58)\n            }\n            default { result := MAX_SD59x18 }\n        }\n\n        if (result == MAX_SD59x18) {\n            // Do the fixed-point division inline to save gas. The denominator is log2(10).\n            unchecked {\n                result = (log2(x) * SCALE) / 3_321_928_094_887_362_347;\n            }\n        }\n    }\n\n    /// @notice Calculates the binary logarithm of x.\n    ///\n    /// @dev Based on the iterative approximation algorithm.\n    /// https://en.wikipedia.org/wiki/Binary_logarithm#Iterative_approximation\n    ///\n    /// Requirements:\n    /// - x must be greater than zero.\n    ///\n    /// Caveats:\n    /// - The results are not perfectly accurate to the last decimal, due to the lossy precision of the iterative approximation.\n    ///\n    /// @param x The signed 59.18-decimal fixed-point number for which to calculate the binary logarithm.\n    /// @return result The binary logarithm as a signed 59.18-decimal fixed-point number.\n    function log2(int256 x) internal pure returns (int256 result) {\n        require(x > 0);\n        unchecked {\n            // This works because log2(x) = -log2(1/x).\n            int256 sign;\n            if (x >= SCALE) {\n                sign = 1;\n            } else {\n                sign = -1;\n                // Do the fixed-point inversion inline to save gas. The numerator is SCALE * SCALE.\n                assembly {\n                    x := div(1000000000000000000000000000000000000, x)\n                }\n            }\n\n            // Calculate the integer part of the logarithm and add it to the result and finally calculate y = x * 2^(-n).\n            uint256 n = PRBMath.mostSignificantBit(uint256(x / SCALE));\n\n            // The integer part of the logarithm as a signed 59.18-decimal fixed-point number. The operation can't overflow\n            // because n is maximum 255, SCALE is 1e18 and sign is either 1 or -1.\n            result = int256(n) * SCALE;\n\n            // This is y = x * 2^(-n).\n            int256 y = x >> n;\n\n            // If y = 1, the fractional part is zero.\n            if (y == SCALE) {\n                return result * sign;\n            }\n\n            // Calculate the fractional part via the iterative approximation.\n            // The \"delta >>= 1\" part is equivalent to \"delta /= 2\", but shifting bits is faster.\n            for (int256 delta = int256(HALF_SCALE); delta > 0; delta >>= 1) {\n                y = (y * y) / SCALE;\n\n                // Is y^2 > 2 and so in the range [2,4)?\n                if (y >= 2 * SCALE) {\n                    // Add the 2^(-m) factor to the logarithm.\n                    result += delta;\n\n                    // Corresponds to z/2 on Wikipedia.\n                    y >>= 1;\n                }\n            }\n            result *= sign;\n        }\n    }\n\n    /// @notice Multiplies two signed 59.18-decimal fixed-point numbers together, returning a new signed 59.18-decimal\n    /// fixed-point number.\n    ///\n    /// @dev Variant of \"mulDiv\" that works with signed numbers and employs constant folding, i.e. the denominator is\n    /// alawys 1e18.\n    ///\n    /// Requirements:\n    /// - All from \"PRBMath.mulDivFixedPoint\".\n    /// - The result must fit within MAX_SD59x18.\n    ///\n    /// Caveats:\n    /// - The body is purposely left uncommented; see the NatSpec comments in \"PRBMath.mulDiv\" to understand how this works.\n    ///\n    /// @param x The multiplicand as a signed 59.18-decimal fixed-point number.\n    /// @param y The multiplier as a signed 59.18-decimal fixed-point number.\n    /// @return result The result as a signed 59.18-decimal fixed-point number.\n    function mul(int256 x, int256 y) internal pure returns (int256 result) {\n        require(x > MIN_SD59x18);\n        require(y > MIN_SD59x18);\n\n        unchecked {\n            uint256 ax;\n            uint256 ay;\n            ax = x < 0 ? uint256(-x) : uint256(x);\n            ay = y < 0 ? uint256(-y) : uint256(y);\n\n            uint256 rUnsigned = PRBMath.mulDivFixedPoint(ax, ay);\n            require(rUnsigned <= uint256(MAX_SD59x18));\n\n            uint256 sx;\n            uint256 sy;\n            assembly {\n                sx := sgt(x, sub(0, 1))\n                sy := sgt(y, sub(0, 1))\n            }\n            result = sx ^ sy == 1 ? -int256(rUnsigned) : int256(rUnsigned);\n        }\n    }\n\n    /// @notice Returns PI as a signed 59.18-decimal fixed-point number.\n    function pi() internal pure returns (int256 result) {\n        result = 3_141_592_653_589_793_238;\n    }\n\n    /// @notice Raises x to the power of y.\n    ///\n    /// @dev Based on the insight that x^y = 2^(log2(x) * y).\n    ///\n    /// Requirements:\n    /// - All from \"exp2\", \"log2\" and \"mul\".\n    /// - z cannot be zero.\n    ///\n    /// Caveats:\n    /// - All from \"exp2\", \"log2\" and \"mul\".\n    /// - Assumes 0^0 is 1.\n    ///\n    /// @param x Number to raise to given power y, as a signed 59.18-decimal fixed-point number.\n    /// @param y Exponent to raise x to, as a signed 59.18-decimal fixed-point number.\n    /// @return result x raised to power y, as a signed 59.18-decimal fixed-point number.\n    function pow(int256 x, int256 y) internal pure returns (int256 result) {\n        if (x == 0) {\n            return y == 0 ? SCALE : int256(0);\n        } else {\n            result = exp2(mul(log2(x), y));\n        }\n    }\n\n    /// @notice Raises x (signed 59.18-decimal fixed-point number) to the power of y (basic unsigned integer) using the\n    /// famous algorithm \"exponentiation by squaring\".\n    ///\n    /// @dev See https://en.wikipedia.org/wiki/Exponentiation_by_squaring\n    ///\n    /// Requirements:\n    /// - All from \"abs\" and \"PRBMath.mulDivFixedPoint\".\n    /// - The result must fit within MAX_SD59x18.\n    ///\n    /// Caveats:\n    /// - All from \"PRBMath.mulDivFixedPoint\".\n    /// - Assumes 0^0 is 1.\n    ///\n    /// @param x The base as a signed 59.18-decimal fixed-point number.\n    /// @param y The exponent as an uint256.\n    /// @return result The result as a signed 59.18-decimal fixed-point number.\n    function powu(int256 x, uint256 y) internal pure returns (int256 result) {\n        uint256 xAbs = uint256(abs(x));\n\n        // Calculate the first iteration of the loop in advance.\n        uint256 rAbs = y & 1 > 0 ? xAbs : uint256(SCALE);\n\n        // Equivalent to \"for(y /= 2; y > 0; y /= 2)\" but faster.\n        uint256 yAux = y;\n        for (yAux >>= 1; yAux > 0; yAux >>= 1) {\n            xAbs = PRBMath.mulDivFixedPoint(xAbs, xAbs);\n\n            // Equivalent to \"y % 2 == 1\" but faster.\n            if (yAux & 1 > 0) {\n                rAbs = PRBMath.mulDivFixedPoint(rAbs, xAbs);\n            }\n        }\n\n        // The result must fit within the 59.18-decimal fixed-point representation.\n        require(rAbs <= uint256(MAX_SD59x18));\n\n        // Is the base negative and the exponent an odd number?\n        bool isNegative = x < 0 && y & 1 == 1;\n        result = isNegative ? -int256(rAbs) : int256(rAbs);\n    }\n\n    /// @notice Returns 1 as a signed 59.18-decimal fixed-point number.\n    function scale() internal pure returns (int256 result) {\n        result = SCALE;\n    }\n\n    /// @notice Calculates the square root of x, rounding down.\n    /// @dev Uses the Babylonian method https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method.\n    ///\n    /// Requirements:\n    /// - x cannot be negative.\n    /// - x must be less than MAX_SD59x18 / SCALE.\n    ///\n    /// Caveats:\n    /// - The maximum fixed-point number permitted is 57896044618658097711785492504343953926634.992332820282019729.\n    ///\n    /// @param x The signed 59.18-decimal fixed-point number for which to calculate the square root.\n    /// @return result The result as a signed 59.18-decimal fixed-point .\n    function sqrt(int256 x) internal pure returns (int256 result) {\n        require(x >= 0);\n        require(x < 57_896_044_618_658_097_711_785_492_504_343_953_926_634_992_332_820_282_019_729);\n        unchecked {\n            // Multiply x by the SCALE to account for the factor of SCALE that is picked up when multiplying two signed\n            // 59.18-decimal fixed-point numbers together (in this case, those two numbers are both the square root).\n            result = int256(PRBMath.sqrt(uint256(x * SCALE)));\n        }\n    }\n\n    /// @notice Converts a signed 59.18-decimal fixed-point number to basic integer form, rounding down in the process.\n    /// @param x The signed 59.18-decimal fixed-point number to convert.\n    /// @return result The same number in basic integer form.\n    function toInt(int256 x) internal pure returns (int256 result) {\n        unchecked {\n            result = x / SCALE;\n        }\n    }\n}\n"
      },
      "src/utils/PRBMathUD60x18.sol": {
        "content": "// SPDX-License-Identifier: Unlicense\npragma solidity >=0.8.4;\n\nimport \"./PRBMath.sol\";\n\n/// @title PRBMathUD60x18\n/// @author Paul Razvan Berg\n/// @notice Smart contract library for advanced fixed-point math that works with uint256 numbers considered to have 18\n/// trailing decimals. We call this number representation unsigned 60.18-decimal fixed-point, since there can be up to 60\n/// digits in the integer part and up to 18 decimals in the fractional part. The numbers are bound by the minimum and the\n/// maximum values permitted by the Solidity type uint256.\nlibrary PRBMathUD60x18 {\n    /// @dev Half the SCALE number.\n    uint256 internal constant HALF_SCALE = 5e17;\n\n    /// @dev log2(e) as an unsigned 60.18-decimal fixed-point number.\n    uint256 internal constant LOG2_E = 1_442_695_040_888_963_407;\n\n    /// @dev The maximum value an unsigned 60.18-decimal fixed-point number can have.\n    uint256 internal constant MAX_UD60x18 =\n        115_792_089_237_316_195_423_570_985_008_687_907_853_269_984_665_640_564_039_457_584_007_913_129_639_935;\n\n    /// @dev The maximum whole value an unsigned 60.18-decimal fixed-point number can have.\n    uint256 internal constant MAX_WHOLE_UD60x18 =\n        115_792_089_237_316_195_423_570_985_008_687_907_853_269_984_665_640_564_039_457_000_000_000_000_000_000;\n\n    /// @dev How many trailing decimals can be represented.\n    uint256 internal constant SCALE = 1e18;\n\n    /// @notice Calculates the arithmetic average of x and y, rounding down.\n    /// @param x The first operand as an unsigned 60.18-decimal fixed-point number.\n    /// @param y The second operand as an unsigned 60.18-decimal fixed-point number.\n    /// @return result The arithmetic average as an unsigned 60.18-decimal fixed-point number.\n    function avg(uint256 x, uint256 y) internal pure returns (uint256 result) {\n        // The operations can never overflow.\n        unchecked {\n            // The last operand checks if both x and y are odd and if that is the case, we add 1 to the result. We need\n            // to do this because if both numbers are odd, the 0.5 remainder gets truncated twice.\n            result = (x >> 1) + (y >> 1) + (x & y & 1);\n        }\n    }\n\n    /// @notice Yields the least unsigned 60.18 decimal fixed-point number greater than or equal to x.\n    ///\n    /// @dev Optimized for fractional value inputs, because for every whole value there are (1e18 - 1) fractional counterparts.\n    /// See https://en.wikipedia.org/wiki/Floor_and_ceiling_functions.\n    ///\n    /// Requirements:\n    /// - x must be less than or equal to MAX_WHOLE_UD60x18.\n    ///\n    /// @param x The unsigned 60.18-decimal fixed-point number to ceil.\n    /// @param result The least integer greater than or equal to x, as an unsigned 60.18-decimal fixed-point number.\n    function ceil(uint256 x) internal pure returns (uint256 result) {\n        if (x > MAX_WHOLE_UD60x18) {\n            revert PRBMathUD60x18__CeilOverflow(x);\n        }\n        assembly {\n            // Equivalent to \"x % SCALE\" but faster.\n            let remainder := mod(x, SCALE)\n\n            // Equivalent to \"SCALE - remainder\" but faster.\n            let delta := sub(SCALE, remainder)\n\n            // Equivalent to \"x + delta * (remainder > 0 ? 1 : 0)\" but faster.\n            result := add(x, mul(delta, gt(remainder, 0)))\n        }\n    }\n\n    /// @notice Divides two unsigned 60.18-decimal fixed-point numbers, returning a new unsigned 60.18-decimal fixed-point number.\n    ///\n    /// @dev Uses mulDiv to enable overflow-safe multiplication and division.\n    ///\n    /// Requirements:\n    /// - The denominator cannot be zero.\n    ///\n    /// @param x The numerator as an unsigned 60.18-decimal fixed-point number.\n    /// @param y The denominator as an unsigned 60.18-decimal fixed-point number.\n    /// @param result The quotient as an unsigned 60.18-decimal fixed-point number.\n    function div(uint256 x, uint256 y) internal pure returns (uint256 result) {\n        result = PRBMath.mulDiv(x, SCALE, y);\n    }\n\n    /// @notice Returns Euler's number as an unsigned 60.18-decimal fixed-point number.\n    /// @dev See https://en.wikipedia.org/wiki/E_(mathematical_constant).\n    function e() internal pure returns (uint256 result) {\n        result = 2_718_281_828_459_045_235;\n    }\n\n    /// @notice Calculates the natural exponent of x.\n    ///\n    /// @dev Based on the insight that e^x = 2^(x * log2(e)).\n    ///\n    /// Requirements:\n    /// - All from \"log2\".\n    /// - x must be less than 133.084258667509499441.\n    ///\n    /// @param x The exponent as an unsigned 60.18-decimal fixed-point number.\n    /// @return result The result as an unsigned 60.18-decimal fixed-point number.\n    function exp(uint256 x) internal pure returns (uint256 result) {\n        // Without this check, the value passed to \"exp2\" would be greater than 192.\n        if (x >= 133_084_258_667_509_499_441) {\n            revert PRBMathUD60x18__ExpInputTooBig(x);\n        }\n\n        // Do the fixed-point multiplication inline to save gas.\n        unchecked {\n            uint256 doubleScaleProduct = x * LOG2_E;\n            result = exp2((doubleScaleProduct + HALF_SCALE) / SCALE);\n        }\n    }\n\n    /// @notice Calculates the binary exponent of x using the binary fraction method.\n    ///\n    /// @dev See https://ethereum.stackexchange.com/q/79903/24693.\n    ///\n    /// Requirements:\n    /// - x must be 192 or less.\n    /// - The result must fit within MAX_UD60x18.\n    ///\n    /// @param x The exponent as an unsigned 60.18-decimal fixed-point number.\n    /// @return result The result as an unsigned 60.18-decimal fixed-point number.\n    function exp2(uint256 x) internal pure returns (uint256 result) {\n        // 2^192 doesn't fit within the 192.64-bit format used internally in this function.\n        if (x >= 192e18) {\n            revert PRBMathUD60x18__Exp2InputTooBig(x);\n        }\n\n        unchecked {\n            // Convert x to the 192.64-bit fixed-point format.\n            uint256 x192x64 = (x << 64) / SCALE;\n\n            // Pass x to the PRBMath.exp2 function, which uses the 192.64-bit fixed-point number representation.\n            result = PRBMath.exp2(x192x64);\n        }\n    }\n\n    /// @notice Yields the greatest unsigned 60.18 decimal fixed-point number less than or equal to x.\n    /// @dev Optimized for fractional value inputs, because for every whole value there are (1e18 - 1) fractional counterparts.\n    /// See https://en.wikipedia.org/wiki/Floor_and_ceiling_functions.\n    /// @param x The unsigned 60.18-decimal fixed-point number to floor.\n    /// @param result The greatest integer less than or equal to x, as an unsigned 60.18-decimal fixed-point number.\n    function floor(uint256 x) internal pure returns (uint256 result) {\n        assembly {\n            // Equivalent to \"x % SCALE\" but faster.\n            let remainder := mod(x, SCALE)\n\n            // Equivalent to \"x - remainder * (remainder > 0 ? 1 : 0)\" but faster.\n            result := sub(x, mul(remainder, gt(remainder, 0)))\n        }\n    }\n\n    /// @notice Yields the excess beyond the floor of x.\n    /// @dev Based on the odd function definition https://en.wikipedia.org/wiki/Fractional_part.\n    /// @param x The unsigned 60.18-decimal fixed-point number to get the fractional part of.\n    /// @param result The fractional part of x as an unsigned 60.18-decimal fixed-point number.\n    function frac(uint256 x) internal pure returns (uint256 result) {\n        assembly {\n            result := mod(x, SCALE)\n        }\n    }\n\n    /// @notice Converts a number from basic integer form to unsigned 60.18-decimal fixed-point representation.\n    ///\n    /// @dev Requirements:\n    /// - x must be less than or equal to MAX_UD60x18 divided by SCALE.\n    ///\n    /// @param x The basic integer to convert.\n    /// @param result The same number in unsigned 60.18-decimal fixed-point representation.\n    function fromUint(uint256 x) internal pure returns (uint256 result) {\n        unchecked {\n            if (x > MAX_UD60x18 / SCALE) {\n                revert PRBMathUD60x18__FromUintOverflow(x);\n            }\n            result = x * SCALE;\n        }\n    }\n\n    /// @notice Calculates geometric mean of x and y, i.e. sqrt(x * y), rounding down.\n    ///\n    /// @dev Requirements:\n    /// - x * y must fit within MAX_UD60x18, lest it overflows.\n    ///\n    /// @param x The first operand as an unsigned 60.18-decimal fixed-point number.\n    /// @param y The second operand as an unsigned 60.18-decimal fixed-point number.\n    /// @return result The result as an unsigned 60.18-decimal fixed-point number.\n    function gm(uint256 x, uint256 y) internal pure returns (uint256 result) {\n        if (x == 0) {\n            return 0;\n        }\n\n        unchecked {\n            // Checking for overflow this way is faster than letting Solidity do it.\n            uint256 xy = x * y;\n            if (xy / x != y) {\n                revert PRBMathUD60x18__GmOverflow(x, y);\n            }\n\n            // We don't need to multiply by the SCALE here because the x*y product had already picked up a factor of SCALE\n            // during multiplication. See the comments within the \"sqrt\" function.\n            result = PRBMath.sqrt(xy);\n        }\n    }\n\n    /// @notice Calculates 1 / x, rounding toward zero.\n    ///\n    /// @dev Requirements:\n    /// - x cannot be zero.\n    ///\n    /// @param x The unsigned 60.18-decimal fixed-point number for which to calculate the inverse.\n    /// @return result The inverse as an unsigned 60.18-decimal fixed-point number.\n    function inv(uint256 x) internal pure returns (uint256 result) {\n        unchecked {\n            // 1e36 is SCALE * SCALE.\n            result = 1e36 / x;\n        }\n    }\n\n    /// @notice Calculates the natural logarithm of x.\n    ///\n    /// @dev Based on the insight that ln(x) = log2(x) / log2(e).\n    ///\n    /// Requirements:\n    /// - All from \"log2\".\n    ///\n    /// Caveats:\n    /// - All from \"log2\".\n    /// - This doesn't return exactly 1 for 2.718281828459045235, for that we would need more fine-grained precision.\n    ///\n    /// @param x The unsigned 60.18-decimal fixed-point number for which to calculate the natural logarithm.\n    /// @return result The natural logarithm as an unsigned 60.18-decimal fixed-point number.\n    function ln(uint256 x) internal pure returns (uint256 result) {\n        // Do the fixed-point multiplication inline to save gas. This is overflow-safe because the maximum value that log2(x)\n        // can return is 196205294292027477728.\n        unchecked {\n            result = (log2(x) * SCALE) / LOG2_E;\n        }\n    }\n\n    /// @notice Calculates the common logarithm of x.\n    ///\n    /// @dev First checks if x is an exact power of ten and it stops if yes. If it's not, calculates the common\n    /// logarithm based on the insight that log10(x) = log2(x) / log2(10).\n    ///\n    /// Requirements:\n    /// - All from \"log2\".\n    ///\n    /// Caveats:\n    /// - All from \"log2\".\n    ///\n    /// @param x The unsigned 60.18-decimal fixed-point number for which to calculate the common logarithm.\n    /// @return result The common logarithm as an unsigned 60.18-decimal fixed-point number.\n    function log10(uint256 x) internal pure returns (uint256 result) {\n        if (x < SCALE) {\n            revert PRBMathUD60x18__LogInputTooSmall(x);\n        }\n\n        // Note that the \"mul\" in this block is the assembly multiplication operation, not the \"mul\" function defined\n        // in this contract.\n        // prettier-ignore\n        assembly {\n            switch x\n            case 1 { result := mul(SCALE, sub(0, 18)) }\n            case 10 { result := mul(SCALE, sub(1, 18)) }\n            case 100 { result := mul(SCALE, sub(2, 18)) }\n            case 1000 { result := mul(SCALE, sub(3, 18)) }\n            case 10000 { result := mul(SCALE, sub(4, 18)) }\n            case 100000 { result := mul(SCALE, sub(5, 18)) }\n            case 1000000 { result := mul(SCALE, sub(6, 18)) }\n            case 10000000 { result := mul(SCALE, sub(7, 18)) }\n            case 100000000 { result := mul(SCALE, sub(8, 18)) }\n            case 1000000000 { result := mul(SCALE, sub(9, 18)) }\n            case 10000000000 { result := mul(SCALE, sub(10, 18)) }\n            case 100000000000 { result := mul(SCALE, sub(11, 18)) }\n            case 1000000000000 { result := mul(SCALE, sub(12, 18)) }\n            case 10000000000000 { result := mul(SCALE, sub(13, 18)) }\n            case 100000000000000 { result := mul(SCALE, sub(14, 18)) }\n            case 1000000000000000 { result := mul(SCALE, sub(15, 18)) }\n            case 10000000000000000 { result := mul(SCALE, sub(16, 18)) }\n            case 100000000000000000 { result := mul(SCALE, sub(17, 18)) }\n            case 1000000000000000000 { result := 0 }\n            case 10000000000000000000 { result := SCALE }\n            case 100000000000000000000 { result := mul(SCALE, 2) }\n            case 1000000000000000000000 { result := mul(SCALE, 3) }\n            case 10000000000000000000000 { result := mul(SCALE, 4) }\n            case 100000000000000000000000 { result := mul(SCALE, 5) }\n            case 1000000000000000000000000 { result := mul(SCALE, 6) }\n            case 10000000000000000000000000 { result := mul(SCALE, 7) }\n            case 100000000000000000000000000 { result := mul(SCALE, 8) }\n            case 1000000000000000000000000000 { result := mul(SCALE, 9) }\n            case 10000000000000000000000000000 { result := mul(SCALE, 10) }\n            case 100000000000000000000000000000 { result := mul(SCALE, 11) }\n            case 1000000000000000000000000000000 { result := mul(SCALE, 12) }\n            case 10000000000000000000000000000000 { result := mul(SCALE, 13) }\n            case 100000000000000000000000000000000 { result := mul(SCALE, 14) }\n            case 1000000000000000000000000000000000 { result := mul(SCALE, 15) }\n            case 10000000000000000000000000000000000 { result := mul(SCALE, 16) }\n            case 100000000000000000000000000000000000 { result := mul(SCALE, 17) }\n            case 1000000000000000000000000000000000000 { result := mul(SCALE, 18) }\n            case 10000000000000000000000000000000000000 { result := mul(SCALE, 19) }\n            case 100000000000000000000000000000000000000 { result := mul(SCALE, 20) }\n            case 1000000000000000000000000000000000000000 { result := mul(SCALE, 21) }\n            case 10000000000000000000000000000000000000000 { result := mul(SCALE, 22) }\n            case 100000000000000000000000000000000000000000 { result := mul(SCALE, 23) }\n            case 1000000000000000000000000000000000000000000 { result := mul(SCALE, 24) }\n            case 10000000000000000000000000000000000000000000 { result := mul(SCALE, 25) }\n            case 100000000000000000000000000000000000000000000 { result := mul(SCALE, 26) }\n            case 1000000000000000000000000000000000000000000000 { result := mul(SCALE, 27) }\n            case 10000000000000000000000000000000000000000000000 { result := mul(SCALE, 28) }\n            case 100000000000000000000000000000000000000000000000 { result := mul(SCALE, 29) }\n            case 1000000000000000000000000000000000000000000000000 { result := mul(SCALE, 30) }\n            case 10000000000000000000000000000000000000000000000000 { result := mul(SCALE, 31) }\n            case 100000000000000000000000000000000000000000000000000 { result := mul(SCALE, 32) }\n            case 1000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 33) }\n            case 10000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 34) }\n            case 100000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 35) }\n            case 1000000000000000000000000000000000000000000000000000000 {\n                result := mul(SCALE, 36)\n            }\n            case 10000000000000000000000000000000000000000000000000000000 {\n                result := mul(SCALE, 37)\n            }\n            case 100000000000000000000000000000000000000000000000000000000 {\n                result := mul(SCALE, 38)\n            }\n            case 1000000000000000000000000000000000000000000000000000000000 {\n                result := mul(SCALE, 39)\n            }\n            case 10000000000000000000000000000000000000000000000000000000000 {\n                result := mul(SCALE, 40)\n            }\n            case 100000000000000000000000000000000000000000000000000000000000 {\n                result := mul(SCALE, 41)\n            }\n            case 1000000000000000000000000000000000000000000000000000000000000 {\n                result := mul(SCALE, 42)\n            }\n            case 10000000000000000000000000000000000000000000000000000000000000 {\n                result := mul(SCALE, 43)\n            }\n            case 100000000000000000000000000000000000000000000000000000000000000 {\n                result := mul(SCALE, 44)\n            }\n            case 1000000000000000000000000000000000000000000000000000000000000000 {\n                result := mul(SCALE, 45)\n            }\n            case 10000000000000000000000000000000000000000000000000000000000000000 {\n                result := mul(SCALE, 46)\n            }\n            case 100000000000000000000000000000000000000000000000000000000000000000 {\n                result := mul(SCALE, 47)\n            }\n            case 1000000000000000000000000000000000000000000000000000000000000000000 {\n                result := mul(SCALE, 48)\n            }\n            case 10000000000000000000000000000000000000000000000000000000000000000000 {\n                result := mul(SCALE, 49)\n            }\n            case 100000000000000000000000000000000000000000000000000000000000000000000 {\n                result := mul(SCALE, 50)\n            }\n            case 1000000000000000000000000000000000000000000000000000000000000000000000 {\n                result := mul(SCALE, 51)\n            }\n            case 10000000000000000000000000000000000000000000000000000000000000000000000 {\n                result := mul(SCALE, 52)\n            }\n            case 100000000000000000000000000000000000000000000000000000000000000000000000 {\n                result := mul(SCALE, 53)\n            }\n            case 1000000000000000000000000000000000000000000000000000000000000000000000000 {\n                result := mul(SCALE, 54)\n            }\n            case 10000000000000000000000000000000000000000000000000000000000000000000000000 {\n                result := mul(SCALE, 55)\n            }\n            case 100000000000000000000000000000000000000000000000000000000000000000000000000 {\n                result := mul(SCALE, 56)\n            }\n            case 1000000000000000000000000000000000000000000000000000000000000000000000000000 {\n                result := mul(SCALE, 57)\n            }\n            case 10000000000000000000000000000000000000000000000000000000000000000000000000000 {\n                result := mul(SCALE, 58)\n            }\n            case 100000000000000000000000000000000000000000000000000000000000000000000000000000 {\n                result := mul(SCALE, 59)\n            }\n            default { result := MAX_UD60x18 }\n        }\n\n        if (result == MAX_UD60x18) {\n            // Do the fixed-point division inline to save gas. The denominator is log2(10).\n            unchecked {\n                result = (log2(x) * SCALE) / 3_321_928_094_887_362_347;\n            }\n        }\n    }\n\n    /// @notice Calculates the binary logarithm of x.\n    ///\n    /// @dev Based on the iterative approximation algorithm.\n    /// https://en.wikipedia.org/wiki/Binary_logarithm#Iterative_approximation\n    ///\n    /// Requirements:\n    /// - x must be greater than or equal to SCALE, otherwise the result would be negative.\n    ///\n    /// Caveats:\n    /// - The results are nor perfectly accurate to the last decimal, due to the lossy precision of the iterative approximation.\n    ///\n    /// @param x The unsigned 60.18-decimal fixed-point number for which to calculate the binary logarithm.\n    /// @return result The binary logarithm as an unsigned 60.18-decimal fixed-point number.\n    function log2(uint256 x) internal pure returns (uint256 result) {\n        if (x < SCALE) {\n            revert PRBMathUD60x18__LogInputTooSmall(x);\n        }\n        unchecked {\n            // Calculate the integer part of the logarithm and add it to the result and finally calculate y = x * 2^(-n).\n            uint256 n = PRBMath.mostSignificantBit(x / SCALE);\n\n            // The integer part of the logarithm as an unsigned 60.18-decimal fixed-point number. The operation can't overflow\n            // because n is maximum 255 and SCALE is 1e18.\n            result = n * SCALE;\n\n            // This is y = x * 2^(-n).\n            uint256 y = x >> n;\n\n            // If y = 1, the fractional part is zero.\n            if (y == SCALE) {\n                return result;\n            }\n\n            // Calculate the fractional part via the iterative approximation.\n            // The \"delta >>= 1\" part is equivalent to \"delta /= 2\", but shifting bits is faster.\n            for (uint256 delta = HALF_SCALE; delta > 0; delta >>= 1) {\n                y = (y * y) / SCALE;\n\n                // Is y^2 > 2 and so in the range [2,4)?\n                if (y >= 2 * SCALE) {\n                    // Add the 2^(-m) factor to the logarithm.\n                    result += delta;\n\n                    // Corresponds to z/2 on Wikipedia.\n                    y >>= 1;\n                }\n            }\n        }\n    }\n\n    /// @notice Multiplies two unsigned 60.18-decimal fixed-point numbers together, returning a new unsigned 60.18-decimal\n    /// fixed-point number.\n    /// @dev See the documentation for the \"PRBMath.mulDivFixedPoint\" function.\n    /// @param x The multiplicand as an unsigned 60.18-decimal fixed-point number.\n    /// @param y The multiplier as an unsigned 60.18-decimal fixed-point number.\n    /// @return result The product as an unsigned 60.18-decimal fixed-point number.\n    function mul(uint256 x, uint256 y) internal pure returns (uint256 result) {\n        result = PRBMath.mulDivFixedPoint(x, y);\n    }\n\n    /// @notice Returns PI as an unsigned 60.18-decimal fixed-point number.\n    function pi() internal pure returns (uint256 result) {\n        result = 3_141_592_653_589_793_238;\n    }\n\n    /// @notice Raises x to the power of y.\n    ///\n    /// @dev Based on the insight that x^y = 2^(log2(x) * y).\n    ///\n    /// Requirements:\n    /// - All from \"exp2\", \"log2\" and \"mul\".\n    ///\n    /// Caveats:\n    /// - All from \"exp2\", \"log2\" and \"mul\".\n    /// - Assumes 0^0 is 1.\n    ///\n    /// @param x Number to raise to given power y, as an unsigned 60.18-decimal fixed-point number.\n    /// @param y Exponent to raise x to, as an unsigned 60.18-decimal fixed-point number.\n    /// @return result x raised to power y, as an unsigned 60.18-decimal fixed-point number.\n    function pow(uint256 x, uint256 y) internal pure returns (uint256 result) {\n        if (x == 0) {\n            result = y == 0 ? SCALE : uint256(0);\n        } else {\n            result = exp2(mul(log2(x), y));\n        }\n    }\n\n    /// @notice Raises x (unsigned 60.18-decimal fixed-point number) to the power of y (basic unsigned integer) using the\n    /// famous algorithm \"exponentiation by squaring\".\n    ///\n    /// @dev See https://en.wikipedia.org/wiki/Exponentiation_by_squaring\n    ///\n    /// Requirements:\n    /// - The result must fit within MAX_UD60x18.\n    ///\n    /// Caveats:\n    /// - All from \"mul\".\n    /// - Assumes 0^0 is 1.\n    ///\n    /// @param x The base as an unsigned 60.18-decimal fixed-point number.\n    /// @param y The exponent as an uint256.\n    /// @return result The result as an unsigned 60.18-decimal fixed-point number.\n    function powu(uint256 x, uint256 y) internal pure returns (uint256 result) {\n        // Calculate the first iteration of the loop in advance.\n        result = y & 1 > 0 ? x : SCALE;\n\n        // Equivalent to \"for(y /= 2; y > 0; y /= 2)\" but faster.\n        uint256 yAux = y;\n        for (yAux >>= 1; yAux > 0; yAux >>= 1) {\n            x = PRBMath.mulDivFixedPoint(x, x);\n\n            // Equivalent to \"y % 2 == 1\" but faster.\n            if (yAux & 1 > 0) {\n                result = PRBMath.mulDivFixedPoint(result, x);\n            }\n        }\n    }\n\n    /// @notice Returns 1 as an unsigned 60.18-decimal fixed-point number.\n    function scale() internal pure returns (uint256 result) {\n        result = SCALE;\n    }\n\n    /// @notice Calculates the square root of x, rounding down.\n    /// @dev Uses the Babylonian method https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method.\n    ///\n    /// Requirements:\n    /// - x must be less than MAX_UD60x18 / SCALE.\n    ///\n    /// @param x The unsigned 60.18-decimal fixed-point number for which to calculate the square root.\n    /// @return result The result as an unsigned 60.18-decimal fixed-point .\n    function sqrt(uint256 x) internal pure returns (uint256 result) {\n        unchecked {\n            if (x > MAX_UD60x18 / SCALE) {\n                revert PRBMathUD60x18__SqrtOverflow(x);\n            }\n            // Multiply x by the SCALE to account for the factor of SCALE that is picked up when multiplying two unsigned\n            // 60.18-decimal fixed-point numbers together (in this case, those two numbers are both the square root).\n            result = PRBMath.sqrt(x * SCALE);\n        }\n    }\n\n    /// @notice Converts a unsigned 60.18-decimal fixed-point number to basic integer form, rounding down in the process.\n    /// @param x The unsigned 60.18-decimal fixed-point number to convert.\n    /// @return result The same number in basic integer form.\n    function toUint(uint256 x) internal pure returns (uint256 result) {\n        unchecked {\n            result = x / SCALE;\n        }\n    }\n}\n"
      },
      "lib/balancer-v2-monorepo/pkg/interfaces/contracts/solidity-utils/openzeppelin/IERC20.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.7.0 <0.9.0;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20 {\n    /**\n     * @dev Returns the amount of tokens in existence.\n     */\n    function totalSupply() external view returns (uint256);\n\n    /**\n     * @dev Returns the amount of tokens owned by `account`.\n     */\n    function balanceOf(address account) external view returns (uint256);\n\n    /**\n     * @dev Moves `amount` tokens from the caller's account to `recipient`.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * Emits a {Transfer} event.\n     */\n    function transfer(address recipient, uint256 amount) 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 `amount` as the allowance of `spender` over the 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 amount) external returns (bool);\n\n    /**\n     * @dev Moves `amount` tokens from `sender` to `recipient` using the\n     * allowance mechanism. `amount` 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(\n        address sender,\n        address recipient,\n        uint256 amount\n    ) external returns (bool);\n\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"
      },
      "lib/balancer-v2-monorepo/pkg/interfaces/contracts/vault/IBasePool.sol": {
        "content": "// SPDX-License-Identifier: GPL-3.0-or-later\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n// GNU General Public License for more details.\n\n// You should have received a copy of the GNU General Public License\n// along with this program.  If not, see <http://www.gnu.org/licenses/>.\n\npragma solidity >=0.7.0 <0.9.0;\npragma experimental ABIEncoderV2;\n\nimport \"./IVault.sol\";\nimport \"./IPoolSwapStructs.sol\";\n\n/**\n * @dev Interface for adding and removing liquidity that all Pool contracts should implement. Note that this is not\n * the complete Pool contract interface, as it is missing the swap hooks. Pool contracts should also inherit from\n * either IGeneralPool or IMinimalSwapInfoPool\n */\ninterface IBasePool is IPoolSwapStructs {\n    /**\n     * @dev Called by the Vault when a user calls `IVault.joinPool` to add liquidity to this Pool. Returns how many of\n     * each registered token the user should provide, as well as the amount of protocol fees the Pool owes to the Vault.\n     * The Vault will then take tokens from `sender` and add them to the Pool's balances, as well as collect\n     * the reported amount in protocol fees, which the pool should calculate based on `protocolSwapFeePercentage`.\n     *\n     * Protocol fees are reported and charged on join events so that the Pool is free of debt whenever new users join.\n     *\n     * `sender` is the account performing the join (from which tokens will be withdrawn), and `recipient` is the account\n     * designated to receive any benefits (typically pool shares). `balances` contains the total balances\n     * for each token the Pool registered in the Vault, in the same order that `IVault.getPoolTokens` would return.\n     *\n     * `lastChangeBlock` is the last block in which *any* of the Pool's registered tokens last changed its total\n     * balance.\n     *\n     * `userData` contains any pool-specific instructions needed to perform the calculations, such as the type of\n     * join (e.g., proportional given an amount of pool shares, single-asset, multi-asset, etc.)\n     *\n     * Contracts implementing this function should check that the caller is indeed the Vault before performing any\n     * state-changing operations, such as minting pool shares.\n     */\n    function onJoinPool(\n        bytes32 poolId,\n        address sender,\n        address recipient,\n        uint256[] memory balances,\n        uint256 lastChangeBlock,\n        uint256 protocolSwapFeePercentage,\n        bytes memory userData\n    ) external returns (uint256[] memory amountsIn, uint256[] memory dueProtocolFeeAmounts);\n\n    /**\n     * @dev Called by the Vault when a user calls `IVault.exitPool` to remove liquidity from this Pool. Returns how many\n     * tokens the Vault should deduct from the Pool's balances, as well as the amount of protocol fees the Pool owes\n     * to the Vault. The Vault will then take tokens from the Pool's balances and send them to `recipient`,\n     * as well as collect the reported amount in protocol fees, which the Pool should calculate based on\n     * `protocolSwapFeePercentage`.\n     *\n     * Protocol fees are charged on exit events to guarantee that users exiting the Pool have paid their share.\n     *\n     * `sender` is the account performing the exit (typically the pool shareholder), and `recipient` is the account\n     * to which the Vault will send the proceeds. `balances` contains the total token balances for each token\n     * the Pool registered in the Vault, in the same order that `IVault.getPoolTokens` would return.\n     *\n     * `lastChangeBlock` is the last block in which *any* of the Pool's registered tokens last changed its total\n     * balance.\n     *\n     * `userData` contains any pool-specific instructions needed to perform the calculations, such as the type of\n     * exit (e.g., proportional given an amount of pool shares, single-asset, multi-asset, etc.)\n     *\n     * Contracts implementing this function should check that the caller is indeed the Vault before performing any\n     * state-changing operations, such as burning pool shares.\n     */\n    function onExitPool(\n        bytes32 poolId,\n        address sender,\n        address recipient,\n        uint256[] memory balances,\n        uint256 lastChangeBlock,\n        uint256 protocolSwapFeePercentage,\n        bytes memory userData\n    ) external returns (uint256[] memory amountsOut, uint256[] memory dueProtocolFeeAmounts);\n\n    /**\n     * @dev Returns this Pool's ID, used when interacting with the Vault (to e.g. join the Pool or swap with it).\n     */\n    function getPoolId() external view returns (bytes32);\n\n    /**\n     * @dev Returns the current swap fee percentage as a 18 decimal fixed point number, so e.g. 1e17 corresponds to a\n     * 10% swap fee.\n     */\n    function getSwapFeePercentage() external view returns (uint256);\n\n    /**\n     * @dev Returns the scaling factors of each of the Pool's tokens. This is an implementation detail that is typically\n     * not relevant for outside parties, but which might be useful for some types of Pools.\n     */\n    function getScalingFactors() external view returns (uint256[] memory);\n\n    function queryJoin(\n        bytes32 poolId,\n        address sender,\n        address recipient,\n        uint256[] memory balances,\n        uint256 lastChangeBlock,\n        uint256 protocolSwapFeePercentage,\n        bytes memory userData\n    ) external returns (uint256 bptOut, uint256[] memory amountsIn);\n\n    function queryExit(\n        bytes32 poolId,\n        address sender,\n        address recipient,\n        uint256[] memory balances,\n        uint256 lastChangeBlock,\n        uint256 protocolSwapFeePercentage,\n        bytes memory userData\n    ) external returns (uint256 bptIn, uint256[] memory amountsOut);\n}\n"
      },
      "lib/balancer-v2-monorepo/pkg/interfaces/contracts/solidity-utils/helpers/BalancerErrors.sol": {
        "content": "// SPDX-License-Identifier: GPL-3.0-or-later\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n// GNU General Public License for more details.\n\n// You should have received a copy of the GNU General Public License\n// along with this program.  If not, see <http://www.gnu.org/licenses/>.\n\npragma solidity >=0.7.1 <0.9.0;\n\n// solhint-disable\n\n/**\n * @dev Reverts if `condition` is false, with a revert reason containing `errorCode`. Only codes up to 999 are\n * supported.\n * Uses the default 'BAL' prefix for the error code\n */\nfunction _require(bool condition, uint256 errorCode) pure {\n    if (!condition) _revert(errorCode);\n}\n\n/**\n * @dev Reverts if `condition` is false, with a revert reason containing `errorCode`. Only codes up to 999 are\n * supported.\n */\nfunction _require(\n    bool condition,\n    uint256 errorCode,\n    bytes3 prefix\n) pure {\n    if (!condition) _revert(errorCode, prefix);\n}\n\n/**\n * @dev Reverts with a revert reason containing `errorCode`. Only codes up to 999 are supported.\n * Uses the default 'BAL' prefix for the error code\n */\nfunction _revert(uint256 errorCode) pure {\n    _revert(errorCode, 0x42414c); // This is the raw byte representation of \"BAL\"\n}\n\n/**\n * @dev Reverts with a revert reason containing `errorCode`. Only codes up to 999 are supported.\n */\nfunction _revert(uint256 errorCode, bytes3 prefix) pure {\n    uint256 prefixUint = uint256(uint24(prefix));\n    // We're going to dynamically create a revert string based on the error code, with the following format:\n    // 'BAL#{errorCode}'\n    // where the code is left-padded with zeroes to three digits (so they range from 000 to 999).\n    //\n    // We don't have revert strings embedded in the contract to save bytecode size: it takes much less space to store a\n    // number (8 to 16 bits) than the individual string characters.\n    //\n    // The dynamic string creation algorithm that follows could be implemented in Solidity, but assembly allows for a\n    // much denser implementation, again saving bytecode size. Given this function unconditionally reverts, this is a\n    // safe place to rely on it without worrying about how its usage might affect e.g. memory contents.\n    assembly {\n        // First, we need to compute the ASCII representation of the error code. We assume that it is in the 0-999\n        // range, so we only need to convert three digits. To convert the digits to ASCII, we add 0x30, the value for\n        // the '0' character.\n\n        let units := add(mod(errorCode, 10), 0x30)\n\n        errorCode := div(errorCode, 10)\n        let tenths := add(mod(errorCode, 10), 0x30)\n\n        errorCode := div(errorCode, 10)\n        let hundreds := add(mod(errorCode, 10), 0x30)\n\n        // With the individual characters, we can now construct the full string.\n        // We first append the '#' character (0x23) to the prefix. In the case of 'BAL', it results in 0x42414c23 ('BAL#')\n        // Then, we shift this by 24 (to provide space for the 3 bytes of the error code), and add the\n        // characters to it, each shifted by a multiple of 8.\n        // The revert reason is then shifted left by 200 bits (256 minus the length of the string, 7 characters * 8 bits\n        // per character = 56) to locate it in the most significant part of the 256 slot (the beginning of a byte\n        // array).\n        let formattedPrefix := shl(24, add(0x23, shl(8, prefixUint)))\n\n        let revertReason := shl(200, add(formattedPrefix, add(add(units, shl(8, tenths)), shl(16, hundreds))))\n\n        // We can now encode the reason in memory, which can be safely overwritten as we're about to revert. The encoded\n        // message will have the following layout:\n        // [ revert reason identifier ] [ string location offset ] [ string length ] [ string contents ]\n\n        // The Solidity revert reason identifier is 0x08c739a0, the function selector of the Error(string) function. We\n        // also write zeroes to the next 28 bytes of memory, but those are about to be overwritten.\n        mstore(0x0, 0x08c379a000000000000000000000000000000000000000000000000000000000)\n        // Next is the offset to the location of the string, which will be placed immediately after (20 bytes away).\n        mstore(0x04, 0x0000000000000000000000000000000000000000000000000000000000000020)\n        // The string length is fixed: 7 characters.\n        mstore(0x24, 7)\n        // Finally, the string itself is stored.\n        mstore(0x44, revertReason)\n\n        // Even if the string is only 7 bytes long, we need to return a full 32 byte slot containing it. The length of\n        // the encoded message is therefore 4 + 32 + 32 + 32 = 100.\n        revert(0, 100)\n    }\n}\n\nlibrary Errors {\n    // Math\n    uint256 internal constant ADD_OVERFLOW = 0;\n    uint256 internal constant SUB_OVERFLOW = 1;\n    uint256 internal constant SUB_UNDERFLOW = 2;\n    uint256 internal constant MUL_OVERFLOW = 3;\n    uint256 internal constant ZERO_DIVISION = 4;\n    uint256 internal constant DIV_INTERNAL = 5;\n    uint256 internal constant X_OUT_OF_BOUNDS = 6;\n    uint256 internal constant Y_OUT_OF_BOUNDS = 7;\n    uint256 internal constant PRODUCT_OUT_OF_BOUNDS = 8;\n    uint256 internal constant INVALID_EXPONENT = 9;\n\n    // Input\n    uint256 internal constant OUT_OF_BOUNDS = 100;\n    uint256 internal constant UNSORTED_ARRAY = 101;\n    uint256 internal constant UNSORTED_TOKENS = 102;\n    uint256 internal constant INPUT_LENGTH_MISMATCH = 103;\n    uint256 internal constant ZERO_TOKEN = 104;\n    uint256 internal constant INSUFFICIENT_DATA = 105;\n\n    // Shared pools\n    uint256 internal constant MIN_TOKENS = 200;\n    uint256 internal constant MAX_TOKENS = 201;\n    uint256 internal constant MAX_SWAP_FEE_PERCENTAGE = 202;\n    uint256 internal constant MIN_SWAP_FEE_PERCENTAGE = 203;\n    uint256 internal constant MINIMUM_BPT = 204;\n    uint256 internal constant CALLER_NOT_VAULT = 205;\n    uint256 internal constant UNINITIALIZED = 206;\n    uint256 internal constant BPT_IN_MAX_AMOUNT = 207;\n    uint256 internal constant BPT_OUT_MIN_AMOUNT = 208;\n    uint256 internal constant EXPIRED_PERMIT = 209;\n    uint256 internal constant NOT_TWO_TOKENS = 210;\n    uint256 internal constant DISABLED = 211;\n\n    // Pools\n    uint256 internal constant MIN_AMP = 300;\n    uint256 internal constant MAX_AMP = 301;\n    uint256 internal constant MIN_WEIGHT = 302;\n    uint256 internal constant MAX_STABLE_TOKENS = 303;\n    uint256 internal constant MAX_IN_RATIO = 304;\n    uint256 internal constant MAX_OUT_RATIO = 305;\n    uint256 internal constant MIN_BPT_IN_FOR_TOKEN_OUT = 306;\n    uint256 internal constant MAX_OUT_BPT_FOR_TOKEN_IN = 307;\n    uint256 internal constant NORMALIZED_WEIGHT_INVARIANT = 308;\n    uint256 internal constant INVALID_TOKEN = 309;\n    uint256 internal constant UNHANDLED_JOIN_KIND = 310;\n    uint256 internal constant ZERO_INVARIANT = 311;\n    uint256 internal constant ORACLE_INVALID_SECONDS_QUERY = 312;\n    uint256 internal constant ORACLE_NOT_INITIALIZED = 313;\n    uint256 internal constant ORACLE_QUERY_TOO_OLD = 314;\n    uint256 internal constant ORACLE_INVALID_INDEX = 315;\n    uint256 internal constant ORACLE_BAD_SECS = 316;\n    uint256 internal constant AMP_END_TIME_TOO_CLOSE = 317;\n    uint256 internal constant AMP_ONGOING_UPDATE = 318;\n    uint256 internal constant AMP_RATE_TOO_HIGH = 319;\n    uint256 internal constant AMP_NO_ONGOING_UPDATE = 320;\n    uint256 internal constant STABLE_INVARIANT_DIDNT_CONVERGE = 321;\n    uint256 internal constant STABLE_GET_BALANCE_DIDNT_CONVERGE = 322;\n    uint256 internal constant RELAYER_NOT_CONTRACT = 323;\n    uint256 internal constant BASE_POOL_RELAYER_NOT_CALLED = 324;\n    uint256 internal constant REBALANCING_RELAYER_REENTERED = 325;\n    uint256 internal constant GRADUAL_UPDATE_TIME_TRAVEL = 326;\n    uint256 internal constant SWAPS_DISABLED = 327;\n    uint256 internal constant CALLER_IS_NOT_LBP_OWNER = 328;\n    uint256 internal constant PRICE_RATE_OVERFLOW = 329;\n    uint256 internal constant INVALID_JOIN_EXIT_KIND_WHILE_SWAPS_DISABLED = 330;\n    uint256 internal constant WEIGHT_CHANGE_TOO_FAST = 331;\n    uint256 internal constant LOWER_GREATER_THAN_UPPER_TARGET = 332;\n    uint256 internal constant UPPER_TARGET_TOO_HIGH = 333;\n    uint256 internal constant UNHANDLED_BY_LINEAR_POOL = 334;\n    uint256 internal constant OUT_OF_TARGET_RANGE = 335;\n    uint256 internal constant UNHANDLED_EXIT_KIND = 336;\n    uint256 internal constant UNAUTHORIZED_EXIT = 337;\n    uint256 internal constant MAX_MANAGEMENT_SWAP_FEE_PERCENTAGE = 338;\n    uint256 internal constant UNHANDLED_BY_MANAGED_POOL = 339;\n    uint256 internal constant UNHANDLED_BY_PHANTOM_POOL = 340;\n    uint256 internal constant TOKEN_DOES_NOT_HAVE_RATE_PROVIDER = 341;\n    uint256 internal constant INVALID_INITIALIZATION = 342;\n    uint256 internal constant OUT_OF_NEW_TARGET_RANGE = 343;\n    uint256 internal constant FEATURE_DISABLED = 344;\n    uint256 internal constant UNINITIALIZED_POOL_CONTROLLER = 345;\n    uint256 internal constant SET_SWAP_FEE_DURING_FEE_CHANGE = 346;\n    uint256 internal constant SET_SWAP_FEE_PENDING_FEE_CHANGE = 347;\n    uint256 internal constant CHANGE_TOKENS_DURING_WEIGHT_CHANGE = 348;\n    uint256 internal constant CHANGE_TOKENS_PENDING_WEIGHT_CHANGE = 349;\n    uint256 internal constant MAX_WEIGHT = 350;\n    uint256 internal constant UNAUTHORIZED_JOIN = 351;\n    uint256 internal constant MAX_MANAGEMENT_AUM_FEE_PERCENTAGE = 352;\n    uint256 internal constant FRACTIONAL_TARGET = 353;\n    uint256 internal constant ADD_OR_REMOVE_BPT = 354;\n    uint256 internal constant INVALID_CIRCUIT_BREAKER_BOUNDS = 355;\n    uint256 internal constant CIRCUIT_BREAKER_TRIPPED = 356;\n    uint256 internal constant MALICIOUS_QUERY_REVERT = 357;\n    uint256 internal constant JOINS_EXITS_DISABLED = 358;\n\n    // Lib\n    uint256 internal constant REENTRANCY = 400;\n    uint256 internal constant SENDER_NOT_ALLOWED = 401;\n    uint256 internal constant PAUSED = 402;\n    uint256 internal constant PAUSE_WINDOW_EXPIRED = 403;\n    uint256 internal constant MAX_PAUSE_WINDOW_DURATION = 404;\n    uint256 internal constant MAX_BUFFER_PERIOD_DURATION = 405;\n    uint256 internal constant INSUFFICIENT_BALANCE = 406;\n    uint256 internal constant INSUFFICIENT_ALLOWANCE = 407;\n    uint256 internal constant ERC20_TRANSFER_FROM_ZERO_ADDRESS = 408;\n    uint256 internal constant ERC20_TRANSFER_TO_ZERO_ADDRESS = 409;\n    uint256 internal constant ERC20_MINT_TO_ZERO_ADDRESS = 410;\n    uint256 internal constant ERC20_BURN_FROM_ZERO_ADDRESS = 411;\n    uint256 internal constant ERC20_APPROVE_FROM_ZERO_ADDRESS = 412;\n    uint256 internal constant ERC20_APPROVE_TO_ZERO_ADDRESS = 413;\n    uint256 internal constant ERC20_TRANSFER_EXCEEDS_ALLOWANCE = 414;\n    uint256 internal constant ERC20_DECREASED_ALLOWANCE_BELOW_ZERO = 415;\n    uint256 internal constant ERC20_TRANSFER_EXCEEDS_BALANCE = 416;\n    uint256 internal constant ERC20_BURN_EXCEEDS_ALLOWANCE = 417;\n    uint256 internal constant SAFE_ERC20_CALL_FAILED = 418;\n    uint256 internal constant ADDRESS_INSUFFICIENT_BALANCE = 419;\n    uint256 internal constant ADDRESS_CANNOT_SEND_VALUE = 420;\n    uint256 internal constant SAFE_CAST_VALUE_CANT_FIT_INT256 = 421;\n    uint256 internal constant GRANT_SENDER_NOT_ADMIN = 422;\n    uint256 internal constant REVOKE_SENDER_NOT_ADMIN = 423;\n    uint256 internal constant RENOUNCE_SENDER_NOT_ALLOWED = 424;\n    uint256 internal constant BUFFER_PERIOD_EXPIRED = 425;\n    uint256 internal constant CALLER_IS_NOT_OWNER = 426;\n    uint256 internal constant NEW_OWNER_IS_ZERO = 427;\n    uint256 internal constant CODE_DEPLOYMENT_FAILED = 428;\n    uint256 internal constant CALL_TO_NON_CONTRACT = 429;\n    uint256 internal constant LOW_LEVEL_CALL_FAILED = 430;\n    uint256 internal constant NOT_PAUSED = 431;\n    uint256 internal constant ADDRESS_ALREADY_ALLOWLISTED = 432;\n    uint256 internal constant ADDRESS_NOT_ALLOWLISTED = 433;\n    uint256 internal constant ERC20_BURN_EXCEEDS_BALANCE = 434;\n    uint256 internal constant INVALID_OPERATION = 435;\n    uint256 internal constant CODEC_OVERFLOW = 436;\n    uint256 internal constant IN_RECOVERY_MODE = 437;\n    uint256 internal constant NOT_IN_RECOVERY_MODE = 438;\n    uint256 internal constant INDUCED_FAILURE = 439;\n    uint256 internal constant EXPIRED_SIGNATURE = 440;\n    uint256 internal constant MALFORMED_SIGNATURE = 441;\n    uint256 internal constant SAFE_CAST_VALUE_CANT_FIT_UINT64 = 442;\n    uint256 internal constant UNHANDLED_FEE_TYPE = 443;\n    uint256 internal constant BURN_FROM_ZERO = 444;\n\n    // Vault\n    uint256 internal constant INVALID_POOL_ID = 500;\n    uint256 internal constant CALLER_NOT_POOL = 501;\n    uint256 internal constant SENDER_NOT_ASSET_MANAGER = 502;\n    uint256 internal constant USER_DOESNT_ALLOW_RELAYER = 503;\n    uint256 internal constant INVALID_SIGNATURE = 504;\n    uint256 internal constant EXIT_BELOW_MIN = 505;\n    uint256 internal constant JOIN_ABOVE_MAX = 506;\n    uint256 internal constant SWAP_LIMIT = 507;\n    uint256 internal constant SWAP_DEADLINE = 508;\n    uint256 internal constant CANNOT_SWAP_SAME_TOKEN = 509;\n    uint256 internal constant UNKNOWN_AMOUNT_IN_FIRST_SWAP = 510;\n    uint256 internal constant MALCONSTRUCTED_MULTIHOP_SWAP = 511;\n    uint256 internal constant INTERNAL_BALANCE_OVERFLOW = 512;\n    uint256 internal constant INSUFFICIENT_INTERNAL_BALANCE = 513;\n    uint256 internal constant INVALID_ETH_INTERNAL_BALANCE = 514;\n    uint256 internal constant INVALID_POST_LOAN_BALANCE = 515;\n    uint256 internal constant INSUFFICIENT_ETH = 516;\n    uint256 internal constant UNALLOCATED_ETH = 517;\n    uint256 internal constant ETH_TRANSFER = 518;\n    uint256 internal constant CANNOT_USE_ETH_SENTINEL = 519;\n    uint256 internal constant TOKENS_MISMATCH = 520;\n    uint256 internal constant TOKEN_NOT_REGISTERED = 521;\n    uint256 internal constant TOKEN_ALREADY_REGISTERED = 522;\n    uint256 internal constant TOKENS_ALREADY_SET = 523;\n    uint256 internal constant TOKENS_LENGTH_MUST_BE_2 = 524;\n    uint256 internal constant NONZERO_TOKEN_BALANCE = 525;\n    uint256 internal constant BALANCE_TOTAL_OVERFLOW = 526;\n    uint256 internal constant POOL_NO_TOKENS = 527;\n    uint256 internal constant INSUFFICIENT_FLASH_LOAN_BALANCE = 528;\n\n    // Fees\n    uint256 internal constant SWAP_FEE_PERCENTAGE_TOO_HIGH = 600;\n    uint256 internal constant FLASH_LOAN_FEE_PERCENTAGE_TOO_HIGH = 601;\n    uint256 internal constant INSUFFICIENT_FLASH_LOAN_FEE_AMOUNT = 602;\n    uint256 internal constant AUM_FEE_PERCENTAGE_TOO_HIGH = 603;\n\n    // FeeSplitter\n    uint256 internal constant SPLITTER_FEE_PERCENTAGE_TOO_HIGH = 700;\n\n    // Misc\n    uint256 internal constant UNIMPLEMENTED = 998;\n    uint256 internal constant SHOULD_NOT_HAPPEN = 999;\n}\n"
      },
      "lib/balancer-v2-monorepo/pkg/interfaces/contracts/solidity-utils/helpers/IAuthentication.sol": {
        "content": "// SPDX-License-Identifier: GPL-3.0-or-later\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n// GNU General Public License for more details.\n\n// You should have received a copy of the GNU General Public License\n// along with this program.  If not, see <http://www.gnu.org/licenses/>.\n\npragma solidity >=0.7.0 <0.9.0;\n\ninterface IAuthentication {\n    /**\n     * @dev Returns the action identifier associated with the external function described by `selector`.\n     */\n    function getActionId(bytes4 selector) external view returns (bytes32);\n}\n"
      },
      "lib/balancer-v2-monorepo/pkg/interfaces/contracts/solidity-utils/helpers/ISignaturesValidator.sol": {
        "content": "// SPDX-License-Identifier: GPL-3.0-or-later\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n// GNU General Public License for more details.\n\n// You should have received a copy of the GNU General Public License\n// along with this program.  If not, see <http://www.gnu.org/licenses/>.\n\npragma solidity >=0.7.0 <0.9.0;\n\n/**\n * @dev Interface for the SignatureValidator helper, used to support meta-transactions.\n */\ninterface ISignaturesValidator {\n    /**\n     * @dev Returns the EIP712 domain separator.\n     */\n    function getDomainSeparator() external view returns (bytes32);\n\n    /**\n     * @dev Returns the next nonce used by an address to sign messages.\n     */\n    function getNextNonce(address user) external view returns (uint256);\n}\n"
      },
      "lib/balancer-v2-monorepo/pkg/interfaces/contracts/solidity-utils/helpers/ITemporarilyPausable.sol": {
        "content": "// SPDX-License-Identifier: GPL-3.0-or-later\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n// GNU General Public License for more details.\n\n// You should have received a copy of the GNU General Public License\n// along with this program.  If not, see <http://www.gnu.org/licenses/>.\n\npragma solidity >=0.7.0 <0.9.0;\n\n/**\n * @dev Interface for the TemporarilyPausable helper.\n */\ninterface ITemporarilyPausable {\n    /**\n     * @dev Emitted every time the pause state changes by `_setPaused`.\n     */\n    event PausedStateChanged(bool paused);\n\n    /**\n     * @dev Returns the current paused state.\n     */\n    function getPausedState()\n        external\n        view\n        returns (\n            bool paused,\n            uint256 pauseWindowEndTime,\n            uint256 bufferPeriodEndTime\n        );\n}\n"
      },
      "lib/balancer-v2-monorepo/pkg/interfaces/contracts/solidity-utils/misc/IWETH.sol": {
        "content": "// SPDX-License-Identifier: GPL-3.0-or-later\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n// GNU General Public License for more details.\n\n// You should have received a copy of the GNU General Public License\n// along with this program.  If not, see <http://www.gnu.org/licenses/>.\n\npragma solidity >=0.7.0 <0.9.0;\n\nimport \"../openzeppelin/IERC20.sol\";\n\n/**\n * @dev Interface for WETH9.\n * See https://github.com/gnosis/canonical-weth/blob/0dd1ea3e295eef916d0c6223ec63141137d22d67/contracts/WETH9.sol\n */\ninterface IWETH is IERC20 {\n    function deposit() external payable;\n\n    function withdraw(uint256 amount) external;\n}\n"
      },
      "lib/balancer-v2-monorepo/pkg/interfaces/contracts/vault/IAuthorizer.sol": {
        "content": "// SPDX-License-Identifier: GPL-3.0-or-later\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n// GNU General Public License for more details.\n\n// You should have received a copy of the GNU General Public License\n// along with this program.  If not, see <http://www.gnu.org/licenses/>.\n\npragma solidity >=0.7.0 <0.9.0;\n\ninterface IAuthorizer {\n    /**\n     * @dev Returns true if `account` can perform the action described by `actionId` in the contract `where`.\n     */\n    function canPerform(\n        bytes32 actionId,\n        address account,\n        address where\n    ) external view returns (bool);\n}\n"
      },
      "lib/balancer-v2-monorepo/pkg/interfaces/contracts/vault/IFlashLoanRecipient.sol": {
        "content": "// SPDX-License-Identifier: GPL-3.0-or-later\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n// GNU General Public License for more details.\n\n// You should have received a copy of the GNU General Public License\n// along with this program.  If not, see <http://www.gnu.org/licenses/>.\n\npragma solidity >=0.7.0 <0.9.0;\n\n// Inspired by Aave Protocol's IFlashLoanReceiver.\n\nimport \"../solidity-utils/openzeppelin/IERC20.sol\";\n\ninterface IFlashLoanRecipient {\n    /**\n     * @dev When `flashLoan` is called on the Vault, it invokes the `receiveFlashLoan` hook on the recipient.\n     *\n     * At the time of the call, the Vault will have transferred `amounts` for `tokens` to the recipient. Before this\n     * call returns, the recipient must have transferred `amounts` plus `feeAmounts` for each token back to the\n     * Vault, or else the entire flash loan will revert.\n     *\n     * `userData` is the same value passed in the `IVault.flashLoan` call.\n     */\n    function receiveFlashLoan(\n        IERC20[] memory tokens,\n        uint256[] memory amounts,\n        uint256[] memory feeAmounts,\n        bytes memory userData\n    ) external;\n}\n"
      },
      "lib/balancer-v2-monorepo/pkg/interfaces/contracts/vault/IProtocolFeesCollector.sol": {
        "content": "// SPDX-License-Identifier: GPL-3.0-or-later\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n// GNU General Public License for more details.\n\n// You should have received a copy of the GNU General Public License\n// along with this program.  If not, see <http://www.gnu.org/licenses/>.\n\npragma solidity >=0.7.0 <0.9.0;\npragma experimental ABIEncoderV2;\n\nimport \"../solidity-utils/openzeppelin/IERC20.sol\";\n\nimport \"./IVault.sol\";\nimport \"./IAuthorizer.sol\";\n\ninterface IProtocolFeesCollector {\n    event SwapFeePercentageChanged(uint256 newSwapFeePercentage);\n    event FlashLoanFeePercentageChanged(uint256 newFlashLoanFeePercentage);\n\n    function withdrawCollectedFees(\n        IERC20[] calldata tokens,\n        uint256[] calldata amounts,\n        address recipient\n    ) external;\n\n    function setSwapFeePercentage(uint256 newSwapFeePercentage) external;\n\n    function setFlashLoanFeePercentage(uint256 newFlashLoanFeePercentage) external;\n\n    function getSwapFeePercentage() external view returns (uint256);\n\n    function getFlashLoanFeePercentage() external view returns (uint256);\n\n    function getCollectedFeeAmounts(IERC20[] memory tokens) external view returns (uint256[] memory feeAmounts);\n\n    function getAuthorizer() external view returns (IAuthorizer);\n\n    function vault() external view returns (IVault);\n}\n"
      },
      "src/utils/PRBMath.sol": {
        "content": "// SPDX-License-Identifier: Unlicense\npragma solidity >=0.8.4;\n\n/// @notice Emitted when the result overflows uint256.\nerror PRBMath__MulDivFixedPointOverflow(uint256 prod1);\n/// @notice Emitted when the result overflows uint256.\nerror PRBMath__MulDivOverflow(uint256 prod1, uint256 denominator);\n\n/// @notice Emitted when one of the inputs is type(int256).min.\nerror PRBMath__MulDivSignedInputTooSmall();\n\n/// @notice Emitted when the intermediary absolute result overflows int256.\nerror PRBMath__MulDivSignedOverflow(uint256 rAbs);\n\n/// @notice Emitted when the input is MIN_SD59x18.\nerror PRBMathSD59x18__AbsInputTooSmall();\n\n/// @notice Emitted when ceiling a number overflows SD59x18.\nerror PRBMathSD59x18__CeilOverflow(int256 x);\n\n/// @notice Emitted when one of the inputs is MIN_SD59x18.\nerror PRBMathSD59x18__DivInputTooSmall();\n\n/// @notice Emitted when one of the intermediary unsigned results overflows SD59x18.\nerror PRBMathSD59x18__DivOverflow(uint256 rAbs);\n\n/// @notice Emitted when the input is greater than 133.084258667509499441.\nerror PRBMathSD59x18__ExpInputTooBig(int256 x);\n\n/// @notice Emitted when the input is greater than 192.\nerror PRBMathSD59x18__Exp2InputTooBig(int256 x);\n\n/// @notice Emitted when flooring a number underflows SD59x18.\nerror PRBMathSD59x18__FloorUnderflow(int256 x);\n\n/// @notice Emitted when converting a basic integer to the fixed-point format overflows SD59x18.\nerror PRBMathSD59x18__FromIntOverflow(int256 x);\n\n/// @notice Emitted when converting a basic integer to the fixed-point format underflows SD59x18.\nerror PRBMathSD59x18__FromIntUnderflow(int256 x);\n\n/// @notice Emitted when the product of the inputs is negative.\nerror PRBMathSD59x18__GmNegativeProduct(int256 x, int256 y);\n\n/// @notice Emitted when multiplying the inputs overflows SD59x18.\nerror PRBMathSD59x18__GmOverflow(int256 x, int256 y);\n\n/// @notice Emitted when the input is less than or equal to zero.\nerror PRBMathSD59x18__LogInputTooSmall(int256 x);\n\n/// @notice Emitted when one of the inputs is MIN_SD59x18.\nerror PRBMathSD59x18__MulInputTooSmall();\n\n/// @notice Emitted when the intermediary absolute result overflows SD59x18.\nerror PRBMathSD59x18__MulOverflow(uint256 rAbs);\n\n/// @notice Emitted when the intermediary absolute result overflows SD59x18.\nerror PRBMathSD59x18__PowuOverflow(uint256 rAbs);\n\n/// @notice Emitted when the input is negative.\nerror PRBMathSD59x18__SqrtNegativeInput(int256 x);\n\n/// @notice Emitted when the calculating the square root overflows SD59x18.\nerror PRBMathSD59x18__SqrtOverflow(int256 x);\n\n/// @notice Emitted when addition overflows UD60x18.\nerror PRBMathUD60x18__AddOverflow(uint256 x, uint256 y);\n\n/// @notice Emitted when ceiling a number overflows UD60x18.\nerror PRBMathUD60x18__CeilOverflow(uint256 x);\n\n/// @notice Emitted when the input is greater than 133.084258667509499441.\nerror PRBMathUD60x18__ExpInputTooBig(uint256 x);\n\n/// @notice Emitted when the input is greater than 192.\nerror PRBMathUD60x18__Exp2InputTooBig(uint256 x);\n\n/// @notice Emitted when converting a basic integer to the fixed-point format format overflows UD60x18.\nerror PRBMathUD60x18__FromUintOverflow(uint256 x);\n\n/// @notice Emitted when multiplying the inputs overflows UD60x18.\nerror PRBMathUD60x18__GmOverflow(uint256 x, uint256 y);\n\n/// @notice Emitted when the input is less than 1.\nerror PRBMathUD60x18__LogInputTooSmall(uint256 x);\n\n/// @notice Emitted when the calculating the square root overflows UD60x18.\nerror PRBMathUD60x18__SqrtOverflow(uint256 x);\n\n/// @notice Emitted when subtraction underflows UD60x18.\nerror PRBMathUD60x18__SubUnderflow(uint256 x, uint256 y);\n\n/// @dev Common mathematical functions used in both PRBMathSD59x18 and PRBMathUD60x18. Note that this shared library\n/// does not always assume the signed 59.18-decimal fixed-point or the unsigned 60.18-decimal fixed-point\n/// representation. When it does not, it is explicitly mentioned in the NatSpec documentation.\nlibrary PRBMath {\n    /// STRUCTS ///\n\n    struct SD59x18 {\n        int256 value;\n    }\n\n    struct UD60x18 {\n        uint256 value;\n    }\n\n    /// STORAGE ///\n\n    /// @dev How many trailing decimals can be represented.\n    uint256 internal constant SCALE = 1e18;\n\n    /// @dev Largest power of two divisor of SCALE.\n    uint256 internal constant SCALE_LPOTD = 262_144;\n\n    /// @dev SCALE inverted mod 2^256.\n    uint256 internal constant SCALE_INVERSE =\n        78_156_646_155_174_841_979_727_994_598_816_262_306_175_212_592_076_161_876_661_508_869_554_232_690_281;\n\n    /// FUNCTIONS ///\n\n    /// @notice Calculates the binary exponent of x using the binary fraction method.\n    /// @dev Has to use 192.64-bit fixed-point numbers.\n    /// See https://ethereum.stackexchange.com/a/96594/24693.\n    /// @param x The exponent as an unsigned 192.64-bit fixed-point number.\n    /// @return result The result as an unsigned 60.18-decimal fixed-point number.\n    function exp2(uint256 x) internal pure returns (uint256 result) {\n        unchecked {\n            // Start from 0.5 in the 192.64-bit fixed-point format.\n            result = 0x800000000000000000000000000000000000000000000000;\n\n            // Multiply the result by root(2, 2^-i) when the bit at position i is 1. None of the intermediary results overflows\n            // because the initial result is 2^191 and all magic factors are less than 2^65.\n            if (x & 0x8000000000000000 > 0) {\n                result = (result * 0x16A09E667F3BCC909) >> 64;\n            }\n            if (x & 0x4000000000000000 > 0) {\n                result = (result * 0x1306FE0A31B7152DF) >> 64;\n            }\n            if (x & 0x2000000000000000 > 0) {\n                result = (result * 0x1172B83C7D517ADCE) >> 64;\n            }\n            if (x & 0x1000000000000000 > 0) {\n                result = (result * 0x10B5586CF9890F62A) >> 64;\n            }\n            if (x & 0x800000000000000 > 0) {\n                result = (result * 0x1059B0D31585743AE) >> 64;\n            }\n            if (x & 0x400000000000000 > 0) {\n                result = (result * 0x102C9A3E778060EE7) >> 64;\n            }\n            if (x & 0x200000000000000 > 0) {\n                result = (result * 0x10163DA9FB33356D8) >> 64;\n            }\n            if (x & 0x100000000000000 > 0) {\n                result = (result * 0x100B1AFA5ABCBED61) >> 64;\n            }\n            if (x & 0x80000000000000 > 0) {\n                result = (result * 0x10058C86DA1C09EA2) >> 64;\n            }\n            if (x & 0x40000000000000 > 0) {\n                result = (result * 0x1002C605E2E8CEC50) >> 64;\n            }\n            if (x & 0x20000000000000 > 0) {\n                result = (result * 0x100162F3904051FA1) >> 64;\n            }\n            if (x & 0x10000000000000 > 0) {\n                result = (result * 0x1000B175EFFDC76BA) >> 64;\n            }\n            if (x & 0x8000000000000 > 0) {\n                result = (result * 0x100058BA01FB9F96D) >> 64;\n            }\n            if (x & 0x4000000000000 > 0) {\n                result = (result * 0x10002C5CC37DA9492) >> 64;\n            }\n            if (x & 0x2000000000000 > 0) {\n                result = (result * 0x1000162E525EE0547) >> 64;\n            }\n            if (x & 0x1000000000000 > 0) {\n                result = (result * 0x10000B17255775C04) >> 64;\n            }\n            if (x & 0x800000000000 > 0) {\n                result = (result * 0x1000058B91B5BC9AE) >> 64;\n            }\n            if (x & 0x400000000000 > 0) {\n                result = (result * 0x100002C5C89D5EC6D) >> 64;\n            }\n            if (x & 0x200000000000 > 0) {\n                result = (result * 0x10000162E43F4F831) >> 64;\n            }\n            if (x & 0x100000000000 > 0) {\n                result = (result * 0x100000B1721BCFC9A) >> 64;\n            }\n            if (x & 0x80000000000 > 0) {\n                result = (result * 0x10000058B90CF1E6E) >> 64;\n            }\n            if (x & 0x40000000000 > 0) {\n                result = (result * 0x1000002C5C863B73F) >> 64;\n            }\n            if (x & 0x20000000000 > 0) {\n                result = (result * 0x100000162E430E5A2) >> 64;\n            }\n            if (x & 0x10000000000 > 0) {\n                result = (result * 0x1000000B172183551) >> 64;\n            }\n            if (x & 0x8000000000 > 0) {\n                result = (result * 0x100000058B90C0B49) >> 64;\n            }\n            if (x & 0x4000000000 > 0) {\n                result = (result * 0x10000002C5C8601CC) >> 64;\n            }\n            if (x & 0x2000000000 > 0) {\n                result = (result * 0x1000000162E42FFF0) >> 64;\n            }\n            if (x & 0x1000000000 > 0) {\n                result = (result * 0x10000000B17217FBB) >> 64;\n            }\n            if (x & 0x800000000 > 0) {\n                result = (result * 0x1000000058B90BFCE) >> 64;\n            }\n            if (x & 0x400000000 > 0) {\n                result = (result * 0x100000002C5C85FE3) >> 64;\n            }\n            if (x & 0x200000000 > 0) {\n                result = (result * 0x10000000162E42FF1) >> 64;\n            }\n            if (x & 0x100000000 > 0) {\n                result = (result * 0x100000000B17217F8) >> 64;\n            }\n            if (x & 0x80000000 > 0) {\n                result = (result * 0x10000000058B90BFC) >> 64;\n            }\n            if (x & 0x40000000 > 0) {\n                result = (result * 0x1000000002C5C85FE) >> 64;\n            }\n            if (x & 0x20000000 > 0) {\n                result = (result * 0x100000000162E42FF) >> 64;\n            }\n            if (x & 0x10000000 > 0) {\n                result = (result * 0x1000000000B17217F) >> 64;\n            }\n            if (x & 0x8000000 > 0) {\n                result = (result * 0x100000000058B90C0) >> 64;\n            }\n            if (x & 0x4000000 > 0) {\n                result = (result * 0x10000000002C5C860) >> 64;\n            }\n            if (x & 0x2000000 > 0) {\n                result = (result * 0x1000000000162E430) >> 64;\n            }\n            if (x & 0x1000000 > 0) {\n                result = (result * 0x10000000000B17218) >> 64;\n            }\n            if (x & 0x800000 > 0) {\n                result = (result * 0x1000000000058B90C) >> 64;\n            }\n            if (x & 0x400000 > 0) {\n                result = (result * 0x100000000002C5C86) >> 64;\n            }\n            if (x & 0x200000 > 0) {\n                result = (result * 0x10000000000162E43) >> 64;\n            }\n            if (x & 0x100000 > 0) {\n                result = (result * 0x100000000000B1721) >> 64;\n            }\n            if (x & 0x80000 > 0) {\n                result = (result * 0x10000000000058B91) >> 64;\n            }\n            if (x & 0x40000 > 0) {\n                result = (result * 0x1000000000002C5C8) >> 64;\n            }\n            if (x & 0x20000 > 0) {\n                result = (result * 0x100000000000162E4) >> 64;\n            }\n            if (x & 0x10000 > 0) {\n                result = (result * 0x1000000000000B172) >> 64;\n            }\n            if (x & 0x8000 > 0) {\n                result = (result * 0x100000000000058B9) >> 64;\n            }\n            if (x & 0x4000 > 0) {\n                result = (result * 0x10000000000002C5D) >> 64;\n            }\n            if (x & 0x2000 > 0) {\n                result = (result * 0x1000000000000162E) >> 64;\n            }\n            if (x & 0x1000 > 0) {\n                result = (result * 0x10000000000000B17) >> 64;\n            }\n            if (x & 0x800 > 0) {\n                result = (result * 0x1000000000000058C) >> 64;\n            }\n            if (x & 0x400 > 0) {\n                result = (result * 0x100000000000002C6) >> 64;\n            }\n            if (x & 0x200 > 0) {\n                result = (result * 0x10000000000000163) >> 64;\n            }\n            if (x & 0x100 > 0) {\n                result = (result * 0x100000000000000B1) >> 64;\n            }\n            if (x & 0x80 > 0) {\n                result = (result * 0x10000000000000059) >> 64;\n            }\n            if (x & 0x40 > 0) {\n                result = (result * 0x1000000000000002C) >> 64;\n            }\n            if (x & 0x20 > 0) {\n                result = (result * 0x10000000000000016) >> 64;\n            }\n            if (x & 0x10 > 0) {\n                result = (result * 0x1000000000000000B) >> 64;\n            }\n            if (x & 0x8 > 0) {\n                result = (result * 0x10000000000000006) >> 64;\n            }\n            if (x & 0x4 > 0) {\n                result = (result * 0x10000000000000003) >> 64;\n            }\n            if (x & 0x2 > 0) {\n                result = (result * 0x10000000000000001) >> 64;\n            }\n            if (x & 0x1 > 0) {\n                result = (result * 0x10000000000000001) >> 64;\n            }\n\n            // We're doing two things at the same time:\n            //\n            //   1. Multiply the result by 2^n + 1, where \"2^n\" is the integer part and the one is added to account for\n            //      the fact that we initially set the result to 0.5. This is accomplished by subtracting from 191\n            //      rather than 192.\n            //   2. Convert the result to the unsigned 60.18-decimal fixed-point format.\n            //\n            // This works because 2^(191-ip) = 2^ip / 2^191, where \"ip\" is the integer part \"2^n\".\n            result *= SCALE;\n            result >>= (191 - (x >> 64));\n        }\n    }\n\n    /// @notice Finds the zero-based index of the first one in the binary representation of x.\n    /// @dev See the note on msb in the \"Find First Set\" Wikipedia article https://en.wikipedia.org/wiki/Find_first_set\n    /// @param x The uint256 number for which to find the index of the most significant bit.\n    /// @return msb The index of the most significant bit as an uint256.\n    function mostSignificantBit(uint256 x) internal pure returns (uint256 msb) {\n        if (x >= 2 ** 128) {\n            x >>= 128;\n            msb += 128;\n        }\n        if (x >= 2 ** 64) {\n            x >>= 64;\n            msb += 64;\n        }\n        if (x >= 2 ** 32) {\n            x >>= 32;\n            msb += 32;\n        }\n        if (x >= 2 ** 16) {\n            x >>= 16;\n            msb += 16;\n        }\n        if (x >= 2 ** 8) {\n            x >>= 8;\n            msb += 8;\n        }\n        if (x >= 2 ** 4) {\n            x >>= 4;\n            msb += 4;\n        }\n        if (x >= 2 ** 2) {\n            x >>= 2;\n            msb += 2;\n        }\n        if (x >= 2 ** 1) {\n            // No need to shift x any more.\n            msb += 1;\n        }\n    }\n\n    /// @notice Calculates floor(x*y÷denominator) with full precision.\n    ///\n    /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv.\n    ///\n    /// Requirements:\n    /// - The denominator cannot be zero.\n    /// - The result must fit within uint256.\n    ///\n    /// Caveats:\n    /// - This function does not work with fixed-point numbers.\n    ///\n    /// @param x The multiplicand as an uint256.\n    /// @param y The multiplier as an uint256.\n    /// @param denominator The divisor as an uint256.\n    /// @return result The result as an uint256.\n    function mulDiv(uint256 x, uint256 y, uint256 denominator)\n        internal\n        pure\n        returns (uint256 result)\n    {\n        // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use\n        // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256\n        // variables such that product = prod1 * 2^256 + prod0.\n        uint256 prod0; // Least significant 256 bits of the product\n        uint256 prod1; // Most significant 256 bits of the product\n        assembly {\n            let mm := mulmod(x, y, not(0))\n            prod0 := mul(x, y)\n            prod1 := sub(sub(mm, prod0), lt(mm, prod0))\n        }\n\n        // Handle non-overflow cases, 256 by 256 division.\n        if (prod1 == 0) {\n            unchecked {\n                result = prod0 / denominator;\n            }\n            return result;\n        }\n\n        // Make sure the result is less than 2^256. Also prevents denominator == 0.\n        if (prod1 >= denominator) {\n            revert PRBMath__MulDivOverflow(prod1, denominator);\n        }\n\n        ///////////////////////////////////////////////\n        // 512 by 256 division.\n        ///////////////////////////////////////////////\n\n        // Make division exact by subtracting the remainder from [prod1 prod0].\n        uint256 remainder;\n        assembly {\n            // Compute remainder using mulmod.\n            remainder := mulmod(x, y, denominator)\n\n            // Subtract 256 bit number from 512 bit number.\n            prod1 := sub(prod1, gt(remainder, prod0))\n            prod0 := sub(prod0, remainder)\n        }\n\n        // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.\n        // See https://cs.stackexchange.com/q/138556/92363.\n        unchecked {\n            // Does not overflow because the denominator cannot be zero at this stage in the function.\n            uint256 lpotdod = denominator & (~denominator + 1);\n            assembly {\n                // Divide denominator by lpotdod.\n                denominator := div(denominator, lpotdod)\n\n                // Divide [prod1 prod0] by lpotdod.\n                prod0 := div(prod0, lpotdod)\n\n                // Flip lpotdod such that it is 2^256 / lpotdod. If lpotdod is zero, then it becomes one.\n                lpotdod := add(div(sub(0, lpotdod), lpotdod), 1)\n            }\n\n            // Shift in bits from prod1 into prod0.\n            prod0 |= prod1 * lpotdod;\n\n            // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such\n            // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for\n            // four bits. That is, denominator * inv = 1 mod 2^4.\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 works\n            // in modular arithmetic, doubling the correct bits in each step.\n            inverse *= 2 - denominator * inverse; // inverse mod 2^8\n            inverse *= 2 - denominator * inverse; // inverse mod 2^16\n            inverse *= 2 - denominator * inverse; // inverse mod 2^32\n            inverse *= 2 - denominator * inverse; // inverse mod 2^64\n            inverse *= 2 - denominator * inverse; // inverse mod 2^128\n            inverse *= 2 - denominator * inverse; // inverse mod 2^256\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^256. Since the preconditions guarantee that the outcome is\n            // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1\n            // is no longer required.\n            result = prod0 * inverse;\n            return result;\n        }\n    }\n\n    /// @notice Calculates floor(x*y÷1e18) with full precision.\n    ///\n    /// @dev Variant of \"mulDiv\" with constant folding, i.e. in which the denominator is always 1e18. Before returning the\n    /// final result, we add 1 if (x * y) % SCALE >= HALF_SCALE. Without this, 6.6e-19 would be truncated to 0 instead of\n    /// being rounded to 1e-18.  See \"Listing 6\" and text above it at https://accu.org/index.php/journals/1717.\n    ///\n    /// Requirements:\n    /// - The result must fit within uint256.\n    ///\n    /// Caveats:\n    /// - The body is purposely left uncommented; see the NatSpec comments in \"PRBMath.mulDiv\" to understand how this works.\n    /// - It is assumed that the result can never be type(uint256).max when x and y solve the following two equations:\n    ///     1. x * y = type(uint256).max * SCALE\n    ///     2. (x * y) % SCALE >= SCALE / 2\n    ///\n    /// @param x The multiplicand as an unsigned 60.18-decimal fixed-point number.\n    /// @param y The multiplier as an unsigned 60.18-decimal fixed-point number.\n    /// @return result The result as an unsigned 60.18-decimal fixed-point number.\n    function mulDivFixedPoint(uint256 x, uint256 y) internal pure returns (uint256 result) {\n        uint256 prod0;\n        uint256 prod1;\n        assembly {\n            let mm := mulmod(x, y, not(0))\n            prod0 := mul(x, y)\n            prod1 := sub(sub(mm, prod0), lt(mm, prod0))\n        }\n\n        if (prod1 >= SCALE) {\n            revert PRBMath__MulDivFixedPointOverflow(prod1);\n        }\n\n        uint256 remainder;\n        uint256 roundUpUnit;\n        assembly {\n            remainder := mulmod(x, y, SCALE)\n            roundUpUnit := gt(remainder, 499999999999999999)\n        }\n\n        if (prod1 == 0) {\n            unchecked {\n                result = (prod0 / SCALE) + roundUpUnit;\n                return result;\n            }\n        }\n\n        assembly {\n            result :=\n                add(\n                    mul(\n                        or(\n                            div(sub(prod0, remainder), SCALE_LPOTD),\n                            mul(\n                                sub(prod1, gt(remainder, prod0)),\n                                add(div(sub(0, SCALE_LPOTD), SCALE_LPOTD), 1)\n                            )\n                        ),\n                        SCALE_INVERSE\n                    ),\n                    roundUpUnit\n                )\n        }\n    }\n\n    /// @notice Calculates floor(x*y÷denominator) with full precision.\n    ///\n    /// @dev An extension of \"mulDiv\" for signed numbers. Works by computing the signs and the absolute values separately.\n    ///\n    /// Requirements:\n    /// - None of the inputs can be type(int256).min.\n    /// - The result must fit within int256.\n    ///\n    /// @param x The multiplicand as an int256.\n    /// @param y The multiplier as an int256.\n    /// @param denominator The divisor as an int256.\n    /// @return result The result as an int256.\n    function mulDivSigned(int256 x, int256 y, int256 denominator)\n        internal\n        pure\n        returns (int256 result)\n    {\n        if (x == type(int256).min || y == type(int256).min || denominator == type(int256).min) {\n            revert PRBMath__MulDivSignedInputTooSmall();\n        }\n\n        // Get hold of the absolute values of x, y and the denominator.\n        uint256 ax;\n        uint256 ay;\n        uint256 ad;\n        unchecked {\n            ax = x < 0 ? uint256(-x) : uint256(x);\n            ay = y < 0 ? uint256(-y) : uint256(y);\n            ad = denominator < 0 ? uint256(-denominator) : uint256(denominator);\n        }\n\n        // Compute the absolute value of (x*y)÷denominator. The result must fit within int256.\n        uint256 rAbs = mulDiv(ax, ay, ad);\n        if (rAbs > uint256(type(int256).max)) {\n            revert PRBMath__MulDivSignedOverflow(rAbs);\n        }\n\n        // Get the signs of x, y and the denominator.\n        uint256 sx;\n        uint256 sy;\n        uint256 sd;\n        assembly {\n            sx := sgt(x, sub(0, 1))\n            sy := sgt(y, sub(0, 1))\n            sd := sgt(denominator, sub(0, 1))\n        }\n\n        // XOR over sx, sy and sd. This is checking whether there are one or three negative signs in the inputs.\n        // If yes, the result should be negative.\n        result = sx ^ sy ^ sd == 0 ? -int256(rAbs) : int256(rAbs);\n    }\n\n    /// @notice Calculates the square root of x, rounding down.\n    /// @dev Uses the Babylonian method https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method.\n    ///\n    /// Caveats:\n    /// - This function does not work with fixed-point numbers.\n    ///\n    /// @param x The uint256 number for which to calculate the square root.\n    /// @return result The result as an uint256.\n    function sqrt(uint256 x) internal pure returns (uint256 result) {\n        if (x == 0) {\n            return 0;\n        }\n\n        // Set the initial guess to the least power of two that is greater than or equal to sqrt(x).\n        uint256 xAux = uint256(x);\n        result = 1;\n        if (xAux >= 0x100000000000000000000000000000000) {\n            xAux >>= 128;\n            result <<= 64;\n        }\n        if (xAux >= 0x10000000000000000) {\n            xAux >>= 64;\n            result <<= 32;\n        }\n        if (xAux >= 0x100000000) {\n            xAux >>= 32;\n            result <<= 16;\n        }\n        if (xAux >= 0x10000) {\n            xAux >>= 16;\n            result <<= 8;\n        }\n        if (xAux >= 0x100) {\n            xAux >>= 8;\n            result <<= 4;\n        }\n        if (xAux >= 0x10) {\n            xAux >>= 4;\n            result <<= 2;\n        }\n        if (xAux >= 0x8) {\n            result <<= 1;\n        }\n\n        // The operations can never overflow because the result is max 2^127 when it enters this block.\n        unchecked {\n            result = (result + x / result) >> 1;\n            result = (result + x / result) >> 1;\n            result = (result + x / result) >> 1;\n            result = (result + x / result) >> 1;\n            result = (result + x / result) >> 1;\n            result = (result + x / result) >> 1;\n            result = (result + x / result) >> 1; // Seven iterations should be enough\n            uint256 roundedDownResult = x / result;\n            return result >= roundedDownResult ? roundedDownResult : result;\n        }\n    }\n}\n"
      },
      "lib/balancer-v2-monorepo/pkg/interfaces/contracts/vault/IPoolSwapStructs.sol": {
        "content": "// SPDX-License-Identifier: GPL-3.0-or-later\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n// GNU General Public License for more details.\n\n// You should have received a copy of the GNU General Public License\n// along with this program.  If not, see <http://www.gnu.org/licenses/>.\n\npragma solidity >=0.7.0 <0.9.0;\npragma experimental ABIEncoderV2;\n\nimport \"../solidity-utils/openzeppelin/IERC20.sol\";\n\nimport \"./IVault.sol\";\n\ninterface IPoolSwapStructs {\n    // This is not really an interface - it just defines common structs used by other interfaces: IGeneralPool and\n    // IMinimalSwapInfoPool.\n    //\n    // This data structure represents a request for a token swap, where `kind` indicates the swap type ('given in' or\n    // 'given out') which indicates whether or not the amount sent by the pool is known.\n    //\n    // The pool receives `tokenIn` and sends `tokenOut`. `amount` is the number of `tokenIn` tokens the pool will take\n    // in, or the number of `tokenOut` tokens the Pool will send out, depending on the given swap `kind`.\n    //\n    // All other fields are not strictly necessary for most swaps, but are provided to support advanced scenarios in\n    // some Pools.\n    //\n    // `poolId` is the ID of the Pool involved in the swap - this is useful for Pool contracts that implement more than\n    // one Pool.\n    //\n    // The meaning of `lastChangeBlock` depends on the Pool specialization:\n    //  - Two Token or Minimal Swap Info: the last block in which either `tokenIn` or `tokenOut` changed its total\n    //    balance.\n    //  - General: the last block in which *any* of the Pool's registered tokens changed its total balance.\n    //\n    // `from` is the origin address for the funds the Pool receives, and `to` is the destination address\n    // where the Pool sends the outgoing tokens.\n    //\n    // `userData` is extra data provided by the caller - typically a signature from a trusted party.\n    struct SwapRequest {\n        IVault.SwapKind kind;\n        IERC20 tokenIn;\n        IERC20 tokenOut;\n        uint256 amount;\n        // Misc data\n        bytes32 poolId;\n        uint256 lastChangeBlock;\n        address from;\n        address to;\n        bytes userData;\n    }\n}\n"
      }
    },
    "settings": {
      "remappings": [
        "@balancer-labs/=lib/balancer-v2-monorepo/",
        "aura-contracts/=lib/aura-contracts/",
        "balancer-v2-monorepo/=lib/balancer-v2-monorepo/",
        "ds-test/=lib/forge-std/lib/ds-test/src/",
        "erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
        "forge-std/=lib/forge-std/src/",
        "@openzeppelin-contracts/=lib/openzeppelin-contracts/",
        "@openzeppelin/=lib/openzeppelin-contracts/",
        "@openzeppelin-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
        "@openzeppelin-upgradeable-contracts/=lib/openzeppelin-contracts-upgradeable/contracts/",
        "@ensdomains/=lib/balancer-v2-monorepo/node_modules/@ensdomains/",
        "@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
        "@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
        "@solidity-parser/=lib/balancer-v2-monorepo/node_modules/",
        "hardhat/=lib/balancer-v2-monorepo/node_modules/hardhat/",
        "openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
        "openzeppelin-contracts/=lib/openzeppelin-contracts/",
        "prettier-plugin-solidity/=lib/balancer-v2-monorepo/node_modules/prettier-plugin-solidity/"
      ],
      "optimizer": {
        "enabled": true,
        "runs": 1
      },
      "metadata": {
        "useLiteralContent": false,
        "bytecodeHash": "ipfs",
        "appendCBOR": true
      },
      "outputSelection": {
        "*": {
          "*": [
            "evm.bytecode",
            "evm.deployedBytecode",
            "devdoc",
            "userdoc",
            "metadata",
            "abi"
          ]
        }
      },
      "evmVersion": "paris",
      "viaIR": true,
      "libraries": {}
    }
  }}